6

I'm trying to get up to speed on using Clang by doing a bit of dynamic code instrumentation with C (and maybe C++) where I take a source file and generate an instrumented output. I'd like to add a function call at the beginning of any block and also change all boolean expressions to call some function so I can track that too. For example:

foo = a && (b || c);

would become something like:

foo = EXPR_AND(a, EXPR_OR(b, c));

and thus I can track all combinations of conditions that occur.

I assume using a RecursiveASTVisitor would be the best approach, but is there an easy way to output the C code for each node I visit?

Any suggestions of what to look at to accomplish something like this would be most appreciated!

Note: After some further investigation, I just discovered libclang which looks like it could be my best friend. Coupled with a rewriter, I might just have what I need. Any pointers to good examples (I just found the excellent Apple developers meeting video on libclang) would be great.

  • Your proposed transform greatly changes the semantics of the code if `b` or `c` contain any side effects... – Chris Dodd Jan 22 '12 at 01:15
  • Actually, EXPR_AND and EXPR_OR are macro expansions that look something like: #define EXPR_AND(a, b) (a ? instr[0] = 1 : instr[1] = 1,0) && (b ? instr[2] = 0 : instr[3] = 1,0) – Robert Ankeney Jan 28 '12 at 23:45

1 Answers1

2

For a good example see this project.

It uses clang in order to instrument call function entering and exit, and it also inspects types of passed arguments.

Dan Aloni
  • 3,968
  • 22
  • 30