I am not sure if it is even possible to do what I want to in C, but I thought I'd ask just in case.
Basically I want to modify the behavior of a library function without having to rename all calls to the function or directly edit the library.
Say there is a library that contains a function: void foo(). I would like to somehow write a function with the same interface, void foo(), which does something and then somehow calls the original foo function from the library.
For anyone familiar with CLOS, I want the equivalent of an :around method.
I was thinking there might be a way for me to write my own library that links to the original library, but somehow renames the original foo() function so it won't collide with mine.
Does anyone know if something like this is possible in C?
This is possible on some systems, under certain conditions. Platform details?
I'm working on an old-ish sparc machine running Solaris 5.9 (though I can also use a linux machine if that would work better)
On Solaris you can use the LD_PRELOAD environment variable to hook a shared object during the dynamic linking. This object can override any symbols in any other shared libraries referenced by that program.
Originally Posted by cusavior
The problem is calling the original function. If you were trying to override malloc() for instance, you need some way of calling the ACTUAL malloc(), but you can't do it through the name malloc() because you've overridden it, so you'd just be calling yourself.
Most standard C libraries expose "internal" names for some of their standard functions specifically to allow this kind of thing. Poking around on my SunOS 5.7 box, I see this:
So presumably, if you wanted to hook malloc(), you'd write a function called malloc(), do your thing, and eventually call the real _libc_malloc(). You'd compile this module as a .so file, then list it in the LD_PRELOAD variable. Any program you run will now be hooked to your wrapper function.
 | 0| 4|OBJT |GLOB |0 |3 |_libc_malloc
If you are trying to hook a function in a library which doesn't expose an internal name, it is going to be more difficult.