2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright 1996, 1997, 1998, 1999, 2000 John D. Polstra.
5 * Copyright 2003 Alexander Kabaev <kan@FreeBSD.ORG>.
6 * Copyright 2009-2013 Konstantin Belousov <kib@FreeBSD.ORG>.
7 * Copyright 2012 John Marino <draco@marino.st>.
8 * Copyright 2014-2017 The FreeBSD Foundation
11 * Portions of this software were developed by Konstantin Belousov
12 * under sponsorship from the FreeBSD Foundation.
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
17 * 1. Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 * Dynamic linker for ELF.
38 * John Polstra <jdp@polstra.com>.
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
44 #include <sys/param.h>
45 #include <sys/mount.h>
48 #include <sys/sysctl.h>
50 #include <sys/utsname.h>
51 #include <sys/ktrace.h>
68 #include "rtld_printf.h"
69 #include "rtld_utrace.h"
73 typedef void (*func_ptr_type)();
74 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg);
77 * Function declarations.
79 static const char *basename(const char *);
80 static void digest_dynamic1(Obj_Entry *, int, const Elf_Dyn **,
81 const Elf_Dyn **, const Elf_Dyn **);
82 static void digest_dynamic2(Obj_Entry *, const Elf_Dyn *, const Elf_Dyn *,
84 static void digest_dynamic(Obj_Entry *, int);
85 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
86 static Obj_Entry *dlcheck(void *);
87 static int dlclose_locked(void *, RtldLockState *);
88 static Obj_Entry *dlopen_object(const char *name, int fd, Obj_Entry *refobj,
89 int lo_flags, int mode, RtldLockState *lockstate);
90 static Obj_Entry *do_load_object(int, const char *, char *, struct stat *, int);
91 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
92 static bool donelist_check(DoneList *, const Obj_Entry *);
93 static void errmsg_restore(char *);
94 static char *errmsg_save(void);
95 static void *fill_search_info(const char *, size_t, void *);
96 static char *find_library(const char *, const Obj_Entry *, int *);
97 static const char *gethints(bool);
98 static void hold_object(Obj_Entry *);
99 static void unhold_object(Obj_Entry *);
100 static void init_dag(Obj_Entry *);
101 static void init_marker(Obj_Entry *);
102 static void init_pagesizes(Elf_Auxinfo **aux_info);
103 static void init_rtld(caddr_t, Elf_Auxinfo **);
104 static void initlist_add_neededs(Needed_Entry *, Objlist *);
105 static void initlist_add_objects(Obj_Entry *, Obj_Entry *, Objlist *);
106 static int initlist_objects_ifunc(Objlist *, bool, int, RtldLockState *);
107 static void linkmap_add(Obj_Entry *);
108 static void linkmap_delete(Obj_Entry *);
109 static void load_filtees(Obj_Entry *, int flags, RtldLockState *);
110 static void unload_filtees(Obj_Entry *, RtldLockState *);
111 static int load_needed_objects(Obj_Entry *, int);
112 static int load_preload_objects(void);
113 static Obj_Entry *load_object(const char *, int fd, const Obj_Entry *, int);
114 static void map_stacks_exec(RtldLockState *);
115 static int obj_disable_relro(Obj_Entry *);
116 static int obj_enforce_relro(Obj_Entry *);
117 static Obj_Entry *obj_from_addr(const void *);
118 static void objlist_call_fini(Objlist *, Obj_Entry *, RtldLockState *);
119 static void objlist_call_init(Objlist *, RtldLockState *);
120 static void objlist_clear(Objlist *);
121 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
122 static void objlist_init(Objlist *);
123 static void objlist_push_head(Objlist *, Obj_Entry *);
124 static void objlist_push_tail(Objlist *, Obj_Entry *);
125 static void objlist_put_after(Objlist *, Obj_Entry *, Obj_Entry *);
126 static void objlist_remove(Objlist *, Obj_Entry *);
127 static int open_binary_fd(const char *argv0, bool search_in_path);
128 static int parse_args(char* argv[], int argc, bool *use_pathp, int *fdp);
129 static int parse_integer(const char *);
130 static void *path_enumerate(const char *, path_enum_proc, const char *, void *);
131 static void print_usage(const char *argv0);
132 static void release_object(Obj_Entry *);
133 static int relocate_object_dag(Obj_Entry *root, bool bind_now,
134 Obj_Entry *rtldobj, int flags, RtldLockState *lockstate);
135 static int relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
136 int flags, RtldLockState *lockstate);
137 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, int,
139 static int resolve_object_ifunc(Obj_Entry *, bool, int, RtldLockState *);
140 static int rtld_dirname(const char *, char *);
141 static int rtld_dirname_abs(const char *, char *);
142 static void *rtld_dlopen(const char *name, int fd, int mode);
143 static void rtld_exit(void);
144 static char *search_library_path(const char *, const char *, const char *,
146 static char *search_library_pathfds(const char *, const char *, int *);
147 static const void **get_program_var_addr(const char *, RtldLockState *);
148 static void set_program_var(const char *, const void *);
149 static int symlook_default(SymLook *, const Obj_Entry *refobj);
150 static int symlook_global(SymLook *, DoneList *);
151 static void symlook_init_from_req(SymLook *, const SymLook *);
152 static int symlook_list(SymLook *, const Objlist *, DoneList *);
153 static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *);
154 static int symlook_obj1_sysv(SymLook *, const Obj_Entry *);
155 static int symlook_obj1_gnu(SymLook *, const Obj_Entry *);
156 static void trace_loaded_objects(Obj_Entry *);
157 static void unlink_object(Obj_Entry *);
158 static void unload_object(Obj_Entry *, RtldLockState *lockstate);
159 static void unref_dag(Obj_Entry *);
160 static void ref_dag(Obj_Entry *);
161 static char *origin_subst_one(Obj_Entry *, char *, const char *,
163 static char *origin_subst(Obj_Entry *, char *);
164 static bool obj_resolve_origin(Obj_Entry *obj);
165 static void preinit_main(void);
166 static int rtld_verify_versions(const Objlist *);
167 static int rtld_verify_object_versions(Obj_Entry *);
168 static void object_add_name(Obj_Entry *, const char *);
169 static int object_match_name(const Obj_Entry *, const char *);
170 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
171 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
172 struct dl_phdr_info *phdr_info);
173 static uint32_t gnu_hash(const char *);
174 static bool matched_symbol(SymLook *, const Obj_Entry *, Sym_Match_Result *,
175 const unsigned long);
177 void r_debug_state(struct r_debug *, struct link_map *) __noinline __exported;
178 void _r_debug_postinit(struct link_map *) __noinline __exported;
180 int __sys_openat(int, const char *, int, ...);
185 static char *error_message; /* Message for dlerror(), or NULL */
186 struct r_debug r_debug __exported; /* for GDB; */
187 static bool libmap_disable; /* Disable libmap */
188 static bool ld_loadfltr; /* Immediate filters processing */
189 static char *libmap_override; /* Maps to use in addition to libmap.conf */
190 static bool trust; /* False for setuid and setgid programs */
191 static bool dangerous_ld_env; /* True if environment variables have been
192 used to affect the libraries loaded */
193 bool ld_bind_not; /* Disable PLT update */
194 static char *ld_bind_now; /* Environment variable for immediate binding */
195 static char *ld_debug; /* Environment variable for debugging */
196 static char *ld_library_path; /* Environment variable for search path */
197 static char *ld_library_dirs; /* Environment variable for library descriptors */
198 static char *ld_preload; /* Environment variable for libraries to
200 static char *ld_elf_hints_path; /* Environment variable for alternative hints path */
201 static char *ld_tracing; /* Called from ldd to print libs */
202 static char *ld_utrace; /* Use utrace() to log events. */
203 static struct obj_entry_q obj_list; /* Queue of all loaded objects */
204 static Obj_Entry *obj_main; /* The main program shared object */
205 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
206 static unsigned int obj_count; /* Number of objects in obj_list */
207 static unsigned int obj_loads; /* Number of loads of objects (gen count) */
209 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
210 STAILQ_HEAD_INITIALIZER(list_global);
211 static Objlist list_main = /* Objects loaded at program startup */
212 STAILQ_HEAD_INITIALIZER(list_main);
213 static Objlist list_fini = /* Objects needing fini() calls */
214 STAILQ_HEAD_INITIALIZER(list_fini);
216 Elf_Sym sym_zero; /* For resolving undefined weak refs. */
218 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
220 extern Elf_Dyn _DYNAMIC;
221 #pragma weak _DYNAMIC
223 int dlclose(void *) __exported;
224 char *dlerror(void) __exported;
225 void *dlopen(const char *, int) __exported;
226 void *fdlopen(int, int) __exported;
227 void *dlsym(void *, const char *) __exported;
228 dlfunc_t dlfunc(void *, const char *) __exported;
229 void *dlvsym(void *, const char *, const char *) __exported;
230 int dladdr(const void *, Dl_info *) __exported;
231 void dllockinit(void *, void *(*)(void *), void (*)(void *), void (*)(void *),
232 void (*)(void *), void (*)(void *), void (*)(void *)) __exported;
233 int dlinfo(void *, int , void *) __exported;
234 int dl_iterate_phdr(__dl_iterate_hdr_callback, void *) __exported;
235 int _rtld_addr_phdr(const void *, struct dl_phdr_info *) __exported;
236 int _rtld_get_stack_prot(void) __exported;
237 int _rtld_is_dlopened(void *) __exported;
238 void _rtld_error(const char *, ...) __exported;
240 int npagesizes, osreldate;
243 static int stack_prot = PROT_READ | PROT_WRITE | RTLD_DEFAULT_STACK_EXEC;
244 static int max_stack_flags;
247 * Global declarations normally provided by crt1. The dynamic linker is
248 * not built with crt1, so we have to provide them ourselves.
254 * Used to pass argc, argv to init functions.
260 * Globals to control TLS allocation.
262 size_t tls_last_offset; /* Static TLS offset of last module */
263 size_t tls_last_size; /* Static TLS size of last module */
264 size_t tls_static_space; /* Static TLS space allocated */
265 size_t tls_static_max_align;
266 int tls_dtv_generation = 1; /* Used to detect when dtv size changes */
267 int tls_max_index = 1; /* Largest module index allocated */
269 bool ld_library_path_rpath = false;
272 * Globals for path names, and such
274 char *ld_elf_hints_default = _PATH_ELF_HINTS;
275 char *ld_path_libmap_conf = _PATH_LIBMAP_CONF;
276 char *ld_path_rtld = _PATH_RTLD;
277 char *ld_standard_library_path = STANDARD_LIBRARY_PATH;
278 char *ld_env_prefix = LD_;
281 * Fill in a DoneList with an allocation large enough to hold all of
282 * the currently-loaded objects. Keep this as a macro since it calls
283 * alloca and we want that to occur within the scope of the caller.
285 #define donelist_init(dlp) \
286 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
287 assert((dlp)->objs != NULL), \
288 (dlp)->num_alloc = obj_count, \
291 #define LD_UTRACE(e, h, mb, ms, r, n) do { \
292 if (ld_utrace != NULL) \
293 ld_utrace_log(e, h, mb, ms, r, n); \
297 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
298 int refcnt, const char *name)
300 struct utrace_rtld ut;
301 static const char rtld_utrace_sig[RTLD_UTRACE_SIG_SZ] = RTLD_UTRACE_SIG;
303 memcpy(ut.sig, rtld_utrace_sig, sizeof(ut.sig));
306 ut.mapbase = mapbase;
307 ut.mapsize = mapsize;
309 bzero(ut.name, sizeof(ut.name));
311 strlcpy(ut.name, name, sizeof(ut.name));
312 utrace(&ut, sizeof(ut));
315 #ifdef RTLD_VARIANT_ENV_NAMES
317 * construct the env variable based on the type of binary that's
320 static inline const char *
323 static char buffer[128];
325 strlcpy(buffer, ld_env_prefix, sizeof(buffer));
326 strlcat(buffer, var, sizeof(buffer));
334 * Main entry point for dynamic linking. The first argument is the
335 * stack pointer. The stack is expected to be laid out as described
336 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
337 * Specifically, the stack pointer points to a word containing
338 * ARGC. Following that in the stack is a null-terminated sequence
339 * of pointers to argument strings. Then comes a null-terminated
340 * sequence of pointers to environment strings. Finally, there is a
341 * sequence of "auxiliary vector" entries.
343 * The second argument points to a place to store the dynamic linker's
344 * exit procedure pointer and the third to a place to store the main
347 * The return value is the main program's entry point.
350 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
352 Elf_Auxinfo *aux, *auxp, *auxpf, *aux_info[AT_COUNT];
353 Objlist_Entry *entry;
354 Obj_Entry *last_interposer, *obj, *preload_tail;
355 const Elf_Phdr *phdr;
357 RtldLockState lockstate;
360 char **argv, *argv0, **env, **envp, *kexecpath, *library_path_rpath;
362 char buf[MAXPATHLEN];
363 int argc, fd, i, phnum, rtld_argc;
364 bool dir_enable, explicit_fd, search_in_path;
367 * On entry, the dynamic linker itself has not been relocated yet.
368 * Be very careful not to reference any global data until after
369 * init_rtld has returned. It is OK to reference file-scope statics
370 * and string constants, and to call static and global functions.
373 /* Find the auxiliary vector on the stack. */
377 sp += argc + 1; /* Skip over arguments and NULL terminator */
379 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
381 aux = (Elf_Auxinfo *) sp;
383 /* Digest the auxiliary vector. */
384 for (i = 0; i < AT_COUNT; i++)
386 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
387 if (auxp->a_type < AT_COUNT)
388 aux_info[auxp->a_type] = auxp;
391 /* Initialize and relocate ourselves. */
392 assert(aux_info[AT_BASE] != NULL);
393 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
395 __progname = obj_rtld.path;
396 argv0 = argv[0] != NULL ? argv[0] : "(null)";
401 trust = !issetugid();
403 md_abi_variant_hook(aux_info);
406 if (aux_info[AT_EXECFD] != NULL) {
407 fd = aux_info[AT_EXECFD]->a_un.a_val;
409 assert(aux_info[AT_PHDR] != NULL);
410 phdr = (const Elf_Phdr *)aux_info[AT_PHDR]->a_un.a_ptr;
411 if (phdr == obj_rtld.phdr) {
413 _rtld_error("Tainted process refusing to run binary %s",
417 dbg("opening main program in direct exec mode");
419 rtld_argc = parse_args(argv, argc, &search_in_path, &fd);
420 argv0 = argv[rtld_argc];
421 explicit_fd = (fd != -1);
423 fd = open_binary_fd(argv0, search_in_path);
424 if (fstat(fd, &st) == -1) {
425 _rtld_error("Failed to fstat FD %d (%s): %s", fd,
426 explicit_fd ? "user-provided descriptor" : argv0,
427 rtld_strerror(errno));
432 * Rough emulation of the permission checks done by
433 * execve(2), only Unix DACs are checked, ACLs are
434 * ignored. Preserve the semantic of disabling owner
435 * to execute if owner x bit is cleared, even if
436 * others x bit is enabled.
437 * mmap(2) does not allow to mmap with PROT_EXEC if
438 * binary' file comes from noexec mount. We cannot
439 * set VV_TEXT on the binary.
442 if (st.st_uid == geteuid()) {
443 if ((st.st_mode & S_IXUSR) != 0)
445 } else if (st.st_gid == getegid()) {
446 if ((st.st_mode & S_IXGRP) != 0)
448 } else if ((st.st_mode & S_IXOTH) != 0) {
452 _rtld_error("No execute permission for binary %s",
458 * For direct exec mode, argv[0] is the interpreter
459 * name, we must remove it and shift arguments left
460 * before invoking binary main. Since stack layout
461 * places environment pointers and aux vectors right
462 * after the terminating NULL, we must shift
463 * environment and aux as well.
465 main_argc = argc - rtld_argc;
466 for (i = 0; i <= main_argc; i++)
467 argv[i] = argv[i + rtld_argc];
469 environ = env = envp = argv + main_argc + 1;
471 *envp = *(envp + rtld_argc);
473 } while (*envp != NULL);
474 aux = auxp = (Elf_Auxinfo *)envp;
475 auxpf = (Elf_Auxinfo *)(envp + rtld_argc);
476 for (;; auxp++, auxpf++) {
478 if (auxp->a_type == AT_NULL)
482 _rtld_error("No binary");
488 ld_bind_now = getenv(_LD("BIND_NOW"));
491 * If the process is tainted, then we un-set the dangerous environment
492 * variables. The process will be marked as tainted until setuid(2)
493 * is called. If any child process calls setuid(2) we do not want any
494 * future processes to honor the potentially un-safe variables.
497 if (unsetenv(_LD("PRELOAD")) || unsetenv(_LD("LIBMAP")) ||
498 unsetenv(_LD("LIBRARY_PATH")) || unsetenv(_LD("LIBRARY_PATH_FDS")) ||
499 unsetenv(_LD("LIBMAP_DISABLE")) || unsetenv(_LD("BIND_NOT")) ||
500 unsetenv(_LD("DEBUG")) || unsetenv(_LD("ELF_HINTS_PATH")) ||
501 unsetenv(_LD("LOADFLTR")) || unsetenv(_LD("LIBRARY_PATH_RPATH"))) {
502 _rtld_error("environment corrupt; aborting");
506 ld_debug = getenv(_LD("DEBUG"));
507 if (ld_bind_now == NULL)
508 ld_bind_not = getenv(_LD("BIND_NOT")) != NULL;
509 libmap_disable = getenv(_LD("LIBMAP_DISABLE")) != NULL;
510 libmap_override = getenv(_LD("LIBMAP"));
511 ld_library_path = getenv(_LD("LIBRARY_PATH"));
512 ld_library_dirs = getenv(_LD("LIBRARY_PATH_FDS"));
513 ld_preload = getenv(_LD("PRELOAD"));
514 ld_elf_hints_path = getenv(_LD("ELF_HINTS_PATH"));
515 ld_loadfltr = getenv(_LD("LOADFLTR")) != NULL;
516 library_path_rpath = getenv(_LD("LIBRARY_PATH_RPATH"));
517 if (library_path_rpath != NULL) {
518 if (library_path_rpath[0] == 'y' ||
519 library_path_rpath[0] == 'Y' ||
520 library_path_rpath[0] == '1')
521 ld_library_path_rpath = true;
523 ld_library_path_rpath = false;
525 dangerous_ld_env = libmap_disable || (libmap_override != NULL) ||
526 (ld_library_path != NULL) || (ld_preload != NULL) ||
527 (ld_elf_hints_path != NULL) || ld_loadfltr;
528 ld_tracing = getenv(_LD("TRACE_LOADED_OBJECTS"));
529 ld_utrace = getenv(_LD("UTRACE"));
531 if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0)
532 ld_elf_hints_path = ld_elf_hints_default;
534 if (ld_debug != NULL && *ld_debug != '\0')
536 dbg("%s is initialized, base address = %p", __progname,
537 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
538 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
539 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
541 dbg("initializing thread locks");
545 * Load the main program, or process its program header if it is
548 if (fd != -1) { /* Load the main program. */
549 dbg("loading main program");
550 obj_main = map_object(fd, argv0, NULL);
552 if (obj_main == NULL)
554 max_stack_flags = obj_main->stack_flags;
555 } else { /* Main program already loaded. */
556 dbg("processing main program's program header");
557 assert(aux_info[AT_PHDR] != NULL);
558 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
559 assert(aux_info[AT_PHNUM] != NULL);
560 phnum = aux_info[AT_PHNUM]->a_un.a_val;
561 assert(aux_info[AT_PHENT] != NULL);
562 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
563 assert(aux_info[AT_ENTRY] != NULL);
564 imgentry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
565 if ((obj_main = digest_phdr(phdr, phnum, imgentry, argv0)) == NULL)
569 if (aux_info[AT_EXECPATH] != NULL && fd == -1) {
570 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
571 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
572 if (kexecpath[0] == '/')
573 obj_main->path = kexecpath;
574 else if (getcwd(buf, sizeof(buf)) == NULL ||
575 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
576 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
577 obj_main->path = xstrdup(argv0);
579 obj_main->path = xstrdup(buf);
581 dbg("No AT_EXECPATH or direct exec");
582 obj_main->path = xstrdup(argv0);
584 dbg("obj_main path %s", obj_main->path);
585 obj_main->mainprog = true;
587 if (aux_info[AT_STACKPROT] != NULL &&
588 aux_info[AT_STACKPROT]->a_un.a_val != 0)
589 stack_prot = aux_info[AT_STACKPROT]->a_un.a_val;
593 * Get the actual dynamic linker pathname from the executable if
594 * possible. (It should always be possible.) That ensures that
595 * gdb will find the right dynamic linker even if a non-standard
598 if (obj_main->interp != NULL &&
599 strcmp(obj_main->interp, obj_rtld.path) != 0) {
601 obj_rtld.path = xstrdup(obj_main->interp);
602 __progname = obj_rtld.path;
606 digest_dynamic(obj_main, 0);
607 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d",
608 obj_main->path, obj_main->valid_hash_sysv, obj_main->valid_hash_gnu,
609 obj_main->dynsymcount);
611 linkmap_add(obj_main);
612 linkmap_add(&obj_rtld);
614 /* Link the main program into the list of objects. */
615 TAILQ_INSERT_HEAD(&obj_list, obj_main, next);
619 /* Initialize a fake symbol for resolving undefined weak references. */
620 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
621 sym_zero.st_shndx = SHN_UNDEF;
622 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
625 libmap_disable = (bool)lm_init(libmap_override);
627 dbg("loading LD_PRELOAD libraries");
628 if (load_preload_objects() == -1)
630 preload_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
632 dbg("loading needed objects");
633 if (load_needed_objects(obj_main, 0) == -1)
636 /* Make a list of all objects loaded at startup. */
637 last_interposer = obj_main;
638 TAILQ_FOREACH(obj, &obj_list, next) {
641 if (obj->z_interpose && obj != obj_main) {
642 objlist_put_after(&list_main, last_interposer, obj);
643 last_interposer = obj;
645 objlist_push_tail(&list_main, obj);
650 dbg("checking for required versions");
651 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
654 if (ld_tracing) { /* We're done */
655 trace_loaded_objects(obj_main);
659 if (getenv(_LD("DUMP_REL_PRE")) != NULL) {
660 dump_relocations(obj_main);
665 * Processing tls relocations requires having the tls offsets
666 * initialized. Prepare offsets before starting initial
667 * relocation processing.
669 dbg("initializing initial thread local storage offsets");
670 STAILQ_FOREACH(entry, &list_main, link) {
672 * Allocate all the initial objects out of the static TLS
673 * block even if they didn't ask for it.
675 allocate_tls_offset(entry->obj);
678 if (relocate_objects(obj_main,
679 ld_bind_now != NULL && *ld_bind_now != '\0',
680 &obj_rtld, SYMLOOK_EARLY, NULL) == -1)
683 dbg("doing copy relocations");
684 if (do_copy_relocations(obj_main) == -1)
687 if (getenv(_LD("DUMP_REL_POST")) != NULL) {
688 dump_relocations(obj_main);
695 * Setup TLS for main thread. This must be done after the
696 * relocations are processed, since tls initialization section
697 * might be the subject for relocations.
699 dbg("initializing initial thread local storage");
700 allocate_initial_tls(globallist_curr(TAILQ_FIRST(&obj_list)));
702 dbg("initializing key program variables");
703 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
704 set_program_var("environ", env);
705 set_program_var("__elf_aux_vector", aux);
707 /* Make a list of init functions to call. */
708 objlist_init(&initlist);
709 initlist_add_objects(globallist_curr(TAILQ_FIRST(&obj_list)),
710 preload_tail, &initlist);
712 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
714 map_stacks_exec(NULL);
716 if (!obj_main->crt_no_init) {
718 * Make sure we don't call the main program's init and fini
719 * functions for binaries linked with old crt1 which calls
722 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
723 obj_main->preinit_array = obj_main->init_array =
724 obj_main->fini_array = (Elf_Addr)NULL;
728 * Execute MD initializers required before we call the objects'
733 wlock_acquire(rtld_bind_lock, &lockstate);
735 dbg("resolving ifuncs");
736 if (initlist_objects_ifunc(&initlist, ld_bind_now != NULL &&
737 *ld_bind_now != '\0', SYMLOOK_EARLY, &lockstate) == -1)
740 if (obj_main->crt_no_init)
742 objlist_call_init(&initlist, &lockstate);
743 _r_debug_postinit(&obj_main->linkmap);
744 objlist_clear(&initlist);
745 dbg("loading filtees");
746 TAILQ_FOREACH(obj, &obj_list, next) {
749 if (ld_loadfltr || obj->z_loadfltr)
750 load_filtees(obj, 0, &lockstate);
753 dbg("enforcing main obj relro");
754 if (obj_enforce_relro(obj_main) == -1)
757 lock_release(rtld_bind_lock, &lockstate);
759 dbg("transferring control to program entry point = %p", obj_main->entry);
761 /* Return the exit procedure and the program entry point. */
762 *exit_proc = rtld_exit;
764 return (func_ptr_type) obj_main->entry;
768 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def)
773 ptr = (void *)make_function_pointer(def, obj);
774 target = call_ifunc_resolver(ptr);
775 return ((void *)target);
779 * NB: MIPS uses a private version of this function (_mips_rtld_bind).
780 * Changes to this function should be applied there as well.
783 _rtld_bind(Obj_Entry *obj, Elf_Size reloff)
787 const Obj_Entry *defobj;
790 RtldLockState lockstate;
792 rlock_acquire(rtld_bind_lock, &lockstate);
793 if (sigsetjmp(lockstate.env, 0) != 0)
794 lock_upgrade(rtld_bind_lock, &lockstate);
796 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
798 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
800 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
801 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, SYMLOOK_IN_PLT,
805 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
806 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
808 target = (Elf_Addr)(defobj->relocbase + def->st_value);
810 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
811 defobj->strtab + def->st_name, basename(obj->path),
812 (void *)target, basename(defobj->path));
815 * Write the new contents for the jmpslot. Note that depending on
816 * architecture, the value which we need to return back to the
817 * lazy binding trampoline may or may not be the target
818 * address. The value returned from reloc_jmpslot() is the value
819 * that the trampoline needs.
821 target = reloc_jmpslot(where, target, defobj, obj, rel);
822 lock_release(rtld_bind_lock, &lockstate);
827 * Error reporting function. Use it like printf. If formats the message
828 * into a buffer, and sets things up so that the next call to dlerror()
829 * will return the message.
832 _rtld_error(const char *fmt, ...)
834 static char buf[512];
838 rtld_vsnprintf(buf, sizeof buf, fmt, ap);
841 LD_UTRACE(UTRACE_RTLD_ERROR, NULL, NULL, 0, 0, error_message);
845 * Return a dynamically-allocated copy of the current error message, if any.
850 return error_message == NULL ? NULL : xstrdup(error_message);
854 * Restore the current error message from a copy which was previously saved
855 * by errmsg_save(). The copy is freed.
858 errmsg_restore(char *saved_msg)
860 if (saved_msg == NULL)
861 error_message = NULL;
863 _rtld_error("%s", saved_msg);
869 basename(const char *name)
871 const char *p = strrchr(name, '/');
872 return p != NULL ? p + 1 : name;
875 static struct utsname uts;
878 origin_subst_one(Obj_Entry *obj, char *real, const char *kw,
879 const char *subst, bool may_free)
881 char *p, *p1, *res, *resp;
882 int subst_len, kw_len, subst_count, old_len, new_len;
887 * First, count the number of the keyword occurrences, to
888 * preallocate the final string.
890 for (p = real, subst_count = 0;; p = p1 + kw_len, subst_count++) {
897 * If the keyword is not found, just return.
899 * Return non-substituted string if resolution failed. We
900 * cannot do anything more reasonable, the failure mode of the
901 * caller is unresolved library anyway.
903 if (subst_count == 0 || (obj != NULL && !obj_resolve_origin(obj)))
904 return (may_free ? real : xstrdup(real));
906 subst = obj->origin_path;
909 * There is indeed something to substitute. Calculate the
910 * length of the resulting string, and allocate it.
912 subst_len = strlen(subst);
913 old_len = strlen(real);
914 new_len = old_len + (subst_len - kw_len) * subst_count;
915 res = xmalloc(new_len + 1);
918 * Now, execute the substitution loop.
920 for (p = real, resp = res, *resp = '\0';;) {
923 /* Copy the prefix before keyword. */
924 memcpy(resp, p, p1 - p);
926 /* Keyword replacement. */
927 memcpy(resp, subst, subst_len);
935 /* Copy to the end of string and finish. */
943 origin_subst(Obj_Entry *obj, char *real)
945 char *res1, *res2, *res3, *res4;
947 if (obj == NULL || !trust)
948 return (xstrdup(real));
949 if (uts.sysname[0] == '\0') {
950 if (uname(&uts) != 0) {
951 _rtld_error("utsname failed: %d", errno);
955 res1 = origin_subst_one(obj, real, "$ORIGIN", NULL, false);
956 res2 = origin_subst_one(NULL, res1, "$OSNAME", uts.sysname, true);
957 res3 = origin_subst_one(NULL, res2, "$OSREL", uts.release, true);
958 res4 = origin_subst_one(NULL, res3, "$PLATFORM", uts.machine, true);
965 const char *msg = dlerror();
969 rtld_fdputstr(STDERR_FILENO, _BASENAME_RTLD ": ");
970 rtld_fdputstr(STDERR_FILENO, msg);
971 rtld_fdputchar(STDERR_FILENO, '\n');
976 * Process a shared object's DYNAMIC section, and save the important
977 * information in its Obj_Entry structure.
980 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
981 const Elf_Dyn **dyn_soname, const Elf_Dyn **dyn_runpath)
984 Needed_Entry **needed_tail = &obj->needed;
985 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
986 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
987 const Elf_Hashelt *hashtab;
988 const Elf32_Word *hashval;
989 Elf32_Word bkt, nmaskwords;
991 int plttype = DT_REL;
997 obj->bind_now = false;
998 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
999 switch (dynp->d_tag) {
1002 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
1006 obj->relsize = dynp->d_un.d_val;
1010 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
1014 obj->pltrel = (const Elf_Rel *)
1015 (obj->relocbase + dynp->d_un.d_ptr);
1019 obj->pltrelsize = dynp->d_un.d_val;
1023 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
1027 obj->relasize = dynp->d_un.d_val;
1031 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
1035 plttype = dynp->d_un.d_val;
1036 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
1040 obj->symtab = (const Elf_Sym *)
1041 (obj->relocbase + dynp->d_un.d_ptr);
1045 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
1049 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
1053 obj->strsize = dynp->d_un.d_val;
1057 obj->verneed = (const Elf_Verneed *) (obj->relocbase +
1062 obj->verneednum = dynp->d_un.d_val;
1066 obj->verdef = (const Elf_Verdef *) (obj->relocbase +
1071 obj->verdefnum = dynp->d_un.d_val;
1075 obj->versyms = (const Elf_Versym *)(obj->relocbase +
1081 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1083 obj->nbuckets = hashtab[0];
1084 obj->nchains = hashtab[1];
1085 obj->buckets = hashtab + 2;
1086 obj->chains = obj->buckets + obj->nbuckets;
1087 obj->valid_hash_sysv = obj->nbuckets > 0 && obj->nchains > 0 &&
1088 obj->buckets != NULL;
1094 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1096 obj->nbuckets_gnu = hashtab[0];
1097 obj->symndx_gnu = hashtab[1];
1098 nmaskwords = hashtab[2];
1099 bloom_size32 = (__ELF_WORD_SIZE / 32) * nmaskwords;
1100 obj->maskwords_bm_gnu = nmaskwords - 1;
1101 obj->shift2_gnu = hashtab[3];
1102 obj->bloom_gnu = (Elf_Addr *) (hashtab + 4);
1103 obj->buckets_gnu = hashtab + 4 + bloom_size32;
1104 obj->chain_zero_gnu = obj->buckets_gnu + obj->nbuckets_gnu -
1106 /* Number of bitmask words is required to be power of 2 */
1107 obj->valid_hash_gnu = powerof2(nmaskwords) &&
1108 obj->nbuckets_gnu > 0 && obj->buckets_gnu != NULL;
1114 Needed_Entry *nep = NEW(Needed_Entry);
1115 nep->name = dynp->d_un.d_val;
1120 needed_tail = &nep->next;
1126 Needed_Entry *nep = NEW(Needed_Entry);
1127 nep->name = dynp->d_un.d_val;
1131 *needed_filtees_tail = nep;
1132 needed_filtees_tail = &nep->next;
1138 Needed_Entry *nep = NEW(Needed_Entry);
1139 nep->name = dynp->d_un.d_val;
1143 *needed_aux_filtees_tail = nep;
1144 needed_aux_filtees_tail = &nep->next;
1149 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
1153 obj->textrel = true;
1157 obj->symbolic = true;
1162 * We have to wait until later to process this, because we
1163 * might not have gotten the address of the string table yet.
1173 *dyn_runpath = dynp;
1177 obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1180 case DT_PREINIT_ARRAY:
1181 obj->preinit_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1184 case DT_PREINIT_ARRAYSZ:
1185 obj->preinit_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1189 obj->init_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1192 case DT_INIT_ARRAYSZ:
1193 obj->init_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1197 obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1201 obj->fini_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1204 case DT_FINI_ARRAYSZ:
1205 obj->fini_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1209 * Don't process DT_DEBUG on MIPS as the dynamic section
1210 * is mapped read-only. DT_MIPS_RLD_MAP is used instead.
1216 dbg("Filling in DT_DEBUG entry");
1217 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
1222 if (dynp->d_un.d_val & DF_ORIGIN)
1223 obj->z_origin = true;
1224 if (dynp->d_un.d_val & DF_SYMBOLIC)
1225 obj->symbolic = true;
1226 if (dynp->d_un.d_val & DF_TEXTREL)
1227 obj->textrel = true;
1228 if (dynp->d_un.d_val & DF_BIND_NOW)
1229 obj->bind_now = true;
1230 /*if (dynp->d_un.d_val & DF_STATIC_TLS)
1234 case DT_MIPS_LOCAL_GOTNO:
1235 obj->local_gotno = dynp->d_un.d_val;
1238 case DT_MIPS_SYMTABNO:
1239 obj->symtabno = dynp->d_un.d_val;
1242 case DT_MIPS_GOTSYM:
1243 obj->gotsym = dynp->d_un.d_val;
1246 case DT_MIPS_RLD_MAP:
1247 *((Elf_Addr *)(dynp->d_un.d_ptr)) = (Elf_Addr) &r_debug;
1250 case DT_MIPS_PLTGOT:
1251 obj->mips_pltgot = (Elf_Addr *) (obj->relocbase +
1257 #ifdef __powerpc64__
1258 case DT_PPC64_GLINK:
1259 obj->glink = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1264 if (dynp->d_un.d_val & DF_1_NOOPEN)
1265 obj->z_noopen = true;
1266 if (dynp->d_un.d_val & DF_1_ORIGIN)
1267 obj->z_origin = true;
1268 if (dynp->d_un.d_val & DF_1_GLOBAL)
1269 obj->z_global = true;
1270 if (dynp->d_un.d_val & DF_1_BIND_NOW)
1271 obj->bind_now = true;
1272 if (dynp->d_un.d_val & DF_1_NODELETE)
1273 obj->z_nodelete = true;
1274 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1275 obj->z_loadfltr = true;
1276 if (dynp->d_un.d_val & DF_1_INTERPOSE)
1277 obj->z_interpose = true;
1278 if (dynp->d_un.d_val & DF_1_NODEFLIB)
1279 obj->z_nodeflib = true;
1284 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1291 obj->traced = false;
1293 if (plttype == DT_RELA) {
1294 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1296 obj->pltrelasize = obj->pltrelsize;
1297 obj->pltrelsize = 0;
1300 /* Determine size of dynsym table (equal to nchains of sysv hash) */
1301 if (obj->valid_hash_sysv)
1302 obj->dynsymcount = obj->nchains;
1303 else if (obj->valid_hash_gnu) {
1304 obj->dynsymcount = 0;
1305 for (bkt = 0; bkt < obj->nbuckets_gnu; bkt++) {
1306 if (obj->buckets_gnu[bkt] == 0)
1308 hashval = &obj->chain_zero_gnu[obj->buckets_gnu[bkt]];
1311 while ((*hashval++ & 1u) == 0);
1313 obj->dynsymcount += obj->symndx_gnu;
1318 obj_resolve_origin(Obj_Entry *obj)
1321 if (obj->origin_path != NULL)
1323 obj->origin_path = xmalloc(PATH_MAX);
1324 return (rtld_dirname_abs(obj->path, obj->origin_path) != -1);
1328 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1329 const Elf_Dyn *dyn_soname, const Elf_Dyn *dyn_runpath)
1332 if (obj->z_origin && !obj_resolve_origin(obj))
1335 if (dyn_runpath != NULL) {
1336 obj->runpath = (char *)obj->strtab + dyn_runpath->d_un.d_val;
1337 obj->runpath = origin_subst(obj, obj->runpath);
1338 } else if (dyn_rpath != NULL) {
1339 obj->rpath = (char *)obj->strtab + dyn_rpath->d_un.d_val;
1340 obj->rpath = origin_subst(obj, obj->rpath);
1342 if (dyn_soname != NULL)
1343 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1347 digest_dynamic(Obj_Entry *obj, int early)
1349 const Elf_Dyn *dyn_rpath;
1350 const Elf_Dyn *dyn_soname;
1351 const Elf_Dyn *dyn_runpath;
1353 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname, &dyn_runpath);
1354 digest_dynamic2(obj, dyn_rpath, dyn_soname, dyn_runpath);
1358 * Process a shared object's program header. This is used only for the
1359 * main program, when the kernel has already loaded the main program
1360 * into memory before calling the dynamic linker. It creates and
1361 * returns an Obj_Entry structure.
1364 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1367 const Elf_Phdr *phlimit = phdr + phnum;
1369 Elf_Addr note_start, note_end;
1373 for (ph = phdr; ph < phlimit; ph++) {
1374 if (ph->p_type != PT_PHDR)
1378 obj->phsize = ph->p_memsz;
1379 obj->relocbase = (caddr_t)phdr - ph->p_vaddr;
1383 obj->stack_flags = PF_X | PF_R | PF_W;
1385 for (ph = phdr; ph < phlimit; ph++) {
1386 switch (ph->p_type) {
1389 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1393 if (nsegs == 0) { /* First load segment */
1394 obj->vaddrbase = trunc_page(ph->p_vaddr);
1395 obj->mapbase = obj->vaddrbase + obj->relocbase;
1396 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
1398 } else { /* Last load segment */
1399 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1406 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1411 obj->tlssize = ph->p_memsz;
1412 obj->tlsalign = ph->p_align;
1413 obj->tlsinitsize = ph->p_filesz;
1414 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1418 obj->stack_flags = ph->p_flags;
1422 obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1423 obj->relro_size = round_page(ph->p_memsz);
1427 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
1428 note_end = note_start + ph->p_filesz;
1429 digest_notes(obj, note_start, note_end);
1434 _rtld_error("%s: too few PT_LOAD segments", path);
1443 digest_notes(Obj_Entry *obj, Elf_Addr note_start, Elf_Addr note_end)
1445 const Elf_Note *note;
1446 const char *note_name;
1449 for (note = (const Elf_Note *)note_start; (Elf_Addr)note < note_end;
1450 note = (const Elf_Note *)((const char *)(note + 1) +
1451 roundup2(note->n_namesz, sizeof(Elf32_Addr)) +
1452 roundup2(note->n_descsz, sizeof(Elf32_Addr)))) {
1453 if (note->n_namesz != sizeof(NOTE_FREEBSD_VENDOR) ||
1454 note->n_descsz != sizeof(int32_t))
1456 if (note->n_type != NT_FREEBSD_ABI_TAG &&
1457 note->n_type != NT_FREEBSD_FEATURE_CTL &&
1458 note->n_type != NT_FREEBSD_NOINIT_TAG)
1460 note_name = (const char *)(note + 1);
1461 if (strncmp(NOTE_FREEBSD_VENDOR, note_name,
1462 sizeof(NOTE_FREEBSD_VENDOR)) != 0)
1464 switch (note->n_type) {
1465 case NT_FREEBSD_ABI_TAG:
1466 /* FreeBSD osrel note */
1467 p = (uintptr_t)(note + 1);
1468 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1469 obj->osrel = *(const int32_t *)(p);
1470 dbg("note osrel %d", obj->osrel);
1472 case NT_FREEBSD_FEATURE_CTL:
1473 /* FreeBSD ABI feature control note */
1474 p = (uintptr_t)(note + 1);
1475 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1476 obj->fctl0 = *(const uint32_t *)(p);
1477 dbg("note fctl0 %#x", obj->fctl0);
1479 case NT_FREEBSD_NOINIT_TAG:
1480 /* FreeBSD 'crt does not call init' note */
1481 obj->crt_no_init = true;
1482 dbg("note crt_no_init");
1489 dlcheck(void *handle)
1493 TAILQ_FOREACH(obj, &obj_list, next) {
1494 if (obj == (Obj_Entry *) handle)
1498 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1499 _rtld_error("Invalid shared object handle %p", handle);
1506 * If the given object is already in the donelist, return true. Otherwise
1507 * add the object to the list and return false.
1510 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1514 for (i = 0; i < dlp->num_used; i++)
1515 if (dlp->objs[i] == obj)
1518 * Our donelist allocation should always be sufficient. But if
1519 * our threads locking isn't working properly, more shared objects
1520 * could have been loaded since we allocated the list. That should
1521 * never happen, but we'll handle it properly just in case it does.
1523 if (dlp->num_used < dlp->num_alloc)
1524 dlp->objs[dlp->num_used++] = obj;
1529 * Hash function for symbol table lookup. Don't even think about changing
1530 * this. It is specified by the System V ABI.
1533 elf_hash(const char *name)
1535 const unsigned char *p = (const unsigned char *) name;
1536 unsigned long h = 0;
1539 while (*p != '\0') {
1540 h = (h << 4) + *p++;
1541 if ((g = h & 0xf0000000) != 0)
1549 * The GNU hash function is the Daniel J. Bernstein hash clipped to 32 bits
1550 * unsigned in case it's implemented with a wider type.
1553 gnu_hash(const char *s)
1559 for (c = *s; c != '\0'; c = *++s)
1561 return (h & 0xffffffff);
1566 * Find the library with the given name, and return its full pathname.
1567 * The returned string is dynamically allocated. Generates an error
1568 * message and returns NULL if the library cannot be found.
1570 * If the second argument is non-NULL, then it refers to an already-
1571 * loaded shared object, whose library search path will be searched.
1573 * If a library is successfully located via LD_LIBRARY_PATH_FDS, its
1574 * descriptor (which is close-on-exec) will be passed out via the third
1577 * The search order is:
1578 * DT_RPATH in the referencing file _unless_ DT_RUNPATH is present (1)
1579 * DT_RPATH of the main object if DSO without defined DT_RUNPATH (1)
1581 * DT_RUNPATH in the referencing file
1582 * ldconfig hints (if -z nodefaultlib, filter out default library directories
1584 * /lib:/usr/lib _unless_ the referencing file is linked with -z nodefaultlib
1586 * (1) Handled in digest_dynamic2 - rpath left NULL if runpath defined.
1589 find_library(const char *xname, const Obj_Entry *refobj, int *fdp)
1591 char *name, *pathname, *refobj_path;
1592 bool nodeflib, objgiven;
1594 objgiven = refobj != NULL;
1596 if (libmap_disable || !objgiven ||
1597 (name = lm_find(refobj->path, xname)) == NULL)
1598 name = (char *)xname;
1600 if (strchr(name, '/') != NULL) { /* Hard coded pathname */
1601 if (name[0] != '/' && !trust) {
1602 _rtld_error("Absolute pathname required "
1603 "for shared object \"%s\"", name);
1606 return (origin_subst(__DECONST(Obj_Entry *, refobj),
1607 __DECONST(char *, name)));
1610 dbg(" Searching for \"%s\"", name);
1611 refobj_path = objgiven ? refobj->path : NULL;
1614 * If refobj->rpath != NULL, then refobj->runpath is NULL. Fall
1615 * back to pre-conforming behaviour if user requested so with
1616 * LD_LIBRARY_PATH_RPATH environment variable and ignore -z
1619 if (objgiven && refobj->rpath != NULL && ld_library_path_rpath) {
1620 pathname = search_library_path(name, ld_library_path,
1622 if (pathname != NULL)
1624 if (refobj != NULL) {
1625 pathname = search_library_path(name, refobj->rpath,
1627 if (pathname != NULL)
1630 pathname = search_library_pathfds(name, ld_library_dirs, fdp);
1631 if (pathname != NULL)
1633 pathname = search_library_path(name, gethints(false),
1635 if (pathname != NULL)
1637 pathname = search_library_path(name, ld_standard_library_path,
1639 if (pathname != NULL)
1642 nodeflib = objgiven ? refobj->z_nodeflib : false;
1644 pathname = search_library_path(name, refobj->rpath,
1646 if (pathname != NULL)
1649 if (objgiven && refobj->runpath == NULL && refobj != obj_main) {
1650 pathname = search_library_path(name, obj_main->rpath,
1652 if (pathname != NULL)
1655 pathname = search_library_path(name, ld_library_path,
1657 if (pathname != NULL)
1660 pathname = search_library_path(name, refobj->runpath,
1662 if (pathname != NULL)
1665 pathname = search_library_pathfds(name, ld_library_dirs, fdp);
1666 if (pathname != NULL)
1668 pathname = search_library_path(name, gethints(nodeflib),
1670 if (pathname != NULL)
1672 if (objgiven && !nodeflib) {
1673 pathname = search_library_path(name,
1674 ld_standard_library_path, refobj_path, fdp);
1675 if (pathname != NULL)
1680 if (objgiven && refobj->path != NULL) {
1681 _rtld_error("Shared object \"%s\" not found, "
1682 "required by \"%s\"", name, basename(refobj->path));
1684 _rtld_error("Shared object \"%s\" not found", name);
1690 * Given a symbol number in a referencing object, find the corresponding
1691 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1692 * no definition was found. Returns a pointer to the Obj_Entry of the
1693 * defining object via the reference parameter DEFOBJ_OUT.
1696 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1697 const Obj_Entry **defobj_out, int flags, SymCache *cache,
1698 RtldLockState *lockstate)
1702 const Obj_Entry *defobj;
1703 const Ver_Entry *ve;
1709 * If we have already found this symbol, get the information from
1712 if (symnum >= refobj->dynsymcount)
1713 return NULL; /* Bad object */
1714 if (cache != NULL && cache[symnum].sym != NULL) {
1715 *defobj_out = cache[symnum].obj;
1716 return cache[symnum].sym;
1719 ref = refobj->symtab + symnum;
1720 name = refobj->strtab + ref->st_name;
1726 * We don't have to do a full scale lookup if the symbol is local.
1727 * We know it will bind to the instance in this load module; to
1728 * which we already have a pointer (ie ref). By not doing a lookup,
1729 * we not only improve performance, but it also avoids unresolvable
1730 * symbols when local symbols are not in the hash table. This has
1731 * been seen with the ia64 toolchain.
1733 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1734 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1735 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1738 symlook_init(&req, name);
1740 ve = req.ventry = fetch_ventry(refobj, symnum);
1741 req.lockstate = lockstate;
1742 res = symlook_default(&req, refobj);
1745 defobj = req.defobj_out;
1753 * If we found no definition and the reference is weak, treat the
1754 * symbol as having the value zero.
1756 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1762 *defobj_out = defobj;
1763 /* Record the information in the cache to avoid subsequent lookups. */
1764 if (cache != NULL) {
1765 cache[symnum].sym = def;
1766 cache[symnum].obj = defobj;
1769 if (refobj != &obj_rtld)
1770 _rtld_error("%s: Undefined symbol \"%s%s%s\"", refobj->path, name,
1771 ve != NULL ? "@" : "", ve != NULL ? ve->name : "");
1777 * Return the search path from the ldconfig hints file, reading it if
1778 * necessary. If nostdlib is true, then the default search paths are
1779 * not added to result.
1781 * Returns NULL if there are problems with the hints file,
1782 * or if the search path there is empty.
1785 gethints(bool nostdlib)
1787 static char *hints, *filtered_path;
1788 static struct elfhints_hdr hdr;
1789 struct fill_search_info_args sargs, hargs;
1790 struct dl_serinfo smeta, hmeta, *SLPinfo, *hintinfo;
1791 struct dl_serpath *SLPpath, *hintpath;
1793 struct stat hint_stat;
1794 unsigned int SLPndx, hintndx, fndx, fcount;
1800 /* First call, read the hints file */
1801 if (hints == NULL) {
1802 /* Keep from trying again in case the hints file is bad. */
1805 if ((fd = open(ld_elf_hints_path, O_RDONLY | O_CLOEXEC)) == -1)
1809 * Check of hdr.dirlistlen value against type limit
1810 * intends to pacify static analyzers. Further
1811 * paranoia leads to checks that dirlist is fully
1812 * contained in the file range.
1814 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1815 hdr.magic != ELFHINTS_MAGIC ||
1816 hdr.version != 1 || hdr.dirlistlen > UINT_MAX / 2 ||
1817 fstat(fd, &hint_stat) == -1) {
1824 if (dl + hdr.dirlist < dl)
1827 if (dl + hdr.dirlistlen < dl)
1829 dl += hdr.dirlistlen;
1830 if (dl > hint_stat.st_size)
1832 p = xmalloc(hdr.dirlistlen + 1);
1833 if (pread(fd, p, hdr.dirlistlen + 1,
1834 hdr.strtab + hdr.dirlist) != (ssize_t)hdr.dirlistlen + 1 ||
1835 p[hdr.dirlistlen] != '\0') {
1844 * If caller agreed to receive list which includes the default
1845 * paths, we are done. Otherwise, if we still did not
1846 * calculated filtered result, do it now.
1849 return (hints[0] != '\0' ? hints : NULL);
1850 if (filtered_path != NULL)
1854 * Obtain the list of all configured search paths, and the
1855 * list of the default paths.
1857 * First estimate the size of the results.
1859 smeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1861 hmeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1864 sargs.request = RTLD_DI_SERINFOSIZE;
1865 sargs.serinfo = &smeta;
1866 hargs.request = RTLD_DI_SERINFOSIZE;
1867 hargs.serinfo = &hmeta;
1869 path_enumerate(ld_standard_library_path, fill_search_info, NULL,
1871 path_enumerate(hints, fill_search_info, NULL, &hargs);
1873 SLPinfo = xmalloc(smeta.dls_size);
1874 hintinfo = xmalloc(hmeta.dls_size);
1877 * Next fetch both sets of paths.
1879 sargs.request = RTLD_DI_SERINFO;
1880 sargs.serinfo = SLPinfo;
1881 sargs.serpath = &SLPinfo->dls_serpath[0];
1882 sargs.strspace = (char *)&SLPinfo->dls_serpath[smeta.dls_cnt];
1884 hargs.request = RTLD_DI_SERINFO;
1885 hargs.serinfo = hintinfo;
1886 hargs.serpath = &hintinfo->dls_serpath[0];
1887 hargs.strspace = (char *)&hintinfo->dls_serpath[hmeta.dls_cnt];
1889 path_enumerate(ld_standard_library_path, fill_search_info, NULL,
1891 path_enumerate(hints, fill_search_info, NULL, &hargs);
1894 * Now calculate the difference between two sets, by excluding
1895 * standard paths from the full set.
1899 filtered_path = xmalloc(hdr.dirlistlen + 1);
1900 hintpath = &hintinfo->dls_serpath[0];
1901 for (hintndx = 0; hintndx < hmeta.dls_cnt; hintndx++, hintpath++) {
1903 SLPpath = &SLPinfo->dls_serpath[0];
1905 * Check each standard path against current.
1907 for (SLPndx = 0; SLPndx < smeta.dls_cnt; SLPndx++, SLPpath++) {
1908 /* matched, skip the path */
1909 if (!strcmp(hintpath->dls_name, SLPpath->dls_name)) {
1917 * Not matched against any standard path, add the path
1918 * to result. Separate consequtive paths with ':'.
1921 filtered_path[fndx] = ':';
1925 flen = strlen(hintpath->dls_name);
1926 strncpy((filtered_path + fndx), hintpath->dls_name, flen);
1929 filtered_path[fndx] = '\0';
1935 return (filtered_path[0] != '\0' ? filtered_path : NULL);
1939 init_dag(Obj_Entry *root)
1941 const Needed_Entry *needed;
1942 const Objlist_Entry *elm;
1945 if (root->dag_inited)
1947 donelist_init(&donelist);
1949 /* Root object belongs to own DAG. */
1950 objlist_push_tail(&root->dldags, root);
1951 objlist_push_tail(&root->dagmembers, root);
1952 donelist_check(&donelist, root);
1955 * Add dependencies of root object to DAG in breadth order
1956 * by exploiting the fact that each new object get added
1957 * to the tail of the dagmembers list.
1959 STAILQ_FOREACH(elm, &root->dagmembers, link) {
1960 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
1961 if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
1963 objlist_push_tail(&needed->obj->dldags, root);
1964 objlist_push_tail(&root->dagmembers, needed->obj);
1967 root->dag_inited = true;
1971 init_marker(Obj_Entry *marker)
1974 bzero(marker, sizeof(*marker));
1975 marker->marker = true;
1979 globallist_curr(const Obj_Entry *obj)
1986 return (__DECONST(Obj_Entry *, obj));
1987 obj = TAILQ_PREV(obj, obj_entry_q, next);
1992 globallist_next(const Obj_Entry *obj)
1996 obj = TAILQ_NEXT(obj, next);
2000 return (__DECONST(Obj_Entry *, obj));
2004 /* Prevent the object from being unmapped while the bind lock is dropped. */
2006 hold_object(Obj_Entry *obj)
2013 unhold_object(Obj_Entry *obj)
2016 assert(obj->holdcount > 0);
2017 if (--obj->holdcount == 0 && obj->unholdfree)
2018 release_object(obj);
2022 process_z(Obj_Entry *root)
2024 const Objlist_Entry *elm;
2028 * Walk over object DAG and process every dependent object
2029 * that is marked as DF_1_NODELETE or DF_1_GLOBAL. They need
2030 * to grow their own DAG.
2032 * For DF_1_GLOBAL, DAG is required for symbol lookups in
2033 * symlook_global() to work.
2035 * For DF_1_NODELETE, the DAG should have its reference upped.
2037 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2041 if (obj->z_nodelete && !obj->ref_nodel) {
2042 dbg("obj %s -z nodelete", obj->path);
2045 obj->ref_nodel = true;
2047 if (obj->z_global && objlist_find(&list_global, obj) == NULL) {
2048 dbg("obj %s -z global", obj->path);
2049 objlist_push_tail(&list_global, obj);
2055 * Initialize the dynamic linker. The argument is the address at which
2056 * the dynamic linker has been mapped into memory. The primary task of
2057 * this function is to relocate the dynamic linker.
2060 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
2062 Obj_Entry objtmp; /* Temporary rtld object */
2063 const Elf_Ehdr *ehdr;
2064 const Elf_Dyn *dyn_rpath;
2065 const Elf_Dyn *dyn_soname;
2066 const Elf_Dyn *dyn_runpath;
2068 #ifdef RTLD_INIT_PAGESIZES_EARLY
2069 /* The page size is required by the dynamic memory allocator. */
2070 init_pagesizes(aux_info);
2074 * Conjure up an Obj_Entry structure for the dynamic linker.
2076 * The "path" member can't be initialized yet because string constants
2077 * cannot yet be accessed. Below we will set it correctly.
2079 memset(&objtmp, 0, sizeof(objtmp));
2082 objtmp.mapbase = mapbase;
2084 objtmp.relocbase = mapbase;
2087 objtmp.dynamic = rtld_dynamic(&objtmp);
2088 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname, &dyn_runpath);
2089 assert(objtmp.needed == NULL);
2090 #if !defined(__mips__)
2091 /* MIPS has a bogus DT_TEXTREL. */
2092 assert(!objtmp.textrel);
2095 * Temporarily put the dynamic linker entry into the object list, so
2096 * that symbols can be found.
2098 relocate_objects(&objtmp, true, &objtmp, 0, NULL);
2100 ehdr = (Elf_Ehdr *)mapbase;
2101 objtmp.phdr = (Elf_Phdr *)((char *)mapbase + ehdr->e_phoff);
2102 objtmp.phsize = ehdr->e_phnum * sizeof(objtmp.phdr[0]);
2104 /* Initialize the object list. */
2105 TAILQ_INIT(&obj_list);
2107 /* Now that non-local variables can be accesses, copy out obj_rtld. */
2108 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
2110 #ifndef RTLD_INIT_PAGESIZES_EARLY
2111 /* The page size is required by the dynamic memory allocator. */
2112 init_pagesizes(aux_info);
2115 if (aux_info[AT_OSRELDATE] != NULL)
2116 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
2118 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname, dyn_runpath);
2120 /* Replace the path with a dynamically allocated copy. */
2121 obj_rtld.path = xstrdup(ld_path_rtld);
2123 r_debug.r_brk = r_debug_state;
2124 r_debug.r_state = RT_CONSISTENT;
2128 * Retrieve the array of supported page sizes. The kernel provides the page
2129 * sizes in increasing order.
2132 init_pagesizes(Elf_Auxinfo **aux_info)
2134 static size_t psa[MAXPAGESIZES];
2138 if (aux_info[AT_PAGESIZES] != NULL && aux_info[AT_PAGESIZESLEN] !=
2140 size = aux_info[AT_PAGESIZESLEN]->a_un.a_val;
2141 pagesizes = aux_info[AT_PAGESIZES]->a_un.a_ptr;
2144 if (sysctlnametomib("hw.pagesizes", mib, &len) == 0)
2147 /* As a fallback, retrieve the base page size. */
2148 size = sizeof(psa[0]);
2149 if (aux_info[AT_PAGESZ] != NULL) {
2150 psa[0] = aux_info[AT_PAGESZ]->a_un.a_val;
2154 mib[1] = HW_PAGESIZE;
2158 if (sysctl(mib, len, psa, &size, NULL, 0) == -1) {
2159 _rtld_error("sysctl for hw.pagesize(s) failed");
2165 npagesizes = size / sizeof(pagesizes[0]);
2166 /* Discard any invalid entries at the end of the array. */
2167 while (npagesizes > 0 && pagesizes[npagesizes - 1] == 0)
2172 * Add the init functions from a needed object list (and its recursive
2173 * needed objects) to "list". This is not used directly; it is a helper
2174 * function for initlist_add_objects(). The write lock must be held
2175 * when this function is called.
2178 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
2180 /* Recursively process the successor needed objects. */
2181 if (needed->next != NULL)
2182 initlist_add_neededs(needed->next, list);
2184 /* Process the current needed object. */
2185 if (needed->obj != NULL)
2186 initlist_add_objects(needed->obj, needed->obj, list);
2190 * Scan all of the DAGs rooted in the range of objects from "obj" to
2191 * "tail" and add their init functions to "list". This recurses over
2192 * the DAGs and ensure the proper init ordering such that each object's
2193 * needed libraries are initialized before the object itself. At the
2194 * same time, this function adds the objects to the global finalization
2195 * list "list_fini" in the opposite order. The write lock must be
2196 * held when this function is called.
2199 initlist_add_objects(Obj_Entry *obj, Obj_Entry *tail, Objlist *list)
2203 if (obj->init_scanned || obj->init_done)
2205 obj->init_scanned = true;
2207 /* Recursively process the successor objects. */
2208 nobj = globallist_next(obj);
2209 if (nobj != NULL && obj != tail)
2210 initlist_add_objects(nobj, tail, list);
2212 /* Recursively process the needed objects. */
2213 if (obj->needed != NULL)
2214 initlist_add_neededs(obj->needed, list);
2215 if (obj->needed_filtees != NULL)
2216 initlist_add_neededs(obj->needed_filtees, list);
2217 if (obj->needed_aux_filtees != NULL)
2218 initlist_add_neededs(obj->needed_aux_filtees, list);
2220 /* Add the object to the init list. */
2221 objlist_push_tail(list, obj);
2223 /* Add the object to the global fini list in the reverse order. */
2224 if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL)
2225 && !obj->on_fini_list) {
2226 objlist_push_head(&list_fini, obj);
2227 obj->on_fini_list = true;
2232 #define FPTR_TARGET(f) ((Elf_Addr) (f))
2236 free_needed_filtees(Needed_Entry *n, RtldLockState *lockstate)
2238 Needed_Entry *needed, *needed1;
2240 for (needed = n; needed != NULL; needed = needed->next) {
2241 if (needed->obj != NULL) {
2242 dlclose_locked(needed->obj, lockstate);
2246 for (needed = n; needed != NULL; needed = needed1) {
2247 needed1 = needed->next;
2253 unload_filtees(Obj_Entry *obj, RtldLockState *lockstate)
2256 free_needed_filtees(obj->needed_filtees, lockstate);
2257 obj->needed_filtees = NULL;
2258 free_needed_filtees(obj->needed_aux_filtees, lockstate);
2259 obj->needed_aux_filtees = NULL;
2260 obj->filtees_loaded = false;
2264 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags,
2265 RtldLockState *lockstate)
2268 for (; needed != NULL; needed = needed->next) {
2269 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
2270 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
2271 RTLD_LOCAL, lockstate);
2276 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
2279 lock_restart_for_upgrade(lockstate);
2280 if (!obj->filtees_loaded) {
2281 load_filtee1(obj, obj->needed_filtees, flags, lockstate);
2282 load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate);
2283 obj->filtees_loaded = true;
2288 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
2292 for (; needed != NULL; needed = needed->next) {
2293 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
2294 flags & ~RTLD_LO_NOLOAD);
2295 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
2302 * Given a shared object, traverse its list of needed objects, and load
2303 * each of them. Returns 0 on success. Generates an error message and
2304 * returns -1 on failure.
2307 load_needed_objects(Obj_Entry *first, int flags)
2311 for (obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
2314 if (process_needed(obj, obj->needed, flags) == -1)
2321 load_preload_objects(void)
2323 char *p = ld_preload;
2325 static const char delim[] = " \t:;";
2330 p += strspn(p, delim);
2331 while (*p != '\0') {
2332 size_t len = strcspn(p, delim);
2337 obj = load_object(p, -1, NULL, 0);
2339 return -1; /* XXX - cleanup */
2340 obj->z_interpose = true;
2343 p += strspn(p, delim);
2345 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
2350 printable_path(const char *path)
2353 return (path == NULL ? "<unknown>" : path);
2357 * Load a shared object into memory, if it is not already loaded. The
2358 * object may be specified by name or by user-supplied file descriptor
2359 * fd_u. In the later case, the fd_u descriptor is not closed, but its
2362 * Returns a pointer to the Obj_Entry for the object. Returns NULL
2366 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
2375 TAILQ_FOREACH(obj, &obj_list, next) {
2376 if (obj->marker || obj->doomed)
2378 if (object_match_name(obj, name))
2382 path = find_library(name, refobj, &fd);
2390 * search_library_pathfds() opens a fresh file descriptor for the
2391 * library, so there is no need to dup().
2393 } else if (fd_u == -1) {
2395 * If we didn't find a match by pathname, or the name is not
2396 * supplied, open the file and check again by device and inode.
2397 * This avoids false mismatches caused by multiple links or ".."
2400 * To avoid a race, we open the file and use fstat() rather than
2403 if ((fd = open(path, O_RDONLY | O_CLOEXEC | O_VERIFY)) == -1) {
2404 _rtld_error("Cannot open \"%s\"", path);
2409 fd = fcntl(fd_u, F_DUPFD_CLOEXEC, 0);
2411 _rtld_error("Cannot dup fd");
2416 if (fstat(fd, &sb) == -1) {
2417 _rtld_error("Cannot fstat \"%s\"", printable_path(path));
2422 TAILQ_FOREACH(obj, &obj_list, next) {
2423 if (obj->marker || obj->doomed)
2425 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
2428 if (obj != NULL && name != NULL) {
2429 object_add_name(obj, name);
2434 if (flags & RTLD_LO_NOLOAD) {
2440 /* First use of this object, so we must map it in */
2441 obj = do_load_object(fd, name, path, &sb, flags);
2450 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
2457 * but first, make sure that environment variables haven't been
2458 * used to circumvent the noexec flag on a filesystem.
2460 if (dangerous_ld_env) {
2461 if (fstatfs(fd, &fs) != 0) {
2462 _rtld_error("Cannot fstatfs \"%s\"", printable_path(path));
2465 if (fs.f_flags & MNT_NOEXEC) {
2466 _rtld_error("Cannot execute objects on %s", fs.f_mntonname);
2470 dbg("loading \"%s\"", printable_path(path));
2471 obj = map_object(fd, printable_path(path), sbp);
2476 * If DT_SONAME is present in the object, digest_dynamic2 already
2477 * added it to the object names.
2480 object_add_name(obj, name);
2482 digest_dynamic(obj, 0);
2483 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path,
2484 obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount);
2485 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
2487 dbg("refusing to load non-loadable \"%s\"", obj->path);
2488 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
2489 munmap(obj->mapbase, obj->mapsize);
2494 obj->dlopened = (flags & RTLD_LO_DLOPEN) != 0;
2495 TAILQ_INSERT_TAIL(&obj_list, obj, next);
2498 linkmap_add(obj); /* for GDB & dlinfo() */
2499 max_stack_flags |= obj->stack_flags;
2501 dbg(" %p .. %p: %s", obj->mapbase,
2502 obj->mapbase + obj->mapsize - 1, obj->path);
2504 dbg(" WARNING: %s has impure text", obj->path);
2505 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
2512 obj_from_addr(const void *addr)
2516 TAILQ_FOREACH(obj, &obj_list, next) {
2519 if (addr < (void *) obj->mapbase)
2521 if (addr < (void *) (obj->mapbase + obj->mapsize))
2530 Elf_Addr *preinit_addr;
2533 preinit_addr = (Elf_Addr *)obj_main->preinit_array;
2534 if (preinit_addr == NULL)
2537 for (index = 0; index < obj_main->preinit_array_num; index++) {
2538 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) {
2539 dbg("calling preinit function for %s at %p", obj_main->path,
2540 (void *)preinit_addr[index]);
2541 LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index],
2542 0, 0, obj_main->path);
2543 call_init_pointer(obj_main, preinit_addr[index]);
2549 * Call the finalization functions for each of the objects in "list"
2550 * belonging to the DAG of "root" and referenced once. If NULL "root"
2551 * is specified, every finalization function will be called regardless
2552 * of the reference count and the list elements won't be freed. All of
2553 * the objects are expected to have non-NULL fini functions.
2556 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
2560 Elf_Addr *fini_addr;
2563 assert(root == NULL || root->refcount == 1);
2566 root->doomed = true;
2569 * Preserve the current error message since a fini function might
2570 * call into the dynamic linker and overwrite it.
2572 saved_msg = errmsg_save();
2574 STAILQ_FOREACH(elm, list, link) {
2575 if (root != NULL && (elm->obj->refcount != 1 ||
2576 objlist_find(&root->dagmembers, elm->obj) == NULL))
2578 /* Remove object from fini list to prevent recursive invocation. */
2579 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2580 /* Ensure that new references cannot be acquired. */
2581 elm->obj->doomed = true;
2583 hold_object(elm->obj);
2584 lock_release(rtld_bind_lock, lockstate);
2586 * It is legal to have both DT_FINI and DT_FINI_ARRAY defined.
2587 * When this happens, DT_FINI_ARRAY is processed first.
2589 fini_addr = (Elf_Addr *)elm->obj->fini_array;
2590 if (fini_addr != NULL && elm->obj->fini_array_num > 0) {
2591 for (index = elm->obj->fini_array_num - 1; index >= 0;
2593 if (fini_addr[index] != 0 && fini_addr[index] != 1) {
2594 dbg("calling fini function for %s at %p",
2595 elm->obj->path, (void *)fini_addr[index]);
2596 LD_UTRACE(UTRACE_FINI_CALL, elm->obj,
2597 (void *)fini_addr[index], 0, 0, elm->obj->path);
2598 call_initfini_pointer(elm->obj, fini_addr[index]);
2602 if (elm->obj->fini != (Elf_Addr)NULL) {
2603 dbg("calling fini function for %s at %p", elm->obj->path,
2604 (void *)elm->obj->fini);
2605 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini,
2606 0, 0, elm->obj->path);
2607 call_initfini_pointer(elm->obj, elm->obj->fini);
2609 wlock_acquire(rtld_bind_lock, lockstate);
2610 unhold_object(elm->obj);
2611 /* No need to free anything if process is going down. */
2615 * We must restart the list traversal after every fini call
2616 * because a dlclose() call from the fini function or from
2617 * another thread might have modified the reference counts.
2621 } while (elm != NULL);
2622 errmsg_restore(saved_msg);
2626 * Call the initialization functions for each of the objects in
2627 * "list". All of the objects are expected to have non-NULL init
2631 objlist_call_init(Objlist *list, RtldLockState *lockstate)
2636 Elf_Addr *init_addr;
2640 * Clean init_scanned flag so that objects can be rechecked and
2641 * possibly initialized earlier if any of vectors called below
2642 * cause the change by using dlopen.
2644 TAILQ_FOREACH(obj, &obj_list, next) {
2647 obj->init_scanned = false;
2651 * Preserve the current error message since an init function might
2652 * call into the dynamic linker and overwrite it.
2654 saved_msg = errmsg_save();
2655 STAILQ_FOREACH(elm, list, link) {
2656 if (elm->obj->init_done) /* Initialized early. */
2659 * Race: other thread might try to use this object before current
2660 * one completes the initialization. Not much can be done here
2661 * without better locking.
2663 elm->obj->init_done = true;
2664 hold_object(elm->obj);
2665 lock_release(rtld_bind_lock, lockstate);
2668 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined.
2669 * When this happens, DT_INIT is processed first.
2671 if (elm->obj->init != (Elf_Addr)NULL) {
2672 dbg("calling init function for %s at %p", elm->obj->path,
2673 (void *)elm->obj->init);
2674 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init,
2675 0, 0, elm->obj->path);
2676 call_initfini_pointer(elm->obj, elm->obj->init);
2678 init_addr = (Elf_Addr *)elm->obj->init_array;
2679 if (init_addr != NULL) {
2680 for (index = 0; index < elm->obj->init_array_num; index++) {
2681 if (init_addr[index] != 0 && init_addr[index] != 1) {
2682 dbg("calling init function for %s at %p", elm->obj->path,
2683 (void *)init_addr[index]);
2684 LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
2685 (void *)init_addr[index], 0, 0, elm->obj->path);
2686 call_init_pointer(elm->obj, init_addr[index]);
2690 wlock_acquire(rtld_bind_lock, lockstate);
2691 unhold_object(elm->obj);
2693 errmsg_restore(saved_msg);
2697 objlist_clear(Objlist *list)
2701 while (!STAILQ_EMPTY(list)) {
2702 elm = STAILQ_FIRST(list);
2703 STAILQ_REMOVE_HEAD(list, link);
2708 static Objlist_Entry *
2709 objlist_find(Objlist *list, const Obj_Entry *obj)
2713 STAILQ_FOREACH(elm, list, link)
2714 if (elm->obj == obj)
2720 objlist_init(Objlist *list)
2726 objlist_push_head(Objlist *list, Obj_Entry *obj)
2730 elm = NEW(Objlist_Entry);
2732 STAILQ_INSERT_HEAD(list, elm, link);
2736 objlist_push_tail(Objlist *list, Obj_Entry *obj)
2740 elm = NEW(Objlist_Entry);
2742 STAILQ_INSERT_TAIL(list, elm, link);
2746 objlist_put_after(Objlist *list, Obj_Entry *listobj, Obj_Entry *obj)
2748 Objlist_Entry *elm, *listelm;
2750 STAILQ_FOREACH(listelm, list, link) {
2751 if (listelm->obj == listobj)
2754 elm = NEW(Objlist_Entry);
2756 if (listelm != NULL)
2757 STAILQ_INSERT_AFTER(list, listelm, elm, link);
2759 STAILQ_INSERT_TAIL(list, elm, link);
2763 objlist_remove(Objlist *list, Obj_Entry *obj)
2767 if ((elm = objlist_find(list, obj)) != NULL) {
2768 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2774 * Relocate dag rooted in the specified object.
2775 * Returns 0 on success, or -1 on failure.
2779 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj,
2780 int flags, RtldLockState *lockstate)
2786 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2787 error = relocate_object(elm->obj, bind_now, rtldobj, flags,
2796 * Prepare for, or clean after, relocating an object marked with
2797 * DT_TEXTREL or DF_TEXTREL. Before relocating, all read-only
2798 * segments are remapped read-write. After relocations are done, the
2799 * segment's permissions are returned back to the modes specified in
2800 * the phdrs. If any relocation happened, or always for wired
2801 * program, COW is triggered.
2804 reloc_textrel_prot(Obj_Entry *obj, bool before)
2811 for (l = obj->phsize / sizeof(*ph), ph = obj->phdr; l > 0;
2813 if (ph->p_type != PT_LOAD || (ph->p_flags & PF_W) != 0)
2815 base = obj->relocbase + trunc_page(ph->p_vaddr);
2816 sz = round_page(ph->p_vaddr + ph->p_filesz) -
2817 trunc_page(ph->p_vaddr);
2818 prot = convert_prot(ph->p_flags) | (before ? PROT_WRITE : 0);
2819 if (mprotect(base, sz, prot) == -1) {
2820 _rtld_error("%s: Cannot write-%sable text segment: %s",
2821 obj->path, before ? "en" : "dis",
2822 rtld_strerror(errno));
2830 * Relocate single object.
2831 * Returns 0 on success, or -1 on failure.
2834 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
2835 int flags, RtldLockState *lockstate)
2840 obj->relocated = true;
2842 dbg("relocating \"%s\"", obj->path);
2844 if (obj->symtab == NULL || obj->strtab == NULL ||
2845 !(obj->valid_hash_sysv || obj->valid_hash_gnu)) {
2846 _rtld_error("%s: Shared object has no run-time symbol table",
2851 /* There are relocations to the write-protected text segment. */
2852 if (obj->textrel && reloc_textrel_prot(obj, true) != 0)
2855 /* Process the non-PLT non-IFUNC relocations. */
2856 if (reloc_non_plt(obj, rtldobj, flags, lockstate))
2859 /* Re-protected the text segment. */
2860 if (obj->textrel && reloc_textrel_prot(obj, false) != 0)
2863 /* Set the special PLT or GOT entries. */
2866 /* Process the PLT relocations. */
2867 if (reloc_plt(obj, flags, lockstate) == -1)
2869 /* Relocate the jump slots if we are doing immediate binding. */
2870 if ((obj->bind_now || bind_now) && reloc_jmpslots(obj, flags,
2874 if (!obj->mainprog && obj_enforce_relro(obj) == -1)
2878 * Set up the magic number and version in the Obj_Entry. These
2879 * were checked in the crt1.o from the original ElfKit, so we
2880 * set them for backward compatibility.
2882 obj->magic = RTLD_MAGIC;
2883 obj->version = RTLD_VERSION;
2889 * Relocate newly-loaded shared objects. The argument is a pointer to
2890 * the Obj_Entry for the first such object. All objects from the first
2891 * to the end of the list of objects are relocated. Returns 0 on success,
2895 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
2896 int flags, RtldLockState *lockstate)
2901 for (error = 0, obj = first; obj != NULL;
2902 obj = TAILQ_NEXT(obj, next)) {
2905 error = relocate_object(obj, bind_now, rtldobj, flags,
2914 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
2915 * referencing STT_GNU_IFUNC symbols is postponed till the other
2916 * relocations are done. The indirect functions specified as
2917 * ifunc are allowed to call other symbols, so we need to have
2918 * objects relocated before asking for resolution from indirects.
2920 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
2921 * instead of the usual lazy handling of PLT slots. It is
2922 * consistent with how GNU does it.
2925 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags,
2926 RtldLockState *lockstate)
2929 if (obj->ifuncs_resolved)
2931 obj->ifuncs_resolved = true;
2932 if (obj->irelative && reloc_iresolve(obj, lockstate) == -1)
2934 if ((obj->bind_now || bind_now) && obj->gnu_ifunc) {
2935 if (obj_disable_relro(obj) ||
2936 reloc_gnu_ifunc(obj, flags, lockstate) == -1 ||
2937 obj_enforce_relro(obj))
2944 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags,
2945 RtldLockState *lockstate)
2950 STAILQ_FOREACH(elm, list, link) {
2954 if (resolve_object_ifunc(obj, bind_now, flags,
2962 * Cleanup procedure. It will be called (by the atexit mechanism) just
2963 * before the process exits.
2968 RtldLockState lockstate;
2970 wlock_acquire(rtld_bind_lock, &lockstate);
2972 objlist_call_fini(&list_fini, NULL, &lockstate);
2973 /* No need to remove the items from the list, since we are exiting. */
2974 if (!libmap_disable)
2976 lock_release(rtld_bind_lock, &lockstate);
2980 * Iterate over a search path, translate each element, and invoke the
2981 * callback on the result.
2984 path_enumerate(const char *path, path_enum_proc callback,
2985 const char *refobj_path, void *arg)
2991 path += strspn(path, ":;");
2992 while (*path != '\0') {
2996 len = strcspn(path, ":;");
2997 trans = lm_findn(refobj_path, path, len);
2999 res = callback(trans, strlen(trans), arg);
3001 res = callback(path, len, arg);
3007 path += strspn(path, ":;");
3013 struct try_library_args {
3022 try_library_path(const char *dir, size_t dirlen, void *param)
3024 struct try_library_args *arg;
3028 if (*dir == '/' || trust) {
3031 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
3034 pathname = arg->buffer;
3035 strncpy(pathname, dir, dirlen);
3036 pathname[dirlen] = '/';
3037 strcpy(pathname + dirlen + 1, arg->name);
3039 dbg(" Trying \"%s\"", pathname);
3040 fd = open(pathname, O_RDONLY | O_CLOEXEC | O_VERIFY);
3042 dbg(" Opened \"%s\", fd %d", pathname, fd);
3043 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
3044 strcpy(pathname, arg->buffer);
3048 dbg(" Failed to open \"%s\": %s",
3049 pathname, rtld_strerror(errno));
3056 search_library_path(const char *name, const char *path,
3057 const char *refobj_path, int *fdp)
3060 struct try_library_args arg;
3066 arg.namelen = strlen(name);
3067 arg.buffer = xmalloc(PATH_MAX);
3068 arg.buflen = PATH_MAX;
3071 p = path_enumerate(path, try_library_path, refobj_path, &arg);
3081 * Finds the library with the given name using the directory descriptors
3082 * listed in the LD_LIBRARY_PATH_FDS environment variable.
3084 * Returns a freshly-opened close-on-exec file descriptor for the library,
3085 * or -1 if the library cannot be found.
3088 search_library_pathfds(const char *name, const char *path, int *fdp)
3090 char *envcopy, *fdstr, *found, *last_token;
3094 dbg("%s('%s', '%s', fdp)", __func__, name, path);
3096 /* Don't load from user-specified libdirs into setuid binaries. */
3100 /* We can't do anything if LD_LIBRARY_PATH_FDS isn't set. */
3104 /* LD_LIBRARY_PATH_FDS only works with relative paths. */
3105 if (name[0] == '/') {
3106 dbg("Absolute path (%s) passed to %s", name, __func__);
3111 * Use strtok_r() to walk the FD:FD:FD list. This requires a local
3112 * copy of the path, as strtok_r rewrites separator tokens
3116 envcopy = xstrdup(path);
3117 for (fdstr = strtok_r(envcopy, ":", &last_token); fdstr != NULL;
3118 fdstr = strtok_r(NULL, ":", &last_token)) {
3119 dirfd = parse_integer(fdstr);
3121 _rtld_error("failed to parse directory FD: '%s'",
3125 fd = __sys_openat(dirfd, name, O_RDONLY | O_CLOEXEC | O_VERIFY);
3128 len = strlen(fdstr) + strlen(name) + 3;
3129 found = xmalloc(len);
3130 if (rtld_snprintf(found, len, "#%d/%s", dirfd, name) < 0) {
3131 _rtld_error("error generating '%d/%s'",
3135 dbg("open('%s') => %d", found, fd);
3146 dlclose(void *handle)
3148 RtldLockState lockstate;
3151 wlock_acquire(rtld_bind_lock, &lockstate);
3152 error = dlclose_locked(handle, &lockstate);
3153 lock_release(rtld_bind_lock, &lockstate);
3158 dlclose_locked(void *handle, RtldLockState *lockstate)
3162 root = dlcheck(handle);
3165 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
3168 /* Unreference the object and its dependencies. */
3169 root->dl_refcount--;
3171 if (root->refcount == 1) {
3173 * The object will be no longer referenced, so we must unload it.
3174 * First, call the fini functions.
3176 objlist_call_fini(&list_fini, root, lockstate);
3180 /* Finish cleaning up the newly-unreferenced objects. */
3181 GDB_STATE(RT_DELETE,&root->linkmap);
3182 unload_object(root, lockstate);
3183 GDB_STATE(RT_CONSISTENT,NULL);
3187 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
3194 char *msg = error_message;
3195 error_message = NULL;
3200 * This function is deprecated and has no effect.
3203 dllockinit(void *context,
3204 void *(*lock_create)(void *context),
3205 void (*rlock_acquire)(void *lock),
3206 void (*wlock_acquire)(void *lock),
3207 void (*lock_release)(void *lock),
3208 void (*lock_destroy)(void *lock),
3209 void (*context_destroy)(void *context))
3211 static void *cur_context;
3212 static void (*cur_context_destroy)(void *);
3214 /* Just destroy the context from the previous call, if necessary. */
3215 if (cur_context_destroy != NULL)
3216 cur_context_destroy(cur_context);
3217 cur_context = context;
3218 cur_context_destroy = context_destroy;
3222 dlopen(const char *name, int mode)
3225 return (rtld_dlopen(name, -1, mode));
3229 fdlopen(int fd, int mode)
3232 return (rtld_dlopen(NULL, fd, mode));
3236 rtld_dlopen(const char *name, int fd, int mode)
3238 RtldLockState lockstate;
3241 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
3242 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
3243 if (ld_tracing != NULL) {
3244 rlock_acquire(rtld_bind_lock, &lockstate);
3245 if (sigsetjmp(lockstate.env, 0) != 0)
3246 lock_upgrade(rtld_bind_lock, &lockstate);
3247 environ = (char **)*get_program_var_addr("environ", &lockstate);
3248 lock_release(rtld_bind_lock, &lockstate);
3250 lo_flags = RTLD_LO_DLOPEN;
3251 if (mode & RTLD_NODELETE)
3252 lo_flags |= RTLD_LO_NODELETE;
3253 if (mode & RTLD_NOLOAD)
3254 lo_flags |= RTLD_LO_NOLOAD;
3255 if (ld_tracing != NULL)
3256 lo_flags |= RTLD_LO_TRACE;
3258 return (dlopen_object(name, fd, obj_main, lo_flags,
3259 mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL));
3263 dlopen_cleanup(Obj_Entry *obj, RtldLockState *lockstate)
3268 if (obj->refcount == 0)
3269 unload_object(obj, lockstate);
3273 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
3274 int mode, RtldLockState *lockstate)
3276 Obj_Entry *old_obj_tail;
3279 RtldLockState mlockstate;
3282 objlist_init(&initlist);
3284 if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) {
3285 wlock_acquire(rtld_bind_lock, &mlockstate);
3286 lockstate = &mlockstate;
3288 GDB_STATE(RT_ADD,NULL);
3290 old_obj_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
3292 if (name == NULL && fd == -1) {
3296 obj = load_object(name, fd, refobj, lo_flags);
3301 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
3302 objlist_push_tail(&list_global, obj);
3303 if (globallist_next(old_obj_tail) != NULL) {
3304 /* We loaded something new. */
3305 assert(globallist_next(old_obj_tail) == obj);
3306 result = load_needed_objects(obj,
3307 lo_flags & (RTLD_LO_DLOPEN | RTLD_LO_EARLY));
3311 result = rtld_verify_versions(&obj->dagmembers);
3312 if (result != -1 && ld_tracing)
3314 if (result == -1 || relocate_object_dag(obj,
3315 (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld,
3316 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3318 dlopen_cleanup(obj, lockstate);
3320 } else if (lo_flags & RTLD_LO_EARLY) {
3322 * Do not call the init functions for early loaded
3323 * filtees. The image is still not initialized enough
3326 * Our object is found by the global object list and
3327 * will be ordered among all init calls done right
3328 * before transferring control to main.
3331 /* Make list of init functions to call. */
3332 initlist_add_objects(obj, obj, &initlist);
3335 * Process all no_delete or global objects here, given
3336 * them own DAGs to prevent their dependencies from being
3337 * unloaded. This has to be done after we have loaded all
3338 * of the dependencies, so that we do not miss any.
3344 * Bump the reference counts for objects on this DAG. If
3345 * this is the first dlopen() call for the object that was
3346 * already loaded as a dependency, initialize the dag
3352 if ((lo_flags & RTLD_LO_TRACE) != 0)
3355 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
3356 obj->z_nodelete) && !obj->ref_nodel) {
3357 dbg("obj %s nodelete", obj->path);
3359 obj->z_nodelete = obj->ref_nodel = true;
3363 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
3365 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
3367 if (!(lo_flags & RTLD_LO_EARLY)) {
3368 map_stacks_exec(lockstate);
3371 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
3372 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3374 objlist_clear(&initlist);
3375 dlopen_cleanup(obj, lockstate);
3376 if (lockstate == &mlockstate)
3377 lock_release(rtld_bind_lock, lockstate);
3381 if (!(lo_flags & RTLD_LO_EARLY)) {
3382 /* Call the init functions. */
3383 objlist_call_init(&initlist, lockstate);
3385 objlist_clear(&initlist);
3386 if (lockstate == &mlockstate)
3387 lock_release(rtld_bind_lock, lockstate);
3390 trace_loaded_objects(obj);
3391 if (lockstate == &mlockstate)
3392 lock_release(rtld_bind_lock, lockstate);
3397 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
3401 const Obj_Entry *obj, *defobj;
3404 RtldLockState lockstate;
3411 symlook_init(&req, name);
3413 req.flags = flags | SYMLOOK_IN_PLT;
3414 req.lockstate = &lockstate;
3416 LD_UTRACE(UTRACE_DLSYM_START, handle, NULL, 0, 0, name);
3417 rlock_acquire(rtld_bind_lock, &lockstate);
3418 if (sigsetjmp(lockstate.env, 0) != 0)
3419 lock_upgrade(rtld_bind_lock, &lockstate);
3420 if (handle == NULL || handle == RTLD_NEXT ||
3421 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
3423 if ((obj = obj_from_addr(retaddr)) == NULL) {
3424 _rtld_error("Cannot determine caller's shared object");
3425 lock_release(rtld_bind_lock, &lockstate);
3426 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3429 if (handle == NULL) { /* Just the caller's shared object. */
3430 res = symlook_obj(&req, obj);
3433 defobj = req.defobj_out;
3435 } else if (handle == RTLD_NEXT || /* Objects after caller's */
3436 handle == RTLD_SELF) { /* ... caller included */
3437 if (handle == RTLD_NEXT)
3438 obj = globallist_next(obj);
3439 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
3442 res = symlook_obj(&req, obj);
3445 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) {
3447 defobj = req.defobj_out;
3448 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3454 * Search the dynamic linker itself, and possibly resolve the
3455 * symbol from there. This is how the application links to
3456 * dynamic linker services such as dlopen.
3458 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3459 res = symlook_obj(&req, &obj_rtld);
3462 defobj = req.defobj_out;
3466 assert(handle == RTLD_DEFAULT);
3467 res = symlook_default(&req, obj);
3469 defobj = req.defobj_out;
3474 if ((obj = dlcheck(handle)) == NULL) {
3475 lock_release(rtld_bind_lock, &lockstate);
3476 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3480 donelist_init(&donelist);
3481 if (obj->mainprog) {
3482 /* Handle obtained by dlopen(NULL, ...) implies global scope. */
3483 res = symlook_global(&req, &donelist);
3486 defobj = req.defobj_out;
3489 * Search the dynamic linker itself, and possibly resolve the
3490 * symbol from there. This is how the application links to
3491 * dynamic linker services such as dlopen.
3493 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3494 res = symlook_obj(&req, &obj_rtld);
3497 defobj = req.defobj_out;
3502 /* Search the whole DAG rooted at the given object. */
3503 res = symlook_list(&req, &obj->dagmembers, &donelist);
3506 defobj = req.defobj_out;
3512 lock_release(rtld_bind_lock, &lockstate);
3515 * The value required by the caller is derived from the value
3516 * of the symbol. this is simply the relocated value of the
3519 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
3520 sym = make_function_pointer(def, defobj);
3521 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
3522 sym = rtld_resolve_ifunc(defobj, def);
3523 else if (ELF_ST_TYPE(def->st_info) == STT_TLS) {
3524 ti.ti_module = defobj->tlsindex;
3525 ti.ti_offset = def->st_value;
3526 sym = __tls_get_addr(&ti);
3528 sym = defobj->relocbase + def->st_value;
3529 LD_UTRACE(UTRACE_DLSYM_STOP, handle, sym, 0, 0, name);
3533 _rtld_error("Undefined symbol \"%s%s%s\"", name, ve != NULL ? "@" : "",
3534 ve != NULL ? ve->name : "");
3535 lock_release(rtld_bind_lock, &lockstate);
3536 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3541 dlsym(void *handle, const char *name)
3543 return do_dlsym(handle, name, __builtin_return_address(0), NULL,
3548 dlfunc(void *handle, const char *name)
3555 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
3561 dlvsym(void *handle, const char *name, const char *version)
3565 ventry.name = version;
3567 ventry.hash = elf_hash(version);
3569 return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
3574 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
3576 const Obj_Entry *obj;
3577 RtldLockState lockstate;
3579 rlock_acquire(rtld_bind_lock, &lockstate);
3580 obj = obj_from_addr(addr);
3582 _rtld_error("No shared object contains address");
3583 lock_release(rtld_bind_lock, &lockstate);
3586 rtld_fill_dl_phdr_info(obj, phdr_info);
3587 lock_release(rtld_bind_lock, &lockstate);
3592 dladdr(const void *addr, Dl_info *info)
3594 const Obj_Entry *obj;
3597 unsigned long symoffset;
3598 RtldLockState lockstate;
3600 rlock_acquire(rtld_bind_lock, &lockstate);
3601 obj = obj_from_addr(addr);
3603 _rtld_error("No shared object contains address");
3604 lock_release(rtld_bind_lock, &lockstate);
3607 info->dli_fname = obj->path;
3608 info->dli_fbase = obj->mapbase;
3609 info->dli_saddr = (void *)0;
3610 info->dli_sname = NULL;
3613 * Walk the symbol list looking for the symbol whose address is
3614 * closest to the address sent in.
3616 for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) {
3617 def = obj->symtab + symoffset;
3620 * For skip the symbol if st_shndx is either SHN_UNDEF or
3623 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
3627 * If the symbol is greater than the specified address, or if it
3628 * is further away from addr than the current nearest symbol,
3631 symbol_addr = obj->relocbase + def->st_value;
3632 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
3635 /* Update our idea of the nearest symbol. */
3636 info->dli_sname = obj->strtab + def->st_name;
3637 info->dli_saddr = symbol_addr;
3640 if (info->dli_saddr == addr)
3643 lock_release(rtld_bind_lock, &lockstate);
3648 dlinfo(void *handle, int request, void *p)
3650 const Obj_Entry *obj;
3651 RtldLockState lockstate;
3654 rlock_acquire(rtld_bind_lock, &lockstate);
3656 if (handle == NULL || handle == RTLD_SELF) {
3659 retaddr = __builtin_return_address(0); /* __GNUC__ only */
3660 if ((obj = obj_from_addr(retaddr)) == NULL)
3661 _rtld_error("Cannot determine caller's shared object");
3663 obj = dlcheck(handle);
3666 lock_release(rtld_bind_lock, &lockstate);
3672 case RTLD_DI_LINKMAP:
3673 *((struct link_map const **)p) = &obj->linkmap;
3675 case RTLD_DI_ORIGIN:
3676 error = rtld_dirname(obj->path, p);
3679 case RTLD_DI_SERINFOSIZE:
3680 case RTLD_DI_SERINFO:
3681 error = do_search_info(obj, request, (struct dl_serinfo *)p);
3685 _rtld_error("Invalid request %d passed to dlinfo()", request);
3689 lock_release(rtld_bind_lock, &lockstate);
3695 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
3698 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
3699 phdr_info->dlpi_name = obj->path;
3700 phdr_info->dlpi_phdr = obj->phdr;
3701 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
3702 phdr_info->dlpi_tls_modid = obj->tlsindex;
3703 phdr_info->dlpi_tls_data = obj->tlsinit;
3704 phdr_info->dlpi_adds = obj_loads;
3705 phdr_info->dlpi_subs = obj_loads - obj_count;
3709 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
3711 struct dl_phdr_info phdr_info;
3712 Obj_Entry *obj, marker;
3713 RtldLockState bind_lockstate, phdr_lockstate;
3716 init_marker(&marker);
3719 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
3720 wlock_acquire(rtld_bind_lock, &bind_lockstate);
3721 for (obj = globallist_curr(TAILQ_FIRST(&obj_list)); obj != NULL;) {
3722 TAILQ_INSERT_AFTER(&obj_list, obj, &marker, next);
3723 rtld_fill_dl_phdr_info(obj, &phdr_info);
3725 lock_release(rtld_bind_lock, &bind_lockstate);
3727 error = callback(&phdr_info, sizeof phdr_info, param);
3729 wlock_acquire(rtld_bind_lock, &bind_lockstate);
3731 obj = globallist_next(&marker);
3732 TAILQ_REMOVE(&obj_list, &marker, next);
3734 lock_release(rtld_bind_lock, &bind_lockstate);
3735 lock_release(rtld_phdr_lock, &phdr_lockstate);
3741 rtld_fill_dl_phdr_info(&obj_rtld, &phdr_info);
3742 lock_release(rtld_bind_lock, &bind_lockstate);
3743 error = callback(&phdr_info, sizeof(phdr_info), param);
3745 lock_release(rtld_phdr_lock, &phdr_lockstate);
3750 fill_search_info(const char *dir, size_t dirlen, void *param)
3752 struct fill_search_info_args *arg;
3756 if (arg->request == RTLD_DI_SERINFOSIZE) {
3757 arg->serinfo->dls_cnt ++;
3758 arg->serinfo->dls_size += sizeof(struct dl_serpath) + dirlen + 1;
3760 struct dl_serpath *s_entry;
3762 s_entry = arg->serpath;
3763 s_entry->dls_name = arg->strspace;
3764 s_entry->dls_flags = arg->flags;
3766 strncpy(arg->strspace, dir, dirlen);
3767 arg->strspace[dirlen] = '\0';
3769 arg->strspace += dirlen + 1;
3777 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
3779 struct dl_serinfo _info;
3780 struct fill_search_info_args args;
3782 args.request = RTLD_DI_SERINFOSIZE;
3783 args.serinfo = &_info;
3785 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
3788 path_enumerate(obj->rpath, fill_search_info, NULL, &args);
3789 path_enumerate(ld_library_path, fill_search_info, NULL, &args);
3790 path_enumerate(obj->runpath, fill_search_info, NULL, &args);
3791 path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args);
3792 if (!obj->z_nodeflib)
3793 path_enumerate(ld_standard_library_path, fill_search_info, NULL, &args);
3796 if (request == RTLD_DI_SERINFOSIZE) {
3797 info->dls_size = _info.dls_size;
3798 info->dls_cnt = _info.dls_cnt;
3802 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
3803 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
3807 args.request = RTLD_DI_SERINFO;
3808 args.serinfo = info;
3809 args.serpath = &info->dls_serpath[0];
3810 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
3812 args.flags = LA_SER_RUNPATH;
3813 if (path_enumerate(obj->rpath, fill_search_info, NULL, &args) != NULL)
3816 args.flags = LA_SER_LIBPATH;
3817 if (path_enumerate(ld_library_path, fill_search_info, NULL, &args) != NULL)
3820 args.flags = LA_SER_RUNPATH;
3821 if (path_enumerate(obj->runpath, fill_search_info, NULL, &args) != NULL)
3824 args.flags = LA_SER_CONFIG;
3825 if (path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args)
3829 args.flags = LA_SER_DEFAULT;
3830 if (!obj->z_nodeflib && path_enumerate(ld_standard_library_path,
3831 fill_search_info, NULL, &args) != NULL)
3837 rtld_dirname(const char *path, char *bname)
3841 /* Empty or NULL string gets treated as "." */
3842 if (path == NULL || *path == '\0') {
3848 /* Strip trailing slashes */
3849 endp = path + strlen(path) - 1;
3850 while (endp > path && *endp == '/')
3853 /* Find the start of the dir */
3854 while (endp > path && *endp != '/')
3857 /* Either the dir is "/" or there are no slashes */
3859 bname[0] = *endp == '/' ? '/' : '.';
3865 } while (endp > path && *endp == '/');
3868 if (endp - path + 2 > PATH_MAX)
3870 _rtld_error("Filename is too long: %s", path);
3874 strncpy(bname, path, endp - path + 1);
3875 bname[endp - path + 1] = '\0';
3880 rtld_dirname_abs(const char *path, char *base)
3884 if (realpath(path, base) == NULL)
3886 dbg("%s -> %s", path, base);
3887 last = strrchr(base, '/');
3896 linkmap_add(Obj_Entry *obj)
3898 struct link_map *l = &obj->linkmap;
3899 struct link_map *prev;
3901 obj->linkmap.l_name = obj->path;
3902 obj->linkmap.l_addr = obj->mapbase;
3903 obj->linkmap.l_ld = obj->dynamic;
3905 /* GDB needs load offset on MIPS to use the symbols */
3906 obj->linkmap.l_offs = obj->relocbase;
3909 if (r_debug.r_map == NULL) {
3915 * Scan to the end of the list, but not past the entry for the
3916 * dynamic linker, which we want to keep at the very end.
3918 for (prev = r_debug.r_map;
3919 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
3920 prev = prev->l_next)
3923 /* Link in the new entry. */
3925 l->l_next = prev->l_next;
3926 if (l->l_next != NULL)
3927 l->l_next->l_prev = l;
3932 linkmap_delete(Obj_Entry *obj)
3934 struct link_map *l = &obj->linkmap;
3936 if (l->l_prev == NULL) {
3937 if ((r_debug.r_map = l->l_next) != NULL)
3938 l->l_next->l_prev = NULL;
3942 if ((l->l_prev->l_next = l->l_next) != NULL)
3943 l->l_next->l_prev = l->l_prev;
3947 * Function for the debugger to set a breakpoint on to gain control.
3949 * The two parameters allow the debugger to easily find and determine
3950 * what the runtime loader is doing and to whom it is doing it.
3952 * When the loadhook trap is hit (r_debug_state, set at program
3953 * initialization), the arguments can be found on the stack:
3955 * +8 struct link_map *m
3956 * +4 struct r_debug *rd
3960 r_debug_state(struct r_debug* rd, struct link_map *m)
3963 * The following is a hack to force the compiler to emit calls to
3964 * this function, even when optimizing. If the function is empty,
3965 * the compiler is not obliged to emit any code for calls to it,
3966 * even when marked __noinline. However, gdb depends on those
3969 __compiler_membar();
3973 * A function called after init routines have completed. This can be used to
3974 * break before a program's entry routine is called, and can be used when
3975 * main is not available in the symbol table.
3978 _r_debug_postinit(struct link_map *m)
3981 /* See r_debug_state(). */
3982 __compiler_membar();
3986 release_object(Obj_Entry *obj)
3989 if (obj->holdcount > 0) {
3990 obj->unholdfree = true;
3993 munmap(obj->mapbase, obj->mapsize);
3994 linkmap_delete(obj);
3999 * Get address of the pointer variable in the main program.
4000 * Prefer non-weak symbol over the weak one.
4002 static const void **
4003 get_program_var_addr(const char *name, RtldLockState *lockstate)
4008 symlook_init(&req, name);
4009 req.lockstate = lockstate;
4010 donelist_init(&donelist);
4011 if (symlook_global(&req, &donelist) != 0)
4013 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
4014 return ((const void **)make_function_pointer(req.sym_out,
4016 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
4017 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
4019 return ((const void **)(req.defobj_out->relocbase +
4020 req.sym_out->st_value));
4024 * Set a pointer variable in the main program to the given value. This
4025 * is used to set key variables such as "environ" before any of the
4026 * init functions are called.
4029 set_program_var(const char *name, const void *value)
4033 if ((addr = get_program_var_addr(name, NULL)) != NULL) {
4034 dbg("\"%s\": *%p <-- %p", name, addr, value);
4040 * Search the global objects, including dependencies and main object,
4041 * for the given symbol.
4044 symlook_global(SymLook *req, DoneList *donelist)
4047 const Objlist_Entry *elm;
4050 symlook_init_from_req(&req1, req);
4052 /* Search all objects loaded at program start up. */
4053 if (req->defobj_out == NULL ||
4054 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
4055 res = symlook_list(&req1, &list_main, donelist);
4056 if (res == 0 && (req->defobj_out == NULL ||
4057 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4058 req->sym_out = req1.sym_out;
4059 req->defobj_out = req1.defobj_out;
4060 assert(req->defobj_out != NULL);
4064 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
4065 STAILQ_FOREACH(elm, &list_global, link) {
4066 if (req->defobj_out != NULL &&
4067 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
4069 res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
4070 if (res == 0 && (req->defobj_out == NULL ||
4071 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4072 req->sym_out = req1.sym_out;
4073 req->defobj_out = req1.defobj_out;
4074 assert(req->defobj_out != NULL);
4078 return (req->sym_out != NULL ? 0 : ESRCH);
4082 * Given a symbol name in a referencing object, find the corresponding
4083 * definition of the symbol. Returns a pointer to the symbol, or NULL if
4084 * no definition was found. Returns a pointer to the Obj_Entry of the
4085 * defining object via the reference parameter DEFOBJ_OUT.
4088 symlook_default(SymLook *req, const Obj_Entry *refobj)
4091 const Objlist_Entry *elm;
4095 donelist_init(&donelist);
4096 symlook_init_from_req(&req1, req);
4099 * Look first in the referencing object if linked symbolically,
4100 * and similarly handle protected symbols.
4102 res = symlook_obj(&req1, refobj);
4103 if (res == 0 && (refobj->symbolic ||
4104 ELF_ST_VISIBILITY(req1.sym_out->st_other) == STV_PROTECTED)) {
4105 req->sym_out = req1.sym_out;
4106 req->defobj_out = req1.defobj_out;
4107 assert(req->defobj_out != NULL);
4109 if (refobj->symbolic || req->defobj_out != NULL)
4110 donelist_check(&donelist, refobj);
4112 symlook_global(req, &donelist);
4114 /* Search all dlopened DAGs containing the referencing object. */
4115 STAILQ_FOREACH(elm, &refobj->dldags, link) {
4116 if (req->sym_out != NULL &&
4117 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
4119 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
4120 if (res == 0 && (req->sym_out == NULL ||
4121 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4122 req->sym_out = req1.sym_out;
4123 req->defobj_out = req1.defobj_out;
4124 assert(req->defobj_out != NULL);
4129 * Search the dynamic linker itself, and possibly resolve the
4130 * symbol from there. This is how the application links to
4131 * dynamic linker services such as dlopen.
4133 if (req->sym_out == NULL ||
4134 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
4135 res = symlook_obj(&req1, &obj_rtld);
4137 req->sym_out = req1.sym_out;
4138 req->defobj_out = req1.defobj_out;
4139 assert(req->defobj_out != NULL);
4143 return (req->sym_out != NULL ? 0 : ESRCH);
4147 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
4150 const Obj_Entry *defobj;
4151 const Objlist_Entry *elm;
4157 STAILQ_FOREACH(elm, objlist, link) {
4158 if (donelist_check(dlp, elm->obj))
4160 symlook_init_from_req(&req1, req);
4161 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
4162 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
4164 defobj = req1.defobj_out;
4165 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
4172 req->defobj_out = defobj;
4179 * Search the chain of DAGS cointed to by the given Needed_Entry
4180 * for a symbol of the given name. Each DAG is scanned completely
4181 * before advancing to the next one. Returns a pointer to the symbol,
4182 * or NULL if no definition was found.
4185 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
4188 const Needed_Entry *n;
4189 const Obj_Entry *defobj;
4195 symlook_init_from_req(&req1, req);
4196 for (n = needed; n != NULL; n = n->next) {
4197 if (n->obj == NULL ||
4198 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
4200 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
4202 defobj = req1.defobj_out;
4203 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
4209 req->defobj_out = defobj;
4216 * Search the symbol table of a single shared object for a symbol of
4217 * the given name and version, if requested. Returns a pointer to the
4218 * symbol, or NULL if no definition was found. If the object is
4219 * filter, return filtered symbol from filtee.
4221 * The symbol's hash value is passed in for efficiency reasons; that
4222 * eliminates many recomputations of the hash value.
4225 symlook_obj(SymLook *req, const Obj_Entry *obj)
4229 int flags, res, mres;
4232 * If there is at least one valid hash at this point, we prefer to
4233 * use the faster GNU version if available.
4235 if (obj->valid_hash_gnu)
4236 mres = symlook_obj1_gnu(req, obj);
4237 else if (obj->valid_hash_sysv)
4238 mres = symlook_obj1_sysv(req, obj);
4243 if (obj->needed_filtees != NULL) {
4244 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4245 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4246 donelist_init(&donelist);
4247 symlook_init_from_req(&req1, req);
4248 res = symlook_needed(&req1, obj->needed_filtees, &donelist);
4250 req->sym_out = req1.sym_out;
4251 req->defobj_out = req1.defobj_out;
4255 if (obj->needed_aux_filtees != NULL) {
4256 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4257 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4258 donelist_init(&donelist);
4259 symlook_init_from_req(&req1, req);
4260 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
4262 req->sym_out = req1.sym_out;
4263 req->defobj_out = req1.defobj_out;
4271 /* Symbol match routine common to both hash functions */
4273 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result,
4274 const unsigned long symnum)
4277 const Elf_Sym *symp;
4280 symp = obj->symtab + symnum;
4281 strp = obj->strtab + symp->st_name;
4283 switch (ELF_ST_TYPE(symp->st_info)) {
4289 if (symp->st_value == 0)
4293 if (symp->st_shndx != SHN_UNDEF)
4296 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
4297 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
4304 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
4307 if (req->ventry == NULL) {
4308 if (obj->versyms != NULL) {
4309 verndx = VER_NDX(obj->versyms[symnum]);
4310 if (verndx > obj->vernum) {
4312 "%s: symbol %s references wrong version %d",
4313 obj->path, obj->strtab + symnum, verndx);
4317 * If we are not called from dlsym (i.e. this
4318 * is a normal relocation from unversioned
4319 * binary), accept the symbol immediately if
4320 * it happens to have first version after this
4321 * shared object became versioned. Otherwise,
4322 * if symbol is versioned and not hidden,
4323 * remember it. If it is the only symbol with
4324 * this name exported by the shared object, it
4325 * will be returned as a match by the calling
4326 * function. If symbol is global (verndx < 2)
4327 * accept it unconditionally.
4329 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
4330 verndx == VER_NDX_GIVEN) {
4331 result->sym_out = symp;
4334 else if (verndx >= VER_NDX_GIVEN) {
4335 if ((obj->versyms[symnum] & VER_NDX_HIDDEN)
4337 if (result->vsymp == NULL)
4338 result->vsymp = symp;
4344 result->sym_out = symp;
4347 if (obj->versyms == NULL) {
4348 if (object_match_name(obj, req->ventry->name)) {
4349 _rtld_error("%s: object %s should provide version %s "
4350 "for symbol %s", obj_rtld.path, obj->path,
4351 req->ventry->name, obj->strtab + symnum);
4355 verndx = VER_NDX(obj->versyms[symnum]);
4356 if (verndx > obj->vernum) {
4357 _rtld_error("%s: symbol %s references wrong version %d",
4358 obj->path, obj->strtab + symnum, verndx);
4361 if (obj->vertab[verndx].hash != req->ventry->hash ||
4362 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
4364 * Version does not match. Look if this is a
4365 * global symbol and if it is not hidden. If
4366 * global symbol (verndx < 2) is available,
4367 * use it. Do not return symbol if we are
4368 * called by dlvsym, because dlvsym looks for
4369 * a specific version and default one is not
4370 * what dlvsym wants.
4372 if ((req->flags & SYMLOOK_DLSYM) ||
4373 (verndx >= VER_NDX_GIVEN) ||
4374 (obj->versyms[symnum] & VER_NDX_HIDDEN))
4378 result->sym_out = symp;
4383 * Search for symbol using SysV hash function.
4384 * obj->buckets is known not to be NULL at this point; the test for this was
4385 * performed with the obj->valid_hash_sysv assignment.
4388 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj)
4390 unsigned long symnum;
4391 Sym_Match_Result matchres;
4393 matchres.sym_out = NULL;
4394 matchres.vsymp = NULL;
4395 matchres.vcount = 0;
4397 for (symnum = obj->buckets[req->hash % obj->nbuckets];
4398 symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
4399 if (symnum >= obj->nchains)
4400 return (ESRCH); /* Bad object */
4402 if (matched_symbol(req, obj, &matchres, symnum)) {
4403 req->sym_out = matchres.sym_out;
4404 req->defobj_out = obj;
4408 if (matchres.vcount == 1) {
4409 req->sym_out = matchres.vsymp;
4410 req->defobj_out = obj;
4416 /* Search for symbol using GNU hash function */
4418 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj)
4420 Elf_Addr bloom_word;
4421 const Elf32_Word *hashval;
4423 Sym_Match_Result matchres;
4424 unsigned int h1, h2;
4425 unsigned long symnum;
4427 matchres.sym_out = NULL;
4428 matchres.vsymp = NULL;
4429 matchres.vcount = 0;
4431 /* Pick right bitmask word from Bloom filter array */
4432 bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) &
4433 obj->maskwords_bm_gnu];
4435 /* Calculate modulus word size of gnu hash and its derivative */
4436 h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1);
4437 h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1));
4439 /* Filter out the "definitely not in set" queries */
4440 if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0)
4443 /* Locate hash chain and corresponding value element*/
4444 bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu];
4447 hashval = &obj->chain_zero_gnu[bucket];
4449 if (((*hashval ^ req->hash_gnu) >> 1) == 0) {
4450 symnum = hashval - obj->chain_zero_gnu;
4451 if (matched_symbol(req, obj, &matchres, symnum)) {
4452 req->sym_out = matchres.sym_out;
4453 req->defobj_out = obj;
4457 } while ((*hashval++ & 1) == 0);
4458 if (matchres.vcount == 1) {
4459 req->sym_out = matchres.vsymp;
4460 req->defobj_out = obj;
4467 trace_loaded_objects(Obj_Entry *obj)
4469 char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
4472 if ((main_local = getenv(_LD("TRACE_LOADED_OBJECTS_PROGNAME"))) == NULL)
4475 if ((fmt1 = getenv(_LD("TRACE_LOADED_OBJECTS_FMT1"))) == NULL)
4476 fmt1 = "\t%o => %p (%x)\n";
4478 if ((fmt2 = getenv(_LD("TRACE_LOADED_OBJECTS_FMT2"))) == NULL)
4479 fmt2 = "\t%o (%x)\n";
4481 list_containers = getenv(_LD("TRACE_LOADED_OBJECTS_ALL"));
4483 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
4484 Needed_Entry *needed;
4490 if (list_containers && obj->needed != NULL)
4491 rtld_printf("%s:\n", obj->path);
4492 for (needed = obj->needed; needed; needed = needed->next) {
4493 if (needed->obj != NULL) {
4494 if (needed->obj->traced && !list_containers)
4496 needed->obj->traced = true;
4497 path = needed->obj->path;
4501 name = (char *)obj->strtab + needed->name;
4502 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
4504 fmt = is_lib ? fmt1 : fmt2;
4505 while ((c = *fmt++) != '\0') {
4531 rtld_putstr(main_local);
4534 rtld_putstr(obj_main->path);
4541 rtld_printf("%d", sodp->sod_major);
4544 rtld_printf("%d", sodp->sod_minor);
4551 rtld_printf("%p", needed->obj ? needed->obj->mapbase :
4564 * Unload a dlopened object and its dependencies from memory and from
4565 * our data structures. It is assumed that the DAG rooted in the
4566 * object has already been unreferenced, and that the object has a
4567 * reference count of 0.
4570 unload_object(Obj_Entry *root, RtldLockState *lockstate)
4572 Obj_Entry marker, *obj, *next;
4574 assert(root->refcount == 0);
4577 * Pass over the DAG removing unreferenced objects from
4578 * appropriate lists.
4580 unlink_object(root);
4582 /* Unmap all objects that are no longer referenced. */
4583 for (obj = TAILQ_FIRST(&obj_list); obj != NULL; obj = next) {
4584 next = TAILQ_NEXT(obj, next);
4585 if (obj->marker || obj->refcount != 0)
4587 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase,
4588 obj->mapsize, 0, obj->path);
4589 dbg("unloading \"%s\"", obj->path);
4591 * Unlink the object now to prevent new references from
4592 * being acquired while the bind lock is dropped in
4593 * recursive dlclose() invocations.
4595 TAILQ_REMOVE(&obj_list, obj, next);
4598 if (obj->filtees_loaded) {
4600 init_marker(&marker);
4601 TAILQ_INSERT_BEFORE(next, &marker, next);
4602 unload_filtees(obj, lockstate);
4603 next = TAILQ_NEXT(&marker, next);
4604 TAILQ_REMOVE(&obj_list, &marker, next);
4606 unload_filtees(obj, lockstate);
4608 release_object(obj);
4613 unlink_object(Obj_Entry *root)
4617 if (root->refcount == 0) {
4618 /* Remove the object from the RTLD_GLOBAL list. */
4619 objlist_remove(&list_global, root);
4621 /* Remove the object from all objects' DAG lists. */
4622 STAILQ_FOREACH(elm, &root->dagmembers, link) {
4623 objlist_remove(&elm->obj->dldags, root);
4624 if (elm->obj != root)
4625 unlink_object(elm->obj);
4631 ref_dag(Obj_Entry *root)
4635 assert(root->dag_inited);
4636 STAILQ_FOREACH(elm, &root->dagmembers, link)
4637 elm->obj->refcount++;
4641 unref_dag(Obj_Entry *root)
4645 assert(root->dag_inited);
4646 STAILQ_FOREACH(elm, &root->dagmembers, link)
4647 elm->obj->refcount--;
4651 * Common code for MD __tls_get_addr().
4653 static void *tls_get_addr_slow(Elf_Addr **, int, size_t) __noinline;
4655 tls_get_addr_slow(Elf_Addr **dtvp, int index, size_t offset)
4657 Elf_Addr *newdtv, *dtv;
4658 RtldLockState lockstate;
4662 /* Check dtv generation in case new modules have arrived */
4663 if (dtv[0] != tls_dtv_generation) {
4664 wlock_acquire(rtld_bind_lock, &lockstate);
4665 newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4667 if (to_copy > tls_max_index)
4668 to_copy = tls_max_index;
4669 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
4670 newdtv[0] = tls_dtv_generation;
4671 newdtv[1] = tls_max_index;
4673 lock_release(rtld_bind_lock, &lockstate);
4674 dtv = *dtvp = newdtv;
4677 /* Dynamically allocate module TLS if necessary */
4678 if (dtv[index + 1] == 0) {
4679 /* Signal safe, wlock will block out signals. */
4680 wlock_acquire(rtld_bind_lock, &lockstate);
4681 if (!dtv[index + 1])
4682 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
4683 lock_release(rtld_bind_lock, &lockstate);
4685 return ((void *)(dtv[index + 1] + offset));
4689 tls_get_addr_common(Elf_Addr **dtvp, int index, size_t offset)
4694 /* Check dtv generation in case new modules have arrived */
4695 if (__predict_true(dtv[0] == tls_dtv_generation &&
4696 dtv[index + 1] != 0))
4697 return ((void *)(dtv[index + 1] + offset));
4698 return (tls_get_addr_slow(dtvp, index, offset));
4701 #if defined(__aarch64__) || defined(__arm__) || defined(__mips__) || \
4702 defined(__powerpc__) || defined(__riscv)
4705 * Return pointer to allocated TLS block
4708 get_tls_block_ptr(void *tcb, size_t tcbsize)
4710 size_t extra_size, post_size, pre_size, tls_block_size;
4711 size_t tls_init_align;
4713 tls_init_align = MAX(obj_main->tlsalign, 1);
4715 /* Compute fragments sizes. */
4716 extra_size = tcbsize - TLS_TCB_SIZE;
4717 post_size = calculate_tls_post_size(tls_init_align);
4718 tls_block_size = tcbsize + post_size;
4719 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size;
4721 return ((char *)tcb - pre_size - extra_size);
4725 * Allocate Static TLS using the Variant I method.
4727 * For details on the layout, see lib/libc/gen/tls.c.
4729 * NB: rtld's tls_static_space variable includes TLS_TCB_SIZE and post_size as
4730 * it is based on tls_last_offset, and TLS offsets here are really TCB
4731 * offsets, whereas libc's tls_static_space is just the executable's static
4735 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
4739 Elf_Addr *dtv, **tcb;
4742 size_t extra_size, maxalign, post_size, pre_size, tls_block_size;
4743 size_t tls_init_align;
4745 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
4748 assert(tcbsize >= TLS_TCB_SIZE);
4749 maxalign = MAX(tcbalign, tls_static_max_align);
4750 tls_init_align = MAX(obj_main->tlsalign, 1);
4752 /* Compute fragmets sizes. */
4753 extra_size = tcbsize - TLS_TCB_SIZE;
4754 post_size = calculate_tls_post_size(tls_init_align);
4755 tls_block_size = tcbsize + post_size;
4756 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size;
4757 tls_block_size += pre_size + tls_static_space - TLS_TCB_SIZE - post_size;
4759 /* Allocate whole TLS block */
4760 tls_block = malloc_aligned(tls_block_size, maxalign);
4761 tcb = (Elf_Addr **)(tls_block + pre_size + extra_size);
4763 if (oldtcb != NULL) {
4764 memcpy(tls_block, get_tls_block_ptr(oldtcb, tcbsize),
4766 free_aligned(get_tls_block_ptr(oldtcb, tcbsize));
4768 /* Adjust the DTV. */
4770 for (i = 0; i < dtv[1]; i++) {
4771 if (dtv[i+2] >= (Elf_Addr)oldtcb &&
4772 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
4773 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tcb;
4777 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4779 dtv[0] = tls_dtv_generation;
4780 dtv[1] = tls_max_index;
4782 for (obj = globallist_curr(objs); obj != NULL;
4783 obj = globallist_next(obj)) {
4784 if (obj->tlsoffset > 0) {
4785 addr = (Elf_Addr)tcb + obj->tlsoffset;
4786 if (obj->tlsinitsize > 0)
4787 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4788 if (obj->tlssize > obj->tlsinitsize)
4789 memset((void*) (addr + obj->tlsinitsize), 0,
4790 obj->tlssize - obj->tlsinitsize);
4791 dtv[obj->tlsindex + 1] = addr;
4800 free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
4803 Elf_Addr tlsstart, tlsend;
4805 size_t dtvsize, i, tls_init_align;
4807 assert(tcbsize >= TLS_TCB_SIZE);
4808 tls_init_align = MAX(obj_main->tlsalign, 1);
4810 /* Compute fragments sizes. */
4811 post_size = calculate_tls_post_size(tls_init_align);
4813 tlsstart = (Elf_Addr)tcb + TLS_TCB_SIZE + post_size;
4814 tlsend = (Elf_Addr)tcb + tls_static_space;
4816 dtv = *(Elf_Addr **)tcb;
4818 for (i = 0; i < dtvsize; i++) {
4819 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
4820 free((void*)dtv[i+2]);
4824 free_aligned(get_tls_block_ptr(tcb, tcbsize));
4829 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__)
4832 * Allocate Static TLS using the Variant II method.
4835 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
4838 size_t size, ralign;
4840 Elf_Addr *dtv, *olddtv;
4841 Elf_Addr segbase, oldsegbase, addr;
4845 if (tls_static_max_align > ralign)
4846 ralign = tls_static_max_align;
4847 size = round(tls_static_space, ralign) + round(tcbsize, ralign);
4849 assert(tcbsize >= 2*sizeof(Elf_Addr));
4850 tls = malloc_aligned(size, ralign);
4851 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4853 segbase = (Elf_Addr)(tls + round(tls_static_space, ralign));
4854 ((Elf_Addr*)segbase)[0] = segbase;
4855 ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
4857 dtv[0] = tls_dtv_generation;
4858 dtv[1] = tls_max_index;
4862 * Copy the static TLS block over whole.
4864 oldsegbase = (Elf_Addr) oldtls;
4865 memcpy((void *)(segbase - tls_static_space),
4866 (const void *)(oldsegbase - tls_static_space),
4870 * If any dynamic TLS blocks have been created tls_get_addr(),
4873 olddtv = ((Elf_Addr**)oldsegbase)[1];
4874 for (i = 0; i < olddtv[1]; i++) {
4875 if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
4876 dtv[i+2] = olddtv[i+2];
4882 * We assume that this block was the one we created with
4883 * allocate_initial_tls().
4885 free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
4887 for (obj = objs; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
4888 if (obj->marker || obj->tlsoffset == 0)
4890 addr = segbase - obj->tlsoffset;
4891 memset((void*) (addr + obj->tlsinitsize),
4892 0, obj->tlssize - obj->tlsinitsize);
4894 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4895 dtv[obj->tlsindex + 1] = addr;
4899 return (void*) segbase;
4903 free_tls(void *tls, size_t tcbsize, size_t tcbalign)
4906 size_t size, ralign;
4908 Elf_Addr tlsstart, tlsend;
4911 * Figure out the size of the initial TLS block so that we can
4912 * find stuff which ___tls_get_addr() allocated dynamically.
4915 if (tls_static_max_align > ralign)
4916 ralign = tls_static_max_align;
4917 size = round(tls_static_space, ralign);
4919 dtv = ((Elf_Addr**)tls)[1];
4921 tlsend = (Elf_Addr) tls;
4922 tlsstart = tlsend - size;
4923 for (i = 0; i < dtvsize; i++) {
4924 if (dtv[i + 2] != 0 && (dtv[i + 2] < tlsstart || dtv[i + 2] > tlsend)) {
4925 free_aligned((void *)dtv[i + 2]);
4929 free_aligned((void *)tlsstart);
4936 * Allocate TLS block for module with given index.
4939 allocate_module_tls(int index)
4944 TAILQ_FOREACH(obj, &obj_list, next) {
4947 if (obj->tlsindex == index)
4951 _rtld_error("Can't find module with TLS index %d", index);
4955 p = malloc_aligned(obj->tlssize, obj->tlsalign);
4956 memcpy(p, obj->tlsinit, obj->tlsinitsize);
4957 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
4963 allocate_tls_offset(Obj_Entry *obj)
4970 if (obj->tlssize == 0) {
4971 obj->tls_done = true;
4975 if (tls_last_offset == 0)
4976 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
4978 off = calculate_tls_offset(tls_last_offset, tls_last_size,
4979 obj->tlssize, obj->tlsalign);
4982 * If we have already fixed the size of the static TLS block, we
4983 * must stay within that size. When allocating the static TLS, we
4984 * leave a small amount of space spare to be used for dynamically
4985 * loading modules which use static TLS.
4987 if (tls_static_space != 0) {
4988 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
4990 } else if (obj->tlsalign > tls_static_max_align) {
4991 tls_static_max_align = obj->tlsalign;
4994 tls_last_offset = obj->tlsoffset = off;
4995 tls_last_size = obj->tlssize;
4996 obj->tls_done = true;
5002 free_tls_offset(Obj_Entry *obj)
5006 * If we were the last thing to allocate out of the static TLS
5007 * block, we give our space back to the 'allocator'. This is a
5008 * simplistic workaround to allow libGL.so.1 to be loaded and
5009 * unloaded multiple times.
5011 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
5012 == calculate_tls_end(tls_last_offset, tls_last_size)) {
5013 tls_last_offset -= obj->tlssize;
5019 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
5022 RtldLockState lockstate;
5024 wlock_acquire(rtld_bind_lock, &lockstate);
5025 ret = allocate_tls(globallist_curr(TAILQ_FIRST(&obj_list)), oldtls,
5027 lock_release(rtld_bind_lock, &lockstate);
5032 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
5034 RtldLockState lockstate;
5036 wlock_acquire(rtld_bind_lock, &lockstate);
5037 free_tls(tcb, tcbsize, tcbalign);
5038 lock_release(rtld_bind_lock, &lockstate);
5042 object_add_name(Obj_Entry *obj, const char *name)
5048 entry = malloc(sizeof(Name_Entry) + len);
5050 if (entry != NULL) {
5051 strcpy(entry->name, name);
5052 STAILQ_INSERT_TAIL(&obj->names, entry, link);
5057 object_match_name(const Obj_Entry *obj, const char *name)
5061 STAILQ_FOREACH(entry, &obj->names, link) {
5062 if (strcmp(name, entry->name) == 0)
5069 locate_dependency(const Obj_Entry *obj, const char *name)
5071 const Objlist_Entry *entry;
5072 const Needed_Entry *needed;
5074 STAILQ_FOREACH(entry, &list_main, link) {
5075 if (object_match_name(entry->obj, name))
5079 for (needed = obj->needed; needed != NULL; needed = needed->next) {
5080 if (strcmp(obj->strtab + needed->name, name) == 0 ||
5081 (needed->obj != NULL && object_match_name(needed->obj, name))) {
5083 * If there is DT_NEEDED for the name we are looking for,
5084 * we are all set. Note that object might not be found if
5085 * dependency was not loaded yet, so the function can
5086 * return NULL here. This is expected and handled
5087 * properly by the caller.
5089 return (needed->obj);
5092 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
5098 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
5099 const Elf_Vernaux *vna)
5101 const Elf_Verdef *vd;
5102 const char *vername;
5104 vername = refobj->strtab + vna->vna_name;
5105 vd = depobj->verdef;
5107 _rtld_error("%s: version %s required by %s not defined",
5108 depobj->path, vername, refobj->path);
5112 if (vd->vd_version != VER_DEF_CURRENT) {
5113 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
5114 depobj->path, vd->vd_version);
5117 if (vna->vna_hash == vd->vd_hash) {
5118 const Elf_Verdaux *aux = (const Elf_Verdaux *)
5119 ((char *)vd + vd->vd_aux);
5120 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
5123 if (vd->vd_next == 0)
5125 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
5127 if (vna->vna_flags & VER_FLG_WEAK)
5129 _rtld_error("%s: version %s required by %s not found",
5130 depobj->path, vername, refobj->path);
5135 rtld_verify_object_versions(Obj_Entry *obj)
5137 const Elf_Verneed *vn;
5138 const Elf_Verdef *vd;
5139 const Elf_Verdaux *vda;
5140 const Elf_Vernaux *vna;
5141 const Obj_Entry *depobj;
5142 int maxvernum, vernum;
5144 if (obj->ver_checked)
5146 obj->ver_checked = true;
5150 * Walk over defined and required version records and figure out
5151 * max index used by any of them. Do very basic sanity checking
5155 while (vn != NULL) {
5156 if (vn->vn_version != VER_NEED_CURRENT) {
5157 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
5158 obj->path, vn->vn_version);
5161 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
5163 vernum = VER_NEED_IDX(vna->vna_other);
5164 if (vernum > maxvernum)
5166 if (vna->vna_next == 0)
5168 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
5170 if (vn->vn_next == 0)
5172 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
5176 while (vd != NULL) {
5177 if (vd->vd_version != VER_DEF_CURRENT) {
5178 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
5179 obj->path, vd->vd_version);
5182 vernum = VER_DEF_IDX(vd->vd_ndx);
5183 if (vernum > maxvernum)
5185 if (vd->vd_next == 0)
5187 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
5194 * Store version information in array indexable by version index.
5195 * Verify that object version requirements are satisfied along the
5198 obj->vernum = maxvernum + 1;
5199 obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry));
5202 while (vd != NULL) {
5203 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
5204 vernum = VER_DEF_IDX(vd->vd_ndx);
5205 assert(vernum <= maxvernum);
5206 vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
5207 obj->vertab[vernum].hash = vd->vd_hash;
5208 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
5209 obj->vertab[vernum].file = NULL;
5210 obj->vertab[vernum].flags = 0;
5212 if (vd->vd_next == 0)
5214 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
5218 while (vn != NULL) {
5219 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
5222 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
5224 if (check_object_provided_version(obj, depobj, vna))
5226 vernum = VER_NEED_IDX(vna->vna_other);
5227 assert(vernum <= maxvernum);
5228 obj->vertab[vernum].hash = vna->vna_hash;
5229 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
5230 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
5231 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
5232 VER_INFO_HIDDEN : 0;
5233 if (vna->vna_next == 0)
5235 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
5237 if (vn->vn_next == 0)
5239 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
5245 rtld_verify_versions(const Objlist *objlist)
5247 Objlist_Entry *entry;
5251 STAILQ_FOREACH(entry, objlist, link) {
5253 * Skip dummy objects or objects that have their version requirements
5256 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
5258 if (rtld_verify_object_versions(entry->obj) == -1) {
5260 if (ld_tracing == NULL)
5264 if (rc == 0 || ld_tracing != NULL)
5265 rc = rtld_verify_object_versions(&obj_rtld);
5270 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
5275 vernum = VER_NDX(obj->versyms[symnum]);
5276 if (vernum >= obj->vernum) {
5277 _rtld_error("%s: symbol %s has wrong verneed value %d",
5278 obj->path, obj->strtab + symnum, vernum);
5279 } else if (obj->vertab[vernum].hash != 0) {
5280 return &obj->vertab[vernum];
5287 _rtld_get_stack_prot(void)
5290 return (stack_prot);
5294 _rtld_is_dlopened(void *arg)
5297 RtldLockState lockstate;
5300 rlock_acquire(rtld_bind_lock, &lockstate);
5303 obj = obj_from_addr(arg);
5305 _rtld_error("No shared object contains address");
5306 lock_release(rtld_bind_lock, &lockstate);
5309 res = obj->dlopened ? 1 : 0;
5310 lock_release(rtld_bind_lock, &lockstate);
5315 obj_remap_relro(Obj_Entry *obj, int prot)
5318 if (obj->relro_size > 0 && mprotect(obj->relro_page, obj->relro_size,
5320 _rtld_error("%s: Cannot set relro protection to %#x: %s",
5321 obj->path, prot, rtld_strerror(errno));
5328 obj_disable_relro(Obj_Entry *obj)
5331 return (obj_remap_relro(obj, PROT_READ | PROT_WRITE));
5335 obj_enforce_relro(Obj_Entry *obj)
5338 return (obj_remap_relro(obj, PROT_READ));
5342 map_stacks_exec(RtldLockState *lockstate)
5344 void (*thr_map_stacks_exec)(void);
5346 if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
5348 thr_map_stacks_exec = (void (*)(void))(uintptr_t)
5349 get_program_var_addr("__pthread_map_stacks_exec", lockstate);
5350 if (thr_map_stacks_exec != NULL) {
5351 stack_prot |= PROT_EXEC;
5352 thr_map_stacks_exec();
5357 symlook_init(SymLook *dst, const char *name)
5360 bzero(dst, sizeof(*dst));
5362 dst->hash = elf_hash(name);
5363 dst->hash_gnu = gnu_hash(name);
5367 symlook_init_from_req(SymLook *dst, const SymLook *src)
5370 dst->name = src->name;
5371 dst->hash = src->hash;
5372 dst->hash_gnu = src->hash_gnu;
5373 dst->ventry = src->ventry;
5374 dst->flags = src->flags;
5375 dst->defobj_out = NULL;
5376 dst->sym_out = NULL;
5377 dst->lockstate = src->lockstate;
5381 open_binary_fd(const char *argv0, bool search_in_path)
5383 char *pathenv, *pe, binpath[PATH_MAX];
5386 if (search_in_path && strchr(argv0, '/') == NULL) {
5387 pathenv = getenv("PATH");
5388 if (pathenv == NULL) {
5389 _rtld_error("-p and no PATH environment variable");
5392 pathenv = strdup(pathenv);
5393 if (pathenv == NULL) {
5394 _rtld_error("Cannot allocate memory");
5399 while ((pe = strsep(&pathenv, ":")) != NULL) {
5400 if (strlcpy(binpath, pe, sizeof(binpath)) >=
5403 if (binpath[0] != '\0' &&
5404 strlcat(binpath, "/", sizeof(binpath)) >=
5407 if (strlcat(binpath, argv0, sizeof(binpath)) >=
5410 fd = open(binpath, O_RDONLY | O_CLOEXEC | O_VERIFY);
5411 if (fd != -1 || errno != ENOENT)
5416 fd = open(argv0, O_RDONLY | O_CLOEXEC | O_VERIFY);
5420 _rtld_error("Cannot open %s: %s", argv0, rtld_strerror(errno));
5427 * Parse a set of command-line arguments.
5430 parse_args(char* argv[], int argc, bool *use_pathp, int *fdp)
5433 int fd, i, j, arglen;
5436 dbg("Parsing command-line arguments");
5440 for (i = 1; i < argc; i++ ) {
5442 dbg("argv[%d]: '%s'", i, arg);
5445 * rtld arguments end with an explicit "--" or with the first
5446 * non-prefixed argument.
5448 if (strcmp(arg, "--") == 0) {
5456 * All other arguments are single-character options that can
5457 * be combined, so we need to search through `arg` for them.
5459 arglen = strlen(arg);
5460 for (j = 1; j < arglen; j++) {
5463 print_usage(argv[0]);
5465 } else if (opt == 'f') {
5467 * -f XX can be used to specify a descriptor for the
5468 * binary named at the command line (i.e., the later
5469 * argument will specify the process name but the
5470 * descriptor is what will actually be executed)
5472 if (j != arglen - 1) {
5473 /* -f must be the last option in, e.g., -abcf */
5474 _rtld_error("Invalid options: %s", arg);
5478 fd = parse_integer(argv[i]);
5480 _rtld_error("Invalid file descriptor: '%s'",
5486 } else if (opt == 'p') {
5489 _rtld_error("Invalid argument: '%s'", arg);
5490 print_usage(argv[0]);
5500 * Parse a file descriptor number without pulling in more of libc (e.g. atoi).
5503 parse_integer(const char *str)
5505 static const int RADIX = 10; /* XXXJA: possibly support hex? */
5512 for (c = *str; c != '\0'; c = *++str) {
5513 if (c < '0' || c > '9')
5520 /* Make sure we actually parsed something. */
5527 print_usage(const char *argv0)
5530 rtld_printf("Usage: %s [-h] [-f <FD>] [--] <binary> [<args>]\n"
5533 " -h Display this help message\n"
5534 " -p Search in PATH for named binary\n"
5535 " -f <FD> Execute <FD> instead of searching for <binary>\n"
5536 " -- End of RTLD options\n"
5537 " <binary> Name of process to execute\n"
5538 " <args> Arguments to the executed process\n", argv0);
5542 * Overrides for libc_pic-provided functions.
5546 __getosreldate(void)
5556 oid[1] = KERN_OSRELDATE;
5558 len = sizeof(osrel);
5559 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
5560 if (error == 0 && osrel > 0 && len == sizeof(osrel))
5572 void (*__cleanup)(void);
5573 int __isthreaded = 0;
5574 int _thread_autoinit_dummy_decl = 1;
5577 * No unresolved symbols for rtld.
5580 __pthread_cxa_finalize(struct dl_phdr_info *a)
5585 rtld_strerror(int errnum)
5588 if (errnum < 0 || errnum >= sys_nerr)
5589 return ("Unknown error");
5590 return (sys_errlist[errnum]);
5594 * No ifunc relocations.
5597 memset(void *dest, int c, size_t len)
5601 for (i = 0; i < len; i++)
5602 ((char *)dest)[i] = c;
5607 bzero(void *dest, size_t len)
5611 for (i = 0; i < len; i++)
5612 ((char *)dest)[i] = 0;