xref: /openbmc/qemu/scripts/tracetool/__init__.py (revision b2b36c22bd8b14de34bd108daa96d89ba41fe8e7)
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
231    def api(self, fmt=None):
232        if fmt is None:
233            fmt = Event.QEMU_TRACE
234        return fmt % {"name": self.name}
235
236    def transform(self, *trans):
237        """Return a new Event with transformed Arguments."""
238        return Event(self.name,
239                     list(self.properties),
240                     self.fmt,
241                     self.args.transform(*trans),
242                     self)
243
244
245def _read_events(fobj):
246    res = []
247    for line in fobj:
248        if not line.strip():
249            continue
250        if line.lstrip().startswith('#'):
251            continue
252        res.append(Event.build(line))
253    return res
254
255
256class TracetoolError (Exception):
257    """Exception for calls to generate."""
258    pass
259
260
261def try_import(mod_name, attr_name=None, attr_default=None):
262    """Try to import a module and get an attribute from it.
263
264    Parameters
265    ----------
266    mod_name : str
267        Module name.
268    attr_name : str, optional
269        Name of an attribute in the module.
270    attr_default : optional
271        Default value if the attribute does not exist in the module.
272
273    Returns
274    -------
275    A pair indicating whether the module could be imported and the module or
276    object or attribute value.
277    """
278    try:
279        module = __import__(mod_name, globals(), locals(), ["__package__"])
280        if attr_name is None:
281            return True, module
282        return True, getattr(module, str(attr_name), attr_default)
283    except ImportError:
284        return False, None
285
286
287def generate(fevents, format, backends,
288             binary=None, probe_prefix=None):
289    """Generate the output for the given (format, backends) pair.
290
291    Parameters
292    ----------
293    fevents : file
294        Event description file.
295    format : str
296        Output format name.
297    backends : list
298        Output backend names.
299    binary : str or None
300        See tracetool.backend.dtrace.BINARY.
301    probe_prefix : str or None
302        See tracetool.backend.dtrace.PROBEPREFIX.
303    """
304    # fix strange python error (UnboundLocalError tracetool)
305    import tracetool
306
307    format = str(format)
308    if len(format) is 0:
309        raise TracetoolError("format not set")
310    if not tracetool.format.exists(format):
311        raise TracetoolError("unknown format: %s" % format)
312
313    if len(backends) is 0:
314        raise TracetoolError("no backends specified")
315    for backend in backends:
316        if not tracetool.backend.exists(backend):
317            raise TracetoolError("unknown backend: %s" % backend)
318    backend = tracetool.backend.Wrapper(backends, format)
319
320    import tracetool.backend.dtrace
321    tracetool.backend.dtrace.BINARY = binary
322    tracetool.backend.dtrace.PROBEPREFIX = probe_prefix
323
324    events = _read_events(fevents)
325
326    # transform TCG-enabled events
327    new_events = []
328    for event in events:
329        if "tcg" not in event.properties:
330            new_events.append(event)
331        else:
332            event_trans = event.copy()
333            event_trans.name += "_trans"
334            event_trans.properties += ["tcg-trans"]
335            event_trans.fmt = event.fmt[0]
336            args_trans = []
337            for atrans, aorig in zip(
338                    event_trans.transform(tracetool.transform.TCG_2_HOST).args,
339                    event.args):
340                if atrans == aorig:
341                    args_trans.append(atrans)
342            event_trans.args = Arguments(args_trans)
343            event_trans = event_trans.copy()
344
345            event_exec = event.copy()
346            event_exec.name += "_exec"
347            event_exec.properties += ["tcg-exec"]
348            event_exec.fmt = event.fmt[1]
349            event_exec = event_exec.transform(tracetool.transform.TCG_2_HOST)
350
351            new_event = [event_trans, event_exec]
352            event.event_trans, event.event_exec = new_event
353
354            new_events.extend(new_event)
355    events = new_events
356
357    tracetool.format.generate(events, format, backend)
358