1DLOPEN(3) Linux Programmer's Manual DLOPEN(3)
2
3
4
6 dlclose, dlopen, dlmopen - open and close a shared object
7
9 #include <dlfcn.h>
10
11 void *dlopen(const char *filename, int flags);
12 int dlclose(void *handle);
13
14 #define _GNU_SOURCE
15 #include <dlfcn.h>
16
17 void *dlmopen(Lmid_t lmid, const char *filename, int flags);
18
19 Link with -ldl.
20
22 dlopen()
23 The function dlopen() loads the dynamic shared object (shared library)
24 file named by the null-terminated string filename and returns an opaque
25 "handle" for the loaded object. This handle is employed with other
26 functions in the dlopen API, such as dlsym(3), dladdr(3), dlinfo(3),
27 and dlclose().
28
29 If filename is NULL, then the returned handle is for the main program.
30 If filename contains a slash ("/"), then it is interpreted as a (rela‐
31 tive or absolute) pathname. Otherwise, the dynamic linker searches for
32 the object as follows (see ld.so(8) for further details):
33
34 o (ELF only) If the calling object (i.e., the shared library or exe‐
35 cutable from which dlopen() is called) contains a DT_RPATH tag, and
36 does not contain a DT_RUNPATH tag, then the directories listed in
37 the DT_RPATH tag are searched.
38
39 o If, at the time that the program was started, the environment vari‐
40 able LD_LIBRARY_PATH was defined to contain a colon-separated list
41 of directories, then these are searched. (As a security measure,
42 this variable is ignored for set-user-ID and set-group-ID pro‐
43 grams.)
44
45 o (ELF only) If the calling object contains a DT_RUNPATH tag, then
46 the directories listed in that tag are searched.
47
48 o 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 o 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 dlopen() and dlclose() are present in glibc 2.0 and later. dlmopen()
208 first appeared in glibc 2.3.4.
209
211 For an explanation of the terms used in this section, see at‐
212 tributes(7).
213
214 ┌────────────────────────────────────────────┬───────────────┬─────────┐
215 │Interface │ Attribute │ Value │
216 ├────────────────────────────────────────────┼───────────────┼─────────┤
217 │dlopen(), dlmopen(), dlclose() │ Thread safety │ MT-Safe │
218 └────────────────────────────────────────────┴───────────────┴─────────┘
219
221 POSIX.1-2001 describes dlclose() and dlopen(). The dlmopen() function
222 is a GNU extension.
223
224 The RTLD_NOLOAD, RTLD_NODELETE, and RTLD_DEEPBIND flags are GNU exten‐
225 sions; the first two of these flags are also present on Solaris.
226
228 dlmopen() and namespaces
229 A link-map list defines an isolated namespace for the resolution of
230 symbols by the dynamic linker. Within a namespace, dependent shared
231 objects are implicitly loaded according to the usual rules, and symbol
232 references are likewise resolved according to the usual rules, but such
233 resolution is confined to the definitions provided by the objects that
234 have been (explicitly and implicitly) loaded into the namespace.
235
236 The dlmopen() function permits object-load isolation—the ability to
237 load a shared object in a new namespace without exposing the rest of
238 the application to the symbols made available by the new object. Note
239 that the use of the RTLD_LOCAL flag is not sufficient for this purpose,
240 since it prevents a shared object's symbols from being available to any
241 other shared object. In some cases, we may want to make the symbols
242 provided by a dynamically loaded shared object available to (a subset
243 of) other shared objects without exposing those symbols to the entire
244 application. This can be achieved by using a separate namespace and
245 the RTLD_GLOBAL flag.
246
247 The dlmopen() function also can be used to provide better isolation
248 than the RTLD_LOCAL flag. In particular, shared objects loaded with
249 RTLD_LOCAL may be promoted to RTLD_GLOBAL if they are dependencies of
250 another shared object loaded with RTLD_GLOBAL. Thus, RTLD_LOCAL is in‐
251 sufficient to isolate a loaded shared object except in the (uncommon)
252 case where one has explicit control over all shared object dependen‐
253 cies.
254
255 Possible uses of dlmopen() are plugins where the author of the plugin-
256 loading framework can't trust the plugin authors and does not wish any
257 undefined symbols from the plugin framework to be resolved to plugin
258 symbols. Another use is to load the same object more than once. With‐
259 out the use of dlmopen(), this would require the creation of distinct
260 copies of the shared object file. Using dlmopen(), this can be
261 achieved by loading the same shared object file into different name‐
262 spaces.
263
264 The glibc implementation supports a maximum of 16 namespaces.
265
266 Initialization and finalization functions
267 Shared objects may export functions using the __attribute__((construc‐
268 tor)) and __attribute__((destructor)) function attributes. Constructor
269 functions are executed before dlopen() returns, and destructor func‐
270 tions are executed before dlclose() returns. A shared object may ex‐
271 port multiple constructors and destructors, and priorities can be asso‐
272 ciated with each function to determine the order in which they are exe‐
273 cuted. See the gcc info pages (under "Function attributes") for fur‐
274 ther information.
275
276 An older method of (partially) achieving the same result is via the use
277 of two special symbols recognized by the linker: _init and _fini. If a
278 dynamically loaded shared object exports a routine named _init(), then
279 that code is executed after loading a shared object, before dlopen()
280 returns. If the shared object exports a routine named _fini(), then
281 that routine is called just before the object is unloaded. In this
282 case, one must avoid linking against the system startup files, which
283 contain default versions of these files; this can be done by using the
284 gcc(1) -nostartfiles command-line option.
285
286 Use of _init and _fini is now deprecated in favor of the aforementioned
287 constructors and destructors, which among other advantages, permit mul‐
288 tiple initialization and finalization functions to be defined.
289
290 Since glibc 2.2.3, atexit(3) can be used to register an exit handler
291 that is automatically called when a shared object is unloaded.
292
293 History
294 These functions are part of the dlopen API, derived from SunOS.
295
297 As at glibc 2.24, specifying the RTLD_GLOBAL flag when calling dl‐
298 mopen() generates an error. Furthermore, specifying RTLD_GLOBAL when
299 calling dlopen() results in a program crash (SIGSEGV) if the call is
300 made from any object loaded in a namespace other than the initial name‐
301 space.
302
304 The program below loads the (glibc) math library, looks up the address
305 of the cos(3) function, and prints the cosine of 2.0. The following is
306 an example of building and running the program:
307
308 $ cc dlopen_demo.c -ldl
309 $ ./a.out
310 -0.416147
311
312 Program source
313
314 #include <stdio.h>
315 #include <stdlib.h>
316 #include <dlfcn.h>
317 #include <gnu/lib-names.h> /* Defines LIBM_SO (which will be a
318 string such as "libm.so.6") */
319 int
320 main(void)
321 {
322 void *handle;
323 double (*cosine)(double);
324 char *error;
325
326 handle = dlopen(LIBM_SO, RTLD_LAZY);
327 if (!handle) {
328 fprintf(stderr, "%s\n", dlerror());
329 exit(EXIT_FAILURE);
330 }
331
332 dlerror(); /* Clear any existing error */
333
334 cosine = (double (*)(double)) dlsym(handle, "cos");
335
336 /* According to the ISO C standard, casting between function
337 pointers and 'void *', as done above, produces undefined results.
338 POSIX.1-2001 and POSIX.1-2008 accepted this state of affairs and
339 proposed the following workaround:
340
341 *(void **) (&cosine) = dlsym(handle, "cos");
342
343 This (clumsy) cast conforms with the ISO C standard and will
344 avoid any compiler warnings.
345
346 The 2013 Technical Corrigendum 1 to POSIX.1-2008 improved matters
347 by requiring that conforming implementations support casting
348 'void *' to a function pointer. Nevertheless, some compilers
349 (e.g., gcc with the '-pedantic' option) may complain about the
350 cast used in this program. */
351
352 error = dlerror();
353 if (error != NULL) {
354 fprintf(stderr, "%s\n", error);
355 exit(EXIT_FAILURE);
356 }
357
358 printf("%f\n", (*cosine)(2.0));
359 dlclose(handle);
360 exit(EXIT_SUCCESS);
361 }
362
364 ld(1), ldd(1), pldd(1), dl_iterate_phdr(3), dladdr(3), dlerror(3),
365 dlinfo(3), dlsym(3), rtld-audit(7), ld.so(8), ldconfig(8)
366
367 gcc info pages, ld info pages
368
370 This page is part of release 5.12 of the Linux man-pages project. A
371 description of the project, information about reporting bugs, and the
372 latest version of this page, can be found at
373 https://www.kernel.org/doc/man-pages/.
374
375
376
377Linux 2021-03-22 DLOPEN(3)