0

I'm working on automating a tool that prints out all constants in a C file. So far, I have managed to print out all the constants in a C file but I can't figure out of a way to show the variable names they are associated with without printing out the whole abstract syntax tree, which has a lot of unnecessary information for me. Does anyone have any ideas? Right now, it will print out the constants, and their type. Here is my code:

from pycparser import c_parser, c_ast, parse_file

class ConstantVisitor(c_ast.NodeVisitor):
    def __init__(self):
        self.values = []
    def visit_Constant(self, node):
        self.values.append(node.value)
        node.show(showcoord=True,nodenames=True,attrnames=True)

def show_tree(filename):
# Note that cpp is used. Provide a path to your own cpp or
# make sure one exists in PATH.
    ast = parse_file(filename, use_cpp=True,cpp_args=['-E', r'-Iutils/fake_libc_include'])
    cv = ConstantVisitor()
    cv.visit(ast)

if __name__ == "__main__":
    if len(sys.argv) > 1:
        filename  = sys.argv[1]
    else:
        filename = 'xmrig-master/src/crypto/c_blake256.c'

    show_tree(filename)

edit: current output: constant: type=int, value=0x243456BE desired output: constant: type=int, name=variable name constant belongs to(usually an array name), value=0x243456BE

1 Answers1

0

You may need to create a more sophisticated visitor if you want to retain information about parent nodes of the visited node. See this FAQ answer for an example.

That said, you will also need to define your goal much more clearly. Constant nodes are not always associated with a variable. For example:

  return a + 30 + 50;

Has two Constant nodes in it (for 30 and for 50); what variable are they associated with?

Perhaps what you're looking for is variable declarations - Decl nodes with names. Then once you find a Decl node, do another visiting under this node looking for all Constant nodes.

Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412