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 * NB: MIPS uses a private version of this function (_mips_rtld_bind).
706 * Changes to this function should be applied there as well.
709 _rtld_bind(Obj_Entry *obj, Elf_Size reloff)
713 const Obj_Entry *defobj;
716 RtldLockState lockstate;
718 rlock_acquire(rtld_bind_lock, &lockstate);
719 if (sigsetjmp(lockstate.env, 0) != 0)
720 lock_upgrade(rtld_bind_lock, &lockstate);
722 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
724 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
726 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
727 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, SYMLOOK_IN_PLT,
731 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
732 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
734 target = (Elf_Addr)(defobj->relocbase + def->st_value);
736 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
737 defobj->strtab + def->st_name, basename(obj->path),
738 (void *)target, basename(defobj->path));
741 * Write the new contents for the jmpslot. Note that depending on
742 * architecture, the value which we need to return back to the
743 * lazy binding trampoline may or may not be the target
744 * address. The value returned from reloc_jmpslot() is the value
745 * that the trampoline needs.
747 target = reloc_jmpslot(where, target, defobj, obj, rel);
748 lock_release(rtld_bind_lock, &lockstate);
753 * Error reporting function. Use it like printf. If formats the message
754 * into a buffer, and sets things up so that the next call to dlerror()
755 * will return the message.
758 _rtld_error(const char *fmt, ...)
760 static char buf[512];
764 rtld_vsnprintf(buf, sizeof buf, fmt, ap);
770 * Return a dynamically-allocated copy of the current error message, if any.
775 return error_message == NULL ? NULL : xstrdup(error_message);
779 * Restore the current error message from a copy which was previously saved
780 * by errmsg_save(). The copy is freed.
783 errmsg_restore(char *saved_msg)
785 if (saved_msg == NULL)
786 error_message = NULL;
788 _rtld_error("%s", saved_msg);
794 basename(const char *name)
796 const char *p = strrchr(name, '/');
797 return p != NULL ? p + 1 : name;
800 static struct utsname uts;
803 origin_subst_one(Obj_Entry *obj, char *real, const char *kw,
804 const char *subst, bool may_free)
806 char *p, *p1, *res, *resp;
807 int subst_len, kw_len, subst_count, old_len, new_len;
812 * First, count the number of the keyword occurrences, to
813 * preallocate the final string.
815 for (p = real, subst_count = 0;; p = p1 + kw_len, subst_count++) {
822 * If the keyword is not found, just return.
824 * Return non-substituted string if resolution failed. We
825 * cannot do anything more reasonable, the failure mode of the
826 * caller is unresolved library anyway.
828 if (subst_count == 0 || (obj != NULL && !obj_resolve_origin(obj)))
829 return (may_free ? real : xstrdup(real));
831 subst = obj->origin_path;
834 * There is indeed something to substitute. Calculate the
835 * length of the resulting string, and allocate it.
837 subst_len = strlen(subst);
838 old_len = strlen(real);
839 new_len = old_len + (subst_len - kw_len) * subst_count;
840 res = xmalloc(new_len + 1);
843 * Now, execute the substitution loop.
845 for (p = real, resp = res, *resp = '\0';;) {
848 /* Copy the prefix before keyword. */
849 memcpy(resp, p, p1 - p);
851 /* Keyword replacement. */
852 memcpy(resp, subst, subst_len);
860 /* Copy to the end of string and finish. */
868 origin_subst(Obj_Entry *obj, char *real)
870 char *res1, *res2, *res3, *res4;
872 if (obj == NULL || !trust)
873 return (xstrdup(real));
874 if (uts.sysname[0] == '\0') {
875 if (uname(&uts) != 0) {
876 _rtld_error("utsname failed: %d", errno);
880 res1 = origin_subst_one(obj, real, "$ORIGIN", NULL, false);
881 res2 = origin_subst_one(NULL, res1, "$OSNAME", uts.sysname, true);
882 res3 = origin_subst_one(NULL, res2, "$OSREL", uts.release, true);
883 res4 = origin_subst_one(NULL, res3, "$PLATFORM", uts.machine, true);
890 const char *msg = dlerror();
894 rtld_fdputstr(STDERR_FILENO, msg);
895 rtld_fdputchar(STDERR_FILENO, '\n');
900 * Process a shared object's DYNAMIC section, and save the important
901 * information in its Obj_Entry structure.
904 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
905 const Elf_Dyn **dyn_soname, const Elf_Dyn **dyn_runpath)
908 Needed_Entry **needed_tail = &obj->needed;
909 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
910 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
911 const Elf_Hashelt *hashtab;
912 const Elf32_Word *hashval;
913 Elf32_Word bkt, nmaskwords;
915 int plttype = DT_REL;
921 obj->bind_now = false;
922 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
923 switch (dynp->d_tag) {
926 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
930 obj->relsize = dynp->d_un.d_val;
934 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
938 obj->pltrel = (const Elf_Rel *)
939 (obj->relocbase + dynp->d_un.d_ptr);
943 obj->pltrelsize = dynp->d_un.d_val;
947 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
951 obj->relasize = dynp->d_un.d_val;
955 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
959 plttype = dynp->d_un.d_val;
960 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
964 obj->symtab = (const Elf_Sym *)
965 (obj->relocbase + dynp->d_un.d_ptr);
969 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
973 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
977 obj->strsize = dynp->d_un.d_val;
981 obj->verneed = (const Elf_Verneed *) (obj->relocbase +
986 obj->verneednum = dynp->d_un.d_val;
990 obj->verdef = (const Elf_Verdef *) (obj->relocbase +
995 obj->verdefnum = dynp->d_un.d_val;
999 obj->versyms = (const Elf_Versym *)(obj->relocbase +
1005 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1007 obj->nbuckets = hashtab[0];
1008 obj->nchains = hashtab[1];
1009 obj->buckets = hashtab + 2;
1010 obj->chains = obj->buckets + obj->nbuckets;
1011 obj->valid_hash_sysv = obj->nbuckets > 0 && obj->nchains > 0 &&
1012 obj->buckets != NULL;
1018 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1020 obj->nbuckets_gnu = hashtab[0];
1021 obj->symndx_gnu = hashtab[1];
1022 nmaskwords = hashtab[2];
1023 bloom_size32 = (__ELF_WORD_SIZE / 32) * nmaskwords;
1024 obj->maskwords_bm_gnu = nmaskwords - 1;
1025 obj->shift2_gnu = hashtab[3];
1026 obj->bloom_gnu = (Elf_Addr *) (hashtab + 4);
1027 obj->buckets_gnu = hashtab + 4 + bloom_size32;
1028 obj->chain_zero_gnu = obj->buckets_gnu + obj->nbuckets_gnu -
1030 /* Number of bitmask words is required to be power of 2 */
1031 obj->valid_hash_gnu = powerof2(nmaskwords) &&
1032 obj->nbuckets_gnu > 0 && obj->buckets_gnu != NULL;
1038 Needed_Entry *nep = NEW(Needed_Entry);
1039 nep->name = dynp->d_un.d_val;
1044 needed_tail = &nep->next;
1050 Needed_Entry *nep = NEW(Needed_Entry);
1051 nep->name = dynp->d_un.d_val;
1055 *needed_filtees_tail = nep;
1056 needed_filtees_tail = &nep->next;
1062 Needed_Entry *nep = NEW(Needed_Entry);
1063 nep->name = dynp->d_un.d_val;
1067 *needed_aux_filtees_tail = nep;
1068 needed_aux_filtees_tail = &nep->next;
1073 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
1077 obj->textrel = true;
1081 obj->symbolic = true;
1086 * We have to wait until later to process this, because we
1087 * might not have gotten the address of the string table yet.
1097 *dyn_runpath = dynp;
1101 obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1104 case DT_PREINIT_ARRAY:
1105 obj->preinit_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1108 case DT_PREINIT_ARRAYSZ:
1109 obj->preinit_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1113 obj->init_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1116 case DT_INIT_ARRAYSZ:
1117 obj->init_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1121 obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1125 obj->fini_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1128 case DT_FINI_ARRAYSZ:
1129 obj->fini_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1133 * Don't process DT_DEBUG on MIPS as the dynamic section
1134 * is mapped read-only. DT_MIPS_RLD_MAP is used instead.
1140 dbg("Filling in DT_DEBUG entry");
1141 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
1146 if (dynp->d_un.d_val & DF_ORIGIN)
1147 obj->z_origin = true;
1148 if (dynp->d_un.d_val & DF_SYMBOLIC)
1149 obj->symbolic = true;
1150 if (dynp->d_un.d_val & DF_TEXTREL)
1151 obj->textrel = true;
1152 if (dynp->d_un.d_val & DF_BIND_NOW)
1153 obj->bind_now = true;
1154 /*if (dynp->d_un.d_val & DF_STATIC_TLS)
1158 case DT_MIPS_LOCAL_GOTNO:
1159 obj->local_gotno = dynp->d_un.d_val;
1162 case DT_MIPS_SYMTABNO:
1163 obj->symtabno = dynp->d_un.d_val;
1166 case DT_MIPS_GOTSYM:
1167 obj->gotsym = dynp->d_un.d_val;
1170 case DT_MIPS_RLD_MAP:
1171 *((Elf_Addr *)(dynp->d_un.d_ptr)) = (Elf_Addr) &r_debug;
1175 #ifdef __powerpc64__
1176 case DT_PPC64_GLINK:
1177 obj->glink = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1182 if (dynp->d_un.d_val & DF_1_NOOPEN)
1183 obj->z_noopen = true;
1184 if (dynp->d_un.d_val & DF_1_ORIGIN)
1185 obj->z_origin = true;
1186 if (dynp->d_un.d_val & DF_1_GLOBAL)
1187 obj->z_global = true;
1188 if (dynp->d_un.d_val & DF_1_BIND_NOW)
1189 obj->bind_now = true;
1190 if (dynp->d_un.d_val & DF_1_NODELETE)
1191 obj->z_nodelete = true;
1192 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1193 obj->z_loadfltr = true;
1194 if (dynp->d_un.d_val & DF_1_INTERPOSE)
1195 obj->z_interpose = true;
1196 if (dynp->d_un.d_val & DF_1_NODEFLIB)
1197 obj->z_nodeflib = true;
1202 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1209 obj->traced = false;
1211 if (plttype == DT_RELA) {
1212 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1214 obj->pltrelasize = obj->pltrelsize;
1215 obj->pltrelsize = 0;
1218 /* Determine size of dynsym table (equal to nchains of sysv hash) */
1219 if (obj->valid_hash_sysv)
1220 obj->dynsymcount = obj->nchains;
1221 else if (obj->valid_hash_gnu) {
1222 obj->dynsymcount = 0;
1223 for (bkt = 0; bkt < obj->nbuckets_gnu; bkt++) {
1224 if (obj->buckets_gnu[bkt] == 0)
1226 hashval = &obj->chain_zero_gnu[obj->buckets_gnu[bkt]];
1229 while ((*hashval++ & 1u) == 0);
1231 obj->dynsymcount += obj->symndx_gnu;
1236 obj_resolve_origin(Obj_Entry *obj)
1239 if (obj->origin_path != NULL)
1241 obj->origin_path = xmalloc(PATH_MAX);
1242 return (rtld_dirname_abs(obj->path, obj->origin_path) != -1);
1246 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1247 const Elf_Dyn *dyn_soname, const Elf_Dyn *dyn_runpath)
1250 if (obj->z_origin && !obj_resolve_origin(obj))
1253 if (dyn_runpath != NULL) {
1254 obj->runpath = (char *)obj->strtab + dyn_runpath->d_un.d_val;
1255 obj->runpath = origin_subst(obj, obj->runpath);
1256 } else if (dyn_rpath != NULL) {
1257 obj->rpath = (char *)obj->strtab + dyn_rpath->d_un.d_val;
1258 obj->rpath = origin_subst(obj, obj->rpath);
1260 if (dyn_soname != NULL)
1261 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1265 digest_dynamic(Obj_Entry *obj, int early)
1267 const Elf_Dyn *dyn_rpath;
1268 const Elf_Dyn *dyn_soname;
1269 const Elf_Dyn *dyn_runpath;
1271 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname, &dyn_runpath);
1272 digest_dynamic2(obj, dyn_rpath, dyn_soname, dyn_runpath);
1276 * Process a shared object's program header. This is used only for the
1277 * main program, when the kernel has already loaded the main program
1278 * into memory before calling the dynamic linker. It creates and
1279 * returns an Obj_Entry structure.
1282 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1285 const Elf_Phdr *phlimit = phdr + phnum;
1287 Elf_Addr note_start, note_end;
1291 for (ph = phdr; ph < phlimit; ph++) {
1292 if (ph->p_type != PT_PHDR)
1296 obj->phsize = ph->p_memsz;
1297 obj->relocbase = (caddr_t)phdr - ph->p_vaddr;
1301 obj->stack_flags = PF_X | PF_R | PF_W;
1303 for (ph = phdr; ph < phlimit; ph++) {
1304 switch (ph->p_type) {
1307 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1311 if (nsegs == 0) { /* First load segment */
1312 obj->vaddrbase = trunc_page(ph->p_vaddr);
1313 obj->mapbase = obj->vaddrbase + obj->relocbase;
1314 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
1316 } else { /* Last load segment */
1317 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1324 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1329 obj->tlssize = ph->p_memsz;
1330 obj->tlsalign = ph->p_align;
1331 obj->tlsinitsize = ph->p_filesz;
1332 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1336 obj->stack_flags = ph->p_flags;
1340 obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1341 obj->relro_size = round_page(ph->p_memsz);
1345 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
1346 note_end = note_start + ph->p_filesz;
1347 digest_notes(obj, note_start, note_end);
1352 _rtld_error("%s: too few PT_LOAD segments", path);
1361 digest_notes(Obj_Entry *obj, Elf_Addr note_start, Elf_Addr note_end)
1363 const Elf_Note *note;
1364 const char *note_name;
1367 for (note = (const Elf_Note *)note_start; (Elf_Addr)note < note_end;
1368 note = (const Elf_Note *)((const char *)(note + 1) +
1369 roundup2(note->n_namesz, sizeof(Elf32_Addr)) +
1370 roundup2(note->n_descsz, sizeof(Elf32_Addr)))) {
1371 if (note->n_namesz != sizeof(NOTE_FREEBSD_VENDOR) ||
1372 note->n_descsz != sizeof(int32_t))
1374 if (note->n_type != NT_FREEBSD_ABI_TAG &&
1375 note->n_type != NT_FREEBSD_NOINIT_TAG)
1377 note_name = (const char *)(note + 1);
1378 if (strncmp(NOTE_FREEBSD_VENDOR, note_name,
1379 sizeof(NOTE_FREEBSD_VENDOR)) != 0)
1381 switch (note->n_type) {
1382 case NT_FREEBSD_ABI_TAG:
1383 /* FreeBSD osrel note */
1384 p = (uintptr_t)(note + 1);
1385 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1386 obj->osrel = *(const int32_t *)(p);
1387 dbg("note osrel %d", obj->osrel);
1389 case NT_FREEBSD_NOINIT_TAG:
1390 /* FreeBSD 'crt does not call init' note */
1391 obj->crt_no_init = true;
1392 dbg("note crt_no_init");
1399 dlcheck(void *handle)
1403 TAILQ_FOREACH(obj, &obj_list, next) {
1404 if (obj == (Obj_Entry *) handle)
1408 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1409 _rtld_error("Invalid shared object handle %p", handle);
1416 * If the given object is already in the donelist, return true. Otherwise
1417 * add the object to the list and return false.
1420 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1424 for (i = 0; i < dlp->num_used; i++)
1425 if (dlp->objs[i] == obj)
1428 * Our donelist allocation should always be sufficient. But if
1429 * our threads locking isn't working properly, more shared objects
1430 * could have been loaded since we allocated the list. That should
1431 * never happen, but we'll handle it properly just in case it does.
1433 if (dlp->num_used < dlp->num_alloc)
1434 dlp->objs[dlp->num_used++] = obj;
1439 * Hash function for symbol table lookup. Don't even think about changing
1440 * this. It is specified by the System V ABI.
1443 elf_hash(const char *name)
1445 const unsigned char *p = (const unsigned char *) name;
1446 unsigned long h = 0;
1449 while (*p != '\0') {
1450 h = (h << 4) + *p++;
1451 if ((g = h & 0xf0000000) != 0)
1459 * The GNU hash function is the Daniel J. Bernstein hash clipped to 32 bits
1460 * unsigned in case it's implemented with a wider type.
1463 gnu_hash(const char *s)
1469 for (c = *s; c != '\0'; c = *++s)
1471 return (h & 0xffffffff);
1476 * Find the library with the given name, and return its full pathname.
1477 * The returned string is dynamically allocated. Generates an error
1478 * message and returns NULL if the library cannot be found.
1480 * If the second argument is non-NULL, then it refers to an already-
1481 * loaded shared object, whose library search path will be searched.
1483 * If a library is successfully located via LD_LIBRARY_PATH_FDS, its
1484 * descriptor (which is close-on-exec) will be passed out via the third
1487 * The search order is:
1488 * DT_RPATH in the referencing file _unless_ DT_RUNPATH is present (1)
1489 * DT_RPATH of the main object if DSO without defined DT_RUNPATH (1)
1491 * DT_RUNPATH in the referencing file
1492 * ldconfig hints (if -z nodefaultlib, filter out default library directories
1494 * /lib:/usr/lib _unless_ the referencing file is linked with -z nodefaultlib
1496 * (1) Handled in digest_dynamic2 - rpath left NULL if runpath defined.
1499 find_library(const char *xname, const Obj_Entry *refobj, int *fdp)
1503 bool nodeflib, objgiven;
1505 objgiven = refobj != NULL;
1506 if (strchr(xname, '/') != NULL) { /* Hard coded pathname */
1507 if (xname[0] != '/' && !trust) {
1508 _rtld_error("Absolute pathname required for shared object \"%s\"",
1512 return (origin_subst(__DECONST(Obj_Entry *, refobj),
1513 __DECONST(char *, xname)));
1516 if (libmap_disable || !objgiven ||
1517 (name = lm_find(refobj->path, xname)) == NULL)
1518 name = (char *)xname;
1520 dbg(" Searching for \"%s\"", name);
1523 * If refobj->rpath != NULL, then refobj->runpath is NULL. Fall
1524 * back to pre-conforming behaviour if user requested so with
1525 * LD_LIBRARY_PATH_RPATH environment variable and ignore -z
1528 if (objgiven && refobj->rpath != NULL && ld_library_path_rpath) {
1529 if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
1531 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
1532 (pathname = search_library_pathfds(name, ld_library_dirs, fdp)) != NULL ||
1533 (pathname = search_library_path(name, gethints(false))) != NULL ||
1534 (pathname = search_library_path(name, ld_standard_library_path)) != NULL)
1537 nodeflib = objgiven ? refobj->z_nodeflib : false;
1539 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
1540 (objgiven && refobj->runpath == NULL && refobj != obj_main &&
1541 (pathname = search_library_path(name, obj_main->rpath)) != NULL) ||
1542 (pathname = search_library_path(name, ld_library_path)) != NULL ||
1544 (pathname = search_library_path(name, refobj->runpath)) != NULL) ||
1545 (pathname = search_library_pathfds(name, ld_library_dirs, fdp)) != NULL ||
1546 (pathname = search_library_path(name, gethints(nodeflib))) != NULL ||
1547 (objgiven && !nodeflib &&
1548 (pathname = search_library_path(name, ld_standard_library_path)) != NULL))
1552 if (objgiven && refobj->path != NULL) {
1553 _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
1554 name, basename(refobj->path));
1556 _rtld_error("Shared object \"%s\" not found", name);
1562 * Given a symbol number in a referencing object, find the corresponding
1563 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1564 * no definition was found. Returns a pointer to the Obj_Entry of the
1565 * defining object via the reference parameter DEFOBJ_OUT.
1568 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1569 const Obj_Entry **defobj_out, int flags, SymCache *cache,
1570 RtldLockState *lockstate)
1574 const Obj_Entry *defobj;
1580 * If we have already found this symbol, get the information from
1583 if (symnum >= refobj->dynsymcount)
1584 return NULL; /* Bad object */
1585 if (cache != NULL && cache[symnum].sym != NULL) {
1586 *defobj_out = cache[symnum].obj;
1587 return cache[symnum].sym;
1590 ref = refobj->symtab + symnum;
1591 name = refobj->strtab + ref->st_name;
1596 * We don't have to do a full scale lookup if the symbol is local.
1597 * We know it will bind to the instance in this load module; to
1598 * which we already have a pointer (ie ref). By not doing a lookup,
1599 * we not only improve performance, but it also avoids unresolvable
1600 * symbols when local symbols are not in the hash table. This has
1601 * been seen with the ia64 toolchain.
1603 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1604 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1605 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1608 symlook_init(&req, name);
1610 req.ventry = fetch_ventry(refobj, symnum);
1611 req.lockstate = lockstate;
1612 res = symlook_default(&req, refobj);
1615 defobj = req.defobj_out;
1623 * If we found no definition and the reference is weak, treat the
1624 * symbol as having the value zero.
1626 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1632 *defobj_out = defobj;
1633 /* Record the information in the cache to avoid subsequent lookups. */
1634 if (cache != NULL) {
1635 cache[symnum].sym = def;
1636 cache[symnum].obj = defobj;
1639 if (refobj != &obj_rtld)
1640 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1646 * Return the search path from the ldconfig hints file, reading it if
1647 * necessary. If nostdlib is true, then the default search paths are
1648 * not added to result.
1650 * Returns NULL if there are problems with the hints file,
1651 * or if the search path there is empty.
1654 gethints(bool nostdlib)
1656 static char *hints, *filtered_path;
1657 static struct elfhints_hdr hdr;
1658 struct fill_search_info_args sargs, hargs;
1659 struct dl_serinfo smeta, hmeta, *SLPinfo, *hintinfo;
1660 struct dl_serpath *SLPpath, *hintpath;
1662 struct stat hint_stat;
1663 unsigned int SLPndx, hintndx, fndx, fcount;
1669 /* First call, read the hints file */
1670 if (hints == NULL) {
1671 /* Keep from trying again in case the hints file is bad. */
1674 if ((fd = open(ld_elf_hints_path, O_RDONLY | O_CLOEXEC)) == -1)
1678 * Check of hdr.dirlistlen value against type limit
1679 * intends to pacify static analyzers. Further
1680 * paranoia leads to checks that dirlist is fully
1681 * contained in the file range.
1683 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1684 hdr.magic != ELFHINTS_MAGIC ||
1685 hdr.version != 1 || hdr.dirlistlen > UINT_MAX / 2 ||
1686 fstat(fd, &hint_stat) == -1) {
1693 if (dl + hdr.dirlist < dl)
1696 if (dl + hdr.dirlistlen < dl)
1698 dl += hdr.dirlistlen;
1699 if (dl > hint_stat.st_size)
1701 p = xmalloc(hdr.dirlistlen + 1);
1703 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1704 read(fd, p, hdr.dirlistlen + 1) !=
1705 (ssize_t)hdr.dirlistlen + 1 || p[hdr.dirlistlen] != '\0') {
1714 * If caller agreed to receive list which includes the default
1715 * paths, we are done. Otherwise, if we still did not
1716 * calculated filtered result, do it now.
1719 return (hints[0] != '\0' ? hints : NULL);
1720 if (filtered_path != NULL)
1724 * Obtain the list of all configured search paths, and the
1725 * list of the default paths.
1727 * First estimate the size of the results.
1729 smeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1731 hmeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1734 sargs.request = RTLD_DI_SERINFOSIZE;
1735 sargs.serinfo = &smeta;
1736 hargs.request = RTLD_DI_SERINFOSIZE;
1737 hargs.serinfo = &hmeta;
1739 path_enumerate(ld_standard_library_path, fill_search_info, &sargs);
1740 path_enumerate(hints, fill_search_info, &hargs);
1742 SLPinfo = xmalloc(smeta.dls_size);
1743 hintinfo = xmalloc(hmeta.dls_size);
1746 * Next fetch both sets of paths.
1748 sargs.request = RTLD_DI_SERINFO;
1749 sargs.serinfo = SLPinfo;
1750 sargs.serpath = &SLPinfo->dls_serpath[0];
1751 sargs.strspace = (char *)&SLPinfo->dls_serpath[smeta.dls_cnt];
1753 hargs.request = RTLD_DI_SERINFO;
1754 hargs.serinfo = hintinfo;
1755 hargs.serpath = &hintinfo->dls_serpath[0];
1756 hargs.strspace = (char *)&hintinfo->dls_serpath[hmeta.dls_cnt];
1758 path_enumerate(ld_standard_library_path, fill_search_info, &sargs);
1759 path_enumerate(hints, fill_search_info, &hargs);
1762 * Now calculate the difference between two sets, by excluding
1763 * standard paths from the full set.
1767 filtered_path = xmalloc(hdr.dirlistlen + 1);
1768 hintpath = &hintinfo->dls_serpath[0];
1769 for (hintndx = 0; hintndx < hmeta.dls_cnt; hintndx++, hintpath++) {
1771 SLPpath = &SLPinfo->dls_serpath[0];
1773 * Check each standard path against current.
1775 for (SLPndx = 0; SLPndx < smeta.dls_cnt; SLPndx++, SLPpath++) {
1776 /* matched, skip the path */
1777 if (!strcmp(hintpath->dls_name, SLPpath->dls_name)) {
1785 * Not matched against any standard path, add the path
1786 * to result. Separate consequtive paths with ':'.
1789 filtered_path[fndx] = ':';
1793 flen = strlen(hintpath->dls_name);
1794 strncpy((filtered_path + fndx), hintpath->dls_name, flen);
1797 filtered_path[fndx] = '\0';
1803 return (filtered_path[0] != '\0' ? filtered_path : NULL);
1807 init_dag(Obj_Entry *root)
1809 const Needed_Entry *needed;
1810 const Objlist_Entry *elm;
1813 if (root->dag_inited)
1815 donelist_init(&donelist);
1817 /* Root object belongs to own DAG. */
1818 objlist_push_tail(&root->dldags, root);
1819 objlist_push_tail(&root->dagmembers, root);
1820 donelist_check(&donelist, root);
1823 * Add dependencies of root object to DAG in breadth order
1824 * by exploiting the fact that each new object get added
1825 * to the tail of the dagmembers list.
1827 STAILQ_FOREACH(elm, &root->dagmembers, link) {
1828 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
1829 if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
1831 objlist_push_tail(&needed->obj->dldags, root);
1832 objlist_push_tail(&root->dagmembers, needed->obj);
1835 root->dag_inited = true;
1839 init_marker(Obj_Entry *marker)
1842 bzero(marker, sizeof(*marker));
1843 marker->marker = true;
1847 globallist_curr(const Obj_Entry *obj)
1854 return (__DECONST(Obj_Entry *, obj));
1855 obj = TAILQ_PREV(obj, obj_entry_q, next);
1860 globallist_next(const Obj_Entry *obj)
1864 obj = TAILQ_NEXT(obj, next);
1868 return (__DECONST(Obj_Entry *, obj));
1872 /* Prevent the object from being unmapped while the bind lock is dropped. */
1874 hold_object(Obj_Entry *obj)
1881 unhold_object(Obj_Entry *obj)
1884 assert(obj->holdcount > 0);
1885 if (--obj->holdcount == 0 && obj->unholdfree)
1886 release_object(obj);
1890 process_z(Obj_Entry *root)
1892 const Objlist_Entry *elm;
1896 * Walk over object DAG and process every dependent object
1897 * that is marked as DF_1_NODELETE or DF_1_GLOBAL. They need
1898 * to grow their own DAG.
1900 * For DF_1_GLOBAL, DAG is required for symbol lookups in
1901 * symlook_global() to work.
1903 * For DF_1_NODELETE, the DAG should have its reference upped.
1905 STAILQ_FOREACH(elm, &root->dagmembers, link) {
1909 if (obj->z_nodelete && !obj->ref_nodel) {
1910 dbg("obj %s -z nodelete", obj->path);
1913 obj->ref_nodel = true;
1915 if (obj->z_global && objlist_find(&list_global, obj) == NULL) {
1916 dbg("obj %s -z global", obj->path);
1917 objlist_push_tail(&list_global, obj);
1923 * Initialize the dynamic linker. The argument is the address at which
1924 * the dynamic linker has been mapped into memory. The primary task of
1925 * this function is to relocate the dynamic linker.
1928 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
1930 Obj_Entry objtmp; /* Temporary rtld object */
1931 const Elf_Ehdr *ehdr;
1932 const Elf_Dyn *dyn_rpath;
1933 const Elf_Dyn *dyn_soname;
1934 const Elf_Dyn *dyn_runpath;
1936 #ifdef RTLD_INIT_PAGESIZES_EARLY
1937 /* The page size is required by the dynamic memory allocator. */
1938 init_pagesizes(aux_info);
1942 * Conjure up an Obj_Entry structure for the dynamic linker.
1944 * The "path" member can't be initialized yet because string constants
1945 * cannot yet be accessed. Below we will set it correctly.
1947 memset(&objtmp, 0, sizeof(objtmp));
1950 objtmp.mapbase = mapbase;
1952 objtmp.relocbase = mapbase;
1955 objtmp.dynamic = rtld_dynamic(&objtmp);
1956 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname, &dyn_runpath);
1957 assert(objtmp.needed == NULL);
1958 #if !defined(__mips__)
1959 /* MIPS has a bogus DT_TEXTREL. */
1960 assert(!objtmp.textrel);
1963 * Temporarily put the dynamic linker entry into the object list, so
1964 * that symbols can be found.
1966 relocate_objects(&objtmp, true, &objtmp, 0, NULL);
1968 ehdr = (Elf_Ehdr *)mapbase;
1969 objtmp.phdr = (Elf_Phdr *)((char *)mapbase + ehdr->e_phoff);
1970 objtmp.phsize = ehdr->e_phnum * sizeof(objtmp.phdr[0]);
1972 /* Initialize the object list. */
1973 TAILQ_INIT(&obj_list);
1975 /* Now that non-local variables can be accesses, copy out obj_rtld. */
1976 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1978 #ifndef RTLD_INIT_PAGESIZES_EARLY
1979 /* The page size is required by the dynamic memory allocator. */
1980 init_pagesizes(aux_info);
1983 if (aux_info[AT_OSRELDATE] != NULL)
1984 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
1986 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname, dyn_runpath);
1988 /* Replace the path with a dynamically allocated copy. */
1989 obj_rtld.path = xstrdup(ld_path_rtld);
1991 r_debug.r_brk = r_debug_state;
1992 r_debug.r_state = RT_CONSISTENT;
1996 * Retrieve the array of supported page sizes. The kernel provides the page
1997 * sizes in increasing order.
2000 init_pagesizes(Elf_Auxinfo **aux_info)
2002 static size_t psa[MAXPAGESIZES];
2006 if (aux_info[AT_PAGESIZES] != NULL && aux_info[AT_PAGESIZESLEN] !=
2008 size = aux_info[AT_PAGESIZESLEN]->a_un.a_val;
2009 pagesizes = aux_info[AT_PAGESIZES]->a_un.a_ptr;
2012 if (sysctlnametomib("hw.pagesizes", mib, &len) == 0)
2015 /* As a fallback, retrieve the base page size. */
2016 size = sizeof(psa[0]);
2017 if (aux_info[AT_PAGESZ] != NULL) {
2018 psa[0] = aux_info[AT_PAGESZ]->a_un.a_val;
2022 mib[1] = HW_PAGESIZE;
2026 if (sysctl(mib, len, psa, &size, NULL, 0) == -1) {
2027 _rtld_error("sysctl for hw.pagesize(s) failed");
2033 npagesizes = size / sizeof(pagesizes[0]);
2034 /* Discard any invalid entries at the end of the array. */
2035 while (npagesizes > 0 && pagesizes[npagesizes - 1] == 0)
2040 * Add the init functions from a needed object list (and its recursive
2041 * needed objects) to "list". This is not used directly; it is a helper
2042 * function for initlist_add_objects(). The write lock must be held
2043 * when this function is called.
2046 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
2048 /* Recursively process the successor needed objects. */
2049 if (needed->next != NULL)
2050 initlist_add_neededs(needed->next, list);
2052 /* Process the current needed object. */
2053 if (needed->obj != NULL)
2054 initlist_add_objects(needed->obj, needed->obj, list);
2058 * Scan all of the DAGs rooted in the range of objects from "obj" to
2059 * "tail" and add their init functions to "list". This recurses over
2060 * the DAGs and ensure the proper init ordering such that each object's
2061 * needed libraries are initialized before the object itself. At the
2062 * same time, this function adds the objects to the global finalization
2063 * list "list_fini" in the opposite order. The write lock must be
2064 * held when this function is called.
2067 initlist_add_objects(Obj_Entry *obj, Obj_Entry *tail, Objlist *list)
2071 if (obj->init_scanned || obj->init_done)
2073 obj->init_scanned = true;
2075 /* Recursively process the successor objects. */
2076 nobj = globallist_next(obj);
2077 if (nobj != NULL && obj != tail)
2078 initlist_add_objects(nobj, tail, list);
2080 /* Recursively process the needed objects. */
2081 if (obj->needed != NULL)
2082 initlist_add_neededs(obj->needed, list);
2083 if (obj->needed_filtees != NULL)
2084 initlist_add_neededs(obj->needed_filtees, list);
2085 if (obj->needed_aux_filtees != NULL)
2086 initlist_add_neededs(obj->needed_aux_filtees, list);
2088 /* Add the object to the init list. */
2089 if (obj->preinit_array != (Elf_Addr)NULL || obj->init != (Elf_Addr)NULL ||
2090 obj->init_array != (Elf_Addr)NULL)
2091 objlist_push_tail(list, obj);
2093 /* Add the object to the global fini list in the reverse order. */
2094 if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL)
2095 && !obj->on_fini_list) {
2096 objlist_push_head(&list_fini, obj);
2097 obj->on_fini_list = true;
2102 #define FPTR_TARGET(f) ((Elf_Addr) (f))
2106 free_needed_filtees(Needed_Entry *n)
2108 Needed_Entry *needed, *needed1;
2110 for (needed = n; needed != NULL; needed = needed->next) {
2111 if (needed->obj != NULL) {
2112 dlclose(needed->obj);
2116 for (needed = n; needed != NULL; needed = needed1) {
2117 needed1 = needed->next;
2123 unload_filtees(Obj_Entry *obj)
2126 free_needed_filtees(obj->needed_filtees);
2127 obj->needed_filtees = NULL;
2128 free_needed_filtees(obj->needed_aux_filtees);
2129 obj->needed_aux_filtees = NULL;
2130 obj->filtees_loaded = false;
2134 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags,
2135 RtldLockState *lockstate)
2138 for (; needed != NULL; needed = needed->next) {
2139 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
2140 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
2141 RTLD_LOCAL, lockstate);
2146 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
2149 lock_restart_for_upgrade(lockstate);
2150 if (!obj->filtees_loaded) {
2151 load_filtee1(obj, obj->needed_filtees, flags, lockstate);
2152 load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate);
2153 obj->filtees_loaded = true;
2158 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
2162 for (; needed != NULL; needed = needed->next) {
2163 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
2164 flags & ~RTLD_LO_NOLOAD);
2165 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
2172 * Given a shared object, traverse its list of needed objects, and load
2173 * each of them. Returns 0 on success. Generates an error message and
2174 * returns -1 on failure.
2177 load_needed_objects(Obj_Entry *first, int flags)
2181 for (obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
2184 if (process_needed(obj, obj->needed, flags) == -1)
2191 load_preload_objects(void)
2193 char *p = ld_preload;
2195 static const char delim[] = " \t:;";
2200 p += strspn(p, delim);
2201 while (*p != '\0') {
2202 size_t len = strcspn(p, delim);
2207 obj = load_object(p, -1, NULL, 0);
2209 return -1; /* XXX - cleanup */
2210 obj->z_interpose = true;
2213 p += strspn(p, delim);
2215 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
2220 printable_path(const char *path)
2223 return (path == NULL ? "<unknown>" : path);
2227 * Load a shared object into memory, if it is not already loaded. The
2228 * object may be specified by name or by user-supplied file descriptor
2229 * fd_u. In the later case, the fd_u descriptor is not closed, but its
2232 * Returns a pointer to the Obj_Entry for the object. Returns NULL
2236 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
2245 TAILQ_FOREACH(obj, &obj_list, next) {
2246 if (obj->marker || obj->doomed)
2248 if (object_match_name(obj, name))
2252 path = find_library(name, refobj, &fd);
2260 * search_library_pathfds() opens a fresh file descriptor for the
2261 * library, so there is no need to dup().
2263 } else if (fd_u == -1) {
2265 * If we didn't find a match by pathname, or the name is not
2266 * supplied, open the file and check again by device and inode.
2267 * This avoids false mismatches caused by multiple links or ".."
2270 * To avoid a race, we open the file and use fstat() rather than
2273 if ((fd = open(path, O_RDONLY | O_CLOEXEC | O_VERIFY)) == -1) {
2274 _rtld_error("Cannot open \"%s\"", path);
2279 fd = fcntl(fd_u, F_DUPFD_CLOEXEC, 0);
2281 _rtld_error("Cannot dup fd");
2286 if (fstat(fd, &sb) == -1) {
2287 _rtld_error("Cannot fstat \"%s\"", printable_path(path));
2292 TAILQ_FOREACH(obj, &obj_list, next) {
2293 if (obj->marker || obj->doomed)
2295 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
2298 if (obj != NULL && name != NULL) {
2299 object_add_name(obj, name);
2304 if (flags & RTLD_LO_NOLOAD) {
2310 /* First use of this object, so we must map it in */
2311 obj = do_load_object(fd, name, path, &sb, flags);
2320 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
2327 * but first, make sure that environment variables haven't been
2328 * used to circumvent the noexec flag on a filesystem.
2330 if (dangerous_ld_env) {
2331 if (fstatfs(fd, &fs) != 0) {
2332 _rtld_error("Cannot fstatfs \"%s\"", printable_path(path));
2335 if (fs.f_flags & MNT_NOEXEC) {
2336 _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
2340 dbg("loading \"%s\"", printable_path(path));
2341 obj = map_object(fd, printable_path(path), sbp);
2346 * If DT_SONAME is present in the object, digest_dynamic2 already
2347 * added it to the object names.
2350 object_add_name(obj, name);
2352 digest_dynamic(obj, 0);
2353 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path,
2354 obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount);
2355 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
2357 dbg("refusing to load non-loadable \"%s\"", obj->path);
2358 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
2359 munmap(obj->mapbase, obj->mapsize);
2364 obj->dlopened = (flags & RTLD_LO_DLOPEN) != 0;
2365 TAILQ_INSERT_TAIL(&obj_list, obj, next);
2368 linkmap_add(obj); /* for GDB & dlinfo() */
2369 max_stack_flags |= obj->stack_flags;
2371 dbg(" %p .. %p: %s", obj->mapbase,
2372 obj->mapbase + obj->mapsize - 1, obj->path);
2374 dbg(" WARNING: %s has impure text", obj->path);
2375 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
2382 obj_from_addr(const void *addr)
2386 TAILQ_FOREACH(obj, &obj_list, next) {
2389 if (addr < (void *) obj->mapbase)
2391 if (addr < (void *) (obj->mapbase + obj->mapsize))
2400 Elf_Addr *preinit_addr;
2403 preinit_addr = (Elf_Addr *)obj_main->preinit_array;
2404 if (preinit_addr == NULL)
2407 for (index = 0; index < obj_main->preinit_array_num; index++) {
2408 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) {
2409 dbg("calling preinit function for %s at %p", obj_main->path,
2410 (void *)preinit_addr[index]);
2411 LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index],
2412 0, 0, obj_main->path);
2413 call_init_pointer(obj_main, preinit_addr[index]);
2419 * Call the finalization functions for each of the objects in "list"
2420 * belonging to the DAG of "root" and referenced once. If NULL "root"
2421 * is specified, every finalization function will be called regardless
2422 * of the reference count and the list elements won't be freed. All of
2423 * the objects are expected to have non-NULL fini functions.
2426 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
2430 Elf_Addr *fini_addr;
2433 assert(root == NULL || root->refcount == 1);
2436 root->doomed = true;
2439 * Preserve the current error message since a fini function might
2440 * call into the dynamic linker and overwrite it.
2442 saved_msg = errmsg_save();
2444 STAILQ_FOREACH(elm, list, link) {
2445 if (root != NULL && (elm->obj->refcount != 1 ||
2446 objlist_find(&root->dagmembers, elm->obj) == NULL))
2448 /* Remove object from fini list to prevent recursive invocation. */
2449 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2450 /* Ensure that new references cannot be acquired. */
2451 elm->obj->doomed = true;
2453 hold_object(elm->obj);
2454 lock_release(rtld_bind_lock, lockstate);
2456 * It is legal to have both DT_FINI and DT_FINI_ARRAY defined.
2457 * When this happens, DT_FINI_ARRAY is processed first.
2459 fini_addr = (Elf_Addr *)elm->obj->fini_array;
2460 if (fini_addr != NULL && elm->obj->fini_array_num > 0) {
2461 for (index = elm->obj->fini_array_num - 1; index >= 0;
2463 if (fini_addr[index] != 0 && fini_addr[index] != 1) {
2464 dbg("calling fini function for %s at %p",
2465 elm->obj->path, (void *)fini_addr[index]);
2466 LD_UTRACE(UTRACE_FINI_CALL, elm->obj,
2467 (void *)fini_addr[index], 0, 0, elm->obj->path);
2468 call_initfini_pointer(elm->obj, fini_addr[index]);
2472 if (elm->obj->fini != (Elf_Addr)NULL) {
2473 dbg("calling fini function for %s at %p", elm->obj->path,
2474 (void *)elm->obj->fini);
2475 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini,
2476 0, 0, elm->obj->path);
2477 call_initfini_pointer(elm->obj, elm->obj->fini);
2479 wlock_acquire(rtld_bind_lock, lockstate);
2480 unhold_object(elm->obj);
2481 /* No need to free anything if process is going down. */
2485 * We must restart the list traversal after every fini call
2486 * because a dlclose() call from the fini function or from
2487 * another thread might have modified the reference counts.
2491 } while (elm != NULL);
2492 errmsg_restore(saved_msg);
2496 * Call the initialization functions for each of the objects in
2497 * "list". All of the objects are expected to have non-NULL init
2501 objlist_call_init(Objlist *list, RtldLockState *lockstate)
2506 Elf_Addr *init_addr;
2510 * Clean init_scanned flag so that objects can be rechecked and
2511 * possibly initialized earlier if any of vectors called below
2512 * cause the change by using dlopen.
2514 TAILQ_FOREACH(obj, &obj_list, next) {
2517 obj->init_scanned = false;
2521 * Preserve the current error message since an init function might
2522 * call into the dynamic linker and overwrite it.
2524 saved_msg = errmsg_save();
2525 STAILQ_FOREACH(elm, list, link) {
2526 if (elm->obj->init_done) /* Initialized early. */
2529 * Race: other thread might try to use this object before current
2530 * one completes the initialization. Not much can be done here
2531 * without better locking.
2533 elm->obj->init_done = true;
2534 hold_object(elm->obj);
2535 lock_release(rtld_bind_lock, lockstate);
2538 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined.
2539 * When this happens, DT_INIT is processed first.
2541 if (elm->obj->init != (Elf_Addr)NULL) {
2542 dbg("calling init function for %s at %p", elm->obj->path,
2543 (void *)elm->obj->init);
2544 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init,
2545 0, 0, elm->obj->path);
2546 call_initfini_pointer(elm->obj, elm->obj->init);
2548 init_addr = (Elf_Addr *)elm->obj->init_array;
2549 if (init_addr != NULL) {
2550 for (index = 0; index < elm->obj->init_array_num; index++) {
2551 if (init_addr[index] != 0 && init_addr[index] != 1) {
2552 dbg("calling init function for %s at %p", elm->obj->path,
2553 (void *)init_addr[index]);
2554 LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
2555 (void *)init_addr[index], 0, 0, elm->obj->path);
2556 call_init_pointer(elm->obj, init_addr[index]);
2560 wlock_acquire(rtld_bind_lock, lockstate);
2561 unhold_object(elm->obj);
2563 errmsg_restore(saved_msg);
2567 objlist_clear(Objlist *list)
2571 while (!STAILQ_EMPTY(list)) {
2572 elm = STAILQ_FIRST(list);
2573 STAILQ_REMOVE_HEAD(list, link);
2578 static Objlist_Entry *
2579 objlist_find(Objlist *list, const Obj_Entry *obj)
2583 STAILQ_FOREACH(elm, list, link)
2584 if (elm->obj == obj)
2590 objlist_init(Objlist *list)
2596 objlist_push_head(Objlist *list, Obj_Entry *obj)
2600 elm = NEW(Objlist_Entry);
2602 STAILQ_INSERT_HEAD(list, elm, link);
2606 objlist_push_tail(Objlist *list, Obj_Entry *obj)
2610 elm = NEW(Objlist_Entry);
2612 STAILQ_INSERT_TAIL(list, elm, link);
2616 objlist_put_after(Objlist *list, Obj_Entry *listobj, Obj_Entry *obj)
2618 Objlist_Entry *elm, *listelm;
2620 STAILQ_FOREACH(listelm, list, link) {
2621 if (listelm->obj == listobj)
2624 elm = NEW(Objlist_Entry);
2626 if (listelm != NULL)
2627 STAILQ_INSERT_AFTER(list, listelm, elm, link);
2629 STAILQ_INSERT_TAIL(list, elm, link);
2633 objlist_remove(Objlist *list, Obj_Entry *obj)
2637 if ((elm = objlist_find(list, obj)) != NULL) {
2638 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2644 * Relocate dag rooted in the specified object.
2645 * Returns 0 on success, or -1 on failure.
2649 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj,
2650 int flags, RtldLockState *lockstate)
2656 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2657 error = relocate_object(elm->obj, bind_now, rtldobj, flags,
2666 * Prepare for, or clean after, relocating an object marked with
2667 * DT_TEXTREL or DF_TEXTREL. Before relocating, all read-only
2668 * segments are remapped read-write. After relocations are done, the
2669 * segment's permissions are returned back to the modes specified in
2670 * the phdrs. If any relocation happened, or always for wired
2671 * program, COW is triggered.
2674 reloc_textrel_prot(Obj_Entry *obj, bool before)
2681 for (l = obj->phsize / sizeof(*ph), ph = obj->phdr; l > 0;
2683 if (ph->p_type != PT_LOAD || (ph->p_flags & PF_W) != 0)
2685 base = obj->relocbase + trunc_page(ph->p_vaddr);
2686 sz = round_page(ph->p_vaddr + ph->p_filesz) -
2687 trunc_page(ph->p_vaddr);
2688 prot = convert_prot(ph->p_flags) | (before ? PROT_WRITE : 0);
2689 if (mprotect(base, sz, prot) == -1) {
2690 _rtld_error("%s: Cannot write-%sable text segment: %s",
2691 obj->path, before ? "en" : "dis",
2692 rtld_strerror(errno));
2700 * Relocate single object.
2701 * Returns 0 on success, or -1 on failure.
2704 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
2705 int flags, RtldLockState *lockstate)
2710 obj->relocated = true;
2712 dbg("relocating \"%s\"", obj->path);
2714 if (obj->symtab == NULL || obj->strtab == NULL ||
2715 !(obj->valid_hash_sysv || obj->valid_hash_gnu)) {
2716 _rtld_error("%s: Shared object has no run-time symbol table",
2721 /* There are relocations to the write-protected text segment. */
2722 if (obj->textrel && reloc_textrel_prot(obj, true) != 0)
2725 /* Process the non-PLT non-IFUNC relocations. */
2726 if (reloc_non_plt(obj, rtldobj, flags, lockstate))
2729 /* Re-protected the text segment. */
2730 if (obj->textrel && reloc_textrel_prot(obj, false) != 0)
2733 /* Set the special PLT or GOT entries. */
2736 /* Process the PLT relocations. */
2737 if (reloc_plt(obj) == -1)
2739 /* Relocate the jump slots if we are doing immediate binding. */
2740 if (obj->bind_now || bind_now)
2741 if (reloc_jmpslots(obj, flags, lockstate) == -1)
2745 * Process the non-PLT IFUNC relocations. The relocations are
2746 * processed in two phases, because IFUNC resolvers may
2747 * reference other symbols, which must be readily processed
2748 * before resolvers are called.
2750 if (obj->non_plt_gnu_ifunc &&
2751 reloc_non_plt(obj, rtldobj, flags | SYMLOOK_IFUNC, lockstate))
2754 if (!obj->mainprog && obj_enforce_relro(obj) == -1)
2758 * Set up the magic number and version in the Obj_Entry. These
2759 * were checked in the crt1.o from the original ElfKit, so we
2760 * set them for backward compatibility.
2762 obj->magic = RTLD_MAGIC;
2763 obj->version = RTLD_VERSION;
2769 * Relocate newly-loaded shared objects. The argument is a pointer to
2770 * the Obj_Entry for the first such object. All objects from the first
2771 * to the end of the list of objects are relocated. Returns 0 on success,
2775 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
2776 int flags, RtldLockState *lockstate)
2781 for (error = 0, obj = first; obj != NULL;
2782 obj = TAILQ_NEXT(obj, next)) {
2785 error = relocate_object(obj, bind_now, rtldobj, flags,
2794 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
2795 * referencing STT_GNU_IFUNC symbols is postponed till the other
2796 * relocations are done. The indirect functions specified as
2797 * ifunc are allowed to call other symbols, so we need to have
2798 * objects relocated before asking for resolution from indirects.
2800 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
2801 * instead of the usual lazy handling of PLT slots. It is
2802 * consistent with how GNU does it.
2805 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags,
2806 RtldLockState *lockstate)
2808 if (obj->irelative && reloc_iresolve(obj, lockstate) == -1)
2810 if ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
2811 reloc_gnu_ifunc(obj, flags, lockstate) == -1)
2817 resolve_objects_ifunc(Obj_Entry *first, bool bind_now, int flags,
2818 RtldLockState *lockstate)
2822 for (obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
2825 if (resolve_object_ifunc(obj, bind_now, flags, lockstate) == -1)
2832 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags,
2833 RtldLockState *lockstate)
2837 STAILQ_FOREACH(elm, list, link) {
2838 if (resolve_object_ifunc(elm->obj, bind_now, flags,
2846 * Cleanup procedure. It will be called (by the atexit mechanism) just
2847 * before the process exits.
2852 RtldLockState lockstate;
2854 wlock_acquire(rtld_bind_lock, &lockstate);
2856 objlist_call_fini(&list_fini, NULL, &lockstate);
2857 /* No need to remove the items from the list, since we are exiting. */
2858 if (!libmap_disable)
2860 lock_release(rtld_bind_lock, &lockstate);
2864 * Iterate over a search path, translate each element, and invoke the
2865 * callback on the result.
2868 path_enumerate(const char *path, path_enum_proc callback, void *arg)
2874 path += strspn(path, ":;");
2875 while (*path != '\0') {
2879 len = strcspn(path, ":;");
2880 trans = lm_findn(NULL, path, len);
2882 res = callback(trans, strlen(trans), arg);
2884 res = callback(path, len, arg);
2890 path += strspn(path, ":;");
2896 struct try_library_args {
2904 try_library_path(const char *dir, size_t dirlen, void *param)
2906 struct try_library_args *arg;
2909 if (*dir == '/' || trust) {
2912 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
2915 pathname = arg->buffer;
2916 strncpy(pathname, dir, dirlen);
2917 pathname[dirlen] = '/';
2918 strcpy(pathname + dirlen + 1, arg->name);
2920 dbg(" Trying \"%s\"", pathname);
2921 if (access(pathname, F_OK) == 0) { /* We found it */
2922 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
2923 strcpy(pathname, arg->buffer);
2931 search_library_path(const char *name, const char *path)
2934 struct try_library_args arg;
2940 arg.namelen = strlen(name);
2941 arg.buffer = xmalloc(PATH_MAX);
2942 arg.buflen = PATH_MAX;
2944 p = path_enumerate(path, try_library_path, &arg);
2953 * Finds the library with the given name using the directory descriptors
2954 * listed in the LD_LIBRARY_PATH_FDS environment variable.
2956 * Returns a freshly-opened close-on-exec file descriptor for the library,
2957 * or -1 if the library cannot be found.
2960 search_library_pathfds(const char *name, const char *path, int *fdp)
2962 char *envcopy, *fdstr, *found, *last_token;
2966 dbg("%s('%s', '%s', fdp)", __func__, name, path);
2968 /* Don't load from user-specified libdirs into setuid binaries. */
2972 /* We can't do anything if LD_LIBRARY_PATH_FDS isn't set. */
2976 /* LD_LIBRARY_PATH_FDS only works with relative paths. */
2977 if (name[0] == '/') {
2978 dbg("Absolute path (%s) passed to %s", name, __func__);
2983 * Use strtok_r() to walk the FD:FD:FD list. This requires a local
2984 * copy of the path, as strtok_r rewrites separator tokens
2988 envcopy = xstrdup(path);
2989 for (fdstr = strtok_r(envcopy, ":", &last_token); fdstr != NULL;
2990 fdstr = strtok_r(NULL, ":", &last_token)) {
2991 dirfd = parse_libdir(fdstr);
2994 fd = __sys_openat(dirfd, name, O_RDONLY | O_CLOEXEC | O_VERIFY);
2997 len = strlen(fdstr) + strlen(name) + 3;
2998 found = xmalloc(len);
2999 if (rtld_snprintf(found, len, "#%d/%s", dirfd, name) < 0) {
3000 _rtld_error("error generating '%d/%s'",
3004 dbg("open('%s') => %d", found, fd);
3015 dlclose(void *handle)
3018 RtldLockState lockstate;
3020 wlock_acquire(rtld_bind_lock, &lockstate);
3021 root = dlcheck(handle);
3023 lock_release(rtld_bind_lock, &lockstate);
3026 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
3029 /* Unreference the object and its dependencies. */
3030 root->dl_refcount--;
3032 if (root->refcount == 1) {
3034 * The object will be no longer referenced, so we must unload it.
3035 * First, call the fini functions.
3037 objlist_call_fini(&list_fini, root, &lockstate);
3041 /* Finish cleaning up the newly-unreferenced objects. */
3042 GDB_STATE(RT_DELETE,&root->linkmap);
3043 unload_object(root);
3044 GDB_STATE(RT_CONSISTENT,NULL);
3048 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
3049 lock_release(rtld_bind_lock, &lockstate);
3056 char *msg = error_message;
3057 error_message = NULL;
3062 * This function is deprecated and has no effect.
3065 dllockinit(void *context,
3066 void *(*lock_create)(void *context),
3067 void (*rlock_acquire)(void *lock),
3068 void (*wlock_acquire)(void *lock),
3069 void (*lock_release)(void *lock),
3070 void (*lock_destroy)(void *lock),
3071 void (*context_destroy)(void *context))
3073 static void *cur_context;
3074 static void (*cur_context_destroy)(void *);
3076 /* Just destroy the context from the previous call, if necessary. */
3077 if (cur_context_destroy != NULL)
3078 cur_context_destroy(cur_context);
3079 cur_context = context;
3080 cur_context_destroy = context_destroy;
3084 dlopen(const char *name, int mode)
3087 return (rtld_dlopen(name, -1, mode));
3091 fdlopen(int fd, int mode)
3094 return (rtld_dlopen(NULL, fd, mode));
3098 rtld_dlopen(const char *name, int fd, int mode)
3100 RtldLockState lockstate;
3103 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
3104 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
3105 if (ld_tracing != NULL) {
3106 rlock_acquire(rtld_bind_lock, &lockstate);
3107 if (sigsetjmp(lockstate.env, 0) != 0)
3108 lock_upgrade(rtld_bind_lock, &lockstate);
3109 environ = (char **)*get_program_var_addr("environ", &lockstate);
3110 lock_release(rtld_bind_lock, &lockstate);
3112 lo_flags = RTLD_LO_DLOPEN;
3113 if (mode & RTLD_NODELETE)
3114 lo_flags |= RTLD_LO_NODELETE;
3115 if (mode & RTLD_NOLOAD)
3116 lo_flags |= RTLD_LO_NOLOAD;
3117 if (ld_tracing != NULL)
3118 lo_flags |= RTLD_LO_TRACE;
3120 return (dlopen_object(name, fd, obj_main, lo_flags,
3121 mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL));
3125 dlopen_cleanup(Obj_Entry *obj)
3130 if (obj->refcount == 0)
3135 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
3136 int mode, RtldLockState *lockstate)
3138 Obj_Entry *old_obj_tail;
3141 RtldLockState mlockstate;
3144 objlist_init(&initlist);
3146 if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) {
3147 wlock_acquire(rtld_bind_lock, &mlockstate);
3148 lockstate = &mlockstate;
3150 GDB_STATE(RT_ADD,NULL);
3152 old_obj_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
3154 if (name == NULL && fd == -1) {
3158 obj = load_object(name, fd, refobj, lo_flags);
3163 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
3164 objlist_push_tail(&list_global, obj);
3165 if (globallist_next(old_obj_tail) != NULL) {
3166 /* We loaded something new. */
3167 assert(globallist_next(old_obj_tail) == obj);
3168 result = load_needed_objects(obj,
3169 lo_flags & (RTLD_LO_DLOPEN | RTLD_LO_EARLY));
3173 result = rtld_verify_versions(&obj->dagmembers);
3174 if (result != -1 && ld_tracing)
3176 if (result == -1 || relocate_object_dag(obj,
3177 (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld,
3178 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3180 dlopen_cleanup(obj);
3182 } else if (lo_flags & RTLD_LO_EARLY) {
3184 * Do not call the init functions for early loaded
3185 * filtees. The image is still not initialized enough
3188 * Our object is found by the global object list and
3189 * will be ordered among all init calls done right
3190 * before transferring control to main.
3193 /* Make list of init functions to call. */
3194 initlist_add_objects(obj, obj, &initlist);
3197 * Process all no_delete or global objects here, given
3198 * them own DAGs to prevent their dependencies from being
3199 * unloaded. This has to be done after we have loaded all
3200 * of the dependencies, so that we do not miss any.
3206 * Bump the reference counts for objects on this DAG. If
3207 * this is the first dlopen() call for the object that was
3208 * already loaded as a dependency, initialize the dag
3214 if ((lo_flags & RTLD_LO_TRACE) != 0)
3217 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
3218 obj->z_nodelete) && !obj->ref_nodel) {
3219 dbg("obj %s nodelete", obj->path);
3221 obj->z_nodelete = obj->ref_nodel = true;
3225 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
3227 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
3229 if (!(lo_flags & RTLD_LO_EARLY)) {
3230 map_stacks_exec(lockstate);
3233 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
3234 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3236 objlist_clear(&initlist);
3237 dlopen_cleanup(obj);
3238 if (lockstate == &mlockstate)
3239 lock_release(rtld_bind_lock, lockstate);
3243 if (!(lo_flags & RTLD_LO_EARLY)) {
3244 /* Call the init functions. */
3245 objlist_call_init(&initlist, lockstate);
3247 objlist_clear(&initlist);
3248 if (lockstate == &mlockstate)
3249 lock_release(rtld_bind_lock, lockstate);
3252 trace_loaded_objects(obj);
3253 if (lockstate == &mlockstate)
3254 lock_release(rtld_bind_lock, lockstate);
3259 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
3263 const Obj_Entry *obj, *defobj;
3266 RtldLockState lockstate;
3273 symlook_init(&req, name);
3275 req.flags = flags | SYMLOOK_IN_PLT;
3276 req.lockstate = &lockstate;
3278 LD_UTRACE(UTRACE_DLSYM_START, handle, NULL, 0, 0, name);
3279 rlock_acquire(rtld_bind_lock, &lockstate);
3280 if (sigsetjmp(lockstate.env, 0) != 0)
3281 lock_upgrade(rtld_bind_lock, &lockstate);
3282 if (handle == NULL || handle == RTLD_NEXT ||
3283 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
3285 if ((obj = obj_from_addr(retaddr)) == NULL) {
3286 _rtld_error("Cannot determine caller's shared object");
3287 lock_release(rtld_bind_lock, &lockstate);
3288 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3291 if (handle == NULL) { /* Just the caller's shared object. */
3292 res = symlook_obj(&req, obj);
3295 defobj = req.defobj_out;
3297 } else if (handle == RTLD_NEXT || /* Objects after caller's */
3298 handle == RTLD_SELF) { /* ... caller included */
3299 if (handle == RTLD_NEXT)
3300 obj = globallist_next(obj);
3301 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
3304 res = symlook_obj(&req, obj);
3307 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) {
3309 defobj = req.defobj_out;
3310 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3316 * Search the dynamic linker itself, and possibly resolve the
3317 * symbol from there. This is how the application links to
3318 * dynamic linker services such as dlopen.
3320 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3321 res = symlook_obj(&req, &obj_rtld);
3324 defobj = req.defobj_out;
3328 assert(handle == RTLD_DEFAULT);
3329 res = symlook_default(&req, obj);
3331 defobj = req.defobj_out;
3336 if ((obj = dlcheck(handle)) == NULL) {
3337 lock_release(rtld_bind_lock, &lockstate);
3338 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3342 donelist_init(&donelist);
3343 if (obj->mainprog) {
3344 /* Handle obtained by dlopen(NULL, ...) implies global scope. */
3345 res = symlook_global(&req, &donelist);
3348 defobj = req.defobj_out;
3351 * Search the dynamic linker itself, and possibly resolve the
3352 * symbol from there. This is how the application links to
3353 * dynamic linker services such as dlopen.
3355 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3356 res = symlook_obj(&req, &obj_rtld);
3359 defobj = req.defobj_out;
3364 /* Search the whole DAG rooted at the given object. */
3365 res = symlook_list(&req, &obj->dagmembers, &donelist);
3368 defobj = req.defobj_out;
3374 lock_release(rtld_bind_lock, &lockstate);
3377 * The value required by the caller is derived from the value
3378 * of the symbol. this is simply the relocated value of the
3381 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
3382 sym = make_function_pointer(def, defobj);
3383 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
3384 sym = rtld_resolve_ifunc(defobj, def);
3385 else if (ELF_ST_TYPE(def->st_info) == STT_TLS) {
3386 ti.ti_module = defobj->tlsindex;
3387 ti.ti_offset = def->st_value;
3388 sym = __tls_get_addr(&ti);
3390 sym = defobj->relocbase + def->st_value;
3391 LD_UTRACE(UTRACE_DLSYM_STOP, handle, sym, 0, 0, name);
3395 _rtld_error("Undefined symbol \"%s\"", name);
3396 lock_release(rtld_bind_lock, &lockstate);
3397 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3402 dlsym(void *handle, const char *name)
3404 return do_dlsym(handle, name, __builtin_return_address(0), NULL,
3409 dlfunc(void *handle, const char *name)
3416 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
3422 dlvsym(void *handle, const char *name, const char *version)
3426 ventry.name = version;
3428 ventry.hash = elf_hash(version);
3430 return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
3435 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
3437 const Obj_Entry *obj;
3438 RtldLockState lockstate;
3440 rlock_acquire(rtld_bind_lock, &lockstate);
3441 obj = obj_from_addr(addr);
3443 _rtld_error("No shared object contains address");
3444 lock_release(rtld_bind_lock, &lockstate);
3447 rtld_fill_dl_phdr_info(obj, phdr_info);
3448 lock_release(rtld_bind_lock, &lockstate);
3453 dladdr(const void *addr, Dl_info *info)
3455 const Obj_Entry *obj;
3458 unsigned long symoffset;
3459 RtldLockState lockstate;
3461 rlock_acquire(rtld_bind_lock, &lockstate);
3462 obj = obj_from_addr(addr);
3464 _rtld_error("No shared object contains address");
3465 lock_release(rtld_bind_lock, &lockstate);
3468 info->dli_fname = obj->path;
3469 info->dli_fbase = obj->mapbase;
3470 info->dli_saddr = (void *)0;
3471 info->dli_sname = NULL;
3474 * Walk the symbol list looking for the symbol whose address is
3475 * closest to the address sent in.
3477 for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) {
3478 def = obj->symtab + symoffset;
3481 * For skip the symbol if st_shndx is either SHN_UNDEF or
3484 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
3488 * If the symbol is greater than the specified address, or if it
3489 * is further away from addr than the current nearest symbol,
3492 symbol_addr = obj->relocbase + def->st_value;
3493 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
3496 /* Update our idea of the nearest symbol. */
3497 info->dli_sname = obj->strtab + def->st_name;
3498 info->dli_saddr = symbol_addr;
3501 if (info->dli_saddr == addr)
3504 lock_release(rtld_bind_lock, &lockstate);
3509 dlinfo(void *handle, int request, void *p)
3511 const Obj_Entry *obj;
3512 RtldLockState lockstate;
3515 rlock_acquire(rtld_bind_lock, &lockstate);
3517 if (handle == NULL || handle == RTLD_SELF) {
3520 retaddr = __builtin_return_address(0); /* __GNUC__ only */
3521 if ((obj = obj_from_addr(retaddr)) == NULL)
3522 _rtld_error("Cannot determine caller's shared object");
3524 obj = dlcheck(handle);
3527 lock_release(rtld_bind_lock, &lockstate);
3533 case RTLD_DI_LINKMAP:
3534 *((struct link_map const **)p) = &obj->linkmap;
3536 case RTLD_DI_ORIGIN:
3537 error = rtld_dirname(obj->path, p);
3540 case RTLD_DI_SERINFOSIZE:
3541 case RTLD_DI_SERINFO:
3542 error = do_search_info(obj, request, (struct dl_serinfo *)p);
3546 _rtld_error("Invalid request %d passed to dlinfo()", request);
3550 lock_release(rtld_bind_lock, &lockstate);
3556 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
3559 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
3560 phdr_info->dlpi_name = obj->path;
3561 phdr_info->dlpi_phdr = obj->phdr;
3562 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
3563 phdr_info->dlpi_tls_modid = obj->tlsindex;
3564 phdr_info->dlpi_tls_data = obj->tlsinit;
3565 phdr_info->dlpi_adds = obj_loads;
3566 phdr_info->dlpi_subs = obj_loads - obj_count;
3570 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
3572 struct dl_phdr_info phdr_info;
3573 Obj_Entry *obj, marker;
3574 RtldLockState bind_lockstate, phdr_lockstate;
3577 init_marker(&marker);
3580 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
3581 wlock_acquire(rtld_bind_lock, &bind_lockstate);
3582 for (obj = globallist_curr(TAILQ_FIRST(&obj_list)); obj != NULL;) {
3583 TAILQ_INSERT_AFTER(&obj_list, obj, &marker, next);
3584 rtld_fill_dl_phdr_info(obj, &phdr_info);
3586 lock_release(rtld_bind_lock, &bind_lockstate);
3588 error = callback(&phdr_info, sizeof phdr_info, param);
3590 wlock_acquire(rtld_bind_lock, &bind_lockstate);
3592 obj = globallist_next(&marker);
3593 TAILQ_REMOVE(&obj_list, &marker, next);
3595 lock_release(rtld_bind_lock, &bind_lockstate);
3596 lock_release(rtld_phdr_lock, &phdr_lockstate);
3602 rtld_fill_dl_phdr_info(&obj_rtld, &phdr_info);
3603 lock_release(rtld_bind_lock, &bind_lockstate);
3604 error = callback(&phdr_info, sizeof(phdr_info), param);
3606 lock_release(rtld_phdr_lock, &phdr_lockstate);
3611 fill_search_info(const char *dir, size_t dirlen, void *param)
3613 struct fill_search_info_args *arg;
3617 if (arg->request == RTLD_DI_SERINFOSIZE) {
3618 arg->serinfo->dls_cnt ++;
3619 arg->serinfo->dls_size += sizeof(struct dl_serpath) + dirlen + 1;
3621 struct dl_serpath *s_entry;
3623 s_entry = arg->serpath;
3624 s_entry->dls_name = arg->strspace;
3625 s_entry->dls_flags = arg->flags;
3627 strncpy(arg->strspace, dir, dirlen);
3628 arg->strspace[dirlen] = '\0';
3630 arg->strspace += dirlen + 1;
3638 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
3640 struct dl_serinfo _info;
3641 struct fill_search_info_args args;
3643 args.request = RTLD_DI_SERINFOSIZE;
3644 args.serinfo = &_info;
3646 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
3649 path_enumerate(obj->rpath, fill_search_info, &args);
3650 path_enumerate(ld_library_path, fill_search_info, &args);
3651 path_enumerate(obj->runpath, fill_search_info, &args);
3652 path_enumerate(gethints(obj->z_nodeflib), fill_search_info, &args);
3653 if (!obj->z_nodeflib)
3654 path_enumerate(ld_standard_library_path, fill_search_info, &args);
3657 if (request == RTLD_DI_SERINFOSIZE) {
3658 info->dls_size = _info.dls_size;
3659 info->dls_cnt = _info.dls_cnt;
3663 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
3664 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
3668 args.request = RTLD_DI_SERINFO;
3669 args.serinfo = info;
3670 args.serpath = &info->dls_serpath[0];
3671 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
3673 args.flags = LA_SER_RUNPATH;
3674 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
3677 args.flags = LA_SER_LIBPATH;
3678 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
3681 args.flags = LA_SER_RUNPATH;
3682 if (path_enumerate(obj->runpath, fill_search_info, &args) != NULL)
3685 args.flags = LA_SER_CONFIG;
3686 if (path_enumerate(gethints(obj->z_nodeflib), fill_search_info, &args)
3690 args.flags = LA_SER_DEFAULT;
3691 if (!obj->z_nodeflib &&
3692 path_enumerate(ld_standard_library_path, fill_search_info, &args) != NULL)
3698 rtld_dirname(const char *path, char *bname)
3702 /* Empty or NULL string gets treated as "." */
3703 if (path == NULL || *path == '\0') {
3709 /* Strip trailing slashes */
3710 endp = path + strlen(path) - 1;
3711 while (endp > path && *endp == '/')
3714 /* Find the start of the dir */
3715 while (endp > path && *endp != '/')
3718 /* Either the dir is "/" or there are no slashes */
3720 bname[0] = *endp == '/' ? '/' : '.';
3726 } while (endp > path && *endp == '/');
3729 if (endp - path + 2 > PATH_MAX)
3731 _rtld_error("Filename is too long: %s", path);
3735 strncpy(bname, path, endp - path + 1);
3736 bname[endp - path + 1] = '\0';
3741 rtld_dirname_abs(const char *path, char *base)
3745 if (realpath(path, base) == NULL)
3747 dbg("%s -> %s", path, base);
3748 last = strrchr(base, '/');
3757 linkmap_add(Obj_Entry *obj)
3759 struct link_map *l = &obj->linkmap;
3760 struct link_map *prev;
3762 obj->linkmap.l_name = obj->path;
3763 obj->linkmap.l_addr = obj->mapbase;
3764 obj->linkmap.l_ld = obj->dynamic;
3766 /* GDB needs load offset on MIPS to use the symbols */
3767 obj->linkmap.l_offs = obj->relocbase;
3770 if (r_debug.r_map == NULL) {
3776 * Scan to the end of the list, but not past the entry for the
3777 * dynamic linker, which we want to keep at the very end.
3779 for (prev = r_debug.r_map;
3780 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
3781 prev = prev->l_next)
3784 /* Link in the new entry. */
3786 l->l_next = prev->l_next;
3787 if (l->l_next != NULL)
3788 l->l_next->l_prev = l;
3793 linkmap_delete(Obj_Entry *obj)
3795 struct link_map *l = &obj->linkmap;
3797 if (l->l_prev == NULL) {
3798 if ((r_debug.r_map = l->l_next) != NULL)
3799 l->l_next->l_prev = NULL;
3803 if ((l->l_prev->l_next = l->l_next) != NULL)
3804 l->l_next->l_prev = l->l_prev;
3808 * Function for the debugger to set a breakpoint on to gain control.
3810 * The two parameters allow the debugger to easily find and determine
3811 * what the runtime loader is doing and to whom it is doing it.
3813 * When the loadhook trap is hit (r_debug_state, set at program
3814 * initialization), the arguments can be found on the stack:
3816 * +8 struct link_map *m
3817 * +4 struct r_debug *rd
3821 r_debug_state(struct r_debug* rd, struct link_map *m)
3824 * The following is a hack to force the compiler to emit calls to
3825 * this function, even when optimizing. If the function is empty,
3826 * the compiler is not obliged to emit any code for calls to it,
3827 * even when marked __noinline. However, gdb depends on those
3830 __compiler_membar();
3834 * A function called after init routines have completed. This can be used to
3835 * break before a program's entry routine is called, and can be used when
3836 * main is not available in the symbol table.
3839 _r_debug_postinit(struct link_map *m)
3842 /* See r_debug_state(). */
3843 __compiler_membar();
3847 release_object(Obj_Entry *obj)
3850 if (obj->holdcount > 0) {
3851 obj->unholdfree = true;
3854 munmap(obj->mapbase, obj->mapsize);
3855 linkmap_delete(obj);
3860 * Get address of the pointer variable in the main program.
3861 * Prefer non-weak symbol over the weak one.
3863 static const void **
3864 get_program_var_addr(const char *name, RtldLockState *lockstate)
3869 symlook_init(&req, name);
3870 req.lockstate = lockstate;
3871 donelist_init(&donelist);
3872 if (symlook_global(&req, &donelist) != 0)
3874 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
3875 return ((const void **)make_function_pointer(req.sym_out,
3877 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
3878 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
3880 return ((const void **)(req.defobj_out->relocbase +
3881 req.sym_out->st_value));
3885 * Set a pointer variable in the main program to the given value. This
3886 * is used to set key variables such as "environ" before any of the
3887 * init functions are called.
3890 set_program_var(const char *name, const void *value)
3894 if ((addr = get_program_var_addr(name, NULL)) != NULL) {
3895 dbg("\"%s\": *%p <-- %p", name, addr, value);
3901 * Search the global objects, including dependencies and main object,
3902 * for the given symbol.
3905 symlook_global(SymLook *req, DoneList *donelist)
3908 const Objlist_Entry *elm;
3911 symlook_init_from_req(&req1, req);
3913 /* Search all objects loaded at program start up. */
3914 if (req->defobj_out == NULL ||
3915 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3916 res = symlook_list(&req1, &list_main, donelist);
3917 if (res == 0 && (req->defobj_out == NULL ||
3918 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3919 req->sym_out = req1.sym_out;
3920 req->defobj_out = req1.defobj_out;
3921 assert(req->defobj_out != NULL);
3925 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
3926 STAILQ_FOREACH(elm, &list_global, link) {
3927 if (req->defobj_out != NULL &&
3928 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3930 res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
3931 if (res == 0 && (req->defobj_out == NULL ||
3932 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3933 req->sym_out = req1.sym_out;
3934 req->defobj_out = req1.defobj_out;
3935 assert(req->defobj_out != NULL);
3939 return (req->sym_out != NULL ? 0 : ESRCH);
3943 * Given a symbol name in a referencing object, find the corresponding
3944 * definition of the symbol. Returns a pointer to the symbol, or NULL if
3945 * no definition was found. Returns a pointer to the Obj_Entry of the
3946 * defining object via the reference parameter DEFOBJ_OUT.
3949 symlook_default(SymLook *req, const Obj_Entry *refobj)
3952 const Objlist_Entry *elm;
3956 donelist_init(&donelist);
3957 symlook_init_from_req(&req1, req);
3959 /* Look first in the referencing object if linked symbolically. */
3960 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
3961 res = symlook_obj(&req1, refobj);
3963 req->sym_out = req1.sym_out;
3964 req->defobj_out = req1.defobj_out;
3965 assert(req->defobj_out != NULL);
3969 symlook_global(req, &donelist);
3971 /* Search all dlopened DAGs containing the referencing object. */
3972 STAILQ_FOREACH(elm, &refobj->dldags, link) {
3973 if (req->sym_out != NULL &&
3974 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3976 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
3977 if (res == 0 && (req->sym_out == NULL ||
3978 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3979 req->sym_out = req1.sym_out;
3980 req->defobj_out = req1.defobj_out;
3981 assert(req->defobj_out != NULL);
3986 * Search the dynamic linker itself, and possibly resolve the
3987 * symbol from there. This is how the application links to
3988 * dynamic linker services such as dlopen.
3990 if (req->sym_out == NULL ||
3991 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3992 res = symlook_obj(&req1, &obj_rtld);
3994 req->sym_out = req1.sym_out;
3995 req->defobj_out = req1.defobj_out;
3996 assert(req->defobj_out != NULL);
4000 return (req->sym_out != NULL ? 0 : ESRCH);
4004 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
4007 const Obj_Entry *defobj;
4008 const Objlist_Entry *elm;
4014 STAILQ_FOREACH(elm, objlist, link) {
4015 if (donelist_check(dlp, elm->obj))
4017 symlook_init_from_req(&req1, req);
4018 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
4019 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
4021 defobj = req1.defobj_out;
4022 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
4029 req->defobj_out = defobj;
4036 * Search the chain of DAGS cointed to by the given Needed_Entry
4037 * for a symbol of the given name. Each DAG is scanned completely
4038 * before advancing to the next one. Returns a pointer to the symbol,
4039 * or NULL if no definition was found.
4042 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
4045 const Needed_Entry *n;
4046 const Obj_Entry *defobj;
4052 symlook_init_from_req(&req1, req);
4053 for (n = needed; n != NULL; n = n->next) {
4054 if (n->obj == NULL ||
4055 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
4057 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
4059 defobj = req1.defobj_out;
4060 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
4066 req->defobj_out = defobj;
4073 * Search the symbol table of a single shared object for a symbol of
4074 * the given name and version, if requested. Returns a pointer to the
4075 * symbol, or NULL if no definition was found. If the object is
4076 * filter, return filtered symbol from filtee.
4078 * The symbol's hash value is passed in for efficiency reasons; that
4079 * eliminates many recomputations of the hash value.
4082 symlook_obj(SymLook *req, const Obj_Entry *obj)
4086 int flags, res, mres;
4089 * If there is at least one valid hash at this point, we prefer to
4090 * use the faster GNU version if available.
4092 if (obj->valid_hash_gnu)
4093 mres = symlook_obj1_gnu(req, obj);
4094 else if (obj->valid_hash_sysv)
4095 mres = symlook_obj1_sysv(req, obj);
4100 if (obj->needed_filtees != NULL) {
4101 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4102 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4103 donelist_init(&donelist);
4104 symlook_init_from_req(&req1, req);
4105 res = symlook_needed(&req1, obj->needed_filtees, &donelist);
4107 req->sym_out = req1.sym_out;
4108 req->defobj_out = req1.defobj_out;
4112 if (obj->needed_aux_filtees != NULL) {
4113 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4114 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4115 donelist_init(&donelist);
4116 symlook_init_from_req(&req1, req);
4117 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
4119 req->sym_out = req1.sym_out;
4120 req->defobj_out = req1.defobj_out;
4128 /* Symbol match routine common to both hash functions */
4130 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result,
4131 const unsigned long symnum)
4134 const Elf_Sym *symp;
4137 symp = obj->symtab + symnum;
4138 strp = obj->strtab + symp->st_name;
4140 switch (ELF_ST_TYPE(symp->st_info)) {
4146 if (symp->st_value == 0)
4150 if (symp->st_shndx != SHN_UNDEF)
4153 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
4154 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
4161 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
4164 if (req->ventry == NULL) {
4165 if (obj->versyms != NULL) {
4166 verndx = VER_NDX(obj->versyms[symnum]);
4167 if (verndx > obj->vernum) {
4169 "%s: symbol %s references wrong version %d",
4170 obj->path, obj->strtab + symnum, verndx);
4174 * If we are not called from dlsym (i.e. this
4175 * is a normal relocation from unversioned
4176 * binary), accept the symbol immediately if
4177 * it happens to have first version after this
4178 * shared object became versioned. Otherwise,
4179 * if symbol is versioned and not hidden,
4180 * remember it. If it is the only symbol with
4181 * this name exported by the shared object, it
4182 * will be returned as a match by the calling
4183 * function. If symbol is global (verndx < 2)
4184 * accept it unconditionally.
4186 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
4187 verndx == VER_NDX_GIVEN) {
4188 result->sym_out = symp;
4191 else if (verndx >= VER_NDX_GIVEN) {
4192 if ((obj->versyms[symnum] & VER_NDX_HIDDEN)
4194 if (result->vsymp == NULL)
4195 result->vsymp = symp;
4201 result->sym_out = symp;
4204 if (obj->versyms == NULL) {
4205 if (object_match_name(obj, req->ventry->name)) {
4206 _rtld_error("%s: object %s should provide version %s "
4207 "for symbol %s", obj_rtld.path, obj->path,
4208 req->ventry->name, obj->strtab + symnum);
4212 verndx = VER_NDX(obj->versyms[symnum]);
4213 if (verndx > obj->vernum) {
4214 _rtld_error("%s: symbol %s references wrong version %d",
4215 obj->path, obj->strtab + symnum, verndx);
4218 if (obj->vertab[verndx].hash != req->ventry->hash ||
4219 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
4221 * Version does not match. Look if this is a
4222 * global symbol and if it is not hidden. If
4223 * global symbol (verndx < 2) is available,
4224 * use it. Do not return symbol if we are
4225 * called by dlvsym, because dlvsym looks for
4226 * a specific version and default one is not
4227 * what dlvsym wants.
4229 if ((req->flags & SYMLOOK_DLSYM) ||
4230 (verndx >= VER_NDX_GIVEN) ||
4231 (obj->versyms[symnum] & VER_NDX_HIDDEN))
4235 result->sym_out = symp;
4240 * Search for symbol using SysV hash function.
4241 * obj->buckets is known not to be NULL at this point; the test for this was
4242 * performed with the obj->valid_hash_sysv assignment.
4245 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj)
4247 unsigned long symnum;
4248 Sym_Match_Result matchres;
4250 matchres.sym_out = NULL;
4251 matchres.vsymp = NULL;
4252 matchres.vcount = 0;
4254 for (symnum = obj->buckets[req->hash % obj->nbuckets];
4255 symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
4256 if (symnum >= obj->nchains)
4257 return (ESRCH); /* Bad object */
4259 if (matched_symbol(req, obj, &matchres, symnum)) {
4260 req->sym_out = matchres.sym_out;
4261 req->defobj_out = obj;
4265 if (matchres.vcount == 1) {
4266 req->sym_out = matchres.vsymp;
4267 req->defobj_out = obj;
4273 /* Search for symbol using GNU hash function */
4275 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj)
4277 Elf_Addr bloom_word;
4278 const Elf32_Word *hashval;
4280 Sym_Match_Result matchres;
4281 unsigned int h1, h2;
4282 unsigned long symnum;
4284 matchres.sym_out = NULL;
4285 matchres.vsymp = NULL;
4286 matchres.vcount = 0;
4288 /* Pick right bitmask word from Bloom filter array */
4289 bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) &
4290 obj->maskwords_bm_gnu];
4292 /* Calculate modulus word size of gnu hash and its derivative */
4293 h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1);
4294 h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1));
4296 /* Filter out the "definitely not in set" queries */
4297 if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0)
4300 /* Locate hash chain and corresponding value element*/
4301 bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu];
4304 hashval = &obj->chain_zero_gnu[bucket];
4306 if (((*hashval ^ req->hash_gnu) >> 1) == 0) {
4307 symnum = hashval - obj->chain_zero_gnu;
4308 if (matched_symbol(req, obj, &matchres, symnum)) {
4309 req->sym_out = matchres.sym_out;
4310 req->defobj_out = obj;
4314 } while ((*hashval++ & 1) == 0);
4315 if (matchres.vcount == 1) {
4316 req->sym_out = matchres.vsymp;
4317 req->defobj_out = obj;
4324 trace_loaded_objects(Obj_Entry *obj)
4326 char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
4329 if ((main_local = getenv(_LD("TRACE_LOADED_OBJECTS_PROGNAME"))) == NULL)
4332 if ((fmt1 = getenv(_LD("TRACE_LOADED_OBJECTS_FMT1"))) == NULL)
4333 fmt1 = "\t%o => %p (%x)\n";
4335 if ((fmt2 = getenv(_LD("TRACE_LOADED_OBJECTS_FMT2"))) == NULL)
4336 fmt2 = "\t%o (%x)\n";
4338 list_containers = getenv(_LD("TRACE_LOADED_OBJECTS_ALL"));
4340 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
4341 Needed_Entry *needed;
4347 if (list_containers && obj->needed != NULL)
4348 rtld_printf("%s:\n", obj->path);
4349 for (needed = obj->needed; needed; needed = needed->next) {
4350 if (needed->obj != NULL) {
4351 if (needed->obj->traced && !list_containers)
4353 needed->obj->traced = true;
4354 path = needed->obj->path;
4358 name = (char *)obj->strtab + needed->name;
4359 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
4361 fmt = is_lib ? fmt1 : fmt2;
4362 while ((c = *fmt++) != '\0') {
4388 rtld_putstr(main_local);
4391 rtld_putstr(obj_main->path);
4398 rtld_printf("%d", sodp->sod_major);
4401 rtld_printf("%d", sodp->sod_minor);
4408 rtld_printf("%p", needed->obj ? needed->obj->mapbase :
4421 * Unload a dlopened object and its dependencies from memory and from
4422 * our data structures. It is assumed that the DAG rooted in the
4423 * object has already been unreferenced, and that the object has a
4424 * reference count of 0.
4427 unload_object(Obj_Entry *root)
4429 Obj_Entry marker, *obj, *next;
4431 assert(root->refcount == 0);
4434 * Pass over the DAG removing unreferenced objects from
4435 * appropriate lists.
4437 unlink_object(root);
4439 /* Unmap all objects that are no longer referenced. */
4440 for (obj = TAILQ_FIRST(&obj_list); obj != NULL; obj = next) {
4441 next = TAILQ_NEXT(obj, next);
4442 if (obj->marker || obj->refcount != 0)
4444 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase,
4445 obj->mapsize, 0, obj->path);
4446 dbg("unloading \"%s\"", obj->path);
4448 * Unlink the object now to prevent new references from
4449 * being acquired while the bind lock is dropped in
4450 * recursive dlclose() invocations.
4452 TAILQ_REMOVE(&obj_list, obj, next);
4455 if (obj->filtees_loaded) {
4457 init_marker(&marker);
4458 TAILQ_INSERT_BEFORE(next, &marker, next);
4459 unload_filtees(obj);
4460 next = TAILQ_NEXT(&marker, next);
4461 TAILQ_REMOVE(&obj_list, &marker, next);
4463 unload_filtees(obj);
4465 release_object(obj);
4470 unlink_object(Obj_Entry *root)
4474 if (root->refcount == 0) {
4475 /* Remove the object from the RTLD_GLOBAL list. */
4476 objlist_remove(&list_global, root);
4478 /* Remove the object from all objects' DAG lists. */
4479 STAILQ_FOREACH(elm, &root->dagmembers, link) {
4480 objlist_remove(&elm->obj->dldags, root);
4481 if (elm->obj != root)
4482 unlink_object(elm->obj);
4488 ref_dag(Obj_Entry *root)
4492 assert(root->dag_inited);
4493 STAILQ_FOREACH(elm, &root->dagmembers, link)
4494 elm->obj->refcount++;
4498 unref_dag(Obj_Entry *root)
4502 assert(root->dag_inited);
4503 STAILQ_FOREACH(elm, &root->dagmembers, link)
4504 elm->obj->refcount--;
4508 * Common code for MD __tls_get_addr().
4510 static void *tls_get_addr_slow(Elf_Addr **, int, size_t) __noinline;
4512 tls_get_addr_slow(Elf_Addr **dtvp, int index, size_t offset)
4514 Elf_Addr *newdtv, *dtv;
4515 RtldLockState lockstate;
4519 /* Check dtv generation in case new modules have arrived */
4520 if (dtv[0] != tls_dtv_generation) {
4521 wlock_acquire(rtld_bind_lock, &lockstate);
4522 newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4524 if (to_copy > tls_max_index)
4525 to_copy = tls_max_index;
4526 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
4527 newdtv[0] = tls_dtv_generation;
4528 newdtv[1] = tls_max_index;
4530 lock_release(rtld_bind_lock, &lockstate);
4531 dtv = *dtvp = newdtv;
4534 /* Dynamically allocate module TLS if necessary */
4535 if (dtv[index + 1] == 0) {
4536 /* Signal safe, wlock will block out signals. */
4537 wlock_acquire(rtld_bind_lock, &lockstate);
4538 if (!dtv[index + 1])
4539 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
4540 lock_release(rtld_bind_lock, &lockstate);
4542 return ((void *)(dtv[index + 1] + offset));
4546 tls_get_addr_common(Elf_Addr **dtvp, int index, size_t offset)
4551 /* Check dtv generation in case new modules have arrived */
4552 if (__predict_true(dtv[0] == tls_dtv_generation &&
4553 dtv[index + 1] != 0))
4554 return ((void *)(dtv[index + 1] + offset));
4555 return (tls_get_addr_slow(dtvp, index, offset));
4558 #if defined(__aarch64__) || defined(__arm__) || defined(__mips__) || \
4559 defined(__powerpc__) || defined(__riscv__)
4562 * Allocate Static TLS using the Variant I method.
4565 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
4574 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
4577 assert(tcbsize >= TLS_TCB_SIZE);
4578 tcb = xcalloc(1, tls_static_space - TLS_TCB_SIZE + tcbsize);
4579 tls = (Elf_Addr **)(tcb + tcbsize - TLS_TCB_SIZE);
4581 if (oldtcb != NULL) {
4582 memcpy(tls, oldtcb, tls_static_space);
4585 /* Adjust the DTV. */
4587 for (i = 0; i < dtv[1]; i++) {
4588 if (dtv[i+2] >= (Elf_Addr)oldtcb &&
4589 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
4590 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tls;
4594 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4596 dtv[0] = tls_dtv_generation;
4597 dtv[1] = tls_max_index;
4599 for (obj = globallist_curr(objs); obj != NULL;
4600 obj = globallist_next(obj)) {
4601 if (obj->tlsoffset > 0) {
4602 addr = (Elf_Addr)tls + obj->tlsoffset;
4603 if (obj->tlsinitsize > 0)
4604 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4605 if (obj->tlssize > obj->tlsinitsize)
4606 memset((void*) (addr + obj->tlsinitsize), 0,
4607 obj->tlssize - obj->tlsinitsize);
4608 dtv[obj->tlsindex + 1] = addr;
4617 free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
4620 Elf_Addr tlsstart, tlsend;
4623 assert(tcbsize >= TLS_TCB_SIZE);
4625 tlsstart = (Elf_Addr)tcb + tcbsize - TLS_TCB_SIZE;
4626 tlsend = tlsstart + tls_static_space;
4628 dtv = *(Elf_Addr **)tlsstart;
4630 for (i = 0; i < dtvsize; i++) {
4631 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
4632 free((void*)dtv[i+2]);
4641 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__)
4644 * Allocate Static TLS using the Variant II method.
4647 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
4650 size_t size, ralign;
4652 Elf_Addr *dtv, *olddtv;
4653 Elf_Addr segbase, oldsegbase, addr;
4657 if (tls_static_max_align > ralign)
4658 ralign = tls_static_max_align;
4659 size = round(tls_static_space, ralign) + round(tcbsize, ralign);
4661 assert(tcbsize >= 2*sizeof(Elf_Addr));
4662 tls = malloc_aligned(size, ralign);
4663 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4665 segbase = (Elf_Addr)(tls + round(tls_static_space, ralign));
4666 ((Elf_Addr*)segbase)[0] = segbase;
4667 ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
4669 dtv[0] = tls_dtv_generation;
4670 dtv[1] = tls_max_index;
4674 * Copy the static TLS block over whole.
4676 oldsegbase = (Elf_Addr) oldtls;
4677 memcpy((void *)(segbase - tls_static_space),
4678 (const void *)(oldsegbase - tls_static_space),
4682 * If any dynamic TLS blocks have been created tls_get_addr(),
4685 olddtv = ((Elf_Addr**)oldsegbase)[1];
4686 for (i = 0; i < olddtv[1]; i++) {
4687 if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
4688 dtv[i+2] = olddtv[i+2];
4694 * We assume that this block was the one we created with
4695 * allocate_initial_tls().
4697 free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
4699 for (obj = objs; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
4700 if (obj->marker || obj->tlsoffset == 0)
4702 addr = segbase - obj->tlsoffset;
4703 memset((void*) (addr + obj->tlsinitsize),
4704 0, obj->tlssize - obj->tlsinitsize);
4706 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4707 dtv[obj->tlsindex + 1] = addr;
4711 return (void*) segbase;
4715 free_tls(void *tls, size_t tcbsize, size_t tcbalign)
4718 size_t size, ralign;
4720 Elf_Addr tlsstart, tlsend;
4723 * Figure out the size of the initial TLS block so that we can
4724 * find stuff which ___tls_get_addr() allocated dynamically.
4727 if (tls_static_max_align > ralign)
4728 ralign = tls_static_max_align;
4729 size = round(tls_static_space, ralign);
4731 dtv = ((Elf_Addr**)tls)[1];
4733 tlsend = (Elf_Addr) tls;
4734 tlsstart = tlsend - size;
4735 for (i = 0; i < dtvsize; i++) {
4736 if (dtv[i + 2] != 0 && (dtv[i + 2] < tlsstart || dtv[i + 2] > tlsend)) {
4737 free_aligned((void *)dtv[i + 2]);
4741 free_aligned((void *)tlsstart);
4748 * Allocate TLS block for module with given index.
4751 allocate_module_tls(int index)
4756 TAILQ_FOREACH(obj, &obj_list, next) {
4759 if (obj->tlsindex == index)
4763 _rtld_error("Can't find module with TLS index %d", index);
4767 p = malloc_aligned(obj->tlssize, obj->tlsalign);
4768 memcpy(p, obj->tlsinit, obj->tlsinitsize);
4769 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
4775 allocate_tls_offset(Obj_Entry *obj)
4782 if (obj->tlssize == 0) {
4783 obj->tls_done = true;
4787 if (tls_last_offset == 0)
4788 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
4790 off = calculate_tls_offset(tls_last_offset, tls_last_size,
4791 obj->tlssize, obj->tlsalign);
4794 * If we have already fixed the size of the static TLS block, we
4795 * must stay within that size. When allocating the static TLS, we
4796 * leave a small amount of space spare to be used for dynamically
4797 * loading modules which use static TLS.
4799 if (tls_static_space != 0) {
4800 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
4802 } else if (obj->tlsalign > tls_static_max_align) {
4803 tls_static_max_align = obj->tlsalign;
4806 tls_last_offset = obj->tlsoffset = off;
4807 tls_last_size = obj->tlssize;
4808 obj->tls_done = true;
4814 free_tls_offset(Obj_Entry *obj)
4818 * If we were the last thing to allocate out of the static TLS
4819 * block, we give our space back to the 'allocator'. This is a
4820 * simplistic workaround to allow libGL.so.1 to be loaded and
4821 * unloaded multiple times.
4823 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
4824 == calculate_tls_end(tls_last_offset, tls_last_size)) {
4825 tls_last_offset -= obj->tlssize;
4831 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
4834 RtldLockState lockstate;
4836 wlock_acquire(rtld_bind_lock, &lockstate);
4837 ret = allocate_tls(globallist_curr(TAILQ_FIRST(&obj_list)), oldtls,
4839 lock_release(rtld_bind_lock, &lockstate);
4844 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
4846 RtldLockState lockstate;
4848 wlock_acquire(rtld_bind_lock, &lockstate);
4849 free_tls(tcb, tcbsize, tcbalign);
4850 lock_release(rtld_bind_lock, &lockstate);
4854 object_add_name(Obj_Entry *obj, const char *name)
4860 entry = malloc(sizeof(Name_Entry) + len);
4862 if (entry != NULL) {
4863 strcpy(entry->name, name);
4864 STAILQ_INSERT_TAIL(&obj->names, entry, link);
4869 object_match_name(const Obj_Entry *obj, const char *name)
4873 STAILQ_FOREACH(entry, &obj->names, link) {
4874 if (strcmp(name, entry->name) == 0)
4881 locate_dependency(const Obj_Entry *obj, const char *name)
4883 const Objlist_Entry *entry;
4884 const Needed_Entry *needed;
4886 STAILQ_FOREACH(entry, &list_main, link) {
4887 if (object_match_name(entry->obj, name))
4891 for (needed = obj->needed; needed != NULL; needed = needed->next) {
4892 if (strcmp(obj->strtab + needed->name, name) == 0 ||
4893 (needed->obj != NULL && object_match_name(needed->obj, name))) {
4895 * If there is DT_NEEDED for the name we are looking for,
4896 * we are all set. Note that object might not be found if
4897 * dependency was not loaded yet, so the function can
4898 * return NULL here. This is expected and handled
4899 * properly by the caller.
4901 return (needed->obj);
4904 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
4910 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
4911 const Elf_Vernaux *vna)
4913 const Elf_Verdef *vd;
4914 const char *vername;
4916 vername = refobj->strtab + vna->vna_name;
4917 vd = depobj->verdef;
4919 _rtld_error("%s: version %s required by %s not defined",
4920 depobj->path, vername, refobj->path);
4924 if (vd->vd_version != VER_DEF_CURRENT) {
4925 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
4926 depobj->path, vd->vd_version);
4929 if (vna->vna_hash == vd->vd_hash) {
4930 const Elf_Verdaux *aux = (const Elf_Verdaux *)
4931 ((char *)vd + vd->vd_aux);
4932 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
4935 if (vd->vd_next == 0)
4937 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4939 if (vna->vna_flags & VER_FLG_WEAK)
4941 _rtld_error("%s: version %s required by %s not found",
4942 depobj->path, vername, refobj->path);
4947 rtld_verify_object_versions(Obj_Entry *obj)
4949 const Elf_Verneed *vn;
4950 const Elf_Verdef *vd;
4951 const Elf_Verdaux *vda;
4952 const Elf_Vernaux *vna;
4953 const Obj_Entry *depobj;
4954 int maxvernum, vernum;
4956 if (obj->ver_checked)
4958 obj->ver_checked = true;
4962 * Walk over defined and required version records and figure out
4963 * max index used by any of them. Do very basic sanity checking
4967 while (vn != NULL) {
4968 if (vn->vn_version != VER_NEED_CURRENT) {
4969 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
4970 obj->path, vn->vn_version);
4973 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4975 vernum = VER_NEED_IDX(vna->vna_other);
4976 if (vernum > maxvernum)
4978 if (vna->vna_next == 0)
4980 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4982 if (vn->vn_next == 0)
4984 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4988 while (vd != NULL) {
4989 if (vd->vd_version != VER_DEF_CURRENT) {
4990 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
4991 obj->path, vd->vd_version);
4994 vernum = VER_DEF_IDX(vd->vd_ndx);
4995 if (vernum > maxvernum)
4997 if (vd->vd_next == 0)
4999 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
5006 * Store version information in array indexable by version index.
5007 * Verify that object version requirements are satisfied along the
5010 obj->vernum = maxvernum + 1;
5011 obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry));
5014 while (vd != NULL) {
5015 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
5016 vernum = VER_DEF_IDX(vd->vd_ndx);
5017 assert(vernum <= maxvernum);
5018 vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
5019 obj->vertab[vernum].hash = vd->vd_hash;
5020 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
5021 obj->vertab[vernum].file = NULL;
5022 obj->vertab[vernum].flags = 0;
5024 if (vd->vd_next == 0)
5026 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
5030 while (vn != NULL) {
5031 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
5034 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
5036 if (check_object_provided_version(obj, depobj, vna))
5038 vernum = VER_NEED_IDX(vna->vna_other);
5039 assert(vernum <= maxvernum);
5040 obj->vertab[vernum].hash = vna->vna_hash;
5041 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
5042 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
5043 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
5044 VER_INFO_HIDDEN : 0;
5045 if (vna->vna_next == 0)
5047 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
5049 if (vn->vn_next == 0)
5051 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
5057 rtld_verify_versions(const Objlist *objlist)
5059 Objlist_Entry *entry;
5063 STAILQ_FOREACH(entry, objlist, link) {
5065 * Skip dummy objects or objects that have their version requirements
5068 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
5070 if (rtld_verify_object_versions(entry->obj) == -1) {
5072 if (ld_tracing == NULL)
5076 if (rc == 0 || ld_tracing != NULL)
5077 rc = rtld_verify_object_versions(&obj_rtld);
5082 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
5087 vernum = VER_NDX(obj->versyms[symnum]);
5088 if (vernum >= obj->vernum) {
5089 _rtld_error("%s: symbol %s has wrong verneed value %d",
5090 obj->path, obj->strtab + symnum, vernum);
5091 } else if (obj->vertab[vernum].hash != 0) {
5092 return &obj->vertab[vernum];
5099 _rtld_get_stack_prot(void)
5102 return (stack_prot);
5106 _rtld_is_dlopened(void *arg)
5109 RtldLockState lockstate;
5112 rlock_acquire(rtld_bind_lock, &lockstate);
5115 obj = obj_from_addr(arg);
5117 _rtld_error("No shared object contains address");
5118 lock_release(rtld_bind_lock, &lockstate);
5121 res = obj->dlopened ? 1 : 0;
5122 lock_release(rtld_bind_lock, &lockstate);
5127 obj_enforce_relro(Obj_Entry *obj)
5130 if (obj->relro_size > 0 && mprotect(obj->relro_page, obj->relro_size,
5132 _rtld_error("%s: Cannot enforce relro protection: %s",
5133 obj->path, rtld_strerror(errno));
5140 map_stacks_exec(RtldLockState *lockstate)
5142 void (*thr_map_stacks_exec)(void);
5144 if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
5146 thr_map_stacks_exec = (void (*)(void))(uintptr_t)
5147 get_program_var_addr("__pthread_map_stacks_exec", lockstate);
5148 if (thr_map_stacks_exec != NULL) {
5149 stack_prot |= PROT_EXEC;
5150 thr_map_stacks_exec();
5155 symlook_init(SymLook *dst, const char *name)
5158 bzero(dst, sizeof(*dst));
5160 dst->hash = elf_hash(name);
5161 dst->hash_gnu = gnu_hash(name);
5165 symlook_init_from_req(SymLook *dst, const SymLook *src)
5168 dst->name = src->name;
5169 dst->hash = src->hash;
5170 dst->hash_gnu = src->hash_gnu;
5171 dst->ventry = src->ventry;
5172 dst->flags = src->flags;
5173 dst->defobj_out = NULL;
5174 dst->sym_out = NULL;
5175 dst->lockstate = src->lockstate;
5180 * Parse a file descriptor number without pulling in more of libc (e.g. atoi).
5183 parse_libdir(const char *str)
5185 static const int RADIX = 10; /* XXXJA: possibly support hex? */
5192 for (c = *str; c != '\0'; c = *++str) {
5193 if (c < '0' || c > '9')
5200 /* Make sure we actually parsed something. */
5202 _rtld_error("failed to parse directory FD from '%s'", str);
5209 * Overrides for libc_pic-provided functions.
5213 __getosreldate(void)
5223 oid[1] = KERN_OSRELDATE;
5225 len = sizeof(osrel);
5226 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
5227 if (error == 0 && osrel > 0 && len == sizeof(osrel))
5239 void (*__cleanup)(void);
5240 int __isthreaded = 0;
5241 int _thread_autoinit_dummy_decl = 1;
5244 * No unresolved symbols for rtld.
5247 __pthread_cxa_finalize(struct dl_phdr_info *a)
5252 __stack_chk_fail(void)
5255 _rtld_error("stack overflow detected; terminated");
5258 __weak_reference(__stack_chk_fail, __stack_chk_fail_local);
5264 _rtld_error("buffer overflow detected; terminated");
5269 rtld_strerror(int errnum)
5272 if (errnum < 0 || errnum >= sys_nerr)
5273 return ("Unknown error");
5274 return (sys_errlist[errnum]);