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.6 2004/01/20 21:13:57 dillon 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>
58 #define END_SYM "_end"
59 #define PATH_RTLD "/usr/libexec/ld-elf.so.1"
60 #define LD_ARY_CACHE 16
63 typedef void (*func_ptr_type)();
64 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg);
67 * This structure provides a reentrant way to keep a list of objects and
68 * check which ones have already been processed in some way.
70 typedef struct Struct_DoneList {
71 const Obj_Entry **objs; /* Array of object pointers */
72 unsigned int num_alloc; /* Allocated size of the array */
73 unsigned int num_used; /* Number of array slots used */
77 * Function declarations.
79 static void die(void);
80 static void digest_dynamic(Obj_Entry *);
81 static const char *_getenv_ld(const char *id);
82 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
83 static Obj_Entry *dlcheck(void *);
84 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
85 static bool donelist_check(DoneList *, const Obj_Entry *);
86 static u_int32_t elf_uniqid(u_int32_t, const void *, size_t);
87 static void errmsg_restore(char *);
88 static char *errmsg_save(void);
89 static void *fill_search_info(const char *, size_t, void *);
90 static char *find_library(const char *, const Obj_Entry *);
91 static const char *gethints(void);
92 static void init_dag(Obj_Entry *);
93 static void init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *);
94 static void init_rtld(caddr_t);
95 static void initlist_add_neededs(Needed_Entry *needed, Objlist *list);
96 static void initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail,
98 static bool is_exported(const Elf_Sym *);
99 static void linkmap_add(Obj_Entry *);
100 static void linkmap_delete(Obj_Entry *);
101 static int load_needed_objects(Obj_Entry *);
102 static int load_preload_objects(void);
103 static Obj_Entry *load_object(char *);
104 static void lock_check(void);
105 static Obj_Entry *obj_from_addr(const void *);
106 static void objlist_call_fini(Objlist *);
107 static void objlist_call_init(Objlist *);
108 static void objlist_clear(Objlist *);
109 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
110 static void objlist_init(Objlist *);
111 static void objlist_push_head(Objlist *, Obj_Entry *);
112 static void objlist_push_tail(Objlist *, Obj_Entry *);
113 static void objlist_remove(Objlist *, Obj_Entry *);
114 static void objlist_remove_unref(Objlist *);
115 static void *path_enumerate(const char *, path_enum_proc, void *);
116 static int relocate_objects(Obj_Entry *, bool);
117 static int rtld_dirname(const char *, char *);
118 static void rtld_exit(void);
119 static char *search_library_path(const char *, const char *);
120 static const void **get_program_var_addr(const char *name);
121 static void set_program_var(const char *, const void *);
122 static const Elf_Sym *symlook_default(const char *, unsigned long hash,
123 const Obj_Entry *refobj, const Obj_Entry **defobj_out, bool in_plt);
124 static const Elf_Sym *symlook_list(const char *, unsigned long,
125 Objlist *, const Obj_Entry **, bool in_plt, DoneList *);
126 static void trace_loaded_objects(Obj_Entry *obj);
127 static void unlink_object(Obj_Entry *);
128 static void unload_object(Obj_Entry *);
129 static void unref_dag(Obj_Entry *);
131 void r_debug_state(struct r_debug*, struct link_map*);
136 static char *error_message; /* Message for dlerror(), or NULL */
137 struct r_debug r_debug; /* for GDB; */
138 static bool trust; /* False for setuid and setgid programs */
139 static const char *ld_bind_now; /* Environment variable for immediate binding */
140 static const char *ld_debug; /* Environment variable for debugging */
141 static const char *ld_library_path; /* Environment variable for search path */
142 static char *ld_preload; /* Environment variable for libraries to
144 static const char *ld_tracing; /* Called from ldd(1) to print libs */
145 static const char *ld_prebind; /* Called from prebind(1) to prebind libs */
146 static Obj_Entry *obj_list; /* Head of linked list of shared objects */
147 static Obj_Entry **obj_tail; /* Link field of last object in list */
148 static Obj_Entry **preload_tail;
149 static Obj_Entry *obj_main; /* The main program shared object */
150 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
151 static unsigned int obj_count; /* Number of objects in obj_list */
152 static int ld_resident; /* Non-zero if resident */
153 static const char *ld_ary[LD_ARY_CACHE];
156 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
157 STAILQ_HEAD_INITIALIZER(list_global);
158 static Objlist list_main = /* Objects loaded at program startup */
159 STAILQ_HEAD_INITIALIZER(list_main);
160 static Objlist list_fini = /* Objects needing fini() calls */
161 STAILQ_HEAD_INITIALIZER(list_fini);
163 static LockInfo lockinfo;
165 static Elf_Sym sym_zero; /* For resolving undefined weak refs. */
167 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
169 extern Elf_Dyn _DYNAMIC;
170 #pragma weak _DYNAMIC
173 * These are the functions the dynamic linker exports to application
174 * programs. They are the only symbols the dynamic linker is willing
175 * to export from itself.
177 static func_ptr_type exports[] = {
178 (func_ptr_type) &_rtld_error,
179 (func_ptr_type) &dlclose,
180 (func_ptr_type) &dlerror,
181 (func_ptr_type) &dlopen,
182 (func_ptr_type) &dlsym,
183 (func_ptr_type) &dladdr,
184 (func_ptr_type) &dllockinit,
185 (func_ptr_type) &dlinfo,
190 * Global declarations normally provided by crt1. The dynamic linker is
191 * not built with crt1, so we have to provide them ourselves.
197 * Fill in a DoneList with an allocation large enough to hold all of
198 * the currently-loaded objects. Keep this as a macro since it calls
199 * alloca and we want that to occur within the scope of the caller.
201 #define donelist_init(dlp) \
202 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
203 assert((dlp)->objs != NULL), \
204 (dlp)->num_alloc = obj_count, \
210 lockinfo.rlock_acquire(lockinfo.thelock);
211 atomic_incr_int(&lockinfo.rcount);
218 lockinfo.wlock_acquire(lockinfo.thelock);
219 atomic_incr_int(&lockinfo.wcount);
226 atomic_decr_int(&lockinfo.rcount);
227 lockinfo.rlock_release(lockinfo.thelock);
233 atomic_decr_int(&lockinfo.wcount);
234 lockinfo.wlock_release(lockinfo.thelock);
238 * Main entry point for dynamic linking. The first argument is the
239 * stack pointer. The stack is expected to be laid out as described
240 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
241 * Specifically, the stack pointer points to a word containing
242 * ARGC. Following that in the stack is a null-terminated sequence
243 * of pointers to argument strings. Then comes a null-terminated
244 * sequence of pointers to environment strings. Finally, there is a
245 * sequence of "auxiliary vector" entries.
247 * The second argument points to a place to store the dynamic linker's
248 * exit procedure pointer and the third to a place to store the main
251 * The return value is the main program's entry point.
254 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
256 Elf_Auxinfo *aux_info[AT_COUNT];
266 int prebind_disable = 0;
268 ld_index = 0; /* don't use old env cache in case we are resident */
271 * On entry, the dynamic linker itself has not been relocated yet.
272 * Be very careful not to reference any global data until after
273 * init_rtld has returned. It is OK to reference file-scope statics
274 * and string constants, and to call static and global functions.
277 /* Find the auxiliary vector on the stack. */
280 sp += argc + 1; /* Skip over arguments and NULL terminator */
284 * If we aren't already resident we have to dig out some more info.
285 * Note that auxinfo does not exist when we are resident.
287 if (ld_resident == 0) {
288 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
290 aux = (Elf_Auxinfo *) sp;
292 /* Digest the auxiliary vector. */
293 for (i = 0; i < AT_COUNT; i++)
295 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
296 if (auxp->a_type < AT_COUNT)
297 aux_info[auxp->a_type] = auxp;
300 /* Initialize and relocate ourselves. */
301 assert(aux_info[AT_BASE] != NULL);
302 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
305 __progname = obj_rtld.path;
306 argv0 = argv[0] != NULL ? argv[0] : "(null)";
309 trust = (geteuid() == getuid()) && (getegid() == getgid());
311 prebind_disable = _getenv_ld("LD_PREBIND_DISABLE") != NULL;
313 ld_bind_now = _getenv_ld("LD_BIND_NOW");
315 ld_debug = _getenv_ld("LD_DEBUG");
316 ld_library_path = _getenv_ld("LD_LIBRARY_PATH");
317 ld_preload = (char *)_getenv_ld("LD_PRELOAD");
319 ld_tracing = _getenv_ld("LD_TRACE_LOADED_OBJECTS");
322 ld_prebind = _getenv_ld("LD_PREBIND");
323 if (ld_prebind != NULL && *ld_prebind != '\0') {
324 ld_bind_now = ld_prebind;
329 if (ld_debug != NULL && *ld_debug != '\0')
331 dbg("%s is initialized, base address = %p", __progname,
332 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
333 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
334 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
337 * If we are resident we can skip work that we have already done.
338 * Note that the stack is reset and there is no Elf_Auxinfo
339 * when running from a resident image, and the static globals setup
340 * between here and resident_skip will have already been setup.
346 * Load the main program, or process its program header if it is
349 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
350 int fd = aux_info[AT_EXECFD]->a_un.a_val;
351 dbg("loading main program");
352 obj_main = map_object(fd, argv0, NULL);
354 if (obj_main == NULL)
356 } else { /* Main program already loaded. */
357 const Elf_Phdr *phdr;
361 dbg("processing main program's program header");
362 assert(aux_info[AT_PHDR] != NULL);
363 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
364 assert(aux_info[AT_PHNUM] != NULL);
365 phnum = aux_info[AT_PHNUM]->a_un.a_val;
366 assert(aux_info[AT_PHENT] != NULL);
367 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
368 assert(aux_info[AT_ENTRY] != NULL);
369 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
370 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
374 obj_main->path = xstrdup(argv0);
375 obj_main->mainprog = true;
378 * Get the actual dynamic linker pathname from the executable if
379 * possible. (It should always be possible.) That ensures that
380 * gdb will find the right dynamic linker even if a non-standard
383 if (obj_main->interp != NULL &&
384 strcmp(obj_main->interp, obj_rtld.path) != 0) {
386 obj_rtld.path = xstrdup(obj_main->interp);
389 digest_dynamic(obj_main);
391 linkmap_add(obj_main);
392 linkmap_add(&obj_rtld);
394 /* Link the main program into the list of objects. */
395 *obj_tail = obj_main;
396 obj_tail = &obj_main->next;
398 obj_main->refcount++;
399 /* Make sure we don't call the main program's init and fini functions. */
400 obj_main->init = obj_main->fini = NULL;
402 /* Initialize a fake symbol for resolving undefined weak references. */
403 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
404 sym_zero.st_shndx = SHN_ABS;
406 dbg("loading LD_PRELOAD libraries");
407 if (load_preload_objects() == -1)
409 preload_tail = obj_tail;
411 dbg("loading needed objects");
412 if (load_needed_objects(obj_main) == -1)
415 /* Make a list of all objects loaded at startup. */
416 for (obj = obj_list; obj != NULL; obj = obj->next)
417 objlist_push_tail(&list_main, obj);
421 if (ld_tracing) { /* We're done */
422 trace_loaded_objects(obj_main);
426 if (ld_resident) /* XXX clean this up! */
429 if (prebind_disable || prebind_load(&obj_rtld, obj_main)) {
430 if (relocate_objects(obj_main,
431 ld_bind_now != NULL && *ld_bind_now != '\0') == -1)
434 dbg("doing copy relocations");
435 if (do_copy_relocations(obj_main) == -1)
441 if (ld_prebind != NULL && *ld_prebind != '\0')
442 exit (prebind_save(&obj_rtld, obj_main));
444 if (_getenv_ld("LD_RESIDENT_UNREGISTER_NOW")) {
445 if (exec_sys_unregister(-1) < 0) {
446 dbg("exec_sys_unregister failed %d\n", errno);
449 dbg("exec_sys_unregister success\n");
453 dbg("initializing key program variables");
454 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
455 set_program_var("environ", env);
457 if (_getenv_ld("LD_RESIDENT_REGISTER_NOW")) {
458 extern void resident_start(void);
460 if (exec_sys_register(resident_start) < 0) {
461 dbg("exec_sys_register failed %d\n", errno);
464 dbg("exec_sys_register success\n");
468 dbg("initializing thread locks");
469 lockdflt_init(&lockinfo);
470 lockinfo.thelock = lockinfo.lock_create(lockinfo.context);
472 /* Make a list of init functions to call. */
473 objlist_init(&initlist);
474 initlist_add_objects(obj_list, preload_tail, &initlist);
476 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
478 objlist_call_init(&initlist);
480 objlist_clear(&initlist);
485 dbg("transferring control to program entry point = %p", obj_main->entry);
487 /* Return the exit procedure and the program entry point. */
488 *exit_proc = rtld_exit;
490 return (func_ptr_type) obj_main->entry;
494 _rtld_bind(Obj_Entry *obj, Elf_Word reloff)
498 const Obj_Entry *defobj;
504 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
506 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
508 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
509 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL);
513 target = (Elf_Addr)(defobj->relocbase + def->st_value);
515 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
516 defobj->strtab + def->st_name, basename(obj->path),
517 (void *)target, basename(defobj->path));
519 reloc_jmpslot(where, target);
525 * Error reporting function. Use it like printf. If formats the message
526 * into a buffer, and sets things up so that the next call to dlerror()
527 * will return the message.
530 _rtld_error(const char *fmt, ...)
532 static char buf[512];
536 vsnprintf(buf, sizeof buf, fmt, ap);
542 * Return a dynamically-allocated copy of the current error message, if any.
547 return error_message == NULL ? NULL : xstrdup(error_message);
551 * Restore the current error message from a copy which was previously saved
552 * by errmsg_save(). The copy is freed.
555 errmsg_restore(char *saved_msg)
557 if (saved_msg == NULL)
558 error_message = NULL;
560 _rtld_error("%s", saved_msg);
566 basename(const char *name)
568 const char *p = strrchr(name, '/');
569 return p != NULL ? p + 1 : name;
575 const char *msg = dlerror();
583 * Process a shared object's DYNAMIC section, and save the important
584 * information in its Obj_Entry structure.
587 digest_dynamic(Obj_Entry *obj)
590 Needed_Entry **needed_tail = &obj->needed;
591 const Elf_Dyn *dyn_rpath = NULL;
592 int plttype = DT_REL;
594 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
595 switch (dynp->d_tag) {
598 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
602 obj->relsize = dynp->d_un.d_val;
606 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
610 obj->pltrel = (const Elf_Rel *)
611 (obj->relocbase + dynp->d_un.d_ptr);
615 obj->pltrelsize = dynp->d_un.d_val;
619 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
623 obj->relasize = dynp->d_un.d_val;
627 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
631 plttype = dynp->d_un.d_val;
632 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
636 obj->symtab = (const Elf_Sym *)
637 (obj->relocbase + dynp->d_un.d_ptr);
641 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
645 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
649 obj->strsize = dynp->d_un.d_val;
654 const Elf_Addr *hashtab = (const Elf_Addr *)
655 (obj->relocbase + dynp->d_un.d_ptr);
656 obj->nbuckets = hashtab[0];
657 obj->nchains = hashtab[1];
658 obj->buckets = hashtab + 2;
659 obj->chains = obj->buckets + obj->nbuckets;
665 Needed_Entry *nep = NEW(Needed_Entry);
666 nep->name = dynp->d_un.d_val;
671 needed_tail = &nep->next;
676 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
684 obj->symbolic = true;
689 * We have to wait until later to process this, because we
690 * might not have gotten the address of the string table yet.
696 /* Not used by the dynamic linker. */
700 obj->init = (InitFunc) (obj->relocbase + dynp->d_un.d_ptr);
704 obj->fini = (InitFunc) (obj->relocbase + dynp->d_un.d_ptr);
708 /* XXX - not implemented yet */
709 dbg("Filling in DT_DEBUG entry");
710 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
714 dbg("Ignoring d_tag %d = %#x", dynp->d_tag, dynp->d_tag);
723 obj->uniqid = elf_uniqid(obj->uniqid, obj->pltrel, obj->pltrelsize);
725 obj->uniqid = elf_uniqid(obj->uniqid, obj->symtab, obj->nchains * sizeof(*obj->symtab));
727 if (plttype == DT_RELA) {
728 obj->pltrela = (const Elf_Rela *) obj->pltrel;
730 obj->pltrelasize = obj->pltrelsize;
734 if (dyn_rpath != NULL)
735 obj->rpath = obj->strtab + dyn_rpath->d_un.d_val;
739 * Process a shared object's program header. This is used only for the
740 * main program, when the kernel has already loaded the main program
741 * into memory before calling the dynamic linker. It creates and
742 * returns an Obj_Entry structure.
745 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
748 const Elf_Phdr *phlimit = phdr + phnum;
753 for (ph = phdr; ph < phlimit; ph++) {
754 switch (ph->p_type) {
757 if ((const Elf_Phdr *)ph->p_vaddr != phdr) {
758 _rtld_error("%s: invalid PT_PHDR", path);
761 obj->phdr = (const Elf_Phdr *) ph->p_vaddr;
762 obj->phsize = ph->p_memsz;
766 obj->interp = (const char *) ph->p_vaddr;
770 if (nsegs == 0) { /* First load segment */
771 obj->vaddrbase = trunc_page(ph->p_vaddr);
772 obj->mapbase = (caddr_t) obj->vaddrbase;
773 obj->relocbase = obj->mapbase - obj->vaddrbase;
774 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
776 } else { /* Last load segment */
777 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
784 obj->dynamic = (const Elf_Dyn *) ph->p_vaddr;
789 _rtld_error("%s: too few PT_LOAD segments", path);
798 dlcheck(void *handle)
802 for (obj = obj_list; obj != NULL; obj = obj->next)
803 if (obj == (Obj_Entry *) handle)
806 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
807 _rtld_error("Invalid shared object handle %p", handle);
814 * If the given object is already in the donelist, return true. Otherwise
815 * add the object to the list and return false.
818 donelist_check(DoneList *dlp, const Obj_Entry *obj)
822 for (i = 0; i < dlp->num_used; i++)
823 if (dlp->objs[i] == obj)
826 * Our donelist allocation should always be sufficient. But if
827 * our threads locking isn't working properly, more shared objects
828 * could have been loaded since we allocated the list. That should
829 * never happen, but we'll handle it properly just in case it does.
831 if (dlp->num_used < dlp->num_alloc)
832 dlp->objs[dlp->num_used++] = obj;
837 * Hash function for symbol table lookup. Don't even think about changing
838 * this. It is specified by the System V ABI.
841 elf_hash(const char *name)
843 const unsigned char *p = (const unsigned char *) name;
849 if ((g = h & 0xf0000000) != 0)
857 * Hash function to get an unique ID from an ELF object file
858 * needs to be fast and small
860 * This one is after Krovetz, Rogaway: The PolyR construction,
861 * http://www.cs.ucdavis.edu/~rogaway/papers/poly.htm
863 * If called for the first time on a block, pass hash = 1
866 elf_uniqid(u_int32_t hash, const void *data, size_t len)
868 const u_int32_t p = 0xfffffffb; /* The largest prime smaller than 2^32 */
869 const u_int32_t offset = 5; /* Constant for translating out-of-range words */
870 const u_int32_t marker = 0xfffffffa; /* Constant for indicating out-of-range words */
871 const u_int32_t key = RTLD_TS; /* Hash key XXX */
872 u_int32_t n = len / 4; /* 32 bit blocks */
873 u_int32_t remainder = 0;
874 const u_int32_t *block;
876 for (block = data; n; --n, ++block)
878 if (*block >= p - 1) { /* If word is not in range, then */
879 hash = uniqid_hash_block(hash, key, marker); /* Maker indicates out-of-range */
880 hash = uniqid_hash_block(hash, key, *block - offset); /* Offset m back into range */
882 hash = uniqid_hash_block(hash, key, *block);
884 if (len % 4) { /* we got some remainder */
885 memcpy(&remainder, block, len % 4); /* copy remaining bytes into 0-padded block */
886 block = &remainder; /* set up pointer */
887 n = 1; /* one block to process */
888 len = 0; /* we've done the remainder */
889 goto uniqid_hash; /* run once again */
896 * Find the library with the given name, and return its full pathname.
897 * The returned string is dynamically allocated. Generates an error
898 * message and returns NULL if the library cannot be found.
900 * If the second argument is non-NULL, then it refers to an already-
901 * loaded shared object, whose library search path will be searched.
903 * The search order is:
905 * rpath in the referencing file
910 find_library(const char *name, const Obj_Entry *refobj)
914 if (strchr(name, '/') != NULL) { /* Hard coded pathname */
915 if (name[0] != '/' && !trust) {
916 _rtld_error("Absolute pathname required for shared object \"%s\"",
920 return xstrdup(name);
923 dbg(" Searching for \"%s\"", name);
925 if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
927 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
928 (pathname = search_library_path(name, gethints())) != NULL ||
929 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
932 _rtld_error("Shared object \"%s\" not found", name);
937 * Given a symbol number in a referencing object, find the corresponding
938 * definition of the symbol. Returns a pointer to the symbol, or NULL if
939 * no definition was found. Returns a pointer to the Obj_Entry of the
940 * defining object via the reference parameter DEFOBJ_OUT.
943 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
944 const Obj_Entry **defobj_out, bool in_plt, SymCache *cache)
948 const Obj_Entry *defobj;
953 * If we have already found this symbol, get the information from
956 if (symnum >= refobj->nchains)
957 return NULL; /* Bad object */
958 if (cache != NULL && cache[symnum].sym != NULL) {
959 *defobj_out = cache[symnum].obj;
960 return cache[symnum].sym;
963 ref = refobj->symtab + symnum;
964 name = refobj->strtab + ref->st_name;
965 hash = elf_hash(name);
968 def = symlook_default(name, hash, refobj, &defobj, in_plt);
971 * If we found no definition and the reference is weak, treat the
972 * symbol as having the value zero.
974 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
980 *defobj_out = defobj;
981 /* Record the information in the cache to avoid subsequent lookups. */
983 cache[symnum].sym = def;
984 cache[symnum].obj = defobj;
987 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
992 * Return the search path from the ldconfig hints file, reading it if
993 * necessary. Returns NULL if there are problems with the hints file,
994 * or if the search path there is empty.
1001 if (hints == NULL) {
1003 struct elfhints_hdr hdr;
1006 /* Keep from trying again in case the hints file is bad. */
1009 if ((fd = open(_PATH_ELF_HINTS, O_RDONLY)) == -1)
1011 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1012 hdr.magic != ELFHINTS_MAGIC ||
1017 p = xmalloc(hdr.dirlistlen + 1);
1018 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1019 read(fd, p, hdr.dirlistlen + 1) != hdr.dirlistlen + 1) {
1027 return hints[0] != '\0' ? hints : NULL;
1031 init_dag(Obj_Entry *root)
1035 donelist_init(&donelist);
1036 init_dag1(root, root, &donelist);
1040 init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *dlp)
1042 const Needed_Entry *needed;
1044 if (donelist_check(dlp, obj))
1046 objlist_push_tail(&obj->dldags, root);
1047 objlist_push_tail(&root->dagmembers, obj);
1048 for (needed = obj->needed; needed != NULL; needed = needed->next)
1049 if (needed->obj != NULL)
1050 init_dag1(root, needed->obj, dlp);
1054 * Initialize the dynamic linker. The argument is the address at which
1055 * the dynamic linker has been mapped into memory. The primary task of
1056 * this function is to relocate the dynamic linker.
1059 init_rtld(caddr_t mapbase)
1062 * Conjure up an Obj_Entry structure for the dynamic linker.
1064 * The "path" member is supposed to be dynamically-allocated, but we
1065 * aren't yet initialized sufficiently to do that. Below we will
1066 * replace the static version with a dynamically-allocated copy.
1068 obj_rtld.path = PATH_RTLD;
1069 obj_rtld.rtld = true;
1070 obj_rtld.mapbase = mapbase;
1072 obj_rtld.relocbase = mapbase;
1074 if (&_DYNAMIC != 0) {
1075 obj_rtld.dynamic = rtld_dynamic(&obj_rtld);
1076 digest_dynamic(&obj_rtld);
1077 assert(obj_rtld.needed == NULL);
1078 assert(!obj_rtld.textrel);
1081 * Temporarily put the dynamic linker entry into the object list, so
1082 * that symbols can be found.
1084 obj_list = &obj_rtld;
1085 obj_tail = &obj_rtld.next;
1088 relocate_objects(&obj_rtld, true);
1091 /* Make the object list empty again. */
1093 obj_tail = &obj_list;
1096 /* Replace the path with a dynamically allocated copy. */
1097 obj_rtld.path = xstrdup(obj_rtld.path);
1099 obj_rtld.uniqid = RTLD_TS;
1101 r_debug.r_brk = r_debug_state;
1102 r_debug.r_state = RT_CONSISTENT;
1106 * Add the init functions from a needed object list (and its recursive
1107 * needed objects) to "list". This is not used directly; it is a helper
1108 * function for initlist_add_objects(). The write lock must be held
1109 * when this function is called.
1112 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1114 /* Recursively process the successor needed objects. */
1115 if (needed->next != NULL)
1116 initlist_add_neededs(needed->next, list);
1118 /* Process the current needed object. */
1119 if (needed->obj != NULL)
1120 initlist_add_objects(needed->obj, &needed->obj->next, list);
1124 * Scan all of the DAGs rooted in the range of objects from "obj" to
1125 * "tail" and add their init functions to "list". This recurses over
1126 * the DAGs and ensure the proper init ordering such that each object's
1127 * needed libraries are initialized before the object itself. At the
1128 * same time, this function adds the objects to the global finalization
1129 * list "list_fini" in the opposite order. The write lock must be
1130 * held when this function is called.
1133 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1137 obj->init_done = true;
1139 /* Recursively process the successor objects. */
1140 if (&obj->next != tail)
1141 initlist_add_objects(obj->next, tail, list);
1143 /* Recursively process the needed objects. */
1144 if (obj->needed != NULL)
1145 initlist_add_neededs(obj->needed, list);
1147 /* Add the object to the init list. */
1148 if (obj->init != NULL)
1149 objlist_push_tail(list, obj);
1151 /* Add the object to the global fini list in the reverse order. */
1152 if (obj->fini != NULL)
1153 objlist_push_head(&list_fini, obj);
1157 is_exported(const Elf_Sym *def)
1159 func_ptr_type value;
1160 const func_ptr_type *p;
1162 value = (func_ptr_type)(obj_rtld.relocbase + def->st_value);
1163 for (p = exports; *p != NULL; p++)
1170 * Given a shared object, traverse its list of needed objects, and load
1171 * each of them. Returns 0 on success. Generates an error message and
1172 * returns -1 on failure.
1175 load_needed_objects(Obj_Entry *first)
1179 for (obj = first; obj != NULL; obj = obj->next) {
1180 Needed_Entry *needed;
1182 for (needed = obj->needed; needed != NULL; needed = needed->next) {
1183 const char *name = obj->strtab + needed->name;
1184 char *path = find_library(name, obj);
1187 if (path == NULL && !ld_tracing)
1191 needed->obj = load_object(path);
1192 if (needed->obj == NULL && !ld_tracing)
1193 return -1; /* XXX - cleanup */
1202 load_preload_objects(void)
1204 char *p = ld_preload;
1205 static const char delim[] = " \t:;";
1210 p += strspn(p, delim);
1211 while (*p != '\0') {
1212 size_t len = strcspn(p, delim);
1218 if ((path = find_library(p, NULL)) == NULL)
1220 if (load_object(path) == NULL)
1221 return -1; /* XXX - cleanup */
1224 p += strspn(p, delim);
1230 * Load a shared object into memory, if it is not already loaded. The
1231 * argument must be a string allocated on the heap. This function assumes
1232 * responsibility for freeing it when necessary.
1234 * Returns a pointer to the Obj_Entry for the object. Returns NULL
1238 load_object(char *path)
1244 for (obj = obj_list->next; obj != NULL; obj = obj->next)
1245 if (strcmp(obj->path, path) == 0)
1249 * If we didn't find a match by pathname, open the file and check
1250 * again by device and inode. This avoids false mismatches caused
1251 * by multiple links or ".." in pathnames.
1253 * To avoid a race, we open the file and use fstat() rather than
1257 if ((fd = open(path, O_RDONLY)) == -1) {
1258 _rtld_error("Cannot open \"%s\"", path);
1261 if (fstat(fd, &sb) == -1) {
1262 _rtld_error("Cannot fstat \"%s\"", path);
1266 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
1267 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev) {
1274 if (obj == NULL) { /* First use of this object, so we must map it in */
1275 dbg("loading \"%s\"", path);
1276 obj = map_object(fd, path, &sb);
1284 digest_dynamic(obj);
1287 obj_tail = &obj->next;
1289 linkmap_add(obj); /* for GDB & dlinfo() */
1291 dbg(" %p .. %p: %s", obj->mapbase,
1292 obj->mapbase + obj->mapsize - 1, obj->path);
1294 dbg(" WARNING: %s has impure text", obj->path);
1303 * Check for locking violations and die if one is found.
1310 rcount = lockinfo.rcount;
1311 wcount = lockinfo.wcount;
1312 assert(rcount >= 0);
1313 assert(wcount >= 0);
1314 if (wcount > 1 || (wcount != 0 && rcount != 0)) {
1315 _rtld_error("Application locking error: %d readers and %d writers"
1316 " in dynamic linker. See DLLOCKINIT(3) in manual pages.",
1323 obj_from_addr(const void *addr)
1325 unsigned long endhash;
1328 endhash = elf_hash(END_SYM);
1329 for (obj = obj_list; obj != NULL; obj = obj->next) {
1330 const Elf_Sym *endsym;
1332 if (addr < (void *) obj->mapbase)
1334 if ((endsym = symlook_obj(END_SYM, endhash, obj, true)) == NULL)
1335 continue; /* No "end" symbol?! */
1336 if (addr < (void *) (obj->relocbase + endsym->st_value))
1343 * Call the finalization functions for each of the objects in "list"
1344 * which are unreferenced. All of the objects are expected to have
1345 * non-NULL fini functions.
1348 objlist_call_fini(Objlist *list)
1354 * Preserve the current error message since a fini function might
1355 * call into the dynamic linker and overwrite it.
1357 saved_msg = errmsg_save();
1358 STAILQ_FOREACH(elm, list, link) {
1359 if (elm->obj->refcount == 0) {
1360 dbg("calling fini function for %s", elm->obj->path);
1361 (*elm->obj->fini)();
1364 errmsg_restore(saved_msg);
1368 * Call the initialization functions for each of the objects in
1369 * "list". All of the objects are expected to have non-NULL init
1373 objlist_call_init(Objlist *list)
1379 * Preserve the current error message since an init function might
1380 * call into the dynamic linker and overwrite it.
1382 saved_msg = errmsg_save();
1383 STAILQ_FOREACH(elm, list, link) {
1384 dbg("calling init function for %s", elm->obj->path);
1385 (*elm->obj->init)();
1387 errmsg_restore(saved_msg);
1391 objlist_clear(Objlist *list)
1395 while (!STAILQ_EMPTY(list)) {
1396 elm = STAILQ_FIRST(list);
1397 STAILQ_REMOVE_HEAD(list, link);
1402 static Objlist_Entry *
1403 objlist_find(Objlist *list, const Obj_Entry *obj)
1407 STAILQ_FOREACH(elm, list, link)
1408 if (elm->obj == obj)
1414 objlist_init(Objlist *list)
1420 objlist_push_head(Objlist *list, Obj_Entry *obj)
1424 elm = NEW(Objlist_Entry);
1426 STAILQ_INSERT_HEAD(list, elm, link);
1430 objlist_push_tail(Objlist *list, Obj_Entry *obj)
1434 elm = NEW(Objlist_Entry);
1436 STAILQ_INSERT_TAIL(list, elm, link);
1440 objlist_remove(Objlist *list, Obj_Entry *obj)
1444 if ((elm = objlist_find(list, obj)) != NULL) {
1445 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1451 * Remove all of the unreferenced objects from "list".
1454 objlist_remove_unref(Objlist *list)
1459 STAILQ_INIT(&newlist);
1460 while (!STAILQ_EMPTY(list)) {
1461 elm = STAILQ_FIRST(list);
1462 STAILQ_REMOVE_HEAD(list, link);
1463 if (elm->obj->refcount == 0)
1466 STAILQ_INSERT_TAIL(&newlist, elm, link);
1472 * Relocate newly-loaded shared objects. The argument is a pointer to
1473 * the Obj_Entry for the first such object. All objects from the first
1474 * to the end of the list of objects are relocated. Returns 0 on success,
1478 relocate_objects(Obj_Entry *first, bool bind_now)
1482 for (obj = first; obj != NULL; obj = obj->next) {
1483 if (obj != &obj_rtld)
1484 dbg("relocating \"%s\"", obj->path);
1485 if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
1486 obj->symtab == NULL || obj->strtab == NULL) {
1487 _rtld_error("%s: Shared object has no run-time symbol table",
1493 /* There are relocations to the write-protected text segment. */
1494 if (mprotect(obj->mapbase, obj->textsize,
1495 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
1496 _rtld_error("%s: Cannot write-enable text segment: %s",
1497 obj->path, strerror(errno));
1502 /* Process the non-PLT relocations. */
1503 if (reloc_non_plt(obj, &obj_rtld))
1506 if (obj->textrel) { /* Re-protected the text segment. */
1507 if (mprotect(obj->mapbase, obj->textsize,
1508 PROT_READ|PROT_EXEC) == -1) {
1509 _rtld_error("%s: Cannot write-protect text segment: %s",
1510 obj->path, strerror(errno));
1515 /* Process the PLT relocations. */
1516 if (reloc_plt(obj) == -1)
1518 /* Relocate the jump slots if we are doing immediate binding. */
1520 if (reloc_jmpslots(obj) == -1)
1525 * Set up the magic number and version in the Obj_Entry. These
1526 * were checked in the crt1.o from the original ElfKit, so we
1527 * set them for backward compatibility.
1529 obj->magic = RTLD_MAGIC;
1530 obj->version = RTLD_VERSION;
1532 /* Set the special PLT or GOT entries. */
1540 * Cleanup procedure. It will be called (by the atexit mechanism) just
1541 * before the process exits.
1549 /* Clear all the reference counts so the fini functions will be called. */
1550 for (obj = obj_list; obj != NULL; obj = obj->next)
1552 objlist_call_fini(&list_fini);
1553 /* No need to remove the items from the list, since we are exiting. */
1557 path_enumerate(const char *path, path_enum_proc callback, void *arg)
1562 path += strspn(path, ":;");
1563 while (*path != '\0') {
1567 len = strcspn(path, ":;");
1568 res = callback(path, len, arg);
1574 path += strspn(path, ":;");
1580 struct try_library_args {
1588 try_library_path(const char *dir, size_t dirlen, void *param)
1590 struct try_library_args *arg;
1593 if (*dir == '/' || trust) {
1596 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
1599 pathname = arg->buffer;
1600 strncpy(pathname, dir, dirlen);
1601 pathname[dirlen] = '/';
1602 strcpy(pathname + dirlen + 1, arg->name);
1604 dbg(" Trying \"%s\"", pathname);
1605 if (access(pathname, F_OK) == 0) { /* We found it */
1606 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
1607 strcpy(pathname, arg->buffer);
1615 search_library_path(const char *name, const char *path)
1618 struct try_library_args arg;
1624 arg.namelen = strlen(name);
1625 arg.buffer = xmalloc(PATH_MAX);
1626 arg.buflen = PATH_MAX;
1628 p = path_enumerate(path, try_library_path, &arg);
1636 dlclose(void *handle)
1641 root = dlcheck(handle);
1647 /* Unreference the object and its dependencies. */
1648 root->dl_refcount--;
1651 if (root->refcount == 0) {
1653 * The object is no longer referenced, so we must unload it.
1654 * First, call the fini functions with no locks held.
1657 objlist_call_fini(&list_fini);
1659 objlist_remove_unref(&list_fini);
1661 /* Finish cleaning up the newly-unreferenced objects. */
1662 GDB_STATE(RT_DELETE,&root->linkmap);
1663 unload_object(root);
1664 GDB_STATE(RT_CONSISTENT,NULL);
1673 char *msg = error_message;
1674 error_message = NULL;
1679 * This function is deprecated and has no effect.
1682 dllockinit(void *context,
1683 void *(*lock_create)(void *context),
1684 void (*rlock_acquire)(void *lock),
1685 void (*wlock_acquire)(void *lock),
1686 void (*lock_release)(void *lock),
1687 void (*lock_destroy)(void *lock),
1688 void (*context_destroy)(void *context))
1690 static void *cur_context;
1691 static void (*cur_context_destroy)(void *);
1693 /* Just destroy the context from the previous call, if necessary. */
1694 if (cur_context_destroy != NULL)
1695 cur_context_destroy(cur_context);
1696 cur_context = context;
1697 cur_context_destroy = context_destroy;
1701 dlopen(const char *name, int mode)
1703 Obj_Entry **old_obj_tail;
1708 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
1709 if (ld_tracing != NULL)
1710 environ = (char **)*get_program_var_addr("environ");
1712 objlist_init(&initlist);
1715 GDB_STATE(RT_ADD,NULL);
1717 old_obj_tail = obj_tail;
1723 char *path = find_library(name, obj_main);
1725 obj = load_object(path);
1730 if ((mode & RTLD_GLOBAL) && objlist_find(&list_global, obj) == NULL)
1731 objlist_push_tail(&list_global, obj);
1732 mode &= RTLD_MODEMASK;
1733 if (*old_obj_tail != NULL) { /* We loaded something new. */
1734 assert(*old_obj_tail == obj);
1736 result = load_needed_objects(obj);
1737 if (result != -1 && ld_tracing)
1741 (init_dag(obj), relocate_objects(obj, mode == RTLD_NOW)) == -1) {
1744 if (obj->refcount == 0)
1748 /* Make list of init functions to call. */
1749 initlist_add_objects(obj, &obj->next, &initlist);
1751 } else if (ld_tracing)
1755 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
1757 /* Call the init functions with no locks held. */
1759 objlist_call_init(&initlist);
1761 objlist_clear(&initlist);
1765 trace_loaded_objects(obj);
1771 dlsym(void *handle, const char *name)
1773 const Obj_Entry *obj;
1776 const Obj_Entry *defobj;
1778 hash = elf_hash(name);
1783 if (handle == NULL || handle == RTLD_NEXT ||
1784 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
1787 retaddr = __builtin_return_address(0); /* __GNUC__ only */
1788 if ((obj = obj_from_addr(retaddr)) == NULL) {
1789 _rtld_error("Cannot determine caller's shared object");
1793 if (handle == NULL) { /* Just the caller's shared object. */
1794 def = symlook_obj(name, hash, obj, true);
1796 } else if (handle == RTLD_NEXT || /* Objects after caller's */
1797 handle == RTLD_SELF) { /* ... caller included */
1798 if (handle == RTLD_NEXT)
1800 for (; obj != NULL; obj = obj->next) {
1801 if ((def = symlook_obj(name, hash, obj, true)) != NULL) {
1807 assert(handle == RTLD_DEFAULT);
1808 def = symlook_default(name, hash, obj, &defobj, true);
1811 if ((obj = dlcheck(handle)) == NULL) {
1816 if (obj->mainprog) {
1819 /* Search main program and all libraries loaded by it. */
1820 donelist_init(&donelist);
1821 def = symlook_list(name, hash, &list_main, &defobj, true,
1825 * XXX - This isn't correct. The search should include the whole
1826 * DAG rooted at the given object.
1828 def = symlook_obj(name, hash, obj, true);
1835 return defobj->relocbase + def->st_value;
1838 _rtld_error("Undefined symbol \"%s\"", name);
1844 dladdr(const void *addr, Dl_info *info)
1846 const Obj_Entry *obj;
1849 unsigned long symoffset;
1852 obj = obj_from_addr(addr);
1854 _rtld_error("No shared object contains address");
1858 info->dli_fname = obj->path;
1859 info->dli_fbase = obj->mapbase;
1860 info->dli_saddr = (void *)0;
1861 info->dli_sname = NULL;
1864 * Walk the symbol list looking for the symbol whose address is
1865 * closest to the address sent in.
1867 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
1868 def = obj->symtab + symoffset;
1871 * For skip the symbol if st_shndx is either SHN_UNDEF or
1874 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
1878 * If the symbol is greater than the specified address, or if it
1879 * is further away from addr than the current nearest symbol,
1882 symbol_addr = obj->relocbase + def->st_value;
1883 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
1886 /* Update our idea of the nearest symbol. */
1887 info->dli_sname = obj->strtab + def->st_name;
1888 info->dli_saddr = symbol_addr;
1891 if (info->dli_saddr == addr)
1899 dlinfo(void *handle, int request, void *p)
1901 const Obj_Entry *obj;
1906 if (handle == NULL || handle == RTLD_SELF) {
1909 retaddr = __builtin_return_address(0); /* __GNUC__ only */
1910 if ((obj = obj_from_addr(retaddr)) == NULL)
1911 _rtld_error("Cannot determine caller's shared object");
1913 obj = dlcheck(handle);
1922 case RTLD_DI_LINKMAP:
1923 *((struct link_map const **)p) = &obj->linkmap;
1925 case RTLD_DI_ORIGIN:
1926 error = rtld_dirname(obj->path, p);
1929 case RTLD_DI_SERINFOSIZE:
1930 case RTLD_DI_SERINFO:
1931 error = do_search_info(obj, request, (struct dl_serinfo *)p);
1935 _rtld_error("Invalid request %d passed to dlinfo()", request);
1944 struct fill_search_info_args {
1947 Dl_serinfo *serinfo;
1948 Dl_serpath *serpath;
1953 fill_search_info(const char *dir, size_t dirlen, void *param)
1955 struct fill_search_info_args *arg;
1959 if (arg->request == RTLD_DI_SERINFOSIZE) {
1960 arg->serinfo->dls_cnt ++;
1961 arg->serinfo->dls_size += dirlen + 1;
1963 struct dl_serpath *s_entry;
1965 s_entry = arg->serpath;
1966 s_entry->dls_name = arg->strspace;
1967 s_entry->dls_flags = arg->flags;
1969 strncpy(arg->strspace, dir, dirlen);
1970 arg->strspace[dirlen] = '\0';
1972 arg->strspace += dirlen + 1;
1980 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
1982 struct dl_serinfo _info;
1983 struct fill_search_info_args args;
1985 args.request = RTLD_DI_SERINFOSIZE;
1986 args.serinfo = &_info;
1988 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1991 path_enumerate(ld_library_path, fill_search_info, &args);
1992 path_enumerate(obj->rpath, fill_search_info, &args);
1993 path_enumerate(gethints(), fill_search_info, &args);
1994 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
1997 if (request == RTLD_DI_SERINFOSIZE) {
1998 info->dls_size = _info.dls_size;
1999 info->dls_cnt = _info.dls_cnt;
2003 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
2004 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
2008 args.request = RTLD_DI_SERINFO;
2009 args.serinfo = info;
2010 args.serpath = &info->dls_serpath[0];
2011 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
2013 args.flags = LA_SER_LIBPATH;
2014 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
2017 args.flags = LA_SER_RUNPATH;
2018 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
2021 args.flags = LA_SER_CONFIG;
2022 if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
2025 args.flags = LA_SER_DEFAULT;
2026 if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
2032 rtld_dirname(const char *path, char *bname)
2036 /* Empty or NULL string gets treated as "." */
2037 if (path == NULL || *path == '\0') {
2043 /* Strip trailing slashes */
2044 endp = path + strlen(path) - 1;
2045 while (endp > path && *endp == '/')
2048 /* Find the start of the dir */
2049 while (endp > path && *endp != '/')
2052 /* Either the dir is "/" or there are no slashes */
2054 bname[0] = *endp == '/' ? '/' : '.';
2060 } while (endp > path && *endp == '/');
2063 if (endp - path + 2 > PATH_MAX)
2065 _rtld_error("Filename is too long: %s", path);
2069 strncpy(bname, path, endp - path + 1);
2070 bname[endp - path + 1] = '\0';
2075 linkmap_add(Obj_Entry *obj)
2077 struct link_map *l = &obj->linkmap;
2078 struct link_map *prev;
2080 obj->linkmap.l_name = obj->path;
2081 obj->linkmap.l_addr = obj->mapbase;
2082 obj->linkmap.l_ld = obj->dynamic;
2084 /* GDB needs load offset on MIPS to use the symbols */
2085 obj->linkmap.l_offs = obj->relocbase;
2088 if (r_debug.r_map == NULL) {
2094 * Scan to the end of the list, but not past the entry for the
2095 * dynamic linker, which we want to keep at the very end.
2097 for (prev = r_debug.r_map;
2098 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
2099 prev = prev->l_next)
2102 /* Link in the new entry. */
2104 l->l_next = prev->l_next;
2105 if (l->l_next != NULL)
2106 l->l_next->l_prev = l;
2111 linkmap_delete(Obj_Entry *obj)
2113 struct link_map *l = &obj->linkmap;
2115 if (l->l_prev == NULL) {
2116 if ((r_debug.r_map = l->l_next) != NULL)
2117 l->l_next->l_prev = NULL;
2121 if ((l->l_prev->l_next = l->l_next) != NULL)
2122 l->l_next->l_prev = l->l_prev;
2126 * Function for the debugger to set a breakpoint on to gain control.
2128 * The two parameters allow the debugger to easily find and determine
2129 * what the runtime loader is doing and to whom it is doing it.
2131 * When the loadhook trap is hit (r_debug_state, set at program
2132 * initialization), the arguments can be found on the stack:
2134 * +8 struct link_map *m
2135 * +4 struct r_debug *rd
2139 r_debug_state(struct r_debug* rd, struct link_map *m)
2144 * Get address of the pointer variable in the main program.
2146 static const void **
2147 get_program_var_addr(const char *name)
2149 const Obj_Entry *obj;
2152 hash = elf_hash(name);
2153 for (obj = obj_main; obj != NULL; obj = obj->next) {
2156 if ((def = symlook_obj(name, hash, obj, false)) != NULL) {
2159 addr = (const void **)(obj->relocbase + def->st_value);
2167 * Set a pointer variable in the main program to the given value. This
2168 * is used to set key variables such as "environ" before any of the
2169 * init functions are called.
2172 set_program_var(const char *name, const void *value)
2176 if ((addr = get_program_var_addr(name)) != NULL) {
2177 dbg("\"%s\": *%p <-- %p", name, addr, value);
2183 * This is a special version of getenv which is far more efficient
2184 * at finding LD_ environment vars.
2188 _getenv_ld(const char *id)
2192 int idlen = strlen(id);
2194 if (ld_index == LD_ARY_CACHE)
2196 if (ld_index == 0) {
2197 for (i = j = 0; (envp = environ[i]) != NULL && j < LD_ARY_CACHE; ++i) {
2198 if (envp[0] == 'L' && envp[1] == 'D' && envp[2] == '_')
2205 for (i = ld_index - 1; i >= 0; --i) {
2206 if (strncmp(ld_ary[i], id, idlen) == 0 && ld_ary[i][idlen] == '=')
2207 return(ld_ary[i] + idlen + 1);
2213 * Given a symbol name in a referencing object, find the corresponding
2214 * definition of the symbol. Returns a pointer to the symbol, or NULL if
2215 * no definition was found. Returns a pointer to the Obj_Entry of the
2216 * defining object via the reference parameter DEFOBJ_OUT.
2218 static const Elf_Sym *
2219 symlook_default(const char *name, unsigned long hash,
2220 const Obj_Entry *refobj, const Obj_Entry **defobj_out, bool in_plt)
2224 const Elf_Sym *symp;
2225 const Obj_Entry *obj;
2226 const Obj_Entry *defobj;
2227 const Objlist_Entry *elm;
2230 donelist_init(&donelist);
2232 /* Look first in the referencing object if linked symbolically. */
2233 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
2234 symp = symlook_obj(name, hash, refobj, in_plt);
2241 /* Search all objects loaded at program start up. */
2242 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2243 symp = symlook_list(name, hash, &list_main, &obj, in_plt, &donelist);
2245 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2251 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
2252 STAILQ_FOREACH(elm, &list_global, link) {
2253 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2255 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt,
2258 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2264 /* Search all dlopened DAGs containing the referencing object. */
2265 STAILQ_FOREACH(elm, &refobj->dldags, link) {
2266 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2268 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt,
2271 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2278 * Search the dynamic linker itself, and possibly resolve the
2279 * symbol from there. This is how the application links to
2280 * dynamic linker services such as dlopen. Only the values listed
2281 * in the "exports" array can be resolved from the dynamic linker.
2283 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2284 symp = symlook_obj(name, hash, &obj_rtld, in_plt);
2285 if (symp != NULL && is_exported(symp)) {
2292 *defobj_out = defobj;
2296 static const Elf_Sym *
2297 symlook_list(const char *name, unsigned long hash, Objlist *objlist,
2298 const Obj_Entry **defobj_out, bool in_plt, DoneList *dlp)
2300 const Elf_Sym *symp;
2302 const Obj_Entry *defobj;
2303 const Objlist_Entry *elm;
2307 STAILQ_FOREACH(elm, objlist, link) {
2308 if (donelist_check(dlp, elm->obj))
2310 if ((symp = symlook_obj(name, hash, elm->obj, in_plt)) != NULL) {
2311 if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
2314 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2320 *defobj_out = defobj;
2325 * Search the symbol table of a single shared object for a symbol of
2326 * the given name. Returns a pointer to the symbol, or NULL if no
2327 * definition was found.
2329 * The symbol's hash value is passed in for efficiency reasons; that
2330 * eliminates many recomputations of the hash value.
2333 symlook_obj(const char *name, unsigned long hash, const Obj_Entry *obj,
2336 if (obj->buckets != NULL) {
2337 unsigned long symnum = obj->buckets[hash % obj->nbuckets];
2339 while (symnum != STN_UNDEF) {
2340 const Elf_Sym *symp;
2343 if (symnum >= obj->nchains)
2344 return NULL; /* Bad object */
2345 symp = obj->symtab + symnum;
2346 strp = obj->strtab + symp->st_name;
2348 if (name[0] == strp[0] && strcmp(name, strp) == 0)
2349 return symp->st_shndx != SHN_UNDEF ||
2350 (!in_plt && symp->st_value != 0 &&
2351 ELF_ST_TYPE(symp->st_info) == STT_FUNC) ? symp : NULL;
2353 symnum = obj->chains[symnum];
2360 trace_loaded_objects(Obj_Entry *obj)
2362 const char *fmt1, *fmt2, *fmt, *main_local;
2365 if ((main_local = _getenv_ld("LD_TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
2368 if ((fmt1 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT1")) == NULL)
2369 fmt1 = "\t%o => %p (%x)\n";
2371 if ((fmt2 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT2")) == NULL)
2372 fmt2 = "\t%o (%x)\n";
2374 for (; obj; obj = obj->next) {
2375 Needed_Entry *needed;
2379 for (needed = obj->needed; needed; needed = needed->next) {
2380 if (needed->obj != NULL) {
2381 if (needed->obj->traced)
2383 needed->obj->traced = true;
2384 path = needed->obj->path;
2388 name = (char *)obj->strtab + needed->name;
2389 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
2391 fmt = is_lib ? fmt1 : fmt2;
2392 while ((c = *fmt++) != '\0') {
2418 printf("%s", main_local);
2421 printf("%s", obj_main->path);
2428 printf("%d", sodp->sod_major);
2431 printf("%d", sodp->sod_minor);
2438 printf("%p", needed->obj ? needed->obj->mapbase : 0);
2450 * Unload a dlopened object and its dependencies from memory and from
2451 * our data structures. It is assumed that the DAG rooted in the
2452 * object has already been unreferenced, and that the object has a
2453 * reference count of 0.
2456 unload_object(Obj_Entry *root)
2461 assert(root->refcount == 0);
2464 * Pass over the DAG removing unreferenced objects from
2465 * appropriate lists.
2467 unlink_object(root);
2469 /* Unmap all objects that are no longer referenced. */
2470 linkp = &obj_list->next;
2471 while ((obj = *linkp) != NULL) {
2472 if (obj->refcount == 0) {
2473 dbg("unloading \"%s\"", obj->path);
2474 munmap(obj->mapbase, obj->mapsize);
2475 linkmap_delete(obj);
2486 unlink_object(Obj_Entry *root)
2488 const Needed_Entry *needed;
2491 if (root->refcount == 0) {
2492 /* Remove the object from the RTLD_GLOBAL list. */
2493 objlist_remove(&list_global, root);
2495 /* Remove the object from all objects' DAG lists. */
2496 STAILQ_FOREACH(elm, &root->dagmembers , link)
2497 objlist_remove(&elm->obj->dldags, root);
2500 for (needed = root->needed; needed != NULL; needed = needed->next)
2501 if (needed->obj != NULL)
2502 unlink_object(needed->obj);
2506 unref_dag(Obj_Entry *root)
2508 const Needed_Entry *needed;
2510 if (root->refcount == 0)
2513 if (root->refcount == 0)
2514 for (needed = root->needed; needed != NULL; needed = needed->next)
2515 if (needed->obj != NULL)
2516 unref_dag(needed->obj);