Automatically wrap C/C++ function at compile-time with annotation

516 views Asked by At

In my C/C++ code I want to annotate different functions and methods so that additional code gets added at compile-time (or link-time). The added wrapping code should be able to inspect context (function being called, thread information, etc.), read/write input variables and modify return values and output variables.

How can I do that with GCC and/or Clang?

1

There are 1 answers

0
Greg Prisament On

Take a look at instrumentation functions in GCC. From man gcc:

   -finstrument-functions
       Generate instrumentation calls for entry and exit to functions.  Just after function entry and just before function exit, the following profiling functions will be called with the address of the current function and its call site.  (On some platforms,
       "__builtin_return_address" does not work beyond the current function, so the call site information may not be available to the profiling functions otherwise.)

               void __cyg_profile_func_enter (void *this_fn,
                                              void *call_site);
               void __cyg_profile_func_exit  (void *this_fn,
                                              void *call_site);

       The first argument is the address of the start of the current function, which may be looked up exactly in the symbol table.

       This instrumentation is also done for functions expanded inline in other functions.  The profiling calls will indicate where, conceptually, the inline function is entered and exited.  This means that addressable versions of such functions must be available.  If
       all your uses of a function are expanded inline, this may mean an additional expansion of code size.  If you use extern inline in your C code, an addressable version of such functions must be provided.  (This is normally the case anyways, but if you get lucky
       and the optimizer always expands the functions inline, you might have gotten away without providing static copies.)

       A function may be given the attribute "no_instrument_function", in which case this instrumentation will not be done.  This can be used, for example, for the profiling functions listed above, high-priority interrupt routines, and any functions from which the
       profiling functions cannot safely be called (perhaps signal handlers, if the profiling routines generate output or allocate memory).