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 Obj_Entry *load_object(const char *, int fd, const Obj_Entry *, int);
129 static void map_stacks_exec(RtldLockState *);
130 static int obj_disable_relro(Obj_Entry *);
131 static int obj_enforce_relro(Obj_Entry *);
132 static void objlist_call_fini(Objlist *, Obj_Entry *, RtldLockState *);
133 static void objlist_call_init(Objlist *, RtldLockState *);
134 static void objlist_clear(Objlist *);
135 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
136 static void objlist_init(Objlist *);
137 static void objlist_push_head(Objlist *, Obj_Entry *);
138 static void objlist_push_tail(Objlist *, Obj_Entry *);
139 static void objlist_put_after(Objlist *, Obj_Entry *, Obj_Entry *);
140 static void objlist_remove(Objlist *, Obj_Entry *);
141 static int open_binary_fd(const char *argv0, bool search_in_path,
142 const char **binpath_res);
143 static int parse_args(char* argv[], int argc, bool *use_pathp, int *fdp,
144 const char **argv0, bool *dir_ignore);
145 static int parse_integer(const char *);
146 static void *path_enumerate(const char *, path_enum_proc, const char *, void *);
147 static void print_usage(const char *argv0);
148 static void release_object(Obj_Entry *);
149 static int relocate_object_dag(Obj_Entry *root, bool bind_now,
150 Obj_Entry *rtldobj, int flags, RtldLockState *lockstate);
151 static int relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
152 int flags, RtldLockState *lockstate);
153 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, int,
155 static int resolve_object_ifunc(Obj_Entry *, bool, int, RtldLockState *);
156 static int rtld_dirname(const char *, char *);
157 static int rtld_dirname_abs(const char *, char *);
158 static void *rtld_dlopen(const char *name, int fd, int mode);
159 static void rtld_exit(void);
160 static void rtld_nop_exit(void);
161 static char *search_library_path(const char *, const char *, const char *,
163 static char *search_library_pathfds(const char *, const char *, int *);
164 static const void **get_program_var_addr(const char *, RtldLockState *);
165 static void set_program_var(const char *, const void *);
166 static int symlook_default(SymLook *, const Obj_Entry *refobj);
167 static int symlook_global(SymLook *, DoneList *);
168 static void symlook_init_from_req(SymLook *, const SymLook *);
169 static int symlook_list(SymLook *, const Objlist *, DoneList *);
170 static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *);
171 static int symlook_obj1_sysv(SymLook *, const Obj_Entry *);
172 static int symlook_obj1_gnu(SymLook *, const Obj_Entry *);
173 static void *tls_get_addr_slow(Elf_Addr **, int, size_t, bool) __noinline;
174 static void trace_loaded_objects(Obj_Entry *);
175 static void unlink_object(Obj_Entry *);
176 static void unload_object(Obj_Entry *, RtldLockState *lockstate);
177 static void unref_dag(Obj_Entry *);
178 static void ref_dag(Obj_Entry *);
179 static char *origin_subst_one(Obj_Entry *, char *, const char *,
181 static char *origin_subst(Obj_Entry *, const char *);
182 static bool obj_resolve_origin(Obj_Entry *obj);
183 static void preinit_main(void);
184 static int rtld_verify_versions(const Objlist *);
185 static int rtld_verify_object_versions(Obj_Entry *);
186 static void object_add_name(Obj_Entry *, const char *);
187 static int object_match_name(const Obj_Entry *, const char *);
188 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
189 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
190 struct dl_phdr_info *phdr_info);
191 static uint32_t gnu_hash(const char *);
192 static bool matched_symbol(SymLook *, const Obj_Entry *, Sym_Match_Result *,
193 const unsigned long);
195 void r_debug_state(struct r_debug *, struct link_map *) __noinline __exported;
196 void _r_debug_postinit(struct link_map *) __noinline __exported;
198 int __sys_openat(int, const char *, int, ...);
203 struct r_debug r_debug __exported; /* for GDB; */
204 static bool libmap_disable; /* Disable libmap */
205 static bool ld_loadfltr; /* Immediate filters processing */
206 static const char *libmap_override;/* Maps to use in addition to libmap.conf */
207 static bool trust; /* False for setuid and setgid programs */
208 static bool dangerous_ld_env; /* True if environment variables have been
209 used to affect the libraries loaded */
210 bool ld_bind_not; /* Disable PLT update */
211 static const char *ld_bind_now; /* Environment variable for immediate binding */
212 static const char *ld_debug; /* Environment variable for debugging */
213 static bool ld_dynamic_weak = true; /* True if non-weak definition overrides
215 static const char *ld_library_path;/* Environment variable for search path */
216 static const char *ld_library_dirs;/* Environment variable for library descriptors */
217 static const char *ld_preload; /* Environment variable for libraries to
219 static const char *ld_preload_fds;/* Environment variable for libraries represented by
221 static const char *ld_elf_hints_path; /* Environment variable for alternative hints path */
222 static const char *ld_tracing; /* Called from ldd to print libs */
223 static const char *ld_utrace; /* Use utrace() to log events. */
224 static struct obj_entry_q obj_list; /* Queue of all loaded objects */
225 static Obj_Entry *obj_main; /* The main program shared object */
226 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
227 static unsigned int obj_count; /* Number of objects in obj_list */
228 static unsigned int obj_loads; /* Number of loads of objects (gen count) */
230 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
231 STAILQ_HEAD_INITIALIZER(list_global);
232 static Objlist list_main = /* Objects loaded at program startup */
233 STAILQ_HEAD_INITIALIZER(list_main);
234 static Objlist list_fini = /* Objects needing fini() calls */
235 STAILQ_HEAD_INITIALIZER(list_fini);
237 Elf_Sym sym_zero; /* For resolving undefined weak refs. */
239 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
241 extern Elf_Dyn _DYNAMIC;
242 #pragma weak _DYNAMIC
244 int dlclose(void *) __exported;
245 char *dlerror(void) __exported;
246 void *dlopen(const char *, int) __exported;
247 void *fdlopen(int, int) __exported;
248 void *dlsym(void *, const char *) __exported;
249 dlfunc_t dlfunc(void *, const char *) __exported;
250 void *dlvsym(void *, const char *, const char *) __exported;
251 int dladdr(const void *, Dl_info *) __exported;
252 void dllockinit(void *, void *(*)(void *), void (*)(void *), void (*)(void *),
253 void (*)(void *), void (*)(void *), void (*)(void *)) __exported;
254 int dlinfo(void *, int , void *) __exported;
255 int dl_iterate_phdr(__dl_iterate_hdr_callback, void *) __exported;
256 int _rtld_addr_phdr(const void *, struct dl_phdr_info *) __exported;
257 int _rtld_get_stack_prot(void) __exported;
258 int _rtld_is_dlopened(void *) __exported;
259 void _rtld_error(const char *, ...) __exported;
261 /* Only here to fix -Wmissing-prototypes warnings */
262 int __getosreldate(void);
263 func_ptr_type _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp);
264 Elf_Addr _rtld_bind(Obj_Entry *obj, Elf_Size reloff);
268 static int osreldate;
271 static int stack_prot = PROT_READ | PROT_WRITE | RTLD_DEFAULT_STACK_EXEC;
272 static int max_stack_flags;
275 * Global declarations normally provided by crt1. The dynamic linker is
276 * not built with crt1, so we have to provide them ourselves.
282 * Used to pass argc, argv to init functions.
288 * Globals to control TLS allocation.
290 size_t tls_last_offset; /* Static TLS offset of last module */
291 size_t tls_last_size; /* Static TLS size of last module */
292 size_t tls_static_space; /* Static TLS space allocated */
293 static size_t tls_static_max_align;
294 Elf_Addr tls_dtv_generation = 1; /* Used to detect when dtv size changes */
295 int tls_max_index = 1; /* Largest module index allocated */
297 static bool ld_library_path_rpath = false;
298 bool ld_fast_sigblock = false;
301 * Globals for path names, and such
303 const char *ld_elf_hints_default = _PATH_ELF_HINTS;
304 const char *ld_path_libmap_conf = _PATH_LIBMAP_CONF;
305 const char *ld_path_rtld = _PATH_RTLD;
306 const char *ld_standard_library_path = STANDARD_LIBRARY_PATH;
307 const char *ld_env_prefix = LD_;
309 static void (*rtld_exit_ptr)(void);
312 * Fill in a DoneList with an allocation large enough to hold all of
313 * the currently-loaded objects. Keep this as a macro since it calls
314 * alloca and we want that to occur within the scope of the caller.
316 #define donelist_init(dlp) \
317 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
318 assert((dlp)->objs != NULL), \
319 (dlp)->num_alloc = obj_count, \
322 #define LD_UTRACE(e, h, mb, ms, r, n) do { \
323 if (ld_utrace != NULL) \
324 ld_utrace_log(e, h, mb, ms, r, n); \
328 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
329 int refcnt, const char *name)
331 struct utrace_rtld ut;
332 static const char rtld_utrace_sig[RTLD_UTRACE_SIG_SZ] = RTLD_UTRACE_SIG;
334 memcpy(ut.sig, rtld_utrace_sig, sizeof(ut.sig));
337 ut.mapbase = mapbase;
338 ut.mapsize = mapsize;
340 bzero(ut.name, sizeof(ut.name));
342 strlcpy(ut.name, name, sizeof(ut.name));
343 utrace(&ut, sizeof(ut));
357 LD_LIBRARY_PATH_RPATH,
360 LD_TRACE_LOADED_OBJECTS,
364 LD_TRACE_LOADED_OBJECTS_PROGNAME,
365 LD_TRACE_LOADED_OBJECTS_FMT1,
366 LD_TRACE_LOADED_OBJECTS_FMT2,
367 LD_TRACE_LOADED_OBJECTS_ALL,
371 struct ld_env_var_desc {
372 const char * const n;
376 #define LD_ENV_DESC(var, unsec) \
377 [LD_##var] = { .n = #var, .unsecure = unsec }
379 static struct ld_env_var_desc ld_env_vars[] = {
380 LD_ENV_DESC(BIND_NOW, false),
381 LD_ENV_DESC(PRELOAD, true),
382 LD_ENV_DESC(LIBMAP, true),
383 LD_ENV_DESC(LIBRARY_PATH, true),
384 LD_ENV_DESC(LIBRARY_PATH_FDS, true),
385 LD_ENV_DESC(LIBMAP_DISABLE, true),
386 LD_ENV_DESC(BIND_NOT, true),
387 LD_ENV_DESC(DEBUG, true),
388 LD_ENV_DESC(ELF_HINTS_PATH, true),
389 LD_ENV_DESC(LOADFLTR, true),
390 LD_ENV_DESC(LIBRARY_PATH_RPATH, true),
391 LD_ENV_DESC(PRELOAD_FDS, true),
392 LD_ENV_DESC(DYNAMIC_WEAK, true),
393 LD_ENV_DESC(TRACE_LOADED_OBJECTS, false),
394 LD_ENV_DESC(UTRACE, false),
395 LD_ENV_DESC(DUMP_REL_PRE, false),
396 LD_ENV_DESC(DUMP_REL_POST, false),
397 LD_ENV_DESC(TRACE_LOADED_OBJECTS_PROGNAME, false),
398 LD_ENV_DESC(TRACE_LOADED_OBJECTS_FMT1, false),
399 LD_ENV_DESC(TRACE_LOADED_OBJECTS_FMT2, false),
400 LD_ENV_DESC(TRACE_LOADED_OBJECTS_ALL, false),
401 LD_ENV_DESC(SHOW_AUXV, false),
405 ld_get_env_var(int idx)
407 return (ld_env_vars[idx].val);
411 rtld_get_env_val(char **env, const char *name, size_t name_len)
415 for (m = env; *m != NULL; m++) {
419 /* corrupt environment? */
422 if (v - n == (ptrdiff_t)name_len &&
423 strncmp(name, n, name_len) == 0)
430 rtld_init_env_vars_for_prefix(char **env, const char *env_prefix)
432 struct ld_env_var_desc *lvd;
433 size_t prefix_len, nlen;
437 prefix_len = strlen(env_prefix);
438 for (m = env; *m != NULL; m++) {
440 if (strncmp(env_prefix, n, prefix_len) != 0) {
441 /* Not a rtld environment variable. */
447 /* corrupt environment? */
450 for (i = 0; i < (int)nitems(ld_env_vars); i++) {
451 lvd = &ld_env_vars[i];
452 if (lvd->val != NULL) {
453 /* Saw higher-priority variable name already. */
456 nlen = strlen(lvd->n);
457 if (v - n == (ptrdiff_t)nlen &&
458 strncmp(lvd->n, n, nlen) == 0) {
467 rtld_init_env_vars(char **env)
469 rtld_init_env_vars_for_prefix(env, ld_env_prefix);
473 set_ld_elf_hints_path(void)
475 if (ld_elf_hints_path == NULL || strlen(ld_elf_hints_path) == 0)
476 ld_elf_hints_path = ld_elf_hints_default;
480 * Main entry point for dynamic linking. The first argument is the
481 * stack pointer. The stack is expected to be laid out as described
482 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
483 * Specifically, the stack pointer points to a word containing
484 * ARGC. Following that in the stack is a null-terminated sequence
485 * of pointers to argument strings. Then comes a null-terminated
486 * sequence of pointers to environment strings. Finally, there is a
487 * sequence of "auxiliary vector" entries.
489 * The second argument points to a place to store the dynamic linker's
490 * exit procedure pointer and the third to a place to store the main
493 * The return value is the main program's entry point.
496 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
498 Elf_Auxinfo *aux, *auxp, *auxpf, *aux_info[AT_COUNT];
499 Objlist_Entry *entry;
500 Obj_Entry *last_interposer, *obj, *preload_tail;
501 const Elf_Phdr *phdr;
503 RtldLockState lockstate;
506 char **argv, **env, **envp, *kexecpath;
507 const char *argv0, *binpath, *library_path_rpath;
508 struct ld_env_var_desc *lvd;
510 char buf[MAXPATHLEN];
511 int argc, fd, i, mib[4], old_osrel, osrel, phnum, rtld_argc;
514 int old_auxv_format = 1;
516 bool dir_enable, dir_ignore, direct_exec, explicit_fd, search_in_path;
519 * On entry, the dynamic linker itself has not been relocated yet.
520 * Be very careful not to reference any global data until after
521 * init_rtld has returned. It is OK to reference file-scope statics
522 * and string constants, and to call static and global functions.
525 /* Find the auxiliary vector on the stack. */
529 sp += argc + 1; /* Skip over arguments and NULL terminator */
531 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
533 aux = (Elf_Auxinfo *) sp;
535 /* Digest the auxiliary vector. */
536 for (i = 0; i < AT_COUNT; i++)
538 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
539 if (auxp->a_type < AT_COUNT)
540 aux_info[auxp->a_type] = auxp;
542 if (auxp->a_type == 23) /* AT_STACKPROT */
548 if (old_auxv_format) {
549 /* Remap from old-style auxv numbers. */
550 aux_info[23] = aux_info[21]; /* AT_STACKPROT */
551 aux_info[21] = aux_info[19]; /* AT_PAGESIZESLEN */
552 aux_info[19] = aux_info[17]; /* AT_NCPUS */
553 aux_info[17] = aux_info[15]; /* AT_CANARYLEN */
554 aux_info[15] = aux_info[13]; /* AT_EXECPATH */
555 aux_info[13] = NULL; /* AT_GID */
557 aux_info[20] = aux_info[18]; /* AT_PAGESIZES */
558 aux_info[18] = aux_info[16]; /* AT_OSRELDATE */
559 aux_info[16] = aux_info[14]; /* AT_CANARY */
560 aux_info[14] = NULL; /* AT_EGID */
564 /* Initialize and relocate ourselves. */
565 assert(aux_info[AT_BASE] != NULL);
566 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
570 __progname = obj_rtld.path;
571 argv0 = argv[0] != NULL ? argv[0] : "(null)";
576 if (aux_info[AT_BSDFLAGS] != NULL &&
577 (aux_info[AT_BSDFLAGS]->a_un.a_val & ELF_BSDF_SIGFASTBLK) != 0)
578 ld_fast_sigblock = true;
580 trust = !issetugid();
583 md_abi_variant_hook(aux_info);
584 rtld_init_env_vars(env);
587 if (aux_info[AT_EXECFD] != NULL) {
588 fd = aux_info[AT_EXECFD]->a_un.a_val;
590 assert(aux_info[AT_PHDR] != NULL);
591 phdr = (const Elf_Phdr *)aux_info[AT_PHDR]->a_un.a_ptr;
592 if (phdr == obj_rtld.phdr) {
594 _rtld_error("Tainted process refusing to run binary %s",
600 dbg("opening main program in direct exec mode");
602 rtld_argc = parse_args(argv, argc, &search_in_path, &fd,
603 &argv0, &dir_ignore);
604 explicit_fd = (fd != -1);
607 fd = open_binary_fd(argv0, search_in_path, &binpath);
608 if (fstat(fd, &st) == -1) {
609 _rtld_error("Failed to fstat FD %d (%s): %s", fd,
610 explicit_fd ? "user-provided descriptor" : argv0,
611 rtld_strerror(errno));
616 * Rough emulation of the permission checks done by
617 * execve(2), only Unix DACs are checked, ACLs are
618 * ignored. Preserve the semantic of disabling owner
619 * to execute if owner x bit is cleared, even if
620 * others x bit is enabled.
621 * mmap(2) does not allow to mmap with PROT_EXEC if
622 * binary' file comes from noexec mount. We cannot
623 * set a text reference on the binary.
626 if (st.st_uid == geteuid()) {
627 if ((st.st_mode & S_IXUSR) != 0)
629 } else if (st.st_gid == getegid()) {
630 if ((st.st_mode & S_IXGRP) != 0)
632 } else if ((st.st_mode & S_IXOTH) != 0) {
635 if (!dir_enable && !dir_ignore) {
636 _rtld_error("No execute permission for binary %s",
642 * For direct exec mode, argv[0] is the interpreter
643 * name, we must remove it and shift arguments left
644 * before invoking binary main. Since stack layout
645 * places environment pointers and aux vectors right
646 * after the terminating NULL, we must shift
647 * environment and aux as well.
649 main_argc = argc - rtld_argc;
650 for (i = 0; i <= main_argc; i++)
651 argv[i] = argv[i + rtld_argc];
653 environ = env = envp = argv + main_argc + 1;
654 dbg("move env from %p to %p", envp + rtld_argc, envp);
656 *envp = *(envp + rtld_argc);
657 } while (*envp++ != NULL);
658 aux = auxp = (Elf_Auxinfo *)envp;
659 auxpf = (Elf_Auxinfo *)(envp + rtld_argc);
660 dbg("move aux from %p to %p", auxpf, aux);
661 /* XXXKIB insert place for AT_EXECPATH if not present */
662 for (;; auxp++, auxpf++) {
664 if (auxp->a_type == AT_NULL)
667 /* Since the auxiliary vector has moved, redigest it. */
668 for (i = 0; i < AT_COUNT; i++)
670 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
671 if (auxp->a_type < AT_COUNT)
672 aux_info[auxp->a_type] = auxp;
675 /* Point AT_EXECPATH auxv and aux_info to the binary path. */
676 if (binpath == NULL) {
677 aux_info[AT_EXECPATH] = NULL;
679 if (aux_info[AT_EXECPATH] == NULL) {
680 aux_info[AT_EXECPATH] = xmalloc(sizeof(Elf_Auxinfo));
681 aux_info[AT_EXECPATH]->a_type = AT_EXECPATH;
683 aux_info[AT_EXECPATH]->a_un.a_ptr = __DECONST(void *,
687 _rtld_error("No binary");
693 ld_bind_now = ld_get_env_var(LD_BIND_NOW);
696 * If the process is tainted, then we un-set the dangerous environment
697 * variables. The process will be marked as tainted until setuid(2)
698 * is called. If any child process calls setuid(2) we do not want any
699 * future processes to honor the potentially un-safe variables.
702 for (i = 0; i < (int)nitems(ld_env_vars); i++) {
703 lvd = &ld_env_vars[i];
709 ld_debug = ld_get_env_var(LD_DEBUG);
710 if (ld_bind_now == NULL)
711 ld_bind_not = ld_get_env_var(LD_BIND_NOT) != NULL;
712 ld_dynamic_weak = ld_get_env_var(LD_DYNAMIC_WEAK) == NULL;
713 libmap_disable = ld_get_env_var(LD_LIBMAP_DISABLE) != NULL;
714 libmap_override = ld_get_env_var(LD_LIBMAP);
715 ld_library_path = ld_get_env_var(LD_LIBRARY_PATH);
716 ld_library_dirs = ld_get_env_var(LD_LIBRARY_PATH_FDS);
717 ld_preload = ld_get_env_var(LD_PRELOAD);
718 ld_preload_fds = ld_get_env_var(LD_PRELOAD_FDS);
719 ld_elf_hints_path = ld_get_env_var(LD_ELF_HINTS_PATH);
720 ld_loadfltr = ld_get_env_var(LD_LOADFLTR) != NULL;
721 library_path_rpath = ld_get_env_var(LD_LIBRARY_PATH_RPATH);
722 if (library_path_rpath != NULL) {
723 if (library_path_rpath[0] == 'y' ||
724 library_path_rpath[0] == 'Y' ||
725 library_path_rpath[0] == '1')
726 ld_library_path_rpath = true;
728 ld_library_path_rpath = false;
730 dangerous_ld_env = libmap_disable || libmap_override != NULL ||
731 ld_library_path != NULL || ld_preload != NULL ||
732 ld_elf_hints_path != NULL || ld_loadfltr || !ld_dynamic_weak;
733 ld_tracing = ld_get_env_var(LD_TRACE_LOADED_OBJECTS);
734 ld_utrace = ld_get_env_var(LD_UTRACE);
736 set_ld_elf_hints_path();
737 if (ld_debug != NULL && *ld_debug != '\0')
739 dbg("%s is initialized, base address = %p", __progname,
740 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
741 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
742 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
744 dbg("initializing thread locks");
748 * Load the main program, or process its program header if it is
751 if (fd != -1) { /* Load the main program. */
752 dbg("loading main program");
753 obj_main = map_object(fd, argv0, NULL);
755 if (obj_main == NULL)
757 max_stack_flags = obj_main->stack_flags;
758 } else { /* Main program already loaded. */
759 dbg("processing main program's program header");
760 assert(aux_info[AT_PHDR] != NULL);
761 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
762 assert(aux_info[AT_PHNUM] != NULL);
763 phnum = aux_info[AT_PHNUM]->a_un.a_val;
764 assert(aux_info[AT_PHENT] != NULL);
765 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
766 assert(aux_info[AT_ENTRY] != NULL);
767 imgentry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
768 if ((obj_main = digest_phdr(phdr, phnum, imgentry, argv0)) == NULL)
772 if (aux_info[AT_EXECPATH] != NULL && fd == -1) {
773 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
774 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
775 if (kexecpath[0] == '/')
776 obj_main->path = kexecpath;
777 else if (getcwd(buf, sizeof(buf)) == NULL ||
778 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
779 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
780 obj_main->path = xstrdup(argv0);
782 obj_main->path = xstrdup(buf);
784 dbg("No AT_EXECPATH or direct exec");
785 obj_main->path = xstrdup(argv0);
787 dbg("obj_main path %s", obj_main->path);
788 obj_main->mainprog = true;
790 if (aux_info[AT_STACKPROT] != NULL &&
791 aux_info[AT_STACKPROT]->a_un.a_val != 0)
792 stack_prot = aux_info[AT_STACKPROT]->a_un.a_val;
796 * Get the actual dynamic linker pathname from the executable if
797 * possible. (It should always be possible.) That ensures that
798 * gdb will find the right dynamic linker even if a non-standard
801 if (obj_main->interp != NULL &&
802 strcmp(obj_main->interp, obj_rtld.path) != 0) {
804 obj_rtld.path = xstrdup(obj_main->interp);
805 __progname = obj_rtld.path;
809 if (!digest_dynamic(obj_main, 0))
811 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d",
812 obj_main->path, obj_main->valid_hash_sysv, obj_main->valid_hash_gnu,
813 obj_main->dynsymcount);
815 linkmap_add(obj_main);
816 linkmap_add(&obj_rtld);
818 /* Link the main program into the list of objects. */
819 TAILQ_INSERT_HEAD(&obj_list, obj_main, next);
823 /* Initialize a fake symbol for resolving undefined weak references. */
824 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
825 sym_zero.st_shndx = SHN_UNDEF;
826 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
829 libmap_disable = (bool)lm_init(libmap_override);
831 dbg("loading LD_PRELOAD_FDS libraries");
832 if (load_preload_objects(ld_preload_fds, true) == -1)
835 dbg("loading LD_PRELOAD libraries");
836 if (load_preload_objects(ld_preload, false) == -1)
838 preload_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
840 dbg("loading needed objects");
841 if (load_needed_objects(obj_main, ld_tracing != NULL ? RTLD_LO_TRACE :
845 /* Make a list of all objects loaded at startup. */
846 last_interposer = obj_main;
847 TAILQ_FOREACH(obj, &obj_list, next) {
850 if (obj->z_interpose && obj != obj_main) {
851 objlist_put_after(&list_main, last_interposer, obj);
852 last_interposer = obj;
854 objlist_push_tail(&list_main, obj);
859 dbg("checking for required versions");
860 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
863 if (ld_get_env_var(LD_SHOW_AUXV) != NULL)
866 if (ld_tracing) { /* We're done */
867 trace_loaded_objects(obj_main);
871 if (ld_get_env_var(LD_DUMP_REL_PRE) != NULL) {
872 dump_relocations(obj_main);
877 * Processing tls relocations requires having the tls offsets
878 * initialized. Prepare offsets before starting initial
879 * relocation processing.
881 dbg("initializing initial thread local storage offsets");
882 STAILQ_FOREACH(entry, &list_main, link) {
884 * Allocate all the initial objects out of the static TLS
885 * block even if they didn't ask for it.
887 allocate_tls_offset(entry->obj);
890 if (relocate_objects(obj_main,
891 ld_bind_now != NULL && *ld_bind_now != '\0',
892 &obj_rtld, SYMLOOK_EARLY, NULL) == -1)
895 dbg("doing copy relocations");
896 if (do_copy_relocations(obj_main) == -1)
899 if (ld_get_env_var(LD_DUMP_REL_POST) != NULL) {
900 dump_relocations(obj_main);
907 * Setup TLS for main thread. This must be done after the
908 * relocations are processed, since tls initialization section
909 * might be the subject for relocations.
911 dbg("initializing initial thread local storage");
912 allocate_initial_tls(globallist_curr(TAILQ_FIRST(&obj_list)));
914 dbg("initializing key program variables");
915 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
916 set_program_var("environ", env);
917 set_program_var("__elf_aux_vector", aux);
919 /* Make a list of init functions to call. */
920 objlist_init(&initlist);
921 initlist_add_objects(globallist_curr(TAILQ_FIRST(&obj_list)),
922 preload_tail, &initlist);
924 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
926 map_stacks_exec(NULL);
928 if (!obj_main->crt_no_init) {
930 * Make sure we don't call the main program's init and fini
931 * functions for binaries linked with old crt1 which calls
934 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
935 obj_main->preinit_array = obj_main->init_array =
936 obj_main->fini_array = (Elf_Addr)NULL;
940 /* Set osrel for direct-execed binary */
943 mib[2] = KERN_PROC_OSREL;
945 osrel = obj_main->osrel;
946 sz = sizeof(old_osrel);
947 dbg("setting osrel to %d", osrel);
948 (void)sysctl(mib, 4, &old_osrel, &sz, &osrel, sizeof(osrel));
951 wlock_acquire(rtld_bind_lock, &lockstate);
953 dbg("resolving ifuncs");
954 if (initlist_objects_ifunc(&initlist, ld_bind_now != NULL &&
955 *ld_bind_now != '\0', SYMLOOK_EARLY, &lockstate) == -1)
958 rtld_exit_ptr = rtld_exit;
959 if (obj_main->crt_no_init)
961 objlist_call_init(&initlist, &lockstate);
962 _r_debug_postinit(&obj_main->linkmap);
963 objlist_clear(&initlist);
964 dbg("loading filtees");
965 TAILQ_FOREACH(obj, &obj_list, next) {
968 if (ld_loadfltr || obj->z_loadfltr)
969 load_filtees(obj, 0, &lockstate);
972 dbg("enforcing main obj relro");
973 if (obj_enforce_relro(obj_main) == -1)
976 lock_release(rtld_bind_lock, &lockstate);
978 dbg("transferring control to program entry point = %p", obj_main->entry);
980 /* Return the exit procedure and the program entry point. */
981 *exit_proc = rtld_exit_ptr;
983 return ((func_ptr_type)obj_main->entry);
987 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def)
992 ptr = (void *)make_function_pointer(def, obj);
993 target = call_ifunc_resolver(ptr);
994 return ((void *)target);
998 * NB: MIPS uses a private version of this function (_mips_rtld_bind).
999 * Changes to this function should be applied there as well.
1002 _rtld_bind(Obj_Entry *obj, Elf_Size reloff)
1006 const Obj_Entry *defobj;
1009 RtldLockState lockstate;
1011 rlock_acquire(rtld_bind_lock, &lockstate);
1012 if (sigsetjmp(lockstate.env, 0) != 0)
1013 lock_upgrade(rtld_bind_lock, &lockstate);
1015 rel = (const Elf_Rel *)((const char *)obj->pltrel + reloff);
1017 rel = (const Elf_Rel *)((const char *)obj->pltrela + reloff);
1019 where = (Elf_Addr *)(obj->relocbase + rel->r_offset);
1020 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, SYMLOOK_IN_PLT,
1024 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
1025 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
1027 target = (Elf_Addr)(defobj->relocbase + def->st_value);
1029 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
1030 defobj->strtab + def->st_name,
1031 obj->path == NULL ? NULL : basename(obj->path),
1033 defobj->path == NULL ? NULL : basename(defobj->path));
1036 * Write the new contents for the jmpslot. Note that depending on
1037 * architecture, the value which we need to return back to the
1038 * lazy binding trampoline may or may not be the target
1039 * address. The value returned from reloc_jmpslot() is the value
1040 * that the trampoline needs.
1042 target = reloc_jmpslot(where, target, defobj, obj, rel);
1043 lock_release(rtld_bind_lock, &lockstate);
1048 * Error reporting function. Use it like printf. If formats the message
1049 * into a buffer, and sets things up so that the next call to dlerror()
1050 * will return the message.
1053 _rtld_error(const char *fmt, ...)
1058 rtld_vsnprintf(lockinfo.dlerror_loc(), lockinfo.dlerror_loc_sz,
1061 *lockinfo.dlerror_seen() = 0;
1062 LD_UTRACE(UTRACE_RTLD_ERROR, NULL, NULL, 0, 0, lockinfo.dlerror_loc());
1066 * Return a dynamically-allocated copy of the current error message, if any.
1068 static struct dlerror_save *
1071 struct dlerror_save *res;
1073 res = xmalloc(sizeof(*res));
1074 res->seen = *lockinfo.dlerror_seen();
1076 res->msg = xstrdup(lockinfo.dlerror_loc());
1081 * Restore the current error message from a copy which was previously saved
1082 * by errmsg_save(). The copy is freed.
1085 errmsg_restore(struct dlerror_save *saved_msg)
1087 if (saved_msg == NULL || saved_msg->seen == 1) {
1088 *lockinfo.dlerror_seen() = 1;
1090 *lockinfo.dlerror_seen() = 0;
1091 strlcpy(lockinfo.dlerror_loc(), saved_msg->msg,
1092 lockinfo.dlerror_loc_sz);
1093 free(saved_msg->msg);
1099 basename(const char *name)
1103 p = strrchr(name, '/');
1104 return (p != NULL ? p + 1 : name);
1107 static struct utsname uts;
1110 origin_subst_one(Obj_Entry *obj, char *real, const char *kw,
1111 const char *subst, bool may_free)
1113 char *p, *p1, *res, *resp;
1114 int subst_len, kw_len, subst_count, old_len, new_len;
1116 kw_len = strlen(kw);
1119 * First, count the number of the keyword occurrences, to
1120 * preallocate the final string.
1122 for (p = real, subst_count = 0;; p = p1 + kw_len, subst_count++) {
1129 * If the keyword is not found, just return.
1131 * Return non-substituted string if resolution failed. We
1132 * cannot do anything more reasonable, the failure mode of the
1133 * caller is unresolved library anyway.
1135 if (subst_count == 0 || (obj != NULL && !obj_resolve_origin(obj)))
1136 return (may_free ? real : xstrdup(real));
1138 subst = obj->origin_path;
1141 * There is indeed something to substitute. Calculate the
1142 * length of the resulting string, and allocate it.
1144 subst_len = strlen(subst);
1145 old_len = strlen(real);
1146 new_len = old_len + (subst_len - kw_len) * subst_count;
1147 res = xmalloc(new_len + 1);
1150 * Now, execute the substitution loop.
1152 for (p = real, resp = res, *resp = '\0';;) {
1155 /* Copy the prefix before keyword. */
1156 memcpy(resp, p, p1 - p);
1158 /* Keyword replacement. */
1159 memcpy(resp, subst, subst_len);
1167 /* Copy to the end of string and finish. */
1175 origin_subst(Obj_Entry *obj, const char *real)
1177 char *res1, *res2, *res3, *res4;
1179 if (obj == NULL || !trust)
1180 return (xstrdup(real));
1181 if (uts.sysname[0] == '\0') {
1182 if (uname(&uts) != 0) {
1183 _rtld_error("utsname failed: %d", errno);
1187 /* __DECONST is safe here since without may_free real is unchanged */
1188 res1 = origin_subst_one(obj, __DECONST(char *, real), "$ORIGIN", NULL,
1190 res2 = origin_subst_one(NULL, res1, "$OSNAME", uts.sysname, true);
1191 res3 = origin_subst_one(NULL, res2, "$OSREL", uts.release, true);
1192 res4 = origin_subst_one(NULL, res3, "$PLATFORM", uts.machine, true);
1199 const char *msg = dlerror();
1202 msg = "Fatal error";
1203 rtld_fdputstr(STDERR_FILENO, _BASENAME_RTLD ": ");
1204 rtld_fdputstr(STDERR_FILENO, msg);
1205 rtld_fdputchar(STDERR_FILENO, '\n');
1210 * Process a shared object's DYNAMIC section, and save the important
1211 * information in its Obj_Entry structure.
1214 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
1215 const Elf_Dyn **dyn_soname, const Elf_Dyn **dyn_runpath)
1217 const Elf_Dyn *dynp;
1218 Needed_Entry **needed_tail = &obj->needed;
1219 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
1220 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
1221 const Elf_Hashelt *hashtab;
1222 const Elf32_Word *hashval;
1223 Elf32_Word bkt, nmaskwords;
1225 int plttype = DT_REL;
1229 *dyn_runpath = NULL;
1231 obj->bind_now = false;
1232 dynp = obj->dynamic;
1235 for (; dynp->d_tag != DT_NULL; dynp++) {
1236 switch (dynp->d_tag) {
1239 obj->rel = (const Elf_Rel *)(obj->relocbase + dynp->d_un.d_ptr);
1243 obj->relsize = dynp->d_un.d_val;
1247 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
1251 obj->pltrel = (const Elf_Rel *)
1252 (obj->relocbase + dynp->d_un.d_ptr);
1256 obj->pltrelsize = dynp->d_un.d_val;
1260 obj->rela = (const Elf_Rela *)(obj->relocbase + dynp->d_un.d_ptr);
1264 obj->relasize = dynp->d_un.d_val;
1268 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
1272 obj->relr = (const Elf_Relr *)(obj->relocbase + dynp->d_un.d_ptr);
1276 obj->relrsize = dynp->d_un.d_val;
1280 assert(dynp->d_un.d_val == sizeof(Elf_Relr));
1284 plttype = dynp->d_un.d_val;
1285 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
1289 obj->symtab = (const Elf_Sym *)
1290 (obj->relocbase + dynp->d_un.d_ptr);
1294 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
1298 obj->strtab = (const char *)(obj->relocbase + dynp->d_un.d_ptr);
1302 obj->strsize = dynp->d_un.d_val;
1306 obj->verneed = (const Elf_Verneed *)(obj->relocbase +
1311 obj->verneednum = dynp->d_un.d_val;
1315 obj->verdef = (const Elf_Verdef *)(obj->relocbase +
1320 obj->verdefnum = dynp->d_un.d_val;
1324 obj->versyms = (const Elf_Versym *)(obj->relocbase +
1330 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1332 obj->nbuckets = hashtab[0];
1333 obj->nchains = hashtab[1];
1334 obj->buckets = hashtab + 2;
1335 obj->chains = obj->buckets + obj->nbuckets;
1336 obj->valid_hash_sysv = obj->nbuckets > 0 && obj->nchains > 0 &&
1337 obj->buckets != NULL;
1343 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1345 obj->nbuckets_gnu = hashtab[0];
1346 obj->symndx_gnu = hashtab[1];
1347 nmaskwords = hashtab[2];
1348 bloom_size32 = (__ELF_WORD_SIZE / 32) * nmaskwords;
1349 obj->maskwords_bm_gnu = nmaskwords - 1;
1350 obj->shift2_gnu = hashtab[3];
1351 obj->bloom_gnu = (const Elf_Addr *)(hashtab + 4);
1352 obj->buckets_gnu = hashtab + 4 + bloom_size32;
1353 obj->chain_zero_gnu = obj->buckets_gnu + obj->nbuckets_gnu -
1355 /* Number of bitmask words is required to be power of 2 */
1356 obj->valid_hash_gnu = powerof2(nmaskwords) &&
1357 obj->nbuckets_gnu > 0 && obj->buckets_gnu != NULL;
1363 Needed_Entry *nep = NEW(Needed_Entry);
1364 nep->name = dynp->d_un.d_val;
1369 needed_tail = &nep->next;
1375 Needed_Entry *nep = NEW(Needed_Entry);
1376 nep->name = dynp->d_un.d_val;
1380 *needed_filtees_tail = nep;
1381 needed_filtees_tail = &nep->next;
1383 if (obj->linkmap.l_refname == NULL)
1384 obj->linkmap.l_refname = (char *)dynp->d_un.d_val;
1390 Needed_Entry *nep = NEW(Needed_Entry);
1391 nep->name = dynp->d_un.d_val;
1395 *needed_aux_filtees_tail = nep;
1396 needed_aux_filtees_tail = &nep->next;
1401 obj->pltgot = (Elf_Addr *)(obj->relocbase + dynp->d_un.d_ptr);
1405 obj->textrel = true;
1409 obj->symbolic = true;
1414 * We have to wait until later to process this, because we
1415 * might not have gotten the address of the string table yet.
1425 *dyn_runpath = dynp;
1429 obj->init = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1432 case DT_PREINIT_ARRAY:
1433 obj->preinit_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1436 case DT_PREINIT_ARRAYSZ:
1437 obj->preinit_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1441 obj->init_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1444 case DT_INIT_ARRAYSZ:
1445 obj->init_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1449 obj->fini = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1453 obj->fini_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1456 case DT_FINI_ARRAYSZ:
1457 obj->fini_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1461 * Don't process DT_DEBUG on MIPS as the dynamic section
1462 * is mapped read-only. DT_MIPS_RLD_MAP is used instead.
1468 dbg("Filling in DT_DEBUG entry");
1469 (__DECONST(Elf_Dyn *, dynp))->d_un.d_ptr = (Elf_Addr)&r_debug;
1474 if (dynp->d_un.d_val & DF_ORIGIN)
1475 obj->z_origin = true;
1476 if (dynp->d_un.d_val & DF_SYMBOLIC)
1477 obj->symbolic = true;
1478 if (dynp->d_un.d_val & DF_TEXTREL)
1479 obj->textrel = true;
1480 if (dynp->d_un.d_val & DF_BIND_NOW)
1481 obj->bind_now = true;
1482 if (dynp->d_un.d_val & DF_STATIC_TLS)
1483 obj->static_tls = true;
1486 case DT_MIPS_LOCAL_GOTNO:
1487 obj->local_gotno = dynp->d_un.d_val;
1490 case DT_MIPS_SYMTABNO:
1491 obj->symtabno = dynp->d_un.d_val;
1494 case DT_MIPS_GOTSYM:
1495 obj->gotsym = dynp->d_un.d_val;
1498 case DT_MIPS_RLD_MAP:
1499 *((Elf_Addr *)(dynp->d_un.d_ptr)) = (Elf_Addr) &r_debug;
1502 case DT_MIPS_RLD_MAP_REL:
1503 // The MIPS_RLD_MAP_REL tag stores the offset to the .rld_map
1504 // section relative to the address of the tag itself.
1505 *((Elf_Addr *)(__DECONST(char*, dynp) + dynp->d_un.d_val)) =
1506 (Elf_Addr) &r_debug;
1509 case DT_MIPS_PLTGOT:
1510 obj->mips_pltgot = (Elf_Addr *)(obj->relocbase +
1517 #ifdef __powerpc64__
1518 case DT_PPC64_GLINK:
1519 obj->glink = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1523 obj->gotptr = (Elf_Addr *)(obj->relocbase + dynp->d_un.d_ptr);
1529 if (dynp->d_un.d_val & DF_1_NOOPEN)
1530 obj->z_noopen = true;
1531 if (dynp->d_un.d_val & DF_1_ORIGIN)
1532 obj->z_origin = true;
1533 if (dynp->d_un.d_val & DF_1_GLOBAL)
1534 obj->z_global = true;
1535 if (dynp->d_un.d_val & DF_1_BIND_NOW)
1536 obj->bind_now = true;
1537 if (dynp->d_un.d_val & DF_1_NODELETE)
1538 obj->z_nodelete = true;
1539 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1540 obj->z_loadfltr = true;
1541 if (dynp->d_un.d_val & DF_1_INTERPOSE)
1542 obj->z_interpose = true;
1543 if (dynp->d_un.d_val & DF_1_NODEFLIB)
1544 obj->z_nodeflib = true;
1545 if (dynp->d_un.d_val & DF_1_PIE)
1551 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1558 obj->traced = false;
1560 if (plttype == DT_RELA) {
1561 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1563 obj->pltrelasize = obj->pltrelsize;
1564 obj->pltrelsize = 0;
1567 /* Determine size of dynsym table (equal to nchains of sysv hash) */
1568 if (obj->valid_hash_sysv)
1569 obj->dynsymcount = obj->nchains;
1570 else if (obj->valid_hash_gnu) {
1571 obj->dynsymcount = 0;
1572 for (bkt = 0; bkt < obj->nbuckets_gnu; bkt++) {
1573 if (obj->buckets_gnu[bkt] == 0)
1575 hashval = &obj->chain_zero_gnu[obj->buckets_gnu[bkt]];
1578 while ((*hashval++ & 1u) == 0);
1580 obj->dynsymcount += obj->symndx_gnu;
1583 if (obj->linkmap.l_refname != NULL)
1584 obj->linkmap.l_refname = obj->strtab + (unsigned long)obj->
1589 obj_resolve_origin(Obj_Entry *obj)
1592 if (obj->origin_path != NULL)
1594 obj->origin_path = xmalloc(PATH_MAX);
1595 return (rtld_dirname_abs(obj->path, obj->origin_path) != -1);
1599 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1600 const Elf_Dyn *dyn_soname, const Elf_Dyn *dyn_runpath)
1603 if (obj->z_origin && !obj_resolve_origin(obj))
1606 if (dyn_runpath != NULL) {
1607 obj->runpath = (const char *)obj->strtab + dyn_runpath->d_un.d_val;
1608 obj->runpath = origin_subst(obj, obj->runpath);
1609 } else if (dyn_rpath != NULL) {
1610 obj->rpath = (const char *)obj->strtab + dyn_rpath->d_un.d_val;
1611 obj->rpath = origin_subst(obj, obj->rpath);
1613 if (dyn_soname != NULL)
1614 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1619 digest_dynamic(Obj_Entry *obj, int early)
1621 const Elf_Dyn *dyn_rpath;
1622 const Elf_Dyn *dyn_soname;
1623 const Elf_Dyn *dyn_runpath;
1625 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname, &dyn_runpath);
1626 return (digest_dynamic2(obj, dyn_rpath, dyn_soname, dyn_runpath));
1630 * Process a shared object's program header. This is used only for the
1631 * main program, when the kernel has already loaded the main program
1632 * into memory before calling the dynamic linker. It creates and
1633 * returns an Obj_Entry structure.
1636 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1639 const Elf_Phdr *phlimit = phdr + phnum;
1641 Elf_Addr note_start, note_end;
1645 for (ph = phdr; ph < phlimit; ph++) {
1646 if (ph->p_type != PT_PHDR)
1650 obj->phsize = ph->p_memsz;
1651 obj->relocbase = __DECONST(char *, phdr) - ph->p_vaddr;
1655 obj->stack_flags = PF_X | PF_R | PF_W;
1657 for (ph = phdr; ph < phlimit; ph++) {
1658 switch (ph->p_type) {
1661 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1665 if (nsegs == 0) { /* First load segment */
1666 obj->vaddrbase = trunc_page(ph->p_vaddr);
1667 obj->mapbase = obj->vaddrbase + obj->relocbase;
1668 } else { /* Last load segment */
1669 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1676 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1681 obj->tlssize = ph->p_memsz;
1682 obj->tlsalign = ph->p_align;
1683 obj->tlsinitsize = ph->p_filesz;
1684 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1685 obj->tlspoffset = ph->p_offset;
1689 obj->stack_flags = ph->p_flags;
1693 obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1694 obj->relro_size = trunc_page(ph->p_vaddr + ph->p_memsz) -
1695 trunc_page(ph->p_vaddr);
1699 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
1700 note_end = note_start + ph->p_filesz;
1701 digest_notes(obj, note_start, note_end);
1706 _rtld_error("%s: too few PT_LOAD segments", path);
1715 digest_notes(Obj_Entry *obj, Elf_Addr note_start, Elf_Addr note_end)
1717 const Elf_Note *note;
1718 const char *note_name;
1721 for (note = (const Elf_Note *)note_start; (Elf_Addr)note < note_end;
1722 note = (const Elf_Note *)((const char *)(note + 1) +
1723 roundup2(note->n_namesz, sizeof(Elf32_Addr)) +
1724 roundup2(note->n_descsz, sizeof(Elf32_Addr)))) {
1725 if (note->n_namesz != sizeof(NOTE_FREEBSD_VENDOR) ||
1726 note->n_descsz != sizeof(int32_t))
1728 if (note->n_type != NT_FREEBSD_ABI_TAG &&
1729 note->n_type != NT_FREEBSD_FEATURE_CTL &&
1730 note->n_type != NT_FREEBSD_NOINIT_TAG)
1732 note_name = (const char *)(note + 1);
1733 if (strncmp(NOTE_FREEBSD_VENDOR, note_name,
1734 sizeof(NOTE_FREEBSD_VENDOR)) != 0)
1736 switch (note->n_type) {
1737 case NT_FREEBSD_ABI_TAG:
1738 /* FreeBSD osrel note */
1739 p = (uintptr_t)(note + 1);
1740 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1741 obj->osrel = *(const int32_t *)(p);
1742 dbg("note osrel %d", obj->osrel);
1744 case NT_FREEBSD_FEATURE_CTL:
1745 /* FreeBSD ABI feature control note */
1746 p = (uintptr_t)(note + 1);
1747 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1748 obj->fctl0 = *(const uint32_t *)(p);
1749 dbg("note fctl0 %#x", obj->fctl0);
1751 case NT_FREEBSD_NOINIT_TAG:
1752 /* FreeBSD 'crt does not call init' note */
1753 obj->crt_no_init = true;
1754 dbg("note crt_no_init");
1761 dlcheck(void *handle)
1765 TAILQ_FOREACH(obj, &obj_list, next) {
1766 if (obj == (Obj_Entry *) handle)
1770 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1771 _rtld_error("Invalid shared object handle %p", handle);
1778 * If the given object is already in the donelist, return true. Otherwise
1779 * add the object to the list and return false.
1782 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1786 for (i = 0; i < dlp->num_used; i++)
1787 if (dlp->objs[i] == obj)
1790 * Our donelist allocation should always be sufficient. But if
1791 * our threads locking isn't working properly, more shared objects
1792 * could have been loaded since we allocated the list. That should
1793 * never happen, but we'll handle it properly just in case it does.
1795 if (dlp->num_used < dlp->num_alloc)
1796 dlp->objs[dlp->num_used++] = obj;
1801 * Hash function for symbol table lookup. Don't even think about changing
1802 * this. It is specified by the System V ABI.
1805 elf_hash(const char *name)
1807 const unsigned char *p = (const unsigned char *) name;
1808 unsigned long h = 0;
1811 while (*p != '\0') {
1812 h = (h << 4) + *p++;
1813 if ((g = h & 0xf0000000) != 0)
1821 * The GNU hash function is the Daniel J. Bernstein hash clipped to 32 bits
1822 * unsigned in case it's implemented with a wider type.
1825 gnu_hash(const char *s)
1831 for (c = *s; c != '\0'; c = *++s)
1833 return (h & 0xffffffff);
1838 * Find the library with the given name, and return its full pathname.
1839 * The returned string is dynamically allocated. Generates an error
1840 * message and returns NULL if the library cannot be found.
1842 * If the second argument is non-NULL, then it refers to an already-
1843 * loaded shared object, whose library search path will be searched.
1845 * If a library is successfully located via LD_LIBRARY_PATH_FDS, its
1846 * descriptor (which is close-on-exec) will be passed out via the third
1849 * The search order is:
1850 * DT_RPATH in the referencing file _unless_ DT_RUNPATH is present (1)
1851 * DT_RPATH of the main object if DSO without defined DT_RUNPATH (1)
1853 * DT_RUNPATH in the referencing file
1854 * ldconfig hints (if -z nodefaultlib, filter out default library directories
1856 * /lib:/usr/lib _unless_ the referencing file is linked with -z nodefaultlib
1858 * (1) Handled in digest_dynamic2 - rpath left NULL if runpath defined.
1861 find_library(const char *xname, const Obj_Entry *refobj, int *fdp)
1863 char *pathname, *refobj_path;
1865 bool nodeflib, objgiven;
1867 objgiven = refobj != NULL;
1869 if (libmap_disable || !objgiven ||
1870 (name = lm_find(refobj->path, xname)) == NULL)
1873 if (strchr(name, '/') != NULL) { /* Hard coded pathname */
1874 if (name[0] != '/' && !trust) {
1875 _rtld_error("Absolute pathname required "
1876 "for shared object \"%s\"", name);
1879 return (origin_subst(__DECONST(Obj_Entry *, refobj),
1880 __DECONST(char *, name)));
1883 dbg(" Searching for \"%s\"", name);
1884 refobj_path = objgiven ? refobj->path : NULL;
1887 * If refobj->rpath != NULL, then refobj->runpath is NULL. Fall
1888 * back to pre-conforming behaviour if user requested so with
1889 * LD_LIBRARY_PATH_RPATH environment variable and ignore -z
1892 if (objgiven && refobj->rpath != NULL && ld_library_path_rpath) {
1893 pathname = search_library_path(name, ld_library_path,
1895 if (pathname != NULL)
1897 if (refobj != NULL) {
1898 pathname = search_library_path(name, refobj->rpath,
1900 if (pathname != NULL)
1903 pathname = search_library_pathfds(name, ld_library_dirs, fdp);
1904 if (pathname != NULL)
1906 pathname = search_library_path(name, gethints(false),
1908 if (pathname != NULL)
1910 pathname = search_library_path(name, ld_standard_library_path,
1912 if (pathname != NULL)
1915 nodeflib = objgiven ? refobj->z_nodeflib : false;
1917 pathname = search_library_path(name, refobj->rpath,
1919 if (pathname != NULL)
1922 if (objgiven && refobj->runpath == NULL && refobj != obj_main) {
1923 pathname = search_library_path(name, obj_main->rpath,
1925 if (pathname != NULL)
1928 pathname = search_library_path(name, ld_library_path,
1930 if (pathname != NULL)
1933 pathname = search_library_path(name, refobj->runpath,
1935 if (pathname != NULL)
1938 pathname = search_library_pathfds(name, ld_library_dirs, fdp);
1939 if (pathname != NULL)
1941 pathname = search_library_path(name, gethints(nodeflib),
1943 if (pathname != NULL)
1945 if (objgiven && !nodeflib) {
1946 pathname = search_library_path(name,
1947 ld_standard_library_path, refobj_path, fdp);
1948 if (pathname != NULL)
1953 if (objgiven && refobj->path != NULL) {
1954 _rtld_error("Shared object \"%s\" not found, "
1955 "required by \"%s\"", name, basename(refobj->path));
1957 _rtld_error("Shared object \"%s\" not found", name);
1963 * Given a symbol number in a referencing object, find the corresponding
1964 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1965 * no definition was found. Returns a pointer to the Obj_Entry of the
1966 * defining object via the reference parameter DEFOBJ_OUT.
1969 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1970 const Obj_Entry **defobj_out, int flags, SymCache *cache,
1971 RtldLockState *lockstate)
1975 const Obj_Entry *defobj;
1976 const Ver_Entry *ve;
1982 * If we have already found this symbol, get the information from
1985 if (symnum >= refobj->dynsymcount)
1986 return (NULL); /* Bad object */
1987 if (cache != NULL && cache[symnum].sym != NULL) {
1988 *defobj_out = cache[symnum].obj;
1989 return (cache[symnum].sym);
1992 ref = refobj->symtab + symnum;
1993 name = refobj->strtab + ref->st_name;
1999 * We don't have to do a full scale lookup if the symbol is local.
2000 * We know it will bind to the instance in this load module; to
2001 * which we already have a pointer (ie ref). By not doing a lookup,
2002 * we not only improve performance, but it also avoids unresolvable
2003 * symbols when local symbols are not in the hash table. This has
2004 * been seen with the ia64 toolchain.
2006 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
2007 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
2008 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
2011 symlook_init(&req, name);
2013 ve = req.ventry = fetch_ventry(refobj, symnum);
2014 req.lockstate = lockstate;
2015 res = symlook_default(&req, refobj);
2018 defobj = req.defobj_out;
2026 * If we found no definition and the reference is weak, treat the
2027 * symbol as having the value zero.
2029 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
2035 *defobj_out = defobj;
2036 /* Record the information in the cache to avoid subsequent lookups. */
2037 if (cache != NULL) {
2038 cache[symnum].sym = def;
2039 cache[symnum].obj = defobj;
2042 if (refobj != &obj_rtld)
2043 _rtld_error("%s: Undefined symbol \"%s%s%s\"", refobj->path, name,
2044 ve != NULL ? "@" : "", ve != NULL ? ve->name : "");
2050 * Return the search path from the ldconfig hints file, reading it if
2051 * necessary. If nostdlib is true, then the default search paths are
2052 * not added to result.
2054 * Returns NULL if there are problems with the hints file,
2055 * or if the search path there is empty.
2058 gethints(bool nostdlib)
2060 static char *filtered_path;
2061 static const char *hints;
2062 static struct elfhints_hdr hdr;
2063 struct fill_search_info_args sargs, hargs;
2064 struct dl_serinfo smeta, hmeta, *SLPinfo, *hintinfo;
2065 struct dl_serpath *SLPpath, *hintpath;
2067 struct stat hint_stat;
2068 unsigned int SLPndx, hintndx, fndx, fcount;
2074 /* First call, read the hints file */
2075 if (hints == NULL) {
2076 /* Keep from trying again in case the hints file is bad. */
2079 if ((fd = open(ld_elf_hints_path, O_RDONLY | O_CLOEXEC)) == -1)
2083 * Check of hdr.dirlistlen value against type limit
2084 * intends to pacify static analyzers. Further
2085 * paranoia leads to checks that dirlist is fully
2086 * contained in the file range.
2088 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
2089 hdr.magic != ELFHINTS_MAGIC ||
2090 hdr.version != 1 || hdr.dirlistlen > UINT_MAX / 2 ||
2091 fstat(fd, &hint_stat) == -1) {
2098 if (dl + hdr.dirlist < dl)
2101 if (dl + hdr.dirlistlen < dl)
2103 dl += hdr.dirlistlen;
2104 if (dl > hint_stat.st_size)
2106 p = xmalloc(hdr.dirlistlen + 1);
2107 if (pread(fd, p, hdr.dirlistlen + 1,
2108 hdr.strtab + hdr.dirlist) != (ssize_t)hdr.dirlistlen + 1 ||
2109 p[hdr.dirlistlen] != '\0') {
2118 * If caller agreed to receive list which includes the default
2119 * paths, we are done. Otherwise, if we still did not
2120 * calculated filtered result, do it now.
2123 return (hints[0] != '\0' ? hints : NULL);
2124 if (filtered_path != NULL)
2128 * Obtain the list of all configured search paths, and the
2129 * list of the default paths.
2131 * First estimate the size of the results.
2133 smeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2135 hmeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2138 sargs.request = RTLD_DI_SERINFOSIZE;
2139 sargs.serinfo = &smeta;
2140 hargs.request = RTLD_DI_SERINFOSIZE;
2141 hargs.serinfo = &hmeta;
2143 path_enumerate(ld_standard_library_path, fill_search_info, NULL,
2145 path_enumerate(hints, fill_search_info, NULL, &hargs);
2147 SLPinfo = xmalloc(smeta.dls_size);
2148 hintinfo = xmalloc(hmeta.dls_size);
2151 * Next fetch both sets of paths.
2153 sargs.request = RTLD_DI_SERINFO;
2154 sargs.serinfo = SLPinfo;
2155 sargs.serpath = &SLPinfo->dls_serpath[0];
2156 sargs.strspace = (char *)&SLPinfo->dls_serpath[smeta.dls_cnt];
2158 hargs.request = RTLD_DI_SERINFO;
2159 hargs.serinfo = hintinfo;
2160 hargs.serpath = &hintinfo->dls_serpath[0];
2161 hargs.strspace = (char *)&hintinfo->dls_serpath[hmeta.dls_cnt];
2163 path_enumerate(ld_standard_library_path, fill_search_info, NULL,
2165 path_enumerate(hints, fill_search_info, NULL, &hargs);
2168 * Now calculate the difference between two sets, by excluding
2169 * standard paths from the full set.
2173 filtered_path = xmalloc(hdr.dirlistlen + 1);
2174 hintpath = &hintinfo->dls_serpath[0];
2175 for (hintndx = 0; hintndx < hmeta.dls_cnt; hintndx++, hintpath++) {
2177 SLPpath = &SLPinfo->dls_serpath[0];
2179 * Check each standard path against current.
2181 for (SLPndx = 0; SLPndx < smeta.dls_cnt; SLPndx++, SLPpath++) {
2182 /* matched, skip the path */
2183 if (!strcmp(hintpath->dls_name, SLPpath->dls_name)) {
2191 * Not matched against any standard path, add the path
2192 * to result. Separate consequtive paths with ':'.
2195 filtered_path[fndx] = ':';
2199 flen = strlen(hintpath->dls_name);
2200 strncpy((filtered_path + fndx), hintpath->dls_name, flen);
2203 filtered_path[fndx] = '\0';
2209 return (filtered_path[0] != '\0' ? filtered_path : NULL);
2213 init_dag(Obj_Entry *root)
2215 const Needed_Entry *needed;
2216 const Objlist_Entry *elm;
2219 if (root->dag_inited)
2221 donelist_init(&donelist);
2223 /* Root object belongs to own DAG. */
2224 objlist_push_tail(&root->dldags, root);
2225 objlist_push_tail(&root->dagmembers, root);
2226 donelist_check(&donelist, root);
2229 * Add dependencies of root object to DAG in breadth order
2230 * by exploiting the fact that each new object get added
2231 * to the tail of the dagmembers list.
2233 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2234 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
2235 if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
2237 objlist_push_tail(&needed->obj->dldags, root);
2238 objlist_push_tail(&root->dagmembers, needed->obj);
2241 root->dag_inited = true;
2245 init_marker(Obj_Entry *marker)
2248 bzero(marker, sizeof(*marker));
2249 marker->marker = true;
2253 globallist_curr(const Obj_Entry *obj)
2260 return (__DECONST(Obj_Entry *, obj));
2261 obj = TAILQ_PREV(obj, obj_entry_q, next);
2266 globallist_next(const Obj_Entry *obj)
2270 obj = TAILQ_NEXT(obj, next);
2274 return (__DECONST(Obj_Entry *, obj));
2278 /* Prevent the object from being unmapped while the bind lock is dropped. */
2280 hold_object(Obj_Entry *obj)
2287 unhold_object(Obj_Entry *obj)
2290 assert(obj->holdcount > 0);
2291 if (--obj->holdcount == 0 && obj->unholdfree)
2292 release_object(obj);
2296 process_z(Obj_Entry *root)
2298 const Objlist_Entry *elm;
2302 * Walk over object DAG and process every dependent object
2303 * that is marked as DF_1_NODELETE or DF_1_GLOBAL. They need
2304 * to grow their own DAG.
2306 * For DF_1_GLOBAL, DAG is required for symbol lookups in
2307 * symlook_global() to work.
2309 * For DF_1_NODELETE, the DAG should have its reference upped.
2311 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2315 if (obj->z_nodelete && !obj->ref_nodel) {
2316 dbg("obj %s -z nodelete", obj->path);
2319 obj->ref_nodel = true;
2321 if (obj->z_global && objlist_find(&list_global, obj) == NULL) {
2322 dbg("obj %s -z global", obj->path);
2323 objlist_push_tail(&list_global, obj);
2330 parse_rtld_phdr(Obj_Entry *obj)
2333 Elf_Addr note_start, note_end;
2335 obj->stack_flags = PF_X | PF_R | PF_W;
2336 for (ph = obj->phdr; (const char *)ph < (const char *)obj->phdr +
2337 obj->phsize; ph++) {
2338 switch (ph->p_type) {
2340 obj->stack_flags = ph->p_flags;
2343 obj->relro_page = obj->relocbase +
2344 trunc_page(ph->p_vaddr);
2345 obj->relro_size = round_page(ph->p_memsz);
2348 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
2349 note_end = note_start + ph->p_filesz;
2350 digest_notes(obj, note_start, note_end);
2357 * Initialize the dynamic linker. The argument is the address at which
2358 * the dynamic linker has been mapped into memory. The primary task of
2359 * this function is to relocate the dynamic linker.
2362 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
2364 Obj_Entry objtmp; /* Temporary rtld object */
2365 const Elf_Ehdr *ehdr;
2366 const Elf_Dyn *dyn_rpath;
2367 const Elf_Dyn *dyn_soname;
2368 const Elf_Dyn *dyn_runpath;
2370 #ifdef RTLD_INIT_PAGESIZES_EARLY
2371 /* The page size is required by the dynamic memory allocator. */
2372 init_pagesizes(aux_info);
2376 * Conjure up an Obj_Entry structure for the dynamic linker.
2378 * The "path" member can't be initialized yet because string constants
2379 * cannot yet be accessed. Below we will set it correctly.
2381 memset(&objtmp, 0, sizeof(objtmp));
2384 objtmp.mapbase = mapbase;
2386 objtmp.relocbase = mapbase;
2389 objtmp.dynamic = rtld_dynamic(&objtmp);
2390 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname, &dyn_runpath);
2391 assert(objtmp.needed == NULL);
2392 #if !defined(__mips__)
2393 /* MIPS has a bogus DT_TEXTREL. */
2394 assert(!objtmp.textrel);
2397 * Temporarily put the dynamic linker entry into the object list, so
2398 * that symbols can be found.
2400 relocate_objects(&objtmp, true, &objtmp, 0, NULL);
2402 ehdr = (Elf_Ehdr *)mapbase;
2403 objtmp.phdr = (Elf_Phdr *)((char *)mapbase + ehdr->e_phoff);
2404 objtmp.phsize = ehdr->e_phnum * sizeof(objtmp.phdr[0]);
2406 /* Initialize the object list. */
2407 TAILQ_INIT(&obj_list);
2409 /* Now that non-local variables can be accesses, copy out obj_rtld. */
2410 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
2412 #ifndef RTLD_INIT_PAGESIZES_EARLY
2413 /* The page size is required by the dynamic memory allocator. */
2414 init_pagesizes(aux_info);
2417 if (aux_info[AT_OSRELDATE] != NULL)
2418 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
2420 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname, dyn_runpath);
2422 /* Replace the path with a dynamically allocated copy. */
2423 obj_rtld.path = xstrdup(ld_path_rtld);
2425 parse_rtld_phdr(&obj_rtld);
2426 if (obj_enforce_relro(&obj_rtld) == -1)
2429 r_debug.r_version = R_DEBUG_VERSION;
2430 r_debug.r_brk = r_debug_state;
2431 r_debug.r_state = RT_CONSISTENT;
2432 r_debug.r_ldbase = obj_rtld.relocbase;
2436 * Retrieve the array of supported page sizes. The kernel provides the page
2437 * sizes in increasing order.
2440 init_pagesizes(Elf_Auxinfo **aux_info)
2442 static size_t psa[MAXPAGESIZES];
2446 if (aux_info[AT_PAGESIZES] != NULL && aux_info[AT_PAGESIZESLEN] !=
2448 size = aux_info[AT_PAGESIZESLEN]->a_un.a_val;
2449 pagesizes = aux_info[AT_PAGESIZES]->a_un.a_ptr;
2452 if (sysctlnametomib("hw.pagesizes", mib, &len) == 0)
2455 /* As a fallback, retrieve the base page size. */
2456 size = sizeof(psa[0]);
2457 if (aux_info[AT_PAGESZ] != NULL) {
2458 psa[0] = aux_info[AT_PAGESZ]->a_un.a_val;
2462 mib[1] = HW_PAGESIZE;
2466 if (sysctl(mib, len, psa, &size, NULL, 0) == -1) {
2467 _rtld_error("sysctl for hw.pagesize(s) failed");
2473 npagesizes = size / sizeof(pagesizes[0]);
2474 /* Discard any invalid entries at the end of the array. */
2475 while (npagesizes > 0 && pagesizes[npagesizes - 1] == 0)
2480 * Add the init functions from a needed object list (and its recursive
2481 * needed objects) to "list". This is not used directly; it is a helper
2482 * function for initlist_add_objects(). The write lock must be held
2483 * when this function is called.
2486 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
2488 /* Recursively process the successor needed objects. */
2489 if (needed->next != NULL)
2490 initlist_add_neededs(needed->next, list);
2492 /* Process the current needed object. */
2493 if (needed->obj != NULL)
2494 initlist_add_objects(needed->obj, needed->obj, list);
2498 * Scan all of the DAGs rooted in the range of objects from "obj" to
2499 * "tail" and add their init functions to "list". This recurses over
2500 * the DAGs and ensure the proper init ordering such that each object's
2501 * needed libraries are initialized before the object itself. At the
2502 * same time, this function adds the objects to the global finalization
2503 * list "list_fini" in the opposite order. The write lock must be
2504 * held when this function is called.
2507 initlist_add_objects(Obj_Entry *obj, Obj_Entry *tail, Objlist *list)
2511 if (obj->init_scanned || obj->init_done)
2513 obj->init_scanned = true;
2515 /* Recursively process the successor objects. */
2516 nobj = globallist_next(obj);
2517 if (nobj != NULL && obj != tail)
2518 initlist_add_objects(nobj, tail, list);
2520 /* Recursively process the needed objects. */
2521 if (obj->needed != NULL)
2522 initlist_add_neededs(obj->needed, list);
2523 if (obj->needed_filtees != NULL)
2524 initlist_add_neededs(obj->needed_filtees, list);
2525 if (obj->needed_aux_filtees != NULL)
2526 initlist_add_neededs(obj->needed_aux_filtees, list);
2528 /* Add the object to the init list. */
2529 objlist_push_tail(list, obj);
2531 /* Add the object to the global fini list in the reverse order. */
2532 if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL)
2533 && !obj->on_fini_list) {
2534 objlist_push_head(&list_fini, obj);
2535 obj->on_fini_list = true;
2540 #define FPTR_TARGET(f) ((Elf_Addr) (f))
2544 free_needed_filtees(Needed_Entry *n, RtldLockState *lockstate)
2546 Needed_Entry *needed, *needed1;
2548 for (needed = n; needed != NULL; needed = needed->next) {
2549 if (needed->obj != NULL) {
2550 dlclose_locked(needed->obj, lockstate);
2554 for (needed = n; needed != NULL; needed = needed1) {
2555 needed1 = needed->next;
2561 unload_filtees(Obj_Entry *obj, RtldLockState *lockstate)
2564 free_needed_filtees(obj->needed_filtees, lockstate);
2565 obj->needed_filtees = NULL;
2566 free_needed_filtees(obj->needed_aux_filtees, lockstate);
2567 obj->needed_aux_filtees = NULL;
2568 obj->filtees_loaded = false;
2572 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags,
2573 RtldLockState *lockstate)
2576 for (; needed != NULL; needed = needed->next) {
2577 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
2578 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
2579 RTLD_LOCAL, lockstate);
2584 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
2587 lock_restart_for_upgrade(lockstate);
2588 if (!obj->filtees_loaded) {
2589 load_filtee1(obj, obj->needed_filtees, flags, lockstate);
2590 load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate);
2591 obj->filtees_loaded = true;
2596 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
2600 for (; needed != NULL; needed = needed->next) {
2601 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
2602 flags & ~RTLD_LO_NOLOAD);
2603 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
2610 * Given a shared object, traverse its list of needed objects, and load
2611 * each of them. Returns 0 on success. Generates an error message and
2612 * returns -1 on failure.
2615 load_needed_objects(Obj_Entry *first, int flags)
2619 for (obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
2622 if (process_needed(obj, obj->needed, flags) == -1)
2629 load_preload_objects(const char *penv, bool isfd)
2634 char savech, *p, *psave;
2636 static const char delim[] = " \t:;";
2641 p = psave = xstrdup(penv);
2642 p += strspn(p, delim);
2643 while (*p != '\0') {
2644 len = strcspn(p, delim);
2650 fd = parse_integer(p);
2660 obj = load_object(name, fd, NULL, 0);
2663 return (-1); /* XXX - cleanup */
2665 obj->z_interpose = true;
2668 p += strspn(p, delim);
2670 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
2677 printable_path(const char *path)
2680 return (path == NULL ? "<unknown>" : path);
2684 * Load a shared object into memory, if it is not already loaded. The
2685 * object may be specified by name or by user-supplied file descriptor
2686 * fd_u. In the later case, the fd_u descriptor is not closed, but its
2689 * Returns a pointer to the Obj_Entry for the object. Returns NULL
2693 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
2702 TAILQ_FOREACH(obj, &obj_list, next) {
2703 if (obj->marker || obj->doomed)
2705 if (object_match_name(obj, name))
2709 path = find_library(name, refobj, &fd);
2717 * search_library_pathfds() opens a fresh file descriptor for the
2718 * library, so there is no need to dup().
2720 } else if (fd_u == -1) {
2722 * If we didn't find a match by pathname, or the name is not
2723 * supplied, open the file and check again by device and inode.
2724 * This avoids false mismatches caused by multiple links or ".."
2727 * To avoid a race, we open the file and use fstat() rather than
2730 if ((fd = open(path, O_RDONLY | O_CLOEXEC | O_VERIFY)) == -1) {
2731 _rtld_error("Cannot open \"%s\"", path);
2736 fd = fcntl(fd_u, F_DUPFD_CLOEXEC, 0);
2738 _rtld_error("Cannot dup fd");
2743 if (fstat(fd, &sb) == -1) {
2744 _rtld_error("Cannot fstat \"%s\"", printable_path(path));
2749 TAILQ_FOREACH(obj, &obj_list, next) {
2750 if (obj->marker || obj->doomed)
2752 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
2755 if (obj != NULL && name != NULL) {
2756 object_add_name(obj, name);
2761 if (flags & RTLD_LO_NOLOAD) {
2767 /* First use of this object, so we must map it in */
2768 obj = do_load_object(fd, name, path, &sb, flags);
2777 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
2784 * First, make sure that environment variables haven't been
2785 * used to circumvent the noexec flag on a filesystem.
2786 * We ignore fstatfs(2) failures, since fd might reference
2787 * not a file, e.g. shmfd.
2789 if (dangerous_ld_env && fstatfs(fd, &fs) == 0 &&
2790 (fs.f_flags & MNT_NOEXEC) != 0) {
2791 _rtld_error("Cannot execute objects on %s", fs.f_mntonname);
2795 dbg("loading \"%s\"", printable_path(path));
2796 obj = map_object(fd, printable_path(path), sbp);
2801 * If DT_SONAME is present in the object, digest_dynamic2 already
2802 * added it to the object names.
2805 object_add_name(obj, name);
2807 if (!digest_dynamic(obj, 0))
2809 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path,
2810 obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount);
2811 if (obj->z_pie && (flags & RTLD_LO_TRACE) == 0) {
2812 dbg("refusing to load PIE executable \"%s\"", obj->path);
2813 _rtld_error("Cannot load PIE binary %s as DSO", obj->path);
2816 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
2818 dbg("refusing to load non-loadable \"%s\"", obj->path);
2819 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
2823 obj->dlopened = (flags & RTLD_LO_DLOPEN) != 0;
2824 TAILQ_INSERT_TAIL(&obj_list, obj, next);
2827 linkmap_add(obj); /* for GDB & dlinfo() */
2828 max_stack_flags |= obj->stack_flags;
2830 dbg(" %p .. %p: %s", obj->mapbase,
2831 obj->mapbase + obj->mapsize - 1, obj->path);
2833 dbg(" WARNING: %s has impure text", obj->path);
2834 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
2840 munmap(obj->mapbase, obj->mapsize);
2846 obj_from_addr(const void *addr)
2850 TAILQ_FOREACH(obj, &obj_list, next) {
2853 if (addr < (void *) obj->mapbase)
2855 if (addr < (void *)(obj->mapbase + obj->mapsize))
2864 Elf_Addr *preinit_addr;
2867 preinit_addr = (Elf_Addr *)obj_main->preinit_array;
2868 if (preinit_addr == NULL)
2871 for (index = 0; index < obj_main->preinit_array_num; index++) {
2872 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) {
2873 dbg("calling preinit function for %s at %p", obj_main->path,
2874 (void *)preinit_addr[index]);
2875 LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index],
2876 0, 0, obj_main->path);
2877 call_init_pointer(obj_main, preinit_addr[index]);
2883 * Call the finalization functions for each of the objects in "list"
2884 * belonging to the DAG of "root" and referenced once. If NULL "root"
2885 * is specified, every finalization function will be called regardless
2886 * of the reference count and the list elements won't be freed. All of
2887 * the objects are expected to have non-NULL fini functions.
2890 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
2893 struct dlerror_save *saved_msg;
2894 Elf_Addr *fini_addr;
2897 assert(root == NULL || root->refcount == 1);
2900 root->doomed = true;
2903 * Preserve the current error message since a fini function might
2904 * call into the dynamic linker and overwrite it.
2906 saved_msg = errmsg_save();
2908 STAILQ_FOREACH(elm, list, link) {
2909 if (root != NULL && (elm->obj->refcount != 1 ||
2910 objlist_find(&root->dagmembers, elm->obj) == NULL))
2912 /* Remove object from fini list to prevent recursive invocation. */
2913 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2914 /* Ensure that new references cannot be acquired. */
2915 elm->obj->doomed = true;
2917 hold_object(elm->obj);
2918 lock_release(rtld_bind_lock, lockstate);
2920 * It is legal to have both DT_FINI and DT_FINI_ARRAY defined.
2921 * When this happens, DT_FINI_ARRAY is processed first.
2923 fini_addr = (Elf_Addr *)elm->obj->fini_array;
2924 if (fini_addr != NULL && elm->obj->fini_array_num > 0) {
2925 for (index = elm->obj->fini_array_num - 1; index >= 0;
2927 if (fini_addr[index] != 0 && fini_addr[index] != 1) {
2928 dbg("calling fini function for %s at %p",
2929 elm->obj->path, (void *)fini_addr[index]);
2930 LD_UTRACE(UTRACE_FINI_CALL, elm->obj,
2931 (void *)fini_addr[index], 0, 0, elm->obj->path);
2932 call_initfini_pointer(elm->obj, fini_addr[index]);
2936 if (elm->obj->fini != (Elf_Addr)NULL) {
2937 dbg("calling fini function for %s at %p", elm->obj->path,
2938 (void *)elm->obj->fini);
2939 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini,
2940 0, 0, elm->obj->path);
2941 call_initfini_pointer(elm->obj, elm->obj->fini);
2943 wlock_acquire(rtld_bind_lock, lockstate);
2944 unhold_object(elm->obj);
2945 /* No need to free anything if process is going down. */
2949 * We must restart the list traversal after every fini call
2950 * because a dlclose() call from the fini function or from
2951 * another thread might have modified the reference counts.
2955 } while (elm != NULL);
2956 errmsg_restore(saved_msg);
2960 * Call the initialization functions for each of the objects in
2961 * "list". All of the objects are expected to have non-NULL init
2965 objlist_call_init(Objlist *list, RtldLockState *lockstate)
2969 struct dlerror_save *saved_msg;
2970 Elf_Addr *init_addr;
2971 void (*reg)(void (*)(void));
2975 * Clean init_scanned flag so that objects can be rechecked and
2976 * possibly initialized earlier if any of vectors called below
2977 * cause the change by using dlopen.
2979 TAILQ_FOREACH(obj, &obj_list, next) {
2982 obj->init_scanned = false;
2986 * Preserve the current error message since an init function might
2987 * call into the dynamic linker and overwrite it.
2989 saved_msg = errmsg_save();
2990 STAILQ_FOREACH(elm, list, link) {
2991 if (elm->obj->init_done) /* Initialized early. */
2994 * Race: other thread might try to use this object before current
2995 * one completes the initialization. Not much can be done here
2996 * without better locking.
2998 elm->obj->init_done = true;
2999 hold_object(elm->obj);
3001 if (elm->obj == obj_main && obj_main->crt_no_init) {
3002 reg = (void (*)(void (*)(void)))get_program_var_addr(
3003 "__libc_atexit", lockstate);
3005 lock_release(rtld_bind_lock, lockstate);
3008 rtld_exit_ptr = rtld_nop_exit;
3012 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined.
3013 * When this happens, DT_INIT is processed first.
3015 if (elm->obj->init != (Elf_Addr)NULL) {
3016 dbg("calling init function for %s at %p", elm->obj->path,
3017 (void *)elm->obj->init);
3018 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init,
3019 0, 0, elm->obj->path);
3020 call_init_pointer(elm->obj, elm->obj->init);
3022 init_addr = (Elf_Addr *)elm->obj->init_array;
3023 if (init_addr != NULL) {
3024 for (index = 0; index < elm->obj->init_array_num; index++) {
3025 if (init_addr[index] != 0 && init_addr[index] != 1) {
3026 dbg("calling init function for %s at %p", elm->obj->path,
3027 (void *)init_addr[index]);
3028 LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
3029 (void *)init_addr[index], 0, 0, elm->obj->path);
3030 call_init_pointer(elm->obj, init_addr[index]);
3034 wlock_acquire(rtld_bind_lock, lockstate);
3035 unhold_object(elm->obj);
3037 errmsg_restore(saved_msg);
3041 objlist_clear(Objlist *list)
3045 while (!STAILQ_EMPTY(list)) {
3046 elm = STAILQ_FIRST(list);
3047 STAILQ_REMOVE_HEAD(list, link);
3052 static Objlist_Entry *
3053 objlist_find(Objlist *list, const Obj_Entry *obj)
3057 STAILQ_FOREACH(elm, list, link)
3058 if (elm->obj == obj)
3064 objlist_init(Objlist *list)
3070 objlist_push_head(Objlist *list, Obj_Entry *obj)
3074 elm = NEW(Objlist_Entry);
3076 STAILQ_INSERT_HEAD(list, elm, link);
3080 objlist_push_tail(Objlist *list, Obj_Entry *obj)
3084 elm = NEW(Objlist_Entry);
3086 STAILQ_INSERT_TAIL(list, elm, link);
3090 objlist_put_after(Objlist *list, Obj_Entry *listobj, Obj_Entry *obj)
3092 Objlist_Entry *elm, *listelm;
3094 STAILQ_FOREACH(listelm, list, link) {
3095 if (listelm->obj == listobj)
3098 elm = NEW(Objlist_Entry);
3100 if (listelm != NULL)
3101 STAILQ_INSERT_AFTER(list, listelm, elm, link);
3103 STAILQ_INSERT_TAIL(list, elm, link);
3107 objlist_remove(Objlist *list, Obj_Entry *obj)
3111 if ((elm = objlist_find(list, obj)) != NULL) {
3112 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
3118 * Relocate dag rooted in the specified object.
3119 * Returns 0 on success, or -1 on failure.
3123 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj,
3124 int flags, RtldLockState *lockstate)
3130 STAILQ_FOREACH(elm, &root->dagmembers, link) {
3131 error = relocate_object(elm->obj, bind_now, rtldobj, flags,
3140 * Prepare for, or clean after, relocating an object marked with
3141 * DT_TEXTREL or DF_TEXTREL. Before relocating, all read-only
3142 * segments are remapped read-write. After relocations are done, the
3143 * segment's permissions are returned back to the modes specified in
3144 * the phdrs. If any relocation happened, or always for wired
3145 * program, COW is triggered.
3148 reloc_textrel_prot(Obj_Entry *obj, bool before)
3155 for (l = obj->phsize / sizeof(*ph), ph = obj->phdr; l > 0;
3157 if (ph->p_type != PT_LOAD || (ph->p_flags & PF_W) != 0)
3159 base = obj->relocbase + trunc_page(ph->p_vaddr);
3160 sz = round_page(ph->p_vaddr + ph->p_filesz) -
3161 trunc_page(ph->p_vaddr);
3162 prot = before ? (PROT_READ | PROT_WRITE) :
3163 convert_prot(ph->p_flags);
3164 if (mprotect(base, sz, prot) == -1) {
3165 _rtld_error("%s: Cannot write-%sable text segment: %s",
3166 obj->path, before ? "en" : "dis",
3167 rtld_strerror(errno));
3174 /* Process RELR relative relocations. */
3176 reloc_relr(Obj_Entry *obj)
3178 const Elf_Relr *relr, *relrlim;
3181 relrlim = (const Elf_Relr *)((const char *)obj->relr + obj->relrsize);
3182 for (relr = obj->relr; relr < relrlim; relr++) {
3183 Elf_Relr entry = *relr;
3185 if ((entry & 1) == 0) {
3186 where = (Elf_Addr *)(obj->relocbase + entry);
3187 *where++ += (Elf_Addr)obj->relocbase;
3189 for (long i = 0; (entry >>= 1) != 0; i++)
3190 if ((entry & 1) != 0)
3191 where[i] += (Elf_Addr)obj->relocbase;
3192 where += CHAR_BIT * sizeof(Elf_Relr) - 1;
3198 * Relocate single object.
3199 * Returns 0 on success, or -1 on failure.
3202 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
3203 int flags, RtldLockState *lockstate)
3208 obj->relocated = true;
3210 dbg("relocating \"%s\"", obj->path);
3212 if (obj->symtab == NULL || obj->strtab == NULL ||
3213 !(obj->valid_hash_sysv || obj->valid_hash_gnu))
3214 dbg("object %s has no run-time symbol table", obj->path);
3216 /* There are relocations to the write-protected text segment. */
3217 if (obj->textrel && reloc_textrel_prot(obj, true) != 0)
3220 /* Process the non-PLT non-IFUNC relocations. */
3221 if (reloc_non_plt(obj, rtldobj, flags, lockstate))
3225 /* Re-protected the text segment. */
3226 if (obj->textrel && reloc_textrel_prot(obj, false) != 0)
3229 /* Set the special PLT or GOT entries. */
3232 /* Process the PLT relocations. */
3233 if (reloc_plt(obj, flags, lockstate) == -1)
3235 /* Relocate the jump slots if we are doing immediate binding. */
3236 if ((obj->bind_now || bind_now) && reloc_jmpslots(obj, flags,
3240 if (!obj->mainprog && obj_enforce_relro(obj) == -1)
3244 * Set up the magic number and version in the Obj_Entry. These
3245 * were checked in the crt1.o from the original ElfKit, so we
3246 * set them for backward compatibility.
3248 obj->magic = RTLD_MAGIC;
3249 obj->version = RTLD_VERSION;
3255 * Relocate newly-loaded shared objects. The argument is a pointer to
3256 * the Obj_Entry for the first such object. All objects from the first
3257 * to the end of the list of objects are relocated. Returns 0 on success,
3261 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
3262 int flags, RtldLockState *lockstate)
3267 for (error = 0, obj = first; obj != NULL;
3268 obj = TAILQ_NEXT(obj, next)) {
3271 error = relocate_object(obj, bind_now, rtldobj, flags,
3280 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
3281 * referencing STT_GNU_IFUNC symbols is postponed till the other
3282 * relocations are done. The indirect functions specified as
3283 * ifunc are allowed to call other symbols, so we need to have
3284 * objects relocated before asking for resolution from indirects.
3286 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
3287 * instead of the usual lazy handling of PLT slots. It is
3288 * consistent with how GNU does it.
3291 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags,
3292 RtldLockState *lockstate)
3295 if (obj->ifuncs_resolved)
3297 obj->ifuncs_resolved = true;
3298 if (!obj->irelative && !obj->irelative_nonplt &&
3299 !((obj->bind_now || bind_now) && obj->gnu_ifunc) &&
3300 !obj->non_plt_gnu_ifunc)
3302 if (obj_disable_relro(obj) == -1 ||
3303 (obj->irelative && reloc_iresolve(obj, lockstate) == -1) ||
3304 (obj->irelative_nonplt && reloc_iresolve_nonplt(obj,
3305 lockstate) == -1) ||
3306 ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
3307 reloc_gnu_ifunc(obj, flags, lockstate) == -1) ||
3308 (obj->non_plt_gnu_ifunc && reloc_non_plt(obj, &obj_rtld,
3309 flags | SYMLOOK_IFUNC, lockstate) == -1) ||
3310 obj_enforce_relro(obj) == -1)
3316 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags,
3317 RtldLockState *lockstate)
3322 STAILQ_FOREACH(elm, list, link) {
3326 if (resolve_object_ifunc(obj, bind_now, flags,
3334 * Cleanup procedure. It will be called (by the atexit mechanism) just
3335 * before the process exits.
3340 RtldLockState lockstate;
3342 wlock_acquire(rtld_bind_lock, &lockstate);
3344 objlist_call_fini(&list_fini, NULL, &lockstate);
3345 /* No need to remove the items from the list, since we are exiting. */
3346 if (!libmap_disable)
3348 lock_release(rtld_bind_lock, &lockstate);
3357 * Iterate over a search path, translate each element, and invoke the
3358 * callback on the result.
3361 path_enumerate(const char *path, path_enum_proc callback,
3362 const char *refobj_path, void *arg)
3368 path += strspn(path, ":;");
3369 while (*path != '\0') {
3373 len = strcspn(path, ":;");
3374 trans = lm_findn(refobj_path, path, len);
3376 res = callback(trans, strlen(trans), arg);
3378 res = callback(path, len, arg);
3384 path += strspn(path, ":;");
3390 struct try_library_args {
3399 try_library_path(const char *dir, size_t dirlen, void *param)
3401 struct try_library_args *arg;
3405 if (*dir == '/' || trust) {
3408 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
3411 pathname = arg->buffer;
3412 strncpy(pathname, dir, dirlen);
3413 pathname[dirlen] = '/';
3414 strcpy(pathname + dirlen + 1, arg->name);
3416 dbg(" Trying \"%s\"", pathname);
3417 fd = open(pathname, O_RDONLY | O_CLOEXEC | O_VERIFY);
3419 dbg(" Opened \"%s\", fd %d", pathname, fd);
3420 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
3421 strcpy(pathname, arg->buffer);
3425 dbg(" Failed to open \"%s\": %s",
3426 pathname, rtld_strerror(errno));
3433 search_library_path(const char *name, const char *path,
3434 const char *refobj_path, int *fdp)
3437 struct try_library_args arg;
3443 arg.namelen = strlen(name);
3444 arg.buffer = xmalloc(PATH_MAX);
3445 arg.buflen = PATH_MAX;
3448 p = path_enumerate(path, try_library_path, refobj_path, &arg);
3458 * Finds the library with the given name using the directory descriptors
3459 * listed in the LD_LIBRARY_PATH_FDS environment variable.
3461 * Returns a freshly-opened close-on-exec file descriptor for the library,
3462 * or -1 if the library cannot be found.
3465 search_library_pathfds(const char *name, const char *path, int *fdp)
3467 char *envcopy, *fdstr, *found, *last_token;
3471 dbg("%s('%s', '%s', fdp)", __func__, name, path);
3473 /* Don't load from user-specified libdirs into setuid binaries. */
3477 /* We can't do anything if LD_LIBRARY_PATH_FDS isn't set. */
3481 /* LD_LIBRARY_PATH_FDS only works with relative paths. */
3482 if (name[0] == '/') {
3483 dbg("Absolute path (%s) passed to %s", name, __func__);
3488 * Use strtok_r() to walk the FD:FD:FD list. This requires a local
3489 * copy of the path, as strtok_r rewrites separator tokens
3493 envcopy = xstrdup(path);
3494 for (fdstr = strtok_r(envcopy, ":", &last_token); fdstr != NULL;
3495 fdstr = strtok_r(NULL, ":", &last_token)) {
3496 dirfd = parse_integer(fdstr);
3498 _rtld_error("failed to parse directory FD: '%s'",
3502 fd = __sys_openat(dirfd, name, O_RDONLY | O_CLOEXEC | O_VERIFY);
3505 len = strlen(fdstr) + strlen(name) + 3;
3506 found = xmalloc(len);
3507 if (rtld_snprintf(found, len, "#%d/%s", dirfd, name) < 0) {
3508 _rtld_error("error generating '%d/%s'",
3512 dbg("open('%s') => %d", found, fd);
3523 dlclose(void *handle)
3525 RtldLockState lockstate;
3528 wlock_acquire(rtld_bind_lock, &lockstate);
3529 error = dlclose_locked(handle, &lockstate);
3530 lock_release(rtld_bind_lock, &lockstate);
3535 dlclose_locked(void *handle, RtldLockState *lockstate)
3539 root = dlcheck(handle);
3542 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
3545 /* Unreference the object and its dependencies. */
3546 root->dl_refcount--;
3548 if (root->refcount == 1) {
3550 * The object will be no longer referenced, so we must unload it.
3551 * First, call the fini functions.
3553 objlist_call_fini(&list_fini, root, lockstate);
3557 /* Finish cleaning up the newly-unreferenced objects. */
3558 GDB_STATE(RT_DELETE,&root->linkmap);
3559 unload_object(root, lockstate);
3560 GDB_STATE(RT_CONSISTENT,NULL);
3564 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
3571 if (*(lockinfo.dlerror_seen()) != 0)
3573 *lockinfo.dlerror_seen() = 1;
3574 return (lockinfo.dlerror_loc());
3578 * This function is deprecated and has no effect.
3581 dllockinit(void *context,
3582 void *(*_lock_create)(void *context) __unused,
3583 void (*_rlock_acquire)(void *lock) __unused,
3584 void (*_wlock_acquire)(void *lock) __unused,
3585 void (*_lock_release)(void *lock) __unused,
3586 void (*_lock_destroy)(void *lock) __unused,
3587 void (*context_destroy)(void *context))
3589 static void *cur_context;
3590 static void (*cur_context_destroy)(void *);
3592 /* Just destroy the context from the previous call, if necessary. */
3593 if (cur_context_destroy != NULL)
3594 cur_context_destroy(cur_context);
3595 cur_context = context;
3596 cur_context_destroy = context_destroy;
3600 dlopen(const char *name, int mode)
3603 return (rtld_dlopen(name, -1, mode));
3607 fdlopen(int fd, int mode)
3610 return (rtld_dlopen(NULL, fd, mode));
3614 rtld_dlopen(const char *name, int fd, int mode)
3616 RtldLockState lockstate;
3619 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
3620 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
3621 if (ld_tracing != NULL) {
3622 rlock_acquire(rtld_bind_lock, &lockstate);
3623 if (sigsetjmp(lockstate.env, 0) != 0)
3624 lock_upgrade(rtld_bind_lock, &lockstate);
3625 environ = __DECONST(char **, *get_program_var_addr("environ", &lockstate));
3626 lock_release(rtld_bind_lock, &lockstate);
3628 lo_flags = RTLD_LO_DLOPEN;
3629 if (mode & RTLD_NODELETE)
3630 lo_flags |= RTLD_LO_NODELETE;
3631 if (mode & RTLD_NOLOAD)
3632 lo_flags |= RTLD_LO_NOLOAD;
3633 if (mode & RTLD_DEEPBIND)
3634 lo_flags |= RTLD_LO_DEEPBIND;
3635 if (ld_tracing != NULL)
3636 lo_flags |= RTLD_LO_TRACE | RTLD_LO_IGNSTLS;
3638 return (dlopen_object(name, fd, obj_main, lo_flags,
3639 mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL));
3643 dlopen_cleanup(Obj_Entry *obj, RtldLockState *lockstate)
3648 if (obj->refcount == 0)
3649 unload_object(obj, lockstate);
3653 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
3654 int mode, RtldLockState *lockstate)
3656 Obj_Entry *old_obj_tail;
3659 RtldLockState mlockstate;
3662 dbg("dlopen_object name \"%s\" fd %d refobj \"%s\" lo_flags %#x mode %#x",
3663 name != NULL ? name : "<null>", fd, refobj == NULL ? "<null>" :
3664 refobj->path, lo_flags, mode);
3665 objlist_init(&initlist);
3667 if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) {
3668 wlock_acquire(rtld_bind_lock, &mlockstate);
3669 lockstate = &mlockstate;
3671 GDB_STATE(RT_ADD,NULL);
3673 old_obj_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
3675 if (name == NULL && fd == -1) {
3679 obj = load_object(name, fd, refobj, lo_flags);
3684 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
3685 objlist_push_tail(&list_global, obj);
3686 if (globallist_next(old_obj_tail) != NULL) {
3687 /* We loaded something new. */
3688 assert(globallist_next(old_obj_tail) == obj);
3689 if ((lo_flags & RTLD_LO_DEEPBIND) != 0)
3690 obj->symbolic = true;
3692 if ((lo_flags & (RTLD_LO_EARLY | RTLD_LO_IGNSTLS)) == 0 &&
3693 obj->static_tls && !allocate_tls_offset(obj)) {
3694 _rtld_error("%s: No space available "
3695 "for static Thread Local Storage", obj->path);
3699 result = load_needed_objects(obj, lo_flags & (RTLD_LO_DLOPEN |
3700 RTLD_LO_EARLY | RTLD_LO_IGNSTLS | RTLD_LO_TRACE));
3704 result = rtld_verify_versions(&obj->dagmembers);
3705 if (result != -1 && ld_tracing)
3707 if (result == -1 || relocate_object_dag(obj,
3708 (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld,
3709 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3711 dlopen_cleanup(obj, lockstate);
3713 } else if (lo_flags & RTLD_LO_EARLY) {
3715 * Do not call the init functions for early loaded
3716 * filtees. The image is still not initialized enough
3719 * Our object is found by the global object list and
3720 * will be ordered among all init calls done right
3721 * before transferring control to main.
3724 /* Make list of init functions to call. */
3725 initlist_add_objects(obj, obj, &initlist);
3728 * Process all no_delete or global objects here, given
3729 * them own DAGs to prevent their dependencies from being
3730 * unloaded. This has to be done after we have loaded all
3731 * of the dependencies, so that we do not miss any.
3737 * Bump the reference counts for objects on this DAG. If
3738 * this is the first dlopen() call for the object that was
3739 * already loaded as a dependency, initialize the dag
3745 if ((lo_flags & RTLD_LO_TRACE) != 0)
3748 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
3749 obj->z_nodelete) && !obj->ref_nodel) {
3750 dbg("obj %s nodelete", obj->path);
3752 obj->z_nodelete = obj->ref_nodel = true;
3756 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
3758 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
3760 if ((lo_flags & RTLD_LO_EARLY) == 0) {
3761 map_stacks_exec(lockstate);
3763 distribute_static_tls(&initlist, lockstate);
3766 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
3767 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3769 objlist_clear(&initlist);
3770 dlopen_cleanup(obj, lockstate);
3771 if (lockstate == &mlockstate)
3772 lock_release(rtld_bind_lock, lockstate);
3776 if (!(lo_flags & RTLD_LO_EARLY)) {
3777 /* Call the init functions. */
3778 objlist_call_init(&initlist, lockstate);
3780 objlist_clear(&initlist);
3781 if (lockstate == &mlockstate)
3782 lock_release(rtld_bind_lock, lockstate);
3785 trace_loaded_objects(obj);
3786 if (lockstate == &mlockstate)
3787 lock_release(rtld_bind_lock, lockstate);
3792 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
3796 const Obj_Entry *obj, *defobj;
3799 RtldLockState lockstate;
3806 symlook_init(&req, name);
3808 req.flags = flags | SYMLOOK_IN_PLT;
3809 req.lockstate = &lockstate;
3811 LD_UTRACE(UTRACE_DLSYM_START, handle, NULL, 0, 0, name);
3812 rlock_acquire(rtld_bind_lock, &lockstate);
3813 if (sigsetjmp(lockstate.env, 0) != 0)
3814 lock_upgrade(rtld_bind_lock, &lockstate);
3815 if (handle == NULL || handle == RTLD_NEXT ||
3816 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
3818 if ((obj = obj_from_addr(retaddr)) == NULL) {
3819 _rtld_error("Cannot determine caller's shared object");
3820 lock_release(rtld_bind_lock, &lockstate);
3821 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3824 if (handle == NULL) { /* Just the caller's shared object. */
3825 res = symlook_obj(&req, obj);
3828 defobj = req.defobj_out;
3830 } else if (handle == RTLD_NEXT || /* Objects after caller's */
3831 handle == RTLD_SELF) { /* ... caller included */
3832 if (handle == RTLD_NEXT)
3833 obj = globallist_next(obj);
3834 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
3837 res = symlook_obj(&req, obj);
3839 if (def == NULL || (ld_dynamic_weak &&
3840 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK)) {
3842 defobj = req.defobj_out;
3843 if (!ld_dynamic_weak ||
3844 ELF_ST_BIND(def->st_info) != STB_WEAK)
3850 * Search the dynamic linker itself, and possibly resolve the
3851 * symbol from there. This is how the application links to
3852 * dynamic linker services such as dlopen.
3853 * Note that we ignore ld_dynamic_weak == false case,
3854 * always overriding weak symbols by rtld definitions.
3856 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3857 res = symlook_obj(&req, &obj_rtld);
3860 defobj = req.defobj_out;
3864 assert(handle == RTLD_DEFAULT);
3865 res = symlook_default(&req, obj);
3867 defobj = req.defobj_out;
3872 if ((obj = dlcheck(handle)) == NULL) {
3873 lock_release(rtld_bind_lock, &lockstate);
3874 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3878 donelist_init(&donelist);
3879 if (obj->mainprog) {
3880 /* Handle obtained by dlopen(NULL, ...) implies global scope. */
3881 res = symlook_global(&req, &donelist);
3884 defobj = req.defobj_out;
3887 * Search the dynamic linker itself, and possibly resolve the
3888 * symbol from there. This is how the application links to
3889 * dynamic linker services such as dlopen.
3891 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3892 res = symlook_obj(&req, &obj_rtld);
3895 defobj = req.defobj_out;
3900 /* Search the whole DAG rooted at the given object. */
3901 res = symlook_list(&req, &obj->dagmembers, &donelist);
3904 defobj = req.defobj_out;
3910 lock_release(rtld_bind_lock, &lockstate);
3913 * The value required by the caller is derived from the value
3914 * of the symbol. this is simply the relocated value of the
3917 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
3918 sym = make_function_pointer(def, defobj);
3919 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
3920 sym = rtld_resolve_ifunc(defobj, def);
3921 else if (ELF_ST_TYPE(def->st_info) == STT_TLS) {
3922 ti.ti_module = defobj->tlsindex;
3923 ti.ti_offset = def->st_value;
3924 sym = __tls_get_addr(&ti);
3926 sym = defobj->relocbase + def->st_value;
3927 LD_UTRACE(UTRACE_DLSYM_STOP, handle, sym, 0, 0, name);
3931 _rtld_error("Undefined symbol \"%s%s%s\"", name, ve != NULL ? "@" : "",
3932 ve != NULL ? ve->name : "");
3933 lock_release(rtld_bind_lock, &lockstate);
3934 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3939 dlsym(void *handle, const char *name)
3941 return (do_dlsym(handle, name, __builtin_return_address(0), NULL,
3946 dlfunc(void *handle, const char *name)
3953 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
3959 dlvsym(void *handle, const char *name, const char *version)
3963 ventry.name = version;
3965 ventry.hash = elf_hash(version);
3967 return (do_dlsym(handle, name, __builtin_return_address(0), &ventry,
3972 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
3974 const Obj_Entry *obj;
3975 RtldLockState lockstate;
3977 rlock_acquire(rtld_bind_lock, &lockstate);
3978 obj = obj_from_addr(addr);
3980 _rtld_error("No shared object contains address");
3981 lock_release(rtld_bind_lock, &lockstate);
3984 rtld_fill_dl_phdr_info(obj, phdr_info);
3985 lock_release(rtld_bind_lock, &lockstate);
3990 dladdr(const void *addr, Dl_info *info)
3992 const Obj_Entry *obj;
3995 unsigned long symoffset;
3996 RtldLockState lockstate;
3998 rlock_acquire(rtld_bind_lock, &lockstate);
3999 obj = obj_from_addr(addr);
4001 _rtld_error("No shared object contains address");
4002 lock_release(rtld_bind_lock, &lockstate);
4005 info->dli_fname = obj->path;
4006 info->dli_fbase = obj->mapbase;
4007 info->dli_saddr = (void *)0;
4008 info->dli_sname = NULL;
4011 * Walk the symbol list looking for the symbol whose address is
4012 * closest to the address sent in.
4014 for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) {
4015 def = obj->symtab + symoffset;
4018 * For skip the symbol if st_shndx is either SHN_UNDEF or
4021 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
4025 * If the symbol is greater than the specified address, or if it
4026 * is further away from addr than the current nearest symbol,
4029 symbol_addr = obj->relocbase + def->st_value;
4030 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
4033 /* Update our idea of the nearest symbol. */
4034 info->dli_sname = obj->strtab + def->st_name;
4035 info->dli_saddr = symbol_addr;
4038 if (info->dli_saddr == addr)
4041 lock_release(rtld_bind_lock, &lockstate);
4046 dlinfo(void *handle, int request, void *p)
4048 const Obj_Entry *obj;
4049 RtldLockState lockstate;
4052 rlock_acquire(rtld_bind_lock, &lockstate);
4054 if (handle == NULL || handle == RTLD_SELF) {
4057 retaddr = __builtin_return_address(0); /* __GNUC__ only */
4058 if ((obj = obj_from_addr(retaddr)) == NULL)
4059 _rtld_error("Cannot determine caller's shared object");
4061 obj = dlcheck(handle);
4064 lock_release(rtld_bind_lock, &lockstate);
4070 case RTLD_DI_LINKMAP:
4071 *((struct link_map const **)p) = &obj->linkmap;
4073 case RTLD_DI_ORIGIN:
4074 error = rtld_dirname(obj->path, p);
4077 case RTLD_DI_SERINFOSIZE:
4078 case RTLD_DI_SERINFO:
4079 error = do_search_info(obj, request, (struct dl_serinfo *)p);
4083 _rtld_error("Invalid request %d passed to dlinfo()", request);
4087 lock_release(rtld_bind_lock, &lockstate);
4093 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
4097 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
4098 phdr_info->dlpi_name = obj->path;
4099 phdr_info->dlpi_phdr = obj->phdr;
4100 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
4101 phdr_info->dlpi_tls_modid = obj->tlsindex;
4103 phdr_info->dlpi_tls_data = (char *)tls_get_addr_slow(dtvp,
4104 obj->tlsindex, 0, true) + TLS_DTV_OFFSET;
4105 phdr_info->dlpi_adds = obj_loads;
4106 phdr_info->dlpi_subs = obj_loads - obj_count;
4110 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
4112 struct dl_phdr_info phdr_info;
4113 Obj_Entry *obj, marker;
4114 RtldLockState bind_lockstate, phdr_lockstate;
4117 init_marker(&marker);
4120 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
4121 wlock_acquire(rtld_bind_lock, &bind_lockstate);
4122 for (obj = globallist_curr(TAILQ_FIRST(&obj_list)); obj != NULL;) {
4123 TAILQ_INSERT_AFTER(&obj_list, obj, &marker, next);
4124 rtld_fill_dl_phdr_info(obj, &phdr_info);
4126 lock_release(rtld_bind_lock, &bind_lockstate);
4128 error = callback(&phdr_info, sizeof phdr_info, param);
4130 wlock_acquire(rtld_bind_lock, &bind_lockstate);
4132 obj = globallist_next(&marker);
4133 TAILQ_REMOVE(&obj_list, &marker, next);
4135 lock_release(rtld_bind_lock, &bind_lockstate);
4136 lock_release(rtld_phdr_lock, &phdr_lockstate);
4142 rtld_fill_dl_phdr_info(&obj_rtld, &phdr_info);
4143 lock_release(rtld_bind_lock, &bind_lockstate);
4144 error = callback(&phdr_info, sizeof(phdr_info), param);
4146 lock_release(rtld_phdr_lock, &phdr_lockstate);
4151 fill_search_info(const char *dir, size_t dirlen, void *param)
4153 struct fill_search_info_args *arg;
4157 if (arg->request == RTLD_DI_SERINFOSIZE) {
4158 arg->serinfo->dls_cnt ++;
4159 arg->serinfo->dls_size += sizeof(struct dl_serpath) + dirlen + 1;
4161 struct dl_serpath *s_entry;
4163 s_entry = arg->serpath;
4164 s_entry->dls_name = arg->strspace;
4165 s_entry->dls_flags = arg->flags;
4167 strncpy(arg->strspace, dir, dirlen);
4168 arg->strspace[dirlen] = '\0';
4170 arg->strspace += dirlen + 1;
4178 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
4180 struct dl_serinfo _info;
4181 struct fill_search_info_args args;
4183 args.request = RTLD_DI_SERINFOSIZE;
4184 args.serinfo = &_info;
4186 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
4189 path_enumerate(obj->rpath, fill_search_info, NULL, &args);
4190 path_enumerate(ld_library_path, fill_search_info, NULL, &args);
4191 path_enumerate(obj->runpath, fill_search_info, NULL, &args);
4192 path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args);
4193 if (!obj->z_nodeflib)
4194 path_enumerate(ld_standard_library_path, fill_search_info, NULL, &args);
4197 if (request == RTLD_DI_SERINFOSIZE) {
4198 info->dls_size = _info.dls_size;
4199 info->dls_cnt = _info.dls_cnt;
4203 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
4204 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
4208 args.request = RTLD_DI_SERINFO;
4209 args.serinfo = info;
4210 args.serpath = &info->dls_serpath[0];
4211 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
4213 args.flags = LA_SER_RUNPATH;
4214 if (path_enumerate(obj->rpath, fill_search_info, NULL, &args) != NULL)
4217 args.flags = LA_SER_LIBPATH;
4218 if (path_enumerate(ld_library_path, fill_search_info, NULL, &args) != NULL)
4221 args.flags = LA_SER_RUNPATH;
4222 if (path_enumerate(obj->runpath, fill_search_info, NULL, &args) != NULL)
4225 args.flags = LA_SER_CONFIG;
4226 if (path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args)
4230 args.flags = LA_SER_DEFAULT;
4231 if (!obj->z_nodeflib && path_enumerate(ld_standard_library_path,
4232 fill_search_info, NULL, &args) != NULL)
4238 rtld_dirname(const char *path, char *bname)
4242 /* Empty or NULL string gets treated as "." */
4243 if (path == NULL || *path == '\0') {
4249 /* Strip trailing slashes */
4250 endp = path + strlen(path) - 1;
4251 while (endp > path && *endp == '/')
4254 /* Find the start of the dir */
4255 while (endp > path && *endp != '/')
4258 /* Either the dir is "/" or there are no slashes */
4260 bname[0] = *endp == '/' ? '/' : '.';
4266 } while (endp > path && *endp == '/');
4269 if (endp - path + 2 > PATH_MAX)
4271 _rtld_error("Filename is too long: %s", path);
4275 strncpy(bname, path, endp - path + 1);
4276 bname[endp - path + 1] = '\0';
4281 rtld_dirname_abs(const char *path, char *base)
4285 if (realpath(path, base) == NULL) {
4286 _rtld_error("realpath \"%s\" failed (%s)", path,
4287 rtld_strerror(errno));
4290 dbg("%s -> %s", path, base);
4291 last = strrchr(base, '/');
4293 _rtld_error("non-abs result from realpath \"%s\"", path);
4302 linkmap_add(Obj_Entry *obj)
4304 struct link_map *l, *prev;
4307 l->l_name = obj->path;
4308 l->l_base = obj->mapbase;
4309 l->l_ld = obj->dynamic;
4310 l->l_addr = obj->relocbase;
4312 if (r_debug.r_map == NULL) {
4318 * Scan to the end of the list, but not past the entry for the
4319 * dynamic linker, which we want to keep at the very end.
4321 for (prev = r_debug.r_map;
4322 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
4323 prev = prev->l_next)
4326 /* Link in the new entry. */
4328 l->l_next = prev->l_next;
4329 if (l->l_next != NULL)
4330 l->l_next->l_prev = l;
4335 linkmap_delete(Obj_Entry *obj)
4340 if (l->l_prev == NULL) {
4341 if ((r_debug.r_map = l->l_next) != NULL)
4342 l->l_next->l_prev = NULL;
4346 if ((l->l_prev->l_next = l->l_next) != NULL)
4347 l->l_next->l_prev = l->l_prev;
4351 * Function for the debugger to set a breakpoint on to gain control.
4353 * The two parameters allow the debugger to easily find and determine
4354 * what the runtime loader is doing and to whom it is doing it.
4356 * When the loadhook trap is hit (r_debug_state, set at program
4357 * initialization), the arguments can be found on the stack:
4359 * +8 struct link_map *m
4360 * +4 struct r_debug *rd
4364 r_debug_state(struct r_debug* rd __unused, struct link_map *m __unused)
4367 * The following is a hack to force the compiler to emit calls to
4368 * this function, even when optimizing. If the function is empty,
4369 * the compiler is not obliged to emit any code for calls to it,
4370 * even when marked __noinline. However, gdb depends on those
4373 __compiler_membar();
4377 * A function called after init routines have completed. This can be used to
4378 * break before a program's entry routine is called, and can be used when
4379 * main is not available in the symbol table.
4382 _r_debug_postinit(struct link_map *m __unused)
4385 /* See r_debug_state(). */
4386 __compiler_membar();
4390 release_object(Obj_Entry *obj)
4393 if (obj->holdcount > 0) {
4394 obj->unholdfree = true;
4397 munmap(obj->mapbase, obj->mapsize);
4398 linkmap_delete(obj);
4403 * Get address of the pointer variable in the main program.
4404 * Prefer non-weak symbol over the weak one.
4406 static const void **
4407 get_program_var_addr(const char *name, RtldLockState *lockstate)
4412 symlook_init(&req, name);
4413 req.lockstate = lockstate;
4414 donelist_init(&donelist);
4415 if (symlook_global(&req, &donelist) != 0)
4417 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
4418 return ((const void **)make_function_pointer(req.sym_out,
4420 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
4421 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
4423 return ((const void **)(req.defobj_out->relocbase +
4424 req.sym_out->st_value));
4428 * Set a pointer variable in the main program to the given value. This
4429 * is used to set key variables such as "environ" before any of the
4430 * init functions are called.
4433 set_program_var(const char *name, const void *value)
4437 if ((addr = get_program_var_addr(name, NULL)) != NULL) {
4438 dbg("\"%s\": *%p <-- %p", name, addr, value);
4444 * Search the global objects, including dependencies and main object,
4445 * for the given symbol.
4448 symlook_global(SymLook *req, DoneList *donelist)
4451 const Objlist_Entry *elm;
4454 symlook_init_from_req(&req1, req);
4456 /* Search all objects loaded at program start up. */
4457 if (req->defobj_out == NULL || (ld_dynamic_weak &&
4458 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK)) {
4459 res = symlook_list(&req1, &list_main, donelist);
4460 if (res == 0 && (!ld_dynamic_weak || req->defobj_out == NULL ||
4461 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4462 req->sym_out = req1.sym_out;
4463 req->defobj_out = req1.defobj_out;
4464 assert(req->defobj_out != NULL);
4468 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
4469 STAILQ_FOREACH(elm, &list_global, link) {
4470 if (req->defobj_out != NULL && (!ld_dynamic_weak ||
4471 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK))
4473 res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
4474 if (res == 0 && (req->defobj_out == NULL ||
4475 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4476 req->sym_out = req1.sym_out;
4477 req->defobj_out = req1.defobj_out;
4478 assert(req->defobj_out != NULL);
4482 return (req->sym_out != NULL ? 0 : ESRCH);
4486 * Given a symbol name in a referencing object, find the corresponding
4487 * definition of the symbol. Returns a pointer to the symbol, or NULL if
4488 * no definition was found. Returns a pointer to the Obj_Entry of the
4489 * defining object via the reference parameter DEFOBJ_OUT.
4492 symlook_default(SymLook *req, const Obj_Entry *refobj)
4495 const Objlist_Entry *elm;
4499 donelist_init(&donelist);
4500 symlook_init_from_req(&req1, req);
4503 * Look first in the referencing object if linked symbolically,
4504 * and similarly handle protected symbols.
4506 res = symlook_obj(&req1, refobj);
4507 if (res == 0 && (refobj->symbolic ||
4508 ELF_ST_VISIBILITY(req1.sym_out->st_other) == STV_PROTECTED)) {
4509 req->sym_out = req1.sym_out;
4510 req->defobj_out = req1.defobj_out;
4511 assert(req->defobj_out != NULL);
4513 if (refobj->symbolic || req->defobj_out != NULL)
4514 donelist_check(&donelist, refobj);
4516 symlook_global(req, &donelist);
4518 /* Search all dlopened DAGs containing the referencing object. */
4519 STAILQ_FOREACH(elm, &refobj->dldags, link) {
4520 if (req->sym_out != NULL && (!ld_dynamic_weak ||
4521 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK))
4523 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
4524 if (res == 0 && (req->sym_out == NULL ||
4525 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4526 req->sym_out = req1.sym_out;
4527 req->defobj_out = req1.defobj_out;
4528 assert(req->defobj_out != NULL);
4533 * Search the dynamic linker itself, and possibly resolve the
4534 * symbol from there. This is how the application links to
4535 * dynamic linker services such as dlopen.
4537 if (req->sym_out == NULL ||
4538 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
4539 res = symlook_obj(&req1, &obj_rtld);
4541 req->sym_out = req1.sym_out;
4542 req->defobj_out = req1.defobj_out;
4543 assert(req->defobj_out != NULL);
4547 return (req->sym_out != NULL ? 0 : ESRCH);
4551 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
4554 const Obj_Entry *defobj;
4555 const Objlist_Entry *elm;
4561 STAILQ_FOREACH(elm, objlist, link) {
4562 if (donelist_check(dlp, elm->obj))
4564 symlook_init_from_req(&req1, req);
4565 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
4566 if (def == NULL || (ld_dynamic_weak &&
4567 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4569 defobj = req1.defobj_out;
4570 if (!ld_dynamic_weak || ELF_ST_BIND(def->st_info) != STB_WEAK)
4577 req->defobj_out = defobj;
4584 * Search the chain of DAGS cointed to by the given Needed_Entry
4585 * for a symbol of the given name. Each DAG is scanned completely
4586 * before advancing to the next one. Returns a pointer to the symbol,
4587 * or NULL if no definition was found.
4590 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
4593 const Needed_Entry *n;
4594 const Obj_Entry *defobj;
4600 symlook_init_from_req(&req1, req);
4601 for (n = needed; n != NULL; n = n->next) {
4602 if (n->obj == NULL ||
4603 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
4605 if (def == NULL || (ld_dynamic_weak &&
4606 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4608 defobj = req1.defobj_out;
4609 if (!ld_dynamic_weak || ELF_ST_BIND(def->st_info) != STB_WEAK)
4615 req->defobj_out = defobj;
4622 * Search the symbol table of a single shared object for a symbol of
4623 * the given name and version, if requested. Returns a pointer to the
4624 * symbol, or NULL if no definition was found. If the object is
4625 * filter, return filtered symbol from filtee.
4627 * The symbol's hash value is passed in for efficiency reasons; that
4628 * eliminates many recomputations of the hash value.
4631 symlook_obj(SymLook *req, const Obj_Entry *obj)
4635 int flags, res, mres;
4638 * If there is at least one valid hash at this point, we prefer to
4639 * use the faster GNU version if available.
4641 if (obj->valid_hash_gnu)
4642 mres = symlook_obj1_gnu(req, obj);
4643 else if (obj->valid_hash_sysv)
4644 mres = symlook_obj1_sysv(req, obj);
4649 if (obj->needed_filtees != NULL) {
4650 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4651 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4652 donelist_init(&donelist);
4653 symlook_init_from_req(&req1, req);
4654 res = symlook_needed(&req1, obj->needed_filtees, &donelist);
4656 req->sym_out = req1.sym_out;
4657 req->defobj_out = req1.defobj_out;
4661 if (obj->needed_aux_filtees != NULL) {
4662 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4663 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4664 donelist_init(&donelist);
4665 symlook_init_from_req(&req1, req);
4666 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
4668 req->sym_out = req1.sym_out;
4669 req->defobj_out = req1.defobj_out;
4677 /* Symbol match routine common to both hash functions */
4679 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result,
4680 const unsigned long symnum)
4683 const Elf_Sym *symp;
4686 symp = obj->symtab + symnum;
4687 strp = obj->strtab + symp->st_name;
4689 switch (ELF_ST_TYPE(symp->st_info)) {
4695 if (symp->st_value == 0)
4699 if (symp->st_shndx != SHN_UNDEF)
4702 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
4703 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
4710 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
4713 if (req->ventry == NULL) {
4714 if (obj->versyms != NULL) {
4715 verndx = VER_NDX(obj->versyms[symnum]);
4716 if (verndx > obj->vernum) {
4718 "%s: symbol %s references wrong version %d",
4719 obj->path, obj->strtab + symnum, verndx);
4723 * If we are not called from dlsym (i.e. this
4724 * is a normal relocation from unversioned
4725 * binary), accept the symbol immediately if
4726 * it happens to have first version after this
4727 * shared object became versioned. Otherwise,
4728 * if symbol is versioned and not hidden,
4729 * remember it. If it is the only symbol with
4730 * this name exported by the shared object, it
4731 * will be returned as a match by the calling
4732 * function. If symbol is global (verndx < 2)
4733 * accept it unconditionally.
4735 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
4736 verndx == VER_NDX_GIVEN) {
4737 result->sym_out = symp;
4740 else if (verndx >= VER_NDX_GIVEN) {
4741 if ((obj->versyms[symnum] & VER_NDX_HIDDEN)
4743 if (result->vsymp == NULL)
4744 result->vsymp = symp;
4750 result->sym_out = symp;
4753 if (obj->versyms == NULL) {
4754 if (object_match_name(obj, req->ventry->name)) {
4755 _rtld_error("%s: object %s should provide version %s "
4756 "for symbol %s", obj_rtld.path, obj->path,
4757 req->ventry->name, obj->strtab + symnum);
4761 verndx = VER_NDX(obj->versyms[symnum]);
4762 if (verndx > obj->vernum) {
4763 _rtld_error("%s: symbol %s references wrong version %d",
4764 obj->path, obj->strtab + symnum, verndx);
4767 if (obj->vertab[verndx].hash != req->ventry->hash ||
4768 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
4770 * Version does not match. Look if this is a
4771 * global symbol and if it is not hidden. If
4772 * global symbol (verndx < 2) is available,
4773 * use it. Do not return symbol if we are
4774 * called by dlvsym, because dlvsym looks for
4775 * a specific version and default one is not
4776 * what dlvsym wants.
4778 if ((req->flags & SYMLOOK_DLSYM) ||
4779 (verndx >= VER_NDX_GIVEN) ||
4780 (obj->versyms[symnum] & VER_NDX_HIDDEN))
4784 result->sym_out = symp;
4789 * Search for symbol using SysV hash function.
4790 * obj->buckets is known not to be NULL at this point; the test for this was
4791 * performed with the obj->valid_hash_sysv assignment.
4794 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj)
4796 unsigned long symnum;
4797 Sym_Match_Result matchres;
4799 matchres.sym_out = NULL;
4800 matchres.vsymp = NULL;
4801 matchres.vcount = 0;
4803 for (symnum = obj->buckets[req->hash % obj->nbuckets];
4804 symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
4805 if (symnum >= obj->nchains)
4806 return (ESRCH); /* Bad object */
4808 if (matched_symbol(req, obj, &matchres, symnum)) {
4809 req->sym_out = matchres.sym_out;
4810 req->defobj_out = obj;
4814 if (matchres.vcount == 1) {
4815 req->sym_out = matchres.vsymp;
4816 req->defobj_out = obj;
4822 /* Search for symbol using GNU hash function */
4824 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj)
4826 Elf_Addr bloom_word;
4827 const Elf32_Word *hashval;
4829 Sym_Match_Result matchres;
4830 unsigned int h1, h2;
4831 unsigned long symnum;
4833 matchres.sym_out = NULL;
4834 matchres.vsymp = NULL;
4835 matchres.vcount = 0;
4837 /* Pick right bitmask word from Bloom filter array */
4838 bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) &
4839 obj->maskwords_bm_gnu];
4841 /* Calculate modulus word size of gnu hash and its derivative */
4842 h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1);
4843 h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1));
4845 /* Filter out the "definitely not in set" queries */
4846 if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0)
4849 /* Locate hash chain and corresponding value element*/
4850 bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu];
4853 hashval = &obj->chain_zero_gnu[bucket];
4855 if (((*hashval ^ req->hash_gnu) >> 1) == 0) {
4856 symnum = hashval - obj->chain_zero_gnu;
4857 if (matched_symbol(req, obj, &matchres, symnum)) {
4858 req->sym_out = matchres.sym_out;
4859 req->defobj_out = obj;
4863 } while ((*hashval++ & 1) == 0);
4864 if (matchres.vcount == 1) {
4865 req->sym_out = matchres.vsymp;
4866 req->defobj_out = obj;
4873 trace_loaded_objects(Obj_Entry *obj)
4875 const char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
4878 if ((main_local = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_PROGNAME)) ==
4882 if ((fmt1 = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_FMT1)) == NULL)
4883 fmt1 = "\t%o => %p (%x)\n";
4885 if ((fmt2 = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_FMT2)) == NULL)
4886 fmt2 = "\t%o (%x)\n";
4888 list_containers = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_ALL);
4890 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
4891 Needed_Entry *needed;
4892 const char *name, *path;
4897 if (list_containers && obj->needed != NULL)
4898 rtld_printf("%s:\n", obj->path);
4899 for (needed = obj->needed; needed; needed = needed->next) {
4900 if (needed->obj != NULL) {
4901 if (needed->obj->traced && !list_containers)
4903 needed->obj->traced = true;
4904 path = needed->obj->path;
4908 name = obj->strtab + needed->name;
4909 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
4911 fmt = is_lib ? fmt1 : fmt2;
4912 while ((c = *fmt++) != '\0') {
4938 rtld_putstr(main_local);
4941 rtld_putstr(obj_main->path);
4948 rtld_printf("%d", sodp->sod_major);
4951 rtld_printf("%d", sodp->sod_minor);
4958 rtld_printf("%p", needed->obj ? needed->obj->mapbase :
4971 * Unload a dlopened object and its dependencies from memory and from
4972 * our data structures. It is assumed that the DAG rooted in the
4973 * object has already been unreferenced, and that the object has a
4974 * reference count of 0.
4977 unload_object(Obj_Entry *root, RtldLockState *lockstate)
4979 Obj_Entry marker, *obj, *next;
4981 assert(root->refcount == 0);
4984 * Pass over the DAG removing unreferenced objects from
4985 * appropriate lists.
4987 unlink_object(root);
4989 /* Unmap all objects that are no longer referenced. */
4990 for (obj = TAILQ_FIRST(&obj_list); obj != NULL; obj = next) {
4991 next = TAILQ_NEXT(obj, next);
4992 if (obj->marker || obj->refcount != 0)
4994 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase,
4995 obj->mapsize, 0, obj->path);
4996 dbg("unloading \"%s\"", obj->path);
4998 * Unlink the object now to prevent new references from
4999 * being acquired while the bind lock is dropped in
5000 * recursive dlclose() invocations.
5002 TAILQ_REMOVE(&obj_list, obj, next);
5005 if (obj->filtees_loaded) {
5007 init_marker(&marker);
5008 TAILQ_INSERT_BEFORE(next, &marker, next);
5009 unload_filtees(obj, lockstate);
5010 next = TAILQ_NEXT(&marker, next);
5011 TAILQ_REMOVE(&obj_list, &marker, next);
5013 unload_filtees(obj, lockstate);
5015 release_object(obj);
5020 unlink_object(Obj_Entry *root)
5024 if (root->refcount == 0) {
5025 /* Remove the object from the RTLD_GLOBAL list. */
5026 objlist_remove(&list_global, root);
5028 /* Remove the object from all objects' DAG lists. */
5029 STAILQ_FOREACH(elm, &root->dagmembers, link) {
5030 objlist_remove(&elm->obj->dldags, root);
5031 if (elm->obj != root)
5032 unlink_object(elm->obj);
5038 ref_dag(Obj_Entry *root)
5042 assert(root->dag_inited);
5043 STAILQ_FOREACH(elm, &root->dagmembers, link)
5044 elm->obj->refcount++;
5048 unref_dag(Obj_Entry *root)
5052 assert(root->dag_inited);
5053 STAILQ_FOREACH(elm, &root->dagmembers, link)
5054 elm->obj->refcount--;
5058 * Common code for MD __tls_get_addr().
5061 tls_get_addr_slow(Elf_Addr **dtvp, int index, size_t offset, bool locked)
5063 Elf_Addr *newdtv, *dtv;
5064 RtldLockState lockstate;
5068 /* Check dtv generation in case new modules have arrived */
5069 if (dtv[0] != tls_dtv_generation) {
5071 wlock_acquire(rtld_bind_lock, &lockstate);
5072 newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
5074 if (to_copy > tls_max_index)
5075 to_copy = tls_max_index;
5076 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
5077 newdtv[0] = tls_dtv_generation;
5078 newdtv[1] = tls_max_index;
5081 lock_release(rtld_bind_lock, &lockstate);
5082 dtv = *dtvp = newdtv;
5085 /* Dynamically allocate module TLS if necessary */
5086 if (dtv[index + 1] == 0) {
5087 /* Signal safe, wlock will block out signals. */
5089 wlock_acquire(rtld_bind_lock, &lockstate);
5090 if (!dtv[index + 1])
5091 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
5093 lock_release(rtld_bind_lock, &lockstate);
5095 return ((void *)(dtv[index + 1] + offset));
5099 tls_get_addr_common(Elf_Addr **dtvp, int index, size_t offset)
5104 /* Check dtv generation in case new modules have arrived */
5105 if (__predict_true(dtv[0] == tls_dtv_generation &&
5106 dtv[index + 1] != 0))
5107 return ((void *)(dtv[index + 1] + offset));
5108 return (tls_get_addr_slow(dtvp, index, offset, false));
5111 #ifdef TLS_VARIANT_I
5114 * Return pointer to allocated TLS block
5117 get_tls_block_ptr(void *tcb, size_t tcbsize)
5119 size_t extra_size, post_size, pre_size, tls_block_size;
5120 size_t tls_init_align;
5122 tls_init_align = MAX(obj_main->tlsalign, 1);
5124 /* Compute fragments sizes. */
5125 extra_size = tcbsize - TLS_TCB_SIZE;
5126 post_size = calculate_tls_post_size(tls_init_align);
5127 tls_block_size = tcbsize + post_size;
5128 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size;
5130 return ((char *)tcb - pre_size - extra_size);
5134 * Allocate Static TLS using the Variant I method.
5136 * For details on the layout, see lib/libc/gen/tls.c.
5138 * NB: rtld's tls_static_space variable includes TLS_TCB_SIZE and post_size as
5139 * it is based on tls_last_offset, and TLS offsets here are really TCB
5140 * offsets, whereas libc's tls_static_space is just the executable's static
5144 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
5148 Elf_Addr *dtv, **tcb;
5151 size_t extra_size, maxalign, post_size, pre_size, tls_block_size;
5152 size_t tls_init_align, tls_init_offset;
5154 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
5157 assert(tcbsize >= TLS_TCB_SIZE);
5158 maxalign = MAX(tcbalign, tls_static_max_align);
5159 tls_init_align = MAX(obj_main->tlsalign, 1);
5161 /* Compute fragmets sizes. */
5162 extra_size = tcbsize - TLS_TCB_SIZE;
5163 post_size = calculate_tls_post_size(tls_init_align);
5164 tls_block_size = tcbsize + post_size;
5165 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size;
5166 tls_block_size += pre_size + tls_static_space - TLS_TCB_SIZE - post_size;
5168 /* Allocate whole TLS block */
5169 tls_block = malloc_aligned(tls_block_size, maxalign, 0);
5170 tcb = (Elf_Addr **)(tls_block + pre_size + extra_size);
5172 if (oldtcb != NULL) {
5173 memcpy(tls_block, get_tls_block_ptr(oldtcb, tcbsize),
5175 free_aligned(get_tls_block_ptr(oldtcb, tcbsize));
5177 /* Adjust the DTV. */
5179 for (i = 0; i < dtv[1]; i++) {
5180 if (dtv[i+2] >= (Elf_Addr)oldtcb &&
5181 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
5182 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tcb;
5186 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
5188 dtv[0] = tls_dtv_generation;
5189 dtv[1] = tls_max_index;
5191 for (obj = globallist_curr(objs); obj != NULL;
5192 obj = globallist_next(obj)) {
5193 if (obj->tlsoffset == 0)
5195 tls_init_offset = obj->tlspoffset & (obj->tlsalign - 1);
5196 addr = (Elf_Addr)tcb + obj->tlsoffset;
5197 if (tls_init_offset > 0)
5198 memset((void *)addr, 0, tls_init_offset);
5199 if (obj->tlsinitsize > 0) {
5200 memcpy((void *)(addr + tls_init_offset), obj->tlsinit,
5203 if (obj->tlssize > obj->tlsinitsize) {
5204 memset((void *)(addr + tls_init_offset + obj->tlsinitsize),
5205 0, obj->tlssize - obj->tlsinitsize - tls_init_offset);
5207 dtv[obj->tlsindex + 1] = addr;
5215 free_tls(void *tcb, size_t tcbsize, size_t tcbalign __unused)
5218 Elf_Addr tlsstart, tlsend;
5220 size_t dtvsize, i, tls_init_align;
5222 assert(tcbsize >= TLS_TCB_SIZE);
5223 tls_init_align = MAX(obj_main->tlsalign, 1);
5225 /* Compute fragments sizes. */
5226 post_size = calculate_tls_post_size(tls_init_align);
5228 tlsstart = (Elf_Addr)tcb + TLS_TCB_SIZE + post_size;
5229 tlsend = (Elf_Addr)tcb + tls_static_space;
5231 dtv = *(Elf_Addr **)tcb;
5233 for (i = 0; i < dtvsize; i++) {
5234 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
5235 free((void*)dtv[i+2]);
5239 free_aligned(get_tls_block_ptr(tcb, tcbsize));
5242 #endif /* TLS_VARIANT_I */
5244 #ifdef TLS_VARIANT_II
5247 * Allocate Static TLS using the Variant II method.
5250 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
5253 size_t size, ralign;
5255 Elf_Addr *dtv, *olddtv;
5256 Elf_Addr segbase, oldsegbase, addr;
5260 if (tls_static_max_align > ralign)
5261 ralign = tls_static_max_align;
5262 size = roundup(tls_static_space, ralign) + roundup(tcbsize, ralign);
5264 assert(tcbsize >= 2*sizeof(Elf_Addr));
5265 tls = malloc_aligned(size, ralign, 0 /* XXX */);
5266 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
5268 segbase = (Elf_Addr)(tls + roundup(tls_static_space, ralign));
5269 ((Elf_Addr *)segbase)[0] = segbase;
5270 ((Elf_Addr *)segbase)[1] = (Elf_Addr) dtv;
5272 dtv[0] = tls_dtv_generation;
5273 dtv[1] = tls_max_index;
5277 * Copy the static TLS block over whole.
5279 oldsegbase = (Elf_Addr) oldtls;
5280 memcpy((void *)(segbase - tls_static_space),
5281 (const void *)(oldsegbase - tls_static_space),
5285 * If any dynamic TLS blocks have been created tls_get_addr(),
5288 olddtv = ((Elf_Addr **)oldsegbase)[1];
5289 for (i = 0; i < olddtv[1]; i++) {
5290 if (olddtv[i + 2] < oldsegbase - size ||
5291 olddtv[i + 2] > oldsegbase) {
5292 dtv[i + 2] = olddtv[i + 2];
5298 * We assume that this block was the one we created with
5299 * allocate_initial_tls().
5301 free_tls(oldtls, 2 * sizeof(Elf_Addr), sizeof(Elf_Addr));
5303 for (obj = objs; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
5304 if (obj->marker || obj->tlsoffset == 0)
5306 addr = segbase - obj->tlsoffset;
5307 memset((void *)(addr + obj->tlsinitsize),
5308 0, obj->tlssize - obj->tlsinitsize);
5310 memcpy((void *)addr, obj->tlsinit, obj->tlsinitsize);
5311 obj->static_tls_copied = true;
5313 dtv[obj->tlsindex + 1] = addr;
5317 return ((void *)segbase);
5321 free_tls(void *tls, size_t tcbsize __unused, size_t tcbalign)
5324 size_t size, ralign;
5326 Elf_Addr tlsstart, tlsend;
5329 * Figure out the size of the initial TLS block so that we can
5330 * find stuff which ___tls_get_addr() allocated dynamically.
5333 if (tls_static_max_align > ralign)
5334 ralign = tls_static_max_align;
5335 size = roundup(tls_static_space, ralign);
5337 dtv = ((Elf_Addr **)tls)[1];
5339 tlsend = (Elf_Addr)tls;
5340 tlsstart = tlsend - size;
5341 for (i = 0; i < dtvsize; i++) {
5342 if (dtv[i + 2] != 0 && (dtv[i + 2] < tlsstart ||
5343 dtv[i + 2] > tlsend)) {
5344 free_aligned((void *)dtv[i + 2]);
5348 free_aligned((void *)tlsstart);
5352 #endif /* TLS_VARIANT_II */
5355 * Allocate TLS block for module with given index.
5358 allocate_module_tls(int index)
5363 TAILQ_FOREACH(obj, &obj_list, next) {
5366 if (obj->tlsindex == index)
5370 _rtld_error("Can't find module with TLS index %d", index);
5374 p = malloc_aligned(obj->tlssize, obj->tlsalign, obj->tlspoffset);
5375 memcpy(p, obj->tlsinit, obj->tlsinitsize);
5376 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
5381 allocate_tls_offset(Obj_Entry *obj)
5388 if (obj->tlssize == 0) {
5389 obj->tls_done = true;
5393 if (tls_last_offset == 0)
5394 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign,
5397 off = calculate_tls_offset(tls_last_offset, tls_last_size,
5398 obj->tlssize, obj->tlsalign, obj->tlspoffset);
5400 obj->tlsoffset = off;
5401 #ifdef TLS_VARIANT_I
5402 off += obj->tlssize;
5406 * If we have already fixed the size of the static TLS block, we
5407 * must stay within that size. When allocating the static TLS, we
5408 * leave a small amount of space spare to be used for dynamically
5409 * loading modules which use static TLS.
5411 if (tls_static_space != 0) {
5412 if (off > tls_static_space)
5414 } else if (obj->tlsalign > tls_static_max_align) {
5415 tls_static_max_align = obj->tlsalign;
5418 tls_last_offset = off;
5419 tls_last_size = obj->tlssize;
5420 obj->tls_done = true;
5426 free_tls_offset(Obj_Entry *obj)
5430 * If we were the last thing to allocate out of the static TLS
5431 * block, we give our space back to the 'allocator'. This is a
5432 * simplistic workaround to allow libGL.so.1 to be loaded and
5433 * unloaded multiple times.
5435 size_t off = obj->tlsoffset;
5436 #ifdef TLS_VARIANT_I
5437 off += obj->tlssize;
5439 if (off == tls_last_offset) {
5440 tls_last_offset -= obj->tlssize;
5446 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
5449 RtldLockState lockstate;
5451 wlock_acquire(rtld_bind_lock, &lockstate);
5452 ret = allocate_tls(globallist_curr(TAILQ_FIRST(&obj_list)), oldtls,
5454 lock_release(rtld_bind_lock, &lockstate);
5459 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
5461 RtldLockState lockstate;
5463 wlock_acquire(rtld_bind_lock, &lockstate);
5464 free_tls(tcb, tcbsize, tcbalign);
5465 lock_release(rtld_bind_lock, &lockstate);
5469 object_add_name(Obj_Entry *obj, const char *name)
5475 entry = malloc(sizeof(Name_Entry) + len);
5477 if (entry != NULL) {
5478 strcpy(entry->name, name);
5479 STAILQ_INSERT_TAIL(&obj->names, entry, link);
5484 object_match_name(const Obj_Entry *obj, const char *name)
5488 STAILQ_FOREACH(entry, &obj->names, link) {
5489 if (strcmp(name, entry->name) == 0)
5496 locate_dependency(const Obj_Entry *obj, const char *name)
5498 const Objlist_Entry *entry;
5499 const Needed_Entry *needed;
5501 STAILQ_FOREACH(entry, &list_main, link) {
5502 if (object_match_name(entry->obj, name))
5503 return (entry->obj);
5506 for (needed = obj->needed; needed != NULL; needed = needed->next) {
5507 if (strcmp(obj->strtab + needed->name, name) == 0 ||
5508 (needed->obj != NULL && object_match_name(needed->obj, name))) {
5510 * If there is DT_NEEDED for the name we are looking for,
5511 * we are all set. Note that object might not be found if
5512 * dependency was not loaded yet, so the function can
5513 * return NULL here. This is expected and handled
5514 * properly by the caller.
5516 return (needed->obj);
5519 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
5525 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
5526 const Elf_Vernaux *vna)
5528 const Elf_Verdef *vd;
5529 const char *vername;
5531 vername = refobj->strtab + vna->vna_name;
5532 vd = depobj->verdef;
5534 _rtld_error("%s: version %s required by %s not defined",
5535 depobj->path, vername, refobj->path);
5539 if (vd->vd_version != VER_DEF_CURRENT) {
5540 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
5541 depobj->path, vd->vd_version);
5544 if (vna->vna_hash == vd->vd_hash) {
5545 const Elf_Verdaux *aux = (const Elf_Verdaux *)
5546 ((const char *)vd + vd->vd_aux);
5547 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
5550 if (vd->vd_next == 0)
5552 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5554 if (vna->vna_flags & VER_FLG_WEAK)
5556 _rtld_error("%s: version %s required by %s not found",
5557 depobj->path, vername, refobj->path);
5562 rtld_verify_object_versions(Obj_Entry *obj)
5564 const Elf_Verneed *vn;
5565 const Elf_Verdef *vd;
5566 const Elf_Verdaux *vda;
5567 const Elf_Vernaux *vna;
5568 const Obj_Entry *depobj;
5569 int maxvernum, vernum;
5571 if (obj->ver_checked)
5573 obj->ver_checked = true;
5577 * Walk over defined and required version records and figure out
5578 * max index used by any of them. Do very basic sanity checking
5582 while (vn != NULL) {
5583 if (vn->vn_version != VER_NEED_CURRENT) {
5584 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
5585 obj->path, vn->vn_version);
5588 vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux);
5590 vernum = VER_NEED_IDX(vna->vna_other);
5591 if (vernum > maxvernum)
5593 if (vna->vna_next == 0)
5595 vna = (const Elf_Vernaux *)((const char *)vna + vna->vna_next);
5597 if (vn->vn_next == 0)
5599 vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next);
5603 while (vd != NULL) {
5604 if (vd->vd_version != VER_DEF_CURRENT) {
5605 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
5606 obj->path, vd->vd_version);
5609 vernum = VER_DEF_IDX(vd->vd_ndx);
5610 if (vernum > maxvernum)
5612 if (vd->vd_next == 0)
5614 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5621 * Store version information in array indexable by version index.
5622 * Verify that object version requirements are satisfied along the
5625 obj->vernum = maxvernum + 1;
5626 obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry));
5629 while (vd != NULL) {
5630 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
5631 vernum = VER_DEF_IDX(vd->vd_ndx);
5632 assert(vernum <= maxvernum);
5633 vda = (const Elf_Verdaux *)((const char *)vd + vd->vd_aux);
5634 obj->vertab[vernum].hash = vd->vd_hash;
5635 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
5636 obj->vertab[vernum].file = NULL;
5637 obj->vertab[vernum].flags = 0;
5639 if (vd->vd_next == 0)
5641 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5645 while (vn != NULL) {
5646 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
5649 vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux);
5651 if (check_object_provided_version(obj, depobj, vna))
5653 vernum = VER_NEED_IDX(vna->vna_other);
5654 assert(vernum <= maxvernum);
5655 obj->vertab[vernum].hash = vna->vna_hash;
5656 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
5657 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
5658 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
5659 VER_INFO_HIDDEN : 0;
5660 if (vna->vna_next == 0)
5662 vna = (const Elf_Vernaux *)((const char *)vna + vna->vna_next);
5664 if (vn->vn_next == 0)
5666 vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next);
5672 rtld_verify_versions(const Objlist *objlist)
5674 Objlist_Entry *entry;
5678 STAILQ_FOREACH(entry, objlist, link) {
5680 * Skip dummy objects or objects that have their version requirements
5683 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
5685 if (rtld_verify_object_versions(entry->obj) == -1) {
5687 if (ld_tracing == NULL)
5691 if (rc == 0 || ld_tracing != NULL)
5692 rc = rtld_verify_object_versions(&obj_rtld);
5697 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
5702 vernum = VER_NDX(obj->versyms[symnum]);
5703 if (vernum >= obj->vernum) {
5704 _rtld_error("%s: symbol %s has wrong verneed value %d",
5705 obj->path, obj->strtab + symnum, vernum);
5706 } else if (obj->vertab[vernum].hash != 0) {
5707 return (&obj->vertab[vernum]);
5714 _rtld_get_stack_prot(void)
5717 return (stack_prot);
5721 _rtld_is_dlopened(void *arg)
5724 RtldLockState lockstate;
5727 rlock_acquire(rtld_bind_lock, &lockstate);
5730 obj = obj_from_addr(arg);
5732 _rtld_error("No shared object contains address");
5733 lock_release(rtld_bind_lock, &lockstate);
5736 res = obj->dlopened ? 1 : 0;
5737 lock_release(rtld_bind_lock, &lockstate);
5742 obj_remap_relro(Obj_Entry *obj, int prot)
5745 if (obj->relro_size > 0 && mprotect(obj->relro_page, obj->relro_size,
5747 _rtld_error("%s: Cannot set relro protection to %#x: %s",
5748 obj->path, prot, rtld_strerror(errno));
5755 obj_disable_relro(Obj_Entry *obj)
5758 return (obj_remap_relro(obj, PROT_READ | PROT_WRITE));
5762 obj_enforce_relro(Obj_Entry *obj)
5765 return (obj_remap_relro(obj, PROT_READ));
5769 map_stacks_exec(RtldLockState *lockstate)
5771 void (*thr_map_stacks_exec)(void);
5773 if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
5775 thr_map_stacks_exec = (void (*)(void))(uintptr_t)
5776 get_program_var_addr("__pthread_map_stacks_exec", lockstate);
5777 if (thr_map_stacks_exec != NULL) {
5778 stack_prot |= PROT_EXEC;
5779 thr_map_stacks_exec();
5784 distribute_static_tls(Objlist *list, RtldLockState *lockstate)
5788 void (*distrib)(size_t, void *, size_t, size_t);
5790 distrib = (void (*)(size_t, void *, size_t, size_t))(uintptr_t)
5791 get_program_var_addr("__pthread_distribute_static_tls", lockstate);
5792 if (distrib == NULL)
5794 STAILQ_FOREACH(elm, list, link) {
5796 if (obj->marker || !obj->tls_done || obj->static_tls_copied)
5798 distrib(obj->tlsoffset, obj->tlsinit, obj->tlsinitsize,
5800 obj->static_tls_copied = true;
5805 symlook_init(SymLook *dst, const char *name)
5808 bzero(dst, sizeof(*dst));
5810 dst->hash = elf_hash(name);
5811 dst->hash_gnu = gnu_hash(name);
5815 symlook_init_from_req(SymLook *dst, const SymLook *src)
5818 dst->name = src->name;
5819 dst->hash = src->hash;
5820 dst->hash_gnu = src->hash_gnu;
5821 dst->ventry = src->ventry;
5822 dst->flags = src->flags;
5823 dst->defobj_out = NULL;
5824 dst->sym_out = NULL;
5825 dst->lockstate = src->lockstate;
5829 open_binary_fd(const char *argv0, bool search_in_path,
5830 const char **binpath_res)
5832 char *binpath, *pathenv, *pe, *res1;
5838 if (search_in_path && strchr(argv0, '/') == NULL) {
5839 binpath = xmalloc(PATH_MAX);
5840 pathenv = getenv("PATH");
5841 if (pathenv == NULL) {
5842 _rtld_error("-p and no PATH environment variable");
5845 pathenv = strdup(pathenv);
5846 if (pathenv == NULL) {
5847 _rtld_error("Cannot allocate memory");
5852 while ((pe = strsep(&pathenv, ":")) != NULL) {
5853 if (strlcpy(binpath, pe, PATH_MAX) >= PATH_MAX)
5855 if (binpath[0] != '\0' &&
5856 strlcat(binpath, "/", PATH_MAX) >= PATH_MAX)
5858 if (strlcat(binpath, argv0, PATH_MAX) >= PATH_MAX)
5860 fd = open(binpath, O_RDONLY | O_CLOEXEC | O_VERIFY);
5861 if (fd != -1 || errno != ENOENT) {
5868 fd = open(argv0, O_RDONLY | O_CLOEXEC | O_VERIFY);
5873 _rtld_error("Cannot open %s: %s", argv0, rtld_strerror(errno));
5876 if (res != NULL && res[0] != '/') {
5877 res1 = xmalloc(PATH_MAX);
5878 if (realpath(res, res1) != NULL) {
5880 free(__DECONST(char *, res));
5891 * Parse a set of command-line arguments.
5894 parse_args(char* argv[], int argc, bool *use_pathp, int *fdp,
5895 const char **argv0, bool *dir_ignore)
5900 int arglen, fd, i, j, mib[2];
5902 bool seen_b, seen_f;
5904 dbg("Parsing command-line arguments");
5907 *dir_ignore = false;
5908 seen_b = seen_f = false;
5910 for (i = 1; i < argc; i++ ) {
5912 dbg("argv[%d]: '%s'", i, arg);
5915 * rtld arguments end with an explicit "--" or with the first
5916 * non-prefixed argument.
5918 if (strcmp(arg, "--") == 0) {
5926 * All other arguments are single-character options that can
5927 * be combined, so we need to search through `arg` for them.
5929 arglen = strlen(arg);
5930 for (j = 1; j < arglen; j++) {
5933 print_usage(argv[0]);
5935 } else if (opt == 'b') {
5937 _rtld_error("Both -b and -f specified");
5944 } else if (opt == 'd') {
5947 } else if (opt == 'f') {
5949 _rtld_error("Both -b and -f specified");
5954 * -f XX can be used to specify a
5955 * descriptor for the binary named at
5956 * the command line (i.e., the later
5957 * argument will specify the process
5958 * name but the descriptor is what
5959 * will actually be executed).
5961 * -f must be the last option in, e.g., -abcf.
5963 if (j != arglen - 1) {
5964 _rtld_error("Invalid options: %s", arg);
5968 fd = parse_integer(argv[i]);
5971 "Invalid file descriptor: '%s'",
5978 } else if (opt == 'p') {
5980 } else if (opt == 'u') {
5982 } else if (opt == 'v') {
5985 mib[1] = HW_MACHINE;
5986 sz = sizeof(machine);
5987 sysctl(mib, nitems(mib), machine, &sz, NULL, 0);
5988 ld_elf_hints_path = ld_get_env_var(
5990 set_ld_elf_hints_path();
5992 "FreeBSD ld-elf.so.1 %s\n"
5993 "FreeBSD_version %d\n"
5994 "Default lib path %s\n"
5995 "Hints lib path %s\n"
5997 "Default hint file %s\n"
6001 __FreeBSD_version, ld_standard_library_path,
6003 ld_env_prefix, ld_elf_hints_default,
6005 ld_path_libmap_conf);
6008 _rtld_error("Invalid argument: '%s'", arg);
6009 print_usage(argv[0]);
6021 * Parse a file descriptor number without pulling in more of libc (e.g. atoi).
6024 parse_integer(const char *str)
6026 static const int RADIX = 10; /* XXXJA: possibly support hex? */
6033 for (c = *str; c != '\0'; c = *++str) {
6034 if (c < '0' || c > '9')
6041 /* Make sure we actually parsed something. */
6048 print_usage(const char *argv0)
6052 "Usage: %s [-h] [-b <exe>] [-d] [-f <FD>] [-p] [--] <binary> [<args>]\n"
6055 " -h Display this help message\n"
6056 " -b <exe> Execute <exe> instead of <binary>, arg0 is <binary>\n"
6057 " -d Ignore lack of exec permissions for the binary\n"
6058 " -f <FD> Execute <FD> instead of searching for <binary>\n"
6059 " -p Search in PATH for named binary\n"
6060 " -u Ignore LD_ environment variables\n"
6061 " -v Display identification information\n"
6062 " -- End of RTLD options\n"
6063 " <binary> Name of process to execute\n"
6064 " <args> Arguments to the executed process\n", argv0);
6067 #define AUXFMT(at, xfmt) [at] = { .name = #at, .fmt = xfmt }
6068 static const struct auxfmt {
6072 AUXFMT(AT_NULL, NULL),
6073 AUXFMT(AT_IGNORE, NULL),
6074 AUXFMT(AT_EXECFD, "%ld"),
6075 AUXFMT(AT_PHDR, "%p"),
6076 AUXFMT(AT_PHENT, "%lu"),
6077 AUXFMT(AT_PHNUM, "%lu"),
6078 AUXFMT(AT_PAGESZ, "%lu"),
6079 AUXFMT(AT_BASE, "%#lx"),
6080 AUXFMT(AT_FLAGS, "%#lx"),
6081 AUXFMT(AT_ENTRY, "%p"),
6082 AUXFMT(AT_NOTELF, NULL),
6083 AUXFMT(AT_UID, "%ld"),
6084 AUXFMT(AT_EUID, "%ld"),
6085 AUXFMT(AT_GID, "%ld"),
6086 AUXFMT(AT_EGID, "%ld"),
6087 AUXFMT(AT_EXECPATH, "%s"),
6088 AUXFMT(AT_CANARY, "%p"),
6089 AUXFMT(AT_CANARYLEN, "%lu"),
6090 AUXFMT(AT_OSRELDATE, "%lu"),
6091 AUXFMT(AT_NCPUS, "%lu"),
6092 AUXFMT(AT_PAGESIZES, "%p"),
6093 AUXFMT(AT_PAGESIZESLEN, "%lu"),
6094 AUXFMT(AT_TIMEKEEP, "%p"),
6095 AUXFMT(AT_STACKPROT, "%#lx"),
6096 AUXFMT(AT_EHDRFLAGS, "%#lx"),
6097 AUXFMT(AT_HWCAP, "%#lx"),
6098 AUXFMT(AT_HWCAP2, "%#lx"),
6099 AUXFMT(AT_BSDFLAGS, "%#lx"),
6100 AUXFMT(AT_ARGC, "%lu"),
6101 AUXFMT(AT_ARGV, "%p"),
6102 AUXFMT(AT_ENVC, "%p"),
6103 AUXFMT(AT_ENVV, "%p"),
6104 AUXFMT(AT_PS_STRINGS, "%p"),
6105 AUXFMT(AT_FXRNG, "%p"),
6109 is_ptr_fmt(const char *fmt)
6113 last = fmt[strlen(fmt) - 1];
6114 return (last == 'p' || last == 's');
6118 dump_auxv(Elf_Auxinfo **aux_info)
6121 const struct auxfmt *fmt;
6124 for (i = 0; i < AT_COUNT; i++) {
6129 if (fmt->fmt == NULL)
6131 rtld_fdprintf(STDOUT_FILENO, "%s:\t", fmt->name);
6132 if (is_ptr_fmt(fmt->fmt)) {
6133 rtld_fdprintfx(STDOUT_FILENO, fmt->fmt,
6136 rtld_fdprintfx(STDOUT_FILENO, fmt->fmt,
6139 rtld_fdprintf(STDOUT_FILENO, "\n");
6144 * Overrides for libc_pic-provided functions.
6148 __getosreldate(void)
6158 oid[1] = KERN_OSRELDATE;
6160 len = sizeof(osrel);
6161 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
6162 if (error == 0 && osrel > 0 && len == sizeof(osrel))
6167 rtld_strerror(int errnum)
6170 if (errnum < 0 || errnum >= sys_nerr)
6171 return ("Unknown error");
6172 return (sys_errlist[errnum]);
6176 getenv(const char *name)
6178 return (__DECONST(char *, rtld_get_env_val(environ, name,
6184 malloc(size_t nbytes)
6187 return (__crt_malloc(nbytes));
6191 calloc(size_t num, size_t size)
6194 return (__crt_calloc(num, size));
6205 realloc(void *cp, size_t nbytes)
6208 return (__crt_realloc(cp, nbytes));
6211 extern int _rtld_version__FreeBSD_version __exported;
6212 int _rtld_version__FreeBSD_version = __FreeBSD_version;
6214 extern char _rtld_version_laddr_offset __exported;
6215 char _rtld_version_laddr_offset;
6217 extern char _rtld_version_dlpi_tls_data __exported;
6218 char _rtld_version_dlpi_tls_data;