2 * Copyright 1996, 1997, 1998, 1999, 2000 John D. Polstra.
3 * Copyright 2003 Alexander Kabaev <kan@FreeBSD.ORG>.
4 * Copyright 2009, 2010, 2011 Konstantin Belousov <kib@FreeBSD.ORG>.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
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>
41 #include <sys/mount.h>
44 #include <sys/sysctl.h>
46 #include <sys/utsname.h>
47 #include <sys/ktrace.h>
63 #include "rtld_printf.h"
67 #define PATH_RTLD "/libexec/ld-elf.so.1"
69 #define PATH_RTLD "/libexec/ld-elf32.so.1"
73 typedef void (*func_ptr_type)();
74 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg);
77 * Function declarations.
79 static const char *basename(const char *);
80 static void die(void) __dead2;
81 static void digest_dynamic1(Obj_Entry *, int, const Elf_Dyn **,
83 static void digest_dynamic2(Obj_Entry *, const Elf_Dyn *, const Elf_Dyn *);
84 static void digest_dynamic(Obj_Entry *, int);
85 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
86 static Obj_Entry *dlcheck(void *);
87 static Obj_Entry *dlopen_object(const char *name, int fd, Obj_Entry *refobj,
88 int lo_flags, int mode);
89 static Obj_Entry *do_load_object(int, const char *, char *, struct stat *, int);
90 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
91 static bool donelist_check(DoneList *, const Obj_Entry *);
92 static void errmsg_restore(char *);
93 static char *errmsg_save(void);
94 static void *fill_search_info(const char *, size_t, void *);
95 static char *find_library(const char *, const Obj_Entry *);
96 static const char *gethints(void);
97 static void init_dag(Obj_Entry *);
98 static void init_rtld(caddr_t, Elf_Auxinfo **);
99 static void initlist_add_neededs(Needed_Entry *, Objlist *);
100 static void initlist_add_objects(Obj_Entry *, Obj_Entry **, Objlist *);
101 static void linkmap_add(Obj_Entry *);
102 static void linkmap_delete(Obj_Entry *);
103 static void load_filtees(Obj_Entry *, int flags, RtldLockState *);
104 static void unload_filtees(Obj_Entry *);
105 static int load_needed_objects(Obj_Entry *, int);
106 static int load_preload_objects(void);
107 static Obj_Entry *load_object(const char *, int fd, const Obj_Entry *, int);
108 static void map_stacks_exec(RtldLockState *);
109 static Obj_Entry *obj_from_addr(const void *);
110 static void objlist_call_fini(Objlist *, Obj_Entry *, RtldLockState *);
111 static void objlist_call_init(Objlist *, RtldLockState *);
112 static void objlist_clear(Objlist *);
113 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
114 static void objlist_init(Objlist *);
115 static void objlist_push_head(Objlist *, Obj_Entry *);
116 static void objlist_push_tail(Objlist *, Obj_Entry *);
117 static void objlist_remove(Objlist *, Obj_Entry *);
118 static void *path_enumerate(const char *, path_enum_proc, void *);
119 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, RtldLockState *);
120 static int resolve_objects_ifunc(Obj_Entry *first, bool bind_now,
121 RtldLockState *lockstate);
122 static int rtld_dirname(const char *, char *);
123 static int rtld_dirname_abs(const char *, char *);
124 static void *rtld_dlopen(const char *name, int fd, int mode);
125 static void rtld_exit(void);
126 static char *search_library_path(const char *, const char *);
127 static const void **get_program_var_addr(const char *, RtldLockState *);
128 static void set_program_var(const char *, const void *);
129 static int symlook_default(SymLook *, const Obj_Entry *refobj);
130 static int symlook_global(SymLook *, DoneList *);
131 static void symlook_init_from_req(SymLook *, const SymLook *);
132 static int symlook_list(SymLook *, const Objlist *, DoneList *);
133 static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *);
134 static int symlook_obj1(SymLook *, const Obj_Entry *);
135 static void trace_loaded_objects(Obj_Entry *);
136 static void unlink_object(Obj_Entry *);
137 static void unload_object(Obj_Entry *);
138 static void unref_dag(Obj_Entry *);
139 static void ref_dag(Obj_Entry *);
140 static int origin_subst_one(char **, const char *, const char *,
141 const char *, char *);
142 static char *origin_subst(const char *, const char *);
143 static void preinit_main(void);
144 static int rtld_verify_versions(const Objlist *);
145 static int rtld_verify_object_versions(Obj_Entry *);
146 static void object_add_name(Obj_Entry *, const char *);
147 static int object_match_name(const Obj_Entry *, const char *);
148 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
149 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
150 struct dl_phdr_info *phdr_info);
152 void r_debug_state(struct r_debug *, struct link_map *) __noinline;
157 static char *error_message; /* Message for dlerror(), or NULL */
158 struct r_debug r_debug; /* for GDB; */
159 static bool libmap_disable; /* Disable libmap */
160 static bool ld_loadfltr; /* Immediate filters processing */
161 static char *libmap_override; /* Maps to use in addition to libmap.conf */
162 static bool trust; /* False for setuid and setgid programs */
163 static bool dangerous_ld_env; /* True if environment variables have been
164 used to affect the libraries loaded */
165 static char *ld_bind_now; /* Environment variable for immediate binding */
166 static char *ld_debug; /* Environment variable for debugging */
167 static char *ld_library_path; /* Environment variable for search path */
168 static char *ld_preload; /* Environment variable for libraries to
170 static char *ld_elf_hints_path; /* Environment variable for alternative hints path */
171 static char *ld_tracing; /* Called from ldd to print libs */
172 static char *ld_utrace; /* Use utrace() to log events. */
173 static Obj_Entry *obj_list; /* Head of linked list of shared objects */
174 static Obj_Entry **obj_tail; /* Link field of last object in list */
175 static Obj_Entry *obj_main; /* The main program shared object */
176 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
177 static unsigned int obj_count; /* Number of objects in obj_list */
178 static unsigned int obj_loads; /* Number of objects in obj_list */
180 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
181 STAILQ_HEAD_INITIALIZER(list_global);
182 static Objlist list_main = /* Objects loaded at program startup */
183 STAILQ_HEAD_INITIALIZER(list_main);
184 static Objlist list_fini = /* Objects needing fini() calls */
185 STAILQ_HEAD_INITIALIZER(list_fini);
187 Elf_Sym sym_zero; /* For resolving undefined weak refs. */
189 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
191 extern Elf_Dyn _DYNAMIC;
192 #pragma weak _DYNAMIC
193 #ifndef RTLD_IS_DYNAMIC
194 #define RTLD_IS_DYNAMIC() (&_DYNAMIC != NULL)
197 int osreldate, pagesize;
199 static int stack_prot = PROT_READ | PROT_WRITE | RTLD_DEFAULT_STACK_EXEC;
200 static int max_stack_flags;
203 * Global declarations normally provided by crt1. The dynamic linker is
204 * not built with crt1, so we have to provide them ourselves.
210 * Used to pass argc, argv to init functions.
216 * Globals to control TLS allocation.
218 size_t tls_last_offset; /* Static TLS offset of last module */
219 size_t tls_last_size; /* Static TLS size of last module */
220 size_t tls_static_space; /* Static TLS space allocated */
221 int tls_dtv_generation = 1; /* Used to detect when dtv size changes */
222 int tls_max_index = 1; /* Largest module index allocated */
225 * Fill in a DoneList with an allocation large enough to hold all of
226 * the currently-loaded objects. Keep this as a macro since it calls
227 * alloca and we want that to occur within the scope of the caller.
229 #define donelist_init(dlp) \
230 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
231 assert((dlp)->objs != NULL), \
232 (dlp)->num_alloc = obj_count, \
235 #define UTRACE_DLOPEN_START 1
236 #define UTRACE_DLOPEN_STOP 2
237 #define UTRACE_DLCLOSE_START 3
238 #define UTRACE_DLCLOSE_STOP 4
239 #define UTRACE_LOAD_OBJECT 5
240 #define UTRACE_UNLOAD_OBJECT 6
241 #define UTRACE_ADD_RUNDEP 7
242 #define UTRACE_PRELOAD_FINISHED 8
243 #define UTRACE_INIT_CALL 9
244 #define UTRACE_FINI_CALL 10
247 char sig[4]; /* 'RTLD' */
250 void *mapbase; /* Used for 'parent' and 'init/fini' */
252 int refcnt; /* Used for 'mode' */
253 char name[MAXPATHLEN];
256 #define LD_UTRACE(e, h, mb, ms, r, n) do { \
257 if (ld_utrace != NULL) \
258 ld_utrace_log(e, h, mb, ms, r, n); \
262 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
263 int refcnt, const char *name)
265 struct utrace_rtld ut;
273 ut.mapbase = mapbase;
274 ut.mapsize = mapsize;
276 bzero(ut.name, sizeof(ut.name));
278 strlcpy(ut.name, name, sizeof(ut.name));
279 utrace(&ut, sizeof(ut));
283 * Main entry point for dynamic linking. The first argument is the
284 * stack pointer. The stack is expected to be laid out as described
285 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
286 * Specifically, the stack pointer points to a word containing
287 * ARGC. Following that in the stack is a null-terminated sequence
288 * of pointers to argument strings. Then comes a null-terminated
289 * sequence of pointers to environment strings. Finally, there is a
290 * sequence of "auxiliary vector" entries.
292 * The second argument points to a place to store the dynamic linker's
293 * exit procedure pointer and the third to a place to store the main
296 * The return value is the main program's entry point.
299 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
301 Elf_Auxinfo *aux_info[AT_COUNT];
309 Objlist_Entry *entry;
311 Obj_Entry **preload_tail;
313 RtldLockState lockstate;
316 * On entry, the dynamic linker itself has not been relocated yet.
317 * Be very careful not to reference any global data until after
318 * init_rtld has returned. It is OK to reference file-scope statics
319 * and string constants, and to call static and global functions.
322 /* Find the auxiliary vector on the stack. */
325 sp += argc + 1; /* Skip over arguments and NULL terminator */
327 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
329 aux = (Elf_Auxinfo *) sp;
331 /* Digest the auxiliary vector. */
332 for (i = 0; i < AT_COUNT; i++)
334 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
335 if (auxp->a_type < AT_COUNT)
336 aux_info[auxp->a_type] = auxp;
339 /* Initialize and relocate ourselves. */
340 assert(aux_info[AT_BASE] != NULL);
341 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
343 __progname = obj_rtld.path;
344 argv0 = argv[0] != NULL ? argv[0] : "(null)";
349 trust = !issetugid();
351 ld_bind_now = getenv(LD_ "BIND_NOW");
353 * If the process is tainted, then we un-set the dangerous environment
354 * variables. The process will be marked as tainted until setuid(2)
355 * is called. If any child process calls setuid(2) we do not want any
356 * future processes to honor the potentially un-safe variables.
359 if (unsetenv(LD_ "PRELOAD") || unsetenv(LD_ "LIBMAP") ||
360 unsetenv(LD_ "LIBRARY_PATH") || unsetenv(LD_ "LIBMAP_DISABLE") ||
361 unsetenv(LD_ "DEBUG") || unsetenv(LD_ "ELF_HINTS_PATH") ||
362 unsetenv(LD_ "LOADFLTR")) {
363 _rtld_error("environment corrupt; aborting");
367 ld_debug = getenv(LD_ "DEBUG");
368 libmap_disable = getenv(LD_ "LIBMAP_DISABLE") != NULL;
369 libmap_override = getenv(LD_ "LIBMAP");
370 ld_library_path = getenv(LD_ "LIBRARY_PATH");
371 ld_preload = getenv(LD_ "PRELOAD");
372 ld_elf_hints_path = getenv(LD_ "ELF_HINTS_PATH");
373 ld_loadfltr = getenv(LD_ "LOADFLTR") != NULL;
374 dangerous_ld_env = libmap_disable || (libmap_override != NULL) ||
375 (ld_library_path != NULL) || (ld_preload != NULL) ||
376 (ld_elf_hints_path != NULL) || ld_loadfltr;
377 ld_tracing = getenv(LD_ "TRACE_LOADED_OBJECTS");
378 ld_utrace = getenv(LD_ "UTRACE");
380 if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0)
381 ld_elf_hints_path = _PATH_ELF_HINTS;
383 if (ld_debug != NULL && *ld_debug != '\0')
385 dbg("%s is initialized, base address = %p", __progname,
386 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
387 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
388 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
390 dbg("initializing thread locks");
394 * Load the main program, or process its program header if it is
397 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
398 int fd = aux_info[AT_EXECFD]->a_un.a_val;
399 dbg("loading main program");
400 obj_main = map_object(fd, argv0, NULL);
402 if (obj_main == NULL)
404 max_stack_flags = obj->stack_flags;
405 } else { /* Main program already loaded. */
406 const Elf_Phdr *phdr;
410 dbg("processing main program's program header");
411 assert(aux_info[AT_PHDR] != NULL);
412 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
413 assert(aux_info[AT_PHNUM] != NULL);
414 phnum = aux_info[AT_PHNUM]->a_un.a_val;
415 assert(aux_info[AT_PHENT] != NULL);
416 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
417 assert(aux_info[AT_ENTRY] != NULL);
418 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
419 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
423 if (aux_info[AT_EXECPATH] != 0) {
425 char buf[MAXPATHLEN];
427 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
428 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
429 if (kexecpath[0] == '/')
430 obj_main->path = kexecpath;
431 else if (getcwd(buf, sizeof(buf)) == NULL ||
432 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
433 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
434 obj_main->path = xstrdup(argv0);
436 obj_main->path = xstrdup(buf);
438 dbg("No AT_EXECPATH");
439 obj_main->path = xstrdup(argv0);
441 dbg("obj_main path %s", obj_main->path);
442 obj_main->mainprog = true;
444 if (aux_info[AT_STACKPROT] != NULL &&
445 aux_info[AT_STACKPROT]->a_un.a_val != 0)
446 stack_prot = aux_info[AT_STACKPROT]->a_un.a_val;
449 * Get the actual dynamic linker pathname from the executable if
450 * possible. (It should always be possible.) That ensures that
451 * gdb will find the right dynamic linker even if a non-standard
454 if (obj_main->interp != NULL &&
455 strcmp(obj_main->interp, obj_rtld.path) != 0) {
457 obj_rtld.path = xstrdup(obj_main->interp);
458 __progname = obj_rtld.path;
461 digest_dynamic(obj_main, 0);
463 linkmap_add(obj_main);
464 linkmap_add(&obj_rtld);
466 /* Link the main program into the list of objects. */
467 *obj_tail = obj_main;
468 obj_tail = &obj_main->next;
472 /* Initialize a fake symbol for resolving undefined weak references. */
473 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
474 sym_zero.st_shndx = SHN_UNDEF;
475 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
478 libmap_disable = (bool)lm_init(libmap_override);
480 dbg("loading LD_PRELOAD libraries");
481 if (load_preload_objects() == -1)
483 preload_tail = obj_tail;
485 dbg("loading needed objects");
486 if (load_needed_objects(obj_main, 0) == -1)
489 /* Make a list of all objects loaded at startup. */
490 for (obj = obj_list; obj != NULL; obj = obj->next) {
491 objlist_push_tail(&list_main, obj);
495 dbg("checking for required versions");
496 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
499 if (ld_tracing) { /* We're done */
500 trace_loaded_objects(obj_main);
504 if (getenv(LD_ "DUMP_REL_PRE") != NULL) {
505 dump_relocations(obj_main);
510 * Processing tls relocations requires having the tls offsets
511 * initialized. Prepare offsets before starting initial
512 * relocation processing.
514 dbg("initializing initial thread local storage offsets");
515 STAILQ_FOREACH(entry, &list_main, link) {
517 * Allocate all the initial objects out of the static TLS
518 * block even if they didn't ask for it.
520 allocate_tls_offset(entry->obj);
523 if (relocate_objects(obj_main,
524 ld_bind_now != NULL && *ld_bind_now != '\0', &obj_rtld, NULL) == -1)
527 dbg("doing copy relocations");
528 if (do_copy_relocations(obj_main) == -1)
531 if (getenv(LD_ "DUMP_REL_POST") != NULL) {
532 dump_relocations(obj_main);
537 * Setup TLS for main thread. This must be done after the
538 * relocations are processed, since tls initialization section
539 * might be the subject for relocations.
541 dbg("initializing initial thread local storage");
542 allocate_initial_tls(obj_list);
544 dbg("initializing key program variables");
545 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
546 set_program_var("environ", env);
547 set_program_var("__elf_aux_vector", aux);
549 /* Make a list of init functions to call. */
550 objlist_init(&initlist);
551 initlist_add_objects(obj_list, preload_tail, &initlist);
553 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
555 map_stacks_exec(NULL);
557 dbg("resolving ifuncs");
558 if (resolve_objects_ifunc(obj_main,
559 ld_bind_now != NULL && *ld_bind_now != '\0', NULL) == -1)
562 if (!obj_main->crt_no_init) {
564 * Make sure we don't call the main program's init and fini
565 * functions for binaries linked with old crt1 which calls
568 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
569 obj_main->preinit_array = obj_main->init_array =
570 obj_main->fini_array = (Elf_Addr)NULL;
573 wlock_acquire(rtld_bind_lock, &lockstate);
574 if (obj_main->crt_no_init)
576 objlist_call_init(&initlist, &lockstate);
577 objlist_clear(&initlist);
578 dbg("loading filtees");
579 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
580 if (ld_loadfltr || obj->z_loadfltr)
581 load_filtees(obj, 0, &lockstate);
583 lock_release(rtld_bind_lock, &lockstate);
585 dbg("transferring control to program entry point = %p", obj_main->entry);
587 /* Return the exit procedure and the program entry point. */
588 *exit_proc = rtld_exit;
590 return (func_ptr_type) obj_main->entry;
594 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def)
599 ptr = (void *)make_function_pointer(def, obj);
600 target = ((Elf_Addr (*)(void))ptr)();
601 return ((void *)target);
605 _rtld_bind(Obj_Entry *obj, Elf_Size reloff)
609 const Obj_Entry *defobj;
612 RtldLockState lockstate;
614 rlock_acquire(rtld_bind_lock, &lockstate);
615 if (sigsetjmp(lockstate.env, 0) != 0)
616 lock_upgrade(rtld_bind_lock, &lockstate);
618 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
620 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
622 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
623 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL,
627 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
628 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
630 target = (Elf_Addr)(defobj->relocbase + def->st_value);
632 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
633 defobj->strtab + def->st_name, basename(obj->path),
634 (void *)target, basename(defobj->path));
637 * Write the new contents for the jmpslot. Note that depending on
638 * architecture, the value which we need to return back to the
639 * lazy binding trampoline may or may not be the target
640 * address. The value returned from reloc_jmpslot() is the value
641 * that the trampoline needs.
643 target = reloc_jmpslot(where, target, defobj, obj, rel);
644 lock_release(rtld_bind_lock, &lockstate);
649 * Error reporting function. Use it like printf. If formats the message
650 * into a buffer, and sets things up so that the next call to dlerror()
651 * will return the message.
654 _rtld_error(const char *fmt, ...)
656 static char buf[512];
660 rtld_vsnprintf(buf, sizeof buf, fmt, ap);
666 * Return a dynamically-allocated copy of the current error message, if any.
671 return error_message == NULL ? NULL : xstrdup(error_message);
675 * Restore the current error message from a copy which was previously saved
676 * by errmsg_save(). The copy is freed.
679 errmsg_restore(char *saved_msg)
681 if (saved_msg == NULL)
682 error_message = NULL;
684 _rtld_error("%s", saved_msg);
690 basename(const char *name)
692 const char *p = strrchr(name, '/');
693 return p != NULL ? p + 1 : name;
696 static struct utsname uts;
699 origin_subst_one(char **res, const char *real, const char *kw, const char *subst,
709 subst_len = kw_len = 0;
713 if (subst_len == 0) {
714 subst_len = strlen(subst);
718 *res = xmalloc(PATH_MAX);
721 if ((res1 - *res) + subst_len + (p1 - p) >= PATH_MAX) {
722 _rtld_error("Substitution of %s in %s cannot be performed",
724 if (may_free != NULL)
729 memcpy(res1, p, p1 - p);
731 memcpy(res1, subst, subst_len);
736 if (may_free != NULL)
739 *res = xstrdup(real);
743 if (may_free != NULL)
745 if (strlcat(res1, p, PATH_MAX - (res1 - *res)) >= PATH_MAX) {
755 origin_subst(const char *real, const char *origin_path)
757 char *res1, *res2, *res3, *res4;
759 if (uts.sysname[0] == '\0') {
760 if (uname(&uts) != 0) {
761 _rtld_error("utsname failed: %d", errno);
765 if (!origin_subst_one(&res1, real, "$ORIGIN", origin_path, NULL) ||
766 !origin_subst_one(&res2, res1, "$OSNAME", uts.sysname, res1) ||
767 !origin_subst_one(&res3, res2, "$OSREL", uts.release, res2) ||
768 !origin_subst_one(&res4, res3, "$PLATFORM", uts.machine, res3))
776 const char *msg = dlerror();
780 rtld_fdputstr(STDERR_FILENO, msg);
781 rtld_fdputchar(STDERR_FILENO, '\n');
786 * Process a shared object's DYNAMIC section, and save the important
787 * information in its Obj_Entry structure.
790 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
791 const Elf_Dyn **dyn_soname)
794 Needed_Entry **needed_tail = &obj->needed;
795 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
796 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
797 int plttype = DT_REL;
802 obj->bind_now = false;
803 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
804 switch (dynp->d_tag) {
807 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
811 obj->relsize = dynp->d_un.d_val;
815 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
819 obj->pltrel = (const Elf_Rel *)
820 (obj->relocbase + dynp->d_un.d_ptr);
824 obj->pltrelsize = dynp->d_un.d_val;
828 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
832 obj->relasize = dynp->d_un.d_val;
836 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
840 plttype = dynp->d_un.d_val;
841 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
845 obj->symtab = (const Elf_Sym *)
846 (obj->relocbase + dynp->d_un.d_ptr);
850 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
854 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
858 obj->strsize = dynp->d_un.d_val;
862 obj->verneed = (const Elf_Verneed *) (obj->relocbase +
867 obj->verneednum = dynp->d_un.d_val;
871 obj->verdef = (const Elf_Verdef *) (obj->relocbase +
876 obj->verdefnum = dynp->d_un.d_val;
880 obj->versyms = (const Elf_Versym *)(obj->relocbase +
886 const Elf_Hashelt *hashtab = (const Elf_Hashelt *)
887 (obj->relocbase + dynp->d_un.d_ptr);
888 obj->nbuckets = hashtab[0];
889 obj->nchains = hashtab[1];
890 obj->buckets = hashtab + 2;
891 obj->chains = obj->buckets + obj->nbuckets;
897 Needed_Entry *nep = NEW(Needed_Entry);
898 nep->name = dynp->d_un.d_val;
903 needed_tail = &nep->next;
909 Needed_Entry *nep = NEW(Needed_Entry);
910 nep->name = dynp->d_un.d_val;
914 *needed_filtees_tail = nep;
915 needed_filtees_tail = &nep->next;
921 Needed_Entry *nep = NEW(Needed_Entry);
922 nep->name = dynp->d_un.d_val;
926 *needed_aux_filtees_tail = nep;
927 needed_aux_filtees_tail = &nep->next;
932 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
940 obj->symbolic = true;
944 case DT_RUNPATH: /* XXX: process separately */
946 * We have to wait until later to process this, because we
947 * might not have gotten the address of the string table yet.
957 obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
960 case DT_PREINIT_ARRAY:
961 obj->preinit_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
964 case DT_PREINIT_ARRAYSZ:
965 obj->preinit_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
969 obj->init_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
972 case DT_INIT_ARRAYSZ:
973 obj->init_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
977 obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
981 obj->fini_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
984 case DT_FINI_ARRAYSZ:
985 obj->fini_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
989 * Don't process DT_DEBUG on MIPS as the dynamic section
990 * is mapped read-only. DT_MIPS_RLD_MAP is used instead.
995 /* XXX - not implemented yet */
997 dbg("Filling in DT_DEBUG entry");
998 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
1003 if ((dynp->d_un.d_val & DF_ORIGIN) && trust)
1004 obj->z_origin = true;
1005 if (dynp->d_un.d_val & DF_SYMBOLIC)
1006 obj->symbolic = true;
1007 if (dynp->d_un.d_val & DF_TEXTREL)
1008 obj->textrel = true;
1009 if (dynp->d_un.d_val & DF_BIND_NOW)
1010 obj->bind_now = true;
1011 /*if (dynp->d_un.d_val & DF_STATIC_TLS)
1015 case DT_MIPS_LOCAL_GOTNO:
1016 obj->local_gotno = dynp->d_un.d_val;
1019 case DT_MIPS_SYMTABNO:
1020 obj->symtabno = dynp->d_un.d_val;
1023 case DT_MIPS_GOTSYM:
1024 obj->gotsym = dynp->d_un.d_val;
1027 case DT_MIPS_RLD_MAP:
1030 dbg("Filling in DT_DEBUG entry");
1031 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
1037 if (dynp->d_un.d_val & DF_1_NOOPEN)
1038 obj->z_noopen = true;
1039 if ((dynp->d_un.d_val & DF_1_ORIGIN) && trust)
1040 obj->z_origin = true;
1041 /*if (dynp->d_un.d_val & DF_1_GLOBAL)
1043 if (dynp->d_un.d_val & DF_1_BIND_NOW)
1044 obj->bind_now = true;
1045 if (dynp->d_un.d_val & DF_1_NODELETE)
1046 obj->z_nodelete = true;
1047 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1048 obj->z_loadfltr = true;
1053 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1060 obj->traced = false;
1062 if (plttype == DT_RELA) {
1063 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1065 obj->pltrelasize = obj->pltrelsize;
1066 obj->pltrelsize = 0;
1071 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1072 const Elf_Dyn *dyn_soname)
1075 if (obj->z_origin && obj->origin_path == NULL) {
1076 obj->origin_path = xmalloc(PATH_MAX);
1077 if (rtld_dirname_abs(obj->path, obj->origin_path) == -1)
1081 if (dyn_rpath != NULL) {
1082 obj->rpath = (char *)obj->strtab + dyn_rpath->d_un.d_val;
1084 obj->rpath = origin_subst(obj->rpath, obj->origin_path);
1087 if (dyn_soname != NULL)
1088 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1092 digest_dynamic(Obj_Entry *obj, int early)
1094 const Elf_Dyn *dyn_rpath;
1095 const Elf_Dyn *dyn_soname;
1097 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname);
1098 digest_dynamic2(obj, dyn_rpath, dyn_soname);
1102 * Process a shared object's program header. This is used only for the
1103 * main program, when the kernel has already loaded the main program
1104 * into memory before calling the dynamic linker. It creates and
1105 * returns an Obj_Entry structure.
1108 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1111 const Elf_Phdr *phlimit = phdr + phnum;
1113 Elf_Addr note_start, note_end;
1117 for (ph = phdr; ph < phlimit; ph++) {
1118 if (ph->p_type != PT_PHDR)
1122 obj->phsize = ph->p_memsz;
1123 obj->relocbase = (caddr_t)phdr - ph->p_vaddr;
1127 obj->stack_flags = PF_X | PF_R | PF_W;
1129 for (ph = phdr; ph < phlimit; ph++) {
1130 switch (ph->p_type) {
1133 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1137 if (nsegs == 0) { /* First load segment */
1138 obj->vaddrbase = trunc_page(ph->p_vaddr);
1139 obj->mapbase = obj->vaddrbase + obj->relocbase;
1140 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
1142 } else { /* Last load segment */
1143 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1150 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1155 obj->tlssize = ph->p_memsz;
1156 obj->tlsalign = ph->p_align;
1157 obj->tlsinitsize = ph->p_filesz;
1158 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1162 obj->stack_flags = ph->p_flags;
1166 obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1167 obj->relro_size = round_page(ph->p_memsz);
1171 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
1172 note_end = note_start + ph->p_filesz;
1173 digest_notes(obj, note_start, note_end);
1178 _rtld_error("%s: too few PT_LOAD segments", path);
1187 digest_notes(Obj_Entry *obj, Elf_Addr note_start, Elf_Addr note_end)
1189 const Elf_Note *note;
1190 const char *note_name;
1193 for (note = (const Elf_Note *)note_start; (Elf_Addr)note < note_end;
1194 note = (const Elf_Note *)((const char *)(note + 1) +
1195 roundup2(note->n_namesz, sizeof(Elf32_Addr)) +
1196 roundup2(note->n_descsz, sizeof(Elf32_Addr)))) {
1197 if (note->n_namesz != sizeof(NOTE_FREEBSD_VENDOR) ||
1198 note->n_descsz != sizeof(int32_t))
1200 if (note->n_type != ABI_NOTETYPE &&
1201 note->n_type != CRT_NOINIT_NOTETYPE)
1203 note_name = (const char *)(note + 1);
1204 if (strncmp(NOTE_FREEBSD_VENDOR, note_name,
1205 sizeof(NOTE_FREEBSD_VENDOR)) != 0)
1207 switch (note->n_type) {
1209 /* FreeBSD osrel note */
1210 p = (uintptr_t)(note + 1);
1211 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1212 obj->osrel = *(const int32_t *)(p);
1213 dbg("note osrel %d", obj->osrel);
1215 case CRT_NOINIT_NOTETYPE:
1216 /* FreeBSD 'crt does not call init' note */
1217 obj->crt_no_init = true;
1218 dbg("note crt_no_init");
1225 dlcheck(void *handle)
1229 for (obj = obj_list; obj != NULL; obj = obj->next)
1230 if (obj == (Obj_Entry *) handle)
1233 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1234 _rtld_error("Invalid shared object handle %p", handle);
1241 * If the given object is already in the donelist, return true. Otherwise
1242 * add the object to the list and return false.
1245 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1249 for (i = 0; i < dlp->num_used; i++)
1250 if (dlp->objs[i] == obj)
1253 * Our donelist allocation should always be sufficient. But if
1254 * our threads locking isn't working properly, more shared objects
1255 * could have been loaded since we allocated the list. That should
1256 * never happen, but we'll handle it properly just in case it does.
1258 if (dlp->num_used < dlp->num_alloc)
1259 dlp->objs[dlp->num_used++] = obj;
1264 * Hash function for symbol table lookup. Don't even think about changing
1265 * this. It is specified by the System V ABI.
1268 elf_hash(const char *name)
1270 const unsigned char *p = (const unsigned char *) name;
1271 unsigned long h = 0;
1274 while (*p != '\0') {
1275 h = (h << 4) + *p++;
1276 if ((g = h & 0xf0000000) != 0)
1284 * Find the library with the given name, and return its full pathname.
1285 * The returned string is dynamically allocated. Generates an error
1286 * message and returns NULL if the library cannot be found.
1288 * If the second argument is non-NULL, then it refers to an already-
1289 * loaded shared object, whose library search path will be searched.
1291 * The search order is:
1293 * rpath in the referencing file
1298 find_library(const char *xname, const Obj_Entry *refobj)
1303 if (strchr(xname, '/') != NULL) { /* Hard coded pathname */
1304 if (xname[0] != '/' && !trust) {
1305 _rtld_error("Absolute pathname required for shared object \"%s\"",
1309 if (refobj != NULL && refobj->z_origin)
1310 return origin_subst(xname, refobj->origin_path);
1312 return xstrdup(xname);
1315 if (libmap_disable || (refobj == NULL) ||
1316 (name = lm_find(refobj->path, xname)) == NULL)
1317 name = (char *)xname;
1319 dbg(" Searching for \"%s\"", name);
1321 if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
1323 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
1324 (pathname = search_library_path(name, gethints())) != NULL ||
1325 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
1328 if(refobj != NULL && refobj->path != NULL) {
1329 _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
1330 name, basename(refobj->path));
1332 _rtld_error("Shared object \"%s\" not found", name);
1338 * Given a symbol number in a referencing object, find the corresponding
1339 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1340 * no definition was found. Returns a pointer to the Obj_Entry of the
1341 * defining object via the reference parameter DEFOBJ_OUT.
1344 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1345 const Obj_Entry **defobj_out, int flags, SymCache *cache,
1346 RtldLockState *lockstate)
1350 const Obj_Entry *defobj;
1356 * If we have already found this symbol, get the information from
1359 if (symnum >= refobj->nchains)
1360 return NULL; /* Bad object */
1361 if (cache != NULL && cache[symnum].sym != NULL) {
1362 *defobj_out = cache[symnum].obj;
1363 return cache[symnum].sym;
1366 ref = refobj->symtab + symnum;
1367 name = refobj->strtab + ref->st_name;
1372 * We don't have to do a full scale lookup if the symbol is local.
1373 * We know it will bind to the instance in this load module; to
1374 * which we already have a pointer (ie ref). By not doing a lookup,
1375 * we not only improve performance, but it also avoids unresolvable
1376 * symbols when local symbols are not in the hash table. This has
1377 * been seen with the ia64 toolchain.
1379 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1380 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1381 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1384 symlook_init(&req, name);
1386 req.ventry = fetch_ventry(refobj, symnum);
1387 req.lockstate = lockstate;
1388 res = symlook_default(&req, refobj);
1391 defobj = req.defobj_out;
1399 * If we found no definition and the reference is weak, treat the
1400 * symbol as having the value zero.
1402 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1408 *defobj_out = defobj;
1409 /* Record the information in the cache to avoid subsequent lookups. */
1410 if (cache != NULL) {
1411 cache[symnum].sym = def;
1412 cache[symnum].obj = defobj;
1415 if (refobj != &obj_rtld)
1416 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1422 * Return the search path from the ldconfig hints file, reading it if
1423 * necessary. Returns NULL if there are problems with the hints file,
1424 * or if the search path there is empty.
1431 if (hints == NULL) {
1433 struct elfhints_hdr hdr;
1436 /* Keep from trying again in case the hints file is bad. */
1439 if ((fd = open(ld_elf_hints_path, O_RDONLY)) == -1)
1441 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1442 hdr.magic != ELFHINTS_MAGIC ||
1447 p = xmalloc(hdr.dirlistlen + 1);
1448 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1449 read(fd, p, hdr.dirlistlen + 1) != (ssize_t)hdr.dirlistlen + 1) {
1457 return hints[0] != '\0' ? hints : NULL;
1461 init_dag(Obj_Entry *root)
1463 const Needed_Entry *needed;
1464 const Objlist_Entry *elm;
1467 if (root->dag_inited)
1469 donelist_init(&donelist);
1471 /* Root object belongs to own DAG. */
1472 objlist_push_tail(&root->dldags, root);
1473 objlist_push_tail(&root->dagmembers, root);
1474 donelist_check(&donelist, root);
1477 * Add dependencies of root object to DAG in breadth order
1478 * by exploiting the fact that each new object get added
1479 * to the tail of the dagmembers list.
1481 STAILQ_FOREACH(elm, &root->dagmembers, link) {
1482 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
1483 if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
1485 objlist_push_tail(&needed->obj->dldags, root);
1486 objlist_push_tail(&root->dagmembers, needed->obj);
1489 root->dag_inited = true;
1493 * Initialize the dynamic linker. The argument is the address at which
1494 * the dynamic linker has been mapped into memory. The primary task of
1495 * this function is to relocate the dynamic linker.
1498 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
1500 Obj_Entry objtmp; /* Temporary rtld object */
1501 const Elf_Dyn *dyn_rpath;
1502 const Elf_Dyn *dyn_soname;
1505 * Conjure up an Obj_Entry structure for the dynamic linker.
1507 * The "path" member can't be initialized yet because string constants
1508 * cannot yet be accessed. Below we will set it correctly.
1510 memset(&objtmp, 0, sizeof(objtmp));
1513 objtmp.mapbase = mapbase;
1515 objtmp.relocbase = mapbase;
1517 if (RTLD_IS_DYNAMIC()) {
1518 objtmp.dynamic = rtld_dynamic(&objtmp);
1519 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname);
1520 assert(objtmp.needed == NULL);
1521 #if !defined(__mips__)
1522 /* MIPS has a bogus DT_TEXTREL. */
1523 assert(!objtmp.textrel);
1527 * Temporarily put the dynamic linker entry into the object list, so
1528 * that symbols can be found.
1531 relocate_objects(&objtmp, true, &objtmp, NULL);
1534 /* Initialize the object list. */
1535 obj_tail = &obj_list;
1537 /* Now that non-local variables can be accesses, copy out obj_rtld. */
1538 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1540 if (aux_info[AT_PAGESZ] != NULL)
1541 pagesize = aux_info[AT_PAGESZ]->a_un.a_val;
1542 if (aux_info[AT_OSRELDATE] != NULL)
1543 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
1545 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname);
1547 /* Replace the path with a dynamically allocated copy. */
1548 obj_rtld.path = xstrdup(PATH_RTLD);
1550 r_debug.r_brk = r_debug_state;
1551 r_debug.r_state = RT_CONSISTENT;
1555 * Add the init functions from a needed object list (and its recursive
1556 * needed objects) to "list". This is not used directly; it is a helper
1557 * function for initlist_add_objects(). The write lock must be held
1558 * when this function is called.
1561 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1563 /* Recursively process the successor needed objects. */
1564 if (needed->next != NULL)
1565 initlist_add_neededs(needed->next, list);
1567 /* Process the current needed object. */
1568 if (needed->obj != NULL)
1569 initlist_add_objects(needed->obj, &needed->obj->next, list);
1573 * Scan all of the DAGs rooted in the range of objects from "obj" to
1574 * "tail" and add their init functions to "list". This recurses over
1575 * the DAGs and ensure the proper init ordering such that each object's
1576 * needed libraries are initialized before the object itself. At the
1577 * same time, this function adds the objects to the global finalization
1578 * list "list_fini" in the opposite order. The write lock must be
1579 * held when this function is called.
1582 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1584 if (obj->init_scanned || obj->init_done)
1586 obj->init_scanned = true;
1588 /* Recursively process the successor objects. */
1589 if (&obj->next != tail)
1590 initlist_add_objects(obj->next, tail, list);
1592 /* Recursively process the needed objects. */
1593 if (obj->needed != NULL)
1594 initlist_add_neededs(obj->needed, list);
1596 /* Add the object to the init list. */
1597 if (obj->preinit_array != (Elf_Addr)NULL || obj->init != (Elf_Addr)NULL ||
1598 obj->init_array != (Elf_Addr)NULL)
1599 objlist_push_tail(list, obj);
1601 /* Add the object to the global fini list in the reverse order. */
1602 if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL)
1603 && !obj->on_fini_list) {
1604 objlist_push_head(&list_fini, obj);
1605 obj->on_fini_list = true;
1610 #define FPTR_TARGET(f) ((Elf_Addr) (f))
1614 free_needed_filtees(Needed_Entry *n)
1616 Needed_Entry *needed, *needed1;
1618 for (needed = n; needed != NULL; needed = needed->next) {
1619 if (needed->obj != NULL) {
1620 dlclose(needed->obj);
1624 for (needed = n; needed != NULL; needed = needed1) {
1625 needed1 = needed->next;
1631 unload_filtees(Obj_Entry *obj)
1634 free_needed_filtees(obj->needed_filtees);
1635 obj->needed_filtees = NULL;
1636 free_needed_filtees(obj->needed_aux_filtees);
1637 obj->needed_aux_filtees = NULL;
1638 obj->filtees_loaded = false;
1642 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags)
1645 for (; needed != NULL; needed = needed->next) {
1646 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
1647 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
1653 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
1656 lock_restart_for_upgrade(lockstate);
1657 if (!obj->filtees_loaded) {
1658 load_filtee1(obj, obj->needed_filtees, flags);
1659 load_filtee1(obj, obj->needed_aux_filtees, flags);
1660 obj->filtees_loaded = true;
1665 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
1669 for (; needed != NULL; needed = needed->next) {
1670 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
1671 flags & ~RTLD_LO_NOLOAD);
1672 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
1674 if (obj1 != NULL && obj1->z_nodelete && !obj1->ref_nodel) {
1675 dbg("obj %s nodelete", obj1->path);
1678 obj1->ref_nodel = true;
1685 * Given a shared object, traverse its list of needed objects, and load
1686 * each of them. Returns 0 on success. Generates an error message and
1687 * returns -1 on failure.
1690 load_needed_objects(Obj_Entry *first, int flags)
1694 for (obj = first; obj != NULL; obj = obj->next) {
1695 if (process_needed(obj, obj->needed, flags) == -1)
1702 load_preload_objects(void)
1704 char *p = ld_preload;
1705 static const char delim[] = " \t:;";
1710 p += strspn(p, delim);
1711 while (*p != '\0') {
1712 size_t len = strcspn(p, delim);
1717 if (load_object(p, -1, NULL, 0) == NULL)
1718 return -1; /* XXX - cleanup */
1721 p += strspn(p, delim);
1723 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
1728 printable_path(const char *path)
1731 return (path == NULL ? "<unknown>" : path);
1735 * Load a shared object into memory, if it is not already loaded. The
1736 * object may be specified by name or by user-supplied file descriptor
1737 * fd_u. In the later case, the fd_u descriptor is not closed, but its
1740 * Returns a pointer to the Obj_Entry for the object. Returns NULL
1744 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
1752 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
1753 if (object_match_name(obj, name))
1757 path = find_library(name, refobj);
1764 * If we didn't find a match by pathname, or the name is not
1765 * supplied, open the file and check again by device and inode.
1766 * This avoids false mismatches caused by multiple links or ".."
1769 * To avoid a race, we open the file and use fstat() rather than
1774 if ((fd = open(path, O_RDONLY)) == -1) {
1775 _rtld_error("Cannot open \"%s\"", path);
1782 _rtld_error("Cannot dup fd");
1787 if (fstat(fd, &sb) == -1) {
1788 _rtld_error("Cannot fstat \"%s\"", printable_path(path));
1793 for (obj = obj_list->next; obj != NULL; obj = obj->next)
1794 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
1796 if (obj != NULL && name != NULL) {
1797 object_add_name(obj, name);
1802 if (flags & RTLD_LO_NOLOAD) {
1808 /* First use of this object, so we must map it in */
1809 obj = do_load_object(fd, name, path, &sb, flags);
1818 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
1825 * but first, make sure that environment variables haven't been
1826 * used to circumvent the noexec flag on a filesystem.
1828 if (dangerous_ld_env) {
1829 if (fstatfs(fd, &fs) != 0) {
1830 _rtld_error("Cannot fstatfs \"%s\"", printable_path(path));
1833 if (fs.f_flags & MNT_NOEXEC) {
1834 _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
1838 dbg("loading \"%s\"", printable_path(path));
1839 obj = map_object(fd, printable_path(path), sbp);
1844 * If DT_SONAME is present in the object, digest_dynamic2 already
1845 * added it to the object names.
1848 object_add_name(obj, name);
1850 digest_dynamic(obj, 0);
1851 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
1853 dbg("refusing to load non-loadable \"%s\"", obj->path);
1854 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
1855 munmap(obj->mapbase, obj->mapsize);
1861 obj_tail = &obj->next;
1864 linkmap_add(obj); /* for GDB & dlinfo() */
1865 max_stack_flags |= obj->stack_flags;
1867 dbg(" %p .. %p: %s", obj->mapbase,
1868 obj->mapbase + obj->mapsize - 1, obj->path);
1870 dbg(" WARNING: %s has impure text", obj->path);
1871 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
1878 obj_from_addr(const void *addr)
1882 for (obj = obj_list; obj != NULL; obj = obj->next) {
1883 if (addr < (void *) obj->mapbase)
1885 if (addr < (void *) (obj->mapbase + obj->mapsize))
1894 Elf_Addr *preinit_addr;
1897 preinit_addr = (Elf_Addr *)obj_main->preinit_array;
1898 if (preinit_addr == NULL)
1901 for (index = 0; index < obj_main->preinit_array_num; index++) {
1902 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) {
1903 dbg("calling preinit function for %s at %p", obj_main->path,
1904 (void *)preinit_addr[index]);
1905 LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index],
1906 0, 0, obj_main->path);
1907 call_init_pointer(obj_main, preinit_addr[index]);
1913 * Call the finalization functions for each of the objects in "list"
1914 * belonging to the DAG of "root" and referenced once. If NULL "root"
1915 * is specified, every finalization function will be called regardless
1916 * of the reference count and the list elements won't be freed. All of
1917 * the objects are expected to have non-NULL fini functions.
1920 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
1924 Elf_Addr *fini_addr;
1927 assert(root == NULL || root->refcount == 1);
1930 * Preserve the current error message since a fini function might
1931 * call into the dynamic linker and overwrite it.
1933 saved_msg = errmsg_save();
1935 STAILQ_FOREACH(elm, list, link) {
1936 if (root != NULL && (elm->obj->refcount != 1 ||
1937 objlist_find(&root->dagmembers, elm->obj) == NULL))
1939 /* Remove object from fini list to prevent recursive invocation. */
1940 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1942 * XXX: If a dlopen() call references an object while the
1943 * fini function is in progress, we might end up trying to
1944 * unload the referenced object in dlclose() or the object
1945 * won't be unloaded although its fini function has been
1948 lock_release(rtld_bind_lock, lockstate);
1951 * It is legal to have both DT_FINI and DT_FINI_ARRAY defined.
1952 * When this happens, DT_FINI_ARRAY is processed first.
1954 fini_addr = (Elf_Addr *)elm->obj->fini_array;
1955 if (fini_addr != NULL && elm->obj->fini_array_num > 0) {
1956 for (index = elm->obj->fini_array_num - 1; index >= 0;
1958 if (fini_addr[index] != 0 && fini_addr[index] != 1) {
1959 dbg("calling fini function for %s at %p",
1960 elm->obj->path, (void *)fini_addr[index]);
1961 LD_UTRACE(UTRACE_FINI_CALL, elm->obj,
1962 (void *)fini_addr[index], 0, 0, elm->obj->path);
1963 call_initfini_pointer(elm->obj, fini_addr[index]);
1967 if (elm->obj->fini != (Elf_Addr)NULL) {
1968 dbg("calling fini function for %s at %p", elm->obj->path,
1969 (void *)elm->obj->fini);
1970 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini,
1971 0, 0, elm->obj->path);
1972 call_initfini_pointer(elm->obj, elm->obj->fini);
1974 wlock_acquire(rtld_bind_lock, lockstate);
1975 /* No need to free anything if process is going down. */
1979 * We must restart the list traversal after every fini call
1980 * because a dlclose() call from the fini function or from
1981 * another thread might have modified the reference counts.
1985 } while (elm != NULL);
1986 errmsg_restore(saved_msg);
1990 * Call the initialization functions for each of the objects in
1991 * "list". All of the objects are expected to have non-NULL init
1995 objlist_call_init(Objlist *list, RtldLockState *lockstate)
2000 Elf_Addr *init_addr;
2004 * Clean init_scanned flag so that objects can be rechecked and
2005 * possibly initialized earlier if any of vectors called below
2006 * cause the change by using dlopen.
2008 for (obj = obj_list; obj != NULL; obj = obj->next)
2009 obj->init_scanned = false;
2012 * Preserve the current error message since an init function might
2013 * call into the dynamic linker and overwrite it.
2015 saved_msg = errmsg_save();
2016 STAILQ_FOREACH(elm, list, link) {
2017 if (elm->obj->init_done) /* Initialized early. */
2020 * Race: other thread might try to use this object before current
2021 * one completes the initilization. Not much can be done here
2022 * without better locking.
2024 elm->obj->init_done = true;
2025 lock_release(rtld_bind_lock, lockstate);
2028 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined.
2029 * When this happens, DT_INIT is processed first.
2031 if (elm->obj->init != (Elf_Addr)NULL) {
2032 dbg("calling init function for %s at %p", elm->obj->path,
2033 (void *)elm->obj->init);
2034 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init,
2035 0, 0, elm->obj->path);
2036 call_initfini_pointer(elm->obj, elm->obj->init);
2038 init_addr = (Elf_Addr *)elm->obj->init_array;
2039 if (init_addr != NULL) {
2040 for (index = 0; index < elm->obj->init_array_num; index++) {
2041 if (init_addr[index] != 0 && init_addr[index] != 1) {
2042 dbg("calling init function for %s at %p", elm->obj->path,
2043 (void *)init_addr[index]);
2044 LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
2045 (void *)init_addr[index], 0, 0, elm->obj->path);
2046 call_init_pointer(elm->obj, init_addr[index]);
2050 wlock_acquire(rtld_bind_lock, lockstate);
2052 errmsg_restore(saved_msg);
2056 objlist_clear(Objlist *list)
2060 while (!STAILQ_EMPTY(list)) {
2061 elm = STAILQ_FIRST(list);
2062 STAILQ_REMOVE_HEAD(list, link);
2067 static Objlist_Entry *
2068 objlist_find(Objlist *list, const Obj_Entry *obj)
2072 STAILQ_FOREACH(elm, list, link)
2073 if (elm->obj == obj)
2079 objlist_init(Objlist *list)
2085 objlist_push_head(Objlist *list, Obj_Entry *obj)
2089 elm = NEW(Objlist_Entry);
2091 STAILQ_INSERT_HEAD(list, elm, link);
2095 objlist_push_tail(Objlist *list, Obj_Entry *obj)
2099 elm = NEW(Objlist_Entry);
2101 STAILQ_INSERT_TAIL(list, elm, link);
2105 objlist_remove(Objlist *list, Obj_Entry *obj)
2109 if ((elm = objlist_find(list, obj)) != NULL) {
2110 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2116 * Relocate newly-loaded shared objects. The argument is a pointer to
2117 * the Obj_Entry for the first such object. All objects from the first
2118 * to the end of the list of objects are relocated. Returns 0 on success,
2122 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
2123 RtldLockState *lockstate)
2127 for (obj = first; obj != NULL; obj = obj->next) {
2129 dbg("relocating \"%s\"", obj->path);
2130 if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
2131 obj->symtab == NULL || obj->strtab == NULL) {
2132 _rtld_error("%s: Shared object has no run-time symbol table",
2138 /* There are relocations to the write-protected text segment. */
2139 if (mprotect(obj->mapbase, obj->textsize,
2140 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
2141 _rtld_error("%s: Cannot write-enable text segment: %s",
2142 obj->path, strerror(errno));
2147 /* Process the non-PLT relocations. */
2148 if (reloc_non_plt(obj, rtldobj, lockstate))
2151 if (obj->textrel) { /* Re-protected the text segment. */
2152 if (mprotect(obj->mapbase, obj->textsize,
2153 PROT_READ|PROT_EXEC) == -1) {
2154 _rtld_error("%s: Cannot write-protect text segment: %s",
2155 obj->path, strerror(errno));
2161 /* Set the special PLT or GOT entries. */
2164 /* Process the PLT relocations. */
2165 if (reloc_plt(obj) == -1)
2167 /* Relocate the jump slots if we are doing immediate binding. */
2168 if (obj->bind_now || bind_now)
2169 if (reloc_jmpslots(obj, lockstate) == -1)
2172 if (obj->relro_size > 0) {
2173 if (mprotect(obj->relro_page, obj->relro_size, PROT_READ) == -1) {
2174 _rtld_error("%s: Cannot enforce relro protection: %s",
2175 obj->path, strerror(errno));
2181 * Set up the magic number and version in the Obj_Entry. These
2182 * were checked in the crt1.o from the original ElfKit, so we
2183 * set them for backward compatibility.
2185 obj->magic = RTLD_MAGIC;
2186 obj->version = RTLD_VERSION;
2193 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
2194 * referencing STT_GNU_IFUNC symbols is postponed till the other
2195 * relocations are done. The indirect functions specified as
2196 * ifunc are allowed to call other symbols, so we need to have
2197 * objects relocated before asking for resolution from indirects.
2199 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
2200 * instead of the usual lazy handling of PLT slots. It is
2201 * consistent with how GNU does it.
2204 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, RtldLockState *lockstate)
2206 if (obj->irelative && reloc_iresolve(obj, lockstate) == -1)
2208 if ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
2209 reloc_gnu_ifunc(obj, lockstate) == -1)
2215 resolve_objects_ifunc(Obj_Entry *first, bool bind_now, RtldLockState *lockstate)
2219 for (obj = first; obj != NULL; obj = obj->next) {
2220 if (resolve_object_ifunc(obj, bind_now, lockstate) == -1)
2227 initlist_objects_ifunc(Objlist *list, bool bind_now, RtldLockState *lockstate)
2231 STAILQ_FOREACH(elm, list, link) {
2232 if (resolve_object_ifunc(elm->obj, bind_now, lockstate) == -1)
2239 * Cleanup procedure. It will be called (by the atexit mechanism) just
2240 * before the process exits.
2245 RtldLockState lockstate;
2247 wlock_acquire(rtld_bind_lock, &lockstate);
2249 objlist_call_fini(&list_fini, NULL, &lockstate);
2250 /* No need to remove the items from the list, since we are exiting. */
2251 if (!libmap_disable)
2253 lock_release(rtld_bind_lock, &lockstate);
2257 path_enumerate(const char *path, path_enum_proc callback, void *arg)
2265 path += strspn(path, ":;");
2266 while (*path != '\0') {
2270 len = strcspn(path, ":;");
2272 trans = lm_findn(NULL, path, len);
2274 res = callback(trans, strlen(trans), arg);
2277 res = callback(path, len, arg);
2283 path += strspn(path, ":;");
2289 struct try_library_args {
2297 try_library_path(const char *dir, size_t dirlen, void *param)
2299 struct try_library_args *arg;
2302 if (*dir == '/' || trust) {
2305 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
2308 pathname = arg->buffer;
2309 strncpy(pathname, dir, dirlen);
2310 pathname[dirlen] = '/';
2311 strcpy(pathname + dirlen + 1, arg->name);
2313 dbg(" Trying \"%s\"", pathname);
2314 if (access(pathname, F_OK) == 0) { /* We found it */
2315 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
2316 strcpy(pathname, arg->buffer);
2324 search_library_path(const char *name, const char *path)
2327 struct try_library_args arg;
2333 arg.namelen = strlen(name);
2334 arg.buffer = xmalloc(PATH_MAX);
2335 arg.buflen = PATH_MAX;
2337 p = path_enumerate(path, try_library_path, &arg);
2345 dlclose(void *handle)
2348 RtldLockState lockstate;
2350 wlock_acquire(rtld_bind_lock, &lockstate);
2351 root = dlcheck(handle);
2353 lock_release(rtld_bind_lock, &lockstate);
2356 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
2359 /* Unreference the object and its dependencies. */
2360 root->dl_refcount--;
2362 if (root->refcount == 1) {
2364 * The object will be no longer referenced, so we must unload it.
2365 * First, call the fini functions.
2367 objlist_call_fini(&list_fini, root, &lockstate);
2371 /* Finish cleaning up the newly-unreferenced objects. */
2372 GDB_STATE(RT_DELETE,&root->linkmap);
2373 unload_object(root);
2374 GDB_STATE(RT_CONSISTENT,NULL);
2378 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
2379 lock_release(rtld_bind_lock, &lockstate);
2386 char *msg = error_message;
2387 error_message = NULL;
2392 * This function is deprecated and has no effect.
2395 dllockinit(void *context,
2396 void *(*lock_create)(void *context),
2397 void (*rlock_acquire)(void *lock),
2398 void (*wlock_acquire)(void *lock),
2399 void (*lock_release)(void *lock),
2400 void (*lock_destroy)(void *lock),
2401 void (*context_destroy)(void *context))
2403 static void *cur_context;
2404 static void (*cur_context_destroy)(void *);
2406 /* Just destroy the context from the previous call, if necessary. */
2407 if (cur_context_destroy != NULL)
2408 cur_context_destroy(cur_context);
2409 cur_context = context;
2410 cur_context_destroy = context_destroy;
2414 dlopen(const char *name, int mode)
2417 return (rtld_dlopen(name, -1, mode));
2421 fdlopen(int fd, int mode)
2424 return (rtld_dlopen(NULL, fd, mode));
2428 rtld_dlopen(const char *name, int fd, int mode)
2430 RtldLockState lockstate;
2433 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
2434 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
2435 if (ld_tracing != NULL) {
2436 rlock_acquire(rtld_bind_lock, &lockstate);
2437 if (sigsetjmp(lockstate.env, 0) != 0)
2438 lock_upgrade(rtld_bind_lock, &lockstate);
2439 environ = (char **)*get_program_var_addr("environ", &lockstate);
2440 lock_release(rtld_bind_lock, &lockstate);
2442 lo_flags = RTLD_LO_DLOPEN;
2443 if (mode & RTLD_NODELETE)
2444 lo_flags |= RTLD_LO_NODELETE;
2445 if (mode & RTLD_NOLOAD)
2446 lo_flags |= RTLD_LO_NOLOAD;
2447 if (ld_tracing != NULL)
2448 lo_flags |= RTLD_LO_TRACE;
2450 return (dlopen_object(name, fd, obj_main, lo_flags,
2451 mode & (RTLD_MODEMASK | RTLD_GLOBAL)));
2455 dlopen_cleanup(Obj_Entry *obj)
2460 if (obj->refcount == 0)
2465 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
2468 Obj_Entry **old_obj_tail;
2471 RtldLockState lockstate;
2474 objlist_init(&initlist);
2476 wlock_acquire(rtld_bind_lock, &lockstate);
2477 GDB_STATE(RT_ADD,NULL);
2479 old_obj_tail = obj_tail;
2481 if (name == NULL && fd == -1) {
2485 obj = load_object(name, fd, refobj, lo_flags);
2490 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
2491 objlist_push_tail(&list_global, obj);
2492 if (*old_obj_tail != NULL) { /* We loaded something new. */
2493 assert(*old_obj_tail == obj);
2494 result = load_needed_objects(obj, lo_flags & RTLD_LO_DLOPEN);
2498 result = rtld_verify_versions(&obj->dagmembers);
2499 if (result != -1 && ld_tracing)
2501 if (result == -1 || (relocate_objects(obj, (mode & RTLD_MODEMASK)
2502 == RTLD_NOW, &obj_rtld, &lockstate)) == -1) {
2503 dlopen_cleanup(obj);
2506 /* Make list of init functions to call. */
2507 initlist_add_objects(obj, &obj->next, &initlist);
2512 * Bump the reference counts for objects on this DAG. If
2513 * this is the first dlopen() call for the object that was
2514 * already loaded as a dependency, initialize the dag
2520 if ((lo_flags & RTLD_LO_TRACE) != 0)
2523 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
2524 obj->z_nodelete) && !obj->ref_nodel) {
2525 dbg("obj %s nodelete", obj->path);
2527 obj->z_nodelete = obj->ref_nodel = true;
2531 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
2533 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
2535 map_stacks_exec(&lockstate);
2537 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
2538 &lockstate) == -1) {
2539 objlist_clear(&initlist);
2540 dlopen_cleanup(obj);
2541 lock_release(rtld_bind_lock, &lockstate);
2545 /* Call the init functions. */
2546 objlist_call_init(&initlist, &lockstate);
2547 objlist_clear(&initlist);
2548 lock_release(rtld_bind_lock, &lockstate);
2551 trace_loaded_objects(obj);
2552 lock_release(rtld_bind_lock, &lockstate);
2557 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
2561 const Obj_Entry *obj, *defobj;
2564 RtldLockState lockstate;
2569 symlook_init(&req, name);
2571 req.flags = flags | SYMLOOK_IN_PLT;
2572 req.lockstate = &lockstate;
2574 rlock_acquire(rtld_bind_lock, &lockstate);
2575 if (sigsetjmp(lockstate.env, 0) != 0)
2576 lock_upgrade(rtld_bind_lock, &lockstate);
2577 if (handle == NULL || handle == RTLD_NEXT ||
2578 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
2580 if ((obj = obj_from_addr(retaddr)) == NULL) {
2581 _rtld_error("Cannot determine caller's shared object");
2582 lock_release(rtld_bind_lock, &lockstate);
2585 if (handle == NULL) { /* Just the caller's shared object. */
2586 res = symlook_obj(&req, obj);
2589 defobj = req.defobj_out;
2591 } else if (handle == RTLD_NEXT || /* Objects after caller's */
2592 handle == RTLD_SELF) { /* ... caller included */
2593 if (handle == RTLD_NEXT)
2595 for (; obj != NULL; obj = obj->next) {
2596 res = symlook_obj(&req, obj);
2599 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) {
2601 defobj = req.defobj_out;
2602 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2608 * Search the dynamic linker itself, and possibly resolve the
2609 * symbol from there. This is how the application links to
2610 * dynamic linker services such as dlopen.
2612 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2613 res = symlook_obj(&req, &obj_rtld);
2616 defobj = req.defobj_out;
2620 assert(handle == RTLD_DEFAULT);
2621 res = symlook_default(&req, obj);
2623 defobj = req.defobj_out;
2628 if ((obj = dlcheck(handle)) == NULL) {
2629 lock_release(rtld_bind_lock, &lockstate);
2633 donelist_init(&donelist);
2634 if (obj->mainprog) {
2635 /* Handle obtained by dlopen(NULL, ...) implies global scope. */
2636 res = symlook_global(&req, &donelist);
2639 defobj = req.defobj_out;
2642 * Search the dynamic linker itself, and possibly resolve the
2643 * symbol from there. This is how the application links to
2644 * dynamic linker services such as dlopen.
2646 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2647 res = symlook_obj(&req, &obj_rtld);
2650 defobj = req.defobj_out;
2655 /* Search the whole DAG rooted at the given object. */
2656 res = symlook_list(&req, &obj->dagmembers, &donelist);
2659 defobj = req.defobj_out;
2665 lock_release(rtld_bind_lock, &lockstate);
2668 * The value required by the caller is derived from the value
2669 * of the symbol. For the ia64 architecture, we need to
2670 * construct a function descriptor which the caller can use to
2671 * call the function with the right 'gp' value. For other
2672 * architectures and for non-functions, the value is simply
2673 * the relocated value of the symbol.
2675 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
2676 return (make_function_pointer(def, defobj));
2677 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
2678 return (rtld_resolve_ifunc(defobj, def));
2680 return (defobj->relocbase + def->st_value);
2683 _rtld_error("Undefined symbol \"%s\"", name);
2684 lock_release(rtld_bind_lock, &lockstate);
2689 dlsym(void *handle, const char *name)
2691 return do_dlsym(handle, name, __builtin_return_address(0), NULL,
2696 dlfunc(void *handle, const char *name)
2703 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
2709 dlvsym(void *handle, const char *name, const char *version)
2713 ventry.name = version;
2715 ventry.hash = elf_hash(version);
2717 return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
2722 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
2724 const Obj_Entry *obj;
2725 RtldLockState lockstate;
2727 rlock_acquire(rtld_bind_lock, &lockstate);
2728 obj = obj_from_addr(addr);
2730 _rtld_error("No shared object contains address");
2731 lock_release(rtld_bind_lock, &lockstate);
2734 rtld_fill_dl_phdr_info(obj, phdr_info);
2735 lock_release(rtld_bind_lock, &lockstate);
2740 dladdr(const void *addr, Dl_info *info)
2742 const Obj_Entry *obj;
2745 unsigned long symoffset;
2746 RtldLockState lockstate;
2748 rlock_acquire(rtld_bind_lock, &lockstate);
2749 obj = obj_from_addr(addr);
2751 _rtld_error("No shared object contains address");
2752 lock_release(rtld_bind_lock, &lockstate);
2755 info->dli_fname = obj->path;
2756 info->dli_fbase = obj->mapbase;
2757 info->dli_saddr = (void *)0;
2758 info->dli_sname = NULL;
2761 * Walk the symbol list looking for the symbol whose address is
2762 * closest to the address sent in.
2764 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
2765 def = obj->symtab + symoffset;
2768 * For skip the symbol if st_shndx is either SHN_UNDEF or
2771 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
2775 * If the symbol is greater than the specified address, or if it
2776 * is further away from addr than the current nearest symbol,
2779 symbol_addr = obj->relocbase + def->st_value;
2780 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
2783 /* Update our idea of the nearest symbol. */
2784 info->dli_sname = obj->strtab + def->st_name;
2785 info->dli_saddr = symbol_addr;
2788 if (info->dli_saddr == addr)
2791 lock_release(rtld_bind_lock, &lockstate);
2796 dlinfo(void *handle, int request, void *p)
2798 const Obj_Entry *obj;
2799 RtldLockState lockstate;
2802 rlock_acquire(rtld_bind_lock, &lockstate);
2804 if (handle == NULL || handle == RTLD_SELF) {
2807 retaddr = __builtin_return_address(0); /* __GNUC__ only */
2808 if ((obj = obj_from_addr(retaddr)) == NULL)
2809 _rtld_error("Cannot determine caller's shared object");
2811 obj = dlcheck(handle);
2814 lock_release(rtld_bind_lock, &lockstate);
2820 case RTLD_DI_LINKMAP:
2821 *((struct link_map const **)p) = &obj->linkmap;
2823 case RTLD_DI_ORIGIN:
2824 error = rtld_dirname(obj->path, p);
2827 case RTLD_DI_SERINFOSIZE:
2828 case RTLD_DI_SERINFO:
2829 error = do_search_info(obj, request, (struct dl_serinfo *)p);
2833 _rtld_error("Invalid request %d passed to dlinfo()", request);
2837 lock_release(rtld_bind_lock, &lockstate);
2843 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
2846 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
2847 phdr_info->dlpi_name = STAILQ_FIRST(&obj->names) ?
2848 STAILQ_FIRST(&obj->names)->name : obj->path;
2849 phdr_info->dlpi_phdr = obj->phdr;
2850 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
2851 phdr_info->dlpi_tls_modid = obj->tlsindex;
2852 phdr_info->dlpi_tls_data = obj->tlsinit;
2853 phdr_info->dlpi_adds = obj_loads;
2854 phdr_info->dlpi_subs = obj_loads - obj_count;
2858 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
2860 struct dl_phdr_info phdr_info;
2861 const Obj_Entry *obj;
2862 RtldLockState bind_lockstate, phdr_lockstate;
2865 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
2866 rlock_acquire(rtld_bind_lock, &bind_lockstate);
2870 for (obj = obj_list; obj != NULL; obj = obj->next) {
2871 rtld_fill_dl_phdr_info(obj, &phdr_info);
2872 if ((error = callback(&phdr_info, sizeof phdr_info, param)) != 0)
2876 lock_release(rtld_bind_lock, &bind_lockstate);
2877 lock_release(rtld_phdr_lock, &phdr_lockstate);
2882 struct fill_search_info_args {
2885 Dl_serinfo *serinfo;
2886 Dl_serpath *serpath;
2891 fill_search_info(const char *dir, size_t dirlen, void *param)
2893 struct fill_search_info_args *arg;
2897 if (arg->request == RTLD_DI_SERINFOSIZE) {
2898 arg->serinfo->dls_cnt ++;
2899 arg->serinfo->dls_size += sizeof(Dl_serpath) + dirlen + 1;
2901 struct dl_serpath *s_entry;
2903 s_entry = arg->serpath;
2904 s_entry->dls_name = arg->strspace;
2905 s_entry->dls_flags = arg->flags;
2907 strncpy(arg->strspace, dir, dirlen);
2908 arg->strspace[dirlen] = '\0';
2910 arg->strspace += dirlen + 1;
2918 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
2920 struct dl_serinfo _info;
2921 struct fill_search_info_args args;
2923 args.request = RTLD_DI_SERINFOSIZE;
2924 args.serinfo = &_info;
2926 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2929 path_enumerate(ld_library_path, fill_search_info, &args);
2930 path_enumerate(obj->rpath, fill_search_info, &args);
2931 path_enumerate(gethints(), fill_search_info, &args);
2932 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
2935 if (request == RTLD_DI_SERINFOSIZE) {
2936 info->dls_size = _info.dls_size;
2937 info->dls_cnt = _info.dls_cnt;
2941 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
2942 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
2946 args.request = RTLD_DI_SERINFO;
2947 args.serinfo = info;
2948 args.serpath = &info->dls_serpath[0];
2949 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
2951 args.flags = LA_SER_LIBPATH;
2952 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
2955 args.flags = LA_SER_RUNPATH;
2956 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
2959 args.flags = LA_SER_CONFIG;
2960 if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
2963 args.flags = LA_SER_DEFAULT;
2964 if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
2970 rtld_dirname(const char *path, char *bname)
2974 /* Empty or NULL string gets treated as "." */
2975 if (path == NULL || *path == '\0') {
2981 /* Strip trailing slashes */
2982 endp = path + strlen(path) - 1;
2983 while (endp > path && *endp == '/')
2986 /* Find the start of the dir */
2987 while (endp > path && *endp != '/')
2990 /* Either the dir is "/" or there are no slashes */
2992 bname[0] = *endp == '/' ? '/' : '.';
2998 } while (endp > path && *endp == '/');
3001 if (endp - path + 2 > PATH_MAX)
3003 _rtld_error("Filename is too long: %s", path);
3007 strncpy(bname, path, endp - path + 1);
3008 bname[endp - path + 1] = '\0';
3013 rtld_dirname_abs(const char *path, char *base)
3015 char base_rel[PATH_MAX];
3017 if (rtld_dirname(path, base) == -1)
3021 if (getcwd(base_rel, sizeof(base_rel)) == NULL ||
3022 strlcat(base_rel, "/", sizeof(base_rel)) >= sizeof(base_rel) ||
3023 strlcat(base_rel, base, sizeof(base_rel)) >= sizeof(base_rel))
3025 strcpy(base, base_rel);
3030 linkmap_add(Obj_Entry *obj)
3032 struct link_map *l = &obj->linkmap;
3033 struct link_map *prev;
3035 obj->linkmap.l_name = obj->path;
3036 obj->linkmap.l_addr = obj->mapbase;
3037 obj->linkmap.l_ld = obj->dynamic;
3039 /* GDB needs load offset on MIPS to use the symbols */
3040 obj->linkmap.l_offs = obj->relocbase;
3043 if (r_debug.r_map == NULL) {
3049 * Scan to the end of the list, but not past the entry for the
3050 * dynamic linker, which we want to keep at the very end.
3052 for (prev = r_debug.r_map;
3053 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
3054 prev = prev->l_next)
3057 /* Link in the new entry. */
3059 l->l_next = prev->l_next;
3060 if (l->l_next != NULL)
3061 l->l_next->l_prev = l;
3066 linkmap_delete(Obj_Entry *obj)
3068 struct link_map *l = &obj->linkmap;
3070 if (l->l_prev == NULL) {
3071 if ((r_debug.r_map = l->l_next) != NULL)
3072 l->l_next->l_prev = NULL;
3076 if ((l->l_prev->l_next = l->l_next) != NULL)
3077 l->l_next->l_prev = l->l_prev;
3081 * Function for the debugger to set a breakpoint on to gain control.
3083 * The two parameters allow the debugger to easily find and determine
3084 * what the runtime loader is doing and to whom it is doing it.
3086 * When the loadhook trap is hit (r_debug_state, set at program
3087 * initialization), the arguments can be found on the stack:
3089 * +8 struct link_map *m
3090 * +4 struct r_debug *rd
3094 r_debug_state(struct r_debug* rd, struct link_map *m)
3097 * The following is a hack to force the compiler to emit calls to
3098 * this function, even when optimizing. If the function is empty,
3099 * the compiler is not obliged to emit any code for calls to it,
3100 * even when marked __noinline. However, gdb depends on those
3103 __asm __volatile("" : : : "memory");
3107 * Get address of the pointer variable in the main program.
3108 * Prefer non-weak symbol over the weak one.
3110 static const void **
3111 get_program_var_addr(const char *name, RtldLockState *lockstate)
3116 symlook_init(&req, name);
3117 req.lockstate = lockstate;
3118 donelist_init(&donelist);
3119 if (symlook_global(&req, &donelist) != 0)
3121 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
3122 return ((const void **)make_function_pointer(req.sym_out,
3124 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
3125 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
3127 return ((const void **)(req.defobj_out->relocbase +
3128 req.sym_out->st_value));
3132 * Set a pointer variable in the main program to the given value. This
3133 * is used to set key variables such as "environ" before any of the
3134 * init functions are called.
3137 set_program_var(const char *name, const void *value)
3141 if ((addr = get_program_var_addr(name, NULL)) != NULL) {
3142 dbg("\"%s\": *%p <-- %p", name, addr, value);
3148 * Search the global objects, including dependencies and main object,
3149 * for the given symbol.
3152 symlook_global(SymLook *req, DoneList *donelist)
3155 const Objlist_Entry *elm;
3158 symlook_init_from_req(&req1, req);
3160 /* Search all objects loaded at program start up. */
3161 if (req->defobj_out == NULL ||
3162 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3163 res = symlook_list(&req1, &list_main, donelist);
3164 if (res == 0 && (req->defobj_out == NULL ||
3165 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3166 req->sym_out = req1.sym_out;
3167 req->defobj_out = req1.defobj_out;
3168 assert(req->defobj_out != NULL);
3172 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
3173 STAILQ_FOREACH(elm, &list_global, link) {
3174 if (req->defobj_out != NULL &&
3175 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3177 res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
3178 if (res == 0 && (req->defobj_out == NULL ||
3179 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3180 req->sym_out = req1.sym_out;
3181 req->defobj_out = req1.defobj_out;
3182 assert(req->defobj_out != NULL);
3186 return (req->sym_out != NULL ? 0 : ESRCH);
3190 * Given a symbol name in a referencing object, find the corresponding
3191 * definition of the symbol. Returns a pointer to the symbol, or NULL if
3192 * no definition was found. Returns a pointer to the Obj_Entry of the
3193 * defining object via the reference parameter DEFOBJ_OUT.
3196 symlook_default(SymLook *req, const Obj_Entry *refobj)
3199 const Objlist_Entry *elm;
3203 donelist_init(&donelist);
3204 symlook_init_from_req(&req1, req);
3206 /* Look first in the referencing object if linked symbolically. */
3207 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
3208 res = symlook_obj(&req1, refobj);
3210 req->sym_out = req1.sym_out;
3211 req->defobj_out = req1.defobj_out;
3212 assert(req->defobj_out != NULL);
3216 symlook_global(req, &donelist);
3218 /* Search all dlopened DAGs containing the referencing object. */
3219 STAILQ_FOREACH(elm, &refobj->dldags, link) {
3220 if (req->sym_out != NULL &&
3221 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3223 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
3224 if (res == 0 && (req->sym_out == NULL ||
3225 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3226 req->sym_out = req1.sym_out;
3227 req->defobj_out = req1.defobj_out;
3228 assert(req->defobj_out != NULL);
3233 * Search the dynamic linker itself, and possibly resolve the
3234 * symbol from there. This is how the application links to
3235 * dynamic linker services such as dlopen.
3237 if (req->sym_out == NULL ||
3238 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3239 res = symlook_obj(&req1, &obj_rtld);
3241 req->sym_out = req1.sym_out;
3242 req->defobj_out = req1.defobj_out;
3243 assert(req->defobj_out != NULL);
3247 return (req->sym_out != NULL ? 0 : ESRCH);
3251 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
3254 const Obj_Entry *defobj;
3255 const Objlist_Entry *elm;
3261 STAILQ_FOREACH(elm, objlist, link) {
3262 if (donelist_check(dlp, elm->obj))
3264 symlook_init_from_req(&req1, req);
3265 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
3266 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3268 defobj = req1.defobj_out;
3269 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3276 req->defobj_out = defobj;
3283 * Search the chain of DAGS cointed to by the given Needed_Entry
3284 * for a symbol of the given name. Each DAG is scanned completely
3285 * before advancing to the next one. Returns a pointer to the symbol,
3286 * or NULL if no definition was found.
3289 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
3292 const Needed_Entry *n;
3293 const Obj_Entry *defobj;
3299 symlook_init_from_req(&req1, req);
3300 for (n = needed; n != NULL; n = n->next) {
3301 if (n->obj == NULL ||
3302 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
3304 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3306 defobj = req1.defobj_out;
3307 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3313 req->defobj_out = defobj;
3320 * Search the symbol table of a single shared object for a symbol of
3321 * the given name and version, if requested. Returns a pointer to the
3322 * symbol, or NULL if no definition was found. If the object is
3323 * filter, return filtered symbol from filtee.
3325 * The symbol's hash value is passed in for efficiency reasons; that
3326 * eliminates many recomputations of the hash value.
3329 symlook_obj(SymLook *req, const Obj_Entry *obj)
3335 mres = symlook_obj1(req, obj);
3337 if (obj->needed_filtees != NULL) {
3338 load_filtees(__DECONST(Obj_Entry *, obj), 0, req->lockstate);
3339 donelist_init(&donelist);
3340 symlook_init_from_req(&req1, req);
3341 res = symlook_needed(&req1, obj->needed_filtees, &donelist);
3343 req->sym_out = req1.sym_out;
3344 req->defobj_out = req1.defobj_out;
3348 if (obj->needed_aux_filtees != NULL) {
3349 load_filtees(__DECONST(Obj_Entry *, obj), 0, req->lockstate);
3350 donelist_init(&donelist);
3351 symlook_init_from_req(&req1, req);
3352 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
3354 req->sym_out = req1.sym_out;
3355 req->defobj_out = req1.defobj_out;
3364 symlook_obj1(SymLook *req, const Obj_Entry *obj)
3366 unsigned long symnum;
3367 const Elf_Sym *vsymp;
3371 if (obj->buckets == NULL)
3376 symnum = obj->buckets[req->hash % obj->nbuckets];
3378 for (; symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
3379 const Elf_Sym *symp;
3382 if (symnum >= obj->nchains)
3383 return (ESRCH); /* Bad object */
3385 symp = obj->symtab + symnum;
3386 strp = obj->strtab + symp->st_name;
3388 switch (ELF_ST_TYPE(symp->st_info)) {
3393 if (symp->st_value == 0)
3397 if (symp->st_shndx != SHN_UNDEF)
3400 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
3401 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
3408 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
3411 if (req->ventry == NULL) {
3412 if (obj->versyms != NULL) {
3413 verndx = VER_NDX(obj->versyms[symnum]);
3414 if (verndx > obj->vernum) {
3415 _rtld_error("%s: symbol %s references wrong version %d",
3416 obj->path, obj->strtab + symnum, verndx);
3420 * If we are not called from dlsym (i.e. this is a normal
3421 * relocation from unversioned binary), accept the symbol
3422 * immediately if it happens to have first version after
3423 * this shared object became versioned. Otherwise, if
3424 * symbol is versioned and not hidden, remember it. If it
3425 * is the only symbol with this name exported by the
3426 * shared object, it will be returned as a match at the
3427 * end of the function. If symbol is global (verndx < 2)
3428 * accept it unconditionally.
3430 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
3431 verndx == VER_NDX_GIVEN) {
3432 req->sym_out = symp;
3433 req->defobj_out = obj;
3436 else if (verndx >= VER_NDX_GIVEN) {
3437 if ((obj->versyms[symnum] & VER_NDX_HIDDEN) == 0) {
3445 req->sym_out = symp;
3446 req->defobj_out = obj;
3449 if (obj->versyms == NULL) {
3450 if (object_match_name(obj, req->ventry->name)) {
3451 _rtld_error("%s: object %s should provide version %s for "
3452 "symbol %s", obj_rtld.path, obj->path,
3453 req->ventry->name, obj->strtab + symnum);
3457 verndx = VER_NDX(obj->versyms[symnum]);
3458 if (verndx > obj->vernum) {
3459 _rtld_error("%s: symbol %s references wrong version %d",
3460 obj->path, obj->strtab + symnum, verndx);
3463 if (obj->vertab[verndx].hash != req->ventry->hash ||
3464 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
3466 * Version does not match. Look if this is a global symbol
3467 * and if it is not hidden. If global symbol (verndx < 2)
3468 * is available, use it. Do not return symbol if we are
3469 * called by dlvsym, because dlvsym looks for a specific
3470 * version and default one is not what dlvsym wants.
3472 if ((req->flags & SYMLOOK_DLSYM) ||
3473 (obj->versyms[symnum] & VER_NDX_HIDDEN) ||
3474 (verndx >= VER_NDX_GIVEN))
3478 req->sym_out = symp;
3479 req->defobj_out = obj;
3484 req->sym_out = vsymp;
3485 req->defobj_out = obj;
3492 trace_loaded_objects(Obj_Entry *obj)
3494 char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
3497 if ((main_local = getenv(LD_ "TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
3500 if ((fmt1 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT1")) == NULL)
3501 fmt1 = "\t%o => %p (%x)\n";
3503 if ((fmt2 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT2")) == NULL)
3504 fmt2 = "\t%o (%x)\n";
3506 list_containers = getenv(LD_ "TRACE_LOADED_OBJECTS_ALL");
3508 for (; obj; obj = obj->next) {
3509 Needed_Entry *needed;
3513 if (list_containers && obj->needed != NULL)
3514 rtld_printf("%s:\n", obj->path);
3515 for (needed = obj->needed; needed; needed = needed->next) {
3516 if (needed->obj != NULL) {
3517 if (needed->obj->traced && !list_containers)
3519 needed->obj->traced = true;
3520 path = needed->obj->path;
3524 name = (char *)obj->strtab + needed->name;
3525 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
3527 fmt = is_lib ? fmt1 : fmt2;
3528 while ((c = *fmt++) != '\0') {
3554 rtld_putstr(main_local);
3557 rtld_putstr(obj_main->path);
3564 rtld_printf("%d", sodp->sod_major);
3567 rtld_printf("%d", sodp->sod_minor);
3574 rtld_printf("%p", needed->obj ? needed->obj->mapbase :
3587 * Unload a dlopened object and its dependencies from memory and from
3588 * our data structures. It is assumed that the DAG rooted in the
3589 * object has already been unreferenced, and that the object has a
3590 * reference count of 0.
3593 unload_object(Obj_Entry *root)
3598 assert(root->refcount == 0);
3601 * Pass over the DAG removing unreferenced objects from
3602 * appropriate lists.
3604 unlink_object(root);
3606 /* Unmap all objects that are no longer referenced. */
3607 linkp = &obj_list->next;
3608 while ((obj = *linkp) != NULL) {
3609 if (obj->refcount == 0) {
3610 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
3612 dbg("unloading \"%s\"", obj->path);
3613 unload_filtees(root);
3614 munmap(obj->mapbase, obj->mapsize);
3615 linkmap_delete(obj);
3626 unlink_object(Obj_Entry *root)
3630 if (root->refcount == 0) {
3631 /* Remove the object from the RTLD_GLOBAL list. */
3632 objlist_remove(&list_global, root);
3634 /* Remove the object from all objects' DAG lists. */
3635 STAILQ_FOREACH(elm, &root->dagmembers, link) {
3636 objlist_remove(&elm->obj->dldags, root);
3637 if (elm->obj != root)
3638 unlink_object(elm->obj);
3644 ref_dag(Obj_Entry *root)
3648 assert(root->dag_inited);
3649 STAILQ_FOREACH(elm, &root->dagmembers, link)
3650 elm->obj->refcount++;
3654 unref_dag(Obj_Entry *root)
3658 assert(root->dag_inited);
3659 STAILQ_FOREACH(elm, &root->dagmembers, link)
3660 elm->obj->refcount--;
3664 * Common code for MD __tls_get_addr().
3666 static void *tls_get_addr_slow(Elf_Addr **, int, size_t) __noinline;
3668 tls_get_addr_slow(Elf_Addr **dtvp, int index, size_t offset)
3670 Elf_Addr *newdtv, *dtv;
3671 RtldLockState lockstate;
3675 /* Check dtv generation in case new modules have arrived */
3676 if (dtv[0] != tls_dtv_generation) {
3677 wlock_acquire(rtld_bind_lock, &lockstate);
3678 newdtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
3680 if (to_copy > tls_max_index)
3681 to_copy = tls_max_index;
3682 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
3683 newdtv[0] = tls_dtv_generation;
3684 newdtv[1] = tls_max_index;
3686 lock_release(rtld_bind_lock, &lockstate);
3687 dtv = *dtvp = newdtv;
3690 /* Dynamically allocate module TLS if necessary */
3691 if (dtv[index + 1] == 0) {
3692 /* Signal safe, wlock will block out signals. */
3693 wlock_acquire(rtld_bind_lock, &lockstate);
3694 if (!dtv[index + 1])
3695 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
3696 lock_release(rtld_bind_lock, &lockstate);
3698 return ((void *)(dtv[index + 1] + offset));
3702 tls_get_addr_common(Elf_Addr **dtvp, int index, size_t offset)
3707 /* Check dtv generation in case new modules have arrived */
3708 if (__predict_true(dtv[0] == tls_dtv_generation &&
3709 dtv[index + 1] != 0))
3710 return ((void *)(dtv[index + 1] + offset));
3711 return (tls_get_addr_slow(dtvp, index, offset));
3714 /* XXX not sure what variants to use for arm. */
3716 #if defined(__ia64__) || defined(__powerpc__)
3719 * Allocate Static TLS using the Variant I method.
3722 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
3731 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
3734 assert(tcbsize >= TLS_TCB_SIZE);
3735 tcb = calloc(1, tls_static_space - TLS_TCB_SIZE + tcbsize);
3736 tls = (Elf_Addr **)(tcb + tcbsize - TLS_TCB_SIZE);
3738 if (oldtcb != NULL) {
3739 memcpy(tls, oldtcb, tls_static_space);
3742 /* Adjust the DTV. */
3744 for (i = 0; i < dtv[1]; i++) {
3745 if (dtv[i+2] >= (Elf_Addr)oldtcb &&
3746 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
3747 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tls;
3751 dtv = calloc(tls_max_index + 2, sizeof(Elf_Addr));
3753 dtv[0] = tls_dtv_generation;
3754 dtv[1] = tls_max_index;
3756 for (obj = objs; obj; obj = obj->next) {
3757 if (obj->tlsoffset > 0) {
3758 addr = (Elf_Addr)tls + obj->tlsoffset;
3759 if (obj->tlsinitsize > 0)
3760 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
3761 if (obj->tlssize > obj->tlsinitsize)
3762 memset((void*) (addr + obj->tlsinitsize), 0,
3763 obj->tlssize - obj->tlsinitsize);
3764 dtv[obj->tlsindex + 1] = addr;
3773 free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
3776 Elf_Addr tlsstart, tlsend;
3779 assert(tcbsize >= TLS_TCB_SIZE);
3781 tlsstart = (Elf_Addr)tcb + tcbsize - TLS_TCB_SIZE;
3782 tlsend = tlsstart + tls_static_space;
3784 dtv = *(Elf_Addr **)tlsstart;
3786 for (i = 0; i < dtvsize; i++) {
3787 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
3788 free((void*)dtv[i+2]);
3797 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) || \
3798 defined(__arm__) || defined(__mips__)
3801 * Allocate Static TLS using the Variant II method.
3804 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
3809 Elf_Addr *dtv, *olddtv;
3810 Elf_Addr segbase, oldsegbase, addr;
3813 size = round(tls_static_space, tcbalign);
3815 assert(tcbsize >= 2*sizeof(Elf_Addr));
3816 tls = calloc(1, size + tcbsize);
3817 dtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
3819 segbase = (Elf_Addr)(tls + size);
3820 ((Elf_Addr*)segbase)[0] = segbase;
3821 ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
3823 dtv[0] = tls_dtv_generation;
3824 dtv[1] = tls_max_index;
3828 * Copy the static TLS block over whole.
3830 oldsegbase = (Elf_Addr) oldtls;
3831 memcpy((void *)(segbase - tls_static_space),
3832 (const void *)(oldsegbase - tls_static_space),
3836 * If any dynamic TLS blocks have been created tls_get_addr(),
3839 olddtv = ((Elf_Addr**)oldsegbase)[1];
3840 for (i = 0; i < olddtv[1]; i++) {
3841 if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
3842 dtv[i+2] = olddtv[i+2];
3848 * We assume that this block was the one we created with
3849 * allocate_initial_tls().
3851 free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
3853 for (obj = objs; obj; obj = obj->next) {
3854 if (obj->tlsoffset) {
3855 addr = segbase - obj->tlsoffset;
3856 memset((void*) (addr + obj->tlsinitsize),
3857 0, obj->tlssize - obj->tlsinitsize);
3859 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
3860 dtv[obj->tlsindex + 1] = addr;
3865 return (void*) segbase;
3869 free_tls(void *tls, size_t tcbsize, size_t tcbalign)
3874 Elf_Addr tlsstart, tlsend;
3877 * Figure out the size of the initial TLS block so that we can
3878 * find stuff which ___tls_get_addr() allocated dynamically.
3880 size = round(tls_static_space, tcbalign);
3882 dtv = ((Elf_Addr**)tls)[1];
3884 tlsend = (Elf_Addr) tls;
3885 tlsstart = tlsend - size;
3886 for (i = 0; i < dtvsize; i++) {
3887 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] > tlsend)) {
3888 free((void*) dtv[i+2]);
3892 free((void*) tlsstart);
3899 * Allocate TLS block for module with given index.
3902 allocate_module_tls(int index)
3907 for (obj = obj_list; obj; obj = obj->next) {
3908 if (obj->tlsindex == index)
3912 _rtld_error("Can't find module with TLS index %d", index);
3916 p = malloc(obj->tlssize);
3918 _rtld_error("Cannot allocate TLS block for index %d", index);
3921 memcpy(p, obj->tlsinit, obj->tlsinitsize);
3922 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
3928 allocate_tls_offset(Obj_Entry *obj)
3935 if (obj->tlssize == 0) {
3936 obj->tls_done = true;
3940 if (obj->tlsindex == 1)
3941 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
3943 off = calculate_tls_offset(tls_last_offset, tls_last_size,
3944 obj->tlssize, obj->tlsalign);
3947 * If we have already fixed the size of the static TLS block, we
3948 * must stay within that size. When allocating the static TLS, we
3949 * leave a small amount of space spare to be used for dynamically
3950 * loading modules which use static TLS.
3952 if (tls_static_space) {
3953 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
3957 tls_last_offset = obj->tlsoffset = off;
3958 tls_last_size = obj->tlssize;
3959 obj->tls_done = true;
3965 free_tls_offset(Obj_Entry *obj)
3969 * If we were the last thing to allocate out of the static TLS
3970 * block, we give our space back to the 'allocator'. This is a
3971 * simplistic workaround to allow libGL.so.1 to be loaded and
3972 * unloaded multiple times.
3974 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
3975 == calculate_tls_end(tls_last_offset, tls_last_size)) {
3976 tls_last_offset -= obj->tlssize;
3982 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
3985 RtldLockState lockstate;
3987 wlock_acquire(rtld_bind_lock, &lockstate);
3988 ret = allocate_tls(obj_list, oldtls, tcbsize, tcbalign);
3989 lock_release(rtld_bind_lock, &lockstate);
3994 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
3996 RtldLockState lockstate;
3998 wlock_acquire(rtld_bind_lock, &lockstate);
3999 free_tls(tcb, tcbsize, tcbalign);
4000 lock_release(rtld_bind_lock, &lockstate);
4004 object_add_name(Obj_Entry *obj, const char *name)
4010 entry = malloc(sizeof(Name_Entry) + len);
4012 if (entry != NULL) {
4013 strcpy(entry->name, name);
4014 STAILQ_INSERT_TAIL(&obj->names, entry, link);
4019 object_match_name(const Obj_Entry *obj, const char *name)
4023 STAILQ_FOREACH(entry, &obj->names, link) {
4024 if (strcmp(name, entry->name) == 0)
4031 locate_dependency(const Obj_Entry *obj, const char *name)
4033 const Objlist_Entry *entry;
4034 const Needed_Entry *needed;
4036 STAILQ_FOREACH(entry, &list_main, link) {
4037 if (object_match_name(entry->obj, name))
4041 for (needed = obj->needed; needed != NULL; needed = needed->next) {
4042 if (strcmp(obj->strtab + needed->name, name) == 0 ||
4043 (needed->obj != NULL && object_match_name(needed->obj, name))) {
4045 * If there is DT_NEEDED for the name we are looking for,
4046 * we are all set. Note that object might not be found if
4047 * dependency was not loaded yet, so the function can
4048 * return NULL here. This is expected and handled
4049 * properly by the caller.
4051 return (needed->obj);
4054 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
4060 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
4061 const Elf_Vernaux *vna)
4063 const Elf_Verdef *vd;
4064 const char *vername;
4066 vername = refobj->strtab + vna->vna_name;
4067 vd = depobj->verdef;
4069 _rtld_error("%s: version %s required by %s not defined",
4070 depobj->path, vername, refobj->path);
4074 if (vd->vd_version != VER_DEF_CURRENT) {
4075 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
4076 depobj->path, vd->vd_version);
4079 if (vna->vna_hash == vd->vd_hash) {
4080 const Elf_Verdaux *aux = (const Elf_Verdaux *)
4081 ((char *)vd + vd->vd_aux);
4082 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
4085 if (vd->vd_next == 0)
4087 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4089 if (vna->vna_flags & VER_FLG_WEAK)
4091 _rtld_error("%s: version %s required by %s not found",
4092 depobj->path, vername, refobj->path);
4097 rtld_verify_object_versions(Obj_Entry *obj)
4099 const Elf_Verneed *vn;
4100 const Elf_Verdef *vd;
4101 const Elf_Verdaux *vda;
4102 const Elf_Vernaux *vna;
4103 const Obj_Entry *depobj;
4104 int maxvernum, vernum;
4108 * Walk over defined and required version records and figure out
4109 * max index used by any of them. Do very basic sanity checking
4113 while (vn != NULL) {
4114 if (vn->vn_version != VER_NEED_CURRENT) {
4115 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
4116 obj->path, vn->vn_version);
4119 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4121 vernum = VER_NEED_IDX(vna->vna_other);
4122 if (vernum > maxvernum)
4124 if (vna->vna_next == 0)
4126 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4128 if (vn->vn_next == 0)
4130 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4134 while (vd != NULL) {
4135 if (vd->vd_version != VER_DEF_CURRENT) {
4136 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
4137 obj->path, vd->vd_version);
4140 vernum = VER_DEF_IDX(vd->vd_ndx);
4141 if (vernum > maxvernum)
4143 if (vd->vd_next == 0)
4145 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4152 * Store version information in array indexable by version index.
4153 * Verify that object version requirements are satisfied along the
4156 obj->vernum = maxvernum + 1;
4157 obj->vertab = calloc(obj->vernum, sizeof(Ver_Entry));
4160 while (vd != NULL) {
4161 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
4162 vernum = VER_DEF_IDX(vd->vd_ndx);
4163 assert(vernum <= maxvernum);
4164 vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
4165 obj->vertab[vernum].hash = vd->vd_hash;
4166 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
4167 obj->vertab[vernum].file = NULL;
4168 obj->vertab[vernum].flags = 0;
4170 if (vd->vd_next == 0)
4172 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4176 while (vn != NULL) {
4177 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
4180 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4182 if (check_object_provided_version(obj, depobj, vna))
4184 vernum = VER_NEED_IDX(vna->vna_other);
4185 assert(vernum <= maxvernum);
4186 obj->vertab[vernum].hash = vna->vna_hash;
4187 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
4188 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
4189 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
4190 VER_INFO_HIDDEN : 0;
4191 if (vna->vna_next == 0)
4193 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4195 if (vn->vn_next == 0)
4197 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4203 rtld_verify_versions(const Objlist *objlist)
4205 Objlist_Entry *entry;
4209 STAILQ_FOREACH(entry, objlist, link) {
4211 * Skip dummy objects or objects that have their version requirements
4214 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
4216 if (rtld_verify_object_versions(entry->obj) == -1) {
4218 if (ld_tracing == NULL)
4222 if (rc == 0 || ld_tracing != NULL)
4223 rc = rtld_verify_object_versions(&obj_rtld);
4228 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
4233 vernum = VER_NDX(obj->versyms[symnum]);
4234 if (vernum >= obj->vernum) {
4235 _rtld_error("%s: symbol %s has wrong verneed value %d",
4236 obj->path, obj->strtab + symnum, vernum);
4237 } else if (obj->vertab[vernum].hash != 0) {
4238 return &obj->vertab[vernum];
4245 _rtld_get_stack_prot(void)
4248 return (stack_prot);
4252 map_stacks_exec(RtldLockState *lockstate)
4254 void (*thr_map_stacks_exec)(void);
4256 if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
4258 thr_map_stacks_exec = (void (*)(void))(uintptr_t)
4259 get_program_var_addr("__pthread_map_stacks_exec", lockstate);
4260 if (thr_map_stacks_exec != NULL) {
4261 stack_prot |= PROT_EXEC;
4262 thr_map_stacks_exec();
4267 symlook_init(SymLook *dst, const char *name)
4270 bzero(dst, sizeof(*dst));
4272 dst->hash = elf_hash(name);
4276 symlook_init_from_req(SymLook *dst, const SymLook *src)
4279 dst->name = src->name;
4280 dst->hash = src->hash;
4281 dst->ventry = src->ventry;
4282 dst->flags = src->flags;
4283 dst->defobj_out = NULL;
4284 dst->sym_out = NULL;
4285 dst->lockstate = src->lockstate;
4289 * Overrides for libc_pic-provided functions.
4293 __getosreldate(void)
4303 oid[1] = KERN_OSRELDATE;
4305 len = sizeof(osrel);
4306 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
4307 if (error == 0 && osrel > 0 && len == sizeof(osrel))
4313 * No unresolved symbols for rtld.
4316 __pthread_cxa_finalize(struct dl_phdr_info *a)