1dlopen(3) Library Functions Manual dlopen(3)
2
3
4
6 dlclose, dlopen, dlmopen - open and close a shared object
7
9 Dynamic linking library (libdl, -ldl)
10
12 #include <dlfcn.h>
13
14 void *dlopen(const char *filename, int flags);
15 int dlclose(void *handle);
16
17 #define _GNU_SOURCE
18 #include <dlfcn.h>
19
20 void *dlmopen(Lmid_t lmid, const char *filename, int flags);
21
23 dlopen()
24 The function dlopen() loads the dynamic shared object (shared library)
25 file named by the null-terminated string filename and returns an opaque
26 "handle" for the loaded object. This handle is employed with other
27 functions in the dlopen API, such as dlsym(3), dladdr(3), dlinfo(3),
28 and dlclose().
29
30 If filename is NULL, then the returned handle is for the main program.
31 If filename contains a slash ("/"), then it is interpreted as a (rela‐
32 tive or absolute) pathname. Otherwise, the dynamic linker searches for
33 the object as follows (see ld.so(8) for further details):
34
35 • (ELF only) If the calling object (i.e., the shared library or exe‐
36 cutable from which dlopen() is called) contains a DT_RPATH tag, and
37 does not contain a DT_RUNPATH tag, then the directories listed in
38 the DT_RPATH tag are searched.
39
40 • If, at the time that the program was started, the environment vari‐
41 able LD_LIBRARY_PATH was defined to contain a colon-separated list
42 of directories, then these are searched. (As a security measure,
43 this variable is ignored for set-user-ID and set-group-ID programs.)
44
45 • (ELF only) If the calling object contains a DT_RUNPATH tag, then the
46 directories listed in that tag are searched.
47
48 • The cache file /etc/ld.so.cache (maintained by ldconfig(8)) is
49 checked to see whether it contains an entry for filename.
50
51 • The directories /lib and /usr/lib are searched (in that order).
52
53 If the object specified by filename has dependencies on other shared
54 objects, then these are also automatically loaded by the dynamic linker
55 using the same rules. (This process may occur recursively, if those
56 objects in turn have dependencies, and so on.)
57
58 One of the following two values must be included in flags:
59
60 RTLD_LAZY
61 Perform lazy binding. Resolve symbols only as the code that
62 references them is executed. If the symbol is never referenced,
63 then it is never resolved. (Lazy binding is performed only for
64 function references; references to variables are always immedi‐
65 ately bound when the shared object is loaded.) Since glibc
66 2.1.1, this flag is overridden by the effect of the LD_BIND_NOW
67 environment variable.
68
69 RTLD_NOW
70 If this value is specified, or the environment variable
71 LD_BIND_NOW is set to a nonempty string, all undefined symbols
72 in the shared object are resolved before dlopen() returns. If
73 this cannot be done, an error is returned.
74
75 Zero or more of the following values may also be ORed in flags:
76
77 RTLD_GLOBAL
78 The symbols defined by this shared object will be made available
79 for symbol resolution of subsequently loaded shared objects.
80
81 RTLD_LOCAL
82 This is the converse of RTLD_GLOBAL, and the default if neither
83 flag is specified. Symbols defined in this shared object are
84 not made available to resolve references in subsequently loaded
85 shared objects.
86
87 RTLD_NODELETE (since glibc 2.2)
88 Do not unload the shared object during dlclose(). Consequently,
89 the object's static and global variables are not reinitialized
90 if the object is reloaded with dlopen() at a later time.
91
92 RTLD_NOLOAD (since glibc 2.2)
93 Don't load the shared object. This can be used to test if the
94 object is already resident (dlopen() returns NULL if it is not,
95 or the object's handle if it is resident). This flag can also
96 be used to promote the flags on a shared object that is already
97 loaded. For example, a shared object that was previously loaded
98 with RTLD_LOCAL can be reopened with RTLD_NOLOAD | RTLD_GLOBAL.
99
100 RTLD_DEEPBIND (since glibc 2.3.4)
101 Place the lookup scope of the symbols in this shared object
102 ahead of the global scope. This means that a self-contained ob‐
103 ject will use its own symbols in preference to global symbols
104 with the same name contained in objects that have already been
105 loaded.
106
107 If filename is NULL, then the returned handle is for the main program.
108 When given to dlsym(3), this handle causes a search for a symbol in the
109 main program, followed by all shared objects loaded at program startup,
110 and then all shared objects loaded by dlopen() with the flag
111 RTLD_GLOBAL.
112
113 Symbol references in the shared object are resolved using (in order):
114 symbols in the link map of objects loaded for the main program and its
115 dependencies; symbols in shared objects (and their dependencies) that
116 were previously opened with dlopen() using the RTLD_GLOBAL flag; and
117 definitions in the shared object itself (and any dependencies that were
118 loaded for that object).
119
120 Any global symbols in the executable that were placed into its dynamic
121 symbol table by ld(1) can also be used to resolve references in a dy‐
122 namically loaded shared object. Symbols may be placed in the dynamic
123 symbol table either because the executable was linked with the flag
124 "-rdynamic" (or, synonymously, "--export-dynamic"), which causes all of
125 the executable's global symbols to be placed in the dynamic symbol ta‐
126 ble, or because ld(1) noted a dependency on a symbol in another object
127 during static linking.
128
129 If the same shared object is opened again with dlopen(), the same ob‐
130 ject handle is returned. The dynamic linker maintains reference counts
131 for object handles, so a dynamically loaded shared object is not de‐
132 allocated until dlclose() has been called on it as many times as
133 dlopen() has succeeded on it. Constructors (see below) are called only
134 when the object is actually loaded into memory (i.e., when the refer‐
135 ence count increases to 1).
136
137 A subsequent dlopen() call that loads the same shared object with
138 RTLD_NOW may force symbol resolution for a shared object earlier loaded
139 with RTLD_LAZY. Similarly, an object that was previously opened with
140 RTLD_LOCAL can be promoted to RTLD_GLOBAL in a subsequent dlopen().
141
142 If dlopen() fails for any reason, it returns NULL.
143
144 dlmopen()
145 This function performs the same task as dlopen()—the filename and flags
146 arguments, as well as the return value, are the same, except for the
147 differences noted below.
148
149 The dlmopen() function differs from dlopen() primarily in that it ac‐
150 cepts an additional argument, lmid, that specifies the link-map list
151 (also referred to as a namespace) in which the shared object should be
152 loaded. (By comparison, dlopen() adds the dynamically loaded shared
153 object to the same namespace as the shared object from which the
154 dlopen() call is made.) The Lmid_t type is an opaque handle that
155 refers to a namespace.
156
157 The lmid argument is either the ID of an existing namespace (which can
158 be obtained using the dlinfo(3) RTLD_DI_LMID request) or one of the
159 following special values:
160
161 LM_ID_BASE
162 Load the shared object in the initial namespace (i.e., the ap‐
163 plication's namespace).
164
165 LM_ID_NEWLM
166 Create a new namespace and load the shared object in that name‐
167 space. The object must have been correctly linked to reference
168 all of the other shared objects that it requires, since the new
169 namespace is initially empty.
170
171 If filename is NULL, then the only permitted value for lmid is
172 LM_ID_BASE.
173
174 dlclose()
175 The function dlclose() decrements the reference count on the dynami‐
176 cally loaded shared object referred to by handle.
177
178 If the object's reference count drops to zero and no symbols in this
179 object are required by other objects, then the object is unloaded after
180 first calling any destructors defined for the object. (Symbols in this
181 object might be required in another object because this object was
182 opened with the RTLD_GLOBAL flag and one of its symbols satisfied a re‐
183 location in another object.)
184
185 All shared objects that were automatically loaded when dlopen() was in‐
186 voked on the object referred to by handle are recursively closed in the
187 same manner.
188
189 A successful return from dlclose() does not guarantee that the symbols
190 associated with handle are removed from the caller's address space. In
191 addition to references resulting from explicit dlopen() calls, a shared
192 object may have been implicitly loaded (and reference counted) because
193 of dependencies in other shared objects. Only when all references have
194 been released can the shared object be removed from the address space.
195
197 On success, dlopen() and dlmopen() return a non-NULL handle for the
198 loaded object. On error (file could not be found, was not readable,
199 had the wrong format, or caused errors during loading), these functions
200 return NULL.
201
202 On success, dlclose() returns 0; on error, it returns a nonzero value.
203
204 Errors from these functions can be diagnosed using dlerror(3).
205
207 For an explanation of the terms used in this section, see at‐
208 tributes(7).
209
210 ┌────────────────────────────────────────────┬───────────────┬─────────┐
211 │Interface │ Attribute │ Value │
212 ├────────────────────────────────────────────┼───────────────┼─────────┤
213 │dlopen(), dlmopen(), dlclose() │ Thread safety │ MT-Safe │
214 └────────────────────────────────────────────┴───────────────┴─────────┘
215
217 dlopen()
218 dlclose()
219 POSIX.1-2008.
220
221 dlmopen()
222 RTLD_NOLOAD
223 RTLD_NODELETE
224 GNU.
225
226 RTLD_DEEPBIND
227 Solaris.
228
230 dlopen()
231 dlclose()
232 glibc 2.0. POSIX.1-2001.
233
234 dlmopen()
235 glibc 2.3.4.
236
238 dlmopen() and namespaces
239 A link-map list defines an isolated namespace for the resolution of
240 symbols by the dynamic linker. Within a namespace, dependent shared
241 objects are implicitly loaded according to the usual rules, and symbol
242 references are likewise resolved according to the usual rules, but such
243 resolution is confined to the definitions provided by the objects that
244 have been (explicitly and implicitly) loaded into the namespace.
245
246 The dlmopen() function permits object-load isolation—the ability to
247 load a shared object in a new namespace without exposing the rest of
248 the application to the symbols made available by the new object. Note
249 that the use of the RTLD_LOCAL flag is not sufficient for this purpose,
250 since it prevents a shared object's symbols from being available to any
251 other shared object. In some cases, we may want to make the symbols
252 provided by a dynamically loaded shared object available to (a subset
253 of) other shared objects without exposing those symbols to the entire
254 application. This can be achieved by using a separate namespace and
255 the RTLD_GLOBAL flag.
256
257 The dlmopen() function also can be used to provide better isolation
258 than the RTLD_LOCAL flag. In particular, shared objects loaded with
259 RTLD_LOCAL may be promoted to RTLD_GLOBAL if they are dependencies of
260 another shared object loaded with RTLD_GLOBAL. Thus, RTLD_LOCAL is
261 insufficient to isolate a loaded shared object except in the (uncommon)
262 case where one has explicit control over all shared object
263 dependencies.
264
265 Possible uses of dlmopen() are plugins where the author of the plugin-
266 loading framework can't trust the plugin authors and does not wish any
267 undefined symbols from the plugin framework to be resolved to plugin
268 symbols. Another use is to load the same object more than once.
269 Without the use of dlmopen(), this would require the creation of
270 distinct copies of the shared object file. Using dlmopen(), this can
271 be achieved by loading the same shared object file into different
272 namespaces.
273
274 The glibc implementation supports a maximum of 16 namespaces.
275
276 Initialization and finalization functions
277 Shared objects may export functions using the
278 __attribute__((constructor)) and __attribute__((destructor)) function
279 attributes. Constructor functions are executed before dlopen()
280 returns, and destructor functions are executed before dlclose()
281 returns. A shared object may export multiple constructors and
282 destructors, and priorities can be associated with each function to
283 determine the order in which they are executed. See the gcc info pages
284 (under "Function attributes") for further information.
285
286 An older method of (partially) achieving the same result is via the use
287 of two special symbols recognized by the linker: _init and _fini. If a
288 dynamically loaded shared object exports a routine named _init(), then
289 that code is executed after loading a shared object, before dlopen()
290 returns. If the shared object exports a routine named _fini(), then
291 that routine is called just before the object is unloaded. In this
292 case, one must avoid linking against the system startup files, which
293 contain default versions of these files; this can be done by using the
294 gcc(1) -nostartfiles command-line option.
295
296 Use of _init and _fini is now deprecated in favor of the aforementioned
297 constructors and destructors, which among other advantages, permit
298 multiple initialization and finalization functions to be defined.
299
300 Since glibc 2.2.3, atexit(3) can be used to register an exit handler
301 that is automatically called when a shared object is unloaded.
302
303 History
304 These functions are part of the dlopen API, derived from SunOS.
305
307 As at glibc 2.24, specifying the RTLD_GLOBAL flag when calling
308 dlmopen() generates an error. Furthermore, specifying RTLD_GLOBAL when
309 calling dlopen() results in a program crash (SIGSEGV) if the call is
310 made from any object loaded in a namespace other than the initial
311 namespace.
312
314 The program below loads the (glibc) math library, looks up the address
315 of the cos(3) function, and prints the cosine of 2.0. The following is
316 an example of building and running the program:
317
318 $ cc dlopen_demo.c -ldl
319 $ ./a.out
320 -0.416147
321
322 Program source
323
324 #include <dlfcn.h>
325 #include <stdio.h>
326 #include <stdlib.h>
327
328 #include <gnu/lib-names.h> /* Defines LIBM_SO (which will be a
329 string such as "libm.so.6") */
330 int
331 main(void)
332 {
333 void *handle;
334 double (*cosine)(double);
335 char *error;
336
337 handle = dlopen(LIBM_SO, RTLD_LAZY);
338 if (!handle) {
339 fprintf(stderr, "%s\n", dlerror());
340 exit(EXIT_FAILURE);
341 }
342
343 dlerror(); /* Clear any existing error */
344
345 cosine = (double (*)(double)) dlsym(handle, "cos");
346
347 /* According to the ISO C standard, casting between function
348 pointers and 'void *', as done above, produces undefined results.
349 POSIX.1-2001 and POSIX.1-2008 accepted this state of affairs and
350 proposed the following workaround:
351
352 *(void **) (&cosine) = dlsym(handle, "cos");
353
354 This (clumsy) cast conforms with the ISO C standard and will
355 avoid any compiler warnings.
356
357 The 2013 Technical Corrigendum 1 to POSIX.1-2008 improved matters
358 by requiring that conforming implementations support casting
359 'void *' to a function pointer. Nevertheless, some compilers
360 (e.g., gcc with the '-pedantic' option) may complain about the
361 cast used in this program. */
362
363 error = dlerror();
364 if (error != NULL) {
365 fprintf(stderr, "%s\n", error);
366 exit(EXIT_FAILURE);
367 }
368
369 printf("%f\n", (*cosine)(2.0));
370 dlclose(handle);
371 exit(EXIT_SUCCESS);
372 }
373
375 ld(1), ldd(1), pldd(1), dl_iterate_phdr(3), dladdr(3), dlerror(3),
376 dlinfo(3), dlsym(3), rtld-audit(7), ld.so(8), ldconfig(8)
377
378 gcc info pages, ld info pages
379
380
381
382Linux man-pages 6.05 2023-07-20 dlopen(3)