1 /* Load a shared object at runtime, relocate it, and run its initializer.
2 Copyright (C) 1996-2007, 2009, 2010, 2011 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, write to the Free
17 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
28 #include <sys/mman.h> /* Check whether MAP_COPY is defined. */
29 #include <sys/param.h>
30 #include <bits/libc-lock.h>
34 #include <sysdep-cancel.h>
40 extern ElfW(Addr) _dl_sysdep_start (void **start_argptr,
41 void (*dl_main) (const ElfW(Phdr) *phdr,
43 ElfW(Addr) *user_entry,
45 weak_extern (BP_SYM (_dl_sysdep_start))
47 extern int __libc_multiple_libcs; /* Defined in init-first.c. */
49 /* We must be carefull not to leave us in an inconsistent state. Thus we
50 catch any error and re-raise it after cleaning up. */
56 /* This is the caller of the dlopen() function. */
57 const void *caller_dlopen;
58 /* This is the caller if _dl_open(). */
59 const void *caller_dl_open;
63 /* Original parameters to the program and the current environment. */
71 add_to_global (struct link_map *new)
73 struct link_map **new_global;
74 unsigned int to_add = 0;
77 /* Count the objects we have to put in the global scope. */
78 for (cnt = 0; cnt < new->l_searchlist.r_nlist; ++cnt)
79 if (new->l_searchlist.r_list[cnt]->l_global == 0)
82 /* The symbols of the new objects and its dependencies are to be
83 introduced into the global scope that will be used to resolve
84 references from other dynamically-loaded objects.
86 The global scope is the searchlist in the main link map. We
87 extend this list if necessary. There is one problem though:
88 since this structure was allocated very early (before the libc
89 is loaded) the memory it uses is allocated by the malloc()-stub
90 in the ld.so. When we come here these functions are not used
91 anymore. Instead the malloc() implementation of the libc is
92 used. But this means the block from the main map cannot be used
93 in an realloc() call. Therefore we allocate a completely new
94 array the first time we have to add something to the locale scope. */
96 struct link_namespaces *ns = &GL(dl_ns)[new->l_ns];
97 if (ns->_ns_global_scope_alloc == 0)
99 /* This is the first dynamic object given global scope. */
100 ns->_ns_global_scope_alloc
101 = ns->_ns_main_searchlist->r_nlist + to_add + 8;
102 new_global = (struct link_map **)
103 malloc (ns->_ns_global_scope_alloc * sizeof (struct link_map *));
104 if (new_global == NULL)
106 ns->_ns_global_scope_alloc = 0;
108 _dl_signal_error (ENOMEM, new->l_libname->name, NULL,
109 N_("cannot extend global scope"));
113 /* Copy over the old entries. */
114 ns->_ns_main_searchlist->r_list
115 = memcpy (new_global, ns->_ns_main_searchlist->r_list,
116 (ns->_ns_main_searchlist->r_nlist
117 * sizeof (struct link_map *)));
119 else if (ns->_ns_main_searchlist->r_nlist + to_add
120 > ns->_ns_global_scope_alloc)
122 /* We have to extend the existing array of link maps in the
124 struct link_map **old_global
125 = GL(dl_ns)[new->l_ns]._ns_main_searchlist->r_list;
126 size_t new_nalloc = ((ns->_ns_global_scope_alloc + to_add) * 2);
128 new_global = (struct link_map **)
129 malloc (new_nalloc * sizeof (struct link_map *));
130 if (new_global == NULL)
133 memcpy (new_global, old_global,
134 ns->_ns_global_scope_alloc * sizeof (struct link_map *));
136 ns->_ns_global_scope_alloc = new_nalloc;
137 ns->_ns_main_searchlist->r_list = new_global;
139 if (!RTLD_SINGLE_THREAD_P)
140 THREAD_GSCOPE_WAIT ();
145 /* Now add the new entries. */
146 unsigned int new_nlist = ns->_ns_main_searchlist->r_nlist;
147 for (cnt = 0; cnt < new->l_searchlist.r_nlist; ++cnt)
149 struct link_map *map = new->l_searchlist.r_list[cnt];
151 if (map->l_global == 0)
154 ns->_ns_main_searchlist->r_list[new_nlist++] = map;
157 atomic_write_barrier ();
158 ns->_ns_main_searchlist->r_nlist = new_nlist;
164 dl_open_worker (void *a)
166 struct dl_open_args *args = a;
167 const char *file = args->file;
168 int mode = args->mode;
169 struct link_map *call_map = NULL;
171 /* Check whether _dl_open() has been called from a valid DSO. */
172 if (__check_caller (args->caller_dl_open,
173 allow_libc|allow_libdl|allow_ldso) != 0)
174 _dl_signal_error (0, "dlopen", NULL, N_("invalid caller"));
176 /* Determine the caller's map if necessary. This is needed in case
177 we have a DST, when we don't know the namespace ID we have to put
178 the new object in, or when the file name has no path in which
179 case we need to look along the RUNPATH/RPATH of the caller. */
180 const char *dst = strchr (file, '$');
181 if (dst != NULL || args->nsid == __LM_ID_CALLER
182 || strchr (file, '/') == NULL)
184 const void *caller_dlopen = args->caller_dlopen;
186 /* We have to find out from which object the caller is calling.
187 By default we assume this is the main application. */
188 call_map = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
191 for (Lmid_t ns = 0; ns < GL(dl_nns); ++ns)
192 for (l = GL(dl_ns)[ns]._ns_loaded; l != NULL; l = l->l_next)
193 if (caller_dlopen >= (const void *) l->l_map_start
194 && caller_dlopen < (const void *) l->l_map_end
196 || _dl_addr_inside_object (l, (ElfW(Addr)) caller_dlopen)))
198 assert (ns == l->l_ns);
204 if (args->nsid == __LM_ID_CALLER)
207 /* In statically linked apps there might be no loaded object. */
208 if (call_map == NULL)
209 args->nsid = LM_ID_BASE;
212 args->nsid = call_map->l_ns;
216 assert (_dl_debug_initialize (0, args->nsid)->r_state == RT_CONSISTENT);
218 /* Load the named object. */
219 struct link_map *new;
220 args->map = new = _dl_map_object (call_map, file, lt_loaded, 0,
221 mode | __RTLD_CALLMAP, args->nsid);
223 /* If the pointer returned is NULL this means the RTLD_NOLOAD flag is
224 set and the object is not already loaded. */
227 assert (mode & RTLD_NOLOAD);
231 if (__builtin_expect (mode & __RTLD_SPROF, 0))
232 /* This happens only if we load a DSO for 'sprof'. */
235 /* This object is directly loaded. */
236 ++new->l_direct_opencount;
238 /* It was already open. */
239 if (__builtin_expect (new->l_searchlist.r_list != NULL, 0))
241 /* Let the user know about the opencount. */
242 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_FILES, 0))
243 _dl_debug_printf ("opening file=%s [%lu]; direct_opencount=%u\n\n",
244 new->l_name, new->l_ns, new->l_direct_opencount);
246 /* If the user requested the object to be in the global namespace
247 but it is not so far, add it now. */
248 if ((mode & RTLD_GLOBAL) && new->l_global == 0)
249 (void) add_to_global (new);
251 assert (_dl_debug_initialize (0, args->nsid)->r_state == RT_CONSISTENT);
256 /* Load that object's dependencies. */
257 _dl_map_object_deps (new, NULL, 0, 0,
258 mode & (__RTLD_DLOPEN | RTLD_DEEPBIND | __RTLD_AUDIT));
260 /* So far, so good. Now check the versions. */
261 for (unsigned int i = 0; i < new->l_searchlist.r_nlist; ++i)
262 if (new->l_searchlist.r_list[i]->l_real->l_versions == NULL)
263 (void) _dl_check_map_versions (new->l_searchlist.r_list[i]->l_real,
267 /* Auditing checkpoint: we have added all objects. */
268 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
270 struct link_map *head = GL(dl_ns)[new->l_ns]._ns_loaded;
271 /* Do not call the functions for any auditing object. */
272 if (head->l_auditing == 0)
274 struct audit_ifaces *afct = GLRO(dl_audit);
275 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
277 if (afct->activity != NULL)
278 afct->activity (&head->l_audit[cnt].cookie, LA_ACT_CONSISTENT);
286 /* Notify the debugger all new objects are now ready to go. */
287 struct r_debug *r = _dl_debug_initialize (0, args->nsid);
288 r->r_state = RT_CONSISTENT;
291 /* Only do lazy relocation if `LD_BIND_NOW' is not set. */
292 int reloc_mode = mode & __RTLD_AUDIT;
294 reloc_mode |= mode & RTLD_LAZY;
296 /* Relocate the objects loaded. We do this in reverse order so that copy
297 relocs of earlier objects overwrite the data written by later objects. */
299 struct link_map *l = new;
304 if (! l->l_real->l_relocated)
307 if (__builtin_expect (GLRO(dl_profile) != NULL, 0))
309 /* If this here is the shared object which we want to profile
310 make sure the profile is started. We can find out whether
311 this is necessary or not by observing the `_dl_profile_map'
312 variable. If was NULL but is not NULL afterwars we must
313 start the profiling. */
314 struct link_map *old_profile_map = GL(dl_profile_map);
316 _dl_relocate_object (l, l->l_scope, reloc_mode | RTLD_LAZY, 1);
318 if (old_profile_map == NULL && GL(dl_profile_map) != NULL)
320 /* We must prepare the profiling. */
321 _dl_start_profile ();
323 /* Prevent unloading the object. */
324 GL(dl_profile_map)->l_flags_1 |= DF_1_NODELETE;
329 _dl_relocate_object (l, l->l_scope, reloc_mode, 0);
337 /* If the file is not loaded now as a dependency, add the search
338 list of the newly loaded object to the scope. */
339 bool any_tls = false;
340 unsigned int first_static_tls = new->l_searchlist.r_nlist;
341 for (unsigned int i = 0; i < new->l_searchlist.r_nlist; ++i)
343 struct link_map *imap = new->l_searchlist.r_list[i];
345 /* If the initializer has been called already, the object has
346 not been loaded here and now. */
347 if (imap->l_init_called && imap->l_type == lt_loaded)
349 struct r_scope_elem **runp = imap->l_scope;
352 while (*runp != NULL)
354 if (*runp == &new->l_searchlist)
361 /* Avoid duplicates. */
364 if (__builtin_expect (cnt + 1 >= imap->l_scope_max, 0))
366 /* The 'r_scope' array is too small. Allocate a new one
369 struct r_scope_elem **newp;
371 #define SCOPE_ELEMS(imap) \
372 (sizeof (imap->l_scope_mem) / sizeof (imap->l_scope_mem[0]))
374 if (imap->l_scope != imap->l_scope_mem
375 && imap->l_scope_max < SCOPE_ELEMS (imap))
377 new_size = SCOPE_ELEMS (imap);
378 newp = imap->l_scope_mem;
382 new_size = imap->l_scope_max * 2;
383 newp = (struct r_scope_elem **)
384 malloc (new_size * sizeof (struct r_scope_elem *));
386 _dl_signal_error (ENOMEM, "dlopen", NULL,
387 N_("cannot create scope list"));
390 memcpy (newp, imap->l_scope, cnt * sizeof (imap->l_scope[0]));
391 struct r_scope_elem **old = imap->l_scope;
393 imap->l_scope = newp;
395 if (old != imap->l_scope_mem)
396 _dl_scope_free (old);
398 imap->l_scope_max = new_size;
401 /* First terminate the extended list. Otherwise a thread
402 might use the new last element and then use the garbage
404 imap->l_scope[cnt + 1] = NULL;
405 atomic_write_barrier ();
406 imap->l_scope[cnt] = &new->l_searchlist;
408 /* Print scope information. */
409 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_SCOPES, 0))
410 _dl_show_scope (imap);
412 /* Only add TLS memory if this object is loaded now and
413 therefore is not yet initialized. */
414 else if (! imap->l_init_called
415 /* Only if the module defines thread local data. */
416 && __builtin_expect (imap->l_tls_blocksize > 0, 0))
418 /* Now that we know the object is loaded successfully add
419 modules containing TLS data to the slot info table. We
420 might have to increase its size. */
421 _dl_add_to_slotinfo (imap);
423 if (imap->l_need_tls_init
424 && first_static_tls == new->l_searchlist.r_nlist)
425 first_static_tls = i;
427 /* We have to bump the generation counter. */
432 /* Bump the generation number if necessary. */
433 if (any_tls && __builtin_expect (++GL(dl_tls_generation) == 0, 0))
434 _dl_fatal_printf (N_("\
435 TLS generation counter wrapped! Please report this."));
437 /* We need a second pass for static tls data, because _dl_update_slotinfo
438 must not be run while calls to _dl_add_to_slotinfo are still pending. */
439 for (unsigned int i = first_static_tls; i < new->l_searchlist.r_nlist; ++i)
441 struct link_map *imap = new->l_searchlist.r_list[i];
443 if (imap->l_need_tls_init
444 && ! imap->l_init_called
445 && imap->l_tls_blocksize > 0)
447 /* For static TLS we have to allocate the memory here and
448 now. This includes allocating memory in the DTV. But we
449 cannot change any DTV other than our own. So, if we
450 cannot guarantee that there is room in the DTV we don't
451 even try it and fail the load.
453 XXX We could track the minimum DTV slots allocated in
455 if (! RTLD_SINGLE_THREAD_P && imap->l_tls_modid > DTV_SURPLUS)
456 _dl_signal_error (0, "dlopen", NULL, N_("\
457 cannot load any more object with static TLS"));
459 imap->l_need_tls_init = 0;
461 /* Update the slot information data for at least the
462 generation of the DSO we are allocating data for. */
463 _dl_update_slotinfo (imap->l_tls_modid);
466 GL(dl_init_static_tls) (imap);
467 assert (imap->l_need_tls_init == 0);
471 /* Run the initializer functions of new objects. */
472 _dl_init (new, args->argc, args->argv, args->env);
474 /* Now we can make the new map available in the global scope. */
475 if (mode & RTLD_GLOBAL)
476 /* Move the object in the global namespace. */
477 if (add_to_global (new) != 0)
481 /* Mark the object as not deletable if the RTLD_NODELETE flags was
483 if (__builtin_expect (mode & RTLD_NODELETE, 0))
484 new->l_flags_1 |= DF_1_NODELETE;
487 /* We must be the static _dl_open in libc.a. A static program that
488 has loaded a dynamic object now has competition. */
489 __libc_multiple_libcs = 1;
492 /* Let the user know about the opencount. */
493 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_FILES, 0))
494 _dl_debug_printf ("opening file=%s [%lu]; direct_opencount=%u\n\n",
495 new->l_name, new->l_ns, new->l_direct_opencount);
497 /* Print scope information. */
498 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_SCOPES, 0))
499 _dl_show_scope (new);
504 _dl_open (const char *file, int mode, const void *caller_dlopen, Lmid_t nsid,
505 int argc, char *argv[], char *env[])
507 if ((mode & RTLD_BINDING_MASK) == 0)
508 /* One of the flags must be set. */
509 _dl_signal_error (EINVAL, file, NULL, N_("invalid mode for dlopen()"));
511 /* Make sure we are alone. */
512 __rtld_lock_lock_recursive (GL(dl_load_lock));
514 if (__builtin_expect (nsid == LM_ID_NEWLM, 0))
516 /* Find a new namespace. */
517 for (nsid = 1; DL_NNS > 1 && nsid < GL(dl_nns); ++nsid)
518 if (GL(dl_ns)[nsid]._ns_loaded == NULL)
521 if (__builtin_expect (nsid == DL_NNS, 0))
523 /* No more namespace available. */
524 __rtld_lock_unlock_recursive (GL(dl_load_lock));
526 _dl_signal_error (EINVAL, file, NULL, N_("\
527 no more namespaces available for dlmopen()"));
529 else if (nsid == GL(dl_nns))
531 __rtld_lock_initialize (GL(dl_ns)[nsid]._ns_unique_sym_table.lock);
535 _dl_debug_initialize (0, nsid)->r_state = RT_CONSISTENT;
537 /* Never allow loading a DSO in a namespace which is empty. Such
538 direct placements is only causing problems. Also don't allow
539 loading into a namespace used for auditing. */
540 else if (__builtin_expect (nsid != LM_ID_BASE && nsid != __LM_ID_CALLER, 0)
541 && (GL(dl_ns)[nsid]._ns_nloaded == 0
542 || GL(dl_ns)[nsid]._ns_loaded->l_auditing))
543 _dl_signal_error (EINVAL, file, NULL,
544 N_("invalid target namespace in dlmopen()"));
546 else if ((nsid == LM_ID_BASE || nsid == __LM_ID_CALLER)
547 && GL(dl_ns)[LM_ID_BASE]._ns_loaded == NULL
552 struct dl_open_args args;
555 args.caller_dlopen = caller_dlopen;
556 args.caller_dl_open = RETURN_ADDRESS (0);
564 const char *errstring;
566 int errcode = _dl_catch_error (&objname, &errstring, &malloced,
567 dl_open_worker, &args);
570 /* We must munmap() the cache file. */
574 /* See if an error occurred during loading. */
575 if (__builtin_expect (errstring != NULL, 0))
577 /* Remove the object from memory. It may be in an inconsistent
578 state if relocation failed, for example. */
581 /* Maybe some of the modules which were loaded use TLS.
582 Since it will be removed in the following _dl_close call
583 we have to mark the dtv array as having gaps to fill the
584 holes. This is a pessimistic assumption which won't hurt
585 if not true. There is no need to do this when we are
586 loading the auditing DSOs since TLS has not yet been set
588 if ((mode & __RTLD_AUDIT) == 0)
589 GL(dl_tls_dtv_gaps) = true;
591 _dl_close_worker (args.map);
594 assert (_dl_debug_initialize (0, args.nsid)->r_state == RT_CONSISTENT);
596 /* Release the lock. */
597 __rtld_lock_unlock_recursive (GL(dl_load_lock));
599 /* Make a local copy of the error string so that we can release the
600 memory allocated for it. */
601 size_t len_errstring = strlen (errstring) + 1;
602 char *local_errstring;
603 if (objname == errstring + len_errstring)
605 size_t total_len = len_errstring + strlen (objname) + 1;
606 local_errstring = alloca (total_len);
607 memcpy (local_errstring, errstring, total_len);
608 objname = local_errstring + len_errstring;
612 local_errstring = alloca (len_errstring);
613 memcpy (local_errstring, errstring, len_errstring);
617 free ((char *) errstring);
619 /* Reraise the error. */
620 _dl_signal_error (errcode, objname, NULL, local_errstring);
623 assert (_dl_debug_initialize (0, args.nsid)->r_state == RT_CONSISTENT);
625 /* Release the lock. */
626 __rtld_lock_unlock_recursive (GL(dl_load_lock));
629 DL_STATIC_INIT (args.map);
637 _dl_show_scope (struct link_map *l)
639 _dl_debug_printf ("object=%s [%lu]\n",
640 *l->l_name ? l->l_name : rtld_progname, l->l_ns);
641 if (l->l_scope != NULL)
642 for (int scope_cnt = 0; l->l_scope[scope_cnt] != NULL; ++scope_cnt)
644 _dl_debug_printf (" scope %u:", scope_cnt);
646 for (unsigned int cnt = 0; cnt < l->l_scope[scope_cnt]->r_nlist; ++cnt)
647 if (*l->l_scope[scope_cnt]->r_list[cnt]->l_name)
648 _dl_debug_printf_c (" %s",
649 l->l_scope[scope_cnt]->r_list[cnt]->l_name);
651 _dl_debug_printf_c (" %s", rtld_progname);
653 _dl_debug_printf_c ("\n");
655 _dl_debug_printf ("\n");
659 /* Return non-zero if ADDR lies within one of L's segments. */
662 _dl_addr_inside_object (struct link_map *l, const ElfW(Addr) addr)
665 const ElfW(Addr) reladdr = addr - l->l_addr;
668 if (l->l_phdr[n].p_type == PT_LOAD
669 && reladdr - l->l_phdr[n].p_vaddr >= 0
670 && reladdr - l->l_phdr[n].p_vaddr < l->l_phdr[n].p_memsz)