xref: /qemu/scripts/tracetool/__init__.py (revision 707c8a98e4c42a559ad8d1ec0e77e28ffd666346)
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 <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"
11
12__maintainer__ = "Stefan Hajnoczi"
13__email__      = "stefanha@linux.vnet.ibm.com"
14
15
16import re
17import sys
18import weakref
19
20import tracetool.format
21import tracetool.backend
22import tracetool.transform
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 :
53            List of (type, name) tuples.
54        """
55        self._args = args
56
57    def copy(self):
58        """Create a new copy."""
59        return Arguments(list(self._args))
60
61    @staticmethod
62    def build(arg_str):
63        """Build and Arguments instance from an argument string.
64
65        Parameters
66        ----------
67        arg_str : str
68            String describing the event arguments.
69        """
70        res = []
71        for arg in arg_str.split(","):
72            arg = arg.strip()
73            if arg == 'void':
74                continue
75
76            if '*' in arg:
77                arg_type, identifier = arg.rsplit('*', 1)
78                arg_type += '*'
79                identifier = identifier.strip()
80            else:
81                arg_type, identifier = arg.rsplit(None, 1)
82
83            res.append((arg_type, identifier))
84        return Arguments(res)
85
86    def __iter__(self):
87        """Iterate over the (type, name) pairs."""
88        return iter(self._args)
89
90    def __len__(self):
91        """Number of arguments."""
92        return len(self._args)
93
94    def __str__(self):
95        """String suitable for declaring function arguments."""
96        if len(self._args) == 0:
97            return "void"
98        else:
99            return ", ".join([ " ".join([t, n]) for t,n in self._args ])
100
101    def __repr__(self):
102        """Evaluable string representation for this object."""
103        return "Arguments(\"%s\")" % str(self)
104
105    def names(self):
106        """List of argument names."""
107        return [ name for _, name in self._args ]
108
109    def types(self):
110        """List of argument types."""
111        return [ type_ for type_, _ in self._args ]
112
113    def transform(self, *trans):
114        """Return a new Arguments instance with transformed types.
115
116        The types in the resulting Arguments instance are transformed according
117        to tracetool.transform.transform_type.
118        """
119        res = []
120        for type_, name in self._args:
121            res.append((tracetool.transform.transform_type(type_, *trans),
122                        name))
123        return Arguments(res)
124
125
126class Event(object):
127    """Event description.
128
129    Attributes
130    ----------
131    name : str
132        The event name.
133    fmt : str
134        The event format string.
135    properties : set(str)
136        Properties of the event.
137    args : Arguments
138        The event arguments.
139    """
140
141    _CRE = re.compile("((?P<props>.*)\s+)?"
142                      "(?P<name>[^(\s]+)"
143                      "\((?P<args>[^)]*)\)"
144                      "\s*"
145                      "(?:(?:(?P<fmt_trans>\".+),)?\s*(?P<fmt>\".+))?"
146                      "\s*")
147
148    _VALID_PROPS = set(["disable", "tcg", "tcg-trans", "tcg-exec"])
149
150    def __init__(self, name, props, fmt, args, orig=None):
151        """
152        Parameters
153        ----------
154        name : string
155            Event name.
156        props : list of str
157            Property names.
158        fmt : str, list of str
159            Event printing format (or formats).
160        args : Arguments
161            Event arguments.
162        orig : Event or None
163            Original Event before transformation.
164        """
165        self.name = name
166        self.properties = props
167        self.fmt = fmt
168        self.args = args
169
170        if orig is None:
171            self.original = weakref.ref(self)
172        else:
173            self.original = orig
174
175        unknown_props = set(self.properties) - self._VALID_PROPS
176        if len(unknown_props) > 0:
177            raise ValueError("Unknown properties: %s"
178                             % ", ".join(unknown_props))
179        assert isinstance(self.fmt, str) or len(self.fmt) == 2
180
181    def copy(self):
182        """Create a new copy."""
183        return Event(self.name, list(self.properties), self.fmt,
184                     self.args.copy(), self)
185
186    @staticmethod
187    def build(line_str):
188        """Build an Event instance from a string.
189
190        Parameters
191        ----------
192        line_str : str
193            Line describing the event.
194        """
195        m = Event._CRE.match(line_str)
196        assert m is not None
197        groups = m.groupdict('')
198
199        name = groups["name"]
200        props = groups["props"].split()
201        fmt = groups["fmt"]
202        fmt_trans = groups["fmt_trans"]
203        if len(fmt_trans) > 0:
204            fmt = [fmt_trans, fmt]
205        args = Arguments.build(groups["args"])
206
207        if "tcg-trans" in props:
208            raise ValueError("Invalid property 'tcg-trans'")
209        if "tcg-exec" in props:
210            raise ValueError("Invalid property 'tcg-exec'")
211        if "tcg" not in props and not isinstance(fmt, str):
212            raise ValueError("Only events with 'tcg' property can have two formats")
213        if "tcg" in props and isinstance(fmt, str):
214            raise ValueError("Events with 'tcg' property must have two formats")
215
216        return Event(name, props, fmt, args)
217
218    def __repr__(self):
219        """Evaluable string representation for this object."""
220        if isinstance(self.fmt, str):
221            fmt = self.fmt
222        else:
223            fmt = "%s, %s" % (self.fmt[0], self.fmt[1])
224        return "Event('%s %s(%s) %s')" % (" ".join(self.properties),
225                                          self.name,
226                                          self.args,
227                                          fmt)
228
229    QEMU_TRACE               = "trace_%(name)s"
230    QEMU_TRACE_TCG           = QEMU_TRACE + "_tcg"
231
232    def api(self, fmt=None):
233        if fmt is None:
234            fmt = Event.QEMU_TRACE
235        return fmt % {"name": self.name}
236
237    def transform(self, *trans):
238        """Return a new Event with transformed Arguments."""
239        return Event(self.name,
240                     list(self.properties),
241                     self.fmt,
242                     self.args.transform(*trans),
243                     self)
244
245
246def _read_events(fobj):
247    res = []
248    for line in fobj:
249        if not line.strip():
250            continue
251        if line.lstrip().startswith('#'):
252            continue
253        res.append(Event.build(line))
254    return res
255
256
257class TracetoolError (Exception):
258    """Exception for calls to generate."""
259    pass
260
261
262def try_import(mod_name, attr_name=None, attr_default=None):
263    """Try to import a module and get an attribute from it.
264
265    Parameters
266    ----------
267    mod_name : str
268        Module name.
269    attr_name : str, optional
270        Name of an attribute in the module.
271    attr_default : optional
272        Default value if the attribute does not exist in the module.
273
274    Returns
275    -------
276    A pair indicating whether the module could be imported and the module or
277    object or attribute value.
278    """
279    try:
280        module = __import__(mod_name, globals(), locals(), ["__package__"])
281        if attr_name is None:
282            return True, module
283        return True, getattr(module, str(attr_name), attr_default)
284    except ImportError:
285        return False, None
286
287
288def generate(fevents, format, backends,
289             binary=None, probe_prefix=None):
290    """Generate the output for the given (format, backends) pair.
291
292    Parameters
293    ----------
294    fevents : file
295        Event description file.
296    format : str
297        Output format name.
298    backends : list
299        Output backend names.
300    binary : str or None
301        See tracetool.backend.dtrace.BINARY.
302    probe_prefix : str or None
303        See tracetool.backend.dtrace.PROBEPREFIX.
304    """
305    # fix strange python error (UnboundLocalError tracetool)
306    import tracetool
307
308    format = str(format)
309    if len(format) is 0:
310        raise TracetoolError("format not set")
311    if not tracetool.format.exists(format):
312        raise TracetoolError("unknown format: %s" % format)
313
314    if len(backends) is 0:
315        raise TracetoolError("no backends specified")
316    for backend in backends:
317        if not tracetool.backend.exists(backend):
318            raise TracetoolError("unknown backend: %s" % backend)
319    backend = tracetool.backend.Wrapper(backends, format)
320
321    import tracetool.backend.dtrace
322    tracetool.backend.dtrace.BINARY = binary
323    tracetool.backend.dtrace.PROBEPREFIX = probe_prefix
324
325    events = _read_events(fevents)
326
327    # transform TCG-enabled events
328    new_events = []
329    for event in events:
330        if "tcg" not in event.properties:
331            new_events.append(event)
332        else:
333            event_trans = event.copy()
334            event_trans.name += "_trans"
335            event_trans.properties += ["tcg-trans"]
336            event_trans.fmt = event.fmt[0]
337            args_trans = []
338            for atrans, aorig in zip(
339                    event_trans.transform(tracetool.transform.TCG_2_HOST).args,
340                    event.args):
341                if atrans == aorig:
342                    args_trans.append(atrans)
343            event_trans.args = Arguments(args_trans)
344            event_trans = event_trans.copy()
345
346            event_exec = event.copy()
347            event_exec.name += "_exec"
348            event_exec.properties += ["tcg-exec"]
349            event_exec.fmt = event.fmt[1]
350            event_exec = event_exec.transform(tracetool.transform.TCG_2_HOST)
351
352            new_event = [event_trans, event_exec]
353            event.event_trans, event.event_exec = new_event
354
355            new_events.extend(new_event)
356    events = new_events
357
358    tracetool.format.generate(events, format, backend)
359