2 * Copyright 1996, 1997, 1998, 1999, 2000 John D. Polstra.
3 * Copyright 2003 Alexander Kabaev <kan@FreeBSD.ORG>.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 * Dynamic linker for ELF.
32 * John Polstra <jdp@polstra.com>.
36 #error "GCC is needed to compile this file"
39 #include <sys/param.h>
40 #include <sys/mount.h>
44 #include <sys/ktrace.h>
62 #define PATH_RTLD "/libexec/ld-elf.so.1"
64 #define PATH_RTLD "/libexec/ld-elf32.so.1"
68 typedef void (*func_ptr_type)();
69 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg);
72 * This structure provides a reentrant way to keep a list of objects and
73 * check which ones have already been processed in some way.
75 typedef struct Struct_DoneList {
76 const Obj_Entry **objs; /* Array of object pointers */
77 unsigned int num_alloc; /* Allocated size of the array */
78 unsigned int num_used; /* Number of array slots used */
82 * Function declarations.
84 static const char *basename(const char *);
85 static void die(void) __dead2;
86 static void digest_dynamic(Obj_Entry *, int);
87 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
88 static Obj_Entry *dlcheck(void *);
89 static Obj_Entry *do_load_object(int, const char *, char *, struct stat *);
90 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
91 static bool donelist_check(DoneList *, const Obj_Entry *);
92 static void errmsg_restore(char *);
93 static char *errmsg_save(void);
94 static void *fill_search_info(const char *, size_t, void *);
95 static char *find_library(const char *, const Obj_Entry *);
96 static const char *gethints(void);
97 static void init_dag(Obj_Entry *);
98 static void init_dag1(Obj_Entry *, Obj_Entry *, DoneList *);
99 static void init_rtld(caddr_t);
100 static void initlist_add_neededs(Needed_Entry *, Objlist *);
101 static void initlist_add_objects(Obj_Entry *, Obj_Entry **, Objlist *);
102 static bool is_exported(const Elf_Sym *);
103 static void linkmap_add(Obj_Entry *);
104 static void linkmap_delete(Obj_Entry *);
105 static int load_needed_objects(Obj_Entry *);
106 static int load_preload_objects(void);
107 static Obj_Entry *load_object(const char *, const Obj_Entry *);
108 static Obj_Entry *obj_from_addr(const void *);
109 static void objlist_call_fini(Objlist *, int *lockstate);
110 static void objlist_call_init(Objlist *, int *lockstate);
111 static void objlist_clear(Objlist *);
112 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
113 static void objlist_init(Objlist *);
114 static void objlist_push_head(Objlist *, Obj_Entry *);
115 static void objlist_push_tail(Objlist *, Obj_Entry *);
116 static void objlist_remove(Objlist *, Obj_Entry *);
117 static void objlist_remove_unref(Objlist *);
118 static void *path_enumerate(const char *, path_enum_proc, void *);
119 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *);
120 static int rtld_dirname(const char *, char *);
121 static void rtld_exit(void);
122 static char *search_library_path(const char *, const char *);
123 static const void **get_program_var_addr(const char *);
124 static void set_program_var(const char *, const void *);
125 static const Elf_Sym *symlook_default(const char *, unsigned long,
126 const Obj_Entry *, const Obj_Entry **, const Ver_Entry *, int);
127 static const Elf_Sym *symlook_list(const char *, unsigned long, const Objlist *,
128 const Obj_Entry **, const Ver_Entry *, int, DoneList *);
129 static const Elf_Sym *symlook_needed(const char *, unsigned long,
130 const Needed_Entry *, const Obj_Entry **, const Ver_Entry *,
132 static void trace_loaded_objects(Obj_Entry *);
133 static void unlink_object(Obj_Entry *);
134 static void unload_object(Obj_Entry *);
135 static void unref_dag(Obj_Entry *);
136 static void ref_dag(Obj_Entry *);
137 static int rtld_verify_versions(const Objlist *);
138 static int rtld_verify_object_versions(Obj_Entry *);
139 static void object_add_name(Obj_Entry *, const char *);
140 static int object_match_name(const Obj_Entry *, const char *);
141 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
143 void r_debug_state(struct r_debug *, struct link_map *);
148 static char *error_message; /* Message for dlerror(), or NULL */
149 struct r_debug r_debug; /* for GDB; */
150 static bool libmap_disable; /* Disable libmap */
151 static char *libmap_override; /* Maps to use in addition to libmap.conf */
152 static bool trust; /* False for setuid and setgid programs */
153 static bool dangerous_ld_env; /* True if environment variables have been
154 used to affect the libraries loaded */
155 static char *ld_bind_now; /* Environment variable for immediate binding */
156 static char *ld_debug; /* Environment variable for debugging */
157 static char *ld_library_path; /* Environment variable for search path */
158 static char *ld_preload; /* Environment variable for libraries to
160 static char *ld_tracing; /* Called from ldd to print libs */
161 static char *ld_utrace; /* Use utrace() to log events. */
162 static Obj_Entry *obj_list; /* Head of linked list of shared objects */
163 static Obj_Entry **obj_tail; /* Link field of last object in list */
164 static Obj_Entry *obj_main; /* The main program shared object */
165 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
166 static unsigned int obj_count; /* Number of objects in obj_list */
167 static unsigned int obj_loads; /* Number of objects in obj_list */
169 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
170 STAILQ_HEAD_INITIALIZER(list_global);
171 static Objlist list_main = /* Objects loaded at program startup */
172 STAILQ_HEAD_INITIALIZER(list_main);
173 static Objlist list_fini = /* Objects needing fini() calls */
174 STAILQ_HEAD_INITIALIZER(list_fini);
176 static Elf_Sym sym_zero; /* For resolving undefined weak refs. */
178 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
180 extern Elf_Dyn _DYNAMIC;
181 #pragma weak _DYNAMIC
182 #ifndef RTLD_IS_DYNAMIC
183 #define RTLD_IS_DYNAMIC() (&_DYNAMIC != NULL)
187 * These are the functions the dynamic linker exports to application
188 * programs. They are the only symbols the dynamic linker is willing
189 * to export from itself.
191 static func_ptr_type exports[] = {
192 (func_ptr_type) &_rtld_error,
193 (func_ptr_type) &dlclose,
194 (func_ptr_type) &dlerror,
195 (func_ptr_type) &dlopen,
196 (func_ptr_type) &dlsym,
197 (func_ptr_type) &dlvsym,
198 (func_ptr_type) &dladdr,
199 (func_ptr_type) &dllockinit,
200 (func_ptr_type) &dlinfo,
201 (func_ptr_type) &_rtld_thread_init,
203 (func_ptr_type) &___tls_get_addr,
205 (func_ptr_type) &__tls_get_addr,
206 (func_ptr_type) &_rtld_allocate_tls,
207 (func_ptr_type) &_rtld_free_tls,
208 (func_ptr_type) &dl_iterate_phdr,
209 (func_ptr_type) &_rtld_atfork_pre,
210 (func_ptr_type) &_rtld_atfork_post,
215 * Global declarations normally provided by crt1. The dynamic linker is
216 * not built with crt1, so we have to provide them ourselves.
222 * Globals to control TLS allocation.
224 size_t tls_last_offset; /* Static TLS offset of last module */
225 size_t tls_last_size; /* Static TLS size of last module */
226 size_t tls_static_space; /* Static TLS space allocated */
227 int tls_dtv_generation = 1; /* Used to detect when dtv size changes */
228 int tls_max_index = 1; /* Largest module index allocated */
231 * Fill in a DoneList with an allocation large enough to hold all of
232 * the currently-loaded objects. Keep this as a macro since it calls
233 * alloca and we want that to occur within the scope of the caller.
235 #define donelist_init(dlp) \
236 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
237 assert((dlp)->objs != NULL), \
238 (dlp)->num_alloc = obj_count, \
241 #define UTRACE_DLOPEN_START 1
242 #define UTRACE_DLOPEN_STOP 2
243 #define UTRACE_DLCLOSE_START 3
244 #define UTRACE_DLCLOSE_STOP 4
245 #define UTRACE_LOAD_OBJECT 5
246 #define UTRACE_UNLOAD_OBJECT 6
247 #define UTRACE_ADD_RUNDEP 7
248 #define UTRACE_PRELOAD_FINISHED 8
249 #define UTRACE_INIT_CALL 9
250 #define UTRACE_FINI_CALL 10
253 char sig[4]; /* 'RTLD' */
256 void *mapbase; /* Used for 'parent' and 'init/fini' */
258 int refcnt; /* Used for 'mode' */
259 char name[MAXPATHLEN];
262 #define LD_UTRACE(e, h, mb, ms, r, n) do { \
263 if (ld_utrace != NULL) \
264 ld_utrace_log(e, h, mb, ms, r, n); \
268 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
269 int refcnt, const char *name)
271 struct utrace_rtld ut;
279 ut.mapbase = mapbase;
280 ut.mapsize = mapsize;
282 bzero(ut.name, sizeof(ut.name));
284 strlcpy(ut.name, name, sizeof(ut.name));
285 utrace(&ut, sizeof(ut));
289 * Main entry point for dynamic linking. The first argument is the
290 * stack pointer. The stack is expected to be laid out as described
291 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
292 * Specifically, the stack pointer points to a word containing
293 * ARGC. Following that in the stack is a null-terminated sequence
294 * of pointers to argument strings. Then comes a null-terminated
295 * sequence of pointers to environment strings. Finally, there is a
296 * sequence of "auxiliary vector" entries.
298 * The second argument points to a place to store the dynamic linker's
299 * exit procedure pointer and the third to a place to store the main
302 * The return value is the main program's entry point.
305 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
307 Elf_Auxinfo *aux_info[AT_COUNT];
315 Objlist_Entry *entry;
317 Obj_Entry **preload_tail;
322 * On entry, the dynamic linker itself has not been relocated yet.
323 * Be very careful not to reference any global data until after
324 * init_rtld has returned. It is OK to reference file-scope statics
325 * and string constants, and to call static and global functions.
328 /* Find the auxiliary vector on the stack. */
331 sp += argc + 1; /* Skip over arguments and NULL terminator */
333 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
335 aux = (Elf_Auxinfo *) sp;
337 /* Digest the auxiliary vector. */
338 for (i = 0; i < AT_COUNT; i++)
340 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
341 if (auxp->a_type < AT_COUNT)
342 aux_info[auxp->a_type] = auxp;
345 /* Initialize and relocate ourselves. */
346 assert(aux_info[AT_BASE] != NULL);
347 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
349 __progname = obj_rtld.path;
350 argv0 = argv[0] != NULL ? argv[0] : "(null)";
353 trust = !issetugid();
355 ld_bind_now = getenv(LD_ "BIND_NOW");
357 * If the process is tainted, then we un-set the dangerous environment
358 * variables. The process will be marked as tainted until setuid(2)
359 * is called. If any child process calls setuid(2) we do not want any
360 * future processes to honor the potentially un-safe variables.
363 unsetenv(LD_ "PRELOAD");
364 unsetenv(LD_ "LIBMAP");
365 unsetenv(LD_ "LIBRARY_PATH");
366 unsetenv(LD_ "LIBMAP_DISABLE");
367 unsetenv(LD_ "DEBUG");
369 ld_debug = getenv(LD_ "DEBUG");
370 libmap_disable = getenv(LD_ "LIBMAP_DISABLE") != NULL;
371 libmap_override = getenv(LD_ "LIBMAP");
372 ld_library_path = getenv(LD_ "LIBRARY_PATH");
373 ld_preload = getenv(LD_ "PRELOAD");
374 dangerous_ld_env = libmap_disable || (libmap_override != NULL) ||
375 (ld_library_path != NULL) || (ld_preload != NULL);
376 ld_tracing = getenv(LD_ "TRACE_LOADED_OBJECTS");
377 ld_utrace = getenv(LD_ "UTRACE");
379 if (ld_debug != NULL && *ld_debug != '\0')
381 dbg("%s is initialized, base address = %p", __progname,
382 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
383 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
384 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
387 * Load the main program, or process its program header if it is
390 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
391 int fd = aux_info[AT_EXECFD]->a_un.a_val;
392 dbg("loading main program");
393 obj_main = map_object(fd, argv0, NULL);
395 if (obj_main == NULL)
397 } else { /* Main program already loaded. */
398 const Elf_Phdr *phdr;
402 dbg("processing main program's program header");
403 assert(aux_info[AT_PHDR] != NULL);
404 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
405 assert(aux_info[AT_PHNUM] != NULL);
406 phnum = aux_info[AT_PHNUM]->a_un.a_val;
407 assert(aux_info[AT_PHENT] != NULL);
408 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
409 assert(aux_info[AT_ENTRY] != NULL);
410 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
411 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
415 obj_main->path = xstrdup(argv0);
416 obj_main->mainprog = true;
419 * Get the actual dynamic linker pathname from the executable if
420 * possible. (It should always be possible.) That ensures that
421 * gdb will find the right dynamic linker even if a non-standard
424 if (obj_main->interp != NULL &&
425 strcmp(obj_main->interp, obj_rtld.path) != 0) {
427 obj_rtld.path = xstrdup(obj_main->interp);
428 __progname = obj_rtld.path;
431 digest_dynamic(obj_main, 0);
433 linkmap_add(obj_main);
434 linkmap_add(&obj_rtld);
436 /* Link the main program into the list of objects. */
437 *obj_tail = obj_main;
438 obj_tail = &obj_main->next;
441 /* Make sure we don't call the main program's init and fini functions. */
442 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
444 /* Initialize a fake symbol for resolving undefined weak references. */
445 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
446 sym_zero.st_shndx = SHN_UNDEF;
449 libmap_disable = (bool)lm_init(libmap_override);
451 dbg("loading LD_PRELOAD libraries");
452 if (load_preload_objects() == -1)
454 preload_tail = obj_tail;
456 dbg("loading needed objects");
457 if (load_needed_objects(obj_main) == -1)
460 /* Make a list of all objects loaded at startup. */
461 for (obj = obj_list; obj != NULL; obj = obj->next) {
462 objlist_push_tail(&list_main, obj);
466 dbg("checking for required versions");
467 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
470 if (ld_tracing) { /* We're done */
471 trace_loaded_objects(obj_main);
475 if (getenv(LD_ "DUMP_REL_PRE") != NULL) {
476 dump_relocations(obj_main);
480 /* setup TLS for main thread */
481 dbg("initializing initial thread local storage");
482 STAILQ_FOREACH(entry, &list_main, link) {
484 * Allocate all the initial objects out of the static TLS
485 * block even if they didn't ask for it.
487 allocate_tls_offset(entry->obj);
489 allocate_initial_tls(obj_list);
491 if (relocate_objects(obj_main,
492 ld_bind_now != NULL && *ld_bind_now != '\0', &obj_rtld) == -1)
495 dbg("doing copy relocations");
496 if (do_copy_relocations(obj_main) == -1)
499 if (getenv(LD_ "DUMP_REL_POST") != NULL) {
500 dump_relocations(obj_main);
504 dbg("initializing key program variables");
505 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
506 set_program_var("environ", env);
508 dbg("initializing thread locks");
511 /* Make a list of init functions to call. */
512 objlist_init(&initlist);
513 initlist_add_objects(obj_list, preload_tail, &initlist);
515 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
517 lockstate = wlock_acquire(rtld_bind_lock);
518 objlist_call_init(&initlist, &lockstate);
519 objlist_clear(&initlist);
520 wlock_release(rtld_bind_lock, lockstate);
522 dbg("transferring control to program entry point = %p", obj_main->entry);
524 /* Return the exit procedure and the program entry point. */
525 *exit_proc = rtld_exit;
527 return (func_ptr_type) obj_main->entry;
531 _rtld_bind(Obj_Entry *obj, Elf_Size reloff)
535 const Obj_Entry *defobj;
540 lockstate = rlock_acquire(rtld_bind_lock);
542 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
544 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
546 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
547 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL);
551 target = (Elf_Addr)(defobj->relocbase + def->st_value);
553 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
554 defobj->strtab + def->st_name, basename(obj->path),
555 (void *)target, basename(defobj->path));
558 * Write the new contents for the jmpslot. Note that depending on
559 * architecture, the value which we need to return back to the
560 * lazy binding trampoline may or may not be the target
561 * address. The value returned from reloc_jmpslot() is the value
562 * that the trampoline needs.
564 target = reloc_jmpslot(where, target, defobj, obj, rel);
565 rlock_release(rtld_bind_lock, lockstate);
570 * Error reporting function. Use it like printf. If formats the message
571 * into a buffer, and sets things up so that the next call to dlerror()
572 * will return the message.
575 _rtld_error(const char *fmt, ...)
577 static char buf[512];
581 vsnprintf(buf, sizeof buf, fmt, ap);
587 * Return a dynamically-allocated copy of the current error message, if any.
592 return error_message == NULL ? NULL : xstrdup(error_message);
596 * Restore the current error message from a copy which was previously saved
597 * by errmsg_save(). The copy is freed.
600 errmsg_restore(char *saved_msg)
602 if (saved_msg == NULL)
603 error_message = NULL;
605 _rtld_error("%s", saved_msg);
611 basename(const char *name)
613 const char *p = strrchr(name, '/');
614 return p != NULL ? p + 1 : name;
620 const char *msg = dlerror();
628 * Process a shared object's DYNAMIC section, and save the important
629 * information in its Obj_Entry structure.
632 digest_dynamic(Obj_Entry *obj, int early)
635 Needed_Entry **needed_tail = &obj->needed;
636 const Elf_Dyn *dyn_rpath = NULL;
637 const Elf_Dyn *dyn_soname = NULL;
638 int plttype = DT_REL;
640 obj->bind_now = false;
641 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
642 switch (dynp->d_tag) {
645 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
649 obj->relsize = dynp->d_un.d_val;
653 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
657 obj->pltrel = (const Elf_Rel *)
658 (obj->relocbase + dynp->d_un.d_ptr);
662 obj->pltrelsize = dynp->d_un.d_val;
666 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
670 obj->relasize = dynp->d_un.d_val;
674 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
678 plttype = dynp->d_un.d_val;
679 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
683 obj->symtab = (const Elf_Sym *)
684 (obj->relocbase + dynp->d_un.d_ptr);
688 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
692 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
696 obj->strsize = dynp->d_un.d_val;
700 obj->verneed = (const Elf_Verneed *) (obj->relocbase +
705 obj->verneednum = dynp->d_un.d_val;
709 obj->verdef = (const Elf_Verdef *) (obj->relocbase +
714 obj->verdefnum = dynp->d_un.d_val;
718 obj->versyms = (const Elf_Versym *)(obj->relocbase +
724 const Elf_Hashelt *hashtab = (const Elf_Hashelt *)
725 (obj->relocbase + dynp->d_un.d_ptr);
726 obj->nbuckets = hashtab[0];
727 obj->nchains = hashtab[1];
728 obj->buckets = hashtab + 2;
729 obj->chains = obj->buckets + obj->nbuckets;
735 Needed_Entry *nep = NEW(Needed_Entry);
736 nep->name = dynp->d_un.d_val;
741 needed_tail = &nep->next;
746 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
754 obj->symbolic = true;
758 case DT_RUNPATH: /* XXX: process separately */
760 * We have to wait until later to process this, because we
761 * might not have gotten the address of the string table yet.
771 obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
775 obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
779 /* XXX - not implemented yet */
781 dbg("Filling in DT_DEBUG entry");
782 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
786 if (dynp->d_un.d_val & DF_ORIGIN) {
787 obj->origin_path = xmalloc(PATH_MAX);
788 if (rtld_dirname(obj->path, obj->origin_path) == -1)
791 if (dynp->d_un.d_val & DF_SYMBOLIC)
792 obj->symbolic = true;
793 if (dynp->d_un.d_val & DF_TEXTREL)
795 if (dynp->d_un.d_val & DF_BIND_NOW)
796 obj->bind_now = true;
797 if (dynp->d_un.d_val & DF_STATIC_TLS)
803 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
812 if (plttype == DT_RELA) {
813 obj->pltrela = (const Elf_Rela *) obj->pltrel;
815 obj->pltrelasize = obj->pltrelsize;
819 if (dyn_rpath != NULL)
820 obj->rpath = obj->strtab + dyn_rpath->d_un.d_val;
822 if (dyn_soname != NULL)
823 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
827 * Process a shared object's program header. This is used only for the
828 * main program, when the kernel has already loaded the main program
829 * into memory before calling the dynamic linker. It creates and
830 * returns an Obj_Entry structure.
833 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
836 const Elf_Phdr *phlimit = phdr + phnum;
841 for (ph = phdr; ph < phlimit; ph++) {
842 switch (ph->p_type) {
845 if ((const Elf_Phdr *)ph->p_vaddr != phdr) {
846 _rtld_error("%s: invalid PT_PHDR", path);
849 obj->phdr = (const Elf_Phdr *) ph->p_vaddr;
850 obj->phsize = ph->p_memsz;
854 obj->interp = (const char *) ph->p_vaddr;
858 if (nsegs == 0) { /* First load segment */
859 obj->vaddrbase = trunc_page(ph->p_vaddr);
860 obj->mapbase = (caddr_t) obj->vaddrbase;
861 obj->relocbase = obj->mapbase - obj->vaddrbase;
862 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
864 } else { /* Last load segment */
865 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
872 obj->dynamic = (const Elf_Dyn *) ph->p_vaddr;
877 obj->tlssize = ph->p_memsz;
878 obj->tlsalign = ph->p_align;
879 obj->tlsinitsize = ph->p_filesz;
880 obj->tlsinit = (void*) ph->p_vaddr;
885 _rtld_error("%s: too few PT_LOAD segments", path);
894 dlcheck(void *handle)
898 for (obj = obj_list; obj != NULL; obj = obj->next)
899 if (obj == (Obj_Entry *) handle)
902 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
903 _rtld_error("Invalid shared object handle %p", handle);
910 * If the given object is already in the donelist, return true. Otherwise
911 * add the object to the list and return false.
914 donelist_check(DoneList *dlp, const Obj_Entry *obj)
918 for (i = 0; i < dlp->num_used; i++)
919 if (dlp->objs[i] == obj)
922 * Our donelist allocation should always be sufficient. But if
923 * our threads locking isn't working properly, more shared objects
924 * could have been loaded since we allocated the list. That should
925 * never happen, but we'll handle it properly just in case it does.
927 if (dlp->num_used < dlp->num_alloc)
928 dlp->objs[dlp->num_used++] = obj;
933 * Hash function for symbol table lookup. Don't even think about changing
934 * this. It is specified by the System V ABI.
937 elf_hash(const char *name)
939 const unsigned char *p = (const unsigned char *) name;
945 if ((g = h & 0xf0000000) != 0)
953 * Find the library with the given name, and return its full pathname.
954 * The returned string is dynamically allocated. Generates an error
955 * message and returns NULL if the library cannot be found.
957 * If the second argument is non-NULL, then it refers to an already-
958 * loaded shared object, whose library search path will be searched.
960 * The search order is:
962 * rpath in the referencing file
967 find_library(const char *xname, const Obj_Entry *refobj)
972 if (strchr(xname, '/') != NULL) { /* Hard coded pathname */
973 if (xname[0] != '/' && !trust) {
974 _rtld_error("Absolute pathname required for shared object \"%s\"",
978 return xstrdup(xname);
981 if (libmap_disable || (refobj == NULL) ||
982 (name = lm_find(refobj->path, xname)) == NULL)
983 name = (char *)xname;
985 dbg(" Searching for \"%s\"", name);
987 if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
989 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
990 (pathname = search_library_path(name, gethints())) != NULL ||
991 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
994 if(refobj != NULL && refobj->path != NULL) {
995 _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
996 name, basename(refobj->path));
998 _rtld_error("Shared object \"%s\" not found", name);
1004 * Given a symbol number in a referencing object, find the corresponding
1005 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1006 * no definition was found. Returns a pointer to the Obj_Entry of the
1007 * defining object via the reference parameter DEFOBJ_OUT.
1010 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1011 const Obj_Entry **defobj_out, int flags, SymCache *cache)
1015 const Obj_Entry *defobj;
1016 const Ver_Entry *ventry;
1021 * If we have already found this symbol, get the information from
1024 if (symnum >= refobj->nchains)
1025 return NULL; /* Bad object */
1026 if (cache != NULL && cache[symnum].sym != NULL) {
1027 *defobj_out = cache[symnum].obj;
1028 return cache[symnum].sym;
1031 ref = refobj->symtab + symnum;
1032 name = refobj->strtab + ref->st_name;
1036 * We don't have to do a full scale lookup if the symbol is local.
1037 * We know it will bind to the instance in this load module; to
1038 * which we already have a pointer (ie ref). By not doing a lookup,
1039 * we not only improve performance, but it also avoids unresolvable
1040 * symbols when local symbols are not in the hash table. This has
1041 * been seen with the ia64 toolchain.
1043 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1044 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1045 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1048 ventry = fetch_ventry(refobj, symnum);
1049 hash = elf_hash(name);
1050 def = symlook_default(name, hash, refobj, &defobj, ventry, flags);
1057 * If we found no definition and the reference is weak, treat the
1058 * symbol as having the value zero.
1060 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1066 *defobj_out = defobj;
1067 /* Record the information in the cache to avoid subsequent lookups. */
1068 if (cache != NULL) {
1069 cache[symnum].sym = def;
1070 cache[symnum].obj = defobj;
1073 if (refobj != &obj_rtld)
1074 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1080 * Return the search path from the ldconfig hints file, reading it if
1081 * necessary. Returns NULL if there are problems with the hints file,
1082 * or if the search path there is empty.
1089 if (hints == NULL) {
1091 struct elfhints_hdr hdr;
1094 /* Keep from trying again in case the hints file is bad. */
1097 if ((fd = open(_PATH_ELF_HINTS, O_RDONLY)) == -1)
1099 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1100 hdr.magic != ELFHINTS_MAGIC ||
1105 p = xmalloc(hdr.dirlistlen + 1);
1106 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1107 read(fd, p, hdr.dirlistlen + 1) != (ssize_t)hdr.dirlistlen + 1) {
1115 return hints[0] != '\0' ? hints : NULL;
1119 init_dag(Obj_Entry *root)
1123 donelist_init(&donelist);
1124 init_dag1(root, root, &donelist);
1128 init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *dlp)
1130 const Needed_Entry *needed;
1132 if (donelist_check(dlp, obj))
1136 objlist_push_tail(&obj->dldags, root);
1137 objlist_push_tail(&root->dagmembers, obj);
1138 for (needed = obj->needed; needed != NULL; needed = needed->next)
1139 if (needed->obj != NULL)
1140 init_dag1(root, needed->obj, dlp);
1144 * Initialize the dynamic linker. The argument is the address at which
1145 * the dynamic linker has been mapped into memory. The primary task of
1146 * this function is to relocate the dynamic linker.
1149 init_rtld(caddr_t mapbase)
1151 Obj_Entry objtmp; /* Temporary rtld object */
1154 * Conjure up an Obj_Entry structure for the dynamic linker.
1156 * The "path" member can't be initialized yet because string constatns
1157 * cannot yet be acessed. Below we will set it correctly.
1159 memset(&objtmp, 0, sizeof(objtmp));
1162 objtmp.mapbase = mapbase;
1164 objtmp.relocbase = mapbase;
1166 if (RTLD_IS_DYNAMIC()) {
1167 objtmp.dynamic = rtld_dynamic(&objtmp);
1168 digest_dynamic(&objtmp, 1);
1169 assert(objtmp.needed == NULL);
1170 assert(!objtmp.textrel);
1173 * Temporarily put the dynamic linker entry into the object list, so
1174 * that symbols can be found.
1177 relocate_objects(&objtmp, true, &objtmp);
1180 /* Initialize the object list. */
1181 obj_tail = &obj_list;
1183 /* Now that non-local variables can be accesses, copy out obj_rtld. */
1184 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1186 /* Replace the path with a dynamically allocated copy. */
1187 obj_rtld.path = xstrdup(PATH_RTLD);
1189 r_debug.r_brk = r_debug_state;
1190 r_debug.r_state = RT_CONSISTENT;
1194 * Add the init functions from a needed object list (and its recursive
1195 * needed objects) to "list". This is not used directly; it is a helper
1196 * function for initlist_add_objects(). The write lock must be held
1197 * when this function is called.
1200 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1202 /* Recursively process the successor needed objects. */
1203 if (needed->next != NULL)
1204 initlist_add_neededs(needed->next, list);
1206 /* Process the current needed object. */
1207 if (needed->obj != NULL)
1208 initlist_add_objects(needed->obj, &needed->obj->next, list);
1212 * Scan all of the DAGs rooted in the range of objects from "obj" to
1213 * "tail" and add their init functions to "list". This recurses over
1214 * the DAGs and ensure the proper init ordering such that each object's
1215 * needed libraries are initialized before the object itself. At the
1216 * same time, this function adds the objects to the global finalization
1217 * list "list_fini" in the opposite order. The write lock must be
1218 * held when this function is called.
1221 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1225 obj->init_done = true;
1227 /* Recursively process the successor objects. */
1228 if (&obj->next != tail)
1229 initlist_add_objects(obj->next, tail, list);
1231 /* Recursively process the needed objects. */
1232 if (obj->needed != NULL)
1233 initlist_add_neededs(obj->needed, list);
1235 /* Add the object to the init list. */
1236 if (obj->init != (Elf_Addr)NULL)
1237 objlist_push_tail(list, obj);
1239 /* Add the object to the global fini list in the reverse order. */
1240 if (obj->fini != (Elf_Addr)NULL)
1241 objlist_push_head(&list_fini, obj);
1245 #define FPTR_TARGET(f) ((Elf_Addr) (f))
1249 is_exported(const Elf_Sym *def)
1252 const func_ptr_type *p;
1254 value = (Elf_Addr)(obj_rtld.relocbase + def->st_value);
1255 for (p = exports; *p != NULL; p++)
1256 if (FPTR_TARGET(*p) == value)
1262 * Given a shared object, traverse its list of needed objects, and load
1263 * each of them. Returns 0 on success. Generates an error message and
1264 * returns -1 on failure.
1267 load_needed_objects(Obj_Entry *first)
1271 for (obj = first; obj != NULL; obj = obj->next) {
1272 Needed_Entry *needed;
1274 for (needed = obj->needed; needed != NULL; needed = needed->next) {
1275 needed->obj = load_object(obj->strtab + needed->name, obj);
1276 if (needed->obj == NULL && !ld_tracing)
1285 load_preload_objects(void)
1287 char *p = ld_preload;
1288 static const char delim[] = " \t:;";
1293 p += strspn(p, delim);
1294 while (*p != '\0') {
1295 size_t len = strcspn(p, delim);
1300 if (load_object(p, NULL) == NULL)
1301 return -1; /* XXX - cleanup */
1304 p += strspn(p, delim);
1306 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
1311 * Load a shared object into memory, if it is not already loaded.
1313 * Returns a pointer to the Obj_Entry for the object. Returns NULL
1317 load_object(const char *name, const Obj_Entry *refobj)
1324 for (obj = obj_list->next; obj != NULL; obj = obj->next)
1325 if (object_match_name(obj, name))
1328 path = find_library(name, refobj);
1333 * If we didn't find a match by pathname, open the file and check
1334 * again by device and inode. This avoids false mismatches caused
1335 * by multiple links or ".." in pathnames.
1337 * To avoid a race, we open the file and use fstat() rather than
1340 if ((fd = open(path, O_RDONLY)) == -1) {
1341 _rtld_error("Cannot open \"%s\"", path);
1345 if (fstat(fd, &sb) == -1) {
1346 _rtld_error("Cannot fstat \"%s\"", path);
1351 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
1352 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev) {
1358 object_add_name(obj, name);
1364 /* First use of this object, so we must map it in */
1365 obj = do_load_object(fd, name, path, &sb);
1374 do_load_object(int fd, const char *name, char *path, struct stat *sbp)
1380 * but first, make sure that environment variables haven't been
1381 * used to circumvent the noexec flag on a filesystem.
1383 if (dangerous_ld_env) {
1384 if (fstatfs(fd, &fs) != 0) {
1385 _rtld_error("Cannot fstatfs \"%s\"", path);
1388 if (fs.f_flags & MNT_NOEXEC) {
1389 _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
1393 dbg("loading \"%s\"", path);
1394 obj = map_object(fd, path, sbp);
1398 object_add_name(obj, name);
1400 digest_dynamic(obj, 0);
1403 obj_tail = &obj->next;
1406 linkmap_add(obj); /* for GDB & dlinfo() */
1408 dbg(" %p .. %p: %s", obj->mapbase,
1409 obj->mapbase + obj->mapsize - 1, obj->path);
1411 dbg(" WARNING: %s has impure text", obj->path);
1412 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
1419 obj_from_addr(const void *addr)
1423 for (obj = obj_list; obj != NULL; obj = obj->next) {
1424 if (addr < (void *) obj->mapbase)
1426 if (addr < (void *) (obj->mapbase + obj->mapsize))
1433 * Call the finalization functions for each of the objects in "list"
1434 * which are unreferenced. All of the objects are expected to have
1435 * non-NULL fini functions.
1438 objlist_call_fini(Objlist *list, int *lockstate)
1444 * Preserve the current error message since a fini function might
1445 * call into the dynamic linker and overwrite it.
1447 saved_msg = errmsg_save();
1448 wlock_release(rtld_bind_lock, *lockstate);
1449 STAILQ_FOREACH(elm, list, link) {
1450 if (elm->obj->refcount == 0) {
1451 dbg("calling fini function for %s at %p", elm->obj->path,
1452 (void *)elm->obj->fini);
1453 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini, 0, 0,
1455 call_initfini_pointer(elm->obj, elm->obj->fini);
1458 *lockstate = wlock_acquire(rtld_bind_lock);
1459 errmsg_restore(saved_msg);
1463 * Call the initialization functions for each of the objects in
1464 * "list". All of the objects are expected to have non-NULL init
1468 objlist_call_init(Objlist *list, int *lockstate)
1474 * Preserve the current error message since an init function might
1475 * call into the dynamic linker and overwrite it.
1477 saved_msg = errmsg_save();
1478 wlock_release(rtld_bind_lock, *lockstate);
1479 STAILQ_FOREACH(elm, list, link) {
1480 dbg("calling init function for %s at %p", elm->obj->path,
1481 (void *)elm->obj->init);
1482 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init, 0, 0,
1484 call_initfini_pointer(elm->obj, elm->obj->init);
1486 *lockstate = wlock_acquire(rtld_bind_lock);
1487 errmsg_restore(saved_msg);
1491 objlist_clear(Objlist *list)
1495 while (!STAILQ_EMPTY(list)) {
1496 elm = STAILQ_FIRST(list);
1497 STAILQ_REMOVE_HEAD(list, link);
1502 static Objlist_Entry *
1503 objlist_find(Objlist *list, const Obj_Entry *obj)
1507 STAILQ_FOREACH(elm, list, link)
1508 if (elm->obj == obj)
1514 objlist_init(Objlist *list)
1520 objlist_push_head(Objlist *list, Obj_Entry *obj)
1524 elm = NEW(Objlist_Entry);
1526 STAILQ_INSERT_HEAD(list, elm, link);
1530 objlist_push_tail(Objlist *list, Obj_Entry *obj)
1534 elm = NEW(Objlist_Entry);
1536 STAILQ_INSERT_TAIL(list, elm, link);
1540 objlist_remove(Objlist *list, Obj_Entry *obj)
1544 if ((elm = objlist_find(list, obj)) != NULL) {
1545 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1551 * Remove all of the unreferenced objects from "list".
1554 objlist_remove_unref(Objlist *list)
1559 STAILQ_INIT(&newlist);
1560 while (!STAILQ_EMPTY(list)) {
1561 elm = STAILQ_FIRST(list);
1562 STAILQ_REMOVE_HEAD(list, link);
1563 if (elm->obj->refcount == 0)
1566 STAILQ_INSERT_TAIL(&newlist, elm, link);
1572 * Relocate newly-loaded shared objects. The argument is a pointer to
1573 * the Obj_Entry for the first such object. All objects from the first
1574 * to the end of the list of objects are relocated. Returns 0 on success,
1578 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj)
1582 for (obj = first; obj != NULL; obj = obj->next) {
1584 dbg("relocating \"%s\"", obj->path);
1585 if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
1586 obj->symtab == NULL || obj->strtab == NULL) {
1587 _rtld_error("%s: Shared object has no run-time symbol table",
1593 /* There are relocations to the write-protected text segment. */
1594 if (mprotect(obj->mapbase, obj->textsize,
1595 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
1596 _rtld_error("%s: Cannot write-enable text segment: %s",
1597 obj->path, strerror(errno));
1602 /* Process the non-PLT relocations. */
1603 if (reloc_non_plt(obj, rtldobj))
1606 if (obj->textrel) { /* Re-protected the text segment. */
1607 if (mprotect(obj->mapbase, obj->textsize,
1608 PROT_READ|PROT_EXEC) == -1) {
1609 _rtld_error("%s: Cannot write-protect text segment: %s",
1610 obj->path, strerror(errno));
1615 /* Process the PLT relocations. */
1616 if (reloc_plt(obj) == -1)
1618 /* Relocate the jump slots if we are doing immediate binding. */
1619 if (obj->bind_now || bind_now)
1620 if (reloc_jmpslots(obj) == -1)
1625 * Set up the magic number and version in the Obj_Entry. These
1626 * were checked in the crt1.o from the original ElfKit, so we
1627 * set them for backward compatibility.
1629 obj->magic = RTLD_MAGIC;
1630 obj->version = RTLD_VERSION;
1632 /* Set the special PLT or GOT entries. */
1640 * Cleanup procedure. It will be called (by the atexit mechanism) just
1641 * before the process exits.
1649 lockstate = wlock_acquire(rtld_bind_lock);
1651 /* Clear all the reference counts so the fini functions will be called. */
1652 for (obj = obj_list; obj != NULL; obj = obj->next)
1654 objlist_call_fini(&list_fini, &lockstate);
1655 /* No need to remove the items from the list, since we are exiting. */
1656 if (!libmap_disable)
1658 wlock_release(rtld_bind_lock, lockstate);
1662 path_enumerate(const char *path, path_enum_proc callback, void *arg)
1670 path += strspn(path, ":;");
1671 while (*path != '\0') {
1675 len = strcspn(path, ":;");
1677 trans = lm_findn(NULL, path, len);
1679 res = callback(trans, strlen(trans), arg);
1682 res = callback(path, len, arg);
1688 path += strspn(path, ":;");
1694 struct try_library_args {
1702 try_library_path(const char *dir, size_t dirlen, void *param)
1704 struct try_library_args *arg;
1707 if (*dir == '/' || trust) {
1710 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
1713 pathname = arg->buffer;
1714 strncpy(pathname, dir, dirlen);
1715 pathname[dirlen] = '/';
1716 strcpy(pathname + dirlen + 1, arg->name);
1718 dbg(" Trying \"%s\"", pathname);
1719 if (access(pathname, F_OK) == 0) { /* We found it */
1720 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
1721 strcpy(pathname, arg->buffer);
1729 search_library_path(const char *name, const char *path)
1732 struct try_library_args arg;
1738 arg.namelen = strlen(name);
1739 arg.buffer = xmalloc(PATH_MAX);
1740 arg.buflen = PATH_MAX;
1742 p = path_enumerate(path, try_library_path, &arg);
1750 dlclose(void *handle)
1755 lockstate = wlock_acquire(rtld_bind_lock);
1756 root = dlcheck(handle);
1758 wlock_release(rtld_bind_lock, lockstate);
1761 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
1764 /* Unreference the object and its dependencies. */
1765 root->dl_refcount--;
1769 if (root->refcount == 0) {
1771 * The object is no longer referenced, so we must unload it.
1772 * First, call the fini functions.
1774 objlist_call_fini(&list_fini, &lockstate);
1775 objlist_remove_unref(&list_fini);
1777 /* Finish cleaning up the newly-unreferenced objects. */
1778 GDB_STATE(RT_DELETE,&root->linkmap);
1779 unload_object(root);
1780 GDB_STATE(RT_CONSISTENT,NULL);
1782 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
1783 wlock_release(rtld_bind_lock, lockstate);
1790 char *msg = error_message;
1791 error_message = NULL;
1796 * This function is deprecated and has no effect.
1799 dllockinit(void *context,
1800 void *(*lock_create)(void *context),
1801 void (*rlock_acquire)(void *lock),
1802 void (*wlock_acquire)(void *lock),
1803 void (*lock_release)(void *lock),
1804 void (*lock_destroy)(void *lock),
1805 void (*context_destroy)(void *context))
1807 static void *cur_context;
1808 static void (*cur_context_destroy)(void *);
1810 /* Just destroy the context from the previous call, if necessary. */
1811 if (cur_context_destroy != NULL)
1812 cur_context_destroy(cur_context);
1813 cur_context = context;
1814 cur_context_destroy = context_destroy;
1818 dlopen(const char *name, int mode)
1820 Obj_Entry **old_obj_tail;
1823 int result, lockstate;
1825 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
1826 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
1827 if (ld_tracing != NULL)
1828 environ = (char **)*get_program_var_addr("environ");
1830 objlist_init(&initlist);
1832 lockstate = wlock_acquire(rtld_bind_lock);
1833 GDB_STATE(RT_ADD,NULL);
1835 old_obj_tail = obj_tail;
1841 obj = load_object(name, obj_main);
1846 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
1847 objlist_push_tail(&list_global, obj);
1848 mode &= RTLD_MODEMASK;
1849 if (*old_obj_tail != NULL) { /* We loaded something new. */
1850 assert(*old_obj_tail == obj);
1851 result = load_needed_objects(obj);
1854 result = rtld_verify_versions(&obj->dagmembers);
1855 if (result != -1 && ld_tracing)
1858 (relocate_objects(obj, mode == RTLD_NOW, &obj_rtld)) == -1) {
1861 if (obj->refcount == 0)
1865 /* Make list of init functions to call. */
1866 initlist_add_objects(obj, &obj->next, &initlist);
1870 /* Bump the reference counts for objects on this DAG. */
1878 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
1880 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
1882 /* Call the init functions. */
1883 objlist_call_init(&initlist, &lockstate);
1884 objlist_clear(&initlist);
1885 wlock_release(rtld_bind_lock, lockstate);
1888 trace_loaded_objects(obj);
1889 wlock_release(rtld_bind_lock, lockstate);
1894 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
1898 const Obj_Entry *obj, *defobj;
1899 const Elf_Sym *def, *symp;
1903 hash = elf_hash(name);
1906 flags |= SYMLOOK_IN_PLT;
1908 lockstate = rlock_acquire(rtld_bind_lock);
1909 if (handle == NULL || handle == RTLD_NEXT ||
1910 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
1912 if ((obj = obj_from_addr(retaddr)) == NULL) {
1913 _rtld_error("Cannot determine caller's shared object");
1914 rlock_release(rtld_bind_lock, lockstate);
1917 if (handle == NULL) { /* Just the caller's shared object. */
1918 def = symlook_obj(name, hash, obj, ve, flags);
1920 } else if (handle == RTLD_NEXT || /* Objects after caller's */
1921 handle == RTLD_SELF) { /* ... caller included */
1922 if (handle == RTLD_NEXT)
1924 for (; obj != NULL; obj = obj->next) {
1925 if ((symp = symlook_obj(name, hash, obj, ve, flags)) != NULL) {
1926 if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
1929 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
1935 * Search the dynamic linker itself, and possibly resolve the
1936 * symbol from there. This is how the application links to
1937 * dynamic linker services such as dlopen. Only the values listed
1938 * in the "exports" array can be resolved from the dynamic linker.
1940 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
1941 symp = symlook_obj(name, hash, &obj_rtld, ve, flags);
1942 if (symp != NULL && is_exported(symp)) {
1948 assert(handle == RTLD_DEFAULT);
1949 def = symlook_default(name, hash, obj, &defobj, ve, flags);
1952 if ((obj = dlcheck(handle)) == NULL) {
1953 rlock_release(rtld_bind_lock, lockstate);
1957 donelist_init(&donelist);
1958 if (obj->mainprog) {
1959 /* Search main program and all libraries loaded by it. */
1960 def = symlook_list(name, hash, &list_main, &defobj, ve, flags,
1965 /* Search the whole DAG rooted at the given object. */
1967 fake.obj = (Obj_Entry *)obj;
1969 def = symlook_needed(name, hash, &fake, &defobj, ve, flags,
1975 rlock_release(rtld_bind_lock, lockstate);
1978 * The value required by the caller is derived from the value
1979 * of the symbol. For the ia64 architecture, we need to
1980 * construct a function descriptor which the caller can use to
1981 * call the function with the right 'gp' value. For other
1982 * architectures and for non-functions, the value is simply
1983 * the relocated value of the symbol.
1985 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
1986 return make_function_pointer(def, defobj);
1988 return defobj->relocbase + def->st_value;
1991 _rtld_error("Undefined symbol \"%s\"", name);
1992 rlock_release(rtld_bind_lock, lockstate);
1997 dlsym(void *handle, const char *name)
1999 return do_dlsym(handle, name, __builtin_return_address(0), NULL,
2004 dlvsym(void *handle, const char *name, const char *version)
2008 ventry.name = version;
2010 ventry.hash = elf_hash(version);
2012 return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
2017 dladdr(const void *addr, Dl_info *info)
2019 const Obj_Entry *obj;
2022 unsigned long symoffset;
2025 lockstate = rlock_acquire(rtld_bind_lock);
2026 obj = obj_from_addr(addr);
2028 _rtld_error("No shared object contains address");
2029 rlock_release(rtld_bind_lock, lockstate);
2032 info->dli_fname = obj->path;
2033 info->dli_fbase = obj->mapbase;
2034 info->dli_saddr = (void *)0;
2035 info->dli_sname = NULL;
2038 * Walk the symbol list looking for the symbol whose address is
2039 * closest to the address sent in.
2041 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
2042 def = obj->symtab + symoffset;
2045 * For skip the symbol if st_shndx is either SHN_UNDEF or
2048 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
2052 * If the symbol is greater than the specified address, or if it
2053 * is further away from addr than the current nearest symbol,
2056 symbol_addr = obj->relocbase + def->st_value;
2057 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
2060 /* Update our idea of the nearest symbol. */
2061 info->dli_sname = obj->strtab + def->st_name;
2062 info->dli_saddr = symbol_addr;
2065 if (info->dli_saddr == addr)
2068 rlock_release(rtld_bind_lock, lockstate);
2073 dlinfo(void *handle, int request, void *p)
2075 const Obj_Entry *obj;
2076 int error, lockstate;
2078 lockstate = rlock_acquire(rtld_bind_lock);
2080 if (handle == NULL || handle == RTLD_SELF) {
2083 retaddr = __builtin_return_address(0); /* __GNUC__ only */
2084 if ((obj = obj_from_addr(retaddr)) == NULL)
2085 _rtld_error("Cannot determine caller's shared object");
2087 obj = dlcheck(handle);
2090 rlock_release(rtld_bind_lock, lockstate);
2096 case RTLD_DI_LINKMAP:
2097 *((struct link_map const **)p) = &obj->linkmap;
2099 case RTLD_DI_ORIGIN:
2100 error = rtld_dirname(obj->path, p);
2103 case RTLD_DI_SERINFOSIZE:
2104 case RTLD_DI_SERINFO:
2105 error = do_search_info(obj, request, (struct dl_serinfo *)p);
2109 _rtld_error("Invalid request %d passed to dlinfo()", request);
2113 rlock_release(rtld_bind_lock, lockstate);
2119 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
2121 struct dl_phdr_info phdr_info;
2122 const Obj_Entry *obj;
2123 int error, bind_lockstate, phdr_lockstate;
2125 phdr_lockstate = wlock_acquire(rtld_phdr_lock);
2126 bind_lockstate = rlock_acquire(rtld_bind_lock);
2130 for (obj = obj_list; obj != NULL; obj = obj->next) {
2131 phdr_info.dlpi_addr = (Elf_Addr)obj->relocbase;
2132 phdr_info.dlpi_name = STAILQ_FIRST(&obj->names) ?
2133 STAILQ_FIRST(&obj->names)->name : obj->path;
2134 phdr_info.dlpi_phdr = obj->phdr;
2135 phdr_info.dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
2136 phdr_info.dlpi_tls_modid = obj->tlsindex;
2137 phdr_info.dlpi_tls_data = obj->tlsinit;
2138 phdr_info.dlpi_adds = obj_loads;
2139 phdr_info.dlpi_subs = obj_loads - obj_count;
2141 if ((error = callback(&phdr_info, sizeof phdr_info, param)) != 0)
2145 rlock_release(rtld_bind_lock, bind_lockstate);
2146 wlock_release(rtld_phdr_lock, phdr_lockstate);
2151 struct fill_search_info_args {
2154 Dl_serinfo *serinfo;
2155 Dl_serpath *serpath;
2160 fill_search_info(const char *dir, size_t dirlen, void *param)
2162 struct fill_search_info_args *arg;
2166 if (arg->request == RTLD_DI_SERINFOSIZE) {
2167 arg->serinfo->dls_cnt ++;
2168 arg->serinfo->dls_size += sizeof(Dl_serpath) + dirlen + 1;
2170 struct dl_serpath *s_entry;
2172 s_entry = arg->serpath;
2173 s_entry->dls_name = arg->strspace;
2174 s_entry->dls_flags = arg->flags;
2176 strncpy(arg->strspace, dir, dirlen);
2177 arg->strspace[dirlen] = '\0';
2179 arg->strspace += dirlen + 1;
2187 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
2189 struct dl_serinfo _info;
2190 struct fill_search_info_args args;
2192 args.request = RTLD_DI_SERINFOSIZE;
2193 args.serinfo = &_info;
2195 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2198 path_enumerate(ld_library_path, fill_search_info, &args);
2199 path_enumerate(obj->rpath, fill_search_info, &args);
2200 path_enumerate(gethints(), fill_search_info, &args);
2201 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
2204 if (request == RTLD_DI_SERINFOSIZE) {
2205 info->dls_size = _info.dls_size;
2206 info->dls_cnt = _info.dls_cnt;
2210 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
2211 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
2215 args.request = RTLD_DI_SERINFO;
2216 args.serinfo = info;
2217 args.serpath = &info->dls_serpath[0];
2218 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
2220 args.flags = LA_SER_LIBPATH;
2221 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
2224 args.flags = LA_SER_RUNPATH;
2225 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
2228 args.flags = LA_SER_CONFIG;
2229 if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
2232 args.flags = LA_SER_DEFAULT;
2233 if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
2239 rtld_dirname(const char *path, char *bname)
2243 /* Empty or NULL string gets treated as "." */
2244 if (path == NULL || *path == '\0') {
2250 /* Strip trailing slashes */
2251 endp = path + strlen(path) - 1;
2252 while (endp > path && *endp == '/')
2255 /* Find the start of the dir */
2256 while (endp > path && *endp != '/')
2259 /* Either the dir is "/" or there are no slashes */
2261 bname[0] = *endp == '/' ? '/' : '.';
2267 } while (endp > path && *endp == '/');
2270 if (endp - path + 2 > PATH_MAX)
2272 _rtld_error("Filename is too long: %s", path);
2276 strncpy(bname, path, endp - path + 1);
2277 bname[endp - path + 1] = '\0';
2282 linkmap_add(Obj_Entry *obj)
2284 struct link_map *l = &obj->linkmap;
2285 struct link_map *prev;
2287 obj->linkmap.l_name = obj->path;
2288 obj->linkmap.l_addr = obj->mapbase;
2289 obj->linkmap.l_ld = obj->dynamic;
2291 /* GDB needs load offset on MIPS to use the symbols */
2292 obj->linkmap.l_offs = obj->relocbase;
2295 if (r_debug.r_map == NULL) {
2301 * Scan to the end of the list, but not past the entry for the
2302 * dynamic linker, which we want to keep at the very end.
2304 for (prev = r_debug.r_map;
2305 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
2306 prev = prev->l_next)
2309 /* Link in the new entry. */
2311 l->l_next = prev->l_next;
2312 if (l->l_next != NULL)
2313 l->l_next->l_prev = l;
2318 linkmap_delete(Obj_Entry *obj)
2320 struct link_map *l = &obj->linkmap;
2322 if (l->l_prev == NULL) {
2323 if ((r_debug.r_map = l->l_next) != NULL)
2324 l->l_next->l_prev = NULL;
2328 if ((l->l_prev->l_next = l->l_next) != NULL)
2329 l->l_next->l_prev = l->l_prev;
2333 * Function for the debugger to set a breakpoint on to gain control.
2335 * The two parameters allow the debugger to easily find and determine
2336 * what the runtime loader is doing and to whom it is doing it.
2338 * When the loadhook trap is hit (r_debug_state, set at program
2339 * initialization), the arguments can be found on the stack:
2341 * +8 struct link_map *m
2342 * +4 struct r_debug *rd
2346 r_debug_state(struct r_debug* rd, struct link_map *m)
2351 * Get address of the pointer variable in the main program.
2353 static const void **
2354 get_program_var_addr(const char *name)
2356 const Obj_Entry *obj;
2359 hash = elf_hash(name);
2360 for (obj = obj_main; obj != NULL; obj = obj->next) {
2363 if ((def = symlook_obj(name, hash, obj, NULL, 0)) != NULL) {
2366 addr = (const void **)(obj->relocbase + def->st_value);
2374 * Set a pointer variable in the main program to the given value. This
2375 * is used to set key variables such as "environ" before any of the
2376 * init functions are called.
2379 set_program_var(const char *name, const void *value)
2383 if ((addr = get_program_var_addr(name)) != NULL) {
2384 dbg("\"%s\": *%p <-- %p", name, addr, value);
2390 * Given a symbol name in a referencing object, find the corresponding
2391 * definition of the symbol. Returns a pointer to the symbol, or NULL if
2392 * no definition was found. Returns a pointer to the Obj_Entry of the
2393 * defining object via the reference parameter DEFOBJ_OUT.
2395 static const Elf_Sym *
2396 symlook_default(const char *name, unsigned long hash, const Obj_Entry *refobj,
2397 const Obj_Entry **defobj_out, const Ver_Entry *ventry, int flags)
2401 const Elf_Sym *symp;
2402 const Obj_Entry *obj;
2403 const Obj_Entry *defobj;
2404 const Objlist_Entry *elm;
2407 donelist_init(&donelist);
2409 /* Look first in the referencing object if linked symbolically. */
2410 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
2411 symp = symlook_obj(name, hash, refobj, ventry, flags);
2418 /* Search all objects loaded at program start up. */
2419 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2420 symp = symlook_list(name, hash, &list_main, &obj, ventry, flags,
2423 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2429 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
2430 STAILQ_FOREACH(elm, &list_global, link) {
2431 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2433 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, ventry,
2436 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2442 /* Search all dlopened DAGs containing the referencing object. */
2443 STAILQ_FOREACH(elm, &refobj->dldags, link) {
2444 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2446 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, ventry,
2449 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2456 * Search the dynamic linker itself, and possibly resolve the
2457 * symbol from there. This is how the application links to
2458 * dynamic linker services such as dlopen. Only the values listed
2459 * in the "exports" array can be resolved from the dynamic linker.
2461 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2462 symp = symlook_obj(name, hash, &obj_rtld, ventry, flags);
2463 if (symp != NULL && is_exported(symp)) {
2470 *defobj_out = defobj;
2474 static const Elf_Sym *
2475 symlook_list(const char *name, unsigned long hash, const Objlist *objlist,
2476 const Obj_Entry **defobj_out, const Ver_Entry *ventry, int flags,
2479 const Elf_Sym *symp;
2481 const Obj_Entry *defobj;
2482 const Objlist_Entry *elm;
2486 STAILQ_FOREACH(elm, objlist, link) {
2487 if (donelist_check(dlp, elm->obj))
2489 if ((symp = symlook_obj(name, hash, elm->obj, ventry, flags)) != NULL) {
2490 if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
2493 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2499 *defobj_out = defobj;
2504 * Search the symbol table of a shared object and all objects needed
2505 * by it for a symbol of the given name. Search order is
2506 * breadth-first. Returns a pointer to the symbol, or NULL if no
2507 * definition was found.
2509 static const Elf_Sym *
2510 symlook_needed(const char *name, unsigned long hash, const Needed_Entry *needed,
2511 const Obj_Entry **defobj_out, const Ver_Entry *ventry, int flags,
2514 const Elf_Sym *def, *def_w;
2515 const Needed_Entry *n;
2516 const Obj_Entry *obj, *defobj, *defobj1;
2520 for (n = needed; n != NULL; n = n->next) {
2521 if ((obj = n->obj) == NULL ||
2522 donelist_check(dlp, obj) ||
2523 (def = symlook_obj(name, hash, obj, ventry, flags)) == NULL)
2526 if (ELF_ST_BIND(def->st_info) != STB_WEAK) {
2527 *defobj_out = defobj;
2532 * There we come when either symbol definition is not found in
2533 * directly needed objects, or found symbol is weak.
2535 for (n = needed; n != NULL; n = n->next) {
2536 if ((obj = n->obj) == NULL)
2538 def_w = symlook_needed(name, hash, obj->needed, &defobj1,
2539 ventry, flags, dlp);
2542 if (def == NULL || ELF_ST_BIND(def_w->st_info) != STB_WEAK) {
2546 if (ELF_ST_BIND(def_w->st_info) != STB_WEAK)
2550 *defobj_out = defobj;
2555 * Search the symbol table of a single shared object for a symbol of
2556 * the given name and version, if requested. Returns a pointer to the
2557 * symbol, or NULL if no definition was found.
2559 * The symbol's hash value is passed in for efficiency reasons; that
2560 * eliminates many recomputations of the hash value.
2563 symlook_obj(const char *name, unsigned long hash, const Obj_Entry *obj,
2564 const Ver_Entry *ventry, int flags)
2566 unsigned long symnum;
2567 const Elf_Sym *vsymp;
2571 if (obj->buckets == NULL)
2576 symnum = obj->buckets[hash % obj->nbuckets];
2578 for (; symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
2579 const Elf_Sym *symp;
2582 if (symnum >= obj->nchains)
2583 return NULL; /* Bad object */
2585 symp = obj->symtab + symnum;
2586 strp = obj->strtab + symp->st_name;
2588 switch (ELF_ST_TYPE(symp->st_info)) {
2592 if (symp->st_value == 0)
2596 if (symp->st_shndx != SHN_UNDEF ||
2597 ((flags & SYMLOOK_IN_PLT) == 0 &&
2598 ELF_ST_TYPE(symp->st_info) == STT_FUNC))
2604 if (name[0] != strp[0] || strcmp(name, strp) != 0)
2607 if (ventry == NULL) {
2608 if (obj->versyms != NULL) {
2609 verndx = VER_NDX(obj->versyms[symnum]);
2610 if (verndx > obj->vernum) {
2611 _rtld_error("%s: symbol %s references wrong version %d",
2612 obj->path, obj->strtab + symnum, verndx);
2616 * If we are not called from dlsym (i.e. this is a normal
2617 * relocation from unversioned binary, accept the symbol
2618 * immediately if it happens to have first version after
2619 * this shared object became versioned. Otherwise, if
2620 * symbol is versioned and not hidden, remember it. If it
2621 * is the only symbol with this name exported by the
2622 * shared object, it will be returned as a match at the
2623 * end of the function. If symbol is global (verndx < 2)
2624 * accept it unconditionally.
2626 if ((flags & SYMLOOK_DLSYM) == 0 && verndx == VER_NDX_GIVEN)
2628 else if (verndx >= VER_NDX_GIVEN) {
2629 if ((obj->versyms[symnum] & VER_NDX_HIDDEN) == 0) {
2639 if (obj->versyms == NULL) {
2640 if (object_match_name(obj, ventry->name)) {
2641 _rtld_error("%s: object %s should provide version %s for "
2642 "symbol %s", obj_rtld.path, obj->path, ventry->name,
2643 obj->strtab + symnum);
2647 verndx = VER_NDX(obj->versyms[symnum]);
2648 if (verndx > obj->vernum) {
2649 _rtld_error("%s: symbol %s references wrong version %d",
2650 obj->path, obj->strtab + symnum, verndx);
2653 if (obj->vertab[verndx].hash != ventry->hash ||
2654 strcmp(obj->vertab[verndx].name, ventry->name)) {
2656 * Version does not match. Look if this is a global symbol
2657 * and if it is not hidden. If global symbol (verndx < 2)
2658 * is available, use it. Do not return symbol if we are
2659 * called by dlvsym, because dlvsym looks for a specific
2660 * version and default one is not what dlvsym wants.
2662 if ((flags & SYMLOOK_DLSYM) ||
2663 (obj->versyms[symnum] & VER_NDX_HIDDEN) ||
2664 (verndx >= VER_NDX_GIVEN))
2671 return (vcount == 1) ? vsymp : NULL;
2675 trace_loaded_objects(Obj_Entry *obj)
2677 char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
2680 if ((main_local = getenv(LD_ "TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
2683 if ((fmt1 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT1")) == NULL)
2684 fmt1 = "\t%o => %p (%x)\n";
2686 if ((fmt2 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT2")) == NULL)
2687 fmt2 = "\t%o (%x)\n";
2689 list_containers = getenv(LD_ "TRACE_LOADED_OBJECTS_ALL");
2691 for (; obj; obj = obj->next) {
2692 Needed_Entry *needed;
2696 if (list_containers && obj->needed != NULL)
2697 printf("%s:\n", obj->path);
2698 for (needed = obj->needed; needed; needed = needed->next) {
2699 if (needed->obj != NULL) {
2700 if (needed->obj->traced && !list_containers)
2702 needed->obj->traced = true;
2703 path = needed->obj->path;
2707 name = (char *)obj->strtab + needed->name;
2708 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
2710 fmt = is_lib ? fmt1 : fmt2;
2711 while ((c = *fmt++) != '\0') {
2737 printf("%s", main_local);
2740 printf("%s", obj_main->path);
2747 printf("%d", sodp->sod_major);
2750 printf("%d", sodp->sod_minor);
2757 printf("%p", needed->obj ? needed->obj->mapbase : 0);
2769 * Unload a dlopened object and its dependencies from memory and from
2770 * our data structures. It is assumed that the DAG rooted in the
2771 * object has already been unreferenced, and that the object has a
2772 * reference count of 0.
2775 unload_object(Obj_Entry *root)
2780 assert(root->refcount == 0);
2783 * Pass over the DAG removing unreferenced objects from
2784 * appropriate lists.
2786 unlink_object(root);
2788 /* Unmap all objects that are no longer referenced. */
2789 linkp = &obj_list->next;
2790 while ((obj = *linkp) != NULL) {
2791 if (obj->refcount == 0) {
2792 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
2794 dbg("unloading \"%s\"", obj->path);
2795 munmap(obj->mapbase, obj->mapsize);
2796 linkmap_delete(obj);
2807 unlink_object(Obj_Entry *root)
2811 if (root->refcount == 0) {
2812 /* Remove the object from the RTLD_GLOBAL list. */
2813 objlist_remove(&list_global, root);
2815 /* Remove the object from all objects' DAG lists. */
2816 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2817 objlist_remove(&elm->obj->dldags, root);
2818 if (elm->obj != root)
2819 unlink_object(elm->obj);
2825 ref_dag(Obj_Entry *root)
2829 STAILQ_FOREACH(elm, &root->dagmembers, link)
2830 elm->obj->refcount++;
2834 unref_dag(Obj_Entry *root)
2838 STAILQ_FOREACH(elm, &root->dagmembers, link)
2839 elm->obj->refcount--;
2843 * Common code for MD __tls_get_addr().
2846 tls_get_addr_common(Elf_Addr** dtvp, int index, size_t offset)
2848 Elf_Addr* dtv = *dtvp;
2851 /* Check dtv generation in case new modules have arrived */
2852 if (dtv[0] != tls_dtv_generation) {
2856 lockstate = wlock_acquire(rtld_bind_lock);
2857 newdtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
2859 if (to_copy > tls_max_index)
2860 to_copy = tls_max_index;
2861 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
2862 newdtv[0] = tls_dtv_generation;
2863 newdtv[1] = tls_max_index;
2865 wlock_release(rtld_bind_lock, lockstate);
2869 /* Dynamically allocate module TLS if necessary */
2870 if (!dtv[index + 1]) {
2871 /* Signal safe, wlock will block out signals. */
2872 lockstate = wlock_acquire(rtld_bind_lock);
2873 if (!dtv[index + 1])
2874 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
2875 wlock_release(rtld_bind_lock, lockstate);
2877 return (void*) (dtv[index + 1] + offset);
2880 /* XXX not sure what variants to use for arm. */
2882 #if defined(__ia64__) || defined(__powerpc__)
2885 * Allocate Static TLS using the Variant I method.
2888 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
2897 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
2900 assert(tcbsize >= TLS_TCB_SIZE);
2901 tcb = calloc(1, tls_static_space - TLS_TCB_SIZE + tcbsize);
2902 tls = (Elf_Addr **)(tcb + tcbsize - TLS_TCB_SIZE);
2904 if (oldtcb != NULL) {
2905 memcpy(tls, oldtcb, tls_static_space);
2908 /* Adjust the DTV. */
2910 for (i = 0; i < dtv[1]; i++) {
2911 if (dtv[i+2] >= (Elf_Addr)oldtcb &&
2912 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
2913 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tls;
2917 dtv = calloc(tls_max_index + 2, sizeof(Elf_Addr));
2919 dtv[0] = tls_dtv_generation;
2920 dtv[1] = tls_max_index;
2922 for (obj = objs; obj; obj = obj->next) {
2923 if (obj->tlsoffset) {
2924 addr = (Elf_Addr)tls + obj->tlsoffset;
2925 memset((void*) (addr + obj->tlsinitsize),
2926 0, obj->tlssize - obj->tlsinitsize);
2928 memcpy((void*) addr, obj->tlsinit,
2930 dtv[obj->tlsindex + 1] = addr;
2939 free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
2942 Elf_Addr tlsstart, tlsend;
2945 assert(tcbsize >= TLS_TCB_SIZE);
2947 tlsstart = (Elf_Addr)tcb + tcbsize - TLS_TCB_SIZE;
2948 tlsend = tlsstart + tls_static_space;
2950 dtv = *(Elf_Addr **)tlsstart;
2952 for (i = 0; i < dtvsize; i++) {
2953 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
2954 free((void*)dtv[i+2]);
2963 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) || \
2967 * Allocate Static TLS using the Variant II method.
2970 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
2975 Elf_Addr *dtv, *olddtv;
2976 Elf_Addr segbase, oldsegbase, addr;
2979 size = round(tls_static_space, tcbalign);
2981 assert(tcbsize >= 2*sizeof(Elf_Addr));
2982 tls = calloc(1, size + tcbsize);
2983 dtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
2985 segbase = (Elf_Addr)(tls + size);
2986 ((Elf_Addr*)segbase)[0] = segbase;
2987 ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
2989 dtv[0] = tls_dtv_generation;
2990 dtv[1] = tls_max_index;
2994 * Copy the static TLS block over whole.
2996 oldsegbase = (Elf_Addr) oldtls;
2997 memcpy((void *)(segbase - tls_static_space),
2998 (const void *)(oldsegbase - tls_static_space),
3002 * If any dynamic TLS blocks have been created tls_get_addr(),
3005 olddtv = ((Elf_Addr**)oldsegbase)[1];
3006 for (i = 0; i < olddtv[1]; i++) {
3007 if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
3008 dtv[i+2] = olddtv[i+2];
3014 * We assume that this block was the one we created with
3015 * allocate_initial_tls().
3017 free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
3019 for (obj = objs; obj; obj = obj->next) {
3020 if (obj->tlsoffset) {
3021 addr = segbase - obj->tlsoffset;
3022 memset((void*) (addr + obj->tlsinitsize),
3023 0, obj->tlssize - obj->tlsinitsize);
3025 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
3026 dtv[obj->tlsindex + 1] = addr;
3031 return (void*) segbase;
3035 free_tls(void *tls, size_t tcbsize, size_t tcbalign)
3040 Elf_Addr tlsstart, tlsend;
3043 * Figure out the size of the initial TLS block so that we can
3044 * find stuff which ___tls_get_addr() allocated dynamically.
3046 size = round(tls_static_space, tcbalign);
3048 dtv = ((Elf_Addr**)tls)[1];
3050 tlsend = (Elf_Addr) tls;
3051 tlsstart = tlsend - size;
3052 for (i = 0; i < dtvsize; i++) {
3053 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] > tlsend)) {
3054 free((void*) dtv[i+2]);
3058 free((void*) tlsstart);
3065 * Allocate TLS block for module with given index.
3068 allocate_module_tls(int index)
3073 for (obj = obj_list; obj; obj = obj->next) {
3074 if (obj->tlsindex == index)
3078 _rtld_error("Can't find module with TLS index %d", index);
3082 p = malloc(obj->tlssize);
3083 memcpy(p, obj->tlsinit, obj->tlsinitsize);
3084 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
3090 allocate_tls_offset(Obj_Entry *obj)
3097 if (obj->tlssize == 0) {
3098 obj->tls_done = true;
3102 if (obj->tlsindex == 1)
3103 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
3105 off = calculate_tls_offset(tls_last_offset, tls_last_size,
3106 obj->tlssize, obj->tlsalign);
3109 * If we have already fixed the size of the static TLS block, we
3110 * must stay within that size. When allocating the static TLS, we
3111 * leave a small amount of space spare to be used for dynamically
3112 * loading modules which use static TLS.
3114 if (tls_static_space) {
3115 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
3119 tls_last_offset = obj->tlsoffset = off;
3120 tls_last_size = obj->tlssize;
3121 obj->tls_done = true;
3127 free_tls_offset(Obj_Entry *obj)
3129 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) || \
3132 * If we were the last thing to allocate out of the static TLS
3133 * block, we give our space back to the 'allocator'. This is a
3134 * simplistic workaround to allow libGL.so.1 to be loaded and
3135 * unloaded multiple times. We only handle the Variant II
3136 * mechanism for now - this really needs a proper allocator.
3138 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
3139 == calculate_tls_end(tls_last_offset, tls_last_size)) {
3140 tls_last_offset -= obj->tlssize;
3147 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
3152 lockstate = wlock_acquire(rtld_bind_lock);
3153 ret = allocate_tls(obj_list, oldtls, tcbsize, tcbalign);
3154 wlock_release(rtld_bind_lock, lockstate);
3159 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
3163 lockstate = wlock_acquire(rtld_bind_lock);
3164 free_tls(tcb, tcbsize, tcbalign);
3165 wlock_release(rtld_bind_lock, lockstate);
3169 object_add_name(Obj_Entry *obj, const char *name)
3175 entry = malloc(sizeof(Name_Entry) + len);
3177 if (entry != NULL) {
3178 strcpy(entry->name, name);
3179 STAILQ_INSERT_TAIL(&obj->names, entry, link);
3184 object_match_name(const Obj_Entry *obj, const char *name)
3188 STAILQ_FOREACH(entry, &obj->names, link) {
3189 if (strcmp(name, entry->name) == 0)
3196 locate_dependency(const Obj_Entry *obj, const char *name)
3198 const Objlist_Entry *entry;
3199 const Needed_Entry *needed;
3201 STAILQ_FOREACH(entry, &list_main, link) {
3202 if (object_match_name(entry->obj, name))
3206 for (needed = obj->needed; needed != NULL; needed = needed->next) {
3207 if (needed->obj == NULL)
3209 if (object_match_name(needed->obj, name))
3212 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
3218 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
3219 const Elf_Vernaux *vna)
3221 const Elf_Verdef *vd;
3222 const char *vername;
3224 vername = refobj->strtab + vna->vna_name;
3225 vd = depobj->verdef;
3227 _rtld_error("%s: version %s required by %s not defined",
3228 depobj->path, vername, refobj->path);
3232 if (vd->vd_version != VER_DEF_CURRENT) {
3233 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
3234 depobj->path, vd->vd_version);
3237 if (vna->vna_hash == vd->vd_hash) {
3238 const Elf_Verdaux *aux = (const Elf_Verdaux *)
3239 ((char *)vd + vd->vd_aux);
3240 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
3243 if (vd->vd_next == 0)
3245 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3247 if (vna->vna_flags & VER_FLG_WEAK)
3249 _rtld_error("%s: version %s required by %s not found",
3250 depobj->path, vername, refobj->path);
3255 rtld_verify_object_versions(Obj_Entry *obj)
3257 const Elf_Verneed *vn;
3258 const Elf_Verdef *vd;
3259 const Elf_Verdaux *vda;
3260 const Elf_Vernaux *vna;
3261 const Obj_Entry *depobj;
3262 int maxvernum, vernum;
3266 * Walk over defined and required version records and figure out
3267 * max index used by any of them. Do very basic sanity checking
3271 while (vn != NULL) {
3272 if (vn->vn_version != VER_NEED_CURRENT) {
3273 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
3274 obj->path, vn->vn_version);
3277 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
3279 vernum = VER_NEED_IDX(vna->vna_other);
3280 if (vernum > maxvernum)
3282 if (vna->vna_next == 0)
3284 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
3286 if (vn->vn_next == 0)
3288 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
3292 while (vd != NULL) {
3293 if (vd->vd_version != VER_DEF_CURRENT) {
3294 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
3295 obj->path, vd->vd_version);
3298 vernum = VER_DEF_IDX(vd->vd_ndx);
3299 if (vernum > maxvernum)
3301 if (vd->vd_next == 0)
3303 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3310 * Store version information in array indexable by version index.
3311 * Verify that object version requirements are satisfied along the
3314 obj->vernum = maxvernum + 1;
3315 obj->vertab = calloc(obj->vernum, sizeof(Ver_Entry));
3318 while (vd != NULL) {
3319 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
3320 vernum = VER_DEF_IDX(vd->vd_ndx);
3321 assert(vernum <= maxvernum);
3322 vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
3323 obj->vertab[vernum].hash = vd->vd_hash;
3324 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
3325 obj->vertab[vernum].file = NULL;
3326 obj->vertab[vernum].flags = 0;
3328 if (vd->vd_next == 0)
3330 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3334 while (vn != NULL) {
3335 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
3336 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
3338 if (check_object_provided_version(obj, depobj, vna))
3340 vernum = VER_NEED_IDX(vna->vna_other);
3341 assert(vernum <= maxvernum);
3342 obj->vertab[vernum].hash = vna->vna_hash;
3343 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
3344 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
3345 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
3346 VER_INFO_HIDDEN : 0;
3347 if (vna->vna_next == 0)
3349 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
3351 if (vn->vn_next == 0)
3353 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
3359 rtld_verify_versions(const Objlist *objlist)
3361 Objlist_Entry *entry;
3365 STAILQ_FOREACH(entry, objlist, link) {
3367 * Skip dummy objects or objects that have their version requirements
3370 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
3372 if (rtld_verify_object_versions(entry->obj) == -1) {
3374 if (ld_tracing == NULL)
3378 if (rc == 0 || ld_tracing != NULL)
3379 rc = rtld_verify_object_versions(&obj_rtld);
3384 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
3389 vernum = VER_NDX(obj->versyms[symnum]);
3390 if (vernum >= obj->vernum) {
3391 _rtld_error("%s: symbol %s has wrong verneed value %d",
3392 obj->path, obj->strtab + symnum, vernum);
3393 } else if (obj->vertab[vernum].hash != 0) {
3394 return &obj->vertab[vernum];