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.13 2005/02/05 22:54:49 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 PATH_RTLD "/usr/libexec/ld-elf.so.1"
59 #define LD_ARY_CACHE 16
62 typedef void (*func_ptr_type)();
63 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg);
66 * This structure provides a reentrant way to keep a list of objects and
67 * check which ones have already been processed in some way.
69 typedef struct Struct_DoneList {
70 const Obj_Entry **objs; /* Array of object pointers */
71 unsigned int num_alloc; /* Allocated size of the array */
72 unsigned int num_used; /* Number of array slots used */
76 * Function declarations.
78 static void die(void);
79 static void digest_dynamic(Obj_Entry *);
80 static const char *_getenv_ld(const char *id);
81 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
82 static Obj_Entry *dlcheck(void *);
83 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
84 static bool donelist_check(DoneList *, const Obj_Entry *);
85 static void errmsg_restore(char *);
86 static char *errmsg_save(void);
87 static void *fill_search_info(const char *, size_t, void *);
88 static char *find_library(const char *, const Obj_Entry *);
89 static const char *gethints(void);
90 static void init_dag(Obj_Entry *);
91 static void init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *);
92 static void init_rtld(caddr_t);
93 static void initlist_add_neededs(Needed_Entry *needed, Objlist *list);
94 static void initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail,
96 static bool is_exported(const Elf_Sym *);
97 static void linkmap_add(Obj_Entry *);
98 static void linkmap_delete(Obj_Entry *);
99 static int load_needed_objects(Obj_Entry *);
100 static int load_preload_objects(void);
101 static Obj_Entry *load_object(char *);
102 static void lock_check(void);
103 static Obj_Entry *obj_from_addr(const void *);
104 static void objlist_call_fini(Objlist *);
105 static void objlist_call_init(Objlist *);
106 static void objlist_clear(Objlist *);
107 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
108 static void objlist_init(Objlist *);
109 static void objlist_push_head(Objlist *, Obj_Entry *);
110 static void objlist_push_tail(Objlist *, Obj_Entry *);
111 static void objlist_remove(Objlist *, Obj_Entry *);
112 static void objlist_remove_unref(Objlist *);
113 static void *path_enumerate(const char *, path_enum_proc, void *);
114 static int relocate_objects(Obj_Entry *, bool);
115 static int rtld_dirname(const char *, char *);
116 static void rtld_exit(void);
117 static char *search_library_path(const char *, const char *);
118 static const void **get_program_var_addr(const char *name);
119 static void set_program_var(const char *, const void *);
120 static const Elf_Sym *symlook_default(const char *, unsigned long hash,
121 const Obj_Entry *refobj, const Obj_Entry **defobj_out, bool in_plt);
122 static const Elf_Sym *symlook_list(const char *, unsigned long,
123 Objlist *, const Obj_Entry **, bool in_plt, DoneList *);
124 static void trace_loaded_objects(Obj_Entry *obj);
125 static void unlink_object(Obj_Entry *);
126 static void unload_object(Obj_Entry *);
127 static void unref_dag(Obj_Entry *);
129 void r_debug_state(struct r_debug*, struct link_map*);
134 static char *error_message; /* Message for dlerror(), or NULL */
135 struct r_debug r_debug; /* for GDB; */
136 static bool trust; /* False for setuid and setgid programs */
137 static const char *ld_bind_now; /* Environment variable for immediate binding */
138 static const char *ld_debug; /* Environment variable for debugging */
139 static const char *ld_library_path; /* Environment variable for search path */
140 static char *ld_preload; /* Environment variable for libraries to
142 static const char *ld_tracing; /* Called from ldd(1) to print libs */
143 static Obj_Entry *obj_list; /* Head of linked list of shared objects */
144 static Obj_Entry **obj_tail; /* Link field of last object in list */
145 static Obj_Entry **preload_tail;
146 static Obj_Entry *obj_main; /* The main program shared object */
147 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
148 static unsigned int obj_count; /* Number of objects in obj_list */
149 static int ld_resident; /* Non-zero if resident */
150 static const char *ld_ary[LD_ARY_CACHE];
153 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
154 STAILQ_HEAD_INITIALIZER(list_global);
155 static Objlist list_main = /* Objects loaded at program startup */
156 STAILQ_HEAD_INITIALIZER(list_main);
157 static Objlist list_fini = /* Objects needing fini() calls */
158 STAILQ_HEAD_INITIALIZER(list_fini);
160 static LockInfo lockinfo;
162 static Elf_Sym sym_zero; /* For resolving undefined weak refs. */
164 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
166 extern Elf_Dyn _DYNAMIC;
167 #pragma weak _DYNAMIC
170 * These are the functions the dynamic linker exports to application
171 * programs. They are the only symbols the dynamic linker is willing
172 * to export from itself.
174 static func_ptr_type exports[] = {
175 (func_ptr_type) &_rtld_error,
176 (func_ptr_type) &dlclose,
177 (func_ptr_type) &dlerror,
178 (func_ptr_type) &dlopen,
179 (func_ptr_type) &dlsym,
180 (func_ptr_type) &dladdr,
181 (func_ptr_type) &dllockinit,
182 (func_ptr_type) &dlinfo,
187 * Global declarations normally provided by crt1. The dynamic linker is
188 * not built with crt1, so we have to provide them ourselves.
194 * Fill in a DoneList with an allocation large enough to hold all of
195 * the currently-loaded objects. Keep this as a macro since it calls
196 * alloca and we want that to occur within the scope of the caller.
198 #define donelist_init(dlp) \
199 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
200 assert((dlp)->objs != NULL), \
201 (dlp)->num_alloc = obj_count, \
207 lockinfo.rlock_acquire(lockinfo.thelock);
208 atomic_incr_int(&lockinfo.rcount);
215 lockinfo.wlock_acquire(lockinfo.thelock);
216 atomic_incr_int(&lockinfo.wcount);
223 atomic_decr_int(&lockinfo.rcount);
224 lockinfo.rlock_release(lockinfo.thelock);
230 atomic_decr_int(&lockinfo.wcount);
231 lockinfo.wlock_release(lockinfo.thelock);
235 * Main entry point for dynamic linking. The first argument is the
236 * stack pointer. The stack is expected to be laid out as described
237 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
238 * Specifically, the stack pointer points to a word containing
239 * ARGC. Following that in the stack is a null-terminated sequence
240 * of pointers to argument strings. Then comes a null-terminated
241 * sequence of pointers to environment strings. Finally, there is a
242 * sequence of "auxiliary vector" entries.
244 * The second argument points to a place to store the dynamic linker's
245 * exit procedure pointer and the third to a place to store the main
248 * The return value is the main program's entry point.
251 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
253 Elf_Auxinfo *aux_info[AT_COUNT];
264 ld_index = 0; /* don't use old env cache in case we are resident */
267 * On entry, the dynamic linker itself has not been relocated yet.
268 * Be very careful not to reference any global data until after
269 * init_rtld has returned. It is OK to reference file-scope statics
270 * and string constants, and to call static and global functions.
273 /* Find the auxiliary vector on the stack. */
276 sp += argc + 1; /* Skip over arguments and NULL terminator */
280 * If we aren't already resident we have to dig out some more info.
281 * Note that auxinfo does not exist when we are resident.
283 if (ld_resident == 0) {
284 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
286 aux = (Elf_Auxinfo *) sp;
288 /* Digest the auxiliary vector. */
289 for (i = 0; i < AT_COUNT; i++)
291 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
292 if (auxp->a_type < AT_COUNT)
293 aux_info[auxp->a_type] = auxp;
296 /* Initialize and relocate ourselves. */
297 assert(aux_info[AT_BASE] != NULL);
298 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
301 __progname = obj_rtld.path;
302 argv0 = argv[0] != NULL ? argv[0] : "(null)";
305 trust = (geteuid() == getuid()) && (getegid() == getgid());
307 ld_bind_now = _getenv_ld("LD_BIND_NOW");
309 ld_debug = _getenv_ld("LD_DEBUG");
310 ld_library_path = _getenv_ld("LD_LIBRARY_PATH");
311 ld_preload = (char *)_getenv_ld("LD_PRELOAD");
313 ld_tracing = _getenv_ld("LD_TRACE_LOADED_OBJECTS");
315 if (ld_debug != NULL && *ld_debug != '\0')
317 dbg("%s is initialized, base address = %p", __progname,
318 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
319 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
320 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
323 * If we are resident we can skip work that we have already done.
324 * Note that the stack is reset and there is no Elf_Auxinfo
325 * when running from a resident image, and the static globals setup
326 * between here and resident_skip will have already been setup.
332 * Load the main program, or process its program header if it is
335 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
336 int fd = aux_info[AT_EXECFD]->a_un.a_val;
337 dbg("loading main program");
338 obj_main = map_object(fd, argv0, NULL);
340 if (obj_main == NULL)
342 } else { /* Main program already loaded. */
343 const Elf_Phdr *phdr;
347 dbg("processing main program's program header");
348 assert(aux_info[AT_PHDR] != NULL);
349 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
350 assert(aux_info[AT_PHNUM] != NULL);
351 phnum = aux_info[AT_PHNUM]->a_un.a_val;
352 assert(aux_info[AT_PHENT] != NULL);
353 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
354 assert(aux_info[AT_ENTRY] != NULL);
355 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
356 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
360 obj_main->path = xstrdup(argv0);
361 obj_main->mainprog = true;
364 * Get the actual dynamic linker pathname from the executable if
365 * possible. (It should always be possible.) That ensures that
366 * gdb will find the right dynamic linker even if a non-standard
369 if (obj_main->interp != NULL &&
370 strcmp(obj_main->interp, obj_rtld.path) != 0) {
372 obj_rtld.path = xstrdup(obj_main->interp);
373 __progname = obj_rtld.path;
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;
680 case DT_RUNPATH: /* XXX: process separately */
682 * We have to wait until later to process this, because we
683 * might not have gotten the address of the string table yet.
689 /* Not used by the dynamic linker. */
693 obj->init = (InitFunc) (obj->relocbase + dynp->d_un.d_ptr);
697 obj->fini = (InitFunc) (obj->relocbase + dynp->d_un.d_ptr);
701 /* XXX - not implemented yet */
702 dbg("Filling in DT_DEBUG entry");
703 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
707 if (dynp->d_un.d_val & DF_ORIGIN) {
708 obj->origin_path = xmalloc(PATH_MAX);
709 if (rtld_dirname(obj->path, obj->origin_path) == -1)
712 if (dynp->d_un.d_val & DF_SYMBOLIC)
713 obj->symbolic = true;
714 if (dynp->d_un.d_val & DF_TEXTREL)
716 if (dynp->d_un.d_val & DF_BIND_NOW)
717 obj->bind_now = true;
718 if (dynp->d_un.d_val & DF_STATIC_TLS)
723 dbg("Ignoring d_tag %d = %#x", dynp->d_tag, dynp->d_tag);
730 if (plttype == DT_RELA) {
731 obj->pltrela = (const Elf_Rela *) obj->pltrel;
733 obj->pltrelasize = obj->pltrelsize;
737 if (dyn_rpath != NULL)
738 obj->rpath = obj->strtab + dyn_rpath->d_un.d_val;
742 * Process a shared object's program header. This is used only for the
743 * main program, when the kernel has already loaded the main program
744 * into memory before calling the dynamic linker. It creates and
745 * returns an Obj_Entry structure.
748 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
751 const Elf_Phdr *phlimit = phdr + phnum;
756 for (ph = phdr; ph < phlimit; ph++) {
757 switch (ph->p_type) {
760 if ((const Elf_Phdr *)ph->p_vaddr != phdr) {
761 _rtld_error("%s: invalid PT_PHDR", path);
764 obj->phdr = (const Elf_Phdr *) ph->p_vaddr;
765 obj->phsize = ph->p_memsz;
769 obj->interp = (const char *) ph->p_vaddr;
773 if (nsegs == 0) { /* First load segment */
774 obj->vaddrbase = trunc_page(ph->p_vaddr);
775 obj->mapbase = (caddr_t) obj->vaddrbase;
776 obj->relocbase = obj->mapbase - obj->vaddrbase;
777 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
779 } else { /* Last load segment */
780 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
787 obj->dynamic = (const Elf_Dyn *) ph->p_vaddr;
792 _rtld_error("%s: too few PT_LOAD segments", path);
801 dlcheck(void *handle)
805 for (obj = obj_list; obj != NULL; obj = obj->next)
806 if (obj == (Obj_Entry *) handle)
809 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
810 _rtld_error("Invalid shared object handle %p", handle);
817 * If the given object is already in the donelist, return true. Otherwise
818 * add the object to the list and return false.
821 donelist_check(DoneList *dlp, const Obj_Entry *obj)
825 for (i = 0; i < dlp->num_used; i++)
826 if (dlp->objs[i] == obj)
829 * Our donelist allocation should always be sufficient. But if
830 * our threads locking isn't working properly, more shared objects
831 * could have been loaded since we allocated the list. That should
832 * never happen, but we'll handle it properly just in case it does.
834 if (dlp->num_used < dlp->num_alloc)
835 dlp->objs[dlp->num_used++] = obj;
840 * Hash function for symbol table lookup. Don't even think about changing
841 * this. It is specified by the System V ABI.
844 elf_hash(const char *name)
846 const unsigned char *p = (const unsigned char *) name;
852 if ((g = h & 0xf0000000) != 0)
860 * Find the library with the given name, and return its full pathname.
861 * The returned string is dynamically allocated. Generates an error
862 * message and returns NULL if the library cannot be found.
864 * If the second argument is non-NULL, then it refers to an already-
865 * loaded shared object, whose library search path will be searched.
867 * The search order is:
869 * rpath in the referencing file
874 find_library(const char *name, const Obj_Entry *refobj)
878 if (strchr(name, '/') != NULL) { /* Hard coded pathname */
879 if (name[0] != '/' && !trust) {
880 _rtld_error("Absolute pathname required for shared object \"%s\"",
884 return xstrdup(name);
887 dbg(" Searching for \"%s\"", name);
889 if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
891 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
892 (pathname = search_library_path(name, gethints())) != NULL ||
893 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
896 if(refobj != NULL && refobj->path != NULL) {
897 _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
898 name, basename(refobj->path));
900 _rtld_error("Shared object \"%s\" not found", name);
906 * Given a symbol number in a referencing object, find the corresponding
907 * definition of the symbol. Returns a pointer to the symbol, or NULL if
908 * no definition was found. Returns a pointer to the Obj_Entry of the
909 * defining object via the reference parameter DEFOBJ_OUT.
912 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
913 const Obj_Entry **defobj_out, bool in_plt, SymCache *cache)
917 const Obj_Entry *defobj;
922 * If we have already found this symbol, get the information from
925 if (symnum >= refobj->nchains)
926 return NULL; /* Bad object */
927 if (cache != NULL && cache[symnum].sym != NULL) {
928 *defobj_out = cache[symnum].obj;
929 return cache[symnum].sym;
932 ref = refobj->symtab + symnum;
933 name = refobj->strtab + ref->st_name;
934 hash = elf_hash(name);
937 def = symlook_default(name, hash, refobj, &defobj, in_plt);
940 * If we found no definition and the reference is weak, treat the
941 * symbol as having the value zero.
943 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
949 *defobj_out = defobj;
950 /* Record the information in the cache to avoid subsequent lookups. */
952 cache[symnum].sym = def;
953 cache[symnum].obj = defobj;
956 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
961 * Return the search path from the ldconfig hints file, reading it if
962 * necessary. Returns NULL if there are problems with the hints file,
963 * or if the search path there is empty.
972 struct elfhints_hdr hdr;
975 /* Keep from trying again in case the hints file is bad. */
978 if ((fd = open(_PATH_ELF_HINTS, O_RDONLY)) == -1)
980 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
981 hdr.magic != ELFHINTS_MAGIC ||
986 p = xmalloc(hdr.dirlistlen + 1);
987 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
988 read(fd, p, hdr.dirlistlen + 1) != hdr.dirlistlen + 1) {
996 return hints[0] != '\0' ? hints : NULL;
1000 init_dag(Obj_Entry *root)
1004 donelist_init(&donelist);
1005 init_dag1(root, root, &donelist);
1009 init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *dlp)
1011 const Needed_Entry *needed;
1013 if (donelist_check(dlp, obj))
1015 objlist_push_tail(&obj->dldags, root);
1016 objlist_push_tail(&root->dagmembers, obj);
1017 for (needed = obj->needed; needed != NULL; needed = needed->next)
1018 if (needed->obj != NULL)
1019 init_dag1(root, needed->obj, dlp);
1023 * Initialize the dynamic linker. The argument is the address at which
1024 * the dynamic linker has been mapped into memory. The primary task of
1025 * this function is to relocate the dynamic linker.
1028 init_rtld(caddr_t mapbase)
1031 * Conjure up an Obj_Entry structure for the dynamic linker.
1033 * The "path" member is supposed to be dynamically-allocated, but we
1034 * aren't yet initialized sufficiently to do that. Below we will
1035 * replace the static version with a dynamically-allocated copy.
1037 obj_rtld.path = PATH_RTLD;
1038 obj_rtld.rtld = true;
1039 obj_rtld.mapbase = mapbase;
1041 obj_rtld.relocbase = mapbase;
1043 if (&_DYNAMIC != 0) {
1044 obj_rtld.dynamic = rtld_dynamic(&obj_rtld);
1045 digest_dynamic(&obj_rtld);
1046 assert(obj_rtld.needed == NULL);
1047 assert(!obj_rtld.textrel);
1050 * Temporarily put the dynamic linker entry into the object list, so
1051 * that symbols can be found.
1053 obj_list = &obj_rtld;
1054 obj_tail = &obj_rtld.next;
1057 relocate_objects(&obj_rtld, true);
1060 /* Make the object list empty again. */
1062 obj_tail = &obj_list;
1065 /* Replace the path with a dynamically allocated copy. */
1066 obj_rtld.path = xstrdup(obj_rtld.path);
1068 r_debug.r_brk = r_debug_state;
1069 r_debug.r_state = RT_CONSISTENT;
1073 * Add the init functions from a needed object list (and its recursive
1074 * needed objects) to "list". This is not used directly; it is a helper
1075 * function for initlist_add_objects(). The write lock must be held
1076 * when this function is called.
1079 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1081 /* Recursively process the successor needed objects. */
1082 if (needed->next != NULL)
1083 initlist_add_neededs(needed->next, list);
1085 /* Process the current needed object. */
1086 if (needed->obj != NULL)
1087 initlist_add_objects(needed->obj, &needed->obj->next, list);
1091 * Scan all of the DAGs rooted in the range of objects from "obj" to
1092 * "tail" and add their init functions to "list". This recurses over
1093 * the DAGs and ensure the proper init ordering such that each object's
1094 * needed libraries are initialized before the object itself. At the
1095 * same time, this function adds the objects to the global finalization
1096 * list "list_fini" in the opposite order. The write lock must be
1097 * held when this function is called.
1100 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1104 obj->init_done = true;
1106 /* Recursively process the successor objects. */
1107 if (&obj->next != tail)
1108 initlist_add_objects(obj->next, tail, list);
1110 /* Recursively process the needed objects. */
1111 if (obj->needed != NULL)
1112 initlist_add_neededs(obj->needed, list);
1114 /* Add the object to the init list. */
1115 if (obj->init != NULL)
1116 objlist_push_tail(list, obj);
1118 /* Add the object to the global fini list in the reverse order. */
1119 if (obj->fini != NULL)
1120 objlist_push_head(&list_fini, obj);
1124 is_exported(const Elf_Sym *def)
1126 func_ptr_type value;
1127 const func_ptr_type *p;
1129 value = (func_ptr_type)(obj_rtld.relocbase + def->st_value);
1130 for (p = exports; *p != NULL; p++)
1137 * Given a shared object, traverse its list of needed objects, and load
1138 * each of them. Returns 0 on success. Generates an error message and
1139 * returns -1 on failure.
1142 load_needed_objects(Obj_Entry *first)
1146 for (obj = first; obj != NULL; obj = obj->next) {
1147 Needed_Entry *needed;
1149 for (needed = obj->needed; needed != NULL; needed = needed->next) {
1150 const char *name = obj->strtab + needed->name;
1151 char *path = find_library(name, obj);
1154 if (path == NULL && !ld_tracing)
1158 needed->obj = load_object(path);
1159 if (needed->obj == NULL && !ld_tracing)
1160 return -1; /* XXX - cleanup */
1169 load_preload_objects(void)
1171 char *p = ld_preload;
1172 static const char delim[] = " \t:;";
1177 p += strspn(p, delim);
1178 while (*p != '\0') {
1179 size_t len = strcspn(p, delim);
1185 if ((path = find_library(p, NULL)) == NULL)
1187 if (load_object(path) == NULL)
1188 return -1; /* XXX - cleanup */
1191 p += strspn(p, delim);
1197 * Load a shared object into memory, if it is not already loaded. The
1198 * argument must be a string allocated on the heap. This function assumes
1199 * responsibility for freeing it when necessary.
1201 * Returns a pointer to the Obj_Entry for the object. Returns NULL
1205 load_object(char *path)
1211 for (obj = obj_list->next; obj != NULL; obj = obj->next)
1212 if (strcmp(obj->path, path) == 0)
1216 * If we didn't find a match by pathname, open the file and check
1217 * again by device and inode. This avoids false mismatches caused
1218 * by multiple links or ".." in pathnames.
1220 * To avoid a race, we open the file and use fstat() rather than
1224 if ((fd = open(path, O_RDONLY)) == -1) {
1225 _rtld_error("Cannot open \"%s\"", path);
1228 if (fstat(fd, &sb) == -1) {
1229 _rtld_error("Cannot fstat \"%s\"", path);
1233 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
1234 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev) {
1241 if (obj == NULL) { /* First use of this object, so we must map it in */
1242 dbg("loading \"%s\"", path);
1243 obj = map_object(fd, path, &sb);
1251 digest_dynamic(obj);
1254 obj_tail = &obj->next;
1256 linkmap_add(obj); /* for GDB & dlinfo() */
1258 dbg(" %p .. %p: %s", obj->mapbase,
1259 obj->mapbase + obj->mapsize - 1, obj->path);
1261 dbg(" WARNING: %s has impure text", obj->path);
1270 * Check for locking violations and die if one is found.
1277 rcount = lockinfo.rcount;
1278 wcount = lockinfo.wcount;
1279 assert(rcount >= 0);
1280 assert(wcount >= 0);
1281 if (wcount > 1 || (wcount != 0 && rcount != 0)) {
1282 _rtld_error("Application locking error: %d readers and %d writers"
1283 " in dynamic linker. See DLLOCKINIT(3) in manual pages.",
1290 obj_from_addr(const void *addr)
1294 for (obj = obj_list; obj != NULL; obj = obj->next) {
1295 if (addr < (void *) obj->mapbase)
1297 if (addr < (void *) (obj->mapbase + obj->mapsize))
1304 * Call the finalization functions for each of the objects in "list"
1305 * which are unreferenced. All of the objects are expected to have
1306 * non-NULL fini functions.
1309 objlist_call_fini(Objlist *list)
1315 * Preserve the current error message since a fini function might
1316 * call into the dynamic linker and overwrite it.
1318 saved_msg = errmsg_save();
1319 STAILQ_FOREACH(elm, list, link) {
1320 if (elm->obj->refcount == 0) {
1321 dbg("calling fini function for %s", elm->obj->path);
1322 (*elm->obj->fini)();
1325 errmsg_restore(saved_msg);
1329 * Call the initialization functions for each of the objects in
1330 * "list". All of the objects are expected to have non-NULL init
1334 objlist_call_init(Objlist *list)
1340 * Preserve the current error message since an init function might
1341 * call into the dynamic linker and overwrite it.
1343 saved_msg = errmsg_save();
1344 STAILQ_FOREACH(elm, list, link) {
1345 dbg("calling init function for %s", elm->obj->path);
1346 (*elm->obj->init)();
1348 errmsg_restore(saved_msg);
1352 objlist_clear(Objlist *list)
1356 while (!STAILQ_EMPTY(list)) {
1357 elm = STAILQ_FIRST(list);
1358 STAILQ_REMOVE_HEAD(list, link);
1363 static Objlist_Entry *
1364 objlist_find(Objlist *list, const Obj_Entry *obj)
1368 STAILQ_FOREACH(elm, list, link)
1369 if (elm->obj == obj)
1375 objlist_init(Objlist *list)
1381 objlist_push_head(Objlist *list, Obj_Entry *obj)
1385 elm = NEW(Objlist_Entry);
1387 STAILQ_INSERT_HEAD(list, elm, link);
1391 objlist_push_tail(Objlist *list, Obj_Entry *obj)
1395 elm = NEW(Objlist_Entry);
1397 STAILQ_INSERT_TAIL(list, elm, link);
1401 objlist_remove(Objlist *list, Obj_Entry *obj)
1405 if ((elm = objlist_find(list, obj)) != NULL) {
1406 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1412 * Remove all of the unreferenced objects from "list".
1415 objlist_remove_unref(Objlist *list)
1420 STAILQ_INIT(&newlist);
1421 while (!STAILQ_EMPTY(list)) {
1422 elm = STAILQ_FIRST(list);
1423 STAILQ_REMOVE_HEAD(list, link);
1424 if (elm->obj->refcount == 0)
1427 STAILQ_INSERT_TAIL(&newlist, elm, link);
1433 * Relocate newly-loaded shared objects. The argument is a pointer to
1434 * the Obj_Entry for the first such object. All objects from the first
1435 * to the end of the list of objects are relocated. Returns 0 on success,
1439 relocate_objects(Obj_Entry *first, bool bind_now)
1443 for (obj = first; obj != NULL; obj = obj->next) {
1444 if (obj != &obj_rtld)
1445 dbg("relocating \"%s\"", obj->path);
1446 if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
1447 obj->symtab == NULL || obj->strtab == NULL) {
1448 _rtld_error("%s: Shared object has no run-time symbol table",
1454 /* There are relocations to the write-protected text segment. */
1455 if (mprotect(obj->mapbase, obj->textsize,
1456 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
1457 _rtld_error("%s: Cannot write-enable text segment: %s",
1458 obj->path, strerror(errno));
1463 /* Process the non-PLT relocations. */
1464 if (reloc_non_plt(obj, &obj_rtld))
1468 * Reprotect the text segment. Make sure it is included in the
1469 * core dump since we modified it. This unfortunately causes the
1470 * entire text segment to core-out but we don't have much of a
1471 * choice. We could try to only reenable core dumps on pages
1472 * in which relocations occured but that is likely most of the text
1473 * pages anyway, and even that would not work because the rest of
1474 * the text pages would wind up as a read-only OBJT_DEFAULT object
1475 * (created due to our modifications) backed by the original OBJT_VNODE
1476 * object, and the ELF coredump code is currently only able to dump
1477 * vnode records for pure vnode-backed mappings, not vnode backings
1478 * to memory objects.
1481 madvise(obj->mapbase, obj->textsize, MADV_CORE);
1482 if (mprotect(obj->mapbase, obj->textsize,
1483 PROT_READ|PROT_EXEC) == -1) {
1484 _rtld_error("%s: Cannot write-protect text segment: %s",
1485 obj->path, strerror(errno));
1490 /* Process the PLT relocations. */
1491 if (reloc_plt(obj) == -1)
1493 /* Relocate the jump slots if we are doing immediate binding. */
1494 if (obj->bind_now || bind_now)
1495 if (reloc_jmpslots(obj) == -1)
1500 * Set up the magic number and version in the Obj_Entry. These
1501 * were checked in the crt1.o from the original ElfKit, so we
1502 * set them for backward compatibility.
1504 obj->magic = RTLD_MAGIC;
1505 obj->version = RTLD_VERSION;
1507 /* Set the special PLT or GOT entries. */
1515 * Cleanup procedure. It will be called (by the atexit mechanism) just
1516 * before the process exits.
1524 /* Clear all the reference counts so the fini functions will be called. */
1525 for (obj = obj_list; obj != NULL; obj = obj->next)
1527 objlist_call_fini(&list_fini);
1528 /* No need to remove the items from the list, since we are exiting. */
1532 path_enumerate(const char *path, path_enum_proc callback, void *arg)
1537 path += strspn(path, ":;");
1538 while (*path != '\0') {
1542 len = strcspn(path, ":;");
1543 res = callback(path, len, arg);
1549 path += strspn(path, ":;");
1555 struct try_library_args {
1563 try_library_path(const char *dir, size_t dirlen, void *param)
1565 struct try_library_args *arg;
1568 if (*dir == '/' || trust) {
1571 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
1574 pathname = arg->buffer;
1575 strncpy(pathname, dir, dirlen);
1576 pathname[dirlen] = '/';
1577 strcpy(pathname + dirlen + 1, arg->name);
1579 dbg(" Trying \"%s\"", pathname);
1580 if (access(pathname, F_OK) == 0) { /* We found it */
1581 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
1582 strcpy(pathname, arg->buffer);
1590 search_library_path(const char *name, const char *path)
1593 struct try_library_args arg;
1599 arg.namelen = strlen(name);
1600 arg.buffer = xmalloc(PATH_MAX);
1601 arg.buflen = PATH_MAX;
1603 p = path_enumerate(path, try_library_path, &arg);
1611 dlclose(void *handle)
1616 root = dlcheck(handle);
1622 /* Unreference the object and its dependencies. */
1623 root->dl_refcount--;
1626 if (root->refcount == 0) {
1628 * The object is no longer referenced, so we must unload it.
1629 * First, call the fini functions with no locks held.
1632 objlist_call_fini(&list_fini);
1634 objlist_remove_unref(&list_fini);
1636 /* Finish cleaning up the newly-unreferenced objects. */
1637 GDB_STATE(RT_DELETE,&root->linkmap);
1638 unload_object(root);
1639 GDB_STATE(RT_CONSISTENT,NULL);
1648 char *msg = error_message;
1649 error_message = NULL;
1654 * This function is deprecated and has no effect.
1657 dllockinit(void *context,
1658 void *(*lock_create)(void *context),
1659 void (*rlock_acquire)(void *lock),
1660 void (*wlock_acquire)(void *lock),
1661 void (*lock_release)(void *lock),
1662 void (*lock_destroy)(void *lock),
1663 void (*context_destroy)(void *context))
1665 static void *cur_context;
1666 static void (*cur_context_destroy)(void *);
1668 /* Just destroy the context from the previous call, if necessary. */
1669 if (cur_context_destroy != NULL)
1670 cur_context_destroy(cur_context);
1671 cur_context = context;
1672 cur_context_destroy = context_destroy;
1676 dlopen(const char *name, int mode)
1678 Obj_Entry **old_obj_tail;
1683 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
1684 if (ld_tracing != NULL)
1685 environ = (char **)*get_program_var_addr("environ");
1687 objlist_init(&initlist);
1690 GDB_STATE(RT_ADD,NULL);
1692 old_obj_tail = obj_tail;
1698 char *path = find_library(name, obj_main);
1700 obj = load_object(path);
1705 if ((mode & RTLD_GLOBAL) && objlist_find(&list_global, obj) == NULL)
1706 objlist_push_tail(&list_global, obj);
1707 mode &= RTLD_MODEMASK;
1708 if (*old_obj_tail != NULL) { /* We loaded something new. */
1709 assert(*old_obj_tail == obj);
1711 result = load_needed_objects(obj);
1712 if (result != -1 && ld_tracing)
1716 (init_dag(obj), relocate_objects(obj, mode == RTLD_NOW)) == -1) {
1719 if (obj->refcount == 0)
1723 /* Make list of init functions to call. */
1724 initlist_add_objects(obj, &obj->next, &initlist);
1726 } else if (ld_tracing)
1730 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
1732 /* Call the init functions with no locks held. */
1734 objlist_call_init(&initlist);
1736 objlist_clear(&initlist);
1740 trace_loaded_objects(obj);
1746 dlsym(void *handle, const char *name)
1748 const Obj_Entry *obj;
1751 const Obj_Entry *defobj;
1753 hash = elf_hash(name);
1758 if (handle == NULL || handle == RTLD_NEXT ||
1759 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
1762 retaddr = __builtin_return_address(0); /* __GNUC__ only */
1763 if ((obj = obj_from_addr(retaddr)) == NULL) {
1764 _rtld_error("Cannot determine caller's shared object");
1768 if (handle == NULL) { /* Just the caller's shared object. */
1769 def = symlook_obj(name, hash, obj, true);
1771 } else if (handle == RTLD_NEXT || /* Objects after caller's */
1772 handle == RTLD_SELF) { /* ... caller included */
1773 if (handle == RTLD_NEXT)
1775 for (; obj != NULL; obj = obj->next) {
1776 if ((def = symlook_obj(name, hash, obj, true)) != NULL) {
1782 assert(handle == RTLD_DEFAULT);
1783 def = symlook_default(name, hash, obj, &defobj, true);
1786 if ((obj = dlcheck(handle)) == NULL) {
1791 if (obj->mainprog) {
1794 /* Search main program and all libraries loaded by it. */
1795 donelist_init(&donelist);
1796 def = symlook_list(name, hash, &list_main, &defobj, true,
1800 * XXX - This isn't correct. The search should include the whole
1801 * DAG rooted at the given object.
1803 def = symlook_obj(name, hash, obj, true);
1810 return defobj->relocbase + def->st_value;
1813 _rtld_error("Undefined symbol \"%s\"", name);
1819 dladdr(const void *addr, Dl_info *info)
1821 const Obj_Entry *obj;
1824 unsigned long symoffset;
1827 obj = obj_from_addr(addr);
1829 _rtld_error("No shared object contains address");
1833 info->dli_fname = obj->path;
1834 info->dli_fbase = obj->mapbase;
1835 info->dli_saddr = (void *)0;
1836 info->dli_sname = NULL;
1839 * Walk the symbol list looking for the symbol whose address is
1840 * closest to the address sent in.
1842 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
1843 def = obj->symtab + symoffset;
1846 * For skip the symbol if st_shndx is either SHN_UNDEF or
1849 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
1853 * If the symbol is greater than the specified address, or if it
1854 * is further away from addr than the current nearest symbol,
1857 symbol_addr = obj->relocbase + def->st_value;
1858 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
1861 /* Update our idea of the nearest symbol. */
1862 info->dli_sname = obj->strtab + def->st_name;
1863 info->dli_saddr = symbol_addr;
1866 if (info->dli_saddr == addr)
1874 dlinfo(void *handle, int request, void *p)
1876 const Obj_Entry *obj;
1881 if (handle == NULL || handle == RTLD_SELF) {
1884 retaddr = __builtin_return_address(0); /* __GNUC__ only */
1885 if ((obj = obj_from_addr(retaddr)) == NULL)
1886 _rtld_error("Cannot determine caller's shared object");
1888 obj = dlcheck(handle);
1897 case RTLD_DI_LINKMAP:
1898 *((struct link_map const **)p) = &obj->linkmap;
1900 case RTLD_DI_ORIGIN:
1901 error = rtld_dirname(obj->path, p);
1904 case RTLD_DI_SERINFOSIZE:
1905 case RTLD_DI_SERINFO:
1906 error = do_search_info(obj, request, (struct dl_serinfo *)p);
1910 _rtld_error("Invalid request %d passed to dlinfo()", request);
1919 struct fill_search_info_args {
1922 Dl_serinfo *serinfo;
1923 Dl_serpath *serpath;
1928 fill_search_info(const char *dir, size_t dirlen, void *param)
1930 struct fill_search_info_args *arg;
1934 if (arg->request == RTLD_DI_SERINFOSIZE) {
1935 arg->serinfo->dls_cnt ++;
1936 arg->serinfo->dls_size += dirlen + 1;
1938 struct dl_serpath *s_entry;
1940 s_entry = arg->serpath;
1941 s_entry->dls_name = arg->strspace;
1942 s_entry->dls_flags = arg->flags;
1944 strncpy(arg->strspace, dir, dirlen);
1945 arg->strspace[dirlen] = '\0';
1947 arg->strspace += dirlen + 1;
1955 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
1957 struct dl_serinfo _info;
1958 struct fill_search_info_args args;
1960 args.request = RTLD_DI_SERINFOSIZE;
1961 args.serinfo = &_info;
1963 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1966 path_enumerate(ld_library_path, fill_search_info, &args);
1967 path_enumerate(obj->rpath, fill_search_info, &args);
1968 path_enumerate(gethints(), fill_search_info, &args);
1969 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
1972 if (request == RTLD_DI_SERINFOSIZE) {
1973 info->dls_size = _info.dls_size;
1974 info->dls_cnt = _info.dls_cnt;
1978 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
1979 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
1983 args.request = RTLD_DI_SERINFO;
1984 args.serinfo = info;
1985 args.serpath = &info->dls_serpath[0];
1986 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
1988 args.flags = LA_SER_LIBPATH;
1989 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
1992 args.flags = LA_SER_RUNPATH;
1993 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
1996 args.flags = LA_SER_CONFIG;
1997 if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
2000 args.flags = LA_SER_DEFAULT;
2001 if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
2007 rtld_dirname(const char *path, char *bname)
2011 /* Empty or NULL string gets treated as "." */
2012 if (path == NULL || *path == '\0') {
2018 /* Strip trailing slashes */
2019 endp = path + strlen(path) - 1;
2020 while (endp > path && *endp == '/')
2023 /* Find the start of the dir */
2024 while (endp > path && *endp != '/')
2027 /* Either the dir is "/" or there are no slashes */
2029 bname[0] = *endp == '/' ? '/' : '.';
2035 } while (endp > path && *endp == '/');
2038 if (endp - path + 2 > PATH_MAX)
2040 _rtld_error("Filename is too long: %s", path);
2044 strncpy(bname, path, endp - path + 1);
2045 bname[endp - path + 1] = '\0';
2050 linkmap_add(Obj_Entry *obj)
2052 struct link_map *l = &obj->linkmap;
2053 struct link_map *prev;
2055 obj->linkmap.l_name = obj->path;
2056 obj->linkmap.l_addr = obj->mapbase;
2057 obj->linkmap.l_ld = obj->dynamic;
2059 /* GDB needs load offset on MIPS to use the symbols */
2060 obj->linkmap.l_offs = obj->relocbase;
2063 if (r_debug.r_map == NULL) {
2069 * Scan to the end of the list, but not past the entry for the
2070 * dynamic linker, which we want to keep at the very end.
2072 for (prev = r_debug.r_map;
2073 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
2074 prev = prev->l_next)
2077 /* Link in the new entry. */
2079 l->l_next = prev->l_next;
2080 if (l->l_next != NULL)
2081 l->l_next->l_prev = l;
2086 linkmap_delete(Obj_Entry *obj)
2088 struct link_map *l = &obj->linkmap;
2090 if (l->l_prev == NULL) {
2091 if ((r_debug.r_map = l->l_next) != NULL)
2092 l->l_next->l_prev = NULL;
2096 if ((l->l_prev->l_next = l->l_next) != NULL)
2097 l->l_next->l_prev = l->l_prev;
2101 * Function for the debugger to set a breakpoint on to gain control.
2103 * The two parameters allow the debugger to easily find and determine
2104 * what the runtime loader is doing and to whom it is doing it.
2106 * When the loadhook trap is hit (r_debug_state, set at program
2107 * initialization), the arguments can be found on the stack:
2109 * +8 struct link_map *m
2110 * +4 struct r_debug *rd
2114 r_debug_state(struct r_debug* rd, struct link_map *m)
2119 * Get address of the pointer variable in the main program.
2121 static const void **
2122 get_program_var_addr(const char *name)
2124 const Obj_Entry *obj;
2127 hash = elf_hash(name);
2128 for (obj = obj_main; obj != NULL; obj = obj->next) {
2131 if ((def = symlook_obj(name, hash, obj, false)) != NULL) {
2134 addr = (const void **)(obj->relocbase + def->st_value);
2142 * Set a pointer variable in the main program to the given value. This
2143 * is used to set key variables such as "environ" before any of the
2144 * init functions are called.
2147 set_program_var(const char *name, const void *value)
2151 if ((addr = get_program_var_addr(name)) != NULL) {
2152 dbg("\"%s\": *%p <-- %p", name, addr, value);
2158 * This is a special version of getenv which is far more efficient
2159 * at finding LD_ environment vars.
2163 _getenv_ld(const char *id)
2167 int idlen = strlen(id);
2169 if (ld_index == LD_ARY_CACHE)
2171 if (ld_index == 0) {
2172 for (i = j = 0; (envp = environ[i]) != NULL && j < LD_ARY_CACHE; ++i) {
2173 if (envp[0] == 'L' && envp[1] == 'D' && envp[2] == '_')
2180 for (i = ld_index - 1; i >= 0; --i) {
2181 if (strncmp(ld_ary[i], id, idlen) == 0 && ld_ary[i][idlen] == '=')
2182 return(ld_ary[i] + idlen + 1);
2188 * Given a symbol name in a referencing object, find the corresponding
2189 * definition of the symbol. Returns a pointer to the symbol, or NULL if
2190 * no definition was found. Returns a pointer to the Obj_Entry of the
2191 * defining object via the reference parameter DEFOBJ_OUT.
2193 static const Elf_Sym *
2194 symlook_default(const char *name, unsigned long hash,
2195 const Obj_Entry *refobj, const Obj_Entry **defobj_out, bool in_plt)
2199 const Elf_Sym *symp;
2200 const Obj_Entry *obj;
2201 const Obj_Entry *defobj;
2202 const Objlist_Entry *elm;
2205 donelist_init(&donelist);
2207 /* Look first in the referencing object if linked symbolically. */
2208 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
2209 symp = symlook_obj(name, hash, refobj, in_plt);
2216 /* Search all objects loaded at program start up. */
2217 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2218 symp = symlook_list(name, hash, &list_main, &obj, in_plt, &donelist);
2220 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2226 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
2227 STAILQ_FOREACH(elm, &list_global, link) {
2228 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2230 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt,
2233 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2239 /* Search all dlopened DAGs containing the referencing object. */
2240 STAILQ_FOREACH(elm, &refobj->dldags, link) {
2241 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2243 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt,
2246 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2253 * Search the dynamic linker itself, and possibly resolve the
2254 * symbol from there. This is how the application links to
2255 * dynamic linker services such as dlopen. Only the values listed
2256 * in the "exports" array can be resolved from the dynamic linker.
2258 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2259 symp = symlook_obj(name, hash, &obj_rtld, in_plt);
2260 if (symp != NULL && is_exported(symp)) {
2267 *defobj_out = defobj;
2271 static const Elf_Sym *
2272 symlook_list(const char *name, unsigned long hash, Objlist *objlist,
2273 const Obj_Entry **defobj_out, bool in_plt, DoneList *dlp)
2275 const Elf_Sym *symp;
2277 const Obj_Entry *defobj;
2278 const Objlist_Entry *elm;
2282 STAILQ_FOREACH(elm, objlist, link) {
2283 if (donelist_check(dlp, elm->obj))
2285 if ((symp = symlook_obj(name, hash, elm->obj, in_plt)) != NULL) {
2286 if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
2289 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2295 *defobj_out = defobj;
2300 * Search the symbol table of a single shared object for a symbol of
2301 * the given name. Returns a pointer to the symbol, or NULL if no
2302 * definition was found.
2304 * The symbol's hash value is passed in for efficiency reasons; that
2305 * eliminates many recomputations of the hash value.
2308 symlook_obj(const char *name, unsigned long hash, const Obj_Entry *obj,
2311 if (obj->buckets != NULL) {
2312 unsigned long symnum = obj->buckets[hash % obj->nbuckets];
2314 while (symnum != STN_UNDEF) {
2315 const Elf_Sym *symp;
2318 if (symnum >= obj->nchains)
2319 return NULL; /* Bad object */
2320 symp = obj->symtab + symnum;
2321 strp = obj->strtab + symp->st_name;
2323 if (name[0] == strp[0] && strcmp(name, strp) == 0)
2324 return symp->st_shndx != SHN_UNDEF ||
2325 (!in_plt && symp->st_value != 0 &&
2326 ELF_ST_TYPE(symp->st_info) == STT_FUNC) ? symp : NULL;
2328 symnum = obj->chains[symnum];
2335 trace_loaded_objects(Obj_Entry *obj)
2337 const char *fmt1, *fmt2, *fmt, *main_local;
2340 if ((main_local = _getenv_ld("LD_TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
2343 if ((fmt1 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT1")) == NULL)
2344 fmt1 = "\t%o => %p (%x)\n";
2346 if ((fmt2 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT2")) == NULL)
2347 fmt2 = "\t%o (%x)\n";
2349 for (; obj; obj = obj->next) {
2350 Needed_Entry *needed;
2354 for (needed = obj->needed; needed; needed = needed->next) {
2355 if (needed->obj != NULL) {
2356 if (needed->obj->traced)
2358 needed->obj->traced = true;
2359 path = needed->obj->path;
2363 name = (char *)obj->strtab + needed->name;
2364 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
2366 fmt = is_lib ? fmt1 : fmt2;
2367 while ((c = *fmt++) != '\0') {
2393 printf("%s", main_local);
2396 printf("%s", obj_main->path);
2403 printf("%d", sodp->sod_major);
2406 printf("%d", sodp->sod_minor);
2413 printf("%p", needed->obj ? needed->obj->mapbase : 0);
2425 * Unload a dlopened object and its dependencies from memory and from
2426 * our data structures. It is assumed that the DAG rooted in the
2427 * object has already been unreferenced, and that the object has a
2428 * reference count of 0.
2431 unload_object(Obj_Entry *root)
2436 assert(root->refcount == 0);
2439 * Pass over the DAG removing unreferenced objects from
2440 * appropriate lists.
2442 unlink_object(root);
2444 /* Unmap all objects that are no longer referenced. */
2445 linkp = &obj_list->next;
2446 while ((obj = *linkp) != NULL) {
2447 if (obj->refcount == 0) {
2448 dbg("unloading \"%s\"", obj->path);
2449 munmap(obj->mapbase, obj->mapsize);
2450 linkmap_delete(obj);
2461 unlink_object(Obj_Entry *root)
2463 const Needed_Entry *needed;
2466 if (root->refcount == 0) {
2467 /* Remove the object from the RTLD_GLOBAL list. */
2468 objlist_remove(&list_global, root);
2470 /* Remove the object from all objects' DAG lists. */
2471 STAILQ_FOREACH(elm, &root->dagmembers , link)
2472 objlist_remove(&elm->obj->dldags, root);
2475 for (needed = root->needed; needed != NULL; needed = needed->next)
2476 if (needed->obj != NULL)
2477 unlink_object(needed->obj);
2481 unref_dag(Obj_Entry *root)
2483 const Needed_Entry *needed;
2485 if (root->refcount == 0)
2488 if (root->refcount == 0)
2489 for (needed = root->needed; needed != NULL; needed = needed->next)
2490 if (needed->obj != NULL)
2491 unref_dag(needed->obj);