LD_PRELOAD is an environment variable in Linux/Unix systems that tells the dynamic linker
to load specific shared libraries before any other libraries when running a program.
When you run a program, the dynamic linker loads the required shared libraries.
LD_PRELOAD forces certain libraries to be loaded first, allowing you to override functions from other libraries.
LD_PRELOAD=/path/to/library.so ./program
- Function interception/hooking - Replace standard library functions with custom versions (my_malloc.so)
- Debugging and testing - Inject debugging code or mock functions (Electric Fence memory debugger)
- Performance analysis - Wrap functions to measure performance
- Security testing - Test how programs behave with modified library behavior
Lets use create a faketime shared lib, which replaces the os call. I'll use an alpine container to compile/test.
docker run -it --rm alpine
setup the env
apk add cmd:gcc musl-dev
cat > faketime.c <<EOF
#include <time.h>
time_t time(time_t *t) {
time_t fake_time = 1234567890; // Always return this timestamp
if (t) *t = fake_time;
return fake_time;
}
EOF
gcc -shared -fPIC faketime.c -o faketime.so
date
LD_PRELOAD=./faketime.so date