2 * Copyright 1996, 1997, 1998, 1999, 2000 John D. Polstra.
3 * Copyright 2003 Alexander Kabaev <kan@FreeBSD.ORG>.
4 * Copyright 2009-2012 Konstantin Belousov <kib@FreeBSD.ORG>.
5 * Copyright 2012 John Marino <draco@marino.st>.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 * Dynamic linker for ELF.
34 * John Polstra <jdp@polstra.com>.
37 #include <sys/param.h>
38 #include <sys/mount.h>
41 #include <sys/sysctl.h>
43 #include <sys/utsname.h>
44 #include <sys/ktrace.h>
61 #include "rtld_printf.h"
62 #include "rtld_utrace.h"
66 typedef void (*func_ptr_type)();
67 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg);
70 * Function declarations.
72 static const char *basename(const char *);
73 static void digest_dynamic1(Obj_Entry *, int, const Elf_Dyn **,
74 const Elf_Dyn **, const Elf_Dyn **);
75 static void digest_dynamic2(Obj_Entry *, const Elf_Dyn *, const Elf_Dyn *,
77 static void digest_dynamic(Obj_Entry *, int);
78 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
79 static Obj_Entry *dlcheck(void *);
80 static Obj_Entry *dlopen_object(const char *name, int fd, Obj_Entry *refobj,
81 int lo_flags, int mode, RtldLockState *lockstate);
82 static Obj_Entry *do_load_object(int, const char *, char *, struct stat *, int);
83 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
84 static bool donelist_check(DoneList *, const Obj_Entry *);
85 static void errmsg_restore(char *);
86 static char *errmsg_save(void);
87 static void *fill_search_info(const char *, size_t, void *);
88 static char *find_library(const char *, const Obj_Entry *, int *);
89 static const char *gethints(bool);
90 static void init_dag(Obj_Entry *);
91 static void init_pagesizes(Elf_Auxinfo **aux_info);
92 static void init_rtld(caddr_t, Elf_Auxinfo **);
93 static void initlist_add_neededs(Needed_Entry *, Objlist *);
94 static void initlist_add_objects(Obj_Entry *, Obj_Entry *, Objlist *);
95 static void linkmap_add(Obj_Entry *);
96 static void linkmap_delete(Obj_Entry *);
97 static void load_filtees(Obj_Entry *, int flags, RtldLockState *);
98 static void unload_filtees(Obj_Entry *);
99 static int load_needed_objects(Obj_Entry *, int);
100 static int load_preload_objects(void);
101 static Obj_Entry *load_object(const char *, int fd, const Obj_Entry *, int);
102 static void map_stacks_exec(RtldLockState *);
103 static Obj_Entry *obj_from_addr(const void *);
104 static void objlist_call_fini(Objlist *, Obj_Entry *, RtldLockState *);
105 static void objlist_call_init(Objlist *, RtldLockState *);
106 static void objlist_clear(Objlist *);
107 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
108 static void objlist_init(Objlist *);
109 static void objlist_push_head(Objlist *, Obj_Entry *);
110 static void objlist_push_tail(Objlist *, Obj_Entry *);
111 static void objlist_put_after(Objlist *, Obj_Entry *, Obj_Entry *);
112 static void objlist_remove(Objlist *, Obj_Entry *);
113 static int parse_libdir(const char *);
114 static void *path_enumerate(const char *, path_enum_proc, void *);
115 static int relocate_object_dag(Obj_Entry *root, bool bind_now,
116 Obj_Entry *rtldobj, int flags, RtldLockState *lockstate);
117 static int relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
118 int flags, RtldLockState *lockstate);
119 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, int,
121 static int resolve_objects_ifunc(Obj_Entry *first, bool bind_now,
122 int flags, RtldLockState *lockstate);
123 static int rtld_dirname(const char *, char *);
124 static int rtld_dirname_abs(const char *, char *);
125 static void *rtld_dlopen(const char *name, int fd, int mode);
126 static void rtld_exit(void);
127 static char *search_library_path(const char *, const char *);
128 static char *search_library_pathfds(const char *, const char *, int *);
129 static const void **get_program_var_addr(const char *, RtldLockState *);
130 static void set_program_var(const char *, const void *);
131 static int symlook_default(SymLook *, const Obj_Entry *refobj);
132 static int symlook_global(SymLook *, DoneList *);
133 static void symlook_init_from_req(SymLook *, const SymLook *);
134 static int symlook_list(SymLook *, const Objlist *, DoneList *);
135 static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *);
136 static int symlook_obj1_sysv(SymLook *, const Obj_Entry *);
137 static int symlook_obj1_gnu(SymLook *, const Obj_Entry *);
138 static void trace_loaded_objects(Obj_Entry *);
139 static void unlink_object(Obj_Entry *);
140 static void unload_object(Obj_Entry *);
141 static void unref_dag(Obj_Entry *);
142 static void ref_dag(Obj_Entry *);
143 static char *origin_subst_one(Obj_Entry *, char *, const char *,
145 static char *origin_subst(Obj_Entry *, char *);
146 static bool obj_resolve_origin(Obj_Entry *obj);
147 static void preinit_main(void);
148 static int rtld_verify_versions(const Objlist *);
149 static int rtld_verify_object_versions(Obj_Entry *);
150 static void object_add_name(Obj_Entry *, const char *);
151 static int object_match_name(const Obj_Entry *, const char *);
152 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
153 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
154 struct dl_phdr_info *phdr_info);
155 static uint32_t gnu_hash(const char *);
156 static bool matched_symbol(SymLook *, const Obj_Entry *, Sym_Match_Result *,
157 const unsigned long);
159 void r_debug_state(struct r_debug *, struct link_map *) __noinline __exported;
160 void _r_debug_postinit(struct link_map *) __noinline __exported;
162 int __sys_openat(int, const char *, int, ...);
167 static char *error_message; /* Message for dlerror(), or NULL */
168 struct r_debug r_debug __exported; /* for GDB; */
169 static bool libmap_disable; /* Disable libmap */
170 static bool ld_loadfltr; /* Immediate filters processing */
171 static char *libmap_override; /* Maps to use in addition to libmap.conf */
172 static bool trust; /* False for setuid and setgid programs */
173 static bool dangerous_ld_env; /* True if environment variables have been
174 used to affect the libraries loaded */
175 static char *ld_bind_now; /* Environment variable for immediate binding */
176 static char *ld_debug; /* Environment variable for debugging */
177 static char *ld_library_path; /* Environment variable for search path */
178 static char *ld_library_dirs; /* Environment variable for library descriptors */
179 static char *ld_preload; /* Environment variable for libraries to
181 static char *ld_elf_hints_path; /* Environment variable for alternative hints path */
182 static char *ld_tracing; /* Called from ldd to print libs */
183 static char *ld_utrace; /* Use utrace() to log events. */
184 static struct obj_entry_q obj_list; /* Queue of all loaded objects */
185 static Obj_Entry *obj_main; /* The main program shared object */
186 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
187 static unsigned int obj_count; /* Number of objects in obj_list */
188 static unsigned int obj_loads; /* Number of loads of objects (gen count) */
190 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
191 STAILQ_HEAD_INITIALIZER(list_global);
192 static Objlist list_main = /* Objects loaded at program startup */
193 STAILQ_HEAD_INITIALIZER(list_main);
194 static Objlist list_fini = /* Objects needing fini() calls */
195 STAILQ_HEAD_INITIALIZER(list_fini);
197 Elf_Sym sym_zero; /* For resolving undefined weak refs. */
199 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
201 extern Elf_Dyn _DYNAMIC;
202 #pragma weak _DYNAMIC
203 #ifndef RTLD_IS_DYNAMIC
204 #define RTLD_IS_DYNAMIC() (&_DYNAMIC != NULL)
207 int dlclose(void *) __exported;
208 char *dlerror(void) __exported;
209 void *dlopen(const char *, int) __exported;
210 void *fdlopen(int, int) __exported;
211 void *dlsym(void *, const char *) __exported;
212 dlfunc_t dlfunc(void *, const char *) __exported;
213 void *dlvsym(void *, const char *, const char *) __exported;
214 int dladdr(const void *, Dl_info *) __exported;
215 void dllockinit(void *, void *(*)(void *), void (*)(void *), void (*)(void *),
216 void (*)(void *), void (*)(void *), void (*)(void *)) __exported;
217 int dlinfo(void *, int , void *) __exported;
218 int dl_iterate_phdr(__dl_iterate_hdr_callback, void *) __exported;
219 int _rtld_addr_phdr(const void *, struct dl_phdr_info *) __exported;
220 int _rtld_get_stack_prot(void) __exported;
221 int _rtld_is_dlopened(void *) __exported;
222 void _rtld_error(const char *, ...) __exported;
224 int npagesizes, osreldate;
227 long __stack_chk_guard[8] = {0, 0, 0, 0, 0, 0, 0, 0};
229 static int stack_prot = PROT_READ | PROT_WRITE | RTLD_DEFAULT_STACK_EXEC;
230 static int max_stack_flags;
233 * Global declarations normally provided by crt1. The dynamic linker is
234 * not built with crt1, so we have to provide them ourselves.
240 * Used to pass argc, argv to init functions.
246 * Globals to control TLS allocation.
248 size_t tls_last_offset; /* Static TLS offset of last module */
249 size_t tls_last_size; /* Static TLS size of last module */
250 size_t tls_static_space; /* Static TLS space allocated */
251 size_t tls_static_max_align;
252 int tls_dtv_generation = 1; /* Used to detect when dtv size changes */
253 int tls_max_index = 1; /* Largest module index allocated */
255 bool ld_library_path_rpath = false;
258 * Globals for path names, and such
260 char *ld_elf_hints_default = _PATH_ELF_HINTS;
261 char *ld_path_libmap_conf = _PATH_LIBMAP_CONF;
262 char *ld_path_rtld = _PATH_RTLD;
263 char *ld_standard_library_path = STANDARD_LIBRARY_PATH;
264 char *ld_env_prefix = LD_;
267 * Fill in a DoneList with an allocation large enough to hold all of
268 * the currently-loaded objects. Keep this as a macro since it calls
269 * alloca and we want that to occur within the scope of the caller.
271 #define donelist_init(dlp) \
272 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
273 assert((dlp)->objs != NULL), \
274 (dlp)->num_alloc = obj_count, \
277 #define LD_UTRACE(e, h, mb, ms, r, n) do { \
278 if (ld_utrace != NULL) \
279 ld_utrace_log(e, h, mb, ms, r, n); \
283 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
284 int refcnt, const char *name)
286 struct utrace_rtld ut;
287 static const char rtld_utrace_sig[RTLD_UTRACE_SIG_SZ] = RTLD_UTRACE_SIG;
289 memcpy(ut.sig, rtld_utrace_sig, sizeof(ut.sig));
292 ut.mapbase = mapbase;
293 ut.mapsize = mapsize;
295 bzero(ut.name, sizeof(ut.name));
297 strlcpy(ut.name, name, sizeof(ut.name));
298 utrace(&ut, sizeof(ut));
301 #ifdef RTLD_VARIANT_ENV_NAMES
303 * construct the env variable based on the type of binary that's
306 static inline const char *
309 static char buffer[128];
311 strlcpy(buffer, ld_env_prefix, sizeof(buffer));
312 strlcat(buffer, var, sizeof(buffer));
320 * Main entry point for dynamic linking. The first argument is the
321 * stack pointer. The stack is expected to be laid out as described
322 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
323 * Specifically, the stack pointer points to a word containing
324 * ARGC. Following that in the stack is a null-terminated sequence
325 * of pointers to argument strings. Then comes a null-terminated
326 * sequence of pointers to environment strings. Finally, there is a
327 * sequence of "auxiliary vector" entries.
329 * The second argument points to a place to store the dynamic linker's
330 * exit procedure pointer and the third to a place to store the main
333 * The return value is the main program's entry point.
336 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
338 Elf_Auxinfo *aux_info[AT_COUNT];
346 Objlist_Entry *entry;
348 Obj_Entry *preload_tail;
349 Obj_Entry *last_interposer;
351 RtldLockState lockstate;
352 char *library_path_rpath;
357 * On entry, the dynamic linker itself has not been relocated yet.
358 * Be very careful not to reference any global data until after
359 * init_rtld has returned. It is OK to reference file-scope statics
360 * and string constants, and to call static and global functions.
363 /* Find the auxiliary vector on the stack. */
366 sp += argc + 1; /* Skip over arguments and NULL terminator */
368 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
370 aux = (Elf_Auxinfo *) sp;
372 /* Digest the auxiliary vector. */
373 for (i = 0; i < AT_COUNT; i++)
375 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
376 if (auxp->a_type < AT_COUNT)
377 aux_info[auxp->a_type] = auxp;
380 /* Initialize and relocate ourselves. */
381 assert(aux_info[AT_BASE] != NULL);
382 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
384 __progname = obj_rtld.path;
385 argv0 = argv[0] != NULL ? argv[0] : "(null)";
390 if (aux_info[AT_CANARY] != NULL &&
391 aux_info[AT_CANARY]->a_un.a_ptr != NULL) {
392 i = aux_info[AT_CANARYLEN]->a_un.a_val;
393 if (i > sizeof(__stack_chk_guard))
394 i = sizeof(__stack_chk_guard);
395 memcpy(__stack_chk_guard, aux_info[AT_CANARY]->a_un.a_ptr, i);
400 len = sizeof(__stack_chk_guard);
401 if (sysctl(mib, 2, __stack_chk_guard, &len, NULL, 0) == -1 ||
402 len != sizeof(__stack_chk_guard)) {
403 /* If sysctl was unsuccessful, use the "terminator canary". */
404 ((unsigned char *)(void *)__stack_chk_guard)[0] = 0;
405 ((unsigned char *)(void *)__stack_chk_guard)[1] = 0;
406 ((unsigned char *)(void *)__stack_chk_guard)[2] = '\n';
407 ((unsigned char *)(void *)__stack_chk_guard)[3] = 255;
411 trust = !issetugid();
413 md_abi_variant_hook(aux_info);
415 ld_bind_now = getenv(_LD("BIND_NOW"));
417 * If the process is tainted, then we un-set the dangerous environment
418 * variables. The process will be marked as tainted until setuid(2)
419 * is called. If any child process calls setuid(2) we do not want any
420 * future processes to honor the potentially un-safe variables.
423 if (unsetenv(_LD("PRELOAD")) || unsetenv(_LD("LIBMAP")) ||
424 unsetenv(_LD("LIBRARY_PATH")) || unsetenv(_LD("LIBRARY_PATH_FDS")) ||
425 unsetenv(_LD("LIBMAP_DISABLE")) ||
426 unsetenv(_LD("DEBUG")) || unsetenv(_LD("ELF_HINTS_PATH")) ||
427 unsetenv(_LD("LOADFLTR")) || unsetenv(_LD("LIBRARY_PATH_RPATH"))) {
428 _rtld_error("environment corrupt; aborting");
432 ld_debug = getenv(_LD("DEBUG"));
433 libmap_disable = getenv(_LD("LIBMAP_DISABLE")) != NULL;
434 libmap_override = getenv(_LD("LIBMAP"));
435 ld_library_path = getenv(_LD("LIBRARY_PATH"));
436 ld_library_dirs = getenv(_LD("LIBRARY_PATH_FDS"));
437 ld_preload = getenv(_LD("PRELOAD"));
438 ld_elf_hints_path = getenv(_LD("ELF_HINTS_PATH"));
439 ld_loadfltr = getenv(_LD("LOADFLTR")) != NULL;
440 library_path_rpath = getenv(_LD("LIBRARY_PATH_RPATH"));
441 if (library_path_rpath != NULL) {
442 if (library_path_rpath[0] == 'y' ||
443 library_path_rpath[0] == 'Y' ||
444 library_path_rpath[0] == '1')
445 ld_library_path_rpath = true;
447 ld_library_path_rpath = false;
449 dangerous_ld_env = libmap_disable || (libmap_override != NULL) ||
450 (ld_library_path != NULL) || (ld_preload != NULL) ||
451 (ld_elf_hints_path != NULL) || ld_loadfltr;
452 ld_tracing = getenv(_LD("TRACE_LOADED_OBJECTS"));
453 ld_utrace = getenv(_LD("UTRACE"));
455 if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0)
456 ld_elf_hints_path = ld_elf_hints_default;
458 if (ld_debug != NULL && *ld_debug != '\0')
460 dbg("%s is initialized, base address = %p", __progname,
461 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
462 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
463 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
465 dbg("initializing thread locks");
469 * Load the main program, or process its program header if it is
472 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
473 int fd = aux_info[AT_EXECFD]->a_un.a_val;
474 dbg("loading main program");
475 obj_main = map_object(fd, argv0, NULL);
477 if (obj_main == NULL)
479 max_stack_flags = obj->stack_flags;
480 } else { /* Main program already loaded. */
481 const Elf_Phdr *phdr;
485 dbg("processing main program's program header");
486 assert(aux_info[AT_PHDR] != NULL);
487 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
488 assert(aux_info[AT_PHNUM] != NULL);
489 phnum = aux_info[AT_PHNUM]->a_un.a_val;
490 assert(aux_info[AT_PHENT] != NULL);
491 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
492 assert(aux_info[AT_ENTRY] != NULL);
493 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
494 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
498 if (aux_info[AT_EXECPATH] != NULL) {
500 char buf[MAXPATHLEN];
502 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
503 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
504 if (kexecpath[0] == '/')
505 obj_main->path = kexecpath;
506 else if (getcwd(buf, sizeof(buf)) == NULL ||
507 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
508 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
509 obj_main->path = xstrdup(argv0);
511 obj_main->path = xstrdup(buf);
513 dbg("No AT_EXECPATH");
514 obj_main->path = xstrdup(argv0);
516 dbg("obj_main path %s", obj_main->path);
517 obj_main->mainprog = true;
519 if (aux_info[AT_STACKPROT] != NULL &&
520 aux_info[AT_STACKPROT]->a_un.a_val != 0)
521 stack_prot = aux_info[AT_STACKPROT]->a_un.a_val;
525 * Get the actual dynamic linker pathname from the executable if
526 * possible. (It should always be possible.) That ensures that
527 * gdb will find the right dynamic linker even if a non-standard
530 if (obj_main->interp != NULL &&
531 strcmp(obj_main->interp, obj_rtld.path) != 0) {
533 obj_rtld.path = xstrdup(obj_main->interp);
534 __progname = obj_rtld.path;
538 digest_dynamic(obj_main, 0);
539 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d",
540 obj_main->path, obj_main->valid_hash_sysv, obj_main->valid_hash_gnu,
541 obj_main->dynsymcount);
543 linkmap_add(obj_main);
544 linkmap_add(&obj_rtld);
546 /* Link the main program into the list of objects. */
547 TAILQ_INSERT_HEAD(&obj_list, obj_main, next);
551 /* Initialize a fake symbol for resolving undefined weak references. */
552 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
553 sym_zero.st_shndx = SHN_UNDEF;
554 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
557 libmap_disable = (bool)lm_init(libmap_override);
559 dbg("loading LD_PRELOAD libraries");
560 if (load_preload_objects() == -1)
562 preload_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
564 dbg("loading needed objects");
565 if (load_needed_objects(obj_main, 0) == -1)
568 /* Make a list of all objects loaded at startup. */
569 last_interposer = obj_main;
570 TAILQ_FOREACH(obj, &obj_list, next) {
573 if (obj->z_interpose && obj != obj_main) {
574 objlist_put_after(&list_main, last_interposer, obj);
575 last_interposer = obj;
577 objlist_push_tail(&list_main, obj);
582 dbg("checking for required versions");
583 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
586 if (ld_tracing) { /* We're done */
587 trace_loaded_objects(obj_main);
591 if (getenv(_LD("DUMP_REL_PRE")) != NULL) {
592 dump_relocations(obj_main);
597 * Processing tls relocations requires having the tls offsets
598 * initialized. Prepare offsets before starting initial
599 * relocation processing.
601 dbg("initializing initial thread local storage offsets");
602 STAILQ_FOREACH(entry, &list_main, link) {
604 * Allocate all the initial objects out of the static TLS
605 * block even if they didn't ask for it.
607 allocate_tls_offset(entry->obj);
610 if (relocate_objects(obj_main,
611 ld_bind_now != NULL && *ld_bind_now != '\0',
612 &obj_rtld, SYMLOOK_EARLY, NULL) == -1)
615 dbg("doing copy relocations");
616 if (do_copy_relocations(obj_main) == -1)
619 if (getenv(_LD("DUMP_REL_POST")) != NULL) {
620 dump_relocations(obj_main);
625 * Setup TLS for main thread. This must be done after the
626 * relocations are processed, since tls initialization section
627 * might be the subject for relocations.
629 dbg("initializing initial thread local storage");
630 allocate_initial_tls(globallist_curr(TAILQ_FIRST(&obj_list)));
632 dbg("initializing key program variables");
633 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
634 set_program_var("environ", env);
635 set_program_var("__elf_aux_vector", aux);
637 /* Make a list of init functions to call. */
638 objlist_init(&initlist);
639 initlist_add_objects(globallist_curr(TAILQ_FIRST(&obj_list)),
640 preload_tail, &initlist);
642 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
644 map_stacks_exec(NULL);
646 dbg("resolving ifuncs");
647 if (resolve_objects_ifunc(obj_main,
648 ld_bind_now != NULL && *ld_bind_now != '\0', SYMLOOK_EARLY,
652 if (!obj_main->crt_no_init) {
654 * Make sure we don't call the main program's init and fini
655 * functions for binaries linked with old crt1 which calls
658 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
659 obj_main->preinit_array = obj_main->init_array =
660 obj_main->fini_array = (Elf_Addr)NULL;
663 wlock_acquire(rtld_bind_lock, &lockstate);
664 if (obj_main->crt_no_init)
666 objlist_call_init(&initlist, &lockstate);
667 _r_debug_postinit(&obj_main->linkmap);
668 objlist_clear(&initlist);
669 dbg("loading filtees");
670 TAILQ_FOREACH(obj, &obj_list, next) {
673 if (ld_loadfltr || obj->z_loadfltr)
674 load_filtees(obj, 0, &lockstate);
676 lock_release(rtld_bind_lock, &lockstate);
678 dbg("transferring control to program entry point = %p", obj_main->entry);
680 /* Return the exit procedure and the program entry point. */
681 *exit_proc = rtld_exit;
683 return (func_ptr_type) obj_main->entry;
687 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def)
692 ptr = (void *)make_function_pointer(def, obj);
693 target = ((Elf_Addr (*)(void))ptr)();
694 return ((void *)target);
698 _rtld_bind(Obj_Entry *obj, Elf_Size reloff)
702 const Obj_Entry *defobj;
705 RtldLockState lockstate;
707 rlock_acquire(rtld_bind_lock, &lockstate);
708 if (sigsetjmp(lockstate.env, 0) != 0)
709 lock_upgrade(rtld_bind_lock, &lockstate);
711 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
713 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
715 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
716 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL,
720 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
721 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
723 target = (Elf_Addr)(defobj->relocbase + def->st_value);
725 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
726 defobj->strtab + def->st_name, basename(obj->path),
727 (void *)target, basename(defobj->path));
730 * Write the new contents for the jmpslot. Note that depending on
731 * architecture, the value which we need to return back to the
732 * lazy binding trampoline may or may not be the target
733 * address. The value returned from reloc_jmpslot() is the value
734 * that the trampoline needs.
736 target = reloc_jmpslot(where, target, defobj, obj, rel);
737 lock_release(rtld_bind_lock, &lockstate);
742 * Error reporting function. Use it like printf. If formats the message
743 * into a buffer, and sets things up so that the next call to dlerror()
744 * will return the message.
747 _rtld_error(const char *fmt, ...)
749 static char buf[512];
753 rtld_vsnprintf(buf, sizeof buf, fmt, ap);
759 * Return a dynamically-allocated copy of the current error message, if any.
764 return error_message == NULL ? NULL : xstrdup(error_message);
768 * Restore the current error message from a copy which was previously saved
769 * by errmsg_save(). The copy is freed.
772 errmsg_restore(char *saved_msg)
774 if (saved_msg == NULL)
775 error_message = NULL;
777 _rtld_error("%s", saved_msg);
783 basename(const char *name)
785 const char *p = strrchr(name, '/');
786 return p != NULL ? p + 1 : name;
789 static struct utsname uts;
792 origin_subst_one(Obj_Entry *obj, char *real, const char *kw,
793 const char *subst, bool may_free)
795 char *p, *p1, *res, *resp;
796 int subst_len, kw_len, subst_count, old_len, new_len;
801 * First, count the number of the keyword occurrences, to
802 * preallocate the final string.
804 for (p = real, subst_count = 0;; p = p1 + kw_len, subst_count++) {
811 * If the keyword is not found, just return.
813 * Return non-substituted string if resolution failed. We
814 * cannot do anything more reasonable, the failure mode of the
815 * caller is unresolved library anyway.
817 if (subst_count == 0 || (obj != NULL && !obj_resolve_origin(obj)))
818 return (may_free ? real : xstrdup(real));
820 subst = obj->origin_path;
823 * There is indeed something to substitute. Calculate the
824 * length of the resulting string, and allocate it.
826 subst_len = strlen(subst);
827 old_len = strlen(real);
828 new_len = old_len + (subst_len - kw_len) * subst_count;
829 res = xmalloc(new_len + 1);
832 * Now, execute the substitution loop.
834 for (p = real, resp = res, *resp = '\0';;) {
837 /* Copy the prefix before keyword. */
838 memcpy(resp, p, p1 - p);
840 /* Keyword replacement. */
841 memcpy(resp, subst, subst_len);
849 /* Copy to the end of string and finish. */
857 origin_subst(Obj_Entry *obj, char *real)
859 char *res1, *res2, *res3, *res4;
861 if (obj == NULL || !trust)
862 return (xstrdup(real));
863 if (uts.sysname[0] == '\0') {
864 if (uname(&uts) != 0) {
865 _rtld_error("utsname failed: %d", errno);
869 res1 = origin_subst_one(obj, real, "$ORIGIN", NULL, false);
870 res2 = origin_subst_one(NULL, res1, "$OSNAME", uts.sysname, true);
871 res3 = origin_subst_one(NULL, res2, "$OSREL", uts.release, true);
872 res4 = origin_subst_one(NULL, res3, "$PLATFORM", uts.machine, true);
879 const char *msg = dlerror();
883 rtld_fdputstr(STDERR_FILENO, msg);
884 rtld_fdputchar(STDERR_FILENO, '\n');
889 * Process a shared object's DYNAMIC section, and save the important
890 * information in its Obj_Entry structure.
893 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
894 const Elf_Dyn **dyn_soname, const Elf_Dyn **dyn_runpath)
897 Needed_Entry **needed_tail = &obj->needed;
898 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
899 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
900 const Elf_Hashelt *hashtab;
901 const Elf32_Word *hashval;
902 Elf32_Word bkt, nmaskwords;
904 int plttype = DT_REL;
910 obj->bind_now = false;
911 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
912 switch (dynp->d_tag) {
915 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
919 obj->relsize = dynp->d_un.d_val;
923 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
927 obj->pltrel = (const Elf_Rel *)
928 (obj->relocbase + dynp->d_un.d_ptr);
932 obj->pltrelsize = dynp->d_un.d_val;
936 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
940 obj->relasize = dynp->d_un.d_val;
944 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
948 plttype = dynp->d_un.d_val;
949 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
953 obj->symtab = (const Elf_Sym *)
954 (obj->relocbase + dynp->d_un.d_ptr);
958 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
962 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
966 obj->strsize = dynp->d_un.d_val;
970 obj->verneed = (const Elf_Verneed *) (obj->relocbase +
975 obj->verneednum = dynp->d_un.d_val;
979 obj->verdef = (const Elf_Verdef *) (obj->relocbase +
984 obj->verdefnum = dynp->d_un.d_val;
988 obj->versyms = (const Elf_Versym *)(obj->relocbase +
994 hashtab = (const Elf_Hashelt *)(obj->relocbase +
996 obj->nbuckets = hashtab[0];
997 obj->nchains = hashtab[1];
998 obj->buckets = hashtab + 2;
999 obj->chains = obj->buckets + obj->nbuckets;
1000 obj->valid_hash_sysv = obj->nbuckets > 0 && obj->nchains > 0 &&
1001 obj->buckets != NULL;
1007 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1009 obj->nbuckets_gnu = hashtab[0];
1010 obj->symndx_gnu = hashtab[1];
1011 nmaskwords = hashtab[2];
1012 bloom_size32 = (__ELF_WORD_SIZE / 32) * nmaskwords;
1013 obj->maskwords_bm_gnu = nmaskwords - 1;
1014 obj->shift2_gnu = hashtab[3];
1015 obj->bloom_gnu = (Elf_Addr *) (hashtab + 4);
1016 obj->buckets_gnu = hashtab + 4 + bloom_size32;
1017 obj->chain_zero_gnu = obj->buckets_gnu + obj->nbuckets_gnu -
1019 /* Number of bitmask words is required to be power of 2 */
1020 obj->valid_hash_gnu = powerof2(nmaskwords) &&
1021 obj->nbuckets_gnu > 0 && obj->buckets_gnu != NULL;
1027 Needed_Entry *nep = NEW(Needed_Entry);
1028 nep->name = dynp->d_un.d_val;
1033 needed_tail = &nep->next;
1039 Needed_Entry *nep = NEW(Needed_Entry);
1040 nep->name = dynp->d_un.d_val;
1044 *needed_filtees_tail = nep;
1045 needed_filtees_tail = &nep->next;
1051 Needed_Entry *nep = NEW(Needed_Entry);
1052 nep->name = dynp->d_un.d_val;
1056 *needed_aux_filtees_tail = nep;
1057 needed_aux_filtees_tail = &nep->next;
1062 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
1066 obj->textrel = true;
1070 obj->symbolic = true;
1075 * We have to wait until later to process this, because we
1076 * might not have gotten the address of the string table yet.
1086 *dyn_runpath = dynp;
1090 obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1093 case DT_PREINIT_ARRAY:
1094 obj->preinit_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1097 case DT_PREINIT_ARRAYSZ:
1098 obj->preinit_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1102 obj->init_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1105 case DT_INIT_ARRAYSZ:
1106 obj->init_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1110 obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1114 obj->fini_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1117 case DT_FINI_ARRAYSZ:
1118 obj->fini_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1122 * Don't process DT_DEBUG on MIPS as the dynamic section
1123 * is mapped read-only. DT_MIPS_RLD_MAP is used instead.
1129 dbg("Filling in DT_DEBUG entry");
1130 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
1135 if (dynp->d_un.d_val & DF_ORIGIN)
1136 obj->z_origin = true;
1137 if (dynp->d_un.d_val & DF_SYMBOLIC)
1138 obj->symbolic = true;
1139 if (dynp->d_un.d_val & DF_TEXTREL)
1140 obj->textrel = true;
1141 if (dynp->d_un.d_val & DF_BIND_NOW)
1142 obj->bind_now = true;
1143 /*if (dynp->d_un.d_val & DF_STATIC_TLS)
1147 case DT_MIPS_LOCAL_GOTNO:
1148 obj->local_gotno = dynp->d_un.d_val;
1151 case DT_MIPS_SYMTABNO:
1152 obj->symtabno = dynp->d_un.d_val;
1155 case DT_MIPS_GOTSYM:
1156 obj->gotsym = dynp->d_un.d_val;
1159 case DT_MIPS_RLD_MAP:
1160 *((Elf_Addr *)(dynp->d_un.d_ptr)) = (Elf_Addr) &r_debug;
1164 #ifdef __powerpc64__
1165 case DT_PPC64_GLINK:
1166 obj->glink = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1171 if (dynp->d_un.d_val & DF_1_NOOPEN)
1172 obj->z_noopen = true;
1173 if (dynp->d_un.d_val & DF_1_ORIGIN)
1174 obj->z_origin = true;
1175 if (dynp->d_un.d_val & DF_1_GLOBAL)
1176 obj->z_global = true;
1177 if (dynp->d_un.d_val & DF_1_BIND_NOW)
1178 obj->bind_now = true;
1179 if (dynp->d_un.d_val & DF_1_NODELETE)
1180 obj->z_nodelete = true;
1181 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1182 obj->z_loadfltr = true;
1183 if (dynp->d_un.d_val & DF_1_INTERPOSE)
1184 obj->z_interpose = true;
1185 if (dynp->d_un.d_val & DF_1_NODEFLIB)
1186 obj->z_nodeflib = true;
1191 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1198 obj->traced = false;
1200 if (plttype == DT_RELA) {
1201 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1203 obj->pltrelasize = obj->pltrelsize;
1204 obj->pltrelsize = 0;
1207 /* Determine size of dynsym table (equal to nchains of sysv hash) */
1208 if (obj->valid_hash_sysv)
1209 obj->dynsymcount = obj->nchains;
1210 else if (obj->valid_hash_gnu) {
1211 obj->dynsymcount = 0;
1212 for (bkt = 0; bkt < obj->nbuckets_gnu; bkt++) {
1213 if (obj->buckets_gnu[bkt] == 0)
1215 hashval = &obj->chain_zero_gnu[obj->buckets_gnu[bkt]];
1218 while ((*hashval++ & 1u) == 0);
1220 obj->dynsymcount += obj->symndx_gnu;
1225 obj_resolve_origin(Obj_Entry *obj)
1228 if (obj->origin_path != NULL)
1230 obj->origin_path = xmalloc(PATH_MAX);
1231 return (rtld_dirname_abs(obj->path, obj->origin_path) != -1);
1235 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1236 const Elf_Dyn *dyn_soname, const Elf_Dyn *dyn_runpath)
1239 if (obj->z_origin && !obj_resolve_origin(obj))
1242 if (dyn_runpath != NULL) {
1243 obj->runpath = (char *)obj->strtab + dyn_runpath->d_un.d_val;
1244 obj->runpath = origin_subst(obj, obj->runpath);
1245 } else if (dyn_rpath != NULL) {
1246 obj->rpath = (char *)obj->strtab + dyn_rpath->d_un.d_val;
1247 obj->rpath = origin_subst(obj, obj->rpath);
1249 if (dyn_soname != NULL)
1250 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1254 digest_dynamic(Obj_Entry *obj, int early)
1256 const Elf_Dyn *dyn_rpath;
1257 const Elf_Dyn *dyn_soname;
1258 const Elf_Dyn *dyn_runpath;
1260 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname, &dyn_runpath);
1261 digest_dynamic2(obj, dyn_rpath, dyn_soname, dyn_runpath);
1265 * Process a shared object's program header. This is used only for the
1266 * main program, when the kernel has already loaded the main program
1267 * into memory before calling the dynamic linker. It creates and
1268 * returns an Obj_Entry structure.
1271 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1274 const Elf_Phdr *phlimit = phdr + phnum;
1276 Elf_Addr note_start, note_end;
1280 for (ph = phdr; ph < phlimit; ph++) {
1281 if (ph->p_type != PT_PHDR)
1285 obj->phsize = ph->p_memsz;
1286 obj->relocbase = (caddr_t)phdr - ph->p_vaddr;
1290 obj->stack_flags = PF_X | PF_R | PF_W;
1292 for (ph = phdr; ph < phlimit; ph++) {
1293 switch (ph->p_type) {
1296 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1300 if (nsegs == 0) { /* First load segment */
1301 obj->vaddrbase = trunc_page(ph->p_vaddr);
1302 obj->mapbase = obj->vaddrbase + obj->relocbase;
1303 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
1305 } else { /* Last load segment */
1306 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1313 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1318 obj->tlssize = ph->p_memsz;
1319 obj->tlsalign = ph->p_align;
1320 obj->tlsinitsize = ph->p_filesz;
1321 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1325 obj->stack_flags = ph->p_flags;
1329 obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1330 obj->relro_size = round_page(ph->p_memsz);
1334 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
1335 note_end = note_start + ph->p_filesz;
1336 digest_notes(obj, note_start, note_end);
1341 _rtld_error("%s: too few PT_LOAD segments", path);
1350 digest_notes(Obj_Entry *obj, Elf_Addr note_start, Elf_Addr note_end)
1352 const Elf_Note *note;
1353 const char *note_name;
1356 for (note = (const Elf_Note *)note_start; (Elf_Addr)note < note_end;
1357 note = (const Elf_Note *)((const char *)(note + 1) +
1358 roundup2(note->n_namesz, sizeof(Elf32_Addr)) +
1359 roundup2(note->n_descsz, sizeof(Elf32_Addr)))) {
1360 if (note->n_namesz != sizeof(NOTE_FREEBSD_VENDOR) ||
1361 note->n_descsz != sizeof(int32_t))
1363 if (note->n_type != NT_FREEBSD_ABI_TAG &&
1364 note->n_type != NT_FREEBSD_NOINIT_TAG)
1366 note_name = (const char *)(note + 1);
1367 if (strncmp(NOTE_FREEBSD_VENDOR, note_name,
1368 sizeof(NOTE_FREEBSD_VENDOR)) != 0)
1370 switch (note->n_type) {
1371 case NT_FREEBSD_ABI_TAG:
1372 /* FreeBSD osrel note */
1373 p = (uintptr_t)(note + 1);
1374 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1375 obj->osrel = *(const int32_t *)(p);
1376 dbg("note osrel %d", obj->osrel);
1378 case NT_FREEBSD_NOINIT_TAG:
1379 /* FreeBSD 'crt does not call init' note */
1380 obj->crt_no_init = true;
1381 dbg("note crt_no_init");
1388 dlcheck(void *handle)
1392 TAILQ_FOREACH(obj, &obj_list, next) {
1393 if (obj == (Obj_Entry *) handle)
1397 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1398 _rtld_error("Invalid shared object handle %p", handle);
1405 * If the given object is already in the donelist, return true. Otherwise
1406 * add the object to the list and return false.
1409 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1413 for (i = 0; i < dlp->num_used; i++)
1414 if (dlp->objs[i] == obj)
1417 * Our donelist allocation should always be sufficient. But if
1418 * our threads locking isn't working properly, more shared objects
1419 * could have been loaded since we allocated the list. That should
1420 * never happen, but we'll handle it properly just in case it does.
1422 if (dlp->num_used < dlp->num_alloc)
1423 dlp->objs[dlp->num_used++] = obj;
1428 * Hash function for symbol table lookup. Don't even think about changing
1429 * this. It is specified by the System V ABI.
1432 elf_hash(const char *name)
1434 const unsigned char *p = (const unsigned char *) name;
1435 unsigned long h = 0;
1438 while (*p != '\0') {
1439 h = (h << 4) + *p++;
1440 if ((g = h & 0xf0000000) != 0)
1448 * The GNU hash function is the Daniel J. Bernstein hash clipped to 32 bits
1449 * unsigned in case it's implemented with a wider type.
1452 gnu_hash(const char *s)
1458 for (c = *s; c != '\0'; c = *++s)
1460 return (h & 0xffffffff);
1465 * Find the library with the given name, and return its full pathname.
1466 * The returned string is dynamically allocated. Generates an error
1467 * message and returns NULL if the library cannot be found.
1469 * If the second argument is non-NULL, then it refers to an already-
1470 * loaded shared object, whose library search path will be searched.
1472 * If a library is successfully located via LD_LIBRARY_PATH_FDS, its
1473 * descriptor (which is close-on-exec) will be passed out via the third
1476 * The search order is:
1477 * DT_RPATH in the referencing file _unless_ DT_RUNPATH is present (1)
1478 * DT_RPATH of the main object if DSO without defined DT_RUNPATH (1)
1480 * DT_RUNPATH in the referencing file
1481 * ldconfig hints (if -z nodefaultlib, filter out default library directories
1483 * /lib:/usr/lib _unless_ the referencing file is linked with -z nodefaultlib
1485 * (1) Handled in digest_dynamic2 - rpath left NULL if runpath defined.
1488 find_library(const char *xname, const Obj_Entry *refobj, int *fdp)
1492 bool nodeflib, objgiven;
1494 objgiven = refobj != NULL;
1495 if (strchr(xname, '/') != NULL) { /* Hard coded pathname */
1496 if (xname[0] != '/' && !trust) {
1497 _rtld_error("Absolute pathname required for shared object \"%s\"",
1501 return (origin_subst(__DECONST(Obj_Entry *, refobj),
1502 __DECONST(char *, xname)));
1505 if (libmap_disable || !objgiven ||
1506 (name = lm_find(refobj->path, xname)) == NULL)
1507 name = (char *)xname;
1509 dbg(" Searching for \"%s\"", name);
1512 * If refobj->rpath != NULL, then refobj->runpath is NULL. Fall
1513 * back to pre-conforming behaviour if user requested so with
1514 * LD_LIBRARY_PATH_RPATH environment variable and ignore -z
1517 if (objgiven && refobj->rpath != NULL && ld_library_path_rpath) {
1518 if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
1520 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
1521 (pathname = search_library_pathfds(name, ld_library_dirs, fdp)) != NULL ||
1522 (pathname = search_library_path(name, gethints(false))) != NULL ||
1523 (pathname = search_library_path(name, ld_standard_library_path)) != NULL)
1526 nodeflib = objgiven ? refobj->z_nodeflib : false;
1528 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
1529 (objgiven && refobj->runpath == NULL && refobj != obj_main &&
1530 (pathname = search_library_path(name, obj_main->rpath)) != NULL) ||
1531 (pathname = search_library_path(name, ld_library_path)) != NULL ||
1533 (pathname = search_library_path(name, refobj->runpath)) != NULL) ||
1534 (pathname = search_library_pathfds(name, ld_library_dirs, fdp)) != NULL ||
1535 (pathname = search_library_path(name, gethints(nodeflib))) != NULL ||
1536 (objgiven && !nodeflib &&
1537 (pathname = search_library_path(name, ld_standard_library_path)) != NULL))
1541 if (objgiven && refobj->path != NULL) {
1542 _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
1543 name, basename(refobj->path));
1545 _rtld_error("Shared object \"%s\" not found", name);
1551 * Given a symbol number in a referencing object, find the corresponding
1552 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1553 * no definition was found. Returns a pointer to the Obj_Entry of the
1554 * defining object via the reference parameter DEFOBJ_OUT.
1557 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1558 const Obj_Entry **defobj_out, int flags, SymCache *cache,
1559 RtldLockState *lockstate)
1563 const Obj_Entry *defobj;
1569 * If we have already found this symbol, get the information from
1572 if (symnum >= refobj->dynsymcount)
1573 return NULL; /* Bad object */
1574 if (cache != NULL && cache[symnum].sym != NULL) {
1575 *defobj_out = cache[symnum].obj;
1576 return cache[symnum].sym;
1579 ref = refobj->symtab + symnum;
1580 name = refobj->strtab + ref->st_name;
1585 * We don't have to do a full scale lookup if the symbol is local.
1586 * We know it will bind to the instance in this load module; to
1587 * which we already have a pointer (ie ref). By not doing a lookup,
1588 * we not only improve performance, but it also avoids unresolvable
1589 * symbols when local symbols are not in the hash table. This has
1590 * been seen with the ia64 toolchain.
1592 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1593 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1594 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1597 symlook_init(&req, name);
1599 req.ventry = fetch_ventry(refobj, symnum);
1600 req.lockstate = lockstate;
1601 res = symlook_default(&req, refobj);
1604 defobj = req.defobj_out;
1612 * If we found no definition and the reference is weak, treat the
1613 * symbol as having the value zero.
1615 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1621 *defobj_out = defobj;
1622 /* Record the information in the cache to avoid subsequent lookups. */
1623 if (cache != NULL) {
1624 cache[symnum].sym = def;
1625 cache[symnum].obj = defobj;
1628 if (refobj != &obj_rtld)
1629 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1635 * Return the search path from the ldconfig hints file, reading it if
1636 * necessary. If nostdlib is true, then the default search paths are
1637 * not added to result.
1639 * Returns NULL if there are problems with the hints file,
1640 * or if the search path there is empty.
1643 gethints(bool nostdlib)
1645 static char *hints, *filtered_path;
1646 static struct elfhints_hdr hdr;
1647 struct fill_search_info_args sargs, hargs;
1648 struct dl_serinfo smeta, hmeta, *SLPinfo, *hintinfo;
1649 struct dl_serpath *SLPpath, *hintpath;
1651 struct stat hint_stat;
1652 unsigned int SLPndx, hintndx, fndx, fcount;
1658 /* First call, read the hints file */
1659 if (hints == NULL) {
1660 /* Keep from trying again in case the hints file is bad. */
1663 if ((fd = open(ld_elf_hints_path, O_RDONLY | O_CLOEXEC)) == -1)
1667 * Check of hdr.dirlistlen value against type limit
1668 * intends to pacify static analyzers. Further
1669 * paranoia leads to checks that dirlist is fully
1670 * contained in the file range.
1672 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1673 hdr.magic != ELFHINTS_MAGIC ||
1674 hdr.version != 1 || hdr.dirlistlen > UINT_MAX / 2 ||
1675 fstat(fd, &hint_stat) == -1) {
1682 if (dl + hdr.dirlist < dl)
1685 if (dl + hdr.dirlistlen < dl)
1687 dl += hdr.dirlistlen;
1688 if (dl > hint_stat.st_size)
1690 p = xmalloc(hdr.dirlistlen + 1);
1692 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1693 read(fd, p, hdr.dirlistlen + 1) !=
1694 (ssize_t)hdr.dirlistlen + 1 || p[hdr.dirlistlen] != '\0') {
1703 * If caller agreed to receive list which includes the default
1704 * paths, we are done. Otherwise, if we still did not
1705 * calculated filtered result, do it now.
1708 return (hints[0] != '\0' ? hints : NULL);
1709 if (filtered_path != NULL)
1713 * Obtain the list of all configured search paths, and the
1714 * list of the default paths.
1716 * First estimate the size of the results.
1718 smeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1720 hmeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1723 sargs.request = RTLD_DI_SERINFOSIZE;
1724 sargs.serinfo = &smeta;
1725 hargs.request = RTLD_DI_SERINFOSIZE;
1726 hargs.serinfo = &hmeta;
1728 path_enumerate(ld_standard_library_path, fill_search_info, &sargs);
1729 path_enumerate(hints, fill_search_info, &hargs);
1731 SLPinfo = xmalloc(smeta.dls_size);
1732 hintinfo = xmalloc(hmeta.dls_size);
1735 * Next fetch both sets of paths.
1737 sargs.request = RTLD_DI_SERINFO;
1738 sargs.serinfo = SLPinfo;
1739 sargs.serpath = &SLPinfo->dls_serpath[0];
1740 sargs.strspace = (char *)&SLPinfo->dls_serpath[smeta.dls_cnt];
1742 hargs.request = RTLD_DI_SERINFO;
1743 hargs.serinfo = hintinfo;
1744 hargs.serpath = &hintinfo->dls_serpath[0];
1745 hargs.strspace = (char *)&hintinfo->dls_serpath[hmeta.dls_cnt];
1747 path_enumerate(ld_standard_library_path, fill_search_info, &sargs);
1748 path_enumerate(hints, fill_search_info, &hargs);
1751 * Now calculate the difference between two sets, by excluding
1752 * standard paths from the full set.
1756 filtered_path = xmalloc(hdr.dirlistlen + 1);
1757 hintpath = &hintinfo->dls_serpath[0];
1758 for (hintndx = 0; hintndx < hmeta.dls_cnt; hintndx++, hintpath++) {
1760 SLPpath = &SLPinfo->dls_serpath[0];
1762 * Check each standard path against current.
1764 for (SLPndx = 0; SLPndx < smeta.dls_cnt; SLPndx++, SLPpath++) {
1765 /* matched, skip the path */
1766 if (!strcmp(hintpath->dls_name, SLPpath->dls_name)) {
1774 * Not matched against any standard path, add the path
1775 * to result. Separate consequtive paths with ':'.
1778 filtered_path[fndx] = ':';
1782 flen = strlen(hintpath->dls_name);
1783 strncpy((filtered_path + fndx), hintpath->dls_name, flen);
1786 filtered_path[fndx] = '\0';
1792 return (filtered_path[0] != '\0' ? filtered_path : NULL);
1796 init_dag(Obj_Entry *root)
1798 const Needed_Entry *needed;
1799 const Objlist_Entry *elm;
1802 if (root->dag_inited)
1804 donelist_init(&donelist);
1806 /* Root object belongs to own DAG. */
1807 objlist_push_tail(&root->dldags, root);
1808 objlist_push_tail(&root->dagmembers, root);
1809 donelist_check(&donelist, root);
1812 * Add dependencies of root object to DAG in breadth order
1813 * by exploiting the fact that each new object get added
1814 * to the tail of the dagmembers list.
1816 STAILQ_FOREACH(elm, &root->dagmembers, link) {
1817 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
1818 if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
1820 objlist_push_tail(&needed->obj->dldags, root);
1821 objlist_push_tail(&root->dagmembers, needed->obj);
1824 root->dag_inited = true;
1828 globallist_curr(const Obj_Entry *obj)
1835 return (__DECONST(Obj_Entry *, obj));
1836 obj = TAILQ_PREV(obj, obj_entry_q, next);
1841 globallist_next(const Obj_Entry *obj)
1845 obj = TAILQ_NEXT(obj, next);
1849 return (__DECONST(Obj_Entry *, obj));
1854 process_z(Obj_Entry *root)
1856 const Objlist_Entry *elm;
1860 * Walk over object DAG and process every dependent object
1861 * that is marked as DF_1_NODELETE or DF_1_GLOBAL. They need
1862 * to grow their own DAG.
1864 * For DF_1_GLOBAL, DAG is required for symbol lookups in
1865 * symlook_global() to work.
1867 * For DF_1_NODELETE, the DAG should have its reference upped.
1869 STAILQ_FOREACH(elm, &root->dagmembers, link) {
1873 if (obj->z_nodelete && !obj->ref_nodel) {
1874 dbg("obj %s -z nodelete", obj->path);
1877 obj->ref_nodel = true;
1879 if (obj->z_global && objlist_find(&list_global, obj) == NULL) {
1880 dbg("obj %s -z global", obj->path);
1881 objlist_push_tail(&list_global, obj);
1887 * Initialize the dynamic linker. The argument is the address at which
1888 * the dynamic linker has been mapped into memory. The primary task of
1889 * this function is to relocate the dynamic linker.
1892 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
1894 Obj_Entry objtmp; /* Temporary rtld object */
1895 const Elf_Ehdr *ehdr;
1896 const Elf_Dyn *dyn_rpath;
1897 const Elf_Dyn *dyn_soname;
1898 const Elf_Dyn *dyn_runpath;
1900 #ifdef RTLD_INIT_PAGESIZES_EARLY
1901 /* The page size is required by the dynamic memory allocator. */
1902 init_pagesizes(aux_info);
1906 * Conjure up an Obj_Entry structure for the dynamic linker.
1908 * The "path" member can't be initialized yet because string constants
1909 * cannot yet be accessed. Below we will set it correctly.
1911 memset(&objtmp, 0, sizeof(objtmp));
1914 objtmp.mapbase = mapbase;
1916 objtmp.relocbase = mapbase;
1918 if (RTLD_IS_DYNAMIC()) {
1919 objtmp.dynamic = rtld_dynamic(&objtmp);
1920 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname, &dyn_runpath);
1921 assert(objtmp.needed == NULL);
1922 #if !defined(__mips__)
1923 /* MIPS has a bogus DT_TEXTREL. */
1924 assert(!objtmp.textrel);
1928 * Temporarily put the dynamic linker entry into the object list, so
1929 * that symbols can be found.
1932 relocate_objects(&objtmp, true, &objtmp, 0, NULL);
1934 ehdr = (Elf_Ehdr *)mapbase;
1935 objtmp.phdr = (Elf_Phdr *)((char *)mapbase + ehdr->e_phoff);
1936 objtmp.phsize = ehdr->e_phnum * sizeof(objtmp.phdr[0]);
1938 /* Initialize the object list. */
1939 TAILQ_INIT(&obj_list);
1941 /* Now that non-local variables can be accesses, copy out obj_rtld. */
1942 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1944 #ifndef RTLD_INIT_PAGESIZES_EARLY
1945 /* The page size is required by the dynamic memory allocator. */
1946 init_pagesizes(aux_info);
1949 if (aux_info[AT_OSRELDATE] != NULL)
1950 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
1952 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname, dyn_runpath);
1954 /* Replace the path with a dynamically allocated copy. */
1955 obj_rtld.path = xstrdup(ld_path_rtld);
1957 r_debug.r_brk = r_debug_state;
1958 r_debug.r_state = RT_CONSISTENT;
1962 * Retrieve the array of supported page sizes. The kernel provides the page
1963 * sizes in increasing order.
1966 init_pagesizes(Elf_Auxinfo **aux_info)
1968 static size_t psa[MAXPAGESIZES];
1972 if (aux_info[AT_PAGESIZES] != NULL && aux_info[AT_PAGESIZESLEN] !=
1974 size = aux_info[AT_PAGESIZESLEN]->a_un.a_val;
1975 pagesizes = aux_info[AT_PAGESIZES]->a_un.a_ptr;
1978 if (sysctlnametomib("hw.pagesizes", mib, &len) == 0)
1981 /* As a fallback, retrieve the base page size. */
1982 size = sizeof(psa[0]);
1983 if (aux_info[AT_PAGESZ] != NULL) {
1984 psa[0] = aux_info[AT_PAGESZ]->a_un.a_val;
1988 mib[1] = HW_PAGESIZE;
1992 if (sysctl(mib, len, psa, &size, NULL, 0) == -1) {
1993 _rtld_error("sysctl for hw.pagesize(s) failed");
1999 npagesizes = size / sizeof(pagesizes[0]);
2000 /* Discard any invalid entries at the end of the array. */
2001 while (npagesizes > 0 && pagesizes[npagesizes - 1] == 0)
2006 * Add the init functions from a needed object list (and its recursive
2007 * needed objects) to "list". This is not used directly; it is a helper
2008 * function for initlist_add_objects(). The write lock must be held
2009 * when this function is called.
2012 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
2014 /* Recursively process the successor needed objects. */
2015 if (needed->next != NULL)
2016 initlist_add_neededs(needed->next, list);
2018 /* Process the current needed object. */
2019 if (needed->obj != NULL)
2020 initlist_add_objects(needed->obj, needed->obj, list);
2024 * Scan all of the DAGs rooted in the range of objects from "obj" to
2025 * "tail" and add their init functions to "list". This recurses over
2026 * the DAGs and ensure the proper init ordering such that each object's
2027 * needed libraries are initialized before the object itself. At the
2028 * same time, this function adds the objects to the global finalization
2029 * list "list_fini" in the opposite order. The write lock must be
2030 * held when this function is called.
2033 initlist_add_objects(Obj_Entry *obj, Obj_Entry *tail, Objlist *list)
2037 if (obj->init_scanned || obj->init_done)
2039 obj->init_scanned = true;
2041 /* Recursively process the successor objects. */
2042 nobj = globallist_next(obj);
2043 if (nobj != NULL && obj != tail)
2044 initlist_add_objects(nobj, tail, list);
2046 /* Recursively process the needed objects. */
2047 if (obj->needed != NULL)
2048 initlist_add_neededs(obj->needed, list);
2049 if (obj->needed_filtees != NULL)
2050 initlist_add_neededs(obj->needed_filtees, list);
2051 if (obj->needed_aux_filtees != NULL)
2052 initlist_add_neededs(obj->needed_aux_filtees, list);
2054 /* Add the object to the init list. */
2055 if (obj->preinit_array != (Elf_Addr)NULL || obj->init != (Elf_Addr)NULL ||
2056 obj->init_array != (Elf_Addr)NULL)
2057 objlist_push_tail(list, obj);
2059 /* Add the object to the global fini list in the reverse order. */
2060 if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL)
2061 && !obj->on_fini_list) {
2062 objlist_push_head(&list_fini, obj);
2063 obj->on_fini_list = true;
2068 #define FPTR_TARGET(f) ((Elf_Addr) (f))
2072 free_needed_filtees(Needed_Entry *n)
2074 Needed_Entry *needed, *needed1;
2076 for (needed = n; needed != NULL; needed = needed->next) {
2077 if (needed->obj != NULL) {
2078 dlclose(needed->obj);
2082 for (needed = n; needed != NULL; needed = needed1) {
2083 needed1 = needed->next;
2089 unload_filtees(Obj_Entry *obj)
2092 free_needed_filtees(obj->needed_filtees);
2093 obj->needed_filtees = NULL;
2094 free_needed_filtees(obj->needed_aux_filtees);
2095 obj->needed_aux_filtees = NULL;
2096 obj->filtees_loaded = false;
2100 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags,
2101 RtldLockState *lockstate)
2104 for (; needed != NULL; needed = needed->next) {
2105 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
2106 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
2107 RTLD_LOCAL, lockstate);
2112 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
2115 lock_restart_for_upgrade(lockstate);
2116 if (!obj->filtees_loaded) {
2117 load_filtee1(obj, obj->needed_filtees, flags, lockstate);
2118 load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate);
2119 obj->filtees_loaded = true;
2124 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
2128 for (; needed != NULL; needed = needed->next) {
2129 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
2130 flags & ~RTLD_LO_NOLOAD);
2131 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
2138 * Given a shared object, traverse its list of needed objects, and load
2139 * each of them. Returns 0 on success. Generates an error message and
2140 * returns -1 on failure.
2143 load_needed_objects(Obj_Entry *first, int flags)
2147 for (obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
2150 if (process_needed(obj, obj->needed, flags) == -1)
2157 load_preload_objects(void)
2159 char *p = ld_preload;
2161 static const char delim[] = " \t:;";
2166 p += strspn(p, delim);
2167 while (*p != '\0') {
2168 size_t len = strcspn(p, delim);
2173 obj = load_object(p, -1, NULL, 0);
2175 return -1; /* XXX - cleanup */
2176 obj->z_interpose = true;
2179 p += strspn(p, delim);
2181 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
2186 printable_path(const char *path)
2189 return (path == NULL ? "<unknown>" : path);
2193 * Load a shared object into memory, if it is not already loaded. The
2194 * object may be specified by name or by user-supplied file descriptor
2195 * fd_u. In the later case, the fd_u descriptor is not closed, but its
2198 * Returns a pointer to the Obj_Entry for the object. Returns NULL
2202 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
2211 TAILQ_FOREACH(obj, &obj_list, next) {
2214 if (object_match_name(obj, name))
2218 path = find_library(name, refobj, &fd);
2226 * search_library_pathfds() opens a fresh file descriptor for the
2227 * library, so there is no need to dup().
2229 } else if (fd_u == -1) {
2231 * If we didn't find a match by pathname, or the name is not
2232 * supplied, open the file and check again by device and inode.
2233 * This avoids false mismatches caused by multiple links or ".."
2236 * To avoid a race, we open the file and use fstat() rather than
2239 if ((fd = open(path, O_RDONLY | O_CLOEXEC | O_VERIFY)) == -1) {
2240 _rtld_error("Cannot open \"%s\"", path);
2245 fd = fcntl(fd_u, F_DUPFD_CLOEXEC, 0);
2247 _rtld_error("Cannot dup fd");
2252 if (fstat(fd, &sb) == -1) {
2253 _rtld_error("Cannot fstat \"%s\"", printable_path(path));
2258 TAILQ_FOREACH(obj, &obj_list, next) {
2261 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
2264 if (obj != NULL && name != NULL) {
2265 object_add_name(obj, name);
2270 if (flags & RTLD_LO_NOLOAD) {
2276 /* First use of this object, so we must map it in */
2277 obj = do_load_object(fd, name, path, &sb, flags);
2286 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
2293 * but first, make sure that environment variables haven't been
2294 * used to circumvent the noexec flag on a filesystem.
2296 if (dangerous_ld_env) {
2297 if (fstatfs(fd, &fs) != 0) {
2298 _rtld_error("Cannot fstatfs \"%s\"", printable_path(path));
2301 if (fs.f_flags & MNT_NOEXEC) {
2302 _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
2306 dbg("loading \"%s\"", printable_path(path));
2307 obj = map_object(fd, printable_path(path), sbp);
2312 * If DT_SONAME is present in the object, digest_dynamic2 already
2313 * added it to the object names.
2316 object_add_name(obj, name);
2318 digest_dynamic(obj, 0);
2319 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path,
2320 obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount);
2321 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
2323 dbg("refusing to load non-loadable \"%s\"", obj->path);
2324 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
2325 munmap(obj->mapbase, obj->mapsize);
2330 obj->dlopened = (flags & RTLD_LO_DLOPEN) != 0;
2331 TAILQ_INSERT_TAIL(&obj_list, obj, next);
2334 linkmap_add(obj); /* for GDB & dlinfo() */
2335 max_stack_flags |= obj->stack_flags;
2337 dbg(" %p .. %p: %s", obj->mapbase,
2338 obj->mapbase + obj->mapsize - 1, obj->path);
2340 dbg(" WARNING: %s has impure text", obj->path);
2341 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
2348 obj_from_addr(const void *addr)
2352 TAILQ_FOREACH(obj, &obj_list, next) {
2355 if (addr < (void *) obj->mapbase)
2357 if (addr < (void *) (obj->mapbase + obj->mapsize))
2366 Elf_Addr *preinit_addr;
2369 preinit_addr = (Elf_Addr *)obj_main->preinit_array;
2370 if (preinit_addr == NULL)
2373 for (index = 0; index < obj_main->preinit_array_num; index++) {
2374 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) {
2375 dbg("calling preinit function for %s at %p", obj_main->path,
2376 (void *)preinit_addr[index]);
2377 LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index],
2378 0, 0, obj_main->path);
2379 call_init_pointer(obj_main, preinit_addr[index]);
2385 * Call the finalization functions for each of the objects in "list"
2386 * belonging to the DAG of "root" and referenced once. If NULL "root"
2387 * is specified, every finalization function will be called regardless
2388 * of the reference count and the list elements won't be freed. All of
2389 * the objects are expected to have non-NULL fini functions.
2392 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
2396 Elf_Addr *fini_addr;
2399 assert(root == NULL || root->refcount == 1);
2402 * Preserve the current error message since a fini function might
2403 * call into the dynamic linker and overwrite it.
2405 saved_msg = errmsg_save();
2407 STAILQ_FOREACH(elm, list, link) {
2408 if (root != NULL && (elm->obj->refcount != 1 ||
2409 objlist_find(&root->dagmembers, elm->obj) == NULL))
2411 /* Remove object from fini list to prevent recursive invocation. */
2412 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2414 * XXX: If a dlopen() call references an object while the
2415 * fini function is in progress, we might end up trying to
2416 * unload the referenced object in dlclose() or the object
2417 * won't be unloaded although its fini function has been
2420 lock_release(rtld_bind_lock, lockstate);
2423 * It is legal to have both DT_FINI and DT_FINI_ARRAY defined.
2424 * When this happens, DT_FINI_ARRAY is processed first.
2426 fini_addr = (Elf_Addr *)elm->obj->fini_array;
2427 if (fini_addr != NULL && elm->obj->fini_array_num > 0) {
2428 for (index = elm->obj->fini_array_num - 1; index >= 0;
2430 if (fini_addr[index] != 0 && fini_addr[index] != 1) {
2431 dbg("calling fini function for %s at %p",
2432 elm->obj->path, (void *)fini_addr[index]);
2433 LD_UTRACE(UTRACE_FINI_CALL, elm->obj,
2434 (void *)fini_addr[index], 0, 0, elm->obj->path);
2435 call_initfini_pointer(elm->obj, fini_addr[index]);
2439 if (elm->obj->fini != (Elf_Addr)NULL) {
2440 dbg("calling fini function for %s at %p", elm->obj->path,
2441 (void *)elm->obj->fini);
2442 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini,
2443 0, 0, elm->obj->path);
2444 call_initfini_pointer(elm->obj, elm->obj->fini);
2446 wlock_acquire(rtld_bind_lock, lockstate);
2447 /* No need to free anything if process is going down. */
2451 * We must restart the list traversal after every fini call
2452 * because a dlclose() call from the fini function or from
2453 * another thread might have modified the reference counts.
2457 } while (elm != NULL);
2458 errmsg_restore(saved_msg);
2462 * Call the initialization functions for each of the objects in
2463 * "list". All of the objects are expected to have non-NULL init
2467 objlist_call_init(Objlist *list, RtldLockState *lockstate)
2472 Elf_Addr *init_addr;
2476 * Clean init_scanned flag so that objects can be rechecked and
2477 * possibly initialized earlier if any of vectors called below
2478 * cause the change by using dlopen.
2480 TAILQ_FOREACH(obj, &obj_list, next) {
2483 obj->init_scanned = false;
2487 * Preserve the current error message since an init function might
2488 * call into the dynamic linker and overwrite it.
2490 saved_msg = errmsg_save();
2491 STAILQ_FOREACH(elm, list, link) {
2492 if (elm->obj->init_done) /* Initialized early. */
2495 * Race: other thread might try to use this object before current
2496 * one completes the initilization. Not much can be done here
2497 * without better locking.
2499 elm->obj->init_done = true;
2500 lock_release(rtld_bind_lock, lockstate);
2503 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined.
2504 * When this happens, DT_INIT is processed first.
2506 if (elm->obj->init != (Elf_Addr)NULL) {
2507 dbg("calling init function for %s at %p", elm->obj->path,
2508 (void *)elm->obj->init);
2509 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init,
2510 0, 0, elm->obj->path);
2511 call_initfini_pointer(elm->obj, elm->obj->init);
2513 init_addr = (Elf_Addr *)elm->obj->init_array;
2514 if (init_addr != NULL) {
2515 for (index = 0; index < elm->obj->init_array_num; index++) {
2516 if (init_addr[index] != 0 && init_addr[index] != 1) {
2517 dbg("calling init function for %s at %p", elm->obj->path,
2518 (void *)init_addr[index]);
2519 LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
2520 (void *)init_addr[index], 0, 0, elm->obj->path);
2521 call_init_pointer(elm->obj, init_addr[index]);
2525 wlock_acquire(rtld_bind_lock, lockstate);
2527 errmsg_restore(saved_msg);
2531 objlist_clear(Objlist *list)
2535 while (!STAILQ_EMPTY(list)) {
2536 elm = STAILQ_FIRST(list);
2537 STAILQ_REMOVE_HEAD(list, link);
2542 static Objlist_Entry *
2543 objlist_find(Objlist *list, const Obj_Entry *obj)
2547 STAILQ_FOREACH(elm, list, link)
2548 if (elm->obj == obj)
2554 objlist_init(Objlist *list)
2560 objlist_push_head(Objlist *list, Obj_Entry *obj)
2564 elm = NEW(Objlist_Entry);
2566 STAILQ_INSERT_HEAD(list, elm, link);
2570 objlist_push_tail(Objlist *list, Obj_Entry *obj)
2574 elm = NEW(Objlist_Entry);
2576 STAILQ_INSERT_TAIL(list, elm, link);
2580 objlist_put_after(Objlist *list, Obj_Entry *listobj, Obj_Entry *obj)
2582 Objlist_Entry *elm, *listelm;
2584 STAILQ_FOREACH(listelm, list, link) {
2585 if (listelm->obj == listobj)
2588 elm = NEW(Objlist_Entry);
2590 if (listelm != NULL)
2591 STAILQ_INSERT_AFTER(list, listelm, elm, link);
2593 STAILQ_INSERT_TAIL(list, elm, link);
2597 objlist_remove(Objlist *list, Obj_Entry *obj)
2601 if ((elm = objlist_find(list, obj)) != NULL) {
2602 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2608 * Relocate dag rooted in the specified object.
2609 * Returns 0 on success, or -1 on failure.
2613 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj,
2614 int flags, RtldLockState *lockstate)
2620 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2621 error = relocate_object(elm->obj, bind_now, rtldobj, flags,
2630 * Prepare for, or clean after, relocating an object marked with
2631 * DT_TEXTREL or DF_TEXTREL. Before relocating, all read-only
2632 * segments are remapped read-write. After relocations are done, the
2633 * segment's permissions are returned back to the modes specified in
2634 * the phdrs. If any relocation happened, or always for wired
2635 * program, COW is triggered.
2638 reloc_textrel_prot(Obj_Entry *obj, bool before)
2645 for (l = obj->phsize / sizeof(*ph), ph = obj->phdr; l > 0;
2647 if (ph->p_type != PT_LOAD || (ph->p_flags & PF_W) != 0)
2649 base = obj->relocbase + trunc_page(ph->p_vaddr);
2650 sz = round_page(ph->p_vaddr + ph->p_filesz) -
2651 trunc_page(ph->p_vaddr);
2652 prot = convert_prot(ph->p_flags) | (before ? PROT_WRITE : 0);
2653 if (mprotect(base, sz, prot) == -1) {
2654 _rtld_error("%s: Cannot write-%sable text segment: %s",
2655 obj->path, before ? "en" : "dis",
2656 rtld_strerror(errno));
2664 * Relocate single object.
2665 * Returns 0 on success, or -1 on failure.
2668 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
2669 int flags, RtldLockState *lockstate)
2674 obj->relocated = true;
2676 dbg("relocating \"%s\"", obj->path);
2678 if (obj->symtab == NULL || obj->strtab == NULL ||
2679 !(obj->valid_hash_sysv || obj->valid_hash_gnu)) {
2680 _rtld_error("%s: Shared object has no run-time symbol table",
2685 /* There are relocations to the write-protected text segment. */
2686 if (obj->textrel && reloc_textrel_prot(obj, true) != 0)
2689 /* Process the non-PLT non-IFUNC relocations. */
2690 if (reloc_non_plt(obj, rtldobj, flags, lockstate))
2693 /* Re-protected the text segment. */
2694 if (obj->textrel && reloc_textrel_prot(obj, false) != 0)
2697 /* Set the special PLT or GOT entries. */
2700 /* Process the PLT relocations. */
2701 if (reloc_plt(obj) == -1)
2703 /* Relocate the jump slots if we are doing immediate binding. */
2704 if (obj->bind_now || bind_now)
2705 if (reloc_jmpslots(obj, flags, lockstate) == -1)
2709 * Process the non-PLT IFUNC relocations. The relocations are
2710 * processed in two phases, because IFUNC resolvers may
2711 * reference other symbols, which must be readily processed
2712 * before resolvers are called.
2714 if (obj->non_plt_gnu_ifunc &&
2715 reloc_non_plt(obj, rtldobj, flags | SYMLOOK_IFUNC, lockstate))
2718 if (obj->relro_size > 0) {
2719 if (mprotect(obj->relro_page, obj->relro_size,
2721 _rtld_error("%s: Cannot enforce relro protection: %s",
2722 obj->path, rtld_strerror(errno));
2728 * Set up the magic number and version in the Obj_Entry. These
2729 * were checked in the crt1.o from the original ElfKit, so we
2730 * set them for backward compatibility.
2732 obj->magic = RTLD_MAGIC;
2733 obj->version = RTLD_VERSION;
2739 * Relocate newly-loaded shared objects. The argument is a pointer to
2740 * the Obj_Entry for the first such object. All objects from the first
2741 * to the end of the list of objects are relocated. Returns 0 on success,
2745 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
2746 int flags, RtldLockState *lockstate)
2751 for (error = 0, obj = first; obj != NULL;
2752 obj = TAILQ_NEXT(obj, next)) {
2755 error = relocate_object(obj, bind_now, rtldobj, flags,
2764 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
2765 * referencing STT_GNU_IFUNC symbols is postponed till the other
2766 * relocations are done. The indirect functions specified as
2767 * ifunc are allowed to call other symbols, so we need to have
2768 * objects relocated before asking for resolution from indirects.
2770 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
2771 * instead of the usual lazy handling of PLT slots. It is
2772 * consistent with how GNU does it.
2775 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags,
2776 RtldLockState *lockstate)
2778 if (obj->irelative && reloc_iresolve(obj, lockstate) == -1)
2780 if ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
2781 reloc_gnu_ifunc(obj, flags, lockstate) == -1)
2787 resolve_objects_ifunc(Obj_Entry *first, bool bind_now, int flags,
2788 RtldLockState *lockstate)
2792 for (obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
2795 if (resolve_object_ifunc(obj, bind_now, flags, lockstate) == -1)
2802 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags,
2803 RtldLockState *lockstate)
2807 STAILQ_FOREACH(elm, list, link) {
2808 if (resolve_object_ifunc(elm->obj, bind_now, flags,
2816 * Cleanup procedure. It will be called (by the atexit mechanism) just
2817 * before the process exits.
2822 RtldLockState lockstate;
2824 wlock_acquire(rtld_bind_lock, &lockstate);
2826 objlist_call_fini(&list_fini, NULL, &lockstate);
2827 /* No need to remove the items from the list, since we are exiting. */
2828 if (!libmap_disable)
2830 lock_release(rtld_bind_lock, &lockstate);
2834 * Iterate over a search path, translate each element, and invoke the
2835 * callback on the result.
2838 path_enumerate(const char *path, path_enum_proc callback, void *arg)
2844 path += strspn(path, ":;");
2845 while (*path != '\0') {
2849 len = strcspn(path, ":;");
2850 trans = lm_findn(NULL, path, len);
2852 res = callback(trans, strlen(trans), arg);
2854 res = callback(path, len, arg);
2860 path += strspn(path, ":;");
2866 struct try_library_args {
2874 try_library_path(const char *dir, size_t dirlen, void *param)
2876 struct try_library_args *arg;
2879 if (*dir == '/' || trust) {
2882 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
2885 pathname = arg->buffer;
2886 strncpy(pathname, dir, dirlen);
2887 pathname[dirlen] = '/';
2888 strcpy(pathname + dirlen + 1, arg->name);
2890 dbg(" Trying \"%s\"", pathname);
2891 if (access(pathname, F_OK) == 0) { /* We found it */
2892 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
2893 strcpy(pathname, arg->buffer);
2901 search_library_path(const char *name, const char *path)
2904 struct try_library_args arg;
2910 arg.namelen = strlen(name);
2911 arg.buffer = xmalloc(PATH_MAX);
2912 arg.buflen = PATH_MAX;
2914 p = path_enumerate(path, try_library_path, &arg);
2923 * Finds the library with the given name using the directory descriptors
2924 * listed in the LD_LIBRARY_PATH_FDS environment variable.
2926 * Returns a freshly-opened close-on-exec file descriptor for the library,
2927 * or -1 if the library cannot be found.
2930 search_library_pathfds(const char *name, const char *path, int *fdp)
2932 char *envcopy, *fdstr, *found, *last_token;
2936 dbg("%s('%s', '%s', fdp)", __func__, name, path);
2938 /* Don't load from user-specified libdirs into setuid binaries. */
2942 /* We can't do anything if LD_LIBRARY_PATH_FDS isn't set. */
2946 /* LD_LIBRARY_PATH_FDS only works with relative paths. */
2947 if (name[0] == '/') {
2948 dbg("Absolute path (%s) passed to %s", name, __func__);
2953 * Use strtok_r() to walk the FD:FD:FD list. This requires a local
2954 * copy of the path, as strtok_r rewrites separator tokens
2958 envcopy = xstrdup(path);
2959 for (fdstr = strtok_r(envcopy, ":", &last_token); fdstr != NULL;
2960 fdstr = strtok_r(NULL, ":", &last_token)) {
2961 dirfd = parse_libdir(fdstr);
2964 fd = __sys_openat(dirfd, name, O_RDONLY | O_CLOEXEC | O_VERIFY);
2967 len = strlen(fdstr) + strlen(name) + 3;
2968 found = xmalloc(len);
2969 if (rtld_snprintf(found, len, "#%d/%s", dirfd, name) < 0) {
2970 _rtld_error("error generating '%d/%s'",
2974 dbg("open('%s') => %d", found, fd);
2985 dlclose(void *handle)
2988 RtldLockState lockstate;
2990 wlock_acquire(rtld_bind_lock, &lockstate);
2991 root = dlcheck(handle);
2993 lock_release(rtld_bind_lock, &lockstate);
2996 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
2999 /* Unreference the object and its dependencies. */
3000 root->dl_refcount--;
3002 if (root->refcount == 1) {
3004 * The object will be no longer referenced, so we must unload it.
3005 * First, call the fini functions.
3007 objlist_call_fini(&list_fini, root, &lockstate);
3011 /* Finish cleaning up the newly-unreferenced objects. */
3012 GDB_STATE(RT_DELETE,&root->linkmap);
3013 unload_object(root);
3014 GDB_STATE(RT_CONSISTENT,NULL);
3018 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
3019 lock_release(rtld_bind_lock, &lockstate);
3026 char *msg = error_message;
3027 error_message = NULL;
3032 * This function is deprecated and has no effect.
3035 dllockinit(void *context,
3036 void *(*lock_create)(void *context),
3037 void (*rlock_acquire)(void *lock),
3038 void (*wlock_acquire)(void *lock),
3039 void (*lock_release)(void *lock),
3040 void (*lock_destroy)(void *lock),
3041 void (*context_destroy)(void *context))
3043 static void *cur_context;
3044 static void (*cur_context_destroy)(void *);
3046 /* Just destroy the context from the previous call, if necessary. */
3047 if (cur_context_destroy != NULL)
3048 cur_context_destroy(cur_context);
3049 cur_context = context;
3050 cur_context_destroy = context_destroy;
3054 dlopen(const char *name, int mode)
3057 return (rtld_dlopen(name, -1, mode));
3061 fdlopen(int fd, int mode)
3064 return (rtld_dlopen(NULL, fd, mode));
3068 rtld_dlopen(const char *name, int fd, int mode)
3070 RtldLockState lockstate;
3073 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
3074 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
3075 if (ld_tracing != NULL) {
3076 rlock_acquire(rtld_bind_lock, &lockstate);
3077 if (sigsetjmp(lockstate.env, 0) != 0)
3078 lock_upgrade(rtld_bind_lock, &lockstate);
3079 environ = (char **)*get_program_var_addr("environ", &lockstate);
3080 lock_release(rtld_bind_lock, &lockstate);
3082 lo_flags = RTLD_LO_DLOPEN;
3083 if (mode & RTLD_NODELETE)
3084 lo_flags |= RTLD_LO_NODELETE;
3085 if (mode & RTLD_NOLOAD)
3086 lo_flags |= RTLD_LO_NOLOAD;
3087 if (ld_tracing != NULL)
3088 lo_flags |= RTLD_LO_TRACE;
3090 return (dlopen_object(name, fd, obj_main, lo_flags,
3091 mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL));
3095 dlopen_cleanup(Obj_Entry *obj)
3100 if (obj->refcount == 0)
3105 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
3106 int mode, RtldLockState *lockstate)
3108 Obj_Entry *old_obj_tail;
3111 RtldLockState mlockstate;
3114 objlist_init(&initlist);
3116 if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) {
3117 wlock_acquire(rtld_bind_lock, &mlockstate);
3118 lockstate = &mlockstate;
3120 GDB_STATE(RT_ADD,NULL);
3122 old_obj_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
3124 if (name == NULL && fd == -1) {
3128 obj = load_object(name, fd, refobj, lo_flags);
3133 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
3134 objlist_push_tail(&list_global, obj);
3135 if (globallist_next(old_obj_tail) != NULL) {
3136 /* We loaded something new. */
3137 assert(globallist_next(old_obj_tail) == obj);
3138 result = load_needed_objects(obj,
3139 lo_flags & (RTLD_LO_DLOPEN | RTLD_LO_EARLY));
3143 result = rtld_verify_versions(&obj->dagmembers);
3144 if (result != -1 && ld_tracing)
3146 if (result == -1 || relocate_object_dag(obj,
3147 (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld,
3148 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3150 dlopen_cleanup(obj);
3152 } else if (lo_flags & RTLD_LO_EARLY) {
3154 * Do not call the init functions for early loaded
3155 * filtees. The image is still not initialized enough
3158 * Our object is found by the global object list and
3159 * will be ordered among all init calls done right
3160 * before transferring control to main.
3163 /* Make list of init functions to call. */
3164 initlist_add_objects(obj, obj, &initlist);
3167 * Process all no_delete or global objects here, given
3168 * them own DAGs to prevent their dependencies from being
3169 * unloaded. This has to be done after we have loaded all
3170 * of the dependencies, so that we do not miss any.
3176 * Bump the reference counts for objects on this DAG. If
3177 * this is the first dlopen() call for the object that was
3178 * already loaded as a dependency, initialize the dag
3184 if ((lo_flags & RTLD_LO_TRACE) != 0)
3187 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
3188 obj->z_nodelete) && !obj->ref_nodel) {
3189 dbg("obj %s nodelete", obj->path);
3191 obj->z_nodelete = obj->ref_nodel = true;
3195 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
3197 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
3199 if (!(lo_flags & RTLD_LO_EARLY)) {
3200 map_stacks_exec(lockstate);
3203 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
3204 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3206 objlist_clear(&initlist);
3207 dlopen_cleanup(obj);
3208 if (lockstate == &mlockstate)
3209 lock_release(rtld_bind_lock, lockstate);
3213 if (!(lo_flags & RTLD_LO_EARLY)) {
3214 /* Call the init functions. */
3215 objlist_call_init(&initlist, lockstate);
3217 objlist_clear(&initlist);
3218 if (lockstate == &mlockstate)
3219 lock_release(rtld_bind_lock, lockstate);
3222 trace_loaded_objects(obj);
3223 if (lockstate == &mlockstate)
3224 lock_release(rtld_bind_lock, lockstate);
3229 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
3233 const Obj_Entry *obj, *defobj;
3236 RtldLockState lockstate;
3243 symlook_init(&req, name);
3245 req.flags = flags | SYMLOOK_IN_PLT;
3246 req.lockstate = &lockstate;
3248 LD_UTRACE(UTRACE_DLSYM_START, handle, NULL, 0, 0, name);
3249 rlock_acquire(rtld_bind_lock, &lockstate);
3250 if (sigsetjmp(lockstate.env, 0) != 0)
3251 lock_upgrade(rtld_bind_lock, &lockstate);
3252 if (handle == NULL || handle == RTLD_NEXT ||
3253 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
3255 if ((obj = obj_from_addr(retaddr)) == NULL) {
3256 _rtld_error("Cannot determine caller's shared object");
3257 lock_release(rtld_bind_lock, &lockstate);
3258 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3261 if (handle == NULL) { /* Just the caller's shared object. */
3262 res = symlook_obj(&req, obj);
3265 defobj = req.defobj_out;
3267 } else if (handle == RTLD_NEXT || /* Objects after caller's */
3268 handle == RTLD_SELF) { /* ... caller included */
3269 if (handle == RTLD_NEXT)
3270 obj = globallist_next(obj);
3271 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
3274 res = symlook_obj(&req, obj);
3277 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) {
3279 defobj = req.defobj_out;
3280 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3286 * Search the dynamic linker itself, and possibly resolve the
3287 * symbol from there. This is how the application links to
3288 * dynamic linker services such as dlopen.
3290 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3291 res = symlook_obj(&req, &obj_rtld);
3294 defobj = req.defobj_out;
3298 assert(handle == RTLD_DEFAULT);
3299 res = symlook_default(&req, obj);
3301 defobj = req.defobj_out;
3306 if ((obj = dlcheck(handle)) == NULL) {
3307 lock_release(rtld_bind_lock, &lockstate);
3308 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3312 donelist_init(&donelist);
3313 if (obj->mainprog) {
3314 /* Handle obtained by dlopen(NULL, ...) implies global scope. */
3315 res = symlook_global(&req, &donelist);
3318 defobj = req.defobj_out;
3321 * Search the dynamic linker itself, and possibly resolve the
3322 * symbol from there. This is how the application links to
3323 * dynamic linker services such as dlopen.
3325 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3326 res = symlook_obj(&req, &obj_rtld);
3329 defobj = req.defobj_out;
3334 /* Search the whole DAG rooted at the given object. */
3335 res = symlook_list(&req, &obj->dagmembers, &donelist);
3338 defobj = req.defobj_out;
3344 lock_release(rtld_bind_lock, &lockstate);
3347 * The value required by the caller is derived from the value
3348 * of the symbol. this is simply the relocated value of the
3351 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
3352 sym = make_function_pointer(def, defobj);
3353 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
3354 sym = rtld_resolve_ifunc(defobj, def);
3355 else if (ELF_ST_TYPE(def->st_info) == STT_TLS) {
3356 ti.ti_module = defobj->tlsindex;
3357 ti.ti_offset = def->st_value;
3358 sym = __tls_get_addr(&ti);
3360 sym = defobj->relocbase + def->st_value;
3361 LD_UTRACE(UTRACE_DLSYM_STOP, handle, sym, 0, 0, name);
3365 _rtld_error("Undefined symbol \"%s\"", name);
3366 lock_release(rtld_bind_lock, &lockstate);
3367 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3372 dlsym(void *handle, const char *name)
3374 return do_dlsym(handle, name, __builtin_return_address(0), NULL,
3379 dlfunc(void *handle, const char *name)
3386 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
3392 dlvsym(void *handle, const char *name, const char *version)
3396 ventry.name = version;
3398 ventry.hash = elf_hash(version);
3400 return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
3405 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
3407 const Obj_Entry *obj;
3408 RtldLockState lockstate;
3410 rlock_acquire(rtld_bind_lock, &lockstate);
3411 obj = obj_from_addr(addr);
3413 _rtld_error("No shared object contains address");
3414 lock_release(rtld_bind_lock, &lockstate);
3417 rtld_fill_dl_phdr_info(obj, phdr_info);
3418 lock_release(rtld_bind_lock, &lockstate);
3423 dladdr(const void *addr, Dl_info *info)
3425 const Obj_Entry *obj;
3428 unsigned long symoffset;
3429 RtldLockState lockstate;
3431 rlock_acquire(rtld_bind_lock, &lockstate);
3432 obj = obj_from_addr(addr);
3434 _rtld_error("No shared object contains address");
3435 lock_release(rtld_bind_lock, &lockstate);
3438 info->dli_fname = obj->path;
3439 info->dli_fbase = obj->mapbase;
3440 info->dli_saddr = (void *)0;
3441 info->dli_sname = NULL;
3444 * Walk the symbol list looking for the symbol whose address is
3445 * closest to the address sent in.
3447 for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) {
3448 def = obj->symtab + symoffset;
3451 * For skip the symbol if st_shndx is either SHN_UNDEF or
3454 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
3458 * If the symbol is greater than the specified address, or if it
3459 * is further away from addr than the current nearest symbol,
3462 symbol_addr = obj->relocbase + def->st_value;
3463 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
3466 /* Update our idea of the nearest symbol. */
3467 info->dli_sname = obj->strtab + def->st_name;
3468 info->dli_saddr = symbol_addr;
3471 if (info->dli_saddr == addr)
3474 lock_release(rtld_bind_lock, &lockstate);
3479 dlinfo(void *handle, int request, void *p)
3481 const Obj_Entry *obj;
3482 RtldLockState lockstate;
3485 rlock_acquire(rtld_bind_lock, &lockstate);
3487 if (handle == NULL || handle == RTLD_SELF) {
3490 retaddr = __builtin_return_address(0); /* __GNUC__ only */
3491 if ((obj = obj_from_addr(retaddr)) == NULL)
3492 _rtld_error("Cannot determine caller's shared object");
3494 obj = dlcheck(handle);
3497 lock_release(rtld_bind_lock, &lockstate);
3503 case RTLD_DI_LINKMAP:
3504 *((struct link_map const **)p) = &obj->linkmap;
3506 case RTLD_DI_ORIGIN:
3507 error = rtld_dirname(obj->path, p);
3510 case RTLD_DI_SERINFOSIZE:
3511 case RTLD_DI_SERINFO:
3512 error = do_search_info(obj, request, (struct dl_serinfo *)p);
3516 _rtld_error("Invalid request %d passed to dlinfo()", request);
3520 lock_release(rtld_bind_lock, &lockstate);
3526 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
3529 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
3530 phdr_info->dlpi_name = obj->path;
3531 phdr_info->dlpi_phdr = obj->phdr;
3532 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
3533 phdr_info->dlpi_tls_modid = obj->tlsindex;
3534 phdr_info->dlpi_tls_data = obj->tlsinit;
3535 phdr_info->dlpi_adds = obj_loads;
3536 phdr_info->dlpi_subs = obj_loads - obj_count;
3540 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
3542 struct dl_phdr_info phdr_info;
3543 Obj_Entry *obj, marker;
3544 RtldLockState bind_lockstate, phdr_lockstate;
3547 bzero(&marker, sizeof(marker));
3548 marker.marker = true;
3551 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
3552 rlock_acquire(rtld_bind_lock, &bind_lockstate);
3553 for (obj = globallist_curr(TAILQ_FIRST(&obj_list)); obj != NULL;) {
3554 TAILQ_INSERT_AFTER(&obj_list, obj, &marker, next);
3555 rtld_fill_dl_phdr_info(obj, &phdr_info);
3556 lock_release(rtld_bind_lock, &bind_lockstate);
3558 error = callback(&phdr_info, sizeof phdr_info, param);
3560 rlock_acquire(rtld_bind_lock, &bind_lockstate);
3561 obj = globallist_next(&marker);
3562 TAILQ_REMOVE(&obj_list, &marker, next);
3564 lock_release(rtld_bind_lock, &bind_lockstate);
3565 lock_release(rtld_phdr_lock, &phdr_lockstate);
3571 rtld_fill_dl_phdr_info(&obj_rtld, &phdr_info);
3572 lock_release(rtld_bind_lock, &bind_lockstate);
3573 error = callback(&phdr_info, sizeof(phdr_info), param);
3575 lock_release(rtld_phdr_lock, &phdr_lockstate);
3580 fill_search_info(const char *dir, size_t dirlen, void *param)
3582 struct fill_search_info_args *arg;
3586 if (arg->request == RTLD_DI_SERINFOSIZE) {
3587 arg->serinfo->dls_cnt ++;
3588 arg->serinfo->dls_size += sizeof(struct dl_serpath) + dirlen + 1;
3590 struct dl_serpath *s_entry;
3592 s_entry = arg->serpath;
3593 s_entry->dls_name = arg->strspace;
3594 s_entry->dls_flags = arg->flags;
3596 strncpy(arg->strspace, dir, dirlen);
3597 arg->strspace[dirlen] = '\0';
3599 arg->strspace += dirlen + 1;
3607 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
3609 struct dl_serinfo _info;
3610 struct fill_search_info_args args;
3612 args.request = RTLD_DI_SERINFOSIZE;
3613 args.serinfo = &_info;
3615 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
3618 path_enumerate(obj->rpath, fill_search_info, &args);
3619 path_enumerate(ld_library_path, fill_search_info, &args);
3620 path_enumerate(obj->runpath, fill_search_info, &args);
3621 path_enumerate(gethints(obj->z_nodeflib), fill_search_info, &args);
3622 if (!obj->z_nodeflib)
3623 path_enumerate(ld_standard_library_path, fill_search_info, &args);
3626 if (request == RTLD_DI_SERINFOSIZE) {
3627 info->dls_size = _info.dls_size;
3628 info->dls_cnt = _info.dls_cnt;
3632 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
3633 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
3637 args.request = RTLD_DI_SERINFO;
3638 args.serinfo = info;
3639 args.serpath = &info->dls_serpath[0];
3640 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
3642 args.flags = LA_SER_RUNPATH;
3643 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
3646 args.flags = LA_SER_LIBPATH;
3647 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
3650 args.flags = LA_SER_RUNPATH;
3651 if (path_enumerate(obj->runpath, fill_search_info, &args) != NULL)
3654 args.flags = LA_SER_CONFIG;
3655 if (path_enumerate(gethints(obj->z_nodeflib), fill_search_info, &args)
3659 args.flags = LA_SER_DEFAULT;
3660 if (!obj->z_nodeflib &&
3661 path_enumerate(ld_standard_library_path, fill_search_info, &args) != NULL)
3667 rtld_dirname(const char *path, char *bname)
3671 /* Empty or NULL string gets treated as "." */
3672 if (path == NULL || *path == '\0') {
3678 /* Strip trailing slashes */
3679 endp = path + strlen(path) - 1;
3680 while (endp > path && *endp == '/')
3683 /* Find the start of the dir */
3684 while (endp > path && *endp != '/')
3687 /* Either the dir is "/" or there are no slashes */
3689 bname[0] = *endp == '/' ? '/' : '.';
3695 } while (endp > path && *endp == '/');
3698 if (endp - path + 2 > PATH_MAX)
3700 _rtld_error("Filename is too long: %s", path);
3704 strncpy(bname, path, endp - path + 1);
3705 bname[endp - path + 1] = '\0';
3710 rtld_dirname_abs(const char *path, char *base)
3714 if (realpath(path, base) == NULL)
3716 dbg("%s -> %s", path, base);
3717 last = strrchr(base, '/');
3726 linkmap_add(Obj_Entry *obj)
3728 struct link_map *l = &obj->linkmap;
3729 struct link_map *prev;
3731 obj->linkmap.l_name = obj->path;
3732 obj->linkmap.l_addr = obj->mapbase;
3733 obj->linkmap.l_ld = obj->dynamic;
3735 /* GDB needs load offset on MIPS to use the symbols */
3736 obj->linkmap.l_offs = obj->relocbase;
3739 if (r_debug.r_map == NULL) {
3745 * Scan to the end of the list, but not past the entry for the
3746 * dynamic linker, which we want to keep at the very end.
3748 for (prev = r_debug.r_map;
3749 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
3750 prev = prev->l_next)
3753 /* Link in the new entry. */
3755 l->l_next = prev->l_next;
3756 if (l->l_next != NULL)
3757 l->l_next->l_prev = l;
3762 linkmap_delete(Obj_Entry *obj)
3764 struct link_map *l = &obj->linkmap;
3766 if (l->l_prev == NULL) {
3767 if ((r_debug.r_map = l->l_next) != NULL)
3768 l->l_next->l_prev = NULL;
3772 if ((l->l_prev->l_next = l->l_next) != NULL)
3773 l->l_next->l_prev = l->l_prev;
3777 * Function for the debugger to set a breakpoint on to gain control.
3779 * The two parameters allow the debugger to easily find and determine
3780 * what the runtime loader is doing and to whom it is doing it.
3782 * When the loadhook trap is hit (r_debug_state, set at program
3783 * initialization), the arguments can be found on the stack:
3785 * +8 struct link_map *m
3786 * +4 struct r_debug *rd
3790 r_debug_state(struct r_debug* rd, struct link_map *m)
3793 * The following is a hack to force the compiler to emit calls to
3794 * this function, even when optimizing. If the function is empty,
3795 * the compiler is not obliged to emit any code for calls to it,
3796 * even when marked __noinline. However, gdb depends on those
3799 __compiler_membar();
3803 * A function called after init routines have completed. This can be used to
3804 * break before a program's entry routine is called, and can be used when
3805 * main is not available in the symbol table.
3808 _r_debug_postinit(struct link_map *m)
3811 /* See r_debug_state(). */
3812 __compiler_membar();
3816 * Get address of the pointer variable in the main program.
3817 * Prefer non-weak symbol over the weak one.
3819 static const void **
3820 get_program_var_addr(const char *name, RtldLockState *lockstate)
3825 symlook_init(&req, name);
3826 req.lockstate = lockstate;
3827 donelist_init(&donelist);
3828 if (symlook_global(&req, &donelist) != 0)
3830 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
3831 return ((const void **)make_function_pointer(req.sym_out,
3833 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
3834 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
3836 return ((const void **)(req.defobj_out->relocbase +
3837 req.sym_out->st_value));
3841 * Set a pointer variable in the main program to the given value. This
3842 * is used to set key variables such as "environ" before any of the
3843 * init functions are called.
3846 set_program_var(const char *name, const void *value)
3850 if ((addr = get_program_var_addr(name, NULL)) != NULL) {
3851 dbg("\"%s\": *%p <-- %p", name, addr, value);
3857 * Search the global objects, including dependencies and main object,
3858 * for the given symbol.
3861 symlook_global(SymLook *req, DoneList *donelist)
3864 const Objlist_Entry *elm;
3867 symlook_init_from_req(&req1, req);
3869 /* Search all objects loaded at program start up. */
3870 if (req->defobj_out == NULL ||
3871 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3872 res = symlook_list(&req1, &list_main, donelist);
3873 if (res == 0 && (req->defobj_out == NULL ||
3874 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3875 req->sym_out = req1.sym_out;
3876 req->defobj_out = req1.defobj_out;
3877 assert(req->defobj_out != NULL);
3881 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
3882 STAILQ_FOREACH(elm, &list_global, link) {
3883 if (req->defobj_out != NULL &&
3884 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3886 res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
3887 if (res == 0 && (req->defobj_out == NULL ||
3888 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3889 req->sym_out = req1.sym_out;
3890 req->defobj_out = req1.defobj_out;
3891 assert(req->defobj_out != NULL);
3895 return (req->sym_out != NULL ? 0 : ESRCH);
3899 * Given a symbol name in a referencing object, find the corresponding
3900 * definition of the symbol. Returns a pointer to the symbol, or NULL if
3901 * no definition was found. Returns a pointer to the Obj_Entry of the
3902 * defining object via the reference parameter DEFOBJ_OUT.
3905 symlook_default(SymLook *req, const Obj_Entry *refobj)
3908 const Objlist_Entry *elm;
3912 donelist_init(&donelist);
3913 symlook_init_from_req(&req1, req);
3915 /* Look first in the referencing object if linked symbolically. */
3916 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
3917 res = symlook_obj(&req1, refobj);
3919 req->sym_out = req1.sym_out;
3920 req->defobj_out = req1.defobj_out;
3921 assert(req->defobj_out != NULL);
3925 symlook_global(req, &donelist);
3927 /* Search all dlopened DAGs containing the referencing object. */
3928 STAILQ_FOREACH(elm, &refobj->dldags, link) {
3929 if (req->sym_out != NULL &&
3930 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3932 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
3933 if (res == 0 && (req->sym_out == NULL ||
3934 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3935 req->sym_out = req1.sym_out;
3936 req->defobj_out = req1.defobj_out;
3937 assert(req->defobj_out != NULL);
3942 * Search the dynamic linker itself, and possibly resolve the
3943 * symbol from there. This is how the application links to
3944 * dynamic linker services such as dlopen.
3946 if (req->sym_out == NULL ||
3947 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3948 res = symlook_obj(&req1, &obj_rtld);
3950 req->sym_out = req1.sym_out;
3951 req->defobj_out = req1.defobj_out;
3952 assert(req->defobj_out != NULL);
3956 return (req->sym_out != NULL ? 0 : ESRCH);
3960 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
3963 const Obj_Entry *defobj;
3964 const Objlist_Entry *elm;
3970 STAILQ_FOREACH(elm, objlist, link) {
3971 if (donelist_check(dlp, elm->obj))
3973 symlook_init_from_req(&req1, req);
3974 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
3975 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3977 defobj = req1.defobj_out;
3978 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3985 req->defobj_out = defobj;
3992 * Search the chain of DAGS cointed to by the given Needed_Entry
3993 * for a symbol of the given name. Each DAG is scanned completely
3994 * before advancing to the next one. Returns a pointer to the symbol,
3995 * or NULL if no definition was found.
3998 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
4001 const Needed_Entry *n;
4002 const Obj_Entry *defobj;
4008 symlook_init_from_req(&req1, req);
4009 for (n = needed; n != NULL; n = n->next) {
4010 if (n->obj == NULL ||
4011 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
4013 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
4015 defobj = req1.defobj_out;
4016 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
4022 req->defobj_out = defobj;
4029 * Search the symbol table of a single shared object for a symbol of
4030 * the given name and version, if requested. Returns a pointer to the
4031 * symbol, or NULL if no definition was found. If the object is
4032 * filter, return filtered symbol from filtee.
4034 * The symbol's hash value is passed in for efficiency reasons; that
4035 * eliminates many recomputations of the hash value.
4038 symlook_obj(SymLook *req, const Obj_Entry *obj)
4042 int flags, res, mres;
4045 * If there is at least one valid hash at this point, we prefer to
4046 * use the faster GNU version if available.
4048 if (obj->valid_hash_gnu)
4049 mres = symlook_obj1_gnu(req, obj);
4050 else if (obj->valid_hash_sysv)
4051 mres = symlook_obj1_sysv(req, obj);
4056 if (obj->needed_filtees != NULL) {
4057 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4058 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4059 donelist_init(&donelist);
4060 symlook_init_from_req(&req1, req);
4061 res = symlook_needed(&req1, obj->needed_filtees, &donelist);
4063 req->sym_out = req1.sym_out;
4064 req->defobj_out = req1.defobj_out;
4068 if (obj->needed_aux_filtees != NULL) {
4069 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4070 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4071 donelist_init(&donelist);
4072 symlook_init_from_req(&req1, req);
4073 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
4075 req->sym_out = req1.sym_out;
4076 req->defobj_out = req1.defobj_out;
4084 /* Symbol match routine common to both hash functions */
4086 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result,
4087 const unsigned long symnum)
4090 const Elf_Sym *symp;
4093 symp = obj->symtab + symnum;
4094 strp = obj->strtab + symp->st_name;
4096 switch (ELF_ST_TYPE(symp->st_info)) {
4102 if (symp->st_value == 0)
4106 if (symp->st_shndx != SHN_UNDEF)
4109 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
4110 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
4117 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
4120 if (req->ventry == NULL) {
4121 if (obj->versyms != NULL) {
4122 verndx = VER_NDX(obj->versyms[symnum]);
4123 if (verndx > obj->vernum) {
4125 "%s: symbol %s references wrong version %d",
4126 obj->path, obj->strtab + symnum, verndx);
4130 * If we are not called from dlsym (i.e. this
4131 * is a normal relocation from unversioned
4132 * binary), accept the symbol immediately if
4133 * it happens to have first version after this
4134 * shared object became versioned. Otherwise,
4135 * if symbol is versioned and not hidden,
4136 * remember it. If it is the only symbol with
4137 * this name exported by the shared object, it
4138 * will be returned as a match by the calling
4139 * function. If symbol is global (verndx < 2)
4140 * accept it unconditionally.
4142 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
4143 verndx == VER_NDX_GIVEN) {
4144 result->sym_out = symp;
4147 else if (verndx >= VER_NDX_GIVEN) {
4148 if ((obj->versyms[symnum] & VER_NDX_HIDDEN)
4150 if (result->vsymp == NULL)
4151 result->vsymp = symp;
4157 result->sym_out = symp;
4160 if (obj->versyms == NULL) {
4161 if (object_match_name(obj, req->ventry->name)) {
4162 _rtld_error("%s: object %s should provide version %s "
4163 "for symbol %s", obj_rtld.path, obj->path,
4164 req->ventry->name, obj->strtab + symnum);
4168 verndx = VER_NDX(obj->versyms[symnum]);
4169 if (verndx > obj->vernum) {
4170 _rtld_error("%s: symbol %s references wrong version %d",
4171 obj->path, obj->strtab + symnum, verndx);
4174 if (obj->vertab[verndx].hash != req->ventry->hash ||
4175 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
4177 * Version does not match. Look if this is a
4178 * global symbol and if it is not hidden. If
4179 * global symbol (verndx < 2) is available,
4180 * use it. Do not return symbol if we are
4181 * called by dlvsym, because dlvsym looks for
4182 * a specific version and default one is not
4183 * what dlvsym wants.
4185 if ((req->flags & SYMLOOK_DLSYM) ||
4186 (verndx >= VER_NDX_GIVEN) ||
4187 (obj->versyms[symnum] & VER_NDX_HIDDEN))
4191 result->sym_out = symp;
4196 * Search for symbol using SysV hash function.
4197 * obj->buckets is known not to be NULL at this point; the test for this was
4198 * performed with the obj->valid_hash_sysv assignment.
4201 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj)
4203 unsigned long symnum;
4204 Sym_Match_Result matchres;
4206 matchres.sym_out = NULL;
4207 matchres.vsymp = NULL;
4208 matchres.vcount = 0;
4210 for (symnum = obj->buckets[req->hash % obj->nbuckets];
4211 symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
4212 if (symnum >= obj->nchains)
4213 return (ESRCH); /* Bad object */
4215 if (matched_symbol(req, obj, &matchres, symnum)) {
4216 req->sym_out = matchres.sym_out;
4217 req->defobj_out = obj;
4221 if (matchres.vcount == 1) {
4222 req->sym_out = matchres.vsymp;
4223 req->defobj_out = obj;
4229 /* Search for symbol using GNU hash function */
4231 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj)
4233 Elf_Addr bloom_word;
4234 const Elf32_Word *hashval;
4236 Sym_Match_Result matchres;
4237 unsigned int h1, h2;
4238 unsigned long symnum;
4240 matchres.sym_out = NULL;
4241 matchres.vsymp = NULL;
4242 matchres.vcount = 0;
4244 /* Pick right bitmask word from Bloom filter array */
4245 bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) &
4246 obj->maskwords_bm_gnu];
4248 /* Calculate modulus word size of gnu hash and its derivative */
4249 h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1);
4250 h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1));
4252 /* Filter out the "definitely not in set" queries */
4253 if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0)
4256 /* Locate hash chain and corresponding value element*/
4257 bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu];
4260 hashval = &obj->chain_zero_gnu[bucket];
4262 if (((*hashval ^ req->hash_gnu) >> 1) == 0) {
4263 symnum = hashval - obj->chain_zero_gnu;
4264 if (matched_symbol(req, obj, &matchres, symnum)) {
4265 req->sym_out = matchres.sym_out;
4266 req->defobj_out = obj;
4270 } while ((*hashval++ & 1) == 0);
4271 if (matchres.vcount == 1) {
4272 req->sym_out = matchres.vsymp;
4273 req->defobj_out = obj;
4280 trace_loaded_objects(Obj_Entry *obj)
4282 char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
4285 if ((main_local = getenv(_LD("TRACE_LOADED_OBJECTS_PROGNAME"))) == NULL)
4288 if ((fmt1 = getenv(_LD("TRACE_LOADED_OBJECTS_FMT1"))) == NULL)
4289 fmt1 = "\t%o => %p (%x)\n";
4291 if ((fmt2 = getenv(_LD("TRACE_LOADED_OBJECTS_FMT2"))) == NULL)
4292 fmt2 = "\t%o (%x)\n";
4294 list_containers = getenv(_LD("TRACE_LOADED_OBJECTS_ALL"));
4296 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
4297 Needed_Entry *needed;
4303 if (list_containers && obj->needed != NULL)
4304 rtld_printf("%s:\n", obj->path);
4305 for (needed = obj->needed; needed; needed = needed->next) {
4306 if (needed->obj != NULL) {
4307 if (needed->obj->traced && !list_containers)
4309 needed->obj->traced = true;
4310 path = needed->obj->path;
4314 name = (char *)obj->strtab + needed->name;
4315 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
4317 fmt = is_lib ? fmt1 : fmt2;
4318 while ((c = *fmt++) != '\0') {
4344 rtld_putstr(main_local);
4347 rtld_putstr(obj_main->path);
4354 rtld_printf("%d", sodp->sod_major);
4357 rtld_printf("%d", sodp->sod_minor);
4364 rtld_printf("%p", needed->obj ? needed->obj->mapbase :
4377 * Unload a dlopened object and its dependencies from memory and from
4378 * our data structures. It is assumed that the DAG rooted in the
4379 * object has already been unreferenced, and that the object has a
4380 * reference count of 0.
4383 unload_object(Obj_Entry *root)
4385 Obj_Entry *obj, *obj1;
4387 assert(root->refcount == 0);
4390 * Pass over the DAG removing unreferenced objects from
4391 * appropriate lists.
4393 unlink_object(root);
4395 /* Unmap all objects that are no longer referenced. */
4396 TAILQ_FOREACH_SAFE(obj, &obj_list, next, obj1) {
4397 if (obj->marker || obj->refcount != 0)
4399 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase,
4400 obj->mapsize, 0, obj->path);
4401 dbg("unloading \"%s\"", obj->path);
4402 unload_filtees(root);
4403 munmap(obj->mapbase, obj->mapsize);
4404 linkmap_delete(obj);
4405 TAILQ_REMOVE(&obj_list, obj, next);
4412 unlink_object(Obj_Entry *root)
4416 if (root->refcount == 0) {
4417 /* Remove the object from the RTLD_GLOBAL list. */
4418 objlist_remove(&list_global, root);
4420 /* Remove the object from all objects' DAG lists. */
4421 STAILQ_FOREACH(elm, &root->dagmembers, link) {
4422 objlist_remove(&elm->obj->dldags, root);
4423 if (elm->obj != root)
4424 unlink_object(elm->obj);
4430 ref_dag(Obj_Entry *root)
4434 assert(root->dag_inited);
4435 STAILQ_FOREACH(elm, &root->dagmembers, link)
4436 elm->obj->refcount++;
4440 unref_dag(Obj_Entry *root)
4444 assert(root->dag_inited);
4445 STAILQ_FOREACH(elm, &root->dagmembers, link)
4446 elm->obj->refcount--;
4450 * Common code for MD __tls_get_addr().
4452 static void *tls_get_addr_slow(Elf_Addr **, int, size_t) __noinline;
4454 tls_get_addr_slow(Elf_Addr **dtvp, int index, size_t offset)
4456 Elf_Addr *newdtv, *dtv;
4457 RtldLockState lockstate;
4461 /* Check dtv generation in case new modules have arrived */
4462 if (dtv[0] != tls_dtv_generation) {
4463 wlock_acquire(rtld_bind_lock, &lockstate);
4464 newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4466 if (to_copy > tls_max_index)
4467 to_copy = tls_max_index;
4468 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
4469 newdtv[0] = tls_dtv_generation;
4470 newdtv[1] = tls_max_index;
4472 lock_release(rtld_bind_lock, &lockstate);
4473 dtv = *dtvp = newdtv;
4476 /* Dynamically allocate module TLS if necessary */
4477 if (dtv[index + 1] == 0) {
4478 /* Signal safe, wlock will block out signals. */
4479 wlock_acquire(rtld_bind_lock, &lockstate);
4480 if (!dtv[index + 1])
4481 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
4482 lock_release(rtld_bind_lock, &lockstate);
4484 return ((void *)(dtv[index + 1] + offset));
4488 tls_get_addr_common(Elf_Addr **dtvp, int index, size_t offset)
4493 /* Check dtv generation in case new modules have arrived */
4494 if (__predict_true(dtv[0] == tls_dtv_generation &&
4495 dtv[index + 1] != 0))
4496 return ((void *)(dtv[index + 1] + offset));
4497 return (tls_get_addr_slow(dtvp, index, offset));
4500 #if defined(__aarch64__) || defined(__arm__) || defined(__mips__) || \
4501 defined(__powerpc__) || defined(__riscv__)
4504 * Allocate Static TLS using the Variant I method.
4507 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
4516 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
4519 assert(tcbsize >= TLS_TCB_SIZE);
4520 tcb = xcalloc(1, tls_static_space - TLS_TCB_SIZE + tcbsize);
4521 tls = (Elf_Addr **)(tcb + tcbsize - TLS_TCB_SIZE);
4523 if (oldtcb != NULL) {
4524 memcpy(tls, oldtcb, tls_static_space);
4527 /* Adjust the DTV. */
4529 for (i = 0; i < dtv[1]; i++) {
4530 if (dtv[i+2] >= (Elf_Addr)oldtcb &&
4531 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
4532 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tls;
4536 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4538 dtv[0] = tls_dtv_generation;
4539 dtv[1] = tls_max_index;
4541 for (obj = globallist_curr(objs); obj != NULL;
4542 obj = globallist_next(obj)) {
4543 if (obj->tlsoffset > 0) {
4544 addr = (Elf_Addr)tls + obj->tlsoffset;
4545 if (obj->tlsinitsize > 0)
4546 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4547 if (obj->tlssize > obj->tlsinitsize)
4548 memset((void*) (addr + obj->tlsinitsize), 0,
4549 obj->tlssize - obj->tlsinitsize);
4550 dtv[obj->tlsindex + 1] = addr;
4559 free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
4562 Elf_Addr tlsstart, tlsend;
4565 assert(tcbsize >= TLS_TCB_SIZE);
4567 tlsstart = (Elf_Addr)tcb + tcbsize - TLS_TCB_SIZE;
4568 tlsend = tlsstart + tls_static_space;
4570 dtv = *(Elf_Addr **)tlsstart;
4572 for (i = 0; i < dtvsize; i++) {
4573 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
4574 free((void*)dtv[i+2]);
4583 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__)
4586 * Allocate Static TLS using the Variant II method.
4589 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
4592 size_t size, ralign;
4594 Elf_Addr *dtv, *olddtv;
4595 Elf_Addr segbase, oldsegbase, addr;
4599 if (tls_static_max_align > ralign)
4600 ralign = tls_static_max_align;
4601 size = round(tls_static_space, ralign) + round(tcbsize, ralign);
4603 assert(tcbsize >= 2*sizeof(Elf_Addr));
4604 tls = malloc_aligned(size, ralign);
4605 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4607 segbase = (Elf_Addr)(tls + round(tls_static_space, ralign));
4608 ((Elf_Addr*)segbase)[0] = segbase;
4609 ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
4611 dtv[0] = tls_dtv_generation;
4612 dtv[1] = tls_max_index;
4616 * Copy the static TLS block over whole.
4618 oldsegbase = (Elf_Addr) oldtls;
4619 memcpy((void *)(segbase - tls_static_space),
4620 (const void *)(oldsegbase - tls_static_space),
4624 * If any dynamic TLS blocks have been created tls_get_addr(),
4627 olddtv = ((Elf_Addr**)oldsegbase)[1];
4628 for (i = 0; i < olddtv[1]; i++) {
4629 if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
4630 dtv[i+2] = olddtv[i+2];
4636 * We assume that this block was the one we created with
4637 * allocate_initial_tls().
4639 free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
4641 for (obj = objs; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
4642 if (obj->marker || obj->tlsoffset == 0)
4644 addr = segbase - obj->tlsoffset;
4645 memset((void*) (addr + obj->tlsinitsize),
4646 0, obj->tlssize - obj->tlsinitsize);
4648 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4649 dtv[obj->tlsindex + 1] = addr;
4653 return (void*) segbase;
4657 free_tls(void *tls, size_t tcbsize, size_t tcbalign)
4660 size_t size, ralign;
4662 Elf_Addr tlsstart, tlsend;
4665 * Figure out the size of the initial TLS block so that we can
4666 * find stuff which ___tls_get_addr() allocated dynamically.
4669 if (tls_static_max_align > ralign)
4670 ralign = tls_static_max_align;
4671 size = round(tls_static_space, ralign);
4673 dtv = ((Elf_Addr**)tls)[1];
4675 tlsend = (Elf_Addr) tls;
4676 tlsstart = tlsend - size;
4677 for (i = 0; i < dtvsize; i++) {
4678 if (dtv[i + 2] != 0 && (dtv[i + 2] < tlsstart || dtv[i + 2] > tlsend)) {
4679 free_aligned((void *)dtv[i + 2]);
4683 free_aligned((void *)tlsstart);
4690 * Allocate TLS block for module with given index.
4693 allocate_module_tls(int index)
4698 TAILQ_FOREACH(obj, &obj_list, next) {
4701 if (obj->tlsindex == index)
4705 _rtld_error("Can't find module with TLS index %d", index);
4709 p = malloc_aligned(obj->tlssize, obj->tlsalign);
4710 memcpy(p, obj->tlsinit, obj->tlsinitsize);
4711 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
4717 allocate_tls_offset(Obj_Entry *obj)
4724 if (obj->tlssize == 0) {
4725 obj->tls_done = true;
4729 if (tls_last_offset == 0)
4730 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
4732 off = calculate_tls_offset(tls_last_offset, tls_last_size,
4733 obj->tlssize, obj->tlsalign);
4736 * If we have already fixed the size of the static TLS block, we
4737 * must stay within that size. When allocating the static TLS, we
4738 * leave a small amount of space spare to be used for dynamically
4739 * loading modules which use static TLS.
4741 if (tls_static_space != 0) {
4742 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
4744 } else if (obj->tlsalign > tls_static_max_align) {
4745 tls_static_max_align = obj->tlsalign;
4748 tls_last_offset = obj->tlsoffset = off;
4749 tls_last_size = obj->tlssize;
4750 obj->tls_done = true;
4756 free_tls_offset(Obj_Entry *obj)
4760 * If we were the last thing to allocate out of the static TLS
4761 * block, we give our space back to the 'allocator'. This is a
4762 * simplistic workaround to allow libGL.so.1 to be loaded and
4763 * unloaded multiple times.
4765 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
4766 == calculate_tls_end(tls_last_offset, tls_last_size)) {
4767 tls_last_offset -= obj->tlssize;
4773 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
4776 RtldLockState lockstate;
4778 wlock_acquire(rtld_bind_lock, &lockstate);
4779 ret = allocate_tls(globallist_curr(TAILQ_FIRST(&obj_list)), oldtls,
4781 lock_release(rtld_bind_lock, &lockstate);
4786 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
4788 RtldLockState lockstate;
4790 wlock_acquire(rtld_bind_lock, &lockstate);
4791 free_tls(tcb, tcbsize, tcbalign);
4792 lock_release(rtld_bind_lock, &lockstate);
4796 object_add_name(Obj_Entry *obj, const char *name)
4802 entry = malloc(sizeof(Name_Entry) + len);
4804 if (entry != NULL) {
4805 strcpy(entry->name, name);
4806 STAILQ_INSERT_TAIL(&obj->names, entry, link);
4811 object_match_name(const Obj_Entry *obj, const char *name)
4815 STAILQ_FOREACH(entry, &obj->names, link) {
4816 if (strcmp(name, entry->name) == 0)
4823 locate_dependency(const Obj_Entry *obj, const char *name)
4825 const Objlist_Entry *entry;
4826 const Needed_Entry *needed;
4828 STAILQ_FOREACH(entry, &list_main, link) {
4829 if (object_match_name(entry->obj, name))
4833 for (needed = obj->needed; needed != NULL; needed = needed->next) {
4834 if (strcmp(obj->strtab + needed->name, name) == 0 ||
4835 (needed->obj != NULL && object_match_name(needed->obj, name))) {
4837 * If there is DT_NEEDED for the name we are looking for,
4838 * we are all set. Note that object might not be found if
4839 * dependency was not loaded yet, so the function can
4840 * return NULL here. This is expected and handled
4841 * properly by the caller.
4843 return (needed->obj);
4846 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
4852 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
4853 const Elf_Vernaux *vna)
4855 const Elf_Verdef *vd;
4856 const char *vername;
4858 vername = refobj->strtab + vna->vna_name;
4859 vd = depobj->verdef;
4861 _rtld_error("%s: version %s required by %s not defined",
4862 depobj->path, vername, refobj->path);
4866 if (vd->vd_version != VER_DEF_CURRENT) {
4867 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
4868 depobj->path, vd->vd_version);
4871 if (vna->vna_hash == vd->vd_hash) {
4872 const Elf_Verdaux *aux = (const Elf_Verdaux *)
4873 ((char *)vd + vd->vd_aux);
4874 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
4877 if (vd->vd_next == 0)
4879 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4881 if (vna->vna_flags & VER_FLG_WEAK)
4883 _rtld_error("%s: version %s required by %s not found",
4884 depobj->path, vername, refobj->path);
4889 rtld_verify_object_versions(Obj_Entry *obj)
4891 const Elf_Verneed *vn;
4892 const Elf_Verdef *vd;
4893 const Elf_Verdaux *vda;
4894 const Elf_Vernaux *vna;
4895 const Obj_Entry *depobj;
4896 int maxvernum, vernum;
4898 if (obj->ver_checked)
4900 obj->ver_checked = true;
4904 * Walk over defined and required version records and figure out
4905 * max index used by any of them. Do very basic sanity checking
4909 while (vn != NULL) {
4910 if (vn->vn_version != VER_NEED_CURRENT) {
4911 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
4912 obj->path, vn->vn_version);
4915 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4917 vernum = VER_NEED_IDX(vna->vna_other);
4918 if (vernum > maxvernum)
4920 if (vna->vna_next == 0)
4922 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4924 if (vn->vn_next == 0)
4926 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4930 while (vd != NULL) {
4931 if (vd->vd_version != VER_DEF_CURRENT) {
4932 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
4933 obj->path, vd->vd_version);
4936 vernum = VER_DEF_IDX(vd->vd_ndx);
4937 if (vernum > maxvernum)
4939 if (vd->vd_next == 0)
4941 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4948 * Store version information in array indexable by version index.
4949 * Verify that object version requirements are satisfied along the
4952 obj->vernum = maxvernum + 1;
4953 obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry));
4956 while (vd != NULL) {
4957 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
4958 vernum = VER_DEF_IDX(vd->vd_ndx);
4959 assert(vernum <= maxvernum);
4960 vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
4961 obj->vertab[vernum].hash = vd->vd_hash;
4962 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
4963 obj->vertab[vernum].file = NULL;
4964 obj->vertab[vernum].flags = 0;
4966 if (vd->vd_next == 0)
4968 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4972 while (vn != NULL) {
4973 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
4976 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4978 if (check_object_provided_version(obj, depobj, vna))
4980 vernum = VER_NEED_IDX(vna->vna_other);
4981 assert(vernum <= maxvernum);
4982 obj->vertab[vernum].hash = vna->vna_hash;
4983 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
4984 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
4985 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
4986 VER_INFO_HIDDEN : 0;
4987 if (vna->vna_next == 0)
4989 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4991 if (vn->vn_next == 0)
4993 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4999 rtld_verify_versions(const Objlist *objlist)
5001 Objlist_Entry *entry;
5005 STAILQ_FOREACH(entry, objlist, link) {
5007 * Skip dummy objects or objects that have their version requirements
5010 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
5012 if (rtld_verify_object_versions(entry->obj) == -1) {
5014 if (ld_tracing == NULL)
5018 if (rc == 0 || ld_tracing != NULL)
5019 rc = rtld_verify_object_versions(&obj_rtld);
5024 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
5029 vernum = VER_NDX(obj->versyms[symnum]);
5030 if (vernum >= obj->vernum) {
5031 _rtld_error("%s: symbol %s has wrong verneed value %d",
5032 obj->path, obj->strtab + symnum, vernum);
5033 } else if (obj->vertab[vernum].hash != 0) {
5034 return &obj->vertab[vernum];
5041 _rtld_get_stack_prot(void)
5044 return (stack_prot);
5048 _rtld_is_dlopened(void *arg)
5051 RtldLockState lockstate;
5054 rlock_acquire(rtld_bind_lock, &lockstate);
5057 obj = obj_from_addr(arg);
5059 _rtld_error("No shared object contains address");
5060 lock_release(rtld_bind_lock, &lockstate);
5063 res = obj->dlopened ? 1 : 0;
5064 lock_release(rtld_bind_lock, &lockstate);
5069 map_stacks_exec(RtldLockState *lockstate)
5071 void (*thr_map_stacks_exec)(void);
5073 if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
5075 thr_map_stacks_exec = (void (*)(void))(uintptr_t)
5076 get_program_var_addr("__pthread_map_stacks_exec", lockstate);
5077 if (thr_map_stacks_exec != NULL) {
5078 stack_prot |= PROT_EXEC;
5079 thr_map_stacks_exec();
5084 symlook_init(SymLook *dst, const char *name)
5087 bzero(dst, sizeof(*dst));
5089 dst->hash = elf_hash(name);
5090 dst->hash_gnu = gnu_hash(name);
5094 symlook_init_from_req(SymLook *dst, const SymLook *src)
5097 dst->name = src->name;
5098 dst->hash = src->hash;
5099 dst->hash_gnu = src->hash_gnu;
5100 dst->ventry = src->ventry;
5101 dst->flags = src->flags;
5102 dst->defobj_out = NULL;
5103 dst->sym_out = NULL;
5104 dst->lockstate = src->lockstate;
5109 * Parse a file descriptor number without pulling in more of libc (e.g. atoi).
5112 parse_libdir(const char *str)
5114 static const int RADIX = 10; /* XXXJA: possibly support hex? */
5121 for (c = *str; c != '\0'; c = *++str) {
5122 if (c < '0' || c > '9')
5129 /* Make sure we actually parsed something. */
5131 _rtld_error("failed to parse directory FD from '%s'", str);
5138 * Overrides for libc_pic-provided functions.
5142 __getosreldate(void)
5152 oid[1] = KERN_OSRELDATE;
5154 len = sizeof(osrel);
5155 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
5156 if (error == 0 && osrel > 0 && len == sizeof(osrel))
5168 void (*__cleanup)(void);
5169 int __isthreaded = 0;
5170 int _thread_autoinit_dummy_decl = 1;
5173 * No unresolved symbols for rtld.
5176 __pthread_cxa_finalize(struct dl_phdr_info *a)
5181 __stack_chk_fail(void)
5184 _rtld_error("stack overflow detected; terminated");
5187 __weak_reference(__stack_chk_fail, __stack_chk_fail_local);
5193 _rtld_error("buffer overflow detected; terminated");
5198 rtld_strerror(int errnum)
5201 if (errnum < 0 || errnum >= sys_nerr)
5202 return ("Unknown error");
5203 return (sys_errlist[errnum]);