2 * Copyright 1996, 1997, 1998, 1999, 2000 John D. Polstra.
3 * Copyright 2003 Alexander Kabaev <kan@FreeBSD.ORG>.
4 * Copyright 2009-2012 Konstantin Belousov <kib@FreeBSD.ORG>.
5 * Copyright 2012 John Marino <draco@marino.st>.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 * Dynamic linker for ELF.
34 * John Polstra <jdp@polstra.com>.
38 #error "GCC is needed to compile this file"
41 #include <sys/param.h>
42 #include <sys/mount.h>
45 #include <sys/sysctl.h>
47 #include <sys/utsname.h>
48 #include <sys/ktrace.h>
64 #include "rtld_printf.h"
68 #define PATH_RTLD "/libexec/ld-elf.so.1"
70 #define PATH_RTLD "/libexec/ld-elf32.so.1"
74 typedef void (*func_ptr_type)();
75 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg);
78 * Function declarations.
80 static const char *basename(const char *);
81 static void die(void) __dead2;
82 static void digest_dynamic1(Obj_Entry *, int, const Elf_Dyn **,
84 static void digest_dynamic2(Obj_Entry *, const Elf_Dyn *, const Elf_Dyn *);
85 static void digest_dynamic(Obj_Entry *, int);
86 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
87 static Obj_Entry *dlcheck(void *);
88 static Obj_Entry *dlopen_object(const char *name, int fd, Obj_Entry *refobj,
89 int lo_flags, int mode, RtldLockState *lockstate);
90 static Obj_Entry *do_load_object(int, const char *, char *, struct stat *, int);
91 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
92 static bool donelist_check(DoneList *, const Obj_Entry *);
93 static void errmsg_restore(char *);
94 static char *errmsg_save(void);
95 static void *fill_search_info(const char *, size_t, void *);
96 static char *find_library(const char *, const Obj_Entry *);
97 static const char *gethints(void);
98 static void init_dag(Obj_Entry *);
99 static void init_rtld(caddr_t, Elf_Auxinfo **);
100 static void initlist_add_neededs(Needed_Entry *, Objlist *);
101 static void initlist_add_objects(Obj_Entry *, Obj_Entry **, Objlist *);
102 static void linkmap_add(Obj_Entry *);
103 static void linkmap_delete(Obj_Entry *);
104 static void load_filtees(Obj_Entry *, int flags, RtldLockState *);
105 static void unload_filtees(Obj_Entry *);
106 static int load_needed_objects(Obj_Entry *, int);
107 static int load_preload_objects(void);
108 static Obj_Entry *load_object(const char *, int fd, const Obj_Entry *, int);
109 static void map_stacks_exec(RtldLockState *);
110 static Obj_Entry *obj_from_addr(const void *);
111 static void objlist_call_fini(Objlist *, Obj_Entry *, RtldLockState *);
112 static void objlist_call_init(Objlist *, RtldLockState *);
113 static void objlist_clear(Objlist *);
114 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
115 static void objlist_init(Objlist *);
116 static void objlist_push_head(Objlist *, Obj_Entry *);
117 static void objlist_push_tail(Objlist *, Obj_Entry *);
118 static void objlist_remove(Objlist *, Obj_Entry *);
119 static void *path_enumerate(const char *, path_enum_proc, void *);
120 static int relocate_object_dag(Obj_Entry *root, bool bind_now,
121 Obj_Entry *rtldobj, int flags, RtldLockState *lockstate);
122 static int relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
123 int flags, RtldLockState *lockstate);
124 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, int,
126 static int resolve_objects_ifunc(Obj_Entry *first, bool bind_now,
127 int flags, RtldLockState *lockstate);
128 static int rtld_dirname(const char *, char *);
129 static int rtld_dirname_abs(const char *, char *);
130 static void *rtld_dlopen(const char *name, int fd, int mode);
131 static void rtld_exit(void);
132 static char *search_library_path(const char *, const char *);
133 static const void **get_program_var_addr(const char *, RtldLockState *);
134 static void set_program_var(const char *, const void *);
135 static int symlook_default(SymLook *, const Obj_Entry *refobj);
136 static int symlook_global(SymLook *, DoneList *);
137 static void symlook_init_from_req(SymLook *, const SymLook *);
138 static int symlook_list(SymLook *, const Objlist *, DoneList *);
139 static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *);
140 static int symlook_obj1_sysv(SymLook *, const Obj_Entry *);
141 static int symlook_obj1_gnu(SymLook *, const Obj_Entry *);
142 static void trace_loaded_objects(Obj_Entry *);
143 static void unlink_object(Obj_Entry *);
144 static void unload_object(Obj_Entry *);
145 static void unref_dag(Obj_Entry *);
146 static void ref_dag(Obj_Entry *);
147 static int origin_subst_one(char **, const char *, const char *,
148 const char *, char *);
149 static char *origin_subst(const char *, const char *);
150 static void preinit_main(void);
151 static int rtld_verify_versions(const Objlist *);
152 static int rtld_verify_object_versions(Obj_Entry *);
153 static void object_add_name(Obj_Entry *, const char *);
154 static int object_match_name(const Obj_Entry *, const char *);
155 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
156 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
157 struct dl_phdr_info *phdr_info);
158 static uint32_t gnu_hash(const char *);
159 static bool matched_symbol(SymLook *, const Obj_Entry *, Sym_Match_Result *,
160 const unsigned long);
162 void r_debug_state(struct r_debug *, struct link_map *) __noinline;
167 static char *error_message; /* Message for dlerror(), or NULL */
168 struct r_debug r_debug; /* for GDB; */
169 static bool libmap_disable; /* Disable libmap */
170 static bool ld_loadfltr; /* Immediate filters processing */
171 static char *libmap_override; /* Maps to use in addition to libmap.conf */
172 static bool trust; /* False for setuid and setgid programs */
173 static bool dangerous_ld_env; /* True if environment variables have been
174 used to affect the libraries loaded */
175 static char *ld_bind_now; /* Environment variable for immediate binding */
176 static char *ld_debug; /* Environment variable for debugging */
177 static char *ld_library_path; /* Environment variable for search path */
178 static char *ld_preload; /* Environment variable for libraries to
180 static char *ld_elf_hints_path; /* Environment variable for alternative hints path */
181 static char *ld_tracing; /* Called from ldd to print libs */
182 static char *ld_utrace; /* Use utrace() to log events. */
183 static Obj_Entry *obj_list; /* Head of linked list of shared objects */
184 static Obj_Entry **obj_tail; /* Link field of last object in list */
185 static Obj_Entry *obj_main; /* The main program shared object */
186 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
187 static unsigned int obj_count; /* Number of objects in obj_list */
188 static unsigned int obj_loads; /* Number of objects in obj_list */
190 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
191 STAILQ_HEAD_INITIALIZER(list_global);
192 static Objlist list_main = /* Objects loaded at program startup */
193 STAILQ_HEAD_INITIALIZER(list_main);
194 static Objlist list_fini = /* Objects needing fini() calls */
195 STAILQ_HEAD_INITIALIZER(list_fini);
197 Elf_Sym sym_zero; /* For resolving undefined weak refs. */
199 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
201 extern Elf_Dyn _DYNAMIC;
202 #pragma weak _DYNAMIC
203 #ifndef RTLD_IS_DYNAMIC
204 #define RTLD_IS_DYNAMIC() (&_DYNAMIC != NULL)
207 int osreldate, pagesize;
209 long __stack_chk_guard[8] = {0, 0, 0, 0, 0, 0, 0, 0};
211 static int stack_prot = PROT_READ | PROT_WRITE | RTLD_DEFAULT_STACK_EXEC;
212 static int max_stack_flags;
215 * Global declarations normally provided by crt1. The dynamic linker is
216 * not built with crt1, so we have to provide them ourselves.
222 * Used to pass argc, argv to init functions.
228 * Globals to control TLS allocation.
230 size_t tls_last_offset; /* Static TLS offset of last module */
231 size_t tls_last_size; /* Static TLS size of last module */
232 size_t tls_static_space; /* Static TLS space allocated */
233 int tls_dtv_generation = 1; /* Used to detect when dtv size changes */
234 int tls_max_index = 1; /* Largest module index allocated */
237 * Fill in a DoneList with an allocation large enough to hold all of
238 * the currently-loaded objects. Keep this as a macro since it calls
239 * alloca and we want that to occur within the scope of the caller.
241 #define donelist_init(dlp) \
242 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
243 assert((dlp)->objs != NULL), \
244 (dlp)->num_alloc = obj_count, \
247 #define UTRACE_DLOPEN_START 1
248 #define UTRACE_DLOPEN_STOP 2
249 #define UTRACE_DLCLOSE_START 3
250 #define UTRACE_DLCLOSE_STOP 4
251 #define UTRACE_LOAD_OBJECT 5
252 #define UTRACE_UNLOAD_OBJECT 6
253 #define UTRACE_ADD_RUNDEP 7
254 #define UTRACE_PRELOAD_FINISHED 8
255 #define UTRACE_INIT_CALL 9
256 #define UTRACE_FINI_CALL 10
259 char sig[4]; /* 'RTLD' */
262 void *mapbase; /* Used for 'parent' and 'init/fini' */
264 int refcnt; /* Used for 'mode' */
265 char name[MAXPATHLEN];
268 #define LD_UTRACE(e, h, mb, ms, r, n) do { \
269 if (ld_utrace != NULL) \
270 ld_utrace_log(e, h, mb, ms, r, n); \
274 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
275 int refcnt, const char *name)
277 struct utrace_rtld ut;
285 ut.mapbase = mapbase;
286 ut.mapsize = mapsize;
288 bzero(ut.name, sizeof(ut.name));
290 strlcpy(ut.name, name, sizeof(ut.name));
291 utrace(&ut, sizeof(ut));
295 * Main entry point for dynamic linking. The first argument is the
296 * stack pointer. The stack is expected to be laid out as described
297 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
298 * Specifically, the stack pointer points to a word containing
299 * ARGC. Following that in the stack is a null-terminated sequence
300 * of pointers to argument strings. Then comes a null-terminated
301 * sequence of pointers to environment strings. Finally, there is a
302 * sequence of "auxiliary vector" entries.
304 * The second argument points to a place to store the dynamic linker's
305 * exit procedure pointer and the third to a place to store the main
308 * The return value is the main program's entry point.
311 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
313 Elf_Auxinfo *aux_info[AT_COUNT];
321 Objlist_Entry *entry;
323 Obj_Entry **preload_tail;
325 RtldLockState lockstate;
330 * On entry, the dynamic linker itself has not been relocated yet.
331 * Be very careful not to reference any global data until after
332 * init_rtld has returned. It is OK to reference file-scope statics
333 * and string constants, and to call static and global functions.
336 /* Find the auxiliary vector on the stack. */
339 sp += argc + 1; /* Skip over arguments and NULL terminator */
341 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
343 aux = (Elf_Auxinfo *) sp;
345 /* Digest the auxiliary vector. */
346 for (i = 0; i < AT_COUNT; i++)
348 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
349 if (auxp->a_type < AT_COUNT)
350 aux_info[auxp->a_type] = auxp;
353 /* Initialize and relocate ourselves. */
354 assert(aux_info[AT_BASE] != NULL);
355 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
357 __progname = obj_rtld.path;
358 argv0 = argv[0] != NULL ? argv[0] : "(null)";
363 if (aux_info[AT_CANARY] != NULL &&
364 aux_info[AT_CANARY]->a_un.a_ptr != NULL) {
365 i = aux_info[AT_CANARYLEN]->a_un.a_val;
366 if (i > sizeof(__stack_chk_guard))
367 i = sizeof(__stack_chk_guard);
368 memcpy(__stack_chk_guard, aux_info[AT_CANARY]->a_un.a_ptr, i);
373 len = sizeof(__stack_chk_guard);
374 if (sysctl(mib, 2, __stack_chk_guard, &len, NULL, 0) == -1 ||
375 len != sizeof(__stack_chk_guard)) {
376 /* If sysctl was unsuccessful, use the "terminator canary". */
377 ((unsigned char *)(void *)__stack_chk_guard)[0] = 0;
378 ((unsigned char *)(void *)__stack_chk_guard)[1] = 0;
379 ((unsigned char *)(void *)__stack_chk_guard)[2] = '\n';
380 ((unsigned char *)(void *)__stack_chk_guard)[3] = 255;
384 trust = !issetugid();
386 ld_bind_now = getenv(LD_ "BIND_NOW");
388 * If the process is tainted, then we un-set the dangerous environment
389 * variables. The process will be marked as tainted until setuid(2)
390 * is called. If any child process calls setuid(2) we do not want any
391 * future processes to honor the potentially un-safe variables.
394 if (unsetenv(LD_ "PRELOAD") || unsetenv(LD_ "LIBMAP") ||
395 unsetenv(LD_ "LIBRARY_PATH") || unsetenv(LD_ "LIBMAP_DISABLE") ||
396 unsetenv(LD_ "DEBUG") || unsetenv(LD_ "ELF_HINTS_PATH") ||
397 unsetenv(LD_ "LOADFLTR")) {
398 _rtld_error("environment corrupt; aborting");
402 ld_debug = getenv(LD_ "DEBUG");
403 libmap_disable = getenv(LD_ "LIBMAP_DISABLE") != NULL;
404 libmap_override = getenv(LD_ "LIBMAP");
405 ld_library_path = getenv(LD_ "LIBRARY_PATH");
406 ld_preload = getenv(LD_ "PRELOAD");
407 ld_elf_hints_path = getenv(LD_ "ELF_HINTS_PATH");
408 ld_loadfltr = getenv(LD_ "LOADFLTR") != NULL;
409 dangerous_ld_env = libmap_disable || (libmap_override != NULL) ||
410 (ld_library_path != NULL) || (ld_preload != NULL) ||
411 (ld_elf_hints_path != NULL) || ld_loadfltr;
412 ld_tracing = getenv(LD_ "TRACE_LOADED_OBJECTS");
413 ld_utrace = getenv(LD_ "UTRACE");
415 if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0)
416 ld_elf_hints_path = _PATH_ELF_HINTS;
418 if (ld_debug != NULL && *ld_debug != '\0')
420 dbg("%s is initialized, base address = %p", __progname,
421 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
422 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
423 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
425 dbg("initializing thread locks");
429 * Load the main program, or process its program header if it is
432 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
433 int fd = aux_info[AT_EXECFD]->a_un.a_val;
434 dbg("loading main program");
435 obj_main = map_object(fd, argv0, NULL);
437 if (obj_main == NULL)
439 max_stack_flags = obj->stack_flags;
440 } else { /* Main program already loaded. */
441 const Elf_Phdr *phdr;
445 dbg("processing main program's program header");
446 assert(aux_info[AT_PHDR] != NULL);
447 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
448 assert(aux_info[AT_PHNUM] != NULL);
449 phnum = aux_info[AT_PHNUM]->a_un.a_val;
450 assert(aux_info[AT_PHENT] != NULL);
451 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
452 assert(aux_info[AT_ENTRY] != NULL);
453 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
454 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
458 if (aux_info[AT_EXECPATH] != 0) {
460 char buf[MAXPATHLEN];
462 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
463 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
464 if (kexecpath[0] == '/')
465 obj_main->path = kexecpath;
466 else if (getcwd(buf, sizeof(buf)) == NULL ||
467 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
468 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
469 obj_main->path = xstrdup(argv0);
471 obj_main->path = xstrdup(buf);
473 dbg("No AT_EXECPATH");
474 obj_main->path = xstrdup(argv0);
476 dbg("obj_main path %s", obj_main->path);
477 obj_main->mainprog = true;
479 if (aux_info[AT_STACKPROT] != NULL &&
480 aux_info[AT_STACKPROT]->a_un.a_val != 0)
481 stack_prot = aux_info[AT_STACKPROT]->a_un.a_val;
484 * Get the actual dynamic linker pathname from the executable if
485 * possible. (It should always be possible.) That ensures that
486 * gdb will find the right dynamic linker even if a non-standard
489 if (obj_main->interp != NULL &&
490 strcmp(obj_main->interp, obj_rtld.path) != 0) {
492 obj_rtld.path = xstrdup(obj_main->interp);
493 __progname = obj_rtld.path;
496 digest_dynamic(obj_main, 0);
497 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d",
498 obj_main->path, obj_main->valid_hash_sysv, obj_main->valid_hash_gnu,
499 obj_main->dynsymcount);
501 linkmap_add(obj_main);
502 linkmap_add(&obj_rtld);
504 /* Link the main program into the list of objects. */
505 *obj_tail = obj_main;
506 obj_tail = &obj_main->next;
510 /* Initialize a fake symbol for resolving undefined weak references. */
511 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
512 sym_zero.st_shndx = SHN_UNDEF;
513 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
516 libmap_disable = (bool)lm_init(libmap_override);
518 dbg("loading LD_PRELOAD libraries");
519 if (load_preload_objects() == -1)
521 preload_tail = obj_tail;
523 dbg("loading needed objects");
524 if (load_needed_objects(obj_main, 0) == -1)
527 /* Make a list of all objects loaded at startup. */
528 for (obj = obj_list; obj != NULL; obj = obj->next) {
529 objlist_push_tail(&list_main, obj);
533 dbg("checking for required versions");
534 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
537 if (ld_tracing) { /* We're done */
538 trace_loaded_objects(obj_main);
542 if (getenv(LD_ "DUMP_REL_PRE") != NULL) {
543 dump_relocations(obj_main);
548 * Processing tls relocations requires having the tls offsets
549 * initialized. Prepare offsets before starting initial
550 * relocation processing.
552 dbg("initializing initial thread local storage offsets");
553 STAILQ_FOREACH(entry, &list_main, link) {
555 * Allocate all the initial objects out of the static TLS
556 * block even if they didn't ask for it.
558 allocate_tls_offset(entry->obj);
561 if (relocate_objects(obj_main,
562 ld_bind_now != NULL && *ld_bind_now != '\0',
563 &obj_rtld, SYMLOOK_EARLY, NULL) == -1)
566 dbg("doing copy relocations");
567 if (do_copy_relocations(obj_main) == -1)
570 if (getenv(LD_ "DUMP_REL_POST") != NULL) {
571 dump_relocations(obj_main);
576 * Setup TLS for main thread. This must be done after the
577 * relocations are processed, since tls initialization section
578 * might be the subject for relocations.
580 dbg("initializing initial thread local storage");
581 allocate_initial_tls(obj_list);
583 dbg("initializing key program variables");
584 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
585 set_program_var("environ", env);
586 set_program_var("__elf_aux_vector", aux);
588 /* Make a list of init functions to call. */
589 objlist_init(&initlist);
590 initlist_add_objects(obj_list, preload_tail, &initlist);
592 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
594 map_stacks_exec(NULL);
596 dbg("resolving ifuncs");
597 if (resolve_objects_ifunc(obj_main,
598 ld_bind_now != NULL && *ld_bind_now != '\0', SYMLOOK_EARLY,
602 if (!obj_main->crt_no_init) {
604 * Make sure we don't call the main program's init and fini
605 * functions for binaries linked with old crt1 which calls
608 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
609 obj_main->preinit_array = obj_main->init_array =
610 obj_main->fini_array = (Elf_Addr)NULL;
613 wlock_acquire(rtld_bind_lock, &lockstate);
614 if (obj_main->crt_no_init)
616 objlist_call_init(&initlist, &lockstate);
617 objlist_clear(&initlist);
618 dbg("loading filtees");
619 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
620 if (ld_loadfltr || obj->z_loadfltr)
621 load_filtees(obj, 0, &lockstate);
623 lock_release(rtld_bind_lock, &lockstate);
625 dbg("transferring control to program entry point = %p", obj_main->entry);
627 /* Return the exit procedure and the program entry point. */
628 *exit_proc = rtld_exit;
630 return (func_ptr_type) obj_main->entry;
634 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def)
639 ptr = (void *)make_function_pointer(def, obj);
640 target = ((Elf_Addr (*)(void))ptr)();
641 return ((void *)target);
645 _rtld_bind(Obj_Entry *obj, Elf_Size reloff)
649 const Obj_Entry *defobj;
652 RtldLockState lockstate;
654 rlock_acquire(rtld_bind_lock, &lockstate);
655 if (sigsetjmp(lockstate.env, 0) != 0)
656 lock_upgrade(rtld_bind_lock, &lockstate);
658 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
660 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
662 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
663 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL,
667 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
668 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
670 target = (Elf_Addr)(defobj->relocbase + def->st_value);
672 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
673 defobj->strtab + def->st_name, basename(obj->path),
674 (void *)target, basename(defobj->path));
677 * Write the new contents for the jmpslot. Note that depending on
678 * architecture, the value which we need to return back to the
679 * lazy binding trampoline may or may not be the target
680 * address. The value returned from reloc_jmpslot() is the value
681 * that the trampoline needs.
683 target = reloc_jmpslot(where, target, defobj, obj, rel);
684 lock_release(rtld_bind_lock, &lockstate);
689 * Error reporting function. Use it like printf. If formats the message
690 * into a buffer, and sets things up so that the next call to dlerror()
691 * will return the message.
694 _rtld_error(const char *fmt, ...)
696 static char buf[512];
700 rtld_vsnprintf(buf, sizeof buf, fmt, ap);
706 * Return a dynamically-allocated copy of the current error message, if any.
711 return error_message == NULL ? NULL : xstrdup(error_message);
715 * Restore the current error message from a copy which was previously saved
716 * by errmsg_save(). The copy is freed.
719 errmsg_restore(char *saved_msg)
721 if (saved_msg == NULL)
722 error_message = NULL;
724 _rtld_error("%s", saved_msg);
730 basename(const char *name)
732 const char *p = strrchr(name, '/');
733 return p != NULL ? p + 1 : name;
736 static struct utsname uts;
739 origin_subst_one(char **res, const char *real, const char *kw, const char *subst,
749 subst_len = kw_len = 0;
753 if (subst_len == 0) {
754 subst_len = strlen(subst);
758 *res = xmalloc(PATH_MAX);
761 if ((res1 - *res) + subst_len + (p1 - p) >= PATH_MAX) {
762 _rtld_error("Substitution of %s in %s cannot be performed",
764 if (may_free != NULL)
769 memcpy(res1, p, p1 - p);
771 memcpy(res1, subst, subst_len);
776 if (may_free != NULL)
779 *res = xstrdup(real);
783 if (may_free != NULL)
785 if (strlcat(res1, p, PATH_MAX - (res1 - *res)) >= PATH_MAX) {
795 origin_subst(const char *real, const char *origin_path)
797 char *res1, *res2, *res3, *res4;
799 if (uts.sysname[0] == '\0') {
800 if (uname(&uts) != 0) {
801 _rtld_error("utsname failed: %d", errno);
805 if (!origin_subst_one(&res1, real, "$ORIGIN", origin_path, NULL) ||
806 !origin_subst_one(&res2, res1, "$OSNAME", uts.sysname, res1) ||
807 !origin_subst_one(&res3, res2, "$OSREL", uts.release, res2) ||
808 !origin_subst_one(&res4, res3, "$PLATFORM", uts.machine, res3))
816 const char *msg = dlerror();
820 rtld_fdputstr(STDERR_FILENO, msg);
821 rtld_fdputchar(STDERR_FILENO, '\n');
826 * Process a shared object's DYNAMIC section, and save the important
827 * information in its Obj_Entry structure.
830 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
831 const Elf_Dyn **dyn_soname)
834 Needed_Entry **needed_tail = &obj->needed;
835 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
836 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
837 const Elf_Hashelt *hashtab;
838 const Elf32_Word *hashval;
839 Elf32_Word bkt, nmaskwords;
842 int plttype = DT_REL;
847 obj->bind_now = false;
848 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
849 switch (dynp->d_tag) {
852 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
856 obj->relsize = dynp->d_un.d_val;
860 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
864 obj->pltrel = (const Elf_Rel *)
865 (obj->relocbase + dynp->d_un.d_ptr);
869 obj->pltrelsize = dynp->d_un.d_val;
873 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
877 obj->relasize = dynp->d_un.d_val;
881 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
885 plttype = dynp->d_un.d_val;
886 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
890 obj->symtab = (const Elf_Sym *)
891 (obj->relocbase + dynp->d_un.d_ptr);
895 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
899 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
903 obj->strsize = dynp->d_un.d_val;
907 obj->verneed = (const Elf_Verneed *) (obj->relocbase +
912 obj->verneednum = dynp->d_un.d_val;
916 obj->verdef = (const Elf_Verdef *) (obj->relocbase +
921 obj->verdefnum = dynp->d_un.d_val;
925 obj->versyms = (const Elf_Versym *)(obj->relocbase +
931 hashtab = (const Elf_Hashelt *)(obj->relocbase +
933 obj->nbuckets = hashtab[0];
934 obj->nchains = hashtab[1];
935 obj->buckets = hashtab + 2;
936 obj->chains = obj->buckets + obj->nbuckets;
937 obj->valid_hash_sysv = obj->nbuckets > 0 && obj->nchains > 0 &&
938 obj->buckets != NULL;
944 hashtab = (const Elf_Hashelt *)(obj->relocbase +
946 obj->nbuckets_gnu = hashtab[0];
947 obj->symndx_gnu = hashtab[1];
948 nmaskwords = hashtab[2];
949 bloom_size32 = (__ELF_WORD_SIZE / 32) * nmaskwords;
950 /* Number of bitmask words is required to be power of 2 */
951 nmw_power2 = ((nmaskwords & (nmaskwords - 1)) == 0);
952 obj->maskwords_bm_gnu = nmaskwords - 1;
953 obj->shift2_gnu = hashtab[3];
954 obj->bloom_gnu = (Elf_Addr *) (hashtab + 4);
955 obj->buckets_gnu = hashtab + 4 + bloom_size32;
956 obj->chain_zero_gnu = obj->buckets_gnu + obj->nbuckets_gnu -
958 obj->valid_hash_gnu = nmw_power2 && obj->nbuckets_gnu > 0 &&
959 obj->buckets_gnu != NULL;
965 Needed_Entry *nep = NEW(Needed_Entry);
966 nep->name = dynp->d_un.d_val;
971 needed_tail = &nep->next;
977 Needed_Entry *nep = NEW(Needed_Entry);
978 nep->name = dynp->d_un.d_val;
982 *needed_filtees_tail = nep;
983 needed_filtees_tail = &nep->next;
989 Needed_Entry *nep = NEW(Needed_Entry);
990 nep->name = dynp->d_un.d_val;
994 *needed_aux_filtees_tail = nep;
995 needed_aux_filtees_tail = &nep->next;
1000 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
1004 obj->textrel = true;
1008 obj->symbolic = true;
1012 case DT_RUNPATH: /* XXX: process separately */
1014 * We have to wait until later to process this, because we
1015 * might not have gotten the address of the string table yet.
1025 obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1028 case DT_PREINIT_ARRAY:
1029 obj->preinit_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1032 case DT_PREINIT_ARRAYSZ:
1033 obj->preinit_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1037 obj->init_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1040 case DT_INIT_ARRAYSZ:
1041 obj->init_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1045 obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1049 obj->fini_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1052 case DT_FINI_ARRAYSZ:
1053 obj->fini_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1057 * Don't process DT_DEBUG on MIPS as the dynamic section
1058 * is mapped read-only. DT_MIPS_RLD_MAP is used instead.
1063 /* XXX - not implemented yet */
1065 dbg("Filling in DT_DEBUG entry");
1066 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
1071 if ((dynp->d_un.d_val & DF_ORIGIN) && trust)
1072 obj->z_origin = true;
1073 if (dynp->d_un.d_val & DF_SYMBOLIC)
1074 obj->symbolic = true;
1075 if (dynp->d_un.d_val & DF_TEXTREL)
1076 obj->textrel = true;
1077 if (dynp->d_un.d_val & DF_BIND_NOW)
1078 obj->bind_now = true;
1079 /*if (dynp->d_un.d_val & DF_STATIC_TLS)
1083 case DT_MIPS_LOCAL_GOTNO:
1084 obj->local_gotno = dynp->d_un.d_val;
1087 case DT_MIPS_SYMTABNO:
1088 obj->symtabno = dynp->d_un.d_val;
1091 case DT_MIPS_GOTSYM:
1092 obj->gotsym = dynp->d_un.d_val;
1095 case DT_MIPS_RLD_MAP:
1098 dbg("Filling in DT_DEBUG entry");
1099 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
1105 if (dynp->d_un.d_val & DF_1_NOOPEN)
1106 obj->z_noopen = true;
1107 if ((dynp->d_un.d_val & DF_1_ORIGIN) && trust)
1108 obj->z_origin = true;
1109 /*if (dynp->d_un.d_val & DF_1_GLOBAL)
1111 if (dynp->d_un.d_val & DF_1_BIND_NOW)
1112 obj->bind_now = true;
1113 if (dynp->d_un.d_val & DF_1_NODELETE)
1114 obj->z_nodelete = true;
1115 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1116 obj->z_loadfltr = true;
1121 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1128 obj->traced = false;
1130 if (plttype == DT_RELA) {
1131 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1133 obj->pltrelasize = obj->pltrelsize;
1134 obj->pltrelsize = 0;
1137 /* Determine size of dynsym table (equal to nchains of sysv hash) */
1138 if (obj->valid_hash_sysv)
1139 obj->dynsymcount = obj->nchains;
1140 else if (obj->valid_hash_gnu) {
1141 obj->dynsymcount = 0;
1142 for (bkt = 0; bkt < obj->nbuckets_gnu; bkt++) {
1143 if (obj->buckets_gnu[bkt] == 0)
1145 hashval = &obj->chain_zero_gnu[obj->buckets_gnu[bkt]];
1148 while ((*hashval++ & 1u) == 0);
1150 obj->dynsymcount += obj->symndx_gnu;
1155 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1156 const Elf_Dyn *dyn_soname)
1159 if (obj->z_origin && obj->origin_path == NULL) {
1160 obj->origin_path = xmalloc(PATH_MAX);
1161 if (rtld_dirname_abs(obj->path, obj->origin_path) == -1)
1165 if (dyn_rpath != NULL) {
1166 obj->rpath = (char *)obj->strtab + dyn_rpath->d_un.d_val;
1168 obj->rpath = origin_subst(obj->rpath, obj->origin_path);
1171 if (dyn_soname != NULL)
1172 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1176 digest_dynamic(Obj_Entry *obj, int early)
1178 const Elf_Dyn *dyn_rpath;
1179 const Elf_Dyn *dyn_soname;
1181 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname);
1182 digest_dynamic2(obj, dyn_rpath, dyn_soname);
1186 * Process a shared object's program header. This is used only for the
1187 * main program, when the kernel has already loaded the main program
1188 * into memory before calling the dynamic linker. It creates and
1189 * returns an Obj_Entry structure.
1192 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1195 const Elf_Phdr *phlimit = phdr + phnum;
1197 Elf_Addr note_start, note_end;
1201 for (ph = phdr; ph < phlimit; ph++) {
1202 if (ph->p_type != PT_PHDR)
1206 obj->phsize = ph->p_memsz;
1207 obj->relocbase = (caddr_t)phdr - ph->p_vaddr;
1211 obj->stack_flags = PF_X | PF_R | PF_W;
1213 for (ph = phdr; ph < phlimit; ph++) {
1214 switch (ph->p_type) {
1217 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1221 if (nsegs == 0) { /* First load segment */
1222 obj->vaddrbase = trunc_page(ph->p_vaddr);
1223 obj->mapbase = obj->vaddrbase + obj->relocbase;
1224 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
1226 } else { /* Last load segment */
1227 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1234 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1239 obj->tlssize = ph->p_memsz;
1240 obj->tlsalign = ph->p_align;
1241 obj->tlsinitsize = ph->p_filesz;
1242 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1246 obj->stack_flags = ph->p_flags;
1250 obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1251 obj->relro_size = round_page(ph->p_memsz);
1255 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
1256 note_end = note_start + ph->p_filesz;
1257 digest_notes(obj, note_start, note_end);
1262 _rtld_error("%s: too few PT_LOAD segments", path);
1271 digest_notes(Obj_Entry *obj, Elf_Addr note_start, Elf_Addr note_end)
1273 const Elf_Note *note;
1274 const char *note_name;
1277 for (note = (const Elf_Note *)note_start; (Elf_Addr)note < note_end;
1278 note = (const Elf_Note *)((const char *)(note + 1) +
1279 roundup2(note->n_namesz, sizeof(Elf32_Addr)) +
1280 roundup2(note->n_descsz, sizeof(Elf32_Addr)))) {
1281 if (note->n_namesz != sizeof(NOTE_FREEBSD_VENDOR) ||
1282 note->n_descsz != sizeof(int32_t))
1284 if (note->n_type != ABI_NOTETYPE &&
1285 note->n_type != CRT_NOINIT_NOTETYPE)
1287 note_name = (const char *)(note + 1);
1288 if (strncmp(NOTE_FREEBSD_VENDOR, note_name,
1289 sizeof(NOTE_FREEBSD_VENDOR)) != 0)
1291 switch (note->n_type) {
1293 /* FreeBSD osrel note */
1294 p = (uintptr_t)(note + 1);
1295 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1296 obj->osrel = *(const int32_t *)(p);
1297 dbg("note osrel %d", obj->osrel);
1299 case CRT_NOINIT_NOTETYPE:
1300 /* FreeBSD 'crt does not call init' note */
1301 obj->crt_no_init = true;
1302 dbg("note crt_no_init");
1309 dlcheck(void *handle)
1313 for (obj = obj_list; obj != NULL; obj = obj->next)
1314 if (obj == (Obj_Entry *) handle)
1317 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1318 _rtld_error("Invalid shared object handle %p", handle);
1325 * If the given object is already in the donelist, return true. Otherwise
1326 * add the object to the list and return false.
1329 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1333 for (i = 0; i < dlp->num_used; i++)
1334 if (dlp->objs[i] == obj)
1337 * Our donelist allocation should always be sufficient. But if
1338 * our threads locking isn't working properly, more shared objects
1339 * could have been loaded since we allocated the list. That should
1340 * never happen, but we'll handle it properly just in case it does.
1342 if (dlp->num_used < dlp->num_alloc)
1343 dlp->objs[dlp->num_used++] = obj;
1348 * Hash function for symbol table lookup. Don't even think about changing
1349 * this. It is specified by the System V ABI.
1352 elf_hash(const char *name)
1354 const unsigned char *p = (const unsigned char *) name;
1355 unsigned long h = 0;
1358 while (*p != '\0') {
1359 h = (h << 4) + *p++;
1360 if ((g = h & 0xf0000000) != 0)
1368 * The GNU hash function is the Daniel J. Bernstein hash clipped to 32 bits
1369 * unsigned in case it's implemented with a wider type.
1372 gnu_hash(const char *s)
1378 for (c = *s; c != '\0'; c = *++s)
1380 return (h & 0xffffffff);
1384 * Find the library with the given name, and return its full pathname.
1385 * The returned string is dynamically allocated. Generates an error
1386 * message and returns NULL if the library cannot be found.
1388 * If the second argument is non-NULL, then it refers to an already-
1389 * loaded shared object, whose library search path will be searched.
1391 * The search order is:
1393 * rpath in the referencing file
1398 find_library(const char *xname, const Obj_Entry *refobj)
1403 if (strchr(xname, '/') != NULL) { /* Hard coded pathname */
1404 if (xname[0] != '/' && !trust) {
1405 _rtld_error("Absolute pathname required for shared object \"%s\"",
1409 if (refobj != NULL && refobj->z_origin)
1410 return origin_subst(xname, refobj->origin_path);
1412 return xstrdup(xname);
1415 if (libmap_disable || (refobj == NULL) ||
1416 (name = lm_find(refobj->path, xname)) == NULL)
1417 name = (char *)xname;
1419 dbg(" Searching for \"%s\"", name);
1421 if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
1423 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
1424 (pathname = search_library_path(name, gethints())) != NULL ||
1425 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
1428 if(refobj != NULL && refobj->path != NULL) {
1429 _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
1430 name, basename(refobj->path));
1432 _rtld_error("Shared object \"%s\" not found", name);
1438 * Given a symbol number in a referencing object, find the corresponding
1439 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1440 * no definition was found. Returns a pointer to the Obj_Entry of the
1441 * defining object via the reference parameter DEFOBJ_OUT.
1444 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1445 const Obj_Entry **defobj_out, int flags, SymCache *cache,
1446 RtldLockState *lockstate)
1450 const Obj_Entry *defobj;
1456 * If we have already found this symbol, get the information from
1459 if (symnum >= refobj->dynsymcount)
1460 return NULL; /* Bad object */
1461 if (cache != NULL && cache[symnum].sym != NULL) {
1462 *defobj_out = cache[symnum].obj;
1463 return cache[symnum].sym;
1466 ref = refobj->symtab + symnum;
1467 name = refobj->strtab + ref->st_name;
1472 * We don't have to do a full scale lookup if the symbol is local.
1473 * We know it will bind to the instance in this load module; to
1474 * which we already have a pointer (ie ref). By not doing a lookup,
1475 * we not only improve performance, but it also avoids unresolvable
1476 * symbols when local symbols are not in the hash table. This has
1477 * been seen with the ia64 toolchain.
1479 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1480 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1481 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1484 symlook_init(&req, name);
1486 req.ventry = fetch_ventry(refobj, symnum);
1487 req.lockstate = lockstate;
1488 res = symlook_default(&req, refobj);
1491 defobj = req.defobj_out;
1499 * If we found no definition and the reference is weak, treat the
1500 * symbol as having the value zero.
1502 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1508 *defobj_out = defobj;
1509 /* Record the information in the cache to avoid subsequent lookups. */
1510 if (cache != NULL) {
1511 cache[symnum].sym = def;
1512 cache[symnum].obj = defobj;
1515 if (refobj != &obj_rtld)
1516 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1522 * Return the search path from the ldconfig hints file, reading it if
1523 * necessary. Returns NULL if there are problems with the hints file,
1524 * or if the search path there is empty.
1531 if (hints == NULL) {
1533 struct elfhints_hdr hdr;
1536 /* Keep from trying again in case the hints file is bad. */
1539 if ((fd = open(ld_elf_hints_path, O_RDONLY)) == -1)
1541 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1542 hdr.magic != ELFHINTS_MAGIC ||
1547 p = xmalloc(hdr.dirlistlen + 1);
1548 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1549 read(fd, p, hdr.dirlistlen + 1) != (ssize_t)hdr.dirlistlen + 1) {
1557 return hints[0] != '\0' ? hints : NULL;
1561 init_dag(Obj_Entry *root)
1563 const Needed_Entry *needed;
1564 const Objlist_Entry *elm;
1567 if (root->dag_inited)
1569 donelist_init(&donelist);
1571 /* Root object belongs to own DAG. */
1572 objlist_push_tail(&root->dldags, root);
1573 objlist_push_tail(&root->dagmembers, root);
1574 donelist_check(&donelist, root);
1577 * Add dependencies of root object to DAG in breadth order
1578 * by exploiting the fact that each new object get added
1579 * to the tail of the dagmembers list.
1581 STAILQ_FOREACH(elm, &root->dagmembers, link) {
1582 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
1583 if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
1585 objlist_push_tail(&needed->obj->dldags, root);
1586 objlist_push_tail(&root->dagmembers, needed->obj);
1589 root->dag_inited = true;
1593 * Initialize the dynamic linker. The argument is the address at which
1594 * the dynamic linker has been mapped into memory. The primary task of
1595 * this function is to relocate the dynamic linker.
1598 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
1600 Obj_Entry objtmp; /* Temporary rtld object */
1601 const Elf_Dyn *dyn_rpath;
1602 const Elf_Dyn *dyn_soname;
1605 * Conjure up an Obj_Entry structure for the dynamic linker.
1607 * The "path" member can't be initialized yet because string constants
1608 * cannot yet be accessed. Below we will set it correctly.
1610 memset(&objtmp, 0, sizeof(objtmp));
1613 objtmp.mapbase = mapbase;
1615 objtmp.relocbase = mapbase;
1617 if (RTLD_IS_DYNAMIC()) {
1618 objtmp.dynamic = rtld_dynamic(&objtmp);
1619 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname);
1620 assert(objtmp.needed == NULL);
1621 #if !defined(__mips__)
1622 /* MIPS has a bogus DT_TEXTREL. */
1623 assert(!objtmp.textrel);
1627 * Temporarily put the dynamic linker entry into the object list, so
1628 * that symbols can be found.
1631 relocate_objects(&objtmp, true, &objtmp, 0, NULL);
1634 /* Initialize the object list. */
1635 obj_tail = &obj_list;
1637 /* Now that non-local variables can be accesses, copy out obj_rtld. */
1638 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1640 if (aux_info[AT_PAGESZ] != NULL)
1641 pagesize = aux_info[AT_PAGESZ]->a_un.a_val;
1642 if (aux_info[AT_OSRELDATE] != NULL)
1643 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
1645 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname);
1647 /* Replace the path with a dynamically allocated copy. */
1648 obj_rtld.path = xstrdup(PATH_RTLD);
1650 r_debug.r_brk = r_debug_state;
1651 r_debug.r_state = RT_CONSISTENT;
1655 * Add the init functions from a needed object list (and its recursive
1656 * needed objects) to "list". This is not used directly; it is a helper
1657 * function for initlist_add_objects(). The write lock must be held
1658 * when this function is called.
1661 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1663 /* Recursively process the successor needed objects. */
1664 if (needed->next != NULL)
1665 initlist_add_neededs(needed->next, list);
1667 /* Process the current needed object. */
1668 if (needed->obj != NULL)
1669 initlist_add_objects(needed->obj, &needed->obj->next, list);
1673 * Scan all of the DAGs rooted in the range of objects from "obj" to
1674 * "tail" and add their init functions to "list". This recurses over
1675 * the DAGs and ensure the proper init ordering such that each object's
1676 * needed libraries are initialized before the object itself. At the
1677 * same time, this function adds the objects to the global finalization
1678 * list "list_fini" in the opposite order. The write lock must be
1679 * held when this function is called.
1682 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1685 if (obj->init_scanned || obj->init_done)
1687 obj->init_scanned = true;
1689 /* Recursively process the successor objects. */
1690 if (&obj->next != tail)
1691 initlist_add_objects(obj->next, tail, list);
1693 /* Recursively process the needed objects. */
1694 if (obj->needed != NULL)
1695 initlist_add_neededs(obj->needed, list);
1696 if (obj->needed_filtees != NULL)
1697 initlist_add_neededs(obj->needed_filtees, list);
1698 if (obj->needed_aux_filtees != NULL)
1699 initlist_add_neededs(obj->needed_aux_filtees, list);
1701 /* Add the object to the init list. */
1702 if (obj->preinit_array != (Elf_Addr)NULL || obj->init != (Elf_Addr)NULL ||
1703 obj->init_array != (Elf_Addr)NULL)
1704 objlist_push_tail(list, obj);
1706 /* Add the object to the global fini list in the reverse order. */
1707 if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL)
1708 && !obj->on_fini_list) {
1709 objlist_push_head(&list_fini, obj);
1710 obj->on_fini_list = true;
1715 #define FPTR_TARGET(f) ((Elf_Addr) (f))
1719 free_needed_filtees(Needed_Entry *n)
1721 Needed_Entry *needed, *needed1;
1723 for (needed = n; needed != NULL; needed = needed->next) {
1724 if (needed->obj != NULL) {
1725 dlclose(needed->obj);
1729 for (needed = n; needed != NULL; needed = needed1) {
1730 needed1 = needed->next;
1736 unload_filtees(Obj_Entry *obj)
1739 free_needed_filtees(obj->needed_filtees);
1740 obj->needed_filtees = NULL;
1741 free_needed_filtees(obj->needed_aux_filtees);
1742 obj->needed_aux_filtees = NULL;
1743 obj->filtees_loaded = false;
1747 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags,
1748 RtldLockState *lockstate)
1751 for (; needed != NULL; needed = needed->next) {
1752 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
1753 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
1754 RTLD_LOCAL, lockstate);
1759 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
1762 lock_restart_for_upgrade(lockstate);
1763 if (!obj->filtees_loaded) {
1764 load_filtee1(obj, obj->needed_filtees, flags, lockstate);
1765 load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate);
1766 obj->filtees_loaded = true;
1771 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
1775 for (; needed != NULL; needed = needed->next) {
1776 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
1777 flags & ~RTLD_LO_NOLOAD);
1778 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
1780 if (obj1 != NULL && obj1->z_nodelete && !obj1->ref_nodel) {
1781 dbg("obj %s nodelete", obj1->path);
1784 obj1->ref_nodel = true;
1791 * Given a shared object, traverse its list of needed objects, and load
1792 * each of them. Returns 0 on success. Generates an error message and
1793 * returns -1 on failure.
1796 load_needed_objects(Obj_Entry *first, int flags)
1800 for (obj = first; obj != NULL; obj = obj->next) {
1801 if (process_needed(obj, obj->needed, flags) == -1)
1808 load_preload_objects(void)
1810 char *p = ld_preload;
1811 static const char delim[] = " \t:;";
1816 p += strspn(p, delim);
1817 while (*p != '\0') {
1818 size_t len = strcspn(p, delim);
1823 if (load_object(p, -1, NULL, 0) == NULL)
1824 return -1; /* XXX - cleanup */
1827 p += strspn(p, delim);
1829 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
1834 printable_path(const char *path)
1837 return (path == NULL ? "<unknown>" : path);
1841 * Load a shared object into memory, if it is not already loaded. The
1842 * object may be specified by name or by user-supplied file descriptor
1843 * fd_u. In the later case, the fd_u descriptor is not closed, but its
1846 * Returns a pointer to the Obj_Entry for the object. Returns NULL
1850 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
1858 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
1859 if (object_match_name(obj, name))
1863 path = find_library(name, refobj);
1870 * If we didn't find a match by pathname, or the name is not
1871 * supplied, open the file and check again by device and inode.
1872 * This avoids false mismatches caused by multiple links or ".."
1875 * To avoid a race, we open the file and use fstat() rather than
1880 if ((fd = open(path, O_RDONLY)) == -1) {
1881 _rtld_error("Cannot open \"%s\"", path);
1888 _rtld_error("Cannot dup fd");
1893 if (fstat(fd, &sb) == -1) {
1894 _rtld_error("Cannot fstat \"%s\"", printable_path(path));
1899 for (obj = obj_list->next; obj != NULL; obj = obj->next)
1900 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
1902 if (obj != NULL && name != NULL) {
1903 object_add_name(obj, name);
1908 if (flags & RTLD_LO_NOLOAD) {
1914 /* First use of this object, so we must map it in */
1915 obj = do_load_object(fd, name, path, &sb, flags);
1924 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
1931 * but first, make sure that environment variables haven't been
1932 * used to circumvent the noexec flag on a filesystem.
1934 if (dangerous_ld_env) {
1935 if (fstatfs(fd, &fs) != 0) {
1936 _rtld_error("Cannot fstatfs \"%s\"", printable_path(path));
1939 if (fs.f_flags & MNT_NOEXEC) {
1940 _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
1944 dbg("loading \"%s\"", printable_path(path));
1945 obj = map_object(fd, printable_path(path), sbp);
1950 * If DT_SONAME is present in the object, digest_dynamic2 already
1951 * added it to the object names.
1954 object_add_name(obj, name);
1956 digest_dynamic(obj, 0);
1957 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path,
1958 obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount);
1959 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
1961 dbg("refusing to load non-loadable \"%s\"", obj->path);
1962 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
1963 munmap(obj->mapbase, obj->mapsize);
1969 obj_tail = &obj->next;
1972 linkmap_add(obj); /* for GDB & dlinfo() */
1973 max_stack_flags |= obj->stack_flags;
1975 dbg(" %p .. %p: %s", obj->mapbase,
1976 obj->mapbase + obj->mapsize - 1, obj->path);
1978 dbg(" WARNING: %s has impure text", obj->path);
1979 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
1986 obj_from_addr(const void *addr)
1990 for (obj = obj_list; obj != NULL; obj = obj->next) {
1991 if (addr < (void *) obj->mapbase)
1993 if (addr < (void *) (obj->mapbase + obj->mapsize))
2002 Elf_Addr *preinit_addr;
2005 preinit_addr = (Elf_Addr *)obj_main->preinit_array;
2006 if (preinit_addr == NULL)
2009 for (index = 0; index < obj_main->preinit_array_num; index++) {
2010 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) {
2011 dbg("calling preinit function for %s at %p", obj_main->path,
2012 (void *)preinit_addr[index]);
2013 LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index],
2014 0, 0, obj_main->path);
2015 call_init_pointer(obj_main, preinit_addr[index]);
2021 * Call the finalization functions for each of the objects in "list"
2022 * belonging to the DAG of "root" and referenced once. If NULL "root"
2023 * is specified, every finalization function will be called regardless
2024 * of the reference count and the list elements won't be freed. All of
2025 * the objects are expected to have non-NULL fini functions.
2028 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
2032 Elf_Addr *fini_addr;
2035 assert(root == NULL || root->refcount == 1);
2038 * Preserve the current error message since a fini function might
2039 * call into the dynamic linker and overwrite it.
2041 saved_msg = errmsg_save();
2043 STAILQ_FOREACH(elm, list, link) {
2044 if (root != NULL && (elm->obj->refcount != 1 ||
2045 objlist_find(&root->dagmembers, elm->obj) == NULL))
2047 /* Remove object from fini list to prevent recursive invocation. */
2048 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2050 * XXX: If a dlopen() call references an object while the
2051 * fini function is in progress, we might end up trying to
2052 * unload the referenced object in dlclose() or the object
2053 * won't be unloaded although its fini function has been
2056 lock_release(rtld_bind_lock, lockstate);
2059 * It is legal to have both DT_FINI and DT_FINI_ARRAY defined.
2060 * When this happens, DT_FINI_ARRAY is processed first.
2062 fini_addr = (Elf_Addr *)elm->obj->fini_array;
2063 if (fini_addr != NULL && elm->obj->fini_array_num > 0) {
2064 for (index = elm->obj->fini_array_num - 1; index >= 0;
2066 if (fini_addr[index] != 0 && fini_addr[index] != 1) {
2067 dbg("calling fini function for %s at %p",
2068 elm->obj->path, (void *)fini_addr[index]);
2069 LD_UTRACE(UTRACE_FINI_CALL, elm->obj,
2070 (void *)fini_addr[index], 0, 0, elm->obj->path);
2071 call_initfini_pointer(elm->obj, fini_addr[index]);
2075 if (elm->obj->fini != (Elf_Addr)NULL) {
2076 dbg("calling fini function for %s at %p", elm->obj->path,
2077 (void *)elm->obj->fini);
2078 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini,
2079 0, 0, elm->obj->path);
2080 call_initfini_pointer(elm->obj, elm->obj->fini);
2082 wlock_acquire(rtld_bind_lock, lockstate);
2083 /* No need to free anything if process is going down. */
2087 * We must restart the list traversal after every fini call
2088 * because a dlclose() call from the fini function or from
2089 * another thread might have modified the reference counts.
2093 } while (elm != NULL);
2094 errmsg_restore(saved_msg);
2098 * Call the initialization functions for each of the objects in
2099 * "list". All of the objects are expected to have non-NULL init
2103 objlist_call_init(Objlist *list, RtldLockState *lockstate)
2108 Elf_Addr *init_addr;
2112 * Clean init_scanned flag so that objects can be rechecked and
2113 * possibly initialized earlier if any of vectors called below
2114 * cause the change by using dlopen.
2116 for (obj = obj_list; obj != NULL; obj = obj->next)
2117 obj->init_scanned = false;
2120 * Preserve the current error message since an init function might
2121 * call into the dynamic linker and overwrite it.
2123 saved_msg = errmsg_save();
2124 STAILQ_FOREACH(elm, list, link) {
2125 if (elm->obj->init_done) /* Initialized early. */
2128 * Race: other thread might try to use this object before current
2129 * one completes the initilization. Not much can be done here
2130 * without better locking.
2132 elm->obj->init_done = true;
2133 lock_release(rtld_bind_lock, lockstate);
2136 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined.
2137 * When this happens, DT_INIT is processed first.
2139 if (elm->obj->init != (Elf_Addr)NULL) {
2140 dbg("calling init function for %s at %p", elm->obj->path,
2141 (void *)elm->obj->init);
2142 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init,
2143 0, 0, elm->obj->path);
2144 call_initfini_pointer(elm->obj, elm->obj->init);
2146 init_addr = (Elf_Addr *)elm->obj->init_array;
2147 if (init_addr != NULL) {
2148 for (index = 0; index < elm->obj->init_array_num; index++) {
2149 if (init_addr[index] != 0 && init_addr[index] != 1) {
2150 dbg("calling init function for %s at %p", elm->obj->path,
2151 (void *)init_addr[index]);
2152 LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
2153 (void *)init_addr[index], 0, 0, elm->obj->path);
2154 call_init_pointer(elm->obj, init_addr[index]);
2158 wlock_acquire(rtld_bind_lock, lockstate);
2160 errmsg_restore(saved_msg);
2164 objlist_clear(Objlist *list)
2168 while (!STAILQ_EMPTY(list)) {
2169 elm = STAILQ_FIRST(list);
2170 STAILQ_REMOVE_HEAD(list, link);
2175 static Objlist_Entry *
2176 objlist_find(Objlist *list, const Obj_Entry *obj)
2180 STAILQ_FOREACH(elm, list, link)
2181 if (elm->obj == obj)
2187 objlist_init(Objlist *list)
2193 objlist_push_head(Objlist *list, Obj_Entry *obj)
2197 elm = NEW(Objlist_Entry);
2199 STAILQ_INSERT_HEAD(list, elm, link);
2203 objlist_push_tail(Objlist *list, Obj_Entry *obj)
2207 elm = NEW(Objlist_Entry);
2209 STAILQ_INSERT_TAIL(list, elm, link);
2213 objlist_remove(Objlist *list, Obj_Entry *obj)
2217 if ((elm = objlist_find(list, obj)) != NULL) {
2218 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2224 * Relocate dag rooted in the specified object.
2225 * Returns 0 on success, or -1 on failure.
2229 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj,
2230 int flags, RtldLockState *lockstate)
2236 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2237 error = relocate_object(elm->obj, bind_now, rtldobj, flags,
2246 * Relocate single object.
2247 * Returns 0 on success, or -1 on failure.
2250 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
2251 int flags, RtldLockState *lockstate)
2256 obj->relocated = true;
2258 dbg("relocating \"%s\"", obj->path);
2260 if (obj->symtab == NULL || obj->strtab == NULL ||
2261 !(obj->valid_hash_sysv || obj->valid_hash_gnu)) {
2262 _rtld_error("%s: Shared object has no run-time symbol table",
2268 /* There are relocations to the write-protected text segment. */
2269 if (mprotect(obj->mapbase, obj->textsize,
2270 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
2271 _rtld_error("%s: Cannot write-enable text segment: %s",
2272 obj->path, rtld_strerror(errno));
2277 /* Process the non-PLT relocations. */
2278 if (reloc_non_plt(obj, rtldobj, flags, lockstate))
2281 if (obj->textrel) { /* Re-protected the text segment. */
2282 if (mprotect(obj->mapbase, obj->textsize,
2283 PROT_READ|PROT_EXEC) == -1) {
2284 _rtld_error("%s: Cannot write-protect text segment: %s",
2285 obj->path, rtld_strerror(errno));
2291 /* Set the special PLT or GOT entries. */
2294 /* Process the PLT relocations. */
2295 if (reloc_plt(obj) == -1)
2297 /* Relocate the jump slots if we are doing immediate binding. */
2298 if (obj->bind_now || bind_now)
2299 if (reloc_jmpslots(obj, flags, lockstate) == -1)
2302 if (obj->relro_size > 0) {
2303 if (mprotect(obj->relro_page, obj->relro_size,
2305 _rtld_error("%s: Cannot enforce relro protection: %s",
2306 obj->path, rtld_strerror(errno));
2312 * Set up the magic number and version in the Obj_Entry. These
2313 * were checked in the crt1.o from the original ElfKit, so we
2314 * set them for backward compatibility.
2316 obj->magic = RTLD_MAGIC;
2317 obj->version = RTLD_VERSION;
2323 * Relocate newly-loaded shared objects. The argument is a pointer to
2324 * the Obj_Entry for the first such object. All objects from the first
2325 * to the end of the list of objects are relocated. Returns 0 on success,
2329 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
2330 int flags, RtldLockState *lockstate)
2335 for (error = 0, obj = first; obj != NULL; obj = obj->next) {
2336 error = relocate_object(obj, bind_now, rtldobj, flags,
2345 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
2346 * referencing STT_GNU_IFUNC symbols is postponed till the other
2347 * relocations are done. The indirect functions specified as
2348 * ifunc are allowed to call other symbols, so we need to have
2349 * objects relocated before asking for resolution from indirects.
2351 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
2352 * instead of the usual lazy handling of PLT slots. It is
2353 * consistent with how GNU does it.
2356 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags,
2357 RtldLockState *lockstate)
2359 if (obj->irelative && reloc_iresolve(obj, lockstate) == -1)
2361 if ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
2362 reloc_gnu_ifunc(obj, flags, lockstate) == -1)
2368 resolve_objects_ifunc(Obj_Entry *first, bool bind_now, int flags,
2369 RtldLockState *lockstate)
2373 for (obj = first; obj != NULL; obj = obj->next) {
2374 if (resolve_object_ifunc(obj, bind_now, flags, lockstate) == -1)
2381 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags,
2382 RtldLockState *lockstate)
2386 STAILQ_FOREACH(elm, list, link) {
2387 if (resolve_object_ifunc(elm->obj, bind_now, flags,
2395 * Cleanup procedure. It will be called (by the atexit mechanism) just
2396 * before the process exits.
2401 RtldLockState lockstate;
2403 wlock_acquire(rtld_bind_lock, &lockstate);
2405 objlist_call_fini(&list_fini, NULL, &lockstate);
2406 /* No need to remove the items from the list, since we are exiting. */
2407 if (!libmap_disable)
2409 lock_release(rtld_bind_lock, &lockstate);
2413 path_enumerate(const char *path, path_enum_proc callback, void *arg)
2421 path += strspn(path, ":;");
2422 while (*path != '\0') {
2426 len = strcspn(path, ":;");
2428 trans = lm_findn(NULL, path, len);
2430 res = callback(trans, strlen(trans), arg);
2433 res = callback(path, len, arg);
2439 path += strspn(path, ":;");
2445 struct try_library_args {
2453 try_library_path(const char *dir, size_t dirlen, void *param)
2455 struct try_library_args *arg;
2458 if (*dir == '/' || trust) {
2461 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
2464 pathname = arg->buffer;
2465 strncpy(pathname, dir, dirlen);
2466 pathname[dirlen] = '/';
2467 strcpy(pathname + dirlen + 1, arg->name);
2469 dbg(" Trying \"%s\"", pathname);
2470 if (access(pathname, F_OK) == 0) { /* We found it */
2471 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
2472 strcpy(pathname, arg->buffer);
2480 search_library_path(const char *name, const char *path)
2483 struct try_library_args arg;
2489 arg.namelen = strlen(name);
2490 arg.buffer = xmalloc(PATH_MAX);
2491 arg.buflen = PATH_MAX;
2493 p = path_enumerate(path, try_library_path, &arg);
2501 dlclose(void *handle)
2504 RtldLockState lockstate;
2506 wlock_acquire(rtld_bind_lock, &lockstate);
2507 root = dlcheck(handle);
2509 lock_release(rtld_bind_lock, &lockstate);
2512 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
2515 /* Unreference the object and its dependencies. */
2516 root->dl_refcount--;
2518 if (root->refcount == 1) {
2520 * The object will be no longer referenced, so we must unload it.
2521 * First, call the fini functions.
2523 objlist_call_fini(&list_fini, root, &lockstate);
2527 /* Finish cleaning up the newly-unreferenced objects. */
2528 GDB_STATE(RT_DELETE,&root->linkmap);
2529 unload_object(root);
2530 GDB_STATE(RT_CONSISTENT,NULL);
2534 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
2535 lock_release(rtld_bind_lock, &lockstate);
2542 char *msg = error_message;
2543 error_message = NULL;
2548 * This function is deprecated and has no effect.
2551 dllockinit(void *context,
2552 void *(*lock_create)(void *context),
2553 void (*rlock_acquire)(void *lock),
2554 void (*wlock_acquire)(void *lock),
2555 void (*lock_release)(void *lock),
2556 void (*lock_destroy)(void *lock),
2557 void (*context_destroy)(void *context))
2559 static void *cur_context;
2560 static void (*cur_context_destroy)(void *);
2562 /* Just destroy the context from the previous call, if necessary. */
2563 if (cur_context_destroy != NULL)
2564 cur_context_destroy(cur_context);
2565 cur_context = context;
2566 cur_context_destroy = context_destroy;
2570 dlopen(const char *name, int mode)
2573 return (rtld_dlopen(name, -1, mode));
2577 fdlopen(int fd, int mode)
2580 return (rtld_dlopen(NULL, fd, mode));
2584 rtld_dlopen(const char *name, int fd, int mode)
2586 RtldLockState lockstate;
2589 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
2590 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
2591 if (ld_tracing != NULL) {
2592 rlock_acquire(rtld_bind_lock, &lockstate);
2593 if (sigsetjmp(lockstate.env, 0) != 0)
2594 lock_upgrade(rtld_bind_lock, &lockstate);
2595 environ = (char **)*get_program_var_addr("environ", &lockstate);
2596 lock_release(rtld_bind_lock, &lockstate);
2598 lo_flags = RTLD_LO_DLOPEN;
2599 if (mode & RTLD_NODELETE)
2600 lo_flags |= RTLD_LO_NODELETE;
2601 if (mode & RTLD_NOLOAD)
2602 lo_flags |= RTLD_LO_NOLOAD;
2603 if (ld_tracing != NULL)
2604 lo_flags |= RTLD_LO_TRACE;
2606 return (dlopen_object(name, fd, obj_main, lo_flags,
2607 mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL));
2611 dlopen_cleanup(Obj_Entry *obj)
2616 if (obj->refcount == 0)
2621 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
2622 int mode, RtldLockState *lockstate)
2624 Obj_Entry **old_obj_tail;
2627 RtldLockState mlockstate;
2630 objlist_init(&initlist);
2632 if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) {
2633 wlock_acquire(rtld_bind_lock, &mlockstate);
2634 lockstate = &mlockstate;
2636 GDB_STATE(RT_ADD,NULL);
2638 old_obj_tail = obj_tail;
2640 if (name == NULL && fd == -1) {
2644 obj = load_object(name, fd, refobj, lo_flags);
2649 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
2650 objlist_push_tail(&list_global, obj);
2651 if (*old_obj_tail != NULL) { /* We loaded something new. */
2652 assert(*old_obj_tail == obj);
2653 result = load_needed_objects(obj,
2654 lo_flags & (RTLD_LO_DLOPEN | RTLD_LO_EARLY));
2658 result = rtld_verify_versions(&obj->dagmembers);
2659 if (result != -1 && ld_tracing)
2661 if (result == -1 || relocate_object_dag(obj,
2662 (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld,
2663 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
2665 dlopen_cleanup(obj);
2667 } else if (lo_flags & RTLD_LO_EARLY) {
2669 * Do not call the init functions for early loaded
2670 * filtees. The image is still not initialized enough
2673 * Our object is found by the global object list and
2674 * will be ordered among all init calls done right
2675 * before transferring control to main.
2678 /* Make list of init functions to call. */
2679 initlist_add_objects(obj, &obj->next, &initlist);
2684 * Bump the reference counts for objects on this DAG. If
2685 * this is the first dlopen() call for the object that was
2686 * already loaded as a dependency, initialize the dag
2692 if ((lo_flags & RTLD_LO_TRACE) != 0)
2695 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
2696 obj->z_nodelete) && !obj->ref_nodel) {
2697 dbg("obj %s nodelete", obj->path);
2699 obj->z_nodelete = obj->ref_nodel = true;
2703 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
2705 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
2707 if (!(lo_flags & RTLD_LO_EARLY)) {
2708 map_stacks_exec(lockstate);
2711 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
2712 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
2714 objlist_clear(&initlist);
2715 dlopen_cleanup(obj);
2716 if (lockstate == &mlockstate)
2717 lock_release(rtld_bind_lock, lockstate);
2721 if (!(lo_flags & RTLD_LO_EARLY)) {
2722 /* Call the init functions. */
2723 objlist_call_init(&initlist, lockstate);
2725 objlist_clear(&initlist);
2726 if (lockstate == &mlockstate)
2727 lock_release(rtld_bind_lock, lockstate);
2730 trace_loaded_objects(obj);
2731 if (lockstate == &mlockstate)
2732 lock_release(rtld_bind_lock, lockstate);
2737 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
2741 const Obj_Entry *obj, *defobj;
2744 RtldLockState lockstate;
2752 symlook_init(&req, name);
2754 req.flags = flags | SYMLOOK_IN_PLT;
2755 req.lockstate = &lockstate;
2757 rlock_acquire(rtld_bind_lock, &lockstate);
2758 if (sigsetjmp(lockstate.env, 0) != 0)
2759 lock_upgrade(rtld_bind_lock, &lockstate);
2760 if (handle == NULL || handle == RTLD_NEXT ||
2761 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
2763 if ((obj = obj_from_addr(retaddr)) == NULL) {
2764 _rtld_error("Cannot determine caller's shared object");
2765 lock_release(rtld_bind_lock, &lockstate);
2768 if (handle == NULL) { /* Just the caller's shared object. */
2769 res = symlook_obj(&req, obj);
2772 defobj = req.defobj_out;
2774 } else if (handle == RTLD_NEXT || /* Objects after caller's */
2775 handle == RTLD_SELF) { /* ... caller included */
2776 if (handle == RTLD_NEXT)
2778 for (; obj != NULL; obj = obj->next) {
2779 res = symlook_obj(&req, obj);
2782 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) {
2784 defobj = req.defobj_out;
2785 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2791 * Search the dynamic linker itself, and possibly resolve the
2792 * symbol from there. This is how the application links to
2793 * dynamic linker services such as dlopen.
2795 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2796 res = symlook_obj(&req, &obj_rtld);
2799 defobj = req.defobj_out;
2803 assert(handle == RTLD_DEFAULT);
2804 res = symlook_default(&req, obj);
2806 defobj = req.defobj_out;
2811 if ((obj = dlcheck(handle)) == NULL) {
2812 lock_release(rtld_bind_lock, &lockstate);
2816 donelist_init(&donelist);
2817 if (obj->mainprog) {
2818 /* Handle obtained by dlopen(NULL, ...) implies global scope. */
2819 res = symlook_global(&req, &donelist);
2822 defobj = req.defobj_out;
2825 * Search the dynamic linker itself, and possibly resolve the
2826 * symbol from there. This is how the application links to
2827 * dynamic linker services such as dlopen.
2829 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2830 res = symlook_obj(&req, &obj_rtld);
2833 defobj = req.defobj_out;
2838 /* Search the whole DAG rooted at the given object. */
2839 res = symlook_list(&req, &obj->dagmembers, &donelist);
2842 defobj = req.defobj_out;
2848 lock_release(rtld_bind_lock, &lockstate);
2851 * The value required by the caller is derived from the value
2852 * of the symbol. For the ia64 architecture, we need to
2853 * construct a function descriptor which the caller can use to
2854 * call the function with the right 'gp' value. For other
2855 * architectures and for non-functions, the value is simply
2856 * the relocated value of the symbol.
2858 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
2859 return (make_function_pointer(def, defobj));
2860 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
2861 return (rtld_resolve_ifunc(defobj, def));
2862 else if (ELF_ST_TYPE(def->st_info) == STT_TLS) {
2864 return (__tls_get_addr(defobj->tlsindex, def->st_value));
2866 ti.ti_module = defobj->tlsindex;
2867 ti.ti_offset = def->st_value;
2868 return (__tls_get_addr(&ti));
2871 return (defobj->relocbase + def->st_value);
2874 _rtld_error("Undefined symbol \"%s\"", name);
2875 lock_release(rtld_bind_lock, &lockstate);
2880 dlsym(void *handle, const char *name)
2882 return do_dlsym(handle, name, __builtin_return_address(0), NULL,
2887 dlfunc(void *handle, const char *name)
2894 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
2900 dlvsym(void *handle, const char *name, const char *version)
2904 ventry.name = version;
2906 ventry.hash = elf_hash(version);
2908 return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
2913 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
2915 const Obj_Entry *obj;
2916 RtldLockState lockstate;
2918 rlock_acquire(rtld_bind_lock, &lockstate);
2919 obj = obj_from_addr(addr);
2921 _rtld_error("No shared object contains address");
2922 lock_release(rtld_bind_lock, &lockstate);
2925 rtld_fill_dl_phdr_info(obj, phdr_info);
2926 lock_release(rtld_bind_lock, &lockstate);
2931 dladdr(const void *addr, Dl_info *info)
2933 const Obj_Entry *obj;
2936 unsigned long symoffset;
2937 RtldLockState lockstate;
2939 rlock_acquire(rtld_bind_lock, &lockstate);
2940 obj = obj_from_addr(addr);
2942 _rtld_error("No shared object contains address");
2943 lock_release(rtld_bind_lock, &lockstate);
2946 info->dli_fname = obj->path;
2947 info->dli_fbase = obj->mapbase;
2948 info->dli_saddr = (void *)0;
2949 info->dli_sname = NULL;
2952 * Walk the symbol list looking for the symbol whose address is
2953 * closest to the address sent in.
2955 for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) {
2956 def = obj->symtab + symoffset;
2959 * For skip the symbol if st_shndx is either SHN_UNDEF or
2962 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
2966 * If the symbol is greater than the specified address, or if it
2967 * is further away from addr than the current nearest symbol,
2970 symbol_addr = obj->relocbase + def->st_value;
2971 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
2974 /* Update our idea of the nearest symbol. */
2975 info->dli_sname = obj->strtab + def->st_name;
2976 info->dli_saddr = symbol_addr;
2979 if (info->dli_saddr == addr)
2982 lock_release(rtld_bind_lock, &lockstate);
2987 dlinfo(void *handle, int request, void *p)
2989 const Obj_Entry *obj;
2990 RtldLockState lockstate;
2993 rlock_acquire(rtld_bind_lock, &lockstate);
2995 if (handle == NULL || handle == RTLD_SELF) {
2998 retaddr = __builtin_return_address(0); /* __GNUC__ only */
2999 if ((obj = obj_from_addr(retaddr)) == NULL)
3000 _rtld_error("Cannot determine caller's shared object");
3002 obj = dlcheck(handle);
3005 lock_release(rtld_bind_lock, &lockstate);
3011 case RTLD_DI_LINKMAP:
3012 *((struct link_map const **)p) = &obj->linkmap;
3014 case RTLD_DI_ORIGIN:
3015 error = rtld_dirname(obj->path, p);
3018 case RTLD_DI_SERINFOSIZE:
3019 case RTLD_DI_SERINFO:
3020 error = do_search_info(obj, request, (struct dl_serinfo *)p);
3024 _rtld_error("Invalid request %d passed to dlinfo()", request);
3028 lock_release(rtld_bind_lock, &lockstate);
3034 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
3037 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
3038 phdr_info->dlpi_name = STAILQ_FIRST(&obj->names) ?
3039 STAILQ_FIRST(&obj->names)->name : obj->path;
3040 phdr_info->dlpi_phdr = obj->phdr;
3041 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
3042 phdr_info->dlpi_tls_modid = obj->tlsindex;
3043 phdr_info->dlpi_tls_data = obj->tlsinit;
3044 phdr_info->dlpi_adds = obj_loads;
3045 phdr_info->dlpi_subs = obj_loads - obj_count;
3049 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
3051 struct dl_phdr_info phdr_info;
3052 const Obj_Entry *obj;
3053 RtldLockState bind_lockstate, phdr_lockstate;
3056 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
3057 rlock_acquire(rtld_bind_lock, &bind_lockstate);
3061 for (obj = obj_list; obj != NULL; obj = obj->next) {
3062 rtld_fill_dl_phdr_info(obj, &phdr_info);
3063 if ((error = callback(&phdr_info, sizeof phdr_info, param)) != 0)
3067 lock_release(rtld_bind_lock, &bind_lockstate);
3068 lock_release(rtld_phdr_lock, &phdr_lockstate);
3073 struct fill_search_info_args {
3076 Dl_serinfo *serinfo;
3077 Dl_serpath *serpath;
3082 fill_search_info(const char *dir, size_t dirlen, void *param)
3084 struct fill_search_info_args *arg;
3088 if (arg->request == RTLD_DI_SERINFOSIZE) {
3089 arg->serinfo->dls_cnt ++;
3090 arg->serinfo->dls_size += sizeof(Dl_serpath) + dirlen + 1;
3092 struct dl_serpath *s_entry;
3094 s_entry = arg->serpath;
3095 s_entry->dls_name = arg->strspace;
3096 s_entry->dls_flags = arg->flags;
3098 strncpy(arg->strspace, dir, dirlen);
3099 arg->strspace[dirlen] = '\0';
3101 arg->strspace += dirlen + 1;
3109 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
3111 struct dl_serinfo _info;
3112 struct fill_search_info_args args;
3114 args.request = RTLD_DI_SERINFOSIZE;
3115 args.serinfo = &_info;
3117 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
3120 path_enumerate(ld_library_path, fill_search_info, &args);
3121 path_enumerate(obj->rpath, fill_search_info, &args);
3122 path_enumerate(gethints(), fill_search_info, &args);
3123 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
3126 if (request == RTLD_DI_SERINFOSIZE) {
3127 info->dls_size = _info.dls_size;
3128 info->dls_cnt = _info.dls_cnt;
3132 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
3133 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
3137 args.request = RTLD_DI_SERINFO;
3138 args.serinfo = info;
3139 args.serpath = &info->dls_serpath[0];
3140 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
3142 args.flags = LA_SER_LIBPATH;
3143 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
3146 args.flags = LA_SER_RUNPATH;
3147 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
3150 args.flags = LA_SER_CONFIG;
3151 if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
3154 args.flags = LA_SER_DEFAULT;
3155 if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
3161 rtld_dirname(const char *path, char *bname)
3165 /* Empty or NULL string gets treated as "." */
3166 if (path == NULL || *path == '\0') {
3172 /* Strip trailing slashes */
3173 endp = path + strlen(path) - 1;
3174 while (endp > path && *endp == '/')
3177 /* Find the start of the dir */
3178 while (endp > path && *endp != '/')
3181 /* Either the dir is "/" or there are no slashes */
3183 bname[0] = *endp == '/' ? '/' : '.';
3189 } while (endp > path && *endp == '/');
3192 if (endp - path + 2 > PATH_MAX)
3194 _rtld_error("Filename is too long: %s", path);
3198 strncpy(bname, path, endp - path + 1);
3199 bname[endp - path + 1] = '\0';
3204 rtld_dirname_abs(const char *path, char *base)
3206 char base_rel[PATH_MAX];
3208 if (rtld_dirname(path, base) == -1)
3212 if (getcwd(base_rel, sizeof(base_rel)) == NULL ||
3213 strlcat(base_rel, "/", sizeof(base_rel)) >= sizeof(base_rel) ||
3214 strlcat(base_rel, base, sizeof(base_rel)) >= sizeof(base_rel))
3216 strcpy(base, base_rel);
3221 linkmap_add(Obj_Entry *obj)
3223 struct link_map *l = &obj->linkmap;
3224 struct link_map *prev;
3226 obj->linkmap.l_name = obj->path;
3227 obj->linkmap.l_addr = obj->mapbase;
3228 obj->linkmap.l_ld = obj->dynamic;
3230 /* GDB needs load offset on MIPS to use the symbols */
3231 obj->linkmap.l_offs = obj->relocbase;
3234 if (r_debug.r_map == NULL) {
3240 * Scan to the end of the list, but not past the entry for the
3241 * dynamic linker, which we want to keep at the very end.
3243 for (prev = r_debug.r_map;
3244 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
3245 prev = prev->l_next)
3248 /* Link in the new entry. */
3250 l->l_next = prev->l_next;
3251 if (l->l_next != NULL)
3252 l->l_next->l_prev = l;
3257 linkmap_delete(Obj_Entry *obj)
3259 struct link_map *l = &obj->linkmap;
3261 if (l->l_prev == NULL) {
3262 if ((r_debug.r_map = l->l_next) != NULL)
3263 l->l_next->l_prev = NULL;
3267 if ((l->l_prev->l_next = l->l_next) != NULL)
3268 l->l_next->l_prev = l->l_prev;
3272 * Function for the debugger to set a breakpoint on to gain control.
3274 * The two parameters allow the debugger to easily find and determine
3275 * what the runtime loader is doing and to whom it is doing it.
3277 * When the loadhook trap is hit (r_debug_state, set at program
3278 * initialization), the arguments can be found on the stack:
3280 * +8 struct link_map *m
3281 * +4 struct r_debug *rd
3285 r_debug_state(struct r_debug* rd, struct link_map *m)
3288 * The following is a hack to force the compiler to emit calls to
3289 * this function, even when optimizing. If the function is empty,
3290 * the compiler is not obliged to emit any code for calls to it,
3291 * even when marked __noinline. However, gdb depends on those
3294 __asm __volatile("" : : : "memory");
3298 * Get address of the pointer variable in the main program.
3299 * Prefer non-weak symbol over the weak one.
3301 static const void **
3302 get_program_var_addr(const char *name, RtldLockState *lockstate)
3307 symlook_init(&req, name);
3308 req.lockstate = lockstate;
3309 donelist_init(&donelist);
3310 if (symlook_global(&req, &donelist) != 0)
3312 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
3313 return ((const void **)make_function_pointer(req.sym_out,
3315 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
3316 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
3318 return ((const void **)(req.defobj_out->relocbase +
3319 req.sym_out->st_value));
3323 * Set a pointer variable in the main program to the given value. This
3324 * is used to set key variables such as "environ" before any of the
3325 * init functions are called.
3328 set_program_var(const char *name, const void *value)
3332 if ((addr = get_program_var_addr(name, NULL)) != NULL) {
3333 dbg("\"%s\": *%p <-- %p", name, addr, value);
3339 * Search the global objects, including dependencies and main object,
3340 * for the given symbol.
3343 symlook_global(SymLook *req, DoneList *donelist)
3346 const Objlist_Entry *elm;
3349 symlook_init_from_req(&req1, req);
3351 /* Search all objects loaded at program start up. */
3352 if (req->defobj_out == NULL ||
3353 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3354 res = symlook_list(&req1, &list_main, donelist);
3355 if (res == 0 && (req->defobj_out == NULL ||
3356 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3357 req->sym_out = req1.sym_out;
3358 req->defobj_out = req1.defobj_out;
3359 assert(req->defobj_out != NULL);
3363 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
3364 STAILQ_FOREACH(elm, &list_global, link) {
3365 if (req->defobj_out != NULL &&
3366 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3368 res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
3369 if (res == 0 && (req->defobj_out == NULL ||
3370 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3371 req->sym_out = req1.sym_out;
3372 req->defobj_out = req1.defobj_out;
3373 assert(req->defobj_out != NULL);
3377 return (req->sym_out != NULL ? 0 : ESRCH);
3381 * Given a symbol name in a referencing object, find the corresponding
3382 * definition of the symbol. Returns a pointer to the symbol, or NULL if
3383 * no definition was found. Returns a pointer to the Obj_Entry of the
3384 * defining object via the reference parameter DEFOBJ_OUT.
3387 symlook_default(SymLook *req, const Obj_Entry *refobj)
3390 const Objlist_Entry *elm;
3394 donelist_init(&donelist);
3395 symlook_init_from_req(&req1, req);
3397 /* Look first in the referencing object if linked symbolically. */
3398 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
3399 res = symlook_obj(&req1, refobj);
3401 req->sym_out = req1.sym_out;
3402 req->defobj_out = req1.defobj_out;
3403 assert(req->defobj_out != NULL);
3407 symlook_global(req, &donelist);
3409 /* Search all dlopened DAGs containing the referencing object. */
3410 STAILQ_FOREACH(elm, &refobj->dldags, link) {
3411 if (req->sym_out != NULL &&
3412 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3414 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
3415 if (res == 0 && (req->sym_out == NULL ||
3416 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3417 req->sym_out = req1.sym_out;
3418 req->defobj_out = req1.defobj_out;
3419 assert(req->defobj_out != NULL);
3424 * Search the dynamic linker itself, and possibly resolve the
3425 * symbol from there. This is how the application links to
3426 * dynamic linker services such as dlopen.
3428 if (req->sym_out == NULL ||
3429 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3430 res = symlook_obj(&req1, &obj_rtld);
3432 req->sym_out = req1.sym_out;
3433 req->defobj_out = req1.defobj_out;
3434 assert(req->defobj_out != NULL);
3438 return (req->sym_out != NULL ? 0 : ESRCH);
3442 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
3445 const Obj_Entry *defobj;
3446 const Objlist_Entry *elm;
3452 STAILQ_FOREACH(elm, objlist, link) {
3453 if (donelist_check(dlp, elm->obj))
3455 symlook_init_from_req(&req1, req);
3456 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
3457 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3459 defobj = req1.defobj_out;
3460 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3467 req->defobj_out = defobj;
3474 * Search the chain of DAGS cointed to by the given Needed_Entry
3475 * for a symbol of the given name. Each DAG is scanned completely
3476 * before advancing to the next one. Returns a pointer to the symbol,
3477 * or NULL if no definition was found.
3480 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
3483 const Needed_Entry *n;
3484 const Obj_Entry *defobj;
3490 symlook_init_from_req(&req1, req);
3491 for (n = needed; n != NULL; n = n->next) {
3492 if (n->obj == NULL ||
3493 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
3495 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3497 defobj = req1.defobj_out;
3498 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3504 req->defobj_out = defobj;
3511 * Search the symbol table of a single shared object for a symbol of
3512 * the given name and version, if requested. Returns a pointer to the
3513 * symbol, or NULL if no definition was found. If the object is
3514 * filter, return filtered symbol from filtee.
3516 * The symbol's hash value is passed in for efficiency reasons; that
3517 * eliminates many recomputations of the hash value.
3520 symlook_obj(SymLook *req, const Obj_Entry *obj)
3524 int flags, res, mres;
3527 * If there is at least one valid hash at this point, we prefer to
3528 * use the faster GNU version if available.
3530 if (obj->valid_hash_gnu)
3531 mres = symlook_obj1_gnu(req, obj);
3532 else if (obj->valid_hash_sysv)
3533 mres = symlook_obj1_sysv(req, obj);
3538 if (obj->needed_filtees != NULL) {
3539 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
3540 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
3541 donelist_init(&donelist);
3542 symlook_init_from_req(&req1, req);
3543 res = symlook_needed(&req1, obj->needed_filtees, &donelist);
3545 req->sym_out = req1.sym_out;
3546 req->defobj_out = req1.defobj_out;
3550 if (obj->needed_aux_filtees != NULL) {
3551 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
3552 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
3553 donelist_init(&donelist);
3554 symlook_init_from_req(&req1, req);
3555 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
3557 req->sym_out = req1.sym_out;
3558 req->defobj_out = req1.defobj_out;
3566 /* Symbol match routine common to both hash functions */
3568 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result,
3569 const unsigned long symnum)
3572 const Elf_Sym *symp;
3575 symp = obj->symtab + symnum;
3576 strp = obj->strtab + symp->st_name;
3578 switch (ELF_ST_TYPE(symp->st_info)) {
3584 if (symp->st_value == 0)
3588 if (symp->st_shndx != SHN_UNDEF)
3591 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
3592 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
3599 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
3602 if (req->ventry == NULL) {
3603 if (obj->versyms != NULL) {
3604 verndx = VER_NDX(obj->versyms[symnum]);
3605 if (verndx > obj->vernum) {
3607 "%s: symbol %s references wrong version %d",
3608 obj->path, obj->strtab + symnum, verndx);
3612 * If we are not called from dlsym (i.e. this
3613 * is a normal relocation from unversioned
3614 * binary), accept the symbol immediately if
3615 * it happens to have first version after this
3616 * shared object became versioned. Otherwise,
3617 * if symbol is versioned and not hidden,
3618 * remember it. If it is the only symbol with
3619 * this name exported by the shared object, it
3620 * will be returned as a match by the calling
3621 * function. If symbol is global (verndx < 2)
3622 * accept it unconditionally.
3624 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
3625 verndx == VER_NDX_GIVEN) {
3626 result->sym_out = symp;
3629 else if (verndx >= VER_NDX_GIVEN) {
3630 if ((obj->versyms[symnum] & VER_NDX_HIDDEN)
3632 if (result->vsymp == NULL)
3633 result->vsymp = symp;
3639 result->sym_out = symp;
3642 if (obj->versyms == NULL) {
3643 if (object_match_name(obj, req->ventry->name)) {
3644 _rtld_error("%s: object %s should provide version %s "
3645 "for symbol %s", obj_rtld.path, obj->path,
3646 req->ventry->name, obj->strtab + symnum);
3650 verndx = VER_NDX(obj->versyms[symnum]);
3651 if (verndx > obj->vernum) {
3652 _rtld_error("%s: symbol %s references wrong version %d",
3653 obj->path, obj->strtab + symnum, verndx);
3656 if (obj->vertab[verndx].hash != req->ventry->hash ||
3657 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
3659 * Version does not match. Look if this is a
3660 * global symbol and if it is not hidden. If
3661 * global symbol (verndx < 2) is available,
3662 * use it. Do not return symbol if we are
3663 * called by dlvsym, because dlvsym looks for
3664 * a specific version and default one is not
3665 * what dlvsym wants.
3667 if ((req->flags & SYMLOOK_DLSYM) ||
3668 (verndx >= VER_NDX_GIVEN) ||
3669 (obj->versyms[symnum] & VER_NDX_HIDDEN))
3673 result->sym_out = symp;
3678 * Search for symbol using SysV hash function.
3679 * obj->buckets is known not to be NULL at this point; the test for this was
3680 * performed with the obj->valid_hash_sysv assignment.
3683 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj)
3685 unsigned long symnum;
3686 Sym_Match_Result matchres;
3688 matchres.sym_out = NULL;
3689 matchres.vsymp = NULL;
3690 matchres.vcount = 0;
3692 for (symnum = obj->buckets[req->hash % obj->nbuckets];
3693 symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
3694 if (symnum >= obj->nchains)
3695 return (ESRCH); /* Bad object */
3697 if (matched_symbol(req, obj, &matchres, symnum)) {
3698 req->sym_out = matchres.sym_out;
3699 req->defobj_out = obj;
3703 if (matchres.vcount == 1) {
3704 req->sym_out = matchres.vsymp;
3705 req->defobj_out = obj;
3711 /* Search for symbol using GNU hash function */
3713 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj)
3715 Elf_Addr bloom_word;
3716 const Elf32_Word *hashval;
3718 Sym_Match_Result matchres;
3719 unsigned int h1, h2;
3720 unsigned long symnum;
3722 matchres.sym_out = NULL;
3723 matchres.vsymp = NULL;
3724 matchres.vcount = 0;
3726 /* Pick right bitmask word from Bloom filter array */
3727 bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) &
3728 obj->maskwords_bm_gnu];
3730 /* Calculate modulus word size of gnu hash and its derivative */
3731 h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1);
3732 h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1));
3734 /* Filter out the "definitely not in set" queries */
3735 if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0)
3738 /* Locate hash chain and corresponding value element*/
3739 bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu];
3742 hashval = &obj->chain_zero_gnu[bucket];
3744 if (((*hashval ^ req->hash_gnu) >> 1) == 0) {
3745 symnum = hashval - obj->chain_zero_gnu;
3746 if (matched_symbol(req, obj, &matchres, symnum)) {
3747 req->sym_out = matchres.sym_out;
3748 req->defobj_out = obj;
3752 } while ((*hashval++ & 1) == 0);
3753 if (matchres.vcount == 1) {
3754 req->sym_out = matchres.vsymp;
3755 req->defobj_out = obj;
3762 trace_loaded_objects(Obj_Entry *obj)
3764 char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
3767 if ((main_local = getenv(LD_ "TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
3770 if ((fmt1 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT1")) == NULL)
3771 fmt1 = "\t%o => %p (%x)\n";
3773 if ((fmt2 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT2")) == NULL)
3774 fmt2 = "\t%o (%x)\n";
3776 list_containers = getenv(LD_ "TRACE_LOADED_OBJECTS_ALL");
3778 for (; obj; obj = obj->next) {
3779 Needed_Entry *needed;
3783 if (list_containers && obj->needed != NULL)
3784 rtld_printf("%s:\n", obj->path);
3785 for (needed = obj->needed; needed; needed = needed->next) {
3786 if (needed->obj != NULL) {
3787 if (needed->obj->traced && !list_containers)
3789 needed->obj->traced = true;
3790 path = needed->obj->path;
3794 name = (char *)obj->strtab + needed->name;
3795 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
3797 fmt = is_lib ? fmt1 : fmt2;
3798 while ((c = *fmt++) != '\0') {
3824 rtld_putstr(main_local);
3827 rtld_putstr(obj_main->path);
3834 rtld_printf("%d", sodp->sod_major);
3837 rtld_printf("%d", sodp->sod_minor);
3844 rtld_printf("%p", needed->obj ? needed->obj->mapbase :
3857 * Unload a dlopened object and its dependencies from memory and from
3858 * our data structures. It is assumed that the DAG rooted in the
3859 * object has already been unreferenced, and that the object has a
3860 * reference count of 0.
3863 unload_object(Obj_Entry *root)
3868 assert(root->refcount == 0);
3871 * Pass over the DAG removing unreferenced objects from
3872 * appropriate lists.
3874 unlink_object(root);
3876 /* Unmap all objects that are no longer referenced. */
3877 linkp = &obj_list->next;
3878 while ((obj = *linkp) != NULL) {
3879 if (obj->refcount == 0) {
3880 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
3882 dbg("unloading \"%s\"", obj->path);
3883 unload_filtees(root);
3884 munmap(obj->mapbase, obj->mapsize);
3885 linkmap_delete(obj);
3896 unlink_object(Obj_Entry *root)
3900 if (root->refcount == 0) {
3901 /* Remove the object from the RTLD_GLOBAL list. */
3902 objlist_remove(&list_global, root);
3904 /* Remove the object from all objects' DAG lists. */
3905 STAILQ_FOREACH(elm, &root->dagmembers, link) {
3906 objlist_remove(&elm->obj->dldags, root);
3907 if (elm->obj != root)
3908 unlink_object(elm->obj);
3914 ref_dag(Obj_Entry *root)
3918 assert(root->dag_inited);
3919 STAILQ_FOREACH(elm, &root->dagmembers, link)
3920 elm->obj->refcount++;
3924 unref_dag(Obj_Entry *root)
3928 assert(root->dag_inited);
3929 STAILQ_FOREACH(elm, &root->dagmembers, link)
3930 elm->obj->refcount--;
3934 * Common code for MD __tls_get_addr().
3936 static void *tls_get_addr_slow(Elf_Addr **, int, size_t) __noinline;
3938 tls_get_addr_slow(Elf_Addr **dtvp, int index, size_t offset)
3940 Elf_Addr *newdtv, *dtv;
3941 RtldLockState lockstate;
3945 /* Check dtv generation in case new modules have arrived */
3946 if (dtv[0] != tls_dtv_generation) {
3947 wlock_acquire(rtld_bind_lock, &lockstate);
3948 newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
3950 if (to_copy > tls_max_index)
3951 to_copy = tls_max_index;
3952 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
3953 newdtv[0] = tls_dtv_generation;
3954 newdtv[1] = tls_max_index;
3956 lock_release(rtld_bind_lock, &lockstate);
3957 dtv = *dtvp = newdtv;
3960 /* Dynamically allocate module TLS if necessary */
3961 if (dtv[index + 1] == 0) {
3962 /* Signal safe, wlock will block out signals. */
3963 wlock_acquire(rtld_bind_lock, &lockstate);
3964 if (!dtv[index + 1])
3965 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
3966 lock_release(rtld_bind_lock, &lockstate);
3968 return ((void *)(dtv[index + 1] + offset));
3972 tls_get_addr_common(Elf_Addr **dtvp, int index, size_t offset)
3977 /* Check dtv generation in case new modules have arrived */
3978 if (__predict_true(dtv[0] == tls_dtv_generation &&
3979 dtv[index + 1] != 0))
3980 return ((void *)(dtv[index + 1] + offset));
3981 return (tls_get_addr_slow(dtvp, index, offset));
3984 #if defined(__arm__) || defined(__ia64__) || defined(__powerpc__)
3987 * Allocate Static TLS using the Variant I method.
3990 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
3999 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
4002 assert(tcbsize >= TLS_TCB_SIZE);
4003 tcb = xcalloc(1, tls_static_space - TLS_TCB_SIZE + tcbsize);
4004 tls = (Elf_Addr **)(tcb + tcbsize - TLS_TCB_SIZE);
4006 if (oldtcb != NULL) {
4007 memcpy(tls, oldtcb, tls_static_space);
4010 /* Adjust the DTV. */
4012 for (i = 0; i < dtv[1]; i++) {
4013 if (dtv[i+2] >= (Elf_Addr)oldtcb &&
4014 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
4015 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tls;
4019 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4021 dtv[0] = tls_dtv_generation;
4022 dtv[1] = tls_max_index;
4024 for (obj = objs; obj; obj = obj->next) {
4025 if (obj->tlsoffset > 0) {
4026 addr = (Elf_Addr)tls + obj->tlsoffset;
4027 if (obj->tlsinitsize > 0)
4028 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4029 if (obj->tlssize > obj->tlsinitsize)
4030 memset((void*) (addr + obj->tlsinitsize), 0,
4031 obj->tlssize - obj->tlsinitsize);
4032 dtv[obj->tlsindex + 1] = addr;
4041 free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
4044 Elf_Addr tlsstart, tlsend;
4047 assert(tcbsize >= TLS_TCB_SIZE);
4049 tlsstart = (Elf_Addr)tcb + tcbsize - TLS_TCB_SIZE;
4050 tlsend = tlsstart + tls_static_space;
4052 dtv = *(Elf_Addr **)tlsstart;
4054 for (i = 0; i < dtvsize; i++) {
4055 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
4056 free((void*)dtv[i+2]);
4065 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) || \
4069 * Allocate Static TLS using the Variant II method.
4072 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
4077 Elf_Addr *dtv, *olddtv;
4078 Elf_Addr segbase, oldsegbase, addr;
4081 size = round(tls_static_space, tcbalign);
4083 assert(tcbsize >= 2*sizeof(Elf_Addr));
4084 tls = xcalloc(1, size + tcbsize);
4085 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4087 segbase = (Elf_Addr)(tls + size);
4088 ((Elf_Addr*)segbase)[0] = segbase;
4089 ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
4091 dtv[0] = tls_dtv_generation;
4092 dtv[1] = tls_max_index;
4096 * Copy the static TLS block over whole.
4098 oldsegbase = (Elf_Addr) oldtls;
4099 memcpy((void *)(segbase - tls_static_space),
4100 (const void *)(oldsegbase - tls_static_space),
4104 * If any dynamic TLS blocks have been created tls_get_addr(),
4107 olddtv = ((Elf_Addr**)oldsegbase)[1];
4108 for (i = 0; i < olddtv[1]; i++) {
4109 if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
4110 dtv[i+2] = olddtv[i+2];
4116 * We assume that this block was the one we created with
4117 * allocate_initial_tls().
4119 free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
4121 for (obj = objs; obj; obj = obj->next) {
4122 if (obj->tlsoffset) {
4123 addr = segbase - obj->tlsoffset;
4124 memset((void*) (addr + obj->tlsinitsize),
4125 0, obj->tlssize - obj->tlsinitsize);
4127 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4128 dtv[obj->tlsindex + 1] = addr;
4133 return (void*) segbase;
4137 free_tls(void *tls, size_t tcbsize, size_t tcbalign)
4142 Elf_Addr tlsstart, tlsend;
4145 * Figure out the size of the initial TLS block so that we can
4146 * find stuff which ___tls_get_addr() allocated dynamically.
4148 size = round(tls_static_space, tcbalign);
4150 dtv = ((Elf_Addr**)tls)[1];
4152 tlsend = (Elf_Addr) tls;
4153 tlsstart = tlsend - size;
4154 for (i = 0; i < dtvsize; i++) {
4155 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] > tlsend)) {
4156 free((void*) dtv[i+2]);
4160 free((void*) tlsstart);
4167 * Allocate TLS block for module with given index.
4170 allocate_module_tls(int index)
4175 for (obj = obj_list; obj; obj = obj->next) {
4176 if (obj->tlsindex == index)
4180 _rtld_error("Can't find module with TLS index %d", index);
4184 p = malloc(obj->tlssize);
4186 _rtld_error("Cannot allocate TLS block for index %d", index);
4189 memcpy(p, obj->tlsinit, obj->tlsinitsize);
4190 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
4196 allocate_tls_offset(Obj_Entry *obj)
4203 if (obj->tlssize == 0) {
4204 obj->tls_done = true;
4208 if (obj->tlsindex == 1)
4209 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
4211 off = calculate_tls_offset(tls_last_offset, tls_last_size,
4212 obj->tlssize, obj->tlsalign);
4215 * If we have already fixed the size of the static TLS block, we
4216 * must stay within that size. When allocating the static TLS, we
4217 * leave a small amount of space spare to be used for dynamically
4218 * loading modules which use static TLS.
4220 if (tls_static_space) {
4221 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
4225 tls_last_offset = obj->tlsoffset = off;
4226 tls_last_size = obj->tlssize;
4227 obj->tls_done = true;
4233 free_tls_offset(Obj_Entry *obj)
4237 * If we were the last thing to allocate out of the static TLS
4238 * block, we give our space back to the 'allocator'. This is a
4239 * simplistic workaround to allow libGL.so.1 to be loaded and
4240 * unloaded multiple times.
4242 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
4243 == calculate_tls_end(tls_last_offset, tls_last_size)) {
4244 tls_last_offset -= obj->tlssize;
4250 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
4253 RtldLockState lockstate;
4255 wlock_acquire(rtld_bind_lock, &lockstate);
4256 ret = allocate_tls(obj_list, oldtls, tcbsize, tcbalign);
4257 lock_release(rtld_bind_lock, &lockstate);
4262 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
4264 RtldLockState lockstate;
4266 wlock_acquire(rtld_bind_lock, &lockstate);
4267 free_tls(tcb, tcbsize, tcbalign);
4268 lock_release(rtld_bind_lock, &lockstate);
4272 object_add_name(Obj_Entry *obj, const char *name)
4278 entry = malloc(sizeof(Name_Entry) + len);
4280 if (entry != NULL) {
4281 strcpy(entry->name, name);
4282 STAILQ_INSERT_TAIL(&obj->names, entry, link);
4287 object_match_name(const Obj_Entry *obj, const char *name)
4291 STAILQ_FOREACH(entry, &obj->names, link) {
4292 if (strcmp(name, entry->name) == 0)
4299 locate_dependency(const Obj_Entry *obj, const char *name)
4301 const Objlist_Entry *entry;
4302 const Needed_Entry *needed;
4304 STAILQ_FOREACH(entry, &list_main, link) {
4305 if (object_match_name(entry->obj, name))
4309 for (needed = obj->needed; needed != NULL; needed = needed->next) {
4310 if (strcmp(obj->strtab + needed->name, name) == 0 ||
4311 (needed->obj != NULL && object_match_name(needed->obj, name))) {
4313 * If there is DT_NEEDED for the name we are looking for,
4314 * we are all set. Note that object might not be found if
4315 * dependency was not loaded yet, so the function can
4316 * return NULL here. This is expected and handled
4317 * properly by the caller.
4319 return (needed->obj);
4322 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
4328 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
4329 const Elf_Vernaux *vna)
4331 const Elf_Verdef *vd;
4332 const char *vername;
4334 vername = refobj->strtab + vna->vna_name;
4335 vd = depobj->verdef;
4337 _rtld_error("%s: version %s required by %s not defined",
4338 depobj->path, vername, refobj->path);
4342 if (vd->vd_version != VER_DEF_CURRENT) {
4343 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
4344 depobj->path, vd->vd_version);
4347 if (vna->vna_hash == vd->vd_hash) {
4348 const Elf_Verdaux *aux = (const Elf_Verdaux *)
4349 ((char *)vd + vd->vd_aux);
4350 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
4353 if (vd->vd_next == 0)
4355 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4357 if (vna->vna_flags & VER_FLG_WEAK)
4359 _rtld_error("%s: version %s required by %s not found",
4360 depobj->path, vername, refobj->path);
4365 rtld_verify_object_versions(Obj_Entry *obj)
4367 const Elf_Verneed *vn;
4368 const Elf_Verdef *vd;
4369 const Elf_Verdaux *vda;
4370 const Elf_Vernaux *vna;
4371 const Obj_Entry *depobj;
4372 int maxvernum, vernum;
4374 if (obj->ver_checked)
4376 obj->ver_checked = true;
4380 * Walk over defined and required version records and figure out
4381 * max index used by any of them. Do very basic sanity checking
4385 while (vn != NULL) {
4386 if (vn->vn_version != VER_NEED_CURRENT) {
4387 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
4388 obj->path, vn->vn_version);
4391 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4393 vernum = VER_NEED_IDX(vna->vna_other);
4394 if (vernum > maxvernum)
4396 if (vna->vna_next == 0)
4398 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4400 if (vn->vn_next == 0)
4402 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4406 while (vd != NULL) {
4407 if (vd->vd_version != VER_DEF_CURRENT) {
4408 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
4409 obj->path, vd->vd_version);
4412 vernum = VER_DEF_IDX(vd->vd_ndx);
4413 if (vernum > maxvernum)
4415 if (vd->vd_next == 0)
4417 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4424 * Store version information in array indexable by version index.
4425 * Verify that object version requirements are satisfied along the
4428 obj->vernum = maxvernum + 1;
4429 obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry));
4432 while (vd != NULL) {
4433 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
4434 vernum = VER_DEF_IDX(vd->vd_ndx);
4435 assert(vernum <= maxvernum);
4436 vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
4437 obj->vertab[vernum].hash = vd->vd_hash;
4438 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
4439 obj->vertab[vernum].file = NULL;
4440 obj->vertab[vernum].flags = 0;
4442 if (vd->vd_next == 0)
4444 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4448 while (vn != NULL) {
4449 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
4452 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4454 if (check_object_provided_version(obj, depobj, vna))
4456 vernum = VER_NEED_IDX(vna->vna_other);
4457 assert(vernum <= maxvernum);
4458 obj->vertab[vernum].hash = vna->vna_hash;
4459 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
4460 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
4461 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
4462 VER_INFO_HIDDEN : 0;
4463 if (vna->vna_next == 0)
4465 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4467 if (vn->vn_next == 0)
4469 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4475 rtld_verify_versions(const Objlist *objlist)
4477 Objlist_Entry *entry;
4481 STAILQ_FOREACH(entry, objlist, link) {
4483 * Skip dummy objects or objects that have their version requirements
4486 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
4488 if (rtld_verify_object_versions(entry->obj) == -1) {
4490 if (ld_tracing == NULL)
4494 if (rc == 0 || ld_tracing != NULL)
4495 rc = rtld_verify_object_versions(&obj_rtld);
4500 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
4505 vernum = VER_NDX(obj->versyms[symnum]);
4506 if (vernum >= obj->vernum) {
4507 _rtld_error("%s: symbol %s has wrong verneed value %d",
4508 obj->path, obj->strtab + symnum, vernum);
4509 } else if (obj->vertab[vernum].hash != 0) {
4510 return &obj->vertab[vernum];
4517 _rtld_get_stack_prot(void)
4520 return (stack_prot);
4524 map_stacks_exec(RtldLockState *lockstate)
4526 void (*thr_map_stacks_exec)(void);
4528 if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
4530 thr_map_stacks_exec = (void (*)(void))(uintptr_t)
4531 get_program_var_addr("__pthread_map_stacks_exec", lockstate);
4532 if (thr_map_stacks_exec != NULL) {
4533 stack_prot |= PROT_EXEC;
4534 thr_map_stacks_exec();
4539 symlook_init(SymLook *dst, const char *name)
4542 bzero(dst, sizeof(*dst));
4544 dst->hash = elf_hash(name);
4545 dst->hash_gnu = gnu_hash(name);
4549 symlook_init_from_req(SymLook *dst, const SymLook *src)
4552 dst->name = src->name;
4553 dst->hash = src->hash;
4554 dst->hash_gnu = src->hash_gnu;
4555 dst->ventry = src->ventry;
4556 dst->flags = src->flags;
4557 dst->defobj_out = NULL;
4558 dst->sym_out = NULL;
4559 dst->lockstate = src->lockstate;
4563 * Overrides for libc_pic-provided functions.
4567 __getosreldate(void)
4577 oid[1] = KERN_OSRELDATE;
4579 len = sizeof(osrel);
4580 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
4581 if (error == 0 && osrel > 0 && len == sizeof(osrel))
4593 void (*__cleanup)(void);
4594 int __isthreaded = 0;
4595 int _thread_autoinit_dummy_decl = 1;
4598 * No unresolved symbols for rtld.
4601 __pthread_cxa_finalize(struct dl_phdr_info *a)
4606 __stack_chk_fail(void)
4609 _rtld_error("stack overflow detected; terminated");
4612 __weak_reference(__stack_chk_fail, __stack_chk_fail_local);
4618 _rtld_error("buffer overflow detected; terminated");
4623 rtld_strerror(int errnum)
4626 if (errnum < 0 || errnum >= sys_nerr)
4627 return ("Unknown error");
4628 return (sys_errlist[errnum]);