2 # -*- coding: utf-8 -*-
5 Machinery for generating tracing-related intermediate files.
8 __author__
= "Lluís Vilanova <vilanova@ac.upc.edu>"
9 __copyright__
= "Copyright 2012-2014, Lluís Vilanova <vilanova@ac.upc.edu>"
10 __license__
= "GPL version 2 or (at your option) any later version"
12 __maintainer__
= "Stefan Hajnoczi"
13 __email__
= "stefanha@linux.vnet.ibm.com"
20 import tracetool
.format
21 import tracetool
.backend
22 import tracetool
.transform
25 def error_write(*lines
):
26 """Write a set of error lines."""
27 sys
.stderr
.writelines("\n".join(lines
) + "\n")
30 """Write a set of error lines and exit."""
35 def out(*lines
, **kwargs
):
36 """Write a set of output lines.
38 You can use kwargs as a shorthand for mapping variables when formating all
41 lines
= [ l
% kwargs
for l
in lines
]
42 sys
.stdout
.writelines("\n".join(lines
) + "\n")
46 """Event arguments description."""
48 def __init__(self
, args
):
53 List of (type, name) tuples.
58 """Create a new copy."""
59 return Arguments(list(self
._args
))
63 """Build and Arguments instance from an argument string.
68 String describing the event arguments.
71 for arg
in arg_str
.split(","):
77 arg_type
, identifier
= arg
.rsplit('*', 1)
79 identifier
= identifier
.strip()
81 arg_type
, identifier
= arg
.rsplit(None, 1)
83 res
.append((arg_type
, identifier
))
87 """Iterate over the (type, name) pairs."""
88 return iter(self
._args
)
91 """Number of arguments."""
92 return len(self
._args
)
95 """String suitable for declaring function arguments."""
96 if len(self
._args
) == 0:
99 return ", ".join([ " ".join([t
, n
]) for t
,n
in self
._args
])
102 """Evaluable string representation for this object."""
103 return "Arguments(\"%s\")" % str(self
)
106 """List of argument names."""
107 return [ name
for _
, name
in self
._args
]
110 """List of argument types."""
111 return [ type_
for type_
, _
in self
._args
]
113 def transform(self
, *trans
):
114 """Return a new Arguments instance with transformed types.
116 The types in the resulting Arguments instance are transformed according
117 to tracetool.transform.transform_type.
120 for type_
, name
in self
._args
:
121 res
.append((tracetool
.transform
.transform_type(type_
, *trans
),
123 return Arguments(res
)
127 """Event description.
134 The event format string.
135 properties : set(str)
136 Properties of the event.
142 _CRE
= re
.compile("((?P<props>[\w\s]+)\s+)?"
144 "\((?P<args>[^)]*)\)"
146 "(?:(?:(?P<fmt_trans>\".+),)?\s*(?P<fmt>\".+))?"
149 _VALID_PROPS
= set(["disable", "tcg", "tcg-trans", "tcg-exec"])
151 def __init__(self
, name
, props
, fmt
, args
, orig
=None):
159 fmt : str, list of str
160 Event printing format (or formats).
164 Original Event before transformation.
168 self
.properties
= props
173 self
.original
= weakref
.ref(self
)
177 unknown_props
= set(self
.properties
) - self
._VALID
_PROPS
178 if len(unknown_props
) > 0:
179 raise ValueError("Unknown properties: %s"
180 % ", ".join(unknown_props
))
181 assert isinstance(self
.fmt
, str) or len(self
.fmt
) == 2
184 """Create a new copy."""
185 return Event(self
.name
, list(self
.properties
), self
.fmt
,
186 self
.args
.copy(), self
)
190 """Build an Event instance from a string.
195 Line describing the event.
197 m
= Event
._CRE
.match(line_str
)
199 groups
= m
.groupdict('')
201 name
= groups
["name"]
202 props
= groups
["props"].split()
204 fmt_trans
= groups
["fmt_trans"]
205 if len(fmt_trans
) > 0:
206 fmt
= [fmt_trans
, fmt
]
207 args
= Arguments
.build(groups
["args"])
209 if "tcg-trans" in props
:
210 raise ValueError("Invalid property 'tcg-trans'")
211 if "tcg-exec" in props
:
212 raise ValueError("Invalid property 'tcg-exec'")
213 if "tcg" not in props
and not isinstance(fmt
, str):
214 raise ValueError("Only events with 'tcg' property can have two formats")
215 if "tcg" in props
and isinstance(fmt
, str):
216 raise ValueError("Events with 'tcg' property must have two formats")
218 return Event(name
, props
, fmt
, args
)
221 """Evaluable string representation for this object."""
222 if isinstance(self
.fmt
, str):
225 fmt
= "%s, %s" % (self
.fmt
[0], self
.fmt
[1])
226 return "Event('%s %s(%s) %s')" % (" ".join(self
.properties
),
231 _FMT
= re
.compile("(%[\d\.]*\w+|%.*PRI\S+)")
234 """List of argument print formats."""
235 assert not isinstance(self
.fmt
, list)
236 return self
._FMT
.findall(self
.fmt
)
238 QEMU_TRACE
= "trace_%(name)s"
239 QEMU_TRACE_TCG
= QEMU_TRACE
+ "_tcg"
241 def api(self
, fmt
=None):
243 fmt
= Event
.QEMU_TRACE
244 return fmt
% {"name": self
.name
}
246 def transform(self
, *trans
):
247 """Return a new Event with transformed Arguments."""
248 return Event(self
.name
,
249 list(self
.properties
),
251 self
.args
.transform(*trans
),
255 def _read_events(fobj
):
260 if line
.lstrip().startswith('#'):
263 event
= Event
.build(line
)
265 # transform TCG-enabled events
266 if "tcg" not in event
.properties
:
269 event_trans
= event
.copy()
270 event_trans
.name
+= "_trans"
271 event_trans
.properties
+= ["tcg-trans"]
272 event_trans
.fmt
= event
.fmt
[0]
274 for atrans
, aorig
in zip(
275 event_trans
.transform(tracetool
.transform
.TCG_2_HOST
).args
,
278 args_trans
.append(atrans
)
279 event_trans
.args
= Arguments(args_trans
)
280 event_trans
= event_trans
.copy()
282 event_exec
= event
.copy()
283 event_exec
.name
+= "_exec"
284 event_exec
.properties
+= ["tcg-exec"]
285 event_exec
.fmt
= event
.fmt
[1]
286 event_exec
= event_exec
.transform(tracetool
.transform
.TCG_2_HOST
)
288 new_event
= [event_trans
, event_exec
]
289 event
.event_trans
, event
.event_exec
= new_event
291 events
.extend(new_event
)
296 class TracetoolError (Exception):
297 """Exception for calls to generate."""
301 def try_import(mod_name
, attr_name
=None, attr_default
=None):
302 """Try to import a module and get an attribute from it.
308 attr_name : str, optional
309 Name of an attribute in the module.
310 attr_default : optional
311 Default value if the attribute does not exist in the module.
315 A pair indicating whether the module could be imported and the module or
316 object or attribute value.
319 module
= __import__(mod_name
, globals(), locals(), ["__package__"])
320 if attr_name
is None:
322 return True, getattr(module
, str(attr_name
), attr_default
)
327 def generate(fevents
, format
, backends
,
328 binary
=None, probe_prefix
=None):
329 """Generate the output for the given (format, backends) pair.
334 Event description file.
338 Output backend names.
340 See tracetool.backend.dtrace.BINARY.
341 probe_prefix : str or None
342 See tracetool.backend.dtrace.PROBEPREFIX.
344 # fix strange python error (UnboundLocalError tracetool)
349 raise TracetoolError("format not set")
350 if not tracetool
.format
.exists(format
):
351 raise TracetoolError("unknown format: %s" % format
)
353 if len(backends
) is 0:
354 raise TracetoolError("no backends specified")
355 for backend
in backends
:
356 if not tracetool
.backend
.exists(backend
):
357 raise TracetoolError("unknown backend: %s" % backend
)
358 backend
= tracetool
.backend
.Wrapper(backends
, format
)
360 import tracetool
.backend
.dtrace
361 tracetool
.backend
.dtrace
.BINARY
= binary
362 tracetool
.backend
.dtrace
.PROBEPREFIX
= probe_prefix
364 events
= _read_events(fevents
)
366 tracetool
.format
.generate(events
, format
, backend
)