This is the mail archive of the binutils@sourceware.org mailing list for the binutils project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

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


On 07/20/2017 12:28 PM, Yubin Ruan wrote:
> Hi,
> 
> 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 function call */
>     }
> 
> Obviously, this cannot work, as it would call into a 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 infinite
> loop. In the example above, it would be perfect for the `open()'
> system call at (2) to be linked to the standard library, rather than
> the one that I hook.
> 
> As for now, because I set the LD_PRELOAD as:
> 
>     export LD_PRELOAD=/path/to/my_open.so
> 
> whenever a program that have a `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 try to link the `open()'
> at (2), it would also try to link that to my `open()' at (1),
> resulting in a infinite loop.
> 
> Any idea?

(1) Use ld's --wrap=symbol.

See the man page for details.

(2) Use libdl's dlopen().

Use dlopen to get the real open() from libc.so.6, and then
call that through the handle returned from dlsym().

-- 
Cheers,
Carlos.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]