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>
60 #include "rtld_printf.h"
64 #define PATH_RTLD "/libexec/ld-elf.so.1"
66 #define PATH_RTLD "/libexec/ld-elf32.so.1"
70 typedef void (*func_ptr_type)();
71 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg);
74 * Function declarations.
76 static const char *basename(const char *);
77 static void digest_dynamic1(Obj_Entry *, int, const Elf_Dyn **,
78 const Elf_Dyn **, const Elf_Dyn **);
79 static void digest_dynamic2(Obj_Entry *, const Elf_Dyn *, const Elf_Dyn *,
81 static void digest_dynamic(Obj_Entry *, int);
82 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
83 static Obj_Entry *dlcheck(void *);
84 static Obj_Entry *dlopen_object(const char *name, int fd, Obj_Entry *refobj,
85 int lo_flags, int mode, RtldLockState *lockstate);
86 static Obj_Entry *do_load_object(int, const char *, char *, struct stat *, int);
87 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
88 static bool donelist_check(DoneList *, const Obj_Entry *);
89 static void errmsg_restore(char *);
90 static char *errmsg_save(void);
91 static void *fill_search_info(const char *, size_t, void *);
92 static char *find_library(const char *, const Obj_Entry *, int *);
93 static const char *gethints(bool);
94 static void init_dag(Obj_Entry *);
95 static void init_pagesizes(Elf_Auxinfo **aux_info);
96 static void init_rtld(caddr_t, Elf_Auxinfo **);
97 static void initlist_add_neededs(Needed_Entry *, Objlist *);
98 static void initlist_add_objects(Obj_Entry *, Obj_Entry **, Objlist *);
99 static void linkmap_add(Obj_Entry *);
100 static void linkmap_delete(Obj_Entry *);
101 static void load_filtees(Obj_Entry *, int flags, RtldLockState *);
102 static void unload_filtees(Obj_Entry *);
103 static int load_needed_objects(Obj_Entry *, int);
104 static int load_preload_objects(void);
105 static Obj_Entry *load_object(const char *, int fd, const Obj_Entry *, int);
106 static void map_stacks_exec(RtldLockState *);
107 static Obj_Entry *obj_from_addr(const void *);
108 static void objlist_call_fini(Objlist *, Obj_Entry *, RtldLockState *);
109 static void objlist_call_init(Objlist *, RtldLockState *);
110 static void objlist_clear(Objlist *);
111 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
112 static void objlist_init(Objlist *);
113 static void objlist_push_head(Objlist *, Obj_Entry *);
114 static void objlist_push_tail(Objlist *, Obj_Entry *);
115 static void objlist_put_after(Objlist *, Obj_Entry *, Obj_Entry *);
116 static void objlist_remove(Objlist *, Obj_Entry *);
117 static int parse_libdir(const char *);
118 static void *path_enumerate(const char *, path_enum_proc, void *);
119 static int relocate_object_dag(Obj_Entry *root, bool bind_now,
120 Obj_Entry *rtldobj, int flags, RtldLockState *lockstate);
121 static int relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
122 int flags, RtldLockState *lockstate);
123 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, int,
125 static int resolve_objects_ifunc(Obj_Entry *first, bool bind_now,
126 int flags, RtldLockState *lockstate);
127 static int rtld_dirname(const char *, char *);
128 static int rtld_dirname_abs(const char *, char *);
129 static void *rtld_dlopen(const char *name, int fd, int mode);
130 static void rtld_exit(void);
131 static char *search_library_path(const char *, const char *);
132 static char *search_library_pathfds(const char *, const char *, int *);
133 static const void **get_program_var_addr(const char *, RtldLockState *);
134 static void set_program_var(const char *, const void *);
135 static int symlook_default(SymLook *, const Obj_Entry *refobj);
136 static int symlook_global(SymLook *, DoneList *);
137 static void symlook_init_from_req(SymLook *, const SymLook *);
138 static int symlook_list(SymLook *, const Objlist *, DoneList *);
139 static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *);
140 static int symlook_obj1_sysv(SymLook *, const Obj_Entry *);
141 static int symlook_obj1_gnu(SymLook *, const Obj_Entry *);
142 static void trace_loaded_objects(Obj_Entry *);
143 static void unlink_object(Obj_Entry *);
144 static void unload_object(Obj_Entry *);
145 static void unref_dag(Obj_Entry *);
146 static void ref_dag(Obj_Entry *);
147 static char *origin_subst_one(Obj_Entry *, char *, const char *,
149 static char *origin_subst(Obj_Entry *, char *);
150 static bool obj_resolve_origin(Obj_Entry *obj);
151 static void preinit_main(void);
152 static int rtld_verify_versions(const Objlist *);
153 static int rtld_verify_object_versions(Obj_Entry *);
154 static void object_add_name(Obj_Entry *, const char *);
155 static int object_match_name(const Obj_Entry *, const char *);
156 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
157 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
158 struct dl_phdr_info *phdr_info);
159 static uint32_t gnu_hash(const char *);
160 static bool matched_symbol(SymLook *, const Obj_Entry *, Sym_Match_Result *,
161 const unsigned long);
163 void r_debug_state(struct r_debug *, struct link_map *) __noinline __exported;
164 void _r_debug_postinit(struct link_map *) __noinline __exported;
166 int __sys_openat(int, const char *, int, ...);
171 static char *error_message; /* Message for dlerror(), or NULL */
172 struct r_debug r_debug __exported; /* for GDB; */
173 static bool libmap_disable; /* Disable libmap */
174 static bool ld_loadfltr; /* Immediate filters processing */
175 static char *libmap_override; /* Maps to use in addition to libmap.conf */
176 static bool trust; /* False for setuid and setgid programs */
177 static bool dangerous_ld_env; /* True if environment variables have been
178 used to affect the libraries loaded */
179 static char *ld_bind_now; /* Environment variable for immediate binding */
180 static char *ld_debug; /* Environment variable for debugging */
181 static char *ld_library_path; /* Environment variable for search path */
182 static char *ld_library_dirs; /* Environment variable for library descriptors */
183 static char *ld_preload; /* Environment variable for libraries to
185 static char *ld_elf_hints_path; /* Environment variable for alternative hints path */
186 static char *ld_tracing; /* Called from ldd to print libs */
187 static char *ld_utrace; /* Use utrace() to log events. */
188 static Obj_Entry *obj_list; /* Head of linked list of shared objects */
189 static Obj_Entry **obj_tail; /* Link field of last object in list */
190 static Obj_Entry *obj_main; /* The main program shared object */
191 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
192 static unsigned int obj_count; /* Number of objects in obj_list */
193 static unsigned int obj_loads; /* Number of objects in obj_list */
195 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
196 STAILQ_HEAD_INITIALIZER(list_global);
197 static Objlist list_main = /* Objects loaded at program startup */
198 STAILQ_HEAD_INITIALIZER(list_main);
199 static Objlist list_fini = /* Objects needing fini() calls */
200 STAILQ_HEAD_INITIALIZER(list_fini);
202 Elf_Sym sym_zero; /* For resolving undefined weak refs. */
204 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
206 extern Elf_Dyn _DYNAMIC;
207 #pragma weak _DYNAMIC
208 #ifndef RTLD_IS_DYNAMIC
209 #define RTLD_IS_DYNAMIC() (&_DYNAMIC != NULL)
212 int dlclose(void *) __exported;
213 char *dlerror(void) __exported;
214 void *dlopen(const char *, int) __exported;
215 void *fdlopen(int, int) __exported;
216 void *dlsym(void *, const char *) __exported;
217 dlfunc_t dlfunc(void *, const char *) __exported;
218 void *dlvsym(void *, const char *, const char *) __exported;
219 int dladdr(const void *, Dl_info *) __exported;
220 void dllockinit(void *, void *(*)(void *), void (*)(void *), void (*)(void *),
221 void (*)(void *), void (*)(void *), void (*)(void *)) __exported;
222 int dlinfo(void *, int , void *) __exported;
223 int dl_iterate_phdr(__dl_iterate_hdr_callback, void *) __exported;
224 int _rtld_addr_phdr(const void *, struct dl_phdr_info *) __exported;
225 int _rtld_get_stack_prot(void) __exported;
226 int _rtld_is_dlopened(void *) __exported;
227 void _rtld_error(const char *, ...) __exported;
229 int npagesizes, osreldate;
232 long __stack_chk_guard[8] = {0, 0, 0, 0, 0, 0, 0, 0};
234 static int stack_prot = PROT_READ | PROT_WRITE | RTLD_DEFAULT_STACK_EXEC;
235 static int max_stack_flags;
238 * Global declarations normally provided by crt1. The dynamic linker is
239 * not built with crt1, so we have to provide them ourselves.
245 * Used to pass argc, argv to init functions.
251 * Globals to control TLS allocation.
253 size_t tls_last_offset; /* Static TLS offset of last module */
254 size_t tls_last_size; /* Static TLS size of last module */
255 size_t tls_static_space; /* Static TLS space allocated */
256 size_t tls_static_max_align;
257 int tls_dtv_generation = 1; /* Used to detect when dtv size changes */
258 int tls_max_index = 1; /* Largest module index allocated */
260 bool ld_library_path_rpath = false;
263 * Fill in a DoneList with an allocation large enough to hold all of
264 * the currently-loaded objects. Keep this as a macro since it calls
265 * alloca and we want that to occur within the scope of the caller.
267 #define donelist_init(dlp) \
268 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
269 assert((dlp)->objs != NULL), \
270 (dlp)->num_alloc = obj_count, \
273 #define UTRACE_DLOPEN_START 1
274 #define UTRACE_DLOPEN_STOP 2
275 #define UTRACE_DLCLOSE_START 3
276 #define UTRACE_DLCLOSE_STOP 4
277 #define UTRACE_LOAD_OBJECT 5
278 #define UTRACE_UNLOAD_OBJECT 6
279 #define UTRACE_ADD_RUNDEP 7
280 #define UTRACE_PRELOAD_FINISHED 8
281 #define UTRACE_INIT_CALL 9
282 #define UTRACE_FINI_CALL 10
283 #define UTRACE_DLSYM_START 11
284 #define UTRACE_DLSYM_STOP 12
287 char sig[4]; /* 'RTLD' */
290 void *mapbase; /* Used for 'parent' and 'init/fini' */
292 int refcnt; /* Used for 'mode' */
293 char name[MAXPATHLEN];
296 #define LD_UTRACE(e, h, mb, ms, r, n) do { \
297 if (ld_utrace != NULL) \
298 ld_utrace_log(e, h, mb, ms, r, n); \
302 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
303 int refcnt, const char *name)
305 struct utrace_rtld ut;
313 ut.mapbase = mapbase;
314 ut.mapsize = mapsize;
316 bzero(ut.name, sizeof(ut.name));
318 strlcpy(ut.name, name, sizeof(ut.name));
319 utrace(&ut, sizeof(ut));
323 * Main entry point for dynamic linking. The first argument is the
324 * stack pointer. The stack is expected to be laid out as described
325 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
326 * Specifically, the stack pointer points to a word containing
327 * ARGC. Following that in the stack is a null-terminated sequence
328 * of pointers to argument strings. Then comes a null-terminated
329 * sequence of pointers to environment strings. Finally, there is a
330 * sequence of "auxiliary vector" entries.
332 * The second argument points to a place to store the dynamic linker's
333 * exit procedure pointer and the third to a place to store the main
336 * The return value is the main program's entry point.
339 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
341 Elf_Auxinfo *aux_info[AT_COUNT];
349 Objlist_Entry *entry;
351 Obj_Entry **preload_tail;
352 Obj_Entry *last_interposer;
354 RtldLockState lockstate;
355 char *library_path_rpath;
360 * On entry, the dynamic linker itself has not been relocated yet.
361 * Be very careful not to reference any global data until after
362 * init_rtld has returned. It is OK to reference file-scope statics
363 * and string constants, and to call static and global functions.
366 /* Find the auxiliary vector on the stack. */
369 sp += argc + 1; /* Skip over arguments and NULL terminator */
371 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
373 aux = (Elf_Auxinfo *) sp;
375 /* Digest the auxiliary vector. */
376 for (i = 0; i < AT_COUNT; i++)
378 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
379 if (auxp->a_type < AT_COUNT)
380 aux_info[auxp->a_type] = auxp;
383 /* Initialize and relocate ourselves. */
384 assert(aux_info[AT_BASE] != NULL);
385 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
387 __progname = obj_rtld.path;
388 argv0 = argv[0] != NULL ? argv[0] : "(null)";
393 if (aux_info[AT_CANARY] != NULL &&
394 aux_info[AT_CANARY]->a_un.a_ptr != NULL) {
395 i = aux_info[AT_CANARYLEN]->a_un.a_val;
396 if (i > sizeof(__stack_chk_guard))
397 i = sizeof(__stack_chk_guard);
398 memcpy(__stack_chk_guard, aux_info[AT_CANARY]->a_un.a_ptr, i);
403 len = sizeof(__stack_chk_guard);
404 if (sysctl(mib, 2, __stack_chk_guard, &len, NULL, 0) == -1 ||
405 len != sizeof(__stack_chk_guard)) {
406 /* If sysctl was unsuccessful, use the "terminator canary". */
407 ((unsigned char *)(void *)__stack_chk_guard)[0] = 0;
408 ((unsigned char *)(void *)__stack_chk_guard)[1] = 0;
409 ((unsigned char *)(void *)__stack_chk_guard)[2] = '\n';
410 ((unsigned char *)(void *)__stack_chk_guard)[3] = 255;
414 trust = !issetugid();
416 ld_bind_now = getenv(LD_ "BIND_NOW");
418 * If the process is tainted, then we un-set the dangerous environment
419 * variables. The process will be marked as tainted until setuid(2)
420 * is called. If any child process calls setuid(2) we do not want any
421 * future processes to honor the potentially un-safe variables.
424 if (unsetenv(LD_ "PRELOAD") || unsetenv(LD_ "LIBMAP") ||
425 unsetenv(LD_ "LIBRARY_PATH") || unsetenv(LD_ "LIBRARY_PATH_FDS") ||
426 unsetenv(LD_ "LIBMAP_DISABLE") ||
427 unsetenv(LD_ "DEBUG") || unsetenv(LD_ "ELF_HINTS_PATH") ||
428 unsetenv(LD_ "LOADFLTR") || unsetenv(LD_ "LIBRARY_PATH_RPATH")) {
429 _rtld_error("environment corrupt; aborting");
433 ld_debug = getenv(LD_ "DEBUG");
434 libmap_disable = getenv(LD_ "LIBMAP_DISABLE") != NULL;
435 libmap_override = getenv(LD_ "LIBMAP");
436 ld_library_path = getenv(LD_ "LIBRARY_PATH");
437 ld_library_dirs = getenv(LD_ "LIBRARY_PATH_FDS");
438 ld_preload = getenv(LD_ "PRELOAD");
439 ld_elf_hints_path = getenv(LD_ "ELF_HINTS_PATH");
440 ld_loadfltr = getenv(LD_ "LOADFLTR") != NULL;
441 library_path_rpath = getenv(LD_ "LIBRARY_PATH_RPATH");
442 if (library_path_rpath != NULL) {
443 if (library_path_rpath[0] == 'y' ||
444 library_path_rpath[0] == 'Y' ||
445 library_path_rpath[0] == '1')
446 ld_library_path_rpath = true;
448 ld_library_path_rpath = false;
450 dangerous_ld_env = libmap_disable || (libmap_override != NULL) ||
451 (ld_library_path != NULL) || (ld_preload != NULL) ||
452 (ld_elf_hints_path != NULL) || ld_loadfltr;
453 ld_tracing = getenv(LD_ "TRACE_LOADED_OBJECTS");
454 ld_utrace = getenv(LD_ "UTRACE");
456 if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0)
457 ld_elf_hints_path = _PATH_ELF_HINTS;
459 if (ld_debug != NULL && *ld_debug != '\0')
461 dbg("%s is initialized, base address = %p", __progname,
462 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
463 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
464 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
466 dbg("initializing thread locks");
470 * Load the main program, or process its program header if it is
473 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
474 int fd = aux_info[AT_EXECFD]->a_un.a_val;
475 dbg("loading main program");
476 obj_main = map_object(fd, argv0, NULL);
478 if (obj_main == NULL)
480 max_stack_flags = obj->stack_flags;
481 } else { /* Main program already loaded. */
482 const Elf_Phdr *phdr;
486 dbg("processing main program's program header");
487 assert(aux_info[AT_PHDR] != NULL);
488 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
489 assert(aux_info[AT_PHNUM] != NULL);
490 phnum = aux_info[AT_PHNUM]->a_un.a_val;
491 assert(aux_info[AT_PHENT] != NULL);
492 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
493 assert(aux_info[AT_ENTRY] != NULL);
494 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
495 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
499 if (aux_info[AT_EXECPATH] != 0) {
501 char buf[MAXPATHLEN];
503 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
504 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
505 if (kexecpath[0] == '/')
506 obj_main->path = kexecpath;
507 else if (getcwd(buf, sizeof(buf)) == NULL ||
508 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
509 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
510 obj_main->path = xstrdup(argv0);
512 obj_main->path = xstrdup(buf);
514 dbg("No AT_EXECPATH");
515 obj_main->path = xstrdup(argv0);
517 dbg("obj_main path %s", obj_main->path);
518 obj_main->mainprog = true;
520 if (aux_info[AT_STACKPROT] != NULL &&
521 aux_info[AT_STACKPROT]->a_un.a_val != 0)
522 stack_prot = aux_info[AT_STACKPROT]->a_un.a_val;
526 * Get the actual dynamic linker pathname from the executable if
527 * possible. (It should always be possible.) That ensures that
528 * gdb will find the right dynamic linker even if a non-standard
531 if (obj_main->interp != NULL &&
532 strcmp(obj_main->interp, obj_rtld.path) != 0) {
534 obj_rtld.path = xstrdup(obj_main->interp);
535 __progname = obj_rtld.path;
539 digest_dynamic(obj_main, 0);
540 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d",
541 obj_main->path, obj_main->valid_hash_sysv, obj_main->valid_hash_gnu,
542 obj_main->dynsymcount);
544 linkmap_add(obj_main);
545 linkmap_add(&obj_rtld);
547 /* Link the main program into the list of objects. */
548 *obj_tail = obj_main;
549 obj_tail = &obj_main->next;
553 /* Initialize a fake symbol for resolving undefined weak references. */
554 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
555 sym_zero.st_shndx = SHN_UNDEF;
556 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
559 libmap_disable = (bool)lm_init(libmap_override);
561 dbg("loading LD_PRELOAD libraries");
562 if (load_preload_objects() == -1)
564 preload_tail = obj_tail;
566 dbg("loading needed objects");
567 if (load_needed_objects(obj_main, 0) == -1)
570 /* Make a list of all objects loaded at startup. */
571 last_interposer = obj_main;
572 for (obj = obj_list; obj != NULL; obj = obj->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(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(obj_list, preload_tail, &initlist);
641 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
643 map_stacks_exec(NULL);
645 dbg("resolving ifuncs");
646 if (resolve_objects_ifunc(obj_main,
647 ld_bind_now != NULL && *ld_bind_now != '\0', SYMLOOK_EARLY,
651 if (!obj_main->crt_no_init) {
653 * Make sure we don't call the main program's init and fini
654 * functions for binaries linked with old crt1 which calls
657 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
658 obj_main->preinit_array = obj_main->init_array =
659 obj_main->fini_array = (Elf_Addr)NULL;
662 wlock_acquire(rtld_bind_lock, &lockstate);
663 if (obj_main->crt_no_init)
665 objlist_call_init(&initlist, &lockstate);
666 _r_debug_postinit(&obj_main->linkmap);
667 objlist_clear(&initlist);
668 dbg("loading filtees");
669 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
670 if (ld_loadfltr || obj->z_loadfltr)
671 load_filtees(obj, 0, &lockstate);
673 lock_release(rtld_bind_lock, &lockstate);
675 dbg("transferring control to program entry point = %p", obj_main->entry);
677 /* Return the exit procedure and the program entry point. */
678 *exit_proc = rtld_exit;
680 return (func_ptr_type) obj_main->entry;
684 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def)
689 ptr = (void *)make_function_pointer(def, obj);
690 target = ((Elf_Addr (*)(void))ptr)();
691 return ((void *)target);
695 _rtld_bind(Obj_Entry *obj, Elf_Size reloff)
699 const Obj_Entry *defobj;
702 RtldLockState lockstate;
704 rlock_acquire(rtld_bind_lock, &lockstate);
705 if (sigsetjmp(lockstate.env, 0) != 0)
706 lock_upgrade(rtld_bind_lock, &lockstate);
708 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
710 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
712 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
713 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL,
717 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
718 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
720 target = (Elf_Addr)(defobj->relocbase + def->st_value);
722 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
723 defobj->strtab + def->st_name, basename(obj->path),
724 (void *)target, basename(defobj->path));
727 * Write the new contents for the jmpslot. Note that depending on
728 * architecture, the value which we need to return back to the
729 * lazy binding trampoline may or may not be the target
730 * address. The value returned from reloc_jmpslot() is the value
731 * that the trampoline needs.
733 target = reloc_jmpslot(where, target, defobj, obj, rel);
734 lock_release(rtld_bind_lock, &lockstate);
739 * Error reporting function. Use it like printf. If formats the message
740 * into a buffer, and sets things up so that the next call to dlerror()
741 * will return the message.
744 _rtld_error(const char *fmt, ...)
746 static char buf[512];
750 rtld_vsnprintf(buf, sizeof buf, fmt, ap);
756 * Return a dynamically-allocated copy of the current error message, if any.
761 return error_message == NULL ? NULL : xstrdup(error_message);
765 * Restore the current error message from a copy which was previously saved
766 * by errmsg_save(). The copy is freed.
769 errmsg_restore(char *saved_msg)
771 if (saved_msg == NULL)
772 error_message = NULL;
774 _rtld_error("%s", saved_msg);
780 basename(const char *name)
782 const char *p = strrchr(name, '/');
783 return p != NULL ? p + 1 : name;
786 static struct utsname uts;
789 origin_subst_one(Obj_Entry *obj, char *real, const char *kw,
790 const char *subst, bool may_free)
792 char *p, *p1, *res, *resp;
793 int subst_len, kw_len, subst_count, old_len, new_len;
798 * First, count the number of the keyword occurences, to
799 * preallocate the final string.
801 for (p = real, subst_count = 0;; p = p1 + kw_len, subst_count++) {
808 * If the keyword is not found, just return.
810 * Return non-substituted string if resolution failed. We
811 * cannot do anything more reasonable, the failure mode of the
812 * caller is unresolved library anyway.
814 if (subst_count == 0 || (obj != NULL && !obj_resolve_origin(obj)))
815 return (may_free ? real : xstrdup(real));
817 subst = obj->origin_path;
820 * There is indeed something to substitute. Calculate the
821 * length of the resulting string, and allocate it.
823 subst_len = strlen(subst);
824 old_len = strlen(real);
825 new_len = old_len + (subst_len - kw_len) * subst_count;
826 res = xmalloc(new_len + 1);
829 * Now, execute the substitution loop.
831 for (p = real, resp = res, *resp = '\0';;) {
834 /* Copy the prefix before keyword. */
835 memcpy(resp, p, p1 - p);
837 /* Keyword replacement. */
838 memcpy(resp, subst, subst_len);
846 /* Copy to the end of string and finish. */
854 origin_subst(Obj_Entry *obj, char *real)
856 char *res1, *res2, *res3, *res4;
858 if (obj == NULL || !trust)
859 return (xstrdup(real));
860 if (uts.sysname[0] == '\0') {
861 if (uname(&uts) != 0) {
862 _rtld_error("utsname failed: %d", errno);
866 res1 = origin_subst_one(obj, real, "$ORIGIN", NULL, false);
867 res2 = origin_subst_one(NULL, res1, "$OSNAME", uts.sysname, true);
868 res3 = origin_subst_one(NULL, res2, "$OSREL", uts.release, true);
869 res4 = origin_subst_one(NULL, res3, "$PLATFORM", uts.machine, true);
876 const char *msg = dlerror();
880 rtld_fdputstr(STDERR_FILENO, msg);
881 rtld_fdputchar(STDERR_FILENO, '\n');
886 * Process a shared object's DYNAMIC section, and save the important
887 * information in its Obj_Entry structure.
890 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
891 const Elf_Dyn **dyn_soname, const Elf_Dyn **dyn_runpath)
894 Needed_Entry **needed_tail = &obj->needed;
895 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
896 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
897 const Elf_Hashelt *hashtab;
898 const Elf32_Word *hashval;
899 Elf32_Word bkt, nmaskwords;
901 int plttype = DT_REL;
907 obj->bind_now = false;
908 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
909 switch (dynp->d_tag) {
912 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
916 obj->relsize = dynp->d_un.d_val;
920 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
924 obj->pltrel = (const Elf_Rel *)
925 (obj->relocbase + dynp->d_un.d_ptr);
929 obj->pltrelsize = dynp->d_un.d_val;
933 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
937 obj->relasize = dynp->d_un.d_val;
941 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
945 plttype = dynp->d_un.d_val;
946 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
950 obj->symtab = (const Elf_Sym *)
951 (obj->relocbase + dynp->d_un.d_ptr);
955 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
959 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
963 obj->strsize = dynp->d_un.d_val;
967 obj->verneed = (const Elf_Verneed *) (obj->relocbase +
972 obj->verneednum = dynp->d_un.d_val;
976 obj->verdef = (const Elf_Verdef *) (obj->relocbase +
981 obj->verdefnum = dynp->d_un.d_val;
985 obj->versyms = (const Elf_Versym *)(obj->relocbase +
991 hashtab = (const Elf_Hashelt *)(obj->relocbase +
993 obj->nbuckets = hashtab[0];
994 obj->nchains = hashtab[1];
995 obj->buckets = hashtab + 2;
996 obj->chains = obj->buckets + obj->nbuckets;
997 obj->valid_hash_sysv = obj->nbuckets > 0 && obj->nchains > 0 &&
998 obj->buckets != NULL;
1004 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1006 obj->nbuckets_gnu = hashtab[0];
1007 obj->symndx_gnu = hashtab[1];
1008 nmaskwords = hashtab[2];
1009 bloom_size32 = (__ELF_WORD_SIZE / 32) * nmaskwords;
1010 obj->maskwords_bm_gnu = nmaskwords - 1;
1011 obj->shift2_gnu = hashtab[3];
1012 obj->bloom_gnu = (Elf_Addr *) (hashtab + 4);
1013 obj->buckets_gnu = hashtab + 4 + bloom_size32;
1014 obj->chain_zero_gnu = obj->buckets_gnu + obj->nbuckets_gnu -
1016 /* Number of bitmask words is required to be power of 2 */
1017 obj->valid_hash_gnu = powerof2(nmaskwords) &&
1018 obj->nbuckets_gnu > 0 && obj->buckets_gnu != NULL;
1024 Needed_Entry *nep = NEW(Needed_Entry);
1025 nep->name = dynp->d_un.d_val;
1030 needed_tail = &nep->next;
1036 Needed_Entry *nep = NEW(Needed_Entry);
1037 nep->name = dynp->d_un.d_val;
1041 *needed_filtees_tail = nep;
1042 needed_filtees_tail = &nep->next;
1048 Needed_Entry *nep = NEW(Needed_Entry);
1049 nep->name = dynp->d_un.d_val;
1053 *needed_aux_filtees_tail = nep;
1054 needed_aux_filtees_tail = &nep->next;
1059 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
1063 obj->textrel = true;
1067 obj->symbolic = true;
1072 * We have to wait until later to process this, because we
1073 * might not have gotten the address of the string table yet.
1083 *dyn_runpath = dynp;
1087 obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1090 case DT_PREINIT_ARRAY:
1091 obj->preinit_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1094 case DT_PREINIT_ARRAYSZ:
1095 obj->preinit_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1099 obj->init_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1102 case DT_INIT_ARRAYSZ:
1103 obj->init_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1107 obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1111 obj->fini_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1114 case DT_FINI_ARRAYSZ:
1115 obj->fini_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1119 * Don't process DT_DEBUG on MIPS as the dynamic section
1120 * is mapped read-only. DT_MIPS_RLD_MAP is used instead.
1125 /* XXX - not implemented yet */
1127 dbg("Filling in DT_DEBUG entry");
1128 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
1133 if (dynp->d_un.d_val & DF_ORIGIN)
1134 obj->z_origin = true;
1135 if (dynp->d_un.d_val & DF_SYMBOLIC)
1136 obj->symbolic = true;
1137 if (dynp->d_un.d_val & DF_TEXTREL)
1138 obj->textrel = true;
1139 if (dynp->d_un.d_val & DF_BIND_NOW)
1140 obj->bind_now = true;
1141 /*if (dynp->d_un.d_val & DF_STATIC_TLS)
1145 case DT_MIPS_LOCAL_GOTNO:
1146 obj->local_gotno = dynp->d_un.d_val;
1149 case DT_MIPS_SYMTABNO:
1150 obj->symtabno = dynp->d_un.d_val;
1153 case DT_MIPS_GOTSYM:
1154 obj->gotsym = dynp->d_un.d_val;
1157 case DT_MIPS_RLD_MAP:
1158 *((Elf_Addr *)(dynp->d_un.d_ptr)) = (Elf_Addr) &r_debug;
1163 if (dynp->d_un.d_val & DF_1_NOOPEN)
1164 obj->z_noopen = true;
1165 if (dynp->d_un.d_val & DF_1_ORIGIN)
1166 obj->z_origin = true;
1167 if (dynp->d_un.d_val & DF_1_GLOBAL)
1168 obj->z_global = true;
1169 if (dynp->d_un.d_val & DF_1_BIND_NOW)
1170 obj->bind_now = true;
1171 if (dynp->d_un.d_val & DF_1_NODELETE)
1172 obj->z_nodelete = true;
1173 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1174 obj->z_loadfltr = true;
1175 if (dynp->d_un.d_val & DF_1_INTERPOSE)
1176 obj->z_interpose = true;
1177 if (dynp->d_un.d_val & DF_1_NODEFLIB)
1178 obj->z_nodeflib = true;
1183 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1190 obj->traced = false;
1192 if (plttype == DT_RELA) {
1193 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1195 obj->pltrelasize = obj->pltrelsize;
1196 obj->pltrelsize = 0;
1199 /* Determine size of dynsym table (equal to nchains of sysv hash) */
1200 if (obj->valid_hash_sysv)
1201 obj->dynsymcount = obj->nchains;
1202 else if (obj->valid_hash_gnu) {
1203 obj->dynsymcount = 0;
1204 for (bkt = 0; bkt < obj->nbuckets_gnu; bkt++) {
1205 if (obj->buckets_gnu[bkt] == 0)
1207 hashval = &obj->chain_zero_gnu[obj->buckets_gnu[bkt]];
1210 while ((*hashval++ & 1u) == 0);
1212 obj->dynsymcount += obj->symndx_gnu;
1217 obj_resolve_origin(Obj_Entry *obj)
1220 if (obj->origin_path != NULL)
1222 obj->origin_path = xmalloc(PATH_MAX);
1223 return (rtld_dirname_abs(obj->path, obj->origin_path) != -1);
1227 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1228 const Elf_Dyn *dyn_soname, const Elf_Dyn *dyn_runpath)
1231 if (obj->z_origin && !obj_resolve_origin(obj))
1234 if (dyn_runpath != NULL) {
1235 obj->runpath = (char *)obj->strtab + dyn_runpath->d_un.d_val;
1236 obj->runpath = origin_subst(obj, obj->runpath);
1237 } else if (dyn_rpath != NULL) {
1238 obj->rpath = (char *)obj->strtab + dyn_rpath->d_un.d_val;
1239 obj->rpath = origin_subst(obj, obj->rpath);
1241 if (dyn_soname != NULL)
1242 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1246 digest_dynamic(Obj_Entry *obj, int early)
1248 const Elf_Dyn *dyn_rpath;
1249 const Elf_Dyn *dyn_soname;
1250 const Elf_Dyn *dyn_runpath;
1252 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname, &dyn_runpath);
1253 digest_dynamic2(obj, dyn_rpath, dyn_soname, dyn_runpath);
1257 * Process a shared object's program header. This is used only for the
1258 * main program, when the kernel has already loaded the main program
1259 * into memory before calling the dynamic linker. It creates and
1260 * returns an Obj_Entry structure.
1263 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1266 const Elf_Phdr *phlimit = phdr + phnum;
1268 Elf_Addr note_start, note_end;
1272 for (ph = phdr; ph < phlimit; ph++) {
1273 if (ph->p_type != PT_PHDR)
1277 obj->phsize = ph->p_memsz;
1278 obj->relocbase = (caddr_t)phdr - ph->p_vaddr;
1282 obj->stack_flags = PF_X | PF_R | PF_W;
1284 for (ph = phdr; ph < phlimit; ph++) {
1285 switch (ph->p_type) {
1288 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1292 if (nsegs == 0) { /* First load segment */
1293 obj->vaddrbase = trunc_page(ph->p_vaddr);
1294 obj->mapbase = obj->vaddrbase + obj->relocbase;
1295 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
1297 } else { /* Last load segment */
1298 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1305 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1310 obj->tlssize = ph->p_memsz;
1311 obj->tlsalign = ph->p_align;
1312 obj->tlsinitsize = ph->p_filesz;
1313 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1317 obj->stack_flags = ph->p_flags;
1321 obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1322 obj->relro_size = round_page(ph->p_memsz);
1326 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
1327 note_end = note_start + ph->p_filesz;
1328 digest_notes(obj, note_start, note_end);
1333 _rtld_error("%s: too few PT_LOAD segments", path);
1342 digest_notes(Obj_Entry *obj, Elf_Addr note_start, Elf_Addr note_end)
1344 const Elf_Note *note;
1345 const char *note_name;
1348 for (note = (const Elf_Note *)note_start; (Elf_Addr)note < note_end;
1349 note = (const Elf_Note *)((const char *)(note + 1) +
1350 roundup2(note->n_namesz, sizeof(Elf32_Addr)) +
1351 roundup2(note->n_descsz, sizeof(Elf32_Addr)))) {
1352 if (note->n_namesz != sizeof(NOTE_FREEBSD_VENDOR) ||
1353 note->n_descsz != sizeof(int32_t))
1355 if (note->n_type != ABI_NOTETYPE &&
1356 note->n_type != CRT_NOINIT_NOTETYPE)
1358 note_name = (const char *)(note + 1);
1359 if (strncmp(NOTE_FREEBSD_VENDOR, note_name,
1360 sizeof(NOTE_FREEBSD_VENDOR)) != 0)
1362 switch (note->n_type) {
1364 /* FreeBSD osrel note */
1365 p = (uintptr_t)(note + 1);
1366 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1367 obj->osrel = *(const int32_t *)(p);
1368 dbg("note osrel %d", obj->osrel);
1370 case CRT_NOINIT_NOTETYPE:
1371 /* FreeBSD 'crt does not call init' note */
1372 obj->crt_no_init = true;
1373 dbg("note crt_no_init");
1380 dlcheck(void *handle)
1384 for (obj = obj_list; obj != NULL; obj = obj->next)
1385 if (obj == (Obj_Entry *) handle)
1388 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1389 _rtld_error("Invalid shared object handle %p", handle);
1396 * If the given object is already in the donelist, return true. Otherwise
1397 * add the object to the list and return false.
1400 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1404 for (i = 0; i < dlp->num_used; i++)
1405 if (dlp->objs[i] == obj)
1408 * Our donelist allocation should always be sufficient. But if
1409 * our threads locking isn't working properly, more shared objects
1410 * could have been loaded since we allocated the list. That should
1411 * never happen, but we'll handle it properly just in case it does.
1413 if (dlp->num_used < dlp->num_alloc)
1414 dlp->objs[dlp->num_used++] = obj;
1419 * Hash function for symbol table lookup. Don't even think about changing
1420 * this. It is specified by the System V ABI.
1423 elf_hash(const char *name)
1425 const unsigned char *p = (const unsigned char *) name;
1426 unsigned long h = 0;
1429 while (*p != '\0') {
1430 h = (h << 4) + *p++;
1431 if ((g = h & 0xf0000000) != 0)
1439 * The GNU hash function is the Daniel J. Bernstein hash clipped to 32 bits
1440 * unsigned in case it's implemented with a wider type.
1443 gnu_hash(const char *s)
1449 for (c = *s; c != '\0'; c = *++s)
1451 return (h & 0xffffffff);
1456 * Find the library with the given name, and return its full pathname.
1457 * The returned string is dynamically allocated. Generates an error
1458 * message and returns NULL if the library cannot be found.
1460 * If the second argument is non-NULL, then it refers to an already-
1461 * loaded shared object, whose library search path will be searched.
1463 * If a library is successfully located via LD_LIBRARY_PATH_FDS, its
1464 * descriptor (which is close-on-exec) will be passed out via the third
1467 * The search order is:
1468 * DT_RPATH in the referencing file _unless_ DT_RUNPATH is present (1)
1469 * DT_RPATH of the main object if DSO without defined DT_RUNPATH (1)
1471 * DT_RUNPATH in the referencing file
1472 * ldconfig hints (if -z nodefaultlib, filter out default library directories
1474 * /lib:/usr/lib _unless_ the referencing file is linked with -z nodefaultlib
1476 * (1) Handled in digest_dynamic2 - rpath left NULL if runpath defined.
1479 find_library(const char *xname, const Obj_Entry *refobj, int *fdp)
1483 bool nodeflib, objgiven;
1485 objgiven = refobj != NULL;
1486 if (strchr(xname, '/') != NULL) { /* Hard coded pathname */
1487 if (xname[0] != '/' && !trust) {
1488 _rtld_error("Absolute pathname required for shared object \"%s\"",
1492 return (origin_subst(__DECONST(Obj_Entry *, refobj),
1493 __DECONST(char *, xname)));
1496 if (libmap_disable || !objgiven ||
1497 (name = lm_find(refobj->path, xname)) == NULL)
1498 name = (char *)xname;
1500 dbg(" Searching for \"%s\"", name);
1503 * If refobj->rpath != NULL, then refobj->runpath is NULL. Fall
1504 * back to pre-conforming behaviour if user requested so with
1505 * LD_LIBRARY_PATH_RPATH environment variable and ignore -z
1508 if (objgiven && refobj->rpath != NULL && ld_library_path_rpath) {
1509 if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
1511 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
1512 (pathname = search_library_pathfds(name, ld_library_dirs, fdp)) != NULL ||
1513 (pathname = search_library_path(name, gethints(false))) != NULL ||
1514 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
1517 nodeflib = objgiven ? refobj->z_nodeflib : false;
1519 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
1520 (objgiven && refobj->runpath == NULL && refobj != obj_main &&
1521 (pathname = search_library_path(name, obj_main->rpath)) != NULL) ||
1522 (pathname = search_library_path(name, ld_library_path)) != NULL ||
1524 (pathname = search_library_path(name, refobj->runpath)) != NULL) ||
1525 (pathname = search_library_pathfds(name, ld_library_dirs, fdp)) != NULL ||
1526 (pathname = search_library_path(name, gethints(nodeflib))) != NULL ||
1527 (objgiven && !nodeflib &&
1528 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL))
1532 if (objgiven && refobj->path != NULL) {
1533 _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
1534 name, basename(refobj->path));
1536 _rtld_error("Shared object \"%s\" not found", name);
1542 * Given a symbol number in a referencing object, find the corresponding
1543 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1544 * no definition was found. Returns a pointer to the Obj_Entry of the
1545 * defining object via the reference parameter DEFOBJ_OUT.
1548 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1549 const Obj_Entry **defobj_out, int flags, SymCache *cache,
1550 RtldLockState *lockstate)
1554 const Obj_Entry *defobj;
1560 * If we have already found this symbol, get the information from
1563 if (symnum >= refobj->dynsymcount)
1564 return NULL; /* Bad object */
1565 if (cache != NULL && cache[symnum].sym != NULL) {
1566 *defobj_out = cache[symnum].obj;
1567 return cache[symnum].sym;
1570 ref = refobj->symtab + symnum;
1571 name = refobj->strtab + ref->st_name;
1576 * We don't have to do a full scale lookup if the symbol is local.
1577 * We know it will bind to the instance in this load module; to
1578 * which we already have a pointer (ie ref). By not doing a lookup,
1579 * we not only improve performance, but it also avoids unresolvable
1580 * symbols when local symbols are not in the hash table. This has
1581 * been seen with the ia64 toolchain.
1583 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1584 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1585 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1588 symlook_init(&req, name);
1590 req.ventry = fetch_ventry(refobj, symnum);
1591 req.lockstate = lockstate;
1592 res = symlook_default(&req, refobj);
1595 defobj = req.defobj_out;
1603 * If we found no definition and the reference is weak, treat the
1604 * symbol as having the value zero.
1606 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1612 *defobj_out = defobj;
1613 /* Record the information in the cache to avoid subsequent lookups. */
1614 if (cache != NULL) {
1615 cache[symnum].sym = def;
1616 cache[symnum].obj = defobj;
1619 if (refobj != &obj_rtld)
1620 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1626 * Return the search path from the ldconfig hints file, reading it if
1627 * necessary. If nostdlib is true, then the default search paths are
1628 * not added to result.
1630 * Returns NULL if there are problems with the hints file,
1631 * or if the search path there is empty.
1634 gethints(bool nostdlib)
1636 static char *hints, *filtered_path;
1637 struct elfhints_hdr hdr;
1638 struct fill_search_info_args sargs, hargs;
1639 struct dl_serinfo smeta, hmeta, *SLPinfo, *hintinfo;
1640 struct dl_serpath *SLPpath, *hintpath;
1642 unsigned int SLPndx, hintndx, fndx, fcount;
1647 /* First call, read the hints file */
1648 if (hints == NULL) {
1649 /* Keep from trying again in case the hints file is bad. */
1652 if ((fd = open(ld_elf_hints_path, O_RDONLY | O_CLOEXEC)) == -1)
1654 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1655 hdr.magic != ELFHINTS_MAGIC ||
1660 p = xmalloc(hdr.dirlistlen + 1);
1661 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1662 read(fd, p, hdr.dirlistlen + 1) !=
1663 (ssize_t)hdr.dirlistlen + 1) {
1673 * If caller agreed to receive list which includes the default
1674 * paths, we are done. Otherwise, if we still did not
1675 * calculated filtered result, do it now.
1678 return (hints[0] != '\0' ? hints : NULL);
1679 if (filtered_path != NULL)
1683 * Obtain the list of all configured search paths, and the
1684 * list of the default paths.
1686 * First estimate the size of the results.
1688 smeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1690 hmeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1693 sargs.request = RTLD_DI_SERINFOSIZE;
1694 sargs.serinfo = &smeta;
1695 hargs.request = RTLD_DI_SERINFOSIZE;
1696 hargs.serinfo = &hmeta;
1698 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &sargs);
1699 path_enumerate(p, fill_search_info, &hargs);
1701 SLPinfo = xmalloc(smeta.dls_size);
1702 hintinfo = xmalloc(hmeta.dls_size);
1705 * Next fetch both sets of paths.
1707 sargs.request = RTLD_DI_SERINFO;
1708 sargs.serinfo = SLPinfo;
1709 sargs.serpath = &SLPinfo->dls_serpath[0];
1710 sargs.strspace = (char *)&SLPinfo->dls_serpath[smeta.dls_cnt];
1712 hargs.request = RTLD_DI_SERINFO;
1713 hargs.serinfo = hintinfo;
1714 hargs.serpath = &hintinfo->dls_serpath[0];
1715 hargs.strspace = (char *)&hintinfo->dls_serpath[hmeta.dls_cnt];
1717 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &sargs);
1718 path_enumerate(p, fill_search_info, &hargs);
1721 * Now calculate the difference between two sets, by excluding
1722 * standard paths from the full set.
1726 filtered_path = xmalloc(hdr.dirlistlen + 1);
1727 hintpath = &hintinfo->dls_serpath[0];
1728 for (hintndx = 0; hintndx < hmeta.dls_cnt; hintndx++, hintpath++) {
1730 SLPpath = &SLPinfo->dls_serpath[0];
1732 * Check each standard path against current.
1734 for (SLPndx = 0; SLPndx < smeta.dls_cnt; SLPndx++, SLPpath++) {
1735 /* matched, skip the path */
1736 if (!strcmp(hintpath->dls_name, SLPpath->dls_name)) {
1744 * Not matched against any standard path, add the path
1745 * to result. Separate consequtive paths with ':'.
1748 filtered_path[fndx] = ':';
1752 flen = strlen(hintpath->dls_name);
1753 strncpy((filtered_path + fndx), hintpath->dls_name, flen);
1756 filtered_path[fndx] = '\0';
1762 return (filtered_path[0] != '\0' ? filtered_path : NULL);
1766 init_dag(Obj_Entry *root)
1768 const Needed_Entry *needed;
1769 const Objlist_Entry *elm;
1772 if (root->dag_inited)
1774 donelist_init(&donelist);
1776 /* Root object belongs to own DAG. */
1777 objlist_push_tail(&root->dldags, root);
1778 objlist_push_tail(&root->dagmembers, root);
1779 donelist_check(&donelist, root);
1782 * Add dependencies of root object to DAG in breadth order
1783 * by exploiting the fact that each new object get added
1784 * to the tail of the dagmembers list.
1786 STAILQ_FOREACH(elm, &root->dagmembers, link) {
1787 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
1788 if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
1790 objlist_push_tail(&needed->obj->dldags, root);
1791 objlist_push_tail(&root->dagmembers, needed->obj);
1794 root->dag_inited = true;
1798 process_z(Obj_Entry *root)
1800 const Objlist_Entry *elm;
1804 * Walk over object DAG and process every dependent object
1805 * that is marked as DF_1_NODELETE or DF_1_GLOBAL. They need
1806 * to grow their own DAG.
1808 * For DF_1_GLOBAL, DAG is required for symbol lookups in
1809 * symlook_global() to work.
1811 * For DF_1_NODELETE, the DAG should have its reference upped.
1813 STAILQ_FOREACH(elm, &root->dagmembers, link) {
1817 if (obj->z_nodelete && !obj->ref_nodel) {
1818 dbg("obj %s -z nodelete", obj->path);
1821 obj->ref_nodel = true;
1823 if (obj->z_global && objlist_find(&list_global, obj) == NULL) {
1824 dbg("obj %s -z global", obj->path);
1825 objlist_push_tail(&list_global, obj);
1831 * Initialize the dynamic linker. The argument is the address at which
1832 * the dynamic linker has been mapped into memory. The primary task of
1833 * this function is to relocate the dynamic linker.
1836 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
1838 Obj_Entry objtmp; /* Temporary rtld object */
1839 const Elf_Dyn *dyn_rpath;
1840 const Elf_Dyn *dyn_soname;
1841 const Elf_Dyn *dyn_runpath;
1843 #ifdef RTLD_INIT_PAGESIZES_EARLY
1844 /* The page size is required by the dynamic memory allocator. */
1845 init_pagesizes(aux_info);
1849 * Conjure up an Obj_Entry structure for the dynamic linker.
1851 * The "path" member can't be initialized yet because string constants
1852 * cannot yet be accessed. Below we will set it correctly.
1854 memset(&objtmp, 0, sizeof(objtmp));
1857 objtmp.mapbase = mapbase;
1859 objtmp.relocbase = mapbase;
1861 if (RTLD_IS_DYNAMIC()) {
1862 objtmp.dynamic = rtld_dynamic(&objtmp);
1863 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname, &dyn_runpath);
1864 assert(objtmp.needed == NULL);
1865 #if !defined(__mips__)
1866 /* MIPS has a bogus DT_TEXTREL. */
1867 assert(!objtmp.textrel);
1871 * Temporarily put the dynamic linker entry into the object list, so
1872 * that symbols can be found.
1875 relocate_objects(&objtmp, true, &objtmp, 0, NULL);
1878 /* Initialize the object list. */
1879 obj_tail = &obj_list;
1881 /* Now that non-local variables can be accesses, copy out obj_rtld. */
1882 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1884 #ifndef RTLD_INIT_PAGESIZES_EARLY
1885 /* The page size is required by the dynamic memory allocator. */
1886 init_pagesizes(aux_info);
1889 if (aux_info[AT_OSRELDATE] != NULL)
1890 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
1892 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname, dyn_runpath);
1894 /* Replace the path with a dynamically allocated copy. */
1895 obj_rtld.path = xstrdup(PATH_RTLD);
1897 r_debug.r_brk = r_debug_state;
1898 r_debug.r_state = RT_CONSISTENT;
1902 * Retrieve the array of supported page sizes. The kernel provides the page
1903 * sizes in increasing order.
1906 init_pagesizes(Elf_Auxinfo **aux_info)
1908 static size_t psa[MAXPAGESIZES];
1912 if (aux_info[AT_PAGESIZES] != NULL && aux_info[AT_PAGESIZESLEN] !=
1914 size = aux_info[AT_PAGESIZESLEN]->a_un.a_val;
1915 pagesizes = aux_info[AT_PAGESIZES]->a_un.a_ptr;
1918 if (sysctlnametomib("hw.pagesizes", mib, &len) == 0)
1921 /* As a fallback, retrieve the base page size. */
1922 size = sizeof(psa[0]);
1923 if (aux_info[AT_PAGESZ] != NULL) {
1924 psa[0] = aux_info[AT_PAGESZ]->a_un.a_val;
1928 mib[1] = HW_PAGESIZE;
1932 if (sysctl(mib, len, psa, &size, NULL, 0) == -1) {
1933 _rtld_error("sysctl for hw.pagesize(s) failed");
1939 npagesizes = size / sizeof(pagesizes[0]);
1940 /* Discard any invalid entries at the end of the array. */
1941 while (npagesizes > 0 && pagesizes[npagesizes - 1] == 0)
1946 * Add the init functions from a needed object list (and its recursive
1947 * needed objects) to "list". This is not used directly; it is a helper
1948 * function for initlist_add_objects(). The write lock must be held
1949 * when this function is called.
1952 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1954 /* Recursively process the successor needed objects. */
1955 if (needed->next != NULL)
1956 initlist_add_neededs(needed->next, list);
1958 /* Process the current needed object. */
1959 if (needed->obj != NULL)
1960 initlist_add_objects(needed->obj, &needed->obj->next, list);
1964 * Scan all of the DAGs rooted in the range of objects from "obj" to
1965 * "tail" and add their init functions to "list". This recurses over
1966 * the DAGs and ensure the proper init ordering such that each object's
1967 * needed libraries are initialized before the object itself. At the
1968 * same time, this function adds the objects to the global finalization
1969 * list "list_fini" in the opposite order. The write lock must be
1970 * held when this function is called.
1973 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1976 if (obj->init_scanned || obj->init_done)
1978 obj->init_scanned = true;
1980 /* Recursively process the successor objects. */
1981 if (&obj->next != tail)
1982 initlist_add_objects(obj->next, tail, list);
1984 /* Recursively process the needed objects. */
1985 if (obj->needed != NULL)
1986 initlist_add_neededs(obj->needed, list);
1987 if (obj->needed_filtees != NULL)
1988 initlist_add_neededs(obj->needed_filtees, list);
1989 if (obj->needed_aux_filtees != NULL)
1990 initlist_add_neededs(obj->needed_aux_filtees, list);
1992 /* Add the object to the init list. */
1993 if (obj->preinit_array != (Elf_Addr)NULL || obj->init != (Elf_Addr)NULL ||
1994 obj->init_array != (Elf_Addr)NULL)
1995 objlist_push_tail(list, obj);
1997 /* Add the object to the global fini list in the reverse order. */
1998 if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL)
1999 && !obj->on_fini_list) {
2000 objlist_push_head(&list_fini, obj);
2001 obj->on_fini_list = true;
2006 #define FPTR_TARGET(f) ((Elf_Addr) (f))
2010 free_needed_filtees(Needed_Entry *n)
2012 Needed_Entry *needed, *needed1;
2014 for (needed = n; needed != NULL; needed = needed->next) {
2015 if (needed->obj != NULL) {
2016 dlclose(needed->obj);
2020 for (needed = n; needed != NULL; needed = needed1) {
2021 needed1 = needed->next;
2027 unload_filtees(Obj_Entry *obj)
2030 free_needed_filtees(obj->needed_filtees);
2031 obj->needed_filtees = NULL;
2032 free_needed_filtees(obj->needed_aux_filtees);
2033 obj->needed_aux_filtees = NULL;
2034 obj->filtees_loaded = false;
2038 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags,
2039 RtldLockState *lockstate)
2042 for (; needed != NULL; needed = needed->next) {
2043 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
2044 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
2045 RTLD_LOCAL, lockstate);
2050 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
2053 lock_restart_for_upgrade(lockstate);
2054 if (!obj->filtees_loaded) {
2055 load_filtee1(obj, obj->needed_filtees, flags, lockstate);
2056 load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate);
2057 obj->filtees_loaded = true;
2062 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
2066 for (; needed != NULL; needed = needed->next) {
2067 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
2068 flags & ~RTLD_LO_NOLOAD);
2069 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
2076 * Given a shared object, traverse its list of needed objects, and load
2077 * each of them. Returns 0 on success. Generates an error message and
2078 * returns -1 on failure.
2081 load_needed_objects(Obj_Entry *first, int flags)
2085 for (obj = first; obj != NULL; obj = obj->next) {
2086 if (process_needed(obj, obj->needed, flags) == -1)
2093 load_preload_objects(void)
2095 char *p = ld_preload;
2097 static const char delim[] = " \t:;";
2102 p += strspn(p, delim);
2103 while (*p != '\0') {
2104 size_t len = strcspn(p, delim);
2109 obj = load_object(p, -1, NULL, 0);
2111 return -1; /* XXX - cleanup */
2112 obj->z_interpose = true;
2115 p += strspn(p, delim);
2117 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
2122 printable_path(const char *path)
2125 return (path == NULL ? "<unknown>" : path);
2129 * Load a shared object into memory, if it is not already loaded. The
2130 * object may be specified by name or by user-supplied file descriptor
2131 * fd_u. In the later case, the fd_u descriptor is not closed, but its
2134 * Returns a pointer to the Obj_Entry for the object. Returns NULL
2138 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
2147 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
2148 if (object_match_name(obj, name))
2152 path = find_library(name, refobj, &fd);
2160 * search_library_pathfds() opens a fresh file descriptor for the
2161 * library, so there is no need to dup().
2163 } else if (fd_u == -1) {
2165 * If we didn't find a match by pathname, or the name is not
2166 * supplied, open the file and check again by device and inode.
2167 * This avoids false mismatches caused by multiple links or ".."
2170 * To avoid a race, we open the file and use fstat() rather than
2173 if ((fd = open(path, O_RDONLY | O_CLOEXEC | O_VERIFY)) == -1) {
2174 _rtld_error("Cannot open \"%s\"", path);
2179 fd = fcntl(fd_u, F_DUPFD_CLOEXEC, 0);
2181 _rtld_error("Cannot dup fd");
2186 if (fstat(fd, &sb) == -1) {
2187 _rtld_error("Cannot fstat \"%s\"", printable_path(path));
2192 for (obj = obj_list->next; obj != NULL; obj = obj->next)
2193 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
2195 if (obj != NULL && name != NULL) {
2196 object_add_name(obj, name);
2201 if (flags & RTLD_LO_NOLOAD) {
2207 /* First use of this object, so we must map it in */
2208 obj = do_load_object(fd, name, path, &sb, flags);
2217 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
2224 * but first, make sure that environment variables haven't been
2225 * used to circumvent the noexec flag on a filesystem.
2227 if (dangerous_ld_env) {
2228 if (fstatfs(fd, &fs) != 0) {
2229 _rtld_error("Cannot fstatfs \"%s\"", printable_path(path));
2232 if (fs.f_flags & MNT_NOEXEC) {
2233 _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
2237 dbg("loading \"%s\"", printable_path(path));
2238 obj = map_object(fd, printable_path(path), sbp);
2243 * If DT_SONAME is present in the object, digest_dynamic2 already
2244 * added it to the object names.
2247 object_add_name(obj, name);
2249 digest_dynamic(obj, 0);
2250 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path,
2251 obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount);
2252 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
2254 dbg("refusing to load non-loadable \"%s\"", obj->path);
2255 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
2256 munmap(obj->mapbase, obj->mapsize);
2261 obj->dlopened = (flags & RTLD_LO_DLOPEN) != 0;
2263 obj_tail = &obj->next;
2266 linkmap_add(obj); /* for GDB & dlinfo() */
2267 max_stack_flags |= obj->stack_flags;
2269 dbg(" %p .. %p: %s", obj->mapbase,
2270 obj->mapbase + obj->mapsize - 1, obj->path);
2272 dbg(" WARNING: %s has impure text", obj->path);
2273 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
2280 obj_from_addr(const void *addr)
2284 for (obj = obj_list; obj != NULL; obj = obj->next) {
2285 if (addr < (void *) obj->mapbase)
2287 if (addr < (void *) (obj->mapbase + obj->mapsize))
2296 Elf_Addr *preinit_addr;
2299 preinit_addr = (Elf_Addr *)obj_main->preinit_array;
2300 if (preinit_addr == NULL)
2303 for (index = 0; index < obj_main->preinit_array_num; index++) {
2304 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) {
2305 dbg("calling preinit function for %s at %p", obj_main->path,
2306 (void *)preinit_addr[index]);
2307 LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index],
2308 0, 0, obj_main->path);
2309 call_init_pointer(obj_main, preinit_addr[index]);
2315 * Call the finalization functions for each of the objects in "list"
2316 * belonging to the DAG of "root" and referenced once. If NULL "root"
2317 * is specified, every finalization function will be called regardless
2318 * of the reference count and the list elements won't be freed. All of
2319 * the objects are expected to have non-NULL fini functions.
2322 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
2326 Elf_Addr *fini_addr;
2329 assert(root == NULL || root->refcount == 1);
2332 * Preserve the current error message since a fini function might
2333 * call into the dynamic linker and overwrite it.
2335 saved_msg = errmsg_save();
2337 STAILQ_FOREACH(elm, list, link) {
2338 if (root != NULL && (elm->obj->refcount != 1 ||
2339 objlist_find(&root->dagmembers, elm->obj) == NULL))
2341 /* Remove object from fini list to prevent recursive invocation. */
2342 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2344 * XXX: If a dlopen() call references an object while the
2345 * fini function is in progress, we might end up trying to
2346 * unload the referenced object in dlclose() or the object
2347 * won't be unloaded although its fini function has been
2350 lock_release(rtld_bind_lock, lockstate);
2353 * It is legal to have both DT_FINI and DT_FINI_ARRAY defined.
2354 * When this happens, DT_FINI_ARRAY is processed first.
2356 fini_addr = (Elf_Addr *)elm->obj->fini_array;
2357 if (fini_addr != NULL && elm->obj->fini_array_num > 0) {
2358 for (index = elm->obj->fini_array_num - 1; index >= 0;
2360 if (fini_addr[index] != 0 && fini_addr[index] != 1) {
2361 dbg("calling fini function for %s at %p",
2362 elm->obj->path, (void *)fini_addr[index]);
2363 LD_UTRACE(UTRACE_FINI_CALL, elm->obj,
2364 (void *)fini_addr[index], 0, 0, elm->obj->path);
2365 call_initfini_pointer(elm->obj, fini_addr[index]);
2369 if (elm->obj->fini != (Elf_Addr)NULL) {
2370 dbg("calling fini function for %s at %p", elm->obj->path,
2371 (void *)elm->obj->fini);
2372 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini,
2373 0, 0, elm->obj->path);
2374 call_initfini_pointer(elm->obj, elm->obj->fini);
2376 wlock_acquire(rtld_bind_lock, lockstate);
2377 /* No need to free anything if process is going down. */
2381 * We must restart the list traversal after every fini call
2382 * because a dlclose() call from the fini function or from
2383 * another thread might have modified the reference counts.
2387 } while (elm != NULL);
2388 errmsg_restore(saved_msg);
2392 * Call the initialization functions for each of the objects in
2393 * "list". All of the objects are expected to have non-NULL init
2397 objlist_call_init(Objlist *list, RtldLockState *lockstate)
2402 Elf_Addr *init_addr;
2406 * Clean init_scanned flag so that objects can be rechecked and
2407 * possibly initialized earlier if any of vectors called below
2408 * cause the change by using dlopen.
2410 for (obj = obj_list; obj != NULL; obj = obj->next)
2411 obj->init_scanned = false;
2414 * Preserve the current error message since an init function might
2415 * call into the dynamic linker and overwrite it.
2417 saved_msg = errmsg_save();
2418 STAILQ_FOREACH(elm, list, link) {
2419 if (elm->obj->init_done) /* Initialized early. */
2422 * Race: other thread might try to use this object before current
2423 * one completes the initilization. Not much can be done here
2424 * without better locking.
2426 elm->obj->init_done = true;
2427 lock_release(rtld_bind_lock, lockstate);
2430 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined.
2431 * When this happens, DT_INIT is processed first.
2433 if (elm->obj->init != (Elf_Addr)NULL) {
2434 dbg("calling init function for %s at %p", elm->obj->path,
2435 (void *)elm->obj->init);
2436 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init,
2437 0, 0, elm->obj->path);
2438 call_initfini_pointer(elm->obj, elm->obj->init);
2440 init_addr = (Elf_Addr *)elm->obj->init_array;
2441 if (init_addr != NULL) {
2442 for (index = 0; index < elm->obj->init_array_num; index++) {
2443 if (init_addr[index] != 0 && init_addr[index] != 1) {
2444 dbg("calling init function for %s at %p", elm->obj->path,
2445 (void *)init_addr[index]);
2446 LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
2447 (void *)init_addr[index], 0, 0, elm->obj->path);
2448 call_init_pointer(elm->obj, init_addr[index]);
2452 wlock_acquire(rtld_bind_lock, lockstate);
2454 errmsg_restore(saved_msg);
2458 objlist_clear(Objlist *list)
2462 while (!STAILQ_EMPTY(list)) {
2463 elm = STAILQ_FIRST(list);
2464 STAILQ_REMOVE_HEAD(list, link);
2469 static Objlist_Entry *
2470 objlist_find(Objlist *list, const Obj_Entry *obj)
2474 STAILQ_FOREACH(elm, list, link)
2475 if (elm->obj == obj)
2481 objlist_init(Objlist *list)
2487 objlist_push_head(Objlist *list, Obj_Entry *obj)
2491 elm = NEW(Objlist_Entry);
2493 STAILQ_INSERT_HEAD(list, elm, link);
2497 objlist_push_tail(Objlist *list, Obj_Entry *obj)
2501 elm = NEW(Objlist_Entry);
2503 STAILQ_INSERT_TAIL(list, elm, link);
2507 objlist_put_after(Objlist *list, Obj_Entry *listobj, Obj_Entry *obj)
2509 Objlist_Entry *elm, *listelm;
2511 STAILQ_FOREACH(listelm, list, link) {
2512 if (listelm->obj == listobj)
2515 elm = NEW(Objlist_Entry);
2517 if (listelm != NULL)
2518 STAILQ_INSERT_AFTER(list, listelm, elm, link);
2520 STAILQ_INSERT_TAIL(list, elm, link);
2524 objlist_remove(Objlist *list, Obj_Entry *obj)
2528 if ((elm = objlist_find(list, obj)) != NULL) {
2529 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2535 * Relocate dag rooted in the specified object.
2536 * Returns 0 on success, or -1 on failure.
2540 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj,
2541 int flags, RtldLockState *lockstate)
2547 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2548 error = relocate_object(elm->obj, bind_now, rtldobj, flags,
2557 * Relocate single object.
2558 * Returns 0 on success, or -1 on failure.
2561 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
2562 int flags, RtldLockState *lockstate)
2567 obj->relocated = true;
2569 dbg("relocating \"%s\"", obj->path);
2571 if (obj->symtab == NULL || obj->strtab == NULL ||
2572 !(obj->valid_hash_sysv || obj->valid_hash_gnu)) {
2573 _rtld_error("%s: Shared object has no run-time symbol table",
2579 /* There are relocations to the write-protected text segment. */
2580 if (mprotect(obj->mapbase, obj->textsize,
2581 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
2582 _rtld_error("%s: Cannot write-enable text segment: %s",
2583 obj->path, rtld_strerror(errno));
2588 /* Process the non-PLT non-IFUNC relocations. */
2589 if (reloc_non_plt(obj, rtldobj, flags, lockstate))
2592 if (obj->textrel) { /* Re-protected the text segment. */
2593 if (mprotect(obj->mapbase, obj->textsize,
2594 PROT_READ|PROT_EXEC) == -1) {
2595 _rtld_error("%s: Cannot write-protect text segment: %s",
2596 obj->path, rtld_strerror(errno));
2601 /* Set the special PLT or GOT entries. */
2604 /* Process the PLT relocations. */
2605 if (reloc_plt(obj) == -1)
2607 /* Relocate the jump slots if we are doing immediate binding. */
2608 if (obj->bind_now || bind_now)
2609 if (reloc_jmpslots(obj, flags, lockstate) == -1)
2613 * Process the non-PLT IFUNC relocations. The relocations are
2614 * processed in two phases, because IFUNC resolvers may
2615 * reference other symbols, which must be readily processed
2616 * before resolvers are called.
2618 if (obj->non_plt_gnu_ifunc &&
2619 reloc_non_plt(obj, rtldobj, flags | SYMLOOK_IFUNC, lockstate))
2622 if (obj->relro_size > 0) {
2623 if (mprotect(obj->relro_page, obj->relro_size,
2625 _rtld_error("%s: Cannot enforce relro protection: %s",
2626 obj->path, rtld_strerror(errno));
2632 * Set up the magic number and version in the Obj_Entry. These
2633 * were checked in the crt1.o from the original ElfKit, so we
2634 * set them for backward compatibility.
2636 obj->magic = RTLD_MAGIC;
2637 obj->version = RTLD_VERSION;
2643 * Relocate newly-loaded shared objects. The argument is a pointer to
2644 * the Obj_Entry for the first such object. All objects from the first
2645 * to the end of the list of objects are relocated. Returns 0 on success,
2649 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
2650 int flags, RtldLockState *lockstate)
2655 for (error = 0, obj = first; obj != NULL; obj = obj->next) {
2656 error = relocate_object(obj, bind_now, rtldobj, flags,
2665 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
2666 * referencing STT_GNU_IFUNC symbols is postponed till the other
2667 * relocations are done. The indirect functions specified as
2668 * ifunc are allowed to call other symbols, so we need to have
2669 * objects relocated before asking for resolution from indirects.
2671 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
2672 * instead of the usual lazy handling of PLT slots. It is
2673 * consistent with how GNU does it.
2676 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags,
2677 RtldLockState *lockstate)
2679 if (obj->irelative && reloc_iresolve(obj, lockstate) == -1)
2681 if ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
2682 reloc_gnu_ifunc(obj, flags, lockstate) == -1)
2688 resolve_objects_ifunc(Obj_Entry *first, bool bind_now, int flags,
2689 RtldLockState *lockstate)
2693 for (obj = first; obj != NULL; obj = obj->next) {
2694 if (resolve_object_ifunc(obj, bind_now, flags, lockstate) == -1)
2701 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags,
2702 RtldLockState *lockstate)
2706 STAILQ_FOREACH(elm, list, link) {
2707 if (resolve_object_ifunc(elm->obj, bind_now, flags,
2715 * Cleanup procedure. It will be called (by the atexit mechanism) just
2716 * before the process exits.
2721 RtldLockState lockstate;
2723 wlock_acquire(rtld_bind_lock, &lockstate);
2725 objlist_call_fini(&list_fini, NULL, &lockstate);
2726 /* No need to remove the items from the list, since we are exiting. */
2727 if (!libmap_disable)
2729 lock_release(rtld_bind_lock, &lockstate);
2733 * Iterate over a search path, translate each element, and invoke the
2734 * callback on the result.
2737 path_enumerate(const char *path, path_enum_proc callback, void *arg)
2743 path += strspn(path, ":;");
2744 while (*path != '\0') {
2748 len = strcspn(path, ":;");
2749 trans = lm_findn(NULL, path, len);
2751 res = callback(trans, strlen(trans), arg);
2753 res = callback(path, len, arg);
2759 path += strspn(path, ":;");
2765 struct try_library_args {
2773 try_library_path(const char *dir, size_t dirlen, void *param)
2775 struct try_library_args *arg;
2778 if (*dir == '/' || trust) {
2781 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
2784 pathname = arg->buffer;
2785 strncpy(pathname, dir, dirlen);
2786 pathname[dirlen] = '/';
2787 strcpy(pathname + dirlen + 1, arg->name);
2789 dbg(" Trying \"%s\"", pathname);
2790 if (access(pathname, F_OK) == 0) { /* We found it */
2791 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
2792 strcpy(pathname, arg->buffer);
2800 search_library_path(const char *name, const char *path)
2803 struct try_library_args arg;
2809 arg.namelen = strlen(name);
2810 arg.buffer = xmalloc(PATH_MAX);
2811 arg.buflen = PATH_MAX;
2813 p = path_enumerate(path, try_library_path, &arg);
2822 * Finds the library with the given name using the directory descriptors
2823 * listed in the LD_LIBRARY_PATH_FDS environment variable.
2825 * Returns a freshly-opened close-on-exec file descriptor for the library,
2826 * or -1 if the library cannot be found.
2829 search_library_pathfds(const char *name, const char *path, int *fdp)
2831 char *envcopy, *fdstr, *found, *last_token;
2835 dbg("%s('%s', '%s', fdp)", __func__, name, path);
2837 /* Don't load from user-specified libdirs into setuid binaries. */
2841 /* We can't do anything if LD_LIBRARY_PATH_FDS isn't set. */
2845 /* LD_LIBRARY_PATH_FDS only works with relative paths. */
2846 if (name[0] == '/') {
2847 dbg("Absolute path (%s) passed to %s", name, __func__);
2852 * Use strtok_r() to walk the FD:FD:FD list. This requires a local
2853 * copy of the path, as strtok_r rewrites separator tokens
2857 envcopy = xstrdup(path);
2858 for (fdstr = strtok_r(envcopy, ":", &last_token); fdstr != NULL;
2859 fdstr = strtok_r(NULL, ":", &last_token)) {
2860 dirfd = parse_libdir(fdstr);
2863 fd = __sys_openat(dirfd, name, O_RDONLY | O_CLOEXEC | O_VERIFY);
2866 len = strlen(fdstr) + strlen(name) + 3;
2867 found = xmalloc(len);
2868 if (rtld_snprintf(found, len, "#%d/%s", dirfd, name) < 0) {
2869 _rtld_error("error generating '%d/%s'",
2873 dbg("open('%s') => %d", found, fd);
2884 dlclose(void *handle)
2887 RtldLockState lockstate;
2889 wlock_acquire(rtld_bind_lock, &lockstate);
2890 root = dlcheck(handle);
2892 lock_release(rtld_bind_lock, &lockstate);
2895 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
2898 /* Unreference the object and its dependencies. */
2899 root->dl_refcount--;
2901 if (root->refcount == 1) {
2903 * The object will be no longer referenced, so we must unload it.
2904 * First, call the fini functions.
2906 objlist_call_fini(&list_fini, root, &lockstate);
2910 /* Finish cleaning up the newly-unreferenced objects. */
2911 GDB_STATE(RT_DELETE,&root->linkmap);
2912 unload_object(root);
2913 GDB_STATE(RT_CONSISTENT,NULL);
2917 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
2918 lock_release(rtld_bind_lock, &lockstate);
2925 char *msg = error_message;
2926 error_message = NULL;
2931 * This function is deprecated and has no effect.
2934 dllockinit(void *context,
2935 void *(*lock_create)(void *context),
2936 void (*rlock_acquire)(void *lock),
2937 void (*wlock_acquire)(void *lock),
2938 void (*lock_release)(void *lock),
2939 void (*lock_destroy)(void *lock),
2940 void (*context_destroy)(void *context))
2942 static void *cur_context;
2943 static void (*cur_context_destroy)(void *);
2945 /* Just destroy the context from the previous call, if necessary. */
2946 if (cur_context_destroy != NULL)
2947 cur_context_destroy(cur_context);
2948 cur_context = context;
2949 cur_context_destroy = context_destroy;
2953 dlopen(const char *name, int mode)
2956 return (rtld_dlopen(name, -1, mode));
2960 fdlopen(int fd, int mode)
2963 return (rtld_dlopen(NULL, fd, mode));
2967 rtld_dlopen(const char *name, int fd, int mode)
2969 RtldLockState lockstate;
2972 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
2973 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
2974 if (ld_tracing != NULL) {
2975 rlock_acquire(rtld_bind_lock, &lockstate);
2976 if (sigsetjmp(lockstate.env, 0) != 0)
2977 lock_upgrade(rtld_bind_lock, &lockstate);
2978 environ = (char **)*get_program_var_addr("environ", &lockstate);
2979 lock_release(rtld_bind_lock, &lockstate);
2981 lo_flags = RTLD_LO_DLOPEN;
2982 if (mode & RTLD_NODELETE)
2983 lo_flags |= RTLD_LO_NODELETE;
2984 if (mode & RTLD_NOLOAD)
2985 lo_flags |= RTLD_LO_NOLOAD;
2986 if (ld_tracing != NULL)
2987 lo_flags |= RTLD_LO_TRACE;
2989 return (dlopen_object(name, fd, obj_main, lo_flags,
2990 mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL));
2994 dlopen_cleanup(Obj_Entry *obj)
2999 if (obj->refcount == 0)
3004 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
3005 int mode, RtldLockState *lockstate)
3007 Obj_Entry **old_obj_tail;
3010 RtldLockState mlockstate;
3013 objlist_init(&initlist);
3015 if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) {
3016 wlock_acquire(rtld_bind_lock, &mlockstate);
3017 lockstate = &mlockstate;
3019 GDB_STATE(RT_ADD,NULL);
3021 old_obj_tail = obj_tail;
3023 if (name == NULL && fd == -1) {
3027 obj = load_object(name, fd, refobj, lo_flags);
3032 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
3033 objlist_push_tail(&list_global, obj);
3034 if (*old_obj_tail != NULL) { /* We loaded something new. */
3035 assert(*old_obj_tail == obj);
3036 result = load_needed_objects(obj,
3037 lo_flags & (RTLD_LO_DLOPEN | RTLD_LO_EARLY));
3041 result = rtld_verify_versions(&obj->dagmembers);
3042 if (result != -1 && ld_tracing)
3044 if (result == -1 || relocate_object_dag(obj,
3045 (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld,
3046 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3048 dlopen_cleanup(obj);
3050 } else if (lo_flags & RTLD_LO_EARLY) {
3052 * Do not call the init functions for early loaded
3053 * filtees. The image is still not initialized enough
3056 * Our object is found by the global object list and
3057 * will be ordered among all init calls done right
3058 * before transferring control to main.
3061 /* Make list of init functions to call. */
3062 initlist_add_objects(obj, &obj->next, &initlist);
3065 * Process all no_delete or global objects here, given
3066 * them own DAGs to prevent their dependencies from being
3067 * unloaded. This has to be done after we have loaded all
3068 * of the dependencies, so that we do not miss any.
3074 * Bump the reference counts for objects on this DAG. If
3075 * this is the first dlopen() call for the object that was
3076 * already loaded as a dependency, initialize the dag
3082 if ((lo_flags & RTLD_LO_TRACE) != 0)
3085 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
3086 obj->z_nodelete) && !obj->ref_nodel) {
3087 dbg("obj %s nodelete", obj->path);
3089 obj->z_nodelete = obj->ref_nodel = true;
3093 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
3095 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
3097 if (!(lo_flags & RTLD_LO_EARLY)) {
3098 map_stacks_exec(lockstate);
3101 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
3102 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3104 objlist_clear(&initlist);
3105 dlopen_cleanup(obj);
3106 if (lockstate == &mlockstate)
3107 lock_release(rtld_bind_lock, lockstate);
3111 if (!(lo_flags & RTLD_LO_EARLY)) {
3112 /* Call the init functions. */
3113 objlist_call_init(&initlist, lockstate);
3115 objlist_clear(&initlist);
3116 if (lockstate == &mlockstate)
3117 lock_release(rtld_bind_lock, lockstate);
3120 trace_loaded_objects(obj);
3121 if (lockstate == &mlockstate)
3122 lock_release(rtld_bind_lock, lockstate);
3127 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
3131 const Obj_Entry *obj, *defobj;
3134 RtldLockState lockstate;
3141 symlook_init(&req, name);
3143 req.flags = flags | SYMLOOK_IN_PLT;
3144 req.lockstate = &lockstate;
3146 LD_UTRACE(UTRACE_DLSYM_START, handle, NULL, 0, 0, name);
3147 rlock_acquire(rtld_bind_lock, &lockstate);
3148 if (sigsetjmp(lockstate.env, 0) != 0)
3149 lock_upgrade(rtld_bind_lock, &lockstate);
3150 if (handle == NULL || handle == RTLD_NEXT ||
3151 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
3153 if ((obj = obj_from_addr(retaddr)) == NULL) {
3154 _rtld_error("Cannot determine caller's shared object");
3155 lock_release(rtld_bind_lock, &lockstate);
3156 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3159 if (handle == NULL) { /* Just the caller's shared object. */
3160 res = symlook_obj(&req, obj);
3163 defobj = req.defobj_out;
3165 } else if (handle == RTLD_NEXT || /* Objects after caller's */
3166 handle == RTLD_SELF) { /* ... caller included */
3167 if (handle == RTLD_NEXT)
3169 for (; obj != NULL; obj = obj->next) {
3170 res = symlook_obj(&req, obj);
3173 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) {
3175 defobj = req.defobj_out;
3176 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3182 * Search the dynamic linker itself, and possibly resolve the
3183 * symbol from there. This is how the application links to
3184 * dynamic linker services such as dlopen.
3186 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3187 res = symlook_obj(&req, &obj_rtld);
3190 defobj = req.defobj_out;
3194 assert(handle == RTLD_DEFAULT);
3195 res = symlook_default(&req, obj);
3197 defobj = req.defobj_out;
3202 if ((obj = dlcheck(handle)) == NULL) {
3203 lock_release(rtld_bind_lock, &lockstate);
3204 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3208 donelist_init(&donelist);
3209 if (obj->mainprog) {
3210 /* Handle obtained by dlopen(NULL, ...) implies global scope. */
3211 res = symlook_global(&req, &donelist);
3214 defobj = req.defobj_out;
3217 * Search the dynamic linker itself, and possibly resolve the
3218 * symbol from there. This is how the application links to
3219 * dynamic linker services such as dlopen.
3221 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3222 res = symlook_obj(&req, &obj_rtld);
3225 defobj = req.defobj_out;
3230 /* Search the whole DAG rooted at the given object. */
3231 res = symlook_list(&req, &obj->dagmembers, &donelist);
3234 defobj = req.defobj_out;
3240 lock_release(rtld_bind_lock, &lockstate);
3243 * The value required by the caller is derived from the value
3244 * of the symbol. this is simply the relocated value of the
3247 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
3248 sym = make_function_pointer(def, defobj);
3249 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
3250 sym = rtld_resolve_ifunc(defobj, def);
3251 else if (ELF_ST_TYPE(def->st_info) == STT_TLS) {
3252 ti.ti_module = defobj->tlsindex;
3253 ti.ti_offset = def->st_value;
3254 sym = __tls_get_addr(&ti);
3256 sym = defobj->relocbase + def->st_value;
3257 LD_UTRACE(UTRACE_DLSYM_STOP, handle, sym, 0, 0, name);
3261 _rtld_error("Undefined symbol \"%s\"", name);
3262 lock_release(rtld_bind_lock, &lockstate);
3263 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3268 dlsym(void *handle, const char *name)
3270 return do_dlsym(handle, name, __builtin_return_address(0), NULL,
3275 dlfunc(void *handle, const char *name)
3282 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
3288 dlvsym(void *handle, const char *name, const char *version)
3292 ventry.name = version;
3294 ventry.hash = elf_hash(version);
3296 return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
3301 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
3303 const Obj_Entry *obj;
3304 RtldLockState lockstate;
3306 rlock_acquire(rtld_bind_lock, &lockstate);
3307 obj = obj_from_addr(addr);
3309 _rtld_error("No shared object contains address");
3310 lock_release(rtld_bind_lock, &lockstate);
3313 rtld_fill_dl_phdr_info(obj, phdr_info);
3314 lock_release(rtld_bind_lock, &lockstate);
3319 dladdr(const void *addr, Dl_info *info)
3321 const Obj_Entry *obj;
3324 unsigned long symoffset;
3325 RtldLockState lockstate;
3327 rlock_acquire(rtld_bind_lock, &lockstate);
3328 obj = obj_from_addr(addr);
3330 _rtld_error("No shared object contains address");
3331 lock_release(rtld_bind_lock, &lockstate);
3334 info->dli_fname = obj->path;
3335 info->dli_fbase = obj->mapbase;
3336 info->dli_saddr = (void *)0;
3337 info->dli_sname = NULL;
3340 * Walk the symbol list looking for the symbol whose address is
3341 * closest to the address sent in.
3343 for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) {
3344 def = obj->symtab + symoffset;
3347 * For skip the symbol if st_shndx is either SHN_UNDEF or
3350 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
3354 * If the symbol is greater than the specified address, or if it
3355 * is further away from addr than the current nearest symbol,
3358 symbol_addr = obj->relocbase + def->st_value;
3359 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
3362 /* Update our idea of the nearest symbol. */
3363 info->dli_sname = obj->strtab + def->st_name;
3364 info->dli_saddr = symbol_addr;
3367 if (info->dli_saddr == addr)
3370 lock_release(rtld_bind_lock, &lockstate);
3375 dlinfo(void *handle, int request, void *p)
3377 const Obj_Entry *obj;
3378 RtldLockState lockstate;
3381 rlock_acquire(rtld_bind_lock, &lockstate);
3383 if (handle == NULL || handle == RTLD_SELF) {
3386 retaddr = __builtin_return_address(0); /* __GNUC__ only */
3387 if ((obj = obj_from_addr(retaddr)) == NULL)
3388 _rtld_error("Cannot determine caller's shared object");
3390 obj = dlcheck(handle);
3393 lock_release(rtld_bind_lock, &lockstate);
3399 case RTLD_DI_LINKMAP:
3400 *((struct link_map const **)p) = &obj->linkmap;
3402 case RTLD_DI_ORIGIN:
3403 error = rtld_dirname(obj->path, p);
3406 case RTLD_DI_SERINFOSIZE:
3407 case RTLD_DI_SERINFO:
3408 error = do_search_info(obj, request, (struct dl_serinfo *)p);
3412 _rtld_error("Invalid request %d passed to dlinfo()", request);
3416 lock_release(rtld_bind_lock, &lockstate);
3422 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
3425 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
3426 phdr_info->dlpi_name = obj->path;
3427 phdr_info->dlpi_phdr = obj->phdr;
3428 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
3429 phdr_info->dlpi_tls_modid = obj->tlsindex;
3430 phdr_info->dlpi_tls_data = obj->tlsinit;
3431 phdr_info->dlpi_adds = obj_loads;
3432 phdr_info->dlpi_subs = obj_loads - obj_count;
3436 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
3438 struct dl_phdr_info phdr_info;
3439 const Obj_Entry *obj;
3440 RtldLockState bind_lockstate, phdr_lockstate;
3443 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
3444 rlock_acquire(rtld_bind_lock, &bind_lockstate);
3448 for (obj = obj_list; obj != NULL; obj = obj->next) {
3449 rtld_fill_dl_phdr_info(obj, &phdr_info);
3450 if ((error = callback(&phdr_info, sizeof phdr_info, param)) != 0)
3455 rtld_fill_dl_phdr_info(&obj_rtld, &phdr_info);
3456 error = callback(&phdr_info, sizeof(phdr_info), param);
3459 lock_release(rtld_bind_lock, &bind_lockstate);
3460 lock_release(rtld_phdr_lock, &phdr_lockstate);
3466 fill_search_info(const char *dir, size_t dirlen, void *param)
3468 struct fill_search_info_args *arg;
3472 if (arg->request == RTLD_DI_SERINFOSIZE) {
3473 arg->serinfo->dls_cnt ++;
3474 arg->serinfo->dls_size += sizeof(struct dl_serpath) + dirlen + 1;
3476 struct dl_serpath *s_entry;
3478 s_entry = arg->serpath;
3479 s_entry->dls_name = arg->strspace;
3480 s_entry->dls_flags = arg->flags;
3482 strncpy(arg->strspace, dir, dirlen);
3483 arg->strspace[dirlen] = '\0';
3485 arg->strspace += dirlen + 1;
3493 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
3495 struct dl_serinfo _info;
3496 struct fill_search_info_args args;
3498 args.request = RTLD_DI_SERINFOSIZE;
3499 args.serinfo = &_info;
3501 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
3504 path_enumerate(obj->rpath, fill_search_info, &args);
3505 path_enumerate(ld_library_path, fill_search_info, &args);
3506 path_enumerate(obj->runpath, fill_search_info, &args);
3507 path_enumerate(gethints(obj->z_nodeflib), fill_search_info, &args);
3508 if (!obj->z_nodeflib)
3509 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
3512 if (request == RTLD_DI_SERINFOSIZE) {
3513 info->dls_size = _info.dls_size;
3514 info->dls_cnt = _info.dls_cnt;
3518 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
3519 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
3523 args.request = RTLD_DI_SERINFO;
3524 args.serinfo = info;
3525 args.serpath = &info->dls_serpath[0];
3526 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
3528 args.flags = LA_SER_RUNPATH;
3529 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
3532 args.flags = LA_SER_LIBPATH;
3533 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
3536 args.flags = LA_SER_RUNPATH;
3537 if (path_enumerate(obj->runpath, fill_search_info, &args) != NULL)
3540 args.flags = LA_SER_CONFIG;
3541 if (path_enumerate(gethints(obj->z_nodeflib), fill_search_info, &args)
3545 args.flags = LA_SER_DEFAULT;
3546 if (!obj->z_nodeflib &&
3547 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
3553 rtld_dirname(const char *path, char *bname)
3557 /* Empty or NULL string gets treated as "." */
3558 if (path == NULL || *path == '\0') {
3564 /* Strip trailing slashes */
3565 endp = path + strlen(path) - 1;
3566 while (endp > path && *endp == '/')
3569 /* Find the start of the dir */
3570 while (endp > path && *endp != '/')
3573 /* Either the dir is "/" or there are no slashes */
3575 bname[0] = *endp == '/' ? '/' : '.';
3581 } while (endp > path && *endp == '/');
3584 if (endp - path + 2 > PATH_MAX)
3586 _rtld_error("Filename is too long: %s", path);
3590 strncpy(bname, path, endp - path + 1);
3591 bname[endp - path + 1] = '\0';
3596 rtld_dirname_abs(const char *path, char *base)
3600 if (realpath(path, base) == NULL)
3602 dbg("%s -> %s", path, base);
3603 last = strrchr(base, '/');
3612 linkmap_add(Obj_Entry *obj)
3614 struct link_map *l = &obj->linkmap;
3615 struct link_map *prev;
3617 obj->linkmap.l_name = obj->path;
3618 obj->linkmap.l_addr = obj->mapbase;
3619 obj->linkmap.l_ld = obj->dynamic;
3621 /* GDB needs load offset on MIPS to use the symbols */
3622 obj->linkmap.l_offs = obj->relocbase;
3625 if (r_debug.r_map == NULL) {
3631 * Scan to the end of the list, but not past the entry for the
3632 * dynamic linker, which we want to keep at the very end.
3634 for (prev = r_debug.r_map;
3635 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
3636 prev = prev->l_next)
3639 /* Link in the new entry. */
3641 l->l_next = prev->l_next;
3642 if (l->l_next != NULL)
3643 l->l_next->l_prev = l;
3648 linkmap_delete(Obj_Entry *obj)
3650 struct link_map *l = &obj->linkmap;
3652 if (l->l_prev == NULL) {
3653 if ((r_debug.r_map = l->l_next) != NULL)
3654 l->l_next->l_prev = NULL;
3658 if ((l->l_prev->l_next = l->l_next) != NULL)
3659 l->l_next->l_prev = l->l_prev;
3663 * Function for the debugger to set a breakpoint on to gain control.
3665 * The two parameters allow the debugger to easily find and determine
3666 * what the runtime loader is doing and to whom it is doing it.
3668 * When the loadhook trap is hit (r_debug_state, set at program
3669 * initialization), the arguments can be found on the stack:
3671 * +8 struct link_map *m
3672 * +4 struct r_debug *rd
3676 r_debug_state(struct r_debug* rd, struct link_map *m)
3679 * The following is a hack to force the compiler to emit calls to
3680 * this function, even when optimizing. If the function is empty,
3681 * the compiler is not obliged to emit any code for calls to it,
3682 * even when marked __noinline. However, gdb depends on those
3685 __compiler_membar();
3689 * A function called after init routines have completed. This can be used to
3690 * break before a program's entry routine is called, and can be used when
3691 * main is not available in the symbol table.
3694 _r_debug_postinit(struct link_map *m)
3697 /* See r_debug_state(). */
3698 __compiler_membar();
3702 * Get address of the pointer variable in the main program.
3703 * Prefer non-weak symbol over the weak one.
3705 static const void **
3706 get_program_var_addr(const char *name, RtldLockState *lockstate)
3711 symlook_init(&req, name);
3712 req.lockstate = lockstate;
3713 donelist_init(&donelist);
3714 if (symlook_global(&req, &donelist) != 0)
3716 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
3717 return ((const void **)make_function_pointer(req.sym_out,
3719 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
3720 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
3722 return ((const void **)(req.defobj_out->relocbase +
3723 req.sym_out->st_value));
3727 * Set a pointer variable in the main program to the given value. This
3728 * is used to set key variables such as "environ" before any of the
3729 * init functions are called.
3732 set_program_var(const char *name, const void *value)
3736 if ((addr = get_program_var_addr(name, NULL)) != NULL) {
3737 dbg("\"%s\": *%p <-- %p", name, addr, value);
3743 * Search the global objects, including dependencies and main object,
3744 * for the given symbol.
3747 symlook_global(SymLook *req, DoneList *donelist)
3750 const Objlist_Entry *elm;
3753 symlook_init_from_req(&req1, req);
3755 /* Search all objects loaded at program start up. */
3756 if (req->defobj_out == NULL ||
3757 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3758 res = symlook_list(&req1, &list_main, donelist);
3759 if (res == 0 && (req->defobj_out == NULL ||
3760 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3761 req->sym_out = req1.sym_out;
3762 req->defobj_out = req1.defobj_out;
3763 assert(req->defobj_out != NULL);
3767 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
3768 STAILQ_FOREACH(elm, &list_global, link) {
3769 if (req->defobj_out != NULL &&
3770 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3772 res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
3773 if (res == 0 && (req->defobj_out == NULL ||
3774 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3775 req->sym_out = req1.sym_out;
3776 req->defobj_out = req1.defobj_out;
3777 assert(req->defobj_out != NULL);
3781 return (req->sym_out != NULL ? 0 : ESRCH);
3785 * Given a symbol name in a referencing object, find the corresponding
3786 * definition of the symbol. Returns a pointer to the symbol, or NULL if
3787 * no definition was found. Returns a pointer to the Obj_Entry of the
3788 * defining object via the reference parameter DEFOBJ_OUT.
3791 symlook_default(SymLook *req, const Obj_Entry *refobj)
3794 const Objlist_Entry *elm;
3798 donelist_init(&donelist);
3799 symlook_init_from_req(&req1, req);
3801 /* Look first in the referencing object if linked symbolically. */
3802 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
3803 res = symlook_obj(&req1, refobj);
3805 req->sym_out = req1.sym_out;
3806 req->defobj_out = req1.defobj_out;
3807 assert(req->defobj_out != NULL);
3811 symlook_global(req, &donelist);
3813 /* Search all dlopened DAGs containing the referencing object. */
3814 STAILQ_FOREACH(elm, &refobj->dldags, link) {
3815 if (req->sym_out != NULL &&
3816 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3818 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
3819 if (res == 0 && (req->sym_out == NULL ||
3820 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3821 req->sym_out = req1.sym_out;
3822 req->defobj_out = req1.defobj_out;
3823 assert(req->defobj_out != NULL);
3828 * Search the dynamic linker itself, and possibly resolve the
3829 * symbol from there. This is how the application links to
3830 * dynamic linker services such as dlopen.
3832 if (req->sym_out == NULL ||
3833 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3834 res = symlook_obj(&req1, &obj_rtld);
3836 req->sym_out = req1.sym_out;
3837 req->defobj_out = req1.defobj_out;
3838 assert(req->defobj_out != NULL);
3842 return (req->sym_out != NULL ? 0 : ESRCH);
3846 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
3849 const Obj_Entry *defobj;
3850 const Objlist_Entry *elm;
3856 STAILQ_FOREACH(elm, objlist, link) {
3857 if (donelist_check(dlp, elm->obj))
3859 symlook_init_from_req(&req1, req);
3860 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
3861 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3863 defobj = req1.defobj_out;
3864 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3871 req->defobj_out = defobj;
3878 * Search the chain of DAGS cointed to by the given Needed_Entry
3879 * for a symbol of the given name. Each DAG is scanned completely
3880 * before advancing to the next one. Returns a pointer to the symbol,
3881 * or NULL if no definition was found.
3884 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
3887 const Needed_Entry *n;
3888 const Obj_Entry *defobj;
3894 symlook_init_from_req(&req1, req);
3895 for (n = needed; n != NULL; n = n->next) {
3896 if (n->obj == NULL ||
3897 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
3899 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3901 defobj = req1.defobj_out;
3902 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3908 req->defobj_out = defobj;
3915 * Search the symbol table of a single shared object for a symbol of
3916 * the given name and version, if requested. Returns a pointer to the
3917 * symbol, or NULL if no definition was found. If the object is
3918 * filter, return filtered symbol from filtee.
3920 * The symbol's hash value is passed in for efficiency reasons; that
3921 * eliminates many recomputations of the hash value.
3924 symlook_obj(SymLook *req, const Obj_Entry *obj)
3928 int flags, res, mres;
3931 * If there is at least one valid hash at this point, we prefer to
3932 * use the faster GNU version if available.
3934 if (obj->valid_hash_gnu)
3935 mres = symlook_obj1_gnu(req, obj);
3936 else if (obj->valid_hash_sysv)
3937 mres = symlook_obj1_sysv(req, obj);
3942 if (obj->needed_filtees != NULL) {
3943 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
3944 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
3945 donelist_init(&donelist);
3946 symlook_init_from_req(&req1, req);
3947 res = symlook_needed(&req1, obj->needed_filtees, &donelist);
3949 req->sym_out = req1.sym_out;
3950 req->defobj_out = req1.defobj_out;
3954 if (obj->needed_aux_filtees != NULL) {
3955 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
3956 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
3957 donelist_init(&donelist);
3958 symlook_init_from_req(&req1, req);
3959 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
3961 req->sym_out = req1.sym_out;
3962 req->defobj_out = req1.defobj_out;
3970 /* Symbol match routine common to both hash functions */
3972 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result,
3973 const unsigned long symnum)
3976 const Elf_Sym *symp;
3979 symp = obj->symtab + symnum;
3980 strp = obj->strtab + symp->st_name;
3982 switch (ELF_ST_TYPE(symp->st_info)) {
3988 if (symp->st_value == 0)
3992 if (symp->st_shndx != SHN_UNDEF)
3995 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
3996 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
4003 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
4006 if (req->ventry == NULL) {
4007 if (obj->versyms != NULL) {
4008 verndx = VER_NDX(obj->versyms[symnum]);
4009 if (verndx > obj->vernum) {
4011 "%s: symbol %s references wrong version %d",
4012 obj->path, obj->strtab + symnum, verndx);
4016 * If we are not called from dlsym (i.e. this
4017 * is a normal relocation from unversioned
4018 * binary), accept the symbol immediately if
4019 * it happens to have first version after this
4020 * shared object became versioned. Otherwise,
4021 * if symbol is versioned and not hidden,
4022 * remember it. If it is the only symbol with
4023 * this name exported by the shared object, it
4024 * will be returned as a match by the calling
4025 * function. If symbol is global (verndx < 2)
4026 * accept it unconditionally.
4028 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
4029 verndx == VER_NDX_GIVEN) {
4030 result->sym_out = symp;
4033 else if (verndx >= VER_NDX_GIVEN) {
4034 if ((obj->versyms[symnum] & VER_NDX_HIDDEN)
4036 if (result->vsymp == NULL)
4037 result->vsymp = symp;
4043 result->sym_out = symp;
4046 if (obj->versyms == NULL) {
4047 if (object_match_name(obj, req->ventry->name)) {
4048 _rtld_error("%s: object %s should provide version %s "
4049 "for symbol %s", obj_rtld.path, obj->path,
4050 req->ventry->name, obj->strtab + symnum);
4054 verndx = VER_NDX(obj->versyms[symnum]);
4055 if (verndx > obj->vernum) {
4056 _rtld_error("%s: symbol %s references wrong version %d",
4057 obj->path, obj->strtab + symnum, verndx);
4060 if (obj->vertab[verndx].hash != req->ventry->hash ||
4061 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
4063 * Version does not match. Look if this is a
4064 * global symbol and if it is not hidden. If
4065 * global symbol (verndx < 2) is available,
4066 * use it. Do not return symbol if we are
4067 * called by dlvsym, because dlvsym looks for
4068 * a specific version and default one is not
4069 * what dlvsym wants.
4071 if ((req->flags & SYMLOOK_DLSYM) ||
4072 (verndx >= VER_NDX_GIVEN) ||
4073 (obj->versyms[symnum] & VER_NDX_HIDDEN))
4077 result->sym_out = symp;
4082 * Search for symbol using SysV hash function.
4083 * obj->buckets is known not to be NULL at this point; the test for this was
4084 * performed with the obj->valid_hash_sysv assignment.
4087 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj)
4089 unsigned long symnum;
4090 Sym_Match_Result matchres;
4092 matchres.sym_out = NULL;
4093 matchres.vsymp = NULL;
4094 matchres.vcount = 0;
4096 for (symnum = obj->buckets[req->hash % obj->nbuckets];
4097 symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
4098 if (symnum >= obj->nchains)
4099 return (ESRCH); /* Bad object */
4101 if (matched_symbol(req, obj, &matchres, symnum)) {
4102 req->sym_out = matchres.sym_out;
4103 req->defobj_out = obj;
4107 if (matchres.vcount == 1) {
4108 req->sym_out = matchres.vsymp;
4109 req->defobj_out = obj;
4115 /* Search for symbol using GNU hash function */
4117 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj)
4119 Elf_Addr bloom_word;
4120 const Elf32_Word *hashval;
4122 Sym_Match_Result matchres;
4123 unsigned int h1, h2;
4124 unsigned long symnum;
4126 matchres.sym_out = NULL;
4127 matchres.vsymp = NULL;
4128 matchres.vcount = 0;
4130 /* Pick right bitmask word from Bloom filter array */
4131 bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) &
4132 obj->maskwords_bm_gnu];
4134 /* Calculate modulus word size of gnu hash and its derivative */
4135 h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1);
4136 h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1));
4138 /* Filter out the "definitely not in set" queries */
4139 if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0)
4142 /* Locate hash chain and corresponding value element*/
4143 bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu];
4146 hashval = &obj->chain_zero_gnu[bucket];
4148 if (((*hashval ^ req->hash_gnu) >> 1) == 0) {
4149 symnum = hashval - obj->chain_zero_gnu;
4150 if (matched_symbol(req, obj, &matchres, symnum)) {
4151 req->sym_out = matchres.sym_out;
4152 req->defobj_out = obj;
4156 } while ((*hashval++ & 1) == 0);
4157 if (matchres.vcount == 1) {
4158 req->sym_out = matchres.vsymp;
4159 req->defobj_out = obj;
4166 trace_loaded_objects(Obj_Entry *obj)
4168 char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
4171 if ((main_local = getenv(LD_ "TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
4174 if ((fmt1 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT1")) == NULL)
4175 fmt1 = "\t%o => %p (%x)\n";
4177 if ((fmt2 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT2")) == NULL)
4178 fmt2 = "\t%o (%x)\n";
4180 list_containers = getenv(LD_ "TRACE_LOADED_OBJECTS_ALL");
4182 for (; obj; obj = obj->next) {
4183 Needed_Entry *needed;
4187 if (list_containers && obj->needed != NULL)
4188 rtld_printf("%s:\n", obj->path);
4189 for (needed = obj->needed; needed; needed = needed->next) {
4190 if (needed->obj != NULL) {
4191 if (needed->obj->traced && !list_containers)
4193 needed->obj->traced = true;
4194 path = needed->obj->path;
4198 name = (char *)obj->strtab + needed->name;
4199 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
4201 fmt = is_lib ? fmt1 : fmt2;
4202 while ((c = *fmt++) != '\0') {
4228 rtld_putstr(main_local);
4231 rtld_putstr(obj_main->path);
4238 rtld_printf("%d", sodp->sod_major);
4241 rtld_printf("%d", sodp->sod_minor);
4248 rtld_printf("%p", needed->obj ? needed->obj->mapbase :
4261 * Unload a dlopened object and its dependencies from memory and from
4262 * our data structures. It is assumed that the DAG rooted in the
4263 * object has already been unreferenced, and that the object has a
4264 * reference count of 0.
4267 unload_object(Obj_Entry *root)
4272 assert(root->refcount == 0);
4275 * Pass over the DAG removing unreferenced objects from
4276 * appropriate lists.
4278 unlink_object(root);
4280 /* Unmap all objects that are no longer referenced. */
4281 linkp = &obj_list->next;
4282 while ((obj = *linkp) != NULL) {
4283 if (obj->refcount == 0) {
4284 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
4286 dbg("unloading \"%s\"", obj->path);
4287 unload_filtees(root);
4288 munmap(obj->mapbase, obj->mapsize);
4289 linkmap_delete(obj);
4300 unlink_object(Obj_Entry *root)
4304 if (root->refcount == 0) {
4305 /* Remove the object from the RTLD_GLOBAL list. */
4306 objlist_remove(&list_global, root);
4308 /* Remove the object from all objects' DAG lists. */
4309 STAILQ_FOREACH(elm, &root->dagmembers, link) {
4310 objlist_remove(&elm->obj->dldags, root);
4311 if (elm->obj != root)
4312 unlink_object(elm->obj);
4318 ref_dag(Obj_Entry *root)
4322 assert(root->dag_inited);
4323 STAILQ_FOREACH(elm, &root->dagmembers, link)
4324 elm->obj->refcount++;
4328 unref_dag(Obj_Entry *root)
4332 assert(root->dag_inited);
4333 STAILQ_FOREACH(elm, &root->dagmembers, link)
4334 elm->obj->refcount--;
4338 * Common code for MD __tls_get_addr().
4340 static void *tls_get_addr_slow(Elf_Addr **, int, size_t) __noinline;
4342 tls_get_addr_slow(Elf_Addr **dtvp, int index, size_t offset)
4344 Elf_Addr *newdtv, *dtv;
4345 RtldLockState lockstate;
4349 /* Check dtv generation in case new modules have arrived */
4350 if (dtv[0] != tls_dtv_generation) {
4351 wlock_acquire(rtld_bind_lock, &lockstate);
4352 newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4354 if (to_copy > tls_max_index)
4355 to_copy = tls_max_index;
4356 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
4357 newdtv[0] = tls_dtv_generation;
4358 newdtv[1] = tls_max_index;
4360 lock_release(rtld_bind_lock, &lockstate);
4361 dtv = *dtvp = newdtv;
4364 /* Dynamically allocate module TLS if necessary */
4365 if (dtv[index + 1] == 0) {
4366 /* Signal safe, wlock will block out signals. */
4367 wlock_acquire(rtld_bind_lock, &lockstate);
4368 if (!dtv[index + 1])
4369 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
4370 lock_release(rtld_bind_lock, &lockstate);
4372 return ((void *)(dtv[index + 1] + offset));
4376 tls_get_addr_common(Elf_Addr **dtvp, int index, size_t offset)
4381 /* Check dtv generation in case new modules have arrived */
4382 if (__predict_true(dtv[0] == tls_dtv_generation &&
4383 dtv[index + 1] != 0))
4384 return ((void *)(dtv[index + 1] + offset));
4385 return (tls_get_addr_slow(dtvp, index, offset));
4388 #if defined(__aarch64__) || defined(__arm__) || defined(__mips__) || \
4389 defined(__powerpc__)
4392 * Allocate Static TLS using the Variant I method.
4395 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
4404 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
4407 assert(tcbsize >= TLS_TCB_SIZE);
4408 tcb = xcalloc(1, tls_static_space - TLS_TCB_SIZE + tcbsize);
4409 tls = (Elf_Addr **)(tcb + tcbsize - TLS_TCB_SIZE);
4411 if (oldtcb != NULL) {
4412 memcpy(tls, oldtcb, tls_static_space);
4415 /* Adjust the DTV. */
4417 for (i = 0; i < dtv[1]; i++) {
4418 if (dtv[i+2] >= (Elf_Addr)oldtcb &&
4419 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
4420 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tls;
4424 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4426 dtv[0] = tls_dtv_generation;
4427 dtv[1] = tls_max_index;
4429 for (obj = objs; obj; obj = obj->next) {
4430 if (obj->tlsoffset > 0) {
4431 addr = (Elf_Addr)tls + obj->tlsoffset;
4432 if (obj->tlsinitsize > 0)
4433 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4434 if (obj->tlssize > obj->tlsinitsize)
4435 memset((void*) (addr + obj->tlsinitsize), 0,
4436 obj->tlssize - obj->tlsinitsize);
4437 dtv[obj->tlsindex + 1] = addr;
4446 free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
4449 Elf_Addr tlsstart, tlsend;
4452 assert(tcbsize >= TLS_TCB_SIZE);
4454 tlsstart = (Elf_Addr)tcb + tcbsize - TLS_TCB_SIZE;
4455 tlsend = tlsstart + tls_static_space;
4457 dtv = *(Elf_Addr **)tlsstart;
4459 for (i = 0; i < dtvsize; i++) {
4460 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
4461 free((void*)dtv[i+2]);
4470 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__)
4473 * Allocate Static TLS using the Variant II method.
4476 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
4479 size_t size, ralign;
4481 Elf_Addr *dtv, *olddtv;
4482 Elf_Addr segbase, oldsegbase, addr;
4486 if (tls_static_max_align > ralign)
4487 ralign = tls_static_max_align;
4488 size = round(tls_static_space, ralign) + round(tcbsize, ralign);
4490 assert(tcbsize >= 2*sizeof(Elf_Addr));
4491 tls = malloc_aligned(size, ralign);
4492 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4494 segbase = (Elf_Addr)(tls + round(tls_static_space, ralign));
4495 ((Elf_Addr*)segbase)[0] = segbase;
4496 ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
4498 dtv[0] = tls_dtv_generation;
4499 dtv[1] = tls_max_index;
4503 * Copy the static TLS block over whole.
4505 oldsegbase = (Elf_Addr) oldtls;
4506 memcpy((void *)(segbase - tls_static_space),
4507 (const void *)(oldsegbase - tls_static_space),
4511 * If any dynamic TLS blocks have been created tls_get_addr(),
4514 olddtv = ((Elf_Addr**)oldsegbase)[1];
4515 for (i = 0; i < olddtv[1]; i++) {
4516 if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
4517 dtv[i+2] = olddtv[i+2];
4523 * We assume that this block was the one we created with
4524 * allocate_initial_tls().
4526 free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
4528 for (obj = objs; obj; obj = obj->next) {
4529 if (obj->tlsoffset) {
4530 addr = segbase - obj->tlsoffset;
4531 memset((void*) (addr + obj->tlsinitsize),
4532 0, obj->tlssize - obj->tlsinitsize);
4534 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4535 dtv[obj->tlsindex + 1] = addr;
4540 return (void*) segbase;
4544 free_tls(void *tls, size_t tcbsize, size_t tcbalign)
4547 size_t size, ralign;
4549 Elf_Addr tlsstart, tlsend;
4552 * Figure out the size of the initial TLS block so that we can
4553 * find stuff which ___tls_get_addr() allocated dynamically.
4556 if (tls_static_max_align > ralign)
4557 ralign = tls_static_max_align;
4558 size = round(tls_static_space, ralign);
4560 dtv = ((Elf_Addr**)tls)[1];
4562 tlsend = (Elf_Addr) tls;
4563 tlsstart = tlsend - size;
4564 for (i = 0; i < dtvsize; i++) {
4565 if (dtv[i + 2] != 0 && (dtv[i + 2] < tlsstart || dtv[i + 2] > tlsend)) {
4566 free_aligned((void *)dtv[i + 2]);
4570 free_aligned((void *)tlsstart);
4577 * Allocate TLS block for module with given index.
4580 allocate_module_tls(int index)
4585 for (obj = obj_list; obj; obj = obj->next) {
4586 if (obj->tlsindex == index)
4590 _rtld_error("Can't find module with TLS index %d", index);
4594 p = malloc_aligned(obj->tlssize, obj->tlsalign);
4595 memcpy(p, obj->tlsinit, obj->tlsinitsize);
4596 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
4602 allocate_tls_offset(Obj_Entry *obj)
4609 if (obj->tlssize == 0) {
4610 obj->tls_done = true;
4614 if (tls_last_offset == 0)
4615 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
4617 off = calculate_tls_offset(tls_last_offset, tls_last_size,
4618 obj->tlssize, obj->tlsalign);
4621 * If we have already fixed the size of the static TLS block, we
4622 * must stay within that size. When allocating the static TLS, we
4623 * leave a small amount of space spare to be used for dynamically
4624 * loading modules which use static TLS.
4626 if (tls_static_space != 0) {
4627 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
4629 } else if (obj->tlsalign > tls_static_max_align) {
4630 tls_static_max_align = obj->tlsalign;
4633 tls_last_offset = obj->tlsoffset = off;
4634 tls_last_size = obj->tlssize;
4635 obj->tls_done = true;
4641 free_tls_offset(Obj_Entry *obj)
4645 * If we were the last thing to allocate out of the static TLS
4646 * block, we give our space back to the 'allocator'. This is a
4647 * simplistic workaround to allow libGL.so.1 to be loaded and
4648 * unloaded multiple times.
4650 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
4651 == calculate_tls_end(tls_last_offset, tls_last_size)) {
4652 tls_last_offset -= obj->tlssize;
4658 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
4661 RtldLockState lockstate;
4663 wlock_acquire(rtld_bind_lock, &lockstate);
4664 ret = allocate_tls(obj_list, oldtls, tcbsize, tcbalign);
4665 lock_release(rtld_bind_lock, &lockstate);
4670 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
4672 RtldLockState lockstate;
4674 wlock_acquire(rtld_bind_lock, &lockstate);
4675 free_tls(tcb, tcbsize, tcbalign);
4676 lock_release(rtld_bind_lock, &lockstate);
4680 object_add_name(Obj_Entry *obj, const char *name)
4686 entry = malloc(sizeof(Name_Entry) + len);
4688 if (entry != NULL) {
4689 strcpy(entry->name, name);
4690 STAILQ_INSERT_TAIL(&obj->names, entry, link);
4695 object_match_name(const Obj_Entry *obj, const char *name)
4699 STAILQ_FOREACH(entry, &obj->names, link) {
4700 if (strcmp(name, entry->name) == 0)
4707 locate_dependency(const Obj_Entry *obj, const char *name)
4709 const Objlist_Entry *entry;
4710 const Needed_Entry *needed;
4712 STAILQ_FOREACH(entry, &list_main, link) {
4713 if (object_match_name(entry->obj, name))
4717 for (needed = obj->needed; needed != NULL; needed = needed->next) {
4718 if (strcmp(obj->strtab + needed->name, name) == 0 ||
4719 (needed->obj != NULL && object_match_name(needed->obj, name))) {
4721 * If there is DT_NEEDED for the name we are looking for,
4722 * we are all set. Note that object might not be found if
4723 * dependency was not loaded yet, so the function can
4724 * return NULL here. This is expected and handled
4725 * properly by the caller.
4727 return (needed->obj);
4730 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
4736 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
4737 const Elf_Vernaux *vna)
4739 const Elf_Verdef *vd;
4740 const char *vername;
4742 vername = refobj->strtab + vna->vna_name;
4743 vd = depobj->verdef;
4745 _rtld_error("%s: version %s required by %s not defined",
4746 depobj->path, vername, refobj->path);
4750 if (vd->vd_version != VER_DEF_CURRENT) {
4751 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
4752 depobj->path, vd->vd_version);
4755 if (vna->vna_hash == vd->vd_hash) {
4756 const Elf_Verdaux *aux = (const Elf_Verdaux *)
4757 ((char *)vd + vd->vd_aux);
4758 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
4761 if (vd->vd_next == 0)
4763 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4765 if (vna->vna_flags & VER_FLG_WEAK)
4767 _rtld_error("%s: version %s required by %s not found",
4768 depobj->path, vername, refobj->path);
4773 rtld_verify_object_versions(Obj_Entry *obj)
4775 const Elf_Verneed *vn;
4776 const Elf_Verdef *vd;
4777 const Elf_Verdaux *vda;
4778 const Elf_Vernaux *vna;
4779 const Obj_Entry *depobj;
4780 int maxvernum, vernum;
4782 if (obj->ver_checked)
4784 obj->ver_checked = true;
4788 * Walk over defined and required version records and figure out
4789 * max index used by any of them. Do very basic sanity checking
4793 while (vn != NULL) {
4794 if (vn->vn_version != VER_NEED_CURRENT) {
4795 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
4796 obj->path, vn->vn_version);
4799 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4801 vernum = VER_NEED_IDX(vna->vna_other);
4802 if (vernum > maxvernum)
4804 if (vna->vna_next == 0)
4806 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4808 if (vn->vn_next == 0)
4810 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4814 while (vd != NULL) {
4815 if (vd->vd_version != VER_DEF_CURRENT) {
4816 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
4817 obj->path, vd->vd_version);
4820 vernum = VER_DEF_IDX(vd->vd_ndx);
4821 if (vernum > maxvernum)
4823 if (vd->vd_next == 0)
4825 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4832 * Store version information in array indexable by version index.
4833 * Verify that object version requirements are satisfied along the
4836 obj->vernum = maxvernum + 1;
4837 obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry));
4840 while (vd != NULL) {
4841 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
4842 vernum = VER_DEF_IDX(vd->vd_ndx);
4843 assert(vernum <= maxvernum);
4844 vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
4845 obj->vertab[vernum].hash = vd->vd_hash;
4846 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
4847 obj->vertab[vernum].file = NULL;
4848 obj->vertab[vernum].flags = 0;
4850 if (vd->vd_next == 0)
4852 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4856 while (vn != NULL) {
4857 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
4860 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4862 if (check_object_provided_version(obj, depobj, vna))
4864 vernum = VER_NEED_IDX(vna->vna_other);
4865 assert(vernum <= maxvernum);
4866 obj->vertab[vernum].hash = vna->vna_hash;
4867 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
4868 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
4869 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
4870 VER_INFO_HIDDEN : 0;
4871 if (vna->vna_next == 0)
4873 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4875 if (vn->vn_next == 0)
4877 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4883 rtld_verify_versions(const Objlist *objlist)
4885 Objlist_Entry *entry;
4889 STAILQ_FOREACH(entry, objlist, link) {
4891 * Skip dummy objects or objects that have their version requirements
4894 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
4896 if (rtld_verify_object_versions(entry->obj) == -1) {
4898 if (ld_tracing == NULL)
4902 if (rc == 0 || ld_tracing != NULL)
4903 rc = rtld_verify_object_versions(&obj_rtld);
4908 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
4913 vernum = VER_NDX(obj->versyms[symnum]);
4914 if (vernum >= obj->vernum) {
4915 _rtld_error("%s: symbol %s has wrong verneed value %d",
4916 obj->path, obj->strtab + symnum, vernum);
4917 } else if (obj->vertab[vernum].hash != 0) {
4918 return &obj->vertab[vernum];
4925 _rtld_get_stack_prot(void)
4928 return (stack_prot);
4932 _rtld_is_dlopened(void *arg)
4935 RtldLockState lockstate;
4938 rlock_acquire(rtld_bind_lock, &lockstate);
4941 obj = obj_from_addr(arg);
4943 _rtld_error("No shared object contains address");
4944 lock_release(rtld_bind_lock, &lockstate);
4947 res = obj->dlopened ? 1 : 0;
4948 lock_release(rtld_bind_lock, &lockstate);
4953 map_stacks_exec(RtldLockState *lockstate)
4955 void (*thr_map_stacks_exec)(void);
4957 if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
4959 thr_map_stacks_exec = (void (*)(void))(uintptr_t)
4960 get_program_var_addr("__pthread_map_stacks_exec", lockstate);
4961 if (thr_map_stacks_exec != NULL) {
4962 stack_prot |= PROT_EXEC;
4963 thr_map_stacks_exec();
4968 symlook_init(SymLook *dst, const char *name)
4971 bzero(dst, sizeof(*dst));
4973 dst->hash = elf_hash(name);
4974 dst->hash_gnu = gnu_hash(name);
4978 symlook_init_from_req(SymLook *dst, const SymLook *src)
4981 dst->name = src->name;
4982 dst->hash = src->hash;
4983 dst->hash_gnu = src->hash_gnu;
4984 dst->ventry = src->ventry;
4985 dst->flags = src->flags;
4986 dst->defobj_out = NULL;
4987 dst->sym_out = NULL;
4988 dst->lockstate = src->lockstate;
4993 * Parse a file descriptor number without pulling in more of libc (e.g. atoi).
4996 parse_libdir(const char *str)
4998 static const int RADIX = 10; /* XXXJA: possibly support hex? */
5005 for (c = *str; c != '\0'; c = *++str) {
5006 if (c < '0' || c > '9')
5013 /* Make sure we actually parsed something. */
5015 _rtld_error("failed to parse directory FD from '%s'", str);
5022 * Overrides for libc_pic-provided functions.
5026 __getosreldate(void)
5036 oid[1] = KERN_OSRELDATE;
5038 len = sizeof(osrel);
5039 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
5040 if (error == 0 && osrel > 0 && len == sizeof(osrel))
5052 void (*__cleanup)(void);
5053 int __isthreaded = 0;
5054 int _thread_autoinit_dummy_decl = 1;
5057 * No unresolved symbols for rtld.
5060 __pthread_cxa_finalize(struct dl_phdr_info *a)
5065 __stack_chk_fail(void)
5068 _rtld_error("stack overflow detected; terminated");
5071 __weak_reference(__stack_chk_fail, __stack_chk_fail_local);
5077 _rtld_error("buffer overflow detected; terminated");
5082 rtld_strerror(int errnum)
5085 if (errnum < 0 || errnum >= sys_nerr)
5086 return ("Unknown error");
5087 return (sys_errlist[errnum]);