Dynamic Linker Resolution and Interposition
About 3202 words
Many functions in Linux C/C++ programs are not compiled into the final executable. Functions such as printf, malloc, pthread_create, and dlopen usually come from external shared libraries. At startup, the dynamic linker loads these libraries into the process address space and binds function calls to their actual addresses.
Dynamic-link interposition uses this process: before the program calls a real function, it first calls our implementation with the same name. Common approaches include:
- Adjusting the shared-library search path.
- Preloading libraries with
LD_PRELOAD. - Globally preloading libraries through
/etc/ld.so.preload. - Finding the next real implementation from a wrapper with
dlsym(RTLD_NEXT, "...").
These mechanisms are often used for debugging, profiling, instrumentation, compatibility, sandboxing, and resource limits. For example, HAMi-Core's libvgpu.so uses library injection and CUDA / NVML API hooks to limit GPU memory and compute inside containers.
Static and Dynamic Linking
A C program roughly follows this path from source to execution:
source.c -> object file -> executable -> processThere are two common approaches at the linking stage.
Static Linking
Static linking copies object code from dependency libraries into the final executable:
gcc main.c -static -o appCharacteristics:
- Few external
.sodependencies at runtime. - Larger executable files.
- The program must be rebuilt when a library is updated.
- Dynamic-link interposition such as
LD_PRELOADgenerally cannot affect functions already linked statically.
Dynamic Linking
Dynamic linking does not copy all library code into the executable. Instead, the executable records which shared libraries and symbols it needs:
gcc main.c -o appAt runtime, the dynamic linker loads dependencies. One example of a dynamic linker is:
/lib64/ld-linux-x86-64.so.2Use ldd to see which shared libraries a program depends on:
ldd ./appExample output:
linux-vdso.so.1
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6
/lib64/ld-linux-x86-64.so.2What ELF Records
Linux executables and .so files usually use the ELF format. Information relevant to dynamic linking includes:
INTERP: specifies the dynamic linker path, such as/lib64/ld-linux-x86-64.so.2.NEEDED: declares shared-library dependencies, such aslibc.so.6..dynsym: the dynamic symbol table, containing symbols that need runtime resolution..plt/.got.plt: the procedure linkage table and global offset table, used for lazy function-address binding.RPATH/RUNPATH: library search paths embedded in the program.
Inspect them with:
readelf -l ./app | grep interpreter
readelf -d ./app
objdump -T ./appWhat the Dynamic Linker Does at Startup
When a dynamically linked program starts, the kernel does not transfer control directly to main. It first loads the dynamic linker specified by the ELF INTERP entry.
The approximate sequence is:
kernel execve()
-> load executable ELF
-> load interpreter ld-linux
-> ld-linux loads NEEDED libraries
-> resolve relocations
-> run init functions
-> jump to program entry
-> __libc_start_main()
-> main()The dynamic linker's main responsibilities are:
- Read the executable's dynamic section.
- Find all
DT_NEEDEDlibraries. - Load
.sofiles according to search rules. - Resolve symbols, binding functions and global variables to actual addresses.
- Execute initialization functions such as those in
.init_array. - Finally transfer control to the program entry point.
Shared-Library Search Order
When a program depends on libfoo.so, the dynamic linker must find its actual path. The order depends on the system, distribution, and ELF flags. A rough view of common priorities is:
- Load libraries specified by
LD_PRELOADfirst. - Directories specified by
LD_LIBRARY_PATH. RPATHorRUNPATHin the ELF file.- Cached paths in
/etc/ld.so.cache. - Default system directories such as
/lib,/usr/lib,/lib64, and/usr/lib64.
Observe the dynamic linker's actual search process:
LD_DEBUG=libs ./appInspect the system shared-library cache:
ldconfig -p | headNote: LD_LIBRARY_PATH and LD_PRELOAD are powerful runtime controls, suitable for debugging and targeted injection. Do not casually place them in the global environment. Misusing them in production can easily load the wrong library version.
What Are the PLT and GOT?
Suppose a program calls printf:
printf("hello\n");The compiler does not know the final runtime address of printf in libc.so.6, so the executable contains an indirect jump sequence.
A simplified view is:
call printf@plt
|
v
PLT stub reads GOT entry
|
v
actual printf address in libcOn the first call, the GOT may not contain the real address yet. The PLT jumps to the dynamic linker's resolver, which resolves printf and writes its address back to the GOT. Later calls can jump directly to that address.
This is called lazy binding.
Use an environment variable to observe binding:
LD_DEBUG=bindings ./appTo resolve every symbol at startup, set:
LD_BIND_NOW=1 ./appWhat Is Symbol Interposition?
When resolving symbols, the dynamic linker searches loaded objects in order for an implementation. If we preload a library exporting the same functions, such as malloc, printf, or open, the program may bind to our implementation first.
This is symbol interposition, also known as:
- symbol interposition
- function interposition
- hook
- preload hook
It changes the dynamic linker's symbol-resolution result rather than modifying the target program's binary.
Interposing Functions with LD_PRELOAD
First write a normal program:
// app.c
#include <stdio.h>
int main(void) {
puts("hello");
return 0;
}Compile it:
gcc app.c -o appThen write a hook library:
// hook.c
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>
typedef int (*puts_fn)(const char *);
int puts(const char *s) {
static puts_fn real_puts;
if (real_puts == NULL) {
real_puts = (puts_fn)dlsym(RTLD_NEXT, "puts");
}
real_puts("[hook] before puts");
return real_puts(s);
}Compile it as a shared library:
gcc -shared -fPIC hook.c -o libhook.so -ldlRun it:
LD_PRELOAD=$PWD/libhook.so ./appOutput:
[hook] before puts
helloSeveral things happen here:
LD_PRELOADcauses the dynamic linker to loadlibhook.sobeforelibc.so.6.- When resolving
puts, the program findsputsinlibhook.sofirst. - Our
putsusesdlsym(RTLD_NEXT, "puts")to find the next realputsimplementation. - After its own logic, the wrapper calls the real function.
What RTLD_NEXT Means
dlsym searches for a symbol in objects loaded by the dynamic linker:
void *dlsym(void *handle, const char *symbol);RTLD_NEXT is a special handle meaning:
Continue searching for the next symbol with this name in loaded objects after the current shared library.
Inside a hook, directly calling puts(s) would enter our own puts again, causing infinite recursion. RTLD_NEXT skips our implementation and finds the real one in libc.
A common pattern is:
static int (*real_open)(const char *, int, ...);
if (real_open == NULL) {
real_open = dlsym(RTLD_NEXT, "open");
}An Example of Interposing malloc
malloc is another common hook target, useful for observing memory allocation.
// malloc_hook.c
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
typedef void *(*malloc_fn)(size_t);
void *malloc(size_t size) {
static malloc_fn real_malloc;
if (real_malloc == NULL) {
real_malloc = (malloc_fn)dlsym(RTLD_NEXT, "malloc");
}
void *ptr = real_malloc(size);
fprintf(stderr, "malloc(%zu) = %p\n", size, ptr);
return ptr;
}Compile it:
gcc -shared -fPIC malloc_hook.c -o libmalloc_hook.so -ldlRun any dynamically linked program:
LD_PRELOAD=$PWD/libmalloc_hook.so ls >/dev/nullThis example can work, but a production malloc hook is much more complicated because:
fprintfmay itself callmalloc, causing recursion.- Initializing the real function pointer in a multithreaded process requires concurrency handling.
- Some internal libc symbols may not use paths that support interposition.
- Allocation functions may already run very early during initialization.
Be particularly careful when hooking fundamental library functions. There is a large gap between a simple demonstration and a production-ready implementation.
/etc/ld.so.preload
LD_PRELOAD is a process-level environment variable. It affects only the current command and its child processes.
/etc/ld.so.preload is a system-level configuration file. The dynamic linker reads it and preferentially loads the listed shared libraries.
Example file contents:
/usr/local/lib/libhook.soIts effect is similar to adding this to every dynamically linked program:
LD_PRELOAD=/usr/local/lib/libhook.soThat is also why it is dangerous:
- An incorrect path may prevent many commands from starting.
- A crash in the hook library may affect the entire system.
- When mounted at
/etc/ld.so.preloadinside a container, it affects dynamically linked processes in that container.
Systems such as HAMi normally mount their preload file into a container when it is created, rather than modifying the host's global /etc/ld.so.preload.
Interposing dlsym Itself
Many programs do not directly link to a function. They obtain its address at runtime through dlopen / dlsym.
For example:
void *handle = dlopen("libcuda.so.1", RTLD_NOW);
void *fn = dlsym(handle, "cuMemAlloc_v2");Simply exporting another cuMemAlloc_v2 may not affect this dynamic lookup path. A more comprehensive approach also hooks dlsym itself:
void *dlsym(void *handle, const char *symbol) {
if (strcmp(symbol, "cuMemAlloc_v2") == 0) {
return my_cuMemAlloc_v2;
}
return real_dlsym(handle, symbol);
}This is more complicated than an ordinary function hook because:
- A replacement
dlsymstill needs to find the realdlsym. - Initialization can easily recurse.
- Implementation details vary across libc versions and dynamic linkers.
- Symbol versions such as
dlsym@@GLIBC_2.34must be handled.
However, it covers more paths, making it useful for intercepting plugin APIs, driver APIs, and extension APIs that frameworks look up dynamically.
CUDA hook libraries such as HAMi-Core face this issue: deep-learning frameworks may obtain CUDA Driver API functions dynamically. Ordinary symbol replacement is therefore insufficient, and the dlsym path usually needs interception as well.
How HAMi Replaces dlsym
HAMi-Core's central shared library is libvgpu.so. It does not modify glibc's implementation of dlsym; it exports its own function named dlsym from libvgpu.so.
Because libvgpu.so is preloaded through LD_PRELOAD or the container's /etc/ld.so.preload, subsequent calls to dlsym in the process reach HAMi's implementation first.
The overall flow can be simplified to:
application / CUDA runtime
-> dlsym(handle, "cuMemAlloc_v2")
-> libvgpu.so::dlsym()
-> if symbol is CUDA/NVML API, return HAMi wrapper
-> otherwise call real glibc dlsym()1. Save the Real dlsym First
HAMi implements dlsym, but it still needs to call the real glibc dlsym internally. Otherwise it could neither forward ordinary symbol lookups nor find the real CUDA / NVML functions.
HAMi-Core has a global function pointer conceptually like this:
typedef void *(*fp_dlsym)(void *, const char *);
fp_dlsym real_dlsym = NULL;On the first entry into HAMi's dlsym, it tries to find the real implementation with dlvsym:
real_dlsym = dlvsym(RTLD_NEXT, "dlsym", "GLIBC_2.2.5");It avoids an ordinary dlsym(RTLD_NEXT, "dlsym") call for a simple reason: it is currently implementing dlsym, so calling it again can reenter itself and recurse.
HAMi also tries several glibc version names, for example:
GLIBC_2.2.5
GLIBC_2.17
GLIBC_2.3
GLIBC_2.4
GLIBC_2.10
GLIBC_2.18
GLIBC_2.22This supports glibc symbol versions on different architectures and distributions.
2. Open Its Own libvgpu.so
HAMi needs to find its wrapper functions in libvgpu.so, so it opens its own shared library:
char *path = getenv("CUDA_REDIRECT");
if (path != NULL && strlen(path) > 0) {
vgpulib = dlopen(path, RTLD_LAZY);
} else {
vgpulib = dlopen("/usr/local/vgpu/libvgpu.so", RTLD_LAZY);
}CUDA_REDIRECT acts as a debugging or redirection entry point: if set, libvgpu.so is loaded from that path; otherwise the default /usr/local/vgpu/libvgpu.so is used.
3. Handle RTLD_NEXT Specially
If the caller passes RTLD_NEXT:
dlsym(RTLD_NEXT, "malloc")HAMi should preserve its semantics rather than rewriting the lookup as a CUDA hook. It calls the real dlsym directly:
if (handle == RTLD_NEXT) {
return real_dlsym(RTLD_NEXT, symbol);
}The actual implementation also keeps a simple (thread id, pointer) record to detect recursive dlsym calls. If the same thread repeatedly finds the same address, HAMi treats this as possible recursive lookup and returns NULL to prevent infinite recursion.
4. Intercept the CUDA Driver API
HAMi's CUDA hooks primarily target CUDA Driver API functions beginning with cu*, such as:
cuMemAlloc_v2
cuMemAllocManaged
cuMemAllocAsync
cuLaunchKernel
cuDeviceTotalMem_v2
cuGetProcAddressWhen a symbol starts with cu, HAMi first initializes CUDA, then looks up the same symbol in libvgpu.so:
if (symbol[0] == 'c' && symbol[1] == 'u') {
if (strcmp(symbol, "cuGetExportTable") != 0) {
pthread_once(&pre_cuinit_flag, preInit);
}
void *f = real_dlsym(vgpulib, symbol);
if (f != NULL) {
return f;
}
}If libvgpu.so exports cuMemAlloc_v2, this returns HAMi's cuMemAlloc_v2 wrapper rather than the real function in NVIDIA's libcuda.so.1.
This step is central to HAMi's interception of the CUDA execution path.
5. Intercept the NVML API
nvidia-smi and many monitoring tools mainly query GPU information through NVML. HAMi also handles symbols beginning with nvml, such as:
nvmlDeviceGetMemoryInfo
nvmlDeviceGetMemoryInfo_v2Simplified logic:
if (symbol starts with "nvml") {
void *f = __dlsym_hook_section_nvml(handle, symbol);
if (f != NULL) {
return f;
}
}Thus, when nvidia-smi inside the container obtains NVML functions through dlsym, it also receives HAMi's wrappers. A wrapper can replace the physical GPU's real memory figure with the virtual memory allocated to the Pod.
6. Pass Through All Other Symbols
For symbols outside the CUDA / NVML APIs that HAMi handles, call the real dlsym directly:
return real_dlsym(handle, symbol);This minimizes effects on ordinary shared-library behavior. For example, HAMi does not deliberately replace pthread_create, malloc, or printf when applications look them up.
7. How Wrappers Call the Real CUDA Functions
After HAMi returns a wrapper address, the application's later calls enter that HAMi function. For example:
app calls cuMemAlloc_v2
-> HAMi cuMemAlloc_v2 wrapper
-> check memory quota
-> call real cuMemAlloc_v2 if allowedHow does the wrapper find the real CUDA function?
During initialization, HAMi opens the real NVIDIA driver library:
void *table = dlopen("libcuda.so.1", RTLD_NOW | RTLD_NODELETE);It then traverses its CUDA API table and finds function addresses with the real dlsym:
cuda_library_entry[i].fn_ptr =
real_dlsym(table, cuda_library_entry[i].name);If a function cannot be found in libcuda.so.1, it also tries:
real_dlsym(RTLD_NEXT, cuda_library_entry[i].name);When the wrapper ultimately calls the real function, it uses the saved function pointer instead of going through HAMi's replacement dlsym again.
8. Putting It Together in Pseudocode
HAMi's logic can be condensed into the following pseudocode:
void *dlsym(void *handle, const char *symbol) {
init_once();
if (real_dlsym == NULL) {
real_dlsym = dlvsym(RTLD_NEXT, "dlsym", "GLIBC_2.2.5");
}
if (vgpulib == NULL) {
vgpulib = dlopen("/usr/local/vgpu/libvgpu.so", RTLD_LAZY);
}
if (handle == RTLD_NEXT) {
return real_dlsym(RTLD_NEXT, symbol);
}
if (starts_with(symbol, "cu")) {
preInit();
void *wrapper = real_dlsym(vgpulib, symbol);
if (wrapper != NULL) {
return wrapper;
}
}
if (starts_with(symbol, "nvml")) {
void *wrapper = find_nvml_wrapper(symbol);
if (wrapper != NULL) {
return wrapper;
}
}
return real_dlsym(handle, symbol);
}HAMi's replacement dlsym therefore does not intercept every symbol indiscriminately. It is selective:
- CUDA Driver API: return a HAMi wrapper.
- NVML API: return a HAMi wrapper.
RTLD_NEXT: preserve its original semantics to avoid breaking other hooks.- Other ordinary symbols: forward to the real
dlsym.
This explains how HAMi remains transparent to applications. Deep-learning frameworks call CUDA / NVML in the same way, but the function addresses they receive have been replaced by HAMi's controlled entry points.
Symbol Versions and Visibility
Two further details matter for symbol resolution in real systems.
Symbol Versions
glibc and many system libraries use symbol versioning. One function name may have multiple ABI versions, for example:
memcpy@GLIBC_2.2.5
memcpy@@GLIBC_2.14@@ denotes the default version. Failing to handle versions in a hook may cause:
- The program not to bind to your implementation.
dlsymto find an unexpected version.- Crashes caused by ABI mismatches.
Inspect symbol versions with objdump -T:
objdump -T /lib/x86_64-linux-gnu/libc.so.6 | grep memcpySymbol Visibility
An external library cannot interpose every function call. Relevant factors include:
- Whether the function is exported in the dynamic symbol table.
- Whether the call occurs inside the same shared library.
- Whether compilation used
-fvisibility=hidden. - Whether the linker used
-Bsymbolic. - Whether the compiler inlined the function.
LD_PRELOAD is powerful, but it is not universal.
Secure-Execution Mode
For setuid / setgid programs, the dynamic linker enters a stricter secure-execution mode. Many environment variables are ignored or removed, including:
LD_PRELOAD
LD_LIBRARY_PATH
LD_AUDIT
LD_DEBUGThe reason is straightforward: allowing an ordinary user to interpose a root-privileged program with LD_PRELOAD would create a serious privilege-escalation vulnerability.
If LD_PRELOAD appears ineffective while debugging, check whether the target is a setuid program or runs in a restricted security context.
Common Uses
Dynamic-link interposition is not limited to attacks. Common engineering uses include:
- Debugging: log calls such as
open,connect,malloc, andpthread_create. - Profiling: count function calls and record duration and arguments.
- Compatibility: patch an old program's assumptions about paths, environments, or syscall wrappers.
- Gradual replacement: substitute selected library implementations without changing the program.
- Resource control: intercept allocation, query, submission, and other operations at the API layer.
- Observability: add tracing to third-party binaries.
There are costs as well:
- Sensitivity to ABI details and libc behavior.
- Risk of recursion, deadlocks, and crashes.
- Difficulty covering static linking, inlining, or direct syscall paths.
- Increasing maintenance costs as target-library versions change.
Differences from ptrace and eBPF
Dynamic-link interposition is only one way to observe and control programs.
| Method | Layer | Advantages | Limitations |
|---|---|---|---|
LD_PRELOAD | User-space function calls | Simple; can modify arguments and return values | Requires dynamic linking; limited coverage |
/etc/ld.so.preload | User-space process startup | Transparent to processes; useful for uniform injection | High risk and broad impact |
ptrace | Process debugging interface | Can intercept syscalls and read/write registers and memory | High overhead and intrusive |
| eBPF | Kernel observation/control points | Low overhead; suitable for system-wide observation | Awkward for changing user-space function semantics |
| seccomp | Syscall filtering | Suitable for security restrictions | Operates on syscalls, without understanding library-level semantics |
For changing library-function behavior, LD_PRELOAD is direct. For observing syscalls system-wide, eBPF is more suitable. For blocking particular syscalls, seccomp is the more natural choice.
Troubleshooting Checklist
If dynamic-link interposition does not work, check the following in order.
1. Is the Program Dynamically Linked?
file ./app
ldd ./appIf it is statically linked, LD_PRELOAD generally does not work.
2. Was the Hook Library Loaded?
LD_DEBUG=libs LD_PRELOAD=$PWD/libhook.so ./appYou can also inspect process mappings:
cat /proc/<pid>/maps | grep libhook3. Is the Symbol Exported?
nm -D libhook.so | grep ' puts'
objdump -T libhook.so | grep puts-D selects the dynamic symbol table. Only exported dynamic symbols can participate in dynamic-link resolution.
4. Do the Function Signatures Match?
The hook's signature must be ABI-compatible with the real function, especially for:
- Variadic functions such as
open,fcntl, andioctl. - Functions returning structures or complex types.
- Thread-related functions.
A signature mismatch may compile successfully but cause stack corruption, misaligned arguments, or random crashes at runtime.
5. Is Secure Mode Ignoring It?
ls -l ./appIf the setuid bit is present:
-rwsr-xr-xConsider secure-execution mode.
Summary
The core idea of dynamic-link interposition is to make the dynamic linker prefer our implementation when resolving a symbol.
The most common path is:
LD_PRELOAD / ld.so.preload
-> preload libhook.so
-> libhook.so exports same symbol
-> program calls wrapper first
-> wrapper uses dlsym(RTLD_NEXT) to call real functionIt is powerful but not universal. Remember:
- It primarily affects dynamically linked programs.
- It depends on symbol-resolution order and ABI compatibility.
dlsym(RTLD_NEXT)is a common way to call the real implementation.- Be especially careful about recursion and initialization order when hooking fundamental library functions.
- It is useful for debugging, observability, compatibility, and resource control, but should not be treated as a strong security boundary.
References:
man ld.soman dlopenman dlsymman rtld-audit