TExcelTAD
Home › Build Fundamentals: From Source to Binary › Dynamic Loading (dlopen)

Dynamic Loading (dlopen)

So far the loader decided which libraries to load, from the NEEDED list, before main ran. A program can also load a shared library while it runs, by name, and look up functions in it by string. That is how plugins work: audio effects, editor extensions, database drivers, game mods and the Python interpreter's C extensions are all shared libraries opened with dlopen (or LoadLibrary on Windows).

The API, declared in <dlfcn.h>:

Function Does
void *dlopen(const char *file, int flags) load a library, returns a handle or NULL
void *dlsym(void *handle, const char *name) address of a symbol in it, or NULL
int dlclose(void *handle) release it (unloaded when the last handle closes)
char *dlerror(void) a readable message for the last failure

A plugin host

Each plugin exports a function with an agreed name and signature, here const char *plugin_transform(const char *). The host doesn't know the plugins at build time; it gets their paths as command-line arguments:

bash · try it yourself
mkdir -p plug && cd plug
cat > host.c <<'SRC'
#include <dlfcn.h>
#include <stdio.h>

typedef const char *(*transform_fn)(const char *);

int main(int argc, char **argv) {
    for (int i = 1; i < argc; i++) {
        void *lib = dlopen(argv[i], RTLD_NOW | RTLD_LOCAL);
        if (!lib) { printf("load failed: %s\n", dlerror()); continue; }
        transform_fn fn = (transform_fn)dlsym(lib, "plugin_transform");
        if (!fn) { printf("bad plugin: %s\n", dlerror()); dlclose(lib); continue; }
        printf("%-16s -> %s\n", argv[i], fn("build systems"));
        dlclose(lib);
    }
    return 0;
}
SRC
cat > upper.c <<'SRC'
#include <ctype.h>
static char buf[64];
const char *plugin_transform(const char *s) {
    int i = 0;
    for (; s[i] && i < 63; i++) buf[i] = (char)toupper((unsigned char)s[i]);
    buf[i] = 0;
    return buf;
}
SRC
cat > reverse.c <<'SRC'
#include <string.h>
static char buf[64];
const char *plugin_transform(const char *s) {
    size_t n = strlen(s);
    for (size_t i = 0; i < n && i < 63; i++) buf[i] = s[n - 1 - i];
    buf[n < 63 ? n : 63] = 0;
    return buf;
}
SRC
printf 'int unrelated(void) { return 1; }\n' > broken.c
for p in upper reverse broken; do gcc -fPIC -shared $p.c -o $p.so; done
gcc host.c -o host
./host ./upper.so ./reverse.so ./broken.so ./missing.so
./upper.so       -> BUILD SYSTEMS
./reverse.so     -> smetsys dliub
bad plugin: ./broken.so: undefined symbol: plugin_transform
load failed: ./missing.so: cannot open shared object file: No such file or directory

Things to notice:

  • The host was linked with no reference to any plugin; readelf -d host would show only libc.so.6. Adding a plugin means dropping a new .so in place, no rebuild.
  • The paths start with ./. A name without a slash (upper.so) is searched like a NEEDED entry (rpath, LD_LIBRARY_PATH, the cache, system directories), not in the current directory.
  • Both plugins define plugin_transform and a static char buf. RTLD_LOCAL keeps each library's symbols private to its handle, so they don't clash. RTLD_GLOBAL would make them available to libraries loaded later, which plugins rarely want.
  • Since glibc 2.34 the dl* functions live in libc itself. On older systems (and some other Unix systems) link the host with -ldl.

Lazy versus immediate binding

RTLD_NOW resolves every undefined symbol of the plugin at dlopen time, so a plugin that needs a function nobody provides fails at load. RTLD_LAZY defers function lookups until the first call, so the same plugin loads fine and the program dies later, at the first call, in the middle of work:

bash · try it yourself
mkdir -p plug && cd plug
cat > needy.c <<'SRC'
void host_log(const char *msg);           /* expected from the host */
const char *plugin_transform(const char *s) { host_log("called"); return s; }
SRC
gcc -fPIC -shared needy.c -o needy.so
cat > load.c <<'SRC'
#include <dlfcn.h>
#include <stdio.h>
int main(void) {
    void *now = dlopen("./needy.so", RTLD_NOW);
    printf("RTLD_NOW : %s\n", now ? "loaded" : dlerror());
    void *lazy = dlopen("./needy.so", RTLD_LAZY);
    printf("RTLD_LAZY: %s\n", lazy ? "loaded" : dlerror());
    const char *(*fn)(const char *) = (const char *(*)(const char *))dlsym(lazy, "plugin_transform");
    fflush(stdout);
    printf("result: %s\n", fn("first call"));
    return 0;
}
SRC
gcc load.c -o load && ./load
echo "exit status: $?"
RTLD_NOW : ./needy.so: undefined symbol: host_log
RTLD_LAZY: loaded
./load: symbol lookup error: ./needy.so: undefined symbol: host_log
exit status: 127

The loader kills the process with a symbol lookup error and exit status 127; the fflush makes sure the earlier lines were written before that. Prefer RTLD_NOW for plugins: an incompatible plugin is rejected with a clear message instead of crashing later. If plugins should call back into the host (like host_log here), link the host with -rdynamic (-Wl,--export-dynamic) so its global functions are visible to libraries it loads, or better, pass the plugin a table of function pointers.

Plugin interfaces in practice

A real plugin system needs more than one function name:

  • A version check. Export something like int plugin_api_version(void) and refuse plugins built for another version of the interface. The ABI concerns from Sonames, rpath & the Loader apply, but nobody enforces them for you.
  • A single entry point returning a struct of function pointers (const struct plugin *plugin_entry(void)), so the host calls dlsym once and the plugin's internals stay hidden (-fvisibility=hidden).
  • C linkage. For plugins written in C++, declare the entry point extern "C", or dlsym needs the mangled name.
  • Unloading is hard. dlclose while any pointer into the library (a callback, a string, an object's vtable) is still in use crashes later. Many programs never unload plugins.

Test yourself

Why does dlopen("upper.so", …) (no slash) not load a file from the current directory?

  1. dlopen needs an absolute path
  2. A name without a slash is searched like a NEEDED entry: rpath, LD_LIBRARY_PATH, the cache, system directories
  3. Plugins must be in /usr/lib
  4. It does load it

A plugin needs a function nobody provides. What happens with RTLD_NOW?

  1. It loads and crashes on first call
  2. dlopen fails immediately with an 'undefined symbol' message
  3. The function is created automatically
  4. The program exits silently

What does RTLD_LOCAL do?

  1. Loads from the local directory
  2. Keeps the library's symbols private, so they aren't used to resolve later libraries
  3. Makes the library static
  4. Disables dlsym