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.
26 * $FreeBSD: src/libexec/rtld-elf/rtld.c,v 1.43.2.15 2003/02/20 20:42:46 kan Exp $
27 * $DragonFly: src/libexec/rtld-elf/rtld.c,v 1.29 2008/01/08 00:02:04 corecode Exp $
31 * Dynamic linker for ELF.
33 * John Polstra <jdp@polstra.com>.
37 #error "GCC is needed to compile this file"
40 #include <sys/param.h>
43 #include <sys/resident.h>
46 #include <machine/tls.h>
61 #define PATH_RTLD "/usr/libexec/ld-elf.so.2"
62 #define LD_ARY_CACHE 16
65 typedef void (*func_ptr_type)();
66 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg);
69 * This structure provides a reentrant way to keep a list of objects and
70 * check which ones have already been processed in some way.
72 typedef struct Struct_DoneList {
73 const Obj_Entry **objs; /* Array of object pointers */
74 unsigned int num_alloc; /* Allocated size of the array */
75 unsigned int num_used; /* Number of array slots used */
79 * Function declarations.
81 static void die(void);
82 static void digest_dynamic(Obj_Entry *, int);
83 static const char *_getenv_ld(const char *id);
84 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
85 static Obj_Entry *dlcheck(void *);
86 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
87 static bool donelist_check(DoneList *, const Obj_Entry *);
88 static void errmsg_restore(char *);
89 static char *errmsg_save(void);
90 static void *fill_search_info(const char *, size_t, void *);
91 static char *find_library(const char *, const Obj_Entry *);
92 static Obj_Entry *find_object(const char *);
93 static Obj_Entry *find_object2(const char *, int *, struct stat *);
94 static const char *gethints(void);
95 static void init_dag(Obj_Entry *);
96 static void init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *);
97 static void init_rtld(caddr_t);
98 static void initlist_add_neededs(Needed_Entry *needed, Objlist *list);
99 static void initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail,
101 static bool is_exported(const Elf_Sym *);
102 static void linkmap_add(Obj_Entry *);
103 static void linkmap_delete(Obj_Entry *);
104 static int load_needed_objects(Obj_Entry *);
105 static int load_preload_objects(void);
106 static Obj_Entry *load_object(char *);
107 static void lock_check(void);
108 static Obj_Entry *obj_from_addr(const void *);
109 static void objlist_call_fini(Objlist *);
110 static void objlist_call_init(Objlist *);
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 *name);
124 static void set_program_var(const char *, const void *);
125 static const Elf_Sym *symlook_default(const char *, unsigned long hash,
126 const Obj_Entry *refobj, const Obj_Entry **defobj_out, bool in_plt);
127 static const Elf_Sym *symlook_list(const char *, unsigned long,
128 const Objlist *, const Obj_Entry **, bool in_plt, DoneList *);
129 static const Elf_Sym *symlook_needed(const char *, unsigned long,
130 const Needed_Entry *, const Obj_Entry **, bool in_plt, DoneList *);
131 static void trace_loaded_objects(Obj_Entry *obj);
132 static void unlink_object(Obj_Entry *);
133 static void unload_object(Obj_Entry *);
134 static void unref_dag(Obj_Entry *);
136 void r_debug_state(struct r_debug*, struct link_map*);
141 static char *error_message; /* Message for dlerror(), or NULL */
142 struct r_debug r_debug; /* for GDB; */
143 static bool trust; /* False for setuid and setgid programs */
144 static const char *ld_bind_now; /* Environment variable for immediate binding */
145 static const char *ld_debug; /* Environment variable for debugging */
146 static const char *ld_library_path; /* Environment variable for search path */
147 static char *ld_preload; /* Environment variable for libraries to
149 static const char *ld_tracing; /* Called from ldd(1) to print libs */
150 /* Optional function call tracing hook */
151 static int (*rtld_functrace)(const char *caller_obj,
152 const char *callee_obj,
153 const char *callee_func,
155 static Obj_Entry *rtld_functrace_obj; /* Object thereof */
156 static Obj_Entry *obj_list; /* Head of linked list of shared objects */
157 static Obj_Entry **obj_tail; /* Link field of last object in list */
158 static Obj_Entry **preload_tail;
159 static Obj_Entry *obj_main; /* The main program shared object */
160 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
161 static unsigned int obj_count; /* Number of objects in obj_list */
162 static int ld_resident; /* Non-zero if resident */
163 static const char *ld_ary[LD_ARY_CACHE];
165 static Objlist initlist;
167 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
168 STAILQ_HEAD_INITIALIZER(list_global);
169 static Objlist list_main = /* Objects loaded at program startup */
170 STAILQ_HEAD_INITIALIZER(list_main);
171 static Objlist list_fini = /* Objects needing fini() calls */
172 STAILQ_HEAD_INITIALIZER(list_fini);
174 static LockInfo lockinfo;
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
184 * These are the functions the dynamic linker exports to application
185 * programs. They are the only symbols the dynamic linker is willing
186 * to export from itself.
188 static func_ptr_type exports[] = {
189 (func_ptr_type) &_rtld_error,
190 (func_ptr_type) &dlclose,
191 (func_ptr_type) &dlerror,
192 (func_ptr_type) &dlopen,
193 (func_ptr_type) &dlsym,
194 (func_ptr_type) &dladdr,
195 (func_ptr_type) &dlinfo,
197 (func_ptr_type) &___tls_get_addr,
199 (func_ptr_type) &__tls_get_addr,
200 (func_ptr_type) &__tls_get_addr_tcb,
201 (func_ptr_type) &_rtld_allocate_tls,
202 (func_ptr_type) &_rtld_free_tls,
203 (func_ptr_type) &_rtld_call_init,
208 * Global declarations normally provided by crt1. The dynamic linker is
209 * not built with crt1, so we have to provide them ourselves.
215 * Globals to control TLS allocation.
217 size_t tls_last_offset; /* Static TLS offset of last module */
218 size_t tls_last_size; /* Static TLS size of last module */
219 size_t tls_static_space; /* Static TLS space allocated */
220 int tls_dtv_generation = 1; /* Used to detect when dtv size changes */
221 int tls_max_index = 1; /* Largest module index allocated */
224 * Fill in a DoneList with an allocation large enough to hold all of
225 * the currently-loaded objects. Keep this as a macro since it calls
226 * alloca and we want that to occur within the scope of the caller.
228 #define donelist_init(dlp) \
229 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
230 assert((dlp)->objs != NULL), \
231 (dlp)->num_alloc = obj_count, \
237 lockinfo.rlock_acquire(lockinfo.thelock);
238 atomic_incr_int(&lockinfo.rcount);
245 lockinfo.wlock_acquire(lockinfo.thelock);
246 atomic_incr_int(&lockinfo.wcount);
253 atomic_decr_int(&lockinfo.rcount);
254 lockinfo.rlock_release(lockinfo.thelock);
260 atomic_decr_int(&lockinfo.wcount);
261 lockinfo.wlock_release(lockinfo.thelock);
265 * Main entry point for dynamic linking. The first argument is the
266 * stack pointer. The stack is expected to be laid out as described
267 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
268 * Specifically, the stack pointer points to a word containing
269 * ARGC. Following that in the stack is a null-terminated sequence
270 * of pointers to argument strings. Then comes a null-terminated
271 * sequence of pointers to environment strings. Finally, there is a
272 * sequence of "auxiliary vector" entries.
274 * The second argument points to a place to store the dynamic linker's
275 * exit procedure pointer and the third to a place to store the main
278 * The return value is the main program's entry point.
282 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
284 Elf_Auxinfo *aux_info[AT_COUNT];
292 Objlist_Entry *entry;
295 ld_index = 0; /* don't use old env cache in case we are resident */
298 * On entry, the dynamic linker itself has not been relocated yet.
299 * Be very careful not to reference any global data until after
300 * init_rtld has returned. It is OK to reference file-scope statics
301 * and string constants, and to call static and global functions.
304 /* Find the auxiliary vector on the stack. */
307 sp += argc + 1; /* Skip over arguments and NULL terminator */
311 * If we aren't already resident we have to dig out some more info.
312 * Note that auxinfo does not exist when we are resident.
314 if (ld_resident == 0) {
315 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
317 aux = (Elf_Auxinfo *) sp;
319 /* Digest the auxiliary vector. */
320 for (i = 0; i < AT_COUNT; i++)
322 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
323 if (auxp->a_type < AT_COUNT)
324 aux_info[auxp->a_type] = auxp;
327 /* Initialize and relocate ourselves. */
328 assert(aux_info[AT_BASE] != NULL);
329 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
332 __progname = obj_rtld.path;
333 argv0 = argv[0] != NULL ? argv[0] : "(null)";
336 trust = (geteuid() == getuid()) && (getegid() == getgid());
338 ld_bind_now = _getenv_ld("LD_BIND_NOW");
340 ld_debug = _getenv_ld("LD_DEBUG");
341 ld_library_path = _getenv_ld("LD_LIBRARY_PATH");
342 ld_preload = (char *)_getenv_ld("LD_PRELOAD");
344 ld_tracing = _getenv_ld("LD_TRACE_LOADED_OBJECTS");
346 if (ld_debug != NULL && *ld_debug != '\0')
348 dbg("%s is initialized, base address = %p", __progname,
349 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
350 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
351 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
354 * If we are resident we can skip work that we have already done.
355 * Note that the stack is reset and there is no Elf_Auxinfo
356 * when running from a resident image, and the static globals setup
357 * between here and resident_skip will have already been setup.
363 * Load the main program, or process its program header if it is
366 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
367 int fd = aux_info[AT_EXECFD]->a_un.a_val;
368 dbg("loading main program");
369 obj_main = map_object(fd, argv0, NULL);
371 if (obj_main == NULL)
373 } else { /* Main program already loaded. */
374 const Elf_Phdr *phdr;
378 dbg("processing main program's program header");
379 assert(aux_info[AT_PHDR] != NULL);
380 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
381 assert(aux_info[AT_PHNUM] != NULL);
382 phnum = aux_info[AT_PHNUM]->a_un.a_val;
383 assert(aux_info[AT_PHENT] != NULL);
384 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
385 assert(aux_info[AT_ENTRY] != NULL);
386 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
387 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
391 obj_main->path = xstrdup(argv0);
392 obj_main->mainprog = true;
395 * Get the actual dynamic linker pathname from the executable if
396 * possible. (It should always be possible.) That ensures that
397 * gdb will find the right dynamic linker even if a non-standard
400 if (obj_main->interp != NULL &&
401 strcmp(obj_main->interp, obj_rtld.path) != 0) {
403 obj_rtld.path = xstrdup(obj_main->interp);
404 __progname = obj_rtld.path;
407 digest_dynamic(obj_main, 0);
409 linkmap_add(obj_main);
410 linkmap_add(&obj_rtld);
412 /* Link the main program into the list of objects. */
413 *obj_tail = obj_main;
414 obj_tail = &obj_main->next;
416 obj_main->refcount++;
417 /* Make sure we don't call the main program's init and fini functions. */
418 obj_main->init = obj_main->fini = NULL;
420 /* Initialize a fake symbol for resolving undefined weak references. */
421 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
422 sym_zero.st_shndx = SHN_ABS;
424 dbg("loading LD_PRELOAD libraries");
425 if (load_preload_objects() == -1)
427 preload_tail = obj_tail;
429 dbg("loading needed objects");
430 if (load_needed_objects(obj_main) == -1)
433 /* Make a list of all objects loaded at startup. */
434 for (obj = obj_list; obj != NULL; obj = obj->next)
435 objlist_push_tail(&list_main, obj);
439 if (ld_tracing) { /* We're done */
440 trace_loaded_objects(obj_main);
444 if (ld_resident) /* XXX clean this up! */
447 if (getenv("LD_DUMP_REL_PRE") != NULL) {
448 dump_relocations(obj_main);
452 /* setup TLS for main thread */
453 dbg("initializing initial thread local storage");
454 STAILQ_FOREACH(entry, &list_main, link) {
456 * Allocate all the initial objects out of the static TLS
457 * block even if they didn't ask for it.
459 allocate_tls_offset(entry->obj);
462 tls_static_space = tls_last_offset + RTLD_STATIC_TLS_EXTRA;
465 * Do not try to allocate the TLS here, let libc do it itself.
466 * (crt1 for the program will call _init_tls())
469 if (relocate_objects(obj_main,
470 ld_bind_now != NULL && *ld_bind_now != '\0', &obj_rtld) == -1)
473 dbg("doing copy relocations");
474 if (do_copy_relocations(obj_main) == -1)
479 if (_getenv_ld("LD_RESIDENT_UNREGISTER_NOW")) {
480 if (exec_sys_unregister(-1) < 0) {
481 dbg("exec_sys_unregister failed %d\n", errno);
484 dbg("exec_sys_unregister success\n");
488 if (getenv("LD_DUMP_REL_POST") != NULL) {
489 dump_relocations(obj_main);
493 dbg("initializing key program variables");
494 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
495 set_program_var("environ", env);
497 if (_getenv_ld("LD_RESIDENT_REGISTER_NOW")) {
498 extern void resident_start(void);
500 if (exec_sys_register(resident_start) < 0) {
501 dbg("exec_sys_register failed %d\n", errno);
504 dbg("exec_sys_register success\n");
508 dbg("initializing thread locks");
509 lockdflt_init(&lockinfo);
510 lockinfo.thelock = lockinfo.lock_create(lockinfo.context);
512 /* Make a list of init functions to call. */
513 objlist_init(&initlist);
514 initlist_add_objects(obj_list, preload_tail, &initlist);
516 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
519 * Do NOT call the initlist here, give libc a chance to set up
520 * the initial TLS segment. crt1 will then call _rtld_call_init().
523 dbg("transferring control to program entry point = %p", obj_main->entry);
525 /* Return the exit procedure and the program entry point. */
526 *exit_proc = rtld_exit;
528 return (func_ptr_type) obj_main->entry;
532 * Call the initialization list for dynamically loaded libraries.
533 * (called from crt1.c).
536 _rtld_call_init(void)
538 objlist_call_init(&initlist);
540 objlist_clear(&initlist);
545 _rtld_bind(Obj_Entry *obj, Elf_Size reloff, void *stack)
549 const Obj_Entry *defobj;
556 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
558 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
560 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
561 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL);
565 target = (Elf_Addr)(defobj->relocbase + def->st_value);
567 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
568 defobj->strtab + def->st_name, basename(obj->path),
569 (void *)target, basename(defobj->path));
573 * If we have a function call tracing hook, and the
574 * hook would like to keep tracing this one function,
575 * prevent the relocation so we will wind up here
576 * the next time again.
578 * We don't want to functrace calls from the functracer
579 * to avoid recursive loops.
581 if (rtld_functrace != NULL && obj != rtld_functrace_obj) {
582 if (rtld_functrace(obj->path,
584 defobj->strtab + def->st_name,
590 reloc_jmpslot(where, target);
595 * Error reporting function. Use it like printf. If formats the message
596 * into a buffer, and sets things up so that the next call to dlerror()
597 * will return the message.
600 _rtld_error(const char *fmt, ...)
602 static char buf[512];
606 vsnprintf(buf, sizeof buf, fmt, ap);
612 * Return a dynamically-allocated copy of the current error message, if any.
617 return error_message == NULL ? NULL : xstrdup(error_message);
621 * Restore the current error message from a copy which was previously saved
622 * by errmsg_save(). The copy is freed.
625 errmsg_restore(char *saved_msg)
627 if (saved_msg == NULL)
628 error_message = NULL;
630 _rtld_error("%s", saved_msg);
636 basename(const char *name)
638 const char *p = strrchr(name, '/');
639 return p != NULL ? p + 1 : name;
645 const char *msg = dlerror();
653 * Process a shared object's DYNAMIC section, and save the important
654 * information in its Obj_Entry structure.
657 digest_dynamic(Obj_Entry *obj, int early)
660 Needed_Entry **needed_tail = &obj->needed;
661 const Elf_Dyn *dyn_rpath = NULL;
662 int plttype = DT_REL;
664 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
665 switch (dynp->d_tag) {
668 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
672 obj->relsize = dynp->d_un.d_val;
676 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
680 obj->pltrel = (const Elf_Rel *)
681 (obj->relocbase + dynp->d_un.d_ptr);
685 obj->pltrelsize = dynp->d_un.d_val;
689 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
693 obj->relasize = dynp->d_un.d_val;
697 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
701 plttype = dynp->d_un.d_val;
702 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
706 obj->symtab = (const Elf_Sym *)
707 (obj->relocbase + dynp->d_un.d_ptr);
711 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
715 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
719 obj->strsize = dynp->d_un.d_val;
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.
767 /* Not used by the dynamic linker. */
771 obj->init = (InitFunc) (obj->relocbase + dynp->d_un.d_ptr);
775 obj->fini = (InitFunc) (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 %d = %#x", dynp->d_tag, dynp->d_tag);
810 if (plttype == DT_RELA) {
811 obj->pltrela = (const Elf_Rela *) obj->pltrel;
813 obj->pltrelasize = obj->pltrelsize;
817 if (dyn_rpath != NULL)
818 obj->rpath = obj->strtab + dyn_rpath->d_un.d_val;
822 * Process a shared object's program header. This is used only for the
823 * main program, when the kernel has already loaded the main program
824 * into memory before calling the dynamic linker. It creates and
825 * returns an Obj_Entry structure.
828 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
831 const Elf_Phdr *phlimit = phdr + phnum;
836 for (ph = phdr; ph < phlimit; ph++) {
837 switch (ph->p_type) {
840 if ((const Elf_Phdr *)ph->p_vaddr != phdr) {
841 _rtld_error("%s: invalid PT_PHDR", path);
844 obj->phdr = (const Elf_Phdr *) ph->p_vaddr;
845 obj->phsize = ph->p_memsz;
849 obj->interp = (const char *) ph->p_vaddr;
853 if (nsegs == 0) { /* First load segment */
854 obj->vaddrbase = trunc_page(ph->p_vaddr);
855 obj->mapbase = (caddr_t) obj->vaddrbase;
856 obj->relocbase = obj->mapbase - obj->vaddrbase;
857 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
859 } else { /* Last load segment */
860 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
867 obj->dynamic = (const Elf_Dyn *) ph->p_vaddr;
872 obj->tlssize = ph->p_memsz;
873 obj->tlsalign = ph->p_align;
874 obj->tlsinitsize = ph->p_filesz;
875 obj->tlsinit = (void*) ph->p_vaddr;
880 _rtld_error("%s: too few PT_LOAD segments", path);
889 dlcheck(void *handle)
893 for (obj = obj_list; obj != NULL; obj = obj->next)
894 if (obj == (Obj_Entry *) handle)
897 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
898 _rtld_error("Invalid shared object handle %p", handle);
905 * If the given object is already in the donelist, return true. Otherwise
906 * add the object to the list and return false.
909 donelist_check(DoneList *dlp, const Obj_Entry *obj)
913 for (i = 0; i < dlp->num_used; i++)
914 if (dlp->objs[i] == obj)
917 * Our donelist allocation should always be sufficient. But if
918 * our threads locking isn't working properly, more shared objects
919 * could have been loaded since we allocated the list. That should
920 * never happen, but we'll handle it properly just in case it does.
922 if (dlp->num_used < dlp->num_alloc)
923 dlp->objs[dlp->num_used++] = obj;
928 * Hash function for symbol table lookup. Don't even think about changing
929 * this. It is specified by the System V ABI.
932 elf_hash(const char *name)
934 const unsigned char *p = (const unsigned char *) name;
940 if ((g = h & 0xf0000000) != 0)
948 * Find the library with the given name, and return its full pathname.
949 * The returned string is dynamically allocated. Generates an error
950 * message and returns NULL if the library cannot be found.
952 * If the second argument is non-NULL, then it refers to an already-
953 * loaded shared object, whose library search path will be searched.
955 * The search order is:
957 * rpath in the referencing file
962 find_library(const char *name, const Obj_Entry *refobj)
966 if (strchr(name, '/') != NULL) { /* Hard coded pathname */
967 if (name[0] != '/' && !trust) {
968 _rtld_error("Absolute pathname required for shared object \"%s\"",
972 return xstrdup(name);
975 dbg(" Searching for \"%s\"", name);
977 if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
979 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
980 (pathname = search_library_path(name, gethints())) != NULL ||
981 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
984 if(refobj != NULL && refobj->path != NULL) {
985 _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
986 name, basename(refobj->path));
988 _rtld_error("Shared object \"%s\" not found", name);
994 * Given a symbol number in a referencing object, find the corresponding
995 * definition of the symbol. Returns a pointer to the symbol, or NULL if
996 * no definition was found. Returns a pointer to the Obj_Entry of the
997 * defining object via the reference parameter DEFOBJ_OUT.
1000 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1001 const Obj_Entry **defobj_out, bool in_plt, SymCache *cache)
1005 const Obj_Entry *defobj;
1010 * If we have already found this symbol, get the information from
1013 if (symnum >= refobj->nchains)
1014 return NULL; /* Bad object */
1015 if (cache != NULL && cache[symnum].sym != NULL) {
1016 *defobj_out = cache[symnum].obj;
1017 return cache[symnum].sym;
1020 ref = refobj->symtab + symnum;
1021 name = refobj->strtab + ref->st_name;
1025 * We don't have to do a full scale lookup if the symbol is local.
1026 * We know it will bind to the instance in this load module; to
1027 * which we already have a pointer (ie ref). By not doing a lookup,
1028 * we not only improve performance, but it also avoids unresolvable
1029 * symbols when local symbols are not in the hash table.
1031 * This might occur for TLS module relocations, which simply use
1034 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1035 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1036 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1039 hash = elf_hash(name);
1040 def = symlook_default(name, hash, refobj, &defobj, in_plt);
1047 * If we found no definition and the reference is weak, treat the
1048 * symbol as having the value zero.
1050 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1056 *defobj_out = defobj;
1057 /* Record the information in the cache to avoid subsequent lookups. */
1058 if (cache != NULL) {
1059 cache[symnum].sym = def;
1060 cache[symnum].obj = defobj;
1063 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1068 * Return the search path from the ldconfig hints file, reading it if
1069 * necessary. Returns NULL if there are problems with the hints file,
1070 * or if the search path there is empty.
1077 if (hints == NULL) {
1079 struct elfhints_hdr hdr;
1082 /* Keep from trying again in case the hints file is bad. */
1085 if ((fd = open(_PATH_ELF_HINTS, O_RDONLY)) == -1)
1087 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1088 hdr.magic != ELFHINTS_MAGIC ||
1093 p = xmalloc(hdr.dirlistlen + 1);
1094 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1095 read(fd, p, hdr.dirlistlen + 1) != hdr.dirlistlen + 1) {
1103 return hints[0] != '\0' ? hints : NULL;
1107 init_dag(Obj_Entry *root)
1111 donelist_init(&donelist);
1112 init_dag1(root, root, &donelist);
1116 init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *dlp)
1118 const Needed_Entry *needed;
1120 if (donelist_check(dlp, obj))
1122 objlist_push_tail(&obj->dldags, root);
1123 objlist_push_tail(&root->dagmembers, obj);
1124 for (needed = obj->needed; needed != NULL; needed = needed->next)
1125 if (needed->obj != NULL)
1126 init_dag1(root, needed->obj, dlp);
1130 * Initialize the dynamic linker. The argument is the address at which
1131 * the dynamic linker has been mapped into memory. The primary task of
1132 * this function is to relocate the dynamic linker.
1135 init_rtld(caddr_t mapbase)
1137 Obj_Entry objtmp; /* Temporary rtld object */
1140 * Conjure up an Obj_Entry structure for the dynamic linker.
1142 * The "path" member can't be initialized yet because string constatns
1143 * cannot yet be acessed. Below we will set it correctly.
1145 memset(&objtmp, 0, sizeof(objtmp));
1148 objtmp.mapbase = mapbase;
1150 objtmp.relocbase = mapbase;
1152 if (&_DYNAMIC != 0) {
1153 objtmp.dynamic = rtld_dynamic(&objtmp);
1154 digest_dynamic(&objtmp, 1);
1155 assert(objtmp.needed == NULL);
1156 assert(!objtmp.textrel);
1159 * Temporarily put the dynamic linker entry into the object list, so
1160 * that symbols can be found.
1163 relocate_objects(&objtmp, true, &objtmp);
1166 /* Initialize the object list. */
1167 obj_tail = &obj_list;
1169 /* Now that non-local variables can be accesses, copy out obj_rtld. */
1170 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1172 /* Replace the path with a dynamically allocated copy. */
1173 obj_rtld.path = xstrdup(PATH_RTLD);
1175 r_debug.r_brk = r_debug_state;
1176 r_debug.r_state = RT_CONSISTENT;
1180 * Add the init functions from a needed object list (and its recursive
1181 * needed objects) to "list". This is not used directly; it is a helper
1182 * function for initlist_add_objects(). The write lock must be held
1183 * when this function is called.
1186 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1188 /* Recursively process the successor needed objects. */
1189 if (needed->next != NULL)
1190 initlist_add_neededs(needed->next, list);
1192 /* Process the current needed object. */
1193 if (needed->obj != NULL)
1194 initlist_add_objects(needed->obj, &needed->obj->next, list);
1198 * Scan all of the DAGs rooted in the range of objects from "obj" to
1199 * "tail" and add their init functions to "list". This recurses over
1200 * the DAGs and ensure the proper init ordering such that each object's
1201 * needed libraries are initialized before the object itself. At the
1202 * same time, this function adds the objects to the global finalization
1203 * list "list_fini" in the opposite order. The write lock must be
1204 * held when this function is called.
1207 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1211 obj->init_done = true;
1213 /* Recursively process the successor objects. */
1214 if (&obj->next != tail)
1215 initlist_add_objects(obj->next, tail, list);
1217 /* Recursively process the needed objects. */
1218 if (obj->needed != NULL)
1219 initlist_add_neededs(obj->needed, list);
1221 /* Add the object to the init list. */
1222 if (obj->init != NULL)
1223 objlist_push_tail(list, obj);
1225 /* Add the object to the global fini list in the reverse order. */
1226 if (obj->fini != NULL)
1227 objlist_push_head(&list_fini, obj);
1231 is_exported(const Elf_Sym *def)
1234 const func_ptr_type *p;
1236 value = (Elf_Addr)(obj_rtld.relocbase + def->st_value);
1237 for (p = exports; *p != NULL; p++) {
1238 if ((Elf_Addr)(*p) == value)
1245 * Given a shared object, traverse its list of needed objects, and load
1246 * each of them. Returns 0 on success. Generates an error message and
1247 * returns -1 on failure.
1250 load_needed_objects(Obj_Entry *first)
1254 for (obj = first; obj != NULL; obj = obj->next) {
1255 Needed_Entry *needed;
1257 for (needed = obj->needed; needed != NULL; needed = needed->next) {
1258 const char *name = obj->strtab + needed->name;
1259 char *path = find_library(name, obj);
1262 if (path == NULL && !ld_tracing)
1266 needed->obj = load_object(path);
1267 if (needed->obj == NULL && !ld_tracing)
1268 return -1; /* XXX - cleanup */
1276 #define RTLD_FUNCTRACE "_rtld_functrace"
1279 load_preload_objects(void)
1281 char *p = ld_preload;
1282 static const char delim[] = " \t:;";
1287 p += strspn(p, delim);
1288 while (*p != '\0') {
1289 size_t len = strcspn(p, delim);
1297 if ((path = find_library(p, NULL)) == NULL)
1299 obj = load_object(path);
1301 return -1; /* XXX - cleanup */
1304 p += strspn(p, delim);
1306 /* Check for the magic tracing function */
1307 sym = symlook_obj(RTLD_FUNCTRACE, elf_hash(RTLD_FUNCTRACE), obj, true);
1309 rtld_functrace = (void *)(obj->relocbase + sym->st_value);
1310 rtld_functrace_obj = obj;
1317 * Returns a pointer to the Obj_Entry for the object with the given path.
1318 * Returns NULL if no matching object was found.
1321 find_object(const char *path)
1325 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
1326 if (strcmp(obj->path, path) == 0)
1333 * Returns a pointer to the Obj_Entry for the object matching device and
1334 * inode of the given path. If no matching object was found, the descriptor
1335 * is returned in fd.
1336 * Returns with obj == NULL && fd == -1 on error.
1339 find_object2(const char *path, int *fd, struct stat *sb)
1343 if ((*fd = open(path, O_RDONLY)) == -1) {
1344 _rtld_error("Cannot open \"%s\"", path);
1348 if (fstat(*fd, sb) == -1) {
1349 _rtld_error("Cannot fstat \"%s\"", path);
1355 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
1356 if (obj->ino == sb->st_ino && obj->dev == sb->st_dev) {
1366 * Load a shared object into memory, if it is not already loaded. The
1367 * argument must be a string allocated on the heap. This function assumes
1368 * responsibility for freeing it when necessary.
1370 * Returns a pointer to the Obj_Entry for the object. Returns NULL
1374 load_object(char *path)
1380 obj = find_object(path);
1387 obj = find_object2(path, &fd, &sb);
1392 } else if (fd == -1) {
1397 dbg("loading \"%s\"", path);
1398 obj = map_object(fd, path, &sb);
1406 digest_dynamic(obj, 0);
1409 obj_tail = &obj->next;
1411 linkmap_add(obj); /* for GDB & dlinfo() */
1413 dbg(" %p .. %p: %s", obj->mapbase, obj->mapbase + obj->mapsize - 1,
1416 dbg(" WARNING: %s has impure text", obj->path);
1423 * Check for locking violations and die if one is found.
1430 rcount = lockinfo.rcount;
1431 wcount = lockinfo.wcount;
1432 assert(rcount >= 0);
1433 assert(wcount >= 0);
1434 if (wcount > 1 || (wcount != 0 && rcount != 0)) {
1435 _rtld_error("Application locking error: %d readers and %d writers"
1436 " in dynamic linker. See DLLOCKINIT(3) in manual pages.",
1443 obj_from_addr(const void *addr)
1447 for (obj = obj_list; obj != NULL; obj = obj->next) {
1448 if (addr < (void *) obj->mapbase)
1450 if (addr < (void *) (obj->mapbase + obj->mapsize))
1457 * Call the finalization functions for each of the objects in "list"
1458 * which are unreferenced. All of the objects are expected to have
1459 * non-NULL fini functions.
1462 objlist_call_fini(Objlist *list)
1468 * Preserve the current error message since a fini function might
1469 * call into the dynamic linker and overwrite it.
1471 saved_msg = errmsg_save();
1472 STAILQ_FOREACH(elm, list, link) {
1473 if (elm->obj->refcount == 0) {
1474 dbg("calling fini function for %s", elm->obj->path);
1475 (*elm->obj->fini)();
1478 errmsg_restore(saved_msg);
1482 * Call the initialization functions for each of the objects in
1483 * "list". All of the objects are expected to have non-NULL init
1487 objlist_call_init(Objlist *list)
1493 * Preserve the current error message since an init function might
1494 * call into the dynamic linker and overwrite it.
1496 saved_msg = errmsg_save();
1497 STAILQ_FOREACH(elm, list, link) {
1498 dbg("calling init function for %s", elm->obj->path);
1499 (*elm->obj->init)();
1501 errmsg_restore(saved_msg);
1505 objlist_clear(Objlist *list)
1509 while (!STAILQ_EMPTY(list)) {
1510 elm = STAILQ_FIRST(list);
1511 STAILQ_REMOVE_HEAD(list, link);
1516 static Objlist_Entry *
1517 objlist_find(Objlist *list, const Obj_Entry *obj)
1521 STAILQ_FOREACH(elm, list, link)
1522 if (elm->obj == obj)
1528 objlist_init(Objlist *list)
1534 objlist_push_head(Objlist *list, Obj_Entry *obj)
1538 elm = NEW(Objlist_Entry);
1540 STAILQ_INSERT_HEAD(list, elm, link);
1544 objlist_push_tail(Objlist *list, Obj_Entry *obj)
1548 elm = NEW(Objlist_Entry);
1550 STAILQ_INSERT_TAIL(list, elm, link);
1554 objlist_remove(Objlist *list, Obj_Entry *obj)
1558 if ((elm = objlist_find(list, obj)) != NULL) {
1559 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1565 * Remove all of the unreferenced objects from "list".
1568 objlist_remove_unref(Objlist *list)
1573 STAILQ_INIT(&newlist);
1574 while (!STAILQ_EMPTY(list)) {
1575 elm = STAILQ_FIRST(list);
1576 STAILQ_REMOVE_HEAD(list, link);
1577 if (elm->obj->refcount == 0)
1580 STAILQ_INSERT_TAIL(&newlist, elm, link);
1586 * Relocate newly-loaded shared objects. The argument is a pointer to
1587 * the Obj_Entry for the first such object. All objects from the first
1588 * to the end of the list of objects are relocated. Returns 0 on success,
1592 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj)
1596 for (obj = first; obj != NULL; obj = obj->next) {
1598 dbg("relocating \"%s\"", obj->path);
1599 if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
1600 obj->symtab == NULL || obj->strtab == NULL) {
1601 _rtld_error("%s: Shared object has no run-time symbol table",
1607 /* There are relocations to the write-protected text segment. */
1608 if (mprotect(obj->mapbase, obj->textsize,
1609 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
1610 _rtld_error("%s: Cannot write-enable text segment: %s",
1611 obj->path, strerror(errno));
1616 /* Process the non-PLT relocations. */
1617 if (reloc_non_plt(obj, rtldobj))
1621 * Reprotect the text segment. Make sure it is included in the
1622 * core dump since we modified it. This unfortunately causes the
1623 * entire text segment to core-out but we don't have much of a
1624 * choice. We could try to only reenable core dumps on pages
1625 * in which relocations occured but that is likely most of the text
1626 * pages anyway, and even that would not work because the rest of
1627 * the text pages would wind up as a read-only OBJT_DEFAULT object
1628 * (created due to our modifications) backed by the original OBJT_VNODE
1629 * object, and the ELF coredump code is currently only able to dump
1630 * vnode records for pure vnode-backed mappings, not vnode backings
1631 * to memory objects.
1634 madvise(obj->mapbase, obj->textsize, MADV_CORE);
1635 if (mprotect(obj->mapbase, obj->textsize,
1636 PROT_READ|PROT_EXEC) == -1) {
1637 _rtld_error("%s: Cannot write-protect text segment: %s",
1638 obj->path, strerror(errno));
1643 /* Process the PLT relocations. */
1644 if (reloc_plt(obj) == -1)
1646 /* Relocate the jump slots if we are doing immediate binding. */
1647 if (obj->bind_now || bind_now)
1648 if (reloc_jmpslots(obj) == -1)
1653 * Set up the magic number and version in the Obj_Entry. These
1654 * were checked in the crt1.o from the original ElfKit, so we
1655 * set them for backward compatibility.
1657 obj->magic = RTLD_MAGIC;
1658 obj->version = RTLD_VERSION;
1660 /* Set the special PLT or GOT entries. */
1668 * Cleanup procedure. It will be called (by the atexit mechanism) just
1669 * before the process exits.
1677 /* Clear all the reference counts so the fini functions will be called. */
1678 for (obj = obj_list; obj != NULL; obj = obj->next)
1680 objlist_call_fini(&list_fini);
1681 /* No need to remove the items from the list, since we are exiting. */
1685 path_enumerate(const char *path, path_enum_proc callback, void *arg)
1690 path += strspn(path, ":;");
1691 while (*path != '\0') {
1695 len = strcspn(path, ":;");
1696 res = callback(path, len, arg);
1702 path += strspn(path, ":;");
1708 struct try_library_args {
1716 try_library_path(const char *dir, size_t dirlen, void *param)
1718 struct try_library_args *arg;
1721 if (*dir == '/' || trust) {
1724 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
1727 pathname = arg->buffer;
1728 strncpy(pathname, dir, dirlen);
1729 pathname[dirlen] = '/';
1730 strcpy(pathname + dirlen + 1, arg->name);
1732 dbg(" Trying \"%s\"", pathname);
1733 if (access(pathname, F_OK) == 0) { /* We found it */
1734 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
1735 strcpy(pathname, arg->buffer);
1743 search_library_path(const char *name, const char *path)
1746 struct try_library_args arg;
1752 arg.namelen = strlen(name);
1753 arg.buffer = xmalloc(PATH_MAX);
1754 arg.buflen = PATH_MAX;
1756 p = path_enumerate(path, try_library_path, &arg);
1764 dlclose(void *handle)
1769 root = dlcheck(handle);
1775 /* Unreference the object and its dependencies. */
1776 root->dl_refcount--;
1779 if (root->refcount == 0) {
1781 * The object is no longer referenced, so we must unload it.
1782 * First, call the fini functions with no locks held.
1785 objlist_call_fini(&list_fini);
1787 objlist_remove_unref(&list_fini);
1789 /* Finish cleaning up the newly-unreferenced objects. */
1790 GDB_STATE(RT_DELETE,&root->linkmap);
1791 unload_object(root);
1792 GDB_STATE(RT_CONSISTENT,NULL);
1801 char *msg = error_message;
1802 error_message = NULL;
1807 dlopen(const char *name, int mode)
1809 Obj_Entry **old_obj_tail;
1814 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
1815 if (ld_tracing != NULL)
1816 environ = (char **)*get_program_var_addr("environ");
1818 objlist_init(&initlist);
1821 GDB_STATE(RT_ADD,NULL);
1823 old_obj_tail = obj_tail;
1829 char *path = find_library(name, obj_main);
1831 obj = load_object(path);
1836 if ((mode & RTLD_GLOBAL) && objlist_find(&list_global, obj) == NULL)
1837 objlist_push_tail(&list_global, obj);
1838 mode &= RTLD_MODEMASK;
1839 if (*old_obj_tail != NULL) { /* We loaded something new. */
1840 assert(*old_obj_tail == obj);
1842 result = load_needed_objects(obj);
1843 if (result != -1 && ld_tracing)
1847 (init_dag(obj), relocate_objects(obj, mode == RTLD_NOW,
1848 &obj_rtld)) == -1) {
1851 if (obj->refcount == 0)
1855 /* Make list of init functions to call. */
1856 initlist_add_objects(obj, &obj->next, &initlist);
1858 } else if (ld_tracing)
1862 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
1864 /* Call the init functions with no locks held. */
1866 objlist_call_init(&initlist);
1868 objlist_clear(&initlist);
1872 trace_loaded_objects(obj);
1878 dlsym(void *handle, const char *name)
1880 const Obj_Entry *obj;
1883 const Obj_Entry *defobj;
1885 hash = elf_hash(name);
1890 if (handle == NULL || handle == RTLD_NEXT ||
1891 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
1894 retaddr = __builtin_return_address(0); /* __GNUC__ only */
1895 if ((obj = obj_from_addr(retaddr)) == NULL) {
1896 _rtld_error("Cannot determine caller's shared object");
1900 if (handle == NULL) { /* Just the caller's shared object. */
1901 def = symlook_obj(name, hash, obj, true);
1903 } else if (handle == RTLD_NEXT || /* Objects after caller's */
1904 handle == RTLD_SELF) { /* ... caller included */
1905 if (handle == RTLD_NEXT)
1907 for (; obj != NULL; obj = obj->next) {
1908 if ((def = symlook_obj(name, hash, obj, true)) != NULL) {
1914 assert(handle == RTLD_DEFAULT);
1915 def = symlook_default(name, hash, obj, &defobj, true);
1920 if ((obj = dlcheck(handle)) == NULL) {
1925 donelist_init(&donelist);
1926 if (obj->mainprog) {
1927 /* Search main program and all libraries loaded by it. */
1928 def = symlook_list(name, hash, &list_main, &defobj, true,
1933 /* Search the given object and its needed objects. */
1935 fake.obj = (Obj_Entry *)obj;
1937 def = symlook_needed(name, hash, &fake, &defobj, true,
1944 return defobj->relocbase + def->st_value;
1947 _rtld_error("Undefined symbol \"%s\"", name);
1953 dladdr(const void *addr, Dl_info *info)
1955 const Obj_Entry *obj;
1958 unsigned long symoffset;
1961 obj = obj_from_addr(addr);
1963 _rtld_error("No shared object contains address");
1967 info->dli_fname = obj->path;
1968 info->dli_fbase = obj->mapbase;
1969 info->dli_saddr = (void *)0;
1970 info->dli_sname = NULL;
1973 * Walk the symbol list looking for the symbol whose address is
1974 * closest to the address sent in.
1976 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
1977 def = obj->symtab + symoffset;
1980 * For skip the symbol if st_shndx is either SHN_UNDEF or
1983 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
1987 * If the symbol is greater than the specified address, or if it
1988 * is further away from addr than the current nearest symbol,
1991 symbol_addr = obj->relocbase + def->st_value;
1992 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
1995 /* Update our idea of the nearest symbol. */
1996 info->dli_sname = obj->strtab + def->st_name;
1997 info->dli_saddr = symbol_addr;
2000 if (info->dli_saddr == addr)
2008 dlinfo(void *handle, int request, void *p)
2010 const Obj_Entry *obj;
2015 if (handle == NULL || handle == RTLD_SELF) {
2018 retaddr = __builtin_return_address(0); /* __GNUC__ only */
2019 if ((obj = obj_from_addr(retaddr)) == NULL)
2020 _rtld_error("Cannot determine caller's shared object");
2022 obj = dlcheck(handle);
2031 case RTLD_DI_LINKMAP:
2032 *((struct link_map const **)p) = &obj->linkmap;
2034 case RTLD_DI_ORIGIN:
2035 error = rtld_dirname(obj->path, p);
2038 case RTLD_DI_SERINFOSIZE:
2039 case RTLD_DI_SERINFO:
2040 error = do_search_info(obj, request, (struct dl_serinfo *)p);
2044 _rtld_error("Invalid request %d passed to dlinfo()", request);
2053 struct fill_search_info_args {
2056 Dl_serinfo *serinfo;
2057 Dl_serpath *serpath;
2062 fill_search_info(const char *dir, size_t dirlen, void *param)
2064 struct fill_search_info_args *arg;
2068 if (arg->request == RTLD_DI_SERINFOSIZE) {
2069 arg->serinfo->dls_cnt ++;
2070 arg->serinfo->dls_size += dirlen + 1;
2072 struct dl_serpath *s_entry;
2074 s_entry = arg->serpath;
2075 s_entry->dls_name = arg->strspace;
2076 s_entry->dls_flags = arg->flags;
2078 strncpy(arg->strspace, dir, dirlen);
2079 arg->strspace[dirlen] = '\0';
2081 arg->strspace += dirlen + 1;
2089 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
2091 struct dl_serinfo _info;
2092 struct fill_search_info_args args;
2094 args.request = RTLD_DI_SERINFOSIZE;
2095 args.serinfo = &_info;
2097 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2100 path_enumerate(ld_library_path, fill_search_info, &args);
2101 path_enumerate(obj->rpath, fill_search_info, &args);
2102 path_enumerate(gethints(), fill_search_info, &args);
2103 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
2106 if (request == RTLD_DI_SERINFOSIZE) {
2107 info->dls_size = _info.dls_size;
2108 info->dls_cnt = _info.dls_cnt;
2112 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
2113 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
2117 args.request = RTLD_DI_SERINFO;
2118 args.serinfo = info;
2119 args.serpath = &info->dls_serpath[0];
2120 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
2122 args.flags = LA_SER_LIBPATH;
2123 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
2126 args.flags = LA_SER_RUNPATH;
2127 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
2130 args.flags = LA_SER_CONFIG;
2131 if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
2134 args.flags = LA_SER_DEFAULT;
2135 if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
2141 rtld_dirname(const char *path, char *bname)
2145 /* Empty or NULL string gets treated as "." */
2146 if (path == NULL || *path == '\0') {
2152 /* Strip trailing slashes */
2153 endp = path + strlen(path) - 1;
2154 while (endp > path && *endp == '/')
2157 /* Find the start of the dir */
2158 while (endp > path && *endp != '/')
2161 /* Either the dir is "/" or there are no slashes */
2163 bname[0] = *endp == '/' ? '/' : '.';
2169 } while (endp > path && *endp == '/');
2172 if (endp - path + 2 > PATH_MAX)
2174 _rtld_error("Filename is too long: %s", path);
2178 strncpy(bname, path, endp - path + 1);
2179 bname[endp - path + 1] = '\0';
2184 linkmap_add(Obj_Entry *obj)
2186 struct link_map *l = &obj->linkmap;
2187 struct link_map *prev;
2189 obj->linkmap.l_name = obj->path;
2190 obj->linkmap.l_addr = obj->mapbase;
2191 obj->linkmap.l_ld = obj->dynamic;
2193 /* GDB needs load offset on MIPS to use the symbols */
2194 obj->linkmap.l_offs = obj->relocbase;
2197 if (r_debug.r_map == NULL) {
2203 * Scan to the end of the list, but not past the entry for the
2204 * dynamic linker, which we want to keep at the very end.
2206 for (prev = r_debug.r_map;
2207 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
2208 prev = prev->l_next)
2211 /* Link in the new entry. */
2213 l->l_next = prev->l_next;
2214 if (l->l_next != NULL)
2215 l->l_next->l_prev = l;
2220 linkmap_delete(Obj_Entry *obj)
2222 struct link_map *l = &obj->linkmap;
2224 if (l->l_prev == NULL) {
2225 if ((r_debug.r_map = l->l_next) != NULL)
2226 l->l_next->l_prev = NULL;
2230 if ((l->l_prev->l_next = l->l_next) != NULL)
2231 l->l_next->l_prev = l->l_prev;
2235 * Function for the debugger to set a breakpoint on to gain control.
2237 * The two parameters allow the debugger to easily find and determine
2238 * what the runtime loader is doing and to whom it is doing it.
2240 * When the loadhook trap is hit (r_debug_state, set at program
2241 * initialization), the arguments can be found on the stack:
2243 * +8 struct link_map *m
2244 * +4 struct r_debug *rd
2248 r_debug_state(struct r_debug* rd, struct link_map *m)
2253 * Get address of the pointer variable in the main program.
2255 static const void **
2256 get_program_var_addr(const char *name)
2258 const Obj_Entry *obj;
2261 hash = elf_hash(name);
2262 for (obj = obj_main; obj != NULL; obj = obj->next) {
2265 if ((def = symlook_obj(name, hash, obj, false)) != NULL) {
2268 addr = (const void **)(obj->relocbase + def->st_value);
2276 * Set a pointer variable in the main program to the given value. This
2277 * is used to set key variables such as "environ" before any of the
2278 * init functions are called.
2281 set_program_var(const char *name, const void *value)
2285 if ((addr = get_program_var_addr(name)) != NULL) {
2286 dbg("\"%s\": *%p <-- %p", name, addr, value);
2292 * This is a special version of getenv which is far more efficient
2293 * at finding LD_ environment vars.
2297 _getenv_ld(const char *id)
2301 int idlen = strlen(id);
2303 if (ld_index == LD_ARY_CACHE)
2305 if (ld_index == 0) {
2306 for (i = j = 0; (envp = environ[i]) != NULL && j < LD_ARY_CACHE; ++i) {
2307 if (envp[0] == 'L' && envp[1] == 'D' && envp[2] == '_')
2314 for (i = ld_index - 1; i >= 0; --i) {
2315 if (strncmp(ld_ary[i], id, idlen) == 0 && ld_ary[i][idlen] == '=')
2316 return(ld_ary[i] + idlen + 1);
2322 * Given a symbol name in a referencing object, find the corresponding
2323 * definition of the symbol. Returns a pointer to the symbol, or NULL if
2324 * no definition was found. Returns a pointer to the Obj_Entry of the
2325 * defining object via the reference parameter DEFOBJ_OUT.
2327 static const Elf_Sym *
2328 symlook_default(const char *name, unsigned long hash,
2329 const Obj_Entry *refobj, const Obj_Entry **defobj_out, bool in_plt)
2333 const Elf_Sym *symp;
2334 const Obj_Entry *obj;
2335 const Obj_Entry *defobj;
2336 const Objlist_Entry *elm;
2339 donelist_init(&donelist);
2341 /* Look first in the referencing object if linked symbolically. */
2342 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
2343 symp = symlook_obj(name, hash, refobj, in_plt);
2350 /* Search all objects loaded at program start up. */
2351 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2352 symp = symlook_list(name, hash, &list_main, &obj, in_plt, &donelist);
2354 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2360 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
2361 STAILQ_FOREACH(elm, &list_global, link) {
2362 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2364 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt,
2367 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2373 /* Search all dlopened DAGs containing the referencing object. */
2374 STAILQ_FOREACH(elm, &refobj->dldags, link) {
2375 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2377 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt,
2380 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2387 * Search the dynamic linker itself, and possibly resolve the
2388 * symbol from there. This is how the application links to
2389 * dynamic linker services such as dlopen. Only the values listed
2390 * in the "exports" array can be resolved from the dynamic linker.
2392 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2393 symp = symlook_obj(name, hash, &obj_rtld, in_plt);
2394 if (symp != NULL && is_exported(symp)) {
2401 *defobj_out = defobj;
2405 static const Elf_Sym *
2406 symlook_list(const char *name, unsigned long hash, const Objlist *objlist,
2407 const Obj_Entry **defobj_out, bool in_plt, DoneList *dlp)
2409 const Elf_Sym *symp;
2411 const Obj_Entry *defobj;
2412 const Objlist_Entry *elm;
2416 STAILQ_FOREACH(elm, objlist, link) {
2417 if (donelist_check(dlp, elm->obj))
2419 if ((symp = symlook_obj(name, hash, elm->obj, in_plt)) != NULL) {
2420 if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
2423 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2429 *defobj_out = defobj;
2434 * Search the symbol table of a shared object and all objects needed
2435 * by it for a symbol of the given name. Search order is
2436 * breadth-first. Returns a pointer to the symbol, or NULL if no
2437 * definition was found.
2439 static const Elf_Sym *
2440 symlook_needed(const char *name, unsigned long hash, const Needed_Entry *needed,
2441 const Obj_Entry **defobj_out, bool in_plt, DoneList *dlp)
2443 const Elf_Sym *def, *def_w;
2444 const Needed_Entry *n;
2445 const Obj_Entry *obj, *defobj, *defobj1;
2449 for (n = needed; n != NULL; n = n->next) {
2450 if ((obj = n->obj) == NULL ||
2451 donelist_check(dlp, obj) ||
2452 (def = symlook_obj(name, hash, obj, in_plt)) == NULL)
2455 if (ELF_ST_BIND(def->st_info) != STB_WEAK) {
2456 *defobj_out = defobj;
2461 * There we come when either symbol definition is not found in
2462 * directly needed objects, or found symbol is weak.
2464 for (n = needed; n != NULL; n = n->next) {
2465 if ((obj = n->obj) == NULL)
2467 def_w = symlook_needed(name, hash, obj->needed, &defobj1,
2471 if (def == NULL || ELF_ST_BIND(def_w->st_info) != STB_WEAK) {
2475 if (ELF_ST_BIND(def_w->st_info) != STB_WEAK)
2479 *defobj_out = defobj;
2484 * Search the symbol table of a single shared object for a symbol of
2485 * the given name. Returns a pointer to the symbol, or NULL if no
2486 * definition was found.
2488 * The symbol's hash value is passed in for efficiency reasons; that
2489 * eliminates many recomputations of the hash value.
2492 symlook_obj(const char *name, unsigned long hash, const Obj_Entry *obj,
2495 if (obj->buckets != NULL) {
2496 unsigned long symnum = obj->buckets[hash % obj->nbuckets];
2498 while (symnum != STN_UNDEF) {
2499 const Elf_Sym *symp;
2502 if (symnum >= obj->nchains)
2503 return NULL; /* Bad object */
2504 symp = obj->symtab + symnum;
2505 strp = obj->strtab + symp->st_name;
2507 if (name[0] == strp[0] && strcmp(name, strp) == 0)
2508 return symp->st_shndx != SHN_UNDEF ||
2509 (!in_plt && symp->st_value != 0 &&
2510 ELF_ST_TYPE(symp->st_info) == STT_FUNC) ? symp : NULL;
2512 symnum = obj->chains[symnum];
2519 trace_loaded_objects(Obj_Entry *obj)
2521 const char *fmt1, *fmt2, *fmt, *main_local;
2524 if ((main_local = _getenv_ld("LD_TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
2527 if ((fmt1 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT1")) == NULL)
2528 fmt1 = "\t%o => %p (%x)\n";
2530 if ((fmt2 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT2")) == NULL)
2531 fmt2 = "\t%o (%x)\n";
2533 for (; obj; obj = obj->next) {
2534 Needed_Entry *needed;
2538 for (needed = obj->needed; needed; needed = needed->next) {
2539 if (needed->obj != NULL) {
2540 if (needed->obj->traced)
2542 needed->obj->traced = true;
2543 path = needed->obj->path;
2547 name = (char *)obj->strtab + needed->name;
2548 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
2550 fmt = is_lib ? fmt1 : fmt2;
2551 while ((c = *fmt++) != '\0') {
2577 printf("%s", main_local);
2580 printf("%s", obj_main->path);
2587 printf("%d", sodp->sod_major);
2590 printf("%d", sodp->sod_minor);
2597 printf("%p", needed->obj ? needed->obj->mapbase : 0);
2609 * Unload a dlopened object and its dependencies from memory and from
2610 * our data structures. It is assumed that the DAG rooted in the
2611 * object has already been unreferenced, and that the object has a
2612 * reference count of 0.
2615 unload_object(Obj_Entry *root)
2620 assert(root->refcount == 0);
2623 * Pass over the DAG removing unreferenced objects from
2624 * appropriate lists.
2626 unlink_object(root);
2628 /* Unmap all objects that are no longer referenced. */
2629 linkp = &obj_list->next;
2630 while ((obj = *linkp) != NULL) {
2631 if (obj->refcount == 0) {
2632 dbg("unloading \"%s\"", obj->path);
2633 munmap(obj->mapbase, obj->mapsize);
2634 linkmap_delete(obj);
2645 unlink_object(Obj_Entry *root)
2647 const Needed_Entry *needed;
2650 if (root->refcount == 0) {
2651 /* Remove the object from the RTLD_GLOBAL list. */
2652 objlist_remove(&list_global, root);
2654 /* Remove the object from all objects' DAG lists. */
2655 STAILQ_FOREACH(elm, &root->dagmembers , link)
2656 objlist_remove(&elm->obj->dldags, root);
2659 for (needed = root->needed; needed != NULL; needed = needed->next)
2660 if (needed->obj != NULL)
2661 unlink_object(needed->obj);
2665 unref_dag(Obj_Entry *root)
2667 const Needed_Entry *needed;
2669 if (root->refcount == 0)
2672 if (root->refcount == 0)
2673 for (needed = root->needed; needed != NULL; needed = needed->next)
2674 if (needed->obj != NULL)
2675 unref_dag(needed->obj);
2679 * Common code for MD __tls_get_addr().
2682 tls_get_addr_common(void **dtvp, int index, size_t offset)
2684 Elf_Addr* dtv = *dtvp;
2686 /* Check dtv generation in case new modules have arrived */
2687 if (dtv[0] != tls_dtv_generation) {
2693 newdtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
2695 if (to_copy > tls_max_index)
2696 to_copy = tls_max_index;
2697 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
2698 newdtv[0] = tls_dtv_generation;
2699 newdtv[1] = tls_max_index;
2706 /* Dynamically allocate module TLS if necessary */
2707 if (!dtv[index + 1]) {
2709 * here we should avoid to be re-entered by signal handler
2710 * code, I assume wlock_acquire will masked all signals,
2711 * otherwise there is race and dead lock thread itself.
2714 if (!dtv[index + 1])
2715 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
2719 return (void*) (dtv[index + 1] + offset);
2722 #if defined(RTLD_STATIC_TLS_VARIANT_II)
2725 * Allocate the static TLS area. Return a pointer to the TCB. The
2726 * static area is based on negative offsets relative to the tcb.
2728 * The TCB contains an errno pointer for the system call layer, but because
2729 * we are the RTLD we really have no idea how the caller was compiled so
2730 * the information has to be passed in. errno can either be:
2732 * type 0 errno is a simple non-TLS global pointer.
2733 * (special case for e.g. libc_rtld)
2734 * type 1 errno accessed by GOT entry (dynamically linked programs)
2735 * type 2 errno accessed by %gs:OFFSET (statically linked programs)
2738 allocate_tls(Obj_Entry *objs)
2743 struct tls_tcb *tcb;
2748 * Allocate the new TCB. static TLS storage is placed just before the
2749 * TCB to support the %gs:OFFSET (negative offset) model.
2751 data_size = (tls_static_space + RTLD_STATIC_TLS_ALIGN_MASK) &
2752 ~RTLD_STATIC_TLS_ALIGN_MASK;
2753 tcb = malloc(data_size + sizeof(*tcb));
2754 tcb = (void *)((char *)tcb + data_size); /* actual tcb location */
2756 dtv_size = (tls_max_index + 2) * sizeof(Elf_Addr);
2757 dtv = malloc(dtv_size);
2758 bzero(dtv, dtv_size);
2760 #ifdef RTLD_TCB_HAS_SELF_POINTER
2761 tcb->tcb_self = tcb;
2764 tcb->tcb_pthread = NULL;
2766 dtv[0] = tls_dtv_generation;
2767 dtv[1] = tls_max_index;
2769 for (obj = objs; obj; obj = obj->next) {
2770 if (obj->tlsoffset) {
2771 addr = (Elf_Addr)tcb - obj->tlsoffset;
2772 memset((void *)(addr + obj->tlsinitsize),
2773 0, obj->tlssize - obj->tlsinitsize);
2775 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
2776 dtv[obj->tlsindex + 1] = addr;
2783 free_tls(struct tls_tcb *tcb)
2787 Elf_Addr tls_start, tls_end;
2790 data_size = (tls_static_space + RTLD_STATIC_TLS_ALIGN_MASK) &
2791 ~RTLD_STATIC_TLS_ALIGN_MASK;
2794 tls_end = (Elf_Addr)tcb;
2795 tls_start = (Elf_Addr)tcb - data_size;
2796 for (i = 0; i < dtv_size; i++) {
2797 if (dtv[i+2] != 0 && (dtv[i+2] < tls_start || dtv[i+2] > tls_end)) {
2798 free((void *)dtv[i+2]);
2801 free((void *)tls_start);
2805 #error "Unsupported TLS layout"
2809 * Allocate TLS block for module with given index.
2812 allocate_module_tls(int index)
2817 for (obj = obj_list; obj; obj = obj->next) {
2818 if (obj->tlsindex == index)
2822 _rtld_error("Can't find module with TLS index %d", index);
2826 p = malloc(obj->tlssize);
2827 memcpy(p, obj->tlsinit, obj->tlsinitsize);
2828 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
2834 allocate_tls_offset(Obj_Entry *obj)
2841 if (obj->tlssize == 0) {
2842 obj->tls_done = true;
2846 if (obj->tlsindex == 1)
2847 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
2849 off = calculate_tls_offset(tls_last_offset, tls_last_size,
2850 obj->tlssize, obj->tlsalign);
2853 * If we have already fixed the size of the static TLS block, we
2854 * must stay within that size. When allocating the static TLS, we
2855 * leave a small amount of space spare to be used for dynamically
2856 * loading modules which use static TLS.
2858 if (tls_static_space) {
2859 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
2863 tls_last_offset = obj->tlsoffset = off;
2864 tls_last_size = obj->tlssize;
2865 obj->tls_done = true;
2871 free_tls_offset(Obj_Entry *obj)
2873 #ifdef RTLD_STATIC_TLS_VARIANT_II
2875 * If we were the last thing to allocate out of the static TLS
2876 * block, we give our space back to the 'allocator'. This is a
2877 * simplistic workaround to allow libGL.so.1 to be loaded and
2878 * unloaded multiple times. We only handle the Variant II
2879 * mechanism for now - this really needs a proper allocator.
2881 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
2882 == calculate_tls_end(tls_last_offset, tls_last_size)) {
2883 tls_last_offset -= obj->tlssize;
2890 _rtld_allocate_tls(void)
2892 struct tls_tcb *new_tcb;
2895 new_tcb = allocate_tls(obj_list);
2902 _rtld_free_tls(struct tls_tcb *tcb)