The runtime linker provides an additional level of flexibility by enabling you to introduce new objects during process initialization.
The environment variable LD_PRELOAD
can be initialized to a shared object or relocatable object file name, or a string of file names separated by white
space. These objects are loaded after the dynamic executable and before any dependencies. These objects are assigned world search scope, and global symbol visibility.
$ LD_PRELOAD=./newstuff.so.1 prog |
The dynamic executable prog is loaded, followed by the shared object newstuff.so.1, and then by the dependencies defined within prog.
The order in which these objects are processed can be displayed using ldd(1):
$ LD_PRELOAD=./newstuff.so.1 ldd prog ./newstuff.so.1 => ./newstuff.so libc.so.1 => /usr/lib/libc.so.1 |
In another example the preloading is a little more complex and time consuming.
$ LD_PRELOAD="./foo.o ./bar.o" prog |
The runtime linker first link-edits the relocatable objects foo.o and bar.o to generate a shared object that is maintained in memory. This memory image is then inserted between the dynamic executable and its dependencies in the same manner as the shared object newstuff.so.1 was preloaded in the previous example. Again, the order in which these objects are processed can be displayed with ldd(1):
$ LD_PRELOAD="./foo.o ./bar.o" ldd prog ./foo.o => ./foo.o ./bar.o => ./bar.o libc.so.1 => /usr/lib/libc.so.1 |
These mechanisms of inserting an object after a dynamic executable take the concept of interposition to another level. You can use these mechanisms to experiment with a new implementation of a function that resides in a standard shared object. If you preload an object containing this function, the object interposes on the original. Thus the old functionality can be completely hidden with the new preloaded version.
Another use of preloading is to augment a function that resides in a standard shared object. The intention is to interpose the new symbol on the original, enabling the new function to carry out some additional processing while calling through to the original function. This mechanism requires either a symbol alias that is to be associated with the original function or the ability to look up the original symbol's address.