Is it possible to conditionally replace a function at runtime in C (in particular, a function in a dynamically loaded library)?
I know that you can use LD_PRELOAD or just make a function of the same name, such as:
// Silly example intercepting exit
typedef void (*exit_func)(int code);
void exit(int code)
{
exit_func orig_exit = (exit_func)dlsym(RTLD_NEXT, "exit");
NSLog(@"EXIT CALLED WITH CODE %d!!!!", code);
orig_exit(code);
}
However, is it possible to CONDITIONALLY replace a function, at runtime, after the program has loaded and is running?
if(some_condition)
{
swap_impementations(exit, my_exit);
}
Edit: This is somewhat similar to Is it possible to swap C functions? but specifically, I am trying to intercept a call to a function from a different library that was loaded by the operating system.
What this means is that, for example, were I to intercept the exit() function from stdlib, ANY call to exit() from ANYWHERE would call my implementation instead of the original, much like my example above, except controllable at runtime.
There have been suggestions of hooking the call by overwriting the original with a jump instruction, but I was hoping for something that doesn't require stomping on executable memory, like perhaps there was something I could call in the dynamic linker to "re-link" the function after the program starts and point it somewhere else?