Language/C&C++ 2010.12.13 17:05
"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
|[Linux][C/C++] strange pipe issue in linux in 'ylisp'. (0)||2011.02.09|
|[C/C++][Linux] Avoiding making zombie process (0)||2010.12.14|
|[C/C++][Linux] Tips about LD_PRELOAD (0)||2010.12.13|
|[C/C++][linux] redirect standard io with pipe in code. (0)||2010.12.10|
|[Linux][C/C++] 'select' function - glibc bug?? (0)||2010.11.19|
|[C/C++] Encapsulation tip in C. (0)||2010.11.12|