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.21 2005/03/29 23:04:36 joerg 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.1"
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 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];
158 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
159 STAILQ_HEAD_INITIALIZER(list_global);
160 static Objlist list_main = /* Objects loaded at program startup */
161 STAILQ_HEAD_INITIALIZER(list_main);
162 static Objlist list_fini = /* Objects needing fini() calls */
163 STAILQ_HEAD_INITIALIZER(list_fini);
165 static LockInfo lockinfo;
167 static Elf_Sym sym_zero; /* For resolving undefined weak refs. */
169 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
171 extern Elf_Dyn _DYNAMIC;
172 #pragma weak _DYNAMIC
175 * These are the functions the dynamic linker exports to application
176 * programs. They are the only symbols the dynamic linker is willing
177 * to export from itself.
179 static func_ptr_type exports[] = {
180 (func_ptr_type) &_rtld_error,
181 (func_ptr_type) &dlclose,
182 (func_ptr_type) &dlerror,
183 (func_ptr_type) &dlopen,
184 (func_ptr_type) &dlsym,
185 (func_ptr_type) &dladdr,
186 (func_ptr_type) &dllockinit,
187 (func_ptr_type) &dlinfo,
189 (func_ptr_type) &___tls_get_addr,
191 (func_ptr_type) &__tls_get_addr,
192 (func_ptr_type) &_rtld_allocate_tls,
193 (func_ptr_type) &_rtld_free_tls,
198 * Global declarations normally provided by crt1. The dynamic linker is
199 * not built with crt1, so we have to provide them ourselves.
205 * Globals to control TLS allocation.
207 size_t tls_last_offset; /* Static TLS offset of last module */
208 size_t tls_last_size; /* Static TLS size of last module */
209 size_t tls_static_space; /* Static TLS space allocated */
210 int tls_dtv_generation = 1; /* Used to detect when dtv size changes */
211 int tls_max_index = 1; /* Largest module index allocated */
214 * Fill in a DoneList with an allocation large enough to hold all of
215 * the currently-loaded objects. Keep this as a macro since it calls
216 * alloca and we want that to occur within the scope of the caller.
218 #define donelist_init(dlp) \
219 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
220 assert((dlp)->objs != NULL), \
221 (dlp)->num_alloc = obj_count, \
227 lockinfo.rlock_acquire(lockinfo.thelock);
228 atomic_incr_int(&lockinfo.rcount);
235 lockinfo.wlock_acquire(lockinfo.thelock);
236 atomic_incr_int(&lockinfo.wcount);
243 atomic_decr_int(&lockinfo.rcount);
244 lockinfo.rlock_release(lockinfo.thelock);
250 atomic_decr_int(&lockinfo.wcount);
251 lockinfo.wlock_release(lockinfo.thelock);
255 * Main entry point for dynamic linking. The first argument is the
256 * stack pointer. The stack is expected to be laid out as described
257 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
258 * Specifically, the stack pointer points to a word containing
259 * ARGC. Following that in the stack is a null-terminated sequence
260 * of pointers to argument strings. Then comes a null-terminated
261 * sequence of pointers to environment strings. Finally, there is a
262 * sequence of "auxiliary vector" entries.
264 * The second argument points to a place to store the dynamic linker's
265 * exit procedure pointer and the third to a place to store the main
268 * The return value is the main program's entry point.
271 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
273 Elf_Auxinfo *aux_info[AT_COUNT];
281 Objlist_Entry *entry;
285 ld_index = 0; /* don't use old env cache in case we are resident */
288 * On entry, the dynamic linker itself has not been relocated yet.
289 * Be very careful not to reference any global data until after
290 * init_rtld has returned. It is OK to reference file-scope statics
291 * and string constants, and to call static and global functions.
294 /* Find the auxiliary vector on the stack. */
297 sp += argc + 1; /* Skip over arguments and NULL terminator */
301 * If we aren't already resident we have to dig out some more info.
302 * Note that auxinfo does not exist when we are resident.
304 if (ld_resident == 0) {
305 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
307 aux = (Elf_Auxinfo *) sp;
309 /* Digest the auxiliary vector. */
310 for (i = 0; i < AT_COUNT; i++)
312 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
313 if (auxp->a_type < AT_COUNT)
314 aux_info[auxp->a_type] = auxp;
317 /* Initialize and relocate ourselves. */
318 assert(aux_info[AT_BASE] != NULL);
319 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
322 __progname = obj_rtld.path;
323 argv0 = argv[0] != NULL ? argv[0] : "(null)";
326 trust = (geteuid() == getuid()) && (getegid() == getgid());
328 ld_bind_now = _getenv_ld("LD_BIND_NOW");
330 ld_debug = _getenv_ld("LD_DEBUG");
331 ld_library_path = _getenv_ld("LD_LIBRARY_PATH");
332 ld_preload = (char *)_getenv_ld("LD_PRELOAD");
334 ld_tracing = _getenv_ld("LD_TRACE_LOADED_OBJECTS");
336 if (ld_debug != NULL && *ld_debug != '\0')
338 dbg("%s is initialized, base address = %p", __progname,
339 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
340 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
341 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
344 * If we are resident we can skip work that we have already done.
345 * Note that the stack is reset and there is no Elf_Auxinfo
346 * when running from a resident image, and the static globals setup
347 * between here and resident_skip will have already been setup.
353 * Load the main program, or process its program header if it is
356 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
357 int fd = aux_info[AT_EXECFD]->a_un.a_val;
358 dbg("loading main program");
359 obj_main = map_object(fd, argv0, NULL);
361 if (obj_main == NULL)
363 } else { /* Main program already loaded. */
364 const Elf_Phdr *phdr;
368 dbg("processing main program's program header");
369 assert(aux_info[AT_PHDR] != NULL);
370 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
371 assert(aux_info[AT_PHNUM] != NULL);
372 phnum = aux_info[AT_PHNUM]->a_un.a_val;
373 assert(aux_info[AT_PHENT] != NULL);
374 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
375 assert(aux_info[AT_ENTRY] != NULL);
376 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
377 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
381 obj_main->path = xstrdup(argv0);
382 obj_main->mainprog = true;
385 * Get the actual dynamic linker pathname from the executable if
386 * possible. (It should always be possible.) That ensures that
387 * gdb will find the right dynamic linker even if a non-standard
390 if (obj_main->interp != NULL &&
391 strcmp(obj_main->interp, obj_rtld.path) != 0) {
393 obj_rtld.path = xstrdup(obj_main->interp);
394 __progname = obj_rtld.path;
397 digest_dynamic(obj_main);
399 linkmap_add(obj_main);
400 linkmap_add(&obj_rtld);
402 /* Link the main program into the list of objects. */
403 *obj_tail = obj_main;
404 obj_tail = &obj_main->next;
406 obj_main->refcount++;
407 /* Make sure we don't call the main program's init and fini functions. */
408 obj_main->init = obj_main->fini = NULL;
410 /* Initialize a fake symbol for resolving undefined weak references. */
411 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
412 sym_zero.st_shndx = SHN_ABS;
414 dbg("loading LD_PRELOAD libraries");
415 if (load_preload_objects() == -1)
417 preload_tail = obj_tail;
419 dbg("loading needed objects");
420 if (load_needed_objects(obj_main) == -1)
423 /* Make a list of all objects loaded at startup. */
424 for (obj = obj_list; obj != NULL; obj = obj->next)
425 objlist_push_tail(&list_main, obj);
429 if (ld_tracing) { /* We're done */
430 trace_loaded_objects(obj_main);
434 if (ld_resident) /* XXX clean this up! */
437 if (getenv("LD_DUMP_REL_PRE") != NULL) {
438 dump_relocations(obj_main);
442 /* setup TLS for main thread */
443 dbg("initializing initial thread local storage");
444 STAILQ_FOREACH(entry, &list_main, link) {
446 * Allocate all the initial objects out of the static TLS
447 * block even if they didn't ask for it.
449 allocate_tls_offset(entry->obj);
451 allocate_initial_tls(obj_list);
453 if (relocate_objects(obj_main,
454 ld_bind_now != NULL && *ld_bind_now != '\0') == -1)
457 dbg("doing copy relocations");
458 if (do_copy_relocations(obj_main) == -1)
463 if (_getenv_ld("LD_RESIDENT_UNREGISTER_NOW")) {
464 if (exec_sys_unregister(-1) < 0) {
465 dbg("exec_sys_unregister failed %d\n", errno);
468 dbg("exec_sys_unregister success\n");
472 if (getenv("LD_DUMP_REL_POST") != NULL) {
473 dump_relocations(obj_main);
477 dbg("initializing key program variables");
478 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
479 set_program_var("environ", env);
481 if (_getenv_ld("LD_RESIDENT_REGISTER_NOW")) {
482 extern void resident_start(void);
484 if (exec_sys_register(resident_start) < 0) {
485 dbg("exec_sys_register failed %d\n", errno);
488 dbg("exec_sys_register success\n");
492 dbg("initializing thread locks");
493 lockdflt_init(&lockinfo);
494 lockinfo.thelock = lockinfo.lock_create(lockinfo.context);
496 /* Make a list of init functions to call. */
497 objlist_init(&initlist);
498 initlist_add_objects(obj_list, preload_tail, &initlist);
500 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
502 objlist_call_init(&initlist);
504 objlist_clear(&initlist);
509 dbg("transferring control to program entry point = %p", obj_main->entry);
511 /* Return the exit procedure and the program entry point. */
512 *exit_proc = rtld_exit;
514 return (func_ptr_type) obj_main->entry;
518 _rtld_bind(Obj_Entry *obj, Elf_Word reloff)
522 const Obj_Entry *defobj;
528 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
530 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
532 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
533 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL);
537 target = (Elf_Addr)(defobj->relocbase + def->st_value);
539 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
540 defobj->strtab + def->st_name, basename(obj->path),
541 (void *)target, basename(defobj->path));
543 reloc_jmpslot(where, target);
549 * Error reporting function. Use it like printf. If formats the message
550 * into a buffer, and sets things up so that the next call to dlerror()
551 * will return the message.
554 _rtld_error(const char *fmt, ...)
556 static char buf[512];
560 vsnprintf(buf, sizeof buf, fmt, ap);
566 * Return a dynamically-allocated copy of the current error message, if any.
571 return error_message == NULL ? NULL : xstrdup(error_message);
575 * Restore the current error message from a copy which was previously saved
576 * by errmsg_save(). The copy is freed.
579 errmsg_restore(char *saved_msg)
581 if (saved_msg == NULL)
582 error_message = NULL;
584 _rtld_error("%s", saved_msg);
590 basename(const char *name)
592 const char *p = strrchr(name, '/');
593 return p != NULL ? p + 1 : name;
599 const char *msg = dlerror();
607 * Process a shared object's DYNAMIC section, and save the important
608 * information in its Obj_Entry structure.
611 digest_dynamic(Obj_Entry *obj)
614 Needed_Entry **needed_tail = &obj->needed;
615 const Elf_Dyn *dyn_rpath = NULL;
616 int plttype = DT_REL;
618 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
619 switch (dynp->d_tag) {
622 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
626 obj->relsize = dynp->d_un.d_val;
630 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
634 obj->pltrel = (const Elf_Rel *)
635 (obj->relocbase + dynp->d_un.d_ptr);
639 obj->pltrelsize = dynp->d_un.d_val;
643 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
647 obj->relasize = dynp->d_un.d_val;
651 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
655 plttype = dynp->d_un.d_val;
656 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
660 obj->symtab = (const Elf_Sym *)
661 (obj->relocbase + dynp->d_un.d_ptr);
665 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
669 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
673 obj->strsize = dynp->d_un.d_val;
678 const Elf_Addr *hashtab = (const Elf_Addr *)
679 (obj->relocbase + dynp->d_un.d_ptr);
680 obj->nbuckets = hashtab[0];
681 obj->nchains = hashtab[1];
682 obj->buckets = hashtab + 2;
683 obj->chains = obj->buckets + obj->nbuckets;
689 Needed_Entry *nep = NEW(Needed_Entry);
690 nep->name = dynp->d_un.d_val;
695 needed_tail = &nep->next;
700 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
708 obj->symbolic = true;
712 case DT_RUNPATH: /* XXX: process separately */
714 * We have to wait until later to process this, because we
715 * might not have gotten the address of the string table yet.
721 /* Not used by the dynamic linker. */
725 obj->init = (InitFunc) (obj->relocbase + dynp->d_un.d_ptr);
729 obj->fini = (InitFunc) (obj->relocbase + dynp->d_un.d_ptr);
733 /* XXX - not implemented yet */
734 dbg("Filling in DT_DEBUG entry");
735 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
739 if (dynp->d_un.d_val & DF_ORIGIN) {
740 obj->origin_path = xmalloc(PATH_MAX);
741 if (rtld_dirname(obj->path, obj->origin_path) == -1)
744 if (dynp->d_un.d_val & DF_SYMBOLIC)
745 obj->symbolic = true;
746 if (dynp->d_un.d_val & DF_TEXTREL)
748 if (dynp->d_un.d_val & DF_BIND_NOW)
749 obj->bind_now = true;
750 if (dynp->d_un.d_val & DF_STATIC_TLS)
755 dbg("Ignoring d_tag %d = %#x", dynp->d_tag, dynp->d_tag);
762 if (plttype == DT_RELA) {
763 obj->pltrela = (const Elf_Rela *) obj->pltrel;
765 obj->pltrelasize = obj->pltrelsize;
769 if (dyn_rpath != NULL)
770 obj->rpath = obj->strtab + dyn_rpath->d_un.d_val;
774 * Process a shared object's program header. This is used only for the
775 * main program, when the kernel has already loaded the main program
776 * into memory before calling the dynamic linker. It creates and
777 * returns an Obj_Entry structure.
780 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
783 const Elf_Phdr *phlimit = phdr + phnum;
788 for (ph = phdr; ph < phlimit; ph++) {
789 switch (ph->p_type) {
792 if ((const Elf_Phdr *)ph->p_vaddr != phdr) {
793 _rtld_error("%s: invalid PT_PHDR", path);
796 obj->phdr = (const Elf_Phdr *) ph->p_vaddr;
797 obj->phsize = ph->p_memsz;
801 obj->interp = (const char *) ph->p_vaddr;
805 if (nsegs == 0) { /* First load segment */
806 obj->vaddrbase = trunc_page(ph->p_vaddr);
807 obj->mapbase = (caddr_t) obj->vaddrbase;
808 obj->relocbase = obj->mapbase - obj->vaddrbase;
809 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
811 } else { /* Last load segment */
812 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
819 obj->dynamic = (const Elf_Dyn *) ph->p_vaddr;
824 obj->tlssize = ph->p_memsz;
825 obj->tlsalign = ph->p_align;
826 obj->tlsinitsize = ph->p_filesz;
827 obj->tlsinit = (void*) ph->p_vaddr;
832 _rtld_error("%s: too few PT_LOAD segments", path);
841 dlcheck(void *handle)
845 for (obj = obj_list; obj != NULL; obj = obj->next)
846 if (obj == (Obj_Entry *) handle)
849 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
850 _rtld_error("Invalid shared object handle %p", handle);
857 * If the given object is already in the donelist, return true. Otherwise
858 * add the object to the list and return false.
861 donelist_check(DoneList *dlp, const Obj_Entry *obj)
865 for (i = 0; i < dlp->num_used; i++)
866 if (dlp->objs[i] == obj)
869 * Our donelist allocation should always be sufficient. But if
870 * our threads locking isn't working properly, more shared objects
871 * could have been loaded since we allocated the list. That should
872 * never happen, but we'll handle it properly just in case it does.
874 if (dlp->num_used < dlp->num_alloc)
875 dlp->objs[dlp->num_used++] = obj;
880 * Hash function for symbol table lookup. Don't even think about changing
881 * this. It is specified by the System V ABI.
884 elf_hash(const char *name)
886 const unsigned char *p = (const unsigned char *) name;
892 if ((g = h & 0xf0000000) != 0)
900 * Find the library with the given name, and return its full pathname.
901 * The returned string is dynamically allocated. Generates an error
902 * message and returns NULL if the library cannot be found.
904 * If the second argument is non-NULL, then it refers to an already-
905 * loaded shared object, whose library search path will be searched.
907 * The search order is:
909 * rpath in the referencing file
914 find_library(const char *name, const Obj_Entry *refobj)
918 if (strchr(name, '/') != NULL) { /* Hard coded pathname */
919 if (name[0] != '/' && !trust) {
920 _rtld_error("Absolute pathname required for shared object \"%s\"",
924 return xstrdup(name);
927 dbg(" Searching for \"%s\"", name);
929 if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
931 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
932 (pathname = search_library_path(name, gethints())) != NULL ||
933 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
936 if(refobj != NULL && refobj->path != NULL) {
937 _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
938 name, basename(refobj->path));
940 _rtld_error("Shared object \"%s\" not found", name);
946 * Given a symbol number in a referencing object, find the corresponding
947 * definition of the symbol. Returns a pointer to the symbol, or NULL if
948 * no definition was found. Returns a pointer to the Obj_Entry of the
949 * defining object via the reference parameter DEFOBJ_OUT.
952 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
953 const Obj_Entry **defobj_out, bool in_plt, SymCache *cache)
957 const Obj_Entry *defobj;
962 * If we have already found this symbol, get the information from
965 if (symnum >= refobj->nchains)
966 return NULL; /* Bad object */
967 if (cache != NULL && cache[symnum].sym != NULL) {
968 *defobj_out = cache[symnum].obj;
969 return cache[symnum].sym;
972 ref = refobj->symtab + symnum;
973 name = refobj->strtab + ref->st_name;
974 hash = elf_hash(name);
977 def = symlook_default(name, hash, refobj, &defobj, in_plt);
980 * If we found no definition and the reference is weak, treat the
981 * symbol as having the value zero.
983 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
989 *defobj_out = defobj;
990 /* Record the information in the cache to avoid subsequent lookups. */
992 cache[symnum].sym = def;
993 cache[symnum].obj = defobj;
996 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1001 * Return the search path from the ldconfig hints file, reading it if
1002 * necessary. Returns NULL if there are problems with the hints file,
1003 * or if the search path there is empty.
1010 if (hints == NULL) {
1012 struct elfhints_hdr hdr;
1015 /* Keep from trying again in case the hints file is bad. */
1018 if ((fd = open(_PATH_ELF_HINTS, O_RDONLY)) == -1)
1020 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1021 hdr.magic != ELFHINTS_MAGIC ||
1026 p = xmalloc(hdr.dirlistlen + 1);
1027 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1028 read(fd, p, hdr.dirlistlen + 1) != hdr.dirlistlen + 1) {
1036 return hints[0] != '\0' ? hints : NULL;
1040 init_dag(Obj_Entry *root)
1044 donelist_init(&donelist);
1045 init_dag1(root, root, &donelist);
1049 init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *dlp)
1051 const Needed_Entry *needed;
1053 if (donelist_check(dlp, obj))
1055 objlist_push_tail(&obj->dldags, root);
1056 objlist_push_tail(&root->dagmembers, obj);
1057 for (needed = obj->needed; needed != NULL; needed = needed->next)
1058 if (needed->obj != NULL)
1059 init_dag1(root, needed->obj, dlp);
1063 * Initialize the dynamic linker. The argument is the address at which
1064 * the dynamic linker has been mapped into memory. The primary task of
1065 * this function is to relocate the dynamic linker.
1068 init_rtld(caddr_t mapbase)
1071 * Conjure up an Obj_Entry structure for the dynamic linker.
1073 * The "path" member is supposed to be dynamically-allocated, but we
1074 * aren't yet initialized sufficiently to do that. Below we will
1075 * replace the static version with a dynamically-allocated copy.
1077 obj_rtld.path = PATH_RTLD;
1078 obj_rtld.rtld = true;
1079 obj_rtld.mapbase = mapbase;
1081 obj_rtld.relocbase = mapbase;
1083 if (&_DYNAMIC != 0) {
1084 obj_rtld.dynamic = rtld_dynamic(&obj_rtld);
1085 digest_dynamic(&obj_rtld);
1086 assert(obj_rtld.needed == NULL);
1087 assert(!obj_rtld.textrel);
1090 * Temporarily put the dynamic linker entry into the object list, so
1091 * that symbols can be found.
1093 obj_list = &obj_rtld;
1094 obj_tail = &obj_rtld.next;
1097 relocate_objects(&obj_rtld, true);
1100 /* Make the object list empty again. */
1102 obj_tail = &obj_list;
1105 /* Replace the path with a dynamically allocated copy. */
1106 obj_rtld.path = xstrdup(obj_rtld.path);
1108 r_debug.r_brk = r_debug_state;
1109 r_debug.r_state = RT_CONSISTENT;
1113 * Add the init functions from a needed object list (and its recursive
1114 * needed objects) to "list". This is not used directly; it is a helper
1115 * function for initlist_add_objects(). The write lock must be held
1116 * when this function is called.
1119 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1121 /* Recursively process the successor needed objects. */
1122 if (needed->next != NULL)
1123 initlist_add_neededs(needed->next, list);
1125 /* Process the current needed object. */
1126 if (needed->obj != NULL)
1127 initlist_add_objects(needed->obj, &needed->obj->next, list);
1131 * Scan all of the DAGs rooted in the range of objects from "obj" to
1132 * "tail" and add their init functions to "list". This recurses over
1133 * the DAGs and ensure the proper init ordering such that each object's
1134 * needed libraries are initialized before the object itself. At the
1135 * same time, this function adds the objects to the global finalization
1136 * list "list_fini" in the opposite order. The write lock must be
1137 * held when this function is called.
1140 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1144 obj->init_done = true;
1146 /* Recursively process the successor objects. */
1147 if (&obj->next != tail)
1148 initlist_add_objects(obj->next, tail, list);
1150 /* Recursively process the needed objects. */
1151 if (obj->needed != NULL)
1152 initlist_add_neededs(obj->needed, list);
1154 /* Add the object to the init list. */
1155 if (obj->init != NULL)
1156 objlist_push_tail(list, obj);
1158 /* Add the object to the global fini list in the reverse order. */
1159 if (obj->fini != NULL)
1160 objlist_push_head(&list_fini, obj);
1164 is_exported(const Elf_Sym *def)
1166 func_ptr_type value;
1167 const func_ptr_type *p;
1169 value = (func_ptr_type)(obj_rtld.relocbase + def->st_value);
1170 for (p = exports; *p != NULL; p++)
1177 * Given a shared object, traverse its list of needed objects, and load
1178 * each of them. Returns 0 on success. Generates an error message and
1179 * returns -1 on failure.
1182 load_needed_objects(Obj_Entry *first)
1186 for (obj = first; obj != NULL; obj = obj->next) {
1187 Needed_Entry *needed;
1189 for (needed = obj->needed; needed != NULL; needed = needed->next) {
1190 const char *name = obj->strtab + needed->name;
1191 char *path = find_library(name, obj);
1194 if (path == NULL && !ld_tracing)
1198 needed->obj = load_object(path);
1199 if (needed->obj == NULL && !ld_tracing)
1200 return -1; /* XXX - cleanup */
1209 load_preload_objects(void)
1211 char *p = ld_preload;
1212 static const char delim[] = " \t:;";
1217 p += strspn(p, delim);
1218 while (*p != '\0') {
1219 size_t len = strcspn(p, delim);
1225 if ((path = find_library(p, NULL)) == NULL)
1227 if (load_object(path) == NULL)
1228 return -1; /* XXX - cleanup */
1231 p += strspn(p, delim);
1237 * Returns a pointer to the Obj_Entry for the object with the given path.
1238 * Returns NULL if no matching object was found.
1241 find_object(const char *path)
1245 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
1246 if (strcmp(obj->path, path) == 0)
1253 * Returns a pointer to the Obj_Entry for the object matching device and
1254 * inode of the given path. If no matching object was found, the descriptor
1255 * is returned in fd.
1256 * Returns with obj == NULL && fd == -1 on error.
1259 find_object2(const char *path, int *fd, struct stat *sb)
1263 if ((*fd = open(path, O_RDONLY)) == -1) {
1264 _rtld_error("Cannot open \"%s\"", path);
1268 if (fstat(*fd, sb) == -1) {
1269 _rtld_error("Cannot fstat \"%s\"", path);
1275 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
1276 if (obj->ino == sb->st_ino && obj->dev == sb->st_dev) {
1286 * Load a shared object into memory, if it is not already loaded. The
1287 * argument must be a string allocated on the heap. This function assumes
1288 * responsibility for freeing it when necessary.
1290 * Returns a pointer to the Obj_Entry for the object. Returns NULL
1294 load_object(char *path)
1300 obj = find_object(path);
1307 obj = find_object2(path, &fd, &sb);
1312 } else if (fd == -1) {
1317 dbg("loading \"%s\"", path);
1318 obj = map_object(fd, path, &sb);
1326 digest_dynamic(obj);
1329 obj_tail = &obj->next;
1331 linkmap_add(obj); /* for GDB & dlinfo() */
1333 dbg(" %p .. %p: %s", obj->mapbase, obj->mapbase + obj->mapsize - 1,
1336 dbg(" WARNING: %s has impure text", obj->path);
1343 * Check for locking violations and die if one is found.
1350 rcount = lockinfo.rcount;
1351 wcount = lockinfo.wcount;
1352 assert(rcount >= 0);
1353 assert(wcount >= 0);
1354 if (wcount > 1 || (wcount != 0 && rcount != 0)) {
1355 _rtld_error("Application locking error: %d readers and %d writers"
1356 " in dynamic linker. See DLLOCKINIT(3) in manual pages.",
1363 obj_from_addr(const void *addr)
1367 for (obj = obj_list; obj != NULL; obj = obj->next) {
1368 if (addr < (void *) obj->mapbase)
1370 if (addr < (void *) (obj->mapbase + obj->mapsize))
1377 * Call the finalization functions for each of the objects in "list"
1378 * which are unreferenced. All of the objects are expected to have
1379 * non-NULL fini functions.
1382 objlist_call_fini(Objlist *list)
1388 * Preserve the current error message since a fini function might
1389 * call into the dynamic linker and overwrite it.
1391 saved_msg = errmsg_save();
1392 STAILQ_FOREACH(elm, list, link) {
1393 if (elm->obj->refcount == 0) {
1394 dbg("calling fini function for %s", elm->obj->path);
1395 (*elm->obj->fini)();
1398 errmsg_restore(saved_msg);
1402 * Call the initialization functions for each of the objects in
1403 * "list". All of the objects are expected to have non-NULL init
1407 objlist_call_init(Objlist *list)
1413 * Preserve the current error message since an init function might
1414 * call into the dynamic linker and overwrite it.
1416 saved_msg = errmsg_save();
1417 STAILQ_FOREACH(elm, list, link) {
1418 dbg("calling init function for %s", elm->obj->path);
1419 (*elm->obj->init)();
1421 errmsg_restore(saved_msg);
1425 objlist_clear(Objlist *list)
1429 while (!STAILQ_EMPTY(list)) {
1430 elm = STAILQ_FIRST(list);
1431 STAILQ_REMOVE_HEAD(list, link);
1436 static Objlist_Entry *
1437 objlist_find(Objlist *list, const Obj_Entry *obj)
1441 STAILQ_FOREACH(elm, list, link)
1442 if (elm->obj == obj)
1448 objlist_init(Objlist *list)
1454 objlist_push_head(Objlist *list, Obj_Entry *obj)
1458 elm = NEW(Objlist_Entry);
1460 STAILQ_INSERT_HEAD(list, elm, link);
1464 objlist_push_tail(Objlist *list, Obj_Entry *obj)
1468 elm = NEW(Objlist_Entry);
1470 STAILQ_INSERT_TAIL(list, elm, link);
1474 objlist_remove(Objlist *list, Obj_Entry *obj)
1478 if ((elm = objlist_find(list, obj)) != NULL) {
1479 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1485 * Remove all of the unreferenced objects from "list".
1488 objlist_remove_unref(Objlist *list)
1493 STAILQ_INIT(&newlist);
1494 while (!STAILQ_EMPTY(list)) {
1495 elm = STAILQ_FIRST(list);
1496 STAILQ_REMOVE_HEAD(list, link);
1497 if (elm->obj->refcount == 0)
1500 STAILQ_INSERT_TAIL(&newlist, elm, link);
1506 * Relocate newly-loaded shared objects. The argument is a pointer to
1507 * the Obj_Entry for the first such object. All objects from the first
1508 * to the end of the list of objects are relocated. Returns 0 on success,
1512 relocate_objects(Obj_Entry *first, bool bind_now)
1516 for (obj = first; obj != NULL; obj = obj->next) {
1517 if (obj != &obj_rtld)
1518 dbg("relocating \"%s\"", obj->path);
1519 if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
1520 obj->symtab == NULL || obj->strtab == NULL) {
1521 _rtld_error("%s: Shared object has no run-time symbol table",
1527 /* There are relocations to the write-protected text segment. */
1528 if (mprotect(obj->mapbase, obj->textsize,
1529 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
1530 _rtld_error("%s: Cannot write-enable text segment: %s",
1531 obj->path, strerror(errno));
1536 /* Process the non-PLT relocations. */
1537 if (reloc_non_plt(obj, &obj_rtld))
1541 * Reprotect the text segment. Make sure it is included in the
1542 * core dump since we modified it. This unfortunately causes the
1543 * entire text segment to core-out but we don't have much of a
1544 * choice. We could try to only reenable core dumps on pages
1545 * in which relocations occured but that is likely most of the text
1546 * pages anyway, and even that would not work because the rest of
1547 * the text pages would wind up as a read-only OBJT_DEFAULT object
1548 * (created due to our modifications) backed by the original OBJT_VNODE
1549 * object, and the ELF coredump code is currently only able to dump
1550 * vnode records for pure vnode-backed mappings, not vnode backings
1551 * to memory objects.
1554 madvise(obj->mapbase, obj->textsize, MADV_CORE);
1555 if (mprotect(obj->mapbase, obj->textsize,
1556 PROT_READ|PROT_EXEC) == -1) {
1557 _rtld_error("%s: Cannot write-protect text segment: %s",
1558 obj->path, strerror(errno));
1563 /* Process the PLT relocations. */
1564 if (reloc_plt(obj) == -1)
1566 /* Relocate the jump slots if we are doing immediate binding. */
1567 if (obj->bind_now || bind_now)
1568 if (reloc_jmpslots(obj) == -1)
1573 * Set up the magic number and version in the Obj_Entry. These
1574 * were checked in the crt1.o from the original ElfKit, so we
1575 * set them for backward compatibility.
1577 obj->magic = RTLD_MAGIC;
1578 obj->version = RTLD_VERSION;
1580 /* Set the special PLT or GOT entries. */
1588 * Cleanup procedure. It will be called (by the atexit mechanism) just
1589 * before the process exits.
1597 /* Clear all the reference counts so the fini functions will be called. */
1598 for (obj = obj_list; obj != NULL; obj = obj->next)
1600 objlist_call_fini(&list_fini);
1601 /* No need to remove the items from the list, since we are exiting. */
1605 path_enumerate(const char *path, path_enum_proc callback, void *arg)
1610 path += strspn(path, ":;");
1611 while (*path != '\0') {
1615 len = strcspn(path, ":;");
1616 res = callback(path, len, arg);
1622 path += strspn(path, ":;");
1628 struct try_library_args {
1636 try_library_path(const char *dir, size_t dirlen, void *param)
1638 struct try_library_args *arg;
1641 if (*dir == '/' || trust) {
1644 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
1647 pathname = arg->buffer;
1648 strncpy(pathname, dir, dirlen);
1649 pathname[dirlen] = '/';
1650 strcpy(pathname + dirlen + 1, arg->name);
1652 dbg(" Trying \"%s\"", pathname);
1653 if (access(pathname, F_OK) == 0) { /* We found it */
1654 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
1655 strcpy(pathname, arg->buffer);
1663 search_library_path(const char *name, const char *path)
1666 struct try_library_args arg;
1672 arg.namelen = strlen(name);
1673 arg.buffer = xmalloc(PATH_MAX);
1674 arg.buflen = PATH_MAX;
1676 p = path_enumerate(path, try_library_path, &arg);
1684 dlclose(void *handle)
1689 root = dlcheck(handle);
1695 /* Unreference the object and its dependencies. */
1696 root->dl_refcount--;
1699 if (root->refcount == 0) {
1701 * The object is no longer referenced, so we must unload it.
1702 * First, call the fini functions with no locks held.
1705 objlist_call_fini(&list_fini);
1707 objlist_remove_unref(&list_fini);
1709 /* Finish cleaning up the newly-unreferenced objects. */
1710 GDB_STATE(RT_DELETE,&root->linkmap);
1711 unload_object(root);
1712 GDB_STATE(RT_CONSISTENT,NULL);
1721 char *msg = error_message;
1722 error_message = NULL;
1727 * This function is deprecated and has no effect.
1730 dllockinit(void *context,
1731 void *(*lock_create)(void *context),
1732 void (*rlock_acquire)(void *lock),
1733 void (*wlock_acquire)(void *lock),
1734 void (*lock_release)(void *lock),
1735 void (*lock_destroy)(void *lock),
1736 void (*context_destroy)(void *context))
1738 static void *cur_context;
1739 static void (*cur_context_destroy)(void *);
1741 /* Just destroy the context from the previous call, if necessary. */
1742 if (cur_context_destroy != NULL)
1743 cur_context_destroy(cur_context);
1744 cur_context = context;
1745 cur_context_destroy = context_destroy;
1749 dlopen(const char *name, int mode)
1751 Obj_Entry **old_obj_tail;
1756 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
1757 if (ld_tracing != NULL)
1758 environ = (char **)*get_program_var_addr("environ");
1760 objlist_init(&initlist);
1763 GDB_STATE(RT_ADD,NULL);
1765 old_obj_tail = obj_tail;
1771 char *path = find_library(name, obj_main);
1773 obj = load_object(path);
1778 if ((mode & RTLD_GLOBAL) && objlist_find(&list_global, obj) == NULL)
1779 objlist_push_tail(&list_global, obj);
1780 mode &= RTLD_MODEMASK;
1781 if (*old_obj_tail != NULL) { /* We loaded something new. */
1782 assert(*old_obj_tail == obj);
1784 result = load_needed_objects(obj);
1785 if (result != -1 && ld_tracing)
1789 (init_dag(obj), relocate_objects(obj, mode == RTLD_NOW)) == -1) {
1792 if (obj->refcount == 0)
1796 /* Make list of init functions to call. */
1797 initlist_add_objects(obj, &obj->next, &initlist);
1799 } else if (ld_tracing)
1803 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
1805 /* Call the init functions with no locks held. */
1807 objlist_call_init(&initlist);
1809 objlist_clear(&initlist);
1813 trace_loaded_objects(obj);
1819 dlsym(void *handle, const char *name)
1821 const Obj_Entry *obj;
1824 const Obj_Entry *defobj;
1826 hash = elf_hash(name);
1831 if (handle == NULL || handle == RTLD_NEXT ||
1832 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
1835 retaddr = __builtin_return_address(0); /* __GNUC__ only */
1836 if ((obj = obj_from_addr(retaddr)) == NULL) {
1837 _rtld_error("Cannot determine caller's shared object");
1841 if (handle == NULL) { /* Just the caller's shared object. */
1842 def = symlook_obj(name, hash, obj, true);
1844 } else if (handle == RTLD_NEXT || /* Objects after caller's */
1845 handle == RTLD_SELF) { /* ... caller included */
1846 if (handle == RTLD_NEXT)
1848 for (; obj != NULL; obj = obj->next) {
1849 if ((def = symlook_obj(name, hash, obj, true)) != NULL) {
1855 assert(handle == RTLD_DEFAULT);
1856 def = symlook_default(name, hash, obj, &defobj, true);
1859 if ((obj = dlcheck(handle)) == NULL) {
1864 if (obj->mainprog) {
1867 /* Search main program and all libraries loaded by it. */
1868 donelist_init(&donelist);
1869 def = symlook_list(name, hash, &list_main, &defobj, true,
1873 * XXX - This isn't correct. The search should include the whole
1874 * DAG rooted at the given object.
1876 def = symlook_obj(name, hash, obj, true);
1883 return defobj->relocbase + def->st_value;
1886 _rtld_error("Undefined symbol \"%s\"", name);
1892 dladdr(const void *addr, Dl_info *info)
1894 const Obj_Entry *obj;
1897 unsigned long symoffset;
1900 obj = obj_from_addr(addr);
1902 _rtld_error("No shared object contains address");
1906 info->dli_fname = obj->path;
1907 info->dli_fbase = obj->mapbase;
1908 info->dli_saddr = (void *)0;
1909 info->dli_sname = NULL;
1912 * Walk the symbol list looking for the symbol whose address is
1913 * closest to the address sent in.
1915 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
1916 def = obj->symtab + symoffset;
1919 * For skip the symbol if st_shndx is either SHN_UNDEF or
1922 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
1926 * If the symbol is greater than the specified address, or if it
1927 * is further away from addr than the current nearest symbol,
1930 symbol_addr = obj->relocbase + def->st_value;
1931 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
1934 /* Update our idea of the nearest symbol. */
1935 info->dli_sname = obj->strtab + def->st_name;
1936 info->dli_saddr = symbol_addr;
1939 if (info->dli_saddr == addr)
1947 dlinfo(void *handle, int request, void *p)
1949 const Obj_Entry *obj;
1954 if (handle == NULL || handle == RTLD_SELF) {
1957 retaddr = __builtin_return_address(0); /* __GNUC__ only */
1958 if ((obj = obj_from_addr(retaddr)) == NULL)
1959 _rtld_error("Cannot determine caller's shared object");
1961 obj = dlcheck(handle);
1970 case RTLD_DI_LINKMAP:
1971 *((struct link_map const **)p) = &obj->linkmap;
1973 case RTLD_DI_ORIGIN:
1974 error = rtld_dirname(obj->path, p);
1977 case RTLD_DI_SERINFOSIZE:
1978 case RTLD_DI_SERINFO:
1979 error = do_search_info(obj, request, (struct dl_serinfo *)p);
1983 _rtld_error("Invalid request %d passed to dlinfo()", request);
1992 struct fill_search_info_args {
1995 Dl_serinfo *serinfo;
1996 Dl_serpath *serpath;
2001 fill_search_info(const char *dir, size_t dirlen, void *param)
2003 struct fill_search_info_args *arg;
2007 if (arg->request == RTLD_DI_SERINFOSIZE) {
2008 arg->serinfo->dls_cnt ++;
2009 arg->serinfo->dls_size += dirlen + 1;
2011 struct dl_serpath *s_entry;
2013 s_entry = arg->serpath;
2014 s_entry->dls_name = arg->strspace;
2015 s_entry->dls_flags = arg->flags;
2017 strncpy(arg->strspace, dir, dirlen);
2018 arg->strspace[dirlen] = '\0';
2020 arg->strspace += dirlen + 1;
2028 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
2030 struct dl_serinfo _info;
2031 struct fill_search_info_args args;
2033 args.request = RTLD_DI_SERINFOSIZE;
2034 args.serinfo = &_info;
2036 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2039 path_enumerate(ld_library_path, fill_search_info, &args);
2040 path_enumerate(obj->rpath, fill_search_info, &args);
2041 path_enumerate(gethints(), fill_search_info, &args);
2042 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
2045 if (request == RTLD_DI_SERINFOSIZE) {
2046 info->dls_size = _info.dls_size;
2047 info->dls_cnt = _info.dls_cnt;
2051 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
2052 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
2056 args.request = RTLD_DI_SERINFO;
2057 args.serinfo = info;
2058 args.serpath = &info->dls_serpath[0];
2059 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
2061 args.flags = LA_SER_LIBPATH;
2062 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
2065 args.flags = LA_SER_RUNPATH;
2066 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
2069 args.flags = LA_SER_CONFIG;
2070 if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
2073 args.flags = LA_SER_DEFAULT;
2074 if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
2080 rtld_dirname(const char *path, char *bname)
2084 /* Empty or NULL string gets treated as "." */
2085 if (path == NULL || *path == '\0') {
2091 /* Strip trailing slashes */
2092 endp = path + strlen(path) - 1;
2093 while (endp > path && *endp == '/')
2096 /* Find the start of the dir */
2097 while (endp > path && *endp != '/')
2100 /* Either the dir is "/" or there are no slashes */
2102 bname[0] = *endp == '/' ? '/' : '.';
2108 } while (endp > path && *endp == '/');
2111 if (endp - path + 2 > PATH_MAX)
2113 _rtld_error("Filename is too long: %s", path);
2117 strncpy(bname, path, endp - path + 1);
2118 bname[endp - path + 1] = '\0';
2123 linkmap_add(Obj_Entry *obj)
2125 struct link_map *l = &obj->linkmap;
2126 struct link_map *prev;
2128 obj->linkmap.l_name = obj->path;
2129 obj->linkmap.l_addr = obj->mapbase;
2130 obj->linkmap.l_ld = obj->dynamic;
2132 /* GDB needs load offset on MIPS to use the symbols */
2133 obj->linkmap.l_offs = obj->relocbase;
2136 if (r_debug.r_map == NULL) {
2142 * Scan to the end of the list, but not past the entry for the
2143 * dynamic linker, which we want to keep at the very end.
2145 for (prev = r_debug.r_map;
2146 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
2147 prev = prev->l_next)
2150 /* Link in the new entry. */
2152 l->l_next = prev->l_next;
2153 if (l->l_next != NULL)
2154 l->l_next->l_prev = l;
2159 linkmap_delete(Obj_Entry *obj)
2161 struct link_map *l = &obj->linkmap;
2163 if (l->l_prev == NULL) {
2164 if ((r_debug.r_map = l->l_next) != NULL)
2165 l->l_next->l_prev = NULL;
2169 if ((l->l_prev->l_next = l->l_next) != NULL)
2170 l->l_next->l_prev = l->l_prev;
2174 * Function for the debugger to set a breakpoint on to gain control.
2176 * The two parameters allow the debugger to easily find and determine
2177 * what the runtime loader is doing and to whom it is doing it.
2179 * When the loadhook trap is hit (r_debug_state, set at program
2180 * initialization), the arguments can be found on the stack:
2182 * +8 struct link_map *m
2183 * +4 struct r_debug *rd
2187 r_debug_state(struct r_debug* rd, struct link_map *m)
2192 * Get address of the pointer variable in the main program.
2194 static const void **
2195 get_program_var_addr(const char *name)
2197 const Obj_Entry *obj;
2200 hash = elf_hash(name);
2201 for (obj = obj_main; obj != NULL; obj = obj->next) {
2204 if ((def = symlook_obj(name, hash, obj, false)) != NULL) {
2207 addr = (const void **)(obj->relocbase + def->st_value);
2215 * Set a pointer variable in the main program to the given value. This
2216 * is used to set key variables such as "environ" before any of the
2217 * init functions are called.
2220 set_program_var(const char *name, const void *value)
2224 if ((addr = get_program_var_addr(name)) != NULL) {
2225 dbg("\"%s\": *%p <-- %p", name, addr, value);
2231 * This is a special version of getenv which is far more efficient
2232 * at finding LD_ environment vars.
2236 _getenv_ld(const char *id)
2240 int idlen = strlen(id);
2242 if (ld_index == LD_ARY_CACHE)
2244 if (ld_index == 0) {
2245 for (i = j = 0; (envp = environ[i]) != NULL && j < LD_ARY_CACHE; ++i) {
2246 if (envp[0] == 'L' && envp[1] == 'D' && envp[2] == '_')
2253 for (i = ld_index - 1; i >= 0; --i) {
2254 if (strncmp(ld_ary[i], id, idlen) == 0 && ld_ary[i][idlen] == '=')
2255 return(ld_ary[i] + idlen + 1);
2261 * Given a symbol name in a referencing object, find the corresponding
2262 * definition of the symbol. Returns a pointer to the symbol, or NULL if
2263 * no definition was found. Returns a pointer to the Obj_Entry of the
2264 * defining object via the reference parameter DEFOBJ_OUT.
2266 static const Elf_Sym *
2267 symlook_default(const char *name, unsigned long hash,
2268 const Obj_Entry *refobj, const Obj_Entry **defobj_out, bool in_plt)
2272 const Elf_Sym *symp;
2273 const Obj_Entry *obj;
2274 const Obj_Entry *defobj;
2275 const Objlist_Entry *elm;
2278 donelist_init(&donelist);
2280 /* Look first in the referencing object if linked symbolically. */
2281 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
2282 symp = symlook_obj(name, hash, refobj, in_plt);
2289 /* Search all objects loaded at program start up. */
2290 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2291 symp = symlook_list(name, hash, &list_main, &obj, in_plt, &donelist);
2293 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2299 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
2300 STAILQ_FOREACH(elm, &list_global, link) {
2301 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2303 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt,
2306 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2312 /* Search all dlopened DAGs containing the referencing object. */
2313 STAILQ_FOREACH(elm, &refobj->dldags, link) {
2314 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2316 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt,
2319 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2326 * Search the dynamic linker itself, and possibly resolve the
2327 * symbol from there. This is how the application links to
2328 * dynamic linker services such as dlopen. Only the values listed
2329 * in the "exports" array can be resolved from the dynamic linker.
2331 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2332 symp = symlook_obj(name, hash, &obj_rtld, in_plt);
2333 if (symp != NULL && is_exported(symp)) {
2340 *defobj_out = defobj;
2344 static const Elf_Sym *
2345 symlook_list(const char *name, unsigned long hash, Objlist *objlist,
2346 const Obj_Entry **defobj_out, bool in_plt, DoneList *dlp)
2348 const Elf_Sym *symp;
2350 const Obj_Entry *defobj;
2351 const Objlist_Entry *elm;
2355 STAILQ_FOREACH(elm, objlist, link) {
2356 if (donelist_check(dlp, elm->obj))
2358 if ((symp = symlook_obj(name, hash, elm->obj, in_plt)) != NULL) {
2359 if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
2362 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2368 *defobj_out = defobj;
2373 * Search the symbol table of a single shared object for a symbol of
2374 * the given name. Returns a pointer to the symbol, or NULL if no
2375 * definition was found.
2377 * The symbol's hash value is passed in for efficiency reasons; that
2378 * eliminates many recomputations of the hash value.
2381 symlook_obj(const char *name, unsigned long hash, const Obj_Entry *obj,
2384 if (obj->buckets != NULL) {
2385 unsigned long symnum = obj->buckets[hash % obj->nbuckets];
2387 while (symnum != STN_UNDEF) {
2388 const Elf_Sym *symp;
2391 if (symnum >= obj->nchains)
2392 return NULL; /* Bad object */
2393 symp = obj->symtab + symnum;
2394 strp = obj->strtab + symp->st_name;
2396 if (name[0] == strp[0] && strcmp(name, strp) == 0)
2397 return symp->st_shndx != SHN_UNDEF ||
2398 (!in_plt && symp->st_value != 0 &&
2399 ELF_ST_TYPE(symp->st_info) == STT_FUNC) ? symp : NULL;
2401 symnum = obj->chains[symnum];
2408 trace_loaded_objects(Obj_Entry *obj)
2410 const char *fmt1, *fmt2, *fmt, *main_local;
2413 if ((main_local = _getenv_ld("LD_TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
2416 if ((fmt1 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT1")) == NULL)
2417 fmt1 = "\t%o => %p (%x)\n";
2419 if ((fmt2 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT2")) == NULL)
2420 fmt2 = "\t%o (%x)\n";
2422 for (; obj; obj = obj->next) {
2423 Needed_Entry *needed;
2427 for (needed = obj->needed; needed; needed = needed->next) {
2428 if (needed->obj != NULL) {
2429 if (needed->obj->traced)
2431 needed->obj->traced = true;
2432 path = needed->obj->path;
2436 name = (char *)obj->strtab + needed->name;
2437 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
2439 fmt = is_lib ? fmt1 : fmt2;
2440 while ((c = *fmt++) != '\0') {
2466 printf("%s", main_local);
2469 printf("%s", obj_main->path);
2476 printf("%d", sodp->sod_major);
2479 printf("%d", sodp->sod_minor);
2486 printf("%p", needed->obj ? needed->obj->mapbase : 0);
2498 * Unload a dlopened object and its dependencies from memory and from
2499 * our data structures. It is assumed that the DAG rooted in the
2500 * object has already been unreferenced, and that the object has a
2501 * reference count of 0.
2504 unload_object(Obj_Entry *root)
2509 assert(root->refcount == 0);
2512 * Pass over the DAG removing unreferenced objects from
2513 * appropriate lists.
2515 unlink_object(root);
2517 /* Unmap all objects that are no longer referenced. */
2518 linkp = &obj_list->next;
2519 while ((obj = *linkp) != NULL) {
2520 if (obj->refcount == 0) {
2521 dbg("unloading \"%s\"", obj->path);
2522 munmap(obj->mapbase, obj->mapsize);
2523 linkmap_delete(obj);
2534 unlink_object(Obj_Entry *root)
2536 const Needed_Entry *needed;
2539 if (root->refcount == 0) {
2540 /* Remove the object from the RTLD_GLOBAL list. */
2541 objlist_remove(&list_global, root);
2543 /* Remove the object from all objects' DAG lists. */
2544 STAILQ_FOREACH(elm, &root->dagmembers , link)
2545 objlist_remove(&elm->obj->dldags, root);
2548 for (needed = root->needed; needed != NULL; needed = needed->next)
2549 if (needed->obj != NULL)
2550 unlink_object(needed->obj);
2554 unref_dag(Obj_Entry *root)
2556 const Needed_Entry *needed;
2558 if (root->refcount == 0)
2561 if (root->refcount == 0)
2562 for (needed = root->needed; needed != NULL; needed = needed->next)
2563 if (needed->obj != NULL)
2564 unref_dag(needed->obj);
2568 * Common code for MD __tls_get_addr().
2571 tls_get_addr_common(void **dtvp, int index, size_t offset)
2573 Elf_Addr* dtv = *dtvp;
2575 /* Check dtv generation in case new modules have arrived */
2576 if (dtv[0] != tls_dtv_generation) {
2582 newdtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
2584 if (to_copy > tls_max_index)
2585 to_copy = tls_max_index;
2586 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
2587 newdtv[0] = tls_dtv_generation;
2588 newdtv[1] = tls_max_index;
2595 /* Dynamically allocate module TLS if necessary */
2596 if (!dtv[index + 1]) {
2598 * here we should avoid to be re-entered by signal handler
2599 * code, I assume wlock_acquire will masked all signals,
2600 * otherwise there is race and dead lock thread itself.
2603 if (!dtv[index + 1])
2604 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
2608 return (void*) (dtv[index + 1] + offset);
2611 #if defined(RTLD_STATIC_TLS_VARIANT_II)
2614 * Allocate the static TLS area. Return a pointer to the TCB. The
2615 * static area is based on negative offsets relative to the tcb.
2618 allocate_tls(Obj_Entry *objs, struct tls_tcb *old_tcb)
2623 struct tls_tcb *tcb;
2624 Elf_Addr *dtv, *old_dtv;
2629 * Allocate the new TCB. static TLS storage is placed just before the
2630 * TCB to support the %gs:OFFSET (negative offset) model.
2632 data_size = (tls_static_space + RTLD_STATIC_TLS_ALIGN_MASK) &
2633 ~RTLD_STATIC_TLS_ALIGN_MASK;
2634 tcb = malloc(data_size + sizeof(*tcb));
2635 tcb = (void *)((char *)tcb + data_size); /* actual tcb location */
2637 dtv_size = (tls_max_index + 2) * sizeof(Elf_Addr);
2638 dtv = malloc(dtv_size);
2639 bzero(dtv, dtv_size);
2641 #ifdef RTLD_TCB_HAS_SELF_POINTER
2642 tcb->tcb_self = tcb;
2645 tcb->tcb_pthread = NULL;
2647 dtv[0] = tls_dtv_generation;
2648 dtv[1] = tls_max_index;
2651 * If a template tcb is supplied, copy the TLS storage from the template
2652 * to the new tcb, otherwise create a pristine data set.
2656 * Copy the static TLS block over whole.
2658 memcpy((char *)tcb - data_size, (char *)old_tcb - data_size, data_size);
2661 * If any dynamic TLS blocks have been created tls_get_addr(),
2664 old_dtv = old_tcb->tcb_dtv;
2665 for (i = 0; i < old_dtv[1]; i++) {
2666 if (old_dtv[i+2] < (Elf_Addr)((char *)old_tcb - data_size) ||
2667 old_dtv[i+2] >= (Elf_Addr)((char *)old_tcb)
2669 dtv[i + 2] = old_dtv[i + 2];
2675 for (obj = objs; obj; obj = obj->next) {
2676 if (obj->tlsoffset) {
2677 addr = (Elf_Addr)tcb - obj->tlsoffset;
2678 memset((void *)(addr + obj->tlsinitsize),
2679 0, obj->tlssize - obj->tlsinitsize);
2681 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
2682 dtv[obj->tlsindex + 1] = addr;
2690 free_tls(struct tls_tcb *tcb)
2694 Elf_Addr tls_start, tls_end;
2697 data_size = (tls_static_space + RTLD_STATIC_TLS_ALIGN_MASK) &
2698 ~RTLD_STATIC_TLS_ALIGN_MASK;
2701 tls_end = (Elf_Addr)tcb;
2702 tls_start = (Elf_Addr)tcb - data_size;
2703 for (i = 0; i < dtv_size; i++) {
2704 if (dtv[i+2] != NULL && (dtv[i+2] < tls_start || dtv[i+2] > tls_end)) {
2705 free((void *)dtv[i+2]);
2708 free((void *)tls_start);
2712 #error "Unsupported TLS layout"
2716 * Allocate TLS block for module with given index.
2719 allocate_module_tls(int index)
2724 for (obj = obj_list; obj; obj = obj->next) {
2725 if (obj->tlsindex == index)
2729 _rtld_error("Can't find module with TLS index %d", index);
2733 p = malloc(obj->tlssize);
2734 memcpy(p, obj->tlsinit, obj->tlsinitsize);
2735 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
2741 allocate_tls_offset(Obj_Entry *obj)
2748 if (obj->tlssize == 0) {
2749 obj->tls_done = true;
2753 if (obj->tlsindex == 1)
2754 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
2756 off = calculate_tls_offset(tls_last_offset, tls_last_size,
2757 obj->tlssize, obj->tlsalign);
2760 * If we have already fixed the size of the static TLS block, we
2761 * must stay within that size. When allocating the static TLS, we
2762 * leave a small amount of space spare to be used for dynamically
2763 * loading modules which use static TLS.
2765 if (tls_static_space) {
2766 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
2770 tls_last_offset = obj->tlsoffset = off;
2771 tls_last_size = obj->tlssize;
2772 obj->tls_done = true;
2778 free_tls_offset(Obj_Entry *obj)
2780 #ifdef RTLD_STATIC_TLS_VARIANT_II
2782 * If we were the last thing to allocate out of the static TLS
2783 * block, we give our space back to the 'allocator'. This is a
2784 * simplistic workaround to allow libGL.so.1 to be loaded and
2785 * unloaded multiple times. We only handle the Variant II
2786 * mechanism for now - this really needs a proper allocator.
2788 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
2789 == calculate_tls_end(tls_last_offset, tls_last_size)) {
2790 tls_last_offset -= obj->tlssize;
2797 _rtld_allocate_tls(struct tls_tcb *old_tcb)
2799 struct tls_tcb *new_tcb;
2802 new_tcb = allocate_tls(obj_list, old_tcb);
2809 _rtld_free_tls(struct tls_tcb *tcb)