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.24 2006/07/16 22:15:38 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 *);
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);
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 void trace_loaded_objects(Obj_Entry *obj);
130 static void unlink_object(Obj_Entry *);
131 static void unload_object(Obj_Entry *);
132 static void unref_dag(Obj_Entry *);
134 void r_debug_state(struct r_debug*, struct link_map*);
139 static char *error_message; /* Message for dlerror(), or NULL */
140 struct r_debug r_debug; /* for GDB; */
141 static bool trust; /* False for setuid and setgid programs */
142 static const char *ld_bind_now; /* Environment variable for immediate binding */
143 static const char *ld_debug; /* Environment variable for debugging */
144 static const char *ld_library_path; /* Environment variable for search path */
145 static char *ld_preload; /* Environment variable for libraries to
147 static const char *ld_tracing; /* Called from ldd(1) to print libs */
148 static Obj_Entry *obj_list; /* Head of linked list of shared objects */
149 static Obj_Entry **obj_tail; /* Link field of last object in list */
150 static Obj_Entry **preload_tail;
151 static Obj_Entry *obj_main; /* The main program shared object */
152 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
153 static unsigned int obj_count; /* Number of objects in obj_list */
154 static int ld_resident; /* Non-zero if resident */
155 static const char *ld_ary[LD_ARY_CACHE];
157 static Objlist initlist;
159 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
160 STAILQ_HEAD_INITIALIZER(list_global);
161 static Objlist list_main = /* Objects loaded at program startup */
162 STAILQ_HEAD_INITIALIZER(list_main);
163 static Objlist list_fini = /* Objects needing fini() calls */
164 STAILQ_HEAD_INITIALIZER(list_fini);
166 static LockInfo lockinfo;
168 static Elf_Sym sym_zero; /* For resolving undefined weak refs. */
170 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
172 extern Elf_Dyn _DYNAMIC;
173 #pragma weak _DYNAMIC
176 * These are the functions the dynamic linker exports to application
177 * programs. They are the only symbols the dynamic linker is willing
178 * to export from itself.
180 static func_ptr_type exports[] = {
181 (func_ptr_type) &_rtld_error,
182 (func_ptr_type) &dlclose,
183 (func_ptr_type) &dlerror,
184 (func_ptr_type) &dlopen,
185 (func_ptr_type) &dlsym,
186 (func_ptr_type) &dladdr,
187 (func_ptr_type) &dlinfo,
189 (func_ptr_type) &___tls_get_addr,
191 (func_ptr_type) &__tls_get_addr,
192 (func_ptr_type) &__tls_get_addr_tcb,
193 (func_ptr_type) &_rtld_allocate_tls,
194 (func_ptr_type) &_rtld_free_tls,
195 (func_ptr_type) &_rtld_call_init,
200 * Global declarations normally provided by crt1. The dynamic linker is
201 * not built with crt1, so we have to provide them ourselves.
207 * Globals to control TLS allocation.
209 size_t tls_last_offset; /* Static TLS offset of last module */
210 size_t tls_last_size; /* Static TLS size of last module */
211 size_t tls_static_space; /* Static TLS space allocated */
212 int tls_dtv_generation = 1; /* Used to detect when dtv size changes */
213 int tls_max_index = 1; /* Largest module index allocated */
216 * Fill in a DoneList with an allocation large enough to hold all of
217 * the currently-loaded objects. Keep this as a macro since it calls
218 * alloca and we want that to occur within the scope of the caller.
220 #define donelist_init(dlp) \
221 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
222 assert((dlp)->objs != NULL), \
223 (dlp)->num_alloc = obj_count, \
229 lockinfo.rlock_acquire(lockinfo.thelock);
230 atomic_incr_int(&lockinfo.rcount);
237 lockinfo.wlock_acquire(lockinfo.thelock);
238 atomic_incr_int(&lockinfo.wcount);
245 atomic_decr_int(&lockinfo.rcount);
246 lockinfo.rlock_release(lockinfo.thelock);
252 atomic_decr_int(&lockinfo.wcount);
253 lockinfo.wlock_release(lockinfo.thelock);
257 * Main entry point for dynamic linking. The first argument is the
258 * stack pointer. The stack is expected to be laid out as described
259 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
260 * Specifically, the stack pointer points to a word containing
261 * ARGC. Following that in the stack is a null-terminated sequence
262 * of pointers to argument strings. Then comes a null-terminated
263 * sequence of pointers to environment strings. Finally, there is a
264 * sequence of "auxiliary vector" entries.
266 * The second argument points to a place to store the dynamic linker's
267 * exit procedure pointer and the third to a place to store the main
270 * The return value is the main program's entry point.
274 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
276 Elf_Auxinfo *aux_info[AT_COUNT];
284 Objlist_Entry *entry;
287 ld_index = 0; /* don't use old env cache in case we are resident */
290 * On entry, the dynamic linker itself has not been relocated yet.
291 * Be very careful not to reference any global data until after
292 * init_rtld has returned. It is OK to reference file-scope statics
293 * and string constants, and to call static and global functions.
296 /* Find the auxiliary vector on the stack. */
299 sp += argc + 1; /* Skip over arguments and NULL terminator */
303 * If we aren't already resident we have to dig out some more info.
304 * Note that auxinfo does not exist when we are resident.
306 if (ld_resident == 0) {
307 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
309 aux = (Elf_Auxinfo *) sp;
311 /* Digest the auxiliary vector. */
312 for (i = 0; i < AT_COUNT; i++)
314 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
315 if (auxp->a_type < AT_COUNT)
316 aux_info[auxp->a_type] = auxp;
319 /* Initialize and relocate ourselves. */
320 assert(aux_info[AT_BASE] != NULL);
321 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
324 __progname = obj_rtld.path;
325 argv0 = argv[0] != NULL ? argv[0] : "(null)";
328 trust = (geteuid() == getuid()) && (getegid() == getgid());
330 ld_bind_now = _getenv_ld("LD_BIND_NOW");
332 ld_debug = _getenv_ld("LD_DEBUG");
333 ld_library_path = _getenv_ld("LD_LIBRARY_PATH");
334 ld_preload = (char *)_getenv_ld("LD_PRELOAD");
336 ld_tracing = _getenv_ld("LD_TRACE_LOADED_OBJECTS");
338 if (ld_debug != NULL && *ld_debug != '\0')
340 dbg("%s is initialized, base address = %p", __progname,
341 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
342 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
343 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
346 * If we are resident we can skip work that we have already done.
347 * Note that the stack is reset and there is no Elf_Auxinfo
348 * when running from a resident image, and the static globals setup
349 * between here and resident_skip will have already been setup.
355 * Load the main program, or process its program header if it is
358 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
359 int fd = aux_info[AT_EXECFD]->a_un.a_val;
360 dbg("loading main program");
361 obj_main = map_object(fd, argv0, NULL);
363 if (obj_main == NULL)
365 } else { /* Main program already loaded. */
366 const Elf_Phdr *phdr;
370 dbg("processing main program's program header");
371 assert(aux_info[AT_PHDR] != NULL);
372 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
373 assert(aux_info[AT_PHNUM] != NULL);
374 phnum = aux_info[AT_PHNUM]->a_un.a_val;
375 assert(aux_info[AT_PHENT] != NULL);
376 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
377 assert(aux_info[AT_ENTRY] != NULL);
378 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
379 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
383 obj_main->path = xstrdup(argv0);
384 obj_main->mainprog = true;
387 * Get the actual dynamic linker pathname from the executable if
388 * possible. (It should always be possible.) That ensures that
389 * gdb will find the right dynamic linker even if a non-standard
392 if (obj_main->interp != NULL &&
393 strcmp(obj_main->interp, obj_rtld.path) != 0) {
395 obj_rtld.path = xstrdup(obj_main->interp);
396 __progname = obj_rtld.path;
399 digest_dynamic(obj_main);
401 linkmap_add(obj_main);
402 linkmap_add(&obj_rtld);
404 /* Link the main program into the list of objects. */
405 *obj_tail = obj_main;
406 obj_tail = &obj_main->next;
408 obj_main->refcount++;
409 /* Make sure we don't call the main program's init and fini functions. */
410 obj_main->init = obj_main->fini = NULL;
412 /* Initialize a fake symbol for resolving undefined weak references. */
413 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
414 sym_zero.st_shndx = SHN_ABS;
416 dbg("loading LD_PRELOAD libraries");
417 if (load_preload_objects() == -1)
419 preload_tail = obj_tail;
421 dbg("loading needed objects");
422 if (load_needed_objects(obj_main) == -1)
425 /* Make a list of all objects loaded at startup. */
426 for (obj = obj_list; obj != NULL; obj = obj->next)
427 objlist_push_tail(&list_main, obj);
431 if (ld_tracing) { /* We're done */
432 trace_loaded_objects(obj_main);
436 if (ld_resident) /* XXX clean this up! */
439 if (getenv("LD_DUMP_REL_PRE") != NULL) {
440 dump_relocations(obj_main);
444 /* setup TLS for main thread */
445 dbg("initializing initial thread local storage");
446 STAILQ_FOREACH(entry, &list_main, link) {
448 * Allocate all the initial objects out of the static TLS
449 * block even if they didn't ask for it.
451 allocate_tls_offset(entry->obj);
454 tls_static_space = tls_last_offset + RTLD_STATIC_TLS_EXTRA;
457 * Do not try to allocate the TLS here, let libc do it itself.
458 * (crt1 for the program will call _init_tls())
461 if (relocate_objects(obj_main,
462 ld_bind_now != NULL && *ld_bind_now != '\0') == -1)
465 dbg("doing copy relocations");
466 if (do_copy_relocations(obj_main) == -1)
471 if (_getenv_ld("LD_RESIDENT_UNREGISTER_NOW")) {
472 if (exec_sys_unregister(-1) < 0) {
473 dbg("exec_sys_unregister failed %d\n", errno);
476 dbg("exec_sys_unregister success\n");
480 if (getenv("LD_DUMP_REL_POST") != NULL) {
481 dump_relocations(obj_main);
485 dbg("initializing key program variables");
486 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
487 set_program_var("environ", env);
489 if (_getenv_ld("LD_RESIDENT_REGISTER_NOW")) {
490 extern void resident_start(void);
492 if (exec_sys_register(resident_start) < 0) {
493 dbg("exec_sys_register failed %d\n", errno);
496 dbg("exec_sys_register success\n");
500 dbg("initializing thread locks");
501 lockdflt_init(&lockinfo);
502 lockinfo.thelock = lockinfo.lock_create(lockinfo.context);
504 /* Make a list of init functions to call. */
505 objlist_init(&initlist);
506 initlist_add_objects(obj_list, preload_tail, &initlist);
508 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
511 * Do NOT call the initlist here, give libc a chance to set up
512 * the initial TLS segment. crt1 will then call _rtld_call_init().
515 dbg("transferring control to program entry point = %p", obj_main->entry);
517 /* Return the exit procedure and the program entry point. */
518 *exit_proc = rtld_exit;
520 return (func_ptr_type) obj_main->entry;
524 * Call the initialization list for dynamically loaded libraries.
525 * (called from crt1.c).
528 _rtld_call_init(void)
530 objlist_call_init(&initlist);
532 objlist_clear(&initlist);
537 _rtld_bind(Obj_Entry *obj, Elf_Word reloff)
541 const Obj_Entry *defobj;
547 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
549 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
551 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
552 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL);
556 target = (Elf_Addr)(defobj->relocbase + def->st_value);
558 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
559 defobj->strtab + def->st_name, basename(obj->path),
560 (void *)target, basename(defobj->path));
562 reloc_jmpslot(where, target);
568 * Error reporting function. Use it like printf. If formats the message
569 * into a buffer, and sets things up so that the next call to dlerror()
570 * will return the message.
573 _rtld_error(const char *fmt, ...)
575 static char buf[512];
579 vsnprintf(buf, sizeof buf, fmt, ap);
585 * Return a dynamically-allocated copy of the current error message, if any.
590 return error_message == NULL ? NULL : xstrdup(error_message);
594 * Restore the current error message from a copy which was previously saved
595 * by errmsg_save(). The copy is freed.
598 errmsg_restore(char *saved_msg)
600 if (saved_msg == NULL)
601 error_message = NULL;
603 _rtld_error("%s", saved_msg);
609 basename(const char *name)
611 const char *p = strrchr(name, '/');
612 return p != NULL ? p + 1 : name;
618 const char *msg = dlerror();
626 * Process a shared object's DYNAMIC section, and save the important
627 * information in its Obj_Entry structure.
630 digest_dynamic(Obj_Entry *obj)
633 Needed_Entry **needed_tail = &obj->needed;
634 const Elf_Dyn *dyn_rpath = NULL;
635 int plttype = DT_REL;
637 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
638 switch (dynp->d_tag) {
641 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
645 obj->relsize = dynp->d_un.d_val;
649 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
653 obj->pltrel = (const Elf_Rel *)
654 (obj->relocbase + dynp->d_un.d_ptr);
658 obj->pltrelsize = dynp->d_un.d_val;
662 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
666 obj->relasize = dynp->d_un.d_val;
670 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
674 plttype = dynp->d_un.d_val;
675 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
679 obj->symtab = (const Elf_Sym *)
680 (obj->relocbase + dynp->d_un.d_ptr);
684 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
688 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
692 obj->strsize = dynp->d_un.d_val;
697 const Elf_Addr *hashtab = (const Elf_Addr *)
698 (obj->relocbase + dynp->d_un.d_ptr);
699 obj->nbuckets = hashtab[0];
700 obj->nchains = hashtab[1];
701 obj->buckets = hashtab + 2;
702 obj->chains = obj->buckets + obj->nbuckets;
708 Needed_Entry *nep = NEW(Needed_Entry);
709 nep->name = dynp->d_un.d_val;
714 needed_tail = &nep->next;
719 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
727 obj->symbolic = true;
731 case DT_RUNPATH: /* XXX: process separately */
733 * We have to wait until later to process this, because we
734 * might not have gotten the address of the string table yet.
740 /* Not used by the dynamic linker. */
744 obj->init = (InitFunc) (obj->relocbase + dynp->d_un.d_ptr);
748 obj->fini = (InitFunc) (obj->relocbase + dynp->d_un.d_ptr);
752 /* XXX - not implemented yet */
753 dbg("Filling in DT_DEBUG entry");
754 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
758 if (dynp->d_un.d_val & DF_ORIGIN) {
759 obj->origin_path = xmalloc(PATH_MAX);
760 if (rtld_dirname(obj->path, obj->origin_path) == -1)
763 if (dynp->d_un.d_val & DF_SYMBOLIC)
764 obj->symbolic = true;
765 if (dynp->d_un.d_val & DF_TEXTREL)
767 if (dynp->d_un.d_val & DF_BIND_NOW)
768 obj->bind_now = true;
769 if (dynp->d_un.d_val & DF_STATIC_TLS)
774 dbg("Ignoring d_tag %d = %#x", dynp->d_tag, dynp->d_tag);
781 if (plttype == DT_RELA) {
782 obj->pltrela = (const Elf_Rela *) obj->pltrel;
784 obj->pltrelasize = obj->pltrelsize;
788 if (dyn_rpath != NULL)
789 obj->rpath = obj->strtab + dyn_rpath->d_un.d_val;
793 * Process a shared object's program header. This is used only for the
794 * main program, when the kernel has already loaded the main program
795 * into memory before calling the dynamic linker. It creates and
796 * returns an Obj_Entry structure.
799 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
802 const Elf_Phdr *phlimit = phdr + phnum;
807 for (ph = phdr; ph < phlimit; ph++) {
808 switch (ph->p_type) {
811 if ((const Elf_Phdr *)ph->p_vaddr != phdr) {
812 _rtld_error("%s: invalid PT_PHDR", path);
815 obj->phdr = (const Elf_Phdr *) ph->p_vaddr;
816 obj->phsize = ph->p_memsz;
820 obj->interp = (const char *) ph->p_vaddr;
824 if (nsegs == 0) { /* First load segment */
825 obj->vaddrbase = trunc_page(ph->p_vaddr);
826 obj->mapbase = (caddr_t) obj->vaddrbase;
827 obj->relocbase = obj->mapbase - obj->vaddrbase;
828 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
830 } else { /* Last load segment */
831 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
838 obj->dynamic = (const Elf_Dyn *) ph->p_vaddr;
843 obj->tlssize = ph->p_memsz;
844 obj->tlsalign = ph->p_align;
845 obj->tlsinitsize = ph->p_filesz;
846 obj->tlsinit = (void*) ph->p_vaddr;
851 _rtld_error("%s: too few PT_LOAD segments", path);
860 dlcheck(void *handle)
864 for (obj = obj_list; obj != NULL; obj = obj->next)
865 if (obj == (Obj_Entry *) handle)
868 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
869 _rtld_error("Invalid shared object handle %p", handle);
876 * If the given object is already in the donelist, return true. Otherwise
877 * add the object to the list and return false.
880 donelist_check(DoneList *dlp, const Obj_Entry *obj)
884 for (i = 0; i < dlp->num_used; i++)
885 if (dlp->objs[i] == obj)
888 * Our donelist allocation should always be sufficient. But if
889 * our threads locking isn't working properly, more shared objects
890 * could have been loaded since we allocated the list. That should
891 * never happen, but we'll handle it properly just in case it does.
893 if (dlp->num_used < dlp->num_alloc)
894 dlp->objs[dlp->num_used++] = obj;
899 * Hash function for symbol table lookup. Don't even think about changing
900 * this. It is specified by the System V ABI.
903 elf_hash(const char *name)
905 const unsigned char *p = (const unsigned char *) name;
911 if ((g = h & 0xf0000000) != 0)
919 * Find the library with the given name, and return its full pathname.
920 * The returned string is dynamically allocated. Generates an error
921 * message and returns NULL if the library cannot be found.
923 * If the second argument is non-NULL, then it refers to an already-
924 * loaded shared object, whose library search path will be searched.
926 * The search order is:
928 * rpath in the referencing file
933 find_library(const char *name, const Obj_Entry *refobj)
937 if (strchr(name, '/') != NULL) { /* Hard coded pathname */
938 if (name[0] != '/' && !trust) {
939 _rtld_error("Absolute pathname required for shared object \"%s\"",
943 return xstrdup(name);
946 dbg(" Searching for \"%s\"", name);
948 if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
950 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
951 (pathname = search_library_path(name, gethints())) != NULL ||
952 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
955 if(refobj != NULL && refobj->path != NULL) {
956 _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
957 name, basename(refobj->path));
959 _rtld_error("Shared object \"%s\" not found", name);
965 * Given a symbol number in a referencing object, find the corresponding
966 * definition of the symbol. Returns a pointer to the symbol, or NULL if
967 * no definition was found. Returns a pointer to the Obj_Entry of the
968 * defining object via the reference parameter DEFOBJ_OUT.
971 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
972 const Obj_Entry **defobj_out, bool in_plt, SymCache *cache)
976 const Obj_Entry *defobj;
981 * If we have already found this symbol, get the information from
984 if (symnum >= refobj->nchains)
985 return NULL; /* Bad object */
986 if (cache != NULL && cache[symnum].sym != NULL) {
987 *defobj_out = cache[symnum].obj;
988 return cache[symnum].sym;
991 ref = refobj->symtab + symnum;
992 name = refobj->strtab + ref->st_name;
993 hash = elf_hash(name);
996 def = symlook_default(name, hash, refobj, &defobj, in_plt);
999 * If we found no definition and the reference is weak, treat the
1000 * symbol as having the value zero.
1002 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1008 *defobj_out = defobj;
1009 /* Record the information in the cache to avoid subsequent lookups. */
1010 if (cache != NULL) {
1011 cache[symnum].sym = def;
1012 cache[symnum].obj = defobj;
1015 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1020 * Return the search path from the ldconfig hints file, reading it if
1021 * necessary. Returns NULL if there are problems with the hints file,
1022 * or if the search path there is empty.
1029 if (hints == NULL) {
1031 struct elfhints_hdr hdr;
1034 /* Keep from trying again in case the hints file is bad. */
1037 if ((fd = open(_PATH_ELF_HINTS, O_RDONLY)) == -1)
1039 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1040 hdr.magic != ELFHINTS_MAGIC ||
1045 p = xmalloc(hdr.dirlistlen + 1);
1046 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1047 read(fd, p, hdr.dirlistlen + 1) != hdr.dirlistlen + 1) {
1055 return hints[0] != '\0' ? hints : NULL;
1059 init_dag(Obj_Entry *root)
1063 donelist_init(&donelist);
1064 init_dag1(root, root, &donelist);
1068 init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *dlp)
1070 const Needed_Entry *needed;
1072 if (donelist_check(dlp, obj))
1074 objlist_push_tail(&obj->dldags, root);
1075 objlist_push_tail(&root->dagmembers, obj);
1076 for (needed = obj->needed; needed != NULL; needed = needed->next)
1077 if (needed->obj != NULL)
1078 init_dag1(root, needed->obj, dlp);
1082 * Initialize the dynamic linker. The argument is the address at which
1083 * the dynamic linker has been mapped into memory. The primary task of
1084 * this function is to relocate the dynamic linker.
1087 init_rtld(caddr_t mapbase)
1090 * Conjure up an Obj_Entry structure for the dynamic linker.
1092 * The "path" member is supposed to be dynamically-allocated, but we
1093 * aren't yet initialized sufficiently to do that. Below we will
1094 * replace the static version with a dynamically-allocated copy.
1096 obj_rtld.path = PATH_RTLD;
1097 obj_rtld.rtld = true;
1098 obj_rtld.mapbase = mapbase;
1100 obj_rtld.relocbase = mapbase;
1102 if (&_DYNAMIC != 0) {
1103 obj_rtld.dynamic = rtld_dynamic(&obj_rtld);
1104 digest_dynamic(&obj_rtld);
1105 assert(obj_rtld.needed == NULL);
1106 assert(!obj_rtld.textrel);
1109 * Temporarily put the dynamic linker entry into the object list, so
1110 * that symbols can be found.
1112 obj_list = &obj_rtld;
1113 obj_tail = &obj_rtld.next;
1116 relocate_objects(&obj_rtld, true);
1119 /* Make the object list empty again. */
1121 obj_tail = &obj_list;
1124 /* Replace the path with a dynamically allocated copy. */
1125 obj_rtld.path = xstrdup(obj_rtld.path);
1127 r_debug.r_brk = r_debug_state;
1128 r_debug.r_state = RT_CONSISTENT;
1132 * Add the init functions from a needed object list (and its recursive
1133 * needed objects) to "list". This is not used directly; it is a helper
1134 * function for initlist_add_objects(). The write lock must be held
1135 * when this function is called.
1138 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1140 /* Recursively process the successor needed objects. */
1141 if (needed->next != NULL)
1142 initlist_add_neededs(needed->next, list);
1144 /* Process the current needed object. */
1145 if (needed->obj != NULL)
1146 initlist_add_objects(needed->obj, &needed->obj->next, list);
1150 * Scan all of the DAGs rooted in the range of objects from "obj" to
1151 * "tail" and add their init functions to "list". This recurses over
1152 * the DAGs and ensure the proper init ordering such that each object's
1153 * needed libraries are initialized before the object itself. At the
1154 * same time, this function adds the objects to the global finalization
1155 * list "list_fini" in the opposite order. The write lock must be
1156 * held when this function is called.
1159 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1163 obj->init_done = true;
1165 /* Recursively process the successor objects. */
1166 if (&obj->next != tail)
1167 initlist_add_objects(obj->next, tail, list);
1169 /* Recursively process the needed objects. */
1170 if (obj->needed != NULL)
1171 initlist_add_neededs(obj->needed, list);
1173 /* Add the object to the init list. */
1174 if (obj->init != NULL)
1175 objlist_push_tail(list, obj);
1177 /* Add the object to the global fini list in the reverse order. */
1178 if (obj->fini != NULL)
1179 objlist_push_head(&list_fini, obj);
1183 is_exported(const Elf_Sym *def)
1185 func_ptr_type value;
1186 const func_ptr_type *p;
1188 value = (func_ptr_type)(obj_rtld.relocbase + def->st_value);
1189 for (p = exports; *p != NULL; p++)
1196 * Given a shared object, traverse its list of needed objects, and load
1197 * each of them. Returns 0 on success. Generates an error message and
1198 * returns -1 on failure.
1201 load_needed_objects(Obj_Entry *first)
1205 for (obj = first; obj != NULL; obj = obj->next) {
1206 Needed_Entry *needed;
1208 for (needed = obj->needed; needed != NULL; needed = needed->next) {
1209 const char *name = obj->strtab + needed->name;
1210 char *path = find_library(name, obj);
1213 if (path == NULL && !ld_tracing)
1217 needed->obj = load_object(path);
1218 if (needed->obj == NULL && !ld_tracing)
1219 return -1; /* XXX - cleanup */
1228 load_preload_objects(void)
1230 char *p = ld_preload;
1231 static const char delim[] = " \t:;";
1236 p += strspn(p, delim);
1237 while (*p != '\0') {
1238 size_t len = strcspn(p, delim);
1244 if ((path = find_library(p, NULL)) == NULL)
1246 if (load_object(path) == NULL)
1247 return -1; /* XXX - cleanup */
1250 p += strspn(p, delim);
1256 * Returns a pointer to the Obj_Entry for the object with the given path.
1257 * Returns NULL if no matching object was found.
1260 find_object(const char *path)
1264 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
1265 if (strcmp(obj->path, path) == 0)
1272 * Returns a pointer to the Obj_Entry for the object matching device and
1273 * inode of the given path. If no matching object was found, the descriptor
1274 * is returned in fd.
1275 * Returns with obj == NULL && fd == -1 on error.
1278 find_object2(const char *path, int *fd, struct stat *sb)
1282 if ((*fd = open(path, O_RDONLY)) == -1) {
1283 _rtld_error("Cannot open \"%s\"", path);
1287 if (fstat(*fd, sb) == -1) {
1288 _rtld_error("Cannot fstat \"%s\"", path);
1294 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
1295 if (obj->ino == sb->st_ino && obj->dev == sb->st_dev) {
1305 * Load a shared object into memory, if it is not already loaded. The
1306 * argument must be a string allocated on the heap. This function assumes
1307 * responsibility for freeing it when necessary.
1309 * Returns a pointer to the Obj_Entry for the object. Returns NULL
1313 load_object(char *path)
1319 obj = find_object(path);
1326 obj = find_object2(path, &fd, &sb);
1331 } else if (fd == -1) {
1336 dbg("loading \"%s\"", path);
1337 obj = map_object(fd, path, &sb);
1345 digest_dynamic(obj);
1348 obj_tail = &obj->next;
1350 linkmap_add(obj); /* for GDB & dlinfo() */
1352 dbg(" %p .. %p: %s", obj->mapbase, obj->mapbase + obj->mapsize - 1,
1355 dbg(" WARNING: %s has impure text", obj->path);
1362 * Check for locking violations and die if one is found.
1369 rcount = lockinfo.rcount;
1370 wcount = lockinfo.wcount;
1371 assert(rcount >= 0);
1372 assert(wcount >= 0);
1373 if (wcount > 1 || (wcount != 0 && rcount != 0)) {
1374 _rtld_error("Application locking error: %d readers and %d writers"
1375 " in dynamic linker. See DLLOCKINIT(3) in manual pages.",
1382 obj_from_addr(const void *addr)
1386 for (obj = obj_list; obj != NULL; obj = obj->next) {
1387 if (addr < (void *) obj->mapbase)
1389 if (addr < (void *) (obj->mapbase + obj->mapsize))
1396 * Call the finalization functions for each of the objects in "list"
1397 * which are unreferenced. All of the objects are expected to have
1398 * non-NULL fini functions.
1401 objlist_call_fini(Objlist *list)
1407 * Preserve the current error message since a fini function might
1408 * call into the dynamic linker and overwrite it.
1410 saved_msg = errmsg_save();
1411 STAILQ_FOREACH(elm, list, link) {
1412 if (elm->obj->refcount == 0) {
1413 dbg("calling fini function for %s", elm->obj->path);
1414 (*elm->obj->fini)();
1417 errmsg_restore(saved_msg);
1421 * Call the initialization functions for each of the objects in
1422 * "list". All of the objects are expected to have non-NULL init
1426 objlist_call_init(Objlist *list)
1432 * Preserve the current error message since an init function might
1433 * call into the dynamic linker and overwrite it.
1435 saved_msg = errmsg_save();
1436 STAILQ_FOREACH(elm, list, link) {
1437 dbg("calling init function for %s", elm->obj->path);
1438 (*elm->obj->init)();
1440 errmsg_restore(saved_msg);
1444 objlist_clear(Objlist *list)
1448 while (!STAILQ_EMPTY(list)) {
1449 elm = STAILQ_FIRST(list);
1450 STAILQ_REMOVE_HEAD(list, link);
1455 static Objlist_Entry *
1456 objlist_find(Objlist *list, const Obj_Entry *obj)
1460 STAILQ_FOREACH(elm, list, link)
1461 if (elm->obj == obj)
1467 objlist_init(Objlist *list)
1473 objlist_push_head(Objlist *list, Obj_Entry *obj)
1477 elm = NEW(Objlist_Entry);
1479 STAILQ_INSERT_HEAD(list, elm, link);
1483 objlist_push_tail(Objlist *list, Obj_Entry *obj)
1487 elm = NEW(Objlist_Entry);
1489 STAILQ_INSERT_TAIL(list, elm, link);
1493 objlist_remove(Objlist *list, Obj_Entry *obj)
1497 if ((elm = objlist_find(list, obj)) != NULL) {
1498 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1504 * Remove all of the unreferenced objects from "list".
1507 objlist_remove_unref(Objlist *list)
1512 STAILQ_INIT(&newlist);
1513 while (!STAILQ_EMPTY(list)) {
1514 elm = STAILQ_FIRST(list);
1515 STAILQ_REMOVE_HEAD(list, link);
1516 if (elm->obj->refcount == 0)
1519 STAILQ_INSERT_TAIL(&newlist, elm, link);
1525 * Relocate newly-loaded shared objects. The argument is a pointer to
1526 * the Obj_Entry for the first such object. All objects from the first
1527 * to the end of the list of objects are relocated. Returns 0 on success,
1531 relocate_objects(Obj_Entry *first, bool bind_now)
1535 for (obj = first; obj != NULL; obj = obj->next) {
1536 if (obj != &obj_rtld)
1537 dbg("relocating \"%s\"", obj->path);
1538 if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
1539 obj->symtab == NULL || obj->strtab == NULL) {
1540 _rtld_error("%s: Shared object has no run-time symbol table",
1546 /* There are relocations to the write-protected text segment. */
1547 if (mprotect(obj->mapbase, obj->textsize,
1548 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
1549 _rtld_error("%s: Cannot write-enable text segment: %s",
1550 obj->path, strerror(errno));
1555 /* Process the non-PLT relocations. */
1556 if (reloc_non_plt(obj, &obj_rtld))
1560 * Reprotect the text segment. Make sure it is included in the
1561 * core dump since we modified it. This unfortunately causes the
1562 * entire text segment to core-out but we don't have much of a
1563 * choice. We could try to only reenable core dumps on pages
1564 * in which relocations occured but that is likely most of the text
1565 * pages anyway, and even that would not work because the rest of
1566 * the text pages would wind up as a read-only OBJT_DEFAULT object
1567 * (created due to our modifications) backed by the original OBJT_VNODE
1568 * object, and the ELF coredump code is currently only able to dump
1569 * vnode records for pure vnode-backed mappings, not vnode backings
1570 * to memory objects.
1573 madvise(obj->mapbase, obj->textsize, MADV_CORE);
1574 if (mprotect(obj->mapbase, obj->textsize,
1575 PROT_READ|PROT_EXEC) == -1) {
1576 _rtld_error("%s: Cannot write-protect text segment: %s",
1577 obj->path, strerror(errno));
1582 /* Process the PLT relocations. */
1583 if (reloc_plt(obj) == -1)
1585 /* Relocate the jump slots if we are doing immediate binding. */
1586 if (obj->bind_now || bind_now)
1587 if (reloc_jmpslots(obj) == -1)
1592 * Set up the magic number and version in the Obj_Entry. These
1593 * were checked in the crt1.o from the original ElfKit, so we
1594 * set them for backward compatibility.
1596 obj->magic = RTLD_MAGIC;
1597 obj->version = RTLD_VERSION;
1599 /* Set the special PLT or GOT entries. */
1607 * Cleanup procedure. It will be called (by the atexit mechanism) just
1608 * before the process exits.
1616 /* Clear all the reference counts so the fini functions will be called. */
1617 for (obj = obj_list; obj != NULL; obj = obj->next)
1619 objlist_call_fini(&list_fini);
1620 /* No need to remove the items from the list, since we are exiting. */
1624 path_enumerate(const char *path, path_enum_proc callback, void *arg)
1629 path += strspn(path, ":;");
1630 while (*path != '\0') {
1634 len = strcspn(path, ":;");
1635 res = callback(path, len, arg);
1641 path += strspn(path, ":;");
1647 struct try_library_args {
1655 try_library_path(const char *dir, size_t dirlen, void *param)
1657 struct try_library_args *arg;
1660 if (*dir == '/' || trust) {
1663 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
1666 pathname = arg->buffer;
1667 strncpy(pathname, dir, dirlen);
1668 pathname[dirlen] = '/';
1669 strcpy(pathname + dirlen + 1, arg->name);
1671 dbg(" Trying \"%s\"", pathname);
1672 if (access(pathname, F_OK) == 0) { /* We found it */
1673 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
1674 strcpy(pathname, arg->buffer);
1682 search_library_path(const char *name, const char *path)
1685 struct try_library_args arg;
1691 arg.namelen = strlen(name);
1692 arg.buffer = xmalloc(PATH_MAX);
1693 arg.buflen = PATH_MAX;
1695 p = path_enumerate(path, try_library_path, &arg);
1703 dlclose(void *handle)
1708 root = dlcheck(handle);
1714 /* Unreference the object and its dependencies. */
1715 root->dl_refcount--;
1718 if (root->refcount == 0) {
1720 * The object is no longer referenced, so we must unload it.
1721 * First, call the fini functions with no locks held.
1724 objlist_call_fini(&list_fini);
1726 objlist_remove_unref(&list_fini);
1728 /* Finish cleaning up the newly-unreferenced objects. */
1729 GDB_STATE(RT_DELETE,&root->linkmap);
1730 unload_object(root);
1731 GDB_STATE(RT_CONSISTENT,NULL);
1740 char *msg = error_message;
1741 error_message = NULL;
1746 dlopen(const char *name, int mode)
1748 Obj_Entry **old_obj_tail;
1753 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
1754 if (ld_tracing != NULL)
1755 environ = (char **)*get_program_var_addr("environ");
1757 objlist_init(&initlist);
1760 GDB_STATE(RT_ADD,NULL);
1762 old_obj_tail = obj_tail;
1768 char *path = find_library(name, obj_main);
1770 obj = load_object(path);
1775 if ((mode & RTLD_GLOBAL) && objlist_find(&list_global, obj) == NULL)
1776 objlist_push_tail(&list_global, obj);
1777 mode &= RTLD_MODEMASK;
1778 if (*old_obj_tail != NULL) { /* We loaded something new. */
1779 assert(*old_obj_tail == obj);
1781 result = load_needed_objects(obj);
1782 if (result != -1 && ld_tracing)
1786 (init_dag(obj), relocate_objects(obj, mode == RTLD_NOW)) == -1) {
1789 if (obj->refcount == 0)
1793 /* Make list of init functions to call. */
1794 initlist_add_objects(obj, &obj->next, &initlist);
1796 } else if (ld_tracing)
1800 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
1802 /* Call the init functions with no locks held. */
1804 objlist_call_init(&initlist);
1806 objlist_clear(&initlist);
1810 trace_loaded_objects(obj);
1816 dlsym(void *handle, const char *name)
1818 const Obj_Entry *obj;
1821 const Obj_Entry *defobj;
1823 hash = elf_hash(name);
1828 if (handle == NULL || handle == RTLD_NEXT ||
1829 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
1832 retaddr = __builtin_return_address(0); /* __GNUC__ only */
1833 if ((obj = obj_from_addr(retaddr)) == NULL) {
1834 _rtld_error("Cannot determine caller's shared object");
1838 if (handle == NULL) { /* Just the caller's shared object. */
1839 def = symlook_obj(name, hash, obj, true);
1841 } else if (handle == RTLD_NEXT || /* Objects after caller's */
1842 handle == RTLD_SELF) { /* ... caller included */
1843 if (handle == RTLD_NEXT)
1845 for (; obj != NULL; obj = obj->next) {
1846 if ((def = symlook_obj(name, hash, obj, true)) != NULL) {
1852 assert(handle == RTLD_DEFAULT);
1853 def = symlook_default(name, hash, obj, &defobj, true);
1858 if ((obj = dlcheck(handle)) == NULL) {
1863 donelist_init(&donelist);
1864 if (obj->mainprog) {
1865 /* Search main program and all libraries loaded by it. */
1866 def = symlook_list(name, hash, &list_main, &defobj, true,
1869 def = symlook_list(name, hash, &(obj->dagmembers), &defobj, true,
1876 return defobj->relocbase + def->st_value;
1879 _rtld_error("Undefined symbol \"%s\"", name);
1885 dladdr(const void *addr, Dl_info *info)
1887 const Obj_Entry *obj;
1890 unsigned long symoffset;
1893 obj = obj_from_addr(addr);
1895 _rtld_error("No shared object contains address");
1899 info->dli_fname = obj->path;
1900 info->dli_fbase = obj->mapbase;
1901 info->dli_saddr = (void *)0;
1902 info->dli_sname = NULL;
1905 * Walk the symbol list looking for the symbol whose address is
1906 * closest to the address sent in.
1908 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
1909 def = obj->symtab + symoffset;
1912 * For skip the symbol if st_shndx is either SHN_UNDEF or
1915 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
1919 * If the symbol is greater than the specified address, or if it
1920 * is further away from addr than the current nearest symbol,
1923 symbol_addr = obj->relocbase + def->st_value;
1924 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
1927 /* Update our idea of the nearest symbol. */
1928 info->dli_sname = obj->strtab + def->st_name;
1929 info->dli_saddr = symbol_addr;
1932 if (info->dli_saddr == addr)
1940 dlinfo(void *handle, int request, void *p)
1942 const Obj_Entry *obj;
1947 if (handle == NULL || handle == RTLD_SELF) {
1950 retaddr = __builtin_return_address(0); /* __GNUC__ only */
1951 if ((obj = obj_from_addr(retaddr)) == NULL)
1952 _rtld_error("Cannot determine caller's shared object");
1954 obj = dlcheck(handle);
1963 case RTLD_DI_LINKMAP:
1964 *((struct link_map const **)p) = &obj->linkmap;
1966 case RTLD_DI_ORIGIN:
1967 error = rtld_dirname(obj->path, p);
1970 case RTLD_DI_SERINFOSIZE:
1971 case RTLD_DI_SERINFO:
1972 error = do_search_info(obj, request, (struct dl_serinfo *)p);
1976 _rtld_error("Invalid request %d passed to dlinfo()", request);
1985 struct fill_search_info_args {
1988 Dl_serinfo *serinfo;
1989 Dl_serpath *serpath;
1994 fill_search_info(const char *dir, size_t dirlen, void *param)
1996 struct fill_search_info_args *arg;
2000 if (arg->request == RTLD_DI_SERINFOSIZE) {
2001 arg->serinfo->dls_cnt ++;
2002 arg->serinfo->dls_size += dirlen + 1;
2004 struct dl_serpath *s_entry;
2006 s_entry = arg->serpath;
2007 s_entry->dls_name = arg->strspace;
2008 s_entry->dls_flags = arg->flags;
2010 strncpy(arg->strspace, dir, dirlen);
2011 arg->strspace[dirlen] = '\0';
2013 arg->strspace += dirlen + 1;
2021 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
2023 struct dl_serinfo _info;
2024 struct fill_search_info_args args;
2026 args.request = RTLD_DI_SERINFOSIZE;
2027 args.serinfo = &_info;
2029 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2032 path_enumerate(ld_library_path, fill_search_info, &args);
2033 path_enumerate(obj->rpath, fill_search_info, &args);
2034 path_enumerate(gethints(), fill_search_info, &args);
2035 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
2038 if (request == RTLD_DI_SERINFOSIZE) {
2039 info->dls_size = _info.dls_size;
2040 info->dls_cnt = _info.dls_cnt;
2044 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
2045 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
2049 args.request = RTLD_DI_SERINFO;
2050 args.serinfo = info;
2051 args.serpath = &info->dls_serpath[0];
2052 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
2054 args.flags = LA_SER_LIBPATH;
2055 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
2058 args.flags = LA_SER_RUNPATH;
2059 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
2062 args.flags = LA_SER_CONFIG;
2063 if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
2066 args.flags = LA_SER_DEFAULT;
2067 if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
2073 rtld_dirname(const char *path, char *bname)
2077 /* Empty or NULL string gets treated as "." */
2078 if (path == NULL || *path == '\0') {
2084 /* Strip trailing slashes */
2085 endp = path + strlen(path) - 1;
2086 while (endp > path && *endp == '/')
2089 /* Find the start of the dir */
2090 while (endp > path && *endp != '/')
2093 /* Either the dir is "/" or there are no slashes */
2095 bname[0] = *endp == '/' ? '/' : '.';
2101 } while (endp > path && *endp == '/');
2104 if (endp - path + 2 > PATH_MAX)
2106 _rtld_error("Filename is too long: %s", path);
2110 strncpy(bname, path, endp - path + 1);
2111 bname[endp - path + 1] = '\0';
2116 linkmap_add(Obj_Entry *obj)
2118 struct link_map *l = &obj->linkmap;
2119 struct link_map *prev;
2121 obj->linkmap.l_name = obj->path;
2122 obj->linkmap.l_addr = obj->mapbase;
2123 obj->linkmap.l_ld = obj->dynamic;
2125 /* GDB needs load offset on MIPS to use the symbols */
2126 obj->linkmap.l_offs = obj->relocbase;
2129 if (r_debug.r_map == NULL) {
2135 * Scan to the end of the list, but not past the entry for the
2136 * dynamic linker, which we want to keep at the very end.
2138 for (prev = r_debug.r_map;
2139 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
2140 prev = prev->l_next)
2143 /* Link in the new entry. */
2145 l->l_next = prev->l_next;
2146 if (l->l_next != NULL)
2147 l->l_next->l_prev = l;
2152 linkmap_delete(Obj_Entry *obj)
2154 struct link_map *l = &obj->linkmap;
2156 if (l->l_prev == NULL) {
2157 if ((r_debug.r_map = l->l_next) != NULL)
2158 l->l_next->l_prev = NULL;
2162 if ((l->l_prev->l_next = l->l_next) != NULL)
2163 l->l_next->l_prev = l->l_prev;
2167 * Function for the debugger to set a breakpoint on to gain control.
2169 * The two parameters allow the debugger to easily find and determine
2170 * what the runtime loader is doing and to whom it is doing it.
2172 * When the loadhook trap is hit (r_debug_state, set at program
2173 * initialization), the arguments can be found on the stack:
2175 * +8 struct link_map *m
2176 * +4 struct r_debug *rd
2180 r_debug_state(struct r_debug* rd, struct link_map *m)
2185 * Get address of the pointer variable in the main program.
2187 static const void **
2188 get_program_var_addr(const char *name)
2190 const Obj_Entry *obj;
2193 hash = elf_hash(name);
2194 for (obj = obj_main; obj != NULL; obj = obj->next) {
2197 if ((def = symlook_obj(name, hash, obj, false)) != NULL) {
2200 addr = (const void **)(obj->relocbase + def->st_value);
2208 * Set a pointer variable in the main program to the given value. This
2209 * is used to set key variables such as "environ" before any of the
2210 * init functions are called.
2213 set_program_var(const char *name, const void *value)
2217 if ((addr = get_program_var_addr(name)) != NULL) {
2218 dbg("\"%s\": *%p <-- %p", name, addr, value);
2224 * This is a special version of getenv which is far more efficient
2225 * at finding LD_ environment vars.
2229 _getenv_ld(const char *id)
2233 int idlen = strlen(id);
2235 if (ld_index == LD_ARY_CACHE)
2237 if (ld_index == 0) {
2238 for (i = j = 0; (envp = environ[i]) != NULL && j < LD_ARY_CACHE; ++i) {
2239 if (envp[0] == 'L' && envp[1] == 'D' && envp[2] == '_')
2246 for (i = ld_index - 1; i >= 0; --i) {
2247 if (strncmp(ld_ary[i], id, idlen) == 0 && ld_ary[i][idlen] == '=')
2248 return(ld_ary[i] + idlen + 1);
2254 * Given a symbol name in a referencing object, find the corresponding
2255 * definition of the symbol. Returns a pointer to the symbol, or NULL if
2256 * no definition was found. Returns a pointer to the Obj_Entry of the
2257 * defining object via the reference parameter DEFOBJ_OUT.
2259 static const Elf_Sym *
2260 symlook_default(const char *name, unsigned long hash,
2261 const Obj_Entry *refobj, const Obj_Entry **defobj_out, bool in_plt)
2265 const Elf_Sym *symp;
2266 const Obj_Entry *obj;
2267 const Obj_Entry *defobj;
2268 const Objlist_Entry *elm;
2271 donelist_init(&donelist);
2273 /* Look first in the referencing object if linked symbolically. */
2274 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
2275 symp = symlook_obj(name, hash, refobj, in_plt);
2282 /* Search all objects loaded at program start up. */
2283 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2284 symp = symlook_list(name, hash, &list_main, &obj, in_plt, &donelist);
2286 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2292 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
2293 STAILQ_FOREACH(elm, &list_global, link) {
2294 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2296 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt,
2299 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2305 /* Search all dlopened DAGs containing the referencing object. */
2306 STAILQ_FOREACH(elm, &refobj->dldags, link) {
2307 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2309 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt,
2312 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2319 * Search the dynamic linker itself, and possibly resolve the
2320 * symbol from there. This is how the application links to
2321 * dynamic linker services such as dlopen. Only the values listed
2322 * in the "exports" array can be resolved from the dynamic linker.
2324 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2325 symp = symlook_obj(name, hash, &obj_rtld, in_plt);
2326 if (symp != NULL && is_exported(symp)) {
2333 *defobj_out = defobj;
2337 static const Elf_Sym *
2338 symlook_list(const char *name, unsigned long hash, const Objlist *objlist,
2339 const Obj_Entry **defobj_out, bool in_plt, DoneList *dlp)
2341 const Elf_Sym *symp;
2343 const Obj_Entry *defobj;
2344 const Objlist_Entry *elm;
2348 STAILQ_FOREACH(elm, objlist, link) {
2349 if (donelist_check(dlp, elm->obj))
2351 if ((symp = symlook_obj(name, hash, elm->obj, in_plt)) != NULL) {
2352 if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
2355 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2361 *defobj_out = defobj;
2366 * Search the symbol table of a single shared object for a symbol of
2367 * the given name. Returns a pointer to the symbol, or NULL if no
2368 * definition was found.
2370 * The symbol's hash value is passed in for efficiency reasons; that
2371 * eliminates many recomputations of the hash value.
2374 symlook_obj(const char *name, unsigned long hash, const Obj_Entry *obj,
2377 if (obj->buckets != NULL) {
2378 unsigned long symnum = obj->buckets[hash % obj->nbuckets];
2380 while (symnum != STN_UNDEF) {
2381 const Elf_Sym *symp;
2384 if (symnum >= obj->nchains)
2385 return NULL; /* Bad object */
2386 symp = obj->symtab + symnum;
2387 strp = obj->strtab + symp->st_name;
2389 if (name[0] == strp[0] && strcmp(name, strp) == 0)
2390 return symp->st_shndx != SHN_UNDEF ||
2391 (!in_plt && symp->st_value != 0 &&
2392 ELF_ST_TYPE(symp->st_info) == STT_FUNC) ? symp : NULL;
2394 symnum = obj->chains[symnum];
2401 trace_loaded_objects(Obj_Entry *obj)
2403 const char *fmt1, *fmt2, *fmt, *main_local;
2406 if ((main_local = _getenv_ld("LD_TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
2409 if ((fmt1 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT1")) == NULL)
2410 fmt1 = "\t%o => %p (%x)\n";
2412 if ((fmt2 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT2")) == NULL)
2413 fmt2 = "\t%o (%x)\n";
2415 for (; obj; obj = obj->next) {
2416 Needed_Entry *needed;
2420 for (needed = obj->needed; needed; needed = needed->next) {
2421 if (needed->obj != NULL) {
2422 if (needed->obj->traced)
2424 needed->obj->traced = true;
2425 path = needed->obj->path;
2429 name = (char *)obj->strtab + needed->name;
2430 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
2432 fmt = is_lib ? fmt1 : fmt2;
2433 while ((c = *fmt++) != '\0') {
2459 printf("%s", main_local);
2462 printf("%s", obj_main->path);
2469 printf("%d", sodp->sod_major);
2472 printf("%d", sodp->sod_minor);
2479 printf("%p", needed->obj ? needed->obj->mapbase : 0);
2491 * Unload a dlopened object and its dependencies from memory and from
2492 * our data structures. It is assumed that the DAG rooted in the
2493 * object has already been unreferenced, and that the object has a
2494 * reference count of 0.
2497 unload_object(Obj_Entry *root)
2502 assert(root->refcount == 0);
2505 * Pass over the DAG removing unreferenced objects from
2506 * appropriate lists.
2508 unlink_object(root);
2510 /* Unmap all objects that are no longer referenced. */
2511 linkp = &obj_list->next;
2512 while ((obj = *linkp) != NULL) {
2513 if (obj->refcount == 0) {
2514 dbg("unloading \"%s\"", obj->path);
2515 munmap(obj->mapbase, obj->mapsize);
2516 linkmap_delete(obj);
2527 unlink_object(Obj_Entry *root)
2529 const Needed_Entry *needed;
2532 if (root->refcount == 0) {
2533 /* Remove the object from the RTLD_GLOBAL list. */
2534 objlist_remove(&list_global, root);
2536 /* Remove the object from all objects' DAG lists. */
2537 STAILQ_FOREACH(elm, &root->dagmembers , link)
2538 objlist_remove(&elm->obj->dldags, root);
2541 for (needed = root->needed; needed != NULL; needed = needed->next)
2542 if (needed->obj != NULL)
2543 unlink_object(needed->obj);
2547 unref_dag(Obj_Entry *root)
2549 const Needed_Entry *needed;
2551 if (root->refcount == 0)
2554 if (root->refcount == 0)
2555 for (needed = root->needed; needed != NULL; needed = needed->next)
2556 if (needed->obj != NULL)
2557 unref_dag(needed->obj);
2561 * Common code for MD __tls_get_addr().
2564 tls_get_addr_common(void **dtvp, int index, size_t offset)
2566 Elf_Addr* dtv = *dtvp;
2568 /* Check dtv generation in case new modules have arrived */
2569 if (dtv[0] != tls_dtv_generation) {
2575 newdtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
2577 if (to_copy > tls_max_index)
2578 to_copy = tls_max_index;
2579 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
2580 newdtv[0] = tls_dtv_generation;
2581 newdtv[1] = tls_max_index;
2588 /* Dynamically allocate module TLS if necessary */
2589 if (!dtv[index + 1]) {
2591 * here we should avoid to be re-entered by signal handler
2592 * code, I assume wlock_acquire will masked all signals,
2593 * otherwise there is race and dead lock thread itself.
2596 if (!dtv[index + 1])
2597 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
2601 return (void*) (dtv[index + 1] + offset);
2604 #if defined(RTLD_STATIC_TLS_VARIANT_II)
2607 * Allocate the static TLS area. Return a pointer to the TCB. The
2608 * static area is based on negative offsets relative to the tcb.
2610 * The TCB contains an errno pointer for the system call layer, but because
2611 * we are the RTLD we really have no idea how the caller was compiled so
2612 * the information has to be passed in. errno can either be:
2614 * type 0 errno is a simple non-TLS global pointer.
2615 * (special case for e.g. libc_rtld)
2616 * type 1 errno accessed by GOT entry (dynamically linked programs)
2617 * type 2 errno accessed by %gs:OFFSET (statically linked programs)
2620 allocate_tls(Obj_Entry *objs)
2625 struct tls_tcb *tcb;
2630 * Allocate the new TCB. static TLS storage is placed just before the
2631 * TCB to support the %gs:OFFSET (negative offset) model.
2633 data_size = (tls_static_space + RTLD_STATIC_TLS_ALIGN_MASK) &
2634 ~RTLD_STATIC_TLS_ALIGN_MASK;
2635 tcb = malloc(data_size + sizeof(*tcb));
2636 tcb = (void *)((char *)tcb + data_size); /* actual tcb location */
2638 dtv_size = (tls_max_index + 2) * sizeof(Elf_Addr);
2639 dtv = malloc(dtv_size);
2640 bzero(dtv, dtv_size);
2642 #ifdef RTLD_TCB_HAS_SELF_POINTER
2643 tcb->tcb_self = tcb;
2646 tcb->tcb_pthread = NULL;
2648 dtv[0] = tls_dtv_generation;
2649 dtv[1] = tls_max_index;
2651 for (obj = objs; obj; obj = obj->next) {
2652 if (obj->tlsoffset) {
2653 addr = (Elf_Addr)tcb - obj->tlsoffset;
2654 memset((void *)(addr + obj->tlsinitsize),
2655 0, obj->tlssize - obj->tlsinitsize);
2657 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
2658 dtv[obj->tlsindex + 1] = addr;
2665 free_tls(struct tls_tcb *tcb)
2669 Elf_Addr tls_start, tls_end;
2672 data_size = (tls_static_space + RTLD_STATIC_TLS_ALIGN_MASK) &
2673 ~RTLD_STATIC_TLS_ALIGN_MASK;
2676 tls_end = (Elf_Addr)tcb;
2677 tls_start = (Elf_Addr)tcb - data_size;
2678 for (i = 0; i < dtv_size; i++) {
2679 if (dtv[i+2] != NULL && (dtv[i+2] < tls_start || dtv[i+2] > tls_end)) {
2680 free((void *)dtv[i+2]);
2683 free((void *)tls_start);
2687 #error "Unsupported TLS layout"
2691 * Allocate TLS block for module with given index.
2694 allocate_module_tls(int index)
2699 for (obj = obj_list; obj; obj = obj->next) {
2700 if (obj->tlsindex == index)
2704 _rtld_error("Can't find module with TLS index %d", index);
2708 p = malloc(obj->tlssize);
2709 memcpy(p, obj->tlsinit, obj->tlsinitsize);
2710 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
2716 allocate_tls_offset(Obj_Entry *obj)
2723 if (obj->tlssize == 0) {
2724 obj->tls_done = true;
2728 if (obj->tlsindex == 1)
2729 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
2731 off = calculate_tls_offset(tls_last_offset, tls_last_size,
2732 obj->tlssize, obj->tlsalign);
2735 * If we have already fixed the size of the static TLS block, we
2736 * must stay within that size. When allocating the static TLS, we
2737 * leave a small amount of space spare to be used for dynamically
2738 * loading modules which use static TLS.
2740 if (tls_static_space) {
2741 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
2745 tls_last_offset = obj->tlsoffset = off;
2746 tls_last_size = obj->tlssize;
2747 obj->tls_done = true;
2753 free_tls_offset(Obj_Entry *obj)
2755 #ifdef RTLD_STATIC_TLS_VARIANT_II
2757 * If we were the last thing to allocate out of the static TLS
2758 * block, we give our space back to the 'allocator'. This is a
2759 * simplistic workaround to allow libGL.so.1 to be loaded and
2760 * unloaded multiple times. We only handle the Variant II
2761 * mechanism for now - this really needs a proper allocator.
2763 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
2764 == calculate_tls_end(tls_last_offset, tls_last_size)) {
2765 tls_last_offset -= obj->tlssize;
2772 _rtld_allocate_tls(void)
2774 struct tls_tcb *new_tcb;
2777 new_tcb = allocate_tls(obj_list);
2784 _rtld_free_tls(struct tls_tcb *tcb)