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