File: __init__.py

package info (click to toggle)
systemtap 5.1-5
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 47,964 kB
  • sloc: cpp: 80,838; ansic: 54,757; xml: 49,725; exp: 43,665; sh: 11,527; python: 5,003; perl: 2,252; tcl: 1,312; makefile: 1,006; javascript: 149; lisp: 105; awk: 101; asm: 91; java: 70; sed: 16
file content (305 lines) | stat: -rw-r--r-- 11,292 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# systemtap python module
# Copyright (C) 2016 Red Hat Inc.
#
# This file is part of systemtap, and is free software.  You can
# redistribute it and/or modify it under the terms of the GNU General
# Public License (GPL); either version 2, or (at your option) any
# later version.

# Note that we'd like for this module to be the same between python 2
# and python 3, but the 'print' function has changed quite
# dramatically between the two versions. You'd think we could use the
# '__future__' module's 'print' function so we'd be able to use python
# 3's 'print' function style everywhere. However, this causes python 2
# scripts that get loaded to have to use python 3 print syntax, since
# the '__future__' module's print function "leaks" through to the
# python 2 script. There's probably a way to fix that, but we'll just
# punt and use 'sys.stdout.write()', which is a little less
# convenient, but works the same on both python 2 and python 3.
import cmd
import os.path
import sys

if sys.version_info[0] == 2:
    import _HelperSDT
else:
    from . import _HelperSDT

class _Breakpoint:
    def __init__(self, index, filename, funcname, lineno, flags, key):
        self.index = index
        self.filename = filename
        self.funcname = funcname
        self.lineno = lineno
        self.key = key

        # Decode flags.
        self.callp = False
        self.returnp = False
        if flags & 0x2:
            self.callp = True
        if flags & 0x1:
            self.returnp = True

    def dump(self, out=None):
        if out is None:
            out = sys.stdout
        out.write("%s\n" % self.bpformat())

    def bpformat(self):
        if self.returnp:
            disp = '%s.return:%d' % (self.funcname, self.lineno)
        elif self.callp:
            disp = '%s.call:%d' % (self.funcname, self.lineno)
        else:
            disp = '%s:%d' % (self.funcname, self.lineno)
        return '%-4dbreakpoint at %s:%s %d' % (self.index, self.filename,
                                               disp, self.key)


class _BreakpointList:
    def __init__(self):
        self._index = 1
        self._bynumber = []      # breakpoints indexed by number

        # N.B. To make sure we're inside the right function, and not
        # just executing a 'def' statement, we need the function name
        # for line number breakpoints.
        #
        # The 'by line' and 'by function' lists are indexed by a (file,
        # function, lineno) tuple. The 'by function return' list is
        # indexed by a (file, function) tuple.
        self._byline = {}
        self._byfunc = {}
        self._byfuncret = {}

        # Let's keep a cache of the os.path.abspath() results, to
        # avoid looking up the same paths over and over again.
        self._abspath_cache = {}

    def _abspath(self, path):
        if path in self._abspath_cache:
            return self._abspath_cache[path]
        abspath = os.path.abspath(path)
        self._abspath_cache[path] = abspath
        return abspath
        
    def add(self, filename, funcname, lineno, flags, key):
        # Ensure we've got a full absolute path here.
        filename = self._abspath(filename)

        # We get passed the full function name, like
        # "class.method". When the breakpoint hits, we only see
        # 'method'. So, cut the function name down to the last bit.
        period = funcname.rfind('.')
        if period >= 0:
            funcname = funcname[period + 1:]

        bp = _Breakpoint(self._index, filename, funcname, lineno,
                         flags, key)
        self._index += 1
        self._bynumber.append(bp)

        if bp.returnp:
            if (filename, funcname) in self._byfuncret:
                self._byfuncret[filename, funcname].append(bp)
            else:
                self._byfuncret[filename, funcname] = [bp]
        elif bp.callp:
            if (filename, funcname, lineno) in self._byfunc:
                self._byfunc[filename, funcname, lineno].append(bp)
            else:
                self._byfunc[filename, funcname, lineno] = [bp]
        else:
            if (filename, funcname, lineno) in self._byline:
                self._byline[filename, funcname, lineno].append(bp)
            else:
                self._byline[filename, funcname, lineno] = [bp]

    def dump(self, out=None):
        if out is None:
            out = sys.stdout
        for bp in self._bynumber:
            bp.dump(out)

    def break_here(self, frame, event):
        # Depending on how the script name was passed to python,
        # relative or absolute, we might or might not get a full
        # pathname here. So, we'll make sure we've got an absolute
        # path.
        filename = self._abspath(frame.f_code.co_filename)

        funcname = frame.f_code.co_name
        lineno = frame.f_lineno
        if event == 'call':
            if (filename, funcname, lineno) in self._byfunc:
                return self._byfunc[filename, funcname, lineno]
        elif event == 'line':
            if (filename, funcname, lineno) in self._byline:
                return self._byline[filename, funcname, lineno]
        elif event == 'return':
            if (filename, funcname) in self._byfuncret:
                return self._byfuncret[filename, funcname]
        return None


class Dispatcher(cmd.Cmd):
    def __init__(self, pyfile):
        # Note that using the cmd class here is overkill, but it would
        # allow us to add more commands very easily.
        cmd.Cmd.__init__(self)
        self._bplist = _BreakpointList()

        # Note that the filename of breakpoint info has the python
        # major version present.
        bpFileBase = '_stp_python%d_probes' % sys.version_info[0]

        # Read the breakpoints from a file.
        lines = []
        if 'SYSTEMTAP_MODULE' in os.environ:
            self.envModule = os.environ['SYSTEMTAP_MODULE']
            bpFileName = "/proc/systemtap/%s/%s" % (self.envModule,
                                                    bpFileBase)
            try:
                bpFile = open(bpFileName)
            except IOError:
                sys.stderr.write("Error: the '%s' file could not be opened\n"
                                 % bpFileName)
                sys.exit(1)
            else:
                lines = bpFile.readlines()
                bpFile.close()
        else:
            sys.stderr.write("Error: the 'SYSTEMTAP_MODULE' environment"
                             " variable does not exist\n")
            sys.exit(1)

        # Now handle each command
        for line in lines:
            line = line[:-1]
            if len(line) > 0 and line[0] != '#':
                self.onecmd(line)

    def pytrace_dispatch(self, frame, event, arg):
        if event == 'call':
            bplist = self._bplist.break_here(frame, event)
            if bplist:
                for bp in bplist:
                    _HelperSDT.trace_callback(_HelperSDT.PyTrace_CALL,
                                              frame, arg, self.envModule,
                                              bp.key)
            return self.pytrace_dispatch
        elif event == 'line':
            bplist = self._bplist.break_here(frame, event)
            if bplist:
                for bp in bplist:
                    _HelperSDT.trace_callback(_HelperSDT.PyTrace_LINE,
                                              frame, arg, self.envModule,
                                              bp.key)
            return self.pytrace_dispatch
        elif event == 'return':
            bplist = self._bplist.break_here(frame, event)
            if bplist:
                for bp in bplist:
                    _HelperSDT.trace_callback(_HelperSDT.PyTrace_RETURN,
                                              frame, arg, self.envModule,
                                              bp.key)
            return self.pytrace_dispatch
        return self.pytrace_dispatch

    #
    # cmd class commands
    #

    def do_b(self, arg):
        # Breakpoint command:
        #   b [ MODULE|FUNCTION@FILENAME:LINENO|FLAGS|KEY ]
        if not arg:
            self._bplist.dump()
            return

        # Parse argument.
        # FIXME: 'module' needed?
        #  module = None
        funcname = None
        filename = None
        lineno = None
        flags = None
        key = None
        parts = arg.split('|')
        if len(parts) != 4:
            sys.stderr.write("Invalid breakpoint format: %s\n" % arg)
            sys.stderr.write("Wrong number of major parts (%d vs. 4)\n" %
                             len(parts))
            return
        #  module = parts[0]
        filename_arg = parts[1]
        try:
            flags = int(parts[2])
        except:
            sys.stderr.write("Invalid breakpoint format: %s\n" % arg)
            sys.stderr.write("Invalid flags value (%s)\n" % parts[2])
            return
        try:
            key = int(parts[3])
        except:
            sys.stderr.write("Invalid breakpoint format: %s\n" % arg)
            sys.stderr.write("Invalid key value (%s)\n" % parts[3])
            return
        parts = filename_arg.split('@')
        if len(parts) != 2:
            sys.stderr.write("Invalid breakpoint format: %s\n" % arg)
            sys.stderr.write("Wrong number of filename parts (%d vs. 2)\n" %
                             len(parts))
            return
        funcname = parts[0]
        lineno_arg = parts[1]
        parts = lineno_arg.split(':')
        if len(parts) != 2:
            sys.stderr.write("Invalid breakpoint format: %s\n" % arg)
            sys.stderr.write("Wrong number of line number parts (%d vs. 2)\n" %
                             len(parts))
            return
        filename = parts[0]
        try:
            lineno = int(parts[1])
        except:
            sys.stderr.write("Invalid breakpoint format: %s\n" % arg)
            sys.stderr.write("Invalid line number value (%s)\n" % parts[1])
            return

        # Actually add the breakpoint.
        self._bplist.add(filename, funcname, lineno, flags, key)


def run():
    # Now that we're attached, run the real python file.
    mainpyfile = sys.argv[1]
    if not os.path.exists(mainpyfile):
        sys.stderr.write("Error: '%s' does not exist\n" % mainpyfile)
        sys.exit(1)

    del sys.argv[0]         # Hide this module from the argument list

    # Start tracing.
    dispatcher = Dispatcher(mainpyfile)
    sys.settrace(dispatcher.pytrace_dispatch)

    # The script we're about to run has to run in __main__ namespace
    # (or imports from __main__ will break).
    #
    # So we clear up the __main__ namespace and set several special
    # variables (this gets rid of our globals).
    import __main__
    __main__.__dict__.clear()
    __main__.__dict__.update({"__name__": "__main__",
                              "__file__": mainpyfile,
                              "__builtins__": __builtins__})

    # Run the real file. When it finishes, remove tracing.
    try:
        # execfile(mainpyfile, __main__.__dict__, __main__.__dict__)
        exec(compile(open(mainpyfile).read(), mainpyfile, 'exec'),
             __main__.__dict__, __main__.__dict__)
    finally:
        sys.settrace(None)