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.
30 * Dynamic linker for ELF.
32 * John Polstra <jdp@polstra.com>.
36 #error "GCC is needed to compile this file"
39 #include <sys/param.h>
59 #define PATH_RTLD "/libexec/ld-elf.so.1"
61 #define PATH_RTLD "/libexec/ld-elf32.so.1"
65 typedef void (*func_ptr_type)();
66 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg);
69 * This structure provides a reentrant way to keep a list of objects and
70 * check which ones have already been processed in some way.
72 typedef struct Struct_DoneList {
73 const Obj_Entry **objs; /* Array of object pointers */
74 unsigned int num_alloc; /* Allocated size of the array */
75 unsigned int num_used; /* Number of array slots used */
79 * Function declarations.
81 static const char *basename(const char *);
82 static void die(void);
83 static void digest_dynamic(Obj_Entry *, int);
84 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
85 static Obj_Entry *dlcheck(void *);
86 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
87 static bool donelist_check(DoneList *, const Obj_Entry *);
88 static void errmsg_restore(char *);
89 static char *errmsg_save(void);
90 static void *fill_search_info(const char *, size_t, void *);
91 static char *find_library(const char *, const Obj_Entry *);
92 static const char *gethints(void);
93 static void init_dag(Obj_Entry *);
94 static void init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *);
95 static void init_rtld(caddr_t);
96 static void initlist_add_neededs(Needed_Entry *needed, Objlist *list);
97 static void initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail,
99 static bool is_exported(const Elf_Sym *);
100 static void linkmap_add(Obj_Entry *);
101 static void linkmap_delete(Obj_Entry *);
102 static int load_needed_objects(Obj_Entry *);
103 static int load_preload_objects(void);
104 static Obj_Entry *load_object(char *);
105 static Obj_Entry *obj_from_addr(const void *);
106 static void objlist_call_fini(Objlist *);
107 static void objlist_call_init(Objlist *);
108 static void objlist_clear(Objlist *);
109 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
110 static void objlist_init(Objlist *);
111 static void objlist_push_head(Objlist *, Obj_Entry *);
112 static void objlist_push_tail(Objlist *, Obj_Entry *);
113 static void objlist_remove(Objlist *, Obj_Entry *);
114 static void objlist_remove_unref(Objlist *);
115 static void *path_enumerate(const char *, path_enum_proc, void *);
116 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *);
117 static int rtld_dirname(const char *, char *);
118 static void rtld_exit(void);
119 static char *search_library_path(const char *, const char *);
120 static const void **get_program_var_addr(const char *name);
121 static void set_program_var(const char *, const void *);
122 static const Elf_Sym *symlook_default(const char *, unsigned long hash,
123 const Obj_Entry *refobj, const Obj_Entry **defobj_out, bool in_plt);
124 static const Elf_Sym *symlook_list(const char *, unsigned long,
125 Objlist *, const Obj_Entry **, bool in_plt, DoneList *);
126 static void trace_loaded_objects(Obj_Entry *obj);
127 static void unlink_object(Obj_Entry *);
128 static void unload_object(Obj_Entry *);
129 static void unref_dag(Obj_Entry *);
130 static void ref_dag(Obj_Entry *);
132 void r_debug_state(struct r_debug*, struct link_map*);
137 static char *error_message; /* Message for dlerror(), or NULL */
138 struct r_debug r_debug; /* for GDB; */
139 static bool libmap_disable; /* Disable libmap */
140 static bool trust; /* False for setuid and setgid programs */
141 static char *ld_bind_now; /* Environment variable for immediate binding */
142 static char *ld_debug; /* Environment variable for debugging */
143 static char *ld_library_path; /* Environment variable for search path */
144 static char *ld_preload; /* Environment variable for libraries to
146 static char *ld_tracing; /* Called from ldd to print libs */
147 static Obj_Entry *obj_list; /* Head of linked list of shared objects */
148 static Obj_Entry **obj_tail; /* Link field of last object in list */
149 static Obj_Entry *obj_main; /* The main program shared object */
150 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
151 static unsigned int obj_count; /* Number of objects in obj_list */
153 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
154 STAILQ_HEAD_INITIALIZER(list_global);
155 static Objlist list_main = /* Objects loaded at program startup */
156 STAILQ_HEAD_INITIALIZER(list_main);
157 static Objlist list_fini = /* Objects needing fini() calls */
158 STAILQ_HEAD_INITIALIZER(list_fini);
160 static Elf_Sym sym_zero; /* For resolving undefined weak refs. */
162 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
164 extern Elf_Dyn _DYNAMIC;
165 #pragma weak _DYNAMIC
166 #ifndef RTLD_IS_DYNAMIC
167 #define RTLD_IS_DYNAMIC() (&_DYNAMIC != NULL)
171 * These are the functions the dynamic linker exports to application
172 * programs. They are the only symbols the dynamic linker is willing
173 * to export from itself.
175 static func_ptr_type exports[] = {
176 (func_ptr_type) &_rtld_error,
177 (func_ptr_type) &dlclose,
178 (func_ptr_type) &dlerror,
179 (func_ptr_type) &dlopen,
180 (func_ptr_type) &dlsym,
181 (func_ptr_type) &dladdr,
182 (func_ptr_type) &dllockinit,
183 (func_ptr_type) &dlinfo,
184 (func_ptr_type) &_rtld_thread_init,
186 (func_ptr_type) &___tls_get_addr,
188 (func_ptr_type) &__tls_get_addr,
189 (func_ptr_type) &_rtld_allocate_tls,
190 (func_ptr_type) &_rtld_free_tls,
195 * Global declarations normally provided by crt1. The dynamic linker is
196 * not built with crt1, so we have to provide them ourselves.
202 * Globals to control TLS allocation.
204 size_t tls_last_offset; /* Static TLS offset of last module */
205 size_t tls_last_size; /* Static TLS size of last module */
206 size_t tls_static_space; /* Static TLS space allocated */
207 int tls_dtv_generation = 1; /* Used to detect when dtv size changes */
208 int tls_max_index = 1; /* Largest module index allocated */
211 * Fill in a DoneList with an allocation large enough to hold all of
212 * the currently-loaded objects. Keep this as a macro since it calls
213 * alloca and we want that to occur within the scope of the caller.
215 #define donelist_init(dlp) \
216 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
217 assert((dlp)->objs != NULL), \
218 (dlp)->num_alloc = obj_count, \
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];
248 Objlist_Entry *entry;
250 Obj_Entry **preload_tail;
255 * On entry, the dynamic linker itself has not been relocated yet.
256 * Be very careful not to reference any global data until after
257 * init_rtld has returned. It is OK to reference file-scope statics
258 * and string constants, and to call static and global functions.
261 /* Find the auxiliary vector on the stack. */
264 sp += argc + 1; /* Skip over arguments and NULL terminator */
266 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
268 aux = (Elf_Auxinfo *) sp;
270 /* Digest the auxiliary vector. */
271 for (i = 0; i < AT_COUNT; i++)
273 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
274 if (auxp->a_type < AT_COUNT)
275 aux_info[auxp->a_type] = auxp;
278 /* Initialize and relocate ourselves. */
279 assert(aux_info[AT_BASE] != NULL);
280 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
282 __progname = obj_rtld.path;
283 argv0 = argv[0] != NULL ? argv[0] : "(null)";
286 trust = !issetugid();
288 ld_bind_now = getenv(LD_ "BIND_NOW");
290 ld_debug = getenv(LD_ "DEBUG");
291 libmap_disable = getenv(LD_ "LIBMAP_DISABLE") != NULL;
292 ld_library_path = getenv(LD_ "LIBRARY_PATH");
293 ld_preload = getenv(LD_ "PRELOAD");
295 ld_tracing = getenv(LD_ "TRACE_LOADED_OBJECTS");
297 if (ld_debug != NULL && *ld_debug != '\0')
299 dbg("%s is initialized, base address = %p", __progname,
300 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
301 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
302 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
305 * Load the main program, or process its program header if it is
308 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
309 int fd = aux_info[AT_EXECFD]->a_un.a_val;
310 dbg("loading main program");
311 obj_main = map_object(fd, argv0, NULL);
313 if (obj_main == NULL)
315 } else { /* Main program already loaded. */
316 const Elf_Phdr *phdr;
320 dbg("processing main program's program header");
321 assert(aux_info[AT_PHDR] != NULL);
322 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
323 assert(aux_info[AT_PHNUM] != NULL);
324 phnum = aux_info[AT_PHNUM]->a_un.a_val;
325 assert(aux_info[AT_PHENT] != NULL);
326 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
327 assert(aux_info[AT_ENTRY] != NULL);
328 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
329 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
333 obj_main->path = xstrdup(argv0);
334 obj_main->mainprog = true;
337 * Get the actual dynamic linker pathname from the executable if
338 * possible. (It should always be possible.) That ensures that
339 * gdb will find the right dynamic linker even if a non-standard
342 if (obj_main->interp != NULL &&
343 strcmp(obj_main->interp, obj_rtld.path) != 0) {
345 obj_rtld.path = xstrdup(obj_main->interp);
346 __progname = obj_rtld.path;
349 digest_dynamic(obj_main, 0);
351 linkmap_add(obj_main);
352 linkmap_add(&obj_rtld);
354 /* Link the main program into the list of objects. */
355 *obj_tail = obj_main;
356 obj_tail = &obj_main->next;
358 /* Make sure we don't call the main program's init and fini functions. */
359 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
361 /* Initialize a fake symbol for resolving undefined weak references. */
362 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
363 sym_zero.st_shndx = SHN_UNDEF;
366 libmap_disable = (bool)lm_init();
368 dbg("loading LD_PRELOAD libraries");
369 if (load_preload_objects() == -1)
371 preload_tail = obj_tail;
373 dbg("loading needed objects");
374 if (load_needed_objects(obj_main) == -1)
377 /* Make a list of all objects loaded at startup. */
378 for (obj = obj_list; obj != NULL; obj = obj->next) {
379 objlist_push_tail(&list_main, obj);
383 if (ld_tracing) { /* We're done */
384 trace_loaded_objects(obj_main);
388 if (getenv(LD_ "DUMP_REL_PRE") != NULL) {
389 dump_relocations(obj_main);
393 if (relocate_objects(obj_main,
394 ld_bind_now != NULL && *ld_bind_now != '\0', &obj_rtld) == -1)
397 dbg("doing copy relocations");
398 if (do_copy_relocations(obj_main) == -1)
401 if (getenv(LD_ "DUMP_REL_POST") != NULL) {
402 dump_relocations(obj_main);
406 dbg("initializing key program variables");
407 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
408 set_program_var("environ", env);
410 dbg("initializing thread locks");
413 /* setup TLS for main thread */
414 dbg("initializing initial thread local storage");
415 STAILQ_FOREACH(entry, &list_main, link) {
417 * Allocate all the initial objects out of the static TLS
418 * block even if they didn't ask for it.
420 allocate_tls_offset(entry->obj);
422 allocate_initial_tls(obj_list);
424 /* Make a list of init functions to call. */
425 objlist_init(&initlist);
426 initlist_add_objects(obj_list, preload_tail, &initlist);
428 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
430 objlist_call_init(&initlist);
431 lockstate = wlock_acquire(rtld_bind_lock);
432 objlist_clear(&initlist);
433 wlock_release(rtld_bind_lock, lockstate);
435 dbg("transferring control to program entry point = %p", obj_main->entry);
437 /* Return the exit procedure and the program entry point. */
438 *exit_proc = rtld_exit;
440 return (func_ptr_type) obj_main->entry;
444 _rtld_bind(Obj_Entry *obj, Elf_Word reloff)
448 const Obj_Entry *defobj;
453 lockstate = rlock_acquire(rtld_bind_lock);
455 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
457 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
459 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
460 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL);
464 target = (Elf_Addr)(defobj->relocbase + def->st_value);
466 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
467 defobj->strtab + def->st_name, basename(obj->path),
468 (void *)target, basename(defobj->path));
471 * Write the new contents for the jmpslot. Note that depending on
472 * architecture, the value which we need to return back to the
473 * lazy binding trampoline may or may not be the target
474 * address. The value returned from reloc_jmpslot() is the value
475 * that the trampoline needs.
477 target = reloc_jmpslot(where, target, defobj, obj, rel);
478 rlock_release(rtld_bind_lock, lockstate);
483 * Error reporting function. Use it like printf. If formats the message
484 * into a buffer, and sets things up so that the next call to dlerror()
485 * will return the message.
488 _rtld_error(const char *fmt, ...)
490 static char buf[512];
494 vsnprintf(buf, sizeof buf, fmt, ap);
500 * Return a dynamically-allocated copy of the current error message, if any.
505 return error_message == NULL ? NULL : xstrdup(error_message);
509 * Restore the current error message from a copy which was previously saved
510 * by errmsg_save(). The copy is freed.
513 errmsg_restore(char *saved_msg)
515 if (saved_msg == NULL)
516 error_message = NULL;
518 _rtld_error("%s", saved_msg);
524 basename(const char *name)
526 const char *p = strrchr(name, '/');
527 return p != NULL ? p + 1 : name;
533 const char *msg = dlerror();
541 * Process a shared object's DYNAMIC section, and save the important
542 * information in its Obj_Entry structure.
545 digest_dynamic(Obj_Entry *obj, int early)
548 Needed_Entry **needed_tail = &obj->needed;
549 const Elf_Dyn *dyn_rpath = NULL;
550 int plttype = DT_REL;
552 obj->bind_now = false;
553 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
554 switch (dynp->d_tag) {
557 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
561 obj->relsize = dynp->d_un.d_val;
565 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
569 obj->pltrel = (const Elf_Rel *)
570 (obj->relocbase + dynp->d_un.d_ptr);
574 obj->pltrelsize = dynp->d_un.d_val;
578 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
582 obj->relasize = dynp->d_un.d_val;
586 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
590 plttype = dynp->d_un.d_val;
591 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
595 obj->symtab = (const Elf_Sym *)
596 (obj->relocbase + dynp->d_un.d_ptr);
600 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
604 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
608 obj->strsize = dynp->d_un.d_val;
613 const Elf_Hashelt *hashtab = (const Elf_Hashelt *)
614 (obj->relocbase + dynp->d_un.d_ptr);
615 obj->nbuckets = hashtab[0];
616 obj->nchains = hashtab[1];
617 obj->buckets = hashtab + 2;
618 obj->chains = obj->buckets + obj->nbuckets;
624 Needed_Entry *nep = NEW(Needed_Entry);
625 nep->name = dynp->d_un.d_val;
630 needed_tail = &nep->next;
635 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
643 obj->symbolic = true;
647 case DT_RUNPATH: /* XXX: process separately */
649 * We have to wait until later to process this, because we
650 * might not have gotten the address of the string table yet.
656 /* Not used by the dynamic linker. */
660 obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
664 obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
668 /* XXX - not implemented yet */
670 dbg("Filling in DT_DEBUG entry");
671 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
675 if (dynp->d_un.d_val & DF_ORIGIN) {
676 obj->origin_path = xmalloc(PATH_MAX);
677 if (rtld_dirname(obj->path, obj->origin_path) == -1)
680 if (dynp->d_un.d_val & DF_SYMBOLIC)
681 obj->symbolic = true;
682 if (dynp->d_un.d_val & DF_TEXTREL)
684 if (dynp->d_un.d_val & DF_BIND_NOW)
685 obj->bind_now = true;
686 if (dynp->d_un.d_val & DF_STATIC_TLS)
692 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
701 if (plttype == DT_RELA) {
702 obj->pltrela = (const Elf_Rela *) obj->pltrel;
704 obj->pltrelasize = obj->pltrelsize;
708 if (dyn_rpath != NULL)
709 obj->rpath = obj->strtab + dyn_rpath->d_un.d_val;
713 * Process a shared object's program header. This is used only for the
714 * main program, when the kernel has already loaded the main program
715 * into memory before calling the dynamic linker. It creates and
716 * returns an Obj_Entry structure.
719 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
722 const Elf_Phdr *phlimit = phdr + phnum;
727 for (ph = phdr; ph < phlimit; ph++) {
728 switch (ph->p_type) {
731 if ((const Elf_Phdr *)ph->p_vaddr != phdr) {
732 _rtld_error("%s: invalid PT_PHDR", path);
735 obj->phdr = (const Elf_Phdr *) ph->p_vaddr;
736 obj->phsize = ph->p_memsz;
740 obj->interp = (const char *) ph->p_vaddr;
744 if (nsegs == 0) { /* First load segment */
745 obj->vaddrbase = trunc_page(ph->p_vaddr);
746 obj->mapbase = (caddr_t) obj->vaddrbase;
747 obj->relocbase = obj->mapbase - obj->vaddrbase;
748 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
750 } else { /* Last load segment */
751 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
758 obj->dynamic = (const Elf_Dyn *) ph->p_vaddr;
763 obj->tlssize = ph->p_memsz;
764 obj->tlsalign = ph->p_align;
765 obj->tlsinitsize = ph->p_filesz;
766 obj->tlsinit = (void*) ph->p_vaddr;
771 _rtld_error("%s: too few PT_LOAD segments", path);
780 dlcheck(void *handle)
784 for (obj = obj_list; obj != NULL; obj = obj->next)
785 if (obj == (Obj_Entry *) handle)
788 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
789 _rtld_error("Invalid shared object handle %p", handle);
796 * If the given object is already in the donelist, return true. Otherwise
797 * add the object to the list and return false.
800 donelist_check(DoneList *dlp, const Obj_Entry *obj)
804 for (i = 0; i < dlp->num_used; i++)
805 if (dlp->objs[i] == obj)
808 * Our donelist allocation should always be sufficient. But if
809 * our threads locking isn't working properly, more shared objects
810 * could have been loaded since we allocated the list. That should
811 * never happen, but we'll handle it properly just in case it does.
813 if (dlp->num_used < dlp->num_alloc)
814 dlp->objs[dlp->num_used++] = obj;
819 * Hash function for symbol table lookup. Don't even think about changing
820 * this. It is specified by the System V ABI.
823 elf_hash(const char *name)
825 const unsigned char *p = (const unsigned char *) name;
831 if ((g = h & 0xf0000000) != 0)
839 * Find the library with the given name, and return its full pathname.
840 * The returned string is dynamically allocated. Generates an error
841 * message and returns NULL if the library cannot be found.
843 * If the second argument is non-NULL, then it refers to an already-
844 * loaded shared object, whose library search path will be searched.
846 * The search order is:
848 * rpath in the referencing file
853 find_library(const char *xname, const Obj_Entry *refobj)
858 if (strchr(xname, '/') != NULL) { /* Hard coded pathname */
859 if (xname[0] != '/' && !trust) {
860 _rtld_error("Absolute pathname required for shared object \"%s\"",
864 return xstrdup(xname);
867 if (libmap_disable || (refobj == NULL) ||
868 (name = lm_find(refobj->path, xname)) == NULL)
869 name = (char *)xname;
871 dbg(" Searching for \"%s\"", name);
873 if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
875 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
876 (pathname = search_library_path(name, gethints())) != NULL ||
877 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
880 if(refobj != NULL && refobj->path != NULL) {
881 _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
882 name, basename(refobj->path));
884 _rtld_error("Shared object \"%s\" not found", name);
890 * Given a symbol number in a referencing object, find the corresponding
891 * definition of the symbol. Returns a pointer to the symbol, or NULL if
892 * no definition was found. Returns a pointer to the Obj_Entry of the
893 * defining object via the reference parameter DEFOBJ_OUT.
896 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
897 const Obj_Entry **defobj_out, bool in_plt, SymCache *cache)
901 const Obj_Entry *defobj;
906 * If we have already found this symbol, get the information from
909 if (symnum >= refobj->nchains)
910 return NULL; /* Bad object */
911 if (cache != NULL && cache[symnum].sym != NULL) {
912 *defobj_out = cache[symnum].obj;
913 return cache[symnum].sym;
916 ref = refobj->symtab + symnum;
917 name = refobj->strtab + ref->st_name;
921 * We don't have to do a full scale lookup if the symbol is local.
922 * We know it will bind to the instance in this load module; to
923 * which we already have a pointer (ie ref). By not doing a lookup,
924 * we not only improve performance, but it also avoids unresolvable
925 * symbols when local symbols are not in the hash table. This has
926 * been seen with the ia64 toolchain.
928 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
929 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
930 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
933 hash = elf_hash(name);
934 def = symlook_default(name, hash, refobj, &defobj, in_plt);
941 * If we found no definition and the reference is weak, treat the
942 * symbol as having the value zero.
944 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
950 *defobj_out = defobj;
951 /* Record the information in the cache to avoid subsequent lookups. */
953 cache[symnum].sym = def;
954 cache[symnum].obj = defobj;
957 if (refobj != &obj_rtld)
958 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
964 * Return the search path from the ldconfig hints file, reading it if
965 * necessary. Returns NULL if there are problems with the hints file,
966 * or if the search path there is empty.
975 struct elfhints_hdr hdr;
978 /* Keep from trying again in case the hints file is bad. */
981 if ((fd = open(_PATH_ELF_HINTS, O_RDONLY)) == -1)
983 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
984 hdr.magic != ELFHINTS_MAGIC ||
989 p = xmalloc(hdr.dirlistlen + 1);
990 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
991 read(fd, p, hdr.dirlistlen + 1) != (ssize_t)hdr.dirlistlen + 1) {
999 return hints[0] != '\0' ? hints : NULL;
1003 init_dag(Obj_Entry *root)
1007 donelist_init(&donelist);
1008 init_dag1(root, root, &donelist);
1012 init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *dlp)
1014 const Needed_Entry *needed;
1016 if (donelist_check(dlp, obj))
1020 objlist_push_tail(&obj->dldags, root);
1021 objlist_push_tail(&root->dagmembers, obj);
1022 for (needed = obj->needed; needed != NULL; needed = needed->next)
1023 if (needed->obj != NULL)
1024 init_dag1(root, needed->obj, dlp);
1028 * Initialize the dynamic linker. The argument is the address at which
1029 * the dynamic linker has been mapped into memory. The primary task of
1030 * this function is to relocate the dynamic linker.
1033 init_rtld(caddr_t mapbase)
1035 Obj_Entry objtmp; /* Temporary rtld object */
1038 * Conjure up an Obj_Entry structure for the dynamic linker.
1040 * The "path" member can't be initialized yet because string constatns
1041 * cannot yet be acessed. Below we will set it correctly.
1043 memset(&objtmp, 0, sizeof(objtmp));
1046 objtmp.mapbase = mapbase;
1048 objtmp.relocbase = mapbase;
1050 if (RTLD_IS_DYNAMIC()) {
1051 objtmp.dynamic = rtld_dynamic(&objtmp);
1052 digest_dynamic(&objtmp, 1);
1053 assert(objtmp.needed == NULL);
1054 assert(!objtmp.textrel);
1057 * Temporarily put the dynamic linker entry into the object list, so
1058 * that symbols can be found.
1061 relocate_objects(&objtmp, true, &objtmp);
1064 /* Initialize the object list. */
1065 obj_tail = &obj_list;
1067 /* Now that non-local variables can be accesses, copy out obj_rtld. */
1068 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1070 /* Replace the path with a dynamically allocated copy. */
1071 obj_rtld.path = xstrdup(PATH_RTLD);
1073 r_debug.r_brk = r_debug_state;
1074 r_debug.r_state = RT_CONSISTENT;
1078 * Add the init functions from a needed object list (and its recursive
1079 * needed objects) to "list". This is not used directly; it is a helper
1080 * function for initlist_add_objects(). The write lock must be held
1081 * when this function is called.
1084 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1086 /* Recursively process the successor needed objects. */
1087 if (needed->next != NULL)
1088 initlist_add_neededs(needed->next, list);
1090 /* Process the current needed object. */
1091 if (needed->obj != NULL)
1092 initlist_add_objects(needed->obj, &needed->obj->next, list);
1096 * Scan all of the DAGs rooted in the range of objects from "obj" to
1097 * "tail" and add their init functions to "list". This recurses over
1098 * the DAGs and ensure the proper init ordering such that each object's
1099 * needed libraries are initialized before the object itself. At the
1100 * same time, this function adds the objects to the global finalization
1101 * list "list_fini" in the opposite order. The write lock must be
1102 * held when this function is called.
1105 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1109 obj->init_done = true;
1111 /* Recursively process the successor objects. */
1112 if (&obj->next != tail)
1113 initlist_add_objects(obj->next, tail, list);
1115 /* Recursively process the needed objects. */
1116 if (obj->needed != NULL)
1117 initlist_add_neededs(obj->needed, list);
1119 /* Add the object to the init list. */
1120 if (obj->init != (Elf_Addr)NULL)
1121 objlist_push_tail(list, obj);
1123 /* Add the object to the global fini list in the reverse order. */
1124 if (obj->fini != (Elf_Addr)NULL)
1125 objlist_push_head(&list_fini, obj);
1129 #define FPTR_TARGET(f) ((Elf_Addr) (f))
1133 is_exported(const Elf_Sym *def)
1136 const func_ptr_type *p;
1138 value = (Elf_Addr)(obj_rtld.relocbase + def->st_value);
1139 for (p = exports; *p != NULL; p++)
1140 if (FPTR_TARGET(*p) == value)
1146 * Given a shared object, traverse its list of needed objects, and load
1147 * each of them. Returns 0 on success. Generates an error message and
1148 * returns -1 on failure.
1151 load_needed_objects(Obj_Entry *first)
1155 for (obj = first; obj != NULL; obj = obj->next) {
1156 Needed_Entry *needed;
1158 for (needed = obj->needed; needed != NULL; needed = needed->next) {
1159 const char *name = obj->strtab + needed->name;
1160 char *path = find_library(name, obj);
1163 if (path == NULL && !ld_tracing)
1167 needed->obj = load_object(path);
1168 if (needed->obj == NULL && !ld_tracing)
1169 return -1; /* XXX - cleanup */
1178 load_preload_objects(void)
1180 char *p = ld_preload;
1181 static const char delim[] = " \t:;";
1186 p += strspn(p, delim);
1187 while (*p != '\0') {
1188 size_t len = strcspn(p, delim);
1194 if ((path = find_library(p, NULL)) == NULL)
1196 if (load_object(path) == NULL)
1197 return -1; /* XXX - cleanup */
1200 p += strspn(p, delim);
1206 * Load a shared object into memory, if it is not already loaded. The
1207 * argument must be a string allocated on the heap. This function assumes
1208 * responsibility for freeing it when necessary.
1210 * Returns a pointer to the Obj_Entry for the object. Returns NULL
1214 load_object(char *path)
1220 for (obj = obj_list->next; obj != NULL; obj = obj->next)
1221 if (strcmp(obj->path, path) == 0)
1225 * If we didn't find a match by pathname, open the file and check
1226 * again by device and inode. This avoids false mismatches caused
1227 * by multiple links or ".." in pathnames.
1229 * To avoid a race, we open the file and use fstat() rather than
1233 if ((fd = open(path, O_RDONLY)) == -1) {
1234 _rtld_error("Cannot open \"%s\"", path);
1237 if (fstat(fd, &sb) == -1) {
1238 _rtld_error("Cannot fstat \"%s\"", path);
1242 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
1243 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev) {
1250 if (obj == NULL) { /* First use of this object, so we must map it in */
1251 dbg("loading \"%s\"", path);
1252 obj = map_object(fd, path, &sb);
1260 digest_dynamic(obj, 0);
1263 obj_tail = &obj->next;
1265 linkmap_add(obj); /* for GDB & dlinfo() */
1267 dbg(" %p .. %p: %s", obj->mapbase,
1268 obj->mapbase + obj->mapsize - 1, obj->path);
1270 dbg(" WARNING: %s has impure text", obj->path);
1278 obj_from_addr(const void *addr)
1282 for (obj = obj_list; obj != NULL; obj = obj->next) {
1283 if (addr < (void *) obj->mapbase)
1285 if (addr < (void *) (obj->mapbase + obj->mapsize))
1292 * Call the finalization functions for each of the objects in "list"
1293 * which are unreferenced. All of the objects are expected to have
1294 * non-NULL fini functions.
1297 objlist_call_fini(Objlist *list)
1303 * Preserve the current error message since a fini function might
1304 * call into the dynamic linker and overwrite it.
1306 saved_msg = errmsg_save();
1307 STAILQ_FOREACH(elm, list, link) {
1308 if (elm->obj->refcount == 0) {
1309 dbg("calling fini function for %s at %p", elm->obj->path,
1310 (void *)elm->obj->fini);
1311 call_initfini_pointer(elm->obj, elm->obj->fini);
1314 errmsg_restore(saved_msg);
1318 * Call the initialization functions for each of the objects in
1319 * "list". All of the objects are expected to have non-NULL init
1323 objlist_call_init(Objlist *list)
1329 * Preserve the current error message since an init function might
1330 * call into the dynamic linker and overwrite it.
1332 saved_msg = errmsg_save();
1333 STAILQ_FOREACH(elm, list, link) {
1334 dbg("calling init function for %s at %p", elm->obj->path,
1335 (void *)elm->obj->init);
1336 call_initfini_pointer(elm->obj, elm->obj->init);
1338 errmsg_restore(saved_msg);
1342 objlist_clear(Objlist *list)
1346 while (!STAILQ_EMPTY(list)) {
1347 elm = STAILQ_FIRST(list);
1348 STAILQ_REMOVE_HEAD(list, link);
1353 static Objlist_Entry *
1354 objlist_find(Objlist *list, const Obj_Entry *obj)
1358 STAILQ_FOREACH(elm, list, link)
1359 if (elm->obj == obj)
1365 objlist_init(Objlist *list)
1371 objlist_push_head(Objlist *list, Obj_Entry *obj)
1375 elm = NEW(Objlist_Entry);
1377 STAILQ_INSERT_HEAD(list, elm, link);
1381 objlist_push_tail(Objlist *list, Obj_Entry *obj)
1385 elm = NEW(Objlist_Entry);
1387 STAILQ_INSERT_TAIL(list, elm, link);
1391 objlist_remove(Objlist *list, Obj_Entry *obj)
1395 if ((elm = objlist_find(list, obj)) != NULL) {
1396 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1402 * Remove all of the unreferenced objects from "list".
1405 objlist_remove_unref(Objlist *list)
1410 STAILQ_INIT(&newlist);
1411 while (!STAILQ_EMPTY(list)) {
1412 elm = STAILQ_FIRST(list);
1413 STAILQ_REMOVE_HEAD(list, link);
1414 if (elm->obj->refcount == 0)
1417 STAILQ_INSERT_TAIL(&newlist, elm, link);
1423 * Relocate newly-loaded shared objects. The argument is a pointer to
1424 * the Obj_Entry for the first such object. All objects from the first
1425 * to the end of the list of objects are relocated. Returns 0 on success,
1429 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj)
1433 for (obj = first; obj != NULL; obj = obj->next) {
1435 dbg("relocating \"%s\"", obj->path);
1436 if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
1437 obj->symtab == NULL || obj->strtab == NULL) {
1438 _rtld_error("%s: Shared object has no run-time symbol table",
1444 /* There are relocations to the write-protected text segment. */
1445 if (mprotect(obj->mapbase, obj->textsize,
1446 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
1447 _rtld_error("%s: Cannot write-enable text segment: %s",
1448 obj->path, strerror(errno));
1453 /* Process the non-PLT relocations. */
1454 if (reloc_non_plt(obj, rtldobj))
1457 if (obj->textrel) { /* Re-protected the text segment. */
1458 if (mprotect(obj->mapbase, obj->textsize,
1459 PROT_READ|PROT_EXEC) == -1) {
1460 _rtld_error("%s: Cannot write-protect text segment: %s",
1461 obj->path, strerror(errno));
1466 /* Process the PLT relocations. */
1467 if (reloc_plt(obj) == -1)
1469 /* Relocate the jump slots if we are doing immediate binding. */
1470 if (obj->bind_now || bind_now)
1471 if (reloc_jmpslots(obj) == -1)
1476 * Set up the magic number and version in the Obj_Entry. These
1477 * were checked in the crt1.o from the original ElfKit, so we
1478 * set them for backward compatibility.
1480 obj->magic = RTLD_MAGIC;
1481 obj->version = RTLD_VERSION;
1483 /* Set the special PLT or GOT entries. */
1491 * Cleanup procedure. It will be called (by the atexit mechanism) just
1492 * before the process exits.
1500 /* Clear all the reference counts so the fini functions will be called. */
1501 for (obj = obj_list; obj != NULL; obj = obj->next)
1503 objlist_call_fini(&list_fini);
1504 /* No need to remove the items from the list, since we are exiting. */
1505 if (!libmap_disable)
1510 path_enumerate(const char *path, path_enum_proc callback, void *arg)
1518 path += strspn(path, ":;");
1519 while (*path != '\0') {
1523 len = strcspn(path, ":;");
1525 trans = lm_findn(NULL, path, len);
1527 res = callback(trans, strlen(trans), arg);
1530 res = callback(path, len, arg);
1536 path += strspn(path, ":;");
1542 struct try_library_args {
1550 try_library_path(const char *dir, size_t dirlen, void *param)
1552 struct try_library_args *arg;
1555 if (*dir == '/' || trust) {
1558 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
1561 pathname = arg->buffer;
1562 strncpy(pathname, dir, dirlen);
1563 pathname[dirlen] = '/';
1564 strcpy(pathname + dirlen + 1, arg->name);
1566 dbg(" Trying \"%s\"", pathname);
1567 if (access(pathname, F_OK) == 0) { /* We found it */
1568 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
1569 strcpy(pathname, arg->buffer);
1577 search_library_path(const char *name, const char *path)
1580 struct try_library_args arg;
1586 arg.namelen = strlen(name);
1587 arg.buffer = xmalloc(PATH_MAX);
1588 arg.buflen = PATH_MAX;
1590 p = path_enumerate(path, try_library_path, &arg);
1598 dlclose(void *handle)
1603 lockstate = wlock_acquire(rtld_bind_lock);
1604 root = dlcheck(handle);
1606 wlock_release(rtld_bind_lock, lockstate);
1610 /* Unreference the object and its dependencies. */
1611 root->dl_refcount--;
1615 if (root->refcount == 0) {
1617 * The object is no longer referenced, so we must unload it.
1618 * First, call the fini functions with no locks held.
1620 wlock_release(rtld_bind_lock, lockstate);
1621 objlist_call_fini(&list_fini);
1622 lockstate = wlock_acquire(rtld_bind_lock);
1623 objlist_remove_unref(&list_fini);
1625 /* Finish cleaning up the newly-unreferenced objects. */
1626 GDB_STATE(RT_DELETE,&root->linkmap);
1627 unload_object(root);
1628 GDB_STATE(RT_CONSISTENT,NULL);
1630 wlock_release(rtld_bind_lock, lockstate);
1637 char *msg = error_message;
1638 error_message = NULL;
1643 * This function is deprecated and has no effect.
1646 dllockinit(void *context,
1647 void *(*lock_create)(void *context),
1648 void (*rlock_acquire)(void *lock),
1649 void (*wlock_acquire)(void *lock),
1650 void (*lock_release)(void *lock),
1651 void (*lock_destroy)(void *lock),
1652 void (*context_destroy)(void *context))
1654 static void *cur_context;
1655 static void (*cur_context_destroy)(void *);
1657 /* Just destroy the context from the previous call, if necessary. */
1658 if (cur_context_destroy != NULL)
1659 cur_context_destroy(cur_context);
1660 cur_context = context;
1661 cur_context_destroy = context_destroy;
1665 dlopen(const char *name, int mode)
1667 Obj_Entry **old_obj_tail;
1670 int result, lockstate;
1672 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
1673 if (ld_tracing != NULL)
1674 environ = (char **)*get_program_var_addr("environ");
1676 objlist_init(&initlist);
1678 lockstate = wlock_acquire(rtld_bind_lock);
1679 GDB_STATE(RT_ADD,NULL);
1681 old_obj_tail = obj_tail;
1687 char *path = find_library(name, obj_main);
1689 obj = load_object(path);
1694 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
1695 objlist_push_tail(&list_global, obj);
1696 mode &= RTLD_MODEMASK;
1697 if (*old_obj_tail != NULL) { /* We loaded something new. */
1698 assert(*old_obj_tail == obj);
1700 result = load_needed_objects(obj);
1701 if (result != -1 && ld_tracing)
1705 (init_dag(obj), relocate_objects(obj, mode == RTLD_NOW,
1706 &obj_rtld)) == -1) {
1709 if (obj->refcount == 0)
1713 /* Make list of init functions to call. */
1714 initlist_add_objects(obj, &obj->next, &initlist);
1718 /* Bump the reference counts for objects on this DAG. */
1726 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
1728 /* Call the init functions with no locks held. */
1729 wlock_release(rtld_bind_lock, lockstate);
1730 objlist_call_init(&initlist);
1731 lockstate = wlock_acquire(rtld_bind_lock);
1732 objlist_clear(&initlist);
1733 wlock_release(rtld_bind_lock, lockstate);
1736 trace_loaded_objects(obj);
1737 wlock_release(rtld_bind_lock, lockstate);
1742 dlsym(void *handle, const char *name)
1744 const Obj_Entry *obj;
1747 const Obj_Entry *defobj;
1750 hash = elf_hash(name);
1754 lockstate = rlock_acquire(rtld_bind_lock);
1755 if (handle == NULL || handle == RTLD_NEXT ||
1756 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
1759 retaddr = __builtin_return_address(0); /* __GNUC__ only */
1760 if ((obj = obj_from_addr(retaddr)) == NULL) {
1761 _rtld_error("Cannot determine caller's shared object");
1762 rlock_release(rtld_bind_lock, lockstate);
1765 if (handle == NULL) { /* Just the caller's shared object. */
1766 def = symlook_obj(name, hash, obj, true);
1768 } else if (handle == RTLD_NEXT || /* Objects after caller's */
1769 handle == RTLD_SELF) { /* ... caller included */
1770 if (handle == RTLD_NEXT)
1772 for (; obj != NULL; obj = obj->next) {
1773 if ((def = symlook_obj(name, hash, obj, true)) != NULL) {
1779 assert(handle == RTLD_DEFAULT);
1780 def = symlook_default(name, hash, obj, &defobj, true);
1783 if ((obj = dlcheck(handle)) == NULL) {
1784 rlock_release(rtld_bind_lock, lockstate);
1788 if (obj->mainprog) {
1791 /* Search main program and all libraries loaded by it. */
1792 donelist_init(&donelist);
1793 def = symlook_list(name, hash, &list_main, &defobj, true,
1797 * XXX - This isn't correct. The search should include the whole
1798 * DAG rooted at the given object.
1800 def = symlook_obj(name, hash, obj, true);
1806 rlock_release(rtld_bind_lock, lockstate);
1809 * The value required by the caller is derived from the value
1810 * of the symbol. For the ia64 architecture, we need to
1811 * construct a function descriptor which the caller can use to
1812 * call the function with the right 'gp' value. For other
1813 * architectures and for non-functions, the value is simply
1814 * the relocated value of the symbol.
1816 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
1817 return make_function_pointer(def, defobj);
1819 return defobj->relocbase + def->st_value;
1822 _rtld_error("Undefined symbol \"%s\"", name);
1823 rlock_release(rtld_bind_lock, lockstate);
1828 dladdr(const void *addr, Dl_info *info)
1830 const Obj_Entry *obj;
1833 unsigned long symoffset;
1836 lockstate = rlock_acquire(rtld_bind_lock);
1837 obj = obj_from_addr(addr);
1839 _rtld_error("No shared object contains address");
1840 rlock_release(rtld_bind_lock, lockstate);
1843 info->dli_fname = obj->path;
1844 info->dli_fbase = obj->mapbase;
1845 info->dli_saddr = (void *)0;
1846 info->dli_sname = NULL;
1849 * Walk the symbol list looking for the symbol whose address is
1850 * closest to the address sent in.
1852 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
1853 def = obj->symtab + symoffset;
1856 * For skip the symbol if st_shndx is either SHN_UNDEF or
1859 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
1863 * If the symbol is greater than the specified address, or if it
1864 * is further away from addr than the current nearest symbol,
1867 symbol_addr = obj->relocbase + def->st_value;
1868 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
1871 /* Update our idea of the nearest symbol. */
1872 info->dli_sname = obj->strtab + def->st_name;
1873 info->dli_saddr = symbol_addr;
1876 if (info->dli_saddr == addr)
1879 rlock_release(rtld_bind_lock, lockstate);
1884 dlinfo(void *handle, int request, void *p)
1886 const Obj_Entry *obj;
1887 int error, lockstate;
1889 lockstate = rlock_acquire(rtld_bind_lock);
1891 if (handle == NULL || handle == RTLD_SELF) {
1894 retaddr = __builtin_return_address(0); /* __GNUC__ only */
1895 if ((obj = obj_from_addr(retaddr)) == NULL)
1896 _rtld_error("Cannot determine caller's shared object");
1898 obj = dlcheck(handle);
1901 rlock_release(rtld_bind_lock, lockstate);
1907 case RTLD_DI_LINKMAP:
1908 *((struct link_map const **)p) = &obj->linkmap;
1910 case RTLD_DI_ORIGIN:
1911 error = rtld_dirname(obj->path, p);
1914 case RTLD_DI_SERINFOSIZE:
1915 case RTLD_DI_SERINFO:
1916 error = do_search_info(obj, request, (struct dl_serinfo *)p);
1920 _rtld_error("Invalid request %d passed to dlinfo()", request);
1924 rlock_release(rtld_bind_lock, lockstate);
1929 struct fill_search_info_args {
1932 Dl_serinfo *serinfo;
1933 Dl_serpath *serpath;
1938 fill_search_info(const char *dir, size_t dirlen, void *param)
1940 struct fill_search_info_args *arg;
1944 if (arg->request == RTLD_DI_SERINFOSIZE) {
1945 arg->serinfo->dls_cnt ++;
1946 arg->serinfo->dls_size += dirlen + 1;
1948 struct dl_serpath *s_entry;
1950 s_entry = arg->serpath;
1951 s_entry->dls_name = arg->strspace;
1952 s_entry->dls_flags = arg->flags;
1954 strncpy(arg->strspace, dir, dirlen);
1955 arg->strspace[dirlen] = '\0';
1957 arg->strspace += dirlen + 1;
1965 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
1967 struct dl_serinfo _info;
1968 struct fill_search_info_args args;
1970 args.request = RTLD_DI_SERINFOSIZE;
1971 args.serinfo = &_info;
1973 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1976 path_enumerate(ld_library_path, fill_search_info, &args);
1977 path_enumerate(obj->rpath, fill_search_info, &args);
1978 path_enumerate(gethints(), fill_search_info, &args);
1979 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
1982 if (request == RTLD_DI_SERINFOSIZE) {
1983 info->dls_size = _info.dls_size;
1984 info->dls_cnt = _info.dls_cnt;
1988 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
1989 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
1993 args.request = RTLD_DI_SERINFO;
1994 args.serinfo = info;
1995 args.serpath = &info->dls_serpath[0];
1996 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
1998 args.flags = LA_SER_LIBPATH;
1999 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
2002 args.flags = LA_SER_RUNPATH;
2003 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
2006 args.flags = LA_SER_CONFIG;
2007 if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
2010 args.flags = LA_SER_DEFAULT;
2011 if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
2017 rtld_dirname(const char *path, char *bname)
2021 /* Empty or NULL string gets treated as "." */
2022 if (path == NULL || *path == '\0') {
2028 /* Strip trailing slashes */
2029 endp = path + strlen(path) - 1;
2030 while (endp > path && *endp == '/')
2033 /* Find the start of the dir */
2034 while (endp > path && *endp != '/')
2037 /* Either the dir is "/" or there are no slashes */
2039 bname[0] = *endp == '/' ? '/' : '.';
2045 } while (endp > path && *endp == '/');
2048 if (endp - path + 2 > PATH_MAX)
2050 _rtld_error("Filename is too long: %s", path);
2054 strncpy(bname, path, endp - path + 1);
2055 bname[endp - path + 1] = '\0';
2060 linkmap_add(Obj_Entry *obj)
2062 struct link_map *l = &obj->linkmap;
2063 struct link_map *prev;
2065 obj->linkmap.l_name = obj->path;
2066 obj->linkmap.l_addr = obj->mapbase;
2067 obj->linkmap.l_ld = obj->dynamic;
2069 /* GDB needs load offset on MIPS to use the symbols */
2070 obj->linkmap.l_offs = obj->relocbase;
2073 if (r_debug.r_map == NULL) {
2079 * Scan to the end of the list, but not past the entry for the
2080 * dynamic linker, which we want to keep at the very end.
2082 for (prev = r_debug.r_map;
2083 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
2084 prev = prev->l_next)
2087 /* Link in the new entry. */
2089 l->l_next = prev->l_next;
2090 if (l->l_next != NULL)
2091 l->l_next->l_prev = l;
2096 linkmap_delete(Obj_Entry *obj)
2098 struct link_map *l = &obj->linkmap;
2100 if (l->l_prev == NULL) {
2101 if ((r_debug.r_map = l->l_next) != NULL)
2102 l->l_next->l_prev = NULL;
2106 if ((l->l_prev->l_next = l->l_next) != NULL)
2107 l->l_next->l_prev = l->l_prev;
2111 * Function for the debugger to set a breakpoint on to gain control.
2113 * The two parameters allow the debugger to easily find and determine
2114 * what the runtime loader is doing and to whom it is doing it.
2116 * When the loadhook trap is hit (r_debug_state, set at program
2117 * initialization), the arguments can be found on the stack:
2119 * +8 struct link_map *m
2120 * +4 struct r_debug *rd
2124 r_debug_state(struct r_debug* rd, struct link_map *m)
2129 * Get address of the pointer variable in the main program.
2131 static const void **
2132 get_program_var_addr(const char *name)
2134 const Obj_Entry *obj;
2137 hash = elf_hash(name);
2138 for (obj = obj_main; obj != NULL; obj = obj->next) {
2141 if ((def = symlook_obj(name, hash, obj, false)) != NULL) {
2144 addr = (const void **)(obj->relocbase + def->st_value);
2152 * Set a pointer variable in the main program to the given value. This
2153 * is used to set key variables such as "environ" before any of the
2154 * init functions are called.
2157 set_program_var(const char *name, const void *value)
2161 if ((addr = get_program_var_addr(name)) != NULL) {
2162 dbg("\"%s\": *%p <-- %p", name, addr, value);
2168 * Given a symbol name in a referencing object, find the corresponding
2169 * definition of the symbol. Returns a pointer to the symbol, or NULL if
2170 * no definition was found. Returns a pointer to the Obj_Entry of the
2171 * defining object via the reference parameter DEFOBJ_OUT.
2173 static const Elf_Sym *
2174 symlook_default(const char *name, unsigned long hash,
2175 const Obj_Entry *refobj, const Obj_Entry **defobj_out, bool in_plt)
2179 const Elf_Sym *symp;
2180 const Obj_Entry *obj;
2181 const Obj_Entry *defobj;
2182 const Objlist_Entry *elm;
2185 donelist_init(&donelist);
2187 /* Look first in the referencing object if linked symbolically. */
2188 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
2189 symp = symlook_obj(name, hash, refobj, in_plt);
2196 /* Search all objects loaded at program start up. */
2197 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2198 symp = symlook_list(name, hash, &list_main, &obj, in_plt, &donelist);
2200 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2206 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
2207 STAILQ_FOREACH(elm, &list_global, link) {
2208 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2210 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt,
2213 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2219 /* Search all dlopened DAGs containing the referencing object. */
2220 STAILQ_FOREACH(elm, &refobj->dldags, link) {
2221 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2223 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt,
2226 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2233 * Search the dynamic linker itself, and possibly resolve the
2234 * symbol from there. This is how the application links to
2235 * dynamic linker services such as dlopen. Only the values listed
2236 * in the "exports" array can be resolved from the dynamic linker.
2238 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2239 symp = symlook_obj(name, hash, &obj_rtld, in_plt);
2240 if (symp != NULL && is_exported(symp)) {
2247 *defobj_out = defobj;
2251 static const Elf_Sym *
2252 symlook_list(const char *name, unsigned long hash, Objlist *objlist,
2253 const Obj_Entry **defobj_out, bool in_plt, DoneList *dlp)
2255 const Elf_Sym *symp;
2257 const Obj_Entry *defobj;
2258 const Objlist_Entry *elm;
2262 STAILQ_FOREACH(elm, objlist, link) {
2263 if (donelist_check(dlp, elm->obj))
2265 if ((symp = symlook_obj(name, hash, elm->obj, in_plt)) != NULL) {
2266 if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
2269 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2275 *defobj_out = defobj;
2280 * Search the symbol table of a single shared object for a symbol of
2281 * the given name. Returns a pointer to the symbol, or NULL if no
2282 * definition was found.
2284 * The symbol's hash value is passed in for efficiency reasons; that
2285 * eliminates many recomputations of the hash value.
2288 symlook_obj(const char *name, unsigned long hash, const Obj_Entry *obj,
2291 if (obj->buckets != NULL) {
2292 unsigned long symnum = obj->buckets[hash % obj->nbuckets];
2294 while (symnum != STN_UNDEF) {
2295 const Elf_Sym *symp;
2298 if (symnum >= obj->nchains)
2299 return NULL; /* Bad object */
2300 symp = obj->symtab + symnum;
2301 strp = obj->strtab + symp->st_name;
2303 if (name[0] == strp[0] && strcmp(name, strp) == 0)
2304 return symp->st_shndx != SHN_UNDEF ||
2305 (!in_plt && symp->st_value != 0 &&
2306 ELF_ST_TYPE(symp->st_info) == STT_FUNC) ? symp : NULL;
2308 symnum = obj->chains[symnum];
2315 trace_loaded_objects(Obj_Entry *obj)
2317 char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
2320 if ((main_local = getenv(LD_ "TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
2323 if ((fmt1 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT1")) == NULL)
2324 fmt1 = "\t%o => %p (%x)\n";
2326 if ((fmt2 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT2")) == NULL)
2327 fmt2 = "\t%o (%x)\n";
2329 list_containers = getenv(LD_ "TRACE_LOADED_OBJECTS_ALL");
2331 for (; obj; obj = obj->next) {
2332 Needed_Entry *needed;
2336 if (list_containers && obj->needed != NULL)
2337 printf("%s:\n", obj->path);
2338 for (needed = obj->needed; needed; needed = needed->next) {
2339 if (needed->obj != NULL) {
2340 if (needed->obj->traced && !list_containers)
2342 needed->obj->traced = true;
2343 path = needed->obj->path;
2347 name = (char *)obj->strtab + needed->name;
2348 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
2350 fmt = is_lib ? fmt1 : fmt2;
2351 while ((c = *fmt++) != '\0') {
2377 printf("%s", main_local);
2380 printf("%s", obj_main->path);
2387 printf("%d", sodp->sod_major);
2390 printf("%d", sodp->sod_minor);
2397 printf("%p", needed->obj ? needed->obj->mapbase : 0);
2409 * Unload a dlopened object and its dependencies from memory and from
2410 * our data structures. It is assumed that the DAG rooted in the
2411 * object has already been unreferenced, and that the object has a
2412 * reference count of 0.
2415 unload_object(Obj_Entry *root)
2420 assert(root->refcount == 0);
2423 * Pass over the DAG removing unreferenced objects from
2424 * appropriate lists.
2426 unlink_object(root);
2428 /* Unmap all objects that are no longer referenced. */
2429 linkp = &obj_list->next;
2430 while ((obj = *linkp) != NULL) {
2431 if (obj->refcount == 0) {
2432 dbg("unloading \"%s\"", obj->path);
2433 munmap(obj->mapbase, obj->mapsize);
2434 linkmap_delete(obj);
2445 unlink_object(Obj_Entry *root)
2449 if (root->refcount == 0) {
2450 /* Remove the object from the RTLD_GLOBAL list. */
2451 objlist_remove(&list_global, root);
2453 /* Remove the object from all objects' DAG lists. */
2454 STAILQ_FOREACH(elm, &root->dagmembers , link) {
2455 objlist_remove(&elm->obj->dldags, root);
2456 if (elm->obj != root)
2457 unlink_object(elm->obj);
2463 ref_dag(Obj_Entry *root)
2467 STAILQ_FOREACH(elm, &root->dagmembers , link)
2468 elm->obj->refcount++;
2472 unref_dag(Obj_Entry *root)
2476 STAILQ_FOREACH(elm, &root->dagmembers , link)
2477 elm->obj->refcount--;
2481 * Common code for MD __tls_get_addr().
2484 tls_get_addr_common(Elf_Addr** dtvp, int index, size_t offset)
2486 Elf_Addr* dtv = *dtvp;
2488 /* Check dtv generation in case new modules have arrived */
2489 if (dtv[0] != tls_dtv_generation) {
2493 newdtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
2495 if (to_copy > tls_max_index)
2496 to_copy = tls_max_index;
2497 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
2498 newdtv[0] = tls_dtv_generation;
2499 newdtv[1] = tls_max_index;
2504 /* Dynamically allocate module TLS if necessary */
2505 if (!dtv[index + 1])
2506 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
2508 return (void*) (dtv[index + 1] + offset);
2511 /* XXX not sure what variants to use for arm. */
2513 #if defined(__ia64__) || defined(__alpha__) || defined(__powerpc__)
2516 * Allocate Static TLS using the Variant I method.
2519 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
2524 Elf_Addr *dtv, *olddtv;
2528 size = tls_static_space;
2531 dtv = malloc((tls_max_index + 2) * sizeof(Elf_Addr));
2533 *(Elf_Addr**) tls = dtv;
2535 dtv[0] = tls_dtv_generation;
2536 dtv[1] = tls_max_index;
2540 * Copy the static TLS block over whole.
2542 memcpy(tls + tcbsize, oldtls + tcbsize, tls_static_space - tcbsize);
2545 * If any dynamic TLS blocks have been created tls_get_addr(),
2548 olddtv = *(Elf_Addr**) oldtls;
2549 for (i = 0; i < olddtv[1]; i++) {
2550 if (olddtv[i+2] < (Elf_Addr)oldtls ||
2551 olddtv[i+2] > (Elf_Addr)oldtls + tls_static_space) {
2552 dtv[i+2] = olddtv[i+2];
2558 * We assume that all tls blocks are allocated with the same
2559 * size and alignment.
2561 free_tls(oldtls, tcbsize, tcbalign);
2563 for (obj = objs; obj; obj = obj->next) {
2564 if (obj->tlsoffset) {
2565 addr = (Elf_Addr)tls + obj->tlsoffset;
2566 memset((void*) (addr + obj->tlsinitsize),
2567 0, obj->tlssize - obj->tlsinitsize);
2569 memcpy((void*) addr, obj->tlsinit,
2571 dtv[obj->tlsindex + 1] = addr;
2572 } else if (obj->tlsindex) {
2573 dtv[obj->tlsindex + 1] = 0;
2582 free_tls(void *tls, size_t tcbsize, size_t tcbalign)
2587 Elf_Addr tlsstart, tlsend;
2590 * Figure out the size of the initial TLS block so that we can
2591 * find stuff which __tls_get_addr() allocated dynamically.
2593 size = tls_static_space;
2595 dtv = ((Elf_Addr**)tls)[0];
2597 tlsstart = (Elf_Addr) tls;
2598 tlsend = tlsstart + size;
2599 for (i = 0; i < dtvsize; i++) {
2600 if (dtv[i+2] < tlsstart || dtv[i+2] > tlsend) {
2601 free((void*) dtv[i+2]);
2605 free((void*) tlsstart);
2610 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__)
2613 * Allocate Static TLS using the Variant II method.
2616 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
2621 Elf_Addr *dtv, *olddtv;
2622 Elf_Addr segbase, oldsegbase, addr;
2625 size = round(tls_static_space, tcbalign);
2627 assert(tcbsize >= 2*sizeof(Elf_Addr));
2628 tls = malloc(size + tcbsize);
2629 dtv = malloc((tls_max_index + 2) * sizeof(Elf_Addr));
2631 segbase = (Elf_Addr)(tls + size);
2632 ((Elf_Addr*)segbase)[0] = segbase;
2633 ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
2635 dtv[0] = tls_dtv_generation;
2636 dtv[1] = tls_max_index;
2640 * Copy the static TLS block over whole.
2642 oldsegbase = (Elf_Addr) oldtls;
2643 memcpy((void *)(segbase - tls_static_space),
2644 (const void *)(oldsegbase - tls_static_space),
2648 * If any dynamic TLS blocks have been created tls_get_addr(),
2651 olddtv = ((Elf_Addr**)oldsegbase)[1];
2652 for (i = 0; i < olddtv[1]; i++) {
2653 if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
2654 dtv[i+2] = olddtv[i+2];
2660 * We assume that this block was the one we created with
2661 * allocate_initial_tls().
2663 free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
2665 for (obj = objs; obj; obj = obj->next) {
2666 if (obj->tlsoffset) {
2667 addr = segbase - obj->tlsoffset;
2668 memset((void*) (addr + obj->tlsinitsize),
2669 0, obj->tlssize - obj->tlsinitsize);
2671 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
2672 dtv[obj->tlsindex + 1] = addr;
2673 } else if (obj->tlsindex) {
2674 dtv[obj->tlsindex + 1] = 0;
2679 return (void*) segbase;
2683 free_tls(void *tls, size_t tcbsize, size_t tcbalign)
2688 Elf_Addr tlsstart, tlsend;
2691 * Figure out the size of the initial TLS block so that we can
2692 * find stuff which ___tls_get_addr() allocated dynamically.
2694 size = round(tls_static_space, tcbalign);
2696 dtv = ((Elf_Addr**)tls)[1];
2698 tlsend = (Elf_Addr) tls;
2699 tlsstart = tlsend - size;
2700 for (i = 0; i < dtvsize; i++) {
2701 if (dtv[i+2] < tlsstart || dtv[i+2] > tlsend) {
2702 free((void*) dtv[i+2]);
2706 free((void*) tlsstart);
2712 * Allocate TLS block for module with given index.
2715 allocate_module_tls(int index)
2720 for (obj = obj_list; obj; obj = obj->next) {
2721 if (obj->tlsindex == index)
2725 _rtld_error("Can't find module with TLS index %d", index);
2729 p = malloc(obj->tlssize);
2730 memcpy(p, obj->tlsinit, obj->tlsinitsize);
2731 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
2737 allocate_tls_offset(Obj_Entry *obj)
2744 if (obj->tlssize == 0) {
2745 obj->tls_done = true;
2749 if (obj->tlsindex == 1)
2750 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
2752 off = calculate_tls_offset(tls_last_offset, tls_last_size,
2753 obj->tlssize, obj->tlsalign);
2756 * If we have already fixed the size of the static TLS block, we
2757 * must stay within that size. When allocating the static TLS, we
2758 * leave a small amount of space spare to be used for dynamically
2759 * loading modules which use static TLS.
2761 if (tls_static_space) {
2762 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
2766 tls_last_offset = obj->tlsoffset = off;
2767 tls_last_size = obj->tlssize;
2768 obj->tls_done = true;
2774 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
2776 return allocate_tls(obj_list, oldtls, tcbsize, tcbalign);
2780 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
2782 free_tls(tcb, tcbsize, tcbalign);