2 * Copyright 1996, 1997, 1998, 1999, 2000 John D. Polstra.
3 * Copyright 2003 Alexander Kabaev <kan@FreeBSD.ORG>.
4 * Copyright 2009-2013 Konstantin Belousov <kib@FreeBSD.ORG>.
5 * Copyright 2012 John Marino <draco@marino.st>.
6 * Copyright 2014-2017 The FreeBSD Foundation
9 * Portions of this software were developed by Konstantin Belousov
10 * under sponsorship from the FreeBSD Foundation.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
21 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
22 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
23 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
24 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
25 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
26 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
30 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 * Dynamic linker for ELF.
36 * John Polstra <jdp@polstra.com>.
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
42 #include <sys/param.h>
43 #include <sys/mount.h>
46 #include <sys/sysctl.h>
48 #include <sys/utsname.h>
49 #include <sys/ktrace.h>
66 #include "rtld_printf.h"
67 #include "rtld_utrace.h"
71 typedef void (*func_ptr_type)();
72 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg);
75 * Function declarations.
77 static const char *basename(const char *);
78 static void digest_dynamic1(Obj_Entry *, int, const Elf_Dyn **,
79 const Elf_Dyn **, const Elf_Dyn **);
80 static void digest_dynamic2(Obj_Entry *, const Elf_Dyn *, const Elf_Dyn *,
82 static void digest_dynamic(Obj_Entry *, int);
83 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
84 static void distribute_static_tls(Objlist *, RtldLockState *);
85 static Obj_Entry *dlcheck(void *);
86 static int dlclose_locked(void *, RtldLockState *);
87 static Obj_Entry *dlopen_object(const char *name, int fd, Obj_Entry *refobj,
88 int lo_flags, int mode, RtldLockState *lockstate);
89 static Obj_Entry *do_load_object(int, const char *, char *, struct stat *, int);
90 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
91 static bool donelist_check(DoneList *, const Obj_Entry *);
92 static void errmsg_restore(char *);
93 static char *errmsg_save(void);
94 static void *fill_search_info(const char *, size_t, void *);
95 static char *find_library(const char *, const Obj_Entry *, int *);
96 static const char *gethints(bool);
97 static void hold_object(Obj_Entry *);
98 static void unhold_object(Obj_Entry *);
99 static void init_dag(Obj_Entry *);
100 static void init_marker(Obj_Entry *);
101 static void init_pagesizes(Elf_Auxinfo **aux_info);
102 static void init_rtld(caddr_t, Elf_Auxinfo **);
103 static void initlist_add_neededs(Needed_Entry *, Objlist *);
104 static void initlist_add_objects(Obj_Entry *, Obj_Entry *, Objlist *);
105 static int initlist_objects_ifunc(Objlist *, bool, int, RtldLockState *);
106 static void linkmap_add(Obj_Entry *);
107 static void linkmap_delete(Obj_Entry *);
108 static void load_filtees(Obj_Entry *, int flags, RtldLockState *);
109 static void unload_filtees(Obj_Entry *, RtldLockState *);
110 static int load_needed_objects(Obj_Entry *, int);
111 static int load_preload_objects(void);
112 static Obj_Entry *load_object(const char *, int fd, const Obj_Entry *, int);
113 static void map_stacks_exec(RtldLockState *);
114 static int obj_disable_relro(Obj_Entry *);
115 static int obj_enforce_relro(Obj_Entry *);
116 static Obj_Entry *obj_from_addr(const void *);
117 static void objlist_call_fini(Objlist *, Obj_Entry *, RtldLockState *);
118 static void objlist_call_init(Objlist *, RtldLockState *);
119 static void objlist_clear(Objlist *);
120 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
121 static void objlist_init(Objlist *);
122 static void objlist_push_head(Objlist *, Obj_Entry *);
123 static void objlist_push_tail(Objlist *, Obj_Entry *);
124 static void objlist_put_after(Objlist *, Obj_Entry *, Obj_Entry *);
125 static void objlist_remove(Objlist *, Obj_Entry *);
126 static int open_binary_fd(const char *argv0, bool search_in_path);
127 static int parse_args(char* argv[], int argc, bool *use_pathp, int *fdp);
128 static int parse_integer(const char *);
129 static void *path_enumerate(const char *, path_enum_proc, const char *, void *);
130 static void print_usage(const char *argv0);
131 static void release_object(Obj_Entry *);
132 static int relocate_object_dag(Obj_Entry *root, bool bind_now,
133 Obj_Entry *rtldobj, int flags, RtldLockState *lockstate);
134 static int relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
135 int flags, RtldLockState *lockstate);
136 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, int,
138 static int resolve_object_ifunc(Obj_Entry *, bool, int, RtldLockState *);
139 static int rtld_dirname(const char *, char *);
140 static int rtld_dirname_abs(const char *, char *);
141 static void *rtld_dlopen(const char *name, int fd, int mode);
142 static void rtld_exit(void);
143 static void rtld_nop_exit(void);
144 static char *search_library_path(const char *, const char *, const char *,
146 static char *search_library_pathfds(const char *, const char *, int *);
147 static const void **get_program_var_addr(const char *, RtldLockState *);
148 static void set_program_var(const char *, const void *);
149 static int symlook_default(SymLook *, const Obj_Entry *refobj);
150 static int symlook_global(SymLook *, DoneList *);
151 static void symlook_init_from_req(SymLook *, const SymLook *);
152 static int symlook_list(SymLook *, const Objlist *, DoneList *);
153 static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *);
154 static int symlook_obj1_sysv(SymLook *, const Obj_Entry *);
155 static int symlook_obj1_gnu(SymLook *, const Obj_Entry *);
156 static void trace_loaded_objects(Obj_Entry *);
157 static void unlink_object(Obj_Entry *);
158 static void unload_object(Obj_Entry *, RtldLockState *lockstate);
159 static void unref_dag(Obj_Entry *);
160 static void ref_dag(Obj_Entry *);
161 static char *origin_subst_one(Obj_Entry *, char *, const char *,
163 static char *origin_subst(Obj_Entry *, char *);
164 static bool obj_resolve_origin(Obj_Entry *obj);
165 static void preinit_main(void);
166 static int rtld_verify_versions(const Objlist *);
167 static int rtld_verify_object_versions(Obj_Entry *);
168 static void object_add_name(Obj_Entry *, const char *);
169 static int object_match_name(const Obj_Entry *, const char *);
170 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
171 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
172 struct dl_phdr_info *phdr_info);
173 static uint32_t gnu_hash(const char *);
174 static bool matched_symbol(SymLook *, const Obj_Entry *, Sym_Match_Result *,
175 const unsigned long);
177 void r_debug_state(struct r_debug *, struct link_map *) __noinline __exported;
178 void _r_debug_postinit(struct link_map *) __noinline __exported;
180 int __sys_openat(int, const char *, int, ...);
185 static char *error_message; /* Message for dlerror(), or NULL */
186 struct r_debug r_debug __exported; /* for GDB; */
187 static bool libmap_disable; /* Disable libmap */
188 static bool ld_loadfltr; /* Immediate filters processing */
189 static char *libmap_override; /* Maps to use in addition to libmap.conf */
190 static bool trust; /* False for setuid and setgid programs */
191 static bool dangerous_ld_env; /* True if environment variables have been
192 used to affect the libraries loaded */
193 bool ld_bind_not; /* Disable PLT update */
194 static char *ld_bind_now; /* Environment variable for immediate binding */
195 static char *ld_debug; /* Environment variable for debugging */
196 static char *ld_library_path; /* Environment variable for search path */
197 static char *ld_library_dirs; /* Environment variable for library descriptors */
198 static char *ld_preload; /* Environment variable for libraries to
200 static char *ld_elf_hints_path; /* Environment variable for alternative hints path */
201 static char *ld_tracing; /* Called from ldd to print libs */
202 static char *ld_utrace; /* Use utrace() to log events. */
203 static struct obj_entry_q obj_list; /* Queue of all loaded objects */
204 static Obj_Entry *obj_main; /* The main program shared object */
205 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
206 static unsigned int obj_count; /* Number of objects in obj_list */
207 static unsigned int obj_loads; /* Number of loads of objects (gen count) */
209 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
210 STAILQ_HEAD_INITIALIZER(list_global);
211 static Objlist list_main = /* Objects loaded at program startup */
212 STAILQ_HEAD_INITIALIZER(list_main);
213 static Objlist list_fini = /* Objects needing fini() calls */
214 STAILQ_HEAD_INITIALIZER(list_fini);
216 Elf_Sym sym_zero; /* For resolving undefined weak refs. */
218 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
220 extern Elf_Dyn _DYNAMIC;
221 #pragma weak _DYNAMIC
223 int dlclose(void *) __exported;
224 char *dlerror(void) __exported;
225 void *dlopen(const char *, int) __exported;
226 void *fdlopen(int, int) __exported;
227 void *dlsym(void *, const char *) __exported;
228 dlfunc_t dlfunc(void *, const char *) __exported;
229 void *dlvsym(void *, const char *, const char *) __exported;
230 int dladdr(const void *, Dl_info *) __exported;
231 void dllockinit(void *, void *(*)(void *), void (*)(void *), void (*)(void *),
232 void (*)(void *), void (*)(void *), void (*)(void *)) __exported;
233 int dlinfo(void *, int , void *) __exported;
234 int dl_iterate_phdr(__dl_iterate_hdr_callback, void *) __exported;
235 int _rtld_addr_phdr(const void *, struct dl_phdr_info *) __exported;
236 int _rtld_get_stack_prot(void) __exported;
237 int _rtld_is_dlopened(void *) __exported;
238 void _rtld_error(const char *, ...) __exported;
240 int npagesizes, osreldate;
243 long __stack_chk_guard[8] = {0, 0, 0, 0, 0, 0, 0, 0};
245 static int stack_prot = PROT_READ | PROT_WRITE | RTLD_DEFAULT_STACK_EXEC;
246 static int max_stack_flags;
249 * Global declarations normally provided by crt1. The dynamic linker is
250 * not built with crt1, so we have to provide them ourselves.
256 * Used to pass argc, argv to init functions.
262 * Globals to control TLS allocation.
264 size_t tls_last_offset; /* Static TLS offset of last module */
265 size_t tls_last_size; /* Static TLS size of last module */
266 size_t tls_static_space; /* Static TLS space allocated */
267 size_t tls_static_max_align;
268 int tls_dtv_generation = 1; /* Used to detect when dtv size changes */
269 int tls_max_index = 1; /* Largest module index allocated */
271 bool ld_library_path_rpath = false;
274 * Globals for path names, and such
276 char *ld_elf_hints_default = _PATH_ELF_HINTS;
277 char *ld_path_libmap_conf = _PATH_LIBMAP_CONF;
278 char *ld_path_rtld = _PATH_RTLD;
279 char *ld_standard_library_path = STANDARD_LIBRARY_PATH;
280 char *ld_env_prefix = LD_;
282 static void (*rtld_exit_ptr)(void);
285 * Fill in a DoneList with an allocation large enough to hold all of
286 * the currently-loaded objects. Keep this as a macro since it calls
287 * alloca and we want that to occur within the scope of the caller.
289 #define donelist_init(dlp) \
290 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
291 assert((dlp)->objs != NULL), \
292 (dlp)->num_alloc = obj_count, \
295 #define LD_UTRACE(e, h, mb, ms, r, n) do { \
296 if (ld_utrace != NULL) \
297 ld_utrace_log(e, h, mb, ms, r, n); \
301 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
302 int refcnt, const char *name)
304 struct utrace_rtld ut;
305 static const char rtld_utrace_sig[RTLD_UTRACE_SIG_SZ] = RTLD_UTRACE_SIG;
307 memcpy(ut.sig, rtld_utrace_sig, sizeof(ut.sig));
310 ut.mapbase = mapbase;
311 ut.mapsize = mapsize;
313 bzero(ut.name, sizeof(ut.name));
315 strlcpy(ut.name, name, sizeof(ut.name));
316 utrace(&ut, sizeof(ut));
319 #ifdef RTLD_VARIANT_ENV_NAMES
321 * construct the env variable based on the type of binary that's
324 static inline const char *
327 static char buffer[128];
329 strlcpy(buffer, ld_env_prefix, sizeof(buffer));
330 strlcat(buffer, var, sizeof(buffer));
338 * Main entry point for dynamic linking. The first argument is the
339 * stack pointer. The stack is expected to be laid out as described
340 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
341 * Specifically, the stack pointer points to a word containing
342 * ARGC. Following that in the stack is a null-terminated sequence
343 * of pointers to argument strings. Then comes a null-terminated
344 * sequence of pointers to environment strings. Finally, there is a
345 * sequence of "auxiliary vector" entries.
347 * The second argument points to a place to store the dynamic linker's
348 * exit procedure pointer and the third to a place to store the main
351 * The return value is the main program's entry point.
354 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
356 Elf_Auxinfo *aux, *auxp, *auxpf, *aux_info[AT_COUNT];
357 Objlist_Entry *entry;
358 Obj_Entry *last_interposer, *obj, *preload_tail;
359 const Elf_Phdr *phdr;
361 RtldLockState lockstate;
364 char **argv, *argv0, **env, **envp, *kexecpath, *library_path_rpath;
366 char buf[MAXPATHLEN];
367 int argc, fd, i, mib[2], phnum, rtld_argc;
369 bool dir_enable, explicit_fd, search_in_path;
372 * On entry, the dynamic linker itself has not been relocated yet.
373 * Be very careful not to reference any global data until after
374 * init_rtld has returned. It is OK to reference file-scope statics
375 * and string constants, and to call static and global functions.
378 /* Find the auxiliary vector on the stack. */
382 sp += argc + 1; /* Skip over arguments and NULL terminator */
384 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
386 aux = (Elf_Auxinfo *) sp;
388 /* Digest the auxiliary vector. */
389 for (i = 0; i < AT_COUNT; i++)
391 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
392 if (auxp->a_type < AT_COUNT)
393 aux_info[auxp->a_type] = auxp;
396 /* Initialize and relocate ourselves. */
397 assert(aux_info[AT_BASE] != NULL);
398 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
400 __progname = obj_rtld.path;
401 argv0 = argv[0] != NULL ? argv[0] : "(null)";
406 if (aux_info[AT_CANARY] != NULL &&
407 aux_info[AT_CANARY]->a_un.a_ptr != NULL) {
408 i = aux_info[AT_CANARYLEN]->a_un.a_val;
409 if (i > sizeof(__stack_chk_guard))
410 i = sizeof(__stack_chk_guard);
411 memcpy(__stack_chk_guard, aux_info[AT_CANARY]->a_un.a_ptr, i);
416 len = sizeof(__stack_chk_guard);
417 if (sysctl(mib, 2, __stack_chk_guard, &len, NULL, 0) == -1 ||
418 len != sizeof(__stack_chk_guard)) {
419 /* If sysctl was unsuccessful, use the "terminator canary". */
420 ((unsigned char *)(void *)__stack_chk_guard)[0] = 0;
421 ((unsigned char *)(void *)__stack_chk_guard)[1] = 0;
422 ((unsigned char *)(void *)__stack_chk_guard)[2] = '\n';
423 ((unsigned char *)(void *)__stack_chk_guard)[3] = 255;
427 trust = !issetugid();
429 md_abi_variant_hook(aux_info);
432 if (aux_info[AT_EXECFD] != NULL) {
433 fd = aux_info[AT_EXECFD]->a_un.a_val;
435 assert(aux_info[AT_PHDR] != NULL);
436 phdr = (const Elf_Phdr *)aux_info[AT_PHDR]->a_un.a_ptr;
437 if (phdr == obj_rtld.phdr) {
439 rtld_printf("Tainted process refusing to run binary %s\n",
443 dbg("opening main program in direct exec mode");
445 rtld_argc = parse_args(argv, argc, &search_in_path, &fd);
446 argv0 = argv[rtld_argc];
447 explicit_fd = (fd != -1);
449 fd = open_binary_fd(argv0, search_in_path);
450 if (fstat(fd, &st) == -1) {
451 _rtld_error("failed to fstat FD %d (%s): %s", fd,
452 explicit_fd ? "user-provided descriptor" : argv0,
453 rtld_strerror(errno));
458 * Rough emulation of the permission checks done by
459 * execve(2), only Unix DACs are checked, ACLs are
460 * ignored. Preserve the semantic of disabling owner
461 * to execute if owner x bit is cleared, even if
462 * others x bit is enabled.
463 * mmap(2) does not allow to mmap with PROT_EXEC if
464 * binary' file comes from noexec mount. We cannot
465 * set VV_TEXT on the binary.
468 if (st.st_uid == geteuid()) {
469 if ((st.st_mode & S_IXUSR) != 0)
471 } else if (st.st_gid == getegid()) {
472 if ((st.st_mode & S_IXGRP) != 0)
474 } else if ((st.st_mode & S_IXOTH) != 0) {
478 rtld_printf("No execute permission for binary %s\n",
484 * For direct exec mode, argv[0] is the interpreter
485 * name, we must remove it and shift arguments left
486 * before invoking binary main. Since stack layout
487 * places environment pointers and aux vectors right
488 * after the terminating NULL, we must shift
489 * environment and aux as well.
491 main_argc = argc - rtld_argc;
492 for (i = 0; i <= main_argc; i++)
493 argv[i] = argv[i + rtld_argc];
495 environ = env = envp = argv + main_argc + 1;
497 *envp = *(envp + rtld_argc);
499 } while (*envp != NULL);
500 aux = auxp = (Elf_Auxinfo *)envp;
501 auxpf = (Elf_Auxinfo *)(envp + rtld_argc);
502 for (;; auxp++, auxpf++) {
504 if (auxp->a_type == AT_NULL)
508 rtld_printf("no binary\n");
514 ld_bind_now = getenv(_LD("BIND_NOW"));
517 * If the process is tainted, then we un-set the dangerous environment
518 * variables. The process will be marked as tainted until setuid(2)
519 * is called. If any child process calls setuid(2) we do not want any
520 * future processes to honor the potentially un-safe variables.
523 if (unsetenv(_LD("PRELOAD")) || unsetenv(_LD("LIBMAP")) ||
524 unsetenv(_LD("LIBRARY_PATH")) || unsetenv(_LD("LIBRARY_PATH_FDS")) ||
525 unsetenv(_LD("LIBMAP_DISABLE")) || unsetenv(_LD("BIND_NOT")) ||
526 unsetenv(_LD("DEBUG")) || unsetenv(_LD("ELF_HINTS_PATH")) ||
527 unsetenv(_LD("LOADFLTR")) || unsetenv(_LD("LIBRARY_PATH_RPATH"))) {
528 _rtld_error("environment corrupt; aborting");
532 ld_debug = getenv(_LD("DEBUG"));
533 if (ld_bind_now == NULL)
534 ld_bind_not = getenv(_LD("BIND_NOT")) != NULL;
535 libmap_disable = getenv(_LD("LIBMAP_DISABLE")) != NULL;
536 libmap_override = getenv(_LD("LIBMAP"));
537 ld_library_path = getenv(_LD("LIBRARY_PATH"));
538 ld_library_dirs = getenv(_LD("LIBRARY_PATH_FDS"));
539 ld_preload = getenv(_LD("PRELOAD"));
540 ld_elf_hints_path = getenv(_LD("ELF_HINTS_PATH"));
541 ld_loadfltr = getenv(_LD("LOADFLTR")) != NULL;
542 library_path_rpath = getenv(_LD("LIBRARY_PATH_RPATH"));
543 if (library_path_rpath != NULL) {
544 if (library_path_rpath[0] == 'y' ||
545 library_path_rpath[0] == 'Y' ||
546 library_path_rpath[0] == '1')
547 ld_library_path_rpath = true;
549 ld_library_path_rpath = false;
551 dangerous_ld_env = libmap_disable || (libmap_override != NULL) ||
552 (ld_library_path != NULL) || (ld_preload != NULL) ||
553 (ld_elf_hints_path != NULL) || ld_loadfltr;
554 ld_tracing = getenv(_LD("TRACE_LOADED_OBJECTS"));
555 ld_utrace = getenv(_LD("UTRACE"));
557 if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0)
558 ld_elf_hints_path = ld_elf_hints_default;
560 if (ld_debug != NULL && *ld_debug != '\0')
562 dbg("%s is initialized, base address = %p", __progname,
563 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
564 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
565 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
567 dbg("initializing thread locks");
571 * Load the main program, or process its program header if it is
574 if (fd != -1) { /* Load the main program. */
575 dbg("loading main program");
576 obj_main = map_object(fd, argv0, NULL);
578 if (obj_main == NULL)
580 max_stack_flags = obj_main->stack_flags;
581 } else { /* Main program already loaded. */
582 dbg("processing main program's program header");
583 assert(aux_info[AT_PHDR] != NULL);
584 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
585 assert(aux_info[AT_PHNUM] != NULL);
586 phnum = aux_info[AT_PHNUM]->a_un.a_val;
587 assert(aux_info[AT_PHENT] != NULL);
588 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
589 assert(aux_info[AT_ENTRY] != NULL);
590 imgentry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
591 if ((obj_main = digest_phdr(phdr, phnum, imgentry, argv0)) == NULL)
595 if (aux_info[AT_EXECPATH] != NULL && fd == -1) {
596 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
597 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
598 if (kexecpath[0] == '/')
599 obj_main->path = kexecpath;
600 else if (getcwd(buf, sizeof(buf)) == NULL ||
601 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
602 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
603 obj_main->path = xstrdup(argv0);
605 obj_main->path = xstrdup(buf);
607 dbg("No AT_EXECPATH or direct exec");
608 obj_main->path = xstrdup(argv0);
610 dbg("obj_main path %s", obj_main->path);
611 obj_main->mainprog = true;
613 if (aux_info[AT_STACKPROT] != NULL &&
614 aux_info[AT_STACKPROT]->a_un.a_val != 0)
615 stack_prot = aux_info[AT_STACKPROT]->a_un.a_val;
619 * Get the actual dynamic linker pathname from the executable if
620 * possible. (It should always be possible.) That ensures that
621 * gdb will find the right dynamic linker even if a non-standard
624 if (obj_main->interp != NULL &&
625 strcmp(obj_main->interp, obj_rtld.path) != 0) {
627 obj_rtld.path = xstrdup(obj_main->interp);
628 __progname = obj_rtld.path;
632 digest_dynamic(obj_main, 0);
633 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d",
634 obj_main->path, obj_main->valid_hash_sysv, obj_main->valid_hash_gnu,
635 obj_main->dynsymcount);
637 linkmap_add(obj_main);
638 linkmap_add(&obj_rtld);
640 /* Link the main program into the list of objects. */
641 TAILQ_INSERT_HEAD(&obj_list, obj_main, next);
645 /* Initialize a fake symbol for resolving undefined weak references. */
646 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
647 sym_zero.st_shndx = SHN_UNDEF;
648 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
651 libmap_disable = (bool)lm_init(libmap_override);
653 dbg("loading LD_PRELOAD libraries");
654 if (load_preload_objects() == -1)
656 preload_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
658 dbg("loading needed objects");
659 if (load_needed_objects(obj_main, 0) == -1)
662 /* Make a list of all objects loaded at startup. */
663 last_interposer = obj_main;
664 TAILQ_FOREACH(obj, &obj_list, next) {
667 if (obj->z_interpose && obj != obj_main) {
668 objlist_put_after(&list_main, last_interposer, obj);
669 last_interposer = obj;
671 objlist_push_tail(&list_main, obj);
676 dbg("checking for required versions");
677 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
680 if (ld_tracing) { /* We're done */
681 trace_loaded_objects(obj_main);
685 if (getenv(_LD("DUMP_REL_PRE")) != NULL) {
686 dump_relocations(obj_main);
691 * Processing tls relocations requires having the tls offsets
692 * initialized. Prepare offsets before starting initial
693 * relocation processing.
695 dbg("initializing initial thread local storage offsets");
696 STAILQ_FOREACH(entry, &list_main, link) {
698 * Allocate all the initial objects out of the static TLS
699 * block even if they didn't ask for it.
701 allocate_tls_offset(entry->obj);
704 if (relocate_objects(obj_main,
705 ld_bind_now != NULL && *ld_bind_now != '\0',
706 &obj_rtld, SYMLOOK_EARLY, NULL) == -1)
709 dbg("doing copy relocations");
710 if (do_copy_relocations(obj_main) == -1)
713 if (getenv(_LD("DUMP_REL_POST")) != NULL) {
714 dump_relocations(obj_main);
721 * Setup TLS for main thread. This must be done after the
722 * relocations are processed, since tls initialization section
723 * might be the subject for relocations.
725 dbg("initializing initial thread local storage");
726 allocate_initial_tls(globallist_curr(TAILQ_FIRST(&obj_list)));
728 dbg("initializing key program variables");
729 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
730 set_program_var("environ", env);
731 set_program_var("__elf_aux_vector", aux);
733 /* Make a list of init functions to call. */
734 objlist_init(&initlist);
735 initlist_add_objects(globallist_curr(TAILQ_FIRST(&obj_list)),
736 preload_tail, &initlist);
738 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
740 map_stacks_exec(NULL);
742 if (!obj_main->crt_no_init) {
744 * Make sure we don't call the main program's init and fini
745 * functions for binaries linked with old crt1 which calls
748 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
749 obj_main->preinit_array = obj_main->init_array =
750 obj_main->fini_array = (Elf_Addr)NULL;
754 * Execute MD initializers required before we call the objects'
759 wlock_acquire(rtld_bind_lock, &lockstate);
761 dbg("resolving ifuncs");
762 if (initlist_objects_ifunc(&initlist, ld_bind_now != NULL &&
763 *ld_bind_now != '\0', SYMLOOK_EARLY, &lockstate) == -1)
766 rtld_exit_ptr = rtld_exit;
767 if (obj_main->crt_no_init)
769 objlist_call_init(&initlist, &lockstate);
770 _r_debug_postinit(&obj_main->linkmap);
771 objlist_clear(&initlist);
772 dbg("loading filtees");
773 TAILQ_FOREACH(obj, &obj_list, next) {
776 if (ld_loadfltr || obj->z_loadfltr)
777 load_filtees(obj, 0, &lockstate);
780 dbg("enforcing main obj relro");
781 if (obj_enforce_relro(obj_main) == -1)
784 lock_release(rtld_bind_lock, &lockstate);
786 dbg("transferring control to program entry point = %p", obj_main->entry);
788 /* Return the exit procedure and the program entry point. */
789 *exit_proc = rtld_exit_ptr;
791 return (func_ptr_type) obj_main->entry;
795 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def)
800 ptr = (void *)make_function_pointer(def, obj);
801 target = call_ifunc_resolver(ptr);
802 return ((void *)target);
806 * NB: MIPS uses a private version of this function (_mips_rtld_bind).
807 * Changes to this function should be applied there as well.
810 _rtld_bind(Obj_Entry *obj, Elf_Size reloff)
814 const Obj_Entry *defobj;
817 RtldLockState lockstate;
819 rlock_acquire(rtld_bind_lock, &lockstate);
820 if (sigsetjmp(lockstate.env, 0) != 0)
821 lock_upgrade(rtld_bind_lock, &lockstate);
823 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
825 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
827 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
828 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, SYMLOOK_IN_PLT,
832 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
833 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
835 target = (Elf_Addr)(defobj->relocbase + def->st_value);
837 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
838 defobj->strtab + def->st_name, basename(obj->path),
839 (void *)target, basename(defobj->path));
842 * Write the new contents for the jmpslot. Note that depending on
843 * architecture, the value which we need to return back to the
844 * lazy binding trampoline may or may not be the target
845 * address. The value returned from reloc_jmpslot() is the value
846 * that the trampoline needs.
848 target = reloc_jmpslot(where, target, defobj, obj, rel);
849 lock_release(rtld_bind_lock, &lockstate);
854 * Error reporting function. Use it like printf. If formats the message
855 * into a buffer, and sets things up so that the next call to dlerror()
856 * will return the message.
859 _rtld_error(const char *fmt, ...)
861 static char buf[512];
865 rtld_vsnprintf(buf, sizeof buf, fmt, ap);
871 * Return a dynamically-allocated copy of the current error message, if any.
876 return error_message == NULL ? NULL : xstrdup(error_message);
880 * Restore the current error message from a copy which was previously saved
881 * by errmsg_save(). The copy is freed.
884 errmsg_restore(char *saved_msg)
886 if (saved_msg == NULL)
887 error_message = NULL;
889 _rtld_error("%s", saved_msg);
895 basename(const char *name)
897 const char *p = strrchr(name, '/');
898 return p != NULL ? p + 1 : name;
901 static struct utsname uts;
904 origin_subst_one(Obj_Entry *obj, char *real, const char *kw,
905 const char *subst, bool may_free)
907 char *p, *p1, *res, *resp;
908 int subst_len, kw_len, subst_count, old_len, new_len;
913 * First, count the number of the keyword occurrences, to
914 * preallocate the final string.
916 for (p = real, subst_count = 0;; p = p1 + kw_len, subst_count++) {
923 * If the keyword is not found, just return.
925 * Return non-substituted string if resolution failed. We
926 * cannot do anything more reasonable, the failure mode of the
927 * caller is unresolved library anyway.
929 if (subst_count == 0 || (obj != NULL && !obj_resolve_origin(obj)))
930 return (may_free ? real : xstrdup(real));
932 subst = obj->origin_path;
935 * There is indeed something to substitute. Calculate the
936 * length of the resulting string, and allocate it.
938 subst_len = strlen(subst);
939 old_len = strlen(real);
940 new_len = old_len + (subst_len - kw_len) * subst_count;
941 res = xmalloc(new_len + 1);
944 * Now, execute the substitution loop.
946 for (p = real, resp = res, *resp = '\0';;) {
949 /* Copy the prefix before keyword. */
950 memcpy(resp, p, p1 - p);
952 /* Keyword replacement. */
953 memcpy(resp, subst, subst_len);
961 /* Copy to the end of string and finish. */
969 origin_subst(Obj_Entry *obj, char *real)
971 char *res1, *res2, *res3, *res4;
973 if (obj == NULL || !trust)
974 return (xstrdup(real));
975 if (uts.sysname[0] == '\0') {
976 if (uname(&uts) != 0) {
977 _rtld_error("utsname failed: %d", errno);
981 res1 = origin_subst_one(obj, real, "$ORIGIN", NULL, false);
982 res2 = origin_subst_one(NULL, res1, "$OSNAME", uts.sysname, true);
983 res3 = origin_subst_one(NULL, res2, "$OSREL", uts.release, true);
984 res4 = origin_subst_one(NULL, res3, "$PLATFORM", uts.machine, true);
991 const char *msg = dlerror();
995 rtld_fdputstr(STDERR_FILENO, msg);
996 rtld_fdputchar(STDERR_FILENO, '\n');
1001 * Process a shared object's DYNAMIC section, and save the important
1002 * information in its Obj_Entry structure.
1005 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
1006 const Elf_Dyn **dyn_soname, const Elf_Dyn **dyn_runpath)
1008 const Elf_Dyn *dynp;
1009 Needed_Entry **needed_tail = &obj->needed;
1010 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
1011 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
1012 const Elf_Hashelt *hashtab;
1013 const Elf32_Word *hashval;
1014 Elf32_Word bkt, nmaskwords;
1016 int plttype = DT_REL;
1020 *dyn_runpath = NULL;
1022 obj->bind_now = false;
1023 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
1024 switch (dynp->d_tag) {
1027 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
1031 obj->relsize = dynp->d_un.d_val;
1035 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
1039 obj->pltrel = (const Elf_Rel *)
1040 (obj->relocbase + dynp->d_un.d_ptr);
1044 obj->pltrelsize = dynp->d_un.d_val;
1048 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
1052 obj->relasize = dynp->d_un.d_val;
1056 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
1060 plttype = dynp->d_un.d_val;
1061 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
1065 obj->symtab = (const Elf_Sym *)
1066 (obj->relocbase + dynp->d_un.d_ptr);
1070 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
1074 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
1078 obj->strsize = dynp->d_un.d_val;
1082 obj->verneed = (const Elf_Verneed *) (obj->relocbase +
1087 obj->verneednum = dynp->d_un.d_val;
1091 obj->verdef = (const Elf_Verdef *) (obj->relocbase +
1096 obj->verdefnum = dynp->d_un.d_val;
1100 obj->versyms = (const Elf_Versym *)(obj->relocbase +
1106 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1108 obj->nbuckets = hashtab[0];
1109 obj->nchains = hashtab[1];
1110 obj->buckets = hashtab + 2;
1111 obj->chains = obj->buckets + obj->nbuckets;
1112 obj->valid_hash_sysv = obj->nbuckets > 0 && obj->nchains > 0 &&
1113 obj->buckets != NULL;
1119 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1121 obj->nbuckets_gnu = hashtab[0];
1122 obj->symndx_gnu = hashtab[1];
1123 nmaskwords = hashtab[2];
1124 bloom_size32 = (__ELF_WORD_SIZE / 32) * nmaskwords;
1125 obj->maskwords_bm_gnu = nmaskwords - 1;
1126 obj->shift2_gnu = hashtab[3];
1127 obj->bloom_gnu = (Elf_Addr *) (hashtab + 4);
1128 obj->buckets_gnu = hashtab + 4 + bloom_size32;
1129 obj->chain_zero_gnu = obj->buckets_gnu + obj->nbuckets_gnu -
1131 /* Number of bitmask words is required to be power of 2 */
1132 obj->valid_hash_gnu = powerof2(nmaskwords) &&
1133 obj->nbuckets_gnu > 0 && obj->buckets_gnu != NULL;
1139 Needed_Entry *nep = NEW(Needed_Entry);
1140 nep->name = dynp->d_un.d_val;
1145 needed_tail = &nep->next;
1151 Needed_Entry *nep = NEW(Needed_Entry);
1152 nep->name = dynp->d_un.d_val;
1156 *needed_filtees_tail = nep;
1157 needed_filtees_tail = &nep->next;
1163 Needed_Entry *nep = NEW(Needed_Entry);
1164 nep->name = dynp->d_un.d_val;
1168 *needed_aux_filtees_tail = nep;
1169 needed_aux_filtees_tail = &nep->next;
1174 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
1178 obj->textrel = true;
1182 obj->symbolic = true;
1187 * We have to wait until later to process this, because we
1188 * might not have gotten the address of the string table yet.
1198 *dyn_runpath = dynp;
1202 obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1205 case DT_PREINIT_ARRAY:
1206 obj->preinit_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1209 case DT_PREINIT_ARRAYSZ:
1210 obj->preinit_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1214 obj->init_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1217 case DT_INIT_ARRAYSZ:
1218 obj->init_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1222 obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1226 obj->fini_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1229 case DT_FINI_ARRAYSZ:
1230 obj->fini_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1234 * Don't process DT_DEBUG on MIPS as the dynamic section
1235 * is mapped read-only. DT_MIPS_RLD_MAP is used instead.
1241 dbg("Filling in DT_DEBUG entry");
1242 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
1247 if (dynp->d_un.d_val & DF_ORIGIN)
1248 obj->z_origin = true;
1249 if (dynp->d_un.d_val & DF_SYMBOLIC)
1250 obj->symbolic = true;
1251 if (dynp->d_un.d_val & DF_TEXTREL)
1252 obj->textrel = true;
1253 if (dynp->d_un.d_val & DF_BIND_NOW)
1254 obj->bind_now = true;
1255 if (dynp->d_un.d_val & DF_STATIC_TLS)
1256 obj->static_tls = true;
1259 case DT_MIPS_LOCAL_GOTNO:
1260 obj->local_gotno = dynp->d_un.d_val;
1263 case DT_MIPS_SYMTABNO:
1264 obj->symtabno = dynp->d_un.d_val;
1267 case DT_MIPS_GOTSYM:
1268 obj->gotsym = dynp->d_un.d_val;
1271 case DT_MIPS_RLD_MAP:
1272 *((Elf_Addr *)(dynp->d_un.d_ptr)) = (Elf_Addr) &r_debug;
1276 #ifdef __powerpc64__
1277 case DT_PPC64_GLINK:
1278 obj->glink = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1283 if (dynp->d_un.d_val & DF_1_NOOPEN)
1284 obj->z_noopen = true;
1285 if (dynp->d_un.d_val & DF_1_ORIGIN)
1286 obj->z_origin = true;
1287 if (dynp->d_un.d_val & DF_1_GLOBAL)
1288 obj->z_global = true;
1289 if (dynp->d_un.d_val & DF_1_BIND_NOW)
1290 obj->bind_now = true;
1291 if (dynp->d_un.d_val & DF_1_NODELETE)
1292 obj->z_nodelete = true;
1293 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1294 obj->z_loadfltr = true;
1295 if (dynp->d_un.d_val & DF_1_INTERPOSE)
1296 obj->z_interpose = true;
1297 if (dynp->d_un.d_val & DF_1_NODEFLIB)
1298 obj->z_nodeflib = true;
1303 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1310 obj->traced = false;
1312 if (plttype == DT_RELA) {
1313 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1315 obj->pltrelasize = obj->pltrelsize;
1316 obj->pltrelsize = 0;
1319 /* Determine size of dynsym table (equal to nchains of sysv hash) */
1320 if (obj->valid_hash_sysv)
1321 obj->dynsymcount = obj->nchains;
1322 else if (obj->valid_hash_gnu) {
1323 obj->dynsymcount = 0;
1324 for (bkt = 0; bkt < obj->nbuckets_gnu; bkt++) {
1325 if (obj->buckets_gnu[bkt] == 0)
1327 hashval = &obj->chain_zero_gnu[obj->buckets_gnu[bkt]];
1330 while ((*hashval++ & 1u) == 0);
1332 obj->dynsymcount += obj->symndx_gnu;
1337 obj_resolve_origin(Obj_Entry *obj)
1340 if (obj->origin_path != NULL)
1342 obj->origin_path = xmalloc(PATH_MAX);
1343 return (rtld_dirname_abs(obj->path, obj->origin_path) != -1);
1347 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1348 const Elf_Dyn *dyn_soname, const Elf_Dyn *dyn_runpath)
1351 if (obj->z_origin && !obj_resolve_origin(obj))
1354 if (dyn_runpath != NULL) {
1355 obj->runpath = (char *)obj->strtab + dyn_runpath->d_un.d_val;
1356 obj->runpath = origin_subst(obj, obj->runpath);
1357 } else if (dyn_rpath != NULL) {
1358 obj->rpath = (char *)obj->strtab + dyn_rpath->d_un.d_val;
1359 obj->rpath = origin_subst(obj, obj->rpath);
1361 if (dyn_soname != NULL)
1362 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1366 digest_dynamic(Obj_Entry *obj, int early)
1368 const Elf_Dyn *dyn_rpath;
1369 const Elf_Dyn *dyn_soname;
1370 const Elf_Dyn *dyn_runpath;
1372 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname, &dyn_runpath);
1373 digest_dynamic2(obj, dyn_rpath, dyn_soname, dyn_runpath);
1377 * Process a shared object's program header. This is used only for the
1378 * main program, when the kernel has already loaded the main program
1379 * into memory before calling the dynamic linker. It creates and
1380 * returns an Obj_Entry structure.
1383 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1386 const Elf_Phdr *phlimit = phdr + phnum;
1388 Elf_Addr note_start, note_end;
1392 for (ph = phdr; ph < phlimit; ph++) {
1393 if (ph->p_type != PT_PHDR)
1397 obj->phsize = ph->p_memsz;
1398 obj->relocbase = (caddr_t)phdr - ph->p_vaddr;
1402 obj->stack_flags = PF_X | PF_R | PF_W;
1404 for (ph = phdr; ph < phlimit; ph++) {
1405 switch (ph->p_type) {
1408 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1412 if (nsegs == 0) { /* First load segment */
1413 obj->vaddrbase = trunc_page(ph->p_vaddr);
1414 obj->mapbase = obj->vaddrbase + obj->relocbase;
1415 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
1417 } else { /* Last load segment */
1418 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1425 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1430 obj->tlssize = ph->p_memsz;
1431 obj->tlsalign = ph->p_align;
1432 obj->tlsinitsize = ph->p_filesz;
1433 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1437 obj->stack_flags = ph->p_flags;
1441 obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1442 obj->relro_size = round_page(ph->p_memsz);
1446 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
1447 note_end = note_start + ph->p_filesz;
1448 digest_notes(obj, note_start, note_end);
1453 _rtld_error("%s: too few PT_LOAD segments", path);
1462 digest_notes(Obj_Entry *obj, Elf_Addr note_start, Elf_Addr note_end)
1464 const Elf_Note *note;
1465 const char *note_name;
1468 for (note = (const Elf_Note *)note_start; (Elf_Addr)note < note_end;
1469 note = (const Elf_Note *)((const char *)(note + 1) +
1470 roundup2(note->n_namesz, sizeof(Elf32_Addr)) +
1471 roundup2(note->n_descsz, sizeof(Elf32_Addr)))) {
1472 if (note->n_namesz != sizeof(NOTE_FREEBSD_VENDOR) ||
1473 note->n_descsz != sizeof(int32_t))
1475 if (note->n_type != NT_FREEBSD_ABI_TAG &&
1476 note->n_type != NT_FREEBSD_NOINIT_TAG)
1478 note_name = (const char *)(note + 1);
1479 if (strncmp(NOTE_FREEBSD_VENDOR, note_name,
1480 sizeof(NOTE_FREEBSD_VENDOR)) != 0)
1482 switch (note->n_type) {
1483 case NT_FREEBSD_ABI_TAG:
1484 /* FreeBSD osrel note */
1485 p = (uintptr_t)(note + 1);
1486 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1487 obj->osrel = *(const int32_t *)(p);
1488 dbg("note osrel %d", obj->osrel);
1490 case NT_FREEBSD_NOINIT_TAG:
1491 /* FreeBSD 'crt does not call init' note */
1492 obj->crt_no_init = true;
1493 dbg("note crt_no_init");
1500 dlcheck(void *handle)
1504 TAILQ_FOREACH(obj, &obj_list, next) {
1505 if (obj == (Obj_Entry *) handle)
1509 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1510 _rtld_error("Invalid shared object handle %p", handle);
1517 * If the given object is already in the donelist, return true. Otherwise
1518 * add the object to the list and return false.
1521 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1525 for (i = 0; i < dlp->num_used; i++)
1526 if (dlp->objs[i] == obj)
1529 * Our donelist allocation should always be sufficient. But if
1530 * our threads locking isn't working properly, more shared objects
1531 * could have been loaded since we allocated the list. That should
1532 * never happen, but we'll handle it properly just in case it does.
1534 if (dlp->num_used < dlp->num_alloc)
1535 dlp->objs[dlp->num_used++] = obj;
1540 * Hash function for symbol table lookup. Don't even think about changing
1541 * this. It is specified by the System V ABI.
1544 elf_hash(const char *name)
1546 const unsigned char *p = (const unsigned char *) name;
1547 unsigned long h = 0;
1550 while (*p != '\0') {
1551 h = (h << 4) + *p++;
1552 if ((g = h & 0xf0000000) != 0)
1560 * The GNU hash function is the Daniel J. Bernstein hash clipped to 32 bits
1561 * unsigned in case it's implemented with a wider type.
1564 gnu_hash(const char *s)
1570 for (c = *s; c != '\0'; c = *++s)
1572 return (h & 0xffffffff);
1577 * Find the library with the given name, and return its full pathname.
1578 * The returned string is dynamically allocated. Generates an error
1579 * message and returns NULL if the library cannot be found.
1581 * If the second argument is non-NULL, then it refers to an already-
1582 * loaded shared object, whose library search path will be searched.
1584 * If a library is successfully located via LD_LIBRARY_PATH_FDS, its
1585 * descriptor (which is close-on-exec) will be passed out via the third
1588 * The search order is:
1589 * DT_RPATH in the referencing file _unless_ DT_RUNPATH is present (1)
1590 * DT_RPATH of the main object if DSO without defined DT_RUNPATH (1)
1592 * DT_RUNPATH in the referencing file
1593 * ldconfig hints (if -z nodefaultlib, filter out default library directories
1595 * /lib:/usr/lib _unless_ the referencing file is linked with -z nodefaultlib
1597 * (1) Handled in digest_dynamic2 - rpath left NULL if runpath defined.
1600 find_library(const char *xname, const Obj_Entry *refobj, int *fdp)
1602 char *name, *pathname, *refobj_path;
1603 bool nodeflib, objgiven;
1605 objgiven = refobj != NULL;
1607 if (libmap_disable || !objgiven ||
1608 (name = lm_find(refobj->path, xname)) == NULL)
1609 name = (char *)xname;
1611 if (strchr(name, '/') != NULL) { /* Hard coded pathname */
1612 if (name[0] != '/' && !trust) {
1613 _rtld_error("Absolute pathname required "
1614 "for shared object \"%s\"", name);
1617 return (origin_subst(__DECONST(Obj_Entry *, refobj),
1618 __DECONST(char *, name)));
1621 dbg(" Searching for \"%s\"", name);
1622 refobj_path = objgiven ? refobj->path : NULL;
1625 * If refobj->rpath != NULL, then refobj->runpath is NULL. Fall
1626 * back to pre-conforming behaviour if user requested so with
1627 * LD_LIBRARY_PATH_RPATH environment variable and ignore -z
1630 if (objgiven && refobj->rpath != NULL && ld_library_path_rpath) {
1631 pathname = search_library_path(name, ld_library_path,
1633 if (pathname != NULL)
1635 if (refobj != NULL) {
1636 pathname = search_library_path(name, refobj->rpath,
1638 if (pathname != NULL)
1641 pathname = search_library_pathfds(name, ld_library_dirs, fdp);
1642 if (pathname != NULL)
1644 pathname = search_library_path(name, gethints(false),
1646 if (pathname != NULL)
1648 pathname = search_library_path(name, ld_standard_library_path,
1650 if (pathname != NULL)
1653 nodeflib = objgiven ? refobj->z_nodeflib : false;
1655 pathname = search_library_path(name, refobj->rpath,
1657 if (pathname != NULL)
1660 if (objgiven && refobj->runpath == NULL && refobj != obj_main) {
1661 pathname = search_library_path(name, obj_main->rpath,
1663 if (pathname != NULL)
1666 pathname = search_library_path(name, ld_library_path,
1668 if (pathname != NULL)
1671 pathname = search_library_path(name, refobj->runpath,
1673 if (pathname != NULL)
1676 pathname = search_library_pathfds(name, ld_library_dirs, fdp);
1677 if (pathname != NULL)
1679 pathname = search_library_path(name, gethints(nodeflib),
1681 if (pathname != NULL)
1683 if (objgiven && !nodeflib) {
1684 pathname = search_library_path(name,
1685 ld_standard_library_path, refobj_path, fdp);
1686 if (pathname != NULL)
1691 if (objgiven && refobj->path != NULL) {
1692 _rtld_error("Shared object \"%s\" not found, "
1693 "required by \"%s\"", name, basename(refobj->path));
1695 _rtld_error("Shared object \"%s\" not found", name);
1701 * Given a symbol number in a referencing object, find the corresponding
1702 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1703 * no definition was found. Returns a pointer to the Obj_Entry of the
1704 * defining object via the reference parameter DEFOBJ_OUT.
1707 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1708 const Obj_Entry **defobj_out, int flags, SymCache *cache,
1709 RtldLockState *lockstate)
1713 const Obj_Entry *defobj;
1714 const Ver_Entry *ve;
1720 * If we have already found this symbol, get the information from
1723 if (symnum >= refobj->dynsymcount)
1724 return NULL; /* Bad object */
1725 if (cache != NULL && cache[symnum].sym != NULL) {
1726 *defobj_out = cache[symnum].obj;
1727 return cache[symnum].sym;
1730 ref = refobj->symtab + symnum;
1731 name = refobj->strtab + ref->st_name;
1737 * We don't have to do a full scale lookup if the symbol is local.
1738 * We know it will bind to the instance in this load module; to
1739 * which we already have a pointer (ie ref). By not doing a lookup,
1740 * we not only improve performance, but it also avoids unresolvable
1741 * symbols when local symbols are not in the hash table. This has
1742 * been seen with the ia64 toolchain.
1744 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1745 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1746 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1749 symlook_init(&req, name);
1751 ve = req.ventry = fetch_ventry(refobj, symnum);
1752 req.lockstate = lockstate;
1753 res = symlook_default(&req, refobj);
1756 defobj = req.defobj_out;
1764 * If we found no definition and the reference is weak, treat the
1765 * symbol as having the value zero.
1767 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1773 *defobj_out = defobj;
1774 /* Record the information in the cache to avoid subsequent lookups. */
1775 if (cache != NULL) {
1776 cache[symnum].sym = def;
1777 cache[symnum].obj = defobj;
1780 if (refobj != &obj_rtld)
1781 _rtld_error("%s: Undefined symbol \"%s%s%s\"", refobj->path, name,
1782 ve != NULL ? "@" : "", ve != NULL ? ve->name : "");
1788 * Return the search path from the ldconfig hints file, reading it if
1789 * necessary. If nostdlib is true, then the default search paths are
1790 * not added to result.
1792 * Returns NULL if there are problems with the hints file,
1793 * or if the search path there is empty.
1796 gethints(bool nostdlib)
1798 static char *hints, *filtered_path;
1799 static struct elfhints_hdr hdr;
1800 struct fill_search_info_args sargs, hargs;
1801 struct dl_serinfo smeta, hmeta, *SLPinfo, *hintinfo;
1802 struct dl_serpath *SLPpath, *hintpath;
1804 struct stat hint_stat;
1805 unsigned int SLPndx, hintndx, fndx, fcount;
1811 /* First call, read the hints file */
1812 if (hints == NULL) {
1813 /* Keep from trying again in case the hints file is bad. */
1816 if ((fd = open(ld_elf_hints_path, O_RDONLY | O_CLOEXEC)) == -1)
1820 * Check of hdr.dirlistlen value against type limit
1821 * intends to pacify static analyzers. Further
1822 * paranoia leads to checks that dirlist is fully
1823 * contained in the file range.
1825 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1826 hdr.magic != ELFHINTS_MAGIC ||
1827 hdr.version != 1 || hdr.dirlistlen > UINT_MAX / 2 ||
1828 fstat(fd, &hint_stat) == -1) {
1835 if (dl + hdr.dirlist < dl)
1838 if (dl + hdr.dirlistlen < dl)
1840 dl += hdr.dirlistlen;
1841 if (dl > hint_stat.st_size)
1843 p = xmalloc(hdr.dirlistlen + 1);
1844 if (pread(fd, p, hdr.dirlistlen + 1,
1845 hdr.strtab + hdr.dirlist) != (ssize_t)hdr.dirlistlen + 1 ||
1846 p[hdr.dirlistlen] != '\0') {
1855 * If caller agreed to receive list which includes the default
1856 * paths, we are done. Otherwise, if we still did not
1857 * calculated filtered result, do it now.
1860 return (hints[0] != '\0' ? hints : NULL);
1861 if (filtered_path != NULL)
1865 * Obtain the list of all configured search paths, and the
1866 * list of the default paths.
1868 * First estimate the size of the results.
1870 smeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1872 hmeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1875 sargs.request = RTLD_DI_SERINFOSIZE;
1876 sargs.serinfo = &smeta;
1877 hargs.request = RTLD_DI_SERINFOSIZE;
1878 hargs.serinfo = &hmeta;
1880 path_enumerate(ld_standard_library_path, fill_search_info, NULL,
1882 path_enumerate(hints, fill_search_info, NULL, &hargs);
1884 SLPinfo = xmalloc(smeta.dls_size);
1885 hintinfo = xmalloc(hmeta.dls_size);
1888 * Next fetch both sets of paths.
1890 sargs.request = RTLD_DI_SERINFO;
1891 sargs.serinfo = SLPinfo;
1892 sargs.serpath = &SLPinfo->dls_serpath[0];
1893 sargs.strspace = (char *)&SLPinfo->dls_serpath[smeta.dls_cnt];
1895 hargs.request = RTLD_DI_SERINFO;
1896 hargs.serinfo = hintinfo;
1897 hargs.serpath = &hintinfo->dls_serpath[0];
1898 hargs.strspace = (char *)&hintinfo->dls_serpath[hmeta.dls_cnt];
1900 path_enumerate(ld_standard_library_path, fill_search_info, NULL,
1902 path_enumerate(hints, fill_search_info, NULL, &hargs);
1905 * Now calculate the difference between two sets, by excluding
1906 * standard paths from the full set.
1910 filtered_path = xmalloc(hdr.dirlistlen + 1);
1911 hintpath = &hintinfo->dls_serpath[0];
1912 for (hintndx = 0; hintndx < hmeta.dls_cnt; hintndx++, hintpath++) {
1914 SLPpath = &SLPinfo->dls_serpath[0];
1916 * Check each standard path against current.
1918 for (SLPndx = 0; SLPndx < smeta.dls_cnt; SLPndx++, SLPpath++) {
1919 /* matched, skip the path */
1920 if (!strcmp(hintpath->dls_name, SLPpath->dls_name)) {
1928 * Not matched against any standard path, add the path
1929 * to result. Separate consequtive paths with ':'.
1932 filtered_path[fndx] = ':';
1936 flen = strlen(hintpath->dls_name);
1937 strncpy((filtered_path + fndx), hintpath->dls_name, flen);
1940 filtered_path[fndx] = '\0';
1946 return (filtered_path[0] != '\0' ? filtered_path : NULL);
1950 init_dag(Obj_Entry *root)
1952 const Needed_Entry *needed;
1953 const Objlist_Entry *elm;
1956 if (root->dag_inited)
1958 donelist_init(&donelist);
1960 /* Root object belongs to own DAG. */
1961 objlist_push_tail(&root->dldags, root);
1962 objlist_push_tail(&root->dagmembers, root);
1963 donelist_check(&donelist, root);
1966 * Add dependencies of root object to DAG in breadth order
1967 * by exploiting the fact that each new object get added
1968 * to the tail of the dagmembers list.
1970 STAILQ_FOREACH(elm, &root->dagmembers, link) {
1971 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
1972 if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
1974 objlist_push_tail(&needed->obj->dldags, root);
1975 objlist_push_tail(&root->dagmembers, needed->obj);
1978 root->dag_inited = true;
1982 init_marker(Obj_Entry *marker)
1985 bzero(marker, sizeof(*marker));
1986 marker->marker = true;
1990 globallist_curr(const Obj_Entry *obj)
1997 return (__DECONST(Obj_Entry *, obj));
1998 obj = TAILQ_PREV(obj, obj_entry_q, next);
2003 globallist_next(const Obj_Entry *obj)
2007 obj = TAILQ_NEXT(obj, next);
2011 return (__DECONST(Obj_Entry *, obj));
2015 /* Prevent the object from being unmapped while the bind lock is dropped. */
2017 hold_object(Obj_Entry *obj)
2024 unhold_object(Obj_Entry *obj)
2027 assert(obj->holdcount > 0);
2028 if (--obj->holdcount == 0 && obj->unholdfree)
2029 release_object(obj);
2033 process_z(Obj_Entry *root)
2035 const Objlist_Entry *elm;
2039 * Walk over object DAG and process every dependent object
2040 * that is marked as DF_1_NODELETE or DF_1_GLOBAL. They need
2041 * to grow their own DAG.
2043 * For DF_1_GLOBAL, DAG is required for symbol lookups in
2044 * symlook_global() to work.
2046 * For DF_1_NODELETE, the DAG should have its reference upped.
2048 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2052 if (obj->z_nodelete && !obj->ref_nodel) {
2053 dbg("obj %s -z nodelete", obj->path);
2056 obj->ref_nodel = true;
2058 if (obj->z_global && objlist_find(&list_global, obj) == NULL) {
2059 dbg("obj %s -z global", obj->path);
2060 objlist_push_tail(&list_global, obj);
2066 * Initialize the dynamic linker. The argument is the address at which
2067 * the dynamic linker has been mapped into memory. The primary task of
2068 * this function is to relocate the dynamic linker.
2071 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
2073 Obj_Entry objtmp; /* Temporary rtld object */
2074 const Elf_Ehdr *ehdr;
2075 const Elf_Dyn *dyn_rpath;
2076 const Elf_Dyn *dyn_soname;
2077 const Elf_Dyn *dyn_runpath;
2079 #ifdef RTLD_INIT_PAGESIZES_EARLY
2080 /* The page size is required by the dynamic memory allocator. */
2081 init_pagesizes(aux_info);
2085 * Conjure up an Obj_Entry structure for the dynamic linker.
2087 * The "path" member can't be initialized yet because string constants
2088 * cannot yet be accessed. Below we will set it correctly.
2090 memset(&objtmp, 0, sizeof(objtmp));
2093 objtmp.mapbase = mapbase;
2095 objtmp.relocbase = mapbase;
2098 objtmp.dynamic = rtld_dynamic(&objtmp);
2099 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname, &dyn_runpath);
2100 assert(objtmp.needed == NULL);
2101 #if !defined(__mips__)
2102 /* MIPS has a bogus DT_TEXTREL. */
2103 assert(!objtmp.textrel);
2106 * Temporarily put the dynamic linker entry into the object list, so
2107 * that symbols can be found.
2109 relocate_objects(&objtmp, true, &objtmp, 0, NULL);
2111 ehdr = (Elf_Ehdr *)mapbase;
2112 objtmp.phdr = (Elf_Phdr *)((char *)mapbase + ehdr->e_phoff);
2113 objtmp.phsize = ehdr->e_phnum * sizeof(objtmp.phdr[0]);
2115 /* Initialize the object list. */
2116 TAILQ_INIT(&obj_list);
2118 /* Now that non-local variables can be accesses, copy out obj_rtld. */
2119 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
2121 #ifndef RTLD_INIT_PAGESIZES_EARLY
2122 /* The page size is required by the dynamic memory allocator. */
2123 init_pagesizes(aux_info);
2126 if (aux_info[AT_OSRELDATE] != NULL)
2127 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
2129 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname, dyn_runpath);
2131 /* Replace the path with a dynamically allocated copy. */
2132 obj_rtld.path = xstrdup(ld_path_rtld);
2134 r_debug.r_brk = r_debug_state;
2135 r_debug.r_state = RT_CONSISTENT;
2139 * Retrieve the array of supported page sizes. The kernel provides the page
2140 * sizes in increasing order.
2143 init_pagesizes(Elf_Auxinfo **aux_info)
2145 static size_t psa[MAXPAGESIZES];
2149 if (aux_info[AT_PAGESIZES] != NULL && aux_info[AT_PAGESIZESLEN] !=
2151 size = aux_info[AT_PAGESIZESLEN]->a_un.a_val;
2152 pagesizes = aux_info[AT_PAGESIZES]->a_un.a_ptr;
2155 if (sysctlnametomib("hw.pagesizes", mib, &len) == 0)
2158 /* As a fallback, retrieve the base page size. */
2159 size = sizeof(psa[0]);
2160 if (aux_info[AT_PAGESZ] != NULL) {
2161 psa[0] = aux_info[AT_PAGESZ]->a_un.a_val;
2165 mib[1] = HW_PAGESIZE;
2169 if (sysctl(mib, len, psa, &size, NULL, 0) == -1) {
2170 _rtld_error("sysctl for hw.pagesize(s) failed");
2176 npagesizes = size / sizeof(pagesizes[0]);
2177 /* Discard any invalid entries at the end of the array. */
2178 while (npagesizes > 0 && pagesizes[npagesizes - 1] == 0)
2183 * Add the init functions from a needed object list (and its recursive
2184 * needed objects) to "list". This is not used directly; it is a helper
2185 * function for initlist_add_objects(). The write lock must be held
2186 * when this function is called.
2189 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
2191 /* Recursively process the successor needed objects. */
2192 if (needed->next != NULL)
2193 initlist_add_neededs(needed->next, list);
2195 /* Process the current needed object. */
2196 if (needed->obj != NULL)
2197 initlist_add_objects(needed->obj, needed->obj, list);
2201 * Scan all of the DAGs rooted in the range of objects from "obj" to
2202 * "tail" and add their init functions to "list". This recurses over
2203 * the DAGs and ensure the proper init ordering such that each object's
2204 * needed libraries are initialized before the object itself. At the
2205 * same time, this function adds the objects to the global finalization
2206 * list "list_fini" in the opposite order. The write lock must be
2207 * held when this function is called.
2210 initlist_add_objects(Obj_Entry *obj, Obj_Entry *tail, Objlist *list)
2214 if (obj->init_scanned || obj->init_done)
2216 obj->init_scanned = true;
2218 /* Recursively process the successor objects. */
2219 nobj = globallist_next(obj);
2220 if (nobj != NULL && obj != tail)
2221 initlist_add_objects(nobj, tail, list);
2223 /* Recursively process the needed objects. */
2224 if (obj->needed != NULL)
2225 initlist_add_neededs(obj->needed, list);
2226 if (obj->needed_filtees != NULL)
2227 initlist_add_neededs(obj->needed_filtees, list);
2228 if (obj->needed_aux_filtees != NULL)
2229 initlist_add_neededs(obj->needed_aux_filtees, list);
2231 /* Add the object to the init list. */
2232 objlist_push_tail(list, obj);
2234 /* Add the object to the global fini list in the reverse order. */
2235 if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL)
2236 && !obj->on_fini_list) {
2237 objlist_push_head(&list_fini, obj);
2238 obj->on_fini_list = true;
2243 #define FPTR_TARGET(f) ((Elf_Addr) (f))
2247 free_needed_filtees(Needed_Entry *n, RtldLockState *lockstate)
2249 Needed_Entry *needed, *needed1;
2251 for (needed = n; needed != NULL; needed = needed->next) {
2252 if (needed->obj != NULL) {
2253 dlclose_locked(needed->obj, lockstate);
2257 for (needed = n; needed != NULL; needed = needed1) {
2258 needed1 = needed->next;
2264 unload_filtees(Obj_Entry *obj, RtldLockState *lockstate)
2267 free_needed_filtees(obj->needed_filtees, lockstate);
2268 obj->needed_filtees = NULL;
2269 free_needed_filtees(obj->needed_aux_filtees, lockstate);
2270 obj->needed_aux_filtees = NULL;
2271 obj->filtees_loaded = false;
2275 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags,
2276 RtldLockState *lockstate)
2279 for (; needed != NULL; needed = needed->next) {
2280 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
2281 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
2282 RTLD_LOCAL, lockstate);
2287 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
2290 lock_restart_for_upgrade(lockstate);
2291 if (!obj->filtees_loaded) {
2292 load_filtee1(obj, obj->needed_filtees, flags, lockstate);
2293 load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate);
2294 obj->filtees_loaded = true;
2299 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
2303 for (; needed != NULL; needed = needed->next) {
2304 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
2305 flags & ~RTLD_LO_NOLOAD);
2306 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
2313 * Given a shared object, traverse its list of needed objects, and load
2314 * each of them. Returns 0 on success. Generates an error message and
2315 * returns -1 on failure.
2318 load_needed_objects(Obj_Entry *first, int flags)
2322 for (obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
2325 if (process_needed(obj, obj->needed, flags) == -1)
2332 load_preload_objects(void)
2334 char *p = ld_preload;
2336 static const char delim[] = " \t:;";
2341 p += strspn(p, delim);
2342 while (*p != '\0') {
2343 size_t len = strcspn(p, delim);
2348 obj = load_object(p, -1, NULL, 0);
2350 return -1; /* XXX - cleanup */
2351 obj->z_interpose = true;
2354 p += strspn(p, delim);
2356 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
2361 printable_path(const char *path)
2364 return (path == NULL ? "<unknown>" : path);
2368 * Load a shared object into memory, if it is not already loaded. The
2369 * object may be specified by name or by user-supplied file descriptor
2370 * fd_u. In the later case, the fd_u descriptor is not closed, but its
2373 * Returns a pointer to the Obj_Entry for the object. Returns NULL
2377 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
2386 TAILQ_FOREACH(obj, &obj_list, next) {
2387 if (obj->marker || obj->doomed)
2389 if (object_match_name(obj, name))
2393 path = find_library(name, refobj, &fd);
2401 * search_library_pathfds() opens a fresh file descriptor for the
2402 * library, so there is no need to dup().
2404 } else if (fd_u == -1) {
2406 * If we didn't find a match by pathname, or the name is not
2407 * supplied, open the file and check again by device and inode.
2408 * This avoids false mismatches caused by multiple links or ".."
2411 * To avoid a race, we open the file and use fstat() rather than
2414 if ((fd = open(path, O_RDONLY | O_CLOEXEC | O_VERIFY)) == -1) {
2415 _rtld_error("Cannot open \"%s\"", path);
2420 fd = fcntl(fd_u, F_DUPFD_CLOEXEC, 0);
2422 _rtld_error("Cannot dup fd");
2427 if (fstat(fd, &sb) == -1) {
2428 _rtld_error("Cannot fstat \"%s\"", printable_path(path));
2433 TAILQ_FOREACH(obj, &obj_list, next) {
2434 if (obj->marker || obj->doomed)
2436 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
2439 if (obj != NULL && name != NULL) {
2440 object_add_name(obj, name);
2445 if (flags & RTLD_LO_NOLOAD) {
2451 /* First use of this object, so we must map it in */
2452 obj = do_load_object(fd, name, path, &sb, flags);
2461 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
2468 * but first, make sure that environment variables haven't been
2469 * used to circumvent the noexec flag on a filesystem.
2471 if (dangerous_ld_env) {
2472 if (fstatfs(fd, &fs) != 0) {
2473 _rtld_error("Cannot fstatfs \"%s\"", printable_path(path));
2476 if (fs.f_flags & MNT_NOEXEC) {
2477 _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
2481 dbg("loading \"%s\"", printable_path(path));
2482 obj = map_object(fd, printable_path(path), sbp);
2487 * If DT_SONAME is present in the object, digest_dynamic2 already
2488 * added it to the object names.
2491 object_add_name(obj, name);
2493 digest_dynamic(obj, 0);
2494 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path,
2495 obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount);
2496 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
2498 dbg("refusing to load non-loadable \"%s\"", obj->path);
2499 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
2500 munmap(obj->mapbase, obj->mapsize);
2505 obj->dlopened = (flags & RTLD_LO_DLOPEN) != 0;
2506 TAILQ_INSERT_TAIL(&obj_list, obj, next);
2509 linkmap_add(obj); /* for GDB & dlinfo() */
2510 max_stack_flags |= obj->stack_flags;
2512 dbg(" %p .. %p: %s", obj->mapbase,
2513 obj->mapbase + obj->mapsize - 1, obj->path);
2515 dbg(" WARNING: %s has impure text", obj->path);
2516 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
2523 obj_from_addr(const void *addr)
2527 TAILQ_FOREACH(obj, &obj_list, next) {
2530 if (addr < (void *) obj->mapbase)
2532 if (addr < (void *) (obj->mapbase + obj->mapsize))
2541 Elf_Addr *preinit_addr;
2544 preinit_addr = (Elf_Addr *)obj_main->preinit_array;
2545 if (preinit_addr == NULL)
2548 for (index = 0; index < obj_main->preinit_array_num; index++) {
2549 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) {
2550 dbg("calling preinit function for %s at %p", obj_main->path,
2551 (void *)preinit_addr[index]);
2552 LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index],
2553 0, 0, obj_main->path);
2554 call_init_pointer(obj_main, preinit_addr[index]);
2560 * Call the finalization functions for each of the objects in "list"
2561 * belonging to the DAG of "root" and referenced once. If NULL "root"
2562 * is specified, every finalization function will be called regardless
2563 * of the reference count and the list elements won't be freed. All of
2564 * the objects are expected to have non-NULL fini functions.
2567 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
2571 Elf_Addr *fini_addr;
2574 assert(root == NULL || root->refcount == 1);
2577 root->doomed = true;
2580 * Preserve the current error message since a fini function might
2581 * call into the dynamic linker and overwrite it.
2583 saved_msg = errmsg_save();
2585 STAILQ_FOREACH(elm, list, link) {
2586 if (root != NULL && (elm->obj->refcount != 1 ||
2587 objlist_find(&root->dagmembers, elm->obj) == NULL))
2589 /* Remove object from fini list to prevent recursive invocation. */
2590 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2591 /* Ensure that new references cannot be acquired. */
2592 elm->obj->doomed = true;
2594 hold_object(elm->obj);
2595 lock_release(rtld_bind_lock, lockstate);
2597 * It is legal to have both DT_FINI and DT_FINI_ARRAY defined.
2598 * When this happens, DT_FINI_ARRAY is processed first.
2600 fini_addr = (Elf_Addr *)elm->obj->fini_array;
2601 if (fini_addr != NULL && elm->obj->fini_array_num > 0) {
2602 for (index = elm->obj->fini_array_num - 1; index >= 0;
2604 if (fini_addr[index] != 0 && fini_addr[index] != 1) {
2605 dbg("calling fini function for %s at %p",
2606 elm->obj->path, (void *)fini_addr[index]);
2607 LD_UTRACE(UTRACE_FINI_CALL, elm->obj,
2608 (void *)fini_addr[index], 0, 0, elm->obj->path);
2609 call_initfini_pointer(elm->obj, fini_addr[index]);
2613 if (elm->obj->fini != (Elf_Addr)NULL) {
2614 dbg("calling fini function for %s at %p", elm->obj->path,
2615 (void *)elm->obj->fini);
2616 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini,
2617 0, 0, elm->obj->path);
2618 call_initfini_pointer(elm->obj, elm->obj->fini);
2620 wlock_acquire(rtld_bind_lock, lockstate);
2621 unhold_object(elm->obj);
2622 /* No need to free anything if process is going down. */
2626 * We must restart the list traversal after every fini call
2627 * because a dlclose() call from the fini function or from
2628 * another thread might have modified the reference counts.
2632 } while (elm != NULL);
2633 errmsg_restore(saved_msg);
2637 * Call the initialization functions for each of the objects in
2638 * "list". All of the objects are expected to have non-NULL init
2642 objlist_call_init(Objlist *list, RtldLockState *lockstate)
2647 Elf_Addr *init_addr;
2648 void (*reg)(void (*)(void));
2652 * Clean init_scanned flag so that objects can be rechecked and
2653 * possibly initialized earlier if any of vectors called below
2654 * cause the change by using dlopen.
2656 TAILQ_FOREACH(obj, &obj_list, next) {
2659 obj->init_scanned = false;
2663 * Preserve the current error message since an init function might
2664 * call into the dynamic linker and overwrite it.
2666 saved_msg = errmsg_save();
2667 STAILQ_FOREACH(elm, list, link) {
2668 if (elm->obj->init_done) /* Initialized early. */
2671 * Race: other thread might try to use this object before current
2672 * one completes the initialization. Not much can be done here
2673 * without better locking.
2675 elm->obj->init_done = true;
2676 hold_object(elm->obj);
2678 if (elm->obj == obj_main && obj_main->crt_no_init) {
2679 reg = (void (*)(void (*)(void)))get_program_var_addr(
2680 "__libc_atexit", lockstate);
2682 lock_release(rtld_bind_lock, lockstate);
2685 rtld_exit_ptr = rtld_nop_exit;
2689 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined.
2690 * When this happens, DT_INIT is processed first.
2692 if (elm->obj->init != (Elf_Addr)NULL) {
2693 dbg("calling init function for %s at %p", elm->obj->path,
2694 (void *)elm->obj->init);
2695 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init,
2696 0, 0, elm->obj->path);
2697 call_initfini_pointer(elm->obj, elm->obj->init);
2699 init_addr = (Elf_Addr *)elm->obj->init_array;
2700 if (init_addr != NULL) {
2701 for (index = 0; index < elm->obj->init_array_num; index++) {
2702 if (init_addr[index] != 0 && init_addr[index] != 1) {
2703 dbg("calling init function for %s at %p", elm->obj->path,
2704 (void *)init_addr[index]);
2705 LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
2706 (void *)init_addr[index], 0, 0, elm->obj->path);
2707 call_init_pointer(elm->obj, init_addr[index]);
2711 wlock_acquire(rtld_bind_lock, lockstate);
2712 unhold_object(elm->obj);
2714 errmsg_restore(saved_msg);
2718 objlist_clear(Objlist *list)
2722 while (!STAILQ_EMPTY(list)) {
2723 elm = STAILQ_FIRST(list);
2724 STAILQ_REMOVE_HEAD(list, link);
2729 static Objlist_Entry *
2730 objlist_find(Objlist *list, const Obj_Entry *obj)
2734 STAILQ_FOREACH(elm, list, link)
2735 if (elm->obj == obj)
2741 objlist_init(Objlist *list)
2747 objlist_push_head(Objlist *list, Obj_Entry *obj)
2751 elm = NEW(Objlist_Entry);
2753 STAILQ_INSERT_HEAD(list, elm, link);
2757 objlist_push_tail(Objlist *list, Obj_Entry *obj)
2761 elm = NEW(Objlist_Entry);
2763 STAILQ_INSERT_TAIL(list, elm, link);
2767 objlist_put_after(Objlist *list, Obj_Entry *listobj, Obj_Entry *obj)
2769 Objlist_Entry *elm, *listelm;
2771 STAILQ_FOREACH(listelm, list, link) {
2772 if (listelm->obj == listobj)
2775 elm = NEW(Objlist_Entry);
2777 if (listelm != NULL)
2778 STAILQ_INSERT_AFTER(list, listelm, elm, link);
2780 STAILQ_INSERT_TAIL(list, elm, link);
2784 objlist_remove(Objlist *list, Obj_Entry *obj)
2788 if ((elm = objlist_find(list, obj)) != NULL) {
2789 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2795 * Relocate dag rooted in the specified object.
2796 * Returns 0 on success, or -1 on failure.
2800 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj,
2801 int flags, RtldLockState *lockstate)
2807 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2808 error = relocate_object(elm->obj, bind_now, rtldobj, flags,
2817 * Prepare for, or clean after, relocating an object marked with
2818 * DT_TEXTREL or DF_TEXTREL. Before relocating, all read-only
2819 * segments are remapped read-write. After relocations are done, the
2820 * segment's permissions are returned back to the modes specified in
2821 * the phdrs. If any relocation happened, or always for wired
2822 * program, COW is triggered.
2825 reloc_textrel_prot(Obj_Entry *obj, bool before)
2832 for (l = obj->phsize / sizeof(*ph), ph = obj->phdr; l > 0;
2834 if (ph->p_type != PT_LOAD || (ph->p_flags & PF_W) != 0)
2836 base = obj->relocbase + trunc_page(ph->p_vaddr);
2837 sz = round_page(ph->p_vaddr + ph->p_filesz) -
2838 trunc_page(ph->p_vaddr);
2839 prot = convert_prot(ph->p_flags) | (before ? PROT_WRITE : 0);
2840 if (mprotect(base, sz, prot) == -1) {
2841 _rtld_error("%s: Cannot write-%sable text segment: %s",
2842 obj->path, before ? "en" : "dis",
2843 rtld_strerror(errno));
2851 * Relocate single object.
2852 * Returns 0 on success, or -1 on failure.
2855 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
2856 int flags, RtldLockState *lockstate)
2861 obj->relocated = true;
2863 dbg("relocating \"%s\"", obj->path);
2865 if (obj->symtab == NULL || obj->strtab == NULL ||
2866 !(obj->valid_hash_sysv || obj->valid_hash_gnu)) {
2867 _rtld_error("%s: Shared object has no run-time symbol table",
2872 /* There are relocations to the write-protected text segment. */
2873 if (obj->textrel && reloc_textrel_prot(obj, true) != 0)
2876 /* Process the non-PLT non-IFUNC relocations. */
2877 if (reloc_non_plt(obj, rtldobj, flags, lockstate))
2880 /* Re-protected the text segment. */
2881 if (obj->textrel && reloc_textrel_prot(obj, false) != 0)
2884 /* Set the special PLT or GOT entries. */
2887 /* Process the PLT relocations. */
2888 if (reloc_plt(obj) == -1)
2890 /* Relocate the jump slots if we are doing immediate binding. */
2891 if ((obj->bind_now || bind_now) && reloc_jmpslots(obj, flags,
2895 if (!obj->mainprog && obj_enforce_relro(obj) == -1)
2899 * Set up the magic number and version in the Obj_Entry. These
2900 * were checked in the crt1.o from the original ElfKit, so we
2901 * set them for backward compatibility.
2903 obj->magic = RTLD_MAGIC;
2904 obj->version = RTLD_VERSION;
2910 * Relocate newly-loaded shared objects. The argument is a pointer to
2911 * the Obj_Entry for the first such object. All objects from the first
2912 * to the end of the list of objects are relocated. Returns 0 on success,
2916 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
2917 int flags, RtldLockState *lockstate)
2922 for (error = 0, obj = first; obj != NULL;
2923 obj = TAILQ_NEXT(obj, next)) {
2926 error = relocate_object(obj, bind_now, rtldobj, flags,
2935 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
2936 * referencing STT_GNU_IFUNC symbols is postponed till the other
2937 * relocations are done. The indirect functions specified as
2938 * ifunc are allowed to call other symbols, so we need to have
2939 * objects relocated before asking for resolution from indirects.
2941 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
2942 * instead of the usual lazy handling of PLT slots. It is
2943 * consistent with how GNU does it.
2946 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags,
2947 RtldLockState *lockstate)
2950 if (obj->ifuncs_resolved)
2952 obj->ifuncs_resolved = true;
2953 if (!obj->irelative && !((obj->bind_now || bind_now) && obj->gnu_ifunc))
2955 if (obj_disable_relro(obj) == -1 ||
2956 (obj->irelative && reloc_iresolve(obj, lockstate) == -1) ||
2957 ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
2958 reloc_gnu_ifunc(obj, flags, lockstate) == -1) ||
2959 obj_enforce_relro(obj) == -1)
2965 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags,
2966 RtldLockState *lockstate)
2971 STAILQ_FOREACH(elm, list, link) {
2975 if (resolve_object_ifunc(obj, bind_now, flags,
2983 * Cleanup procedure. It will be called (by the atexit mechanism) just
2984 * before the process exits.
2989 RtldLockState lockstate;
2991 wlock_acquire(rtld_bind_lock, &lockstate);
2993 objlist_call_fini(&list_fini, NULL, &lockstate);
2994 /* No need to remove the items from the list, since we are exiting. */
2995 if (!libmap_disable)
2997 lock_release(rtld_bind_lock, &lockstate);
3006 * Iterate over a search path, translate each element, and invoke the
3007 * callback on the result.
3010 path_enumerate(const char *path, path_enum_proc callback,
3011 const char *refobj_path, void *arg)
3017 path += strspn(path, ":;");
3018 while (*path != '\0') {
3022 len = strcspn(path, ":;");
3023 trans = lm_findn(refobj_path, path, len);
3025 res = callback(trans, strlen(trans), arg);
3027 res = callback(path, len, arg);
3033 path += strspn(path, ":;");
3039 struct try_library_args {
3048 try_library_path(const char *dir, size_t dirlen, void *param)
3050 struct try_library_args *arg;
3054 if (*dir == '/' || trust) {
3057 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
3060 pathname = arg->buffer;
3061 strncpy(pathname, dir, dirlen);
3062 pathname[dirlen] = '/';
3063 strcpy(pathname + dirlen + 1, arg->name);
3065 dbg(" Trying \"%s\"", pathname);
3066 fd = open(pathname, O_RDONLY | O_CLOEXEC | O_VERIFY);
3068 dbg(" Opened \"%s\", fd %d", pathname, fd);
3069 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
3070 strcpy(pathname, arg->buffer);
3074 dbg(" Failed to open \"%s\": %s",
3075 pathname, rtld_strerror(errno));
3082 search_library_path(const char *name, const char *path,
3083 const char *refobj_path, int *fdp)
3086 struct try_library_args arg;
3092 arg.namelen = strlen(name);
3093 arg.buffer = xmalloc(PATH_MAX);
3094 arg.buflen = PATH_MAX;
3097 p = path_enumerate(path, try_library_path, refobj_path, &arg);
3107 * Finds the library with the given name using the directory descriptors
3108 * listed in the LD_LIBRARY_PATH_FDS environment variable.
3110 * Returns a freshly-opened close-on-exec file descriptor for the library,
3111 * or -1 if the library cannot be found.
3114 search_library_pathfds(const char *name, const char *path, int *fdp)
3116 char *envcopy, *fdstr, *found, *last_token;
3120 dbg("%s('%s', '%s', fdp)", __func__, name, path);
3122 /* Don't load from user-specified libdirs into setuid binaries. */
3126 /* We can't do anything if LD_LIBRARY_PATH_FDS isn't set. */
3130 /* LD_LIBRARY_PATH_FDS only works with relative paths. */
3131 if (name[0] == '/') {
3132 dbg("Absolute path (%s) passed to %s", name, __func__);
3137 * Use strtok_r() to walk the FD:FD:FD list. This requires a local
3138 * copy of the path, as strtok_r rewrites separator tokens
3142 envcopy = xstrdup(path);
3143 for (fdstr = strtok_r(envcopy, ":", &last_token); fdstr != NULL;
3144 fdstr = strtok_r(NULL, ":", &last_token)) {
3145 dirfd = parse_integer(fdstr);
3147 _rtld_error("failed to parse directory FD: '%s'",
3151 fd = __sys_openat(dirfd, name, O_RDONLY | O_CLOEXEC | O_VERIFY);
3154 len = strlen(fdstr) + strlen(name) + 3;
3155 found = xmalloc(len);
3156 if (rtld_snprintf(found, len, "#%d/%s", dirfd, name) < 0) {
3157 _rtld_error("error generating '%d/%s'",
3161 dbg("open('%s') => %d", found, fd);
3172 dlclose(void *handle)
3174 RtldLockState lockstate;
3177 wlock_acquire(rtld_bind_lock, &lockstate);
3178 error = dlclose_locked(handle, &lockstate);
3179 lock_release(rtld_bind_lock, &lockstate);
3184 dlclose_locked(void *handle, RtldLockState *lockstate)
3188 root = dlcheck(handle);
3191 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
3194 /* Unreference the object and its dependencies. */
3195 root->dl_refcount--;
3197 if (root->refcount == 1) {
3199 * The object will be no longer referenced, so we must unload it.
3200 * First, call the fini functions.
3202 objlist_call_fini(&list_fini, root, lockstate);
3206 /* Finish cleaning up the newly-unreferenced objects. */
3207 GDB_STATE(RT_DELETE,&root->linkmap);
3208 unload_object(root, lockstate);
3209 GDB_STATE(RT_CONSISTENT,NULL);
3213 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
3220 char *msg = error_message;
3221 error_message = NULL;
3226 * This function is deprecated and has no effect.
3229 dllockinit(void *context,
3230 void *(*lock_create)(void *context),
3231 void (*rlock_acquire)(void *lock),
3232 void (*wlock_acquire)(void *lock),
3233 void (*lock_release)(void *lock),
3234 void (*lock_destroy)(void *lock),
3235 void (*context_destroy)(void *context))
3237 static void *cur_context;
3238 static void (*cur_context_destroy)(void *);
3240 /* Just destroy the context from the previous call, if necessary. */
3241 if (cur_context_destroy != NULL)
3242 cur_context_destroy(cur_context);
3243 cur_context = context;
3244 cur_context_destroy = context_destroy;
3248 dlopen(const char *name, int mode)
3251 return (rtld_dlopen(name, -1, mode));
3255 fdlopen(int fd, int mode)
3258 return (rtld_dlopen(NULL, fd, mode));
3262 rtld_dlopen(const char *name, int fd, int mode)
3264 RtldLockState lockstate;
3267 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
3268 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
3269 if (ld_tracing != NULL) {
3270 rlock_acquire(rtld_bind_lock, &lockstate);
3271 if (sigsetjmp(lockstate.env, 0) != 0)
3272 lock_upgrade(rtld_bind_lock, &lockstate);
3273 environ = (char **)*get_program_var_addr("environ", &lockstate);
3274 lock_release(rtld_bind_lock, &lockstate);
3276 lo_flags = RTLD_LO_DLOPEN;
3277 if (mode & RTLD_NODELETE)
3278 lo_flags |= RTLD_LO_NODELETE;
3279 if (mode & RTLD_NOLOAD)
3280 lo_flags |= RTLD_LO_NOLOAD;
3281 if (ld_tracing != NULL)
3282 lo_flags |= RTLD_LO_TRACE;
3284 return (dlopen_object(name, fd, obj_main, lo_flags,
3285 mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL));
3289 dlopen_cleanup(Obj_Entry *obj, RtldLockState *lockstate)
3294 if (obj->refcount == 0)
3295 unload_object(obj, lockstate);
3299 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
3300 int mode, RtldLockState *lockstate)
3302 Obj_Entry *old_obj_tail;
3305 RtldLockState mlockstate;
3308 objlist_init(&initlist);
3310 if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) {
3311 wlock_acquire(rtld_bind_lock, &mlockstate);
3312 lockstate = &mlockstate;
3314 GDB_STATE(RT_ADD,NULL);
3316 old_obj_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
3318 if (name == NULL && fd == -1) {
3322 obj = load_object(name, fd, refobj, lo_flags);
3327 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
3328 objlist_push_tail(&list_global, obj);
3329 if (globallist_next(old_obj_tail) != NULL) {
3330 /* We loaded something new. */
3331 assert(globallist_next(old_obj_tail) == obj);
3333 if ((lo_flags & RTLD_LO_EARLY) == 0 && obj->static_tls &&
3334 !allocate_tls_offset(obj)) {
3335 _rtld_error("%s: No space available "
3336 "for static Thread Local Storage", obj->path);
3340 result = load_needed_objects(obj, lo_flags & (RTLD_LO_DLOPEN |
3345 result = rtld_verify_versions(&obj->dagmembers);
3346 if (result != -1 && ld_tracing)
3348 if (result == -1 || relocate_object_dag(obj,
3349 (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld,
3350 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3352 dlopen_cleanup(obj, lockstate);
3354 } else if (lo_flags & RTLD_LO_EARLY) {
3356 * Do not call the init functions for early loaded
3357 * filtees. The image is still not initialized enough
3360 * Our object is found by the global object list and
3361 * will be ordered among all init calls done right
3362 * before transferring control to main.
3365 /* Make list of init functions to call. */
3366 initlist_add_objects(obj, obj, &initlist);
3369 * Process all no_delete or global objects here, given
3370 * them own DAGs to prevent their dependencies from being
3371 * unloaded. This has to be done after we have loaded all
3372 * of the dependencies, so that we do not miss any.
3378 * Bump the reference counts for objects on this DAG. If
3379 * this is the first dlopen() call for the object that was
3380 * already loaded as a dependency, initialize the dag
3386 if ((lo_flags & RTLD_LO_TRACE) != 0)
3389 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
3390 obj->z_nodelete) && !obj->ref_nodel) {
3391 dbg("obj %s nodelete", obj->path);
3393 obj->z_nodelete = obj->ref_nodel = true;
3397 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
3399 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
3401 if ((lo_flags & RTLD_LO_EARLY) == 0) {
3402 map_stacks_exec(lockstate);
3404 distribute_static_tls(&initlist, lockstate);
3407 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
3408 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3410 objlist_clear(&initlist);
3411 dlopen_cleanup(obj, lockstate);
3412 if (lockstate == &mlockstate)
3413 lock_release(rtld_bind_lock, lockstate);
3417 if (!(lo_flags & RTLD_LO_EARLY)) {
3418 /* Call the init functions. */
3419 objlist_call_init(&initlist, lockstate);
3421 objlist_clear(&initlist);
3422 if (lockstate == &mlockstate)
3423 lock_release(rtld_bind_lock, lockstate);
3426 trace_loaded_objects(obj);
3427 if (lockstate == &mlockstate)
3428 lock_release(rtld_bind_lock, lockstate);
3433 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
3437 const Obj_Entry *obj, *defobj;
3440 RtldLockState lockstate;
3447 symlook_init(&req, name);
3449 req.flags = flags | SYMLOOK_IN_PLT;
3450 req.lockstate = &lockstate;
3452 LD_UTRACE(UTRACE_DLSYM_START, handle, NULL, 0, 0, name);
3453 rlock_acquire(rtld_bind_lock, &lockstate);
3454 if (sigsetjmp(lockstate.env, 0) != 0)
3455 lock_upgrade(rtld_bind_lock, &lockstate);
3456 if (handle == NULL || handle == RTLD_NEXT ||
3457 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
3459 if ((obj = obj_from_addr(retaddr)) == NULL) {
3460 _rtld_error("Cannot determine caller's shared object");
3461 lock_release(rtld_bind_lock, &lockstate);
3462 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3465 if (handle == NULL) { /* Just the caller's shared object. */
3466 res = symlook_obj(&req, obj);
3469 defobj = req.defobj_out;
3471 } else if (handle == RTLD_NEXT || /* Objects after caller's */
3472 handle == RTLD_SELF) { /* ... caller included */
3473 if (handle == RTLD_NEXT)
3474 obj = globallist_next(obj);
3475 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
3478 res = symlook_obj(&req, obj);
3481 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) {
3483 defobj = req.defobj_out;
3484 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3490 * Search the dynamic linker itself, and possibly resolve the
3491 * symbol from there. This is how the application links to
3492 * dynamic linker services such as dlopen.
3494 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3495 res = symlook_obj(&req, &obj_rtld);
3498 defobj = req.defobj_out;
3502 assert(handle == RTLD_DEFAULT);
3503 res = symlook_default(&req, obj);
3505 defobj = req.defobj_out;
3510 if ((obj = dlcheck(handle)) == NULL) {
3511 lock_release(rtld_bind_lock, &lockstate);
3512 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3516 donelist_init(&donelist);
3517 if (obj->mainprog) {
3518 /* Handle obtained by dlopen(NULL, ...) implies global scope. */
3519 res = symlook_global(&req, &donelist);
3522 defobj = req.defobj_out;
3525 * Search the dynamic linker itself, and possibly resolve the
3526 * symbol from there. This is how the application links to
3527 * dynamic linker services such as dlopen.
3529 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3530 res = symlook_obj(&req, &obj_rtld);
3533 defobj = req.defobj_out;
3538 /* Search the whole DAG rooted at the given object. */
3539 res = symlook_list(&req, &obj->dagmembers, &donelist);
3542 defobj = req.defobj_out;
3548 lock_release(rtld_bind_lock, &lockstate);
3551 * The value required by the caller is derived from the value
3552 * of the symbol. this is simply the relocated value of the
3555 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
3556 sym = make_function_pointer(def, defobj);
3557 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
3558 sym = rtld_resolve_ifunc(defobj, def);
3559 else if (ELF_ST_TYPE(def->st_info) == STT_TLS) {
3560 ti.ti_module = defobj->tlsindex;
3561 ti.ti_offset = def->st_value;
3562 sym = __tls_get_addr(&ti);
3564 sym = defobj->relocbase + def->st_value;
3565 LD_UTRACE(UTRACE_DLSYM_STOP, handle, sym, 0, 0, name);
3569 _rtld_error("Undefined symbol \"%s%s%s\"", name, ve != NULL ? "@" : "",
3570 ve != NULL ? ve->name : "");
3571 lock_release(rtld_bind_lock, &lockstate);
3572 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3577 dlsym(void *handle, const char *name)
3579 return do_dlsym(handle, name, __builtin_return_address(0), NULL,
3584 dlfunc(void *handle, const char *name)
3591 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
3597 dlvsym(void *handle, const char *name, const char *version)
3601 ventry.name = version;
3603 ventry.hash = elf_hash(version);
3605 return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
3610 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
3612 const Obj_Entry *obj;
3613 RtldLockState lockstate;
3615 rlock_acquire(rtld_bind_lock, &lockstate);
3616 obj = obj_from_addr(addr);
3618 _rtld_error("No shared object contains address");
3619 lock_release(rtld_bind_lock, &lockstate);
3622 rtld_fill_dl_phdr_info(obj, phdr_info);
3623 lock_release(rtld_bind_lock, &lockstate);
3628 dladdr(const void *addr, Dl_info *info)
3630 const Obj_Entry *obj;
3633 unsigned long symoffset;
3634 RtldLockState lockstate;
3636 rlock_acquire(rtld_bind_lock, &lockstate);
3637 obj = obj_from_addr(addr);
3639 _rtld_error("No shared object contains address");
3640 lock_release(rtld_bind_lock, &lockstate);
3643 info->dli_fname = obj->path;
3644 info->dli_fbase = obj->mapbase;
3645 info->dli_saddr = (void *)0;
3646 info->dli_sname = NULL;
3649 * Walk the symbol list looking for the symbol whose address is
3650 * closest to the address sent in.
3652 for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) {
3653 def = obj->symtab + symoffset;
3656 * For skip the symbol if st_shndx is either SHN_UNDEF or
3659 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
3663 * If the symbol is greater than the specified address, or if it
3664 * is further away from addr than the current nearest symbol,
3667 symbol_addr = obj->relocbase + def->st_value;
3668 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
3671 /* Update our idea of the nearest symbol. */
3672 info->dli_sname = obj->strtab + def->st_name;
3673 info->dli_saddr = symbol_addr;
3676 if (info->dli_saddr == addr)
3679 lock_release(rtld_bind_lock, &lockstate);
3684 dlinfo(void *handle, int request, void *p)
3686 const Obj_Entry *obj;
3687 RtldLockState lockstate;
3690 rlock_acquire(rtld_bind_lock, &lockstate);
3692 if (handle == NULL || handle == RTLD_SELF) {
3695 retaddr = __builtin_return_address(0); /* __GNUC__ only */
3696 if ((obj = obj_from_addr(retaddr)) == NULL)
3697 _rtld_error("Cannot determine caller's shared object");
3699 obj = dlcheck(handle);
3702 lock_release(rtld_bind_lock, &lockstate);
3708 case RTLD_DI_LINKMAP:
3709 *((struct link_map const **)p) = &obj->linkmap;
3711 case RTLD_DI_ORIGIN:
3712 error = rtld_dirname(obj->path, p);
3715 case RTLD_DI_SERINFOSIZE:
3716 case RTLD_DI_SERINFO:
3717 error = do_search_info(obj, request, (struct dl_serinfo *)p);
3721 _rtld_error("Invalid request %d passed to dlinfo()", request);
3725 lock_release(rtld_bind_lock, &lockstate);
3731 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
3734 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
3735 phdr_info->dlpi_name = obj->path;
3736 phdr_info->dlpi_phdr = obj->phdr;
3737 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
3738 phdr_info->dlpi_tls_modid = obj->tlsindex;
3739 phdr_info->dlpi_tls_data = obj->tlsinit;
3740 phdr_info->dlpi_adds = obj_loads;
3741 phdr_info->dlpi_subs = obj_loads - obj_count;
3745 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
3747 struct dl_phdr_info phdr_info;
3748 Obj_Entry *obj, marker;
3749 RtldLockState bind_lockstate, phdr_lockstate;
3752 init_marker(&marker);
3755 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
3756 wlock_acquire(rtld_bind_lock, &bind_lockstate);
3757 for (obj = globallist_curr(TAILQ_FIRST(&obj_list)); obj != NULL;) {
3758 TAILQ_INSERT_AFTER(&obj_list, obj, &marker, next);
3759 rtld_fill_dl_phdr_info(obj, &phdr_info);
3761 lock_release(rtld_bind_lock, &bind_lockstate);
3763 error = callback(&phdr_info, sizeof phdr_info, param);
3765 wlock_acquire(rtld_bind_lock, &bind_lockstate);
3767 obj = globallist_next(&marker);
3768 TAILQ_REMOVE(&obj_list, &marker, next);
3770 lock_release(rtld_bind_lock, &bind_lockstate);
3771 lock_release(rtld_phdr_lock, &phdr_lockstate);
3777 rtld_fill_dl_phdr_info(&obj_rtld, &phdr_info);
3778 lock_release(rtld_bind_lock, &bind_lockstate);
3779 error = callback(&phdr_info, sizeof(phdr_info), param);
3781 lock_release(rtld_phdr_lock, &phdr_lockstate);
3786 fill_search_info(const char *dir, size_t dirlen, void *param)
3788 struct fill_search_info_args *arg;
3792 if (arg->request == RTLD_DI_SERINFOSIZE) {
3793 arg->serinfo->dls_cnt ++;
3794 arg->serinfo->dls_size += sizeof(struct dl_serpath) + dirlen + 1;
3796 struct dl_serpath *s_entry;
3798 s_entry = arg->serpath;
3799 s_entry->dls_name = arg->strspace;
3800 s_entry->dls_flags = arg->flags;
3802 strncpy(arg->strspace, dir, dirlen);
3803 arg->strspace[dirlen] = '\0';
3805 arg->strspace += dirlen + 1;
3813 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
3815 struct dl_serinfo _info;
3816 struct fill_search_info_args args;
3818 args.request = RTLD_DI_SERINFOSIZE;
3819 args.serinfo = &_info;
3821 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
3824 path_enumerate(obj->rpath, fill_search_info, NULL, &args);
3825 path_enumerate(ld_library_path, fill_search_info, NULL, &args);
3826 path_enumerate(obj->runpath, fill_search_info, NULL, &args);
3827 path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args);
3828 if (!obj->z_nodeflib)
3829 path_enumerate(ld_standard_library_path, fill_search_info, NULL, &args);
3832 if (request == RTLD_DI_SERINFOSIZE) {
3833 info->dls_size = _info.dls_size;
3834 info->dls_cnt = _info.dls_cnt;
3838 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
3839 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
3843 args.request = RTLD_DI_SERINFO;
3844 args.serinfo = info;
3845 args.serpath = &info->dls_serpath[0];
3846 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
3848 args.flags = LA_SER_RUNPATH;
3849 if (path_enumerate(obj->rpath, fill_search_info, NULL, &args) != NULL)
3852 args.flags = LA_SER_LIBPATH;
3853 if (path_enumerate(ld_library_path, fill_search_info, NULL, &args) != NULL)
3856 args.flags = LA_SER_RUNPATH;
3857 if (path_enumerate(obj->runpath, fill_search_info, NULL, &args) != NULL)
3860 args.flags = LA_SER_CONFIG;
3861 if (path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args)
3865 args.flags = LA_SER_DEFAULT;
3866 if (!obj->z_nodeflib && path_enumerate(ld_standard_library_path,
3867 fill_search_info, NULL, &args) != NULL)
3873 rtld_dirname(const char *path, char *bname)
3877 /* Empty or NULL string gets treated as "." */
3878 if (path == NULL || *path == '\0') {
3884 /* Strip trailing slashes */
3885 endp = path + strlen(path) - 1;
3886 while (endp > path && *endp == '/')
3889 /* Find the start of the dir */
3890 while (endp > path && *endp != '/')
3893 /* Either the dir is "/" or there are no slashes */
3895 bname[0] = *endp == '/' ? '/' : '.';
3901 } while (endp > path && *endp == '/');
3904 if (endp - path + 2 > PATH_MAX)
3906 _rtld_error("Filename is too long: %s", path);
3910 strncpy(bname, path, endp - path + 1);
3911 bname[endp - path + 1] = '\0';
3916 rtld_dirname_abs(const char *path, char *base)
3920 if (realpath(path, base) == NULL)
3922 dbg("%s -> %s", path, base);
3923 last = strrchr(base, '/');
3932 linkmap_add(Obj_Entry *obj)
3934 struct link_map *l = &obj->linkmap;
3935 struct link_map *prev;
3937 obj->linkmap.l_name = obj->path;
3938 obj->linkmap.l_addr = obj->mapbase;
3939 obj->linkmap.l_ld = obj->dynamic;
3941 /* GDB needs load offset on MIPS to use the symbols */
3942 obj->linkmap.l_offs = obj->relocbase;
3945 if (r_debug.r_map == NULL) {
3951 * Scan to the end of the list, but not past the entry for the
3952 * dynamic linker, which we want to keep at the very end.
3954 for (prev = r_debug.r_map;
3955 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
3956 prev = prev->l_next)
3959 /* Link in the new entry. */
3961 l->l_next = prev->l_next;
3962 if (l->l_next != NULL)
3963 l->l_next->l_prev = l;
3968 linkmap_delete(Obj_Entry *obj)
3970 struct link_map *l = &obj->linkmap;
3972 if (l->l_prev == NULL) {
3973 if ((r_debug.r_map = l->l_next) != NULL)
3974 l->l_next->l_prev = NULL;
3978 if ((l->l_prev->l_next = l->l_next) != NULL)
3979 l->l_next->l_prev = l->l_prev;
3983 * Function for the debugger to set a breakpoint on to gain control.
3985 * The two parameters allow the debugger to easily find and determine
3986 * what the runtime loader is doing and to whom it is doing it.
3988 * When the loadhook trap is hit (r_debug_state, set at program
3989 * initialization), the arguments can be found on the stack:
3991 * +8 struct link_map *m
3992 * +4 struct r_debug *rd
3996 r_debug_state(struct r_debug* rd, struct link_map *m)
3999 * The following is a hack to force the compiler to emit calls to
4000 * this function, even when optimizing. If the function is empty,
4001 * the compiler is not obliged to emit any code for calls to it,
4002 * even when marked __noinline. However, gdb depends on those
4005 __compiler_membar();
4009 * A function called after init routines have completed. This can be used to
4010 * break before a program's entry routine is called, and can be used when
4011 * main is not available in the symbol table.
4014 _r_debug_postinit(struct link_map *m)
4017 /* See r_debug_state(). */
4018 __compiler_membar();
4022 release_object(Obj_Entry *obj)
4025 if (obj->holdcount > 0) {
4026 obj->unholdfree = true;
4029 munmap(obj->mapbase, obj->mapsize);
4030 linkmap_delete(obj);
4035 * Get address of the pointer variable in the main program.
4036 * Prefer non-weak symbol over the weak one.
4038 static const void **
4039 get_program_var_addr(const char *name, RtldLockState *lockstate)
4044 symlook_init(&req, name);
4045 req.lockstate = lockstate;
4046 donelist_init(&donelist);
4047 if (symlook_global(&req, &donelist) != 0)
4049 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
4050 return ((const void **)make_function_pointer(req.sym_out,
4052 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
4053 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
4055 return ((const void **)(req.defobj_out->relocbase +
4056 req.sym_out->st_value));
4060 * Set a pointer variable in the main program to the given value. This
4061 * is used to set key variables such as "environ" before any of the
4062 * init functions are called.
4065 set_program_var(const char *name, const void *value)
4069 if ((addr = get_program_var_addr(name, NULL)) != NULL) {
4070 dbg("\"%s\": *%p <-- %p", name, addr, value);
4076 * Search the global objects, including dependencies and main object,
4077 * for the given symbol.
4080 symlook_global(SymLook *req, DoneList *donelist)
4083 const Objlist_Entry *elm;
4086 symlook_init_from_req(&req1, req);
4088 /* Search all objects loaded at program start up. */
4089 if (req->defobj_out == NULL ||
4090 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
4091 res = symlook_list(&req1, &list_main, donelist);
4092 if (res == 0 && (req->defobj_out == NULL ||
4093 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4094 req->sym_out = req1.sym_out;
4095 req->defobj_out = req1.defobj_out;
4096 assert(req->defobj_out != NULL);
4100 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
4101 STAILQ_FOREACH(elm, &list_global, link) {
4102 if (req->defobj_out != NULL &&
4103 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
4105 res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
4106 if (res == 0 && (req->defobj_out == NULL ||
4107 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4108 req->sym_out = req1.sym_out;
4109 req->defobj_out = req1.defobj_out;
4110 assert(req->defobj_out != NULL);
4114 return (req->sym_out != NULL ? 0 : ESRCH);
4118 * Given a symbol name in a referencing object, find the corresponding
4119 * definition of the symbol. Returns a pointer to the symbol, or NULL if
4120 * no definition was found. Returns a pointer to the Obj_Entry of the
4121 * defining object via the reference parameter DEFOBJ_OUT.
4124 symlook_default(SymLook *req, const Obj_Entry *refobj)
4127 const Objlist_Entry *elm;
4131 donelist_init(&donelist);
4132 symlook_init_from_req(&req1, req);
4135 * Look first in the referencing object if linked symbolically,
4136 * and similarly handle protected symbols.
4138 res = symlook_obj(&req1, refobj);
4139 if (res == 0 && (refobj->symbolic ||
4140 ELF_ST_VISIBILITY(req1.sym_out->st_other) == STV_PROTECTED)) {
4141 req->sym_out = req1.sym_out;
4142 req->defobj_out = req1.defobj_out;
4143 assert(req->defobj_out != NULL);
4145 if (refobj->symbolic || req->defobj_out != NULL)
4146 donelist_check(&donelist, refobj);
4148 symlook_global(req, &donelist);
4150 /* Search all dlopened DAGs containing the referencing object. */
4151 STAILQ_FOREACH(elm, &refobj->dldags, link) {
4152 if (req->sym_out != NULL &&
4153 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
4155 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
4156 if (res == 0 && (req->sym_out == NULL ||
4157 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4158 req->sym_out = req1.sym_out;
4159 req->defobj_out = req1.defobj_out;
4160 assert(req->defobj_out != NULL);
4165 * Search the dynamic linker itself, and possibly resolve the
4166 * symbol from there. This is how the application links to
4167 * dynamic linker services such as dlopen.
4169 if (req->sym_out == NULL ||
4170 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
4171 res = symlook_obj(&req1, &obj_rtld);
4173 req->sym_out = req1.sym_out;
4174 req->defobj_out = req1.defobj_out;
4175 assert(req->defobj_out != NULL);
4179 return (req->sym_out != NULL ? 0 : ESRCH);
4183 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
4186 const Obj_Entry *defobj;
4187 const Objlist_Entry *elm;
4193 STAILQ_FOREACH(elm, objlist, link) {
4194 if (donelist_check(dlp, elm->obj))
4196 symlook_init_from_req(&req1, req);
4197 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
4198 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
4200 defobj = req1.defobj_out;
4201 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
4208 req->defobj_out = defobj;
4215 * Search the chain of DAGS cointed to by the given Needed_Entry
4216 * for a symbol of the given name. Each DAG is scanned completely
4217 * before advancing to the next one. Returns a pointer to the symbol,
4218 * or NULL if no definition was found.
4221 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
4224 const Needed_Entry *n;
4225 const Obj_Entry *defobj;
4231 symlook_init_from_req(&req1, req);
4232 for (n = needed; n != NULL; n = n->next) {
4233 if (n->obj == NULL ||
4234 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
4236 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
4238 defobj = req1.defobj_out;
4239 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
4245 req->defobj_out = defobj;
4252 * Search the symbol table of a single shared object for a symbol of
4253 * the given name and version, if requested. Returns a pointer to the
4254 * symbol, or NULL if no definition was found. If the object is
4255 * filter, return filtered symbol from filtee.
4257 * The symbol's hash value is passed in for efficiency reasons; that
4258 * eliminates many recomputations of the hash value.
4261 symlook_obj(SymLook *req, const Obj_Entry *obj)
4265 int flags, res, mres;
4268 * If there is at least one valid hash at this point, we prefer to
4269 * use the faster GNU version if available.
4271 if (obj->valid_hash_gnu)
4272 mres = symlook_obj1_gnu(req, obj);
4273 else if (obj->valid_hash_sysv)
4274 mres = symlook_obj1_sysv(req, obj);
4279 if (obj->needed_filtees != NULL) {
4280 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4281 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4282 donelist_init(&donelist);
4283 symlook_init_from_req(&req1, req);
4284 res = symlook_needed(&req1, obj->needed_filtees, &donelist);
4286 req->sym_out = req1.sym_out;
4287 req->defobj_out = req1.defobj_out;
4291 if (obj->needed_aux_filtees != NULL) {
4292 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4293 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4294 donelist_init(&donelist);
4295 symlook_init_from_req(&req1, req);
4296 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
4298 req->sym_out = req1.sym_out;
4299 req->defobj_out = req1.defobj_out;
4307 /* Symbol match routine common to both hash functions */
4309 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result,
4310 const unsigned long symnum)
4313 const Elf_Sym *symp;
4316 symp = obj->symtab + symnum;
4317 strp = obj->strtab + symp->st_name;
4319 switch (ELF_ST_TYPE(symp->st_info)) {
4325 if (symp->st_value == 0)
4329 if (symp->st_shndx != SHN_UNDEF)
4332 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
4333 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
4340 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
4343 if (req->ventry == NULL) {
4344 if (obj->versyms != NULL) {
4345 verndx = VER_NDX(obj->versyms[symnum]);
4346 if (verndx > obj->vernum) {
4348 "%s: symbol %s references wrong version %d",
4349 obj->path, obj->strtab + symnum, verndx);
4353 * If we are not called from dlsym (i.e. this
4354 * is a normal relocation from unversioned
4355 * binary), accept the symbol immediately if
4356 * it happens to have first version after this
4357 * shared object became versioned. Otherwise,
4358 * if symbol is versioned and not hidden,
4359 * remember it. If it is the only symbol with
4360 * this name exported by the shared object, it
4361 * will be returned as a match by the calling
4362 * function. If symbol is global (verndx < 2)
4363 * accept it unconditionally.
4365 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
4366 verndx == VER_NDX_GIVEN) {
4367 result->sym_out = symp;
4370 else if (verndx >= VER_NDX_GIVEN) {
4371 if ((obj->versyms[symnum] & VER_NDX_HIDDEN)
4373 if (result->vsymp == NULL)
4374 result->vsymp = symp;
4380 result->sym_out = symp;
4383 if (obj->versyms == NULL) {
4384 if (object_match_name(obj, req->ventry->name)) {
4385 _rtld_error("%s: object %s should provide version %s "
4386 "for symbol %s", obj_rtld.path, obj->path,
4387 req->ventry->name, obj->strtab + symnum);
4391 verndx = VER_NDX(obj->versyms[symnum]);
4392 if (verndx > obj->vernum) {
4393 _rtld_error("%s: symbol %s references wrong version %d",
4394 obj->path, obj->strtab + symnum, verndx);
4397 if (obj->vertab[verndx].hash != req->ventry->hash ||
4398 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
4400 * Version does not match. Look if this is a
4401 * global symbol and if it is not hidden. If
4402 * global symbol (verndx < 2) is available,
4403 * use it. Do not return symbol if we are
4404 * called by dlvsym, because dlvsym looks for
4405 * a specific version and default one is not
4406 * what dlvsym wants.
4408 if ((req->flags & SYMLOOK_DLSYM) ||
4409 (verndx >= VER_NDX_GIVEN) ||
4410 (obj->versyms[symnum] & VER_NDX_HIDDEN))
4414 result->sym_out = symp;
4419 * Search for symbol using SysV hash function.
4420 * obj->buckets is known not to be NULL at this point; the test for this was
4421 * performed with the obj->valid_hash_sysv assignment.
4424 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj)
4426 unsigned long symnum;
4427 Sym_Match_Result matchres;
4429 matchres.sym_out = NULL;
4430 matchres.vsymp = NULL;
4431 matchres.vcount = 0;
4433 for (symnum = obj->buckets[req->hash % obj->nbuckets];
4434 symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
4435 if (symnum >= obj->nchains)
4436 return (ESRCH); /* Bad object */
4438 if (matched_symbol(req, obj, &matchres, symnum)) {
4439 req->sym_out = matchres.sym_out;
4440 req->defobj_out = obj;
4444 if (matchres.vcount == 1) {
4445 req->sym_out = matchres.vsymp;
4446 req->defobj_out = obj;
4452 /* Search for symbol using GNU hash function */
4454 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj)
4456 Elf_Addr bloom_word;
4457 const Elf32_Word *hashval;
4459 Sym_Match_Result matchres;
4460 unsigned int h1, h2;
4461 unsigned long symnum;
4463 matchres.sym_out = NULL;
4464 matchres.vsymp = NULL;
4465 matchres.vcount = 0;
4467 /* Pick right bitmask word from Bloom filter array */
4468 bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) &
4469 obj->maskwords_bm_gnu];
4471 /* Calculate modulus word size of gnu hash and its derivative */
4472 h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1);
4473 h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1));
4475 /* Filter out the "definitely not in set" queries */
4476 if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0)
4479 /* Locate hash chain and corresponding value element*/
4480 bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu];
4483 hashval = &obj->chain_zero_gnu[bucket];
4485 if (((*hashval ^ req->hash_gnu) >> 1) == 0) {
4486 symnum = hashval - obj->chain_zero_gnu;
4487 if (matched_symbol(req, obj, &matchres, symnum)) {
4488 req->sym_out = matchres.sym_out;
4489 req->defobj_out = obj;
4493 } while ((*hashval++ & 1) == 0);
4494 if (matchres.vcount == 1) {
4495 req->sym_out = matchres.vsymp;
4496 req->defobj_out = obj;
4503 trace_loaded_objects(Obj_Entry *obj)
4505 char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
4508 if ((main_local = getenv(_LD("TRACE_LOADED_OBJECTS_PROGNAME"))) == NULL)
4511 if ((fmt1 = getenv(_LD("TRACE_LOADED_OBJECTS_FMT1"))) == NULL)
4512 fmt1 = "\t%o => %p (%x)\n";
4514 if ((fmt2 = getenv(_LD("TRACE_LOADED_OBJECTS_FMT2"))) == NULL)
4515 fmt2 = "\t%o (%x)\n";
4517 list_containers = getenv(_LD("TRACE_LOADED_OBJECTS_ALL"));
4519 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
4520 Needed_Entry *needed;
4526 if (list_containers && obj->needed != NULL)
4527 rtld_printf("%s:\n", obj->path);
4528 for (needed = obj->needed; needed; needed = needed->next) {
4529 if (needed->obj != NULL) {
4530 if (needed->obj->traced && !list_containers)
4532 needed->obj->traced = true;
4533 path = needed->obj->path;
4537 name = (char *)obj->strtab + needed->name;
4538 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
4540 fmt = is_lib ? fmt1 : fmt2;
4541 while ((c = *fmt++) != '\0') {
4567 rtld_putstr(main_local);
4570 rtld_putstr(obj_main->path);
4577 rtld_printf("%d", sodp->sod_major);
4580 rtld_printf("%d", sodp->sod_minor);
4587 rtld_printf("%p", needed->obj ? needed->obj->mapbase :
4600 * Unload a dlopened object and its dependencies from memory and from
4601 * our data structures. It is assumed that the DAG rooted in the
4602 * object has already been unreferenced, and that the object has a
4603 * reference count of 0.
4606 unload_object(Obj_Entry *root, RtldLockState *lockstate)
4608 Obj_Entry marker, *obj, *next;
4610 assert(root->refcount == 0);
4613 * Pass over the DAG removing unreferenced objects from
4614 * appropriate lists.
4616 unlink_object(root);
4618 /* Unmap all objects that are no longer referenced. */
4619 for (obj = TAILQ_FIRST(&obj_list); obj != NULL; obj = next) {
4620 next = TAILQ_NEXT(obj, next);
4621 if (obj->marker || obj->refcount != 0)
4623 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase,
4624 obj->mapsize, 0, obj->path);
4625 dbg("unloading \"%s\"", obj->path);
4627 * Unlink the object now to prevent new references from
4628 * being acquired while the bind lock is dropped in
4629 * recursive dlclose() invocations.
4631 TAILQ_REMOVE(&obj_list, obj, next);
4634 if (obj->filtees_loaded) {
4636 init_marker(&marker);
4637 TAILQ_INSERT_BEFORE(next, &marker, next);
4638 unload_filtees(obj, lockstate);
4639 next = TAILQ_NEXT(&marker, next);
4640 TAILQ_REMOVE(&obj_list, &marker, next);
4642 unload_filtees(obj, lockstate);
4644 release_object(obj);
4649 unlink_object(Obj_Entry *root)
4653 if (root->refcount == 0) {
4654 /* Remove the object from the RTLD_GLOBAL list. */
4655 objlist_remove(&list_global, root);
4657 /* Remove the object from all objects' DAG lists. */
4658 STAILQ_FOREACH(elm, &root->dagmembers, link) {
4659 objlist_remove(&elm->obj->dldags, root);
4660 if (elm->obj != root)
4661 unlink_object(elm->obj);
4667 ref_dag(Obj_Entry *root)
4671 assert(root->dag_inited);
4672 STAILQ_FOREACH(elm, &root->dagmembers, link)
4673 elm->obj->refcount++;
4677 unref_dag(Obj_Entry *root)
4681 assert(root->dag_inited);
4682 STAILQ_FOREACH(elm, &root->dagmembers, link)
4683 elm->obj->refcount--;
4687 * Common code for MD __tls_get_addr().
4689 static void *tls_get_addr_slow(Elf_Addr **, int, size_t) __noinline;
4691 tls_get_addr_slow(Elf_Addr **dtvp, int index, size_t offset)
4693 Elf_Addr *newdtv, *dtv;
4694 RtldLockState lockstate;
4698 /* Check dtv generation in case new modules have arrived */
4699 if (dtv[0] != tls_dtv_generation) {
4700 wlock_acquire(rtld_bind_lock, &lockstate);
4701 newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4703 if (to_copy > tls_max_index)
4704 to_copy = tls_max_index;
4705 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
4706 newdtv[0] = tls_dtv_generation;
4707 newdtv[1] = tls_max_index;
4709 lock_release(rtld_bind_lock, &lockstate);
4710 dtv = *dtvp = newdtv;
4713 /* Dynamically allocate module TLS if necessary */
4714 if (dtv[index + 1] == 0) {
4715 /* Signal safe, wlock will block out signals. */
4716 wlock_acquire(rtld_bind_lock, &lockstate);
4717 if (!dtv[index + 1])
4718 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
4719 lock_release(rtld_bind_lock, &lockstate);
4721 return ((void *)(dtv[index + 1] + offset));
4725 tls_get_addr_common(Elf_Addr **dtvp, int index, size_t offset)
4730 /* Check dtv generation in case new modules have arrived */
4731 if (__predict_true(dtv[0] == tls_dtv_generation &&
4732 dtv[index + 1] != 0))
4733 return ((void *)(dtv[index + 1] + offset));
4734 return (tls_get_addr_slow(dtvp, index, offset));
4737 #if defined(__aarch64__) || defined(__arm__) || defined(__mips__) || \
4738 defined(__powerpc__) || defined(__riscv__)
4741 * Allocate Static TLS using the Variant I method.
4744 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
4753 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
4756 assert(tcbsize >= TLS_TCB_SIZE);
4757 tcb = xcalloc(1, tls_static_space - TLS_TCB_SIZE + tcbsize);
4758 tls = (Elf_Addr **)(tcb + tcbsize - TLS_TCB_SIZE);
4760 if (oldtcb != NULL) {
4761 memcpy(tls, oldtcb, tls_static_space);
4764 /* Adjust the DTV. */
4766 for (i = 0; i < dtv[1]; i++) {
4767 if (dtv[i+2] >= (Elf_Addr)oldtcb &&
4768 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
4769 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tls;
4773 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4775 dtv[0] = tls_dtv_generation;
4776 dtv[1] = tls_max_index;
4778 for (obj = globallist_curr(objs); obj != NULL;
4779 obj = globallist_next(obj)) {
4780 if (obj->tlsoffset > 0) {
4781 addr = (Elf_Addr)tls + obj->tlsoffset;
4782 if (obj->tlsinitsize > 0)
4783 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4784 if (obj->tlssize > obj->tlsinitsize)
4785 memset((void*) (addr + obj->tlsinitsize), 0,
4786 obj->tlssize - obj->tlsinitsize);
4787 dtv[obj->tlsindex + 1] = addr;
4796 free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
4799 Elf_Addr tlsstart, tlsend;
4802 assert(tcbsize >= TLS_TCB_SIZE);
4804 tlsstart = (Elf_Addr)tcb + tcbsize - TLS_TCB_SIZE;
4805 tlsend = tlsstart + tls_static_space;
4807 dtv = *(Elf_Addr **)tlsstart;
4809 for (i = 0; i < dtvsize; i++) {
4810 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
4811 free((void*)dtv[i+2]);
4820 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__)
4823 * Allocate Static TLS using the Variant II method.
4826 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
4829 size_t size, ralign;
4831 Elf_Addr *dtv, *olddtv;
4832 Elf_Addr segbase, oldsegbase, addr;
4836 if (tls_static_max_align > ralign)
4837 ralign = tls_static_max_align;
4838 size = round(tls_static_space, ralign) + round(tcbsize, ralign);
4840 assert(tcbsize >= 2*sizeof(Elf_Addr));
4841 tls = malloc_aligned(size, ralign);
4842 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4844 segbase = (Elf_Addr)(tls + round(tls_static_space, ralign));
4845 ((Elf_Addr*)segbase)[0] = segbase;
4846 ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
4848 dtv[0] = tls_dtv_generation;
4849 dtv[1] = tls_max_index;
4853 * Copy the static TLS block over whole.
4855 oldsegbase = (Elf_Addr) oldtls;
4856 memcpy((void *)(segbase - tls_static_space),
4857 (const void *)(oldsegbase - tls_static_space),
4861 * If any dynamic TLS blocks have been created tls_get_addr(),
4864 olddtv = ((Elf_Addr**)oldsegbase)[1];
4865 for (i = 0; i < olddtv[1]; i++) {
4866 if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
4867 dtv[i+2] = olddtv[i+2];
4873 * We assume that this block was the one we created with
4874 * allocate_initial_tls().
4876 free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
4878 for (obj = objs; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
4879 if (obj->marker || obj->tlsoffset == 0)
4881 addr = segbase - obj->tlsoffset;
4882 memset((void*) (addr + obj->tlsinitsize),
4883 0, obj->tlssize - obj->tlsinitsize);
4885 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4886 obj->static_tls_copied = true;
4888 dtv[obj->tlsindex + 1] = addr;
4892 return (void*) segbase;
4896 free_tls(void *tls, size_t tcbsize, size_t tcbalign)
4899 size_t size, ralign;
4901 Elf_Addr tlsstart, tlsend;
4904 * Figure out the size of the initial TLS block so that we can
4905 * find stuff which ___tls_get_addr() allocated dynamically.
4908 if (tls_static_max_align > ralign)
4909 ralign = tls_static_max_align;
4910 size = round(tls_static_space, ralign);
4912 dtv = ((Elf_Addr**)tls)[1];
4914 tlsend = (Elf_Addr) tls;
4915 tlsstart = tlsend - size;
4916 for (i = 0; i < dtvsize; i++) {
4917 if (dtv[i + 2] != 0 && (dtv[i + 2] < tlsstart || dtv[i + 2] > tlsend)) {
4918 free_aligned((void *)dtv[i + 2]);
4922 free_aligned((void *)tlsstart);
4929 * Allocate TLS block for module with given index.
4932 allocate_module_tls(int index)
4937 TAILQ_FOREACH(obj, &obj_list, next) {
4940 if (obj->tlsindex == index)
4944 _rtld_error("Can't find module with TLS index %d", index);
4948 p = malloc_aligned(obj->tlssize, obj->tlsalign);
4949 memcpy(p, obj->tlsinit, obj->tlsinitsize);
4950 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
4956 allocate_tls_offset(Obj_Entry *obj)
4963 if (obj->tlssize == 0) {
4964 obj->tls_done = true;
4968 if (tls_last_offset == 0)
4969 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
4971 off = calculate_tls_offset(tls_last_offset, tls_last_size,
4972 obj->tlssize, obj->tlsalign);
4975 * If we have already fixed the size of the static TLS block, we
4976 * must stay within that size. When allocating the static TLS, we
4977 * leave a small amount of space spare to be used for dynamically
4978 * loading modules which use static TLS.
4980 if (tls_static_space != 0) {
4981 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
4983 } else if (obj->tlsalign > tls_static_max_align) {
4984 tls_static_max_align = obj->tlsalign;
4987 tls_last_offset = obj->tlsoffset = off;
4988 tls_last_size = obj->tlssize;
4989 obj->tls_done = true;
4995 free_tls_offset(Obj_Entry *obj)
4999 * If we were the last thing to allocate out of the static TLS
5000 * block, we give our space back to the 'allocator'. This is a
5001 * simplistic workaround to allow libGL.so.1 to be loaded and
5002 * unloaded multiple times.
5004 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
5005 == calculate_tls_end(tls_last_offset, tls_last_size)) {
5006 tls_last_offset -= obj->tlssize;
5012 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
5015 RtldLockState lockstate;
5017 wlock_acquire(rtld_bind_lock, &lockstate);
5018 ret = allocate_tls(globallist_curr(TAILQ_FIRST(&obj_list)), oldtls,
5020 lock_release(rtld_bind_lock, &lockstate);
5025 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
5027 RtldLockState lockstate;
5029 wlock_acquire(rtld_bind_lock, &lockstate);
5030 free_tls(tcb, tcbsize, tcbalign);
5031 lock_release(rtld_bind_lock, &lockstate);
5035 object_add_name(Obj_Entry *obj, const char *name)
5041 entry = malloc(sizeof(Name_Entry) + len);
5043 if (entry != NULL) {
5044 strcpy(entry->name, name);
5045 STAILQ_INSERT_TAIL(&obj->names, entry, link);
5050 object_match_name(const Obj_Entry *obj, const char *name)
5054 STAILQ_FOREACH(entry, &obj->names, link) {
5055 if (strcmp(name, entry->name) == 0)
5062 locate_dependency(const Obj_Entry *obj, const char *name)
5064 const Objlist_Entry *entry;
5065 const Needed_Entry *needed;
5067 STAILQ_FOREACH(entry, &list_main, link) {
5068 if (object_match_name(entry->obj, name))
5072 for (needed = obj->needed; needed != NULL; needed = needed->next) {
5073 if (strcmp(obj->strtab + needed->name, name) == 0 ||
5074 (needed->obj != NULL && object_match_name(needed->obj, name))) {
5076 * If there is DT_NEEDED for the name we are looking for,
5077 * we are all set. Note that object might not be found if
5078 * dependency was not loaded yet, so the function can
5079 * return NULL here. This is expected and handled
5080 * properly by the caller.
5082 return (needed->obj);
5085 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
5091 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
5092 const Elf_Vernaux *vna)
5094 const Elf_Verdef *vd;
5095 const char *vername;
5097 vername = refobj->strtab + vna->vna_name;
5098 vd = depobj->verdef;
5100 _rtld_error("%s: version %s required by %s not defined",
5101 depobj->path, vername, refobj->path);
5105 if (vd->vd_version != VER_DEF_CURRENT) {
5106 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
5107 depobj->path, vd->vd_version);
5110 if (vna->vna_hash == vd->vd_hash) {
5111 const Elf_Verdaux *aux = (const Elf_Verdaux *)
5112 ((char *)vd + vd->vd_aux);
5113 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
5116 if (vd->vd_next == 0)
5118 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
5120 if (vna->vna_flags & VER_FLG_WEAK)
5122 _rtld_error("%s: version %s required by %s not found",
5123 depobj->path, vername, refobj->path);
5128 rtld_verify_object_versions(Obj_Entry *obj)
5130 const Elf_Verneed *vn;
5131 const Elf_Verdef *vd;
5132 const Elf_Verdaux *vda;
5133 const Elf_Vernaux *vna;
5134 const Obj_Entry *depobj;
5135 int maxvernum, vernum;
5137 if (obj->ver_checked)
5139 obj->ver_checked = true;
5143 * Walk over defined and required version records and figure out
5144 * max index used by any of them. Do very basic sanity checking
5148 while (vn != NULL) {
5149 if (vn->vn_version != VER_NEED_CURRENT) {
5150 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
5151 obj->path, vn->vn_version);
5154 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
5156 vernum = VER_NEED_IDX(vna->vna_other);
5157 if (vernum > maxvernum)
5159 if (vna->vna_next == 0)
5161 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
5163 if (vn->vn_next == 0)
5165 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
5169 while (vd != NULL) {
5170 if (vd->vd_version != VER_DEF_CURRENT) {
5171 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
5172 obj->path, vd->vd_version);
5175 vernum = VER_DEF_IDX(vd->vd_ndx);
5176 if (vernum > maxvernum)
5178 if (vd->vd_next == 0)
5180 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
5187 * Store version information in array indexable by version index.
5188 * Verify that object version requirements are satisfied along the
5191 obj->vernum = maxvernum + 1;
5192 obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry));
5195 while (vd != NULL) {
5196 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
5197 vernum = VER_DEF_IDX(vd->vd_ndx);
5198 assert(vernum <= maxvernum);
5199 vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
5200 obj->vertab[vernum].hash = vd->vd_hash;
5201 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
5202 obj->vertab[vernum].file = NULL;
5203 obj->vertab[vernum].flags = 0;
5205 if (vd->vd_next == 0)
5207 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
5211 while (vn != NULL) {
5212 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
5215 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
5217 if (check_object_provided_version(obj, depobj, vna))
5219 vernum = VER_NEED_IDX(vna->vna_other);
5220 assert(vernum <= maxvernum);
5221 obj->vertab[vernum].hash = vna->vna_hash;
5222 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
5223 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
5224 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
5225 VER_INFO_HIDDEN : 0;
5226 if (vna->vna_next == 0)
5228 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
5230 if (vn->vn_next == 0)
5232 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
5238 rtld_verify_versions(const Objlist *objlist)
5240 Objlist_Entry *entry;
5244 STAILQ_FOREACH(entry, objlist, link) {
5246 * Skip dummy objects or objects that have their version requirements
5249 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
5251 if (rtld_verify_object_versions(entry->obj) == -1) {
5253 if (ld_tracing == NULL)
5257 if (rc == 0 || ld_tracing != NULL)
5258 rc = rtld_verify_object_versions(&obj_rtld);
5263 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
5268 vernum = VER_NDX(obj->versyms[symnum]);
5269 if (vernum >= obj->vernum) {
5270 _rtld_error("%s: symbol %s has wrong verneed value %d",
5271 obj->path, obj->strtab + symnum, vernum);
5272 } else if (obj->vertab[vernum].hash != 0) {
5273 return &obj->vertab[vernum];
5280 _rtld_get_stack_prot(void)
5283 return (stack_prot);
5287 _rtld_is_dlopened(void *arg)
5290 RtldLockState lockstate;
5293 rlock_acquire(rtld_bind_lock, &lockstate);
5296 obj = obj_from_addr(arg);
5298 _rtld_error("No shared object contains address");
5299 lock_release(rtld_bind_lock, &lockstate);
5302 res = obj->dlopened ? 1 : 0;
5303 lock_release(rtld_bind_lock, &lockstate);
5308 obj_remap_relro(Obj_Entry *obj, int prot)
5311 if (obj->relro_size > 0 && mprotect(obj->relro_page, obj->relro_size,
5313 _rtld_error("%s: Cannot set relro protection to %#x: %s",
5314 obj->path, prot, rtld_strerror(errno));
5321 obj_disable_relro(Obj_Entry *obj)
5324 return (obj_remap_relro(obj, PROT_READ | PROT_WRITE));
5328 obj_enforce_relro(Obj_Entry *obj)
5331 return (obj_remap_relro(obj, PROT_READ));
5335 map_stacks_exec(RtldLockState *lockstate)
5337 void (*thr_map_stacks_exec)(void);
5339 if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
5341 thr_map_stacks_exec = (void (*)(void))(uintptr_t)
5342 get_program_var_addr("__pthread_map_stacks_exec", lockstate);
5343 if (thr_map_stacks_exec != NULL) {
5344 stack_prot |= PROT_EXEC;
5345 thr_map_stacks_exec();
5350 distribute_static_tls(Objlist *list, RtldLockState *lockstate)
5354 void (*distrib)(size_t, void *, size_t, size_t);
5356 distrib = (void (*)(size_t, void *, size_t, size_t))(uintptr_t)
5357 get_program_var_addr("__pthread_distribute_static_tls", lockstate);
5358 if (distrib == NULL)
5360 STAILQ_FOREACH(elm, list, link) {
5362 if (obj->marker || !obj->tls_done || obj->static_tls_copied)
5364 distrib(obj->tlsoffset, obj->tlsinit, obj->tlsinitsize,
5366 obj->static_tls_copied = true;
5371 symlook_init(SymLook *dst, const char *name)
5374 bzero(dst, sizeof(*dst));
5376 dst->hash = elf_hash(name);
5377 dst->hash_gnu = gnu_hash(name);
5381 symlook_init_from_req(SymLook *dst, const SymLook *src)
5384 dst->name = src->name;
5385 dst->hash = src->hash;
5386 dst->hash_gnu = src->hash_gnu;
5387 dst->ventry = src->ventry;
5388 dst->flags = src->flags;
5389 dst->defobj_out = NULL;
5390 dst->sym_out = NULL;
5391 dst->lockstate = src->lockstate;
5395 open_binary_fd(const char *argv0, bool search_in_path)
5397 char *pathenv, *pe, binpath[PATH_MAX];
5400 if (search_in_path && strchr(argv0, '/') == NULL) {
5401 pathenv = getenv("PATH");
5402 if (pathenv == NULL) {
5403 rtld_printf("-p and no PATH environment variable\n");
5406 pathenv = strdup(pathenv);
5407 if (pathenv == NULL) {
5408 rtld_printf("Cannot allocate memory\n");
5413 while ((pe = strsep(&pathenv, ":")) != NULL) {
5414 if (strlcpy(binpath, pe, sizeof(binpath)) >=
5417 if (binpath[0] != '\0' &&
5418 strlcat(binpath, "/", sizeof(binpath)) >=
5421 if (strlcat(binpath, argv0, sizeof(binpath)) >=
5424 fd = open(binpath, O_RDONLY | O_CLOEXEC | O_VERIFY);
5425 if (fd != -1 || errno != ENOENT)
5430 fd = open(argv0, O_RDONLY | O_CLOEXEC | O_VERIFY);
5434 rtld_printf("Opening %s: %s\n", argv0,
5435 rtld_strerror(errno));
5442 * Parse a set of command-line arguments.
5445 parse_args(char* argv[], int argc, bool *use_pathp, int *fdp)
5448 int fd, i, j, arglen;
5451 dbg("Parsing command-line arguments");
5455 for (i = 1; i < argc; i++ ) {
5457 dbg("argv[%d]: '%s'", i, arg);
5460 * rtld arguments end with an explicit "--" or with the first
5461 * non-prefixed argument.
5463 if (strcmp(arg, "--") == 0) {
5471 * All other arguments are single-character options that can
5472 * be combined, so we need to search through `arg` for them.
5474 arglen = strlen(arg);
5475 for (j = 1; j < arglen; j++) {
5478 print_usage(argv[0]);
5480 } else if (opt == 'f') {
5482 * -f XX can be used to specify a descriptor for the
5483 * binary named at the command line (i.e., the later
5484 * argument will specify the process name but the
5485 * descriptor is what will actually be executed)
5487 if (j != arglen - 1) {
5488 /* -f must be the last option in, e.g., -abcf */
5489 _rtld_error("invalid options: %s", arg);
5493 fd = parse_integer(argv[i]);
5495 _rtld_error("invalid file descriptor: '%s'",
5501 } else if (opt == 'p') {
5504 rtld_printf("invalid argument: '%s'\n", arg);
5505 print_usage(argv[0]);
5515 * Parse a file descriptor number without pulling in more of libc (e.g. atoi).
5518 parse_integer(const char *str)
5520 static const int RADIX = 10; /* XXXJA: possibly support hex? */
5527 for (c = *str; c != '\0'; c = *++str) {
5528 if (c < '0' || c > '9')
5535 /* Make sure we actually parsed something. */
5542 print_usage(const char *argv0)
5545 rtld_printf("Usage: %s [-h] [-f <FD>] [--] <binary> [<args>]\n"
5548 " -h Display this help message\n"
5549 " -p Search in PATH for named binary\n"
5550 " -f <FD> Execute <FD> instead of searching for <binary>\n"
5551 " -- End of RTLD options\n"
5552 " <binary> Name of process to execute\n"
5553 " <args> Arguments to the executed process\n", argv0);
5557 * Overrides for libc_pic-provided functions.
5561 __getosreldate(void)
5571 oid[1] = KERN_OSRELDATE;
5573 len = sizeof(osrel);
5574 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
5575 if (error == 0 && osrel > 0 && len == sizeof(osrel))
5587 void (*__cleanup)(void);
5588 int __isthreaded = 0;
5589 int _thread_autoinit_dummy_decl = 1;
5592 * No unresolved symbols for rtld.
5595 __pthread_cxa_finalize(struct dl_phdr_info *a)
5600 __stack_chk_fail(void)
5603 _rtld_error("stack overflow detected; terminated");
5606 __weak_reference(__stack_chk_fail, __stack_chk_fail_local);
5612 _rtld_error("buffer overflow detected; terminated");
5617 rtld_strerror(int errnum)
5620 if (errnum < 0 || errnum >= sys_nerr)
5621 return ("Unknown error");
5622 return (sys_errlist[errnum]);
5626 * No ifunc relocations.
5629 memset(void *dest, int c, size_t len)
5633 for (i = 0; i < len; i++)
5634 ((char *)dest)[i] = c;
5639 bzero(void *dest, size_t len)
5643 for (i = 0; i < len; i++)
5644 ((char *)dest)[i] = 0;