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_malloc.h"
70 #include "rtld_utrace.h"
74 typedef void (*func_ptr_type)(void);
75 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg);
78 /* Variables that cannot be static: */
79 extern struct r_debug r_debug; /* For GDB */
80 extern int _thread_autoinit_dummy_decl;
81 extern char* __progname;
82 extern void (*__cleanup)(void);
86 * Function declarations.
88 static const char *basename(const char *);
89 static void digest_dynamic1(Obj_Entry *, int, const Elf_Dyn **,
90 const Elf_Dyn **, const Elf_Dyn **);
91 static bool digest_dynamic2(Obj_Entry *, const Elf_Dyn *, const Elf_Dyn *,
93 static bool digest_dynamic(Obj_Entry *, int);
94 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
95 static void distribute_static_tls(Objlist *, RtldLockState *);
96 static Obj_Entry *dlcheck(void *);
97 static int dlclose_locked(void *, RtldLockState *);
98 static Obj_Entry *dlopen_object(const char *name, int fd, Obj_Entry *refobj,
99 int lo_flags, int mode, RtldLockState *lockstate);
100 static Obj_Entry *do_load_object(int, const char *, char *, struct stat *, int);
101 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
102 static bool donelist_check(DoneList *, const Obj_Entry *);
103 static void errmsg_restore(char *);
104 static char *errmsg_save(void);
105 static void *fill_search_info(const char *, size_t, void *);
106 static char *find_library(const char *, const Obj_Entry *, int *);
107 static const char *gethints(bool);
108 static void hold_object(Obj_Entry *);
109 static void unhold_object(Obj_Entry *);
110 static void init_dag(Obj_Entry *);
111 static void init_marker(Obj_Entry *);
112 static void init_pagesizes(Elf_Auxinfo **aux_info);
113 static void init_rtld(caddr_t, Elf_Auxinfo **);
114 static void initlist_add_neededs(Needed_Entry *, Objlist *);
115 static void initlist_add_objects(Obj_Entry *, Obj_Entry *, Objlist *);
116 static int initlist_objects_ifunc(Objlist *, bool, int, RtldLockState *);
117 static void linkmap_add(Obj_Entry *);
118 static void linkmap_delete(Obj_Entry *);
119 static void load_filtees(Obj_Entry *, int flags, RtldLockState *);
120 static void unload_filtees(Obj_Entry *, RtldLockState *);
121 static int load_needed_objects(Obj_Entry *, int);
122 static int load_preload_objects(void);
123 static Obj_Entry *load_object(const char *, int fd, const Obj_Entry *, int);
124 static void map_stacks_exec(RtldLockState *);
125 static int obj_disable_relro(Obj_Entry *);
126 static int obj_enforce_relro(Obj_Entry *);
127 static Obj_Entry *obj_from_addr(const void *);
128 static void objlist_call_fini(Objlist *, Obj_Entry *, RtldLockState *);
129 static void objlist_call_init(Objlist *, RtldLockState *);
130 static void objlist_clear(Objlist *);
131 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
132 static void objlist_init(Objlist *);
133 static void objlist_push_head(Objlist *, Obj_Entry *);
134 static void objlist_push_tail(Objlist *, Obj_Entry *);
135 static void objlist_put_after(Objlist *, Obj_Entry *, Obj_Entry *);
136 static void objlist_remove(Objlist *, Obj_Entry *);
137 static int open_binary_fd(const char *argv0, bool search_in_path,
138 const char **binpath_res);
139 static int parse_args(char* argv[], int argc, bool *use_pathp, int *fdp);
140 static int parse_integer(const char *);
141 static void *path_enumerate(const char *, path_enum_proc, const char *, void *);
142 static void print_usage(const char *argv0);
143 static void release_object(Obj_Entry *);
144 static int relocate_object_dag(Obj_Entry *root, bool bind_now,
145 Obj_Entry *rtldobj, int flags, RtldLockState *lockstate);
146 static int relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
147 int flags, RtldLockState *lockstate);
148 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, int,
150 static int resolve_object_ifunc(Obj_Entry *, bool, int, RtldLockState *);
151 static int rtld_dirname(const char *, char *);
152 static int rtld_dirname_abs(const char *, char *);
153 static void *rtld_dlopen(const char *name, int fd, int mode);
154 static void rtld_exit(void);
155 static void rtld_nop_exit(void);
156 static char *search_library_path(const char *, const char *, const char *,
158 static char *search_library_pathfds(const char *, const char *, int *);
159 static const void **get_program_var_addr(const char *, RtldLockState *);
160 static void set_program_var(const char *, const void *);
161 static int symlook_default(SymLook *, const Obj_Entry *refobj);
162 static int symlook_global(SymLook *, DoneList *);
163 static void symlook_init_from_req(SymLook *, const SymLook *);
164 static int symlook_list(SymLook *, const Objlist *, DoneList *);
165 static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *);
166 static int symlook_obj1_sysv(SymLook *, const Obj_Entry *);
167 static int symlook_obj1_gnu(SymLook *, const Obj_Entry *);
168 static void trace_loaded_objects(Obj_Entry *);
169 static void unlink_object(Obj_Entry *);
170 static void unload_object(Obj_Entry *, RtldLockState *lockstate);
171 static void unref_dag(Obj_Entry *);
172 static void ref_dag(Obj_Entry *);
173 static char *origin_subst_one(Obj_Entry *, char *, const char *,
175 static char *origin_subst(Obj_Entry *, const char *);
176 static bool obj_resolve_origin(Obj_Entry *obj);
177 static void preinit_main(void);
178 static int rtld_verify_versions(const Objlist *);
179 static int rtld_verify_object_versions(Obj_Entry *);
180 static void object_add_name(Obj_Entry *, const char *);
181 static int object_match_name(const Obj_Entry *, const char *);
182 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
183 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
184 struct dl_phdr_info *phdr_info);
185 static uint32_t gnu_hash(const char *);
186 static bool matched_symbol(SymLook *, const Obj_Entry *, Sym_Match_Result *,
187 const unsigned long);
189 void r_debug_state(struct r_debug *, struct link_map *) __noinline __exported;
190 void _r_debug_postinit(struct link_map *) __noinline __exported;
192 int __sys_openat(int, const char *, int, ...);
197 static char *error_message; /* Message for dlerror(), or NULL */
198 struct r_debug r_debug __exported; /* for GDB; */
199 static bool libmap_disable; /* Disable libmap */
200 static bool ld_loadfltr; /* Immediate filters processing */
201 static char *libmap_override; /* Maps to use in addition to libmap.conf */
202 static bool trust; /* False for setuid and setgid programs */
203 static bool dangerous_ld_env; /* True if environment variables have been
204 used to affect the libraries loaded */
205 bool ld_bind_not; /* Disable PLT update */
206 static char *ld_bind_now; /* Environment variable for immediate binding */
207 static char *ld_debug; /* Environment variable for debugging */
208 static char *ld_library_path; /* Environment variable for search path */
209 static char *ld_library_dirs; /* Environment variable for library descriptors */
210 static char *ld_preload; /* Environment variable for libraries to
212 static const char *ld_elf_hints_path; /* Environment variable for alternative hints path */
213 static const char *ld_tracing; /* Called from ldd to print libs */
214 static char *ld_utrace; /* Use utrace() to log events. */
215 static struct obj_entry_q obj_list; /* Queue of all loaded objects */
216 static Obj_Entry *obj_main; /* The main program shared object */
217 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
218 static unsigned int obj_count; /* Number of objects in obj_list */
219 static unsigned int obj_loads; /* Number of loads of objects (gen count) */
221 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
222 STAILQ_HEAD_INITIALIZER(list_global);
223 static Objlist list_main = /* Objects loaded at program startup */
224 STAILQ_HEAD_INITIALIZER(list_main);
225 static Objlist list_fini = /* Objects needing fini() calls */
226 STAILQ_HEAD_INITIALIZER(list_fini);
228 Elf_Sym sym_zero; /* For resolving undefined weak refs. */
230 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
232 extern Elf_Dyn _DYNAMIC;
233 #pragma weak _DYNAMIC
235 int dlclose(void *) __exported;
236 char *dlerror(void) __exported;
237 void *dlopen(const char *, int) __exported;
238 void *fdlopen(int, int) __exported;
239 void *dlsym(void *, const char *) __exported;
240 dlfunc_t dlfunc(void *, const char *) __exported;
241 void *dlvsym(void *, const char *, const char *) __exported;
242 int dladdr(const void *, Dl_info *) __exported;
243 void dllockinit(void *, void *(*)(void *), void (*)(void *), void (*)(void *),
244 void (*)(void *), void (*)(void *), void (*)(void *)) __exported;
245 int dlinfo(void *, int , void *) __exported;
246 int dl_iterate_phdr(__dl_iterate_hdr_callback, void *) __exported;
247 int _rtld_addr_phdr(const void *, struct dl_phdr_info *) __exported;
248 int _rtld_get_stack_prot(void) __exported;
249 int _rtld_is_dlopened(void *) __exported;
250 void _rtld_error(const char *, ...) __exported;
252 /* Only here to fix -Wmissing-prototypes warnings */
253 int __getosreldate(void);
254 void __pthread_cxa_finalize(struct dl_phdr_info *a);
255 func_ptr_type _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp);
256 Elf_Addr _rtld_bind(Obj_Entry *obj, Elf_Size reloff);
260 static int osreldate;
263 static int stack_prot = PROT_READ | PROT_WRITE | RTLD_DEFAULT_STACK_EXEC;
264 static int max_stack_flags;
267 * Global declarations normally provided by crt1. The dynamic linker is
268 * not built with crt1, so we have to provide them ourselves.
274 * Used to pass argc, argv to init functions.
280 * Globals to control TLS allocation.
282 size_t tls_last_offset; /* Static TLS offset of last module */
283 size_t tls_last_size; /* Static TLS size of last module */
284 size_t tls_static_space; /* Static TLS space allocated */
285 static size_t tls_static_max_align;
286 Elf_Addr tls_dtv_generation = 1; /* Used to detect when dtv size changes */
287 int tls_max_index = 1; /* Largest module index allocated */
289 static bool ld_library_path_rpath = false;
292 * Globals for path names, and such
294 const char *ld_elf_hints_default = _PATH_ELF_HINTS;
295 const char *ld_path_libmap_conf = _PATH_LIBMAP_CONF;
296 const char *ld_path_rtld = _PATH_RTLD;
297 const char *ld_standard_library_path = STANDARD_LIBRARY_PATH;
298 const char *ld_env_prefix = LD_;
300 static void (*rtld_exit_ptr)(void);
303 * Fill in a DoneList with an allocation large enough to hold all of
304 * the currently-loaded objects. Keep this as a macro since it calls
305 * alloca and we want that to occur within the scope of the caller.
307 #define donelist_init(dlp) \
308 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
309 assert((dlp)->objs != NULL), \
310 (dlp)->num_alloc = obj_count, \
313 #define LD_UTRACE(e, h, mb, ms, r, n) do { \
314 if (ld_utrace != NULL) \
315 ld_utrace_log(e, h, mb, ms, r, n); \
319 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
320 int refcnt, const char *name)
322 struct utrace_rtld ut;
323 static const char rtld_utrace_sig[RTLD_UTRACE_SIG_SZ] = RTLD_UTRACE_SIG;
325 memcpy(ut.sig, rtld_utrace_sig, sizeof(ut.sig));
328 ut.mapbase = mapbase;
329 ut.mapsize = mapsize;
331 bzero(ut.name, sizeof(ut.name));
333 strlcpy(ut.name, name, sizeof(ut.name));
334 utrace(&ut, sizeof(ut));
337 #ifdef RTLD_VARIANT_ENV_NAMES
339 * construct the env variable based on the type of binary that's
342 static inline const char *
345 static char buffer[128];
347 strlcpy(buffer, ld_env_prefix, sizeof(buffer));
348 strlcat(buffer, var, sizeof(buffer));
356 * Main entry point for dynamic linking. The first argument is the
357 * stack pointer. The stack is expected to be laid out as described
358 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
359 * Specifically, the stack pointer points to a word containing
360 * ARGC. Following that in the stack is a null-terminated sequence
361 * of pointers to argument strings. Then comes a null-terminated
362 * sequence of pointers to environment strings. Finally, there is a
363 * sequence of "auxiliary vector" entries.
365 * The second argument points to a place to store the dynamic linker's
366 * exit procedure pointer and the third to a place to store the main
369 * The return value is the main program's entry point.
372 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
374 Elf_Auxinfo *aux, *auxp, *auxpf, *aux_info[AT_COUNT];
375 Objlist_Entry *entry;
376 Obj_Entry *last_interposer, *obj, *preload_tail;
377 const Elf_Phdr *phdr;
379 RtldLockState lockstate;
382 char **argv, **env, **envp, *kexecpath, *library_path_rpath;
383 const char *argv0, *binpath;
385 char buf[MAXPATHLEN];
386 int argc, fd, i, phnum, rtld_argc;
387 bool dir_enable, explicit_fd, search_in_path;
390 * On entry, the dynamic linker itself has not been relocated yet.
391 * Be very careful not to reference any global data until after
392 * init_rtld has returned. It is OK to reference file-scope statics
393 * and string constants, and to call static and global functions.
396 /* Find the auxiliary vector on the stack. */
400 sp += argc + 1; /* Skip over arguments and NULL terminator */
402 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
404 aux = (Elf_Auxinfo *) sp;
406 /* Digest the auxiliary vector. */
407 for (i = 0; i < AT_COUNT; i++)
409 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
410 if (auxp->a_type < AT_COUNT)
411 aux_info[auxp->a_type] = auxp;
414 /* Initialize and relocate ourselves. */
415 assert(aux_info[AT_BASE] != NULL);
416 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
418 __progname = obj_rtld.path;
419 argv0 = argv[0] != NULL ? argv[0] : "(null)";
424 trust = !issetugid();
426 md_abi_variant_hook(aux_info);
429 if (aux_info[AT_EXECFD] != NULL) {
430 fd = aux_info[AT_EXECFD]->a_un.a_val;
432 assert(aux_info[AT_PHDR] != NULL);
433 phdr = (const Elf_Phdr *)aux_info[AT_PHDR]->a_un.a_ptr;
434 if (phdr == obj_rtld.phdr) {
436 _rtld_error("Tainted process refusing to run binary %s",
440 dbg("opening main program in direct exec mode");
442 rtld_argc = parse_args(argv, argc, &search_in_path, &fd);
443 argv0 = argv[rtld_argc];
444 explicit_fd = (fd != -1);
447 fd = open_binary_fd(argv0, search_in_path, &binpath);
448 if (fstat(fd, &st) == -1) {
449 _rtld_error("Failed to fstat FD %d (%s): %s", fd,
450 explicit_fd ? "user-provided descriptor" : argv0,
451 rtld_strerror(errno));
456 * Rough emulation of the permission checks done by
457 * execve(2), only Unix DACs are checked, ACLs are
458 * ignored. Preserve the semantic of disabling owner
459 * to execute if owner x bit is cleared, even if
460 * others x bit is enabled.
461 * mmap(2) does not allow to mmap with PROT_EXEC if
462 * binary' file comes from noexec mount. We cannot
463 * set a text reference on the binary.
466 if (st.st_uid == geteuid()) {
467 if ((st.st_mode & S_IXUSR) != 0)
469 } else if (st.st_gid == getegid()) {
470 if ((st.st_mode & S_IXGRP) != 0)
472 } else if ((st.st_mode & S_IXOTH) != 0) {
476 _rtld_error("No execute permission for binary %s",
482 * For direct exec mode, argv[0] is the interpreter
483 * name, we must remove it and shift arguments left
484 * before invoking binary main. Since stack layout
485 * places environment pointers and aux vectors right
486 * after the terminating NULL, we must shift
487 * environment and aux as well.
489 main_argc = argc - rtld_argc;
490 for (i = 0; i <= main_argc; i++)
491 argv[i] = argv[i + rtld_argc];
493 environ = env = envp = argv + main_argc + 1;
495 *envp = *(envp + rtld_argc);
497 } while (*envp != NULL);
498 aux = auxp = (Elf_Auxinfo *)envp;
499 auxpf = (Elf_Auxinfo *)(envp + rtld_argc);
500 /* XXXKIB insert place for AT_EXECPATH if not present */
501 for (;; auxp++, auxpf++) {
503 if (auxp->a_type == AT_NULL)
507 /* Point AT_EXECPATH auxv and aux_info to the binary path. */
508 if (binpath == NULL) {
509 aux_info[AT_EXECPATH] = NULL;
511 if (aux_info[AT_EXECPATH] == NULL) {
512 aux_info[AT_EXECPATH] = xmalloc(sizeof(Elf_Auxinfo));
513 aux_info[AT_EXECPATH]->a_type = AT_EXECPATH;
515 aux_info[AT_EXECPATH]->a_un.a_ptr = __DECONST(void *,
519 _rtld_error("No binary");
525 ld_bind_now = getenv(_LD("BIND_NOW"));
528 * If the process is tainted, then we un-set the dangerous environment
529 * variables. The process will be marked as tainted until setuid(2)
530 * is called. If any child process calls setuid(2) we do not want any
531 * future processes to honor the potentially un-safe variables.
534 if (unsetenv(_LD("PRELOAD")) || unsetenv(_LD("LIBMAP")) ||
535 unsetenv(_LD("LIBRARY_PATH")) || unsetenv(_LD("LIBRARY_PATH_FDS")) ||
536 unsetenv(_LD("LIBMAP_DISABLE")) || unsetenv(_LD("BIND_NOT")) ||
537 unsetenv(_LD("DEBUG")) || unsetenv(_LD("ELF_HINTS_PATH")) ||
538 unsetenv(_LD("LOADFLTR")) || unsetenv(_LD("LIBRARY_PATH_RPATH"))) {
539 _rtld_error("environment corrupt; aborting");
543 ld_debug = getenv(_LD("DEBUG"));
544 if (ld_bind_now == NULL)
545 ld_bind_not = getenv(_LD("BIND_NOT")) != NULL;
546 libmap_disable = getenv(_LD("LIBMAP_DISABLE")) != NULL;
547 libmap_override = getenv(_LD("LIBMAP"));
548 ld_library_path = getenv(_LD("LIBRARY_PATH"));
549 ld_library_dirs = getenv(_LD("LIBRARY_PATH_FDS"));
550 ld_preload = getenv(_LD("PRELOAD"));
551 ld_elf_hints_path = getenv(_LD("ELF_HINTS_PATH"));
552 ld_loadfltr = getenv(_LD("LOADFLTR")) != NULL;
553 library_path_rpath = getenv(_LD("LIBRARY_PATH_RPATH"));
554 if (library_path_rpath != NULL) {
555 if (library_path_rpath[0] == 'y' ||
556 library_path_rpath[0] == 'Y' ||
557 library_path_rpath[0] == '1')
558 ld_library_path_rpath = true;
560 ld_library_path_rpath = false;
562 dangerous_ld_env = libmap_disable || (libmap_override != NULL) ||
563 (ld_library_path != NULL) || (ld_preload != NULL) ||
564 (ld_elf_hints_path != NULL) || ld_loadfltr;
565 ld_tracing = getenv(_LD("TRACE_LOADED_OBJECTS"));
566 ld_utrace = getenv(_LD("UTRACE"));
568 if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0)
569 ld_elf_hints_path = ld_elf_hints_default;
571 if (ld_debug != NULL && *ld_debug != '\0')
573 dbg("%s is initialized, base address = %p", __progname,
574 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
575 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
576 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
578 dbg("initializing thread locks");
582 * Load the main program, or process its program header if it is
585 if (fd != -1) { /* Load the main program. */
586 dbg("loading main program");
587 obj_main = map_object(fd, argv0, NULL);
589 if (obj_main == NULL)
591 max_stack_flags = obj_main->stack_flags;
592 } else { /* Main program already loaded. */
593 dbg("processing main program's program header");
594 assert(aux_info[AT_PHDR] != NULL);
595 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
596 assert(aux_info[AT_PHNUM] != NULL);
597 phnum = aux_info[AT_PHNUM]->a_un.a_val;
598 assert(aux_info[AT_PHENT] != NULL);
599 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
600 assert(aux_info[AT_ENTRY] != NULL);
601 imgentry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
602 if ((obj_main = digest_phdr(phdr, phnum, imgentry, argv0)) == NULL)
606 if (aux_info[AT_EXECPATH] != NULL && fd == -1) {
607 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
608 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
609 if (kexecpath[0] == '/')
610 obj_main->path = kexecpath;
611 else if (getcwd(buf, sizeof(buf)) == NULL ||
612 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
613 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
614 obj_main->path = xstrdup(argv0);
616 obj_main->path = xstrdup(buf);
618 dbg("No AT_EXECPATH or direct exec");
619 obj_main->path = xstrdup(argv0);
621 dbg("obj_main path %s", obj_main->path);
622 obj_main->mainprog = true;
624 if (aux_info[AT_STACKPROT] != NULL &&
625 aux_info[AT_STACKPROT]->a_un.a_val != 0)
626 stack_prot = aux_info[AT_STACKPROT]->a_un.a_val;
630 * Get the actual dynamic linker pathname from the executable if
631 * possible. (It should always be possible.) That ensures that
632 * gdb will find the right dynamic linker even if a non-standard
635 if (obj_main->interp != NULL &&
636 strcmp(obj_main->interp, obj_rtld.path) != 0) {
638 obj_rtld.path = xstrdup(obj_main->interp);
639 __progname = obj_rtld.path;
643 if (!digest_dynamic(obj_main, 0))
645 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d",
646 obj_main->path, obj_main->valid_hash_sysv, obj_main->valid_hash_gnu,
647 obj_main->dynsymcount);
649 linkmap_add(obj_main);
650 linkmap_add(&obj_rtld);
652 /* Link the main program into the list of objects. */
653 TAILQ_INSERT_HEAD(&obj_list, obj_main, next);
657 /* Initialize a fake symbol for resolving undefined weak references. */
658 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
659 sym_zero.st_shndx = SHN_UNDEF;
660 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
663 libmap_disable = (bool)lm_init(libmap_override);
665 dbg("loading LD_PRELOAD libraries");
666 if (load_preload_objects() == -1)
668 preload_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
670 dbg("loading needed objects");
671 if (load_needed_objects(obj_main, 0) == -1)
674 /* Make a list of all objects loaded at startup. */
675 last_interposer = obj_main;
676 TAILQ_FOREACH(obj, &obj_list, next) {
679 if (obj->z_interpose && obj != obj_main) {
680 objlist_put_after(&list_main, last_interposer, obj);
681 last_interposer = obj;
683 objlist_push_tail(&list_main, obj);
688 dbg("checking for required versions");
689 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
692 if (ld_tracing) { /* We're done */
693 trace_loaded_objects(obj_main);
697 if (getenv(_LD("DUMP_REL_PRE")) != NULL) {
698 dump_relocations(obj_main);
703 * Processing tls relocations requires having the tls offsets
704 * initialized. Prepare offsets before starting initial
705 * relocation processing.
707 dbg("initializing initial thread local storage offsets");
708 STAILQ_FOREACH(entry, &list_main, link) {
710 * Allocate all the initial objects out of the static TLS
711 * block even if they didn't ask for it.
713 allocate_tls_offset(entry->obj);
716 if (relocate_objects(obj_main,
717 ld_bind_now != NULL && *ld_bind_now != '\0',
718 &obj_rtld, SYMLOOK_EARLY, NULL) == -1)
721 dbg("doing copy relocations");
722 if (do_copy_relocations(obj_main) == -1)
725 if (getenv(_LD("DUMP_REL_POST")) != NULL) {
726 dump_relocations(obj_main);
733 * Setup TLS for main thread. This must be done after the
734 * relocations are processed, since tls initialization section
735 * might be the subject for relocations.
737 dbg("initializing initial thread local storage");
738 allocate_initial_tls(globallist_curr(TAILQ_FIRST(&obj_list)));
740 dbg("initializing key program variables");
741 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
742 set_program_var("environ", env);
743 set_program_var("__elf_aux_vector", aux);
745 /* Make a list of init functions to call. */
746 objlist_init(&initlist);
747 initlist_add_objects(globallist_curr(TAILQ_FIRST(&obj_list)),
748 preload_tail, &initlist);
750 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
752 map_stacks_exec(NULL);
754 if (!obj_main->crt_no_init) {
756 * Make sure we don't call the main program's init and fini
757 * functions for binaries linked with old crt1 which calls
760 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
761 obj_main->preinit_array = obj_main->init_array =
762 obj_main->fini_array = (Elf_Addr)NULL;
766 * Execute MD initializers required before we call the objects'
771 wlock_acquire(rtld_bind_lock, &lockstate);
773 dbg("resolving ifuncs");
774 if (initlist_objects_ifunc(&initlist, ld_bind_now != NULL &&
775 *ld_bind_now != '\0', SYMLOOK_EARLY, &lockstate) == -1)
778 rtld_exit_ptr = rtld_exit;
779 if (obj_main->crt_no_init)
781 objlist_call_init(&initlist, &lockstate);
782 _r_debug_postinit(&obj_main->linkmap);
783 objlist_clear(&initlist);
784 dbg("loading filtees");
785 TAILQ_FOREACH(obj, &obj_list, next) {
788 if (ld_loadfltr || obj->z_loadfltr)
789 load_filtees(obj, 0, &lockstate);
792 dbg("enforcing main obj relro");
793 if (obj_enforce_relro(obj_main) == -1)
796 lock_release(rtld_bind_lock, &lockstate);
798 dbg("transferring control to program entry point = %p", obj_main->entry);
800 /* Return the exit procedure and the program entry point. */
801 *exit_proc = rtld_exit_ptr;
803 return (func_ptr_type) obj_main->entry;
807 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def)
812 ptr = (void *)make_function_pointer(def, obj);
813 target = call_ifunc_resolver(ptr);
814 return ((void *)target);
818 * NB: MIPS uses a private version of this function (_mips_rtld_bind).
819 * Changes to this function should be applied there as well.
822 _rtld_bind(Obj_Entry *obj, Elf_Size reloff)
826 const Obj_Entry *defobj;
829 RtldLockState lockstate;
831 rlock_acquire(rtld_bind_lock, &lockstate);
832 if (sigsetjmp(lockstate.env, 0) != 0)
833 lock_upgrade(rtld_bind_lock, &lockstate);
835 rel = (const Elf_Rel *)((const char *)obj->pltrel + reloff);
837 rel = (const Elf_Rel *)((const char *)obj->pltrela + reloff);
839 where = (Elf_Addr *)(obj->relocbase + rel->r_offset);
840 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, SYMLOOK_IN_PLT,
844 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
845 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
847 target = (Elf_Addr)(defobj->relocbase + def->st_value);
849 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
850 defobj->strtab + def->st_name, basename(obj->path),
851 (void *)target, basename(defobj->path));
854 * Write the new contents for the jmpslot. Note that depending on
855 * architecture, the value which we need to return back to the
856 * lazy binding trampoline may or may not be the target
857 * address. The value returned from reloc_jmpslot() is the value
858 * that the trampoline needs.
860 target = reloc_jmpslot(where, target, defobj, obj, rel);
861 lock_release(rtld_bind_lock, &lockstate);
866 * Error reporting function. Use it like printf. If formats the message
867 * into a buffer, and sets things up so that the next call to dlerror()
868 * will return the message.
871 _rtld_error(const char *fmt, ...)
873 static char buf[512];
877 rtld_vsnprintf(buf, sizeof buf, fmt, ap);
880 LD_UTRACE(UTRACE_RTLD_ERROR, NULL, NULL, 0, 0, error_message);
884 * Return a dynamically-allocated copy of the current error message, if any.
889 return error_message == NULL ? NULL : xstrdup(error_message);
893 * Restore the current error message from a copy which was previously saved
894 * by errmsg_save(). The copy is freed.
897 errmsg_restore(char *saved_msg)
899 if (saved_msg == NULL)
900 error_message = NULL;
902 _rtld_error("%s", saved_msg);
908 basename(const char *name)
910 const char *p = strrchr(name, '/');
911 return p != NULL ? p + 1 : name;
914 static struct utsname uts;
917 origin_subst_one(Obj_Entry *obj, char *real, const char *kw,
918 const char *subst, bool may_free)
920 char *p, *p1, *res, *resp;
921 int subst_len, kw_len, subst_count, old_len, new_len;
926 * First, count the number of the keyword occurrences, to
927 * preallocate the final string.
929 for (p = real, subst_count = 0;; p = p1 + kw_len, subst_count++) {
936 * If the keyword is not found, just return.
938 * Return non-substituted string if resolution failed. We
939 * cannot do anything more reasonable, the failure mode of the
940 * caller is unresolved library anyway.
942 if (subst_count == 0 || (obj != NULL && !obj_resolve_origin(obj)))
943 return (may_free ? real : xstrdup(real));
945 subst = obj->origin_path;
948 * There is indeed something to substitute. Calculate the
949 * length of the resulting string, and allocate it.
951 subst_len = strlen(subst);
952 old_len = strlen(real);
953 new_len = old_len + (subst_len - kw_len) * subst_count;
954 res = xmalloc(new_len + 1);
957 * Now, execute the substitution loop.
959 for (p = real, resp = res, *resp = '\0';;) {
962 /* Copy the prefix before keyword. */
963 memcpy(resp, p, p1 - p);
965 /* Keyword replacement. */
966 memcpy(resp, subst, subst_len);
974 /* Copy to the end of string and finish. */
982 origin_subst(Obj_Entry *obj, const char *real)
984 char *res1, *res2, *res3, *res4;
986 if (obj == NULL || !trust)
987 return (xstrdup(real));
988 if (uts.sysname[0] == '\0') {
989 if (uname(&uts) != 0) {
990 _rtld_error("utsname failed: %d", errno);
994 /* __DECONST is safe here since without may_free real is unchanged */
995 res1 = origin_subst_one(obj, __DECONST(char *, real), "$ORIGIN", NULL,
997 res2 = origin_subst_one(NULL, res1, "$OSNAME", uts.sysname, true);
998 res3 = origin_subst_one(NULL, res2, "$OSREL", uts.release, true);
999 res4 = origin_subst_one(NULL, res3, "$PLATFORM", uts.machine, true);
1006 const char *msg = dlerror();
1009 msg = "Fatal error";
1010 rtld_fdputstr(STDERR_FILENO, _BASENAME_RTLD ": ");
1011 rtld_fdputstr(STDERR_FILENO, msg);
1012 rtld_fdputchar(STDERR_FILENO, '\n');
1017 * Process a shared object's DYNAMIC section, and save the important
1018 * information in its Obj_Entry structure.
1021 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
1022 const Elf_Dyn **dyn_soname, const Elf_Dyn **dyn_runpath)
1024 const Elf_Dyn *dynp;
1025 Needed_Entry **needed_tail = &obj->needed;
1026 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
1027 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
1028 const Elf_Hashelt *hashtab;
1029 const Elf32_Word *hashval;
1030 Elf32_Word bkt, nmaskwords;
1032 int plttype = DT_REL;
1036 *dyn_runpath = NULL;
1038 obj->bind_now = false;
1039 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
1040 switch (dynp->d_tag) {
1043 obj->rel = (const Elf_Rel *)(obj->relocbase + dynp->d_un.d_ptr);
1047 obj->relsize = dynp->d_un.d_val;
1051 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
1055 obj->pltrel = (const Elf_Rel *)
1056 (obj->relocbase + dynp->d_un.d_ptr);
1060 obj->pltrelsize = dynp->d_un.d_val;
1064 obj->rela = (const Elf_Rela *)(obj->relocbase + dynp->d_un.d_ptr);
1068 obj->relasize = dynp->d_un.d_val;
1072 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
1076 plttype = dynp->d_un.d_val;
1077 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
1081 obj->symtab = (const Elf_Sym *)
1082 (obj->relocbase + dynp->d_un.d_ptr);
1086 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
1090 obj->strtab = (const char *)(obj->relocbase + dynp->d_un.d_ptr);
1094 obj->strsize = dynp->d_un.d_val;
1098 obj->verneed = (const Elf_Verneed *)(obj->relocbase +
1103 obj->verneednum = dynp->d_un.d_val;
1107 obj->verdef = (const Elf_Verdef *)(obj->relocbase +
1112 obj->verdefnum = dynp->d_un.d_val;
1116 obj->versyms = (const Elf_Versym *)(obj->relocbase +
1122 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1124 obj->nbuckets = hashtab[0];
1125 obj->nchains = hashtab[1];
1126 obj->buckets = hashtab + 2;
1127 obj->chains = obj->buckets + obj->nbuckets;
1128 obj->valid_hash_sysv = obj->nbuckets > 0 && obj->nchains > 0 &&
1129 obj->buckets != NULL;
1135 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1137 obj->nbuckets_gnu = hashtab[0];
1138 obj->symndx_gnu = hashtab[1];
1139 nmaskwords = hashtab[2];
1140 bloom_size32 = (__ELF_WORD_SIZE / 32) * nmaskwords;
1141 obj->maskwords_bm_gnu = nmaskwords - 1;
1142 obj->shift2_gnu = hashtab[3];
1143 obj->bloom_gnu = (const Elf_Addr *)(hashtab + 4);
1144 obj->buckets_gnu = hashtab + 4 + bloom_size32;
1145 obj->chain_zero_gnu = obj->buckets_gnu + obj->nbuckets_gnu -
1147 /* Number of bitmask words is required to be power of 2 */
1148 obj->valid_hash_gnu = powerof2(nmaskwords) &&
1149 obj->nbuckets_gnu > 0 && obj->buckets_gnu != NULL;
1155 Needed_Entry *nep = NEW(Needed_Entry);
1156 nep->name = dynp->d_un.d_val;
1161 needed_tail = &nep->next;
1167 Needed_Entry *nep = NEW(Needed_Entry);
1168 nep->name = dynp->d_un.d_val;
1172 *needed_filtees_tail = nep;
1173 needed_filtees_tail = &nep->next;
1179 Needed_Entry *nep = NEW(Needed_Entry);
1180 nep->name = dynp->d_un.d_val;
1184 *needed_aux_filtees_tail = nep;
1185 needed_aux_filtees_tail = &nep->next;
1190 obj->pltgot = (Elf_Addr *)(obj->relocbase + dynp->d_un.d_ptr);
1194 obj->textrel = true;
1198 obj->symbolic = true;
1203 * We have to wait until later to process this, because we
1204 * might not have gotten the address of the string table yet.
1214 *dyn_runpath = dynp;
1218 obj->init = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1221 case DT_PREINIT_ARRAY:
1222 obj->preinit_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1225 case DT_PREINIT_ARRAYSZ:
1226 obj->preinit_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1230 obj->init_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1233 case DT_INIT_ARRAYSZ:
1234 obj->init_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1238 obj->fini = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1242 obj->fini_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1245 case DT_FINI_ARRAYSZ:
1246 obj->fini_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1250 * Don't process DT_DEBUG on MIPS as the dynamic section
1251 * is mapped read-only. DT_MIPS_RLD_MAP is used instead.
1257 dbg("Filling in DT_DEBUG entry");
1258 (__DECONST(Elf_Dyn *, dynp))->d_un.d_ptr = (Elf_Addr)&r_debug;
1263 if (dynp->d_un.d_val & DF_ORIGIN)
1264 obj->z_origin = true;
1265 if (dynp->d_un.d_val & DF_SYMBOLIC)
1266 obj->symbolic = true;
1267 if (dynp->d_un.d_val & DF_TEXTREL)
1268 obj->textrel = true;
1269 if (dynp->d_un.d_val & DF_BIND_NOW)
1270 obj->bind_now = true;
1271 if (dynp->d_un.d_val & DF_STATIC_TLS)
1272 obj->static_tls = true;
1275 case DT_MIPS_LOCAL_GOTNO:
1276 obj->local_gotno = dynp->d_un.d_val;
1279 case DT_MIPS_SYMTABNO:
1280 obj->symtabno = dynp->d_un.d_val;
1283 case DT_MIPS_GOTSYM:
1284 obj->gotsym = dynp->d_un.d_val;
1287 case DT_MIPS_RLD_MAP:
1288 *((Elf_Addr *)(dynp->d_un.d_ptr)) = (Elf_Addr) &r_debug;
1291 case DT_MIPS_PLTGOT:
1292 obj->mips_pltgot = (Elf_Addr *)(obj->relocbase +
1298 #ifdef __powerpc64__
1299 case DT_PPC64_GLINK:
1300 obj->glink = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1305 if (dynp->d_un.d_val & DF_1_NOOPEN)
1306 obj->z_noopen = true;
1307 if (dynp->d_un.d_val & DF_1_ORIGIN)
1308 obj->z_origin = true;
1309 if (dynp->d_un.d_val & DF_1_GLOBAL)
1310 obj->z_global = true;
1311 if (dynp->d_un.d_val & DF_1_BIND_NOW)
1312 obj->bind_now = true;
1313 if (dynp->d_un.d_val & DF_1_NODELETE)
1314 obj->z_nodelete = true;
1315 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1316 obj->z_loadfltr = true;
1317 if (dynp->d_un.d_val & DF_1_INTERPOSE)
1318 obj->z_interpose = true;
1319 if (dynp->d_un.d_val & DF_1_NODEFLIB)
1320 obj->z_nodeflib = true;
1325 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1332 obj->traced = false;
1334 if (plttype == DT_RELA) {
1335 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1337 obj->pltrelasize = obj->pltrelsize;
1338 obj->pltrelsize = 0;
1341 /* Determine size of dynsym table (equal to nchains of sysv hash) */
1342 if (obj->valid_hash_sysv)
1343 obj->dynsymcount = obj->nchains;
1344 else if (obj->valid_hash_gnu) {
1345 obj->dynsymcount = 0;
1346 for (bkt = 0; bkt < obj->nbuckets_gnu; bkt++) {
1347 if (obj->buckets_gnu[bkt] == 0)
1349 hashval = &obj->chain_zero_gnu[obj->buckets_gnu[bkt]];
1352 while ((*hashval++ & 1u) == 0);
1354 obj->dynsymcount += obj->symndx_gnu;
1359 obj_resolve_origin(Obj_Entry *obj)
1362 if (obj->origin_path != NULL)
1364 obj->origin_path = xmalloc(PATH_MAX);
1365 return (rtld_dirname_abs(obj->path, obj->origin_path) != -1);
1369 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1370 const Elf_Dyn *dyn_soname, const Elf_Dyn *dyn_runpath)
1373 if (obj->z_origin && !obj_resolve_origin(obj))
1376 if (dyn_runpath != NULL) {
1377 obj->runpath = (const char *)obj->strtab + dyn_runpath->d_un.d_val;
1378 obj->runpath = origin_subst(obj, obj->runpath);
1379 } else if (dyn_rpath != NULL) {
1380 obj->rpath = (const char *)obj->strtab + dyn_rpath->d_un.d_val;
1381 obj->rpath = origin_subst(obj, obj->rpath);
1383 if (dyn_soname != NULL)
1384 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1389 digest_dynamic(Obj_Entry *obj, int early)
1391 const Elf_Dyn *dyn_rpath;
1392 const Elf_Dyn *dyn_soname;
1393 const Elf_Dyn *dyn_runpath;
1395 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname, &dyn_runpath);
1396 return (digest_dynamic2(obj, dyn_rpath, dyn_soname, dyn_runpath));
1400 * Process a shared object's program header. This is used only for the
1401 * main program, when the kernel has already loaded the main program
1402 * into memory before calling the dynamic linker. It creates and
1403 * returns an Obj_Entry structure.
1406 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1409 const Elf_Phdr *phlimit = phdr + phnum;
1411 Elf_Addr note_start, note_end;
1415 for (ph = phdr; ph < phlimit; ph++) {
1416 if (ph->p_type != PT_PHDR)
1420 obj->phsize = ph->p_memsz;
1421 obj->relocbase = __DECONST(char *, phdr) - ph->p_vaddr;
1425 obj->stack_flags = PF_X | PF_R | PF_W;
1427 for (ph = phdr; ph < phlimit; ph++) {
1428 switch (ph->p_type) {
1431 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1435 if (nsegs == 0) { /* First load segment */
1436 obj->vaddrbase = trunc_page(ph->p_vaddr);
1437 obj->mapbase = obj->vaddrbase + obj->relocbase;
1438 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
1440 } else { /* Last load segment */
1441 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1448 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1453 obj->tlssize = ph->p_memsz;
1454 obj->tlsalign = ph->p_align;
1455 obj->tlsinitsize = ph->p_filesz;
1456 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1457 obj->tlspoffset = ph->p_offset;
1461 obj->stack_flags = ph->p_flags;
1465 obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1466 obj->relro_size = round_page(ph->p_memsz);
1470 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
1471 note_end = note_start + ph->p_filesz;
1472 digest_notes(obj, note_start, note_end);
1477 _rtld_error("%s: too few PT_LOAD segments", path);
1486 digest_notes(Obj_Entry *obj, Elf_Addr note_start, Elf_Addr note_end)
1488 const Elf_Note *note;
1489 const char *note_name;
1492 for (note = (const Elf_Note *)note_start; (Elf_Addr)note < note_end;
1493 note = (const Elf_Note *)((const char *)(note + 1) +
1494 roundup2(note->n_namesz, sizeof(Elf32_Addr)) +
1495 roundup2(note->n_descsz, sizeof(Elf32_Addr)))) {
1496 if (note->n_namesz != sizeof(NOTE_FREEBSD_VENDOR) ||
1497 note->n_descsz != sizeof(int32_t))
1499 if (note->n_type != NT_FREEBSD_ABI_TAG &&
1500 note->n_type != NT_FREEBSD_FEATURE_CTL &&
1501 note->n_type != NT_FREEBSD_NOINIT_TAG)
1503 note_name = (const char *)(note + 1);
1504 if (strncmp(NOTE_FREEBSD_VENDOR, note_name,
1505 sizeof(NOTE_FREEBSD_VENDOR)) != 0)
1507 switch (note->n_type) {
1508 case NT_FREEBSD_ABI_TAG:
1509 /* FreeBSD osrel note */
1510 p = (uintptr_t)(note + 1);
1511 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1512 obj->osrel = *(const int32_t *)(p);
1513 dbg("note osrel %d", obj->osrel);
1515 case NT_FREEBSD_FEATURE_CTL:
1516 /* FreeBSD ABI feature control note */
1517 p = (uintptr_t)(note + 1);
1518 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1519 obj->fctl0 = *(const uint32_t *)(p);
1520 dbg("note fctl0 %#x", obj->fctl0);
1522 case NT_FREEBSD_NOINIT_TAG:
1523 /* FreeBSD 'crt does not call init' note */
1524 obj->crt_no_init = true;
1525 dbg("note crt_no_init");
1532 dlcheck(void *handle)
1536 TAILQ_FOREACH(obj, &obj_list, next) {
1537 if (obj == (Obj_Entry *) handle)
1541 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1542 _rtld_error("Invalid shared object handle %p", handle);
1549 * If the given object is already in the donelist, return true. Otherwise
1550 * add the object to the list and return false.
1553 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1557 for (i = 0; i < dlp->num_used; i++)
1558 if (dlp->objs[i] == obj)
1561 * Our donelist allocation should always be sufficient. But if
1562 * our threads locking isn't working properly, more shared objects
1563 * could have been loaded since we allocated the list. That should
1564 * never happen, but we'll handle it properly just in case it does.
1566 if (dlp->num_used < dlp->num_alloc)
1567 dlp->objs[dlp->num_used++] = obj;
1572 * Hash function for symbol table lookup. Don't even think about changing
1573 * this. It is specified by the System V ABI.
1576 elf_hash(const char *name)
1578 const unsigned char *p = (const unsigned char *) name;
1579 unsigned long h = 0;
1582 while (*p != '\0') {
1583 h = (h << 4) + *p++;
1584 if ((g = h & 0xf0000000) != 0)
1592 * The GNU hash function is the Daniel J. Bernstein hash clipped to 32 bits
1593 * unsigned in case it's implemented with a wider type.
1596 gnu_hash(const char *s)
1602 for (c = *s; c != '\0'; c = *++s)
1604 return (h & 0xffffffff);
1609 * Find the library with the given name, and return its full pathname.
1610 * The returned string is dynamically allocated. Generates an error
1611 * message and returns NULL if the library cannot be found.
1613 * If the second argument is non-NULL, then it refers to an already-
1614 * loaded shared object, whose library search path will be searched.
1616 * If a library is successfully located via LD_LIBRARY_PATH_FDS, its
1617 * descriptor (which is close-on-exec) will be passed out via the third
1620 * The search order is:
1621 * DT_RPATH in the referencing file _unless_ DT_RUNPATH is present (1)
1622 * DT_RPATH of the main object if DSO without defined DT_RUNPATH (1)
1624 * DT_RUNPATH in the referencing file
1625 * ldconfig hints (if -z nodefaultlib, filter out default library directories
1627 * /lib:/usr/lib _unless_ the referencing file is linked with -z nodefaultlib
1629 * (1) Handled in digest_dynamic2 - rpath left NULL if runpath defined.
1632 find_library(const char *xname, const Obj_Entry *refobj, int *fdp)
1634 char *pathname, *refobj_path;
1636 bool nodeflib, objgiven;
1638 objgiven = refobj != NULL;
1640 if (libmap_disable || !objgiven ||
1641 (name = lm_find(refobj->path, xname)) == NULL)
1644 if (strchr(name, '/') != NULL) { /* Hard coded pathname */
1645 if (name[0] != '/' && !trust) {
1646 _rtld_error("Absolute pathname required "
1647 "for shared object \"%s\"", name);
1650 return (origin_subst(__DECONST(Obj_Entry *, refobj),
1651 __DECONST(char *, name)));
1654 dbg(" Searching for \"%s\"", name);
1655 refobj_path = objgiven ? refobj->path : NULL;
1658 * If refobj->rpath != NULL, then refobj->runpath is NULL. Fall
1659 * back to pre-conforming behaviour if user requested so with
1660 * LD_LIBRARY_PATH_RPATH environment variable and ignore -z
1663 if (objgiven && refobj->rpath != NULL && ld_library_path_rpath) {
1664 pathname = search_library_path(name, ld_library_path,
1666 if (pathname != NULL)
1668 if (refobj != NULL) {
1669 pathname = search_library_path(name, refobj->rpath,
1671 if (pathname != NULL)
1674 pathname = search_library_pathfds(name, ld_library_dirs, fdp);
1675 if (pathname != NULL)
1677 pathname = search_library_path(name, gethints(false),
1679 if (pathname != NULL)
1681 pathname = search_library_path(name, ld_standard_library_path,
1683 if (pathname != NULL)
1686 nodeflib = objgiven ? refobj->z_nodeflib : false;
1688 pathname = search_library_path(name, refobj->rpath,
1690 if (pathname != NULL)
1693 if (objgiven && refobj->runpath == NULL && refobj != obj_main) {
1694 pathname = search_library_path(name, obj_main->rpath,
1696 if (pathname != NULL)
1699 pathname = search_library_path(name, ld_library_path,
1701 if (pathname != NULL)
1704 pathname = search_library_path(name, refobj->runpath,
1706 if (pathname != NULL)
1709 pathname = search_library_pathfds(name, ld_library_dirs, fdp);
1710 if (pathname != NULL)
1712 pathname = search_library_path(name, gethints(nodeflib),
1714 if (pathname != NULL)
1716 if (objgiven && !nodeflib) {
1717 pathname = search_library_path(name,
1718 ld_standard_library_path, refobj_path, fdp);
1719 if (pathname != NULL)
1724 if (objgiven && refobj->path != NULL) {
1725 _rtld_error("Shared object \"%s\" not found, "
1726 "required by \"%s\"", name, basename(refobj->path));
1728 _rtld_error("Shared object \"%s\" not found", name);
1734 * Given a symbol number in a referencing object, find the corresponding
1735 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1736 * no definition was found. Returns a pointer to the Obj_Entry of the
1737 * defining object via the reference parameter DEFOBJ_OUT.
1740 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1741 const Obj_Entry **defobj_out, int flags, SymCache *cache,
1742 RtldLockState *lockstate)
1746 const Obj_Entry *defobj;
1747 const Ver_Entry *ve;
1753 * If we have already found this symbol, get the information from
1756 if (symnum >= refobj->dynsymcount)
1757 return NULL; /* Bad object */
1758 if (cache != NULL && cache[symnum].sym != NULL) {
1759 *defobj_out = cache[symnum].obj;
1760 return cache[symnum].sym;
1763 ref = refobj->symtab + symnum;
1764 name = refobj->strtab + ref->st_name;
1770 * We don't have to do a full scale lookup if the symbol is local.
1771 * We know it will bind to the instance in this load module; to
1772 * which we already have a pointer (ie ref). By not doing a lookup,
1773 * we not only improve performance, but it also avoids unresolvable
1774 * symbols when local symbols are not in the hash table. This has
1775 * been seen with the ia64 toolchain.
1777 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1778 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1779 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1782 symlook_init(&req, name);
1784 ve = req.ventry = fetch_ventry(refobj, symnum);
1785 req.lockstate = lockstate;
1786 res = symlook_default(&req, refobj);
1789 defobj = req.defobj_out;
1797 * If we found no definition and the reference is weak, treat the
1798 * symbol as having the value zero.
1800 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1806 *defobj_out = defobj;
1807 /* Record the information in the cache to avoid subsequent lookups. */
1808 if (cache != NULL) {
1809 cache[symnum].sym = def;
1810 cache[symnum].obj = defobj;
1813 if (refobj != &obj_rtld)
1814 _rtld_error("%s: Undefined symbol \"%s%s%s\"", refobj->path, name,
1815 ve != NULL ? "@" : "", ve != NULL ? ve->name : "");
1821 * Return the search path from the ldconfig hints file, reading it if
1822 * necessary. If nostdlib is true, then the default search paths are
1823 * not added to result.
1825 * Returns NULL if there are problems with the hints file,
1826 * or if the search path there is empty.
1829 gethints(bool nostdlib)
1831 static char *filtered_path;
1832 static const char *hints;
1833 static struct elfhints_hdr hdr;
1834 struct fill_search_info_args sargs, hargs;
1835 struct dl_serinfo smeta, hmeta, *SLPinfo, *hintinfo;
1836 struct dl_serpath *SLPpath, *hintpath;
1838 struct stat hint_stat;
1839 unsigned int SLPndx, hintndx, fndx, fcount;
1845 /* First call, read the hints file */
1846 if (hints == NULL) {
1847 /* Keep from trying again in case the hints file is bad. */
1850 if ((fd = open(ld_elf_hints_path, O_RDONLY | O_CLOEXEC)) == -1)
1854 * Check of hdr.dirlistlen value against type limit
1855 * intends to pacify static analyzers. Further
1856 * paranoia leads to checks that dirlist is fully
1857 * contained in the file range.
1859 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1860 hdr.magic != ELFHINTS_MAGIC ||
1861 hdr.version != 1 || hdr.dirlistlen > UINT_MAX / 2 ||
1862 fstat(fd, &hint_stat) == -1) {
1869 if (dl + hdr.dirlist < dl)
1872 if (dl + hdr.dirlistlen < dl)
1874 dl += hdr.dirlistlen;
1875 if (dl > hint_stat.st_size)
1877 p = xmalloc(hdr.dirlistlen + 1);
1878 if (pread(fd, p, hdr.dirlistlen + 1,
1879 hdr.strtab + hdr.dirlist) != (ssize_t)hdr.dirlistlen + 1 ||
1880 p[hdr.dirlistlen] != '\0') {
1889 * If caller agreed to receive list which includes the default
1890 * paths, we are done. Otherwise, if we still did not
1891 * calculated filtered result, do it now.
1894 return (hints[0] != '\0' ? hints : NULL);
1895 if (filtered_path != NULL)
1899 * Obtain the list of all configured search paths, and the
1900 * list of the default paths.
1902 * First estimate the size of the results.
1904 smeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1906 hmeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1909 sargs.request = RTLD_DI_SERINFOSIZE;
1910 sargs.serinfo = &smeta;
1911 hargs.request = RTLD_DI_SERINFOSIZE;
1912 hargs.serinfo = &hmeta;
1914 path_enumerate(ld_standard_library_path, fill_search_info, NULL,
1916 path_enumerate(hints, fill_search_info, NULL, &hargs);
1918 SLPinfo = xmalloc(smeta.dls_size);
1919 hintinfo = xmalloc(hmeta.dls_size);
1922 * Next fetch both sets of paths.
1924 sargs.request = RTLD_DI_SERINFO;
1925 sargs.serinfo = SLPinfo;
1926 sargs.serpath = &SLPinfo->dls_serpath[0];
1927 sargs.strspace = (char *)&SLPinfo->dls_serpath[smeta.dls_cnt];
1929 hargs.request = RTLD_DI_SERINFO;
1930 hargs.serinfo = hintinfo;
1931 hargs.serpath = &hintinfo->dls_serpath[0];
1932 hargs.strspace = (char *)&hintinfo->dls_serpath[hmeta.dls_cnt];
1934 path_enumerate(ld_standard_library_path, fill_search_info, NULL,
1936 path_enumerate(hints, fill_search_info, NULL, &hargs);
1939 * Now calculate the difference between two sets, by excluding
1940 * standard paths from the full set.
1944 filtered_path = xmalloc(hdr.dirlistlen + 1);
1945 hintpath = &hintinfo->dls_serpath[0];
1946 for (hintndx = 0; hintndx < hmeta.dls_cnt; hintndx++, hintpath++) {
1948 SLPpath = &SLPinfo->dls_serpath[0];
1950 * Check each standard path against current.
1952 for (SLPndx = 0; SLPndx < smeta.dls_cnt; SLPndx++, SLPpath++) {
1953 /* matched, skip the path */
1954 if (!strcmp(hintpath->dls_name, SLPpath->dls_name)) {
1962 * Not matched against any standard path, add the path
1963 * to result. Separate consequtive paths with ':'.
1966 filtered_path[fndx] = ':';
1970 flen = strlen(hintpath->dls_name);
1971 strncpy((filtered_path + fndx), hintpath->dls_name, flen);
1974 filtered_path[fndx] = '\0';
1980 return (filtered_path[0] != '\0' ? filtered_path : NULL);
1984 init_dag(Obj_Entry *root)
1986 const Needed_Entry *needed;
1987 const Objlist_Entry *elm;
1990 if (root->dag_inited)
1992 donelist_init(&donelist);
1994 /* Root object belongs to own DAG. */
1995 objlist_push_tail(&root->dldags, root);
1996 objlist_push_tail(&root->dagmembers, root);
1997 donelist_check(&donelist, root);
2000 * Add dependencies of root object to DAG in breadth order
2001 * by exploiting the fact that each new object get added
2002 * to the tail of the dagmembers list.
2004 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2005 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
2006 if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
2008 objlist_push_tail(&needed->obj->dldags, root);
2009 objlist_push_tail(&root->dagmembers, needed->obj);
2012 root->dag_inited = true;
2016 init_marker(Obj_Entry *marker)
2019 bzero(marker, sizeof(*marker));
2020 marker->marker = true;
2024 globallist_curr(const Obj_Entry *obj)
2031 return (__DECONST(Obj_Entry *, obj));
2032 obj = TAILQ_PREV(obj, obj_entry_q, next);
2037 globallist_next(const Obj_Entry *obj)
2041 obj = TAILQ_NEXT(obj, next);
2045 return (__DECONST(Obj_Entry *, obj));
2049 /* Prevent the object from being unmapped while the bind lock is dropped. */
2051 hold_object(Obj_Entry *obj)
2058 unhold_object(Obj_Entry *obj)
2061 assert(obj->holdcount > 0);
2062 if (--obj->holdcount == 0 && obj->unholdfree)
2063 release_object(obj);
2067 process_z(Obj_Entry *root)
2069 const Objlist_Entry *elm;
2073 * Walk over object DAG and process every dependent object
2074 * that is marked as DF_1_NODELETE or DF_1_GLOBAL. They need
2075 * to grow their own DAG.
2077 * For DF_1_GLOBAL, DAG is required for symbol lookups in
2078 * symlook_global() to work.
2080 * For DF_1_NODELETE, the DAG should have its reference upped.
2082 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2086 if (obj->z_nodelete && !obj->ref_nodel) {
2087 dbg("obj %s -z nodelete", obj->path);
2090 obj->ref_nodel = true;
2092 if (obj->z_global && objlist_find(&list_global, obj) == NULL) {
2093 dbg("obj %s -z global", obj->path);
2094 objlist_push_tail(&list_global, obj);
2100 * Initialize the dynamic linker. The argument is the address at which
2101 * the dynamic linker has been mapped into memory. The primary task of
2102 * this function is to relocate the dynamic linker.
2105 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
2107 Obj_Entry objtmp; /* Temporary rtld object */
2108 const Elf_Ehdr *ehdr;
2109 const Elf_Dyn *dyn_rpath;
2110 const Elf_Dyn *dyn_soname;
2111 const Elf_Dyn *dyn_runpath;
2113 #ifdef RTLD_INIT_PAGESIZES_EARLY
2114 /* The page size is required by the dynamic memory allocator. */
2115 init_pagesizes(aux_info);
2119 * Conjure up an Obj_Entry structure for the dynamic linker.
2121 * The "path" member can't be initialized yet because string constants
2122 * cannot yet be accessed. Below we will set it correctly.
2124 memset(&objtmp, 0, sizeof(objtmp));
2127 objtmp.mapbase = mapbase;
2129 objtmp.relocbase = mapbase;
2132 objtmp.dynamic = rtld_dynamic(&objtmp);
2133 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname, &dyn_runpath);
2134 assert(objtmp.needed == NULL);
2135 #if !defined(__mips__)
2136 /* MIPS has a bogus DT_TEXTREL. */
2137 assert(!objtmp.textrel);
2140 * Temporarily put the dynamic linker entry into the object list, so
2141 * that symbols can be found.
2143 relocate_objects(&objtmp, true, &objtmp, 0, NULL);
2145 ehdr = (Elf_Ehdr *)mapbase;
2146 objtmp.phdr = (Elf_Phdr *)((char *)mapbase + ehdr->e_phoff);
2147 objtmp.phsize = ehdr->e_phnum * sizeof(objtmp.phdr[0]);
2149 /* Initialize the object list. */
2150 TAILQ_INIT(&obj_list);
2152 /* Now that non-local variables can be accesses, copy out obj_rtld. */
2153 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
2155 #ifndef RTLD_INIT_PAGESIZES_EARLY
2156 /* The page size is required by the dynamic memory allocator. */
2157 init_pagesizes(aux_info);
2160 if (aux_info[AT_OSRELDATE] != NULL)
2161 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
2163 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname, dyn_runpath);
2165 /* Replace the path with a dynamically allocated copy. */
2166 obj_rtld.path = xstrdup(ld_path_rtld);
2168 r_debug.r_brk = r_debug_state;
2169 r_debug.r_state = RT_CONSISTENT;
2173 * Retrieve the array of supported page sizes. The kernel provides the page
2174 * sizes in increasing order.
2177 init_pagesizes(Elf_Auxinfo **aux_info)
2179 static size_t psa[MAXPAGESIZES];
2183 if (aux_info[AT_PAGESIZES] != NULL && aux_info[AT_PAGESIZESLEN] !=
2185 size = aux_info[AT_PAGESIZESLEN]->a_un.a_val;
2186 pagesizes = aux_info[AT_PAGESIZES]->a_un.a_ptr;
2189 if (sysctlnametomib("hw.pagesizes", mib, &len) == 0)
2192 /* As a fallback, retrieve the base page size. */
2193 size = sizeof(psa[0]);
2194 if (aux_info[AT_PAGESZ] != NULL) {
2195 psa[0] = aux_info[AT_PAGESZ]->a_un.a_val;
2199 mib[1] = HW_PAGESIZE;
2203 if (sysctl(mib, len, psa, &size, NULL, 0) == -1) {
2204 _rtld_error("sysctl for hw.pagesize(s) failed");
2210 npagesizes = size / sizeof(pagesizes[0]);
2211 /* Discard any invalid entries at the end of the array. */
2212 while (npagesizes > 0 && pagesizes[npagesizes - 1] == 0)
2217 * Add the init functions from a needed object list (and its recursive
2218 * needed objects) to "list". This is not used directly; it is a helper
2219 * function for initlist_add_objects(). The write lock must be held
2220 * when this function is called.
2223 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
2225 /* Recursively process the successor needed objects. */
2226 if (needed->next != NULL)
2227 initlist_add_neededs(needed->next, list);
2229 /* Process the current needed object. */
2230 if (needed->obj != NULL)
2231 initlist_add_objects(needed->obj, needed->obj, list);
2235 * Scan all of the DAGs rooted in the range of objects from "obj" to
2236 * "tail" and add their init functions to "list". This recurses over
2237 * the DAGs and ensure the proper init ordering such that each object's
2238 * needed libraries are initialized before the object itself. At the
2239 * same time, this function adds the objects to the global finalization
2240 * list "list_fini" in the opposite order. The write lock must be
2241 * held when this function is called.
2244 initlist_add_objects(Obj_Entry *obj, Obj_Entry *tail, Objlist *list)
2248 if (obj->init_scanned || obj->init_done)
2250 obj->init_scanned = true;
2252 /* Recursively process the successor objects. */
2253 nobj = globallist_next(obj);
2254 if (nobj != NULL && obj != tail)
2255 initlist_add_objects(nobj, tail, list);
2257 /* Recursively process the needed objects. */
2258 if (obj->needed != NULL)
2259 initlist_add_neededs(obj->needed, list);
2260 if (obj->needed_filtees != NULL)
2261 initlist_add_neededs(obj->needed_filtees, list);
2262 if (obj->needed_aux_filtees != NULL)
2263 initlist_add_neededs(obj->needed_aux_filtees, list);
2265 /* Add the object to the init list. */
2266 objlist_push_tail(list, obj);
2268 /* Add the object to the global fini list in the reverse order. */
2269 if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL)
2270 && !obj->on_fini_list) {
2271 objlist_push_head(&list_fini, obj);
2272 obj->on_fini_list = true;
2277 #define FPTR_TARGET(f) ((Elf_Addr) (f))
2281 free_needed_filtees(Needed_Entry *n, RtldLockState *lockstate)
2283 Needed_Entry *needed, *needed1;
2285 for (needed = n; needed != NULL; needed = needed->next) {
2286 if (needed->obj != NULL) {
2287 dlclose_locked(needed->obj, lockstate);
2291 for (needed = n; needed != NULL; needed = needed1) {
2292 needed1 = needed->next;
2298 unload_filtees(Obj_Entry *obj, RtldLockState *lockstate)
2301 free_needed_filtees(obj->needed_filtees, lockstate);
2302 obj->needed_filtees = NULL;
2303 free_needed_filtees(obj->needed_aux_filtees, lockstate);
2304 obj->needed_aux_filtees = NULL;
2305 obj->filtees_loaded = false;
2309 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags,
2310 RtldLockState *lockstate)
2313 for (; needed != NULL; needed = needed->next) {
2314 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
2315 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
2316 RTLD_LOCAL, lockstate);
2321 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
2324 lock_restart_for_upgrade(lockstate);
2325 if (!obj->filtees_loaded) {
2326 load_filtee1(obj, obj->needed_filtees, flags, lockstate);
2327 load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate);
2328 obj->filtees_loaded = true;
2333 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
2337 for (; needed != NULL; needed = needed->next) {
2338 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
2339 flags & ~RTLD_LO_NOLOAD);
2340 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
2347 * Given a shared object, traverse its list of needed objects, and load
2348 * each of them. Returns 0 on success. Generates an error message and
2349 * returns -1 on failure.
2352 load_needed_objects(Obj_Entry *first, int flags)
2356 for (obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
2359 if (process_needed(obj, obj->needed, flags) == -1)
2366 load_preload_objects(void)
2368 char *p = ld_preload;
2370 static const char delim[] = " \t:;";
2375 p += strspn(p, delim);
2376 while (*p != '\0') {
2377 size_t len = strcspn(p, delim);
2382 obj = load_object(p, -1, NULL, 0);
2384 return -1; /* XXX - cleanup */
2385 obj->z_interpose = true;
2388 p += strspn(p, delim);
2390 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
2395 printable_path(const char *path)
2398 return (path == NULL ? "<unknown>" : path);
2402 * Load a shared object into memory, if it is not already loaded. The
2403 * object may be specified by name or by user-supplied file descriptor
2404 * fd_u. In the later case, the fd_u descriptor is not closed, but its
2407 * Returns a pointer to the Obj_Entry for the object. Returns NULL
2411 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
2420 TAILQ_FOREACH(obj, &obj_list, next) {
2421 if (obj->marker || obj->doomed)
2423 if (object_match_name(obj, name))
2427 path = find_library(name, refobj, &fd);
2435 * search_library_pathfds() opens a fresh file descriptor for the
2436 * library, so there is no need to dup().
2438 } else if (fd_u == -1) {
2440 * If we didn't find a match by pathname, or the name is not
2441 * supplied, open the file and check again by device and inode.
2442 * This avoids false mismatches caused by multiple links or ".."
2445 * To avoid a race, we open the file and use fstat() rather than
2448 if ((fd = open(path, O_RDONLY | O_CLOEXEC | O_VERIFY)) == -1) {
2449 _rtld_error("Cannot open \"%s\"", path);
2454 fd = fcntl(fd_u, F_DUPFD_CLOEXEC, 0);
2456 _rtld_error("Cannot dup fd");
2461 if (fstat(fd, &sb) == -1) {
2462 _rtld_error("Cannot fstat \"%s\"", printable_path(path));
2467 TAILQ_FOREACH(obj, &obj_list, next) {
2468 if (obj->marker || obj->doomed)
2470 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
2473 if (obj != NULL && name != NULL) {
2474 object_add_name(obj, name);
2479 if (flags & RTLD_LO_NOLOAD) {
2485 /* First use of this object, so we must map it in */
2486 obj = do_load_object(fd, name, path, &sb, flags);
2495 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
2502 * but first, make sure that environment variables haven't been
2503 * used to circumvent the noexec flag on a filesystem.
2505 if (dangerous_ld_env) {
2506 if (fstatfs(fd, &fs) != 0) {
2507 _rtld_error("Cannot fstatfs \"%s\"", printable_path(path));
2510 if (fs.f_flags & MNT_NOEXEC) {
2511 _rtld_error("Cannot execute objects on %s", fs.f_mntonname);
2515 dbg("loading \"%s\"", printable_path(path));
2516 obj = map_object(fd, printable_path(path), sbp);
2521 * If DT_SONAME is present in the object, digest_dynamic2 already
2522 * added it to the object names.
2525 object_add_name(obj, name);
2527 if (!digest_dynamic(obj, 0))
2529 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path,
2530 obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount);
2531 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
2533 dbg("refusing to load non-loadable \"%s\"", obj->path);
2534 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
2538 obj->dlopened = (flags & RTLD_LO_DLOPEN) != 0;
2539 TAILQ_INSERT_TAIL(&obj_list, obj, next);
2542 linkmap_add(obj); /* for GDB & dlinfo() */
2543 max_stack_flags |= obj->stack_flags;
2545 dbg(" %p .. %p: %s", obj->mapbase,
2546 obj->mapbase + obj->mapsize - 1, obj->path);
2548 dbg(" WARNING: %s has impure text", obj->path);
2549 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
2555 munmap(obj->mapbase, obj->mapsize);
2561 obj_from_addr(const void *addr)
2565 TAILQ_FOREACH(obj, &obj_list, next) {
2568 if (addr < (void *) obj->mapbase)
2570 if (addr < (void *)(obj->mapbase + obj->mapsize))
2579 Elf_Addr *preinit_addr;
2582 preinit_addr = (Elf_Addr *)obj_main->preinit_array;
2583 if (preinit_addr == NULL)
2586 for (index = 0; index < obj_main->preinit_array_num; index++) {
2587 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) {
2588 dbg("calling preinit function for %s at %p", obj_main->path,
2589 (void *)preinit_addr[index]);
2590 LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index],
2591 0, 0, obj_main->path);
2592 call_init_pointer(obj_main, preinit_addr[index]);
2598 * Call the finalization functions for each of the objects in "list"
2599 * belonging to the DAG of "root" and referenced once. If NULL "root"
2600 * is specified, every finalization function will be called regardless
2601 * of the reference count and the list elements won't be freed. All of
2602 * the objects are expected to have non-NULL fini functions.
2605 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
2609 Elf_Addr *fini_addr;
2612 assert(root == NULL || root->refcount == 1);
2615 root->doomed = true;
2618 * Preserve the current error message since a fini function might
2619 * call into the dynamic linker and overwrite it.
2621 saved_msg = errmsg_save();
2623 STAILQ_FOREACH(elm, list, link) {
2624 if (root != NULL && (elm->obj->refcount != 1 ||
2625 objlist_find(&root->dagmembers, elm->obj) == NULL))
2627 /* Remove object from fini list to prevent recursive invocation. */
2628 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2629 /* Ensure that new references cannot be acquired. */
2630 elm->obj->doomed = true;
2632 hold_object(elm->obj);
2633 lock_release(rtld_bind_lock, lockstate);
2635 * It is legal to have both DT_FINI and DT_FINI_ARRAY defined.
2636 * When this happens, DT_FINI_ARRAY is processed first.
2638 fini_addr = (Elf_Addr *)elm->obj->fini_array;
2639 if (fini_addr != NULL && elm->obj->fini_array_num > 0) {
2640 for (index = elm->obj->fini_array_num - 1; index >= 0;
2642 if (fini_addr[index] != 0 && fini_addr[index] != 1) {
2643 dbg("calling fini function for %s at %p",
2644 elm->obj->path, (void *)fini_addr[index]);
2645 LD_UTRACE(UTRACE_FINI_CALL, elm->obj,
2646 (void *)fini_addr[index], 0, 0, elm->obj->path);
2647 call_initfini_pointer(elm->obj, fini_addr[index]);
2651 if (elm->obj->fini != (Elf_Addr)NULL) {
2652 dbg("calling fini function for %s at %p", elm->obj->path,
2653 (void *)elm->obj->fini);
2654 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini,
2655 0, 0, elm->obj->path);
2656 call_initfini_pointer(elm->obj, elm->obj->fini);
2658 wlock_acquire(rtld_bind_lock, lockstate);
2659 unhold_object(elm->obj);
2660 /* No need to free anything if process is going down. */
2664 * We must restart the list traversal after every fini call
2665 * because a dlclose() call from the fini function or from
2666 * another thread might have modified the reference counts.
2670 } while (elm != NULL);
2671 errmsg_restore(saved_msg);
2675 * Call the initialization functions for each of the objects in
2676 * "list". All of the objects are expected to have non-NULL init
2680 objlist_call_init(Objlist *list, RtldLockState *lockstate)
2685 Elf_Addr *init_addr;
2686 void (*reg)(void (*)(void));
2690 * Clean init_scanned flag so that objects can be rechecked and
2691 * possibly initialized earlier if any of vectors called below
2692 * cause the change by using dlopen.
2694 TAILQ_FOREACH(obj, &obj_list, next) {
2697 obj->init_scanned = false;
2701 * Preserve the current error message since an init function might
2702 * call into the dynamic linker and overwrite it.
2704 saved_msg = errmsg_save();
2705 STAILQ_FOREACH(elm, list, link) {
2706 if (elm->obj->init_done) /* Initialized early. */
2709 * Race: other thread might try to use this object before current
2710 * one completes the initialization. Not much can be done here
2711 * without better locking.
2713 elm->obj->init_done = true;
2714 hold_object(elm->obj);
2716 if (elm->obj == obj_main && obj_main->crt_no_init) {
2717 reg = (void (*)(void (*)(void)))get_program_var_addr(
2718 "__libc_atexit", lockstate);
2720 lock_release(rtld_bind_lock, lockstate);
2723 rtld_exit_ptr = rtld_nop_exit;
2727 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined.
2728 * When this happens, DT_INIT is processed first.
2730 if (elm->obj->init != (Elf_Addr)NULL) {
2731 dbg("calling init function for %s at %p", elm->obj->path,
2732 (void *)elm->obj->init);
2733 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init,
2734 0, 0, elm->obj->path);
2735 call_initfini_pointer(elm->obj, elm->obj->init);
2737 init_addr = (Elf_Addr *)elm->obj->init_array;
2738 if (init_addr != NULL) {
2739 for (index = 0; index < elm->obj->init_array_num; index++) {
2740 if (init_addr[index] != 0 && init_addr[index] != 1) {
2741 dbg("calling init function for %s at %p", elm->obj->path,
2742 (void *)init_addr[index]);
2743 LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
2744 (void *)init_addr[index], 0, 0, elm->obj->path);
2745 call_init_pointer(elm->obj, init_addr[index]);
2749 wlock_acquire(rtld_bind_lock, lockstate);
2750 unhold_object(elm->obj);
2752 errmsg_restore(saved_msg);
2756 objlist_clear(Objlist *list)
2760 while (!STAILQ_EMPTY(list)) {
2761 elm = STAILQ_FIRST(list);
2762 STAILQ_REMOVE_HEAD(list, link);
2767 static Objlist_Entry *
2768 objlist_find(Objlist *list, const Obj_Entry *obj)
2772 STAILQ_FOREACH(elm, list, link)
2773 if (elm->obj == obj)
2779 objlist_init(Objlist *list)
2785 objlist_push_head(Objlist *list, Obj_Entry *obj)
2789 elm = NEW(Objlist_Entry);
2791 STAILQ_INSERT_HEAD(list, elm, link);
2795 objlist_push_tail(Objlist *list, Obj_Entry *obj)
2799 elm = NEW(Objlist_Entry);
2801 STAILQ_INSERT_TAIL(list, elm, link);
2805 objlist_put_after(Objlist *list, Obj_Entry *listobj, Obj_Entry *obj)
2807 Objlist_Entry *elm, *listelm;
2809 STAILQ_FOREACH(listelm, list, link) {
2810 if (listelm->obj == listobj)
2813 elm = NEW(Objlist_Entry);
2815 if (listelm != NULL)
2816 STAILQ_INSERT_AFTER(list, listelm, elm, link);
2818 STAILQ_INSERT_TAIL(list, elm, link);
2822 objlist_remove(Objlist *list, Obj_Entry *obj)
2826 if ((elm = objlist_find(list, obj)) != NULL) {
2827 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2833 * Relocate dag rooted in the specified object.
2834 * Returns 0 on success, or -1 on failure.
2838 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj,
2839 int flags, RtldLockState *lockstate)
2845 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2846 error = relocate_object(elm->obj, bind_now, rtldobj, flags,
2855 * Prepare for, or clean after, relocating an object marked with
2856 * DT_TEXTREL or DF_TEXTREL. Before relocating, all read-only
2857 * segments are remapped read-write. After relocations are done, the
2858 * segment's permissions are returned back to the modes specified in
2859 * the phdrs. If any relocation happened, or always for wired
2860 * program, COW is triggered.
2863 reloc_textrel_prot(Obj_Entry *obj, bool before)
2870 for (l = obj->phsize / sizeof(*ph), ph = obj->phdr; l > 0;
2872 if (ph->p_type != PT_LOAD || (ph->p_flags & PF_W) != 0)
2874 base = obj->relocbase + trunc_page(ph->p_vaddr);
2875 sz = round_page(ph->p_vaddr + ph->p_filesz) -
2876 trunc_page(ph->p_vaddr);
2877 prot = convert_prot(ph->p_flags) | (before ? PROT_WRITE : 0);
2878 if (mprotect(base, sz, prot) == -1) {
2879 _rtld_error("%s: Cannot write-%sable text segment: %s",
2880 obj->path, before ? "en" : "dis",
2881 rtld_strerror(errno));
2889 * Relocate single object.
2890 * Returns 0 on success, or -1 on failure.
2893 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
2894 int flags, RtldLockState *lockstate)
2899 obj->relocated = true;
2901 dbg("relocating \"%s\"", obj->path);
2903 if (obj->symtab == NULL || obj->strtab == NULL ||
2904 !(obj->valid_hash_sysv || obj->valid_hash_gnu)) {
2905 _rtld_error("%s: Shared object has no run-time symbol table",
2910 /* There are relocations to the write-protected text segment. */
2911 if (obj->textrel && reloc_textrel_prot(obj, true) != 0)
2914 /* Process the non-PLT non-IFUNC relocations. */
2915 if (reloc_non_plt(obj, rtldobj, flags, lockstate))
2918 /* Re-protected the text segment. */
2919 if (obj->textrel && reloc_textrel_prot(obj, false) != 0)
2922 /* Set the special PLT or GOT entries. */
2925 /* Process the PLT relocations. */
2926 if (reloc_plt(obj, flags, lockstate) == -1)
2928 /* Relocate the jump slots if we are doing immediate binding. */
2929 if ((obj->bind_now || bind_now) && reloc_jmpslots(obj, flags,
2933 if (!obj->mainprog && obj_enforce_relro(obj) == -1)
2937 * Set up the magic number and version in the Obj_Entry. These
2938 * were checked in the crt1.o from the original ElfKit, so we
2939 * set them for backward compatibility.
2941 obj->magic = RTLD_MAGIC;
2942 obj->version = RTLD_VERSION;
2948 * Relocate newly-loaded shared objects. The argument is a pointer to
2949 * the Obj_Entry for the first such object. All objects from the first
2950 * to the end of the list of objects are relocated. Returns 0 on success,
2954 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
2955 int flags, RtldLockState *lockstate)
2960 for (error = 0, obj = first; obj != NULL;
2961 obj = TAILQ_NEXT(obj, next)) {
2964 error = relocate_object(obj, bind_now, rtldobj, flags,
2973 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
2974 * referencing STT_GNU_IFUNC symbols is postponed till the other
2975 * relocations are done. The indirect functions specified as
2976 * ifunc are allowed to call other symbols, so we need to have
2977 * objects relocated before asking for resolution from indirects.
2979 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
2980 * instead of the usual lazy handling of PLT slots. It is
2981 * consistent with how GNU does it.
2984 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags,
2985 RtldLockState *lockstate)
2988 if (obj->ifuncs_resolved)
2990 obj->ifuncs_resolved = true;
2991 if (!obj->irelative && !obj->irelative_nonplt &&
2992 !((obj->bind_now || bind_now) && obj->gnu_ifunc))
2994 if (obj_disable_relro(obj) == -1 ||
2995 (obj->irelative && reloc_iresolve(obj, lockstate) == -1) ||
2996 (obj->irelative_nonplt && reloc_iresolve_nonplt(obj,
2997 lockstate) == -1) ||
2998 ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
2999 reloc_gnu_ifunc(obj, flags, lockstate) == -1) ||
3000 obj_enforce_relro(obj) == -1)
3006 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags,
3007 RtldLockState *lockstate)
3012 STAILQ_FOREACH(elm, list, link) {
3016 if (resolve_object_ifunc(obj, bind_now, flags,
3024 * Cleanup procedure. It will be called (by the atexit mechanism) just
3025 * before the process exits.
3030 RtldLockState lockstate;
3032 wlock_acquire(rtld_bind_lock, &lockstate);
3034 objlist_call_fini(&list_fini, NULL, &lockstate);
3035 /* No need to remove the items from the list, since we are exiting. */
3036 if (!libmap_disable)
3038 lock_release(rtld_bind_lock, &lockstate);
3047 * Iterate over a search path, translate each element, and invoke the
3048 * callback on the result.
3051 path_enumerate(const char *path, path_enum_proc callback,
3052 const char *refobj_path, void *arg)
3058 path += strspn(path, ":;");
3059 while (*path != '\0') {
3063 len = strcspn(path, ":;");
3064 trans = lm_findn(refobj_path, path, len);
3066 res = callback(trans, strlen(trans), arg);
3068 res = callback(path, len, arg);
3074 path += strspn(path, ":;");
3080 struct try_library_args {
3089 try_library_path(const char *dir, size_t dirlen, void *param)
3091 struct try_library_args *arg;
3095 if (*dir == '/' || trust) {
3098 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
3101 pathname = arg->buffer;
3102 strncpy(pathname, dir, dirlen);
3103 pathname[dirlen] = '/';
3104 strcpy(pathname + dirlen + 1, arg->name);
3106 dbg(" Trying \"%s\"", pathname);
3107 fd = open(pathname, O_RDONLY | O_CLOEXEC | O_VERIFY);
3109 dbg(" Opened \"%s\", fd %d", pathname, fd);
3110 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
3111 strcpy(pathname, arg->buffer);
3115 dbg(" Failed to open \"%s\": %s",
3116 pathname, rtld_strerror(errno));
3123 search_library_path(const char *name, const char *path,
3124 const char *refobj_path, int *fdp)
3127 struct try_library_args arg;
3133 arg.namelen = strlen(name);
3134 arg.buffer = xmalloc(PATH_MAX);
3135 arg.buflen = PATH_MAX;
3138 p = path_enumerate(path, try_library_path, refobj_path, &arg);
3148 * Finds the library with the given name using the directory descriptors
3149 * listed in the LD_LIBRARY_PATH_FDS environment variable.
3151 * Returns a freshly-opened close-on-exec file descriptor for the library,
3152 * or -1 if the library cannot be found.
3155 search_library_pathfds(const char *name, const char *path, int *fdp)
3157 char *envcopy, *fdstr, *found, *last_token;
3161 dbg("%s('%s', '%s', fdp)", __func__, name, path);
3163 /* Don't load from user-specified libdirs into setuid binaries. */
3167 /* We can't do anything if LD_LIBRARY_PATH_FDS isn't set. */
3171 /* LD_LIBRARY_PATH_FDS only works with relative paths. */
3172 if (name[0] == '/') {
3173 dbg("Absolute path (%s) passed to %s", name, __func__);
3178 * Use strtok_r() to walk the FD:FD:FD list. This requires a local
3179 * copy of the path, as strtok_r rewrites separator tokens
3183 envcopy = xstrdup(path);
3184 for (fdstr = strtok_r(envcopy, ":", &last_token); fdstr != NULL;
3185 fdstr = strtok_r(NULL, ":", &last_token)) {
3186 dirfd = parse_integer(fdstr);
3188 _rtld_error("failed to parse directory FD: '%s'",
3192 fd = __sys_openat(dirfd, name, O_RDONLY | O_CLOEXEC | O_VERIFY);
3195 len = strlen(fdstr) + strlen(name) + 3;
3196 found = xmalloc(len);
3197 if (rtld_snprintf(found, len, "#%d/%s", dirfd, name) < 0) {
3198 _rtld_error("error generating '%d/%s'",
3202 dbg("open('%s') => %d", found, fd);
3213 dlclose(void *handle)
3215 RtldLockState lockstate;
3218 wlock_acquire(rtld_bind_lock, &lockstate);
3219 error = dlclose_locked(handle, &lockstate);
3220 lock_release(rtld_bind_lock, &lockstate);
3225 dlclose_locked(void *handle, RtldLockState *lockstate)
3229 root = dlcheck(handle);
3232 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
3235 /* Unreference the object and its dependencies. */
3236 root->dl_refcount--;
3238 if (root->refcount == 1) {
3240 * The object will be no longer referenced, so we must unload it.
3241 * First, call the fini functions.
3243 objlist_call_fini(&list_fini, root, lockstate);
3247 /* Finish cleaning up the newly-unreferenced objects. */
3248 GDB_STATE(RT_DELETE,&root->linkmap);
3249 unload_object(root, lockstate);
3250 GDB_STATE(RT_CONSISTENT,NULL);
3254 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
3261 char *msg = error_message;
3262 error_message = NULL;
3267 * This function is deprecated and has no effect.
3270 dllockinit(void *context,
3271 void *(*_lock_create)(void *context) __unused,
3272 void (*_rlock_acquire)(void *lock) __unused,
3273 void (*_wlock_acquire)(void *lock) __unused,
3274 void (*_lock_release)(void *lock) __unused,
3275 void (*_lock_destroy)(void *lock) __unused,
3276 void (*context_destroy)(void *context))
3278 static void *cur_context;
3279 static void (*cur_context_destroy)(void *);
3281 /* Just destroy the context from the previous call, if necessary. */
3282 if (cur_context_destroy != NULL)
3283 cur_context_destroy(cur_context);
3284 cur_context = context;
3285 cur_context_destroy = context_destroy;
3289 dlopen(const char *name, int mode)
3292 return (rtld_dlopen(name, -1, mode));
3296 fdlopen(int fd, int mode)
3299 return (rtld_dlopen(NULL, fd, mode));
3303 rtld_dlopen(const char *name, int fd, int mode)
3305 RtldLockState lockstate;
3308 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
3309 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
3310 if (ld_tracing != NULL) {
3311 rlock_acquire(rtld_bind_lock, &lockstate);
3312 if (sigsetjmp(lockstate.env, 0) != 0)
3313 lock_upgrade(rtld_bind_lock, &lockstate);
3314 environ = __DECONST(char **, *get_program_var_addr("environ", &lockstate));
3315 lock_release(rtld_bind_lock, &lockstate);
3317 lo_flags = RTLD_LO_DLOPEN;
3318 if (mode & RTLD_NODELETE)
3319 lo_flags |= RTLD_LO_NODELETE;
3320 if (mode & RTLD_NOLOAD)
3321 lo_flags |= RTLD_LO_NOLOAD;
3322 if (ld_tracing != NULL)
3323 lo_flags |= RTLD_LO_TRACE | RTLD_LO_IGNSTLS;
3325 return (dlopen_object(name, fd, obj_main, lo_flags,
3326 mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL));
3330 dlopen_cleanup(Obj_Entry *obj, RtldLockState *lockstate)
3335 if (obj->refcount == 0)
3336 unload_object(obj, lockstate);
3340 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
3341 int mode, RtldLockState *lockstate)
3343 Obj_Entry *old_obj_tail;
3346 RtldLockState mlockstate;
3349 objlist_init(&initlist);
3351 if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) {
3352 wlock_acquire(rtld_bind_lock, &mlockstate);
3353 lockstate = &mlockstate;
3355 GDB_STATE(RT_ADD,NULL);
3357 old_obj_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
3359 if (name == NULL && fd == -1) {
3363 obj = load_object(name, fd, refobj, lo_flags);
3368 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
3369 objlist_push_tail(&list_global, obj);
3370 if (globallist_next(old_obj_tail) != NULL) {
3371 /* We loaded something new. */
3372 assert(globallist_next(old_obj_tail) == obj);
3374 if ((lo_flags & (RTLD_LO_EARLY | RTLD_LO_IGNSTLS)) == 0 &&
3375 obj->static_tls && !allocate_tls_offset(obj)) {
3376 _rtld_error("%s: No space available "
3377 "for static Thread Local Storage", obj->path);
3381 result = load_needed_objects(obj, lo_flags & (RTLD_LO_DLOPEN |
3382 RTLD_LO_EARLY | RTLD_LO_IGNSTLS));
3386 result = rtld_verify_versions(&obj->dagmembers);
3387 if (result != -1 && ld_tracing)
3389 if (result == -1 || relocate_object_dag(obj,
3390 (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld,
3391 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3393 dlopen_cleanup(obj, lockstate);
3395 } else if (lo_flags & RTLD_LO_EARLY) {
3397 * Do not call the init functions for early loaded
3398 * filtees. The image is still not initialized enough
3401 * Our object is found by the global object list and
3402 * will be ordered among all init calls done right
3403 * before transferring control to main.
3406 /* Make list of init functions to call. */
3407 initlist_add_objects(obj, obj, &initlist);
3410 * Process all no_delete or global objects here, given
3411 * them own DAGs to prevent their dependencies from being
3412 * unloaded. This has to be done after we have loaded all
3413 * of the dependencies, so that we do not miss any.
3419 * Bump the reference counts for objects on this DAG. If
3420 * this is the first dlopen() call for the object that was
3421 * already loaded as a dependency, initialize the dag
3427 if ((lo_flags & RTLD_LO_TRACE) != 0)
3430 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
3431 obj->z_nodelete) && !obj->ref_nodel) {
3432 dbg("obj %s nodelete", obj->path);
3434 obj->z_nodelete = obj->ref_nodel = true;
3438 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
3440 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
3442 if ((lo_flags & RTLD_LO_EARLY) == 0) {
3443 map_stacks_exec(lockstate);
3445 distribute_static_tls(&initlist, lockstate);
3448 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
3449 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3451 objlist_clear(&initlist);
3452 dlopen_cleanup(obj, lockstate);
3453 if (lockstate == &mlockstate)
3454 lock_release(rtld_bind_lock, lockstate);
3458 if (!(lo_flags & RTLD_LO_EARLY)) {
3459 /* Call the init functions. */
3460 objlist_call_init(&initlist, lockstate);
3462 objlist_clear(&initlist);
3463 if (lockstate == &mlockstate)
3464 lock_release(rtld_bind_lock, lockstate);
3467 trace_loaded_objects(obj);
3468 if (lockstate == &mlockstate)
3469 lock_release(rtld_bind_lock, lockstate);
3474 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
3478 const Obj_Entry *obj, *defobj;
3481 RtldLockState lockstate;
3488 symlook_init(&req, name);
3490 req.flags = flags | SYMLOOK_IN_PLT;
3491 req.lockstate = &lockstate;
3493 LD_UTRACE(UTRACE_DLSYM_START, handle, NULL, 0, 0, name);
3494 rlock_acquire(rtld_bind_lock, &lockstate);
3495 if (sigsetjmp(lockstate.env, 0) != 0)
3496 lock_upgrade(rtld_bind_lock, &lockstate);
3497 if (handle == NULL || handle == RTLD_NEXT ||
3498 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
3500 if ((obj = obj_from_addr(retaddr)) == NULL) {
3501 _rtld_error("Cannot determine caller's shared object");
3502 lock_release(rtld_bind_lock, &lockstate);
3503 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3506 if (handle == NULL) { /* Just the caller's shared object. */
3507 res = symlook_obj(&req, obj);
3510 defobj = req.defobj_out;
3512 } else if (handle == RTLD_NEXT || /* Objects after caller's */
3513 handle == RTLD_SELF) { /* ... caller included */
3514 if (handle == RTLD_NEXT)
3515 obj = globallist_next(obj);
3516 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
3519 res = symlook_obj(&req, obj);
3522 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) {
3524 defobj = req.defobj_out;
3525 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3531 * Search the dynamic linker itself, and possibly resolve the
3532 * symbol from there. This is how the application links to
3533 * dynamic linker services such as dlopen.
3535 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3536 res = symlook_obj(&req, &obj_rtld);
3539 defobj = req.defobj_out;
3543 assert(handle == RTLD_DEFAULT);
3544 res = symlook_default(&req, obj);
3546 defobj = req.defobj_out;
3551 if ((obj = dlcheck(handle)) == NULL) {
3552 lock_release(rtld_bind_lock, &lockstate);
3553 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3557 donelist_init(&donelist);
3558 if (obj->mainprog) {
3559 /* Handle obtained by dlopen(NULL, ...) implies global scope. */
3560 res = symlook_global(&req, &donelist);
3563 defobj = req.defobj_out;
3566 * Search the dynamic linker itself, and possibly resolve the
3567 * symbol from there. This is how the application links to
3568 * dynamic linker services such as dlopen.
3570 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3571 res = symlook_obj(&req, &obj_rtld);
3574 defobj = req.defobj_out;
3579 /* Search the whole DAG rooted at the given object. */
3580 res = symlook_list(&req, &obj->dagmembers, &donelist);
3583 defobj = req.defobj_out;
3589 lock_release(rtld_bind_lock, &lockstate);
3592 * The value required by the caller is derived from the value
3593 * of the symbol. this is simply the relocated value of the
3596 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
3597 sym = make_function_pointer(def, defobj);
3598 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
3599 sym = rtld_resolve_ifunc(defobj, def);
3600 else if (ELF_ST_TYPE(def->st_info) == STT_TLS) {
3601 ti.ti_module = defobj->tlsindex;
3602 ti.ti_offset = def->st_value;
3603 sym = __tls_get_addr(&ti);
3605 sym = defobj->relocbase + def->st_value;
3606 LD_UTRACE(UTRACE_DLSYM_STOP, handle, sym, 0, 0, name);
3610 _rtld_error("Undefined symbol \"%s%s%s\"", name, ve != NULL ? "@" : "",
3611 ve != NULL ? ve->name : "");
3612 lock_release(rtld_bind_lock, &lockstate);
3613 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3618 dlsym(void *handle, const char *name)
3620 return do_dlsym(handle, name, __builtin_return_address(0), NULL,
3625 dlfunc(void *handle, const char *name)
3632 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
3638 dlvsym(void *handle, const char *name, const char *version)
3642 ventry.name = version;
3644 ventry.hash = elf_hash(version);
3646 return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
3651 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
3653 const Obj_Entry *obj;
3654 RtldLockState lockstate;
3656 rlock_acquire(rtld_bind_lock, &lockstate);
3657 obj = obj_from_addr(addr);
3659 _rtld_error("No shared object contains address");
3660 lock_release(rtld_bind_lock, &lockstate);
3663 rtld_fill_dl_phdr_info(obj, phdr_info);
3664 lock_release(rtld_bind_lock, &lockstate);
3669 dladdr(const void *addr, Dl_info *info)
3671 const Obj_Entry *obj;
3674 unsigned long symoffset;
3675 RtldLockState lockstate;
3677 rlock_acquire(rtld_bind_lock, &lockstate);
3678 obj = obj_from_addr(addr);
3680 _rtld_error("No shared object contains address");
3681 lock_release(rtld_bind_lock, &lockstate);
3684 info->dli_fname = obj->path;
3685 info->dli_fbase = obj->mapbase;
3686 info->dli_saddr = (void *)0;
3687 info->dli_sname = NULL;
3690 * Walk the symbol list looking for the symbol whose address is
3691 * closest to the address sent in.
3693 for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) {
3694 def = obj->symtab + symoffset;
3697 * For skip the symbol if st_shndx is either SHN_UNDEF or
3700 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
3704 * If the symbol is greater than the specified address, or if it
3705 * is further away from addr than the current nearest symbol,
3708 symbol_addr = obj->relocbase + def->st_value;
3709 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
3712 /* Update our idea of the nearest symbol. */
3713 info->dli_sname = obj->strtab + def->st_name;
3714 info->dli_saddr = symbol_addr;
3717 if (info->dli_saddr == addr)
3720 lock_release(rtld_bind_lock, &lockstate);
3725 dlinfo(void *handle, int request, void *p)
3727 const Obj_Entry *obj;
3728 RtldLockState lockstate;
3731 rlock_acquire(rtld_bind_lock, &lockstate);
3733 if (handle == NULL || handle == RTLD_SELF) {
3736 retaddr = __builtin_return_address(0); /* __GNUC__ only */
3737 if ((obj = obj_from_addr(retaddr)) == NULL)
3738 _rtld_error("Cannot determine caller's shared object");
3740 obj = dlcheck(handle);
3743 lock_release(rtld_bind_lock, &lockstate);
3749 case RTLD_DI_LINKMAP:
3750 *((struct link_map const **)p) = &obj->linkmap;
3752 case RTLD_DI_ORIGIN:
3753 error = rtld_dirname(obj->path, p);
3756 case RTLD_DI_SERINFOSIZE:
3757 case RTLD_DI_SERINFO:
3758 error = do_search_info(obj, request, (struct dl_serinfo *)p);
3762 _rtld_error("Invalid request %d passed to dlinfo()", request);
3766 lock_release(rtld_bind_lock, &lockstate);
3772 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
3775 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
3776 phdr_info->dlpi_name = obj->path;
3777 phdr_info->dlpi_phdr = obj->phdr;
3778 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
3779 phdr_info->dlpi_tls_modid = obj->tlsindex;
3780 phdr_info->dlpi_tls_data = obj->tlsinit;
3781 phdr_info->dlpi_adds = obj_loads;
3782 phdr_info->dlpi_subs = obj_loads - obj_count;
3786 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
3788 struct dl_phdr_info phdr_info;
3789 Obj_Entry *obj, marker;
3790 RtldLockState bind_lockstate, phdr_lockstate;
3793 init_marker(&marker);
3796 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
3797 wlock_acquire(rtld_bind_lock, &bind_lockstate);
3798 for (obj = globallist_curr(TAILQ_FIRST(&obj_list)); obj != NULL;) {
3799 TAILQ_INSERT_AFTER(&obj_list, obj, &marker, next);
3800 rtld_fill_dl_phdr_info(obj, &phdr_info);
3802 lock_release(rtld_bind_lock, &bind_lockstate);
3804 error = callback(&phdr_info, sizeof phdr_info, param);
3806 wlock_acquire(rtld_bind_lock, &bind_lockstate);
3808 obj = globallist_next(&marker);
3809 TAILQ_REMOVE(&obj_list, &marker, next);
3811 lock_release(rtld_bind_lock, &bind_lockstate);
3812 lock_release(rtld_phdr_lock, &phdr_lockstate);
3818 rtld_fill_dl_phdr_info(&obj_rtld, &phdr_info);
3819 lock_release(rtld_bind_lock, &bind_lockstate);
3820 error = callback(&phdr_info, sizeof(phdr_info), param);
3822 lock_release(rtld_phdr_lock, &phdr_lockstate);
3827 fill_search_info(const char *dir, size_t dirlen, void *param)
3829 struct fill_search_info_args *arg;
3833 if (arg->request == RTLD_DI_SERINFOSIZE) {
3834 arg->serinfo->dls_cnt ++;
3835 arg->serinfo->dls_size += sizeof(struct dl_serpath) + dirlen + 1;
3837 struct dl_serpath *s_entry;
3839 s_entry = arg->serpath;
3840 s_entry->dls_name = arg->strspace;
3841 s_entry->dls_flags = arg->flags;
3843 strncpy(arg->strspace, dir, dirlen);
3844 arg->strspace[dirlen] = '\0';
3846 arg->strspace += dirlen + 1;
3854 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
3856 struct dl_serinfo _info;
3857 struct fill_search_info_args args;
3859 args.request = RTLD_DI_SERINFOSIZE;
3860 args.serinfo = &_info;
3862 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
3865 path_enumerate(obj->rpath, fill_search_info, NULL, &args);
3866 path_enumerate(ld_library_path, fill_search_info, NULL, &args);
3867 path_enumerate(obj->runpath, fill_search_info, NULL, &args);
3868 path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args);
3869 if (!obj->z_nodeflib)
3870 path_enumerate(ld_standard_library_path, fill_search_info, NULL, &args);
3873 if (request == RTLD_DI_SERINFOSIZE) {
3874 info->dls_size = _info.dls_size;
3875 info->dls_cnt = _info.dls_cnt;
3879 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
3880 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
3884 args.request = RTLD_DI_SERINFO;
3885 args.serinfo = info;
3886 args.serpath = &info->dls_serpath[0];
3887 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
3889 args.flags = LA_SER_RUNPATH;
3890 if (path_enumerate(obj->rpath, fill_search_info, NULL, &args) != NULL)
3893 args.flags = LA_SER_LIBPATH;
3894 if (path_enumerate(ld_library_path, fill_search_info, NULL, &args) != NULL)
3897 args.flags = LA_SER_RUNPATH;
3898 if (path_enumerate(obj->runpath, fill_search_info, NULL, &args) != NULL)
3901 args.flags = LA_SER_CONFIG;
3902 if (path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args)
3906 args.flags = LA_SER_DEFAULT;
3907 if (!obj->z_nodeflib && path_enumerate(ld_standard_library_path,
3908 fill_search_info, NULL, &args) != NULL)
3914 rtld_dirname(const char *path, char *bname)
3918 /* Empty or NULL string gets treated as "." */
3919 if (path == NULL || *path == '\0') {
3925 /* Strip trailing slashes */
3926 endp = path + strlen(path) - 1;
3927 while (endp > path && *endp == '/')
3930 /* Find the start of the dir */
3931 while (endp > path && *endp != '/')
3934 /* Either the dir is "/" or there are no slashes */
3936 bname[0] = *endp == '/' ? '/' : '.';
3942 } while (endp > path && *endp == '/');
3945 if (endp - path + 2 > PATH_MAX)
3947 _rtld_error("Filename is too long: %s", path);
3951 strncpy(bname, path, endp - path + 1);
3952 bname[endp - path + 1] = '\0';
3957 rtld_dirname_abs(const char *path, char *base)
3961 if (realpath(path, base) == NULL) {
3962 _rtld_error("realpath \"%s\" failed (%s)", path,
3963 rtld_strerror(errno));
3966 dbg("%s -> %s", path, base);
3967 last = strrchr(base, '/');
3969 _rtld_error("non-abs result from realpath \"%s\"", path);
3978 linkmap_add(Obj_Entry *obj)
3980 struct link_map *l = &obj->linkmap;
3981 struct link_map *prev;
3983 obj->linkmap.l_name = obj->path;
3984 obj->linkmap.l_addr = obj->mapbase;
3985 obj->linkmap.l_ld = obj->dynamic;
3987 /* GDB needs load offset on MIPS to use the symbols */
3988 obj->linkmap.l_offs = obj->relocbase;
3991 if (r_debug.r_map == NULL) {
3997 * Scan to the end of the list, but not past the entry for the
3998 * dynamic linker, which we want to keep at the very end.
4000 for (prev = r_debug.r_map;
4001 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
4002 prev = prev->l_next)
4005 /* Link in the new entry. */
4007 l->l_next = prev->l_next;
4008 if (l->l_next != NULL)
4009 l->l_next->l_prev = l;
4014 linkmap_delete(Obj_Entry *obj)
4016 struct link_map *l = &obj->linkmap;
4018 if (l->l_prev == NULL) {
4019 if ((r_debug.r_map = l->l_next) != NULL)
4020 l->l_next->l_prev = NULL;
4024 if ((l->l_prev->l_next = l->l_next) != NULL)
4025 l->l_next->l_prev = l->l_prev;
4029 * Function for the debugger to set a breakpoint on to gain control.
4031 * The two parameters allow the debugger to easily find and determine
4032 * what the runtime loader is doing and to whom it is doing it.
4034 * When the loadhook trap is hit (r_debug_state, set at program
4035 * initialization), the arguments can be found on the stack:
4037 * +8 struct link_map *m
4038 * +4 struct r_debug *rd
4042 r_debug_state(struct r_debug* rd __unused, struct link_map *m __unused)
4045 * The following is a hack to force the compiler to emit calls to
4046 * this function, even when optimizing. If the function is empty,
4047 * the compiler is not obliged to emit any code for calls to it,
4048 * even when marked __noinline. However, gdb depends on those
4051 __compiler_membar();
4055 * A function called after init routines have completed. This can be used to
4056 * break before a program's entry routine is called, and can be used when
4057 * main is not available in the symbol table.
4060 _r_debug_postinit(struct link_map *m __unused)
4063 /* See r_debug_state(). */
4064 __compiler_membar();
4068 release_object(Obj_Entry *obj)
4071 if (obj->holdcount > 0) {
4072 obj->unholdfree = true;
4075 munmap(obj->mapbase, obj->mapsize);
4076 linkmap_delete(obj);
4081 * Get address of the pointer variable in the main program.
4082 * Prefer non-weak symbol over the weak one.
4084 static const void **
4085 get_program_var_addr(const char *name, RtldLockState *lockstate)
4090 symlook_init(&req, name);
4091 req.lockstate = lockstate;
4092 donelist_init(&donelist);
4093 if (symlook_global(&req, &donelist) != 0)
4095 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
4096 return ((const void **)make_function_pointer(req.sym_out,
4098 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
4099 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
4101 return ((const void **)(req.defobj_out->relocbase +
4102 req.sym_out->st_value));
4106 * Set a pointer variable in the main program to the given value. This
4107 * is used to set key variables such as "environ" before any of the
4108 * init functions are called.
4111 set_program_var(const char *name, const void *value)
4115 if ((addr = get_program_var_addr(name, NULL)) != NULL) {
4116 dbg("\"%s\": *%p <-- %p", name, addr, value);
4122 * Search the global objects, including dependencies and main object,
4123 * for the given symbol.
4126 symlook_global(SymLook *req, DoneList *donelist)
4129 const Objlist_Entry *elm;
4132 symlook_init_from_req(&req1, req);
4134 /* Search all objects loaded at program start up. */
4135 if (req->defobj_out == NULL ||
4136 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
4137 res = symlook_list(&req1, &list_main, donelist);
4138 if (res == 0 && (req->defobj_out == NULL ||
4139 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4140 req->sym_out = req1.sym_out;
4141 req->defobj_out = req1.defobj_out;
4142 assert(req->defobj_out != NULL);
4146 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
4147 STAILQ_FOREACH(elm, &list_global, link) {
4148 if (req->defobj_out != NULL &&
4149 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
4151 res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
4152 if (res == 0 && (req->defobj_out == NULL ||
4153 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4154 req->sym_out = req1.sym_out;
4155 req->defobj_out = req1.defobj_out;
4156 assert(req->defobj_out != NULL);
4160 return (req->sym_out != NULL ? 0 : ESRCH);
4164 * Given a symbol name in a referencing object, find the corresponding
4165 * definition of the symbol. Returns a pointer to the symbol, or NULL if
4166 * no definition was found. Returns a pointer to the Obj_Entry of the
4167 * defining object via the reference parameter DEFOBJ_OUT.
4170 symlook_default(SymLook *req, const Obj_Entry *refobj)
4173 const Objlist_Entry *elm;
4177 donelist_init(&donelist);
4178 symlook_init_from_req(&req1, req);
4181 * Look first in the referencing object if linked symbolically,
4182 * and similarly handle protected symbols.
4184 res = symlook_obj(&req1, refobj);
4185 if (res == 0 && (refobj->symbolic ||
4186 ELF_ST_VISIBILITY(req1.sym_out->st_other) == STV_PROTECTED)) {
4187 req->sym_out = req1.sym_out;
4188 req->defobj_out = req1.defobj_out;
4189 assert(req->defobj_out != NULL);
4191 if (refobj->symbolic || req->defobj_out != NULL)
4192 donelist_check(&donelist, refobj);
4194 symlook_global(req, &donelist);
4196 /* Search all dlopened DAGs containing the referencing object. */
4197 STAILQ_FOREACH(elm, &refobj->dldags, link) {
4198 if (req->sym_out != NULL &&
4199 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
4201 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
4202 if (res == 0 && (req->sym_out == NULL ||
4203 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4204 req->sym_out = req1.sym_out;
4205 req->defobj_out = req1.defobj_out;
4206 assert(req->defobj_out != NULL);
4211 * Search the dynamic linker itself, and possibly resolve the
4212 * symbol from there. This is how the application links to
4213 * dynamic linker services such as dlopen.
4215 if (req->sym_out == NULL ||
4216 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
4217 res = symlook_obj(&req1, &obj_rtld);
4219 req->sym_out = req1.sym_out;
4220 req->defobj_out = req1.defobj_out;
4221 assert(req->defobj_out != NULL);
4225 return (req->sym_out != NULL ? 0 : ESRCH);
4229 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
4232 const Obj_Entry *defobj;
4233 const Objlist_Entry *elm;
4239 STAILQ_FOREACH(elm, objlist, link) {
4240 if (donelist_check(dlp, elm->obj))
4242 symlook_init_from_req(&req1, req);
4243 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
4244 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
4246 defobj = req1.defobj_out;
4247 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
4254 req->defobj_out = defobj;
4261 * Search the chain of DAGS cointed to by the given Needed_Entry
4262 * for a symbol of the given name. Each DAG is scanned completely
4263 * before advancing to the next one. Returns a pointer to the symbol,
4264 * or NULL if no definition was found.
4267 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
4270 const Needed_Entry *n;
4271 const Obj_Entry *defobj;
4277 symlook_init_from_req(&req1, req);
4278 for (n = needed; n != NULL; n = n->next) {
4279 if (n->obj == NULL ||
4280 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
4282 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
4284 defobj = req1.defobj_out;
4285 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
4291 req->defobj_out = defobj;
4298 * Search the symbol table of a single shared object for a symbol of
4299 * the given name and version, if requested. Returns a pointer to the
4300 * symbol, or NULL if no definition was found. If the object is
4301 * filter, return filtered symbol from filtee.
4303 * The symbol's hash value is passed in for efficiency reasons; that
4304 * eliminates many recomputations of the hash value.
4307 symlook_obj(SymLook *req, const Obj_Entry *obj)
4311 int flags, res, mres;
4314 * If there is at least one valid hash at this point, we prefer to
4315 * use the faster GNU version if available.
4317 if (obj->valid_hash_gnu)
4318 mres = symlook_obj1_gnu(req, obj);
4319 else if (obj->valid_hash_sysv)
4320 mres = symlook_obj1_sysv(req, obj);
4325 if (obj->needed_filtees != NULL) {
4326 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4327 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4328 donelist_init(&donelist);
4329 symlook_init_from_req(&req1, req);
4330 res = symlook_needed(&req1, obj->needed_filtees, &donelist);
4332 req->sym_out = req1.sym_out;
4333 req->defobj_out = req1.defobj_out;
4337 if (obj->needed_aux_filtees != NULL) {
4338 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4339 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4340 donelist_init(&donelist);
4341 symlook_init_from_req(&req1, req);
4342 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
4344 req->sym_out = req1.sym_out;
4345 req->defobj_out = req1.defobj_out;
4353 /* Symbol match routine common to both hash functions */
4355 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result,
4356 const unsigned long symnum)
4359 const Elf_Sym *symp;
4362 symp = obj->symtab + symnum;
4363 strp = obj->strtab + symp->st_name;
4365 switch (ELF_ST_TYPE(symp->st_info)) {
4371 if (symp->st_value == 0)
4375 if (symp->st_shndx != SHN_UNDEF)
4378 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
4379 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
4386 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
4389 if (req->ventry == NULL) {
4390 if (obj->versyms != NULL) {
4391 verndx = VER_NDX(obj->versyms[symnum]);
4392 if (verndx > obj->vernum) {
4394 "%s: symbol %s references wrong version %d",
4395 obj->path, obj->strtab + symnum, verndx);
4399 * If we are not called from dlsym (i.e. this
4400 * is a normal relocation from unversioned
4401 * binary), accept the symbol immediately if
4402 * it happens to have first version after this
4403 * shared object became versioned. Otherwise,
4404 * if symbol is versioned and not hidden,
4405 * remember it. If it is the only symbol with
4406 * this name exported by the shared object, it
4407 * will be returned as a match by the calling
4408 * function. If symbol is global (verndx < 2)
4409 * accept it unconditionally.
4411 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
4412 verndx == VER_NDX_GIVEN) {
4413 result->sym_out = symp;
4416 else if (verndx >= VER_NDX_GIVEN) {
4417 if ((obj->versyms[symnum] & VER_NDX_HIDDEN)
4419 if (result->vsymp == NULL)
4420 result->vsymp = symp;
4426 result->sym_out = symp;
4429 if (obj->versyms == NULL) {
4430 if (object_match_name(obj, req->ventry->name)) {
4431 _rtld_error("%s: object %s should provide version %s "
4432 "for symbol %s", obj_rtld.path, obj->path,
4433 req->ventry->name, obj->strtab + symnum);
4437 verndx = VER_NDX(obj->versyms[symnum]);
4438 if (verndx > obj->vernum) {
4439 _rtld_error("%s: symbol %s references wrong version %d",
4440 obj->path, obj->strtab + symnum, verndx);
4443 if (obj->vertab[verndx].hash != req->ventry->hash ||
4444 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
4446 * Version does not match. Look if this is a
4447 * global symbol and if it is not hidden. If
4448 * global symbol (verndx < 2) is available,
4449 * use it. Do not return symbol if we are
4450 * called by dlvsym, because dlvsym looks for
4451 * a specific version and default one is not
4452 * what dlvsym wants.
4454 if ((req->flags & SYMLOOK_DLSYM) ||
4455 (verndx >= VER_NDX_GIVEN) ||
4456 (obj->versyms[symnum] & VER_NDX_HIDDEN))
4460 result->sym_out = symp;
4465 * Search for symbol using SysV hash function.
4466 * obj->buckets is known not to be NULL at this point; the test for this was
4467 * performed with the obj->valid_hash_sysv assignment.
4470 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj)
4472 unsigned long symnum;
4473 Sym_Match_Result matchres;
4475 matchres.sym_out = NULL;
4476 matchres.vsymp = NULL;
4477 matchres.vcount = 0;
4479 for (symnum = obj->buckets[req->hash % obj->nbuckets];
4480 symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
4481 if (symnum >= obj->nchains)
4482 return (ESRCH); /* Bad object */
4484 if (matched_symbol(req, obj, &matchres, symnum)) {
4485 req->sym_out = matchres.sym_out;
4486 req->defobj_out = obj;
4490 if (matchres.vcount == 1) {
4491 req->sym_out = matchres.vsymp;
4492 req->defobj_out = obj;
4498 /* Search for symbol using GNU hash function */
4500 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj)
4502 Elf_Addr bloom_word;
4503 const Elf32_Word *hashval;
4505 Sym_Match_Result matchres;
4506 unsigned int h1, h2;
4507 unsigned long symnum;
4509 matchres.sym_out = NULL;
4510 matchres.vsymp = NULL;
4511 matchres.vcount = 0;
4513 /* Pick right bitmask word from Bloom filter array */
4514 bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) &
4515 obj->maskwords_bm_gnu];
4517 /* Calculate modulus word size of gnu hash and its derivative */
4518 h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1);
4519 h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1));
4521 /* Filter out the "definitely not in set" queries */
4522 if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0)
4525 /* Locate hash chain and corresponding value element*/
4526 bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu];
4529 hashval = &obj->chain_zero_gnu[bucket];
4531 if (((*hashval ^ req->hash_gnu) >> 1) == 0) {
4532 symnum = hashval - obj->chain_zero_gnu;
4533 if (matched_symbol(req, obj, &matchres, symnum)) {
4534 req->sym_out = matchres.sym_out;
4535 req->defobj_out = obj;
4539 } while ((*hashval++ & 1) == 0);
4540 if (matchres.vcount == 1) {
4541 req->sym_out = matchres.vsymp;
4542 req->defobj_out = obj;
4549 trace_loaded_objects(Obj_Entry *obj)
4551 const char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
4554 if ((main_local = getenv(_LD("TRACE_LOADED_OBJECTS_PROGNAME"))) == NULL)
4557 if ((fmt1 = getenv(_LD("TRACE_LOADED_OBJECTS_FMT1"))) == NULL)
4558 fmt1 = "\t%o => %p (%x)\n";
4560 if ((fmt2 = getenv(_LD("TRACE_LOADED_OBJECTS_FMT2"))) == NULL)
4561 fmt2 = "\t%o (%x)\n";
4563 list_containers = getenv(_LD("TRACE_LOADED_OBJECTS_ALL"));
4565 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
4566 Needed_Entry *needed;
4567 const char *name, *path;
4572 if (list_containers && obj->needed != NULL)
4573 rtld_printf("%s:\n", obj->path);
4574 for (needed = obj->needed; needed; needed = needed->next) {
4575 if (needed->obj != NULL) {
4576 if (needed->obj->traced && !list_containers)
4578 needed->obj->traced = true;
4579 path = needed->obj->path;
4583 name = obj->strtab + needed->name;
4584 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
4586 fmt = is_lib ? fmt1 : fmt2;
4587 while ((c = *fmt++) != '\0') {
4613 rtld_putstr(main_local);
4616 rtld_putstr(obj_main->path);
4623 rtld_printf("%d", sodp->sod_major);
4626 rtld_printf("%d", sodp->sod_minor);
4633 rtld_printf("%p", needed->obj ? needed->obj->mapbase :
4646 * Unload a dlopened object and its dependencies from memory and from
4647 * our data structures. It is assumed that the DAG rooted in the
4648 * object has already been unreferenced, and that the object has a
4649 * reference count of 0.
4652 unload_object(Obj_Entry *root, RtldLockState *lockstate)
4654 Obj_Entry marker, *obj, *next;
4656 assert(root->refcount == 0);
4659 * Pass over the DAG removing unreferenced objects from
4660 * appropriate lists.
4662 unlink_object(root);
4664 /* Unmap all objects that are no longer referenced. */
4665 for (obj = TAILQ_FIRST(&obj_list); obj != NULL; obj = next) {
4666 next = TAILQ_NEXT(obj, next);
4667 if (obj->marker || obj->refcount != 0)
4669 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase,
4670 obj->mapsize, 0, obj->path);
4671 dbg("unloading \"%s\"", obj->path);
4673 * Unlink the object now to prevent new references from
4674 * being acquired while the bind lock is dropped in
4675 * recursive dlclose() invocations.
4677 TAILQ_REMOVE(&obj_list, obj, next);
4680 if (obj->filtees_loaded) {
4682 init_marker(&marker);
4683 TAILQ_INSERT_BEFORE(next, &marker, next);
4684 unload_filtees(obj, lockstate);
4685 next = TAILQ_NEXT(&marker, next);
4686 TAILQ_REMOVE(&obj_list, &marker, next);
4688 unload_filtees(obj, lockstate);
4690 release_object(obj);
4695 unlink_object(Obj_Entry *root)
4699 if (root->refcount == 0) {
4700 /* Remove the object from the RTLD_GLOBAL list. */
4701 objlist_remove(&list_global, root);
4703 /* Remove the object from all objects' DAG lists. */
4704 STAILQ_FOREACH(elm, &root->dagmembers, link) {
4705 objlist_remove(&elm->obj->dldags, root);
4706 if (elm->obj != root)
4707 unlink_object(elm->obj);
4713 ref_dag(Obj_Entry *root)
4717 assert(root->dag_inited);
4718 STAILQ_FOREACH(elm, &root->dagmembers, link)
4719 elm->obj->refcount++;
4723 unref_dag(Obj_Entry *root)
4727 assert(root->dag_inited);
4728 STAILQ_FOREACH(elm, &root->dagmembers, link)
4729 elm->obj->refcount--;
4733 * Common code for MD __tls_get_addr().
4735 static void *tls_get_addr_slow(Elf_Addr **, int, size_t) __noinline;
4737 tls_get_addr_slow(Elf_Addr **dtvp, int index, size_t offset)
4739 Elf_Addr *newdtv, *dtv;
4740 RtldLockState lockstate;
4744 /* Check dtv generation in case new modules have arrived */
4745 if (dtv[0] != tls_dtv_generation) {
4746 wlock_acquire(rtld_bind_lock, &lockstate);
4747 newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4749 if (to_copy > tls_max_index)
4750 to_copy = tls_max_index;
4751 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
4752 newdtv[0] = tls_dtv_generation;
4753 newdtv[1] = tls_max_index;
4755 lock_release(rtld_bind_lock, &lockstate);
4756 dtv = *dtvp = newdtv;
4759 /* Dynamically allocate module TLS if necessary */
4760 if (dtv[index + 1] == 0) {
4761 /* Signal safe, wlock will block out signals. */
4762 wlock_acquire(rtld_bind_lock, &lockstate);
4763 if (!dtv[index + 1])
4764 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
4765 lock_release(rtld_bind_lock, &lockstate);
4767 return ((void *)(dtv[index + 1] + offset));
4771 tls_get_addr_common(Elf_Addr **dtvp, int index, size_t offset)
4776 /* Check dtv generation in case new modules have arrived */
4777 if (__predict_true(dtv[0] == tls_dtv_generation &&
4778 dtv[index + 1] != 0))
4779 return ((void *)(dtv[index + 1] + offset));
4780 return (tls_get_addr_slow(dtvp, index, offset));
4783 #if defined(__aarch64__) || defined(__arm__) || defined(__mips__) || \
4784 defined(__powerpc__) || defined(__riscv)
4787 * Return pointer to allocated TLS block
4790 get_tls_block_ptr(void *tcb, size_t tcbsize)
4792 size_t extra_size, post_size, pre_size, tls_block_size;
4793 size_t tls_init_align;
4795 tls_init_align = MAX(obj_main->tlsalign, 1);
4797 /* Compute fragments sizes. */
4798 extra_size = tcbsize - TLS_TCB_SIZE;
4799 post_size = calculate_tls_post_size(tls_init_align);
4800 tls_block_size = tcbsize + post_size;
4801 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size;
4803 return ((char *)tcb - pre_size - extra_size);
4807 * Allocate Static TLS using the Variant I method.
4809 * For details on the layout, see lib/libc/gen/tls.c.
4811 * NB: rtld's tls_static_space variable includes TLS_TCB_SIZE and post_size as
4812 * it is based on tls_last_offset, and TLS offsets here are really TCB
4813 * offsets, whereas libc's tls_static_space is just the executable's static
4817 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
4821 Elf_Addr *dtv, **tcb;
4824 size_t extra_size, maxalign, post_size, pre_size, tls_block_size;
4825 size_t tls_init_align, tls_init_offset;
4827 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
4830 assert(tcbsize >= TLS_TCB_SIZE);
4831 maxalign = MAX(tcbalign, tls_static_max_align);
4832 tls_init_align = MAX(obj_main->tlsalign, 1);
4834 /* Compute fragmets sizes. */
4835 extra_size = tcbsize - TLS_TCB_SIZE;
4836 post_size = calculate_tls_post_size(tls_init_align);
4837 tls_block_size = tcbsize + post_size;
4838 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size;
4839 tls_block_size += pre_size + tls_static_space - TLS_TCB_SIZE - post_size;
4841 /* Allocate whole TLS block */
4842 tls_block = malloc_aligned(tls_block_size, maxalign, 0);
4843 tcb = (Elf_Addr **)(tls_block + pre_size + extra_size);
4845 if (oldtcb != NULL) {
4846 memcpy(tls_block, get_tls_block_ptr(oldtcb, tcbsize),
4848 free_aligned(get_tls_block_ptr(oldtcb, tcbsize));
4850 /* Adjust the DTV. */
4852 for (i = 0; i < dtv[1]; i++) {
4853 if (dtv[i+2] >= (Elf_Addr)oldtcb &&
4854 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
4855 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tcb;
4859 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4861 dtv[0] = tls_dtv_generation;
4862 dtv[1] = tls_max_index;
4864 for (obj = globallist_curr(objs); obj != NULL;
4865 obj = globallist_next(obj)) {
4866 if (obj->tlsoffset == 0)
4868 tls_init_offset = obj->tlspoffset & (obj->tlsalign - 1);
4869 addr = (Elf_Addr)tcb + obj->tlsoffset;
4870 if (tls_init_offset > 0)
4871 memset((void *)addr, 0, tls_init_offset);
4872 if (obj->tlsinitsize > 0) {
4873 memcpy((void *)(addr + tls_init_offset), obj->tlsinit,
4876 if (obj->tlssize > obj->tlsinitsize) {
4877 memset((void *)(addr + tls_init_offset + obj->tlsinitsize),
4878 0, obj->tlssize - obj->tlsinitsize - tls_init_offset);
4880 dtv[obj->tlsindex + 1] = addr;
4888 free_tls(void *tcb, size_t tcbsize, size_t tcbalign __unused)
4891 Elf_Addr tlsstart, tlsend;
4893 size_t dtvsize, i, tls_init_align;
4895 assert(tcbsize >= TLS_TCB_SIZE);
4896 tls_init_align = MAX(obj_main->tlsalign, 1);
4898 /* Compute fragments sizes. */
4899 post_size = calculate_tls_post_size(tls_init_align);
4901 tlsstart = (Elf_Addr)tcb + TLS_TCB_SIZE + post_size;
4902 tlsend = (Elf_Addr)tcb + tls_static_space;
4904 dtv = *(Elf_Addr **)tcb;
4906 for (i = 0; i < dtvsize; i++) {
4907 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
4908 free((void*)dtv[i+2]);
4912 free_aligned(get_tls_block_ptr(tcb, tcbsize));
4917 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__)
4920 * Allocate Static TLS using the Variant II method.
4923 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
4926 size_t size, ralign;
4928 Elf_Addr *dtv, *olddtv;
4929 Elf_Addr segbase, oldsegbase, addr;
4933 if (tls_static_max_align > ralign)
4934 ralign = tls_static_max_align;
4935 size = roundup(tls_static_space, ralign) + roundup(tcbsize, ralign);
4937 assert(tcbsize >= 2*sizeof(Elf_Addr));
4938 tls = malloc_aligned(size, ralign, 0 /* XXX */);
4939 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4941 segbase = (Elf_Addr)(tls + roundup(tls_static_space, ralign));
4942 ((Elf_Addr*)segbase)[0] = segbase;
4943 ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
4945 dtv[0] = tls_dtv_generation;
4946 dtv[1] = tls_max_index;
4950 * Copy the static TLS block over whole.
4952 oldsegbase = (Elf_Addr) oldtls;
4953 memcpy((void *)(segbase - tls_static_space),
4954 (const void *)(oldsegbase - tls_static_space),
4958 * If any dynamic TLS blocks have been created tls_get_addr(),
4961 olddtv = ((Elf_Addr**)oldsegbase)[1];
4962 for (i = 0; i < olddtv[1]; i++) {
4963 if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
4964 dtv[i+2] = olddtv[i+2];
4970 * We assume that this block was the one we created with
4971 * allocate_initial_tls().
4973 free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
4975 for (obj = objs; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
4976 if (obj->marker || obj->tlsoffset == 0)
4978 addr = segbase - obj->tlsoffset;
4979 memset((void*)(addr + obj->tlsinitsize),
4980 0, obj->tlssize - obj->tlsinitsize);
4982 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4983 obj->static_tls_copied = true;
4985 dtv[obj->tlsindex + 1] = addr;
4989 return (void*) segbase;
4993 free_tls(void *tls, size_t tcbsize __unused, size_t tcbalign)
4996 size_t size, ralign;
4998 Elf_Addr tlsstart, tlsend;
5001 * Figure out the size of the initial TLS block so that we can
5002 * find stuff which ___tls_get_addr() allocated dynamically.
5005 if (tls_static_max_align > ralign)
5006 ralign = tls_static_max_align;
5007 size = roundup(tls_static_space, ralign);
5009 dtv = ((Elf_Addr**)tls)[1];
5011 tlsend = (Elf_Addr) tls;
5012 tlsstart = tlsend - size;
5013 for (i = 0; i < dtvsize; i++) {
5014 if (dtv[i + 2] != 0 && (dtv[i + 2] < tlsstart || dtv[i + 2] > tlsend)) {
5015 free_aligned((void *)dtv[i + 2]);
5019 free_aligned((void *)tlsstart);
5026 * Allocate TLS block for module with given index.
5029 allocate_module_tls(int index)
5034 TAILQ_FOREACH(obj, &obj_list, next) {
5037 if (obj->tlsindex == index)
5041 _rtld_error("Can't find module with TLS index %d", index);
5045 p = malloc_aligned(obj->tlssize, obj->tlsalign, obj->tlspoffset);
5046 memcpy(p, obj->tlsinit, obj->tlsinitsize);
5047 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
5052 allocate_tls_offset(Obj_Entry *obj)
5059 if (obj->tlssize == 0) {
5060 obj->tls_done = true;
5064 if (tls_last_offset == 0)
5065 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign,
5068 off = calculate_tls_offset(tls_last_offset, tls_last_size,
5069 obj->tlssize, obj->tlsalign, obj->tlspoffset);
5072 * If we have already fixed the size of the static TLS block, we
5073 * must stay within that size. When allocating the static TLS, we
5074 * leave a small amount of space spare to be used for dynamically
5075 * loading modules which use static TLS.
5077 if (tls_static_space != 0) {
5078 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
5080 } else if (obj->tlsalign > tls_static_max_align) {
5081 tls_static_max_align = obj->tlsalign;
5084 tls_last_offset = obj->tlsoffset = off;
5085 tls_last_size = obj->tlssize;
5086 obj->tls_done = true;
5092 free_tls_offset(Obj_Entry *obj)
5096 * If we were the last thing to allocate out of the static TLS
5097 * block, we give our space back to the 'allocator'. This is a
5098 * simplistic workaround to allow libGL.so.1 to be loaded and
5099 * unloaded multiple times.
5101 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
5102 == calculate_tls_end(tls_last_offset, tls_last_size)) {
5103 tls_last_offset -= obj->tlssize;
5109 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
5112 RtldLockState lockstate;
5114 wlock_acquire(rtld_bind_lock, &lockstate);
5115 ret = allocate_tls(globallist_curr(TAILQ_FIRST(&obj_list)), oldtls,
5117 lock_release(rtld_bind_lock, &lockstate);
5122 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
5124 RtldLockState lockstate;
5126 wlock_acquire(rtld_bind_lock, &lockstate);
5127 free_tls(tcb, tcbsize, tcbalign);
5128 lock_release(rtld_bind_lock, &lockstate);
5132 object_add_name(Obj_Entry *obj, const char *name)
5138 entry = malloc(sizeof(Name_Entry) + len);
5140 if (entry != NULL) {
5141 strcpy(entry->name, name);
5142 STAILQ_INSERT_TAIL(&obj->names, entry, link);
5147 object_match_name(const Obj_Entry *obj, const char *name)
5151 STAILQ_FOREACH(entry, &obj->names, link) {
5152 if (strcmp(name, entry->name) == 0)
5159 locate_dependency(const Obj_Entry *obj, const char *name)
5161 const Objlist_Entry *entry;
5162 const Needed_Entry *needed;
5164 STAILQ_FOREACH(entry, &list_main, link) {
5165 if (object_match_name(entry->obj, name))
5169 for (needed = obj->needed; needed != NULL; needed = needed->next) {
5170 if (strcmp(obj->strtab + needed->name, name) == 0 ||
5171 (needed->obj != NULL && object_match_name(needed->obj, name))) {
5173 * If there is DT_NEEDED for the name we are looking for,
5174 * we are all set. Note that object might not be found if
5175 * dependency was not loaded yet, so the function can
5176 * return NULL here. This is expected and handled
5177 * properly by the caller.
5179 return (needed->obj);
5182 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
5188 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
5189 const Elf_Vernaux *vna)
5191 const Elf_Verdef *vd;
5192 const char *vername;
5194 vername = refobj->strtab + vna->vna_name;
5195 vd = depobj->verdef;
5197 _rtld_error("%s: version %s required by %s not defined",
5198 depobj->path, vername, refobj->path);
5202 if (vd->vd_version != VER_DEF_CURRENT) {
5203 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
5204 depobj->path, vd->vd_version);
5207 if (vna->vna_hash == vd->vd_hash) {
5208 const Elf_Verdaux *aux = (const Elf_Verdaux *)
5209 ((const char *)vd + vd->vd_aux);
5210 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
5213 if (vd->vd_next == 0)
5215 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5217 if (vna->vna_flags & VER_FLG_WEAK)
5219 _rtld_error("%s: version %s required by %s not found",
5220 depobj->path, vername, refobj->path);
5225 rtld_verify_object_versions(Obj_Entry *obj)
5227 const Elf_Verneed *vn;
5228 const Elf_Verdef *vd;
5229 const Elf_Verdaux *vda;
5230 const Elf_Vernaux *vna;
5231 const Obj_Entry *depobj;
5232 int maxvernum, vernum;
5234 if (obj->ver_checked)
5236 obj->ver_checked = true;
5240 * Walk over defined and required version records and figure out
5241 * max index used by any of them. Do very basic sanity checking
5245 while (vn != NULL) {
5246 if (vn->vn_version != VER_NEED_CURRENT) {
5247 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
5248 obj->path, vn->vn_version);
5251 vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux);
5253 vernum = VER_NEED_IDX(vna->vna_other);
5254 if (vernum > maxvernum)
5256 if (vna->vna_next == 0)
5258 vna = (const Elf_Vernaux *)((const char *)vna + vna->vna_next);
5260 if (vn->vn_next == 0)
5262 vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next);
5266 while (vd != NULL) {
5267 if (vd->vd_version != VER_DEF_CURRENT) {
5268 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
5269 obj->path, vd->vd_version);
5272 vernum = VER_DEF_IDX(vd->vd_ndx);
5273 if (vernum > maxvernum)
5275 if (vd->vd_next == 0)
5277 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5284 * Store version information in array indexable by version index.
5285 * Verify that object version requirements are satisfied along the
5288 obj->vernum = maxvernum + 1;
5289 obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry));
5292 while (vd != NULL) {
5293 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
5294 vernum = VER_DEF_IDX(vd->vd_ndx);
5295 assert(vernum <= maxvernum);
5296 vda = (const Elf_Verdaux *)((const char *)vd + vd->vd_aux);
5297 obj->vertab[vernum].hash = vd->vd_hash;
5298 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
5299 obj->vertab[vernum].file = NULL;
5300 obj->vertab[vernum].flags = 0;
5302 if (vd->vd_next == 0)
5304 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5308 while (vn != NULL) {
5309 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
5312 vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux);
5314 if (check_object_provided_version(obj, depobj, vna))
5316 vernum = VER_NEED_IDX(vna->vna_other);
5317 assert(vernum <= maxvernum);
5318 obj->vertab[vernum].hash = vna->vna_hash;
5319 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
5320 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
5321 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
5322 VER_INFO_HIDDEN : 0;
5323 if (vna->vna_next == 0)
5325 vna = (const Elf_Vernaux *)((const char *)vna + vna->vna_next);
5327 if (vn->vn_next == 0)
5329 vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next);
5335 rtld_verify_versions(const Objlist *objlist)
5337 Objlist_Entry *entry;
5341 STAILQ_FOREACH(entry, objlist, link) {
5343 * Skip dummy objects or objects that have their version requirements
5346 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
5348 if (rtld_verify_object_versions(entry->obj) == -1) {
5350 if (ld_tracing == NULL)
5354 if (rc == 0 || ld_tracing != NULL)
5355 rc = rtld_verify_object_versions(&obj_rtld);
5360 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
5365 vernum = VER_NDX(obj->versyms[symnum]);
5366 if (vernum >= obj->vernum) {
5367 _rtld_error("%s: symbol %s has wrong verneed value %d",
5368 obj->path, obj->strtab + symnum, vernum);
5369 } else if (obj->vertab[vernum].hash != 0) {
5370 return &obj->vertab[vernum];
5377 _rtld_get_stack_prot(void)
5380 return (stack_prot);
5384 _rtld_is_dlopened(void *arg)
5387 RtldLockState lockstate;
5390 rlock_acquire(rtld_bind_lock, &lockstate);
5393 obj = obj_from_addr(arg);
5395 _rtld_error("No shared object contains address");
5396 lock_release(rtld_bind_lock, &lockstate);
5399 res = obj->dlopened ? 1 : 0;
5400 lock_release(rtld_bind_lock, &lockstate);
5405 obj_remap_relro(Obj_Entry *obj, int prot)
5408 if (obj->relro_size > 0 && mprotect(obj->relro_page, obj->relro_size,
5410 _rtld_error("%s: Cannot set relro protection to %#x: %s",
5411 obj->path, prot, rtld_strerror(errno));
5418 obj_disable_relro(Obj_Entry *obj)
5421 return (obj_remap_relro(obj, PROT_READ | PROT_WRITE));
5425 obj_enforce_relro(Obj_Entry *obj)
5428 return (obj_remap_relro(obj, PROT_READ));
5432 map_stacks_exec(RtldLockState *lockstate)
5434 void (*thr_map_stacks_exec)(void);
5436 if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
5438 thr_map_stacks_exec = (void (*)(void))(uintptr_t)
5439 get_program_var_addr("__pthread_map_stacks_exec", lockstate);
5440 if (thr_map_stacks_exec != NULL) {
5441 stack_prot |= PROT_EXEC;
5442 thr_map_stacks_exec();
5447 distribute_static_tls(Objlist *list, RtldLockState *lockstate)
5451 void (*distrib)(size_t, void *, size_t, size_t);
5453 distrib = (void (*)(size_t, void *, size_t, size_t))(uintptr_t)
5454 get_program_var_addr("__pthread_distribute_static_tls", lockstate);
5455 if (distrib == NULL)
5457 STAILQ_FOREACH(elm, list, link) {
5459 if (obj->marker || !obj->tls_done || obj->static_tls_copied)
5461 distrib(obj->tlsoffset, obj->tlsinit, obj->tlsinitsize,
5463 obj->static_tls_copied = true;
5468 symlook_init(SymLook *dst, const char *name)
5471 bzero(dst, sizeof(*dst));
5473 dst->hash = elf_hash(name);
5474 dst->hash_gnu = gnu_hash(name);
5478 symlook_init_from_req(SymLook *dst, const SymLook *src)
5481 dst->name = src->name;
5482 dst->hash = src->hash;
5483 dst->hash_gnu = src->hash_gnu;
5484 dst->ventry = src->ventry;
5485 dst->flags = src->flags;
5486 dst->defobj_out = NULL;
5487 dst->sym_out = NULL;
5488 dst->lockstate = src->lockstate;
5492 open_binary_fd(const char *argv0, bool search_in_path,
5493 const char **binpath_res)
5495 char *binpath, *pathenv, *pe, *res1;
5501 if (search_in_path && strchr(argv0, '/') == NULL) {
5502 binpath = xmalloc(PATH_MAX);
5503 pathenv = getenv("PATH");
5504 if (pathenv == NULL) {
5505 _rtld_error("-p and no PATH environment variable");
5508 pathenv = strdup(pathenv);
5509 if (pathenv == NULL) {
5510 _rtld_error("Cannot allocate memory");
5515 while ((pe = strsep(&pathenv, ":")) != NULL) {
5516 if (strlcpy(binpath, pe, PATH_MAX) >= PATH_MAX)
5518 if (binpath[0] != '\0' &&
5519 strlcat(binpath, "/", PATH_MAX) >= PATH_MAX)
5521 if (strlcat(binpath, argv0, PATH_MAX) >= PATH_MAX)
5523 fd = open(binpath, O_RDONLY | O_CLOEXEC | O_VERIFY);
5524 if (fd != -1 || errno != ENOENT) {
5531 fd = open(argv0, O_RDONLY | O_CLOEXEC | O_VERIFY);
5536 _rtld_error("Cannot open %s: %s", argv0, rtld_strerror(errno));
5539 if (res != NULL && res[0] != '/') {
5540 res1 = xmalloc(PATH_MAX);
5541 if (realpath(res, res1) != NULL) {
5543 free(__DECONST(char *, res));
5554 * Parse a set of command-line arguments.
5557 parse_args(char* argv[], int argc, bool *use_pathp, int *fdp)
5560 int fd, i, j, arglen;
5563 dbg("Parsing command-line arguments");
5567 for (i = 1; i < argc; i++ ) {
5569 dbg("argv[%d]: '%s'", i, arg);
5572 * rtld arguments end with an explicit "--" or with the first
5573 * non-prefixed argument.
5575 if (strcmp(arg, "--") == 0) {
5583 * All other arguments are single-character options that can
5584 * be combined, so we need to search through `arg` for them.
5586 arglen = strlen(arg);
5587 for (j = 1; j < arglen; j++) {
5590 print_usage(argv[0]);
5592 } else if (opt == 'f') {
5594 * -f XX can be used to specify a
5595 * descriptor for the binary named at
5596 * the command line (i.e., the later
5597 * argument will specify the process
5598 * name but the descriptor is what
5599 * will actually be executed).
5601 * -f must be the last option in, e.g., -abcf.
5603 if (j != arglen - 1) {
5604 _rtld_error("Invalid options: %s", arg);
5608 fd = parse_integer(argv[i]);
5611 "Invalid file descriptor: '%s'",
5617 } else if (opt == 'p') {
5620 _rtld_error("Invalid argument: '%s'", arg);
5621 print_usage(argv[0]);
5631 * Parse a file descriptor number without pulling in more of libc (e.g. atoi).
5634 parse_integer(const char *str)
5636 static const int RADIX = 10; /* XXXJA: possibly support hex? */
5643 for (c = *str; c != '\0'; c = *++str) {
5644 if (c < '0' || c > '9')
5651 /* Make sure we actually parsed something. */
5658 print_usage(const char *argv0)
5661 rtld_printf("Usage: %s [-h] [-f <FD>] [--] <binary> [<args>]\n"
5664 " -h Display this help message\n"
5665 " -p Search in PATH for named binary\n"
5666 " -f <FD> Execute <FD> instead of searching for <binary>\n"
5667 " -- End of RTLD options\n"
5668 " <binary> Name of process to execute\n"
5669 " <args> Arguments to the executed process\n", argv0);
5673 * Overrides for libc_pic-provided functions.
5677 __getosreldate(void)
5687 oid[1] = KERN_OSRELDATE;
5689 len = sizeof(osrel);
5690 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
5691 if (error == 0 && osrel > 0 && len == sizeof(osrel))
5703 void (*__cleanup)(void);
5704 int __isthreaded = 0;
5705 int _thread_autoinit_dummy_decl = 1;
5708 * No unresolved symbols for rtld.
5711 __pthread_cxa_finalize(struct dl_phdr_info *a __unused)
5716 rtld_strerror(int errnum)
5719 if (errnum < 0 || errnum >= sys_nerr)
5720 return ("Unknown error");
5721 return (sys_errlist[errnum]);
5725 * No ifunc relocations.
5728 memset(void *dest, int c, size_t len)
5732 for (i = 0; i < len; i++)
5733 ((char *)dest)[i] = c;
5738 bzero(void *dest, size_t len)
5742 for (i = 0; i < len; i++)
5743 ((char *)dest)[i] = 0;
5748 malloc(size_t nbytes)
5751 return (__crt_malloc(nbytes));
5755 calloc(size_t num, size_t size)
5758 return (__crt_calloc(num, size));
5769 realloc(void *cp, size_t nbytes)
5772 return (__crt_realloc(cp, nbytes));