9
votes

Currently coding on Windows with VS2005 (but wouldn't mind knowing if there are options for other compilers and platforms. I'm most interested in OSX as an alternative platform.) I have a C (no C++) program and I'd like to do the following...

Given a function, say...

int MyFunction(int myparam)
{
   // Entry point.
   ...
   // Exit point.
   return 1;
}

I'd like to put a snippet of code at the entry point and at the exit point. BUT, I'd rather not have to modify the 100's of functions that are already out there. Is there a way to define function entry and exit code that the compiler will inject for all my functions without having to modify them all?

Most solutions I've found or tried will require me to edit every single function, which is a lot of work. I figure someone else must have hit something like this already and solved it. I can't be unique in this request I suspect.

4
Unless you're using this for some form of debugging or logging, this strikes me as a bad idea. - Brian
Seconded - in the off chance anyone still codes with vs. - quixver

4 Answers

10
votes

It's Microsoft-specific, but you can hook into the _penter and _pexit functions to do something when entering and exiting a function -- you'll have to compile your project with some special flags.

There's a little bit of a tutorial here, and you can find a few more results on how to use them on Google. Also, this blog post goes into some detail on the assembly that you need to do to avoid messing up the stack on entry and exit.

8
votes

GCC has the -finstrument-functions flag which allows you to define two functions that will be called at the beginning and end of each function call:

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

You're looking for something called aspect oriented programming or AOP.

This isn't something that's supported natively in C (or C++). There are some library based implementations listed on the linked page for C (though I don't know how mature / useful these are)

0
votes

OpenWatcom C and C++ compilers have -ee and -ep parameters for that:

-ee           call epilogue hook routine
-ep[=<num>]   call prologue hook routine with <num> stack bytes available

They will cause the compiler to emit calls to __EPI and __PRO user-defined hook routines.

There is also

-en           emit routine names in the code segment

that will emit the function name into the object code as a string of characters just before the function prologue sequence is generated. May be useful for the __PRO routine.

More information in these and other compiler options can be found in the C/C++ user guide available among other manuals at http://openwatcom.org/index.php/Manuals