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 *);
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;
272 static int stack_prot = PROT_READ | PROT_WRITE | RTLD_DEFAULT_STACK_EXEC;
273 static int max_stack_flags;
276 * Global declarations normally provided by crt1. The dynamic linker is
277 * not built with crt1, so we have to provide them ourselves.
283 * Used to pass argc, argv to init functions.
289 * Globals to control TLS allocation.
291 size_t tls_last_offset; /* Static TLS offset of last module */
292 size_t tls_last_size; /* Static TLS size of last module */
293 size_t tls_static_space; /* Static TLS space allocated */
294 static size_t tls_static_max_align;
295 Elf_Addr tls_dtv_generation = 1; /* Used to detect when dtv size changes */
296 int tls_max_index = 1; /* Largest module index allocated */
298 static bool ld_library_path_rpath = false;
299 bool ld_fast_sigblock = false;
302 * Globals for path names, and such
304 const char *ld_elf_hints_default = _PATH_ELF_HINTS;
305 const char *ld_path_libmap_conf = _PATH_LIBMAP_CONF;
306 const char *ld_path_rtld = _PATH_RTLD;
307 const char *ld_standard_library_path = STANDARD_LIBRARY_PATH;
308 const char *ld_env_prefix = LD_;
310 static void (*rtld_exit_ptr)(void);
313 * Fill in a DoneList with an allocation large enough to hold all of
314 * the currently-loaded objects. Keep this as a macro since it calls
315 * alloca and we want that to occur within the scope of the caller.
317 #define donelist_init(dlp) \
318 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
319 assert((dlp)->objs != NULL), \
320 (dlp)->num_alloc = obj_count, \
323 #define LD_UTRACE(e, h, mb, ms, r, n) do { \
324 if (ld_utrace != NULL) \
325 ld_utrace_log(e, h, mb, ms, r, n); \
329 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
330 int refcnt, const char *name)
332 struct utrace_rtld ut;
333 static const char rtld_utrace_sig[RTLD_UTRACE_SIG_SZ] = RTLD_UTRACE_SIG;
335 memcpy(ut.sig, rtld_utrace_sig, sizeof(ut.sig));
338 ut.mapbase = mapbase;
339 ut.mapsize = mapsize;
341 bzero(ut.name, sizeof(ut.name));
343 strlcpy(ut.name, name, sizeof(ut.name));
344 utrace(&ut, sizeof(ut));
358 LD_LIBRARY_PATH_RPATH,
361 LD_TRACE_LOADED_OBJECTS,
365 LD_TRACE_LOADED_OBJECTS_PROGNAME,
366 LD_TRACE_LOADED_OBJECTS_FMT1,
367 LD_TRACE_LOADED_OBJECTS_FMT2,
368 LD_TRACE_LOADED_OBJECTS_ALL,
372 struct ld_env_var_desc {
373 const char * const n;
377 #define LD_ENV_DESC(var, unsec) \
378 [LD_##var] = { .n = #var, .unsecure = unsec }
380 static struct ld_env_var_desc ld_env_vars[] = {
381 LD_ENV_DESC(BIND_NOW, false),
382 LD_ENV_DESC(PRELOAD, true),
383 LD_ENV_DESC(LIBMAP, true),
384 LD_ENV_DESC(LIBRARY_PATH, true),
385 LD_ENV_DESC(LIBRARY_PATH_FDS, true),
386 LD_ENV_DESC(LIBMAP_DISABLE, true),
387 LD_ENV_DESC(BIND_NOT, true),
388 LD_ENV_DESC(DEBUG, true),
389 LD_ENV_DESC(ELF_HINTS_PATH, true),
390 LD_ENV_DESC(LOADFLTR, true),
391 LD_ENV_DESC(LIBRARY_PATH_RPATH, true),
392 LD_ENV_DESC(PRELOAD_FDS, true),
393 LD_ENV_DESC(DYNAMIC_WEAK, true),
394 LD_ENV_DESC(TRACE_LOADED_OBJECTS, false),
395 LD_ENV_DESC(UTRACE, false),
396 LD_ENV_DESC(DUMP_REL_PRE, false),
397 LD_ENV_DESC(DUMP_REL_POST, false),
398 LD_ENV_DESC(TRACE_LOADED_OBJECTS_PROGNAME, false),
399 LD_ENV_DESC(TRACE_LOADED_OBJECTS_FMT1, false),
400 LD_ENV_DESC(TRACE_LOADED_OBJECTS_FMT2, false),
401 LD_ENV_DESC(TRACE_LOADED_OBJECTS_ALL, false),
402 LD_ENV_DESC(SHOW_AUXV, false),
406 ld_get_env_var(int idx)
408 return (ld_env_vars[idx].val);
412 rtld_get_env_val(char **env, const char *name, size_t name_len)
416 for (m = env; *m != NULL; m++) {
420 /* corrupt environment? */
423 if (v - n == (ptrdiff_t)name_len &&
424 strncmp(name, n, name_len) == 0)
431 rtld_init_env_vars_for_prefix(char **env, const char *env_prefix)
433 struct ld_env_var_desc *lvd;
434 size_t prefix_len, nlen;
438 prefix_len = strlen(env_prefix);
439 for (m = env; *m != NULL; m++) {
441 if (strncmp(env_prefix, n, prefix_len) != 0) {
442 /* Not a rtld environment variable. */
448 /* corrupt environment? */
451 for (i = 0; i < (int)nitems(ld_env_vars); i++) {
452 lvd = &ld_env_vars[i];
453 if (lvd->val != NULL) {
454 /* Saw higher-priority variable name already. */
457 nlen = strlen(lvd->n);
458 if (v - n == (ptrdiff_t)nlen &&
459 strncmp(lvd->n, n, nlen) == 0) {
468 rtld_init_env_vars(char **env)
470 rtld_init_env_vars_for_prefix(env, ld_env_prefix);
474 set_ld_elf_hints_path(void)
476 if (ld_elf_hints_path == NULL || strlen(ld_elf_hints_path) == 0)
477 ld_elf_hints_path = ld_elf_hints_default;
481 * Main entry point for dynamic linking. The first argument is the
482 * stack pointer. The stack is expected to be laid out as described
483 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
484 * Specifically, the stack pointer points to a word containing
485 * ARGC. Following that in the stack is a null-terminated sequence
486 * of pointers to argument strings. Then comes a null-terminated
487 * sequence of pointers to environment strings. Finally, there is a
488 * sequence of "auxiliary vector" entries.
490 * The second argument points to a place to store the dynamic linker's
491 * exit procedure pointer and the third to a place to store the main
494 * The return value is the main program's entry point.
497 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
499 Elf_Auxinfo *aux, *auxp, *auxpf, *aux_info[AT_COUNT];
500 Objlist_Entry *entry;
501 Obj_Entry *last_interposer, *obj, *preload_tail;
502 const Elf_Phdr *phdr;
504 RtldLockState lockstate;
507 char **argv, **env, **envp, *kexecpath;
508 const char *argv0, *binpath, *library_path_rpath;
509 struct ld_env_var_desc *lvd;
511 char buf[MAXPATHLEN];
512 int argc, fd, i, mib[4], old_osrel, osrel, phnum, rtld_argc;
515 int old_auxv_format = 1;
517 bool dir_enable, dir_ignore, direct_exec, explicit_fd, search_in_path;
520 * On entry, the dynamic linker itself has not been relocated yet.
521 * Be very careful not to reference any global data until after
522 * init_rtld has returned. It is OK to reference file-scope statics
523 * and string constants, and to call static and global functions.
526 /* Find the auxiliary vector on the stack. */
530 sp += argc + 1; /* Skip over arguments and NULL terminator */
532 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
534 aux = (Elf_Auxinfo *) sp;
536 /* Digest the auxiliary vector. */
537 for (i = 0; i < AT_COUNT; i++)
539 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
540 if (auxp->a_type < AT_COUNT)
541 aux_info[auxp->a_type] = auxp;
543 if (auxp->a_type == 23) /* AT_STACKPROT */
549 if (old_auxv_format) {
550 /* Remap from old-style auxv numbers. */
551 aux_info[23] = aux_info[21]; /* AT_STACKPROT */
552 aux_info[21] = aux_info[19]; /* AT_PAGESIZESLEN */
553 aux_info[19] = aux_info[17]; /* AT_NCPUS */
554 aux_info[17] = aux_info[15]; /* AT_CANARYLEN */
555 aux_info[15] = aux_info[13]; /* AT_EXECPATH */
556 aux_info[13] = NULL; /* AT_GID */
558 aux_info[20] = aux_info[18]; /* AT_PAGESIZES */
559 aux_info[18] = aux_info[16]; /* AT_OSRELDATE */
560 aux_info[16] = aux_info[14]; /* AT_CANARY */
561 aux_info[14] = NULL; /* AT_EGID */
565 /* Initialize and relocate ourselves. */
566 assert(aux_info[AT_BASE] != NULL);
567 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
571 __progname = obj_rtld.path;
572 argv0 = argv[0] != NULL ? argv[0] : "(null)";
577 if (aux_info[AT_BSDFLAGS] != NULL &&
578 (aux_info[AT_BSDFLAGS]->a_un.a_val & ELF_BSDF_SIGFASTBLK) != 0)
579 ld_fast_sigblock = true;
581 trust = !issetugid();
584 md_abi_variant_hook(aux_info);
585 rtld_init_env_vars(env);
588 if (aux_info[AT_EXECFD] != NULL) {
589 fd = aux_info[AT_EXECFD]->a_un.a_val;
591 assert(aux_info[AT_PHDR] != NULL);
592 phdr = (const Elf_Phdr *)aux_info[AT_PHDR]->a_un.a_ptr;
593 if (phdr == obj_rtld.phdr) {
595 _rtld_error("Tainted process refusing to run binary %s",
601 dbg("opening main program in direct exec mode");
603 rtld_argc = parse_args(argv, argc, &search_in_path, &fd,
604 &argv0, &dir_ignore);
605 explicit_fd = (fd != -1);
608 fd = open_binary_fd(argv0, search_in_path, &binpath);
609 if (fstat(fd, &st) == -1) {
610 _rtld_error("Failed to fstat FD %d (%s): %s", fd,
611 explicit_fd ? "user-provided descriptor" : argv0,
612 rtld_strerror(errno));
617 * Rough emulation of the permission checks done by
618 * execve(2), only Unix DACs are checked, ACLs are
619 * ignored. Preserve the semantic of disabling owner
620 * to execute if owner x bit is cleared, even if
621 * others x bit is enabled.
622 * mmap(2) does not allow to mmap with PROT_EXEC if
623 * binary' file comes from noexec mount. We cannot
624 * set a text reference on the binary.
627 if (st.st_uid == geteuid()) {
628 if ((st.st_mode & S_IXUSR) != 0)
630 } else if (st.st_gid == getegid()) {
631 if ((st.st_mode & S_IXGRP) != 0)
633 } else if ((st.st_mode & S_IXOTH) != 0) {
636 if (!dir_enable && !dir_ignore) {
637 _rtld_error("No execute permission for binary %s",
643 * For direct exec mode, argv[0] is the interpreter
644 * name, we must remove it and shift arguments left
645 * before invoking binary main. Since stack layout
646 * places environment pointers and aux vectors right
647 * after the terminating NULL, we must shift
648 * environment and aux as well.
650 main_argc = argc - rtld_argc;
651 for (i = 0; i <= main_argc; i++)
652 argv[i] = argv[i + rtld_argc];
654 environ = env = envp = argv + main_argc + 1;
655 dbg("move env from %p to %p", envp + rtld_argc, envp);
657 *envp = *(envp + rtld_argc);
658 } while (*envp++ != NULL);
659 aux = auxp = (Elf_Auxinfo *)envp;
660 auxpf = (Elf_Auxinfo *)(envp + rtld_argc);
661 dbg("move aux from %p to %p", auxpf, aux);
662 /* XXXKIB insert place for AT_EXECPATH if not present */
663 for (;; auxp++, auxpf++) {
665 if (auxp->a_type == AT_NULL)
668 /* Since the auxiliary vector has moved, redigest it. */
669 for (i = 0; i < AT_COUNT; i++)
671 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
672 if (auxp->a_type < AT_COUNT)
673 aux_info[auxp->a_type] = auxp;
676 /* Point AT_EXECPATH auxv and aux_info to the binary path. */
677 if (binpath == NULL) {
678 aux_info[AT_EXECPATH] = NULL;
680 if (aux_info[AT_EXECPATH] == NULL) {
681 aux_info[AT_EXECPATH] = xmalloc(sizeof(Elf_Auxinfo));
682 aux_info[AT_EXECPATH]->a_type = AT_EXECPATH;
684 aux_info[AT_EXECPATH]->a_un.a_ptr = __DECONST(void *,
688 _rtld_error("No binary");
694 ld_bind_now = ld_get_env_var(LD_BIND_NOW);
697 * If the process is tainted, then we un-set the dangerous environment
698 * variables. The process will be marked as tainted until setuid(2)
699 * is called. If any child process calls setuid(2) we do not want any
700 * future processes to honor the potentially un-safe variables.
703 for (i = 0; i < (int)nitems(ld_env_vars); i++) {
704 lvd = &ld_env_vars[i];
710 ld_debug = ld_get_env_var(LD_DEBUG);
711 if (ld_bind_now == NULL)
712 ld_bind_not = ld_get_env_var(LD_BIND_NOT) != NULL;
713 ld_dynamic_weak = ld_get_env_var(LD_DYNAMIC_WEAK) == NULL;
714 libmap_disable = ld_get_env_var(LD_LIBMAP_DISABLE) != NULL;
715 libmap_override = ld_get_env_var(LD_LIBMAP);
716 ld_library_path = ld_get_env_var(LD_LIBRARY_PATH);
717 ld_library_dirs = ld_get_env_var(LD_LIBRARY_PATH_FDS);
718 ld_preload = ld_get_env_var(LD_PRELOAD);
719 ld_preload_fds = ld_get_env_var(LD_PRELOAD_FDS);
720 ld_elf_hints_path = ld_get_env_var(LD_ELF_HINTS_PATH);
721 ld_loadfltr = ld_get_env_var(LD_LOADFLTR) != NULL;
722 library_path_rpath = ld_get_env_var(LD_LIBRARY_PATH_RPATH);
723 if (library_path_rpath != NULL) {
724 if (library_path_rpath[0] == 'y' ||
725 library_path_rpath[0] == 'Y' ||
726 library_path_rpath[0] == '1')
727 ld_library_path_rpath = true;
729 ld_library_path_rpath = false;
731 dangerous_ld_env = libmap_disable || libmap_override != NULL ||
732 ld_library_path != NULL || ld_preload != NULL ||
733 ld_elf_hints_path != NULL || ld_loadfltr || !ld_dynamic_weak;
734 ld_tracing = ld_get_env_var(LD_TRACE_LOADED_OBJECTS);
735 ld_utrace = ld_get_env_var(LD_UTRACE);
737 set_ld_elf_hints_path();
738 if (ld_debug != NULL && *ld_debug != '\0')
740 dbg("%s is initialized, base address = %p", __progname,
741 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
742 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
743 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
745 dbg("initializing thread locks");
749 * Load the main program, or process its program header if it is
752 if (fd != -1) { /* Load the main program. */
753 dbg("loading main program");
754 obj_main = map_object(fd, argv0, NULL);
756 if (obj_main == NULL)
758 max_stack_flags = obj_main->stack_flags;
759 } else { /* Main program already loaded. */
760 dbg("processing main program's program header");
761 assert(aux_info[AT_PHDR] != NULL);
762 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
763 assert(aux_info[AT_PHNUM] != NULL);
764 phnum = aux_info[AT_PHNUM]->a_un.a_val;
765 assert(aux_info[AT_PHENT] != NULL);
766 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
767 assert(aux_info[AT_ENTRY] != NULL);
768 imgentry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
769 if ((obj_main = digest_phdr(phdr, phnum, imgentry, argv0)) == NULL)
773 if (aux_info[AT_EXECPATH] != NULL && fd == -1) {
774 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
775 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
776 if (kexecpath[0] == '/')
777 obj_main->path = kexecpath;
778 else if (getcwd(buf, sizeof(buf)) == NULL ||
779 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
780 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
781 obj_main->path = xstrdup(argv0);
783 obj_main->path = xstrdup(buf);
785 dbg("No AT_EXECPATH or direct exec");
786 obj_main->path = xstrdup(argv0);
788 dbg("obj_main path %s", obj_main->path);
789 obj_main->mainprog = true;
791 if (aux_info[AT_STACKPROT] != NULL &&
792 aux_info[AT_STACKPROT]->a_un.a_val != 0)
793 stack_prot = aux_info[AT_STACKPROT]->a_un.a_val;
797 * Get the actual dynamic linker pathname from the executable if
798 * possible. (It should always be possible.) That ensures that
799 * gdb will find the right dynamic linker even if a non-standard
802 if (obj_main->interp != NULL &&
803 strcmp(obj_main->interp, obj_rtld.path) != 0) {
805 obj_rtld.path = xstrdup(obj_main->interp);
806 __progname = obj_rtld.path;
810 if (!digest_dynamic(obj_main, 0))
812 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d",
813 obj_main->path, obj_main->valid_hash_sysv, obj_main->valid_hash_gnu,
814 obj_main->dynsymcount);
816 linkmap_add(obj_main);
817 linkmap_add(&obj_rtld);
819 /* Link the main program into the list of objects. */
820 TAILQ_INSERT_HEAD(&obj_list, obj_main, next);
824 /* Initialize a fake symbol for resolving undefined weak references. */
825 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
826 sym_zero.st_shndx = SHN_UNDEF;
827 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
830 libmap_disable = (bool)lm_init(libmap_override);
832 if (aux_info[AT_KPRELOAD] != NULL &&
833 aux_info[AT_KPRELOAD]->a_un.a_ptr != NULL) {
834 dbg("loading kernel vdso");
835 if (load_kpreload(aux_info[AT_KPRELOAD]->a_un.a_ptr) == -1)
839 dbg("loading LD_PRELOAD_FDS libraries");
840 if (load_preload_objects(ld_preload_fds, true) == -1)
843 dbg("loading LD_PRELOAD libraries");
844 if (load_preload_objects(ld_preload, false) == -1)
846 preload_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
848 dbg("loading needed objects");
849 if (load_needed_objects(obj_main, ld_tracing != NULL ? RTLD_LO_TRACE :
853 /* Make a list of all objects loaded at startup. */
854 last_interposer = obj_main;
855 TAILQ_FOREACH(obj, &obj_list, next) {
858 if (obj->z_interpose && obj != obj_main) {
859 objlist_put_after(&list_main, last_interposer, obj);
860 last_interposer = obj;
862 objlist_push_tail(&list_main, obj);
867 dbg("checking for required versions");
868 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
871 if (ld_get_env_var(LD_SHOW_AUXV) != NULL)
874 if (ld_tracing) { /* We're done */
875 trace_loaded_objects(obj_main);
879 if (ld_get_env_var(LD_DUMP_REL_PRE) != NULL) {
880 dump_relocations(obj_main);
885 * Processing tls relocations requires having the tls offsets
886 * initialized. Prepare offsets before starting initial
887 * relocation processing.
889 dbg("initializing initial thread local storage offsets");
890 STAILQ_FOREACH(entry, &list_main, link) {
892 * Allocate all the initial objects out of the static TLS
893 * block even if they didn't ask for it.
895 allocate_tls_offset(entry->obj);
898 if (relocate_objects(obj_main,
899 ld_bind_now != NULL && *ld_bind_now != '\0',
900 &obj_rtld, SYMLOOK_EARLY, NULL) == -1)
903 dbg("doing copy relocations");
904 if (do_copy_relocations(obj_main) == -1)
907 if (ld_get_env_var(LD_DUMP_REL_POST) != NULL) {
908 dump_relocations(obj_main);
915 * Setup TLS for main thread. This must be done after the
916 * relocations are processed, since tls initialization section
917 * might be the subject for relocations.
919 dbg("initializing initial thread local storage");
920 allocate_initial_tls(globallist_curr(TAILQ_FIRST(&obj_list)));
922 dbg("initializing key program variables");
923 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
924 set_program_var("environ", env);
925 set_program_var("__elf_aux_vector", aux);
927 /* Make a list of init functions to call. */
928 objlist_init(&initlist);
929 initlist_add_objects(globallist_curr(TAILQ_FIRST(&obj_list)),
930 preload_tail, &initlist);
932 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
934 map_stacks_exec(NULL);
936 if (!obj_main->crt_no_init) {
938 * Make sure we don't call the main program's init and fini
939 * functions for binaries linked with old crt1 which calls
942 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
943 obj_main->preinit_array = obj_main->init_array =
944 obj_main->fini_array = (Elf_Addr)NULL;
948 /* Set osrel for direct-execed binary */
951 mib[2] = KERN_PROC_OSREL;
953 osrel = obj_main->osrel;
954 sz = sizeof(old_osrel);
955 dbg("setting osrel to %d", osrel);
956 (void)sysctl(mib, 4, &old_osrel, &sz, &osrel, sizeof(osrel));
959 wlock_acquire(rtld_bind_lock, &lockstate);
961 dbg("resolving ifuncs");
962 if (initlist_objects_ifunc(&initlist, ld_bind_now != NULL &&
963 *ld_bind_now != '\0', SYMLOOK_EARLY, &lockstate) == -1)
966 rtld_exit_ptr = rtld_exit;
967 if (obj_main->crt_no_init)
969 objlist_call_init(&initlist, &lockstate);
970 _r_debug_postinit(&obj_main->linkmap);
971 objlist_clear(&initlist);
972 dbg("loading filtees");
973 TAILQ_FOREACH(obj, &obj_list, next) {
976 if (ld_loadfltr || obj->z_loadfltr)
977 load_filtees(obj, 0, &lockstate);
980 dbg("enforcing main obj relro");
981 if (obj_enforce_relro(obj_main) == -1)
984 lock_release(rtld_bind_lock, &lockstate);
986 dbg("transferring control to program entry point = %p", obj_main->entry);
988 /* Return the exit procedure and the program entry point. */
989 *exit_proc = rtld_exit_ptr;
991 return ((func_ptr_type)obj_main->entry);
995 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def)
1000 ptr = (void *)make_function_pointer(def, obj);
1001 target = call_ifunc_resolver(ptr);
1002 return ((void *)target);
1006 _rtld_bind(Obj_Entry *obj, Elf_Size reloff)
1010 const Obj_Entry *defobj;
1013 RtldLockState lockstate;
1015 rlock_acquire(rtld_bind_lock, &lockstate);
1016 if (sigsetjmp(lockstate.env, 0) != 0)
1017 lock_upgrade(rtld_bind_lock, &lockstate);
1019 rel = (const Elf_Rel *)((const char *)obj->pltrel + reloff);
1021 rel = (const Elf_Rel *)((const char *)obj->pltrela + reloff);
1023 where = (Elf_Addr *)(obj->relocbase + rel->r_offset);
1024 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, SYMLOOK_IN_PLT,
1028 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
1029 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
1031 target = (Elf_Addr)(defobj->relocbase + def->st_value);
1033 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
1034 defobj->strtab + def->st_name,
1035 obj->path == NULL ? NULL : basename(obj->path),
1037 defobj->path == NULL ? NULL : basename(defobj->path));
1040 * Write the new contents for the jmpslot. Note that depending on
1041 * architecture, the value which we need to return back to the
1042 * lazy binding trampoline may or may not be the target
1043 * address. The value returned from reloc_jmpslot() is the value
1044 * that the trampoline needs.
1046 target = reloc_jmpslot(where, target, defobj, obj, rel);
1047 lock_release(rtld_bind_lock, &lockstate);
1052 * Error reporting function. Use it like printf. If formats the message
1053 * into a buffer, and sets things up so that the next call to dlerror()
1054 * will return the message.
1057 _rtld_error(const char *fmt, ...)
1062 rtld_vsnprintf(lockinfo.dlerror_loc(), lockinfo.dlerror_loc_sz,
1065 *lockinfo.dlerror_seen() = 0;
1066 LD_UTRACE(UTRACE_RTLD_ERROR, NULL, NULL, 0, 0, lockinfo.dlerror_loc());
1070 * Return a dynamically-allocated copy of the current error message, if any.
1072 static struct dlerror_save *
1075 struct dlerror_save *res;
1077 res = xmalloc(sizeof(*res));
1078 res->seen = *lockinfo.dlerror_seen();
1080 res->msg = xstrdup(lockinfo.dlerror_loc());
1085 * Restore the current error message from a copy which was previously saved
1086 * by errmsg_save(). The copy is freed.
1089 errmsg_restore(struct dlerror_save *saved_msg)
1091 if (saved_msg == NULL || saved_msg->seen == 1) {
1092 *lockinfo.dlerror_seen() = 1;
1094 *lockinfo.dlerror_seen() = 0;
1095 strlcpy(lockinfo.dlerror_loc(), saved_msg->msg,
1096 lockinfo.dlerror_loc_sz);
1097 free(saved_msg->msg);
1103 basename(const char *name)
1107 p = strrchr(name, '/');
1108 return (p != NULL ? p + 1 : name);
1111 static struct utsname uts;
1114 origin_subst_one(Obj_Entry *obj, char *real, const char *kw,
1115 const char *subst, bool may_free)
1117 char *p, *p1, *res, *resp;
1118 int subst_len, kw_len, subst_count, old_len, new_len;
1120 kw_len = strlen(kw);
1123 * First, count the number of the keyword occurrences, to
1124 * preallocate the final string.
1126 for (p = real, subst_count = 0;; p = p1 + kw_len, subst_count++) {
1133 * If the keyword is not found, just return.
1135 * Return non-substituted string if resolution failed. We
1136 * cannot do anything more reasonable, the failure mode of the
1137 * caller is unresolved library anyway.
1139 if (subst_count == 0 || (obj != NULL && !obj_resolve_origin(obj)))
1140 return (may_free ? real : xstrdup(real));
1142 subst = obj->origin_path;
1145 * There is indeed something to substitute. Calculate the
1146 * length of the resulting string, and allocate it.
1148 subst_len = strlen(subst);
1149 old_len = strlen(real);
1150 new_len = old_len + (subst_len - kw_len) * subst_count;
1151 res = xmalloc(new_len + 1);
1154 * Now, execute the substitution loop.
1156 for (p = real, resp = res, *resp = '\0';;) {
1159 /* Copy the prefix before keyword. */
1160 memcpy(resp, p, p1 - p);
1162 /* Keyword replacement. */
1163 memcpy(resp, subst, subst_len);
1171 /* Copy to the end of string and finish. */
1179 origin_subst(Obj_Entry *obj, const char *real)
1181 char *res1, *res2, *res3, *res4;
1183 if (obj == NULL || !trust)
1184 return (xstrdup(real));
1185 if (uts.sysname[0] == '\0') {
1186 if (uname(&uts) != 0) {
1187 _rtld_error("utsname failed: %d", errno);
1191 /* __DECONST is safe here since without may_free real is unchanged */
1192 res1 = origin_subst_one(obj, __DECONST(char *, real), "$ORIGIN", NULL,
1194 res2 = origin_subst_one(NULL, res1, "$OSNAME", uts.sysname, true);
1195 res3 = origin_subst_one(NULL, res2, "$OSREL", uts.release, true);
1196 res4 = origin_subst_one(NULL, res3, "$PLATFORM", uts.machine, true);
1203 const char *msg = dlerror();
1206 msg = "Fatal error";
1207 rtld_fdputstr(STDERR_FILENO, _BASENAME_RTLD ": ");
1208 rtld_fdputstr(STDERR_FILENO, msg);
1209 rtld_fdputchar(STDERR_FILENO, '\n');
1214 * Process a shared object's DYNAMIC section, and save the important
1215 * information in its Obj_Entry structure.
1218 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
1219 const Elf_Dyn **dyn_soname, const Elf_Dyn **dyn_runpath)
1221 const Elf_Dyn *dynp;
1222 Needed_Entry **needed_tail = &obj->needed;
1223 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
1224 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
1225 const Elf_Hashelt *hashtab;
1226 const Elf32_Word *hashval;
1227 Elf32_Word bkt, nmaskwords;
1229 int plttype = DT_REL;
1233 *dyn_runpath = NULL;
1235 obj->bind_now = false;
1236 dynp = obj->dynamic;
1239 for (; dynp->d_tag != DT_NULL; dynp++) {
1240 switch (dynp->d_tag) {
1243 obj->rel = (const Elf_Rel *)(obj->relocbase + dynp->d_un.d_ptr);
1247 obj->relsize = dynp->d_un.d_val;
1251 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
1255 obj->pltrel = (const Elf_Rel *)
1256 (obj->relocbase + dynp->d_un.d_ptr);
1260 obj->pltrelsize = dynp->d_un.d_val;
1264 obj->rela = (const Elf_Rela *)(obj->relocbase + dynp->d_un.d_ptr);
1268 obj->relasize = dynp->d_un.d_val;
1272 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
1276 obj->relr = (const Elf_Relr *)(obj->relocbase + dynp->d_un.d_ptr);
1280 obj->relrsize = dynp->d_un.d_val;
1284 assert(dynp->d_un.d_val == sizeof(Elf_Relr));
1288 plttype = dynp->d_un.d_val;
1289 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
1293 obj->symtab = (const Elf_Sym *)
1294 (obj->relocbase + dynp->d_un.d_ptr);
1298 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
1302 obj->strtab = (const char *)(obj->relocbase + dynp->d_un.d_ptr);
1306 obj->strsize = dynp->d_un.d_val;
1310 obj->verneed = (const Elf_Verneed *)(obj->relocbase +
1315 obj->verneednum = dynp->d_un.d_val;
1319 obj->verdef = (const Elf_Verdef *)(obj->relocbase +
1324 obj->verdefnum = dynp->d_un.d_val;
1328 obj->versyms = (const Elf_Versym *)(obj->relocbase +
1334 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1336 obj->nbuckets = hashtab[0];
1337 obj->nchains = hashtab[1];
1338 obj->buckets = hashtab + 2;
1339 obj->chains = obj->buckets + obj->nbuckets;
1340 obj->valid_hash_sysv = obj->nbuckets > 0 && obj->nchains > 0 &&
1341 obj->buckets != NULL;
1347 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1349 obj->nbuckets_gnu = hashtab[0];
1350 obj->symndx_gnu = hashtab[1];
1351 nmaskwords = hashtab[2];
1352 bloom_size32 = (__ELF_WORD_SIZE / 32) * nmaskwords;
1353 obj->maskwords_bm_gnu = nmaskwords - 1;
1354 obj->shift2_gnu = hashtab[3];
1355 obj->bloom_gnu = (const Elf_Addr *)(hashtab + 4);
1356 obj->buckets_gnu = hashtab + 4 + bloom_size32;
1357 obj->chain_zero_gnu = obj->buckets_gnu + obj->nbuckets_gnu -
1359 /* Number of bitmask words is required to be power of 2 */
1360 obj->valid_hash_gnu = powerof2(nmaskwords) &&
1361 obj->nbuckets_gnu > 0 && obj->buckets_gnu != NULL;
1367 Needed_Entry *nep = NEW(Needed_Entry);
1368 nep->name = dynp->d_un.d_val;
1373 needed_tail = &nep->next;
1379 Needed_Entry *nep = NEW(Needed_Entry);
1380 nep->name = dynp->d_un.d_val;
1384 *needed_filtees_tail = nep;
1385 needed_filtees_tail = &nep->next;
1387 if (obj->linkmap.l_refname == NULL)
1388 obj->linkmap.l_refname = (char *)dynp->d_un.d_val;
1394 Needed_Entry *nep = NEW(Needed_Entry);
1395 nep->name = dynp->d_un.d_val;
1399 *needed_aux_filtees_tail = nep;
1400 needed_aux_filtees_tail = &nep->next;
1405 obj->pltgot = (Elf_Addr *)(obj->relocbase + dynp->d_un.d_ptr);
1409 obj->textrel = true;
1413 obj->symbolic = true;
1418 * We have to wait until later to process this, because we
1419 * might not have gotten the address of the string table yet.
1429 *dyn_runpath = dynp;
1433 obj->init = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1436 case DT_PREINIT_ARRAY:
1437 obj->preinit_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1440 case DT_PREINIT_ARRAYSZ:
1441 obj->preinit_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1445 obj->init_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1448 case DT_INIT_ARRAYSZ:
1449 obj->init_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1453 obj->fini = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1457 obj->fini_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1460 case DT_FINI_ARRAYSZ:
1461 obj->fini_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1466 dbg("Filling in DT_DEBUG entry");
1467 (__DECONST(Elf_Dyn *, dynp))->d_un.d_ptr = (Elf_Addr)&r_debug;
1471 if (dynp->d_un.d_val & DF_ORIGIN)
1472 obj->z_origin = true;
1473 if (dynp->d_un.d_val & DF_SYMBOLIC)
1474 obj->symbolic = true;
1475 if (dynp->d_un.d_val & DF_TEXTREL)
1476 obj->textrel = true;
1477 if (dynp->d_un.d_val & DF_BIND_NOW)
1478 obj->bind_now = true;
1479 if (dynp->d_un.d_val & DF_STATIC_TLS)
1480 obj->static_tls = true;
1484 #ifdef __powerpc64__
1485 case DT_PPC64_GLINK:
1486 obj->glink = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1490 obj->gotptr = (Elf_Addr *)(obj->relocbase + dynp->d_un.d_ptr);
1496 if (dynp->d_un.d_val & DF_1_NOOPEN)
1497 obj->z_noopen = true;
1498 if (dynp->d_un.d_val & DF_1_ORIGIN)
1499 obj->z_origin = true;
1500 if (dynp->d_un.d_val & DF_1_GLOBAL)
1501 obj->z_global = true;
1502 if (dynp->d_un.d_val & DF_1_BIND_NOW)
1503 obj->bind_now = true;
1504 if (dynp->d_un.d_val & DF_1_NODELETE)
1505 obj->z_nodelete = true;
1506 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1507 obj->z_loadfltr = true;
1508 if (dynp->d_un.d_val & DF_1_INTERPOSE)
1509 obj->z_interpose = true;
1510 if (dynp->d_un.d_val & DF_1_NODEFLIB)
1511 obj->z_nodeflib = true;
1512 if (dynp->d_un.d_val & DF_1_PIE)
1518 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1525 obj->traced = false;
1527 if (plttype == DT_RELA) {
1528 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1530 obj->pltrelasize = obj->pltrelsize;
1531 obj->pltrelsize = 0;
1534 /* Determine size of dynsym table (equal to nchains of sysv hash) */
1535 if (obj->valid_hash_sysv)
1536 obj->dynsymcount = obj->nchains;
1537 else if (obj->valid_hash_gnu) {
1538 obj->dynsymcount = 0;
1539 for (bkt = 0; bkt < obj->nbuckets_gnu; bkt++) {
1540 if (obj->buckets_gnu[bkt] == 0)
1542 hashval = &obj->chain_zero_gnu[obj->buckets_gnu[bkt]];
1545 while ((*hashval++ & 1u) == 0);
1547 obj->dynsymcount += obj->symndx_gnu;
1550 if (obj->linkmap.l_refname != NULL)
1551 obj->linkmap.l_refname = obj->strtab + (unsigned long)obj->
1556 obj_resolve_origin(Obj_Entry *obj)
1559 if (obj->origin_path != NULL)
1561 obj->origin_path = xmalloc(PATH_MAX);
1562 return (rtld_dirname_abs(obj->path, obj->origin_path) != -1);
1566 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1567 const Elf_Dyn *dyn_soname, const Elf_Dyn *dyn_runpath)
1570 if (obj->z_origin && !obj_resolve_origin(obj))
1573 if (dyn_runpath != NULL) {
1574 obj->runpath = (const char *)obj->strtab + dyn_runpath->d_un.d_val;
1575 obj->runpath = origin_subst(obj, obj->runpath);
1576 } else if (dyn_rpath != NULL) {
1577 obj->rpath = (const char *)obj->strtab + dyn_rpath->d_un.d_val;
1578 obj->rpath = origin_subst(obj, obj->rpath);
1580 if (dyn_soname != NULL)
1581 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1586 digest_dynamic(Obj_Entry *obj, int early)
1588 const Elf_Dyn *dyn_rpath;
1589 const Elf_Dyn *dyn_soname;
1590 const Elf_Dyn *dyn_runpath;
1592 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname, &dyn_runpath);
1593 return (digest_dynamic2(obj, dyn_rpath, dyn_soname, dyn_runpath));
1597 * Process a shared object's program header. This is used only for the
1598 * main program, when the kernel has already loaded the main program
1599 * into memory before calling the dynamic linker. It creates and
1600 * returns an Obj_Entry structure.
1603 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1606 const Elf_Phdr *phlimit = phdr + phnum;
1608 Elf_Addr note_start, note_end;
1612 for (ph = phdr; ph < phlimit; ph++) {
1613 if (ph->p_type != PT_PHDR)
1617 obj->phsize = ph->p_memsz;
1618 obj->relocbase = __DECONST(char *, phdr) - ph->p_vaddr;
1622 obj->stack_flags = PF_X | PF_R | PF_W;
1624 for (ph = phdr; ph < phlimit; ph++) {
1625 switch (ph->p_type) {
1628 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1632 if (nsegs == 0) { /* First load segment */
1633 obj->vaddrbase = trunc_page(ph->p_vaddr);
1634 obj->mapbase = obj->vaddrbase + obj->relocbase;
1635 } else { /* Last load segment */
1636 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1643 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1648 obj->tlssize = ph->p_memsz;
1649 obj->tlsalign = ph->p_align;
1650 obj->tlsinitsize = ph->p_filesz;
1651 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1652 obj->tlspoffset = ph->p_offset;
1656 obj->stack_flags = ph->p_flags;
1660 obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1661 obj->relro_size = trunc_page(ph->p_vaddr + ph->p_memsz) -
1662 trunc_page(ph->p_vaddr);
1666 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
1667 note_end = note_start + ph->p_filesz;
1668 digest_notes(obj, note_start, note_end);
1673 _rtld_error("%s: too few PT_LOAD segments", path);
1682 digest_notes(Obj_Entry *obj, Elf_Addr note_start, Elf_Addr note_end)
1684 const Elf_Note *note;
1685 const char *note_name;
1688 for (note = (const Elf_Note *)note_start; (Elf_Addr)note < note_end;
1689 note = (const Elf_Note *)((const char *)(note + 1) +
1690 roundup2(note->n_namesz, sizeof(Elf32_Addr)) +
1691 roundup2(note->n_descsz, sizeof(Elf32_Addr)))) {
1692 if (note->n_namesz != sizeof(NOTE_FREEBSD_VENDOR) ||
1693 note->n_descsz != sizeof(int32_t))
1695 if (note->n_type != NT_FREEBSD_ABI_TAG &&
1696 note->n_type != NT_FREEBSD_FEATURE_CTL &&
1697 note->n_type != NT_FREEBSD_NOINIT_TAG)
1699 note_name = (const char *)(note + 1);
1700 if (strncmp(NOTE_FREEBSD_VENDOR, note_name,
1701 sizeof(NOTE_FREEBSD_VENDOR)) != 0)
1703 switch (note->n_type) {
1704 case NT_FREEBSD_ABI_TAG:
1705 /* FreeBSD osrel note */
1706 p = (uintptr_t)(note + 1);
1707 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1708 obj->osrel = *(const int32_t *)(p);
1709 dbg("note osrel %d", obj->osrel);
1711 case NT_FREEBSD_FEATURE_CTL:
1712 /* FreeBSD ABI feature control note */
1713 p = (uintptr_t)(note + 1);
1714 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1715 obj->fctl0 = *(const uint32_t *)(p);
1716 dbg("note fctl0 %#x", obj->fctl0);
1718 case NT_FREEBSD_NOINIT_TAG:
1719 /* FreeBSD 'crt does not call init' note */
1720 obj->crt_no_init = true;
1721 dbg("note crt_no_init");
1728 dlcheck(void *handle)
1732 TAILQ_FOREACH(obj, &obj_list, next) {
1733 if (obj == (Obj_Entry *) handle)
1737 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1738 _rtld_error("Invalid shared object handle %p", handle);
1745 * If the given object is already in the donelist, return true. Otherwise
1746 * add the object to the list and return false.
1749 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1753 for (i = 0; i < dlp->num_used; i++)
1754 if (dlp->objs[i] == obj)
1757 * Our donelist allocation should always be sufficient. But if
1758 * our threads locking isn't working properly, more shared objects
1759 * could have been loaded since we allocated the list. That should
1760 * never happen, but we'll handle it properly just in case it does.
1762 if (dlp->num_used < dlp->num_alloc)
1763 dlp->objs[dlp->num_used++] = obj;
1768 * Hash function for symbol table lookup. Don't even think about changing
1769 * this. It is specified by the System V ABI.
1772 elf_hash(const char *name)
1774 const unsigned char *p = (const unsigned char *) name;
1775 unsigned long h = 0;
1778 while (*p != '\0') {
1779 h = (h << 4) + *p++;
1780 if ((g = h & 0xf0000000) != 0)
1788 * The GNU hash function is the Daniel J. Bernstein hash clipped to 32 bits
1789 * unsigned in case it's implemented with a wider type.
1792 gnu_hash(const char *s)
1798 for (c = *s; c != '\0'; c = *++s)
1800 return (h & 0xffffffff);
1805 * Find the library with the given name, and return its full pathname.
1806 * The returned string is dynamically allocated. Generates an error
1807 * message and returns NULL if the library cannot be found.
1809 * If the second argument is non-NULL, then it refers to an already-
1810 * loaded shared object, whose library search path will be searched.
1812 * If a library is successfully located via LD_LIBRARY_PATH_FDS, its
1813 * descriptor (which is close-on-exec) will be passed out via the third
1816 * The search order is:
1817 * DT_RPATH in the referencing file _unless_ DT_RUNPATH is present (1)
1818 * DT_RPATH of the main object if DSO without defined DT_RUNPATH (1)
1820 * DT_RUNPATH in the referencing file
1821 * ldconfig hints (if -z nodefaultlib, filter out default library directories
1823 * /lib:/usr/lib _unless_ the referencing file is linked with -z nodefaultlib
1825 * (1) Handled in digest_dynamic2 - rpath left NULL if runpath defined.
1828 find_library(const char *xname, const Obj_Entry *refobj, int *fdp)
1830 char *pathname, *refobj_path;
1832 bool nodeflib, objgiven;
1834 objgiven = refobj != NULL;
1836 if (libmap_disable || !objgiven ||
1837 (name = lm_find(refobj->path, xname)) == NULL)
1840 if (strchr(name, '/') != NULL) { /* Hard coded pathname */
1841 if (name[0] != '/' && !trust) {
1842 _rtld_error("Absolute pathname required "
1843 "for shared object \"%s\"", name);
1846 return (origin_subst(__DECONST(Obj_Entry *, refobj),
1847 __DECONST(char *, name)));
1850 dbg(" Searching for \"%s\"", name);
1851 refobj_path = objgiven ? refobj->path : NULL;
1854 * If refobj->rpath != NULL, then refobj->runpath is NULL. Fall
1855 * back to pre-conforming behaviour if user requested so with
1856 * LD_LIBRARY_PATH_RPATH environment variable and ignore -z
1859 if (objgiven && refobj->rpath != NULL && ld_library_path_rpath) {
1860 pathname = search_library_path(name, ld_library_path,
1862 if (pathname != NULL)
1864 if (refobj != NULL) {
1865 pathname = search_library_path(name, refobj->rpath,
1867 if (pathname != NULL)
1870 pathname = search_library_pathfds(name, ld_library_dirs, fdp);
1871 if (pathname != NULL)
1873 pathname = search_library_path(name, gethints(false),
1875 if (pathname != NULL)
1877 pathname = search_library_path(name, ld_standard_library_path,
1879 if (pathname != NULL)
1882 nodeflib = objgiven ? refobj->z_nodeflib : false;
1884 pathname = search_library_path(name, refobj->rpath,
1886 if (pathname != NULL)
1889 if (objgiven && refobj->runpath == NULL && refobj != obj_main) {
1890 pathname = search_library_path(name, obj_main->rpath,
1892 if (pathname != NULL)
1895 pathname = search_library_path(name, ld_library_path,
1897 if (pathname != NULL)
1900 pathname = search_library_path(name, refobj->runpath,
1902 if (pathname != NULL)
1905 pathname = search_library_pathfds(name, ld_library_dirs, fdp);
1906 if (pathname != NULL)
1908 pathname = search_library_path(name, gethints(nodeflib),
1910 if (pathname != NULL)
1912 if (objgiven && !nodeflib) {
1913 pathname = search_library_path(name,
1914 ld_standard_library_path, refobj_path, fdp);
1915 if (pathname != NULL)
1920 if (objgiven && refobj->path != NULL) {
1921 _rtld_error("Shared object \"%s\" not found, "
1922 "required by \"%s\"", name, basename(refobj->path));
1924 _rtld_error("Shared object \"%s\" not found", name);
1930 * Given a symbol number in a referencing object, find the corresponding
1931 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1932 * no definition was found. Returns a pointer to the Obj_Entry of the
1933 * defining object via the reference parameter DEFOBJ_OUT.
1936 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1937 const Obj_Entry **defobj_out, int flags, SymCache *cache,
1938 RtldLockState *lockstate)
1942 const Obj_Entry *defobj;
1943 const Ver_Entry *ve;
1949 * If we have already found this symbol, get the information from
1952 if (symnum >= refobj->dynsymcount)
1953 return (NULL); /* Bad object */
1954 if (cache != NULL && cache[symnum].sym != NULL) {
1955 *defobj_out = cache[symnum].obj;
1956 return (cache[symnum].sym);
1959 ref = refobj->symtab + symnum;
1960 name = refobj->strtab + ref->st_name;
1966 * We don't have to do a full scale lookup if the symbol is local.
1967 * We know it will bind to the instance in this load module; to
1968 * which we already have a pointer (ie ref). By not doing a lookup,
1969 * we not only improve performance, but it also avoids unresolvable
1970 * symbols when local symbols are not in the hash table. This has
1971 * been seen with the ia64 toolchain.
1973 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1974 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1975 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1978 symlook_init(&req, name);
1980 ve = req.ventry = fetch_ventry(refobj, symnum);
1981 req.lockstate = lockstate;
1982 res = symlook_default(&req, refobj);
1985 defobj = req.defobj_out;
1993 * If we found no definition and the reference is weak, treat the
1994 * symbol as having the value zero.
1996 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
2002 *defobj_out = defobj;
2003 /* Record the information in the cache to avoid subsequent lookups. */
2004 if (cache != NULL) {
2005 cache[symnum].sym = def;
2006 cache[symnum].obj = defobj;
2009 if (refobj != &obj_rtld)
2010 _rtld_error("%s: Undefined symbol \"%s%s%s\"", refobj->path, name,
2011 ve != NULL ? "@" : "", ve != NULL ? ve->name : "");
2017 * Return the search path from the ldconfig hints file, reading it if
2018 * necessary. If nostdlib is true, then the default search paths are
2019 * not added to result.
2021 * Returns NULL if there are problems with the hints file,
2022 * or if the search path there is empty.
2025 gethints(bool nostdlib)
2027 static char *filtered_path;
2028 static const char *hints;
2029 static struct elfhints_hdr hdr;
2030 struct fill_search_info_args sargs, hargs;
2031 struct dl_serinfo smeta, hmeta, *SLPinfo, *hintinfo;
2032 struct dl_serpath *SLPpath, *hintpath;
2034 struct stat hint_stat;
2035 unsigned int SLPndx, hintndx, fndx, fcount;
2041 /* First call, read the hints file */
2042 if (hints == NULL) {
2043 /* Keep from trying again in case the hints file is bad. */
2046 if ((fd = open(ld_elf_hints_path, O_RDONLY | O_CLOEXEC)) == -1)
2050 * Check of hdr.dirlistlen value against type limit
2051 * intends to pacify static analyzers. Further
2052 * paranoia leads to checks that dirlist is fully
2053 * contained in the file range.
2055 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
2056 hdr.magic != ELFHINTS_MAGIC ||
2057 hdr.version != 1 || hdr.dirlistlen > UINT_MAX / 2 ||
2058 fstat(fd, &hint_stat) == -1) {
2065 if (dl + hdr.dirlist < dl)
2068 if (dl + hdr.dirlistlen < dl)
2070 dl += hdr.dirlistlen;
2071 if (dl > hint_stat.st_size)
2073 p = xmalloc(hdr.dirlistlen + 1);
2074 if (pread(fd, p, hdr.dirlistlen + 1,
2075 hdr.strtab + hdr.dirlist) != (ssize_t)hdr.dirlistlen + 1 ||
2076 p[hdr.dirlistlen] != '\0') {
2085 * If caller agreed to receive list which includes the default
2086 * paths, we are done. Otherwise, if we still did not
2087 * calculated filtered result, do it now.
2090 return (hints[0] != '\0' ? hints : NULL);
2091 if (filtered_path != NULL)
2095 * Obtain the list of all configured search paths, and the
2096 * list of the default paths.
2098 * First estimate the size of the results.
2100 smeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2102 hmeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2105 sargs.request = RTLD_DI_SERINFOSIZE;
2106 sargs.serinfo = &smeta;
2107 hargs.request = RTLD_DI_SERINFOSIZE;
2108 hargs.serinfo = &hmeta;
2110 path_enumerate(ld_standard_library_path, fill_search_info, NULL,
2112 path_enumerate(hints, fill_search_info, NULL, &hargs);
2114 SLPinfo = xmalloc(smeta.dls_size);
2115 hintinfo = xmalloc(hmeta.dls_size);
2118 * Next fetch both sets of paths.
2120 sargs.request = RTLD_DI_SERINFO;
2121 sargs.serinfo = SLPinfo;
2122 sargs.serpath = &SLPinfo->dls_serpath[0];
2123 sargs.strspace = (char *)&SLPinfo->dls_serpath[smeta.dls_cnt];
2125 hargs.request = RTLD_DI_SERINFO;
2126 hargs.serinfo = hintinfo;
2127 hargs.serpath = &hintinfo->dls_serpath[0];
2128 hargs.strspace = (char *)&hintinfo->dls_serpath[hmeta.dls_cnt];
2130 path_enumerate(ld_standard_library_path, fill_search_info, NULL,
2132 path_enumerate(hints, fill_search_info, NULL, &hargs);
2135 * Now calculate the difference between two sets, by excluding
2136 * standard paths from the full set.
2140 filtered_path = xmalloc(hdr.dirlistlen + 1);
2141 hintpath = &hintinfo->dls_serpath[0];
2142 for (hintndx = 0; hintndx < hmeta.dls_cnt; hintndx++, hintpath++) {
2144 SLPpath = &SLPinfo->dls_serpath[0];
2146 * Check each standard path against current.
2148 for (SLPndx = 0; SLPndx < smeta.dls_cnt; SLPndx++, SLPpath++) {
2149 /* matched, skip the path */
2150 if (!strcmp(hintpath->dls_name, SLPpath->dls_name)) {
2158 * Not matched against any standard path, add the path
2159 * to result. Separate consequtive paths with ':'.
2162 filtered_path[fndx] = ':';
2166 flen = strlen(hintpath->dls_name);
2167 strncpy((filtered_path + fndx), hintpath->dls_name, flen);
2170 filtered_path[fndx] = '\0';
2176 return (filtered_path[0] != '\0' ? filtered_path : NULL);
2180 init_dag(Obj_Entry *root)
2182 const Needed_Entry *needed;
2183 const Objlist_Entry *elm;
2186 if (root->dag_inited)
2188 donelist_init(&donelist);
2190 /* Root object belongs to own DAG. */
2191 objlist_push_tail(&root->dldags, root);
2192 objlist_push_tail(&root->dagmembers, root);
2193 donelist_check(&donelist, root);
2196 * Add dependencies of root object to DAG in breadth order
2197 * by exploiting the fact that each new object get added
2198 * to the tail of the dagmembers list.
2200 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2201 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
2202 if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
2204 objlist_push_tail(&needed->obj->dldags, root);
2205 objlist_push_tail(&root->dagmembers, needed->obj);
2208 root->dag_inited = true;
2212 init_marker(Obj_Entry *marker)
2215 bzero(marker, sizeof(*marker));
2216 marker->marker = true;
2220 globallist_curr(const Obj_Entry *obj)
2227 return (__DECONST(Obj_Entry *, obj));
2228 obj = TAILQ_PREV(obj, obj_entry_q, next);
2233 globallist_next(const Obj_Entry *obj)
2237 obj = TAILQ_NEXT(obj, next);
2241 return (__DECONST(Obj_Entry *, obj));
2245 /* Prevent the object from being unmapped while the bind lock is dropped. */
2247 hold_object(Obj_Entry *obj)
2254 unhold_object(Obj_Entry *obj)
2257 assert(obj->holdcount > 0);
2258 if (--obj->holdcount == 0 && obj->unholdfree)
2259 release_object(obj);
2263 process_z(Obj_Entry *root)
2265 const Objlist_Entry *elm;
2269 * Walk over object DAG and process every dependent object
2270 * that is marked as DF_1_NODELETE or DF_1_GLOBAL. They need
2271 * to grow their own DAG.
2273 * For DF_1_GLOBAL, DAG is required for symbol lookups in
2274 * symlook_global() to work.
2276 * For DF_1_NODELETE, the DAG should have its reference upped.
2278 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2282 if (obj->z_nodelete && !obj->ref_nodel) {
2283 dbg("obj %s -z nodelete", obj->path);
2286 obj->ref_nodel = true;
2288 if (obj->z_global && objlist_find(&list_global, obj) == NULL) {
2289 dbg("obj %s -z global", obj->path);
2290 objlist_push_tail(&list_global, obj);
2297 parse_rtld_phdr(Obj_Entry *obj)
2300 Elf_Addr note_start, note_end;
2302 obj->stack_flags = PF_X | PF_R | PF_W;
2303 for (ph = obj->phdr; (const char *)ph < (const char *)obj->phdr +
2304 obj->phsize; ph++) {
2305 switch (ph->p_type) {
2307 obj->stack_flags = ph->p_flags;
2310 obj->relro_page = obj->relocbase +
2311 trunc_page(ph->p_vaddr);
2312 obj->relro_size = round_page(ph->p_memsz);
2315 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
2316 note_end = note_start + ph->p_filesz;
2317 digest_notes(obj, note_start, note_end);
2324 * Initialize the dynamic linker. The argument is the address at which
2325 * the dynamic linker has been mapped into memory. The primary task of
2326 * this function is to relocate the dynamic linker.
2329 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
2331 Obj_Entry objtmp; /* Temporary rtld object */
2332 const Elf_Ehdr *ehdr;
2333 const Elf_Dyn *dyn_rpath;
2334 const Elf_Dyn *dyn_soname;
2335 const Elf_Dyn *dyn_runpath;
2337 #ifdef RTLD_INIT_PAGESIZES_EARLY
2338 /* The page size is required by the dynamic memory allocator. */
2339 init_pagesizes(aux_info);
2343 * Conjure up an Obj_Entry structure for the dynamic linker.
2345 * The "path" member can't be initialized yet because string constants
2346 * cannot yet be accessed. Below we will set it correctly.
2348 memset(&objtmp, 0, sizeof(objtmp));
2351 objtmp.mapbase = mapbase;
2353 objtmp.relocbase = mapbase;
2356 objtmp.dynamic = rtld_dynamic(&objtmp);
2357 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname, &dyn_runpath);
2358 assert(objtmp.needed == NULL);
2359 assert(objtmp.textrel == NULL);
2361 * Temporarily put the dynamic linker entry into the object list, so
2362 * that symbols can be found.
2364 relocate_objects(&objtmp, true, &objtmp, 0, NULL);
2366 ehdr = (Elf_Ehdr *)mapbase;
2367 objtmp.phdr = (Elf_Phdr *)((char *)mapbase + ehdr->e_phoff);
2368 objtmp.phsize = ehdr->e_phnum * sizeof(objtmp.phdr[0]);
2370 /* Initialize the object list. */
2371 TAILQ_INIT(&obj_list);
2373 /* Now that non-local variables can be accesses, copy out obj_rtld. */
2374 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
2376 #ifndef RTLD_INIT_PAGESIZES_EARLY
2377 /* The page size is required by the dynamic memory allocator. */
2378 init_pagesizes(aux_info);
2381 if (aux_info[AT_OSRELDATE] != NULL)
2382 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
2384 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname, dyn_runpath);
2386 /* Replace the path with a dynamically allocated copy. */
2387 obj_rtld.path = xstrdup(ld_path_rtld);
2389 parse_rtld_phdr(&obj_rtld);
2390 if (obj_enforce_relro(&obj_rtld) == -1)
2393 r_debug.r_version = R_DEBUG_VERSION;
2394 r_debug.r_brk = r_debug_state;
2395 r_debug.r_state = RT_CONSISTENT;
2396 r_debug.r_ldbase = obj_rtld.relocbase;
2400 * Retrieve the array of supported page sizes. The kernel provides the page
2401 * sizes in increasing order.
2404 init_pagesizes(Elf_Auxinfo **aux_info)
2406 static size_t psa[MAXPAGESIZES];
2410 if (aux_info[AT_PAGESIZES] != NULL && aux_info[AT_PAGESIZESLEN] !=
2412 size = aux_info[AT_PAGESIZESLEN]->a_un.a_val;
2413 pagesizes = aux_info[AT_PAGESIZES]->a_un.a_ptr;
2416 if (sysctlnametomib("hw.pagesizes", mib, &len) == 0)
2419 /* As a fallback, retrieve the base page size. */
2420 size = sizeof(psa[0]);
2421 if (aux_info[AT_PAGESZ] != NULL) {
2422 psa[0] = aux_info[AT_PAGESZ]->a_un.a_val;
2426 mib[1] = HW_PAGESIZE;
2430 if (sysctl(mib, len, psa, &size, NULL, 0) == -1) {
2431 _rtld_error("sysctl for hw.pagesize(s) failed");
2437 npagesizes = size / sizeof(pagesizes[0]);
2438 /* Discard any invalid entries at the end of the array. */
2439 while (npagesizes > 0 && pagesizes[npagesizes - 1] == 0)
2444 * Add the init functions from a needed object list (and its recursive
2445 * needed objects) to "list". This is not used directly; it is a helper
2446 * function for initlist_add_objects(). The write lock must be held
2447 * when this function is called.
2450 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
2452 /* Recursively process the successor needed objects. */
2453 if (needed->next != NULL)
2454 initlist_add_neededs(needed->next, list);
2456 /* Process the current needed object. */
2457 if (needed->obj != NULL)
2458 initlist_add_objects(needed->obj, needed->obj, list);
2462 * Scan all of the DAGs rooted in the range of objects from "obj" to
2463 * "tail" and add their init functions to "list". This recurses over
2464 * the DAGs and ensure the proper init ordering such that each object's
2465 * needed libraries are initialized before the object itself. At the
2466 * same time, this function adds the objects to the global finalization
2467 * list "list_fini" in the opposite order. The write lock must be
2468 * held when this function is called.
2471 initlist_add_objects(Obj_Entry *obj, Obj_Entry *tail, Objlist *list)
2475 if (obj->init_scanned || obj->init_done)
2477 obj->init_scanned = true;
2479 /* Recursively process the successor objects. */
2480 nobj = globallist_next(obj);
2481 if (nobj != NULL && obj != tail)
2482 initlist_add_objects(nobj, tail, list);
2484 /* Recursively process the needed objects. */
2485 if (obj->needed != NULL)
2486 initlist_add_neededs(obj->needed, list);
2487 if (obj->needed_filtees != NULL)
2488 initlist_add_neededs(obj->needed_filtees, list);
2489 if (obj->needed_aux_filtees != NULL)
2490 initlist_add_neededs(obj->needed_aux_filtees, list);
2492 /* Add the object to the init list. */
2493 objlist_push_tail(list, obj);
2495 /* Add the object to the global fini list in the reverse order. */
2496 if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL)
2497 && !obj->on_fini_list) {
2498 objlist_push_head(&list_fini, obj);
2499 obj->on_fini_list = true;
2504 #define FPTR_TARGET(f) ((Elf_Addr) (f))
2508 free_needed_filtees(Needed_Entry *n, RtldLockState *lockstate)
2510 Needed_Entry *needed, *needed1;
2512 for (needed = n; needed != NULL; needed = needed->next) {
2513 if (needed->obj != NULL) {
2514 dlclose_locked(needed->obj, lockstate);
2518 for (needed = n; needed != NULL; needed = needed1) {
2519 needed1 = needed->next;
2525 unload_filtees(Obj_Entry *obj, RtldLockState *lockstate)
2528 free_needed_filtees(obj->needed_filtees, lockstate);
2529 obj->needed_filtees = NULL;
2530 free_needed_filtees(obj->needed_aux_filtees, lockstate);
2531 obj->needed_aux_filtees = NULL;
2532 obj->filtees_loaded = false;
2536 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags,
2537 RtldLockState *lockstate)
2540 for (; needed != NULL; needed = needed->next) {
2541 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
2542 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
2543 RTLD_LOCAL, lockstate);
2548 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
2551 lock_restart_for_upgrade(lockstate);
2552 if (!obj->filtees_loaded) {
2553 load_filtee1(obj, obj->needed_filtees, flags, lockstate);
2554 load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate);
2555 obj->filtees_loaded = true;
2560 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
2564 for (; needed != NULL; needed = needed->next) {
2565 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
2566 flags & ~RTLD_LO_NOLOAD);
2567 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
2574 * Given a shared object, traverse its list of needed objects, and load
2575 * each of them. Returns 0 on success. Generates an error message and
2576 * returns -1 on failure.
2579 load_needed_objects(Obj_Entry *first, int flags)
2583 for (obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
2586 if (process_needed(obj, obj->needed, flags) == -1)
2593 load_preload_objects(const char *penv, bool isfd)
2598 char savech, *p, *psave;
2600 static const char delim[] = " \t:;";
2605 p = psave = xstrdup(penv);
2606 p += strspn(p, delim);
2607 while (*p != '\0') {
2608 len = strcspn(p, delim);
2614 fd = parse_integer(p);
2624 obj = load_object(name, fd, NULL, 0);
2627 return (-1); /* XXX - cleanup */
2629 obj->z_interpose = true;
2632 p += strspn(p, delim);
2634 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
2641 printable_path(const char *path)
2644 return (path == NULL ? "<unknown>" : path);
2648 * Load a shared object into memory, if it is not already loaded. The
2649 * object may be specified by name or by user-supplied file descriptor
2650 * fd_u. In the later case, the fd_u descriptor is not closed, but its
2653 * Returns a pointer to the Obj_Entry for the object. Returns NULL
2657 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
2666 TAILQ_FOREACH(obj, &obj_list, next) {
2667 if (obj->marker || obj->doomed)
2669 if (object_match_name(obj, name))
2673 path = find_library(name, refobj, &fd);
2681 * search_library_pathfds() opens a fresh file descriptor for the
2682 * library, so there is no need to dup().
2684 } else if (fd_u == -1) {
2686 * If we didn't find a match by pathname, or the name is not
2687 * supplied, open the file and check again by device and inode.
2688 * This avoids false mismatches caused by multiple links or ".."
2691 * To avoid a race, we open the file and use fstat() rather than
2694 if ((fd = open(path, O_RDONLY | O_CLOEXEC | O_VERIFY)) == -1) {
2695 _rtld_error("Cannot open \"%s\"", path);
2700 fd = fcntl(fd_u, F_DUPFD_CLOEXEC, 0);
2702 _rtld_error("Cannot dup fd");
2707 if (fstat(fd, &sb) == -1) {
2708 _rtld_error("Cannot fstat \"%s\"", printable_path(path));
2713 TAILQ_FOREACH(obj, &obj_list, next) {
2714 if (obj->marker || obj->doomed)
2716 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
2719 if (obj != NULL && name != NULL) {
2720 object_add_name(obj, name);
2725 if (flags & RTLD_LO_NOLOAD) {
2731 /* First use of this object, so we must map it in */
2732 obj = do_load_object(fd, name, path, &sb, flags);
2741 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
2748 * First, make sure that environment variables haven't been
2749 * used to circumvent the noexec flag on a filesystem.
2750 * We ignore fstatfs(2) failures, since fd might reference
2751 * not a file, e.g. shmfd.
2753 if (dangerous_ld_env && fstatfs(fd, &fs) == 0 &&
2754 (fs.f_flags & MNT_NOEXEC) != 0) {
2755 _rtld_error("Cannot execute objects on %s", fs.f_mntonname);
2759 dbg("loading \"%s\"", printable_path(path));
2760 obj = map_object(fd, printable_path(path), sbp);
2765 * If DT_SONAME is present in the object, digest_dynamic2 already
2766 * added it to the object names.
2769 object_add_name(obj, name);
2771 if (!digest_dynamic(obj, 0))
2773 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path,
2774 obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount);
2775 if (obj->z_pie && (flags & RTLD_LO_TRACE) == 0) {
2776 dbg("refusing to load PIE executable \"%s\"", obj->path);
2777 _rtld_error("Cannot load PIE binary %s as DSO", obj->path);
2780 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
2782 dbg("refusing to load non-loadable \"%s\"", obj->path);
2783 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
2787 obj->dlopened = (flags & RTLD_LO_DLOPEN) != 0;
2788 TAILQ_INSERT_TAIL(&obj_list, obj, next);
2791 linkmap_add(obj); /* for GDB & dlinfo() */
2792 max_stack_flags |= obj->stack_flags;
2794 dbg(" %p .. %p: %s", obj->mapbase,
2795 obj->mapbase + obj->mapsize - 1, obj->path);
2797 dbg(" WARNING: %s has impure text", obj->path);
2798 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
2804 munmap(obj->mapbase, obj->mapsize);
2810 load_kpreload(const void *addr)
2813 const Elf_Ehdr *ehdr;
2814 const Elf_Phdr *phdr, *phlimit, *phdyn, *seg0, *segn;
2815 static const char kname[] = "[vdso]";
2818 if (!check_elf_headers(ehdr, "kpreload"))
2821 phdr = (const Elf_Phdr *)((const char *)addr + ehdr->e_phoff);
2823 obj->phsize = ehdr->e_phnum * sizeof(*phdr);
2824 phlimit = phdr + ehdr->e_phnum;
2827 for (; phdr < phlimit; phdr++) {
2828 switch (phdr->p_type) {
2833 /* Absense of PT_GNU_STACK implies stack_flags == 0. */
2834 obj->stack_flags = phdr->p_flags;
2837 if (seg0 == NULL || seg0->p_vaddr > phdr->p_vaddr)
2839 if (segn == NULL || segn->p_vaddr + segn->p_memsz <
2840 phdr->p_vaddr + phdr->p_memsz)
2846 obj->mapbase = __DECONST(caddr_t, addr);
2847 obj->mapsize = segn->p_vaddr + segn->p_memsz - (Elf_Addr)addr;
2849 obj->relocbase = obj->mapbase;
2851 object_add_name(obj, kname);
2852 obj->path = xstrdup(kname);
2853 obj->dynamic = (const Elf_Dyn *)(obj->relocbase + phdyn->p_vaddr);
2855 if (!digest_dynamic(obj, 0)) {
2861 * We assume that kernel-preloaded object does not need
2862 * relocation. It is currently written into read-only page,
2863 * handling relocations would mean we need to allocate at
2864 * least one additional page per AS.
2866 dbg("%s mapbase %p phdrs %p PT_LOAD phdr %p vaddr %p dynamic %p",
2867 obj->path, obj->mapbase, obj->phdr, seg0,
2868 obj->relocbase + seg0->p_vaddr, obj->dynamic);
2870 TAILQ_INSERT_TAIL(&obj_list, obj, next);
2873 linkmap_add(obj); /* for GDB & dlinfo() */
2874 max_stack_flags |= obj->stack_flags;
2876 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, 0, 0, obj->path);
2881 obj_from_addr(const void *addr)
2885 TAILQ_FOREACH(obj, &obj_list, next) {
2888 if (addr < (void *) obj->mapbase)
2890 if (addr < (void *)(obj->mapbase + obj->mapsize))
2899 Elf_Addr *preinit_addr;
2902 preinit_addr = (Elf_Addr *)obj_main->preinit_array;
2903 if (preinit_addr == NULL)
2906 for (index = 0; index < obj_main->preinit_array_num; index++) {
2907 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) {
2908 dbg("calling preinit function for %s at %p", obj_main->path,
2909 (void *)preinit_addr[index]);
2910 LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index],
2911 0, 0, obj_main->path);
2912 call_init_pointer(obj_main, preinit_addr[index]);
2918 * Call the finalization functions for each of the objects in "list"
2919 * belonging to the DAG of "root" and referenced once. If NULL "root"
2920 * is specified, every finalization function will be called regardless
2921 * of the reference count and the list elements won't be freed. All of
2922 * the objects are expected to have non-NULL fini functions.
2925 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
2928 struct dlerror_save *saved_msg;
2929 Elf_Addr *fini_addr;
2932 assert(root == NULL || root->refcount == 1);
2935 root->doomed = true;
2938 * Preserve the current error message since a fini function might
2939 * call into the dynamic linker and overwrite it.
2941 saved_msg = errmsg_save();
2943 STAILQ_FOREACH(elm, list, link) {
2944 if (root != NULL && (elm->obj->refcount != 1 ||
2945 objlist_find(&root->dagmembers, elm->obj) == NULL))
2947 /* Remove object from fini list to prevent recursive invocation. */
2948 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2949 /* Ensure that new references cannot be acquired. */
2950 elm->obj->doomed = true;
2952 hold_object(elm->obj);
2953 lock_release(rtld_bind_lock, lockstate);
2955 * It is legal to have both DT_FINI and DT_FINI_ARRAY defined.
2956 * When this happens, DT_FINI_ARRAY is processed first.
2958 fini_addr = (Elf_Addr *)elm->obj->fini_array;
2959 if (fini_addr != NULL && elm->obj->fini_array_num > 0) {
2960 for (index = elm->obj->fini_array_num - 1; index >= 0;
2962 if (fini_addr[index] != 0 && fini_addr[index] != 1) {
2963 dbg("calling fini function for %s at %p",
2964 elm->obj->path, (void *)fini_addr[index]);
2965 LD_UTRACE(UTRACE_FINI_CALL, elm->obj,
2966 (void *)fini_addr[index], 0, 0, elm->obj->path);
2967 call_initfini_pointer(elm->obj, fini_addr[index]);
2971 if (elm->obj->fini != (Elf_Addr)NULL) {
2972 dbg("calling fini function for %s at %p", elm->obj->path,
2973 (void *)elm->obj->fini);
2974 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini,
2975 0, 0, elm->obj->path);
2976 call_initfini_pointer(elm->obj, elm->obj->fini);
2978 wlock_acquire(rtld_bind_lock, lockstate);
2979 unhold_object(elm->obj);
2980 /* No need to free anything if process is going down. */
2984 * We must restart the list traversal after every fini call
2985 * because a dlclose() call from the fini function or from
2986 * another thread might have modified the reference counts.
2990 } while (elm != NULL);
2991 errmsg_restore(saved_msg);
2995 * Call the initialization functions for each of the objects in
2996 * "list". All of the objects are expected to have non-NULL init
3000 objlist_call_init(Objlist *list, RtldLockState *lockstate)
3004 struct dlerror_save *saved_msg;
3005 Elf_Addr *init_addr;
3006 void (*reg)(void (*)(void));
3010 * Clean init_scanned flag so that objects can be rechecked and
3011 * possibly initialized earlier if any of vectors called below
3012 * cause the change by using dlopen.
3014 TAILQ_FOREACH(obj, &obj_list, next) {
3017 obj->init_scanned = false;
3021 * Preserve the current error message since an init function might
3022 * call into the dynamic linker and overwrite it.
3024 saved_msg = errmsg_save();
3025 STAILQ_FOREACH(elm, list, link) {
3026 if (elm->obj->init_done) /* Initialized early. */
3029 * Race: other thread might try to use this object before current
3030 * one completes the initialization. Not much can be done here
3031 * without better locking.
3033 elm->obj->init_done = true;
3034 hold_object(elm->obj);
3036 if (elm->obj == obj_main && obj_main->crt_no_init) {
3037 reg = (void (*)(void (*)(void)))get_program_var_addr(
3038 "__libc_atexit", lockstate);
3040 lock_release(rtld_bind_lock, lockstate);
3043 rtld_exit_ptr = rtld_nop_exit;
3047 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined.
3048 * When this happens, DT_INIT is processed first.
3050 if (elm->obj->init != (Elf_Addr)NULL) {
3051 dbg("calling init function for %s at %p", elm->obj->path,
3052 (void *)elm->obj->init);
3053 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init,
3054 0, 0, elm->obj->path);
3055 call_init_pointer(elm->obj, elm->obj->init);
3057 init_addr = (Elf_Addr *)elm->obj->init_array;
3058 if (init_addr != NULL) {
3059 for (index = 0; index < elm->obj->init_array_num; index++) {
3060 if (init_addr[index] != 0 && init_addr[index] != 1) {
3061 dbg("calling init function for %s at %p", elm->obj->path,
3062 (void *)init_addr[index]);
3063 LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
3064 (void *)init_addr[index], 0, 0, elm->obj->path);
3065 call_init_pointer(elm->obj, init_addr[index]);
3069 wlock_acquire(rtld_bind_lock, lockstate);
3070 unhold_object(elm->obj);
3072 errmsg_restore(saved_msg);
3076 objlist_clear(Objlist *list)
3080 while (!STAILQ_EMPTY(list)) {
3081 elm = STAILQ_FIRST(list);
3082 STAILQ_REMOVE_HEAD(list, link);
3087 static Objlist_Entry *
3088 objlist_find(Objlist *list, const Obj_Entry *obj)
3092 STAILQ_FOREACH(elm, list, link)
3093 if (elm->obj == obj)
3099 objlist_init(Objlist *list)
3105 objlist_push_head(Objlist *list, Obj_Entry *obj)
3109 elm = NEW(Objlist_Entry);
3111 STAILQ_INSERT_HEAD(list, elm, link);
3115 objlist_push_tail(Objlist *list, Obj_Entry *obj)
3119 elm = NEW(Objlist_Entry);
3121 STAILQ_INSERT_TAIL(list, elm, link);
3125 objlist_put_after(Objlist *list, Obj_Entry *listobj, Obj_Entry *obj)
3127 Objlist_Entry *elm, *listelm;
3129 STAILQ_FOREACH(listelm, list, link) {
3130 if (listelm->obj == listobj)
3133 elm = NEW(Objlist_Entry);
3135 if (listelm != NULL)
3136 STAILQ_INSERT_AFTER(list, listelm, elm, link);
3138 STAILQ_INSERT_TAIL(list, elm, link);
3142 objlist_remove(Objlist *list, Obj_Entry *obj)
3146 if ((elm = objlist_find(list, obj)) != NULL) {
3147 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
3153 * Relocate dag rooted in the specified object.
3154 * Returns 0 on success, or -1 on failure.
3158 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj,
3159 int flags, RtldLockState *lockstate)
3165 STAILQ_FOREACH(elm, &root->dagmembers, link) {
3166 error = relocate_object(elm->obj, bind_now, rtldobj, flags,
3175 * Prepare for, or clean after, relocating an object marked with
3176 * DT_TEXTREL or DF_TEXTREL. Before relocating, all read-only
3177 * segments are remapped read-write. After relocations are done, the
3178 * segment's permissions are returned back to the modes specified in
3179 * the phdrs. If any relocation happened, or always for wired
3180 * program, COW is triggered.
3183 reloc_textrel_prot(Obj_Entry *obj, bool before)
3190 for (l = obj->phsize / sizeof(*ph), ph = obj->phdr; l > 0;
3192 if (ph->p_type != PT_LOAD || (ph->p_flags & PF_W) != 0)
3194 base = obj->relocbase + trunc_page(ph->p_vaddr);
3195 sz = round_page(ph->p_vaddr + ph->p_filesz) -
3196 trunc_page(ph->p_vaddr);
3197 prot = before ? (PROT_READ | PROT_WRITE) :
3198 convert_prot(ph->p_flags);
3199 if (mprotect(base, sz, prot) == -1) {
3200 _rtld_error("%s: Cannot write-%sable text segment: %s",
3201 obj->path, before ? "en" : "dis",
3202 rtld_strerror(errno));
3209 /* Process RELR relative relocations. */
3211 reloc_relr(Obj_Entry *obj)
3213 const Elf_Relr *relr, *relrlim;
3216 relrlim = (const Elf_Relr *)((const char *)obj->relr + obj->relrsize);
3217 for (relr = obj->relr; relr < relrlim; relr++) {
3218 Elf_Relr entry = *relr;
3220 if ((entry & 1) == 0) {
3221 where = (Elf_Addr *)(obj->relocbase + entry);
3222 *where++ += (Elf_Addr)obj->relocbase;
3224 for (long i = 0; (entry >>= 1) != 0; i++)
3225 if ((entry & 1) != 0)
3226 where[i] += (Elf_Addr)obj->relocbase;
3227 where += CHAR_BIT * sizeof(Elf_Relr) - 1;
3233 * Relocate single object.
3234 * Returns 0 on success, or -1 on failure.
3237 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
3238 int flags, RtldLockState *lockstate)
3243 obj->relocated = true;
3245 dbg("relocating \"%s\"", obj->path);
3247 if (obj->symtab == NULL || obj->strtab == NULL ||
3248 !(obj->valid_hash_sysv || obj->valid_hash_gnu))
3249 dbg("object %s has no run-time symbol table", obj->path);
3251 /* There are relocations to the write-protected text segment. */
3252 if (obj->textrel && reloc_textrel_prot(obj, true) != 0)
3255 /* Process the non-PLT non-IFUNC relocations. */
3256 if (reloc_non_plt(obj, rtldobj, flags, lockstate))
3260 /* Re-protected the text segment. */
3261 if (obj->textrel && reloc_textrel_prot(obj, false) != 0)
3264 /* Set the special PLT or GOT entries. */
3267 /* Process the PLT relocations. */
3268 if (reloc_plt(obj, flags, lockstate) == -1)
3270 /* Relocate the jump slots if we are doing immediate binding. */
3271 if ((obj->bind_now || bind_now) && reloc_jmpslots(obj, flags,
3275 if (!obj->mainprog && obj_enforce_relro(obj) == -1)
3279 * Set up the magic number and version in the Obj_Entry. These
3280 * were checked in the crt1.o from the original ElfKit, so we
3281 * set them for backward compatibility.
3283 obj->magic = RTLD_MAGIC;
3284 obj->version = RTLD_VERSION;
3290 * Relocate newly-loaded shared objects. The argument is a pointer to
3291 * the Obj_Entry for the first such object. All objects from the first
3292 * to the end of the list of objects are relocated. Returns 0 on success,
3296 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
3297 int flags, RtldLockState *lockstate)
3302 for (error = 0, obj = first; obj != NULL;
3303 obj = TAILQ_NEXT(obj, next)) {
3306 error = relocate_object(obj, bind_now, rtldobj, flags,
3315 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
3316 * referencing STT_GNU_IFUNC symbols is postponed till the other
3317 * relocations are done. The indirect functions specified as
3318 * ifunc are allowed to call other symbols, so we need to have
3319 * objects relocated before asking for resolution from indirects.
3321 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
3322 * instead of the usual lazy handling of PLT slots. It is
3323 * consistent with how GNU does it.
3326 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags,
3327 RtldLockState *lockstate)
3330 if (obj->ifuncs_resolved)
3332 obj->ifuncs_resolved = true;
3333 if (!obj->irelative && !obj->irelative_nonplt &&
3334 !((obj->bind_now || bind_now) && obj->gnu_ifunc) &&
3335 !obj->non_plt_gnu_ifunc)
3337 if (obj_disable_relro(obj) == -1 ||
3338 (obj->irelative && reloc_iresolve(obj, lockstate) == -1) ||
3339 (obj->irelative_nonplt && reloc_iresolve_nonplt(obj,
3340 lockstate) == -1) ||
3341 ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
3342 reloc_gnu_ifunc(obj, flags, lockstate) == -1) ||
3343 (obj->non_plt_gnu_ifunc && reloc_non_plt(obj, &obj_rtld,
3344 flags | SYMLOOK_IFUNC, lockstate) == -1) ||
3345 obj_enforce_relro(obj) == -1)
3351 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags,
3352 RtldLockState *lockstate)
3357 STAILQ_FOREACH(elm, list, link) {
3361 if (resolve_object_ifunc(obj, bind_now, flags,
3369 * Cleanup procedure. It will be called (by the atexit mechanism) just
3370 * before the process exits.
3375 RtldLockState lockstate;
3377 wlock_acquire(rtld_bind_lock, &lockstate);
3379 objlist_call_fini(&list_fini, NULL, &lockstate);
3380 /* No need to remove the items from the list, since we are exiting. */
3381 if (!libmap_disable)
3383 lock_release(rtld_bind_lock, &lockstate);
3392 * Iterate over a search path, translate each element, and invoke the
3393 * callback on the result.
3396 path_enumerate(const char *path, path_enum_proc callback,
3397 const char *refobj_path, void *arg)
3403 path += strspn(path, ":;");
3404 while (*path != '\0') {
3408 len = strcspn(path, ":;");
3409 trans = lm_findn(refobj_path, path, len);
3411 res = callback(trans, strlen(trans), arg);
3413 res = callback(path, len, arg);
3419 path += strspn(path, ":;");
3425 struct try_library_args {
3434 try_library_path(const char *dir, size_t dirlen, void *param)
3436 struct try_library_args *arg;
3440 if (*dir == '/' || trust) {
3443 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
3446 pathname = arg->buffer;
3447 strncpy(pathname, dir, dirlen);
3448 pathname[dirlen] = '/';
3449 strcpy(pathname + dirlen + 1, arg->name);
3451 dbg(" Trying \"%s\"", pathname);
3452 fd = open(pathname, O_RDONLY | O_CLOEXEC | O_VERIFY);
3454 dbg(" Opened \"%s\", fd %d", pathname, fd);
3455 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
3456 strcpy(pathname, arg->buffer);
3460 dbg(" Failed to open \"%s\": %s",
3461 pathname, rtld_strerror(errno));
3468 search_library_path(const char *name, const char *path,
3469 const char *refobj_path, int *fdp)
3472 struct try_library_args arg;
3478 arg.namelen = strlen(name);
3479 arg.buffer = xmalloc(PATH_MAX);
3480 arg.buflen = PATH_MAX;
3483 p = path_enumerate(path, try_library_path, refobj_path, &arg);
3493 * Finds the library with the given name using the directory descriptors
3494 * listed in the LD_LIBRARY_PATH_FDS environment variable.
3496 * Returns a freshly-opened close-on-exec file descriptor for the library,
3497 * or -1 if the library cannot be found.
3500 search_library_pathfds(const char *name, const char *path, int *fdp)
3502 char *envcopy, *fdstr, *found, *last_token;
3506 dbg("%s('%s', '%s', fdp)", __func__, name, path);
3508 /* Don't load from user-specified libdirs into setuid binaries. */
3512 /* We can't do anything if LD_LIBRARY_PATH_FDS isn't set. */
3516 /* LD_LIBRARY_PATH_FDS only works with relative paths. */
3517 if (name[0] == '/') {
3518 dbg("Absolute path (%s) passed to %s", name, __func__);
3523 * Use strtok_r() to walk the FD:FD:FD list. This requires a local
3524 * copy of the path, as strtok_r rewrites separator tokens
3528 envcopy = xstrdup(path);
3529 for (fdstr = strtok_r(envcopy, ":", &last_token); fdstr != NULL;
3530 fdstr = strtok_r(NULL, ":", &last_token)) {
3531 dirfd = parse_integer(fdstr);
3533 _rtld_error("failed to parse directory FD: '%s'",
3537 fd = __sys_openat(dirfd, name, O_RDONLY | O_CLOEXEC | O_VERIFY);
3540 len = strlen(fdstr) + strlen(name) + 3;
3541 found = xmalloc(len);
3542 if (rtld_snprintf(found, len, "#%d/%s", dirfd, name) < 0) {
3543 _rtld_error("error generating '%d/%s'",
3547 dbg("open('%s') => %d", found, fd);
3558 dlclose(void *handle)
3560 RtldLockState lockstate;
3563 wlock_acquire(rtld_bind_lock, &lockstate);
3564 error = dlclose_locked(handle, &lockstate);
3565 lock_release(rtld_bind_lock, &lockstate);
3570 dlclose_locked(void *handle, RtldLockState *lockstate)
3574 root = dlcheck(handle);
3577 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
3580 /* Unreference the object and its dependencies. */
3581 root->dl_refcount--;
3583 if (root->refcount == 1) {
3585 * The object will be no longer referenced, so we must unload it.
3586 * First, call the fini functions.
3588 objlist_call_fini(&list_fini, root, lockstate);
3592 /* Finish cleaning up the newly-unreferenced objects. */
3593 GDB_STATE(RT_DELETE,&root->linkmap);
3594 unload_object(root, lockstate);
3595 GDB_STATE(RT_CONSISTENT,NULL);
3599 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
3606 if (*(lockinfo.dlerror_seen()) != 0)
3608 *lockinfo.dlerror_seen() = 1;
3609 return (lockinfo.dlerror_loc());
3613 * This function is deprecated and has no effect.
3616 dllockinit(void *context,
3617 void *(*_lock_create)(void *context) __unused,
3618 void (*_rlock_acquire)(void *lock) __unused,
3619 void (*_wlock_acquire)(void *lock) __unused,
3620 void (*_lock_release)(void *lock) __unused,
3621 void (*_lock_destroy)(void *lock) __unused,
3622 void (*context_destroy)(void *context))
3624 static void *cur_context;
3625 static void (*cur_context_destroy)(void *);
3627 /* Just destroy the context from the previous call, if necessary. */
3628 if (cur_context_destroy != NULL)
3629 cur_context_destroy(cur_context);
3630 cur_context = context;
3631 cur_context_destroy = context_destroy;
3635 dlopen(const char *name, int mode)
3638 return (rtld_dlopen(name, -1, mode));
3642 fdlopen(int fd, int mode)
3645 return (rtld_dlopen(NULL, fd, mode));
3649 rtld_dlopen(const char *name, int fd, int mode)
3651 RtldLockState lockstate;
3654 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
3655 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
3656 if (ld_tracing != NULL) {
3657 rlock_acquire(rtld_bind_lock, &lockstate);
3658 if (sigsetjmp(lockstate.env, 0) != 0)
3659 lock_upgrade(rtld_bind_lock, &lockstate);
3660 environ = __DECONST(char **, *get_program_var_addr("environ", &lockstate));
3661 lock_release(rtld_bind_lock, &lockstate);
3663 lo_flags = RTLD_LO_DLOPEN;
3664 if (mode & RTLD_NODELETE)
3665 lo_flags |= RTLD_LO_NODELETE;
3666 if (mode & RTLD_NOLOAD)
3667 lo_flags |= RTLD_LO_NOLOAD;
3668 if (mode & RTLD_DEEPBIND)
3669 lo_flags |= RTLD_LO_DEEPBIND;
3670 if (ld_tracing != NULL)
3671 lo_flags |= RTLD_LO_TRACE | RTLD_LO_IGNSTLS;
3673 return (dlopen_object(name, fd, obj_main, lo_flags,
3674 mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL));
3678 dlopen_cleanup(Obj_Entry *obj, RtldLockState *lockstate)
3683 if (obj->refcount == 0)
3684 unload_object(obj, lockstate);
3688 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
3689 int mode, RtldLockState *lockstate)
3691 Obj_Entry *old_obj_tail;
3694 RtldLockState mlockstate;
3697 dbg("dlopen_object name \"%s\" fd %d refobj \"%s\" lo_flags %#x mode %#x",
3698 name != NULL ? name : "<null>", fd, refobj == NULL ? "<null>" :
3699 refobj->path, lo_flags, mode);
3700 objlist_init(&initlist);
3702 if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) {
3703 wlock_acquire(rtld_bind_lock, &mlockstate);
3704 lockstate = &mlockstate;
3706 GDB_STATE(RT_ADD,NULL);
3708 old_obj_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
3710 if (name == NULL && fd == -1) {
3714 obj = load_object(name, fd, refobj, lo_flags);
3719 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
3720 objlist_push_tail(&list_global, obj);
3721 if (globallist_next(old_obj_tail) != NULL) {
3722 /* We loaded something new. */
3723 assert(globallist_next(old_obj_tail) == obj);
3724 if ((lo_flags & RTLD_LO_DEEPBIND) != 0)
3725 obj->symbolic = true;
3727 if ((lo_flags & (RTLD_LO_EARLY | RTLD_LO_IGNSTLS)) == 0 &&
3728 obj->static_tls && !allocate_tls_offset(obj)) {
3729 _rtld_error("%s: No space available "
3730 "for static Thread Local Storage", obj->path);
3734 result = load_needed_objects(obj, lo_flags & (RTLD_LO_DLOPEN |
3735 RTLD_LO_EARLY | RTLD_LO_IGNSTLS | RTLD_LO_TRACE));
3739 result = rtld_verify_versions(&obj->dagmembers);
3740 if (result != -1 && ld_tracing)
3742 if (result == -1 || relocate_object_dag(obj,
3743 (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld,
3744 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3746 dlopen_cleanup(obj, lockstate);
3748 } else if (lo_flags & RTLD_LO_EARLY) {
3750 * Do not call the init functions for early loaded
3751 * filtees. The image is still not initialized enough
3754 * Our object is found by the global object list and
3755 * will be ordered among all init calls done right
3756 * before transferring control to main.
3759 /* Make list of init functions to call. */
3760 initlist_add_objects(obj, obj, &initlist);
3763 * Process all no_delete or global objects here, given
3764 * them own DAGs to prevent their dependencies from being
3765 * unloaded. This has to be done after we have loaded all
3766 * of the dependencies, so that we do not miss any.
3772 * Bump the reference counts for objects on this DAG. If
3773 * this is the first dlopen() call for the object that was
3774 * already loaded as a dependency, initialize the dag
3780 if ((lo_flags & RTLD_LO_TRACE) != 0)
3783 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
3784 obj->z_nodelete) && !obj->ref_nodel) {
3785 dbg("obj %s nodelete", obj->path);
3787 obj->z_nodelete = obj->ref_nodel = true;
3791 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
3793 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
3795 if ((lo_flags & RTLD_LO_EARLY) == 0) {
3796 map_stacks_exec(lockstate);
3798 distribute_static_tls(&initlist, lockstate);
3801 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
3802 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3804 objlist_clear(&initlist);
3805 dlopen_cleanup(obj, lockstate);
3806 if (lockstate == &mlockstate)
3807 lock_release(rtld_bind_lock, lockstate);
3811 if (!(lo_flags & RTLD_LO_EARLY)) {
3812 /* Call the init functions. */
3813 objlist_call_init(&initlist, lockstate);
3815 objlist_clear(&initlist);
3816 if (lockstate == &mlockstate)
3817 lock_release(rtld_bind_lock, lockstate);
3820 trace_loaded_objects(obj);
3821 if (lockstate == &mlockstate)
3822 lock_release(rtld_bind_lock, lockstate);
3827 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
3831 const Obj_Entry *obj, *defobj;
3834 RtldLockState lockstate;
3841 symlook_init(&req, name);
3843 req.flags = flags | SYMLOOK_IN_PLT;
3844 req.lockstate = &lockstate;
3846 LD_UTRACE(UTRACE_DLSYM_START, handle, NULL, 0, 0, name);
3847 rlock_acquire(rtld_bind_lock, &lockstate);
3848 if (sigsetjmp(lockstate.env, 0) != 0)
3849 lock_upgrade(rtld_bind_lock, &lockstate);
3850 if (handle == NULL || handle == RTLD_NEXT ||
3851 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
3853 if ((obj = obj_from_addr(retaddr)) == NULL) {
3854 _rtld_error("Cannot determine caller's shared object");
3855 lock_release(rtld_bind_lock, &lockstate);
3856 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3859 if (handle == NULL) { /* Just the caller's shared object. */
3860 res = symlook_obj(&req, obj);
3863 defobj = req.defobj_out;
3865 } else if (handle == RTLD_NEXT || /* Objects after caller's */
3866 handle == RTLD_SELF) { /* ... caller included */
3867 if (handle == RTLD_NEXT)
3868 obj = globallist_next(obj);
3869 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
3872 res = symlook_obj(&req, obj);
3874 if (def == NULL || (ld_dynamic_weak &&
3875 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK)) {
3877 defobj = req.defobj_out;
3878 if (!ld_dynamic_weak ||
3879 ELF_ST_BIND(def->st_info) != STB_WEAK)
3885 * Search the dynamic linker itself, and possibly resolve the
3886 * symbol from there. This is how the application links to
3887 * dynamic linker services such as dlopen.
3888 * Note that we ignore ld_dynamic_weak == false case,
3889 * always overriding weak symbols by rtld definitions.
3891 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3892 res = symlook_obj(&req, &obj_rtld);
3895 defobj = req.defobj_out;
3899 assert(handle == RTLD_DEFAULT);
3900 res = symlook_default(&req, obj);
3902 defobj = req.defobj_out;
3907 if ((obj = dlcheck(handle)) == NULL) {
3908 lock_release(rtld_bind_lock, &lockstate);
3909 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3913 donelist_init(&donelist);
3914 if (obj->mainprog) {
3915 /* Handle obtained by dlopen(NULL, ...) implies global scope. */
3916 res = symlook_global(&req, &donelist);
3919 defobj = req.defobj_out;
3922 * Search the dynamic linker itself, and possibly resolve the
3923 * symbol from there. This is how the application links to
3924 * dynamic linker services such as dlopen.
3926 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3927 res = symlook_obj(&req, &obj_rtld);
3930 defobj = req.defobj_out;
3935 /* Search the whole DAG rooted at the given object. */
3936 res = symlook_list(&req, &obj->dagmembers, &donelist);
3939 defobj = req.defobj_out;
3945 lock_release(rtld_bind_lock, &lockstate);
3948 * The value required by the caller is derived from the value
3949 * of the symbol. this is simply the relocated value of the
3952 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
3953 sym = make_function_pointer(def, defobj);
3954 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
3955 sym = rtld_resolve_ifunc(defobj, def);
3956 else if (ELF_ST_TYPE(def->st_info) == STT_TLS) {
3957 ti.ti_module = defobj->tlsindex;
3958 ti.ti_offset = def->st_value;
3959 sym = __tls_get_addr(&ti);
3961 sym = defobj->relocbase + def->st_value;
3962 LD_UTRACE(UTRACE_DLSYM_STOP, handle, sym, 0, 0, name);
3966 _rtld_error("Undefined symbol \"%s%s%s\"", name, ve != NULL ? "@" : "",
3967 ve != NULL ? ve->name : "");
3968 lock_release(rtld_bind_lock, &lockstate);
3969 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3974 dlsym(void *handle, const char *name)
3976 return (do_dlsym(handle, name, __builtin_return_address(0), NULL,
3981 dlfunc(void *handle, const char *name)
3988 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
3994 dlvsym(void *handle, const char *name, const char *version)
3998 ventry.name = version;
4000 ventry.hash = elf_hash(version);
4002 return (do_dlsym(handle, name, __builtin_return_address(0), &ventry,
4007 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
4009 const Obj_Entry *obj;
4010 RtldLockState lockstate;
4012 rlock_acquire(rtld_bind_lock, &lockstate);
4013 obj = obj_from_addr(addr);
4015 _rtld_error("No shared object contains address");
4016 lock_release(rtld_bind_lock, &lockstate);
4019 rtld_fill_dl_phdr_info(obj, phdr_info);
4020 lock_release(rtld_bind_lock, &lockstate);
4025 dladdr(const void *addr, Dl_info *info)
4027 const Obj_Entry *obj;
4030 unsigned long symoffset;
4031 RtldLockState lockstate;
4033 rlock_acquire(rtld_bind_lock, &lockstate);
4034 obj = obj_from_addr(addr);
4036 _rtld_error("No shared object contains address");
4037 lock_release(rtld_bind_lock, &lockstate);
4040 info->dli_fname = obj->path;
4041 info->dli_fbase = obj->mapbase;
4042 info->dli_saddr = (void *)0;
4043 info->dli_sname = NULL;
4046 * Walk the symbol list looking for the symbol whose address is
4047 * closest to the address sent in.
4049 for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) {
4050 def = obj->symtab + symoffset;
4053 * For skip the symbol if st_shndx is either SHN_UNDEF or
4056 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
4060 * If the symbol is greater than the specified address, or if it
4061 * is further away from addr than the current nearest symbol,
4064 symbol_addr = obj->relocbase + def->st_value;
4065 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
4068 /* Update our idea of the nearest symbol. */
4069 info->dli_sname = obj->strtab + def->st_name;
4070 info->dli_saddr = symbol_addr;
4073 if (info->dli_saddr == addr)
4076 lock_release(rtld_bind_lock, &lockstate);
4081 dlinfo(void *handle, int request, void *p)
4083 const Obj_Entry *obj;
4084 RtldLockState lockstate;
4087 rlock_acquire(rtld_bind_lock, &lockstate);
4089 if (handle == NULL || handle == RTLD_SELF) {
4092 retaddr = __builtin_return_address(0); /* __GNUC__ only */
4093 if ((obj = obj_from_addr(retaddr)) == NULL)
4094 _rtld_error("Cannot determine caller's shared object");
4096 obj = dlcheck(handle);
4099 lock_release(rtld_bind_lock, &lockstate);
4105 case RTLD_DI_LINKMAP:
4106 *((struct link_map const **)p) = &obj->linkmap;
4108 case RTLD_DI_ORIGIN:
4109 error = rtld_dirname(obj->path, p);
4112 case RTLD_DI_SERINFOSIZE:
4113 case RTLD_DI_SERINFO:
4114 error = do_search_info(obj, request, (struct dl_serinfo *)p);
4118 _rtld_error("Invalid request %d passed to dlinfo()", request);
4122 lock_release(rtld_bind_lock, &lockstate);
4128 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
4132 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
4133 phdr_info->dlpi_name = obj->path;
4134 phdr_info->dlpi_phdr = obj->phdr;
4135 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
4136 phdr_info->dlpi_tls_modid = obj->tlsindex;
4137 dtvp = &_tcb_get()->tcb_dtv;
4138 phdr_info->dlpi_tls_data = (char *)tls_get_addr_slow(dtvp,
4139 obj->tlsindex, 0, true) + TLS_DTV_OFFSET;
4140 phdr_info->dlpi_adds = obj_loads;
4141 phdr_info->dlpi_subs = obj_loads - obj_count;
4145 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
4147 struct dl_phdr_info phdr_info;
4148 Obj_Entry *obj, marker;
4149 RtldLockState bind_lockstate, phdr_lockstate;
4152 init_marker(&marker);
4155 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
4156 wlock_acquire(rtld_bind_lock, &bind_lockstate);
4157 for (obj = globallist_curr(TAILQ_FIRST(&obj_list)); obj != NULL;) {
4158 TAILQ_INSERT_AFTER(&obj_list, obj, &marker, next);
4159 rtld_fill_dl_phdr_info(obj, &phdr_info);
4161 lock_release(rtld_bind_lock, &bind_lockstate);
4163 error = callback(&phdr_info, sizeof phdr_info, param);
4165 wlock_acquire(rtld_bind_lock, &bind_lockstate);
4167 obj = globallist_next(&marker);
4168 TAILQ_REMOVE(&obj_list, &marker, next);
4170 lock_release(rtld_bind_lock, &bind_lockstate);
4171 lock_release(rtld_phdr_lock, &phdr_lockstate);
4177 rtld_fill_dl_phdr_info(&obj_rtld, &phdr_info);
4178 lock_release(rtld_bind_lock, &bind_lockstate);
4179 error = callback(&phdr_info, sizeof(phdr_info), param);
4181 lock_release(rtld_phdr_lock, &phdr_lockstate);
4186 fill_search_info(const char *dir, size_t dirlen, void *param)
4188 struct fill_search_info_args *arg;
4192 if (arg->request == RTLD_DI_SERINFOSIZE) {
4193 arg->serinfo->dls_cnt ++;
4194 arg->serinfo->dls_size += sizeof(struct dl_serpath) + dirlen + 1;
4196 struct dl_serpath *s_entry;
4198 s_entry = arg->serpath;
4199 s_entry->dls_name = arg->strspace;
4200 s_entry->dls_flags = arg->flags;
4202 strncpy(arg->strspace, dir, dirlen);
4203 arg->strspace[dirlen] = '\0';
4205 arg->strspace += dirlen + 1;
4213 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
4215 struct dl_serinfo _info;
4216 struct fill_search_info_args args;
4218 args.request = RTLD_DI_SERINFOSIZE;
4219 args.serinfo = &_info;
4221 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
4224 path_enumerate(obj->rpath, fill_search_info, NULL, &args);
4225 path_enumerate(ld_library_path, fill_search_info, NULL, &args);
4226 path_enumerate(obj->runpath, fill_search_info, NULL, &args);
4227 path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args);
4228 if (!obj->z_nodeflib)
4229 path_enumerate(ld_standard_library_path, fill_search_info, NULL, &args);
4232 if (request == RTLD_DI_SERINFOSIZE) {
4233 info->dls_size = _info.dls_size;
4234 info->dls_cnt = _info.dls_cnt;
4238 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
4239 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
4243 args.request = RTLD_DI_SERINFO;
4244 args.serinfo = info;
4245 args.serpath = &info->dls_serpath[0];
4246 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
4248 args.flags = LA_SER_RUNPATH;
4249 if (path_enumerate(obj->rpath, fill_search_info, NULL, &args) != NULL)
4252 args.flags = LA_SER_LIBPATH;
4253 if (path_enumerate(ld_library_path, fill_search_info, NULL, &args) != NULL)
4256 args.flags = LA_SER_RUNPATH;
4257 if (path_enumerate(obj->runpath, fill_search_info, NULL, &args) != NULL)
4260 args.flags = LA_SER_CONFIG;
4261 if (path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args)
4265 args.flags = LA_SER_DEFAULT;
4266 if (!obj->z_nodeflib && path_enumerate(ld_standard_library_path,
4267 fill_search_info, NULL, &args) != NULL)
4273 rtld_dirname(const char *path, char *bname)
4277 /* Empty or NULL string gets treated as "." */
4278 if (path == NULL || *path == '\0') {
4284 /* Strip trailing slashes */
4285 endp = path + strlen(path) - 1;
4286 while (endp > path && *endp == '/')
4289 /* Find the start of the dir */
4290 while (endp > path && *endp != '/')
4293 /* Either the dir is "/" or there are no slashes */
4295 bname[0] = *endp == '/' ? '/' : '.';
4301 } while (endp > path && *endp == '/');
4304 if (endp - path + 2 > PATH_MAX)
4306 _rtld_error("Filename is too long: %s", path);
4310 strncpy(bname, path, endp - path + 1);
4311 bname[endp - path + 1] = '\0';
4316 rtld_dirname_abs(const char *path, char *base)
4320 if (realpath(path, base) == NULL) {
4321 _rtld_error("realpath \"%s\" failed (%s)", path,
4322 rtld_strerror(errno));
4325 dbg("%s -> %s", path, base);
4326 last = strrchr(base, '/');
4328 _rtld_error("non-abs result from realpath \"%s\"", path);
4337 linkmap_add(Obj_Entry *obj)
4339 struct link_map *l, *prev;
4342 l->l_name = obj->path;
4343 l->l_base = obj->mapbase;
4344 l->l_ld = obj->dynamic;
4345 l->l_addr = obj->relocbase;
4347 if (r_debug.r_map == NULL) {
4353 * Scan to the end of the list, but not past the entry for the
4354 * dynamic linker, which we want to keep at the very end.
4356 for (prev = r_debug.r_map;
4357 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
4358 prev = prev->l_next)
4361 /* Link in the new entry. */
4363 l->l_next = prev->l_next;
4364 if (l->l_next != NULL)
4365 l->l_next->l_prev = l;
4370 linkmap_delete(Obj_Entry *obj)
4375 if (l->l_prev == NULL) {
4376 if ((r_debug.r_map = l->l_next) != NULL)
4377 l->l_next->l_prev = NULL;
4381 if ((l->l_prev->l_next = l->l_next) != NULL)
4382 l->l_next->l_prev = l->l_prev;
4386 * Function for the debugger to set a breakpoint on to gain control.
4388 * The two parameters allow the debugger to easily find and determine
4389 * what the runtime loader is doing and to whom it is doing it.
4391 * When the loadhook trap is hit (r_debug_state, set at program
4392 * initialization), the arguments can be found on the stack:
4394 * +8 struct link_map *m
4395 * +4 struct r_debug *rd
4399 r_debug_state(struct r_debug* rd __unused, struct link_map *m __unused)
4402 * The following is a hack to force the compiler to emit calls to
4403 * this function, even when optimizing. If the function is empty,
4404 * the compiler is not obliged to emit any code for calls to it,
4405 * even when marked __noinline. However, gdb depends on those
4408 __compiler_membar();
4412 * A function called after init routines have completed. This can be used to
4413 * break before a program's entry routine is called, and can be used when
4414 * main is not available in the symbol table.
4417 _r_debug_postinit(struct link_map *m __unused)
4420 /* See r_debug_state(). */
4421 __compiler_membar();
4425 release_object(Obj_Entry *obj)
4428 if (obj->holdcount > 0) {
4429 obj->unholdfree = true;
4432 munmap(obj->mapbase, obj->mapsize);
4433 linkmap_delete(obj);
4438 * Get address of the pointer variable in the main program.
4439 * Prefer non-weak symbol over the weak one.
4441 static const void **
4442 get_program_var_addr(const char *name, RtldLockState *lockstate)
4447 symlook_init(&req, name);
4448 req.lockstate = lockstate;
4449 donelist_init(&donelist);
4450 if (symlook_global(&req, &donelist) != 0)
4452 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
4453 return ((const void **)make_function_pointer(req.sym_out,
4455 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
4456 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
4458 return ((const void **)(req.defobj_out->relocbase +
4459 req.sym_out->st_value));
4463 * Set a pointer variable in the main program to the given value. This
4464 * is used to set key variables such as "environ" before any of the
4465 * init functions are called.
4468 set_program_var(const char *name, const void *value)
4472 if ((addr = get_program_var_addr(name, NULL)) != NULL) {
4473 dbg("\"%s\": *%p <-- %p", name, addr, value);
4479 * Search the global objects, including dependencies and main object,
4480 * for the given symbol.
4483 symlook_global(SymLook *req, DoneList *donelist)
4486 const Objlist_Entry *elm;
4489 symlook_init_from_req(&req1, req);
4491 /* Search all objects loaded at program start up. */
4492 if (req->defobj_out == NULL || (ld_dynamic_weak &&
4493 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK)) {
4494 res = symlook_list(&req1, &list_main, donelist);
4495 if (res == 0 && (!ld_dynamic_weak || req->defobj_out == NULL ||
4496 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4497 req->sym_out = req1.sym_out;
4498 req->defobj_out = req1.defobj_out;
4499 assert(req->defobj_out != NULL);
4503 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
4504 STAILQ_FOREACH(elm, &list_global, link) {
4505 if (req->defobj_out != NULL && (!ld_dynamic_weak ||
4506 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK))
4508 res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
4509 if (res == 0 && (req->defobj_out == NULL ||
4510 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4511 req->sym_out = req1.sym_out;
4512 req->defobj_out = req1.defobj_out;
4513 assert(req->defobj_out != NULL);
4517 return (req->sym_out != NULL ? 0 : ESRCH);
4521 * Given a symbol name in a referencing object, find the corresponding
4522 * definition of the symbol. Returns a pointer to the symbol, or NULL if
4523 * no definition was found. Returns a pointer to the Obj_Entry of the
4524 * defining object via the reference parameter DEFOBJ_OUT.
4527 symlook_default(SymLook *req, const Obj_Entry *refobj)
4530 const Objlist_Entry *elm;
4534 donelist_init(&donelist);
4535 symlook_init_from_req(&req1, req);
4538 * Look first in the referencing object if linked symbolically,
4539 * and similarly handle protected symbols.
4541 res = symlook_obj(&req1, refobj);
4542 if (res == 0 && (refobj->symbolic ||
4543 ELF_ST_VISIBILITY(req1.sym_out->st_other) == STV_PROTECTED)) {
4544 req->sym_out = req1.sym_out;
4545 req->defobj_out = req1.defobj_out;
4546 assert(req->defobj_out != NULL);
4548 if (refobj->symbolic || req->defobj_out != NULL)
4549 donelist_check(&donelist, refobj);
4551 symlook_global(req, &donelist);
4553 /* Search all dlopened DAGs containing the referencing object. */
4554 STAILQ_FOREACH(elm, &refobj->dldags, link) {
4555 if (req->sym_out != NULL && (!ld_dynamic_weak ||
4556 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK))
4558 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
4559 if (res == 0 && (req->sym_out == NULL ||
4560 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4561 req->sym_out = req1.sym_out;
4562 req->defobj_out = req1.defobj_out;
4563 assert(req->defobj_out != NULL);
4568 * Search the dynamic linker itself, and possibly resolve the
4569 * symbol from there. This is how the application links to
4570 * dynamic linker services such as dlopen.
4572 if (req->sym_out == NULL ||
4573 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
4574 res = symlook_obj(&req1, &obj_rtld);
4576 req->sym_out = req1.sym_out;
4577 req->defobj_out = req1.defobj_out;
4578 assert(req->defobj_out != NULL);
4582 return (req->sym_out != NULL ? 0 : ESRCH);
4586 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
4589 const Obj_Entry *defobj;
4590 const Objlist_Entry *elm;
4596 STAILQ_FOREACH(elm, objlist, link) {
4597 if (donelist_check(dlp, elm->obj))
4599 symlook_init_from_req(&req1, req);
4600 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
4601 if (def == NULL || (ld_dynamic_weak &&
4602 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4604 defobj = req1.defobj_out;
4605 if (!ld_dynamic_weak || ELF_ST_BIND(def->st_info) != STB_WEAK)
4612 req->defobj_out = defobj;
4619 * Search the chain of DAGS cointed to by the given Needed_Entry
4620 * for a symbol of the given name. Each DAG is scanned completely
4621 * before advancing to the next one. Returns a pointer to the symbol,
4622 * or NULL if no definition was found.
4625 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
4628 const Needed_Entry *n;
4629 const Obj_Entry *defobj;
4635 symlook_init_from_req(&req1, req);
4636 for (n = needed; n != NULL; n = n->next) {
4637 if (n->obj == NULL ||
4638 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
4640 if (def == NULL || (ld_dynamic_weak &&
4641 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4643 defobj = req1.defobj_out;
4644 if (!ld_dynamic_weak || ELF_ST_BIND(def->st_info) != STB_WEAK)
4650 req->defobj_out = defobj;
4657 * Search the symbol table of a single shared object for a symbol of
4658 * the given name and version, if requested. Returns a pointer to the
4659 * symbol, or NULL if no definition was found. If the object is
4660 * filter, return filtered symbol from filtee.
4662 * The symbol's hash value is passed in for efficiency reasons; that
4663 * eliminates many recomputations of the hash value.
4666 symlook_obj(SymLook *req, const Obj_Entry *obj)
4670 int flags, res, mres;
4673 * If there is at least one valid hash at this point, we prefer to
4674 * use the faster GNU version if available.
4676 if (obj->valid_hash_gnu)
4677 mres = symlook_obj1_gnu(req, obj);
4678 else if (obj->valid_hash_sysv)
4679 mres = symlook_obj1_sysv(req, obj);
4684 if (obj->needed_filtees != NULL) {
4685 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4686 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4687 donelist_init(&donelist);
4688 symlook_init_from_req(&req1, req);
4689 res = symlook_needed(&req1, obj->needed_filtees, &donelist);
4691 req->sym_out = req1.sym_out;
4692 req->defobj_out = req1.defobj_out;
4696 if (obj->needed_aux_filtees != NULL) {
4697 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4698 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4699 donelist_init(&donelist);
4700 symlook_init_from_req(&req1, req);
4701 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
4703 req->sym_out = req1.sym_out;
4704 req->defobj_out = req1.defobj_out;
4712 /* Symbol match routine common to both hash functions */
4714 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result,
4715 const unsigned long symnum)
4718 const Elf_Sym *symp;
4721 symp = obj->symtab + symnum;
4722 strp = obj->strtab + symp->st_name;
4724 switch (ELF_ST_TYPE(symp->st_info)) {
4730 if (symp->st_value == 0)
4734 if (symp->st_shndx != SHN_UNDEF)
4736 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
4737 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
4743 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
4746 if (req->ventry == NULL) {
4747 if (obj->versyms != NULL) {
4748 verndx = VER_NDX(obj->versyms[symnum]);
4749 if (verndx > obj->vernum) {
4751 "%s: symbol %s references wrong version %d",
4752 obj->path, obj->strtab + symnum, verndx);
4756 * If we are not called from dlsym (i.e. this
4757 * is a normal relocation from unversioned
4758 * binary), accept the symbol immediately if
4759 * it happens to have first version after this
4760 * shared object became versioned. Otherwise,
4761 * if symbol is versioned and not hidden,
4762 * remember it. If it is the only symbol with
4763 * this name exported by the shared object, it
4764 * will be returned as a match by the calling
4765 * function. If symbol is global (verndx < 2)
4766 * accept it unconditionally.
4768 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
4769 verndx == VER_NDX_GIVEN) {
4770 result->sym_out = symp;
4773 else if (verndx >= VER_NDX_GIVEN) {
4774 if ((obj->versyms[symnum] & VER_NDX_HIDDEN)
4776 if (result->vsymp == NULL)
4777 result->vsymp = symp;
4783 result->sym_out = symp;
4786 if (obj->versyms == NULL) {
4787 if (object_match_name(obj, req->ventry->name)) {
4788 _rtld_error("%s: object %s should provide version %s "
4789 "for symbol %s", obj_rtld.path, obj->path,
4790 req->ventry->name, obj->strtab + symnum);
4794 verndx = VER_NDX(obj->versyms[symnum]);
4795 if (verndx > obj->vernum) {
4796 _rtld_error("%s: symbol %s references wrong version %d",
4797 obj->path, obj->strtab + symnum, verndx);
4800 if (obj->vertab[verndx].hash != req->ventry->hash ||
4801 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
4803 * Version does not match. Look if this is a
4804 * global symbol and if it is not hidden. If
4805 * global symbol (verndx < 2) is available,
4806 * use it. Do not return symbol if we are
4807 * called by dlvsym, because dlvsym looks for
4808 * a specific version and default one is not
4809 * what dlvsym wants.
4811 if ((req->flags & SYMLOOK_DLSYM) ||
4812 (verndx >= VER_NDX_GIVEN) ||
4813 (obj->versyms[symnum] & VER_NDX_HIDDEN))
4817 result->sym_out = symp;
4822 * Search for symbol using SysV hash function.
4823 * obj->buckets is known not to be NULL at this point; the test for this was
4824 * performed with the obj->valid_hash_sysv assignment.
4827 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj)
4829 unsigned long symnum;
4830 Sym_Match_Result matchres;
4832 matchres.sym_out = NULL;
4833 matchres.vsymp = NULL;
4834 matchres.vcount = 0;
4836 for (symnum = obj->buckets[req->hash % obj->nbuckets];
4837 symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
4838 if (symnum >= obj->nchains)
4839 return (ESRCH); /* Bad object */
4841 if (matched_symbol(req, obj, &matchres, symnum)) {
4842 req->sym_out = matchres.sym_out;
4843 req->defobj_out = obj;
4847 if (matchres.vcount == 1) {
4848 req->sym_out = matchres.vsymp;
4849 req->defobj_out = obj;
4855 /* Search for symbol using GNU hash function */
4857 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj)
4859 Elf_Addr bloom_word;
4860 const Elf32_Word *hashval;
4862 Sym_Match_Result matchres;
4863 unsigned int h1, h2;
4864 unsigned long symnum;
4866 matchres.sym_out = NULL;
4867 matchres.vsymp = NULL;
4868 matchres.vcount = 0;
4870 /* Pick right bitmask word from Bloom filter array */
4871 bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) &
4872 obj->maskwords_bm_gnu];
4874 /* Calculate modulus word size of gnu hash and its derivative */
4875 h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1);
4876 h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1));
4878 /* Filter out the "definitely not in set" queries */
4879 if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0)
4882 /* Locate hash chain and corresponding value element*/
4883 bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu];
4886 hashval = &obj->chain_zero_gnu[bucket];
4888 if (((*hashval ^ req->hash_gnu) >> 1) == 0) {
4889 symnum = hashval - obj->chain_zero_gnu;
4890 if (matched_symbol(req, obj, &matchres, symnum)) {
4891 req->sym_out = matchres.sym_out;
4892 req->defobj_out = obj;
4896 } while ((*hashval++ & 1) == 0);
4897 if (matchres.vcount == 1) {
4898 req->sym_out = matchres.vsymp;
4899 req->defobj_out = obj;
4906 trace_loaded_objects(Obj_Entry *obj)
4908 const char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
4911 if ((main_local = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_PROGNAME)) ==
4915 if ((fmt1 = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_FMT1)) == NULL)
4916 fmt1 = "\t%o => %p (%x)\n";
4918 if ((fmt2 = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_FMT2)) == NULL)
4919 fmt2 = "\t%o (%x)\n";
4921 list_containers = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_ALL);
4923 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
4924 Needed_Entry *needed;
4925 const char *name, *path;
4930 if (list_containers && obj->needed != NULL)
4931 rtld_printf("%s:\n", obj->path);
4932 for (needed = obj->needed; needed; needed = needed->next) {
4933 if (needed->obj != NULL) {
4934 if (needed->obj->traced && !list_containers)
4936 needed->obj->traced = true;
4937 path = needed->obj->path;
4941 name = obj->strtab + needed->name;
4942 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
4944 fmt = is_lib ? fmt1 : fmt2;
4945 while ((c = *fmt++) != '\0') {
4971 rtld_putstr(main_local);
4974 rtld_putstr(obj_main->path);
4981 rtld_printf("%d", sodp->sod_major);
4984 rtld_printf("%d", sodp->sod_minor);
4991 rtld_printf("%p", needed->obj ? needed->obj->mapbase :
5004 * Unload a dlopened object and its dependencies from memory and from
5005 * our data structures. It is assumed that the DAG rooted in the
5006 * object has already been unreferenced, and that the object has a
5007 * reference count of 0.
5010 unload_object(Obj_Entry *root, RtldLockState *lockstate)
5012 Obj_Entry marker, *obj, *next;
5014 assert(root->refcount == 0);
5017 * Pass over the DAG removing unreferenced objects from
5018 * appropriate lists.
5020 unlink_object(root);
5022 /* Unmap all objects that are no longer referenced. */
5023 for (obj = TAILQ_FIRST(&obj_list); obj != NULL; obj = next) {
5024 next = TAILQ_NEXT(obj, next);
5025 if (obj->marker || obj->refcount != 0)
5027 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase,
5028 obj->mapsize, 0, obj->path);
5029 dbg("unloading \"%s\"", obj->path);
5031 * Unlink the object now to prevent new references from
5032 * being acquired while the bind lock is dropped in
5033 * recursive dlclose() invocations.
5035 TAILQ_REMOVE(&obj_list, obj, next);
5038 if (obj->filtees_loaded) {
5040 init_marker(&marker);
5041 TAILQ_INSERT_BEFORE(next, &marker, next);
5042 unload_filtees(obj, lockstate);
5043 next = TAILQ_NEXT(&marker, next);
5044 TAILQ_REMOVE(&obj_list, &marker, next);
5046 unload_filtees(obj, lockstate);
5048 release_object(obj);
5053 unlink_object(Obj_Entry *root)
5057 if (root->refcount == 0) {
5058 /* Remove the object from the RTLD_GLOBAL list. */
5059 objlist_remove(&list_global, root);
5061 /* Remove the object from all objects' DAG lists. */
5062 STAILQ_FOREACH(elm, &root->dagmembers, link) {
5063 objlist_remove(&elm->obj->dldags, root);
5064 if (elm->obj != root)
5065 unlink_object(elm->obj);
5071 ref_dag(Obj_Entry *root)
5075 assert(root->dag_inited);
5076 STAILQ_FOREACH(elm, &root->dagmembers, link)
5077 elm->obj->refcount++;
5081 unref_dag(Obj_Entry *root)
5085 assert(root->dag_inited);
5086 STAILQ_FOREACH(elm, &root->dagmembers, link)
5087 elm->obj->refcount--;
5091 * Common code for MD __tls_get_addr().
5094 tls_get_addr_slow(Elf_Addr **dtvp, int index, size_t offset, bool locked)
5096 Elf_Addr *newdtv, *dtv;
5097 RtldLockState lockstate;
5101 /* Check dtv generation in case new modules have arrived */
5102 if (dtv[0] != tls_dtv_generation) {
5104 wlock_acquire(rtld_bind_lock, &lockstate);
5105 newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
5107 if (to_copy > tls_max_index)
5108 to_copy = tls_max_index;
5109 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
5110 newdtv[0] = tls_dtv_generation;
5111 newdtv[1] = tls_max_index;
5114 lock_release(rtld_bind_lock, &lockstate);
5115 dtv = *dtvp = newdtv;
5118 /* Dynamically allocate module TLS if necessary */
5119 if (dtv[index + 1] == 0) {
5120 /* Signal safe, wlock will block out signals. */
5122 wlock_acquire(rtld_bind_lock, &lockstate);
5123 if (!dtv[index + 1])
5124 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
5126 lock_release(rtld_bind_lock, &lockstate);
5128 return ((void *)(dtv[index + 1] + offset));
5132 tls_get_addr_common(uintptr_t **dtvp, int index, size_t offset)
5137 /* Check dtv generation in case new modules have arrived */
5138 if (__predict_true(dtv[0] == tls_dtv_generation &&
5139 dtv[index + 1] != 0))
5140 return ((void *)(dtv[index + 1] + offset));
5141 return (tls_get_addr_slow(dtvp, index, offset, false));
5144 #ifdef TLS_VARIANT_I
5147 * Return pointer to allocated TLS block
5150 get_tls_block_ptr(void *tcb, size_t tcbsize)
5152 size_t extra_size, post_size, pre_size, tls_block_size;
5153 size_t tls_init_align;
5155 tls_init_align = MAX(obj_main->tlsalign, 1);
5157 /* Compute fragments sizes. */
5158 extra_size = tcbsize - TLS_TCB_SIZE;
5159 post_size = calculate_tls_post_size(tls_init_align);
5160 tls_block_size = tcbsize + post_size;
5161 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size;
5163 return ((char *)tcb - pre_size - extra_size);
5167 * Allocate Static TLS using the Variant I method.
5169 * For details on the layout, see lib/libc/gen/tls.c.
5171 * NB: rtld's tls_static_space variable includes TLS_TCB_SIZE and post_size as
5172 * it is based on tls_last_offset, and TLS offsets here are really TCB
5173 * offsets, whereas libc's tls_static_space is just the executable's static
5177 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
5181 Elf_Addr *dtv, **tcb;
5184 size_t extra_size, maxalign, post_size, pre_size, tls_block_size;
5185 size_t tls_init_align, tls_init_offset;
5187 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
5190 assert(tcbsize >= TLS_TCB_SIZE);
5191 maxalign = MAX(tcbalign, tls_static_max_align);
5192 tls_init_align = MAX(obj_main->tlsalign, 1);
5194 /* Compute fragmets sizes. */
5195 extra_size = tcbsize - TLS_TCB_SIZE;
5196 post_size = calculate_tls_post_size(tls_init_align);
5197 tls_block_size = tcbsize + post_size;
5198 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size;
5199 tls_block_size += pre_size + tls_static_space - TLS_TCB_SIZE - post_size;
5201 /* Allocate whole TLS block */
5202 tls_block = malloc_aligned(tls_block_size, maxalign, 0);
5203 tcb = (Elf_Addr **)(tls_block + pre_size + extra_size);
5205 if (oldtcb != NULL) {
5206 memcpy(tls_block, get_tls_block_ptr(oldtcb, tcbsize),
5208 free_aligned(get_tls_block_ptr(oldtcb, tcbsize));
5210 /* Adjust the DTV. */
5212 for (i = 0; i < dtv[1]; i++) {
5213 if (dtv[i+2] >= (Elf_Addr)oldtcb &&
5214 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
5215 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tcb;
5219 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
5221 dtv[0] = tls_dtv_generation;
5222 dtv[1] = tls_max_index;
5224 for (obj = globallist_curr(objs); obj != NULL;
5225 obj = globallist_next(obj)) {
5226 if (obj->tlsoffset == 0)
5228 tls_init_offset = obj->tlspoffset & (obj->tlsalign - 1);
5229 addr = (Elf_Addr)tcb + obj->tlsoffset;
5230 if (tls_init_offset > 0)
5231 memset((void *)addr, 0, tls_init_offset);
5232 if (obj->tlsinitsize > 0) {
5233 memcpy((void *)(addr + tls_init_offset), obj->tlsinit,
5236 if (obj->tlssize > obj->tlsinitsize) {
5237 memset((void *)(addr + tls_init_offset + obj->tlsinitsize),
5238 0, obj->tlssize - obj->tlsinitsize - tls_init_offset);
5240 dtv[obj->tlsindex + 1] = addr;
5248 free_tls(void *tcb, size_t tcbsize, size_t tcbalign __unused)
5251 Elf_Addr tlsstart, tlsend;
5253 size_t dtvsize, i, tls_init_align;
5255 assert(tcbsize >= TLS_TCB_SIZE);
5256 tls_init_align = MAX(obj_main->tlsalign, 1);
5258 /* Compute fragments sizes. */
5259 post_size = calculate_tls_post_size(tls_init_align);
5261 tlsstart = (Elf_Addr)tcb + TLS_TCB_SIZE + post_size;
5262 tlsend = (Elf_Addr)tcb + tls_static_space;
5264 dtv = *(Elf_Addr **)tcb;
5266 for (i = 0; i < dtvsize; i++) {
5267 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
5268 free((void*)dtv[i+2]);
5272 free_aligned(get_tls_block_ptr(tcb, tcbsize));
5275 #endif /* TLS_VARIANT_I */
5277 #ifdef TLS_VARIANT_II
5280 * Allocate Static TLS using the Variant II method.
5283 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
5286 size_t size, ralign;
5288 Elf_Addr *dtv, *olddtv;
5289 Elf_Addr segbase, oldsegbase, addr;
5293 if (tls_static_max_align > ralign)
5294 ralign = tls_static_max_align;
5295 size = roundup(tls_static_space, ralign) + roundup(tcbsize, ralign);
5297 assert(tcbsize >= 2*sizeof(Elf_Addr));
5298 tls = malloc_aligned(size, ralign, 0 /* XXX */);
5299 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
5301 segbase = (Elf_Addr)(tls + roundup(tls_static_space, ralign));
5302 ((Elf_Addr *)segbase)[0] = segbase;
5303 ((Elf_Addr *)segbase)[1] = (Elf_Addr) dtv;
5305 dtv[0] = tls_dtv_generation;
5306 dtv[1] = tls_max_index;
5310 * Copy the static TLS block over whole.
5312 oldsegbase = (Elf_Addr) oldtls;
5313 memcpy((void *)(segbase - tls_static_space),
5314 (const void *)(oldsegbase - tls_static_space),
5318 * If any dynamic TLS blocks have been created tls_get_addr(),
5321 olddtv = ((Elf_Addr **)oldsegbase)[1];
5322 for (i = 0; i < olddtv[1]; i++) {
5323 if (olddtv[i + 2] < oldsegbase - size ||
5324 olddtv[i + 2] > oldsegbase) {
5325 dtv[i + 2] = olddtv[i + 2];
5331 * We assume that this block was the one we created with
5332 * allocate_initial_tls().
5334 free_tls(oldtls, 2 * sizeof(Elf_Addr), sizeof(Elf_Addr));
5336 for (obj = objs; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
5337 if (obj->marker || obj->tlsoffset == 0)
5339 addr = segbase - obj->tlsoffset;
5340 memset((void *)(addr + obj->tlsinitsize),
5341 0, obj->tlssize - obj->tlsinitsize);
5343 memcpy((void *)addr, obj->tlsinit, obj->tlsinitsize);
5344 obj->static_tls_copied = true;
5346 dtv[obj->tlsindex + 1] = addr;
5350 return ((void *)segbase);
5354 free_tls(void *tls, size_t tcbsize __unused, size_t tcbalign)
5357 size_t size, ralign;
5359 Elf_Addr tlsstart, tlsend;
5362 * Figure out the size of the initial TLS block so that we can
5363 * find stuff which ___tls_get_addr() allocated dynamically.
5366 if (tls_static_max_align > ralign)
5367 ralign = tls_static_max_align;
5368 size = roundup(tls_static_space, ralign);
5370 dtv = ((Elf_Addr **)tls)[1];
5372 tlsend = (Elf_Addr)tls;
5373 tlsstart = tlsend - size;
5374 for (i = 0; i < dtvsize; i++) {
5375 if (dtv[i + 2] != 0 && (dtv[i + 2] < tlsstart ||
5376 dtv[i + 2] > tlsend)) {
5377 free_aligned((void *)dtv[i + 2]);
5381 free_aligned((void *)tlsstart);
5385 #endif /* TLS_VARIANT_II */
5388 * Allocate TLS block for module with given index.
5391 allocate_module_tls(int index)
5396 TAILQ_FOREACH(obj, &obj_list, next) {
5399 if (obj->tlsindex == index)
5403 _rtld_error("Can't find module with TLS index %d", index);
5407 p = malloc_aligned(obj->tlssize, obj->tlsalign, obj->tlspoffset);
5408 memcpy(p, obj->tlsinit, obj->tlsinitsize);
5409 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
5414 allocate_tls_offset(Obj_Entry *obj)
5421 if (obj->tlssize == 0) {
5422 obj->tls_done = true;
5426 if (tls_last_offset == 0)
5427 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign,
5430 off = calculate_tls_offset(tls_last_offset, tls_last_size,
5431 obj->tlssize, obj->tlsalign, obj->tlspoffset);
5433 obj->tlsoffset = off;
5434 #ifdef TLS_VARIANT_I
5435 off += obj->tlssize;
5439 * If we have already fixed the size of the static TLS block, we
5440 * must stay within that size. When allocating the static TLS, we
5441 * leave a small amount of space spare to be used for dynamically
5442 * loading modules which use static TLS.
5444 if (tls_static_space != 0) {
5445 if (off > tls_static_space)
5447 } else if (obj->tlsalign > tls_static_max_align) {
5448 tls_static_max_align = obj->tlsalign;
5451 tls_last_offset = off;
5452 tls_last_size = obj->tlssize;
5453 obj->tls_done = true;
5459 free_tls_offset(Obj_Entry *obj)
5463 * If we were the last thing to allocate out of the static TLS
5464 * block, we give our space back to the 'allocator'. This is a
5465 * simplistic workaround to allow libGL.so.1 to be loaded and
5466 * unloaded multiple times.
5468 size_t off = obj->tlsoffset;
5469 #ifdef TLS_VARIANT_I
5470 off += obj->tlssize;
5472 if (off == tls_last_offset) {
5473 tls_last_offset -= obj->tlssize;
5479 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
5482 RtldLockState lockstate;
5484 wlock_acquire(rtld_bind_lock, &lockstate);
5485 ret = allocate_tls(globallist_curr(TAILQ_FIRST(&obj_list)), oldtls,
5487 lock_release(rtld_bind_lock, &lockstate);
5492 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
5494 RtldLockState lockstate;
5496 wlock_acquire(rtld_bind_lock, &lockstate);
5497 free_tls(tcb, tcbsize, tcbalign);
5498 lock_release(rtld_bind_lock, &lockstate);
5502 object_add_name(Obj_Entry *obj, const char *name)
5508 entry = malloc(sizeof(Name_Entry) + len);
5510 if (entry != NULL) {
5511 strcpy(entry->name, name);
5512 STAILQ_INSERT_TAIL(&obj->names, entry, link);
5517 object_match_name(const Obj_Entry *obj, const char *name)
5521 STAILQ_FOREACH(entry, &obj->names, link) {
5522 if (strcmp(name, entry->name) == 0)
5529 locate_dependency(const Obj_Entry *obj, const char *name)
5531 const Objlist_Entry *entry;
5532 const Needed_Entry *needed;
5534 STAILQ_FOREACH(entry, &list_main, link) {
5535 if (object_match_name(entry->obj, name))
5536 return (entry->obj);
5539 for (needed = obj->needed; needed != NULL; needed = needed->next) {
5540 if (strcmp(obj->strtab + needed->name, name) == 0 ||
5541 (needed->obj != NULL && object_match_name(needed->obj, name))) {
5543 * If there is DT_NEEDED for the name we are looking for,
5544 * we are all set. Note that object might not be found if
5545 * dependency was not loaded yet, so the function can
5546 * return NULL here. This is expected and handled
5547 * properly by the caller.
5549 return (needed->obj);
5552 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
5558 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
5559 const Elf_Vernaux *vna)
5561 const Elf_Verdef *vd;
5562 const char *vername;
5564 vername = refobj->strtab + vna->vna_name;
5565 vd = depobj->verdef;
5567 _rtld_error("%s: version %s required by %s not defined",
5568 depobj->path, vername, refobj->path);
5572 if (vd->vd_version != VER_DEF_CURRENT) {
5573 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
5574 depobj->path, vd->vd_version);
5577 if (vna->vna_hash == vd->vd_hash) {
5578 const Elf_Verdaux *aux = (const Elf_Verdaux *)
5579 ((const char *)vd + vd->vd_aux);
5580 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
5583 if (vd->vd_next == 0)
5585 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5587 if (vna->vna_flags & VER_FLG_WEAK)
5589 _rtld_error("%s: version %s required by %s not found",
5590 depobj->path, vername, refobj->path);
5595 rtld_verify_object_versions(Obj_Entry *obj)
5597 const Elf_Verneed *vn;
5598 const Elf_Verdef *vd;
5599 const Elf_Verdaux *vda;
5600 const Elf_Vernaux *vna;
5601 const Obj_Entry *depobj;
5602 int maxvernum, vernum;
5604 if (obj->ver_checked)
5606 obj->ver_checked = true;
5610 * Walk over defined and required version records and figure out
5611 * max index used by any of them. Do very basic sanity checking
5615 while (vn != NULL) {
5616 if (vn->vn_version != VER_NEED_CURRENT) {
5617 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
5618 obj->path, vn->vn_version);
5621 vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux);
5623 vernum = VER_NEED_IDX(vna->vna_other);
5624 if (vernum > maxvernum)
5626 if (vna->vna_next == 0)
5628 vna = (const Elf_Vernaux *)((const char *)vna + vna->vna_next);
5630 if (vn->vn_next == 0)
5632 vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next);
5636 while (vd != NULL) {
5637 if (vd->vd_version != VER_DEF_CURRENT) {
5638 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
5639 obj->path, vd->vd_version);
5642 vernum = VER_DEF_IDX(vd->vd_ndx);
5643 if (vernum > maxvernum)
5645 if (vd->vd_next == 0)
5647 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5654 * Store version information in array indexable by version index.
5655 * Verify that object version requirements are satisfied along the
5658 obj->vernum = maxvernum + 1;
5659 obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry));
5662 while (vd != NULL) {
5663 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
5664 vernum = VER_DEF_IDX(vd->vd_ndx);
5665 assert(vernum <= maxvernum);
5666 vda = (const Elf_Verdaux *)((const char *)vd + vd->vd_aux);
5667 obj->vertab[vernum].hash = vd->vd_hash;
5668 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
5669 obj->vertab[vernum].file = NULL;
5670 obj->vertab[vernum].flags = 0;
5672 if (vd->vd_next == 0)
5674 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5678 while (vn != NULL) {
5679 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
5682 vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux);
5684 if (check_object_provided_version(obj, depobj, vna))
5686 vernum = VER_NEED_IDX(vna->vna_other);
5687 assert(vernum <= maxvernum);
5688 obj->vertab[vernum].hash = vna->vna_hash;
5689 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
5690 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
5691 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
5692 VER_INFO_HIDDEN : 0;
5693 if (vna->vna_next == 0)
5695 vna = (const Elf_Vernaux *)((const char *)vna + vna->vna_next);
5697 if (vn->vn_next == 0)
5699 vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next);
5705 rtld_verify_versions(const Objlist *objlist)
5707 Objlist_Entry *entry;
5711 STAILQ_FOREACH(entry, objlist, link) {
5713 * Skip dummy objects or objects that have their version requirements
5716 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
5718 if (rtld_verify_object_versions(entry->obj) == -1) {
5720 if (ld_tracing == NULL)
5724 if (rc == 0 || ld_tracing != NULL)
5725 rc = rtld_verify_object_versions(&obj_rtld);
5730 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
5735 vernum = VER_NDX(obj->versyms[symnum]);
5736 if (vernum >= obj->vernum) {
5737 _rtld_error("%s: symbol %s has wrong verneed value %d",
5738 obj->path, obj->strtab + symnum, vernum);
5739 } else if (obj->vertab[vernum].hash != 0) {
5740 return (&obj->vertab[vernum]);
5747 _rtld_get_stack_prot(void)
5750 return (stack_prot);
5754 _rtld_is_dlopened(void *arg)
5757 RtldLockState lockstate;
5760 rlock_acquire(rtld_bind_lock, &lockstate);
5763 obj = obj_from_addr(arg);
5765 _rtld_error("No shared object contains address");
5766 lock_release(rtld_bind_lock, &lockstate);
5769 res = obj->dlopened ? 1 : 0;
5770 lock_release(rtld_bind_lock, &lockstate);
5775 obj_remap_relro(Obj_Entry *obj, int prot)
5778 if (obj->relro_size > 0 && mprotect(obj->relro_page, obj->relro_size,
5780 _rtld_error("%s: Cannot set relro protection to %#x: %s",
5781 obj->path, prot, rtld_strerror(errno));
5788 obj_disable_relro(Obj_Entry *obj)
5791 return (obj_remap_relro(obj, PROT_READ | PROT_WRITE));
5795 obj_enforce_relro(Obj_Entry *obj)
5798 return (obj_remap_relro(obj, PROT_READ));
5802 map_stacks_exec(RtldLockState *lockstate)
5804 void (*thr_map_stacks_exec)(void);
5806 if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
5808 thr_map_stacks_exec = (void (*)(void))(uintptr_t)
5809 get_program_var_addr("__pthread_map_stacks_exec", lockstate);
5810 if (thr_map_stacks_exec != NULL) {
5811 stack_prot |= PROT_EXEC;
5812 thr_map_stacks_exec();
5817 distribute_static_tls(Objlist *list, RtldLockState *lockstate)
5821 void (*distrib)(size_t, void *, size_t, size_t);
5823 distrib = (void (*)(size_t, void *, size_t, size_t))(uintptr_t)
5824 get_program_var_addr("__pthread_distribute_static_tls", lockstate);
5825 if (distrib == NULL)
5827 STAILQ_FOREACH(elm, list, link) {
5829 if (obj->marker || !obj->tls_done || obj->static_tls_copied)
5831 distrib(obj->tlsoffset, obj->tlsinit, obj->tlsinitsize,
5833 obj->static_tls_copied = true;
5838 symlook_init(SymLook *dst, const char *name)
5841 bzero(dst, sizeof(*dst));
5843 dst->hash = elf_hash(name);
5844 dst->hash_gnu = gnu_hash(name);
5848 symlook_init_from_req(SymLook *dst, const SymLook *src)
5851 dst->name = src->name;
5852 dst->hash = src->hash;
5853 dst->hash_gnu = src->hash_gnu;
5854 dst->ventry = src->ventry;
5855 dst->flags = src->flags;
5856 dst->defobj_out = NULL;
5857 dst->sym_out = NULL;
5858 dst->lockstate = src->lockstate;
5862 open_binary_fd(const char *argv0, bool search_in_path,
5863 const char **binpath_res)
5865 char *binpath, *pathenv, *pe, *res1;
5871 if (search_in_path && strchr(argv0, '/') == NULL) {
5872 binpath = xmalloc(PATH_MAX);
5873 pathenv = getenv("PATH");
5874 if (pathenv == NULL) {
5875 _rtld_error("-p and no PATH environment variable");
5878 pathenv = strdup(pathenv);
5879 if (pathenv == NULL) {
5880 _rtld_error("Cannot allocate memory");
5885 while ((pe = strsep(&pathenv, ":")) != NULL) {
5886 if (strlcpy(binpath, pe, PATH_MAX) >= PATH_MAX)
5888 if (binpath[0] != '\0' &&
5889 strlcat(binpath, "/", PATH_MAX) >= PATH_MAX)
5891 if (strlcat(binpath, argv0, PATH_MAX) >= PATH_MAX)
5893 fd = open(binpath, O_RDONLY | O_CLOEXEC | O_VERIFY);
5894 if (fd != -1 || errno != ENOENT) {
5901 fd = open(argv0, O_RDONLY | O_CLOEXEC | O_VERIFY);
5906 _rtld_error("Cannot open %s: %s", argv0, rtld_strerror(errno));
5909 if (res != NULL && res[0] != '/') {
5910 res1 = xmalloc(PATH_MAX);
5911 if (realpath(res, res1) != NULL) {
5913 free(__DECONST(char *, res));
5924 * Parse a set of command-line arguments.
5927 parse_args(char* argv[], int argc, bool *use_pathp, int *fdp,
5928 const char **argv0, bool *dir_ignore)
5933 int arglen, fd, i, j, mib[2];
5935 bool seen_b, seen_f;
5937 dbg("Parsing command-line arguments");
5940 *dir_ignore = false;
5941 seen_b = seen_f = false;
5943 for (i = 1; i < argc; i++ ) {
5945 dbg("argv[%d]: '%s'", i, arg);
5948 * rtld arguments end with an explicit "--" or with the first
5949 * non-prefixed argument.
5951 if (strcmp(arg, "--") == 0) {
5959 * All other arguments are single-character options that can
5960 * be combined, so we need to search through `arg` for them.
5962 arglen = strlen(arg);
5963 for (j = 1; j < arglen; j++) {
5966 print_usage(argv[0]);
5968 } else if (opt == 'b') {
5970 _rtld_error("Both -b and -f specified");
5977 } else if (opt == 'd') {
5980 } else if (opt == 'f') {
5982 _rtld_error("Both -b and -f specified");
5987 * -f XX can be used to specify a
5988 * descriptor for the binary named at
5989 * the command line (i.e., the later
5990 * argument will specify the process
5991 * name but the descriptor is what
5992 * will actually be executed).
5994 * -f must be the last option in, e.g., -abcf.
5996 if (j != arglen - 1) {
5997 _rtld_error("Invalid options: %s", arg);
6001 fd = parse_integer(argv[i]);
6004 "Invalid file descriptor: '%s'",
6011 } else if (opt == 'p') {
6013 } else if (opt == 'u') {
6015 } else if (opt == 'v') {
6018 mib[1] = HW_MACHINE;
6019 sz = sizeof(machine);
6020 sysctl(mib, nitems(mib), machine, &sz, NULL, 0);
6021 ld_elf_hints_path = ld_get_env_var(
6023 set_ld_elf_hints_path();
6025 "FreeBSD ld-elf.so.1 %s\n"
6026 "FreeBSD_version %d\n"
6027 "Default lib path %s\n"
6028 "Hints lib path %s\n"
6030 "Default hint file %s\n"
6034 __FreeBSD_version, ld_standard_library_path,
6036 ld_env_prefix, ld_elf_hints_default,
6038 ld_path_libmap_conf);
6041 _rtld_error("Invalid argument: '%s'", arg);
6042 print_usage(argv[0]);
6054 * Parse a file descriptor number without pulling in more of libc (e.g. atoi).
6057 parse_integer(const char *str)
6059 static const int RADIX = 10; /* XXXJA: possibly support hex? */
6066 for (c = *str; c != '\0'; c = *++str) {
6067 if (c < '0' || c > '9')
6074 /* Make sure we actually parsed something. */
6081 print_usage(const char *argv0)
6085 "Usage: %s [-h] [-b <exe>] [-d] [-f <FD>] [-p] [--] <binary> [<args>]\n"
6088 " -h Display this help message\n"
6089 " -b <exe> Execute <exe> instead of <binary>, arg0 is <binary>\n"
6090 " -d Ignore lack of exec permissions for the binary\n"
6091 " -f <FD> Execute <FD> instead of searching for <binary>\n"
6092 " -p Search in PATH for named binary\n"
6093 " -u Ignore LD_ environment variables\n"
6094 " -v Display identification information\n"
6095 " -- End of RTLD options\n"
6096 " <binary> Name of process to execute\n"
6097 " <args> Arguments to the executed process\n", argv0);
6100 #define AUXFMT(at, xfmt) [at] = { .name = #at, .fmt = xfmt }
6101 static const struct auxfmt {
6105 AUXFMT(AT_NULL, NULL),
6106 AUXFMT(AT_IGNORE, NULL),
6107 AUXFMT(AT_EXECFD, "%ld"),
6108 AUXFMT(AT_PHDR, "%p"),
6109 AUXFMT(AT_PHENT, "%lu"),
6110 AUXFMT(AT_PHNUM, "%lu"),
6111 AUXFMT(AT_PAGESZ, "%lu"),
6112 AUXFMT(AT_BASE, "%#lx"),
6113 AUXFMT(AT_FLAGS, "%#lx"),
6114 AUXFMT(AT_ENTRY, "%p"),
6115 AUXFMT(AT_NOTELF, NULL),
6116 AUXFMT(AT_UID, "%ld"),
6117 AUXFMT(AT_EUID, "%ld"),
6118 AUXFMT(AT_GID, "%ld"),
6119 AUXFMT(AT_EGID, "%ld"),
6120 AUXFMT(AT_EXECPATH, "%s"),
6121 AUXFMT(AT_CANARY, "%p"),
6122 AUXFMT(AT_CANARYLEN, "%lu"),
6123 AUXFMT(AT_OSRELDATE, "%lu"),
6124 AUXFMT(AT_NCPUS, "%lu"),
6125 AUXFMT(AT_PAGESIZES, "%p"),
6126 AUXFMT(AT_PAGESIZESLEN, "%lu"),
6127 AUXFMT(AT_TIMEKEEP, "%p"),
6128 AUXFMT(AT_STACKPROT, "%#lx"),
6129 AUXFMT(AT_EHDRFLAGS, "%#lx"),
6130 AUXFMT(AT_HWCAP, "%#lx"),
6131 AUXFMT(AT_HWCAP2, "%#lx"),
6132 AUXFMT(AT_BSDFLAGS, "%#lx"),
6133 AUXFMT(AT_ARGC, "%lu"),
6134 AUXFMT(AT_ARGV, "%p"),
6135 AUXFMT(AT_ENVC, "%p"),
6136 AUXFMT(AT_ENVV, "%p"),
6137 AUXFMT(AT_PS_STRINGS, "%p"),
6138 AUXFMT(AT_FXRNG, "%p"),
6139 AUXFMT(AT_KPRELOAD, "%p"),
6143 is_ptr_fmt(const char *fmt)
6147 last = fmt[strlen(fmt) - 1];
6148 return (last == 'p' || last == 's');
6152 dump_auxv(Elf_Auxinfo **aux_info)
6155 const struct auxfmt *fmt;
6158 for (i = 0; i < AT_COUNT; i++) {
6163 if (fmt->fmt == NULL)
6165 rtld_fdprintf(STDOUT_FILENO, "%s:\t", fmt->name);
6166 if (is_ptr_fmt(fmt->fmt)) {
6167 rtld_fdprintfx(STDOUT_FILENO, fmt->fmt,
6170 rtld_fdprintfx(STDOUT_FILENO, fmt->fmt,
6173 rtld_fdprintf(STDOUT_FILENO, "\n");
6178 * Overrides for libc_pic-provided functions.
6182 __getosreldate(void)
6192 oid[1] = KERN_OSRELDATE;
6194 len = sizeof(osrel);
6195 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
6196 if (error == 0 && osrel > 0 && len == sizeof(osrel))
6201 rtld_strerror(int errnum)
6204 if (errnum < 0 || errnum >= sys_nerr)
6205 return ("Unknown error");
6206 return (sys_errlist[errnum]);
6210 getenv(const char *name)
6212 return (__DECONST(char *, rtld_get_env_val(environ, name,
6218 malloc(size_t nbytes)
6221 return (__crt_malloc(nbytes));
6225 calloc(size_t num, size_t size)
6228 return (__crt_calloc(num, size));
6239 realloc(void *cp, size_t nbytes)
6242 return (__crt_realloc(cp, nbytes));
6245 extern int _rtld_version__FreeBSD_version __exported;
6246 int _rtld_version__FreeBSD_version = __FreeBSD_version;
6248 extern char _rtld_version_laddr_offset __exported;
6249 char _rtld_version_laddr_offset;
6251 extern char _rtld_version_dlpi_tls_data __exported;
6252 char _rtld_version_dlpi_tls_data;