2 * Copyright 1996, 1997, 1998, 1999, 2000 John D. Polstra.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 * Dynamic linker for ELF.
31 * John Polstra <jdp@polstra.com>.
35 #error "GCC is needed to compile this file"
38 #include <sys/param.h>
55 #define END_SYM "_end"
56 #define PATH_RTLD "/usr/libexec/ld-elf.so.1"
59 typedef void (*func_ptr_type)();
62 * This structure provides a reentrant way to keep a list of objects and
63 * check which ones have already been processed in some way.
65 typedef struct Struct_DoneList {
66 const Obj_Entry **objs; /* Array of object pointers */
67 unsigned int num_alloc; /* Allocated size of the array */
68 unsigned int num_used; /* Number of array slots used */
72 * Function declarations.
74 static const char *basename(const char *);
75 static void die(void);
76 static void digest_dynamic(Obj_Entry *, int);
77 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
78 static Obj_Entry *dlcheck(void *);
79 static bool donelist_check(DoneList *, const Obj_Entry *);
80 static void errmsg_restore(char *);
81 static char *errmsg_save(void);
82 static char *find_library(const char *, const Obj_Entry *);
83 static const char *gethints(void);
84 static void init_dag(Obj_Entry *);
85 static void init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *);
86 static void init_rtld(caddr_t);
87 static void initlist_add_neededs(Needed_Entry *needed, Objlist *list);
88 static void initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail,
90 static bool is_exported(const Elf_Sym *);
91 static void linkmap_add(Obj_Entry *);
92 static void linkmap_delete(Obj_Entry *);
93 static int load_needed_objects(Obj_Entry *);
94 static int load_preload_objects(void);
95 static Obj_Entry *load_object(char *);
96 static void lock_check(void);
97 static Obj_Entry *obj_from_addr(const void *);
98 static void objlist_call_fini(Objlist *);
99 static void objlist_call_init(Objlist *);
100 static void objlist_clear(Objlist *);
101 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
102 static void objlist_init(Objlist *);
103 static void objlist_push_head(Objlist *, Obj_Entry *);
104 static void objlist_push_tail(Objlist *, Obj_Entry *);
105 static void objlist_remove(Objlist *, Obj_Entry *);
106 static void objlist_remove_unref(Objlist *);
107 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *);
108 static void rtld_exit(void);
109 static char *search_library_path(const char *, const char *);
110 static const void **get_program_var_addr(const char *name);
111 static void set_program_var(const char *, const void *);
112 static const Elf_Sym *symlook_default(const char *, unsigned long hash,
113 const Obj_Entry *refobj, const Obj_Entry **defobj_out, bool in_plt);
114 static const Elf_Sym *symlook_list(const char *, unsigned long,
115 Objlist *, const Obj_Entry **, bool in_plt, DoneList *);
116 static void trace_loaded_objects(Obj_Entry *obj);
117 static void unload_object(Obj_Entry *);
118 static void unref_dag(Obj_Entry *);
120 void r_debug_state(struct r_debug*, struct link_map*);
121 void xprintf(const char *, ...) __printflike(1, 2);
126 static char *error_message; /* Message for dlerror(), or NULL */
127 struct r_debug r_debug; /* for GDB; */
128 static bool trust; /* False for setuid and setgid programs */
129 static char *ld_bind_now; /* Environment variable for immediate binding */
130 static char *ld_debug; /* Environment variable for debugging */
131 static char *ld_library_path; /* Environment variable for search path */
132 static char *ld_preload; /* Environment variable for libraries to
134 static char *ld_tracing; /* Called from ldd to print libs */
135 static Obj_Entry *obj_list; /* Head of linked list of shared objects */
136 static Obj_Entry **obj_tail; /* Link field of last object in list */
137 static Obj_Entry *obj_main; /* The main program shared object */
138 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
139 static unsigned int obj_count; /* Number of objects in obj_list */
141 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
142 STAILQ_HEAD_INITIALIZER(list_global);
143 static Objlist list_main = /* Objects loaded at program startup */
144 STAILQ_HEAD_INITIALIZER(list_main);
145 static Objlist list_fini = /* Objects needing fini() calls */
146 STAILQ_HEAD_INITIALIZER(list_fini);
148 static LockInfo lockinfo;
150 static Elf_Sym sym_zero; /* For resolving undefined weak refs. */
152 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
154 extern Elf_Dyn _DYNAMIC;
155 #pragma weak _DYNAMIC
158 * These are the functions the dynamic linker exports to application
159 * programs. They are the only symbols the dynamic linker is willing
160 * to export from itself.
162 static func_ptr_type exports[] = {
163 (func_ptr_type) &_rtld_error,
164 (func_ptr_type) &dlclose,
165 (func_ptr_type) &dlerror,
166 (func_ptr_type) &dlopen,
167 (func_ptr_type) &dlsym,
168 (func_ptr_type) &dladdr,
169 (func_ptr_type) &dllockinit,
174 * Global declarations normally provided by crt1. The dynamic linker is
175 * not built with crt1, so we have to provide them ourselves.
181 * Fill in a DoneList with an allocation large enough to hold all of
182 * the currently-loaded objects. Keep this as a macro since it calls
183 * alloca and we want that to occur within the scope of the caller.
185 #define donelist_init(dlp) \
186 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
187 assert((dlp)->objs != NULL), \
188 (dlp)->num_alloc = obj_count, \
194 lockinfo.rlock_acquire(lockinfo.thelock);
195 atomic_incr_int(&lockinfo.rcount);
202 lockinfo.wlock_acquire(lockinfo.thelock);
203 atomic_incr_int(&lockinfo.wcount);
210 atomic_decr_int(&lockinfo.rcount);
211 lockinfo.rlock_release(lockinfo.thelock);
217 atomic_decr_int(&lockinfo.wcount);
218 lockinfo.wlock_release(lockinfo.thelock);
222 * Main entry point for dynamic linking. The first argument is the
223 * stack pointer. The stack is expected to be laid out as described
224 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
225 * Specifically, the stack pointer points to a word containing
226 * ARGC. Following that in the stack is a null-terminated sequence
227 * of pointers to argument strings. Then comes a null-terminated
228 * sequence of pointers to environment strings. Finally, there is a
229 * sequence of "auxiliary vector" entries.
231 * The second argument points to a place to store the dynamic linker's
232 * exit procedure pointer and the third to a place to store the main
235 * The return value is the main program's entry point.
238 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
240 Elf_Auxinfo *aux_info[AT_COUNT];
249 Obj_Entry **preload_tail;
253 * On entry, the dynamic linker itself has not been relocated yet.
254 * Be very careful not to reference any global data until after
255 * init_rtld has returned. It is OK to reference file-scope statics
256 * and string constants, and to call static and global functions.
259 /* Find the auxiliary vector on the stack. */
262 sp += argc + 1; /* Skip over arguments and NULL terminator */
264 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
266 aux = (Elf_Auxinfo *) sp;
268 /* Digest the auxiliary vector. */
269 for (i = 0; i < AT_COUNT; i++)
271 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
272 if (auxp->a_type < AT_COUNT)
273 aux_info[auxp->a_type] = auxp;
276 /* Initialize and relocate ourselves. */
277 assert(aux_info[AT_BASE] != NULL);
278 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
280 __progname = obj_rtld.path;
281 argv0 = argv[0] != NULL ? argv[0] : "(null)";
284 trust = geteuid() == getuid() && getegid() == getgid();
286 ld_bind_now = getenv("LD_BIND_NOW");
288 ld_debug = getenv("LD_DEBUG");
289 ld_library_path = getenv("LD_LIBRARY_PATH");
290 ld_preload = getenv("LD_PRELOAD");
292 ld_tracing = getenv("LD_TRACE_LOADED_OBJECTS");
294 if (ld_debug != NULL && *ld_debug != '\0')
296 dbg("%s is initialized, base address = %p", __progname,
297 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
298 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
299 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
302 * Load the main program, or process its program header if it is
305 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
306 int fd = aux_info[AT_EXECFD]->a_un.a_val;
307 dbg("loading main program");
308 obj_main = map_object(fd, argv0, NULL);
310 if (obj_main == NULL)
312 } else { /* Main program already loaded. */
313 const Elf_Phdr *phdr;
317 dbg("processing main program's program header");
318 assert(aux_info[AT_PHDR] != NULL);
319 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
320 assert(aux_info[AT_PHNUM] != NULL);
321 phnum = aux_info[AT_PHNUM]->a_un.a_val;
322 assert(aux_info[AT_PHENT] != NULL);
323 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
324 assert(aux_info[AT_ENTRY] != NULL);
325 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
326 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
330 obj_main->path = xstrdup(argv0);
331 obj_main->mainprog = true;
334 * Get the actual dynamic linker pathname from the executable if
335 * possible. (It should always be possible.) That ensures that
336 * gdb will find the right dynamic linker even if a non-standard
339 if (obj_main->interp != NULL &&
340 strcmp(obj_main->interp, obj_rtld.path) != 0) {
342 obj_rtld.path = xstrdup(obj_main->interp);
345 digest_dynamic(obj_main, 0);
347 linkmap_add(obj_main);
348 linkmap_add(&obj_rtld);
350 /* Link the main program into the list of objects. */
351 *obj_tail = obj_main;
352 obj_tail = &obj_main->next;
354 obj_main->refcount++;
355 /* Make sure we don't call the main program's init and fini functions. */
356 obj_main->init = obj_main->fini = NULL;
358 /* Initialize a fake symbol for resolving undefined weak references. */
359 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
360 sym_zero.st_shndx = SHN_UNDEF;
362 dbg("loading LD_PRELOAD libraries");
363 if (load_preload_objects() == -1)
365 preload_tail = obj_tail;
367 dbg("loading needed objects");
368 if (load_needed_objects(obj_main) == -1)
371 /* Make a list of all objects loaded at startup. */
372 for (obj = obj_list; obj != NULL; obj = obj->next)
373 objlist_push_tail(&list_main, obj);
375 if (ld_tracing) { /* We're done */
376 trace_loaded_objects(obj_main);
380 if (relocate_objects(obj_main,
381 ld_bind_now != NULL && *ld_bind_now != '\0', &obj_rtld) == -1)
384 dbg("doing copy relocations");
385 if (do_copy_relocations(obj_main) == -1)
388 dbg("initializing key program variables");
389 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
390 set_program_var("environ", env);
392 dbg("initializing thread locks");
393 lockdflt_init(&lockinfo);
394 lockinfo.thelock = lockinfo.lock_create(lockinfo.context);
396 /* Make a list of init functions to call. */
397 objlist_init(&initlist);
398 initlist_add_objects(obj_list, preload_tail, &initlist);
400 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
402 objlist_call_init(&initlist);
404 objlist_clear(&initlist);
407 dbg("transferring control to program entry point = %p", obj_main->entry);
409 /* Return the exit procedure and the program entry point. */
410 *exit_proc = rtld_exit;
412 return (func_ptr_type) obj_main->entry;
416 _rtld_bind(Obj_Entry *obj, Elf_Word reloff)
420 const Obj_Entry *defobj;
426 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
428 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
430 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
431 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL);
435 target = (Elf_Addr)(defobj->relocbase + def->st_value);
437 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
438 defobj->strtab + def->st_name, basename(obj->path),
439 (void *)target, basename(defobj->path));
442 * Write the new contents for the jmpslot. Note that depending on
443 * architecture, the value which we need to return back to the
444 * lazy binding trampoline may or may not be the target
445 * address. The value returned from reloc_jmpslot() is the value
446 * that the trampoline needs.
448 target = reloc_jmpslot(where, target, defobj);
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, int early)
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_Hashelt *hashtab = (const Elf_Hashelt *)
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 = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
633 obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
637 /* XXX - not implemented yet */
639 dbg("Filling in DT_DEBUG entry");
640 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
645 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
654 if (plttype == DT_RELA) {
655 obj->pltrela = (const Elf_Rela *) obj->pltrel;
657 obj->pltrelasize = obj->pltrelsize;
661 if (dyn_rpath != NULL)
662 obj->rpath = obj->strtab + dyn_rpath->d_un.d_val;
666 * Process a shared object's program header. This is used only for the
667 * main program, when the kernel has already loaded the main program
668 * into memory before calling the dynamic linker. It creates and
669 * returns an Obj_Entry structure.
672 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
675 const Elf_Phdr *phlimit = phdr + phnum;
680 for (ph = phdr; ph < phlimit; ph++) {
681 switch (ph->p_type) {
684 if ((const Elf_Phdr *)ph->p_vaddr != phdr) {
685 _rtld_error("%s: invalid PT_PHDR", path);
688 obj->phdr = (const Elf_Phdr *) ph->p_vaddr;
689 obj->phsize = ph->p_memsz;
693 obj->interp = (const char *) ph->p_vaddr;
698 _rtld_error("%s: too many PT_LOAD segments", path);
701 if (nsegs == 0) { /* First load segment */
702 obj->vaddrbase = trunc_page(ph->p_vaddr);
703 obj->mapbase = (caddr_t) obj->vaddrbase;
704 obj->relocbase = obj->mapbase - obj->vaddrbase;
705 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
707 } else { /* Last load segment */
708 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
715 obj->dynamic = (const Elf_Dyn *) ph->p_vaddr;
720 _rtld_error("%s: too few PT_LOAD segments", path);
729 dlcheck(void *handle)
733 for (obj = obj_list; obj != NULL; obj = obj->next)
734 if (obj == (Obj_Entry *) handle)
737 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
738 _rtld_error("Invalid shared object handle %p", handle);
745 * If the given object is already in the donelist, return true. Otherwise
746 * add the object to the list and return false.
749 donelist_check(DoneList *dlp, const Obj_Entry *obj)
753 for (i = 0; i < dlp->num_used; i++)
754 if (dlp->objs[i] == obj)
757 * Our donelist allocation should always be sufficient. But if
758 * our threads locking isn't working properly, more shared objects
759 * could have been loaded since we allocated the list. That should
760 * never happen, but we'll handle it properly just in case it does.
762 if (dlp->num_used < dlp->num_alloc)
763 dlp->objs[dlp->num_used++] = obj;
768 * Hash function for symbol table lookup. Don't even think about changing
769 * this. It is specified by the System V ABI.
772 elf_hash(const char *name)
774 const unsigned char *p = (const unsigned char *) name;
780 if ((g = h & 0xf0000000) != 0)
788 * Find the library with the given name, and return its full pathname.
789 * The returned string is dynamically allocated. Generates an error
790 * message and returns NULL if the library cannot be found.
792 * If the second argument is non-NULL, then it refers to an already-
793 * loaded shared object, whose library search path will be searched.
795 * The search order is:
796 * rpath in the referencing file
802 find_library(const char *name, const Obj_Entry *refobj)
806 if (strchr(name, '/') != NULL) { /* Hard coded pathname */
807 if (name[0] != '/' && !trust) {
808 _rtld_error("Absolute pathname required for shared object \"%s\"",
812 return xstrdup(name);
815 dbg(" Searching for \"%s\"", name);
817 if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
819 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
820 (pathname = search_library_path(name, gethints())) != NULL ||
821 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
824 _rtld_error("Shared object \"%s\" not found", name);
829 * Given a symbol number in a referencing object, find the corresponding
830 * definition of the symbol. Returns a pointer to the symbol, or NULL if
831 * no definition was found. Returns a pointer to the Obj_Entry of the
832 * defining object via the reference parameter DEFOBJ_OUT.
835 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
836 const Obj_Entry **defobj_out, bool in_plt, SymCache *cache)
840 const Obj_Entry *defobj;
845 * If we have already found this symbol, get the information from
848 if (symnum >= refobj->nchains)
849 return NULL; /* Bad object */
850 if (cache != NULL && cache[symnum].sym != NULL) {
851 *defobj_out = cache[symnum].obj;
852 return cache[symnum].sym;
855 ref = refobj->symtab + symnum;
856 name = refobj->strtab + ref->st_name;
860 * We don't have to do a full scale lookup if the symbol is local.
861 * We know it will bind to the instance in this load module; to
862 * which we already have a pointer (ie ref). By not doing a lookup,
863 * we not only improve performance, but it also avoids unresolvable
864 * symbols when local symbols are not in the hash table. This has
865 * been seen with the ia64 toolchain.
867 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
868 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
869 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
872 hash = elf_hash(name);
873 def = symlook_default(name, hash, refobj, &defobj, in_plt);
880 * If we found no definition and the reference is weak, treat the
881 * symbol as having the value zero.
883 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
889 *defobj_out = defobj;
890 /* Record the information in the cache to avoid subsequent lookups. */
892 cache[symnum].sym = def;
893 cache[symnum].obj = defobj;
896 if (refobj != &obj_rtld)
897 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
903 * Return the search path from the ldconfig hints file, reading it if
904 * necessary. Returns NULL if there are problems with the hints file,
905 * or if the search path there is empty.
914 struct elfhints_hdr hdr;
917 /* Keep from trying again in case the hints file is bad. */
920 if ((fd = open(_PATH_ELF_HINTS, O_RDONLY)) == -1)
922 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
923 hdr.magic != ELFHINTS_MAGIC ||
928 p = xmalloc(hdr.dirlistlen + 1);
929 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
930 read(fd, p, hdr.dirlistlen + 1) != hdr.dirlistlen + 1) {
938 return hints[0] != '\0' ? hints : NULL;
942 init_dag(Obj_Entry *root)
946 donelist_init(&donelist);
947 init_dag1(root, root, &donelist);
951 init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *dlp)
953 const Needed_Entry *needed;
955 if (donelist_check(dlp, obj))
957 objlist_push_tail(&obj->dldags, root);
958 objlist_push_tail(&root->dagmembers, obj);
959 for (needed = obj->needed; needed != NULL; needed = needed->next)
960 if (needed->obj != NULL)
961 init_dag1(root, needed->obj, dlp);
965 * Initialize the dynamic linker. The argument is the address at which
966 * the dynamic linker has been mapped into memory. The primary task of
967 * this function is to relocate the dynamic linker.
970 init_rtld(caddr_t mapbase)
972 Obj_Entry objtmp; /* Temporary rtld object */
975 * Conjure up an Obj_Entry structure for the dynamic linker.
977 * The "path" member can't be initialized yet because string constatns
978 * cannot yet be acessed. Below we will set it correctly.
982 objtmp.mapbase = mapbase;
984 objtmp.relocbase = mapbase;
986 if (&_DYNAMIC != 0) {
987 objtmp.dynamic = rtld_dynamic(&objtmp);
988 digest_dynamic(&objtmp, 1);
989 assert(objtmp.needed == NULL);
990 assert(!objtmp.textrel);
993 * Temporarily put the dynamic linker entry into the object list, so
994 * that symbols can be found.
997 relocate_objects(&objtmp, true, &objtmp);
1000 /* Initialize the object list. */
1001 obj_tail = &obj_list;
1003 /* Now that non-local variables can be accesses, copy out obj_rtld. */
1004 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1006 /* Replace the path with a dynamically allocated copy. */
1007 obj_rtld.path = xstrdup(PATH_RTLD);
1009 r_debug.r_brk = r_debug_state;
1010 r_debug.r_state = RT_CONSISTENT;
1014 * Add the init functions from a needed object list (and its recursive
1015 * needed objects) to "list". This is not used directly; it is a helper
1016 * function for initlist_add_objects(). The write lock must be held
1017 * when this function is called.
1020 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1022 /* Recursively process the successor needed objects. */
1023 if (needed->next != NULL)
1024 initlist_add_neededs(needed->next, list);
1026 /* Process the current needed object. */
1027 if (needed->obj != NULL)
1028 initlist_add_objects(needed->obj, &needed->obj->next, list);
1032 * Scan all of the DAGs rooted in the range of objects from "obj" to
1033 * "tail" and add their init functions to "list". This recurses over
1034 * the DAGs and ensure the proper init ordering such that each object's
1035 * needed libraries are initialized before the object itself. At the
1036 * same time, this function adds the objects to the global finalization
1037 * list "list_fini" in the opposite order. The write lock must be
1038 * held when this function is called.
1041 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1045 obj->init_done = true;
1047 /* Recursively process the successor objects. */
1048 if (&obj->next != tail)
1049 initlist_add_objects(obj->next, tail, list);
1051 /* Recursively process the needed objects. */
1052 if (obj->needed != NULL)
1053 initlist_add_neededs(obj->needed, list);
1055 /* Add the object to the init list. */
1056 if (obj->init != NULL)
1057 objlist_push_tail(list, obj);
1059 /* Add the object to the global fini list in the reverse order. */
1060 if (obj->fini != NULL)
1061 objlist_push_head(&list_fini, obj);
1065 #define FPTR_TARGET(f) ((Elf_Addr) (f))
1069 is_exported(const Elf_Sym *def)
1072 const func_ptr_type *p;
1074 value = (Elf_Addr)(obj_rtld.relocbase + def->st_value);
1075 for (p = exports; *p != NULL; p++)
1076 if (FPTR_TARGET(*p) == value)
1082 * Given a shared object, traverse its list of needed objects, and load
1083 * each of them. Returns 0 on success. Generates an error message and
1084 * returns -1 on failure.
1087 load_needed_objects(Obj_Entry *first)
1091 for (obj = first; obj != NULL; obj = obj->next) {
1092 Needed_Entry *needed;
1094 for (needed = obj->needed; needed != NULL; needed = needed->next) {
1095 const char *name = obj->strtab + needed->name;
1096 char *path = find_library(name, obj);
1099 if (path == NULL && !ld_tracing)
1103 needed->obj = load_object(path);
1104 if (needed->obj == NULL && !ld_tracing)
1105 return -1; /* XXX - cleanup */
1114 load_preload_objects(void)
1116 char *p = ld_preload;
1117 static const char delim[] = " \t:;";
1122 p += strspn(p, delim);
1123 while (*p != '\0') {
1124 size_t len = strcspn(p, delim);
1130 if ((path = find_library(p, NULL)) == NULL)
1132 if (load_object(path) == NULL)
1133 return -1; /* XXX - cleanup */
1136 p += strspn(p, delim);
1142 * Load a shared object into memory, if it is not already loaded. The
1143 * argument must be a string allocated on the heap. This function assumes
1144 * responsibility for freeing it when necessary.
1146 * Returns a pointer to the Obj_Entry for the object. Returns NULL
1150 load_object(char *path)
1156 for (obj = obj_list->next; obj != NULL; obj = obj->next)
1157 if (strcmp(obj->path, path) == 0)
1161 * If we didn't find a match by pathname, open the file and check
1162 * again by device and inode. This avoids false mismatches caused
1163 * by multiple links or ".." in pathnames.
1165 * To avoid a race, we open the file and use fstat() rather than
1169 if ((fd = open(path, O_RDONLY)) == -1) {
1170 _rtld_error("Cannot open \"%s\"", path);
1173 if (fstat(fd, &sb) == -1) {
1174 _rtld_error("Cannot fstat \"%s\"", path);
1178 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
1179 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev) {
1186 if (obj == NULL) { /* First use of this object, so we must map it in */
1187 dbg("loading \"%s\"", path);
1188 obj = map_object(fd, path, &sb);
1196 digest_dynamic(obj, 0);
1199 obj_tail = &obj->next;
1201 linkmap_add(obj); /* for GDB */
1203 dbg(" %p .. %p: %s", obj->mapbase,
1204 obj->mapbase + obj->mapsize - 1, obj->path);
1206 dbg(" WARNING: %s has impure text", obj->path);
1215 * Check for locking violations and die if one is found.
1222 rcount = lockinfo.rcount;
1223 wcount = lockinfo.wcount;
1224 assert(rcount >= 0);
1225 assert(wcount >= 0);
1226 if (wcount > 1 || (wcount != 0 && rcount != 0)) {
1227 _rtld_error("Application locking error: %d readers and %d writers"
1228 " in dynamic linker. See DLLOCKINIT(3) in manual pages.",
1235 obj_from_addr(const void *addr)
1237 unsigned long endhash;
1240 endhash = elf_hash(END_SYM);
1241 for (obj = obj_list; obj != NULL; obj = obj->next) {
1242 const Elf_Sym *endsym;
1244 if (addr < (void *) obj->mapbase)
1246 if ((endsym = symlook_obj(END_SYM, endhash, obj, true)) == NULL)
1247 continue; /* No "end" symbol?! */
1248 if (addr < (void *) (obj->relocbase + endsym->st_value))
1255 * Call the finalization functions for each of the objects in "list"
1256 * which are unreferenced. All of the objects are expected to have
1257 * non-NULL fini functions.
1260 objlist_call_fini(Objlist *list)
1266 * Preserve the current error message since a fini function might
1267 * call into the dynamic linker and overwrite it.
1269 saved_msg = errmsg_save();
1270 STAILQ_FOREACH(elm, list, link) {
1271 if (elm->obj->refcount == 0) {
1272 dbg("calling fini function for %s at %p", elm->obj->path,
1273 (void *)elm->obj->fini);
1274 call_initfini_pointer(elm->obj, elm->obj->fini);
1277 errmsg_restore(saved_msg);
1281 * Call the initialization functions for each of the objects in
1282 * "list". All of the objects are expected to have non-NULL init
1286 objlist_call_init(Objlist *list)
1292 * Preserve the current error message since an init function might
1293 * call into the dynamic linker and overwrite it.
1295 saved_msg = errmsg_save();
1296 STAILQ_FOREACH(elm, list, link) {
1297 dbg("calling init function for %s at %p", elm->obj->path,
1298 (void *)elm->obj->init);
1299 call_initfini_pointer(elm->obj, elm->obj->init);
1301 errmsg_restore(saved_msg);
1305 objlist_clear(Objlist *list)
1309 while (!STAILQ_EMPTY(list)) {
1310 elm = STAILQ_FIRST(list);
1311 STAILQ_REMOVE_HEAD(list, link);
1316 static Objlist_Entry *
1317 objlist_find(Objlist *list, const Obj_Entry *obj)
1321 STAILQ_FOREACH(elm, list, link)
1322 if (elm->obj == obj)
1328 objlist_init(Objlist *list)
1334 objlist_push_head(Objlist *list, Obj_Entry *obj)
1338 elm = NEW(Objlist_Entry);
1340 STAILQ_INSERT_HEAD(list, elm, link);
1344 objlist_push_tail(Objlist *list, Obj_Entry *obj)
1348 elm = NEW(Objlist_Entry);
1350 STAILQ_INSERT_TAIL(list, elm, link);
1354 objlist_remove(Objlist *list, Obj_Entry *obj)
1358 if ((elm = objlist_find(list, obj)) != NULL) {
1359 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1365 * Remove all of the unreferenced objects from "list".
1368 objlist_remove_unref(Objlist *list)
1373 STAILQ_INIT(&newlist);
1374 while (!STAILQ_EMPTY(list)) {
1375 elm = STAILQ_FIRST(list);
1376 STAILQ_REMOVE_HEAD(list, link);
1377 if (elm->obj->refcount == 0)
1380 STAILQ_INSERT_TAIL(&newlist, elm, link);
1386 * Relocate newly-loaded shared objects. The argument is a pointer to
1387 * the Obj_Entry for the first such object. All objects from the first
1388 * to the end of the list of objects are relocated. Returns 0 on success,
1392 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj)
1396 for (obj = first; obj != NULL; obj = obj->next) {
1398 dbg("relocating \"%s\"", obj->path);
1399 if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
1400 obj->symtab == NULL || obj->strtab == NULL) {
1401 _rtld_error("%s: Shared object has no run-time symbol table",
1407 /* There are relocations to the write-protected text segment. */
1408 if (mprotect(obj->mapbase, obj->textsize,
1409 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
1410 _rtld_error("%s: Cannot write-enable text segment: %s",
1411 obj->path, strerror(errno));
1416 /* Process the non-PLT relocations. */
1417 if (reloc_non_plt(obj, rtldobj))
1420 if (obj->textrel) { /* Re-protected the text segment. */
1421 if (mprotect(obj->mapbase, obj->textsize,
1422 PROT_READ|PROT_EXEC) == -1) {
1423 _rtld_error("%s: Cannot write-protect text segment: %s",
1424 obj->path, strerror(errno));
1429 /* Process the PLT relocations. */
1430 if (reloc_plt(obj) == -1)
1432 /* Relocate the jump slots if we are doing immediate binding. */
1434 if (reloc_jmpslots(obj) == -1)
1439 * Set up the magic number and version in the Obj_Entry. These
1440 * were checked in the crt1.o from the original ElfKit, so we
1441 * set them for backward compatibility.
1443 obj->magic = RTLD_MAGIC;
1444 obj->version = RTLD_VERSION;
1446 /* Set the special PLT or GOT entries. */
1454 * Cleanup procedure. It will be called (by the atexit mechanism) just
1455 * before the process exits.
1464 /* Clear all the reference counts so the fini functions will be called. */
1465 for (obj = obj_list; obj != NULL; obj = obj->next)
1468 objlist_call_fini(&list_fini);
1469 /* No need to remove the items from the list, since we are exiting. */
1473 search_library_path(const char *name, const char *path)
1475 size_t namelen = strlen(name);
1476 const char *p = path;
1481 p += strspn(p, ":;");
1482 while (*p != '\0') {
1483 size_t len = strcspn(p, ":;");
1485 if (*p == '/' || trust) {
1487 const char *dir = p;
1488 size_t dirlen = len;
1490 pathname = xmalloc(dirlen + 1 + namelen + 1);
1491 strncpy(pathname, dir, dirlen);
1492 pathname[dirlen] = '/';
1493 strcpy(pathname + dirlen + 1, name);
1495 dbg(" Trying \"%s\"", pathname);
1496 if (access(pathname, F_OK) == 0) /* We found it */
1502 p += strspn(p, ":;");
1509 dlclose(void *handle)
1514 root = dlcheck(handle);
1520 /* Unreference the object and its dependencies. */
1521 root->dl_refcount--;
1524 if (root->refcount == 0) {
1526 * The object is no longer referenced, so we must unload it.
1527 * First, call the fini functions with no locks held.
1530 objlist_call_fini(&list_fini);
1532 objlist_remove_unref(&list_fini);
1534 /* Finish cleaning up the newly-unreferenced objects. */
1535 GDB_STATE(RT_DELETE,&root->linkmap);
1536 unload_object(root);
1537 GDB_STATE(RT_CONSISTENT,NULL);
1546 char *msg = error_message;
1547 error_message = NULL;
1552 * This function is deprecated and has no effect.
1555 dllockinit(void *context,
1556 void *(*lock_create)(void *context),
1557 void (*rlock_acquire)(void *lock),
1558 void (*wlock_acquire)(void *lock),
1559 void (*lock_release)(void *lock),
1560 void (*lock_destroy)(void *lock),
1561 void (*context_destroy)(void *context))
1563 static void *cur_context;
1564 static void (*cur_context_destroy)(void *);
1566 /* Just destroy the context from the previous call, if necessary. */
1567 if (cur_context_destroy != NULL)
1568 cur_context_destroy(cur_context);
1569 cur_context = context;
1570 cur_context_destroy = context_destroy;
1574 dlopen(const char *name, int mode)
1576 Obj_Entry **old_obj_tail;
1581 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
1582 if (ld_tracing != NULL)
1583 environ = (char **)*get_program_var_addr("environ");
1585 objlist_init(&initlist);
1588 GDB_STATE(RT_ADD,NULL);
1590 old_obj_tail = obj_tail;
1596 char *path = find_library(name, obj_main);
1598 obj = load_object(path);
1603 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
1604 objlist_push_tail(&list_global, obj);
1605 mode &= RTLD_MODEMASK;
1606 if (*old_obj_tail != NULL) { /* We loaded something new. */
1607 assert(*old_obj_tail == obj);
1609 result = load_needed_objects(obj);
1610 if (result != -1 && ld_tracing) {
1611 trace_loaded_objects(obj);
1617 (init_dag(obj), relocate_objects(obj, mode == RTLD_NOW,
1618 &obj_rtld)) == -1) {
1621 if (obj->refcount == 0)
1625 /* Make list of init functions to call. */
1626 initlist_add_objects(obj, &obj->next, &initlist);
1631 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
1633 /* Call the init functions with no locks held. */
1635 objlist_call_init(&initlist);
1637 objlist_clear(&initlist);
1643 dlsym(void *handle, const char *name)
1645 const Obj_Entry *obj;
1648 const Obj_Entry *defobj;
1650 hash = elf_hash(name);
1655 if (handle == NULL || handle == RTLD_NEXT || handle == RTLD_DEFAULT) {
1658 retaddr = __builtin_return_address(0); /* __GNUC__ only */
1659 if ((obj = obj_from_addr(retaddr)) == NULL) {
1660 _rtld_error("Cannot determine caller's shared object");
1664 if (handle == NULL) { /* Just the caller's shared object. */
1665 def = symlook_obj(name, hash, obj, true);
1667 } else if (handle == RTLD_NEXT) { /* Objects after caller's */
1668 while ((obj = obj->next) != NULL) {
1669 if ((def = symlook_obj(name, hash, obj, true)) != NULL) {
1675 assert(handle == RTLD_DEFAULT);
1676 def = symlook_default(name, hash, obj, &defobj, true);
1679 if ((obj = dlcheck(handle)) == NULL) {
1684 if (obj->mainprog) {
1687 /* Search main program and all libraries loaded by it. */
1688 donelist_init(&donelist);
1689 def = symlook_list(name, hash, &list_main, &defobj, true,
1693 * XXX - This isn't correct. The search should include the whole
1694 * DAG rooted at the given object.
1696 def = symlook_obj(name, hash, obj, true);
1705 * The value required by the caller is derived from the value
1706 * of the symbol. For the ia64 architecture, we need to
1707 * construct a function descriptor which the caller can use to
1708 * call the function with the right 'gp' value. For other
1709 * architectures and for non-functions, the value is simply
1710 * the relocated value of the symbol.
1712 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
1713 return make_function_pointer(def, defobj);
1715 return defobj->relocbase + def->st_value;
1718 _rtld_error("Undefined symbol \"%s\"", name);
1724 dladdr(const void *addr, Dl_info *info)
1726 const Obj_Entry *obj;
1729 unsigned long symoffset;
1732 obj = obj_from_addr(addr);
1734 _rtld_error("No shared object contains address");
1738 info->dli_fname = obj->path;
1739 info->dli_fbase = obj->mapbase;
1740 info->dli_saddr = (void *)0;
1741 info->dli_sname = NULL;
1744 * Walk the symbol list looking for the symbol whose address is
1745 * closest to the address sent in.
1747 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
1748 def = obj->symtab + symoffset;
1751 * For skip the symbol if st_shndx is either SHN_UNDEF or
1754 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
1758 * If the symbol is greater than the specified address, or if it
1759 * is further away from addr than the current nearest symbol,
1762 symbol_addr = obj->relocbase + def->st_value;
1763 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
1766 /* Update our idea of the nearest symbol. */
1767 info->dli_sname = obj->strtab + def->st_name;
1768 info->dli_saddr = symbol_addr;
1771 if (info->dli_saddr == addr)
1779 linkmap_add(Obj_Entry *obj)
1781 struct link_map *l = &obj->linkmap;
1782 struct link_map *prev;
1784 obj->linkmap.l_name = obj->path;
1785 obj->linkmap.l_addr = obj->mapbase;
1786 obj->linkmap.l_ld = obj->dynamic;
1788 /* GDB needs load offset on MIPS to use the symbols */
1789 obj->linkmap.l_offs = obj->relocbase;
1792 if (r_debug.r_map == NULL) {
1798 * Scan to the end of the list, but not past the entry for the
1799 * dynamic linker, which we want to keep at the very end.
1801 for (prev = r_debug.r_map;
1802 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
1803 prev = prev->l_next)
1806 /* Link in the new entry. */
1808 l->l_next = prev->l_next;
1809 if (l->l_next != NULL)
1810 l->l_next->l_prev = l;
1815 linkmap_delete(Obj_Entry *obj)
1817 struct link_map *l = &obj->linkmap;
1819 if (l->l_prev == NULL) {
1820 if ((r_debug.r_map = l->l_next) != NULL)
1821 l->l_next->l_prev = NULL;
1825 if ((l->l_prev->l_next = l->l_next) != NULL)
1826 l->l_next->l_prev = l->l_prev;
1830 * Function for the debugger to set a breakpoint on to gain control.
1832 * The two parameters allow the debugger to easily find and determine
1833 * what the runtime loader is doing and to whom it is doing it.
1835 * When the loadhook trap is hit (r_debug_state, set at program
1836 * initialization), the arguments can be found on the stack:
1838 * +8 struct link_map *m
1839 * +4 struct r_debug *rd
1843 r_debug_state(struct r_debug* rd, struct link_map *m)
1848 * Get address of the pointer variable in the main program.
1850 static const void **
1851 get_program_var_addr(const char *name)
1853 const Obj_Entry *obj;
1856 hash = elf_hash(name);
1857 for (obj = obj_main; obj != NULL; obj = obj->next) {
1860 if ((def = symlook_obj(name, hash, obj, false)) != NULL) {
1863 addr = (const void **)(obj->relocbase + def->st_value);
1871 * Set a pointer variable in the main program to the given value. This
1872 * is used to set key variables such as "environ" before any of the
1873 * init functions are called.
1876 set_program_var(const char *name, const void *value)
1880 if ((addr = get_program_var_addr(name)) != NULL) {
1881 dbg("\"%s\": *%p <-- %p", name, addr, value);
1887 * Given a symbol name in a referencing object, find the corresponding
1888 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1889 * no definition was found. Returns a pointer to the Obj_Entry of the
1890 * defining object via the reference parameter DEFOBJ_OUT.
1892 static const Elf_Sym *
1893 symlook_default(const char *name, unsigned long hash,
1894 const Obj_Entry *refobj, const Obj_Entry **defobj_out, bool in_plt)
1898 const Elf_Sym *symp;
1899 const Obj_Entry *obj;
1900 const Obj_Entry *defobj;
1901 const Objlist_Entry *elm;
1904 donelist_init(&donelist);
1906 /* Look first in the referencing object if linked symbolically. */
1907 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
1908 symp = symlook_obj(name, hash, refobj, in_plt);
1915 /* Search all objects loaded at program start up. */
1916 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
1917 symp = symlook_list(name, hash, &list_main, &obj, in_plt, &donelist);
1919 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
1925 /* Search all dlopened DAGs containing the referencing object. */
1926 STAILQ_FOREACH(elm, &refobj->dldags, link) {
1927 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
1929 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt,
1932 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
1938 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
1939 STAILQ_FOREACH(elm, &list_global, link) {
1940 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
1942 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt,
1945 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
1952 * Search the dynamic linker itself, and possibly resolve the
1953 * symbol from there. This is how the application links to
1954 * dynamic linker services such as dlopen. Only the values listed
1955 * in the "exports" array can be resolved from the dynamic linker.
1957 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
1958 symp = symlook_obj(name, hash, &obj_rtld, in_plt);
1959 if (symp != NULL && is_exported(symp)) {
1966 *defobj_out = defobj;
1970 static const Elf_Sym *
1971 symlook_list(const char *name, unsigned long hash, Objlist *objlist,
1972 const Obj_Entry **defobj_out, bool in_plt, DoneList *dlp)
1974 const Elf_Sym *symp;
1976 const Obj_Entry *defobj;
1977 const Objlist_Entry *elm;
1981 STAILQ_FOREACH(elm, objlist, link) {
1982 if (donelist_check(dlp, elm->obj))
1984 if ((symp = symlook_obj(name, hash, elm->obj, in_plt)) != NULL) {
1985 if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
1988 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
1994 *defobj_out = defobj;
1999 * Search the symbol table of a single shared object for a symbol of
2000 * the given name. Returns a pointer to the symbol, or NULL if no
2001 * definition was found.
2003 * The symbol's hash value is passed in for efficiency reasons; that
2004 * eliminates many recomputations of the hash value.
2007 symlook_obj(const char *name, unsigned long hash, const Obj_Entry *obj,
2010 if (obj->buckets != NULL) {
2011 unsigned long symnum = obj->buckets[hash % obj->nbuckets];
2013 while (symnum != STN_UNDEF) {
2014 const Elf_Sym *symp;
2017 if (symnum >= obj->nchains)
2018 return NULL; /* Bad object */
2019 symp = obj->symtab + symnum;
2020 strp = obj->strtab + symp->st_name;
2022 if (name[0] == strp[0] && strcmp(name, strp) == 0)
2023 return symp->st_shndx != SHN_UNDEF ||
2024 (!in_plt && symp->st_value != 0 &&
2025 ELF_ST_TYPE(symp->st_info) == STT_FUNC) ? symp : NULL;
2027 symnum = obj->chains[symnum];
2034 trace_loaded_objects(Obj_Entry *obj)
2036 char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
2039 if ((main_local = getenv("LD_TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
2042 if ((fmt1 = getenv("LD_TRACE_LOADED_OBJECTS_FMT1")) == NULL)
2043 fmt1 = "\t%o => %p (%x)\n";
2045 if ((fmt2 = getenv("LD_TRACE_LOADED_OBJECTS_FMT2")) == NULL)
2046 fmt2 = "\t%o (%x)\n";
2048 list_containers = getenv("LD_TRACE_LOADED_OBJECTS_ALL");
2050 for (; obj; obj = obj->next) {
2051 Needed_Entry *needed;
2055 if (list_containers && obj->needed != NULL)
2056 printf("%s:\n", obj->path);
2057 for (needed = obj->needed; needed; needed = needed->next) {
2058 if (needed->obj != NULL) {
2059 if (needed->obj->traced && !list_containers)
2061 needed->obj->traced = true;
2062 path = needed->obj->path;
2066 name = (char *)obj->strtab + needed->name;
2067 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
2069 fmt = is_lib ? fmt1 : fmt2;
2070 while ((c = *fmt++) != '\0') {
2096 printf("%s", main_local);
2099 printf("%s", obj_main->path);
2106 printf("%d", sodp->sod_major);
2109 printf("%d", sodp->sod_minor);
2116 printf("%p", needed->obj ? needed->obj->mapbase : 0);
2128 * Unload a dlopened object and its dependencies from memory and from
2129 * our data structures. It is assumed that the DAG rooted in the
2130 * object has already been unreferenced, and that the object has a
2131 * reference count of 0.
2134 unload_object(Obj_Entry *root)
2140 assert(root->refcount == 0);
2142 /* Remove the DAG from all objects' DAG lists. */
2143 STAILQ_FOREACH(elm, &root->dagmembers , link)
2144 objlist_remove(&elm->obj->dldags, root);
2146 /* Remove the DAG from the RTLD_GLOBAL list. */
2147 objlist_remove(&list_global, root);
2149 /* Unmap all objects that are no longer referenced. */
2150 linkp = &obj_list->next;
2151 while ((obj = *linkp) != NULL) {
2152 if (obj->refcount == 0) {
2153 dbg("unloading \"%s\"", obj->path);
2154 munmap(obj->mapbase, obj->mapsize);
2155 linkmap_delete(obj);
2166 unref_dag(Obj_Entry *root)
2168 const Needed_Entry *needed;
2170 if (root->refcount == 0)
2173 if (root->refcount == 0)
2174 for (needed = root->needed; needed != NULL; needed = needed->next)
2175 if (needed->obj != NULL)
2176 unref_dag(needed->obj);
2180 * Non-mallocing printf, for use by malloc itself.
2181 * XXX - This doesn't belong in this module.
2184 xprintf(const char *fmt, ...)
2190 vsprintf(buf, fmt, ap);
2191 (void)write(STDOUT_FILENO, buf, strlen(buf));