xref: /openbmc/qemu/scripts/tracetool/__init__.py (revision 7d08f0da901db4e9a36e17164bc77941cbcd87b7)
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
18
19import tracetool.format
20import tracetool.backend
21
22
23def error_write(*lines):
24    """Write a set of error lines."""
25    sys.stderr.writelines("\n".join(lines) + "\n")
26
27def error(*lines):
28    """Write a set of error lines and exit."""
29    error_write(*lines)
30    sys.exit(1)
31
32
33def out(*lines, **kwargs):
34    """Write a set of output lines.
35
36    You can use kwargs as a shorthand for mapping variables when formating all
37    the strings in lines.
38    """
39    lines = [ l % kwargs for l in lines ]
40    sys.stdout.writelines("\n".join(lines) + "\n")
41
42
43class Arguments:
44    """Event arguments description."""
45
46    def __init__(self, args):
47        """
48        Parameters
49        ----------
50        args :
51            List of (type, name) tuples.
52        """
53        self._args = args
54
55    @staticmethod
56    def build(arg_str):
57        """Build and Arguments instance from an argument string.
58
59        Parameters
60        ----------
61        arg_str : str
62            String describing the event arguments.
63        """
64        res = []
65        for arg in arg_str.split(","):
66            arg = arg.strip()
67            if arg == 'void':
68                continue
69
70            if '*' in arg:
71                arg_type, identifier = arg.rsplit('*', 1)
72                arg_type += '*'
73                identifier = identifier.strip()
74            else:
75                arg_type, identifier = arg.rsplit(None, 1)
76
77            res.append((arg_type, identifier))
78        return Arguments(res)
79
80    def __iter__(self):
81        """Iterate over the (type, name) pairs."""
82        return iter(self._args)
83
84    def __len__(self):
85        """Number of arguments."""
86        return len(self._args)
87
88    def __str__(self):
89        """String suitable for declaring function arguments."""
90        if len(self._args) == 0:
91            return "void"
92        else:
93            return ", ".join([ " ".join([t, n]) for t,n in self._args ])
94
95    def __repr__(self):
96        """Evaluable string representation for this object."""
97        return "Arguments(\"%s\")" % str(self)
98
99    def names(self):
100        """List of argument names."""
101        return [ name for _, name in self._args ]
102
103    def types(self):
104        """List of argument types."""
105        return [ type_ for type_, _ in self._args ]
106
107
108class Event(object):
109    """Event description.
110
111    Attributes
112    ----------
113    name : str
114        The event name.
115    fmt : str
116        The event format string.
117    properties : set(str)
118        Properties of the event.
119    args : Arguments
120        The event arguments.
121    """
122
123    _CRE = re.compile("((?P<props>.*)\s+)?(?P<name>[^(\s]+)\((?P<args>[^)]*)\)\s*(?P<fmt>\".*)?")
124
125    _VALID_PROPS = set(["disable"])
126
127    def __init__(self, name, props, fmt, args):
128        """
129        Parameters
130        ----------
131        name : string
132            Event name.
133        props : list of str
134            Property names.
135        fmt : str
136            Event printing format.
137        args : Arguments
138            Event arguments.
139        """
140        self.name = name
141        self.properties = props
142        self.fmt = fmt
143        self.args = args
144
145        unknown_props = set(self.properties) - self._VALID_PROPS
146        if len(unknown_props) > 0:
147            raise ValueError("Unknown properties: %s" % ", ".join(unknown_props))
148
149    @staticmethod
150    def build(line_str):
151        """Build an Event instance from a string.
152
153        Parameters
154        ----------
155        line_str : str
156            Line describing the event.
157        """
158        m = Event._CRE.match(line_str)
159        assert m is not None
160        groups = m.groupdict('')
161
162        name = groups["name"]
163        props = groups["props"].split()
164        fmt = groups["fmt"]
165        args = Arguments.build(groups["args"])
166
167        return Event(name, props, fmt, args)
168
169    def __repr__(self):
170        """Evaluable string representation for this object."""
171        return "Event('%s %s(%s) %s')" % (" ".join(self.properties),
172                                          self.name,
173                                          self.args,
174                                          self.fmt)
175
176    QEMU_TRACE               = "trace_%(name)s"
177
178    def api(self, fmt=None):
179        if fmt is None:
180            fmt = Event.QEMU_TRACE
181        return fmt % {"name": self.name}
182
183
184def _read_events(fobj):
185    res = []
186    for line in fobj:
187        if not line.strip():
188            continue
189        if line.lstrip().startswith('#'):
190            continue
191        res.append(Event.build(line))
192    return res
193
194
195class TracetoolError (Exception):
196    """Exception for calls to generate."""
197    pass
198
199
200def try_import(mod_name, attr_name = None, attr_default = None):
201    """Try to import a module and get an attribute from it.
202
203    Parameters
204    ----------
205    mod_name : str
206        Module name.
207    attr_name : str, optional
208        Name of an attribute in the module.
209    attr_default : optional
210        Default value if the attribute does not exist in the module.
211
212    Returns
213    -------
214    A pair indicating whether the module could be imported and the module or
215    object or attribute value.
216    """
217    try:
218        module = __import__(mod_name, globals(), locals(), ["__package__"])
219        if attr_name is None:
220            return True, module
221        return True, getattr(module, str(attr_name), attr_default)
222    except ImportError:
223        return False, None
224
225
226def generate(fevents, format, backend,
227             binary = None, probe_prefix = None):
228    """Generate the output for the given (format, backend) pair.
229
230    Parameters
231    ----------
232    fevents : file
233        Event description file.
234    format : str
235        Output format name.
236    backend : str
237        Output backend name.
238    binary : str or None
239        See tracetool.backend.dtrace.BINARY.
240    probe_prefix : str or None
241        See tracetool.backend.dtrace.PROBEPREFIX.
242    """
243    # fix strange python error (UnboundLocalError tracetool)
244    import tracetool
245
246    format = str(format)
247    if len(format) is 0:
248        raise TracetoolError("format not set")
249    mformat = format.replace("-", "_")
250    if not tracetool.format.exists(mformat):
251        raise TracetoolError("unknown format: %s" % format)
252
253    backend = str(backend)
254    if len(backend) is 0:
255        raise TracetoolError("backend not set")
256    mbackend = backend.replace("-", "_")
257    if not tracetool.backend.exists(mbackend):
258        raise TracetoolError("unknown backend: %s" % backend)
259
260    if not tracetool.backend.compatible(mbackend, mformat):
261        raise TracetoolError("backend '%s' not compatible with format '%s'" %
262                             (backend, format))
263
264    import tracetool.backend.dtrace
265    tracetool.backend.dtrace.BINARY = binary
266    tracetool.backend.dtrace.PROBEPREFIX = probe_prefix
267
268    events = _read_events(fevents)
269
270    if backend == "nop":
271        ( e.properies.add("disable") for e in events )
272
273    tracetool.format.generate_begin(mformat, events)
274    tracetool.backend.generate("nop", format,
275                               [ e
276                                 for e in events
277                                 if "disable" in e.properties ])
278    tracetool.backend.generate(backend, format,
279                               [ e
280                                 for e in events
281                                 if "disable" not in e.properties ])
282    tracetool.format.generate_end(mformat, events)
283