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_objects(Obj_Entry *, bool, Obj_Entry *, int,
122 static int resolve_objects_ifunc(Obj_Entry *first, bool bind_now,
123 int flags, RtldLockState *lockstate);
124 static int rtld_dirname(const char *, char *);
125 static int rtld_dirname_abs(const char *, char *);
126 static void *rtld_dlopen(const char *name, int fd, int mode);
127 static void rtld_exit(void);
128 static char *search_library_path(const char *, const char *);
129 static const void **get_program_var_addr(const char *, RtldLockState *);
130 static void set_program_var(const char *, const void *);
131 static int symlook_default(SymLook *, const Obj_Entry *refobj);
132 static int symlook_global(SymLook *, DoneList *);
133 static void symlook_init_from_req(SymLook *, const SymLook *);
134 static int symlook_list(SymLook *, const Objlist *, DoneList *);
135 static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *);
136 static int symlook_obj1_sysv(SymLook *, const Obj_Entry *);
137 static int symlook_obj1_gnu(SymLook *, const Obj_Entry *);
138 static void trace_loaded_objects(Obj_Entry *);
139 static void unlink_object(Obj_Entry *);
140 static void unload_object(Obj_Entry *);
141 static void unref_dag(Obj_Entry *);
142 static void ref_dag(Obj_Entry *);
143 static int origin_subst_one(char **, const char *, const char *,
144 const char *, char *);
145 static char *origin_subst(const char *, const char *);
146 static void preinit_main(void);
147 static int rtld_verify_versions(const Objlist *);
148 static int rtld_verify_object_versions(Obj_Entry *);
149 static void object_add_name(Obj_Entry *, const char *);
150 static int object_match_name(const Obj_Entry *, const char *);
151 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
152 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
153 struct dl_phdr_info *phdr_info);
154 static uint32_t gnu_hash(const char *);
155 static bool matched_symbol(SymLook *, const Obj_Entry *, Sym_Match_Result *,
156 const unsigned long);
158 void r_debug_state(struct r_debug *, struct link_map *) __noinline;
163 static char *error_message; /* Message for dlerror(), or NULL */
164 struct r_debug r_debug; /* for GDB; */
165 static bool libmap_disable; /* Disable libmap */
166 static bool ld_loadfltr; /* Immediate filters processing */
167 static char *libmap_override; /* Maps to use in addition to libmap.conf */
168 static bool trust; /* False for setuid and setgid programs */
169 static bool dangerous_ld_env; /* True if environment variables have been
170 used to affect the libraries loaded */
171 static char *ld_bind_now; /* Environment variable for immediate binding */
172 static char *ld_debug; /* Environment variable for debugging */
173 static char *ld_library_path; /* Environment variable for search path */
174 static char *ld_preload; /* Environment variable for libraries to
176 static char *ld_elf_hints_path; /* Environment variable for alternative hints path */
177 static char *ld_tracing; /* Called from ldd to print libs */
178 static char *ld_utrace; /* Use utrace() to log events. */
179 static Obj_Entry *obj_list; /* Head of linked list of shared objects */
180 static Obj_Entry **obj_tail; /* Link field of last object in list */
181 static Obj_Entry *obj_main; /* The main program shared object */
182 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
183 static unsigned int obj_count; /* Number of objects in obj_list */
184 static unsigned int obj_loads; /* Number of objects in obj_list */
186 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
187 STAILQ_HEAD_INITIALIZER(list_global);
188 static Objlist list_main = /* Objects loaded at program startup */
189 STAILQ_HEAD_INITIALIZER(list_main);
190 static Objlist list_fini = /* Objects needing fini() calls */
191 STAILQ_HEAD_INITIALIZER(list_fini);
193 Elf_Sym sym_zero; /* For resolving undefined weak refs. */
195 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
197 extern Elf_Dyn _DYNAMIC;
198 #pragma weak _DYNAMIC
199 #ifndef RTLD_IS_DYNAMIC
200 #define RTLD_IS_DYNAMIC() (&_DYNAMIC != NULL)
203 int osreldate, pagesize;
205 long __stack_chk_guard[8] = {0, 0, 0, 0, 0, 0, 0, 0};
207 static int stack_prot = PROT_READ | PROT_WRITE | RTLD_DEFAULT_STACK_EXEC;
208 static int max_stack_flags;
211 * Global declarations normally provided by crt1. The dynamic linker is
212 * not built with crt1, so we have to provide them ourselves.
218 * Used to pass argc, argv to init functions.
224 * Globals to control TLS allocation.
226 size_t tls_last_offset; /* Static TLS offset of last module */
227 size_t tls_last_size; /* Static TLS size of last module */
228 size_t tls_static_space; /* Static TLS space allocated */
229 int tls_dtv_generation = 1; /* Used to detect when dtv size changes */
230 int tls_max_index = 1; /* Largest module index allocated */
233 * Fill in a DoneList with an allocation large enough to hold all of
234 * the currently-loaded objects. Keep this as a macro since it calls
235 * alloca and we want that to occur within the scope of the caller.
237 #define donelist_init(dlp) \
238 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
239 assert((dlp)->objs != NULL), \
240 (dlp)->num_alloc = obj_count, \
243 #define UTRACE_DLOPEN_START 1
244 #define UTRACE_DLOPEN_STOP 2
245 #define UTRACE_DLCLOSE_START 3
246 #define UTRACE_DLCLOSE_STOP 4
247 #define UTRACE_LOAD_OBJECT 5
248 #define UTRACE_UNLOAD_OBJECT 6
249 #define UTRACE_ADD_RUNDEP 7
250 #define UTRACE_PRELOAD_FINISHED 8
251 #define UTRACE_INIT_CALL 9
252 #define UTRACE_FINI_CALL 10
255 char sig[4]; /* 'RTLD' */
258 void *mapbase; /* Used for 'parent' and 'init/fini' */
260 int refcnt; /* Used for 'mode' */
261 char name[MAXPATHLEN];
264 #define LD_UTRACE(e, h, mb, ms, r, n) do { \
265 if (ld_utrace != NULL) \
266 ld_utrace_log(e, h, mb, ms, r, n); \
270 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
271 int refcnt, const char *name)
273 struct utrace_rtld ut;
281 ut.mapbase = mapbase;
282 ut.mapsize = mapsize;
284 bzero(ut.name, sizeof(ut.name));
286 strlcpy(ut.name, name, sizeof(ut.name));
287 utrace(&ut, sizeof(ut));
291 * Main entry point for dynamic linking. The first argument is the
292 * stack pointer. The stack is expected to be laid out as described
293 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
294 * Specifically, the stack pointer points to a word containing
295 * ARGC. Following that in the stack is a null-terminated sequence
296 * of pointers to argument strings. Then comes a null-terminated
297 * sequence of pointers to environment strings. Finally, there is a
298 * sequence of "auxiliary vector" entries.
300 * The second argument points to a place to store the dynamic linker's
301 * exit procedure pointer and the third to a place to store the main
304 * The return value is the main program's entry point.
307 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
309 Elf_Auxinfo *aux_info[AT_COUNT];
317 Objlist_Entry *entry;
319 Obj_Entry **preload_tail;
321 RtldLockState lockstate;
326 * On entry, the dynamic linker itself has not been relocated yet.
327 * Be very careful not to reference any global data until after
328 * init_rtld has returned. It is OK to reference file-scope statics
329 * and string constants, and to call static and global functions.
332 /* Find the auxiliary vector on the stack. */
335 sp += argc + 1; /* Skip over arguments and NULL terminator */
337 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
339 aux = (Elf_Auxinfo *) sp;
341 /* Digest the auxiliary vector. */
342 for (i = 0; i < AT_COUNT; i++)
344 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
345 if (auxp->a_type < AT_COUNT)
346 aux_info[auxp->a_type] = auxp;
349 /* Initialize and relocate ourselves. */
350 assert(aux_info[AT_BASE] != NULL);
351 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
353 __progname = obj_rtld.path;
354 argv0 = argv[0] != NULL ? argv[0] : "(null)";
359 if (aux_info[AT_CANARY] != NULL &&
360 aux_info[AT_CANARY]->a_un.a_ptr != NULL) {
361 i = aux_info[AT_CANARYLEN]->a_un.a_val;
362 if (i > sizeof(__stack_chk_guard))
363 i = sizeof(__stack_chk_guard);
364 memcpy(__stack_chk_guard, aux_info[AT_CANARY]->a_un.a_ptr, i);
369 len = sizeof(__stack_chk_guard);
370 if (sysctl(mib, 2, __stack_chk_guard, &len, NULL, 0) == -1 ||
371 len != sizeof(__stack_chk_guard)) {
372 /* If sysctl was unsuccessful, use the "terminator canary". */
373 ((unsigned char *)(void *)__stack_chk_guard)[0] = 0;
374 ((unsigned char *)(void *)__stack_chk_guard)[1] = 0;
375 ((unsigned char *)(void *)__stack_chk_guard)[2] = '\n';
376 ((unsigned char *)(void *)__stack_chk_guard)[3] = 255;
380 trust = !issetugid();
382 ld_bind_now = getenv(LD_ "BIND_NOW");
384 * If the process is tainted, then we un-set the dangerous environment
385 * variables. The process will be marked as tainted until setuid(2)
386 * is called. If any child process calls setuid(2) we do not want any
387 * future processes to honor the potentially un-safe variables.
390 if (unsetenv(LD_ "PRELOAD") || unsetenv(LD_ "LIBMAP") ||
391 unsetenv(LD_ "LIBRARY_PATH") || unsetenv(LD_ "LIBMAP_DISABLE") ||
392 unsetenv(LD_ "DEBUG") || unsetenv(LD_ "ELF_HINTS_PATH") ||
393 unsetenv(LD_ "LOADFLTR")) {
394 _rtld_error("environment corrupt; aborting");
398 ld_debug = getenv(LD_ "DEBUG");
399 libmap_disable = getenv(LD_ "LIBMAP_DISABLE") != NULL;
400 libmap_override = getenv(LD_ "LIBMAP");
401 ld_library_path = getenv(LD_ "LIBRARY_PATH");
402 ld_preload = getenv(LD_ "PRELOAD");
403 ld_elf_hints_path = getenv(LD_ "ELF_HINTS_PATH");
404 ld_loadfltr = getenv(LD_ "LOADFLTR") != NULL;
405 dangerous_ld_env = libmap_disable || (libmap_override != NULL) ||
406 (ld_library_path != NULL) || (ld_preload != NULL) ||
407 (ld_elf_hints_path != NULL) || ld_loadfltr;
408 ld_tracing = getenv(LD_ "TRACE_LOADED_OBJECTS");
409 ld_utrace = getenv(LD_ "UTRACE");
411 if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0)
412 ld_elf_hints_path = _PATH_ELF_HINTS;
414 if (ld_debug != NULL && *ld_debug != '\0')
416 dbg("%s is initialized, base address = %p", __progname,
417 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
418 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
419 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
421 dbg("initializing thread locks");
425 * Load the main program, or process its program header if it is
428 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
429 int fd = aux_info[AT_EXECFD]->a_un.a_val;
430 dbg("loading main program");
431 obj_main = map_object(fd, argv0, NULL);
433 if (obj_main == NULL)
435 max_stack_flags = obj->stack_flags;
436 } else { /* Main program already loaded. */
437 const Elf_Phdr *phdr;
441 dbg("processing main program's program header");
442 assert(aux_info[AT_PHDR] != NULL);
443 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
444 assert(aux_info[AT_PHNUM] != NULL);
445 phnum = aux_info[AT_PHNUM]->a_un.a_val;
446 assert(aux_info[AT_PHENT] != NULL);
447 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
448 assert(aux_info[AT_ENTRY] != NULL);
449 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
450 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
454 if (aux_info[AT_EXECPATH] != 0) {
456 char buf[MAXPATHLEN];
458 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
459 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
460 if (kexecpath[0] == '/')
461 obj_main->path = kexecpath;
462 else if (getcwd(buf, sizeof(buf)) == NULL ||
463 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
464 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
465 obj_main->path = xstrdup(argv0);
467 obj_main->path = xstrdup(buf);
469 dbg("No AT_EXECPATH");
470 obj_main->path = xstrdup(argv0);
472 dbg("obj_main path %s", obj_main->path);
473 obj_main->mainprog = true;
475 if (aux_info[AT_STACKPROT] != NULL &&
476 aux_info[AT_STACKPROT]->a_un.a_val != 0)
477 stack_prot = aux_info[AT_STACKPROT]->a_un.a_val;
480 * Get the actual dynamic linker pathname from the executable if
481 * possible. (It should always be possible.) That ensures that
482 * gdb will find the right dynamic linker even if a non-standard
485 if (obj_main->interp != NULL &&
486 strcmp(obj_main->interp, obj_rtld.path) != 0) {
488 obj_rtld.path = xstrdup(obj_main->interp);
489 __progname = obj_rtld.path;
492 digest_dynamic(obj_main, 0);
493 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d",
494 obj_main->path, obj_main->valid_hash_sysv, obj_main->valid_hash_gnu,
495 obj_main->dynsymcount);
497 linkmap_add(obj_main);
498 linkmap_add(&obj_rtld);
500 /* Link the main program into the list of objects. */
501 *obj_tail = obj_main;
502 obj_tail = &obj_main->next;
506 /* Initialize a fake symbol for resolving undefined weak references. */
507 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
508 sym_zero.st_shndx = SHN_UNDEF;
509 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
512 libmap_disable = (bool)lm_init(libmap_override);
514 dbg("loading LD_PRELOAD libraries");
515 if (load_preload_objects() == -1)
517 preload_tail = obj_tail;
519 dbg("loading needed objects");
520 if (load_needed_objects(obj_main, 0) == -1)
523 /* Make a list of all objects loaded at startup. */
524 for (obj = obj_list; obj != NULL; obj = obj->next) {
525 objlist_push_tail(&list_main, obj);
529 dbg("checking for required versions");
530 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
533 if (ld_tracing) { /* We're done */
534 trace_loaded_objects(obj_main);
538 if (getenv(LD_ "DUMP_REL_PRE") != NULL) {
539 dump_relocations(obj_main);
544 * Processing tls relocations requires having the tls offsets
545 * initialized. Prepare offsets before starting initial
546 * relocation processing.
548 dbg("initializing initial thread local storage offsets");
549 STAILQ_FOREACH(entry, &list_main, link) {
551 * Allocate all the initial objects out of the static TLS
552 * block even if they didn't ask for it.
554 allocate_tls_offset(entry->obj);
557 if (relocate_objects(obj_main,
558 ld_bind_now != NULL && *ld_bind_now != '\0',
559 &obj_rtld, SYMLOOK_EARLY, NULL) == -1)
562 dbg("doing copy relocations");
563 if (do_copy_relocations(obj_main) == -1)
566 if (getenv(LD_ "DUMP_REL_POST") != NULL) {
567 dump_relocations(obj_main);
572 * Setup TLS for main thread. This must be done after the
573 * relocations are processed, since tls initialization section
574 * might be the subject for relocations.
576 dbg("initializing initial thread local storage");
577 allocate_initial_tls(obj_list);
579 dbg("initializing key program variables");
580 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
581 set_program_var("environ", env);
582 set_program_var("__elf_aux_vector", aux);
584 /* Make a list of init functions to call. */
585 objlist_init(&initlist);
586 initlist_add_objects(obj_list, preload_tail, &initlist);
588 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
590 map_stacks_exec(NULL);
592 dbg("resolving ifuncs");
593 if (resolve_objects_ifunc(obj_main,
594 ld_bind_now != NULL && *ld_bind_now != '\0', SYMLOOK_EARLY,
598 if (!obj_main->crt_no_init) {
600 * Make sure we don't call the main program's init and fini
601 * functions for binaries linked with old crt1 which calls
604 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
605 obj_main->preinit_array = obj_main->init_array =
606 obj_main->fini_array = (Elf_Addr)NULL;
609 wlock_acquire(rtld_bind_lock, &lockstate);
610 if (obj_main->crt_no_init)
612 objlist_call_init(&initlist, &lockstate);
613 objlist_clear(&initlist);
614 dbg("loading filtees");
615 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
616 if (ld_loadfltr || obj->z_loadfltr)
617 load_filtees(obj, 0, &lockstate);
619 lock_release(rtld_bind_lock, &lockstate);
621 dbg("transferring control to program entry point = %p", obj_main->entry);
623 /* Return the exit procedure and the program entry point. */
624 *exit_proc = rtld_exit;
626 return (func_ptr_type) obj_main->entry;
630 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def)
635 ptr = (void *)make_function_pointer(def, obj);
636 target = ((Elf_Addr (*)(void))ptr)();
637 return ((void *)target);
641 _rtld_bind(Obj_Entry *obj, Elf_Size reloff)
645 const Obj_Entry *defobj;
648 RtldLockState lockstate;
650 rlock_acquire(rtld_bind_lock, &lockstate);
651 if (sigsetjmp(lockstate.env, 0) != 0)
652 lock_upgrade(rtld_bind_lock, &lockstate);
654 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
656 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
658 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
659 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL,
663 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
664 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
666 target = (Elf_Addr)(defobj->relocbase + def->st_value);
668 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
669 defobj->strtab + def->st_name, basename(obj->path),
670 (void *)target, basename(defobj->path));
673 * Write the new contents for the jmpslot. Note that depending on
674 * architecture, the value which we need to return back to the
675 * lazy binding trampoline may or may not be the target
676 * address. The value returned from reloc_jmpslot() is the value
677 * that the trampoline needs.
679 target = reloc_jmpslot(where, target, defobj, obj, rel);
680 lock_release(rtld_bind_lock, &lockstate);
685 * Error reporting function. Use it like printf. If formats the message
686 * into a buffer, and sets things up so that the next call to dlerror()
687 * will return the message.
690 _rtld_error(const char *fmt, ...)
692 static char buf[512];
696 rtld_vsnprintf(buf, sizeof buf, fmt, ap);
702 * Return a dynamically-allocated copy of the current error message, if any.
707 return error_message == NULL ? NULL : xstrdup(error_message);
711 * Restore the current error message from a copy which was previously saved
712 * by errmsg_save(). The copy is freed.
715 errmsg_restore(char *saved_msg)
717 if (saved_msg == NULL)
718 error_message = NULL;
720 _rtld_error("%s", saved_msg);
726 basename(const char *name)
728 const char *p = strrchr(name, '/');
729 return p != NULL ? p + 1 : name;
732 static struct utsname uts;
735 origin_subst_one(char **res, const char *real, const char *kw, const char *subst,
745 subst_len = kw_len = 0;
749 if (subst_len == 0) {
750 subst_len = strlen(subst);
754 *res = xmalloc(PATH_MAX);
757 if ((res1 - *res) + subst_len + (p1 - p) >= PATH_MAX) {
758 _rtld_error("Substitution of %s in %s cannot be performed",
760 if (may_free != NULL)
765 memcpy(res1, p, p1 - p);
767 memcpy(res1, subst, subst_len);
772 if (may_free != NULL)
775 *res = xstrdup(real);
779 if (may_free != NULL)
781 if (strlcat(res1, p, PATH_MAX - (res1 - *res)) >= PATH_MAX) {
791 origin_subst(const char *real, const char *origin_path)
793 char *res1, *res2, *res3, *res4;
795 if (uts.sysname[0] == '\0') {
796 if (uname(&uts) != 0) {
797 _rtld_error("utsname failed: %d", errno);
801 if (!origin_subst_one(&res1, real, "$ORIGIN", origin_path, NULL) ||
802 !origin_subst_one(&res2, res1, "$OSNAME", uts.sysname, res1) ||
803 !origin_subst_one(&res3, res2, "$OSREL", uts.release, res2) ||
804 !origin_subst_one(&res4, res3, "$PLATFORM", uts.machine, res3))
812 const char *msg = dlerror();
816 rtld_fdputstr(STDERR_FILENO, msg);
817 rtld_fdputchar(STDERR_FILENO, '\n');
822 * Process a shared object's DYNAMIC section, and save the important
823 * information in its Obj_Entry structure.
826 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
827 const Elf_Dyn **dyn_soname)
830 Needed_Entry **needed_tail = &obj->needed;
831 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
832 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
833 const Elf_Hashelt *hashtab;
834 const Elf32_Word *hashval;
835 Elf32_Word bkt, nmaskwords;
838 int plttype = DT_REL;
843 obj->bind_now = false;
844 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
845 switch (dynp->d_tag) {
848 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
852 obj->relsize = dynp->d_un.d_val;
856 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
860 obj->pltrel = (const Elf_Rel *)
861 (obj->relocbase + dynp->d_un.d_ptr);
865 obj->pltrelsize = dynp->d_un.d_val;
869 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
873 obj->relasize = dynp->d_un.d_val;
877 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
881 plttype = dynp->d_un.d_val;
882 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
886 obj->symtab = (const Elf_Sym *)
887 (obj->relocbase + dynp->d_un.d_ptr);
891 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
895 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
899 obj->strsize = dynp->d_un.d_val;
903 obj->verneed = (const Elf_Verneed *) (obj->relocbase +
908 obj->verneednum = dynp->d_un.d_val;
912 obj->verdef = (const Elf_Verdef *) (obj->relocbase +
917 obj->verdefnum = dynp->d_un.d_val;
921 obj->versyms = (const Elf_Versym *)(obj->relocbase +
927 hashtab = (const Elf_Hashelt *)(obj->relocbase +
929 obj->nbuckets = hashtab[0];
930 obj->nchains = hashtab[1];
931 obj->buckets = hashtab + 2;
932 obj->chains = obj->buckets + obj->nbuckets;
933 obj->valid_hash_sysv = obj->nbuckets > 0 && obj->nchains > 0 &&
934 obj->buckets != NULL;
940 hashtab = (const Elf_Hashelt *)(obj->relocbase +
942 obj->nbuckets_gnu = hashtab[0];
943 obj->symndx_gnu = hashtab[1];
944 nmaskwords = hashtab[2];
945 bloom_size32 = (__ELF_WORD_SIZE / 32) * nmaskwords;
946 /* Number of bitmask words is required to be power of 2 */
947 nmw_power2 = ((nmaskwords & (nmaskwords - 1)) == 0);
948 obj->maskwords_bm_gnu = nmaskwords - 1;
949 obj->shift2_gnu = hashtab[3];
950 obj->bloom_gnu = (Elf_Addr *) (hashtab + 4);
951 obj->buckets_gnu = hashtab + 4 + bloom_size32;
952 obj->chain_zero_gnu = obj->buckets_gnu + obj->nbuckets_gnu -
954 obj->valid_hash_gnu = nmw_power2 && obj->nbuckets_gnu > 0 &&
955 obj->buckets_gnu != NULL;
961 Needed_Entry *nep = NEW(Needed_Entry);
962 nep->name = dynp->d_un.d_val;
967 needed_tail = &nep->next;
973 Needed_Entry *nep = NEW(Needed_Entry);
974 nep->name = dynp->d_un.d_val;
978 *needed_filtees_tail = nep;
979 needed_filtees_tail = &nep->next;
985 Needed_Entry *nep = NEW(Needed_Entry);
986 nep->name = dynp->d_un.d_val;
990 *needed_aux_filtees_tail = nep;
991 needed_aux_filtees_tail = &nep->next;
996 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
1000 obj->textrel = true;
1004 obj->symbolic = true;
1008 case DT_RUNPATH: /* XXX: process separately */
1010 * We have to wait until later to process this, because we
1011 * might not have gotten the address of the string table yet.
1021 obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1024 case DT_PREINIT_ARRAY:
1025 obj->preinit_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1028 case DT_PREINIT_ARRAYSZ:
1029 obj->preinit_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1033 obj->init_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1036 case DT_INIT_ARRAYSZ:
1037 obj->init_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1041 obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1045 obj->fini_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1048 case DT_FINI_ARRAYSZ:
1049 obj->fini_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1053 * Don't process DT_DEBUG on MIPS as the dynamic section
1054 * is mapped read-only. DT_MIPS_RLD_MAP is used instead.
1059 /* XXX - not implemented yet */
1061 dbg("Filling in DT_DEBUG entry");
1062 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
1067 if ((dynp->d_un.d_val & DF_ORIGIN) && trust)
1068 obj->z_origin = true;
1069 if (dynp->d_un.d_val & DF_SYMBOLIC)
1070 obj->symbolic = true;
1071 if (dynp->d_un.d_val & DF_TEXTREL)
1072 obj->textrel = true;
1073 if (dynp->d_un.d_val & DF_BIND_NOW)
1074 obj->bind_now = true;
1075 /*if (dynp->d_un.d_val & DF_STATIC_TLS)
1079 case DT_MIPS_LOCAL_GOTNO:
1080 obj->local_gotno = dynp->d_un.d_val;
1083 case DT_MIPS_SYMTABNO:
1084 obj->symtabno = dynp->d_un.d_val;
1087 case DT_MIPS_GOTSYM:
1088 obj->gotsym = dynp->d_un.d_val;
1091 case DT_MIPS_RLD_MAP:
1094 dbg("Filling in DT_DEBUG entry");
1095 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
1101 if (dynp->d_un.d_val & DF_1_NOOPEN)
1102 obj->z_noopen = true;
1103 if ((dynp->d_un.d_val & DF_1_ORIGIN) && trust)
1104 obj->z_origin = true;
1105 /*if (dynp->d_un.d_val & DF_1_GLOBAL)
1107 if (dynp->d_un.d_val & DF_1_BIND_NOW)
1108 obj->bind_now = true;
1109 if (dynp->d_un.d_val & DF_1_NODELETE)
1110 obj->z_nodelete = true;
1111 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1112 obj->z_loadfltr = true;
1117 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1124 obj->traced = false;
1126 if (plttype == DT_RELA) {
1127 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1129 obj->pltrelasize = obj->pltrelsize;
1130 obj->pltrelsize = 0;
1133 /* Determine size of dynsym table (equal to nchains of sysv hash) */
1134 if (obj->valid_hash_sysv)
1135 obj->dynsymcount = obj->nchains;
1136 else if (obj->valid_hash_gnu) {
1137 obj->dynsymcount = 0;
1138 for (bkt = 0; bkt < obj->nbuckets_gnu; bkt++) {
1139 if (obj->buckets_gnu[bkt] == 0)
1141 hashval = &obj->chain_zero_gnu[obj->buckets_gnu[bkt]];
1144 while ((*hashval++ & 1u) == 0);
1146 obj->dynsymcount += obj->symndx_gnu;
1151 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1152 const Elf_Dyn *dyn_soname)
1155 if (obj->z_origin && obj->origin_path == NULL) {
1156 obj->origin_path = xmalloc(PATH_MAX);
1157 if (rtld_dirname_abs(obj->path, obj->origin_path) == -1)
1161 if (dyn_rpath != NULL) {
1162 obj->rpath = (char *)obj->strtab + dyn_rpath->d_un.d_val;
1164 obj->rpath = origin_subst(obj->rpath, obj->origin_path);
1167 if (dyn_soname != NULL)
1168 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1172 digest_dynamic(Obj_Entry *obj, int early)
1174 const Elf_Dyn *dyn_rpath;
1175 const Elf_Dyn *dyn_soname;
1177 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname);
1178 digest_dynamic2(obj, dyn_rpath, dyn_soname);
1182 * Process a shared object's program header. This is used only for the
1183 * main program, when the kernel has already loaded the main program
1184 * into memory before calling the dynamic linker. It creates and
1185 * returns an Obj_Entry structure.
1188 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1191 const Elf_Phdr *phlimit = phdr + phnum;
1193 Elf_Addr note_start, note_end;
1197 for (ph = phdr; ph < phlimit; ph++) {
1198 if (ph->p_type != PT_PHDR)
1202 obj->phsize = ph->p_memsz;
1203 obj->relocbase = (caddr_t)phdr - ph->p_vaddr;
1207 obj->stack_flags = PF_X | PF_R | PF_W;
1209 for (ph = phdr; ph < phlimit; ph++) {
1210 switch (ph->p_type) {
1213 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1217 if (nsegs == 0) { /* First load segment */
1218 obj->vaddrbase = trunc_page(ph->p_vaddr);
1219 obj->mapbase = obj->vaddrbase + obj->relocbase;
1220 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
1222 } else { /* Last load segment */
1223 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1230 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1235 obj->tlssize = ph->p_memsz;
1236 obj->tlsalign = ph->p_align;
1237 obj->tlsinitsize = ph->p_filesz;
1238 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1242 obj->stack_flags = ph->p_flags;
1246 obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1247 obj->relro_size = round_page(ph->p_memsz);
1251 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
1252 note_end = note_start + ph->p_filesz;
1253 digest_notes(obj, note_start, note_end);
1258 _rtld_error("%s: too few PT_LOAD segments", path);
1267 digest_notes(Obj_Entry *obj, Elf_Addr note_start, Elf_Addr note_end)
1269 const Elf_Note *note;
1270 const char *note_name;
1273 for (note = (const Elf_Note *)note_start; (Elf_Addr)note < note_end;
1274 note = (const Elf_Note *)((const char *)(note + 1) +
1275 roundup2(note->n_namesz, sizeof(Elf32_Addr)) +
1276 roundup2(note->n_descsz, sizeof(Elf32_Addr)))) {
1277 if (note->n_namesz != sizeof(NOTE_FREEBSD_VENDOR) ||
1278 note->n_descsz != sizeof(int32_t))
1280 if (note->n_type != ABI_NOTETYPE &&
1281 note->n_type != CRT_NOINIT_NOTETYPE)
1283 note_name = (const char *)(note + 1);
1284 if (strncmp(NOTE_FREEBSD_VENDOR, note_name,
1285 sizeof(NOTE_FREEBSD_VENDOR)) != 0)
1287 switch (note->n_type) {
1289 /* FreeBSD osrel note */
1290 p = (uintptr_t)(note + 1);
1291 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1292 obj->osrel = *(const int32_t *)(p);
1293 dbg("note osrel %d", obj->osrel);
1295 case CRT_NOINIT_NOTETYPE:
1296 /* FreeBSD 'crt does not call init' note */
1297 obj->crt_no_init = true;
1298 dbg("note crt_no_init");
1305 dlcheck(void *handle)
1309 for (obj = obj_list; obj != NULL; obj = obj->next)
1310 if (obj == (Obj_Entry *) handle)
1313 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1314 _rtld_error("Invalid shared object handle %p", handle);
1321 * If the given object is already in the donelist, return true. Otherwise
1322 * add the object to the list and return false.
1325 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1329 for (i = 0; i < dlp->num_used; i++)
1330 if (dlp->objs[i] == obj)
1333 * Our donelist allocation should always be sufficient. But if
1334 * our threads locking isn't working properly, more shared objects
1335 * could have been loaded since we allocated the list. That should
1336 * never happen, but we'll handle it properly just in case it does.
1338 if (dlp->num_used < dlp->num_alloc)
1339 dlp->objs[dlp->num_used++] = obj;
1344 * Hash function for symbol table lookup. Don't even think about changing
1345 * this. It is specified by the System V ABI.
1348 elf_hash(const char *name)
1350 const unsigned char *p = (const unsigned char *) name;
1351 unsigned long h = 0;
1354 while (*p != '\0') {
1355 h = (h << 4) + *p++;
1356 if ((g = h & 0xf0000000) != 0)
1364 * The GNU hash function is the Daniel J. Bernstein hash clipped to 32 bits
1365 * unsigned in case it's implemented with a wider type.
1368 gnu_hash(const char *s)
1374 for (c = *s; c != '\0'; c = *++s)
1376 return (h & 0xffffffff);
1380 * Find the library with the given name, and return its full pathname.
1381 * The returned string is dynamically allocated. Generates an error
1382 * message and returns NULL if the library cannot be found.
1384 * If the second argument is non-NULL, then it refers to an already-
1385 * loaded shared object, whose library search path will be searched.
1387 * The search order is:
1389 * rpath in the referencing file
1394 find_library(const char *xname, const Obj_Entry *refobj)
1399 if (strchr(xname, '/') != NULL) { /* Hard coded pathname */
1400 if (xname[0] != '/' && !trust) {
1401 _rtld_error("Absolute pathname required for shared object \"%s\"",
1405 if (refobj != NULL && refobj->z_origin)
1406 return origin_subst(xname, refobj->origin_path);
1408 return xstrdup(xname);
1411 if (libmap_disable || (refobj == NULL) ||
1412 (name = lm_find(refobj->path, xname)) == NULL)
1413 name = (char *)xname;
1415 dbg(" Searching for \"%s\"", name);
1417 if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
1419 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
1420 (pathname = search_library_path(name, gethints())) != NULL ||
1421 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
1424 if(refobj != NULL && refobj->path != NULL) {
1425 _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
1426 name, basename(refobj->path));
1428 _rtld_error("Shared object \"%s\" not found", name);
1434 * Given a symbol number in a referencing object, find the corresponding
1435 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1436 * no definition was found. Returns a pointer to the Obj_Entry of the
1437 * defining object via the reference parameter DEFOBJ_OUT.
1440 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1441 const Obj_Entry **defobj_out, int flags, SymCache *cache,
1442 RtldLockState *lockstate)
1446 const Obj_Entry *defobj;
1452 * If we have already found this symbol, get the information from
1455 if (symnum >= refobj->dynsymcount)
1456 return NULL; /* Bad object */
1457 if (cache != NULL && cache[symnum].sym != NULL) {
1458 *defobj_out = cache[symnum].obj;
1459 return cache[symnum].sym;
1462 ref = refobj->symtab + symnum;
1463 name = refobj->strtab + ref->st_name;
1468 * We don't have to do a full scale lookup if the symbol is local.
1469 * We know it will bind to the instance in this load module; to
1470 * which we already have a pointer (ie ref). By not doing a lookup,
1471 * we not only improve performance, but it also avoids unresolvable
1472 * symbols when local symbols are not in the hash table. This has
1473 * been seen with the ia64 toolchain.
1475 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1476 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1477 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1480 symlook_init(&req, name);
1482 req.ventry = fetch_ventry(refobj, symnum);
1483 req.lockstate = lockstate;
1484 res = symlook_default(&req, refobj);
1487 defobj = req.defobj_out;
1495 * If we found no definition and the reference is weak, treat the
1496 * symbol as having the value zero.
1498 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1504 *defobj_out = defobj;
1505 /* Record the information in the cache to avoid subsequent lookups. */
1506 if (cache != NULL) {
1507 cache[symnum].sym = def;
1508 cache[symnum].obj = defobj;
1511 if (refobj != &obj_rtld)
1512 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1518 * Return the search path from the ldconfig hints file, reading it if
1519 * necessary. Returns NULL if there are problems with the hints file,
1520 * or if the search path there is empty.
1527 if (hints == NULL) {
1529 struct elfhints_hdr hdr;
1532 /* Keep from trying again in case the hints file is bad. */
1535 if ((fd = open(ld_elf_hints_path, O_RDONLY)) == -1)
1537 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1538 hdr.magic != ELFHINTS_MAGIC ||
1543 p = xmalloc(hdr.dirlistlen + 1);
1544 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1545 read(fd, p, hdr.dirlistlen + 1) != (ssize_t)hdr.dirlistlen + 1) {
1553 return hints[0] != '\0' ? hints : NULL;
1557 init_dag(Obj_Entry *root)
1559 const Needed_Entry *needed;
1560 const Objlist_Entry *elm;
1563 if (root->dag_inited)
1565 donelist_init(&donelist);
1567 /* Root object belongs to own DAG. */
1568 objlist_push_tail(&root->dldags, root);
1569 objlist_push_tail(&root->dagmembers, root);
1570 donelist_check(&donelist, root);
1573 * Add dependencies of root object to DAG in breadth order
1574 * by exploiting the fact that each new object get added
1575 * to the tail of the dagmembers list.
1577 STAILQ_FOREACH(elm, &root->dagmembers, link) {
1578 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
1579 if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
1581 objlist_push_tail(&needed->obj->dldags, root);
1582 objlist_push_tail(&root->dagmembers, needed->obj);
1585 root->dag_inited = true;
1589 * Initialize the dynamic linker. The argument is the address at which
1590 * the dynamic linker has been mapped into memory. The primary task of
1591 * this function is to relocate the dynamic linker.
1594 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
1596 Obj_Entry objtmp; /* Temporary rtld object */
1597 const Elf_Dyn *dyn_rpath;
1598 const Elf_Dyn *dyn_soname;
1601 * Conjure up an Obj_Entry structure for the dynamic linker.
1603 * The "path" member can't be initialized yet because string constants
1604 * cannot yet be accessed. Below we will set it correctly.
1606 memset(&objtmp, 0, sizeof(objtmp));
1609 objtmp.mapbase = mapbase;
1611 objtmp.relocbase = mapbase;
1613 if (RTLD_IS_DYNAMIC()) {
1614 objtmp.dynamic = rtld_dynamic(&objtmp);
1615 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname);
1616 assert(objtmp.needed == NULL);
1617 #if !defined(__mips__)
1618 /* MIPS has a bogus DT_TEXTREL. */
1619 assert(!objtmp.textrel);
1623 * Temporarily put the dynamic linker entry into the object list, so
1624 * that symbols can be found.
1627 relocate_objects(&objtmp, true, &objtmp, 0, NULL);
1630 /* Initialize the object list. */
1631 obj_tail = &obj_list;
1633 /* Now that non-local variables can be accesses, copy out obj_rtld. */
1634 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1636 if (aux_info[AT_PAGESZ] != NULL)
1637 pagesize = aux_info[AT_PAGESZ]->a_un.a_val;
1638 if (aux_info[AT_OSRELDATE] != NULL)
1639 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
1641 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname);
1643 /* Replace the path with a dynamically allocated copy. */
1644 obj_rtld.path = xstrdup(PATH_RTLD);
1646 r_debug.r_brk = r_debug_state;
1647 r_debug.r_state = RT_CONSISTENT;
1651 * Add the init functions from a needed object list (and its recursive
1652 * needed objects) to "list". This is not used directly; it is a helper
1653 * function for initlist_add_objects(). The write lock must be held
1654 * when this function is called.
1657 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1659 /* Recursively process the successor needed objects. */
1660 if (needed->next != NULL)
1661 initlist_add_neededs(needed->next, list);
1663 /* Process the current needed object. */
1664 if (needed->obj != NULL)
1665 initlist_add_objects(needed->obj, &needed->obj->next, list);
1669 * Scan all of the DAGs rooted in the range of objects from "obj" to
1670 * "tail" and add their init functions to "list". This recurses over
1671 * the DAGs and ensure the proper init ordering such that each object's
1672 * needed libraries are initialized before the object itself. At the
1673 * same time, this function adds the objects to the global finalization
1674 * list "list_fini" in the opposite order. The write lock must be
1675 * held when this function is called.
1678 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1681 if (obj->init_scanned || obj->init_done)
1683 obj->init_scanned = true;
1685 /* Recursively process the successor objects. */
1686 if (&obj->next != tail)
1687 initlist_add_objects(obj->next, tail, list);
1689 /* Recursively process the needed objects. */
1690 if (obj->needed != NULL)
1691 initlist_add_neededs(obj->needed, list);
1692 if (obj->needed_filtees != NULL)
1693 initlist_add_neededs(obj->needed_filtees, list);
1694 if (obj->needed_aux_filtees != NULL)
1695 initlist_add_neededs(obj->needed_aux_filtees, list);
1697 /* Add the object to the init list. */
1698 if (obj->preinit_array != (Elf_Addr)NULL || obj->init != (Elf_Addr)NULL ||
1699 obj->init_array != (Elf_Addr)NULL)
1700 objlist_push_tail(list, obj);
1702 /* Add the object to the global fini list in the reverse order. */
1703 if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL)
1704 && !obj->on_fini_list) {
1705 objlist_push_head(&list_fini, obj);
1706 obj->on_fini_list = true;
1711 #define FPTR_TARGET(f) ((Elf_Addr) (f))
1715 free_needed_filtees(Needed_Entry *n)
1717 Needed_Entry *needed, *needed1;
1719 for (needed = n; needed != NULL; needed = needed->next) {
1720 if (needed->obj != NULL) {
1721 dlclose(needed->obj);
1725 for (needed = n; needed != NULL; needed = needed1) {
1726 needed1 = needed->next;
1732 unload_filtees(Obj_Entry *obj)
1735 free_needed_filtees(obj->needed_filtees);
1736 obj->needed_filtees = NULL;
1737 free_needed_filtees(obj->needed_aux_filtees);
1738 obj->needed_aux_filtees = NULL;
1739 obj->filtees_loaded = false;
1743 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags,
1744 RtldLockState *lockstate)
1747 for (; needed != NULL; needed = needed->next) {
1748 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
1749 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
1750 RTLD_LOCAL, lockstate);
1755 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
1758 lock_restart_for_upgrade(lockstate);
1759 if (!obj->filtees_loaded) {
1760 load_filtee1(obj, obj->needed_filtees, flags, lockstate);
1761 load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate);
1762 obj->filtees_loaded = true;
1767 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
1771 for (; needed != NULL; needed = needed->next) {
1772 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
1773 flags & ~RTLD_LO_NOLOAD);
1774 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
1776 if (obj1 != NULL && obj1->z_nodelete && !obj1->ref_nodel) {
1777 dbg("obj %s nodelete", obj1->path);
1780 obj1->ref_nodel = true;
1787 * Given a shared object, traverse its list of needed objects, and load
1788 * each of them. Returns 0 on success. Generates an error message and
1789 * returns -1 on failure.
1792 load_needed_objects(Obj_Entry *first, int flags)
1796 for (obj = first; obj != NULL; obj = obj->next) {
1797 if (process_needed(obj, obj->needed, flags) == -1)
1804 load_preload_objects(void)
1806 char *p = ld_preload;
1807 static const char delim[] = " \t:;";
1812 p += strspn(p, delim);
1813 while (*p != '\0') {
1814 size_t len = strcspn(p, delim);
1819 if (load_object(p, -1, NULL, 0) == NULL)
1820 return -1; /* XXX - cleanup */
1823 p += strspn(p, delim);
1825 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
1830 printable_path(const char *path)
1833 return (path == NULL ? "<unknown>" : path);
1837 * Load a shared object into memory, if it is not already loaded. The
1838 * object may be specified by name or by user-supplied file descriptor
1839 * fd_u. In the later case, the fd_u descriptor is not closed, but its
1842 * Returns a pointer to the Obj_Entry for the object. Returns NULL
1846 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
1854 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
1855 if (object_match_name(obj, name))
1859 path = find_library(name, refobj);
1866 * If we didn't find a match by pathname, or the name is not
1867 * supplied, open the file and check again by device and inode.
1868 * This avoids false mismatches caused by multiple links or ".."
1871 * To avoid a race, we open the file and use fstat() rather than
1876 if ((fd = open(path, O_RDONLY)) == -1) {
1877 _rtld_error("Cannot open \"%s\"", path);
1884 _rtld_error("Cannot dup fd");
1889 if (fstat(fd, &sb) == -1) {
1890 _rtld_error("Cannot fstat \"%s\"", printable_path(path));
1895 for (obj = obj_list->next; obj != NULL; obj = obj->next)
1896 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
1898 if (obj != NULL && name != NULL) {
1899 object_add_name(obj, name);
1904 if (flags & RTLD_LO_NOLOAD) {
1910 /* First use of this object, so we must map it in */
1911 obj = do_load_object(fd, name, path, &sb, flags);
1920 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
1927 * but first, make sure that environment variables haven't been
1928 * used to circumvent the noexec flag on a filesystem.
1930 if (dangerous_ld_env) {
1931 if (fstatfs(fd, &fs) != 0) {
1932 _rtld_error("Cannot fstatfs \"%s\"", printable_path(path));
1935 if (fs.f_flags & MNT_NOEXEC) {
1936 _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
1940 dbg("loading \"%s\"", printable_path(path));
1941 obj = map_object(fd, printable_path(path), sbp);
1946 * If DT_SONAME is present in the object, digest_dynamic2 already
1947 * added it to the object names.
1950 object_add_name(obj, name);
1952 digest_dynamic(obj, 0);
1953 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path,
1954 obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount);
1955 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
1957 dbg("refusing to load non-loadable \"%s\"", obj->path);
1958 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
1959 munmap(obj->mapbase, obj->mapsize);
1965 obj_tail = &obj->next;
1968 linkmap_add(obj); /* for GDB & dlinfo() */
1969 max_stack_flags |= obj->stack_flags;
1971 dbg(" %p .. %p: %s", obj->mapbase,
1972 obj->mapbase + obj->mapsize - 1, obj->path);
1974 dbg(" WARNING: %s has impure text", obj->path);
1975 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
1982 obj_from_addr(const void *addr)
1986 for (obj = obj_list; obj != NULL; obj = obj->next) {
1987 if (addr < (void *) obj->mapbase)
1989 if (addr < (void *) (obj->mapbase + obj->mapsize))
1998 Elf_Addr *preinit_addr;
2001 preinit_addr = (Elf_Addr *)obj_main->preinit_array;
2002 if (preinit_addr == NULL)
2005 for (index = 0; index < obj_main->preinit_array_num; index++) {
2006 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) {
2007 dbg("calling preinit function for %s at %p", obj_main->path,
2008 (void *)preinit_addr[index]);
2009 LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index],
2010 0, 0, obj_main->path);
2011 call_init_pointer(obj_main, preinit_addr[index]);
2017 * Call the finalization functions for each of the objects in "list"
2018 * belonging to the DAG of "root" and referenced once. If NULL "root"
2019 * is specified, every finalization function will be called regardless
2020 * of the reference count and the list elements won't be freed. All of
2021 * the objects are expected to have non-NULL fini functions.
2024 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
2028 Elf_Addr *fini_addr;
2031 assert(root == NULL || root->refcount == 1);
2034 * Preserve the current error message since a fini function might
2035 * call into the dynamic linker and overwrite it.
2037 saved_msg = errmsg_save();
2039 STAILQ_FOREACH(elm, list, link) {
2040 if (root != NULL && (elm->obj->refcount != 1 ||
2041 objlist_find(&root->dagmembers, elm->obj) == NULL))
2043 /* Remove object from fini list to prevent recursive invocation. */
2044 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2046 * XXX: If a dlopen() call references an object while the
2047 * fini function is in progress, we might end up trying to
2048 * unload the referenced object in dlclose() or the object
2049 * won't be unloaded although its fini function has been
2052 lock_release(rtld_bind_lock, lockstate);
2055 * It is legal to have both DT_FINI and DT_FINI_ARRAY defined.
2056 * When this happens, DT_FINI_ARRAY is processed first.
2058 fini_addr = (Elf_Addr *)elm->obj->fini_array;
2059 if (fini_addr != NULL && elm->obj->fini_array_num > 0) {
2060 for (index = elm->obj->fini_array_num - 1; index >= 0;
2062 if (fini_addr[index] != 0 && fini_addr[index] != 1) {
2063 dbg("calling fini function for %s at %p",
2064 elm->obj->path, (void *)fini_addr[index]);
2065 LD_UTRACE(UTRACE_FINI_CALL, elm->obj,
2066 (void *)fini_addr[index], 0, 0, elm->obj->path);
2067 call_initfini_pointer(elm->obj, fini_addr[index]);
2071 if (elm->obj->fini != (Elf_Addr)NULL) {
2072 dbg("calling fini function for %s at %p", elm->obj->path,
2073 (void *)elm->obj->fini);
2074 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini,
2075 0, 0, elm->obj->path);
2076 call_initfini_pointer(elm->obj, elm->obj->fini);
2078 wlock_acquire(rtld_bind_lock, lockstate);
2079 /* No need to free anything if process is going down. */
2083 * We must restart the list traversal after every fini call
2084 * because a dlclose() call from the fini function or from
2085 * another thread might have modified the reference counts.
2089 } while (elm != NULL);
2090 errmsg_restore(saved_msg);
2094 * Call the initialization functions for each of the objects in
2095 * "list". All of the objects are expected to have non-NULL init
2099 objlist_call_init(Objlist *list, RtldLockState *lockstate)
2104 Elf_Addr *init_addr;
2108 * Clean init_scanned flag so that objects can be rechecked and
2109 * possibly initialized earlier if any of vectors called below
2110 * cause the change by using dlopen.
2112 for (obj = obj_list; obj != NULL; obj = obj->next)
2113 obj->init_scanned = false;
2116 * Preserve the current error message since an init function might
2117 * call into the dynamic linker and overwrite it.
2119 saved_msg = errmsg_save();
2120 STAILQ_FOREACH(elm, list, link) {
2121 if (elm->obj->init_done) /* Initialized early. */
2124 * Race: other thread might try to use this object before current
2125 * one completes the initilization. Not much can be done here
2126 * without better locking.
2128 elm->obj->init_done = true;
2129 lock_release(rtld_bind_lock, lockstate);
2132 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined.
2133 * When this happens, DT_INIT is processed first.
2135 if (elm->obj->init != (Elf_Addr)NULL) {
2136 dbg("calling init function for %s at %p", elm->obj->path,
2137 (void *)elm->obj->init);
2138 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init,
2139 0, 0, elm->obj->path);
2140 call_initfini_pointer(elm->obj, elm->obj->init);
2142 init_addr = (Elf_Addr *)elm->obj->init_array;
2143 if (init_addr != NULL) {
2144 for (index = 0; index < elm->obj->init_array_num; index++) {
2145 if (init_addr[index] != 0 && init_addr[index] != 1) {
2146 dbg("calling init function for %s at %p", elm->obj->path,
2147 (void *)init_addr[index]);
2148 LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
2149 (void *)init_addr[index], 0, 0, elm->obj->path);
2150 call_init_pointer(elm->obj, init_addr[index]);
2154 wlock_acquire(rtld_bind_lock, lockstate);
2156 errmsg_restore(saved_msg);
2160 objlist_clear(Objlist *list)
2164 while (!STAILQ_EMPTY(list)) {
2165 elm = STAILQ_FIRST(list);
2166 STAILQ_REMOVE_HEAD(list, link);
2171 static Objlist_Entry *
2172 objlist_find(Objlist *list, const Obj_Entry *obj)
2176 STAILQ_FOREACH(elm, list, link)
2177 if (elm->obj == obj)
2183 objlist_init(Objlist *list)
2189 objlist_push_head(Objlist *list, Obj_Entry *obj)
2193 elm = NEW(Objlist_Entry);
2195 STAILQ_INSERT_HEAD(list, elm, link);
2199 objlist_push_tail(Objlist *list, Obj_Entry *obj)
2203 elm = NEW(Objlist_Entry);
2205 STAILQ_INSERT_TAIL(list, elm, link);
2209 objlist_remove(Objlist *list, Obj_Entry *obj)
2213 if ((elm = objlist_find(list, obj)) != NULL) {
2214 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2220 * Relocate newly-loaded shared objects. The argument is a pointer to
2221 * the Obj_Entry for the first such object. All objects from the first
2222 * to the end of the list of objects are relocated. Returns 0 on success,
2226 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
2227 int flags, RtldLockState *lockstate)
2231 for (obj = first; obj != NULL; obj = obj->next) {
2234 obj->relocated = true;
2236 dbg("relocating \"%s\"", obj->path);
2238 if (obj->symtab == NULL || obj->strtab == NULL ||
2239 !(obj->valid_hash_sysv || obj->valid_hash_gnu)) {
2240 _rtld_error("%s: Shared object has no run-time symbol table",
2246 /* There are relocations to the write-protected text segment. */
2247 if (mprotect(obj->mapbase, obj->textsize,
2248 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
2249 _rtld_error("%s: Cannot write-enable text segment: %s",
2250 obj->path, rtld_strerror(errno));
2255 /* Process the non-PLT relocations. */
2256 if (reloc_non_plt(obj, rtldobj, flags, lockstate))
2259 if (obj->textrel) { /* Re-protected the text segment. */
2260 if (mprotect(obj->mapbase, obj->textsize,
2261 PROT_READ|PROT_EXEC) == -1) {
2262 _rtld_error("%s: Cannot write-protect text segment: %s",
2263 obj->path, rtld_strerror(errno));
2269 /* Set the special PLT or GOT entries. */
2272 /* Process the PLT relocations. */
2273 if (reloc_plt(obj) == -1)
2275 /* Relocate the jump slots if we are doing immediate binding. */
2276 if (obj->bind_now || bind_now)
2277 if (reloc_jmpslots(obj, flags, lockstate) == -1)
2280 if (obj->relro_size > 0) {
2281 if (mprotect(obj->relro_page, obj->relro_size, PROT_READ) == -1) {
2282 _rtld_error("%s: Cannot enforce relro protection: %s",
2283 obj->path, rtld_strerror(errno));
2289 * Set up the magic number and version in the Obj_Entry. These
2290 * were checked in the crt1.o from the original ElfKit, so we
2291 * set them for backward compatibility.
2293 obj->magic = RTLD_MAGIC;
2294 obj->version = RTLD_VERSION;
2301 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
2302 * referencing STT_GNU_IFUNC symbols is postponed till the other
2303 * relocations are done. The indirect functions specified as
2304 * ifunc are allowed to call other symbols, so we need to have
2305 * objects relocated before asking for resolution from indirects.
2307 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
2308 * instead of the usual lazy handling of PLT slots. It is
2309 * consistent with how GNU does it.
2312 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags,
2313 RtldLockState *lockstate)
2315 if (obj->irelative && reloc_iresolve(obj, lockstate) == -1)
2317 if ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
2318 reloc_gnu_ifunc(obj, flags, lockstate) == -1)
2324 resolve_objects_ifunc(Obj_Entry *first, bool bind_now, int flags,
2325 RtldLockState *lockstate)
2329 for (obj = first; obj != NULL; obj = obj->next) {
2330 if (resolve_object_ifunc(obj, bind_now, flags, lockstate) == -1)
2337 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags,
2338 RtldLockState *lockstate)
2342 STAILQ_FOREACH(elm, list, link) {
2343 if (resolve_object_ifunc(elm->obj, bind_now, flags,
2351 * Cleanup procedure. It will be called (by the atexit mechanism) just
2352 * before the process exits.
2357 RtldLockState lockstate;
2359 wlock_acquire(rtld_bind_lock, &lockstate);
2361 objlist_call_fini(&list_fini, NULL, &lockstate);
2362 /* No need to remove the items from the list, since we are exiting. */
2363 if (!libmap_disable)
2365 lock_release(rtld_bind_lock, &lockstate);
2369 path_enumerate(const char *path, path_enum_proc callback, void *arg)
2377 path += strspn(path, ":;");
2378 while (*path != '\0') {
2382 len = strcspn(path, ":;");
2384 trans = lm_findn(NULL, path, len);
2386 res = callback(trans, strlen(trans), arg);
2389 res = callback(path, len, arg);
2395 path += strspn(path, ":;");
2401 struct try_library_args {
2409 try_library_path(const char *dir, size_t dirlen, void *param)
2411 struct try_library_args *arg;
2414 if (*dir == '/' || trust) {
2417 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
2420 pathname = arg->buffer;
2421 strncpy(pathname, dir, dirlen);
2422 pathname[dirlen] = '/';
2423 strcpy(pathname + dirlen + 1, arg->name);
2425 dbg(" Trying \"%s\"", pathname);
2426 if (access(pathname, F_OK) == 0) { /* We found it */
2427 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
2428 strcpy(pathname, arg->buffer);
2436 search_library_path(const char *name, const char *path)
2439 struct try_library_args arg;
2445 arg.namelen = strlen(name);
2446 arg.buffer = xmalloc(PATH_MAX);
2447 arg.buflen = PATH_MAX;
2449 p = path_enumerate(path, try_library_path, &arg);
2457 dlclose(void *handle)
2460 RtldLockState lockstate;
2462 wlock_acquire(rtld_bind_lock, &lockstate);
2463 root = dlcheck(handle);
2465 lock_release(rtld_bind_lock, &lockstate);
2468 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
2471 /* Unreference the object and its dependencies. */
2472 root->dl_refcount--;
2474 if (root->refcount == 1) {
2476 * The object will be no longer referenced, so we must unload it.
2477 * First, call the fini functions.
2479 objlist_call_fini(&list_fini, root, &lockstate);
2483 /* Finish cleaning up the newly-unreferenced objects. */
2484 GDB_STATE(RT_DELETE,&root->linkmap);
2485 unload_object(root);
2486 GDB_STATE(RT_CONSISTENT,NULL);
2490 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
2491 lock_release(rtld_bind_lock, &lockstate);
2498 char *msg = error_message;
2499 error_message = NULL;
2504 * This function is deprecated and has no effect.
2507 dllockinit(void *context,
2508 void *(*lock_create)(void *context),
2509 void (*rlock_acquire)(void *lock),
2510 void (*wlock_acquire)(void *lock),
2511 void (*lock_release)(void *lock),
2512 void (*lock_destroy)(void *lock),
2513 void (*context_destroy)(void *context))
2515 static void *cur_context;
2516 static void (*cur_context_destroy)(void *);
2518 /* Just destroy the context from the previous call, if necessary. */
2519 if (cur_context_destroy != NULL)
2520 cur_context_destroy(cur_context);
2521 cur_context = context;
2522 cur_context_destroy = context_destroy;
2526 dlopen(const char *name, int mode)
2529 return (rtld_dlopen(name, -1, mode));
2533 fdlopen(int fd, int mode)
2536 return (rtld_dlopen(NULL, fd, mode));
2540 rtld_dlopen(const char *name, int fd, int mode)
2542 RtldLockState lockstate;
2545 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
2546 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
2547 if (ld_tracing != NULL) {
2548 rlock_acquire(rtld_bind_lock, &lockstate);
2549 if (sigsetjmp(lockstate.env, 0) != 0)
2550 lock_upgrade(rtld_bind_lock, &lockstate);
2551 environ = (char **)*get_program_var_addr("environ", &lockstate);
2552 lock_release(rtld_bind_lock, &lockstate);
2554 lo_flags = RTLD_LO_DLOPEN;
2555 if (mode & RTLD_NODELETE)
2556 lo_flags |= RTLD_LO_NODELETE;
2557 if (mode & RTLD_NOLOAD)
2558 lo_flags |= RTLD_LO_NOLOAD;
2559 if (ld_tracing != NULL)
2560 lo_flags |= RTLD_LO_TRACE;
2562 return (dlopen_object(name, fd, obj_main, lo_flags,
2563 mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL));
2567 dlopen_cleanup(Obj_Entry *obj)
2572 if (obj->refcount == 0)
2577 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
2578 int mode, RtldLockState *lockstate)
2580 Obj_Entry **old_obj_tail;
2583 RtldLockState mlockstate;
2586 objlist_init(&initlist);
2588 if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) {
2589 wlock_acquire(rtld_bind_lock, &mlockstate);
2590 lockstate = &mlockstate;
2592 GDB_STATE(RT_ADD,NULL);
2594 old_obj_tail = obj_tail;
2596 if (name == NULL && fd == -1) {
2600 obj = load_object(name, fd, refobj, lo_flags);
2605 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
2606 objlist_push_tail(&list_global, obj);
2607 if (*old_obj_tail != NULL) { /* We loaded something new. */
2608 assert(*old_obj_tail == obj);
2609 result = load_needed_objects(obj,
2610 lo_flags & (RTLD_LO_DLOPEN | RTLD_LO_EARLY));
2614 result = rtld_verify_versions(&obj->dagmembers);
2615 if (result != -1 && ld_tracing)
2617 if (result == -1 || (relocate_objects(obj,
2618 (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld,
2619 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
2620 lockstate)) == -1) {
2621 dlopen_cleanup(obj);
2623 } else if (lo_flags & RTLD_LO_EARLY) {
2625 * Do not call the init functions for early loaded
2626 * filtees. The image is still not initialized enough
2629 * Our object is found by the global object list and
2630 * will be ordered among all init calls done right
2631 * before transferring control to main.
2634 /* Make list of init functions to call. */
2635 initlist_add_objects(obj, &obj->next, &initlist);
2640 * Bump the reference counts for objects on this DAG. If
2641 * this is the first dlopen() call for the object that was
2642 * already loaded as a dependency, initialize the dag
2648 if ((lo_flags & RTLD_LO_TRACE) != 0)
2651 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
2652 obj->z_nodelete) && !obj->ref_nodel) {
2653 dbg("obj %s nodelete", obj->path);
2655 obj->z_nodelete = obj->ref_nodel = true;
2659 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
2661 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
2663 if (!(lo_flags & RTLD_LO_EARLY)) {
2664 map_stacks_exec(lockstate);
2667 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
2668 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
2670 objlist_clear(&initlist);
2671 dlopen_cleanup(obj);
2672 if (lockstate == &mlockstate)
2673 lock_release(rtld_bind_lock, lockstate);
2677 if (!(lo_flags & RTLD_LO_EARLY)) {
2678 /* Call the init functions. */
2679 objlist_call_init(&initlist, lockstate);
2681 objlist_clear(&initlist);
2682 if (lockstate == &mlockstate)
2683 lock_release(rtld_bind_lock, lockstate);
2686 trace_loaded_objects(obj);
2687 if (lockstate == &mlockstate)
2688 lock_release(rtld_bind_lock, lockstate);
2693 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
2697 const Obj_Entry *obj, *defobj;
2700 RtldLockState lockstate;
2708 symlook_init(&req, name);
2710 req.flags = flags | SYMLOOK_IN_PLT;
2711 req.lockstate = &lockstate;
2713 rlock_acquire(rtld_bind_lock, &lockstate);
2714 if (sigsetjmp(lockstate.env, 0) != 0)
2715 lock_upgrade(rtld_bind_lock, &lockstate);
2716 if (handle == NULL || handle == RTLD_NEXT ||
2717 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
2719 if ((obj = obj_from_addr(retaddr)) == NULL) {
2720 _rtld_error("Cannot determine caller's shared object");
2721 lock_release(rtld_bind_lock, &lockstate);
2724 if (handle == NULL) { /* Just the caller's shared object. */
2725 res = symlook_obj(&req, obj);
2728 defobj = req.defobj_out;
2730 } else if (handle == RTLD_NEXT || /* Objects after caller's */
2731 handle == RTLD_SELF) { /* ... caller included */
2732 if (handle == RTLD_NEXT)
2734 for (; obj != NULL; obj = obj->next) {
2735 res = symlook_obj(&req, obj);
2738 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) {
2740 defobj = req.defobj_out;
2741 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2747 * Search the dynamic linker itself, and possibly resolve the
2748 * symbol from there. This is how the application links to
2749 * dynamic linker services such as dlopen.
2751 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2752 res = symlook_obj(&req, &obj_rtld);
2755 defobj = req.defobj_out;
2759 assert(handle == RTLD_DEFAULT);
2760 res = symlook_default(&req, obj);
2762 defobj = req.defobj_out;
2767 if ((obj = dlcheck(handle)) == NULL) {
2768 lock_release(rtld_bind_lock, &lockstate);
2772 donelist_init(&donelist);
2773 if (obj->mainprog) {
2774 /* Handle obtained by dlopen(NULL, ...) implies global scope. */
2775 res = symlook_global(&req, &donelist);
2778 defobj = req.defobj_out;
2781 * Search the dynamic linker itself, and possibly resolve the
2782 * symbol from there. This is how the application links to
2783 * dynamic linker services such as dlopen.
2785 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2786 res = symlook_obj(&req, &obj_rtld);
2789 defobj = req.defobj_out;
2794 /* Search the whole DAG rooted at the given object. */
2795 res = symlook_list(&req, &obj->dagmembers, &donelist);
2798 defobj = req.defobj_out;
2804 lock_release(rtld_bind_lock, &lockstate);
2807 * The value required by the caller is derived from the value
2808 * of the symbol. For the ia64 architecture, we need to
2809 * construct a function descriptor which the caller can use to
2810 * call the function with the right 'gp' value. For other
2811 * architectures and for non-functions, the value is simply
2812 * the relocated value of the symbol.
2814 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
2815 return (make_function_pointer(def, defobj));
2816 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
2817 return (rtld_resolve_ifunc(defobj, def));
2818 else if (ELF_ST_TYPE(def->st_info) == STT_TLS) {
2820 return (__tls_get_addr(defobj->tlsindex, def->st_value));
2822 ti.ti_module = defobj->tlsindex;
2823 ti.ti_offset = def->st_value;
2824 return (__tls_get_addr(&ti));
2827 return (defobj->relocbase + def->st_value);
2830 _rtld_error("Undefined symbol \"%s\"", name);
2831 lock_release(rtld_bind_lock, &lockstate);
2836 dlsym(void *handle, const char *name)
2838 return do_dlsym(handle, name, __builtin_return_address(0), NULL,
2843 dlfunc(void *handle, const char *name)
2850 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
2856 dlvsym(void *handle, const char *name, const char *version)
2860 ventry.name = version;
2862 ventry.hash = elf_hash(version);
2864 return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
2869 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
2871 const Obj_Entry *obj;
2872 RtldLockState lockstate;
2874 rlock_acquire(rtld_bind_lock, &lockstate);
2875 obj = obj_from_addr(addr);
2877 _rtld_error("No shared object contains address");
2878 lock_release(rtld_bind_lock, &lockstate);
2881 rtld_fill_dl_phdr_info(obj, phdr_info);
2882 lock_release(rtld_bind_lock, &lockstate);
2887 dladdr(const void *addr, Dl_info *info)
2889 const Obj_Entry *obj;
2892 unsigned long symoffset;
2893 RtldLockState lockstate;
2895 rlock_acquire(rtld_bind_lock, &lockstate);
2896 obj = obj_from_addr(addr);
2898 _rtld_error("No shared object contains address");
2899 lock_release(rtld_bind_lock, &lockstate);
2902 info->dli_fname = obj->path;
2903 info->dli_fbase = obj->mapbase;
2904 info->dli_saddr = (void *)0;
2905 info->dli_sname = NULL;
2908 * Walk the symbol list looking for the symbol whose address is
2909 * closest to the address sent in.
2911 for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) {
2912 def = obj->symtab + symoffset;
2915 * For skip the symbol if st_shndx is either SHN_UNDEF or
2918 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
2922 * If the symbol is greater than the specified address, or if it
2923 * is further away from addr than the current nearest symbol,
2926 symbol_addr = obj->relocbase + def->st_value;
2927 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
2930 /* Update our idea of the nearest symbol. */
2931 info->dli_sname = obj->strtab + def->st_name;
2932 info->dli_saddr = symbol_addr;
2935 if (info->dli_saddr == addr)
2938 lock_release(rtld_bind_lock, &lockstate);
2943 dlinfo(void *handle, int request, void *p)
2945 const Obj_Entry *obj;
2946 RtldLockState lockstate;
2949 rlock_acquire(rtld_bind_lock, &lockstate);
2951 if (handle == NULL || handle == RTLD_SELF) {
2954 retaddr = __builtin_return_address(0); /* __GNUC__ only */
2955 if ((obj = obj_from_addr(retaddr)) == NULL)
2956 _rtld_error("Cannot determine caller's shared object");
2958 obj = dlcheck(handle);
2961 lock_release(rtld_bind_lock, &lockstate);
2967 case RTLD_DI_LINKMAP:
2968 *((struct link_map const **)p) = &obj->linkmap;
2970 case RTLD_DI_ORIGIN:
2971 error = rtld_dirname(obj->path, p);
2974 case RTLD_DI_SERINFOSIZE:
2975 case RTLD_DI_SERINFO:
2976 error = do_search_info(obj, request, (struct dl_serinfo *)p);
2980 _rtld_error("Invalid request %d passed to dlinfo()", request);
2984 lock_release(rtld_bind_lock, &lockstate);
2990 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
2993 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
2994 phdr_info->dlpi_name = STAILQ_FIRST(&obj->names) ?
2995 STAILQ_FIRST(&obj->names)->name : obj->path;
2996 phdr_info->dlpi_phdr = obj->phdr;
2997 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
2998 phdr_info->dlpi_tls_modid = obj->tlsindex;
2999 phdr_info->dlpi_tls_data = obj->tlsinit;
3000 phdr_info->dlpi_adds = obj_loads;
3001 phdr_info->dlpi_subs = obj_loads - obj_count;
3005 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
3007 struct dl_phdr_info phdr_info;
3008 const Obj_Entry *obj;
3009 RtldLockState bind_lockstate, phdr_lockstate;
3012 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
3013 rlock_acquire(rtld_bind_lock, &bind_lockstate);
3017 for (obj = obj_list; obj != NULL; obj = obj->next) {
3018 rtld_fill_dl_phdr_info(obj, &phdr_info);
3019 if ((error = callback(&phdr_info, sizeof phdr_info, param)) != 0)
3023 lock_release(rtld_bind_lock, &bind_lockstate);
3024 lock_release(rtld_phdr_lock, &phdr_lockstate);
3029 struct fill_search_info_args {
3032 Dl_serinfo *serinfo;
3033 Dl_serpath *serpath;
3038 fill_search_info(const char *dir, size_t dirlen, void *param)
3040 struct fill_search_info_args *arg;
3044 if (arg->request == RTLD_DI_SERINFOSIZE) {
3045 arg->serinfo->dls_cnt ++;
3046 arg->serinfo->dls_size += sizeof(Dl_serpath) + dirlen + 1;
3048 struct dl_serpath *s_entry;
3050 s_entry = arg->serpath;
3051 s_entry->dls_name = arg->strspace;
3052 s_entry->dls_flags = arg->flags;
3054 strncpy(arg->strspace, dir, dirlen);
3055 arg->strspace[dirlen] = '\0';
3057 arg->strspace += dirlen + 1;
3065 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
3067 struct dl_serinfo _info;
3068 struct fill_search_info_args args;
3070 args.request = RTLD_DI_SERINFOSIZE;
3071 args.serinfo = &_info;
3073 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
3076 path_enumerate(ld_library_path, fill_search_info, &args);
3077 path_enumerate(obj->rpath, fill_search_info, &args);
3078 path_enumerate(gethints(), fill_search_info, &args);
3079 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
3082 if (request == RTLD_DI_SERINFOSIZE) {
3083 info->dls_size = _info.dls_size;
3084 info->dls_cnt = _info.dls_cnt;
3088 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
3089 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
3093 args.request = RTLD_DI_SERINFO;
3094 args.serinfo = info;
3095 args.serpath = &info->dls_serpath[0];
3096 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
3098 args.flags = LA_SER_LIBPATH;
3099 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
3102 args.flags = LA_SER_RUNPATH;
3103 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
3106 args.flags = LA_SER_CONFIG;
3107 if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
3110 args.flags = LA_SER_DEFAULT;
3111 if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
3117 rtld_dirname(const char *path, char *bname)
3121 /* Empty or NULL string gets treated as "." */
3122 if (path == NULL || *path == '\0') {
3128 /* Strip trailing slashes */
3129 endp = path + strlen(path) - 1;
3130 while (endp > path && *endp == '/')
3133 /* Find the start of the dir */
3134 while (endp > path && *endp != '/')
3137 /* Either the dir is "/" or there are no slashes */
3139 bname[0] = *endp == '/' ? '/' : '.';
3145 } while (endp > path && *endp == '/');
3148 if (endp - path + 2 > PATH_MAX)
3150 _rtld_error("Filename is too long: %s", path);
3154 strncpy(bname, path, endp - path + 1);
3155 bname[endp - path + 1] = '\0';
3160 rtld_dirname_abs(const char *path, char *base)
3162 char base_rel[PATH_MAX];
3164 if (rtld_dirname(path, base) == -1)
3168 if (getcwd(base_rel, sizeof(base_rel)) == NULL ||
3169 strlcat(base_rel, "/", sizeof(base_rel)) >= sizeof(base_rel) ||
3170 strlcat(base_rel, base, sizeof(base_rel)) >= sizeof(base_rel))
3172 strcpy(base, base_rel);
3177 linkmap_add(Obj_Entry *obj)
3179 struct link_map *l = &obj->linkmap;
3180 struct link_map *prev;
3182 obj->linkmap.l_name = obj->path;
3183 obj->linkmap.l_addr = obj->mapbase;
3184 obj->linkmap.l_ld = obj->dynamic;
3186 /* GDB needs load offset on MIPS to use the symbols */
3187 obj->linkmap.l_offs = obj->relocbase;
3190 if (r_debug.r_map == NULL) {
3196 * Scan to the end of the list, but not past the entry for the
3197 * dynamic linker, which we want to keep at the very end.
3199 for (prev = r_debug.r_map;
3200 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
3201 prev = prev->l_next)
3204 /* Link in the new entry. */
3206 l->l_next = prev->l_next;
3207 if (l->l_next != NULL)
3208 l->l_next->l_prev = l;
3213 linkmap_delete(Obj_Entry *obj)
3215 struct link_map *l = &obj->linkmap;
3217 if (l->l_prev == NULL) {
3218 if ((r_debug.r_map = l->l_next) != NULL)
3219 l->l_next->l_prev = NULL;
3223 if ((l->l_prev->l_next = l->l_next) != NULL)
3224 l->l_next->l_prev = l->l_prev;
3228 * Function for the debugger to set a breakpoint on to gain control.
3230 * The two parameters allow the debugger to easily find and determine
3231 * what the runtime loader is doing and to whom it is doing it.
3233 * When the loadhook trap is hit (r_debug_state, set at program
3234 * initialization), the arguments can be found on the stack:
3236 * +8 struct link_map *m
3237 * +4 struct r_debug *rd
3241 r_debug_state(struct r_debug* rd, struct link_map *m)
3244 * The following is a hack to force the compiler to emit calls to
3245 * this function, even when optimizing. If the function is empty,
3246 * the compiler is not obliged to emit any code for calls to it,
3247 * even when marked __noinline. However, gdb depends on those
3250 __asm __volatile("" : : : "memory");
3254 * Get address of the pointer variable in the main program.
3255 * Prefer non-weak symbol over the weak one.
3257 static const void **
3258 get_program_var_addr(const char *name, RtldLockState *lockstate)
3263 symlook_init(&req, name);
3264 req.lockstate = lockstate;
3265 donelist_init(&donelist);
3266 if (symlook_global(&req, &donelist) != 0)
3268 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
3269 return ((const void **)make_function_pointer(req.sym_out,
3271 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
3272 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
3274 return ((const void **)(req.defobj_out->relocbase +
3275 req.sym_out->st_value));
3279 * Set a pointer variable in the main program to the given value. This
3280 * is used to set key variables such as "environ" before any of the
3281 * init functions are called.
3284 set_program_var(const char *name, const void *value)
3288 if ((addr = get_program_var_addr(name, NULL)) != NULL) {
3289 dbg("\"%s\": *%p <-- %p", name, addr, value);
3295 * Search the global objects, including dependencies and main object,
3296 * for the given symbol.
3299 symlook_global(SymLook *req, DoneList *donelist)
3302 const Objlist_Entry *elm;
3305 symlook_init_from_req(&req1, req);
3307 /* Search all objects loaded at program start up. */
3308 if (req->defobj_out == NULL ||
3309 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3310 res = symlook_list(&req1, &list_main, donelist);
3311 if (res == 0 && (req->defobj_out == NULL ||
3312 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3313 req->sym_out = req1.sym_out;
3314 req->defobj_out = req1.defobj_out;
3315 assert(req->defobj_out != NULL);
3319 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
3320 STAILQ_FOREACH(elm, &list_global, link) {
3321 if (req->defobj_out != NULL &&
3322 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3324 res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
3325 if (res == 0 && (req->defobj_out == NULL ||
3326 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3327 req->sym_out = req1.sym_out;
3328 req->defobj_out = req1.defobj_out;
3329 assert(req->defobj_out != NULL);
3333 return (req->sym_out != NULL ? 0 : ESRCH);
3337 * Given a symbol name in a referencing object, find the corresponding
3338 * definition of the symbol. Returns a pointer to the symbol, or NULL if
3339 * no definition was found. Returns a pointer to the Obj_Entry of the
3340 * defining object via the reference parameter DEFOBJ_OUT.
3343 symlook_default(SymLook *req, const Obj_Entry *refobj)
3346 const Objlist_Entry *elm;
3350 donelist_init(&donelist);
3351 symlook_init_from_req(&req1, req);
3353 /* Look first in the referencing object if linked symbolically. */
3354 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
3355 res = symlook_obj(&req1, refobj);
3357 req->sym_out = req1.sym_out;
3358 req->defobj_out = req1.defobj_out;
3359 assert(req->defobj_out != NULL);
3363 symlook_global(req, &donelist);
3365 /* Search all dlopened DAGs containing the referencing object. */
3366 STAILQ_FOREACH(elm, &refobj->dldags, link) {
3367 if (req->sym_out != NULL &&
3368 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3370 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
3371 if (res == 0 && (req->sym_out == NULL ||
3372 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3373 req->sym_out = req1.sym_out;
3374 req->defobj_out = req1.defobj_out;
3375 assert(req->defobj_out != NULL);
3380 * Search the dynamic linker itself, and possibly resolve the
3381 * symbol from there. This is how the application links to
3382 * dynamic linker services such as dlopen.
3384 if (req->sym_out == NULL ||
3385 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3386 res = symlook_obj(&req1, &obj_rtld);
3388 req->sym_out = req1.sym_out;
3389 req->defobj_out = req1.defobj_out;
3390 assert(req->defobj_out != NULL);
3394 return (req->sym_out != NULL ? 0 : ESRCH);
3398 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
3401 const Obj_Entry *defobj;
3402 const Objlist_Entry *elm;
3408 STAILQ_FOREACH(elm, objlist, link) {
3409 if (donelist_check(dlp, elm->obj))
3411 symlook_init_from_req(&req1, req);
3412 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
3413 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3415 defobj = req1.defobj_out;
3416 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3423 req->defobj_out = defobj;
3430 * Search the chain of DAGS cointed to by the given Needed_Entry
3431 * for a symbol of the given name. Each DAG is scanned completely
3432 * before advancing to the next one. Returns a pointer to the symbol,
3433 * or NULL if no definition was found.
3436 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
3439 const Needed_Entry *n;
3440 const Obj_Entry *defobj;
3446 symlook_init_from_req(&req1, req);
3447 for (n = needed; n != NULL; n = n->next) {
3448 if (n->obj == NULL ||
3449 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
3451 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3453 defobj = req1.defobj_out;
3454 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3460 req->defobj_out = defobj;
3467 * Search the symbol table of a single shared object for a symbol of
3468 * the given name and version, if requested. Returns a pointer to the
3469 * symbol, or NULL if no definition was found. If the object is
3470 * filter, return filtered symbol from filtee.
3472 * The symbol's hash value is passed in for efficiency reasons; that
3473 * eliminates many recomputations of the hash value.
3476 symlook_obj(SymLook *req, const Obj_Entry *obj)
3480 int flags, res, mres;
3483 * If there is at least one valid hash at this point, we prefer to
3484 * use the faster GNU version if available.
3486 if (obj->valid_hash_gnu)
3487 mres = symlook_obj1_gnu(req, obj);
3488 else if (obj->valid_hash_sysv)
3489 mres = symlook_obj1_sysv(req, obj);
3494 if (obj->needed_filtees != NULL) {
3495 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
3496 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
3497 donelist_init(&donelist);
3498 symlook_init_from_req(&req1, req);
3499 res = symlook_needed(&req1, obj->needed_filtees, &donelist);
3501 req->sym_out = req1.sym_out;
3502 req->defobj_out = req1.defobj_out;
3506 if (obj->needed_aux_filtees != NULL) {
3507 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
3508 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
3509 donelist_init(&donelist);
3510 symlook_init_from_req(&req1, req);
3511 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
3513 req->sym_out = req1.sym_out;
3514 req->defobj_out = req1.defobj_out;
3522 /* Symbol match routine common to both hash functions */
3524 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result,
3525 const unsigned long symnum)
3528 const Elf_Sym *symp;
3531 symp = obj->symtab + symnum;
3532 strp = obj->strtab + symp->st_name;
3534 switch (ELF_ST_TYPE(symp->st_info)) {
3540 if (symp->st_value == 0)
3544 if (symp->st_shndx != SHN_UNDEF)
3547 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
3548 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
3555 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
3558 if (req->ventry == NULL) {
3559 if (obj->versyms != NULL) {
3560 verndx = VER_NDX(obj->versyms[symnum]);
3561 if (verndx > obj->vernum) {
3563 "%s: symbol %s references wrong version %d",
3564 obj->path, obj->strtab + symnum, verndx);
3568 * If we are not called from dlsym (i.e. this
3569 * is a normal relocation from unversioned
3570 * binary), accept the symbol immediately if
3571 * it happens to have first version after this
3572 * shared object became versioned. Otherwise,
3573 * if symbol is versioned and not hidden,
3574 * remember it. If it is the only symbol with
3575 * this name exported by the shared object, it
3576 * will be returned as a match by the calling
3577 * function. If symbol is global (verndx < 2)
3578 * accept it unconditionally.
3580 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
3581 verndx == VER_NDX_GIVEN) {
3582 result->sym_out = symp;
3585 else if (verndx >= VER_NDX_GIVEN) {
3586 if ((obj->versyms[symnum] & VER_NDX_HIDDEN)
3588 if (result->vsymp == NULL)
3589 result->vsymp = symp;
3595 result->sym_out = symp;
3598 if (obj->versyms == NULL) {
3599 if (object_match_name(obj, req->ventry->name)) {
3600 _rtld_error("%s: object %s should provide version %s "
3601 "for symbol %s", obj_rtld.path, obj->path,
3602 req->ventry->name, obj->strtab + symnum);
3606 verndx = VER_NDX(obj->versyms[symnum]);
3607 if (verndx > obj->vernum) {
3608 _rtld_error("%s: symbol %s references wrong version %d",
3609 obj->path, obj->strtab + symnum, verndx);
3612 if (obj->vertab[verndx].hash != req->ventry->hash ||
3613 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
3615 * Version does not match. Look if this is a
3616 * global symbol and if it is not hidden. If
3617 * global symbol (verndx < 2) is available,
3618 * use it. Do not return symbol if we are
3619 * called by dlvsym, because dlvsym looks for
3620 * a specific version and default one is not
3621 * what dlvsym wants.
3623 if ((req->flags & SYMLOOK_DLSYM) ||
3624 (verndx >= VER_NDX_GIVEN) ||
3625 (obj->versyms[symnum] & VER_NDX_HIDDEN))
3629 result->sym_out = symp;
3634 * Search for symbol using SysV hash function.
3635 * obj->buckets is known not to be NULL at this point; the test for this was
3636 * performed with the obj->valid_hash_sysv assignment.
3639 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj)
3641 unsigned long symnum;
3642 Sym_Match_Result matchres;
3644 matchres.sym_out = NULL;
3645 matchres.vsymp = NULL;
3646 matchres.vcount = 0;
3648 for (symnum = obj->buckets[req->hash % obj->nbuckets];
3649 symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
3650 if (symnum >= obj->nchains)
3651 return (ESRCH); /* Bad object */
3653 if (matched_symbol(req, obj, &matchres, symnum)) {
3654 req->sym_out = matchres.sym_out;
3655 req->defobj_out = obj;
3659 if (matchres.vcount == 1) {
3660 req->sym_out = matchres.vsymp;
3661 req->defobj_out = obj;
3667 /* Search for symbol using GNU hash function */
3669 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj)
3671 Elf_Addr bloom_word;
3672 const Elf32_Word *hashval;
3674 Sym_Match_Result matchres;
3675 unsigned int h1, h2;
3676 unsigned long symnum;
3678 matchres.sym_out = NULL;
3679 matchres.vsymp = NULL;
3680 matchres.vcount = 0;
3682 /* Pick right bitmask word from Bloom filter array */
3683 bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) &
3684 obj->maskwords_bm_gnu];
3686 /* Calculate modulus word size of gnu hash and its derivative */
3687 h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1);
3688 h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1));
3690 /* Filter out the "definitely not in set" queries */
3691 if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0)
3694 /* Locate hash chain and corresponding value element*/
3695 bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu];
3698 hashval = &obj->chain_zero_gnu[bucket];
3700 if (((*hashval ^ req->hash_gnu) >> 1) == 0) {
3701 symnum = hashval - obj->chain_zero_gnu;
3702 if (matched_symbol(req, obj, &matchres, symnum)) {
3703 req->sym_out = matchres.sym_out;
3704 req->defobj_out = obj;
3708 } while ((*hashval++ & 1) == 0);
3709 if (matchres.vcount == 1) {
3710 req->sym_out = matchres.vsymp;
3711 req->defobj_out = obj;
3718 trace_loaded_objects(Obj_Entry *obj)
3720 char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
3723 if ((main_local = getenv(LD_ "TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
3726 if ((fmt1 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT1")) == NULL)
3727 fmt1 = "\t%o => %p (%x)\n";
3729 if ((fmt2 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT2")) == NULL)
3730 fmt2 = "\t%o (%x)\n";
3732 list_containers = getenv(LD_ "TRACE_LOADED_OBJECTS_ALL");
3734 for (; obj; obj = obj->next) {
3735 Needed_Entry *needed;
3739 if (list_containers && obj->needed != NULL)
3740 rtld_printf("%s:\n", obj->path);
3741 for (needed = obj->needed; needed; needed = needed->next) {
3742 if (needed->obj != NULL) {
3743 if (needed->obj->traced && !list_containers)
3745 needed->obj->traced = true;
3746 path = needed->obj->path;
3750 name = (char *)obj->strtab + needed->name;
3751 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
3753 fmt = is_lib ? fmt1 : fmt2;
3754 while ((c = *fmt++) != '\0') {
3780 rtld_putstr(main_local);
3783 rtld_putstr(obj_main->path);
3790 rtld_printf("%d", sodp->sod_major);
3793 rtld_printf("%d", sodp->sod_minor);
3800 rtld_printf("%p", needed->obj ? needed->obj->mapbase :
3813 * Unload a dlopened object and its dependencies from memory and from
3814 * our data structures. It is assumed that the DAG rooted in the
3815 * object has already been unreferenced, and that the object has a
3816 * reference count of 0.
3819 unload_object(Obj_Entry *root)
3824 assert(root->refcount == 0);
3827 * Pass over the DAG removing unreferenced objects from
3828 * appropriate lists.
3830 unlink_object(root);
3832 /* Unmap all objects that are no longer referenced. */
3833 linkp = &obj_list->next;
3834 while ((obj = *linkp) != NULL) {
3835 if (obj->refcount == 0) {
3836 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
3838 dbg("unloading \"%s\"", obj->path);
3839 unload_filtees(root);
3840 munmap(obj->mapbase, obj->mapsize);
3841 linkmap_delete(obj);
3852 unlink_object(Obj_Entry *root)
3856 if (root->refcount == 0) {
3857 /* Remove the object from the RTLD_GLOBAL list. */
3858 objlist_remove(&list_global, root);
3860 /* Remove the object from all objects' DAG lists. */
3861 STAILQ_FOREACH(elm, &root->dagmembers, link) {
3862 objlist_remove(&elm->obj->dldags, root);
3863 if (elm->obj != root)
3864 unlink_object(elm->obj);
3870 ref_dag(Obj_Entry *root)
3874 assert(root->dag_inited);
3875 STAILQ_FOREACH(elm, &root->dagmembers, link)
3876 elm->obj->refcount++;
3880 unref_dag(Obj_Entry *root)
3884 assert(root->dag_inited);
3885 STAILQ_FOREACH(elm, &root->dagmembers, link)
3886 elm->obj->refcount--;
3890 * Common code for MD __tls_get_addr().
3892 static void *tls_get_addr_slow(Elf_Addr **, int, size_t) __noinline;
3894 tls_get_addr_slow(Elf_Addr **dtvp, int index, size_t offset)
3896 Elf_Addr *newdtv, *dtv;
3897 RtldLockState lockstate;
3901 /* Check dtv generation in case new modules have arrived */
3902 if (dtv[0] != tls_dtv_generation) {
3903 wlock_acquire(rtld_bind_lock, &lockstate);
3904 newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
3906 if (to_copy > tls_max_index)
3907 to_copy = tls_max_index;
3908 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
3909 newdtv[0] = tls_dtv_generation;
3910 newdtv[1] = tls_max_index;
3912 lock_release(rtld_bind_lock, &lockstate);
3913 dtv = *dtvp = newdtv;
3916 /* Dynamically allocate module TLS if necessary */
3917 if (dtv[index + 1] == 0) {
3918 /* Signal safe, wlock will block out signals. */
3919 wlock_acquire(rtld_bind_lock, &lockstate);
3920 if (!dtv[index + 1])
3921 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
3922 lock_release(rtld_bind_lock, &lockstate);
3924 return ((void *)(dtv[index + 1] + offset));
3928 tls_get_addr_common(Elf_Addr **dtvp, int index, size_t offset)
3933 /* Check dtv generation in case new modules have arrived */
3934 if (__predict_true(dtv[0] == tls_dtv_generation &&
3935 dtv[index + 1] != 0))
3936 return ((void *)(dtv[index + 1] + offset));
3937 return (tls_get_addr_slow(dtvp, index, offset));
3940 /* XXX not sure what variants to use for arm. */
3942 #if defined(__ia64__) || defined(__powerpc__)
3945 * Allocate Static TLS using the Variant I method.
3948 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
3957 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
3960 assert(tcbsize >= TLS_TCB_SIZE);
3961 tcb = xcalloc(1, tls_static_space - TLS_TCB_SIZE + tcbsize);
3962 tls = (Elf_Addr **)(tcb + tcbsize - TLS_TCB_SIZE);
3964 if (oldtcb != NULL) {
3965 memcpy(tls, oldtcb, tls_static_space);
3968 /* Adjust the DTV. */
3970 for (i = 0; i < dtv[1]; i++) {
3971 if (dtv[i+2] >= (Elf_Addr)oldtcb &&
3972 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
3973 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tls;
3977 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
3979 dtv[0] = tls_dtv_generation;
3980 dtv[1] = tls_max_index;
3982 for (obj = objs; obj; obj = obj->next) {
3983 if (obj->tlsoffset > 0) {
3984 addr = (Elf_Addr)tls + obj->tlsoffset;
3985 if (obj->tlsinitsize > 0)
3986 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
3987 if (obj->tlssize > obj->tlsinitsize)
3988 memset((void*) (addr + obj->tlsinitsize), 0,
3989 obj->tlssize - obj->tlsinitsize);
3990 dtv[obj->tlsindex + 1] = addr;
3999 free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
4002 Elf_Addr tlsstart, tlsend;
4005 assert(tcbsize >= TLS_TCB_SIZE);
4007 tlsstart = (Elf_Addr)tcb + tcbsize - TLS_TCB_SIZE;
4008 tlsend = tlsstart + tls_static_space;
4010 dtv = *(Elf_Addr **)tlsstart;
4012 for (i = 0; i < dtvsize; i++) {
4013 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
4014 free((void*)dtv[i+2]);
4023 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) || \
4024 defined(__arm__) || defined(__mips__)
4027 * Allocate Static TLS using the Variant II method.
4030 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
4035 Elf_Addr *dtv, *olddtv;
4036 Elf_Addr segbase, oldsegbase, addr;
4039 size = round(tls_static_space, tcbalign);
4041 assert(tcbsize >= 2*sizeof(Elf_Addr));
4042 tls = xcalloc(1, size + tcbsize);
4043 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4045 segbase = (Elf_Addr)(tls + size);
4046 ((Elf_Addr*)segbase)[0] = segbase;
4047 ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
4049 dtv[0] = tls_dtv_generation;
4050 dtv[1] = tls_max_index;
4054 * Copy the static TLS block over whole.
4056 oldsegbase = (Elf_Addr) oldtls;
4057 memcpy((void *)(segbase - tls_static_space),
4058 (const void *)(oldsegbase - tls_static_space),
4062 * If any dynamic TLS blocks have been created tls_get_addr(),
4065 olddtv = ((Elf_Addr**)oldsegbase)[1];
4066 for (i = 0; i < olddtv[1]; i++) {
4067 if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
4068 dtv[i+2] = olddtv[i+2];
4074 * We assume that this block was the one we created with
4075 * allocate_initial_tls().
4077 free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
4079 for (obj = objs; obj; obj = obj->next) {
4080 if (obj->tlsoffset) {
4081 addr = segbase - obj->tlsoffset;
4082 memset((void*) (addr + obj->tlsinitsize),
4083 0, obj->tlssize - obj->tlsinitsize);
4085 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4086 dtv[obj->tlsindex + 1] = addr;
4091 return (void*) segbase;
4095 free_tls(void *tls, size_t tcbsize, size_t tcbalign)
4100 Elf_Addr tlsstart, tlsend;
4103 * Figure out the size of the initial TLS block so that we can
4104 * find stuff which ___tls_get_addr() allocated dynamically.
4106 size = round(tls_static_space, tcbalign);
4108 dtv = ((Elf_Addr**)tls)[1];
4110 tlsend = (Elf_Addr) tls;
4111 tlsstart = tlsend - size;
4112 for (i = 0; i < dtvsize; i++) {
4113 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] > tlsend)) {
4114 free((void*) dtv[i+2]);
4118 free((void*) tlsstart);
4125 * Allocate TLS block for module with given index.
4128 allocate_module_tls(int index)
4133 for (obj = obj_list; obj; obj = obj->next) {
4134 if (obj->tlsindex == index)
4138 _rtld_error("Can't find module with TLS index %d", index);
4142 p = malloc(obj->tlssize);
4144 _rtld_error("Cannot allocate TLS block for index %d", index);
4147 memcpy(p, obj->tlsinit, obj->tlsinitsize);
4148 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
4154 allocate_tls_offset(Obj_Entry *obj)
4161 if (obj->tlssize == 0) {
4162 obj->tls_done = true;
4166 if (obj->tlsindex == 1)
4167 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
4169 off = calculate_tls_offset(tls_last_offset, tls_last_size,
4170 obj->tlssize, obj->tlsalign);
4173 * If we have already fixed the size of the static TLS block, we
4174 * must stay within that size. When allocating the static TLS, we
4175 * leave a small amount of space spare to be used for dynamically
4176 * loading modules which use static TLS.
4178 if (tls_static_space) {
4179 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
4183 tls_last_offset = obj->tlsoffset = off;
4184 tls_last_size = obj->tlssize;
4185 obj->tls_done = true;
4191 free_tls_offset(Obj_Entry *obj)
4195 * If we were the last thing to allocate out of the static TLS
4196 * block, we give our space back to the 'allocator'. This is a
4197 * simplistic workaround to allow libGL.so.1 to be loaded and
4198 * unloaded multiple times.
4200 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
4201 == calculate_tls_end(tls_last_offset, tls_last_size)) {
4202 tls_last_offset -= obj->tlssize;
4208 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
4211 RtldLockState lockstate;
4213 wlock_acquire(rtld_bind_lock, &lockstate);
4214 ret = allocate_tls(obj_list, oldtls, tcbsize, tcbalign);
4215 lock_release(rtld_bind_lock, &lockstate);
4220 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
4222 RtldLockState lockstate;
4224 wlock_acquire(rtld_bind_lock, &lockstate);
4225 free_tls(tcb, tcbsize, tcbalign);
4226 lock_release(rtld_bind_lock, &lockstate);
4230 object_add_name(Obj_Entry *obj, const char *name)
4236 entry = malloc(sizeof(Name_Entry) + len);
4238 if (entry != NULL) {
4239 strcpy(entry->name, name);
4240 STAILQ_INSERT_TAIL(&obj->names, entry, link);
4245 object_match_name(const Obj_Entry *obj, const char *name)
4249 STAILQ_FOREACH(entry, &obj->names, link) {
4250 if (strcmp(name, entry->name) == 0)
4257 locate_dependency(const Obj_Entry *obj, const char *name)
4259 const Objlist_Entry *entry;
4260 const Needed_Entry *needed;
4262 STAILQ_FOREACH(entry, &list_main, link) {
4263 if (object_match_name(entry->obj, name))
4267 for (needed = obj->needed; needed != NULL; needed = needed->next) {
4268 if (strcmp(obj->strtab + needed->name, name) == 0 ||
4269 (needed->obj != NULL && object_match_name(needed->obj, name))) {
4271 * If there is DT_NEEDED for the name we are looking for,
4272 * we are all set. Note that object might not be found if
4273 * dependency was not loaded yet, so the function can
4274 * return NULL here. This is expected and handled
4275 * properly by the caller.
4277 return (needed->obj);
4280 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
4286 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
4287 const Elf_Vernaux *vna)
4289 const Elf_Verdef *vd;
4290 const char *vername;
4292 vername = refobj->strtab + vna->vna_name;
4293 vd = depobj->verdef;
4295 _rtld_error("%s: version %s required by %s not defined",
4296 depobj->path, vername, refobj->path);
4300 if (vd->vd_version != VER_DEF_CURRENT) {
4301 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
4302 depobj->path, vd->vd_version);
4305 if (vna->vna_hash == vd->vd_hash) {
4306 const Elf_Verdaux *aux = (const Elf_Verdaux *)
4307 ((char *)vd + vd->vd_aux);
4308 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
4311 if (vd->vd_next == 0)
4313 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4315 if (vna->vna_flags & VER_FLG_WEAK)
4317 _rtld_error("%s: version %s required by %s not found",
4318 depobj->path, vername, refobj->path);
4323 rtld_verify_object_versions(Obj_Entry *obj)
4325 const Elf_Verneed *vn;
4326 const Elf_Verdef *vd;
4327 const Elf_Verdaux *vda;
4328 const Elf_Vernaux *vna;
4329 const Obj_Entry *depobj;
4330 int maxvernum, vernum;
4332 if (obj->ver_checked)
4334 obj->ver_checked = true;
4338 * Walk over defined and required version records and figure out
4339 * max index used by any of them. Do very basic sanity checking
4343 while (vn != NULL) {
4344 if (vn->vn_version != VER_NEED_CURRENT) {
4345 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
4346 obj->path, vn->vn_version);
4349 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4351 vernum = VER_NEED_IDX(vna->vna_other);
4352 if (vernum > maxvernum)
4354 if (vna->vna_next == 0)
4356 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4358 if (vn->vn_next == 0)
4360 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4364 while (vd != NULL) {
4365 if (vd->vd_version != VER_DEF_CURRENT) {
4366 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
4367 obj->path, vd->vd_version);
4370 vernum = VER_DEF_IDX(vd->vd_ndx);
4371 if (vernum > maxvernum)
4373 if (vd->vd_next == 0)
4375 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4382 * Store version information in array indexable by version index.
4383 * Verify that object version requirements are satisfied along the
4386 obj->vernum = maxvernum + 1;
4387 obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry));
4390 while (vd != NULL) {
4391 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
4392 vernum = VER_DEF_IDX(vd->vd_ndx);
4393 assert(vernum <= maxvernum);
4394 vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
4395 obj->vertab[vernum].hash = vd->vd_hash;
4396 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
4397 obj->vertab[vernum].file = NULL;
4398 obj->vertab[vernum].flags = 0;
4400 if (vd->vd_next == 0)
4402 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4406 while (vn != NULL) {
4407 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
4410 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4412 if (check_object_provided_version(obj, depobj, vna))
4414 vernum = VER_NEED_IDX(vna->vna_other);
4415 assert(vernum <= maxvernum);
4416 obj->vertab[vernum].hash = vna->vna_hash;
4417 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
4418 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
4419 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
4420 VER_INFO_HIDDEN : 0;
4421 if (vna->vna_next == 0)
4423 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4425 if (vn->vn_next == 0)
4427 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4433 rtld_verify_versions(const Objlist *objlist)
4435 Objlist_Entry *entry;
4439 STAILQ_FOREACH(entry, objlist, link) {
4441 * Skip dummy objects or objects that have their version requirements
4444 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
4446 if (rtld_verify_object_versions(entry->obj) == -1) {
4448 if (ld_tracing == NULL)
4452 if (rc == 0 || ld_tracing != NULL)
4453 rc = rtld_verify_object_versions(&obj_rtld);
4458 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
4463 vernum = VER_NDX(obj->versyms[symnum]);
4464 if (vernum >= obj->vernum) {
4465 _rtld_error("%s: symbol %s has wrong verneed value %d",
4466 obj->path, obj->strtab + symnum, vernum);
4467 } else if (obj->vertab[vernum].hash != 0) {
4468 return &obj->vertab[vernum];
4475 _rtld_get_stack_prot(void)
4478 return (stack_prot);
4482 map_stacks_exec(RtldLockState *lockstate)
4484 void (*thr_map_stacks_exec)(void);
4486 if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
4488 thr_map_stacks_exec = (void (*)(void))(uintptr_t)
4489 get_program_var_addr("__pthread_map_stacks_exec", lockstate);
4490 if (thr_map_stacks_exec != NULL) {
4491 stack_prot |= PROT_EXEC;
4492 thr_map_stacks_exec();
4497 symlook_init(SymLook *dst, const char *name)
4500 bzero(dst, sizeof(*dst));
4502 dst->hash = elf_hash(name);
4503 dst->hash_gnu = gnu_hash(name);
4507 symlook_init_from_req(SymLook *dst, const SymLook *src)
4510 dst->name = src->name;
4511 dst->hash = src->hash;
4512 dst->hash_gnu = src->hash_gnu;
4513 dst->ventry = src->ventry;
4514 dst->flags = src->flags;
4515 dst->defobj_out = NULL;
4516 dst->sym_out = NULL;
4517 dst->lockstate = src->lockstate;
4521 * Overrides for libc_pic-provided functions.
4525 __getosreldate(void)
4535 oid[1] = KERN_OSRELDATE;
4537 len = sizeof(osrel);
4538 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
4539 if (error == 0 && osrel > 0 && len == sizeof(osrel))
4551 void (*__cleanup)(void);
4552 int __isthreaded = 0;
4553 int _thread_autoinit_dummy_decl = 1;
4556 * No unresolved symbols for rtld.
4559 __pthread_cxa_finalize(struct dl_phdr_info *a)
4564 __stack_chk_fail(void)
4567 _rtld_error("stack overflow detected; terminated");
4570 __weak_reference(__stack_chk_fail, __stack_chk_fail_local);
4576 _rtld_error("buffer overflow detected; terminated");
4581 rtld_strerror(int errnum)
4584 if (errnum < 0 || errnum >= sys_nerr)
4585 return ("Unknown error");
4586 return (sys_errlist[errnum]);