-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.py
202 lines (164 loc) · 5.48 KB
/
test.py
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
#!/usr/bin/env python2
from pprint import pprint
import clang
from clang.cindex import CursorKind, Index, CompilationDatabase
from collections import defaultdict
import sys
import json
"""
Dumps a callgraph of a function in a codebase
usage: callgraph.py file.cpp|compile_commands.json [-x exclude-list] [extra clang args...]
The easiest way to generate the file compile_commands.json for any make based
compilation chain is to use Bear and recompile with `bear make`.
When running the python script, after parsing all the codebase, you are
prompted to type in the function's name for which you wan to obtain the
callgraph
"""
clang.cindex.Config.set_library_path("/usr/lib/llvm-7/lib")
CALLGRAPH = defaultdict(list)
FULLNAMES = defaultdict(set)
def get_diag_info(diag):
return {
'severity': diag.severity,
'location': diag.location,
'spelling': diag.spelling,
'ranges': diag.ranges,
'fixits': diag.fixits
}
def fully_qualified(c):
if c is None:
return ''
elif c.kind == CursorKind.TRANSLATION_UNIT:
return ''
else:
res = fully_qualified(c.semantic_parent)
if res != '':
return res + '::' + c.spelling
return c.spelling
def fully_qualified_pretty(c):
if c is None:
return ''
elif c.kind == CursorKind.TRANSLATION_UNIT:
return ''
else:
res = fully_qualified(c.semantic_parent)
if res != '':
return res + '::' + c.displayname
return c.displayname
def is_excluded(node, xfiles, xprefs):
if not node.extent.start.file:
return False
for xf in xfiles:
if node.extent.start.file.name.startswith(xf):
return True
fqp = fully_qualified_pretty(node)
for xp in xprefs:
if fqp.startswith(xp):
return True
return False
def show_info(node, xfiles, xprefs, cur_fun=None):
if node.kind == CursorKind.FUNCTION_TEMPLATE:
if not is_excluded(node, xfiles, xprefs):
cur_fun = node
FULLNAMES[fully_qualified(cur_fun)].add(
fully_qualified_pretty(cur_fun))
if node.kind == CursorKind.CXX_METHOD or \
node.kind == CursorKind.FUNCTION_DECL:
if not is_excluded(node, xfiles, xprefs):
cur_fun = node
FULLNAMES[fully_qualified(cur_fun)].add(
fully_qualified_pretty(cur_fun))
if node.kind == CursorKind.CALL_EXPR:
if node.referenced and not is_excluded(node.referenced, xfiles, xprefs):
CALLGRAPH[fully_qualified_pretty(cur_fun)].append(node.referenced)
for c in node.get_children():
show_info(c, xfiles, xprefs, cur_fun)
def pretty_print(n):
v = ''
if n.is_virtual_method():
v = ' virtual'
if n.is_pure_virtual_method():
v = ' = 0'
return fully_qualified_pretty(n) + v
def print_calls(fun_name, so_far, depth=0):
if depth >= 15:
print('...<too deep>...')
return
if fun_name in CALLGRAPH:
for f in CALLGRAPH[fun_name]:
print(' ' * (depth + 1) + pretty_print(f))
if f in so_far:
continue
so_far.append(f)
if fully_qualified_pretty(f) in CALLGRAPH:
print_calls(fully_qualified_pretty(f), so_far, depth + 1)
else:
print_calls(fully_qualified(f), so_far, depth + 1)
def read_compile_commands(filename):
if filename.endswith('.json'):
with open(filename) as compdb:
return json.load(compdb)
else:
return [{'command': '', 'file': filename}]
def read_args(args):
db = None
clang_args = []
excluded_prefixes = []
excluded_paths = ['/usr']
i = 0
while i < len(args):
if args[i] == '-x':
i += 1
excluded_prefixes = args[i].split(',')
elif args[i] == '-p':
i += 1
excluded_paths = args[i].split(',')
elif args[i][0] == '-':
clang_args.append(args[i])
else:
db = args[i]
i += 1
return {
'db': db,
'clang_args': clang_args,
'excluded_prefixes': excluded_prefixes,
'excluded_paths': excluded_paths
}
def main():
if len(sys.argv) < 2:
print('usage: ' + sys.argv[0] + ' file.cpp|compile_database.json '
'[extra clang args...]')
return
cfg = read_args(sys.argv)
print('reading source files...')
for cmd in read_compile_commands(cfg['db']):
index = Index.create()
c = [
x for x in cmd['command'].split()
if x.startswith('-I') or x.startswith('-std=') or x.startswith('-D')
] + cfg['clang_args']
tu = index.parse(cmd['file'], c)
print(cmd['file'])
if not tu:
parser.error("unable to load input")
for d in tu.diagnostics:
if d.severity == d.Error or d.severity == d.Fatal:
print(' '.join(c))
pprint(('diags', map(get_diag_info, tu.diagnostics)))
return
show_info(tu.cursor, cfg['excluded_paths'], cfg['excluded_prefixes'])
while True:
fun = raw_input('> ')
if not fun:
break
if fun in CALLGRAPH:
print(fun)
print_calls(fun, list())
else:
print('matching:')
for f, ff in FULLNAMES.iteritems():
if f.startswith(fun):
for fff in ff:
print(fff)
if __name__ == '__main__':
main()