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 $
30 * Dynamic linker for ELF.
32 * John Polstra <jdp@polstra.com>.
36 #error "GCC is needed to compile this file"
39 #include <sys/param.h>
56 #define END_SYM "_end"
57 #define PATH_RTLD "/usr/libexec/ld-elf.so.1"
60 typedef void (*func_ptr_type)();
61 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg);
64 * This structure provides a reentrant way to keep a list of objects and
65 * check which ones have already been processed in some way.
67 typedef struct Struct_DoneList {
68 const Obj_Entry **objs; /* Array of object pointers */
69 unsigned int num_alloc; /* Allocated size of the array */
70 unsigned int num_used; /* Number of array slots used */
74 * Function declarations.
76 static const char *basename(const char *);
77 static void die(void);
78 static void digest_dynamic(Obj_Entry *);
79 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
80 static Obj_Entry *dlcheck(void *);
81 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
82 static bool donelist_check(DoneList *, const Obj_Entry *);
83 static void errmsg_restore(char *);
84 static char *errmsg_save(void);
85 static void *fill_search_info(const char *, size_t, void *);
86 static char *find_library(const char *, const Obj_Entry *);
87 static const char *gethints(void);
88 static void init_dag(Obj_Entry *);
89 static void init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *);
90 static void init_rtld(caddr_t);
91 static void initlist_add_neededs(Needed_Entry *needed, Objlist *list);
92 static void initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail,
94 static bool is_exported(const Elf_Sym *);
95 static void linkmap_add(Obj_Entry *);
96 static void linkmap_delete(Obj_Entry *);
97 static int load_needed_objects(Obj_Entry *);
98 static int load_preload_objects(void);
99 static Obj_Entry *load_object(char *);
100 static void lock_check(void);
101 static Obj_Entry *obj_from_addr(const void *);
102 static void objlist_call_fini(Objlist *);
103 static void objlist_call_init(Objlist *);
104 static void objlist_clear(Objlist *);
105 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
106 static void objlist_init(Objlist *);
107 static void objlist_push_head(Objlist *, Obj_Entry *);
108 static void objlist_push_tail(Objlist *, Obj_Entry *);
109 static void objlist_remove(Objlist *, Obj_Entry *);
110 static void objlist_remove_unref(Objlist *);
111 static void *path_enumerate(const char *, path_enum_proc, void *);
112 static int relocate_objects(Obj_Entry *, bool);
113 static int rtld_dirname(const char *, char *);
114 static void rtld_exit(void);
115 static char *search_library_path(const char *, const char *);
116 static const void **get_program_var_addr(const char *name);
117 static void set_program_var(const char *, const void *);
118 static const Elf_Sym *symlook_default(const char *, unsigned long hash,
119 const Obj_Entry *refobj, const Obj_Entry **defobj_out, bool in_plt);
120 static const Elf_Sym *symlook_list(const char *, unsigned long,
121 Objlist *, const Obj_Entry **, bool in_plt, DoneList *);
122 static void trace_loaded_objects(Obj_Entry *obj);
123 static void unlink_object(Obj_Entry *);
124 static void unload_object(Obj_Entry *);
125 static void unref_dag(Obj_Entry *);
127 void r_debug_state(struct r_debug*, struct link_map*);
132 static char *error_message; /* Message for dlerror(), or NULL */
133 struct r_debug r_debug; /* for GDB; */
134 static bool trust; /* False for setuid and setgid programs */
135 static char *ld_bind_now; /* Environment variable for immediate binding */
136 static char *ld_debug; /* Environment variable for debugging */
137 static char *ld_library_path; /* Environment variable for search path */
138 static char *ld_preload; /* Environment variable for libraries to
140 static char *ld_tracing; /* Called from ldd to print libs */
141 static Obj_Entry *obj_list; /* Head of linked list of shared objects */
142 static Obj_Entry **obj_tail; /* Link field of last object in list */
143 static Obj_Entry *obj_main; /* The main program shared object */
144 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
145 static unsigned int obj_count; /* Number of objects in obj_list */
147 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
148 STAILQ_HEAD_INITIALIZER(list_global);
149 static Objlist list_main = /* Objects loaded at program startup */
150 STAILQ_HEAD_INITIALIZER(list_main);
151 static Objlist list_fini = /* Objects needing fini() calls */
152 STAILQ_HEAD_INITIALIZER(list_fini);
154 static LockInfo lockinfo;
156 static Elf_Sym sym_zero; /* For resolving undefined weak refs. */
158 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
160 extern Elf_Dyn _DYNAMIC;
161 #pragma weak _DYNAMIC
164 * These are the functions the dynamic linker exports to application
165 * programs. They are the only symbols the dynamic linker is willing
166 * to export from itself.
168 static func_ptr_type exports[] = {
169 (func_ptr_type) &_rtld_error,
170 (func_ptr_type) &dlclose,
171 (func_ptr_type) &dlerror,
172 (func_ptr_type) &dlopen,
173 (func_ptr_type) &dlsym,
174 (func_ptr_type) &dladdr,
175 (func_ptr_type) &dllockinit,
176 (func_ptr_type) &dlinfo,
181 * Global declarations normally provided by crt1. The dynamic linker is
182 * not built with crt1, so we have to provide them ourselves.
188 * Fill in a DoneList with an allocation large enough to hold all of
189 * the currently-loaded objects. Keep this as a macro since it calls
190 * alloca and we want that to occur within the scope of the caller.
192 #define donelist_init(dlp) \
193 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
194 assert((dlp)->objs != NULL), \
195 (dlp)->num_alloc = obj_count, \
201 lockinfo.rlock_acquire(lockinfo.thelock);
202 atomic_incr_int(&lockinfo.rcount);
209 lockinfo.wlock_acquire(lockinfo.thelock);
210 atomic_incr_int(&lockinfo.wcount);
217 atomic_decr_int(&lockinfo.rcount);
218 lockinfo.rlock_release(lockinfo.thelock);
224 atomic_decr_int(&lockinfo.wcount);
225 lockinfo.wlock_release(lockinfo.thelock);
229 * Main entry point for dynamic linking. The first argument is the
230 * stack pointer. The stack is expected to be laid out as described
231 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
232 * Specifically, the stack pointer points to a word containing
233 * ARGC. Following that in the stack is a null-terminated sequence
234 * of pointers to argument strings. Then comes a null-terminated
235 * sequence of pointers to environment strings. Finally, there is a
236 * sequence of "auxiliary vector" entries.
238 * The second argument points to a place to store the dynamic linker's
239 * exit procedure pointer and the third to a place to store the main
242 * The return value is the main program's entry point.
245 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
247 Elf_Auxinfo *aux_info[AT_COUNT];
256 Obj_Entry **preload_tail;
260 * On entry, the dynamic linker itself has not been relocated yet.
261 * Be very careful not to reference any global data until after
262 * init_rtld has returned. It is OK to reference file-scope statics
263 * and string constants, and to call static and global functions.
266 /* Find the auxiliary vector on the stack. */
269 sp += argc + 1; /* Skip over arguments and NULL terminator */
271 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
273 aux = (Elf_Auxinfo *) sp;
275 /* Digest the auxiliary vector. */
276 for (i = 0; i < AT_COUNT; i++)
278 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
279 if (auxp->a_type < AT_COUNT)
280 aux_info[auxp->a_type] = auxp;
283 /* Initialize and relocate ourselves. */
284 assert(aux_info[AT_BASE] != NULL);
285 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
287 __progname = obj_rtld.path;
288 argv0 = argv[0] != NULL ? argv[0] : "(null)";
291 trust = geteuid() == getuid() && getegid() == getgid();
293 ld_bind_now = getenv("LD_BIND_NOW");
295 ld_debug = getenv("LD_DEBUG");
296 ld_library_path = getenv("LD_LIBRARY_PATH");
297 ld_preload = getenv("LD_PRELOAD");
299 ld_tracing = getenv("LD_TRACE_LOADED_OBJECTS");
301 if (ld_debug != NULL && *ld_debug != '\0')
303 dbg("%s is initialized, base address = %p", __progname,
304 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
305 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
306 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
309 * Load the main program, or process its program header if it is
312 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
313 int fd = aux_info[AT_EXECFD]->a_un.a_val;
314 dbg("loading main program");
315 obj_main = map_object(fd, argv0, NULL);
317 if (obj_main == NULL)
319 } else { /* Main program already loaded. */
320 const Elf_Phdr *phdr;
324 dbg("processing main program's program header");
325 assert(aux_info[AT_PHDR] != NULL);
326 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
327 assert(aux_info[AT_PHNUM] != NULL);
328 phnum = aux_info[AT_PHNUM]->a_un.a_val;
329 assert(aux_info[AT_PHENT] != NULL);
330 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
331 assert(aux_info[AT_ENTRY] != NULL);
332 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
333 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
337 obj_main->path = xstrdup(argv0);
338 obj_main->mainprog = true;
341 * Get the actual dynamic linker pathname from the executable if
342 * possible. (It should always be possible.) That ensures that
343 * gdb will find the right dynamic linker even if a non-standard
346 if (obj_main->interp != NULL &&
347 strcmp(obj_main->interp, obj_rtld.path) != 0) {
349 obj_rtld.path = xstrdup(obj_main->interp);
352 digest_dynamic(obj_main);
354 linkmap_add(obj_main);
355 linkmap_add(&obj_rtld);
357 /* Link the main program into the list of objects. */
358 *obj_tail = obj_main;
359 obj_tail = &obj_main->next;
361 obj_main->refcount++;
362 /* Make sure we don't call the main program's init and fini functions. */
363 obj_main->init = obj_main->fini = NULL;
365 /* Initialize a fake symbol for resolving undefined weak references. */
366 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
367 sym_zero.st_shndx = SHN_ABS;
369 dbg("loading LD_PRELOAD libraries");
370 if (load_preload_objects() == -1)
372 preload_tail = obj_tail;
374 dbg("loading needed objects");
375 if (load_needed_objects(obj_main) == -1)
378 /* Make a list of all objects loaded at startup. */
379 for (obj = obj_list; obj != NULL; obj = obj->next)
380 objlist_push_tail(&list_main, obj);
382 if (ld_tracing) { /* We're done */
383 trace_loaded_objects(obj_main);
387 if (relocate_objects(obj_main,
388 ld_bind_now != NULL && *ld_bind_now != '\0') == -1)
391 dbg("doing copy relocations");
392 if (do_copy_relocations(obj_main) == -1)
395 dbg("initializing key program variables");
396 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
397 set_program_var("environ", env);
399 dbg("initializing thread locks");
400 lockdflt_init(&lockinfo);
401 lockinfo.thelock = lockinfo.lock_create(lockinfo.context);
403 /* Make a list of init functions to call. */
404 objlist_init(&initlist);
405 initlist_add_objects(obj_list, preload_tail, &initlist);
407 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
409 objlist_call_init(&initlist);
411 objlist_clear(&initlist);
414 dbg("transferring control to program entry point = %p", obj_main->entry);
416 /* Return the exit procedure and the program entry point. */
417 *exit_proc = rtld_exit;
419 return (func_ptr_type) obj_main->entry;
423 _rtld_bind(Obj_Entry *obj, Elf_Word reloff)
427 const Obj_Entry *defobj;
433 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
435 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
437 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
438 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL);
442 target = (Elf_Addr)(defobj->relocbase + def->st_value);
444 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
445 defobj->strtab + def->st_name, basename(obj->path),
446 (void *)target, basename(defobj->path));
448 reloc_jmpslot(where, target);
454 * Error reporting function. Use it like printf. If formats the message
455 * into a buffer, and sets things up so that the next call to dlerror()
456 * will return the message.
459 _rtld_error(const char *fmt, ...)
461 static char buf[512];
465 vsnprintf(buf, sizeof buf, fmt, ap);
471 * Return a dynamically-allocated copy of the current error message, if any.
476 return error_message == NULL ? NULL : xstrdup(error_message);
480 * Restore the current error message from a copy which was previously saved
481 * by errmsg_save(). The copy is freed.
484 errmsg_restore(char *saved_msg)
486 if (saved_msg == NULL)
487 error_message = NULL;
489 _rtld_error("%s", saved_msg);
495 basename(const char *name)
497 const char *p = strrchr(name, '/');
498 return p != NULL ? p + 1 : name;
504 const char *msg = dlerror();
512 * Process a shared object's DYNAMIC section, and save the important
513 * information in its Obj_Entry structure.
516 digest_dynamic(Obj_Entry *obj)
519 Needed_Entry **needed_tail = &obj->needed;
520 const Elf_Dyn *dyn_rpath = NULL;
521 int plttype = DT_REL;
523 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
524 switch (dynp->d_tag) {
527 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
531 obj->relsize = dynp->d_un.d_val;
535 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
539 obj->pltrel = (const Elf_Rel *)
540 (obj->relocbase + dynp->d_un.d_ptr);
544 obj->pltrelsize = dynp->d_un.d_val;
548 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
552 obj->relasize = dynp->d_un.d_val;
556 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
560 plttype = dynp->d_un.d_val;
561 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
565 obj->symtab = (const Elf_Sym *)
566 (obj->relocbase + dynp->d_un.d_ptr);
570 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
574 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
578 obj->strsize = dynp->d_un.d_val;
583 const Elf_Addr *hashtab = (const Elf_Addr *)
584 (obj->relocbase + dynp->d_un.d_ptr);
585 obj->nbuckets = hashtab[0];
586 obj->nchains = hashtab[1];
587 obj->buckets = hashtab + 2;
588 obj->chains = obj->buckets + obj->nbuckets;
594 Needed_Entry *nep = NEW(Needed_Entry);
595 nep->name = dynp->d_un.d_val;
600 needed_tail = &nep->next;
605 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
613 obj->symbolic = true;
618 * We have to wait until later to process this, because we
619 * might not have gotten the address of the string table yet.
625 /* Not used by the dynamic linker. */
629 obj->init = (InitFunc) (obj->relocbase + dynp->d_un.d_ptr);
633 obj->fini = (InitFunc) (obj->relocbase + dynp->d_un.d_ptr);
637 /* XXX - not implemented yet */
638 dbg("Filling in DT_DEBUG entry");
639 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
643 dbg("Ignoring d_tag %d = %#x", dynp->d_tag, dynp->d_tag);
650 if (plttype == DT_RELA) {
651 obj->pltrela = (const Elf_Rela *) obj->pltrel;
653 obj->pltrelasize = obj->pltrelsize;
657 if (dyn_rpath != NULL)
658 obj->rpath = obj->strtab + dyn_rpath->d_un.d_val;
662 * Process a shared object's program header. This is used only for the
663 * main program, when the kernel has already loaded the main program
664 * into memory before calling the dynamic linker. It creates and
665 * returns an Obj_Entry structure.
668 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
671 const Elf_Phdr *phlimit = phdr + phnum;
676 for (ph = phdr; ph < phlimit; ph++) {
677 switch (ph->p_type) {
680 if ((const Elf_Phdr *)ph->p_vaddr != phdr) {
681 _rtld_error("%s: invalid PT_PHDR", path);
684 obj->phdr = (const Elf_Phdr *) ph->p_vaddr;
685 obj->phsize = ph->p_memsz;
689 obj->interp = (const char *) ph->p_vaddr;
693 if (nsegs == 0) { /* First load segment */
694 obj->vaddrbase = trunc_page(ph->p_vaddr);
695 obj->mapbase = (caddr_t) obj->vaddrbase;
696 obj->relocbase = obj->mapbase - obj->vaddrbase;
697 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
699 } else { /* Last load segment */
700 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
707 obj->dynamic = (const Elf_Dyn *) ph->p_vaddr;
712 _rtld_error("%s: too few PT_LOAD segments", path);
721 dlcheck(void *handle)
725 for (obj = obj_list; obj != NULL; obj = obj->next)
726 if (obj == (Obj_Entry *) handle)
729 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
730 _rtld_error("Invalid shared object handle %p", handle);
737 * If the given object is already in the donelist, return true. Otherwise
738 * add the object to the list and return false.
741 donelist_check(DoneList *dlp, const Obj_Entry *obj)
745 for (i = 0; i < dlp->num_used; i++)
746 if (dlp->objs[i] == obj)
749 * Our donelist allocation should always be sufficient. But if
750 * our threads locking isn't working properly, more shared objects
751 * could have been loaded since we allocated the list. That should
752 * never happen, but we'll handle it properly just in case it does.
754 if (dlp->num_used < dlp->num_alloc)
755 dlp->objs[dlp->num_used++] = obj;
760 * Hash function for symbol table lookup. Don't even think about changing
761 * this. It is specified by the System V ABI.
764 elf_hash(const char *name)
766 const unsigned char *p = (const unsigned char *) name;
772 if ((g = h & 0xf0000000) != 0)
780 * Find the library with the given name, and return its full pathname.
781 * The returned string is dynamically allocated. Generates an error
782 * message and returns NULL if the library cannot be found.
784 * If the second argument is non-NULL, then it refers to an already-
785 * loaded shared object, whose library search path will be searched.
787 * The search order is:
788 * rpath in the referencing file
794 find_library(const char *name, const Obj_Entry *refobj)
798 if (strchr(name, '/') != NULL) { /* Hard coded pathname */
799 if (name[0] != '/' && !trust) {
800 _rtld_error("Absolute pathname required for shared object \"%s\"",
804 return xstrdup(name);
807 dbg(" Searching for \"%s\"", name);
809 if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
811 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
812 (pathname = search_library_path(name, gethints())) != NULL ||
813 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
816 _rtld_error("Shared object \"%s\" not found", name);
821 * Given a symbol number in a referencing object, find the corresponding
822 * definition of the symbol. Returns a pointer to the symbol, or NULL if
823 * no definition was found. Returns a pointer to the Obj_Entry of the
824 * defining object via the reference parameter DEFOBJ_OUT.
827 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
828 const Obj_Entry **defobj_out, bool in_plt, SymCache *cache)
832 const Obj_Entry *defobj;
837 * If we have already found this symbol, get the information from
840 if (symnum >= refobj->nchains)
841 return NULL; /* Bad object */
842 if (cache != NULL && cache[symnum].sym != NULL) {
843 *defobj_out = cache[symnum].obj;
844 return cache[symnum].sym;
847 ref = refobj->symtab + symnum;
848 name = refobj->strtab + ref->st_name;
849 hash = elf_hash(name);
852 def = symlook_default(name, hash, refobj, &defobj, in_plt);
855 * If we found no definition and the reference is weak, treat the
856 * symbol as having the value zero.
858 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
864 *defobj_out = defobj;
865 /* Record the information in the cache to avoid subsequent lookups. */
867 cache[symnum].sym = def;
868 cache[symnum].obj = defobj;
871 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
876 * Return the search path from the ldconfig hints file, reading it if
877 * necessary. Returns NULL if there are problems with the hints file,
878 * or if the search path there is empty.
887 struct elfhints_hdr hdr;
890 /* Keep from trying again in case the hints file is bad. */
893 if ((fd = open(_PATH_ELF_HINTS, O_RDONLY)) == -1)
895 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
896 hdr.magic != ELFHINTS_MAGIC ||
901 p = xmalloc(hdr.dirlistlen + 1);
902 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
903 read(fd, p, hdr.dirlistlen + 1) != hdr.dirlistlen + 1) {
911 return hints[0] != '\0' ? hints : NULL;
915 init_dag(Obj_Entry *root)
919 donelist_init(&donelist);
920 init_dag1(root, root, &donelist);
924 init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *dlp)
926 const Needed_Entry *needed;
928 if (donelist_check(dlp, obj))
930 objlist_push_tail(&obj->dldags, root);
931 objlist_push_tail(&root->dagmembers, obj);
932 for (needed = obj->needed; needed != NULL; needed = needed->next)
933 if (needed->obj != NULL)
934 init_dag1(root, needed->obj, dlp);
938 * Initialize the dynamic linker. The argument is the address at which
939 * the dynamic linker has been mapped into memory. The primary task of
940 * this function is to relocate the dynamic linker.
943 init_rtld(caddr_t mapbase)
946 * Conjure up an Obj_Entry structure for the dynamic linker.
948 * The "path" member is supposed to be dynamically-allocated, but we
949 * aren't yet initialized sufficiently to do that. Below we will
950 * replace the static version with a dynamically-allocated copy.
952 obj_rtld.path = PATH_RTLD;
953 obj_rtld.rtld = true;
954 obj_rtld.mapbase = mapbase;
956 obj_rtld.relocbase = mapbase;
958 if (&_DYNAMIC != 0) {
959 obj_rtld.dynamic = rtld_dynamic(&obj_rtld);
960 digest_dynamic(&obj_rtld);
961 assert(obj_rtld.needed == NULL);
962 assert(!obj_rtld.textrel);
965 * Temporarily put the dynamic linker entry into the object list, so
966 * that symbols can be found.
968 obj_list = &obj_rtld;
969 obj_tail = &obj_rtld.next;
972 relocate_objects(&obj_rtld, true);
975 /* Make the object list empty again. */
977 obj_tail = &obj_list;
980 /* Replace the path with a dynamically allocated copy. */
981 obj_rtld.path = xstrdup(obj_rtld.path);
983 r_debug.r_brk = r_debug_state;
984 r_debug.r_state = RT_CONSISTENT;
988 * Add the init functions from a needed object list (and its recursive
989 * needed objects) to "list". This is not used directly; it is a helper
990 * function for initlist_add_objects(). The write lock must be held
991 * when this function is called.
994 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
996 /* Recursively process the successor needed objects. */
997 if (needed->next != NULL)
998 initlist_add_neededs(needed->next, list);
1000 /* Process the current needed object. */
1001 if (needed->obj != NULL)
1002 initlist_add_objects(needed->obj, &needed->obj->next, list);
1006 * Scan all of the DAGs rooted in the range of objects from "obj" to
1007 * "tail" and add their init functions to "list". This recurses over
1008 * the DAGs and ensure the proper init ordering such that each object's
1009 * needed libraries are initialized before the object itself. At the
1010 * same time, this function adds the objects to the global finalization
1011 * list "list_fini" in the opposite order. The write lock must be
1012 * held when this function is called.
1015 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1019 obj->init_done = true;
1021 /* Recursively process the successor objects. */
1022 if (&obj->next != tail)
1023 initlist_add_objects(obj->next, tail, list);
1025 /* Recursively process the needed objects. */
1026 if (obj->needed != NULL)
1027 initlist_add_neededs(obj->needed, list);
1029 /* Add the object to the init list. */
1030 if (obj->init != NULL)
1031 objlist_push_tail(list, obj);
1033 /* Add the object to the global fini list in the reverse order. */
1034 if (obj->fini != NULL)
1035 objlist_push_head(&list_fini, obj);
1039 is_exported(const Elf_Sym *def)
1041 func_ptr_type value;
1042 const func_ptr_type *p;
1044 value = (func_ptr_type)(obj_rtld.relocbase + def->st_value);
1045 for (p = exports; *p != NULL; p++)
1052 * Given a shared object, traverse its list of needed objects, and load
1053 * each of them. Returns 0 on success. Generates an error message and
1054 * returns -1 on failure.
1057 load_needed_objects(Obj_Entry *first)
1061 for (obj = first; obj != NULL; obj = obj->next) {
1062 Needed_Entry *needed;
1064 for (needed = obj->needed; needed != NULL; needed = needed->next) {
1065 const char *name = obj->strtab + needed->name;
1066 char *path = find_library(name, obj);
1069 if (path == NULL && !ld_tracing)
1073 needed->obj = load_object(path);
1074 if (needed->obj == NULL && !ld_tracing)
1075 return -1; /* XXX - cleanup */
1084 load_preload_objects(void)
1086 char *p = ld_preload;
1087 static const char delim[] = " \t:;";
1092 p += strspn(p, delim);
1093 while (*p != '\0') {
1094 size_t len = strcspn(p, delim);
1100 if ((path = find_library(p, NULL)) == NULL)
1102 if (load_object(path) == NULL)
1103 return -1; /* XXX - cleanup */
1106 p += strspn(p, delim);
1112 * Load a shared object into memory, if it is not already loaded. The
1113 * argument must be a string allocated on the heap. This function assumes
1114 * responsibility for freeing it when necessary.
1116 * Returns a pointer to the Obj_Entry for the object. Returns NULL
1120 load_object(char *path)
1126 for (obj = obj_list->next; obj != NULL; obj = obj->next)
1127 if (strcmp(obj->path, path) == 0)
1131 * If we didn't find a match by pathname, open the file and check
1132 * again by device and inode. This avoids false mismatches caused
1133 * by multiple links or ".." in pathnames.
1135 * To avoid a race, we open the file and use fstat() rather than
1139 if ((fd = open(path, O_RDONLY)) == -1) {
1140 _rtld_error("Cannot open \"%s\"", path);
1143 if (fstat(fd, &sb) == -1) {
1144 _rtld_error("Cannot fstat \"%s\"", path);
1148 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
1149 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev) {
1156 if (obj == NULL) { /* First use of this object, so we must map it in */
1157 dbg("loading \"%s\"", path);
1158 obj = map_object(fd, path, &sb);
1166 digest_dynamic(obj);
1169 obj_tail = &obj->next;
1171 linkmap_add(obj); /* for GDB & dlinfo() */
1173 dbg(" %p .. %p: %s", obj->mapbase,
1174 obj->mapbase + obj->mapsize - 1, obj->path);
1176 dbg(" WARNING: %s has impure text", obj->path);
1185 * Check for locking violations and die if one is found.
1192 rcount = lockinfo.rcount;
1193 wcount = lockinfo.wcount;
1194 assert(rcount >= 0);
1195 assert(wcount >= 0);
1196 if (wcount > 1 || (wcount != 0 && rcount != 0)) {
1197 _rtld_error("Application locking error: %d readers and %d writers"
1198 " in dynamic linker. See DLLOCKINIT(3) in manual pages.",
1205 obj_from_addr(const void *addr)
1207 unsigned long endhash;
1210 endhash = elf_hash(END_SYM);
1211 for (obj = obj_list; obj != NULL; obj = obj->next) {
1212 const Elf_Sym *endsym;
1214 if (addr < (void *) obj->mapbase)
1216 if ((endsym = symlook_obj(END_SYM, endhash, obj, true)) == NULL)
1217 continue; /* No "end" symbol?! */
1218 if (addr < (void *) (obj->relocbase + endsym->st_value))
1225 * Call the finalization functions for each of the objects in "list"
1226 * which are unreferenced. All of the objects are expected to have
1227 * non-NULL fini functions.
1230 objlist_call_fini(Objlist *list)
1236 * Preserve the current error message since a fini function might
1237 * call into the dynamic linker and overwrite it.
1239 saved_msg = errmsg_save();
1240 STAILQ_FOREACH(elm, list, link) {
1241 if (elm->obj->refcount == 0) {
1242 dbg("calling fini function for %s", elm->obj->path);
1243 (*elm->obj->fini)();
1246 errmsg_restore(saved_msg);
1250 * Call the initialization functions for each of the objects in
1251 * "list". All of the objects are expected to have non-NULL init
1255 objlist_call_init(Objlist *list)
1261 * Preserve the current error message since an init function might
1262 * call into the dynamic linker and overwrite it.
1264 saved_msg = errmsg_save();
1265 STAILQ_FOREACH(elm, list, link) {
1266 dbg("calling init function for %s", elm->obj->path);
1267 (*elm->obj->init)();
1269 errmsg_restore(saved_msg);
1273 objlist_clear(Objlist *list)
1277 while (!STAILQ_EMPTY(list)) {
1278 elm = STAILQ_FIRST(list);
1279 STAILQ_REMOVE_HEAD(list, link);
1284 static Objlist_Entry *
1285 objlist_find(Objlist *list, const Obj_Entry *obj)
1289 STAILQ_FOREACH(elm, list, link)
1290 if (elm->obj == obj)
1296 objlist_init(Objlist *list)
1302 objlist_push_head(Objlist *list, Obj_Entry *obj)
1306 elm = NEW(Objlist_Entry);
1308 STAILQ_INSERT_HEAD(list, elm, link);
1312 objlist_push_tail(Objlist *list, Obj_Entry *obj)
1316 elm = NEW(Objlist_Entry);
1318 STAILQ_INSERT_TAIL(list, elm, link);
1322 objlist_remove(Objlist *list, Obj_Entry *obj)
1326 if ((elm = objlist_find(list, obj)) != NULL) {
1327 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1333 * Remove all of the unreferenced objects from "list".
1336 objlist_remove_unref(Objlist *list)
1341 STAILQ_INIT(&newlist);
1342 while (!STAILQ_EMPTY(list)) {
1343 elm = STAILQ_FIRST(list);
1344 STAILQ_REMOVE_HEAD(list, link);
1345 if (elm->obj->refcount == 0)
1348 STAILQ_INSERT_TAIL(&newlist, elm, link);
1354 * Relocate newly-loaded shared objects. The argument is a pointer to
1355 * the Obj_Entry for the first such object. All objects from the first
1356 * to the end of the list of objects are relocated. Returns 0 on success,
1360 relocate_objects(Obj_Entry *first, bool bind_now)
1364 for (obj = first; obj != NULL; obj = obj->next) {
1365 if (obj != &obj_rtld)
1366 dbg("relocating \"%s\"", obj->path);
1367 if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
1368 obj->symtab == NULL || obj->strtab == NULL) {
1369 _rtld_error("%s: Shared object has no run-time symbol table",
1375 /* There are relocations to the write-protected text segment. */
1376 if (mprotect(obj->mapbase, obj->textsize,
1377 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
1378 _rtld_error("%s: Cannot write-enable text segment: %s",
1379 obj->path, strerror(errno));
1384 /* Process the non-PLT relocations. */
1385 if (reloc_non_plt(obj, &obj_rtld))
1388 if (obj->textrel) { /* Re-protected the text segment. */
1389 if (mprotect(obj->mapbase, obj->textsize,
1390 PROT_READ|PROT_EXEC) == -1) {
1391 _rtld_error("%s: Cannot write-protect text segment: %s",
1392 obj->path, strerror(errno));
1397 /* Process the PLT relocations. */
1398 if (reloc_plt(obj) == -1)
1400 /* Relocate the jump slots if we are doing immediate binding. */
1402 if (reloc_jmpslots(obj) == -1)
1407 * Set up the magic number and version in the Obj_Entry. These
1408 * were checked in the crt1.o from the original ElfKit, so we
1409 * set them for backward compatibility.
1411 obj->magic = RTLD_MAGIC;
1412 obj->version = RTLD_VERSION;
1414 /* Set the special PLT or GOT entries. */
1422 * Cleanup procedure. It will be called (by the atexit mechanism) just
1423 * before the process exits.
1431 /* Clear all the reference counts so the fini functions will be called. */
1432 for (obj = obj_list; obj != NULL; obj = obj->next)
1434 objlist_call_fini(&list_fini);
1435 /* No need to remove the items from the list, since we are exiting. */
1439 path_enumerate(const char *path, path_enum_proc callback, void *arg)
1444 path += strspn(path, ":;");
1445 while (*path != '\0') {
1449 len = strcspn(path, ":;");
1450 res = callback(path, len, arg);
1456 path += strspn(path, ":;");
1462 struct try_library_args {
1470 try_library_path(const char *dir, size_t dirlen, void *param)
1472 struct try_library_args *arg;
1475 if (*dir == '/' || trust) {
1478 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
1481 pathname = arg->buffer;
1482 strncpy(pathname, dir, dirlen);
1483 pathname[dirlen] = '/';
1484 strcpy(pathname + dirlen + 1, arg->name);
1486 dbg(" Trying \"%s\"", pathname);
1487 if (access(pathname, F_OK) == 0) { /* We found it */
1488 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
1489 strcpy(pathname, arg->buffer);
1497 search_library_path(const char *name, const char *path)
1500 struct try_library_args arg;
1506 arg.namelen = strlen(name);
1507 arg.buffer = xmalloc(PATH_MAX);
1508 arg.buflen = PATH_MAX;
1510 p = path_enumerate(path, try_library_path, &arg);
1518 dlclose(void *handle)
1523 root = dlcheck(handle);
1529 /* Unreference the object and its dependencies. */
1530 root->dl_refcount--;
1533 if (root->refcount == 0) {
1535 * The object is no longer referenced, so we must unload it.
1536 * First, call the fini functions with no locks held.
1539 objlist_call_fini(&list_fini);
1541 objlist_remove_unref(&list_fini);
1543 /* Finish cleaning up the newly-unreferenced objects. */
1544 GDB_STATE(RT_DELETE,&root->linkmap);
1545 unload_object(root);
1546 GDB_STATE(RT_CONSISTENT,NULL);
1555 char *msg = error_message;
1556 error_message = NULL;
1561 * This function is deprecated and has no effect.
1564 dllockinit(void *context,
1565 void *(*lock_create)(void *context),
1566 void (*rlock_acquire)(void *lock),
1567 void (*wlock_acquire)(void *lock),
1568 void (*lock_release)(void *lock),
1569 void (*lock_destroy)(void *lock),
1570 void (*context_destroy)(void *context))
1572 static void *cur_context;
1573 static void (*cur_context_destroy)(void *);
1575 /* Just destroy the context from the previous call, if necessary. */
1576 if (cur_context_destroy != NULL)
1577 cur_context_destroy(cur_context);
1578 cur_context = context;
1579 cur_context_destroy = context_destroy;
1583 dlopen(const char *name, int mode)
1585 Obj_Entry **old_obj_tail;
1590 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
1591 if (ld_tracing != NULL)
1592 environ = (char **)*get_program_var_addr("environ");
1594 objlist_init(&initlist);
1597 GDB_STATE(RT_ADD,NULL);
1599 old_obj_tail = obj_tail;
1605 char *path = find_library(name, obj_main);
1607 obj = load_object(path);
1612 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
1613 objlist_push_tail(&list_global, obj);
1614 mode &= RTLD_MODEMASK;
1615 if (*old_obj_tail != NULL) { /* We loaded something new. */
1616 assert(*old_obj_tail == obj);
1618 result = load_needed_objects(obj);
1619 if (result != -1 && ld_tracing)
1623 (init_dag(obj), relocate_objects(obj, mode == RTLD_NOW)) == -1) {
1626 if (obj->refcount == 0)
1630 /* Make list of init functions to call. */
1631 initlist_add_objects(obj, &obj->next, &initlist);
1633 } else if (ld_tracing)
1637 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
1639 /* Call the init functions with no locks held. */
1641 objlist_call_init(&initlist);
1643 objlist_clear(&initlist);
1647 trace_loaded_objects(obj);
1653 dlsym(void *handle, const char *name)
1655 const Obj_Entry *obj;
1658 const Obj_Entry *defobj;
1660 hash = elf_hash(name);
1665 if (handle == NULL || handle == RTLD_NEXT ||
1666 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
1669 retaddr = __builtin_return_address(0); /* __GNUC__ only */
1670 if ((obj = obj_from_addr(retaddr)) == NULL) {
1671 _rtld_error("Cannot determine caller's shared object");
1675 if (handle == NULL) { /* Just the caller's shared object. */
1676 def = symlook_obj(name, hash, obj, true);
1678 } else if (handle == RTLD_NEXT || /* Objects after caller's */
1679 handle == RTLD_SELF) { /* ... caller included */
1680 if (handle == RTLD_NEXT)
1682 for (; obj != NULL; obj = obj->next) {
1683 if ((def = symlook_obj(name, hash, obj, true)) != NULL) {
1689 assert(handle == RTLD_DEFAULT);
1690 def = symlook_default(name, hash, obj, &defobj, true);
1693 if ((obj = dlcheck(handle)) == NULL) {
1698 if (obj->mainprog) {
1701 /* Search main program and all libraries loaded by it. */
1702 donelist_init(&donelist);
1703 def = symlook_list(name, hash, &list_main, &defobj, true,
1707 * XXX - This isn't correct. The search should include the whole
1708 * DAG rooted at the given object.
1710 def = symlook_obj(name, hash, obj, true);
1717 return defobj->relocbase + def->st_value;
1720 _rtld_error("Undefined symbol \"%s\"", name);
1726 dladdr(const void *addr, Dl_info *info)
1728 const Obj_Entry *obj;
1731 unsigned long symoffset;
1734 obj = obj_from_addr(addr);
1736 _rtld_error("No shared object contains address");
1740 info->dli_fname = obj->path;
1741 info->dli_fbase = obj->mapbase;
1742 info->dli_saddr = (void *)0;
1743 info->dli_sname = NULL;
1746 * Walk the symbol list looking for the symbol whose address is
1747 * closest to the address sent in.
1749 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
1750 def = obj->symtab + symoffset;
1753 * For skip the symbol if st_shndx is either SHN_UNDEF or
1756 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
1760 * If the symbol is greater than the specified address, or if it
1761 * is further away from addr than the current nearest symbol,
1764 symbol_addr = obj->relocbase + def->st_value;
1765 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
1768 /* Update our idea of the nearest symbol. */
1769 info->dli_sname = obj->strtab + def->st_name;
1770 info->dli_saddr = symbol_addr;
1773 if (info->dli_saddr == addr)
1781 dlinfo(void *handle, int request, void *p)
1783 const Obj_Entry *obj;
1788 if (handle == NULL || handle == RTLD_SELF) {
1791 retaddr = __builtin_return_address(0); /* __GNUC__ only */
1792 if ((obj = obj_from_addr(retaddr)) == NULL)
1793 _rtld_error("Cannot determine caller's shared object");
1795 obj = dlcheck(handle);
1804 case RTLD_DI_LINKMAP:
1805 *((struct link_map const **)p) = &obj->linkmap;
1807 case RTLD_DI_ORIGIN:
1808 error = rtld_dirname(obj->path, p);
1811 case RTLD_DI_SERINFOSIZE:
1812 case RTLD_DI_SERINFO:
1813 error = do_search_info(obj, request, (struct dl_serinfo *)p);
1817 _rtld_error("Invalid request %d passed to dlinfo()", request);
1826 struct fill_search_info_args {
1829 Dl_serinfo *serinfo;
1830 Dl_serpath *serpath;
1835 fill_search_info(const char *dir, size_t dirlen, void *param)
1837 struct fill_search_info_args *arg;
1841 if (arg->request == RTLD_DI_SERINFOSIZE) {
1842 arg->serinfo->dls_cnt ++;
1843 arg->serinfo->dls_size += dirlen + 1;
1845 struct dl_serpath *s_entry;
1847 s_entry = arg->serpath;
1848 s_entry->dls_name = arg->strspace;
1849 s_entry->dls_flags = arg->flags;
1851 strncpy(arg->strspace, dir, dirlen);
1852 arg->strspace[dirlen] = '\0';
1854 arg->strspace += dirlen + 1;
1862 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
1864 struct dl_serinfo _info;
1865 struct fill_search_info_args args;
1867 args.request = RTLD_DI_SERINFOSIZE;
1868 args.serinfo = &_info;
1870 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1873 path_enumerate(ld_library_path, fill_search_info, &args);
1874 path_enumerate(obj->rpath, fill_search_info, &args);
1875 path_enumerate(gethints(), fill_search_info, &args);
1876 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
1879 if (request == RTLD_DI_SERINFOSIZE) {
1880 info->dls_size = _info.dls_size;
1881 info->dls_cnt = _info.dls_cnt;
1885 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
1886 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
1890 args.request = RTLD_DI_SERINFO;
1891 args.serinfo = info;
1892 args.serpath = &info->dls_serpath[0];
1893 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
1895 args.flags = LA_SER_LIBPATH;
1896 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
1899 args.flags = LA_SER_RUNPATH;
1900 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
1903 args.flags = LA_SER_CONFIG;
1904 if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
1907 args.flags = LA_SER_DEFAULT;
1908 if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
1914 rtld_dirname(const char *path, char *bname)
1918 /* Empty or NULL string gets treated as "." */
1919 if (path == NULL || *path == '\0') {
1925 /* Strip trailing slashes */
1926 endp = path + strlen(path) - 1;
1927 while (endp > path && *endp == '/')
1930 /* Find the start of the dir */
1931 while (endp > path && *endp != '/')
1934 /* Either the dir is "/" or there are no slashes */
1936 bname[0] = *endp == '/' ? '/' : '.';
1942 } while (endp > path && *endp == '/');
1945 if (endp - path + 2 > PATH_MAX)
1947 _rtld_error("Filename is too long: %s", path);
1951 strncpy(bname, path, endp - path + 1);
1952 bname[endp - path + 1] = '\0';
1957 linkmap_add(Obj_Entry *obj)
1959 struct link_map *l = &obj->linkmap;
1960 struct link_map *prev;
1962 obj->linkmap.l_name = obj->path;
1963 obj->linkmap.l_addr = obj->mapbase;
1964 obj->linkmap.l_ld = obj->dynamic;
1966 /* GDB needs load offset on MIPS to use the symbols */
1967 obj->linkmap.l_offs = obj->relocbase;
1970 if (r_debug.r_map == NULL) {
1976 * Scan to the end of the list, but not past the entry for the
1977 * dynamic linker, which we want to keep at the very end.
1979 for (prev = r_debug.r_map;
1980 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
1981 prev = prev->l_next)
1984 /* Link in the new entry. */
1986 l->l_next = prev->l_next;
1987 if (l->l_next != NULL)
1988 l->l_next->l_prev = l;
1993 linkmap_delete(Obj_Entry *obj)
1995 struct link_map *l = &obj->linkmap;
1997 if (l->l_prev == NULL) {
1998 if ((r_debug.r_map = l->l_next) != NULL)
1999 l->l_next->l_prev = NULL;
2003 if ((l->l_prev->l_next = l->l_next) != NULL)
2004 l->l_next->l_prev = l->l_prev;
2008 * Function for the debugger to set a breakpoint on to gain control.
2010 * The two parameters allow the debugger to easily find and determine
2011 * what the runtime loader is doing and to whom it is doing it.
2013 * When the loadhook trap is hit (r_debug_state, set at program
2014 * initialization), the arguments can be found on the stack:
2016 * +8 struct link_map *m
2017 * +4 struct r_debug *rd
2021 r_debug_state(struct r_debug* rd, struct link_map *m)
2026 * Get address of the pointer variable in the main program.
2028 static const void **
2029 get_program_var_addr(const char *name)
2031 const Obj_Entry *obj;
2034 hash = elf_hash(name);
2035 for (obj = obj_main; obj != NULL; obj = obj->next) {
2038 if ((def = symlook_obj(name, hash, obj, false)) != NULL) {
2041 addr = (const void **)(obj->relocbase + def->st_value);
2049 * Set a pointer variable in the main program to the given value. This
2050 * is used to set key variables such as "environ" before any of the
2051 * init functions are called.
2054 set_program_var(const char *name, const void *value)
2058 if ((addr = get_program_var_addr(name)) != NULL) {
2059 dbg("\"%s\": *%p <-- %p", name, addr, value);
2065 * Given a symbol name in a referencing object, find the corresponding
2066 * definition of the symbol. Returns a pointer to the symbol, or NULL if
2067 * no definition was found. Returns a pointer to the Obj_Entry of the
2068 * defining object via the reference parameter DEFOBJ_OUT.
2070 static const Elf_Sym *
2071 symlook_default(const char *name, unsigned long hash,
2072 const Obj_Entry *refobj, const Obj_Entry **defobj_out, bool in_plt)
2076 const Elf_Sym *symp;
2077 const Obj_Entry *obj;
2078 const Obj_Entry *defobj;
2079 const Objlist_Entry *elm;
2082 donelist_init(&donelist);
2084 /* Look first in the referencing object if linked symbolically. */
2085 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
2086 symp = symlook_obj(name, hash, refobj, in_plt);
2093 /* Search all objects loaded at program start up. */
2094 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2095 symp = symlook_list(name, hash, &list_main, &obj, in_plt, &donelist);
2097 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2103 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
2104 STAILQ_FOREACH(elm, &list_global, link) {
2105 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2107 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt,
2110 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2116 /* Search all dlopened DAGs containing the referencing object. */
2117 STAILQ_FOREACH(elm, &refobj->dldags, link) {
2118 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2120 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt,
2123 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2130 * Search the dynamic linker itself, and possibly resolve the
2131 * symbol from there. This is how the application links to
2132 * dynamic linker services such as dlopen. Only the values listed
2133 * in the "exports" array can be resolved from the dynamic linker.
2135 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2136 symp = symlook_obj(name, hash, &obj_rtld, in_plt);
2137 if (symp != NULL && is_exported(symp)) {
2144 *defobj_out = defobj;
2148 static const Elf_Sym *
2149 symlook_list(const char *name, unsigned long hash, Objlist *objlist,
2150 const Obj_Entry **defobj_out, bool in_plt, DoneList *dlp)
2152 const Elf_Sym *symp;
2154 const Obj_Entry *defobj;
2155 const Objlist_Entry *elm;
2159 STAILQ_FOREACH(elm, objlist, link) {
2160 if (donelist_check(dlp, elm->obj))
2162 if ((symp = symlook_obj(name, hash, elm->obj, in_plt)) != NULL) {
2163 if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
2166 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2172 *defobj_out = defobj;
2177 * Search the symbol table of a single shared object for a symbol of
2178 * the given name. Returns a pointer to the symbol, or NULL if no
2179 * definition was found.
2181 * The symbol's hash value is passed in for efficiency reasons; that
2182 * eliminates many recomputations of the hash value.
2185 symlook_obj(const char *name, unsigned long hash, const Obj_Entry *obj,
2188 if (obj->buckets != NULL) {
2189 unsigned long symnum = obj->buckets[hash % obj->nbuckets];
2191 while (symnum != STN_UNDEF) {
2192 const Elf_Sym *symp;
2195 if (symnum >= obj->nchains)
2196 return NULL; /* Bad object */
2197 symp = obj->symtab + symnum;
2198 strp = obj->strtab + symp->st_name;
2200 if (name[0] == strp[0] && strcmp(name, strp) == 0)
2201 return symp->st_shndx != SHN_UNDEF ||
2202 (!in_plt && symp->st_value != 0 &&
2203 ELF_ST_TYPE(symp->st_info) == STT_FUNC) ? symp : NULL;
2205 symnum = obj->chains[symnum];
2212 trace_loaded_objects(Obj_Entry *obj)
2214 char *fmt1, *fmt2, *fmt, *main_local;
2217 if ((main_local = getenv("LD_TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
2220 if ((fmt1 = getenv("LD_TRACE_LOADED_OBJECTS_FMT1")) == NULL)
2221 fmt1 = "\t%o => %p (%x)\n";
2223 if ((fmt2 = getenv("LD_TRACE_LOADED_OBJECTS_FMT2")) == NULL)
2224 fmt2 = "\t%o (%x)\n";
2226 for (; obj; obj = obj->next) {
2227 Needed_Entry *needed;
2231 for (needed = obj->needed; needed; needed = needed->next) {
2232 if (needed->obj != NULL) {
2233 if (needed->obj->traced)
2235 needed->obj->traced = true;
2236 path = needed->obj->path;
2240 name = (char *)obj->strtab + needed->name;
2241 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
2243 fmt = is_lib ? fmt1 : fmt2;
2244 while ((c = *fmt++) != '\0') {
2270 printf("%s", main_local);
2273 printf("%s", obj_main->path);
2280 printf("%d", sodp->sod_major);
2283 printf("%d", sodp->sod_minor);
2290 printf("%p", needed->obj ? needed->obj->mapbase : 0);
2302 * Unload a dlopened object and its dependencies from memory and from
2303 * our data structures. It is assumed that the DAG rooted in the
2304 * object has already been unreferenced, and that the object has a
2305 * reference count of 0.
2308 unload_object(Obj_Entry *root)
2313 assert(root->refcount == 0);
2316 * Pass over the DAG removing unreferenced objects from
2317 * appropriate lists.
2319 unlink_object(root);
2321 /* Unmap all objects that are no longer referenced. */
2322 linkp = &obj_list->next;
2323 while ((obj = *linkp) != NULL) {
2324 if (obj->refcount == 0) {
2325 dbg("unloading \"%s\"", obj->path);
2326 munmap(obj->mapbase, obj->mapsize);
2327 linkmap_delete(obj);
2338 unlink_object(Obj_Entry *root)
2340 const Needed_Entry *needed;
2343 if (root->refcount == 0) {
2344 /* Remove the object from the RTLD_GLOBAL list. */
2345 objlist_remove(&list_global, root);
2347 /* Remove the object from all objects' DAG lists. */
2348 STAILQ_FOREACH(elm, &root->dagmembers , link)
2349 objlist_remove(&elm->obj->dldags, root);
2352 for (needed = root->needed; needed != NULL; needed = needed->next)
2353 if (needed->obj != NULL)
2354 unlink_object(needed->obj);
2358 unref_dag(Obj_Entry *root)
2360 const Needed_Entry *needed;
2362 if (root->refcount == 0)
2365 if (root->refcount == 0)
2366 for (needed = root->needed; needed != NULL; needed = needed->next)
2367 if (needed->obj != NULL)
2368 unref_dag(needed->obj);