1#----------------------------------------------------------------- 2# pycparser: func_calls.py 3# 4# Using pycparser for printing out all the calls of some function 5# in a C file. 6# 7# Eli Bendersky [https://eli.thegreenplace.net/] 8# License: BSD 9#----------------------------------------------------------------- 10from __future__ import print_function 11import sys 12 13# This is not required if you've installed pycparser into 14# your site-packages/ with setup.py 15sys.path.extend(['.', '..']) 16 17from pycparser import c_parser, c_ast, parse_file 18 19 20# A visitor with some state information (the funcname it's looking for) 21class FuncCallVisitor(c_ast.NodeVisitor): 22 def __init__(self, funcname): 23 self.funcname = funcname 24 25 def visit_FuncCall(self, node): 26 if node.name.name == self.funcname: 27 print('%s called at %s' % (self.funcname, node.name.coord)) 28 # Visit args in case they contain more func calls. 29 if node.args: 30 self.visit(node.args) 31 32 33def show_func_calls(filename, funcname): 34 ast = parse_file(filename, use_cpp=True) 35 v = FuncCallVisitor(funcname) 36 v.visit(ast) 37 38 39if __name__ == "__main__": 40 if len(sys.argv) > 2: 41 filename = sys.argv[1] 42 func = sys.argv[2] 43 else: 44 filename = 'examples/c_files/hash.c' 45 func = 'malloc' 46 47 show_func_calls(filename, func) 48