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>.
38 #error "GCC is needed to compile this file"
41 #include <sys/param.h>
42 #include <sys/mount.h>
45 #include <sys/sysctl.h>
47 #include <sys/utsname.h>
48 #include <sys/ktrace.h>
49 #include <sys/resident.h>
52 #include <machine/tls.h>
67 #include "rtld_printf.h"
70 #define PATH_RTLD "/usr/libexec/ld-elf.so.2"
71 #define LD_ARY_CACHE 16
74 typedef void (*func_ptr_type)();
75 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg);
78 * Function declarations.
80 static const char *_getenv_ld(const char *id);
81 static void die(void) __dead2;
82 static void digest_dynamic1(Obj_Entry *, int, const Elf_Dyn **,
83 const Elf_Dyn **, const Elf_Dyn **);
84 static void digest_dynamic2(Obj_Entry *, const Elf_Dyn *, const Elf_Dyn *,
86 static void digest_dynamic(Obj_Entry *, int);
87 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
88 static Obj_Entry *dlcheck(void *);
89 static Obj_Entry *dlopen_object(const char *name, int fd, Obj_Entry *refobj,
90 int lo_flags, int mode, RtldLockState *lockstate);
91 static Obj_Entry *do_load_object(int, const char *, char *, struct stat *, int);
92 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
93 static bool donelist_check(DoneList *, const Obj_Entry *);
94 static void errmsg_restore(char *);
95 static char *errmsg_save(void);
96 static void *fill_search_info(const char *, size_t, void *);
97 static char *find_library(const char *, const Obj_Entry *, int *);
98 static const char *gethints(bool);
99 static void init_dag(Obj_Entry *);
100 static void init_rtld(caddr_t, Elf_Auxinfo **);
101 static void initlist_add_neededs(Needed_Entry *, Objlist *);
102 static void initlist_add_objects(Obj_Entry *, Obj_Entry **, Objlist *);
103 static void linkmap_add(Obj_Entry *);
104 static void linkmap_delete(Obj_Entry *);
105 static void load_filtees(Obj_Entry *, int flags, RtldLockState *);
106 static void unload_filtees(Obj_Entry *);
107 static int load_needed_objects(Obj_Entry *, int);
108 static int load_preload_objects(void);
109 static Obj_Entry *load_object(const char *, int fd, const Obj_Entry *, int);
110 static void map_stacks_exec(RtldLockState *);
111 static Obj_Entry *obj_from_addr(const void *);
112 static void objlist_call_fini(Objlist *, Obj_Entry *, RtldLockState *);
113 static void objlist_call_init(Objlist *, RtldLockState *);
114 static void objlist_clear(Objlist *);
115 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
116 static void objlist_init(Objlist *);
117 static void objlist_push_head(Objlist *, Obj_Entry *);
118 static void objlist_push_tail(Objlist *, Obj_Entry *);
119 static void objlist_put_after(Objlist *, Obj_Entry *, Obj_Entry *);
120 static void objlist_remove(Objlist *, Obj_Entry *);
121 static int parse_libdir(const char *);
122 static void *path_enumerate(const char *, path_enum_proc, void *);
123 static int relocate_object_dag(Obj_Entry *root, bool bind_now,
124 Obj_Entry *rtldobj, int flags, RtldLockState *lockstate);
125 static int relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
126 int flags, RtldLockState *lockstate);
127 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, int,
129 static int resolve_objects_ifunc(Obj_Entry *first, bool bind_now,
130 int flags, RtldLockState *lockstate);
131 static int rtld_dirname(const char *, char *);
132 static int rtld_dirname_abs(const char *, char *);
133 static void *rtld_dlopen(const char *name, int fd, int mode);
134 static void rtld_exit(void);
135 static char *search_library_path(const char *, const char *);
136 static char *search_library_pathfds(const char *, const char *, int *);
137 static const void **get_program_var_addr(const char *, RtldLockState *);
138 static void set_program_var(const char *, const void *);
139 static int symlook_default(SymLook *, const Obj_Entry *refobj);
140 static int symlook_global(SymLook *, DoneList *);
141 static void symlook_init_from_req(SymLook *, const SymLook *);
142 static int symlook_list(SymLook *, const Objlist *, DoneList *);
143 static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *);
144 static int symlook_obj1_sysv(SymLook *, const Obj_Entry *);
145 static int symlook_obj1_gnu(SymLook *, const Obj_Entry *);
146 static void trace_loaded_objects(Obj_Entry *);
147 static void unlink_object(Obj_Entry *);
148 static void unload_object(Obj_Entry *);
149 static void unref_dag(Obj_Entry *);
150 static void ref_dag(Obj_Entry *);
151 static char *origin_subst_one(char *, const char *, const char *, bool);
152 static char *origin_subst(char *, const char *);
153 static void preinit_main(void);
154 static int rtld_verify_versions(const Objlist *);
155 static int rtld_verify_object_versions(Obj_Entry *);
156 static void object_add_name(Obj_Entry *, const char *);
157 static int object_match_name(const Obj_Entry *, const char *);
158 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
159 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
160 struct dl_phdr_info *phdr_info);
161 static uint_fast32_t gnu_hash (const char *);
162 static bool matched_symbol(SymLook *, const Obj_Entry *, Sym_Match_Result *,
163 const unsigned long);
165 void r_debug_state(struct r_debug *, struct link_map *) __noinline;
170 static char *error_message; /* Message for dlerror(), or NULL */
171 struct r_debug r_debug; /* for GDB; */
172 static bool libmap_disable; /* Disable libmap */
173 static bool ld_loadfltr; /* Immediate filters processing */
174 static char *libmap_override; /* Maps to use in addition to libmap.conf */
175 static bool trust; /* False for setuid and setgid programs */
176 static bool dangerous_ld_env; /* True if environment variables have been
177 used to affect the libraries loaded */
178 static const char *ld_bind_now; /* Environment variable for immediate binding */
179 static const char *ld_debug; /* Environment variable for debugging */
180 static const char *ld_library_path; /* Environment variable for search path */
181 static const char *ld_library_dirs; /* Env variable for library descriptors */
182 static char *ld_preload; /* Environment variable for libraries to
184 static const char *ld_elf_hints_path; /* Env var. for alternative hints path */
185 static const char *ld_tracing; /* Called from ldd to print libs */
186 static const char *ld_utrace; /* Use utrace() to log events. */
187 static int (*rtld_functrace)( /* Optional function call tracing hook */
188 const char *caller_obj,
189 const char *callee_obj,
190 const char *callee_func,
192 static const Obj_Entry *rtld_functrace_obj; /* Object thereof */
193 static Obj_Entry *obj_list; /* Head of linked list of shared objects */
194 static Obj_Entry **obj_tail; /* Link field of last object in list */
195 static Obj_Entry **preload_tail;
196 static Obj_Entry *obj_main; /* The main program shared object */
197 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
198 static unsigned int obj_count; /* Number of objects in obj_list */
199 static unsigned int obj_loads; /* Number of objects in obj_list */
201 static int ld_resident; /* Non-zero if resident */
202 static const char *ld_ary[LD_ARY_CACHE];
204 static Objlist initlist;
206 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
207 STAILQ_HEAD_INITIALIZER(list_global);
208 static Objlist list_main = /* Objects loaded at program startup */
209 STAILQ_HEAD_INITIALIZER(list_main);
210 static Objlist list_fini = /* Objects needing fini() calls */
211 STAILQ_HEAD_INITIALIZER(list_fini);
213 static Elf_Sym sym_zero; /* For resolving undefined weak refs. */
214 const char *__ld_sharedlib_base;
216 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
218 extern Elf_Dyn _DYNAMIC;
219 #pragma weak _DYNAMIC
220 #ifndef RTLD_IS_DYNAMIC
221 #define RTLD_IS_DYNAMIC() (&_DYNAMIC != NULL)
224 #ifdef ENABLE_OSRELDATE
228 static int stack_prot = PROT_READ | PROT_WRITE | RTLD_DEFAULT_STACK_EXEC;
230 static int max_stack_flags;
234 * Global declarations normally provided by crt1. The dynamic linker is
235 * not built with crt1, so we have to provide them ourselves.
241 * Used to pass argc, argv to init functions.
247 * Globals to control TLS allocation.
249 size_t tls_last_offset; /* Static TLS offset of last module */
250 size_t tls_last_size; /* Static TLS size of last module */
251 size_t tls_static_space; /* Static TLS space allocated */
252 int tls_dtv_generation = 1; /* Used to detect when dtv size changes */
253 int tls_max_index = 1; /* Largest module index allocated */
256 * Fill in a DoneList with an allocation large enough to hold all of
257 * the currently-loaded objects. Keep this as a macro since it calls
258 * alloca and we want that to occur within the scope of the caller.
260 #define donelist_init(dlp) \
261 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
262 assert((dlp)->objs != NULL), \
263 (dlp)->num_alloc = obj_count, \
266 #define UTRACE_DLOPEN_START 1
267 #define UTRACE_DLOPEN_STOP 2
268 #define UTRACE_DLCLOSE_START 3
269 #define UTRACE_DLCLOSE_STOP 4
270 #define UTRACE_LOAD_OBJECT 5
271 #define UTRACE_UNLOAD_OBJECT 6
272 #define UTRACE_ADD_RUNDEP 7
273 #define UTRACE_PRELOAD_FINISHED 8
274 #define UTRACE_INIT_CALL 9
275 #define UTRACE_FINI_CALL 10
278 char sig[4]; /* 'RTLD' */
281 void *mapbase; /* Used for 'parent' and 'init/fini' */
283 int refcnt; /* Used for 'mode' */
284 char name[MAXPATHLEN];
287 #define LD_UTRACE(e, h, mb, ms, r, n) do { \
288 if (ld_utrace != NULL) \
289 ld_utrace_log(e, h, mb, ms, r, n); \
293 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
294 int refcnt, const char *name)
296 struct utrace_rtld ut;
304 ut.mapbase = mapbase;
305 ut.mapsize = mapsize;
307 bzero(ut.name, sizeof(ut.name));
309 strlcpy(ut.name, name, sizeof(ut.name));
310 utrace(&ut, sizeof(ut));
314 * Main entry point for dynamic linking. The first argument is the
315 * stack pointer. The stack is expected to be laid out as described
316 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
317 * Specifically, the stack pointer points to a word containing
318 * ARGC. Following that in the stack is a null-terminated sequence
319 * of pointers to argument strings. Then comes a null-terminated
320 * sequence of pointers to environment strings. Finally, there is a
321 * sequence of "auxiliary vector" entries.
323 * The second argument points to a place to store the dynamic linker's
324 * exit procedure pointer and the third to a place to store the main
327 * The return value is the main program's entry point.
330 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
332 Elf_Auxinfo *aux_info[AT_COUNT];
340 Objlist_Entry *entry;
342 Obj_Entry *last_interposer;
344 /* marino: DO NOT MOVE THESE VARIABLES TO _rtld
345 Obj_Entry **preload_tail;
347 from global to here. It will break the DWARF2 unwind scheme.
351 * On entry, the dynamic linker itself has not been relocated yet.
352 * Be very careful not to reference any global data until after
353 * init_rtld has returned. It is OK to reference file-scope statics
354 * and string constants, and to call static and global functions.
357 /* Find the auxiliary vector on the stack. */
360 sp += argc + 1; /* Skip over arguments and NULL terminator */
364 * If we aren't already resident we have to dig out some more info.
365 * Note that auxinfo does not exist when we are resident.
367 * I'm not sure about the ld_resident check. It seems to read zero
368 * prior to relocation, which is what we want. When running from a
369 * resident copy everything will be relocated so we are definitely
372 if (ld_resident == 0) {
373 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
375 aux = (Elf_Auxinfo *) sp;
377 /* Digest the auxiliary vector. */
378 for (i = 0; i < AT_COUNT; i++)
380 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
381 if (auxp->a_type < AT_COUNT)
382 aux_info[auxp->a_type] = auxp;
385 /* Initialize and relocate ourselves. */
386 assert(aux_info[AT_BASE] != NULL);
387 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
390 ld_index = 0; /* don't use old env cache in case we are resident */
391 __progname = obj_rtld.path;
392 argv0 = argv[0] != NULL ? argv[0] : "(null)";
397 trust = !issetugid();
399 ld_bind_now = _getenv_ld("LD_BIND_NOW");
401 * If the process is tainted, then we un-set the dangerous environment
402 * variables. The process will be marked as tainted until setuid(2)
403 * is called. If any child process calls setuid(2) we do not want any
404 * future processes to honor the potentially un-safe variables.
407 if ( unsetenv("LD_DEBUG")
408 || unsetenv("LD_PRELOAD")
409 || unsetenv("LD_LIBRARY_PATH")
410 || unsetenv("LD_LIBRARY_PATH_FDS")
411 || unsetenv("LD_ELF_HINTS_PATH")
412 || unsetenv("LD_LIBMAP")
413 || unsetenv("LD_LIBMAP_DISABLE")
414 || unsetenv("LD_LOADFLTR")
415 || unsetenv("LD_SHAREDLIB_BASE")
417 _rtld_error("environment corrupt; aborting");
421 __ld_sharedlib_base = _getenv_ld("LD_SHAREDLIB_BASE");
422 ld_debug = _getenv_ld("LD_DEBUG");
423 libmap_disable = _getenv_ld("LD_LIBMAP_DISABLE") != NULL;
424 libmap_override = (char *)_getenv_ld("LD_LIBMAP");
425 ld_library_path = _getenv_ld("LD_LIBRARY_PATH");
426 ld_library_dirs = _getenv_ld("LD_LIBRARY_PATH_FDS");
427 ld_preload = (char *)_getenv_ld("LD_PRELOAD");
428 ld_elf_hints_path = _getenv_ld("LD_ELF_HINTS_PATH");
429 ld_loadfltr = _getenv_ld("LD_LOADFLTR") != NULL;
430 dangerous_ld_env = (ld_library_path != NULL)
431 || (ld_preload != NULL)
432 || (ld_elf_hints_path != NULL)
434 || (libmap_override != NULL)
437 ld_tracing = _getenv_ld("LD_TRACE_LOADED_OBJECTS");
438 ld_utrace = _getenv_ld("LD_UTRACE");
440 if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0)
441 ld_elf_hints_path = _PATH_ELF_HINTS;
443 if (ld_debug != NULL && *ld_debug != '\0')
445 dbg("%s is initialized, base address = %p", __progname,
446 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
447 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
448 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
450 dbg("initializing thread locks");
454 * If we are resident we can skip work that we have already done.
455 * Note that the stack is reset and there is no Elf_Auxinfo
456 * when running from a resident image, and the static globals setup
457 * between here and resident_skip will have already been setup.
463 * Load the main program, or process its program header if it is
466 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
467 int fd = aux_info[AT_EXECFD]->a_un.a_val;
468 dbg("loading main program");
469 obj_main = map_object(fd, argv0, NULL);
471 if (obj_main == NULL)
474 max_stack_flags = obj_main->stack_flags;
476 } else { /* Main program already loaded. */
477 const Elf_Phdr *phdr;
481 dbg("processing main program's program header");
482 assert(aux_info[AT_PHDR] != NULL);
483 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
484 assert(aux_info[AT_PHNUM] != NULL);
485 phnum = aux_info[AT_PHNUM]->a_un.a_val;
486 assert(aux_info[AT_PHENT] != NULL);
487 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
488 assert(aux_info[AT_ENTRY] != NULL);
489 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
490 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
494 char buf[MAXPATHLEN];
495 if (aux_info[AT_EXECPATH] != NULL) {
498 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
499 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
500 if (kexecpath[0] == '/')
501 obj_main->path = kexecpath;
502 else if (getcwd(buf, sizeof(buf)) == NULL ||
503 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
504 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
505 obj_main->path = xstrdup(argv0);
507 obj_main->path = xstrdup(buf);
509 char resolved[MAXPATHLEN];
510 dbg("No AT_EXECPATH");
511 if (argv0[0] == '/') {
512 if (realpath(argv0, resolved) != NULL)
513 obj_main->path = xstrdup(resolved);
515 obj_main->path = xstrdup(argv0);
517 if (getcwd(buf, sizeof(buf)) != NULL
518 && strlcat(buf, "/", sizeof(buf)) < sizeof(buf)
519 && strlcat(buf, argv0, sizeof (buf)) < sizeof(buf)
520 && access(buf, R_OK) == 0
521 && realpath(buf, resolved) != NULL)
522 obj_main->path = xstrdup(resolved);
524 obj_main->path = xstrdup(argv0);
527 dbg("obj_main path %s", obj_main->path);
528 obj_main->mainprog = true;
530 if (aux_info[AT_STACKPROT] != NULL &&
531 aux_info[AT_STACKPROT]->a_un.a_val != 0)
532 stack_prot = aux_info[AT_STACKPROT]->a_un.a_val;
535 * Get the actual dynamic linker pathname from the executable if
536 * possible. (It should always be possible.) That ensures that
537 * gdb will find the right dynamic linker even if a non-standard
540 if (obj_main->interp != NULL &&
541 strcmp(obj_main->interp, obj_rtld.path) != 0) {
543 obj_rtld.path = xstrdup(obj_main->interp);
544 __progname = obj_rtld.path;
547 digest_dynamic(obj_main, 0);
548 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d",
549 obj_main->path, obj_main->valid_hash_sysv, obj_main->valid_hash_gnu,
550 obj_main->dynsymcount);
552 linkmap_add(obj_main);
553 linkmap_add(&obj_rtld);
555 /* Link the main program into the list of objects. */
556 *obj_tail = obj_main;
557 obj_tail = &obj_main->next;
561 /* Initialize a fake symbol for resolving undefined weak references. */
562 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
563 sym_zero.st_shndx = SHN_UNDEF;
564 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
567 libmap_disable = (bool)lm_init(libmap_override);
569 dbg("loading LD_PRELOAD libraries");
570 if (load_preload_objects() == -1)
572 preload_tail = obj_tail;
574 dbg("loading needed objects");
575 if (load_needed_objects(obj_main, 0) == -1)
578 /* Make a list of all objects loaded at startup. */
579 last_interposer = obj_main;
580 for (obj = obj_list; obj != NULL; obj = obj->next) {
581 if (obj->z_interpose && obj != obj_main) {
582 objlist_put_after(&list_main, last_interposer, obj);
583 last_interposer = obj;
585 objlist_push_tail(&list_main, obj);
590 dbg("checking for required versions");
591 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
596 if (ld_tracing) { /* We're done */
597 trace_loaded_objects(obj_main);
601 if (ld_resident) /* XXX clean this up! */
604 if (_getenv_ld("LD_DUMP_REL_PRE") != NULL) {
605 dump_relocations(obj_main);
609 /* setup TLS for main thread */
610 dbg("initializing initial thread local storage");
611 STAILQ_FOREACH(entry, &list_main, link) {
613 * Allocate all the initial objects out of the static TLS
614 * block even if they didn't ask for it.
616 allocate_tls_offset(entry->obj);
619 tls_static_space = tls_last_offset + RTLD_STATIC_TLS_EXTRA;
622 * Do not try to allocate the TLS here, let libc do it itself.
623 * (crt1 for the program will call _init_tls())
626 if (relocate_objects(obj_main,
627 ld_bind_now != NULL && *ld_bind_now != '\0',
628 &obj_rtld, SYMLOOK_EARLY, NULL) == -1)
631 dbg("doing copy relocations");
632 if (do_copy_relocations(obj_main) == -1)
637 if (_getenv_ld("LD_RESIDENT_UNREGISTER_NOW")) {
638 if (exec_sys_unregister(-1) < 0) {
639 dbg("exec_sys_unregister failed %d\n", errno);
642 dbg("exec_sys_unregister success\n");
646 if (_getenv_ld("LD_DUMP_REL_POST") != NULL) {
647 dump_relocations(obj_main);
651 dbg("initializing key program variables");
652 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
653 set_program_var("environ", env);
654 set_program_var("__elf_aux_vector", aux);
656 if (_getenv_ld("LD_RESIDENT_REGISTER_NOW")) {
657 extern void resident_start(void);
659 if (exec_sys_register(resident_start) < 0) {
660 dbg("exec_sys_register failed %d\n", errno);
663 dbg("exec_sys_register success\n");
667 /* Make a list of init functions to call. */
668 objlist_init(&initlist);
669 initlist_add_objects(obj_list, preload_tail, &initlist);
671 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
673 map_stacks_exec(NULL);
675 dbg("resolving ifuncs");
676 if (resolve_objects_ifunc(obj_main,
677 ld_bind_now != NULL && *ld_bind_now != '\0', SYMLOOK_EARLY,
682 * Do NOT call the initlist here, give libc a chance to set up
683 * the initial TLS segment. crt1 will then call _rtld_call_init().
686 dbg("transferring control to program entry point = %p", obj_main->entry);
688 /* Return the exit procedure and the program entry point. */
689 *exit_proc = rtld_exit;
691 return (func_ptr_type) obj_main->entry;
695 * Call the initialization list for dynamically loaded libraries.
696 * (called from crt1.c).
699 _rtld_call_init(void)
701 RtldLockState lockstate;
704 if (!obj_main->note_present && obj_main->valid_hash_gnu) {
706 * The use of a linker script with a PHDRS directive that does not include
707 * PT_NOTE will block the crt_no_init note. In this case we'll look for the
708 * recently added GNU hash dynamic tag which gets built by default. It is
709 * extremely unlikely to find a pre-3.1 binary without a PT_NOTE header and
710 * a gnu hash tag. If gnu hash found, consider binary to use new crt code.
712 obj_main->crt_no_init = true;
713 dbg("Setting crt_no_init without presence of PT_NOTE header");
716 wlock_acquire(rtld_bind_lock, &lockstate);
717 if (obj_main->crt_no_init)
721 * Make sure we don't call the main program's init and fini functions
722 * for binaries linked with old crt1 which calls _init itself.
724 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
725 obj_main->init_array = obj_main->fini_array = (Elf_Addr)NULL;
727 objlist_call_init(&initlist, &lockstate);
728 objlist_clear(&initlist);
729 dbg("loading filtees");
730 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
731 if (ld_loadfltr || obj->z_loadfltr)
732 load_filtees(obj, 0, &lockstate);
734 lock_release(rtld_bind_lock, &lockstate);
738 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def)
743 ptr = (void *)make_function_pointer(def, obj);
744 target = ((Elf_Addr (*)(void))ptr)();
745 return ((void *)target);
749 _rtld_bind(Obj_Entry *obj, Elf_Size reloff, void *stack)
753 const Obj_Entry *defobj;
756 RtldLockState lockstate;
758 rlock_acquire(rtld_bind_lock, &lockstate);
759 if (sigsetjmp(lockstate.env, 0) != 0)
760 lock_upgrade(rtld_bind_lock, &lockstate);
762 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
764 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
766 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
767 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL,
771 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
772 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
774 target = (Elf_Addr)(defobj->relocbase + def->st_value);
776 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
777 defobj->strtab + def->st_name, basename(obj->path),
778 (void *)target, basename(defobj->path));
781 * If we have a function call tracing hook, and the
782 * hook would like to keep tracing this one function,
783 * prevent the relocation so we will wind up here
784 * the next time again.
786 * We don't want to functrace calls from the functracer
787 * to avoid recursive loops.
789 if (rtld_functrace != NULL && obj != rtld_functrace_obj) {
790 if (rtld_functrace(obj->path,
792 defobj->strtab + def->st_name,
794 lock_release(rtld_bind_lock, &lockstate);
800 * Write the new contents for the jmpslot. Note that depending on
801 * architecture, the value which we need to return back to the
802 * lazy binding trampoline may or may not be the target
803 * address. The value returned from reloc_jmpslot() is the value
804 * that the trampoline needs.
806 target = reloc_jmpslot(where, target, defobj, obj, rel);
807 lock_release(rtld_bind_lock, &lockstate);
812 * Error reporting function. Use it like printf. If formats the message
813 * into a buffer, and sets things up so that the next call to dlerror()
814 * will return the message.
817 _rtld_error(const char *fmt, ...)
819 static char buf[512];
823 rtld_vsnprintf(buf, sizeof buf, fmt, ap);
829 * Return a dynamically-allocated copy of the current error message, if any.
834 return error_message == NULL ? NULL : xstrdup(error_message);
838 * Restore the current error message from a copy which was previously saved
839 * by errmsg_save(). The copy is freed.
842 errmsg_restore(char *saved_msg)
844 if (saved_msg == NULL)
845 error_message = NULL;
847 _rtld_error("%s", saved_msg);
853 basename(const char *name)
855 const char *p = strrchr(name, '/');
856 return p != NULL ? p + 1 : name;
859 static struct utsname uts;
862 origin_subst_one(char *real, const char *kw, const char *subst,
865 char *p, *p1, *res, *resp;
866 int subst_len, kw_len, subst_count, old_len, new_len;
871 * First, count the number of the keyword occurences, to
872 * preallocate the final string.
874 for (p = real, subst_count = 0;; p = p1 + kw_len, subst_count++) {
881 * If the keyword is not found, just return.
883 if (subst_count == 0)
884 return (may_free ? real : xstrdup(real));
887 * There is indeed something to substitute. Calculate the
888 * length of the resulting string, and allocate it.
890 subst_len = strlen(subst);
891 old_len = strlen(real);
892 new_len = old_len + (subst_len - kw_len) * subst_count;
893 res = xmalloc(new_len + 1);
896 * Now, execute the substitution loop.
898 for (p = real, resp = res, *resp = '\0';;) {
901 /* Copy the prefix before keyword. */
902 memcpy(resp, p, p1 - p);
904 /* Keyword replacement. */
905 memcpy(resp, subst, subst_len);
913 /* Copy to the end of string and finish. */
921 origin_subst(char *real, const char *origin_path)
923 char *res1, *res2, *res3, *res4;
925 if (uts.sysname[0] == '\0') {
926 if (uname(&uts) != 0) {
927 _rtld_error("utsname failed: %d", errno);
931 res1 = origin_subst_one(real, "$ORIGIN", origin_path, false);
932 res2 = origin_subst_one(res1, "$OSNAME", uts.sysname, true);
933 res3 = origin_subst_one(res2, "$OSREL", uts.release, true);
934 res4 = origin_subst_one(res3, "$PLATFORM", uts.machine, true);
941 const char *msg = dlerror();
945 rtld_fdputstr(STDERR_FILENO, msg);
946 rtld_fdputchar(STDERR_FILENO, '\n');
951 * Process a shared object's DYNAMIC section, and save the important
952 * information in its Obj_Entry structure.
955 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
956 const Elf_Dyn **dyn_soname, const Elf_Dyn **dyn_runpath)
959 Needed_Entry **needed_tail = &obj->needed;
960 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
961 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
962 const Elf_Hashelt *hashtab;
963 const Elf32_Word *hashval;
964 Elf32_Word bkt, nmaskwords;
967 int plttype = DT_REL;
973 obj->bind_now = false;
974 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
975 switch (dynp->d_tag) {
978 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
982 obj->relsize = dynp->d_un.d_val;
986 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
990 obj->pltrel = (const Elf_Rel *)
991 (obj->relocbase + dynp->d_un.d_ptr);
995 obj->pltrelsize = dynp->d_un.d_val;
999 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
1003 obj->relasize = dynp->d_un.d_val;
1007 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
1011 plttype = dynp->d_un.d_val;
1012 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
1016 obj->symtab = (const Elf_Sym *)
1017 (obj->relocbase + dynp->d_un.d_ptr);
1021 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
1025 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
1029 obj->strsize = dynp->d_un.d_val;
1033 obj->verneed = (const Elf_Verneed *) (obj->relocbase +
1038 obj->verneednum = dynp->d_un.d_val;
1042 obj->verdef = (const Elf_Verdef *) (obj->relocbase +
1047 obj->verdefnum = dynp->d_un.d_val;
1051 obj->versyms = (const Elf_Versym *)(obj->relocbase +
1057 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1059 obj->nbuckets = hashtab[0];
1060 obj->nchains = hashtab[1];
1061 obj->buckets = hashtab + 2;
1062 obj->chains = obj->buckets + obj->nbuckets;
1063 obj->valid_hash_sysv = obj->nbuckets > 0 && obj->nchains > 0 &&
1064 obj->buckets != NULL;
1070 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1072 obj->nbuckets_gnu = hashtab[0];
1073 obj->symndx_gnu = hashtab[1];
1074 nmaskwords = hashtab[2];
1075 bloom_size32 = (__ELF_WORD_SIZE / 32) * nmaskwords;
1076 /* Number of bitmask words is required to be power of 2 */
1077 nmw_power2 = ((nmaskwords & (nmaskwords - 1)) == 0);
1078 obj->maskwords_bm_gnu = nmaskwords - 1;
1079 obj->shift2_gnu = hashtab[3];
1080 obj->bloom_gnu = (Elf_Addr *) (hashtab + 4);
1081 obj->buckets_gnu = hashtab + 4 + bloom_size32;
1082 obj->chain_zero_gnu = obj->buckets_gnu + obj->nbuckets_gnu -
1084 obj->valid_hash_gnu = nmw_power2 && obj->nbuckets_gnu > 0 &&
1085 obj->buckets_gnu != NULL;
1091 Needed_Entry *nep = NEW(Needed_Entry);
1092 nep->name = dynp->d_un.d_val;
1097 needed_tail = &nep->next;
1103 Needed_Entry *nep = NEW(Needed_Entry);
1104 nep->name = dynp->d_un.d_val;
1108 *needed_filtees_tail = nep;
1109 needed_filtees_tail = &nep->next;
1115 Needed_Entry *nep = NEW(Needed_Entry);
1116 nep->name = dynp->d_un.d_val;
1120 *needed_aux_filtees_tail = nep;
1121 needed_aux_filtees_tail = &nep->next;
1126 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
1130 obj->textrel = true;
1134 obj->symbolic = true;
1139 * We have to wait until later to process this, because we
1140 * might not have gotten the address of the string table yet.
1150 *dyn_runpath = dynp;
1154 obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1157 case DT_PREINIT_ARRAY:
1158 obj->preinit_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1161 case DT_PREINIT_ARRAYSZ:
1162 obj->preinit_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1166 obj->init_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1169 case DT_INIT_ARRAYSZ:
1170 obj->init_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1174 obj->fini = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1178 obj->fini_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1181 case DT_FINI_ARRAYSZ:
1182 obj->fini_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1186 /* XXX - not implemented yet */
1188 dbg("Filling in DT_DEBUG entry");
1189 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
1193 if ((dynp->d_un.d_val & DF_ORIGIN) && trust)
1194 obj->z_origin = true;
1195 if (dynp->d_un.d_val & DF_SYMBOLIC)
1196 obj->symbolic = true;
1197 if (dynp->d_un.d_val & DF_TEXTREL)
1198 obj->textrel = true;
1199 if (dynp->d_un.d_val & DF_BIND_NOW)
1200 obj->bind_now = true;
1201 /*if (dynp->d_un.d_val & DF_STATIC_TLS)
1206 if (dynp->d_un.d_val & DF_1_NOOPEN)
1207 obj->z_noopen = true;
1208 if ((dynp->d_un.d_val & DF_1_ORIGIN) && trust)
1209 obj->z_origin = true;
1210 /*if (dynp->d_un.d_val & DF_1_GLOBAL)
1212 if (dynp->d_un.d_val & DF_1_BIND_NOW)
1213 obj->bind_now = true;
1214 if (dynp->d_un.d_val & DF_1_NODELETE)
1215 obj->z_nodelete = true;
1216 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1217 obj->z_loadfltr = true;
1218 if (dynp->d_un.d_val & DF_1_INTERPOSE)
1219 obj->z_interpose = true;
1220 if (dynp->d_un.d_val & DF_1_NODEFLIB)
1221 obj->z_nodeflib = true;
1226 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1233 obj->traced = false;
1235 if (plttype == DT_RELA) {
1236 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1238 obj->pltrelasize = obj->pltrelsize;
1239 obj->pltrelsize = 0;
1242 /* Determine size of dynsym table (equal to nchains of sysv hash) */
1243 if (obj->valid_hash_sysv)
1244 obj->dynsymcount = obj->nchains;
1245 else if (obj->valid_hash_gnu) {
1246 obj->dynsymcount = 0;
1247 for (bkt = 0; bkt < obj->nbuckets_gnu; bkt++) {
1248 if (obj->buckets_gnu[bkt] == 0)
1250 hashval = &obj->chain_zero_gnu[obj->buckets_gnu[bkt]];
1253 while ((*hashval++ & 1u) == 0);
1255 obj->dynsymcount += obj->symndx_gnu;
1260 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1261 const Elf_Dyn *dyn_soname, const Elf_Dyn *dyn_runpath)
1264 if (obj->z_origin && obj->origin_path == NULL) {
1265 obj->origin_path = xmalloc(PATH_MAX);
1266 if (rtld_dirname_abs(obj->path, obj->origin_path) == -1)
1270 if (dyn_runpath != NULL) {
1271 obj->runpath = (char *)obj->strtab + dyn_runpath->d_un.d_val;
1273 obj->runpath = origin_subst(obj->runpath, obj->origin_path);
1275 else if (dyn_rpath != NULL) {
1276 obj->rpath = (char *)obj->strtab + dyn_rpath->d_un.d_val;
1278 obj->rpath = origin_subst(obj->rpath, obj->origin_path);
1281 if (dyn_soname != NULL)
1282 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1286 digest_dynamic(Obj_Entry *obj, int early)
1288 const Elf_Dyn *dyn_rpath;
1289 const Elf_Dyn *dyn_soname;
1290 const Elf_Dyn *dyn_runpath;
1292 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname, &dyn_runpath);
1293 digest_dynamic2(obj, dyn_rpath, dyn_soname, dyn_runpath);
1297 * Process a shared object's program header. This is used only for the
1298 * main program, when the kernel has already loaded the main program
1299 * into memory before calling the dynamic linker. It creates and
1300 * returns an Obj_Entry structure.
1303 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1306 const Elf_Phdr *phlimit = phdr + phnum;
1308 Elf_Addr note_start, note_end;
1312 for (ph = phdr; ph < phlimit; ph++) {
1313 if (ph->p_type != PT_PHDR)
1317 obj->phsize = ph->p_memsz;
1318 obj->relocbase = (caddr_t)phdr - ph->p_vaddr;
1322 obj->stack_flags = PF_X | PF_R | PF_W;
1324 for (ph = phdr; ph < phlimit; ph++) {
1325 switch (ph->p_type) {
1328 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1332 if (nsegs == 0) { /* First load segment */
1333 obj->vaddrbase = trunc_page(ph->p_vaddr);
1334 obj->mapbase = obj->vaddrbase + obj->relocbase;
1335 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
1337 } else { /* Last load segment */
1338 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1345 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1350 obj->tlssize = ph->p_memsz;
1351 obj->tlsalign = ph->p_align;
1352 obj->tlsinitsize = ph->p_filesz;
1353 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1357 obj->stack_flags = ph->p_flags;
1361 obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1362 obj->relro_size = round_page(ph->p_memsz);
1366 obj->note_present = true;
1367 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
1368 note_end = note_start + ph->p_filesz;
1369 digest_notes(obj, note_start, note_end);
1374 _rtld_error("%s: too few PT_LOAD segments", path);
1383 digest_notes(Obj_Entry *obj, Elf_Addr note_start, Elf_Addr note_end)
1385 const Elf_Note *note;
1386 const char *note_name;
1389 for (note = (const Elf_Note *)note_start; (Elf_Addr)note < note_end;
1390 note = (const Elf_Note *)((const char *)(note + 1) +
1391 roundup2(note->n_namesz, sizeof(Elf32_Addr)) +
1392 roundup2(note->n_descsz, sizeof(Elf32_Addr)))) {
1393 if (note->n_namesz != sizeof(NOTE_VENDOR) ||
1394 note->n_descsz != sizeof(int32_t))
1396 if (note->n_type != ABI_NOTETYPE &&
1397 note->n_type != CRT_NOINIT_NOTETYPE)
1399 note_name = (const char *)(note + 1);
1400 if (strncmp(NOTE_VENDOR, note_name, sizeof(NOTE_VENDOR)) != 0)
1402 switch (note->n_type) {
1404 /* DragonFly osrel note */
1405 p = (uintptr_t)(note + 1);
1406 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1407 obj->osrel = *(const int32_t *)(p);
1408 dbg("note osrel %d", obj->osrel);
1410 case CRT_NOINIT_NOTETYPE:
1411 /* DragonFly 'crt does not call init' note */
1412 obj->crt_no_init = true;
1413 dbg("note crt_no_init");
1420 dlcheck(void *handle)
1424 for (obj = obj_list; obj != NULL; obj = obj->next)
1425 if (obj == (Obj_Entry *) handle)
1428 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1429 _rtld_error("Invalid shared object handle %p", handle);
1436 * If the given object is already in the donelist, return true. Otherwise
1437 * add the object to the list and return false.
1440 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1444 for (i = 0; i < dlp->num_used; i++)
1445 if (dlp->objs[i] == obj)
1448 * Our donelist allocation should always be sufficient. But if
1449 * our threads locking isn't working properly, more shared objects
1450 * could have been loaded since we allocated the list. That should
1451 * never happen, but we'll handle it properly just in case it does.
1453 if (dlp->num_used < dlp->num_alloc)
1454 dlp->objs[dlp->num_used++] = obj;
1459 * Hash function for symbol table lookup. Don't even think about changing
1460 * this. It is specified by the System V ABI.
1463 elf_hash(const char *name)
1465 const unsigned char *p = (const unsigned char *) name;
1466 unsigned long h = 0;
1469 while (*p != '\0') {
1470 h = (h << 4) + *p++;
1471 if ((g = h & 0xf0000000) != 0)
1479 * The GNU hash function is the Daniel J. Bernstein hash clipped to 32 bits
1480 * unsigned in case it's implemented with a wider type.
1482 static uint_fast32_t
1483 gnu_hash(const char *s)
1489 for (c = *s; c != '\0'; c = *++s)
1491 return (h & 0xffffffff);
1496 * Find the library with the given name, and return its full pathname.
1497 * The returned string is dynamically allocated. Generates an error
1498 * message and returns NULL if the library cannot be found.
1500 * If the second argument is non-NULL, then it refers to an already-
1501 * loaded shared object, whose library search path will be searched.
1503 * If a library is successfully located via LD_LIBRARY_PATH_FDS, its
1504 * descriptor (which is close-on-exec) will be passed out via the third
1507 * The search order is:
1508 * DT_RPATH in the referencing file _unless_ DT_RUNPATH is present (1)
1509 * DT_RPATH of the main object if DSO without defined DT_RUNPATH (1)
1511 * DT_RUNPATH in the referencing file
1512 * ldconfig hints (if -z nodefaultlib, filter out default library directories
1514 * /lib:/usr/lib _unless_ the referencing file is linked with -z nodefaultlib
1516 * (1) Handled in digest_dynamic2 - rpath left NULL if runpath defined.
1519 find_library(const char *xname, const Obj_Entry *refobj, int *fdp)
1523 bool nodeflib, objgiven;
1525 objgiven = refobj != NULL;
1526 if (strchr(xname, '/') != NULL) { /* Hard coded pathname */
1527 if (xname[0] != '/' && !trust) {
1528 _rtld_error("Absolute pathname required for shared object \"%s\"",
1532 if (objgiven && refobj->z_origin) {
1533 return (origin_subst(__DECONST(char *, xname),
1534 refobj->origin_path));
1536 return (xstrdup(xname));
1540 if (libmap_disable || !objgiven ||
1541 (name = lm_find(refobj->path, xname)) == NULL)
1542 name = (char *)xname;
1544 dbg(" Searching for \"%s\"", name);
1546 nodeflib = objgiven ? refobj->z_nodeflib : false;
1548 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
1549 (objgiven && refobj->runpath == NULL && refobj != obj_main &&
1550 (pathname = search_library_path(name, obj_main->rpath)) != NULL) ||
1551 (pathname = search_library_path(name, ld_library_path)) != NULL ||
1553 (pathname = search_library_path(name, refobj->runpath)) != NULL) ||
1554 (pathname = search_library_pathfds(name, ld_library_dirs, fdp)) != NULL ||
1555 (pathname = search_library_path(name, gethints(nodeflib))) != NULL ||
1556 (objgiven && !nodeflib &&
1557 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL))
1560 if (objgiven && refobj->path != NULL) {
1561 _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
1562 name, basename(refobj->path));
1564 _rtld_error("Shared object \"%s\" not found", name);
1570 * Given a symbol number in a referencing object, find the corresponding
1571 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1572 * no definition was found. Returns a pointer to the Obj_Entry of the
1573 * defining object via the reference parameter DEFOBJ_OUT.
1576 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1577 const Obj_Entry **defobj_out, int flags, SymCache *cache,
1578 RtldLockState *lockstate)
1582 const Obj_Entry *defobj;
1588 * If we have already found this symbol, get the information from
1591 if (symnum >= refobj->dynsymcount)
1592 return NULL; /* Bad object */
1593 if (cache != NULL && cache[symnum].sym != NULL) {
1594 *defobj_out = cache[symnum].obj;
1595 return cache[symnum].sym;
1598 ref = refobj->symtab + symnum;
1599 name = refobj->strtab + ref->st_name;
1604 * We don't have to do a full scale lookup if the symbol is local.
1605 * We know it will bind to the instance in this load module; to
1606 * which we already have a pointer (ie ref). By not doing a lookup,
1607 * we not only improve performance, but it also avoids unresolvable
1608 * symbols when local symbols are not in the hash table.
1610 * This might occur for TLS module relocations, which simply use
1613 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1614 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1615 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1618 symlook_init(&req, name);
1620 req.ventry = fetch_ventry(refobj, symnum);
1621 req.lockstate = lockstate;
1622 res = symlook_default(&req, refobj);
1625 defobj = req.defobj_out;
1633 * If we found no definition and the reference is weak, treat the
1634 * symbol as having the value zero.
1636 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1642 *defobj_out = defobj;
1643 /* Record the information in the cache to avoid subsequent lookups. */
1644 if (cache != NULL) {
1645 cache[symnum].sym = def;
1646 cache[symnum].obj = defobj;
1649 if (refobj != &obj_rtld)
1650 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1656 * Return the search path from the ldconfig hints file, reading it if
1657 * necessary. If nostdlib is true, then the default search paths are
1658 * not added to result.
1660 * Returns NULL if there are problems with the hints file,
1661 * or if the search path there is empty.
1664 gethints(bool nostdlib)
1666 static char *hints, *filtered_path;
1667 struct elfhints_hdr hdr;
1668 struct fill_search_info_args sargs, hargs;
1669 struct dl_serinfo smeta, hmeta, *SLPinfo, *hintinfo;
1670 struct dl_serpath *SLPpath, *hintpath;
1672 unsigned int SLPndx, hintndx, fndx, fcount;
1677 /* First call, read the hints file */
1678 if (hints == NULL) {
1679 /* Keep from trying again in case the hints file is bad. */
1682 if ((fd = open(ld_elf_hints_path, O_RDONLY | O_CLOEXEC)) == -1)
1684 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1685 hdr.magic != ELFHINTS_MAGIC ||
1690 p = xmalloc(hdr.dirlistlen + 1);
1691 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1692 read(fd, p, hdr.dirlistlen + 1) !=
1693 (ssize_t)hdr.dirlistlen + 1) {
1703 * If caller agreed to receive list which includes the default
1704 * paths, we are done. Otherwise, if we still have not
1705 * calculated filtered result, do it now.
1708 return (hints[0] != '\0' ? hints : NULL);
1709 if (filtered_path != NULL)
1713 * Obtain the list of all configured search paths, and the
1714 * list of the default paths.
1716 * First estimate the size of the results.
1718 smeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1720 hmeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1723 sargs.request = RTLD_DI_SERINFOSIZE;
1724 sargs.serinfo = &smeta;
1725 hargs.request = RTLD_DI_SERINFOSIZE;
1726 hargs.serinfo = &hmeta;
1728 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &sargs);
1729 path_enumerate(p, fill_search_info, &hargs);
1731 SLPinfo = xmalloc(smeta.dls_size);
1732 hintinfo = xmalloc(hmeta.dls_size);
1735 * Next fetch both sets of paths.
1737 sargs.request = RTLD_DI_SERINFO;
1738 sargs.serinfo = SLPinfo;
1739 sargs.serpath = &SLPinfo->dls_serpath[0];
1740 sargs.strspace = (char *)&SLPinfo->dls_serpath[smeta.dls_cnt];
1742 hargs.request = RTLD_DI_SERINFO;
1743 hargs.serinfo = hintinfo;
1744 hargs.serpath = &hintinfo->dls_serpath[0];
1745 hargs.strspace = (char *)&hintinfo->dls_serpath[hmeta.dls_cnt];
1747 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &sargs);
1748 path_enumerate(p, fill_search_info, &hargs);
1751 * Now calculate the difference between two sets, by excluding
1752 * standard paths from the full set.
1756 filtered_path = xmalloc(hdr.dirlistlen + 1);
1757 hintpath = &hintinfo->dls_serpath[0];
1758 for (hintndx = 0; hintndx < hmeta.dls_cnt; hintndx++, hintpath++) {
1760 SLPpath = &SLPinfo->dls_serpath[0];
1762 * Check each standard path against current.
1764 for (SLPndx = 0; SLPndx < smeta.dls_cnt; SLPndx++, SLPpath++) {
1765 /* matched, skip the path */
1766 if (!strcmp(hintpath->dls_name, SLPpath->dls_name)) {
1774 * Not matched against any standard path, add the path
1775 * to result. Separate consecutive paths with ':'.
1778 filtered_path[fndx] = ':';
1782 flen = strlen(hintpath->dls_name);
1783 strncpy((filtered_path + fndx), hintpath->dls_name, flen);
1786 filtered_path[fndx] = '\0';
1792 return (filtered_path[0] != '\0' ? filtered_path : NULL);
1796 init_dag(Obj_Entry *root)
1798 const Needed_Entry *needed;
1799 const Objlist_Entry *elm;
1802 if (root->dag_inited)
1804 donelist_init(&donelist);
1806 /* Root object belongs to own DAG. */
1807 objlist_push_tail(&root->dldags, root);
1808 objlist_push_tail(&root->dagmembers, root);
1809 donelist_check(&donelist, root);
1812 * Add dependencies of root object to DAG in breadth order
1813 * by exploiting the fact that each new object get added
1814 * to the tail of the dagmembers list.
1816 STAILQ_FOREACH(elm, &root->dagmembers, link) {
1817 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
1818 if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
1820 objlist_push_tail(&needed->obj->dldags, root);
1821 objlist_push_tail(&root->dagmembers, needed->obj);
1824 root->dag_inited = true;
1828 process_nodelete(Obj_Entry *root)
1830 const Objlist_Entry *elm;
1833 * Walk over object DAG and process every dependent object that
1834 * is marked as DF_1_NODELETE. They need to grow their own DAG,
1835 * which then should have its reference upped separately.
1837 STAILQ_FOREACH(elm, &root->dagmembers, link) {
1838 if (elm->obj != NULL && elm->obj->z_nodelete &&
1839 !elm->obj->ref_nodel) {
1840 dbg("obj %s nodelete", elm->obj->path);
1843 elm->obj->ref_nodel = true;
1849 * Initialize the dynamic linker. The argument is the address at which
1850 * the dynamic linker has been mapped into memory. The primary task of
1851 * this function is to relocate the dynamic linker.
1854 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
1856 Obj_Entry objtmp; /* Temporary rtld object */
1857 const Elf_Dyn *dyn_rpath;
1858 const Elf_Dyn *dyn_soname;
1859 const Elf_Dyn *dyn_runpath;
1862 * Conjure up an Obj_Entry structure for the dynamic linker.
1864 * The "path" member can't be initialized yet because string constants
1865 * cannot yet be accessed. Below we will set it correctly.
1867 memset(&objtmp, 0, sizeof(objtmp));
1870 objtmp.mapbase = mapbase;
1872 objtmp.relocbase = mapbase;
1874 if (RTLD_IS_DYNAMIC()) {
1875 objtmp.dynamic = rtld_dynamic(&objtmp);
1876 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname, &dyn_runpath);
1877 assert(objtmp.needed == NULL);
1878 assert(!objtmp.textrel);
1881 * Temporarily put the dynamic linker entry into the object list, so
1882 * that symbols can be found.
1885 relocate_objects(&objtmp, true, &objtmp, 0, NULL);
1888 /* Initialize the object list. */
1889 obj_tail = &obj_list;
1891 /* Now that non-local variables can be accesses, copy out obj_rtld. */
1892 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1894 #ifdef ENABLE_OSRELDATE
1895 if (aux_info[AT_OSRELDATE] != NULL)
1896 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
1899 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname, dyn_runpath);
1901 /* Replace the path with a dynamically allocated copy. */
1902 obj_rtld.path = xstrdup(PATH_RTLD);
1904 r_debug.r_brk = r_debug_state;
1905 r_debug.r_state = RT_CONSISTENT;
1909 * Add the init functions from a needed object list (and its recursive
1910 * needed objects) to "list". This is not used directly; it is a helper
1911 * function for initlist_add_objects(). The write lock must be held
1912 * when this function is called.
1915 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1917 /* Recursively process the successor needed objects. */
1918 if (needed->next != NULL)
1919 initlist_add_neededs(needed->next, list);
1921 /* Process the current needed object. */
1922 if (needed->obj != NULL)
1923 initlist_add_objects(needed->obj, &needed->obj->next, list);
1927 * Scan all of the DAGs rooted in the range of objects from "obj" to
1928 * "tail" and add their init functions to "list". This recurses over
1929 * the DAGs and ensure the proper init ordering such that each object's
1930 * needed libraries are initialized before the object itself. At the
1931 * same time, this function adds the objects to the global finalization
1932 * list "list_fini" in the opposite order. The write lock must be
1933 * held when this function is called.
1936 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1939 if (obj->init_scanned || obj->init_done)
1941 obj->init_scanned = true;
1943 /* Recursively process the successor objects. */
1944 if (&obj->next != tail)
1945 initlist_add_objects(obj->next, tail, list);
1947 /* Recursively process the needed objects. */
1948 if (obj->needed != NULL)
1949 initlist_add_neededs(obj->needed, list);
1950 if (obj->needed_filtees != NULL)
1951 initlist_add_neededs(obj->needed_filtees, list);
1952 if (obj->needed_aux_filtees != NULL)
1953 initlist_add_neededs(obj->needed_aux_filtees, list);
1955 /* Add the object to the init list. */
1956 if (obj->preinit_array != (Elf_Addr)NULL || obj->init != (Elf_Addr)NULL ||
1957 obj->init_array != (Elf_Addr)NULL)
1958 objlist_push_tail(list, obj);
1960 /* Add the object to the global fini list in the reverse order. */
1961 if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL)
1962 && !obj->on_fini_list) {
1963 objlist_push_head(&list_fini, obj);
1964 obj->on_fini_list = true;
1969 #define FPTR_TARGET(f) ((Elf_Addr) (f))
1973 free_needed_filtees(Needed_Entry *n)
1975 Needed_Entry *needed, *needed1;
1977 for (needed = n; needed != NULL; needed = needed->next) {
1978 if (needed->obj != NULL) {
1979 dlclose(needed->obj);
1983 for (needed = n; needed != NULL; needed = needed1) {
1984 needed1 = needed->next;
1990 unload_filtees(Obj_Entry *obj)
1993 free_needed_filtees(obj->needed_filtees);
1994 obj->needed_filtees = NULL;
1995 free_needed_filtees(obj->needed_aux_filtees);
1996 obj->needed_aux_filtees = NULL;
1997 obj->filtees_loaded = false;
2001 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags,
2002 RtldLockState *lockstate)
2005 for (; needed != NULL; needed = needed->next) {
2006 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
2007 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
2008 RTLD_LOCAL, lockstate);
2013 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
2016 lock_restart_for_upgrade(lockstate);
2017 if (!obj->filtees_loaded) {
2018 load_filtee1(obj, obj->needed_filtees, flags, lockstate);
2019 load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate);
2020 obj->filtees_loaded = true;
2025 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
2029 for (; needed != NULL; needed = needed->next) {
2030 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
2031 flags & ~RTLD_LO_NOLOAD);
2032 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
2039 * Given a shared object, traverse its list of needed objects, and load
2040 * each of them. Returns 0 on success. Generates an error message and
2041 * returns -1 on failure.
2044 load_needed_objects(Obj_Entry *first, int flags)
2048 for (obj = first; obj != NULL; obj = obj->next) {
2049 if (process_needed(obj, obj->needed, flags) == -1)
2056 load_preload_objects(void)
2058 char *p = ld_preload;
2060 static const char delim[] = " \t:;";
2065 p += strspn(p, delim);
2066 while (*p != '\0') {
2067 size_t len = strcspn(p, delim);
2074 obj = load_object(p, -1, NULL, 0);
2076 return -1; /* XXX - cleanup */
2077 obj->z_interpose = true;
2080 p += strspn(p, delim);
2082 /* Check for the magic tracing function */
2083 symlook_init(&req, RTLD_FUNCTRACE);
2084 res = symlook_obj(&req, obj);
2086 rtld_functrace = (void *)(req.defobj_out->relocbase +
2087 req.sym_out->st_value);
2088 rtld_functrace_obj = req.defobj_out;
2091 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
2096 printable_path(const char *path)
2099 return (path == NULL ? "<unknown>" : path);
2103 * Load a shared object into memory, if it is not already loaded. The
2104 * object may be specified by name or by user-supplied file descriptor
2105 * fd_u. In the later case, the fd_u descriptor is not closed, but its
2108 * Returns a pointer to the Obj_Entry for the object. Returns NULL
2112 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
2121 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
2122 if (object_match_name(obj, name))
2126 path = find_library(name, refobj, &fd);
2134 * search_library_pathfds() opens a fresh file descriptor for the
2135 * library, so there is no need to dup().
2137 } else if (fd_u == -1) {
2139 * If we didn't find a match by pathname, or the name is not
2140 * supplied, open the file and check again by device and inode.
2141 * This avoids false mismatches caused by multiple links or ".."
2144 * To avoid a race, we open the file and use fstat() rather than
2147 if ((fd = open(path, O_RDONLY | O_CLOEXEC)) == -1) {
2148 _rtld_error("Cannot open \"%s\"", path);
2153 fd = fcntl(fd_u, F_DUPFD_CLOEXEC, 0);
2155 _rtld_error("Cannot dup fd");
2160 if (fstat(fd, &sb) == -1) {
2161 _rtld_error("Cannot fstat \"%s\"", printable_path(path));
2166 for (obj = obj_list->next; obj != NULL; obj = obj->next)
2167 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
2169 if (obj != NULL && name != NULL) {
2170 object_add_name(obj, name);
2175 if (flags & RTLD_LO_NOLOAD) {
2181 /* First use of this object, so we must map it in */
2182 obj = do_load_object(fd, name, path, &sb, flags);
2191 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
2198 * but first, make sure that environment variables haven't been
2199 * used to circumvent the noexec flag on a filesystem.
2201 if (dangerous_ld_env) {
2202 if (fstatfs(fd, &fs) != 0) {
2203 _rtld_error("Cannot fstatfs \"%s\"", printable_path(path));
2206 if (fs.f_flags & MNT_NOEXEC) {
2207 _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
2211 dbg("loading \"%s\"", printable_path(path));
2212 obj = map_object(fd, printable_path(path), sbp);
2217 * If DT_SONAME is present in the object, digest_dynamic2 already
2218 * added it to the object names.
2221 object_add_name(obj, name);
2223 digest_dynamic(obj, 0);
2224 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path,
2225 obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount);
2226 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
2228 dbg("refusing to load non-loadable \"%s\"", obj->path);
2229 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
2230 munmap(obj->mapbase, obj->mapsize);
2236 obj_tail = &obj->next;
2239 linkmap_add(obj); /* for GDB & dlinfo() */
2241 max_stack_flags |= obj->stack_flags;
2244 dbg(" %p .. %p: %s", obj->mapbase,
2245 obj->mapbase + obj->mapsize - 1, obj->path);
2247 dbg(" WARNING: %s has impure text", obj->path);
2248 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
2255 obj_from_addr(const void *addr)
2259 for (obj = obj_list; obj != NULL; obj = obj->next) {
2260 if (addr < (void *) obj->mapbase)
2262 if (addr < (void *) (obj->mapbase + obj->mapsize))
2269 * If the main program is defined with a .preinit_array section, call
2270 * each function in order. This must occur before the initialization
2271 * of any shared object or the main program.
2276 Elf_Addr *preinit_addr;
2279 preinit_addr = (Elf_Addr *)obj_main->preinit_array;
2280 if (preinit_addr == NULL)
2283 for (index = 0; index < obj_main->preinit_array_num; index++) {
2284 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) {
2285 dbg("calling preinit function for %s at %p", obj_main->path,
2286 (void *)preinit_addr[index]);
2287 LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index],
2288 0, 0, obj_main->path);
2289 call_init_pointer(obj_main, preinit_addr[index]);
2295 * Call the finalization functions for each of the objects in "list"
2296 * belonging to the DAG of "root" and referenced once. If NULL "root"
2297 * is specified, every finalization function will be called regardless
2298 * of the reference count and the list elements won't be freed. All of
2299 * the objects are expected to have non-NULL fini functions.
2302 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
2306 Elf_Addr *fini_addr;
2309 assert(root == NULL || root->refcount == 1);
2312 * Preserve the current error message since a fini function might
2313 * call into the dynamic linker and overwrite it.
2315 saved_msg = errmsg_save();
2317 STAILQ_FOREACH(elm, list, link) {
2318 if (root != NULL && (elm->obj->refcount != 1 ||
2319 objlist_find(&root->dagmembers, elm->obj) == NULL))
2322 /* Remove object from fini list to prevent recursive invocation. */
2323 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2325 * XXX: If a dlopen() call references an object while the
2326 * fini function is in progress, we might end up trying to
2327 * unload the referenced object in dlclose() or the object
2328 * won't be unloaded although its fini function has been
2331 lock_release(rtld_bind_lock, lockstate);
2334 * It is legal to have both DT_FINI and DT_FINI_ARRAY defined.
2335 * When this happens, DT_FINI_ARRAY is processed first.
2336 * It is also processed backwards. It is possible to encounter
2337 * DT_FINI_ARRAY elements with values of 0 or 1, but they need
2340 fini_addr = (Elf_Addr *)elm->obj->fini_array;
2341 if (fini_addr != NULL && elm->obj->fini_array_num > 0) {
2342 for (index = elm->obj->fini_array_num - 1; index >= 0; index--) {
2343 if (fini_addr[index] != 0 && fini_addr[index] != 1) {
2344 dbg("calling fini array function for %s at %p",
2345 elm->obj->path, (void *)fini_addr[index]);
2346 LD_UTRACE(UTRACE_FINI_CALL, elm->obj,
2347 (void *)fini_addr[index], 0, 0, elm->obj->path);
2348 call_initfini_pointer(elm->obj, fini_addr[index]);
2352 if (elm->obj->fini != (Elf_Addr)NULL) {
2353 dbg("calling fini function for %s at %p", elm->obj->path,
2354 (void *)elm->obj->fini);
2355 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini,
2356 0, 0, elm->obj->path);
2357 call_initfini_pointer(elm->obj, elm->obj->fini);
2359 wlock_acquire(rtld_bind_lock, lockstate);
2360 /* No need to free anything if process is going down. */
2364 * We must restart the list traversal after every fini call
2365 * because a dlclose() call from the fini function or from
2366 * another thread might have modified the reference counts.
2370 } while (elm != NULL);
2371 errmsg_restore(saved_msg);
2375 * Call the initialization functions for each of the objects in
2376 * "list". All of the objects are expected to have non-NULL init
2380 objlist_call_init(Objlist *list, RtldLockState *lockstate)
2385 Elf_Addr *init_addr;
2389 * Clean init_scanned flag so that objects can be rechecked and
2390 * possibly initialized earlier if any of vectors called below
2391 * cause the change by using dlopen.
2393 for (obj = obj_list; obj != NULL; obj = obj->next)
2394 obj->init_scanned = false;
2397 * Preserve the current error message since an init function might
2398 * call into the dynamic linker and overwrite it.
2400 saved_msg = errmsg_save();
2401 STAILQ_FOREACH(elm, list, link) {
2402 if (elm->obj->init_done) /* Initialized early. */
2406 * Race: other thread might try to use this object before current
2407 * one completes the initilization. Not much can be done here
2408 * without better locking.
2410 elm->obj->init_done = true;
2411 lock_release(rtld_bind_lock, lockstate);
2414 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined.
2415 * When this happens, DT_INIT is processed first.
2416 * It is possible to encounter DT_INIT_ARRAY elements with values
2417 * of 0 or 1, but they need to be ignored.
2419 if (elm->obj->init != (Elf_Addr)NULL) {
2420 dbg("calling init function for %s at %p", elm->obj->path,
2421 (void *)elm->obj->init);
2422 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init,
2423 0, 0, elm->obj->path);
2424 call_initfini_pointer(elm->obj, elm->obj->init);
2426 init_addr = (Elf_Addr *)elm->obj->init_array;
2427 if (init_addr != NULL) {
2428 for (index = 0; index < elm->obj->init_array_num; index++) {
2429 if (init_addr[index] != 0 && init_addr[index] != 1) {
2430 dbg("calling init array function for %s at %p", elm->obj->path,
2431 (void *)init_addr[index]);
2432 LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
2433 (void *)init_addr[index], 0, 0, elm->obj->path);
2434 call_init_pointer(elm->obj, init_addr[index]);
2438 wlock_acquire(rtld_bind_lock, lockstate);
2440 errmsg_restore(saved_msg);
2444 objlist_clear(Objlist *list)
2448 while (!STAILQ_EMPTY(list)) {
2449 elm = STAILQ_FIRST(list);
2450 STAILQ_REMOVE_HEAD(list, link);
2455 static Objlist_Entry *
2456 objlist_find(Objlist *list, const Obj_Entry *obj)
2460 STAILQ_FOREACH(elm, list, link)
2461 if (elm->obj == obj)
2467 objlist_init(Objlist *list)
2473 objlist_push_head(Objlist *list, Obj_Entry *obj)
2477 elm = NEW(Objlist_Entry);
2479 STAILQ_INSERT_HEAD(list, elm, link);
2483 objlist_push_tail(Objlist *list, Obj_Entry *obj)
2487 elm = NEW(Objlist_Entry);
2489 STAILQ_INSERT_TAIL(list, elm, link);
2493 objlist_put_after(Objlist *list, Obj_Entry *listobj, Obj_Entry *obj)
2495 Objlist_Entry *elm, *listelm;
2497 STAILQ_FOREACH(listelm, list, link) {
2498 if (listelm->obj == listobj)
2501 elm = NEW(Objlist_Entry);
2503 if (listelm != NULL)
2504 STAILQ_INSERT_AFTER(list, listelm, elm, link);
2506 STAILQ_INSERT_TAIL(list, elm, link);
2510 objlist_remove(Objlist *list, Obj_Entry *obj)
2514 if ((elm = objlist_find(list, obj)) != NULL) {
2515 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2521 * Relocate dag rooted in the specified object.
2522 * Returns 0 on success, or -1 on failure.
2526 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj,
2527 int flags, RtldLockState *lockstate)
2533 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2534 error = relocate_object(elm->obj, bind_now, rtldobj, flags,
2543 * Relocate single object.
2544 * Returns 0 on success, or -1 on failure.
2547 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
2548 int flags, RtldLockState *lockstate)
2553 obj->relocated = true;
2555 dbg("relocating \"%s\"", obj->path);
2557 if (obj->symtab == NULL || obj->strtab == NULL ||
2558 !(obj->valid_hash_sysv || obj->valid_hash_gnu)) {
2559 _rtld_error("%s: Shared object has no run-time symbol table",
2565 /* There are relocations to the write-protected text segment. */
2566 if (mprotect(obj->mapbase, obj->textsize,
2567 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
2568 _rtld_error("%s: Cannot write-enable text segment: %s",
2569 obj->path, rtld_strerror(errno));
2574 /* Process the non-PLT relocations. */
2575 if (reloc_non_plt(obj, rtldobj, flags, lockstate))
2579 * Reprotect the text segment. Make sure it is included in the
2580 * core dump since we modified it. This unfortunately causes the
2581 * entire text segment to core-out but we don't have much of a
2582 * choice. We could try to only reenable core dumps on pages
2583 * in which relocations occured but that is likely most of the text
2584 * pages anyway, and even that would not work because the rest of
2585 * the text pages would wind up as a read-only OBJT_DEFAULT object
2586 * (created due to our modifications) backed by the original OBJT_VNODE
2587 * object, and the ELF coredump code is currently only able to dump
2588 * vnode records for pure vnode-backed mappings, not vnode backings
2589 * to memory objects.
2592 madvise(obj->mapbase, obj->textsize, MADV_CORE);
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 * Set up the magic number and version in the Obj_Entry. These
2614 * were checked in the crt1.o from the original ElfKit, so we
2615 * set them for backward compatibility.
2617 obj->magic = RTLD_MAGIC;
2618 obj->version = RTLD_VERSION;
2621 * Set relocated data to read-only status if protection specified
2624 if (obj->relro_size) {
2625 if (mprotect(obj->relro_page, obj->relro_size, PROT_READ) == -1) {
2626 _rtld_error("%s: Cannot enforce relro relocation: %s",
2627 obj->path, rtld_strerror(errno));
2635 * Relocate newly-loaded shared objects. The argument is a pointer to
2636 * the Obj_Entry for the first such object. All objects from the first
2637 * to the end of the list of objects are relocated. Returns 0 on success,
2641 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
2642 int flags, RtldLockState *lockstate)
2647 for (error = 0, obj = first; obj != NULL; obj = obj->next) {
2648 error = relocate_object(obj, bind_now, rtldobj, flags,
2657 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
2658 * referencing STT_GNU_IFUNC symbols is postponed till the other
2659 * relocations are done. The indirect functions specified as
2660 * ifunc are allowed to call other symbols, so we need to have
2661 * objects relocated before asking for resolution from indirects.
2663 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
2664 * instead of the usual lazy handling of PLT slots. It is
2665 * consistent with how GNU does it.
2668 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags,
2669 RtldLockState *lockstate)
2671 if (obj->irelative && reloc_iresolve(obj, lockstate) == -1)
2673 if ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
2674 reloc_gnu_ifunc(obj, flags, lockstate) == -1)
2680 resolve_objects_ifunc(Obj_Entry *first, bool bind_now, int flags,
2681 RtldLockState *lockstate)
2685 for (obj = first; obj != NULL; obj = obj->next) {
2686 if (resolve_object_ifunc(obj, bind_now, flags, lockstate) == -1)
2693 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags,
2694 RtldLockState *lockstate)
2698 STAILQ_FOREACH(elm, list, link) {
2699 if (resolve_object_ifunc(elm->obj, bind_now, flags,
2707 * Cleanup procedure. It will be called (by the atexit mechanism) just
2708 * before the process exits.
2713 RtldLockState lockstate;
2715 wlock_acquire(rtld_bind_lock, &lockstate);
2717 objlist_call_fini(&list_fini, NULL, &lockstate);
2718 /* No need to remove the items from the list, since we are exiting. */
2719 if (!libmap_disable)
2721 lock_release(rtld_bind_lock, &lockstate);
2725 * Iterate over a search path, translate each element, and invoke the
2726 * callback on the result.
2729 path_enumerate(const char *path, path_enum_proc callback, void *arg)
2735 path += strspn(path, ":;");
2736 while (*path != '\0') {
2740 len = strcspn(path, ":;");
2741 trans = lm_findn(NULL, path, len);
2743 res = callback(trans, strlen(trans), arg);
2745 res = callback(path, len, arg);
2751 path += strspn(path, ":;");
2757 struct try_library_args {
2765 try_library_path(const char *dir, size_t dirlen, void *param)
2767 struct try_library_args *arg;
2770 if (*dir == '/' || trust) {
2773 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
2776 pathname = arg->buffer;
2777 strncpy(pathname, dir, dirlen);
2778 pathname[dirlen] = '/';
2779 strcpy(pathname + dirlen + 1, arg->name);
2781 dbg(" Trying \"%s\"", pathname);
2782 if (access(pathname, F_OK) == 0) { /* We found it */
2783 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
2784 strcpy(pathname, arg->buffer);
2792 search_library_path(const char *name, const char *path)
2795 struct try_library_args arg;
2801 arg.namelen = strlen(name);
2802 arg.buffer = xmalloc(PATH_MAX);
2803 arg.buflen = PATH_MAX;
2805 p = path_enumerate(path, try_library_path, &arg);
2814 * Finds the library with the given name using the directory descriptors
2815 * listed in the LD_LIBRARY_PATH_FDS environment variable.
2817 * Returns a freshly-opened close-on-exec file descriptor for the library,
2818 * or -1 if the library cannot be found.
2821 search_library_pathfds(const char *name, const char *path, int *fdp)
2823 char *envcopy, *fdstr, *found, *last_token;
2827 dbg("%s('%s', '%s', fdp)", __func__, name, path);
2829 /* Don't load from user-specified libdirs into setuid binaries. */
2833 /* We can't do anything if LD_LIBRARY_PATH_FDS isn't set. */
2837 /* LD_LIBRARY_PATH_FDS only works with relative paths. */
2838 if (name[0] == '/') {
2839 dbg("Absolute path (%s) passed to %s", name, __func__);
2844 * Use strtok_r() to walk the FD:FD:FD list. This requires a local
2845 * copy of the path, as strtok_r rewrites separator tokens
2849 envcopy = xstrdup(path);
2850 for (fdstr = strtok_r(envcopy, ":", &last_token); fdstr != NULL;
2851 fdstr = strtok_r(NULL, ":", &last_token)) {
2852 dirfd = parse_libdir(fdstr);
2855 fd = openat(dirfd, name, O_RDONLY | O_CLOEXEC);
2858 len = strlen(fdstr) + strlen(name) + 3;
2859 found = xmalloc(len);
2860 if (rtld_snprintf(found, len, "#%d/%s", dirfd, name) < 0) {
2861 _rtld_error("error generating '%d/%s'",
2865 dbg("open('%s') => %d", found, fd);
2876 dlclose(void *handle)
2879 RtldLockState lockstate;
2881 wlock_acquire(rtld_bind_lock, &lockstate);
2882 root = dlcheck(handle);
2884 lock_release(rtld_bind_lock, &lockstate);
2887 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
2890 /* Unreference the object and its dependencies. */
2891 root->dl_refcount--;
2893 if (root->refcount == 1) {
2895 * The object will be no longer referenced, so we must unload it.
2896 * First, call the fini functions.
2898 objlist_call_fini(&list_fini, root, &lockstate);
2902 /* Finish cleaning up the newly-unreferenced objects. */
2903 GDB_STATE(RT_DELETE,&root->linkmap);
2904 unload_object(root);
2905 GDB_STATE(RT_CONSISTENT,NULL);
2909 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
2910 lock_release(rtld_bind_lock, &lockstate);
2917 char *msg = error_message;
2918 error_message = NULL;
2923 dlopen(const char *name, int mode)
2926 return (rtld_dlopen(name, -1, mode));
2930 fdlopen(int fd, int mode)
2933 return (rtld_dlopen(NULL, fd, mode));
2937 rtld_dlopen(const char *name, int fd, int mode)
2939 RtldLockState lockstate;
2942 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
2943 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
2944 if (ld_tracing != NULL) {
2945 rlock_acquire(rtld_bind_lock, &lockstate);
2946 if (sigsetjmp(lockstate.env, 0) != 0)
2947 lock_upgrade(rtld_bind_lock, &lockstate);
2948 environ = (char **)*get_program_var_addr("environ", &lockstate);
2949 lock_release(rtld_bind_lock, &lockstate);
2951 lo_flags = RTLD_LO_DLOPEN;
2952 if (mode & RTLD_NODELETE)
2953 lo_flags |= RTLD_LO_NODELETE;
2954 if (mode & RTLD_NOLOAD)
2955 lo_flags |= RTLD_LO_NOLOAD;
2956 if (ld_tracing != NULL)
2957 lo_flags |= RTLD_LO_TRACE;
2959 return (dlopen_object(name, fd, obj_main, lo_flags,
2960 mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL));
2964 dlopen_cleanup(Obj_Entry *obj)
2969 if (obj->refcount == 0)
2974 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
2975 int mode, RtldLockState *lockstate)
2977 Obj_Entry **old_obj_tail;
2980 RtldLockState mlockstate;
2983 objlist_init(&initlist);
2985 if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) {
2986 wlock_acquire(rtld_bind_lock, &mlockstate);
2987 lockstate = &mlockstate;
2989 GDB_STATE(RT_ADD,NULL);
2991 old_obj_tail = obj_tail;
2993 if (name == NULL && fd == -1) {
2997 obj = load_object(name, fd, refobj, lo_flags);
3002 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
3003 objlist_push_tail(&list_global, obj);
3004 if (*old_obj_tail != NULL) { /* We loaded something new. */
3005 assert(*old_obj_tail == obj);
3006 result = load_needed_objects(obj,
3007 lo_flags & (RTLD_LO_DLOPEN | RTLD_LO_EARLY));
3011 result = rtld_verify_versions(&obj->dagmembers);
3012 if (result != -1 && ld_tracing)
3014 if (result == -1 || relocate_object_dag(obj,
3015 (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld,
3016 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3018 dlopen_cleanup(obj);
3020 } else if (lo_flags & RTLD_LO_EARLY) {
3022 * Do not call the init functions for early loaded
3023 * filtees. The image is still not initialized enough
3026 * Our object is found by the global object list and
3027 * will be ordered among all init calls done right
3028 * before transferring control to main.
3031 /* Make list of init functions to call. */
3032 initlist_add_objects(obj, &obj->next, &initlist);
3035 * Process all no_delete objects here, given them own
3036 * DAGs to prevent their dependencies from being unloaded.
3037 * This has to be done after we have loaded all of the
3038 * dependencies, so that we do not miss any.
3041 process_nodelete(obj);
3044 * Bump the reference counts for objects on this DAG. If
3045 * this is the first dlopen() call for the object that was
3046 * already loaded as a dependency, initialize the dag
3052 if ((lo_flags & RTLD_LO_TRACE) != 0)
3055 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
3056 obj->z_nodelete) && !obj->ref_nodel) {
3057 dbg("obj %s nodelete", obj->path);
3059 obj->z_nodelete = obj->ref_nodel = true;
3063 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
3065 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
3067 if (!(lo_flags & RTLD_LO_EARLY)) {
3068 map_stacks_exec(lockstate);
3071 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
3072 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3074 objlist_clear(&initlist);
3075 dlopen_cleanup(obj);
3076 if (lockstate == &mlockstate)
3077 lock_release(rtld_bind_lock, lockstate);
3081 if (!(lo_flags & RTLD_LO_EARLY)) {
3082 /* Call the init functions. */
3083 objlist_call_init(&initlist, lockstate);
3085 objlist_clear(&initlist);
3086 if (lockstate == &mlockstate)
3087 lock_release(rtld_bind_lock, lockstate);
3090 trace_loaded_objects(obj);
3091 if (lockstate == &mlockstate)
3092 lock_release(rtld_bind_lock, lockstate);
3097 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
3101 const Obj_Entry *obj, *defobj;
3104 RtldLockState lockstate;
3110 symlook_init(&req, name);
3112 req.flags = flags | SYMLOOK_IN_PLT;
3113 req.lockstate = &lockstate;
3115 rlock_acquire(rtld_bind_lock, &lockstate);
3116 if (sigsetjmp(lockstate.env, 0) != 0)
3117 lock_upgrade(rtld_bind_lock, &lockstate);
3118 if (handle == NULL || handle == RTLD_NEXT ||
3119 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
3121 if ((obj = obj_from_addr(retaddr)) == NULL) {
3122 _rtld_error("Cannot determine caller's shared object");
3123 lock_release(rtld_bind_lock, &lockstate);
3126 if (handle == NULL) { /* Just the caller's shared object. */
3127 res = symlook_obj(&req, obj);
3130 defobj = req.defobj_out;
3132 } else if (handle == RTLD_NEXT || /* Objects after caller's */
3133 handle == RTLD_SELF) { /* ... caller included */
3134 if (handle == RTLD_NEXT)
3136 for (; obj != NULL; obj = obj->next) {
3137 res = symlook_obj(&req, obj);
3140 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) {
3142 defobj = req.defobj_out;
3143 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3149 * Search the dynamic linker itself, and possibly resolve the
3150 * symbol from there. This is how the application links to
3151 * dynamic linker services such as dlopen.
3153 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3154 res = symlook_obj(&req, &obj_rtld);
3157 defobj = req.defobj_out;
3161 assert(handle == RTLD_DEFAULT);
3162 res = symlook_default(&req, obj);
3164 defobj = req.defobj_out;
3169 if ((obj = dlcheck(handle)) == NULL) {
3170 lock_release(rtld_bind_lock, &lockstate);
3174 donelist_init(&donelist);
3175 if (obj->mainprog) {
3176 /* Handle obtained by dlopen(NULL, ...) implies global scope. */
3177 res = symlook_global(&req, &donelist);
3180 defobj = req.defobj_out;
3183 * Search the dynamic linker itself, and possibly resolve the
3184 * symbol from there. This is how the application links to
3185 * dynamic linker services such as dlopen.
3187 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3188 res = symlook_obj(&req, &obj_rtld);
3191 defobj = req.defobj_out;
3196 /* Search the whole DAG rooted at the given object. */
3197 res = symlook_list(&req, &obj->dagmembers, &donelist);
3200 defobj = req.defobj_out;
3206 lock_release(rtld_bind_lock, &lockstate);
3209 * The value required by the caller is derived from the value
3210 * of the symbol. this is simply the relocated value of the
3213 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
3214 return (make_function_pointer(def, defobj));
3215 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
3216 return (rtld_resolve_ifunc(defobj, def));
3217 else if (ELF_ST_TYPE(def->st_info) == STT_TLS) {
3218 ti.ti_module = defobj->tlsindex;
3219 ti.ti_offset = def->st_value;
3220 return (__tls_get_addr(&ti));
3222 return (defobj->relocbase + def->st_value);
3225 _rtld_error("Undefined symbol \"%s\"", name);
3226 lock_release(rtld_bind_lock, &lockstate);
3231 dlsym(void *handle, const char *name)
3233 return do_dlsym(handle, name, __builtin_return_address(0), NULL,
3238 dlfunc(void *handle, const char *name)
3245 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
3251 dlvsym(void *handle, const char *name, const char *version)
3255 ventry.name = version;
3257 ventry.hash = elf_hash(version);
3259 return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
3264 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
3266 const Obj_Entry *obj;
3267 RtldLockState lockstate;
3269 rlock_acquire(rtld_bind_lock, &lockstate);
3270 obj = obj_from_addr(addr);
3272 _rtld_error("No shared object contains address");
3273 lock_release(rtld_bind_lock, &lockstate);
3276 rtld_fill_dl_phdr_info(obj, phdr_info);
3277 lock_release(rtld_bind_lock, &lockstate);
3282 dladdr(const void *addr, Dl_info *info)
3284 const Obj_Entry *obj;
3287 unsigned long symoffset;
3288 RtldLockState lockstate;
3290 rlock_acquire(rtld_bind_lock, &lockstate);
3291 obj = obj_from_addr(addr);
3293 _rtld_error("No shared object contains address");
3294 lock_release(rtld_bind_lock, &lockstate);
3297 info->dli_fname = obj->path;
3298 info->dli_fbase = obj->mapbase;
3299 info->dli_saddr = NULL;
3300 info->dli_sname = NULL;
3303 * Walk the symbol list looking for the symbol whose address is
3304 * closest to the address sent in.
3306 for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) {
3307 def = obj->symtab + symoffset;
3310 * For skip the symbol if st_shndx is either SHN_UNDEF or
3313 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
3317 * If the symbol is greater than the specified address, or if it
3318 * is further away from addr than the current nearest symbol,
3321 symbol_addr = obj->relocbase + def->st_value;
3322 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
3325 /* Update our idea of the nearest symbol. */
3326 info->dli_sname = obj->strtab + def->st_name;
3327 info->dli_saddr = symbol_addr;
3330 if (info->dli_saddr == addr)
3333 lock_release(rtld_bind_lock, &lockstate);
3338 dlinfo(void *handle, int request, void *p)
3340 const Obj_Entry *obj;
3341 RtldLockState lockstate;
3344 rlock_acquire(rtld_bind_lock, &lockstate);
3346 if (handle == NULL || handle == RTLD_SELF) {
3349 retaddr = __builtin_return_address(0); /* __GNUC__ only */
3350 if ((obj = obj_from_addr(retaddr)) == NULL)
3351 _rtld_error("Cannot determine caller's shared object");
3353 obj = dlcheck(handle);
3356 lock_release(rtld_bind_lock, &lockstate);
3362 case RTLD_DI_LINKMAP:
3363 *((struct link_map const **)p) = &obj->linkmap;
3365 case RTLD_DI_ORIGIN:
3366 error = rtld_dirname(obj->path, p);
3369 case RTLD_DI_SERINFOSIZE:
3370 case RTLD_DI_SERINFO:
3371 error = do_search_info(obj, request, (struct dl_serinfo *)p);
3375 _rtld_error("Invalid request %d passed to dlinfo()", request);
3379 lock_release(rtld_bind_lock, &lockstate);
3385 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
3388 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
3389 phdr_info->dlpi_name = obj->path;
3390 phdr_info->dlpi_phdr = obj->phdr;
3391 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
3392 phdr_info->dlpi_tls_modid = obj->tlsindex;
3393 phdr_info->dlpi_tls_data = obj->tlsinit;
3394 phdr_info->dlpi_adds = obj_loads;
3395 phdr_info->dlpi_subs = obj_loads - obj_count;
3399 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
3401 struct dl_phdr_info phdr_info;
3402 const Obj_Entry *obj;
3403 RtldLockState bind_lockstate, phdr_lockstate;
3406 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
3407 rlock_acquire(rtld_bind_lock, &bind_lockstate);
3411 for (obj = obj_list; obj != NULL; obj = obj->next) {
3412 rtld_fill_dl_phdr_info(obj, &phdr_info);
3413 if ((error = callback(&phdr_info, sizeof phdr_info, param)) != 0)
3418 rtld_fill_dl_phdr_info(&obj_rtld, &phdr_info);
3419 error = callback(&phdr_info, sizeof(phdr_info), param);
3422 lock_release(rtld_bind_lock, &bind_lockstate);
3423 lock_release(rtld_phdr_lock, &phdr_lockstate);
3429 fill_search_info(const char *dir, size_t dirlen, void *param)
3431 struct fill_search_info_args *arg;
3435 if (arg->request == RTLD_DI_SERINFOSIZE) {
3436 arg->serinfo->dls_cnt ++;
3437 arg->serinfo->dls_size += sizeof(struct dl_serpath) + dirlen + 1;
3439 struct dl_serpath *s_entry;
3441 s_entry = arg->serpath;
3442 s_entry->dls_name = arg->strspace;
3443 s_entry->dls_flags = arg->flags;
3445 strncpy(arg->strspace, dir, dirlen);
3446 arg->strspace[dirlen] = '\0';
3448 arg->strspace += dirlen + 1;
3456 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
3458 struct dl_serinfo _info;
3459 struct fill_search_info_args args;
3461 args.request = RTLD_DI_SERINFOSIZE;
3462 args.serinfo = &_info;
3464 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
3467 path_enumerate(obj->rpath, fill_search_info, &args);
3468 path_enumerate(ld_library_path, fill_search_info, &args);
3469 path_enumerate(obj->runpath, fill_search_info, &args);
3470 path_enumerate(gethints(obj->z_nodeflib), fill_search_info, &args);
3471 if (!obj->z_nodeflib)
3472 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
3475 if (request == RTLD_DI_SERINFOSIZE) {
3476 info->dls_size = _info.dls_size;
3477 info->dls_cnt = _info.dls_cnt;
3481 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
3482 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
3486 args.request = RTLD_DI_SERINFO;
3487 args.serinfo = info;
3488 args.serpath = &info->dls_serpath[0];
3489 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
3491 args.flags = LA_SER_RUNPATH;
3492 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
3495 args.flags = LA_SER_LIBPATH;
3496 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
3499 args.flags = LA_SER_RUNPATH;
3500 if (path_enumerate(obj->runpath, fill_search_info, &args) != NULL)
3503 args.flags = LA_SER_CONFIG;
3504 if (path_enumerate(gethints(obj->z_nodeflib), fill_search_info, &args)
3508 args.flags = LA_SER_DEFAULT;
3509 if (!obj->z_nodeflib &&
3510 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
3516 rtld_dirname(const char *path, char *bname)
3520 /* Empty or NULL string gets treated as "." */
3521 if (path == NULL || *path == '\0') {
3527 /* Strip trailing slashes */
3528 endp = path + strlen(path) - 1;
3529 while (endp > path && *endp == '/')
3532 /* Find the start of the dir */
3533 while (endp > path && *endp != '/')
3536 /* Either the dir is "/" or there are no slashes */
3538 bname[0] = *endp == '/' ? '/' : '.';
3544 } while (endp > path && *endp == '/');
3547 if (endp - path + 2 > PATH_MAX)
3549 _rtld_error("Filename is too long: %s", path);
3553 strncpy(bname, path, endp - path + 1);
3554 bname[endp - path + 1] = '\0';
3559 rtld_dirname_abs(const char *path, char *base)
3561 char base_rel[PATH_MAX];
3563 if (rtld_dirname(path, base) == -1)
3567 if (getcwd(base_rel, sizeof(base_rel)) == NULL ||
3568 strlcat(base_rel, "/", sizeof(base_rel)) >= sizeof(base_rel) ||
3569 strlcat(base_rel, base, sizeof(base_rel)) >= sizeof(base_rel))
3571 strcpy(base, base_rel);
3576 linkmap_add(Obj_Entry *obj)
3578 struct link_map *l = &obj->linkmap;
3579 struct link_map *prev;
3581 obj->linkmap.l_name = obj->path;
3582 obj->linkmap.l_addr = obj->mapbase;
3583 obj->linkmap.l_ld = obj->dynamic;
3585 /* GDB needs load offset on MIPS to use the symbols */
3586 obj->linkmap.l_offs = obj->relocbase;
3589 if (r_debug.r_map == NULL) {
3595 * Scan to the end of the list, but not past the entry for the
3596 * dynamic linker, which we want to keep at the very end.
3598 for (prev = r_debug.r_map;
3599 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
3600 prev = prev->l_next)
3603 /* Link in the new entry. */
3605 l->l_next = prev->l_next;
3606 if (l->l_next != NULL)
3607 l->l_next->l_prev = l;
3612 linkmap_delete(Obj_Entry *obj)
3614 struct link_map *l = &obj->linkmap;
3616 if (l->l_prev == NULL) {
3617 if ((r_debug.r_map = l->l_next) != NULL)
3618 l->l_next->l_prev = NULL;
3622 if ((l->l_prev->l_next = l->l_next) != NULL)
3623 l->l_next->l_prev = l->l_prev;
3627 * Function for the debugger to set a breakpoint on to gain control.
3629 * The two parameters allow the debugger to easily find and determine
3630 * what the runtime loader is doing and to whom it is doing it.
3632 * When the loadhook trap is hit (r_debug_state, set at program
3633 * initialization), the arguments can be found on the stack:
3635 * +8 struct link_map *m
3636 * +4 struct r_debug *rd
3640 r_debug_state(struct r_debug* rd, struct link_map *m)
3643 * The following is a hack to force the compiler to emit calls to
3644 * this function, even when optimizing. If the function is empty,
3645 * the compiler is not obliged to emit any code for calls to it,
3646 * even when marked __noinline. However, gdb depends on those
3649 __asm __volatile("" : : : "memory");
3653 * Get address of the pointer variable in the main program.
3654 * Prefer non-weak symbol over the weak one.
3656 static const void **
3657 get_program_var_addr(const char *name, RtldLockState *lockstate)
3662 symlook_init(&req, name);
3663 req.lockstate = lockstate;
3664 donelist_init(&donelist);
3665 if (symlook_global(&req, &donelist) != 0)
3667 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
3668 return ((const void **)make_function_pointer(req.sym_out,
3670 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
3671 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
3673 return ((const void **)(req.defobj_out->relocbase +
3674 req.sym_out->st_value));
3678 * Set a pointer variable in the main program to the given value. This
3679 * is used to set key variables such as "environ" before any of the
3680 * init functions are called.
3683 set_program_var(const char *name, const void *value)
3687 if ((addr = get_program_var_addr(name, NULL)) != NULL) {
3688 dbg("\"%s\": *%p <-- %p", name, addr, value);
3694 * Search the global objects, including dependencies and main object,
3695 * for the given symbol.
3698 symlook_global(SymLook *req, DoneList *donelist)
3701 const Objlist_Entry *elm;
3704 symlook_init_from_req(&req1, req);
3706 /* Search all objects loaded at program start up. */
3707 if (req->defobj_out == NULL ||
3708 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3709 res = symlook_list(&req1, &list_main, donelist);
3710 if (res == 0 && (req->defobj_out == NULL ||
3711 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3712 req->sym_out = req1.sym_out;
3713 req->defobj_out = req1.defobj_out;
3714 assert(req->defobj_out != NULL);
3718 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
3719 STAILQ_FOREACH(elm, &list_global, link) {
3720 if (req->defobj_out != NULL &&
3721 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3723 res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
3724 if (res == 0 && (req->defobj_out == NULL ||
3725 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3726 req->sym_out = req1.sym_out;
3727 req->defobj_out = req1.defobj_out;
3728 assert(req->defobj_out != NULL);
3732 return (req->sym_out != NULL ? 0 : ESRCH);
3736 * This is a special version of getenv which is far more efficient
3737 * at finding LD_ environment vars.
3741 _getenv_ld(const char *id)
3745 int idlen = strlen(id);
3747 if (ld_index == LD_ARY_CACHE)
3749 if (ld_index == 0) {
3750 for (i = j = 0; (envp = environ[i]) != NULL && j < LD_ARY_CACHE; ++i) {
3751 if (envp[0] == 'L' && envp[1] == 'D' && envp[2] == '_')
3758 for (i = ld_index - 1; i >= 0; --i) {
3759 if (strncmp(ld_ary[i], id, idlen) == 0 && ld_ary[i][idlen] == '=')
3760 return(ld_ary[i] + idlen + 1);
3766 * Given a symbol name in a referencing object, find the corresponding
3767 * definition of the symbol. Returns a pointer to the symbol, or NULL if
3768 * no definition was found. Returns a pointer to the Obj_Entry of the
3769 * defining object via the reference parameter DEFOBJ_OUT.
3772 symlook_default(SymLook *req, const Obj_Entry *refobj)
3775 const Objlist_Entry *elm;
3779 donelist_init(&donelist);
3780 symlook_init_from_req(&req1, req);
3782 /* Look first in the referencing object if linked symbolically. */
3783 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
3784 res = symlook_obj(&req1, refobj);
3786 req->sym_out = req1.sym_out;
3787 req->defobj_out = req1.defobj_out;
3788 assert(req->defobj_out != NULL);
3792 symlook_global(req, &donelist);
3794 /* Search all dlopened DAGs containing the referencing object. */
3795 STAILQ_FOREACH(elm, &refobj->dldags, link) {
3796 if (req->sym_out != NULL &&
3797 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3799 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
3800 if (res == 0 && (req->sym_out == NULL ||
3801 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3802 req->sym_out = req1.sym_out;
3803 req->defobj_out = req1.defobj_out;
3804 assert(req->defobj_out != NULL);
3809 * Search the dynamic linker itself, and possibly resolve the
3810 * symbol from there. This is how the application links to
3811 * dynamic linker services such as dlopen.
3813 if (req->sym_out == NULL ||
3814 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3815 res = symlook_obj(&req1, &obj_rtld);
3817 req->sym_out = req1.sym_out;
3818 req->defobj_out = req1.defobj_out;
3819 assert(req->defobj_out != NULL);
3823 return (req->sym_out != NULL ? 0 : ESRCH);
3827 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
3830 const Obj_Entry *defobj;
3831 const Objlist_Entry *elm;
3837 STAILQ_FOREACH(elm, objlist, link) {
3838 if (donelist_check(dlp, elm->obj))
3840 symlook_init_from_req(&req1, req);
3841 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
3842 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3844 defobj = req1.defobj_out;
3845 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3852 req->defobj_out = defobj;
3859 * Search the chain of DAGS cointed to by the given Needed_Entry
3860 * for a symbol of the given name. Each DAG is scanned completely
3861 * before advancing to the next one. Returns a pointer to the symbol,
3862 * or NULL if no definition was found.
3865 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
3868 const Needed_Entry *n;
3869 const Obj_Entry *defobj;
3875 symlook_init_from_req(&req1, req);
3876 for (n = needed; n != NULL; n = n->next) {
3877 if (n->obj == NULL ||
3878 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
3880 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3882 defobj = req1.defobj_out;
3883 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3889 req->defobj_out = defobj;
3896 * Search the symbol table of a single shared object for a symbol of
3897 * the given name and version, if requested. Returns a pointer to the
3898 * symbol, or NULL if no definition was found. If the object is
3899 * filter, return filtered symbol from filtee.
3901 * The symbol's hash value is passed in for efficiency reasons; that
3902 * eliminates many recomputations of the hash value.
3905 symlook_obj(SymLook *req, const Obj_Entry *obj)
3909 int flags, res, mres;
3912 * If there is at least one valid hash at this point, we prefer to
3913 * use the faster GNU version if available.
3915 if (obj->valid_hash_gnu)
3916 mres = symlook_obj1_gnu(req, obj);
3917 else if (obj->valid_hash_sysv)
3918 mres = symlook_obj1_sysv(req, obj);
3923 if (obj->needed_filtees != NULL) {
3924 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
3925 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
3926 donelist_init(&donelist);
3927 symlook_init_from_req(&req1, req);
3928 res = symlook_needed(&req1, obj->needed_filtees, &donelist);
3930 req->sym_out = req1.sym_out;
3931 req->defobj_out = req1.defobj_out;
3935 if (obj->needed_aux_filtees != NULL) {
3936 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
3937 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
3938 donelist_init(&donelist);
3939 symlook_init_from_req(&req1, req);
3940 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
3942 req->sym_out = req1.sym_out;
3943 req->defobj_out = req1.defobj_out;
3951 /* Symbol match routine common to both hash functions */
3953 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result,
3954 const unsigned long symnum)
3957 const Elf_Sym *symp;
3960 symp = obj->symtab + symnum;
3961 strp = obj->strtab + symp->st_name;
3963 switch (ELF_ST_TYPE(symp->st_info)) {
3969 if (symp->st_value == 0)
3973 if (symp->st_shndx != SHN_UNDEF)
3975 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
3976 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
3982 if (strcmp(req->name, strp) != 0)
3985 if (req->ventry == NULL) {
3986 if (obj->versyms != NULL) {
3987 verndx = VER_NDX(obj->versyms[symnum]);
3988 if (verndx > obj->vernum) {
3990 "%s: symbol %s references wrong version %d",
3991 obj->path, obj->strtab + symnum, verndx);
3995 * If we are not called from dlsym (i.e. this
3996 * is a normal relocation from unversioned
3997 * binary), accept the symbol immediately if
3998 * it happens to have first version after this
3999 * shared object became versioned. Otherwise,
4000 * if symbol is versioned and not hidden,
4001 * remember it. If it is the only symbol with
4002 * this name exported by the shared object, it
4003 * will be returned as a match by the calling
4004 * function. If symbol is global (verndx < 2)
4005 * accept it unconditionally.
4007 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
4008 verndx == VER_NDX_GIVEN) {
4009 result->sym_out = symp;
4012 else if (verndx >= VER_NDX_GIVEN) {
4013 if ((obj->versyms[symnum] & VER_NDX_HIDDEN)
4015 if (result->vsymp == NULL)
4016 result->vsymp = symp;
4022 result->sym_out = symp;
4025 if (obj->versyms == NULL) {
4026 if (object_match_name(obj, req->ventry->name)) {
4027 _rtld_error("%s: object %s should provide version %s "
4028 "for symbol %s", obj_rtld.path, obj->path,
4029 req->ventry->name, obj->strtab + symnum);
4033 verndx = VER_NDX(obj->versyms[symnum]);
4034 if (verndx > obj->vernum) {
4035 _rtld_error("%s: symbol %s references wrong version %d",
4036 obj->path, obj->strtab + symnum, verndx);
4039 if (obj->vertab[verndx].hash != req->ventry->hash ||
4040 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
4042 * Version does not match. Look if this is a
4043 * global symbol and if it is not hidden. If
4044 * global symbol (verndx < 2) is available,
4045 * use it. Do not return symbol if we are
4046 * called by dlvsym, because dlvsym looks for
4047 * a specific version and default one is not
4048 * what dlvsym wants.
4050 if ((req->flags & SYMLOOK_DLSYM) ||
4051 (verndx >= VER_NDX_GIVEN) ||
4052 (obj->versyms[symnum] & VER_NDX_HIDDEN))
4056 result->sym_out = symp;
4061 * Search for symbol using SysV hash function.
4062 * obj->buckets is known not to be NULL at this point; the test for this was
4063 * performed with the obj->valid_hash_sysv assignment.
4066 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj)
4068 unsigned long symnum;
4069 Sym_Match_Result matchres;
4071 matchres.sym_out = NULL;
4072 matchres.vsymp = NULL;
4073 matchres.vcount = 0;
4075 for (symnum = obj->buckets[req->hash % obj->nbuckets];
4076 symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
4077 if (symnum >= obj->nchains)
4078 return (ESRCH); /* Bad object */
4080 if (matched_symbol(req, obj, &matchres, symnum)) {
4081 req->sym_out = matchres.sym_out;
4082 req->defobj_out = obj;
4086 if (matchres.vcount == 1) {
4087 req->sym_out = matchres.vsymp;
4088 req->defobj_out = obj;
4094 /* Search for symbol using GNU hash function */
4096 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj)
4098 Elf_Addr bloom_word;
4099 const Elf32_Word *hashval;
4101 Sym_Match_Result matchres;
4102 unsigned int h1, h2;
4103 unsigned long symnum;
4105 matchres.sym_out = NULL;
4106 matchres.vsymp = NULL;
4107 matchres.vcount = 0;
4109 /* Pick right bitmask word from Bloom filter array */
4110 bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) &
4111 obj->maskwords_bm_gnu];
4113 /* Calculate modulus word size of gnu hash and its derivative */
4114 h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1);
4115 h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1));
4117 /* Filter out the "definitely not in set" queries */
4118 if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0)
4121 /* Locate hash chain and corresponding value element*/
4122 bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu];
4125 hashval = &obj->chain_zero_gnu[bucket];
4127 if (((*hashval ^ req->hash_gnu) >> 1) == 0) {
4128 symnum = hashval - obj->chain_zero_gnu;
4129 if (matched_symbol(req, obj, &matchres, symnum)) {
4130 req->sym_out = matchres.sym_out;
4131 req->defobj_out = obj;
4135 } while ((*hashval++ & 1) == 0);
4136 if (matchres.vcount == 1) {
4137 req->sym_out = matchres.vsymp;
4138 req->defobj_out = obj;
4145 trace_loaded_objects(Obj_Entry *obj)
4147 const char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
4150 if ((main_local = _getenv_ld("LD_TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
4153 if ((fmt1 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT1")) == NULL)
4154 fmt1 = "\t%o => %p (%x)\n";
4156 if ((fmt2 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT2")) == NULL)
4157 fmt2 = "\t%o (%x)\n";
4159 list_containers = _getenv_ld("LD_TRACE_LOADED_OBJECTS_ALL");
4161 for (; obj; obj = obj->next) {
4162 Needed_Entry *needed;
4166 if (list_containers && obj->needed != NULL)
4167 rtld_printf("%s:\n", obj->path);
4168 for (needed = obj->needed; needed; needed = needed->next) {
4169 if (needed->obj != NULL) {
4170 if (needed->obj->traced && !list_containers)
4172 needed->obj->traced = true;
4173 path = needed->obj->path;
4177 name = (char *)obj->strtab + needed->name;
4178 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
4180 fmt = is_lib ? fmt1 : fmt2;
4181 while ((c = *fmt++) != '\0') {
4207 rtld_putstr(main_local);
4210 rtld_putstr(obj_main->path);
4219 rtld_printf("%p", needed->obj ? needed->obj->mapbase :
4232 * Unload a dlopened object and its dependencies from memory and from
4233 * our data structures. It is assumed that the DAG rooted in the
4234 * object has already been unreferenced, and that the object has a
4235 * reference count of 0.
4238 unload_object(Obj_Entry *root)
4243 assert(root->refcount == 0);
4246 * Pass over the DAG removing unreferenced objects from
4247 * appropriate lists.
4249 unlink_object(root);
4251 /* Unmap all objects that are no longer referenced. */
4252 linkp = &obj_list->next;
4253 while ((obj = *linkp) != NULL) {
4254 if (obj->refcount == 0) {
4255 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
4257 dbg("unloading \"%s\"", obj->path);
4258 unload_filtees(root);
4259 munmap(obj->mapbase, obj->mapsize);
4260 linkmap_delete(obj);
4271 unlink_object(Obj_Entry *root)
4275 if (root->refcount == 0) {
4276 /* Remove the object from the RTLD_GLOBAL list. */
4277 objlist_remove(&list_global, root);
4279 /* Remove the object from all objects' DAG lists. */
4280 STAILQ_FOREACH(elm, &root->dagmembers, link) {
4281 objlist_remove(&elm->obj->dldags, root);
4282 if (elm->obj != root)
4283 unlink_object(elm->obj);
4289 ref_dag(Obj_Entry *root)
4293 assert(root->dag_inited);
4294 STAILQ_FOREACH(elm, &root->dagmembers, link)
4295 elm->obj->refcount++;
4299 unref_dag(Obj_Entry *root)
4303 assert(root->dag_inited);
4304 STAILQ_FOREACH(elm, &root->dagmembers, link)
4305 elm->obj->refcount--;
4309 * Common code for MD __tls_get_addr().
4312 tls_get_addr_common(Elf_Addr** dtvp, int index, size_t offset)
4314 Elf_Addr* dtv = *dtvp;
4315 RtldLockState lockstate;
4317 /* Check dtv generation in case new modules have arrived */
4318 if (dtv[0] != tls_dtv_generation) {
4322 wlock_acquire(rtld_bind_lock, &lockstate);
4323 newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4325 if (to_copy > tls_max_index)
4326 to_copy = tls_max_index;
4327 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
4328 newdtv[0] = tls_dtv_generation;
4329 newdtv[1] = tls_max_index;
4331 lock_release(rtld_bind_lock, &lockstate);
4332 dtv = *dtvp = newdtv;
4335 /* Dynamically allocate module TLS if necessary */
4336 if (!dtv[index + 1]) {
4337 /* Signal safe, wlock will block out signals. */
4338 wlock_acquire(rtld_bind_lock, &lockstate);
4339 if (!dtv[index + 1])
4340 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
4341 lock_release(rtld_bind_lock, &lockstate);
4343 return ((void *)(dtv[index + 1] + offset));
4346 #if defined(RTLD_STATIC_TLS_VARIANT_II)
4349 * Allocate the static TLS area. Return a pointer to the TCB. The
4350 * static area is based on negative offsets relative to the tcb.
4352 * The TCB contains an errno pointer for the system call layer, but because
4353 * we are the RTLD we really have no idea how the caller was compiled so
4354 * the information has to be passed in. errno can either be:
4356 * type 0 errno is a simple non-TLS global pointer.
4357 * (special case for e.g. libc_rtld)
4358 * type 1 errno accessed by GOT entry (dynamically linked programs)
4359 * type 2 errno accessed by %gs:OFFSET (statically linked programs)
4362 allocate_tls(Obj_Entry *objs)
4367 struct tls_tcb *tcb;
4372 * Allocate the new TCB. static TLS storage is placed just before the
4373 * TCB to support the %gs:OFFSET (negative offset) model.
4375 data_size = (tls_static_space + RTLD_STATIC_TLS_ALIGN_MASK) &
4376 ~RTLD_STATIC_TLS_ALIGN_MASK;
4377 tcb = malloc(data_size + sizeof(*tcb));
4378 tcb = (void *)((char *)tcb + data_size); /* actual tcb location */
4380 dtv_size = (tls_max_index + 2) * sizeof(Elf_Addr);
4381 dtv = malloc(dtv_size);
4382 bzero(dtv, dtv_size);
4384 #ifdef RTLD_TCB_HAS_SELF_POINTER
4385 tcb->tcb_self = tcb;
4388 tcb->tcb_pthread = NULL;
4390 dtv[0] = tls_dtv_generation;
4391 dtv[1] = tls_max_index;
4393 for (obj = objs; obj; obj = obj->next) {
4394 if (obj->tlsoffset) {
4395 addr = (Elf_Addr)tcb - obj->tlsoffset;
4396 memset((void *)(addr + obj->tlsinitsize),
4397 0, obj->tlssize - obj->tlsinitsize);
4399 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4400 dtv[obj->tlsindex + 1] = addr;
4407 free_tls(struct tls_tcb *tcb)
4411 Elf_Addr tls_start, tls_end;
4414 data_size = (tls_static_space + RTLD_STATIC_TLS_ALIGN_MASK) &
4415 ~RTLD_STATIC_TLS_ALIGN_MASK;
4419 tls_end = (Elf_Addr)tcb;
4420 tls_start = (Elf_Addr)tcb - data_size;
4421 for (i = 0; i < dtv_size; i++) {
4422 if (dtv[i+2] != 0 && (dtv[i+2] < tls_start || dtv[i+2] > tls_end)) {
4423 free((void *)dtv[i+2]);
4427 free((void*) tls_start);
4431 #error "Unsupported TLS layout"
4435 * Allocate TLS block for module with given index.
4438 allocate_module_tls(int index)
4443 for (obj = obj_list; obj; obj = obj->next) {
4444 if (obj->tlsindex == index)
4448 _rtld_error("Can't find module with TLS index %d", index);
4452 p = malloc(obj->tlssize);
4454 _rtld_error("Cannot allocate TLS block for index %d", index);
4457 memcpy(p, obj->tlsinit, obj->tlsinitsize);
4458 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
4464 allocate_tls_offset(Obj_Entry *obj)
4471 if (obj->tlssize == 0) {
4472 obj->tls_done = true;
4476 if (obj->tlsindex == 1)
4477 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
4479 off = calculate_tls_offset(tls_last_offset, tls_last_size,
4480 obj->tlssize, obj->tlsalign);
4483 * If we have already fixed the size of the static TLS block, we
4484 * must stay within that size. When allocating the static TLS, we
4485 * leave a small amount of space spare to be used for dynamically
4486 * loading modules which use static TLS.
4488 if (tls_static_space) {
4489 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
4493 tls_last_offset = obj->tlsoffset = off;
4494 tls_last_size = obj->tlssize;
4495 obj->tls_done = true;
4501 free_tls_offset(Obj_Entry *obj)
4503 #ifdef RTLD_STATIC_TLS_VARIANT_II
4505 * If we were the last thing to allocate out of the static TLS
4506 * block, we give our space back to the 'allocator'. This is a
4507 * simplistic workaround to allow libGL.so.1 to be loaded and
4508 * unloaded multiple times. We only handle the Variant II
4509 * mechanism for now - this really needs a proper allocator.
4511 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
4512 == calculate_tls_end(tls_last_offset, tls_last_size)) {
4513 tls_last_offset -= obj->tlssize;
4520 _rtld_allocate_tls(void)
4522 struct tls_tcb *new_tcb;
4523 RtldLockState lockstate;
4525 wlock_acquire(rtld_bind_lock, &lockstate);
4526 new_tcb = allocate_tls(obj_list);
4527 lock_release(rtld_bind_lock, &lockstate);
4532 _rtld_free_tls(struct tls_tcb *tcb)
4534 RtldLockState lockstate;
4536 wlock_acquire(rtld_bind_lock, &lockstate);
4538 lock_release(rtld_bind_lock, &lockstate);
4542 object_add_name(Obj_Entry *obj, const char *name)
4548 entry = malloc(sizeof(Name_Entry) + len);
4550 if (entry != NULL) {
4551 strcpy(entry->name, name);
4552 STAILQ_INSERT_TAIL(&obj->names, entry, link);
4557 object_match_name(const Obj_Entry *obj, const char *name)
4561 STAILQ_FOREACH(entry, &obj->names, link) {
4562 if (strcmp(name, entry->name) == 0)
4569 locate_dependency(const Obj_Entry *obj, const char *name)
4571 const Objlist_Entry *entry;
4572 const Needed_Entry *needed;
4574 STAILQ_FOREACH(entry, &list_main, link) {
4575 if (object_match_name(entry->obj, name))
4579 for (needed = obj->needed; needed != NULL; needed = needed->next) {
4580 if (strcmp(obj->strtab + needed->name, name) == 0 ||
4581 (needed->obj != NULL && object_match_name(needed->obj, name))) {
4583 * If there is DT_NEEDED for the name we are looking for,
4584 * we are all set. Note that object might not be found if
4585 * dependency was not loaded yet, so the function can
4586 * return NULL here. This is expected and handled
4587 * properly by the caller.
4589 return (needed->obj);
4592 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
4598 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
4599 const Elf_Vernaux *vna)
4601 const Elf_Verdef *vd;
4602 const char *vername;
4604 vername = refobj->strtab + vna->vna_name;
4605 vd = depobj->verdef;
4607 _rtld_error("%s: version %s required by %s not defined",
4608 depobj->path, vername, refobj->path);
4612 if (vd->vd_version != VER_DEF_CURRENT) {
4613 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
4614 depobj->path, vd->vd_version);
4617 if (vna->vna_hash == vd->vd_hash) {
4618 const Elf_Verdaux *aux = (const Elf_Verdaux *)
4619 ((char *)vd + vd->vd_aux);
4620 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
4623 if (vd->vd_next == 0)
4625 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4627 if (vna->vna_flags & VER_FLG_WEAK)
4629 _rtld_error("%s: version %s required by %s not found",
4630 depobj->path, vername, refobj->path);
4635 rtld_verify_object_versions(Obj_Entry *obj)
4637 const Elf_Verneed *vn;
4638 const Elf_Verdef *vd;
4639 const Elf_Verdaux *vda;
4640 const Elf_Vernaux *vna;
4641 const Obj_Entry *depobj;
4642 int maxvernum, vernum;
4644 if (obj->ver_checked)
4646 obj->ver_checked = true;
4650 * Walk over defined and required version records and figure out
4651 * max index used by any of them. Do very basic sanity checking
4655 while (vn != NULL) {
4656 if (vn->vn_version != VER_NEED_CURRENT) {
4657 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
4658 obj->path, vn->vn_version);
4661 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4663 vernum = VER_NEED_IDX(vna->vna_other);
4664 if (vernum > maxvernum)
4666 if (vna->vna_next == 0)
4668 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4670 if (vn->vn_next == 0)
4672 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4676 while (vd != NULL) {
4677 if (vd->vd_version != VER_DEF_CURRENT) {
4678 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
4679 obj->path, vd->vd_version);
4682 vernum = VER_DEF_IDX(vd->vd_ndx);
4683 if (vernum > maxvernum)
4685 if (vd->vd_next == 0)
4687 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4694 * Store version information in array indexable by version index.
4695 * Verify that object version requirements are satisfied along the
4698 obj->vernum = maxvernum + 1;
4699 obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry));
4702 while (vd != NULL) {
4703 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
4704 vernum = VER_DEF_IDX(vd->vd_ndx);
4705 assert(vernum <= maxvernum);
4706 vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
4707 obj->vertab[vernum].hash = vd->vd_hash;
4708 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
4709 obj->vertab[vernum].file = NULL;
4710 obj->vertab[vernum].flags = 0;
4712 if (vd->vd_next == 0)
4714 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4718 while (vn != NULL) {
4719 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
4722 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4724 if (check_object_provided_version(obj, depobj, vna))
4726 vernum = VER_NEED_IDX(vna->vna_other);
4727 assert(vernum <= maxvernum);
4728 obj->vertab[vernum].hash = vna->vna_hash;
4729 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
4730 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
4731 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
4732 VER_INFO_HIDDEN : 0;
4733 if (vna->vna_next == 0)
4735 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4737 if (vn->vn_next == 0)
4739 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4745 rtld_verify_versions(const Objlist *objlist)
4747 Objlist_Entry *entry;
4751 STAILQ_FOREACH(entry, objlist, link) {
4753 * Skip dummy objects or objects that have their version requirements
4756 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
4758 if (rtld_verify_object_versions(entry->obj) == -1) {
4760 if (ld_tracing == NULL)
4764 if (rc == 0 || ld_tracing != NULL)
4765 rc = rtld_verify_object_versions(&obj_rtld);
4770 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
4775 vernum = VER_NDX(obj->versyms[symnum]);
4776 if (vernum >= obj->vernum) {
4777 _rtld_error("%s: symbol %s has wrong verneed value %d",
4778 obj->path, obj->strtab + symnum, vernum);
4779 } else if (obj->vertab[vernum].hash != 0) {
4780 return &obj->vertab[vernum];
4787 _rtld_get_stack_prot(void)
4790 return (stack_prot);
4794 map_stacks_exec(RtldLockState *lockstate)
4798 * Stack protection must be implemented in the kernel before the dynamic
4799 * linker can handle PT_GNU_STACK sections.
4800 * The following is the FreeBSD implementation of map_stacks_exec()
4801 * void (*thr_map_stacks_exec)(void);
4803 * if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
4805 * thr_map_stacks_exec = (void (*)(void))(uintptr_t)
4806 * get_program_var_addr("__pthread_map_stacks_exec", lockstate);
4807 * if (thr_map_stacks_exec != NULL) {
4808 * stack_prot |= PROT_EXEC;
4809 * thr_map_stacks_exec();
4815 symlook_init(SymLook *dst, const char *name)
4818 bzero(dst, sizeof(*dst));
4820 dst->hash = elf_hash(name);
4821 dst->hash_gnu = gnu_hash(name);
4825 symlook_init_from_req(SymLook *dst, const SymLook *src)
4828 dst->name = src->name;
4829 dst->hash = src->hash;
4830 dst->hash_gnu = src->hash_gnu;
4831 dst->ventry = src->ventry;
4832 dst->flags = src->flags;
4833 dst->defobj_out = NULL;
4834 dst->sym_out = NULL;
4835 dst->lockstate = src->lockstate;
4840 * Parse a file descriptor number without pulling in more of libc (e.g. atoi).
4843 parse_libdir(const char *str)
4845 static const int RADIX = 10; /* XXXJA: possibly support hex? */
4852 for (c = *str; c != '\0'; c = *++str) {
4853 if (c < '0' || c > '9')
4860 /* Make sure we actually parsed something. */
4862 _rtld_error("failed to parse directory FD from '%s'", str);
4868 #ifdef ENABLE_OSRELDATE
4870 * Overrides for libc_pic-provided functions.
4874 __getosreldate(void)
4884 oid[1] = KERN_OSRELDATE;
4886 len = sizeof(osrel);
4887 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
4888 if (error == 0 && osrel > 0 && len == sizeof(osrel))
4895 * No unresolved symbols for rtld.
4898 __pthread_cxa_finalize(struct dl_phdr_info *a)
4903 rtld_strerror(int errnum)
4906 if (errnum < 0 || errnum >= sys_nerr)
4907 return ("Unknown error");
4908 return (sys_errlist[errnum]);