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>
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,
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 * Main entry point for dynamic linking. The first argument is the
471 * stack pointer. The stack is expected to be laid out as described
472 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
473 * Specifically, the stack pointer points to a word containing
474 * ARGC. Following that in the stack is a null-terminated sequence
475 * of pointers to argument strings. Then comes a null-terminated
476 * sequence of pointers to environment strings. Finally, there is a
477 * sequence of "auxiliary vector" entries.
479 * The second argument points to a place to store the dynamic linker's
480 * exit procedure pointer and the third to a place to store the main
483 * The return value is the main program's entry point.
486 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
488 Elf_Auxinfo *aux, *auxp, *auxpf, *aux_info[AT_COUNT];
489 Objlist_Entry *entry;
490 Obj_Entry *last_interposer, *obj, *preload_tail;
491 const Elf_Phdr *phdr;
493 RtldLockState lockstate;
496 char **argv, **env, **envp, *kexecpath;
497 const char *argv0, *binpath, *library_path_rpath;
498 struct ld_env_var_desc *lvd;
500 char buf[MAXPATHLEN];
501 int argc, fd, i, mib[4], old_osrel, osrel, phnum, rtld_argc;
504 int old_auxv_format = 1;
506 bool dir_enable, direct_exec, explicit_fd, search_in_path;
509 * On entry, the dynamic linker itself has not been relocated yet.
510 * Be very careful not to reference any global data until after
511 * init_rtld has returned. It is OK to reference file-scope statics
512 * and string constants, and to call static and global functions.
515 /* Find the auxiliary vector on the stack. */
519 sp += argc + 1; /* Skip over arguments and NULL terminator */
521 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
523 aux = (Elf_Auxinfo *) sp;
525 /* Digest the auxiliary vector. */
526 for (i = 0; i < AT_COUNT; i++)
528 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
529 if (auxp->a_type < AT_COUNT)
530 aux_info[auxp->a_type] = auxp;
532 if (auxp->a_type == 23) /* AT_STACKPROT */
538 if (old_auxv_format) {
539 /* Remap from old-style auxv numbers. */
540 aux_info[23] = aux_info[21]; /* AT_STACKPROT */
541 aux_info[21] = aux_info[19]; /* AT_PAGESIZESLEN */
542 aux_info[19] = aux_info[17]; /* AT_NCPUS */
543 aux_info[17] = aux_info[15]; /* AT_CANARYLEN */
544 aux_info[15] = aux_info[13]; /* AT_EXECPATH */
545 aux_info[13] = NULL; /* AT_GID */
547 aux_info[20] = aux_info[18]; /* AT_PAGESIZES */
548 aux_info[18] = aux_info[16]; /* AT_OSRELDATE */
549 aux_info[16] = aux_info[14]; /* AT_CANARY */
550 aux_info[14] = NULL; /* AT_EGID */
554 /* Initialize and relocate ourselves. */
555 assert(aux_info[AT_BASE] != NULL);
556 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
560 __progname = obj_rtld.path;
561 argv0 = argv[0] != NULL ? argv[0] : "(null)";
566 if (aux_info[AT_BSDFLAGS] != NULL &&
567 (aux_info[AT_BSDFLAGS]->a_un.a_val & ELF_BSDF_SIGFASTBLK) != 0)
568 ld_fast_sigblock = true;
570 trust = !issetugid();
573 md_abi_variant_hook(aux_info);
574 rtld_init_env_vars(env);
577 if (aux_info[AT_EXECFD] != NULL) {
578 fd = aux_info[AT_EXECFD]->a_un.a_val;
580 assert(aux_info[AT_PHDR] != NULL);
581 phdr = (const Elf_Phdr *)aux_info[AT_PHDR]->a_un.a_ptr;
582 if (phdr == obj_rtld.phdr) {
584 _rtld_error("Tainted process refusing to run binary %s",
590 dbg("opening main program in direct exec mode");
592 rtld_argc = parse_args(argv, argc, &search_in_path, &fd, &argv0);
593 explicit_fd = (fd != -1);
596 fd = open_binary_fd(argv0, search_in_path, &binpath);
597 if (fstat(fd, &st) == -1) {
598 _rtld_error("Failed to fstat FD %d (%s): %s", fd,
599 explicit_fd ? "user-provided descriptor" : argv0,
600 rtld_strerror(errno));
605 * Rough emulation of the permission checks done by
606 * execve(2), only Unix DACs are checked, ACLs are
607 * ignored. Preserve the semantic of disabling owner
608 * to execute if owner x bit is cleared, even if
609 * others x bit is enabled.
610 * mmap(2) does not allow to mmap with PROT_EXEC if
611 * binary' file comes from noexec mount. We cannot
612 * set a text reference on the binary.
615 if (st.st_uid == geteuid()) {
616 if ((st.st_mode & S_IXUSR) != 0)
618 } else if (st.st_gid == getegid()) {
619 if ((st.st_mode & S_IXGRP) != 0)
621 } else if ((st.st_mode & S_IXOTH) != 0) {
625 _rtld_error("No execute permission for binary %s",
631 * For direct exec mode, argv[0] is the interpreter
632 * name, we must remove it and shift arguments left
633 * before invoking binary main. Since stack layout
634 * places environment pointers and aux vectors right
635 * after the terminating NULL, we must shift
636 * environment and aux as well.
638 main_argc = argc - rtld_argc;
639 for (i = 0; i <= main_argc; i++)
640 argv[i] = argv[i + rtld_argc];
642 environ = env = envp = argv + main_argc + 1;
643 dbg("move env from %p to %p", envp + rtld_argc, envp);
645 *envp = *(envp + rtld_argc);
646 } while (*envp++ != NULL);
647 aux = auxp = (Elf_Auxinfo *)envp;
648 auxpf = (Elf_Auxinfo *)(envp + rtld_argc);
649 dbg("move aux from %p to %p", auxpf, aux);
650 /* XXXKIB insert place for AT_EXECPATH if not present */
651 for (;; auxp++, auxpf++) {
653 if (auxp->a_type == AT_NULL)
656 /* Since the auxiliary vector has moved, redigest it. */
657 for (i = 0; i < AT_COUNT; i++)
659 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
660 if (auxp->a_type < AT_COUNT)
661 aux_info[auxp->a_type] = auxp;
664 /* Point AT_EXECPATH auxv and aux_info to the binary path. */
665 if (binpath == NULL) {
666 aux_info[AT_EXECPATH] = NULL;
668 if (aux_info[AT_EXECPATH] == NULL) {
669 aux_info[AT_EXECPATH] = xmalloc(sizeof(Elf_Auxinfo));
670 aux_info[AT_EXECPATH]->a_type = AT_EXECPATH;
672 aux_info[AT_EXECPATH]->a_un.a_ptr = __DECONST(void *,
676 _rtld_error("No binary");
682 ld_bind_now = ld_get_env_var(LD_BIND_NOW);
685 * If the process is tainted, then we un-set the dangerous environment
686 * variables. The process will be marked as tainted until setuid(2)
687 * is called. If any child process calls setuid(2) we do not want any
688 * future processes to honor the potentially un-safe variables.
691 for (i = 0; i < (int)nitems(ld_env_vars); i++) {
692 lvd = &ld_env_vars[i];
698 ld_debug = ld_get_env_var(LD_DEBUG);
699 if (ld_bind_now == NULL)
700 ld_bind_not = ld_get_env_var(LD_BIND_NOT) != NULL;
701 ld_dynamic_weak = ld_get_env_var(LD_DYNAMIC_WEAK) == NULL;
702 libmap_disable = ld_get_env_var(LD_LIBMAP_DISABLE) != NULL;
703 libmap_override = ld_get_env_var(LD_LIBMAP);
704 ld_library_path = ld_get_env_var(LD_LIBRARY_PATH);
705 ld_library_dirs = ld_get_env_var(LD_LIBRARY_PATH_FDS);
706 ld_preload = ld_get_env_var(LD_PRELOAD);
707 ld_preload_fds = ld_get_env_var(LD_PRELOAD_FDS);
708 ld_elf_hints_path = ld_get_env_var(LD_ELF_HINTS_PATH);
709 ld_loadfltr = ld_get_env_var(LD_LOADFLTR) != NULL;
710 library_path_rpath = ld_get_env_var(LD_LIBRARY_PATH_RPATH);
711 if (library_path_rpath != NULL) {
712 if (library_path_rpath[0] == 'y' ||
713 library_path_rpath[0] == 'Y' ||
714 library_path_rpath[0] == '1')
715 ld_library_path_rpath = true;
717 ld_library_path_rpath = false;
719 dangerous_ld_env = libmap_disable || libmap_override != NULL ||
720 ld_library_path != NULL || ld_preload != NULL ||
721 ld_elf_hints_path != NULL || ld_loadfltr || ld_dynamic_weak;
722 ld_tracing = ld_get_env_var(LD_TRACE_LOADED_OBJECTS);
723 ld_utrace = ld_get_env_var(LD_UTRACE);
725 if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0)
726 ld_elf_hints_path = ld_elf_hints_default;
728 if (ld_debug != NULL && *ld_debug != '\0')
730 dbg("%s is initialized, base address = %p", __progname,
731 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
732 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
733 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
735 dbg("initializing thread locks");
739 * Load the main program, or process its program header if it is
742 if (fd != -1) { /* Load the main program. */
743 dbg("loading main program");
744 obj_main = map_object(fd, argv0, NULL);
746 if (obj_main == NULL)
748 max_stack_flags = obj_main->stack_flags;
749 } else { /* Main program already loaded. */
750 dbg("processing main program's program header");
751 assert(aux_info[AT_PHDR] != NULL);
752 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
753 assert(aux_info[AT_PHNUM] != NULL);
754 phnum = aux_info[AT_PHNUM]->a_un.a_val;
755 assert(aux_info[AT_PHENT] != NULL);
756 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
757 assert(aux_info[AT_ENTRY] != NULL);
758 imgentry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
759 if ((obj_main = digest_phdr(phdr, phnum, imgentry, argv0)) == NULL)
763 if (aux_info[AT_EXECPATH] != NULL && fd == -1) {
764 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
765 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
766 if (kexecpath[0] == '/')
767 obj_main->path = kexecpath;
768 else if (getcwd(buf, sizeof(buf)) == NULL ||
769 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
770 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
771 obj_main->path = xstrdup(argv0);
773 obj_main->path = xstrdup(buf);
775 dbg("No AT_EXECPATH or direct exec");
776 obj_main->path = xstrdup(argv0);
778 dbg("obj_main path %s", obj_main->path);
779 obj_main->mainprog = true;
781 if (aux_info[AT_STACKPROT] != NULL &&
782 aux_info[AT_STACKPROT]->a_un.a_val != 0)
783 stack_prot = aux_info[AT_STACKPROT]->a_un.a_val;
787 * Get the actual dynamic linker pathname from the executable if
788 * possible. (It should always be possible.) That ensures that
789 * gdb will find the right dynamic linker even if a non-standard
792 if (obj_main->interp != NULL &&
793 strcmp(obj_main->interp, obj_rtld.path) != 0) {
795 obj_rtld.path = xstrdup(obj_main->interp);
796 __progname = obj_rtld.path;
800 if (!digest_dynamic(obj_main, 0))
802 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d",
803 obj_main->path, obj_main->valid_hash_sysv, obj_main->valid_hash_gnu,
804 obj_main->dynsymcount);
806 linkmap_add(obj_main);
807 linkmap_add(&obj_rtld);
809 /* Link the main program into the list of objects. */
810 TAILQ_INSERT_HEAD(&obj_list, obj_main, next);
814 /* Initialize a fake symbol for resolving undefined weak references. */
815 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
816 sym_zero.st_shndx = SHN_UNDEF;
817 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
820 libmap_disable = (bool)lm_init(libmap_override);
822 dbg("loading LD_PRELOAD_FDS libraries");
823 if (load_preload_objects(ld_preload_fds, true) == -1)
826 dbg("loading LD_PRELOAD libraries");
827 if (load_preload_objects(ld_preload, false) == -1)
829 preload_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
831 dbg("loading needed objects");
832 if (load_needed_objects(obj_main, ld_tracing != NULL ? RTLD_LO_TRACE :
836 /* Make a list of all objects loaded at startup. */
837 last_interposer = obj_main;
838 TAILQ_FOREACH(obj, &obj_list, next) {
841 if (obj->z_interpose && obj != obj_main) {
842 objlist_put_after(&list_main, last_interposer, obj);
843 last_interposer = obj;
845 objlist_push_tail(&list_main, obj);
850 dbg("checking for required versions");
851 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
854 if (ld_tracing) { /* We're done */
855 trace_loaded_objects(obj_main);
859 if (ld_get_env_var(LD_DUMP_REL_PRE) != NULL) {
860 dump_relocations(obj_main);
865 * Processing tls relocations requires having the tls offsets
866 * initialized. Prepare offsets before starting initial
867 * relocation processing.
869 dbg("initializing initial thread local storage offsets");
870 STAILQ_FOREACH(entry, &list_main, link) {
872 * Allocate all the initial objects out of the static TLS
873 * block even if they didn't ask for it.
875 allocate_tls_offset(entry->obj);
878 if (relocate_objects(obj_main,
879 ld_bind_now != NULL && *ld_bind_now != '\0',
880 &obj_rtld, SYMLOOK_EARLY, NULL) == -1)
883 dbg("doing copy relocations");
884 if (do_copy_relocations(obj_main) == -1)
887 if (ld_get_env_var(LD_DUMP_REL_POST) != NULL) {
888 dump_relocations(obj_main);
895 * Setup TLS for main thread. This must be done after the
896 * relocations are processed, since tls initialization section
897 * might be the subject for relocations.
899 dbg("initializing initial thread local storage");
900 allocate_initial_tls(globallist_curr(TAILQ_FIRST(&obj_list)));
902 dbg("initializing key program variables");
903 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
904 set_program_var("environ", env);
905 set_program_var("__elf_aux_vector", aux);
907 /* Make a list of init functions to call. */
908 objlist_init(&initlist);
909 initlist_add_objects(globallist_curr(TAILQ_FIRST(&obj_list)),
910 preload_tail, &initlist);
912 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
914 map_stacks_exec(NULL);
916 if (!obj_main->crt_no_init) {
918 * Make sure we don't call the main program's init and fini
919 * functions for binaries linked with old crt1 which calls
922 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
923 obj_main->preinit_array = obj_main->init_array =
924 obj_main->fini_array = (Elf_Addr)NULL;
928 /* Set osrel for direct-execed binary */
931 mib[2] = KERN_PROC_OSREL;
933 osrel = obj_main->osrel;
934 sz = sizeof(old_osrel);
935 dbg("setting osrel to %d", osrel);
936 (void)sysctl(mib, 4, &old_osrel, &sz, &osrel, sizeof(osrel));
939 wlock_acquire(rtld_bind_lock, &lockstate);
941 dbg("resolving ifuncs");
942 if (initlist_objects_ifunc(&initlist, ld_bind_now != NULL &&
943 *ld_bind_now != '\0', SYMLOOK_EARLY, &lockstate) == -1)
946 rtld_exit_ptr = rtld_exit;
947 if (obj_main->crt_no_init)
949 objlist_call_init(&initlist, &lockstate);
950 _r_debug_postinit(&obj_main->linkmap);
951 objlist_clear(&initlist);
952 dbg("loading filtees");
953 TAILQ_FOREACH(obj, &obj_list, next) {
956 if (ld_loadfltr || obj->z_loadfltr)
957 load_filtees(obj, 0, &lockstate);
960 dbg("enforcing main obj relro");
961 if (obj_enforce_relro(obj_main) == -1)
964 lock_release(rtld_bind_lock, &lockstate);
966 dbg("transferring control to program entry point = %p", obj_main->entry);
968 /* Return the exit procedure and the program entry point. */
969 *exit_proc = rtld_exit_ptr;
971 return (func_ptr_type) obj_main->entry;
975 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def)
980 ptr = (void *)make_function_pointer(def, obj);
981 target = call_ifunc_resolver(ptr);
982 return ((void *)target);
986 * NB: MIPS uses a private version of this function (_mips_rtld_bind).
987 * Changes to this function should be applied there as well.
990 _rtld_bind(Obj_Entry *obj, Elf_Size reloff)
994 const Obj_Entry *defobj;
997 RtldLockState lockstate;
999 rlock_acquire(rtld_bind_lock, &lockstate);
1000 if (sigsetjmp(lockstate.env, 0) != 0)
1001 lock_upgrade(rtld_bind_lock, &lockstate);
1003 rel = (const Elf_Rel *)((const char *)obj->pltrel + reloff);
1005 rel = (const Elf_Rel *)((const char *)obj->pltrela + reloff);
1007 where = (Elf_Addr *)(obj->relocbase + rel->r_offset);
1008 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, SYMLOOK_IN_PLT,
1012 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
1013 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
1015 target = (Elf_Addr)(defobj->relocbase + def->st_value);
1017 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
1018 defobj->strtab + def->st_name,
1019 obj->path == NULL ? NULL : basename(obj->path),
1021 defobj->path == NULL ? NULL : basename(defobj->path));
1024 * Write the new contents for the jmpslot. Note that depending on
1025 * architecture, the value which we need to return back to the
1026 * lazy binding trampoline may or may not be the target
1027 * address. The value returned from reloc_jmpslot() is the value
1028 * that the trampoline needs.
1030 target = reloc_jmpslot(where, target, defobj, obj, rel);
1031 lock_release(rtld_bind_lock, &lockstate);
1036 * Error reporting function. Use it like printf. If formats the message
1037 * into a buffer, and sets things up so that the next call to dlerror()
1038 * will return the message.
1041 _rtld_error(const char *fmt, ...)
1046 rtld_vsnprintf(lockinfo.dlerror_loc(), lockinfo.dlerror_loc_sz,
1049 *lockinfo.dlerror_seen() = 0;
1050 LD_UTRACE(UTRACE_RTLD_ERROR, NULL, NULL, 0, 0, lockinfo.dlerror_loc());
1054 * Return a dynamically-allocated copy of the current error message, if any.
1056 static struct dlerror_save *
1059 struct dlerror_save *res;
1061 res = xmalloc(sizeof(*res));
1062 res->seen = *lockinfo.dlerror_seen();
1064 res->msg = xstrdup(lockinfo.dlerror_loc());
1069 * Restore the current error message from a copy which was previously saved
1070 * by errmsg_save(). The copy is freed.
1073 errmsg_restore(struct dlerror_save *saved_msg)
1075 if (saved_msg == NULL || saved_msg->seen == 1) {
1076 *lockinfo.dlerror_seen() = 1;
1078 *lockinfo.dlerror_seen() = 0;
1079 strlcpy(lockinfo.dlerror_loc(), saved_msg->msg,
1080 lockinfo.dlerror_loc_sz);
1081 free(saved_msg->msg);
1087 basename(const char *name)
1089 const char *p = strrchr(name, '/');
1090 return p != NULL ? p + 1 : name;
1093 static struct utsname uts;
1096 origin_subst_one(Obj_Entry *obj, char *real, const char *kw,
1097 const char *subst, bool may_free)
1099 char *p, *p1, *res, *resp;
1100 int subst_len, kw_len, subst_count, old_len, new_len;
1102 kw_len = strlen(kw);
1105 * First, count the number of the keyword occurrences, to
1106 * preallocate the final string.
1108 for (p = real, subst_count = 0;; p = p1 + kw_len, subst_count++) {
1115 * If the keyword is not found, just return.
1117 * Return non-substituted string if resolution failed. We
1118 * cannot do anything more reasonable, the failure mode of the
1119 * caller is unresolved library anyway.
1121 if (subst_count == 0 || (obj != NULL && !obj_resolve_origin(obj)))
1122 return (may_free ? real : xstrdup(real));
1124 subst = obj->origin_path;
1127 * There is indeed something to substitute. Calculate the
1128 * length of the resulting string, and allocate it.
1130 subst_len = strlen(subst);
1131 old_len = strlen(real);
1132 new_len = old_len + (subst_len - kw_len) * subst_count;
1133 res = xmalloc(new_len + 1);
1136 * Now, execute the substitution loop.
1138 for (p = real, resp = res, *resp = '\0';;) {
1141 /* Copy the prefix before keyword. */
1142 memcpy(resp, p, p1 - p);
1144 /* Keyword replacement. */
1145 memcpy(resp, subst, subst_len);
1153 /* Copy to the end of string and finish. */
1161 origin_subst(Obj_Entry *obj, const char *real)
1163 char *res1, *res2, *res3, *res4;
1165 if (obj == NULL || !trust)
1166 return (xstrdup(real));
1167 if (uts.sysname[0] == '\0') {
1168 if (uname(&uts) != 0) {
1169 _rtld_error("utsname failed: %d", errno);
1173 /* __DECONST is safe here since without may_free real is unchanged */
1174 res1 = origin_subst_one(obj, __DECONST(char *, real), "$ORIGIN", NULL,
1176 res2 = origin_subst_one(NULL, res1, "$OSNAME", uts.sysname, true);
1177 res3 = origin_subst_one(NULL, res2, "$OSREL", uts.release, true);
1178 res4 = origin_subst_one(NULL, res3, "$PLATFORM", uts.machine, true);
1185 const char *msg = dlerror();
1188 msg = "Fatal error";
1189 rtld_fdputstr(STDERR_FILENO, _BASENAME_RTLD ": ");
1190 rtld_fdputstr(STDERR_FILENO, msg);
1191 rtld_fdputchar(STDERR_FILENO, '\n');
1196 * Process a shared object's DYNAMIC section, and save the important
1197 * information in its Obj_Entry structure.
1200 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
1201 const Elf_Dyn **dyn_soname, const Elf_Dyn **dyn_runpath)
1203 const Elf_Dyn *dynp;
1204 Needed_Entry **needed_tail = &obj->needed;
1205 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
1206 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
1207 const Elf_Hashelt *hashtab;
1208 const Elf32_Word *hashval;
1209 Elf32_Word bkt, nmaskwords;
1211 int plttype = DT_REL;
1215 *dyn_runpath = NULL;
1217 obj->bind_now = false;
1218 dynp = obj->dynamic;
1221 for (; dynp->d_tag != DT_NULL; dynp++) {
1222 switch (dynp->d_tag) {
1225 obj->rel = (const Elf_Rel *)(obj->relocbase + dynp->d_un.d_ptr);
1229 obj->relsize = dynp->d_un.d_val;
1233 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
1237 obj->pltrel = (const Elf_Rel *)
1238 (obj->relocbase + dynp->d_un.d_ptr);
1242 obj->pltrelsize = dynp->d_un.d_val;
1246 obj->rela = (const Elf_Rela *)(obj->relocbase + dynp->d_un.d_ptr);
1250 obj->relasize = dynp->d_un.d_val;
1254 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
1258 plttype = dynp->d_un.d_val;
1259 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
1263 obj->symtab = (const Elf_Sym *)
1264 (obj->relocbase + dynp->d_un.d_ptr);
1268 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
1272 obj->strtab = (const char *)(obj->relocbase + dynp->d_un.d_ptr);
1276 obj->strsize = dynp->d_un.d_val;
1280 obj->verneed = (const Elf_Verneed *)(obj->relocbase +
1285 obj->verneednum = dynp->d_un.d_val;
1289 obj->verdef = (const Elf_Verdef *)(obj->relocbase +
1294 obj->verdefnum = dynp->d_un.d_val;
1298 obj->versyms = (const Elf_Versym *)(obj->relocbase +
1304 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1306 obj->nbuckets = hashtab[0];
1307 obj->nchains = hashtab[1];
1308 obj->buckets = hashtab + 2;
1309 obj->chains = obj->buckets + obj->nbuckets;
1310 obj->valid_hash_sysv = obj->nbuckets > 0 && obj->nchains > 0 &&
1311 obj->buckets != NULL;
1317 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1319 obj->nbuckets_gnu = hashtab[0];
1320 obj->symndx_gnu = hashtab[1];
1321 nmaskwords = hashtab[2];
1322 bloom_size32 = (__ELF_WORD_SIZE / 32) * nmaskwords;
1323 obj->maskwords_bm_gnu = nmaskwords - 1;
1324 obj->shift2_gnu = hashtab[3];
1325 obj->bloom_gnu = (const Elf_Addr *)(hashtab + 4);
1326 obj->buckets_gnu = hashtab + 4 + bloom_size32;
1327 obj->chain_zero_gnu = obj->buckets_gnu + obj->nbuckets_gnu -
1329 /* Number of bitmask words is required to be power of 2 */
1330 obj->valid_hash_gnu = powerof2(nmaskwords) &&
1331 obj->nbuckets_gnu > 0 && obj->buckets_gnu != NULL;
1337 Needed_Entry *nep = NEW(Needed_Entry);
1338 nep->name = dynp->d_un.d_val;
1343 needed_tail = &nep->next;
1349 Needed_Entry *nep = NEW(Needed_Entry);
1350 nep->name = dynp->d_un.d_val;
1354 *needed_filtees_tail = nep;
1355 needed_filtees_tail = &nep->next;
1357 if (obj->linkmap.l_refname == NULL)
1358 obj->linkmap.l_refname = (char *)dynp->d_un.d_val;
1364 Needed_Entry *nep = NEW(Needed_Entry);
1365 nep->name = dynp->d_un.d_val;
1369 *needed_aux_filtees_tail = nep;
1370 needed_aux_filtees_tail = &nep->next;
1375 obj->pltgot = (Elf_Addr *)(obj->relocbase + dynp->d_un.d_ptr);
1379 obj->textrel = true;
1383 obj->symbolic = true;
1388 * We have to wait until later to process this, because we
1389 * might not have gotten the address of the string table yet.
1399 *dyn_runpath = dynp;
1403 obj->init = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1406 case DT_PREINIT_ARRAY:
1407 obj->preinit_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1410 case DT_PREINIT_ARRAYSZ:
1411 obj->preinit_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1415 obj->init_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1418 case DT_INIT_ARRAYSZ:
1419 obj->init_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1423 obj->fini = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1427 obj->fini_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1430 case DT_FINI_ARRAYSZ:
1431 obj->fini_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1435 * Don't process DT_DEBUG on MIPS as the dynamic section
1436 * is mapped read-only. DT_MIPS_RLD_MAP is used instead.
1442 dbg("Filling in DT_DEBUG entry");
1443 (__DECONST(Elf_Dyn *, dynp))->d_un.d_ptr = (Elf_Addr)&r_debug;
1448 if (dynp->d_un.d_val & DF_ORIGIN)
1449 obj->z_origin = true;
1450 if (dynp->d_un.d_val & DF_SYMBOLIC)
1451 obj->symbolic = true;
1452 if (dynp->d_un.d_val & DF_TEXTREL)
1453 obj->textrel = true;
1454 if (dynp->d_un.d_val & DF_BIND_NOW)
1455 obj->bind_now = true;
1456 if (dynp->d_un.d_val & DF_STATIC_TLS)
1457 obj->static_tls = true;
1460 case DT_MIPS_LOCAL_GOTNO:
1461 obj->local_gotno = dynp->d_un.d_val;
1464 case DT_MIPS_SYMTABNO:
1465 obj->symtabno = dynp->d_un.d_val;
1468 case DT_MIPS_GOTSYM:
1469 obj->gotsym = dynp->d_un.d_val;
1472 case DT_MIPS_RLD_MAP:
1473 *((Elf_Addr *)(dynp->d_un.d_ptr)) = (Elf_Addr) &r_debug;
1476 case DT_MIPS_RLD_MAP_REL:
1477 // The MIPS_RLD_MAP_REL tag stores the offset to the .rld_map
1478 // section relative to the address of the tag itself.
1479 *((Elf_Addr *)(__DECONST(char*, dynp) + dynp->d_un.d_val)) =
1480 (Elf_Addr) &r_debug;
1483 case DT_MIPS_PLTGOT:
1484 obj->mips_pltgot = (Elf_Addr *)(obj->relocbase +
1491 #ifdef __powerpc64__
1492 case DT_PPC64_GLINK:
1493 obj->glink = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1497 obj->gotptr = (Elf_Addr *)(obj->relocbase + dynp->d_un.d_ptr);
1503 if (dynp->d_un.d_val & DF_1_NOOPEN)
1504 obj->z_noopen = true;
1505 if (dynp->d_un.d_val & DF_1_ORIGIN)
1506 obj->z_origin = true;
1507 if (dynp->d_un.d_val & DF_1_GLOBAL)
1508 obj->z_global = true;
1509 if (dynp->d_un.d_val & DF_1_BIND_NOW)
1510 obj->bind_now = true;
1511 if (dynp->d_un.d_val & DF_1_NODELETE)
1512 obj->z_nodelete = true;
1513 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1514 obj->z_loadfltr = true;
1515 if (dynp->d_un.d_val & DF_1_INTERPOSE)
1516 obj->z_interpose = true;
1517 if (dynp->d_un.d_val & DF_1_NODEFLIB)
1518 obj->z_nodeflib = true;
1519 if (dynp->d_un.d_val & DF_1_PIE)
1525 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1532 obj->traced = false;
1534 if (plttype == DT_RELA) {
1535 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1537 obj->pltrelasize = obj->pltrelsize;
1538 obj->pltrelsize = 0;
1541 /* Determine size of dynsym table (equal to nchains of sysv hash) */
1542 if (obj->valid_hash_sysv)
1543 obj->dynsymcount = obj->nchains;
1544 else if (obj->valid_hash_gnu) {
1545 obj->dynsymcount = 0;
1546 for (bkt = 0; bkt < obj->nbuckets_gnu; bkt++) {
1547 if (obj->buckets_gnu[bkt] == 0)
1549 hashval = &obj->chain_zero_gnu[obj->buckets_gnu[bkt]];
1552 while ((*hashval++ & 1u) == 0);
1554 obj->dynsymcount += obj->symndx_gnu;
1557 if (obj->linkmap.l_refname != NULL)
1558 obj->linkmap.l_refname = obj->strtab + (unsigned long)obj->
1563 obj_resolve_origin(Obj_Entry *obj)
1566 if (obj->origin_path != NULL)
1568 obj->origin_path = xmalloc(PATH_MAX);
1569 return (rtld_dirname_abs(obj->path, obj->origin_path) != -1);
1573 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1574 const Elf_Dyn *dyn_soname, const Elf_Dyn *dyn_runpath)
1577 if (obj->z_origin && !obj_resolve_origin(obj))
1580 if (dyn_runpath != NULL) {
1581 obj->runpath = (const char *)obj->strtab + dyn_runpath->d_un.d_val;
1582 obj->runpath = origin_subst(obj, obj->runpath);
1583 } else if (dyn_rpath != NULL) {
1584 obj->rpath = (const char *)obj->strtab + dyn_rpath->d_un.d_val;
1585 obj->rpath = origin_subst(obj, obj->rpath);
1587 if (dyn_soname != NULL)
1588 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1593 digest_dynamic(Obj_Entry *obj, int early)
1595 const Elf_Dyn *dyn_rpath;
1596 const Elf_Dyn *dyn_soname;
1597 const Elf_Dyn *dyn_runpath;
1599 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname, &dyn_runpath);
1600 return (digest_dynamic2(obj, dyn_rpath, dyn_soname, dyn_runpath));
1604 * Process a shared object's program header. This is used only for the
1605 * main program, when the kernel has already loaded the main program
1606 * into memory before calling the dynamic linker. It creates and
1607 * returns an Obj_Entry structure.
1610 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1613 const Elf_Phdr *phlimit = phdr + phnum;
1615 Elf_Addr note_start, note_end;
1619 for (ph = phdr; ph < phlimit; ph++) {
1620 if (ph->p_type != PT_PHDR)
1624 obj->phsize = ph->p_memsz;
1625 obj->relocbase = __DECONST(char *, phdr) - ph->p_vaddr;
1629 obj->stack_flags = PF_X | PF_R | PF_W;
1631 for (ph = phdr; ph < phlimit; ph++) {
1632 switch (ph->p_type) {
1635 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1639 if (nsegs == 0) { /* First load segment */
1640 obj->vaddrbase = trunc_page(ph->p_vaddr);
1641 obj->mapbase = obj->vaddrbase + obj->relocbase;
1642 } else { /* Last load segment */
1643 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1650 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1655 obj->tlssize = ph->p_memsz;
1656 obj->tlsalign = ph->p_align;
1657 obj->tlsinitsize = ph->p_filesz;
1658 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1659 obj->tlspoffset = ph->p_offset;
1663 obj->stack_flags = ph->p_flags;
1667 obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1668 obj->relro_size = trunc_page(ph->p_vaddr + ph->p_memsz) -
1669 trunc_page(ph->p_vaddr);
1673 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
1674 note_end = note_start + ph->p_filesz;
1675 digest_notes(obj, note_start, note_end);
1680 _rtld_error("%s: too few PT_LOAD segments", path);
1689 digest_notes(Obj_Entry *obj, Elf_Addr note_start, Elf_Addr note_end)
1691 const Elf_Note *note;
1692 const char *note_name;
1695 for (note = (const Elf_Note *)note_start; (Elf_Addr)note < note_end;
1696 note = (const Elf_Note *)((const char *)(note + 1) +
1697 roundup2(note->n_namesz, sizeof(Elf32_Addr)) +
1698 roundup2(note->n_descsz, sizeof(Elf32_Addr)))) {
1699 if (note->n_namesz != sizeof(NOTE_FREEBSD_VENDOR) ||
1700 note->n_descsz != sizeof(int32_t))
1702 if (note->n_type != NT_FREEBSD_ABI_TAG &&
1703 note->n_type != NT_FREEBSD_FEATURE_CTL &&
1704 note->n_type != NT_FREEBSD_NOINIT_TAG)
1706 note_name = (const char *)(note + 1);
1707 if (strncmp(NOTE_FREEBSD_VENDOR, note_name,
1708 sizeof(NOTE_FREEBSD_VENDOR)) != 0)
1710 switch (note->n_type) {
1711 case NT_FREEBSD_ABI_TAG:
1712 /* FreeBSD osrel note */
1713 p = (uintptr_t)(note + 1);
1714 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1715 obj->osrel = *(const int32_t *)(p);
1716 dbg("note osrel %d", obj->osrel);
1718 case NT_FREEBSD_FEATURE_CTL:
1719 /* FreeBSD ABI feature control note */
1720 p = (uintptr_t)(note + 1);
1721 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1722 obj->fctl0 = *(const uint32_t *)(p);
1723 dbg("note fctl0 %#x", obj->fctl0);
1725 case NT_FREEBSD_NOINIT_TAG:
1726 /* FreeBSD 'crt does not call init' note */
1727 obj->crt_no_init = true;
1728 dbg("note crt_no_init");
1735 dlcheck(void *handle)
1739 TAILQ_FOREACH(obj, &obj_list, next) {
1740 if (obj == (Obj_Entry *) handle)
1744 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1745 _rtld_error("Invalid shared object handle %p", handle);
1752 * If the given object is already in the donelist, return true. Otherwise
1753 * add the object to the list and return false.
1756 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1760 for (i = 0; i < dlp->num_used; i++)
1761 if (dlp->objs[i] == obj)
1764 * Our donelist allocation should always be sufficient. But if
1765 * our threads locking isn't working properly, more shared objects
1766 * could have been loaded since we allocated the list. That should
1767 * never happen, but we'll handle it properly just in case it does.
1769 if (dlp->num_used < dlp->num_alloc)
1770 dlp->objs[dlp->num_used++] = obj;
1775 * Hash function for symbol table lookup. Don't even think about changing
1776 * this. It is specified by the System V ABI.
1779 elf_hash(const char *name)
1781 const unsigned char *p = (const unsigned char *) name;
1782 unsigned long h = 0;
1785 while (*p != '\0') {
1786 h = (h << 4) + *p++;
1787 if ((g = h & 0xf0000000) != 0)
1795 * The GNU hash function is the Daniel J. Bernstein hash clipped to 32 bits
1796 * unsigned in case it's implemented with a wider type.
1799 gnu_hash(const char *s)
1805 for (c = *s; c != '\0'; c = *++s)
1807 return (h & 0xffffffff);
1812 * Find the library with the given name, and return its full pathname.
1813 * The returned string is dynamically allocated. Generates an error
1814 * message and returns NULL if the library cannot be found.
1816 * If the second argument is non-NULL, then it refers to an already-
1817 * loaded shared object, whose library search path will be searched.
1819 * If a library is successfully located via LD_LIBRARY_PATH_FDS, its
1820 * descriptor (which is close-on-exec) will be passed out via the third
1823 * The search order is:
1824 * DT_RPATH in the referencing file _unless_ DT_RUNPATH is present (1)
1825 * DT_RPATH of the main object if DSO without defined DT_RUNPATH (1)
1827 * DT_RUNPATH in the referencing file
1828 * ldconfig hints (if -z nodefaultlib, filter out default library directories
1830 * /lib:/usr/lib _unless_ the referencing file is linked with -z nodefaultlib
1832 * (1) Handled in digest_dynamic2 - rpath left NULL if runpath defined.
1835 find_library(const char *xname, const Obj_Entry *refobj, int *fdp)
1837 char *pathname, *refobj_path;
1839 bool nodeflib, objgiven;
1841 objgiven = refobj != NULL;
1843 if (libmap_disable || !objgiven ||
1844 (name = lm_find(refobj->path, xname)) == NULL)
1847 if (strchr(name, '/') != NULL) { /* Hard coded pathname */
1848 if (name[0] != '/' && !trust) {
1849 _rtld_error("Absolute pathname required "
1850 "for shared object \"%s\"", name);
1853 return (origin_subst(__DECONST(Obj_Entry *, refobj),
1854 __DECONST(char *, name)));
1857 dbg(" Searching for \"%s\"", name);
1858 refobj_path = objgiven ? refobj->path : NULL;
1861 * If refobj->rpath != NULL, then refobj->runpath is NULL. Fall
1862 * back to pre-conforming behaviour if user requested so with
1863 * LD_LIBRARY_PATH_RPATH environment variable and ignore -z
1866 if (objgiven && refobj->rpath != NULL && ld_library_path_rpath) {
1867 pathname = search_library_path(name, ld_library_path,
1869 if (pathname != NULL)
1871 if (refobj != NULL) {
1872 pathname = search_library_path(name, refobj->rpath,
1874 if (pathname != NULL)
1877 pathname = search_library_pathfds(name, ld_library_dirs, fdp);
1878 if (pathname != NULL)
1880 pathname = search_library_path(name, gethints(false),
1882 if (pathname != NULL)
1884 pathname = search_library_path(name, ld_standard_library_path,
1886 if (pathname != NULL)
1889 nodeflib = objgiven ? refobj->z_nodeflib : false;
1891 pathname = search_library_path(name, refobj->rpath,
1893 if (pathname != NULL)
1896 if (objgiven && refobj->runpath == NULL && refobj != obj_main) {
1897 pathname = search_library_path(name, obj_main->rpath,
1899 if (pathname != NULL)
1902 pathname = search_library_path(name, ld_library_path,
1904 if (pathname != NULL)
1907 pathname = search_library_path(name, refobj->runpath,
1909 if (pathname != NULL)
1912 pathname = search_library_pathfds(name, ld_library_dirs, fdp);
1913 if (pathname != NULL)
1915 pathname = search_library_path(name, gethints(nodeflib),
1917 if (pathname != NULL)
1919 if (objgiven && !nodeflib) {
1920 pathname = search_library_path(name,
1921 ld_standard_library_path, refobj_path, fdp);
1922 if (pathname != NULL)
1927 if (objgiven && refobj->path != NULL) {
1928 _rtld_error("Shared object \"%s\" not found, "
1929 "required by \"%s\"", name, basename(refobj->path));
1931 _rtld_error("Shared object \"%s\" not found", name);
1937 * Given a symbol number in a referencing object, find the corresponding
1938 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1939 * no definition was found. Returns a pointer to the Obj_Entry of the
1940 * defining object via the reference parameter DEFOBJ_OUT.
1943 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1944 const Obj_Entry **defobj_out, int flags, SymCache *cache,
1945 RtldLockState *lockstate)
1949 const Obj_Entry *defobj;
1950 const Ver_Entry *ve;
1956 * If we have already found this symbol, get the information from
1959 if (symnum >= refobj->dynsymcount)
1960 return NULL; /* Bad object */
1961 if (cache != NULL && cache[symnum].sym != NULL) {
1962 *defobj_out = cache[symnum].obj;
1963 return cache[symnum].sym;
1966 ref = refobj->symtab + symnum;
1967 name = refobj->strtab + ref->st_name;
1973 * We don't have to do a full scale lookup if the symbol is local.
1974 * We know it will bind to the instance in this load module; to
1975 * which we already have a pointer (ie ref). By not doing a lookup,
1976 * we not only improve performance, but it also avoids unresolvable
1977 * symbols when local symbols are not in the hash table. This has
1978 * been seen with the ia64 toolchain.
1980 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1981 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1982 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1985 symlook_init(&req, name);
1987 ve = req.ventry = fetch_ventry(refobj, symnum);
1988 req.lockstate = lockstate;
1989 res = symlook_default(&req, refobj);
1992 defobj = req.defobj_out;
2000 * If we found no definition and the reference is weak, treat the
2001 * symbol as having the value zero.
2003 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
2009 *defobj_out = defobj;
2010 /* Record the information in the cache to avoid subsequent lookups. */
2011 if (cache != NULL) {
2012 cache[symnum].sym = def;
2013 cache[symnum].obj = defobj;
2016 if (refobj != &obj_rtld)
2017 _rtld_error("%s: Undefined symbol \"%s%s%s\"", refobj->path, name,
2018 ve != NULL ? "@" : "", ve != NULL ? ve->name : "");
2024 * Return the search path from the ldconfig hints file, reading it if
2025 * necessary. If nostdlib is true, then the default search paths are
2026 * not added to result.
2028 * Returns NULL if there are problems with the hints file,
2029 * or if the search path there is empty.
2032 gethints(bool nostdlib)
2034 static char *filtered_path;
2035 static const char *hints;
2036 static struct elfhints_hdr hdr;
2037 struct fill_search_info_args sargs, hargs;
2038 struct dl_serinfo smeta, hmeta, *SLPinfo, *hintinfo;
2039 struct dl_serpath *SLPpath, *hintpath;
2041 struct stat hint_stat;
2042 unsigned int SLPndx, hintndx, fndx, fcount;
2048 /* First call, read the hints file */
2049 if (hints == NULL) {
2050 /* Keep from trying again in case the hints file is bad. */
2053 if ((fd = open(ld_elf_hints_path, O_RDONLY | O_CLOEXEC)) == -1)
2057 * Check of hdr.dirlistlen value against type limit
2058 * intends to pacify static analyzers. Further
2059 * paranoia leads to checks that dirlist is fully
2060 * contained in the file range.
2062 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
2063 hdr.magic != ELFHINTS_MAGIC ||
2064 hdr.version != 1 || hdr.dirlistlen > UINT_MAX / 2 ||
2065 fstat(fd, &hint_stat) == -1) {
2072 if (dl + hdr.dirlist < dl)
2075 if (dl + hdr.dirlistlen < dl)
2077 dl += hdr.dirlistlen;
2078 if (dl > hint_stat.st_size)
2080 p = xmalloc(hdr.dirlistlen + 1);
2081 if (pread(fd, p, hdr.dirlistlen + 1,
2082 hdr.strtab + hdr.dirlist) != (ssize_t)hdr.dirlistlen + 1 ||
2083 p[hdr.dirlistlen] != '\0') {
2092 * If caller agreed to receive list which includes the default
2093 * paths, we are done. Otherwise, if we still did not
2094 * calculated filtered result, do it now.
2097 return (hints[0] != '\0' ? hints : NULL);
2098 if (filtered_path != NULL)
2102 * Obtain the list of all configured search paths, and the
2103 * list of the default paths.
2105 * First estimate the size of the results.
2107 smeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2109 hmeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2112 sargs.request = RTLD_DI_SERINFOSIZE;
2113 sargs.serinfo = &smeta;
2114 hargs.request = RTLD_DI_SERINFOSIZE;
2115 hargs.serinfo = &hmeta;
2117 path_enumerate(ld_standard_library_path, fill_search_info, NULL,
2119 path_enumerate(hints, fill_search_info, NULL, &hargs);
2121 SLPinfo = xmalloc(smeta.dls_size);
2122 hintinfo = xmalloc(hmeta.dls_size);
2125 * Next fetch both sets of paths.
2127 sargs.request = RTLD_DI_SERINFO;
2128 sargs.serinfo = SLPinfo;
2129 sargs.serpath = &SLPinfo->dls_serpath[0];
2130 sargs.strspace = (char *)&SLPinfo->dls_serpath[smeta.dls_cnt];
2132 hargs.request = RTLD_DI_SERINFO;
2133 hargs.serinfo = hintinfo;
2134 hargs.serpath = &hintinfo->dls_serpath[0];
2135 hargs.strspace = (char *)&hintinfo->dls_serpath[hmeta.dls_cnt];
2137 path_enumerate(ld_standard_library_path, fill_search_info, NULL,
2139 path_enumerate(hints, fill_search_info, NULL, &hargs);
2142 * Now calculate the difference between two sets, by excluding
2143 * standard paths from the full set.
2147 filtered_path = xmalloc(hdr.dirlistlen + 1);
2148 hintpath = &hintinfo->dls_serpath[0];
2149 for (hintndx = 0; hintndx < hmeta.dls_cnt; hintndx++, hintpath++) {
2151 SLPpath = &SLPinfo->dls_serpath[0];
2153 * Check each standard path against current.
2155 for (SLPndx = 0; SLPndx < smeta.dls_cnt; SLPndx++, SLPpath++) {
2156 /* matched, skip the path */
2157 if (!strcmp(hintpath->dls_name, SLPpath->dls_name)) {
2165 * Not matched against any standard path, add the path
2166 * to result. Separate consequtive paths with ':'.
2169 filtered_path[fndx] = ':';
2173 flen = strlen(hintpath->dls_name);
2174 strncpy((filtered_path + fndx), hintpath->dls_name, flen);
2177 filtered_path[fndx] = '\0';
2183 return (filtered_path[0] != '\0' ? filtered_path : NULL);
2187 init_dag(Obj_Entry *root)
2189 const Needed_Entry *needed;
2190 const Objlist_Entry *elm;
2193 if (root->dag_inited)
2195 donelist_init(&donelist);
2197 /* Root object belongs to own DAG. */
2198 objlist_push_tail(&root->dldags, root);
2199 objlist_push_tail(&root->dagmembers, root);
2200 donelist_check(&donelist, root);
2203 * Add dependencies of root object to DAG in breadth order
2204 * by exploiting the fact that each new object get added
2205 * to the tail of the dagmembers list.
2207 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2208 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
2209 if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
2211 objlist_push_tail(&needed->obj->dldags, root);
2212 objlist_push_tail(&root->dagmembers, needed->obj);
2215 root->dag_inited = true;
2219 init_marker(Obj_Entry *marker)
2222 bzero(marker, sizeof(*marker));
2223 marker->marker = true;
2227 globallist_curr(const Obj_Entry *obj)
2234 return (__DECONST(Obj_Entry *, obj));
2235 obj = TAILQ_PREV(obj, obj_entry_q, next);
2240 globallist_next(const Obj_Entry *obj)
2244 obj = TAILQ_NEXT(obj, next);
2248 return (__DECONST(Obj_Entry *, obj));
2252 /* Prevent the object from being unmapped while the bind lock is dropped. */
2254 hold_object(Obj_Entry *obj)
2261 unhold_object(Obj_Entry *obj)
2264 assert(obj->holdcount > 0);
2265 if (--obj->holdcount == 0 && obj->unholdfree)
2266 release_object(obj);
2270 process_z(Obj_Entry *root)
2272 const Objlist_Entry *elm;
2276 * Walk over object DAG and process every dependent object
2277 * that is marked as DF_1_NODELETE or DF_1_GLOBAL. They need
2278 * to grow their own DAG.
2280 * For DF_1_GLOBAL, DAG is required for symbol lookups in
2281 * symlook_global() to work.
2283 * For DF_1_NODELETE, the DAG should have its reference upped.
2285 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2289 if (obj->z_nodelete && !obj->ref_nodel) {
2290 dbg("obj %s -z nodelete", obj->path);
2293 obj->ref_nodel = true;
2295 if (obj->z_global && objlist_find(&list_global, obj) == NULL) {
2296 dbg("obj %s -z global", obj->path);
2297 objlist_push_tail(&list_global, obj);
2304 parse_rtld_phdr(Obj_Entry *obj)
2307 Elf_Addr note_start, note_end;
2309 obj->stack_flags = PF_X | PF_R | PF_W;
2310 for (ph = obj->phdr; (const char *)ph < (const char *)obj->phdr +
2311 obj->phsize; ph++) {
2312 switch (ph->p_type) {
2314 obj->stack_flags = ph->p_flags;
2317 obj->relro_page = obj->relocbase +
2318 trunc_page(ph->p_vaddr);
2319 obj->relro_size = round_page(ph->p_memsz);
2322 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
2323 note_end = note_start + ph->p_filesz;
2324 digest_notes(obj, note_start, note_end);
2331 * Initialize the dynamic linker. The argument is the address at which
2332 * the dynamic linker has been mapped into memory. The primary task of
2333 * this function is to relocate the dynamic linker.
2336 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
2338 Obj_Entry objtmp; /* Temporary rtld object */
2339 const Elf_Ehdr *ehdr;
2340 const Elf_Dyn *dyn_rpath;
2341 const Elf_Dyn *dyn_soname;
2342 const Elf_Dyn *dyn_runpath;
2344 #ifdef RTLD_INIT_PAGESIZES_EARLY
2345 /* The page size is required by the dynamic memory allocator. */
2346 init_pagesizes(aux_info);
2350 * Conjure up an Obj_Entry structure for the dynamic linker.
2352 * The "path" member can't be initialized yet because string constants
2353 * cannot yet be accessed. Below we will set it correctly.
2355 memset(&objtmp, 0, sizeof(objtmp));
2358 objtmp.mapbase = mapbase;
2360 objtmp.relocbase = mapbase;
2363 objtmp.dynamic = rtld_dynamic(&objtmp);
2364 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname, &dyn_runpath);
2365 assert(objtmp.needed == NULL);
2366 #if !defined(__mips__)
2367 /* MIPS has a bogus DT_TEXTREL. */
2368 assert(!objtmp.textrel);
2371 * Temporarily put the dynamic linker entry into the object list, so
2372 * that symbols can be found.
2374 relocate_objects(&objtmp, true, &objtmp, 0, NULL);
2376 ehdr = (Elf_Ehdr *)mapbase;
2377 objtmp.phdr = (Elf_Phdr *)((char *)mapbase + ehdr->e_phoff);
2378 objtmp.phsize = ehdr->e_phnum * sizeof(objtmp.phdr[0]);
2380 /* Initialize the object list. */
2381 TAILQ_INIT(&obj_list);
2383 /* Now that non-local variables can be accesses, copy out obj_rtld. */
2384 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
2386 #ifndef RTLD_INIT_PAGESIZES_EARLY
2387 /* The page size is required by the dynamic memory allocator. */
2388 init_pagesizes(aux_info);
2391 if (aux_info[AT_OSRELDATE] != NULL)
2392 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
2394 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname, dyn_runpath);
2396 /* Replace the path with a dynamically allocated copy. */
2397 obj_rtld.path = xstrdup(ld_path_rtld);
2399 parse_rtld_phdr(&obj_rtld);
2400 if (obj_enforce_relro(&obj_rtld) == -1)
2403 r_debug.r_version = R_DEBUG_VERSION;
2404 r_debug.r_brk = r_debug_state;
2405 r_debug.r_state = RT_CONSISTENT;
2406 r_debug.r_ldbase = obj_rtld.relocbase;
2410 * Retrieve the array of supported page sizes. The kernel provides the page
2411 * sizes in increasing order.
2414 init_pagesizes(Elf_Auxinfo **aux_info)
2416 static size_t psa[MAXPAGESIZES];
2420 if (aux_info[AT_PAGESIZES] != NULL && aux_info[AT_PAGESIZESLEN] !=
2422 size = aux_info[AT_PAGESIZESLEN]->a_un.a_val;
2423 pagesizes = aux_info[AT_PAGESIZES]->a_un.a_ptr;
2426 if (sysctlnametomib("hw.pagesizes", mib, &len) == 0)
2429 /* As a fallback, retrieve the base page size. */
2430 size = sizeof(psa[0]);
2431 if (aux_info[AT_PAGESZ] != NULL) {
2432 psa[0] = aux_info[AT_PAGESZ]->a_un.a_val;
2436 mib[1] = HW_PAGESIZE;
2440 if (sysctl(mib, len, psa, &size, NULL, 0) == -1) {
2441 _rtld_error("sysctl for hw.pagesize(s) failed");
2447 npagesizes = size / sizeof(pagesizes[0]);
2448 /* Discard any invalid entries at the end of the array. */
2449 while (npagesizes > 0 && pagesizes[npagesizes - 1] == 0)
2454 * Add the init functions from a needed object list (and its recursive
2455 * needed objects) to "list". This is not used directly; it is a helper
2456 * function for initlist_add_objects(). The write lock must be held
2457 * when this function is called.
2460 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
2462 /* Recursively process the successor needed objects. */
2463 if (needed->next != NULL)
2464 initlist_add_neededs(needed->next, list);
2466 /* Process the current needed object. */
2467 if (needed->obj != NULL)
2468 initlist_add_objects(needed->obj, needed->obj, list);
2472 * Scan all of the DAGs rooted in the range of objects from "obj" to
2473 * "tail" and add their init functions to "list". This recurses over
2474 * the DAGs and ensure the proper init ordering such that each object's
2475 * needed libraries are initialized before the object itself. At the
2476 * same time, this function adds the objects to the global finalization
2477 * list "list_fini" in the opposite order. The write lock must be
2478 * held when this function is called.
2481 initlist_add_objects(Obj_Entry *obj, Obj_Entry *tail, Objlist *list)
2485 if (obj->init_scanned || obj->init_done)
2487 obj->init_scanned = true;
2489 /* Recursively process the successor objects. */
2490 nobj = globallist_next(obj);
2491 if (nobj != NULL && obj != tail)
2492 initlist_add_objects(nobj, tail, list);
2494 /* Recursively process the needed objects. */
2495 if (obj->needed != NULL)
2496 initlist_add_neededs(obj->needed, list);
2497 if (obj->needed_filtees != NULL)
2498 initlist_add_neededs(obj->needed_filtees, list);
2499 if (obj->needed_aux_filtees != NULL)
2500 initlist_add_neededs(obj->needed_aux_filtees, list);
2502 /* Add the object to the init list. */
2503 objlist_push_tail(list, obj);
2505 /* Add the object to the global fini list in the reverse order. */
2506 if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL)
2507 && !obj->on_fini_list) {
2508 objlist_push_head(&list_fini, obj);
2509 obj->on_fini_list = true;
2514 #define FPTR_TARGET(f) ((Elf_Addr) (f))
2518 free_needed_filtees(Needed_Entry *n, RtldLockState *lockstate)
2520 Needed_Entry *needed, *needed1;
2522 for (needed = n; needed != NULL; needed = needed->next) {
2523 if (needed->obj != NULL) {
2524 dlclose_locked(needed->obj, lockstate);
2528 for (needed = n; needed != NULL; needed = needed1) {
2529 needed1 = needed->next;
2535 unload_filtees(Obj_Entry *obj, RtldLockState *lockstate)
2538 free_needed_filtees(obj->needed_filtees, lockstate);
2539 obj->needed_filtees = NULL;
2540 free_needed_filtees(obj->needed_aux_filtees, lockstate);
2541 obj->needed_aux_filtees = NULL;
2542 obj->filtees_loaded = false;
2546 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags,
2547 RtldLockState *lockstate)
2550 for (; needed != NULL; needed = needed->next) {
2551 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
2552 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
2553 RTLD_LOCAL, lockstate);
2558 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
2561 lock_restart_for_upgrade(lockstate);
2562 if (!obj->filtees_loaded) {
2563 load_filtee1(obj, obj->needed_filtees, flags, lockstate);
2564 load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate);
2565 obj->filtees_loaded = true;
2570 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
2574 for (; needed != NULL; needed = needed->next) {
2575 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
2576 flags & ~RTLD_LO_NOLOAD);
2577 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
2584 * Given a shared object, traverse its list of needed objects, and load
2585 * each of them. Returns 0 on success. Generates an error message and
2586 * returns -1 on failure.
2589 load_needed_objects(Obj_Entry *first, int flags)
2593 for (obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
2596 if (process_needed(obj, obj->needed, flags) == -1)
2603 load_preload_objects(const char *penv, bool isfd)
2608 char savech, *p, *psave;
2610 static const char delim[] = " \t:;";
2615 p = psave = xstrdup(penv);
2616 p += strspn(p, delim);
2617 while (*p != '\0') {
2618 len = strcspn(p, delim);
2624 fd = parse_integer(p);
2634 obj = load_object(name, fd, NULL, 0);
2637 return (-1); /* XXX - cleanup */
2639 obj->z_interpose = true;
2642 p += strspn(p, delim);
2644 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
2651 printable_path(const char *path)
2654 return (path == NULL ? "<unknown>" : path);
2658 * Load a shared object into memory, if it is not already loaded. The
2659 * object may be specified by name or by user-supplied file descriptor
2660 * fd_u. In the later case, the fd_u descriptor is not closed, but its
2663 * Returns a pointer to the Obj_Entry for the object. Returns NULL
2667 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
2676 TAILQ_FOREACH(obj, &obj_list, next) {
2677 if (obj->marker || obj->doomed)
2679 if (object_match_name(obj, name))
2683 path = find_library(name, refobj, &fd);
2691 * search_library_pathfds() opens a fresh file descriptor for the
2692 * library, so there is no need to dup().
2694 } else if (fd_u == -1) {
2696 * If we didn't find a match by pathname, or the name is not
2697 * supplied, open the file and check again by device and inode.
2698 * This avoids false mismatches caused by multiple links or ".."
2701 * To avoid a race, we open the file and use fstat() rather than
2704 if ((fd = open(path, O_RDONLY | O_CLOEXEC | O_VERIFY)) == -1) {
2705 _rtld_error("Cannot open \"%s\"", path);
2710 fd = fcntl(fd_u, F_DUPFD_CLOEXEC, 0);
2712 _rtld_error("Cannot dup fd");
2717 if (fstat(fd, &sb) == -1) {
2718 _rtld_error("Cannot fstat \"%s\"", printable_path(path));
2723 TAILQ_FOREACH(obj, &obj_list, next) {
2724 if (obj->marker || obj->doomed)
2726 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
2729 if (obj != NULL && name != NULL) {
2730 object_add_name(obj, name);
2735 if (flags & RTLD_LO_NOLOAD) {
2741 /* First use of this object, so we must map it in */
2742 obj = do_load_object(fd, name, path, &sb, flags);
2751 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
2758 * but first, make sure that environment variables haven't been
2759 * used to circumvent the noexec flag on a filesystem.
2761 if (dangerous_ld_env) {
2762 if (fstatfs(fd, &fs) != 0) {
2763 _rtld_error("Cannot fstatfs \"%s\"", printable_path(path));
2766 if (fs.f_flags & MNT_NOEXEC) {
2767 _rtld_error("Cannot execute objects on %s", fs.f_mntonname);
2771 dbg("loading \"%s\"", printable_path(path));
2772 obj = map_object(fd, printable_path(path), sbp);
2777 * If DT_SONAME is present in the object, digest_dynamic2 already
2778 * added it to the object names.
2781 object_add_name(obj, name);
2783 if (!digest_dynamic(obj, 0))
2785 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path,
2786 obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount);
2787 if (obj->z_pie && (flags & RTLD_LO_TRACE) == 0) {
2788 dbg("refusing to load PIE executable \"%s\"", obj->path);
2789 _rtld_error("Cannot load PIE binary %s as DSO", obj->path);
2792 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
2794 dbg("refusing to load non-loadable \"%s\"", obj->path);
2795 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
2799 obj->dlopened = (flags & RTLD_LO_DLOPEN) != 0;
2800 TAILQ_INSERT_TAIL(&obj_list, obj, next);
2803 linkmap_add(obj); /* for GDB & dlinfo() */
2804 max_stack_flags |= obj->stack_flags;
2806 dbg(" %p .. %p: %s", obj->mapbase,
2807 obj->mapbase + obj->mapsize - 1, obj->path);
2809 dbg(" WARNING: %s has impure text", obj->path);
2810 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
2816 munmap(obj->mapbase, obj->mapsize);
2822 obj_from_addr(const void *addr)
2826 TAILQ_FOREACH(obj, &obj_list, next) {
2829 if (addr < (void *) obj->mapbase)
2831 if (addr < (void *)(obj->mapbase + obj->mapsize))
2840 Elf_Addr *preinit_addr;
2843 preinit_addr = (Elf_Addr *)obj_main->preinit_array;
2844 if (preinit_addr == NULL)
2847 for (index = 0; index < obj_main->preinit_array_num; index++) {
2848 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) {
2849 dbg("calling preinit function for %s at %p", obj_main->path,
2850 (void *)preinit_addr[index]);
2851 LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index],
2852 0, 0, obj_main->path);
2853 call_init_pointer(obj_main, preinit_addr[index]);
2859 * Call the finalization functions for each of the objects in "list"
2860 * belonging to the DAG of "root" and referenced once. If NULL "root"
2861 * is specified, every finalization function will be called regardless
2862 * of the reference count and the list elements won't be freed. All of
2863 * the objects are expected to have non-NULL fini functions.
2866 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
2869 struct dlerror_save *saved_msg;
2870 Elf_Addr *fini_addr;
2873 assert(root == NULL || root->refcount == 1);
2876 root->doomed = true;
2879 * Preserve the current error message since a fini function might
2880 * call into the dynamic linker and overwrite it.
2882 saved_msg = errmsg_save();
2884 STAILQ_FOREACH(elm, list, link) {
2885 if (root != NULL && (elm->obj->refcount != 1 ||
2886 objlist_find(&root->dagmembers, elm->obj) == NULL))
2888 /* Remove object from fini list to prevent recursive invocation. */
2889 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2890 /* Ensure that new references cannot be acquired. */
2891 elm->obj->doomed = true;
2893 hold_object(elm->obj);
2894 lock_release(rtld_bind_lock, lockstate);
2896 * It is legal to have both DT_FINI and DT_FINI_ARRAY defined.
2897 * When this happens, DT_FINI_ARRAY is processed first.
2899 fini_addr = (Elf_Addr *)elm->obj->fini_array;
2900 if (fini_addr != NULL && elm->obj->fini_array_num > 0) {
2901 for (index = elm->obj->fini_array_num - 1; index >= 0;
2903 if (fini_addr[index] != 0 && fini_addr[index] != 1) {
2904 dbg("calling fini function for %s at %p",
2905 elm->obj->path, (void *)fini_addr[index]);
2906 LD_UTRACE(UTRACE_FINI_CALL, elm->obj,
2907 (void *)fini_addr[index], 0, 0, elm->obj->path);
2908 call_initfini_pointer(elm->obj, fini_addr[index]);
2912 if (elm->obj->fini != (Elf_Addr)NULL) {
2913 dbg("calling fini function for %s at %p", elm->obj->path,
2914 (void *)elm->obj->fini);
2915 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini,
2916 0, 0, elm->obj->path);
2917 call_initfini_pointer(elm->obj, elm->obj->fini);
2919 wlock_acquire(rtld_bind_lock, lockstate);
2920 unhold_object(elm->obj);
2921 /* No need to free anything if process is going down. */
2925 * We must restart the list traversal after every fini call
2926 * because a dlclose() call from the fini function or from
2927 * another thread might have modified the reference counts.
2931 } while (elm != NULL);
2932 errmsg_restore(saved_msg);
2936 * Call the initialization functions for each of the objects in
2937 * "list". All of the objects are expected to have non-NULL init
2941 objlist_call_init(Objlist *list, RtldLockState *lockstate)
2945 struct dlerror_save *saved_msg;
2946 Elf_Addr *init_addr;
2947 void (*reg)(void (*)(void));
2951 * Clean init_scanned flag so that objects can be rechecked and
2952 * possibly initialized earlier if any of vectors called below
2953 * cause the change by using dlopen.
2955 TAILQ_FOREACH(obj, &obj_list, next) {
2958 obj->init_scanned = false;
2962 * Preserve the current error message since an init function might
2963 * call into the dynamic linker and overwrite it.
2965 saved_msg = errmsg_save();
2966 STAILQ_FOREACH(elm, list, link) {
2967 if (elm->obj->init_done) /* Initialized early. */
2970 * Race: other thread might try to use this object before current
2971 * one completes the initialization. Not much can be done here
2972 * without better locking.
2974 elm->obj->init_done = true;
2975 hold_object(elm->obj);
2977 if (elm->obj == obj_main && obj_main->crt_no_init) {
2978 reg = (void (*)(void (*)(void)))get_program_var_addr(
2979 "__libc_atexit", lockstate);
2981 lock_release(rtld_bind_lock, lockstate);
2984 rtld_exit_ptr = rtld_nop_exit;
2988 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined.
2989 * When this happens, DT_INIT is processed first.
2991 if (elm->obj->init != (Elf_Addr)NULL) {
2992 dbg("calling init function for %s at %p", elm->obj->path,
2993 (void *)elm->obj->init);
2994 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init,
2995 0, 0, elm->obj->path);
2996 call_init_pointer(elm->obj, elm->obj->init);
2998 init_addr = (Elf_Addr *)elm->obj->init_array;
2999 if (init_addr != NULL) {
3000 for (index = 0; index < elm->obj->init_array_num; index++) {
3001 if (init_addr[index] != 0 && init_addr[index] != 1) {
3002 dbg("calling init function for %s at %p", elm->obj->path,
3003 (void *)init_addr[index]);
3004 LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
3005 (void *)init_addr[index], 0, 0, elm->obj->path);
3006 call_init_pointer(elm->obj, init_addr[index]);
3010 wlock_acquire(rtld_bind_lock, lockstate);
3011 unhold_object(elm->obj);
3013 errmsg_restore(saved_msg);
3017 objlist_clear(Objlist *list)
3021 while (!STAILQ_EMPTY(list)) {
3022 elm = STAILQ_FIRST(list);
3023 STAILQ_REMOVE_HEAD(list, link);
3028 static Objlist_Entry *
3029 objlist_find(Objlist *list, const Obj_Entry *obj)
3033 STAILQ_FOREACH(elm, list, link)
3034 if (elm->obj == obj)
3040 objlist_init(Objlist *list)
3046 objlist_push_head(Objlist *list, Obj_Entry *obj)
3050 elm = NEW(Objlist_Entry);
3052 STAILQ_INSERT_HEAD(list, elm, link);
3056 objlist_push_tail(Objlist *list, Obj_Entry *obj)
3060 elm = NEW(Objlist_Entry);
3062 STAILQ_INSERT_TAIL(list, elm, link);
3066 objlist_put_after(Objlist *list, Obj_Entry *listobj, Obj_Entry *obj)
3068 Objlist_Entry *elm, *listelm;
3070 STAILQ_FOREACH(listelm, list, link) {
3071 if (listelm->obj == listobj)
3074 elm = NEW(Objlist_Entry);
3076 if (listelm != NULL)
3077 STAILQ_INSERT_AFTER(list, listelm, elm, link);
3079 STAILQ_INSERT_TAIL(list, elm, link);
3083 objlist_remove(Objlist *list, Obj_Entry *obj)
3087 if ((elm = objlist_find(list, obj)) != NULL) {
3088 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
3094 * Relocate dag rooted in the specified object.
3095 * Returns 0 on success, or -1 on failure.
3099 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj,
3100 int flags, RtldLockState *lockstate)
3106 STAILQ_FOREACH(elm, &root->dagmembers, link) {
3107 error = relocate_object(elm->obj, bind_now, rtldobj, flags,
3116 * Prepare for, or clean after, relocating an object marked with
3117 * DT_TEXTREL or DF_TEXTREL. Before relocating, all read-only
3118 * segments are remapped read-write. After relocations are done, the
3119 * segment's permissions are returned back to the modes specified in
3120 * the phdrs. If any relocation happened, or always for wired
3121 * program, COW is triggered.
3124 reloc_textrel_prot(Obj_Entry *obj, bool before)
3131 for (l = obj->phsize / sizeof(*ph), ph = obj->phdr; l > 0;
3133 if (ph->p_type != PT_LOAD || (ph->p_flags & PF_W) != 0)
3135 base = obj->relocbase + trunc_page(ph->p_vaddr);
3136 sz = round_page(ph->p_vaddr + ph->p_filesz) -
3137 trunc_page(ph->p_vaddr);
3138 prot = before ? (PROT_READ | PROT_WRITE) :
3139 convert_prot(ph->p_flags);
3140 if (mprotect(base, sz, prot) == -1) {
3141 _rtld_error("%s: Cannot write-%sable text segment: %s",
3142 obj->path, before ? "en" : "dis",
3143 rtld_strerror(errno));
3151 * Relocate single object.
3152 * Returns 0 on success, or -1 on failure.
3155 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
3156 int flags, RtldLockState *lockstate)
3161 obj->relocated = true;
3163 dbg("relocating \"%s\"", obj->path);
3165 if (obj->symtab == NULL || obj->strtab == NULL ||
3166 !(obj->valid_hash_sysv || obj->valid_hash_gnu))
3167 dbg("object %s has no run-time symbol table", obj->path);
3169 /* There are relocations to the write-protected text segment. */
3170 if (obj->textrel && reloc_textrel_prot(obj, true) != 0)
3173 /* Process the non-PLT non-IFUNC relocations. */
3174 if (reloc_non_plt(obj, rtldobj, flags, lockstate))
3177 /* Re-protected the text segment. */
3178 if (obj->textrel && reloc_textrel_prot(obj, false) != 0)
3181 /* Set the special PLT or GOT entries. */
3184 /* Process the PLT relocations. */
3185 if (reloc_plt(obj, flags, lockstate) == -1)
3187 /* Relocate the jump slots if we are doing immediate binding. */
3188 if ((obj->bind_now || bind_now) && reloc_jmpslots(obj, flags,
3192 if (!obj->mainprog && obj_enforce_relro(obj) == -1)
3196 * Set up the magic number and version in the Obj_Entry. These
3197 * were checked in the crt1.o from the original ElfKit, so we
3198 * set them for backward compatibility.
3200 obj->magic = RTLD_MAGIC;
3201 obj->version = RTLD_VERSION;
3207 * Relocate newly-loaded shared objects. The argument is a pointer to
3208 * the Obj_Entry for the first such object. All objects from the first
3209 * to the end of the list of objects are relocated. Returns 0 on success,
3213 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
3214 int flags, RtldLockState *lockstate)
3219 for (error = 0, obj = first; obj != NULL;
3220 obj = TAILQ_NEXT(obj, next)) {
3223 error = relocate_object(obj, bind_now, rtldobj, flags,
3232 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
3233 * referencing STT_GNU_IFUNC symbols is postponed till the other
3234 * relocations are done. The indirect functions specified as
3235 * ifunc are allowed to call other symbols, so we need to have
3236 * objects relocated before asking for resolution from indirects.
3238 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
3239 * instead of the usual lazy handling of PLT slots. It is
3240 * consistent with how GNU does it.
3243 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags,
3244 RtldLockState *lockstate)
3247 if (obj->ifuncs_resolved)
3249 obj->ifuncs_resolved = true;
3250 if (!obj->irelative && !obj->irelative_nonplt &&
3251 !((obj->bind_now || bind_now) && obj->gnu_ifunc) &&
3252 !obj->non_plt_gnu_ifunc)
3254 if (obj_disable_relro(obj) == -1 ||
3255 (obj->irelative && reloc_iresolve(obj, lockstate) == -1) ||
3256 (obj->irelative_nonplt && reloc_iresolve_nonplt(obj,
3257 lockstate) == -1) ||
3258 ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
3259 reloc_gnu_ifunc(obj, flags, lockstate) == -1) ||
3260 (obj->non_plt_gnu_ifunc && reloc_non_plt(obj, &obj_rtld,
3261 flags | SYMLOOK_IFUNC, lockstate) == -1) ||
3262 obj_enforce_relro(obj) == -1)
3268 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags,
3269 RtldLockState *lockstate)
3274 STAILQ_FOREACH(elm, list, link) {
3278 if (resolve_object_ifunc(obj, bind_now, flags,
3286 * Cleanup procedure. It will be called (by the atexit mechanism) just
3287 * before the process exits.
3292 RtldLockState lockstate;
3294 wlock_acquire(rtld_bind_lock, &lockstate);
3296 objlist_call_fini(&list_fini, NULL, &lockstate);
3297 /* No need to remove the items from the list, since we are exiting. */
3298 if (!libmap_disable)
3300 lock_release(rtld_bind_lock, &lockstate);
3309 * Iterate over a search path, translate each element, and invoke the
3310 * callback on the result.
3313 path_enumerate(const char *path, path_enum_proc callback,
3314 const char *refobj_path, void *arg)
3320 path += strspn(path, ":;");
3321 while (*path != '\0') {
3325 len = strcspn(path, ":;");
3326 trans = lm_findn(refobj_path, path, len);
3328 res = callback(trans, strlen(trans), arg);
3330 res = callback(path, len, arg);
3336 path += strspn(path, ":;");
3342 struct try_library_args {
3351 try_library_path(const char *dir, size_t dirlen, void *param)
3353 struct try_library_args *arg;
3357 if (*dir == '/' || trust) {
3360 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
3363 pathname = arg->buffer;
3364 strncpy(pathname, dir, dirlen);
3365 pathname[dirlen] = '/';
3366 strcpy(pathname + dirlen + 1, arg->name);
3368 dbg(" Trying \"%s\"", pathname);
3369 fd = open(pathname, O_RDONLY | O_CLOEXEC | O_VERIFY);
3371 dbg(" Opened \"%s\", fd %d", pathname, fd);
3372 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
3373 strcpy(pathname, arg->buffer);
3377 dbg(" Failed to open \"%s\": %s",
3378 pathname, rtld_strerror(errno));
3385 search_library_path(const char *name, const char *path,
3386 const char *refobj_path, int *fdp)
3389 struct try_library_args arg;
3395 arg.namelen = strlen(name);
3396 arg.buffer = xmalloc(PATH_MAX);
3397 arg.buflen = PATH_MAX;
3400 p = path_enumerate(path, try_library_path, refobj_path, &arg);
3410 * Finds the library with the given name using the directory descriptors
3411 * listed in the LD_LIBRARY_PATH_FDS environment variable.
3413 * Returns a freshly-opened close-on-exec file descriptor for the library,
3414 * or -1 if the library cannot be found.
3417 search_library_pathfds(const char *name, const char *path, int *fdp)
3419 char *envcopy, *fdstr, *found, *last_token;
3423 dbg("%s('%s', '%s', fdp)", __func__, name, path);
3425 /* Don't load from user-specified libdirs into setuid binaries. */
3429 /* We can't do anything if LD_LIBRARY_PATH_FDS isn't set. */
3433 /* LD_LIBRARY_PATH_FDS only works with relative paths. */
3434 if (name[0] == '/') {
3435 dbg("Absolute path (%s) passed to %s", name, __func__);
3440 * Use strtok_r() to walk the FD:FD:FD list. This requires a local
3441 * copy of the path, as strtok_r rewrites separator tokens
3445 envcopy = xstrdup(path);
3446 for (fdstr = strtok_r(envcopy, ":", &last_token); fdstr != NULL;
3447 fdstr = strtok_r(NULL, ":", &last_token)) {
3448 dirfd = parse_integer(fdstr);
3450 _rtld_error("failed to parse directory FD: '%s'",
3454 fd = __sys_openat(dirfd, name, O_RDONLY | O_CLOEXEC | O_VERIFY);
3457 len = strlen(fdstr) + strlen(name) + 3;
3458 found = xmalloc(len);
3459 if (rtld_snprintf(found, len, "#%d/%s", dirfd, name) < 0) {
3460 _rtld_error("error generating '%d/%s'",
3464 dbg("open('%s') => %d", found, fd);
3475 dlclose(void *handle)
3477 RtldLockState lockstate;
3480 wlock_acquire(rtld_bind_lock, &lockstate);
3481 error = dlclose_locked(handle, &lockstate);
3482 lock_release(rtld_bind_lock, &lockstate);
3487 dlclose_locked(void *handle, RtldLockState *lockstate)
3491 root = dlcheck(handle);
3494 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
3497 /* Unreference the object and its dependencies. */
3498 root->dl_refcount--;
3500 if (root->refcount == 1) {
3502 * The object will be no longer referenced, so we must unload it.
3503 * First, call the fini functions.
3505 objlist_call_fini(&list_fini, root, lockstate);
3509 /* Finish cleaning up the newly-unreferenced objects. */
3510 GDB_STATE(RT_DELETE,&root->linkmap);
3511 unload_object(root, lockstate);
3512 GDB_STATE(RT_CONSISTENT,NULL);
3516 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
3523 if (*(lockinfo.dlerror_seen()) != 0)
3525 *lockinfo.dlerror_seen() = 1;
3526 return (lockinfo.dlerror_loc());
3530 * This function is deprecated and has no effect.
3533 dllockinit(void *context,
3534 void *(*_lock_create)(void *context) __unused,
3535 void (*_rlock_acquire)(void *lock) __unused,
3536 void (*_wlock_acquire)(void *lock) __unused,
3537 void (*_lock_release)(void *lock) __unused,
3538 void (*_lock_destroy)(void *lock) __unused,
3539 void (*context_destroy)(void *context))
3541 static void *cur_context;
3542 static void (*cur_context_destroy)(void *);
3544 /* Just destroy the context from the previous call, if necessary. */
3545 if (cur_context_destroy != NULL)
3546 cur_context_destroy(cur_context);
3547 cur_context = context;
3548 cur_context_destroy = context_destroy;
3552 dlopen(const char *name, int mode)
3555 return (rtld_dlopen(name, -1, mode));
3559 fdlopen(int fd, int mode)
3562 return (rtld_dlopen(NULL, fd, mode));
3566 rtld_dlopen(const char *name, int fd, int mode)
3568 RtldLockState lockstate;
3571 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
3572 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
3573 if (ld_tracing != NULL) {
3574 rlock_acquire(rtld_bind_lock, &lockstate);
3575 if (sigsetjmp(lockstate.env, 0) != 0)
3576 lock_upgrade(rtld_bind_lock, &lockstate);
3577 environ = __DECONST(char **, *get_program_var_addr("environ", &lockstate));
3578 lock_release(rtld_bind_lock, &lockstate);
3580 lo_flags = RTLD_LO_DLOPEN;
3581 if (mode & RTLD_NODELETE)
3582 lo_flags |= RTLD_LO_NODELETE;
3583 if (mode & RTLD_NOLOAD)
3584 lo_flags |= RTLD_LO_NOLOAD;
3585 if (mode & RTLD_DEEPBIND)
3586 lo_flags |= RTLD_LO_DEEPBIND;
3587 if (ld_tracing != NULL)
3588 lo_flags |= RTLD_LO_TRACE | RTLD_LO_IGNSTLS;
3590 return (dlopen_object(name, fd, obj_main, lo_flags,
3591 mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL));
3595 dlopen_cleanup(Obj_Entry *obj, RtldLockState *lockstate)
3600 if (obj->refcount == 0)
3601 unload_object(obj, lockstate);
3605 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
3606 int mode, RtldLockState *lockstate)
3608 Obj_Entry *old_obj_tail;
3611 RtldLockState mlockstate;
3614 dbg("dlopen_object name \"%s\" fd %d refobj \"%s\" lo_flags %#x mode %#x",
3615 name != NULL ? name : "<null>", fd, refobj == NULL ? "<null>" :
3616 refobj->path, lo_flags, mode);
3617 objlist_init(&initlist);
3619 if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) {
3620 wlock_acquire(rtld_bind_lock, &mlockstate);
3621 lockstate = &mlockstate;
3623 GDB_STATE(RT_ADD,NULL);
3625 old_obj_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
3627 if (name == NULL && fd == -1) {
3631 obj = load_object(name, fd, refobj, lo_flags);
3636 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
3637 objlist_push_tail(&list_global, obj);
3638 if (globallist_next(old_obj_tail) != NULL) {
3639 /* We loaded something new. */
3640 assert(globallist_next(old_obj_tail) == obj);
3641 if ((lo_flags & RTLD_LO_DEEPBIND) != 0)
3642 obj->symbolic = true;
3644 if ((lo_flags & (RTLD_LO_EARLY | RTLD_LO_IGNSTLS)) == 0 &&
3645 obj->static_tls && !allocate_tls_offset(obj)) {
3646 _rtld_error("%s: No space available "
3647 "for static Thread Local Storage", obj->path);
3651 result = load_needed_objects(obj, lo_flags & (RTLD_LO_DLOPEN |
3652 RTLD_LO_EARLY | RTLD_LO_IGNSTLS | RTLD_LO_TRACE));
3656 result = rtld_verify_versions(&obj->dagmembers);
3657 if (result != -1 && ld_tracing)
3659 if (result == -1 || relocate_object_dag(obj,
3660 (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld,
3661 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3663 dlopen_cleanup(obj, lockstate);
3665 } else if (lo_flags & RTLD_LO_EARLY) {
3667 * Do not call the init functions for early loaded
3668 * filtees. The image is still not initialized enough
3671 * Our object is found by the global object list and
3672 * will be ordered among all init calls done right
3673 * before transferring control to main.
3676 /* Make list of init functions to call. */
3677 initlist_add_objects(obj, obj, &initlist);
3680 * Process all no_delete or global objects here, given
3681 * them own DAGs to prevent their dependencies from being
3682 * unloaded. This has to be done after we have loaded all
3683 * of the dependencies, so that we do not miss any.
3689 * Bump the reference counts for objects on this DAG. If
3690 * this is the first dlopen() call for the object that was
3691 * already loaded as a dependency, initialize the dag
3697 if ((lo_flags & RTLD_LO_TRACE) != 0)
3700 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
3701 obj->z_nodelete) && !obj->ref_nodel) {
3702 dbg("obj %s nodelete", obj->path);
3704 obj->z_nodelete = obj->ref_nodel = true;
3708 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
3710 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
3712 if ((lo_flags & RTLD_LO_EARLY) == 0) {
3713 map_stacks_exec(lockstate);
3715 distribute_static_tls(&initlist, lockstate);
3718 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
3719 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3721 objlist_clear(&initlist);
3722 dlopen_cleanup(obj, lockstate);
3723 if (lockstate == &mlockstate)
3724 lock_release(rtld_bind_lock, lockstate);
3728 if (!(lo_flags & RTLD_LO_EARLY)) {
3729 /* Call the init functions. */
3730 objlist_call_init(&initlist, lockstate);
3732 objlist_clear(&initlist);
3733 if (lockstate == &mlockstate)
3734 lock_release(rtld_bind_lock, lockstate);
3737 trace_loaded_objects(obj);
3738 if (lockstate == &mlockstate)
3739 lock_release(rtld_bind_lock, lockstate);
3744 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
3748 const Obj_Entry *obj, *defobj;
3751 RtldLockState lockstate;
3758 symlook_init(&req, name);
3760 req.flags = flags | SYMLOOK_IN_PLT;
3761 req.lockstate = &lockstate;
3763 LD_UTRACE(UTRACE_DLSYM_START, handle, NULL, 0, 0, name);
3764 rlock_acquire(rtld_bind_lock, &lockstate);
3765 if (sigsetjmp(lockstate.env, 0) != 0)
3766 lock_upgrade(rtld_bind_lock, &lockstate);
3767 if (handle == NULL || handle == RTLD_NEXT ||
3768 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
3770 if ((obj = obj_from_addr(retaddr)) == NULL) {
3771 _rtld_error("Cannot determine caller's shared object");
3772 lock_release(rtld_bind_lock, &lockstate);
3773 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3776 if (handle == NULL) { /* Just the caller's shared object. */
3777 res = symlook_obj(&req, obj);
3780 defobj = req.defobj_out;
3782 } else if (handle == RTLD_NEXT || /* Objects after caller's */
3783 handle == RTLD_SELF) { /* ... caller included */
3784 if (handle == RTLD_NEXT)
3785 obj = globallist_next(obj);
3786 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
3789 res = symlook_obj(&req, obj);
3791 if (def == NULL || (ld_dynamic_weak &&
3792 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK)) {
3794 defobj = req.defobj_out;
3795 if (!ld_dynamic_weak ||
3796 ELF_ST_BIND(def->st_info) != STB_WEAK)
3802 * Search the dynamic linker itself, and possibly resolve the
3803 * symbol from there. This is how the application links to
3804 * dynamic linker services such as dlopen.
3805 * Note that we ignore ld_dynamic_weak == false case,
3806 * always overriding weak symbols by rtld definitions.
3808 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3809 res = symlook_obj(&req, &obj_rtld);
3812 defobj = req.defobj_out;
3816 assert(handle == RTLD_DEFAULT);
3817 res = symlook_default(&req, obj);
3819 defobj = req.defobj_out;
3824 if ((obj = dlcheck(handle)) == NULL) {
3825 lock_release(rtld_bind_lock, &lockstate);
3826 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3830 donelist_init(&donelist);
3831 if (obj->mainprog) {
3832 /* Handle obtained by dlopen(NULL, ...) implies global scope. */
3833 res = symlook_global(&req, &donelist);
3836 defobj = req.defobj_out;
3839 * Search the dynamic linker itself, and possibly resolve the
3840 * symbol from there. This is how the application links to
3841 * dynamic linker services such as dlopen.
3843 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3844 res = symlook_obj(&req, &obj_rtld);
3847 defobj = req.defobj_out;
3852 /* Search the whole DAG rooted at the given object. */
3853 res = symlook_list(&req, &obj->dagmembers, &donelist);
3856 defobj = req.defobj_out;
3862 lock_release(rtld_bind_lock, &lockstate);
3865 * The value required by the caller is derived from the value
3866 * of the symbol. this is simply the relocated value of the
3869 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
3870 sym = make_function_pointer(def, defobj);
3871 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
3872 sym = rtld_resolve_ifunc(defobj, def);
3873 else if (ELF_ST_TYPE(def->st_info) == STT_TLS) {
3874 ti.ti_module = defobj->tlsindex;
3875 ti.ti_offset = def->st_value;
3876 sym = __tls_get_addr(&ti);
3878 sym = defobj->relocbase + def->st_value;
3879 LD_UTRACE(UTRACE_DLSYM_STOP, handle, sym, 0, 0, name);
3883 _rtld_error("Undefined symbol \"%s%s%s\"", name, ve != NULL ? "@" : "",
3884 ve != NULL ? ve->name : "");
3885 lock_release(rtld_bind_lock, &lockstate);
3886 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3891 dlsym(void *handle, const char *name)
3893 return do_dlsym(handle, name, __builtin_return_address(0), NULL,
3898 dlfunc(void *handle, const char *name)
3905 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
3911 dlvsym(void *handle, const char *name, const char *version)
3915 ventry.name = version;
3917 ventry.hash = elf_hash(version);
3919 return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
3924 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
3926 const Obj_Entry *obj;
3927 RtldLockState lockstate;
3929 rlock_acquire(rtld_bind_lock, &lockstate);
3930 obj = obj_from_addr(addr);
3932 _rtld_error("No shared object contains address");
3933 lock_release(rtld_bind_lock, &lockstate);
3936 rtld_fill_dl_phdr_info(obj, phdr_info);
3937 lock_release(rtld_bind_lock, &lockstate);
3942 dladdr(const void *addr, Dl_info *info)
3944 const Obj_Entry *obj;
3947 unsigned long symoffset;
3948 RtldLockState lockstate;
3950 rlock_acquire(rtld_bind_lock, &lockstate);
3951 obj = obj_from_addr(addr);
3953 _rtld_error("No shared object contains address");
3954 lock_release(rtld_bind_lock, &lockstate);
3957 info->dli_fname = obj->path;
3958 info->dli_fbase = obj->mapbase;
3959 info->dli_saddr = (void *)0;
3960 info->dli_sname = NULL;
3963 * Walk the symbol list looking for the symbol whose address is
3964 * closest to the address sent in.
3966 for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) {
3967 def = obj->symtab + symoffset;
3970 * For skip the symbol if st_shndx is either SHN_UNDEF or
3973 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
3977 * If the symbol is greater than the specified address, or if it
3978 * is further away from addr than the current nearest symbol,
3981 symbol_addr = obj->relocbase + def->st_value;
3982 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
3985 /* Update our idea of the nearest symbol. */
3986 info->dli_sname = obj->strtab + def->st_name;
3987 info->dli_saddr = symbol_addr;
3990 if (info->dli_saddr == addr)
3993 lock_release(rtld_bind_lock, &lockstate);
3998 dlinfo(void *handle, int request, void *p)
4000 const Obj_Entry *obj;
4001 RtldLockState lockstate;
4004 rlock_acquire(rtld_bind_lock, &lockstate);
4006 if (handle == NULL || handle == RTLD_SELF) {
4009 retaddr = __builtin_return_address(0); /* __GNUC__ only */
4010 if ((obj = obj_from_addr(retaddr)) == NULL)
4011 _rtld_error("Cannot determine caller's shared object");
4013 obj = dlcheck(handle);
4016 lock_release(rtld_bind_lock, &lockstate);
4022 case RTLD_DI_LINKMAP:
4023 *((struct link_map const **)p) = &obj->linkmap;
4025 case RTLD_DI_ORIGIN:
4026 error = rtld_dirname(obj->path, p);
4029 case RTLD_DI_SERINFOSIZE:
4030 case RTLD_DI_SERINFO:
4031 error = do_search_info(obj, request, (struct dl_serinfo *)p);
4035 _rtld_error("Invalid request %d passed to dlinfo()", request);
4039 lock_release(rtld_bind_lock, &lockstate);
4045 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
4049 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
4050 phdr_info->dlpi_name = obj->path;
4051 phdr_info->dlpi_phdr = obj->phdr;
4052 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
4053 phdr_info->dlpi_tls_modid = obj->tlsindex;
4055 phdr_info->dlpi_tls_data = (char *)tls_get_addr_slow(dtvp,
4056 obj->tlsindex, 0, true) + TLS_DTV_OFFSET;
4057 phdr_info->dlpi_adds = obj_loads;
4058 phdr_info->dlpi_subs = obj_loads - obj_count;
4062 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
4064 struct dl_phdr_info phdr_info;
4065 Obj_Entry *obj, marker;
4066 RtldLockState bind_lockstate, phdr_lockstate;
4069 init_marker(&marker);
4072 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
4073 wlock_acquire(rtld_bind_lock, &bind_lockstate);
4074 for (obj = globallist_curr(TAILQ_FIRST(&obj_list)); obj != NULL;) {
4075 TAILQ_INSERT_AFTER(&obj_list, obj, &marker, next);
4076 rtld_fill_dl_phdr_info(obj, &phdr_info);
4078 lock_release(rtld_bind_lock, &bind_lockstate);
4080 error = callback(&phdr_info, sizeof phdr_info, param);
4082 wlock_acquire(rtld_bind_lock, &bind_lockstate);
4084 obj = globallist_next(&marker);
4085 TAILQ_REMOVE(&obj_list, &marker, next);
4087 lock_release(rtld_bind_lock, &bind_lockstate);
4088 lock_release(rtld_phdr_lock, &phdr_lockstate);
4094 rtld_fill_dl_phdr_info(&obj_rtld, &phdr_info);
4095 lock_release(rtld_bind_lock, &bind_lockstate);
4096 error = callback(&phdr_info, sizeof(phdr_info), param);
4098 lock_release(rtld_phdr_lock, &phdr_lockstate);
4103 fill_search_info(const char *dir, size_t dirlen, void *param)
4105 struct fill_search_info_args *arg;
4109 if (arg->request == RTLD_DI_SERINFOSIZE) {
4110 arg->serinfo->dls_cnt ++;
4111 arg->serinfo->dls_size += sizeof(struct dl_serpath) + dirlen + 1;
4113 struct dl_serpath *s_entry;
4115 s_entry = arg->serpath;
4116 s_entry->dls_name = arg->strspace;
4117 s_entry->dls_flags = arg->flags;
4119 strncpy(arg->strspace, dir, dirlen);
4120 arg->strspace[dirlen] = '\0';
4122 arg->strspace += dirlen + 1;
4130 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
4132 struct dl_serinfo _info;
4133 struct fill_search_info_args args;
4135 args.request = RTLD_DI_SERINFOSIZE;
4136 args.serinfo = &_info;
4138 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
4141 path_enumerate(obj->rpath, fill_search_info, NULL, &args);
4142 path_enumerate(ld_library_path, fill_search_info, NULL, &args);
4143 path_enumerate(obj->runpath, fill_search_info, NULL, &args);
4144 path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args);
4145 if (!obj->z_nodeflib)
4146 path_enumerate(ld_standard_library_path, fill_search_info, NULL, &args);
4149 if (request == RTLD_DI_SERINFOSIZE) {
4150 info->dls_size = _info.dls_size;
4151 info->dls_cnt = _info.dls_cnt;
4155 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
4156 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
4160 args.request = RTLD_DI_SERINFO;
4161 args.serinfo = info;
4162 args.serpath = &info->dls_serpath[0];
4163 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
4165 args.flags = LA_SER_RUNPATH;
4166 if (path_enumerate(obj->rpath, fill_search_info, NULL, &args) != NULL)
4169 args.flags = LA_SER_LIBPATH;
4170 if (path_enumerate(ld_library_path, fill_search_info, NULL, &args) != NULL)
4173 args.flags = LA_SER_RUNPATH;
4174 if (path_enumerate(obj->runpath, fill_search_info, NULL, &args) != NULL)
4177 args.flags = LA_SER_CONFIG;
4178 if (path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args)
4182 args.flags = LA_SER_DEFAULT;
4183 if (!obj->z_nodeflib && path_enumerate(ld_standard_library_path,
4184 fill_search_info, NULL, &args) != NULL)
4190 rtld_dirname(const char *path, char *bname)
4194 /* Empty or NULL string gets treated as "." */
4195 if (path == NULL || *path == '\0') {
4201 /* Strip trailing slashes */
4202 endp = path + strlen(path) - 1;
4203 while (endp > path && *endp == '/')
4206 /* Find the start of the dir */
4207 while (endp > path && *endp != '/')
4210 /* Either the dir is "/" or there are no slashes */
4212 bname[0] = *endp == '/' ? '/' : '.';
4218 } while (endp > path && *endp == '/');
4221 if (endp - path + 2 > PATH_MAX)
4223 _rtld_error("Filename is too long: %s", path);
4227 strncpy(bname, path, endp - path + 1);
4228 bname[endp - path + 1] = '\0';
4233 rtld_dirname_abs(const char *path, char *base)
4237 if (realpath(path, base) == NULL) {
4238 _rtld_error("realpath \"%s\" failed (%s)", path,
4239 rtld_strerror(errno));
4242 dbg("%s -> %s", path, base);
4243 last = strrchr(base, '/');
4245 _rtld_error("non-abs result from realpath \"%s\"", path);
4254 linkmap_add(Obj_Entry *obj)
4256 struct link_map *l, *prev;
4259 l->l_name = obj->path;
4260 l->l_base = obj->mapbase;
4261 l->l_ld = obj->dynamic;
4262 l->l_addr = obj->relocbase;
4264 if (r_debug.r_map == NULL) {
4270 * Scan to the end of the list, but not past the entry for the
4271 * dynamic linker, which we want to keep at the very end.
4273 for (prev = r_debug.r_map;
4274 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
4275 prev = prev->l_next)
4278 /* Link in the new entry. */
4280 l->l_next = prev->l_next;
4281 if (l->l_next != NULL)
4282 l->l_next->l_prev = l;
4287 linkmap_delete(Obj_Entry *obj)
4292 if (l->l_prev == NULL) {
4293 if ((r_debug.r_map = l->l_next) != NULL)
4294 l->l_next->l_prev = NULL;
4298 if ((l->l_prev->l_next = l->l_next) != NULL)
4299 l->l_next->l_prev = l->l_prev;
4303 * Function for the debugger to set a breakpoint on to gain control.
4305 * The two parameters allow the debugger to easily find and determine
4306 * what the runtime loader is doing and to whom it is doing it.
4308 * When the loadhook trap is hit (r_debug_state, set at program
4309 * initialization), the arguments can be found on the stack:
4311 * +8 struct link_map *m
4312 * +4 struct r_debug *rd
4316 r_debug_state(struct r_debug* rd __unused, struct link_map *m __unused)
4319 * The following is a hack to force the compiler to emit calls to
4320 * this function, even when optimizing. If the function is empty,
4321 * the compiler is not obliged to emit any code for calls to it,
4322 * even when marked __noinline. However, gdb depends on those
4325 __compiler_membar();
4329 * A function called after init routines have completed. This can be used to
4330 * break before a program's entry routine is called, and can be used when
4331 * main is not available in the symbol table.
4334 _r_debug_postinit(struct link_map *m __unused)
4337 /* See r_debug_state(). */
4338 __compiler_membar();
4342 release_object(Obj_Entry *obj)
4345 if (obj->holdcount > 0) {
4346 obj->unholdfree = true;
4349 munmap(obj->mapbase, obj->mapsize);
4350 linkmap_delete(obj);
4355 * Get address of the pointer variable in the main program.
4356 * Prefer non-weak symbol over the weak one.
4358 static const void **
4359 get_program_var_addr(const char *name, RtldLockState *lockstate)
4364 symlook_init(&req, name);
4365 req.lockstate = lockstate;
4366 donelist_init(&donelist);
4367 if (symlook_global(&req, &donelist) != 0)
4369 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
4370 return ((const void **)make_function_pointer(req.sym_out,
4372 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
4373 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
4375 return ((const void **)(req.defobj_out->relocbase +
4376 req.sym_out->st_value));
4380 * Set a pointer variable in the main program to the given value. This
4381 * is used to set key variables such as "environ" before any of the
4382 * init functions are called.
4385 set_program_var(const char *name, const void *value)
4389 if ((addr = get_program_var_addr(name, NULL)) != NULL) {
4390 dbg("\"%s\": *%p <-- %p", name, addr, value);
4396 * Search the global objects, including dependencies and main object,
4397 * for the given symbol.
4400 symlook_global(SymLook *req, DoneList *donelist)
4403 const Objlist_Entry *elm;
4406 symlook_init_from_req(&req1, req);
4408 /* Search all objects loaded at program start up. */
4409 if (req->defobj_out == NULL || (ld_dynamic_weak &&
4410 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK)) {
4411 res = symlook_list(&req1, &list_main, donelist);
4412 if (res == 0 && (!ld_dynamic_weak || req->defobj_out == NULL ||
4413 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4414 req->sym_out = req1.sym_out;
4415 req->defobj_out = req1.defobj_out;
4416 assert(req->defobj_out != NULL);
4420 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
4421 STAILQ_FOREACH(elm, &list_global, link) {
4422 if (req->defobj_out != NULL && (!ld_dynamic_weak ||
4423 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK))
4425 res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
4426 if (res == 0 && (req->defobj_out == NULL ||
4427 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4428 req->sym_out = req1.sym_out;
4429 req->defobj_out = req1.defobj_out;
4430 assert(req->defobj_out != NULL);
4434 return (req->sym_out != NULL ? 0 : ESRCH);
4438 * Given a symbol name in a referencing object, find the corresponding
4439 * definition of the symbol. Returns a pointer to the symbol, or NULL if
4440 * no definition was found. Returns a pointer to the Obj_Entry of the
4441 * defining object via the reference parameter DEFOBJ_OUT.
4444 symlook_default(SymLook *req, const Obj_Entry *refobj)
4447 const Objlist_Entry *elm;
4451 donelist_init(&donelist);
4452 symlook_init_from_req(&req1, req);
4455 * Look first in the referencing object if linked symbolically,
4456 * and similarly handle protected symbols.
4458 res = symlook_obj(&req1, refobj);
4459 if (res == 0 && (refobj->symbolic ||
4460 ELF_ST_VISIBILITY(req1.sym_out->st_other) == STV_PROTECTED)) {
4461 req->sym_out = req1.sym_out;
4462 req->defobj_out = req1.defobj_out;
4463 assert(req->defobj_out != NULL);
4465 if (refobj->symbolic || req->defobj_out != NULL)
4466 donelist_check(&donelist, refobj);
4468 symlook_global(req, &donelist);
4470 /* Search all dlopened DAGs containing the referencing object. */
4471 STAILQ_FOREACH(elm, &refobj->dldags, link) {
4472 if (req->sym_out != NULL && (!ld_dynamic_weak ||
4473 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK))
4475 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
4476 if (res == 0 && (req->sym_out == NULL ||
4477 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4478 req->sym_out = req1.sym_out;
4479 req->defobj_out = req1.defobj_out;
4480 assert(req->defobj_out != NULL);
4485 * Search the dynamic linker itself, and possibly resolve the
4486 * symbol from there. This is how the application links to
4487 * dynamic linker services such as dlopen.
4489 if (req->sym_out == NULL ||
4490 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
4491 res = symlook_obj(&req1, &obj_rtld);
4493 req->sym_out = req1.sym_out;
4494 req->defobj_out = req1.defobj_out;
4495 assert(req->defobj_out != NULL);
4499 return (req->sym_out != NULL ? 0 : ESRCH);
4503 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
4506 const Obj_Entry *defobj;
4507 const Objlist_Entry *elm;
4513 STAILQ_FOREACH(elm, objlist, link) {
4514 if (donelist_check(dlp, elm->obj))
4516 symlook_init_from_req(&req1, req);
4517 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
4518 if (def == NULL || (ld_dynamic_weak &&
4519 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4521 defobj = req1.defobj_out;
4522 if (!ld_dynamic_weak || ELF_ST_BIND(def->st_info) != STB_WEAK)
4529 req->defobj_out = defobj;
4536 * Search the chain of DAGS cointed to by the given Needed_Entry
4537 * for a symbol of the given name. Each DAG is scanned completely
4538 * before advancing to the next one. Returns a pointer to the symbol,
4539 * or NULL if no definition was found.
4542 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
4545 const Needed_Entry *n;
4546 const Obj_Entry *defobj;
4552 symlook_init_from_req(&req1, req);
4553 for (n = needed; n != NULL; n = n->next) {
4554 if (n->obj == NULL ||
4555 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
4557 if (def == NULL || (ld_dynamic_weak &&
4558 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4560 defobj = req1.defobj_out;
4561 if (!ld_dynamic_weak || ELF_ST_BIND(def->st_info) != STB_WEAK)
4567 req->defobj_out = defobj;
4574 * Search the symbol table of a single shared object for a symbol of
4575 * the given name and version, if requested. Returns a pointer to the
4576 * symbol, or NULL if no definition was found. If the object is
4577 * filter, return filtered symbol from filtee.
4579 * The symbol's hash value is passed in for efficiency reasons; that
4580 * eliminates many recomputations of the hash value.
4583 symlook_obj(SymLook *req, const Obj_Entry *obj)
4587 int flags, res, mres;
4590 * If there is at least one valid hash at this point, we prefer to
4591 * use the faster GNU version if available.
4593 if (obj->valid_hash_gnu)
4594 mres = symlook_obj1_gnu(req, obj);
4595 else if (obj->valid_hash_sysv)
4596 mres = symlook_obj1_sysv(req, obj);
4601 if (obj->needed_filtees != NULL) {
4602 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4603 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4604 donelist_init(&donelist);
4605 symlook_init_from_req(&req1, req);
4606 res = symlook_needed(&req1, obj->needed_filtees, &donelist);
4608 req->sym_out = req1.sym_out;
4609 req->defobj_out = req1.defobj_out;
4613 if (obj->needed_aux_filtees != NULL) {
4614 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4615 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4616 donelist_init(&donelist);
4617 symlook_init_from_req(&req1, req);
4618 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
4620 req->sym_out = req1.sym_out;
4621 req->defobj_out = req1.defobj_out;
4629 /* Symbol match routine common to both hash functions */
4631 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result,
4632 const unsigned long symnum)
4635 const Elf_Sym *symp;
4638 symp = obj->symtab + symnum;
4639 strp = obj->strtab + symp->st_name;
4641 switch (ELF_ST_TYPE(symp->st_info)) {
4647 if (symp->st_value == 0)
4651 if (symp->st_shndx != SHN_UNDEF)
4654 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
4655 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
4662 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
4665 if (req->ventry == NULL) {
4666 if (obj->versyms != NULL) {
4667 verndx = VER_NDX(obj->versyms[symnum]);
4668 if (verndx > obj->vernum) {
4670 "%s: symbol %s references wrong version %d",
4671 obj->path, obj->strtab + symnum, verndx);
4675 * If we are not called from dlsym (i.e. this
4676 * is a normal relocation from unversioned
4677 * binary), accept the symbol immediately if
4678 * it happens to have first version after this
4679 * shared object became versioned. Otherwise,
4680 * if symbol is versioned and not hidden,
4681 * remember it. If it is the only symbol with
4682 * this name exported by the shared object, it
4683 * will be returned as a match by the calling
4684 * function. If symbol is global (verndx < 2)
4685 * accept it unconditionally.
4687 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
4688 verndx == VER_NDX_GIVEN) {
4689 result->sym_out = symp;
4692 else if (verndx >= VER_NDX_GIVEN) {
4693 if ((obj->versyms[symnum] & VER_NDX_HIDDEN)
4695 if (result->vsymp == NULL)
4696 result->vsymp = symp;
4702 result->sym_out = symp;
4705 if (obj->versyms == NULL) {
4706 if (object_match_name(obj, req->ventry->name)) {
4707 _rtld_error("%s: object %s should provide version %s "
4708 "for symbol %s", obj_rtld.path, obj->path,
4709 req->ventry->name, obj->strtab + symnum);
4713 verndx = VER_NDX(obj->versyms[symnum]);
4714 if (verndx > obj->vernum) {
4715 _rtld_error("%s: symbol %s references wrong version %d",
4716 obj->path, obj->strtab + symnum, verndx);
4719 if (obj->vertab[verndx].hash != req->ventry->hash ||
4720 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
4722 * Version does not match. Look if this is a
4723 * global symbol and if it is not hidden. If
4724 * global symbol (verndx < 2) is available,
4725 * use it. Do not return symbol if we are
4726 * called by dlvsym, because dlvsym looks for
4727 * a specific version and default one is not
4728 * what dlvsym wants.
4730 if ((req->flags & SYMLOOK_DLSYM) ||
4731 (verndx >= VER_NDX_GIVEN) ||
4732 (obj->versyms[symnum] & VER_NDX_HIDDEN))
4736 result->sym_out = symp;
4741 * Search for symbol using SysV hash function.
4742 * obj->buckets is known not to be NULL at this point; the test for this was
4743 * performed with the obj->valid_hash_sysv assignment.
4746 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj)
4748 unsigned long symnum;
4749 Sym_Match_Result matchres;
4751 matchres.sym_out = NULL;
4752 matchres.vsymp = NULL;
4753 matchres.vcount = 0;
4755 for (symnum = obj->buckets[req->hash % obj->nbuckets];
4756 symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
4757 if (symnum >= obj->nchains)
4758 return (ESRCH); /* Bad object */
4760 if (matched_symbol(req, obj, &matchres, symnum)) {
4761 req->sym_out = matchres.sym_out;
4762 req->defobj_out = obj;
4766 if (matchres.vcount == 1) {
4767 req->sym_out = matchres.vsymp;
4768 req->defobj_out = obj;
4774 /* Search for symbol using GNU hash function */
4776 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj)
4778 Elf_Addr bloom_word;
4779 const Elf32_Word *hashval;
4781 Sym_Match_Result matchres;
4782 unsigned int h1, h2;
4783 unsigned long symnum;
4785 matchres.sym_out = NULL;
4786 matchres.vsymp = NULL;
4787 matchres.vcount = 0;
4789 /* Pick right bitmask word from Bloom filter array */
4790 bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) &
4791 obj->maskwords_bm_gnu];
4793 /* Calculate modulus word size of gnu hash and its derivative */
4794 h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1);
4795 h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1));
4797 /* Filter out the "definitely not in set" queries */
4798 if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0)
4801 /* Locate hash chain and corresponding value element*/
4802 bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu];
4805 hashval = &obj->chain_zero_gnu[bucket];
4807 if (((*hashval ^ req->hash_gnu) >> 1) == 0) {
4808 symnum = hashval - obj->chain_zero_gnu;
4809 if (matched_symbol(req, obj, &matchres, symnum)) {
4810 req->sym_out = matchres.sym_out;
4811 req->defobj_out = obj;
4815 } while ((*hashval++ & 1) == 0);
4816 if (matchres.vcount == 1) {
4817 req->sym_out = matchres.vsymp;
4818 req->defobj_out = obj;
4825 trace_loaded_objects(Obj_Entry *obj)
4827 const char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
4830 if ((main_local = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_PROGNAME)) ==
4834 if ((fmt1 = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_FMT1)) == NULL)
4835 fmt1 = "\t%o => %p (%x)\n";
4837 if ((fmt2 = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_FMT2)) == NULL)
4838 fmt2 = "\t%o (%x)\n";
4840 list_containers = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_ALL);
4842 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
4843 Needed_Entry *needed;
4844 const char *name, *path;
4849 if (list_containers && obj->needed != NULL)
4850 rtld_printf("%s:\n", obj->path);
4851 for (needed = obj->needed; needed; needed = needed->next) {
4852 if (needed->obj != NULL) {
4853 if (needed->obj->traced && !list_containers)
4855 needed->obj->traced = true;
4856 path = needed->obj->path;
4860 name = obj->strtab + needed->name;
4861 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
4863 fmt = is_lib ? fmt1 : fmt2;
4864 while ((c = *fmt++) != '\0') {
4890 rtld_putstr(main_local);
4893 rtld_putstr(obj_main->path);
4900 rtld_printf("%d", sodp->sod_major);
4903 rtld_printf("%d", sodp->sod_minor);
4910 rtld_printf("%p", needed->obj ? needed->obj->mapbase :
4923 * Unload a dlopened object and its dependencies from memory and from
4924 * our data structures. It is assumed that the DAG rooted in the
4925 * object has already been unreferenced, and that the object has a
4926 * reference count of 0.
4929 unload_object(Obj_Entry *root, RtldLockState *lockstate)
4931 Obj_Entry marker, *obj, *next;
4933 assert(root->refcount == 0);
4936 * Pass over the DAG removing unreferenced objects from
4937 * appropriate lists.
4939 unlink_object(root);
4941 /* Unmap all objects that are no longer referenced. */
4942 for (obj = TAILQ_FIRST(&obj_list); obj != NULL; obj = next) {
4943 next = TAILQ_NEXT(obj, next);
4944 if (obj->marker || obj->refcount != 0)
4946 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase,
4947 obj->mapsize, 0, obj->path);
4948 dbg("unloading \"%s\"", obj->path);
4950 * Unlink the object now to prevent new references from
4951 * being acquired while the bind lock is dropped in
4952 * recursive dlclose() invocations.
4954 TAILQ_REMOVE(&obj_list, obj, next);
4957 if (obj->filtees_loaded) {
4959 init_marker(&marker);
4960 TAILQ_INSERT_BEFORE(next, &marker, next);
4961 unload_filtees(obj, lockstate);
4962 next = TAILQ_NEXT(&marker, next);
4963 TAILQ_REMOVE(&obj_list, &marker, next);
4965 unload_filtees(obj, lockstate);
4967 release_object(obj);
4972 unlink_object(Obj_Entry *root)
4976 if (root->refcount == 0) {
4977 /* Remove the object from the RTLD_GLOBAL list. */
4978 objlist_remove(&list_global, root);
4980 /* Remove the object from all objects' DAG lists. */
4981 STAILQ_FOREACH(elm, &root->dagmembers, link) {
4982 objlist_remove(&elm->obj->dldags, root);
4983 if (elm->obj != root)
4984 unlink_object(elm->obj);
4990 ref_dag(Obj_Entry *root)
4994 assert(root->dag_inited);
4995 STAILQ_FOREACH(elm, &root->dagmembers, link)
4996 elm->obj->refcount++;
5000 unref_dag(Obj_Entry *root)
5004 assert(root->dag_inited);
5005 STAILQ_FOREACH(elm, &root->dagmembers, link)
5006 elm->obj->refcount--;
5010 * Common code for MD __tls_get_addr().
5013 tls_get_addr_slow(Elf_Addr **dtvp, int index, size_t offset, bool locked)
5015 Elf_Addr *newdtv, *dtv;
5016 RtldLockState lockstate;
5020 /* Check dtv generation in case new modules have arrived */
5021 if (dtv[0] != tls_dtv_generation) {
5023 wlock_acquire(rtld_bind_lock, &lockstate);
5024 newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
5026 if (to_copy > tls_max_index)
5027 to_copy = tls_max_index;
5028 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
5029 newdtv[0] = tls_dtv_generation;
5030 newdtv[1] = tls_max_index;
5033 lock_release(rtld_bind_lock, &lockstate);
5034 dtv = *dtvp = newdtv;
5037 /* Dynamically allocate module TLS if necessary */
5038 if (dtv[index + 1] == 0) {
5039 /* Signal safe, wlock will block out signals. */
5041 wlock_acquire(rtld_bind_lock, &lockstate);
5042 if (!dtv[index + 1])
5043 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
5045 lock_release(rtld_bind_lock, &lockstate);
5047 return ((void *)(dtv[index + 1] + offset));
5051 tls_get_addr_common(Elf_Addr **dtvp, int index, size_t offset)
5056 /* Check dtv generation in case new modules have arrived */
5057 if (__predict_true(dtv[0] == tls_dtv_generation &&
5058 dtv[index + 1] != 0))
5059 return ((void *)(dtv[index + 1] + offset));
5060 return (tls_get_addr_slow(dtvp, index, offset, false));
5063 #ifdef TLS_VARIANT_I
5066 * Return pointer to allocated TLS block
5069 get_tls_block_ptr(void *tcb, size_t tcbsize)
5071 size_t extra_size, post_size, pre_size, tls_block_size;
5072 size_t tls_init_align;
5074 tls_init_align = MAX(obj_main->tlsalign, 1);
5076 /* Compute fragments sizes. */
5077 extra_size = tcbsize - TLS_TCB_SIZE;
5078 post_size = calculate_tls_post_size(tls_init_align);
5079 tls_block_size = tcbsize + post_size;
5080 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size;
5082 return ((char *)tcb - pre_size - extra_size);
5086 * Allocate Static TLS using the Variant I method.
5088 * For details on the layout, see lib/libc/gen/tls.c.
5090 * NB: rtld's tls_static_space variable includes TLS_TCB_SIZE and post_size as
5091 * it is based on tls_last_offset, and TLS offsets here are really TCB
5092 * offsets, whereas libc's tls_static_space is just the executable's static
5096 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
5100 Elf_Addr *dtv, **tcb;
5103 size_t extra_size, maxalign, post_size, pre_size, tls_block_size;
5104 size_t tls_init_align, tls_init_offset;
5106 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
5109 assert(tcbsize >= TLS_TCB_SIZE);
5110 maxalign = MAX(tcbalign, tls_static_max_align);
5111 tls_init_align = MAX(obj_main->tlsalign, 1);
5113 /* Compute fragmets sizes. */
5114 extra_size = tcbsize - TLS_TCB_SIZE;
5115 post_size = calculate_tls_post_size(tls_init_align);
5116 tls_block_size = tcbsize + post_size;
5117 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size;
5118 tls_block_size += pre_size + tls_static_space - TLS_TCB_SIZE - post_size;
5120 /* Allocate whole TLS block */
5121 tls_block = malloc_aligned(tls_block_size, maxalign, 0);
5122 tcb = (Elf_Addr **)(tls_block + pre_size + extra_size);
5124 if (oldtcb != NULL) {
5125 memcpy(tls_block, get_tls_block_ptr(oldtcb, tcbsize),
5127 free_aligned(get_tls_block_ptr(oldtcb, tcbsize));
5129 /* Adjust the DTV. */
5131 for (i = 0; i < dtv[1]; i++) {
5132 if (dtv[i+2] >= (Elf_Addr)oldtcb &&
5133 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
5134 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tcb;
5138 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
5140 dtv[0] = tls_dtv_generation;
5141 dtv[1] = tls_max_index;
5143 for (obj = globallist_curr(objs); obj != NULL;
5144 obj = globallist_next(obj)) {
5145 if (obj->tlsoffset == 0)
5147 tls_init_offset = obj->tlspoffset & (obj->tlsalign - 1);
5148 addr = (Elf_Addr)tcb + obj->tlsoffset;
5149 if (tls_init_offset > 0)
5150 memset((void *)addr, 0, tls_init_offset);
5151 if (obj->tlsinitsize > 0) {
5152 memcpy((void *)(addr + tls_init_offset), obj->tlsinit,
5155 if (obj->tlssize > obj->tlsinitsize) {
5156 memset((void *)(addr + tls_init_offset + obj->tlsinitsize),
5157 0, obj->tlssize - obj->tlsinitsize - tls_init_offset);
5159 dtv[obj->tlsindex + 1] = addr;
5167 free_tls(void *tcb, size_t tcbsize, size_t tcbalign __unused)
5170 Elf_Addr tlsstart, tlsend;
5172 size_t dtvsize, i, tls_init_align;
5174 assert(tcbsize >= TLS_TCB_SIZE);
5175 tls_init_align = MAX(obj_main->tlsalign, 1);
5177 /* Compute fragments sizes. */
5178 post_size = calculate_tls_post_size(tls_init_align);
5180 tlsstart = (Elf_Addr)tcb + TLS_TCB_SIZE + post_size;
5181 tlsend = (Elf_Addr)tcb + tls_static_space;
5183 dtv = *(Elf_Addr **)tcb;
5185 for (i = 0; i < dtvsize; i++) {
5186 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
5187 free((void*)dtv[i+2]);
5191 free_aligned(get_tls_block_ptr(tcb, tcbsize));
5194 #endif /* TLS_VARIANT_I */
5196 #ifdef TLS_VARIANT_II
5199 * Allocate Static TLS using the Variant II method.
5202 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
5205 size_t size, ralign;
5207 Elf_Addr *dtv, *olddtv;
5208 Elf_Addr segbase, oldsegbase, addr;
5212 if (tls_static_max_align > ralign)
5213 ralign = tls_static_max_align;
5214 size = roundup(tls_static_space, ralign) + roundup(tcbsize, ralign);
5216 assert(tcbsize >= 2*sizeof(Elf_Addr));
5217 tls = malloc_aligned(size, ralign, 0 /* XXX */);
5218 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
5220 segbase = (Elf_Addr)(tls + roundup(tls_static_space, ralign));
5221 ((Elf_Addr*)segbase)[0] = segbase;
5222 ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
5224 dtv[0] = tls_dtv_generation;
5225 dtv[1] = tls_max_index;
5229 * Copy the static TLS block over whole.
5231 oldsegbase = (Elf_Addr) oldtls;
5232 memcpy((void *)(segbase - tls_static_space),
5233 (const void *)(oldsegbase - tls_static_space),
5237 * If any dynamic TLS blocks have been created tls_get_addr(),
5240 olddtv = ((Elf_Addr**)oldsegbase)[1];
5241 for (i = 0; i < olddtv[1]; i++) {
5242 if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
5243 dtv[i+2] = olddtv[i+2];
5249 * We assume that this block was the one we created with
5250 * allocate_initial_tls().
5252 free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
5254 for (obj = objs; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
5255 if (obj->marker || obj->tlsoffset == 0)
5257 addr = segbase - obj->tlsoffset;
5258 memset((void*)(addr + obj->tlsinitsize),
5259 0, obj->tlssize - obj->tlsinitsize);
5261 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
5262 obj->static_tls_copied = true;
5264 dtv[obj->tlsindex + 1] = addr;
5268 return (void*) segbase;
5272 free_tls(void *tls, size_t tcbsize __unused, size_t tcbalign)
5275 size_t size, ralign;
5277 Elf_Addr tlsstart, tlsend;
5280 * Figure out the size of the initial TLS block so that we can
5281 * find stuff which ___tls_get_addr() allocated dynamically.
5284 if (tls_static_max_align > ralign)
5285 ralign = tls_static_max_align;
5286 size = roundup(tls_static_space, ralign);
5288 dtv = ((Elf_Addr**)tls)[1];
5290 tlsend = (Elf_Addr) tls;
5291 tlsstart = tlsend - size;
5292 for (i = 0; i < dtvsize; i++) {
5293 if (dtv[i + 2] != 0 && (dtv[i + 2] < tlsstart || dtv[i + 2] > tlsend)) {
5294 free_aligned((void *)dtv[i + 2]);
5298 free_aligned((void *)tlsstart);
5302 #endif /* TLS_VARIANT_II */
5305 * Allocate TLS block for module with given index.
5308 allocate_module_tls(int index)
5313 TAILQ_FOREACH(obj, &obj_list, next) {
5316 if (obj->tlsindex == index)
5320 _rtld_error("Can't find module with TLS index %d", index);
5324 p = malloc_aligned(obj->tlssize, obj->tlsalign, obj->tlspoffset);
5325 memcpy(p, obj->tlsinit, obj->tlsinitsize);
5326 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
5331 allocate_tls_offset(Obj_Entry *obj)
5338 if (obj->tlssize == 0) {
5339 obj->tls_done = true;
5343 if (tls_last_offset == 0)
5344 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign,
5347 off = calculate_tls_offset(tls_last_offset, tls_last_size,
5348 obj->tlssize, obj->tlsalign, obj->tlspoffset);
5350 obj->tlsoffset = off;
5351 #ifdef TLS_VARIANT_I
5352 off += obj->tlssize;
5356 * If we have already fixed the size of the static TLS block, we
5357 * must stay within that size. When allocating the static TLS, we
5358 * leave a small amount of space spare to be used for dynamically
5359 * loading modules which use static TLS.
5361 if (tls_static_space != 0) {
5362 if (off > tls_static_space)
5364 } else if (obj->tlsalign > tls_static_max_align) {
5365 tls_static_max_align = obj->tlsalign;
5368 tls_last_offset = off;
5369 tls_last_size = obj->tlssize;
5370 obj->tls_done = true;
5376 free_tls_offset(Obj_Entry *obj)
5380 * If we were the last thing to allocate out of the static TLS
5381 * block, we give our space back to the 'allocator'. This is a
5382 * simplistic workaround to allow libGL.so.1 to be loaded and
5383 * unloaded multiple times.
5385 size_t off = obj->tlsoffset;
5386 #ifdef TLS_VARIANT_I
5387 off += obj->tlssize;
5389 if (off == tls_last_offset) {
5390 tls_last_offset -= obj->tlssize;
5396 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
5399 RtldLockState lockstate;
5401 wlock_acquire(rtld_bind_lock, &lockstate);
5402 ret = allocate_tls(globallist_curr(TAILQ_FIRST(&obj_list)), oldtls,
5404 lock_release(rtld_bind_lock, &lockstate);
5409 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
5411 RtldLockState lockstate;
5413 wlock_acquire(rtld_bind_lock, &lockstate);
5414 free_tls(tcb, tcbsize, tcbalign);
5415 lock_release(rtld_bind_lock, &lockstate);
5419 object_add_name(Obj_Entry *obj, const char *name)
5425 entry = malloc(sizeof(Name_Entry) + len);
5427 if (entry != NULL) {
5428 strcpy(entry->name, name);
5429 STAILQ_INSERT_TAIL(&obj->names, entry, link);
5434 object_match_name(const Obj_Entry *obj, const char *name)
5438 STAILQ_FOREACH(entry, &obj->names, link) {
5439 if (strcmp(name, entry->name) == 0)
5446 locate_dependency(const Obj_Entry *obj, const char *name)
5448 const Objlist_Entry *entry;
5449 const Needed_Entry *needed;
5451 STAILQ_FOREACH(entry, &list_main, link) {
5452 if (object_match_name(entry->obj, name))
5456 for (needed = obj->needed; needed != NULL; needed = needed->next) {
5457 if (strcmp(obj->strtab + needed->name, name) == 0 ||
5458 (needed->obj != NULL && object_match_name(needed->obj, name))) {
5460 * If there is DT_NEEDED for the name we are looking for,
5461 * we are all set. Note that object might not be found if
5462 * dependency was not loaded yet, so the function can
5463 * return NULL here. This is expected and handled
5464 * properly by the caller.
5466 return (needed->obj);
5469 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
5475 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
5476 const Elf_Vernaux *vna)
5478 const Elf_Verdef *vd;
5479 const char *vername;
5481 vername = refobj->strtab + vna->vna_name;
5482 vd = depobj->verdef;
5484 _rtld_error("%s: version %s required by %s not defined",
5485 depobj->path, vername, refobj->path);
5489 if (vd->vd_version != VER_DEF_CURRENT) {
5490 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
5491 depobj->path, vd->vd_version);
5494 if (vna->vna_hash == vd->vd_hash) {
5495 const Elf_Verdaux *aux = (const Elf_Verdaux *)
5496 ((const char *)vd + vd->vd_aux);
5497 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
5500 if (vd->vd_next == 0)
5502 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5504 if (vna->vna_flags & VER_FLG_WEAK)
5506 _rtld_error("%s: version %s required by %s not found",
5507 depobj->path, vername, refobj->path);
5512 rtld_verify_object_versions(Obj_Entry *obj)
5514 const Elf_Verneed *vn;
5515 const Elf_Verdef *vd;
5516 const Elf_Verdaux *vda;
5517 const Elf_Vernaux *vna;
5518 const Obj_Entry *depobj;
5519 int maxvernum, vernum;
5521 if (obj->ver_checked)
5523 obj->ver_checked = true;
5527 * Walk over defined and required version records and figure out
5528 * max index used by any of them. Do very basic sanity checking
5532 while (vn != NULL) {
5533 if (vn->vn_version != VER_NEED_CURRENT) {
5534 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
5535 obj->path, vn->vn_version);
5538 vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux);
5540 vernum = VER_NEED_IDX(vna->vna_other);
5541 if (vernum > maxvernum)
5543 if (vna->vna_next == 0)
5545 vna = (const Elf_Vernaux *)((const char *)vna + vna->vna_next);
5547 if (vn->vn_next == 0)
5549 vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next);
5553 while (vd != NULL) {
5554 if (vd->vd_version != VER_DEF_CURRENT) {
5555 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
5556 obj->path, vd->vd_version);
5559 vernum = VER_DEF_IDX(vd->vd_ndx);
5560 if (vernum > maxvernum)
5562 if (vd->vd_next == 0)
5564 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5571 * Store version information in array indexable by version index.
5572 * Verify that object version requirements are satisfied along the
5575 obj->vernum = maxvernum + 1;
5576 obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry));
5579 while (vd != NULL) {
5580 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
5581 vernum = VER_DEF_IDX(vd->vd_ndx);
5582 assert(vernum <= maxvernum);
5583 vda = (const Elf_Verdaux *)((const char *)vd + vd->vd_aux);
5584 obj->vertab[vernum].hash = vd->vd_hash;
5585 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
5586 obj->vertab[vernum].file = NULL;
5587 obj->vertab[vernum].flags = 0;
5589 if (vd->vd_next == 0)
5591 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5595 while (vn != NULL) {
5596 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
5599 vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux);
5601 if (check_object_provided_version(obj, depobj, vna))
5603 vernum = VER_NEED_IDX(vna->vna_other);
5604 assert(vernum <= maxvernum);
5605 obj->vertab[vernum].hash = vna->vna_hash;
5606 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
5607 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
5608 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
5609 VER_INFO_HIDDEN : 0;
5610 if (vna->vna_next == 0)
5612 vna = (const Elf_Vernaux *)((const char *)vna + vna->vna_next);
5614 if (vn->vn_next == 0)
5616 vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next);
5622 rtld_verify_versions(const Objlist *objlist)
5624 Objlist_Entry *entry;
5628 STAILQ_FOREACH(entry, objlist, link) {
5630 * Skip dummy objects or objects that have their version requirements
5633 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
5635 if (rtld_verify_object_versions(entry->obj) == -1) {
5637 if (ld_tracing == NULL)
5641 if (rc == 0 || ld_tracing != NULL)
5642 rc = rtld_verify_object_versions(&obj_rtld);
5647 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
5652 vernum = VER_NDX(obj->versyms[symnum]);
5653 if (vernum >= obj->vernum) {
5654 _rtld_error("%s: symbol %s has wrong verneed value %d",
5655 obj->path, obj->strtab + symnum, vernum);
5656 } else if (obj->vertab[vernum].hash != 0) {
5657 return &obj->vertab[vernum];
5664 _rtld_get_stack_prot(void)
5667 return (stack_prot);
5671 _rtld_is_dlopened(void *arg)
5674 RtldLockState lockstate;
5677 rlock_acquire(rtld_bind_lock, &lockstate);
5680 obj = obj_from_addr(arg);
5682 _rtld_error("No shared object contains address");
5683 lock_release(rtld_bind_lock, &lockstate);
5686 res = obj->dlopened ? 1 : 0;
5687 lock_release(rtld_bind_lock, &lockstate);
5692 obj_remap_relro(Obj_Entry *obj, int prot)
5695 if (obj->relro_size > 0 && mprotect(obj->relro_page, obj->relro_size,
5697 _rtld_error("%s: Cannot set relro protection to %#x: %s",
5698 obj->path, prot, rtld_strerror(errno));
5705 obj_disable_relro(Obj_Entry *obj)
5708 return (obj_remap_relro(obj, PROT_READ | PROT_WRITE));
5712 obj_enforce_relro(Obj_Entry *obj)
5715 return (obj_remap_relro(obj, PROT_READ));
5719 map_stacks_exec(RtldLockState *lockstate)
5721 void (*thr_map_stacks_exec)(void);
5723 if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
5725 thr_map_stacks_exec = (void (*)(void))(uintptr_t)
5726 get_program_var_addr("__pthread_map_stacks_exec", lockstate);
5727 if (thr_map_stacks_exec != NULL) {
5728 stack_prot |= PROT_EXEC;
5729 thr_map_stacks_exec();
5734 distribute_static_tls(Objlist *list, RtldLockState *lockstate)
5738 void (*distrib)(size_t, void *, size_t, size_t);
5740 distrib = (void (*)(size_t, void *, size_t, size_t))(uintptr_t)
5741 get_program_var_addr("__pthread_distribute_static_tls", lockstate);
5742 if (distrib == NULL)
5744 STAILQ_FOREACH(elm, list, link) {
5746 if (obj->marker || !obj->tls_done || obj->static_tls_copied)
5748 distrib(obj->tlsoffset, obj->tlsinit, obj->tlsinitsize,
5750 obj->static_tls_copied = true;
5755 symlook_init(SymLook *dst, const char *name)
5758 bzero(dst, sizeof(*dst));
5760 dst->hash = elf_hash(name);
5761 dst->hash_gnu = gnu_hash(name);
5765 symlook_init_from_req(SymLook *dst, const SymLook *src)
5768 dst->name = src->name;
5769 dst->hash = src->hash;
5770 dst->hash_gnu = src->hash_gnu;
5771 dst->ventry = src->ventry;
5772 dst->flags = src->flags;
5773 dst->defobj_out = NULL;
5774 dst->sym_out = NULL;
5775 dst->lockstate = src->lockstate;
5779 open_binary_fd(const char *argv0, bool search_in_path,
5780 const char **binpath_res)
5782 char *binpath, *pathenv, *pe, *res1;
5788 if (search_in_path && strchr(argv0, '/') == NULL) {
5789 binpath = xmalloc(PATH_MAX);
5790 pathenv = getenv("PATH");
5791 if (pathenv == NULL) {
5792 _rtld_error("-p and no PATH environment variable");
5795 pathenv = strdup(pathenv);
5796 if (pathenv == NULL) {
5797 _rtld_error("Cannot allocate memory");
5802 while ((pe = strsep(&pathenv, ":")) != NULL) {
5803 if (strlcpy(binpath, pe, PATH_MAX) >= PATH_MAX)
5805 if (binpath[0] != '\0' &&
5806 strlcat(binpath, "/", PATH_MAX) >= PATH_MAX)
5808 if (strlcat(binpath, argv0, PATH_MAX) >= PATH_MAX)
5810 fd = open(binpath, O_RDONLY | O_CLOEXEC | O_VERIFY);
5811 if (fd != -1 || errno != ENOENT) {
5818 fd = open(argv0, O_RDONLY | O_CLOEXEC | O_VERIFY);
5823 _rtld_error("Cannot open %s: %s", argv0, rtld_strerror(errno));
5826 if (res != NULL && res[0] != '/') {
5827 res1 = xmalloc(PATH_MAX);
5828 if (realpath(res, res1) != NULL) {
5830 free(__DECONST(char *, res));
5841 * Parse a set of command-line arguments.
5844 parse_args(char* argv[], int argc, bool *use_pathp, int *fdp,
5850 int arglen, fd, i, j, mib[2];
5852 bool seen_b, seen_f;
5854 dbg("Parsing command-line arguments");
5857 seen_b = seen_f = false;
5859 for (i = 1; i < argc; i++ ) {
5861 dbg("argv[%d]: '%s'", i, arg);
5864 * rtld arguments end with an explicit "--" or with the first
5865 * non-prefixed argument.
5867 if (strcmp(arg, "--") == 0) {
5875 * All other arguments are single-character options that can
5876 * be combined, so we need to search through `arg` for them.
5878 arglen = strlen(arg);
5879 for (j = 1; j < arglen; j++) {
5882 print_usage(argv[0]);
5884 } else if (opt == 'b') {
5886 _rtld_error("Both -b and -f specified");
5893 } else if (opt == 'f') {
5895 _rtld_error("Both -b and -f specified");
5900 * -f XX can be used to specify a
5901 * descriptor for the binary named at
5902 * the command line (i.e., the later
5903 * argument will specify the process
5904 * name but the descriptor is what
5905 * will actually be executed).
5907 * -f must be the last option in, e.g., -abcf.
5909 if (j != arglen - 1) {
5910 _rtld_error("Invalid options: %s", arg);
5914 fd = parse_integer(argv[i]);
5917 "Invalid file descriptor: '%s'",
5924 } else if (opt == 'p') {
5926 } else if (opt == 'u') {
5928 } else if (opt == 'v') {
5931 mib[1] = HW_MACHINE;
5932 sz = sizeof(machine);
5933 sysctl(mib, nitems(mib), machine, &sz, NULL, 0);
5935 "FreeBSD ld-elf.so.1 %s\n"
5936 "FreeBSD_version %d\n"
5937 "Default lib path %s\n"
5942 __FreeBSD_version, ld_standard_library_path,
5943 ld_env_prefix, ld_elf_hints_default,
5944 ld_path_libmap_conf);
5947 _rtld_error("Invalid argument: '%s'", arg);
5948 print_usage(argv[0]);
5960 * Parse a file descriptor number without pulling in more of libc (e.g. atoi).
5963 parse_integer(const char *str)
5965 static const int RADIX = 10; /* XXXJA: possibly support hex? */
5972 for (c = *str; c != '\0'; c = *++str) {
5973 if (c < '0' || c > '9')
5980 /* Make sure we actually parsed something. */
5987 print_usage(const char *argv0)
5991 "Usage: %s [-h] [-b <exe>] [-f <FD>] [-p] [--] <binary> [<args>]\n"
5994 " -h Display this help message\n"
5995 " -b <exe> Execute <exe> instead of <binary>, arg0 is <binary>\n"
5996 " -f <FD> Execute <FD> instead of searching for <binary>\n"
5997 " -p Search in PATH for named binary\n"
5998 " -u Ignore LD_ environment variables\n"
5999 " -v Display identification information\n"
6000 " -- End of RTLD options\n"
6001 " <binary> Name of process to execute\n"
6002 " <args> Arguments to the executed process\n", argv0);
6006 * Overrides for libc_pic-provided functions.
6010 __getosreldate(void)
6020 oid[1] = KERN_OSRELDATE;
6022 len = sizeof(osrel);
6023 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
6024 if (error == 0 && osrel > 0 && len == sizeof(osrel))
6029 rtld_strerror(int errnum)
6032 if (errnum < 0 || errnum >= sys_nerr)
6033 return ("Unknown error");
6034 return (sys_errlist[errnum]);
6038 getenv(const char *name)
6040 return (__DECONST(char *, rtld_get_env_val(environ, name,
6046 malloc(size_t nbytes)
6049 return (__crt_malloc(nbytes));
6053 calloc(size_t num, size_t size)
6056 return (__crt_calloc(num, size));
6067 realloc(void *cp, size_t nbytes)
6070 return (__crt_realloc(cp, nbytes));
6073 extern int _rtld_version__FreeBSD_version __exported;
6074 int _rtld_version__FreeBSD_version = __FreeBSD_version;
6076 extern char _rtld_version_laddr_offset __exported;
6077 char _rtld_version_laddr_offset;
6079 extern char _rtld_version_dlpi_tls_data __exported;
6080 char _rtld_version_dlpi_tls_data;