]> Git Repo - qemu.git/blame - scripts/tracetool/__init__.py
tracetool: clarify that "formats" means "format strings"
[qemu.git] / scripts / tracetool / __init__.py
CommitLineData
650ab98d
LV
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4"""
5Machinery for generating tracing-related intermediate files.
6"""
7
8__author__ = "Lluís Vilanova <[email protected]>"
864a2178 9__copyright__ = "Copyright 2012-2017, Lluís Vilanova <[email protected]>"
650ab98d
LV
10__license__ = "GPL version 2 or (at your option) any later version"
11
12__maintainer__ = "Stefan Hajnoczi"
13__email__ = "[email protected]"
14
15
16import re
17import sys
b55835ac 18import weakref
650ab98d
LV
19
20import tracetool.format
21import tracetool.backend
b2b36c22 22import tracetool.transform
650ab98d
LV
23
24
25def error_write(*lines):
26 """Write a set of error lines."""
27 sys.stderr.writelines("\n".join(lines) + "\n")
28
29def error(*lines):
30 """Write a set of error lines and exit."""
31 error_write(*lines)
32 sys.exit(1)
33
34
35def out(*lines, **kwargs):
36 """Write a set of output lines.
37
38 You can use kwargs as a shorthand for mapping variables when formating all
39 the strings in lines.
40 """
41 lines = [ l % kwargs for l in lines ]
42 sys.stdout.writelines("\n".join(lines) + "\n")
43
44
45class Arguments:
46 """Event arguments description."""
47
48 def __init__(self, args):
49 """
50 Parameters
51 ----------
52 args :
3596f524 53 List of (type, name) tuples or Arguments objects.
650ab98d 54 """
3596f524
LV
55 self._args = []
56 for arg in args:
57 if isinstance(arg, Arguments):
58 self._args.extend(arg._args)
59 else:
60 self._args.append(arg)
650ab98d 61
ad7443e4
LV
62 def copy(self):
63 """Create a new copy."""
64 return Arguments(list(self._args))
65
650ab98d
LV
66 @staticmethod
67 def build(arg_str):
68 """Build and Arguments instance from an argument string.
69
70 Parameters
71 ----------
72 arg_str : str
73 String describing the event arguments.
74 """
75 res = []
76 for arg in arg_str.split(","):
77 arg = arg.strip()
b3ef0ade 78 if arg == 'void':
650ab98d 79 continue
b3ef0ade
SH
80
81 if '*' in arg:
82 arg_type, identifier = arg.rsplit('*', 1)
83 arg_type += '*'
84 identifier = identifier.strip()
85 else:
86 arg_type, identifier = arg.rsplit(None, 1)
87
88 res.append((arg_type, identifier))
650ab98d
LV
89 return Arguments(res)
90
3596f524
LV
91 def __getitem__(self, index):
92 if isinstance(index, slice):
93 return Arguments(self._args[index])
94 else:
95 return self._args[index]
96
650ab98d
LV
97 def __iter__(self):
98 """Iterate over the (type, name) pairs."""
99 return iter(self._args)
100
101 def __len__(self):
102 """Number of arguments."""
103 return len(self._args)
104
105 def __str__(self):
106 """String suitable for declaring function arguments."""
107 if len(self._args) == 0:
108 return "void"
109 else:
110 return ", ".join([ " ".join([t, n]) for t,n in self._args ])
111
112 def __repr__(self):
113 """Evaluable string representation for this object."""
114 return "Arguments(\"%s\")" % str(self)
115
116 def names(self):
117 """List of argument names."""
118 return [ name for _, name in self._args ]
119
120 def types(self):
121 """List of argument types."""
122 return [ type_ for type_, _ in self._args ]
123
bc9beb47
LV
124 def casted(self):
125 """List of argument names casted to their type."""
126 return ["(%s)%s" % (type_, name) for type_, name in self._args]
127
b55835ac
LV
128 def transform(self, *trans):
129 """Return a new Arguments instance with transformed types.
130
131 The types in the resulting Arguments instance are transformed according
132 to tracetool.transform.transform_type.
133 """
134 res = []
135 for type_, name in self._args:
136 res.append((tracetool.transform.transform_type(type_, *trans),
137 name))
138 return Arguments(res)
139
650ab98d
LV
140
141class Event(object):
142 """Event description.
143
144 Attributes
145 ----------
146 name : str
147 The event name.
148 fmt : str
149 The event format string.
150 properties : set(str)
151 Properties of the event.
152 args : Arguments
153 The event arguments.
23214429 154
650ab98d
LV
155 """
156
f9bbba95
SH
157 _CRE = re.compile("((?P<props>[\w\s]+)\s+)?"
158 "(?P<name>\w+)"
b2b36c22
LV
159 "\((?P<args>[^)]*)\)"
160 "\s*"
161 "(?:(?:(?P<fmt_trans>\".+),)?\s*(?P<fmt>\".+))?"
162 "\s*")
650ab98d 163
3d211d9f 164 _VALID_PROPS = set(["disable", "tcg", "tcg-trans", "tcg-exec", "vcpu"])
650ab98d 165
4ade0541
LV
166 def __init__(self, name, props, fmt, args, orig=None,
167 event_trans=None, event_exec=None):
650ab98d
LV
168 """
169 Parameters
170 ----------
171 name : string
172 Event name.
173 props : list of str
174 Property names.
b2b36c22 175 fmt : str, list of str
6e497fa1 176 Event printing format string(s).
650ab98d
LV
177 args : Arguments
178 Event arguments.
b55835ac 179 orig : Event or None
4ade0541
LV
180 Original Event before transformation/generation.
181 event_trans : Event or None
182 Generated translation-time event ("tcg" property).
183 event_exec : Event or None
184 Generated execution-time event ("tcg" property).
41ef7b00 185
650ab98d
LV
186 """
187 self.name = name
188 self.properties = props
189 self.fmt = fmt
190 self.args = args
4ade0541
LV
191 self.event_trans = event_trans
192 self.event_exec = event_exec
650ab98d 193
f3fddaf6
DB
194 if len(args) > 10:
195 raise ValueError("Event '%s' has more than maximum permitted "
196 "argument count" % name)
197
b55835ac
LV
198 if orig is None:
199 self.original = weakref.ref(self)
200 else:
201 self.original = orig
202
650ab98d
LV
203 unknown_props = set(self.properties) - self._VALID_PROPS
204 if len(unknown_props) > 0:
9c24a52e
LV
205 raise ValueError("Unknown properties: %s"
206 % ", ".join(unknown_props))
b2b36c22 207 assert isinstance(self.fmt, str) or len(self.fmt) == 2
650ab98d 208
ad7443e4
LV
209 def copy(self):
210 """Create a new copy."""
211 return Event(self.name, list(self.properties), self.fmt,
4ade0541 212 self.args.copy(), self, self.event_trans, self.event_exec)
ad7443e4 213
650ab98d
LV
214 @staticmethod
215 def build(line_str):
216 """Build an Event instance from a string.
217
218 Parameters
219 ----------
220 line_str : str
221 Line describing the event.
222 """
223 m = Event._CRE.match(line_str)
224 assert m is not None
225 groups = m.groupdict('')
226
227 name = groups["name"]
228 props = groups["props"].split()
229 fmt = groups["fmt"]
b2b36c22
LV
230 fmt_trans = groups["fmt_trans"]
231 if len(fmt_trans) > 0:
232 fmt = [fmt_trans, fmt]
650ab98d
LV
233 args = Arguments.build(groups["args"])
234
b2b36c22
LV
235 if "tcg-trans" in props:
236 raise ValueError("Invalid property 'tcg-trans'")
237 if "tcg-exec" in props:
238 raise ValueError("Invalid property 'tcg-exec'")
239 if "tcg" not in props and not isinstance(fmt, str):
6e497fa1 240 raise ValueError("Only events with 'tcg' property can have two format strings")
b2b36c22 241 if "tcg" in props and isinstance(fmt, str):
6e497fa1 242 raise ValueError("Events with 'tcg' property must have two format strings")
b2b36c22 243
3d211d9f
LV
244 event = Event(name, props, fmt, args)
245
246 # add implicit arguments when using the 'vcpu' property
247 import tracetool.vcpu
248 event = tracetool.vcpu.transform_event(event)
249
250 return event
650ab98d
LV
251
252 def __repr__(self):
253 """Evaluable string representation for this object."""
b2b36c22
LV
254 if isinstance(self.fmt, str):
255 fmt = self.fmt
256 else:
257 fmt = "%s, %s" % (self.fmt[0], self.fmt[1])
650ab98d
LV
258 return "Event('%s %s(%s) %s')" % (" ".join(self.properties),
259 self.name,
260 self.args,
b2b36c22 261 fmt)
650ab98d 262
931f53e1 263 _FMT = re.compile("(%[\d\.]*\w+|%.*PRI\S+)")
23214429
LV
264
265 def formats(self):
6e497fa1 266 """List conversion specifiers in the argument print format string."""
23214429
LV
267 assert not isinstance(self.fmt, list)
268 return self._FMT.findall(self.fmt)
269
7d08f0da 270 QEMU_TRACE = "trace_%(name)s"
864a2178 271 QEMU_TRACE_NOCHECK = "_nocheck__" + QEMU_TRACE
707c8a98 272 QEMU_TRACE_TCG = QEMU_TRACE + "_tcg"
93977402 273 QEMU_DSTATE = "_TRACE_%(NAME)s_DSTATE"
3932ef3f 274 QEMU_BACKEND_DSTATE = "TRACE_%(NAME)s_BACKEND_DSTATE"
79218be4 275 QEMU_EVENT = "_TRACE_%(NAME)s_EVENT"
7d08f0da
LV
276
277 def api(self, fmt=None):
278 if fmt is None:
279 fmt = Event.QEMU_TRACE
93977402 280 return fmt % {"name": self.name, "NAME": self.name.upper()}
7d08f0da 281
b55835ac
LV
282 def transform(self, *trans):
283 """Return a new Event with transformed Arguments."""
284 return Event(self.name,
285 list(self.properties),
286 self.fmt,
287 self.args.transform(*trans),
288 self)
289
7d08f0da 290
d1b97bce
DB
291def read_events(fobj):
292 """Generate the output for the given (format, backends) pair.
293
294 Parameters
295 ----------
296 fobj : file
297 Event description file.
298
299 Returns a list of Event objects
300 """
301
776ec96f 302 events = []
5069b561 303 for lineno, line in enumerate(fobj, 1):
650ab98d
LV
304 if not line.strip():
305 continue
306 if line.lstrip().startswith('#'):
307 continue
776ec96f 308
5069b561
SH
309 try:
310 event = Event.build(line)
311 except ValueError as e:
312 arg0 = 'Error on line %d: %s' % (lineno, e.args[0])
313 e.args = (arg0,) + e.args[1:]
314 raise
776ec96f
CS
315
316 # transform TCG-enabled events
317 if "tcg" not in event.properties:
318 events.append(event)
319 else:
320 event_trans = event.copy()
321 event_trans.name += "_trans"
322 event_trans.properties += ["tcg-trans"]
323 event_trans.fmt = event.fmt[0]
3d211d9f 324 # ignore TCG arguments
776ec96f
CS
325 args_trans = []
326 for atrans, aorig in zip(
327 event_trans.transform(tracetool.transform.TCG_2_HOST).args,
328 event.args):
329 if atrans == aorig:
330 args_trans.append(atrans)
331 event_trans.args = Arguments(args_trans)
776ec96f
CS
332
333 event_exec = event.copy()
334 event_exec.name += "_exec"
335 event_exec.properties += ["tcg-exec"]
336 event_exec.fmt = event.fmt[1]
56797b1f 337 event_exec.args = event_exec.args.transform(tracetool.transform.TCG_2_HOST)
776ec96f
CS
338
339 new_event = [event_trans, event_exec]
340 event.event_trans, event.event_exec = new_event
341
342 events.extend(new_event)
343
344 return events
650ab98d
LV
345
346
347class TracetoolError (Exception):
348 """Exception for calls to generate."""
349 pass
350
351
9c24a52e 352def try_import(mod_name, attr_name=None, attr_default=None):
650ab98d
LV
353 """Try to import a module and get an attribute from it.
354
355 Parameters
356 ----------
357 mod_name : str
358 Module name.
359 attr_name : str, optional
360 Name of an attribute in the module.
361 attr_default : optional
362 Default value if the attribute does not exist in the module.
363
364 Returns
365 -------
366 A pair indicating whether the module could be imported and the module or
367 object or attribute value.
368 """
369 try:
45d6c787 370 module = __import__(mod_name, globals(), locals(), ["__package__"])
650ab98d
LV
371 if attr_name is None:
372 return True, module
373 return True, getattr(module, str(attr_name), attr_default)
374 except ImportError:
375 return False, None
376
377
80dd5c49 378def generate(events, group, format, backends,
9c24a52e 379 binary=None, probe_prefix=None):
5b808275 380 """Generate the output for the given (format, backends) pair.
650ab98d
LV
381
382 Parameters
383 ----------
9096b78a
DB
384 events : list
385 list of Event objects to generate for
80dd5c49
DB
386 group: str
387 Name of the tracing group
650ab98d
LV
388 format : str
389 Output format name.
5b808275
LV
390 backends : list
391 Output backend names.
52ef093a
LV
392 binary : str or None
393 See tracetool.backend.dtrace.BINARY.
394 probe_prefix : str or None
395 See tracetool.backend.dtrace.PROBEPREFIX.
650ab98d
LV
396 """
397 # fix strange python error (UnboundLocalError tracetool)
398 import tracetool
399
400 format = str(format)
401 if len(format) is 0:
402 raise TracetoolError("format not set")
53158adc 403 if not tracetool.format.exists(format):
650ab98d 404 raise TracetoolError("unknown format: %s" % format)
5b808275
LV
405
406 if len(backends) is 0:
407 raise TracetoolError("no backends specified")
408 for backend in backends:
409 if not tracetool.backend.exists(backend):
410 raise TracetoolError("unknown backend: %s" % backend)
411 backend = tracetool.backend.Wrapper(backends, format)
650ab98d 412
52ef093a
LV
413 import tracetool.backend.dtrace
414 tracetool.backend.dtrace.BINARY = binary
415 tracetool.backend.dtrace.PROBEPREFIX = probe_prefix
416
80dd5c49 417 tracetool.format.generate(events, format, backend, group)
This page took 0.40682 seconds and 4 git commands to generate.