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_utrace.h"
73 typedef void (*func_ptr_type)(void);
74 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg);
77 /* Variables that cannot be static: */
78 extern struct r_debug r_debug; /* For GDB */
79 extern int _thread_autoinit_dummy_decl;
80 extern char* __progname;
81 extern void (*__cleanup)(void);
85 * Function declarations.
87 static const char *basename(const char *);
88 static void digest_dynamic1(Obj_Entry *, int, const Elf_Dyn **,
89 const Elf_Dyn **, const Elf_Dyn **);
90 static void digest_dynamic2(Obj_Entry *, const Elf_Dyn *, const Elf_Dyn *,
92 static void digest_dynamic(Obj_Entry *, int);
93 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
94 static Obj_Entry *dlcheck(void *);
95 static int dlclose_locked(void *, RtldLockState *);
96 static Obj_Entry *dlopen_object(const char *name, int fd, Obj_Entry *refobj,
97 int lo_flags, int mode, RtldLockState *lockstate);
98 static Obj_Entry *do_load_object(int, const char *, char *, struct stat *, int);
99 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
100 static bool donelist_check(DoneList *, const Obj_Entry *);
101 static void errmsg_restore(char *);
102 static char *errmsg_save(void);
103 static void *fill_search_info(const char *, size_t, void *);
104 static char *find_library(const char *, const Obj_Entry *, int *);
105 static const char *gethints(bool);
106 static void hold_object(Obj_Entry *);
107 static void unhold_object(Obj_Entry *);
108 static void init_dag(Obj_Entry *);
109 static void init_marker(Obj_Entry *);
110 static void init_pagesizes(Elf_Auxinfo **aux_info);
111 static void init_rtld(caddr_t, Elf_Auxinfo **);
112 static void initlist_add_neededs(Needed_Entry *, Objlist *);
113 static void initlist_add_objects(Obj_Entry *, Obj_Entry *, Objlist *);
114 static void linkmap_add(Obj_Entry *);
115 static void linkmap_delete(Obj_Entry *);
116 static void load_filtees(Obj_Entry *, int flags, RtldLockState *);
117 static void unload_filtees(Obj_Entry *, RtldLockState *);
118 static int load_needed_objects(Obj_Entry *, int);
119 static int load_preload_objects(void);
120 static Obj_Entry *load_object(const char *, int fd, const Obj_Entry *, int);
121 static void map_stacks_exec(RtldLockState *);
122 static int obj_enforce_relro(Obj_Entry *);
123 static Obj_Entry *obj_from_addr(const void *);
124 static void objlist_call_fini(Objlist *, Obj_Entry *, RtldLockState *);
125 static void objlist_call_init(Objlist *, RtldLockState *);
126 static void objlist_clear(Objlist *);
127 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
128 static void objlist_init(Objlist *);
129 static void objlist_push_head(Objlist *, Obj_Entry *);
130 static void objlist_push_tail(Objlist *, Obj_Entry *);
131 static void objlist_put_after(Objlist *, Obj_Entry *, Obj_Entry *);
132 static void objlist_remove(Objlist *, Obj_Entry *);
133 static int open_binary_fd(const char *argv0, bool search_in_path);
134 static int parse_args(char* argv[], int argc, bool *use_pathp, int *fdp);
135 static int parse_integer(const char *);
136 static void *path_enumerate(const char *, path_enum_proc, const char *, void *);
137 static void print_usage(const char *argv0);
138 static void release_object(Obj_Entry *);
139 static int relocate_object_dag(Obj_Entry *root, bool bind_now,
140 Obj_Entry *rtldobj, int flags, RtldLockState *lockstate);
141 static int relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
142 int flags, RtldLockState *lockstate);
143 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, int,
145 static int resolve_objects_ifunc(Obj_Entry *first, bool bind_now,
146 int flags, RtldLockState *lockstate);
147 static int rtld_dirname(const char *, char *);
148 static int rtld_dirname_abs(const char *, char *);
149 static void *rtld_dlopen(const char *name, int fd, int mode);
150 static void rtld_exit(void);
151 static char *search_library_path(const char *, const char *, const char *,
153 static char *search_library_pathfds(const char *, const char *, int *);
154 static const void **get_program_var_addr(const char *, RtldLockState *);
155 static void set_program_var(const char *, const void *);
156 static int symlook_default(SymLook *, const Obj_Entry *refobj);
157 static int symlook_global(SymLook *, DoneList *);
158 static void symlook_init_from_req(SymLook *, const SymLook *);
159 static int symlook_list(SymLook *, const Objlist *, DoneList *);
160 static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *);
161 static int symlook_obj1_sysv(SymLook *, const Obj_Entry *);
162 static int symlook_obj1_gnu(SymLook *, const Obj_Entry *);
163 static void trace_loaded_objects(Obj_Entry *);
164 static void unlink_object(Obj_Entry *);
165 static void unload_object(Obj_Entry *, RtldLockState *lockstate);
166 static void unref_dag(Obj_Entry *);
167 static void ref_dag(Obj_Entry *);
168 static char *origin_subst_one(Obj_Entry *, char *, const char *,
170 static char *origin_subst(Obj_Entry *, const char *);
171 static bool obj_resolve_origin(Obj_Entry *obj);
172 static void preinit_main(void);
173 static int rtld_verify_versions(const Objlist *);
174 static int rtld_verify_object_versions(Obj_Entry *);
175 static void object_add_name(Obj_Entry *, const char *);
176 static int object_match_name(const Obj_Entry *, const char *);
177 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
178 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
179 struct dl_phdr_info *phdr_info);
180 static uint32_t gnu_hash(const char *);
181 static bool matched_symbol(SymLook *, const Obj_Entry *, Sym_Match_Result *,
182 const unsigned long);
184 void r_debug_state(struct r_debug *, struct link_map *) __noinline __exported;
185 void _r_debug_postinit(struct link_map *) __noinline __exported;
187 int __sys_openat(int, const char *, int, ...);
192 static char *error_message; /* Message for dlerror(), or NULL */
193 struct r_debug r_debug __exported; /* for GDB; */
194 static bool libmap_disable; /* Disable libmap */
195 static bool ld_loadfltr; /* Immediate filters processing */
196 static char *libmap_override; /* Maps to use in addition to libmap.conf */
197 static bool trust; /* False for setuid and setgid programs */
198 static bool dangerous_ld_env; /* True if environment variables have been
199 used to affect the libraries loaded */
200 bool ld_bind_not; /* Disable PLT update */
201 static char *ld_bind_now; /* Environment variable for immediate binding */
202 static char *ld_debug; /* Environment variable for debugging */
203 static char *ld_library_path; /* Environment variable for search path */
204 static char *ld_library_dirs; /* Environment variable for library descriptors */
205 static char *ld_preload; /* Environment variable for libraries to
207 static const char *ld_elf_hints_path; /* Environment variable for alternative hints path */
208 static const char *ld_tracing; /* Called from ldd to print libs */
209 static char *ld_utrace; /* Use utrace() to log events. */
210 static struct obj_entry_q obj_list; /* Queue of all loaded objects */
211 static Obj_Entry *obj_main; /* The main program shared object */
212 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
213 static unsigned int obj_count; /* Number of objects in obj_list */
214 static unsigned int obj_loads; /* Number of loads of objects (gen count) */
216 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
217 STAILQ_HEAD_INITIALIZER(list_global);
218 static Objlist list_main = /* Objects loaded at program startup */
219 STAILQ_HEAD_INITIALIZER(list_main);
220 static Objlist list_fini = /* Objects needing fini() calls */
221 STAILQ_HEAD_INITIALIZER(list_fini);
223 Elf_Sym sym_zero; /* For resolving undefined weak refs. */
225 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
227 extern Elf_Dyn _DYNAMIC;
228 #pragma weak _DYNAMIC
230 int dlclose(void *) __exported;
231 char *dlerror(void) __exported;
232 void *dlopen(const char *, int) __exported;
233 void *fdlopen(int, int) __exported;
234 void *dlsym(void *, const char *) __exported;
235 dlfunc_t dlfunc(void *, const char *) __exported;
236 void *dlvsym(void *, const char *, const char *) __exported;
237 int dladdr(const void *, Dl_info *) __exported;
238 void dllockinit(void *, void *(*)(void *), void (*)(void *), void (*)(void *),
239 void (*)(void *), void (*)(void *), void (*)(void *)) __exported;
240 int dlinfo(void *, int , void *) __exported;
241 int dl_iterate_phdr(__dl_iterate_hdr_callback, void *) __exported;
242 int _rtld_addr_phdr(const void *, struct dl_phdr_info *) __exported;
243 int _rtld_get_stack_prot(void) __exported;
244 int _rtld_is_dlopened(void *) __exported;
245 void _rtld_error(const char *, ...) __exported;
247 /* Only here to fix -Wmissing-prototypes warnings */
248 int __getosreldate(void);
249 void __pthread_cxa_finalize(struct dl_phdr_info *a);
250 func_ptr_type _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp);
251 Elf_Addr _rtld_bind(Obj_Entry *obj, Elf_Size reloff);
255 static int osreldate;
258 static int stack_prot = PROT_READ | PROT_WRITE | RTLD_DEFAULT_STACK_EXEC;
259 static int max_stack_flags;
262 * Global declarations normally provided by crt1. The dynamic linker is
263 * not built with crt1, so we have to provide them ourselves.
269 * Used to pass argc, argv to init functions.
275 * Globals to control TLS allocation.
277 size_t tls_last_offset; /* Static TLS offset of last module */
278 size_t tls_last_size; /* Static TLS size of last module */
279 size_t tls_static_space; /* Static TLS space allocated */
280 static size_t tls_static_max_align;
281 Elf_Addr tls_dtv_generation = 1; /* Used to detect when dtv size changes */
282 int tls_max_index = 1; /* Largest module index allocated */
284 static bool ld_library_path_rpath = false;
287 * Globals for path names, and such
289 const char *ld_elf_hints_default = _PATH_ELF_HINTS;
290 const char *ld_path_libmap_conf = _PATH_LIBMAP_CONF;
291 const char *ld_path_rtld = _PATH_RTLD;
292 const char *ld_standard_library_path = STANDARD_LIBRARY_PATH;
293 const char *ld_env_prefix = LD_;
296 * Fill in a DoneList with an allocation large enough to hold all of
297 * the currently-loaded objects. Keep this as a macro since it calls
298 * alloca and we want that to occur within the scope of the caller.
300 #define donelist_init(dlp) \
301 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
302 assert((dlp)->objs != NULL), \
303 (dlp)->num_alloc = obj_count, \
306 #define LD_UTRACE(e, h, mb, ms, r, n) do { \
307 if (ld_utrace != NULL) \
308 ld_utrace_log(e, h, mb, ms, r, n); \
312 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
313 int refcnt, const char *name)
315 struct utrace_rtld ut;
316 static const char rtld_utrace_sig[RTLD_UTRACE_SIG_SZ] = RTLD_UTRACE_SIG;
318 memcpy(ut.sig, rtld_utrace_sig, sizeof(ut.sig));
321 ut.mapbase = mapbase;
322 ut.mapsize = mapsize;
324 bzero(ut.name, sizeof(ut.name));
326 strlcpy(ut.name, name, sizeof(ut.name));
327 utrace(&ut, sizeof(ut));
330 #ifdef RTLD_VARIANT_ENV_NAMES
332 * construct the env variable based on the type of binary that's
335 static inline const char *
338 static char buffer[128];
340 strlcpy(buffer, ld_env_prefix, sizeof(buffer));
341 strlcat(buffer, var, sizeof(buffer));
349 * Main entry point for dynamic linking. The first argument is the
350 * stack pointer. The stack is expected to be laid out as described
351 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
352 * Specifically, the stack pointer points to a word containing
353 * ARGC. Following that in the stack is a null-terminated sequence
354 * of pointers to argument strings. Then comes a null-terminated
355 * sequence of pointers to environment strings. Finally, there is a
356 * sequence of "auxiliary vector" entries.
358 * The second argument points to a place to store the dynamic linker's
359 * exit procedure pointer and the third to a place to store the main
362 * The return value is the main program's entry point.
365 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
367 Elf_Auxinfo *aux, *auxp, *auxpf, *aux_info[AT_COUNT];
368 Objlist_Entry *entry;
369 Obj_Entry *last_interposer, *obj, *preload_tail;
370 const Elf_Phdr *phdr;
372 RtldLockState lockstate;
375 char **argv, **env, **envp, *kexecpath, *library_path_rpath;
378 char buf[MAXPATHLEN];
379 int argc, fd, i, phnum, rtld_argc;
380 bool dir_enable, explicit_fd, search_in_path;
383 * On entry, the dynamic linker itself has not been relocated yet.
384 * Be very careful not to reference any global data until after
385 * init_rtld has returned. It is OK to reference file-scope statics
386 * and string constants, and to call static and global functions.
389 /* Find the auxiliary vector on the stack. */
393 sp += argc + 1; /* Skip over arguments and NULL terminator */
395 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
397 aux = (Elf_Auxinfo *) sp;
399 /* Digest the auxiliary vector. */
400 for (i = 0; i < AT_COUNT; i++)
402 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
403 if (auxp->a_type < AT_COUNT)
404 aux_info[auxp->a_type] = auxp;
407 /* Initialize and relocate ourselves. */
408 assert(aux_info[AT_BASE] != NULL);
409 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
411 __progname = obj_rtld.path;
412 argv0 = argv[0] != NULL ? argv[0] : "(null)";
417 trust = !issetugid();
419 md_abi_variant_hook(aux_info);
422 if (aux_info[AT_EXECFD] != NULL) {
423 fd = aux_info[AT_EXECFD]->a_un.a_val;
425 assert(aux_info[AT_PHDR] != NULL);
426 phdr = (const Elf_Phdr *)aux_info[AT_PHDR]->a_un.a_ptr;
427 if (phdr == obj_rtld.phdr) {
429 _rtld_error("Tainted process refusing to run binary %s",
433 dbg("opening main program in direct exec mode");
435 rtld_argc = parse_args(argv, argc, &search_in_path, &fd);
436 argv0 = argv[rtld_argc];
437 explicit_fd = (fd != -1);
439 fd = open_binary_fd(argv0, search_in_path);
440 if (fstat(fd, &st) == -1) {
441 _rtld_error("Failed to fstat FD %d (%s): %s", fd,
442 explicit_fd ? "user-provided descriptor" : argv0,
443 rtld_strerror(errno));
448 * Rough emulation of the permission checks done by
449 * execve(2), only Unix DACs are checked, ACLs are
450 * ignored. Preserve the semantic of disabling owner
451 * to execute if owner x bit is cleared, even if
452 * others x bit is enabled.
453 * mmap(2) does not allow to mmap with PROT_EXEC if
454 * binary' file comes from noexec mount. We cannot
455 * set VV_TEXT on the binary.
458 if (st.st_uid == geteuid()) {
459 if ((st.st_mode & S_IXUSR) != 0)
461 } else if (st.st_gid == getegid()) {
462 if ((st.st_mode & S_IXGRP) != 0)
464 } else if ((st.st_mode & S_IXOTH) != 0) {
468 _rtld_error("No execute permission for binary %s",
474 * For direct exec mode, argv[0] is the interpreter
475 * name, we must remove it and shift arguments left
476 * before invoking binary main. Since stack layout
477 * places environment pointers and aux vectors right
478 * after the terminating NULL, we must shift
479 * environment and aux as well.
481 main_argc = argc - rtld_argc;
482 for (i = 0; i <= main_argc; i++)
483 argv[i] = argv[i + rtld_argc];
485 environ = env = envp = argv + main_argc + 1;
487 *envp = *(envp + rtld_argc);
489 } while (*envp != NULL);
490 aux = auxp = (Elf_Auxinfo *)envp;
491 auxpf = (Elf_Auxinfo *)(envp + rtld_argc);
492 for (;; auxp++, auxpf++) {
494 if (auxp->a_type == AT_NULL)
498 _rtld_error("No binary");
504 ld_bind_now = getenv(_LD("BIND_NOW"));
507 * If the process is tainted, then we un-set the dangerous environment
508 * variables. The process will be marked as tainted until setuid(2)
509 * is called. If any child process calls setuid(2) we do not want any
510 * future processes to honor the potentially un-safe variables.
513 if (unsetenv(_LD("PRELOAD")) || unsetenv(_LD("LIBMAP")) ||
514 unsetenv(_LD("LIBRARY_PATH")) || unsetenv(_LD("LIBRARY_PATH_FDS")) ||
515 unsetenv(_LD("LIBMAP_DISABLE")) || unsetenv(_LD("BIND_NOT")) ||
516 unsetenv(_LD("DEBUG")) || unsetenv(_LD("ELF_HINTS_PATH")) ||
517 unsetenv(_LD("LOADFLTR")) || unsetenv(_LD("LIBRARY_PATH_RPATH"))) {
518 _rtld_error("environment corrupt; aborting");
522 ld_debug = getenv(_LD("DEBUG"));
523 if (ld_bind_now == NULL)
524 ld_bind_not = getenv(_LD("BIND_NOT")) != NULL;
525 libmap_disable = getenv(_LD("LIBMAP_DISABLE")) != NULL;
526 libmap_override = getenv(_LD("LIBMAP"));
527 ld_library_path = getenv(_LD("LIBRARY_PATH"));
528 ld_library_dirs = getenv(_LD("LIBRARY_PATH_FDS"));
529 ld_preload = getenv(_LD("PRELOAD"));
530 ld_elf_hints_path = getenv(_LD("ELF_HINTS_PATH"));
531 ld_loadfltr = getenv(_LD("LOADFLTR")) != NULL;
532 library_path_rpath = getenv(_LD("LIBRARY_PATH_RPATH"));
533 if (library_path_rpath != NULL) {
534 if (library_path_rpath[0] == 'y' ||
535 library_path_rpath[0] == 'Y' ||
536 library_path_rpath[0] == '1')
537 ld_library_path_rpath = true;
539 ld_library_path_rpath = false;
541 dangerous_ld_env = libmap_disable || (libmap_override != NULL) ||
542 (ld_library_path != NULL) || (ld_preload != NULL) ||
543 (ld_elf_hints_path != NULL) || ld_loadfltr;
544 ld_tracing = getenv(_LD("TRACE_LOADED_OBJECTS"));
545 ld_utrace = getenv(_LD("UTRACE"));
547 if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0)
548 ld_elf_hints_path = ld_elf_hints_default;
550 if (ld_debug != NULL && *ld_debug != '\0')
552 dbg("%s is initialized, base address = %p", __progname,
553 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
554 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
555 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
557 dbg("initializing thread locks");
561 * Load the main program, or process its program header if it is
564 if (fd != -1) { /* Load the main program. */
565 dbg("loading main program");
566 obj_main = map_object(fd, argv0, NULL);
568 if (obj_main == NULL)
570 max_stack_flags = obj_main->stack_flags;
571 } else { /* Main program already loaded. */
572 dbg("processing main program's program header");
573 assert(aux_info[AT_PHDR] != NULL);
574 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
575 assert(aux_info[AT_PHNUM] != NULL);
576 phnum = aux_info[AT_PHNUM]->a_un.a_val;
577 assert(aux_info[AT_PHENT] != NULL);
578 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
579 assert(aux_info[AT_ENTRY] != NULL);
580 imgentry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
581 if ((obj_main = digest_phdr(phdr, phnum, imgentry, argv0)) == NULL)
585 if (aux_info[AT_EXECPATH] != NULL && fd == -1) {
586 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
587 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
588 if (kexecpath[0] == '/')
589 obj_main->path = kexecpath;
590 else if (getcwd(buf, sizeof(buf)) == NULL ||
591 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
592 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
593 obj_main->path = xstrdup(argv0);
595 obj_main->path = xstrdup(buf);
597 dbg("No AT_EXECPATH or direct exec");
598 obj_main->path = xstrdup(argv0);
600 dbg("obj_main path %s", obj_main->path);
601 obj_main->mainprog = true;
603 if (aux_info[AT_STACKPROT] != NULL &&
604 aux_info[AT_STACKPROT]->a_un.a_val != 0)
605 stack_prot = aux_info[AT_STACKPROT]->a_un.a_val;
609 * Get the actual dynamic linker pathname from the executable if
610 * possible. (It should always be possible.) That ensures that
611 * gdb will find the right dynamic linker even if a non-standard
614 if (obj_main->interp != NULL &&
615 strcmp(obj_main->interp, obj_rtld.path) != 0) {
617 obj_rtld.path = xstrdup(obj_main->interp);
618 __progname = obj_rtld.path;
622 digest_dynamic(obj_main, 0);
623 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d",
624 obj_main->path, obj_main->valid_hash_sysv, obj_main->valid_hash_gnu,
625 obj_main->dynsymcount);
627 linkmap_add(obj_main);
628 linkmap_add(&obj_rtld);
630 /* Link the main program into the list of objects. */
631 TAILQ_INSERT_HEAD(&obj_list, obj_main, next);
635 /* Initialize a fake symbol for resolving undefined weak references. */
636 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
637 sym_zero.st_shndx = SHN_UNDEF;
638 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
641 libmap_disable = (bool)lm_init(libmap_override);
643 dbg("loading LD_PRELOAD libraries");
644 if (load_preload_objects() == -1)
646 preload_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
648 dbg("loading needed objects");
649 if (load_needed_objects(obj_main, 0) == -1)
652 /* Make a list of all objects loaded at startup. */
653 last_interposer = obj_main;
654 TAILQ_FOREACH(obj, &obj_list, next) {
657 if (obj->z_interpose && obj != obj_main) {
658 objlist_put_after(&list_main, last_interposer, obj);
659 last_interposer = obj;
661 objlist_push_tail(&list_main, obj);
666 dbg("checking for required versions");
667 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
670 if (ld_tracing) { /* We're done */
671 trace_loaded_objects(obj_main);
675 if (getenv(_LD("DUMP_REL_PRE")) != NULL) {
676 dump_relocations(obj_main);
681 * Processing tls relocations requires having the tls offsets
682 * initialized. Prepare offsets before starting initial
683 * relocation processing.
685 dbg("initializing initial thread local storage offsets");
686 STAILQ_FOREACH(entry, &list_main, link) {
688 * Allocate all the initial objects out of the static TLS
689 * block even if they didn't ask for it.
691 allocate_tls_offset(entry->obj);
694 if (relocate_objects(obj_main,
695 ld_bind_now != NULL && *ld_bind_now != '\0',
696 &obj_rtld, SYMLOOK_EARLY, NULL) == -1)
699 dbg("doing copy relocations");
700 if (do_copy_relocations(obj_main) == -1)
703 if (getenv(_LD("DUMP_REL_POST")) != NULL) {
704 dump_relocations(obj_main);
711 * Setup TLS for main thread. This must be done after the
712 * relocations are processed, since tls initialization section
713 * might be the subject for relocations.
715 dbg("initializing initial thread local storage");
716 allocate_initial_tls(globallist_curr(TAILQ_FIRST(&obj_list)));
718 dbg("initializing key program variables");
719 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
720 set_program_var("environ", env);
721 set_program_var("__elf_aux_vector", aux);
723 /* Make a list of init functions to call. */
724 objlist_init(&initlist);
725 initlist_add_objects(globallist_curr(TAILQ_FIRST(&obj_list)),
726 preload_tail, &initlist);
728 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
730 map_stacks_exec(NULL);
732 dbg("resolving ifuncs");
733 if (resolve_objects_ifunc(obj_main,
734 ld_bind_now != NULL && *ld_bind_now != '\0', SYMLOOK_EARLY,
738 dbg("enforcing main obj relro");
739 if (obj_enforce_relro(obj_main) == -1)
742 if (!obj_main->crt_no_init) {
744 * Make sure we don't call the main program's init and fini
745 * functions for binaries linked with old crt1 which calls
748 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
749 obj_main->preinit_array = obj_main->init_array =
750 obj_main->fini_array = (Elf_Addr)NULL;
754 * Execute MD initializers required before we call the objects'
759 wlock_acquire(rtld_bind_lock, &lockstate);
760 if (obj_main->crt_no_init)
762 objlist_call_init(&initlist, &lockstate);
763 _r_debug_postinit(&obj_main->linkmap);
764 objlist_clear(&initlist);
765 dbg("loading filtees");
766 TAILQ_FOREACH(obj, &obj_list, next) {
769 if (ld_loadfltr || obj->z_loadfltr)
770 load_filtees(obj, 0, &lockstate);
772 lock_release(rtld_bind_lock, &lockstate);
774 dbg("transferring control to program entry point = %p", obj_main->entry);
776 /* Return the exit procedure and the program entry point. */
777 *exit_proc = rtld_exit;
779 return (func_ptr_type) obj_main->entry;
783 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def)
788 ptr = (void *)make_function_pointer(def, obj);
789 target = call_ifunc_resolver(ptr);
790 return ((void *)target);
794 * NB: MIPS uses a private version of this function (_mips_rtld_bind).
795 * Changes to this function should be applied there as well.
798 _rtld_bind(Obj_Entry *obj, Elf_Size reloff)
802 const Obj_Entry *defobj;
805 RtldLockState lockstate;
807 rlock_acquire(rtld_bind_lock, &lockstate);
808 if (sigsetjmp(lockstate.env, 0) != 0)
809 lock_upgrade(rtld_bind_lock, &lockstate);
811 rel = (const Elf_Rel *)((const char *)obj->pltrel + reloff);
813 rel = (const Elf_Rel *)((const char *)obj->pltrela + reloff);
815 where = (Elf_Addr *)(obj->relocbase + rel->r_offset);
816 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, SYMLOOK_IN_PLT,
820 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
821 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
823 target = (Elf_Addr)(defobj->relocbase + def->st_value);
825 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
826 defobj->strtab + def->st_name, basename(obj->path),
827 (void *)target, basename(defobj->path));
830 * Write the new contents for the jmpslot. Note that depending on
831 * architecture, the value which we need to return back to the
832 * lazy binding trampoline may or may not be the target
833 * address. The value returned from reloc_jmpslot() is the value
834 * that the trampoline needs.
836 target = reloc_jmpslot(where, target, defobj, obj, rel);
837 lock_release(rtld_bind_lock, &lockstate);
842 * Error reporting function. Use it like printf. If formats the message
843 * into a buffer, and sets things up so that the next call to dlerror()
844 * will return the message.
847 _rtld_error(const char *fmt, ...)
849 static char buf[512];
853 rtld_vsnprintf(buf, sizeof buf, fmt, ap);
856 LD_UTRACE(UTRACE_RTLD_ERROR, NULL, NULL, 0, 0, error_message);
860 * Return a dynamically-allocated copy of the current error message, if any.
865 return error_message == NULL ? NULL : xstrdup(error_message);
869 * Restore the current error message from a copy which was previously saved
870 * by errmsg_save(). The copy is freed.
873 errmsg_restore(char *saved_msg)
875 if (saved_msg == NULL)
876 error_message = NULL;
878 _rtld_error("%s", saved_msg);
884 basename(const char *name)
886 const char *p = strrchr(name, '/');
887 return p != NULL ? p + 1 : name;
890 static struct utsname uts;
893 origin_subst_one(Obj_Entry *obj, char *real, const char *kw,
894 const char *subst, bool may_free)
896 char *p, *p1, *res, *resp;
897 int subst_len, kw_len, subst_count, old_len, new_len;
902 * First, count the number of the keyword occurrences, to
903 * preallocate the final string.
905 for (p = real, subst_count = 0;; p = p1 + kw_len, subst_count++) {
912 * If the keyword is not found, just return.
914 * Return non-substituted string if resolution failed. We
915 * cannot do anything more reasonable, the failure mode of the
916 * caller is unresolved library anyway.
918 if (subst_count == 0 || (obj != NULL && !obj_resolve_origin(obj)))
919 return (may_free ? real : xstrdup(real));
921 subst = obj->origin_path;
924 * There is indeed something to substitute. Calculate the
925 * length of the resulting string, and allocate it.
927 subst_len = strlen(subst);
928 old_len = strlen(real);
929 new_len = old_len + (subst_len - kw_len) * subst_count;
930 res = xmalloc(new_len + 1);
933 * Now, execute the substitution loop.
935 for (p = real, resp = res, *resp = '\0';;) {
938 /* Copy the prefix before keyword. */
939 memcpy(resp, p, p1 - p);
941 /* Keyword replacement. */
942 memcpy(resp, subst, subst_len);
950 /* Copy to the end of string and finish. */
958 origin_subst(Obj_Entry *obj, const char *real)
960 char *res1, *res2, *res3, *res4;
962 if (obj == NULL || !trust)
963 return (xstrdup(real));
964 if (uts.sysname[0] == '\0') {
965 if (uname(&uts) != 0) {
966 _rtld_error("utsname failed: %d", errno);
970 /* __DECONST is safe here since without may_free real is unchanged */
971 res1 = origin_subst_one(obj, __DECONST(char *, real), "$ORIGIN", NULL,
973 res2 = origin_subst_one(NULL, res1, "$OSNAME", uts.sysname, true);
974 res3 = origin_subst_one(NULL, res2, "$OSREL", uts.release, true);
975 res4 = origin_subst_one(NULL, res3, "$PLATFORM", uts.machine, true);
982 const char *msg = dlerror();
986 rtld_fdputstr(STDERR_FILENO, _BASENAME_RTLD ": ");
987 rtld_fdputstr(STDERR_FILENO, msg);
988 rtld_fdputchar(STDERR_FILENO, '\n');
993 * Process a shared object's DYNAMIC section, and save the important
994 * information in its Obj_Entry structure.
997 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
998 const Elf_Dyn **dyn_soname, const Elf_Dyn **dyn_runpath)
1000 const Elf_Dyn *dynp;
1001 Needed_Entry **needed_tail = &obj->needed;
1002 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
1003 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
1004 const Elf_Hashelt *hashtab;
1005 const Elf32_Word *hashval;
1006 Elf32_Word bkt, nmaskwords;
1008 int plttype = DT_REL;
1012 *dyn_runpath = NULL;
1014 obj->bind_now = false;
1015 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
1016 switch (dynp->d_tag) {
1019 obj->rel = (const Elf_Rel *)(obj->relocbase + dynp->d_un.d_ptr);
1023 obj->relsize = dynp->d_un.d_val;
1027 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
1031 obj->pltrel = (const Elf_Rel *)
1032 (obj->relocbase + dynp->d_un.d_ptr);
1036 obj->pltrelsize = dynp->d_un.d_val;
1040 obj->rela = (const Elf_Rela *)(obj->relocbase + dynp->d_un.d_ptr);
1044 obj->relasize = dynp->d_un.d_val;
1048 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
1052 plttype = dynp->d_un.d_val;
1053 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
1057 obj->symtab = (const Elf_Sym *)
1058 (obj->relocbase + dynp->d_un.d_ptr);
1062 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
1066 obj->strtab = (const char *)(obj->relocbase + dynp->d_un.d_ptr);
1070 obj->strsize = dynp->d_un.d_val;
1074 obj->verneed = (const Elf_Verneed *)(obj->relocbase +
1079 obj->verneednum = dynp->d_un.d_val;
1083 obj->verdef = (const Elf_Verdef *)(obj->relocbase +
1088 obj->verdefnum = dynp->d_un.d_val;
1092 obj->versyms = (const Elf_Versym *)(obj->relocbase +
1098 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1100 obj->nbuckets = hashtab[0];
1101 obj->nchains = hashtab[1];
1102 obj->buckets = hashtab + 2;
1103 obj->chains = obj->buckets + obj->nbuckets;
1104 obj->valid_hash_sysv = obj->nbuckets > 0 && obj->nchains > 0 &&
1105 obj->buckets != NULL;
1111 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1113 obj->nbuckets_gnu = hashtab[0];
1114 obj->symndx_gnu = hashtab[1];
1115 nmaskwords = hashtab[2];
1116 bloom_size32 = (__ELF_WORD_SIZE / 32) * nmaskwords;
1117 obj->maskwords_bm_gnu = nmaskwords - 1;
1118 obj->shift2_gnu = hashtab[3];
1119 obj->bloom_gnu = (const Elf_Addr *)(hashtab + 4);
1120 obj->buckets_gnu = hashtab + 4 + bloom_size32;
1121 obj->chain_zero_gnu = obj->buckets_gnu + obj->nbuckets_gnu -
1123 /* Number of bitmask words is required to be power of 2 */
1124 obj->valid_hash_gnu = powerof2(nmaskwords) &&
1125 obj->nbuckets_gnu > 0 && obj->buckets_gnu != NULL;
1131 Needed_Entry *nep = NEW(Needed_Entry);
1132 nep->name = dynp->d_un.d_val;
1137 needed_tail = &nep->next;
1143 Needed_Entry *nep = NEW(Needed_Entry);
1144 nep->name = dynp->d_un.d_val;
1148 *needed_filtees_tail = nep;
1149 needed_filtees_tail = &nep->next;
1155 Needed_Entry *nep = NEW(Needed_Entry);
1156 nep->name = dynp->d_un.d_val;
1160 *needed_aux_filtees_tail = nep;
1161 needed_aux_filtees_tail = &nep->next;
1166 obj->pltgot = (Elf_Addr *)(obj->relocbase + dynp->d_un.d_ptr);
1170 obj->textrel = true;
1174 obj->symbolic = true;
1179 * We have to wait until later to process this, because we
1180 * might not have gotten the address of the string table yet.
1190 *dyn_runpath = dynp;
1194 obj->init = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1197 case DT_PREINIT_ARRAY:
1198 obj->preinit_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1201 case DT_PREINIT_ARRAYSZ:
1202 obj->preinit_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1206 obj->init_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1209 case DT_INIT_ARRAYSZ:
1210 obj->init_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1214 obj->fini = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1218 obj->fini_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1221 case DT_FINI_ARRAYSZ:
1222 obj->fini_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1226 * Don't process DT_DEBUG on MIPS as the dynamic section
1227 * is mapped read-only. DT_MIPS_RLD_MAP is used instead.
1233 dbg("Filling in DT_DEBUG entry");
1234 (__DECONST(Elf_Dyn *, dynp))->d_un.d_ptr = (Elf_Addr)&r_debug;
1239 if (dynp->d_un.d_val & DF_ORIGIN)
1240 obj->z_origin = true;
1241 if (dynp->d_un.d_val & DF_SYMBOLIC)
1242 obj->symbolic = true;
1243 if (dynp->d_un.d_val & DF_TEXTREL)
1244 obj->textrel = true;
1245 if (dynp->d_un.d_val & DF_BIND_NOW)
1246 obj->bind_now = true;
1247 /*if (dynp->d_un.d_val & DF_STATIC_TLS)
1251 case DT_MIPS_LOCAL_GOTNO:
1252 obj->local_gotno = dynp->d_un.d_val;
1255 case DT_MIPS_SYMTABNO:
1256 obj->symtabno = dynp->d_un.d_val;
1259 case DT_MIPS_GOTSYM:
1260 obj->gotsym = dynp->d_un.d_val;
1263 case DT_MIPS_RLD_MAP:
1264 *((Elf_Addr *)(dynp->d_un.d_ptr)) = (Elf_Addr) &r_debug;
1267 case DT_MIPS_RLD_MAP_REL:
1268 // The MIPS_RLD_MAP_REL tag stores the offset to the .rld_map
1269 // section relative to the address of the tag itself.
1270 *((Elf_Addr *)(__DECONST(char*, dynp) + dynp->d_un.d_val)) =
1271 (Elf_Addr) &r_debug;
1274 case DT_MIPS_PLTGOT:
1275 obj->mips_pltgot = (Elf_Addr *)(obj->relocbase +
1281 #ifdef __powerpc64__
1282 case DT_PPC64_GLINK:
1283 obj->glink = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1288 if (dynp->d_un.d_val & DF_1_NOOPEN)
1289 obj->z_noopen = true;
1290 if (dynp->d_un.d_val & DF_1_ORIGIN)
1291 obj->z_origin = true;
1292 if (dynp->d_un.d_val & DF_1_GLOBAL)
1293 obj->z_global = true;
1294 if (dynp->d_un.d_val & DF_1_BIND_NOW)
1295 obj->bind_now = true;
1296 if (dynp->d_un.d_val & DF_1_NODELETE)
1297 obj->z_nodelete = true;
1298 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1299 obj->z_loadfltr = true;
1300 if (dynp->d_un.d_val & DF_1_INTERPOSE)
1301 obj->z_interpose = true;
1302 if (dynp->d_un.d_val & DF_1_NODEFLIB)
1303 obj->z_nodeflib = true;
1308 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1315 obj->traced = false;
1317 if (plttype == DT_RELA) {
1318 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1320 obj->pltrelasize = obj->pltrelsize;
1321 obj->pltrelsize = 0;
1324 /* Determine size of dynsym table (equal to nchains of sysv hash) */
1325 if (obj->valid_hash_sysv)
1326 obj->dynsymcount = obj->nchains;
1327 else if (obj->valid_hash_gnu) {
1328 obj->dynsymcount = 0;
1329 for (bkt = 0; bkt < obj->nbuckets_gnu; bkt++) {
1330 if (obj->buckets_gnu[bkt] == 0)
1332 hashval = &obj->chain_zero_gnu[obj->buckets_gnu[bkt]];
1335 while ((*hashval++ & 1u) == 0);
1337 obj->dynsymcount += obj->symndx_gnu;
1342 obj_resolve_origin(Obj_Entry *obj)
1345 if (obj->origin_path != NULL)
1347 obj->origin_path = xmalloc(PATH_MAX);
1348 return (rtld_dirname_abs(obj->path, obj->origin_path) != -1);
1352 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1353 const Elf_Dyn *dyn_soname, const Elf_Dyn *dyn_runpath)
1356 if (obj->z_origin && !obj_resolve_origin(obj))
1359 if (dyn_runpath != NULL) {
1360 obj->runpath = (const char *)obj->strtab + dyn_runpath->d_un.d_val;
1361 obj->runpath = origin_subst(obj, obj->runpath);
1362 } else if (dyn_rpath != NULL) {
1363 obj->rpath = (const char *)obj->strtab + dyn_rpath->d_un.d_val;
1364 obj->rpath = origin_subst(obj, obj->rpath);
1366 if (dyn_soname != NULL)
1367 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1371 digest_dynamic(Obj_Entry *obj, int early)
1373 const Elf_Dyn *dyn_rpath;
1374 const Elf_Dyn *dyn_soname;
1375 const Elf_Dyn *dyn_runpath;
1377 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname, &dyn_runpath);
1378 digest_dynamic2(obj, dyn_rpath, dyn_soname, dyn_runpath);
1382 * Process a shared object's program header. This is used only for the
1383 * main program, when the kernel has already loaded the main program
1384 * into memory before calling the dynamic linker. It creates and
1385 * returns an Obj_Entry structure.
1388 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1391 const Elf_Phdr *phlimit = phdr + phnum;
1393 Elf_Addr note_start, note_end;
1397 for (ph = phdr; ph < phlimit; ph++) {
1398 if (ph->p_type != PT_PHDR)
1402 obj->phsize = ph->p_memsz;
1403 obj->relocbase = __DECONST(char *, phdr) - ph->p_vaddr;
1407 obj->stack_flags = PF_X | PF_R | PF_W;
1409 for (ph = phdr; ph < phlimit; ph++) {
1410 switch (ph->p_type) {
1413 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1417 if (nsegs == 0) { /* First load segment */
1418 obj->vaddrbase = trunc_page(ph->p_vaddr);
1419 obj->mapbase = obj->vaddrbase + obj->relocbase;
1420 } else { /* Last load segment */
1421 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1428 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1433 obj->tlssize = ph->p_memsz;
1434 obj->tlsalign = ph->p_align;
1435 obj->tlsinitsize = ph->p_filesz;
1436 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1440 obj->stack_flags = ph->p_flags;
1444 obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1445 obj->relro_size = round_page(ph->p_memsz);
1449 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
1450 note_end = note_start + ph->p_filesz;
1451 digest_notes(obj, note_start, note_end);
1456 _rtld_error("%s: too few PT_LOAD segments", path);
1465 digest_notes(Obj_Entry *obj, Elf_Addr note_start, Elf_Addr note_end)
1467 const Elf_Note *note;
1468 const char *note_name;
1471 for (note = (const Elf_Note *)note_start; (Elf_Addr)note < note_end;
1472 note = (const Elf_Note *)((const char *)(note + 1) +
1473 roundup2(note->n_namesz, sizeof(Elf32_Addr)) +
1474 roundup2(note->n_descsz, sizeof(Elf32_Addr)))) {
1475 if (note->n_namesz != sizeof(NOTE_FREEBSD_VENDOR) ||
1476 note->n_descsz != sizeof(int32_t))
1478 if (note->n_type != NT_FREEBSD_ABI_TAG &&
1479 note->n_type != NT_FREEBSD_NOINIT_TAG)
1481 note_name = (const char *)(note + 1);
1482 if (strncmp(NOTE_FREEBSD_VENDOR, note_name,
1483 sizeof(NOTE_FREEBSD_VENDOR)) != 0)
1485 switch (note->n_type) {
1486 case NT_FREEBSD_ABI_TAG:
1487 /* FreeBSD osrel note */
1488 p = (uintptr_t)(note + 1);
1489 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1490 obj->osrel = *(const int32_t *)(p);
1491 dbg("note osrel %d", obj->osrel);
1493 case NT_FREEBSD_NOINIT_TAG:
1494 /* FreeBSD 'crt does not call init' note */
1495 obj->crt_no_init = true;
1496 dbg("note crt_no_init");
1503 dlcheck(void *handle)
1507 TAILQ_FOREACH(obj, &obj_list, next) {
1508 if (obj == (Obj_Entry *) handle)
1512 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1513 _rtld_error("Invalid shared object handle %p", handle);
1520 * If the given object is already in the donelist, return true. Otherwise
1521 * add the object to the list and return false.
1524 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1528 for (i = 0; i < dlp->num_used; i++)
1529 if (dlp->objs[i] == obj)
1532 * Our donelist allocation should always be sufficient. But if
1533 * our threads locking isn't working properly, more shared objects
1534 * could have been loaded since we allocated the list. That should
1535 * never happen, but we'll handle it properly just in case it does.
1537 if (dlp->num_used < dlp->num_alloc)
1538 dlp->objs[dlp->num_used++] = obj;
1543 * Hash function for symbol table lookup. Don't even think about changing
1544 * this. It is specified by the System V ABI.
1547 elf_hash(const char *name)
1549 const unsigned char *p = (const unsigned char *) name;
1550 unsigned long h = 0;
1553 while (*p != '\0') {
1554 h = (h << 4) + *p++;
1555 if ((g = h & 0xf0000000) != 0)
1563 * The GNU hash function is the Daniel J. Bernstein hash clipped to 32 bits
1564 * unsigned in case it's implemented with a wider type.
1567 gnu_hash(const char *s)
1573 for (c = *s; c != '\0'; c = *++s)
1575 return (h & 0xffffffff);
1580 * Find the library with the given name, and return its full pathname.
1581 * The returned string is dynamically allocated. Generates an error
1582 * message and returns NULL if the library cannot be found.
1584 * If the second argument is non-NULL, then it refers to an already-
1585 * loaded shared object, whose library search path will be searched.
1587 * If a library is successfully located via LD_LIBRARY_PATH_FDS, its
1588 * descriptor (which is close-on-exec) will be passed out via the third
1591 * The search order is:
1592 * DT_RPATH in the referencing file _unless_ DT_RUNPATH is present (1)
1593 * DT_RPATH of the main object if DSO without defined DT_RUNPATH (1)
1595 * DT_RUNPATH in the referencing file
1596 * ldconfig hints (if -z nodefaultlib, filter out default library directories
1598 * /lib:/usr/lib _unless_ the referencing file is linked with -z nodefaultlib
1600 * (1) Handled in digest_dynamic2 - rpath left NULL if runpath defined.
1603 find_library(const char *xname, const Obj_Entry *refobj, int *fdp)
1605 char *pathname, *refobj_path;
1607 bool nodeflib, objgiven;
1609 objgiven = refobj != NULL;
1611 if (libmap_disable || !objgiven ||
1612 (name = lm_find(refobj->path, xname)) == NULL)
1615 if (strchr(name, '/') != NULL) { /* Hard coded pathname */
1616 if (name[0] != '/' && !trust) {
1617 _rtld_error("Absolute pathname required "
1618 "for shared object \"%s\"", name);
1621 return (origin_subst(__DECONST(Obj_Entry *, refobj),
1622 __DECONST(char *, name)));
1625 dbg(" Searching for \"%s\"", name);
1626 refobj_path = objgiven ? refobj->path : NULL;
1629 * If refobj->rpath != NULL, then refobj->runpath is NULL. Fall
1630 * back to pre-conforming behaviour if user requested so with
1631 * LD_LIBRARY_PATH_RPATH environment variable and ignore -z
1634 if (objgiven && refobj->rpath != NULL && ld_library_path_rpath) {
1635 pathname = search_library_path(name, ld_library_path,
1637 if (pathname != NULL)
1639 if (refobj != NULL) {
1640 pathname = search_library_path(name, refobj->rpath,
1642 if (pathname != NULL)
1645 pathname = search_library_pathfds(name, ld_library_dirs, fdp);
1646 if (pathname != NULL)
1648 pathname = search_library_path(name, gethints(false),
1650 if (pathname != NULL)
1652 pathname = search_library_path(name, ld_standard_library_path,
1654 if (pathname != NULL)
1657 nodeflib = objgiven ? refobj->z_nodeflib : false;
1659 pathname = search_library_path(name, refobj->rpath,
1661 if (pathname != NULL)
1664 if (objgiven && refobj->runpath == NULL && refobj != obj_main) {
1665 pathname = search_library_path(name, obj_main->rpath,
1667 if (pathname != NULL)
1670 pathname = search_library_path(name, ld_library_path,
1672 if (pathname != NULL)
1675 pathname = search_library_path(name, refobj->runpath,
1677 if (pathname != NULL)
1680 pathname = search_library_pathfds(name, ld_library_dirs, fdp);
1681 if (pathname != NULL)
1683 pathname = search_library_path(name, gethints(nodeflib),
1685 if (pathname != NULL)
1687 if (objgiven && !nodeflib) {
1688 pathname = search_library_path(name,
1689 ld_standard_library_path, refobj_path, fdp);
1690 if (pathname != NULL)
1695 if (objgiven && refobj->path != NULL) {
1696 _rtld_error("Shared object \"%s\" not found, "
1697 "required by \"%s\"", name, basename(refobj->path));
1699 _rtld_error("Shared object \"%s\" not found", name);
1705 * Given a symbol number in a referencing object, find the corresponding
1706 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1707 * no definition was found. Returns a pointer to the Obj_Entry of the
1708 * defining object via the reference parameter DEFOBJ_OUT.
1711 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1712 const Obj_Entry **defobj_out, int flags, SymCache *cache,
1713 RtldLockState *lockstate)
1717 const Obj_Entry *defobj;
1718 const Ver_Entry *ve;
1724 * If we have already found this symbol, get the information from
1727 if (symnum >= refobj->dynsymcount)
1728 return NULL; /* Bad object */
1729 if (cache != NULL && cache[symnum].sym != NULL) {
1730 *defobj_out = cache[symnum].obj;
1731 return cache[symnum].sym;
1734 ref = refobj->symtab + symnum;
1735 name = refobj->strtab + ref->st_name;
1741 * We don't have to do a full scale lookup if the symbol is local.
1742 * We know it will bind to the instance in this load module; to
1743 * which we already have a pointer (ie ref). By not doing a lookup,
1744 * we not only improve performance, but it also avoids unresolvable
1745 * symbols when local symbols are not in the hash table. This has
1746 * been seen with the ia64 toolchain.
1748 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1749 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1750 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1753 symlook_init(&req, name);
1755 ve = req.ventry = fetch_ventry(refobj, symnum);
1756 req.lockstate = lockstate;
1757 res = symlook_default(&req, refobj);
1760 defobj = req.defobj_out;
1768 * If we found no definition and the reference is weak, treat the
1769 * symbol as having the value zero.
1771 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1777 *defobj_out = defobj;
1778 /* Record the information in the cache to avoid subsequent lookups. */
1779 if (cache != NULL) {
1780 cache[symnum].sym = def;
1781 cache[symnum].obj = defobj;
1784 if (refobj != &obj_rtld)
1785 _rtld_error("%s: Undefined symbol \"%s%s%s\"", refobj->path, name,
1786 ve != NULL ? "@" : "", ve != NULL ? ve->name : "");
1792 * Return the search path from the ldconfig hints file, reading it if
1793 * necessary. If nostdlib is true, then the default search paths are
1794 * not added to result.
1796 * Returns NULL if there are problems with the hints file,
1797 * or if the search path there is empty.
1800 gethints(bool nostdlib)
1802 static char *filtered_path;
1803 static const char *hints;
1804 static struct elfhints_hdr hdr;
1805 struct fill_search_info_args sargs, hargs;
1806 struct dl_serinfo smeta, hmeta, *SLPinfo, *hintinfo;
1807 struct dl_serpath *SLPpath, *hintpath;
1809 struct stat hint_stat;
1810 unsigned int SLPndx, hintndx, fndx, fcount;
1816 /* First call, read the hints file */
1817 if (hints == NULL) {
1818 /* Keep from trying again in case the hints file is bad. */
1821 if ((fd = open(ld_elf_hints_path, O_RDONLY | O_CLOEXEC)) == -1)
1825 * Check of hdr.dirlistlen value against type limit
1826 * intends to pacify static analyzers. Further
1827 * paranoia leads to checks that dirlist is fully
1828 * contained in the file range.
1830 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1831 hdr.magic != ELFHINTS_MAGIC ||
1832 hdr.version != 1 || hdr.dirlistlen > UINT_MAX / 2 ||
1833 fstat(fd, &hint_stat) == -1) {
1840 if (dl + hdr.dirlist < dl)
1843 if (dl + hdr.dirlistlen < dl)
1845 dl += hdr.dirlistlen;
1846 if (dl > hint_stat.st_size)
1848 p = xmalloc(hdr.dirlistlen + 1);
1849 if (pread(fd, p, hdr.dirlistlen + 1,
1850 hdr.strtab + hdr.dirlist) != (ssize_t)hdr.dirlistlen + 1 ||
1851 p[hdr.dirlistlen] != '\0') {
1860 * If caller agreed to receive list which includes the default
1861 * paths, we are done. Otherwise, if we still did not
1862 * calculated filtered result, do it now.
1865 return (hints[0] != '\0' ? hints : NULL);
1866 if (filtered_path != NULL)
1870 * Obtain the list of all configured search paths, and the
1871 * list of the default paths.
1873 * First estimate the size of the results.
1875 smeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1877 hmeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1880 sargs.request = RTLD_DI_SERINFOSIZE;
1881 sargs.serinfo = &smeta;
1882 hargs.request = RTLD_DI_SERINFOSIZE;
1883 hargs.serinfo = &hmeta;
1885 path_enumerate(ld_standard_library_path, fill_search_info, NULL,
1887 path_enumerate(hints, fill_search_info, NULL, &hargs);
1889 SLPinfo = xmalloc(smeta.dls_size);
1890 hintinfo = xmalloc(hmeta.dls_size);
1893 * Next fetch both sets of paths.
1895 sargs.request = RTLD_DI_SERINFO;
1896 sargs.serinfo = SLPinfo;
1897 sargs.serpath = &SLPinfo->dls_serpath[0];
1898 sargs.strspace = (char *)&SLPinfo->dls_serpath[smeta.dls_cnt];
1900 hargs.request = RTLD_DI_SERINFO;
1901 hargs.serinfo = hintinfo;
1902 hargs.serpath = &hintinfo->dls_serpath[0];
1903 hargs.strspace = (char *)&hintinfo->dls_serpath[hmeta.dls_cnt];
1905 path_enumerate(ld_standard_library_path, fill_search_info, NULL,
1907 path_enumerate(hints, fill_search_info, NULL, &hargs);
1910 * Now calculate the difference between two sets, by excluding
1911 * standard paths from the full set.
1915 filtered_path = xmalloc(hdr.dirlistlen + 1);
1916 hintpath = &hintinfo->dls_serpath[0];
1917 for (hintndx = 0; hintndx < hmeta.dls_cnt; hintndx++, hintpath++) {
1919 SLPpath = &SLPinfo->dls_serpath[0];
1921 * Check each standard path against current.
1923 for (SLPndx = 0; SLPndx < smeta.dls_cnt; SLPndx++, SLPpath++) {
1924 /* matched, skip the path */
1925 if (!strcmp(hintpath->dls_name, SLPpath->dls_name)) {
1933 * Not matched against any standard path, add the path
1934 * to result. Separate consequtive paths with ':'.
1937 filtered_path[fndx] = ':';
1941 flen = strlen(hintpath->dls_name);
1942 strncpy((filtered_path + fndx), hintpath->dls_name, flen);
1945 filtered_path[fndx] = '\0';
1951 return (filtered_path[0] != '\0' ? filtered_path : NULL);
1955 init_dag(Obj_Entry *root)
1957 const Needed_Entry *needed;
1958 const Objlist_Entry *elm;
1961 if (root->dag_inited)
1963 donelist_init(&donelist);
1965 /* Root object belongs to own DAG. */
1966 objlist_push_tail(&root->dldags, root);
1967 objlist_push_tail(&root->dagmembers, root);
1968 donelist_check(&donelist, root);
1971 * Add dependencies of root object to DAG in breadth order
1972 * by exploiting the fact that each new object get added
1973 * to the tail of the dagmembers list.
1975 STAILQ_FOREACH(elm, &root->dagmembers, link) {
1976 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
1977 if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
1979 objlist_push_tail(&needed->obj->dldags, root);
1980 objlist_push_tail(&root->dagmembers, needed->obj);
1983 root->dag_inited = true;
1987 init_marker(Obj_Entry *marker)
1990 bzero(marker, sizeof(*marker));
1991 marker->marker = true;
1995 globallist_curr(const Obj_Entry *obj)
2002 return (__DECONST(Obj_Entry *, obj));
2003 obj = TAILQ_PREV(obj, obj_entry_q, next);
2008 globallist_next(const Obj_Entry *obj)
2012 obj = TAILQ_NEXT(obj, next);
2016 return (__DECONST(Obj_Entry *, obj));
2020 /* Prevent the object from being unmapped while the bind lock is dropped. */
2022 hold_object(Obj_Entry *obj)
2029 unhold_object(Obj_Entry *obj)
2032 assert(obj->holdcount > 0);
2033 if (--obj->holdcount == 0 && obj->unholdfree)
2034 release_object(obj);
2038 process_z(Obj_Entry *root)
2040 const Objlist_Entry *elm;
2044 * Walk over object DAG and process every dependent object
2045 * that is marked as DF_1_NODELETE or DF_1_GLOBAL. They need
2046 * to grow their own DAG.
2048 * For DF_1_GLOBAL, DAG is required for symbol lookups in
2049 * symlook_global() to work.
2051 * For DF_1_NODELETE, the DAG should have its reference upped.
2053 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2057 if (obj->z_nodelete && !obj->ref_nodel) {
2058 dbg("obj %s -z nodelete", obj->path);
2061 obj->ref_nodel = true;
2063 if (obj->z_global && objlist_find(&list_global, obj) == NULL) {
2064 dbg("obj %s -z global", obj->path);
2065 objlist_push_tail(&list_global, obj);
2071 * Initialize the dynamic linker. The argument is the address at which
2072 * the dynamic linker has been mapped into memory. The primary task of
2073 * this function is to relocate the dynamic linker.
2076 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
2078 Obj_Entry objtmp; /* Temporary rtld object */
2079 const Elf_Ehdr *ehdr;
2080 const Elf_Dyn *dyn_rpath;
2081 const Elf_Dyn *dyn_soname;
2082 const Elf_Dyn *dyn_runpath;
2084 #ifdef RTLD_INIT_PAGESIZES_EARLY
2085 /* The page size is required by the dynamic memory allocator. */
2086 init_pagesizes(aux_info);
2090 * Conjure up an Obj_Entry structure for the dynamic linker.
2092 * The "path" member can't be initialized yet because string constants
2093 * cannot yet be accessed. Below we will set it correctly.
2095 memset(&objtmp, 0, sizeof(objtmp));
2098 objtmp.mapbase = mapbase;
2100 objtmp.relocbase = mapbase;
2103 objtmp.dynamic = rtld_dynamic(&objtmp);
2104 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname, &dyn_runpath);
2105 assert(objtmp.needed == NULL);
2106 #if !defined(__mips__)
2107 /* MIPS has a bogus DT_TEXTREL. */
2108 assert(!objtmp.textrel);
2111 * Temporarily put the dynamic linker entry into the object list, so
2112 * that symbols can be found.
2114 relocate_objects(&objtmp, true, &objtmp, 0, NULL);
2116 ehdr = (Elf_Ehdr *)mapbase;
2117 objtmp.phdr = (Elf_Phdr *)((char *)mapbase + ehdr->e_phoff);
2118 objtmp.phsize = ehdr->e_phnum * sizeof(objtmp.phdr[0]);
2120 /* Initialize the object list. */
2121 TAILQ_INIT(&obj_list);
2123 /* Now that non-local variables can be accesses, copy out obj_rtld. */
2124 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
2126 #ifndef RTLD_INIT_PAGESIZES_EARLY
2127 /* The page size is required by the dynamic memory allocator. */
2128 init_pagesizes(aux_info);
2131 if (aux_info[AT_OSRELDATE] != NULL)
2132 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
2134 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname, dyn_runpath);
2136 /* Replace the path with a dynamically allocated copy. */
2137 obj_rtld.path = xstrdup(ld_path_rtld);
2139 r_debug.r_brk = r_debug_state;
2140 r_debug.r_state = RT_CONSISTENT;
2144 * Retrieve the array of supported page sizes. The kernel provides the page
2145 * sizes in increasing order.
2148 init_pagesizes(Elf_Auxinfo **aux_info)
2150 static size_t psa[MAXPAGESIZES];
2154 if (aux_info[AT_PAGESIZES] != NULL && aux_info[AT_PAGESIZESLEN] !=
2156 size = aux_info[AT_PAGESIZESLEN]->a_un.a_val;
2157 pagesizes = aux_info[AT_PAGESIZES]->a_un.a_ptr;
2160 if (sysctlnametomib("hw.pagesizes", mib, &len) == 0)
2163 /* As a fallback, retrieve the base page size. */
2164 size = sizeof(psa[0]);
2165 if (aux_info[AT_PAGESZ] != NULL) {
2166 psa[0] = aux_info[AT_PAGESZ]->a_un.a_val;
2170 mib[1] = HW_PAGESIZE;
2174 if (sysctl(mib, len, psa, &size, NULL, 0) == -1) {
2175 _rtld_error("sysctl for hw.pagesize(s) failed");
2181 npagesizes = size / sizeof(pagesizes[0]);
2182 /* Discard any invalid entries at the end of the array. */
2183 while (npagesizes > 0 && pagesizes[npagesizes - 1] == 0)
2188 * Add the init functions from a needed object list (and its recursive
2189 * needed objects) to "list". This is not used directly; it is a helper
2190 * function for initlist_add_objects(). The write lock must be held
2191 * when this function is called.
2194 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
2196 /* Recursively process the successor needed objects. */
2197 if (needed->next != NULL)
2198 initlist_add_neededs(needed->next, list);
2200 /* Process the current needed object. */
2201 if (needed->obj != NULL)
2202 initlist_add_objects(needed->obj, needed->obj, list);
2206 * Scan all of the DAGs rooted in the range of objects from "obj" to
2207 * "tail" and add their init functions to "list". This recurses over
2208 * the DAGs and ensure the proper init ordering such that each object's
2209 * needed libraries are initialized before the object itself. At the
2210 * same time, this function adds the objects to the global finalization
2211 * list "list_fini" in the opposite order. The write lock must be
2212 * held when this function is called.
2215 initlist_add_objects(Obj_Entry *obj, Obj_Entry *tail, Objlist *list)
2219 if (obj->init_scanned || obj->init_done)
2221 obj->init_scanned = true;
2223 /* Recursively process the successor objects. */
2224 nobj = globallist_next(obj);
2225 if (nobj != NULL && obj != tail)
2226 initlist_add_objects(nobj, tail, list);
2228 /* Recursively process the needed objects. */
2229 if (obj->needed != NULL)
2230 initlist_add_neededs(obj->needed, list);
2231 if (obj->needed_filtees != NULL)
2232 initlist_add_neededs(obj->needed_filtees, list);
2233 if (obj->needed_aux_filtees != NULL)
2234 initlist_add_neededs(obj->needed_aux_filtees, list);
2236 /* Add the object to the init list. */
2237 if (obj->preinit_array != (Elf_Addr)NULL || obj->init != (Elf_Addr)NULL ||
2238 obj->init_array != (Elf_Addr)NULL)
2239 objlist_push_tail(list, obj);
2241 /* Add the object to the global fini list in the reverse order. */
2242 if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL)
2243 && !obj->on_fini_list) {
2244 objlist_push_head(&list_fini, obj);
2245 obj->on_fini_list = true;
2250 #define FPTR_TARGET(f) ((Elf_Addr) (f))
2254 free_needed_filtees(Needed_Entry *n, RtldLockState *lockstate)
2256 Needed_Entry *needed, *needed1;
2258 for (needed = n; needed != NULL; needed = needed->next) {
2259 if (needed->obj != NULL) {
2260 dlclose_locked(needed->obj, lockstate);
2264 for (needed = n; needed != NULL; needed = needed1) {
2265 needed1 = needed->next;
2271 unload_filtees(Obj_Entry *obj, RtldLockState *lockstate)
2274 free_needed_filtees(obj->needed_filtees, lockstate);
2275 obj->needed_filtees = NULL;
2276 free_needed_filtees(obj->needed_aux_filtees, lockstate);
2277 obj->needed_aux_filtees = NULL;
2278 obj->filtees_loaded = false;
2282 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags,
2283 RtldLockState *lockstate)
2286 for (; needed != NULL; needed = needed->next) {
2287 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
2288 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
2289 RTLD_LOCAL, lockstate);
2294 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
2297 lock_restart_for_upgrade(lockstate);
2298 if (!obj->filtees_loaded) {
2299 load_filtee1(obj, obj->needed_filtees, flags, lockstate);
2300 load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate);
2301 obj->filtees_loaded = true;
2306 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
2310 for (; needed != NULL; needed = needed->next) {
2311 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
2312 flags & ~RTLD_LO_NOLOAD);
2313 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
2320 * Given a shared object, traverse its list of needed objects, and load
2321 * each of them. Returns 0 on success. Generates an error message and
2322 * returns -1 on failure.
2325 load_needed_objects(Obj_Entry *first, int flags)
2329 for (obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
2332 if (process_needed(obj, obj->needed, flags) == -1)
2339 load_preload_objects(void)
2341 char *p = ld_preload;
2343 static const char delim[] = " \t:;";
2348 p += strspn(p, delim);
2349 while (*p != '\0') {
2350 size_t len = strcspn(p, delim);
2355 obj = load_object(p, -1, NULL, 0);
2357 return -1; /* XXX - cleanup */
2358 obj->z_interpose = true;
2361 p += strspn(p, delim);
2363 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
2368 printable_path(const char *path)
2371 return (path == NULL ? "<unknown>" : path);
2375 * Load a shared object into memory, if it is not already loaded. The
2376 * object may be specified by name or by user-supplied file descriptor
2377 * fd_u. In the later case, the fd_u descriptor is not closed, but its
2380 * Returns a pointer to the Obj_Entry for the object. Returns NULL
2384 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
2393 TAILQ_FOREACH(obj, &obj_list, next) {
2394 if (obj->marker || obj->doomed)
2396 if (object_match_name(obj, name))
2400 path = find_library(name, refobj, &fd);
2408 * search_library_pathfds() opens a fresh file descriptor for the
2409 * library, so there is no need to dup().
2411 } else if (fd_u == -1) {
2413 * If we didn't find a match by pathname, or the name is not
2414 * supplied, open the file and check again by device and inode.
2415 * This avoids false mismatches caused by multiple links or ".."
2418 * To avoid a race, we open the file and use fstat() rather than
2421 if ((fd = open(path, O_RDONLY | O_CLOEXEC | O_VERIFY)) == -1) {
2422 _rtld_error("Cannot open \"%s\"", path);
2427 fd = fcntl(fd_u, F_DUPFD_CLOEXEC, 0);
2429 _rtld_error("Cannot dup fd");
2434 if (fstat(fd, &sb) == -1) {
2435 _rtld_error("Cannot fstat \"%s\"", printable_path(path));
2440 TAILQ_FOREACH(obj, &obj_list, next) {
2441 if (obj->marker || obj->doomed)
2443 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
2446 if (obj != NULL && name != NULL) {
2447 object_add_name(obj, name);
2452 if (flags & RTLD_LO_NOLOAD) {
2458 /* First use of this object, so we must map it in */
2459 obj = do_load_object(fd, name, path, &sb, flags);
2468 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
2475 * but first, make sure that environment variables haven't been
2476 * used to circumvent the noexec flag on a filesystem.
2478 if (dangerous_ld_env) {
2479 if (fstatfs(fd, &fs) != 0) {
2480 _rtld_error("Cannot fstatfs \"%s\"", printable_path(path));
2483 if (fs.f_flags & MNT_NOEXEC) {
2484 _rtld_error("Cannot execute objects on %s", fs.f_mntonname);
2488 dbg("loading \"%s\"", printable_path(path));
2489 obj = map_object(fd, printable_path(path), sbp);
2494 * If DT_SONAME is present in the object, digest_dynamic2 already
2495 * added it to the object names.
2498 object_add_name(obj, name);
2500 digest_dynamic(obj, 0);
2501 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path,
2502 obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount);
2503 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
2505 dbg("refusing to load non-loadable \"%s\"", obj->path);
2506 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
2507 munmap(obj->mapbase, obj->mapsize);
2512 obj->dlopened = (flags & RTLD_LO_DLOPEN) != 0;
2513 TAILQ_INSERT_TAIL(&obj_list, obj, next);
2516 linkmap_add(obj); /* for GDB & dlinfo() */
2517 max_stack_flags |= obj->stack_flags;
2519 dbg(" %p .. %p: %s", obj->mapbase,
2520 obj->mapbase + obj->mapsize - 1, obj->path);
2522 dbg(" WARNING: %s has impure text", obj->path);
2523 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
2530 obj_from_addr(const void *addr)
2534 TAILQ_FOREACH(obj, &obj_list, next) {
2537 if (addr < (void *) obj->mapbase)
2539 if (addr < (void *)(obj->mapbase + obj->mapsize))
2548 Elf_Addr *preinit_addr;
2551 preinit_addr = (Elf_Addr *)obj_main->preinit_array;
2552 if (preinit_addr == NULL)
2555 for (index = 0; index < obj_main->preinit_array_num; index++) {
2556 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) {
2557 dbg("calling preinit function for %s at %p", obj_main->path,
2558 (void *)preinit_addr[index]);
2559 LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index],
2560 0, 0, obj_main->path);
2561 call_init_pointer(obj_main, preinit_addr[index]);
2567 * Call the finalization functions for each of the objects in "list"
2568 * belonging to the DAG of "root" and referenced once. If NULL "root"
2569 * is specified, every finalization function will be called regardless
2570 * of the reference count and the list elements won't be freed. All of
2571 * the objects are expected to have non-NULL fini functions.
2574 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
2578 Elf_Addr *fini_addr;
2581 assert(root == NULL || root->refcount == 1);
2584 root->doomed = true;
2587 * Preserve the current error message since a fini function might
2588 * call into the dynamic linker and overwrite it.
2590 saved_msg = errmsg_save();
2592 STAILQ_FOREACH(elm, list, link) {
2593 if (root != NULL && (elm->obj->refcount != 1 ||
2594 objlist_find(&root->dagmembers, elm->obj) == NULL))
2596 /* Remove object from fini list to prevent recursive invocation. */
2597 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2598 /* Ensure that new references cannot be acquired. */
2599 elm->obj->doomed = true;
2601 hold_object(elm->obj);
2602 lock_release(rtld_bind_lock, lockstate);
2604 * It is legal to have both DT_FINI and DT_FINI_ARRAY defined.
2605 * When this happens, DT_FINI_ARRAY is processed first.
2607 fini_addr = (Elf_Addr *)elm->obj->fini_array;
2608 if (fini_addr != NULL && elm->obj->fini_array_num > 0) {
2609 for (index = elm->obj->fini_array_num - 1; index >= 0;
2611 if (fini_addr[index] != 0 && fini_addr[index] != 1) {
2612 dbg("calling fini function for %s at %p",
2613 elm->obj->path, (void *)fini_addr[index]);
2614 LD_UTRACE(UTRACE_FINI_CALL, elm->obj,
2615 (void *)fini_addr[index], 0, 0, elm->obj->path);
2616 call_initfini_pointer(elm->obj, fini_addr[index]);
2620 if (elm->obj->fini != (Elf_Addr)NULL) {
2621 dbg("calling fini function for %s at %p", elm->obj->path,
2622 (void *)elm->obj->fini);
2623 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini,
2624 0, 0, elm->obj->path);
2625 call_initfini_pointer(elm->obj, elm->obj->fini);
2627 wlock_acquire(rtld_bind_lock, lockstate);
2628 unhold_object(elm->obj);
2629 /* No need to free anything if process is going down. */
2633 * We must restart the list traversal after every fini call
2634 * because a dlclose() call from the fini function or from
2635 * another thread might have modified the reference counts.
2639 } while (elm != NULL);
2640 errmsg_restore(saved_msg);
2644 * Call the initialization functions for each of the objects in
2645 * "list". All of the objects are expected to have non-NULL init
2649 objlist_call_init(Objlist *list, RtldLockState *lockstate)
2654 Elf_Addr *init_addr;
2658 * Clean init_scanned flag so that objects can be rechecked and
2659 * possibly initialized earlier if any of vectors called below
2660 * cause the change by using dlopen.
2662 TAILQ_FOREACH(obj, &obj_list, next) {
2665 obj->init_scanned = false;
2669 * Preserve the current error message since an init function might
2670 * call into the dynamic linker and overwrite it.
2672 saved_msg = errmsg_save();
2673 STAILQ_FOREACH(elm, list, link) {
2674 if (elm->obj->init_done) /* Initialized early. */
2677 * Race: other thread might try to use this object before current
2678 * one completes the initialization. Not much can be done here
2679 * without better locking.
2681 elm->obj->init_done = true;
2682 hold_object(elm->obj);
2683 lock_release(rtld_bind_lock, lockstate);
2686 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined.
2687 * When this happens, DT_INIT is processed first.
2689 if (elm->obj->init != (Elf_Addr)NULL) {
2690 dbg("calling init function for %s at %p", elm->obj->path,
2691 (void *)elm->obj->init);
2692 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init,
2693 0, 0, elm->obj->path);
2694 call_initfini_pointer(elm->obj, elm->obj->init);
2696 init_addr = (Elf_Addr *)elm->obj->init_array;
2697 if (init_addr != NULL) {
2698 for (index = 0; index < elm->obj->init_array_num; index++) {
2699 if (init_addr[index] != 0 && init_addr[index] != 1) {
2700 dbg("calling init function for %s at %p", elm->obj->path,
2701 (void *)init_addr[index]);
2702 LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
2703 (void *)init_addr[index], 0, 0, elm->obj->path);
2704 call_init_pointer(elm->obj, init_addr[index]);
2708 wlock_acquire(rtld_bind_lock, lockstate);
2709 unhold_object(elm->obj);
2711 errmsg_restore(saved_msg);
2715 objlist_clear(Objlist *list)
2719 while (!STAILQ_EMPTY(list)) {
2720 elm = STAILQ_FIRST(list);
2721 STAILQ_REMOVE_HEAD(list, link);
2726 static Objlist_Entry *
2727 objlist_find(Objlist *list, const Obj_Entry *obj)
2731 STAILQ_FOREACH(elm, list, link)
2732 if (elm->obj == obj)
2738 objlist_init(Objlist *list)
2744 objlist_push_head(Objlist *list, Obj_Entry *obj)
2748 elm = NEW(Objlist_Entry);
2750 STAILQ_INSERT_HEAD(list, elm, link);
2754 objlist_push_tail(Objlist *list, Obj_Entry *obj)
2758 elm = NEW(Objlist_Entry);
2760 STAILQ_INSERT_TAIL(list, elm, link);
2764 objlist_put_after(Objlist *list, Obj_Entry *listobj, Obj_Entry *obj)
2766 Objlist_Entry *elm, *listelm;
2768 STAILQ_FOREACH(listelm, list, link) {
2769 if (listelm->obj == listobj)
2772 elm = NEW(Objlist_Entry);
2774 if (listelm != NULL)
2775 STAILQ_INSERT_AFTER(list, listelm, elm, link);
2777 STAILQ_INSERT_TAIL(list, elm, link);
2781 objlist_remove(Objlist *list, Obj_Entry *obj)
2785 if ((elm = objlist_find(list, obj)) != NULL) {
2786 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2792 * Relocate dag rooted in the specified object.
2793 * Returns 0 on success, or -1 on failure.
2797 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj,
2798 int flags, RtldLockState *lockstate)
2804 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2805 error = relocate_object(elm->obj, bind_now, rtldobj, flags,
2814 * Prepare for, or clean after, relocating an object marked with
2815 * DT_TEXTREL or DF_TEXTREL. Before relocating, all read-only
2816 * segments are remapped read-write. After relocations are done, the
2817 * segment's permissions are returned back to the modes specified in
2818 * the phdrs. If any relocation happened, or always for wired
2819 * program, COW is triggered.
2822 reloc_textrel_prot(Obj_Entry *obj, bool before)
2829 for (l = obj->phsize / sizeof(*ph), ph = obj->phdr; l > 0;
2831 if (ph->p_type != PT_LOAD || (ph->p_flags & PF_W) != 0)
2833 base = obj->relocbase + trunc_page(ph->p_vaddr);
2834 sz = round_page(ph->p_vaddr + ph->p_filesz) -
2835 trunc_page(ph->p_vaddr);
2836 prot = convert_prot(ph->p_flags) | (before ? PROT_WRITE : 0);
2837 if (mprotect(base, sz, prot) == -1) {
2838 _rtld_error("%s: Cannot write-%sable text segment: %s",
2839 obj->path, before ? "en" : "dis",
2840 rtld_strerror(errno));
2848 * Relocate single object.
2849 * Returns 0 on success, or -1 on failure.
2852 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
2853 int flags, RtldLockState *lockstate)
2858 obj->relocated = true;
2860 dbg("relocating \"%s\"", obj->path);
2862 if (obj->symtab == NULL || obj->strtab == NULL ||
2863 !(obj->valid_hash_sysv || obj->valid_hash_gnu)) {
2864 _rtld_error("%s: Shared object has no run-time symbol table",
2869 /* There are relocations to the write-protected text segment. */
2870 if (obj->textrel && reloc_textrel_prot(obj, true) != 0)
2873 /* Process the non-PLT non-IFUNC relocations. */
2874 if (reloc_non_plt(obj, rtldobj, flags, lockstate))
2877 /* Re-protected the text segment. */
2878 if (obj->textrel && reloc_textrel_prot(obj, false) != 0)
2881 /* Set the special PLT or GOT entries. */
2884 /* Process the PLT relocations. */
2885 if (reloc_plt(obj) == -1)
2887 /* Relocate the jump slots if we are doing immediate binding. */
2888 if (obj->bind_now || bind_now)
2889 if (reloc_jmpslots(obj, flags, lockstate) == -1)
2893 * Process the non-PLT IFUNC relocations. The relocations are
2894 * processed in two phases, because IFUNC resolvers may
2895 * reference other symbols, which must be readily processed
2896 * before resolvers are called.
2898 if (obj->non_plt_gnu_ifunc &&
2899 reloc_non_plt(obj, rtldobj, flags | SYMLOOK_IFUNC, lockstate))
2902 if (!obj->mainprog && obj_enforce_relro(obj) == -1)
2906 * Set up the magic number and version in the Obj_Entry. These
2907 * were checked in the crt1.o from the original ElfKit, so we
2908 * set them for backward compatibility.
2910 obj->magic = RTLD_MAGIC;
2911 obj->version = RTLD_VERSION;
2917 * Relocate newly-loaded shared objects. The argument is a pointer to
2918 * the Obj_Entry for the first such object. All objects from the first
2919 * to the end of the list of objects are relocated. Returns 0 on success,
2923 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
2924 int flags, RtldLockState *lockstate)
2929 for (error = 0, obj = first; obj != NULL;
2930 obj = TAILQ_NEXT(obj, next)) {
2933 error = relocate_object(obj, bind_now, rtldobj, flags,
2942 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
2943 * referencing STT_GNU_IFUNC symbols is postponed till the other
2944 * relocations are done. The indirect functions specified as
2945 * ifunc are allowed to call other symbols, so we need to have
2946 * objects relocated before asking for resolution from indirects.
2948 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
2949 * instead of the usual lazy handling of PLT slots. It is
2950 * consistent with how GNU does it.
2953 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags,
2954 RtldLockState *lockstate)
2956 if (obj->irelative && reloc_iresolve(obj, lockstate) == -1)
2958 if ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
2959 reloc_gnu_ifunc(obj, flags, lockstate) == -1)
2965 resolve_objects_ifunc(Obj_Entry *first, bool bind_now, int flags,
2966 RtldLockState *lockstate)
2970 for (obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
2973 if (resolve_object_ifunc(obj, bind_now, flags, lockstate) == -1)
2980 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags,
2981 RtldLockState *lockstate)
2985 STAILQ_FOREACH(elm, list, link) {
2986 if (resolve_object_ifunc(elm->obj, bind_now, flags,
2994 * Cleanup procedure. It will be called (by the atexit mechanism) just
2995 * before the process exits.
3000 RtldLockState lockstate;
3002 wlock_acquire(rtld_bind_lock, &lockstate);
3004 objlist_call_fini(&list_fini, NULL, &lockstate);
3005 /* No need to remove the items from the list, since we are exiting. */
3006 if (!libmap_disable)
3008 lock_release(rtld_bind_lock, &lockstate);
3012 * Iterate over a search path, translate each element, and invoke the
3013 * callback on the result.
3016 path_enumerate(const char *path, path_enum_proc callback,
3017 const char *refobj_path, void *arg)
3023 path += strspn(path, ":;");
3024 while (*path != '\0') {
3028 len = strcspn(path, ":;");
3029 trans = lm_findn(refobj_path, path, len);
3031 res = callback(trans, strlen(trans), arg);
3033 res = callback(path, len, arg);
3039 path += strspn(path, ":;");
3045 struct try_library_args {
3054 try_library_path(const char *dir, size_t dirlen, void *param)
3056 struct try_library_args *arg;
3060 if (*dir == '/' || trust) {
3063 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
3066 pathname = arg->buffer;
3067 strncpy(pathname, dir, dirlen);
3068 pathname[dirlen] = '/';
3069 strcpy(pathname + dirlen + 1, arg->name);
3071 dbg(" Trying \"%s\"", pathname);
3072 fd = open(pathname, O_RDONLY | O_CLOEXEC | O_VERIFY);
3074 dbg(" Opened \"%s\", fd %d", pathname, fd);
3075 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
3076 strcpy(pathname, arg->buffer);
3080 dbg(" Failed to open \"%s\": %s",
3081 pathname, rtld_strerror(errno));
3088 search_library_path(const char *name, const char *path,
3089 const char *refobj_path, int *fdp)
3092 struct try_library_args arg;
3098 arg.namelen = strlen(name);
3099 arg.buffer = xmalloc(PATH_MAX);
3100 arg.buflen = PATH_MAX;
3103 p = path_enumerate(path, try_library_path, refobj_path, &arg);
3113 * Finds the library with the given name using the directory descriptors
3114 * listed in the LD_LIBRARY_PATH_FDS environment variable.
3116 * Returns a freshly-opened close-on-exec file descriptor for the library,
3117 * or -1 if the library cannot be found.
3120 search_library_pathfds(const char *name, const char *path, int *fdp)
3122 char *envcopy, *fdstr, *found, *last_token;
3126 dbg("%s('%s', '%s', fdp)", __func__, name, path);
3128 /* Don't load from user-specified libdirs into setuid binaries. */
3132 /* We can't do anything if LD_LIBRARY_PATH_FDS isn't set. */
3136 /* LD_LIBRARY_PATH_FDS only works with relative paths. */
3137 if (name[0] == '/') {
3138 dbg("Absolute path (%s) passed to %s", name, __func__);
3143 * Use strtok_r() to walk the FD:FD:FD list. This requires a local
3144 * copy of the path, as strtok_r rewrites separator tokens
3148 envcopy = xstrdup(path);
3149 for (fdstr = strtok_r(envcopy, ":", &last_token); fdstr != NULL;
3150 fdstr = strtok_r(NULL, ":", &last_token)) {
3151 dirfd = parse_integer(fdstr);
3153 _rtld_error("failed to parse directory FD: '%s'",
3157 fd = __sys_openat(dirfd, name, O_RDONLY | O_CLOEXEC | O_VERIFY);
3160 len = strlen(fdstr) + strlen(name) + 3;
3161 found = xmalloc(len);
3162 if (rtld_snprintf(found, len, "#%d/%s", dirfd, name) < 0) {
3163 _rtld_error("error generating '%d/%s'",
3167 dbg("open('%s') => %d", found, fd);
3178 dlclose(void *handle)
3180 RtldLockState lockstate;
3183 wlock_acquire(rtld_bind_lock, &lockstate);
3184 error = dlclose_locked(handle, &lockstate);
3185 lock_release(rtld_bind_lock, &lockstate);
3190 dlclose_locked(void *handle, RtldLockState *lockstate)
3194 root = dlcheck(handle);
3197 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
3200 /* Unreference the object and its dependencies. */
3201 root->dl_refcount--;
3203 if (root->refcount == 1) {
3205 * The object will be no longer referenced, so we must unload it.
3206 * First, call the fini functions.
3208 objlist_call_fini(&list_fini, root, lockstate);
3212 /* Finish cleaning up the newly-unreferenced objects. */
3213 GDB_STATE(RT_DELETE,&root->linkmap);
3214 unload_object(root, lockstate);
3215 GDB_STATE(RT_CONSISTENT,NULL);
3219 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
3226 char *msg = error_message;
3227 error_message = NULL;
3232 * This function is deprecated and has no effect.
3235 dllockinit(void *context,
3236 void *(*_lock_create)(void *context) __unused,
3237 void (*_rlock_acquire)(void *lock) __unused,
3238 void (*_wlock_acquire)(void *lock) __unused,
3239 void (*_lock_release)(void *lock) __unused,
3240 void (*_lock_destroy)(void *lock) __unused,
3241 void (*context_destroy)(void *context))
3243 static void *cur_context;
3244 static void (*cur_context_destroy)(void *);
3246 /* Just destroy the context from the previous call, if necessary. */
3247 if (cur_context_destroy != NULL)
3248 cur_context_destroy(cur_context);
3249 cur_context = context;
3250 cur_context_destroy = context_destroy;
3254 dlopen(const char *name, int mode)
3257 return (rtld_dlopen(name, -1, mode));
3261 fdlopen(int fd, int mode)
3264 return (rtld_dlopen(NULL, fd, mode));
3268 rtld_dlopen(const char *name, int fd, int mode)
3270 RtldLockState lockstate;
3273 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
3274 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
3275 if (ld_tracing != NULL) {
3276 rlock_acquire(rtld_bind_lock, &lockstate);
3277 if (sigsetjmp(lockstate.env, 0) != 0)
3278 lock_upgrade(rtld_bind_lock, &lockstate);
3279 environ = __DECONST(char **, *get_program_var_addr("environ", &lockstate));
3280 lock_release(rtld_bind_lock, &lockstate);
3282 lo_flags = RTLD_LO_DLOPEN;
3283 if (mode & RTLD_NODELETE)
3284 lo_flags |= RTLD_LO_NODELETE;
3285 if (mode & RTLD_NOLOAD)
3286 lo_flags |= RTLD_LO_NOLOAD;
3287 if (ld_tracing != NULL)
3288 lo_flags |= RTLD_LO_TRACE;
3290 return (dlopen_object(name, fd, obj_main, lo_flags,
3291 mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL));
3295 dlopen_cleanup(Obj_Entry *obj, RtldLockState *lockstate)
3300 if (obj->refcount == 0)
3301 unload_object(obj, lockstate);
3305 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
3306 int mode, RtldLockState *lockstate)
3308 Obj_Entry *old_obj_tail;
3311 RtldLockState mlockstate;
3314 objlist_init(&initlist);
3316 if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) {
3317 wlock_acquire(rtld_bind_lock, &mlockstate);
3318 lockstate = &mlockstate;
3320 GDB_STATE(RT_ADD,NULL);
3322 old_obj_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
3324 if (name == NULL && fd == -1) {
3328 obj = load_object(name, fd, refobj, lo_flags);
3333 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
3334 objlist_push_tail(&list_global, obj);
3335 if (globallist_next(old_obj_tail) != NULL) {
3336 /* We loaded something new. */
3337 assert(globallist_next(old_obj_tail) == obj);
3338 result = load_needed_objects(obj,
3339 lo_flags & (RTLD_LO_DLOPEN | RTLD_LO_EARLY));
3343 result = rtld_verify_versions(&obj->dagmembers);
3344 if (result != -1 && ld_tracing)
3346 if (result == -1 || relocate_object_dag(obj,
3347 (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld,
3348 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3350 dlopen_cleanup(obj, lockstate);
3352 } else if (lo_flags & RTLD_LO_EARLY) {
3354 * Do not call the init functions for early loaded
3355 * filtees. The image is still not initialized enough
3358 * Our object is found by the global object list and
3359 * will be ordered among all init calls done right
3360 * before transferring control to main.
3363 /* Make list of init functions to call. */
3364 initlist_add_objects(obj, obj, &initlist);
3367 * Process all no_delete or global objects here, given
3368 * them own DAGs to prevent their dependencies from being
3369 * unloaded. This has to be done after we have loaded all
3370 * of the dependencies, so that we do not miss any.
3376 * Bump the reference counts for objects on this DAG. If
3377 * this is the first dlopen() call for the object that was
3378 * already loaded as a dependency, initialize the dag
3384 if ((lo_flags & RTLD_LO_TRACE) != 0)
3387 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
3388 obj->z_nodelete) && !obj->ref_nodel) {
3389 dbg("obj %s nodelete", obj->path);
3391 obj->z_nodelete = obj->ref_nodel = true;
3395 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
3397 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
3399 if (!(lo_flags & RTLD_LO_EARLY)) {
3400 map_stacks_exec(lockstate);
3403 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
3404 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3406 objlist_clear(&initlist);
3407 dlopen_cleanup(obj, lockstate);
3408 if (lockstate == &mlockstate)
3409 lock_release(rtld_bind_lock, lockstate);
3413 if (!(lo_flags & RTLD_LO_EARLY)) {
3414 /* Call the init functions. */
3415 objlist_call_init(&initlist, lockstate);
3417 objlist_clear(&initlist);
3418 if (lockstate == &mlockstate)
3419 lock_release(rtld_bind_lock, lockstate);
3422 trace_loaded_objects(obj);
3423 if (lockstate == &mlockstate)
3424 lock_release(rtld_bind_lock, lockstate);
3429 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
3433 const Obj_Entry *obj, *defobj;
3436 RtldLockState lockstate;
3443 symlook_init(&req, name);
3445 req.flags = flags | SYMLOOK_IN_PLT;
3446 req.lockstate = &lockstate;
3448 LD_UTRACE(UTRACE_DLSYM_START, handle, NULL, 0, 0, name);
3449 rlock_acquire(rtld_bind_lock, &lockstate);
3450 if (sigsetjmp(lockstate.env, 0) != 0)
3451 lock_upgrade(rtld_bind_lock, &lockstate);
3452 if (handle == NULL || handle == RTLD_NEXT ||
3453 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
3455 if ((obj = obj_from_addr(retaddr)) == NULL) {
3456 _rtld_error("Cannot determine caller's shared object");
3457 lock_release(rtld_bind_lock, &lockstate);
3458 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3461 if (handle == NULL) { /* Just the caller's shared object. */
3462 res = symlook_obj(&req, obj);
3465 defobj = req.defobj_out;
3467 } else if (handle == RTLD_NEXT || /* Objects after caller's */
3468 handle == RTLD_SELF) { /* ... caller included */
3469 if (handle == RTLD_NEXT)
3470 obj = globallist_next(obj);
3471 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
3474 res = symlook_obj(&req, obj);
3477 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) {
3479 defobj = req.defobj_out;
3480 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3486 * Search the dynamic linker itself, and possibly resolve the
3487 * symbol from there. This is how the application links to
3488 * dynamic linker services such as dlopen.
3490 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3491 res = symlook_obj(&req, &obj_rtld);
3494 defobj = req.defobj_out;
3498 assert(handle == RTLD_DEFAULT);
3499 res = symlook_default(&req, obj);
3501 defobj = req.defobj_out;
3506 if ((obj = dlcheck(handle)) == NULL) {
3507 lock_release(rtld_bind_lock, &lockstate);
3508 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3512 donelist_init(&donelist);
3513 if (obj->mainprog) {
3514 /* Handle obtained by dlopen(NULL, ...) implies global scope. */
3515 res = symlook_global(&req, &donelist);
3518 defobj = req.defobj_out;
3521 * Search the dynamic linker itself, and possibly resolve the
3522 * symbol from there. This is how the application links to
3523 * dynamic linker services such as dlopen.
3525 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3526 res = symlook_obj(&req, &obj_rtld);
3529 defobj = req.defobj_out;
3534 /* Search the whole DAG rooted at the given object. */
3535 res = symlook_list(&req, &obj->dagmembers, &donelist);
3538 defobj = req.defobj_out;
3544 lock_release(rtld_bind_lock, &lockstate);
3547 * The value required by the caller is derived from the value
3548 * of the symbol. this is simply the relocated value of the
3551 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
3552 sym = make_function_pointer(def, defobj);
3553 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
3554 sym = rtld_resolve_ifunc(defobj, def);
3555 else if (ELF_ST_TYPE(def->st_info) == STT_TLS) {
3556 ti.ti_module = defobj->tlsindex;
3557 ti.ti_offset = def->st_value;
3558 sym = __tls_get_addr(&ti);
3560 sym = defobj->relocbase + def->st_value;
3561 LD_UTRACE(UTRACE_DLSYM_STOP, handle, sym, 0, 0, name);
3565 _rtld_error("Undefined symbol \"%s%s%s\"", name, ve != NULL ? "@" : "",
3566 ve != NULL ? ve->name : "");
3567 lock_release(rtld_bind_lock, &lockstate);
3568 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3573 dlsym(void *handle, const char *name)
3575 return do_dlsym(handle, name, __builtin_return_address(0), NULL,
3580 dlfunc(void *handle, const char *name)
3587 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
3593 dlvsym(void *handle, const char *name, const char *version)
3597 ventry.name = version;
3599 ventry.hash = elf_hash(version);
3601 return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
3606 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
3608 const Obj_Entry *obj;
3609 RtldLockState lockstate;
3611 rlock_acquire(rtld_bind_lock, &lockstate);
3612 obj = obj_from_addr(addr);
3614 _rtld_error("No shared object contains address");
3615 lock_release(rtld_bind_lock, &lockstate);
3618 rtld_fill_dl_phdr_info(obj, phdr_info);
3619 lock_release(rtld_bind_lock, &lockstate);
3624 dladdr(const void *addr, Dl_info *info)
3626 const Obj_Entry *obj;
3629 unsigned long symoffset;
3630 RtldLockState lockstate;
3632 rlock_acquire(rtld_bind_lock, &lockstate);
3633 obj = obj_from_addr(addr);
3635 _rtld_error("No shared object contains address");
3636 lock_release(rtld_bind_lock, &lockstate);
3639 info->dli_fname = obj->path;
3640 info->dli_fbase = obj->mapbase;
3641 info->dli_saddr = (void *)0;
3642 info->dli_sname = NULL;
3645 * Walk the symbol list looking for the symbol whose address is
3646 * closest to the address sent in.
3648 for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) {
3649 def = obj->symtab + symoffset;
3652 * For skip the symbol if st_shndx is either SHN_UNDEF or
3655 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
3659 * If the symbol is greater than the specified address, or if it
3660 * is further away from addr than the current nearest symbol,
3663 symbol_addr = obj->relocbase + def->st_value;
3664 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
3667 /* Update our idea of the nearest symbol. */
3668 info->dli_sname = obj->strtab + def->st_name;
3669 info->dli_saddr = symbol_addr;
3672 if (info->dli_saddr == addr)
3675 lock_release(rtld_bind_lock, &lockstate);
3680 dlinfo(void *handle, int request, void *p)
3682 const Obj_Entry *obj;
3683 RtldLockState lockstate;
3686 rlock_acquire(rtld_bind_lock, &lockstate);
3688 if (handle == NULL || handle == RTLD_SELF) {
3691 retaddr = __builtin_return_address(0); /* __GNUC__ only */
3692 if ((obj = obj_from_addr(retaddr)) == NULL)
3693 _rtld_error("Cannot determine caller's shared object");
3695 obj = dlcheck(handle);
3698 lock_release(rtld_bind_lock, &lockstate);
3704 case RTLD_DI_LINKMAP:
3705 *((struct link_map const **)p) = &obj->linkmap;
3707 case RTLD_DI_ORIGIN:
3708 error = rtld_dirname(obj->path, p);
3711 case RTLD_DI_SERINFOSIZE:
3712 case RTLD_DI_SERINFO:
3713 error = do_search_info(obj, request, (struct dl_serinfo *)p);
3717 _rtld_error("Invalid request %d passed to dlinfo()", request);
3721 lock_release(rtld_bind_lock, &lockstate);
3727 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
3730 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
3731 phdr_info->dlpi_name = obj->path;
3732 phdr_info->dlpi_phdr = obj->phdr;
3733 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
3734 phdr_info->dlpi_tls_modid = obj->tlsindex;
3735 phdr_info->dlpi_tls_data = obj->tlsinit;
3736 phdr_info->dlpi_adds = obj_loads;
3737 phdr_info->dlpi_subs = obj_loads - obj_count;
3741 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
3743 struct dl_phdr_info phdr_info;
3744 Obj_Entry *obj, marker;
3745 RtldLockState bind_lockstate, phdr_lockstate;
3748 init_marker(&marker);
3751 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
3752 wlock_acquire(rtld_bind_lock, &bind_lockstate);
3753 for (obj = globallist_curr(TAILQ_FIRST(&obj_list)); obj != NULL;) {
3754 TAILQ_INSERT_AFTER(&obj_list, obj, &marker, next);
3755 rtld_fill_dl_phdr_info(obj, &phdr_info);
3757 lock_release(rtld_bind_lock, &bind_lockstate);
3759 error = callback(&phdr_info, sizeof phdr_info, param);
3761 wlock_acquire(rtld_bind_lock, &bind_lockstate);
3763 obj = globallist_next(&marker);
3764 TAILQ_REMOVE(&obj_list, &marker, next);
3766 lock_release(rtld_bind_lock, &bind_lockstate);
3767 lock_release(rtld_phdr_lock, &phdr_lockstate);
3773 rtld_fill_dl_phdr_info(&obj_rtld, &phdr_info);
3774 lock_release(rtld_bind_lock, &bind_lockstate);
3775 error = callback(&phdr_info, sizeof(phdr_info), param);
3777 lock_release(rtld_phdr_lock, &phdr_lockstate);
3782 fill_search_info(const char *dir, size_t dirlen, void *param)
3784 struct fill_search_info_args *arg;
3788 if (arg->request == RTLD_DI_SERINFOSIZE) {
3789 arg->serinfo->dls_cnt ++;
3790 arg->serinfo->dls_size += sizeof(struct dl_serpath) + dirlen + 1;
3792 struct dl_serpath *s_entry;
3794 s_entry = arg->serpath;
3795 s_entry->dls_name = arg->strspace;
3796 s_entry->dls_flags = arg->flags;
3798 strncpy(arg->strspace, dir, dirlen);
3799 arg->strspace[dirlen] = '\0';
3801 arg->strspace += dirlen + 1;
3809 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
3811 struct dl_serinfo _info;
3812 struct fill_search_info_args args;
3814 args.request = RTLD_DI_SERINFOSIZE;
3815 args.serinfo = &_info;
3817 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
3820 path_enumerate(obj->rpath, fill_search_info, NULL, &args);
3821 path_enumerate(ld_library_path, fill_search_info, NULL, &args);
3822 path_enumerate(obj->runpath, fill_search_info, NULL, &args);
3823 path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args);
3824 if (!obj->z_nodeflib)
3825 path_enumerate(ld_standard_library_path, fill_search_info, NULL, &args);
3828 if (request == RTLD_DI_SERINFOSIZE) {
3829 info->dls_size = _info.dls_size;
3830 info->dls_cnt = _info.dls_cnt;
3834 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
3835 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
3839 args.request = RTLD_DI_SERINFO;
3840 args.serinfo = info;
3841 args.serpath = &info->dls_serpath[0];
3842 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
3844 args.flags = LA_SER_RUNPATH;
3845 if (path_enumerate(obj->rpath, fill_search_info, NULL, &args) != NULL)
3848 args.flags = LA_SER_LIBPATH;
3849 if (path_enumerate(ld_library_path, fill_search_info, NULL, &args) != NULL)
3852 args.flags = LA_SER_RUNPATH;
3853 if (path_enumerate(obj->runpath, fill_search_info, NULL, &args) != NULL)
3856 args.flags = LA_SER_CONFIG;
3857 if (path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args)
3861 args.flags = LA_SER_DEFAULT;
3862 if (!obj->z_nodeflib && path_enumerate(ld_standard_library_path,
3863 fill_search_info, NULL, &args) != NULL)
3869 rtld_dirname(const char *path, char *bname)
3873 /* Empty or NULL string gets treated as "." */
3874 if (path == NULL || *path == '\0') {
3880 /* Strip trailing slashes */
3881 endp = path + strlen(path) - 1;
3882 while (endp > path && *endp == '/')
3885 /* Find the start of the dir */
3886 while (endp > path && *endp != '/')
3889 /* Either the dir is "/" or there are no slashes */
3891 bname[0] = *endp == '/' ? '/' : '.';
3897 } while (endp > path && *endp == '/');
3900 if (endp - path + 2 > PATH_MAX)
3902 _rtld_error("Filename is too long: %s", path);
3906 strncpy(bname, path, endp - path + 1);
3907 bname[endp - path + 1] = '\0';
3912 rtld_dirname_abs(const char *path, char *base)
3916 if (realpath(path, base) == NULL)
3918 dbg("%s -> %s", path, base);
3919 last = strrchr(base, '/');
3928 linkmap_add(Obj_Entry *obj)
3930 struct link_map *l = &obj->linkmap;
3931 struct link_map *prev;
3933 obj->linkmap.l_name = obj->path;
3934 obj->linkmap.l_addr = obj->mapbase;
3935 obj->linkmap.l_ld = obj->dynamic;
3937 /* GDB needs load offset on MIPS to use the symbols */
3938 obj->linkmap.l_offs = obj->relocbase;
3941 if (r_debug.r_map == NULL) {
3947 * Scan to the end of the list, but not past the entry for the
3948 * dynamic linker, which we want to keep at the very end.
3950 for (prev = r_debug.r_map;
3951 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
3952 prev = prev->l_next)
3955 /* Link in the new entry. */
3957 l->l_next = prev->l_next;
3958 if (l->l_next != NULL)
3959 l->l_next->l_prev = l;
3964 linkmap_delete(Obj_Entry *obj)
3966 struct link_map *l = &obj->linkmap;
3968 if (l->l_prev == NULL) {
3969 if ((r_debug.r_map = l->l_next) != NULL)
3970 l->l_next->l_prev = NULL;
3974 if ((l->l_prev->l_next = l->l_next) != NULL)
3975 l->l_next->l_prev = l->l_prev;
3979 * Function for the debugger to set a breakpoint on to gain control.
3981 * The two parameters allow the debugger to easily find and determine
3982 * what the runtime loader is doing and to whom it is doing it.
3984 * When the loadhook trap is hit (r_debug_state, set at program
3985 * initialization), the arguments can be found on the stack:
3987 * +8 struct link_map *m
3988 * +4 struct r_debug *rd
3992 r_debug_state(struct r_debug* rd __unused, struct link_map *m __unused)
3995 * The following is a hack to force the compiler to emit calls to
3996 * this function, even when optimizing. If the function is empty,
3997 * the compiler is not obliged to emit any code for calls to it,
3998 * even when marked __noinline. However, gdb depends on those
4001 __compiler_membar();
4005 * A function called after init routines have completed. This can be used to
4006 * break before a program's entry routine is called, and can be used when
4007 * main is not available in the symbol table.
4010 _r_debug_postinit(struct link_map *m __unused)
4013 /* See r_debug_state(). */
4014 __compiler_membar();
4018 release_object(Obj_Entry *obj)
4021 if (obj->holdcount > 0) {
4022 obj->unholdfree = true;
4025 munmap(obj->mapbase, obj->mapsize);
4026 linkmap_delete(obj);
4031 * Get address of the pointer variable in the main program.
4032 * Prefer non-weak symbol over the weak one.
4034 static const void **
4035 get_program_var_addr(const char *name, RtldLockState *lockstate)
4040 symlook_init(&req, name);
4041 req.lockstate = lockstate;
4042 donelist_init(&donelist);
4043 if (symlook_global(&req, &donelist) != 0)
4045 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
4046 return ((const void **)make_function_pointer(req.sym_out,
4048 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
4049 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
4051 return ((const void **)(req.defobj_out->relocbase +
4052 req.sym_out->st_value));
4056 * Set a pointer variable in the main program to the given value. This
4057 * is used to set key variables such as "environ" before any of the
4058 * init functions are called.
4061 set_program_var(const char *name, const void *value)
4065 if ((addr = get_program_var_addr(name, NULL)) != NULL) {
4066 dbg("\"%s\": *%p <-- %p", name, addr, value);
4072 * Search the global objects, including dependencies and main object,
4073 * for the given symbol.
4076 symlook_global(SymLook *req, DoneList *donelist)
4079 const Objlist_Entry *elm;
4082 symlook_init_from_req(&req1, req);
4084 /* Search all objects loaded at program start up. */
4085 if (req->defobj_out == NULL ||
4086 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
4087 res = symlook_list(&req1, &list_main, donelist);
4088 if (res == 0 && (req->defobj_out == NULL ||
4089 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4090 req->sym_out = req1.sym_out;
4091 req->defobj_out = req1.defobj_out;
4092 assert(req->defobj_out != NULL);
4096 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
4097 STAILQ_FOREACH(elm, &list_global, link) {
4098 if (req->defobj_out != NULL &&
4099 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
4101 res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
4102 if (res == 0 && (req->defobj_out == NULL ||
4103 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4104 req->sym_out = req1.sym_out;
4105 req->defobj_out = req1.defobj_out;
4106 assert(req->defobj_out != NULL);
4110 return (req->sym_out != NULL ? 0 : ESRCH);
4114 * Given a symbol name in a referencing object, find the corresponding
4115 * definition of the symbol. Returns a pointer to the symbol, or NULL if
4116 * no definition was found. Returns a pointer to the Obj_Entry of the
4117 * defining object via the reference parameter DEFOBJ_OUT.
4120 symlook_default(SymLook *req, const Obj_Entry *refobj)
4123 const Objlist_Entry *elm;
4127 donelist_init(&donelist);
4128 symlook_init_from_req(&req1, req);
4131 * Look first in the referencing object if linked symbolically,
4132 * and similarly handle protected symbols.
4134 res = symlook_obj(&req1, refobj);
4135 if (res == 0 && (refobj->symbolic ||
4136 ELF_ST_VISIBILITY(req1.sym_out->st_other) == STV_PROTECTED)) {
4137 req->sym_out = req1.sym_out;
4138 req->defobj_out = req1.defobj_out;
4139 assert(req->defobj_out != NULL);
4141 if (refobj->symbolic || req->defobj_out != NULL)
4142 donelist_check(&donelist, refobj);
4144 symlook_global(req, &donelist);
4146 /* Search all dlopened DAGs containing the referencing object. */
4147 STAILQ_FOREACH(elm, &refobj->dldags, link) {
4148 if (req->sym_out != NULL &&
4149 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
4151 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
4152 if (res == 0 && (req->sym_out == NULL ||
4153 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4154 req->sym_out = req1.sym_out;
4155 req->defobj_out = req1.defobj_out;
4156 assert(req->defobj_out != NULL);
4161 * Search the dynamic linker itself, and possibly resolve the
4162 * symbol from there. This is how the application links to
4163 * dynamic linker services such as dlopen.
4165 if (req->sym_out == NULL ||
4166 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
4167 res = symlook_obj(&req1, &obj_rtld);
4169 req->sym_out = req1.sym_out;
4170 req->defobj_out = req1.defobj_out;
4171 assert(req->defobj_out != NULL);
4175 return (req->sym_out != NULL ? 0 : ESRCH);
4179 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
4182 const Obj_Entry *defobj;
4183 const Objlist_Entry *elm;
4189 STAILQ_FOREACH(elm, objlist, link) {
4190 if (donelist_check(dlp, elm->obj))
4192 symlook_init_from_req(&req1, req);
4193 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
4194 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
4196 defobj = req1.defobj_out;
4197 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
4204 req->defobj_out = defobj;
4211 * Search the chain of DAGS cointed to by the given Needed_Entry
4212 * for a symbol of the given name. Each DAG is scanned completely
4213 * before advancing to the next one. Returns a pointer to the symbol,
4214 * or NULL if no definition was found.
4217 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
4220 const Needed_Entry *n;
4221 const Obj_Entry *defobj;
4227 symlook_init_from_req(&req1, req);
4228 for (n = needed; n != NULL; n = n->next) {
4229 if (n->obj == NULL ||
4230 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
4232 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
4234 defobj = req1.defobj_out;
4235 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
4241 req->defobj_out = defobj;
4248 * Search the symbol table of a single shared object for a symbol of
4249 * the given name and version, if requested. Returns a pointer to the
4250 * symbol, or NULL if no definition was found. If the object is
4251 * filter, return filtered symbol from filtee.
4253 * The symbol's hash value is passed in for efficiency reasons; that
4254 * eliminates many recomputations of the hash value.
4257 symlook_obj(SymLook *req, const Obj_Entry *obj)
4261 int flags, res, mres;
4264 * If there is at least one valid hash at this point, we prefer to
4265 * use the faster GNU version if available.
4267 if (obj->valid_hash_gnu)
4268 mres = symlook_obj1_gnu(req, obj);
4269 else if (obj->valid_hash_sysv)
4270 mres = symlook_obj1_sysv(req, obj);
4275 if (obj->needed_filtees != NULL) {
4276 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4277 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4278 donelist_init(&donelist);
4279 symlook_init_from_req(&req1, req);
4280 res = symlook_needed(&req1, obj->needed_filtees, &donelist);
4282 req->sym_out = req1.sym_out;
4283 req->defobj_out = req1.defobj_out;
4287 if (obj->needed_aux_filtees != NULL) {
4288 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4289 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4290 donelist_init(&donelist);
4291 symlook_init_from_req(&req1, req);
4292 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
4294 req->sym_out = req1.sym_out;
4295 req->defobj_out = req1.defobj_out;
4303 /* Symbol match routine common to both hash functions */
4305 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result,
4306 const unsigned long symnum)
4309 const Elf_Sym *symp;
4312 symp = obj->symtab + symnum;
4313 strp = obj->strtab + symp->st_name;
4315 switch (ELF_ST_TYPE(symp->st_info)) {
4321 if (symp->st_value == 0)
4325 if (symp->st_shndx != SHN_UNDEF)
4328 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
4329 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
4336 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
4339 if (req->ventry == NULL) {
4340 if (obj->versyms != NULL) {
4341 verndx = VER_NDX(obj->versyms[symnum]);
4342 if (verndx > obj->vernum) {
4344 "%s: symbol %s references wrong version %d",
4345 obj->path, obj->strtab + symnum, verndx);
4349 * If we are not called from dlsym (i.e. this
4350 * is a normal relocation from unversioned
4351 * binary), accept the symbol immediately if
4352 * it happens to have first version after this
4353 * shared object became versioned. Otherwise,
4354 * if symbol is versioned and not hidden,
4355 * remember it. If it is the only symbol with
4356 * this name exported by the shared object, it
4357 * will be returned as a match by the calling
4358 * function. If symbol is global (verndx < 2)
4359 * accept it unconditionally.
4361 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
4362 verndx == VER_NDX_GIVEN) {
4363 result->sym_out = symp;
4366 else if (verndx >= VER_NDX_GIVEN) {
4367 if ((obj->versyms[symnum] & VER_NDX_HIDDEN)
4369 if (result->vsymp == NULL)
4370 result->vsymp = symp;
4376 result->sym_out = symp;
4379 if (obj->versyms == NULL) {
4380 if (object_match_name(obj, req->ventry->name)) {
4381 _rtld_error("%s: object %s should provide version %s "
4382 "for symbol %s", obj_rtld.path, obj->path,
4383 req->ventry->name, obj->strtab + symnum);
4387 verndx = VER_NDX(obj->versyms[symnum]);
4388 if (verndx > obj->vernum) {
4389 _rtld_error("%s: symbol %s references wrong version %d",
4390 obj->path, obj->strtab + symnum, verndx);
4393 if (obj->vertab[verndx].hash != req->ventry->hash ||
4394 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
4396 * Version does not match. Look if this is a
4397 * global symbol and if it is not hidden. If
4398 * global symbol (verndx < 2) is available,
4399 * use it. Do not return symbol if we are
4400 * called by dlvsym, because dlvsym looks for
4401 * a specific version and default one is not
4402 * what dlvsym wants.
4404 if ((req->flags & SYMLOOK_DLSYM) ||
4405 (verndx >= VER_NDX_GIVEN) ||
4406 (obj->versyms[symnum] & VER_NDX_HIDDEN))
4410 result->sym_out = symp;
4415 * Search for symbol using SysV hash function.
4416 * obj->buckets is known not to be NULL at this point; the test for this was
4417 * performed with the obj->valid_hash_sysv assignment.
4420 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj)
4422 unsigned long symnum;
4423 Sym_Match_Result matchres;
4425 matchres.sym_out = NULL;
4426 matchres.vsymp = NULL;
4427 matchres.vcount = 0;
4429 for (symnum = obj->buckets[req->hash % obj->nbuckets];
4430 symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
4431 if (symnum >= obj->nchains)
4432 return (ESRCH); /* Bad object */
4434 if (matched_symbol(req, obj, &matchres, symnum)) {
4435 req->sym_out = matchres.sym_out;
4436 req->defobj_out = obj;
4440 if (matchres.vcount == 1) {
4441 req->sym_out = matchres.vsymp;
4442 req->defobj_out = obj;
4448 /* Search for symbol using GNU hash function */
4450 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj)
4452 Elf_Addr bloom_word;
4453 const Elf32_Word *hashval;
4455 Sym_Match_Result matchres;
4456 unsigned int h1, h2;
4457 unsigned long symnum;
4459 matchres.sym_out = NULL;
4460 matchres.vsymp = NULL;
4461 matchres.vcount = 0;
4463 /* Pick right bitmask word from Bloom filter array */
4464 bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) &
4465 obj->maskwords_bm_gnu];
4467 /* Calculate modulus word size of gnu hash and its derivative */
4468 h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1);
4469 h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1));
4471 /* Filter out the "definitely not in set" queries */
4472 if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0)
4475 /* Locate hash chain and corresponding value element*/
4476 bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu];
4479 hashval = &obj->chain_zero_gnu[bucket];
4481 if (((*hashval ^ req->hash_gnu) >> 1) == 0) {
4482 symnum = hashval - obj->chain_zero_gnu;
4483 if (matched_symbol(req, obj, &matchres, symnum)) {
4484 req->sym_out = matchres.sym_out;
4485 req->defobj_out = obj;
4489 } while ((*hashval++ & 1) == 0);
4490 if (matchres.vcount == 1) {
4491 req->sym_out = matchres.vsymp;
4492 req->defobj_out = obj;
4499 trace_loaded_objects(Obj_Entry *obj)
4501 const char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
4504 if ((main_local = getenv(_LD("TRACE_LOADED_OBJECTS_PROGNAME"))) == NULL)
4507 if ((fmt1 = getenv(_LD("TRACE_LOADED_OBJECTS_FMT1"))) == NULL)
4508 fmt1 = "\t%o => %p (%x)\n";
4510 if ((fmt2 = getenv(_LD("TRACE_LOADED_OBJECTS_FMT2"))) == NULL)
4511 fmt2 = "\t%o (%x)\n";
4513 list_containers = getenv(_LD("TRACE_LOADED_OBJECTS_ALL"));
4515 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
4516 Needed_Entry *needed;
4517 const char *name, *path;
4522 if (list_containers && obj->needed != NULL)
4523 rtld_printf("%s:\n", obj->path);
4524 for (needed = obj->needed; needed; needed = needed->next) {
4525 if (needed->obj != NULL) {
4526 if (needed->obj->traced && !list_containers)
4528 needed->obj->traced = true;
4529 path = needed->obj->path;
4533 name = obj->strtab + needed->name;
4534 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
4536 fmt = is_lib ? fmt1 : fmt2;
4537 while ((c = *fmt++) != '\0') {
4563 rtld_putstr(main_local);
4566 rtld_putstr(obj_main->path);
4573 rtld_printf("%d", sodp->sod_major);
4576 rtld_printf("%d", sodp->sod_minor);
4583 rtld_printf("%p", needed->obj ? needed->obj->mapbase :
4596 * Unload a dlopened object and its dependencies from memory and from
4597 * our data structures. It is assumed that the DAG rooted in the
4598 * object has already been unreferenced, and that the object has a
4599 * reference count of 0.
4602 unload_object(Obj_Entry *root, RtldLockState *lockstate)
4604 Obj_Entry marker, *obj, *next;
4606 assert(root->refcount == 0);
4609 * Pass over the DAG removing unreferenced objects from
4610 * appropriate lists.
4612 unlink_object(root);
4614 /* Unmap all objects that are no longer referenced. */
4615 for (obj = TAILQ_FIRST(&obj_list); obj != NULL; obj = next) {
4616 next = TAILQ_NEXT(obj, next);
4617 if (obj->marker || obj->refcount != 0)
4619 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase,
4620 obj->mapsize, 0, obj->path);
4621 dbg("unloading \"%s\"", obj->path);
4623 * Unlink the object now to prevent new references from
4624 * being acquired while the bind lock is dropped in
4625 * recursive dlclose() invocations.
4627 TAILQ_REMOVE(&obj_list, obj, next);
4630 if (obj->filtees_loaded) {
4632 init_marker(&marker);
4633 TAILQ_INSERT_BEFORE(next, &marker, next);
4634 unload_filtees(obj, lockstate);
4635 next = TAILQ_NEXT(&marker, next);
4636 TAILQ_REMOVE(&obj_list, &marker, next);
4638 unload_filtees(obj, lockstate);
4640 release_object(obj);
4645 unlink_object(Obj_Entry *root)
4649 if (root->refcount == 0) {
4650 /* Remove the object from the RTLD_GLOBAL list. */
4651 objlist_remove(&list_global, root);
4653 /* Remove the object from all objects' DAG lists. */
4654 STAILQ_FOREACH(elm, &root->dagmembers, link) {
4655 objlist_remove(&elm->obj->dldags, root);
4656 if (elm->obj != root)
4657 unlink_object(elm->obj);
4663 ref_dag(Obj_Entry *root)
4667 assert(root->dag_inited);
4668 STAILQ_FOREACH(elm, &root->dagmembers, link)
4669 elm->obj->refcount++;
4673 unref_dag(Obj_Entry *root)
4677 assert(root->dag_inited);
4678 STAILQ_FOREACH(elm, &root->dagmembers, link)
4679 elm->obj->refcount--;
4683 * Common code for MD __tls_get_addr().
4685 static void *tls_get_addr_slow(Elf_Addr **, int, size_t) __noinline;
4687 tls_get_addr_slow(Elf_Addr **dtvp, int index, size_t offset)
4689 Elf_Addr *newdtv, *dtv;
4690 RtldLockState lockstate;
4694 /* Check dtv generation in case new modules have arrived */
4695 if (dtv[0] != tls_dtv_generation) {
4696 wlock_acquire(rtld_bind_lock, &lockstate);
4697 newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4699 if (to_copy > tls_max_index)
4700 to_copy = tls_max_index;
4701 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
4702 newdtv[0] = tls_dtv_generation;
4703 newdtv[1] = tls_max_index;
4705 lock_release(rtld_bind_lock, &lockstate);
4706 dtv = *dtvp = newdtv;
4709 /* Dynamically allocate module TLS if necessary */
4710 if (dtv[index + 1] == 0) {
4711 /* Signal safe, wlock will block out signals. */
4712 wlock_acquire(rtld_bind_lock, &lockstate);
4713 if (!dtv[index + 1])
4714 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
4715 lock_release(rtld_bind_lock, &lockstate);
4717 return ((void *)(dtv[index + 1] + offset));
4721 tls_get_addr_common(Elf_Addr **dtvp, int index, size_t offset)
4726 /* Check dtv generation in case new modules have arrived */
4727 if (__predict_true(dtv[0] == tls_dtv_generation &&
4728 dtv[index + 1] != 0))
4729 return ((void *)(dtv[index + 1] + offset));
4730 return (tls_get_addr_slow(dtvp, index, offset));
4733 #if defined(__aarch64__) || defined(__arm__) || defined(__mips__) || \
4734 defined(__powerpc__) || defined(__riscv)
4737 * Return pointer to allocated TLS block
4740 get_tls_block_ptr(void *tcb, size_t tcbsize)
4742 size_t extra_size, post_size, pre_size, tls_block_size;
4743 size_t tls_init_align;
4745 tls_init_align = MAX(obj_main->tlsalign, 1);
4747 /* Compute fragments sizes. */
4748 extra_size = tcbsize - TLS_TCB_SIZE;
4749 post_size = calculate_tls_post_size(tls_init_align);
4750 tls_block_size = tcbsize + post_size;
4751 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size;
4753 return ((char *)tcb - pre_size - extra_size);
4757 * Allocate Static TLS using the Variant I method.
4759 * For details on the layout, see lib/libc/gen/tls.c.
4761 * NB: rtld's tls_static_space variable includes TLS_TCB_SIZE and post_size as
4762 * it is based on tls_last_offset, and TLS offsets here are really TCB
4763 * offsets, whereas libc's tls_static_space is just the executable's static
4767 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
4771 Elf_Addr *dtv, **tcb;
4774 size_t extra_size, maxalign, post_size, pre_size, tls_block_size;
4775 size_t tls_init_align;
4777 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
4780 assert(tcbsize >= TLS_TCB_SIZE);
4781 maxalign = MAX(tcbalign, tls_static_max_align);
4782 tls_init_align = MAX(obj_main->tlsalign, 1);
4784 /* Compute fragmets sizes. */
4785 extra_size = tcbsize - TLS_TCB_SIZE;
4786 post_size = calculate_tls_post_size(tls_init_align);
4787 tls_block_size = tcbsize + post_size;
4788 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size;
4789 tls_block_size += pre_size + tls_static_space - TLS_TCB_SIZE - post_size;
4791 /* Allocate whole TLS block */
4792 tls_block = malloc_aligned(tls_block_size, maxalign);
4793 tcb = (Elf_Addr **)(tls_block + pre_size + extra_size);
4795 if (oldtcb != NULL) {
4796 memcpy(tls_block, get_tls_block_ptr(oldtcb, tcbsize),
4798 free_aligned(get_tls_block_ptr(oldtcb, tcbsize));
4800 /* Adjust the DTV. */
4802 for (i = 0; i < dtv[1]; i++) {
4803 if (dtv[i+2] >= (Elf_Addr)oldtcb &&
4804 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
4805 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tcb;
4809 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4811 dtv[0] = tls_dtv_generation;
4812 dtv[1] = tls_max_index;
4814 for (obj = globallist_curr(objs); obj != NULL;
4815 obj = globallist_next(obj)) {
4816 if (obj->tlsoffset > 0) {
4817 addr = (Elf_Addr)tcb + obj->tlsoffset;
4818 if (obj->tlsinitsize > 0)
4819 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4820 if (obj->tlssize > obj->tlsinitsize)
4821 memset((void*)(addr + obj->tlsinitsize), 0,
4822 obj->tlssize - obj->tlsinitsize);
4823 dtv[obj->tlsindex + 1] = addr;
4832 free_tls(void *tcb, size_t tcbsize, size_t tcbalign __unused)
4835 Elf_Addr tlsstart, tlsend;
4837 size_t dtvsize, i, tls_init_align;
4839 assert(tcbsize >= TLS_TCB_SIZE);
4840 tls_init_align = MAX(obj_main->tlsalign, 1);
4842 /* Compute fragments sizes. */
4843 post_size = calculate_tls_post_size(tls_init_align);
4845 tlsstart = (Elf_Addr)tcb + TLS_TCB_SIZE + post_size;
4846 tlsend = (Elf_Addr)tcb + tls_static_space;
4848 dtv = *(Elf_Addr **)tcb;
4850 for (i = 0; i < dtvsize; i++) {
4851 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
4852 free((void*)dtv[i+2]);
4856 free_aligned(get_tls_block_ptr(tcb, tcbsize));
4861 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__)
4864 * Allocate Static TLS using the Variant II method.
4867 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
4870 size_t size, ralign;
4872 Elf_Addr *dtv, *olddtv;
4873 Elf_Addr segbase, oldsegbase, addr;
4877 if (tls_static_max_align > ralign)
4878 ralign = tls_static_max_align;
4879 size = round(tls_static_space, ralign) + round(tcbsize, ralign);
4881 assert(tcbsize >= 2*sizeof(Elf_Addr));
4882 tls = malloc_aligned(size, ralign);
4883 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4885 segbase = (Elf_Addr)(tls + round(tls_static_space, ralign));
4886 ((Elf_Addr*)segbase)[0] = segbase;
4887 ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
4889 dtv[0] = tls_dtv_generation;
4890 dtv[1] = tls_max_index;
4894 * Copy the static TLS block over whole.
4896 oldsegbase = (Elf_Addr) oldtls;
4897 memcpy((void *)(segbase - tls_static_space),
4898 (const void *)(oldsegbase - tls_static_space),
4902 * If any dynamic TLS blocks have been created tls_get_addr(),
4905 olddtv = ((Elf_Addr**)oldsegbase)[1];
4906 for (i = 0; i < olddtv[1]; i++) {
4907 if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
4908 dtv[i+2] = olddtv[i+2];
4914 * We assume that this block was the one we created with
4915 * allocate_initial_tls().
4917 free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
4919 for (obj = objs; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
4920 if (obj->marker || obj->tlsoffset == 0)
4922 addr = segbase - obj->tlsoffset;
4923 memset((void*)(addr + obj->tlsinitsize),
4924 0, obj->tlssize - obj->tlsinitsize);
4926 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4927 dtv[obj->tlsindex + 1] = addr;
4931 return (void*) segbase;
4935 free_tls(void *tls, size_t tcbsize __unused, size_t tcbalign)
4938 size_t size, ralign;
4940 Elf_Addr tlsstart, tlsend;
4943 * Figure out the size of the initial TLS block so that we can
4944 * find stuff which ___tls_get_addr() allocated dynamically.
4947 if (tls_static_max_align > ralign)
4948 ralign = tls_static_max_align;
4949 size = round(tls_static_space, ralign);
4951 dtv = ((Elf_Addr**)tls)[1];
4953 tlsend = (Elf_Addr) tls;
4954 tlsstart = tlsend - size;
4955 for (i = 0; i < dtvsize; i++) {
4956 if (dtv[i + 2] != 0 && (dtv[i + 2] < tlsstart || dtv[i + 2] > tlsend)) {
4957 free_aligned((void *)dtv[i + 2]);
4961 free_aligned((void *)tlsstart);
4968 * Allocate TLS block for module with given index.
4971 allocate_module_tls(int index)
4976 TAILQ_FOREACH(obj, &obj_list, next) {
4979 if (obj->tlsindex == index)
4983 _rtld_error("Can't find module with TLS index %d", index);
4987 p = malloc_aligned(obj->tlssize, obj->tlsalign);
4988 memcpy(p, obj->tlsinit, obj->tlsinitsize);
4989 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
4995 allocate_tls_offset(Obj_Entry *obj)
5002 if (obj->tlssize == 0) {
5003 obj->tls_done = true;
5007 if (tls_last_offset == 0)
5008 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
5010 off = calculate_tls_offset(tls_last_offset, tls_last_size,
5011 obj->tlssize, obj->tlsalign);
5014 * If we have already fixed the size of the static TLS block, we
5015 * must stay within that size. When allocating the static TLS, we
5016 * leave a small amount of space spare to be used for dynamically
5017 * loading modules which use static TLS.
5019 if (tls_static_space != 0) {
5020 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
5022 } else if (obj->tlsalign > tls_static_max_align) {
5023 tls_static_max_align = obj->tlsalign;
5026 tls_last_offset = obj->tlsoffset = off;
5027 tls_last_size = obj->tlssize;
5028 obj->tls_done = true;
5034 free_tls_offset(Obj_Entry *obj)
5038 * If we were the last thing to allocate out of the static TLS
5039 * block, we give our space back to the 'allocator'. This is a
5040 * simplistic workaround to allow libGL.so.1 to be loaded and
5041 * unloaded multiple times.
5043 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
5044 == calculate_tls_end(tls_last_offset, tls_last_size)) {
5045 tls_last_offset -= obj->tlssize;
5051 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
5054 RtldLockState lockstate;
5056 wlock_acquire(rtld_bind_lock, &lockstate);
5057 ret = allocate_tls(globallist_curr(TAILQ_FIRST(&obj_list)), oldtls,
5059 lock_release(rtld_bind_lock, &lockstate);
5064 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
5066 RtldLockState lockstate;
5068 wlock_acquire(rtld_bind_lock, &lockstate);
5069 free_tls(tcb, tcbsize, tcbalign);
5070 lock_release(rtld_bind_lock, &lockstate);
5074 object_add_name(Obj_Entry *obj, const char *name)
5080 entry = malloc(sizeof(Name_Entry) + len);
5082 if (entry != NULL) {
5083 strcpy(entry->name, name);
5084 STAILQ_INSERT_TAIL(&obj->names, entry, link);
5089 object_match_name(const Obj_Entry *obj, const char *name)
5093 STAILQ_FOREACH(entry, &obj->names, link) {
5094 if (strcmp(name, entry->name) == 0)
5101 locate_dependency(const Obj_Entry *obj, const char *name)
5103 const Objlist_Entry *entry;
5104 const Needed_Entry *needed;
5106 STAILQ_FOREACH(entry, &list_main, link) {
5107 if (object_match_name(entry->obj, name))
5111 for (needed = obj->needed; needed != NULL; needed = needed->next) {
5112 if (strcmp(obj->strtab + needed->name, name) == 0 ||
5113 (needed->obj != NULL && object_match_name(needed->obj, name))) {
5115 * If there is DT_NEEDED for the name we are looking for,
5116 * we are all set. Note that object might not be found if
5117 * dependency was not loaded yet, so the function can
5118 * return NULL here. This is expected and handled
5119 * properly by the caller.
5121 return (needed->obj);
5124 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
5130 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
5131 const Elf_Vernaux *vna)
5133 const Elf_Verdef *vd;
5134 const char *vername;
5136 vername = refobj->strtab + vna->vna_name;
5137 vd = depobj->verdef;
5139 _rtld_error("%s: version %s required by %s not defined",
5140 depobj->path, vername, refobj->path);
5144 if (vd->vd_version != VER_DEF_CURRENT) {
5145 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
5146 depobj->path, vd->vd_version);
5149 if (vna->vna_hash == vd->vd_hash) {
5150 const Elf_Verdaux *aux = (const Elf_Verdaux *)
5151 ((const char *)vd + vd->vd_aux);
5152 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
5155 if (vd->vd_next == 0)
5157 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5159 if (vna->vna_flags & VER_FLG_WEAK)
5161 _rtld_error("%s: version %s required by %s not found",
5162 depobj->path, vername, refobj->path);
5167 rtld_verify_object_versions(Obj_Entry *obj)
5169 const Elf_Verneed *vn;
5170 const Elf_Verdef *vd;
5171 const Elf_Verdaux *vda;
5172 const Elf_Vernaux *vna;
5173 const Obj_Entry *depobj;
5174 int maxvernum, vernum;
5176 if (obj->ver_checked)
5178 obj->ver_checked = true;
5182 * Walk over defined and required version records and figure out
5183 * max index used by any of them. Do very basic sanity checking
5187 while (vn != NULL) {
5188 if (vn->vn_version != VER_NEED_CURRENT) {
5189 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
5190 obj->path, vn->vn_version);
5193 vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux);
5195 vernum = VER_NEED_IDX(vna->vna_other);
5196 if (vernum > maxvernum)
5198 if (vna->vna_next == 0)
5200 vna = (const Elf_Vernaux *)((const char *)vna + vna->vna_next);
5202 if (vn->vn_next == 0)
5204 vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next);
5208 while (vd != NULL) {
5209 if (vd->vd_version != VER_DEF_CURRENT) {
5210 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
5211 obj->path, vd->vd_version);
5214 vernum = VER_DEF_IDX(vd->vd_ndx);
5215 if (vernum > maxvernum)
5217 if (vd->vd_next == 0)
5219 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5226 * Store version information in array indexable by version index.
5227 * Verify that object version requirements are satisfied along the
5230 obj->vernum = maxvernum + 1;
5231 obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry));
5234 while (vd != NULL) {
5235 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
5236 vernum = VER_DEF_IDX(vd->vd_ndx);
5237 assert(vernum <= maxvernum);
5238 vda = (const Elf_Verdaux *)((const char *)vd + vd->vd_aux);
5239 obj->vertab[vernum].hash = vd->vd_hash;
5240 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
5241 obj->vertab[vernum].file = NULL;
5242 obj->vertab[vernum].flags = 0;
5244 if (vd->vd_next == 0)
5246 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5250 while (vn != NULL) {
5251 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
5254 vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux);
5256 if (check_object_provided_version(obj, depobj, vna))
5258 vernum = VER_NEED_IDX(vna->vna_other);
5259 assert(vernum <= maxvernum);
5260 obj->vertab[vernum].hash = vna->vna_hash;
5261 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
5262 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
5263 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
5264 VER_INFO_HIDDEN : 0;
5265 if (vna->vna_next == 0)
5267 vna = (const Elf_Vernaux *)((const char *)vna + vna->vna_next);
5269 if (vn->vn_next == 0)
5271 vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next);
5277 rtld_verify_versions(const Objlist *objlist)
5279 Objlist_Entry *entry;
5283 STAILQ_FOREACH(entry, objlist, link) {
5285 * Skip dummy objects or objects that have their version requirements
5288 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
5290 if (rtld_verify_object_versions(entry->obj) == -1) {
5292 if (ld_tracing == NULL)
5296 if (rc == 0 || ld_tracing != NULL)
5297 rc = rtld_verify_object_versions(&obj_rtld);
5302 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
5307 vernum = VER_NDX(obj->versyms[symnum]);
5308 if (vernum >= obj->vernum) {
5309 _rtld_error("%s: symbol %s has wrong verneed value %d",
5310 obj->path, obj->strtab + symnum, vernum);
5311 } else if (obj->vertab[vernum].hash != 0) {
5312 return &obj->vertab[vernum];
5319 _rtld_get_stack_prot(void)
5322 return (stack_prot);
5326 _rtld_is_dlopened(void *arg)
5329 RtldLockState lockstate;
5332 rlock_acquire(rtld_bind_lock, &lockstate);
5335 obj = obj_from_addr(arg);
5337 _rtld_error("No shared object contains address");
5338 lock_release(rtld_bind_lock, &lockstate);
5341 res = obj->dlopened ? 1 : 0;
5342 lock_release(rtld_bind_lock, &lockstate);
5347 obj_enforce_relro(Obj_Entry *obj)
5350 if (obj->relro_size > 0 && mprotect(obj->relro_page, obj->relro_size,
5352 _rtld_error("%s: Cannot enforce relro protection: %s",
5353 obj->path, rtld_strerror(errno));
5360 map_stacks_exec(RtldLockState *lockstate)
5362 void (*thr_map_stacks_exec)(void);
5364 if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
5366 thr_map_stacks_exec = (void (*)(void))(uintptr_t)
5367 get_program_var_addr("__pthread_map_stacks_exec", lockstate);
5368 if (thr_map_stacks_exec != NULL) {
5369 stack_prot |= PROT_EXEC;
5370 thr_map_stacks_exec();
5375 symlook_init(SymLook *dst, const char *name)
5378 bzero(dst, sizeof(*dst));
5380 dst->hash = elf_hash(name);
5381 dst->hash_gnu = gnu_hash(name);
5385 symlook_init_from_req(SymLook *dst, const SymLook *src)
5388 dst->name = src->name;
5389 dst->hash = src->hash;
5390 dst->hash_gnu = src->hash_gnu;
5391 dst->ventry = src->ventry;
5392 dst->flags = src->flags;
5393 dst->defobj_out = NULL;
5394 dst->sym_out = NULL;
5395 dst->lockstate = src->lockstate;
5399 open_binary_fd(const char *argv0, bool search_in_path)
5401 char *pathenv, *pe, binpath[PATH_MAX];
5404 if (search_in_path && strchr(argv0, '/') == NULL) {
5405 pathenv = getenv("PATH");
5406 if (pathenv == NULL) {
5407 _rtld_error("-p and no PATH environment variable");
5410 pathenv = strdup(pathenv);
5411 if (pathenv == NULL) {
5412 _rtld_error("Cannot allocate memory");
5417 while ((pe = strsep(&pathenv, ":")) != NULL) {
5418 if (strlcpy(binpath, pe, sizeof(binpath)) >=
5421 if (binpath[0] != '\0' &&
5422 strlcat(binpath, "/", sizeof(binpath)) >=
5425 if (strlcat(binpath, argv0, sizeof(binpath)) >=
5428 fd = open(binpath, O_RDONLY | O_CLOEXEC | O_VERIFY);
5429 if (fd != -1 || errno != ENOENT)
5434 fd = open(argv0, O_RDONLY | O_CLOEXEC | O_VERIFY);
5438 _rtld_error("Cannot open %s: %s", argv0, rtld_strerror(errno));
5445 * Parse a set of command-line arguments.
5448 parse_args(char* argv[], int argc, bool *use_pathp, int *fdp)
5451 int fd, i, j, arglen;
5454 dbg("Parsing command-line arguments");
5458 for (i = 1; i < argc; i++ ) {
5460 dbg("argv[%d]: '%s'", i, arg);
5463 * rtld arguments end with an explicit "--" or with the first
5464 * non-prefixed argument.
5466 if (strcmp(arg, "--") == 0) {
5474 * All other arguments are single-character options that can
5475 * be combined, so we need to search through `arg` for them.
5477 arglen = strlen(arg);
5478 for (j = 1; j < arglen; j++) {
5481 print_usage(argv[0]);
5483 } else if (opt == 'f') {
5485 * -f XX can be used to specify a descriptor for the
5486 * binary named at the command line (i.e., the later
5487 * argument will specify the process name but the
5488 * descriptor is what will actually be executed)
5490 if (j != arglen - 1) {
5491 /* -f must be the last option in, e.g., -abcf */
5492 _rtld_error("Invalid options: %s", arg);
5496 fd = parse_integer(argv[i]);
5498 _rtld_error("Invalid file descriptor: '%s'",
5504 } else if (opt == 'p') {
5507 _rtld_error("Invalid argument: '%s'", arg);
5508 print_usage(argv[0]);
5518 * Parse a file descriptor number without pulling in more of libc (e.g. atoi).
5521 parse_integer(const char *str)
5523 static const int RADIX = 10; /* XXXJA: possibly support hex? */
5530 for (c = *str; c != '\0'; c = *++str) {
5531 if (c < '0' || c > '9')
5538 /* Make sure we actually parsed something. */
5545 print_usage(const char *argv0)
5548 rtld_printf("Usage: %s [-h] [-f <FD>] [--] <binary> [<args>]\n"
5551 " -h Display this help message\n"
5552 " -p Search in PATH for named binary\n"
5553 " -f <FD> Execute <FD> instead of searching for <binary>\n"
5554 " -- End of RTLD options\n"
5555 " <binary> Name of process to execute\n"
5556 " <args> Arguments to the executed process\n", argv0);
5560 * Overrides for libc_pic-provided functions.
5564 __getosreldate(void)
5574 oid[1] = KERN_OSRELDATE;
5576 len = sizeof(osrel);
5577 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
5578 if (error == 0 && osrel > 0 && len == sizeof(osrel))
5590 void (*__cleanup)(void);
5591 int __isthreaded = 0;
5592 int _thread_autoinit_dummy_decl = 1;
5595 * No unresolved symbols for rtld.
5598 __pthread_cxa_finalize(struct dl_phdr_info *a __unused)
5603 rtld_strerror(int errnum)
5606 if (errnum < 0 || errnum >= sys_nerr)
5607 return ("Unknown error");
5608 return (sys_errlist[errnum]);