1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4"""
5Generate .stp file that outputs simpletrace binary traces (DTrace with SystemTAP only).
6"""
7
8__author__     = "Stefan Hajnoczi <redhat.com>"
9__copyright__  = "Copyright (C) 2014, Red Hat, Inc."
10__license__    = "GPL version 2 or (at your option) any later version"
11
12__maintainer__ = "Stefan Hajnoczi"
13__email__      = "stefanha@redhat.com"
14
15
16from tracetool import out
17from tracetool.backend.dtrace import binary, probeprefix
18from tracetool.backend.simple import is_string
19from tracetool.format.stap import stap_escape
20
21def global_var_name(name):
22    return probeprefix().replace(".", "_") + "_" + name
23
24def generate(events, backend, group):
25    out('/* This file is autogenerated by tracetool, do not edit. */',
26        '')
27
28    for event_id, e in enumerate(events):
29        if 'disable' in e.properties:
30            continue
31
32        out('probe %(probeprefix)s.simpletrace.%(name)s = %(probeprefix)s.%(name)s ?',
33            '{',
34            probeprefix=probeprefix(),
35            name=e.name)
36
37        # Calculate record size
38        sizes = ['24'] # sizeof(TraceRecord)
39        for type_, name in e.args:
40            name = stap_escape(name)
41            if is_string(type_):
42                out('    try {',
43                    '        arg%(name)s_str = %(name)s ? user_string_n(%(name)s, 512) : "<null>"',
44                    '    } catch {}',
45                    '    arg%(name)s_len = strlen(arg%(name)s_str)',
46                    name=name)
47                sizes.append('4 + arg%s_len' % name)
48            else:
49                sizes.append('8')
50        sizestr = ' + '.join(sizes)
51
52        # Generate format string and value pairs for record header and arguments
53        fields = [('8b', str(event_id)),
54                  ('8b', 'gettimeofday_ns()'),
55                  ('4b', sizestr),
56                  ('4b', 'pid()')]
57        for type_, name in e.args:
58            name = stap_escape(name)
59            if is_string(type_):
60                fields.extend([('4b', 'arg%s_len' % name),
61                               ('.*s', 'arg%s_len, arg%s_str' % (name, name))])
62            else:
63                fields.append(('8b', name))
64
65        # Emit the entire record in a single SystemTap printf()
66        fmt_str = '%'.join(fmt for fmt, _ in fields)
67        arg_str = ', '.join(arg for _, arg in fields)
68        out('    printf("%%8b%%%(fmt_str)s", 1, %(arg_str)s)',
69            fmt_str=fmt_str, arg_str=arg_str)
70
71        out('}')
72
73    out()
74