dlopen(3)

๐Ÿฆ‹ dlopen(3) โ€” open and close a shared object ๐Ÿฆ‹

Manual page: dlopen(3) from the Library Functions Manual. Okay bestie, this is libdl and it's giving โœจdynamic-linker main character energyโœจ. No cap, this one is a whole vibe. Let's go ๐Ÿ’….

โœจ NAME โœจ

dlclose, dlopen, dlmopen โ€” open and close a shared object. Periodt.

๐Ÿ’– LIBRARY ๐Ÿ’–

Dynamic linking library (libdl, -ldl). That's the whole squad right there ๐Ÿซถ.

๐ŸŽ€ SYNOPSIS ๐ŸŽ€

#include <dlfcn.h>

void *dlopen(const char *path, int flags);
int dlclose(void *handle);

#define _GNU_SOURCE
#include <dlfcn.h>

void *dlmopen(Lmid_t lmid, const char *path, int flags);

๐ŸŒธ DESCRIPTION ๐ŸŒธ

dlopen() ๐Ÿซถ

Okay so the function dlopen() loads the dynamic shared object (shared library) file named by the null-terminated string path and returns an opaque "handle" for the loaded object. This handle is employed with other functions in the dlopen API, such as dlsym(3), dladdr(3), dlinfo(3), and dlclose(). Literally the friend group of this API.

If path is NULL, then the returned handle is for the main program. If path contains a slash ("/"), then it is interpreted as a (relative or absolute) pathname. Otherwise, the dynamic linker searches for the object as follows (see ld.so(8) for further details):

  • (ELF only) If the calling object (i.e., the shared library or executable from which dlopen() is called) contains a DT_RPATH tag, and does not contain a DT_RUNPATH tag, then the directories listed in the DT_RPATH tag are searched.
  • If, at the time that the program was started, the environment variable LD_LIBRARY_PATH was defined to contain a colon-separated list of directories, then these are searched. (As a security measure, this variable is ignored for set-user-ID and set-group-ID programs.)
  • (ELF only) If the calling object contains a DT_RUNPATH tag, then the directories listed in that tag are searched.
  • The cache file /etc/ld.so.cache (maintained by ldconfig(8)) is checked to see whether it contains an entry for path.
  • The directories /lib and /usr/lib are searched (in that order).

If the object specified by path has dependencies on other shared objects, then these are also automatically loaded by the dynamic linker using the same rules. (This process may occur recursively, if those objects in turn have dependencies, and so on.) Not me explaining recursion but here we are ๐Ÿ˜ญ.

One of the following two values must be included in flags:

  • RTLD_LAZY โ€” Perform lazy binding. Resolve symbols only as the code that references them is executed. If the symbol is never referenced, then it is never resolved. (Lazy binding is performed only for function references; references to variables are always immediately bound when the shared object is loaded.) Since glibc 2.1.1, this flag is overridden by the effect of the LD_BIND_NOW environment variable.
  • RTLD_NOW โ€” If this value is specified, or the environment variable LD_BIND_NOW is set to a nonempty string, all undefined symbols in the shared object are resolved before dlopen() returns. If this cannot be done, an error is returned.

Zero or more of the following values may also be ORed in flags:

  • RTLD_GLOBAL โ€” The symbols defined by this shared object will be made available for symbol resolution of subsequently loaded shared objects.
  • RTLD_LOCAL โ€” This is the converse of RTLD_GLOBAL, and the default if neither flag is specified. Symbols defined in this shared object are not made available to resolve references in subsequently loaded shared objects.
  • RTLD_NODELETE (since glibc 2.2) โ€” Do not unload the shared object during dlclose(). Consequently, the object's static and global variables are not reinitialized if the object is reloaded with dlopen() at a later time.
  • RTLD_NOLOAD (since glibc 2.2) โ€” Don't load the shared object. This can be used to test if the object is already resident (dlopen() returns NULL if it is not, or the object's handle if it is resident). This flag can also be used to promote the flags on a shared object that is already loaded. For example, a shared object that was previously loaded with RTLD_LOCAL can be reopened with RTLD_NOLOAD | RTLD_GLOBAL.
  • RTLD_DEEPBIND (since glibc 2.3.4) โ€” Place the lookup scope of the symbols in this shared object ahead of the global scope. This means that a self-contained object will use its own symbols in preference to global symbols with the same name contained in objects that have already been loaded.

If path is NULL, then the returned handle is for the main program. When given to dlsym(3), this handle causes a search for a symbol in the main program, followed by all shared objects loaded at program startup, and then all shared objects loaded by dlopen() with the flag RTLD_GLOBAL.

Symbol references in the shared object are resolved using (in order): symbols in the link map of objects loaded for the main program and its dependencies; symbols in shared objects (and their dependencies) that were previously opened with dlopen() using the RTLD_GLOBAL flag; and definitions in the shared object itself (and any dependencies that were loaded for that object).

Any global symbols in the executable that were placed into its dynamic symbol table by ld(1) can also be used to resolve references in a dynamically loaded shared object. Symbols may be placed in the dynamic symbol table either because the executable was linked with the flag "-rdynamic" (or, synonymously, "--export-dynamic"), which causes all of the executable's global symbols to be placed in the dynamic symbol table, or because ld(1) noted a dependency on a symbol in another object during static linking.

If the same shared object is opened again with dlopen(), the same object handle is returned. The dynamic linker maintains reference counts for object handles, so a dynamically loaded shared object is not deallocated until dlclose() has been called on it as many times as dlopen() has succeeded on it. Constructors (see below) are called only when the object is actually loaded into memory (i.e., when the reference count increases to 1).

A subsequent dlopen() call that loads the same shared object with RTLD_NOW may force symbol resolution for a shared object earlier loaded with RTLD_LAZY. Similarly, an object that was previously opened with RTLD_LOCAL can be promoted to RTLD_GLOBAL in a subsequent dlopen().

If dlopen() fails for any reason, it returns NULL.

dlmopen() ๐ŸŒˆ

This function performs the same task as dlopen()โ€”the path and flags arguments, as well as the return value, are the same, except for the differences noted below.

The dlmopen() function differs from dlopen() primarily in that it accepts an additional argument, lmid, that specifies the link-map list (also referred to as a namespace) in which the shared object should be loaded. (By comparison, dlopen() adds the dynamically loaded shared object to the same namespace as the shared object from which the dlopen() call is made.) The Lmid_t type is an opaque handle that refers to a namespace.

The lmid argument is either the ID of an existing namespace (which can be obtained using the dlinfo(3) RTLD_DI_LMID request) or one of the following special values:

  • LM_ID_BASE โ€” Load the shared object in the initial namespace (i.e., the application's namespace).
  • LM_ID_NEWLM โ€” Create a new namespace and load the shared object in that namespace. The object must have been correctly linked to reference all of the other shared objects that it requires, since the new namespace is initially empty.

If path is NULL, then the only permitted value for lmid is LM_ID_BASE.

dlclose() ๐Ÿ’…

The function dlclose() decrements the reference count on the dynamically loaded shared object referred to by handle.

If the object's reference count drops to zero and no symbols in this object are required by other objects, then the object is unloaded after first calling any destructors defined for the object. (Symbols in this object might be required in another object because this object was opened with the RTLD_GLOBAL flag and one of its symbols satisfied a relocation in another object.)

All shared objects that were automatically loaded when dlopen() was invoked on the object referred to by handle are recursively closed in the same manner.

A successful return from dlclose() does not guarantee that the symbols associated with handle are removed from the caller's address space. In addition to references resulting from explicit dlopen() calls, a shared object may have been implicitly loaded (and reference counted) because of dependencies in other shared objects. Only when all references have been released can the shared object be removed from the address space.

๐Ÿ”ฅ RETURN VALUE ๐Ÿ”ฅ

On success, dlopen() and dlmopen() return a non-NULL handle for the loaded object. On error (file could not be found, was not readable, had the wrong format, or caused errors during loading), these functions return NULL.

On success, dlclose() returns 0; on error, it returns a nonzero value.

Errors from these functions can be diagnosed using dlerror(3).

๐Ÿ‘‘ ATTRIBUTES ๐Ÿ‘‘

For an explanation of the terms used in this section, see attributes(7).

  • Interface: dlopen(), dlmopen(), dlclose() โ€” Attribute: Thread safety โ€” Value: MT-Safe

๐Ÿ“œ STANDARDS ๐Ÿ“œ

  • dlopen(), dlclose() โ€” POSIX.1-2008.
  • dlmopen(), RTLD_NOLOAD, RTLD_NODELETE โ€” GNU.
  • RTLD_DEEPBIND โ€” Solaris.

๐Ÿ•ฐ๏ธ HISTORY ๐Ÿ•ฐ๏ธ

  • dlopen(), dlclose() โ€” glibc 2.0. POSIX.1-2001.
  • dlmopen() โ€” glibc 2.3.4.

๐ŸŒ€ dlmopen() and namespaces ๐ŸŒ€

Okay so bestie, a link-map list โ€” that's the thing โ€” defines an isolated namespace for how the dynamic linker figures out symbols. Inside one namespace, dependent shared objects get loaded implicitly according to the usual rules, and symbol references get resolved according to the usual rules tooโ€ฆ but โœจ here's the twist โœจ that resolution stays confined to the definitions provided by the objects that have been (explicitly and implicitly) loaded into that namespace. No sneaking out, no peeking in. ๐Ÿ’…

So dlmopen() lets you do object-load isolation โ€” the ability to load a shared object in a new namespace without exposing the rest of the application to the symbols that new object brings to the party. And ngl, using the RTLD_LOCAL flag is not enough for this, because it stops a shared object's symbols from being available to any other shared object. Sometimes you wanna make the symbols from a dynamically loaded shared object available to (a subset of) other shared objects without showing them off to the entire application. The way to do that? A separate namespace plus the RTLD_GLOBAL flag. ๐Ÿซถ

dlmopen() also serves up better isolation than RTLD_LOCAL. Lowkey the tea: shared objects loaded with RTLD_LOCAL may be promoted to RTLD_GLOBAL if they're dependencies of another shared object loaded with RTLD_GLOBAL. So RTLD_LOCAL is insufficient to isolate a loaded shared object โ€” except in the (uncommon) case where you have explicit control over all shared object dependencies. ๐Ÿ˜ญ

Possible uses of dlmopen()? Plugins โ€” where the author of the plugin-loading framework can't trust the plugin authors and doesn't want any undefined symbols from the plugin framework getting resolved to plugin symbols. Another use: loading the same object more than once. Without dlmopen(), you'd have to make distinct copies of the shared object file. With dlmopen(), you just load the same shared object file into different namespaces. Iconic. ๐Ÿ‘‘

Heads up: the glibc implementation supports a maximum of 16 namespaces. That's the whole budget, bestie. ๐ŸŽ€

๐ŸŒฑ Initialization and finalization functions ๐ŸŒฑ

Shared objects can export functions using the __attribute__((constructor)) and __attribute__((destructor)) function attributes. Constructor functions run before dlopen() returns, and destructor functions run before dlclose() returns. A shared object may export multiple constructors and destructors, and priorities can be attached to each function to decide the order they get executed in. Peep the gcc info pages (under "Function attributes") for more. ๐Ÿ“–

There's also an older method that gets you (partially) the same result: two special symbols the linker recognizes, _init and _fini. If a dynamically loaded shared object exports a routine named _init(), that code is executed after loading the shared object and before dlopen() returns. If the shared object exports a routine named _fini(), that routine is called just before the object is unloaded. In this case you gotta avoid linking against the system startup files, because they contain default versions of these things โ€” do that with the gcc(1) -nostartfiles command-line option. ๐Ÿงš

Use of _init and _fini is now deprecated in favor of the constructors and destructors above, which, among other perks, let you define multiple initialization and finalization functions. Let the old ways rest, babe. ๐Ÿ’œ

Since glibc 2.2.3, atexit(3) can be used to register an exit handler that gets automatically called when a shared object is unloaded. ๐ŸŒธ

๐Ÿ“œ History ๐Ÿ“œ

These functions are part of the dlopen API, derived from SunOS. Ancestry! ๐ŸŒˆ


๐Ÿ’€ BUGS ๐Ÿ’€

As at glibc 2.24, specifying the RTLD_GLOBAL flag when calling dlmopen() generates an error. And that's not even the worst part โ€” specifying RTLD_GLOBAL when calling dlopen() results in a program crash (SIGSEGV) if the call is made from any object loaded in a namespace other than the initial namespace. Not the vibe. Be careful out there fr fr. ๐Ÿ˜ญ๐Ÿ’…


โœจ EXAMPLES โœจ

The program below loads the (glibc) math library, looks up the address of the cos(3) function, and prints the cosine of 2.0. Here's how you build and run it:

$ cc dlopen_demo.c -ldl;
$ ./a.out;
-0.416147

๐ŸŽ€ Program source ๐ŸŽ€

#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>

#include <gnu/lib-names.h>  /* Defines LIBM_SO (which will be a
                               string such as "libm.so.6") */
int
main(void)
{
    void *handle;
    typeof(double (double)) *cosine;
    char *error;

    handle = dlopen(LIBM_SO, RTLD_LAZY);
    if (!handle) {
        fprintf(stderr, "%s\n", dlerror());
        exit(EXIT_FAILURE);
    }

    dlerror();    /* Clear any existing error */

    cosine = dlsym(handle, "cos");

    /* The 2013 Technical Corrigendum 1 to POSIX.1-2008
       required that conforming implementations support
       converting 'void *' to a function pointer.  */

    error = dlerror();
    if (error != NULL) {
        fprintf(stderr, "%s\n", error);
        exit(EXIT_FAILURE);
    }

    printf("%f\n", (*cosine)(2.0));
    dlclose(handle);
    exit(EXIT_SUCCESS);
}

๐Ÿ‘€ SEE ALSO ๐Ÿ‘€

Also: the gcc info pages, and the ld info pages. ๐Ÿซถ


okay that's the whole page bestie, you ate it UP ๐Ÿ’…โœจ This lil masterpiece is from Linux man-pages 6.20, dated 2026-05-16, and it lives at dlopen(3) โ€” go forth and dynamically link something, you gorgeous main character. ๐ŸŽ€๐Ÿฆ‹๐Ÿ’–

๐Ÿ“ฆ where this page comes from
  • arch rolling: man-pages 6.20-1 ยท BSD-2-Clause AND BSD-3-Clause AND BSD-4.3TAHOE AND BSD-4-Clause-UC AND GPL-1.0-or-later AND GPL-2.0-only AND GPL-2.0-or-later AND GPL-3.0-or-later AND LGPL-3.0-linking-exception AND LGPL-3.0-or-later AND LicenseRef-Public-Domain AND LicenseRef-UltraPermissive AND Linux-man-pages-1-para AND Linux-man-pages-copyleft AND Linux-man-pages-copyleft-2-para AND Linux-man-pages-copyleft-var AND MIT AND Spencer-94
  • nixpkgs unstable: man-pages 6.20
  • ๐Ÿ“œ the page's license: GPL-2.0-or-later
  • ๐Ÿ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms