2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright 1996, 1997, 1998, 1999, 2000 John D. Polstra.
5 * Copyright 2003 Alexander Kabaev <kan@FreeBSD.ORG>.
6 * Copyright 2009-2013 Konstantin Belousov <kib@FreeBSD.ORG>.
7 * Copyright 2012 John Marino <draco@marino.st>.
8 * Copyright 2014-2017 The FreeBSD Foundation
11 * Portions of this software were developed by Konstantin Belousov
12 * under sponsorship from the FreeBSD Foundation.
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
17 * 1. Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 * Dynamic linker for ELF.
38 * John Polstra <jdp@polstra.com>.
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
44 #include <sys/param.h>
45 #include <sys/mount.h>
48 #include <sys/sysctl.h>
50 #include <sys/utsname.h>
51 #include <sys/ktrace.h>
66 #include "rtld_paths.h"
68 #include "rtld_printf.h"
69 #include "rtld_malloc.h"
70 #include "rtld_utrace.h"
72 #include "rtld_libc.h"
75 typedef void (*func_ptr_type)(void);
76 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg);
79 /* Variables that cannot be static: */
80 extern struct r_debug r_debug; /* For GDB */
81 extern int _thread_autoinit_dummy_decl;
82 extern void (*__cleanup)(void);
90 * Function declarations.
92 static const char *basename(const char *);
93 static void digest_dynamic1(Obj_Entry *, int, const Elf_Dyn **,
94 const Elf_Dyn **, const Elf_Dyn **);
95 static bool digest_dynamic2(Obj_Entry *, const Elf_Dyn *, const Elf_Dyn *,
97 static bool digest_dynamic(Obj_Entry *, int);
98 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
99 static void distribute_static_tls(Objlist *, RtldLockState *);
100 static Obj_Entry *dlcheck(void *);
101 static int dlclose_locked(void *, RtldLockState *);
102 static Obj_Entry *dlopen_object(const char *name, int fd, Obj_Entry *refobj,
103 int lo_flags, int mode, RtldLockState *lockstate);
104 static Obj_Entry *do_load_object(int, const char *, char *, struct stat *, int);
105 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
106 static bool donelist_check(DoneList *, const Obj_Entry *);
107 static void dump_auxv(Elf_Auxinfo **aux_info);
108 static void errmsg_restore(struct dlerror_save *);
109 static struct dlerror_save *errmsg_save(void);
110 static void *fill_search_info(const char *, size_t, void *);
111 static char *find_library(const char *, const Obj_Entry *, int *);
112 static const char *gethints(bool);
113 static void hold_object(Obj_Entry *);
114 static void unhold_object(Obj_Entry *);
115 static void init_dag(Obj_Entry *);
116 static void init_marker(Obj_Entry *);
117 static void init_pagesizes(Elf_Auxinfo **aux_info);
118 static void init_rtld(caddr_t, Elf_Auxinfo **);
119 static void initlist_add_neededs(Needed_Entry *, Objlist *);
120 static void initlist_add_objects(Obj_Entry *, Obj_Entry *, Objlist *);
121 static int initlist_objects_ifunc(Objlist *, bool, int, RtldLockState *);
122 static void linkmap_add(Obj_Entry *);
123 static void linkmap_delete(Obj_Entry *);
124 static void load_filtees(Obj_Entry *, int flags, RtldLockState *);
125 static void unload_filtees(Obj_Entry *, RtldLockState *);
126 static int load_needed_objects(Obj_Entry *, int);
127 static int load_preload_objects(const char *, bool);
128 static int load_kpreload(const void *addr);
129 static Obj_Entry *load_object(const char *, int fd, const Obj_Entry *, int);
130 static void map_stacks_exec(RtldLockState *);
131 static int obj_disable_relro(Obj_Entry *);
132 static int obj_enforce_relro(Obj_Entry *);
133 static void objlist_call_fini(Objlist *, Obj_Entry *, RtldLockState *);
134 static void objlist_call_init(Objlist *, RtldLockState *);
135 static void objlist_clear(Objlist *);
136 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
137 static void objlist_init(Objlist *);
138 static void objlist_push_head(Objlist *, Obj_Entry *);
139 static void objlist_push_tail(Objlist *, Obj_Entry *);
140 static void objlist_put_after(Objlist *, Obj_Entry *, Obj_Entry *);
141 static void objlist_remove(Objlist *, Obj_Entry *);
142 static int open_binary_fd(const char *argv0, bool search_in_path,
143 const char **binpath_res);
144 static int parse_args(char* argv[], int argc, bool *use_pathp, int *fdp,
145 const char **argv0, bool *dir_ignore);
146 static int parse_integer(const char *);
147 static void *path_enumerate(const char *, path_enum_proc, const char *, void *);
148 static void print_usage(const char *argv0);
149 static void release_object(Obj_Entry *);
150 static int relocate_object_dag(Obj_Entry *root, bool bind_now,
151 Obj_Entry *rtldobj, int flags, RtldLockState *lockstate);
152 static int relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
153 int flags, RtldLockState *lockstate);
154 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, int,
156 static int resolve_object_ifunc(Obj_Entry *, bool, int, RtldLockState *);
157 static int rtld_dirname(const char *, char *);
158 static int rtld_dirname_abs(const char *, char *);
159 static void *rtld_dlopen(const char *name, int fd, int mode);
160 static void rtld_exit(void);
161 static void rtld_nop_exit(void);
162 static char *search_library_path(const char *, const char *, const char *,
164 static char *search_library_pathfds(const char *, const char *, int *);
165 static const void **get_program_var_addr(const char *, RtldLockState *);
166 static void set_program_var(const char *, const void *);
167 static int symlook_default(SymLook *, const Obj_Entry *refobj);
168 static int symlook_global(SymLook *, DoneList *);
169 static void symlook_init_from_req(SymLook *, const SymLook *);
170 static int symlook_list(SymLook *, const Objlist *, DoneList *);
171 static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *);
172 static int symlook_obj1_sysv(SymLook *, const Obj_Entry *);
173 static int symlook_obj1_gnu(SymLook *, const Obj_Entry *);
174 static void *tls_get_addr_slow(Elf_Addr **, int, size_t, bool) __noinline;
175 static void trace_loaded_objects(Obj_Entry *, bool);
176 static void unlink_object(Obj_Entry *);
177 static void unload_object(Obj_Entry *, RtldLockState *lockstate);
178 static void unref_dag(Obj_Entry *);
179 static void ref_dag(Obj_Entry *);
180 static char *origin_subst_one(Obj_Entry *, char *, const char *,
182 static char *origin_subst(Obj_Entry *, const char *);
183 static bool obj_resolve_origin(Obj_Entry *obj);
184 static void preinit_main(void);
185 static int rtld_verify_versions(const Objlist *);
186 static int rtld_verify_object_versions(Obj_Entry *);
187 static void object_add_name(Obj_Entry *, const char *);
188 static int object_match_name(const Obj_Entry *, const char *);
189 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
190 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
191 struct dl_phdr_info *phdr_info);
192 static uint32_t gnu_hash(const char *);
193 static bool matched_symbol(SymLook *, const Obj_Entry *, Sym_Match_Result *,
194 const unsigned long);
196 void r_debug_state(struct r_debug *, struct link_map *) __noinline __exported;
197 void _r_debug_postinit(struct link_map *) __noinline __exported;
199 int __sys_openat(int, const char *, int, ...);
204 struct r_debug r_debug __exported; /* for GDB; */
205 static bool libmap_disable; /* Disable libmap */
206 static bool ld_loadfltr; /* Immediate filters processing */
207 static const char *libmap_override;/* Maps to use in addition to libmap.conf */
208 static bool trust; /* False for setuid and setgid programs */
209 static bool dangerous_ld_env; /* True if environment variables have been
210 used to affect the libraries loaded */
211 bool ld_bind_not; /* Disable PLT update */
212 static const char *ld_bind_now; /* Environment variable for immediate binding */
213 static const char *ld_debug; /* Environment variable for debugging */
214 static bool ld_dynamic_weak = true; /* True if non-weak definition overrides
216 static const char *ld_library_path;/* Environment variable for search path */
217 static const char *ld_library_dirs;/* Environment variable for library descriptors */
218 static const char *ld_preload; /* Environment variable for libraries to
220 static const char *ld_preload_fds;/* Environment variable for libraries represented by
222 static const char *ld_elf_hints_path; /* Environment variable for alternative hints path */
223 static const char *ld_tracing; /* Called from ldd to print libs */
224 static const char *ld_utrace; /* Use utrace() to log events. */
225 static struct obj_entry_q obj_list; /* Queue of all loaded objects */
226 static Obj_Entry *obj_main; /* The main program shared object */
227 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
228 static unsigned int obj_count; /* Number of objects in obj_list */
229 static unsigned int obj_loads; /* Number of loads of objects (gen count) */
231 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
232 STAILQ_HEAD_INITIALIZER(list_global);
233 static Objlist list_main = /* Objects loaded at program startup */
234 STAILQ_HEAD_INITIALIZER(list_main);
235 static Objlist list_fini = /* Objects needing fini() calls */
236 STAILQ_HEAD_INITIALIZER(list_fini);
238 Elf_Sym sym_zero; /* For resolving undefined weak refs. */
240 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
242 extern Elf_Dyn _DYNAMIC;
243 #pragma weak _DYNAMIC
245 int dlclose(void *) __exported;
246 char *dlerror(void) __exported;
247 void *dlopen(const char *, int) __exported;
248 void *fdlopen(int, int) __exported;
249 void *dlsym(void *, const char *) __exported;
250 dlfunc_t dlfunc(void *, const char *) __exported;
251 void *dlvsym(void *, const char *, const char *) __exported;
252 int dladdr(const void *, Dl_info *) __exported;
253 void dllockinit(void *, void *(*)(void *), void (*)(void *), void (*)(void *),
254 void (*)(void *), void (*)(void *), void (*)(void *)) __exported;
255 int dlinfo(void *, int , void *) __exported;
256 int dl_iterate_phdr(__dl_iterate_hdr_callback, void *) __exported;
257 int _rtld_addr_phdr(const void *, struct dl_phdr_info *) __exported;
258 int _rtld_get_stack_prot(void) __exported;
259 int _rtld_is_dlopened(void *) __exported;
260 void _rtld_error(const char *, ...) __exported;
262 /* Only here to fix -Wmissing-prototypes warnings */
263 int __getosreldate(void);
264 func_ptr_type _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp);
265 Elf_Addr _rtld_bind(Obj_Entry *obj, Elf_Size reloff);
269 static int osreldate;
273 static int stack_prot = PROT_READ | PROT_WRITE | RTLD_DEFAULT_STACK_EXEC;
274 static int max_stack_flags;
277 * Global declarations normally provided by crt1. The dynamic linker is
278 * not built with crt1, so we have to provide them ourselves.
284 * Used to pass argc, argv to init functions.
290 * Globals to control TLS allocation.
292 size_t tls_last_offset; /* Static TLS offset of last module */
293 size_t tls_last_size; /* Static TLS size of last module */
294 size_t tls_static_space; /* Static TLS space allocated */
295 static size_t tls_static_max_align;
296 Elf_Addr tls_dtv_generation = 1; /* Used to detect when dtv size changes */
297 int tls_max_index = 1; /* Largest module index allocated */
299 static bool ld_library_path_rpath = false;
300 bool ld_fast_sigblock = false;
303 * Globals for path names, and such
305 const char *ld_elf_hints_default = _PATH_ELF_HINTS;
306 const char *ld_path_libmap_conf = _PATH_LIBMAP_CONF;
307 const char *ld_path_rtld = _PATH_RTLD;
308 const char *ld_standard_library_path = STANDARD_LIBRARY_PATH;
309 const char *ld_env_prefix = LD_;
311 static void (*rtld_exit_ptr)(void);
314 * Fill in a DoneList with an allocation large enough to hold all of
315 * the currently-loaded objects. Keep this as a macro since it calls
316 * alloca and we want that to occur within the scope of the caller.
318 #define donelist_init(dlp) \
319 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
320 assert((dlp)->objs != NULL), \
321 (dlp)->num_alloc = obj_count, \
324 #define LD_UTRACE(e, h, mb, ms, r, n) do { \
325 if (ld_utrace != NULL) \
326 ld_utrace_log(e, h, mb, ms, r, n); \
330 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
331 int refcnt, const char *name)
333 struct utrace_rtld ut;
334 static const char rtld_utrace_sig[RTLD_UTRACE_SIG_SZ] = RTLD_UTRACE_SIG;
336 memcpy(ut.sig, rtld_utrace_sig, sizeof(ut.sig));
339 ut.mapbase = mapbase;
340 ut.mapsize = mapsize;
342 bzero(ut.name, sizeof(ut.name));
344 strlcpy(ut.name, name, sizeof(ut.name));
345 utrace(&ut, sizeof(ut));
359 LD_LIBRARY_PATH_RPATH,
362 LD_TRACE_LOADED_OBJECTS,
366 LD_TRACE_LOADED_OBJECTS_PROGNAME,
367 LD_TRACE_LOADED_OBJECTS_FMT1,
368 LD_TRACE_LOADED_OBJECTS_FMT2,
369 LD_TRACE_LOADED_OBJECTS_ALL,
373 struct ld_env_var_desc {
374 const char * const n;
378 #define LD_ENV_DESC(var, unsec) \
379 [LD_##var] = { .n = #var, .unsecure = unsec }
381 static struct ld_env_var_desc ld_env_vars[] = {
382 LD_ENV_DESC(BIND_NOW, false),
383 LD_ENV_DESC(PRELOAD, true),
384 LD_ENV_DESC(LIBMAP, true),
385 LD_ENV_DESC(LIBRARY_PATH, true),
386 LD_ENV_DESC(LIBRARY_PATH_FDS, true),
387 LD_ENV_DESC(LIBMAP_DISABLE, true),
388 LD_ENV_DESC(BIND_NOT, true),
389 LD_ENV_DESC(DEBUG, true),
390 LD_ENV_DESC(ELF_HINTS_PATH, true),
391 LD_ENV_DESC(LOADFLTR, true),
392 LD_ENV_DESC(LIBRARY_PATH_RPATH, true),
393 LD_ENV_DESC(PRELOAD_FDS, true),
394 LD_ENV_DESC(DYNAMIC_WEAK, true),
395 LD_ENV_DESC(TRACE_LOADED_OBJECTS, false),
396 LD_ENV_DESC(UTRACE, false),
397 LD_ENV_DESC(DUMP_REL_PRE, false),
398 LD_ENV_DESC(DUMP_REL_POST, false),
399 LD_ENV_DESC(TRACE_LOADED_OBJECTS_PROGNAME, false),
400 LD_ENV_DESC(TRACE_LOADED_OBJECTS_FMT1, false),
401 LD_ENV_DESC(TRACE_LOADED_OBJECTS_FMT2, false),
402 LD_ENV_DESC(TRACE_LOADED_OBJECTS_ALL, false),
403 LD_ENV_DESC(SHOW_AUXV, false),
407 ld_get_env_var(int idx)
409 return (ld_env_vars[idx].val);
413 rtld_get_env_val(char **env, const char *name, size_t name_len)
417 for (m = env; *m != NULL; m++) {
421 /* corrupt environment? */
424 if (v - n == (ptrdiff_t)name_len &&
425 strncmp(name, n, name_len) == 0)
432 rtld_init_env_vars_for_prefix(char **env, const char *env_prefix)
434 struct ld_env_var_desc *lvd;
435 size_t prefix_len, nlen;
439 prefix_len = strlen(env_prefix);
440 for (m = env; *m != NULL; m++) {
442 if (strncmp(env_prefix, n, prefix_len) != 0) {
443 /* Not a rtld environment variable. */
449 /* corrupt environment? */
452 for (i = 0; i < (int)nitems(ld_env_vars); i++) {
453 lvd = &ld_env_vars[i];
454 if (lvd->val != NULL) {
455 /* Saw higher-priority variable name already. */
458 nlen = strlen(lvd->n);
459 if (v - n == (ptrdiff_t)nlen &&
460 strncmp(lvd->n, n, nlen) == 0) {
469 rtld_init_env_vars(char **env)
471 rtld_init_env_vars_for_prefix(env, ld_env_prefix);
475 set_ld_elf_hints_path(void)
477 if (ld_elf_hints_path == NULL || strlen(ld_elf_hints_path) == 0)
478 ld_elf_hints_path = ld_elf_hints_default;
482 rtld_round_page(uintptr_t x)
484 return (roundup2(x, page_size));
488 rtld_trunc_page(uintptr_t x)
490 return (rounddown2(x, page_size));
494 * Main entry point for dynamic linking. The first argument is the
495 * stack pointer. The stack is expected to be laid out as described
496 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
497 * Specifically, the stack pointer points to a word containing
498 * ARGC. Following that in the stack is a null-terminated sequence
499 * of pointers to argument strings. Then comes a null-terminated
500 * sequence of pointers to environment strings. Finally, there is a
501 * sequence of "auxiliary vector" entries.
503 * The second argument points to a place to store the dynamic linker's
504 * exit procedure pointer and the third to a place to store the main
507 * The return value is the main program's entry point.
510 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
512 Elf_Auxinfo *aux, *auxp, *auxpf, *aux_info[AT_COUNT];
513 Objlist_Entry *entry;
514 Obj_Entry *last_interposer, *obj, *preload_tail;
515 const Elf_Phdr *phdr;
517 RtldLockState lockstate;
520 char **argv, **env, **envp, *kexecpath;
521 const char *argv0, *binpath, *library_path_rpath;
522 struct ld_env_var_desc *lvd;
524 char buf[MAXPATHLEN];
525 int argc, fd, i, mib[4], old_osrel, osrel, phnum, rtld_argc;
528 int old_auxv_format = 1;
530 bool dir_enable, dir_ignore, direct_exec, explicit_fd, search_in_path;
533 * On entry, the dynamic linker itself has not been relocated yet.
534 * Be very careful not to reference any global data until after
535 * init_rtld has returned. It is OK to reference file-scope statics
536 * and string constants, and to call static and global functions.
539 /* Find the auxiliary vector on the stack. */
543 sp += argc + 1; /* Skip over arguments and NULL terminator */
545 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
547 aux = (Elf_Auxinfo *) sp;
549 /* Digest the auxiliary vector. */
550 for (i = 0; i < AT_COUNT; i++)
552 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
553 if (auxp->a_type < AT_COUNT)
554 aux_info[auxp->a_type] = auxp;
556 if (auxp->a_type == 23) /* AT_STACKPROT */
562 if (old_auxv_format) {
563 /* Remap from old-style auxv numbers. */
564 aux_info[23] = aux_info[21]; /* AT_STACKPROT */
565 aux_info[21] = aux_info[19]; /* AT_PAGESIZESLEN */
566 aux_info[19] = aux_info[17]; /* AT_NCPUS */
567 aux_info[17] = aux_info[15]; /* AT_CANARYLEN */
568 aux_info[15] = aux_info[13]; /* AT_EXECPATH */
569 aux_info[13] = NULL; /* AT_GID */
571 aux_info[20] = aux_info[18]; /* AT_PAGESIZES */
572 aux_info[18] = aux_info[16]; /* AT_OSRELDATE */
573 aux_info[16] = aux_info[14]; /* AT_CANARY */
574 aux_info[14] = NULL; /* AT_EGID */
578 /* Initialize and relocate ourselves. */
579 assert(aux_info[AT_BASE] != NULL);
580 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
584 __progname = obj_rtld.path;
585 argv0 = argv[0] != NULL ? argv[0] : "(null)";
590 if (aux_info[AT_BSDFLAGS] != NULL &&
591 (aux_info[AT_BSDFLAGS]->a_un.a_val & ELF_BSDF_SIGFASTBLK) != 0)
592 ld_fast_sigblock = true;
594 trust = !issetugid();
597 md_abi_variant_hook(aux_info);
598 rtld_init_env_vars(env);
601 if (aux_info[AT_EXECFD] != NULL) {
602 fd = aux_info[AT_EXECFD]->a_un.a_val;
604 assert(aux_info[AT_PHDR] != NULL);
605 phdr = (const Elf_Phdr *)aux_info[AT_PHDR]->a_un.a_ptr;
606 if (phdr == obj_rtld.phdr) {
608 _rtld_error("Tainted process refusing to run binary %s",
614 dbg("opening main program in direct exec mode");
616 rtld_argc = parse_args(argv, argc, &search_in_path, &fd,
617 &argv0, &dir_ignore);
618 explicit_fd = (fd != -1);
621 fd = open_binary_fd(argv0, search_in_path, &binpath);
622 if (fstat(fd, &st) == -1) {
623 _rtld_error("Failed to fstat FD %d (%s): %s", fd,
624 explicit_fd ? "user-provided descriptor" : argv0,
625 rtld_strerror(errno));
630 * Rough emulation of the permission checks done by
631 * execve(2), only Unix DACs are checked, ACLs are
632 * ignored. Preserve the semantic of disabling owner
633 * to execute if owner x bit is cleared, even if
634 * others x bit is enabled.
635 * mmap(2) does not allow to mmap with PROT_EXEC if
636 * binary' file comes from noexec mount. We cannot
637 * set a text reference on the binary.
640 if (st.st_uid == geteuid()) {
641 if ((st.st_mode & S_IXUSR) != 0)
643 } else if (st.st_gid == getegid()) {
644 if ((st.st_mode & S_IXGRP) != 0)
646 } else if ((st.st_mode & S_IXOTH) != 0) {
649 if (!dir_enable && !dir_ignore) {
650 _rtld_error("No execute permission for binary %s",
656 * For direct exec mode, argv[0] is the interpreter
657 * name, we must remove it and shift arguments left
658 * before invoking binary main. Since stack layout
659 * places environment pointers and aux vectors right
660 * after the terminating NULL, we must shift
661 * environment and aux as well.
663 main_argc = argc - rtld_argc;
664 for (i = 0; i <= main_argc; i++)
665 argv[i] = argv[i + rtld_argc];
667 environ = env = envp = argv + main_argc + 1;
668 dbg("move env from %p to %p", envp + rtld_argc, envp);
670 *envp = *(envp + rtld_argc);
671 } while (*envp++ != NULL);
672 aux = auxp = (Elf_Auxinfo *)envp;
673 auxpf = (Elf_Auxinfo *)(envp + rtld_argc);
674 dbg("move aux from %p to %p", auxpf, aux);
675 /* XXXKIB insert place for AT_EXECPATH if not present */
676 for (;; auxp++, auxpf++) {
678 if (auxp->a_type == AT_NULL)
681 /* Since the auxiliary vector has moved, redigest it. */
682 for (i = 0; i < AT_COUNT; i++)
684 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
685 if (auxp->a_type < AT_COUNT)
686 aux_info[auxp->a_type] = auxp;
689 /* Point AT_EXECPATH auxv and aux_info to the binary path. */
690 if (binpath == NULL) {
691 aux_info[AT_EXECPATH] = NULL;
693 if (aux_info[AT_EXECPATH] == NULL) {
694 aux_info[AT_EXECPATH] = xmalloc(sizeof(Elf_Auxinfo));
695 aux_info[AT_EXECPATH]->a_type = AT_EXECPATH;
697 aux_info[AT_EXECPATH]->a_un.a_ptr = __DECONST(void *,
701 _rtld_error("No binary");
707 ld_bind_now = ld_get_env_var(LD_BIND_NOW);
710 * If the process is tainted, then we un-set the dangerous environment
711 * variables. The process will be marked as tainted until setuid(2)
712 * is called. If any child process calls setuid(2) we do not want any
713 * future processes to honor the potentially un-safe variables.
716 for (i = 0; i < (int)nitems(ld_env_vars); i++) {
717 lvd = &ld_env_vars[i];
723 ld_debug = ld_get_env_var(LD_DEBUG);
724 if (ld_bind_now == NULL)
725 ld_bind_not = ld_get_env_var(LD_BIND_NOT) != NULL;
726 ld_dynamic_weak = ld_get_env_var(LD_DYNAMIC_WEAK) == NULL;
727 libmap_disable = ld_get_env_var(LD_LIBMAP_DISABLE) != NULL;
728 libmap_override = ld_get_env_var(LD_LIBMAP);
729 ld_library_path = ld_get_env_var(LD_LIBRARY_PATH);
730 ld_library_dirs = ld_get_env_var(LD_LIBRARY_PATH_FDS);
731 ld_preload = ld_get_env_var(LD_PRELOAD);
732 ld_preload_fds = ld_get_env_var(LD_PRELOAD_FDS);
733 ld_elf_hints_path = ld_get_env_var(LD_ELF_HINTS_PATH);
734 ld_loadfltr = ld_get_env_var(LD_LOADFLTR) != NULL;
735 library_path_rpath = ld_get_env_var(LD_LIBRARY_PATH_RPATH);
736 if (library_path_rpath != NULL) {
737 if (library_path_rpath[0] == 'y' ||
738 library_path_rpath[0] == 'Y' ||
739 library_path_rpath[0] == '1')
740 ld_library_path_rpath = true;
742 ld_library_path_rpath = false;
744 dangerous_ld_env = libmap_disable || libmap_override != NULL ||
745 ld_library_path != NULL || ld_preload != NULL ||
746 ld_elf_hints_path != NULL || ld_loadfltr || !ld_dynamic_weak;
747 ld_tracing = ld_get_env_var(LD_TRACE_LOADED_OBJECTS);
748 ld_utrace = ld_get_env_var(LD_UTRACE);
750 set_ld_elf_hints_path();
751 if (ld_debug != NULL && *ld_debug != '\0')
753 dbg("%s is initialized, base address = %p", __progname,
754 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
755 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
756 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
758 dbg("initializing thread locks");
762 * Load the main program, or process its program header if it is
765 if (fd != -1) { /* Load the main program. */
766 dbg("loading main program");
767 obj_main = map_object(fd, argv0, NULL);
769 if (obj_main == NULL)
771 max_stack_flags = obj_main->stack_flags;
772 } else { /* Main program already loaded. */
773 dbg("processing main program's program header");
774 assert(aux_info[AT_PHDR] != NULL);
775 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
776 assert(aux_info[AT_PHNUM] != NULL);
777 phnum = aux_info[AT_PHNUM]->a_un.a_val;
778 assert(aux_info[AT_PHENT] != NULL);
779 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
780 assert(aux_info[AT_ENTRY] != NULL);
781 imgentry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
782 if ((obj_main = digest_phdr(phdr, phnum, imgentry, argv0)) == NULL)
786 if (aux_info[AT_EXECPATH] != NULL && fd == -1) {
787 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
788 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
789 if (kexecpath[0] == '/')
790 obj_main->path = kexecpath;
791 else if (getcwd(buf, sizeof(buf)) == NULL ||
792 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
793 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
794 obj_main->path = xstrdup(argv0);
796 obj_main->path = xstrdup(buf);
798 dbg("No AT_EXECPATH or direct exec");
799 obj_main->path = xstrdup(argv0);
801 dbg("obj_main path %s", obj_main->path);
802 obj_main->mainprog = true;
804 if (aux_info[AT_STACKPROT] != NULL &&
805 aux_info[AT_STACKPROT]->a_un.a_val != 0)
806 stack_prot = aux_info[AT_STACKPROT]->a_un.a_val;
810 * Get the actual dynamic linker pathname from the executable if
811 * possible. (It should always be possible.) That ensures that
812 * gdb will find the right dynamic linker even if a non-standard
815 if (obj_main->interp != NULL &&
816 strcmp(obj_main->interp, obj_rtld.path) != 0) {
818 obj_rtld.path = xstrdup(obj_main->interp);
819 __progname = obj_rtld.path;
823 if (!digest_dynamic(obj_main, 0))
825 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d",
826 obj_main->path, obj_main->valid_hash_sysv, obj_main->valid_hash_gnu,
827 obj_main->dynsymcount);
829 linkmap_add(obj_main);
830 linkmap_add(&obj_rtld);
832 /* Link the main program into the list of objects. */
833 TAILQ_INSERT_HEAD(&obj_list, obj_main, next);
837 /* Initialize a fake symbol for resolving undefined weak references. */
838 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
839 sym_zero.st_shndx = SHN_UNDEF;
840 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
843 libmap_disable = (bool)lm_init(libmap_override);
845 if (aux_info[AT_KPRELOAD] != NULL &&
846 aux_info[AT_KPRELOAD]->a_un.a_ptr != NULL) {
847 dbg("loading kernel vdso");
848 if (load_kpreload(aux_info[AT_KPRELOAD]->a_un.a_ptr) == -1)
852 dbg("loading LD_PRELOAD_FDS libraries");
853 if (load_preload_objects(ld_preload_fds, true) == -1)
856 dbg("loading LD_PRELOAD libraries");
857 if (load_preload_objects(ld_preload, false) == -1)
859 preload_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
861 dbg("loading needed objects");
862 if (load_needed_objects(obj_main, ld_tracing != NULL ? RTLD_LO_TRACE :
866 /* Make a list of all objects loaded at startup. */
867 last_interposer = obj_main;
868 TAILQ_FOREACH(obj, &obj_list, next) {
871 if (obj->z_interpose && obj != obj_main) {
872 objlist_put_after(&list_main, last_interposer, obj);
873 last_interposer = obj;
875 objlist_push_tail(&list_main, obj);
880 dbg("checking for required versions");
881 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
884 if (ld_get_env_var(LD_SHOW_AUXV) != NULL)
887 if (ld_tracing) { /* We're done */
888 trace_loaded_objects(obj_main, true);
892 if (ld_get_env_var(LD_DUMP_REL_PRE) != NULL) {
893 dump_relocations(obj_main);
898 * Processing tls relocations requires having the tls offsets
899 * initialized. Prepare offsets before starting initial
900 * relocation processing.
902 dbg("initializing initial thread local storage offsets");
903 STAILQ_FOREACH(entry, &list_main, link) {
905 * Allocate all the initial objects out of the static TLS
906 * block even if they didn't ask for it.
908 allocate_tls_offset(entry->obj);
911 if (relocate_objects(obj_main,
912 ld_bind_now != NULL && *ld_bind_now != '\0',
913 &obj_rtld, SYMLOOK_EARLY, NULL) == -1)
916 dbg("doing copy relocations");
917 if (do_copy_relocations(obj_main) == -1)
920 if (ld_get_env_var(LD_DUMP_REL_POST) != NULL) {
921 dump_relocations(obj_main);
928 * Setup TLS for main thread. This must be done after the
929 * relocations are processed, since tls initialization section
930 * might be the subject for relocations.
932 dbg("initializing initial thread local storage");
933 allocate_initial_tls(globallist_curr(TAILQ_FIRST(&obj_list)));
935 dbg("initializing key program variables");
936 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
937 set_program_var("environ", env);
938 set_program_var("__elf_aux_vector", aux);
940 /* Make a list of init functions to call. */
941 objlist_init(&initlist);
942 initlist_add_objects(globallist_curr(TAILQ_FIRST(&obj_list)),
943 preload_tail, &initlist);
945 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
947 map_stacks_exec(NULL);
949 if (!obj_main->crt_no_init) {
951 * Make sure we don't call the main program's init and fini
952 * functions for binaries linked with old crt1 which calls
955 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
956 obj_main->preinit_array = obj_main->init_array =
957 obj_main->fini_array = (Elf_Addr)NULL;
961 /* Set osrel for direct-execed binary */
964 mib[2] = KERN_PROC_OSREL;
966 osrel = obj_main->osrel;
967 sz = sizeof(old_osrel);
968 dbg("setting osrel to %d", osrel);
969 (void)sysctl(mib, 4, &old_osrel, &sz, &osrel, sizeof(osrel));
972 wlock_acquire(rtld_bind_lock, &lockstate);
974 dbg("resolving ifuncs");
975 if (initlist_objects_ifunc(&initlist, ld_bind_now != NULL &&
976 *ld_bind_now != '\0', SYMLOOK_EARLY, &lockstate) == -1)
979 rtld_exit_ptr = rtld_exit;
980 if (obj_main->crt_no_init)
982 objlist_call_init(&initlist, &lockstate);
983 _r_debug_postinit(&obj_main->linkmap);
984 objlist_clear(&initlist);
985 dbg("loading filtees");
986 TAILQ_FOREACH(obj, &obj_list, next) {
989 if (ld_loadfltr || obj->z_loadfltr)
990 load_filtees(obj, 0, &lockstate);
993 dbg("enforcing main obj relro");
994 if (obj_enforce_relro(obj_main) == -1)
997 lock_release(rtld_bind_lock, &lockstate);
999 dbg("transferring control to program entry point = %p", obj_main->entry);
1001 /* Return the exit procedure and the program entry point. */
1002 *exit_proc = rtld_exit_ptr;
1004 return ((func_ptr_type)obj_main->entry);
1008 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def)
1013 ptr = (void *)make_function_pointer(def, obj);
1014 target = call_ifunc_resolver(ptr);
1015 return ((void *)target);
1019 _rtld_bind(Obj_Entry *obj, Elf_Size reloff)
1023 const Obj_Entry *defobj;
1026 RtldLockState lockstate;
1028 rlock_acquire(rtld_bind_lock, &lockstate);
1029 if (sigsetjmp(lockstate.env, 0) != 0)
1030 lock_upgrade(rtld_bind_lock, &lockstate);
1032 rel = (const Elf_Rel *)((const char *)obj->pltrel + reloff);
1034 rel = (const Elf_Rel *)((const char *)obj->pltrela + reloff);
1036 where = (Elf_Addr *)(obj->relocbase + rel->r_offset);
1037 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, SYMLOOK_IN_PLT,
1041 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
1042 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
1044 target = (Elf_Addr)(defobj->relocbase + def->st_value);
1046 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
1047 defobj->strtab + def->st_name,
1048 obj->path == NULL ? NULL : basename(obj->path),
1050 defobj->path == NULL ? NULL : basename(defobj->path));
1053 * Write the new contents for the jmpslot. Note that depending on
1054 * architecture, the value which we need to return back to the
1055 * lazy binding trampoline may or may not be the target
1056 * address. The value returned from reloc_jmpslot() is the value
1057 * that the trampoline needs.
1059 target = reloc_jmpslot(where, target, defobj, obj, rel);
1060 lock_release(rtld_bind_lock, &lockstate);
1065 * Error reporting function. Use it like printf. If formats the message
1066 * into a buffer, and sets things up so that the next call to dlerror()
1067 * will return the message.
1070 _rtld_error(const char *fmt, ...)
1075 rtld_vsnprintf(lockinfo.dlerror_loc(), lockinfo.dlerror_loc_sz,
1078 *lockinfo.dlerror_seen() = 0;
1079 LD_UTRACE(UTRACE_RTLD_ERROR, NULL, NULL, 0, 0, lockinfo.dlerror_loc());
1083 * Return a dynamically-allocated copy of the current error message, if any.
1085 static struct dlerror_save *
1088 struct dlerror_save *res;
1090 res = xmalloc(sizeof(*res));
1091 res->seen = *lockinfo.dlerror_seen();
1093 res->msg = xstrdup(lockinfo.dlerror_loc());
1098 * Restore the current error message from a copy which was previously saved
1099 * by errmsg_save(). The copy is freed.
1102 errmsg_restore(struct dlerror_save *saved_msg)
1104 if (saved_msg == NULL || saved_msg->seen == 1) {
1105 *lockinfo.dlerror_seen() = 1;
1107 *lockinfo.dlerror_seen() = 0;
1108 strlcpy(lockinfo.dlerror_loc(), saved_msg->msg,
1109 lockinfo.dlerror_loc_sz);
1110 free(saved_msg->msg);
1116 basename(const char *name)
1120 p = strrchr(name, '/');
1121 return (p != NULL ? p + 1 : name);
1124 static struct utsname uts;
1127 origin_subst_one(Obj_Entry *obj, char *real, const char *kw,
1128 const char *subst, bool may_free)
1130 char *p, *p1, *res, *resp;
1131 int subst_len, kw_len, subst_count, old_len, new_len;
1133 kw_len = strlen(kw);
1136 * First, count the number of the keyword occurrences, to
1137 * preallocate the final string.
1139 for (p = real, subst_count = 0;; p = p1 + kw_len, subst_count++) {
1146 * If the keyword is not found, just return.
1148 * Return non-substituted string if resolution failed. We
1149 * cannot do anything more reasonable, the failure mode of the
1150 * caller is unresolved library anyway.
1152 if (subst_count == 0 || (obj != NULL && !obj_resolve_origin(obj)))
1153 return (may_free ? real : xstrdup(real));
1155 subst = obj->origin_path;
1158 * There is indeed something to substitute. Calculate the
1159 * length of the resulting string, and allocate it.
1161 subst_len = strlen(subst);
1162 old_len = strlen(real);
1163 new_len = old_len + (subst_len - kw_len) * subst_count;
1164 res = xmalloc(new_len + 1);
1167 * Now, execute the substitution loop.
1169 for (p = real, resp = res, *resp = '\0';;) {
1172 /* Copy the prefix before keyword. */
1173 memcpy(resp, p, p1 - p);
1175 /* Keyword replacement. */
1176 memcpy(resp, subst, subst_len);
1184 /* Copy to the end of string and finish. */
1191 static const struct {
1196 { .kw = "$ORIGIN", .pass_obj = true, .subst = NULL },
1197 { .kw = "${ORIGIN}", .pass_obj = true, .subst = NULL },
1198 { .kw = "$OSNAME", .pass_obj = false, .subst = uts.sysname },
1199 { .kw = "${OSNAME}", .pass_obj = false, .subst = uts.sysname },
1200 { .kw = "$OSREL", .pass_obj = false, .subst = uts.release },
1201 { .kw = "${OSREL}", .pass_obj = false, .subst = uts.release },
1202 { .kw = "$PLATFORM", .pass_obj = false, .subst = uts.machine },
1203 { .kw = "${PLATFORM}", .pass_obj = false, .subst = uts.machine },
1207 origin_subst(Obj_Entry *obj, const char *real)
1212 if (obj == NULL || !trust)
1213 return (xstrdup(real));
1214 if (uts.sysname[0] == '\0') {
1215 if (uname(&uts) != 0) {
1216 _rtld_error("utsname failed: %d", errno);
1221 /* __DECONST is safe here since without may_free real is unchanged */
1222 res = __DECONST(char *, real);
1223 for (i = 0; i < (int)nitems(tokens); i++) {
1224 res = origin_subst_one(tokens[i].pass_obj ? obj : NULL,
1225 res, tokens[i].kw, tokens[i].subst, i != 0);
1233 const char *msg = dlerror();
1236 msg = "Fatal error";
1237 rtld_fdputstr(STDERR_FILENO, _BASENAME_RTLD ": ");
1238 rtld_fdputstr(STDERR_FILENO, msg);
1239 rtld_fdputchar(STDERR_FILENO, '\n');
1244 * Process a shared object's DYNAMIC section, and save the important
1245 * information in its Obj_Entry structure.
1248 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
1249 const Elf_Dyn **dyn_soname, const Elf_Dyn **dyn_runpath)
1251 const Elf_Dyn *dynp;
1252 Needed_Entry **needed_tail = &obj->needed;
1253 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
1254 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
1255 const Elf_Hashelt *hashtab;
1256 const Elf32_Word *hashval;
1257 Elf32_Word bkt, nmaskwords;
1259 int plttype = DT_REL;
1263 *dyn_runpath = NULL;
1265 obj->bind_now = false;
1266 dynp = obj->dynamic;
1269 for (; dynp->d_tag != DT_NULL; dynp++) {
1270 switch (dynp->d_tag) {
1273 obj->rel = (const Elf_Rel *)(obj->relocbase + dynp->d_un.d_ptr);
1277 obj->relsize = dynp->d_un.d_val;
1281 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
1285 obj->pltrel = (const Elf_Rel *)
1286 (obj->relocbase + dynp->d_un.d_ptr);
1290 obj->pltrelsize = dynp->d_un.d_val;
1294 obj->rela = (const Elf_Rela *)(obj->relocbase + dynp->d_un.d_ptr);
1298 obj->relasize = dynp->d_un.d_val;
1302 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
1306 obj->relr = (const Elf_Relr *)(obj->relocbase + dynp->d_un.d_ptr);
1310 obj->relrsize = dynp->d_un.d_val;
1314 assert(dynp->d_un.d_val == sizeof(Elf_Relr));
1318 plttype = dynp->d_un.d_val;
1319 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
1323 obj->symtab = (const Elf_Sym *)
1324 (obj->relocbase + dynp->d_un.d_ptr);
1328 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
1332 obj->strtab = (const char *)(obj->relocbase + dynp->d_un.d_ptr);
1336 obj->strsize = dynp->d_un.d_val;
1340 obj->verneed = (const Elf_Verneed *)(obj->relocbase +
1345 obj->verneednum = dynp->d_un.d_val;
1349 obj->verdef = (const Elf_Verdef *)(obj->relocbase +
1354 obj->verdefnum = dynp->d_un.d_val;
1358 obj->versyms = (const Elf_Versym *)(obj->relocbase +
1364 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1366 obj->nbuckets = hashtab[0];
1367 obj->nchains = hashtab[1];
1368 obj->buckets = hashtab + 2;
1369 obj->chains = obj->buckets + obj->nbuckets;
1370 obj->valid_hash_sysv = obj->nbuckets > 0 && obj->nchains > 0 &&
1371 obj->buckets != NULL;
1377 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1379 obj->nbuckets_gnu = hashtab[0];
1380 obj->symndx_gnu = hashtab[1];
1381 nmaskwords = hashtab[2];
1382 bloom_size32 = (__ELF_WORD_SIZE / 32) * nmaskwords;
1383 obj->maskwords_bm_gnu = nmaskwords - 1;
1384 obj->shift2_gnu = hashtab[3];
1385 obj->bloom_gnu = (const Elf_Addr *)(hashtab + 4);
1386 obj->buckets_gnu = hashtab + 4 + bloom_size32;
1387 obj->chain_zero_gnu = obj->buckets_gnu + obj->nbuckets_gnu -
1389 /* Number of bitmask words is required to be power of 2 */
1390 obj->valid_hash_gnu = powerof2(nmaskwords) &&
1391 obj->nbuckets_gnu > 0 && obj->buckets_gnu != NULL;
1397 Needed_Entry *nep = NEW(Needed_Entry);
1398 nep->name = dynp->d_un.d_val;
1403 needed_tail = &nep->next;
1409 Needed_Entry *nep = NEW(Needed_Entry);
1410 nep->name = dynp->d_un.d_val;
1414 *needed_filtees_tail = nep;
1415 needed_filtees_tail = &nep->next;
1417 if (obj->linkmap.l_refname == NULL)
1418 obj->linkmap.l_refname = (char *)dynp->d_un.d_val;
1424 Needed_Entry *nep = NEW(Needed_Entry);
1425 nep->name = dynp->d_un.d_val;
1429 *needed_aux_filtees_tail = nep;
1430 needed_aux_filtees_tail = &nep->next;
1435 obj->pltgot = (Elf_Addr *)(obj->relocbase + dynp->d_un.d_ptr);
1439 obj->textrel = true;
1443 obj->symbolic = true;
1448 * We have to wait until later to process this, because we
1449 * might not have gotten the address of the string table yet.
1459 *dyn_runpath = dynp;
1463 obj->init = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1466 case DT_PREINIT_ARRAY:
1467 obj->preinit_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1470 case DT_PREINIT_ARRAYSZ:
1471 obj->preinit_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1475 obj->init_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1478 case DT_INIT_ARRAYSZ:
1479 obj->init_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1483 obj->fini = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1487 obj->fini_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1490 case DT_FINI_ARRAYSZ:
1491 obj->fini_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1496 dbg("Filling in DT_DEBUG entry");
1497 (__DECONST(Elf_Dyn *, dynp))->d_un.d_ptr = (Elf_Addr)&r_debug;
1501 if (dynp->d_un.d_val & DF_ORIGIN)
1502 obj->z_origin = true;
1503 if (dynp->d_un.d_val & DF_SYMBOLIC)
1504 obj->symbolic = true;
1505 if (dynp->d_un.d_val & DF_TEXTREL)
1506 obj->textrel = true;
1507 if (dynp->d_un.d_val & DF_BIND_NOW)
1508 obj->bind_now = true;
1509 if (dynp->d_un.d_val & DF_STATIC_TLS)
1510 obj->static_tls = true;
1514 #ifdef __powerpc64__
1515 case DT_PPC64_GLINK:
1516 obj->glink = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1520 obj->gotptr = (Elf_Addr *)(obj->relocbase + dynp->d_un.d_ptr);
1526 if (dynp->d_un.d_val & DF_1_NOOPEN)
1527 obj->z_noopen = true;
1528 if (dynp->d_un.d_val & DF_1_ORIGIN)
1529 obj->z_origin = true;
1530 if (dynp->d_un.d_val & DF_1_GLOBAL)
1531 obj->z_global = true;
1532 if (dynp->d_un.d_val & DF_1_BIND_NOW)
1533 obj->bind_now = true;
1534 if (dynp->d_un.d_val & DF_1_NODELETE)
1535 obj->z_nodelete = true;
1536 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1537 obj->z_loadfltr = true;
1538 if (dynp->d_un.d_val & DF_1_INTERPOSE)
1539 obj->z_interpose = true;
1540 if (dynp->d_un.d_val & DF_1_NODEFLIB)
1541 obj->z_nodeflib = true;
1542 if (dynp->d_un.d_val & DF_1_PIE)
1548 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1555 obj->traced = false;
1557 if (plttype == DT_RELA) {
1558 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1560 obj->pltrelasize = obj->pltrelsize;
1561 obj->pltrelsize = 0;
1564 /* Determine size of dynsym table (equal to nchains of sysv hash) */
1565 if (obj->valid_hash_sysv)
1566 obj->dynsymcount = obj->nchains;
1567 else if (obj->valid_hash_gnu) {
1568 obj->dynsymcount = 0;
1569 for (bkt = 0; bkt < obj->nbuckets_gnu; bkt++) {
1570 if (obj->buckets_gnu[bkt] == 0)
1572 hashval = &obj->chain_zero_gnu[obj->buckets_gnu[bkt]];
1575 while ((*hashval++ & 1u) == 0);
1577 obj->dynsymcount += obj->symndx_gnu;
1580 if (obj->linkmap.l_refname != NULL)
1581 obj->linkmap.l_refname = obj->strtab + (unsigned long)obj->
1586 obj_resolve_origin(Obj_Entry *obj)
1589 if (obj->origin_path != NULL)
1591 obj->origin_path = xmalloc(PATH_MAX);
1592 return (rtld_dirname_abs(obj->path, obj->origin_path) != -1);
1596 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1597 const Elf_Dyn *dyn_soname, const Elf_Dyn *dyn_runpath)
1600 if (obj->z_origin && !obj_resolve_origin(obj))
1603 if (dyn_runpath != NULL) {
1604 obj->runpath = (const char *)obj->strtab + dyn_runpath->d_un.d_val;
1605 obj->runpath = origin_subst(obj, obj->runpath);
1606 } else if (dyn_rpath != NULL) {
1607 obj->rpath = (const char *)obj->strtab + dyn_rpath->d_un.d_val;
1608 obj->rpath = origin_subst(obj, obj->rpath);
1610 if (dyn_soname != NULL)
1611 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1616 digest_dynamic(Obj_Entry *obj, int early)
1618 const Elf_Dyn *dyn_rpath;
1619 const Elf_Dyn *dyn_soname;
1620 const Elf_Dyn *dyn_runpath;
1622 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname, &dyn_runpath);
1623 return (digest_dynamic2(obj, dyn_rpath, dyn_soname, dyn_runpath));
1627 * Process a shared object's program header. This is used only for the
1628 * main program, when the kernel has already loaded the main program
1629 * into memory before calling the dynamic linker. It creates and
1630 * returns an Obj_Entry structure.
1633 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1636 const Elf_Phdr *phlimit = phdr + phnum;
1638 Elf_Addr note_start, note_end;
1642 for (ph = phdr; ph < phlimit; ph++) {
1643 if (ph->p_type != PT_PHDR)
1647 obj->phsize = ph->p_memsz;
1648 obj->relocbase = __DECONST(char *, phdr) - ph->p_vaddr;
1652 obj->stack_flags = PF_X | PF_R | PF_W;
1654 for (ph = phdr; ph < phlimit; ph++) {
1655 switch (ph->p_type) {
1658 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1662 if (nsegs == 0) { /* First load segment */
1663 obj->vaddrbase = rtld_trunc_page(ph->p_vaddr);
1664 obj->mapbase = obj->vaddrbase + obj->relocbase;
1665 } else { /* Last load segment */
1666 obj->mapsize = rtld_round_page(ph->p_vaddr + ph->p_memsz) -
1673 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1678 obj->tlssize = ph->p_memsz;
1679 obj->tlsalign = ph->p_align;
1680 obj->tlsinitsize = ph->p_filesz;
1681 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1682 obj->tlspoffset = ph->p_offset;
1686 obj->stack_flags = ph->p_flags;
1690 obj->relro_page = obj->relocbase + rtld_trunc_page(ph->p_vaddr);
1691 obj->relro_size = rtld_trunc_page(ph->p_vaddr + ph->p_memsz) -
1692 rtld_trunc_page(ph->p_vaddr);
1696 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
1697 note_end = note_start + ph->p_filesz;
1698 digest_notes(obj, note_start, note_end);
1703 _rtld_error("%s: too few PT_LOAD segments", path);
1712 digest_notes(Obj_Entry *obj, Elf_Addr note_start, Elf_Addr note_end)
1714 const Elf_Note *note;
1715 const char *note_name;
1718 for (note = (const Elf_Note *)note_start; (Elf_Addr)note < note_end;
1719 note = (const Elf_Note *)((const char *)(note + 1) +
1720 roundup2(note->n_namesz, sizeof(Elf32_Addr)) +
1721 roundup2(note->n_descsz, sizeof(Elf32_Addr)))) {
1722 if (note->n_namesz != sizeof(NOTE_FREEBSD_VENDOR) ||
1723 note->n_descsz != sizeof(int32_t))
1725 if (note->n_type != NT_FREEBSD_ABI_TAG &&
1726 note->n_type != NT_FREEBSD_FEATURE_CTL &&
1727 note->n_type != NT_FREEBSD_NOINIT_TAG)
1729 note_name = (const char *)(note + 1);
1730 if (strncmp(NOTE_FREEBSD_VENDOR, note_name,
1731 sizeof(NOTE_FREEBSD_VENDOR)) != 0)
1733 switch (note->n_type) {
1734 case NT_FREEBSD_ABI_TAG:
1735 /* FreeBSD osrel note */
1736 p = (uintptr_t)(note + 1);
1737 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1738 obj->osrel = *(const int32_t *)(p);
1739 dbg("note osrel %d", obj->osrel);
1741 case NT_FREEBSD_FEATURE_CTL:
1742 /* FreeBSD ABI feature control note */
1743 p = (uintptr_t)(note + 1);
1744 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1745 obj->fctl0 = *(const uint32_t *)(p);
1746 dbg("note fctl0 %#x", obj->fctl0);
1748 case NT_FREEBSD_NOINIT_TAG:
1749 /* FreeBSD 'crt does not call init' note */
1750 obj->crt_no_init = true;
1751 dbg("note crt_no_init");
1758 dlcheck(void *handle)
1762 TAILQ_FOREACH(obj, &obj_list, next) {
1763 if (obj == (Obj_Entry *) handle)
1767 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1768 _rtld_error("Invalid shared object handle %p", handle);
1775 * If the given object is already in the donelist, return true. Otherwise
1776 * add the object to the list and return false.
1779 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1783 for (i = 0; i < dlp->num_used; i++)
1784 if (dlp->objs[i] == obj)
1787 * Our donelist allocation should always be sufficient. But if
1788 * our threads locking isn't working properly, more shared objects
1789 * could have been loaded since we allocated the list. That should
1790 * never happen, but we'll handle it properly just in case it does.
1792 if (dlp->num_used < dlp->num_alloc)
1793 dlp->objs[dlp->num_used++] = obj;
1798 * Hash function for symbol table lookup. Don't even think about changing
1799 * this. It is specified by the System V ABI.
1802 elf_hash(const char *name)
1804 const unsigned char *p = (const unsigned char *) name;
1805 unsigned long h = 0;
1808 while (*p != '\0') {
1809 h = (h << 4) + *p++;
1810 if ((g = h & 0xf0000000) != 0)
1818 * The GNU hash function is the Daniel J. Bernstein hash clipped to 32 bits
1819 * unsigned in case it's implemented with a wider type.
1822 gnu_hash(const char *s)
1828 for (c = *s; c != '\0'; c = *++s)
1830 return (h & 0xffffffff);
1835 * Find the library with the given name, and return its full pathname.
1836 * The returned string is dynamically allocated. Generates an error
1837 * message and returns NULL if the library cannot be found.
1839 * If the second argument is non-NULL, then it refers to an already-
1840 * loaded shared object, whose library search path will be searched.
1842 * If a library is successfully located via LD_LIBRARY_PATH_FDS, its
1843 * descriptor (which is close-on-exec) will be passed out via the third
1846 * The search order is:
1847 * DT_RPATH in the referencing file _unless_ DT_RUNPATH is present (1)
1848 * DT_RPATH of the main object if DSO without defined DT_RUNPATH (1)
1850 * DT_RUNPATH in the referencing file
1851 * ldconfig hints (if -z nodefaultlib, filter out default library directories
1853 * /lib:/usr/lib _unless_ the referencing file is linked with -z nodefaultlib
1855 * (1) Handled in digest_dynamic2 - rpath left NULL if runpath defined.
1858 find_library(const char *xname, const Obj_Entry *refobj, int *fdp)
1860 char *pathname, *refobj_path;
1862 bool nodeflib, objgiven;
1864 objgiven = refobj != NULL;
1866 if (libmap_disable || !objgiven ||
1867 (name = lm_find(refobj->path, xname)) == NULL)
1870 if (strchr(name, '/') != NULL) { /* Hard coded pathname */
1871 if (name[0] != '/' && !trust) {
1872 _rtld_error("Absolute pathname required "
1873 "for shared object \"%s\"", name);
1876 return (origin_subst(__DECONST(Obj_Entry *, refobj),
1877 __DECONST(char *, name)));
1880 dbg(" Searching for \"%s\"", name);
1881 refobj_path = objgiven ? refobj->path : NULL;
1884 * If refobj->rpath != NULL, then refobj->runpath is NULL. Fall
1885 * back to pre-conforming behaviour if user requested so with
1886 * LD_LIBRARY_PATH_RPATH environment variable and ignore -z
1889 if (objgiven && refobj->rpath != NULL && ld_library_path_rpath) {
1890 pathname = search_library_path(name, ld_library_path,
1892 if (pathname != NULL)
1894 if (refobj != NULL) {
1895 pathname = search_library_path(name, refobj->rpath,
1897 if (pathname != NULL)
1900 pathname = search_library_pathfds(name, ld_library_dirs, fdp);
1901 if (pathname != NULL)
1903 pathname = search_library_path(name, gethints(false),
1905 if (pathname != NULL)
1907 pathname = search_library_path(name, ld_standard_library_path,
1909 if (pathname != NULL)
1912 nodeflib = objgiven ? refobj->z_nodeflib : false;
1914 pathname = search_library_path(name, refobj->rpath,
1916 if (pathname != NULL)
1919 if (objgiven && refobj->runpath == NULL && refobj != obj_main) {
1920 pathname = search_library_path(name, obj_main->rpath,
1922 if (pathname != NULL)
1925 pathname = search_library_path(name, ld_library_path,
1927 if (pathname != NULL)
1930 pathname = search_library_path(name, refobj->runpath,
1932 if (pathname != NULL)
1935 pathname = search_library_pathfds(name, ld_library_dirs, fdp);
1936 if (pathname != NULL)
1938 pathname = search_library_path(name, gethints(nodeflib),
1940 if (pathname != NULL)
1942 if (objgiven && !nodeflib) {
1943 pathname = search_library_path(name,
1944 ld_standard_library_path, refobj_path, fdp);
1945 if (pathname != NULL)
1950 if (objgiven && refobj->path != NULL) {
1951 _rtld_error("Shared object \"%s\" not found, "
1952 "required by \"%s\"", name, basename(refobj->path));
1954 _rtld_error("Shared object \"%s\" not found", name);
1960 * Given a symbol number in a referencing object, find the corresponding
1961 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1962 * no definition was found. Returns a pointer to the Obj_Entry of the
1963 * defining object via the reference parameter DEFOBJ_OUT.
1966 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1967 const Obj_Entry **defobj_out, int flags, SymCache *cache,
1968 RtldLockState *lockstate)
1972 const Obj_Entry *defobj;
1973 const Ver_Entry *ve;
1979 * If we have already found this symbol, get the information from
1982 if (symnum >= refobj->dynsymcount)
1983 return (NULL); /* Bad object */
1984 if (cache != NULL && cache[symnum].sym != NULL) {
1985 *defobj_out = cache[symnum].obj;
1986 return (cache[symnum].sym);
1989 ref = refobj->symtab + symnum;
1990 name = refobj->strtab + ref->st_name;
1996 * We don't have to do a full scale lookup if the symbol is local.
1997 * We know it will bind to the instance in this load module; to
1998 * which we already have a pointer (ie ref). By not doing a lookup,
1999 * we not only improve performance, but it also avoids unresolvable
2000 * symbols when local symbols are not in the hash table. This has
2001 * been seen with the ia64 toolchain.
2003 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
2004 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
2005 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
2008 symlook_init(&req, name);
2010 ve = req.ventry = fetch_ventry(refobj, symnum);
2011 req.lockstate = lockstate;
2012 res = symlook_default(&req, refobj);
2015 defobj = req.defobj_out;
2023 * If we found no definition and the reference is weak, treat the
2024 * symbol as having the value zero.
2026 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
2032 *defobj_out = defobj;
2033 /* Record the information in the cache to avoid subsequent lookups. */
2034 if (cache != NULL) {
2035 cache[symnum].sym = def;
2036 cache[symnum].obj = defobj;
2039 if (refobj != &obj_rtld)
2040 _rtld_error("%s: Undefined symbol \"%s%s%s\"", refobj->path, name,
2041 ve != NULL ? "@" : "", ve != NULL ? ve->name : "");
2047 * Return the search path from the ldconfig hints file, reading it if
2048 * necessary. If nostdlib is true, then the default search paths are
2049 * not added to result.
2051 * Returns NULL if there are problems with the hints file,
2052 * or if the search path there is empty.
2055 gethints(bool nostdlib)
2057 static char *filtered_path;
2058 static const char *hints;
2059 static struct elfhints_hdr hdr;
2060 struct fill_search_info_args sargs, hargs;
2061 struct dl_serinfo smeta, hmeta, *SLPinfo, *hintinfo;
2062 struct dl_serpath *SLPpath, *hintpath;
2064 struct stat hint_stat;
2065 unsigned int SLPndx, hintndx, fndx, fcount;
2071 /* First call, read the hints file */
2072 if (hints == NULL) {
2073 /* Keep from trying again in case the hints file is bad. */
2076 if ((fd = open(ld_elf_hints_path, O_RDONLY | O_CLOEXEC)) == -1)
2080 * Check of hdr.dirlistlen value against type limit
2081 * intends to pacify static analyzers. Further
2082 * paranoia leads to checks that dirlist is fully
2083 * contained in the file range.
2085 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
2086 hdr.magic != ELFHINTS_MAGIC ||
2087 hdr.version != 1 || hdr.dirlistlen > UINT_MAX / 2 ||
2088 fstat(fd, &hint_stat) == -1) {
2095 if (dl + hdr.dirlist < dl)
2098 if (dl + hdr.dirlistlen < dl)
2100 dl += hdr.dirlistlen;
2101 if (dl > hint_stat.st_size)
2103 p = xmalloc(hdr.dirlistlen + 1);
2104 if (pread(fd, p, hdr.dirlistlen + 1,
2105 hdr.strtab + hdr.dirlist) != (ssize_t)hdr.dirlistlen + 1 ||
2106 p[hdr.dirlistlen] != '\0') {
2115 * If caller agreed to receive list which includes the default
2116 * paths, we are done. Otherwise, if we still did not
2117 * calculated filtered result, do it now.
2120 return (hints[0] != '\0' ? hints : NULL);
2121 if (filtered_path != NULL)
2125 * Obtain the list of all configured search paths, and the
2126 * list of the default paths.
2128 * First estimate the size of the results.
2130 smeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2132 hmeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2135 sargs.request = RTLD_DI_SERINFOSIZE;
2136 sargs.serinfo = &smeta;
2137 hargs.request = RTLD_DI_SERINFOSIZE;
2138 hargs.serinfo = &hmeta;
2140 path_enumerate(ld_standard_library_path, fill_search_info, NULL,
2142 path_enumerate(hints, fill_search_info, NULL, &hargs);
2144 SLPinfo = xmalloc(smeta.dls_size);
2145 hintinfo = xmalloc(hmeta.dls_size);
2148 * Next fetch both sets of paths.
2150 sargs.request = RTLD_DI_SERINFO;
2151 sargs.serinfo = SLPinfo;
2152 sargs.serpath = &SLPinfo->dls_serpath[0];
2153 sargs.strspace = (char *)&SLPinfo->dls_serpath[smeta.dls_cnt];
2155 hargs.request = RTLD_DI_SERINFO;
2156 hargs.serinfo = hintinfo;
2157 hargs.serpath = &hintinfo->dls_serpath[0];
2158 hargs.strspace = (char *)&hintinfo->dls_serpath[hmeta.dls_cnt];
2160 path_enumerate(ld_standard_library_path, fill_search_info, NULL,
2162 path_enumerate(hints, fill_search_info, NULL, &hargs);
2165 * Now calculate the difference between two sets, by excluding
2166 * standard paths from the full set.
2170 filtered_path = xmalloc(hdr.dirlistlen + 1);
2171 hintpath = &hintinfo->dls_serpath[0];
2172 for (hintndx = 0; hintndx < hmeta.dls_cnt; hintndx++, hintpath++) {
2174 SLPpath = &SLPinfo->dls_serpath[0];
2176 * Check each standard path against current.
2178 for (SLPndx = 0; SLPndx < smeta.dls_cnt; SLPndx++, SLPpath++) {
2179 /* matched, skip the path */
2180 if (!strcmp(hintpath->dls_name, SLPpath->dls_name)) {
2188 * Not matched against any standard path, add the path
2189 * to result. Separate consequtive paths with ':'.
2192 filtered_path[fndx] = ':';
2196 flen = strlen(hintpath->dls_name);
2197 strncpy((filtered_path + fndx), hintpath->dls_name, flen);
2200 filtered_path[fndx] = '\0';
2206 return (filtered_path[0] != '\0' ? filtered_path : NULL);
2210 init_dag(Obj_Entry *root)
2212 const Needed_Entry *needed;
2213 const Objlist_Entry *elm;
2216 if (root->dag_inited)
2218 donelist_init(&donelist);
2220 /* Root object belongs to own DAG. */
2221 objlist_push_tail(&root->dldags, root);
2222 objlist_push_tail(&root->dagmembers, root);
2223 donelist_check(&donelist, root);
2226 * Add dependencies of root object to DAG in breadth order
2227 * by exploiting the fact that each new object get added
2228 * to the tail of the dagmembers list.
2230 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2231 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
2232 if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
2234 objlist_push_tail(&needed->obj->dldags, root);
2235 objlist_push_tail(&root->dagmembers, needed->obj);
2238 root->dag_inited = true;
2242 init_marker(Obj_Entry *marker)
2245 bzero(marker, sizeof(*marker));
2246 marker->marker = true;
2250 globallist_curr(const Obj_Entry *obj)
2257 return (__DECONST(Obj_Entry *, obj));
2258 obj = TAILQ_PREV(obj, obj_entry_q, next);
2263 globallist_next(const Obj_Entry *obj)
2267 obj = TAILQ_NEXT(obj, next);
2271 return (__DECONST(Obj_Entry *, obj));
2275 /* Prevent the object from being unmapped while the bind lock is dropped. */
2277 hold_object(Obj_Entry *obj)
2284 unhold_object(Obj_Entry *obj)
2287 assert(obj->holdcount > 0);
2288 if (--obj->holdcount == 0 && obj->unholdfree)
2289 release_object(obj);
2293 process_z(Obj_Entry *root)
2295 const Objlist_Entry *elm;
2299 * Walk over object DAG and process every dependent object
2300 * that is marked as DF_1_NODELETE or DF_1_GLOBAL. They need
2301 * to grow their own DAG.
2303 * For DF_1_GLOBAL, DAG is required for symbol lookups in
2304 * symlook_global() to work.
2306 * For DF_1_NODELETE, the DAG should have its reference upped.
2308 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2312 if (obj->z_nodelete && !obj->ref_nodel) {
2313 dbg("obj %s -z nodelete", obj->path);
2316 obj->ref_nodel = true;
2318 if (obj->z_global && objlist_find(&list_global, obj) == NULL) {
2319 dbg("obj %s -z global", obj->path);
2320 objlist_push_tail(&list_global, obj);
2327 parse_rtld_phdr(Obj_Entry *obj)
2330 Elf_Addr note_start, note_end;
2332 obj->stack_flags = PF_X | PF_R | PF_W;
2333 for (ph = obj->phdr; (const char *)ph < (const char *)obj->phdr +
2334 obj->phsize; ph++) {
2335 switch (ph->p_type) {
2337 obj->stack_flags = ph->p_flags;
2340 obj->relro_page = obj->relocbase +
2341 rtld_trunc_page(ph->p_vaddr);
2342 obj->relro_size = rtld_round_page(ph->p_memsz);
2345 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
2346 note_end = note_start + ph->p_filesz;
2347 digest_notes(obj, note_start, note_end);
2354 * Initialize the dynamic linker. The argument is the address at which
2355 * the dynamic linker has been mapped into memory. The primary task of
2356 * this function is to relocate the dynamic linker.
2359 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
2361 Obj_Entry objtmp; /* Temporary rtld object */
2362 const Elf_Ehdr *ehdr;
2363 const Elf_Dyn *dyn_rpath;
2364 const Elf_Dyn *dyn_soname;
2365 const Elf_Dyn *dyn_runpath;
2367 #ifdef RTLD_INIT_PAGESIZES_EARLY
2368 /* The page size is required by the dynamic memory allocator. */
2369 init_pagesizes(aux_info);
2373 * Conjure up an Obj_Entry structure for the dynamic linker.
2375 * The "path" member can't be initialized yet because string constants
2376 * cannot yet be accessed. Below we will set it correctly.
2378 memset(&objtmp, 0, sizeof(objtmp));
2381 objtmp.mapbase = mapbase;
2383 objtmp.relocbase = mapbase;
2386 objtmp.dynamic = rtld_dynamic(&objtmp);
2387 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname, &dyn_runpath);
2388 assert(objtmp.needed == NULL);
2389 assert(!objtmp.textrel);
2391 * Temporarily put the dynamic linker entry into the object list, so
2392 * that symbols can be found.
2394 relocate_objects(&objtmp, true, &objtmp, 0, NULL);
2396 ehdr = (Elf_Ehdr *)mapbase;
2397 objtmp.phdr = (Elf_Phdr *)((char *)mapbase + ehdr->e_phoff);
2398 objtmp.phsize = ehdr->e_phnum * sizeof(objtmp.phdr[0]);
2400 /* Initialize the object list. */
2401 TAILQ_INIT(&obj_list);
2403 /* Now that non-local variables can be accesses, copy out obj_rtld. */
2404 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
2406 #ifndef RTLD_INIT_PAGESIZES_EARLY
2407 /* The page size is required by the dynamic memory allocator. */
2408 init_pagesizes(aux_info);
2411 if (aux_info[AT_OSRELDATE] != NULL)
2412 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
2414 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname, dyn_runpath);
2416 /* Replace the path with a dynamically allocated copy. */
2417 obj_rtld.path = xstrdup(ld_path_rtld);
2419 parse_rtld_phdr(&obj_rtld);
2420 if (obj_enforce_relro(&obj_rtld) == -1)
2423 r_debug.r_version = R_DEBUG_VERSION;
2424 r_debug.r_brk = r_debug_state;
2425 r_debug.r_state = RT_CONSISTENT;
2426 r_debug.r_ldbase = obj_rtld.relocbase;
2430 * Retrieve the array of supported page sizes. The kernel provides the page
2431 * sizes in increasing order.
2434 init_pagesizes(Elf_Auxinfo **aux_info)
2436 static size_t psa[MAXPAGESIZES];
2440 if (aux_info[AT_PAGESIZES] != NULL && aux_info[AT_PAGESIZESLEN] !=
2442 size = aux_info[AT_PAGESIZESLEN]->a_un.a_val;
2443 pagesizes = aux_info[AT_PAGESIZES]->a_un.a_ptr;
2446 if (sysctlnametomib("hw.pagesizes", mib, &len) == 0)
2449 /* As a fallback, retrieve the base page size. */
2450 size = sizeof(psa[0]);
2451 if (aux_info[AT_PAGESZ] != NULL) {
2452 psa[0] = aux_info[AT_PAGESZ]->a_un.a_val;
2456 mib[1] = HW_PAGESIZE;
2460 if (sysctl(mib, len, psa, &size, NULL, 0) == -1) {
2461 _rtld_error("sysctl for hw.pagesize(s) failed");
2467 npagesizes = size / sizeof(pagesizes[0]);
2468 /* Discard any invalid entries at the end of the array. */
2469 while (npagesizes > 0 && pagesizes[npagesizes - 1] == 0)
2472 page_size = pagesizes[0];
2476 * Add the init functions from a needed object list (and its recursive
2477 * needed objects) to "list". This is not used directly; it is a helper
2478 * function for initlist_add_objects(). The write lock must be held
2479 * when this function is called.
2482 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
2484 /* Recursively process the successor needed objects. */
2485 if (needed->next != NULL)
2486 initlist_add_neededs(needed->next, list);
2488 /* Process the current needed object. */
2489 if (needed->obj != NULL)
2490 initlist_add_objects(needed->obj, needed->obj, list);
2494 * Scan all of the DAGs rooted in the range of objects from "obj" to
2495 * "tail" and add their init functions to "list". This recurses over
2496 * the DAGs and ensure the proper init ordering such that each object's
2497 * needed libraries are initialized before the object itself. At the
2498 * same time, this function adds the objects to the global finalization
2499 * list "list_fini" in the opposite order. The write lock must be
2500 * held when this function is called.
2503 initlist_add_objects(Obj_Entry *obj, Obj_Entry *tail, Objlist *list)
2507 if (obj->init_scanned || obj->init_done)
2509 obj->init_scanned = true;
2511 /* Recursively process the successor objects. */
2512 nobj = globallist_next(obj);
2513 if (nobj != NULL && obj != tail)
2514 initlist_add_objects(nobj, tail, list);
2516 /* Recursively process the needed objects. */
2517 if (obj->needed != NULL)
2518 initlist_add_neededs(obj->needed, list);
2519 if (obj->needed_filtees != NULL)
2520 initlist_add_neededs(obj->needed_filtees, list);
2521 if (obj->needed_aux_filtees != NULL)
2522 initlist_add_neededs(obj->needed_aux_filtees, list);
2524 /* Add the object to the init list. */
2525 objlist_push_tail(list, obj);
2527 /* Add the object to the global fini list in the reverse order. */
2528 if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL)
2529 && !obj->on_fini_list) {
2530 objlist_push_head(&list_fini, obj);
2531 obj->on_fini_list = true;
2536 #define FPTR_TARGET(f) ((Elf_Addr) (f))
2540 free_needed_filtees(Needed_Entry *n, RtldLockState *lockstate)
2542 Needed_Entry *needed, *needed1;
2544 for (needed = n; needed != NULL; needed = needed->next) {
2545 if (needed->obj != NULL) {
2546 dlclose_locked(needed->obj, lockstate);
2550 for (needed = n; needed != NULL; needed = needed1) {
2551 needed1 = needed->next;
2557 unload_filtees(Obj_Entry *obj, RtldLockState *lockstate)
2560 free_needed_filtees(obj->needed_filtees, lockstate);
2561 obj->needed_filtees = NULL;
2562 free_needed_filtees(obj->needed_aux_filtees, lockstate);
2563 obj->needed_aux_filtees = NULL;
2564 obj->filtees_loaded = false;
2568 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags,
2569 RtldLockState *lockstate)
2572 for (; needed != NULL; needed = needed->next) {
2573 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
2574 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
2575 RTLD_LOCAL, lockstate);
2580 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
2583 lock_restart_for_upgrade(lockstate);
2584 if (!obj->filtees_loaded) {
2585 load_filtee1(obj, obj->needed_filtees, flags, lockstate);
2586 load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate);
2587 obj->filtees_loaded = true;
2592 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
2596 for (; needed != NULL; needed = needed->next) {
2597 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
2598 flags & ~RTLD_LO_NOLOAD);
2599 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
2606 * Given a shared object, traverse its list of needed objects, and load
2607 * each of them. Returns 0 on success. Generates an error message and
2608 * returns -1 on failure.
2611 load_needed_objects(Obj_Entry *first, int flags)
2615 for (obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
2618 if (process_needed(obj, obj->needed, flags) == -1)
2625 load_preload_objects(const char *penv, bool isfd)
2630 char savech, *p, *psave;
2632 static const char delim[] = " \t:;";
2637 p = psave = xstrdup(penv);
2638 p += strspn(p, delim);
2639 while (*p != '\0') {
2640 len = strcspn(p, delim);
2646 fd = parse_integer(p);
2656 obj = load_object(name, fd, NULL, 0);
2659 return (-1); /* XXX - cleanup */
2661 obj->z_interpose = true;
2664 p += strspn(p, delim);
2666 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
2673 printable_path(const char *path)
2676 return (path == NULL ? "<unknown>" : path);
2680 * Load a shared object into memory, if it is not already loaded. The
2681 * object may be specified by name or by user-supplied file descriptor
2682 * fd_u. In the later case, the fd_u descriptor is not closed, but its
2685 * Returns a pointer to the Obj_Entry for the object. Returns NULL
2689 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
2698 TAILQ_FOREACH(obj, &obj_list, next) {
2699 if (obj->marker || obj->doomed)
2701 if (object_match_name(obj, name))
2705 path = find_library(name, refobj, &fd);
2713 * search_library_pathfds() opens a fresh file descriptor for the
2714 * library, so there is no need to dup().
2716 } else if (fd_u == -1) {
2718 * If we didn't find a match by pathname, or the name is not
2719 * supplied, open the file and check again by device and inode.
2720 * This avoids false mismatches caused by multiple links or ".."
2723 * To avoid a race, we open the file and use fstat() rather than
2726 if ((fd = open(path, O_RDONLY | O_CLOEXEC | O_VERIFY)) == -1) {
2727 _rtld_error("Cannot open \"%s\"", path);
2732 fd = fcntl(fd_u, F_DUPFD_CLOEXEC, 0);
2734 _rtld_error("Cannot dup fd");
2739 if (fstat(fd, &sb) == -1) {
2740 _rtld_error("Cannot fstat \"%s\"", printable_path(path));
2745 TAILQ_FOREACH(obj, &obj_list, next) {
2746 if (obj->marker || obj->doomed)
2748 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
2751 if (obj != NULL && name != NULL) {
2752 object_add_name(obj, name);
2757 if (flags & RTLD_LO_NOLOAD) {
2763 /* First use of this object, so we must map it in */
2764 obj = do_load_object(fd, name, path, &sb, flags);
2773 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
2780 * First, make sure that environment variables haven't been
2781 * used to circumvent the noexec flag on a filesystem.
2782 * We ignore fstatfs(2) failures, since fd might reference
2783 * not a file, e.g. shmfd.
2785 if (dangerous_ld_env && fstatfs(fd, &fs) == 0 &&
2786 (fs.f_flags & MNT_NOEXEC) != 0) {
2787 _rtld_error("Cannot execute objects on %s", fs.f_mntonname);
2791 dbg("loading \"%s\"", printable_path(path));
2792 obj = map_object(fd, printable_path(path), sbp);
2797 * If DT_SONAME is present in the object, digest_dynamic2 already
2798 * added it to the object names.
2801 object_add_name(obj, name);
2803 if (!digest_dynamic(obj, 0))
2805 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path,
2806 obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount);
2807 if (obj->z_pie && (flags & RTLD_LO_TRACE) == 0) {
2808 dbg("refusing to load PIE executable \"%s\"", obj->path);
2809 _rtld_error("Cannot load PIE binary %s as DSO", obj->path);
2812 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
2814 dbg("refusing to load non-loadable \"%s\"", obj->path);
2815 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
2819 obj->dlopened = (flags & RTLD_LO_DLOPEN) != 0;
2820 TAILQ_INSERT_TAIL(&obj_list, obj, next);
2823 linkmap_add(obj); /* for GDB & dlinfo() */
2824 max_stack_flags |= obj->stack_flags;
2826 dbg(" %p .. %p: %s", obj->mapbase,
2827 obj->mapbase + obj->mapsize - 1, obj->path);
2829 dbg(" WARNING: %s has impure text", obj->path);
2830 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
2836 munmap(obj->mapbase, obj->mapsize);
2842 load_kpreload(const void *addr)
2845 const Elf_Ehdr *ehdr;
2846 const Elf_Phdr *phdr, *phlimit, *phdyn, *seg0, *segn;
2847 static const char kname[] = "[vdso]";
2850 if (!check_elf_headers(ehdr, "kpreload"))
2853 phdr = (const Elf_Phdr *)((const char *)addr + ehdr->e_phoff);
2855 obj->phsize = ehdr->e_phnum * sizeof(*phdr);
2856 phlimit = phdr + ehdr->e_phnum;
2859 for (; phdr < phlimit; phdr++) {
2860 switch (phdr->p_type) {
2865 /* Absense of PT_GNU_STACK implies stack_flags == 0. */
2866 obj->stack_flags = phdr->p_flags;
2869 if (seg0 == NULL || seg0->p_vaddr > phdr->p_vaddr)
2871 if (segn == NULL || segn->p_vaddr + segn->p_memsz <
2872 phdr->p_vaddr + phdr->p_memsz)
2878 obj->mapbase = __DECONST(caddr_t, addr);
2879 obj->mapsize = segn->p_vaddr + segn->p_memsz - (Elf_Addr)addr;
2881 obj->relocbase = obj->mapbase;
2883 object_add_name(obj, kname);
2884 obj->path = xstrdup(kname);
2885 obj->dynamic = (const Elf_Dyn *)(obj->relocbase + phdyn->p_vaddr);
2887 if (!digest_dynamic(obj, 0)) {
2893 * We assume that kernel-preloaded object does not need
2894 * relocation. It is currently written into read-only page,
2895 * handling relocations would mean we need to allocate at
2896 * least one additional page per AS.
2898 dbg("%s mapbase %p phdrs %p PT_LOAD phdr %p vaddr %p dynamic %p",
2899 obj->path, obj->mapbase, obj->phdr, seg0,
2900 obj->relocbase + seg0->p_vaddr, obj->dynamic);
2902 TAILQ_INSERT_TAIL(&obj_list, obj, next);
2905 linkmap_add(obj); /* for GDB & dlinfo() */
2906 max_stack_flags |= obj->stack_flags;
2908 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, 0, 0, obj->path);
2913 obj_from_addr(const void *addr)
2917 TAILQ_FOREACH(obj, &obj_list, next) {
2920 if (addr < (void *) obj->mapbase)
2922 if (addr < (void *)(obj->mapbase + obj->mapsize))
2931 Elf_Addr *preinit_addr;
2934 preinit_addr = (Elf_Addr *)obj_main->preinit_array;
2935 if (preinit_addr == NULL)
2938 for (index = 0; index < obj_main->preinit_array_num; index++) {
2939 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) {
2940 dbg("calling preinit function for %s at %p", obj_main->path,
2941 (void *)preinit_addr[index]);
2942 LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index],
2943 0, 0, obj_main->path);
2944 call_init_pointer(obj_main, preinit_addr[index]);
2950 * Call the finalization functions for each of the objects in "list"
2951 * belonging to the DAG of "root" and referenced once. If NULL "root"
2952 * is specified, every finalization function will be called regardless
2953 * of the reference count and the list elements won't be freed. All of
2954 * the objects are expected to have non-NULL fini functions.
2957 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
2960 struct dlerror_save *saved_msg;
2961 Elf_Addr *fini_addr;
2964 assert(root == NULL || root->refcount == 1);
2967 root->doomed = true;
2970 * Preserve the current error message since a fini function might
2971 * call into the dynamic linker and overwrite it.
2973 saved_msg = errmsg_save();
2975 STAILQ_FOREACH(elm, list, link) {
2976 if (root != NULL && (elm->obj->refcount != 1 ||
2977 objlist_find(&root->dagmembers, elm->obj) == NULL))
2979 /* Remove object from fini list to prevent recursive invocation. */
2980 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2981 /* Ensure that new references cannot be acquired. */
2982 elm->obj->doomed = true;
2984 hold_object(elm->obj);
2985 lock_release(rtld_bind_lock, lockstate);
2987 * It is legal to have both DT_FINI and DT_FINI_ARRAY defined.
2988 * When this happens, DT_FINI_ARRAY is processed first.
2990 fini_addr = (Elf_Addr *)elm->obj->fini_array;
2991 if (fini_addr != NULL && elm->obj->fini_array_num > 0) {
2992 for (index = elm->obj->fini_array_num - 1; index >= 0;
2994 if (fini_addr[index] != 0 && fini_addr[index] != 1) {
2995 dbg("calling fini function for %s at %p",
2996 elm->obj->path, (void *)fini_addr[index]);
2997 LD_UTRACE(UTRACE_FINI_CALL, elm->obj,
2998 (void *)fini_addr[index], 0, 0, elm->obj->path);
2999 call_initfini_pointer(elm->obj, fini_addr[index]);
3003 if (elm->obj->fini != (Elf_Addr)NULL) {
3004 dbg("calling fini function for %s at %p", elm->obj->path,
3005 (void *)elm->obj->fini);
3006 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini,
3007 0, 0, elm->obj->path);
3008 call_initfini_pointer(elm->obj, elm->obj->fini);
3010 wlock_acquire(rtld_bind_lock, lockstate);
3011 unhold_object(elm->obj);
3012 /* No need to free anything if process is going down. */
3016 * We must restart the list traversal after every fini call
3017 * because a dlclose() call from the fini function or from
3018 * another thread might have modified the reference counts.
3022 } while (elm != NULL);
3023 errmsg_restore(saved_msg);
3027 * Call the initialization functions for each of the objects in
3028 * "list". All of the objects are expected to have non-NULL init
3032 objlist_call_init(Objlist *list, RtldLockState *lockstate)
3036 struct dlerror_save *saved_msg;
3037 Elf_Addr *init_addr;
3038 void (*reg)(void (*)(void));
3042 * Clean init_scanned flag so that objects can be rechecked and
3043 * possibly initialized earlier if any of vectors called below
3044 * cause the change by using dlopen.
3046 TAILQ_FOREACH(obj, &obj_list, next) {
3049 obj->init_scanned = false;
3053 * Preserve the current error message since an init function might
3054 * call into the dynamic linker and overwrite it.
3056 saved_msg = errmsg_save();
3057 STAILQ_FOREACH(elm, list, link) {
3058 if (elm->obj->init_done) /* Initialized early. */
3061 * Race: other thread might try to use this object before current
3062 * one completes the initialization. Not much can be done here
3063 * without better locking.
3065 elm->obj->init_done = true;
3066 hold_object(elm->obj);
3068 if (elm->obj == obj_main && obj_main->crt_no_init) {
3069 reg = (void (*)(void (*)(void)))get_program_var_addr(
3070 "__libc_atexit", lockstate);
3072 lock_release(rtld_bind_lock, lockstate);
3075 rtld_exit_ptr = rtld_nop_exit;
3079 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined.
3080 * When this happens, DT_INIT is processed first.
3082 if (elm->obj->init != (Elf_Addr)NULL) {
3083 dbg("calling init function for %s at %p", elm->obj->path,
3084 (void *)elm->obj->init);
3085 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init,
3086 0, 0, elm->obj->path);
3087 call_init_pointer(elm->obj, elm->obj->init);
3089 init_addr = (Elf_Addr *)elm->obj->init_array;
3090 if (init_addr != NULL) {
3091 for (index = 0; index < elm->obj->init_array_num; index++) {
3092 if (init_addr[index] != 0 && init_addr[index] != 1) {
3093 dbg("calling init function for %s at %p", elm->obj->path,
3094 (void *)init_addr[index]);
3095 LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
3096 (void *)init_addr[index], 0, 0, elm->obj->path);
3097 call_init_pointer(elm->obj, init_addr[index]);
3101 wlock_acquire(rtld_bind_lock, lockstate);
3102 unhold_object(elm->obj);
3104 errmsg_restore(saved_msg);
3108 objlist_clear(Objlist *list)
3112 while (!STAILQ_EMPTY(list)) {
3113 elm = STAILQ_FIRST(list);
3114 STAILQ_REMOVE_HEAD(list, link);
3119 static Objlist_Entry *
3120 objlist_find(Objlist *list, const Obj_Entry *obj)
3124 STAILQ_FOREACH(elm, list, link)
3125 if (elm->obj == obj)
3131 objlist_init(Objlist *list)
3137 objlist_push_head(Objlist *list, Obj_Entry *obj)
3141 elm = NEW(Objlist_Entry);
3143 STAILQ_INSERT_HEAD(list, elm, link);
3147 objlist_push_tail(Objlist *list, Obj_Entry *obj)
3151 elm = NEW(Objlist_Entry);
3153 STAILQ_INSERT_TAIL(list, elm, link);
3157 objlist_put_after(Objlist *list, Obj_Entry *listobj, Obj_Entry *obj)
3159 Objlist_Entry *elm, *listelm;
3161 STAILQ_FOREACH(listelm, list, link) {
3162 if (listelm->obj == listobj)
3165 elm = NEW(Objlist_Entry);
3167 if (listelm != NULL)
3168 STAILQ_INSERT_AFTER(list, listelm, elm, link);
3170 STAILQ_INSERT_TAIL(list, elm, link);
3174 objlist_remove(Objlist *list, Obj_Entry *obj)
3178 if ((elm = objlist_find(list, obj)) != NULL) {
3179 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
3185 * Relocate dag rooted in the specified object.
3186 * Returns 0 on success, or -1 on failure.
3190 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj,
3191 int flags, RtldLockState *lockstate)
3197 STAILQ_FOREACH(elm, &root->dagmembers, link) {
3198 error = relocate_object(elm->obj, bind_now, rtldobj, flags,
3207 * Prepare for, or clean after, relocating an object marked with
3208 * DT_TEXTREL or DF_TEXTREL. Before relocating, all read-only
3209 * segments are remapped read-write. After relocations are done, the
3210 * segment's permissions are returned back to the modes specified in
3211 * the phdrs. If any relocation happened, or always for wired
3212 * program, COW is triggered.
3215 reloc_textrel_prot(Obj_Entry *obj, bool before)
3222 for (l = obj->phsize / sizeof(*ph), ph = obj->phdr; l > 0;
3224 if (ph->p_type != PT_LOAD || (ph->p_flags & PF_W) != 0)
3226 base = obj->relocbase + rtld_trunc_page(ph->p_vaddr);
3227 sz = rtld_round_page(ph->p_vaddr + ph->p_filesz) -
3228 rtld_trunc_page(ph->p_vaddr);
3229 prot = before ? (PROT_READ | PROT_WRITE) :
3230 convert_prot(ph->p_flags);
3231 if (mprotect(base, sz, prot) == -1) {
3232 _rtld_error("%s: Cannot write-%sable text segment: %s",
3233 obj->path, before ? "en" : "dis",
3234 rtld_strerror(errno));
3241 /* Process RELR relative relocations. */
3243 reloc_relr(Obj_Entry *obj)
3245 const Elf_Relr *relr, *relrlim;
3248 relrlim = (const Elf_Relr *)((const char *)obj->relr + obj->relrsize);
3249 for (relr = obj->relr; relr < relrlim; relr++) {
3250 Elf_Relr entry = *relr;
3252 if ((entry & 1) == 0) {
3253 where = (Elf_Addr *)(obj->relocbase + entry);
3254 *where++ += (Elf_Addr)obj->relocbase;
3256 for (long i = 0; (entry >>= 1) != 0; i++)
3257 if ((entry & 1) != 0)
3258 where[i] += (Elf_Addr)obj->relocbase;
3259 where += CHAR_BIT * sizeof(Elf_Relr) - 1;
3265 * Relocate single object.
3266 * Returns 0 on success, or -1 on failure.
3269 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
3270 int flags, RtldLockState *lockstate)
3275 obj->relocated = true;
3277 dbg("relocating \"%s\"", obj->path);
3279 if (obj->symtab == NULL || obj->strtab == NULL ||
3280 !(obj->valid_hash_sysv || obj->valid_hash_gnu))
3281 dbg("object %s has no run-time symbol table", obj->path);
3283 /* There are relocations to the write-protected text segment. */
3284 if (obj->textrel && reloc_textrel_prot(obj, true) != 0)
3287 /* Process the non-PLT non-IFUNC relocations. */
3288 if (reloc_non_plt(obj, rtldobj, flags, lockstate))
3292 /* Re-protected the text segment. */
3293 if (obj->textrel && reloc_textrel_prot(obj, false) != 0)
3296 /* Set the special PLT or GOT entries. */
3299 /* Process the PLT relocations. */
3300 if (reloc_plt(obj, flags, lockstate) == -1)
3302 /* Relocate the jump slots if we are doing immediate binding. */
3303 if ((obj->bind_now || bind_now) && reloc_jmpslots(obj, flags,
3307 if (!obj->mainprog && obj_enforce_relro(obj) == -1)
3311 * Set up the magic number and version in the Obj_Entry. These
3312 * were checked in the crt1.o from the original ElfKit, so we
3313 * set them for backward compatibility.
3315 obj->magic = RTLD_MAGIC;
3316 obj->version = RTLD_VERSION;
3322 * Relocate newly-loaded shared objects. The argument is a pointer to
3323 * the Obj_Entry for the first such object. All objects from the first
3324 * to the end of the list of objects are relocated. Returns 0 on success,
3328 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
3329 int flags, RtldLockState *lockstate)
3334 for (error = 0, obj = first; obj != NULL;
3335 obj = TAILQ_NEXT(obj, next)) {
3338 error = relocate_object(obj, bind_now, rtldobj, flags,
3347 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
3348 * referencing STT_GNU_IFUNC symbols is postponed till the other
3349 * relocations are done. The indirect functions specified as
3350 * ifunc are allowed to call other symbols, so we need to have
3351 * objects relocated before asking for resolution from indirects.
3353 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
3354 * instead of the usual lazy handling of PLT slots. It is
3355 * consistent with how GNU does it.
3358 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags,
3359 RtldLockState *lockstate)
3362 if (obj->ifuncs_resolved)
3364 obj->ifuncs_resolved = true;
3365 if (!obj->irelative && !obj->irelative_nonplt &&
3366 !((obj->bind_now || bind_now) && obj->gnu_ifunc) &&
3367 !obj->non_plt_gnu_ifunc)
3369 if (obj_disable_relro(obj) == -1 ||
3370 (obj->irelative && reloc_iresolve(obj, lockstate) == -1) ||
3371 (obj->irelative_nonplt && reloc_iresolve_nonplt(obj,
3372 lockstate) == -1) ||
3373 ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
3374 reloc_gnu_ifunc(obj, flags, lockstate) == -1) ||
3375 (obj->non_plt_gnu_ifunc && reloc_non_plt(obj, &obj_rtld,
3376 flags | SYMLOOK_IFUNC, lockstate) == -1) ||
3377 obj_enforce_relro(obj) == -1)
3383 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags,
3384 RtldLockState *lockstate)
3389 STAILQ_FOREACH(elm, list, link) {
3393 if (resolve_object_ifunc(obj, bind_now, flags,
3401 * Cleanup procedure. It will be called (by the atexit mechanism) just
3402 * before the process exits.
3407 RtldLockState lockstate;
3409 wlock_acquire(rtld_bind_lock, &lockstate);
3411 objlist_call_fini(&list_fini, NULL, &lockstate);
3412 /* No need to remove the items from the list, since we are exiting. */
3413 if (!libmap_disable)
3415 lock_release(rtld_bind_lock, &lockstate);
3424 * Iterate over a search path, translate each element, and invoke the
3425 * callback on the result.
3428 path_enumerate(const char *path, path_enum_proc callback,
3429 const char *refobj_path, void *arg)
3435 path += strspn(path, ":;");
3436 while (*path != '\0') {
3440 len = strcspn(path, ":;");
3441 trans = lm_findn(refobj_path, path, len);
3443 res = callback(trans, strlen(trans), arg);
3445 res = callback(path, len, arg);
3451 path += strspn(path, ":;");
3457 struct try_library_args {
3466 try_library_path(const char *dir, size_t dirlen, void *param)
3468 struct try_library_args *arg;
3472 if (*dir == '/' || trust) {
3475 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
3478 pathname = arg->buffer;
3479 strncpy(pathname, dir, dirlen);
3480 pathname[dirlen] = '/';
3481 strcpy(pathname + dirlen + 1, arg->name);
3483 dbg(" Trying \"%s\"", pathname);
3484 fd = open(pathname, O_RDONLY | O_CLOEXEC | O_VERIFY);
3486 dbg(" Opened \"%s\", fd %d", pathname, fd);
3487 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
3488 strcpy(pathname, arg->buffer);
3492 dbg(" Failed to open \"%s\": %s",
3493 pathname, rtld_strerror(errno));
3500 search_library_path(const char *name, const char *path,
3501 const char *refobj_path, int *fdp)
3504 struct try_library_args arg;
3510 arg.namelen = strlen(name);
3511 arg.buffer = xmalloc(PATH_MAX);
3512 arg.buflen = PATH_MAX;
3515 p = path_enumerate(path, try_library_path, refobj_path, &arg);
3525 * Finds the library with the given name using the directory descriptors
3526 * listed in the LD_LIBRARY_PATH_FDS environment variable.
3528 * Returns a freshly-opened close-on-exec file descriptor for the library,
3529 * or -1 if the library cannot be found.
3532 search_library_pathfds(const char *name, const char *path, int *fdp)
3534 char *envcopy, *fdstr, *found, *last_token;
3538 dbg("%s('%s', '%s', fdp)", __func__, name, path);
3540 /* Don't load from user-specified libdirs into setuid binaries. */
3544 /* We can't do anything if LD_LIBRARY_PATH_FDS isn't set. */
3548 /* LD_LIBRARY_PATH_FDS only works with relative paths. */
3549 if (name[0] == '/') {
3550 dbg("Absolute path (%s) passed to %s", name, __func__);
3555 * Use strtok_r() to walk the FD:FD:FD list. This requires a local
3556 * copy of the path, as strtok_r rewrites separator tokens
3560 envcopy = xstrdup(path);
3561 for (fdstr = strtok_r(envcopy, ":", &last_token); fdstr != NULL;
3562 fdstr = strtok_r(NULL, ":", &last_token)) {
3563 dirfd = parse_integer(fdstr);
3565 _rtld_error("failed to parse directory FD: '%s'",
3569 fd = __sys_openat(dirfd, name, O_RDONLY | O_CLOEXEC | O_VERIFY);
3572 len = strlen(fdstr) + strlen(name) + 3;
3573 found = xmalloc(len);
3574 if (rtld_snprintf(found, len, "#%d/%s", dirfd, name) < 0) {
3575 _rtld_error("error generating '%d/%s'",
3579 dbg("open('%s') => %d", found, fd);
3590 dlclose(void *handle)
3592 RtldLockState lockstate;
3595 wlock_acquire(rtld_bind_lock, &lockstate);
3596 error = dlclose_locked(handle, &lockstate);
3597 lock_release(rtld_bind_lock, &lockstate);
3602 dlclose_locked(void *handle, RtldLockState *lockstate)
3606 root = dlcheck(handle);
3609 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
3612 /* Unreference the object and its dependencies. */
3613 root->dl_refcount--;
3615 if (root->refcount == 1) {
3617 * The object will be no longer referenced, so we must unload it.
3618 * First, call the fini functions.
3620 objlist_call_fini(&list_fini, root, lockstate);
3624 /* Finish cleaning up the newly-unreferenced objects. */
3625 GDB_STATE(RT_DELETE,&root->linkmap);
3626 unload_object(root, lockstate);
3627 GDB_STATE(RT_CONSISTENT,NULL);
3631 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
3638 if (*(lockinfo.dlerror_seen()) != 0)
3640 *lockinfo.dlerror_seen() = 1;
3641 return (lockinfo.dlerror_loc());
3645 * This function is deprecated and has no effect.
3648 dllockinit(void *context,
3649 void *(*_lock_create)(void *context) __unused,
3650 void (*_rlock_acquire)(void *lock) __unused,
3651 void (*_wlock_acquire)(void *lock) __unused,
3652 void (*_lock_release)(void *lock) __unused,
3653 void (*_lock_destroy)(void *lock) __unused,
3654 void (*context_destroy)(void *context))
3656 static void *cur_context;
3657 static void (*cur_context_destroy)(void *);
3659 /* Just destroy the context from the previous call, if necessary. */
3660 if (cur_context_destroy != NULL)
3661 cur_context_destroy(cur_context);
3662 cur_context = context;
3663 cur_context_destroy = context_destroy;
3667 dlopen(const char *name, int mode)
3670 return (rtld_dlopen(name, -1, mode));
3674 fdlopen(int fd, int mode)
3677 return (rtld_dlopen(NULL, fd, mode));
3681 rtld_dlopen(const char *name, int fd, int mode)
3683 RtldLockState lockstate;
3686 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
3687 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
3688 if (ld_tracing != NULL) {
3689 rlock_acquire(rtld_bind_lock, &lockstate);
3690 if (sigsetjmp(lockstate.env, 0) != 0)
3691 lock_upgrade(rtld_bind_lock, &lockstate);
3692 environ = __DECONST(char **, *get_program_var_addr("environ", &lockstate));
3693 lock_release(rtld_bind_lock, &lockstate);
3695 lo_flags = RTLD_LO_DLOPEN;
3696 if (mode & RTLD_NODELETE)
3697 lo_flags |= RTLD_LO_NODELETE;
3698 if (mode & RTLD_NOLOAD)
3699 lo_flags |= RTLD_LO_NOLOAD;
3700 if (mode & RTLD_DEEPBIND)
3701 lo_flags |= RTLD_LO_DEEPBIND;
3702 if (ld_tracing != NULL)
3703 lo_flags |= RTLD_LO_TRACE | RTLD_LO_IGNSTLS;
3705 return (dlopen_object(name, fd, obj_main, lo_flags,
3706 mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL));
3710 dlopen_cleanup(Obj_Entry *obj, RtldLockState *lockstate)
3715 if (obj->refcount == 0)
3716 unload_object(obj, lockstate);
3720 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
3721 int mode, RtldLockState *lockstate)
3723 Obj_Entry *old_obj_tail;
3726 RtldLockState mlockstate;
3729 dbg("dlopen_object name \"%s\" fd %d refobj \"%s\" lo_flags %#x mode %#x",
3730 name != NULL ? name : "<null>", fd, refobj == NULL ? "<null>" :
3731 refobj->path, lo_flags, mode);
3732 objlist_init(&initlist);
3734 if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) {
3735 wlock_acquire(rtld_bind_lock, &mlockstate);
3736 lockstate = &mlockstate;
3738 GDB_STATE(RT_ADD,NULL);
3740 old_obj_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
3742 if (name == NULL && fd == -1) {
3746 obj = load_object(name, fd, refobj, lo_flags);
3751 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
3752 objlist_push_tail(&list_global, obj);
3753 if (globallist_next(old_obj_tail) != NULL) {
3754 /* We loaded something new. */
3755 assert(globallist_next(old_obj_tail) == obj);
3756 if ((lo_flags & RTLD_LO_DEEPBIND) != 0)
3757 obj->symbolic = true;
3759 if ((lo_flags & (RTLD_LO_EARLY | RTLD_LO_IGNSTLS)) == 0 &&
3760 obj->static_tls && !allocate_tls_offset(obj)) {
3761 _rtld_error("%s: No space available "
3762 "for static Thread Local Storage", obj->path);
3766 result = load_needed_objects(obj, lo_flags & (RTLD_LO_DLOPEN |
3767 RTLD_LO_EARLY | RTLD_LO_IGNSTLS | RTLD_LO_TRACE));
3771 result = rtld_verify_versions(&obj->dagmembers);
3772 if (result != -1 && ld_tracing)
3774 if (result == -1 || relocate_object_dag(obj,
3775 (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld,
3776 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3778 dlopen_cleanup(obj, lockstate);
3780 } else if (lo_flags & RTLD_LO_EARLY) {
3782 * Do not call the init functions for early loaded
3783 * filtees. The image is still not initialized enough
3786 * Our object is found by the global object list and
3787 * will be ordered among all init calls done right
3788 * before transferring control to main.
3791 /* Make list of init functions to call. */
3792 initlist_add_objects(obj, obj, &initlist);
3795 * Process all no_delete or global objects here, given
3796 * them own DAGs to prevent their dependencies from being
3797 * unloaded. This has to be done after we have loaded all
3798 * of the dependencies, so that we do not miss any.
3804 * Bump the reference counts for objects on this DAG. If
3805 * this is the first dlopen() call for the object that was
3806 * already loaded as a dependency, initialize the dag
3812 if ((lo_flags & RTLD_LO_TRACE) != 0)
3815 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
3816 obj->z_nodelete) && !obj->ref_nodel) {
3817 dbg("obj %s nodelete", obj->path);
3819 obj->z_nodelete = obj->ref_nodel = true;
3823 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
3825 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
3827 if ((lo_flags & RTLD_LO_EARLY) == 0) {
3828 map_stacks_exec(lockstate);
3830 distribute_static_tls(&initlist, lockstate);
3833 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
3834 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3836 objlist_clear(&initlist);
3837 dlopen_cleanup(obj, lockstate);
3838 if (lockstate == &mlockstate)
3839 lock_release(rtld_bind_lock, lockstate);
3843 if (!(lo_flags & RTLD_LO_EARLY)) {
3844 /* Call the init functions. */
3845 objlist_call_init(&initlist, lockstate);
3847 objlist_clear(&initlist);
3848 if (lockstate == &mlockstate)
3849 lock_release(rtld_bind_lock, lockstate);
3852 trace_loaded_objects(obj, false);
3853 if (lockstate == &mlockstate)
3854 lock_release(rtld_bind_lock, lockstate);
3859 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
3863 const Obj_Entry *obj, *defobj;
3866 RtldLockState lockstate;
3873 symlook_init(&req, name);
3875 req.flags = flags | SYMLOOK_IN_PLT;
3876 req.lockstate = &lockstate;
3878 LD_UTRACE(UTRACE_DLSYM_START, handle, NULL, 0, 0, name);
3879 rlock_acquire(rtld_bind_lock, &lockstate);
3880 if (sigsetjmp(lockstate.env, 0) != 0)
3881 lock_upgrade(rtld_bind_lock, &lockstate);
3882 if (handle == NULL || handle == RTLD_NEXT ||
3883 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
3885 if ((obj = obj_from_addr(retaddr)) == NULL) {
3886 _rtld_error("Cannot determine caller's shared object");
3887 lock_release(rtld_bind_lock, &lockstate);
3888 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3891 if (handle == NULL) { /* Just the caller's shared object. */
3892 res = symlook_obj(&req, obj);
3895 defobj = req.defobj_out;
3897 } else if (handle == RTLD_NEXT || /* Objects after caller's */
3898 handle == RTLD_SELF) { /* ... caller included */
3899 if (handle == RTLD_NEXT)
3900 obj = globallist_next(obj);
3901 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
3904 res = symlook_obj(&req, obj);
3906 if (def == NULL || (ld_dynamic_weak &&
3907 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK)) {
3909 defobj = req.defobj_out;
3910 if (!ld_dynamic_weak ||
3911 ELF_ST_BIND(def->st_info) != STB_WEAK)
3917 * Search the dynamic linker itself, and possibly resolve the
3918 * symbol from there. This is how the application links to
3919 * dynamic linker services such as dlopen.
3920 * Note that we ignore ld_dynamic_weak == false case,
3921 * always overriding weak symbols by rtld definitions.
3923 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3924 res = symlook_obj(&req, &obj_rtld);
3927 defobj = req.defobj_out;
3931 assert(handle == RTLD_DEFAULT);
3932 res = symlook_default(&req, obj);
3934 defobj = req.defobj_out;
3939 if ((obj = dlcheck(handle)) == NULL) {
3940 lock_release(rtld_bind_lock, &lockstate);
3941 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3945 donelist_init(&donelist);
3946 if (obj->mainprog) {
3947 /* Handle obtained by dlopen(NULL, ...) implies global scope. */
3948 res = symlook_global(&req, &donelist);
3951 defobj = req.defobj_out;
3954 * Search the dynamic linker itself, and possibly resolve the
3955 * symbol from there. This is how the application links to
3956 * dynamic linker services such as dlopen.
3958 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3959 res = symlook_obj(&req, &obj_rtld);
3962 defobj = req.defobj_out;
3967 /* Search the whole DAG rooted at the given object. */
3968 res = symlook_list(&req, &obj->dagmembers, &donelist);
3971 defobj = req.defobj_out;
3977 lock_release(rtld_bind_lock, &lockstate);
3980 * The value required by the caller is derived from the value
3981 * of the symbol. this is simply the relocated value of the
3984 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
3985 sym = make_function_pointer(def, defobj);
3986 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
3987 sym = rtld_resolve_ifunc(defobj, def);
3988 else if (ELF_ST_TYPE(def->st_info) == STT_TLS) {
3989 ti.ti_module = defobj->tlsindex;
3990 ti.ti_offset = def->st_value;
3991 sym = __tls_get_addr(&ti);
3993 sym = defobj->relocbase + def->st_value;
3994 LD_UTRACE(UTRACE_DLSYM_STOP, handle, sym, 0, 0, name);
3998 _rtld_error("Undefined symbol \"%s%s%s\"", name, ve != NULL ? "@" : "",
3999 ve != NULL ? ve->name : "");
4000 lock_release(rtld_bind_lock, &lockstate);
4001 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
4006 dlsym(void *handle, const char *name)
4008 return (do_dlsym(handle, name, __builtin_return_address(0), NULL,
4013 dlfunc(void *handle, const char *name)
4020 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
4026 dlvsym(void *handle, const char *name, const char *version)
4030 ventry.name = version;
4032 ventry.hash = elf_hash(version);
4034 return (do_dlsym(handle, name, __builtin_return_address(0), &ventry,
4039 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
4041 const Obj_Entry *obj;
4042 RtldLockState lockstate;
4044 rlock_acquire(rtld_bind_lock, &lockstate);
4045 obj = obj_from_addr(addr);
4047 _rtld_error("No shared object contains address");
4048 lock_release(rtld_bind_lock, &lockstate);
4051 rtld_fill_dl_phdr_info(obj, phdr_info);
4052 lock_release(rtld_bind_lock, &lockstate);
4057 dladdr(const void *addr, Dl_info *info)
4059 const Obj_Entry *obj;
4062 unsigned long symoffset;
4063 RtldLockState lockstate;
4065 rlock_acquire(rtld_bind_lock, &lockstate);
4066 obj = obj_from_addr(addr);
4068 _rtld_error("No shared object contains address");
4069 lock_release(rtld_bind_lock, &lockstate);
4072 info->dli_fname = obj->path;
4073 info->dli_fbase = obj->mapbase;
4074 info->dli_saddr = (void *)0;
4075 info->dli_sname = NULL;
4078 * Walk the symbol list looking for the symbol whose address is
4079 * closest to the address sent in.
4081 for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) {
4082 def = obj->symtab + symoffset;
4085 * For skip the symbol if st_shndx is either SHN_UNDEF or
4088 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
4092 * If the symbol is greater than the specified address, or if it
4093 * is further away from addr than the current nearest symbol,
4096 symbol_addr = obj->relocbase + def->st_value;
4097 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
4100 /* Update our idea of the nearest symbol. */
4101 info->dli_sname = obj->strtab + def->st_name;
4102 info->dli_saddr = symbol_addr;
4105 if (info->dli_saddr == addr)
4108 lock_release(rtld_bind_lock, &lockstate);
4113 dlinfo(void *handle, int request, void *p)
4115 const Obj_Entry *obj;
4116 RtldLockState lockstate;
4119 rlock_acquire(rtld_bind_lock, &lockstate);
4121 if (handle == NULL || handle == RTLD_SELF) {
4124 retaddr = __builtin_return_address(0); /* __GNUC__ only */
4125 if ((obj = obj_from_addr(retaddr)) == NULL)
4126 _rtld_error("Cannot determine caller's shared object");
4128 obj = dlcheck(handle);
4131 lock_release(rtld_bind_lock, &lockstate);
4137 case RTLD_DI_LINKMAP:
4138 *((struct link_map const **)p) = &obj->linkmap;
4140 case RTLD_DI_ORIGIN:
4141 error = rtld_dirname(obj->path, p);
4144 case RTLD_DI_SERINFOSIZE:
4145 case RTLD_DI_SERINFO:
4146 error = do_search_info(obj, request, (struct dl_serinfo *)p);
4150 _rtld_error("Invalid request %d passed to dlinfo()", request);
4154 lock_release(rtld_bind_lock, &lockstate);
4160 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
4164 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
4165 phdr_info->dlpi_name = obj->path;
4166 phdr_info->dlpi_phdr = obj->phdr;
4167 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
4168 phdr_info->dlpi_tls_modid = obj->tlsindex;
4169 dtvp = &_tcb_get()->tcb_dtv;
4170 phdr_info->dlpi_tls_data = (char *)tls_get_addr_slow(dtvp,
4171 obj->tlsindex, 0, true) + TLS_DTV_OFFSET;
4172 phdr_info->dlpi_adds = obj_loads;
4173 phdr_info->dlpi_subs = obj_loads - obj_count;
4177 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
4179 struct dl_phdr_info phdr_info;
4180 Obj_Entry *obj, marker;
4181 RtldLockState bind_lockstate, phdr_lockstate;
4184 init_marker(&marker);
4187 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
4188 wlock_acquire(rtld_bind_lock, &bind_lockstate);
4189 for (obj = globallist_curr(TAILQ_FIRST(&obj_list)); obj != NULL;) {
4190 TAILQ_INSERT_AFTER(&obj_list, obj, &marker, next);
4191 rtld_fill_dl_phdr_info(obj, &phdr_info);
4193 lock_release(rtld_bind_lock, &bind_lockstate);
4195 error = callback(&phdr_info, sizeof phdr_info, param);
4197 wlock_acquire(rtld_bind_lock, &bind_lockstate);
4199 obj = globallist_next(&marker);
4200 TAILQ_REMOVE(&obj_list, &marker, next);
4202 lock_release(rtld_bind_lock, &bind_lockstate);
4203 lock_release(rtld_phdr_lock, &phdr_lockstate);
4209 rtld_fill_dl_phdr_info(&obj_rtld, &phdr_info);
4210 lock_release(rtld_bind_lock, &bind_lockstate);
4211 error = callback(&phdr_info, sizeof(phdr_info), param);
4213 lock_release(rtld_phdr_lock, &phdr_lockstate);
4218 fill_search_info(const char *dir, size_t dirlen, void *param)
4220 struct fill_search_info_args *arg;
4224 if (arg->request == RTLD_DI_SERINFOSIZE) {
4225 arg->serinfo->dls_cnt ++;
4226 arg->serinfo->dls_size += sizeof(struct dl_serpath) + dirlen + 1;
4228 struct dl_serpath *s_entry;
4230 s_entry = arg->serpath;
4231 s_entry->dls_name = arg->strspace;
4232 s_entry->dls_flags = arg->flags;
4234 strncpy(arg->strspace, dir, dirlen);
4235 arg->strspace[dirlen] = '\0';
4237 arg->strspace += dirlen + 1;
4245 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
4247 struct dl_serinfo _info;
4248 struct fill_search_info_args args;
4250 args.request = RTLD_DI_SERINFOSIZE;
4251 args.serinfo = &_info;
4253 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
4256 path_enumerate(obj->rpath, fill_search_info, NULL, &args);
4257 path_enumerate(ld_library_path, fill_search_info, NULL, &args);
4258 path_enumerate(obj->runpath, fill_search_info, NULL, &args);
4259 path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args);
4260 if (!obj->z_nodeflib)
4261 path_enumerate(ld_standard_library_path, fill_search_info, NULL, &args);
4264 if (request == RTLD_DI_SERINFOSIZE) {
4265 info->dls_size = _info.dls_size;
4266 info->dls_cnt = _info.dls_cnt;
4270 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
4271 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
4275 args.request = RTLD_DI_SERINFO;
4276 args.serinfo = info;
4277 args.serpath = &info->dls_serpath[0];
4278 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
4280 args.flags = LA_SER_RUNPATH;
4281 if (path_enumerate(obj->rpath, fill_search_info, NULL, &args) != NULL)
4284 args.flags = LA_SER_LIBPATH;
4285 if (path_enumerate(ld_library_path, fill_search_info, NULL, &args) != NULL)
4288 args.flags = LA_SER_RUNPATH;
4289 if (path_enumerate(obj->runpath, fill_search_info, NULL, &args) != NULL)
4292 args.flags = LA_SER_CONFIG;
4293 if (path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args)
4297 args.flags = LA_SER_DEFAULT;
4298 if (!obj->z_nodeflib && path_enumerate(ld_standard_library_path,
4299 fill_search_info, NULL, &args) != NULL)
4305 rtld_dirname(const char *path, char *bname)
4309 /* Empty or NULL string gets treated as "." */
4310 if (path == NULL || *path == '\0') {
4316 /* Strip trailing slashes */
4317 endp = path + strlen(path) - 1;
4318 while (endp > path && *endp == '/')
4321 /* Find the start of the dir */
4322 while (endp > path && *endp != '/')
4325 /* Either the dir is "/" or there are no slashes */
4327 bname[0] = *endp == '/' ? '/' : '.';
4333 } while (endp > path && *endp == '/');
4336 if (endp - path + 2 > PATH_MAX)
4338 _rtld_error("Filename is too long: %s", path);
4342 strncpy(bname, path, endp - path + 1);
4343 bname[endp - path + 1] = '\0';
4348 rtld_dirname_abs(const char *path, char *base)
4352 if (realpath(path, base) == NULL) {
4353 _rtld_error("realpath \"%s\" failed (%s)", path,
4354 rtld_strerror(errno));
4357 dbg("%s -> %s", path, base);
4358 last = strrchr(base, '/');
4360 _rtld_error("non-abs result from realpath \"%s\"", path);
4369 linkmap_add(Obj_Entry *obj)
4371 struct link_map *l, *prev;
4374 l->l_name = obj->path;
4375 l->l_base = obj->mapbase;
4376 l->l_ld = obj->dynamic;
4377 l->l_addr = obj->relocbase;
4379 if (r_debug.r_map == NULL) {
4385 * Scan to the end of the list, but not past the entry for the
4386 * dynamic linker, which we want to keep at the very end.
4388 for (prev = r_debug.r_map;
4389 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
4390 prev = prev->l_next)
4393 /* Link in the new entry. */
4395 l->l_next = prev->l_next;
4396 if (l->l_next != NULL)
4397 l->l_next->l_prev = l;
4402 linkmap_delete(Obj_Entry *obj)
4407 if (l->l_prev == NULL) {
4408 if ((r_debug.r_map = l->l_next) != NULL)
4409 l->l_next->l_prev = NULL;
4413 if ((l->l_prev->l_next = l->l_next) != NULL)
4414 l->l_next->l_prev = l->l_prev;
4418 * Function for the debugger to set a breakpoint on to gain control.
4420 * The two parameters allow the debugger to easily find and determine
4421 * what the runtime loader is doing and to whom it is doing it.
4423 * When the loadhook trap is hit (r_debug_state, set at program
4424 * initialization), the arguments can be found on the stack:
4426 * +8 struct link_map *m
4427 * +4 struct r_debug *rd
4431 r_debug_state(struct r_debug* rd __unused, struct link_map *m __unused)
4434 * The following is a hack to force the compiler to emit calls to
4435 * this function, even when optimizing. If the function is empty,
4436 * the compiler is not obliged to emit any code for calls to it,
4437 * even when marked __noinline. However, gdb depends on those
4440 __compiler_membar();
4444 * A function called after init routines have completed. This can be used to
4445 * break before a program's entry routine is called, and can be used when
4446 * main is not available in the symbol table.
4449 _r_debug_postinit(struct link_map *m __unused)
4452 /* See r_debug_state(). */
4453 __compiler_membar();
4457 release_object(Obj_Entry *obj)
4460 if (obj->holdcount > 0) {
4461 obj->unholdfree = true;
4464 munmap(obj->mapbase, obj->mapsize);
4465 linkmap_delete(obj);
4470 * Get address of the pointer variable in the main program.
4471 * Prefer non-weak symbol over the weak one.
4473 static const void **
4474 get_program_var_addr(const char *name, RtldLockState *lockstate)
4479 symlook_init(&req, name);
4480 req.lockstate = lockstate;
4481 donelist_init(&donelist);
4482 if (symlook_global(&req, &donelist) != 0)
4484 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
4485 return ((const void **)make_function_pointer(req.sym_out,
4487 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
4488 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
4490 return ((const void **)(req.defobj_out->relocbase +
4491 req.sym_out->st_value));
4495 * Set a pointer variable in the main program to the given value. This
4496 * is used to set key variables such as "environ" before any of the
4497 * init functions are called.
4500 set_program_var(const char *name, const void *value)
4504 if ((addr = get_program_var_addr(name, NULL)) != NULL) {
4505 dbg("\"%s\": *%p <-- %p", name, addr, value);
4511 * Search the global objects, including dependencies and main object,
4512 * for the given symbol.
4515 symlook_global(SymLook *req, DoneList *donelist)
4518 const Objlist_Entry *elm;
4521 symlook_init_from_req(&req1, req);
4523 /* Search all objects loaded at program start up. */
4524 if (req->defobj_out == NULL || (ld_dynamic_weak &&
4525 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK)) {
4526 res = symlook_list(&req1, &list_main, donelist);
4527 if (res == 0 && (!ld_dynamic_weak || req->defobj_out == NULL ||
4528 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4529 req->sym_out = req1.sym_out;
4530 req->defobj_out = req1.defobj_out;
4531 assert(req->defobj_out != NULL);
4535 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
4536 STAILQ_FOREACH(elm, &list_global, link) {
4537 if (req->defobj_out != NULL && (!ld_dynamic_weak ||
4538 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK))
4540 res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
4541 if (res == 0 && (req->defobj_out == NULL ||
4542 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4543 req->sym_out = req1.sym_out;
4544 req->defobj_out = req1.defobj_out;
4545 assert(req->defobj_out != NULL);
4549 return (req->sym_out != NULL ? 0 : ESRCH);
4553 * Given a symbol name in a referencing object, find the corresponding
4554 * definition of the symbol. Returns a pointer to the symbol, or NULL if
4555 * no definition was found. Returns a pointer to the Obj_Entry of the
4556 * defining object via the reference parameter DEFOBJ_OUT.
4559 symlook_default(SymLook *req, const Obj_Entry *refobj)
4562 const Objlist_Entry *elm;
4566 donelist_init(&donelist);
4567 symlook_init_from_req(&req1, req);
4570 * Look first in the referencing object if linked symbolically,
4571 * and similarly handle protected symbols.
4573 res = symlook_obj(&req1, refobj);
4574 if (res == 0 && (refobj->symbolic ||
4575 ELF_ST_VISIBILITY(req1.sym_out->st_other) == STV_PROTECTED)) {
4576 req->sym_out = req1.sym_out;
4577 req->defobj_out = req1.defobj_out;
4578 assert(req->defobj_out != NULL);
4580 if (refobj->symbolic || req->defobj_out != NULL)
4581 donelist_check(&donelist, refobj);
4583 symlook_global(req, &donelist);
4585 /* Search all dlopened DAGs containing the referencing object. */
4586 STAILQ_FOREACH(elm, &refobj->dldags, link) {
4587 if (req->sym_out != NULL && (!ld_dynamic_weak ||
4588 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK))
4590 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
4591 if (res == 0 && (req->sym_out == NULL ||
4592 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4593 req->sym_out = req1.sym_out;
4594 req->defobj_out = req1.defobj_out;
4595 assert(req->defobj_out != NULL);
4600 * Search the dynamic linker itself, and possibly resolve the
4601 * symbol from there. This is how the application links to
4602 * dynamic linker services such as dlopen.
4604 if (req->sym_out == NULL ||
4605 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
4606 res = symlook_obj(&req1, &obj_rtld);
4608 req->sym_out = req1.sym_out;
4609 req->defobj_out = req1.defobj_out;
4610 assert(req->defobj_out != NULL);
4614 return (req->sym_out != NULL ? 0 : ESRCH);
4618 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
4621 const Obj_Entry *defobj;
4622 const Objlist_Entry *elm;
4628 STAILQ_FOREACH(elm, objlist, link) {
4629 if (donelist_check(dlp, elm->obj))
4631 symlook_init_from_req(&req1, req);
4632 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
4633 if (def == NULL || (ld_dynamic_weak &&
4634 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4636 defobj = req1.defobj_out;
4637 if (!ld_dynamic_weak || ELF_ST_BIND(def->st_info) != STB_WEAK)
4644 req->defobj_out = defobj;
4651 * Search the chain of DAGS cointed to by the given Needed_Entry
4652 * for a symbol of the given name. Each DAG is scanned completely
4653 * before advancing to the next one. Returns a pointer to the symbol,
4654 * or NULL if no definition was found.
4657 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
4660 const Needed_Entry *n;
4661 const Obj_Entry *defobj;
4667 symlook_init_from_req(&req1, req);
4668 for (n = needed; n != NULL; n = n->next) {
4669 if (n->obj == NULL ||
4670 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
4672 if (def == NULL || (ld_dynamic_weak &&
4673 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4675 defobj = req1.defobj_out;
4676 if (!ld_dynamic_weak || ELF_ST_BIND(def->st_info) != STB_WEAK)
4682 req->defobj_out = defobj;
4689 * Search the symbol table of a single shared object for a symbol of
4690 * the given name and version, if requested. Returns a pointer to the
4691 * symbol, or NULL if no definition was found. If the object is
4692 * filter, return filtered symbol from filtee.
4694 * The symbol's hash value is passed in for efficiency reasons; that
4695 * eliminates many recomputations of the hash value.
4698 symlook_obj(SymLook *req, const Obj_Entry *obj)
4702 int flags, res, mres;
4705 * If there is at least one valid hash at this point, we prefer to
4706 * use the faster GNU version if available.
4708 if (obj->valid_hash_gnu)
4709 mres = symlook_obj1_gnu(req, obj);
4710 else if (obj->valid_hash_sysv)
4711 mres = symlook_obj1_sysv(req, obj);
4716 if (obj->needed_filtees != NULL) {
4717 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4718 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4719 donelist_init(&donelist);
4720 symlook_init_from_req(&req1, req);
4721 res = symlook_needed(&req1, obj->needed_filtees, &donelist);
4723 req->sym_out = req1.sym_out;
4724 req->defobj_out = req1.defobj_out;
4728 if (obj->needed_aux_filtees != NULL) {
4729 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4730 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4731 donelist_init(&donelist);
4732 symlook_init_from_req(&req1, req);
4733 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
4735 req->sym_out = req1.sym_out;
4736 req->defobj_out = req1.defobj_out;
4744 /* Symbol match routine common to both hash functions */
4746 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result,
4747 const unsigned long symnum)
4750 const Elf_Sym *symp;
4753 symp = obj->symtab + symnum;
4754 strp = obj->strtab + symp->st_name;
4756 switch (ELF_ST_TYPE(symp->st_info)) {
4762 if (symp->st_value == 0)
4766 if (symp->st_shndx != SHN_UNDEF)
4768 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
4769 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
4775 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
4778 if (req->ventry == NULL) {
4779 if (obj->versyms != NULL) {
4780 verndx = VER_NDX(obj->versyms[symnum]);
4781 if (verndx > obj->vernum) {
4783 "%s: symbol %s references wrong version %d",
4784 obj->path, obj->strtab + symnum, verndx);
4788 * If we are not called from dlsym (i.e. this
4789 * is a normal relocation from unversioned
4790 * binary), accept the symbol immediately if
4791 * it happens to have first version after this
4792 * shared object became versioned. Otherwise,
4793 * if symbol is versioned and not hidden,
4794 * remember it. If it is the only symbol with
4795 * this name exported by the shared object, it
4796 * will be returned as a match by the calling
4797 * function. If symbol is global (verndx < 2)
4798 * accept it unconditionally.
4800 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
4801 verndx == VER_NDX_GIVEN) {
4802 result->sym_out = symp;
4805 else if (verndx >= VER_NDX_GIVEN) {
4806 if ((obj->versyms[symnum] & VER_NDX_HIDDEN)
4808 if (result->vsymp == NULL)
4809 result->vsymp = symp;
4815 result->sym_out = symp;
4818 if (obj->versyms == NULL) {
4819 if (object_match_name(obj, req->ventry->name)) {
4820 _rtld_error("%s: object %s should provide version %s "
4821 "for symbol %s", obj_rtld.path, obj->path,
4822 req->ventry->name, obj->strtab + symnum);
4826 verndx = VER_NDX(obj->versyms[symnum]);
4827 if (verndx > obj->vernum) {
4828 _rtld_error("%s: symbol %s references wrong version %d",
4829 obj->path, obj->strtab + symnum, verndx);
4832 if (obj->vertab[verndx].hash != req->ventry->hash ||
4833 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
4835 * Version does not match. Look if this is a
4836 * global symbol and if it is not hidden. If
4837 * global symbol (verndx < 2) is available,
4838 * use it. Do not return symbol if we are
4839 * called by dlvsym, because dlvsym looks for
4840 * a specific version and default one is not
4841 * what dlvsym wants.
4843 if ((req->flags & SYMLOOK_DLSYM) ||
4844 (verndx >= VER_NDX_GIVEN) ||
4845 (obj->versyms[symnum] & VER_NDX_HIDDEN))
4849 result->sym_out = symp;
4854 * Search for symbol using SysV hash function.
4855 * obj->buckets is known not to be NULL at this point; the test for this was
4856 * performed with the obj->valid_hash_sysv assignment.
4859 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj)
4861 unsigned long symnum;
4862 Sym_Match_Result matchres;
4864 matchres.sym_out = NULL;
4865 matchres.vsymp = NULL;
4866 matchres.vcount = 0;
4868 for (symnum = obj->buckets[req->hash % obj->nbuckets];
4869 symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
4870 if (symnum >= obj->nchains)
4871 return (ESRCH); /* Bad object */
4873 if (matched_symbol(req, obj, &matchres, symnum)) {
4874 req->sym_out = matchres.sym_out;
4875 req->defobj_out = obj;
4879 if (matchres.vcount == 1) {
4880 req->sym_out = matchres.vsymp;
4881 req->defobj_out = obj;
4887 /* Search for symbol using GNU hash function */
4889 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj)
4891 Elf_Addr bloom_word;
4892 const Elf32_Word *hashval;
4894 Sym_Match_Result matchres;
4895 unsigned int h1, h2;
4896 unsigned long symnum;
4898 matchres.sym_out = NULL;
4899 matchres.vsymp = NULL;
4900 matchres.vcount = 0;
4902 /* Pick right bitmask word from Bloom filter array */
4903 bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) &
4904 obj->maskwords_bm_gnu];
4906 /* Calculate modulus word size of gnu hash and its derivative */
4907 h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1);
4908 h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1));
4910 /* Filter out the "definitely not in set" queries */
4911 if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0)
4914 /* Locate hash chain and corresponding value element*/
4915 bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu];
4918 hashval = &obj->chain_zero_gnu[bucket];
4920 if (((*hashval ^ req->hash_gnu) >> 1) == 0) {
4921 symnum = hashval - obj->chain_zero_gnu;
4922 if (matched_symbol(req, obj, &matchres, symnum)) {
4923 req->sym_out = matchres.sym_out;
4924 req->defobj_out = obj;
4928 } while ((*hashval++ & 1) == 0);
4929 if (matchres.vcount == 1) {
4930 req->sym_out = matchres.vsymp;
4931 req->defobj_out = obj;
4938 trace_calc_fmts(const char **main_local, const char **fmt1, const char **fmt2)
4940 *main_local = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_PROGNAME);
4941 if (*main_local == NULL)
4944 *fmt1 = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_FMT1);
4946 *fmt1 = "\t%o => %p (%x)\n";
4948 *fmt2 = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_FMT2);
4950 *fmt2 = "\t%o (%x)\n";
4954 trace_print_obj(Obj_Entry *obj, const char *name, const char *path,
4955 const char *main_local, const char *fmt1, const char *fmt2)
4960 fmt = strncmp(name, "lib", 3) == 0 ? fmt1 : fmt2; /* XXX bogus */
4961 while ((c = *fmt++) != '\0') {
4987 rtld_putstr(main_local);
4990 rtld_putstr(obj_main->path);
4999 rtld_printf("%p", obj != NULL ?
5000 obj->mapbase : NULL);
5010 trace_loaded_objects(Obj_Entry *obj, bool show_preload)
5012 const char *fmt1, *fmt2, *main_local;
5013 const char *name, *path;
5014 bool first_spurious, list_containers;
5016 trace_calc_fmts(&main_local, &fmt1, &fmt2);
5017 list_containers = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_ALL) != NULL;
5019 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
5020 Needed_Entry *needed;
5024 if (list_containers && obj->needed != NULL)
5025 rtld_printf("%s:\n", obj->path);
5026 for (needed = obj->needed; needed; needed = needed->next) {
5027 if (needed->obj != NULL) {
5028 if (needed->obj->traced && !list_containers)
5030 needed->obj->traced = true;
5031 path = needed->obj->path;
5035 name = obj->strtab + needed->name;
5036 trace_print_obj(needed->obj, name, path, main_local,
5042 first_spurious = true;
5043 TAILQ_FOREACH(obj, &obj_list, next) {
5044 if (obj->marker || obj == obj_main || obj->traced)
5047 if (first_spurious) {
5048 rtld_printf("[preloaded]\n");
5049 first_spurious = false;
5051 Name_Entry *fname = STAILQ_FIRST(&obj->names);
5052 name = fname == NULL ? "<unknown>" : fname->name;
5053 trace_print_obj(obj, name, obj->path, main_local,
5060 * Unload a dlopened object and its dependencies from memory and from
5061 * our data structures. It is assumed that the DAG rooted in the
5062 * object has already been unreferenced, and that the object has a
5063 * reference count of 0.
5066 unload_object(Obj_Entry *root, RtldLockState *lockstate)
5068 Obj_Entry marker, *obj, *next;
5070 assert(root->refcount == 0);
5073 * Pass over the DAG removing unreferenced objects from
5074 * appropriate lists.
5076 unlink_object(root);
5078 /* Unmap all objects that are no longer referenced. */
5079 for (obj = TAILQ_FIRST(&obj_list); obj != NULL; obj = next) {
5080 next = TAILQ_NEXT(obj, next);
5081 if (obj->marker || obj->refcount != 0)
5083 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase,
5084 obj->mapsize, 0, obj->path);
5085 dbg("unloading \"%s\"", obj->path);
5087 * Unlink the object now to prevent new references from
5088 * being acquired while the bind lock is dropped in
5089 * recursive dlclose() invocations.
5091 TAILQ_REMOVE(&obj_list, obj, next);
5094 if (obj->filtees_loaded) {
5096 init_marker(&marker);
5097 TAILQ_INSERT_BEFORE(next, &marker, next);
5098 unload_filtees(obj, lockstate);
5099 next = TAILQ_NEXT(&marker, next);
5100 TAILQ_REMOVE(&obj_list, &marker, next);
5102 unload_filtees(obj, lockstate);
5104 release_object(obj);
5109 unlink_object(Obj_Entry *root)
5113 if (root->refcount == 0) {
5114 /* Remove the object from the RTLD_GLOBAL list. */
5115 objlist_remove(&list_global, root);
5117 /* Remove the object from all objects' DAG lists. */
5118 STAILQ_FOREACH(elm, &root->dagmembers, link) {
5119 objlist_remove(&elm->obj->dldags, root);
5120 if (elm->obj != root)
5121 unlink_object(elm->obj);
5127 ref_dag(Obj_Entry *root)
5131 assert(root->dag_inited);
5132 STAILQ_FOREACH(elm, &root->dagmembers, link)
5133 elm->obj->refcount++;
5137 unref_dag(Obj_Entry *root)
5141 assert(root->dag_inited);
5142 STAILQ_FOREACH(elm, &root->dagmembers, link)
5143 elm->obj->refcount--;
5147 * Common code for MD __tls_get_addr().
5150 tls_get_addr_slow(Elf_Addr **dtvp, int index, size_t offset, bool locked)
5152 Elf_Addr *newdtv, *dtv;
5153 RtldLockState lockstate;
5157 /* Check dtv generation in case new modules have arrived */
5158 if (dtv[0] != tls_dtv_generation) {
5160 wlock_acquire(rtld_bind_lock, &lockstate);
5161 newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
5163 if (to_copy > tls_max_index)
5164 to_copy = tls_max_index;
5165 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
5166 newdtv[0] = tls_dtv_generation;
5167 newdtv[1] = tls_max_index;
5170 lock_release(rtld_bind_lock, &lockstate);
5171 dtv = *dtvp = newdtv;
5174 /* Dynamically allocate module TLS if necessary */
5175 if (dtv[index + 1] == 0) {
5176 /* Signal safe, wlock will block out signals. */
5178 wlock_acquire(rtld_bind_lock, &lockstate);
5179 if (!dtv[index + 1])
5180 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
5182 lock_release(rtld_bind_lock, &lockstate);
5184 return ((void *)(dtv[index + 1] + offset));
5188 tls_get_addr_common(uintptr_t **dtvp, int index, size_t offset)
5193 /* Check dtv generation in case new modules have arrived */
5194 if (__predict_true(dtv[0] == tls_dtv_generation &&
5195 dtv[index + 1] != 0))
5196 return ((void *)(dtv[index + 1] + offset));
5197 return (tls_get_addr_slow(dtvp, index, offset, false));
5200 #ifdef TLS_VARIANT_I
5203 * Return pointer to allocated TLS block
5206 get_tls_block_ptr(void *tcb, size_t tcbsize)
5208 size_t extra_size, post_size, pre_size, tls_block_size;
5209 size_t tls_init_align;
5211 tls_init_align = MAX(obj_main->tlsalign, 1);
5213 /* Compute fragments sizes. */
5214 extra_size = tcbsize - TLS_TCB_SIZE;
5215 post_size = calculate_tls_post_size(tls_init_align);
5216 tls_block_size = tcbsize + post_size;
5217 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size;
5219 return ((char *)tcb - pre_size - extra_size);
5223 * Allocate Static TLS using the Variant I method.
5225 * For details on the layout, see lib/libc/gen/tls.c.
5227 * NB: rtld's tls_static_space variable includes TLS_TCB_SIZE and post_size as
5228 * it is based on tls_last_offset, and TLS offsets here are really TCB
5229 * offsets, whereas libc's tls_static_space is just the executable's static
5233 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
5237 Elf_Addr *dtv, **tcb;
5240 size_t extra_size, maxalign, post_size, pre_size, tls_block_size;
5241 size_t tls_init_align, tls_init_offset;
5243 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
5246 assert(tcbsize >= TLS_TCB_SIZE);
5247 maxalign = MAX(tcbalign, tls_static_max_align);
5248 tls_init_align = MAX(obj_main->tlsalign, 1);
5250 /* Compute fragmets sizes. */
5251 extra_size = tcbsize - TLS_TCB_SIZE;
5252 post_size = calculate_tls_post_size(tls_init_align);
5253 tls_block_size = tcbsize + post_size;
5254 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size;
5255 tls_block_size += pre_size + tls_static_space - TLS_TCB_SIZE - post_size;
5257 /* Allocate whole TLS block */
5258 tls_block = malloc_aligned(tls_block_size, maxalign, 0);
5259 tcb = (Elf_Addr **)(tls_block + pre_size + extra_size);
5261 if (oldtcb != NULL) {
5262 memcpy(tls_block, get_tls_block_ptr(oldtcb, tcbsize),
5264 free_aligned(get_tls_block_ptr(oldtcb, tcbsize));
5266 /* Adjust the DTV. */
5268 for (i = 0; i < dtv[1]; i++) {
5269 if (dtv[i+2] >= (Elf_Addr)oldtcb &&
5270 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
5271 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tcb;
5275 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
5277 dtv[0] = tls_dtv_generation;
5278 dtv[1] = tls_max_index;
5280 for (obj = globallist_curr(objs); obj != NULL;
5281 obj = globallist_next(obj)) {
5282 if (obj->tlsoffset == 0)
5284 tls_init_offset = obj->tlspoffset & (obj->tlsalign - 1);
5285 addr = (Elf_Addr)tcb + obj->tlsoffset;
5286 if (tls_init_offset > 0)
5287 memset((void *)addr, 0, tls_init_offset);
5288 if (obj->tlsinitsize > 0) {
5289 memcpy((void *)(addr + tls_init_offset), obj->tlsinit,
5292 if (obj->tlssize > obj->tlsinitsize) {
5293 memset((void *)(addr + tls_init_offset + obj->tlsinitsize),
5294 0, obj->tlssize - obj->tlsinitsize - tls_init_offset);
5296 dtv[obj->tlsindex + 1] = addr;
5304 free_tls(void *tcb, size_t tcbsize, size_t tcbalign __unused)
5307 Elf_Addr tlsstart, tlsend;
5309 size_t dtvsize, i, tls_init_align;
5311 assert(tcbsize >= TLS_TCB_SIZE);
5312 tls_init_align = MAX(obj_main->tlsalign, 1);
5314 /* Compute fragments sizes. */
5315 post_size = calculate_tls_post_size(tls_init_align);
5317 tlsstart = (Elf_Addr)tcb + TLS_TCB_SIZE + post_size;
5318 tlsend = (Elf_Addr)tcb + tls_static_space;
5320 dtv = *(Elf_Addr **)tcb;
5322 for (i = 0; i < dtvsize; i++) {
5323 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
5324 free((void*)dtv[i+2]);
5328 free_aligned(get_tls_block_ptr(tcb, tcbsize));
5331 #endif /* TLS_VARIANT_I */
5333 #ifdef TLS_VARIANT_II
5336 * Allocate Static TLS using the Variant II method.
5339 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
5342 size_t size, ralign;
5344 Elf_Addr *dtv, *olddtv;
5345 Elf_Addr segbase, oldsegbase, addr;
5349 if (tls_static_max_align > ralign)
5350 ralign = tls_static_max_align;
5351 size = roundup(tls_static_space, ralign) + roundup(tcbsize, ralign);
5353 assert(tcbsize >= 2*sizeof(Elf_Addr));
5354 tls = malloc_aligned(size, ralign, 0 /* XXX */);
5355 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
5357 segbase = (Elf_Addr)(tls + roundup(tls_static_space, ralign));
5358 ((Elf_Addr *)segbase)[0] = segbase;
5359 ((Elf_Addr *)segbase)[1] = (Elf_Addr) dtv;
5361 dtv[0] = tls_dtv_generation;
5362 dtv[1] = tls_max_index;
5366 * Copy the static TLS block over whole.
5368 oldsegbase = (Elf_Addr) oldtls;
5369 memcpy((void *)(segbase - tls_static_space),
5370 (const void *)(oldsegbase - tls_static_space),
5374 * If any dynamic TLS blocks have been created tls_get_addr(),
5377 olddtv = ((Elf_Addr **)oldsegbase)[1];
5378 for (i = 0; i < olddtv[1]; i++) {
5379 if (olddtv[i + 2] < oldsegbase - size ||
5380 olddtv[i + 2] > oldsegbase) {
5381 dtv[i + 2] = olddtv[i + 2];
5387 * We assume that this block was the one we created with
5388 * allocate_initial_tls().
5390 free_tls(oldtls, 2 * sizeof(Elf_Addr), sizeof(Elf_Addr));
5392 for (obj = objs; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
5393 if (obj->marker || obj->tlsoffset == 0)
5395 addr = segbase - obj->tlsoffset;
5396 memset((void *)(addr + obj->tlsinitsize),
5397 0, obj->tlssize - obj->tlsinitsize);
5399 memcpy((void *)addr, obj->tlsinit, obj->tlsinitsize);
5400 obj->static_tls_copied = true;
5402 dtv[obj->tlsindex + 1] = addr;
5406 return ((void *)segbase);
5410 free_tls(void *tls, size_t tcbsize __unused, size_t tcbalign)
5413 size_t size, ralign;
5415 Elf_Addr tlsstart, tlsend;
5418 * Figure out the size of the initial TLS block so that we can
5419 * find stuff which ___tls_get_addr() allocated dynamically.
5422 if (tls_static_max_align > ralign)
5423 ralign = tls_static_max_align;
5424 size = roundup(tls_static_space, ralign);
5426 dtv = ((Elf_Addr **)tls)[1];
5428 tlsend = (Elf_Addr)tls;
5429 tlsstart = tlsend - size;
5430 for (i = 0; i < dtvsize; i++) {
5431 if (dtv[i + 2] != 0 && (dtv[i + 2] < tlsstart ||
5432 dtv[i + 2] > tlsend)) {
5433 free_aligned((void *)dtv[i + 2]);
5437 free_aligned((void *)tlsstart);
5441 #endif /* TLS_VARIANT_II */
5444 * Allocate TLS block for module with given index.
5447 allocate_module_tls(int index)
5452 TAILQ_FOREACH(obj, &obj_list, next) {
5455 if (obj->tlsindex == index)
5459 _rtld_error("Can't find module with TLS index %d", index);
5463 p = malloc_aligned(obj->tlssize, obj->tlsalign, obj->tlspoffset);
5464 memcpy(p, obj->tlsinit, obj->tlsinitsize);
5465 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
5470 allocate_tls_offset(Obj_Entry *obj)
5477 if (obj->tlssize == 0) {
5478 obj->tls_done = true;
5482 if (tls_last_offset == 0)
5483 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign,
5486 off = calculate_tls_offset(tls_last_offset, tls_last_size,
5487 obj->tlssize, obj->tlsalign, obj->tlspoffset);
5489 obj->tlsoffset = off;
5490 #ifdef TLS_VARIANT_I
5491 off += obj->tlssize;
5495 * If we have already fixed the size of the static TLS block, we
5496 * must stay within that size. When allocating the static TLS, we
5497 * leave a small amount of space spare to be used for dynamically
5498 * loading modules which use static TLS.
5500 if (tls_static_space != 0) {
5501 if (off > tls_static_space)
5503 } else if (obj->tlsalign > tls_static_max_align) {
5504 tls_static_max_align = obj->tlsalign;
5507 tls_last_offset = off;
5508 tls_last_size = obj->tlssize;
5509 obj->tls_done = true;
5515 free_tls_offset(Obj_Entry *obj)
5519 * If we were the last thing to allocate out of the static TLS
5520 * block, we give our space back to the 'allocator'. This is a
5521 * simplistic workaround to allow libGL.so.1 to be loaded and
5522 * unloaded multiple times.
5524 size_t off = obj->tlsoffset;
5525 #ifdef TLS_VARIANT_I
5526 off += obj->tlssize;
5528 if (off == tls_last_offset) {
5529 tls_last_offset -= obj->tlssize;
5535 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
5538 RtldLockState lockstate;
5540 wlock_acquire(rtld_bind_lock, &lockstate);
5541 ret = allocate_tls(globallist_curr(TAILQ_FIRST(&obj_list)), oldtls,
5543 lock_release(rtld_bind_lock, &lockstate);
5548 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
5550 RtldLockState lockstate;
5552 wlock_acquire(rtld_bind_lock, &lockstate);
5553 free_tls(tcb, tcbsize, tcbalign);
5554 lock_release(rtld_bind_lock, &lockstate);
5558 object_add_name(Obj_Entry *obj, const char *name)
5564 entry = malloc(sizeof(Name_Entry) + len);
5566 if (entry != NULL) {
5567 strcpy(entry->name, name);
5568 STAILQ_INSERT_TAIL(&obj->names, entry, link);
5573 object_match_name(const Obj_Entry *obj, const char *name)
5577 STAILQ_FOREACH(entry, &obj->names, link) {
5578 if (strcmp(name, entry->name) == 0)
5585 locate_dependency(const Obj_Entry *obj, const char *name)
5587 const Objlist_Entry *entry;
5588 const Needed_Entry *needed;
5590 STAILQ_FOREACH(entry, &list_main, link) {
5591 if (object_match_name(entry->obj, name))
5592 return (entry->obj);
5595 for (needed = obj->needed; needed != NULL; needed = needed->next) {
5596 if (strcmp(obj->strtab + needed->name, name) == 0 ||
5597 (needed->obj != NULL && object_match_name(needed->obj, name))) {
5599 * If there is DT_NEEDED for the name we are looking for,
5600 * we are all set. Note that object might not be found if
5601 * dependency was not loaded yet, so the function can
5602 * return NULL here. This is expected and handled
5603 * properly by the caller.
5605 return (needed->obj);
5608 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
5614 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
5615 const Elf_Vernaux *vna)
5617 const Elf_Verdef *vd;
5618 const char *vername;
5620 vername = refobj->strtab + vna->vna_name;
5621 vd = depobj->verdef;
5623 _rtld_error("%s: version %s required by %s not defined",
5624 depobj->path, vername, refobj->path);
5628 if (vd->vd_version != VER_DEF_CURRENT) {
5629 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
5630 depobj->path, vd->vd_version);
5633 if (vna->vna_hash == vd->vd_hash) {
5634 const Elf_Verdaux *aux = (const Elf_Verdaux *)
5635 ((const char *)vd + vd->vd_aux);
5636 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
5639 if (vd->vd_next == 0)
5641 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5643 if (vna->vna_flags & VER_FLG_WEAK)
5645 _rtld_error("%s: version %s required by %s not found",
5646 depobj->path, vername, refobj->path);
5651 rtld_verify_object_versions(Obj_Entry *obj)
5653 const Elf_Verneed *vn;
5654 const Elf_Verdef *vd;
5655 const Elf_Verdaux *vda;
5656 const Elf_Vernaux *vna;
5657 const Obj_Entry *depobj;
5658 int maxvernum, vernum;
5660 if (obj->ver_checked)
5662 obj->ver_checked = true;
5666 * Walk over defined and required version records and figure out
5667 * max index used by any of them. Do very basic sanity checking
5671 while (vn != NULL) {
5672 if (vn->vn_version != VER_NEED_CURRENT) {
5673 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
5674 obj->path, vn->vn_version);
5677 vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux);
5679 vernum = VER_NEED_IDX(vna->vna_other);
5680 if (vernum > maxvernum)
5682 if (vna->vna_next == 0)
5684 vna = (const Elf_Vernaux *)((const char *)vna + vna->vna_next);
5686 if (vn->vn_next == 0)
5688 vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next);
5692 while (vd != NULL) {
5693 if (vd->vd_version != VER_DEF_CURRENT) {
5694 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
5695 obj->path, vd->vd_version);
5698 vernum = VER_DEF_IDX(vd->vd_ndx);
5699 if (vernum > maxvernum)
5701 if (vd->vd_next == 0)
5703 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5710 * Store version information in array indexable by version index.
5711 * Verify that object version requirements are satisfied along the
5714 obj->vernum = maxvernum + 1;
5715 obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry));
5718 while (vd != NULL) {
5719 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
5720 vernum = VER_DEF_IDX(vd->vd_ndx);
5721 assert(vernum <= maxvernum);
5722 vda = (const Elf_Verdaux *)((const char *)vd + vd->vd_aux);
5723 obj->vertab[vernum].hash = vd->vd_hash;
5724 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
5725 obj->vertab[vernum].file = NULL;
5726 obj->vertab[vernum].flags = 0;
5728 if (vd->vd_next == 0)
5730 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5734 while (vn != NULL) {
5735 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
5738 vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux);
5740 if (check_object_provided_version(obj, depobj, vna))
5742 vernum = VER_NEED_IDX(vna->vna_other);
5743 assert(vernum <= maxvernum);
5744 obj->vertab[vernum].hash = vna->vna_hash;
5745 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
5746 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
5747 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
5748 VER_INFO_HIDDEN : 0;
5749 if (vna->vna_next == 0)
5751 vna = (const Elf_Vernaux *)((const char *)vna + vna->vna_next);
5753 if (vn->vn_next == 0)
5755 vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next);
5761 rtld_verify_versions(const Objlist *objlist)
5763 Objlist_Entry *entry;
5767 STAILQ_FOREACH(entry, objlist, link) {
5769 * Skip dummy objects or objects that have their version requirements
5772 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
5774 if (rtld_verify_object_versions(entry->obj) == -1) {
5776 if (ld_tracing == NULL)
5780 if (rc == 0 || ld_tracing != NULL)
5781 rc = rtld_verify_object_versions(&obj_rtld);
5786 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
5791 vernum = VER_NDX(obj->versyms[symnum]);
5792 if (vernum >= obj->vernum) {
5793 _rtld_error("%s: symbol %s has wrong verneed value %d",
5794 obj->path, obj->strtab + symnum, vernum);
5795 } else if (obj->vertab[vernum].hash != 0) {
5796 return (&obj->vertab[vernum]);
5803 _rtld_get_stack_prot(void)
5806 return (stack_prot);
5810 _rtld_is_dlopened(void *arg)
5813 RtldLockState lockstate;
5816 rlock_acquire(rtld_bind_lock, &lockstate);
5819 obj = obj_from_addr(arg);
5821 _rtld_error("No shared object contains address");
5822 lock_release(rtld_bind_lock, &lockstate);
5825 res = obj->dlopened ? 1 : 0;
5826 lock_release(rtld_bind_lock, &lockstate);
5831 obj_remap_relro(Obj_Entry *obj, int prot)
5834 if (obj->relro_size > 0 && mprotect(obj->relro_page, obj->relro_size,
5836 _rtld_error("%s: Cannot set relro protection to %#x: %s",
5837 obj->path, prot, rtld_strerror(errno));
5844 obj_disable_relro(Obj_Entry *obj)
5847 return (obj_remap_relro(obj, PROT_READ | PROT_WRITE));
5851 obj_enforce_relro(Obj_Entry *obj)
5854 return (obj_remap_relro(obj, PROT_READ));
5858 map_stacks_exec(RtldLockState *lockstate)
5860 void (*thr_map_stacks_exec)(void);
5862 if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
5864 thr_map_stacks_exec = (void (*)(void))(uintptr_t)
5865 get_program_var_addr("__pthread_map_stacks_exec", lockstate);
5866 if (thr_map_stacks_exec != NULL) {
5867 stack_prot |= PROT_EXEC;
5868 thr_map_stacks_exec();
5873 distribute_static_tls(Objlist *list, RtldLockState *lockstate)
5877 void (*distrib)(size_t, void *, size_t, size_t);
5879 distrib = (void (*)(size_t, void *, size_t, size_t))(uintptr_t)
5880 get_program_var_addr("__pthread_distribute_static_tls", lockstate);
5881 if (distrib == NULL)
5883 STAILQ_FOREACH(elm, list, link) {
5885 if (obj->marker || !obj->tls_done || obj->static_tls_copied)
5887 distrib(obj->tlsoffset, obj->tlsinit, obj->tlsinitsize,
5889 obj->static_tls_copied = true;
5894 symlook_init(SymLook *dst, const char *name)
5897 bzero(dst, sizeof(*dst));
5899 dst->hash = elf_hash(name);
5900 dst->hash_gnu = gnu_hash(name);
5904 symlook_init_from_req(SymLook *dst, const SymLook *src)
5907 dst->name = src->name;
5908 dst->hash = src->hash;
5909 dst->hash_gnu = src->hash_gnu;
5910 dst->ventry = src->ventry;
5911 dst->flags = src->flags;
5912 dst->defobj_out = NULL;
5913 dst->sym_out = NULL;
5914 dst->lockstate = src->lockstate;
5918 open_binary_fd(const char *argv0, bool search_in_path,
5919 const char **binpath_res)
5921 char *binpath, *pathenv, *pe, *res1;
5927 if (search_in_path && strchr(argv0, '/') == NULL) {
5928 binpath = xmalloc(PATH_MAX);
5929 pathenv = getenv("PATH");
5930 if (pathenv == NULL) {
5931 _rtld_error("-p and no PATH environment variable");
5934 pathenv = strdup(pathenv);
5935 if (pathenv == NULL) {
5936 _rtld_error("Cannot allocate memory");
5941 while ((pe = strsep(&pathenv, ":")) != NULL) {
5942 if (strlcpy(binpath, pe, PATH_MAX) >= PATH_MAX)
5944 if (binpath[0] != '\0' &&
5945 strlcat(binpath, "/", PATH_MAX) >= PATH_MAX)
5947 if (strlcat(binpath, argv0, PATH_MAX) >= PATH_MAX)
5949 fd = open(binpath, O_RDONLY | O_CLOEXEC | O_VERIFY);
5950 if (fd != -1 || errno != ENOENT) {
5957 fd = open(argv0, O_RDONLY | O_CLOEXEC | O_VERIFY);
5962 _rtld_error("Cannot open %s: %s", argv0, rtld_strerror(errno));
5965 if (res != NULL && res[0] != '/') {
5966 res1 = xmalloc(PATH_MAX);
5967 if (realpath(res, res1) != NULL) {
5969 free(__DECONST(char *, res));
5980 * Parse a set of command-line arguments.
5983 parse_args(char* argv[], int argc, bool *use_pathp, int *fdp,
5984 const char **argv0, bool *dir_ignore)
5989 int arglen, fd, i, j, mib[2];
5991 bool seen_b, seen_f;
5993 dbg("Parsing command-line arguments");
5996 *dir_ignore = false;
5997 seen_b = seen_f = false;
5999 for (i = 1; i < argc; i++ ) {
6001 dbg("argv[%d]: '%s'", i, arg);
6004 * rtld arguments end with an explicit "--" or with the first
6005 * non-prefixed argument.
6007 if (strcmp(arg, "--") == 0) {
6015 * All other arguments are single-character options that can
6016 * be combined, so we need to search through `arg` for them.
6018 arglen = strlen(arg);
6019 for (j = 1; j < arglen; j++) {
6022 print_usage(argv[0]);
6024 } else if (opt == 'b') {
6026 _rtld_error("Both -b and -f specified");
6033 } else if (opt == 'd') {
6036 } else if (opt == 'f') {
6038 _rtld_error("Both -b and -f specified");
6043 * -f XX can be used to specify a
6044 * descriptor for the binary named at
6045 * the command line (i.e., the later
6046 * argument will specify the process
6047 * name but the descriptor is what
6048 * will actually be executed).
6050 * -f must be the last option in, e.g., -abcf.
6052 if (j != arglen - 1) {
6053 _rtld_error("Invalid options: %s", arg);
6057 fd = parse_integer(argv[i]);
6060 "Invalid file descriptor: '%s'",
6067 } else if (opt == 'p') {
6069 } else if (opt == 'u') {
6071 } else if (opt == 'v') {
6074 mib[1] = HW_MACHINE;
6075 sz = sizeof(machine);
6076 sysctl(mib, nitems(mib), machine, &sz, NULL, 0);
6077 ld_elf_hints_path = ld_get_env_var(
6079 set_ld_elf_hints_path();
6081 "FreeBSD ld-elf.so.1 %s\n"
6082 "FreeBSD_version %d\n"
6083 "Default lib path %s\n"
6084 "Hints lib path %s\n"
6086 "Default hint file %s\n"
6090 __FreeBSD_version, ld_standard_library_path,
6092 ld_env_prefix, ld_elf_hints_default,
6094 ld_path_libmap_conf);
6097 _rtld_error("Invalid argument: '%s'", arg);
6098 print_usage(argv[0]);
6110 * Parse a file descriptor number without pulling in more of libc (e.g. atoi).
6113 parse_integer(const char *str)
6115 static const int RADIX = 10; /* XXXJA: possibly support hex? */
6122 for (c = *str; c != '\0'; c = *++str) {
6123 if (c < '0' || c > '9')
6130 /* Make sure we actually parsed something. */
6137 print_usage(const char *argv0)
6141 "Usage: %s [-h] [-b <exe>] [-d] [-f <FD>] [-p] [--] <binary> [<args>]\n"
6144 " -h Display this help message\n"
6145 " -b <exe> Execute <exe> instead of <binary>, arg0 is <binary>\n"
6146 " -d Ignore lack of exec permissions for the binary\n"
6147 " -f <FD> Execute <FD> instead of searching for <binary>\n"
6148 " -p Search in PATH for named binary\n"
6149 " -u Ignore LD_ environment variables\n"
6150 " -v Display identification information\n"
6151 " -- End of RTLD options\n"
6152 " <binary> Name of process to execute\n"
6153 " <args> Arguments to the executed process\n", argv0);
6156 #define AUXFMT(at, xfmt) [at] = { .name = #at, .fmt = xfmt }
6157 static const struct auxfmt {
6161 AUXFMT(AT_NULL, NULL),
6162 AUXFMT(AT_IGNORE, NULL),
6163 AUXFMT(AT_EXECFD, "%ld"),
6164 AUXFMT(AT_PHDR, "%p"),
6165 AUXFMT(AT_PHENT, "%lu"),
6166 AUXFMT(AT_PHNUM, "%lu"),
6167 AUXFMT(AT_PAGESZ, "%lu"),
6168 AUXFMT(AT_BASE, "%#lx"),
6169 AUXFMT(AT_FLAGS, "%#lx"),
6170 AUXFMT(AT_ENTRY, "%p"),
6171 AUXFMT(AT_NOTELF, NULL),
6172 AUXFMT(AT_UID, "%ld"),
6173 AUXFMT(AT_EUID, "%ld"),
6174 AUXFMT(AT_GID, "%ld"),
6175 AUXFMT(AT_EGID, "%ld"),
6176 AUXFMT(AT_EXECPATH, "%s"),
6177 AUXFMT(AT_CANARY, "%p"),
6178 AUXFMT(AT_CANARYLEN, "%lu"),
6179 AUXFMT(AT_OSRELDATE, "%lu"),
6180 AUXFMT(AT_NCPUS, "%lu"),
6181 AUXFMT(AT_PAGESIZES, "%p"),
6182 AUXFMT(AT_PAGESIZESLEN, "%lu"),
6183 AUXFMT(AT_TIMEKEEP, "%p"),
6184 AUXFMT(AT_STACKPROT, "%#lx"),
6185 AUXFMT(AT_EHDRFLAGS, "%#lx"),
6186 AUXFMT(AT_HWCAP, "%#lx"),
6187 AUXFMT(AT_HWCAP2, "%#lx"),
6188 AUXFMT(AT_BSDFLAGS, "%#lx"),
6189 AUXFMT(AT_ARGC, "%lu"),
6190 AUXFMT(AT_ARGV, "%p"),
6191 AUXFMT(AT_ENVC, "%p"),
6192 AUXFMT(AT_ENVV, "%p"),
6193 AUXFMT(AT_PS_STRINGS, "%p"),
6194 AUXFMT(AT_FXRNG, "%p"),
6195 AUXFMT(AT_KPRELOAD, "%p"),
6199 is_ptr_fmt(const char *fmt)
6203 last = fmt[strlen(fmt) - 1];
6204 return (last == 'p' || last == 's');
6208 dump_auxv(Elf_Auxinfo **aux_info)
6211 const struct auxfmt *fmt;
6214 for (i = 0; i < AT_COUNT; i++) {
6219 if (fmt->fmt == NULL)
6221 rtld_fdprintf(STDOUT_FILENO, "%s:\t", fmt->name);
6222 if (is_ptr_fmt(fmt->fmt)) {
6223 rtld_fdprintfx(STDOUT_FILENO, fmt->fmt,
6226 rtld_fdprintfx(STDOUT_FILENO, fmt->fmt,
6229 rtld_fdprintf(STDOUT_FILENO, "\n");
6234 * Overrides for libc_pic-provided functions.
6238 __getosreldate(void)
6248 oid[1] = KERN_OSRELDATE;
6250 len = sizeof(osrel);
6251 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
6252 if (error == 0 && osrel > 0 && len == sizeof(osrel))
6257 rtld_strerror(int errnum)
6260 if (errnum < 0 || errnum >= sys_nerr)
6261 return ("Unknown error");
6262 return (sys_errlist[errnum]);
6266 getenv(const char *name)
6268 return (__DECONST(char *, rtld_get_env_val(environ, name,
6274 malloc(size_t nbytes)
6277 return (__crt_malloc(nbytes));
6281 calloc(size_t num, size_t size)
6284 return (__crt_calloc(num, size));
6295 realloc(void *cp, size_t nbytes)
6298 return (__crt_realloc(cp, nbytes));
6301 extern int _rtld_version__FreeBSD_version __exported;
6302 int _rtld_version__FreeBSD_version = __FreeBSD_version;
6304 extern char _rtld_version_laddr_offset __exported;
6305 char _rtld_version_laddr_offset;
6307 extern char _rtld_version_dlpi_tls_data __exported;
6308 char _rtld_version_dlpi_tls_data;