[C/C++][Linux] Tips about LD_PRELOAD

“LD_PRELOAD” is set to path of shared libraries. And those are loaded at first (even before C runtime).


One good point is, “Developer can override symbols in the stock libraries, with symbols in LD_PRELOAD-specified-libraries.
For example, ‘malloc’ can be overridden with user-defined one by using LD_PRELOAD.

And another good tip is using LD_PRELOAD with ‘__attribute__((constructor))’.
‘__attribute__((constructor))’ is GCC specific syntax for C/C++.
Functions tagged ‘__attribute__((constructor))’, are located at ‘.ctors’ section of ELF and run when shared library is loaded.
(‘__attribute__((destuctor))’ functions are located at ‘.dtors’ section and run when shared library is unloaded.)
So, functions tagged ‘__attribute__((constructor))’ in LD_PRELOAD-specified-library are executed before ‘main’ function.
It is fantastic, isn’t it?

Real example is ‘stdbuf’ of gnu coreutils.
There are two main parts in ‘stdbuf’. Here are details.

libstdbuf.so :
    libstdbuf.so has stdbuf() tagged '__attribute__((destructor))'.
    In stdbuf, modes of standard buffers - stdin, stdout, stderr - are modified.

    stdbuf puts 'libstdbuf.so' to LD_PRELOAD.
    And then, 'exec()' to main program to execute.

==> So, modes of standard buffer of main program can be changed    

Enjoy trick of LD_PRELOAD!
For more detail example, see this post


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s