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);
86 * Function declarations.
88 static const char *basename(const char *);
89 static void digest_dynamic1(Obj_Entry *, int, const Elf_Dyn **,
90 const Elf_Dyn **, const Elf_Dyn **);
91 static bool digest_dynamic2(Obj_Entry *, const Elf_Dyn *, const Elf_Dyn *,
93 static bool digest_dynamic(Obj_Entry *, int);
94 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
95 static void distribute_static_tls(Objlist *, RtldLockState *);
96 static Obj_Entry *dlcheck(void *);
97 static int dlclose_locked(void *, RtldLockState *);
98 static Obj_Entry *dlopen_object(const char *name, int fd, Obj_Entry *refobj,
99 int lo_flags, int mode, RtldLockState *lockstate);
100 static Obj_Entry *do_load_object(int, const char *, char *, struct stat *, int);
101 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
102 static bool donelist_check(DoneList *, const Obj_Entry *);
103 static void errmsg_restore(char *);
104 static char *errmsg_save(void);
105 static void *fill_search_info(const char *, size_t, void *);
106 static char *find_library(const char *, const Obj_Entry *, int *);
107 static const char *gethints(bool);
108 static void hold_object(Obj_Entry *);
109 static void unhold_object(Obj_Entry *);
110 static void init_dag(Obj_Entry *);
111 static void init_marker(Obj_Entry *);
112 static void init_pagesizes(Elf_Auxinfo **aux_info);
113 static void init_rtld(caddr_t, Elf_Auxinfo **);
114 static void initlist_add_neededs(Needed_Entry *, Objlist *);
115 static void initlist_add_objects(Obj_Entry *, Obj_Entry *, Objlist *);
116 static int initlist_objects_ifunc(Objlist *, bool, int, RtldLockState *);
117 static void linkmap_add(Obj_Entry *);
118 static void linkmap_delete(Obj_Entry *);
119 static void load_filtees(Obj_Entry *, int flags, RtldLockState *);
120 static void unload_filtees(Obj_Entry *, RtldLockState *);
121 static int load_needed_objects(Obj_Entry *, int);
122 static int load_preload_objects(void);
123 static Obj_Entry *load_object(const char *, int fd, const Obj_Entry *, int);
124 static void map_stacks_exec(RtldLockState *);
125 static int obj_disable_relro(Obj_Entry *);
126 static int obj_enforce_relro(Obj_Entry *);
127 static Obj_Entry *obj_from_addr(const void *);
128 static void objlist_call_fini(Objlist *, Obj_Entry *, RtldLockState *);
129 static void objlist_call_init(Objlist *, RtldLockState *);
130 static void objlist_clear(Objlist *);
131 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
132 static void objlist_init(Objlist *);
133 static void objlist_push_head(Objlist *, Obj_Entry *);
134 static void objlist_push_tail(Objlist *, Obj_Entry *);
135 static void objlist_put_after(Objlist *, Obj_Entry *, Obj_Entry *);
136 static void objlist_remove(Objlist *, Obj_Entry *);
137 static int open_binary_fd(const char *argv0, bool search_in_path,
138 const char **binpath_res);
139 static int parse_args(char* argv[], int argc, bool *use_pathp, int *fdp);
140 static int parse_integer(const char *);
141 static void *path_enumerate(const char *, path_enum_proc, const char *, void *);
142 static void print_usage(const char *argv0);
143 static void release_object(Obj_Entry *);
144 static int relocate_object_dag(Obj_Entry *root, bool bind_now,
145 Obj_Entry *rtldobj, int flags, RtldLockState *lockstate);
146 static int relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
147 int flags, RtldLockState *lockstate);
148 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, int,
150 static int resolve_object_ifunc(Obj_Entry *, bool, int, RtldLockState *);
151 static int rtld_dirname(const char *, char *);
152 static int rtld_dirname_abs(const char *, char *);
153 static void *rtld_dlopen(const char *name, int fd, int mode);
154 static void rtld_exit(void);
155 static void rtld_nop_exit(void);
156 static char *search_library_path(const char *, const char *, const char *,
158 static char *search_library_pathfds(const char *, const char *, int *);
159 static const void **get_program_var_addr(const char *, RtldLockState *);
160 static void set_program_var(const char *, const void *);
161 static int symlook_default(SymLook *, const Obj_Entry *refobj);
162 static int symlook_global(SymLook *, DoneList *);
163 static void symlook_init_from_req(SymLook *, const SymLook *);
164 static int symlook_list(SymLook *, const Objlist *, DoneList *);
165 static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *);
166 static int symlook_obj1_sysv(SymLook *, const Obj_Entry *);
167 static int symlook_obj1_gnu(SymLook *, const Obj_Entry *);
168 static void trace_loaded_objects(Obj_Entry *);
169 static void unlink_object(Obj_Entry *);
170 static void unload_object(Obj_Entry *, RtldLockState *lockstate);
171 static void unref_dag(Obj_Entry *);
172 static void ref_dag(Obj_Entry *);
173 static char *origin_subst_one(Obj_Entry *, char *, const char *,
175 static char *origin_subst(Obj_Entry *, const char *);
176 static bool obj_resolve_origin(Obj_Entry *obj);
177 static void preinit_main(void);
178 static int rtld_verify_versions(const Objlist *);
179 static int rtld_verify_object_versions(Obj_Entry *);
180 static void object_add_name(Obj_Entry *, const char *);
181 static int object_match_name(const Obj_Entry *, const char *);
182 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
183 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
184 struct dl_phdr_info *phdr_info);
185 static uint32_t gnu_hash(const char *);
186 static bool matched_symbol(SymLook *, const Obj_Entry *, Sym_Match_Result *,
187 const unsigned long);
189 void r_debug_state(struct r_debug *, struct link_map *) __noinline __exported;
190 void _r_debug_postinit(struct link_map *) __noinline __exported;
192 int __sys_openat(int, const char *, int, ...);
197 static char *error_message; /* Message for dlerror(), or NULL */
198 struct r_debug r_debug __exported; /* for GDB; */
199 static bool libmap_disable; /* Disable libmap */
200 static bool ld_loadfltr; /* Immediate filters processing */
201 static char *libmap_override; /* Maps to use in addition to libmap.conf */
202 static bool trust; /* False for setuid and setgid programs */
203 static bool dangerous_ld_env; /* True if environment variables have been
204 used to affect the libraries loaded */
205 bool ld_bind_not; /* Disable PLT update */
206 static char *ld_bind_now; /* Environment variable for immediate binding */
207 static char *ld_debug; /* Environment variable for debugging */
208 static char *ld_library_path; /* Environment variable for search path */
209 static char *ld_library_dirs; /* Environment variable for library descriptors */
210 static char *ld_preload; /* Environment variable for libraries to
212 static const char *ld_elf_hints_path; /* Environment variable for alternative hints path */
213 static const char *ld_tracing; /* Called from ldd to print libs */
214 static char *ld_utrace; /* Use utrace() to log events. */
215 static struct obj_entry_q obj_list; /* Queue of all loaded objects */
216 static Obj_Entry *obj_main; /* The main program shared object */
217 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
218 static unsigned int obj_count; /* Number of objects in obj_list */
219 static unsigned int obj_loads; /* Number of loads of objects (gen count) */
221 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
222 STAILQ_HEAD_INITIALIZER(list_global);
223 static Objlist list_main = /* Objects loaded at program startup */
224 STAILQ_HEAD_INITIALIZER(list_main);
225 static Objlist list_fini = /* Objects needing fini() calls */
226 STAILQ_HEAD_INITIALIZER(list_fini);
228 Elf_Sym sym_zero; /* For resolving undefined weak refs. */
230 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
232 extern Elf_Dyn _DYNAMIC;
233 #pragma weak _DYNAMIC
235 int dlclose(void *) __exported;
236 char *dlerror(void) __exported;
237 void *dlopen(const char *, int) __exported;
238 void *fdlopen(int, int) __exported;
239 void *dlsym(void *, const char *) __exported;
240 dlfunc_t dlfunc(void *, const char *) __exported;
241 void *dlvsym(void *, const char *, const char *) __exported;
242 int dladdr(const void *, Dl_info *) __exported;
243 void dllockinit(void *, void *(*)(void *), void (*)(void *), void (*)(void *),
244 void (*)(void *), void (*)(void *), void (*)(void *)) __exported;
245 int dlinfo(void *, int , void *) __exported;
246 int dl_iterate_phdr(__dl_iterate_hdr_callback, void *) __exported;
247 int _rtld_addr_phdr(const void *, struct dl_phdr_info *) __exported;
248 int _rtld_get_stack_prot(void) __exported;
249 int _rtld_is_dlopened(void *) __exported;
250 void _rtld_error(const char *, ...) __exported;
252 /* Only here to fix -Wmissing-prototypes warnings */
253 int __getosreldate(void);
254 func_ptr_type _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp);
255 Elf_Addr _rtld_bind(Obj_Entry *obj, Elf_Size reloff);
259 static int osreldate;
262 static int stack_prot = PROT_READ | PROT_WRITE | RTLD_DEFAULT_STACK_EXEC;
263 static int max_stack_flags;
266 * Global declarations normally provided by crt1. The dynamic linker is
267 * not built with crt1, so we have to provide them ourselves.
273 * Used to pass argc, argv to init functions.
279 * Globals to control TLS allocation.
281 size_t tls_last_offset; /* Static TLS offset of last module */
282 size_t tls_last_size; /* Static TLS size of last module */
283 size_t tls_static_space; /* Static TLS space allocated */
284 static size_t tls_static_max_align;
285 Elf_Addr tls_dtv_generation = 1; /* Used to detect when dtv size changes */
286 int tls_max_index = 1; /* Largest module index allocated */
288 static bool ld_library_path_rpath = false;
291 * Globals for path names, and such
293 const char *ld_elf_hints_default = _PATH_ELF_HINTS;
294 const char *ld_path_libmap_conf = _PATH_LIBMAP_CONF;
295 const char *ld_path_rtld = _PATH_RTLD;
296 const char *ld_standard_library_path = STANDARD_LIBRARY_PATH;
297 const char *ld_env_prefix = LD_;
299 static void (*rtld_exit_ptr)(void);
302 * Fill in a DoneList with an allocation large enough to hold all of
303 * the currently-loaded objects. Keep this as a macro since it calls
304 * alloca and we want that to occur within the scope of the caller.
306 #define donelist_init(dlp) \
307 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
308 assert((dlp)->objs != NULL), \
309 (dlp)->num_alloc = obj_count, \
312 #define LD_UTRACE(e, h, mb, ms, r, n) do { \
313 if (ld_utrace != NULL) \
314 ld_utrace_log(e, h, mb, ms, r, n); \
318 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
319 int refcnt, const char *name)
321 struct utrace_rtld ut;
322 static const char rtld_utrace_sig[RTLD_UTRACE_SIG_SZ] = RTLD_UTRACE_SIG;
324 memcpy(ut.sig, rtld_utrace_sig, sizeof(ut.sig));
327 ut.mapbase = mapbase;
328 ut.mapsize = mapsize;
330 bzero(ut.name, sizeof(ut.name));
332 strlcpy(ut.name, name, sizeof(ut.name));
333 utrace(&ut, sizeof(ut));
336 #ifdef RTLD_VARIANT_ENV_NAMES
338 * construct the env variable based on the type of binary that's
341 static inline const char *
344 static char buffer[128];
346 strlcpy(buffer, ld_env_prefix, sizeof(buffer));
347 strlcat(buffer, var, sizeof(buffer));
355 * Main entry point for dynamic linking. The first argument is the
356 * stack pointer. The stack is expected to be laid out as described
357 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
358 * Specifically, the stack pointer points to a word containing
359 * ARGC. Following that in the stack is a null-terminated sequence
360 * of pointers to argument strings. Then comes a null-terminated
361 * sequence of pointers to environment strings. Finally, there is a
362 * sequence of "auxiliary vector" entries.
364 * The second argument points to a place to store the dynamic linker's
365 * exit procedure pointer and the third to a place to store the main
368 * The return value is the main program's entry point.
371 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
373 Elf_Auxinfo *aux, *auxp, *auxpf, *aux_info[AT_COUNT];
374 Objlist_Entry *entry;
375 Obj_Entry *last_interposer, *obj, *preload_tail;
376 const Elf_Phdr *phdr;
378 RtldLockState lockstate;
381 char **argv, **env, **envp, *kexecpath, *library_path_rpath;
382 const char *argv0, *binpath;
384 char buf[MAXPATHLEN];
385 int argc, fd, i, phnum, rtld_argc;
387 int old_auxv_format = 1;
389 bool dir_enable, explicit_fd, search_in_path;
392 * On entry, the dynamic linker itself has not been relocated yet.
393 * Be very careful not to reference any global data until after
394 * init_rtld has returned. It is OK to reference file-scope statics
395 * and string constants, and to call static and global functions.
398 /* Find the auxiliary vector on the stack. */
402 sp += argc + 1; /* Skip over arguments and NULL terminator */
404 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
406 aux = (Elf_Auxinfo *) sp;
408 /* Digest the auxiliary vector. */
409 for (i = 0; i < AT_COUNT; i++)
411 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
412 if (auxp->a_type < AT_COUNT)
413 aux_info[auxp->a_type] = auxp;
415 if (auxp->a_type == 23) /* AT_STACKPROT */
421 if (old_auxv_format) {
422 /* Remap from old-style auxv numbers. */
423 aux_info[23] = aux_info[21]; /* AT_STACKPROT */
424 aux_info[21] = aux_info[19]; /* AT_PAGESIZESLEN */
425 aux_info[19] = aux_info[17]; /* AT_NCPUS */
426 aux_info[17] = aux_info[15]; /* AT_CANARYLEN */
427 aux_info[15] = aux_info[13]; /* AT_EXECPATH */
428 aux_info[13] = NULL; /* AT_GID */
430 aux_info[20] = aux_info[18]; /* AT_PAGESIZES */
431 aux_info[18] = aux_info[16]; /* AT_OSRELDATE */
432 aux_info[16] = aux_info[14]; /* AT_CANARY */
433 aux_info[14] = NULL; /* AT_EGID */
437 /* Initialize and relocate ourselves. */
438 assert(aux_info[AT_BASE] != NULL);
439 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
441 __progname = obj_rtld.path;
442 argv0 = argv[0] != NULL ? argv[0] : "(null)";
447 trust = !issetugid();
449 md_abi_variant_hook(aux_info);
452 if (aux_info[AT_EXECFD] != NULL) {
453 fd = aux_info[AT_EXECFD]->a_un.a_val;
455 assert(aux_info[AT_PHDR] != NULL);
456 phdr = (const Elf_Phdr *)aux_info[AT_PHDR]->a_un.a_ptr;
457 if (phdr == obj_rtld.phdr) {
459 _rtld_error("Tainted process refusing to run binary %s",
463 dbg("opening main program in direct exec mode");
465 rtld_argc = parse_args(argv, argc, &search_in_path, &fd);
466 argv0 = argv[rtld_argc];
467 explicit_fd = (fd != -1);
470 fd = open_binary_fd(argv0, search_in_path, &binpath);
471 if (fstat(fd, &st) == -1) {
472 _rtld_error("Failed to fstat FD %d (%s): %s", fd,
473 explicit_fd ? "user-provided descriptor" : argv0,
474 rtld_strerror(errno));
479 * Rough emulation of the permission checks done by
480 * execve(2), only Unix DACs are checked, ACLs are
481 * ignored. Preserve the semantic of disabling owner
482 * to execute if owner x bit is cleared, even if
483 * others x bit is enabled.
484 * mmap(2) does not allow to mmap with PROT_EXEC if
485 * binary' file comes from noexec mount. We cannot
486 * set a text reference on the binary.
489 if (st.st_uid == geteuid()) {
490 if ((st.st_mode & S_IXUSR) != 0)
492 } else if (st.st_gid == getegid()) {
493 if ((st.st_mode & S_IXGRP) != 0)
495 } else if ((st.st_mode & S_IXOTH) != 0) {
499 _rtld_error("No execute permission for binary %s",
505 * For direct exec mode, argv[0] is the interpreter
506 * name, we must remove it and shift arguments left
507 * before invoking binary main. Since stack layout
508 * places environment pointers and aux vectors right
509 * after the terminating NULL, we must shift
510 * environment and aux as well.
512 main_argc = argc - rtld_argc;
513 for (i = 0; i <= main_argc; i++)
514 argv[i] = argv[i + rtld_argc];
516 environ = env = envp = argv + main_argc + 1;
517 dbg("move env from %p to %p", envp + rtld_argc, envp);
519 *envp = *(envp + rtld_argc);
520 } while (*envp++ != NULL);
521 aux = auxp = (Elf_Auxinfo *)envp;
522 auxpf = (Elf_Auxinfo *)(envp + rtld_argc);
523 dbg("move aux from %p to %p", auxpf, aux);
524 /* XXXKIB insert place for AT_EXECPATH if not present */
525 for (;; auxp++, auxpf++) {
527 if (auxp->a_type == AT_NULL)
530 /* Since the auxiliary vector has moved, redigest it. */
531 for (i = 0; i < AT_COUNT; i++)
533 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
534 if (auxp->a_type < AT_COUNT)
535 aux_info[auxp->a_type] = auxp;
538 /* Point AT_EXECPATH auxv and aux_info to the binary path. */
539 if (binpath == NULL) {
540 aux_info[AT_EXECPATH] = NULL;
542 if (aux_info[AT_EXECPATH] == NULL) {
543 aux_info[AT_EXECPATH] = xmalloc(sizeof(Elf_Auxinfo));
544 aux_info[AT_EXECPATH]->a_type = AT_EXECPATH;
546 aux_info[AT_EXECPATH]->a_un.a_ptr = __DECONST(void *,
550 _rtld_error("No binary");
556 ld_bind_now = getenv(_LD("BIND_NOW"));
559 * If the process is tainted, then we un-set the dangerous environment
560 * variables. The process will be marked as tainted until setuid(2)
561 * is called. If any child process calls setuid(2) we do not want any
562 * future processes to honor the potentially un-safe variables.
565 if (unsetenv(_LD("PRELOAD")) || unsetenv(_LD("LIBMAP")) ||
566 unsetenv(_LD("LIBRARY_PATH")) || unsetenv(_LD("LIBRARY_PATH_FDS")) ||
567 unsetenv(_LD("LIBMAP_DISABLE")) || unsetenv(_LD("BIND_NOT")) ||
568 unsetenv(_LD("DEBUG")) || unsetenv(_LD("ELF_HINTS_PATH")) ||
569 unsetenv(_LD("LOADFLTR")) || unsetenv(_LD("LIBRARY_PATH_RPATH"))) {
570 _rtld_error("environment corrupt; aborting");
574 ld_debug = getenv(_LD("DEBUG"));
575 if (ld_bind_now == NULL)
576 ld_bind_not = getenv(_LD("BIND_NOT")) != NULL;
577 libmap_disable = getenv(_LD("LIBMAP_DISABLE")) != NULL;
578 libmap_override = getenv(_LD("LIBMAP"));
579 ld_library_path = getenv(_LD("LIBRARY_PATH"));
580 ld_library_dirs = getenv(_LD("LIBRARY_PATH_FDS"));
581 ld_preload = getenv(_LD("PRELOAD"));
582 ld_elf_hints_path = getenv(_LD("ELF_HINTS_PATH"));
583 ld_loadfltr = getenv(_LD("LOADFLTR")) != NULL;
584 library_path_rpath = getenv(_LD("LIBRARY_PATH_RPATH"));
585 if (library_path_rpath != NULL) {
586 if (library_path_rpath[0] == 'y' ||
587 library_path_rpath[0] == 'Y' ||
588 library_path_rpath[0] == '1')
589 ld_library_path_rpath = true;
591 ld_library_path_rpath = false;
593 dangerous_ld_env = libmap_disable || (libmap_override != NULL) ||
594 (ld_library_path != NULL) || (ld_preload != NULL) ||
595 (ld_elf_hints_path != NULL) || ld_loadfltr;
596 ld_tracing = getenv(_LD("TRACE_LOADED_OBJECTS"));
597 ld_utrace = getenv(_LD("UTRACE"));
599 if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0)
600 ld_elf_hints_path = ld_elf_hints_default;
602 if (ld_debug != NULL && *ld_debug != '\0')
604 dbg("%s is initialized, base address = %p", __progname,
605 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
606 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
607 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
609 dbg("initializing thread locks");
613 * Load the main program, or process its program header if it is
616 if (fd != -1) { /* Load the main program. */
617 dbg("loading main program");
618 obj_main = map_object(fd, argv0, NULL);
620 if (obj_main == NULL)
622 max_stack_flags = obj_main->stack_flags;
623 } else { /* Main program already loaded. */
624 dbg("processing main program's program header");
625 assert(aux_info[AT_PHDR] != NULL);
626 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
627 assert(aux_info[AT_PHNUM] != NULL);
628 phnum = aux_info[AT_PHNUM]->a_un.a_val;
629 assert(aux_info[AT_PHENT] != NULL);
630 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
631 assert(aux_info[AT_ENTRY] != NULL);
632 imgentry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
633 if ((obj_main = digest_phdr(phdr, phnum, imgentry, argv0)) == NULL)
637 if (aux_info[AT_EXECPATH] != NULL && fd == -1) {
638 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
639 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
640 if (kexecpath[0] == '/')
641 obj_main->path = kexecpath;
642 else if (getcwd(buf, sizeof(buf)) == NULL ||
643 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
644 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
645 obj_main->path = xstrdup(argv0);
647 obj_main->path = xstrdup(buf);
649 dbg("No AT_EXECPATH or direct exec");
650 obj_main->path = xstrdup(argv0);
652 dbg("obj_main path %s", obj_main->path);
653 obj_main->mainprog = true;
655 if (aux_info[AT_STACKPROT] != NULL &&
656 aux_info[AT_STACKPROT]->a_un.a_val != 0)
657 stack_prot = aux_info[AT_STACKPROT]->a_un.a_val;
661 * Get the actual dynamic linker pathname from the executable if
662 * possible. (It should always be possible.) That ensures that
663 * gdb will find the right dynamic linker even if a non-standard
666 if (obj_main->interp != NULL &&
667 strcmp(obj_main->interp, obj_rtld.path) != 0) {
669 obj_rtld.path = xstrdup(obj_main->interp);
670 __progname = obj_rtld.path;
674 if (!digest_dynamic(obj_main, 0))
676 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d",
677 obj_main->path, obj_main->valid_hash_sysv, obj_main->valid_hash_gnu,
678 obj_main->dynsymcount);
680 linkmap_add(obj_main);
681 linkmap_add(&obj_rtld);
683 /* Link the main program into the list of objects. */
684 TAILQ_INSERT_HEAD(&obj_list, obj_main, next);
688 /* Initialize a fake symbol for resolving undefined weak references. */
689 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
690 sym_zero.st_shndx = SHN_UNDEF;
691 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
694 libmap_disable = (bool)lm_init(libmap_override);
696 dbg("loading LD_PRELOAD libraries");
697 if (load_preload_objects() == -1)
699 preload_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
701 dbg("loading needed objects");
702 if (load_needed_objects(obj_main, 0) == -1)
705 /* Make a list of all objects loaded at startup. */
706 last_interposer = obj_main;
707 TAILQ_FOREACH(obj, &obj_list, next) {
710 if (obj->z_interpose && obj != obj_main) {
711 objlist_put_after(&list_main, last_interposer, obj);
712 last_interposer = obj;
714 objlist_push_tail(&list_main, obj);
719 dbg("checking for required versions");
720 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
723 if (ld_tracing) { /* We're done */
724 trace_loaded_objects(obj_main);
728 if (getenv(_LD("DUMP_REL_PRE")) != NULL) {
729 dump_relocations(obj_main);
734 * Processing tls relocations requires having the tls offsets
735 * initialized. Prepare offsets before starting initial
736 * relocation processing.
738 dbg("initializing initial thread local storage offsets");
739 STAILQ_FOREACH(entry, &list_main, link) {
741 * Allocate all the initial objects out of the static TLS
742 * block even if they didn't ask for it.
744 allocate_tls_offset(entry->obj);
747 if (relocate_objects(obj_main,
748 ld_bind_now != NULL && *ld_bind_now != '\0',
749 &obj_rtld, SYMLOOK_EARLY, NULL) == -1)
752 dbg("doing copy relocations");
753 if (do_copy_relocations(obj_main) == -1)
756 if (getenv(_LD("DUMP_REL_POST")) != NULL) {
757 dump_relocations(obj_main);
764 * Setup TLS for main thread. This must be done after the
765 * relocations are processed, since tls initialization section
766 * might be the subject for relocations.
768 dbg("initializing initial thread local storage");
769 allocate_initial_tls(globallist_curr(TAILQ_FIRST(&obj_list)));
771 dbg("initializing key program variables");
772 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
773 set_program_var("environ", env);
774 set_program_var("__elf_aux_vector", aux);
776 /* Make a list of init functions to call. */
777 objlist_init(&initlist);
778 initlist_add_objects(globallist_curr(TAILQ_FIRST(&obj_list)),
779 preload_tail, &initlist);
781 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
783 map_stacks_exec(NULL);
785 if (!obj_main->crt_no_init) {
787 * Make sure we don't call the main program's init and fini
788 * functions for binaries linked with old crt1 which calls
791 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
792 obj_main->preinit_array = obj_main->init_array =
793 obj_main->fini_array = (Elf_Addr)NULL;
797 * Execute MD initializers required before we call the objects'
802 wlock_acquire(rtld_bind_lock, &lockstate);
804 dbg("resolving ifuncs");
805 if (initlist_objects_ifunc(&initlist, ld_bind_now != NULL &&
806 *ld_bind_now != '\0', SYMLOOK_EARLY, &lockstate) == -1)
809 rtld_exit_ptr = rtld_exit;
810 if (obj_main->crt_no_init)
812 objlist_call_init(&initlist, &lockstate);
813 _r_debug_postinit(&obj_main->linkmap);
814 objlist_clear(&initlist);
815 dbg("loading filtees");
816 TAILQ_FOREACH(obj, &obj_list, next) {
819 if (ld_loadfltr || obj->z_loadfltr)
820 load_filtees(obj, 0, &lockstate);
823 dbg("enforcing main obj relro");
824 if (obj_enforce_relro(obj_main) == -1)
827 lock_release(rtld_bind_lock, &lockstate);
829 dbg("transferring control to program entry point = %p", obj_main->entry);
831 /* Return the exit procedure and the program entry point. */
832 *exit_proc = rtld_exit_ptr;
834 return (func_ptr_type) obj_main->entry;
838 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def)
843 ptr = (void *)make_function_pointer(def, obj);
844 target = call_ifunc_resolver(ptr);
845 return ((void *)target);
849 * NB: MIPS uses a private version of this function (_mips_rtld_bind).
850 * Changes to this function should be applied there as well.
853 _rtld_bind(Obj_Entry *obj, Elf_Size reloff)
857 const Obj_Entry *defobj;
860 RtldLockState lockstate;
862 rlock_acquire(rtld_bind_lock, &lockstate);
863 if (sigsetjmp(lockstate.env, 0) != 0)
864 lock_upgrade(rtld_bind_lock, &lockstate);
866 rel = (const Elf_Rel *)((const char *)obj->pltrel + reloff);
868 rel = (const Elf_Rel *)((const char *)obj->pltrela + reloff);
870 where = (Elf_Addr *)(obj->relocbase + rel->r_offset);
871 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, SYMLOOK_IN_PLT,
875 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
876 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
878 target = (Elf_Addr)(defobj->relocbase + def->st_value);
880 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
881 defobj->strtab + def->st_name, basename(obj->path),
882 (void *)target, basename(defobj->path));
885 * Write the new contents for the jmpslot. Note that depending on
886 * architecture, the value which we need to return back to the
887 * lazy binding trampoline may or may not be the target
888 * address. The value returned from reloc_jmpslot() is the value
889 * that the trampoline needs.
891 target = reloc_jmpslot(where, target, defobj, obj, rel);
892 lock_release(rtld_bind_lock, &lockstate);
897 * Error reporting function. Use it like printf. If formats the message
898 * into a buffer, and sets things up so that the next call to dlerror()
899 * will return the message.
902 _rtld_error(const char *fmt, ...)
904 static char buf[512];
908 rtld_vsnprintf(buf, sizeof buf, fmt, ap);
911 LD_UTRACE(UTRACE_RTLD_ERROR, NULL, NULL, 0, 0, error_message);
915 * Return a dynamically-allocated copy of the current error message, if any.
920 return error_message == NULL ? NULL : xstrdup(error_message);
924 * Restore the current error message from a copy which was previously saved
925 * by errmsg_save(). The copy is freed.
928 errmsg_restore(char *saved_msg)
930 if (saved_msg == NULL)
931 error_message = NULL;
933 _rtld_error("%s", saved_msg);
939 basename(const char *name)
941 const char *p = strrchr(name, '/');
942 return p != NULL ? p + 1 : name;
945 static struct utsname uts;
948 origin_subst_one(Obj_Entry *obj, char *real, const char *kw,
949 const char *subst, bool may_free)
951 char *p, *p1, *res, *resp;
952 int subst_len, kw_len, subst_count, old_len, new_len;
957 * First, count the number of the keyword occurrences, to
958 * preallocate the final string.
960 for (p = real, subst_count = 0;; p = p1 + kw_len, subst_count++) {
967 * If the keyword is not found, just return.
969 * Return non-substituted string if resolution failed. We
970 * cannot do anything more reasonable, the failure mode of the
971 * caller is unresolved library anyway.
973 if (subst_count == 0 || (obj != NULL && !obj_resolve_origin(obj)))
974 return (may_free ? real : xstrdup(real));
976 subst = obj->origin_path;
979 * There is indeed something to substitute. Calculate the
980 * length of the resulting string, and allocate it.
982 subst_len = strlen(subst);
983 old_len = strlen(real);
984 new_len = old_len + (subst_len - kw_len) * subst_count;
985 res = xmalloc(new_len + 1);
988 * Now, execute the substitution loop.
990 for (p = real, resp = res, *resp = '\0';;) {
993 /* Copy the prefix before keyword. */
994 memcpy(resp, p, p1 - p);
996 /* Keyword replacement. */
997 memcpy(resp, subst, subst_len);
1005 /* Copy to the end of string and finish. */
1013 origin_subst(Obj_Entry *obj, const char *real)
1015 char *res1, *res2, *res3, *res4;
1017 if (obj == NULL || !trust)
1018 return (xstrdup(real));
1019 if (uts.sysname[0] == '\0') {
1020 if (uname(&uts) != 0) {
1021 _rtld_error("utsname failed: %d", errno);
1025 /* __DECONST is safe here since without may_free real is unchanged */
1026 res1 = origin_subst_one(obj, __DECONST(char *, real), "$ORIGIN", NULL,
1028 res2 = origin_subst_one(NULL, res1, "$OSNAME", uts.sysname, true);
1029 res3 = origin_subst_one(NULL, res2, "$OSREL", uts.release, true);
1030 res4 = origin_subst_one(NULL, res3, "$PLATFORM", uts.machine, true);
1037 const char *msg = dlerror();
1040 msg = "Fatal error";
1041 rtld_fdputstr(STDERR_FILENO, _BASENAME_RTLD ": ");
1042 rtld_fdputstr(STDERR_FILENO, msg);
1043 rtld_fdputchar(STDERR_FILENO, '\n');
1048 * Process a shared object's DYNAMIC section, and save the important
1049 * information in its Obj_Entry structure.
1052 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
1053 const Elf_Dyn **dyn_soname, const Elf_Dyn **dyn_runpath)
1055 const Elf_Dyn *dynp;
1056 Needed_Entry **needed_tail = &obj->needed;
1057 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
1058 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
1059 const Elf_Hashelt *hashtab;
1060 const Elf32_Word *hashval;
1061 Elf32_Word bkt, nmaskwords;
1063 int plttype = DT_REL;
1067 *dyn_runpath = NULL;
1069 obj->bind_now = false;
1070 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
1071 switch (dynp->d_tag) {
1074 obj->rel = (const Elf_Rel *)(obj->relocbase + dynp->d_un.d_ptr);
1078 obj->relsize = dynp->d_un.d_val;
1082 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
1086 obj->pltrel = (const Elf_Rel *)
1087 (obj->relocbase + dynp->d_un.d_ptr);
1091 obj->pltrelsize = dynp->d_un.d_val;
1095 obj->rela = (const Elf_Rela *)(obj->relocbase + dynp->d_un.d_ptr);
1099 obj->relasize = dynp->d_un.d_val;
1103 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
1107 plttype = dynp->d_un.d_val;
1108 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
1112 obj->symtab = (const Elf_Sym *)
1113 (obj->relocbase + dynp->d_un.d_ptr);
1117 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
1121 obj->strtab = (const char *)(obj->relocbase + dynp->d_un.d_ptr);
1125 obj->strsize = dynp->d_un.d_val;
1129 obj->verneed = (const Elf_Verneed *)(obj->relocbase +
1134 obj->verneednum = dynp->d_un.d_val;
1138 obj->verdef = (const Elf_Verdef *)(obj->relocbase +
1143 obj->verdefnum = dynp->d_un.d_val;
1147 obj->versyms = (const Elf_Versym *)(obj->relocbase +
1153 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1155 obj->nbuckets = hashtab[0];
1156 obj->nchains = hashtab[1];
1157 obj->buckets = hashtab + 2;
1158 obj->chains = obj->buckets + obj->nbuckets;
1159 obj->valid_hash_sysv = obj->nbuckets > 0 && obj->nchains > 0 &&
1160 obj->buckets != NULL;
1166 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1168 obj->nbuckets_gnu = hashtab[0];
1169 obj->symndx_gnu = hashtab[1];
1170 nmaskwords = hashtab[2];
1171 bloom_size32 = (__ELF_WORD_SIZE / 32) * nmaskwords;
1172 obj->maskwords_bm_gnu = nmaskwords - 1;
1173 obj->shift2_gnu = hashtab[3];
1174 obj->bloom_gnu = (const Elf_Addr *)(hashtab + 4);
1175 obj->buckets_gnu = hashtab + 4 + bloom_size32;
1176 obj->chain_zero_gnu = obj->buckets_gnu + obj->nbuckets_gnu -
1178 /* Number of bitmask words is required to be power of 2 */
1179 obj->valid_hash_gnu = powerof2(nmaskwords) &&
1180 obj->nbuckets_gnu > 0 && obj->buckets_gnu != NULL;
1186 Needed_Entry *nep = NEW(Needed_Entry);
1187 nep->name = dynp->d_un.d_val;
1192 needed_tail = &nep->next;
1198 Needed_Entry *nep = NEW(Needed_Entry);
1199 nep->name = dynp->d_un.d_val;
1203 *needed_filtees_tail = nep;
1204 needed_filtees_tail = &nep->next;
1210 Needed_Entry *nep = NEW(Needed_Entry);
1211 nep->name = dynp->d_un.d_val;
1215 *needed_aux_filtees_tail = nep;
1216 needed_aux_filtees_tail = &nep->next;
1221 obj->pltgot = (Elf_Addr *)(obj->relocbase + dynp->d_un.d_ptr);
1225 obj->textrel = true;
1229 obj->symbolic = true;
1234 * We have to wait until later to process this, because we
1235 * might not have gotten the address of the string table yet.
1245 *dyn_runpath = dynp;
1249 obj->init = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1252 case DT_PREINIT_ARRAY:
1253 obj->preinit_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1256 case DT_PREINIT_ARRAYSZ:
1257 obj->preinit_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1261 obj->init_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1264 case DT_INIT_ARRAYSZ:
1265 obj->init_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1269 obj->fini = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1273 obj->fini_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1276 case DT_FINI_ARRAYSZ:
1277 obj->fini_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1281 * Don't process DT_DEBUG on MIPS as the dynamic section
1282 * is mapped read-only. DT_MIPS_RLD_MAP is used instead.
1288 dbg("Filling in DT_DEBUG entry");
1289 (__DECONST(Elf_Dyn *, dynp))->d_un.d_ptr = (Elf_Addr)&r_debug;
1294 if (dynp->d_un.d_val & DF_ORIGIN)
1295 obj->z_origin = true;
1296 if (dynp->d_un.d_val & DF_SYMBOLIC)
1297 obj->symbolic = true;
1298 if (dynp->d_un.d_val & DF_TEXTREL)
1299 obj->textrel = true;
1300 if (dynp->d_un.d_val & DF_BIND_NOW)
1301 obj->bind_now = true;
1302 if (dynp->d_un.d_val & DF_STATIC_TLS)
1303 obj->static_tls = true;
1306 case DT_MIPS_LOCAL_GOTNO:
1307 obj->local_gotno = dynp->d_un.d_val;
1310 case DT_MIPS_SYMTABNO:
1311 obj->symtabno = dynp->d_un.d_val;
1314 case DT_MIPS_GOTSYM:
1315 obj->gotsym = dynp->d_un.d_val;
1318 case DT_MIPS_RLD_MAP:
1319 *((Elf_Addr *)(dynp->d_un.d_ptr)) = (Elf_Addr) &r_debug;
1322 case DT_MIPS_RLD_MAP_REL:
1323 // The MIPS_RLD_MAP_REL tag stores the offset to the .rld_map
1324 // section relative to the address of the tag itself.
1325 *((Elf_Addr *)(__DECONST(char*, dynp) + dynp->d_un.d_val)) =
1326 (Elf_Addr) &r_debug;
1329 case DT_MIPS_PLTGOT:
1330 obj->mips_pltgot = (Elf_Addr *)(obj->relocbase +
1337 #ifdef __powerpc64__
1338 case DT_PPC64_GLINK:
1339 obj->glink = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1343 obj->gotptr = (Elf_Addr *)(obj->relocbase + dynp->d_un.d_ptr);
1349 if (dynp->d_un.d_val & DF_1_NOOPEN)
1350 obj->z_noopen = true;
1351 if (dynp->d_un.d_val & DF_1_ORIGIN)
1352 obj->z_origin = true;
1353 if (dynp->d_un.d_val & DF_1_GLOBAL)
1354 obj->z_global = true;
1355 if (dynp->d_un.d_val & DF_1_BIND_NOW)
1356 obj->bind_now = true;
1357 if (dynp->d_un.d_val & DF_1_NODELETE)
1358 obj->z_nodelete = true;
1359 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1360 obj->z_loadfltr = true;
1361 if (dynp->d_un.d_val & DF_1_INTERPOSE)
1362 obj->z_interpose = true;
1363 if (dynp->d_un.d_val & DF_1_NODEFLIB)
1364 obj->z_nodeflib = true;
1369 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1376 obj->traced = false;
1378 if (plttype == DT_RELA) {
1379 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1381 obj->pltrelasize = obj->pltrelsize;
1382 obj->pltrelsize = 0;
1385 /* Determine size of dynsym table (equal to nchains of sysv hash) */
1386 if (obj->valid_hash_sysv)
1387 obj->dynsymcount = obj->nchains;
1388 else if (obj->valid_hash_gnu) {
1389 obj->dynsymcount = 0;
1390 for (bkt = 0; bkt < obj->nbuckets_gnu; bkt++) {
1391 if (obj->buckets_gnu[bkt] == 0)
1393 hashval = &obj->chain_zero_gnu[obj->buckets_gnu[bkt]];
1396 while ((*hashval++ & 1u) == 0);
1398 obj->dynsymcount += obj->symndx_gnu;
1403 obj_resolve_origin(Obj_Entry *obj)
1406 if (obj->origin_path != NULL)
1408 obj->origin_path = xmalloc(PATH_MAX);
1409 return (rtld_dirname_abs(obj->path, obj->origin_path) != -1);
1413 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1414 const Elf_Dyn *dyn_soname, const Elf_Dyn *dyn_runpath)
1417 if (obj->z_origin && !obj_resolve_origin(obj))
1420 if (dyn_runpath != NULL) {
1421 obj->runpath = (const char *)obj->strtab + dyn_runpath->d_un.d_val;
1422 obj->runpath = origin_subst(obj, obj->runpath);
1423 } else if (dyn_rpath != NULL) {
1424 obj->rpath = (const char *)obj->strtab + dyn_rpath->d_un.d_val;
1425 obj->rpath = origin_subst(obj, obj->rpath);
1427 if (dyn_soname != NULL)
1428 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1433 digest_dynamic(Obj_Entry *obj, int early)
1435 const Elf_Dyn *dyn_rpath;
1436 const Elf_Dyn *dyn_soname;
1437 const Elf_Dyn *dyn_runpath;
1439 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname, &dyn_runpath);
1440 return (digest_dynamic2(obj, dyn_rpath, dyn_soname, dyn_runpath));
1444 * Process a shared object's program header. This is used only for the
1445 * main program, when the kernel has already loaded the main program
1446 * into memory before calling the dynamic linker. It creates and
1447 * returns an Obj_Entry structure.
1450 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1453 const Elf_Phdr *phlimit = phdr + phnum;
1455 Elf_Addr note_start, note_end;
1459 for (ph = phdr; ph < phlimit; ph++) {
1460 if (ph->p_type != PT_PHDR)
1464 obj->phsize = ph->p_memsz;
1465 obj->relocbase = __DECONST(char *, phdr) - ph->p_vaddr;
1469 obj->stack_flags = PF_X | PF_R | PF_W;
1471 for (ph = phdr; ph < phlimit; ph++) {
1472 switch (ph->p_type) {
1475 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1479 if (nsegs == 0) { /* First load segment */
1480 obj->vaddrbase = trunc_page(ph->p_vaddr);
1481 obj->mapbase = obj->vaddrbase + obj->relocbase;
1482 } else { /* Last load segment */
1483 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1490 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1495 obj->tlssize = ph->p_memsz;
1496 obj->tlsalign = ph->p_align;
1497 obj->tlsinitsize = ph->p_filesz;
1498 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1502 obj->stack_flags = ph->p_flags;
1506 obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1507 obj->relro_size = round_page(ph->p_memsz);
1511 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
1512 note_end = note_start + ph->p_filesz;
1513 digest_notes(obj, note_start, note_end);
1518 _rtld_error("%s: too few PT_LOAD segments", path);
1527 digest_notes(Obj_Entry *obj, Elf_Addr note_start, Elf_Addr note_end)
1529 const Elf_Note *note;
1530 const char *note_name;
1533 for (note = (const Elf_Note *)note_start; (Elf_Addr)note < note_end;
1534 note = (const Elf_Note *)((const char *)(note + 1) +
1535 roundup2(note->n_namesz, sizeof(Elf32_Addr)) +
1536 roundup2(note->n_descsz, sizeof(Elf32_Addr)))) {
1537 if (note->n_namesz != sizeof(NOTE_FREEBSD_VENDOR) ||
1538 note->n_descsz != sizeof(int32_t))
1540 if (note->n_type != NT_FREEBSD_ABI_TAG &&
1541 note->n_type != NT_FREEBSD_FEATURE_CTL &&
1542 note->n_type != NT_FREEBSD_NOINIT_TAG)
1544 note_name = (const char *)(note + 1);
1545 if (strncmp(NOTE_FREEBSD_VENDOR, note_name,
1546 sizeof(NOTE_FREEBSD_VENDOR)) != 0)
1548 switch (note->n_type) {
1549 case NT_FREEBSD_ABI_TAG:
1550 /* FreeBSD osrel note */
1551 p = (uintptr_t)(note + 1);
1552 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1553 obj->osrel = *(const int32_t *)(p);
1554 dbg("note osrel %d", obj->osrel);
1556 case NT_FREEBSD_FEATURE_CTL:
1557 /* FreeBSD ABI feature control note */
1558 p = (uintptr_t)(note + 1);
1559 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1560 obj->fctl0 = *(const uint32_t *)(p);
1561 dbg("note fctl0 %#x", obj->fctl0);
1563 case NT_FREEBSD_NOINIT_TAG:
1564 /* FreeBSD 'crt does not call init' note */
1565 obj->crt_no_init = true;
1566 dbg("note crt_no_init");
1573 dlcheck(void *handle)
1577 TAILQ_FOREACH(obj, &obj_list, next) {
1578 if (obj == (Obj_Entry *) handle)
1582 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1583 _rtld_error("Invalid shared object handle %p", handle);
1590 * If the given object is already in the donelist, return true. Otherwise
1591 * add the object to the list and return false.
1594 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1598 for (i = 0; i < dlp->num_used; i++)
1599 if (dlp->objs[i] == obj)
1602 * Our donelist allocation should always be sufficient. But if
1603 * our threads locking isn't working properly, more shared objects
1604 * could have been loaded since we allocated the list. That should
1605 * never happen, but we'll handle it properly just in case it does.
1607 if (dlp->num_used < dlp->num_alloc)
1608 dlp->objs[dlp->num_used++] = obj;
1613 * Hash function for symbol table lookup. Don't even think about changing
1614 * this. It is specified by the System V ABI.
1617 elf_hash(const char *name)
1619 const unsigned char *p = (const unsigned char *) name;
1620 unsigned long h = 0;
1623 while (*p != '\0') {
1624 h = (h << 4) + *p++;
1625 if ((g = h & 0xf0000000) != 0)
1633 * The GNU hash function is the Daniel J. Bernstein hash clipped to 32 bits
1634 * unsigned in case it's implemented with a wider type.
1637 gnu_hash(const char *s)
1643 for (c = *s; c != '\0'; c = *++s)
1645 return (h & 0xffffffff);
1650 * Find the library with the given name, and return its full pathname.
1651 * The returned string is dynamically allocated. Generates an error
1652 * message and returns NULL if the library cannot be found.
1654 * If the second argument is non-NULL, then it refers to an already-
1655 * loaded shared object, whose library search path will be searched.
1657 * If a library is successfully located via LD_LIBRARY_PATH_FDS, its
1658 * descriptor (which is close-on-exec) will be passed out via the third
1661 * The search order is:
1662 * DT_RPATH in the referencing file _unless_ DT_RUNPATH is present (1)
1663 * DT_RPATH of the main object if DSO without defined DT_RUNPATH (1)
1665 * DT_RUNPATH in the referencing file
1666 * ldconfig hints (if -z nodefaultlib, filter out default library directories
1668 * /lib:/usr/lib _unless_ the referencing file is linked with -z nodefaultlib
1670 * (1) Handled in digest_dynamic2 - rpath left NULL if runpath defined.
1673 find_library(const char *xname, const Obj_Entry *refobj, int *fdp)
1675 char *pathname, *refobj_path;
1677 bool nodeflib, objgiven;
1679 objgiven = refobj != NULL;
1681 if (libmap_disable || !objgiven ||
1682 (name = lm_find(refobj->path, xname)) == NULL)
1685 if (strchr(name, '/') != NULL) { /* Hard coded pathname */
1686 if (name[0] != '/' && !trust) {
1687 _rtld_error("Absolute pathname required "
1688 "for shared object \"%s\"", name);
1691 return (origin_subst(__DECONST(Obj_Entry *, refobj),
1692 __DECONST(char *, name)));
1695 dbg(" Searching for \"%s\"", name);
1696 refobj_path = objgiven ? refobj->path : NULL;
1699 * If refobj->rpath != NULL, then refobj->runpath is NULL. Fall
1700 * back to pre-conforming behaviour if user requested so with
1701 * LD_LIBRARY_PATH_RPATH environment variable and ignore -z
1704 if (objgiven && refobj->rpath != NULL && ld_library_path_rpath) {
1705 pathname = search_library_path(name, ld_library_path,
1707 if (pathname != NULL)
1709 if (refobj != NULL) {
1710 pathname = search_library_path(name, refobj->rpath,
1712 if (pathname != NULL)
1715 pathname = search_library_pathfds(name, ld_library_dirs, fdp);
1716 if (pathname != NULL)
1718 pathname = search_library_path(name, gethints(false),
1720 if (pathname != NULL)
1722 pathname = search_library_path(name, ld_standard_library_path,
1724 if (pathname != NULL)
1727 nodeflib = objgiven ? refobj->z_nodeflib : false;
1729 pathname = search_library_path(name, refobj->rpath,
1731 if (pathname != NULL)
1734 if (objgiven && refobj->runpath == NULL && refobj != obj_main) {
1735 pathname = search_library_path(name, obj_main->rpath,
1737 if (pathname != NULL)
1740 pathname = search_library_path(name, ld_library_path,
1742 if (pathname != NULL)
1745 pathname = search_library_path(name, refobj->runpath,
1747 if (pathname != NULL)
1750 pathname = search_library_pathfds(name, ld_library_dirs, fdp);
1751 if (pathname != NULL)
1753 pathname = search_library_path(name, gethints(nodeflib),
1755 if (pathname != NULL)
1757 if (objgiven && !nodeflib) {
1758 pathname = search_library_path(name,
1759 ld_standard_library_path, refobj_path, fdp);
1760 if (pathname != NULL)
1765 if (objgiven && refobj->path != NULL) {
1766 _rtld_error("Shared object \"%s\" not found, "
1767 "required by \"%s\"", name, basename(refobj->path));
1769 _rtld_error("Shared object \"%s\" not found", name);
1775 * Given a symbol number in a referencing object, find the corresponding
1776 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1777 * no definition was found. Returns a pointer to the Obj_Entry of the
1778 * defining object via the reference parameter DEFOBJ_OUT.
1781 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1782 const Obj_Entry **defobj_out, int flags, SymCache *cache,
1783 RtldLockState *lockstate)
1787 const Obj_Entry *defobj;
1788 const Ver_Entry *ve;
1794 * If we have already found this symbol, get the information from
1797 if (symnum >= refobj->dynsymcount)
1798 return NULL; /* Bad object */
1799 if (cache != NULL && cache[symnum].sym != NULL) {
1800 *defobj_out = cache[symnum].obj;
1801 return cache[symnum].sym;
1804 ref = refobj->symtab + symnum;
1805 name = refobj->strtab + ref->st_name;
1811 * We don't have to do a full scale lookup if the symbol is local.
1812 * We know it will bind to the instance in this load module; to
1813 * which we already have a pointer (ie ref). By not doing a lookup,
1814 * we not only improve performance, but it also avoids unresolvable
1815 * symbols when local symbols are not in the hash table. This has
1816 * been seen with the ia64 toolchain.
1818 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1819 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1820 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1823 symlook_init(&req, name);
1825 ve = req.ventry = fetch_ventry(refobj, symnum);
1826 req.lockstate = lockstate;
1827 res = symlook_default(&req, refobj);
1830 defobj = req.defobj_out;
1838 * If we found no definition and the reference is weak, treat the
1839 * symbol as having the value zero.
1841 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1847 *defobj_out = defobj;
1848 /* Record the information in the cache to avoid subsequent lookups. */
1849 if (cache != NULL) {
1850 cache[symnum].sym = def;
1851 cache[symnum].obj = defobj;
1854 if (refobj != &obj_rtld)
1855 _rtld_error("%s: Undefined symbol \"%s%s%s\"", refobj->path, name,
1856 ve != NULL ? "@" : "", ve != NULL ? ve->name : "");
1862 * Return the search path from the ldconfig hints file, reading it if
1863 * necessary. If nostdlib is true, then the default search paths are
1864 * not added to result.
1866 * Returns NULL if there are problems with the hints file,
1867 * or if the search path there is empty.
1870 gethints(bool nostdlib)
1872 static char *filtered_path;
1873 static const char *hints;
1874 static struct elfhints_hdr hdr;
1875 struct fill_search_info_args sargs, hargs;
1876 struct dl_serinfo smeta, hmeta, *SLPinfo, *hintinfo;
1877 struct dl_serpath *SLPpath, *hintpath;
1879 struct stat hint_stat;
1880 unsigned int SLPndx, hintndx, fndx, fcount;
1886 /* First call, read the hints file */
1887 if (hints == NULL) {
1888 /* Keep from trying again in case the hints file is bad. */
1891 if ((fd = open(ld_elf_hints_path, O_RDONLY | O_CLOEXEC)) == -1)
1895 * Check of hdr.dirlistlen value against type limit
1896 * intends to pacify static analyzers. Further
1897 * paranoia leads to checks that dirlist is fully
1898 * contained in the file range.
1900 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1901 hdr.magic != ELFHINTS_MAGIC ||
1902 hdr.version != 1 || hdr.dirlistlen > UINT_MAX / 2 ||
1903 fstat(fd, &hint_stat) == -1) {
1910 if (dl + hdr.dirlist < dl)
1913 if (dl + hdr.dirlistlen < dl)
1915 dl += hdr.dirlistlen;
1916 if (dl > hint_stat.st_size)
1918 p = xmalloc(hdr.dirlistlen + 1);
1919 if (pread(fd, p, hdr.dirlistlen + 1,
1920 hdr.strtab + hdr.dirlist) != (ssize_t)hdr.dirlistlen + 1 ||
1921 p[hdr.dirlistlen] != '\0') {
1930 * If caller agreed to receive list which includes the default
1931 * paths, we are done. Otherwise, if we still did not
1932 * calculated filtered result, do it now.
1935 return (hints[0] != '\0' ? hints : NULL);
1936 if (filtered_path != NULL)
1940 * Obtain the list of all configured search paths, and the
1941 * list of the default paths.
1943 * First estimate the size of the results.
1945 smeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1947 hmeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1950 sargs.request = RTLD_DI_SERINFOSIZE;
1951 sargs.serinfo = &smeta;
1952 hargs.request = RTLD_DI_SERINFOSIZE;
1953 hargs.serinfo = &hmeta;
1955 path_enumerate(ld_standard_library_path, fill_search_info, NULL,
1957 path_enumerate(hints, fill_search_info, NULL, &hargs);
1959 SLPinfo = xmalloc(smeta.dls_size);
1960 hintinfo = xmalloc(hmeta.dls_size);
1963 * Next fetch both sets of paths.
1965 sargs.request = RTLD_DI_SERINFO;
1966 sargs.serinfo = SLPinfo;
1967 sargs.serpath = &SLPinfo->dls_serpath[0];
1968 sargs.strspace = (char *)&SLPinfo->dls_serpath[smeta.dls_cnt];
1970 hargs.request = RTLD_DI_SERINFO;
1971 hargs.serinfo = hintinfo;
1972 hargs.serpath = &hintinfo->dls_serpath[0];
1973 hargs.strspace = (char *)&hintinfo->dls_serpath[hmeta.dls_cnt];
1975 path_enumerate(ld_standard_library_path, fill_search_info, NULL,
1977 path_enumerate(hints, fill_search_info, NULL, &hargs);
1980 * Now calculate the difference between two sets, by excluding
1981 * standard paths from the full set.
1985 filtered_path = xmalloc(hdr.dirlistlen + 1);
1986 hintpath = &hintinfo->dls_serpath[0];
1987 for (hintndx = 0; hintndx < hmeta.dls_cnt; hintndx++, hintpath++) {
1989 SLPpath = &SLPinfo->dls_serpath[0];
1991 * Check each standard path against current.
1993 for (SLPndx = 0; SLPndx < smeta.dls_cnt; SLPndx++, SLPpath++) {
1994 /* matched, skip the path */
1995 if (!strcmp(hintpath->dls_name, SLPpath->dls_name)) {
2003 * Not matched against any standard path, add the path
2004 * to result. Separate consequtive paths with ':'.
2007 filtered_path[fndx] = ':';
2011 flen = strlen(hintpath->dls_name);
2012 strncpy((filtered_path + fndx), hintpath->dls_name, flen);
2015 filtered_path[fndx] = '\0';
2021 return (filtered_path[0] != '\0' ? filtered_path : NULL);
2025 init_dag(Obj_Entry *root)
2027 const Needed_Entry *needed;
2028 const Objlist_Entry *elm;
2031 if (root->dag_inited)
2033 donelist_init(&donelist);
2035 /* Root object belongs to own DAG. */
2036 objlist_push_tail(&root->dldags, root);
2037 objlist_push_tail(&root->dagmembers, root);
2038 donelist_check(&donelist, root);
2041 * Add dependencies of root object to DAG in breadth order
2042 * by exploiting the fact that each new object get added
2043 * to the tail of the dagmembers list.
2045 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2046 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
2047 if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
2049 objlist_push_tail(&needed->obj->dldags, root);
2050 objlist_push_tail(&root->dagmembers, needed->obj);
2053 root->dag_inited = true;
2057 init_marker(Obj_Entry *marker)
2060 bzero(marker, sizeof(*marker));
2061 marker->marker = true;
2065 globallist_curr(const Obj_Entry *obj)
2072 return (__DECONST(Obj_Entry *, obj));
2073 obj = TAILQ_PREV(obj, obj_entry_q, next);
2078 globallist_next(const Obj_Entry *obj)
2082 obj = TAILQ_NEXT(obj, next);
2086 return (__DECONST(Obj_Entry *, obj));
2090 /* Prevent the object from being unmapped while the bind lock is dropped. */
2092 hold_object(Obj_Entry *obj)
2099 unhold_object(Obj_Entry *obj)
2102 assert(obj->holdcount > 0);
2103 if (--obj->holdcount == 0 && obj->unholdfree)
2104 release_object(obj);
2108 process_z(Obj_Entry *root)
2110 const Objlist_Entry *elm;
2114 * Walk over object DAG and process every dependent object
2115 * that is marked as DF_1_NODELETE or DF_1_GLOBAL. They need
2116 * to grow their own DAG.
2118 * For DF_1_GLOBAL, DAG is required for symbol lookups in
2119 * symlook_global() to work.
2121 * For DF_1_NODELETE, the DAG should have its reference upped.
2123 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2127 if (obj->z_nodelete && !obj->ref_nodel) {
2128 dbg("obj %s -z nodelete", obj->path);
2131 obj->ref_nodel = true;
2133 if (obj->z_global && objlist_find(&list_global, obj) == NULL) {
2134 dbg("obj %s -z global", obj->path);
2135 objlist_push_tail(&list_global, obj);
2141 * Initialize the dynamic linker. The argument is the address at which
2142 * the dynamic linker has been mapped into memory. The primary task of
2143 * this function is to relocate the dynamic linker.
2146 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
2148 Obj_Entry objtmp; /* Temporary rtld object */
2149 const Elf_Ehdr *ehdr;
2150 const Elf_Dyn *dyn_rpath;
2151 const Elf_Dyn *dyn_soname;
2152 const Elf_Dyn *dyn_runpath;
2154 #ifdef RTLD_INIT_PAGESIZES_EARLY
2155 /* The page size is required by the dynamic memory allocator. */
2156 init_pagesizes(aux_info);
2160 * Conjure up an Obj_Entry structure for the dynamic linker.
2162 * The "path" member can't be initialized yet because string constants
2163 * cannot yet be accessed. Below we will set it correctly.
2165 memset(&objtmp, 0, sizeof(objtmp));
2168 objtmp.mapbase = mapbase;
2170 objtmp.relocbase = mapbase;
2173 objtmp.dynamic = rtld_dynamic(&objtmp);
2174 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname, &dyn_runpath);
2175 assert(objtmp.needed == NULL);
2176 #if !defined(__mips__)
2177 /* MIPS has a bogus DT_TEXTREL. */
2178 assert(!objtmp.textrel);
2181 * Temporarily put the dynamic linker entry into the object list, so
2182 * that symbols can be found.
2184 relocate_objects(&objtmp, true, &objtmp, 0, NULL);
2186 ehdr = (Elf_Ehdr *)mapbase;
2187 objtmp.phdr = (Elf_Phdr *)((char *)mapbase + ehdr->e_phoff);
2188 objtmp.phsize = ehdr->e_phnum * sizeof(objtmp.phdr[0]);
2190 /* Initialize the object list. */
2191 TAILQ_INIT(&obj_list);
2193 /* Now that non-local variables can be accesses, copy out obj_rtld. */
2194 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
2196 #ifndef RTLD_INIT_PAGESIZES_EARLY
2197 /* The page size is required by the dynamic memory allocator. */
2198 init_pagesizes(aux_info);
2201 if (aux_info[AT_OSRELDATE] != NULL)
2202 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
2204 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname, dyn_runpath);
2206 /* Replace the path with a dynamically allocated copy. */
2207 obj_rtld.path = xstrdup(ld_path_rtld);
2209 r_debug.r_brk = r_debug_state;
2210 r_debug.r_state = RT_CONSISTENT;
2214 * Retrieve the array of supported page sizes. The kernel provides the page
2215 * sizes in increasing order.
2218 init_pagesizes(Elf_Auxinfo **aux_info)
2220 static size_t psa[MAXPAGESIZES];
2224 if (aux_info[AT_PAGESIZES] != NULL && aux_info[AT_PAGESIZESLEN] !=
2226 size = aux_info[AT_PAGESIZESLEN]->a_un.a_val;
2227 pagesizes = aux_info[AT_PAGESIZES]->a_un.a_ptr;
2230 if (sysctlnametomib("hw.pagesizes", mib, &len) == 0)
2233 /* As a fallback, retrieve the base page size. */
2234 size = sizeof(psa[0]);
2235 if (aux_info[AT_PAGESZ] != NULL) {
2236 psa[0] = aux_info[AT_PAGESZ]->a_un.a_val;
2240 mib[1] = HW_PAGESIZE;
2244 if (sysctl(mib, len, psa, &size, NULL, 0) == -1) {
2245 _rtld_error("sysctl for hw.pagesize(s) failed");
2251 npagesizes = size / sizeof(pagesizes[0]);
2252 /* Discard any invalid entries at the end of the array. */
2253 while (npagesizes > 0 && pagesizes[npagesizes - 1] == 0)
2258 * Add the init functions from a needed object list (and its recursive
2259 * needed objects) to "list". This is not used directly; it is a helper
2260 * function for initlist_add_objects(). The write lock must be held
2261 * when this function is called.
2264 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
2266 /* Recursively process the successor needed objects. */
2267 if (needed->next != NULL)
2268 initlist_add_neededs(needed->next, list);
2270 /* Process the current needed object. */
2271 if (needed->obj != NULL)
2272 initlist_add_objects(needed->obj, needed->obj, list);
2276 * Scan all of the DAGs rooted in the range of objects from "obj" to
2277 * "tail" and add their init functions to "list". This recurses over
2278 * the DAGs and ensure the proper init ordering such that each object's
2279 * needed libraries are initialized before the object itself. At the
2280 * same time, this function adds the objects to the global finalization
2281 * list "list_fini" in the opposite order. The write lock must be
2282 * held when this function is called.
2285 initlist_add_objects(Obj_Entry *obj, Obj_Entry *tail, Objlist *list)
2289 if (obj->init_scanned || obj->init_done)
2291 obj->init_scanned = true;
2293 /* Recursively process the successor objects. */
2294 nobj = globallist_next(obj);
2295 if (nobj != NULL && obj != tail)
2296 initlist_add_objects(nobj, tail, list);
2298 /* Recursively process the needed objects. */
2299 if (obj->needed != NULL)
2300 initlist_add_neededs(obj->needed, list);
2301 if (obj->needed_filtees != NULL)
2302 initlist_add_neededs(obj->needed_filtees, list);
2303 if (obj->needed_aux_filtees != NULL)
2304 initlist_add_neededs(obj->needed_aux_filtees, list);
2306 /* Add the object to the init list. */
2307 objlist_push_tail(list, obj);
2309 /* Add the object to the global fini list in the reverse order. */
2310 if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL)
2311 && !obj->on_fini_list) {
2312 objlist_push_head(&list_fini, obj);
2313 obj->on_fini_list = true;
2318 #define FPTR_TARGET(f) ((Elf_Addr) (f))
2322 free_needed_filtees(Needed_Entry *n, RtldLockState *lockstate)
2324 Needed_Entry *needed, *needed1;
2326 for (needed = n; needed != NULL; needed = needed->next) {
2327 if (needed->obj != NULL) {
2328 dlclose_locked(needed->obj, lockstate);
2332 for (needed = n; needed != NULL; needed = needed1) {
2333 needed1 = needed->next;
2339 unload_filtees(Obj_Entry *obj, RtldLockState *lockstate)
2342 free_needed_filtees(obj->needed_filtees, lockstate);
2343 obj->needed_filtees = NULL;
2344 free_needed_filtees(obj->needed_aux_filtees, lockstate);
2345 obj->needed_aux_filtees = NULL;
2346 obj->filtees_loaded = false;
2350 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags,
2351 RtldLockState *lockstate)
2354 for (; needed != NULL; needed = needed->next) {
2355 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
2356 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
2357 RTLD_LOCAL, lockstate);
2362 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
2365 lock_restart_for_upgrade(lockstate);
2366 if (!obj->filtees_loaded) {
2367 load_filtee1(obj, obj->needed_filtees, flags, lockstate);
2368 load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate);
2369 obj->filtees_loaded = true;
2374 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
2378 for (; needed != NULL; needed = needed->next) {
2379 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
2380 flags & ~RTLD_LO_NOLOAD);
2381 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
2388 * Given a shared object, traverse its list of needed objects, and load
2389 * each of them. Returns 0 on success. Generates an error message and
2390 * returns -1 on failure.
2393 load_needed_objects(Obj_Entry *first, int flags)
2397 for (obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
2400 if (process_needed(obj, obj->needed, flags) == -1)
2407 load_preload_objects(void)
2409 char *p = ld_preload;
2411 static const char delim[] = " \t:;";
2416 p += strspn(p, delim);
2417 while (*p != '\0') {
2418 size_t len = strcspn(p, delim);
2423 obj = load_object(p, -1, NULL, 0);
2425 return -1; /* XXX - cleanup */
2426 obj->z_interpose = true;
2429 p += strspn(p, delim);
2431 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
2436 printable_path(const char *path)
2439 return (path == NULL ? "<unknown>" : path);
2443 * Load a shared object into memory, if it is not already loaded. The
2444 * object may be specified by name or by user-supplied file descriptor
2445 * fd_u. In the later case, the fd_u descriptor is not closed, but its
2448 * Returns a pointer to the Obj_Entry for the object. Returns NULL
2452 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
2461 TAILQ_FOREACH(obj, &obj_list, next) {
2462 if (obj->marker || obj->doomed)
2464 if (object_match_name(obj, name))
2468 path = find_library(name, refobj, &fd);
2476 * search_library_pathfds() opens a fresh file descriptor for the
2477 * library, so there is no need to dup().
2479 } else if (fd_u == -1) {
2481 * If we didn't find a match by pathname, or the name is not
2482 * supplied, open the file and check again by device and inode.
2483 * This avoids false mismatches caused by multiple links or ".."
2486 * To avoid a race, we open the file and use fstat() rather than
2489 if ((fd = open(path, O_RDONLY | O_CLOEXEC | O_VERIFY)) == -1) {
2490 _rtld_error("Cannot open \"%s\"", path);
2495 fd = fcntl(fd_u, F_DUPFD_CLOEXEC, 0);
2497 _rtld_error("Cannot dup fd");
2502 if (fstat(fd, &sb) == -1) {
2503 _rtld_error("Cannot fstat \"%s\"", printable_path(path));
2508 TAILQ_FOREACH(obj, &obj_list, next) {
2509 if (obj->marker || obj->doomed)
2511 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
2514 if (obj != NULL && name != NULL) {
2515 object_add_name(obj, name);
2520 if (flags & RTLD_LO_NOLOAD) {
2526 /* First use of this object, so we must map it in */
2527 obj = do_load_object(fd, name, path, &sb, flags);
2536 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
2543 * but first, make sure that environment variables haven't been
2544 * used to circumvent the noexec flag on a filesystem.
2546 if (dangerous_ld_env) {
2547 if (fstatfs(fd, &fs) != 0) {
2548 _rtld_error("Cannot fstatfs \"%s\"", printable_path(path));
2551 if (fs.f_flags & MNT_NOEXEC) {
2552 _rtld_error("Cannot execute objects on %s", fs.f_mntonname);
2556 dbg("loading \"%s\"", printable_path(path));
2557 obj = map_object(fd, printable_path(path), sbp);
2562 * If DT_SONAME is present in the object, digest_dynamic2 already
2563 * added it to the object names.
2566 object_add_name(obj, name);
2568 if (!digest_dynamic(obj, 0))
2570 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path,
2571 obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount);
2572 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
2574 dbg("refusing to load non-loadable \"%s\"", obj->path);
2575 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
2579 obj->dlopened = (flags & RTLD_LO_DLOPEN) != 0;
2580 TAILQ_INSERT_TAIL(&obj_list, obj, next);
2583 linkmap_add(obj); /* for GDB & dlinfo() */
2584 max_stack_flags |= obj->stack_flags;
2586 dbg(" %p .. %p: %s", obj->mapbase,
2587 obj->mapbase + obj->mapsize - 1, obj->path);
2589 dbg(" WARNING: %s has impure text", obj->path);
2590 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
2596 munmap(obj->mapbase, obj->mapsize);
2602 obj_from_addr(const void *addr)
2606 TAILQ_FOREACH(obj, &obj_list, next) {
2609 if (addr < (void *) obj->mapbase)
2611 if (addr < (void *)(obj->mapbase + obj->mapsize))
2620 Elf_Addr *preinit_addr;
2623 preinit_addr = (Elf_Addr *)obj_main->preinit_array;
2624 if (preinit_addr == NULL)
2627 for (index = 0; index < obj_main->preinit_array_num; index++) {
2628 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) {
2629 dbg("calling preinit function for %s at %p", obj_main->path,
2630 (void *)preinit_addr[index]);
2631 LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index],
2632 0, 0, obj_main->path);
2633 call_init_pointer(obj_main, preinit_addr[index]);
2639 * Call the finalization functions for each of the objects in "list"
2640 * belonging to the DAG of "root" and referenced once. If NULL "root"
2641 * is specified, every finalization function will be called regardless
2642 * of the reference count and the list elements won't be freed. All of
2643 * the objects are expected to have non-NULL fini functions.
2646 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
2650 Elf_Addr *fini_addr;
2653 assert(root == NULL || root->refcount == 1);
2656 root->doomed = true;
2659 * Preserve the current error message since a fini function might
2660 * call into the dynamic linker and overwrite it.
2662 saved_msg = errmsg_save();
2664 STAILQ_FOREACH(elm, list, link) {
2665 if (root != NULL && (elm->obj->refcount != 1 ||
2666 objlist_find(&root->dagmembers, elm->obj) == NULL))
2668 /* Remove object from fini list to prevent recursive invocation. */
2669 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2670 /* Ensure that new references cannot be acquired. */
2671 elm->obj->doomed = true;
2673 hold_object(elm->obj);
2674 lock_release(rtld_bind_lock, lockstate);
2676 * It is legal to have both DT_FINI and DT_FINI_ARRAY defined.
2677 * When this happens, DT_FINI_ARRAY is processed first.
2679 fini_addr = (Elf_Addr *)elm->obj->fini_array;
2680 if (fini_addr != NULL && elm->obj->fini_array_num > 0) {
2681 for (index = elm->obj->fini_array_num - 1; index >= 0;
2683 if (fini_addr[index] != 0 && fini_addr[index] != 1) {
2684 dbg("calling fini function for %s at %p",
2685 elm->obj->path, (void *)fini_addr[index]);
2686 LD_UTRACE(UTRACE_FINI_CALL, elm->obj,
2687 (void *)fini_addr[index], 0, 0, elm->obj->path);
2688 call_initfini_pointer(elm->obj, fini_addr[index]);
2692 if (elm->obj->fini != (Elf_Addr)NULL) {
2693 dbg("calling fini function for %s at %p", elm->obj->path,
2694 (void *)elm->obj->fini);
2695 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini,
2696 0, 0, elm->obj->path);
2697 call_initfini_pointer(elm->obj, elm->obj->fini);
2699 wlock_acquire(rtld_bind_lock, lockstate);
2700 unhold_object(elm->obj);
2701 /* No need to free anything if process is going down. */
2705 * We must restart the list traversal after every fini call
2706 * because a dlclose() call from the fini function or from
2707 * another thread might have modified the reference counts.
2711 } while (elm != NULL);
2712 errmsg_restore(saved_msg);
2716 * Call the initialization functions for each of the objects in
2717 * "list". All of the objects are expected to have non-NULL init
2721 objlist_call_init(Objlist *list, RtldLockState *lockstate)
2726 Elf_Addr *init_addr;
2727 void (*reg)(void (*)(void));
2731 * Clean init_scanned flag so that objects can be rechecked and
2732 * possibly initialized earlier if any of vectors called below
2733 * cause the change by using dlopen.
2735 TAILQ_FOREACH(obj, &obj_list, next) {
2738 obj->init_scanned = false;
2742 * Preserve the current error message since an init function might
2743 * call into the dynamic linker and overwrite it.
2745 saved_msg = errmsg_save();
2746 STAILQ_FOREACH(elm, list, link) {
2747 if (elm->obj->init_done) /* Initialized early. */
2750 * Race: other thread might try to use this object before current
2751 * one completes the initialization. Not much can be done here
2752 * without better locking.
2754 elm->obj->init_done = true;
2755 hold_object(elm->obj);
2757 if (elm->obj == obj_main && obj_main->crt_no_init) {
2758 reg = (void (*)(void (*)(void)))get_program_var_addr(
2759 "__libc_atexit", lockstate);
2761 lock_release(rtld_bind_lock, lockstate);
2764 rtld_exit_ptr = rtld_nop_exit;
2768 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined.
2769 * When this happens, DT_INIT is processed first.
2771 if (elm->obj->init != (Elf_Addr)NULL) {
2772 dbg("calling init function for %s at %p", elm->obj->path,
2773 (void *)elm->obj->init);
2774 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init,
2775 0, 0, elm->obj->path);
2776 call_initfini_pointer(elm->obj, elm->obj->init);
2778 init_addr = (Elf_Addr *)elm->obj->init_array;
2779 if (init_addr != NULL) {
2780 for (index = 0; index < elm->obj->init_array_num; index++) {
2781 if (init_addr[index] != 0 && init_addr[index] != 1) {
2782 dbg("calling init function for %s at %p", elm->obj->path,
2783 (void *)init_addr[index]);
2784 LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
2785 (void *)init_addr[index], 0, 0, elm->obj->path);
2786 call_init_pointer(elm->obj, init_addr[index]);
2790 wlock_acquire(rtld_bind_lock, lockstate);
2791 unhold_object(elm->obj);
2793 errmsg_restore(saved_msg);
2797 objlist_clear(Objlist *list)
2801 while (!STAILQ_EMPTY(list)) {
2802 elm = STAILQ_FIRST(list);
2803 STAILQ_REMOVE_HEAD(list, link);
2808 static Objlist_Entry *
2809 objlist_find(Objlist *list, const Obj_Entry *obj)
2813 STAILQ_FOREACH(elm, list, link)
2814 if (elm->obj == obj)
2820 objlist_init(Objlist *list)
2826 objlist_push_head(Objlist *list, Obj_Entry *obj)
2830 elm = NEW(Objlist_Entry);
2832 STAILQ_INSERT_HEAD(list, elm, link);
2836 objlist_push_tail(Objlist *list, Obj_Entry *obj)
2840 elm = NEW(Objlist_Entry);
2842 STAILQ_INSERT_TAIL(list, elm, link);
2846 objlist_put_after(Objlist *list, Obj_Entry *listobj, Obj_Entry *obj)
2848 Objlist_Entry *elm, *listelm;
2850 STAILQ_FOREACH(listelm, list, link) {
2851 if (listelm->obj == listobj)
2854 elm = NEW(Objlist_Entry);
2856 if (listelm != NULL)
2857 STAILQ_INSERT_AFTER(list, listelm, elm, link);
2859 STAILQ_INSERT_TAIL(list, elm, link);
2863 objlist_remove(Objlist *list, Obj_Entry *obj)
2867 if ((elm = objlist_find(list, obj)) != NULL) {
2868 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2874 * Relocate dag rooted in the specified object.
2875 * Returns 0 on success, or -1 on failure.
2879 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj,
2880 int flags, RtldLockState *lockstate)
2886 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2887 error = relocate_object(elm->obj, bind_now, rtldobj, flags,
2896 * Prepare for, or clean after, relocating an object marked with
2897 * DT_TEXTREL or DF_TEXTREL. Before relocating, all read-only
2898 * segments are remapped read-write. After relocations are done, the
2899 * segment's permissions are returned back to the modes specified in
2900 * the phdrs. If any relocation happened, or always for wired
2901 * program, COW is triggered.
2904 reloc_textrel_prot(Obj_Entry *obj, bool before)
2911 for (l = obj->phsize / sizeof(*ph), ph = obj->phdr; l > 0;
2913 if (ph->p_type != PT_LOAD || (ph->p_flags & PF_W) != 0)
2915 base = obj->relocbase + trunc_page(ph->p_vaddr);
2916 sz = round_page(ph->p_vaddr + ph->p_filesz) -
2917 trunc_page(ph->p_vaddr);
2918 prot = convert_prot(ph->p_flags) | (before ? PROT_WRITE : 0);
2919 if (mprotect(base, sz, prot) == -1) {
2920 _rtld_error("%s: Cannot write-%sable text segment: %s",
2921 obj->path, before ? "en" : "dis",
2922 rtld_strerror(errno));
2930 * Relocate single object.
2931 * Returns 0 on success, or -1 on failure.
2934 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
2935 int flags, RtldLockState *lockstate)
2940 obj->relocated = true;
2942 dbg("relocating \"%s\"", obj->path);
2944 if (obj->symtab == NULL || obj->strtab == NULL ||
2945 !(obj->valid_hash_sysv || obj->valid_hash_gnu)) {
2946 _rtld_error("%s: Shared object has no run-time symbol table",
2951 /* There are relocations to the write-protected text segment. */
2952 if (obj->textrel && reloc_textrel_prot(obj, true) != 0)
2955 /* Process the non-PLT non-IFUNC relocations. */
2956 if (reloc_non_plt(obj, rtldobj, flags, lockstate))
2959 /* Re-protected the text segment. */
2960 if (obj->textrel && reloc_textrel_prot(obj, false) != 0)
2963 /* Set the special PLT or GOT entries. */
2966 /* Process the PLT relocations. */
2967 if (reloc_plt(obj, flags, lockstate) == -1)
2969 /* Relocate the jump slots if we are doing immediate binding. */
2970 if ((obj->bind_now || bind_now) && reloc_jmpslots(obj, flags,
2974 if (!obj->mainprog && obj_enforce_relro(obj) == -1)
2978 * Set up the magic number and version in the Obj_Entry. These
2979 * were checked in the crt1.o from the original ElfKit, so we
2980 * set them for backward compatibility.
2982 obj->magic = RTLD_MAGIC;
2983 obj->version = RTLD_VERSION;
2989 * Relocate newly-loaded shared objects. The argument is a pointer to
2990 * the Obj_Entry for the first such object. All objects from the first
2991 * to the end of the list of objects are relocated. Returns 0 on success,
2995 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
2996 int flags, RtldLockState *lockstate)
3001 for (error = 0, obj = first; obj != NULL;
3002 obj = TAILQ_NEXT(obj, next)) {
3005 error = relocate_object(obj, bind_now, rtldobj, flags,
3014 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
3015 * referencing STT_GNU_IFUNC symbols is postponed till the other
3016 * relocations are done. The indirect functions specified as
3017 * ifunc are allowed to call other symbols, so we need to have
3018 * objects relocated before asking for resolution from indirects.
3020 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
3021 * instead of the usual lazy handling of PLT slots. It is
3022 * consistent with how GNU does it.
3025 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags,
3026 RtldLockState *lockstate)
3029 if (obj->ifuncs_resolved)
3031 obj->ifuncs_resolved = true;
3032 if (!obj->irelative && !((obj->bind_now || bind_now) && obj->gnu_ifunc))
3034 if (obj_disable_relro(obj) == -1 ||
3035 (obj->irelative && reloc_iresolve(obj, lockstate) == -1) ||
3036 ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
3037 reloc_gnu_ifunc(obj, flags, lockstate) == -1) ||
3038 obj_enforce_relro(obj) == -1)
3044 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags,
3045 RtldLockState *lockstate)
3050 STAILQ_FOREACH(elm, list, link) {
3054 if (resolve_object_ifunc(obj, bind_now, flags,
3062 * Cleanup procedure. It will be called (by the atexit mechanism) just
3063 * before the process exits.
3068 RtldLockState lockstate;
3070 wlock_acquire(rtld_bind_lock, &lockstate);
3072 objlist_call_fini(&list_fini, NULL, &lockstate);
3073 /* No need to remove the items from the list, since we are exiting. */
3074 if (!libmap_disable)
3076 lock_release(rtld_bind_lock, &lockstate);
3085 * Iterate over a search path, translate each element, and invoke the
3086 * callback on the result.
3089 path_enumerate(const char *path, path_enum_proc callback,
3090 const char *refobj_path, void *arg)
3096 path += strspn(path, ":;");
3097 while (*path != '\0') {
3101 len = strcspn(path, ":;");
3102 trans = lm_findn(refobj_path, path, len);
3104 res = callback(trans, strlen(trans), arg);
3106 res = callback(path, len, arg);
3112 path += strspn(path, ":;");
3118 struct try_library_args {
3127 try_library_path(const char *dir, size_t dirlen, void *param)
3129 struct try_library_args *arg;
3133 if (*dir == '/' || trust) {
3136 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
3139 pathname = arg->buffer;
3140 strncpy(pathname, dir, dirlen);
3141 pathname[dirlen] = '/';
3142 strcpy(pathname + dirlen + 1, arg->name);
3144 dbg(" Trying \"%s\"", pathname);
3145 fd = open(pathname, O_RDONLY | O_CLOEXEC | O_VERIFY);
3147 dbg(" Opened \"%s\", fd %d", pathname, fd);
3148 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
3149 strcpy(pathname, arg->buffer);
3153 dbg(" Failed to open \"%s\": %s",
3154 pathname, rtld_strerror(errno));
3161 search_library_path(const char *name, const char *path,
3162 const char *refobj_path, int *fdp)
3165 struct try_library_args arg;
3171 arg.namelen = strlen(name);
3172 arg.buffer = xmalloc(PATH_MAX);
3173 arg.buflen = PATH_MAX;
3176 p = path_enumerate(path, try_library_path, refobj_path, &arg);
3186 * Finds the library with the given name using the directory descriptors
3187 * listed in the LD_LIBRARY_PATH_FDS environment variable.
3189 * Returns a freshly-opened close-on-exec file descriptor for the library,
3190 * or -1 if the library cannot be found.
3193 search_library_pathfds(const char *name, const char *path, int *fdp)
3195 char *envcopy, *fdstr, *found, *last_token;
3199 dbg("%s('%s', '%s', fdp)", __func__, name, path);
3201 /* Don't load from user-specified libdirs into setuid binaries. */
3205 /* We can't do anything if LD_LIBRARY_PATH_FDS isn't set. */
3209 /* LD_LIBRARY_PATH_FDS only works with relative paths. */
3210 if (name[0] == '/') {
3211 dbg("Absolute path (%s) passed to %s", name, __func__);
3216 * Use strtok_r() to walk the FD:FD:FD list. This requires a local
3217 * copy of the path, as strtok_r rewrites separator tokens
3221 envcopy = xstrdup(path);
3222 for (fdstr = strtok_r(envcopy, ":", &last_token); fdstr != NULL;
3223 fdstr = strtok_r(NULL, ":", &last_token)) {
3224 dirfd = parse_integer(fdstr);
3226 _rtld_error("failed to parse directory FD: '%s'",
3230 fd = __sys_openat(dirfd, name, O_RDONLY | O_CLOEXEC | O_VERIFY);
3233 len = strlen(fdstr) + strlen(name) + 3;
3234 found = xmalloc(len);
3235 if (rtld_snprintf(found, len, "#%d/%s", dirfd, name) < 0) {
3236 _rtld_error("error generating '%d/%s'",
3240 dbg("open('%s') => %d", found, fd);
3251 dlclose(void *handle)
3253 RtldLockState lockstate;
3256 wlock_acquire(rtld_bind_lock, &lockstate);
3257 error = dlclose_locked(handle, &lockstate);
3258 lock_release(rtld_bind_lock, &lockstate);
3263 dlclose_locked(void *handle, RtldLockState *lockstate)
3267 root = dlcheck(handle);
3270 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
3273 /* Unreference the object and its dependencies. */
3274 root->dl_refcount--;
3276 if (root->refcount == 1) {
3278 * The object will be no longer referenced, so we must unload it.
3279 * First, call the fini functions.
3281 objlist_call_fini(&list_fini, root, lockstate);
3285 /* Finish cleaning up the newly-unreferenced objects. */
3286 GDB_STATE(RT_DELETE,&root->linkmap);
3287 unload_object(root, lockstate);
3288 GDB_STATE(RT_CONSISTENT,NULL);
3292 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
3299 char *msg = error_message;
3300 error_message = NULL;
3305 * This function is deprecated and has no effect.
3308 dllockinit(void *context,
3309 void *(*_lock_create)(void *context) __unused,
3310 void (*_rlock_acquire)(void *lock) __unused,
3311 void (*_wlock_acquire)(void *lock) __unused,
3312 void (*_lock_release)(void *lock) __unused,
3313 void (*_lock_destroy)(void *lock) __unused,
3314 void (*context_destroy)(void *context))
3316 static void *cur_context;
3317 static void (*cur_context_destroy)(void *);
3319 /* Just destroy the context from the previous call, if necessary. */
3320 if (cur_context_destroy != NULL)
3321 cur_context_destroy(cur_context);
3322 cur_context = context;
3323 cur_context_destroy = context_destroy;
3327 dlopen(const char *name, int mode)
3330 return (rtld_dlopen(name, -1, mode));
3334 fdlopen(int fd, int mode)
3337 return (rtld_dlopen(NULL, fd, mode));
3341 rtld_dlopen(const char *name, int fd, int mode)
3343 RtldLockState lockstate;
3346 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
3347 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
3348 if (ld_tracing != NULL) {
3349 rlock_acquire(rtld_bind_lock, &lockstate);
3350 if (sigsetjmp(lockstate.env, 0) != 0)
3351 lock_upgrade(rtld_bind_lock, &lockstate);
3352 environ = __DECONST(char **, *get_program_var_addr("environ", &lockstate));
3353 lock_release(rtld_bind_lock, &lockstate);
3355 lo_flags = RTLD_LO_DLOPEN;
3356 if (mode & RTLD_NODELETE)
3357 lo_flags |= RTLD_LO_NODELETE;
3358 if (mode & RTLD_NOLOAD)
3359 lo_flags |= RTLD_LO_NOLOAD;
3360 if (ld_tracing != NULL)
3361 lo_flags |= RTLD_LO_TRACE;
3363 return (dlopen_object(name, fd, obj_main, lo_flags,
3364 mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL));
3368 dlopen_cleanup(Obj_Entry *obj, RtldLockState *lockstate)
3373 if (obj->refcount == 0)
3374 unload_object(obj, lockstate);
3378 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
3379 int mode, RtldLockState *lockstate)
3381 Obj_Entry *old_obj_tail;
3384 RtldLockState mlockstate;
3387 objlist_init(&initlist);
3389 if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) {
3390 wlock_acquire(rtld_bind_lock, &mlockstate);
3391 lockstate = &mlockstate;
3393 GDB_STATE(RT_ADD,NULL);
3395 old_obj_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
3397 if (name == NULL && fd == -1) {
3401 obj = load_object(name, fd, refobj, lo_flags);
3406 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
3407 objlist_push_tail(&list_global, obj);
3408 if (globallist_next(old_obj_tail) != NULL) {
3409 /* We loaded something new. */
3410 assert(globallist_next(old_obj_tail) == obj);
3412 if ((lo_flags & RTLD_LO_EARLY) == 0 && obj->static_tls &&
3413 !allocate_tls_offset(obj)) {
3414 _rtld_error("%s: No space available "
3415 "for static Thread Local Storage", obj->path);
3419 result = load_needed_objects(obj, lo_flags & (RTLD_LO_DLOPEN |
3424 result = rtld_verify_versions(&obj->dagmembers);
3425 if (result != -1 && ld_tracing)
3427 if (result == -1 || relocate_object_dag(obj,
3428 (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld,
3429 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3431 dlopen_cleanup(obj, lockstate);
3433 } else if (lo_flags & RTLD_LO_EARLY) {
3435 * Do not call the init functions for early loaded
3436 * filtees. The image is still not initialized enough
3439 * Our object is found by the global object list and
3440 * will be ordered among all init calls done right
3441 * before transferring control to main.
3444 /* Make list of init functions to call. */
3445 initlist_add_objects(obj, obj, &initlist);
3448 * Process all no_delete or global objects here, given
3449 * them own DAGs to prevent their dependencies from being
3450 * unloaded. This has to be done after we have loaded all
3451 * of the dependencies, so that we do not miss any.
3457 * Bump the reference counts for objects on this DAG. If
3458 * this is the first dlopen() call for the object that was
3459 * already loaded as a dependency, initialize the dag
3465 if ((lo_flags & RTLD_LO_TRACE) != 0)
3468 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
3469 obj->z_nodelete) && !obj->ref_nodel) {
3470 dbg("obj %s nodelete", obj->path);
3472 obj->z_nodelete = obj->ref_nodel = true;
3476 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
3478 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
3480 if ((lo_flags & RTLD_LO_EARLY) == 0) {
3481 map_stacks_exec(lockstate);
3483 distribute_static_tls(&initlist, lockstate);
3486 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
3487 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3489 objlist_clear(&initlist);
3490 dlopen_cleanup(obj, lockstate);
3491 if (lockstate == &mlockstate)
3492 lock_release(rtld_bind_lock, lockstate);
3496 if (!(lo_flags & RTLD_LO_EARLY)) {
3497 /* Call the init functions. */
3498 objlist_call_init(&initlist, lockstate);
3500 objlist_clear(&initlist);
3501 if (lockstate == &mlockstate)
3502 lock_release(rtld_bind_lock, lockstate);
3505 trace_loaded_objects(obj);
3506 if (lockstate == &mlockstate)
3507 lock_release(rtld_bind_lock, lockstate);
3512 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
3516 const Obj_Entry *obj, *defobj;
3519 RtldLockState lockstate;
3526 symlook_init(&req, name);
3528 req.flags = flags | SYMLOOK_IN_PLT;
3529 req.lockstate = &lockstate;
3531 LD_UTRACE(UTRACE_DLSYM_START, handle, NULL, 0, 0, name);
3532 rlock_acquire(rtld_bind_lock, &lockstate);
3533 if (sigsetjmp(lockstate.env, 0) != 0)
3534 lock_upgrade(rtld_bind_lock, &lockstate);
3535 if (handle == NULL || handle == RTLD_NEXT ||
3536 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
3538 if ((obj = obj_from_addr(retaddr)) == NULL) {
3539 _rtld_error("Cannot determine caller's shared object");
3540 lock_release(rtld_bind_lock, &lockstate);
3541 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3544 if (handle == NULL) { /* Just the caller's shared object. */
3545 res = symlook_obj(&req, obj);
3548 defobj = req.defobj_out;
3550 } else if (handle == RTLD_NEXT || /* Objects after caller's */
3551 handle == RTLD_SELF) { /* ... caller included */
3552 if (handle == RTLD_NEXT)
3553 obj = globallist_next(obj);
3554 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
3557 res = symlook_obj(&req, obj);
3560 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) {
3562 defobj = req.defobj_out;
3563 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3569 * Search the dynamic linker itself, and possibly resolve the
3570 * symbol from there. This is how the application links to
3571 * dynamic linker services such as dlopen.
3573 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3574 res = symlook_obj(&req, &obj_rtld);
3577 defobj = req.defobj_out;
3581 assert(handle == RTLD_DEFAULT);
3582 res = symlook_default(&req, obj);
3584 defobj = req.defobj_out;
3589 if ((obj = dlcheck(handle)) == NULL) {
3590 lock_release(rtld_bind_lock, &lockstate);
3591 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3595 donelist_init(&donelist);
3596 if (obj->mainprog) {
3597 /* Handle obtained by dlopen(NULL, ...) implies global scope. */
3598 res = symlook_global(&req, &donelist);
3601 defobj = req.defobj_out;
3604 * Search the dynamic linker itself, and possibly resolve the
3605 * symbol from there. This is how the application links to
3606 * dynamic linker services such as dlopen.
3608 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3609 res = symlook_obj(&req, &obj_rtld);
3612 defobj = req.defobj_out;
3617 /* Search the whole DAG rooted at the given object. */
3618 res = symlook_list(&req, &obj->dagmembers, &donelist);
3621 defobj = req.defobj_out;
3627 lock_release(rtld_bind_lock, &lockstate);
3630 * The value required by the caller is derived from the value
3631 * of the symbol. this is simply the relocated value of the
3634 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
3635 sym = make_function_pointer(def, defobj);
3636 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
3637 sym = rtld_resolve_ifunc(defobj, def);
3638 else if (ELF_ST_TYPE(def->st_info) == STT_TLS) {
3639 ti.ti_module = defobj->tlsindex;
3640 ti.ti_offset = def->st_value;
3641 sym = __tls_get_addr(&ti);
3643 sym = defobj->relocbase + def->st_value;
3644 LD_UTRACE(UTRACE_DLSYM_STOP, handle, sym, 0, 0, name);
3648 _rtld_error("Undefined symbol \"%s%s%s\"", name, ve != NULL ? "@" : "",
3649 ve != NULL ? ve->name : "");
3650 lock_release(rtld_bind_lock, &lockstate);
3651 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3656 dlsym(void *handle, const char *name)
3658 return do_dlsym(handle, name, __builtin_return_address(0), NULL,
3663 dlfunc(void *handle, const char *name)
3670 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
3676 dlvsym(void *handle, const char *name, const char *version)
3680 ventry.name = version;
3682 ventry.hash = elf_hash(version);
3684 return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
3689 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
3691 const Obj_Entry *obj;
3692 RtldLockState lockstate;
3694 rlock_acquire(rtld_bind_lock, &lockstate);
3695 obj = obj_from_addr(addr);
3697 _rtld_error("No shared object contains address");
3698 lock_release(rtld_bind_lock, &lockstate);
3701 rtld_fill_dl_phdr_info(obj, phdr_info);
3702 lock_release(rtld_bind_lock, &lockstate);
3707 dladdr(const void *addr, Dl_info *info)
3709 const Obj_Entry *obj;
3712 unsigned long symoffset;
3713 RtldLockState lockstate;
3715 rlock_acquire(rtld_bind_lock, &lockstate);
3716 obj = obj_from_addr(addr);
3718 _rtld_error("No shared object contains address");
3719 lock_release(rtld_bind_lock, &lockstate);
3722 info->dli_fname = obj->path;
3723 info->dli_fbase = obj->mapbase;
3724 info->dli_saddr = (void *)0;
3725 info->dli_sname = NULL;
3728 * Walk the symbol list looking for the symbol whose address is
3729 * closest to the address sent in.
3731 for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) {
3732 def = obj->symtab + symoffset;
3735 * For skip the symbol if st_shndx is either SHN_UNDEF or
3738 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
3742 * If the symbol is greater than the specified address, or if it
3743 * is further away from addr than the current nearest symbol,
3746 symbol_addr = obj->relocbase + def->st_value;
3747 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
3750 /* Update our idea of the nearest symbol. */
3751 info->dli_sname = obj->strtab + def->st_name;
3752 info->dli_saddr = symbol_addr;
3755 if (info->dli_saddr == addr)
3758 lock_release(rtld_bind_lock, &lockstate);
3763 dlinfo(void *handle, int request, void *p)
3765 const Obj_Entry *obj;
3766 RtldLockState lockstate;
3769 rlock_acquire(rtld_bind_lock, &lockstate);
3771 if (handle == NULL || handle == RTLD_SELF) {
3774 retaddr = __builtin_return_address(0); /* __GNUC__ only */
3775 if ((obj = obj_from_addr(retaddr)) == NULL)
3776 _rtld_error("Cannot determine caller's shared object");
3778 obj = dlcheck(handle);
3781 lock_release(rtld_bind_lock, &lockstate);
3787 case RTLD_DI_LINKMAP:
3788 *((struct link_map const **)p) = &obj->linkmap;
3790 case RTLD_DI_ORIGIN:
3791 error = rtld_dirname(obj->path, p);
3794 case RTLD_DI_SERINFOSIZE:
3795 case RTLD_DI_SERINFO:
3796 error = do_search_info(obj, request, (struct dl_serinfo *)p);
3800 _rtld_error("Invalid request %d passed to dlinfo()", request);
3804 lock_release(rtld_bind_lock, &lockstate);
3810 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
3813 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
3814 phdr_info->dlpi_name = obj->path;
3815 phdr_info->dlpi_phdr = obj->phdr;
3816 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
3817 phdr_info->dlpi_tls_modid = obj->tlsindex;
3818 phdr_info->dlpi_tls_data = obj->tlsinit;
3819 phdr_info->dlpi_adds = obj_loads;
3820 phdr_info->dlpi_subs = obj_loads - obj_count;
3824 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
3826 struct dl_phdr_info phdr_info;
3827 Obj_Entry *obj, marker;
3828 RtldLockState bind_lockstate, phdr_lockstate;
3831 init_marker(&marker);
3834 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
3835 wlock_acquire(rtld_bind_lock, &bind_lockstate);
3836 for (obj = globallist_curr(TAILQ_FIRST(&obj_list)); obj != NULL;) {
3837 TAILQ_INSERT_AFTER(&obj_list, obj, &marker, next);
3838 rtld_fill_dl_phdr_info(obj, &phdr_info);
3840 lock_release(rtld_bind_lock, &bind_lockstate);
3842 error = callback(&phdr_info, sizeof phdr_info, param);
3844 wlock_acquire(rtld_bind_lock, &bind_lockstate);
3846 obj = globallist_next(&marker);
3847 TAILQ_REMOVE(&obj_list, &marker, next);
3849 lock_release(rtld_bind_lock, &bind_lockstate);
3850 lock_release(rtld_phdr_lock, &phdr_lockstate);
3856 rtld_fill_dl_phdr_info(&obj_rtld, &phdr_info);
3857 lock_release(rtld_bind_lock, &bind_lockstate);
3858 error = callback(&phdr_info, sizeof(phdr_info), param);
3860 lock_release(rtld_phdr_lock, &phdr_lockstate);
3865 fill_search_info(const char *dir, size_t dirlen, void *param)
3867 struct fill_search_info_args *arg;
3871 if (arg->request == RTLD_DI_SERINFOSIZE) {
3872 arg->serinfo->dls_cnt ++;
3873 arg->serinfo->dls_size += sizeof(struct dl_serpath) + dirlen + 1;
3875 struct dl_serpath *s_entry;
3877 s_entry = arg->serpath;
3878 s_entry->dls_name = arg->strspace;
3879 s_entry->dls_flags = arg->flags;
3881 strncpy(arg->strspace, dir, dirlen);
3882 arg->strspace[dirlen] = '\0';
3884 arg->strspace += dirlen + 1;
3892 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
3894 struct dl_serinfo _info;
3895 struct fill_search_info_args args;
3897 args.request = RTLD_DI_SERINFOSIZE;
3898 args.serinfo = &_info;
3900 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
3903 path_enumerate(obj->rpath, fill_search_info, NULL, &args);
3904 path_enumerate(ld_library_path, fill_search_info, NULL, &args);
3905 path_enumerate(obj->runpath, fill_search_info, NULL, &args);
3906 path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args);
3907 if (!obj->z_nodeflib)
3908 path_enumerate(ld_standard_library_path, fill_search_info, NULL, &args);
3911 if (request == RTLD_DI_SERINFOSIZE) {
3912 info->dls_size = _info.dls_size;
3913 info->dls_cnt = _info.dls_cnt;
3917 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
3918 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
3922 args.request = RTLD_DI_SERINFO;
3923 args.serinfo = info;
3924 args.serpath = &info->dls_serpath[0];
3925 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
3927 args.flags = LA_SER_RUNPATH;
3928 if (path_enumerate(obj->rpath, fill_search_info, NULL, &args) != NULL)
3931 args.flags = LA_SER_LIBPATH;
3932 if (path_enumerate(ld_library_path, fill_search_info, NULL, &args) != NULL)
3935 args.flags = LA_SER_RUNPATH;
3936 if (path_enumerate(obj->runpath, fill_search_info, NULL, &args) != NULL)
3939 args.flags = LA_SER_CONFIG;
3940 if (path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args)
3944 args.flags = LA_SER_DEFAULT;
3945 if (!obj->z_nodeflib && path_enumerate(ld_standard_library_path,
3946 fill_search_info, NULL, &args) != NULL)
3952 rtld_dirname(const char *path, char *bname)
3956 /* Empty or NULL string gets treated as "." */
3957 if (path == NULL || *path == '\0') {
3963 /* Strip trailing slashes */
3964 endp = path + strlen(path) - 1;
3965 while (endp > path && *endp == '/')
3968 /* Find the start of the dir */
3969 while (endp > path && *endp != '/')
3972 /* Either the dir is "/" or there are no slashes */
3974 bname[0] = *endp == '/' ? '/' : '.';
3980 } while (endp > path && *endp == '/');
3983 if (endp - path + 2 > PATH_MAX)
3985 _rtld_error("Filename is too long: %s", path);
3989 strncpy(bname, path, endp - path + 1);
3990 bname[endp - path + 1] = '\0';
3995 rtld_dirname_abs(const char *path, char *base)
3999 if (realpath(path, base) == NULL) {
4000 _rtld_error("realpath \"%s\" failed (%s)", path,
4001 rtld_strerror(errno));
4004 dbg("%s -> %s", path, base);
4005 last = strrchr(base, '/');
4007 _rtld_error("non-abs result from realpath \"%s\"", path);
4016 linkmap_add(Obj_Entry *obj)
4018 struct link_map *l = &obj->linkmap;
4019 struct link_map *prev;
4021 obj->linkmap.l_name = obj->path;
4022 obj->linkmap.l_addr = obj->mapbase;
4023 obj->linkmap.l_ld = obj->dynamic;
4025 /* GDB needs load offset on MIPS to use the symbols */
4026 obj->linkmap.l_offs = obj->relocbase;
4029 if (r_debug.r_map == NULL) {
4035 * Scan to the end of the list, but not past the entry for the
4036 * dynamic linker, which we want to keep at the very end.
4038 for (prev = r_debug.r_map;
4039 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
4040 prev = prev->l_next)
4043 /* Link in the new entry. */
4045 l->l_next = prev->l_next;
4046 if (l->l_next != NULL)
4047 l->l_next->l_prev = l;
4052 linkmap_delete(Obj_Entry *obj)
4054 struct link_map *l = &obj->linkmap;
4056 if (l->l_prev == NULL) {
4057 if ((r_debug.r_map = l->l_next) != NULL)
4058 l->l_next->l_prev = NULL;
4062 if ((l->l_prev->l_next = l->l_next) != NULL)
4063 l->l_next->l_prev = l->l_prev;
4067 * Function for the debugger to set a breakpoint on to gain control.
4069 * The two parameters allow the debugger to easily find and determine
4070 * what the runtime loader is doing and to whom it is doing it.
4072 * When the loadhook trap is hit (r_debug_state, set at program
4073 * initialization), the arguments can be found on the stack:
4075 * +8 struct link_map *m
4076 * +4 struct r_debug *rd
4080 r_debug_state(struct r_debug* rd __unused, struct link_map *m __unused)
4083 * The following is a hack to force the compiler to emit calls to
4084 * this function, even when optimizing. If the function is empty,
4085 * the compiler is not obliged to emit any code for calls to it,
4086 * even when marked __noinline. However, gdb depends on those
4089 __compiler_membar();
4093 * A function called after init routines have completed. This can be used to
4094 * break before a program's entry routine is called, and can be used when
4095 * main is not available in the symbol table.
4098 _r_debug_postinit(struct link_map *m __unused)
4101 /* See r_debug_state(). */
4102 __compiler_membar();
4106 release_object(Obj_Entry *obj)
4109 if (obj->holdcount > 0) {
4110 obj->unholdfree = true;
4113 munmap(obj->mapbase, obj->mapsize);
4114 linkmap_delete(obj);
4119 * Get address of the pointer variable in the main program.
4120 * Prefer non-weak symbol over the weak one.
4122 static const void **
4123 get_program_var_addr(const char *name, RtldLockState *lockstate)
4128 symlook_init(&req, name);
4129 req.lockstate = lockstate;
4130 donelist_init(&donelist);
4131 if (symlook_global(&req, &donelist) != 0)
4133 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
4134 return ((const void **)make_function_pointer(req.sym_out,
4136 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
4137 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
4139 return ((const void **)(req.defobj_out->relocbase +
4140 req.sym_out->st_value));
4144 * Set a pointer variable in the main program to the given value. This
4145 * is used to set key variables such as "environ" before any of the
4146 * init functions are called.
4149 set_program_var(const char *name, const void *value)
4153 if ((addr = get_program_var_addr(name, NULL)) != NULL) {
4154 dbg("\"%s\": *%p <-- %p", name, addr, value);
4160 * Search the global objects, including dependencies and main object,
4161 * for the given symbol.
4164 symlook_global(SymLook *req, DoneList *donelist)
4167 const Objlist_Entry *elm;
4170 symlook_init_from_req(&req1, req);
4172 /* Search all objects loaded at program start up. */
4173 if (req->defobj_out == NULL ||
4174 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
4175 res = symlook_list(&req1, &list_main, donelist);
4176 if (res == 0 && (req->defobj_out == NULL ||
4177 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4178 req->sym_out = req1.sym_out;
4179 req->defobj_out = req1.defobj_out;
4180 assert(req->defobj_out != NULL);
4184 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
4185 STAILQ_FOREACH(elm, &list_global, link) {
4186 if (req->defobj_out != NULL &&
4187 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
4189 res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
4190 if (res == 0 && (req->defobj_out == NULL ||
4191 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4192 req->sym_out = req1.sym_out;
4193 req->defobj_out = req1.defobj_out;
4194 assert(req->defobj_out != NULL);
4198 return (req->sym_out != NULL ? 0 : ESRCH);
4202 * Given a symbol name in a referencing object, find the corresponding
4203 * definition of the symbol. Returns a pointer to the symbol, or NULL if
4204 * no definition was found. Returns a pointer to the Obj_Entry of the
4205 * defining object via the reference parameter DEFOBJ_OUT.
4208 symlook_default(SymLook *req, const Obj_Entry *refobj)
4211 const Objlist_Entry *elm;
4215 donelist_init(&donelist);
4216 symlook_init_from_req(&req1, req);
4219 * Look first in the referencing object if linked symbolically,
4220 * and similarly handle protected symbols.
4222 res = symlook_obj(&req1, refobj);
4223 if (res == 0 && (refobj->symbolic ||
4224 ELF_ST_VISIBILITY(req1.sym_out->st_other) == STV_PROTECTED)) {
4225 req->sym_out = req1.sym_out;
4226 req->defobj_out = req1.defobj_out;
4227 assert(req->defobj_out != NULL);
4229 if (refobj->symbolic || req->defobj_out != NULL)
4230 donelist_check(&donelist, refobj);
4232 symlook_global(req, &donelist);
4234 /* Search all dlopened DAGs containing the referencing object. */
4235 STAILQ_FOREACH(elm, &refobj->dldags, link) {
4236 if (req->sym_out != NULL &&
4237 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
4239 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
4240 if (res == 0 && (req->sym_out == NULL ||
4241 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4242 req->sym_out = req1.sym_out;
4243 req->defobj_out = req1.defobj_out;
4244 assert(req->defobj_out != NULL);
4249 * Search the dynamic linker itself, and possibly resolve the
4250 * symbol from there. This is how the application links to
4251 * dynamic linker services such as dlopen.
4253 if (req->sym_out == NULL ||
4254 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
4255 res = symlook_obj(&req1, &obj_rtld);
4257 req->sym_out = req1.sym_out;
4258 req->defobj_out = req1.defobj_out;
4259 assert(req->defobj_out != NULL);
4263 return (req->sym_out != NULL ? 0 : ESRCH);
4267 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
4270 const Obj_Entry *defobj;
4271 const Objlist_Entry *elm;
4277 STAILQ_FOREACH(elm, objlist, link) {
4278 if (donelist_check(dlp, elm->obj))
4280 symlook_init_from_req(&req1, req);
4281 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
4282 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
4284 defobj = req1.defobj_out;
4285 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
4292 req->defobj_out = defobj;
4299 * Search the chain of DAGS cointed to by the given Needed_Entry
4300 * for a symbol of the given name. Each DAG is scanned completely
4301 * before advancing to the next one. Returns a pointer to the symbol,
4302 * or NULL if no definition was found.
4305 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
4308 const Needed_Entry *n;
4309 const Obj_Entry *defobj;
4315 symlook_init_from_req(&req1, req);
4316 for (n = needed; n != NULL; n = n->next) {
4317 if (n->obj == NULL ||
4318 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
4320 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
4322 defobj = req1.defobj_out;
4323 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
4329 req->defobj_out = defobj;
4336 * Search the symbol table of a single shared object for a symbol of
4337 * the given name and version, if requested. Returns a pointer to the
4338 * symbol, or NULL if no definition was found. If the object is
4339 * filter, return filtered symbol from filtee.
4341 * The symbol's hash value is passed in for efficiency reasons; that
4342 * eliminates many recomputations of the hash value.
4345 symlook_obj(SymLook *req, const Obj_Entry *obj)
4349 int flags, res, mres;
4352 * If there is at least one valid hash at this point, we prefer to
4353 * use the faster GNU version if available.
4355 if (obj->valid_hash_gnu)
4356 mres = symlook_obj1_gnu(req, obj);
4357 else if (obj->valid_hash_sysv)
4358 mres = symlook_obj1_sysv(req, obj);
4363 if (obj->needed_filtees != NULL) {
4364 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4365 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4366 donelist_init(&donelist);
4367 symlook_init_from_req(&req1, req);
4368 res = symlook_needed(&req1, obj->needed_filtees, &donelist);
4370 req->sym_out = req1.sym_out;
4371 req->defobj_out = req1.defobj_out;
4375 if (obj->needed_aux_filtees != NULL) {
4376 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4377 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4378 donelist_init(&donelist);
4379 symlook_init_from_req(&req1, req);
4380 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
4382 req->sym_out = req1.sym_out;
4383 req->defobj_out = req1.defobj_out;
4391 /* Symbol match routine common to both hash functions */
4393 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result,
4394 const unsigned long symnum)
4397 const Elf_Sym *symp;
4400 symp = obj->symtab + symnum;
4401 strp = obj->strtab + symp->st_name;
4403 switch (ELF_ST_TYPE(symp->st_info)) {
4409 if (symp->st_value == 0)
4413 if (symp->st_shndx != SHN_UNDEF)
4416 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
4417 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
4424 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
4427 if (req->ventry == NULL) {
4428 if (obj->versyms != NULL) {
4429 verndx = VER_NDX(obj->versyms[symnum]);
4430 if (verndx > obj->vernum) {
4432 "%s: symbol %s references wrong version %d",
4433 obj->path, obj->strtab + symnum, verndx);
4437 * If we are not called from dlsym (i.e. this
4438 * is a normal relocation from unversioned
4439 * binary), accept the symbol immediately if
4440 * it happens to have first version after this
4441 * shared object became versioned. Otherwise,
4442 * if symbol is versioned and not hidden,
4443 * remember it. If it is the only symbol with
4444 * this name exported by the shared object, it
4445 * will be returned as a match by the calling
4446 * function. If symbol is global (verndx < 2)
4447 * accept it unconditionally.
4449 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
4450 verndx == VER_NDX_GIVEN) {
4451 result->sym_out = symp;
4454 else if (verndx >= VER_NDX_GIVEN) {
4455 if ((obj->versyms[symnum] & VER_NDX_HIDDEN)
4457 if (result->vsymp == NULL)
4458 result->vsymp = symp;
4464 result->sym_out = symp;
4467 if (obj->versyms == NULL) {
4468 if (object_match_name(obj, req->ventry->name)) {
4469 _rtld_error("%s: object %s should provide version %s "
4470 "for symbol %s", obj_rtld.path, obj->path,
4471 req->ventry->name, obj->strtab + symnum);
4475 verndx = VER_NDX(obj->versyms[symnum]);
4476 if (verndx > obj->vernum) {
4477 _rtld_error("%s: symbol %s references wrong version %d",
4478 obj->path, obj->strtab + symnum, verndx);
4481 if (obj->vertab[verndx].hash != req->ventry->hash ||
4482 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
4484 * Version does not match. Look if this is a
4485 * global symbol and if it is not hidden. If
4486 * global symbol (verndx < 2) is available,
4487 * use it. Do not return symbol if we are
4488 * called by dlvsym, because dlvsym looks for
4489 * a specific version and default one is not
4490 * what dlvsym wants.
4492 if ((req->flags & SYMLOOK_DLSYM) ||
4493 (verndx >= VER_NDX_GIVEN) ||
4494 (obj->versyms[symnum] & VER_NDX_HIDDEN))
4498 result->sym_out = symp;
4503 * Search for symbol using SysV hash function.
4504 * obj->buckets is known not to be NULL at this point; the test for this was
4505 * performed with the obj->valid_hash_sysv assignment.
4508 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj)
4510 unsigned long symnum;
4511 Sym_Match_Result matchres;
4513 matchres.sym_out = NULL;
4514 matchres.vsymp = NULL;
4515 matchres.vcount = 0;
4517 for (symnum = obj->buckets[req->hash % obj->nbuckets];
4518 symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
4519 if (symnum >= obj->nchains)
4520 return (ESRCH); /* Bad object */
4522 if (matched_symbol(req, obj, &matchres, symnum)) {
4523 req->sym_out = matchres.sym_out;
4524 req->defobj_out = obj;
4528 if (matchres.vcount == 1) {
4529 req->sym_out = matchres.vsymp;
4530 req->defobj_out = obj;
4536 /* Search for symbol using GNU hash function */
4538 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj)
4540 Elf_Addr bloom_word;
4541 const Elf32_Word *hashval;
4543 Sym_Match_Result matchres;
4544 unsigned int h1, h2;
4545 unsigned long symnum;
4547 matchres.sym_out = NULL;
4548 matchres.vsymp = NULL;
4549 matchres.vcount = 0;
4551 /* Pick right bitmask word from Bloom filter array */
4552 bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) &
4553 obj->maskwords_bm_gnu];
4555 /* Calculate modulus word size of gnu hash and its derivative */
4556 h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1);
4557 h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1));
4559 /* Filter out the "definitely not in set" queries */
4560 if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0)
4563 /* Locate hash chain and corresponding value element*/
4564 bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu];
4567 hashval = &obj->chain_zero_gnu[bucket];
4569 if (((*hashval ^ req->hash_gnu) >> 1) == 0) {
4570 symnum = hashval - obj->chain_zero_gnu;
4571 if (matched_symbol(req, obj, &matchres, symnum)) {
4572 req->sym_out = matchres.sym_out;
4573 req->defobj_out = obj;
4577 } while ((*hashval++ & 1) == 0);
4578 if (matchres.vcount == 1) {
4579 req->sym_out = matchres.vsymp;
4580 req->defobj_out = obj;
4587 trace_loaded_objects(Obj_Entry *obj)
4589 const char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
4592 if ((main_local = getenv(_LD("TRACE_LOADED_OBJECTS_PROGNAME"))) == NULL)
4595 if ((fmt1 = getenv(_LD("TRACE_LOADED_OBJECTS_FMT1"))) == NULL)
4596 fmt1 = "\t%o => %p (%x)\n";
4598 if ((fmt2 = getenv(_LD("TRACE_LOADED_OBJECTS_FMT2"))) == NULL)
4599 fmt2 = "\t%o (%x)\n";
4601 list_containers = getenv(_LD("TRACE_LOADED_OBJECTS_ALL"));
4603 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
4604 Needed_Entry *needed;
4605 const char *name, *path;
4610 if (list_containers && obj->needed != NULL)
4611 rtld_printf("%s:\n", obj->path);
4612 for (needed = obj->needed; needed; needed = needed->next) {
4613 if (needed->obj != NULL) {
4614 if (needed->obj->traced && !list_containers)
4616 needed->obj->traced = true;
4617 path = needed->obj->path;
4621 name = obj->strtab + needed->name;
4622 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
4624 fmt = is_lib ? fmt1 : fmt2;
4625 while ((c = *fmt++) != '\0') {
4651 rtld_putstr(main_local);
4654 rtld_putstr(obj_main->path);
4661 rtld_printf("%d", sodp->sod_major);
4664 rtld_printf("%d", sodp->sod_minor);
4671 rtld_printf("%p", needed->obj ? needed->obj->mapbase :
4684 * Unload a dlopened object and its dependencies from memory and from
4685 * our data structures. It is assumed that the DAG rooted in the
4686 * object has already been unreferenced, and that the object has a
4687 * reference count of 0.
4690 unload_object(Obj_Entry *root, RtldLockState *lockstate)
4692 Obj_Entry marker, *obj, *next;
4694 assert(root->refcount == 0);
4697 * Pass over the DAG removing unreferenced objects from
4698 * appropriate lists.
4700 unlink_object(root);
4702 /* Unmap all objects that are no longer referenced. */
4703 for (obj = TAILQ_FIRST(&obj_list); obj != NULL; obj = next) {
4704 next = TAILQ_NEXT(obj, next);
4705 if (obj->marker || obj->refcount != 0)
4707 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase,
4708 obj->mapsize, 0, obj->path);
4709 dbg("unloading \"%s\"", obj->path);
4711 * Unlink the object now to prevent new references from
4712 * being acquired while the bind lock is dropped in
4713 * recursive dlclose() invocations.
4715 TAILQ_REMOVE(&obj_list, obj, next);
4718 if (obj->filtees_loaded) {
4720 init_marker(&marker);
4721 TAILQ_INSERT_BEFORE(next, &marker, next);
4722 unload_filtees(obj, lockstate);
4723 next = TAILQ_NEXT(&marker, next);
4724 TAILQ_REMOVE(&obj_list, &marker, next);
4726 unload_filtees(obj, lockstate);
4728 release_object(obj);
4733 unlink_object(Obj_Entry *root)
4737 if (root->refcount == 0) {
4738 /* Remove the object from the RTLD_GLOBAL list. */
4739 objlist_remove(&list_global, root);
4741 /* Remove the object from all objects' DAG lists. */
4742 STAILQ_FOREACH(elm, &root->dagmembers, link) {
4743 objlist_remove(&elm->obj->dldags, root);
4744 if (elm->obj != root)
4745 unlink_object(elm->obj);
4751 ref_dag(Obj_Entry *root)
4755 assert(root->dag_inited);
4756 STAILQ_FOREACH(elm, &root->dagmembers, link)
4757 elm->obj->refcount++;
4761 unref_dag(Obj_Entry *root)
4765 assert(root->dag_inited);
4766 STAILQ_FOREACH(elm, &root->dagmembers, link)
4767 elm->obj->refcount--;
4771 * Common code for MD __tls_get_addr().
4773 static void *tls_get_addr_slow(Elf_Addr **, int, size_t) __noinline;
4775 tls_get_addr_slow(Elf_Addr **dtvp, int index, size_t offset)
4777 Elf_Addr *newdtv, *dtv;
4778 RtldLockState lockstate;
4782 /* Check dtv generation in case new modules have arrived */
4783 if (dtv[0] != tls_dtv_generation) {
4784 wlock_acquire(rtld_bind_lock, &lockstate);
4785 newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4787 if (to_copy > tls_max_index)
4788 to_copy = tls_max_index;
4789 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
4790 newdtv[0] = tls_dtv_generation;
4791 newdtv[1] = tls_max_index;
4793 lock_release(rtld_bind_lock, &lockstate);
4794 dtv = *dtvp = newdtv;
4797 /* Dynamically allocate module TLS if necessary */
4798 if (dtv[index + 1] == 0) {
4799 /* Signal safe, wlock will block out signals. */
4800 wlock_acquire(rtld_bind_lock, &lockstate);
4801 if (!dtv[index + 1])
4802 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
4803 lock_release(rtld_bind_lock, &lockstate);
4805 return ((void *)(dtv[index + 1] + offset));
4809 tls_get_addr_common(Elf_Addr **dtvp, int index, size_t offset)
4814 /* Check dtv generation in case new modules have arrived */
4815 if (__predict_true(dtv[0] == tls_dtv_generation &&
4816 dtv[index + 1] != 0))
4817 return ((void *)(dtv[index + 1] + offset));
4818 return (tls_get_addr_slow(dtvp, index, offset));
4821 #if defined(__aarch64__) || defined(__arm__) || defined(__mips__) || \
4822 defined(__powerpc__) || defined(__riscv)
4825 * Return pointer to allocated TLS block
4828 get_tls_block_ptr(void *tcb, size_t tcbsize)
4830 size_t extra_size, post_size, pre_size, tls_block_size;
4831 size_t tls_init_align;
4833 tls_init_align = MAX(obj_main->tlsalign, 1);
4835 /* Compute fragments sizes. */
4836 extra_size = tcbsize - TLS_TCB_SIZE;
4837 post_size = calculate_tls_post_size(tls_init_align);
4838 tls_block_size = tcbsize + post_size;
4839 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size;
4841 return ((char *)tcb - pre_size - extra_size);
4845 * Allocate Static TLS using the Variant I method.
4847 * For details on the layout, see lib/libc/gen/tls.c.
4849 * NB: rtld's tls_static_space variable includes TLS_TCB_SIZE and post_size as
4850 * it is based on tls_last_offset, and TLS offsets here are really TCB
4851 * offsets, whereas libc's tls_static_space is just the executable's static
4855 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
4859 Elf_Addr *dtv, **tcb;
4862 size_t extra_size, maxalign, post_size, pre_size, tls_block_size;
4863 size_t tls_init_align;
4865 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
4868 assert(tcbsize >= TLS_TCB_SIZE);
4869 maxalign = MAX(tcbalign, tls_static_max_align);
4870 tls_init_align = MAX(obj_main->tlsalign, 1);
4872 /* Compute fragmets sizes. */
4873 extra_size = tcbsize - TLS_TCB_SIZE;
4874 post_size = calculate_tls_post_size(tls_init_align);
4875 tls_block_size = tcbsize + post_size;
4876 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size;
4877 tls_block_size += pre_size + tls_static_space - TLS_TCB_SIZE - post_size;
4879 /* Allocate whole TLS block */
4880 tls_block = malloc_aligned(tls_block_size, maxalign);
4881 tcb = (Elf_Addr **)(tls_block + pre_size + extra_size);
4883 if (oldtcb != NULL) {
4884 memcpy(tls_block, get_tls_block_ptr(oldtcb, tcbsize),
4886 free_aligned(get_tls_block_ptr(oldtcb, tcbsize));
4888 /* Adjust the DTV. */
4890 for (i = 0; i < dtv[1]; i++) {
4891 if (dtv[i+2] >= (Elf_Addr)oldtcb &&
4892 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
4893 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tcb;
4897 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4899 dtv[0] = tls_dtv_generation;
4900 dtv[1] = tls_max_index;
4902 for (obj = globallist_curr(objs); obj != NULL;
4903 obj = globallist_next(obj)) {
4904 if (obj->tlsoffset > 0) {
4905 addr = (Elf_Addr)tcb + obj->tlsoffset;
4906 if (obj->tlsinitsize > 0)
4907 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4908 if (obj->tlssize > obj->tlsinitsize)
4909 memset((void*)(addr + obj->tlsinitsize), 0,
4910 obj->tlssize - obj->tlsinitsize);
4911 dtv[obj->tlsindex + 1] = addr;
4920 free_tls(void *tcb, size_t tcbsize, size_t tcbalign __unused)
4923 Elf_Addr tlsstart, tlsend;
4925 size_t dtvsize, i, tls_init_align;
4927 assert(tcbsize >= TLS_TCB_SIZE);
4928 tls_init_align = MAX(obj_main->tlsalign, 1);
4930 /* Compute fragments sizes. */
4931 post_size = calculate_tls_post_size(tls_init_align);
4933 tlsstart = (Elf_Addr)tcb + TLS_TCB_SIZE + post_size;
4934 tlsend = (Elf_Addr)tcb + tls_static_space;
4936 dtv = *(Elf_Addr **)tcb;
4938 for (i = 0; i < dtvsize; i++) {
4939 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
4940 free((void*)dtv[i+2]);
4944 free_aligned(get_tls_block_ptr(tcb, tcbsize));
4949 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__)
4952 * Allocate Static TLS using the Variant II method.
4955 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
4958 size_t size, ralign;
4960 Elf_Addr *dtv, *olddtv;
4961 Elf_Addr segbase, oldsegbase, addr;
4965 if (tls_static_max_align > ralign)
4966 ralign = tls_static_max_align;
4967 size = round(tls_static_space, ralign) + round(tcbsize, ralign);
4969 assert(tcbsize >= 2*sizeof(Elf_Addr));
4970 tls = malloc_aligned(size, ralign);
4971 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4973 segbase = (Elf_Addr)(tls + round(tls_static_space, ralign));
4974 ((Elf_Addr*)segbase)[0] = segbase;
4975 ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
4977 dtv[0] = tls_dtv_generation;
4978 dtv[1] = tls_max_index;
4982 * Copy the static TLS block over whole.
4984 oldsegbase = (Elf_Addr) oldtls;
4985 memcpy((void *)(segbase - tls_static_space),
4986 (const void *)(oldsegbase - tls_static_space),
4990 * If any dynamic TLS blocks have been created tls_get_addr(),
4993 olddtv = ((Elf_Addr**)oldsegbase)[1];
4994 for (i = 0; i < olddtv[1]; i++) {
4995 if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
4996 dtv[i+2] = olddtv[i+2];
5002 * We assume that this block was the one we created with
5003 * allocate_initial_tls().
5005 free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
5007 for (obj = objs; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
5008 if (obj->marker || obj->tlsoffset == 0)
5010 addr = segbase - obj->tlsoffset;
5011 memset((void*)(addr + obj->tlsinitsize),
5012 0, obj->tlssize - obj->tlsinitsize);
5014 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
5015 obj->static_tls_copied = true;
5017 dtv[obj->tlsindex + 1] = addr;
5021 return (void*) segbase;
5025 free_tls(void *tls, size_t tcbsize __unused, size_t tcbalign)
5028 size_t size, ralign;
5030 Elf_Addr tlsstart, tlsend;
5033 * Figure out the size of the initial TLS block so that we can
5034 * find stuff which ___tls_get_addr() allocated dynamically.
5037 if (tls_static_max_align > ralign)
5038 ralign = tls_static_max_align;
5039 size = round(tls_static_space, ralign);
5041 dtv = ((Elf_Addr**)tls)[1];
5043 tlsend = (Elf_Addr) tls;
5044 tlsstart = tlsend - size;
5045 for (i = 0; i < dtvsize; i++) {
5046 if (dtv[i + 2] != 0 && (dtv[i + 2] < tlsstart || dtv[i + 2] > tlsend)) {
5047 free_aligned((void *)dtv[i + 2]);
5051 free_aligned((void *)tlsstart);
5058 * Allocate TLS block for module with given index.
5061 allocate_module_tls(int index)
5066 TAILQ_FOREACH(obj, &obj_list, next) {
5069 if (obj->tlsindex == index)
5073 _rtld_error("Can't find module with TLS index %d", index);
5077 p = malloc_aligned(obj->tlssize, obj->tlsalign);
5078 memcpy(p, obj->tlsinit, obj->tlsinitsize);
5079 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
5085 allocate_tls_offset(Obj_Entry *obj)
5092 if (obj->tlssize == 0) {
5093 obj->tls_done = true;
5097 if (tls_last_offset == 0)
5098 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
5100 off = calculate_tls_offset(tls_last_offset, tls_last_size,
5101 obj->tlssize, obj->tlsalign);
5104 * If we have already fixed the size of the static TLS block, we
5105 * must stay within that size. When allocating the static TLS, we
5106 * leave a small amount of space spare to be used for dynamically
5107 * loading modules which use static TLS.
5109 if (tls_static_space != 0) {
5110 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
5112 } else if (obj->tlsalign > tls_static_max_align) {
5113 tls_static_max_align = obj->tlsalign;
5116 tls_last_offset = obj->tlsoffset = off;
5117 tls_last_size = obj->tlssize;
5118 obj->tls_done = true;
5124 free_tls_offset(Obj_Entry *obj)
5128 * If we were the last thing to allocate out of the static TLS
5129 * block, we give our space back to the 'allocator'. This is a
5130 * simplistic workaround to allow libGL.so.1 to be loaded and
5131 * unloaded multiple times.
5133 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
5134 == calculate_tls_end(tls_last_offset, tls_last_size)) {
5135 tls_last_offset -= obj->tlssize;
5141 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
5144 RtldLockState lockstate;
5146 wlock_acquire(rtld_bind_lock, &lockstate);
5147 ret = allocate_tls(globallist_curr(TAILQ_FIRST(&obj_list)), oldtls,
5149 lock_release(rtld_bind_lock, &lockstate);
5154 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
5156 RtldLockState lockstate;
5158 wlock_acquire(rtld_bind_lock, &lockstate);
5159 free_tls(tcb, tcbsize, tcbalign);
5160 lock_release(rtld_bind_lock, &lockstate);
5164 object_add_name(Obj_Entry *obj, const char *name)
5170 entry = malloc(sizeof(Name_Entry) + len);
5172 if (entry != NULL) {
5173 strcpy(entry->name, name);
5174 STAILQ_INSERT_TAIL(&obj->names, entry, link);
5179 object_match_name(const Obj_Entry *obj, const char *name)
5183 STAILQ_FOREACH(entry, &obj->names, link) {
5184 if (strcmp(name, entry->name) == 0)
5191 locate_dependency(const Obj_Entry *obj, const char *name)
5193 const Objlist_Entry *entry;
5194 const Needed_Entry *needed;
5196 STAILQ_FOREACH(entry, &list_main, link) {
5197 if (object_match_name(entry->obj, name))
5201 for (needed = obj->needed; needed != NULL; needed = needed->next) {
5202 if (strcmp(obj->strtab + needed->name, name) == 0 ||
5203 (needed->obj != NULL && object_match_name(needed->obj, name))) {
5205 * If there is DT_NEEDED for the name we are looking for,
5206 * we are all set. Note that object might not be found if
5207 * dependency was not loaded yet, so the function can
5208 * return NULL here. This is expected and handled
5209 * properly by the caller.
5211 return (needed->obj);
5214 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
5220 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
5221 const Elf_Vernaux *vna)
5223 const Elf_Verdef *vd;
5224 const char *vername;
5226 vername = refobj->strtab + vna->vna_name;
5227 vd = depobj->verdef;
5229 _rtld_error("%s: version %s required by %s not defined",
5230 depobj->path, vername, refobj->path);
5234 if (vd->vd_version != VER_DEF_CURRENT) {
5235 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
5236 depobj->path, vd->vd_version);
5239 if (vna->vna_hash == vd->vd_hash) {
5240 const Elf_Verdaux *aux = (const Elf_Verdaux *)
5241 ((const char *)vd + vd->vd_aux);
5242 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
5245 if (vd->vd_next == 0)
5247 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5249 if (vna->vna_flags & VER_FLG_WEAK)
5251 _rtld_error("%s: version %s required by %s not found",
5252 depobj->path, vername, refobj->path);
5257 rtld_verify_object_versions(Obj_Entry *obj)
5259 const Elf_Verneed *vn;
5260 const Elf_Verdef *vd;
5261 const Elf_Verdaux *vda;
5262 const Elf_Vernaux *vna;
5263 const Obj_Entry *depobj;
5264 int maxvernum, vernum;
5266 if (obj->ver_checked)
5268 obj->ver_checked = true;
5272 * Walk over defined and required version records and figure out
5273 * max index used by any of them. Do very basic sanity checking
5277 while (vn != NULL) {
5278 if (vn->vn_version != VER_NEED_CURRENT) {
5279 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
5280 obj->path, vn->vn_version);
5283 vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux);
5285 vernum = VER_NEED_IDX(vna->vna_other);
5286 if (vernum > maxvernum)
5288 if (vna->vna_next == 0)
5290 vna = (const Elf_Vernaux *)((const char *)vna + vna->vna_next);
5292 if (vn->vn_next == 0)
5294 vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next);
5298 while (vd != NULL) {
5299 if (vd->vd_version != VER_DEF_CURRENT) {
5300 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
5301 obj->path, vd->vd_version);
5304 vernum = VER_DEF_IDX(vd->vd_ndx);
5305 if (vernum > maxvernum)
5307 if (vd->vd_next == 0)
5309 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5316 * Store version information in array indexable by version index.
5317 * Verify that object version requirements are satisfied along the
5320 obj->vernum = maxvernum + 1;
5321 obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry));
5324 while (vd != NULL) {
5325 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
5326 vernum = VER_DEF_IDX(vd->vd_ndx);
5327 assert(vernum <= maxvernum);
5328 vda = (const Elf_Verdaux *)((const char *)vd + vd->vd_aux);
5329 obj->vertab[vernum].hash = vd->vd_hash;
5330 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
5331 obj->vertab[vernum].file = NULL;
5332 obj->vertab[vernum].flags = 0;
5334 if (vd->vd_next == 0)
5336 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5340 while (vn != NULL) {
5341 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
5344 vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux);
5346 if (check_object_provided_version(obj, depobj, vna))
5348 vernum = VER_NEED_IDX(vna->vna_other);
5349 assert(vernum <= maxvernum);
5350 obj->vertab[vernum].hash = vna->vna_hash;
5351 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
5352 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
5353 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
5354 VER_INFO_HIDDEN : 0;
5355 if (vna->vna_next == 0)
5357 vna = (const Elf_Vernaux *)((const char *)vna + vna->vna_next);
5359 if (vn->vn_next == 0)
5361 vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next);
5367 rtld_verify_versions(const Objlist *objlist)
5369 Objlist_Entry *entry;
5373 STAILQ_FOREACH(entry, objlist, link) {
5375 * Skip dummy objects or objects that have their version requirements
5378 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
5380 if (rtld_verify_object_versions(entry->obj) == -1) {
5382 if (ld_tracing == NULL)
5386 if (rc == 0 || ld_tracing != NULL)
5387 rc = rtld_verify_object_versions(&obj_rtld);
5392 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
5397 vernum = VER_NDX(obj->versyms[symnum]);
5398 if (vernum >= obj->vernum) {
5399 _rtld_error("%s: symbol %s has wrong verneed value %d",
5400 obj->path, obj->strtab + symnum, vernum);
5401 } else if (obj->vertab[vernum].hash != 0) {
5402 return &obj->vertab[vernum];
5409 _rtld_get_stack_prot(void)
5412 return (stack_prot);
5416 _rtld_is_dlopened(void *arg)
5419 RtldLockState lockstate;
5422 rlock_acquire(rtld_bind_lock, &lockstate);
5425 obj = obj_from_addr(arg);
5427 _rtld_error("No shared object contains address");
5428 lock_release(rtld_bind_lock, &lockstate);
5431 res = obj->dlopened ? 1 : 0;
5432 lock_release(rtld_bind_lock, &lockstate);
5437 obj_remap_relro(Obj_Entry *obj, int prot)
5440 if (obj->relro_size > 0 && mprotect(obj->relro_page, obj->relro_size,
5442 _rtld_error("%s: Cannot set relro protection to %#x: %s",
5443 obj->path, prot, rtld_strerror(errno));
5450 obj_disable_relro(Obj_Entry *obj)
5453 return (obj_remap_relro(obj, PROT_READ | PROT_WRITE));
5457 obj_enforce_relro(Obj_Entry *obj)
5460 return (obj_remap_relro(obj, PROT_READ));
5464 map_stacks_exec(RtldLockState *lockstate)
5466 void (*thr_map_stacks_exec)(void);
5468 if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
5470 thr_map_stacks_exec = (void (*)(void))(uintptr_t)
5471 get_program_var_addr("__pthread_map_stacks_exec", lockstate);
5472 if (thr_map_stacks_exec != NULL) {
5473 stack_prot |= PROT_EXEC;
5474 thr_map_stacks_exec();
5479 distribute_static_tls(Objlist *list, RtldLockState *lockstate)
5483 void (*distrib)(size_t, void *, size_t, size_t);
5485 distrib = (void (*)(size_t, void *, size_t, size_t))(uintptr_t)
5486 get_program_var_addr("__pthread_distribute_static_tls", lockstate);
5487 if (distrib == NULL)
5489 STAILQ_FOREACH(elm, list, link) {
5491 if (obj->marker || !obj->tls_done || obj->static_tls_copied)
5493 distrib(obj->tlsoffset, obj->tlsinit, obj->tlsinitsize,
5495 obj->static_tls_copied = true;
5500 symlook_init(SymLook *dst, const char *name)
5503 bzero(dst, sizeof(*dst));
5505 dst->hash = elf_hash(name);
5506 dst->hash_gnu = gnu_hash(name);
5510 symlook_init_from_req(SymLook *dst, const SymLook *src)
5513 dst->name = src->name;
5514 dst->hash = src->hash;
5515 dst->hash_gnu = src->hash_gnu;
5516 dst->ventry = src->ventry;
5517 dst->flags = src->flags;
5518 dst->defobj_out = NULL;
5519 dst->sym_out = NULL;
5520 dst->lockstate = src->lockstate;
5524 open_binary_fd(const char *argv0, bool search_in_path,
5525 const char **binpath_res)
5527 char *binpath, *pathenv, *pe, *res1;
5533 if (search_in_path && strchr(argv0, '/') == NULL) {
5534 binpath = xmalloc(PATH_MAX);
5535 pathenv = getenv("PATH");
5536 if (pathenv == NULL) {
5537 _rtld_error("-p and no PATH environment variable");
5540 pathenv = strdup(pathenv);
5541 if (pathenv == NULL) {
5542 _rtld_error("Cannot allocate memory");
5547 while ((pe = strsep(&pathenv, ":")) != NULL) {
5548 if (strlcpy(binpath, pe, PATH_MAX) >= PATH_MAX)
5550 if (binpath[0] != '\0' &&
5551 strlcat(binpath, "/", PATH_MAX) >= PATH_MAX)
5553 if (strlcat(binpath, argv0, PATH_MAX) >= PATH_MAX)
5555 fd = open(binpath, O_RDONLY | O_CLOEXEC | O_VERIFY);
5556 if (fd != -1 || errno != ENOENT) {
5563 fd = open(argv0, O_RDONLY | O_CLOEXEC | O_VERIFY);
5568 _rtld_error("Cannot open %s: %s", argv0, rtld_strerror(errno));
5571 if (res != NULL && res[0] != '/') {
5572 res1 = xmalloc(PATH_MAX);
5573 if (realpath(res, res1) != NULL) {
5575 free(__DECONST(char *, res));
5586 * Parse a set of command-line arguments.
5589 parse_args(char* argv[], int argc, bool *use_pathp, int *fdp)
5592 int fd, i, j, arglen;
5595 dbg("Parsing command-line arguments");
5599 for (i = 1; i < argc; i++ ) {
5601 dbg("argv[%d]: '%s'", i, arg);
5604 * rtld arguments end with an explicit "--" or with the first
5605 * non-prefixed argument.
5607 if (strcmp(arg, "--") == 0) {
5615 * All other arguments are single-character options that can
5616 * be combined, so we need to search through `arg` for them.
5618 arglen = strlen(arg);
5619 for (j = 1; j < arglen; j++) {
5622 print_usage(argv[0]);
5624 } else if (opt == 'f') {
5626 * -f XX can be used to specify a descriptor for the
5627 * binary named at the command line (i.e., the later
5628 * argument will specify the process name but the
5629 * descriptor is what will actually be executed)
5631 if (j != arglen - 1) {
5632 /* -f must be the last option in, e.g., -abcf */
5633 _rtld_error("Invalid options: %s", arg);
5637 fd = parse_integer(argv[i]);
5639 _rtld_error("Invalid file descriptor: '%s'",
5645 } else if (opt == 'p') {
5648 _rtld_error("Invalid argument: '%s'", arg);
5649 print_usage(argv[0]);
5659 * Parse a file descriptor number without pulling in more of libc (e.g. atoi).
5662 parse_integer(const char *str)
5664 static const int RADIX = 10; /* XXXJA: possibly support hex? */
5671 for (c = *str; c != '\0'; c = *++str) {
5672 if (c < '0' || c > '9')
5679 /* Make sure we actually parsed something. */
5686 print_usage(const char *argv0)
5689 rtld_printf("Usage: %s [-h] [-f <FD>] [--] <binary> [<args>]\n"
5692 " -h Display this help message\n"
5693 " -p Search in PATH for named binary\n"
5694 " -f <FD> Execute <FD> instead of searching for <binary>\n"
5695 " -- End of RTLD options\n"
5696 " <binary> Name of process to execute\n"
5697 " <args> Arguments to the executed process\n", argv0);
5701 * Overrides for libc_pic-provided functions.
5705 __getosreldate(void)
5715 oid[1] = KERN_OSRELDATE;
5717 len = sizeof(osrel);
5718 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
5719 if (error == 0 && osrel > 0 && len == sizeof(osrel))
5724 rtld_strerror(int errnum)
5727 if (errnum < 0 || errnum >= sys_nerr)
5728 return ("Unknown error");
5729 return (sys_errlist[errnum]);
5734 malloc(size_t nbytes)
5737 return (__crt_malloc(nbytes));
5741 calloc(size_t num, size_t size)
5744 return (__crt_calloc(num, size));
5755 realloc(void *cp, size_t nbytes)
5758 return (__crt_realloc(cp, nbytes));