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.9 2005/02/03 23:28:24 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>
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 void errmsg_restore(char *);
87 static char *errmsg_save(void);
88 static void *fill_search_info(const char *, size_t, void *);
89 static char *find_library(const char *, const Obj_Entry *);
90 static const char *gethints(void);
91 static void init_dag(Obj_Entry *);
92 static void init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *);
93 static void init_rtld(caddr_t);
94 static void initlist_add_neededs(Needed_Entry *needed, Objlist *list);
95 static void initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail,
97 static bool is_exported(const Elf_Sym *);
98 static void linkmap_add(Obj_Entry *);
99 static void linkmap_delete(Obj_Entry *);
100 static int load_needed_objects(Obj_Entry *);
101 static int load_preload_objects(void);
102 static Obj_Entry *load_object(char *);
103 static void lock_check(void);
104 static Obj_Entry *obj_from_addr(const void *);
105 static void objlist_call_fini(Objlist *);
106 static void objlist_call_init(Objlist *);
107 static void objlist_clear(Objlist *);
108 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
109 static void objlist_init(Objlist *);
110 static void objlist_push_head(Objlist *, Obj_Entry *);
111 static void objlist_push_tail(Objlist *, Obj_Entry *);
112 static void objlist_remove(Objlist *, Obj_Entry *);
113 static void objlist_remove_unref(Objlist *);
114 static void *path_enumerate(const char *, path_enum_proc, void *);
115 static int relocate_objects(Obj_Entry *, bool);
116 static int rtld_dirname(const char *, char *);
117 static void rtld_exit(void);
118 static char *search_library_path(const char *, const char *);
119 static const void **get_program_var_addr(const char *name);
120 static void set_program_var(const char *, const void *);
121 static const Elf_Sym *symlook_default(const char *, unsigned long hash,
122 const Obj_Entry *refobj, const Obj_Entry **defobj_out, bool in_plt);
123 static const Elf_Sym *symlook_list(const char *, unsigned long,
124 Objlist *, const Obj_Entry **, bool in_plt, DoneList *);
125 static void trace_loaded_objects(Obj_Entry *obj);
126 static void unlink_object(Obj_Entry *);
127 static void unload_object(Obj_Entry *);
128 static void unref_dag(Obj_Entry *);
130 void r_debug_state(struct r_debug*, struct link_map*);
135 static char *error_message; /* Message for dlerror(), or NULL */
136 struct r_debug r_debug; /* for GDB; */
137 static bool trust; /* False for setuid and setgid programs */
138 static const char *ld_bind_now; /* Environment variable for immediate binding */
139 static const char *ld_debug; /* Environment variable for debugging */
140 static const char *ld_library_path; /* Environment variable for search path */
141 static char *ld_preload; /* Environment variable for libraries to
143 static const char *ld_tracing; /* Called from ldd(1) to print libs */
144 static Obj_Entry *obj_list; /* Head of linked list of shared objects */
145 static Obj_Entry **obj_tail; /* Link field of last object in list */
146 static Obj_Entry **preload_tail;
147 static Obj_Entry *obj_main; /* The main program shared object */
148 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
149 static unsigned int obj_count; /* Number of objects in obj_list */
150 static int ld_resident; /* Non-zero if resident */
151 static const char *ld_ary[LD_ARY_CACHE];
154 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
155 STAILQ_HEAD_INITIALIZER(list_global);
156 static Objlist list_main = /* Objects loaded at program startup */
157 STAILQ_HEAD_INITIALIZER(list_main);
158 static Objlist list_fini = /* Objects needing fini() calls */
159 STAILQ_HEAD_INITIALIZER(list_fini);
161 static LockInfo lockinfo;
163 static Elf_Sym sym_zero; /* For resolving undefined weak refs. */
165 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
167 extern Elf_Dyn _DYNAMIC;
168 #pragma weak _DYNAMIC
171 * These are the functions the dynamic linker exports to application
172 * programs. They are the only symbols the dynamic linker is willing
173 * to export from itself.
175 static func_ptr_type exports[] = {
176 (func_ptr_type) &_rtld_error,
177 (func_ptr_type) &dlclose,
178 (func_ptr_type) &dlerror,
179 (func_ptr_type) &dlopen,
180 (func_ptr_type) &dlsym,
181 (func_ptr_type) &dladdr,
182 (func_ptr_type) &dllockinit,
183 (func_ptr_type) &dlinfo,
188 * Global declarations normally provided by crt1. The dynamic linker is
189 * not built with crt1, so we have to provide them ourselves.
195 * Fill in a DoneList with an allocation large enough to hold all of
196 * the currently-loaded objects. Keep this as a macro since it calls
197 * alloca and we want that to occur within the scope of the caller.
199 #define donelist_init(dlp) \
200 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
201 assert((dlp)->objs != NULL), \
202 (dlp)->num_alloc = obj_count, \
208 lockinfo.rlock_acquire(lockinfo.thelock);
209 atomic_incr_int(&lockinfo.rcount);
216 lockinfo.wlock_acquire(lockinfo.thelock);
217 atomic_incr_int(&lockinfo.wcount);
224 atomic_decr_int(&lockinfo.rcount);
225 lockinfo.rlock_release(lockinfo.thelock);
231 atomic_decr_int(&lockinfo.wcount);
232 lockinfo.wlock_release(lockinfo.thelock);
236 * Main entry point for dynamic linking. The first argument is the
237 * stack pointer. The stack is expected to be laid out as described
238 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
239 * Specifically, the stack pointer points to a word containing
240 * ARGC. Following that in the stack is a null-terminated sequence
241 * of pointers to argument strings. Then comes a null-terminated
242 * sequence of pointers to environment strings. Finally, there is a
243 * sequence of "auxiliary vector" entries.
245 * The second argument points to a place to store the dynamic linker's
246 * exit procedure pointer and the third to a place to store the main
249 * The return value is the main program's entry point.
252 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
254 Elf_Auxinfo *aux_info[AT_COUNT];
265 ld_index = 0; /* don't use old env cache in case we are resident */
268 * On entry, the dynamic linker itself has not been relocated yet.
269 * Be very careful not to reference any global data until after
270 * init_rtld has returned. It is OK to reference file-scope statics
271 * and string constants, and to call static and global functions.
274 /* Find the auxiliary vector on the stack. */
277 sp += argc + 1; /* Skip over arguments and NULL terminator */
281 * If we aren't already resident we have to dig out some more info.
282 * Note that auxinfo does not exist when we are resident.
284 if (ld_resident == 0) {
285 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
287 aux = (Elf_Auxinfo *) sp;
289 /* Digest the auxiliary vector. */
290 for (i = 0; i < AT_COUNT; i++)
292 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
293 if (auxp->a_type < AT_COUNT)
294 aux_info[auxp->a_type] = auxp;
297 /* Initialize and relocate ourselves. */
298 assert(aux_info[AT_BASE] != NULL);
299 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
302 __progname = obj_rtld.path;
303 argv0 = argv[0] != NULL ? argv[0] : "(null)";
306 trust = (geteuid() == getuid()) && (getegid() == getgid());
308 ld_bind_now = _getenv_ld("LD_BIND_NOW");
310 ld_debug = _getenv_ld("LD_DEBUG");
311 ld_library_path = _getenv_ld("LD_LIBRARY_PATH");
312 ld_preload = (char *)_getenv_ld("LD_PRELOAD");
314 ld_tracing = _getenv_ld("LD_TRACE_LOADED_OBJECTS");
316 if (ld_debug != NULL && *ld_debug != '\0')
318 dbg("%s is initialized, base address = %p", __progname,
319 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
320 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
321 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
324 * If we are resident we can skip work that we have already done.
325 * Note that the stack is reset and there is no Elf_Auxinfo
326 * when running from a resident image, and the static globals setup
327 * between here and resident_skip will have already been setup.
333 * Load the main program, or process its program header if it is
336 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
337 int fd = aux_info[AT_EXECFD]->a_un.a_val;
338 dbg("loading main program");
339 obj_main = map_object(fd, argv0, NULL);
341 if (obj_main == NULL)
343 } else { /* Main program already loaded. */
344 const Elf_Phdr *phdr;
348 dbg("processing main program's program header");
349 assert(aux_info[AT_PHDR] != NULL);
350 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
351 assert(aux_info[AT_PHNUM] != NULL);
352 phnum = aux_info[AT_PHNUM]->a_un.a_val;
353 assert(aux_info[AT_PHENT] != NULL);
354 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
355 assert(aux_info[AT_ENTRY] != NULL);
356 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
357 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
361 obj_main->path = xstrdup(argv0);
362 obj_main->mainprog = true;
365 * Get the actual dynamic linker pathname from the executable if
366 * possible. (It should always be possible.) That ensures that
367 * gdb will find the right dynamic linker even if a non-standard
370 if (obj_main->interp != NULL &&
371 strcmp(obj_main->interp, obj_rtld.path) != 0) {
373 obj_rtld.path = xstrdup(obj_main->interp);
376 digest_dynamic(obj_main);
378 linkmap_add(obj_main);
379 linkmap_add(&obj_rtld);
381 /* Link the main program into the list of objects. */
382 *obj_tail = obj_main;
383 obj_tail = &obj_main->next;
385 obj_main->refcount++;
386 /* Make sure we don't call the main program's init and fini functions. */
387 obj_main->init = obj_main->fini = NULL;
389 /* Initialize a fake symbol for resolving undefined weak references. */
390 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
391 sym_zero.st_shndx = SHN_ABS;
393 dbg("loading LD_PRELOAD libraries");
394 if (load_preload_objects() == -1)
396 preload_tail = obj_tail;
398 dbg("loading needed objects");
399 if (load_needed_objects(obj_main) == -1)
402 /* Make a list of all objects loaded at startup. */
403 for (obj = obj_list; obj != NULL; obj = obj->next)
404 objlist_push_tail(&list_main, obj);
408 if (ld_tracing) { /* We're done */
409 trace_loaded_objects(obj_main);
413 if (ld_resident) /* XXX clean this up! */
416 if (getenv("LD_DUMP_REL_PRE") != NULL) {
417 dump_relocations(obj_main);
421 if (relocate_objects(obj_main,
422 ld_bind_now != NULL && *ld_bind_now != '\0') == -1)
425 dbg("doing copy relocations");
426 if (do_copy_relocations(obj_main) == -1)
431 if (_getenv_ld("LD_RESIDENT_UNREGISTER_NOW")) {
432 if (exec_sys_unregister(-1) < 0) {
433 dbg("exec_sys_unregister failed %d\n", errno);
436 dbg("exec_sys_unregister success\n");
440 if (getenv("LD_DUMP_REL_POST") != NULL) {
441 dump_relocations(obj_main);
445 dbg("initializing key program variables");
446 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
447 set_program_var("environ", env);
449 if (_getenv_ld("LD_RESIDENT_REGISTER_NOW")) {
450 extern void resident_start(void);
452 if (exec_sys_register(resident_start) < 0) {
453 dbg("exec_sys_register failed %d\n", errno);
456 dbg("exec_sys_register success\n");
460 dbg("initializing thread locks");
461 lockdflt_init(&lockinfo);
462 lockinfo.thelock = lockinfo.lock_create(lockinfo.context);
464 /* Make a list of init functions to call. */
465 objlist_init(&initlist);
466 initlist_add_objects(obj_list, preload_tail, &initlist);
468 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
470 objlist_call_init(&initlist);
472 objlist_clear(&initlist);
477 dbg("transferring control to program entry point = %p", obj_main->entry);
479 /* Return the exit procedure and the program entry point. */
480 *exit_proc = rtld_exit;
482 return (func_ptr_type) obj_main->entry;
486 _rtld_bind(Obj_Entry *obj, Elf_Word reloff)
490 const Obj_Entry *defobj;
496 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
498 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
500 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
501 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL);
505 target = (Elf_Addr)(defobj->relocbase + def->st_value);
507 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
508 defobj->strtab + def->st_name, basename(obj->path),
509 (void *)target, basename(defobj->path));
511 reloc_jmpslot(where, target);
517 * Error reporting function. Use it like printf. If formats the message
518 * into a buffer, and sets things up so that the next call to dlerror()
519 * will return the message.
522 _rtld_error(const char *fmt, ...)
524 static char buf[512];
528 vsnprintf(buf, sizeof buf, fmt, ap);
534 * Return a dynamically-allocated copy of the current error message, if any.
539 return error_message == NULL ? NULL : xstrdup(error_message);
543 * Restore the current error message from a copy which was previously saved
544 * by errmsg_save(). The copy is freed.
547 errmsg_restore(char *saved_msg)
549 if (saved_msg == NULL)
550 error_message = NULL;
552 _rtld_error("%s", saved_msg);
558 basename(const char *name)
560 const char *p = strrchr(name, '/');
561 return p != NULL ? p + 1 : name;
567 const char *msg = dlerror();
575 * Process a shared object's DYNAMIC section, and save the important
576 * information in its Obj_Entry structure.
579 digest_dynamic(Obj_Entry *obj)
582 Needed_Entry **needed_tail = &obj->needed;
583 const Elf_Dyn *dyn_rpath = NULL;
584 int plttype = DT_REL;
586 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
587 switch (dynp->d_tag) {
590 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
594 obj->relsize = dynp->d_un.d_val;
598 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
602 obj->pltrel = (const Elf_Rel *)
603 (obj->relocbase + dynp->d_un.d_ptr);
607 obj->pltrelsize = dynp->d_un.d_val;
611 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
615 obj->relasize = dynp->d_un.d_val;
619 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
623 plttype = dynp->d_un.d_val;
624 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
628 obj->symtab = (const Elf_Sym *)
629 (obj->relocbase + dynp->d_un.d_ptr);
633 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
637 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
641 obj->strsize = dynp->d_un.d_val;
646 const Elf_Addr *hashtab = (const Elf_Addr *)
647 (obj->relocbase + dynp->d_un.d_ptr);
648 obj->nbuckets = hashtab[0];
649 obj->nchains = hashtab[1];
650 obj->buckets = hashtab + 2;
651 obj->chains = obj->buckets + obj->nbuckets;
657 Needed_Entry *nep = NEW(Needed_Entry);
658 nep->name = dynp->d_un.d_val;
663 needed_tail = &nep->next;
668 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
676 obj->symbolic = true;
681 * We have to wait until later to process this, because we
682 * might not have gotten the address of the string table yet.
688 /* Not used by the dynamic linker. */
692 obj->init = (InitFunc) (obj->relocbase + dynp->d_un.d_ptr);
696 obj->fini = (InitFunc) (obj->relocbase + dynp->d_un.d_ptr);
700 /* XXX - not implemented yet */
701 dbg("Filling in DT_DEBUG entry");
702 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
706 dbg("Ignoring d_tag %d = %#x", dynp->d_tag, dynp->d_tag);
713 if (plttype == DT_RELA) {
714 obj->pltrela = (const Elf_Rela *) obj->pltrel;
716 obj->pltrelasize = obj->pltrelsize;
720 if (dyn_rpath != NULL)
721 obj->rpath = obj->strtab + dyn_rpath->d_un.d_val;
725 * Process a shared object's program header. This is used only for the
726 * main program, when the kernel has already loaded the main program
727 * into memory before calling the dynamic linker. It creates and
728 * returns an Obj_Entry structure.
731 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
734 const Elf_Phdr *phlimit = phdr + phnum;
739 for (ph = phdr; ph < phlimit; ph++) {
740 switch (ph->p_type) {
743 if ((const Elf_Phdr *)ph->p_vaddr != phdr) {
744 _rtld_error("%s: invalid PT_PHDR", path);
747 obj->phdr = (const Elf_Phdr *) ph->p_vaddr;
748 obj->phsize = ph->p_memsz;
752 obj->interp = (const char *) ph->p_vaddr;
756 if (nsegs == 0) { /* First load segment */
757 obj->vaddrbase = trunc_page(ph->p_vaddr);
758 obj->mapbase = (caddr_t) obj->vaddrbase;
759 obj->relocbase = obj->mapbase - obj->vaddrbase;
760 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
762 } else { /* Last load segment */
763 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
770 obj->dynamic = (const Elf_Dyn *) ph->p_vaddr;
775 _rtld_error("%s: too few PT_LOAD segments", path);
784 dlcheck(void *handle)
788 for (obj = obj_list; obj != NULL; obj = obj->next)
789 if (obj == (Obj_Entry *) handle)
792 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
793 _rtld_error("Invalid shared object handle %p", handle);
800 * If the given object is already in the donelist, return true. Otherwise
801 * add the object to the list and return false.
804 donelist_check(DoneList *dlp, const Obj_Entry *obj)
808 for (i = 0; i < dlp->num_used; i++)
809 if (dlp->objs[i] == obj)
812 * Our donelist allocation should always be sufficient. But if
813 * our threads locking isn't working properly, more shared objects
814 * could have been loaded since we allocated the list. That should
815 * never happen, but we'll handle it properly just in case it does.
817 if (dlp->num_used < dlp->num_alloc)
818 dlp->objs[dlp->num_used++] = obj;
823 * Hash function for symbol table lookup. Don't even think about changing
824 * this. It is specified by the System V ABI.
827 elf_hash(const char *name)
829 const unsigned char *p = (const unsigned char *) name;
835 if ((g = h & 0xf0000000) != 0)
843 * Find the library with the given name, and return its full pathname.
844 * The returned string is dynamically allocated. Generates an error
845 * message and returns NULL if the library cannot be found.
847 * If the second argument is non-NULL, then it refers to an already-
848 * loaded shared object, whose library search path will be searched.
850 * The search order is:
852 * rpath in the referencing file
857 find_library(const char *name, const Obj_Entry *refobj)
861 if (strchr(name, '/') != NULL) { /* Hard coded pathname */
862 if (name[0] != '/' && !trust) {
863 _rtld_error("Absolute pathname required for shared object \"%s\"",
867 return xstrdup(name);
870 dbg(" Searching for \"%s\"", name);
872 if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
874 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
875 (pathname = search_library_path(name, gethints())) != NULL ||
876 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
879 _rtld_error("Shared object \"%s\" not found", name);
884 * Given a symbol number in a referencing object, find the corresponding
885 * definition of the symbol. Returns a pointer to the symbol, or NULL if
886 * no definition was found. Returns a pointer to the Obj_Entry of the
887 * defining object via the reference parameter DEFOBJ_OUT.
890 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
891 const Obj_Entry **defobj_out, bool in_plt, SymCache *cache)
895 const Obj_Entry *defobj;
900 * If we have already found this symbol, get the information from
903 if (symnum >= refobj->nchains)
904 return NULL; /* Bad object */
905 if (cache != NULL && cache[symnum].sym != NULL) {
906 *defobj_out = cache[symnum].obj;
907 return cache[symnum].sym;
910 ref = refobj->symtab + symnum;
911 name = refobj->strtab + ref->st_name;
912 hash = elf_hash(name);
915 def = symlook_default(name, hash, refobj, &defobj, in_plt);
918 * If we found no definition and the reference is weak, treat the
919 * symbol as having the value zero.
921 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
927 *defobj_out = defobj;
928 /* Record the information in the cache to avoid subsequent lookups. */
930 cache[symnum].sym = def;
931 cache[symnum].obj = defobj;
934 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
939 * Return the search path from the ldconfig hints file, reading it if
940 * necessary. Returns NULL if there are problems with the hints file,
941 * or if the search path there is empty.
950 struct elfhints_hdr hdr;
953 /* Keep from trying again in case the hints file is bad. */
956 if ((fd = open(_PATH_ELF_HINTS, O_RDONLY)) == -1)
958 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
959 hdr.magic != ELFHINTS_MAGIC ||
964 p = xmalloc(hdr.dirlistlen + 1);
965 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
966 read(fd, p, hdr.dirlistlen + 1) != hdr.dirlistlen + 1) {
974 return hints[0] != '\0' ? hints : NULL;
978 init_dag(Obj_Entry *root)
982 donelist_init(&donelist);
983 init_dag1(root, root, &donelist);
987 init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *dlp)
989 const Needed_Entry *needed;
991 if (donelist_check(dlp, obj))
993 objlist_push_tail(&obj->dldags, root);
994 objlist_push_tail(&root->dagmembers, obj);
995 for (needed = obj->needed; needed != NULL; needed = needed->next)
996 if (needed->obj != NULL)
997 init_dag1(root, needed->obj, dlp);
1001 * Initialize the dynamic linker. The argument is the address at which
1002 * the dynamic linker has been mapped into memory. The primary task of
1003 * this function is to relocate the dynamic linker.
1006 init_rtld(caddr_t mapbase)
1009 * Conjure up an Obj_Entry structure for the dynamic linker.
1011 * The "path" member is supposed to be dynamically-allocated, but we
1012 * aren't yet initialized sufficiently to do that. Below we will
1013 * replace the static version with a dynamically-allocated copy.
1015 obj_rtld.path = PATH_RTLD;
1016 obj_rtld.rtld = true;
1017 obj_rtld.mapbase = mapbase;
1019 obj_rtld.relocbase = mapbase;
1021 if (&_DYNAMIC != 0) {
1022 obj_rtld.dynamic = rtld_dynamic(&obj_rtld);
1023 digest_dynamic(&obj_rtld);
1024 assert(obj_rtld.needed == NULL);
1025 assert(!obj_rtld.textrel);
1028 * Temporarily put the dynamic linker entry into the object list, so
1029 * that symbols can be found.
1031 obj_list = &obj_rtld;
1032 obj_tail = &obj_rtld.next;
1035 relocate_objects(&obj_rtld, true);
1038 /* Make the object list empty again. */
1040 obj_tail = &obj_list;
1043 /* Replace the path with a dynamically allocated copy. */
1044 obj_rtld.path = xstrdup(obj_rtld.path);
1046 r_debug.r_brk = r_debug_state;
1047 r_debug.r_state = RT_CONSISTENT;
1051 * Add the init functions from a needed object list (and its recursive
1052 * needed objects) to "list". This is not used directly; it is a helper
1053 * function for initlist_add_objects(). The write lock must be held
1054 * when this function is called.
1057 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1059 /* Recursively process the successor needed objects. */
1060 if (needed->next != NULL)
1061 initlist_add_neededs(needed->next, list);
1063 /* Process the current needed object. */
1064 if (needed->obj != NULL)
1065 initlist_add_objects(needed->obj, &needed->obj->next, list);
1069 * Scan all of the DAGs rooted in the range of objects from "obj" to
1070 * "tail" and add their init functions to "list". This recurses over
1071 * the DAGs and ensure the proper init ordering such that each object's
1072 * needed libraries are initialized before the object itself. At the
1073 * same time, this function adds the objects to the global finalization
1074 * list "list_fini" in the opposite order. The write lock must be
1075 * held when this function is called.
1078 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1082 obj->init_done = true;
1084 /* Recursively process the successor objects. */
1085 if (&obj->next != tail)
1086 initlist_add_objects(obj->next, tail, list);
1088 /* Recursively process the needed objects. */
1089 if (obj->needed != NULL)
1090 initlist_add_neededs(obj->needed, list);
1092 /* Add the object to the init list. */
1093 if (obj->init != NULL)
1094 objlist_push_tail(list, obj);
1096 /* Add the object to the global fini list in the reverse order. */
1097 if (obj->fini != NULL)
1098 objlist_push_head(&list_fini, obj);
1102 is_exported(const Elf_Sym *def)
1104 func_ptr_type value;
1105 const func_ptr_type *p;
1107 value = (func_ptr_type)(obj_rtld.relocbase + def->st_value);
1108 for (p = exports; *p != NULL; p++)
1115 * Given a shared object, traverse its list of needed objects, and load
1116 * each of them. Returns 0 on success. Generates an error message and
1117 * returns -1 on failure.
1120 load_needed_objects(Obj_Entry *first)
1124 for (obj = first; obj != NULL; obj = obj->next) {
1125 Needed_Entry *needed;
1127 for (needed = obj->needed; needed != NULL; needed = needed->next) {
1128 const char *name = obj->strtab + needed->name;
1129 char *path = find_library(name, obj);
1132 if (path == NULL && !ld_tracing)
1136 needed->obj = load_object(path);
1137 if (needed->obj == NULL && !ld_tracing)
1138 return -1; /* XXX - cleanup */
1147 load_preload_objects(void)
1149 char *p = ld_preload;
1150 static const char delim[] = " \t:;";
1155 p += strspn(p, delim);
1156 while (*p != '\0') {
1157 size_t len = strcspn(p, delim);
1163 if ((path = find_library(p, NULL)) == NULL)
1165 if (load_object(path) == NULL)
1166 return -1; /* XXX - cleanup */
1169 p += strspn(p, delim);
1175 * Load a shared object into memory, if it is not already loaded. The
1176 * argument must be a string allocated on the heap. This function assumes
1177 * responsibility for freeing it when necessary.
1179 * Returns a pointer to the Obj_Entry for the object. Returns NULL
1183 load_object(char *path)
1189 for (obj = obj_list->next; obj != NULL; obj = obj->next)
1190 if (strcmp(obj->path, path) == 0)
1194 * If we didn't find a match by pathname, open the file and check
1195 * again by device and inode. This avoids false mismatches caused
1196 * by multiple links or ".." in pathnames.
1198 * To avoid a race, we open the file and use fstat() rather than
1202 if ((fd = open(path, O_RDONLY)) == -1) {
1203 _rtld_error("Cannot open \"%s\"", path);
1206 if (fstat(fd, &sb) == -1) {
1207 _rtld_error("Cannot fstat \"%s\"", path);
1211 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
1212 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev) {
1219 if (obj == NULL) { /* First use of this object, so we must map it in */
1220 dbg("loading \"%s\"", path);
1221 obj = map_object(fd, path, &sb);
1229 digest_dynamic(obj);
1232 obj_tail = &obj->next;
1234 linkmap_add(obj); /* for GDB & dlinfo() */
1236 dbg(" %p .. %p: %s", obj->mapbase,
1237 obj->mapbase + obj->mapsize - 1, obj->path);
1239 dbg(" WARNING: %s has impure text", obj->path);
1248 * Check for locking violations and die if one is found.
1255 rcount = lockinfo.rcount;
1256 wcount = lockinfo.wcount;
1257 assert(rcount >= 0);
1258 assert(wcount >= 0);
1259 if (wcount > 1 || (wcount != 0 && rcount != 0)) {
1260 _rtld_error("Application locking error: %d readers and %d writers"
1261 " in dynamic linker. See DLLOCKINIT(3) in manual pages.",
1268 obj_from_addr(const void *addr)
1270 unsigned long endhash;
1273 endhash = elf_hash(END_SYM);
1274 for (obj = obj_list; obj != NULL; obj = obj->next) {
1275 const Elf_Sym *endsym;
1277 if (addr < (void *) obj->mapbase)
1279 if ((endsym = symlook_obj(END_SYM, endhash, obj, true)) == NULL)
1280 continue; /* No "end" symbol?! */
1281 if (addr < (void *) (obj->relocbase + endsym->st_value))
1288 * Call the finalization functions for each of the objects in "list"
1289 * which are unreferenced. All of the objects are expected to have
1290 * non-NULL fini functions.
1293 objlist_call_fini(Objlist *list)
1299 * Preserve the current error message since a fini function might
1300 * call into the dynamic linker and overwrite it.
1302 saved_msg = errmsg_save();
1303 STAILQ_FOREACH(elm, list, link) {
1304 if (elm->obj->refcount == 0) {
1305 dbg("calling fini function for %s", elm->obj->path);
1306 (*elm->obj->fini)();
1309 errmsg_restore(saved_msg);
1313 * Call the initialization functions for each of the objects in
1314 * "list". All of the objects are expected to have non-NULL init
1318 objlist_call_init(Objlist *list)
1324 * Preserve the current error message since an init function might
1325 * call into the dynamic linker and overwrite it.
1327 saved_msg = errmsg_save();
1328 STAILQ_FOREACH(elm, list, link) {
1329 dbg("calling init function for %s", elm->obj->path);
1330 (*elm->obj->init)();
1332 errmsg_restore(saved_msg);
1336 objlist_clear(Objlist *list)
1340 while (!STAILQ_EMPTY(list)) {
1341 elm = STAILQ_FIRST(list);
1342 STAILQ_REMOVE_HEAD(list, link);
1347 static Objlist_Entry *
1348 objlist_find(Objlist *list, const Obj_Entry *obj)
1352 STAILQ_FOREACH(elm, list, link)
1353 if (elm->obj == obj)
1359 objlist_init(Objlist *list)
1365 objlist_push_head(Objlist *list, Obj_Entry *obj)
1369 elm = NEW(Objlist_Entry);
1371 STAILQ_INSERT_HEAD(list, elm, link);
1375 objlist_push_tail(Objlist *list, Obj_Entry *obj)
1379 elm = NEW(Objlist_Entry);
1381 STAILQ_INSERT_TAIL(list, elm, link);
1385 objlist_remove(Objlist *list, Obj_Entry *obj)
1389 if ((elm = objlist_find(list, obj)) != NULL) {
1390 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1396 * Remove all of the unreferenced objects from "list".
1399 objlist_remove_unref(Objlist *list)
1404 STAILQ_INIT(&newlist);
1405 while (!STAILQ_EMPTY(list)) {
1406 elm = STAILQ_FIRST(list);
1407 STAILQ_REMOVE_HEAD(list, link);
1408 if (elm->obj->refcount == 0)
1411 STAILQ_INSERT_TAIL(&newlist, elm, link);
1417 * Relocate newly-loaded shared objects. The argument is a pointer to
1418 * the Obj_Entry for the first such object. All objects from the first
1419 * to the end of the list of objects are relocated. Returns 0 on success,
1423 relocate_objects(Obj_Entry *first, bool bind_now)
1427 for (obj = first; obj != NULL; obj = obj->next) {
1428 if (obj != &obj_rtld)
1429 dbg("relocating \"%s\"", obj->path);
1430 if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
1431 obj->symtab == NULL || obj->strtab == NULL) {
1432 _rtld_error("%s: Shared object has no run-time symbol table",
1438 /* There are relocations to the write-protected text segment. */
1439 if (mprotect(obj->mapbase, obj->textsize,
1440 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
1441 _rtld_error("%s: Cannot write-enable text segment: %s",
1442 obj->path, strerror(errno));
1447 /* Process the non-PLT relocations. */
1448 if (reloc_non_plt(obj, &obj_rtld))
1452 * Reprotect the text segment. Make sure it is included in the
1453 * core dump since we modified it. This unfortunately causes the
1454 * entire text segment to core-out but we don't have much of a
1455 * choice. We could try to only reenable core dumps on pages
1456 * in which relocations occured but that is likely most of the text
1457 * pages anyway, and even that would not work because the rest of
1458 * the text pages would wind up as a read-only OBJT_DEFAULT object
1459 * (created due to our modifications) backed by the original OBJT_VNODE
1460 * object, and the ELF coredump code is currently only able to dump
1461 * vnode records for pure vnode-backed mappings, not vnode backings
1462 * to memory objects.
1465 madvise(obj->mapbase, obj->textsize, MADV_CORE);
1466 if (mprotect(obj->mapbase, obj->textsize,
1467 PROT_READ|PROT_EXEC) == -1) {
1468 _rtld_error("%s: Cannot write-protect text segment: %s",
1469 obj->path, strerror(errno));
1474 /* Process the PLT relocations. */
1475 if (reloc_plt(obj) == -1)
1477 /* Relocate the jump slots if we are doing immediate binding. */
1479 if (reloc_jmpslots(obj) == -1)
1484 * Set up the magic number and version in the Obj_Entry. These
1485 * were checked in the crt1.o from the original ElfKit, so we
1486 * set them for backward compatibility.
1488 obj->magic = RTLD_MAGIC;
1489 obj->version = RTLD_VERSION;
1491 /* Set the special PLT or GOT entries. */
1499 * Cleanup procedure. It will be called (by the atexit mechanism) just
1500 * before the process exits.
1508 /* Clear all the reference counts so the fini functions will be called. */
1509 for (obj = obj_list; obj != NULL; obj = obj->next)
1511 objlist_call_fini(&list_fini);
1512 /* No need to remove the items from the list, since we are exiting. */
1516 path_enumerate(const char *path, path_enum_proc callback, void *arg)
1521 path += strspn(path, ":;");
1522 while (*path != '\0') {
1526 len = strcspn(path, ":;");
1527 res = callback(path, len, arg);
1533 path += strspn(path, ":;");
1539 struct try_library_args {
1547 try_library_path(const char *dir, size_t dirlen, void *param)
1549 struct try_library_args *arg;
1552 if (*dir == '/' || trust) {
1555 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
1558 pathname = arg->buffer;
1559 strncpy(pathname, dir, dirlen);
1560 pathname[dirlen] = '/';
1561 strcpy(pathname + dirlen + 1, arg->name);
1563 dbg(" Trying \"%s\"", pathname);
1564 if (access(pathname, F_OK) == 0) { /* We found it */
1565 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
1566 strcpy(pathname, arg->buffer);
1574 search_library_path(const char *name, const char *path)
1577 struct try_library_args arg;
1583 arg.namelen = strlen(name);
1584 arg.buffer = xmalloc(PATH_MAX);
1585 arg.buflen = PATH_MAX;
1587 p = path_enumerate(path, try_library_path, &arg);
1595 dlclose(void *handle)
1600 root = dlcheck(handle);
1606 /* Unreference the object and its dependencies. */
1607 root->dl_refcount--;
1610 if (root->refcount == 0) {
1612 * The object is no longer referenced, so we must unload it.
1613 * First, call the fini functions with no locks held.
1616 objlist_call_fini(&list_fini);
1618 objlist_remove_unref(&list_fini);
1620 /* Finish cleaning up the newly-unreferenced objects. */
1621 GDB_STATE(RT_DELETE,&root->linkmap);
1622 unload_object(root);
1623 GDB_STATE(RT_CONSISTENT,NULL);
1632 char *msg = error_message;
1633 error_message = NULL;
1638 * This function is deprecated and has no effect.
1641 dllockinit(void *context,
1642 void *(*lock_create)(void *context),
1643 void (*rlock_acquire)(void *lock),
1644 void (*wlock_acquire)(void *lock),
1645 void (*lock_release)(void *lock),
1646 void (*lock_destroy)(void *lock),
1647 void (*context_destroy)(void *context))
1649 static void *cur_context;
1650 static void (*cur_context_destroy)(void *);
1652 /* Just destroy the context from the previous call, if necessary. */
1653 if (cur_context_destroy != NULL)
1654 cur_context_destroy(cur_context);
1655 cur_context = context;
1656 cur_context_destroy = context_destroy;
1660 dlopen(const char *name, int mode)
1662 Obj_Entry **old_obj_tail;
1667 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
1668 if (ld_tracing != NULL)
1669 environ = (char **)*get_program_var_addr("environ");
1671 objlist_init(&initlist);
1674 GDB_STATE(RT_ADD,NULL);
1676 old_obj_tail = obj_tail;
1682 char *path = find_library(name, obj_main);
1684 obj = load_object(path);
1689 if ((mode & RTLD_GLOBAL) && objlist_find(&list_global, obj) == NULL)
1690 objlist_push_tail(&list_global, obj);
1691 mode &= RTLD_MODEMASK;
1692 if (*old_obj_tail != NULL) { /* We loaded something new. */
1693 assert(*old_obj_tail == obj);
1695 result = load_needed_objects(obj);
1696 if (result != -1 && ld_tracing)
1700 (init_dag(obj), relocate_objects(obj, mode == RTLD_NOW)) == -1) {
1703 if (obj->refcount == 0)
1707 /* Make list of init functions to call. */
1708 initlist_add_objects(obj, &obj->next, &initlist);
1710 } else if (ld_tracing)
1714 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
1716 /* Call the init functions with no locks held. */
1718 objlist_call_init(&initlist);
1720 objlist_clear(&initlist);
1724 trace_loaded_objects(obj);
1730 dlsym(void *handle, const char *name)
1732 const Obj_Entry *obj;
1735 const Obj_Entry *defobj;
1737 hash = elf_hash(name);
1742 if (handle == NULL || handle == RTLD_NEXT ||
1743 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
1746 retaddr = __builtin_return_address(0); /* __GNUC__ only */
1747 if ((obj = obj_from_addr(retaddr)) == NULL) {
1748 _rtld_error("Cannot determine caller's shared object");
1752 if (handle == NULL) { /* Just the caller's shared object. */
1753 def = symlook_obj(name, hash, obj, true);
1755 } else if (handle == RTLD_NEXT || /* Objects after caller's */
1756 handle == RTLD_SELF) { /* ... caller included */
1757 if (handle == RTLD_NEXT)
1759 for (; obj != NULL; obj = obj->next) {
1760 if ((def = symlook_obj(name, hash, obj, true)) != NULL) {
1766 assert(handle == RTLD_DEFAULT);
1767 def = symlook_default(name, hash, obj, &defobj, true);
1770 if ((obj = dlcheck(handle)) == NULL) {
1775 if (obj->mainprog) {
1778 /* Search main program and all libraries loaded by it. */
1779 donelist_init(&donelist);
1780 def = symlook_list(name, hash, &list_main, &defobj, true,
1784 * XXX - This isn't correct. The search should include the whole
1785 * DAG rooted at the given object.
1787 def = symlook_obj(name, hash, obj, true);
1794 return defobj->relocbase + def->st_value;
1797 _rtld_error("Undefined symbol \"%s\"", name);
1803 dladdr(const void *addr, Dl_info *info)
1805 const Obj_Entry *obj;
1808 unsigned long symoffset;
1811 obj = obj_from_addr(addr);
1813 _rtld_error("No shared object contains address");
1817 info->dli_fname = obj->path;
1818 info->dli_fbase = obj->mapbase;
1819 info->dli_saddr = (void *)0;
1820 info->dli_sname = NULL;
1823 * Walk the symbol list looking for the symbol whose address is
1824 * closest to the address sent in.
1826 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
1827 def = obj->symtab + symoffset;
1830 * For skip the symbol if st_shndx is either SHN_UNDEF or
1833 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
1837 * If the symbol is greater than the specified address, or if it
1838 * is further away from addr than the current nearest symbol,
1841 symbol_addr = obj->relocbase + def->st_value;
1842 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
1845 /* Update our idea of the nearest symbol. */
1846 info->dli_sname = obj->strtab + def->st_name;
1847 info->dli_saddr = symbol_addr;
1850 if (info->dli_saddr == addr)
1858 dlinfo(void *handle, int request, void *p)
1860 const Obj_Entry *obj;
1865 if (handle == NULL || handle == RTLD_SELF) {
1868 retaddr = __builtin_return_address(0); /* __GNUC__ only */
1869 if ((obj = obj_from_addr(retaddr)) == NULL)
1870 _rtld_error("Cannot determine caller's shared object");
1872 obj = dlcheck(handle);
1881 case RTLD_DI_LINKMAP:
1882 *((struct link_map const **)p) = &obj->linkmap;
1884 case RTLD_DI_ORIGIN:
1885 error = rtld_dirname(obj->path, p);
1888 case RTLD_DI_SERINFOSIZE:
1889 case RTLD_DI_SERINFO:
1890 error = do_search_info(obj, request, (struct dl_serinfo *)p);
1894 _rtld_error("Invalid request %d passed to dlinfo()", request);
1903 struct fill_search_info_args {
1906 Dl_serinfo *serinfo;
1907 Dl_serpath *serpath;
1912 fill_search_info(const char *dir, size_t dirlen, void *param)
1914 struct fill_search_info_args *arg;
1918 if (arg->request == RTLD_DI_SERINFOSIZE) {
1919 arg->serinfo->dls_cnt ++;
1920 arg->serinfo->dls_size += dirlen + 1;
1922 struct dl_serpath *s_entry;
1924 s_entry = arg->serpath;
1925 s_entry->dls_name = arg->strspace;
1926 s_entry->dls_flags = arg->flags;
1928 strncpy(arg->strspace, dir, dirlen);
1929 arg->strspace[dirlen] = '\0';
1931 arg->strspace += dirlen + 1;
1939 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
1941 struct dl_serinfo _info;
1942 struct fill_search_info_args args;
1944 args.request = RTLD_DI_SERINFOSIZE;
1945 args.serinfo = &_info;
1947 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1950 path_enumerate(ld_library_path, fill_search_info, &args);
1951 path_enumerate(obj->rpath, fill_search_info, &args);
1952 path_enumerate(gethints(), fill_search_info, &args);
1953 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
1956 if (request == RTLD_DI_SERINFOSIZE) {
1957 info->dls_size = _info.dls_size;
1958 info->dls_cnt = _info.dls_cnt;
1962 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
1963 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
1967 args.request = RTLD_DI_SERINFO;
1968 args.serinfo = info;
1969 args.serpath = &info->dls_serpath[0];
1970 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
1972 args.flags = LA_SER_LIBPATH;
1973 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
1976 args.flags = LA_SER_RUNPATH;
1977 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
1980 args.flags = LA_SER_CONFIG;
1981 if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
1984 args.flags = LA_SER_DEFAULT;
1985 if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
1991 rtld_dirname(const char *path, char *bname)
1995 /* Empty or NULL string gets treated as "." */
1996 if (path == NULL || *path == '\0') {
2002 /* Strip trailing slashes */
2003 endp = path + strlen(path) - 1;
2004 while (endp > path && *endp == '/')
2007 /* Find the start of the dir */
2008 while (endp > path && *endp != '/')
2011 /* Either the dir is "/" or there are no slashes */
2013 bname[0] = *endp == '/' ? '/' : '.';
2019 } while (endp > path && *endp == '/');
2022 if (endp - path + 2 > PATH_MAX)
2024 _rtld_error("Filename is too long: %s", path);
2028 strncpy(bname, path, endp - path + 1);
2029 bname[endp - path + 1] = '\0';
2034 linkmap_add(Obj_Entry *obj)
2036 struct link_map *l = &obj->linkmap;
2037 struct link_map *prev;
2039 obj->linkmap.l_name = obj->path;
2040 obj->linkmap.l_addr = obj->mapbase;
2041 obj->linkmap.l_ld = obj->dynamic;
2043 /* GDB needs load offset on MIPS to use the symbols */
2044 obj->linkmap.l_offs = obj->relocbase;
2047 if (r_debug.r_map == NULL) {
2053 * Scan to the end of the list, but not past the entry for the
2054 * dynamic linker, which we want to keep at the very end.
2056 for (prev = r_debug.r_map;
2057 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
2058 prev = prev->l_next)
2061 /* Link in the new entry. */
2063 l->l_next = prev->l_next;
2064 if (l->l_next != NULL)
2065 l->l_next->l_prev = l;
2070 linkmap_delete(Obj_Entry *obj)
2072 struct link_map *l = &obj->linkmap;
2074 if (l->l_prev == NULL) {
2075 if ((r_debug.r_map = l->l_next) != NULL)
2076 l->l_next->l_prev = NULL;
2080 if ((l->l_prev->l_next = l->l_next) != NULL)
2081 l->l_next->l_prev = l->l_prev;
2085 * Function for the debugger to set a breakpoint on to gain control.
2087 * The two parameters allow the debugger to easily find and determine
2088 * what the runtime loader is doing and to whom it is doing it.
2090 * When the loadhook trap is hit (r_debug_state, set at program
2091 * initialization), the arguments can be found on the stack:
2093 * +8 struct link_map *m
2094 * +4 struct r_debug *rd
2098 r_debug_state(struct r_debug* rd, struct link_map *m)
2103 * Get address of the pointer variable in the main program.
2105 static const void **
2106 get_program_var_addr(const char *name)
2108 const Obj_Entry *obj;
2111 hash = elf_hash(name);
2112 for (obj = obj_main; obj != NULL; obj = obj->next) {
2115 if ((def = symlook_obj(name, hash, obj, false)) != NULL) {
2118 addr = (const void **)(obj->relocbase + def->st_value);
2126 * Set a pointer variable in the main program to the given value. This
2127 * is used to set key variables such as "environ" before any of the
2128 * init functions are called.
2131 set_program_var(const char *name, const void *value)
2135 if ((addr = get_program_var_addr(name)) != NULL) {
2136 dbg("\"%s\": *%p <-- %p", name, addr, value);
2142 * This is a special version of getenv which is far more efficient
2143 * at finding LD_ environment vars.
2147 _getenv_ld(const char *id)
2151 int idlen = strlen(id);
2153 if (ld_index == LD_ARY_CACHE)
2155 if (ld_index == 0) {
2156 for (i = j = 0; (envp = environ[i]) != NULL && j < LD_ARY_CACHE; ++i) {
2157 if (envp[0] == 'L' && envp[1] == 'D' && envp[2] == '_')
2164 for (i = ld_index - 1; i >= 0; --i) {
2165 if (strncmp(ld_ary[i], id, idlen) == 0 && ld_ary[i][idlen] == '=')
2166 return(ld_ary[i] + idlen + 1);
2172 * Given a symbol name in a referencing object, find the corresponding
2173 * definition of the symbol. Returns a pointer to the symbol, or NULL if
2174 * no definition was found. Returns a pointer to the Obj_Entry of the
2175 * defining object via the reference parameter DEFOBJ_OUT.
2177 static const Elf_Sym *
2178 symlook_default(const char *name, unsigned long hash,
2179 const Obj_Entry *refobj, const Obj_Entry **defobj_out, bool in_plt)
2183 const Elf_Sym *symp;
2184 const Obj_Entry *obj;
2185 const Obj_Entry *defobj;
2186 const Objlist_Entry *elm;
2189 donelist_init(&donelist);
2191 /* Look first in the referencing object if linked symbolically. */
2192 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
2193 symp = symlook_obj(name, hash, refobj, in_plt);
2200 /* Search all objects loaded at program start up. */
2201 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2202 symp = symlook_list(name, hash, &list_main, &obj, in_plt, &donelist);
2204 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2210 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
2211 STAILQ_FOREACH(elm, &list_global, link) {
2212 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2214 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt,
2217 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2223 /* Search all dlopened DAGs containing the referencing object. */
2224 STAILQ_FOREACH(elm, &refobj->dldags, link) {
2225 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2227 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt,
2230 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2237 * Search the dynamic linker itself, and possibly resolve the
2238 * symbol from there. This is how the application links to
2239 * dynamic linker services such as dlopen. Only the values listed
2240 * in the "exports" array can be resolved from the dynamic linker.
2242 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2243 symp = symlook_obj(name, hash, &obj_rtld, in_plt);
2244 if (symp != NULL && is_exported(symp)) {
2251 *defobj_out = defobj;
2255 static const Elf_Sym *
2256 symlook_list(const char *name, unsigned long hash, Objlist *objlist,
2257 const Obj_Entry **defobj_out, bool in_plt, DoneList *dlp)
2259 const Elf_Sym *symp;
2261 const Obj_Entry *defobj;
2262 const Objlist_Entry *elm;
2266 STAILQ_FOREACH(elm, objlist, link) {
2267 if (donelist_check(dlp, elm->obj))
2269 if ((symp = symlook_obj(name, hash, elm->obj, in_plt)) != NULL) {
2270 if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
2273 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2279 *defobj_out = defobj;
2284 * Search the symbol table of a single shared object for a symbol of
2285 * the given name. Returns a pointer to the symbol, or NULL if no
2286 * definition was found.
2288 * The symbol's hash value is passed in for efficiency reasons; that
2289 * eliminates many recomputations of the hash value.
2292 symlook_obj(const char *name, unsigned long hash, const Obj_Entry *obj,
2295 if (obj->buckets != NULL) {
2296 unsigned long symnum = obj->buckets[hash % obj->nbuckets];
2298 while (symnum != STN_UNDEF) {
2299 const Elf_Sym *symp;
2302 if (symnum >= obj->nchains)
2303 return NULL; /* Bad object */
2304 symp = obj->symtab + symnum;
2305 strp = obj->strtab + symp->st_name;
2307 if (name[0] == strp[0] && strcmp(name, strp) == 0)
2308 return symp->st_shndx != SHN_UNDEF ||
2309 (!in_plt && symp->st_value != 0 &&
2310 ELF_ST_TYPE(symp->st_info) == STT_FUNC) ? symp : NULL;
2312 symnum = obj->chains[symnum];
2319 trace_loaded_objects(Obj_Entry *obj)
2321 const char *fmt1, *fmt2, *fmt, *main_local;
2324 if ((main_local = _getenv_ld("LD_TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
2327 if ((fmt1 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT1")) == NULL)
2328 fmt1 = "\t%o => %p (%x)\n";
2330 if ((fmt2 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT2")) == NULL)
2331 fmt2 = "\t%o (%x)\n";
2333 for (; obj; obj = obj->next) {
2334 Needed_Entry *needed;
2338 for (needed = obj->needed; needed; needed = needed->next) {
2339 if (needed->obj != NULL) {
2340 if (needed->obj->traced)
2342 needed->obj->traced = true;
2343 path = needed->obj->path;
2347 name = (char *)obj->strtab + needed->name;
2348 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
2350 fmt = is_lib ? fmt1 : fmt2;
2351 while ((c = *fmt++) != '\0') {
2377 printf("%s", main_local);
2380 printf("%s", obj_main->path);
2387 printf("%d", sodp->sod_major);
2390 printf("%d", sodp->sod_minor);
2397 printf("%p", needed->obj ? needed->obj->mapbase : 0);
2409 * Unload a dlopened object and its dependencies from memory and from
2410 * our data structures. It is assumed that the DAG rooted in the
2411 * object has already been unreferenced, and that the object has a
2412 * reference count of 0.
2415 unload_object(Obj_Entry *root)
2420 assert(root->refcount == 0);
2423 * Pass over the DAG removing unreferenced objects from
2424 * appropriate lists.
2426 unlink_object(root);
2428 /* Unmap all objects that are no longer referenced. */
2429 linkp = &obj_list->next;
2430 while ((obj = *linkp) != NULL) {
2431 if (obj->refcount == 0) {
2432 dbg("unloading \"%s\"", obj->path);
2433 munmap(obj->mapbase, obj->mapsize);
2434 linkmap_delete(obj);
2445 unlink_object(Obj_Entry *root)
2447 const Needed_Entry *needed;
2450 if (root->refcount == 0) {
2451 /* Remove the object from the RTLD_GLOBAL list. */
2452 objlist_remove(&list_global, root);
2454 /* Remove the object from all objects' DAG lists. */
2455 STAILQ_FOREACH(elm, &root->dagmembers , link)
2456 objlist_remove(&elm->obj->dldags, root);
2459 for (needed = root->needed; needed != NULL; needed = needed->next)
2460 if (needed->obj != NULL)
2461 unlink_object(needed->obj);
2465 unref_dag(Obj_Entry *root)
2467 const Needed_Entry *needed;
2469 if (root->refcount == 0)
2472 if (root->refcount == 0)
2473 for (needed = root->needed; needed != NULL; needed = needed->next)
2474 if (needed->obj != NULL)
2475 unref_dag(needed->obj);