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 int dlclose_locked(void *, RtldLockState *);
81 static Obj_Entry *dlopen_object(const char *name, int fd, Obj_Entry *refobj,
82 int lo_flags, int mode, RtldLockState *lockstate);
83 static Obj_Entry *do_load_object(int, const char *, char *, struct stat *, int);
84 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
85 static bool donelist_check(DoneList *, const Obj_Entry *);
86 static void errmsg_restore(char *);
87 static char *errmsg_save(void);
88 static void *fill_search_info(const char *, size_t, void *);
89 static char *find_library(const char *, const Obj_Entry *, int *);
90 static const char *gethints(bool);
91 static void hold_object(Obj_Entry *);
92 static void unhold_object(Obj_Entry *);
93 static void init_dag(Obj_Entry *);
94 static void init_marker(Obj_Entry *);
95 static void init_pagesizes(Elf_Auxinfo **aux_info);
96 static void init_rtld(caddr_t, Elf_Auxinfo **);
97 static void initlist_add_neededs(Needed_Entry *, Objlist *);
98 static void initlist_add_objects(Obj_Entry *, Obj_Entry *, Objlist *);
99 static void linkmap_add(Obj_Entry *);
100 static void linkmap_delete(Obj_Entry *);
101 static void load_filtees(Obj_Entry *, int flags, RtldLockState *);
102 static void unload_filtees(Obj_Entry *, RtldLockState *);
103 static int load_needed_objects(Obj_Entry *, int);
104 static int load_preload_objects(void);
105 static Obj_Entry *load_object(const char *, int fd, const Obj_Entry *, int);
106 static void map_stacks_exec(RtldLockState *);
107 static int obj_enforce_relro(Obj_Entry *);
108 static Obj_Entry *obj_from_addr(const void *);
109 static void objlist_call_fini(Objlist *, Obj_Entry *, RtldLockState *);
110 static void objlist_call_init(Objlist *, RtldLockState *);
111 static void objlist_clear(Objlist *);
112 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
113 static void objlist_init(Objlist *);
114 static void objlist_push_head(Objlist *, Obj_Entry *);
115 static void objlist_push_tail(Objlist *, Obj_Entry *);
116 static void objlist_put_after(Objlist *, Obj_Entry *, Obj_Entry *);
117 static void objlist_remove(Objlist *, Obj_Entry *);
118 static int parse_libdir(const char *);
119 static void *path_enumerate(const char *, path_enum_proc, void *);
120 static void release_object(Obj_Entry *);
121 static int relocate_object_dag(Obj_Entry *root, bool bind_now,
122 Obj_Entry *rtldobj, int flags, RtldLockState *lockstate);
123 static int relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
124 int flags, RtldLockState *lockstate);
125 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, int,
127 static int resolve_objects_ifunc(Obj_Entry *first, bool bind_now,
128 int flags, RtldLockState *lockstate);
129 static int rtld_dirname(const char *, char *);
130 static int rtld_dirname_abs(const char *, char *);
131 static void *rtld_dlopen(const char *name, int fd, int mode);
132 static void rtld_exit(void);
133 static char *search_library_path(const char *, const char *);
134 static char *search_library_pathfds(const char *, const char *, int *);
135 static const void **get_program_var_addr(const char *, RtldLockState *);
136 static void set_program_var(const char *, const void *);
137 static int symlook_default(SymLook *, const Obj_Entry *refobj);
138 static int symlook_global(SymLook *, DoneList *);
139 static void symlook_init_from_req(SymLook *, const SymLook *);
140 static int symlook_list(SymLook *, const Objlist *, DoneList *);
141 static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *);
142 static int symlook_obj1_sysv(SymLook *, const Obj_Entry *);
143 static int symlook_obj1_gnu(SymLook *, const Obj_Entry *);
144 static void trace_loaded_objects(Obj_Entry *);
145 static void unlink_object(Obj_Entry *);
146 static void unload_object(Obj_Entry *, RtldLockState *lockstate);
147 static void unref_dag(Obj_Entry *);
148 static void ref_dag(Obj_Entry *);
149 static char *origin_subst_one(Obj_Entry *, char *, const char *,
151 static char *origin_subst(Obj_Entry *, char *);
152 static bool obj_resolve_origin(Obj_Entry *obj);
153 static void preinit_main(void);
154 static int rtld_verify_versions(const Objlist *);
155 static int rtld_verify_object_versions(Obj_Entry *);
156 static void object_add_name(Obj_Entry *, const char *);
157 static int object_match_name(const Obj_Entry *, const char *);
158 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
159 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
160 struct dl_phdr_info *phdr_info);
161 static uint32_t gnu_hash(const char *);
162 static bool matched_symbol(SymLook *, const Obj_Entry *, Sym_Match_Result *,
163 const unsigned long);
165 void r_debug_state(struct r_debug *, struct link_map *) __noinline __exported;
166 void _r_debug_postinit(struct link_map *) __noinline __exported;
168 int __sys_openat(int, const char *, int, ...);
173 static char *error_message; /* Message for dlerror(), or NULL */
174 struct r_debug r_debug __exported; /* for GDB; */
175 static bool libmap_disable; /* Disable libmap */
176 static bool ld_loadfltr; /* Immediate filters processing */
177 static char *libmap_override; /* Maps to use in addition to libmap.conf */
178 static bool trust; /* False for setuid and setgid programs */
179 static bool dangerous_ld_env; /* True if environment variables have been
180 used to affect the libraries loaded */
181 bool ld_bind_not; /* Disable PLT update */
182 static char *ld_bind_now; /* Environment variable for immediate binding */
183 static char *ld_debug; /* Environment variable for debugging */
184 static char *ld_library_path; /* Environment variable for search path */
185 static char *ld_library_dirs; /* Environment variable for library descriptors */
186 static char *ld_preload; /* Environment variable for libraries to
188 static char *ld_elf_hints_path; /* Environment variable for alternative hints path */
189 static char *ld_tracing; /* Called from ldd to print libs */
190 static char *ld_utrace; /* Use utrace() to log events. */
191 static struct obj_entry_q obj_list; /* Queue of all loaded objects */
192 static Obj_Entry *obj_main; /* The main program shared object */
193 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
194 static unsigned int obj_count; /* Number of objects in obj_list */
195 static unsigned int obj_loads; /* Number of loads of objects (gen count) */
197 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
198 STAILQ_HEAD_INITIALIZER(list_global);
199 static Objlist list_main = /* Objects loaded at program startup */
200 STAILQ_HEAD_INITIALIZER(list_main);
201 static Objlist list_fini = /* Objects needing fini() calls */
202 STAILQ_HEAD_INITIALIZER(list_fini);
204 Elf_Sym sym_zero; /* For resolving undefined weak refs. */
206 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
208 extern Elf_Dyn _DYNAMIC;
209 #pragma weak _DYNAMIC
211 int dlclose(void *) __exported;
212 char *dlerror(void) __exported;
213 void *dlopen(const char *, int) __exported;
214 void *fdlopen(int, int) __exported;
215 void *dlsym(void *, const char *) __exported;
216 dlfunc_t dlfunc(void *, const char *) __exported;
217 void *dlvsym(void *, const char *, const char *) __exported;
218 int dladdr(const void *, Dl_info *) __exported;
219 void dllockinit(void *, void *(*)(void *), void (*)(void *), void (*)(void *),
220 void (*)(void *), void (*)(void *), void (*)(void *)) __exported;
221 int dlinfo(void *, int , void *) __exported;
222 int dl_iterate_phdr(__dl_iterate_hdr_callback, void *) __exported;
223 int _rtld_addr_phdr(const void *, struct dl_phdr_info *) __exported;
224 int _rtld_get_stack_prot(void) __exported;
225 int _rtld_is_dlopened(void *) __exported;
226 void _rtld_error(const char *, ...) __exported;
228 int npagesizes, osreldate;
231 long __stack_chk_guard[8] = {0, 0, 0, 0, 0, 0, 0, 0};
233 static int stack_prot = PROT_READ | PROT_WRITE | RTLD_DEFAULT_STACK_EXEC;
234 static int max_stack_flags;
237 * Global declarations normally provided by crt1. The dynamic linker is
238 * not built with crt1, so we have to provide them ourselves.
244 * Used to pass argc, argv to init functions.
250 * Globals to control TLS allocation.
252 size_t tls_last_offset; /* Static TLS offset of last module */
253 size_t tls_last_size; /* Static TLS size of last module */
254 size_t tls_static_space; /* Static TLS space allocated */
255 size_t tls_static_max_align;
256 int tls_dtv_generation = 1; /* Used to detect when dtv size changes */
257 int tls_max_index = 1; /* Largest module index allocated */
259 bool ld_library_path_rpath = false;
262 * Globals for path names, and such
264 char *ld_elf_hints_default = _PATH_ELF_HINTS;
265 char *ld_path_libmap_conf = _PATH_LIBMAP_CONF;
266 char *ld_path_rtld = _PATH_RTLD;
267 char *ld_standard_library_path = STANDARD_LIBRARY_PATH;
268 char *ld_env_prefix = LD_;
271 * Fill in a DoneList with an allocation large enough to hold all of
272 * the currently-loaded objects. Keep this as a macro since it calls
273 * alloca and we want that to occur within the scope of the caller.
275 #define donelist_init(dlp) \
276 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
277 assert((dlp)->objs != NULL), \
278 (dlp)->num_alloc = obj_count, \
281 #define LD_UTRACE(e, h, mb, ms, r, n) do { \
282 if (ld_utrace != NULL) \
283 ld_utrace_log(e, h, mb, ms, r, n); \
287 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
288 int refcnt, const char *name)
290 struct utrace_rtld ut;
291 static const char rtld_utrace_sig[RTLD_UTRACE_SIG_SZ] = RTLD_UTRACE_SIG;
293 memcpy(ut.sig, rtld_utrace_sig, sizeof(ut.sig));
296 ut.mapbase = mapbase;
297 ut.mapsize = mapsize;
299 bzero(ut.name, sizeof(ut.name));
301 strlcpy(ut.name, name, sizeof(ut.name));
302 utrace(&ut, sizeof(ut));
305 #ifdef RTLD_VARIANT_ENV_NAMES
307 * construct the env variable based on the type of binary that's
310 static inline const char *
313 static char buffer[128];
315 strlcpy(buffer, ld_env_prefix, sizeof(buffer));
316 strlcat(buffer, var, sizeof(buffer));
324 * Main entry point for dynamic linking. The first argument is the
325 * stack pointer. The stack is expected to be laid out as described
326 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
327 * Specifically, the stack pointer points to a word containing
328 * ARGC. Following that in the stack is a null-terminated sequence
329 * of pointers to argument strings. Then comes a null-terminated
330 * sequence of pointers to environment strings. Finally, there is a
331 * sequence of "auxiliary vector" entries.
333 * The second argument points to a place to store the dynamic linker's
334 * exit procedure pointer and the third to a place to store the main
337 * The return value is the main program's entry point.
340 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
342 Elf_Auxinfo *aux, *auxp, *aux_info[AT_COUNT];
343 Objlist_Entry *entry;
344 Obj_Entry *last_interposer, *obj, *preload_tail;
345 const Elf_Phdr *phdr;
347 RtldLockState lockstate;
348 char **argv, *argv0, **env, *kexecpath, *library_path_rpath;
350 char buf[MAXPATHLEN];
351 int argc, fd, i, mib[2], phnum;
355 * On entry, the dynamic linker itself has not been relocated yet.
356 * Be very careful not to reference any global data until after
357 * init_rtld has returned. It is OK to reference file-scope statics
358 * and string constants, and to call static and global functions.
361 /* Find the auxiliary vector on the stack. */
364 sp += argc + 1; /* Skip over arguments and NULL terminator */
366 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
368 aux = (Elf_Auxinfo *) sp;
370 /* Digest the auxiliary vector. */
371 for (i = 0; i < AT_COUNT; i++)
373 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
374 if (auxp->a_type < AT_COUNT)
375 aux_info[auxp->a_type] = auxp;
378 /* Initialize and relocate ourselves. */
379 assert(aux_info[AT_BASE] != NULL);
380 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
382 __progname = obj_rtld.path;
383 argv0 = argv[0] != NULL ? argv[0] : "(null)";
388 if (aux_info[AT_CANARY] != NULL &&
389 aux_info[AT_CANARY]->a_un.a_ptr != NULL) {
390 i = aux_info[AT_CANARYLEN]->a_un.a_val;
391 if (i > sizeof(__stack_chk_guard))
392 i = sizeof(__stack_chk_guard);
393 memcpy(__stack_chk_guard, aux_info[AT_CANARY]->a_un.a_ptr, i);
398 len = sizeof(__stack_chk_guard);
399 if (sysctl(mib, 2, __stack_chk_guard, &len, NULL, 0) == -1 ||
400 len != sizeof(__stack_chk_guard)) {
401 /* If sysctl was unsuccessful, use the "terminator canary". */
402 ((unsigned char *)(void *)__stack_chk_guard)[0] = 0;
403 ((unsigned char *)(void *)__stack_chk_guard)[1] = 0;
404 ((unsigned char *)(void *)__stack_chk_guard)[2] = '\n';
405 ((unsigned char *)(void *)__stack_chk_guard)[3] = 255;
409 trust = !issetugid();
411 md_abi_variant_hook(aux_info);
413 ld_bind_now = getenv(_LD("BIND_NOW"));
416 * If the process is tainted, then we un-set the dangerous environment
417 * variables. The process will be marked as tainted until setuid(2)
418 * is called. If any child process calls setuid(2) we do not want any
419 * future processes to honor the potentially un-safe variables.
422 if (unsetenv(_LD("PRELOAD")) || unsetenv(_LD("LIBMAP")) ||
423 unsetenv(_LD("LIBRARY_PATH")) || unsetenv(_LD("LIBRARY_PATH_FDS")) ||
424 unsetenv(_LD("LIBMAP_DISABLE")) || unsetenv(_LD("BIND_NOT")) ||
425 unsetenv(_LD("DEBUG")) || unsetenv(_LD("ELF_HINTS_PATH")) ||
426 unsetenv(_LD("LOADFLTR")) || unsetenv(_LD("LIBRARY_PATH_RPATH"))) {
427 _rtld_error("environment corrupt; aborting");
431 ld_debug = getenv(_LD("DEBUG"));
432 if (ld_bind_now == NULL)
433 ld_bind_not = getenv(_LD("BIND_NOT")) != NULL;
434 libmap_disable = getenv(_LD("LIBMAP_DISABLE")) != NULL;
435 libmap_override = getenv(_LD("LIBMAP"));
436 ld_library_path = getenv(_LD("LIBRARY_PATH"));
437 ld_library_dirs = getenv(_LD("LIBRARY_PATH_FDS"));
438 ld_preload = getenv(_LD("PRELOAD"));
439 ld_elf_hints_path = getenv(_LD("ELF_HINTS_PATH"));
440 ld_loadfltr = getenv(_LD("LOADFLTR")) != NULL;
441 library_path_rpath = getenv(_LD("LIBRARY_PATH_RPATH"));
442 if (library_path_rpath != NULL) {
443 if (library_path_rpath[0] == 'y' ||
444 library_path_rpath[0] == 'Y' ||
445 library_path_rpath[0] == '1')
446 ld_library_path_rpath = true;
448 ld_library_path_rpath = false;
450 dangerous_ld_env = libmap_disable || (libmap_override != NULL) ||
451 (ld_library_path != NULL) || (ld_preload != NULL) ||
452 (ld_elf_hints_path != NULL) || ld_loadfltr;
453 ld_tracing = getenv(_LD("TRACE_LOADED_OBJECTS"));
454 ld_utrace = getenv(_LD("UTRACE"));
456 if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0)
457 ld_elf_hints_path = ld_elf_hints_default;
459 if (ld_debug != NULL && *ld_debug != '\0')
461 dbg("%s is initialized, base address = %p", __progname,
462 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
463 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
464 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
466 dbg("initializing thread locks");
470 * Load the main program, or process its program header if it is
473 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
474 fd = aux_info[AT_EXECFD]->a_un.a_val;
475 dbg("loading main program");
476 obj_main = map_object(fd, argv0, NULL);
478 if (obj_main == NULL)
480 max_stack_flags = obj->stack_flags;
481 } else { /* Main program already loaded. */
482 dbg("processing main program's program header");
483 assert(aux_info[AT_PHDR] != NULL);
484 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
485 assert(aux_info[AT_PHNUM] != NULL);
486 phnum = aux_info[AT_PHNUM]->a_un.a_val;
487 assert(aux_info[AT_PHENT] != NULL);
488 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
489 assert(aux_info[AT_ENTRY] != NULL);
490 imgentry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
491 if ((obj_main = digest_phdr(phdr, phnum, imgentry, argv0)) == NULL)
495 if (aux_info[AT_EXECPATH] != NULL) {
496 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
497 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
498 if (kexecpath[0] == '/')
499 obj_main->path = kexecpath;
500 else if (getcwd(buf, sizeof(buf)) == NULL ||
501 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
502 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
503 obj_main->path = xstrdup(argv0);
505 obj_main->path = xstrdup(buf);
507 dbg("No AT_EXECPATH");
508 obj_main->path = xstrdup(argv0);
510 dbg("obj_main path %s", obj_main->path);
511 obj_main->mainprog = true;
513 if (aux_info[AT_STACKPROT] != NULL &&
514 aux_info[AT_STACKPROT]->a_un.a_val != 0)
515 stack_prot = aux_info[AT_STACKPROT]->a_un.a_val;
519 * Get the actual dynamic linker pathname from the executable if
520 * possible. (It should always be possible.) That ensures that
521 * gdb will find the right dynamic linker even if a non-standard
524 if (obj_main->interp != NULL &&
525 strcmp(obj_main->interp, obj_rtld.path) != 0) {
527 obj_rtld.path = xstrdup(obj_main->interp);
528 __progname = obj_rtld.path;
532 digest_dynamic(obj_main, 0);
533 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d",
534 obj_main->path, obj_main->valid_hash_sysv, obj_main->valid_hash_gnu,
535 obj_main->dynsymcount);
537 linkmap_add(obj_main);
538 linkmap_add(&obj_rtld);
540 /* Link the main program into the list of objects. */
541 TAILQ_INSERT_HEAD(&obj_list, obj_main, next);
545 /* Initialize a fake symbol for resolving undefined weak references. */
546 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
547 sym_zero.st_shndx = SHN_UNDEF;
548 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
551 libmap_disable = (bool)lm_init(libmap_override);
553 dbg("loading LD_PRELOAD libraries");
554 if (load_preload_objects() == -1)
556 preload_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
558 dbg("loading needed objects");
559 if (load_needed_objects(obj_main, 0) == -1)
562 /* Make a list of all objects loaded at startup. */
563 last_interposer = obj_main;
564 TAILQ_FOREACH(obj, &obj_list, next) {
567 if (obj->z_interpose && obj != obj_main) {
568 objlist_put_after(&list_main, last_interposer, obj);
569 last_interposer = obj;
571 objlist_push_tail(&list_main, obj);
576 dbg("checking for required versions");
577 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
580 if (ld_tracing) { /* We're done */
581 trace_loaded_objects(obj_main);
585 if (getenv(_LD("DUMP_REL_PRE")) != NULL) {
586 dump_relocations(obj_main);
591 * Processing tls relocations requires having the tls offsets
592 * initialized. Prepare offsets before starting initial
593 * relocation processing.
595 dbg("initializing initial thread local storage offsets");
596 STAILQ_FOREACH(entry, &list_main, link) {
598 * Allocate all the initial objects out of the static TLS
599 * block even if they didn't ask for it.
601 allocate_tls_offset(entry->obj);
604 if (relocate_objects(obj_main,
605 ld_bind_now != NULL && *ld_bind_now != '\0',
606 &obj_rtld, SYMLOOK_EARLY, NULL) == -1)
609 dbg("doing copy relocations");
610 if (do_copy_relocations(obj_main) == -1)
613 dbg("enforcing main obj relro");
614 if (obj_enforce_relro(obj_main) == -1)
617 if (getenv(_LD("DUMP_REL_POST")) != NULL) {
618 dump_relocations(obj_main);
623 * Setup TLS for main thread. This must be done after the
624 * relocations are processed, since tls initialization section
625 * might be the subject for relocations.
627 dbg("initializing initial thread local storage");
628 allocate_initial_tls(globallist_curr(TAILQ_FIRST(&obj_list)));
630 dbg("initializing key program variables");
631 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
632 set_program_var("environ", env);
633 set_program_var("__elf_aux_vector", aux);
635 /* Make a list of init functions to call. */
636 objlist_init(&initlist);
637 initlist_add_objects(globallist_curr(TAILQ_FIRST(&obj_list)),
638 preload_tail, &initlist);
640 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
642 map_stacks_exec(NULL);
645 dbg("resolving ifuncs");
646 if (resolve_objects_ifunc(obj_main,
647 ld_bind_now != NULL && *ld_bind_now != '\0', SYMLOOK_EARLY,
651 if (!obj_main->crt_no_init) {
653 * Make sure we don't call the main program's init and fini
654 * functions for binaries linked with old crt1 which calls
657 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
658 obj_main->preinit_array = obj_main->init_array =
659 obj_main->fini_array = (Elf_Addr)NULL;
662 wlock_acquire(rtld_bind_lock, &lockstate);
663 if (obj_main->crt_no_init)
665 objlist_call_init(&initlist, &lockstate);
666 _r_debug_postinit(&obj_main->linkmap);
667 objlist_clear(&initlist);
668 dbg("loading filtees");
669 TAILQ_FOREACH(obj, &obj_list, next) {
672 if (ld_loadfltr || obj->z_loadfltr)
673 load_filtees(obj, 0, &lockstate);
675 lock_release(rtld_bind_lock, &lockstate);
677 dbg("transferring control to program entry point = %p", obj_main->entry);
679 /* Return the exit procedure and the program entry point. */
680 *exit_proc = rtld_exit;
682 return (func_ptr_type) obj_main->entry;
686 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def)
691 ptr = (void *)make_function_pointer(def, obj);
692 target = call_ifunc_resolver(ptr);
693 return ((void *)target);
697 * NB: MIPS uses a private version of this function (_mips_rtld_bind).
698 * Changes to this function should be applied there as well.
701 _rtld_bind(Obj_Entry *obj, Elf_Size reloff)
705 const Obj_Entry *defobj;
708 RtldLockState lockstate;
710 rlock_acquire(rtld_bind_lock, &lockstate);
711 if (sigsetjmp(lockstate.env, 0) != 0)
712 lock_upgrade(rtld_bind_lock, &lockstate);
714 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
716 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
718 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
719 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, SYMLOOK_IN_PLT,
723 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
724 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
726 target = (Elf_Addr)(defobj->relocbase + def->st_value);
728 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
729 defobj->strtab + def->st_name, basename(obj->path),
730 (void *)target, basename(defobj->path));
733 * Write the new contents for the jmpslot. Note that depending on
734 * architecture, the value which we need to return back to the
735 * lazy binding trampoline may or may not be the target
736 * address. The value returned from reloc_jmpslot() is the value
737 * that the trampoline needs.
739 target = reloc_jmpslot(where, target, defobj, obj, rel);
740 lock_release(rtld_bind_lock, &lockstate);
745 * Error reporting function. Use it like printf. If formats the message
746 * into a buffer, and sets things up so that the next call to dlerror()
747 * will return the message.
750 _rtld_error(const char *fmt, ...)
752 static char buf[512];
756 rtld_vsnprintf(buf, sizeof buf, fmt, ap);
762 * Return a dynamically-allocated copy of the current error message, if any.
767 return error_message == NULL ? NULL : xstrdup(error_message);
771 * Restore the current error message from a copy which was previously saved
772 * by errmsg_save(). The copy is freed.
775 errmsg_restore(char *saved_msg)
777 if (saved_msg == NULL)
778 error_message = NULL;
780 _rtld_error("%s", saved_msg);
786 basename(const char *name)
788 const char *p = strrchr(name, '/');
789 return p != NULL ? p + 1 : name;
792 static struct utsname uts;
795 origin_subst_one(Obj_Entry *obj, char *real, const char *kw,
796 const char *subst, bool may_free)
798 char *p, *p1, *res, *resp;
799 int subst_len, kw_len, subst_count, old_len, new_len;
804 * First, count the number of the keyword occurrences, to
805 * preallocate the final string.
807 for (p = real, subst_count = 0;; p = p1 + kw_len, subst_count++) {
814 * If the keyword is not found, just return.
816 * Return non-substituted string if resolution failed. We
817 * cannot do anything more reasonable, the failure mode of the
818 * caller is unresolved library anyway.
820 if (subst_count == 0 || (obj != NULL && !obj_resolve_origin(obj)))
821 return (may_free ? real : xstrdup(real));
823 subst = obj->origin_path;
826 * There is indeed something to substitute. Calculate the
827 * length of the resulting string, and allocate it.
829 subst_len = strlen(subst);
830 old_len = strlen(real);
831 new_len = old_len + (subst_len - kw_len) * subst_count;
832 res = xmalloc(new_len + 1);
835 * Now, execute the substitution loop.
837 for (p = real, resp = res, *resp = '\0';;) {
840 /* Copy the prefix before keyword. */
841 memcpy(resp, p, p1 - p);
843 /* Keyword replacement. */
844 memcpy(resp, subst, subst_len);
852 /* Copy to the end of string and finish. */
860 origin_subst(Obj_Entry *obj, char *real)
862 char *res1, *res2, *res3, *res4;
864 if (obj == NULL || !trust)
865 return (xstrdup(real));
866 if (uts.sysname[0] == '\0') {
867 if (uname(&uts) != 0) {
868 _rtld_error("utsname failed: %d", errno);
872 res1 = origin_subst_one(obj, real, "$ORIGIN", NULL, false);
873 res2 = origin_subst_one(NULL, res1, "$OSNAME", uts.sysname, true);
874 res3 = origin_subst_one(NULL, res2, "$OSREL", uts.release, true);
875 res4 = origin_subst_one(NULL, res3, "$PLATFORM", uts.machine, true);
882 const char *msg = dlerror();
886 rtld_fdputstr(STDERR_FILENO, msg);
887 rtld_fdputchar(STDERR_FILENO, '\n');
892 * Process a shared object's DYNAMIC section, and save the important
893 * information in its Obj_Entry structure.
896 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
897 const Elf_Dyn **dyn_soname, const Elf_Dyn **dyn_runpath)
900 Needed_Entry **needed_tail = &obj->needed;
901 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
902 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
903 const Elf_Hashelt *hashtab;
904 const Elf32_Word *hashval;
905 Elf32_Word bkt, nmaskwords;
907 int plttype = DT_REL;
913 obj->bind_now = false;
914 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
915 switch (dynp->d_tag) {
918 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
922 obj->relsize = dynp->d_un.d_val;
926 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
930 obj->pltrel = (const Elf_Rel *)
931 (obj->relocbase + dynp->d_un.d_ptr);
935 obj->pltrelsize = dynp->d_un.d_val;
939 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
943 obj->relasize = dynp->d_un.d_val;
947 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
951 plttype = dynp->d_un.d_val;
952 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
956 obj->symtab = (const Elf_Sym *)
957 (obj->relocbase + dynp->d_un.d_ptr);
961 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
965 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
969 obj->strsize = dynp->d_un.d_val;
973 obj->verneed = (const Elf_Verneed *) (obj->relocbase +
978 obj->verneednum = dynp->d_un.d_val;
982 obj->verdef = (const Elf_Verdef *) (obj->relocbase +
987 obj->verdefnum = dynp->d_un.d_val;
991 obj->versyms = (const Elf_Versym *)(obj->relocbase +
997 hashtab = (const Elf_Hashelt *)(obj->relocbase +
999 obj->nbuckets = hashtab[0];
1000 obj->nchains = hashtab[1];
1001 obj->buckets = hashtab + 2;
1002 obj->chains = obj->buckets + obj->nbuckets;
1003 obj->valid_hash_sysv = obj->nbuckets > 0 && obj->nchains > 0 &&
1004 obj->buckets != NULL;
1010 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1012 obj->nbuckets_gnu = hashtab[0];
1013 obj->symndx_gnu = hashtab[1];
1014 nmaskwords = hashtab[2];
1015 bloom_size32 = (__ELF_WORD_SIZE / 32) * nmaskwords;
1016 obj->maskwords_bm_gnu = nmaskwords - 1;
1017 obj->shift2_gnu = hashtab[3];
1018 obj->bloom_gnu = (Elf_Addr *) (hashtab + 4);
1019 obj->buckets_gnu = hashtab + 4 + bloom_size32;
1020 obj->chain_zero_gnu = obj->buckets_gnu + obj->nbuckets_gnu -
1022 /* Number of bitmask words is required to be power of 2 */
1023 obj->valid_hash_gnu = powerof2(nmaskwords) &&
1024 obj->nbuckets_gnu > 0 && obj->buckets_gnu != NULL;
1030 Needed_Entry *nep = NEW(Needed_Entry);
1031 nep->name = dynp->d_un.d_val;
1036 needed_tail = &nep->next;
1042 Needed_Entry *nep = NEW(Needed_Entry);
1043 nep->name = dynp->d_un.d_val;
1047 *needed_filtees_tail = nep;
1048 needed_filtees_tail = &nep->next;
1054 Needed_Entry *nep = NEW(Needed_Entry);
1055 nep->name = dynp->d_un.d_val;
1059 *needed_aux_filtees_tail = nep;
1060 needed_aux_filtees_tail = &nep->next;
1065 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
1069 obj->textrel = true;
1073 obj->symbolic = true;
1078 * We have to wait until later to process this, because we
1079 * might not have gotten the address of the string table yet.
1089 *dyn_runpath = dynp;
1093 obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1096 case DT_PREINIT_ARRAY:
1097 obj->preinit_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1100 case DT_PREINIT_ARRAYSZ:
1101 obj->preinit_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1105 obj->init_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1108 case DT_INIT_ARRAYSZ:
1109 obj->init_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1113 obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1117 obj->fini_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1120 case DT_FINI_ARRAYSZ:
1121 obj->fini_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1125 * Don't process DT_DEBUG on MIPS as the dynamic section
1126 * is mapped read-only. DT_MIPS_RLD_MAP is used instead.
1132 dbg("Filling in DT_DEBUG entry");
1133 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
1138 if (dynp->d_un.d_val & DF_ORIGIN)
1139 obj->z_origin = true;
1140 if (dynp->d_un.d_val & DF_SYMBOLIC)
1141 obj->symbolic = true;
1142 if (dynp->d_un.d_val & DF_TEXTREL)
1143 obj->textrel = true;
1144 if (dynp->d_un.d_val & DF_BIND_NOW)
1145 obj->bind_now = true;
1146 /*if (dynp->d_un.d_val & DF_STATIC_TLS)
1150 case DT_MIPS_LOCAL_GOTNO:
1151 obj->local_gotno = dynp->d_un.d_val;
1154 case DT_MIPS_SYMTABNO:
1155 obj->symtabno = dynp->d_un.d_val;
1158 case DT_MIPS_GOTSYM:
1159 obj->gotsym = dynp->d_un.d_val;
1162 case DT_MIPS_RLD_MAP:
1163 *((Elf_Addr *)(dynp->d_un.d_ptr)) = (Elf_Addr) &r_debug;
1167 #ifdef __powerpc64__
1168 case DT_PPC64_GLINK:
1169 obj->glink = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1174 if (dynp->d_un.d_val & DF_1_NOOPEN)
1175 obj->z_noopen = true;
1176 if (dynp->d_un.d_val & DF_1_ORIGIN)
1177 obj->z_origin = true;
1178 if (dynp->d_un.d_val & DF_1_GLOBAL)
1179 obj->z_global = true;
1180 if (dynp->d_un.d_val & DF_1_BIND_NOW)
1181 obj->bind_now = true;
1182 if (dynp->d_un.d_val & DF_1_NODELETE)
1183 obj->z_nodelete = true;
1184 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1185 obj->z_loadfltr = true;
1186 if (dynp->d_un.d_val & DF_1_INTERPOSE)
1187 obj->z_interpose = true;
1188 if (dynp->d_un.d_val & DF_1_NODEFLIB)
1189 obj->z_nodeflib = true;
1194 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1201 obj->traced = false;
1203 if (plttype == DT_RELA) {
1204 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1206 obj->pltrelasize = obj->pltrelsize;
1207 obj->pltrelsize = 0;
1210 /* Determine size of dynsym table (equal to nchains of sysv hash) */
1211 if (obj->valid_hash_sysv)
1212 obj->dynsymcount = obj->nchains;
1213 else if (obj->valid_hash_gnu) {
1214 obj->dynsymcount = 0;
1215 for (bkt = 0; bkt < obj->nbuckets_gnu; bkt++) {
1216 if (obj->buckets_gnu[bkt] == 0)
1218 hashval = &obj->chain_zero_gnu[obj->buckets_gnu[bkt]];
1221 while ((*hashval++ & 1u) == 0);
1223 obj->dynsymcount += obj->symndx_gnu;
1228 obj_resolve_origin(Obj_Entry *obj)
1231 if (obj->origin_path != NULL)
1233 obj->origin_path = xmalloc(PATH_MAX);
1234 return (rtld_dirname_abs(obj->path, obj->origin_path) != -1);
1238 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1239 const Elf_Dyn *dyn_soname, const Elf_Dyn *dyn_runpath)
1242 if (obj->z_origin && !obj_resolve_origin(obj))
1245 if (dyn_runpath != NULL) {
1246 obj->runpath = (char *)obj->strtab + dyn_runpath->d_un.d_val;
1247 obj->runpath = origin_subst(obj, obj->runpath);
1248 } else if (dyn_rpath != NULL) {
1249 obj->rpath = (char *)obj->strtab + dyn_rpath->d_un.d_val;
1250 obj->rpath = origin_subst(obj, obj->rpath);
1252 if (dyn_soname != NULL)
1253 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1257 digest_dynamic(Obj_Entry *obj, int early)
1259 const Elf_Dyn *dyn_rpath;
1260 const Elf_Dyn *dyn_soname;
1261 const Elf_Dyn *dyn_runpath;
1263 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname, &dyn_runpath);
1264 digest_dynamic2(obj, dyn_rpath, dyn_soname, dyn_runpath);
1268 * Process a shared object's program header. This is used only for the
1269 * main program, when the kernel has already loaded the main program
1270 * into memory before calling the dynamic linker. It creates and
1271 * returns an Obj_Entry structure.
1274 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1277 const Elf_Phdr *phlimit = phdr + phnum;
1279 Elf_Addr note_start, note_end;
1283 for (ph = phdr; ph < phlimit; ph++) {
1284 if (ph->p_type != PT_PHDR)
1288 obj->phsize = ph->p_memsz;
1289 obj->relocbase = (caddr_t)phdr - ph->p_vaddr;
1293 obj->stack_flags = PF_X | PF_R | PF_W;
1295 for (ph = phdr; ph < phlimit; ph++) {
1296 switch (ph->p_type) {
1299 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1303 if (nsegs == 0) { /* First load segment */
1304 obj->vaddrbase = trunc_page(ph->p_vaddr);
1305 obj->mapbase = obj->vaddrbase + obj->relocbase;
1306 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
1308 } else { /* Last load segment */
1309 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1316 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1321 obj->tlssize = ph->p_memsz;
1322 obj->tlsalign = ph->p_align;
1323 obj->tlsinitsize = ph->p_filesz;
1324 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1328 obj->stack_flags = ph->p_flags;
1332 obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1333 obj->relro_size = round_page(ph->p_memsz);
1337 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
1338 note_end = note_start + ph->p_filesz;
1339 digest_notes(obj, note_start, note_end);
1344 _rtld_error("%s: too few PT_LOAD segments", path);
1353 digest_notes(Obj_Entry *obj, Elf_Addr note_start, Elf_Addr note_end)
1355 const Elf_Note *note;
1356 const char *note_name;
1359 for (note = (const Elf_Note *)note_start; (Elf_Addr)note < note_end;
1360 note = (const Elf_Note *)((const char *)(note + 1) +
1361 roundup2(note->n_namesz, sizeof(Elf32_Addr)) +
1362 roundup2(note->n_descsz, sizeof(Elf32_Addr)))) {
1363 if (note->n_namesz != sizeof(NOTE_FREEBSD_VENDOR) ||
1364 note->n_descsz != sizeof(int32_t))
1366 if (note->n_type != NT_FREEBSD_ABI_TAG &&
1367 note->n_type != NT_FREEBSD_NOINIT_TAG)
1369 note_name = (const char *)(note + 1);
1370 if (strncmp(NOTE_FREEBSD_VENDOR, note_name,
1371 sizeof(NOTE_FREEBSD_VENDOR)) != 0)
1373 switch (note->n_type) {
1374 case NT_FREEBSD_ABI_TAG:
1375 /* FreeBSD osrel note */
1376 p = (uintptr_t)(note + 1);
1377 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1378 obj->osrel = *(const int32_t *)(p);
1379 dbg("note osrel %d", obj->osrel);
1381 case NT_FREEBSD_NOINIT_TAG:
1382 /* FreeBSD 'crt does not call init' note */
1383 obj->crt_no_init = true;
1384 dbg("note crt_no_init");
1391 dlcheck(void *handle)
1395 TAILQ_FOREACH(obj, &obj_list, next) {
1396 if (obj == (Obj_Entry *) handle)
1400 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1401 _rtld_error("Invalid shared object handle %p", handle);
1408 * If the given object is already in the donelist, return true. Otherwise
1409 * add the object to the list and return false.
1412 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1416 for (i = 0; i < dlp->num_used; i++)
1417 if (dlp->objs[i] == obj)
1420 * Our donelist allocation should always be sufficient. But if
1421 * our threads locking isn't working properly, more shared objects
1422 * could have been loaded since we allocated the list. That should
1423 * never happen, but we'll handle it properly just in case it does.
1425 if (dlp->num_used < dlp->num_alloc)
1426 dlp->objs[dlp->num_used++] = obj;
1431 * Hash function for symbol table lookup. Don't even think about changing
1432 * this. It is specified by the System V ABI.
1435 elf_hash(const char *name)
1437 const unsigned char *p = (const unsigned char *) name;
1438 unsigned long h = 0;
1441 while (*p != '\0') {
1442 h = (h << 4) + *p++;
1443 if ((g = h & 0xf0000000) != 0)
1451 * The GNU hash function is the Daniel J. Bernstein hash clipped to 32 bits
1452 * unsigned in case it's implemented with a wider type.
1455 gnu_hash(const char *s)
1461 for (c = *s; c != '\0'; c = *++s)
1463 return (h & 0xffffffff);
1468 * Find the library with the given name, and return its full pathname.
1469 * The returned string is dynamically allocated. Generates an error
1470 * message and returns NULL if the library cannot be found.
1472 * If the second argument is non-NULL, then it refers to an already-
1473 * loaded shared object, whose library search path will be searched.
1475 * If a library is successfully located via LD_LIBRARY_PATH_FDS, its
1476 * descriptor (which is close-on-exec) will be passed out via the third
1479 * The search order is:
1480 * DT_RPATH in the referencing file _unless_ DT_RUNPATH is present (1)
1481 * DT_RPATH of the main object if DSO without defined DT_RUNPATH (1)
1483 * DT_RUNPATH in the referencing file
1484 * ldconfig hints (if -z nodefaultlib, filter out default library directories
1486 * /lib:/usr/lib _unless_ the referencing file is linked with -z nodefaultlib
1488 * (1) Handled in digest_dynamic2 - rpath left NULL if runpath defined.
1491 find_library(const char *xname, const Obj_Entry *refobj, int *fdp)
1495 bool nodeflib, objgiven;
1497 objgiven = refobj != NULL;
1498 if (strchr(xname, '/') != NULL) { /* Hard coded pathname */
1499 if (xname[0] != '/' && !trust) {
1500 _rtld_error("Absolute pathname required for shared object \"%s\"",
1504 return (origin_subst(__DECONST(Obj_Entry *, refobj),
1505 __DECONST(char *, xname)));
1508 if (libmap_disable || !objgiven ||
1509 (name = lm_find(refobj->path, xname)) == NULL)
1510 name = (char *)xname;
1512 dbg(" Searching for \"%s\"", name);
1515 * If refobj->rpath != NULL, then refobj->runpath is NULL. Fall
1516 * back to pre-conforming behaviour if user requested so with
1517 * LD_LIBRARY_PATH_RPATH environment variable and ignore -z
1520 if (objgiven && refobj->rpath != NULL && ld_library_path_rpath) {
1521 if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
1523 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
1524 (pathname = search_library_pathfds(name, ld_library_dirs, fdp)) != NULL ||
1525 (pathname = search_library_path(name, gethints(false))) != NULL ||
1526 (pathname = search_library_path(name, ld_standard_library_path)) != NULL)
1529 nodeflib = objgiven ? refobj->z_nodeflib : false;
1531 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
1532 (objgiven && refobj->runpath == NULL && refobj != obj_main &&
1533 (pathname = search_library_path(name, obj_main->rpath)) != NULL) ||
1534 (pathname = search_library_path(name, ld_library_path)) != NULL ||
1536 (pathname = search_library_path(name, refobj->runpath)) != NULL) ||
1537 (pathname = search_library_pathfds(name, ld_library_dirs, fdp)) != NULL ||
1538 (pathname = search_library_path(name, gethints(nodeflib))) != NULL ||
1539 (objgiven && !nodeflib &&
1540 (pathname = search_library_path(name, ld_standard_library_path)) != NULL))
1544 if (objgiven && refobj->path != NULL) {
1545 _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
1546 name, basename(refobj->path));
1548 _rtld_error("Shared object \"%s\" not found", name);
1554 * Given a symbol number in a referencing object, find the corresponding
1555 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1556 * no definition was found. Returns a pointer to the Obj_Entry of the
1557 * defining object via the reference parameter DEFOBJ_OUT.
1560 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1561 const Obj_Entry **defobj_out, int flags, SymCache *cache,
1562 RtldLockState *lockstate)
1566 const Obj_Entry *defobj;
1572 * If we have already found this symbol, get the information from
1575 if (symnum >= refobj->dynsymcount)
1576 return NULL; /* Bad object */
1577 if (cache != NULL && cache[symnum].sym != NULL) {
1578 *defobj_out = cache[symnum].obj;
1579 return cache[symnum].sym;
1582 ref = refobj->symtab + symnum;
1583 name = refobj->strtab + ref->st_name;
1588 * We don't have to do a full scale lookup if the symbol is local.
1589 * We know it will bind to the instance in this load module; to
1590 * which we already have a pointer (ie ref). By not doing a lookup,
1591 * we not only improve performance, but it also avoids unresolvable
1592 * symbols when local symbols are not in the hash table. This has
1593 * been seen with the ia64 toolchain.
1595 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1596 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1597 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1600 symlook_init(&req, name);
1602 req.ventry = fetch_ventry(refobj, symnum);
1603 req.lockstate = lockstate;
1604 res = symlook_default(&req, refobj);
1607 defobj = req.defobj_out;
1615 * If we found no definition and the reference is weak, treat the
1616 * symbol as having the value zero.
1618 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1624 *defobj_out = defobj;
1625 /* Record the information in the cache to avoid subsequent lookups. */
1626 if (cache != NULL) {
1627 cache[symnum].sym = def;
1628 cache[symnum].obj = defobj;
1631 if (refobj != &obj_rtld)
1632 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1638 * Return the search path from the ldconfig hints file, reading it if
1639 * necessary. If nostdlib is true, then the default search paths are
1640 * not added to result.
1642 * Returns NULL if there are problems with the hints file,
1643 * or if the search path there is empty.
1646 gethints(bool nostdlib)
1648 static char *hints, *filtered_path;
1649 static struct elfhints_hdr hdr;
1650 struct fill_search_info_args sargs, hargs;
1651 struct dl_serinfo smeta, hmeta, *SLPinfo, *hintinfo;
1652 struct dl_serpath *SLPpath, *hintpath;
1654 struct stat hint_stat;
1655 unsigned int SLPndx, hintndx, fndx, fcount;
1661 /* First call, read the hints file */
1662 if (hints == NULL) {
1663 /* Keep from trying again in case the hints file is bad. */
1666 if ((fd = open(ld_elf_hints_path, O_RDONLY | O_CLOEXEC)) == -1)
1670 * Check of hdr.dirlistlen value against type limit
1671 * intends to pacify static analyzers. Further
1672 * paranoia leads to checks that dirlist is fully
1673 * contained in the file range.
1675 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1676 hdr.magic != ELFHINTS_MAGIC ||
1677 hdr.version != 1 || hdr.dirlistlen > UINT_MAX / 2 ||
1678 fstat(fd, &hint_stat) == -1) {
1685 if (dl + hdr.dirlist < dl)
1688 if (dl + hdr.dirlistlen < dl)
1690 dl += hdr.dirlistlen;
1691 if (dl > hint_stat.st_size)
1693 p = xmalloc(hdr.dirlistlen + 1);
1695 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1696 read(fd, p, hdr.dirlistlen + 1) !=
1697 (ssize_t)hdr.dirlistlen + 1 || p[hdr.dirlistlen] != '\0') {
1706 * If caller agreed to receive list which includes the default
1707 * paths, we are done. Otherwise, if we still did not
1708 * calculated filtered result, do it now.
1711 return (hints[0] != '\0' ? hints : NULL);
1712 if (filtered_path != NULL)
1716 * Obtain the list of all configured search paths, and the
1717 * list of the default paths.
1719 * First estimate the size of the results.
1721 smeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1723 hmeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1726 sargs.request = RTLD_DI_SERINFOSIZE;
1727 sargs.serinfo = &smeta;
1728 hargs.request = RTLD_DI_SERINFOSIZE;
1729 hargs.serinfo = &hmeta;
1731 path_enumerate(ld_standard_library_path, fill_search_info, &sargs);
1732 path_enumerate(hints, fill_search_info, &hargs);
1734 SLPinfo = xmalloc(smeta.dls_size);
1735 hintinfo = xmalloc(hmeta.dls_size);
1738 * Next fetch both sets of paths.
1740 sargs.request = RTLD_DI_SERINFO;
1741 sargs.serinfo = SLPinfo;
1742 sargs.serpath = &SLPinfo->dls_serpath[0];
1743 sargs.strspace = (char *)&SLPinfo->dls_serpath[smeta.dls_cnt];
1745 hargs.request = RTLD_DI_SERINFO;
1746 hargs.serinfo = hintinfo;
1747 hargs.serpath = &hintinfo->dls_serpath[0];
1748 hargs.strspace = (char *)&hintinfo->dls_serpath[hmeta.dls_cnt];
1750 path_enumerate(ld_standard_library_path, fill_search_info, &sargs);
1751 path_enumerate(hints, fill_search_info, &hargs);
1754 * Now calculate the difference between two sets, by excluding
1755 * standard paths from the full set.
1759 filtered_path = xmalloc(hdr.dirlistlen + 1);
1760 hintpath = &hintinfo->dls_serpath[0];
1761 for (hintndx = 0; hintndx < hmeta.dls_cnt; hintndx++, hintpath++) {
1763 SLPpath = &SLPinfo->dls_serpath[0];
1765 * Check each standard path against current.
1767 for (SLPndx = 0; SLPndx < smeta.dls_cnt; SLPndx++, SLPpath++) {
1768 /* matched, skip the path */
1769 if (!strcmp(hintpath->dls_name, SLPpath->dls_name)) {
1777 * Not matched against any standard path, add the path
1778 * to result. Separate consequtive paths with ':'.
1781 filtered_path[fndx] = ':';
1785 flen = strlen(hintpath->dls_name);
1786 strncpy((filtered_path + fndx), hintpath->dls_name, flen);
1789 filtered_path[fndx] = '\0';
1795 return (filtered_path[0] != '\0' ? filtered_path : NULL);
1799 init_dag(Obj_Entry *root)
1801 const Needed_Entry *needed;
1802 const Objlist_Entry *elm;
1805 if (root->dag_inited)
1807 donelist_init(&donelist);
1809 /* Root object belongs to own DAG. */
1810 objlist_push_tail(&root->dldags, root);
1811 objlist_push_tail(&root->dagmembers, root);
1812 donelist_check(&donelist, root);
1815 * Add dependencies of root object to DAG in breadth order
1816 * by exploiting the fact that each new object get added
1817 * to the tail of the dagmembers list.
1819 STAILQ_FOREACH(elm, &root->dagmembers, link) {
1820 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
1821 if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
1823 objlist_push_tail(&needed->obj->dldags, root);
1824 objlist_push_tail(&root->dagmembers, needed->obj);
1827 root->dag_inited = true;
1831 init_marker(Obj_Entry *marker)
1834 bzero(marker, sizeof(*marker));
1835 marker->marker = true;
1839 globallist_curr(const Obj_Entry *obj)
1846 return (__DECONST(Obj_Entry *, obj));
1847 obj = TAILQ_PREV(obj, obj_entry_q, next);
1852 globallist_next(const Obj_Entry *obj)
1856 obj = TAILQ_NEXT(obj, next);
1860 return (__DECONST(Obj_Entry *, obj));
1864 /* Prevent the object from being unmapped while the bind lock is dropped. */
1866 hold_object(Obj_Entry *obj)
1873 unhold_object(Obj_Entry *obj)
1876 assert(obj->holdcount > 0);
1877 if (--obj->holdcount == 0 && obj->unholdfree)
1878 release_object(obj);
1882 process_z(Obj_Entry *root)
1884 const Objlist_Entry *elm;
1888 * Walk over object DAG and process every dependent object
1889 * that is marked as DF_1_NODELETE or DF_1_GLOBAL. They need
1890 * to grow their own DAG.
1892 * For DF_1_GLOBAL, DAG is required for symbol lookups in
1893 * symlook_global() to work.
1895 * For DF_1_NODELETE, the DAG should have its reference upped.
1897 STAILQ_FOREACH(elm, &root->dagmembers, link) {
1901 if (obj->z_nodelete && !obj->ref_nodel) {
1902 dbg("obj %s -z nodelete", obj->path);
1905 obj->ref_nodel = true;
1907 if (obj->z_global && objlist_find(&list_global, obj) == NULL) {
1908 dbg("obj %s -z global", obj->path);
1909 objlist_push_tail(&list_global, obj);
1915 * Initialize the dynamic linker. The argument is the address at which
1916 * the dynamic linker has been mapped into memory. The primary task of
1917 * this function is to relocate the dynamic linker.
1920 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
1922 Obj_Entry objtmp; /* Temporary rtld object */
1923 const Elf_Ehdr *ehdr;
1924 const Elf_Dyn *dyn_rpath;
1925 const Elf_Dyn *dyn_soname;
1926 const Elf_Dyn *dyn_runpath;
1928 #ifdef RTLD_INIT_PAGESIZES_EARLY
1929 /* The page size is required by the dynamic memory allocator. */
1930 init_pagesizes(aux_info);
1934 * Conjure up an Obj_Entry structure for the dynamic linker.
1936 * The "path" member can't be initialized yet because string constants
1937 * cannot yet be accessed. Below we will set it correctly.
1939 memset(&objtmp, 0, sizeof(objtmp));
1942 objtmp.mapbase = mapbase;
1944 objtmp.relocbase = mapbase;
1947 objtmp.dynamic = rtld_dynamic(&objtmp);
1948 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname, &dyn_runpath);
1949 assert(objtmp.needed == NULL);
1950 #if !defined(__mips__)
1951 /* MIPS has a bogus DT_TEXTREL. */
1952 assert(!objtmp.textrel);
1955 * Temporarily put the dynamic linker entry into the object list, so
1956 * that symbols can be found.
1958 relocate_objects(&objtmp, true, &objtmp, 0, NULL);
1960 ehdr = (Elf_Ehdr *)mapbase;
1961 objtmp.phdr = (Elf_Phdr *)((char *)mapbase + ehdr->e_phoff);
1962 objtmp.phsize = ehdr->e_phnum * sizeof(objtmp.phdr[0]);
1964 /* Initialize the object list. */
1965 TAILQ_INIT(&obj_list);
1967 /* Now that non-local variables can be accesses, copy out obj_rtld. */
1968 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1970 #ifndef RTLD_INIT_PAGESIZES_EARLY
1971 /* The page size is required by the dynamic memory allocator. */
1972 init_pagesizes(aux_info);
1975 if (aux_info[AT_OSRELDATE] != NULL)
1976 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
1978 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname, dyn_runpath);
1980 /* Replace the path with a dynamically allocated copy. */
1981 obj_rtld.path = xstrdup(ld_path_rtld);
1983 r_debug.r_brk = r_debug_state;
1984 r_debug.r_state = RT_CONSISTENT;
1988 * Retrieve the array of supported page sizes. The kernel provides the page
1989 * sizes in increasing order.
1992 init_pagesizes(Elf_Auxinfo **aux_info)
1994 static size_t psa[MAXPAGESIZES];
1998 if (aux_info[AT_PAGESIZES] != NULL && aux_info[AT_PAGESIZESLEN] !=
2000 size = aux_info[AT_PAGESIZESLEN]->a_un.a_val;
2001 pagesizes = aux_info[AT_PAGESIZES]->a_un.a_ptr;
2004 if (sysctlnametomib("hw.pagesizes", mib, &len) == 0)
2007 /* As a fallback, retrieve the base page size. */
2008 size = sizeof(psa[0]);
2009 if (aux_info[AT_PAGESZ] != NULL) {
2010 psa[0] = aux_info[AT_PAGESZ]->a_un.a_val;
2014 mib[1] = HW_PAGESIZE;
2018 if (sysctl(mib, len, psa, &size, NULL, 0) == -1) {
2019 _rtld_error("sysctl for hw.pagesize(s) failed");
2025 npagesizes = size / sizeof(pagesizes[0]);
2026 /* Discard any invalid entries at the end of the array. */
2027 while (npagesizes > 0 && pagesizes[npagesizes - 1] == 0)
2032 * Add the init functions from a needed object list (and its recursive
2033 * needed objects) to "list". This is not used directly; it is a helper
2034 * function for initlist_add_objects(). The write lock must be held
2035 * when this function is called.
2038 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
2040 /* Recursively process the successor needed objects. */
2041 if (needed->next != NULL)
2042 initlist_add_neededs(needed->next, list);
2044 /* Process the current needed object. */
2045 if (needed->obj != NULL)
2046 initlist_add_objects(needed->obj, needed->obj, list);
2050 * Scan all of the DAGs rooted in the range of objects from "obj" to
2051 * "tail" and add their init functions to "list". This recurses over
2052 * the DAGs and ensure the proper init ordering such that each object's
2053 * needed libraries are initialized before the object itself. At the
2054 * same time, this function adds the objects to the global finalization
2055 * list "list_fini" in the opposite order. The write lock must be
2056 * held when this function is called.
2059 initlist_add_objects(Obj_Entry *obj, Obj_Entry *tail, Objlist *list)
2063 if (obj->init_scanned || obj->init_done)
2065 obj->init_scanned = true;
2067 /* Recursively process the successor objects. */
2068 nobj = globallist_next(obj);
2069 if (nobj != NULL && obj != tail)
2070 initlist_add_objects(nobj, tail, list);
2072 /* Recursively process the needed objects. */
2073 if (obj->needed != NULL)
2074 initlist_add_neededs(obj->needed, list);
2075 if (obj->needed_filtees != NULL)
2076 initlist_add_neededs(obj->needed_filtees, list);
2077 if (obj->needed_aux_filtees != NULL)
2078 initlist_add_neededs(obj->needed_aux_filtees, list);
2080 /* Add the object to the init list. */
2081 if (obj->preinit_array != (Elf_Addr)NULL || obj->init != (Elf_Addr)NULL ||
2082 obj->init_array != (Elf_Addr)NULL)
2083 objlist_push_tail(list, obj);
2085 /* Add the object to the global fini list in the reverse order. */
2086 if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL)
2087 && !obj->on_fini_list) {
2088 objlist_push_head(&list_fini, obj);
2089 obj->on_fini_list = true;
2094 #define FPTR_TARGET(f) ((Elf_Addr) (f))
2098 free_needed_filtees(Needed_Entry *n, RtldLockState *lockstate)
2100 Needed_Entry *needed, *needed1;
2102 for (needed = n; needed != NULL; needed = needed->next) {
2103 if (needed->obj != NULL) {
2104 dlclose_locked(needed->obj, lockstate);
2108 for (needed = n; needed != NULL; needed = needed1) {
2109 needed1 = needed->next;
2115 unload_filtees(Obj_Entry *obj, RtldLockState *lockstate)
2118 free_needed_filtees(obj->needed_filtees, lockstate);
2119 obj->needed_filtees = NULL;
2120 free_needed_filtees(obj->needed_aux_filtees, lockstate);
2121 obj->needed_aux_filtees = NULL;
2122 obj->filtees_loaded = false;
2126 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags,
2127 RtldLockState *lockstate)
2130 for (; needed != NULL; needed = needed->next) {
2131 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
2132 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
2133 RTLD_LOCAL, lockstate);
2138 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
2141 lock_restart_for_upgrade(lockstate);
2142 if (!obj->filtees_loaded) {
2143 load_filtee1(obj, obj->needed_filtees, flags, lockstate);
2144 load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate);
2145 obj->filtees_loaded = true;
2150 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
2154 for (; needed != NULL; needed = needed->next) {
2155 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
2156 flags & ~RTLD_LO_NOLOAD);
2157 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
2164 * Given a shared object, traverse its list of needed objects, and load
2165 * each of them. Returns 0 on success. Generates an error message and
2166 * returns -1 on failure.
2169 load_needed_objects(Obj_Entry *first, int flags)
2173 for (obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
2176 if (process_needed(obj, obj->needed, flags) == -1)
2183 load_preload_objects(void)
2185 char *p = ld_preload;
2187 static const char delim[] = " \t:;";
2192 p += strspn(p, delim);
2193 while (*p != '\0') {
2194 size_t len = strcspn(p, delim);
2199 obj = load_object(p, -1, NULL, 0);
2201 return -1; /* XXX - cleanup */
2202 obj->z_interpose = true;
2205 p += strspn(p, delim);
2207 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
2212 printable_path(const char *path)
2215 return (path == NULL ? "<unknown>" : path);
2219 * Load a shared object into memory, if it is not already loaded. The
2220 * object may be specified by name or by user-supplied file descriptor
2221 * fd_u. In the later case, the fd_u descriptor is not closed, but its
2224 * Returns a pointer to the Obj_Entry for the object. Returns NULL
2228 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
2237 TAILQ_FOREACH(obj, &obj_list, next) {
2238 if (obj->marker || obj->doomed)
2240 if (object_match_name(obj, name))
2244 path = find_library(name, refobj, &fd);
2252 * search_library_pathfds() opens a fresh file descriptor for the
2253 * library, so there is no need to dup().
2255 } else if (fd_u == -1) {
2257 * If we didn't find a match by pathname, or the name is not
2258 * supplied, open the file and check again by device and inode.
2259 * This avoids false mismatches caused by multiple links or ".."
2262 * To avoid a race, we open the file and use fstat() rather than
2265 if ((fd = open(path, O_RDONLY | O_CLOEXEC | O_VERIFY)) == -1) {
2266 _rtld_error("Cannot open \"%s\"", path);
2271 fd = fcntl(fd_u, F_DUPFD_CLOEXEC, 0);
2273 _rtld_error("Cannot dup fd");
2278 if (fstat(fd, &sb) == -1) {
2279 _rtld_error("Cannot fstat \"%s\"", printable_path(path));
2284 TAILQ_FOREACH(obj, &obj_list, next) {
2285 if (obj->marker || obj->doomed)
2287 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
2290 if (obj != NULL && name != NULL) {
2291 object_add_name(obj, name);
2296 if (flags & RTLD_LO_NOLOAD) {
2302 /* First use of this object, so we must map it in */
2303 obj = do_load_object(fd, name, path, &sb, flags);
2312 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
2319 * but first, make sure that environment variables haven't been
2320 * used to circumvent the noexec flag on a filesystem.
2322 if (dangerous_ld_env) {
2323 if (fstatfs(fd, &fs) != 0) {
2324 _rtld_error("Cannot fstatfs \"%s\"", printable_path(path));
2327 if (fs.f_flags & MNT_NOEXEC) {
2328 _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
2332 dbg("loading \"%s\"", printable_path(path));
2333 obj = map_object(fd, printable_path(path), sbp);
2338 * If DT_SONAME is present in the object, digest_dynamic2 already
2339 * added it to the object names.
2342 object_add_name(obj, name);
2344 digest_dynamic(obj, 0);
2345 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path,
2346 obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount);
2347 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
2349 dbg("refusing to load non-loadable \"%s\"", obj->path);
2350 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
2351 munmap(obj->mapbase, obj->mapsize);
2356 obj->dlopened = (flags & RTLD_LO_DLOPEN) != 0;
2357 TAILQ_INSERT_TAIL(&obj_list, obj, next);
2360 linkmap_add(obj); /* for GDB & dlinfo() */
2361 max_stack_flags |= obj->stack_flags;
2363 dbg(" %p .. %p: %s", obj->mapbase,
2364 obj->mapbase + obj->mapsize - 1, obj->path);
2366 dbg(" WARNING: %s has impure text", obj->path);
2367 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
2374 obj_from_addr(const void *addr)
2378 TAILQ_FOREACH(obj, &obj_list, next) {
2381 if (addr < (void *) obj->mapbase)
2383 if (addr < (void *) (obj->mapbase + obj->mapsize))
2392 Elf_Addr *preinit_addr;
2395 preinit_addr = (Elf_Addr *)obj_main->preinit_array;
2396 if (preinit_addr == NULL)
2399 for (index = 0; index < obj_main->preinit_array_num; index++) {
2400 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) {
2401 dbg("calling preinit function for %s at %p", obj_main->path,
2402 (void *)preinit_addr[index]);
2403 LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index],
2404 0, 0, obj_main->path);
2405 call_init_pointer(obj_main, preinit_addr[index]);
2411 * Call the finalization functions for each of the objects in "list"
2412 * belonging to the DAG of "root" and referenced once. If NULL "root"
2413 * is specified, every finalization function will be called regardless
2414 * of the reference count and the list elements won't be freed. All of
2415 * the objects are expected to have non-NULL fini functions.
2418 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
2422 Elf_Addr *fini_addr;
2425 assert(root == NULL || root->refcount == 1);
2428 root->doomed = true;
2431 * Preserve the current error message since a fini function might
2432 * call into the dynamic linker and overwrite it.
2434 saved_msg = errmsg_save();
2436 STAILQ_FOREACH(elm, list, link) {
2437 if (root != NULL && (elm->obj->refcount != 1 ||
2438 objlist_find(&root->dagmembers, elm->obj) == NULL))
2440 /* Remove object from fini list to prevent recursive invocation. */
2441 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2442 /* Ensure that new references cannot be acquired. */
2443 elm->obj->doomed = true;
2445 hold_object(elm->obj);
2446 lock_release(rtld_bind_lock, lockstate);
2448 * It is legal to have both DT_FINI and DT_FINI_ARRAY defined.
2449 * When this happens, DT_FINI_ARRAY is processed first.
2451 fini_addr = (Elf_Addr *)elm->obj->fini_array;
2452 if (fini_addr != NULL && elm->obj->fini_array_num > 0) {
2453 for (index = elm->obj->fini_array_num - 1; index >= 0;
2455 if (fini_addr[index] != 0 && fini_addr[index] != 1) {
2456 dbg("calling fini function for %s at %p",
2457 elm->obj->path, (void *)fini_addr[index]);
2458 LD_UTRACE(UTRACE_FINI_CALL, elm->obj,
2459 (void *)fini_addr[index], 0, 0, elm->obj->path);
2460 call_initfini_pointer(elm->obj, fini_addr[index]);
2464 if (elm->obj->fini != (Elf_Addr)NULL) {
2465 dbg("calling fini function for %s at %p", elm->obj->path,
2466 (void *)elm->obj->fini);
2467 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini,
2468 0, 0, elm->obj->path);
2469 call_initfini_pointer(elm->obj, elm->obj->fini);
2471 wlock_acquire(rtld_bind_lock, lockstate);
2472 unhold_object(elm->obj);
2473 /* No need to free anything if process is going down. */
2477 * We must restart the list traversal after every fini call
2478 * because a dlclose() call from the fini function or from
2479 * another thread might have modified the reference counts.
2483 } while (elm != NULL);
2484 errmsg_restore(saved_msg);
2488 * Call the initialization functions for each of the objects in
2489 * "list". All of the objects are expected to have non-NULL init
2493 objlist_call_init(Objlist *list, RtldLockState *lockstate)
2498 Elf_Addr *init_addr;
2502 * Clean init_scanned flag so that objects can be rechecked and
2503 * possibly initialized earlier if any of vectors called below
2504 * cause the change by using dlopen.
2506 TAILQ_FOREACH(obj, &obj_list, next) {
2509 obj->init_scanned = false;
2513 * Preserve the current error message since an init function might
2514 * call into the dynamic linker and overwrite it.
2516 saved_msg = errmsg_save();
2517 STAILQ_FOREACH(elm, list, link) {
2518 if (elm->obj->init_done) /* Initialized early. */
2521 * Race: other thread might try to use this object before current
2522 * one completes the initialization. Not much can be done here
2523 * without better locking.
2525 elm->obj->init_done = true;
2526 hold_object(elm->obj);
2527 lock_release(rtld_bind_lock, lockstate);
2530 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined.
2531 * When this happens, DT_INIT is processed first.
2533 if (elm->obj->init != (Elf_Addr)NULL) {
2534 dbg("calling init function for %s at %p", elm->obj->path,
2535 (void *)elm->obj->init);
2536 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init,
2537 0, 0, elm->obj->path);
2538 call_initfini_pointer(elm->obj, elm->obj->init);
2540 init_addr = (Elf_Addr *)elm->obj->init_array;
2541 if (init_addr != NULL) {
2542 for (index = 0; index < elm->obj->init_array_num; index++) {
2543 if (init_addr[index] != 0 && init_addr[index] != 1) {
2544 dbg("calling init function for %s at %p", elm->obj->path,
2545 (void *)init_addr[index]);
2546 LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
2547 (void *)init_addr[index], 0, 0, elm->obj->path);
2548 call_init_pointer(elm->obj, init_addr[index]);
2552 wlock_acquire(rtld_bind_lock, lockstate);
2553 unhold_object(elm->obj);
2555 errmsg_restore(saved_msg);
2559 objlist_clear(Objlist *list)
2563 while (!STAILQ_EMPTY(list)) {
2564 elm = STAILQ_FIRST(list);
2565 STAILQ_REMOVE_HEAD(list, link);
2570 static Objlist_Entry *
2571 objlist_find(Objlist *list, const Obj_Entry *obj)
2575 STAILQ_FOREACH(elm, list, link)
2576 if (elm->obj == obj)
2582 objlist_init(Objlist *list)
2588 objlist_push_head(Objlist *list, Obj_Entry *obj)
2592 elm = NEW(Objlist_Entry);
2594 STAILQ_INSERT_HEAD(list, elm, link);
2598 objlist_push_tail(Objlist *list, Obj_Entry *obj)
2602 elm = NEW(Objlist_Entry);
2604 STAILQ_INSERT_TAIL(list, elm, link);
2608 objlist_put_after(Objlist *list, Obj_Entry *listobj, Obj_Entry *obj)
2610 Objlist_Entry *elm, *listelm;
2612 STAILQ_FOREACH(listelm, list, link) {
2613 if (listelm->obj == listobj)
2616 elm = NEW(Objlist_Entry);
2618 if (listelm != NULL)
2619 STAILQ_INSERT_AFTER(list, listelm, elm, link);
2621 STAILQ_INSERT_TAIL(list, elm, link);
2625 objlist_remove(Objlist *list, Obj_Entry *obj)
2629 if ((elm = objlist_find(list, obj)) != NULL) {
2630 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2636 * Relocate dag rooted in the specified object.
2637 * Returns 0 on success, or -1 on failure.
2641 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj,
2642 int flags, RtldLockState *lockstate)
2648 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2649 error = relocate_object(elm->obj, bind_now, rtldobj, flags,
2658 * Prepare for, or clean after, relocating an object marked with
2659 * DT_TEXTREL or DF_TEXTREL. Before relocating, all read-only
2660 * segments are remapped read-write. After relocations are done, the
2661 * segment's permissions are returned back to the modes specified in
2662 * the phdrs. If any relocation happened, or always for wired
2663 * program, COW is triggered.
2666 reloc_textrel_prot(Obj_Entry *obj, bool before)
2673 for (l = obj->phsize / sizeof(*ph), ph = obj->phdr; l > 0;
2675 if (ph->p_type != PT_LOAD || (ph->p_flags & PF_W) != 0)
2677 base = obj->relocbase + trunc_page(ph->p_vaddr);
2678 sz = round_page(ph->p_vaddr + ph->p_filesz) -
2679 trunc_page(ph->p_vaddr);
2680 prot = convert_prot(ph->p_flags) | (before ? PROT_WRITE : 0);
2681 if (mprotect(base, sz, prot) == -1) {
2682 _rtld_error("%s: Cannot write-%sable text segment: %s",
2683 obj->path, before ? "en" : "dis",
2684 rtld_strerror(errno));
2692 * Relocate single object.
2693 * Returns 0 on success, or -1 on failure.
2696 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
2697 int flags, RtldLockState *lockstate)
2702 obj->relocated = true;
2704 dbg("relocating \"%s\"", obj->path);
2706 if (obj->symtab == NULL || obj->strtab == NULL ||
2707 !(obj->valid_hash_sysv || obj->valid_hash_gnu)) {
2708 _rtld_error("%s: Shared object has no run-time symbol table",
2713 /* There are relocations to the write-protected text segment. */
2714 if (obj->textrel && reloc_textrel_prot(obj, true) != 0)
2717 /* Process the non-PLT non-IFUNC relocations. */
2718 if (reloc_non_plt(obj, rtldobj, flags, lockstate))
2721 /* Re-protected the text segment. */
2722 if (obj->textrel && reloc_textrel_prot(obj, false) != 0)
2725 /* Set the special PLT or GOT entries. */
2728 /* Process the PLT relocations. */
2729 if (reloc_plt(obj) == -1)
2731 /* Relocate the jump slots if we are doing immediate binding. */
2732 if (obj->bind_now || bind_now)
2733 if (reloc_jmpslots(obj, flags, lockstate) == -1)
2737 * Process the non-PLT IFUNC relocations. The relocations are
2738 * processed in two phases, because IFUNC resolvers may
2739 * reference other symbols, which must be readily processed
2740 * before resolvers are called.
2742 if (obj->non_plt_gnu_ifunc &&
2743 reloc_non_plt(obj, rtldobj, flags | SYMLOOK_IFUNC, lockstate))
2746 if (!obj->mainprog && obj_enforce_relro(obj) == -1)
2750 * Set up the magic number and version in the Obj_Entry. These
2751 * were checked in the crt1.o from the original ElfKit, so we
2752 * set them for backward compatibility.
2754 obj->magic = RTLD_MAGIC;
2755 obj->version = RTLD_VERSION;
2761 * Relocate newly-loaded shared objects. The argument is a pointer to
2762 * the Obj_Entry for the first such object. All objects from the first
2763 * to the end of the list of objects are relocated. Returns 0 on success,
2767 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
2768 int flags, RtldLockState *lockstate)
2773 for (error = 0, obj = first; obj != NULL;
2774 obj = TAILQ_NEXT(obj, next)) {
2777 error = relocate_object(obj, bind_now, rtldobj, flags,
2786 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
2787 * referencing STT_GNU_IFUNC symbols is postponed till the other
2788 * relocations are done. The indirect functions specified as
2789 * ifunc are allowed to call other symbols, so we need to have
2790 * objects relocated before asking for resolution from indirects.
2792 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
2793 * instead of the usual lazy handling of PLT slots. It is
2794 * consistent with how GNU does it.
2797 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags,
2798 RtldLockState *lockstate)
2800 if (obj->irelative && reloc_iresolve(obj, lockstate) == -1)
2802 if ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
2803 reloc_gnu_ifunc(obj, flags, lockstate) == -1)
2809 resolve_objects_ifunc(Obj_Entry *first, bool bind_now, int flags,
2810 RtldLockState *lockstate)
2814 for (obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
2817 if (resolve_object_ifunc(obj, bind_now, flags, lockstate) == -1)
2824 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags,
2825 RtldLockState *lockstate)
2829 STAILQ_FOREACH(elm, list, link) {
2830 if (resolve_object_ifunc(elm->obj, bind_now, flags,
2838 * Cleanup procedure. It will be called (by the atexit mechanism) just
2839 * before the process exits.
2844 RtldLockState lockstate;
2846 wlock_acquire(rtld_bind_lock, &lockstate);
2848 objlist_call_fini(&list_fini, NULL, &lockstate);
2849 /* No need to remove the items from the list, since we are exiting. */
2850 if (!libmap_disable)
2852 lock_release(rtld_bind_lock, &lockstate);
2856 * Iterate over a search path, translate each element, and invoke the
2857 * callback on the result.
2860 path_enumerate(const char *path, path_enum_proc callback, void *arg)
2866 path += strspn(path, ":;");
2867 while (*path != '\0') {
2871 len = strcspn(path, ":;");
2872 trans = lm_findn(NULL, path, len);
2874 res = callback(trans, strlen(trans), arg);
2876 res = callback(path, len, arg);
2882 path += strspn(path, ":;");
2888 struct try_library_args {
2896 try_library_path(const char *dir, size_t dirlen, void *param)
2898 struct try_library_args *arg;
2901 if (*dir == '/' || trust) {
2904 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
2907 pathname = arg->buffer;
2908 strncpy(pathname, dir, dirlen);
2909 pathname[dirlen] = '/';
2910 strcpy(pathname + dirlen + 1, arg->name);
2912 dbg(" Trying \"%s\"", pathname);
2913 if (access(pathname, F_OK) == 0) { /* We found it */
2914 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
2915 strcpy(pathname, arg->buffer);
2923 search_library_path(const char *name, const char *path)
2926 struct try_library_args arg;
2932 arg.namelen = strlen(name);
2933 arg.buffer = xmalloc(PATH_MAX);
2934 arg.buflen = PATH_MAX;
2936 p = path_enumerate(path, try_library_path, &arg);
2945 * Finds the library with the given name using the directory descriptors
2946 * listed in the LD_LIBRARY_PATH_FDS environment variable.
2948 * Returns a freshly-opened close-on-exec file descriptor for the library,
2949 * or -1 if the library cannot be found.
2952 search_library_pathfds(const char *name, const char *path, int *fdp)
2954 char *envcopy, *fdstr, *found, *last_token;
2958 dbg("%s('%s', '%s', fdp)", __func__, name, path);
2960 /* Don't load from user-specified libdirs into setuid binaries. */
2964 /* We can't do anything if LD_LIBRARY_PATH_FDS isn't set. */
2968 /* LD_LIBRARY_PATH_FDS only works with relative paths. */
2969 if (name[0] == '/') {
2970 dbg("Absolute path (%s) passed to %s", name, __func__);
2975 * Use strtok_r() to walk the FD:FD:FD list. This requires a local
2976 * copy of the path, as strtok_r rewrites separator tokens
2980 envcopy = xstrdup(path);
2981 for (fdstr = strtok_r(envcopy, ":", &last_token); fdstr != NULL;
2982 fdstr = strtok_r(NULL, ":", &last_token)) {
2983 dirfd = parse_libdir(fdstr);
2986 fd = __sys_openat(dirfd, name, O_RDONLY | O_CLOEXEC | O_VERIFY);
2989 len = strlen(fdstr) + strlen(name) + 3;
2990 found = xmalloc(len);
2991 if (rtld_snprintf(found, len, "#%d/%s", dirfd, name) < 0) {
2992 _rtld_error("error generating '%d/%s'",
2996 dbg("open('%s') => %d", found, fd);
3007 dlclose(void *handle)
3009 RtldLockState lockstate;
3012 wlock_acquire(rtld_bind_lock, &lockstate);
3013 error = dlclose_locked(handle, &lockstate);
3014 lock_release(rtld_bind_lock, &lockstate);
3019 dlclose_locked(void *handle, RtldLockState *lockstate)
3023 root = dlcheck(handle);
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, lockstate);
3044 GDB_STATE(RT_CONSISTENT,NULL);
3048 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
3055 char *msg = error_message;
3056 error_message = NULL;
3061 * This function is deprecated and has no effect.
3064 dllockinit(void *context,
3065 void *(*lock_create)(void *context),
3066 void (*rlock_acquire)(void *lock),
3067 void (*wlock_acquire)(void *lock),
3068 void (*lock_release)(void *lock),
3069 void (*lock_destroy)(void *lock),
3070 void (*context_destroy)(void *context))
3072 static void *cur_context;
3073 static void (*cur_context_destroy)(void *);
3075 /* Just destroy the context from the previous call, if necessary. */
3076 if (cur_context_destroy != NULL)
3077 cur_context_destroy(cur_context);
3078 cur_context = context;
3079 cur_context_destroy = context_destroy;
3083 dlopen(const char *name, int mode)
3086 return (rtld_dlopen(name, -1, mode));
3090 fdlopen(int fd, int mode)
3093 return (rtld_dlopen(NULL, fd, mode));
3097 rtld_dlopen(const char *name, int fd, int mode)
3099 RtldLockState lockstate;
3102 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
3103 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
3104 if (ld_tracing != NULL) {
3105 rlock_acquire(rtld_bind_lock, &lockstate);
3106 if (sigsetjmp(lockstate.env, 0) != 0)
3107 lock_upgrade(rtld_bind_lock, &lockstate);
3108 environ = (char **)*get_program_var_addr("environ", &lockstate);
3109 lock_release(rtld_bind_lock, &lockstate);
3111 lo_flags = RTLD_LO_DLOPEN;
3112 if (mode & RTLD_NODELETE)
3113 lo_flags |= RTLD_LO_NODELETE;
3114 if (mode & RTLD_NOLOAD)
3115 lo_flags |= RTLD_LO_NOLOAD;
3116 if (ld_tracing != NULL)
3117 lo_flags |= RTLD_LO_TRACE;
3119 return (dlopen_object(name, fd, obj_main, lo_flags,
3120 mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL));
3124 dlopen_cleanup(Obj_Entry *obj, RtldLockState *lockstate)
3129 if (obj->refcount == 0)
3130 unload_object(obj, lockstate);
3134 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
3135 int mode, RtldLockState *lockstate)
3137 Obj_Entry *old_obj_tail;
3140 RtldLockState mlockstate;
3143 objlist_init(&initlist);
3145 if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) {
3146 wlock_acquire(rtld_bind_lock, &mlockstate);
3147 lockstate = &mlockstate;
3149 GDB_STATE(RT_ADD,NULL);
3151 old_obj_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
3153 if (name == NULL && fd == -1) {
3157 obj = load_object(name, fd, refobj, lo_flags);
3162 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
3163 objlist_push_tail(&list_global, obj);
3164 if (globallist_next(old_obj_tail) != NULL) {
3165 /* We loaded something new. */
3166 assert(globallist_next(old_obj_tail) == obj);
3167 result = load_needed_objects(obj,
3168 lo_flags & (RTLD_LO_DLOPEN | RTLD_LO_EARLY));
3172 result = rtld_verify_versions(&obj->dagmembers);
3173 if (result != -1 && ld_tracing)
3175 if (result == -1 || relocate_object_dag(obj,
3176 (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld,
3177 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3179 dlopen_cleanup(obj, lockstate);
3181 } else if (lo_flags & RTLD_LO_EARLY) {
3183 * Do not call the init functions for early loaded
3184 * filtees. The image is still not initialized enough
3187 * Our object is found by the global object list and
3188 * will be ordered among all init calls done right
3189 * before transferring control to main.
3192 /* Make list of init functions to call. */
3193 initlist_add_objects(obj, obj, &initlist);
3196 * Process all no_delete or global objects here, given
3197 * them own DAGs to prevent their dependencies from being
3198 * unloaded. This has to be done after we have loaded all
3199 * of the dependencies, so that we do not miss any.
3205 * Bump the reference counts for objects on this DAG. If
3206 * this is the first dlopen() call for the object that was
3207 * already loaded as a dependency, initialize the dag
3213 if ((lo_flags & RTLD_LO_TRACE) != 0)
3216 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
3217 obj->z_nodelete) && !obj->ref_nodel) {
3218 dbg("obj %s nodelete", obj->path);
3220 obj->z_nodelete = obj->ref_nodel = true;
3224 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
3226 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
3228 if (!(lo_flags & RTLD_LO_EARLY)) {
3229 map_stacks_exec(lockstate);
3232 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
3233 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3235 objlist_clear(&initlist);
3236 dlopen_cleanup(obj, lockstate);
3237 if (lockstate == &mlockstate)
3238 lock_release(rtld_bind_lock, lockstate);
3242 if (!(lo_flags & RTLD_LO_EARLY)) {
3243 /* Call the init functions. */
3244 objlist_call_init(&initlist, lockstate);
3246 objlist_clear(&initlist);
3247 if (lockstate == &mlockstate)
3248 lock_release(rtld_bind_lock, lockstate);
3251 trace_loaded_objects(obj);
3252 if (lockstate == &mlockstate)
3253 lock_release(rtld_bind_lock, lockstate);
3258 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
3262 const Obj_Entry *obj, *defobj;
3265 RtldLockState lockstate;
3272 symlook_init(&req, name);
3274 req.flags = flags | SYMLOOK_IN_PLT;
3275 req.lockstate = &lockstate;
3277 LD_UTRACE(UTRACE_DLSYM_START, handle, NULL, 0, 0, name);
3278 rlock_acquire(rtld_bind_lock, &lockstate);
3279 if (sigsetjmp(lockstate.env, 0) != 0)
3280 lock_upgrade(rtld_bind_lock, &lockstate);
3281 if (handle == NULL || handle == RTLD_NEXT ||
3282 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
3284 if ((obj = obj_from_addr(retaddr)) == NULL) {
3285 _rtld_error("Cannot determine caller's shared object");
3286 lock_release(rtld_bind_lock, &lockstate);
3287 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3290 if (handle == NULL) { /* Just the caller's shared object. */
3291 res = symlook_obj(&req, obj);
3294 defobj = req.defobj_out;
3296 } else if (handle == RTLD_NEXT || /* Objects after caller's */
3297 handle == RTLD_SELF) { /* ... caller included */
3298 if (handle == RTLD_NEXT)
3299 obj = globallist_next(obj);
3300 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
3303 res = symlook_obj(&req, obj);
3306 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) {
3308 defobj = req.defobj_out;
3309 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3315 * Search the dynamic linker itself, and possibly resolve the
3316 * symbol from there. This is how the application links to
3317 * dynamic linker services such as dlopen.
3319 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3320 res = symlook_obj(&req, &obj_rtld);
3323 defobj = req.defobj_out;
3327 assert(handle == RTLD_DEFAULT);
3328 res = symlook_default(&req, obj);
3330 defobj = req.defobj_out;
3335 if ((obj = dlcheck(handle)) == NULL) {
3336 lock_release(rtld_bind_lock, &lockstate);
3337 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3341 donelist_init(&donelist);
3342 if (obj->mainprog) {
3343 /* Handle obtained by dlopen(NULL, ...) implies global scope. */
3344 res = symlook_global(&req, &donelist);
3347 defobj = req.defobj_out;
3350 * Search the dynamic linker itself, and possibly resolve the
3351 * symbol from there. This is how the application links to
3352 * dynamic linker services such as dlopen.
3354 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3355 res = symlook_obj(&req, &obj_rtld);
3358 defobj = req.defobj_out;
3363 /* Search the whole DAG rooted at the given object. */
3364 res = symlook_list(&req, &obj->dagmembers, &donelist);
3367 defobj = req.defobj_out;
3373 lock_release(rtld_bind_lock, &lockstate);
3376 * The value required by the caller is derived from the value
3377 * of the symbol. this is simply the relocated value of the
3380 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
3381 sym = make_function_pointer(def, defobj);
3382 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
3383 sym = rtld_resolve_ifunc(defobj, def);
3384 else if (ELF_ST_TYPE(def->st_info) == STT_TLS) {
3385 ti.ti_module = defobj->tlsindex;
3386 ti.ti_offset = def->st_value;
3387 sym = __tls_get_addr(&ti);
3389 sym = defobj->relocbase + def->st_value;
3390 LD_UTRACE(UTRACE_DLSYM_STOP, handle, sym, 0, 0, name);
3394 _rtld_error("Undefined symbol \"%s\"", name);
3395 lock_release(rtld_bind_lock, &lockstate);
3396 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3401 dlsym(void *handle, const char *name)
3403 return do_dlsym(handle, name, __builtin_return_address(0), NULL,
3408 dlfunc(void *handle, const char *name)
3415 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
3421 dlvsym(void *handle, const char *name, const char *version)
3425 ventry.name = version;
3427 ventry.hash = elf_hash(version);
3429 return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
3434 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
3436 const Obj_Entry *obj;
3437 RtldLockState lockstate;
3439 rlock_acquire(rtld_bind_lock, &lockstate);
3440 obj = obj_from_addr(addr);
3442 _rtld_error("No shared object contains address");
3443 lock_release(rtld_bind_lock, &lockstate);
3446 rtld_fill_dl_phdr_info(obj, phdr_info);
3447 lock_release(rtld_bind_lock, &lockstate);
3452 dladdr(const void *addr, Dl_info *info)
3454 const Obj_Entry *obj;
3457 unsigned long symoffset;
3458 RtldLockState lockstate;
3460 rlock_acquire(rtld_bind_lock, &lockstate);
3461 obj = obj_from_addr(addr);
3463 _rtld_error("No shared object contains address");
3464 lock_release(rtld_bind_lock, &lockstate);
3467 info->dli_fname = obj->path;
3468 info->dli_fbase = obj->mapbase;
3469 info->dli_saddr = (void *)0;
3470 info->dli_sname = NULL;
3473 * Walk the symbol list looking for the symbol whose address is
3474 * closest to the address sent in.
3476 for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) {
3477 def = obj->symtab + symoffset;
3480 * For skip the symbol if st_shndx is either SHN_UNDEF or
3483 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
3487 * If the symbol is greater than the specified address, or if it
3488 * is further away from addr than the current nearest symbol,
3491 symbol_addr = obj->relocbase + def->st_value;
3492 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
3495 /* Update our idea of the nearest symbol. */
3496 info->dli_sname = obj->strtab + def->st_name;
3497 info->dli_saddr = symbol_addr;
3500 if (info->dli_saddr == addr)
3503 lock_release(rtld_bind_lock, &lockstate);
3508 dlinfo(void *handle, int request, void *p)
3510 const Obj_Entry *obj;
3511 RtldLockState lockstate;
3514 rlock_acquire(rtld_bind_lock, &lockstate);
3516 if (handle == NULL || handle == RTLD_SELF) {
3519 retaddr = __builtin_return_address(0); /* __GNUC__ only */
3520 if ((obj = obj_from_addr(retaddr)) == NULL)
3521 _rtld_error("Cannot determine caller's shared object");
3523 obj = dlcheck(handle);
3526 lock_release(rtld_bind_lock, &lockstate);
3532 case RTLD_DI_LINKMAP:
3533 *((struct link_map const **)p) = &obj->linkmap;
3535 case RTLD_DI_ORIGIN:
3536 error = rtld_dirname(obj->path, p);
3539 case RTLD_DI_SERINFOSIZE:
3540 case RTLD_DI_SERINFO:
3541 error = do_search_info(obj, request, (struct dl_serinfo *)p);
3545 _rtld_error("Invalid request %d passed to dlinfo()", request);
3549 lock_release(rtld_bind_lock, &lockstate);
3555 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
3558 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
3559 phdr_info->dlpi_name = obj->path;
3560 phdr_info->dlpi_phdr = obj->phdr;
3561 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
3562 phdr_info->dlpi_tls_modid = obj->tlsindex;
3563 phdr_info->dlpi_tls_data = obj->tlsinit;
3564 phdr_info->dlpi_adds = obj_loads;
3565 phdr_info->dlpi_subs = obj_loads - obj_count;
3569 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
3571 struct dl_phdr_info phdr_info;
3572 Obj_Entry *obj, marker;
3573 RtldLockState bind_lockstate, phdr_lockstate;
3576 init_marker(&marker);
3579 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
3580 wlock_acquire(rtld_bind_lock, &bind_lockstate);
3581 for (obj = globallist_curr(TAILQ_FIRST(&obj_list)); obj != NULL;) {
3582 TAILQ_INSERT_AFTER(&obj_list, obj, &marker, next);
3583 rtld_fill_dl_phdr_info(obj, &phdr_info);
3585 lock_release(rtld_bind_lock, &bind_lockstate);
3587 error = callback(&phdr_info, sizeof phdr_info, param);
3589 wlock_acquire(rtld_bind_lock, &bind_lockstate);
3591 obj = globallist_next(&marker);
3592 TAILQ_REMOVE(&obj_list, &marker, next);
3594 lock_release(rtld_bind_lock, &bind_lockstate);
3595 lock_release(rtld_phdr_lock, &phdr_lockstate);
3601 rtld_fill_dl_phdr_info(&obj_rtld, &phdr_info);
3602 lock_release(rtld_bind_lock, &bind_lockstate);
3603 error = callback(&phdr_info, sizeof(phdr_info), param);
3605 lock_release(rtld_phdr_lock, &phdr_lockstate);
3610 fill_search_info(const char *dir, size_t dirlen, void *param)
3612 struct fill_search_info_args *arg;
3616 if (arg->request == RTLD_DI_SERINFOSIZE) {
3617 arg->serinfo->dls_cnt ++;
3618 arg->serinfo->dls_size += sizeof(struct dl_serpath) + dirlen + 1;
3620 struct dl_serpath *s_entry;
3622 s_entry = arg->serpath;
3623 s_entry->dls_name = arg->strspace;
3624 s_entry->dls_flags = arg->flags;
3626 strncpy(arg->strspace, dir, dirlen);
3627 arg->strspace[dirlen] = '\0';
3629 arg->strspace += dirlen + 1;
3637 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
3639 struct dl_serinfo _info;
3640 struct fill_search_info_args args;
3642 args.request = RTLD_DI_SERINFOSIZE;
3643 args.serinfo = &_info;
3645 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
3648 path_enumerate(obj->rpath, fill_search_info, &args);
3649 path_enumerate(ld_library_path, fill_search_info, &args);
3650 path_enumerate(obj->runpath, fill_search_info, &args);
3651 path_enumerate(gethints(obj->z_nodeflib), fill_search_info, &args);
3652 if (!obj->z_nodeflib)
3653 path_enumerate(ld_standard_library_path, fill_search_info, &args);
3656 if (request == RTLD_DI_SERINFOSIZE) {
3657 info->dls_size = _info.dls_size;
3658 info->dls_cnt = _info.dls_cnt;
3662 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
3663 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
3667 args.request = RTLD_DI_SERINFO;
3668 args.serinfo = info;
3669 args.serpath = &info->dls_serpath[0];
3670 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
3672 args.flags = LA_SER_RUNPATH;
3673 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
3676 args.flags = LA_SER_LIBPATH;
3677 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
3680 args.flags = LA_SER_RUNPATH;
3681 if (path_enumerate(obj->runpath, fill_search_info, &args) != NULL)
3684 args.flags = LA_SER_CONFIG;
3685 if (path_enumerate(gethints(obj->z_nodeflib), fill_search_info, &args)
3689 args.flags = LA_SER_DEFAULT;
3690 if (!obj->z_nodeflib &&
3691 path_enumerate(ld_standard_library_path, fill_search_info, &args) != NULL)
3697 rtld_dirname(const char *path, char *bname)
3701 /* Empty or NULL string gets treated as "." */
3702 if (path == NULL || *path == '\0') {
3708 /* Strip trailing slashes */
3709 endp = path + strlen(path) - 1;
3710 while (endp > path && *endp == '/')
3713 /* Find the start of the dir */
3714 while (endp > path && *endp != '/')
3717 /* Either the dir is "/" or there are no slashes */
3719 bname[0] = *endp == '/' ? '/' : '.';
3725 } while (endp > path && *endp == '/');
3728 if (endp - path + 2 > PATH_MAX)
3730 _rtld_error("Filename is too long: %s", path);
3734 strncpy(bname, path, endp - path + 1);
3735 bname[endp - path + 1] = '\0';
3740 rtld_dirname_abs(const char *path, char *base)
3744 if (realpath(path, base) == NULL)
3746 dbg("%s -> %s", path, base);
3747 last = strrchr(base, '/');
3756 linkmap_add(Obj_Entry *obj)
3758 struct link_map *l = &obj->linkmap;
3759 struct link_map *prev;
3761 obj->linkmap.l_name = obj->path;
3762 obj->linkmap.l_addr = obj->mapbase;
3763 obj->linkmap.l_ld = obj->dynamic;
3765 /* GDB needs load offset on MIPS to use the symbols */
3766 obj->linkmap.l_offs = obj->relocbase;
3769 if (r_debug.r_map == NULL) {
3775 * Scan to the end of the list, but not past the entry for the
3776 * dynamic linker, which we want to keep at the very end.
3778 for (prev = r_debug.r_map;
3779 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
3780 prev = prev->l_next)
3783 /* Link in the new entry. */
3785 l->l_next = prev->l_next;
3786 if (l->l_next != NULL)
3787 l->l_next->l_prev = l;
3792 linkmap_delete(Obj_Entry *obj)
3794 struct link_map *l = &obj->linkmap;
3796 if (l->l_prev == NULL) {
3797 if ((r_debug.r_map = l->l_next) != NULL)
3798 l->l_next->l_prev = NULL;
3802 if ((l->l_prev->l_next = l->l_next) != NULL)
3803 l->l_next->l_prev = l->l_prev;
3807 * Function for the debugger to set a breakpoint on to gain control.
3809 * The two parameters allow the debugger to easily find and determine
3810 * what the runtime loader is doing and to whom it is doing it.
3812 * When the loadhook trap is hit (r_debug_state, set at program
3813 * initialization), the arguments can be found on the stack:
3815 * +8 struct link_map *m
3816 * +4 struct r_debug *rd
3820 r_debug_state(struct r_debug* rd, struct link_map *m)
3823 * The following is a hack to force the compiler to emit calls to
3824 * this function, even when optimizing. If the function is empty,
3825 * the compiler is not obliged to emit any code for calls to it,
3826 * even when marked __noinline. However, gdb depends on those
3829 __compiler_membar();
3833 * A function called after init routines have completed. This can be used to
3834 * break before a program's entry routine is called, and can be used when
3835 * main is not available in the symbol table.
3838 _r_debug_postinit(struct link_map *m)
3841 /* See r_debug_state(). */
3842 __compiler_membar();
3846 release_object(Obj_Entry *obj)
3849 if (obj->holdcount > 0) {
3850 obj->unholdfree = true;
3853 munmap(obj->mapbase, obj->mapsize);
3854 linkmap_delete(obj);
3859 * Get address of the pointer variable in the main program.
3860 * Prefer non-weak symbol over the weak one.
3862 static const void **
3863 get_program_var_addr(const char *name, RtldLockState *lockstate)
3868 symlook_init(&req, name);
3869 req.lockstate = lockstate;
3870 donelist_init(&donelist);
3871 if (symlook_global(&req, &donelist) != 0)
3873 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
3874 return ((const void **)make_function_pointer(req.sym_out,
3876 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
3877 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
3879 return ((const void **)(req.defobj_out->relocbase +
3880 req.sym_out->st_value));
3884 * Set a pointer variable in the main program to the given value. This
3885 * is used to set key variables such as "environ" before any of the
3886 * init functions are called.
3889 set_program_var(const char *name, const void *value)
3893 if ((addr = get_program_var_addr(name, NULL)) != NULL) {
3894 dbg("\"%s\": *%p <-- %p", name, addr, value);
3900 * Search the global objects, including dependencies and main object,
3901 * for the given symbol.
3904 symlook_global(SymLook *req, DoneList *donelist)
3907 const Objlist_Entry *elm;
3910 symlook_init_from_req(&req1, req);
3912 /* Search all objects loaded at program start up. */
3913 if (req->defobj_out == NULL ||
3914 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3915 res = symlook_list(&req1, &list_main, donelist);
3916 if (res == 0 && (req->defobj_out == NULL ||
3917 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3918 req->sym_out = req1.sym_out;
3919 req->defobj_out = req1.defobj_out;
3920 assert(req->defobj_out != NULL);
3924 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
3925 STAILQ_FOREACH(elm, &list_global, link) {
3926 if (req->defobj_out != NULL &&
3927 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3929 res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
3930 if (res == 0 && (req->defobj_out == NULL ||
3931 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3932 req->sym_out = req1.sym_out;
3933 req->defobj_out = req1.defobj_out;
3934 assert(req->defobj_out != NULL);
3938 return (req->sym_out != NULL ? 0 : ESRCH);
3942 * Given a symbol name in a referencing object, find the corresponding
3943 * definition of the symbol. Returns a pointer to the symbol, or NULL if
3944 * no definition was found. Returns a pointer to the Obj_Entry of the
3945 * defining object via the reference parameter DEFOBJ_OUT.
3948 symlook_default(SymLook *req, const Obj_Entry *refobj)
3951 const Objlist_Entry *elm;
3955 donelist_init(&donelist);
3956 symlook_init_from_req(&req1, req);
3959 * Look first in the referencing object if linked symbolically,
3960 * and similarly handle protected symbols.
3962 res = symlook_obj(&req1, refobj);
3963 if (res == 0 && (refobj->symbolic ||
3964 ELF_ST_VISIBILITY(req1.sym_out->st_other) == STV_PROTECTED)) {
3965 req->sym_out = req1.sym_out;
3966 req->defobj_out = req1.defobj_out;
3967 assert(req->defobj_out != NULL);
3969 if (refobj->symbolic || req->defobj_out != NULL)
3970 donelist_check(&donelist, refobj);
3972 symlook_global(req, &donelist);
3974 /* Search all dlopened DAGs containing the referencing object. */
3975 STAILQ_FOREACH(elm, &refobj->dldags, link) {
3976 if (req->sym_out != NULL &&
3977 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3979 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
3980 if (res == 0 && (req->sym_out == NULL ||
3981 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3982 req->sym_out = req1.sym_out;
3983 req->defobj_out = req1.defobj_out;
3984 assert(req->defobj_out != NULL);
3989 * Search the dynamic linker itself, and possibly resolve the
3990 * symbol from there. This is how the application links to
3991 * dynamic linker services such as dlopen.
3993 if (req->sym_out == NULL ||
3994 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3995 res = symlook_obj(&req1, &obj_rtld);
3997 req->sym_out = req1.sym_out;
3998 req->defobj_out = req1.defobj_out;
3999 assert(req->defobj_out != NULL);
4003 return (req->sym_out != NULL ? 0 : ESRCH);
4007 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
4010 const Obj_Entry *defobj;
4011 const Objlist_Entry *elm;
4017 STAILQ_FOREACH(elm, objlist, link) {
4018 if (donelist_check(dlp, elm->obj))
4020 symlook_init_from_req(&req1, req);
4021 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
4022 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
4024 defobj = req1.defobj_out;
4025 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
4032 req->defobj_out = defobj;
4039 * Search the chain of DAGS cointed to by the given Needed_Entry
4040 * for a symbol of the given name. Each DAG is scanned completely
4041 * before advancing to the next one. Returns a pointer to the symbol,
4042 * or NULL if no definition was found.
4045 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
4048 const Needed_Entry *n;
4049 const Obj_Entry *defobj;
4055 symlook_init_from_req(&req1, req);
4056 for (n = needed; n != NULL; n = n->next) {
4057 if (n->obj == NULL ||
4058 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
4060 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
4062 defobj = req1.defobj_out;
4063 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
4069 req->defobj_out = defobj;
4076 * Search the symbol table of a single shared object for a symbol of
4077 * the given name and version, if requested. Returns a pointer to the
4078 * symbol, or NULL if no definition was found. If the object is
4079 * filter, return filtered symbol from filtee.
4081 * The symbol's hash value is passed in for efficiency reasons; that
4082 * eliminates many recomputations of the hash value.
4085 symlook_obj(SymLook *req, const Obj_Entry *obj)
4089 int flags, res, mres;
4092 * If there is at least one valid hash at this point, we prefer to
4093 * use the faster GNU version if available.
4095 if (obj->valid_hash_gnu)
4096 mres = symlook_obj1_gnu(req, obj);
4097 else if (obj->valid_hash_sysv)
4098 mres = symlook_obj1_sysv(req, obj);
4103 if (obj->needed_filtees != NULL) {
4104 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4105 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4106 donelist_init(&donelist);
4107 symlook_init_from_req(&req1, req);
4108 res = symlook_needed(&req1, obj->needed_filtees, &donelist);
4110 req->sym_out = req1.sym_out;
4111 req->defobj_out = req1.defobj_out;
4115 if (obj->needed_aux_filtees != NULL) {
4116 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4117 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4118 donelist_init(&donelist);
4119 symlook_init_from_req(&req1, req);
4120 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
4122 req->sym_out = req1.sym_out;
4123 req->defobj_out = req1.defobj_out;
4131 /* Symbol match routine common to both hash functions */
4133 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result,
4134 const unsigned long symnum)
4137 const Elf_Sym *symp;
4140 symp = obj->symtab + symnum;
4141 strp = obj->strtab + symp->st_name;
4143 switch (ELF_ST_TYPE(symp->st_info)) {
4149 if (symp->st_value == 0)
4153 if (symp->st_shndx != SHN_UNDEF)
4156 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
4157 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
4164 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
4167 if (req->ventry == NULL) {
4168 if (obj->versyms != NULL) {
4169 verndx = VER_NDX(obj->versyms[symnum]);
4170 if (verndx > obj->vernum) {
4172 "%s: symbol %s references wrong version %d",
4173 obj->path, obj->strtab + symnum, verndx);
4177 * If we are not called from dlsym (i.e. this
4178 * is a normal relocation from unversioned
4179 * binary), accept the symbol immediately if
4180 * it happens to have first version after this
4181 * shared object became versioned. Otherwise,
4182 * if symbol is versioned and not hidden,
4183 * remember it. If it is the only symbol with
4184 * this name exported by the shared object, it
4185 * will be returned as a match by the calling
4186 * function. If symbol is global (verndx < 2)
4187 * accept it unconditionally.
4189 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
4190 verndx == VER_NDX_GIVEN) {
4191 result->sym_out = symp;
4194 else if (verndx >= VER_NDX_GIVEN) {
4195 if ((obj->versyms[symnum] & VER_NDX_HIDDEN)
4197 if (result->vsymp == NULL)
4198 result->vsymp = symp;
4204 result->sym_out = symp;
4207 if (obj->versyms == NULL) {
4208 if (object_match_name(obj, req->ventry->name)) {
4209 _rtld_error("%s: object %s should provide version %s "
4210 "for symbol %s", obj_rtld.path, obj->path,
4211 req->ventry->name, obj->strtab + symnum);
4215 verndx = VER_NDX(obj->versyms[symnum]);
4216 if (verndx > obj->vernum) {
4217 _rtld_error("%s: symbol %s references wrong version %d",
4218 obj->path, obj->strtab + symnum, verndx);
4221 if (obj->vertab[verndx].hash != req->ventry->hash ||
4222 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
4224 * Version does not match. Look if this is a
4225 * global symbol and if it is not hidden. If
4226 * global symbol (verndx < 2) is available,
4227 * use it. Do not return symbol if we are
4228 * called by dlvsym, because dlvsym looks for
4229 * a specific version and default one is not
4230 * what dlvsym wants.
4232 if ((req->flags & SYMLOOK_DLSYM) ||
4233 (verndx >= VER_NDX_GIVEN) ||
4234 (obj->versyms[symnum] & VER_NDX_HIDDEN))
4238 result->sym_out = symp;
4243 * Search for symbol using SysV hash function.
4244 * obj->buckets is known not to be NULL at this point; the test for this was
4245 * performed with the obj->valid_hash_sysv assignment.
4248 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj)
4250 unsigned long symnum;
4251 Sym_Match_Result matchres;
4253 matchres.sym_out = NULL;
4254 matchres.vsymp = NULL;
4255 matchres.vcount = 0;
4257 for (symnum = obj->buckets[req->hash % obj->nbuckets];
4258 symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
4259 if (symnum >= obj->nchains)
4260 return (ESRCH); /* Bad object */
4262 if (matched_symbol(req, obj, &matchres, symnum)) {
4263 req->sym_out = matchres.sym_out;
4264 req->defobj_out = obj;
4268 if (matchres.vcount == 1) {
4269 req->sym_out = matchres.vsymp;
4270 req->defobj_out = obj;
4276 /* Search for symbol using GNU hash function */
4278 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj)
4280 Elf_Addr bloom_word;
4281 const Elf32_Word *hashval;
4283 Sym_Match_Result matchres;
4284 unsigned int h1, h2;
4285 unsigned long symnum;
4287 matchres.sym_out = NULL;
4288 matchres.vsymp = NULL;
4289 matchres.vcount = 0;
4291 /* Pick right bitmask word from Bloom filter array */
4292 bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) &
4293 obj->maskwords_bm_gnu];
4295 /* Calculate modulus word size of gnu hash and its derivative */
4296 h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1);
4297 h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1));
4299 /* Filter out the "definitely not in set" queries */
4300 if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0)
4303 /* Locate hash chain and corresponding value element*/
4304 bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu];
4307 hashval = &obj->chain_zero_gnu[bucket];
4309 if (((*hashval ^ req->hash_gnu) >> 1) == 0) {
4310 symnum = hashval - obj->chain_zero_gnu;
4311 if (matched_symbol(req, obj, &matchres, symnum)) {
4312 req->sym_out = matchres.sym_out;
4313 req->defobj_out = obj;
4317 } while ((*hashval++ & 1) == 0);
4318 if (matchres.vcount == 1) {
4319 req->sym_out = matchres.vsymp;
4320 req->defobj_out = obj;
4327 trace_loaded_objects(Obj_Entry *obj)
4329 char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
4332 if ((main_local = getenv(_LD("TRACE_LOADED_OBJECTS_PROGNAME"))) == NULL)
4335 if ((fmt1 = getenv(_LD("TRACE_LOADED_OBJECTS_FMT1"))) == NULL)
4336 fmt1 = "\t%o => %p (%x)\n";
4338 if ((fmt2 = getenv(_LD("TRACE_LOADED_OBJECTS_FMT2"))) == NULL)
4339 fmt2 = "\t%o (%x)\n";
4341 list_containers = getenv(_LD("TRACE_LOADED_OBJECTS_ALL"));
4343 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
4344 Needed_Entry *needed;
4350 if (list_containers && obj->needed != NULL)
4351 rtld_printf("%s:\n", obj->path);
4352 for (needed = obj->needed; needed; needed = needed->next) {
4353 if (needed->obj != NULL) {
4354 if (needed->obj->traced && !list_containers)
4356 needed->obj->traced = true;
4357 path = needed->obj->path;
4361 name = (char *)obj->strtab + needed->name;
4362 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
4364 fmt = is_lib ? fmt1 : fmt2;
4365 while ((c = *fmt++) != '\0') {
4391 rtld_putstr(main_local);
4394 rtld_putstr(obj_main->path);
4401 rtld_printf("%d", sodp->sod_major);
4404 rtld_printf("%d", sodp->sod_minor);
4411 rtld_printf("%p", needed->obj ? needed->obj->mapbase :
4424 * Unload a dlopened object and its dependencies from memory and from
4425 * our data structures. It is assumed that the DAG rooted in the
4426 * object has already been unreferenced, and that the object has a
4427 * reference count of 0.
4430 unload_object(Obj_Entry *root, RtldLockState *lockstate)
4432 Obj_Entry marker, *obj, *next;
4434 assert(root->refcount == 0);
4437 * Pass over the DAG removing unreferenced objects from
4438 * appropriate lists.
4440 unlink_object(root);
4442 /* Unmap all objects that are no longer referenced. */
4443 for (obj = TAILQ_FIRST(&obj_list); obj != NULL; obj = next) {
4444 next = TAILQ_NEXT(obj, next);
4445 if (obj->marker || obj->refcount != 0)
4447 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase,
4448 obj->mapsize, 0, obj->path);
4449 dbg("unloading \"%s\"", obj->path);
4451 * Unlink the object now to prevent new references from
4452 * being acquired while the bind lock is dropped in
4453 * recursive dlclose() invocations.
4455 TAILQ_REMOVE(&obj_list, obj, next);
4458 if (obj->filtees_loaded) {
4460 init_marker(&marker);
4461 TAILQ_INSERT_BEFORE(next, &marker, next);
4462 unload_filtees(obj, lockstate);
4463 next = TAILQ_NEXT(&marker, next);
4464 TAILQ_REMOVE(&obj_list, &marker, next);
4466 unload_filtees(obj, lockstate);
4468 release_object(obj);
4473 unlink_object(Obj_Entry *root)
4477 if (root->refcount == 0) {
4478 /* Remove the object from the RTLD_GLOBAL list. */
4479 objlist_remove(&list_global, root);
4481 /* Remove the object from all objects' DAG lists. */
4482 STAILQ_FOREACH(elm, &root->dagmembers, link) {
4483 objlist_remove(&elm->obj->dldags, root);
4484 if (elm->obj != root)
4485 unlink_object(elm->obj);
4491 ref_dag(Obj_Entry *root)
4495 assert(root->dag_inited);
4496 STAILQ_FOREACH(elm, &root->dagmembers, link)
4497 elm->obj->refcount++;
4501 unref_dag(Obj_Entry *root)
4505 assert(root->dag_inited);
4506 STAILQ_FOREACH(elm, &root->dagmembers, link)
4507 elm->obj->refcount--;
4511 * Common code for MD __tls_get_addr().
4513 static void *tls_get_addr_slow(Elf_Addr **, int, size_t) __noinline;
4515 tls_get_addr_slow(Elf_Addr **dtvp, int index, size_t offset)
4517 Elf_Addr *newdtv, *dtv;
4518 RtldLockState lockstate;
4522 /* Check dtv generation in case new modules have arrived */
4523 if (dtv[0] != tls_dtv_generation) {
4524 wlock_acquire(rtld_bind_lock, &lockstate);
4525 newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4527 if (to_copy > tls_max_index)
4528 to_copy = tls_max_index;
4529 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
4530 newdtv[0] = tls_dtv_generation;
4531 newdtv[1] = tls_max_index;
4533 lock_release(rtld_bind_lock, &lockstate);
4534 dtv = *dtvp = newdtv;
4537 /* Dynamically allocate module TLS if necessary */
4538 if (dtv[index + 1] == 0) {
4539 /* Signal safe, wlock will block out signals. */
4540 wlock_acquire(rtld_bind_lock, &lockstate);
4541 if (!dtv[index + 1])
4542 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
4543 lock_release(rtld_bind_lock, &lockstate);
4545 return ((void *)(dtv[index + 1] + offset));
4549 tls_get_addr_common(Elf_Addr **dtvp, int index, size_t offset)
4554 /* Check dtv generation in case new modules have arrived */
4555 if (__predict_true(dtv[0] == tls_dtv_generation &&
4556 dtv[index + 1] != 0))
4557 return ((void *)(dtv[index + 1] + offset));
4558 return (tls_get_addr_slow(dtvp, index, offset));
4561 #if defined(__aarch64__) || defined(__arm__) || defined(__mips__) || \
4562 defined(__powerpc__) || defined(__riscv__)
4565 * Allocate Static TLS using the Variant I method.
4568 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
4577 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
4580 assert(tcbsize >= TLS_TCB_SIZE);
4581 tcb = xcalloc(1, tls_static_space - TLS_TCB_SIZE + tcbsize);
4582 tls = (Elf_Addr **)(tcb + tcbsize - TLS_TCB_SIZE);
4584 if (oldtcb != NULL) {
4585 memcpy(tls, oldtcb, tls_static_space);
4588 /* Adjust the DTV. */
4590 for (i = 0; i < dtv[1]; i++) {
4591 if (dtv[i+2] >= (Elf_Addr)oldtcb &&
4592 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
4593 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tls;
4597 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4599 dtv[0] = tls_dtv_generation;
4600 dtv[1] = tls_max_index;
4602 for (obj = globallist_curr(objs); obj != NULL;
4603 obj = globallist_next(obj)) {
4604 if (obj->tlsoffset > 0) {
4605 addr = (Elf_Addr)tls + obj->tlsoffset;
4606 if (obj->tlsinitsize > 0)
4607 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4608 if (obj->tlssize > obj->tlsinitsize)
4609 memset((void*) (addr + obj->tlsinitsize), 0,
4610 obj->tlssize - obj->tlsinitsize);
4611 dtv[obj->tlsindex + 1] = addr;
4620 free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
4623 Elf_Addr tlsstart, tlsend;
4626 assert(tcbsize >= TLS_TCB_SIZE);
4628 tlsstart = (Elf_Addr)tcb + tcbsize - TLS_TCB_SIZE;
4629 tlsend = tlsstart + tls_static_space;
4631 dtv = *(Elf_Addr **)tlsstart;
4633 for (i = 0; i < dtvsize; i++) {
4634 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
4635 free((void*)dtv[i+2]);
4644 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__)
4647 * Allocate Static TLS using the Variant II method.
4650 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
4653 size_t size, ralign;
4655 Elf_Addr *dtv, *olddtv;
4656 Elf_Addr segbase, oldsegbase, addr;
4660 if (tls_static_max_align > ralign)
4661 ralign = tls_static_max_align;
4662 size = round(tls_static_space, ralign) + round(tcbsize, ralign);
4664 assert(tcbsize >= 2*sizeof(Elf_Addr));
4665 tls = malloc_aligned(size, ralign);
4666 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4668 segbase = (Elf_Addr)(tls + round(tls_static_space, ralign));
4669 ((Elf_Addr*)segbase)[0] = segbase;
4670 ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
4672 dtv[0] = tls_dtv_generation;
4673 dtv[1] = tls_max_index;
4677 * Copy the static TLS block over whole.
4679 oldsegbase = (Elf_Addr) oldtls;
4680 memcpy((void *)(segbase - tls_static_space),
4681 (const void *)(oldsegbase - tls_static_space),
4685 * If any dynamic TLS blocks have been created tls_get_addr(),
4688 olddtv = ((Elf_Addr**)oldsegbase)[1];
4689 for (i = 0; i < olddtv[1]; i++) {
4690 if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
4691 dtv[i+2] = olddtv[i+2];
4697 * We assume that this block was the one we created with
4698 * allocate_initial_tls().
4700 free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
4702 for (obj = objs; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
4703 if (obj->marker || obj->tlsoffset == 0)
4705 addr = segbase - obj->tlsoffset;
4706 memset((void*) (addr + obj->tlsinitsize),
4707 0, obj->tlssize - obj->tlsinitsize);
4709 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4710 dtv[obj->tlsindex + 1] = addr;
4714 return (void*) segbase;
4718 free_tls(void *tls, size_t tcbsize, size_t tcbalign)
4721 size_t size, ralign;
4723 Elf_Addr tlsstart, tlsend;
4726 * Figure out the size of the initial TLS block so that we can
4727 * find stuff which ___tls_get_addr() allocated dynamically.
4730 if (tls_static_max_align > ralign)
4731 ralign = tls_static_max_align;
4732 size = round(tls_static_space, ralign);
4734 dtv = ((Elf_Addr**)tls)[1];
4736 tlsend = (Elf_Addr) tls;
4737 tlsstart = tlsend - size;
4738 for (i = 0; i < dtvsize; i++) {
4739 if (dtv[i + 2] != 0 && (dtv[i + 2] < tlsstart || dtv[i + 2] > tlsend)) {
4740 free_aligned((void *)dtv[i + 2]);
4744 free_aligned((void *)tlsstart);
4751 * Allocate TLS block for module with given index.
4754 allocate_module_tls(int index)
4759 TAILQ_FOREACH(obj, &obj_list, next) {
4762 if (obj->tlsindex == index)
4766 _rtld_error("Can't find module with TLS index %d", index);
4770 p = malloc_aligned(obj->tlssize, obj->tlsalign);
4771 memcpy(p, obj->tlsinit, obj->tlsinitsize);
4772 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
4778 allocate_tls_offset(Obj_Entry *obj)
4785 if (obj->tlssize == 0) {
4786 obj->tls_done = true;
4790 if (tls_last_offset == 0)
4791 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
4793 off = calculate_tls_offset(tls_last_offset, tls_last_size,
4794 obj->tlssize, obj->tlsalign);
4797 * If we have already fixed the size of the static TLS block, we
4798 * must stay within that size. When allocating the static TLS, we
4799 * leave a small amount of space spare to be used for dynamically
4800 * loading modules which use static TLS.
4802 if (tls_static_space != 0) {
4803 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
4805 } else if (obj->tlsalign > tls_static_max_align) {
4806 tls_static_max_align = obj->tlsalign;
4809 tls_last_offset = obj->tlsoffset = off;
4810 tls_last_size = obj->tlssize;
4811 obj->tls_done = true;
4817 free_tls_offset(Obj_Entry *obj)
4821 * If we were the last thing to allocate out of the static TLS
4822 * block, we give our space back to the 'allocator'. This is a
4823 * simplistic workaround to allow libGL.so.1 to be loaded and
4824 * unloaded multiple times.
4826 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
4827 == calculate_tls_end(tls_last_offset, tls_last_size)) {
4828 tls_last_offset -= obj->tlssize;
4834 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
4837 RtldLockState lockstate;
4839 wlock_acquire(rtld_bind_lock, &lockstate);
4840 ret = allocate_tls(globallist_curr(TAILQ_FIRST(&obj_list)), oldtls,
4842 lock_release(rtld_bind_lock, &lockstate);
4847 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
4849 RtldLockState lockstate;
4851 wlock_acquire(rtld_bind_lock, &lockstate);
4852 free_tls(tcb, tcbsize, tcbalign);
4853 lock_release(rtld_bind_lock, &lockstate);
4857 object_add_name(Obj_Entry *obj, const char *name)
4863 entry = malloc(sizeof(Name_Entry) + len);
4865 if (entry != NULL) {
4866 strcpy(entry->name, name);
4867 STAILQ_INSERT_TAIL(&obj->names, entry, link);
4872 object_match_name(const Obj_Entry *obj, const char *name)
4876 STAILQ_FOREACH(entry, &obj->names, link) {
4877 if (strcmp(name, entry->name) == 0)
4884 locate_dependency(const Obj_Entry *obj, const char *name)
4886 const Objlist_Entry *entry;
4887 const Needed_Entry *needed;
4889 STAILQ_FOREACH(entry, &list_main, link) {
4890 if (object_match_name(entry->obj, name))
4894 for (needed = obj->needed; needed != NULL; needed = needed->next) {
4895 if (strcmp(obj->strtab + needed->name, name) == 0 ||
4896 (needed->obj != NULL && object_match_name(needed->obj, name))) {
4898 * If there is DT_NEEDED for the name we are looking for,
4899 * we are all set. Note that object might not be found if
4900 * dependency was not loaded yet, so the function can
4901 * return NULL here. This is expected and handled
4902 * properly by the caller.
4904 return (needed->obj);
4907 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
4913 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
4914 const Elf_Vernaux *vna)
4916 const Elf_Verdef *vd;
4917 const char *vername;
4919 vername = refobj->strtab + vna->vna_name;
4920 vd = depobj->verdef;
4922 _rtld_error("%s: version %s required by %s not defined",
4923 depobj->path, vername, refobj->path);
4927 if (vd->vd_version != VER_DEF_CURRENT) {
4928 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
4929 depobj->path, vd->vd_version);
4932 if (vna->vna_hash == vd->vd_hash) {
4933 const Elf_Verdaux *aux = (const Elf_Verdaux *)
4934 ((char *)vd + vd->vd_aux);
4935 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
4938 if (vd->vd_next == 0)
4940 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4942 if (vna->vna_flags & VER_FLG_WEAK)
4944 _rtld_error("%s: version %s required by %s not found",
4945 depobj->path, vername, refobj->path);
4950 rtld_verify_object_versions(Obj_Entry *obj)
4952 const Elf_Verneed *vn;
4953 const Elf_Verdef *vd;
4954 const Elf_Verdaux *vda;
4955 const Elf_Vernaux *vna;
4956 const Obj_Entry *depobj;
4957 int maxvernum, vernum;
4959 if (obj->ver_checked)
4961 obj->ver_checked = true;
4965 * Walk over defined and required version records and figure out
4966 * max index used by any of them. Do very basic sanity checking
4970 while (vn != NULL) {
4971 if (vn->vn_version != VER_NEED_CURRENT) {
4972 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
4973 obj->path, vn->vn_version);
4976 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4978 vernum = VER_NEED_IDX(vna->vna_other);
4979 if (vernum > maxvernum)
4981 if (vna->vna_next == 0)
4983 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4985 if (vn->vn_next == 0)
4987 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4991 while (vd != NULL) {
4992 if (vd->vd_version != VER_DEF_CURRENT) {
4993 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
4994 obj->path, vd->vd_version);
4997 vernum = VER_DEF_IDX(vd->vd_ndx);
4998 if (vernum > maxvernum)
5000 if (vd->vd_next == 0)
5002 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
5009 * Store version information in array indexable by version index.
5010 * Verify that object version requirements are satisfied along the
5013 obj->vernum = maxvernum + 1;
5014 obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry));
5017 while (vd != NULL) {
5018 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
5019 vernum = VER_DEF_IDX(vd->vd_ndx);
5020 assert(vernum <= maxvernum);
5021 vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
5022 obj->vertab[vernum].hash = vd->vd_hash;
5023 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
5024 obj->vertab[vernum].file = NULL;
5025 obj->vertab[vernum].flags = 0;
5027 if (vd->vd_next == 0)
5029 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
5033 while (vn != NULL) {
5034 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
5037 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
5039 if (check_object_provided_version(obj, depobj, vna))
5041 vernum = VER_NEED_IDX(vna->vna_other);
5042 assert(vernum <= maxvernum);
5043 obj->vertab[vernum].hash = vna->vna_hash;
5044 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
5045 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
5046 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
5047 VER_INFO_HIDDEN : 0;
5048 if (vna->vna_next == 0)
5050 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
5052 if (vn->vn_next == 0)
5054 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
5060 rtld_verify_versions(const Objlist *objlist)
5062 Objlist_Entry *entry;
5066 STAILQ_FOREACH(entry, objlist, link) {
5068 * Skip dummy objects or objects that have their version requirements
5071 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
5073 if (rtld_verify_object_versions(entry->obj) == -1) {
5075 if (ld_tracing == NULL)
5079 if (rc == 0 || ld_tracing != NULL)
5080 rc = rtld_verify_object_versions(&obj_rtld);
5085 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
5090 vernum = VER_NDX(obj->versyms[symnum]);
5091 if (vernum >= obj->vernum) {
5092 _rtld_error("%s: symbol %s has wrong verneed value %d",
5093 obj->path, obj->strtab + symnum, vernum);
5094 } else if (obj->vertab[vernum].hash != 0) {
5095 return &obj->vertab[vernum];
5102 _rtld_get_stack_prot(void)
5105 return (stack_prot);
5109 _rtld_is_dlopened(void *arg)
5112 RtldLockState lockstate;
5115 rlock_acquire(rtld_bind_lock, &lockstate);
5118 obj = obj_from_addr(arg);
5120 _rtld_error("No shared object contains address");
5121 lock_release(rtld_bind_lock, &lockstate);
5124 res = obj->dlopened ? 1 : 0;
5125 lock_release(rtld_bind_lock, &lockstate);
5130 obj_enforce_relro(Obj_Entry *obj)
5133 if (obj->relro_size > 0 && mprotect(obj->relro_page, obj->relro_size,
5135 _rtld_error("%s: Cannot enforce relro protection: %s",
5136 obj->path, rtld_strerror(errno));
5143 map_stacks_exec(RtldLockState *lockstate)
5145 void (*thr_map_stacks_exec)(void);
5147 if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
5149 thr_map_stacks_exec = (void (*)(void))(uintptr_t)
5150 get_program_var_addr("__pthread_map_stacks_exec", lockstate);
5151 if (thr_map_stacks_exec != NULL) {
5152 stack_prot |= PROT_EXEC;
5153 thr_map_stacks_exec();
5158 symlook_init(SymLook *dst, const char *name)
5161 bzero(dst, sizeof(*dst));
5163 dst->hash = elf_hash(name);
5164 dst->hash_gnu = gnu_hash(name);
5168 symlook_init_from_req(SymLook *dst, const SymLook *src)
5171 dst->name = src->name;
5172 dst->hash = src->hash;
5173 dst->hash_gnu = src->hash_gnu;
5174 dst->ventry = src->ventry;
5175 dst->flags = src->flags;
5176 dst->defobj_out = NULL;
5177 dst->sym_out = NULL;
5178 dst->lockstate = src->lockstate;
5183 * Parse a file descriptor number without pulling in more of libc (e.g. atoi).
5186 parse_libdir(const char *str)
5188 static const int RADIX = 10; /* XXXJA: possibly support hex? */
5195 for (c = *str; c != '\0'; c = *++str) {
5196 if (c < '0' || c > '9')
5203 /* Make sure we actually parsed something. */
5205 _rtld_error("failed to parse directory FD from '%s'", str);
5212 * Overrides for libc_pic-provided functions.
5216 __getosreldate(void)
5226 oid[1] = KERN_OSRELDATE;
5228 len = sizeof(osrel);
5229 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
5230 if (error == 0 && osrel > 0 && len == sizeof(osrel))
5242 void (*__cleanup)(void);
5243 int __isthreaded = 0;
5244 int _thread_autoinit_dummy_decl = 1;
5247 * No unresolved symbols for rtld.
5250 __pthread_cxa_finalize(struct dl_phdr_info *a)
5255 __stack_chk_fail(void)
5258 _rtld_error("stack overflow detected; terminated");
5261 __weak_reference(__stack_chk_fail, __stack_chk_fail_local);
5267 _rtld_error("buffer overflow detected; terminated");
5272 rtld_strerror(int errnum)
5275 if (errnum < 0 || errnum >= sys_nerr)
5276 return ("Unknown error");
5277 return (sys_errlist[errnum]);