blob: 97a72710909a6424c958c16c3b38ac690308694b [file] [log] [blame]
Eli Benderskya2915862012-06-23 06:25:53 +03001#-----------------------------------------------------------------
Hart Chua611da92017-02-19 11:30:42 -06002# pycparser: func_calls.py
Eli Benderskya2915862012-06-23 06:25:53 +03003#
4# Using pycparser for printing out all the calls of some function
5# in a C file.
6#
Jon Dufresne1d866992018-06-26 13:49:35 -07007# Eli Bendersky [https://eli.thegreenplace.net/]
Eli Benderskya2915862012-06-23 06:25:53 +03008# 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
Eli Benderskya2915862012-06-23 06:25:53 +030015sys.path.extend(['.', '..'])
16
17from pycparser import c_parser, c_ast, parse_file
18
19
Eli Bendersky2a29d562018-10-23 14:05:56 -070020# A visitor with some state information (the funcname it's looking for)
Eli Benderskya2915862012-06-23 06:25:53 +030021class FuncCallVisitor(c_ast.NodeVisitor):
Eli Bendersky3921e8e2010-05-21 09:05:39 +030022 def __init__(self, funcname):
Eli Benderskya2915862012-06-23 06:25:53 +030023 self.funcname = funcname
24
25 def visit_FuncCall(self, node):
26 if node.name.name == self.funcname:
Eli Bendersky331f81f2015-04-21 14:42:56 -070027 print('%s called at %s' % (self.funcname, node.name.coord))
Eli Bendersky2a29d562018-10-23 14:05:56 -070028 # Visit args in case they contain more func calls.
Eli Bendersky71a19302019-02-15 06:40:34 -080029 if node.args:
30 self.visit(node.args)
Eli Benderskya2915862012-06-23 06:25:53 +030031
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:
Eli Bendersky331f81f2015-04-21 14:42:56 -070044 filename = 'examples/c_files/hash.c'
Eli Benderskya2915862012-06-23 06:25:53 +030045 func = 'malloc'
46
47 show_func_calls(filename, func)