Search code examples
ccompilationlinkerbinutils

Force specified function to be linked to a specified lib when compiling/linking


I am wondering whether it is possible to force the linker to use some specified function to link to when compiling/linking.

I am using the LD_PRELOAD environment variable to hook some specified functions but I am not so familiar with linker so there are some troubles. I am hooking the standard open() system call to add some functionalities so that when users use the open() system call, I can collect some data. Basically, I am doing something like this:

int open(int fd, int flags, ...)  //(1)
{
    // add some functionalities here

    return open(...); // (2), return the original open system call
}

Obviously, this cannot work, as it would call into an infinite loop... So I am wondering whether I can force the linker to link some function to some specified dynamic library so that it would not cause an infinite loop. In the example above, it would be perfect for the "open()" system call at (2) to be linked to the standard library.

As for now, because I set the LD_PRELOAD as:

export LD_PRELOAD=/path/to/my_open.so

whenever a program that has an open() function inside is loaded, the dynamic linker would link that open() to my my_open.so. And that is the same for my open(): when the linker tries to link the open() at (2), it would also try to link that to my open() at (1), resulting in an infinite loop.

Any idea?


Solution

  • You can retrieve the original implementation of open using dlsym (RTLD_NEXT, "open"). There is no other reliable way to reach the original definition of open from an LD_PRELOAD library.

    It might be instructive to look at projects such as fakeroot and cwrap, to see how they handle this.