Skip to main content
Be Bitwise
CSystems Programming in C

Part ofSystems Programming Companion, week 8

Shared Libraries

Every non-trivial C program reaches for shared libraries. Call printf and the code isn't sitting inside your executable — it lives in libc.so, hauled into your process at runtime by the dynamic linker. Once you understand how shared libraries actually work, doors open: plugin systems, function interception, much smaller binaries.

Static vs Shared Libraries

A static library (.a) gets baked straight into the executable at link time. Every program ends up with its own private copy of the library code.

A shared library (.so on Linux, .dylib on macOS) loads into memory once and gets shared across every process using it. Saves RAM, saves disk, and means you can patch a library without rebuilding every program that links against it.

bash
# Static linking
gcc program.c -static -o program # ~1 MB with all of libc
# Shared linking (default)
gcc program.c -o program # ~15 KB, links to libc.so

Creating a Shared Library

c
// mathlib.h
#ifndef MATHLIB_H
#define MATHLIB_H
int add(int a, int b);
int multiply(int a, int b);
#endif
// mathlib.c
#include "mathlib.h"
int add(int a, int b) { return a + b; }
int multiply(int a, int b) { return a * b; }

Compile as a shared library:

bash
gcc -shared -fPIC -o libmath.so mathlib.c
  • -shared: Produce a shared library
  • -fPIC: Generate Position-Independent Code (required for shared libraries)

Use it:

bash
gcc program.c -L. -lmath -o program
LD_LIBRARY_PATH=. ./program
Key Concept

Position-Independent Code (PIC) uses relative addressing instead of absolute. That's what lets the library load at any virtual address the loader feels like picking. Without PIC, the linker would have to chase down and patch every address reference — slow on its own, and worse: it'd prevent the same physical pages being shared across processes.

dlopen and dlsym: Runtime Loading

dlopen and dlsym let you load libraries and resolve symbols at runtime. They're the foundation under every plugin system you'll ever use:

c
#include <dlfcn.h>
#include <stdio.h>
int main() {
void *handle = dlopen("./libmath.so", RTLD_LAZY);
if (!handle) {
fprintf(stderr, "dlopen: %s\n", dlerror());
return 1;
}
// Look up the "add" function
int (*add_fn)(int, int) = dlsym(handle, "add");
char *error = dlerror();
if (error) {
fprintf(stderr, "dlsym: %s\n", error);
dlclose(handle);
return 1;
}
printf("3 + 4 = %d\n", add_fn(3, 4));
dlclose(handle);
return 0;
}

Compile with -ldl to pull in the dynamic-loader library:

bash
gcc plugin_loader.c -ldl -o plugin_loader

Symbol Resolution

At startup, the dynamic linker resolves symbols in a fixed pecking order:

  1. The executable itself
  2. Libraries named in LD_PRELOAD
  3. Libraries listed in DT_NEEDED entries (in order, then their own dependencies)
  4. Libraries loaded with dlopen (if RTLD_GLOBAL was used)

Order matters because the first match wins. Two libraries defining the same symbol? Whichever loaded first owns the name.

For function calls, that search can happen lazily, on the first call rather than at startup. Your code calls a small stub in the PLT (procedure linkage table), which jumps through a slot in the GOT (global offset table). Until the function is resolved, that slot points back into the PLT, which hands off to the dynamic linker:

Many distributions now link with -z now (full RELRO), which does all of this at startup and then makes the GOT read-only. Attackers love a writable GOT, since overwriting one slot redirects every later call to that function.

LD_PRELOAD Tricks

LD_PRELOAD injects a library ahead of everything else in the load order, which lets you intercept and override pretty much any function:

c
// Override malloc to track allocations
// track_alloc.c
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
static void *(*real_malloc)(size_t) = NULL;
static atomic_size_t total_allocated = 0; // malloc runs on every thread
// dlsym may itself allocate. Serve those few early requests from here.
static _Alignas(16) char bootstrap[4096];
static size_t boot_used = 0;
static _Thread_local int in_dlsym = 0;
void *malloc(size_t size) {
if (!real_malloc) {
if (in_dlsym) {
size = (size + 15) & ~(size_t)15;
if (boot_used + size > sizeof(bootstrap)) return NULL;
void *p = bootstrap + boot_used;
boot_used += size;
return p;
}
in_dlsym = 1;
real_malloc = dlsym(RTLD_NEXT, "malloc");
in_dlsym = 0;
}
atomic_fetch_add_explicit(&total_allocated, size, memory_order_relaxed);
return real_malloc(size);
}
void free(void *p) {
static void (*real_free)(void *) = NULL;
// Never hand bootstrap memory to the real free
if ((char *)p >= bootstrap && (char *)p < bootstrap + sizeof(bootstrap)) return;
if (!real_free) real_free = dlsym(RTLD_NEXT, "free");
real_free(p);
}
// Called when the library is unloaded
__attribute__((destructor))
void report(void) {
fprintf(stderr, "Total allocated: %zu bytes\n", (size_t)total_allocated);
}
bash
gcc -shared -fPIC -o track_alloc.so track_alloc.c -ldl
LD_PRELOAD=./track_alloc.so ./any_program

RTLD_NEXT is what makes the trick work: it finds the next definition of malloc further down the load order — the actual libc implementation — so the wrapper can chain through to it. The bootstrap buffer covers a real trap: if dlsym allocates while real_malloc is still NULL, a naive wrapper calls itself forever. A production version would also wrap calloc, realloc and friends.

Building a Plugin System

A plugin system worth using starts with a contract every plugin agrees to implement:

c
// plugin_api.h
#ifndef PLUGIN_API_H
#define PLUGIN_API_H
typedef struct {
const char *name;
const char *version;
int (*init)(void);
void (*process)(const char *input, char *output, size_t output_size);
void (*cleanup)(void);
} Plugin;
// Every plugin must export this function
Plugin *plugin_get_info(void);
#endif

A plugin implementation:

c
// uppercase_plugin.c
#include "plugin_api.h"
#include <ctype.h>
#include <string.h>
static int init(void) {
return 0; // success
}
static void process(const char *input, char *output, size_t output_size) {
size_t i;
for (i = 0; i < output_size - 1 && input[i]; i++) {
output[i] = toupper(input[i]);
}
output[i] = '\0';
}
static void cleanup(void) {}
static Plugin plugin = {
.name = "uppercase",
.version = "1.0",
.init = init,
.process = process,
.cleanup = cleanup,
};
Plugin *plugin_get_info(void) {
return &plugin;
}

The host application loads plugins:

c
#include <dlfcn.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include "plugin_api.h"
#define MAX_PLUGINS 32
typedef struct {
void *handle;
Plugin *plugin;
} LoadedPlugin;
int load_plugins(const char *dir, LoadedPlugin *plugins, int max) {
DIR *d = opendir(dir);
if (!d) return 0;
int count = 0;
struct dirent *entry;
while ((entry = readdir(d)) && count < max) {
if (strstr(entry->d_name, ".so") == NULL) continue;
char path[512];
snprintf(path, sizeof(path), "%s/%s", dir, entry->d_name);
void *handle = dlopen(path, RTLD_LAZY);
if (!handle) continue;
Plugin *(*get_info)(void) = dlsym(handle, "plugin_get_info");
if (!get_info) { dlclose(handle); continue; }
Plugin *p = get_info();
if (p->init() != 0) { dlclose(handle); continue; }
plugins[count].handle = handle;
plugins[count].plugin = p;
count++;
}
closedir(d);
return count;
}

Apache modules, Python's C extension modules, VST audio plugins — all of them are built on this exact shape, just dressed up differently.

Symbol Visibility

By default a shared library exports every function it has. Visibility attributes let you decide what stays public:

c
// Only export functions marked with EXPORT
#define EXPORT __attribute__((visibility("default")))
#define HIDDEN __attribute__((visibility("hidden")))
EXPORT int public_function(void) { return 42; }
HIDDEN int internal_function(void) { return 0; }

Compile with -fvisibility=hidden to hide everything by default, then sprinkle EXPORT on the bits you want public. The symbol table shrinks, load times drop.