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 void digest_dynamic2(Obj_Entry *, const Elf_Dyn *, const Elf_Dyn *,
93 static void 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 static int parse_args(char* argv[], int argc, bool *use_pathp, int *fdp);
139 static int parse_integer(const char *);
140 static void *path_enumerate(const char *, path_enum_proc, const char *, void *);
141 static void print_usage(const char *argv0);
142 static void release_object(Obj_Entry *);
143 static int relocate_object_dag(Obj_Entry *root, bool bind_now,
144 Obj_Entry *rtldobj, int flags, RtldLockState *lockstate);
145 static int relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
146 int flags, RtldLockState *lockstate);
147 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, int,
149 static int resolve_object_ifunc(Obj_Entry *, bool, int, RtldLockState *);
150 static int rtld_dirname(const char *, char *);
151 static int rtld_dirname_abs(const char *, char *);
152 static void *rtld_dlopen(const char *name, int fd, int mode);
153 static void rtld_exit(void);
154 static void rtld_nop_exit(void);
155 static char *search_library_path(const char *, const char *, const char *,
157 static char *search_library_pathfds(const char *, const char *, int *);
158 static const void **get_program_var_addr(const char *, RtldLockState *);
159 static void set_program_var(const char *, const void *);
160 static int symlook_default(SymLook *, const Obj_Entry *refobj);
161 static int symlook_global(SymLook *, DoneList *);
162 static void symlook_init_from_req(SymLook *, const SymLook *);
163 static int symlook_list(SymLook *, const Objlist *, DoneList *);
164 static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *);
165 static int symlook_obj1_sysv(SymLook *, const Obj_Entry *);
166 static int symlook_obj1_gnu(SymLook *, const Obj_Entry *);
167 static void trace_loaded_objects(Obj_Entry *);
168 static void unlink_object(Obj_Entry *);
169 static void unload_object(Obj_Entry *, RtldLockState *lockstate);
170 static void unref_dag(Obj_Entry *);
171 static void ref_dag(Obj_Entry *);
172 static char *origin_subst_one(Obj_Entry *, char *, const char *,
174 static char *origin_subst(Obj_Entry *, const char *);
175 static bool obj_resolve_origin(Obj_Entry *obj);
176 static void preinit_main(void);
177 static int rtld_verify_versions(const Objlist *);
178 static int rtld_verify_object_versions(Obj_Entry *);
179 static void object_add_name(Obj_Entry *, const char *);
180 static int object_match_name(const Obj_Entry *, const char *);
181 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
182 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
183 struct dl_phdr_info *phdr_info);
184 static uint32_t gnu_hash(const char *);
185 static bool matched_symbol(SymLook *, const Obj_Entry *, Sym_Match_Result *,
186 const unsigned long);
188 void r_debug_state(struct r_debug *, struct link_map *) __noinline __exported;
189 void _r_debug_postinit(struct link_map *) __noinline __exported;
191 int __sys_openat(int, const char *, int, ...);
196 static char *error_message; /* Message for dlerror(), or NULL */
197 struct r_debug r_debug __exported; /* for GDB; */
198 static bool libmap_disable; /* Disable libmap */
199 static bool ld_loadfltr; /* Immediate filters processing */
200 static char *libmap_override; /* Maps to use in addition to libmap.conf */
201 static bool trust; /* False for setuid and setgid programs */
202 static bool dangerous_ld_env; /* True if environment variables have been
203 used to affect the libraries loaded */
204 bool ld_bind_not; /* Disable PLT update */
205 static char *ld_bind_now; /* Environment variable for immediate binding */
206 static char *ld_debug; /* Environment variable for debugging */
207 static char *ld_library_path; /* Environment variable for search path */
208 static char *ld_library_dirs; /* Environment variable for library descriptors */
209 static char *ld_preload; /* Environment variable for libraries to
211 static const char *ld_elf_hints_path; /* Environment variable for alternative hints path */
212 static const char *ld_tracing; /* Called from ldd to print libs */
213 static char *ld_utrace; /* Use utrace() to log events. */
214 static struct obj_entry_q obj_list; /* Queue of all loaded objects */
215 static Obj_Entry *obj_main; /* The main program shared object */
216 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
217 static unsigned int obj_count; /* Number of objects in obj_list */
218 static unsigned int obj_loads; /* Number of loads of objects (gen count) */
220 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
221 STAILQ_HEAD_INITIALIZER(list_global);
222 static Objlist list_main = /* Objects loaded at program startup */
223 STAILQ_HEAD_INITIALIZER(list_main);
224 static Objlist list_fini = /* Objects needing fini() calls */
225 STAILQ_HEAD_INITIALIZER(list_fini);
227 Elf_Sym sym_zero; /* For resolving undefined weak refs. */
229 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
231 extern Elf_Dyn _DYNAMIC;
232 #pragma weak _DYNAMIC
234 int dlclose(void *) __exported;
235 char *dlerror(void) __exported;
236 void *dlopen(const char *, int) __exported;
237 void *fdlopen(int, int) __exported;
238 void *dlsym(void *, const char *) __exported;
239 dlfunc_t dlfunc(void *, const char *) __exported;
240 void *dlvsym(void *, const char *, const char *) __exported;
241 int dladdr(const void *, Dl_info *) __exported;
242 void dllockinit(void *, void *(*)(void *), void (*)(void *), void (*)(void *),
243 void (*)(void *), void (*)(void *), void (*)(void *)) __exported;
244 int dlinfo(void *, int , void *) __exported;
245 int dl_iterate_phdr(__dl_iterate_hdr_callback, void *) __exported;
246 int _rtld_addr_phdr(const void *, struct dl_phdr_info *) __exported;
247 int _rtld_get_stack_prot(void) __exported;
248 int _rtld_is_dlopened(void *) __exported;
249 void _rtld_error(const char *, ...) __exported;
251 /* Only here to fix -Wmissing-prototypes warnings */
252 int __getosreldate(void);
253 func_ptr_type _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp);
254 Elf_Addr _rtld_bind(Obj_Entry *obj, Elf_Size reloff);
258 static int osreldate;
261 static int stack_prot = PROT_READ | PROT_WRITE | RTLD_DEFAULT_STACK_EXEC;
262 static int max_stack_flags;
265 * Global declarations normally provided by crt1. The dynamic linker is
266 * not built with crt1, so we have to provide them ourselves.
272 * Used to pass argc, argv to init functions.
278 * Globals to control TLS allocation.
280 size_t tls_last_offset; /* Static TLS offset of last module */
281 size_t tls_last_size; /* Static TLS size of last module */
282 size_t tls_static_space; /* Static TLS space allocated */
283 static size_t tls_static_max_align;
284 Elf_Addr tls_dtv_generation = 1; /* Used to detect when dtv size changes */
285 int tls_max_index = 1; /* Largest module index allocated */
287 static bool ld_library_path_rpath = false;
290 * Globals for path names, and such
292 const char *ld_elf_hints_default = _PATH_ELF_HINTS;
293 const char *ld_path_libmap_conf = _PATH_LIBMAP_CONF;
294 const char *ld_path_rtld = _PATH_RTLD;
295 const char *ld_standard_library_path = STANDARD_LIBRARY_PATH;
296 const char *ld_env_prefix = LD_;
298 static void (*rtld_exit_ptr)(void);
301 * Fill in a DoneList with an allocation large enough to hold all of
302 * the currently-loaded objects. Keep this as a macro since it calls
303 * alloca and we want that to occur within the scope of the caller.
305 #define donelist_init(dlp) \
306 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
307 assert((dlp)->objs != NULL), \
308 (dlp)->num_alloc = obj_count, \
311 #define LD_UTRACE(e, h, mb, ms, r, n) do { \
312 if (ld_utrace != NULL) \
313 ld_utrace_log(e, h, mb, ms, r, n); \
317 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
318 int refcnt, const char *name)
320 struct utrace_rtld ut;
321 static const char rtld_utrace_sig[RTLD_UTRACE_SIG_SZ] = RTLD_UTRACE_SIG;
323 memcpy(ut.sig, rtld_utrace_sig, sizeof(ut.sig));
326 ut.mapbase = mapbase;
327 ut.mapsize = mapsize;
329 bzero(ut.name, sizeof(ut.name));
331 strlcpy(ut.name, name, sizeof(ut.name));
332 utrace(&ut, sizeof(ut));
335 #ifdef RTLD_VARIANT_ENV_NAMES
337 * construct the env variable based on the type of binary that's
340 static inline const char *
343 static char buffer[128];
345 strlcpy(buffer, ld_env_prefix, sizeof(buffer));
346 strlcat(buffer, var, sizeof(buffer));
354 * Main entry point for dynamic linking. The first argument is the
355 * stack pointer. The stack is expected to be laid out as described
356 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
357 * Specifically, the stack pointer points to a word containing
358 * ARGC. Following that in the stack is a null-terminated sequence
359 * of pointers to argument strings. Then comes a null-terminated
360 * sequence of pointers to environment strings. Finally, there is a
361 * sequence of "auxiliary vector" entries.
363 * The second argument points to a place to store the dynamic linker's
364 * exit procedure pointer and the third to a place to store the main
367 * The return value is the main program's entry point.
370 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
372 Elf_Auxinfo *aux, *auxp, *auxpf, *aux_info[AT_COUNT];
373 Objlist_Entry *entry;
374 Obj_Entry *last_interposer, *obj, *preload_tail;
375 const Elf_Phdr *phdr;
377 RtldLockState lockstate;
380 char **argv, **env, **envp, *kexecpath, *library_path_rpath;
383 char buf[MAXPATHLEN];
384 int argc, fd, i, phnum, rtld_argc;
385 bool dir_enable, explicit_fd, search_in_path;
388 * On entry, the dynamic linker itself has not been relocated yet.
389 * Be very careful not to reference any global data until after
390 * init_rtld has returned. It is OK to reference file-scope statics
391 * and string constants, and to call static and global functions.
394 /* Find the auxiliary vector on the stack. */
398 sp += argc + 1; /* Skip over arguments and NULL terminator */
400 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
402 aux = (Elf_Auxinfo *) sp;
404 /* Digest the auxiliary vector. */
405 for (i = 0; i < AT_COUNT; i++)
407 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
408 if (auxp->a_type < AT_COUNT)
409 aux_info[auxp->a_type] = auxp;
412 /* Initialize and relocate ourselves. */
413 assert(aux_info[AT_BASE] != NULL);
414 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
416 __progname = obj_rtld.path;
417 argv0 = argv[0] != NULL ? argv[0] : "(null)";
422 trust = !issetugid();
424 md_abi_variant_hook(aux_info);
427 if (aux_info[AT_EXECFD] != NULL) {
428 fd = aux_info[AT_EXECFD]->a_un.a_val;
430 assert(aux_info[AT_PHDR] != NULL);
431 phdr = (const Elf_Phdr *)aux_info[AT_PHDR]->a_un.a_ptr;
432 if (phdr == obj_rtld.phdr) {
434 _rtld_error("Tainted process refusing to run binary %s",
438 dbg("opening main program in direct exec mode");
440 rtld_argc = parse_args(argv, argc, &search_in_path, &fd);
441 argv0 = argv[rtld_argc];
442 explicit_fd = (fd != -1);
444 fd = open_binary_fd(argv0, search_in_path);
445 if (fstat(fd, &st) == -1) {
446 _rtld_error("Failed to fstat FD %d (%s): %s", fd,
447 explicit_fd ? "user-provided descriptor" : argv0,
448 rtld_strerror(errno));
453 * Rough emulation of the permission checks done by
454 * execve(2), only Unix DACs are checked, ACLs are
455 * ignored. Preserve the semantic of disabling owner
456 * to execute if owner x bit is cleared, even if
457 * others x bit is enabled.
458 * mmap(2) does not allow to mmap with PROT_EXEC if
459 * binary' file comes from noexec mount. We cannot
460 * set a text reference on the binary.
463 if (st.st_uid == geteuid()) {
464 if ((st.st_mode & S_IXUSR) != 0)
466 } else if (st.st_gid == getegid()) {
467 if ((st.st_mode & S_IXGRP) != 0)
469 } else if ((st.st_mode & S_IXOTH) != 0) {
473 _rtld_error("No execute permission for binary %s",
479 * For direct exec mode, argv[0] is the interpreter
480 * name, we must remove it and shift arguments left
481 * before invoking binary main. Since stack layout
482 * places environment pointers and aux vectors right
483 * after the terminating NULL, we must shift
484 * environment and aux as well.
486 main_argc = argc - rtld_argc;
487 for (i = 0; i <= main_argc; i++)
488 argv[i] = argv[i + rtld_argc];
490 environ = env = envp = argv + main_argc + 1;
492 *envp = *(envp + rtld_argc);
494 } while (*envp != NULL);
495 aux = auxp = (Elf_Auxinfo *)envp;
496 auxpf = (Elf_Auxinfo *)(envp + rtld_argc);
497 for (;; auxp++, auxpf++) {
499 if (auxp->a_type == AT_NULL)
503 _rtld_error("No binary");
509 ld_bind_now = getenv(_LD("BIND_NOW"));
512 * If the process is tainted, then we un-set the dangerous environment
513 * variables. The process will be marked as tainted until setuid(2)
514 * is called. If any child process calls setuid(2) we do not want any
515 * future processes to honor the potentially un-safe variables.
518 if (unsetenv(_LD("PRELOAD")) || unsetenv(_LD("LIBMAP")) ||
519 unsetenv(_LD("LIBRARY_PATH")) || unsetenv(_LD("LIBRARY_PATH_FDS")) ||
520 unsetenv(_LD("LIBMAP_DISABLE")) || unsetenv(_LD("BIND_NOT")) ||
521 unsetenv(_LD("DEBUG")) || unsetenv(_LD("ELF_HINTS_PATH")) ||
522 unsetenv(_LD("LOADFLTR")) || unsetenv(_LD("LIBRARY_PATH_RPATH"))) {
523 _rtld_error("environment corrupt; aborting");
527 ld_debug = getenv(_LD("DEBUG"));
528 if (ld_bind_now == NULL)
529 ld_bind_not = getenv(_LD("BIND_NOT")) != NULL;
530 libmap_disable = getenv(_LD("LIBMAP_DISABLE")) != NULL;
531 libmap_override = getenv(_LD("LIBMAP"));
532 ld_library_path = getenv(_LD("LIBRARY_PATH"));
533 ld_library_dirs = getenv(_LD("LIBRARY_PATH_FDS"));
534 ld_preload = getenv(_LD("PRELOAD"));
535 ld_elf_hints_path = getenv(_LD("ELF_HINTS_PATH"));
536 ld_loadfltr = getenv(_LD("LOADFLTR")) != NULL;
537 library_path_rpath = getenv(_LD("LIBRARY_PATH_RPATH"));
538 if (library_path_rpath != NULL) {
539 if (library_path_rpath[0] == 'y' ||
540 library_path_rpath[0] == 'Y' ||
541 library_path_rpath[0] == '1')
542 ld_library_path_rpath = true;
544 ld_library_path_rpath = false;
546 dangerous_ld_env = libmap_disable || (libmap_override != NULL) ||
547 (ld_library_path != NULL) || (ld_preload != NULL) ||
548 (ld_elf_hints_path != NULL) || ld_loadfltr;
549 ld_tracing = getenv(_LD("TRACE_LOADED_OBJECTS"));
550 ld_utrace = getenv(_LD("UTRACE"));
552 if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0)
553 ld_elf_hints_path = ld_elf_hints_default;
555 if (ld_debug != NULL && *ld_debug != '\0')
557 dbg("%s is initialized, base address = %p", __progname,
558 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
559 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
560 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
562 dbg("initializing thread locks");
566 * Load the main program, or process its program header if it is
569 if (fd != -1) { /* Load the main program. */
570 dbg("loading main program");
571 obj_main = map_object(fd, argv0, NULL);
573 if (obj_main == NULL)
575 max_stack_flags = obj_main->stack_flags;
576 } else { /* Main program already loaded. */
577 dbg("processing main program's program header");
578 assert(aux_info[AT_PHDR] != NULL);
579 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
580 assert(aux_info[AT_PHNUM] != NULL);
581 phnum = aux_info[AT_PHNUM]->a_un.a_val;
582 assert(aux_info[AT_PHENT] != NULL);
583 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
584 assert(aux_info[AT_ENTRY] != NULL);
585 imgentry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
586 if ((obj_main = digest_phdr(phdr, phnum, imgentry, argv0)) == NULL)
590 if (aux_info[AT_EXECPATH] != NULL && fd == -1) {
591 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
592 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
593 if (kexecpath[0] == '/')
594 obj_main->path = kexecpath;
595 else if (getcwd(buf, sizeof(buf)) == NULL ||
596 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
597 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
598 obj_main->path = xstrdup(argv0);
600 obj_main->path = xstrdup(buf);
602 dbg("No AT_EXECPATH or direct exec");
603 obj_main->path = xstrdup(argv0);
605 dbg("obj_main path %s", obj_main->path);
606 obj_main->mainprog = true;
608 if (aux_info[AT_STACKPROT] != NULL &&
609 aux_info[AT_STACKPROT]->a_un.a_val != 0)
610 stack_prot = aux_info[AT_STACKPROT]->a_un.a_val;
614 * Get the actual dynamic linker pathname from the executable if
615 * possible. (It should always be possible.) That ensures that
616 * gdb will find the right dynamic linker even if a non-standard
619 if (obj_main->interp != NULL &&
620 strcmp(obj_main->interp, obj_rtld.path) != 0) {
622 obj_rtld.path = xstrdup(obj_main->interp);
623 __progname = obj_rtld.path;
627 digest_dynamic(obj_main, 0);
628 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d",
629 obj_main->path, obj_main->valid_hash_sysv, obj_main->valid_hash_gnu,
630 obj_main->dynsymcount);
632 linkmap_add(obj_main);
633 linkmap_add(&obj_rtld);
635 /* Link the main program into the list of objects. */
636 TAILQ_INSERT_HEAD(&obj_list, obj_main, next);
640 /* Initialize a fake symbol for resolving undefined weak references. */
641 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
642 sym_zero.st_shndx = SHN_UNDEF;
643 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
646 libmap_disable = (bool)lm_init(libmap_override);
648 dbg("loading LD_PRELOAD libraries");
649 if (load_preload_objects() == -1)
651 preload_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
653 dbg("loading needed objects");
654 if (load_needed_objects(obj_main, 0) == -1)
657 /* Make a list of all objects loaded at startup. */
658 last_interposer = obj_main;
659 TAILQ_FOREACH(obj, &obj_list, next) {
662 if (obj->z_interpose && obj != obj_main) {
663 objlist_put_after(&list_main, last_interposer, obj);
664 last_interposer = obj;
666 objlist_push_tail(&list_main, obj);
671 dbg("checking for required versions");
672 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
675 if (ld_tracing) { /* We're done */
676 trace_loaded_objects(obj_main);
680 if (getenv(_LD("DUMP_REL_PRE")) != NULL) {
681 dump_relocations(obj_main);
686 * Processing tls relocations requires having the tls offsets
687 * initialized. Prepare offsets before starting initial
688 * relocation processing.
690 dbg("initializing initial thread local storage offsets");
691 STAILQ_FOREACH(entry, &list_main, link) {
693 * Allocate all the initial objects out of the static TLS
694 * block even if they didn't ask for it.
696 allocate_tls_offset(entry->obj);
699 if (relocate_objects(obj_main,
700 ld_bind_now != NULL && *ld_bind_now != '\0',
701 &obj_rtld, SYMLOOK_EARLY, NULL) == -1)
704 dbg("doing copy relocations");
705 if (do_copy_relocations(obj_main) == -1)
708 if (getenv(_LD("DUMP_REL_POST")) != NULL) {
709 dump_relocations(obj_main);
716 * Setup TLS for main thread. This must be done after the
717 * relocations are processed, since tls initialization section
718 * might be the subject for relocations.
720 dbg("initializing initial thread local storage");
721 allocate_initial_tls(globallist_curr(TAILQ_FIRST(&obj_list)));
723 dbg("initializing key program variables");
724 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
725 set_program_var("environ", env);
726 set_program_var("__elf_aux_vector", aux);
728 /* Make a list of init functions to call. */
729 objlist_init(&initlist);
730 initlist_add_objects(globallist_curr(TAILQ_FIRST(&obj_list)),
731 preload_tail, &initlist);
733 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
735 map_stacks_exec(NULL);
737 if (!obj_main->crt_no_init) {
739 * Make sure we don't call the main program's init and fini
740 * functions for binaries linked with old crt1 which calls
743 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
744 obj_main->preinit_array = obj_main->init_array =
745 obj_main->fini_array = (Elf_Addr)NULL;
749 * Execute MD initializers required before we call the objects'
754 wlock_acquire(rtld_bind_lock, &lockstate);
756 dbg("resolving ifuncs");
757 if (initlist_objects_ifunc(&initlist, ld_bind_now != NULL &&
758 *ld_bind_now != '\0', SYMLOOK_EARLY, &lockstate) == -1)
761 rtld_exit_ptr = rtld_exit;
762 if (obj_main->crt_no_init)
764 objlist_call_init(&initlist, &lockstate);
765 _r_debug_postinit(&obj_main->linkmap);
766 objlist_clear(&initlist);
767 dbg("loading filtees");
768 TAILQ_FOREACH(obj, &obj_list, next) {
771 if (ld_loadfltr || obj->z_loadfltr)
772 load_filtees(obj, 0, &lockstate);
775 dbg("enforcing main obj relro");
776 if (obj_enforce_relro(obj_main) == -1)
779 lock_release(rtld_bind_lock, &lockstate);
781 dbg("transferring control to program entry point = %p", obj_main->entry);
783 /* Return the exit procedure and the program entry point. */
784 *exit_proc = rtld_exit_ptr;
786 return (func_ptr_type) obj_main->entry;
790 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def)
795 ptr = (void *)make_function_pointer(def, obj);
796 target = call_ifunc_resolver(ptr);
797 return ((void *)target);
801 * NB: MIPS uses a private version of this function (_mips_rtld_bind).
802 * Changes to this function should be applied there as well.
805 _rtld_bind(Obj_Entry *obj, Elf_Size reloff)
809 const Obj_Entry *defobj;
812 RtldLockState lockstate;
814 rlock_acquire(rtld_bind_lock, &lockstate);
815 if (sigsetjmp(lockstate.env, 0) != 0)
816 lock_upgrade(rtld_bind_lock, &lockstate);
818 rel = (const Elf_Rel *)((const char *)obj->pltrel + reloff);
820 rel = (const Elf_Rel *)((const char *)obj->pltrela + reloff);
822 where = (Elf_Addr *)(obj->relocbase + rel->r_offset);
823 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, SYMLOOK_IN_PLT,
827 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
828 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
830 target = (Elf_Addr)(defobj->relocbase + def->st_value);
832 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
833 defobj->strtab + def->st_name, basename(obj->path),
834 (void *)target, basename(defobj->path));
837 * Write the new contents for the jmpslot. Note that depending on
838 * architecture, the value which we need to return back to the
839 * lazy binding trampoline may or may not be the target
840 * address. The value returned from reloc_jmpslot() is the value
841 * that the trampoline needs.
843 target = reloc_jmpslot(where, target, defobj, obj, rel);
844 lock_release(rtld_bind_lock, &lockstate);
849 * Error reporting function. Use it like printf. If formats the message
850 * into a buffer, and sets things up so that the next call to dlerror()
851 * will return the message.
854 _rtld_error(const char *fmt, ...)
856 static char buf[512];
860 rtld_vsnprintf(buf, sizeof buf, fmt, ap);
863 LD_UTRACE(UTRACE_RTLD_ERROR, NULL, NULL, 0, 0, error_message);
867 * Return a dynamically-allocated copy of the current error message, if any.
872 return error_message == NULL ? NULL : xstrdup(error_message);
876 * Restore the current error message from a copy which was previously saved
877 * by errmsg_save(). The copy is freed.
880 errmsg_restore(char *saved_msg)
882 if (saved_msg == NULL)
883 error_message = NULL;
885 _rtld_error("%s", saved_msg);
891 basename(const char *name)
893 const char *p = strrchr(name, '/');
894 return p != NULL ? p + 1 : name;
897 static struct utsname uts;
900 origin_subst_one(Obj_Entry *obj, char *real, const char *kw,
901 const char *subst, bool may_free)
903 char *p, *p1, *res, *resp;
904 int subst_len, kw_len, subst_count, old_len, new_len;
909 * First, count the number of the keyword occurrences, to
910 * preallocate the final string.
912 for (p = real, subst_count = 0;; p = p1 + kw_len, subst_count++) {
919 * If the keyword is not found, just return.
921 * Return non-substituted string if resolution failed. We
922 * cannot do anything more reasonable, the failure mode of the
923 * caller is unresolved library anyway.
925 if (subst_count == 0 || (obj != NULL && !obj_resolve_origin(obj)))
926 return (may_free ? real : xstrdup(real));
928 subst = obj->origin_path;
931 * There is indeed something to substitute. Calculate the
932 * length of the resulting string, and allocate it.
934 subst_len = strlen(subst);
935 old_len = strlen(real);
936 new_len = old_len + (subst_len - kw_len) * subst_count;
937 res = xmalloc(new_len + 1);
940 * Now, execute the substitution loop.
942 for (p = real, resp = res, *resp = '\0';;) {
945 /* Copy the prefix before keyword. */
946 memcpy(resp, p, p1 - p);
948 /* Keyword replacement. */
949 memcpy(resp, subst, subst_len);
957 /* Copy to the end of string and finish. */
965 origin_subst(Obj_Entry *obj, const char *real)
967 char *res1, *res2, *res3, *res4;
969 if (obj == NULL || !trust)
970 return (xstrdup(real));
971 if (uts.sysname[0] == '\0') {
972 if (uname(&uts) != 0) {
973 _rtld_error("utsname failed: %d", errno);
977 /* __DECONST is safe here since without may_free real is unchanged */
978 res1 = origin_subst_one(obj, __DECONST(char *, real), "$ORIGIN", NULL,
980 res2 = origin_subst_one(NULL, res1, "$OSNAME", uts.sysname, true);
981 res3 = origin_subst_one(NULL, res2, "$OSREL", uts.release, true);
982 res4 = origin_subst_one(NULL, res3, "$PLATFORM", uts.machine, true);
989 const char *msg = dlerror();
993 rtld_fdputstr(STDERR_FILENO, _BASENAME_RTLD ": ");
994 rtld_fdputstr(STDERR_FILENO, msg);
995 rtld_fdputchar(STDERR_FILENO, '\n');
1000 * Process a shared object's DYNAMIC section, and save the important
1001 * information in its Obj_Entry structure.
1004 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
1005 const Elf_Dyn **dyn_soname, const Elf_Dyn **dyn_runpath)
1007 const Elf_Dyn *dynp;
1008 Needed_Entry **needed_tail = &obj->needed;
1009 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
1010 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
1011 const Elf_Hashelt *hashtab;
1012 const Elf32_Word *hashval;
1013 Elf32_Word bkt, nmaskwords;
1015 int plttype = DT_REL;
1019 *dyn_runpath = NULL;
1021 obj->bind_now = false;
1022 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
1023 switch (dynp->d_tag) {
1026 obj->rel = (const Elf_Rel *)(obj->relocbase + dynp->d_un.d_ptr);
1030 obj->relsize = dynp->d_un.d_val;
1034 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
1038 obj->pltrel = (const Elf_Rel *)
1039 (obj->relocbase + dynp->d_un.d_ptr);
1043 obj->pltrelsize = dynp->d_un.d_val;
1047 obj->rela = (const Elf_Rela *)(obj->relocbase + dynp->d_un.d_ptr);
1051 obj->relasize = dynp->d_un.d_val;
1055 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
1059 plttype = dynp->d_un.d_val;
1060 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
1064 obj->symtab = (const Elf_Sym *)
1065 (obj->relocbase + dynp->d_un.d_ptr);
1069 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
1073 obj->strtab = (const char *)(obj->relocbase + dynp->d_un.d_ptr);
1077 obj->strsize = dynp->d_un.d_val;
1081 obj->verneed = (const Elf_Verneed *)(obj->relocbase +
1086 obj->verneednum = dynp->d_un.d_val;
1090 obj->verdef = (const Elf_Verdef *)(obj->relocbase +
1095 obj->verdefnum = dynp->d_un.d_val;
1099 obj->versyms = (const Elf_Versym *)(obj->relocbase +
1105 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1107 obj->nbuckets = hashtab[0];
1108 obj->nchains = hashtab[1];
1109 obj->buckets = hashtab + 2;
1110 obj->chains = obj->buckets + obj->nbuckets;
1111 obj->valid_hash_sysv = obj->nbuckets > 0 && obj->nchains > 0 &&
1112 obj->buckets != NULL;
1118 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1120 obj->nbuckets_gnu = hashtab[0];
1121 obj->symndx_gnu = hashtab[1];
1122 nmaskwords = hashtab[2];
1123 bloom_size32 = (__ELF_WORD_SIZE / 32) * nmaskwords;
1124 obj->maskwords_bm_gnu = nmaskwords - 1;
1125 obj->shift2_gnu = hashtab[3];
1126 obj->bloom_gnu = (const Elf_Addr *)(hashtab + 4);
1127 obj->buckets_gnu = hashtab + 4 + bloom_size32;
1128 obj->chain_zero_gnu = obj->buckets_gnu + obj->nbuckets_gnu -
1130 /* Number of bitmask words is required to be power of 2 */
1131 obj->valid_hash_gnu = powerof2(nmaskwords) &&
1132 obj->nbuckets_gnu > 0 && obj->buckets_gnu != NULL;
1138 Needed_Entry *nep = NEW(Needed_Entry);
1139 nep->name = dynp->d_un.d_val;
1144 needed_tail = &nep->next;
1150 Needed_Entry *nep = NEW(Needed_Entry);
1151 nep->name = dynp->d_un.d_val;
1155 *needed_filtees_tail = nep;
1156 needed_filtees_tail = &nep->next;
1162 Needed_Entry *nep = NEW(Needed_Entry);
1163 nep->name = dynp->d_un.d_val;
1167 *needed_aux_filtees_tail = nep;
1168 needed_aux_filtees_tail = &nep->next;
1173 obj->pltgot = (Elf_Addr *)(obj->relocbase + dynp->d_un.d_ptr);
1177 obj->textrel = true;
1181 obj->symbolic = true;
1186 * We have to wait until later to process this, because we
1187 * might not have gotten the address of the string table yet.
1197 *dyn_runpath = dynp;
1201 obj->init = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1204 case DT_PREINIT_ARRAY:
1205 obj->preinit_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1208 case DT_PREINIT_ARRAYSZ:
1209 obj->preinit_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1213 obj->init_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1216 case DT_INIT_ARRAYSZ:
1217 obj->init_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1221 obj->fini = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1225 obj->fini_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1228 case DT_FINI_ARRAYSZ:
1229 obj->fini_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1233 * Don't process DT_DEBUG on MIPS as the dynamic section
1234 * is mapped read-only. DT_MIPS_RLD_MAP is used instead.
1240 dbg("Filling in DT_DEBUG entry");
1241 (__DECONST(Elf_Dyn *, dynp))->d_un.d_ptr = (Elf_Addr)&r_debug;
1246 if (dynp->d_un.d_val & DF_ORIGIN)
1247 obj->z_origin = true;
1248 if (dynp->d_un.d_val & DF_SYMBOLIC)
1249 obj->symbolic = true;
1250 if (dynp->d_un.d_val & DF_TEXTREL)
1251 obj->textrel = true;
1252 if (dynp->d_un.d_val & DF_BIND_NOW)
1253 obj->bind_now = true;
1254 if (dynp->d_un.d_val & DF_STATIC_TLS)
1255 obj->static_tls = true;
1258 case DT_MIPS_LOCAL_GOTNO:
1259 obj->local_gotno = dynp->d_un.d_val;
1262 case DT_MIPS_SYMTABNO:
1263 obj->symtabno = dynp->d_un.d_val;
1266 case DT_MIPS_GOTSYM:
1267 obj->gotsym = dynp->d_un.d_val;
1270 case DT_MIPS_RLD_MAP:
1271 *((Elf_Addr *)(dynp->d_un.d_ptr)) = (Elf_Addr) &r_debug;
1274 case DT_MIPS_RLD_MAP_REL:
1275 // The MIPS_RLD_MAP_REL tag stores the offset to the .rld_map
1276 // section relative to the address of the tag itself.
1277 *((Elf_Addr *)(__DECONST(char*, dynp) + dynp->d_un.d_val)) =
1278 (Elf_Addr) &r_debug;
1281 case DT_MIPS_PLTGOT:
1282 obj->mips_pltgot = (Elf_Addr *)(obj->relocbase +
1289 #ifdef __powerpc64__
1290 case DT_PPC64_GLINK:
1291 obj->glink = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1295 obj->gotptr = (Elf_Addr *)(obj->relocbase + dynp->d_un.d_ptr);
1301 if (dynp->d_un.d_val & DF_1_NOOPEN)
1302 obj->z_noopen = true;
1303 if (dynp->d_un.d_val & DF_1_ORIGIN)
1304 obj->z_origin = true;
1305 if (dynp->d_un.d_val & DF_1_GLOBAL)
1306 obj->z_global = true;
1307 if (dynp->d_un.d_val & DF_1_BIND_NOW)
1308 obj->bind_now = true;
1309 if (dynp->d_un.d_val & DF_1_NODELETE)
1310 obj->z_nodelete = true;
1311 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1312 obj->z_loadfltr = true;
1313 if (dynp->d_un.d_val & DF_1_INTERPOSE)
1314 obj->z_interpose = true;
1315 if (dynp->d_un.d_val & DF_1_NODEFLIB)
1316 obj->z_nodeflib = true;
1321 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1328 obj->traced = false;
1330 if (plttype == DT_RELA) {
1331 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1333 obj->pltrelasize = obj->pltrelsize;
1334 obj->pltrelsize = 0;
1337 /* Determine size of dynsym table (equal to nchains of sysv hash) */
1338 if (obj->valid_hash_sysv)
1339 obj->dynsymcount = obj->nchains;
1340 else if (obj->valid_hash_gnu) {
1341 obj->dynsymcount = 0;
1342 for (bkt = 0; bkt < obj->nbuckets_gnu; bkt++) {
1343 if (obj->buckets_gnu[bkt] == 0)
1345 hashval = &obj->chain_zero_gnu[obj->buckets_gnu[bkt]];
1348 while ((*hashval++ & 1u) == 0);
1350 obj->dynsymcount += obj->symndx_gnu;
1355 obj_resolve_origin(Obj_Entry *obj)
1358 if (obj->origin_path != NULL)
1360 obj->origin_path = xmalloc(PATH_MAX);
1361 return (rtld_dirname_abs(obj->path, obj->origin_path) != -1);
1365 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1366 const Elf_Dyn *dyn_soname, const Elf_Dyn *dyn_runpath)
1369 if (obj->z_origin && !obj_resolve_origin(obj))
1372 if (dyn_runpath != NULL) {
1373 obj->runpath = (const char *)obj->strtab + dyn_runpath->d_un.d_val;
1374 obj->runpath = origin_subst(obj, obj->runpath);
1375 } else if (dyn_rpath != NULL) {
1376 obj->rpath = (const char *)obj->strtab + dyn_rpath->d_un.d_val;
1377 obj->rpath = origin_subst(obj, obj->rpath);
1379 if (dyn_soname != NULL)
1380 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1384 digest_dynamic(Obj_Entry *obj, int early)
1386 const Elf_Dyn *dyn_rpath;
1387 const Elf_Dyn *dyn_soname;
1388 const Elf_Dyn *dyn_runpath;
1390 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname, &dyn_runpath);
1391 digest_dynamic2(obj, dyn_rpath, dyn_soname, dyn_runpath);
1395 * Process a shared object's program header. This is used only for the
1396 * main program, when the kernel has already loaded the main program
1397 * into memory before calling the dynamic linker. It creates and
1398 * returns an Obj_Entry structure.
1401 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1404 const Elf_Phdr *phlimit = phdr + phnum;
1406 Elf_Addr note_start, note_end;
1410 for (ph = phdr; ph < phlimit; ph++) {
1411 if (ph->p_type != PT_PHDR)
1415 obj->phsize = ph->p_memsz;
1416 obj->relocbase = __DECONST(char *, phdr) - ph->p_vaddr;
1420 obj->stack_flags = PF_X | PF_R | PF_W;
1422 for (ph = phdr; ph < phlimit; ph++) {
1423 switch (ph->p_type) {
1426 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1430 if (nsegs == 0) { /* First load segment */
1431 obj->vaddrbase = trunc_page(ph->p_vaddr);
1432 obj->mapbase = obj->vaddrbase + obj->relocbase;
1433 } else { /* Last load segment */
1434 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1441 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1446 obj->tlssize = ph->p_memsz;
1447 obj->tlsalign = ph->p_align;
1448 obj->tlsinitsize = ph->p_filesz;
1449 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1453 obj->stack_flags = ph->p_flags;
1457 obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1458 obj->relro_size = round_page(ph->p_memsz);
1462 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
1463 note_end = note_start + ph->p_filesz;
1464 digest_notes(obj, note_start, note_end);
1469 _rtld_error("%s: too few PT_LOAD segments", path);
1478 digest_notes(Obj_Entry *obj, Elf_Addr note_start, Elf_Addr note_end)
1480 const Elf_Note *note;
1481 const char *note_name;
1484 for (note = (const Elf_Note *)note_start; (Elf_Addr)note < note_end;
1485 note = (const Elf_Note *)((const char *)(note + 1) +
1486 roundup2(note->n_namesz, sizeof(Elf32_Addr)) +
1487 roundup2(note->n_descsz, sizeof(Elf32_Addr)))) {
1488 if (note->n_namesz != sizeof(NOTE_FREEBSD_VENDOR) ||
1489 note->n_descsz != sizeof(int32_t))
1491 if (note->n_type != NT_FREEBSD_ABI_TAG &&
1492 note->n_type != NT_FREEBSD_FEATURE_CTL &&
1493 note->n_type != NT_FREEBSD_NOINIT_TAG)
1495 note_name = (const char *)(note + 1);
1496 if (strncmp(NOTE_FREEBSD_VENDOR, note_name,
1497 sizeof(NOTE_FREEBSD_VENDOR)) != 0)
1499 switch (note->n_type) {
1500 case NT_FREEBSD_ABI_TAG:
1501 /* FreeBSD osrel note */
1502 p = (uintptr_t)(note + 1);
1503 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1504 obj->osrel = *(const int32_t *)(p);
1505 dbg("note osrel %d", obj->osrel);
1507 case NT_FREEBSD_FEATURE_CTL:
1508 /* FreeBSD ABI feature control note */
1509 p = (uintptr_t)(note + 1);
1510 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1511 obj->fctl0 = *(const uint32_t *)(p);
1512 dbg("note fctl0 %#x", obj->fctl0);
1514 case NT_FREEBSD_NOINIT_TAG:
1515 /* FreeBSD 'crt does not call init' note */
1516 obj->crt_no_init = true;
1517 dbg("note crt_no_init");
1524 dlcheck(void *handle)
1528 TAILQ_FOREACH(obj, &obj_list, next) {
1529 if (obj == (Obj_Entry *) handle)
1533 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1534 _rtld_error("Invalid shared object handle %p", handle);
1541 * If the given object is already in the donelist, return true. Otherwise
1542 * add the object to the list and return false.
1545 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1549 for (i = 0; i < dlp->num_used; i++)
1550 if (dlp->objs[i] == obj)
1553 * Our donelist allocation should always be sufficient. But if
1554 * our threads locking isn't working properly, more shared objects
1555 * could have been loaded since we allocated the list. That should
1556 * never happen, but we'll handle it properly just in case it does.
1558 if (dlp->num_used < dlp->num_alloc)
1559 dlp->objs[dlp->num_used++] = obj;
1564 * Hash function for symbol table lookup. Don't even think about changing
1565 * this. It is specified by the System V ABI.
1568 elf_hash(const char *name)
1570 const unsigned char *p = (const unsigned char *) name;
1571 unsigned long h = 0;
1574 while (*p != '\0') {
1575 h = (h << 4) + *p++;
1576 if ((g = h & 0xf0000000) != 0)
1584 * The GNU hash function is the Daniel J. Bernstein hash clipped to 32 bits
1585 * unsigned in case it's implemented with a wider type.
1588 gnu_hash(const char *s)
1594 for (c = *s; c != '\0'; c = *++s)
1596 return (h & 0xffffffff);
1601 * Find the library with the given name, and return its full pathname.
1602 * The returned string is dynamically allocated. Generates an error
1603 * message and returns NULL if the library cannot be found.
1605 * If the second argument is non-NULL, then it refers to an already-
1606 * loaded shared object, whose library search path will be searched.
1608 * If a library is successfully located via LD_LIBRARY_PATH_FDS, its
1609 * descriptor (which is close-on-exec) will be passed out via the third
1612 * The search order is:
1613 * DT_RPATH in the referencing file _unless_ DT_RUNPATH is present (1)
1614 * DT_RPATH of the main object if DSO without defined DT_RUNPATH (1)
1616 * DT_RUNPATH in the referencing file
1617 * ldconfig hints (if -z nodefaultlib, filter out default library directories
1619 * /lib:/usr/lib _unless_ the referencing file is linked with -z nodefaultlib
1621 * (1) Handled in digest_dynamic2 - rpath left NULL if runpath defined.
1624 find_library(const char *xname, const Obj_Entry *refobj, int *fdp)
1626 char *pathname, *refobj_path;
1628 bool nodeflib, objgiven;
1630 objgiven = refobj != NULL;
1632 if (libmap_disable || !objgiven ||
1633 (name = lm_find(refobj->path, xname)) == NULL)
1636 if (strchr(name, '/') != NULL) { /* Hard coded pathname */
1637 if (name[0] != '/' && !trust) {
1638 _rtld_error("Absolute pathname required "
1639 "for shared object \"%s\"", name);
1642 return (origin_subst(__DECONST(Obj_Entry *, refobj),
1643 __DECONST(char *, name)));
1646 dbg(" Searching for \"%s\"", name);
1647 refobj_path = objgiven ? refobj->path : NULL;
1650 * If refobj->rpath != NULL, then refobj->runpath is NULL. Fall
1651 * back to pre-conforming behaviour if user requested so with
1652 * LD_LIBRARY_PATH_RPATH environment variable and ignore -z
1655 if (objgiven && refobj->rpath != NULL && ld_library_path_rpath) {
1656 pathname = search_library_path(name, ld_library_path,
1658 if (pathname != NULL)
1660 if (refobj != NULL) {
1661 pathname = search_library_path(name, refobj->rpath,
1663 if (pathname != NULL)
1666 pathname = search_library_pathfds(name, ld_library_dirs, fdp);
1667 if (pathname != NULL)
1669 pathname = search_library_path(name, gethints(false),
1671 if (pathname != NULL)
1673 pathname = search_library_path(name, ld_standard_library_path,
1675 if (pathname != NULL)
1678 nodeflib = objgiven ? refobj->z_nodeflib : false;
1680 pathname = search_library_path(name, refobj->rpath,
1682 if (pathname != NULL)
1685 if (objgiven && refobj->runpath == NULL && refobj != obj_main) {
1686 pathname = search_library_path(name, obj_main->rpath,
1688 if (pathname != NULL)
1691 pathname = search_library_path(name, ld_library_path,
1693 if (pathname != NULL)
1696 pathname = search_library_path(name, refobj->runpath,
1698 if (pathname != NULL)
1701 pathname = search_library_pathfds(name, ld_library_dirs, fdp);
1702 if (pathname != NULL)
1704 pathname = search_library_path(name, gethints(nodeflib),
1706 if (pathname != NULL)
1708 if (objgiven && !nodeflib) {
1709 pathname = search_library_path(name,
1710 ld_standard_library_path, refobj_path, fdp);
1711 if (pathname != NULL)
1716 if (objgiven && refobj->path != NULL) {
1717 _rtld_error("Shared object \"%s\" not found, "
1718 "required by \"%s\"", name, basename(refobj->path));
1720 _rtld_error("Shared object \"%s\" not found", name);
1726 * Given a symbol number in a referencing object, find the corresponding
1727 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1728 * no definition was found. Returns a pointer to the Obj_Entry of the
1729 * defining object via the reference parameter DEFOBJ_OUT.
1732 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1733 const Obj_Entry **defobj_out, int flags, SymCache *cache,
1734 RtldLockState *lockstate)
1738 const Obj_Entry *defobj;
1739 const Ver_Entry *ve;
1745 * If we have already found this symbol, get the information from
1748 if (symnum >= refobj->dynsymcount)
1749 return NULL; /* Bad object */
1750 if (cache != NULL && cache[symnum].sym != NULL) {
1751 *defobj_out = cache[symnum].obj;
1752 return cache[symnum].sym;
1755 ref = refobj->symtab + symnum;
1756 name = refobj->strtab + ref->st_name;
1762 * We don't have to do a full scale lookup if the symbol is local.
1763 * We know it will bind to the instance in this load module; to
1764 * which we already have a pointer (ie ref). By not doing a lookup,
1765 * we not only improve performance, but it also avoids unresolvable
1766 * symbols when local symbols are not in the hash table. This has
1767 * been seen with the ia64 toolchain.
1769 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1770 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1771 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1774 symlook_init(&req, name);
1776 ve = req.ventry = fetch_ventry(refobj, symnum);
1777 req.lockstate = lockstate;
1778 res = symlook_default(&req, refobj);
1781 defobj = req.defobj_out;
1789 * If we found no definition and the reference is weak, treat the
1790 * symbol as having the value zero.
1792 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1798 *defobj_out = defobj;
1799 /* Record the information in the cache to avoid subsequent lookups. */
1800 if (cache != NULL) {
1801 cache[symnum].sym = def;
1802 cache[symnum].obj = defobj;
1805 if (refobj != &obj_rtld)
1806 _rtld_error("%s: Undefined symbol \"%s%s%s\"", refobj->path, name,
1807 ve != NULL ? "@" : "", ve != NULL ? ve->name : "");
1813 * Return the search path from the ldconfig hints file, reading it if
1814 * necessary. If nostdlib is true, then the default search paths are
1815 * not added to result.
1817 * Returns NULL if there are problems with the hints file,
1818 * or if the search path there is empty.
1821 gethints(bool nostdlib)
1823 static char *filtered_path;
1824 static const char *hints;
1825 static struct elfhints_hdr hdr;
1826 struct fill_search_info_args sargs, hargs;
1827 struct dl_serinfo smeta, hmeta, *SLPinfo, *hintinfo;
1828 struct dl_serpath *SLPpath, *hintpath;
1830 struct stat hint_stat;
1831 unsigned int SLPndx, hintndx, fndx, fcount;
1837 /* First call, read the hints file */
1838 if (hints == NULL) {
1839 /* Keep from trying again in case the hints file is bad. */
1842 if ((fd = open(ld_elf_hints_path, O_RDONLY | O_CLOEXEC)) == -1)
1846 * Check of hdr.dirlistlen value against type limit
1847 * intends to pacify static analyzers. Further
1848 * paranoia leads to checks that dirlist is fully
1849 * contained in the file range.
1851 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1852 hdr.magic != ELFHINTS_MAGIC ||
1853 hdr.version != 1 || hdr.dirlistlen > UINT_MAX / 2 ||
1854 fstat(fd, &hint_stat) == -1) {
1861 if (dl + hdr.dirlist < dl)
1864 if (dl + hdr.dirlistlen < dl)
1866 dl += hdr.dirlistlen;
1867 if (dl > hint_stat.st_size)
1869 p = xmalloc(hdr.dirlistlen + 1);
1870 if (pread(fd, p, hdr.dirlistlen + 1,
1871 hdr.strtab + hdr.dirlist) != (ssize_t)hdr.dirlistlen + 1 ||
1872 p[hdr.dirlistlen] != '\0') {
1881 * If caller agreed to receive list which includes the default
1882 * paths, we are done. Otherwise, if we still did not
1883 * calculated filtered result, do it now.
1886 return (hints[0] != '\0' ? hints : NULL);
1887 if (filtered_path != NULL)
1891 * Obtain the list of all configured search paths, and the
1892 * list of the default paths.
1894 * First estimate the size of the results.
1896 smeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1898 hmeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1901 sargs.request = RTLD_DI_SERINFOSIZE;
1902 sargs.serinfo = &smeta;
1903 hargs.request = RTLD_DI_SERINFOSIZE;
1904 hargs.serinfo = &hmeta;
1906 path_enumerate(ld_standard_library_path, fill_search_info, NULL,
1908 path_enumerate(hints, fill_search_info, NULL, &hargs);
1910 SLPinfo = xmalloc(smeta.dls_size);
1911 hintinfo = xmalloc(hmeta.dls_size);
1914 * Next fetch both sets of paths.
1916 sargs.request = RTLD_DI_SERINFO;
1917 sargs.serinfo = SLPinfo;
1918 sargs.serpath = &SLPinfo->dls_serpath[0];
1919 sargs.strspace = (char *)&SLPinfo->dls_serpath[smeta.dls_cnt];
1921 hargs.request = RTLD_DI_SERINFO;
1922 hargs.serinfo = hintinfo;
1923 hargs.serpath = &hintinfo->dls_serpath[0];
1924 hargs.strspace = (char *)&hintinfo->dls_serpath[hmeta.dls_cnt];
1926 path_enumerate(ld_standard_library_path, fill_search_info, NULL,
1928 path_enumerate(hints, fill_search_info, NULL, &hargs);
1931 * Now calculate the difference between two sets, by excluding
1932 * standard paths from the full set.
1936 filtered_path = xmalloc(hdr.dirlistlen + 1);
1937 hintpath = &hintinfo->dls_serpath[0];
1938 for (hintndx = 0; hintndx < hmeta.dls_cnt; hintndx++, hintpath++) {
1940 SLPpath = &SLPinfo->dls_serpath[0];
1942 * Check each standard path against current.
1944 for (SLPndx = 0; SLPndx < smeta.dls_cnt; SLPndx++, SLPpath++) {
1945 /* matched, skip the path */
1946 if (!strcmp(hintpath->dls_name, SLPpath->dls_name)) {
1954 * Not matched against any standard path, add the path
1955 * to result. Separate consequtive paths with ':'.
1958 filtered_path[fndx] = ':';
1962 flen = strlen(hintpath->dls_name);
1963 strncpy((filtered_path + fndx), hintpath->dls_name, flen);
1966 filtered_path[fndx] = '\0';
1972 return (filtered_path[0] != '\0' ? filtered_path : NULL);
1976 init_dag(Obj_Entry *root)
1978 const Needed_Entry *needed;
1979 const Objlist_Entry *elm;
1982 if (root->dag_inited)
1984 donelist_init(&donelist);
1986 /* Root object belongs to own DAG. */
1987 objlist_push_tail(&root->dldags, root);
1988 objlist_push_tail(&root->dagmembers, root);
1989 donelist_check(&donelist, root);
1992 * Add dependencies of root object to DAG in breadth order
1993 * by exploiting the fact that each new object get added
1994 * to the tail of the dagmembers list.
1996 STAILQ_FOREACH(elm, &root->dagmembers, link) {
1997 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
1998 if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
2000 objlist_push_tail(&needed->obj->dldags, root);
2001 objlist_push_tail(&root->dagmembers, needed->obj);
2004 root->dag_inited = true;
2008 init_marker(Obj_Entry *marker)
2011 bzero(marker, sizeof(*marker));
2012 marker->marker = true;
2016 globallist_curr(const Obj_Entry *obj)
2023 return (__DECONST(Obj_Entry *, obj));
2024 obj = TAILQ_PREV(obj, obj_entry_q, next);
2029 globallist_next(const Obj_Entry *obj)
2033 obj = TAILQ_NEXT(obj, next);
2037 return (__DECONST(Obj_Entry *, obj));
2041 /* Prevent the object from being unmapped while the bind lock is dropped. */
2043 hold_object(Obj_Entry *obj)
2050 unhold_object(Obj_Entry *obj)
2053 assert(obj->holdcount > 0);
2054 if (--obj->holdcount == 0 && obj->unholdfree)
2055 release_object(obj);
2059 process_z(Obj_Entry *root)
2061 const Objlist_Entry *elm;
2065 * Walk over object DAG and process every dependent object
2066 * that is marked as DF_1_NODELETE or DF_1_GLOBAL. They need
2067 * to grow their own DAG.
2069 * For DF_1_GLOBAL, DAG is required for symbol lookups in
2070 * symlook_global() to work.
2072 * For DF_1_NODELETE, the DAG should have its reference upped.
2074 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2078 if (obj->z_nodelete && !obj->ref_nodel) {
2079 dbg("obj %s -z nodelete", obj->path);
2082 obj->ref_nodel = true;
2084 if (obj->z_global && objlist_find(&list_global, obj) == NULL) {
2085 dbg("obj %s -z global", obj->path);
2086 objlist_push_tail(&list_global, obj);
2092 * Initialize the dynamic linker. The argument is the address at which
2093 * the dynamic linker has been mapped into memory. The primary task of
2094 * this function is to relocate the dynamic linker.
2097 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
2099 Obj_Entry objtmp; /* Temporary rtld object */
2100 const Elf_Ehdr *ehdr;
2101 const Elf_Dyn *dyn_rpath;
2102 const Elf_Dyn *dyn_soname;
2103 const Elf_Dyn *dyn_runpath;
2105 #ifdef RTLD_INIT_PAGESIZES_EARLY
2106 /* The page size is required by the dynamic memory allocator. */
2107 init_pagesizes(aux_info);
2111 * Conjure up an Obj_Entry structure for the dynamic linker.
2113 * The "path" member can't be initialized yet because string constants
2114 * cannot yet be accessed. Below we will set it correctly.
2116 memset(&objtmp, 0, sizeof(objtmp));
2119 objtmp.mapbase = mapbase;
2121 objtmp.relocbase = mapbase;
2124 objtmp.dynamic = rtld_dynamic(&objtmp);
2125 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname, &dyn_runpath);
2126 assert(objtmp.needed == NULL);
2127 #if !defined(__mips__)
2128 /* MIPS has a bogus DT_TEXTREL. */
2129 assert(!objtmp.textrel);
2132 * Temporarily put the dynamic linker entry into the object list, so
2133 * that symbols can be found.
2135 relocate_objects(&objtmp, true, &objtmp, 0, NULL);
2137 ehdr = (Elf_Ehdr *)mapbase;
2138 objtmp.phdr = (Elf_Phdr *)((char *)mapbase + ehdr->e_phoff);
2139 objtmp.phsize = ehdr->e_phnum * sizeof(objtmp.phdr[0]);
2141 /* Initialize the object list. */
2142 TAILQ_INIT(&obj_list);
2144 /* Now that non-local variables can be accesses, copy out obj_rtld. */
2145 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
2147 #ifndef RTLD_INIT_PAGESIZES_EARLY
2148 /* The page size is required by the dynamic memory allocator. */
2149 init_pagesizes(aux_info);
2152 if (aux_info[AT_OSRELDATE] != NULL)
2153 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
2155 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname, dyn_runpath);
2157 /* Replace the path with a dynamically allocated copy. */
2158 obj_rtld.path = xstrdup(ld_path_rtld);
2160 r_debug.r_brk = r_debug_state;
2161 r_debug.r_state = RT_CONSISTENT;
2165 * Retrieve the array of supported page sizes. The kernel provides the page
2166 * sizes in increasing order.
2169 init_pagesizes(Elf_Auxinfo **aux_info)
2171 static size_t psa[MAXPAGESIZES];
2175 if (aux_info[AT_PAGESIZES] != NULL && aux_info[AT_PAGESIZESLEN] !=
2177 size = aux_info[AT_PAGESIZESLEN]->a_un.a_val;
2178 pagesizes = aux_info[AT_PAGESIZES]->a_un.a_ptr;
2181 if (sysctlnametomib("hw.pagesizes", mib, &len) == 0)
2184 /* As a fallback, retrieve the base page size. */
2185 size = sizeof(psa[0]);
2186 if (aux_info[AT_PAGESZ] != NULL) {
2187 psa[0] = aux_info[AT_PAGESZ]->a_un.a_val;
2191 mib[1] = HW_PAGESIZE;
2195 if (sysctl(mib, len, psa, &size, NULL, 0) == -1) {
2196 _rtld_error("sysctl for hw.pagesize(s) failed");
2202 npagesizes = size / sizeof(pagesizes[0]);
2203 /* Discard any invalid entries at the end of the array. */
2204 while (npagesizes > 0 && pagesizes[npagesizes - 1] == 0)
2209 * Add the init functions from a needed object list (and its recursive
2210 * needed objects) to "list". This is not used directly; it is a helper
2211 * function for initlist_add_objects(). The write lock must be held
2212 * when this function is called.
2215 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
2217 /* Recursively process the successor needed objects. */
2218 if (needed->next != NULL)
2219 initlist_add_neededs(needed->next, list);
2221 /* Process the current needed object. */
2222 if (needed->obj != NULL)
2223 initlist_add_objects(needed->obj, needed->obj, list);
2227 * Scan all of the DAGs rooted in the range of objects from "obj" to
2228 * "tail" and add their init functions to "list". This recurses over
2229 * the DAGs and ensure the proper init ordering such that each object's
2230 * needed libraries are initialized before the object itself. At the
2231 * same time, this function adds the objects to the global finalization
2232 * list "list_fini" in the opposite order. The write lock must be
2233 * held when this function is called.
2236 initlist_add_objects(Obj_Entry *obj, Obj_Entry *tail, Objlist *list)
2240 if (obj->init_scanned || obj->init_done)
2242 obj->init_scanned = true;
2244 /* Recursively process the successor objects. */
2245 nobj = globallist_next(obj);
2246 if (nobj != NULL && obj != tail)
2247 initlist_add_objects(nobj, tail, list);
2249 /* Recursively process the needed objects. */
2250 if (obj->needed != NULL)
2251 initlist_add_neededs(obj->needed, list);
2252 if (obj->needed_filtees != NULL)
2253 initlist_add_neededs(obj->needed_filtees, list);
2254 if (obj->needed_aux_filtees != NULL)
2255 initlist_add_neededs(obj->needed_aux_filtees, list);
2257 /* Add the object to the init list. */
2258 objlist_push_tail(list, obj);
2260 /* Add the object to the global fini list in the reverse order. */
2261 if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL)
2262 && !obj->on_fini_list) {
2263 objlist_push_head(&list_fini, obj);
2264 obj->on_fini_list = true;
2269 #define FPTR_TARGET(f) ((Elf_Addr) (f))
2273 free_needed_filtees(Needed_Entry *n, RtldLockState *lockstate)
2275 Needed_Entry *needed, *needed1;
2277 for (needed = n; needed != NULL; needed = needed->next) {
2278 if (needed->obj != NULL) {
2279 dlclose_locked(needed->obj, lockstate);
2283 for (needed = n; needed != NULL; needed = needed1) {
2284 needed1 = needed->next;
2290 unload_filtees(Obj_Entry *obj, RtldLockState *lockstate)
2293 free_needed_filtees(obj->needed_filtees, lockstate);
2294 obj->needed_filtees = NULL;
2295 free_needed_filtees(obj->needed_aux_filtees, lockstate);
2296 obj->needed_aux_filtees = NULL;
2297 obj->filtees_loaded = false;
2301 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags,
2302 RtldLockState *lockstate)
2305 for (; needed != NULL; needed = needed->next) {
2306 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
2307 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
2308 RTLD_LOCAL, lockstate);
2313 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
2316 lock_restart_for_upgrade(lockstate);
2317 if (!obj->filtees_loaded) {
2318 load_filtee1(obj, obj->needed_filtees, flags, lockstate);
2319 load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate);
2320 obj->filtees_loaded = true;
2325 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
2329 for (; needed != NULL; needed = needed->next) {
2330 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
2331 flags & ~RTLD_LO_NOLOAD);
2332 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
2339 * Given a shared object, traverse its list of needed objects, and load
2340 * each of them. Returns 0 on success. Generates an error message and
2341 * returns -1 on failure.
2344 load_needed_objects(Obj_Entry *first, int flags)
2348 for (obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
2351 if (process_needed(obj, obj->needed, flags) == -1)
2358 load_preload_objects(void)
2360 char *p = ld_preload;
2362 static const char delim[] = " \t:;";
2367 p += strspn(p, delim);
2368 while (*p != '\0') {
2369 size_t len = strcspn(p, delim);
2374 obj = load_object(p, -1, NULL, 0);
2376 return -1; /* XXX - cleanup */
2377 obj->z_interpose = true;
2380 p += strspn(p, delim);
2382 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
2387 printable_path(const char *path)
2390 return (path == NULL ? "<unknown>" : path);
2394 * Load a shared object into memory, if it is not already loaded. The
2395 * object may be specified by name or by user-supplied file descriptor
2396 * fd_u. In the later case, the fd_u descriptor is not closed, but its
2399 * Returns a pointer to the Obj_Entry for the object. Returns NULL
2403 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
2412 TAILQ_FOREACH(obj, &obj_list, next) {
2413 if (obj->marker || obj->doomed)
2415 if (object_match_name(obj, name))
2419 path = find_library(name, refobj, &fd);
2427 * search_library_pathfds() opens a fresh file descriptor for the
2428 * library, so there is no need to dup().
2430 } else if (fd_u == -1) {
2432 * If we didn't find a match by pathname, or the name is not
2433 * supplied, open the file and check again by device and inode.
2434 * This avoids false mismatches caused by multiple links or ".."
2437 * To avoid a race, we open the file and use fstat() rather than
2440 if ((fd = open(path, O_RDONLY | O_CLOEXEC | O_VERIFY)) == -1) {
2441 _rtld_error("Cannot open \"%s\"", path);
2446 fd = fcntl(fd_u, F_DUPFD_CLOEXEC, 0);
2448 _rtld_error("Cannot dup fd");
2453 if (fstat(fd, &sb) == -1) {
2454 _rtld_error("Cannot fstat \"%s\"", printable_path(path));
2459 TAILQ_FOREACH(obj, &obj_list, next) {
2460 if (obj->marker || obj->doomed)
2462 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
2465 if (obj != NULL && name != NULL) {
2466 object_add_name(obj, name);
2471 if (flags & RTLD_LO_NOLOAD) {
2477 /* First use of this object, so we must map it in */
2478 obj = do_load_object(fd, name, path, &sb, flags);
2487 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
2494 * but first, make sure that environment variables haven't been
2495 * used to circumvent the noexec flag on a filesystem.
2497 if (dangerous_ld_env) {
2498 if (fstatfs(fd, &fs) != 0) {
2499 _rtld_error("Cannot fstatfs \"%s\"", printable_path(path));
2502 if (fs.f_flags & MNT_NOEXEC) {
2503 _rtld_error("Cannot execute objects on %s", fs.f_mntonname);
2507 dbg("loading \"%s\"", printable_path(path));
2508 obj = map_object(fd, printable_path(path), sbp);
2513 * If DT_SONAME is present in the object, digest_dynamic2 already
2514 * added it to the object names.
2517 object_add_name(obj, name);
2519 digest_dynamic(obj, 0);
2520 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path,
2521 obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount);
2522 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
2524 dbg("refusing to load non-loadable \"%s\"", obj->path);
2525 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
2526 munmap(obj->mapbase, obj->mapsize);
2531 obj->dlopened = (flags & RTLD_LO_DLOPEN) != 0;
2532 TAILQ_INSERT_TAIL(&obj_list, obj, next);
2535 linkmap_add(obj); /* for GDB & dlinfo() */
2536 max_stack_flags |= obj->stack_flags;
2538 dbg(" %p .. %p: %s", obj->mapbase,
2539 obj->mapbase + obj->mapsize - 1, obj->path);
2541 dbg(" WARNING: %s has impure text", obj->path);
2542 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
2549 obj_from_addr(const void *addr)
2553 TAILQ_FOREACH(obj, &obj_list, next) {
2556 if (addr < (void *) obj->mapbase)
2558 if (addr < (void *)(obj->mapbase + obj->mapsize))
2567 Elf_Addr *preinit_addr;
2570 preinit_addr = (Elf_Addr *)obj_main->preinit_array;
2571 if (preinit_addr == NULL)
2574 for (index = 0; index < obj_main->preinit_array_num; index++) {
2575 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) {
2576 dbg("calling preinit function for %s at %p", obj_main->path,
2577 (void *)preinit_addr[index]);
2578 LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index],
2579 0, 0, obj_main->path);
2580 call_init_pointer(obj_main, preinit_addr[index]);
2586 * Call the finalization functions for each of the objects in "list"
2587 * belonging to the DAG of "root" and referenced once. If NULL "root"
2588 * is specified, every finalization function will be called regardless
2589 * of the reference count and the list elements won't be freed. All of
2590 * the objects are expected to have non-NULL fini functions.
2593 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
2597 Elf_Addr *fini_addr;
2600 assert(root == NULL || root->refcount == 1);
2603 root->doomed = true;
2606 * Preserve the current error message since a fini function might
2607 * call into the dynamic linker and overwrite it.
2609 saved_msg = errmsg_save();
2611 STAILQ_FOREACH(elm, list, link) {
2612 if (root != NULL && (elm->obj->refcount != 1 ||
2613 objlist_find(&root->dagmembers, elm->obj) == NULL))
2615 /* Remove object from fini list to prevent recursive invocation. */
2616 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2617 /* Ensure that new references cannot be acquired. */
2618 elm->obj->doomed = true;
2620 hold_object(elm->obj);
2621 lock_release(rtld_bind_lock, lockstate);
2623 * It is legal to have both DT_FINI and DT_FINI_ARRAY defined.
2624 * When this happens, DT_FINI_ARRAY is processed first.
2626 fini_addr = (Elf_Addr *)elm->obj->fini_array;
2627 if (fini_addr != NULL && elm->obj->fini_array_num > 0) {
2628 for (index = elm->obj->fini_array_num - 1; index >= 0;
2630 if (fini_addr[index] != 0 && fini_addr[index] != 1) {
2631 dbg("calling fini function for %s at %p",
2632 elm->obj->path, (void *)fini_addr[index]);
2633 LD_UTRACE(UTRACE_FINI_CALL, elm->obj,
2634 (void *)fini_addr[index], 0, 0, elm->obj->path);
2635 call_initfini_pointer(elm->obj, fini_addr[index]);
2639 if (elm->obj->fini != (Elf_Addr)NULL) {
2640 dbg("calling fini function for %s at %p", elm->obj->path,
2641 (void *)elm->obj->fini);
2642 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini,
2643 0, 0, elm->obj->path);
2644 call_initfini_pointer(elm->obj, elm->obj->fini);
2646 wlock_acquire(rtld_bind_lock, lockstate);
2647 unhold_object(elm->obj);
2648 /* No need to free anything if process is going down. */
2652 * We must restart the list traversal after every fini call
2653 * because a dlclose() call from the fini function or from
2654 * another thread might have modified the reference counts.
2658 } while (elm != NULL);
2659 errmsg_restore(saved_msg);
2663 * Call the initialization functions for each of the objects in
2664 * "list". All of the objects are expected to have non-NULL init
2668 objlist_call_init(Objlist *list, RtldLockState *lockstate)
2673 Elf_Addr *init_addr;
2674 void (*reg)(void (*)(void));
2678 * Clean init_scanned flag so that objects can be rechecked and
2679 * possibly initialized earlier if any of vectors called below
2680 * cause the change by using dlopen.
2682 TAILQ_FOREACH(obj, &obj_list, next) {
2685 obj->init_scanned = false;
2689 * Preserve the current error message since an init function might
2690 * call into the dynamic linker and overwrite it.
2692 saved_msg = errmsg_save();
2693 STAILQ_FOREACH(elm, list, link) {
2694 if (elm->obj->init_done) /* Initialized early. */
2697 * Race: other thread might try to use this object before current
2698 * one completes the initialization. Not much can be done here
2699 * without better locking.
2701 elm->obj->init_done = true;
2702 hold_object(elm->obj);
2704 if (elm->obj == obj_main && obj_main->crt_no_init) {
2705 reg = (void (*)(void (*)(void)))get_program_var_addr(
2706 "__libc_atexit", lockstate);
2708 lock_release(rtld_bind_lock, lockstate);
2711 rtld_exit_ptr = rtld_nop_exit;
2715 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined.
2716 * When this happens, DT_INIT is processed first.
2718 if (elm->obj->init != (Elf_Addr)NULL) {
2719 dbg("calling init function for %s at %p", elm->obj->path,
2720 (void *)elm->obj->init);
2721 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init,
2722 0, 0, elm->obj->path);
2723 call_initfini_pointer(elm->obj, elm->obj->init);
2725 init_addr = (Elf_Addr *)elm->obj->init_array;
2726 if (init_addr != NULL) {
2727 for (index = 0; index < elm->obj->init_array_num; index++) {
2728 if (init_addr[index] != 0 && init_addr[index] != 1) {
2729 dbg("calling init function for %s at %p", elm->obj->path,
2730 (void *)init_addr[index]);
2731 LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
2732 (void *)init_addr[index], 0, 0, elm->obj->path);
2733 call_init_pointer(elm->obj, init_addr[index]);
2737 wlock_acquire(rtld_bind_lock, lockstate);
2738 unhold_object(elm->obj);
2740 errmsg_restore(saved_msg);
2744 objlist_clear(Objlist *list)
2748 while (!STAILQ_EMPTY(list)) {
2749 elm = STAILQ_FIRST(list);
2750 STAILQ_REMOVE_HEAD(list, link);
2755 static Objlist_Entry *
2756 objlist_find(Objlist *list, const Obj_Entry *obj)
2760 STAILQ_FOREACH(elm, list, link)
2761 if (elm->obj == obj)
2767 objlist_init(Objlist *list)
2773 objlist_push_head(Objlist *list, Obj_Entry *obj)
2777 elm = NEW(Objlist_Entry);
2779 STAILQ_INSERT_HEAD(list, elm, link);
2783 objlist_push_tail(Objlist *list, Obj_Entry *obj)
2787 elm = NEW(Objlist_Entry);
2789 STAILQ_INSERT_TAIL(list, elm, link);
2793 objlist_put_after(Objlist *list, Obj_Entry *listobj, Obj_Entry *obj)
2795 Objlist_Entry *elm, *listelm;
2797 STAILQ_FOREACH(listelm, list, link) {
2798 if (listelm->obj == listobj)
2801 elm = NEW(Objlist_Entry);
2803 if (listelm != NULL)
2804 STAILQ_INSERT_AFTER(list, listelm, elm, link);
2806 STAILQ_INSERT_TAIL(list, elm, link);
2810 objlist_remove(Objlist *list, Obj_Entry *obj)
2814 if ((elm = objlist_find(list, obj)) != NULL) {
2815 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2821 * Relocate dag rooted in the specified object.
2822 * Returns 0 on success, or -1 on failure.
2826 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj,
2827 int flags, RtldLockState *lockstate)
2833 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2834 error = relocate_object(elm->obj, bind_now, rtldobj, flags,
2843 * Prepare for, or clean after, relocating an object marked with
2844 * DT_TEXTREL or DF_TEXTREL. Before relocating, all read-only
2845 * segments are remapped read-write. After relocations are done, the
2846 * segment's permissions are returned back to the modes specified in
2847 * the phdrs. If any relocation happened, or always for wired
2848 * program, COW is triggered.
2851 reloc_textrel_prot(Obj_Entry *obj, bool before)
2858 for (l = obj->phsize / sizeof(*ph), ph = obj->phdr; l > 0;
2860 if (ph->p_type != PT_LOAD || (ph->p_flags & PF_W) != 0)
2862 base = obj->relocbase + trunc_page(ph->p_vaddr);
2863 sz = round_page(ph->p_vaddr + ph->p_filesz) -
2864 trunc_page(ph->p_vaddr);
2865 prot = convert_prot(ph->p_flags) | (before ? PROT_WRITE : 0);
2866 if (mprotect(base, sz, prot) == -1) {
2867 _rtld_error("%s: Cannot write-%sable text segment: %s",
2868 obj->path, before ? "en" : "dis",
2869 rtld_strerror(errno));
2877 * Relocate single object.
2878 * Returns 0 on success, or -1 on failure.
2881 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
2882 int flags, RtldLockState *lockstate)
2887 obj->relocated = true;
2889 dbg("relocating \"%s\"", obj->path);
2891 if (obj->symtab == NULL || obj->strtab == NULL ||
2892 !(obj->valid_hash_sysv || obj->valid_hash_gnu)) {
2893 _rtld_error("%s: Shared object has no run-time symbol table",
2898 /* There are relocations to the write-protected text segment. */
2899 if (obj->textrel && reloc_textrel_prot(obj, true) != 0)
2902 /* Process the non-PLT non-IFUNC relocations. */
2903 if (reloc_non_plt(obj, rtldobj, flags, lockstate))
2906 /* Re-protected the text segment. */
2907 if (obj->textrel && reloc_textrel_prot(obj, false) != 0)
2910 /* Set the special PLT or GOT entries. */
2913 /* Process the PLT relocations. */
2914 if (reloc_plt(obj, flags, lockstate) == -1)
2916 /* Relocate the jump slots if we are doing immediate binding. */
2917 if ((obj->bind_now || bind_now) && reloc_jmpslots(obj, flags,
2921 if (!obj->mainprog && obj_enforce_relro(obj) == -1)
2925 * Set up the magic number and version in the Obj_Entry. These
2926 * were checked in the crt1.o from the original ElfKit, so we
2927 * set them for backward compatibility.
2929 obj->magic = RTLD_MAGIC;
2930 obj->version = RTLD_VERSION;
2936 * Relocate newly-loaded shared objects. The argument is a pointer to
2937 * the Obj_Entry for the first such object. All objects from the first
2938 * to the end of the list of objects are relocated. Returns 0 on success,
2942 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
2943 int flags, RtldLockState *lockstate)
2948 for (error = 0, obj = first; obj != NULL;
2949 obj = TAILQ_NEXT(obj, next)) {
2952 error = relocate_object(obj, bind_now, rtldobj, flags,
2961 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
2962 * referencing STT_GNU_IFUNC symbols is postponed till the other
2963 * relocations are done. The indirect functions specified as
2964 * ifunc are allowed to call other symbols, so we need to have
2965 * objects relocated before asking for resolution from indirects.
2967 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
2968 * instead of the usual lazy handling of PLT slots. It is
2969 * consistent with how GNU does it.
2972 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags,
2973 RtldLockState *lockstate)
2976 if (obj->ifuncs_resolved)
2978 obj->ifuncs_resolved = true;
2979 if (!obj->irelative && !((obj->bind_now || bind_now) && obj->gnu_ifunc))
2981 if (obj_disable_relro(obj) == -1 ||
2982 (obj->irelative && reloc_iresolve(obj, lockstate) == -1) ||
2983 ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
2984 reloc_gnu_ifunc(obj, flags, lockstate) == -1) ||
2985 obj_enforce_relro(obj) == -1)
2991 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags,
2992 RtldLockState *lockstate)
2997 STAILQ_FOREACH(elm, list, link) {
3001 if (resolve_object_ifunc(obj, bind_now, flags,
3009 * Cleanup procedure. It will be called (by the atexit mechanism) just
3010 * before the process exits.
3015 RtldLockState lockstate;
3017 wlock_acquire(rtld_bind_lock, &lockstate);
3019 objlist_call_fini(&list_fini, NULL, &lockstate);
3020 /* No need to remove the items from the list, since we are exiting. */
3021 if (!libmap_disable)
3023 lock_release(rtld_bind_lock, &lockstate);
3032 * Iterate over a search path, translate each element, and invoke the
3033 * callback on the result.
3036 path_enumerate(const char *path, path_enum_proc callback,
3037 const char *refobj_path, void *arg)
3043 path += strspn(path, ":;");
3044 while (*path != '\0') {
3048 len = strcspn(path, ":;");
3049 trans = lm_findn(refobj_path, path, len);
3051 res = callback(trans, strlen(trans), arg);
3053 res = callback(path, len, arg);
3059 path += strspn(path, ":;");
3065 struct try_library_args {
3074 try_library_path(const char *dir, size_t dirlen, void *param)
3076 struct try_library_args *arg;
3080 if (*dir == '/' || trust) {
3083 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
3086 pathname = arg->buffer;
3087 strncpy(pathname, dir, dirlen);
3088 pathname[dirlen] = '/';
3089 strcpy(pathname + dirlen + 1, arg->name);
3091 dbg(" Trying \"%s\"", pathname);
3092 fd = open(pathname, O_RDONLY | O_CLOEXEC | O_VERIFY);
3094 dbg(" Opened \"%s\", fd %d", pathname, fd);
3095 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
3096 strcpy(pathname, arg->buffer);
3100 dbg(" Failed to open \"%s\": %s",
3101 pathname, rtld_strerror(errno));
3108 search_library_path(const char *name, const char *path,
3109 const char *refobj_path, int *fdp)
3112 struct try_library_args arg;
3118 arg.namelen = strlen(name);
3119 arg.buffer = xmalloc(PATH_MAX);
3120 arg.buflen = PATH_MAX;
3123 p = path_enumerate(path, try_library_path, refobj_path, &arg);
3133 * Finds the library with the given name using the directory descriptors
3134 * listed in the LD_LIBRARY_PATH_FDS environment variable.
3136 * Returns a freshly-opened close-on-exec file descriptor for the library,
3137 * or -1 if the library cannot be found.
3140 search_library_pathfds(const char *name, const char *path, int *fdp)
3142 char *envcopy, *fdstr, *found, *last_token;
3146 dbg("%s('%s', '%s', fdp)", __func__, name, path);
3148 /* Don't load from user-specified libdirs into setuid binaries. */
3152 /* We can't do anything if LD_LIBRARY_PATH_FDS isn't set. */
3156 /* LD_LIBRARY_PATH_FDS only works with relative paths. */
3157 if (name[0] == '/') {
3158 dbg("Absolute path (%s) passed to %s", name, __func__);
3163 * Use strtok_r() to walk the FD:FD:FD list. This requires a local
3164 * copy of the path, as strtok_r rewrites separator tokens
3168 envcopy = xstrdup(path);
3169 for (fdstr = strtok_r(envcopy, ":", &last_token); fdstr != NULL;
3170 fdstr = strtok_r(NULL, ":", &last_token)) {
3171 dirfd = parse_integer(fdstr);
3173 _rtld_error("failed to parse directory FD: '%s'",
3177 fd = __sys_openat(dirfd, name, O_RDONLY | O_CLOEXEC | O_VERIFY);
3180 len = strlen(fdstr) + strlen(name) + 3;
3181 found = xmalloc(len);
3182 if (rtld_snprintf(found, len, "#%d/%s", dirfd, name) < 0) {
3183 _rtld_error("error generating '%d/%s'",
3187 dbg("open('%s') => %d", found, fd);
3198 dlclose(void *handle)
3200 RtldLockState lockstate;
3203 wlock_acquire(rtld_bind_lock, &lockstate);
3204 error = dlclose_locked(handle, &lockstate);
3205 lock_release(rtld_bind_lock, &lockstate);
3210 dlclose_locked(void *handle, RtldLockState *lockstate)
3214 root = dlcheck(handle);
3217 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
3220 /* Unreference the object and its dependencies. */
3221 root->dl_refcount--;
3223 if (root->refcount == 1) {
3225 * The object will be no longer referenced, so we must unload it.
3226 * First, call the fini functions.
3228 objlist_call_fini(&list_fini, root, lockstate);
3232 /* Finish cleaning up the newly-unreferenced objects. */
3233 GDB_STATE(RT_DELETE,&root->linkmap);
3234 unload_object(root, lockstate);
3235 GDB_STATE(RT_CONSISTENT,NULL);
3239 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
3246 char *msg = error_message;
3247 error_message = NULL;
3252 * This function is deprecated and has no effect.
3255 dllockinit(void *context,
3256 void *(*_lock_create)(void *context) __unused,
3257 void (*_rlock_acquire)(void *lock) __unused,
3258 void (*_wlock_acquire)(void *lock) __unused,
3259 void (*_lock_release)(void *lock) __unused,
3260 void (*_lock_destroy)(void *lock) __unused,
3261 void (*context_destroy)(void *context))
3263 static void *cur_context;
3264 static void (*cur_context_destroy)(void *);
3266 /* Just destroy the context from the previous call, if necessary. */
3267 if (cur_context_destroy != NULL)
3268 cur_context_destroy(cur_context);
3269 cur_context = context;
3270 cur_context_destroy = context_destroy;
3274 dlopen(const char *name, int mode)
3277 return (rtld_dlopen(name, -1, mode));
3281 fdlopen(int fd, int mode)
3284 return (rtld_dlopen(NULL, fd, mode));
3288 rtld_dlopen(const char *name, int fd, int mode)
3290 RtldLockState lockstate;
3293 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
3294 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
3295 if (ld_tracing != NULL) {
3296 rlock_acquire(rtld_bind_lock, &lockstate);
3297 if (sigsetjmp(lockstate.env, 0) != 0)
3298 lock_upgrade(rtld_bind_lock, &lockstate);
3299 environ = __DECONST(char **, *get_program_var_addr("environ", &lockstate));
3300 lock_release(rtld_bind_lock, &lockstate);
3302 lo_flags = RTLD_LO_DLOPEN;
3303 if (mode & RTLD_NODELETE)
3304 lo_flags |= RTLD_LO_NODELETE;
3305 if (mode & RTLD_NOLOAD)
3306 lo_flags |= RTLD_LO_NOLOAD;
3307 if (ld_tracing != NULL)
3308 lo_flags |= RTLD_LO_TRACE;
3310 return (dlopen_object(name, fd, obj_main, lo_flags,
3311 mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL));
3315 dlopen_cleanup(Obj_Entry *obj, RtldLockState *lockstate)
3320 if (obj->refcount == 0)
3321 unload_object(obj, lockstate);
3325 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
3326 int mode, RtldLockState *lockstate)
3328 Obj_Entry *old_obj_tail;
3331 RtldLockState mlockstate;
3334 objlist_init(&initlist);
3336 if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) {
3337 wlock_acquire(rtld_bind_lock, &mlockstate);
3338 lockstate = &mlockstate;
3340 GDB_STATE(RT_ADD,NULL);
3342 old_obj_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
3344 if (name == NULL && fd == -1) {
3348 obj = load_object(name, fd, refobj, lo_flags);
3353 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
3354 objlist_push_tail(&list_global, obj);
3355 if (globallist_next(old_obj_tail) != NULL) {
3356 /* We loaded something new. */
3357 assert(globallist_next(old_obj_tail) == obj);
3359 if ((lo_flags & RTLD_LO_EARLY) == 0 && obj->static_tls &&
3360 !allocate_tls_offset(obj)) {
3361 _rtld_error("%s: No space available "
3362 "for static Thread Local Storage", obj->path);
3366 result = load_needed_objects(obj, lo_flags & (RTLD_LO_DLOPEN |
3371 result = rtld_verify_versions(&obj->dagmembers);
3372 if (result != -1 && ld_tracing)
3374 if (result == -1 || relocate_object_dag(obj,
3375 (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld,
3376 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3378 dlopen_cleanup(obj, lockstate);
3380 } else if (lo_flags & RTLD_LO_EARLY) {
3382 * Do not call the init functions for early loaded
3383 * filtees. The image is still not initialized enough
3386 * Our object is found by the global object list and
3387 * will be ordered among all init calls done right
3388 * before transferring control to main.
3391 /* Make list of init functions to call. */
3392 initlist_add_objects(obj, obj, &initlist);
3395 * Process all no_delete or global objects here, given
3396 * them own DAGs to prevent their dependencies from being
3397 * unloaded. This has to be done after we have loaded all
3398 * of the dependencies, so that we do not miss any.
3404 * Bump the reference counts for objects on this DAG. If
3405 * this is the first dlopen() call for the object that was
3406 * already loaded as a dependency, initialize the dag
3412 if ((lo_flags & RTLD_LO_TRACE) != 0)
3415 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
3416 obj->z_nodelete) && !obj->ref_nodel) {
3417 dbg("obj %s nodelete", obj->path);
3419 obj->z_nodelete = obj->ref_nodel = true;
3423 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
3425 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
3427 if ((lo_flags & RTLD_LO_EARLY) == 0) {
3428 map_stacks_exec(lockstate);
3430 distribute_static_tls(&initlist, lockstate);
3433 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
3434 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3436 objlist_clear(&initlist);
3437 dlopen_cleanup(obj, lockstate);
3438 if (lockstate == &mlockstate)
3439 lock_release(rtld_bind_lock, lockstate);
3443 if (!(lo_flags & RTLD_LO_EARLY)) {
3444 /* Call the init functions. */
3445 objlist_call_init(&initlist, lockstate);
3447 objlist_clear(&initlist);
3448 if (lockstate == &mlockstate)
3449 lock_release(rtld_bind_lock, lockstate);
3452 trace_loaded_objects(obj);
3453 if (lockstate == &mlockstate)
3454 lock_release(rtld_bind_lock, lockstate);
3459 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
3463 const Obj_Entry *obj, *defobj;
3466 RtldLockState lockstate;
3473 symlook_init(&req, name);
3475 req.flags = flags | SYMLOOK_IN_PLT;
3476 req.lockstate = &lockstate;
3478 LD_UTRACE(UTRACE_DLSYM_START, handle, NULL, 0, 0, name);
3479 rlock_acquire(rtld_bind_lock, &lockstate);
3480 if (sigsetjmp(lockstate.env, 0) != 0)
3481 lock_upgrade(rtld_bind_lock, &lockstate);
3482 if (handle == NULL || handle == RTLD_NEXT ||
3483 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
3485 if ((obj = obj_from_addr(retaddr)) == NULL) {
3486 _rtld_error("Cannot determine caller's shared object");
3487 lock_release(rtld_bind_lock, &lockstate);
3488 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3491 if (handle == NULL) { /* Just the caller's shared object. */
3492 res = symlook_obj(&req, obj);
3495 defobj = req.defobj_out;
3497 } else if (handle == RTLD_NEXT || /* Objects after caller's */
3498 handle == RTLD_SELF) { /* ... caller included */
3499 if (handle == RTLD_NEXT)
3500 obj = globallist_next(obj);
3501 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
3504 res = symlook_obj(&req, obj);
3507 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) {
3509 defobj = req.defobj_out;
3510 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3516 * Search the dynamic linker itself, and possibly resolve the
3517 * symbol from there. This is how the application links to
3518 * dynamic linker services such as dlopen.
3520 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3521 res = symlook_obj(&req, &obj_rtld);
3524 defobj = req.defobj_out;
3528 assert(handle == RTLD_DEFAULT);
3529 res = symlook_default(&req, obj);
3531 defobj = req.defobj_out;
3536 if ((obj = dlcheck(handle)) == NULL) {
3537 lock_release(rtld_bind_lock, &lockstate);
3538 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3542 donelist_init(&donelist);
3543 if (obj->mainprog) {
3544 /* Handle obtained by dlopen(NULL, ...) implies global scope. */
3545 res = symlook_global(&req, &donelist);
3548 defobj = req.defobj_out;
3551 * Search the dynamic linker itself, and possibly resolve the
3552 * symbol from there. This is how the application links to
3553 * dynamic linker services such as dlopen.
3555 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3556 res = symlook_obj(&req, &obj_rtld);
3559 defobj = req.defobj_out;
3564 /* Search the whole DAG rooted at the given object. */
3565 res = symlook_list(&req, &obj->dagmembers, &donelist);
3568 defobj = req.defobj_out;
3574 lock_release(rtld_bind_lock, &lockstate);
3577 * The value required by the caller is derived from the value
3578 * of the symbol. this is simply the relocated value of the
3581 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
3582 sym = make_function_pointer(def, defobj);
3583 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
3584 sym = rtld_resolve_ifunc(defobj, def);
3585 else if (ELF_ST_TYPE(def->st_info) == STT_TLS) {
3586 ti.ti_module = defobj->tlsindex;
3587 ti.ti_offset = def->st_value;
3588 sym = __tls_get_addr(&ti);
3590 sym = defobj->relocbase + def->st_value;
3591 LD_UTRACE(UTRACE_DLSYM_STOP, handle, sym, 0, 0, name);
3595 _rtld_error("Undefined symbol \"%s%s%s\"", name, ve != NULL ? "@" : "",
3596 ve != NULL ? ve->name : "");
3597 lock_release(rtld_bind_lock, &lockstate);
3598 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3603 dlsym(void *handle, const char *name)
3605 return do_dlsym(handle, name, __builtin_return_address(0), NULL,
3610 dlfunc(void *handle, const char *name)
3617 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
3623 dlvsym(void *handle, const char *name, const char *version)
3627 ventry.name = version;
3629 ventry.hash = elf_hash(version);
3631 return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
3636 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
3638 const Obj_Entry *obj;
3639 RtldLockState lockstate;
3641 rlock_acquire(rtld_bind_lock, &lockstate);
3642 obj = obj_from_addr(addr);
3644 _rtld_error("No shared object contains address");
3645 lock_release(rtld_bind_lock, &lockstate);
3648 rtld_fill_dl_phdr_info(obj, phdr_info);
3649 lock_release(rtld_bind_lock, &lockstate);
3654 dladdr(const void *addr, Dl_info *info)
3656 const Obj_Entry *obj;
3659 unsigned long symoffset;
3660 RtldLockState lockstate;
3662 rlock_acquire(rtld_bind_lock, &lockstate);
3663 obj = obj_from_addr(addr);
3665 _rtld_error("No shared object contains address");
3666 lock_release(rtld_bind_lock, &lockstate);
3669 info->dli_fname = obj->path;
3670 info->dli_fbase = obj->mapbase;
3671 info->dli_saddr = (void *)0;
3672 info->dli_sname = NULL;
3675 * Walk the symbol list looking for the symbol whose address is
3676 * closest to the address sent in.
3678 for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) {
3679 def = obj->symtab + symoffset;
3682 * For skip the symbol if st_shndx is either SHN_UNDEF or
3685 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
3689 * If the symbol is greater than the specified address, or if it
3690 * is further away from addr than the current nearest symbol,
3693 symbol_addr = obj->relocbase + def->st_value;
3694 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
3697 /* Update our idea of the nearest symbol. */
3698 info->dli_sname = obj->strtab + def->st_name;
3699 info->dli_saddr = symbol_addr;
3702 if (info->dli_saddr == addr)
3705 lock_release(rtld_bind_lock, &lockstate);
3710 dlinfo(void *handle, int request, void *p)
3712 const Obj_Entry *obj;
3713 RtldLockState lockstate;
3716 rlock_acquire(rtld_bind_lock, &lockstate);
3718 if (handle == NULL || handle == RTLD_SELF) {
3721 retaddr = __builtin_return_address(0); /* __GNUC__ only */
3722 if ((obj = obj_from_addr(retaddr)) == NULL)
3723 _rtld_error("Cannot determine caller's shared object");
3725 obj = dlcheck(handle);
3728 lock_release(rtld_bind_lock, &lockstate);
3734 case RTLD_DI_LINKMAP:
3735 *((struct link_map const **)p) = &obj->linkmap;
3737 case RTLD_DI_ORIGIN:
3738 error = rtld_dirname(obj->path, p);
3741 case RTLD_DI_SERINFOSIZE:
3742 case RTLD_DI_SERINFO:
3743 error = do_search_info(obj, request, (struct dl_serinfo *)p);
3747 _rtld_error("Invalid request %d passed to dlinfo()", request);
3751 lock_release(rtld_bind_lock, &lockstate);
3757 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
3760 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
3761 phdr_info->dlpi_name = obj->path;
3762 phdr_info->dlpi_phdr = obj->phdr;
3763 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
3764 phdr_info->dlpi_tls_modid = obj->tlsindex;
3765 phdr_info->dlpi_tls_data = obj->tlsinit;
3766 phdr_info->dlpi_adds = obj_loads;
3767 phdr_info->dlpi_subs = obj_loads - obj_count;
3771 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
3773 struct dl_phdr_info phdr_info;
3774 Obj_Entry *obj, marker;
3775 RtldLockState bind_lockstate, phdr_lockstate;
3778 init_marker(&marker);
3781 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
3782 wlock_acquire(rtld_bind_lock, &bind_lockstate);
3783 for (obj = globallist_curr(TAILQ_FIRST(&obj_list)); obj != NULL;) {
3784 TAILQ_INSERT_AFTER(&obj_list, obj, &marker, next);
3785 rtld_fill_dl_phdr_info(obj, &phdr_info);
3787 lock_release(rtld_bind_lock, &bind_lockstate);
3789 error = callback(&phdr_info, sizeof phdr_info, param);
3791 wlock_acquire(rtld_bind_lock, &bind_lockstate);
3793 obj = globallist_next(&marker);
3794 TAILQ_REMOVE(&obj_list, &marker, next);
3796 lock_release(rtld_bind_lock, &bind_lockstate);
3797 lock_release(rtld_phdr_lock, &phdr_lockstate);
3803 rtld_fill_dl_phdr_info(&obj_rtld, &phdr_info);
3804 lock_release(rtld_bind_lock, &bind_lockstate);
3805 error = callback(&phdr_info, sizeof(phdr_info), param);
3807 lock_release(rtld_phdr_lock, &phdr_lockstate);
3812 fill_search_info(const char *dir, size_t dirlen, void *param)
3814 struct fill_search_info_args *arg;
3818 if (arg->request == RTLD_DI_SERINFOSIZE) {
3819 arg->serinfo->dls_cnt ++;
3820 arg->serinfo->dls_size += sizeof(struct dl_serpath) + dirlen + 1;
3822 struct dl_serpath *s_entry;
3824 s_entry = arg->serpath;
3825 s_entry->dls_name = arg->strspace;
3826 s_entry->dls_flags = arg->flags;
3828 strncpy(arg->strspace, dir, dirlen);
3829 arg->strspace[dirlen] = '\0';
3831 arg->strspace += dirlen + 1;
3839 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
3841 struct dl_serinfo _info;
3842 struct fill_search_info_args args;
3844 args.request = RTLD_DI_SERINFOSIZE;
3845 args.serinfo = &_info;
3847 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
3850 path_enumerate(obj->rpath, fill_search_info, NULL, &args);
3851 path_enumerate(ld_library_path, fill_search_info, NULL, &args);
3852 path_enumerate(obj->runpath, fill_search_info, NULL, &args);
3853 path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args);
3854 if (!obj->z_nodeflib)
3855 path_enumerate(ld_standard_library_path, fill_search_info, NULL, &args);
3858 if (request == RTLD_DI_SERINFOSIZE) {
3859 info->dls_size = _info.dls_size;
3860 info->dls_cnt = _info.dls_cnt;
3864 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
3865 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
3869 args.request = RTLD_DI_SERINFO;
3870 args.serinfo = info;
3871 args.serpath = &info->dls_serpath[0];
3872 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
3874 args.flags = LA_SER_RUNPATH;
3875 if (path_enumerate(obj->rpath, fill_search_info, NULL, &args) != NULL)
3878 args.flags = LA_SER_LIBPATH;
3879 if (path_enumerate(ld_library_path, fill_search_info, NULL, &args) != NULL)
3882 args.flags = LA_SER_RUNPATH;
3883 if (path_enumerate(obj->runpath, fill_search_info, NULL, &args) != NULL)
3886 args.flags = LA_SER_CONFIG;
3887 if (path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args)
3891 args.flags = LA_SER_DEFAULT;
3892 if (!obj->z_nodeflib && path_enumerate(ld_standard_library_path,
3893 fill_search_info, NULL, &args) != NULL)
3899 rtld_dirname(const char *path, char *bname)
3903 /* Empty or NULL string gets treated as "." */
3904 if (path == NULL || *path == '\0') {
3910 /* Strip trailing slashes */
3911 endp = path + strlen(path) - 1;
3912 while (endp > path && *endp == '/')
3915 /* Find the start of the dir */
3916 while (endp > path && *endp != '/')
3919 /* Either the dir is "/" or there are no slashes */
3921 bname[0] = *endp == '/' ? '/' : '.';
3927 } while (endp > path && *endp == '/');
3930 if (endp - path + 2 > PATH_MAX)
3932 _rtld_error("Filename is too long: %s", path);
3936 strncpy(bname, path, endp - path + 1);
3937 bname[endp - path + 1] = '\0';
3942 rtld_dirname_abs(const char *path, char *base)
3946 if (realpath(path, base) == NULL)
3948 dbg("%s -> %s", path, base);
3949 last = strrchr(base, '/');
3958 linkmap_add(Obj_Entry *obj)
3960 struct link_map *l = &obj->linkmap;
3961 struct link_map *prev;
3963 obj->linkmap.l_name = obj->path;
3964 obj->linkmap.l_addr = obj->mapbase;
3965 obj->linkmap.l_ld = obj->dynamic;
3967 /* GDB needs load offset on MIPS to use the symbols */
3968 obj->linkmap.l_offs = obj->relocbase;
3971 if (r_debug.r_map == NULL) {
3977 * Scan to the end of the list, but not past the entry for the
3978 * dynamic linker, which we want to keep at the very end.
3980 for (prev = r_debug.r_map;
3981 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
3982 prev = prev->l_next)
3985 /* Link in the new entry. */
3987 l->l_next = prev->l_next;
3988 if (l->l_next != NULL)
3989 l->l_next->l_prev = l;
3994 linkmap_delete(Obj_Entry *obj)
3996 struct link_map *l = &obj->linkmap;
3998 if (l->l_prev == NULL) {
3999 if ((r_debug.r_map = l->l_next) != NULL)
4000 l->l_next->l_prev = NULL;
4004 if ((l->l_prev->l_next = l->l_next) != NULL)
4005 l->l_next->l_prev = l->l_prev;
4009 * Function for the debugger to set a breakpoint on to gain control.
4011 * The two parameters allow the debugger to easily find and determine
4012 * what the runtime loader is doing and to whom it is doing it.
4014 * When the loadhook trap is hit (r_debug_state, set at program
4015 * initialization), the arguments can be found on the stack:
4017 * +8 struct link_map *m
4018 * +4 struct r_debug *rd
4022 r_debug_state(struct r_debug* rd __unused, struct link_map *m __unused)
4025 * The following is a hack to force the compiler to emit calls to
4026 * this function, even when optimizing. If the function is empty,
4027 * the compiler is not obliged to emit any code for calls to it,
4028 * even when marked __noinline. However, gdb depends on those
4031 __compiler_membar();
4035 * A function called after init routines have completed. This can be used to
4036 * break before a program's entry routine is called, and can be used when
4037 * main is not available in the symbol table.
4040 _r_debug_postinit(struct link_map *m __unused)
4043 /* See r_debug_state(). */
4044 __compiler_membar();
4048 release_object(Obj_Entry *obj)
4051 if (obj->holdcount > 0) {
4052 obj->unholdfree = true;
4055 munmap(obj->mapbase, obj->mapsize);
4056 linkmap_delete(obj);
4061 * Get address of the pointer variable in the main program.
4062 * Prefer non-weak symbol over the weak one.
4064 static const void **
4065 get_program_var_addr(const char *name, RtldLockState *lockstate)
4070 symlook_init(&req, name);
4071 req.lockstate = lockstate;
4072 donelist_init(&donelist);
4073 if (symlook_global(&req, &donelist) != 0)
4075 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
4076 return ((const void **)make_function_pointer(req.sym_out,
4078 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
4079 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
4081 return ((const void **)(req.defobj_out->relocbase +
4082 req.sym_out->st_value));
4086 * Set a pointer variable in the main program to the given value. This
4087 * is used to set key variables such as "environ" before any of the
4088 * init functions are called.
4091 set_program_var(const char *name, const void *value)
4095 if ((addr = get_program_var_addr(name, NULL)) != NULL) {
4096 dbg("\"%s\": *%p <-- %p", name, addr, value);
4102 * Search the global objects, including dependencies and main object,
4103 * for the given symbol.
4106 symlook_global(SymLook *req, DoneList *donelist)
4109 const Objlist_Entry *elm;
4112 symlook_init_from_req(&req1, req);
4114 /* Search all objects loaded at program start up. */
4115 if (req->defobj_out == NULL ||
4116 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
4117 res = symlook_list(&req1, &list_main, donelist);
4118 if (res == 0 && (req->defobj_out == NULL ||
4119 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4120 req->sym_out = req1.sym_out;
4121 req->defobj_out = req1.defobj_out;
4122 assert(req->defobj_out != NULL);
4126 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
4127 STAILQ_FOREACH(elm, &list_global, link) {
4128 if (req->defobj_out != NULL &&
4129 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
4131 res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
4132 if (res == 0 && (req->defobj_out == NULL ||
4133 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4134 req->sym_out = req1.sym_out;
4135 req->defobj_out = req1.defobj_out;
4136 assert(req->defobj_out != NULL);
4140 return (req->sym_out != NULL ? 0 : ESRCH);
4144 * Given a symbol name in a referencing object, find the corresponding
4145 * definition of the symbol. Returns a pointer to the symbol, or NULL if
4146 * no definition was found. Returns a pointer to the Obj_Entry of the
4147 * defining object via the reference parameter DEFOBJ_OUT.
4150 symlook_default(SymLook *req, const Obj_Entry *refobj)
4153 const Objlist_Entry *elm;
4157 donelist_init(&donelist);
4158 symlook_init_from_req(&req1, req);
4161 * Look first in the referencing object if linked symbolically,
4162 * and similarly handle protected symbols.
4164 res = symlook_obj(&req1, refobj);
4165 if (res == 0 && (refobj->symbolic ||
4166 ELF_ST_VISIBILITY(req1.sym_out->st_other) == STV_PROTECTED)) {
4167 req->sym_out = req1.sym_out;
4168 req->defobj_out = req1.defobj_out;
4169 assert(req->defobj_out != NULL);
4171 if (refobj->symbolic || req->defobj_out != NULL)
4172 donelist_check(&donelist, refobj);
4174 symlook_global(req, &donelist);
4176 /* Search all dlopened DAGs containing the referencing object. */
4177 STAILQ_FOREACH(elm, &refobj->dldags, link) {
4178 if (req->sym_out != NULL &&
4179 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
4181 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
4182 if (res == 0 && (req->sym_out == NULL ||
4183 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4184 req->sym_out = req1.sym_out;
4185 req->defobj_out = req1.defobj_out;
4186 assert(req->defobj_out != NULL);
4191 * Search the dynamic linker itself, and possibly resolve the
4192 * symbol from there. This is how the application links to
4193 * dynamic linker services such as dlopen.
4195 if (req->sym_out == NULL ||
4196 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
4197 res = symlook_obj(&req1, &obj_rtld);
4199 req->sym_out = req1.sym_out;
4200 req->defobj_out = req1.defobj_out;
4201 assert(req->defobj_out != NULL);
4205 return (req->sym_out != NULL ? 0 : ESRCH);
4209 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
4212 const Obj_Entry *defobj;
4213 const Objlist_Entry *elm;
4219 STAILQ_FOREACH(elm, objlist, link) {
4220 if (donelist_check(dlp, elm->obj))
4222 symlook_init_from_req(&req1, req);
4223 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
4224 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
4226 defobj = req1.defobj_out;
4227 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
4234 req->defobj_out = defobj;
4241 * Search the chain of DAGS cointed to by the given Needed_Entry
4242 * for a symbol of the given name. Each DAG is scanned completely
4243 * before advancing to the next one. Returns a pointer to the symbol,
4244 * or NULL if no definition was found.
4247 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
4250 const Needed_Entry *n;
4251 const Obj_Entry *defobj;
4257 symlook_init_from_req(&req1, req);
4258 for (n = needed; n != NULL; n = n->next) {
4259 if (n->obj == NULL ||
4260 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
4262 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
4264 defobj = req1.defobj_out;
4265 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
4271 req->defobj_out = defobj;
4278 * Search the symbol table of a single shared object for a symbol of
4279 * the given name and version, if requested. Returns a pointer to the
4280 * symbol, or NULL if no definition was found. If the object is
4281 * filter, return filtered symbol from filtee.
4283 * The symbol's hash value is passed in for efficiency reasons; that
4284 * eliminates many recomputations of the hash value.
4287 symlook_obj(SymLook *req, const Obj_Entry *obj)
4291 int flags, res, mres;
4294 * If there is at least one valid hash at this point, we prefer to
4295 * use the faster GNU version if available.
4297 if (obj->valid_hash_gnu)
4298 mres = symlook_obj1_gnu(req, obj);
4299 else if (obj->valid_hash_sysv)
4300 mres = symlook_obj1_sysv(req, obj);
4305 if (obj->needed_filtees != NULL) {
4306 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4307 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4308 donelist_init(&donelist);
4309 symlook_init_from_req(&req1, req);
4310 res = symlook_needed(&req1, obj->needed_filtees, &donelist);
4312 req->sym_out = req1.sym_out;
4313 req->defobj_out = req1.defobj_out;
4317 if (obj->needed_aux_filtees != NULL) {
4318 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4319 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4320 donelist_init(&donelist);
4321 symlook_init_from_req(&req1, req);
4322 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
4324 req->sym_out = req1.sym_out;
4325 req->defobj_out = req1.defobj_out;
4333 /* Symbol match routine common to both hash functions */
4335 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result,
4336 const unsigned long symnum)
4339 const Elf_Sym *symp;
4342 symp = obj->symtab + symnum;
4343 strp = obj->strtab + symp->st_name;
4345 switch (ELF_ST_TYPE(symp->st_info)) {
4351 if (symp->st_value == 0)
4355 if (symp->st_shndx != SHN_UNDEF)
4358 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
4359 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
4366 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
4369 if (req->ventry == NULL) {
4370 if (obj->versyms != NULL) {
4371 verndx = VER_NDX(obj->versyms[symnum]);
4372 if (verndx > obj->vernum) {
4374 "%s: symbol %s references wrong version %d",
4375 obj->path, obj->strtab + symnum, verndx);
4379 * If we are not called from dlsym (i.e. this
4380 * is a normal relocation from unversioned
4381 * binary), accept the symbol immediately if
4382 * it happens to have first version after this
4383 * shared object became versioned. Otherwise,
4384 * if symbol is versioned and not hidden,
4385 * remember it. If it is the only symbol with
4386 * this name exported by the shared object, it
4387 * will be returned as a match by the calling
4388 * function. If symbol is global (verndx < 2)
4389 * accept it unconditionally.
4391 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
4392 verndx == VER_NDX_GIVEN) {
4393 result->sym_out = symp;
4396 else if (verndx >= VER_NDX_GIVEN) {
4397 if ((obj->versyms[symnum] & VER_NDX_HIDDEN)
4399 if (result->vsymp == NULL)
4400 result->vsymp = symp;
4406 result->sym_out = symp;
4409 if (obj->versyms == NULL) {
4410 if (object_match_name(obj, req->ventry->name)) {
4411 _rtld_error("%s: object %s should provide version %s "
4412 "for symbol %s", obj_rtld.path, obj->path,
4413 req->ventry->name, obj->strtab + symnum);
4417 verndx = VER_NDX(obj->versyms[symnum]);
4418 if (verndx > obj->vernum) {
4419 _rtld_error("%s: symbol %s references wrong version %d",
4420 obj->path, obj->strtab + symnum, verndx);
4423 if (obj->vertab[verndx].hash != req->ventry->hash ||
4424 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
4426 * Version does not match. Look if this is a
4427 * global symbol and if it is not hidden. If
4428 * global symbol (verndx < 2) is available,
4429 * use it. Do not return symbol if we are
4430 * called by dlvsym, because dlvsym looks for
4431 * a specific version and default one is not
4432 * what dlvsym wants.
4434 if ((req->flags & SYMLOOK_DLSYM) ||
4435 (verndx >= VER_NDX_GIVEN) ||
4436 (obj->versyms[symnum] & VER_NDX_HIDDEN))
4440 result->sym_out = symp;
4445 * Search for symbol using SysV hash function.
4446 * obj->buckets is known not to be NULL at this point; the test for this was
4447 * performed with the obj->valid_hash_sysv assignment.
4450 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj)
4452 unsigned long symnum;
4453 Sym_Match_Result matchres;
4455 matchres.sym_out = NULL;
4456 matchres.vsymp = NULL;
4457 matchres.vcount = 0;
4459 for (symnum = obj->buckets[req->hash % obj->nbuckets];
4460 symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
4461 if (symnum >= obj->nchains)
4462 return (ESRCH); /* Bad object */
4464 if (matched_symbol(req, obj, &matchres, symnum)) {
4465 req->sym_out = matchres.sym_out;
4466 req->defobj_out = obj;
4470 if (matchres.vcount == 1) {
4471 req->sym_out = matchres.vsymp;
4472 req->defobj_out = obj;
4478 /* Search for symbol using GNU hash function */
4480 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj)
4482 Elf_Addr bloom_word;
4483 const Elf32_Word *hashval;
4485 Sym_Match_Result matchres;
4486 unsigned int h1, h2;
4487 unsigned long symnum;
4489 matchres.sym_out = NULL;
4490 matchres.vsymp = NULL;
4491 matchres.vcount = 0;
4493 /* Pick right bitmask word from Bloom filter array */
4494 bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) &
4495 obj->maskwords_bm_gnu];
4497 /* Calculate modulus word size of gnu hash and its derivative */
4498 h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1);
4499 h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1));
4501 /* Filter out the "definitely not in set" queries */
4502 if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0)
4505 /* Locate hash chain and corresponding value element*/
4506 bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu];
4509 hashval = &obj->chain_zero_gnu[bucket];
4511 if (((*hashval ^ req->hash_gnu) >> 1) == 0) {
4512 symnum = hashval - obj->chain_zero_gnu;
4513 if (matched_symbol(req, obj, &matchres, symnum)) {
4514 req->sym_out = matchres.sym_out;
4515 req->defobj_out = obj;
4519 } while ((*hashval++ & 1) == 0);
4520 if (matchres.vcount == 1) {
4521 req->sym_out = matchres.vsymp;
4522 req->defobj_out = obj;
4529 trace_loaded_objects(Obj_Entry *obj)
4531 const char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
4534 if ((main_local = getenv(_LD("TRACE_LOADED_OBJECTS_PROGNAME"))) == NULL)
4537 if ((fmt1 = getenv(_LD("TRACE_LOADED_OBJECTS_FMT1"))) == NULL)
4538 fmt1 = "\t%o => %p (%x)\n";
4540 if ((fmt2 = getenv(_LD("TRACE_LOADED_OBJECTS_FMT2"))) == NULL)
4541 fmt2 = "\t%o (%x)\n";
4543 list_containers = getenv(_LD("TRACE_LOADED_OBJECTS_ALL"));
4545 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
4546 Needed_Entry *needed;
4547 const char *name, *path;
4552 if (list_containers && obj->needed != NULL)
4553 rtld_printf("%s:\n", obj->path);
4554 for (needed = obj->needed; needed; needed = needed->next) {
4555 if (needed->obj != NULL) {
4556 if (needed->obj->traced && !list_containers)
4558 needed->obj->traced = true;
4559 path = needed->obj->path;
4563 name = obj->strtab + needed->name;
4564 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
4566 fmt = is_lib ? fmt1 : fmt2;
4567 while ((c = *fmt++) != '\0') {
4593 rtld_putstr(main_local);
4596 rtld_putstr(obj_main->path);
4603 rtld_printf("%d", sodp->sod_major);
4606 rtld_printf("%d", sodp->sod_minor);
4613 rtld_printf("%p", needed->obj ? needed->obj->mapbase :
4626 * Unload a dlopened object and its dependencies from memory and from
4627 * our data structures. It is assumed that the DAG rooted in the
4628 * object has already been unreferenced, and that the object has a
4629 * reference count of 0.
4632 unload_object(Obj_Entry *root, RtldLockState *lockstate)
4634 Obj_Entry marker, *obj, *next;
4636 assert(root->refcount == 0);
4639 * Pass over the DAG removing unreferenced objects from
4640 * appropriate lists.
4642 unlink_object(root);
4644 /* Unmap all objects that are no longer referenced. */
4645 for (obj = TAILQ_FIRST(&obj_list); obj != NULL; obj = next) {
4646 next = TAILQ_NEXT(obj, next);
4647 if (obj->marker || obj->refcount != 0)
4649 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase,
4650 obj->mapsize, 0, obj->path);
4651 dbg("unloading \"%s\"", obj->path);
4653 * Unlink the object now to prevent new references from
4654 * being acquired while the bind lock is dropped in
4655 * recursive dlclose() invocations.
4657 TAILQ_REMOVE(&obj_list, obj, next);
4660 if (obj->filtees_loaded) {
4662 init_marker(&marker);
4663 TAILQ_INSERT_BEFORE(next, &marker, next);
4664 unload_filtees(obj, lockstate);
4665 next = TAILQ_NEXT(&marker, next);
4666 TAILQ_REMOVE(&obj_list, &marker, next);
4668 unload_filtees(obj, lockstate);
4670 release_object(obj);
4675 unlink_object(Obj_Entry *root)
4679 if (root->refcount == 0) {
4680 /* Remove the object from the RTLD_GLOBAL list. */
4681 objlist_remove(&list_global, root);
4683 /* Remove the object from all objects' DAG lists. */
4684 STAILQ_FOREACH(elm, &root->dagmembers, link) {
4685 objlist_remove(&elm->obj->dldags, root);
4686 if (elm->obj != root)
4687 unlink_object(elm->obj);
4693 ref_dag(Obj_Entry *root)
4697 assert(root->dag_inited);
4698 STAILQ_FOREACH(elm, &root->dagmembers, link)
4699 elm->obj->refcount++;
4703 unref_dag(Obj_Entry *root)
4707 assert(root->dag_inited);
4708 STAILQ_FOREACH(elm, &root->dagmembers, link)
4709 elm->obj->refcount--;
4713 * Common code for MD __tls_get_addr().
4715 static void *tls_get_addr_slow(Elf_Addr **, int, size_t) __noinline;
4717 tls_get_addr_slow(Elf_Addr **dtvp, int index, size_t offset)
4719 Elf_Addr *newdtv, *dtv;
4720 RtldLockState lockstate;
4724 /* Check dtv generation in case new modules have arrived */
4725 if (dtv[0] != tls_dtv_generation) {
4726 wlock_acquire(rtld_bind_lock, &lockstate);
4727 newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4729 if (to_copy > tls_max_index)
4730 to_copy = tls_max_index;
4731 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
4732 newdtv[0] = tls_dtv_generation;
4733 newdtv[1] = tls_max_index;
4735 lock_release(rtld_bind_lock, &lockstate);
4736 dtv = *dtvp = newdtv;
4739 /* Dynamically allocate module TLS if necessary */
4740 if (dtv[index + 1] == 0) {
4741 /* Signal safe, wlock will block out signals. */
4742 wlock_acquire(rtld_bind_lock, &lockstate);
4743 if (!dtv[index + 1])
4744 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
4745 lock_release(rtld_bind_lock, &lockstate);
4747 return ((void *)(dtv[index + 1] + offset));
4751 tls_get_addr_common(Elf_Addr **dtvp, int index, size_t offset)
4756 /* Check dtv generation in case new modules have arrived */
4757 if (__predict_true(dtv[0] == tls_dtv_generation &&
4758 dtv[index + 1] != 0))
4759 return ((void *)(dtv[index + 1] + offset));
4760 return (tls_get_addr_slow(dtvp, index, offset));
4763 #if defined(__aarch64__) || defined(__arm__) || defined(__mips__) || \
4764 defined(__powerpc__) || defined(__riscv)
4767 * Return pointer to allocated TLS block
4770 get_tls_block_ptr(void *tcb, size_t tcbsize)
4772 size_t extra_size, post_size, pre_size, tls_block_size;
4773 size_t tls_init_align;
4775 tls_init_align = MAX(obj_main->tlsalign, 1);
4777 /* Compute fragments sizes. */
4778 extra_size = tcbsize - TLS_TCB_SIZE;
4779 post_size = calculate_tls_post_size(tls_init_align);
4780 tls_block_size = tcbsize + post_size;
4781 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size;
4783 return ((char *)tcb - pre_size - extra_size);
4787 * Allocate Static TLS using the Variant I method.
4789 * For details on the layout, see lib/libc/gen/tls.c.
4791 * NB: rtld's tls_static_space variable includes TLS_TCB_SIZE and post_size as
4792 * it is based on tls_last_offset, and TLS offsets here are really TCB
4793 * offsets, whereas libc's tls_static_space is just the executable's static
4797 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
4801 Elf_Addr *dtv, **tcb;
4804 size_t extra_size, maxalign, post_size, pre_size, tls_block_size;
4805 size_t tls_init_align;
4807 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
4810 assert(tcbsize >= TLS_TCB_SIZE);
4811 maxalign = MAX(tcbalign, tls_static_max_align);
4812 tls_init_align = MAX(obj_main->tlsalign, 1);
4814 /* Compute fragmets sizes. */
4815 extra_size = tcbsize - TLS_TCB_SIZE;
4816 post_size = calculate_tls_post_size(tls_init_align);
4817 tls_block_size = tcbsize + post_size;
4818 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size;
4819 tls_block_size += pre_size + tls_static_space - TLS_TCB_SIZE - post_size;
4821 /* Allocate whole TLS block */
4822 tls_block = malloc_aligned(tls_block_size, maxalign);
4823 tcb = (Elf_Addr **)(tls_block + pre_size + extra_size);
4825 if (oldtcb != NULL) {
4826 memcpy(tls_block, get_tls_block_ptr(oldtcb, tcbsize),
4828 free_aligned(get_tls_block_ptr(oldtcb, tcbsize));
4830 /* Adjust the DTV. */
4832 for (i = 0; i < dtv[1]; i++) {
4833 if (dtv[i+2] >= (Elf_Addr)oldtcb &&
4834 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
4835 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tcb;
4839 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4841 dtv[0] = tls_dtv_generation;
4842 dtv[1] = tls_max_index;
4844 for (obj = globallist_curr(objs); obj != NULL;
4845 obj = globallist_next(obj)) {
4846 if (obj->tlsoffset > 0) {
4847 addr = (Elf_Addr)tcb + obj->tlsoffset;
4848 if (obj->tlsinitsize > 0)
4849 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4850 if (obj->tlssize > obj->tlsinitsize)
4851 memset((void*)(addr + obj->tlsinitsize), 0,
4852 obj->tlssize - obj->tlsinitsize);
4853 dtv[obj->tlsindex + 1] = addr;
4862 free_tls(void *tcb, size_t tcbsize, size_t tcbalign __unused)
4865 Elf_Addr tlsstart, tlsend;
4867 size_t dtvsize, i, tls_init_align;
4869 assert(tcbsize >= TLS_TCB_SIZE);
4870 tls_init_align = MAX(obj_main->tlsalign, 1);
4872 /* Compute fragments sizes. */
4873 post_size = calculate_tls_post_size(tls_init_align);
4875 tlsstart = (Elf_Addr)tcb + TLS_TCB_SIZE + post_size;
4876 tlsend = (Elf_Addr)tcb + tls_static_space;
4878 dtv = *(Elf_Addr **)tcb;
4880 for (i = 0; i < dtvsize; i++) {
4881 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
4882 free((void*)dtv[i+2]);
4886 free_aligned(get_tls_block_ptr(tcb, tcbsize));
4891 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__)
4894 * Allocate Static TLS using the Variant II method.
4897 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
4900 size_t size, ralign;
4902 Elf_Addr *dtv, *olddtv;
4903 Elf_Addr segbase, oldsegbase, addr;
4907 if (tls_static_max_align > ralign)
4908 ralign = tls_static_max_align;
4909 size = round(tls_static_space, ralign) + round(tcbsize, ralign);
4911 assert(tcbsize >= 2*sizeof(Elf_Addr));
4912 tls = malloc_aligned(size, ralign);
4913 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4915 segbase = (Elf_Addr)(tls + round(tls_static_space, ralign));
4916 ((Elf_Addr*)segbase)[0] = segbase;
4917 ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
4919 dtv[0] = tls_dtv_generation;
4920 dtv[1] = tls_max_index;
4924 * Copy the static TLS block over whole.
4926 oldsegbase = (Elf_Addr) oldtls;
4927 memcpy((void *)(segbase - tls_static_space),
4928 (const void *)(oldsegbase - tls_static_space),
4932 * If any dynamic TLS blocks have been created tls_get_addr(),
4935 olddtv = ((Elf_Addr**)oldsegbase)[1];
4936 for (i = 0; i < olddtv[1]; i++) {
4937 if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
4938 dtv[i+2] = olddtv[i+2];
4944 * We assume that this block was the one we created with
4945 * allocate_initial_tls().
4947 free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
4949 for (obj = objs; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
4950 if (obj->marker || obj->tlsoffset == 0)
4952 addr = segbase - obj->tlsoffset;
4953 memset((void*)(addr + obj->tlsinitsize),
4954 0, obj->tlssize - obj->tlsinitsize);
4956 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4957 obj->static_tls_copied = true;
4959 dtv[obj->tlsindex + 1] = addr;
4963 return (void*) segbase;
4967 free_tls(void *tls, size_t tcbsize __unused, size_t tcbalign)
4970 size_t size, ralign;
4972 Elf_Addr tlsstart, tlsend;
4975 * Figure out the size of the initial TLS block so that we can
4976 * find stuff which ___tls_get_addr() allocated dynamically.
4979 if (tls_static_max_align > ralign)
4980 ralign = tls_static_max_align;
4981 size = round(tls_static_space, ralign);
4983 dtv = ((Elf_Addr**)tls)[1];
4985 tlsend = (Elf_Addr) tls;
4986 tlsstart = tlsend - size;
4987 for (i = 0; i < dtvsize; i++) {
4988 if (dtv[i + 2] != 0 && (dtv[i + 2] < tlsstart || dtv[i + 2] > tlsend)) {
4989 free_aligned((void *)dtv[i + 2]);
4993 free_aligned((void *)tlsstart);
5000 * Allocate TLS block for module with given index.
5003 allocate_module_tls(int index)
5008 TAILQ_FOREACH(obj, &obj_list, next) {
5011 if (obj->tlsindex == index)
5015 _rtld_error("Can't find module with TLS index %d", index);
5019 p = malloc_aligned(obj->tlssize, obj->tlsalign);
5020 memcpy(p, obj->tlsinit, obj->tlsinitsize);
5021 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
5027 allocate_tls_offset(Obj_Entry *obj)
5034 if (obj->tlssize == 0) {
5035 obj->tls_done = true;
5039 if (tls_last_offset == 0)
5040 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
5042 off = calculate_tls_offset(tls_last_offset, tls_last_size,
5043 obj->tlssize, obj->tlsalign);
5046 * If we have already fixed the size of the static TLS block, we
5047 * must stay within that size. When allocating the static TLS, we
5048 * leave a small amount of space spare to be used for dynamically
5049 * loading modules which use static TLS.
5051 if (tls_static_space != 0) {
5052 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
5054 } else if (obj->tlsalign > tls_static_max_align) {
5055 tls_static_max_align = obj->tlsalign;
5058 tls_last_offset = obj->tlsoffset = off;
5059 tls_last_size = obj->tlssize;
5060 obj->tls_done = true;
5066 free_tls_offset(Obj_Entry *obj)
5070 * If we were the last thing to allocate out of the static TLS
5071 * block, we give our space back to the 'allocator'. This is a
5072 * simplistic workaround to allow libGL.so.1 to be loaded and
5073 * unloaded multiple times.
5075 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
5076 == calculate_tls_end(tls_last_offset, tls_last_size)) {
5077 tls_last_offset -= obj->tlssize;
5083 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
5086 RtldLockState lockstate;
5088 wlock_acquire(rtld_bind_lock, &lockstate);
5089 ret = allocate_tls(globallist_curr(TAILQ_FIRST(&obj_list)), oldtls,
5091 lock_release(rtld_bind_lock, &lockstate);
5096 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
5098 RtldLockState lockstate;
5100 wlock_acquire(rtld_bind_lock, &lockstate);
5101 free_tls(tcb, tcbsize, tcbalign);
5102 lock_release(rtld_bind_lock, &lockstate);
5106 object_add_name(Obj_Entry *obj, const char *name)
5112 entry = malloc(sizeof(Name_Entry) + len);
5114 if (entry != NULL) {
5115 strcpy(entry->name, name);
5116 STAILQ_INSERT_TAIL(&obj->names, entry, link);
5121 object_match_name(const Obj_Entry *obj, const char *name)
5125 STAILQ_FOREACH(entry, &obj->names, link) {
5126 if (strcmp(name, entry->name) == 0)
5133 locate_dependency(const Obj_Entry *obj, const char *name)
5135 const Objlist_Entry *entry;
5136 const Needed_Entry *needed;
5138 STAILQ_FOREACH(entry, &list_main, link) {
5139 if (object_match_name(entry->obj, name))
5143 for (needed = obj->needed; needed != NULL; needed = needed->next) {
5144 if (strcmp(obj->strtab + needed->name, name) == 0 ||
5145 (needed->obj != NULL && object_match_name(needed->obj, name))) {
5147 * If there is DT_NEEDED for the name we are looking for,
5148 * we are all set. Note that object might not be found if
5149 * dependency was not loaded yet, so the function can
5150 * return NULL here. This is expected and handled
5151 * properly by the caller.
5153 return (needed->obj);
5156 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
5162 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
5163 const Elf_Vernaux *vna)
5165 const Elf_Verdef *vd;
5166 const char *vername;
5168 vername = refobj->strtab + vna->vna_name;
5169 vd = depobj->verdef;
5171 _rtld_error("%s: version %s required by %s not defined",
5172 depobj->path, vername, refobj->path);
5176 if (vd->vd_version != VER_DEF_CURRENT) {
5177 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
5178 depobj->path, vd->vd_version);
5181 if (vna->vna_hash == vd->vd_hash) {
5182 const Elf_Verdaux *aux = (const Elf_Verdaux *)
5183 ((const char *)vd + vd->vd_aux);
5184 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
5187 if (vd->vd_next == 0)
5189 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5191 if (vna->vna_flags & VER_FLG_WEAK)
5193 _rtld_error("%s: version %s required by %s not found",
5194 depobj->path, vername, refobj->path);
5199 rtld_verify_object_versions(Obj_Entry *obj)
5201 const Elf_Verneed *vn;
5202 const Elf_Verdef *vd;
5203 const Elf_Verdaux *vda;
5204 const Elf_Vernaux *vna;
5205 const Obj_Entry *depobj;
5206 int maxvernum, vernum;
5208 if (obj->ver_checked)
5210 obj->ver_checked = true;
5214 * Walk over defined and required version records and figure out
5215 * max index used by any of them. Do very basic sanity checking
5219 while (vn != NULL) {
5220 if (vn->vn_version != VER_NEED_CURRENT) {
5221 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
5222 obj->path, vn->vn_version);
5225 vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux);
5227 vernum = VER_NEED_IDX(vna->vna_other);
5228 if (vernum > maxvernum)
5230 if (vna->vna_next == 0)
5232 vna = (const Elf_Vernaux *)((const char *)vna + vna->vna_next);
5234 if (vn->vn_next == 0)
5236 vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next);
5240 while (vd != NULL) {
5241 if (vd->vd_version != VER_DEF_CURRENT) {
5242 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
5243 obj->path, vd->vd_version);
5246 vernum = VER_DEF_IDX(vd->vd_ndx);
5247 if (vernum > maxvernum)
5249 if (vd->vd_next == 0)
5251 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5258 * Store version information in array indexable by version index.
5259 * Verify that object version requirements are satisfied along the
5262 obj->vernum = maxvernum + 1;
5263 obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry));
5266 while (vd != NULL) {
5267 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
5268 vernum = VER_DEF_IDX(vd->vd_ndx);
5269 assert(vernum <= maxvernum);
5270 vda = (const Elf_Verdaux *)((const char *)vd + vd->vd_aux);
5271 obj->vertab[vernum].hash = vd->vd_hash;
5272 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
5273 obj->vertab[vernum].file = NULL;
5274 obj->vertab[vernum].flags = 0;
5276 if (vd->vd_next == 0)
5278 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5282 while (vn != NULL) {
5283 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
5286 vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux);
5288 if (check_object_provided_version(obj, depobj, vna))
5290 vernum = VER_NEED_IDX(vna->vna_other);
5291 assert(vernum <= maxvernum);
5292 obj->vertab[vernum].hash = vna->vna_hash;
5293 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
5294 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
5295 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
5296 VER_INFO_HIDDEN : 0;
5297 if (vna->vna_next == 0)
5299 vna = (const Elf_Vernaux *)((const char *)vna + vna->vna_next);
5301 if (vn->vn_next == 0)
5303 vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next);
5309 rtld_verify_versions(const Objlist *objlist)
5311 Objlist_Entry *entry;
5315 STAILQ_FOREACH(entry, objlist, link) {
5317 * Skip dummy objects or objects that have their version requirements
5320 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
5322 if (rtld_verify_object_versions(entry->obj) == -1) {
5324 if (ld_tracing == NULL)
5328 if (rc == 0 || ld_tracing != NULL)
5329 rc = rtld_verify_object_versions(&obj_rtld);
5334 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
5339 vernum = VER_NDX(obj->versyms[symnum]);
5340 if (vernum >= obj->vernum) {
5341 _rtld_error("%s: symbol %s has wrong verneed value %d",
5342 obj->path, obj->strtab + symnum, vernum);
5343 } else if (obj->vertab[vernum].hash != 0) {
5344 return &obj->vertab[vernum];
5351 _rtld_get_stack_prot(void)
5354 return (stack_prot);
5358 _rtld_is_dlopened(void *arg)
5361 RtldLockState lockstate;
5364 rlock_acquire(rtld_bind_lock, &lockstate);
5367 obj = obj_from_addr(arg);
5369 _rtld_error("No shared object contains address");
5370 lock_release(rtld_bind_lock, &lockstate);
5373 res = obj->dlopened ? 1 : 0;
5374 lock_release(rtld_bind_lock, &lockstate);
5379 obj_remap_relro(Obj_Entry *obj, int prot)
5382 if (obj->relro_size > 0 && mprotect(obj->relro_page, obj->relro_size,
5384 _rtld_error("%s: Cannot set relro protection to %#x: %s",
5385 obj->path, prot, rtld_strerror(errno));
5392 obj_disable_relro(Obj_Entry *obj)
5395 return (obj_remap_relro(obj, PROT_READ | PROT_WRITE));
5399 obj_enforce_relro(Obj_Entry *obj)
5402 return (obj_remap_relro(obj, PROT_READ));
5406 map_stacks_exec(RtldLockState *lockstate)
5408 void (*thr_map_stacks_exec)(void);
5410 if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
5412 thr_map_stacks_exec = (void (*)(void))(uintptr_t)
5413 get_program_var_addr("__pthread_map_stacks_exec", lockstate);
5414 if (thr_map_stacks_exec != NULL) {
5415 stack_prot |= PROT_EXEC;
5416 thr_map_stacks_exec();
5421 distribute_static_tls(Objlist *list, RtldLockState *lockstate)
5425 void (*distrib)(size_t, void *, size_t, size_t);
5427 distrib = (void (*)(size_t, void *, size_t, size_t))(uintptr_t)
5428 get_program_var_addr("__pthread_distribute_static_tls", lockstate);
5429 if (distrib == NULL)
5431 STAILQ_FOREACH(elm, list, link) {
5433 if (obj->marker || !obj->tls_done || obj->static_tls_copied)
5435 distrib(obj->tlsoffset, obj->tlsinit, obj->tlsinitsize,
5437 obj->static_tls_copied = true;
5442 symlook_init(SymLook *dst, const char *name)
5445 bzero(dst, sizeof(*dst));
5447 dst->hash = elf_hash(name);
5448 dst->hash_gnu = gnu_hash(name);
5452 symlook_init_from_req(SymLook *dst, const SymLook *src)
5455 dst->name = src->name;
5456 dst->hash = src->hash;
5457 dst->hash_gnu = src->hash_gnu;
5458 dst->ventry = src->ventry;
5459 dst->flags = src->flags;
5460 dst->defobj_out = NULL;
5461 dst->sym_out = NULL;
5462 dst->lockstate = src->lockstate;
5466 open_binary_fd(const char *argv0, bool search_in_path)
5468 char *pathenv, *pe, binpath[PATH_MAX];
5471 if (search_in_path && strchr(argv0, '/') == NULL) {
5472 pathenv = getenv("PATH");
5473 if (pathenv == NULL) {
5474 _rtld_error("-p and no PATH environment variable");
5477 pathenv = strdup(pathenv);
5478 if (pathenv == NULL) {
5479 _rtld_error("Cannot allocate memory");
5484 while ((pe = strsep(&pathenv, ":")) != NULL) {
5485 if (strlcpy(binpath, pe, sizeof(binpath)) >=
5488 if (binpath[0] != '\0' &&
5489 strlcat(binpath, "/", sizeof(binpath)) >=
5492 if (strlcat(binpath, argv0, sizeof(binpath)) >=
5495 fd = open(binpath, O_RDONLY | O_CLOEXEC | O_VERIFY);
5496 if (fd != -1 || errno != ENOENT)
5501 fd = open(argv0, O_RDONLY | O_CLOEXEC | O_VERIFY);
5505 _rtld_error("Cannot open %s: %s", argv0, rtld_strerror(errno));
5512 * Parse a set of command-line arguments.
5515 parse_args(char* argv[], int argc, bool *use_pathp, int *fdp)
5518 int fd, i, j, arglen;
5521 dbg("Parsing command-line arguments");
5525 for (i = 1; i < argc; i++ ) {
5527 dbg("argv[%d]: '%s'", i, arg);
5530 * rtld arguments end with an explicit "--" or with the first
5531 * non-prefixed argument.
5533 if (strcmp(arg, "--") == 0) {
5541 * All other arguments are single-character options that can
5542 * be combined, so we need to search through `arg` for them.
5544 arglen = strlen(arg);
5545 for (j = 1; j < arglen; j++) {
5548 print_usage(argv[0]);
5550 } else if (opt == 'f') {
5552 * -f XX can be used to specify a descriptor for the
5553 * binary named at the command line (i.e., the later
5554 * argument will specify the process name but the
5555 * descriptor is what will actually be executed)
5557 if (j != arglen - 1) {
5558 /* -f must be the last option in, e.g., -abcf */
5559 _rtld_error("Invalid options: %s", arg);
5563 fd = parse_integer(argv[i]);
5565 _rtld_error("Invalid file descriptor: '%s'",
5571 } else if (opt == 'p') {
5574 _rtld_error("Invalid argument: '%s'", arg);
5575 print_usage(argv[0]);
5585 * Parse a file descriptor number without pulling in more of libc (e.g. atoi).
5588 parse_integer(const char *str)
5590 static const int RADIX = 10; /* XXXJA: possibly support hex? */
5597 for (c = *str; c != '\0'; c = *++str) {
5598 if (c < '0' || c > '9')
5605 /* Make sure we actually parsed something. */
5612 print_usage(const char *argv0)
5615 rtld_printf("Usage: %s [-h] [-f <FD>] [--] <binary> [<args>]\n"
5618 " -h Display this help message\n"
5619 " -p Search in PATH for named binary\n"
5620 " -f <FD> Execute <FD> instead of searching for <binary>\n"
5621 " -- End of RTLD options\n"
5622 " <binary> Name of process to execute\n"
5623 " <args> Arguments to the executed process\n", argv0);
5627 * Overrides for libc_pic-provided functions.
5631 __getosreldate(void)
5641 oid[1] = KERN_OSRELDATE;
5643 len = sizeof(osrel);
5644 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
5645 if (error == 0 && osrel > 0 && len == sizeof(osrel))
5650 rtld_strerror(int errnum)
5653 if (errnum < 0 || errnum >= sys_nerr)
5654 return ("Unknown error");
5655 return (sys_errlist[errnum]);
5659 * No ifunc relocations.
5662 memset(void *dest, int c, size_t len)
5666 for (i = 0; i < len; i++)
5667 ((char *)dest)[i] = c;
5672 bzero(void *dest, size_t len)
5676 for (i = 0; i < len; i++)
5677 ((char *)dest)[i] = 0;
5682 malloc(size_t nbytes)
5685 return (__crt_malloc(nbytes));
5689 calloc(size_t num, size_t size)
5692 return (__crt_calloc(num, size));
5703 realloc(void *cp, size_t nbytes)
5706 return (__crt_realloc(cp, nbytes));