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>.
37 #include <sys/param.h>
38 #include <sys/mount.h>
41 #include <sys/sysctl.h>
43 #include <sys/utsname.h>
44 #include <sys/ktrace.h>
61 #include "rtld_printf.h"
62 #include "rtld_utrace.h"
66 typedef void (*func_ptr_type)();
67 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg);
70 * Function declarations.
72 static const char *basename(const char *);
73 static void digest_dynamic1(Obj_Entry *, int, const Elf_Dyn **,
74 const Elf_Dyn **, const Elf_Dyn **);
75 static void digest_dynamic2(Obj_Entry *, const Elf_Dyn *, const Elf_Dyn *,
77 static void digest_dynamic(Obj_Entry *, int);
78 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
79 static Obj_Entry *dlcheck(void *);
80 static Obj_Entry *dlopen_object(const char *name, int fd, Obj_Entry *refobj,
81 int lo_flags, int mode, RtldLockState *lockstate);
82 static Obj_Entry *do_load_object(int, const char *, char *, struct stat *, int);
83 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
84 static bool donelist_check(DoneList *, const Obj_Entry *);
85 static void errmsg_restore(char *);
86 static char *errmsg_save(void);
87 static void *fill_search_info(const char *, size_t, void *);
88 static char *find_library(const char *, const Obj_Entry *, int *);
89 static const char *gethints(bool);
90 static void hold_object(Obj_Entry *);
91 static void unhold_object(Obj_Entry *);
92 static void init_dag(Obj_Entry *);
93 static void init_marker(Obj_Entry *);
94 static void init_pagesizes(Elf_Auxinfo **aux_info);
95 static void init_rtld(caddr_t, Elf_Auxinfo **);
96 static void initlist_add_neededs(Needed_Entry *, Objlist *);
97 static void initlist_add_objects(Obj_Entry *, Obj_Entry *, Objlist *);
98 static void linkmap_add(Obj_Entry *);
99 static void linkmap_delete(Obj_Entry *);
100 static void load_filtees(Obj_Entry *, int flags, RtldLockState *);
101 static void unload_filtees(Obj_Entry *);
102 static int load_needed_objects(Obj_Entry *, int);
103 static int load_preload_objects(void);
104 static Obj_Entry *load_object(const char *, int fd, const Obj_Entry *, int);
105 static void map_stacks_exec(RtldLockState *);
106 static int obj_enforce_relro(Obj_Entry *);
107 static Obj_Entry *obj_from_addr(const void *);
108 static void objlist_call_fini(Objlist *, Obj_Entry *, RtldLockState *);
109 static void objlist_call_init(Objlist *, RtldLockState *);
110 static void objlist_clear(Objlist *);
111 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
112 static void objlist_init(Objlist *);
113 static void objlist_push_head(Objlist *, Obj_Entry *);
114 static void objlist_push_tail(Objlist *, Obj_Entry *);
115 static void objlist_put_after(Objlist *, Obj_Entry *, Obj_Entry *);
116 static void objlist_remove(Objlist *, Obj_Entry *);
117 static int parse_libdir(const char *);
118 static void *path_enumerate(const char *, path_enum_proc, void *);
119 static void release_object(Obj_Entry *);
120 static int relocate_object_dag(Obj_Entry *root, bool bind_now,
121 Obj_Entry *rtldobj, int flags, RtldLockState *lockstate);
122 static int relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
123 int flags, RtldLockState *lockstate);
124 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, int,
126 static int resolve_objects_ifunc(Obj_Entry *first, bool bind_now,
127 int flags, RtldLockState *lockstate);
128 static int rtld_dirname(const char *, char *);
129 static int rtld_dirname_abs(const char *, char *);
130 static void *rtld_dlopen(const char *name, int fd, int mode);
131 static void rtld_exit(void);
132 static char *search_library_path(const char *, const char *);
133 static char *search_library_pathfds(const char *, const char *, int *);
134 static const void **get_program_var_addr(const char *, RtldLockState *);
135 static void set_program_var(const char *, const void *);
136 static int symlook_default(SymLook *, const Obj_Entry *refobj);
137 static int symlook_global(SymLook *, DoneList *);
138 static void symlook_init_from_req(SymLook *, const SymLook *);
139 static int symlook_list(SymLook *, const Objlist *, DoneList *);
140 static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *);
141 static int symlook_obj1_sysv(SymLook *, const Obj_Entry *);
142 static int symlook_obj1_gnu(SymLook *, const Obj_Entry *);
143 static void trace_loaded_objects(Obj_Entry *);
144 static void unlink_object(Obj_Entry *);
145 static void unload_object(Obj_Entry *);
146 static void unref_dag(Obj_Entry *);
147 static void ref_dag(Obj_Entry *);
148 static char *origin_subst_one(Obj_Entry *, char *, const char *,
150 static char *origin_subst(Obj_Entry *, char *);
151 static bool obj_resolve_origin(Obj_Entry *obj);
152 static void preinit_main(void);
153 static int rtld_verify_versions(const Objlist *);
154 static int rtld_verify_object_versions(Obj_Entry *);
155 static void object_add_name(Obj_Entry *, const char *);
156 static int object_match_name(const Obj_Entry *, const char *);
157 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
158 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
159 struct dl_phdr_info *phdr_info);
160 static uint32_t gnu_hash(const char *);
161 static bool matched_symbol(SymLook *, const Obj_Entry *, Sym_Match_Result *,
162 const unsigned long);
164 void r_debug_state(struct r_debug *, struct link_map *) __noinline __exported;
165 void _r_debug_postinit(struct link_map *) __noinline __exported;
167 int __sys_openat(int, const char *, int, ...);
172 static char *error_message; /* Message for dlerror(), or NULL */
173 struct r_debug r_debug __exported; /* for GDB; */
174 static bool libmap_disable; /* Disable libmap */
175 static bool ld_loadfltr; /* Immediate filters processing */
176 static char *libmap_override; /* Maps to use in addition to libmap.conf */
177 static bool trust; /* False for setuid and setgid programs */
178 static bool dangerous_ld_env; /* True if environment variables have been
179 used to affect the libraries loaded */
180 static char *ld_bind_now; /* Environment variable for immediate binding */
181 static char *ld_debug; /* Environment variable for debugging */
182 static char *ld_library_path; /* Environment variable for search path */
183 static char *ld_library_dirs; /* Environment variable for library descriptors */
184 static char *ld_preload; /* Environment variable for libraries to
186 static char *ld_elf_hints_path; /* Environment variable for alternative hints path */
187 static char *ld_tracing; /* Called from ldd to print libs */
188 static char *ld_utrace; /* Use utrace() to log events. */
189 static struct obj_entry_q obj_list; /* Queue of all loaded objects */
190 static Obj_Entry *obj_main; /* The main program shared object */
191 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
192 static unsigned int obj_count; /* Number of objects in obj_list */
193 static unsigned int obj_loads; /* Number of loads of objects (gen count) */
195 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
196 STAILQ_HEAD_INITIALIZER(list_global);
197 static Objlist list_main = /* Objects loaded at program startup */
198 STAILQ_HEAD_INITIALIZER(list_main);
199 static Objlist list_fini = /* Objects needing fini() calls */
200 STAILQ_HEAD_INITIALIZER(list_fini);
202 Elf_Sym sym_zero; /* For resolving undefined weak refs. */
204 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
206 extern Elf_Dyn _DYNAMIC;
207 #pragma weak _DYNAMIC
209 int dlclose(void *) __exported;
210 char *dlerror(void) __exported;
211 void *dlopen(const char *, int) __exported;
212 void *fdlopen(int, int) __exported;
213 void *dlsym(void *, const char *) __exported;
214 dlfunc_t dlfunc(void *, const char *) __exported;
215 void *dlvsym(void *, const char *, const char *) __exported;
216 int dladdr(const void *, Dl_info *) __exported;
217 void dllockinit(void *, void *(*)(void *), void (*)(void *), void (*)(void *),
218 void (*)(void *), void (*)(void *), void (*)(void *)) __exported;
219 int dlinfo(void *, int , void *) __exported;
220 int dl_iterate_phdr(__dl_iterate_hdr_callback, void *) __exported;
221 int _rtld_addr_phdr(const void *, struct dl_phdr_info *) __exported;
222 int _rtld_get_stack_prot(void) __exported;
223 int _rtld_is_dlopened(void *) __exported;
224 void _rtld_error(const char *, ...) __exported;
226 int npagesizes, osreldate;
229 long __stack_chk_guard[8] = {0, 0, 0, 0, 0, 0, 0, 0};
231 static int stack_prot = PROT_READ | PROT_WRITE | RTLD_DEFAULT_STACK_EXEC;
232 static int max_stack_flags;
235 * Global declarations normally provided by crt1. The dynamic linker is
236 * not built with crt1, so we have to provide them ourselves.
242 * Used to pass argc, argv to init functions.
248 * Globals to control TLS allocation.
250 size_t tls_last_offset; /* Static TLS offset of last module */
251 size_t tls_last_size; /* Static TLS size of last module */
252 size_t tls_static_space; /* Static TLS space allocated */
253 size_t tls_static_max_align;
254 int tls_dtv_generation = 1; /* Used to detect when dtv size changes */
255 int tls_max_index = 1; /* Largest module index allocated */
257 bool ld_library_path_rpath = false;
260 * Globals for path names, and such
262 char *ld_elf_hints_default = _PATH_ELF_HINTS;
263 char *ld_path_libmap_conf = _PATH_LIBMAP_CONF;
264 char *ld_path_rtld = _PATH_RTLD;
265 char *ld_standard_library_path = STANDARD_LIBRARY_PATH;
266 char *ld_env_prefix = LD_;
269 * Fill in a DoneList with an allocation large enough to hold all of
270 * the currently-loaded objects. Keep this as a macro since it calls
271 * alloca and we want that to occur within the scope of the caller.
273 #define donelist_init(dlp) \
274 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
275 assert((dlp)->objs != NULL), \
276 (dlp)->num_alloc = obj_count, \
279 #define LD_UTRACE(e, h, mb, ms, r, n) do { \
280 if (ld_utrace != NULL) \
281 ld_utrace_log(e, h, mb, ms, r, n); \
285 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
286 int refcnt, const char *name)
288 struct utrace_rtld ut;
289 static const char rtld_utrace_sig[RTLD_UTRACE_SIG_SZ] = RTLD_UTRACE_SIG;
291 memcpy(ut.sig, rtld_utrace_sig, sizeof(ut.sig));
294 ut.mapbase = mapbase;
295 ut.mapsize = mapsize;
297 bzero(ut.name, sizeof(ut.name));
299 strlcpy(ut.name, name, sizeof(ut.name));
300 utrace(&ut, sizeof(ut));
303 #ifdef RTLD_VARIANT_ENV_NAMES
305 * construct the env variable based on the type of binary that's
308 static inline const char *
311 static char buffer[128];
313 strlcpy(buffer, ld_env_prefix, sizeof(buffer));
314 strlcat(buffer, var, sizeof(buffer));
322 * Main entry point for dynamic linking. The first argument is the
323 * stack pointer. The stack is expected to be laid out as described
324 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
325 * Specifically, the stack pointer points to a word containing
326 * ARGC. Following that in the stack is a null-terminated sequence
327 * of pointers to argument strings. Then comes a null-terminated
328 * sequence of pointers to environment strings. Finally, there is a
329 * sequence of "auxiliary vector" entries.
331 * The second argument points to a place to store the dynamic linker's
332 * exit procedure pointer and the third to a place to store the main
335 * The return value is the main program's entry point.
338 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
340 Elf_Auxinfo *aux_info[AT_COUNT];
348 Objlist_Entry *entry;
350 Obj_Entry *preload_tail;
351 Obj_Entry *last_interposer;
353 RtldLockState lockstate;
354 char *library_path_rpath;
359 * On entry, the dynamic linker itself has not been relocated yet.
360 * Be very careful not to reference any global data until after
361 * init_rtld has returned. It is OK to reference file-scope statics
362 * and string constants, and to call static and global functions.
365 /* Find the auxiliary vector on the stack. */
368 sp += argc + 1; /* Skip over arguments and NULL terminator */
370 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
372 aux = (Elf_Auxinfo *) sp;
374 /* Digest the auxiliary vector. */
375 for (i = 0; i < AT_COUNT; i++)
377 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
378 if (auxp->a_type < AT_COUNT)
379 aux_info[auxp->a_type] = auxp;
382 /* Initialize and relocate ourselves. */
383 assert(aux_info[AT_BASE] != NULL);
384 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
386 __progname = obj_rtld.path;
387 argv0 = argv[0] != NULL ? argv[0] : "(null)";
392 if (aux_info[AT_CANARY] != NULL &&
393 aux_info[AT_CANARY]->a_un.a_ptr != NULL) {
394 i = aux_info[AT_CANARYLEN]->a_un.a_val;
395 if (i > sizeof(__stack_chk_guard))
396 i = sizeof(__stack_chk_guard);
397 memcpy(__stack_chk_guard, aux_info[AT_CANARY]->a_un.a_ptr, i);
402 len = sizeof(__stack_chk_guard);
403 if (sysctl(mib, 2, __stack_chk_guard, &len, NULL, 0) == -1 ||
404 len != sizeof(__stack_chk_guard)) {
405 /* If sysctl was unsuccessful, use the "terminator canary". */
406 ((unsigned char *)(void *)__stack_chk_guard)[0] = 0;
407 ((unsigned char *)(void *)__stack_chk_guard)[1] = 0;
408 ((unsigned char *)(void *)__stack_chk_guard)[2] = '\n';
409 ((unsigned char *)(void *)__stack_chk_guard)[3] = 255;
413 trust = !issetugid();
415 md_abi_variant_hook(aux_info);
417 ld_bind_now = getenv(_LD("BIND_NOW"));
419 * If the process is tainted, then we un-set the dangerous environment
420 * variables. The process will be marked as tainted until setuid(2)
421 * is called. If any child process calls setuid(2) we do not want any
422 * future processes to honor the potentially un-safe variables.
425 if (unsetenv(_LD("PRELOAD")) || unsetenv(_LD("LIBMAP")) ||
426 unsetenv(_LD("LIBRARY_PATH")) || unsetenv(_LD("LIBRARY_PATH_FDS")) ||
427 unsetenv(_LD("LIBMAP_DISABLE")) ||
428 unsetenv(_LD("DEBUG")) || unsetenv(_LD("ELF_HINTS_PATH")) ||
429 unsetenv(_LD("LOADFLTR")) || unsetenv(_LD("LIBRARY_PATH_RPATH"))) {
430 _rtld_error("environment corrupt; aborting");
434 ld_debug = getenv(_LD("DEBUG"));
435 libmap_disable = getenv(_LD("LIBMAP_DISABLE")) != NULL;
436 libmap_override = getenv(_LD("LIBMAP"));
437 ld_library_path = getenv(_LD("LIBRARY_PATH"));
438 ld_library_dirs = getenv(_LD("LIBRARY_PATH_FDS"));
439 ld_preload = getenv(_LD("PRELOAD"));
440 ld_elf_hints_path = getenv(_LD("ELF_HINTS_PATH"));
441 ld_loadfltr = getenv(_LD("LOADFLTR")) != NULL;
442 library_path_rpath = getenv(_LD("LIBRARY_PATH_RPATH"));
443 if (library_path_rpath != NULL) {
444 if (library_path_rpath[0] == 'y' ||
445 library_path_rpath[0] == 'Y' ||
446 library_path_rpath[0] == '1')
447 ld_library_path_rpath = true;
449 ld_library_path_rpath = false;
451 dangerous_ld_env = libmap_disable || (libmap_override != NULL) ||
452 (ld_library_path != NULL) || (ld_preload != NULL) ||
453 (ld_elf_hints_path != NULL) || ld_loadfltr;
454 ld_tracing = getenv(_LD("TRACE_LOADED_OBJECTS"));
455 ld_utrace = getenv(_LD("UTRACE"));
457 if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0)
458 ld_elf_hints_path = ld_elf_hints_default;
460 if (ld_debug != NULL && *ld_debug != '\0')
462 dbg("%s is initialized, base address = %p", __progname,
463 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
464 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
465 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
467 dbg("initializing thread locks");
471 * Load the main program, or process its program header if it is
474 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
475 int fd = aux_info[AT_EXECFD]->a_un.a_val;
476 dbg("loading main program");
477 obj_main = map_object(fd, argv0, NULL);
479 if (obj_main == NULL)
481 max_stack_flags = obj->stack_flags;
482 } else { /* Main program already loaded. */
483 const Elf_Phdr *phdr;
487 dbg("processing main program's program header");
488 assert(aux_info[AT_PHDR] != NULL);
489 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
490 assert(aux_info[AT_PHNUM] != NULL);
491 phnum = aux_info[AT_PHNUM]->a_un.a_val;
492 assert(aux_info[AT_PHENT] != NULL);
493 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
494 assert(aux_info[AT_ENTRY] != NULL);
495 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
496 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
500 if (aux_info[AT_EXECPATH] != NULL) {
502 char buf[MAXPATHLEN];
504 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
505 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
506 if (kexecpath[0] == '/')
507 obj_main->path = kexecpath;
508 else if (getcwd(buf, sizeof(buf)) == NULL ||
509 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
510 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
511 obj_main->path = xstrdup(argv0);
513 obj_main->path = xstrdup(buf);
515 dbg("No AT_EXECPATH");
516 obj_main->path = xstrdup(argv0);
518 dbg("obj_main path %s", obj_main->path);
519 obj_main->mainprog = true;
521 if (aux_info[AT_STACKPROT] != NULL &&
522 aux_info[AT_STACKPROT]->a_un.a_val != 0)
523 stack_prot = aux_info[AT_STACKPROT]->a_un.a_val;
527 * Get the actual dynamic linker pathname from the executable if
528 * possible. (It should always be possible.) That ensures that
529 * gdb will find the right dynamic linker even if a non-standard
532 if (obj_main->interp != NULL &&
533 strcmp(obj_main->interp, obj_rtld.path) != 0) {
535 obj_rtld.path = xstrdup(obj_main->interp);
536 __progname = obj_rtld.path;
540 digest_dynamic(obj_main, 0);
541 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d",
542 obj_main->path, obj_main->valid_hash_sysv, obj_main->valid_hash_gnu,
543 obj_main->dynsymcount);
545 linkmap_add(obj_main);
546 linkmap_add(&obj_rtld);
548 /* Link the main program into the list of objects. */
549 TAILQ_INSERT_HEAD(&obj_list, obj_main, next);
553 /* Initialize a fake symbol for resolving undefined weak references. */
554 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
555 sym_zero.st_shndx = SHN_UNDEF;
556 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
559 libmap_disable = (bool)lm_init(libmap_override);
561 dbg("loading LD_PRELOAD libraries");
562 if (load_preload_objects() == -1)
564 preload_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
566 dbg("loading needed objects");
567 if (load_needed_objects(obj_main, 0) == -1)
570 /* Make a list of all objects loaded at startup. */
571 last_interposer = obj_main;
572 TAILQ_FOREACH(obj, &obj_list, next) {
575 if (obj->z_interpose && obj != obj_main) {
576 objlist_put_after(&list_main, last_interposer, obj);
577 last_interposer = obj;
579 objlist_push_tail(&list_main, obj);
584 dbg("checking for required versions");
585 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
588 if (ld_tracing) { /* We're done */
589 trace_loaded_objects(obj_main);
593 if (getenv(_LD("DUMP_REL_PRE")) != NULL) {
594 dump_relocations(obj_main);
599 * Processing tls relocations requires having the tls offsets
600 * initialized. Prepare offsets before starting initial
601 * relocation processing.
603 dbg("initializing initial thread local storage offsets");
604 STAILQ_FOREACH(entry, &list_main, link) {
606 * Allocate all the initial objects out of the static TLS
607 * block even if they didn't ask for it.
609 allocate_tls_offset(entry->obj);
612 if (relocate_objects(obj_main,
613 ld_bind_now != NULL && *ld_bind_now != '\0',
614 &obj_rtld, SYMLOOK_EARLY, NULL) == -1)
617 dbg("doing copy relocations");
618 if (do_copy_relocations(obj_main) == -1)
621 dbg("enforcing main obj relro");
622 if (obj_enforce_relro(obj_main) == -1)
625 if (getenv(_LD("DUMP_REL_POST")) != NULL) {
626 dump_relocations(obj_main);
631 * Setup TLS for main thread. This must be done after the
632 * relocations are processed, since tls initialization section
633 * might be the subject for relocations.
635 dbg("initializing initial thread local storage");
636 allocate_initial_tls(globallist_curr(TAILQ_FIRST(&obj_list)));
638 dbg("initializing key program variables");
639 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
640 set_program_var("environ", env);
641 set_program_var("__elf_aux_vector", aux);
643 /* Make a list of init functions to call. */
644 objlist_init(&initlist);
645 initlist_add_objects(globallist_curr(TAILQ_FIRST(&obj_list)),
646 preload_tail, &initlist);
648 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
650 map_stacks_exec(NULL);
653 dbg("resolving ifuncs");
654 if (resolve_objects_ifunc(obj_main,
655 ld_bind_now != NULL && *ld_bind_now != '\0', SYMLOOK_EARLY,
659 if (!obj_main->crt_no_init) {
661 * Make sure we don't call the main program's init and fini
662 * functions for binaries linked with old crt1 which calls
665 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
666 obj_main->preinit_array = obj_main->init_array =
667 obj_main->fini_array = (Elf_Addr)NULL;
670 wlock_acquire(rtld_bind_lock, &lockstate);
671 if (obj_main->crt_no_init)
673 objlist_call_init(&initlist, &lockstate);
674 _r_debug_postinit(&obj_main->linkmap);
675 objlist_clear(&initlist);
676 dbg("loading filtees");
677 TAILQ_FOREACH(obj, &obj_list, next) {
680 if (ld_loadfltr || obj->z_loadfltr)
681 load_filtees(obj, 0, &lockstate);
683 lock_release(rtld_bind_lock, &lockstate);
685 dbg("transferring control to program entry point = %p", obj_main->entry);
687 /* Return the exit procedure and the program entry point. */
688 *exit_proc = rtld_exit;
690 return (func_ptr_type) obj_main->entry;
694 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def)
699 ptr = (void *)make_function_pointer(def, obj);
700 target = call_ifunc_resolver(ptr);
701 return ((void *)target);
705 _rtld_bind(Obj_Entry *obj, Elf_Size reloff)
709 const Obj_Entry *defobj;
712 RtldLockState lockstate;
714 rlock_acquire(rtld_bind_lock, &lockstate);
715 if (sigsetjmp(lockstate.env, 0) != 0)
716 lock_upgrade(rtld_bind_lock, &lockstate);
718 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
720 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
722 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
723 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, SYMLOOK_IN_PLT,
727 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
728 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
730 target = (Elf_Addr)(defobj->relocbase + def->st_value);
732 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
733 defobj->strtab + def->st_name, basename(obj->path),
734 (void *)target, basename(defobj->path));
737 * Write the new contents for the jmpslot. Note that depending on
738 * architecture, the value which we need to return back to the
739 * lazy binding trampoline may or may not be the target
740 * address. The value returned from reloc_jmpslot() is the value
741 * that the trampoline needs.
743 target = reloc_jmpslot(where, target, defobj, obj, rel);
744 lock_release(rtld_bind_lock, &lockstate);
749 * Error reporting function. Use it like printf. If formats the message
750 * into a buffer, and sets things up so that the next call to dlerror()
751 * will return the message.
754 _rtld_error(const char *fmt, ...)
756 static char buf[512];
760 rtld_vsnprintf(buf, sizeof buf, fmt, ap);
766 * Return a dynamically-allocated copy of the current error message, if any.
771 return error_message == NULL ? NULL : xstrdup(error_message);
775 * Restore the current error message from a copy which was previously saved
776 * by errmsg_save(). The copy is freed.
779 errmsg_restore(char *saved_msg)
781 if (saved_msg == NULL)
782 error_message = NULL;
784 _rtld_error("%s", saved_msg);
790 basename(const char *name)
792 const char *p = strrchr(name, '/');
793 return p != NULL ? p + 1 : name;
796 static struct utsname uts;
799 origin_subst_one(Obj_Entry *obj, char *real, const char *kw,
800 const char *subst, bool may_free)
802 char *p, *p1, *res, *resp;
803 int subst_len, kw_len, subst_count, old_len, new_len;
808 * First, count the number of the keyword occurrences, to
809 * preallocate the final string.
811 for (p = real, subst_count = 0;; p = p1 + kw_len, subst_count++) {
818 * If the keyword is not found, just return.
820 * Return non-substituted string if resolution failed. We
821 * cannot do anything more reasonable, the failure mode of the
822 * caller is unresolved library anyway.
824 if (subst_count == 0 || (obj != NULL && !obj_resolve_origin(obj)))
825 return (may_free ? real : xstrdup(real));
827 subst = obj->origin_path;
830 * There is indeed something to substitute. Calculate the
831 * length of the resulting string, and allocate it.
833 subst_len = strlen(subst);
834 old_len = strlen(real);
835 new_len = old_len + (subst_len - kw_len) * subst_count;
836 res = xmalloc(new_len + 1);
839 * Now, execute the substitution loop.
841 for (p = real, resp = res, *resp = '\0';;) {
844 /* Copy the prefix before keyword. */
845 memcpy(resp, p, p1 - p);
847 /* Keyword replacement. */
848 memcpy(resp, subst, subst_len);
856 /* Copy to the end of string and finish. */
864 origin_subst(Obj_Entry *obj, char *real)
866 char *res1, *res2, *res3, *res4;
868 if (obj == NULL || !trust)
869 return (xstrdup(real));
870 if (uts.sysname[0] == '\0') {
871 if (uname(&uts) != 0) {
872 _rtld_error("utsname failed: %d", errno);
876 res1 = origin_subst_one(obj, real, "$ORIGIN", NULL, false);
877 res2 = origin_subst_one(NULL, res1, "$OSNAME", uts.sysname, true);
878 res3 = origin_subst_one(NULL, res2, "$OSREL", uts.release, true);
879 res4 = origin_subst_one(NULL, res3, "$PLATFORM", uts.machine, true);
886 const char *msg = dlerror();
890 rtld_fdputstr(STDERR_FILENO, msg);
891 rtld_fdputchar(STDERR_FILENO, '\n');
896 * Process a shared object's DYNAMIC section, and save the important
897 * information in its Obj_Entry structure.
900 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
901 const Elf_Dyn **dyn_soname, const Elf_Dyn **dyn_runpath)
904 Needed_Entry **needed_tail = &obj->needed;
905 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
906 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
907 const Elf_Hashelt *hashtab;
908 const Elf32_Word *hashval;
909 Elf32_Word bkt, nmaskwords;
911 int plttype = DT_REL;
917 obj->bind_now = false;
918 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
919 switch (dynp->d_tag) {
922 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
926 obj->relsize = dynp->d_un.d_val;
930 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
934 obj->pltrel = (const Elf_Rel *)
935 (obj->relocbase + dynp->d_un.d_ptr);
939 obj->pltrelsize = dynp->d_un.d_val;
943 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
947 obj->relasize = dynp->d_un.d_val;
951 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
955 plttype = dynp->d_un.d_val;
956 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
960 obj->symtab = (const Elf_Sym *)
961 (obj->relocbase + dynp->d_un.d_ptr);
965 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
969 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
973 obj->strsize = dynp->d_un.d_val;
977 obj->verneed = (const Elf_Verneed *) (obj->relocbase +
982 obj->verneednum = dynp->d_un.d_val;
986 obj->verdef = (const Elf_Verdef *) (obj->relocbase +
991 obj->verdefnum = dynp->d_un.d_val;
995 obj->versyms = (const Elf_Versym *)(obj->relocbase +
1001 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1003 obj->nbuckets = hashtab[0];
1004 obj->nchains = hashtab[1];
1005 obj->buckets = hashtab + 2;
1006 obj->chains = obj->buckets + obj->nbuckets;
1007 obj->valid_hash_sysv = obj->nbuckets > 0 && obj->nchains > 0 &&
1008 obj->buckets != NULL;
1014 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1016 obj->nbuckets_gnu = hashtab[0];
1017 obj->symndx_gnu = hashtab[1];
1018 nmaskwords = hashtab[2];
1019 bloom_size32 = (__ELF_WORD_SIZE / 32) * nmaskwords;
1020 obj->maskwords_bm_gnu = nmaskwords - 1;
1021 obj->shift2_gnu = hashtab[3];
1022 obj->bloom_gnu = (Elf_Addr *) (hashtab + 4);
1023 obj->buckets_gnu = hashtab + 4 + bloom_size32;
1024 obj->chain_zero_gnu = obj->buckets_gnu + obj->nbuckets_gnu -
1026 /* Number of bitmask words is required to be power of 2 */
1027 obj->valid_hash_gnu = powerof2(nmaskwords) &&
1028 obj->nbuckets_gnu > 0 && obj->buckets_gnu != NULL;
1034 Needed_Entry *nep = NEW(Needed_Entry);
1035 nep->name = dynp->d_un.d_val;
1040 needed_tail = &nep->next;
1046 Needed_Entry *nep = NEW(Needed_Entry);
1047 nep->name = dynp->d_un.d_val;
1051 *needed_filtees_tail = nep;
1052 needed_filtees_tail = &nep->next;
1058 Needed_Entry *nep = NEW(Needed_Entry);
1059 nep->name = dynp->d_un.d_val;
1063 *needed_aux_filtees_tail = nep;
1064 needed_aux_filtees_tail = &nep->next;
1069 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
1073 obj->textrel = true;
1077 obj->symbolic = true;
1082 * We have to wait until later to process this, because we
1083 * might not have gotten the address of the string table yet.
1093 *dyn_runpath = dynp;
1097 obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1100 case DT_PREINIT_ARRAY:
1101 obj->preinit_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1104 case DT_PREINIT_ARRAYSZ:
1105 obj->preinit_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1109 obj->init_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1112 case DT_INIT_ARRAYSZ:
1113 obj->init_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1117 obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1121 obj->fini_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1124 case DT_FINI_ARRAYSZ:
1125 obj->fini_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1129 * Don't process DT_DEBUG on MIPS as the dynamic section
1130 * is mapped read-only. DT_MIPS_RLD_MAP is used instead.
1136 dbg("Filling in DT_DEBUG entry");
1137 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
1142 if (dynp->d_un.d_val & DF_ORIGIN)
1143 obj->z_origin = true;
1144 if (dynp->d_un.d_val & DF_SYMBOLIC)
1145 obj->symbolic = true;
1146 if (dynp->d_un.d_val & DF_TEXTREL)
1147 obj->textrel = true;
1148 if (dynp->d_un.d_val & DF_BIND_NOW)
1149 obj->bind_now = true;
1150 /*if (dynp->d_un.d_val & DF_STATIC_TLS)
1154 case DT_MIPS_LOCAL_GOTNO:
1155 obj->local_gotno = dynp->d_un.d_val;
1158 case DT_MIPS_SYMTABNO:
1159 obj->symtabno = dynp->d_un.d_val;
1162 case DT_MIPS_GOTSYM:
1163 obj->gotsym = dynp->d_un.d_val;
1166 case DT_MIPS_RLD_MAP:
1167 *((Elf_Addr *)(dynp->d_un.d_ptr)) = (Elf_Addr) &r_debug;
1171 #ifdef __powerpc64__
1172 case DT_PPC64_GLINK:
1173 obj->glink = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1178 if (dynp->d_un.d_val & DF_1_NOOPEN)
1179 obj->z_noopen = true;
1180 if (dynp->d_un.d_val & DF_1_ORIGIN)
1181 obj->z_origin = true;
1182 if (dynp->d_un.d_val & DF_1_GLOBAL)
1183 obj->z_global = true;
1184 if (dynp->d_un.d_val & DF_1_BIND_NOW)
1185 obj->bind_now = true;
1186 if (dynp->d_un.d_val & DF_1_NODELETE)
1187 obj->z_nodelete = true;
1188 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1189 obj->z_loadfltr = true;
1190 if (dynp->d_un.d_val & DF_1_INTERPOSE)
1191 obj->z_interpose = true;
1192 if (dynp->d_un.d_val & DF_1_NODEFLIB)
1193 obj->z_nodeflib = true;
1198 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1205 obj->traced = false;
1207 if (plttype == DT_RELA) {
1208 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1210 obj->pltrelasize = obj->pltrelsize;
1211 obj->pltrelsize = 0;
1214 /* Determine size of dynsym table (equal to nchains of sysv hash) */
1215 if (obj->valid_hash_sysv)
1216 obj->dynsymcount = obj->nchains;
1217 else if (obj->valid_hash_gnu) {
1218 obj->dynsymcount = 0;
1219 for (bkt = 0; bkt < obj->nbuckets_gnu; bkt++) {
1220 if (obj->buckets_gnu[bkt] == 0)
1222 hashval = &obj->chain_zero_gnu[obj->buckets_gnu[bkt]];
1225 while ((*hashval++ & 1u) == 0);
1227 obj->dynsymcount += obj->symndx_gnu;
1232 obj_resolve_origin(Obj_Entry *obj)
1235 if (obj->origin_path != NULL)
1237 obj->origin_path = xmalloc(PATH_MAX);
1238 return (rtld_dirname_abs(obj->path, obj->origin_path) != -1);
1242 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1243 const Elf_Dyn *dyn_soname, const Elf_Dyn *dyn_runpath)
1246 if (obj->z_origin && !obj_resolve_origin(obj))
1249 if (dyn_runpath != NULL) {
1250 obj->runpath = (char *)obj->strtab + dyn_runpath->d_un.d_val;
1251 obj->runpath = origin_subst(obj, obj->runpath);
1252 } else if (dyn_rpath != NULL) {
1253 obj->rpath = (char *)obj->strtab + dyn_rpath->d_un.d_val;
1254 obj->rpath = origin_subst(obj, obj->rpath);
1256 if (dyn_soname != NULL)
1257 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1261 digest_dynamic(Obj_Entry *obj, int early)
1263 const Elf_Dyn *dyn_rpath;
1264 const Elf_Dyn *dyn_soname;
1265 const Elf_Dyn *dyn_runpath;
1267 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname, &dyn_runpath);
1268 digest_dynamic2(obj, dyn_rpath, dyn_soname, dyn_runpath);
1272 * Process a shared object's program header. This is used only for the
1273 * main program, when the kernel has already loaded the main program
1274 * into memory before calling the dynamic linker. It creates and
1275 * returns an Obj_Entry structure.
1278 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1281 const Elf_Phdr *phlimit = phdr + phnum;
1283 Elf_Addr note_start, note_end;
1287 for (ph = phdr; ph < phlimit; ph++) {
1288 if (ph->p_type != PT_PHDR)
1292 obj->phsize = ph->p_memsz;
1293 obj->relocbase = (caddr_t)phdr - ph->p_vaddr;
1297 obj->stack_flags = PF_X | PF_R | PF_W;
1299 for (ph = phdr; ph < phlimit; ph++) {
1300 switch (ph->p_type) {
1303 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1307 if (nsegs == 0) { /* First load segment */
1308 obj->vaddrbase = trunc_page(ph->p_vaddr);
1309 obj->mapbase = obj->vaddrbase + obj->relocbase;
1310 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
1312 } else { /* Last load segment */
1313 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1320 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1325 obj->tlssize = ph->p_memsz;
1326 obj->tlsalign = ph->p_align;
1327 obj->tlsinitsize = ph->p_filesz;
1328 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1332 obj->stack_flags = ph->p_flags;
1336 obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1337 obj->relro_size = round_page(ph->p_memsz);
1341 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
1342 note_end = note_start + ph->p_filesz;
1343 digest_notes(obj, note_start, note_end);
1348 _rtld_error("%s: too few PT_LOAD segments", path);
1357 digest_notes(Obj_Entry *obj, Elf_Addr note_start, Elf_Addr note_end)
1359 const Elf_Note *note;
1360 const char *note_name;
1363 for (note = (const Elf_Note *)note_start; (Elf_Addr)note < note_end;
1364 note = (const Elf_Note *)((const char *)(note + 1) +
1365 roundup2(note->n_namesz, sizeof(Elf32_Addr)) +
1366 roundup2(note->n_descsz, sizeof(Elf32_Addr)))) {
1367 if (note->n_namesz != sizeof(NOTE_FREEBSD_VENDOR) ||
1368 note->n_descsz != sizeof(int32_t))
1370 if (note->n_type != NT_FREEBSD_ABI_TAG &&
1371 note->n_type != NT_FREEBSD_NOINIT_TAG)
1373 note_name = (const char *)(note + 1);
1374 if (strncmp(NOTE_FREEBSD_VENDOR, note_name,
1375 sizeof(NOTE_FREEBSD_VENDOR)) != 0)
1377 switch (note->n_type) {
1378 case NT_FREEBSD_ABI_TAG:
1379 /* FreeBSD osrel note */
1380 p = (uintptr_t)(note + 1);
1381 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1382 obj->osrel = *(const int32_t *)(p);
1383 dbg("note osrel %d", obj->osrel);
1385 case NT_FREEBSD_NOINIT_TAG:
1386 /* FreeBSD 'crt does not call init' note */
1387 obj->crt_no_init = true;
1388 dbg("note crt_no_init");
1395 dlcheck(void *handle)
1399 TAILQ_FOREACH(obj, &obj_list, next) {
1400 if (obj == (Obj_Entry *) handle)
1404 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1405 _rtld_error("Invalid shared object handle %p", handle);
1412 * If the given object is already in the donelist, return true. Otherwise
1413 * add the object to the list and return false.
1416 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1420 for (i = 0; i < dlp->num_used; i++)
1421 if (dlp->objs[i] == obj)
1424 * Our donelist allocation should always be sufficient. But if
1425 * our threads locking isn't working properly, more shared objects
1426 * could have been loaded since we allocated the list. That should
1427 * never happen, but we'll handle it properly just in case it does.
1429 if (dlp->num_used < dlp->num_alloc)
1430 dlp->objs[dlp->num_used++] = obj;
1435 * Hash function for symbol table lookup. Don't even think about changing
1436 * this. It is specified by the System V ABI.
1439 elf_hash(const char *name)
1441 const unsigned char *p = (const unsigned char *) name;
1442 unsigned long h = 0;
1445 while (*p != '\0') {
1446 h = (h << 4) + *p++;
1447 if ((g = h & 0xf0000000) != 0)
1455 * The GNU hash function is the Daniel J. Bernstein hash clipped to 32 bits
1456 * unsigned in case it's implemented with a wider type.
1459 gnu_hash(const char *s)
1465 for (c = *s; c != '\0'; c = *++s)
1467 return (h & 0xffffffff);
1472 * Find the library with the given name, and return its full pathname.
1473 * The returned string is dynamically allocated. Generates an error
1474 * message and returns NULL if the library cannot be found.
1476 * If the second argument is non-NULL, then it refers to an already-
1477 * loaded shared object, whose library search path will be searched.
1479 * If a library is successfully located via LD_LIBRARY_PATH_FDS, its
1480 * descriptor (which is close-on-exec) will be passed out via the third
1483 * The search order is:
1484 * DT_RPATH in the referencing file _unless_ DT_RUNPATH is present (1)
1485 * DT_RPATH of the main object if DSO without defined DT_RUNPATH (1)
1487 * DT_RUNPATH in the referencing file
1488 * ldconfig hints (if -z nodefaultlib, filter out default library directories
1490 * /lib:/usr/lib _unless_ the referencing file is linked with -z nodefaultlib
1492 * (1) Handled in digest_dynamic2 - rpath left NULL if runpath defined.
1495 find_library(const char *xname, const Obj_Entry *refobj, int *fdp)
1499 bool nodeflib, objgiven;
1501 objgiven = refobj != NULL;
1502 if (strchr(xname, '/') != NULL) { /* Hard coded pathname */
1503 if (xname[0] != '/' && !trust) {
1504 _rtld_error("Absolute pathname required for shared object \"%s\"",
1508 return (origin_subst(__DECONST(Obj_Entry *, refobj),
1509 __DECONST(char *, xname)));
1512 if (libmap_disable || !objgiven ||
1513 (name = lm_find(refobj->path, xname)) == NULL)
1514 name = (char *)xname;
1516 dbg(" Searching for \"%s\"", name);
1519 * If refobj->rpath != NULL, then refobj->runpath is NULL. Fall
1520 * back to pre-conforming behaviour if user requested so with
1521 * LD_LIBRARY_PATH_RPATH environment variable and ignore -z
1524 if (objgiven && refobj->rpath != NULL && ld_library_path_rpath) {
1525 if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
1527 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
1528 (pathname = search_library_pathfds(name, ld_library_dirs, fdp)) != NULL ||
1529 (pathname = search_library_path(name, gethints(false))) != NULL ||
1530 (pathname = search_library_path(name, ld_standard_library_path)) != NULL)
1533 nodeflib = objgiven ? refobj->z_nodeflib : false;
1535 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
1536 (objgiven && refobj->runpath == NULL && refobj != obj_main &&
1537 (pathname = search_library_path(name, obj_main->rpath)) != NULL) ||
1538 (pathname = search_library_path(name, ld_library_path)) != NULL ||
1540 (pathname = search_library_path(name, refobj->runpath)) != NULL) ||
1541 (pathname = search_library_pathfds(name, ld_library_dirs, fdp)) != NULL ||
1542 (pathname = search_library_path(name, gethints(nodeflib))) != NULL ||
1543 (objgiven && !nodeflib &&
1544 (pathname = search_library_path(name, ld_standard_library_path)) != NULL))
1548 if (objgiven && refobj->path != NULL) {
1549 _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
1550 name, basename(refobj->path));
1552 _rtld_error("Shared object \"%s\" not found", name);
1558 * Given a symbol number in a referencing object, find the corresponding
1559 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1560 * no definition was found. Returns a pointer to the Obj_Entry of the
1561 * defining object via the reference parameter DEFOBJ_OUT.
1564 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1565 const Obj_Entry **defobj_out, int flags, SymCache *cache,
1566 RtldLockState *lockstate)
1570 const Obj_Entry *defobj;
1576 * If we have already found this symbol, get the information from
1579 if (symnum >= refobj->dynsymcount)
1580 return NULL; /* Bad object */
1581 if (cache != NULL && cache[symnum].sym != NULL) {
1582 *defobj_out = cache[symnum].obj;
1583 return cache[symnum].sym;
1586 ref = refobj->symtab + symnum;
1587 name = refobj->strtab + ref->st_name;
1592 * We don't have to do a full scale lookup if the symbol is local.
1593 * We know it will bind to the instance in this load module; to
1594 * which we already have a pointer (ie ref). By not doing a lookup,
1595 * we not only improve performance, but it also avoids unresolvable
1596 * symbols when local symbols are not in the hash table. This has
1597 * been seen with the ia64 toolchain.
1599 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1600 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1601 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1604 symlook_init(&req, name);
1606 req.ventry = fetch_ventry(refobj, symnum);
1607 req.lockstate = lockstate;
1608 res = symlook_default(&req, refobj);
1611 defobj = req.defobj_out;
1619 * If we found no definition and the reference is weak, treat the
1620 * symbol as having the value zero.
1622 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1628 *defobj_out = defobj;
1629 /* Record the information in the cache to avoid subsequent lookups. */
1630 if (cache != NULL) {
1631 cache[symnum].sym = def;
1632 cache[symnum].obj = defobj;
1635 if (refobj != &obj_rtld)
1636 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1642 * Return the search path from the ldconfig hints file, reading it if
1643 * necessary. If nostdlib is true, then the default search paths are
1644 * not added to result.
1646 * Returns NULL if there are problems with the hints file,
1647 * or if the search path there is empty.
1650 gethints(bool nostdlib)
1652 static char *hints, *filtered_path;
1653 static struct elfhints_hdr hdr;
1654 struct fill_search_info_args sargs, hargs;
1655 struct dl_serinfo smeta, hmeta, *SLPinfo, *hintinfo;
1656 struct dl_serpath *SLPpath, *hintpath;
1658 struct stat hint_stat;
1659 unsigned int SLPndx, hintndx, fndx, fcount;
1665 /* First call, read the hints file */
1666 if (hints == NULL) {
1667 /* Keep from trying again in case the hints file is bad. */
1670 if ((fd = open(ld_elf_hints_path, O_RDONLY | O_CLOEXEC)) == -1)
1674 * Check of hdr.dirlistlen value against type limit
1675 * intends to pacify static analyzers. Further
1676 * paranoia leads to checks that dirlist is fully
1677 * contained in the file range.
1679 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1680 hdr.magic != ELFHINTS_MAGIC ||
1681 hdr.version != 1 || hdr.dirlistlen > UINT_MAX / 2 ||
1682 fstat(fd, &hint_stat) == -1) {
1689 if (dl + hdr.dirlist < dl)
1692 if (dl + hdr.dirlistlen < dl)
1694 dl += hdr.dirlistlen;
1695 if (dl > hint_stat.st_size)
1697 p = xmalloc(hdr.dirlistlen + 1);
1699 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1700 read(fd, p, hdr.dirlistlen + 1) !=
1701 (ssize_t)hdr.dirlistlen + 1 || p[hdr.dirlistlen] != '\0') {
1710 * If caller agreed to receive list which includes the default
1711 * paths, we are done. Otherwise, if we still did not
1712 * calculated filtered result, do it now.
1715 return (hints[0] != '\0' ? hints : NULL);
1716 if (filtered_path != NULL)
1720 * Obtain the list of all configured search paths, and the
1721 * list of the default paths.
1723 * First estimate the size of the results.
1725 smeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1727 hmeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1730 sargs.request = RTLD_DI_SERINFOSIZE;
1731 sargs.serinfo = &smeta;
1732 hargs.request = RTLD_DI_SERINFOSIZE;
1733 hargs.serinfo = &hmeta;
1735 path_enumerate(ld_standard_library_path, fill_search_info, &sargs);
1736 path_enumerate(hints, fill_search_info, &hargs);
1738 SLPinfo = xmalloc(smeta.dls_size);
1739 hintinfo = xmalloc(hmeta.dls_size);
1742 * Next fetch both sets of paths.
1744 sargs.request = RTLD_DI_SERINFO;
1745 sargs.serinfo = SLPinfo;
1746 sargs.serpath = &SLPinfo->dls_serpath[0];
1747 sargs.strspace = (char *)&SLPinfo->dls_serpath[smeta.dls_cnt];
1749 hargs.request = RTLD_DI_SERINFO;
1750 hargs.serinfo = hintinfo;
1751 hargs.serpath = &hintinfo->dls_serpath[0];
1752 hargs.strspace = (char *)&hintinfo->dls_serpath[hmeta.dls_cnt];
1754 path_enumerate(ld_standard_library_path, fill_search_info, &sargs);
1755 path_enumerate(hints, fill_search_info, &hargs);
1758 * Now calculate the difference between two sets, by excluding
1759 * standard paths from the full set.
1763 filtered_path = xmalloc(hdr.dirlistlen + 1);
1764 hintpath = &hintinfo->dls_serpath[0];
1765 for (hintndx = 0; hintndx < hmeta.dls_cnt; hintndx++, hintpath++) {
1767 SLPpath = &SLPinfo->dls_serpath[0];
1769 * Check each standard path against current.
1771 for (SLPndx = 0; SLPndx < smeta.dls_cnt; SLPndx++, SLPpath++) {
1772 /* matched, skip the path */
1773 if (!strcmp(hintpath->dls_name, SLPpath->dls_name)) {
1781 * Not matched against any standard path, add the path
1782 * to result. Separate consequtive paths with ':'.
1785 filtered_path[fndx] = ':';
1789 flen = strlen(hintpath->dls_name);
1790 strncpy((filtered_path + fndx), hintpath->dls_name, flen);
1793 filtered_path[fndx] = '\0';
1799 return (filtered_path[0] != '\0' ? filtered_path : NULL);
1803 init_dag(Obj_Entry *root)
1805 const Needed_Entry *needed;
1806 const Objlist_Entry *elm;
1809 if (root->dag_inited)
1811 donelist_init(&donelist);
1813 /* Root object belongs to own DAG. */
1814 objlist_push_tail(&root->dldags, root);
1815 objlist_push_tail(&root->dagmembers, root);
1816 donelist_check(&donelist, root);
1819 * Add dependencies of root object to DAG in breadth order
1820 * by exploiting the fact that each new object get added
1821 * to the tail of the dagmembers list.
1823 STAILQ_FOREACH(elm, &root->dagmembers, link) {
1824 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
1825 if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
1827 objlist_push_tail(&needed->obj->dldags, root);
1828 objlist_push_tail(&root->dagmembers, needed->obj);
1831 root->dag_inited = true;
1835 init_marker(Obj_Entry *marker)
1838 bzero(marker, sizeof(*marker));
1839 marker->marker = true;
1843 globallist_curr(const Obj_Entry *obj)
1850 return (__DECONST(Obj_Entry *, obj));
1851 obj = TAILQ_PREV(obj, obj_entry_q, next);
1856 globallist_next(const Obj_Entry *obj)
1860 obj = TAILQ_NEXT(obj, next);
1864 return (__DECONST(Obj_Entry *, obj));
1868 /* Prevent the object from being unmapped while the bind lock is dropped. */
1870 hold_object(Obj_Entry *obj)
1877 unhold_object(Obj_Entry *obj)
1880 assert(obj->holdcount > 0);
1881 if (--obj->holdcount == 0 && obj->unholdfree)
1882 release_object(obj);
1886 process_z(Obj_Entry *root)
1888 const Objlist_Entry *elm;
1892 * Walk over object DAG and process every dependent object
1893 * that is marked as DF_1_NODELETE or DF_1_GLOBAL. They need
1894 * to grow their own DAG.
1896 * For DF_1_GLOBAL, DAG is required for symbol lookups in
1897 * symlook_global() to work.
1899 * For DF_1_NODELETE, the DAG should have its reference upped.
1901 STAILQ_FOREACH(elm, &root->dagmembers, link) {
1905 if (obj->z_nodelete && !obj->ref_nodel) {
1906 dbg("obj %s -z nodelete", obj->path);
1909 obj->ref_nodel = true;
1911 if (obj->z_global && objlist_find(&list_global, obj) == NULL) {
1912 dbg("obj %s -z global", obj->path);
1913 objlist_push_tail(&list_global, obj);
1919 * Initialize the dynamic linker. The argument is the address at which
1920 * the dynamic linker has been mapped into memory. The primary task of
1921 * this function is to relocate the dynamic linker.
1924 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
1926 Obj_Entry objtmp; /* Temporary rtld object */
1927 const Elf_Ehdr *ehdr;
1928 const Elf_Dyn *dyn_rpath;
1929 const Elf_Dyn *dyn_soname;
1930 const Elf_Dyn *dyn_runpath;
1932 #ifdef RTLD_INIT_PAGESIZES_EARLY
1933 /* The page size is required by the dynamic memory allocator. */
1934 init_pagesizes(aux_info);
1938 * Conjure up an Obj_Entry structure for the dynamic linker.
1940 * The "path" member can't be initialized yet because string constants
1941 * cannot yet be accessed. Below we will set it correctly.
1943 memset(&objtmp, 0, sizeof(objtmp));
1946 objtmp.mapbase = mapbase;
1948 objtmp.relocbase = mapbase;
1951 objtmp.dynamic = rtld_dynamic(&objtmp);
1952 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname, &dyn_runpath);
1953 assert(objtmp.needed == NULL);
1954 #if !defined(__mips__)
1955 /* MIPS has a bogus DT_TEXTREL. */
1956 assert(!objtmp.textrel);
1959 * Temporarily put the dynamic linker entry into the object list, so
1960 * that symbols can be found.
1962 relocate_objects(&objtmp, true, &objtmp, 0, NULL);
1964 ehdr = (Elf_Ehdr *)mapbase;
1965 objtmp.phdr = (Elf_Phdr *)((char *)mapbase + ehdr->e_phoff);
1966 objtmp.phsize = ehdr->e_phnum * sizeof(objtmp.phdr[0]);
1968 /* Initialize the object list. */
1969 TAILQ_INIT(&obj_list);
1971 /* Now that non-local variables can be accesses, copy out obj_rtld. */
1972 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1974 #ifndef RTLD_INIT_PAGESIZES_EARLY
1975 /* The page size is required by the dynamic memory allocator. */
1976 init_pagesizes(aux_info);
1979 if (aux_info[AT_OSRELDATE] != NULL)
1980 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
1982 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname, dyn_runpath);
1984 /* Replace the path with a dynamically allocated copy. */
1985 obj_rtld.path = xstrdup(ld_path_rtld);
1987 r_debug.r_brk = r_debug_state;
1988 r_debug.r_state = RT_CONSISTENT;
1992 * Retrieve the array of supported page sizes. The kernel provides the page
1993 * sizes in increasing order.
1996 init_pagesizes(Elf_Auxinfo **aux_info)
1998 static size_t psa[MAXPAGESIZES];
2002 if (aux_info[AT_PAGESIZES] != NULL && aux_info[AT_PAGESIZESLEN] !=
2004 size = aux_info[AT_PAGESIZESLEN]->a_un.a_val;
2005 pagesizes = aux_info[AT_PAGESIZES]->a_un.a_ptr;
2008 if (sysctlnametomib("hw.pagesizes", mib, &len) == 0)
2011 /* As a fallback, retrieve the base page size. */
2012 size = sizeof(psa[0]);
2013 if (aux_info[AT_PAGESZ] != NULL) {
2014 psa[0] = aux_info[AT_PAGESZ]->a_un.a_val;
2018 mib[1] = HW_PAGESIZE;
2022 if (sysctl(mib, len, psa, &size, NULL, 0) == -1) {
2023 _rtld_error("sysctl for hw.pagesize(s) failed");
2029 npagesizes = size / sizeof(pagesizes[0]);
2030 /* Discard any invalid entries at the end of the array. */
2031 while (npagesizes > 0 && pagesizes[npagesizes - 1] == 0)
2036 * Add the init functions from a needed object list (and its recursive
2037 * needed objects) to "list". This is not used directly; it is a helper
2038 * function for initlist_add_objects(). The write lock must be held
2039 * when this function is called.
2042 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
2044 /* Recursively process the successor needed objects. */
2045 if (needed->next != NULL)
2046 initlist_add_neededs(needed->next, list);
2048 /* Process the current needed object. */
2049 if (needed->obj != NULL)
2050 initlist_add_objects(needed->obj, needed->obj, list);
2054 * Scan all of the DAGs rooted in the range of objects from "obj" to
2055 * "tail" and add their init functions to "list". This recurses over
2056 * the DAGs and ensure the proper init ordering such that each object's
2057 * needed libraries are initialized before the object itself. At the
2058 * same time, this function adds the objects to the global finalization
2059 * list "list_fini" in the opposite order. The write lock must be
2060 * held when this function is called.
2063 initlist_add_objects(Obj_Entry *obj, Obj_Entry *tail, Objlist *list)
2067 if (obj->init_scanned || obj->init_done)
2069 obj->init_scanned = true;
2071 /* Recursively process the successor objects. */
2072 nobj = globallist_next(obj);
2073 if (nobj != NULL && obj != tail)
2074 initlist_add_objects(nobj, tail, list);
2076 /* Recursively process the needed objects. */
2077 if (obj->needed != NULL)
2078 initlist_add_neededs(obj->needed, list);
2079 if (obj->needed_filtees != NULL)
2080 initlist_add_neededs(obj->needed_filtees, list);
2081 if (obj->needed_aux_filtees != NULL)
2082 initlist_add_neededs(obj->needed_aux_filtees, list);
2084 /* Add the object to the init list. */
2085 if (obj->preinit_array != (Elf_Addr)NULL || obj->init != (Elf_Addr)NULL ||
2086 obj->init_array != (Elf_Addr)NULL)
2087 objlist_push_tail(list, obj);
2089 /* Add the object to the global fini list in the reverse order. */
2090 if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL)
2091 && !obj->on_fini_list) {
2092 objlist_push_head(&list_fini, obj);
2093 obj->on_fini_list = true;
2098 #define FPTR_TARGET(f) ((Elf_Addr) (f))
2102 free_needed_filtees(Needed_Entry *n)
2104 Needed_Entry *needed, *needed1;
2106 for (needed = n; needed != NULL; needed = needed->next) {
2107 if (needed->obj != NULL) {
2108 dlclose(needed->obj);
2112 for (needed = n; needed != NULL; needed = needed1) {
2113 needed1 = needed->next;
2119 unload_filtees(Obj_Entry *obj)
2122 free_needed_filtees(obj->needed_filtees);
2123 obj->needed_filtees = NULL;
2124 free_needed_filtees(obj->needed_aux_filtees);
2125 obj->needed_aux_filtees = NULL;
2126 obj->filtees_loaded = false;
2130 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags,
2131 RtldLockState *lockstate)
2134 for (; needed != NULL; needed = needed->next) {
2135 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
2136 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
2137 RTLD_LOCAL, lockstate);
2142 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
2145 lock_restart_for_upgrade(lockstate);
2146 if (!obj->filtees_loaded) {
2147 load_filtee1(obj, obj->needed_filtees, flags, lockstate);
2148 load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate);
2149 obj->filtees_loaded = true;
2154 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
2158 for (; needed != NULL; needed = needed->next) {
2159 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
2160 flags & ~RTLD_LO_NOLOAD);
2161 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
2168 * Given a shared object, traverse its list of needed objects, and load
2169 * each of them. Returns 0 on success. Generates an error message and
2170 * returns -1 on failure.
2173 load_needed_objects(Obj_Entry *first, int flags)
2177 for (obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
2180 if (process_needed(obj, obj->needed, flags) == -1)
2187 load_preload_objects(void)
2189 char *p = ld_preload;
2191 static const char delim[] = " \t:;";
2196 p += strspn(p, delim);
2197 while (*p != '\0') {
2198 size_t len = strcspn(p, delim);
2203 obj = load_object(p, -1, NULL, 0);
2205 return -1; /* XXX - cleanup */
2206 obj->z_interpose = true;
2209 p += strspn(p, delim);
2211 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
2216 printable_path(const char *path)
2219 return (path == NULL ? "<unknown>" : path);
2223 * Load a shared object into memory, if it is not already loaded. The
2224 * object may be specified by name or by user-supplied file descriptor
2225 * fd_u. In the later case, the fd_u descriptor is not closed, but its
2228 * Returns a pointer to the Obj_Entry for the object. Returns NULL
2232 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
2241 TAILQ_FOREACH(obj, &obj_list, next) {
2242 if (obj->marker || obj->doomed)
2244 if (object_match_name(obj, name))
2248 path = find_library(name, refobj, &fd);
2256 * search_library_pathfds() opens a fresh file descriptor for the
2257 * library, so there is no need to dup().
2259 } else if (fd_u == -1) {
2261 * If we didn't find a match by pathname, or the name is not
2262 * supplied, open the file and check again by device and inode.
2263 * This avoids false mismatches caused by multiple links or ".."
2266 * To avoid a race, we open the file and use fstat() rather than
2269 if ((fd = open(path, O_RDONLY | O_CLOEXEC | O_VERIFY)) == -1) {
2270 _rtld_error("Cannot open \"%s\"", path);
2275 fd = fcntl(fd_u, F_DUPFD_CLOEXEC, 0);
2277 _rtld_error("Cannot dup fd");
2282 if (fstat(fd, &sb) == -1) {
2283 _rtld_error("Cannot fstat \"%s\"", printable_path(path));
2288 TAILQ_FOREACH(obj, &obj_list, next) {
2289 if (obj->marker || obj->doomed)
2291 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
2294 if (obj != NULL && name != NULL) {
2295 object_add_name(obj, name);
2300 if (flags & RTLD_LO_NOLOAD) {
2306 /* First use of this object, so we must map it in */
2307 obj = do_load_object(fd, name, path, &sb, flags);
2316 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
2323 * but first, make sure that environment variables haven't been
2324 * used to circumvent the noexec flag on a filesystem.
2326 if (dangerous_ld_env) {
2327 if (fstatfs(fd, &fs) != 0) {
2328 _rtld_error("Cannot fstatfs \"%s\"", printable_path(path));
2331 if (fs.f_flags & MNT_NOEXEC) {
2332 _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
2336 dbg("loading \"%s\"", printable_path(path));
2337 obj = map_object(fd, printable_path(path), sbp);
2342 * If DT_SONAME is present in the object, digest_dynamic2 already
2343 * added it to the object names.
2346 object_add_name(obj, name);
2348 digest_dynamic(obj, 0);
2349 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path,
2350 obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount);
2351 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
2353 dbg("refusing to load non-loadable \"%s\"", obj->path);
2354 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
2355 munmap(obj->mapbase, obj->mapsize);
2360 obj->dlopened = (flags & RTLD_LO_DLOPEN) != 0;
2361 TAILQ_INSERT_TAIL(&obj_list, obj, next);
2364 linkmap_add(obj); /* for GDB & dlinfo() */
2365 max_stack_flags |= obj->stack_flags;
2367 dbg(" %p .. %p: %s", obj->mapbase,
2368 obj->mapbase + obj->mapsize - 1, obj->path);
2370 dbg(" WARNING: %s has impure text", obj->path);
2371 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
2378 obj_from_addr(const void *addr)
2382 TAILQ_FOREACH(obj, &obj_list, next) {
2385 if (addr < (void *) obj->mapbase)
2387 if (addr < (void *) (obj->mapbase + obj->mapsize))
2396 Elf_Addr *preinit_addr;
2399 preinit_addr = (Elf_Addr *)obj_main->preinit_array;
2400 if (preinit_addr == NULL)
2403 for (index = 0; index < obj_main->preinit_array_num; index++) {
2404 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) {
2405 dbg("calling preinit function for %s at %p", obj_main->path,
2406 (void *)preinit_addr[index]);
2407 LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index],
2408 0, 0, obj_main->path);
2409 call_init_pointer(obj_main, preinit_addr[index]);
2415 * Call the finalization functions for each of the objects in "list"
2416 * belonging to the DAG of "root" and referenced once. If NULL "root"
2417 * is specified, every finalization function will be called regardless
2418 * of the reference count and the list elements won't be freed. All of
2419 * the objects are expected to have non-NULL fini functions.
2422 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
2426 Elf_Addr *fini_addr;
2429 assert(root == NULL || root->refcount == 1);
2432 root->doomed = true;
2435 * Preserve the current error message since a fini function might
2436 * call into the dynamic linker and overwrite it.
2438 saved_msg = errmsg_save();
2440 STAILQ_FOREACH(elm, list, link) {
2441 if (root != NULL && (elm->obj->refcount != 1 ||
2442 objlist_find(&root->dagmembers, elm->obj) == NULL))
2444 /* Remove object from fini list to prevent recursive invocation. */
2445 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2446 /* Ensure that new references cannot be acquired. */
2447 elm->obj->doomed = true;
2449 hold_object(elm->obj);
2450 lock_release(rtld_bind_lock, lockstate);
2452 * It is legal to have both DT_FINI and DT_FINI_ARRAY defined.
2453 * When this happens, DT_FINI_ARRAY is processed first.
2455 fini_addr = (Elf_Addr *)elm->obj->fini_array;
2456 if (fini_addr != NULL && elm->obj->fini_array_num > 0) {
2457 for (index = elm->obj->fini_array_num - 1; index >= 0;
2459 if (fini_addr[index] != 0 && fini_addr[index] != 1) {
2460 dbg("calling fini function for %s at %p",
2461 elm->obj->path, (void *)fini_addr[index]);
2462 LD_UTRACE(UTRACE_FINI_CALL, elm->obj,
2463 (void *)fini_addr[index], 0, 0, elm->obj->path);
2464 call_initfini_pointer(elm->obj, fini_addr[index]);
2468 if (elm->obj->fini != (Elf_Addr)NULL) {
2469 dbg("calling fini function for %s at %p", elm->obj->path,
2470 (void *)elm->obj->fini);
2471 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini,
2472 0, 0, elm->obj->path);
2473 call_initfini_pointer(elm->obj, elm->obj->fini);
2475 wlock_acquire(rtld_bind_lock, lockstate);
2476 unhold_object(elm->obj);
2477 /* No need to free anything if process is going down. */
2481 * We must restart the list traversal after every fini call
2482 * because a dlclose() call from the fini function or from
2483 * another thread might have modified the reference counts.
2487 } while (elm != NULL);
2488 errmsg_restore(saved_msg);
2492 * Call the initialization functions for each of the objects in
2493 * "list". All of the objects are expected to have non-NULL init
2497 objlist_call_init(Objlist *list, RtldLockState *lockstate)
2502 Elf_Addr *init_addr;
2506 * Clean init_scanned flag so that objects can be rechecked and
2507 * possibly initialized earlier if any of vectors called below
2508 * cause the change by using dlopen.
2510 TAILQ_FOREACH(obj, &obj_list, next) {
2513 obj->init_scanned = false;
2517 * Preserve the current error message since an init function might
2518 * call into the dynamic linker and overwrite it.
2520 saved_msg = errmsg_save();
2521 STAILQ_FOREACH(elm, list, link) {
2522 if (elm->obj->init_done) /* Initialized early. */
2525 * Race: other thread might try to use this object before current
2526 * one completes the initialization. Not much can be done here
2527 * without better locking.
2529 elm->obj->init_done = true;
2530 hold_object(elm->obj);
2531 lock_release(rtld_bind_lock, lockstate);
2534 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined.
2535 * When this happens, DT_INIT is processed first.
2537 if (elm->obj->init != (Elf_Addr)NULL) {
2538 dbg("calling init function for %s at %p", elm->obj->path,
2539 (void *)elm->obj->init);
2540 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init,
2541 0, 0, elm->obj->path);
2542 call_initfini_pointer(elm->obj, elm->obj->init);
2544 init_addr = (Elf_Addr *)elm->obj->init_array;
2545 if (init_addr != NULL) {
2546 for (index = 0; index < elm->obj->init_array_num; index++) {
2547 if (init_addr[index] != 0 && init_addr[index] != 1) {
2548 dbg("calling init function for %s at %p", elm->obj->path,
2549 (void *)init_addr[index]);
2550 LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
2551 (void *)init_addr[index], 0, 0, elm->obj->path);
2552 call_init_pointer(elm->obj, init_addr[index]);
2556 wlock_acquire(rtld_bind_lock, lockstate);
2557 unhold_object(elm->obj);
2559 errmsg_restore(saved_msg);
2563 objlist_clear(Objlist *list)
2567 while (!STAILQ_EMPTY(list)) {
2568 elm = STAILQ_FIRST(list);
2569 STAILQ_REMOVE_HEAD(list, link);
2574 static Objlist_Entry *
2575 objlist_find(Objlist *list, const Obj_Entry *obj)
2579 STAILQ_FOREACH(elm, list, link)
2580 if (elm->obj == obj)
2586 objlist_init(Objlist *list)
2592 objlist_push_head(Objlist *list, Obj_Entry *obj)
2596 elm = NEW(Objlist_Entry);
2598 STAILQ_INSERT_HEAD(list, elm, link);
2602 objlist_push_tail(Objlist *list, Obj_Entry *obj)
2606 elm = NEW(Objlist_Entry);
2608 STAILQ_INSERT_TAIL(list, elm, link);
2612 objlist_put_after(Objlist *list, Obj_Entry *listobj, Obj_Entry *obj)
2614 Objlist_Entry *elm, *listelm;
2616 STAILQ_FOREACH(listelm, list, link) {
2617 if (listelm->obj == listobj)
2620 elm = NEW(Objlist_Entry);
2622 if (listelm != NULL)
2623 STAILQ_INSERT_AFTER(list, listelm, elm, link);
2625 STAILQ_INSERT_TAIL(list, elm, link);
2629 objlist_remove(Objlist *list, Obj_Entry *obj)
2633 if ((elm = objlist_find(list, obj)) != NULL) {
2634 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2640 * Relocate dag rooted in the specified object.
2641 * Returns 0 on success, or -1 on failure.
2645 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj,
2646 int flags, RtldLockState *lockstate)
2652 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2653 error = relocate_object(elm->obj, bind_now, rtldobj, flags,
2662 * Prepare for, or clean after, relocating an object marked with
2663 * DT_TEXTREL or DF_TEXTREL. Before relocating, all read-only
2664 * segments are remapped read-write. After relocations are done, the
2665 * segment's permissions are returned back to the modes specified in
2666 * the phdrs. If any relocation happened, or always for wired
2667 * program, COW is triggered.
2670 reloc_textrel_prot(Obj_Entry *obj, bool before)
2677 for (l = obj->phsize / sizeof(*ph), ph = obj->phdr; l > 0;
2679 if (ph->p_type != PT_LOAD || (ph->p_flags & PF_W) != 0)
2681 base = obj->relocbase + trunc_page(ph->p_vaddr);
2682 sz = round_page(ph->p_vaddr + ph->p_filesz) -
2683 trunc_page(ph->p_vaddr);
2684 prot = convert_prot(ph->p_flags) | (before ? PROT_WRITE : 0);
2685 if (mprotect(base, sz, prot) == -1) {
2686 _rtld_error("%s: Cannot write-%sable text segment: %s",
2687 obj->path, before ? "en" : "dis",
2688 rtld_strerror(errno));
2696 * Relocate single object.
2697 * Returns 0 on success, or -1 on failure.
2700 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
2701 int flags, RtldLockState *lockstate)
2706 obj->relocated = true;
2708 dbg("relocating \"%s\"", obj->path);
2710 if (obj->symtab == NULL || obj->strtab == NULL ||
2711 !(obj->valid_hash_sysv || obj->valid_hash_gnu)) {
2712 _rtld_error("%s: Shared object has no run-time symbol table",
2717 /* There are relocations to the write-protected text segment. */
2718 if (obj->textrel && reloc_textrel_prot(obj, true) != 0)
2721 /* Process the non-PLT non-IFUNC relocations. */
2722 if (reloc_non_plt(obj, rtldobj, flags, lockstate))
2725 /* Re-protected the text segment. */
2726 if (obj->textrel && reloc_textrel_prot(obj, false) != 0)
2729 /* Set the special PLT or GOT entries. */
2732 /* Process the PLT relocations. */
2733 if (reloc_plt(obj) == -1)
2735 /* Relocate the jump slots if we are doing immediate binding. */
2736 if (obj->bind_now || bind_now)
2737 if (reloc_jmpslots(obj, flags, lockstate) == -1)
2741 * Process the non-PLT IFUNC relocations. The relocations are
2742 * processed in two phases, because IFUNC resolvers may
2743 * reference other symbols, which must be readily processed
2744 * before resolvers are called.
2746 if (obj->non_plt_gnu_ifunc &&
2747 reloc_non_plt(obj, rtldobj, flags | SYMLOOK_IFUNC, lockstate))
2750 if (!obj->mainprog && obj_enforce_relro(obj) == -1)
2754 * Set up the magic number and version in the Obj_Entry. These
2755 * were checked in the crt1.o from the original ElfKit, so we
2756 * set them for backward compatibility.
2758 obj->magic = RTLD_MAGIC;
2759 obj->version = RTLD_VERSION;
2765 * Relocate newly-loaded shared objects. The argument is a pointer to
2766 * the Obj_Entry for the first such object. All objects from the first
2767 * to the end of the list of objects are relocated. Returns 0 on success,
2771 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
2772 int flags, RtldLockState *lockstate)
2777 for (error = 0, obj = first; obj != NULL;
2778 obj = TAILQ_NEXT(obj, next)) {
2781 error = relocate_object(obj, bind_now, rtldobj, flags,
2790 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
2791 * referencing STT_GNU_IFUNC symbols is postponed till the other
2792 * relocations are done. The indirect functions specified as
2793 * ifunc are allowed to call other symbols, so we need to have
2794 * objects relocated before asking for resolution from indirects.
2796 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
2797 * instead of the usual lazy handling of PLT slots. It is
2798 * consistent with how GNU does it.
2801 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags,
2802 RtldLockState *lockstate)
2804 if (obj->irelative && reloc_iresolve(obj, lockstate) == -1)
2806 if ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
2807 reloc_gnu_ifunc(obj, flags, lockstate) == -1)
2813 resolve_objects_ifunc(Obj_Entry *first, bool bind_now, int flags,
2814 RtldLockState *lockstate)
2818 for (obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
2821 if (resolve_object_ifunc(obj, bind_now, flags, lockstate) == -1)
2828 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags,
2829 RtldLockState *lockstate)
2833 STAILQ_FOREACH(elm, list, link) {
2834 if (resolve_object_ifunc(elm->obj, bind_now, flags,
2842 * Cleanup procedure. It will be called (by the atexit mechanism) just
2843 * before the process exits.
2848 RtldLockState lockstate;
2850 wlock_acquire(rtld_bind_lock, &lockstate);
2852 objlist_call_fini(&list_fini, NULL, &lockstate);
2853 /* No need to remove the items from the list, since we are exiting. */
2854 if (!libmap_disable)
2856 lock_release(rtld_bind_lock, &lockstate);
2860 * Iterate over a search path, translate each element, and invoke the
2861 * callback on the result.
2864 path_enumerate(const char *path, path_enum_proc callback, void *arg)
2870 path += strspn(path, ":;");
2871 while (*path != '\0') {
2875 len = strcspn(path, ":;");
2876 trans = lm_findn(NULL, path, len);
2878 res = callback(trans, strlen(trans), arg);
2880 res = callback(path, len, arg);
2886 path += strspn(path, ":;");
2892 struct try_library_args {
2900 try_library_path(const char *dir, size_t dirlen, void *param)
2902 struct try_library_args *arg;
2905 if (*dir == '/' || trust) {
2908 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
2911 pathname = arg->buffer;
2912 strncpy(pathname, dir, dirlen);
2913 pathname[dirlen] = '/';
2914 strcpy(pathname + dirlen + 1, arg->name);
2916 dbg(" Trying \"%s\"", pathname);
2917 if (access(pathname, F_OK) == 0) { /* We found it */
2918 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
2919 strcpy(pathname, arg->buffer);
2927 search_library_path(const char *name, const char *path)
2930 struct try_library_args arg;
2936 arg.namelen = strlen(name);
2937 arg.buffer = xmalloc(PATH_MAX);
2938 arg.buflen = PATH_MAX;
2940 p = path_enumerate(path, try_library_path, &arg);
2949 * Finds the library with the given name using the directory descriptors
2950 * listed in the LD_LIBRARY_PATH_FDS environment variable.
2952 * Returns a freshly-opened close-on-exec file descriptor for the library,
2953 * or -1 if the library cannot be found.
2956 search_library_pathfds(const char *name, const char *path, int *fdp)
2958 char *envcopy, *fdstr, *found, *last_token;
2962 dbg("%s('%s', '%s', fdp)", __func__, name, path);
2964 /* Don't load from user-specified libdirs into setuid binaries. */
2968 /* We can't do anything if LD_LIBRARY_PATH_FDS isn't set. */
2972 /* LD_LIBRARY_PATH_FDS only works with relative paths. */
2973 if (name[0] == '/') {
2974 dbg("Absolute path (%s) passed to %s", name, __func__);
2979 * Use strtok_r() to walk the FD:FD:FD list. This requires a local
2980 * copy of the path, as strtok_r rewrites separator tokens
2984 envcopy = xstrdup(path);
2985 for (fdstr = strtok_r(envcopy, ":", &last_token); fdstr != NULL;
2986 fdstr = strtok_r(NULL, ":", &last_token)) {
2987 dirfd = parse_libdir(fdstr);
2990 fd = __sys_openat(dirfd, name, O_RDONLY | O_CLOEXEC | O_VERIFY);
2993 len = strlen(fdstr) + strlen(name) + 3;
2994 found = xmalloc(len);
2995 if (rtld_snprintf(found, len, "#%d/%s", dirfd, name) < 0) {
2996 _rtld_error("error generating '%d/%s'",
3000 dbg("open('%s') => %d", found, fd);
3011 dlclose(void *handle)
3014 RtldLockState lockstate;
3016 wlock_acquire(rtld_bind_lock, &lockstate);
3017 root = dlcheck(handle);
3019 lock_release(rtld_bind_lock, &lockstate);
3022 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
3025 /* Unreference the object and its dependencies. */
3026 root->dl_refcount--;
3028 if (root->refcount == 1) {
3030 * The object will be no longer referenced, so we must unload it.
3031 * First, call the fini functions.
3033 objlist_call_fini(&list_fini, root, &lockstate);
3037 /* Finish cleaning up the newly-unreferenced objects. */
3038 GDB_STATE(RT_DELETE,&root->linkmap);
3039 unload_object(root);
3040 GDB_STATE(RT_CONSISTENT,NULL);
3044 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
3045 lock_release(rtld_bind_lock, &lockstate);
3052 char *msg = error_message;
3053 error_message = NULL;
3058 * This function is deprecated and has no effect.
3061 dllockinit(void *context,
3062 void *(*lock_create)(void *context),
3063 void (*rlock_acquire)(void *lock),
3064 void (*wlock_acquire)(void *lock),
3065 void (*lock_release)(void *lock),
3066 void (*lock_destroy)(void *lock),
3067 void (*context_destroy)(void *context))
3069 static void *cur_context;
3070 static void (*cur_context_destroy)(void *);
3072 /* Just destroy the context from the previous call, if necessary. */
3073 if (cur_context_destroy != NULL)
3074 cur_context_destroy(cur_context);
3075 cur_context = context;
3076 cur_context_destroy = context_destroy;
3080 dlopen(const char *name, int mode)
3083 return (rtld_dlopen(name, -1, mode));
3087 fdlopen(int fd, int mode)
3090 return (rtld_dlopen(NULL, fd, mode));
3094 rtld_dlopen(const char *name, int fd, int mode)
3096 RtldLockState lockstate;
3099 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
3100 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
3101 if (ld_tracing != NULL) {
3102 rlock_acquire(rtld_bind_lock, &lockstate);
3103 if (sigsetjmp(lockstate.env, 0) != 0)
3104 lock_upgrade(rtld_bind_lock, &lockstate);
3105 environ = (char **)*get_program_var_addr("environ", &lockstate);
3106 lock_release(rtld_bind_lock, &lockstate);
3108 lo_flags = RTLD_LO_DLOPEN;
3109 if (mode & RTLD_NODELETE)
3110 lo_flags |= RTLD_LO_NODELETE;
3111 if (mode & RTLD_NOLOAD)
3112 lo_flags |= RTLD_LO_NOLOAD;
3113 if (ld_tracing != NULL)
3114 lo_flags |= RTLD_LO_TRACE;
3116 return (dlopen_object(name, fd, obj_main, lo_flags,
3117 mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL));
3121 dlopen_cleanup(Obj_Entry *obj)
3126 if (obj->refcount == 0)
3131 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
3132 int mode, RtldLockState *lockstate)
3134 Obj_Entry *old_obj_tail;
3137 RtldLockState mlockstate;
3140 objlist_init(&initlist);
3142 if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) {
3143 wlock_acquire(rtld_bind_lock, &mlockstate);
3144 lockstate = &mlockstate;
3146 GDB_STATE(RT_ADD,NULL);
3148 old_obj_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
3150 if (name == NULL && fd == -1) {
3154 obj = load_object(name, fd, refobj, lo_flags);
3159 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
3160 objlist_push_tail(&list_global, obj);
3161 if (globallist_next(old_obj_tail) != NULL) {
3162 /* We loaded something new. */
3163 assert(globallist_next(old_obj_tail) == obj);
3164 result = load_needed_objects(obj,
3165 lo_flags & (RTLD_LO_DLOPEN | RTLD_LO_EARLY));
3169 result = rtld_verify_versions(&obj->dagmembers);
3170 if (result != -1 && ld_tracing)
3172 if (result == -1 || relocate_object_dag(obj,
3173 (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld,
3174 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3176 dlopen_cleanup(obj);
3178 } else if (lo_flags & RTLD_LO_EARLY) {
3180 * Do not call the init functions for early loaded
3181 * filtees. The image is still not initialized enough
3184 * Our object is found by the global object list and
3185 * will be ordered among all init calls done right
3186 * before transferring control to main.
3189 /* Make list of init functions to call. */
3190 initlist_add_objects(obj, obj, &initlist);
3193 * Process all no_delete or global objects here, given
3194 * them own DAGs to prevent their dependencies from being
3195 * unloaded. This has to be done after we have loaded all
3196 * of the dependencies, so that we do not miss any.
3202 * Bump the reference counts for objects on this DAG. If
3203 * this is the first dlopen() call for the object that was
3204 * already loaded as a dependency, initialize the dag
3210 if ((lo_flags & RTLD_LO_TRACE) != 0)
3213 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
3214 obj->z_nodelete) && !obj->ref_nodel) {
3215 dbg("obj %s nodelete", obj->path);
3217 obj->z_nodelete = obj->ref_nodel = true;
3221 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
3223 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
3225 if (!(lo_flags & RTLD_LO_EARLY)) {
3226 map_stacks_exec(lockstate);
3229 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
3230 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3232 objlist_clear(&initlist);
3233 dlopen_cleanup(obj);
3234 if (lockstate == &mlockstate)
3235 lock_release(rtld_bind_lock, lockstate);
3239 if (!(lo_flags & RTLD_LO_EARLY)) {
3240 /* Call the init functions. */
3241 objlist_call_init(&initlist, lockstate);
3243 objlist_clear(&initlist);
3244 if (lockstate == &mlockstate)
3245 lock_release(rtld_bind_lock, lockstate);
3248 trace_loaded_objects(obj);
3249 if (lockstate == &mlockstate)
3250 lock_release(rtld_bind_lock, lockstate);
3255 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
3259 const Obj_Entry *obj, *defobj;
3262 RtldLockState lockstate;
3269 symlook_init(&req, name);
3271 req.flags = flags | SYMLOOK_IN_PLT;
3272 req.lockstate = &lockstate;
3274 LD_UTRACE(UTRACE_DLSYM_START, handle, NULL, 0, 0, name);
3275 rlock_acquire(rtld_bind_lock, &lockstate);
3276 if (sigsetjmp(lockstate.env, 0) != 0)
3277 lock_upgrade(rtld_bind_lock, &lockstate);
3278 if (handle == NULL || handle == RTLD_NEXT ||
3279 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
3281 if ((obj = obj_from_addr(retaddr)) == NULL) {
3282 _rtld_error("Cannot determine caller's shared object");
3283 lock_release(rtld_bind_lock, &lockstate);
3284 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3287 if (handle == NULL) { /* Just the caller's shared object. */
3288 res = symlook_obj(&req, obj);
3291 defobj = req.defobj_out;
3293 } else if (handle == RTLD_NEXT || /* Objects after caller's */
3294 handle == RTLD_SELF) { /* ... caller included */
3295 if (handle == RTLD_NEXT)
3296 obj = globallist_next(obj);
3297 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
3300 res = symlook_obj(&req, obj);
3303 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) {
3305 defobj = req.defobj_out;
3306 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3312 * Search the dynamic linker itself, and possibly resolve the
3313 * symbol from there. This is how the application links to
3314 * dynamic linker services such as dlopen.
3316 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3317 res = symlook_obj(&req, &obj_rtld);
3320 defobj = req.defobj_out;
3324 assert(handle == RTLD_DEFAULT);
3325 res = symlook_default(&req, obj);
3327 defobj = req.defobj_out;
3332 if ((obj = dlcheck(handle)) == NULL) {
3333 lock_release(rtld_bind_lock, &lockstate);
3334 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3338 donelist_init(&donelist);
3339 if (obj->mainprog) {
3340 /* Handle obtained by dlopen(NULL, ...) implies global scope. */
3341 res = symlook_global(&req, &donelist);
3344 defobj = req.defobj_out;
3347 * Search the dynamic linker itself, and possibly resolve the
3348 * symbol from there. This is how the application links to
3349 * dynamic linker services such as dlopen.
3351 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3352 res = symlook_obj(&req, &obj_rtld);
3355 defobj = req.defobj_out;
3360 /* Search the whole DAG rooted at the given object. */
3361 res = symlook_list(&req, &obj->dagmembers, &donelist);
3364 defobj = req.defobj_out;
3370 lock_release(rtld_bind_lock, &lockstate);
3373 * The value required by the caller is derived from the value
3374 * of the symbol. this is simply the relocated value of the
3377 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
3378 sym = make_function_pointer(def, defobj);
3379 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
3380 sym = rtld_resolve_ifunc(defobj, def);
3381 else if (ELF_ST_TYPE(def->st_info) == STT_TLS) {
3382 ti.ti_module = defobj->tlsindex;
3383 ti.ti_offset = def->st_value;
3384 sym = __tls_get_addr(&ti);
3386 sym = defobj->relocbase + def->st_value;
3387 LD_UTRACE(UTRACE_DLSYM_STOP, handle, sym, 0, 0, name);
3391 _rtld_error("Undefined symbol \"%s\"", name);
3392 lock_release(rtld_bind_lock, &lockstate);
3393 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3398 dlsym(void *handle, const char *name)
3400 return do_dlsym(handle, name, __builtin_return_address(0), NULL,
3405 dlfunc(void *handle, const char *name)
3412 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
3418 dlvsym(void *handle, const char *name, const char *version)
3422 ventry.name = version;
3424 ventry.hash = elf_hash(version);
3426 return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
3431 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
3433 const Obj_Entry *obj;
3434 RtldLockState lockstate;
3436 rlock_acquire(rtld_bind_lock, &lockstate);
3437 obj = obj_from_addr(addr);
3439 _rtld_error("No shared object contains address");
3440 lock_release(rtld_bind_lock, &lockstate);
3443 rtld_fill_dl_phdr_info(obj, phdr_info);
3444 lock_release(rtld_bind_lock, &lockstate);
3449 dladdr(const void *addr, Dl_info *info)
3451 const Obj_Entry *obj;
3454 unsigned long symoffset;
3455 RtldLockState lockstate;
3457 rlock_acquire(rtld_bind_lock, &lockstate);
3458 obj = obj_from_addr(addr);
3460 _rtld_error("No shared object contains address");
3461 lock_release(rtld_bind_lock, &lockstate);
3464 info->dli_fname = obj->path;
3465 info->dli_fbase = obj->mapbase;
3466 info->dli_saddr = (void *)0;
3467 info->dli_sname = NULL;
3470 * Walk the symbol list looking for the symbol whose address is
3471 * closest to the address sent in.
3473 for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) {
3474 def = obj->symtab + symoffset;
3477 * For skip the symbol if st_shndx is either SHN_UNDEF or
3480 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
3484 * If the symbol is greater than the specified address, or if it
3485 * is further away from addr than the current nearest symbol,
3488 symbol_addr = obj->relocbase + def->st_value;
3489 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
3492 /* Update our idea of the nearest symbol. */
3493 info->dli_sname = obj->strtab + def->st_name;
3494 info->dli_saddr = symbol_addr;
3497 if (info->dli_saddr == addr)
3500 lock_release(rtld_bind_lock, &lockstate);
3505 dlinfo(void *handle, int request, void *p)
3507 const Obj_Entry *obj;
3508 RtldLockState lockstate;
3511 rlock_acquire(rtld_bind_lock, &lockstate);
3513 if (handle == NULL || handle == RTLD_SELF) {
3516 retaddr = __builtin_return_address(0); /* __GNUC__ only */
3517 if ((obj = obj_from_addr(retaddr)) == NULL)
3518 _rtld_error("Cannot determine caller's shared object");
3520 obj = dlcheck(handle);
3523 lock_release(rtld_bind_lock, &lockstate);
3529 case RTLD_DI_LINKMAP:
3530 *((struct link_map const **)p) = &obj->linkmap;
3532 case RTLD_DI_ORIGIN:
3533 error = rtld_dirname(obj->path, p);
3536 case RTLD_DI_SERINFOSIZE:
3537 case RTLD_DI_SERINFO:
3538 error = do_search_info(obj, request, (struct dl_serinfo *)p);
3542 _rtld_error("Invalid request %d passed to dlinfo()", request);
3546 lock_release(rtld_bind_lock, &lockstate);
3552 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
3555 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
3556 phdr_info->dlpi_name = obj->path;
3557 phdr_info->dlpi_phdr = obj->phdr;
3558 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
3559 phdr_info->dlpi_tls_modid = obj->tlsindex;
3560 phdr_info->dlpi_tls_data = obj->tlsinit;
3561 phdr_info->dlpi_adds = obj_loads;
3562 phdr_info->dlpi_subs = obj_loads - obj_count;
3566 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
3568 struct dl_phdr_info phdr_info;
3569 Obj_Entry *obj, marker;
3570 RtldLockState bind_lockstate, phdr_lockstate;
3573 init_marker(&marker);
3576 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
3577 wlock_acquire(rtld_bind_lock, &bind_lockstate);
3578 for (obj = globallist_curr(TAILQ_FIRST(&obj_list)); obj != NULL;) {
3579 TAILQ_INSERT_AFTER(&obj_list, obj, &marker, next);
3580 rtld_fill_dl_phdr_info(obj, &phdr_info);
3582 lock_release(rtld_bind_lock, &bind_lockstate);
3584 error = callback(&phdr_info, sizeof phdr_info, param);
3586 wlock_acquire(rtld_bind_lock, &bind_lockstate);
3588 obj = globallist_next(&marker);
3589 TAILQ_REMOVE(&obj_list, &marker, next);
3591 lock_release(rtld_bind_lock, &bind_lockstate);
3592 lock_release(rtld_phdr_lock, &phdr_lockstate);
3598 rtld_fill_dl_phdr_info(&obj_rtld, &phdr_info);
3599 lock_release(rtld_bind_lock, &bind_lockstate);
3600 error = callback(&phdr_info, sizeof(phdr_info), param);
3602 lock_release(rtld_phdr_lock, &phdr_lockstate);
3607 fill_search_info(const char *dir, size_t dirlen, void *param)
3609 struct fill_search_info_args *arg;
3613 if (arg->request == RTLD_DI_SERINFOSIZE) {
3614 arg->serinfo->dls_cnt ++;
3615 arg->serinfo->dls_size += sizeof(struct dl_serpath) + dirlen + 1;
3617 struct dl_serpath *s_entry;
3619 s_entry = arg->serpath;
3620 s_entry->dls_name = arg->strspace;
3621 s_entry->dls_flags = arg->flags;
3623 strncpy(arg->strspace, dir, dirlen);
3624 arg->strspace[dirlen] = '\0';
3626 arg->strspace += dirlen + 1;
3634 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
3636 struct dl_serinfo _info;
3637 struct fill_search_info_args args;
3639 args.request = RTLD_DI_SERINFOSIZE;
3640 args.serinfo = &_info;
3642 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
3645 path_enumerate(obj->rpath, fill_search_info, &args);
3646 path_enumerate(ld_library_path, fill_search_info, &args);
3647 path_enumerate(obj->runpath, fill_search_info, &args);
3648 path_enumerate(gethints(obj->z_nodeflib), fill_search_info, &args);
3649 if (!obj->z_nodeflib)
3650 path_enumerate(ld_standard_library_path, fill_search_info, &args);
3653 if (request == RTLD_DI_SERINFOSIZE) {
3654 info->dls_size = _info.dls_size;
3655 info->dls_cnt = _info.dls_cnt;
3659 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
3660 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
3664 args.request = RTLD_DI_SERINFO;
3665 args.serinfo = info;
3666 args.serpath = &info->dls_serpath[0];
3667 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
3669 args.flags = LA_SER_RUNPATH;
3670 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
3673 args.flags = LA_SER_LIBPATH;
3674 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
3677 args.flags = LA_SER_RUNPATH;
3678 if (path_enumerate(obj->runpath, fill_search_info, &args) != NULL)
3681 args.flags = LA_SER_CONFIG;
3682 if (path_enumerate(gethints(obj->z_nodeflib), fill_search_info, &args)
3686 args.flags = LA_SER_DEFAULT;
3687 if (!obj->z_nodeflib &&
3688 path_enumerate(ld_standard_library_path, fill_search_info, &args) != NULL)
3694 rtld_dirname(const char *path, char *bname)
3698 /* Empty or NULL string gets treated as "." */
3699 if (path == NULL || *path == '\0') {
3705 /* Strip trailing slashes */
3706 endp = path + strlen(path) - 1;
3707 while (endp > path && *endp == '/')
3710 /* Find the start of the dir */
3711 while (endp > path && *endp != '/')
3714 /* Either the dir is "/" or there are no slashes */
3716 bname[0] = *endp == '/' ? '/' : '.';
3722 } while (endp > path && *endp == '/');
3725 if (endp - path + 2 > PATH_MAX)
3727 _rtld_error("Filename is too long: %s", path);
3731 strncpy(bname, path, endp - path + 1);
3732 bname[endp - path + 1] = '\0';
3737 rtld_dirname_abs(const char *path, char *base)
3741 if (realpath(path, base) == NULL)
3743 dbg("%s -> %s", path, base);
3744 last = strrchr(base, '/');
3753 linkmap_add(Obj_Entry *obj)
3755 struct link_map *l = &obj->linkmap;
3756 struct link_map *prev;
3758 obj->linkmap.l_name = obj->path;
3759 obj->linkmap.l_addr = obj->mapbase;
3760 obj->linkmap.l_ld = obj->dynamic;
3762 /* GDB needs load offset on MIPS to use the symbols */
3763 obj->linkmap.l_offs = obj->relocbase;
3766 if (r_debug.r_map == NULL) {
3772 * Scan to the end of the list, but not past the entry for the
3773 * dynamic linker, which we want to keep at the very end.
3775 for (prev = r_debug.r_map;
3776 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
3777 prev = prev->l_next)
3780 /* Link in the new entry. */
3782 l->l_next = prev->l_next;
3783 if (l->l_next != NULL)
3784 l->l_next->l_prev = l;
3789 linkmap_delete(Obj_Entry *obj)
3791 struct link_map *l = &obj->linkmap;
3793 if (l->l_prev == NULL) {
3794 if ((r_debug.r_map = l->l_next) != NULL)
3795 l->l_next->l_prev = NULL;
3799 if ((l->l_prev->l_next = l->l_next) != NULL)
3800 l->l_next->l_prev = l->l_prev;
3804 * Function for the debugger to set a breakpoint on to gain control.
3806 * The two parameters allow the debugger to easily find and determine
3807 * what the runtime loader is doing and to whom it is doing it.
3809 * When the loadhook trap is hit (r_debug_state, set at program
3810 * initialization), the arguments can be found on the stack:
3812 * +8 struct link_map *m
3813 * +4 struct r_debug *rd
3817 r_debug_state(struct r_debug* rd, struct link_map *m)
3820 * The following is a hack to force the compiler to emit calls to
3821 * this function, even when optimizing. If the function is empty,
3822 * the compiler is not obliged to emit any code for calls to it,
3823 * even when marked __noinline. However, gdb depends on those
3826 __compiler_membar();
3830 * A function called after init routines have completed. This can be used to
3831 * break before a program's entry routine is called, and can be used when
3832 * main is not available in the symbol table.
3835 _r_debug_postinit(struct link_map *m)
3838 /* See r_debug_state(). */
3839 __compiler_membar();
3843 release_object(Obj_Entry *obj)
3846 if (obj->holdcount > 0) {
3847 obj->unholdfree = true;
3850 munmap(obj->mapbase, obj->mapsize);
3851 linkmap_delete(obj);
3856 * Get address of the pointer variable in the main program.
3857 * Prefer non-weak symbol over the weak one.
3859 static const void **
3860 get_program_var_addr(const char *name, RtldLockState *lockstate)
3865 symlook_init(&req, name);
3866 req.lockstate = lockstate;
3867 donelist_init(&donelist);
3868 if (symlook_global(&req, &donelist) != 0)
3870 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
3871 return ((const void **)make_function_pointer(req.sym_out,
3873 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
3874 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
3876 return ((const void **)(req.defobj_out->relocbase +
3877 req.sym_out->st_value));
3881 * Set a pointer variable in the main program to the given value. This
3882 * is used to set key variables such as "environ" before any of the
3883 * init functions are called.
3886 set_program_var(const char *name, const void *value)
3890 if ((addr = get_program_var_addr(name, NULL)) != NULL) {
3891 dbg("\"%s\": *%p <-- %p", name, addr, value);
3897 * Search the global objects, including dependencies and main object,
3898 * for the given symbol.
3901 symlook_global(SymLook *req, DoneList *donelist)
3904 const Objlist_Entry *elm;
3907 symlook_init_from_req(&req1, req);
3909 /* Search all objects loaded at program start up. */
3910 if (req->defobj_out == NULL ||
3911 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3912 res = symlook_list(&req1, &list_main, donelist);
3913 if (res == 0 && (req->defobj_out == NULL ||
3914 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3915 req->sym_out = req1.sym_out;
3916 req->defobj_out = req1.defobj_out;
3917 assert(req->defobj_out != NULL);
3921 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
3922 STAILQ_FOREACH(elm, &list_global, link) {
3923 if (req->defobj_out != NULL &&
3924 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3926 res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
3927 if (res == 0 && (req->defobj_out == NULL ||
3928 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3929 req->sym_out = req1.sym_out;
3930 req->defobj_out = req1.defobj_out;
3931 assert(req->defobj_out != NULL);
3935 return (req->sym_out != NULL ? 0 : ESRCH);
3939 * Given a symbol name in a referencing object, find the corresponding
3940 * definition of the symbol. Returns a pointer to the symbol, or NULL if
3941 * no definition was found. Returns a pointer to the Obj_Entry of the
3942 * defining object via the reference parameter DEFOBJ_OUT.
3945 symlook_default(SymLook *req, const Obj_Entry *refobj)
3948 const Objlist_Entry *elm;
3952 donelist_init(&donelist);
3953 symlook_init_from_req(&req1, req);
3955 /* Look first in the referencing object if linked symbolically. */
3956 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
3957 res = symlook_obj(&req1, refobj);
3959 req->sym_out = req1.sym_out;
3960 req->defobj_out = req1.defobj_out;
3961 assert(req->defobj_out != NULL);
3965 symlook_global(req, &donelist);
3967 /* Search all dlopened DAGs containing the referencing object. */
3968 STAILQ_FOREACH(elm, &refobj->dldags, link) {
3969 if (req->sym_out != NULL &&
3970 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3972 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
3973 if (res == 0 && (req->sym_out == NULL ||
3974 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3975 req->sym_out = req1.sym_out;
3976 req->defobj_out = req1.defobj_out;
3977 assert(req->defobj_out != NULL);
3982 * Search the dynamic linker itself, and possibly resolve the
3983 * symbol from there. This is how the application links to
3984 * dynamic linker services such as dlopen.
3986 if (req->sym_out == NULL ||
3987 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3988 res = symlook_obj(&req1, &obj_rtld);
3990 req->sym_out = req1.sym_out;
3991 req->defobj_out = req1.defobj_out;
3992 assert(req->defobj_out != NULL);
3996 return (req->sym_out != NULL ? 0 : ESRCH);
4000 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
4003 const Obj_Entry *defobj;
4004 const Objlist_Entry *elm;
4010 STAILQ_FOREACH(elm, objlist, link) {
4011 if (donelist_check(dlp, elm->obj))
4013 symlook_init_from_req(&req1, req);
4014 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
4015 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
4017 defobj = req1.defobj_out;
4018 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
4025 req->defobj_out = defobj;
4032 * Search the chain of DAGS cointed to by the given Needed_Entry
4033 * for a symbol of the given name. Each DAG is scanned completely
4034 * before advancing to the next one. Returns a pointer to the symbol,
4035 * or NULL if no definition was found.
4038 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
4041 const Needed_Entry *n;
4042 const Obj_Entry *defobj;
4048 symlook_init_from_req(&req1, req);
4049 for (n = needed; n != NULL; n = n->next) {
4050 if (n->obj == NULL ||
4051 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
4053 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
4055 defobj = req1.defobj_out;
4056 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
4062 req->defobj_out = defobj;
4069 * Search the symbol table of a single shared object for a symbol of
4070 * the given name and version, if requested. Returns a pointer to the
4071 * symbol, or NULL if no definition was found. If the object is
4072 * filter, return filtered symbol from filtee.
4074 * The symbol's hash value is passed in for efficiency reasons; that
4075 * eliminates many recomputations of the hash value.
4078 symlook_obj(SymLook *req, const Obj_Entry *obj)
4082 int flags, res, mres;
4085 * If there is at least one valid hash at this point, we prefer to
4086 * use the faster GNU version if available.
4088 if (obj->valid_hash_gnu)
4089 mres = symlook_obj1_gnu(req, obj);
4090 else if (obj->valid_hash_sysv)
4091 mres = symlook_obj1_sysv(req, obj);
4096 if (obj->needed_filtees != NULL) {
4097 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4098 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4099 donelist_init(&donelist);
4100 symlook_init_from_req(&req1, req);
4101 res = symlook_needed(&req1, obj->needed_filtees, &donelist);
4103 req->sym_out = req1.sym_out;
4104 req->defobj_out = req1.defobj_out;
4108 if (obj->needed_aux_filtees != NULL) {
4109 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4110 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4111 donelist_init(&donelist);
4112 symlook_init_from_req(&req1, req);
4113 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
4115 req->sym_out = req1.sym_out;
4116 req->defobj_out = req1.defobj_out;
4124 /* Symbol match routine common to both hash functions */
4126 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result,
4127 const unsigned long symnum)
4130 const Elf_Sym *symp;
4133 symp = obj->symtab + symnum;
4134 strp = obj->strtab + symp->st_name;
4136 switch (ELF_ST_TYPE(symp->st_info)) {
4142 if (symp->st_value == 0)
4146 if (symp->st_shndx != SHN_UNDEF)
4149 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
4150 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
4157 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
4160 if (req->ventry == NULL) {
4161 if (obj->versyms != NULL) {
4162 verndx = VER_NDX(obj->versyms[symnum]);
4163 if (verndx > obj->vernum) {
4165 "%s: symbol %s references wrong version %d",
4166 obj->path, obj->strtab + symnum, verndx);
4170 * If we are not called from dlsym (i.e. this
4171 * is a normal relocation from unversioned
4172 * binary), accept the symbol immediately if
4173 * it happens to have first version after this
4174 * shared object became versioned. Otherwise,
4175 * if symbol is versioned and not hidden,
4176 * remember it. If it is the only symbol with
4177 * this name exported by the shared object, it
4178 * will be returned as a match by the calling
4179 * function. If symbol is global (verndx < 2)
4180 * accept it unconditionally.
4182 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
4183 verndx == VER_NDX_GIVEN) {
4184 result->sym_out = symp;
4187 else if (verndx >= VER_NDX_GIVEN) {
4188 if ((obj->versyms[symnum] & VER_NDX_HIDDEN)
4190 if (result->vsymp == NULL)
4191 result->vsymp = symp;
4197 result->sym_out = symp;
4200 if (obj->versyms == NULL) {
4201 if (object_match_name(obj, req->ventry->name)) {
4202 _rtld_error("%s: object %s should provide version %s "
4203 "for symbol %s", obj_rtld.path, obj->path,
4204 req->ventry->name, obj->strtab + symnum);
4208 verndx = VER_NDX(obj->versyms[symnum]);
4209 if (verndx > obj->vernum) {
4210 _rtld_error("%s: symbol %s references wrong version %d",
4211 obj->path, obj->strtab + symnum, verndx);
4214 if (obj->vertab[verndx].hash != req->ventry->hash ||
4215 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
4217 * Version does not match. Look if this is a
4218 * global symbol and if it is not hidden. If
4219 * global symbol (verndx < 2) is available,
4220 * use it. Do not return symbol if we are
4221 * called by dlvsym, because dlvsym looks for
4222 * a specific version and default one is not
4223 * what dlvsym wants.
4225 if ((req->flags & SYMLOOK_DLSYM) ||
4226 (verndx >= VER_NDX_GIVEN) ||
4227 (obj->versyms[symnum] & VER_NDX_HIDDEN))
4231 result->sym_out = symp;
4236 * Search for symbol using SysV hash function.
4237 * obj->buckets is known not to be NULL at this point; the test for this was
4238 * performed with the obj->valid_hash_sysv assignment.
4241 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj)
4243 unsigned long symnum;
4244 Sym_Match_Result matchres;
4246 matchres.sym_out = NULL;
4247 matchres.vsymp = NULL;
4248 matchres.vcount = 0;
4250 for (symnum = obj->buckets[req->hash % obj->nbuckets];
4251 symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
4252 if (symnum >= obj->nchains)
4253 return (ESRCH); /* Bad object */
4255 if (matched_symbol(req, obj, &matchres, symnum)) {
4256 req->sym_out = matchres.sym_out;
4257 req->defobj_out = obj;
4261 if (matchres.vcount == 1) {
4262 req->sym_out = matchres.vsymp;
4263 req->defobj_out = obj;
4269 /* Search for symbol using GNU hash function */
4271 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj)
4273 Elf_Addr bloom_word;
4274 const Elf32_Word *hashval;
4276 Sym_Match_Result matchres;
4277 unsigned int h1, h2;
4278 unsigned long symnum;
4280 matchres.sym_out = NULL;
4281 matchres.vsymp = NULL;
4282 matchres.vcount = 0;
4284 /* Pick right bitmask word from Bloom filter array */
4285 bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) &
4286 obj->maskwords_bm_gnu];
4288 /* Calculate modulus word size of gnu hash and its derivative */
4289 h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1);
4290 h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1));
4292 /* Filter out the "definitely not in set" queries */
4293 if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0)
4296 /* Locate hash chain and corresponding value element*/
4297 bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu];
4300 hashval = &obj->chain_zero_gnu[bucket];
4302 if (((*hashval ^ req->hash_gnu) >> 1) == 0) {
4303 symnum = hashval - obj->chain_zero_gnu;
4304 if (matched_symbol(req, obj, &matchres, symnum)) {
4305 req->sym_out = matchres.sym_out;
4306 req->defobj_out = obj;
4310 } while ((*hashval++ & 1) == 0);
4311 if (matchres.vcount == 1) {
4312 req->sym_out = matchres.vsymp;
4313 req->defobj_out = obj;
4320 trace_loaded_objects(Obj_Entry *obj)
4322 char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
4325 if ((main_local = getenv(_LD("TRACE_LOADED_OBJECTS_PROGNAME"))) == NULL)
4328 if ((fmt1 = getenv(_LD("TRACE_LOADED_OBJECTS_FMT1"))) == NULL)
4329 fmt1 = "\t%o => %p (%x)\n";
4331 if ((fmt2 = getenv(_LD("TRACE_LOADED_OBJECTS_FMT2"))) == NULL)
4332 fmt2 = "\t%o (%x)\n";
4334 list_containers = getenv(_LD("TRACE_LOADED_OBJECTS_ALL"));
4336 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
4337 Needed_Entry *needed;
4343 if (list_containers && obj->needed != NULL)
4344 rtld_printf("%s:\n", obj->path);
4345 for (needed = obj->needed; needed; needed = needed->next) {
4346 if (needed->obj != NULL) {
4347 if (needed->obj->traced && !list_containers)
4349 needed->obj->traced = true;
4350 path = needed->obj->path;
4354 name = (char *)obj->strtab + needed->name;
4355 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
4357 fmt = is_lib ? fmt1 : fmt2;
4358 while ((c = *fmt++) != '\0') {
4384 rtld_putstr(main_local);
4387 rtld_putstr(obj_main->path);
4394 rtld_printf("%d", sodp->sod_major);
4397 rtld_printf("%d", sodp->sod_minor);
4404 rtld_printf("%p", needed->obj ? needed->obj->mapbase :
4417 * Unload a dlopened object and its dependencies from memory and from
4418 * our data structures. It is assumed that the DAG rooted in the
4419 * object has already been unreferenced, and that the object has a
4420 * reference count of 0.
4423 unload_object(Obj_Entry *root)
4425 Obj_Entry marker, *obj, *next;
4427 assert(root->refcount == 0);
4430 * Pass over the DAG removing unreferenced objects from
4431 * appropriate lists.
4433 unlink_object(root);
4435 /* Unmap all objects that are no longer referenced. */
4436 for (obj = TAILQ_FIRST(&obj_list); obj != NULL; obj = next) {
4437 next = TAILQ_NEXT(obj, next);
4438 if (obj->marker || obj->refcount != 0)
4440 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase,
4441 obj->mapsize, 0, obj->path);
4442 dbg("unloading \"%s\"", obj->path);
4444 * Unlink the object now to prevent new references from
4445 * being acquired while the bind lock is dropped in
4446 * recursive dlclose() invocations.
4448 TAILQ_REMOVE(&obj_list, obj, next);
4451 if (obj->filtees_loaded) {
4453 init_marker(&marker);
4454 TAILQ_INSERT_BEFORE(next, &marker, next);
4455 unload_filtees(obj);
4456 next = TAILQ_NEXT(&marker, next);
4457 TAILQ_REMOVE(&obj_list, &marker, next);
4459 unload_filtees(obj);
4461 release_object(obj);
4466 unlink_object(Obj_Entry *root)
4470 if (root->refcount == 0) {
4471 /* Remove the object from the RTLD_GLOBAL list. */
4472 objlist_remove(&list_global, root);
4474 /* Remove the object from all objects' DAG lists. */
4475 STAILQ_FOREACH(elm, &root->dagmembers, link) {
4476 objlist_remove(&elm->obj->dldags, root);
4477 if (elm->obj != root)
4478 unlink_object(elm->obj);
4484 ref_dag(Obj_Entry *root)
4488 assert(root->dag_inited);
4489 STAILQ_FOREACH(elm, &root->dagmembers, link)
4490 elm->obj->refcount++;
4494 unref_dag(Obj_Entry *root)
4498 assert(root->dag_inited);
4499 STAILQ_FOREACH(elm, &root->dagmembers, link)
4500 elm->obj->refcount--;
4504 * Common code for MD __tls_get_addr().
4506 static void *tls_get_addr_slow(Elf_Addr **, int, size_t) __noinline;
4508 tls_get_addr_slow(Elf_Addr **dtvp, int index, size_t offset)
4510 Elf_Addr *newdtv, *dtv;
4511 RtldLockState lockstate;
4515 /* Check dtv generation in case new modules have arrived */
4516 if (dtv[0] != tls_dtv_generation) {
4517 wlock_acquire(rtld_bind_lock, &lockstate);
4518 newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4520 if (to_copy > tls_max_index)
4521 to_copy = tls_max_index;
4522 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
4523 newdtv[0] = tls_dtv_generation;
4524 newdtv[1] = tls_max_index;
4526 lock_release(rtld_bind_lock, &lockstate);
4527 dtv = *dtvp = newdtv;
4530 /* Dynamically allocate module TLS if necessary */
4531 if (dtv[index + 1] == 0) {
4532 /* Signal safe, wlock will block out signals. */
4533 wlock_acquire(rtld_bind_lock, &lockstate);
4534 if (!dtv[index + 1])
4535 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
4536 lock_release(rtld_bind_lock, &lockstate);
4538 return ((void *)(dtv[index + 1] + offset));
4542 tls_get_addr_common(Elf_Addr **dtvp, int index, size_t offset)
4547 /* Check dtv generation in case new modules have arrived */
4548 if (__predict_true(dtv[0] == tls_dtv_generation &&
4549 dtv[index + 1] != 0))
4550 return ((void *)(dtv[index + 1] + offset));
4551 return (tls_get_addr_slow(dtvp, index, offset));
4554 #if defined(__aarch64__) || defined(__arm__) || defined(__mips__) || \
4555 defined(__powerpc__) || defined(__riscv__)
4558 * Allocate Static TLS using the Variant I method.
4561 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
4570 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
4573 assert(tcbsize >= TLS_TCB_SIZE);
4574 tcb = xcalloc(1, tls_static_space - TLS_TCB_SIZE + tcbsize);
4575 tls = (Elf_Addr **)(tcb + tcbsize - TLS_TCB_SIZE);
4577 if (oldtcb != NULL) {
4578 memcpy(tls, oldtcb, tls_static_space);
4581 /* Adjust the DTV. */
4583 for (i = 0; i < dtv[1]; i++) {
4584 if (dtv[i+2] >= (Elf_Addr)oldtcb &&
4585 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
4586 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tls;
4590 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4592 dtv[0] = tls_dtv_generation;
4593 dtv[1] = tls_max_index;
4595 for (obj = globallist_curr(objs); obj != NULL;
4596 obj = globallist_next(obj)) {
4597 if (obj->tlsoffset > 0) {
4598 addr = (Elf_Addr)tls + obj->tlsoffset;
4599 if (obj->tlsinitsize > 0)
4600 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4601 if (obj->tlssize > obj->tlsinitsize)
4602 memset((void*) (addr + obj->tlsinitsize), 0,
4603 obj->tlssize - obj->tlsinitsize);
4604 dtv[obj->tlsindex + 1] = addr;
4613 free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
4616 Elf_Addr tlsstart, tlsend;
4619 assert(tcbsize >= TLS_TCB_SIZE);
4621 tlsstart = (Elf_Addr)tcb + tcbsize - TLS_TCB_SIZE;
4622 tlsend = tlsstart + tls_static_space;
4624 dtv = *(Elf_Addr **)tlsstart;
4626 for (i = 0; i < dtvsize; i++) {
4627 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
4628 free((void*)dtv[i+2]);
4637 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__)
4640 * Allocate Static TLS using the Variant II method.
4643 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
4646 size_t size, ralign;
4648 Elf_Addr *dtv, *olddtv;
4649 Elf_Addr segbase, oldsegbase, addr;
4653 if (tls_static_max_align > ralign)
4654 ralign = tls_static_max_align;
4655 size = round(tls_static_space, ralign) + round(tcbsize, ralign);
4657 assert(tcbsize >= 2*sizeof(Elf_Addr));
4658 tls = malloc_aligned(size, ralign);
4659 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4661 segbase = (Elf_Addr)(tls + round(tls_static_space, ralign));
4662 ((Elf_Addr*)segbase)[0] = segbase;
4663 ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
4665 dtv[0] = tls_dtv_generation;
4666 dtv[1] = tls_max_index;
4670 * Copy the static TLS block over whole.
4672 oldsegbase = (Elf_Addr) oldtls;
4673 memcpy((void *)(segbase - tls_static_space),
4674 (const void *)(oldsegbase - tls_static_space),
4678 * If any dynamic TLS blocks have been created tls_get_addr(),
4681 olddtv = ((Elf_Addr**)oldsegbase)[1];
4682 for (i = 0; i < olddtv[1]; i++) {
4683 if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
4684 dtv[i+2] = olddtv[i+2];
4690 * We assume that this block was the one we created with
4691 * allocate_initial_tls().
4693 free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
4695 for (obj = objs; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
4696 if (obj->marker || obj->tlsoffset == 0)
4698 addr = segbase - obj->tlsoffset;
4699 memset((void*) (addr + obj->tlsinitsize),
4700 0, obj->tlssize - obj->tlsinitsize);
4702 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4703 dtv[obj->tlsindex + 1] = addr;
4707 return (void*) segbase;
4711 free_tls(void *tls, size_t tcbsize, size_t tcbalign)
4714 size_t size, ralign;
4716 Elf_Addr tlsstart, tlsend;
4719 * Figure out the size of the initial TLS block so that we can
4720 * find stuff which ___tls_get_addr() allocated dynamically.
4723 if (tls_static_max_align > ralign)
4724 ralign = tls_static_max_align;
4725 size = round(tls_static_space, ralign);
4727 dtv = ((Elf_Addr**)tls)[1];
4729 tlsend = (Elf_Addr) tls;
4730 tlsstart = tlsend - size;
4731 for (i = 0; i < dtvsize; i++) {
4732 if (dtv[i + 2] != 0 && (dtv[i + 2] < tlsstart || dtv[i + 2] > tlsend)) {
4733 free_aligned((void *)dtv[i + 2]);
4737 free_aligned((void *)tlsstart);
4744 * Allocate TLS block for module with given index.
4747 allocate_module_tls(int index)
4752 TAILQ_FOREACH(obj, &obj_list, next) {
4755 if (obj->tlsindex == index)
4759 _rtld_error("Can't find module with TLS index %d", index);
4763 p = malloc_aligned(obj->tlssize, obj->tlsalign);
4764 memcpy(p, obj->tlsinit, obj->tlsinitsize);
4765 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
4771 allocate_tls_offset(Obj_Entry *obj)
4778 if (obj->tlssize == 0) {
4779 obj->tls_done = true;
4783 if (tls_last_offset == 0)
4784 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
4786 off = calculate_tls_offset(tls_last_offset, tls_last_size,
4787 obj->tlssize, obj->tlsalign);
4790 * If we have already fixed the size of the static TLS block, we
4791 * must stay within that size. When allocating the static TLS, we
4792 * leave a small amount of space spare to be used for dynamically
4793 * loading modules which use static TLS.
4795 if (tls_static_space != 0) {
4796 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
4798 } else if (obj->tlsalign > tls_static_max_align) {
4799 tls_static_max_align = obj->tlsalign;
4802 tls_last_offset = obj->tlsoffset = off;
4803 tls_last_size = obj->tlssize;
4804 obj->tls_done = true;
4810 free_tls_offset(Obj_Entry *obj)
4814 * If we were the last thing to allocate out of the static TLS
4815 * block, we give our space back to the 'allocator'. This is a
4816 * simplistic workaround to allow libGL.so.1 to be loaded and
4817 * unloaded multiple times.
4819 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
4820 == calculate_tls_end(tls_last_offset, tls_last_size)) {
4821 tls_last_offset -= obj->tlssize;
4827 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
4830 RtldLockState lockstate;
4832 wlock_acquire(rtld_bind_lock, &lockstate);
4833 ret = allocate_tls(globallist_curr(TAILQ_FIRST(&obj_list)), oldtls,
4835 lock_release(rtld_bind_lock, &lockstate);
4840 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
4842 RtldLockState lockstate;
4844 wlock_acquire(rtld_bind_lock, &lockstate);
4845 free_tls(tcb, tcbsize, tcbalign);
4846 lock_release(rtld_bind_lock, &lockstate);
4850 object_add_name(Obj_Entry *obj, const char *name)
4856 entry = malloc(sizeof(Name_Entry) + len);
4858 if (entry != NULL) {
4859 strcpy(entry->name, name);
4860 STAILQ_INSERT_TAIL(&obj->names, entry, link);
4865 object_match_name(const Obj_Entry *obj, const char *name)
4869 STAILQ_FOREACH(entry, &obj->names, link) {
4870 if (strcmp(name, entry->name) == 0)
4877 locate_dependency(const Obj_Entry *obj, const char *name)
4879 const Objlist_Entry *entry;
4880 const Needed_Entry *needed;
4882 STAILQ_FOREACH(entry, &list_main, link) {
4883 if (object_match_name(entry->obj, name))
4887 for (needed = obj->needed; needed != NULL; needed = needed->next) {
4888 if (strcmp(obj->strtab + needed->name, name) == 0 ||
4889 (needed->obj != NULL && object_match_name(needed->obj, name))) {
4891 * If there is DT_NEEDED for the name we are looking for,
4892 * we are all set. Note that object might not be found if
4893 * dependency was not loaded yet, so the function can
4894 * return NULL here. This is expected and handled
4895 * properly by the caller.
4897 return (needed->obj);
4900 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
4906 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
4907 const Elf_Vernaux *vna)
4909 const Elf_Verdef *vd;
4910 const char *vername;
4912 vername = refobj->strtab + vna->vna_name;
4913 vd = depobj->verdef;
4915 _rtld_error("%s: version %s required by %s not defined",
4916 depobj->path, vername, refobj->path);
4920 if (vd->vd_version != VER_DEF_CURRENT) {
4921 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
4922 depobj->path, vd->vd_version);
4925 if (vna->vna_hash == vd->vd_hash) {
4926 const Elf_Verdaux *aux = (const Elf_Verdaux *)
4927 ((char *)vd + vd->vd_aux);
4928 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
4931 if (vd->vd_next == 0)
4933 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4935 if (vna->vna_flags & VER_FLG_WEAK)
4937 _rtld_error("%s: version %s required by %s not found",
4938 depobj->path, vername, refobj->path);
4943 rtld_verify_object_versions(Obj_Entry *obj)
4945 const Elf_Verneed *vn;
4946 const Elf_Verdef *vd;
4947 const Elf_Verdaux *vda;
4948 const Elf_Vernaux *vna;
4949 const Obj_Entry *depobj;
4950 int maxvernum, vernum;
4952 if (obj->ver_checked)
4954 obj->ver_checked = true;
4958 * Walk over defined and required version records and figure out
4959 * max index used by any of them. Do very basic sanity checking
4963 while (vn != NULL) {
4964 if (vn->vn_version != VER_NEED_CURRENT) {
4965 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
4966 obj->path, vn->vn_version);
4969 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4971 vernum = VER_NEED_IDX(vna->vna_other);
4972 if (vernum > maxvernum)
4974 if (vna->vna_next == 0)
4976 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4978 if (vn->vn_next == 0)
4980 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4984 while (vd != NULL) {
4985 if (vd->vd_version != VER_DEF_CURRENT) {
4986 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
4987 obj->path, vd->vd_version);
4990 vernum = VER_DEF_IDX(vd->vd_ndx);
4991 if (vernum > maxvernum)
4993 if (vd->vd_next == 0)
4995 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
5002 * Store version information in array indexable by version index.
5003 * Verify that object version requirements are satisfied along the
5006 obj->vernum = maxvernum + 1;
5007 obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry));
5010 while (vd != NULL) {
5011 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
5012 vernum = VER_DEF_IDX(vd->vd_ndx);
5013 assert(vernum <= maxvernum);
5014 vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
5015 obj->vertab[vernum].hash = vd->vd_hash;
5016 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
5017 obj->vertab[vernum].file = NULL;
5018 obj->vertab[vernum].flags = 0;
5020 if (vd->vd_next == 0)
5022 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
5026 while (vn != NULL) {
5027 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
5030 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
5032 if (check_object_provided_version(obj, depobj, vna))
5034 vernum = VER_NEED_IDX(vna->vna_other);
5035 assert(vernum <= maxvernum);
5036 obj->vertab[vernum].hash = vna->vna_hash;
5037 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
5038 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
5039 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
5040 VER_INFO_HIDDEN : 0;
5041 if (vna->vna_next == 0)
5043 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
5045 if (vn->vn_next == 0)
5047 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
5053 rtld_verify_versions(const Objlist *objlist)
5055 Objlist_Entry *entry;
5059 STAILQ_FOREACH(entry, objlist, link) {
5061 * Skip dummy objects or objects that have their version requirements
5064 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
5066 if (rtld_verify_object_versions(entry->obj) == -1) {
5068 if (ld_tracing == NULL)
5072 if (rc == 0 || ld_tracing != NULL)
5073 rc = rtld_verify_object_versions(&obj_rtld);
5078 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
5083 vernum = VER_NDX(obj->versyms[symnum]);
5084 if (vernum >= obj->vernum) {
5085 _rtld_error("%s: symbol %s has wrong verneed value %d",
5086 obj->path, obj->strtab + symnum, vernum);
5087 } else if (obj->vertab[vernum].hash != 0) {
5088 return &obj->vertab[vernum];
5095 _rtld_get_stack_prot(void)
5098 return (stack_prot);
5102 _rtld_is_dlopened(void *arg)
5105 RtldLockState lockstate;
5108 rlock_acquire(rtld_bind_lock, &lockstate);
5111 obj = obj_from_addr(arg);
5113 _rtld_error("No shared object contains address");
5114 lock_release(rtld_bind_lock, &lockstate);
5117 res = obj->dlopened ? 1 : 0;
5118 lock_release(rtld_bind_lock, &lockstate);
5123 obj_enforce_relro(Obj_Entry *obj)
5126 if (obj->relro_size > 0 && mprotect(obj->relro_page, obj->relro_size,
5128 _rtld_error("%s: Cannot enforce relro protection: %s",
5129 obj->path, rtld_strerror(errno));
5136 map_stacks_exec(RtldLockState *lockstate)
5138 void (*thr_map_stacks_exec)(void);
5140 if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
5142 thr_map_stacks_exec = (void (*)(void))(uintptr_t)
5143 get_program_var_addr("__pthread_map_stacks_exec", lockstate);
5144 if (thr_map_stacks_exec != NULL) {
5145 stack_prot |= PROT_EXEC;
5146 thr_map_stacks_exec();
5151 symlook_init(SymLook *dst, const char *name)
5154 bzero(dst, sizeof(*dst));
5156 dst->hash = elf_hash(name);
5157 dst->hash_gnu = gnu_hash(name);
5161 symlook_init_from_req(SymLook *dst, const SymLook *src)
5164 dst->name = src->name;
5165 dst->hash = src->hash;
5166 dst->hash_gnu = src->hash_gnu;
5167 dst->ventry = src->ventry;
5168 dst->flags = src->flags;
5169 dst->defobj_out = NULL;
5170 dst->sym_out = NULL;
5171 dst->lockstate = src->lockstate;
5176 * Parse a file descriptor number without pulling in more of libc (e.g. atoi).
5179 parse_libdir(const char *str)
5181 static const int RADIX = 10; /* XXXJA: possibly support hex? */
5188 for (c = *str; c != '\0'; c = *++str) {
5189 if (c < '0' || c > '9')
5196 /* Make sure we actually parsed something. */
5198 _rtld_error("failed to parse directory FD from '%s'", str);
5205 * Overrides for libc_pic-provided functions.
5209 __getosreldate(void)
5219 oid[1] = KERN_OSRELDATE;
5221 len = sizeof(osrel);
5222 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
5223 if (error == 0 && osrel > 0 && len == sizeof(osrel))
5235 void (*__cleanup)(void);
5236 int __isthreaded = 0;
5237 int _thread_autoinit_dummy_decl = 1;
5240 * No unresolved symbols for rtld.
5243 __pthread_cxa_finalize(struct dl_phdr_info *a)
5248 __stack_chk_fail(void)
5251 _rtld_error("stack overflow detected; terminated");
5254 __weak_reference(__stack_chk_fail, __stack_chk_fail_local);
5260 _rtld_error("buffer overflow detected; terminated");
5265 rtld_strerror(int errnum)
5268 if (errnum < 0 || errnum >= sys_nerr)
5269 return ("Unknown error");
5270 return (sys_errlist[errnum]);