Based on The Linux Programming Interface Chapter 41 (Fundamentals of Shared Libraries) and Chapter 42 (Advanced Features of Shared Libraries).

Shared Libraries#


1. Header vs Static vs Shared Library (TLPI Ch 41)#

C libraries (eg. glibc) separate compile-time declarations from link-time and runtime binaries.

ArtifactExtension & Example PathRolePhase
Header.h (/usr/include/dlfcn.h)Plain-text function signatures, types, and macrosCompile time (gcc -c)
Static Library.a (libc.a)Archive of .o object files copied directly into the executableLink time (gcc -static)
Shared Library.so (/lib/x86_64-linux-gnu/libc.so.6)Precompiled Position-Independent machine code loaded once into memory and shared across processesRuntime (ld.so dynamic linker)

Building and Inspecting Shared Libraries#

$ gcc -fPIC -shared -Wall -o libfoo.so foo.c
$ ldd <binary>
$ nm -D libfoo.so
  • -fPIC: Generate Position-Independent Code so the library can be mapped at any virtual address
  • -shared: Produce a shared object (.so) instead of an executable requiring main
  • ldd: List shared libraries required by a binary and their resolved paths
  • nm -D: Inspect exported dynamic symbols in a .so file

2. Dynamic Loading API: dlopen & dlsym (TLPI Ch 42)#

glibc API for loading shared libraries into memory and resolving symbol addresses dynamically at runtime rather than at program startup (man 3 dlopen, man 3 dlsym). The RTLD_ prefix stands for Run-Time Link-Dynamic.

#include <dlfcn.h>

void *dlopen(const char *filename, int flags);
void *dlsym(void *restrict handle, const char *restrict symbol);
int   dlclose(void *handle);
char *dlerror(void);
  • Linker Flag: Link with -ldl for portability across older glibc releases (merged into libc.so.6 since glibc 2.34)

1. dlopen: Opening a Library#

  • <filename>: Path or soname of the .so file to open (NULL returns a handle to the main program’s global symbol scope)
  • <flags> (resolution mode required):
    • RTLD_LAZY: Resolve function symbols lazily on first call
    • RTLD_NOW: Resolve all undefined symbols immediately before dlopen returns
    • RTLD_GLOBAL: Make loaded symbols available for symbol resolution of subsequently loaded libraries
  • Return Value: Opaque handle pointer on success, or NULL on failure (inspect reason via dlerror())

2. dlsym: Resolving Function and Variable Addresses#

  • <handle>: Target scope for symbol lookup — either a handle returned by dlopen or one of the following pseudo-handles (requires #define _GNU_SOURCE):
    • RTLD_DEFAULT: Search using the default library load order starting from the first loaded object
    • RTLD_NEXT: Search starting from the library loaded after the current one. Used inside an interposed wrapper function to find and delegate to the original implementation.
  • <symbol>: Null-terminated symbol name string (eg. "cuMemAlloc_v2")
  • Return Value: Virtual memory address (void *) of the symbol. Because no type metadata is stored, the caller must know and cast to the exact function pointer signature.

3. dlerror: Shared Error Buffer Inspection and Reset#

dlopen, dlsym, dlvsym, and dlclose all share a single per-thread error buffer. Calling dlerror() both 1) returns the most recent error message string and 2) clears that internal buffer (returning NULL if no error is pending).

void *handle = dlopen("libcuda.so.1", RTLD_LAZY);
if (!handle) {
    // Entered only when dlopen fails; if dlopen succeeds, an older stale error may still sit in the buffer
    fprintf(stderr, "dlopen failed: %s\n", dlerror());
    exit(EXIT_FAILURE);
}

dlerror(); // Step 1: Clear any stale error left in the shared buffer
typedef int (*cuInit_fn)(unsigned int);
cuInit_fn fn = (cuInit_fn) dlsym(handle, "cuInit"); // Step 2: Look up symbol address

char *err = dlerror(); // Step 3: Check whether Step 2 recorded an error
if (err != NULL) {
    fprintf(stderr, "dlsym failed: %s\n", err);
    exit(EXIT_FAILURE);
}

int rc = fn(0);
dlclose(handle);

Because a valid symbol address can legitimately be 0 (NULL) and an earlier unchecked call may have left a stale message in the shared buffer, POSIX specifies the three-step sequence (dlerror() reset -> dlsym() -> dlerror() check) rather than testing fn == NULL.


3. Symbol Interposition: Pairing LD_PRELOAD with RTLD_NEXT#

The dynamic linker (ld-linux.so) resolves symbols using the first loaded library (1st in load order) that defines them. Symbol interposition pairs two mechanisms: LD_PRELOAD injects a wrapper .so into the 1st slot to intercept calls, and dlsym(RTLD_NEXT, ...) inside that wrapper locates the displaced original function in the 2nd slot to delegate the real work.

App calls malloc(64)
  │
  ▼  [1st in load order — injected via LD_PRELOAD or /etc/ld.so.preload]
libhook.so : malloc()          <-- Interposed wrapper runs first
  │
  │  dlsym(RTLD_NEXT, "malloc") --> "Search libraries loaded AFTER libhook.so"
  ▼  [2nd in load order — original shared library]
libc.so.6  : malloc()          <-- Delegates to original glibc implementation

1. Preload Injection Mechanisms#

MechanismScopeCharacteristics
LD_PRELOADProcess environment variableConvenient for single commands ($ LD_PRELOAD=./libhook.so ./app). Can be cleared by child processes and ignored on setuid binaries
/etc/ld.so.preloadSystem/container-wide fileForces ld.so to preload listed .so paths into the 1st slot of every process. Cannot be bypassed by clearing environ (used by container GPU limiters such as HAMi Device Plugin server.go#L1603-L1608)

2. Function Wrapping with LD_PRELOAD + RTLD_NEXT#

#define _GNU_SOURCE
#include <dlfcn.h>
#include <unistd.h>

typedef void *(*malloc_fn)(size_t);

void *malloc(size_t size) {
    static malloc_fn real_malloc = NULL; // Caches address of displaced original malloc
    if (real_malloc == NULL) {
        real_malloc = (malloc_fn) dlsym(RTLD_NEXT, "malloc");
    }

    void *p = real_malloc(size);
    write(STDERR_FILENO, "[hook] malloc called\n", 21);
    return p;
}
$ gcc -fPIC -shared -Wall -o libhook.so hook.c -ldl
$ LD_PRELOAD=./libhook.so ls
  • Infinite Recursion Hazard: Never call printf inside a malloc hook. Because glibc’s printf internally calls malloc to allocate its output buffer, calling printf triggers infinite recursion (malloc -> printf -> malloc) and crashes with a stack overflow. Use allocation-free system calls such as write(2) instead.

3. dlvsym and Hooking dlsym Itself#

When a runtime (eg. CUDA libcudart.so) resolves driver symbols dynamically via dlsym(handle, "cuMemAlloc_v2") rather than direct symbol imports, ordinary function wrappers are bypassed and dlsym itself must be interposed.

Calling dlsym(RTLD_NEXT, "dlsym") inside the fake dlsym triggers infinite recursion back into the 1st-slot fake dlsym. Use dlvsym to bootstrap the real dlsym pointer instead (eg. HAMi-core libvgpu.c#L55-L61):

#define _GNU_SOURCE
#include <dlfcn.h>

void *dlvsym(void *restrict handle, const char *restrict symbol,
             const char *restrict version);
  • dlvsym: Looks up a symbol matching both name and glibc symbol version string (eg. "GLIBC_2.2.5" on x86_64, "GLIBC_2.17" on aarch64).
  • Because its function name differs from dlsym, it is not intercepted by the fake dlsym and safely retrieves libc.so.6’s original dlsym address.
$ objdump -T /lib/x86_64-linux-gnu/libc.so.6 | grep ' dlsym$'