• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
21# looking for)
22#
23class FuncCallVisitor(c_ast.NodeVisitor):
24    def __init__(self, funcname):
25        self.funcname = funcname
26
27    def visit_FuncCall(self, node):
28        if node.name.name == self.funcname:
29            print('%s called at %s' % (self.funcname, node.name.coord))
30
31
32def show_func_calls(filename, funcname):
33    ast = parse_file(filename, use_cpp=True)
34    v = FuncCallVisitor(funcname)
35    v.visit(ast)
36
37
38if __name__ == "__main__":
39    if len(sys.argv) > 2:
40        filename = sys.argv[1]
41        func = sys.argv[2]
42    else:
43        filename = 'examples/c_files/hash.c'
44        func = 'malloc'
45
46    show_func_calls(filename, func)
47