Movatterモバイル変換


[0]ホーム

URL:


man7.org > Linux >man-pages

Linux/UNIX system programming training


dlopen(3) — Linux manual page

NAME |LIBRARY |SYNOPSIS |DESCRIPTION |RETURN VALUE |ATTRIBUTES |STANDARDS |HISTORY |NOTES |BUGS |EXAMPLES |SEE ALSO |COLOPHON

dlopen(3)                Library Functions Manualdlopen(3)

NAME        top

       dlclose, dlopen, dlmopen - open and close a shared object

LIBRARY        top

       Dynamic linking library (libdl,-ldl)

SYNOPSIS        top

#include <dlfcn.h>void *dlopen(const char *path, intflags);int dlclose(void *handle);#define _GNU_SOURCE#include <dlfcn.h>void *dlmopen(Lmid_tlmid, const char *path, intflags);

DESCRIPTION        top

dlopen()       The functiondlopen() loads the dynamic shared object (shared       library) file named by the null-terminated stringpath and returns       an opaque "handle" for the loaded object.  This handle is employed       with other functions in the dlopen API, such asdlsym(3),dladdr(3),dlinfo(3), anddlclose().       Ifpath is NULL, then the returned handle is for the main program.       Ifpath contains a slash ("/"), then it is interpreted as a       (relative or absolute) pathname.  Otherwise, the dynamic linker       searches for the object as follows (seeld.so(8) for further       details):       •  (ELF only) If the calling object (i.e., the shared library or          executable from whichdlopen() 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          variableLD_LIBRARY_PATHwas 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 byldconfig(8)) is          checked to see whether it contains an entry forpath.       •  The directories/lib and/usr/lib are searched (in that order).       If the object specified bypath 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.)       One of the following two values must be included inflags: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 theLD_BIND_NOWenvironment              variable.RTLD_NOW              If this value is specified, or the environment variableLD_BIND_NOWis set to a nonempty string, all undefined              symbols in the shared object are resolved beforedlopen()              returns.  If this cannot be done, an error is returned.       Zero or more of the following values may also be ORed inflags: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 ofRTLD_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 duringdlclose().              Consequently, the object's static and global variables are              not reinitialized if the object is reloaded withdlopen()              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 withRTLD_LOCALcan be              reopened withRTLD_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.       Ifpath is NULL, then the returned handle is for the main program.       When given todlsym(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 bydlopen()       with the flagRTLD_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 withdlopen() using theRTLD_GLOBALflag; 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 byld(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 becauseld(1)       noted a dependency on a symbol in another object during static       linking.       If the same shared object is opened again withdlopen(), the same       object handle is returned.  The dynamic linker maintains reference       counts for object handles, so a dynamically loaded shared object       is not deallocated untildlclose() has been called on it as many       times asdlopen() 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 subsequentdlopen() call that loads the same shared object withRTLD_NOWmay force symbol resolution for a shared object earlier       loaded withRTLD_LAZY.  Similarly, an object that was previously       opened withRTLD_LOCALcan be promoted toRTLD_GLOBALin a       subsequentdlopen().       Ifdlopen() fails for any reason, it returns NULL.dlmopen()       This function performs the same task asdlopen()—thepath andflags arguments, as well as the return value, are the same, except       for the differences noted below.       Thedlmopen() function differs fromdlopen() primarily in that it       accepts an additional argument,lmid, that specifies the link-map       list (also referred to as anamespace) 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 thedlopen() call is made.)  TheLmid_t type is an       opaque handle that refers to a namespace.       Thelmid argument is either the ID of an existing namespace (which       can be obtained using thedlinfo(3)RTLD_DI_LMIDrequest) 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.       Ifpath is NULL, then the only permitted value forlmid isLM_ID_BASE.dlclose()       The functiondlclose() decrements the reference count on the       dynamically loaded shared object referred to byhandle.       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 theRTLD_GLOBALflag       and one of its symbols satisfied a relocation in another object.)       All shared objects that were automatically loaded whendlopen()       was invoked on the object referred to byhandle are recursively       closed in the same manner.       A successful return fromdlclose() does not guarantee that the       symbols associated withhandle are removed from the caller's       address space.  In addition to references resulting from explicitdlopen() 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        top

       On success,dlopen() anddlmopen() 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 usingdlerror(3).

ATTRIBUTES        top

       For an explanation of the terms used in this section, seeattributes(7).       ┌──────────────────────────────────────┬───────────────┬─────────┐       │InterfaceAttributeValue│       ├──────────────────────────────────────┼───────────────┼─────────┤       │dlopen(),dlmopen(),dlclose()       │ Thread safety │ MT-Safe │       └──────────────────────────────────────┴───────────────┴─────────┘

STANDARDS        top

dlopen()dlclose()              POSIX.1-2008.dlmopen()RTLD_NOLOADRTLD_NODELETE              GNU.RTLD_DEEPBIND              Solaris.

HISTORY        top

dlopen()dlclose()              glibc 2.0.  POSIX.1-2001.dlmopen()              glibc 2.3.4.

NOTES        top

dlmopen() and namespaces       A link-map list defines an isolated namespace for the resolution       of symbols by the dynamic linker.  Within a namespace, dependent       shared objects are implicitly loaded according to the usual rules,       and symbol references are likewise resolved according to the usual       rules, but such resolution is confined to the definitions provided       by the objects that have been (explicitly and implicitly) loaded       into the namespace.       Thedlmopen() function permits object-load isolation—the ability       to load a shared object in a new namespace without exposing the       rest of the application to the symbols made available by the new       object.  Note that the use of theRTLD_LOCALflag is not       sufficient for this purpose, since it prevents a shared object's       symbols from being available toany other shared object.  In some       cases, we may want to make the symbols provided by a dynamically       loaded shared object available to (a subset of) other shared       objects without exposing those symbols to the entire application.       This can be achieved by using a separate namespace and theRTLD_GLOBALflag.       Thedlmopen() function also can be used to provide better       isolation than theRTLD_LOCALflag.  In particular, shared objects       loaded withRTLD_LOCALmay be promoted toRTLD_GLOBALif they are       dependencies of another shared object loaded withRTLD_GLOBAL.       Thus,RTLD_LOCALis insufficient to isolate a loaded shared object       except in the (uncommon) case where one has explicit control over       all shared object dependencies.       Possible uses ofdlmopen() are plugins where the author of the       plugin-loading framework can't trust the plugin authors and does       not wish any undefined symbols from the plugin framework to be       resolved to plugin symbols.  Another use is to load the same       object more than once.  Without the use ofdlmopen(), this would       require the creation of distinct copies of the shared object file.       Usingdlmopen(), this can be achieved by loading the same shared       object file into different namespaces.       The glibc implementation supports a maximum of 16 namespaces.Initialization and finalization functions       Shared objects may export functions using the__attribute__((constructor))and__attribute__((destructor))       function attributes.  Constructor functions are executed beforedlopen() returns, and destructor functions are executed beforedlclose() returns.  A shared object may export multiple       constructors and destructors, and priorities can be associated       with each function to determine the order in which they are       executed.  See thegccinfo pages (under "Function attributes")       for further information.       An older method of (partially) achieving the same result is via       the use of two special symbols recognized by the linker:_initand_fini.  If a dynamically loaded shared object exports a routine       named_init(), then that code is executed after loading a shared       object, beforedlopen() returns.  If the shared object exports a       routine named_fini(), then that routine is called just before the       object is unloaded.  In this case, one must avoid linking against       the system startup files, which contain default versions of these       files; this can be done by using thegcc(1)-nostartfiles command-       line option.       Use of_initand_finiis now deprecated in favor of the       aforementioned constructors and destructors, which among other       advantages, permit multiple initialization and finalization       functions to be defined.       Since glibc 2.2.3,atexit(3) can be used to register an exit       handler that is automatically called when a shared object is       unloaded.History       These functions are part of the dlopen API, derived from SunOS.

BUGS        top

       As at glibc 2.24, specifying theRTLD_GLOBALflag when callingdlmopen() generates an error.  Furthermore, specifyingRTLD_GLOBAL       when callingdlopen() results in a program crash (SIGSEGV) if the       call is made from any object loaded in a namespace other than the       initial namespace.

EXAMPLES        top

       The program below loads the (glibc) math library, looks up the       address of thecos(3) function, and prints the cosine of 2.0.  The       following is an example of building and running the program:           $cc dlopen_demo.c -ldl;           $./a.out;           -0.416147Program 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 = (typeof(double (double)) *) dlsym(handle, "cos");           /* According to the ISO C standard, casting between function              pointers and 'void *', as done above, produces undefined results.              POSIX.1-2001 and POSIX.1-2008 accepted this state of affairs and              proposed the following workaround:                  *(void **) &cosine = dlsym(handle, "cos");              This (clumsy) cast conforms with the ISO C standard and will              avoid any compiler warnings.              The 2013 Technical Corrigendum 1 to POSIX.1-2008 improved matters              by requiring that conforming implementations support casting              'void *' to a function pointer.  Nevertheless, some compilers              (e.g., gcc with the '-pedantic' option) may complain about the              cast used in this program. */           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        top

ld(1),ldd(1),pldd(1),dl_iterate_phdr(3),dladdr(3),dlerror(3),dlinfo(3),dlsym(3),rtld-audit(7),ld.so(8),ldconfig(8)       gcc info pages, ld info pages

COLOPHON        top

       This page is part of theman-pages (Linux kernel and C library       user-space interface documentation) project.  Information about       the project can be found at        ⟨https://www.kernel.org/doc/man-pages/⟩.  If you have a bug report       for this manual page, see       ⟨https://git.kernel.org/pub/scm/docs/man-pages/man-pages.git/tree/CONTRIBUTING⟩.       This page was obtained from the tarball man-pages-6.15.tar.gz       fetched from       ⟨https://mirrors.edge.kernel.org/pub/linux/docs/man-pages/⟩ on       2025-08-11.  If you discover any rendering problems in this HTML       version of the page, or you believe there is a better or more up-       to-date source for the page, or you have corrections or       improvements to the information in this COLOPHON (which isnot       part of the original manual page), send a mail to       man-pages@man7.orgLinux man-pages 6.15            2025-05-17dlopen(3)

Pages that refer to this page:dbpmda(1)pldd(1)pmcd(1)mmap(2)uselib(2)vfork(2)atexit(3)backtrace(3)dladdr(3)dlerror(3)dlinfo(3)dl_iterate_phdr(3)dlsym(3)lttng-ust(3)lttng-ust-dl(3)pmda(3)sd-journal(3)rtld-audit(7)ld.so(8)mount(8)



HTML rendering created 2025-09-06 byMichael Kerrisk, author ofThe Linux Programming Interface.

For details of in-depthLinux/UNIX system programming training courses that I teach, lookhere.

Hosting byjambit GmbH.

Cover of TLPI


[8]ページ先頭

©2009-2025 Movatter.jp