The Usage of LD_PRELOAD

If you set LD_PRELOAD to the path of a shared object, that file will be loaded before any other library (including the C runtime, libc.so).

With LD_PRELOAD you can give libraries precedence.
For example you can write a library which implement malloc and free. And by loading these with LD_PRELOAD, your malloc and free will be executed rather than the standard ones.

Source Code: Makefile

all: libpreload libtest test_preload


test_preload: test_preload.c
        $(CC) -ltest -L. -o test_preload test_preload.c

libtest: libtest.c
        $(CC) -c libtest.c -o libtest.o
        gcc -shared -Wl,-soname,libtest.so -o libtest.so libtest.o

libpreload: libpreload.c
        $(CC) -c libpreload.c -o libpreload.o
        gcc -shared -Wl,-soname,libpreload.so -o libpreload.so libpreload.o


.PHONY: all clean distclean install libpreload libtest test_preload
.PHONY: dummy

Source Code: test_preload.c

/* Example of a main program which will call override() provided by an library.
 */
void main(){

printf("Hello\n");
override();
}

Source Code: libtest.c

/* Example of a library:  libtest.so
 * This library provides a function override()
 */
override(){
printf("original override fun\n");
}

Source Code: libpreload.c

/* Example of a library:  libpreload.so
* This library provide a duplicated function override()
* This function will override the the same function provided by libpreload.so, if the program test_preload is executed with the following sequence:

LD_RELOAD=./libpreload.so
test_preload

*/
override(){
printf("override!\n");
}

Execution:

# ./test_preload
Hello
original override fun
# export  LD_PRELOAD=./libpreload.so
# ./test_preload
Hello
override!

留言

熱門文章