|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +"""Call Graph tracing. |
| 4 | +
|
| 5 | +Execute a python program and for each call being made, record the call and callee. This |
| 6 | +allows us to compare call graph resolution from static analysis with actual data -- that |
| 7 | +is, can we statically determine the target of each actual call correctly. |
| 8 | +
|
| 9 | +If there is 100% code coverage from the Python execution, it would also be possible to |
| 10 | +look at the precision of the call graph resolutions -- that is, do we expect a function to |
| 11 | +be able to be called in a place where it is not? Currently not something we're looking at. |
| 12 | +""" |
| 13 | + |
| 14 | +# read: https://eli.thegreenplace.net/2012/03/23/python-internals-how-callables-work/ |
| 15 | + |
| 16 | +# TODO: Know that a call to a C-function was made. See |
| 17 | +# https://docs.python.org/3/library/bdb.html#bdb.Bdb.trace_dispatch. Maybe use `lxml` as |
| 18 | +# test |
| 19 | + |
| 20 | +# For inspiration, look at these projects: |
| 21 | +# - https://github.com/joerick/pyinstrument (capture call-stack every <n> ms for profiling) |
| 22 | +# - https://github.com/gak/pycallgraph (display call-graph with graphviz after python execution) |
| 23 | + |
| 24 | +import argparse |
| 25 | +import bdb |
| 26 | +from io import StringIO |
| 27 | +import sys |
| 28 | +import os |
| 29 | +import dis |
| 30 | +import dataclasses |
| 31 | +import csv |
| 32 | +import xml.etree.ElementTree as ET |
| 33 | + |
| 34 | +# Copy-Paste and uncomment for interactive ipython sessions |
| 35 | +# import IPython; IPython.embed(); sys.exit() |
| 36 | + |
| 37 | + |
| 38 | +@dataclasses.dataclass(frozen=True) |
| 39 | +class Call(): |
| 40 | + """A call |
| 41 | + """ |
| 42 | + filename: str |
| 43 | + linenum: int |
| 44 | + inst_index: int |
| 45 | + |
| 46 | + @classmethod |
| 47 | + def from_frame(cls, frame, debugger: bdb.Bdb): |
| 48 | + code = frame.f_code |
| 49 | + |
| 50 | + # Uncomment to see the bytecode |
| 51 | + # b = dis.Bytecode(frame.f_code, current_offset=frame.f_lasti) |
| 52 | + # print(b.dis(), file=sys.__stderr__) |
| 53 | + |
| 54 | + return cls( |
| 55 | + filename = debugger.canonic(code.co_filename), |
| 56 | + linenum = frame.f_lineno, |
| 57 | + inst_index = frame.f_lasti, |
| 58 | + ) |
| 59 | + |
| 60 | + |
| 61 | +@dataclasses.dataclass(frozen=True) |
| 62 | +class Callee(): |
| 63 | + """A callee (Function/Lambda/???) |
| 64 | +
|
| 65 | + should (hopefully) be uniquely identified by its name and location (filename+line |
| 66 | + number) |
| 67 | + """ |
| 68 | + funcname: str |
| 69 | + filename: str |
| 70 | + linenum: int |
| 71 | + |
| 72 | + @classmethod |
| 73 | + def from_frame(cls, frame, debugger: bdb.Bdb): |
| 74 | + code = frame.f_code |
| 75 | + return cls( |
| 76 | + funcname = code.co_name, |
| 77 | + filename = debugger.canonic(code.co_filename), |
| 78 | + linenum = frame.f_lineno, |
| 79 | + ) |
| 80 | + |
| 81 | + |
| 82 | +class CallGraphTracer(bdb.Bdb): |
| 83 | + """Tracer that records calls being made |
| 84 | +
|
| 85 | + It would seem obvious that this should have extended `trace` library |
| 86 | + (https://docs.python.org/3/library/trace.html), but that part is not extensible -- |
| 87 | + however, the basic debugger (bdb) is, and provides maybe a bit more help than just |
| 88 | + using `sys.settrace` directly. |
| 89 | + """ |
| 90 | + |
| 91 | + recorded_calls: set |
| 92 | + |
| 93 | + def __init__(self): |
| 94 | + self.recorded_calls = set() |
| 95 | + super().__init__() |
| 96 | + |
| 97 | + def user_call(self, frame, argument_list): |
| 98 | + call = Call.from_frame(frame.f_back, self) |
| 99 | + callee = Callee.from_frame(frame, self) |
| 100 | + |
| 101 | + # _print(f'{call} -> {callee}') |
| 102 | + self.recorded_calls.add((call, callee)) |
| 103 | + |
| 104 | + |
| 105 | +################################################################################ |
| 106 | +# Export |
| 107 | +################################################################################ |
| 108 | + |
| 109 | + |
| 110 | +class Exporter: |
| 111 | + |
| 112 | + @staticmethod |
| 113 | + def export(recorded_calls, outfile_path): |
| 114 | + raise NotImplementedError() |
| 115 | + |
| 116 | + @staticmethod |
| 117 | + def dataclass_to_dict(obj): |
| 118 | + d = dataclasses.asdict(obj) |
| 119 | + prefix = obj.__class__.__name__.lower() |
| 120 | + return {f"{prefix}_{key}": val for (key, val) in d.items()} |
| 121 | + |
| 122 | + |
| 123 | +class CSVExporter(Exporter): |
| 124 | + |
| 125 | + @staticmethod |
| 126 | + def export(recorded_calls, outfile_path): |
| 127 | + with open(outfile_path, 'w', newline='') as csv_file: |
| 128 | + writer = None |
| 129 | + for (call, callee) in recorded_calls: |
| 130 | + data = { |
| 131 | + **Exporter.dataclass_to_dict(call), |
| 132 | + **Exporter.dataclass_to_dict(callee) |
| 133 | + } |
| 134 | + |
| 135 | + if writer is None: |
| 136 | + writer = csv.DictWriter(csv_file, fieldnames=data.keys()) |
| 137 | + writer.writeheader() |
| 138 | + |
| 139 | + writer.writerow(data) |
| 140 | + |
| 141 | + |
| 142 | + print(f'output written to {outfile_path}') |
| 143 | + |
| 144 | + # embed(); sys.exit() |
| 145 | + |
| 146 | + |
| 147 | +class XMLExporter(Exporter): |
| 148 | + |
| 149 | + @staticmethod |
| 150 | + def export(recorded_calls, outfile_path): |
| 151 | + |
| 152 | + root = ET.Element('root') |
| 153 | + |
| 154 | + for (call, callee) in recorded_calls: |
| 155 | + data = { |
| 156 | + **Exporter.dataclass_to_dict(call), |
| 157 | + **Exporter.dataclass_to_dict(callee) |
| 158 | + } |
| 159 | + |
| 160 | + rc = ET.SubElement(root, 'recorded_call') |
| 161 | + # this xml library only supports serializing attributes that have string values |
| 162 | + rc.attrib = {k: str(v) for k, v in data.items()} |
| 163 | + |
| 164 | + tree = ET.ElementTree(root) |
| 165 | + tree.write(outfile_path, encoding='utf-8') |
| 166 | + |
| 167 | + |
| 168 | +################################################################################ |
| 169 | +# __main__ |
| 170 | +################################################################################ |
| 171 | + |
| 172 | + |
| 173 | +if __name__ == "__main__": |
| 174 | + |
| 175 | + |
| 176 | + parser = argparse.ArgumentParser() |
| 177 | + |
| 178 | + |
| 179 | + parser.add_argument('--csv') |
| 180 | + parser.add_argument('--xml') |
| 181 | + |
| 182 | + parser.add_argument('progname', help='file to run as main program') |
| 183 | + parser.add_argument('arguments', nargs=argparse.REMAINDER, |
| 184 | + help='arguments to the program') |
| 185 | + |
| 186 | + opts = parser.parse_args() |
| 187 | + |
| 188 | + # These details of setting up the program to be run is very much inspired by `trace` |
| 189 | + # from the standard library |
| 190 | + sys.argv = [opts.progname, *opts.arguments] |
| 191 | + sys.path[0] = os.path.dirname(opts.progname) |
| 192 | + |
| 193 | + with open(opts.progname) as fp: |
| 194 | + code = compile(fp.read(), opts.progname, 'exec') |
| 195 | + |
| 196 | + # try to emulate __main__ namespace as much as possible |
| 197 | + globs = { |
| 198 | + '__file__': opts.progname, |
| 199 | + '__name__': '__main__', |
| 200 | + '__package__': None, |
| 201 | + '__cached__': None, |
| 202 | + } |
| 203 | + |
| 204 | + real_stdout = sys.stdout |
| 205 | + real_stderr = sys.stderr |
| 206 | + captured_stdout = StringIO() |
| 207 | + |
| 208 | + sys.stdout = captured_stdout |
| 209 | + cgt = CallGraphTracer() |
| 210 | + cgt.run(code, globs, globs) |
| 211 | + sys.stdout = real_stdout |
| 212 | + |
| 213 | + if opts.csv: |
| 214 | + CSVExporter.export(cgt.recorded_calls, opts.csv) |
| 215 | + elif opts.xml: |
| 216 | + XMLExporter.export(cgt.recorded_calls, opts.xml) |
| 217 | + else: |
| 218 | + for (call, callee) in cgt.recorded_calls: |
| 219 | + print(f'{call} -> {callee}') |
| 220 | + |
| 221 | + print('--- captured stdout ---') |
| 222 | + print(captured_stdout.getvalue(), end='') |
0 commit comments