Forced given function binds to specified lib on compilation / linking

I am wondering if it is possible to force the linker to use a specific function to reference when compiling / linking.

I am using the LD_PRELOAD environment variable to bind some specific functionality, but I am not that familiar with the linker, so there are some problems. I connect a standard system call open()

to add some functionality, so that when users use the system call open()

, I can collect some data. Basically, I do 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 won't work as it will cause an infinite loop ... So I'm wondering if I can get the linker to link some function to some specified dynamic link library so that it doesn't call an infinite loop. In the above example, it would be ideal if the "open ()" (2) system call was linked to the standard library.

For now, since I am setting LD_PRELOAD as:

export LD_PRELOAD=/path/to/my_open.so

      

whenever a program is loaded with a function open()

inside, the dynamic linker will link this open()

to my my_open.so. And it's the same for mine open()

: when the linker tries to bind open()

to (2), it will also try to bind that to my open()

at (1), which will result in an infinite loop.

Any idea?

+3


source to share


2 answers


You can get the original implementation open

with dlsym (RTLD_NEXT, "open")

. There is no other reliable way to achieve the original definition open

from the library LD_PRELOAD

.



It might be instructive to look at projects like fakeroot

and cwrap

to see how they handle it.

+1


source


A detailed algorithm for linking dynamic symbols can be found in man ld.so

.

ELF allows you to insert a character open@@VERSION

. This is useful to keep different libc versions at the same time. Perhaps you want to keep your own .so library in LD_LIBRARY_PATH

.



See here for details .

+2


source







All Articles