2 # -*- coding: utf-8 -*-
5 Machinery for generating tracing-related intermediate files.
10 __license__ = "GPL version 2 or (at your option) any later version"
12 __maintainer__ = "Stefan Hajnoczi"
19 import tracetool.format
20 import tracetool.backend
23 def error_write(*lines):
24 """Write a set of error lines."""
25 sys.stderr.writelines("\n".join(lines) + "\n")
28 """Write a set of error lines and exit."""
33 def out(*lines, **kwargs):
34 """Write a set of output lines.
36 You can use kwargs as a shorthand for mapping variables when formating all
39 lines = [ l % kwargs for l in lines ]
40 sys.stdout.writelines("\n".join(lines) + "\n")
44 """Event arguments description."""
46 def __init__(self, args):
51 List of (type, name) tuples.
56 """Create a new copy."""
57 return Arguments(list(self._args))
61 """Build and Arguments instance from an argument string.
66 String describing the event arguments.
69 for arg in arg_str.split(","):
75 arg_type, identifier = arg.rsplit('*', 1)
77 identifier = identifier.strip()
79 arg_type, identifier = arg.rsplit(None, 1)
81 res.append((arg_type, identifier))
85 """Iterate over the (type, name) pairs."""
86 return iter(self._args)
89 """Number of arguments."""
90 return len(self._args)
93 """String suitable for declaring function arguments."""
94 if len(self._args) == 0:
97 return ", ".join([ " ".join([t, n]) for t,n in self._args ])
100 """Evaluable string representation for this object."""
101 return "Arguments(\"%s\")" % str(self)
104 """List of argument names."""
105 return [ name for _, name in self._args ]
108 """List of argument types."""
109 return [ type_ for type_, _ in self._args ]
113 """Event description.
120 The event format string.
121 properties : set(str)
122 Properties of the event.
127 _CRE = re.compile("((?P<props>.*)\s+)?(?P<name>[^(\s]+)\((?P<args>[^)]*)\)\s*(?P<fmt>\".*)?")
129 _VALID_PROPS = set(["disable"])
131 def __init__(self, name, props, fmt, args):
140 Event printing format.
145 self.properties = props
149 unknown_props = set(self.properties) - self._VALID_PROPS
150 if len(unknown_props) > 0:
151 raise ValueError("Unknown properties: %s"
152 % ", ".join(unknown_props))
155 """Create a new copy."""
156 return Event(self.name, list(self.properties), self.fmt,
157 self.args.copy(), self)
161 """Build an Event instance from a string.
166 Line describing the event.
168 m = Event._CRE.match(line_str)
170 groups = m.groupdict('')
172 name = groups["name"]
173 props = groups["props"].split()
175 args = Arguments.build(groups["args"])
177 return Event(name, props, fmt, args)
180 """Evaluable string representation for this object."""
181 return "Event('%s %s(%s) %s')" % (" ".join(self.properties),
186 QEMU_TRACE = "trace_%(name)s"
188 def api(self, fmt=None):
190 fmt = Event.QEMU_TRACE
191 return fmt % {"name": self.name}
194 def _read_events(fobj):
199 if line.lstrip().startswith('#'):
201 res.append(Event.build(line))
205 class TracetoolError (Exception):
206 """Exception for calls to generate."""
210 def try_import(mod_name, attr_name=None, attr_default=None):
211 """Try to import a module and get an attribute from it.
217 attr_name : str, optional
218 Name of an attribute in the module.
219 attr_default : optional
220 Default value if the attribute does not exist in the module.
224 A pair indicating whether the module could be imported and the module or
225 object or attribute value.
228 module = __import__(mod_name, globals(), locals(), ["__package__"])
229 if attr_name is None:
231 return True, getattr(module, str(attr_name), attr_default)
236 def generate(fevents, format, backend,
237 binary=None, probe_prefix=None):
238 """Generate the output for the given (format, backend) pair.
243 Event description file.
249 See tracetool.backend.dtrace.BINARY.
250 probe_prefix : str or None
251 See tracetool.backend.dtrace.PROBEPREFIX.
253 # fix strange python error (UnboundLocalError tracetool)
258 raise TracetoolError("format not set")
259 if not tracetool.format.exists(format):
260 raise TracetoolError("unknown format: %s" % format)
261 format = format.replace("-", "_")
263 backend = str(backend)
264 if len(backend) is 0:
265 raise TracetoolError("backend not set")
266 if not tracetool.backend.exists(backend):
267 raise TracetoolError("unknown backend: %s" % backend)
268 backend = backend.replace("-", "_")
270 if not tracetool.backend.compatible(backend, format):
271 raise TracetoolError("backend '%s' not compatible with format '%s'" %
274 import tracetool.backend.dtrace
275 tracetool.backend.dtrace.BINARY = binary
276 tracetool.backend.dtrace.PROBEPREFIX = probe_prefix
278 events = _read_events(fevents)
281 ( e.properies.add("disable") for e in events )
283 tracetool.format.generate_begin(format, events)
284 tracetool.backend.generate("nop", format,
287 if "disable" in e.properties ])
288 tracetool.backend.generate(backend, format,
291 if "disable" not in e.properties ])
292 tracetool.format.generate_end(format, events)