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 errmsg_restore(struct dlerror_save *);
108 static struct dlerror_save *errmsg_save(void);
109 static void *fill_search_info(const char *, size_t, void *);
110 static char *find_library(const char *, const Obj_Entry *, int *);
111 static const char *gethints(bool);
112 static void hold_object(Obj_Entry *);
113 static void unhold_object(Obj_Entry *);
114 static void init_dag(Obj_Entry *);
115 static void init_marker(Obj_Entry *);
116 static void init_pagesizes(Elf_Auxinfo **aux_info);
117 static void init_rtld(caddr_t, Elf_Auxinfo **);
118 static void initlist_add_neededs(Needed_Entry *, Objlist *);
119 static void initlist_add_objects(Obj_Entry *, Obj_Entry *, Objlist *);
120 static int initlist_objects_ifunc(Objlist *, bool, int, RtldLockState *);
121 static void linkmap_add(Obj_Entry *);
122 static void linkmap_delete(Obj_Entry *);
123 static void load_filtees(Obj_Entry *, int flags, RtldLockState *);
124 static void unload_filtees(Obj_Entry *, RtldLockState *);
125 static int load_needed_objects(Obj_Entry *, int);
126 static int load_preload_objects(const char *, bool);
127 static Obj_Entry *load_object(const char *, int fd, const Obj_Entry *, int);
128 static void map_stacks_exec(RtldLockState *);
129 static int obj_disable_relro(Obj_Entry *);
130 static int obj_enforce_relro(Obj_Entry *);
131 static void objlist_call_fini(Objlist *, Obj_Entry *, RtldLockState *);
132 static void objlist_call_init(Objlist *, RtldLockState *);
133 static void objlist_clear(Objlist *);
134 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
135 static void objlist_init(Objlist *);
136 static void objlist_push_head(Objlist *, Obj_Entry *);
137 static void objlist_push_tail(Objlist *, Obj_Entry *);
138 static void objlist_put_after(Objlist *, Obj_Entry *, Obj_Entry *);
139 static void objlist_remove(Objlist *, Obj_Entry *);
140 static int open_binary_fd(const char *argv0, bool search_in_path,
141 const char **binpath_res);
142 static int parse_args(char* argv[], int argc, bool *use_pathp, int *fdp,
143 const char **argv0, bool *dir_ignore);
144 static int parse_integer(const char *);
145 static void *path_enumerate(const char *, path_enum_proc, const char *, void *);
146 static void print_usage(const char *argv0);
147 static void release_object(Obj_Entry *);
148 static int relocate_object_dag(Obj_Entry *root, bool bind_now,
149 Obj_Entry *rtldobj, int flags, RtldLockState *lockstate);
150 static int relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
151 int flags, RtldLockState *lockstate);
152 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, int,
154 static int resolve_object_ifunc(Obj_Entry *, bool, int, RtldLockState *);
155 static int rtld_dirname(const char *, char *);
156 static int rtld_dirname_abs(const char *, char *);
157 static void *rtld_dlopen(const char *name, int fd, int mode);
158 static void rtld_exit(void);
159 static void rtld_nop_exit(void);
160 static char *search_library_path(const char *, const char *, const char *,
162 static char *search_library_pathfds(const char *, const char *, int *);
163 static const void **get_program_var_addr(const char *, RtldLockState *);
164 static void set_program_var(const char *, const void *);
165 static int symlook_default(SymLook *, const Obj_Entry *refobj);
166 static int symlook_global(SymLook *, DoneList *);
167 static void symlook_init_from_req(SymLook *, const SymLook *);
168 static int symlook_list(SymLook *, const Objlist *, DoneList *);
169 static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *);
170 static int symlook_obj1_sysv(SymLook *, const Obj_Entry *);
171 static int symlook_obj1_gnu(SymLook *, const Obj_Entry *);
172 static void *tls_get_addr_slow(Elf_Addr **, int, size_t, bool) __noinline;
173 static void trace_loaded_objects(Obj_Entry *);
174 static void unlink_object(Obj_Entry *);
175 static void unload_object(Obj_Entry *, RtldLockState *lockstate);
176 static void unref_dag(Obj_Entry *);
177 static void ref_dag(Obj_Entry *);
178 static char *origin_subst_one(Obj_Entry *, char *, const char *,
180 static char *origin_subst(Obj_Entry *, const char *);
181 static bool obj_resolve_origin(Obj_Entry *obj);
182 static void preinit_main(void);
183 static int rtld_verify_versions(const Objlist *);
184 static int rtld_verify_object_versions(Obj_Entry *);
185 static void object_add_name(Obj_Entry *, const char *);
186 static int object_match_name(const Obj_Entry *, const char *);
187 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
188 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
189 struct dl_phdr_info *phdr_info);
190 static uint32_t gnu_hash(const char *);
191 static bool matched_symbol(SymLook *, const Obj_Entry *, Sym_Match_Result *,
192 const unsigned long);
194 void r_debug_state(struct r_debug *, struct link_map *) __noinline __exported;
195 void _r_debug_postinit(struct link_map *) __noinline __exported;
197 int __sys_openat(int, const char *, int, ...);
202 struct r_debug r_debug __exported; /* for GDB; */
203 static bool libmap_disable; /* Disable libmap */
204 static bool ld_loadfltr; /* Immediate filters processing */
205 static const char *libmap_override;/* Maps to use in addition to libmap.conf */
206 static bool trust; /* False for setuid and setgid programs */
207 static bool dangerous_ld_env; /* True if environment variables have been
208 used to affect the libraries loaded */
209 bool ld_bind_not; /* Disable PLT update */
210 static const char *ld_bind_now; /* Environment variable for immediate binding */
211 static const char *ld_debug; /* Environment variable for debugging */
212 static bool ld_dynamic_weak = true; /* True if non-weak definition overrides
214 static const char *ld_library_path;/* Environment variable for search path */
215 static const char *ld_library_dirs;/* Environment variable for library descriptors */
216 static const char *ld_preload; /* Environment variable for libraries to
218 static const char *ld_preload_fds;/* Environment variable for libraries represented by
220 static const char *ld_elf_hints_path; /* Environment variable for alternative hints path */
221 static const char *ld_tracing; /* Called from ldd to print libs */
222 static const char *ld_utrace; /* Use utrace() to log events. */
223 static struct obj_entry_q obj_list; /* Queue of all loaded objects */
224 static Obj_Entry *obj_main; /* The main program shared object */
225 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
226 static unsigned int obj_count; /* Number of objects in obj_list */
227 static unsigned int obj_loads; /* Number of loads of objects (gen count) */
229 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
230 STAILQ_HEAD_INITIALIZER(list_global);
231 static Objlist list_main = /* Objects loaded at program startup */
232 STAILQ_HEAD_INITIALIZER(list_main);
233 static Objlist list_fini = /* Objects needing fini() calls */
234 STAILQ_HEAD_INITIALIZER(list_fini);
236 Elf_Sym sym_zero; /* For resolving undefined weak refs. */
238 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
240 extern Elf_Dyn _DYNAMIC;
241 #pragma weak _DYNAMIC
243 int dlclose(void *) __exported;
244 char *dlerror(void) __exported;
245 void *dlopen(const char *, int) __exported;
246 void *fdlopen(int, int) __exported;
247 void *dlsym(void *, const char *) __exported;
248 dlfunc_t dlfunc(void *, const char *) __exported;
249 void *dlvsym(void *, const char *, const char *) __exported;
250 int dladdr(const void *, Dl_info *) __exported;
251 void dllockinit(void *, void *(*)(void *), void (*)(void *), void (*)(void *),
252 void (*)(void *), void (*)(void *), void (*)(void *)) __exported;
253 int dlinfo(void *, int , void *) __exported;
254 int dl_iterate_phdr(__dl_iterate_hdr_callback, void *) __exported;
255 int _rtld_addr_phdr(const void *, struct dl_phdr_info *) __exported;
256 int _rtld_get_stack_prot(void) __exported;
257 int _rtld_is_dlopened(void *) __exported;
258 void _rtld_error(const char *, ...) __exported;
260 /* Only here to fix -Wmissing-prototypes warnings */
261 int __getosreldate(void);
262 func_ptr_type _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp);
263 Elf_Addr _rtld_bind(Obj_Entry *obj, Elf_Size reloff);
267 static int osreldate;
270 static int stack_prot = PROT_READ | PROT_WRITE | RTLD_DEFAULT_STACK_EXEC;
271 static int max_stack_flags;
274 * Global declarations normally provided by crt1. The dynamic linker is
275 * not built with crt1, so we have to provide them ourselves.
281 * Used to pass argc, argv to init functions.
287 * Globals to control TLS allocation.
289 size_t tls_last_offset; /* Static TLS offset of last module */
290 size_t tls_last_size; /* Static TLS size of last module */
291 size_t tls_static_space; /* Static TLS space allocated */
292 static size_t tls_static_max_align;
293 Elf_Addr tls_dtv_generation = 1; /* Used to detect when dtv size changes */
294 int tls_max_index = 1; /* Largest module index allocated */
296 static bool ld_library_path_rpath = false;
297 bool ld_fast_sigblock = false;
300 * Globals for path names, and such
302 const char *ld_elf_hints_default = _PATH_ELF_HINTS;
303 const char *ld_path_libmap_conf = _PATH_LIBMAP_CONF;
304 const char *ld_path_rtld = _PATH_RTLD;
305 const char *ld_standard_library_path = STANDARD_LIBRARY_PATH;
306 const char *ld_env_prefix = LD_;
308 static void (*rtld_exit_ptr)(void);
311 * Fill in a DoneList with an allocation large enough to hold all of
312 * the currently-loaded objects. Keep this as a macro since it calls
313 * alloca and we want that to occur within the scope of the caller.
315 #define donelist_init(dlp) \
316 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
317 assert((dlp)->objs != NULL), \
318 (dlp)->num_alloc = obj_count, \
321 #define LD_UTRACE(e, h, mb, ms, r, n) do { \
322 if (ld_utrace != NULL) \
323 ld_utrace_log(e, h, mb, ms, r, n); \
327 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
328 int refcnt, const char *name)
330 struct utrace_rtld ut;
331 static const char rtld_utrace_sig[RTLD_UTRACE_SIG_SZ] = RTLD_UTRACE_SIG;
333 memcpy(ut.sig, rtld_utrace_sig, sizeof(ut.sig));
336 ut.mapbase = mapbase;
337 ut.mapsize = mapsize;
339 bzero(ut.name, sizeof(ut.name));
341 strlcpy(ut.name, name, sizeof(ut.name));
342 utrace(&ut, sizeof(ut));
356 LD_LIBRARY_PATH_RPATH,
359 LD_TRACE_LOADED_OBJECTS,
363 LD_TRACE_LOADED_OBJECTS_PROGNAME,
364 LD_TRACE_LOADED_OBJECTS_FMT1,
365 LD_TRACE_LOADED_OBJECTS_FMT2,
366 LD_TRACE_LOADED_OBJECTS_ALL,
369 struct ld_env_var_desc {
370 const char * const n;
374 #define LD_ENV_DESC(var, unsec) \
375 [LD_##var] = { .n = #var, .unsecure = unsec }
377 static struct ld_env_var_desc ld_env_vars[] = {
378 LD_ENV_DESC(BIND_NOW, false),
379 LD_ENV_DESC(PRELOAD, true),
380 LD_ENV_DESC(LIBMAP, true),
381 LD_ENV_DESC(LIBRARY_PATH, true),
382 LD_ENV_DESC(LIBRARY_PATH_FDS, true),
383 LD_ENV_DESC(LIBMAP_DISABLE, true),
384 LD_ENV_DESC(BIND_NOT, true),
385 LD_ENV_DESC(DEBUG, true),
386 LD_ENV_DESC(ELF_HINTS_PATH, true),
387 LD_ENV_DESC(LOADFLTR, true),
388 LD_ENV_DESC(LIBRARY_PATH_RPATH, true),
389 LD_ENV_DESC(PRELOAD_FDS, true),
390 LD_ENV_DESC(DYNAMIC_WEAK, true),
391 LD_ENV_DESC(TRACE_LOADED_OBJECTS, false),
392 LD_ENV_DESC(UTRACE, false),
393 LD_ENV_DESC(DUMP_REL_PRE, false),
394 LD_ENV_DESC(DUMP_REL_POST, false),
395 LD_ENV_DESC(TRACE_LOADED_OBJECTS_PROGNAME, false),
396 LD_ENV_DESC(TRACE_LOADED_OBJECTS_FMT1, false),
397 LD_ENV_DESC(TRACE_LOADED_OBJECTS_FMT2, false),
398 LD_ENV_DESC(TRACE_LOADED_OBJECTS_ALL, false),
402 ld_get_env_var(int idx)
404 return (ld_env_vars[idx].val);
408 rtld_get_env_val(char **env, const char *name, size_t name_len)
412 for (m = env; *m != NULL; m++) {
416 /* corrupt environment? */
419 if (v - n == (ptrdiff_t)name_len &&
420 strncmp(name, n, name_len) == 0)
427 rtld_init_env_vars_for_prefix(char **env, const char *env_prefix)
429 struct ld_env_var_desc *lvd;
430 size_t prefix_len, nlen;
434 prefix_len = strlen(env_prefix);
435 for (m = env; *m != NULL; m++) {
437 if (strncmp(env_prefix, n, prefix_len) != 0) {
438 /* Not a rtld environment variable. */
444 /* corrupt environment? */
447 for (i = 0; i < (int)nitems(ld_env_vars); i++) {
448 lvd = &ld_env_vars[i];
449 if (lvd->val != NULL) {
450 /* Saw higher-priority variable name already. */
453 nlen = strlen(lvd->n);
454 if (v - n == (ptrdiff_t)nlen &&
455 strncmp(lvd->n, n, nlen) == 0) {
464 rtld_init_env_vars(char **env)
466 rtld_init_env_vars_for_prefix(env, ld_env_prefix);
470 set_ld_elf_hints_path(void)
472 if (ld_elf_hints_path == NULL || strlen(ld_elf_hints_path) == 0)
473 ld_elf_hints_path = ld_elf_hints_default;
477 * Main entry point for dynamic linking. The first argument is the
478 * stack pointer. The stack is expected to be laid out as described
479 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
480 * Specifically, the stack pointer points to a word containing
481 * ARGC. Following that in the stack is a null-terminated sequence
482 * of pointers to argument strings. Then comes a null-terminated
483 * sequence of pointers to environment strings. Finally, there is a
484 * sequence of "auxiliary vector" entries.
486 * The second argument points to a place to store the dynamic linker's
487 * exit procedure pointer and the third to a place to store the main
490 * The return value is the main program's entry point.
493 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
495 Elf_Auxinfo *aux, *auxp, *auxpf, *aux_info[AT_COUNT];
496 Objlist_Entry *entry;
497 Obj_Entry *last_interposer, *obj, *preload_tail;
498 const Elf_Phdr *phdr;
500 RtldLockState lockstate;
503 char **argv, **env, **envp, *kexecpath;
504 const char *argv0, *binpath, *library_path_rpath;
505 struct ld_env_var_desc *lvd;
507 char buf[MAXPATHLEN];
508 int argc, fd, i, mib[4], old_osrel, osrel, phnum, rtld_argc;
511 int old_auxv_format = 1;
513 bool dir_enable, dir_ignore, direct_exec, explicit_fd, search_in_path;
516 * On entry, the dynamic linker itself has not been relocated yet.
517 * Be very careful not to reference any global data until after
518 * init_rtld has returned. It is OK to reference file-scope statics
519 * and string constants, and to call static and global functions.
522 /* Find the auxiliary vector on the stack. */
526 sp += argc + 1; /* Skip over arguments and NULL terminator */
528 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
530 aux = (Elf_Auxinfo *) sp;
532 /* Digest the auxiliary vector. */
533 for (i = 0; i < AT_COUNT; i++)
535 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
536 if (auxp->a_type < AT_COUNT)
537 aux_info[auxp->a_type] = auxp;
539 if (auxp->a_type == 23) /* AT_STACKPROT */
545 if (old_auxv_format) {
546 /* Remap from old-style auxv numbers. */
547 aux_info[23] = aux_info[21]; /* AT_STACKPROT */
548 aux_info[21] = aux_info[19]; /* AT_PAGESIZESLEN */
549 aux_info[19] = aux_info[17]; /* AT_NCPUS */
550 aux_info[17] = aux_info[15]; /* AT_CANARYLEN */
551 aux_info[15] = aux_info[13]; /* AT_EXECPATH */
552 aux_info[13] = NULL; /* AT_GID */
554 aux_info[20] = aux_info[18]; /* AT_PAGESIZES */
555 aux_info[18] = aux_info[16]; /* AT_OSRELDATE */
556 aux_info[16] = aux_info[14]; /* AT_CANARY */
557 aux_info[14] = NULL; /* AT_EGID */
561 /* Initialize and relocate ourselves. */
562 assert(aux_info[AT_BASE] != NULL);
563 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
567 __progname = obj_rtld.path;
568 argv0 = argv[0] != NULL ? argv[0] : "(null)";
573 if (aux_info[AT_BSDFLAGS] != NULL &&
574 (aux_info[AT_BSDFLAGS]->a_un.a_val & ELF_BSDF_SIGFASTBLK) != 0)
575 ld_fast_sigblock = true;
577 trust = !issetugid();
580 md_abi_variant_hook(aux_info);
581 rtld_init_env_vars(env);
584 if (aux_info[AT_EXECFD] != NULL) {
585 fd = aux_info[AT_EXECFD]->a_un.a_val;
587 assert(aux_info[AT_PHDR] != NULL);
588 phdr = (const Elf_Phdr *)aux_info[AT_PHDR]->a_un.a_ptr;
589 if (phdr == obj_rtld.phdr) {
591 _rtld_error("Tainted process refusing to run binary %s",
597 dbg("opening main program in direct exec mode");
599 rtld_argc = parse_args(argv, argc, &search_in_path, &fd,
600 &argv0, &dir_ignore);
601 explicit_fd = (fd != -1);
604 fd = open_binary_fd(argv0, search_in_path, &binpath);
605 if (fstat(fd, &st) == -1) {
606 _rtld_error("Failed to fstat FD %d (%s): %s", fd,
607 explicit_fd ? "user-provided descriptor" : argv0,
608 rtld_strerror(errno));
613 * Rough emulation of the permission checks done by
614 * execve(2), only Unix DACs are checked, ACLs are
615 * ignored. Preserve the semantic of disabling owner
616 * to execute if owner x bit is cleared, even if
617 * others x bit is enabled.
618 * mmap(2) does not allow to mmap with PROT_EXEC if
619 * binary' file comes from noexec mount. We cannot
620 * set a text reference on the binary.
623 if (st.st_uid == geteuid()) {
624 if ((st.st_mode & S_IXUSR) != 0)
626 } else if (st.st_gid == getegid()) {
627 if ((st.st_mode & S_IXGRP) != 0)
629 } else if ((st.st_mode & S_IXOTH) != 0) {
632 if (!dir_enable && !dir_ignore) {
633 _rtld_error("No execute permission for binary %s",
639 * For direct exec mode, argv[0] is the interpreter
640 * name, we must remove it and shift arguments left
641 * before invoking binary main. Since stack layout
642 * places environment pointers and aux vectors right
643 * after the terminating NULL, we must shift
644 * environment and aux as well.
646 main_argc = argc - rtld_argc;
647 for (i = 0; i <= main_argc; i++)
648 argv[i] = argv[i + rtld_argc];
650 environ = env = envp = argv + main_argc + 1;
651 dbg("move env from %p to %p", envp + rtld_argc, envp);
653 *envp = *(envp + rtld_argc);
654 } while (*envp++ != NULL);
655 aux = auxp = (Elf_Auxinfo *)envp;
656 auxpf = (Elf_Auxinfo *)(envp + rtld_argc);
657 dbg("move aux from %p to %p", auxpf, aux);
658 /* XXXKIB insert place for AT_EXECPATH if not present */
659 for (;; auxp++, auxpf++) {
661 if (auxp->a_type == AT_NULL)
664 /* Since the auxiliary vector has moved, redigest it. */
665 for (i = 0; i < AT_COUNT; i++)
667 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
668 if (auxp->a_type < AT_COUNT)
669 aux_info[auxp->a_type] = auxp;
672 /* Point AT_EXECPATH auxv and aux_info to the binary path. */
673 if (binpath == NULL) {
674 aux_info[AT_EXECPATH] = NULL;
676 if (aux_info[AT_EXECPATH] == NULL) {
677 aux_info[AT_EXECPATH] = xmalloc(sizeof(Elf_Auxinfo));
678 aux_info[AT_EXECPATH]->a_type = AT_EXECPATH;
680 aux_info[AT_EXECPATH]->a_un.a_ptr = __DECONST(void *,
684 _rtld_error("No binary");
690 ld_bind_now = ld_get_env_var(LD_BIND_NOW);
693 * If the process is tainted, then we un-set the dangerous environment
694 * variables. The process will be marked as tainted until setuid(2)
695 * is called. If any child process calls setuid(2) we do not want any
696 * future processes to honor the potentially un-safe variables.
699 for (i = 0; i < (int)nitems(ld_env_vars); i++) {
700 lvd = &ld_env_vars[i];
706 ld_debug = ld_get_env_var(LD_DEBUG);
707 if (ld_bind_now == NULL)
708 ld_bind_not = ld_get_env_var(LD_BIND_NOT) != NULL;
709 ld_dynamic_weak = ld_get_env_var(LD_DYNAMIC_WEAK) == NULL;
710 libmap_disable = ld_get_env_var(LD_LIBMAP_DISABLE) != NULL;
711 libmap_override = ld_get_env_var(LD_LIBMAP);
712 ld_library_path = ld_get_env_var(LD_LIBRARY_PATH);
713 ld_library_dirs = ld_get_env_var(LD_LIBRARY_PATH_FDS);
714 ld_preload = ld_get_env_var(LD_PRELOAD);
715 ld_preload_fds = ld_get_env_var(LD_PRELOAD_FDS);
716 ld_elf_hints_path = ld_get_env_var(LD_ELF_HINTS_PATH);
717 ld_loadfltr = ld_get_env_var(LD_LOADFLTR) != NULL;
718 library_path_rpath = ld_get_env_var(LD_LIBRARY_PATH_RPATH);
719 if (library_path_rpath != NULL) {
720 if (library_path_rpath[0] == 'y' ||
721 library_path_rpath[0] == 'Y' ||
722 library_path_rpath[0] == '1')
723 ld_library_path_rpath = true;
725 ld_library_path_rpath = false;
727 dangerous_ld_env = libmap_disable || libmap_override != NULL ||
728 ld_library_path != NULL || ld_preload != NULL ||
729 ld_elf_hints_path != NULL || ld_loadfltr || !ld_dynamic_weak;
730 ld_tracing = ld_get_env_var(LD_TRACE_LOADED_OBJECTS);
731 ld_utrace = ld_get_env_var(LD_UTRACE);
733 set_ld_elf_hints_path();
734 if (ld_debug != NULL && *ld_debug != '\0')
736 dbg("%s is initialized, base address = %p", __progname,
737 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
738 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
739 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
741 dbg("initializing thread locks");
745 * Load the main program, or process its program header if it is
748 if (fd != -1) { /* Load the main program. */
749 dbg("loading main program");
750 obj_main = map_object(fd, argv0, NULL);
752 if (obj_main == NULL)
754 max_stack_flags = obj_main->stack_flags;
755 } else { /* Main program already loaded. */
756 dbg("processing main program's program header");
757 assert(aux_info[AT_PHDR] != NULL);
758 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
759 assert(aux_info[AT_PHNUM] != NULL);
760 phnum = aux_info[AT_PHNUM]->a_un.a_val;
761 assert(aux_info[AT_PHENT] != NULL);
762 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
763 assert(aux_info[AT_ENTRY] != NULL);
764 imgentry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
765 if ((obj_main = digest_phdr(phdr, phnum, imgentry, argv0)) == NULL)
769 if (aux_info[AT_EXECPATH] != NULL && fd == -1) {
770 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
771 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
772 if (kexecpath[0] == '/')
773 obj_main->path = kexecpath;
774 else if (getcwd(buf, sizeof(buf)) == NULL ||
775 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
776 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
777 obj_main->path = xstrdup(argv0);
779 obj_main->path = xstrdup(buf);
781 dbg("No AT_EXECPATH or direct exec");
782 obj_main->path = xstrdup(argv0);
784 dbg("obj_main path %s", obj_main->path);
785 obj_main->mainprog = true;
787 if (aux_info[AT_STACKPROT] != NULL &&
788 aux_info[AT_STACKPROT]->a_un.a_val != 0)
789 stack_prot = aux_info[AT_STACKPROT]->a_un.a_val;
793 * Get the actual dynamic linker pathname from the executable if
794 * possible. (It should always be possible.) That ensures that
795 * gdb will find the right dynamic linker even if a non-standard
798 if (obj_main->interp != NULL &&
799 strcmp(obj_main->interp, obj_rtld.path) != 0) {
801 obj_rtld.path = xstrdup(obj_main->interp);
802 __progname = obj_rtld.path;
806 if (!digest_dynamic(obj_main, 0))
808 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d",
809 obj_main->path, obj_main->valid_hash_sysv, obj_main->valid_hash_gnu,
810 obj_main->dynsymcount);
812 linkmap_add(obj_main);
813 linkmap_add(&obj_rtld);
815 /* Link the main program into the list of objects. */
816 TAILQ_INSERT_HEAD(&obj_list, obj_main, next);
820 /* Initialize a fake symbol for resolving undefined weak references. */
821 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
822 sym_zero.st_shndx = SHN_UNDEF;
823 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
826 libmap_disable = (bool)lm_init(libmap_override);
828 dbg("loading LD_PRELOAD_FDS libraries");
829 if (load_preload_objects(ld_preload_fds, true) == -1)
832 dbg("loading LD_PRELOAD libraries");
833 if (load_preload_objects(ld_preload, false) == -1)
835 preload_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
837 dbg("loading needed objects");
838 if (load_needed_objects(obj_main, ld_tracing != NULL ? RTLD_LO_TRACE :
842 /* Make a list of all objects loaded at startup. */
843 last_interposer = obj_main;
844 TAILQ_FOREACH(obj, &obj_list, next) {
847 if (obj->z_interpose && obj != obj_main) {
848 objlist_put_after(&list_main, last_interposer, obj);
849 last_interposer = obj;
851 objlist_push_tail(&list_main, obj);
856 dbg("checking for required versions");
857 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
860 if (ld_tracing) { /* We're done */
861 trace_loaded_objects(obj_main);
865 if (ld_get_env_var(LD_DUMP_REL_PRE) != NULL) {
866 dump_relocations(obj_main);
871 * Processing tls relocations requires having the tls offsets
872 * initialized. Prepare offsets before starting initial
873 * relocation processing.
875 dbg("initializing initial thread local storage offsets");
876 STAILQ_FOREACH(entry, &list_main, link) {
878 * Allocate all the initial objects out of the static TLS
879 * block even if they didn't ask for it.
881 allocate_tls_offset(entry->obj);
884 if (relocate_objects(obj_main,
885 ld_bind_now != NULL && *ld_bind_now != '\0',
886 &obj_rtld, SYMLOOK_EARLY, NULL) == -1)
889 dbg("doing copy relocations");
890 if (do_copy_relocations(obj_main) == -1)
893 if (ld_get_env_var(LD_DUMP_REL_POST) != NULL) {
894 dump_relocations(obj_main);
901 * Setup TLS for main thread. This must be done after the
902 * relocations are processed, since tls initialization section
903 * might be the subject for relocations.
905 dbg("initializing initial thread local storage");
906 allocate_initial_tls(globallist_curr(TAILQ_FIRST(&obj_list)));
908 dbg("initializing key program variables");
909 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
910 set_program_var("environ", env);
911 set_program_var("__elf_aux_vector", aux);
913 /* Make a list of init functions to call. */
914 objlist_init(&initlist);
915 initlist_add_objects(globallist_curr(TAILQ_FIRST(&obj_list)),
916 preload_tail, &initlist);
918 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
920 map_stacks_exec(NULL);
922 if (!obj_main->crt_no_init) {
924 * Make sure we don't call the main program's init and fini
925 * functions for binaries linked with old crt1 which calls
928 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
929 obj_main->preinit_array = obj_main->init_array =
930 obj_main->fini_array = (Elf_Addr)NULL;
934 /* Set osrel for direct-execed binary */
937 mib[2] = KERN_PROC_OSREL;
939 osrel = obj_main->osrel;
940 sz = sizeof(old_osrel);
941 dbg("setting osrel to %d", osrel);
942 (void)sysctl(mib, 4, &old_osrel, &sz, &osrel, sizeof(osrel));
945 wlock_acquire(rtld_bind_lock, &lockstate);
947 dbg("resolving ifuncs");
948 if (initlist_objects_ifunc(&initlist, ld_bind_now != NULL &&
949 *ld_bind_now != '\0', SYMLOOK_EARLY, &lockstate) == -1)
952 rtld_exit_ptr = rtld_exit;
953 if (obj_main->crt_no_init)
955 objlist_call_init(&initlist, &lockstate);
956 _r_debug_postinit(&obj_main->linkmap);
957 objlist_clear(&initlist);
958 dbg("loading filtees");
959 TAILQ_FOREACH(obj, &obj_list, next) {
962 if (ld_loadfltr || obj->z_loadfltr)
963 load_filtees(obj, 0, &lockstate);
966 dbg("enforcing main obj relro");
967 if (obj_enforce_relro(obj_main) == -1)
970 lock_release(rtld_bind_lock, &lockstate);
972 dbg("transferring control to program entry point = %p", obj_main->entry);
974 /* Return the exit procedure and the program entry point. */
975 *exit_proc = rtld_exit_ptr;
977 return (func_ptr_type) obj_main->entry;
981 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def)
986 ptr = (void *)make_function_pointer(def, obj);
987 target = call_ifunc_resolver(ptr);
988 return ((void *)target);
992 * NB: MIPS uses a private version of this function (_mips_rtld_bind).
993 * Changes to this function should be applied there as well.
996 _rtld_bind(Obj_Entry *obj, Elf_Size reloff)
1000 const Obj_Entry *defobj;
1003 RtldLockState lockstate;
1005 rlock_acquire(rtld_bind_lock, &lockstate);
1006 if (sigsetjmp(lockstate.env, 0) != 0)
1007 lock_upgrade(rtld_bind_lock, &lockstate);
1009 rel = (const Elf_Rel *)((const char *)obj->pltrel + reloff);
1011 rel = (const Elf_Rel *)((const char *)obj->pltrela + reloff);
1013 where = (Elf_Addr *)(obj->relocbase + rel->r_offset);
1014 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, SYMLOOK_IN_PLT,
1018 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
1019 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
1021 target = (Elf_Addr)(defobj->relocbase + def->st_value);
1023 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
1024 defobj->strtab + def->st_name,
1025 obj->path == NULL ? NULL : basename(obj->path),
1027 defobj->path == NULL ? NULL : basename(defobj->path));
1030 * Write the new contents for the jmpslot. Note that depending on
1031 * architecture, the value which we need to return back to the
1032 * lazy binding trampoline may or may not be the target
1033 * address. The value returned from reloc_jmpslot() is the value
1034 * that the trampoline needs.
1036 target = reloc_jmpslot(where, target, defobj, obj, rel);
1037 lock_release(rtld_bind_lock, &lockstate);
1042 * Error reporting function. Use it like printf. If formats the message
1043 * into a buffer, and sets things up so that the next call to dlerror()
1044 * will return the message.
1047 _rtld_error(const char *fmt, ...)
1052 rtld_vsnprintf(lockinfo.dlerror_loc(), lockinfo.dlerror_loc_sz,
1055 *lockinfo.dlerror_seen() = 0;
1056 LD_UTRACE(UTRACE_RTLD_ERROR, NULL, NULL, 0, 0, lockinfo.dlerror_loc());
1060 * Return a dynamically-allocated copy of the current error message, if any.
1062 static struct dlerror_save *
1065 struct dlerror_save *res;
1067 res = xmalloc(sizeof(*res));
1068 res->seen = *lockinfo.dlerror_seen();
1070 res->msg = xstrdup(lockinfo.dlerror_loc());
1075 * Restore the current error message from a copy which was previously saved
1076 * by errmsg_save(). The copy is freed.
1079 errmsg_restore(struct dlerror_save *saved_msg)
1081 if (saved_msg == NULL || saved_msg->seen == 1) {
1082 *lockinfo.dlerror_seen() = 1;
1084 *lockinfo.dlerror_seen() = 0;
1085 strlcpy(lockinfo.dlerror_loc(), saved_msg->msg,
1086 lockinfo.dlerror_loc_sz);
1087 free(saved_msg->msg);
1093 basename(const char *name)
1095 const char *p = strrchr(name, '/');
1096 return p != NULL ? p + 1 : name;
1099 static struct utsname uts;
1102 origin_subst_one(Obj_Entry *obj, char *real, const char *kw,
1103 const char *subst, bool may_free)
1105 char *p, *p1, *res, *resp;
1106 int subst_len, kw_len, subst_count, old_len, new_len;
1108 kw_len = strlen(kw);
1111 * First, count the number of the keyword occurrences, to
1112 * preallocate the final string.
1114 for (p = real, subst_count = 0;; p = p1 + kw_len, subst_count++) {
1121 * If the keyword is not found, just return.
1123 * Return non-substituted string if resolution failed. We
1124 * cannot do anything more reasonable, the failure mode of the
1125 * caller is unresolved library anyway.
1127 if (subst_count == 0 || (obj != NULL && !obj_resolve_origin(obj)))
1128 return (may_free ? real : xstrdup(real));
1130 subst = obj->origin_path;
1133 * There is indeed something to substitute. Calculate the
1134 * length of the resulting string, and allocate it.
1136 subst_len = strlen(subst);
1137 old_len = strlen(real);
1138 new_len = old_len + (subst_len - kw_len) * subst_count;
1139 res = xmalloc(new_len + 1);
1142 * Now, execute the substitution loop.
1144 for (p = real, resp = res, *resp = '\0';;) {
1147 /* Copy the prefix before keyword. */
1148 memcpy(resp, p, p1 - p);
1150 /* Keyword replacement. */
1151 memcpy(resp, subst, subst_len);
1159 /* Copy to the end of string and finish. */
1167 origin_subst(Obj_Entry *obj, const char *real)
1169 char *res1, *res2, *res3, *res4;
1171 if (obj == NULL || !trust)
1172 return (xstrdup(real));
1173 if (uts.sysname[0] == '\0') {
1174 if (uname(&uts) != 0) {
1175 _rtld_error("utsname failed: %d", errno);
1179 /* __DECONST is safe here since without may_free real is unchanged */
1180 res1 = origin_subst_one(obj, __DECONST(char *, real), "$ORIGIN", NULL,
1182 res2 = origin_subst_one(NULL, res1, "$OSNAME", uts.sysname, true);
1183 res3 = origin_subst_one(NULL, res2, "$OSREL", uts.release, true);
1184 res4 = origin_subst_one(NULL, res3, "$PLATFORM", uts.machine, true);
1191 const char *msg = dlerror();
1194 msg = "Fatal error";
1195 rtld_fdputstr(STDERR_FILENO, _BASENAME_RTLD ": ");
1196 rtld_fdputstr(STDERR_FILENO, msg);
1197 rtld_fdputchar(STDERR_FILENO, '\n');
1202 * Process a shared object's DYNAMIC section, and save the important
1203 * information in its Obj_Entry structure.
1206 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
1207 const Elf_Dyn **dyn_soname, const Elf_Dyn **dyn_runpath)
1209 const Elf_Dyn *dynp;
1210 Needed_Entry **needed_tail = &obj->needed;
1211 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
1212 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
1213 const Elf_Hashelt *hashtab;
1214 const Elf32_Word *hashval;
1215 Elf32_Word bkt, nmaskwords;
1217 int plttype = DT_REL;
1221 *dyn_runpath = NULL;
1223 obj->bind_now = false;
1224 dynp = obj->dynamic;
1227 for (; dynp->d_tag != DT_NULL; dynp++) {
1228 switch (dynp->d_tag) {
1231 obj->rel = (const Elf_Rel *)(obj->relocbase + dynp->d_un.d_ptr);
1235 obj->relsize = dynp->d_un.d_val;
1239 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
1243 obj->pltrel = (const Elf_Rel *)
1244 (obj->relocbase + dynp->d_un.d_ptr);
1248 obj->pltrelsize = dynp->d_un.d_val;
1252 obj->rela = (const Elf_Rela *)(obj->relocbase + dynp->d_un.d_ptr);
1256 obj->relasize = dynp->d_un.d_val;
1260 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
1264 obj->relr = (const Elf_Relr *)(obj->relocbase + dynp->d_un.d_ptr);
1268 obj->relrsize = dynp->d_un.d_val;
1272 assert(dynp->d_un.d_val == sizeof(Elf_Relr));
1276 plttype = dynp->d_un.d_val;
1277 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
1281 obj->symtab = (const Elf_Sym *)
1282 (obj->relocbase + dynp->d_un.d_ptr);
1286 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
1290 obj->strtab = (const char *)(obj->relocbase + dynp->d_un.d_ptr);
1294 obj->strsize = dynp->d_un.d_val;
1298 obj->verneed = (const Elf_Verneed *)(obj->relocbase +
1303 obj->verneednum = dynp->d_un.d_val;
1307 obj->verdef = (const Elf_Verdef *)(obj->relocbase +
1312 obj->verdefnum = dynp->d_un.d_val;
1316 obj->versyms = (const Elf_Versym *)(obj->relocbase +
1322 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1324 obj->nbuckets = hashtab[0];
1325 obj->nchains = hashtab[1];
1326 obj->buckets = hashtab + 2;
1327 obj->chains = obj->buckets + obj->nbuckets;
1328 obj->valid_hash_sysv = obj->nbuckets > 0 && obj->nchains > 0 &&
1329 obj->buckets != NULL;
1335 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1337 obj->nbuckets_gnu = hashtab[0];
1338 obj->symndx_gnu = hashtab[1];
1339 nmaskwords = hashtab[2];
1340 bloom_size32 = (__ELF_WORD_SIZE / 32) * nmaskwords;
1341 obj->maskwords_bm_gnu = nmaskwords - 1;
1342 obj->shift2_gnu = hashtab[3];
1343 obj->bloom_gnu = (const Elf_Addr *)(hashtab + 4);
1344 obj->buckets_gnu = hashtab + 4 + bloom_size32;
1345 obj->chain_zero_gnu = obj->buckets_gnu + obj->nbuckets_gnu -
1347 /* Number of bitmask words is required to be power of 2 */
1348 obj->valid_hash_gnu = powerof2(nmaskwords) &&
1349 obj->nbuckets_gnu > 0 && obj->buckets_gnu != NULL;
1355 Needed_Entry *nep = NEW(Needed_Entry);
1356 nep->name = dynp->d_un.d_val;
1361 needed_tail = &nep->next;
1367 Needed_Entry *nep = NEW(Needed_Entry);
1368 nep->name = dynp->d_un.d_val;
1372 *needed_filtees_tail = nep;
1373 needed_filtees_tail = &nep->next;
1375 if (obj->linkmap.l_refname == NULL)
1376 obj->linkmap.l_refname = (char *)dynp->d_un.d_val;
1382 Needed_Entry *nep = NEW(Needed_Entry);
1383 nep->name = dynp->d_un.d_val;
1387 *needed_aux_filtees_tail = nep;
1388 needed_aux_filtees_tail = &nep->next;
1393 obj->pltgot = (Elf_Addr *)(obj->relocbase + dynp->d_un.d_ptr);
1397 obj->textrel = true;
1401 obj->symbolic = true;
1406 * We have to wait until later to process this, because we
1407 * might not have gotten the address of the string table yet.
1417 *dyn_runpath = dynp;
1421 obj->init = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1424 case DT_PREINIT_ARRAY:
1425 obj->preinit_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1428 case DT_PREINIT_ARRAYSZ:
1429 obj->preinit_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1433 obj->init_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1436 case DT_INIT_ARRAYSZ:
1437 obj->init_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1441 obj->fini = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1445 obj->fini_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1448 case DT_FINI_ARRAYSZ:
1449 obj->fini_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1453 * Don't process DT_DEBUG on MIPS as the dynamic section
1454 * is mapped read-only. DT_MIPS_RLD_MAP is used instead.
1460 dbg("Filling in DT_DEBUG entry");
1461 (__DECONST(Elf_Dyn *, dynp))->d_un.d_ptr = (Elf_Addr)&r_debug;
1466 if (dynp->d_un.d_val & DF_ORIGIN)
1467 obj->z_origin = true;
1468 if (dynp->d_un.d_val & DF_SYMBOLIC)
1469 obj->symbolic = true;
1470 if (dynp->d_un.d_val & DF_TEXTREL)
1471 obj->textrel = true;
1472 if (dynp->d_un.d_val & DF_BIND_NOW)
1473 obj->bind_now = true;
1474 if (dynp->d_un.d_val & DF_STATIC_TLS)
1475 obj->static_tls = true;
1478 case DT_MIPS_LOCAL_GOTNO:
1479 obj->local_gotno = dynp->d_un.d_val;
1482 case DT_MIPS_SYMTABNO:
1483 obj->symtabno = dynp->d_un.d_val;
1486 case DT_MIPS_GOTSYM:
1487 obj->gotsym = dynp->d_un.d_val;
1490 case DT_MIPS_RLD_MAP:
1491 *((Elf_Addr *)(dynp->d_un.d_ptr)) = (Elf_Addr) &r_debug;
1494 case DT_MIPS_RLD_MAP_REL:
1495 // The MIPS_RLD_MAP_REL tag stores the offset to the .rld_map
1496 // section relative to the address of the tag itself.
1497 *((Elf_Addr *)(__DECONST(char*, dynp) + dynp->d_un.d_val)) =
1498 (Elf_Addr) &r_debug;
1501 case DT_MIPS_PLTGOT:
1502 obj->mips_pltgot = (Elf_Addr *)(obj->relocbase +
1509 #ifdef __powerpc64__
1510 case DT_PPC64_GLINK:
1511 obj->glink = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1515 obj->gotptr = (Elf_Addr *)(obj->relocbase + dynp->d_un.d_ptr);
1521 if (dynp->d_un.d_val & DF_1_NOOPEN)
1522 obj->z_noopen = true;
1523 if (dynp->d_un.d_val & DF_1_ORIGIN)
1524 obj->z_origin = true;
1525 if (dynp->d_un.d_val & DF_1_GLOBAL)
1526 obj->z_global = true;
1527 if (dynp->d_un.d_val & DF_1_BIND_NOW)
1528 obj->bind_now = true;
1529 if (dynp->d_un.d_val & DF_1_NODELETE)
1530 obj->z_nodelete = true;
1531 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1532 obj->z_loadfltr = true;
1533 if (dynp->d_un.d_val & DF_1_INTERPOSE)
1534 obj->z_interpose = true;
1535 if (dynp->d_un.d_val & DF_1_NODEFLIB)
1536 obj->z_nodeflib = true;
1537 if (dynp->d_un.d_val & DF_1_PIE)
1543 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1550 obj->traced = false;
1552 if (plttype == DT_RELA) {
1553 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1555 obj->pltrelasize = obj->pltrelsize;
1556 obj->pltrelsize = 0;
1559 /* Determine size of dynsym table (equal to nchains of sysv hash) */
1560 if (obj->valid_hash_sysv)
1561 obj->dynsymcount = obj->nchains;
1562 else if (obj->valid_hash_gnu) {
1563 obj->dynsymcount = 0;
1564 for (bkt = 0; bkt < obj->nbuckets_gnu; bkt++) {
1565 if (obj->buckets_gnu[bkt] == 0)
1567 hashval = &obj->chain_zero_gnu[obj->buckets_gnu[bkt]];
1570 while ((*hashval++ & 1u) == 0);
1572 obj->dynsymcount += obj->symndx_gnu;
1575 if (obj->linkmap.l_refname != NULL)
1576 obj->linkmap.l_refname = obj->strtab + (unsigned long)obj->
1581 obj_resolve_origin(Obj_Entry *obj)
1584 if (obj->origin_path != NULL)
1586 obj->origin_path = xmalloc(PATH_MAX);
1587 return (rtld_dirname_abs(obj->path, obj->origin_path) != -1);
1591 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1592 const Elf_Dyn *dyn_soname, const Elf_Dyn *dyn_runpath)
1595 if (obj->z_origin && !obj_resolve_origin(obj))
1598 if (dyn_runpath != NULL) {
1599 obj->runpath = (const char *)obj->strtab + dyn_runpath->d_un.d_val;
1600 obj->runpath = origin_subst(obj, obj->runpath);
1601 } else if (dyn_rpath != NULL) {
1602 obj->rpath = (const char *)obj->strtab + dyn_rpath->d_un.d_val;
1603 obj->rpath = origin_subst(obj, obj->rpath);
1605 if (dyn_soname != NULL)
1606 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1611 digest_dynamic(Obj_Entry *obj, int early)
1613 const Elf_Dyn *dyn_rpath;
1614 const Elf_Dyn *dyn_soname;
1615 const Elf_Dyn *dyn_runpath;
1617 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname, &dyn_runpath);
1618 return (digest_dynamic2(obj, dyn_rpath, dyn_soname, dyn_runpath));
1622 * Process a shared object's program header. This is used only for the
1623 * main program, when the kernel has already loaded the main program
1624 * into memory before calling the dynamic linker. It creates and
1625 * returns an Obj_Entry structure.
1628 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1631 const Elf_Phdr *phlimit = phdr + phnum;
1633 Elf_Addr note_start, note_end;
1637 for (ph = phdr; ph < phlimit; ph++) {
1638 if (ph->p_type != PT_PHDR)
1642 obj->phsize = ph->p_memsz;
1643 obj->relocbase = __DECONST(char *, phdr) - ph->p_vaddr;
1647 obj->stack_flags = PF_X | PF_R | PF_W;
1649 for (ph = phdr; ph < phlimit; ph++) {
1650 switch (ph->p_type) {
1653 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1657 if (nsegs == 0) { /* First load segment */
1658 obj->vaddrbase = trunc_page(ph->p_vaddr);
1659 obj->mapbase = obj->vaddrbase + obj->relocbase;
1660 } else { /* Last load segment */
1661 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1668 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1673 obj->tlssize = ph->p_memsz;
1674 obj->tlsalign = ph->p_align;
1675 obj->tlsinitsize = ph->p_filesz;
1676 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1677 obj->tlspoffset = ph->p_offset;
1681 obj->stack_flags = ph->p_flags;
1685 obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1686 obj->relro_size = trunc_page(ph->p_vaddr + ph->p_memsz) -
1687 trunc_page(ph->p_vaddr);
1691 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
1692 note_end = note_start + ph->p_filesz;
1693 digest_notes(obj, note_start, note_end);
1698 _rtld_error("%s: too few PT_LOAD segments", path);
1707 digest_notes(Obj_Entry *obj, Elf_Addr note_start, Elf_Addr note_end)
1709 const Elf_Note *note;
1710 const char *note_name;
1713 for (note = (const Elf_Note *)note_start; (Elf_Addr)note < note_end;
1714 note = (const Elf_Note *)((const char *)(note + 1) +
1715 roundup2(note->n_namesz, sizeof(Elf32_Addr)) +
1716 roundup2(note->n_descsz, sizeof(Elf32_Addr)))) {
1717 if (note->n_namesz != sizeof(NOTE_FREEBSD_VENDOR) ||
1718 note->n_descsz != sizeof(int32_t))
1720 if (note->n_type != NT_FREEBSD_ABI_TAG &&
1721 note->n_type != NT_FREEBSD_FEATURE_CTL &&
1722 note->n_type != NT_FREEBSD_NOINIT_TAG)
1724 note_name = (const char *)(note + 1);
1725 if (strncmp(NOTE_FREEBSD_VENDOR, note_name,
1726 sizeof(NOTE_FREEBSD_VENDOR)) != 0)
1728 switch (note->n_type) {
1729 case NT_FREEBSD_ABI_TAG:
1730 /* FreeBSD osrel note */
1731 p = (uintptr_t)(note + 1);
1732 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1733 obj->osrel = *(const int32_t *)(p);
1734 dbg("note osrel %d", obj->osrel);
1736 case NT_FREEBSD_FEATURE_CTL:
1737 /* FreeBSD ABI feature control note */
1738 p = (uintptr_t)(note + 1);
1739 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1740 obj->fctl0 = *(const uint32_t *)(p);
1741 dbg("note fctl0 %#x", obj->fctl0);
1743 case NT_FREEBSD_NOINIT_TAG:
1744 /* FreeBSD 'crt does not call init' note */
1745 obj->crt_no_init = true;
1746 dbg("note crt_no_init");
1753 dlcheck(void *handle)
1757 TAILQ_FOREACH(obj, &obj_list, next) {
1758 if (obj == (Obj_Entry *) handle)
1762 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1763 _rtld_error("Invalid shared object handle %p", handle);
1770 * If the given object is already in the donelist, return true. Otherwise
1771 * add the object to the list and return false.
1774 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1778 for (i = 0; i < dlp->num_used; i++)
1779 if (dlp->objs[i] == obj)
1782 * Our donelist allocation should always be sufficient. But if
1783 * our threads locking isn't working properly, more shared objects
1784 * could have been loaded since we allocated the list. That should
1785 * never happen, but we'll handle it properly just in case it does.
1787 if (dlp->num_used < dlp->num_alloc)
1788 dlp->objs[dlp->num_used++] = obj;
1793 * Hash function for symbol table lookup. Don't even think about changing
1794 * this. It is specified by the System V ABI.
1797 elf_hash(const char *name)
1799 const unsigned char *p = (const unsigned char *) name;
1800 unsigned long h = 0;
1803 while (*p != '\0') {
1804 h = (h << 4) + *p++;
1805 if ((g = h & 0xf0000000) != 0)
1813 * The GNU hash function is the Daniel J. Bernstein hash clipped to 32 bits
1814 * unsigned in case it's implemented with a wider type.
1817 gnu_hash(const char *s)
1823 for (c = *s; c != '\0'; c = *++s)
1825 return (h & 0xffffffff);
1830 * Find the library with the given name, and return its full pathname.
1831 * The returned string is dynamically allocated. Generates an error
1832 * message and returns NULL if the library cannot be found.
1834 * If the second argument is non-NULL, then it refers to an already-
1835 * loaded shared object, whose library search path will be searched.
1837 * If a library is successfully located via LD_LIBRARY_PATH_FDS, its
1838 * descriptor (which is close-on-exec) will be passed out via the third
1841 * The search order is:
1842 * DT_RPATH in the referencing file _unless_ DT_RUNPATH is present (1)
1843 * DT_RPATH of the main object if DSO without defined DT_RUNPATH (1)
1845 * DT_RUNPATH in the referencing file
1846 * ldconfig hints (if -z nodefaultlib, filter out default library directories
1848 * /lib:/usr/lib _unless_ the referencing file is linked with -z nodefaultlib
1850 * (1) Handled in digest_dynamic2 - rpath left NULL if runpath defined.
1853 find_library(const char *xname, const Obj_Entry *refobj, int *fdp)
1855 char *pathname, *refobj_path;
1857 bool nodeflib, objgiven;
1859 objgiven = refobj != NULL;
1861 if (libmap_disable || !objgiven ||
1862 (name = lm_find(refobj->path, xname)) == NULL)
1865 if (strchr(name, '/') != NULL) { /* Hard coded pathname */
1866 if (name[0] != '/' && !trust) {
1867 _rtld_error("Absolute pathname required "
1868 "for shared object \"%s\"", name);
1871 return (origin_subst(__DECONST(Obj_Entry *, refobj),
1872 __DECONST(char *, name)));
1875 dbg(" Searching for \"%s\"", name);
1876 refobj_path = objgiven ? refobj->path : NULL;
1879 * If refobj->rpath != NULL, then refobj->runpath is NULL. Fall
1880 * back to pre-conforming behaviour if user requested so with
1881 * LD_LIBRARY_PATH_RPATH environment variable and ignore -z
1884 if (objgiven && refobj->rpath != NULL && ld_library_path_rpath) {
1885 pathname = search_library_path(name, ld_library_path,
1887 if (pathname != NULL)
1889 if (refobj != NULL) {
1890 pathname = search_library_path(name, refobj->rpath,
1892 if (pathname != NULL)
1895 pathname = search_library_pathfds(name, ld_library_dirs, fdp);
1896 if (pathname != NULL)
1898 pathname = search_library_path(name, gethints(false),
1900 if (pathname != NULL)
1902 pathname = search_library_path(name, ld_standard_library_path,
1904 if (pathname != NULL)
1907 nodeflib = objgiven ? refobj->z_nodeflib : false;
1909 pathname = search_library_path(name, refobj->rpath,
1911 if (pathname != NULL)
1914 if (objgiven && refobj->runpath == NULL && refobj != obj_main) {
1915 pathname = search_library_path(name, obj_main->rpath,
1917 if (pathname != NULL)
1920 pathname = search_library_path(name, ld_library_path,
1922 if (pathname != NULL)
1925 pathname = search_library_path(name, refobj->runpath,
1927 if (pathname != NULL)
1930 pathname = search_library_pathfds(name, ld_library_dirs, fdp);
1931 if (pathname != NULL)
1933 pathname = search_library_path(name, gethints(nodeflib),
1935 if (pathname != NULL)
1937 if (objgiven && !nodeflib) {
1938 pathname = search_library_path(name,
1939 ld_standard_library_path, refobj_path, fdp);
1940 if (pathname != NULL)
1945 if (objgiven && refobj->path != NULL) {
1946 _rtld_error("Shared object \"%s\" not found, "
1947 "required by \"%s\"", name, basename(refobj->path));
1949 _rtld_error("Shared object \"%s\" not found", name);
1955 * Given a symbol number in a referencing object, find the corresponding
1956 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1957 * no definition was found. Returns a pointer to the Obj_Entry of the
1958 * defining object via the reference parameter DEFOBJ_OUT.
1961 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1962 const Obj_Entry **defobj_out, int flags, SymCache *cache,
1963 RtldLockState *lockstate)
1967 const Obj_Entry *defobj;
1968 const Ver_Entry *ve;
1974 * If we have already found this symbol, get the information from
1977 if (symnum >= refobj->dynsymcount)
1978 return NULL; /* Bad object */
1979 if (cache != NULL && cache[symnum].sym != NULL) {
1980 *defobj_out = cache[symnum].obj;
1981 return cache[symnum].sym;
1984 ref = refobj->symtab + symnum;
1985 name = refobj->strtab + ref->st_name;
1991 * We don't have to do a full scale lookup if the symbol is local.
1992 * We know it will bind to the instance in this load module; to
1993 * which we already have a pointer (ie ref). By not doing a lookup,
1994 * we not only improve performance, but it also avoids unresolvable
1995 * symbols when local symbols are not in the hash table. This has
1996 * been seen with the ia64 toolchain.
1998 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1999 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
2000 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
2003 symlook_init(&req, name);
2005 ve = req.ventry = fetch_ventry(refobj, symnum);
2006 req.lockstate = lockstate;
2007 res = symlook_default(&req, refobj);
2010 defobj = req.defobj_out;
2018 * If we found no definition and the reference is weak, treat the
2019 * symbol as having the value zero.
2021 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
2027 *defobj_out = defobj;
2028 /* Record the information in the cache to avoid subsequent lookups. */
2029 if (cache != NULL) {
2030 cache[symnum].sym = def;
2031 cache[symnum].obj = defobj;
2034 if (refobj != &obj_rtld)
2035 _rtld_error("%s: Undefined symbol \"%s%s%s\"", refobj->path, name,
2036 ve != NULL ? "@" : "", ve != NULL ? ve->name : "");
2042 * Return the search path from the ldconfig hints file, reading it if
2043 * necessary. If nostdlib is true, then the default search paths are
2044 * not added to result.
2046 * Returns NULL if there are problems with the hints file,
2047 * or if the search path there is empty.
2050 gethints(bool nostdlib)
2052 static char *filtered_path;
2053 static const char *hints;
2054 static struct elfhints_hdr hdr;
2055 struct fill_search_info_args sargs, hargs;
2056 struct dl_serinfo smeta, hmeta, *SLPinfo, *hintinfo;
2057 struct dl_serpath *SLPpath, *hintpath;
2059 struct stat hint_stat;
2060 unsigned int SLPndx, hintndx, fndx, fcount;
2066 /* First call, read the hints file */
2067 if (hints == NULL) {
2068 /* Keep from trying again in case the hints file is bad. */
2071 if ((fd = open(ld_elf_hints_path, O_RDONLY | O_CLOEXEC)) == -1)
2075 * Check of hdr.dirlistlen value against type limit
2076 * intends to pacify static analyzers. Further
2077 * paranoia leads to checks that dirlist is fully
2078 * contained in the file range.
2080 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
2081 hdr.magic != ELFHINTS_MAGIC ||
2082 hdr.version != 1 || hdr.dirlistlen > UINT_MAX / 2 ||
2083 fstat(fd, &hint_stat) == -1) {
2090 if (dl + hdr.dirlist < dl)
2093 if (dl + hdr.dirlistlen < dl)
2095 dl += hdr.dirlistlen;
2096 if (dl > hint_stat.st_size)
2098 p = xmalloc(hdr.dirlistlen + 1);
2099 if (pread(fd, p, hdr.dirlistlen + 1,
2100 hdr.strtab + hdr.dirlist) != (ssize_t)hdr.dirlistlen + 1 ||
2101 p[hdr.dirlistlen] != '\0') {
2110 * If caller agreed to receive list which includes the default
2111 * paths, we are done. Otherwise, if we still did not
2112 * calculated filtered result, do it now.
2115 return (hints[0] != '\0' ? hints : NULL);
2116 if (filtered_path != NULL)
2120 * Obtain the list of all configured search paths, and the
2121 * list of the default paths.
2123 * First estimate the size of the results.
2125 smeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2127 hmeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2130 sargs.request = RTLD_DI_SERINFOSIZE;
2131 sargs.serinfo = &smeta;
2132 hargs.request = RTLD_DI_SERINFOSIZE;
2133 hargs.serinfo = &hmeta;
2135 path_enumerate(ld_standard_library_path, fill_search_info, NULL,
2137 path_enumerate(hints, fill_search_info, NULL, &hargs);
2139 SLPinfo = xmalloc(smeta.dls_size);
2140 hintinfo = xmalloc(hmeta.dls_size);
2143 * Next fetch both sets of paths.
2145 sargs.request = RTLD_DI_SERINFO;
2146 sargs.serinfo = SLPinfo;
2147 sargs.serpath = &SLPinfo->dls_serpath[0];
2148 sargs.strspace = (char *)&SLPinfo->dls_serpath[smeta.dls_cnt];
2150 hargs.request = RTLD_DI_SERINFO;
2151 hargs.serinfo = hintinfo;
2152 hargs.serpath = &hintinfo->dls_serpath[0];
2153 hargs.strspace = (char *)&hintinfo->dls_serpath[hmeta.dls_cnt];
2155 path_enumerate(ld_standard_library_path, fill_search_info, NULL,
2157 path_enumerate(hints, fill_search_info, NULL, &hargs);
2160 * Now calculate the difference between two sets, by excluding
2161 * standard paths from the full set.
2165 filtered_path = xmalloc(hdr.dirlistlen + 1);
2166 hintpath = &hintinfo->dls_serpath[0];
2167 for (hintndx = 0; hintndx < hmeta.dls_cnt; hintndx++, hintpath++) {
2169 SLPpath = &SLPinfo->dls_serpath[0];
2171 * Check each standard path against current.
2173 for (SLPndx = 0; SLPndx < smeta.dls_cnt; SLPndx++, SLPpath++) {
2174 /* matched, skip the path */
2175 if (!strcmp(hintpath->dls_name, SLPpath->dls_name)) {
2183 * Not matched against any standard path, add the path
2184 * to result. Separate consequtive paths with ':'.
2187 filtered_path[fndx] = ':';
2191 flen = strlen(hintpath->dls_name);
2192 strncpy((filtered_path + fndx), hintpath->dls_name, flen);
2195 filtered_path[fndx] = '\0';
2201 return (filtered_path[0] != '\0' ? filtered_path : NULL);
2205 init_dag(Obj_Entry *root)
2207 const Needed_Entry *needed;
2208 const Objlist_Entry *elm;
2211 if (root->dag_inited)
2213 donelist_init(&donelist);
2215 /* Root object belongs to own DAG. */
2216 objlist_push_tail(&root->dldags, root);
2217 objlist_push_tail(&root->dagmembers, root);
2218 donelist_check(&donelist, root);
2221 * Add dependencies of root object to DAG in breadth order
2222 * by exploiting the fact that each new object get added
2223 * to the tail of the dagmembers list.
2225 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2226 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
2227 if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
2229 objlist_push_tail(&needed->obj->dldags, root);
2230 objlist_push_tail(&root->dagmembers, needed->obj);
2233 root->dag_inited = true;
2237 init_marker(Obj_Entry *marker)
2240 bzero(marker, sizeof(*marker));
2241 marker->marker = true;
2245 globallist_curr(const Obj_Entry *obj)
2252 return (__DECONST(Obj_Entry *, obj));
2253 obj = TAILQ_PREV(obj, obj_entry_q, next);
2258 globallist_next(const Obj_Entry *obj)
2262 obj = TAILQ_NEXT(obj, next);
2266 return (__DECONST(Obj_Entry *, obj));
2270 /* Prevent the object from being unmapped while the bind lock is dropped. */
2272 hold_object(Obj_Entry *obj)
2279 unhold_object(Obj_Entry *obj)
2282 assert(obj->holdcount > 0);
2283 if (--obj->holdcount == 0 && obj->unholdfree)
2284 release_object(obj);
2288 process_z(Obj_Entry *root)
2290 const Objlist_Entry *elm;
2294 * Walk over object DAG and process every dependent object
2295 * that is marked as DF_1_NODELETE or DF_1_GLOBAL. They need
2296 * to grow their own DAG.
2298 * For DF_1_GLOBAL, DAG is required for symbol lookups in
2299 * symlook_global() to work.
2301 * For DF_1_NODELETE, the DAG should have its reference upped.
2303 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2307 if (obj->z_nodelete && !obj->ref_nodel) {
2308 dbg("obj %s -z nodelete", obj->path);
2311 obj->ref_nodel = true;
2313 if (obj->z_global && objlist_find(&list_global, obj) == NULL) {
2314 dbg("obj %s -z global", obj->path);
2315 objlist_push_tail(&list_global, obj);
2322 parse_rtld_phdr(Obj_Entry *obj)
2325 Elf_Addr note_start, note_end;
2327 obj->stack_flags = PF_X | PF_R | PF_W;
2328 for (ph = obj->phdr; (const char *)ph < (const char *)obj->phdr +
2329 obj->phsize; ph++) {
2330 switch (ph->p_type) {
2332 obj->stack_flags = ph->p_flags;
2335 obj->relro_page = obj->relocbase +
2336 trunc_page(ph->p_vaddr);
2337 obj->relro_size = round_page(ph->p_memsz);
2340 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
2341 note_end = note_start + ph->p_filesz;
2342 digest_notes(obj, note_start, note_end);
2349 * Initialize the dynamic linker. The argument is the address at which
2350 * the dynamic linker has been mapped into memory. The primary task of
2351 * this function is to relocate the dynamic linker.
2354 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
2356 Obj_Entry objtmp; /* Temporary rtld object */
2357 const Elf_Ehdr *ehdr;
2358 const Elf_Dyn *dyn_rpath;
2359 const Elf_Dyn *dyn_soname;
2360 const Elf_Dyn *dyn_runpath;
2362 #ifdef RTLD_INIT_PAGESIZES_EARLY
2363 /* The page size is required by the dynamic memory allocator. */
2364 init_pagesizes(aux_info);
2368 * Conjure up an Obj_Entry structure for the dynamic linker.
2370 * The "path" member can't be initialized yet because string constants
2371 * cannot yet be accessed. Below we will set it correctly.
2373 memset(&objtmp, 0, sizeof(objtmp));
2376 objtmp.mapbase = mapbase;
2378 objtmp.relocbase = mapbase;
2381 objtmp.dynamic = rtld_dynamic(&objtmp);
2382 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname, &dyn_runpath);
2383 assert(objtmp.needed == NULL);
2384 #if !defined(__mips__)
2385 /* MIPS has a bogus DT_TEXTREL. */
2386 assert(!objtmp.textrel);
2389 * Temporarily put the dynamic linker entry into the object list, so
2390 * that symbols can be found.
2392 relocate_objects(&objtmp, true, &objtmp, 0, NULL);
2394 ehdr = (Elf_Ehdr *)mapbase;
2395 objtmp.phdr = (Elf_Phdr *)((char *)mapbase + ehdr->e_phoff);
2396 objtmp.phsize = ehdr->e_phnum * sizeof(objtmp.phdr[0]);
2398 /* Initialize the object list. */
2399 TAILQ_INIT(&obj_list);
2401 /* Now that non-local variables can be accesses, copy out obj_rtld. */
2402 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
2404 #ifndef RTLD_INIT_PAGESIZES_EARLY
2405 /* The page size is required by the dynamic memory allocator. */
2406 init_pagesizes(aux_info);
2409 if (aux_info[AT_OSRELDATE] != NULL)
2410 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
2412 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname, dyn_runpath);
2414 /* Replace the path with a dynamically allocated copy. */
2415 obj_rtld.path = xstrdup(ld_path_rtld);
2417 parse_rtld_phdr(&obj_rtld);
2418 if (obj_enforce_relro(&obj_rtld) == -1)
2421 r_debug.r_version = R_DEBUG_VERSION;
2422 r_debug.r_brk = r_debug_state;
2423 r_debug.r_state = RT_CONSISTENT;
2424 r_debug.r_ldbase = obj_rtld.relocbase;
2428 * Retrieve the array of supported page sizes. The kernel provides the page
2429 * sizes in increasing order.
2432 init_pagesizes(Elf_Auxinfo **aux_info)
2434 static size_t psa[MAXPAGESIZES];
2438 if (aux_info[AT_PAGESIZES] != NULL && aux_info[AT_PAGESIZESLEN] !=
2440 size = aux_info[AT_PAGESIZESLEN]->a_un.a_val;
2441 pagesizes = aux_info[AT_PAGESIZES]->a_un.a_ptr;
2444 if (sysctlnametomib("hw.pagesizes", mib, &len) == 0)
2447 /* As a fallback, retrieve the base page size. */
2448 size = sizeof(psa[0]);
2449 if (aux_info[AT_PAGESZ] != NULL) {
2450 psa[0] = aux_info[AT_PAGESZ]->a_un.a_val;
2454 mib[1] = HW_PAGESIZE;
2458 if (sysctl(mib, len, psa, &size, NULL, 0) == -1) {
2459 _rtld_error("sysctl for hw.pagesize(s) failed");
2465 npagesizes = size / sizeof(pagesizes[0]);
2466 /* Discard any invalid entries at the end of the array. */
2467 while (npagesizes > 0 && pagesizes[npagesizes - 1] == 0)
2472 * Add the init functions from a needed object list (and its recursive
2473 * needed objects) to "list". This is not used directly; it is a helper
2474 * function for initlist_add_objects(). The write lock must be held
2475 * when this function is called.
2478 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
2480 /* Recursively process the successor needed objects. */
2481 if (needed->next != NULL)
2482 initlist_add_neededs(needed->next, list);
2484 /* Process the current needed object. */
2485 if (needed->obj != NULL)
2486 initlist_add_objects(needed->obj, needed->obj, list);
2490 * Scan all of the DAGs rooted in the range of objects from "obj" to
2491 * "tail" and add their init functions to "list". This recurses over
2492 * the DAGs and ensure the proper init ordering such that each object's
2493 * needed libraries are initialized before the object itself. At the
2494 * same time, this function adds the objects to the global finalization
2495 * list "list_fini" in the opposite order. The write lock must be
2496 * held when this function is called.
2499 initlist_add_objects(Obj_Entry *obj, Obj_Entry *tail, Objlist *list)
2503 if (obj->init_scanned || obj->init_done)
2505 obj->init_scanned = true;
2507 /* Recursively process the successor objects. */
2508 nobj = globallist_next(obj);
2509 if (nobj != NULL && obj != tail)
2510 initlist_add_objects(nobj, tail, list);
2512 /* Recursively process the needed objects. */
2513 if (obj->needed != NULL)
2514 initlist_add_neededs(obj->needed, list);
2515 if (obj->needed_filtees != NULL)
2516 initlist_add_neededs(obj->needed_filtees, list);
2517 if (obj->needed_aux_filtees != NULL)
2518 initlist_add_neededs(obj->needed_aux_filtees, list);
2520 /* Add the object to the init list. */
2521 objlist_push_tail(list, obj);
2523 /* Add the object to the global fini list in the reverse order. */
2524 if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL)
2525 && !obj->on_fini_list) {
2526 objlist_push_head(&list_fini, obj);
2527 obj->on_fini_list = true;
2532 #define FPTR_TARGET(f) ((Elf_Addr) (f))
2536 free_needed_filtees(Needed_Entry *n, RtldLockState *lockstate)
2538 Needed_Entry *needed, *needed1;
2540 for (needed = n; needed != NULL; needed = needed->next) {
2541 if (needed->obj != NULL) {
2542 dlclose_locked(needed->obj, lockstate);
2546 for (needed = n; needed != NULL; needed = needed1) {
2547 needed1 = needed->next;
2553 unload_filtees(Obj_Entry *obj, RtldLockState *lockstate)
2556 free_needed_filtees(obj->needed_filtees, lockstate);
2557 obj->needed_filtees = NULL;
2558 free_needed_filtees(obj->needed_aux_filtees, lockstate);
2559 obj->needed_aux_filtees = NULL;
2560 obj->filtees_loaded = false;
2564 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags,
2565 RtldLockState *lockstate)
2568 for (; needed != NULL; needed = needed->next) {
2569 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
2570 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
2571 RTLD_LOCAL, lockstate);
2576 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
2579 lock_restart_for_upgrade(lockstate);
2580 if (!obj->filtees_loaded) {
2581 load_filtee1(obj, obj->needed_filtees, flags, lockstate);
2582 load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate);
2583 obj->filtees_loaded = true;
2588 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
2592 for (; needed != NULL; needed = needed->next) {
2593 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
2594 flags & ~RTLD_LO_NOLOAD);
2595 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
2602 * Given a shared object, traverse its list of needed objects, and load
2603 * each of them. Returns 0 on success. Generates an error message and
2604 * returns -1 on failure.
2607 load_needed_objects(Obj_Entry *first, int flags)
2611 for (obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
2614 if (process_needed(obj, obj->needed, flags) == -1)
2621 load_preload_objects(const char *penv, bool isfd)
2626 char savech, *p, *psave;
2628 static const char delim[] = " \t:;";
2633 p = psave = xstrdup(penv);
2634 p += strspn(p, delim);
2635 while (*p != '\0') {
2636 len = strcspn(p, delim);
2642 fd = parse_integer(p);
2652 obj = load_object(name, fd, NULL, 0);
2655 return (-1); /* XXX - cleanup */
2657 obj->z_interpose = true;
2660 p += strspn(p, delim);
2662 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
2669 printable_path(const char *path)
2672 return (path == NULL ? "<unknown>" : path);
2676 * Load a shared object into memory, if it is not already loaded. The
2677 * object may be specified by name or by user-supplied file descriptor
2678 * fd_u. In the later case, the fd_u descriptor is not closed, but its
2681 * Returns a pointer to the Obj_Entry for the object. Returns NULL
2685 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
2694 TAILQ_FOREACH(obj, &obj_list, next) {
2695 if (obj->marker || obj->doomed)
2697 if (object_match_name(obj, name))
2701 path = find_library(name, refobj, &fd);
2709 * search_library_pathfds() opens a fresh file descriptor for the
2710 * library, so there is no need to dup().
2712 } else if (fd_u == -1) {
2714 * If we didn't find a match by pathname, or the name is not
2715 * supplied, open the file and check again by device and inode.
2716 * This avoids false mismatches caused by multiple links or ".."
2719 * To avoid a race, we open the file and use fstat() rather than
2722 if ((fd = open(path, O_RDONLY | O_CLOEXEC | O_VERIFY)) == -1) {
2723 _rtld_error("Cannot open \"%s\"", path);
2728 fd = fcntl(fd_u, F_DUPFD_CLOEXEC, 0);
2730 _rtld_error("Cannot dup fd");
2735 if (fstat(fd, &sb) == -1) {
2736 _rtld_error("Cannot fstat \"%s\"", printable_path(path));
2741 TAILQ_FOREACH(obj, &obj_list, next) {
2742 if (obj->marker || obj->doomed)
2744 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
2747 if (obj != NULL && name != NULL) {
2748 object_add_name(obj, name);
2753 if (flags & RTLD_LO_NOLOAD) {
2759 /* First use of this object, so we must map it in */
2760 obj = do_load_object(fd, name, path, &sb, flags);
2769 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
2776 * First, make sure that environment variables haven't been
2777 * used to circumvent the noexec flag on a filesystem.
2778 * We ignore fstatfs(2) failures, since fd might reference
2779 * not a file, e.g. shmfd.
2781 if (dangerous_ld_env && fstatfs(fd, &fs) == 0 &&
2782 (fs.f_flags & MNT_NOEXEC) != 0) {
2783 _rtld_error("Cannot execute objects on %s", fs.f_mntonname);
2787 dbg("loading \"%s\"", printable_path(path));
2788 obj = map_object(fd, printable_path(path), sbp);
2793 * If DT_SONAME is present in the object, digest_dynamic2 already
2794 * added it to the object names.
2797 object_add_name(obj, name);
2799 if (!digest_dynamic(obj, 0))
2801 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path,
2802 obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount);
2803 if (obj->z_pie && (flags & RTLD_LO_TRACE) == 0) {
2804 dbg("refusing to load PIE executable \"%s\"", obj->path);
2805 _rtld_error("Cannot load PIE binary %s as DSO", obj->path);
2808 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
2810 dbg("refusing to load non-loadable \"%s\"", obj->path);
2811 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
2815 obj->dlopened = (flags & RTLD_LO_DLOPEN) != 0;
2816 TAILQ_INSERT_TAIL(&obj_list, obj, next);
2819 linkmap_add(obj); /* for GDB & dlinfo() */
2820 max_stack_flags |= obj->stack_flags;
2822 dbg(" %p .. %p: %s", obj->mapbase,
2823 obj->mapbase + obj->mapsize - 1, obj->path);
2825 dbg(" WARNING: %s has impure text", obj->path);
2826 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
2832 munmap(obj->mapbase, obj->mapsize);
2838 obj_from_addr(const void *addr)
2842 TAILQ_FOREACH(obj, &obj_list, next) {
2845 if (addr < (void *) obj->mapbase)
2847 if (addr < (void *)(obj->mapbase + obj->mapsize))
2856 Elf_Addr *preinit_addr;
2859 preinit_addr = (Elf_Addr *)obj_main->preinit_array;
2860 if (preinit_addr == NULL)
2863 for (index = 0; index < obj_main->preinit_array_num; index++) {
2864 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) {
2865 dbg("calling preinit function for %s at %p", obj_main->path,
2866 (void *)preinit_addr[index]);
2867 LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index],
2868 0, 0, obj_main->path);
2869 call_init_pointer(obj_main, preinit_addr[index]);
2875 * Call the finalization functions for each of the objects in "list"
2876 * belonging to the DAG of "root" and referenced once. If NULL "root"
2877 * is specified, every finalization function will be called regardless
2878 * of the reference count and the list elements won't be freed. All of
2879 * the objects are expected to have non-NULL fini functions.
2882 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
2885 struct dlerror_save *saved_msg;
2886 Elf_Addr *fini_addr;
2889 assert(root == NULL || root->refcount == 1);
2892 root->doomed = true;
2895 * Preserve the current error message since a fini function might
2896 * call into the dynamic linker and overwrite it.
2898 saved_msg = errmsg_save();
2900 STAILQ_FOREACH(elm, list, link) {
2901 if (root != NULL && (elm->obj->refcount != 1 ||
2902 objlist_find(&root->dagmembers, elm->obj) == NULL))
2904 /* Remove object from fini list to prevent recursive invocation. */
2905 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2906 /* Ensure that new references cannot be acquired. */
2907 elm->obj->doomed = true;
2909 hold_object(elm->obj);
2910 lock_release(rtld_bind_lock, lockstate);
2912 * It is legal to have both DT_FINI and DT_FINI_ARRAY defined.
2913 * When this happens, DT_FINI_ARRAY is processed first.
2915 fini_addr = (Elf_Addr *)elm->obj->fini_array;
2916 if (fini_addr != NULL && elm->obj->fini_array_num > 0) {
2917 for (index = elm->obj->fini_array_num - 1; index >= 0;
2919 if (fini_addr[index] != 0 && fini_addr[index] != 1) {
2920 dbg("calling fini function for %s at %p",
2921 elm->obj->path, (void *)fini_addr[index]);
2922 LD_UTRACE(UTRACE_FINI_CALL, elm->obj,
2923 (void *)fini_addr[index], 0, 0, elm->obj->path);
2924 call_initfini_pointer(elm->obj, fini_addr[index]);
2928 if (elm->obj->fini != (Elf_Addr)NULL) {
2929 dbg("calling fini function for %s at %p", elm->obj->path,
2930 (void *)elm->obj->fini);
2931 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini,
2932 0, 0, elm->obj->path);
2933 call_initfini_pointer(elm->obj, elm->obj->fini);
2935 wlock_acquire(rtld_bind_lock, lockstate);
2936 unhold_object(elm->obj);
2937 /* No need to free anything if process is going down. */
2941 * We must restart the list traversal after every fini call
2942 * because a dlclose() call from the fini function or from
2943 * another thread might have modified the reference counts.
2947 } while (elm != NULL);
2948 errmsg_restore(saved_msg);
2952 * Call the initialization functions for each of the objects in
2953 * "list". All of the objects are expected to have non-NULL init
2957 objlist_call_init(Objlist *list, RtldLockState *lockstate)
2961 struct dlerror_save *saved_msg;
2962 Elf_Addr *init_addr;
2963 void (*reg)(void (*)(void));
2967 * Clean init_scanned flag so that objects can be rechecked and
2968 * possibly initialized earlier if any of vectors called below
2969 * cause the change by using dlopen.
2971 TAILQ_FOREACH(obj, &obj_list, next) {
2974 obj->init_scanned = false;
2978 * Preserve the current error message since an init function might
2979 * call into the dynamic linker and overwrite it.
2981 saved_msg = errmsg_save();
2982 STAILQ_FOREACH(elm, list, link) {
2983 if (elm->obj->init_done) /* Initialized early. */
2986 * Race: other thread might try to use this object before current
2987 * one completes the initialization. Not much can be done here
2988 * without better locking.
2990 elm->obj->init_done = true;
2991 hold_object(elm->obj);
2993 if (elm->obj == obj_main && obj_main->crt_no_init) {
2994 reg = (void (*)(void (*)(void)))get_program_var_addr(
2995 "__libc_atexit", lockstate);
2997 lock_release(rtld_bind_lock, lockstate);
3000 rtld_exit_ptr = rtld_nop_exit;
3004 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined.
3005 * When this happens, DT_INIT is processed first.
3007 if (elm->obj->init != (Elf_Addr)NULL) {
3008 dbg("calling init function for %s at %p", elm->obj->path,
3009 (void *)elm->obj->init);
3010 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init,
3011 0, 0, elm->obj->path);
3012 call_init_pointer(elm->obj, elm->obj->init);
3014 init_addr = (Elf_Addr *)elm->obj->init_array;
3015 if (init_addr != NULL) {
3016 for (index = 0; index < elm->obj->init_array_num; index++) {
3017 if (init_addr[index] != 0 && init_addr[index] != 1) {
3018 dbg("calling init function for %s at %p", elm->obj->path,
3019 (void *)init_addr[index]);
3020 LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
3021 (void *)init_addr[index], 0, 0, elm->obj->path);
3022 call_init_pointer(elm->obj, init_addr[index]);
3026 wlock_acquire(rtld_bind_lock, lockstate);
3027 unhold_object(elm->obj);
3029 errmsg_restore(saved_msg);
3033 objlist_clear(Objlist *list)
3037 while (!STAILQ_EMPTY(list)) {
3038 elm = STAILQ_FIRST(list);
3039 STAILQ_REMOVE_HEAD(list, link);
3044 static Objlist_Entry *
3045 objlist_find(Objlist *list, const Obj_Entry *obj)
3049 STAILQ_FOREACH(elm, list, link)
3050 if (elm->obj == obj)
3056 objlist_init(Objlist *list)
3062 objlist_push_head(Objlist *list, Obj_Entry *obj)
3066 elm = NEW(Objlist_Entry);
3068 STAILQ_INSERT_HEAD(list, elm, link);
3072 objlist_push_tail(Objlist *list, Obj_Entry *obj)
3076 elm = NEW(Objlist_Entry);
3078 STAILQ_INSERT_TAIL(list, elm, link);
3082 objlist_put_after(Objlist *list, Obj_Entry *listobj, Obj_Entry *obj)
3084 Objlist_Entry *elm, *listelm;
3086 STAILQ_FOREACH(listelm, list, link) {
3087 if (listelm->obj == listobj)
3090 elm = NEW(Objlist_Entry);
3092 if (listelm != NULL)
3093 STAILQ_INSERT_AFTER(list, listelm, elm, link);
3095 STAILQ_INSERT_TAIL(list, elm, link);
3099 objlist_remove(Objlist *list, Obj_Entry *obj)
3103 if ((elm = objlist_find(list, obj)) != NULL) {
3104 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
3110 * Relocate dag rooted in the specified object.
3111 * Returns 0 on success, or -1 on failure.
3115 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj,
3116 int flags, RtldLockState *lockstate)
3122 STAILQ_FOREACH(elm, &root->dagmembers, link) {
3123 error = relocate_object(elm->obj, bind_now, rtldobj, flags,
3132 * Prepare for, or clean after, relocating an object marked with
3133 * DT_TEXTREL or DF_TEXTREL. Before relocating, all read-only
3134 * segments are remapped read-write. After relocations are done, the
3135 * segment's permissions are returned back to the modes specified in
3136 * the phdrs. If any relocation happened, or always for wired
3137 * program, COW is triggered.
3140 reloc_textrel_prot(Obj_Entry *obj, bool before)
3147 for (l = obj->phsize / sizeof(*ph), ph = obj->phdr; l > 0;
3149 if (ph->p_type != PT_LOAD || (ph->p_flags & PF_W) != 0)
3151 base = obj->relocbase + trunc_page(ph->p_vaddr);
3152 sz = round_page(ph->p_vaddr + ph->p_filesz) -
3153 trunc_page(ph->p_vaddr);
3154 prot = before ? (PROT_READ | PROT_WRITE) :
3155 convert_prot(ph->p_flags);
3156 if (mprotect(base, sz, prot) == -1) {
3157 _rtld_error("%s: Cannot write-%sable text segment: %s",
3158 obj->path, before ? "en" : "dis",
3159 rtld_strerror(errno));
3166 /* Process RELR relative relocations. */
3168 reloc_relr(Obj_Entry *obj)
3170 const Elf_Relr *relr, *relrlim;
3173 relrlim = (const Elf_Relr *)((const char *)obj->relr + obj->relrsize);
3174 for (relr = obj->relr; relr < relrlim; relr++) {
3175 Elf_Relr entry = *relr;
3177 if ((entry & 1) == 0) {
3178 where = (Elf_Addr *)(obj->relocbase + entry);
3179 *where++ += (Elf_Addr)obj->relocbase;
3181 for (long i = 0; (entry >>= 1) != 0; i++)
3182 if ((entry & 1) != 0)
3183 where[i] += (Elf_Addr)obj->relocbase;
3184 where += CHAR_BIT * sizeof(Elf_Relr) - 1;
3190 * Relocate single object.
3191 * Returns 0 on success, or -1 on failure.
3194 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
3195 int flags, RtldLockState *lockstate)
3200 obj->relocated = true;
3202 dbg("relocating \"%s\"", obj->path);
3204 if (obj->symtab == NULL || obj->strtab == NULL ||
3205 !(obj->valid_hash_sysv || obj->valid_hash_gnu))
3206 dbg("object %s has no run-time symbol table", obj->path);
3208 /* There are relocations to the write-protected text segment. */
3209 if (obj->textrel && reloc_textrel_prot(obj, true) != 0)
3212 /* Process the non-PLT non-IFUNC relocations. */
3213 if (reloc_non_plt(obj, rtldobj, flags, lockstate))
3217 /* Re-protected the text segment. */
3218 if (obj->textrel && reloc_textrel_prot(obj, false) != 0)
3221 /* Set the special PLT or GOT entries. */
3224 /* Process the PLT relocations. */
3225 if (reloc_plt(obj, flags, lockstate) == -1)
3227 /* Relocate the jump slots if we are doing immediate binding. */
3228 if ((obj->bind_now || bind_now) && reloc_jmpslots(obj, flags,
3232 if (!obj->mainprog && obj_enforce_relro(obj) == -1)
3236 * Set up the magic number and version in the Obj_Entry. These
3237 * were checked in the crt1.o from the original ElfKit, so we
3238 * set them for backward compatibility.
3240 obj->magic = RTLD_MAGIC;
3241 obj->version = RTLD_VERSION;
3247 * Relocate newly-loaded shared objects. The argument is a pointer to
3248 * the Obj_Entry for the first such object. All objects from the first
3249 * to the end of the list of objects are relocated. Returns 0 on success,
3253 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
3254 int flags, RtldLockState *lockstate)
3259 for (error = 0, obj = first; obj != NULL;
3260 obj = TAILQ_NEXT(obj, next)) {
3263 error = relocate_object(obj, bind_now, rtldobj, flags,
3272 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
3273 * referencing STT_GNU_IFUNC symbols is postponed till the other
3274 * relocations are done. The indirect functions specified as
3275 * ifunc are allowed to call other symbols, so we need to have
3276 * objects relocated before asking for resolution from indirects.
3278 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
3279 * instead of the usual lazy handling of PLT slots. It is
3280 * consistent with how GNU does it.
3283 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags,
3284 RtldLockState *lockstate)
3287 if (obj->ifuncs_resolved)
3289 obj->ifuncs_resolved = true;
3290 if (!obj->irelative && !obj->irelative_nonplt &&
3291 !((obj->bind_now || bind_now) && obj->gnu_ifunc) &&
3292 !obj->non_plt_gnu_ifunc)
3294 if (obj_disable_relro(obj) == -1 ||
3295 (obj->irelative && reloc_iresolve(obj, lockstate) == -1) ||
3296 (obj->irelative_nonplt && reloc_iresolve_nonplt(obj,
3297 lockstate) == -1) ||
3298 ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
3299 reloc_gnu_ifunc(obj, flags, lockstate) == -1) ||
3300 (obj->non_plt_gnu_ifunc && reloc_non_plt(obj, &obj_rtld,
3301 flags | SYMLOOK_IFUNC, lockstate) == -1) ||
3302 obj_enforce_relro(obj) == -1)
3308 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags,
3309 RtldLockState *lockstate)
3314 STAILQ_FOREACH(elm, list, link) {
3318 if (resolve_object_ifunc(obj, bind_now, flags,
3326 * Cleanup procedure. It will be called (by the atexit mechanism) just
3327 * before the process exits.
3332 RtldLockState lockstate;
3334 wlock_acquire(rtld_bind_lock, &lockstate);
3336 objlist_call_fini(&list_fini, NULL, &lockstate);
3337 /* No need to remove the items from the list, since we are exiting. */
3338 if (!libmap_disable)
3340 lock_release(rtld_bind_lock, &lockstate);
3349 * Iterate over a search path, translate each element, and invoke the
3350 * callback on the result.
3353 path_enumerate(const char *path, path_enum_proc callback,
3354 const char *refobj_path, void *arg)
3360 path += strspn(path, ":;");
3361 while (*path != '\0') {
3365 len = strcspn(path, ":;");
3366 trans = lm_findn(refobj_path, path, len);
3368 res = callback(trans, strlen(trans), arg);
3370 res = callback(path, len, arg);
3376 path += strspn(path, ":;");
3382 struct try_library_args {
3391 try_library_path(const char *dir, size_t dirlen, void *param)
3393 struct try_library_args *arg;
3397 if (*dir == '/' || trust) {
3400 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
3403 pathname = arg->buffer;
3404 strncpy(pathname, dir, dirlen);
3405 pathname[dirlen] = '/';
3406 strcpy(pathname + dirlen + 1, arg->name);
3408 dbg(" Trying \"%s\"", pathname);
3409 fd = open(pathname, O_RDONLY | O_CLOEXEC | O_VERIFY);
3411 dbg(" Opened \"%s\", fd %d", pathname, fd);
3412 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
3413 strcpy(pathname, arg->buffer);
3417 dbg(" Failed to open \"%s\": %s",
3418 pathname, rtld_strerror(errno));
3425 search_library_path(const char *name, const char *path,
3426 const char *refobj_path, int *fdp)
3429 struct try_library_args arg;
3435 arg.namelen = strlen(name);
3436 arg.buffer = xmalloc(PATH_MAX);
3437 arg.buflen = PATH_MAX;
3440 p = path_enumerate(path, try_library_path, refobj_path, &arg);
3450 * Finds the library with the given name using the directory descriptors
3451 * listed in the LD_LIBRARY_PATH_FDS environment variable.
3453 * Returns a freshly-opened close-on-exec file descriptor for the library,
3454 * or -1 if the library cannot be found.
3457 search_library_pathfds(const char *name, const char *path, int *fdp)
3459 char *envcopy, *fdstr, *found, *last_token;
3463 dbg("%s('%s', '%s', fdp)", __func__, name, path);
3465 /* Don't load from user-specified libdirs into setuid binaries. */
3469 /* We can't do anything if LD_LIBRARY_PATH_FDS isn't set. */
3473 /* LD_LIBRARY_PATH_FDS only works with relative paths. */
3474 if (name[0] == '/') {
3475 dbg("Absolute path (%s) passed to %s", name, __func__);
3480 * Use strtok_r() to walk the FD:FD:FD list. This requires a local
3481 * copy of the path, as strtok_r rewrites separator tokens
3485 envcopy = xstrdup(path);
3486 for (fdstr = strtok_r(envcopy, ":", &last_token); fdstr != NULL;
3487 fdstr = strtok_r(NULL, ":", &last_token)) {
3488 dirfd = parse_integer(fdstr);
3490 _rtld_error("failed to parse directory FD: '%s'",
3494 fd = __sys_openat(dirfd, name, O_RDONLY | O_CLOEXEC | O_VERIFY);
3497 len = strlen(fdstr) + strlen(name) + 3;
3498 found = xmalloc(len);
3499 if (rtld_snprintf(found, len, "#%d/%s", dirfd, name) < 0) {
3500 _rtld_error("error generating '%d/%s'",
3504 dbg("open('%s') => %d", found, fd);
3515 dlclose(void *handle)
3517 RtldLockState lockstate;
3520 wlock_acquire(rtld_bind_lock, &lockstate);
3521 error = dlclose_locked(handle, &lockstate);
3522 lock_release(rtld_bind_lock, &lockstate);
3527 dlclose_locked(void *handle, RtldLockState *lockstate)
3531 root = dlcheck(handle);
3534 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
3537 /* Unreference the object and its dependencies. */
3538 root->dl_refcount--;
3540 if (root->refcount == 1) {
3542 * The object will be no longer referenced, so we must unload it.
3543 * First, call the fini functions.
3545 objlist_call_fini(&list_fini, root, lockstate);
3549 /* Finish cleaning up the newly-unreferenced objects. */
3550 GDB_STATE(RT_DELETE,&root->linkmap);
3551 unload_object(root, lockstate);
3552 GDB_STATE(RT_CONSISTENT,NULL);
3556 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
3563 if (*(lockinfo.dlerror_seen()) != 0)
3565 *lockinfo.dlerror_seen() = 1;
3566 return (lockinfo.dlerror_loc());
3570 * This function is deprecated and has no effect.
3573 dllockinit(void *context,
3574 void *(*_lock_create)(void *context) __unused,
3575 void (*_rlock_acquire)(void *lock) __unused,
3576 void (*_wlock_acquire)(void *lock) __unused,
3577 void (*_lock_release)(void *lock) __unused,
3578 void (*_lock_destroy)(void *lock) __unused,
3579 void (*context_destroy)(void *context))
3581 static void *cur_context;
3582 static void (*cur_context_destroy)(void *);
3584 /* Just destroy the context from the previous call, if necessary. */
3585 if (cur_context_destroy != NULL)
3586 cur_context_destroy(cur_context);
3587 cur_context = context;
3588 cur_context_destroy = context_destroy;
3592 dlopen(const char *name, int mode)
3595 return (rtld_dlopen(name, -1, mode));
3599 fdlopen(int fd, int mode)
3602 return (rtld_dlopen(NULL, fd, mode));
3606 rtld_dlopen(const char *name, int fd, int mode)
3608 RtldLockState lockstate;
3611 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
3612 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
3613 if (ld_tracing != NULL) {
3614 rlock_acquire(rtld_bind_lock, &lockstate);
3615 if (sigsetjmp(lockstate.env, 0) != 0)
3616 lock_upgrade(rtld_bind_lock, &lockstate);
3617 environ = __DECONST(char **, *get_program_var_addr("environ", &lockstate));
3618 lock_release(rtld_bind_lock, &lockstate);
3620 lo_flags = RTLD_LO_DLOPEN;
3621 if (mode & RTLD_NODELETE)
3622 lo_flags |= RTLD_LO_NODELETE;
3623 if (mode & RTLD_NOLOAD)
3624 lo_flags |= RTLD_LO_NOLOAD;
3625 if (mode & RTLD_DEEPBIND)
3626 lo_flags |= RTLD_LO_DEEPBIND;
3627 if (ld_tracing != NULL)
3628 lo_flags |= RTLD_LO_TRACE | RTLD_LO_IGNSTLS;
3630 return (dlopen_object(name, fd, obj_main, lo_flags,
3631 mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL));
3635 dlopen_cleanup(Obj_Entry *obj, RtldLockState *lockstate)
3640 if (obj->refcount == 0)
3641 unload_object(obj, lockstate);
3645 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
3646 int mode, RtldLockState *lockstate)
3648 Obj_Entry *old_obj_tail;
3651 RtldLockState mlockstate;
3654 dbg("dlopen_object name \"%s\" fd %d refobj \"%s\" lo_flags %#x mode %#x",
3655 name != NULL ? name : "<null>", fd, refobj == NULL ? "<null>" :
3656 refobj->path, lo_flags, mode);
3657 objlist_init(&initlist);
3659 if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) {
3660 wlock_acquire(rtld_bind_lock, &mlockstate);
3661 lockstate = &mlockstate;
3663 GDB_STATE(RT_ADD,NULL);
3665 old_obj_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
3667 if (name == NULL && fd == -1) {
3671 obj = load_object(name, fd, refobj, lo_flags);
3676 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
3677 objlist_push_tail(&list_global, obj);
3678 if (globallist_next(old_obj_tail) != NULL) {
3679 /* We loaded something new. */
3680 assert(globallist_next(old_obj_tail) == obj);
3681 if ((lo_flags & RTLD_LO_DEEPBIND) != 0)
3682 obj->symbolic = true;
3684 if ((lo_flags & (RTLD_LO_EARLY | RTLD_LO_IGNSTLS)) == 0 &&
3685 obj->static_tls && !allocate_tls_offset(obj)) {
3686 _rtld_error("%s: No space available "
3687 "for static Thread Local Storage", obj->path);
3691 result = load_needed_objects(obj, lo_flags & (RTLD_LO_DLOPEN |
3692 RTLD_LO_EARLY | RTLD_LO_IGNSTLS | RTLD_LO_TRACE));
3696 result = rtld_verify_versions(&obj->dagmembers);
3697 if (result != -1 && ld_tracing)
3699 if (result == -1 || relocate_object_dag(obj,
3700 (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld,
3701 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3703 dlopen_cleanup(obj, lockstate);
3705 } else if (lo_flags & RTLD_LO_EARLY) {
3707 * Do not call the init functions for early loaded
3708 * filtees. The image is still not initialized enough
3711 * Our object is found by the global object list and
3712 * will be ordered among all init calls done right
3713 * before transferring control to main.
3716 /* Make list of init functions to call. */
3717 initlist_add_objects(obj, obj, &initlist);
3720 * Process all no_delete or global objects here, given
3721 * them own DAGs to prevent their dependencies from being
3722 * unloaded. This has to be done after we have loaded all
3723 * of the dependencies, so that we do not miss any.
3729 * Bump the reference counts for objects on this DAG. If
3730 * this is the first dlopen() call for the object that was
3731 * already loaded as a dependency, initialize the dag
3737 if ((lo_flags & RTLD_LO_TRACE) != 0)
3740 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
3741 obj->z_nodelete) && !obj->ref_nodel) {
3742 dbg("obj %s nodelete", obj->path);
3744 obj->z_nodelete = obj->ref_nodel = true;
3748 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
3750 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
3752 if ((lo_flags & RTLD_LO_EARLY) == 0) {
3753 map_stacks_exec(lockstate);
3755 distribute_static_tls(&initlist, lockstate);
3758 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
3759 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3761 objlist_clear(&initlist);
3762 dlopen_cleanup(obj, lockstate);
3763 if (lockstate == &mlockstate)
3764 lock_release(rtld_bind_lock, lockstate);
3768 if (!(lo_flags & RTLD_LO_EARLY)) {
3769 /* Call the init functions. */
3770 objlist_call_init(&initlist, lockstate);
3772 objlist_clear(&initlist);
3773 if (lockstate == &mlockstate)
3774 lock_release(rtld_bind_lock, lockstate);
3777 trace_loaded_objects(obj);
3778 if (lockstate == &mlockstate)
3779 lock_release(rtld_bind_lock, lockstate);
3784 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
3788 const Obj_Entry *obj, *defobj;
3791 RtldLockState lockstate;
3798 symlook_init(&req, name);
3800 req.flags = flags | SYMLOOK_IN_PLT;
3801 req.lockstate = &lockstate;
3803 LD_UTRACE(UTRACE_DLSYM_START, handle, NULL, 0, 0, name);
3804 rlock_acquire(rtld_bind_lock, &lockstate);
3805 if (sigsetjmp(lockstate.env, 0) != 0)
3806 lock_upgrade(rtld_bind_lock, &lockstate);
3807 if (handle == NULL || handle == RTLD_NEXT ||
3808 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
3810 if ((obj = obj_from_addr(retaddr)) == NULL) {
3811 _rtld_error("Cannot determine caller's shared object");
3812 lock_release(rtld_bind_lock, &lockstate);
3813 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3816 if (handle == NULL) { /* Just the caller's shared object. */
3817 res = symlook_obj(&req, obj);
3820 defobj = req.defobj_out;
3822 } else if (handle == RTLD_NEXT || /* Objects after caller's */
3823 handle == RTLD_SELF) { /* ... caller included */
3824 if (handle == RTLD_NEXT)
3825 obj = globallist_next(obj);
3826 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
3829 res = symlook_obj(&req, obj);
3831 if (def == NULL || (ld_dynamic_weak &&
3832 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK)) {
3834 defobj = req.defobj_out;
3835 if (!ld_dynamic_weak ||
3836 ELF_ST_BIND(def->st_info) != STB_WEAK)
3842 * Search the dynamic linker itself, and possibly resolve the
3843 * symbol from there. This is how the application links to
3844 * dynamic linker services such as dlopen.
3845 * Note that we ignore ld_dynamic_weak == false case,
3846 * always overriding weak symbols by rtld definitions.
3848 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3849 res = symlook_obj(&req, &obj_rtld);
3852 defobj = req.defobj_out;
3856 assert(handle == RTLD_DEFAULT);
3857 res = symlook_default(&req, obj);
3859 defobj = req.defobj_out;
3864 if ((obj = dlcheck(handle)) == NULL) {
3865 lock_release(rtld_bind_lock, &lockstate);
3866 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3870 donelist_init(&donelist);
3871 if (obj->mainprog) {
3872 /* Handle obtained by dlopen(NULL, ...) implies global scope. */
3873 res = symlook_global(&req, &donelist);
3876 defobj = req.defobj_out;
3879 * Search the dynamic linker itself, and possibly resolve the
3880 * symbol from there. This is how the application links to
3881 * dynamic linker services such as dlopen.
3883 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3884 res = symlook_obj(&req, &obj_rtld);
3887 defobj = req.defobj_out;
3892 /* Search the whole DAG rooted at the given object. */
3893 res = symlook_list(&req, &obj->dagmembers, &donelist);
3896 defobj = req.defobj_out;
3902 lock_release(rtld_bind_lock, &lockstate);
3905 * The value required by the caller is derived from the value
3906 * of the symbol. this is simply the relocated value of the
3909 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
3910 sym = make_function_pointer(def, defobj);
3911 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
3912 sym = rtld_resolve_ifunc(defobj, def);
3913 else if (ELF_ST_TYPE(def->st_info) == STT_TLS) {
3914 ti.ti_module = defobj->tlsindex;
3915 ti.ti_offset = def->st_value;
3916 sym = __tls_get_addr(&ti);
3918 sym = defobj->relocbase + def->st_value;
3919 LD_UTRACE(UTRACE_DLSYM_STOP, handle, sym, 0, 0, name);
3923 _rtld_error("Undefined symbol \"%s%s%s\"", name, ve != NULL ? "@" : "",
3924 ve != NULL ? ve->name : "");
3925 lock_release(rtld_bind_lock, &lockstate);
3926 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3931 dlsym(void *handle, const char *name)
3933 return do_dlsym(handle, name, __builtin_return_address(0), NULL,
3938 dlfunc(void *handle, const char *name)
3945 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
3951 dlvsym(void *handle, const char *name, const char *version)
3955 ventry.name = version;
3957 ventry.hash = elf_hash(version);
3959 return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
3964 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
3966 const Obj_Entry *obj;
3967 RtldLockState lockstate;
3969 rlock_acquire(rtld_bind_lock, &lockstate);
3970 obj = obj_from_addr(addr);
3972 _rtld_error("No shared object contains address");
3973 lock_release(rtld_bind_lock, &lockstate);
3976 rtld_fill_dl_phdr_info(obj, phdr_info);
3977 lock_release(rtld_bind_lock, &lockstate);
3982 dladdr(const void *addr, Dl_info *info)
3984 const Obj_Entry *obj;
3987 unsigned long symoffset;
3988 RtldLockState lockstate;
3990 rlock_acquire(rtld_bind_lock, &lockstate);
3991 obj = obj_from_addr(addr);
3993 _rtld_error("No shared object contains address");
3994 lock_release(rtld_bind_lock, &lockstate);
3997 info->dli_fname = obj->path;
3998 info->dli_fbase = obj->mapbase;
3999 info->dli_saddr = (void *)0;
4000 info->dli_sname = NULL;
4003 * Walk the symbol list looking for the symbol whose address is
4004 * closest to the address sent in.
4006 for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) {
4007 def = obj->symtab + symoffset;
4010 * For skip the symbol if st_shndx is either SHN_UNDEF or
4013 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
4017 * If the symbol is greater than the specified address, or if it
4018 * is further away from addr than the current nearest symbol,
4021 symbol_addr = obj->relocbase + def->st_value;
4022 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
4025 /* Update our idea of the nearest symbol. */
4026 info->dli_sname = obj->strtab + def->st_name;
4027 info->dli_saddr = symbol_addr;
4030 if (info->dli_saddr == addr)
4033 lock_release(rtld_bind_lock, &lockstate);
4038 dlinfo(void *handle, int request, void *p)
4040 const Obj_Entry *obj;
4041 RtldLockState lockstate;
4044 rlock_acquire(rtld_bind_lock, &lockstate);
4046 if (handle == NULL || handle == RTLD_SELF) {
4049 retaddr = __builtin_return_address(0); /* __GNUC__ only */
4050 if ((obj = obj_from_addr(retaddr)) == NULL)
4051 _rtld_error("Cannot determine caller's shared object");
4053 obj = dlcheck(handle);
4056 lock_release(rtld_bind_lock, &lockstate);
4062 case RTLD_DI_LINKMAP:
4063 *((struct link_map const **)p) = &obj->linkmap;
4065 case RTLD_DI_ORIGIN:
4066 error = rtld_dirname(obj->path, p);
4069 case RTLD_DI_SERINFOSIZE:
4070 case RTLD_DI_SERINFO:
4071 error = do_search_info(obj, request, (struct dl_serinfo *)p);
4075 _rtld_error("Invalid request %d passed to dlinfo()", request);
4079 lock_release(rtld_bind_lock, &lockstate);
4085 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
4089 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
4090 phdr_info->dlpi_name = obj->path;
4091 phdr_info->dlpi_phdr = obj->phdr;
4092 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
4093 phdr_info->dlpi_tls_modid = obj->tlsindex;
4095 phdr_info->dlpi_tls_data = (char *)tls_get_addr_slow(dtvp,
4096 obj->tlsindex, 0, true) + TLS_DTV_OFFSET;
4097 phdr_info->dlpi_adds = obj_loads;
4098 phdr_info->dlpi_subs = obj_loads - obj_count;
4102 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
4104 struct dl_phdr_info phdr_info;
4105 Obj_Entry *obj, marker;
4106 RtldLockState bind_lockstate, phdr_lockstate;
4109 init_marker(&marker);
4112 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
4113 wlock_acquire(rtld_bind_lock, &bind_lockstate);
4114 for (obj = globallist_curr(TAILQ_FIRST(&obj_list)); obj != NULL;) {
4115 TAILQ_INSERT_AFTER(&obj_list, obj, &marker, next);
4116 rtld_fill_dl_phdr_info(obj, &phdr_info);
4118 lock_release(rtld_bind_lock, &bind_lockstate);
4120 error = callback(&phdr_info, sizeof phdr_info, param);
4122 wlock_acquire(rtld_bind_lock, &bind_lockstate);
4124 obj = globallist_next(&marker);
4125 TAILQ_REMOVE(&obj_list, &marker, next);
4127 lock_release(rtld_bind_lock, &bind_lockstate);
4128 lock_release(rtld_phdr_lock, &phdr_lockstate);
4134 rtld_fill_dl_phdr_info(&obj_rtld, &phdr_info);
4135 lock_release(rtld_bind_lock, &bind_lockstate);
4136 error = callback(&phdr_info, sizeof(phdr_info), param);
4138 lock_release(rtld_phdr_lock, &phdr_lockstate);
4143 fill_search_info(const char *dir, size_t dirlen, void *param)
4145 struct fill_search_info_args *arg;
4149 if (arg->request == RTLD_DI_SERINFOSIZE) {
4150 arg->serinfo->dls_cnt ++;
4151 arg->serinfo->dls_size += sizeof(struct dl_serpath) + dirlen + 1;
4153 struct dl_serpath *s_entry;
4155 s_entry = arg->serpath;
4156 s_entry->dls_name = arg->strspace;
4157 s_entry->dls_flags = arg->flags;
4159 strncpy(arg->strspace, dir, dirlen);
4160 arg->strspace[dirlen] = '\0';
4162 arg->strspace += dirlen + 1;
4170 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
4172 struct dl_serinfo _info;
4173 struct fill_search_info_args args;
4175 args.request = RTLD_DI_SERINFOSIZE;
4176 args.serinfo = &_info;
4178 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
4181 path_enumerate(obj->rpath, fill_search_info, NULL, &args);
4182 path_enumerate(ld_library_path, fill_search_info, NULL, &args);
4183 path_enumerate(obj->runpath, fill_search_info, NULL, &args);
4184 path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args);
4185 if (!obj->z_nodeflib)
4186 path_enumerate(ld_standard_library_path, fill_search_info, NULL, &args);
4189 if (request == RTLD_DI_SERINFOSIZE) {
4190 info->dls_size = _info.dls_size;
4191 info->dls_cnt = _info.dls_cnt;
4195 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
4196 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
4200 args.request = RTLD_DI_SERINFO;
4201 args.serinfo = info;
4202 args.serpath = &info->dls_serpath[0];
4203 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
4205 args.flags = LA_SER_RUNPATH;
4206 if (path_enumerate(obj->rpath, fill_search_info, NULL, &args) != NULL)
4209 args.flags = LA_SER_LIBPATH;
4210 if (path_enumerate(ld_library_path, fill_search_info, NULL, &args) != NULL)
4213 args.flags = LA_SER_RUNPATH;
4214 if (path_enumerate(obj->runpath, fill_search_info, NULL, &args) != NULL)
4217 args.flags = LA_SER_CONFIG;
4218 if (path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args)
4222 args.flags = LA_SER_DEFAULT;
4223 if (!obj->z_nodeflib && path_enumerate(ld_standard_library_path,
4224 fill_search_info, NULL, &args) != NULL)
4230 rtld_dirname(const char *path, char *bname)
4234 /* Empty or NULL string gets treated as "." */
4235 if (path == NULL || *path == '\0') {
4241 /* Strip trailing slashes */
4242 endp = path + strlen(path) - 1;
4243 while (endp > path && *endp == '/')
4246 /* Find the start of the dir */
4247 while (endp > path && *endp != '/')
4250 /* Either the dir is "/" or there are no slashes */
4252 bname[0] = *endp == '/' ? '/' : '.';
4258 } while (endp > path && *endp == '/');
4261 if (endp - path + 2 > PATH_MAX)
4263 _rtld_error("Filename is too long: %s", path);
4267 strncpy(bname, path, endp - path + 1);
4268 bname[endp - path + 1] = '\0';
4273 rtld_dirname_abs(const char *path, char *base)
4277 if (realpath(path, base) == NULL) {
4278 _rtld_error("realpath \"%s\" failed (%s)", path,
4279 rtld_strerror(errno));
4282 dbg("%s -> %s", path, base);
4283 last = strrchr(base, '/');
4285 _rtld_error("non-abs result from realpath \"%s\"", path);
4294 linkmap_add(Obj_Entry *obj)
4296 struct link_map *l, *prev;
4299 l->l_name = obj->path;
4300 l->l_base = obj->mapbase;
4301 l->l_ld = obj->dynamic;
4302 l->l_addr = obj->relocbase;
4304 if (r_debug.r_map == NULL) {
4310 * Scan to the end of the list, but not past the entry for the
4311 * dynamic linker, which we want to keep at the very end.
4313 for (prev = r_debug.r_map;
4314 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
4315 prev = prev->l_next)
4318 /* Link in the new entry. */
4320 l->l_next = prev->l_next;
4321 if (l->l_next != NULL)
4322 l->l_next->l_prev = l;
4327 linkmap_delete(Obj_Entry *obj)
4332 if (l->l_prev == NULL) {
4333 if ((r_debug.r_map = l->l_next) != NULL)
4334 l->l_next->l_prev = NULL;
4338 if ((l->l_prev->l_next = l->l_next) != NULL)
4339 l->l_next->l_prev = l->l_prev;
4343 * Function for the debugger to set a breakpoint on to gain control.
4345 * The two parameters allow the debugger to easily find and determine
4346 * what the runtime loader is doing and to whom it is doing it.
4348 * When the loadhook trap is hit (r_debug_state, set at program
4349 * initialization), the arguments can be found on the stack:
4351 * +8 struct link_map *m
4352 * +4 struct r_debug *rd
4356 r_debug_state(struct r_debug* rd __unused, struct link_map *m __unused)
4359 * The following is a hack to force the compiler to emit calls to
4360 * this function, even when optimizing. If the function is empty,
4361 * the compiler is not obliged to emit any code for calls to it,
4362 * even when marked __noinline. However, gdb depends on those
4365 __compiler_membar();
4369 * A function called after init routines have completed. This can be used to
4370 * break before a program's entry routine is called, and can be used when
4371 * main is not available in the symbol table.
4374 _r_debug_postinit(struct link_map *m __unused)
4377 /* See r_debug_state(). */
4378 __compiler_membar();
4382 release_object(Obj_Entry *obj)
4385 if (obj->holdcount > 0) {
4386 obj->unholdfree = true;
4389 munmap(obj->mapbase, obj->mapsize);
4390 linkmap_delete(obj);
4395 * Get address of the pointer variable in the main program.
4396 * Prefer non-weak symbol over the weak one.
4398 static const void **
4399 get_program_var_addr(const char *name, RtldLockState *lockstate)
4404 symlook_init(&req, name);
4405 req.lockstate = lockstate;
4406 donelist_init(&donelist);
4407 if (symlook_global(&req, &donelist) != 0)
4409 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
4410 return ((const void **)make_function_pointer(req.sym_out,
4412 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
4413 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
4415 return ((const void **)(req.defobj_out->relocbase +
4416 req.sym_out->st_value));
4420 * Set a pointer variable in the main program to the given value. This
4421 * is used to set key variables such as "environ" before any of the
4422 * init functions are called.
4425 set_program_var(const char *name, const void *value)
4429 if ((addr = get_program_var_addr(name, NULL)) != NULL) {
4430 dbg("\"%s\": *%p <-- %p", name, addr, value);
4436 * Search the global objects, including dependencies and main object,
4437 * for the given symbol.
4440 symlook_global(SymLook *req, DoneList *donelist)
4443 const Objlist_Entry *elm;
4446 symlook_init_from_req(&req1, req);
4448 /* Search all objects loaded at program start up. */
4449 if (req->defobj_out == NULL || (ld_dynamic_weak &&
4450 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK)) {
4451 res = symlook_list(&req1, &list_main, donelist);
4452 if (res == 0 && (!ld_dynamic_weak || req->defobj_out == NULL ||
4453 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4454 req->sym_out = req1.sym_out;
4455 req->defobj_out = req1.defobj_out;
4456 assert(req->defobj_out != NULL);
4460 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
4461 STAILQ_FOREACH(elm, &list_global, link) {
4462 if (req->defobj_out != NULL && (!ld_dynamic_weak ||
4463 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK))
4465 res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
4466 if (res == 0 && (req->defobj_out == NULL ||
4467 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4468 req->sym_out = req1.sym_out;
4469 req->defobj_out = req1.defobj_out;
4470 assert(req->defobj_out != NULL);
4474 return (req->sym_out != NULL ? 0 : ESRCH);
4478 * Given a symbol name in a referencing object, find the corresponding
4479 * definition of the symbol. Returns a pointer to the symbol, or NULL if
4480 * no definition was found. Returns a pointer to the Obj_Entry of the
4481 * defining object via the reference parameter DEFOBJ_OUT.
4484 symlook_default(SymLook *req, const Obj_Entry *refobj)
4487 const Objlist_Entry *elm;
4491 donelist_init(&donelist);
4492 symlook_init_from_req(&req1, req);
4495 * Look first in the referencing object if linked symbolically,
4496 * and similarly handle protected symbols.
4498 res = symlook_obj(&req1, refobj);
4499 if (res == 0 && (refobj->symbolic ||
4500 ELF_ST_VISIBILITY(req1.sym_out->st_other) == STV_PROTECTED)) {
4501 req->sym_out = req1.sym_out;
4502 req->defobj_out = req1.defobj_out;
4503 assert(req->defobj_out != NULL);
4505 if (refobj->symbolic || req->defobj_out != NULL)
4506 donelist_check(&donelist, refobj);
4508 symlook_global(req, &donelist);
4510 /* Search all dlopened DAGs containing the referencing object. */
4511 STAILQ_FOREACH(elm, &refobj->dldags, link) {
4512 if (req->sym_out != NULL && (!ld_dynamic_weak ||
4513 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK))
4515 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
4516 if (res == 0 && (req->sym_out == NULL ||
4517 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4518 req->sym_out = req1.sym_out;
4519 req->defobj_out = req1.defobj_out;
4520 assert(req->defobj_out != NULL);
4525 * Search the dynamic linker itself, and possibly resolve the
4526 * symbol from there. This is how the application links to
4527 * dynamic linker services such as dlopen.
4529 if (req->sym_out == NULL ||
4530 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
4531 res = symlook_obj(&req1, &obj_rtld);
4533 req->sym_out = req1.sym_out;
4534 req->defobj_out = req1.defobj_out;
4535 assert(req->defobj_out != NULL);
4539 return (req->sym_out != NULL ? 0 : ESRCH);
4543 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
4546 const Obj_Entry *defobj;
4547 const Objlist_Entry *elm;
4553 STAILQ_FOREACH(elm, objlist, link) {
4554 if (donelist_check(dlp, elm->obj))
4556 symlook_init_from_req(&req1, req);
4557 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
4558 if (def == NULL || (ld_dynamic_weak &&
4559 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4561 defobj = req1.defobj_out;
4562 if (!ld_dynamic_weak || ELF_ST_BIND(def->st_info) != STB_WEAK)
4569 req->defobj_out = defobj;
4576 * Search the chain of DAGS cointed to by the given Needed_Entry
4577 * for a symbol of the given name. Each DAG is scanned completely
4578 * before advancing to the next one. Returns a pointer to the symbol,
4579 * or NULL if no definition was found.
4582 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
4585 const Needed_Entry *n;
4586 const Obj_Entry *defobj;
4592 symlook_init_from_req(&req1, req);
4593 for (n = needed; n != NULL; n = n->next) {
4594 if (n->obj == NULL ||
4595 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
4597 if (def == NULL || (ld_dynamic_weak &&
4598 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4600 defobj = req1.defobj_out;
4601 if (!ld_dynamic_weak || ELF_ST_BIND(def->st_info) != STB_WEAK)
4607 req->defobj_out = defobj;
4614 * Search the symbol table of a single shared object for a symbol of
4615 * the given name and version, if requested. Returns a pointer to the
4616 * symbol, or NULL if no definition was found. If the object is
4617 * filter, return filtered symbol from filtee.
4619 * The symbol's hash value is passed in for efficiency reasons; that
4620 * eliminates many recomputations of the hash value.
4623 symlook_obj(SymLook *req, const Obj_Entry *obj)
4627 int flags, res, mres;
4630 * If there is at least one valid hash at this point, we prefer to
4631 * use the faster GNU version if available.
4633 if (obj->valid_hash_gnu)
4634 mres = symlook_obj1_gnu(req, obj);
4635 else if (obj->valid_hash_sysv)
4636 mres = symlook_obj1_sysv(req, obj);
4641 if (obj->needed_filtees != NULL) {
4642 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4643 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4644 donelist_init(&donelist);
4645 symlook_init_from_req(&req1, req);
4646 res = symlook_needed(&req1, obj->needed_filtees, &donelist);
4648 req->sym_out = req1.sym_out;
4649 req->defobj_out = req1.defobj_out;
4653 if (obj->needed_aux_filtees != NULL) {
4654 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4655 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4656 donelist_init(&donelist);
4657 symlook_init_from_req(&req1, req);
4658 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
4660 req->sym_out = req1.sym_out;
4661 req->defobj_out = req1.defobj_out;
4669 /* Symbol match routine common to both hash functions */
4671 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result,
4672 const unsigned long symnum)
4675 const Elf_Sym *symp;
4678 symp = obj->symtab + symnum;
4679 strp = obj->strtab + symp->st_name;
4681 switch (ELF_ST_TYPE(symp->st_info)) {
4687 if (symp->st_value == 0)
4691 if (symp->st_shndx != SHN_UNDEF)
4694 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
4695 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
4702 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
4705 if (req->ventry == NULL) {
4706 if (obj->versyms != NULL) {
4707 verndx = VER_NDX(obj->versyms[symnum]);
4708 if (verndx > obj->vernum) {
4710 "%s: symbol %s references wrong version %d",
4711 obj->path, obj->strtab + symnum, verndx);
4715 * If we are not called from dlsym (i.e. this
4716 * is a normal relocation from unversioned
4717 * binary), accept the symbol immediately if
4718 * it happens to have first version after this
4719 * shared object became versioned. Otherwise,
4720 * if symbol is versioned and not hidden,
4721 * remember it. If it is the only symbol with
4722 * this name exported by the shared object, it
4723 * will be returned as a match by the calling
4724 * function. If symbol is global (verndx < 2)
4725 * accept it unconditionally.
4727 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
4728 verndx == VER_NDX_GIVEN) {
4729 result->sym_out = symp;
4732 else if (verndx >= VER_NDX_GIVEN) {
4733 if ((obj->versyms[symnum] & VER_NDX_HIDDEN)
4735 if (result->vsymp == NULL)
4736 result->vsymp = symp;
4742 result->sym_out = symp;
4745 if (obj->versyms == NULL) {
4746 if (object_match_name(obj, req->ventry->name)) {
4747 _rtld_error("%s: object %s should provide version %s "
4748 "for symbol %s", obj_rtld.path, obj->path,
4749 req->ventry->name, obj->strtab + symnum);
4753 verndx = VER_NDX(obj->versyms[symnum]);
4754 if (verndx > obj->vernum) {
4755 _rtld_error("%s: symbol %s references wrong version %d",
4756 obj->path, obj->strtab + symnum, verndx);
4759 if (obj->vertab[verndx].hash != req->ventry->hash ||
4760 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
4762 * Version does not match. Look if this is a
4763 * global symbol and if it is not hidden. If
4764 * global symbol (verndx < 2) is available,
4765 * use it. Do not return symbol if we are
4766 * called by dlvsym, because dlvsym looks for
4767 * a specific version and default one is not
4768 * what dlvsym wants.
4770 if ((req->flags & SYMLOOK_DLSYM) ||
4771 (verndx >= VER_NDX_GIVEN) ||
4772 (obj->versyms[symnum] & VER_NDX_HIDDEN))
4776 result->sym_out = symp;
4781 * Search for symbol using SysV hash function.
4782 * obj->buckets is known not to be NULL at this point; the test for this was
4783 * performed with the obj->valid_hash_sysv assignment.
4786 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj)
4788 unsigned long symnum;
4789 Sym_Match_Result matchres;
4791 matchres.sym_out = NULL;
4792 matchres.vsymp = NULL;
4793 matchres.vcount = 0;
4795 for (symnum = obj->buckets[req->hash % obj->nbuckets];
4796 symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
4797 if (symnum >= obj->nchains)
4798 return (ESRCH); /* Bad object */
4800 if (matched_symbol(req, obj, &matchres, symnum)) {
4801 req->sym_out = matchres.sym_out;
4802 req->defobj_out = obj;
4806 if (matchres.vcount == 1) {
4807 req->sym_out = matchres.vsymp;
4808 req->defobj_out = obj;
4814 /* Search for symbol using GNU hash function */
4816 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj)
4818 Elf_Addr bloom_word;
4819 const Elf32_Word *hashval;
4821 Sym_Match_Result matchres;
4822 unsigned int h1, h2;
4823 unsigned long symnum;
4825 matchres.sym_out = NULL;
4826 matchres.vsymp = NULL;
4827 matchres.vcount = 0;
4829 /* Pick right bitmask word from Bloom filter array */
4830 bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) &
4831 obj->maskwords_bm_gnu];
4833 /* Calculate modulus word size of gnu hash and its derivative */
4834 h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1);
4835 h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1));
4837 /* Filter out the "definitely not in set" queries */
4838 if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0)
4841 /* Locate hash chain and corresponding value element*/
4842 bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu];
4845 hashval = &obj->chain_zero_gnu[bucket];
4847 if (((*hashval ^ req->hash_gnu) >> 1) == 0) {
4848 symnum = hashval - obj->chain_zero_gnu;
4849 if (matched_symbol(req, obj, &matchres, symnum)) {
4850 req->sym_out = matchres.sym_out;
4851 req->defobj_out = obj;
4855 } while ((*hashval++ & 1) == 0);
4856 if (matchres.vcount == 1) {
4857 req->sym_out = matchres.vsymp;
4858 req->defobj_out = obj;
4865 trace_loaded_objects(Obj_Entry *obj)
4867 const char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
4870 if ((main_local = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_PROGNAME)) ==
4874 if ((fmt1 = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_FMT1)) == NULL)
4875 fmt1 = "\t%o => %p (%x)\n";
4877 if ((fmt2 = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_FMT2)) == NULL)
4878 fmt2 = "\t%o (%x)\n";
4880 list_containers = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_ALL);
4882 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
4883 Needed_Entry *needed;
4884 const char *name, *path;
4889 if (list_containers && obj->needed != NULL)
4890 rtld_printf("%s:\n", obj->path);
4891 for (needed = obj->needed; needed; needed = needed->next) {
4892 if (needed->obj != NULL) {
4893 if (needed->obj->traced && !list_containers)
4895 needed->obj->traced = true;
4896 path = needed->obj->path;
4900 name = obj->strtab + needed->name;
4901 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
4903 fmt = is_lib ? fmt1 : fmt2;
4904 while ((c = *fmt++) != '\0') {
4930 rtld_putstr(main_local);
4933 rtld_putstr(obj_main->path);
4940 rtld_printf("%d", sodp->sod_major);
4943 rtld_printf("%d", sodp->sod_minor);
4950 rtld_printf("%p", needed->obj ? needed->obj->mapbase :
4963 * Unload a dlopened object and its dependencies from memory and from
4964 * our data structures. It is assumed that the DAG rooted in the
4965 * object has already been unreferenced, and that the object has a
4966 * reference count of 0.
4969 unload_object(Obj_Entry *root, RtldLockState *lockstate)
4971 Obj_Entry marker, *obj, *next;
4973 assert(root->refcount == 0);
4976 * Pass over the DAG removing unreferenced objects from
4977 * appropriate lists.
4979 unlink_object(root);
4981 /* Unmap all objects that are no longer referenced. */
4982 for (obj = TAILQ_FIRST(&obj_list); obj != NULL; obj = next) {
4983 next = TAILQ_NEXT(obj, next);
4984 if (obj->marker || obj->refcount != 0)
4986 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase,
4987 obj->mapsize, 0, obj->path);
4988 dbg("unloading \"%s\"", obj->path);
4990 * Unlink the object now to prevent new references from
4991 * being acquired while the bind lock is dropped in
4992 * recursive dlclose() invocations.
4994 TAILQ_REMOVE(&obj_list, obj, next);
4997 if (obj->filtees_loaded) {
4999 init_marker(&marker);
5000 TAILQ_INSERT_BEFORE(next, &marker, next);
5001 unload_filtees(obj, lockstate);
5002 next = TAILQ_NEXT(&marker, next);
5003 TAILQ_REMOVE(&obj_list, &marker, next);
5005 unload_filtees(obj, lockstate);
5007 release_object(obj);
5012 unlink_object(Obj_Entry *root)
5016 if (root->refcount == 0) {
5017 /* Remove the object from the RTLD_GLOBAL list. */
5018 objlist_remove(&list_global, root);
5020 /* Remove the object from all objects' DAG lists. */
5021 STAILQ_FOREACH(elm, &root->dagmembers, link) {
5022 objlist_remove(&elm->obj->dldags, root);
5023 if (elm->obj != root)
5024 unlink_object(elm->obj);
5030 ref_dag(Obj_Entry *root)
5034 assert(root->dag_inited);
5035 STAILQ_FOREACH(elm, &root->dagmembers, link)
5036 elm->obj->refcount++;
5040 unref_dag(Obj_Entry *root)
5044 assert(root->dag_inited);
5045 STAILQ_FOREACH(elm, &root->dagmembers, link)
5046 elm->obj->refcount--;
5050 * Common code for MD __tls_get_addr().
5053 tls_get_addr_slow(Elf_Addr **dtvp, int index, size_t offset, bool locked)
5055 Elf_Addr *newdtv, *dtv;
5056 RtldLockState lockstate;
5060 /* Check dtv generation in case new modules have arrived */
5061 if (dtv[0] != tls_dtv_generation) {
5063 wlock_acquire(rtld_bind_lock, &lockstate);
5064 newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
5066 if (to_copy > tls_max_index)
5067 to_copy = tls_max_index;
5068 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
5069 newdtv[0] = tls_dtv_generation;
5070 newdtv[1] = tls_max_index;
5073 lock_release(rtld_bind_lock, &lockstate);
5074 dtv = *dtvp = newdtv;
5077 /* Dynamically allocate module TLS if necessary */
5078 if (dtv[index + 1] == 0) {
5079 /* Signal safe, wlock will block out signals. */
5081 wlock_acquire(rtld_bind_lock, &lockstate);
5082 if (!dtv[index + 1])
5083 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
5085 lock_release(rtld_bind_lock, &lockstate);
5087 return ((void *)(dtv[index + 1] + offset));
5091 tls_get_addr_common(Elf_Addr **dtvp, int index, size_t offset)
5096 /* Check dtv generation in case new modules have arrived */
5097 if (__predict_true(dtv[0] == tls_dtv_generation &&
5098 dtv[index + 1] != 0))
5099 return ((void *)(dtv[index + 1] + offset));
5100 return (tls_get_addr_slow(dtvp, index, offset, false));
5103 #ifdef TLS_VARIANT_I
5106 * Return pointer to allocated TLS block
5109 get_tls_block_ptr(void *tcb, size_t tcbsize)
5111 size_t extra_size, post_size, pre_size, tls_block_size;
5112 size_t tls_init_align;
5114 tls_init_align = MAX(obj_main->tlsalign, 1);
5116 /* Compute fragments sizes. */
5117 extra_size = tcbsize - TLS_TCB_SIZE;
5118 post_size = calculate_tls_post_size(tls_init_align);
5119 tls_block_size = tcbsize + post_size;
5120 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size;
5122 return ((char *)tcb - pre_size - extra_size);
5126 * Allocate Static TLS using the Variant I method.
5128 * For details on the layout, see lib/libc/gen/tls.c.
5130 * NB: rtld's tls_static_space variable includes TLS_TCB_SIZE and post_size as
5131 * it is based on tls_last_offset, and TLS offsets here are really TCB
5132 * offsets, whereas libc's tls_static_space is just the executable's static
5136 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
5140 Elf_Addr *dtv, **tcb;
5143 size_t extra_size, maxalign, post_size, pre_size, tls_block_size;
5144 size_t tls_init_align, tls_init_offset;
5146 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
5149 assert(tcbsize >= TLS_TCB_SIZE);
5150 maxalign = MAX(tcbalign, tls_static_max_align);
5151 tls_init_align = MAX(obj_main->tlsalign, 1);
5153 /* Compute fragmets sizes. */
5154 extra_size = tcbsize - TLS_TCB_SIZE;
5155 post_size = calculate_tls_post_size(tls_init_align);
5156 tls_block_size = tcbsize + post_size;
5157 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size;
5158 tls_block_size += pre_size + tls_static_space - TLS_TCB_SIZE - post_size;
5160 /* Allocate whole TLS block */
5161 tls_block = malloc_aligned(tls_block_size, maxalign, 0);
5162 tcb = (Elf_Addr **)(tls_block + pre_size + extra_size);
5164 if (oldtcb != NULL) {
5165 memcpy(tls_block, get_tls_block_ptr(oldtcb, tcbsize),
5167 free_aligned(get_tls_block_ptr(oldtcb, tcbsize));
5169 /* Adjust the DTV. */
5171 for (i = 0; i < dtv[1]; i++) {
5172 if (dtv[i+2] >= (Elf_Addr)oldtcb &&
5173 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
5174 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tcb;
5178 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
5180 dtv[0] = tls_dtv_generation;
5181 dtv[1] = tls_max_index;
5183 for (obj = globallist_curr(objs); obj != NULL;
5184 obj = globallist_next(obj)) {
5185 if (obj->tlsoffset == 0)
5187 tls_init_offset = obj->tlspoffset & (obj->tlsalign - 1);
5188 addr = (Elf_Addr)tcb + obj->tlsoffset;
5189 if (tls_init_offset > 0)
5190 memset((void *)addr, 0, tls_init_offset);
5191 if (obj->tlsinitsize > 0) {
5192 memcpy((void *)(addr + tls_init_offset), obj->tlsinit,
5195 if (obj->tlssize > obj->tlsinitsize) {
5196 memset((void *)(addr + tls_init_offset + obj->tlsinitsize),
5197 0, obj->tlssize - obj->tlsinitsize - tls_init_offset);
5199 dtv[obj->tlsindex + 1] = addr;
5207 free_tls(void *tcb, size_t tcbsize, size_t tcbalign __unused)
5210 Elf_Addr tlsstart, tlsend;
5212 size_t dtvsize, i, tls_init_align;
5214 assert(tcbsize >= TLS_TCB_SIZE);
5215 tls_init_align = MAX(obj_main->tlsalign, 1);
5217 /* Compute fragments sizes. */
5218 post_size = calculate_tls_post_size(tls_init_align);
5220 tlsstart = (Elf_Addr)tcb + TLS_TCB_SIZE + post_size;
5221 tlsend = (Elf_Addr)tcb + tls_static_space;
5223 dtv = *(Elf_Addr **)tcb;
5225 for (i = 0; i < dtvsize; i++) {
5226 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
5227 free((void*)dtv[i+2]);
5231 free_aligned(get_tls_block_ptr(tcb, tcbsize));
5234 #endif /* TLS_VARIANT_I */
5236 #ifdef TLS_VARIANT_II
5239 * Allocate Static TLS using the Variant II method.
5242 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
5245 size_t size, ralign;
5247 Elf_Addr *dtv, *olddtv;
5248 Elf_Addr segbase, oldsegbase, addr;
5252 if (tls_static_max_align > ralign)
5253 ralign = tls_static_max_align;
5254 size = roundup(tls_static_space, ralign) + roundup(tcbsize, ralign);
5256 assert(tcbsize >= 2*sizeof(Elf_Addr));
5257 tls = malloc_aligned(size, ralign, 0 /* XXX */);
5258 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
5260 segbase = (Elf_Addr)(tls + roundup(tls_static_space, ralign));
5261 ((Elf_Addr*)segbase)[0] = segbase;
5262 ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
5264 dtv[0] = tls_dtv_generation;
5265 dtv[1] = tls_max_index;
5269 * Copy the static TLS block over whole.
5271 oldsegbase = (Elf_Addr) oldtls;
5272 memcpy((void *)(segbase - tls_static_space),
5273 (const void *)(oldsegbase - tls_static_space),
5277 * If any dynamic TLS blocks have been created tls_get_addr(),
5280 olddtv = ((Elf_Addr**)oldsegbase)[1];
5281 for (i = 0; i < olddtv[1]; i++) {
5282 if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
5283 dtv[i+2] = olddtv[i+2];
5289 * We assume that this block was the one we created with
5290 * allocate_initial_tls().
5292 free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
5294 for (obj = objs; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
5295 if (obj->marker || obj->tlsoffset == 0)
5297 addr = segbase - obj->tlsoffset;
5298 memset((void*)(addr + obj->tlsinitsize),
5299 0, obj->tlssize - obj->tlsinitsize);
5301 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
5302 obj->static_tls_copied = true;
5304 dtv[obj->tlsindex + 1] = addr;
5308 return (void*) segbase;
5312 free_tls(void *tls, size_t tcbsize __unused, size_t tcbalign)
5315 size_t size, ralign;
5317 Elf_Addr tlsstart, tlsend;
5320 * Figure out the size of the initial TLS block so that we can
5321 * find stuff which ___tls_get_addr() allocated dynamically.
5324 if (tls_static_max_align > ralign)
5325 ralign = tls_static_max_align;
5326 size = roundup(tls_static_space, ralign);
5328 dtv = ((Elf_Addr**)tls)[1];
5330 tlsend = (Elf_Addr) tls;
5331 tlsstart = tlsend - size;
5332 for (i = 0; i < dtvsize; i++) {
5333 if (dtv[i + 2] != 0 && (dtv[i + 2] < tlsstart || dtv[i + 2] > tlsend)) {
5334 free_aligned((void *)dtv[i + 2]);
5338 free_aligned((void *)tlsstart);
5342 #endif /* TLS_VARIANT_II */
5345 * Allocate TLS block for module with given index.
5348 allocate_module_tls(int index)
5353 TAILQ_FOREACH(obj, &obj_list, next) {
5356 if (obj->tlsindex == index)
5360 _rtld_error("Can't find module with TLS index %d", index);
5364 p = malloc_aligned(obj->tlssize, obj->tlsalign, obj->tlspoffset);
5365 memcpy(p, obj->tlsinit, obj->tlsinitsize);
5366 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
5371 allocate_tls_offset(Obj_Entry *obj)
5378 if (obj->tlssize == 0) {
5379 obj->tls_done = true;
5383 if (tls_last_offset == 0)
5384 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign,
5387 off = calculate_tls_offset(tls_last_offset, tls_last_size,
5388 obj->tlssize, obj->tlsalign, obj->tlspoffset);
5390 obj->tlsoffset = off;
5391 #ifdef TLS_VARIANT_I
5392 off += obj->tlssize;
5396 * If we have already fixed the size of the static TLS block, we
5397 * must stay within that size. When allocating the static TLS, we
5398 * leave a small amount of space spare to be used for dynamically
5399 * loading modules which use static TLS.
5401 if (tls_static_space != 0) {
5402 if (off > tls_static_space)
5404 } else if (obj->tlsalign > tls_static_max_align) {
5405 tls_static_max_align = obj->tlsalign;
5408 tls_last_offset = off;
5409 tls_last_size = obj->tlssize;
5410 obj->tls_done = true;
5416 free_tls_offset(Obj_Entry *obj)
5420 * If we were the last thing to allocate out of the static TLS
5421 * block, we give our space back to the 'allocator'. This is a
5422 * simplistic workaround to allow libGL.so.1 to be loaded and
5423 * unloaded multiple times.
5425 size_t off = obj->tlsoffset;
5426 #ifdef TLS_VARIANT_I
5427 off += obj->tlssize;
5429 if (off == tls_last_offset) {
5430 tls_last_offset -= obj->tlssize;
5436 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
5439 RtldLockState lockstate;
5441 wlock_acquire(rtld_bind_lock, &lockstate);
5442 ret = allocate_tls(globallist_curr(TAILQ_FIRST(&obj_list)), oldtls,
5444 lock_release(rtld_bind_lock, &lockstate);
5449 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
5451 RtldLockState lockstate;
5453 wlock_acquire(rtld_bind_lock, &lockstate);
5454 free_tls(tcb, tcbsize, tcbalign);
5455 lock_release(rtld_bind_lock, &lockstate);
5459 object_add_name(Obj_Entry *obj, const char *name)
5465 entry = malloc(sizeof(Name_Entry) + len);
5467 if (entry != NULL) {
5468 strcpy(entry->name, name);
5469 STAILQ_INSERT_TAIL(&obj->names, entry, link);
5474 object_match_name(const Obj_Entry *obj, const char *name)
5478 STAILQ_FOREACH(entry, &obj->names, link) {
5479 if (strcmp(name, entry->name) == 0)
5486 locate_dependency(const Obj_Entry *obj, const char *name)
5488 const Objlist_Entry *entry;
5489 const Needed_Entry *needed;
5491 STAILQ_FOREACH(entry, &list_main, link) {
5492 if (object_match_name(entry->obj, name))
5496 for (needed = obj->needed; needed != NULL; needed = needed->next) {
5497 if (strcmp(obj->strtab + needed->name, name) == 0 ||
5498 (needed->obj != NULL && object_match_name(needed->obj, name))) {
5500 * If there is DT_NEEDED for the name we are looking for,
5501 * we are all set. Note that object might not be found if
5502 * dependency was not loaded yet, so the function can
5503 * return NULL here. This is expected and handled
5504 * properly by the caller.
5506 return (needed->obj);
5509 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
5515 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
5516 const Elf_Vernaux *vna)
5518 const Elf_Verdef *vd;
5519 const char *vername;
5521 vername = refobj->strtab + vna->vna_name;
5522 vd = depobj->verdef;
5524 _rtld_error("%s: version %s required by %s not defined",
5525 depobj->path, vername, refobj->path);
5529 if (vd->vd_version != VER_DEF_CURRENT) {
5530 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
5531 depobj->path, vd->vd_version);
5534 if (vna->vna_hash == vd->vd_hash) {
5535 const Elf_Verdaux *aux = (const Elf_Verdaux *)
5536 ((const char *)vd + vd->vd_aux);
5537 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
5540 if (vd->vd_next == 0)
5542 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5544 if (vna->vna_flags & VER_FLG_WEAK)
5546 _rtld_error("%s: version %s required by %s not found",
5547 depobj->path, vername, refobj->path);
5552 rtld_verify_object_versions(Obj_Entry *obj)
5554 const Elf_Verneed *vn;
5555 const Elf_Verdef *vd;
5556 const Elf_Verdaux *vda;
5557 const Elf_Vernaux *vna;
5558 const Obj_Entry *depobj;
5559 int maxvernum, vernum;
5561 if (obj->ver_checked)
5563 obj->ver_checked = true;
5567 * Walk over defined and required version records and figure out
5568 * max index used by any of them. Do very basic sanity checking
5572 while (vn != NULL) {
5573 if (vn->vn_version != VER_NEED_CURRENT) {
5574 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
5575 obj->path, vn->vn_version);
5578 vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux);
5580 vernum = VER_NEED_IDX(vna->vna_other);
5581 if (vernum > maxvernum)
5583 if (vna->vna_next == 0)
5585 vna = (const Elf_Vernaux *)((const char *)vna + vna->vna_next);
5587 if (vn->vn_next == 0)
5589 vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next);
5593 while (vd != NULL) {
5594 if (vd->vd_version != VER_DEF_CURRENT) {
5595 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
5596 obj->path, vd->vd_version);
5599 vernum = VER_DEF_IDX(vd->vd_ndx);
5600 if (vernum > maxvernum)
5602 if (vd->vd_next == 0)
5604 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5611 * Store version information in array indexable by version index.
5612 * Verify that object version requirements are satisfied along the
5615 obj->vernum = maxvernum + 1;
5616 obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry));
5619 while (vd != NULL) {
5620 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
5621 vernum = VER_DEF_IDX(vd->vd_ndx);
5622 assert(vernum <= maxvernum);
5623 vda = (const Elf_Verdaux *)((const char *)vd + vd->vd_aux);
5624 obj->vertab[vernum].hash = vd->vd_hash;
5625 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
5626 obj->vertab[vernum].file = NULL;
5627 obj->vertab[vernum].flags = 0;
5629 if (vd->vd_next == 0)
5631 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5635 while (vn != NULL) {
5636 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
5639 vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux);
5641 if (check_object_provided_version(obj, depobj, vna))
5643 vernum = VER_NEED_IDX(vna->vna_other);
5644 assert(vernum <= maxvernum);
5645 obj->vertab[vernum].hash = vna->vna_hash;
5646 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
5647 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
5648 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
5649 VER_INFO_HIDDEN : 0;
5650 if (vna->vna_next == 0)
5652 vna = (const Elf_Vernaux *)((const char *)vna + vna->vna_next);
5654 if (vn->vn_next == 0)
5656 vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next);
5662 rtld_verify_versions(const Objlist *objlist)
5664 Objlist_Entry *entry;
5668 STAILQ_FOREACH(entry, objlist, link) {
5670 * Skip dummy objects or objects that have their version requirements
5673 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
5675 if (rtld_verify_object_versions(entry->obj) == -1) {
5677 if (ld_tracing == NULL)
5681 if (rc == 0 || ld_tracing != NULL)
5682 rc = rtld_verify_object_versions(&obj_rtld);
5687 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
5692 vernum = VER_NDX(obj->versyms[symnum]);
5693 if (vernum >= obj->vernum) {
5694 _rtld_error("%s: symbol %s has wrong verneed value %d",
5695 obj->path, obj->strtab + symnum, vernum);
5696 } else if (obj->vertab[vernum].hash != 0) {
5697 return &obj->vertab[vernum];
5704 _rtld_get_stack_prot(void)
5707 return (stack_prot);
5711 _rtld_is_dlopened(void *arg)
5714 RtldLockState lockstate;
5717 rlock_acquire(rtld_bind_lock, &lockstate);
5720 obj = obj_from_addr(arg);
5722 _rtld_error("No shared object contains address");
5723 lock_release(rtld_bind_lock, &lockstate);
5726 res = obj->dlopened ? 1 : 0;
5727 lock_release(rtld_bind_lock, &lockstate);
5732 obj_remap_relro(Obj_Entry *obj, int prot)
5735 if (obj->relro_size > 0 && mprotect(obj->relro_page, obj->relro_size,
5737 _rtld_error("%s: Cannot set relro protection to %#x: %s",
5738 obj->path, prot, rtld_strerror(errno));
5745 obj_disable_relro(Obj_Entry *obj)
5748 return (obj_remap_relro(obj, PROT_READ | PROT_WRITE));
5752 obj_enforce_relro(Obj_Entry *obj)
5755 return (obj_remap_relro(obj, PROT_READ));
5759 map_stacks_exec(RtldLockState *lockstate)
5761 void (*thr_map_stacks_exec)(void);
5763 if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
5765 thr_map_stacks_exec = (void (*)(void))(uintptr_t)
5766 get_program_var_addr("__pthread_map_stacks_exec", lockstate);
5767 if (thr_map_stacks_exec != NULL) {
5768 stack_prot |= PROT_EXEC;
5769 thr_map_stacks_exec();
5774 distribute_static_tls(Objlist *list, RtldLockState *lockstate)
5778 void (*distrib)(size_t, void *, size_t, size_t);
5780 distrib = (void (*)(size_t, void *, size_t, size_t))(uintptr_t)
5781 get_program_var_addr("__pthread_distribute_static_tls", lockstate);
5782 if (distrib == NULL)
5784 STAILQ_FOREACH(elm, list, link) {
5786 if (obj->marker || !obj->tls_done || obj->static_tls_copied)
5788 distrib(obj->tlsoffset, obj->tlsinit, obj->tlsinitsize,
5790 obj->static_tls_copied = true;
5795 symlook_init(SymLook *dst, const char *name)
5798 bzero(dst, sizeof(*dst));
5800 dst->hash = elf_hash(name);
5801 dst->hash_gnu = gnu_hash(name);
5805 symlook_init_from_req(SymLook *dst, const SymLook *src)
5808 dst->name = src->name;
5809 dst->hash = src->hash;
5810 dst->hash_gnu = src->hash_gnu;
5811 dst->ventry = src->ventry;
5812 dst->flags = src->flags;
5813 dst->defobj_out = NULL;
5814 dst->sym_out = NULL;
5815 dst->lockstate = src->lockstate;
5819 open_binary_fd(const char *argv0, bool search_in_path,
5820 const char **binpath_res)
5822 char *binpath, *pathenv, *pe, *res1;
5828 if (search_in_path && strchr(argv0, '/') == NULL) {
5829 binpath = xmalloc(PATH_MAX);
5830 pathenv = getenv("PATH");
5831 if (pathenv == NULL) {
5832 _rtld_error("-p and no PATH environment variable");
5835 pathenv = strdup(pathenv);
5836 if (pathenv == NULL) {
5837 _rtld_error("Cannot allocate memory");
5842 while ((pe = strsep(&pathenv, ":")) != NULL) {
5843 if (strlcpy(binpath, pe, PATH_MAX) >= PATH_MAX)
5845 if (binpath[0] != '\0' &&
5846 strlcat(binpath, "/", PATH_MAX) >= PATH_MAX)
5848 if (strlcat(binpath, argv0, PATH_MAX) >= PATH_MAX)
5850 fd = open(binpath, O_RDONLY | O_CLOEXEC | O_VERIFY);
5851 if (fd != -1 || errno != ENOENT) {
5858 fd = open(argv0, O_RDONLY | O_CLOEXEC | O_VERIFY);
5863 _rtld_error("Cannot open %s: %s", argv0, rtld_strerror(errno));
5866 if (res != NULL && res[0] != '/') {
5867 res1 = xmalloc(PATH_MAX);
5868 if (realpath(res, res1) != NULL) {
5870 free(__DECONST(char *, res));
5881 * Parse a set of command-line arguments.
5884 parse_args(char* argv[], int argc, bool *use_pathp, int *fdp,
5885 const char **argv0, bool *dir_ignore)
5890 int arglen, fd, i, j, mib[2];
5892 bool seen_b, seen_f;
5894 dbg("Parsing command-line arguments");
5897 *dir_ignore = false;
5898 seen_b = seen_f = false;
5900 for (i = 1; i < argc; i++ ) {
5902 dbg("argv[%d]: '%s'", i, arg);
5905 * rtld arguments end with an explicit "--" or with the first
5906 * non-prefixed argument.
5908 if (strcmp(arg, "--") == 0) {
5916 * All other arguments are single-character options that can
5917 * be combined, so we need to search through `arg` for them.
5919 arglen = strlen(arg);
5920 for (j = 1; j < arglen; j++) {
5923 print_usage(argv[0]);
5925 } else if (opt == 'b') {
5927 _rtld_error("Both -b and -f specified");
5934 } else if (opt == 'd') {
5937 } else if (opt == 'f') {
5939 _rtld_error("Both -b and -f specified");
5944 * -f XX can be used to specify a
5945 * descriptor for the binary named at
5946 * the command line (i.e., the later
5947 * argument will specify the process
5948 * name but the descriptor is what
5949 * will actually be executed).
5951 * -f must be the last option in, e.g., -abcf.
5953 if (j != arglen - 1) {
5954 _rtld_error("Invalid options: %s", arg);
5958 fd = parse_integer(argv[i]);
5961 "Invalid file descriptor: '%s'",
5968 } else if (opt == 'p') {
5970 } else if (opt == 'u') {
5972 } else if (opt == 'v') {
5975 mib[1] = HW_MACHINE;
5976 sz = sizeof(machine);
5977 sysctl(mib, nitems(mib), machine, &sz, NULL, 0);
5978 ld_elf_hints_path = ld_get_env_var(
5980 set_ld_elf_hints_path();
5982 "FreeBSD ld-elf.so.1 %s\n"
5983 "FreeBSD_version %d\n"
5984 "Default lib path %s\n"
5985 "Hints lib path %s\n"
5987 "Default hint file %s\n"
5991 __FreeBSD_version, ld_standard_library_path,
5993 ld_env_prefix, ld_elf_hints_default,
5995 ld_path_libmap_conf);
5998 _rtld_error("Invalid argument: '%s'", arg);
5999 print_usage(argv[0]);
6011 * Parse a file descriptor number without pulling in more of libc (e.g. atoi).
6014 parse_integer(const char *str)
6016 static const int RADIX = 10; /* XXXJA: possibly support hex? */
6023 for (c = *str; c != '\0'; c = *++str) {
6024 if (c < '0' || c > '9')
6031 /* Make sure we actually parsed something. */
6038 print_usage(const char *argv0)
6042 "Usage: %s [-h] [-b <exe>] [-d] [-f <FD>] [-p] [--] <binary> [<args>]\n"
6045 " -h Display this help message\n"
6046 " -b <exe> Execute <exe> instead of <binary>, arg0 is <binary>\n"
6047 " -d Ignore lack of exec permissions for the binary\n"
6048 " -f <FD> Execute <FD> instead of searching for <binary>\n"
6049 " -p Search in PATH for named binary\n"
6050 " -u Ignore LD_ environment variables\n"
6051 " -v Display identification information\n"
6052 " -- End of RTLD options\n"
6053 " <binary> Name of process to execute\n"
6054 " <args> Arguments to the executed process\n", argv0);
6058 * Overrides for libc_pic-provided functions.
6062 __getosreldate(void)
6072 oid[1] = KERN_OSRELDATE;
6074 len = sizeof(osrel);
6075 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
6076 if (error == 0 && osrel > 0 && len == sizeof(osrel))
6081 rtld_strerror(int errnum)
6084 if (errnum < 0 || errnum >= sys_nerr)
6085 return ("Unknown error");
6086 return (sys_errlist[errnum]);
6090 getenv(const char *name)
6092 return (__DECONST(char *, rtld_get_env_val(environ, name,
6098 malloc(size_t nbytes)
6101 return (__crt_malloc(nbytes));
6105 calloc(size_t num, size_t size)
6108 return (__crt_calloc(num, size));
6119 realloc(void *cp, size_t nbytes)
6122 return (__crt_realloc(cp, nbytes));
6125 extern int _rtld_version__FreeBSD_version __exported;
6126 int _rtld_version__FreeBSD_version = __FreeBSD_version;
6128 extern char _rtld_version_laddr_offset __exported;
6129 char _rtld_version_laddr_offset;
6131 extern char _rtld_version_dlpi_tls_data __exported;
6132 char _rtld_version_dlpi_tls_data;