]> git.proxmox.com Git - qemu.git/blob - scripts/tracetool/__init__.py
tracetool: Add support for the 'dtrace' backend
[qemu.git] / scripts / tracetool / __init__.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 """
5 Machinery for generating tracing-related intermediate files.
6 """
7
8 __author__ = "Lluís Vilanova <vilanova@ac.upc.edu>"
9 __copyright__ = "Copyright 2012, Lluís Vilanova <vilanova@ac.upc.edu>"
10 __license__ = "GPL version 2 or (at your option) any later version"
11
12 __maintainer__ = "Stefan Hajnoczi"
13 __email__ = "stefanha@linux.vnet.ibm.com"
14
15
16 import re
17 import sys
18
19 import tracetool.format
20 import tracetool.backend
21
22
23 def error_write(*lines):
24 """Write a set of error lines."""
25 sys.stderr.writelines("\n".join(lines) + "\n")
26
27 def error(*lines):
28 """Write a set of error lines and exit."""
29 error_write(*lines)
30 sys.exit(1)
31
32
33 def out(*lines, **kwargs):
34 """Write a set of output lines.
35
36 You can use kwargs as a shorthand for mapping variables when formating all
37 the strings in lines.
38 """
39 lines = [ l % kwargs for l in lines ]
40 sys.stdout.writelines("\n".join(lines) + "\n")
41
42
43 class Arguments:
44 """Event arguments description."""
45
46 def __init__(self, args):
47 """
48 Parameters
49 ----------
50 args :
51 List of (type, name) tuples.
52 """
53 self._args = args
54
55 @staticmethod
56 def build(arg_str):
57 """Build and Arguments instance from an argument string.
58
59 Parameters
60 ----------
61 arg_str : str
62 String describing the event arguments.
63 """
64 res = []
65 for arg in arg_str.split(","):
66 arg = arg.strip()
67 parts = arg.split()
68 head, sep, tail = parts[-1].rpartition("*")
69 parts = parts[:-1]
70 if tail == "void":
71 assert len(parts) == 0 and sep == ""
72 continue
73 arg_type = " ".join(parts + [ " ".join([head, sep]).strip() ]).strip()
74 res.append((arg_type, tail))
75 return Arguments(res)
76
77 def __iter__(self):
78 """Iterate over the (type, name) pairs."""
79 return iter(self._args)
80
81 def __len__(self):
82 """Number of arguments."""
83 return len(self._args)
84
85 def __str__(self):
86 """String suitable for declaring function arguments."""
87 if len(self._args) == 0:
88 return "void"
89 else:
90 return ", ".join([ " ".join([t, n]) for t,n in self._args ])
91
92 def __repr__(self):
93 """Evaluable string representation for this object."""
94 return "Arguments(\"%s\")" % str(self)
95
96 def names(self):
97 """List of argument names."""
98 return [ name for _, name in self._args ]
99
100 def types(self):
101 """List of argument types."""
102 return [ type_ for type_, _ in self._args ]
103
104
105 class Event(object):
106 """Event description.
107
108 Attributes
109 ----------
110 name : str
111 The event name.
112 fmt : str
113 The event format string.
114 properties : set(str)
115 Properties of the event.
116 args : Arguments
117 The event arguments.
118 """
119
120 _CRE = re.compile("((?P<props>.*)\s+)?(?P<name>[^(\s]+)\((?P<args>[^)]*)\)\s*(?P<fmt>\".*)?")
121
122 _VALID_PROPS = set(["disable"])
123
124 def __init__(self, name, props, fmt, args):
125 """
126 Parameters
127 ----------
128 name : string
129 Event name.
130 props : list of str
131 Property names.
132 fmt : str
133 Event printing format.
134 args : Arguments
135 Event arguments.
136 """
137 self.name = name
138 self.properties = props
139 self.fmt = fmt
140 self.args = args
141
142 unknown_props = set(self.properties) - self._VALID_PROPS
143 if len(unknown_props) > 0:
144 raise ValueError("Unknown properties: %s" % ", ".join(unknown_props))
145
146 @staticmethod
147 def build(line_str):
148 """Build an Event instance from a string.
149
150 Parameters
151 ----------
152 line_str : str
153 Line describing the event.
154 """
155 m = Event._CRE.match(line_str)
156 assert m is not None
157 groups = m.groupdict('')
158
159 name = groups["name"]
160 props = groups["props"].split()
161 fmt = groups["fmt"]
162 args = Arguments.build(groups["args"])
163
164 return Event(name, props, fmt, args)
165
166 def __repr__(self):
167 """Evaluable string representation for this object."""
168 return "Event('%s %s(%s) %s')" % (" ".join(self.properties),
169 self.name,
170 self.args,
171 self.fmt)
172
173 def _read_events(fobj):
174 res = []
175 for line in fobj:
176 if not line.strip():
177 continue
178 if line.lstrip().startswith('#'):
179 continue
180 res.append(Event.build(line))
181 return res
182
183
184 class TracetoolError (Exception):
185 """Exception for calls to generate."""
186 pass
187
188
189 def try_import(mod_name, attr_name = None, attr_default = None):
190 """Try to import a module and get an attribute from it.
191
192 Parameters
193 ----------
194 mod_name : str
195 Module name.
196 attr_name : str, optional
197 Name of an attribute in the module.
198 attr_default : optional
199 Default value if the attribute does not exist in the module.
200
201 Returns
202 -------
203 A pair indicating whether the module could be imported and the module or
204 object or attribute value.
205 """
206 try:
207 module = __import__(mod_name, fromlist=["__package__"])
208 if attr_name is None:
209 return True, module
210 return True, getattr(module, str(attr_name), attr_default)
211 except ImportError:
212 return False, None
213
214
215 def generate(fevents, format, backend,
216 binary = None, probe_prefix = None):
217 """Generate the output for the given (format, backend) pair.
218
219 Parameters
220 ----------
221 fevents : file
222 Event description file.
223 format : str
224 Output format name.
225 backend : str
226 Output backend name.
227 binary : str or None
228 See tracetool.backend.dtrace.BINARY.
229 probe_prefix : str or None
230 See tracetool.backend.dtrace.PROBEPREFIX.
231 """
232 # fix strange python error (UnboundLocalError tracetool)
233 import tracetool
234
235 format = str(format)
236 if len(format) is 0:
237 raise TracetoolError("format not set")
238 mformat = format.replace("-", "_")
239 if not tracetool.format.exists(mformat):
240 raise TracetoolError("unknown format: %s" % format)
241
242 backend = str(backend)
243 if len(backend) is 0:
244 raise TracetoolError("backend not set")
245 mbackend = backend.replace("-", "_")
246 if not tracetool.backend.exists(mbackend):
247 raise TracetoolError("unknown backend: %s" % backend)
248
249 if not tracetool.backend.compatible(mbackend, mformat):
250 raise TracetoolError("backend '%s' not compatible with format '%s'" %
251 (backend, format))
252
253 import tracetool.backend.dtrace
254 tracetool.backend.dtrace.BINARY = binary
255 tracetool.backend.dtrace.PROBEPREFIX = probe_prefix
256
257 events = _read_events(fevents)
258
259 if backend == "nop":
260 ( e.properies.add("disable") for e in events )
261
262 tracetool.format.generate_begin(mformat, events)
263 tracetool.backend.generate("nop", format,
264 [ e
265 for e in events
266 if "disable" in e.properties ])
267 tracetool.backend.generate(backend, format,
268 [ e
269 for e in events
270 if "disable" not in e.properties ])
271 tracetool.format.generate_end(mformat, events)