Skip to content

Instantly share code, notes, and snippets.

@lalyos
Created December 24, 2025 07:25
Show Gist options
  • Select an option

  • Save lalyos/b58cd906e73f28426ea278266e62a595 to your computer and use it in GitHub Desktop.

Select an option

Save lalyos/b58cd906e73f28426ea278266e62a595 to your computer and use it in GitHub Desktop.
linux LD_PRELOAD demo on alpine implementing faketime

LD_PRELOAD

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.

How it works

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.

Basic usage

LD_PRELOAD=/path/to/library.so ./program

Common use cases

  • 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

Demo

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
#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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment