-1

I need to use lightweight instrumentation tools (say, using some existing Python or maybe C pre-processor framework) to systematically insert statements in if-conditions of C functions:

For example, let foo be the C function:

int foo(int x){
   if (x>3) 
        return x;
}

I need to transform it to

int foo(int x){
   if (x>3){ 
        print ("%d", x); 
        return x;
  }
}

I have tried using LLVM, but it does not integrate better with other parts of the code. Here, I would prefer a Python/C preprocessor framework solution. Thanks for your ideas.

zell
  • 9,830
  • 10
  • 62
  • 115
  • A `void` function cannot return a value. And even if it was `int` type, not all your paths return a value. – Weather Vane Feb 08 '16 at 17:48
  • 1
    What have you tried? And exactly how automatic do you want this to be -- are you willing to manually add anything to these `if` statements? – Dmitri Feb 08 '16 at 17:51
  • 3
    In your example, the code to be inserted seems fairly specific to the context into which you want to insert it. How do you imagine this being accomplished by an automated tool? – John Bollinger Feb 08 '16 at 18:06
  • 2
    https://github.com/eliben/pycparser - parse the C code. Navigate the AST, and add your own customization as you walk the nodes... – Forhad Ahmed Feb 08 '16 at 18:51

1 Answers1

1

You could consider using GCC MELT or perhaps the GCC Python Plugin to customize the GCC compiler to transform its Gimple representation. It would be a complete solution, but I am not sure it qualifies as "lightweight" (because you need to understand the details of GCC internals), but neither is a Clang/LLVM approach. You'll probably need more than a week of work (notably to learn about the internals of GCC, or of Clang/LLVM)

BTW, your problem is less easy than what you believe, since

int foobar(int x) { return (x>3)?(x*6):(x*x); } 

contains a conditional. Also, your original function is exactly equivalent to

int foo(int x){
    while (x>3) // this while is done 0 or 1 time
      return x;
}

and it is easy to find many other ways to express it.

So a purely syntactic approach would never work completely. Hence, you cannot hope for something "light".

(my opinion is that C code instrumentation is never a lightweight problem)

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547