2 * Copyright 1996, 1997, 1998, 1999, 2000 John D. Polstra.
3 * Copyright 2003 Alexander Kabaev <kan@FreeBSD.ORG>.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 * $FreeBSD: src/libexec/rtld-elf/rtld.c,v 1.43.2.15 2003/02/20 20:42:46 kan Exp $
27 * $DragonFly: src/libexec/rtld-elf/rtld.c,v 1.4 2003/12/01 23:50:20 drhodus Exp $
31 * Dynamic linker for ELF.
33 * John Polstra <jdp@polstra.com>.
37 #error "GCC is needed to compile this file"
40 #include <sys/param.h>
57 #define END_SYM "_end"
58 #define PATH_RTLD "/usr/libexec/ld-elf.so.1"
61 typedef void (*func_ptr_type)();
62 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg);
65 * This structure provides a reentrant way to keep a list of objects and
66 * check which ones have already been processed in some way.
68 typedef struct Struct_DoneList {
69 const Obj_Entry **objs; /* Array of object pointers */
70 unsigned int num_alloc; /* Allocated size of the array */
71 unsigned int num_used; /* Number of array slots used */
75 * Function declarations.
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 u_int32_t elf_uniqid(u_int32_t, const void *, size_t);
84 static void errmsg_restore(char *);
85 static char *errmsg_save(void);
86 static void *fill_search_info(const char *, size_t, void *);
87 static char *find_library(const char *, const Obj_Entry *);
88 static const char *gethints(void);
89 static void init_dag(Obj_Entry *);
90 static void init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *);
91 static void init_rtld(caddr_t);
92 static void initlist_add_neededs(Needed_Entry *needed, Objlist *list);
93 static void initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail,
95 static bool is_exported(const Elf_Sym *);
96 static void linkmap_add(Obj_Entry *);
97 static void linkmap_delete(Obj_Entry *);
98 static int load_needed_objects(Obj_Entry *);
99 static int load_preload_objects(void);
100 static Obj_Entry *load_object(char *);
101 static void lock_check(void);
102 static Obj_Entry *obj_from_addr(const void *);
103 static void objlist_call_fini(Objlist *);
104 static void objlist_call_init(Objlist *);
105 static void objlist_clear(Objlist *);
106 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
107 static void objlist_init(Objlist *);
108 static void objlist_push_head(Objlist *, Obj_Entry *);
109 static void objlist_push_tail(Objlist *, Obj_Entry *);
110 static void objlist_remove(Objlist *, Obj_Entry *);
111 static void objlist_remove_unref(Objlist *);
112 static void *path_enumerate(const char *, path_enum_proc, void *);
113 static int relocate_objects(Obj_Entry *, bool);
114 static int rtld_dirname(const char *, char *);
115 static void rtld_exit(void);
116 static char *search_library_path(const char *, const char *);
117 static const void **get_program_var_addr(const char *name);
118 static void set_program_var(const char *, const void *);
119 static const Elf_Sym *symlook_default(const char *, unsigned long hash,
120 const Obj_Entry *refobj, const Obj_Entry **defobj_out, bool in_plt);
121 static const Elf_Sym *symlook_list(const char *, unsigned long,
122 Objlist *, const Obj_Entry **, bool in_plt, DoneList *);
123 static void trace_loaded_objects(Obj_Entry *obj);
124 static void unlink_object(Obj_Entry *);
125 static void unload_object(Obj_Entry *);
126 static void unref_dag(Obj_Entry *);
128 void r_debug_state(struct r_debug*, struct link_map*);
133 static char *error_message; /* Message for dlerror(), or NULL */
134 struct r_debug r_debug; /* for GDB; */
135 static bool trust; /* False for setuid and setgid programs */
136 static char *ld_bind_now; /* Environment variable for immediate binding */
137 static char *ld_debug; /* Environment variable for debugging */
138 static char *ld_library_path; /* Environment variable for search path */
139 static char *ld_preload; /* Environment variable for libraries to
141 static char *ld_tracing; /* Called from ldd(1) to print libs */
142 static char *ld_prebind; /* Called from prebind(1) to prebind libs */
143 static Obj_Entry *obj_list; /* Head of linked list of shared objects */
144 static Obj_Entry **obj_tail; /* Link field of last object in list */
145 static Obj_Entry *obj_main; /* The main program shared object */
146 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
147 static unsigned int obj_count; /* Number of objects in obj_list */
149 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
150 STAILQ_HEAD_INITIALIZER(list_global);
151 static Objlist list_main = /* Objects loaded at program startup */
152 STAILQ_HEAD_INITIALIZER(list_main);
153 static Objlist list_fini = /* Objects needing fini() calls */
154 STAILQ_HEAD_INITIALIZER(list_fini);
156 static LockInfo lockinfo;
158 static Elf_Sym sym_zero; /* For resolving undefined weak refs. */
160 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
162 extern Elf_Dyn _DYNAMIC;
163 #pragma weak _DYNAMIC
166 * These are the functions the dynamic linker exports to application
167 * programs. They are the only symbols the dynamic linker is willing
168 * to export from itself.
170 static func_ptr_type exports[] = {
171 (func_ptr_type) &_rtld_error,
172 (func_ptr_type) &dlclose,
173 (func_ptr_type) &dlerror,
174 (func_ptr_type) &dlopen,
175 (func_ptr_type) &dlsym,
176 (func_ptr_type) &dladdr,
177 (func_ptr_type) &dllockinit,
178 (func_ptr_type) &dlinfo,
183 * Global declarations normally provided by crt1. The dynamic linker is
184 * not built with crt1, so we have to provide them ourselves.
190 * Fill in a DoneList with an allocation large enough to hold all of
191 * the currently-loaded objects. Keep this as a macro since it calls
192 * alloca and we want that to occur within the scope of the caller.
194 #define donelist_init(dlp) \
195 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
196 assert((dlp)->objs != NULL), \
197 (dlp)->num_alloc = obj_count, \
203 lockinfo.rlock_acquire(lockinfo.thelock);
204 atomic_incr_int(&lockinfo.rcount);
211 lockinfo.wlock_acquire(lockinfo.thelock);
212 atomic_incr_int(&lockinfo.wcount);
219 atomic_decr_int(&lockinfo.rcount);
220 lockinfo.rlock_release(lockinfo.thelock);
226 atomic_decr_int(&lockinfo.wcount);
227 lockinfo.wlock_release(lockinfo.thelock);
231 * Main entry point for dynamic linking. The first argument is the
232 * stack pointer. The stack is expected to be laid out as described
233 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
234 * Specifically, the stack pointer points to a word containing
235 * ARGC. Following that in the stack is a null-terminated sequence
236 * of pointers to argument strings. Then comes a null-terminated
237 * sequence of pointers to environment strings. Finally, there is a
238 * sequence of "auxiliary vector" entries.
240 * The second argument points to a place to store the dynamic linker's
241 * exit procedure pointer and the third to a place to store the main
244 * The return value is the main program's entry point.
247 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
249 Elf_Auxinfo *aux_info[AT_COUNT];
258 Obj_Entry **preload_tail;
260 int prebind_disable = 0;
263 * On entry, the dynamic linker itself has not been relocated yet.
264 * Be very careful not to reference any global data until after
265 * init_rtld has returned. It is OK to reference file-scope statics
266 * and string constants, and to call static and global functions.
269 /* Find the auxiliary vector on the stack. */
272 sp += argc + 1; /* Skip over arguments and NULL terminator */
274 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
276 aux = (Elf_Auxinfo *) sp;
278 /* Digest the auxiliary vector. */
279 for (i = 0; i < AT_COUNT; i++)
281 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
282 if (auxp->a_type < AT_COUNT)
283 aux_info[auxp->a_type] = auxp;
286 /* Initialize and relocate ourselves. */
287 assert(aux_info[AT_BASE] != NULL);
288 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
290 __progname = obj_rtld.path;
291 argv0 = argv[0] != NULL ? argv[0] : "(null)";
294 trust = geteuid() == getuid() && getegid() == getgid();
296 prebind_disable = getenv("LD_PREBIND_DISABLE") != NULL;
298 ld_bind_now = getenv("LD_BIND_NOW");
300 ld_debug = getenv("LD_DEBUG");
301 ld_library_path = getenv("LD_LIBRARY_PATH");
302 ld_preload = getenv("LD_PRELOAD");
304 ld_tracing = getenv("LD_TRACE_LOADED_OBJECTS");
307 ld_prebind = getenv("LD_PREBIND");
308 if (ld_prebind != NULL && *ld_prebind != '\0') {
309 ld_bind_now = ld_prebind;
314 if (ld_debug != NULL && *ld_debug != '\0')
316 dbg("%s is initialized, base address = %p", __progname,
317 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
318 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
319 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
322 * Load the main program, or process its program header if it is
325 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
326 int fd = aux_info[AT_EXECFD]->a_un.a_val;
327 dbg("loading main program");
328 obj_main = map_object(fd, argv0, NULL);
330 if (obj_main == NULL)
332 } else { /* Main program already loaded. */
333 const Elf_Phdr *phdr;
337 dbg("processing main program's program header");
338 assert(aux_info[AT_PHDR] != NULL);
339 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
340 assert(aux_info[AT_PHNUM] != NULL);
341 phnum = aux_info[AT_PHNUM]->a_un.a_val;
342 assert(aux_info[AT_PHENT] != NULL);
343 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
344 assert(aux_info[AT_ENTRY] != NULL);
345 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
346 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
350 obj_main->path = xstrdup(argv0);
351 obj_main->mainprog = true;
354 * Get the actual dynamic linker pathname from the executable if
355 * possible. (It should always be possible.) That ensures that
356 * gdb will find the right dynamic linker even if a non-standard
359 if (obj_main->interp != NULL &&
360 strcmp(obj_main->interp, obj_rtld.path) != 0) {
362 obj_rtld.path = xstrdup(obj_main->interp);
365 digest_dynamic(obj_main);
367 linkmap_add(obj_main);
368 linkmap_add(&obj_rtld);
370 /* Link the main program into the list of objects. */
371 *obj_tail = obj_main;
372 obj_tail = &obj_main->next;
374 obj_main->refcount++;
375 /* Make sure we don't call the main program's init and fini functions. */
376 obj_main->init = obj_main->fini = NULL;
378 /* Initialize a fake symbol for resolving undefined weak references. */
379 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
380 sym_zero.st_shndx = SHN_ABS;
382 dbg("loading LD_PRELOAD libraries");
383 if (load_preload_objects() == -1)
385 preload_tail = obj_tail;
387 dbg("loading needed objects");
388 if (load_needed_objects(obj_main) == -1)
391 /* Make a list of all objects loaded at startup. */
392 for (obj = obj_list; obj != NULL; obj = obj->next)
393 objlist_push_tail(&list_main, obj);
395 if (ld_tracing) { /* We're done */
396 trace_loaded_objects(obj_main);
400 if (prebind_disable || prebind_load(&obj_rtld, obj_main)) {
401 if (relocate_objects(obj_main,
402 ld_bind_now != NULL && *ld_bind_now != '\0') == -1)
405 dbg("doing copy relocations");
406 if (do_copy_relocations(obj_main) == -1)
410 if (ld_prebind != NULL && *ld_prebind != '\0')
411 exit (prebind_save(&obj_rtld, obj_main));
413 dbg("initializing key program variables");
414 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
415 set_program_var("environ", env);
417 dbg("initializing thread locks");
418 lockdflt_init(&lockinfo);
419 lockinfo.thelock = lockinfo.lock_create(lockinfo.context);
421 /* Make a list of init functions to call. */
422 objlist_init(&initlist);
423 initlist_add_objects(obj_list, preload_tail, &initlist);
425 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
427 objlist_call_init(&initlist);
429 objlist_clear(&initlist);
432 dbg("transferring control to program entry point = %p", obj_main->entry);
434 /* Return the exit procedure and the program entry point. */
435 *exit_proc = rtld_exit;
437 return (func_ptr_type) obj_main->entry;
441 _rtld_bind(Obj_Entry *obj, Elf_Word reloff)
445 const Obj_Entry *defobj;
451 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
453 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
455 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
456 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL);
460 target = (Elf_Addr)(defobj->relocbase + def->st_value);
462 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
463 defobj->strtab + def->st_name, basename(obj->path),
464 (void *)target, basename(defobj->path));
466 reloc_jmpslot(where, target);
472 * Error reporting function. Use it like printf. If formats the message
473 * into a buffer, and sets things up so that the next call to dlerror()
474 * will return the message.
477 _rtld_error(const char *fmt, ...)
479 static char buf[512];
483 vsnprintf(buf, sizeof buf, fmt, ap);
489 * Return a dynamically-allocated copy of the current error message, if any.
494 return error_message == NULL ? NULL : xstrdup(error_message);
498 * Restore the current error message from a copy which was previously saved
499 * by errmsg_save(). The copy is freed.
502 errmsg_restore(char *saved_msg)
504 if (saved_msg == NULL)
505 error_message = NULL;
507 _rtld_error("%s", saved_msg);
513 basename(const char *name)
515 const char *p = strrchr(name, '/');
516 return p != NULL ? p + 1 : name;
522 const char *msg = dlerror();
530 * Process a shared object's DYNAMIC section, and save the important
531 * information in its Obj_Entry structure.
534 digest_dynamic(Obj_Entry *obj)
537 Needed_Entry **needed_tail = &obj->needed;
538 const Elf_Dyn *dyn_rpath = NULL;
539 int plttype = DT_REL;
541 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
542 switch (dynp->d_tag) {
545 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
549 obj->relsize = dynp->d_un.d_val;
553 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
557 obj->pltrel = (const Elf_Rel *)
558 (obj->relocbase + dynp->d_un.d_ptr);
562 obj->pltrelsize = dynp->d_un.d_val;
566 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
570 obj->relasize = dynp->d_un.d_val;
574 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
578 plttype = dynp->d_un.d_val;
579 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
583 obj->symtab = (const Elf_Sym *)
584 (obj->relocbase + dynp->d_un.d_ptr);
588 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
592 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
596 obj->strsize = dynp->d_un.d_val;
601 const Elf_Addr *hashtab = (const Elf_Addr *)
602 (obj->relocbase + dynp->d_un.d_ptr);
603 obj->nbuckets = hashtab[0];
604 obj->nchains = hashtab[1];
605 obj->buckets = hashtab + 2;
606 obj->chains = obj->buckets + obj->nbuckets;
612 Needed_Entry *nep = NEW(Needed_Entry);
613 nep->name = dynp->d_un.d_val;
618 needed_tail = &nep->next;
623 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
631 obj->symbolic = true;
636 * We have to wait until later to process this, because we
637 * might not have gotten the address of the string table yet.
643 /* Not used by the dynamic linker. */
647 obj->init = (InitFunc) (obj->relocbase + dynp->d_un.d_ptr);
651 obj->fini = (InitFunc) (obj->relocbase + dynp->d_un.d_ptr);
655 /* XXX - not implemented yet */
656 dbg("Filling in DT_DEBUG entry");
657 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
661 dbg("Ignoring d_tag %d = %#x", dynp->d_tag, dynp->d_tag);
670 obj->uniqid = elf_uniqid(obj->uniqid, obj->pltrel, obj->pltrelsize);
672 obj->uniqid = elf_uniqid(obj->uniqid, obj->symtab, obj->nchains * sizeof(*obj->symtab));
674 if (plttype == DT_RELA) {
675 obj->pltrela = (const Elf_Rela *) obj->pltrel;
677 obj->pltrelasize = obj->pltrelsize;
681 if (dyn_rpath != NULL)
682 obj->rpath = obj->strtab + dyn_rpath->d_un.d_val;
686 * Process a shared object's program header. This is used only for the
687 * main program, when the kernel has already loaded the main program
688 * into memory before calling the dynamic linker. It creates and
689 * returns an Obj_Entry structure.
692 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
695 const Elf_Phdr *phlimit = phdr + phnum;
700 for (ph = phdr; ph < phlimit; ph++) {
701 switch (ph->p_type) {
704 if ((const Elf_Phdr *)ph->p_vaddr != phdr) {
705 _rtld_error("%s: invalid PT_PHDR", path);
708 obj->phdr = (const Elf_Phdr *) ph->p_vaddr;
709 obj->phsize = ph->p_memsz;
713 obj->interp = (const char *) ph->p_vaddr;
717 if (nsegs == 0) { /* First load segment */
718 obj->vaddrbase = trunc_page(ph->p_vaddr);
719 obj->mapbase = (caddr_t) obj->vaddrbase;
720 obj->relocbase = obj->mapbase - obj->vaddrbase;
721 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
723 } else { /* Last load segment */
724 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
731 obj->dynamic = (const Elf_Dyn *) ph->p_vaddr;
736 _rtld_error("%s: too few PT_LOAD segments", path);
745 dlcheck(void *handle)
749 for (obj = obj_list; obj != NULL; obj = obj->next)
750 if (obj == (Obj_Entry *) handle)
753 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
754 _rtld_error("Invalid shared object handle %p", handle);
761 * If the given object is already in the donelist, return true. Otherwise
762 * add the object to the list and return false.
765 donelist_check(DoneList *dlp, const Obj_Entry *obj)
769 for (i = 0; i < dlp->num_used; i++)
770 if (dlp->objs[i] == obj)
773 * Our donelist allocation should always be sufficient. But if
774 * our threads locking isn't working properly, more shared objects
775 * could have been loaded since we allocated the list. That should
776 * never happen, but we'll handle it properly just in case it does.
778 if (dlp->num_used < dlp->num_alloc)
779 dlp->objs[dlp->num_used++] = obj;
784 * Hash function for symbol table lookup. Don't even think about changing
785 * this. It is specified by the System V ABI.
788 elf_hash(const char *name)
790 const unsigned char *p = (const unsigned char *) name;
796 if ((g = h & 0xf0000000) != 0)
804 * Hash function to get an unique ID from an ELF object file
805 * needs to be fast and small
807 * This one is after Krovetz, Rogaway: The PolyR construction,
808 * http://www.cs.ucdavis.edu/~rogaway/papers/poly.htm
810 * If called for the first time on a block, pass hash = 1
813 elf_uniqid(u_int32_t hash, const void *data, size_t len)
815 const u_int32_t p = 0xfffffffb; /* The largest prime smaller than 2^32 */
816 const u_int32_t offset = 5; /* Constant for translating out-of-range words */
817 const u_int32_t marker = 0xfffffffa; /* Constant for indicating out-of-range words */
818 const u_int32_t key = RTLD_TS; /* Hash key XXX */
819 u_int32_t n = len / 4; /* 32 bit blocks */
820 u_int32_t remainder = 0;
821 const u_int32_t *block;
823 for (block = data; n; --n, ++block)
825 if (*block >= p - 1) { /* If word is not in range, then */
826 hash = uniqid_hash_block(hash, key, marker); /* Maker indicates out-of-range */
827 hash = uniqid_hash_block(hash, key, *block - offset); /* Offset m back into range */
829 hash = uniqid_hash_block(hash, key, *block);
831 if (len % 4) { /* we got some remainder */
832 memcpy(&remainder, block, len % 4); /* copy remaining bytes into 0-padded block */
833 block = &remainder; /* set up pointer */
834 n = 1; /* one block to process */
835 len = 0; /* we've done the remainder */
836 goto uniqid_hash; /* run once again */
843 * Find the library with the given name, and return its full pathname.
844 * The returned string is dynamically allocated. Generates an error
845 * message and returns NULL if the library cannot be found.
847 * If the second argument is non-NULL, then it refers to an already-
848 * loaded shared object, whose library search path will be searched.
850 * The search order is:
852 * rpath in the referencing file
857 find_library(const char *name, const Obj_Entry *refobj)
861 if (strchr(name, '/') != NULL) { /* Hard coded pathname */
862 if (name[0] != '/' && !trust) {
863 _rtld_error("Absolute pathname required for shared object \"%s\"",
867 return xstrdup(name);
870 dbg(" Searching for \"%s\"", name);
872 if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
874 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
875 (pathname = search_library_path(name, gethints())) != NULL ||
876 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
879 _rtld_error("Shared object \"%s\" not found", name);
884 * Given a symbol number in a referencing object, find the corresponding
885 * definition of the symbol. Returns a pointer to the symbol, or NULL if
886 * no definition was found. Returns a pointer to the Obj_Entry of the
887 * defining object via the reference parameter DEFOBJ_OUT.
890 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
891 const Obj_Entry **defobj_out, bool in_plt, SymCache *cache)
895 const Obj_Entry *defobj;
900 * If we have already found this symbol, get the information from
903 if (symnum >= refobj->nchains)
904 return NULL; /* Bad object */
905 if (cache != NULL && cache[symnum].sym != NULL) {
906 *defobj_out = cache[symnum].obj;
907 return cache[symnum].sym;
910 ref = refobj->symtab + symnum;
911 name = refobj->strtab + ref->st_name;
912 hash = elf_hash(name);
915 def = symlook_default(name, hash, refobj, &defobj, in_plt);
918 * If we found no definition and the reference is weak, treat the
919 * symbol as having the value zero.
921 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
927 *defobj_out = defobj;
928 /* Record the information in the cache to avoid subsequent lookups. */
930 cache[symnum].sym = def;
931 cache[symnum].obj = defobj;
934 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
939 * Return the search path from the ldconfig hints file, reading it if
940 * necessary. Returns NULL if there are problems with the hints file,
941 * or if the search path there is empty.
950 struct elfhints_hdr hdr;
953 /* Keep from trying again in case the hints file is bad. */
956 if ((fd = open(_PATH_ELF_HINTS, O_RDONLY)) == -1)
958 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
959 hdr.magic != ELFHINTS_MAGIC ||
964 p = xmalloc(hdr.dirlistlen + 1);
965 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
966 read(fd, p, hdr.dirlistlen + 1) != hdr.dirlistlen + 1) {
974 return hints[0] != '\0' ? hints : NULL;
978 init_dag(Obj_Entry *root)
982 donelist_init(&donelist);
983 init_dag1(root, root, &donelist);
987 init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *dlp)
989 const Needed_Entry *needed;
991 if (donelist_check(dlp, obj))
993 objlist_push_tail(&obj->dldags, root);
994 objlist_push_tail(&root->dagmembers, obj);
995 for (needed = obj->needed; needed != NULL; needed = needed->next)
996 if (needed->obj != NULL)
997 init_dag1(root, needed->obj, dlp);
1001 * Initialize the dynamic linker. The argument is the address at which
1002 * the dynamic linker has been mapped into memory. The primary task of
1003 * this function is to relocate the dynamic linker.
1006 init_rtld(caddr_t mapbase)
1009 * Conjure up an Obj_Entry structure for the dynamic linker.
1011 * The "path" member is supposed to be dynamically-allocated, but we
1012 * aren't yet initialized sufficiently to do that. Below we will
1013 * replace the static version with a dynamically-allocated copy.
1015 obj_rtld.path = PATH_RTLD;
1016 obj_rtld.rtld = true;
1017 obj_rtld.mapbase = mapbase;
1019 obj_rtld.relocbase = mapbase;
1021 if (&_DYNAMIC != 0) {
1022 obj_rtld.dynamic = rtld_dynamic(&obj_rtld);
1023 digest_dynamic(&obj_rtld);
1024 assert(obj_rtld.needed == NULL);
1025 assert(!obj_rtld.textrel);
1028 * Temporarily put the dynamic linker entry into the object list, so
1029 * that symbols can be found.
1031 obj_list = &obj_rtld;
1032 obj_tail = &obj_rtld.next;
1035 relocate_objects(&obj_rtld, true);
1038 /* Make the object list empty again. */
1040 obj_tail = &obj_list;
1043 /* Replace the path with a dynamically allocated copy. */
1044 obj_rtld.path = xstrdup(obj_rtld.path);
1046 obj_rtld.uniqid = RTLD_TS;
1048 r_debug.r_brk = r_debug_state;
1049 r_debug.r_state = RT_CONSISTENT;
1053 * Add the init functions from a needed object list (and its recursive
1054 * needed objects) to "list". This is not used directly; it is a helper
1055 * function for initlist_add_objects(). The write lock must be held
1056 * when this function is called.
1059 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1061 /* Recursively process the successor needed objects. */
1062 if (needed->next != NULL)
1063 initlist_add_neededs(needed->next, list);
1065 /* Process the current needed object. */
1066 if (needed->obj != NULL)
1067 initlist_add_objects(needed->obj, &needed->obj->next, list);
1071 * Scan all of the DAGs rooted in the range of objects from "obj" to
1072 * "tail" and add their init functions to "list". This recurses over
1073 * the DAGs and ensure the proper init ordering such that each object's
1074 * needed libraries are initialized before the object itself. At the
1075 * same time, this function adds the objects to the global finalization
1076 * list "list_fini" in the opposite order. The write lock must be
1077 * held when this function is called.
1080 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1084 obj->init_done = true;
1086 /* Recursively process the successor objects. */
1087 if (&obj->next != tail)
1088 initlist_add_objects(obj->next, tail, list);
1090 /* Recursively process the needed objects. */
1091 if (obj->needed != NULL)
1092 initlist_add_neededs(obj->needed, list);
1094 /* Add the object to the init list. */
1095 if (obj->init != NULL)
1096 objlist_push_tail(list, obj);
1098 /* Add the object to the global fini list in the reverse order. */
1099 if (obj->fini != NULL)
1100 objlist_push_head(&list_fini, obj);
1104 is_exported(const Elf_Sym *def)
1106 func_ptr_type value;
1107 const func_ptr_type *p;
1109 value = (func_ptr_type)(obj_rtld.relocbase + def->st_value);
1110 for (p = exports; *p != NULL; p++)
1117 * Given a shared object, traverse its list of needed objects, and load
1118 * each of them. Returns 0 on success. Generates an error message and
1119 * returns -1 on failure.
1122 load_needed_objects(Obj_Entry *first)
1126 for (obj = first; obj != NULL; obj = obj->next) {
1127 Needed_Entry *needed;
1129 for (needed = obj->needed; needed != NULL; needed = needed->next) {
1130 const char *name = obj->strtab + needed->name;
1131 char *path = find_library(name, obj);
1134 if (path == NULL && !ld_tracing)
1138 needed->obj = load_object(path);
1139 if (needed->obj == NULL && !ld_tracing)
1140 return -1; /* XXX - cleanup */
1149 load_preload_objects(void)
1151 char *p = ld_preload;
1152 static const char delim[] = " \t:;";
1157 p += strspn(p, delim);
1158 while (*p != '\0') {
1159 size_t len = strcspn(p, delim);
1165 if ((path = find_library(p, NULL)) == NULL)
1167 if (load_object(path) == NULL)
1168 return -1; /* XXX - cleanup */
1171 p += strspn(p, delim);
1177 * Load a shared object into memory, if it is not already loaded. The
1178 * argument must be a string allocated on the heap. This function assumes
1179 * responsibility for freeing it when necessary.
1181 * Returns a pointer to the Obj_Entry for the object. Returns NULL
1185 load_object(char *path)
1191 for (obj = obj_list->next; obj != NULL; obj = obj->next)
1192 if (strcmp(obj->path, path) == 0)
1196 * If we didn't find a match by pathname, open the file and check
1197 * again by device and inode. This avoids false mismatches caused
1198 * by multiple links or ".." in pathnames.
1200 * To avoid a race, we open the file and use fstat() rather than
1204 if ((fd = open(path, O_RDONLY)) == -1) {
1205 _rtld_error("Cannot open \"%s\"", path);
1208 if (fstat(fd, &sb) == -1) {
1209 _rtld_error("Cannot fstat \"%s\"", path);
1213 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
1214 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev) {
1221 if (obj == NULL) { /* First use of this object, so we must map it in */
1222 dbg("loading \"%s\"", path);
1223 obj = map_object(fd, path, &sb);
1231 digest_dynamic(obj);
1234 obj_tail = &obj->next;
1236 linkmap_add(obj); /* for GDB & dlinfo() */
1238 dbg(" %p .. %p: %s", obj->mapbase,
1239 obj->mapbase + obj->mapsize - 1, obj->path);
1241 dbg(" WARNING: %s has impure text", obj->path);
1250 * Check for locking violations and die if one is found.
1257 rcount = lockinfo.rcount;
1258 wcount = lockinfo.wcount;
1259 assert(rcount >= 0);
1260 assert(wcount >= 0);
1261 if (wcount > 1 || (wcount != 0 && rcount != 0)) {
1262 _rtld_error("Application locking error: %d readers and %d writers"
1263 " in dynamic linker. See DLLOCKINIT(3) in manual pages.",
1270 obj_from_addr(const void *addr)
1272 unsigned long endhash;
1275 endhash = elf_hash(END_SYM);
1276 for (obj = obj_list; obj != NULL; obj = obj->next) {
1277 const Elf_Sym *endsym;
1279 if (addr < (void *) obj->mapbase)
1281 if ((endsym = symlook_obj(END_SYM, endhash, obj, true)) == NULL)
1282 continue; /* No "end" symbol?! */
1283 if (addr < (void *) (obj->relocbase + endsym->st_value))
1290 * Call the finalization functions for each of the objects in "list"
1291 * which are unreferenced. All of the objects are expected to have
1292 * non-NULL fini functions.
1295 objlist_call_fini(Objlist *list)
1301 * Preserve the current error message since a fini function might
1302 * call into the dynamic linker and overwrite it.
1304 saved_msg = errmsg_save();
1305 STAILQ_FOREACH(elm, list, link) {
1306 if (elm->obj->refcount == 0) {
1307 dbg("calling fini function for %s", elm->obj->path);
1308 (*elm->obj->fini)();
1311 errmsg_restore(saved_msg);
1315 * Call the initialization functions for each of the objects in
1316 * "list". All of the objects are expected to have non-NULL init
1320 objlist_call_init(Objlist *list)
1326 * Preserve the current error message since an init function might
1327 * call into the dynamic linker and overwrite it.
1329 saved_msg = errmsg_save();
1330 STAILQ_FOREACH(elm, list, link) {
1331 dbg("calling init function for %s", elm->obj->path);
1332 (*elm->obj->init)();
1334 errmsg_restore(saved_msg);
1338 objlist_clear(Objlist *list)
1342 while (!STAILQ_EMPTY(list)) {
1343 elm = STAILQ_FIRST(list);
1344 STAILQ_REMOVE_HEAD(list, link);
1349 static Objlist_Entry *
1350 objlist_find(Objlist *list, const Obj_Entry *obj)
1354 STAILQ_FOREACH(elm, list, link)
1355 if (elm->obj == obj)
1361 objlist_init(Objlist *list)
1367 objlist_push_head(Objlist *list, Obj_Entry *obj)
1371 elm = NEW(Objlist_Entry);
1373 STAILQ_INSERT_HEAD(list, elm, link);
1377 objlist_push_tail(Objlist *list, Obj_Entry *obj)
1381 elm = NEW(Objlist_Entry);
1383 STAILQ_INSERT_TAIL(list, elm, link);
1387 objlist_remove(Objlist *list, Obj_Entry *obj)
1391 if ((elm = objlist_find(list, obj)) != NULL) {
1392 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1398 * Remove all of the unreferenced objects from "list".
1401 objlist_remove_unref(Objlist *list)
1406 STAILQ_INIT(&newlist);
1407 while (!STAILQ_EMPTY(list)) {
1408 elm = STAILQ_FIRST(list);
1409 STAILQ_REMOVE_HEAD(list, link);
1410 if (elm->obj->refcount == 0)
1413 STAILQ_INSERT_TAIL(&newlist, elm, link);
1419 * Relocate newly-loaded shared objects. The argument is a pointer to
1420 * the Obj_Entry for the first such object. All objects from the first
1421 * to the end of the list of objects are relocated. Returns 0 on success,
1425 relocate_objects(Obj_Entry *first, bool bind_now)
1429 for (obj = first; obj != NULL; obj = obj->next) {
1430 if (obj != &obj_rtld)
1431 dbg("relocating \"%s\"", obj->path);
1432 if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
1433 obj->symtab == NULL || obj->strtab == NULL) {
1434 _rtld_error("%s: Shared object has no run-time symbol table",
1440 /* There are relocations to the write-protected text segment. */
1441 if (mprotect(obj->mapbase, obj->textsize,
1442 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
1443 _rtld_error("%s: Cannot write-enable text segment: %s",
1444 obj->path, strerror(errno));
1449 /* Process the non-PLT relocations. */
1450 if (reloc_non_plt(obj, &obj_rtld))
1453 if (obj->textrel) { /* Re-protected the text segment. */
1454 if (mprotect(obj->mapbase, obj->textsize,
1455 PROT_READ|PROT_EXEC) == -1) {
1456 _rtld_error("%s: Cannot write-protect text segment: %s",
1457 obj->path, strerror(errno));
1462 /* Process the PLT relocations. */
1463 if (reloc_plt(obj) == -1)
1465 /* Relocate the jump slots if we are doing immediate binding. */
1467 if (reloc_jmpslots(obj) == -1)
1472 * Set up the magic number and version in the Obj_Entry. These
1473 * were checked in the crt1.o from the original ElfKit, so we
1474 * set them for backward compatibility.
1476 obj->magic = RTLD_MAGIC;
1477 obj->version = RTLD_VERSION;
1479 /* Set the special PLT or GOT entries. */
1487 * Cleanup procedure. It will be called (by the atexit mechanism) just
1488 * before the process exits.
1496 /* Clear all the reference counts so the fini functions will be called. */
1497 for (obj = obj_list; obj != NULL; obj = obj->next)
1499 objlist_call_fini(&list_fini);
1500 /* No need to remove the items from the list, since we are exiting. */
1504 path_enumerate(const char *path, path_enum_proc callback, void *arg)
1509 path += strspn(path, ":;");
1510 while (*path != '\0') {
1514 len = strcspn(path, ":;");
1515 res = callback(path, len, arg);
1521 path += strspn(path, ":;");
1527 struct try_library_args {
1535 try_library_path(const char *dir, size_t dirlen, void *param)
1537 struct try_library_args *arg;
1540 if (*dir == '/' || trust) {
1543 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
1546 pathname = arg->buffer;
1547 strncpy(pathname, dir, dirlen);
1548 pathname[dirlen] = '/';
1549 strcpy(pathname + dirlen + 1, arg->name);
1551 dbg(" Trying \"%s\"", pathname);
1552 if (access(pathname, F_OK) == 0) { /* We found it */
1553 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
1554 strcpy(pathname, arg->buffer);
1562 search_library_path(const char *name, const char *path)
1565 struct try_library_args arg;
1571 arg.namelen = strlen(name);
1572 arg.buffer = xmalloc(PATH_MAX);
1573 arg.buflen = PATH_MAX;
1575 p = path_enumerate(path, try_library_path, &arg);
1583 dlclose(void *handle)
1588 root = dlcheck(handle);
1594 /* Unreference the object and its dependencies. */
1595 root->dl_refcount--;
1598 if (root->refcount == 0) {
1600 * The object is no longer referenced, so we must unload it.
1601 * First, call the fini functions with no locks held.
1604 objlist_call_fini(&list_fini);
1606 objlist_remove_unref(&list_fini);
1608 /* Finish cleaning up the newly-unreferenced objects. */
1609 GDB_STATE(RT_DELETE,&root->linkmap);
1610 unload_object(root);
1611 GDB_STATE(RT_CONSISTENT,NULL);
1620 char *msg = error_message;
1621 error_message = NULL;
1626 * This function is deprecated and has no effect.
1629 dllockinit(void *context,
1630 void *(*lock_create)(void *context),
1631 void (*rlock_acquire)(void *lock),
1632 void (*wlock_acquire)(void *lock),
1633 void (*lock_release)(void *lock),
1634 void (*lock_destroy)(void *lock),
1635 void (*context_destroy)(void *context))
1637 static void *cur_context;
1638 static void (*cur_context_destroy)(void *);
1640 /* Just destroy the context from the previous call, if necessary. */
1641 if (cur_context_destroy != NULL)
1642 cur_context_destroy(cur_context);
1643 cur_context = context;
1644 cur_context_destroy = context_destroy;
1648 dlopen(const char *name, int mode)
1650 Obj_Entry **old_obj_tail;
1655 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
1656 if (ld_tracing != NULL)
1657 environ = (char **)*get_program_var_addr("environ");
1659 objlist_init(&initlist);
1662 GDB_STATE(RT_ADD,NULL);
1664 old_obj_tail = obj_tail;
1670 char *path = find_library(name, obj_main);
1672 obj = load_object(path);
1677 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
1678 objlist_push_tail(&list_global, obj);
1679 mode &= RTLD_MODEMASK;
1680 if (*old_obj_tail != NULL) { /* We loaded something new. */
1681 assert(*old_obj_tail == obj);
1683 result = load_needed_objects(obj);
1684 if (result != -1 && ld_tracing)
1688 (init_dag(obj), relocate_objects(obj, mode == RTLD_NOW)) == -1) {
1691 if (obj->refcount == 0)
1695 /* Make list of init functions to call. */
1696 initlist_add_objects(obj, &obj->next, &initlist);
1698 } else if (ld_tracing)
1702 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
1704 /* Call the init functions with no locks held. */
1706 objlist_call_init(&initlist);
1708 objlist_clear(&initlist);
1712 trace_loaded_objects(obj);
1718 dlsym(void *handle, const char *name)
1720 const Obj_Entry *obj;
1723 const Obj_Entry *defobj;
1725 hash = elf_hash(name);
1730 if (handle == NULL || handle == RTLD_NEXT ||
1731 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
1734 retaddr = __builtin_return_address(0); /* __GNUC__ only */
1735 if ((obj = obj_from_addr(retaddr)) == NULL) {
1736 _rtld_error("Cannot determine caller's shared object");
1740 if (handle == NULL) { /* Just the caller's shared object. */
1741 def = symlook_obj(name, hash, obj, true);
1743 } else if (handle == RTLD_NEXT || /* Objects after caller's */
1744 handle == RTLD_SELF) { /* ... caller included */
1745 if (handle == RTLD_NEXT)
1747 for (; obj != NULL; obj = obj->next) {
1748 if ((def = symlook_obj(name, hash, obj, true)) != NULL) {
1754 assert(handle == RTLD_DEFAULT);
1755 def = symlook_default(name, hash, obj, &defobj, true);
1758 if ((obj = dlcheck(handle)) == NULL) {
1763 if (obj->mainprog) {
1766 /* Search main program and all libraries loaded by it. */
1767 donelist_init(&donelist);
1768 def = symlook_list(name, hash, &list_main, &defobj, true,
1772 * XXX - This isn't correct. The search should include the whole
1773 * DAG rooted at the given object.
1775 def = symlook_obj(name, hash, obj, true);
1782 return defobj->relocbase + def->st_value;
1785 _rtld_error("Undefined symbol \"%s\"", name);
1791 dladdr(const void *addr, Dl_info *info)
1793 const Obj_Entry *obj;
1796 unsigned long symoffset;
1799 obj = obj_from_addr(addr);
1801 _rtld_error("No shared object contains address");
1805 info->dli_fname = obj->path;
1806 info->dli_fbase = obj->mapbase;
1807 info->dli_saddr = (void *)0;
1808 info->dli_sname = NULL;
1811 * Walk the symbol list looking for the symbol whose address is
1812 * closest to the address sent in.
1814 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
1815 def = obj->symtab + symoffset;
1818 * For skip the symbol if st_shndx is either SHN_UNDEF or
1821 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
1825 * If the symbol is greater than the specified address, or if it
1826 * is further away from addr than the current nearest symbol,
1829 symbol_addr = obj->relocbase + def->st_value;
1830 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
1833 /* Update our idea of the nearest symbol. */
1834 info->dli_sname = obj->strtab + def->st_name;
1835 info->dli_saddr = symbol_addr;
1838 if (info->dli_saddr == addr)
1846 dlinfo(void *handle, int request, void *p)
1848 const Obj_Entry *obj;
1853 if (handle == NULL || handle == RTLD_SELF) {
1856 retaddr = __builtin_return_address(0); /* __GNUC__ only */
1857 if ((obj = obj_from_addr(retaddr)) == NULL)
1858 _rtld_error("Cannot determine caller's shared object");
1860 obj = dlcheck(handle);
1869 case RTLD_DI_LINKMAP:
1870 *((struct link_map const **)p) = &obj->linkmap;
1872 case RTLD_DI_ORIGIN:
1873 error = rtld_dirname(obj->path, p);
1876 case RTLD_DI_SERINFOSIZE:
1877 case RTLD_DI_SERINFO:
1878 error = do_search_info(obj, request, (struct dl_serinfo *)p);
1882 _rtld_error("Invalid request %d passed to dlinfo()", request);
1891 struct fill_search_info_args {
1894 Dl_serinfo *serinfo;
1895 Dl_serpath *serpath;
1900 fill_search_info(const char *dir, size_t dirlen, void *param)
1902 struct fill_search_info_args *arg;
1906 if (arg->request == RTLD_DI_SERINFOSIZE) {
1907 arg->serinfo->dls_cnt ++;
1908 arg->serinfo->dls_size += dirlen + 1;
1910 struct dl_serpath *s_entry;
1912 s_entry = arg->serpath;
1913 s_entry->dls_name = arg->strspace;
1914 s_entry->dls_flags = arg->flags;
1916 strncpy(arg->strspace, dir, dirlen);
1917 arg->strspace[dirlen] = '\0';
1919 arg->strspace += dirlen + 1;
1927 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
1929 struct dl_serinfo _info;
1930 struct fill_search_info_args args;
1932 args.request = RTLD_DI_SERINFOSIZE;
1933 args.serinfo = &_info;
1935 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1938 path_enumerate(ld_library_path, fill_search_info, &args);
1939 path_enumerate(obj->rpath, fill_search_info, &args);
1940 path_enumerate(gethints(), fill_search_info, &args);
1941 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
1944 if (request == RTLD_DI_SERINFOSIZE) {
1945 info->dls_size = _info.dls_size;
1946 info->dls_cnt = _info.dls_cnt;
1950 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
1951 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
1955 args.request = RTLD_DI_SERINFO;
1956 args.serinfo = info;
1957 args.serpath = &info->dls_serpath[0];
1958 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
1960 args.flags = LA_SER_LIBPATH;
1961 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
1964 args.flags = LA_SER_RUNPATH;
1965 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
1968 args.flags = LA_SER_CONFIG;
1969 if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
1972 args.flags = LA_SER_DEFAULT;
1973 if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
1979 rtld_dirname(const char *path, char *bname)
1983 /* Empty or NULL string gets treated as "." */
1984 if (path == NULL || *path == '\0') {
1990 /* Strip trailing slashes */
1991 endp = path + strlen(path) - 1;
1992 while (endp > path && *endp == '/')
1995 /* Find the start of the dir */
1996 while (endp > path && *endp != '/')
1999 /* Either the dir is "/" or there are no slashes */
2001 bname[0] = *endp == '/' ? '/' : '.';
2007 } while (endp > path && *endp == '/');
2010 if (endp - path + 2 > PATH_MAX)
2012 _rtld_error("Filename is too long: %s", path);
2016 strncpy(bname, path, endp - path + 1);
2017 bname[endp - path + 1] = '\0';
2022 linkmap_add(Obj_Entry *obj)
2024 struct link_map *l = &obj->linkmap;
2025 struct link_map *prev;
2027 obj->linkmap.l_name = obj->path;
2028 obj->linkmap.l_addr = obj->mapbase;
2029 obj->linkmap.l_ld = obj->dynamic;
2031 /* GDB needs load offset on MIPS to use the symbols */
2032 obj->linkmap.l_offs = obj->relocbase;
2035 if (r_debug.r_map == NULL) {
2041 * Scan to the end of the list, but not past the entry for the
2042 * dynamic linker, which we want to keep at the very end.
2044 for (prev = r_debug.r_map;
2045 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
2046 prev = prev->l_next)
2049 /* Link in the new entry. */
2051 l->l_next = prev->l_next;
2052 if (l->l_next != NULL)
2053 l->l_next->l_prev = l;
2058 linkmap_delete(Obj_Entry *obj)
2060 struct link_map *l = &obj->linkmap;
2062 if (l->l_prev == NULL) {
2063 if ((r_debug.r_map = l->l_next) != NULL)
2064 l->l_next->l_prev = NULL;
2068 if ((l->l_prev->l_next = l->l_next) != NULL)
2069 l->l_next->l_prev = l->l_prev;
2073 * Function for the debugger to set a breakpoint on to gain control.
2075 * The two parameters allow the debugger to easily find and determine
2076 * what the runtime loader is doing and to whom it is doing it.
2078 * When the loadhook trap is hit (r_debug_state, set at program
2079 * initialization), the arguments can be found on the stack:
2081 * +8 struct link_map *m
2082 * +4 struct r_debug *rd
2086 r_debug_state(struct r_debug* rd, struct link_map *m)
2091 * Get address of the pointer variable in the main program.
2093 static const void **
2094 get_program_var_addr(const char *name)
2096 const Obj_Entry *obj;
2099 hash = elf_hash(name);
2100 for (obj = obj_main; obj != NULL; obj = obj->next) {
2103 if ((def = symlook_obj(name, hash, obj, false)) != NULL) {
2106 addr = (const void **)(obj->relocbase + def->st_value);
2114 * Set a pointer variable in the main program to the given value. This
2115 * is used to set key variables such as "environ" before any of the
2116 * init functions are called.
2119 set_program_var(const char *name, const void *value)
2123 if ((addr = get_program_var_addr(name)) != NULL) {
2124 dbg("\"%s\": *%p <-- %p", name, addr, value);
2130 * Given a symbol name in a referencing object, find the corresponding
2131 * definition of the symbol. Returns a pointer to the symbol, or NULL if
2132 * no definition was found. Returns a pointer to the Obj_Entry of the
2133 * defining object via the reference parameter DEFOBJ_OUT.
2135 static const Elf_Sym *
2136 symlook_default(const char *name, unsigned long hash,
2137 const Obj_Entry *refobj, const Obj_Entry **defobj_out, bool in_plt)
2141 const Elf_Sym *symp;
2142 const Obj_Entry *obj;
2143 const Obj_Entry *defobj;
2144 const Objlist_Entry *elm;
2147 donelist_init(&donelist);
2149 /* Look first in the referencing object if linked symbolically. */
2150 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
2151 symp = symlook_obj(name, hash, refobj, in_plt);
2158 /* Search all objects loaded at program start up. */
2159 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2160 symp = symlook_list(name, hash, &list_main, &obj, in_plt, &donelist);
2162 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2168 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
2169 STAILQ_FOREACH(elm, &list_global, link) {
2170 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2172 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt,
2175 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2181 /* Search all dlopened DAGs containing the referencing object. */
2182 STAILQ_FOREACH(elm, &refobj->dldags, link) {
2183 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2185 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt,
2188 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2195 * Search the dynamic linker itself, and possibly resolve the
2196 * symbol from there. This is how the application links to
2197 * dynamic linker services such as dlopen. Only the values listed
2198 * in the "exports" array can be resolved from the dynamic linker.
2200 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2201 symp = symlook_obj(name, hash, &obj_rtld, in_plt);
2202 if (symp != NULL && is_exported(symp)) {
2209 *defobj_out = defobj;
2213 static const Elf_Sym *
2214 symlook_list(const char *name, unsigned long hash, Objlist *objlist,
2215 const Obj_Entry **defobj_out, bool in_plt, DoneList *dlp)
2217 const Elf_Sym *symp;
2219 const Obj_Entry *defobj;
2220 const Objlist_Entry *elm;
2224 STAILQ_FOREACH(elm, objlist, link) {
2225 if (donelist_check(dlp, elm->obj))
2227 if ((symp = symlook_obj(name, hash, elm->obj, in_plt)) != NULL) {
2228 if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
2231 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2237 *defobj_out = defobj;
2242 * Search the symbol table of a single shared object for a symbol of
2243 * the given name. Returns a pointer to the symbol, or NULL if no
2244 * definition was found.
2246 * The symbol's hash value is passed in for efficiency reasons; that
2247 * eliminates many recomputations of the hash value.
2250 symlook_obj(const char *name, unsigned long hash, const Obj_Entry *obj,
2253 if (obj->buckets != NULL) {
2254 unsigned long symnum = obj->buckets[hash % obj->nbuckets];
2256 while (symnum != STN_UNDEF) {
2257 const Elf_Sym *symp;
2260 if (symnum >= obj->nchains)
2261 return NULL; /* Bad object */
2262 symp = obj->symtab + symnum;
2263 strp = obj->strtab + symp->st_name;
2265 if (name[0] == strp[0] && strcmp(name, strp) == 0)
2266 return symp->st_shndx != SHN_UNDEF ||
2267 (!in_plt && symp->st_value != 0 &&
2268 ELF_ST_TYPE(symp->st_info) == STT_FUNC) ? symp : NULL;
2270 symnum = obj->chains[symnum];
2277 trace_loaded_objects(Obj_Entry *obj)
2279 char *fmt1, *fmt2, *fmt, *main_local;
2282 if ((main_local = getenv("LD_TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
2285 if ((fmt1 = getenv("LD_TRACE_LOADED_OBJECTS_FMT1")) == NULL)
2286 fmt1 = "\t%o => %p (%x)\n";
2288 if ((fmt2 = getenv("LD_TRACE_LOADED_OBJECTS_FMT2")) == NULL)
2289 fmt2 = "\t%o (%x)\n";
2291 for (; obj; obj = obj->next) {
2292 Needed_Entry *needed;
2296 for (needed = obj->needed; needed; needed = needed->next) {
2297 if (needed->obj != NULL) {
2298 if (needed->obj->traced)
2300 needed->obj->traced = true;
2301 path = needed->obj->path;
2305 name = (char *)obj->strtab + needed->name;
2306 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
2308 fmt = is_lib ? fmt1 : fmt2;
2309 while ((c = *fmt++) != '\0') {
2335 printf("%s", main_local);
2338 printf("%s", obj_main->path);
2345 printf("%d", sodp->sod_major);
2348 printf("%d", sodp->sod_minor);
2355 printf("%p", needed->obj ? needed->obj->mapbase : 0);
2367 * Unload a dlopened object and its dependencies from memory and from
2368 * our data structures. It is assumed that the DAG rooted in the
2369 * object has already been unreferenced, and that the object has a
2370 * reference count of 0.
2373 unload_object(Obj_Entry *root)
2378 assert(root->refcount == 0);
2381 * Pass over the DAG removing unreferenced objects from
2382 * appropriate lists.
2384 unlink_object(root);
2386 /* Unmap all objects that are no longer referenced. */
2387 linkp = &obj_list->next;
2388 while ((obj = *linkp) != NULL) {
2389 if (obj->refcount == 0) {
2390 dbg("unloading \"%s\"", obj->path);
2391 munmap(obj->mapbase, obj->mapsize);
2392 linkmap_delete(obj);
2403 unlink_object(Obj_Entry *root)
2405 const Needed_Entry *needed;
2408 if (root->refcount == 0) {
2409 /* Remove the object from the RTLD_GLOBAL list. */
2410 objlist_remove(&list_global, root);
2412 /* Remove the object from all objects' DAG lists. */
2413 STAILQ_FOREACH(elm, &root->dagmembers , link)
2414 objlist_remove(&elm->obj->dldags, root);
2417 for (needed = root->needed; needed != NULL; needed = needed->next)
2418 if (needed->obj != NULL)
2419 unlink_object(needed->obj);
2423 unref_dag(Obj_Entry *root)
2425 const Needed_Entry *needed;
2427 if (root->refcount == 0)
2430 if (root->refcount == 0)
2431 for (needed = root->needed; needed != NULL; needed = needed->next)
2432 if (needed->obj != NULL)
2433 unref_dag(needed->obj);