“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 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