Suppose I want to completely take over the open() system call, maybe to wrap the actual syscall and perform some logging. One way to do this is to use LD_PRELOAD to load a (user-made) shared object library that takes over the open() entry point.
The user-made open() routine then obtains the pointer to the glibc function open()
by dlsym()
ing it, and calling it.
The solution proposed above is a dynamic solution, however. Suppose I want to link my own open()
wrapper statically. How would I do it? I guess the mechanism is the same, but I also guess there will be a symbol clash between the user-defined open()
and the libc open()
.
Please share any other techniques to achieve the same goal.
You can use the wrap feature provided by
ld
. Fromman ld
:So you just have to use the prefix
__wrap_
for your wrapper function and__real_
when you want to call the real function. A simple example is:malloc_wrapper.c
:Test application
testapp.c
:Then compile the application:
The output of the resulting application will be:
Symbols are resolved by the linker in the order you list them on the command line so if you listed your library before the standard library you'd have precidence. For gcc you'd need to specify
This way your libraries would be searched and found first.