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 *);
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 bool is_exported(const Elf_Sym *);
104 static void linkmap_add(Obj_Entry *);
105 static void linkmap_delete(Obj_Entry *);
106 static void load_filtees(Obj_Entry *, int flags, RtldLockState *);
107 static void unload_filtees(Obj_Entry *);
108 static int load_needed_objects(Obj_Entry *, int);
109 static int load_preload_objects(void);
110 static Obj_Entry *load_object(const char *, int fd, const Obj_Entry *, int);
111 static void map_stacks_exec(RtldLockState *);
112 static Obj_Entry *obj_from_addr(const void *);
113 static void objlist_call_fini(Objlist *, Obj_Entry *, RtldLockState *);
114 static void objlist_call_init(Objlist *, RtldLockState *);
115 static void objlist_clear(Objlist *);
116 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
117 static void objlist_init(Objlist *);
118 static void objlist_push_head(Objlist *, Obj_Entry *);
119 static void objlist_push_tail(Objlist *, Obj_Entry *);
120 static void objlist_remove(Objlist *, Obj_Entry *);
121 static void *path_enumerate(const char *, path_enum_proc, void *);
122 static int relocate_object_dag(Obj_Entry *root, bool bind_now,
123 Obj_Entry *rtldobj, int flags, RtldLockState *lockstate);
124 static int relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
125 int flags, RtldLockState *lockstate);
126 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, int,
128 static int resolve_objects_ifunc(Obj_Entry *first, bool bind_now,
129 int flags, RtldLockState *lockstate);
130 static int rtld_dirname(const char *, char *);
131 static int rtld_dirname_abs(const char *, char *);
132 static void *rtld_dlopen(const char *name, int fd, int mode);
133 static void rtld_exit(void);
134 static char *search_library_path(const char *, const char *);
135 static const void **get_program_var_addr(const char *, RtldLockState *);
136 static void set_program_var(const char *, const void *);
137 static int symlook_default(SymLook *, const Obj_Entry *refobj);
138 static int symlook_global(SymLook *, DoneList *);
139 static void symlook_init_from_req(SymLook *, const SymLook *);
140 static int symlook_list(SymLook *, const Objlist *, DoneList *);
141 static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *);
142 static int symlook_obj1_sysv(SymLook *, const Obj_Entry *);
143 static int symlook_obj1_gnu(SymLook *, const Obj_Entry *);
144 static void trace_loaded_objects(Obj_Entry *);
145 static void unlink_object(Obj_Entry *);
146 static void unload_object(Obj_Entry *);
147 static void unref_dag(Obj_Entry *);
148 static void ref_dag(Obj_Entry *);
149 static int origin_subst_one(char **, const char *, const char *,
150 const char *, char *);
151 static char *origin_subst(const char *, const char *);
152 static void preinitialize_main_object (void);
153 static int rtld_verify_versions(const Objlist *);
154 static int rtld_verify_object_versions(Obj_Entry *);
155 static void object_add_name(Obj_Entry *, const char *);
156 static int object_match_name(const Obj_Entry *, const char *);
157 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
158 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
159 struct dl_phdr_info *phdr_info);
160 static uint_fast32_t gnu_hash (const char *);
161 static bool matched_symbol(SymLook *, const Obj_Entry *, Sym_Match_Result *,
162 const unsigned long);
164 void r_debug_state(struct r_debug *, struct link_map *) __noinline;
169 static char *error_message; /* Message for dlerror(), or NULL */
170 struct r_debug r_debug; /* for GDB; */
171 static bool libmap_disable; /* Disable libmap */
172 static bool ld_loadfltr; /* Immediate filters processing */
173 static char *libmap_override; /* Maps to use in addition to libmap.conf */
174 static bool trust; /* False for setuid and setgid programs */
175 static bool dangerous_ld_env; /* True if environment variables have been
176 used to affect the libraries loaded */
177 static const char *ld_bind_now; /* Environment variable for immediate binding */
178 static const char *ld_debug; /* Environment variable for debugging */
179 static const char *ld_library_path; /* Environment variable for search path */
180 static char *ld_preload; /* Environment variable for libraries to
182 static const char *ld_elf_hints_path; /* Environment variable for alternative hints path */
183 static const char *ld_tracing; /* Called from ldd to print libs */
184 static const char *ld_utrace; /* Use utrace() to log events. */
185 static int (*rtld_functrace)( /* Optional function call tracing hook */
186 const char *caller_obj,
187 const char *callee_obj,
188 const char *callee_func,
190 static const Obj_Entry *rtld_functrace_obj; /* Object thereof */
191 static Obj_Entry *obj_list; /* Head of linked list of shared objects */
192 static Obj_Entry **obj_tail; /* Link field of last object in list */
193 static Obj_Entry **preload_tail;
194 static Obj_Entry *obj_main; /* The main program shared object */
195 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
196 static unsigned int obj_count; /* Number of objects in obj_list */
197 static unsigned int obj_loads; /* Number of objects in obj_list */
199 static int ld_resident; /* Non-zero if resident */
200 static const char *ld_ary[LD_ARY_CACHE];
202 static Objlist initlist;
204 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
205 STAILQ_HEAD_INITIALIZER(list_global);
206 static Objlist list_main = /* Objects loaded at program startup */
207 STAILQ_HEAD_INITIALIZER(list_main);
208 static Objlist list_fini = /* Objects needing fini() calls */
209 STAILQ_HEAD_INITIALIZER(list_fini);
211 static Elf_Sym sym_zero; /* For resolving undefined weak refs. */
213 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
215 extern Elf_Dyn _DYNAMIC;
216 #pragma weak _DYNAMIC
217 #ifndef RTLD_IS_DYNAMIC
218 #define RTLD_IS_DYNAMIC() (&_DYNAMIC != NULL)
221 #ifdef ENABLE_OSRELDATE
225 static int stack_prot = PROT_READ | PROT_WRITE | RTLD_DEFAULT_STACK_EXEC;
226 static int max_stack_flags;
229 * These are the functions the dynamic linker exports to application
230 * programs. They are the only symbols the dynamic linker is willing
231 * to export from itself.
233 static func_ptr_type exports[] = {
234 (func_ptr_type) &_rtld_error,
235 (func_ptr_type) &dlclose,
236 (func_ptr_type) &dlerror,
237 (func_ptr_type) &dlopen,
238 (func_ptr_type) &fdlopen,
239 (func_ptr_type) &dlfunc,
240 (func_ptr_type) &dlsym,
241 (func_ptr_type) &dlvsym,
242 (func_ptr_type) &dladdr,
243 (func_ptr_type) &dlinfo,
244 (func_ptr_type) &dl_iterate_phdr,
246 (func_ptr_type) &___tls_get_addr,
248 (func_ptr_type) &__tls_get_addr,
249 (func_ptr_type) &__tls_get_addr_tcb,
250 (func_ptr_type) &_rtld_allocate_tls,
251 (func_ptr_type) &_rtld_free_tls,
252 (func_ptr_type) &_rtld_call_init,
253 (func_ptr_type) &_rtld_thread_init,
254 (func_ptr_type) &_rtld_addr_phdr,
255 (func_ptr_type) &_rtld_get_stack_prot,
260 * Global declarations normally provided by crt1. The dynamic linker is
261 * not built with crt1, so we have to provide them ourselves.
267 * Used to pass argc, argv to init functions.
273 * Globals to control TLS allocation.
275 size_t tls_last_offset; /* Static TLS offset of last module */
276 size_t tls_last_size; /* Static TLS size of last module */
277 size_t tls_static_space; /* Static TLS space allocated */
278 int tls_dtv_generation = 1; /* Used to detect when dtv size changes */
279 int tls_max_index = 1; /* Largest module index allocated */
282 * Fill in a DoneList with an allocation large enough to hold all of
283 * the currently-loaded objects. Keep this as a macro since it calls
284 * alloca and we want that to occur within the scope of the caller.
286 #define donelist_init(dlp) \
287 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
288 assert((dlp)->objs != NULL), \
289 (dlp)->num_alloc = obj_count, \
292 #define UTRACE_DLOPEN_START 1
293 #define UTRACE_DLOPEN_STOP 2
294 #define UTRACE_DLCLOSE_START 3
295 #define UTRACE_DLCLOSE_STOP 4
296 #define UTRACE_LOAD_OBJECT 5
297 #define UTRACE_UNLOAD_OBJECT 6
298 #define UTRACE_ADD_RUNDEP 7
299 #define UTRACE_PRELOAD_FINISHED 8
300 #define UTRACE_INIT_CALL 9
301 #define UTRACE_FINI_CALL 10
304 char sig[4]; /* 'RTLD' */
307 void *mapbase; /* Used for 'parent' and 'init/fini' */
309 int refcnt; /* Used for 'mode' */
310 char name[MAXPATHLEN];
313 #define LD_UTRACE(e, h, mb, ms, r, n) do { \
314 if (ld_utrace != NULL) \
315 ld_utrace_log(e, h, mb, ms, r, n); \
319 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
320 int refcnt, const char *name)
322 struct utrace_rtld ut;
330 ut.mapbase = mapbase;
331 ut.mapsize = mapsize;
333 bzero(ut.name, sizeof(ut.name));
335 strlcpy(ut.name, name, sizeof(ut.name));
336 utrace(&ut, sizeof(ut));
340 * Main entry point for dynamic linking. The first argument is the
341 * stack pointer. The stack is expected to be laid out as described
342 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
343 * Specifically, the stack pointer points to a word containing
344 * ARGC. Following that in the stack is a null-terminated sequence
345 * of pointers to argument strings. Then comes a null-terminated
346 * sequence of pointers to environment strings. Finally, there is a
347 * sequence of "auxiliary vector" entries.
349 * The second argument points to a place to store the dynamic linker's
350 * exit procedure pointer and the third to a place to store the main
353 * The return value is the main program's entry point.
356 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
358 Elf_Auxinfo *aux_info[AT_COUNT];
366 Objlist_Entry *entry;
369 /* marino: DO NOT MOVE THESE VARIABLES TO _rtld
370 Obj_Entry **preload_tail;
372 from global to here. It will break the DWARF2 unwind scheme.
373 The system compilers were unaffected, but not gcc 4.6
377 * On entry, the dynamic linker itself has not been relocated yet.
378 * Be very careful not to reference any global data until after
379 * init_rtld has returned. It is OK to reference file-scope statics
380 * and string constants, and to call static and global functions.
383 /* Find the auxiliary vector on the stack. */
386 sp += argc + 1; /* Skip over arguments and NULL terminator */
390 * If we aren't already resident we have to dig out some more info.
391 * Note that auxinfo does not exist when we are resident.
393 * I'm not sure about the ld_resident check. It seems to read zero
394 * prior to relocation, which is what we want. When running from a
395 * resident copy everything will be relocated so we are definitely
398 if (ld_resident == 0) {
399 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
401 aux = (Elf_Auxinfo *) sp;
403 /* Digest the auxiliary vector. */
404 for (i = 0; i < AT_COUNT; i++)
406 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
407 if (auxp->a_type < AT_COUNT)
408 aux_info[auxp->a_type] = auxp;
411 /* Initialize and relocate ourselves. */
412 assert(aux_info[AT_BASE] != NULL);
413 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
416 ld_index = 0; /* don't use old env cache in case we are resident */
417 __progname = obj_rtld.path;
418 argv0 = argv[0] != NULL ? argv[0] : "(null)";
423 trust = !issetugid();
425 ld_bind_now = _getenv_ld("LD_BIND_NOW");
427 * If the process is tainted, then we un-set the dangerous environment
428 * variables. The process will be marked as tainted until setuid(2)
429 * is called. If any child process calls setuid(2) we do not want any
430 * future processes to honor the potentially un-safe variables.
433 if ( unsetenv("LD_DEBUG")
434 || unsetenv("LD_PRELOAD")
435 || unsetenv("LD_LIBRARY_PATH")
436 || unsetenv("LD_ELF_HINTS_PATH")
437 || unsetenv("LD_LIBMAP")
438 || unsetenv("LD_LIBMAP_DISABLE")
439 || unsetenv("LD_LOADFLTR")
441 _rtld_error("environment corrupt; aborting");
445 ld_debug = _getenv_ld("LD_DEBUG");
446 libmap_disable = _getenv_ld("LD_LIBMAP_DISABLE") != NULL;
447 libmap_override = (char *)_getenv_ld("LD_LIBMAP");
448 ld_library_path = _getenv_ld("LD_LIBRARY_PATH");
449 ld_preload = (char *)_getenv_ld("LD_PRELOAD");
450 ld_elf_hints_path = _getenv_ld("LD_ELF_HINTS_PATH");
451 ld_loadfltr = _getenv_ld("LD_LOADFLTR") != NULL;
452 dangerous_ld_env = (ld_library_path != NULL)
453 || (ld_preload != NULL)
454 || (ld_elf_hints_path != NULL)
456 || (libmap_override != NULL)
459 ld_tracing = _getenv_ld("LD_TRACE_LOADED_OBJECTS");
460 ld_utrace = _getenv_ld("LD_UTRACE");
462 if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0)
463 ld_elf_hints_path = _PATH_ELF_HINTS;
465 if (ld_debug != NULL && *ld_debug != '\0')
467 dbg("%s is initialized, base address = %p", __progname,
468 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
469 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
470 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
472 dbg("initializing thread locks");
476 * If we are resident we can skip work that we have already done.
477 * Note that the stack is reset and there is no Elf_Auxinfo
478 * when running from a resident image, and the static globals setup
479 * between here and resident_skip will have already been setup.
485 * Load the main program, or process its program header if it is
488 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
489 int fd = aux_info[AT_EXECFD]->a_un.a_val;
490 dbg("loading main program");
491 obj_main = map_object(fd, argv0, NULL);
493 if (obj_main == NULL)
495 max_stack_flags = obj->stack_flags;
496 } else { /* Main program already loaded. */
497 const Elf_Phdr *phdr;
501 dbg("processing main program's program header");
502 assert(aux_info[AT_PHDR] != NULL);
503 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
504 assert(aux_info[AT_PHNUM] != NULL);
505 phnum = aux_info[AT_PHNUM]->a_un.a_val;
506 assert(aux_info[AT_PHENT] != NULL);
507 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
508 assert(aux_info[AT_ENTRY] != NULL);
509 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
510 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
514 char buf[MAXPATHLEN];
515 if (aux_info[AT_EXECPATH] != NULL) {
518 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
519 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
520 if (kexecpath[0] == '/')
521 obj_main->path = kexecpath;
522 else if (getcwd(buf, sizeof(buf)) == NULL ||
523 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
524 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
525 obj_main->path = xstrdup(argv0);
527 obj_main->path = xstrdup(buf);
529 char resolved[MAXPATHLEN];
530 dbg("No AT_EXECPATH");
531 if (argv0[0] == '/') {
532 if (realpath(argv0, resolved) != NULL)
533 obj_main->path = xstrdup(resolved);
535 obj_main->path = xstrdup(argv0);
537 if (getcwd(buf, sizeof(buf)) != NULL
538 && strlcat(buf, "/", sizeof(buf)) < sizeof(buf)
539 && strlcat(buf, argv0, sizeof (buf)) < sizeof(buf)
540 && access(buf, R_OK) == 0
541 && realpath(buf, resolved) != NULL)
542 obj_main->path = xstrdup(resolved);
544 obj_main->path = xstrdup(argv0);
547 dbg("obj_main path %s", obj_main->path);
548 obj_main->mainprog = true;
550 if (aux_info[AT_STACKPROT] != NULL &&
551 aux_info[AT_STACKPROT]->a_un.a_val != 0)
552 stack_prot = aux_info[AT_STACKPROT]->a_un.a_val;
555 * Get the actual dynamic linker pathname from the executable if
556 * possible. (It should always be possible.) That ensures that
557 * gdb will find the right dynamic linker even if a non-standard
560 if (obj_main->interp != NULL &&
561 strcmp(obj_main->interp, obj_rtld.path) != 0) {
563 obj_rtld.path = xstrdup(obj_main->interp);
564 __progname = obj_rtld.path;
567 digest_dynamic(obj_main, 0);
568 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d",
569 obj_main->path, obj_main->valid_hash_sysv, obj_main->valid_hash_gnu,
570 obj_main->dynsymcount);
572 linkmap_add(obj_main);
573 linkmap_add(&obj_rtld);
575 /* Link the main program into the list of objects. */
576 *obj_tail = obj_main;
577 obj_tail = &obj_main->next;
581 /* Initialize a fake symbol for resolving undefined weak references. */
582 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
583 sym_zero.st_shndx = SHN_UNDEF;
584 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
587 libmap_disable = (bool)lm_init(libmap_override);
589 dbg("loading LD_PRELOAD libraries");
590 if (load_preload_objects() == -1)
592 preload_tail = obj_tail;
594 dbg("loading needed objects");
595 if (load_needed_objects(obj_main, 0) == -1)
598 /* Make a list of all objects loaded at startup. */
599 for (obj = obj_list; obj != NULL; obj = obj->next) {
600 objlist_push_tail(&list_main, obj);
604 dbg("checking for required versions");
605 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
610 if (ld_tracing) { /* We're done */
611 trace_loaded_objects(obj_main);
615 if (ld_resident) /* XXX clean this up! */
618 if (_getenv_ld("LD_DUMP_REL_PRE") != NULL) {
619 dump_relocations(obj_main);
623 /* setup TLS for main thread */
624 dbg("initializing initial thread local storage");
625 STAILQ_FOREACH(entry, &list_main, link) {
627 * Allocate all the initial objects out of the static TLS
628 * block even if they didn't ask for it.
630 allocate_tls_offset(entry->obj);
633 tls_static_space = tls_last_offset + RTLD_STATIC_TLS_EXTRA;
636 * Do not try to allocate the TLS here, let libc do it itself.
637 * (crt1 for the program will call _init_tls())
640 if (relocate_objects(obj_main,
641 ld_bind_now != NULL && *ld_bind_now != '\0',
642 &obj_rtld, SYMLOOK_EARLY, NULL) == -1)
645 dbg("doing copy relocations");
646 if (do_copy_relocations(obj_main) == -1)
651 if (_getenv_ld("LD_RESIDENT_UNREGISTER_NOW")) {
652 if (exec_sys_unregister(-1) < 0) {
653 dbg("exec_sys_unregister failed %d\n", errno);
656 dbg("exec_sys_unregister success\n");
660 if (_getenv_ld("LD_DUMP_REL_POST") != NULL) {
661 dump_relocations(obj_main);
665 dbg("initializing key program variables");
666 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
667 set_program_var("environ", env);
668 set_program_var("__elf_aux_vector", aux);
670 if (_getenv_ld("LD_RESIDENT_REGISTER_NOW")) {
671 extern void resident_start(void);
673 if (exec_sys_register(resident_start) < 0) {
674 dbg("exec_sys_register failed %d\n", errno);
677 dbg("exec_sys_register success\n");
681 /* Make a list of init functions to call. */
682 objlist_init(&initlist);
683 initlist_add_objects(obj_list, preload_tail, &initlist);
685 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
687 map_stacks_exec(NULL);
689 dbg("resolving ifuncs");
690 if (resolve_objects_ifunc(obj_main,
691 ld_bind_now != NULL && *ld_bind_now != '\0', SYMLOOK_EARLY,
696 * Do NOT call the initlist here, give libc a chance to set up
697 * the initial TLS segment. crt1 will then call _rtld_call_init().
700 dbg("transferring control to program entry point = %p", obj_main->entry);
702 /* Return the exit procedure and the program entry point. */
703 *exit_proc = rtld_exit;
705 return (func_ptr_type) obj_main->entry;
709 * Call the initialization list for dynamically loaded libraries.
710 * (called from crt1.c).
713 _rtld_call_init(void)
715 RtldLockState lockstate;
718 if (!obj_main->note_present && obj_main->valid_hash_gnu) {
720 * The use of a linker script with a PHDRS directive that does not include
721 * PT_NOTE will block the crt_no_init note. In this case we'll look for the
722 * recently added GNU hash dynamic tag which gets built by default. It is
723 * extremely unlikely to find a pre-3.1 binary without a PT_NOTE header and
724 * a gnu hash tag. If gnu hash found, consider binary to use new crt code.
726 obj_main->crt_no_init = true;
727 dbg("Setting crt_no_init without presence of PT_NOTE header");
730 wlock_acquire(rtld_bind_lock, &lockstate);
731 if (obj_main->crt_no_init) {
732 preinitialize_main_object();
736 * Make sure we don't call the main program's init and fini functions
737 * for binaries linked with old crt1 which calls _init itself.
739 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
740 obj_main->init_array = obj_main->fini_array = (Elf_Addr)NULL;
742 objlist_call_init(&initlist, &lockstate);
743 objlist_clear(&initlist);
744 dbg("loading filtees");
745 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
746 if (ld_loadfltr || obj->z_loadfltr)
747 load_filtees(obj, 0, &lockstate);
749 lock_release(rtld_bind_lock, &lockstate);
753 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def)
758 ptr = (void *)make_function_pointer(def, obj);
759 target = ((Elf_Addr (*)(void))ptr)();
760 return ((void *)target);
764 _rtld_bind(Obj_Entry *obj, Elf_Size reloff, void *stack)
768 const Obj_Entry *defobj;
771 RtldLockState lockstate;
773 rlock_acquire(rtld_bind_lock, &lockstate);
774 if (sigsetjmp(lockstate.env, 0) != 0)
775 lock_upgrade(rtld_bind_lock, &lockstate);
777 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
779 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
781 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
782 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL,
786 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
787 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
789 target = (Elf_Addr)(defobj->relocbase + def->st_value);
791 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
792 defobj->strtab + def->st_name, basename(obj->path),
793 (void *)target, basename(defobj->path));
796 * If we have a function call tracing hook, and the
797 * hook would like to keep tracing this one function,
798 * prevent the relocation so we will wind up here
799 * the next time again.
801 * We don't want to functrace calls from the functracer
802 * to avoid recursive loops.
804 if (rtld_functrace != NULL && obj != rtld_functrace_obj) {
805 if (rtld_functrace(obj->path,
807 defobj->strtab + def->st_name,
809 lock_release(rtld_bind_lock, &lockstate);
815 * Write the new contents for the jmpslot. Note that depending on
816 * architecture, the value which we need to return back to the
817 * lazy binding trampoline may or may not be the target
818 * address. The value returned from reloc_jmpslot() is the value
819 * that the trampoline needs.
821 target = reloc_jmpslot(where, target, defobj, obj, rel);
822 lock_release(rtld_bind_lock, &lockstate);
827 * Error reporting function. Use it like printf. If formats the message
828 * into a buffer, and sets things up so that the next call to dlerror()
829 * will return the message.
832 _rtld_error(const char *fmt, ...)
834 static char buf[512];
838 rtld_vsnprintf(buf, sizeof buf, fmt, ap);
844 * Return a dynamically-allocated copy of the current error message, if any.
849 return error_message == NULL ? NULL : xstrdup(error_message);
853 * Restore the current error message from a copy which was previously saved
854 * by errmsg_save(). The copy is freed.
857 errmsg_restore(char *saved_msg)
859 if (saved_msg == NULL)
860 error_message = NULL;
862 _rtld_error("%s", saved_msg);
868 basename(const char *name)
870 const char *p = strrchr(name, '/');
871 return p != NULL ? p + 1 : name;
874 static struct utsname uts;
877 origin_subst_one(char **res, const char *real, const char *kw, const char *subst,
887 subst_len = kw_len = 0;
891 if (subst_len == 0) {
892 subst_len = strlen(subst);
896 *res = xmalloc(PATH_MAX);
899 if ((res1 - *res) + subst_len + (p1 - p) >= PATH_MAX) {
900 _rtld_error("Substitution of %s in %s cannot be performed",
902 if (may_free != NULL)
907 memcpy(res1, p, p1 - p);
909 memcpy(res1, subst, subst_len);
914 if (may_free != NULL)
917 *res = xstrdup(real);
921 if (may_free != NULL)
923 if (strlcat(res1, p, PATH_MAX - (res1 - *res)) >= PATH_MAX) {
933 origin_subst(const char *real, const char *origin_path)
935 char *res1, *res2, *res3, *res4;
937 if (uts.sysname[0] == '\0') {
938 if (uname(&uts) != 0) {
939 _rtld_error("utsname failed: %d", errno);
943 if (!origin_subst_one(&res1, real, "$ORIGIN", origin_path, NULL) ||
944 !origin_subst_one(&res2, res1, "$OSNAME", uts.sysname, res1) ||
945 !origin_subst_one(&res3, res2, "$OSREL", uts.release, res2) ||
946 !origin_subst_one(&res4, res3, "$PLATFORM", uts.machine, res3))
954 const char *msg = dlerror();
958 rtld_fdputstr(STDERR_FILENO, msg);
959 rtld_fdputchar(STDERR_FILENO, '\n');
964 * Process a shared object's DYNAMIC section, and save the important
965 * information in its Obj_Entry structure.
968 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
969 const Elf_Dyn **dyn_soname, const Elf_Dyn **dyn_runpath)
972 Needed_Entry **needed_tail = &obj->needed;
973 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
974 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
975 const Elf_Hashelt *hashtab;
976 const Elf32_Word *hashval;
977 Elf32_Word bkt, nmaskwords;
980 int plttype = DT_REL;
986 obj->bind_now = false;
987 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
988 switch (dynp->d_tag) {
991 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
995 obj->relsize = dynp->d_un.d_val;
999 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
1003 obj->pltrel = (const Elf_Rel *)
1004 (obj->relocbase + dynp->d_un.d_ptr);
1008 obj->pltrelsize = dynp->d_un.d_val;
1012 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
1016 obj->relasize = dynp->d_un.d_val;
1020 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
1024 plttype = dynp->d_un.d_val;
1025 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
1029 obj->symtab = (const Elf_Sym *)
1030 (obj->relocbase + dynp->d_un.d_ptr);
1034 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
1038 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
1042 obj->strsize = dynp->d_un.d_val;
1046 obj->verneed = (const Elf_Verneed *) (obj->relocbase +
1051 obj->verneednum = dynp->d_un.d_val;
1055 obj->verdef = (const Elf_Verdef *) (obj->relocbase +
1060 obj->verdefnum = dynp->d_un.d_val;
1064 obj->versyms = (const Elf_Versym *)(obj->relocbase +
1070 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1072 obj->nbuckets = hashtab[0];
1073 obj->nchains = hashtab[1];
1074 obj->buckets = hashtab + 2;
1075 obj->chains = obj->buckets + obj->nbuckets;
1076 obj->valid_hash_sysv = obj->nbuckets > 0 && obj->nchains > 0 &&
1077 obj->buckets != NULL;
1083 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1085 obj->nbuckets_gnu = hashtab[0];
1086 obj->symndx_gnu = hashtab[1];
1087 nmaskwords = hashtab[2];
1088 bloom_size32 = (__ELF_WORD_SIZE / 32) * nmaskwords;
1089 /* Number of bitmask words is required to be power of 2 */
1090 nmw_power2 = ((nmaskwords & (nmaskwords - 1)) == 0);
1091 obj->maskwords_bm_gnu = nmaskwords - 1;
1092 obj->shift2_gnu = hashtab[3];
1093 obj->bloom_gnu = (Elf_Addr *) (hashtab + 4);
1094 obj->buckets_gnu = hashtab + 4 + bloom_size32;
1095 obj->chain_zero_gnu = obj->buckets_gnu + obj->nbuckets_gnu -
1097 obj->valid_hash_gnu = nmw_power2 && obj->nbuckets_gnu > 0 &&
1098 obj->buckets_gnu != NULL;
1104 Needed_Entry *nep = NEW(Needed_Entry);
1105 nep->name = dynp->d_un.d_val;
1110 needed_tail = &nep->next;
1116 Needed_Entry *nep = NEW(Needed_Entry);
1117 nep->name = dynp->d_un.d_val;
1121 *needed_filtees_tail = nep;
1122 needed_filtees_tail = &nep->next;
1128 Needed_Entry *nep = NEW(Needed_Entry);
1129 nep->name = dynp->d_un.d_val;
1133 *needed_aux_filtees_tail = nep;
1134 needed_aux_filtees_tail = &nep->next;
1139 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
1143 obj->textrel = true;
1147 obj->symbolic = true;
1152 * We have to wait until later to process this, because we
1153 * might not have gotten the address of the string table yet.
1163 *dyn_runpath = dynp;
1167 obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1171 obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1174 case DT_PREINIT_ARRAY:
1175 obj->preinit_array = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1179 obj->init_array = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1183 obj->fini_array = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1186 case DT_PREINIT_ARRAYSZ:
1187 obj->preinit_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1190 case DT_INIT_ARRAYSZ:
1191 obj->init_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1194 case DT_FINI_ARRAYSZ:
1195 obj->fini_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1199 /* XXX - not implemented yet */
1201 dbg("Filling in DT_DEBUG entry");
1202 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
1206 if ((dynp->d_un.d_val & DF_ORIGIN) && trust)
1207 obj->z_origin = true;
1208 if (dynp->d_un.d_val & DF_SYMBOLIC)
1209 obj->symbolic = true;
1210 if (dynp->d_un.d_val & DF_TEXTREL)
1211 obj->textrel = true;
1212 if (dynp->d_un.d_val & DF_BIND_NOW)
1213 obj->bind_now = true;
1214 /*if (dynp->d_un.d_val & DF_STATIC_TLS)
1219 if (dynp->d_un.d_val & DF_1_NOOPEN)
1220 obj->z_noopen = true;
1221 if ((dynp->d_un.d_val & DF_1_ORIGIN) && trust)
1222 obj->z_origin = true;
1223 /*if (dynp->d_un.d_val & DF_1_GLOBAL)
1225 if (dynp->d_un.d_val & DF_1_BIND_NOW)
1226 obj->bind_now = true;
1227 if (dynp->d_un.d_val & DF_1_NODELETE)
1228 obj->z_nodelete = true;
1229 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1230 obj->z_loadfltr = true;
1231 if (dynp->d_un.d_val & DF_1_NODEFLIB)
1232 obj->z_nodeflib = true;
1237 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1244 obj->traced = false;
1246 if (plttype == DT_RELA) {
1247 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1249 obj->pltrelasize = obj->pltrelsize;
1250 obj->pltrelsize = 0;
1253 /* Determine size of dynsym table (equal to nchains of sysv hash) */
1254 if (obj->valid_hash_sysv)
1255 obj->dynsymcount = obj->nchains;
1256 else if (obj->valid_hash_gnu) {
1257 obj->dynsymcount = 0;
1258 for (bkt = 0; bkt < obj->nbuckets_gnu; bkt++) {
1259 if (obj->buckets_gnu[bkt] == 0)
1261 hashval = &obj->chain_zero_gnu[obj->buckets_gnu[bkt]];
1264 while ((*hashval++ & 1u) == 0);
1266 obj->dynsymcount += obj->symndx_gnu;
1271 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1272 const Elf_Dyn *dyn_soname, const Elf_Dyn *dyn_runpath)
1275 if (obj->z_origin && obj->origin_path == NULL) {
1276 obj->origin_path = xmalloc(PATH_MAX);
1277 if (rtld_dirname_abs(obj->path, obj->origin_path) == -1)
1281 if (dyn_runpath != NULL) {
1282 obj->runpath = (char *)obj->strtab + dyn_runpath->d_un.d_val;
1284 obj->runpath = origin_subst(obj->runpath, obj->origin_path);
1286 else if (dyn_rpath != NULL) {
1287 obj->rpath = (char *)obj->strtab + dyn_rpath->d_un.d_val;
1289 obj->rpath = origin_subst(obj->rpath, obj->origin_path);
1292 if (dyn_soname != NULL)
1293 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1297 digest_dynamic(Obj_Entry *obj, int early)
1299 const Elf_Dyn *dyn_rpath;
1300 const Elf_Dyn *dyn_soname;
1301 const Elf_Dyn *dyn_runpath;
1303 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname, &dyn_runpath);
1304 digest_dynamic2(obj, dyn_rpath, dyn_soname, dyn_runpath);
1308 * Process a shared object's program header. This is used only for the
1309 * main program, when the kernel has already loaded the main program
1310 * into memory before calling the dynamic linker. It creates and
1311 * returns an Obj_Entry structure.
1314 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1317 const Elf_Phdr *phlimit = phdr + phnum;
1319 Elf_Addr note_start, note_end;
1323 for (ph = phdr; ph < phlimit; ph++) {
1324 if (ph->p_type != PT_PHDR)
1328 obj->phsize = ph->p_memsz;
1329 obj->relocbase = (caddr_t)phdr - ph->p_vaddr;
1333 obj->stack_flags = PF_X | PF_R | PF_W;
1335 for (ph = phdr; ph < phlimit; ph++) {
1336 switch (ph->p_type) {
1339 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1343 if (nsegs == 0) { /* First load segment */
1344 obj->vaddrbase = trunc_page(ph->p_vaddr);
1345 obj->mapbase = obj->vaddrbase + obj->relocbase;
1346 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
1348 } else { /* Last load segment */
1349 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1356 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1361 obj->tlssize = ph->p_memsz;
1362 obj->tlsalign = ph->p_align;
1363 obj->tlsinitsize = ph->p_filesz;
1364 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1368 obj->stack_flags = ph->p_flags;
1372 obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1373 obj->relro_size = round_page(ph->p_memsz);
1377 obj->note_present = true;
1378 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
1379 note_end = note_start + ph->p_filesz;
1380 digest_notes(obj, note_start, note_end);
1385 _rtld_error("%s: too few PT_LOAD segments", path);
1394 digest_notes(Obj_Entry *obj, Elf_Addr note_start, Elf_Addr note_end)
1396 const Elf_Note *note;
1397 const char *note_name;
1400 for (note = (const Elf_Note *)note_start; (Elf_Addr)note < note_end;
1401 note = (const Elf_Note *)((const char *)(note + 1) +
1402 roundup2(note->n_namesz, sizeof(Elf32_Addr)) +
1403 roundup2(note->n_descsz, sizeof(Elf32_Addr)))) {
1404 if (note->n_namesz != sizeof(NOTE_VENDOR) ||
1405 note->n_descsz != sizeof(int32_t))
1407 if (note->n_type != ABI_NOTETYPE && note->n_type != CRT_NOINIT_NOTETYPE)
1409 note_name = (const char *)(note + 1);
1410 if (strncmp(NOTE_VENDOR, note_name, sizeof(NOTE_VENDOR)) != 0)
1412 switch (note->n_type) {
1414 /* DragonFly osrel note */
1415 p = (uintptr_t)(note + 1);
1416 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1417 obj->osrel = *(const int32_t *)(p);
1418 dbg("note osrel %d", obj->osrel);
1420 case CRT_NOINIT_NOTETYPE:
1421 /* DragonFly 'crt does not call init' note */
1422 obj->crt_no_init = true;
1423 dbg("note crt_no_init");
1430 dlcheck(void *handle)
1434 for (obj = obj_list; obj != NULL; obj = obj->next)
1435 if (obj == (Obj_Entry *) handle)
1438 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1439 _rtld_error("Invalid shared object handle %p", handle);
1446 * If the given object is already in the donelist, return true. Otherwise
1447 * add the object to the list and return false.
1450 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1454 for (i = 0; i < dlp->num_used; i++)
1455 if (dlp->objs[i] == obj)
1458 * Our donelist allocation should always be sufficient. But if
1459 * our threads locking isn't working properly, more shared objects
1460 * could have been loaded since we allocated the list. That should
1461 * never happen, but we'll handle it properly just in case it does.
1463 if (dlp->num_used < dlp->num_alloc)
1464 dlp->objs[dlp->num_used++] = obj;
1469 * Hash function for symbol table lookup. Don't even think about changing
1470 * this. It is specified by the System V ABI.
1473 elf_hash(const char *name)
1475 const unsigned char *p = (const unsigned char *) name;
1476 unsigned long h = 0;
1479 while (*p != '\0') {
1480 h = (h << 4) + *p++;
1481 if ((g = h & 0xf0000000) != 0)
1489 * The GNU hash function is the Daniel J. Bernstein hash clipped to 32 bits
1490 * unsigned in case it's implemented with a wider type.
1492 static uint_fast32_t
1493 gnu_hash (const char *s)
1495 uint_fast32_t h = 5381;
1496 for (unsigned char c = *s; c != '\0'; c = *++s)
1498 return h & 0xffffffff;
1502 * Find the library with the given name, and return its full pathname.
1503 * The returned string is dynamically allocated. Generates an error
1504 * message and returns NULL if the library cannot be found.
1506 * If the second argument is non-NULL, then it refers to an already-
1507 * loaded shared object, whose library search path will be searched.
1509 * The search order is:
1510 * DT_RPATH in the referencing file _unless_ DT_RUNPATH is present (1)
1511 * DT_RPATH of the main object if DSO without defined DT_RUNPATH (1)
1513 * DT_RUNPATH in the referencing file
1514 * ldconfig hints (if -z nodefaultlib, filter out /usr/lib from list)
1515 * /usr/lib _unless_ the referencing file is linked with -z nodefaultlib
1517 * (1) Handled in digest_dynamic2 - rpath left NULL if runpath defined.
1520 find_library(const char *xname, const Obj_Entry *refobj)
1524 bool 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(xname, refobj->origin_path);
1535 return xstrdup(xname);
1538 if (libmap_disable || !objgiven ||
1539 (name = lm_find(refobj->path, xname)) == NULL)
1540 name = (char *)xname;
1542 dbg(" Searching for \"%s\"", name);
1545 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
1546 (objgiven && (refobj->runpath == NULL) && (refobj != obj_main) &&
1547 (pathname = search_library_path(name, obj_main->rpath)) != NULL) ||
1548 (pathname = search_library_path(name, ld_library_path)) != NULL ||
1550 (pathname = search_library_path(name, refobj->runpath)) != NULL) ||
1551 (pathname = search_library_path(name, gethints(refobj->z_nodeflib)))
1553 (objgiven && !refobj->z_nodeflib &&
1554 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL))
1557 if(objgiven && refobj->path != NULL) {
1558 _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
1559 name, basename(refobj->path));
1561 _rtld_error("Shared object \"%s\" not found", name);
1567 * Given a symbol number in a referencing object, find the corresponding
1568 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1569 * no definition was found. Returns a pointer to the Obj_Entry of the
1570 * defining object via the reference parameter DEFOBJ_OUT.
1573 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1574 const Obj_Entry **defobj_out, int flags, SymCache *cache,
1575 RtldLockState *lockstate)
1579 const Obj_Entry *defobj;
1585 * If we have already found this symbol, get the information from
1588 if (symnum >= refobj->dynsymcount)
1589 return NULL; /* Bad object */
1590 if (cache != NULL && cache[symnum].sym != NULL) {
1591 *defobj_out = cache[symnum].obj;
1592 return cache[symnum].sym;
1595 ref = refobj->symtab + symnum;
1596 name = refobj->strtab + ref->st_name;
1601 * We don't have to do a full scale lookup if the symbol is local.
1602 * We know it will bind to the instance in this load module; to
1603 * which we already have a pointer (ie ref). By not doing a lookup,
1604 * we not only improve performance, but it also avoids unresolvable
1605 * symbols when local symbols are not in the hash table.
1607 * This might occur for TLS module relocations, which simply use
1610 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1611 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1612 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1615 symlook_init(&req, name);
1617 req.ventry = fetch_ventry(refobj, symnum);
1618 req.lockstate = lockstate;
1619 res = symlook_default(&req, refobj);
1622 defobj = req.defobj_out;
1630 * If we found no definition and the reference is weak, treat the
1631 * symbol as having the value zero.
1633 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1639 *defobj_out = defobj;
1640 /* Record the information in the cache to avoid subsequent lookups. */
1641 if (cache != NULL) {
1642 cache[symnum].sym = def;
1643 cache[symnum].obj = defobj;
1646 if (refobj != &obj_rtld)
1647 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1653 * Return the search path from the ldconfig hints file, reading it if
1654 * necessary. Returns NULL if there are problems with the hints file,
1655 * or if the search path there is empty.
1656 * If DF_1_NODEFLIB flag set, omit STANDARD_LIBRARY_PATH directories
1659 gethints(bool nostdlib)
1661 static char *hints, *filtered_path;
1662 struct elfhints_hdr hdr;
1663 struct fill_search_info_args sargs, hargs;
1664 struct dl_serinfo smeta, hmeta, *SLPinfo, *hintinfo;
1665 struct dl_serpath *SLPpath, *hintpath;
1667 unsigned int SLPndx, hintndx, fndx, fcount;
1672 if (hints == NULL) {
1673 /* Keep from trying again in case the hints file is bad. */
1676 if ((fd = open(ld_elf_hints_path, O_RDONLY)) == -1)
1678 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1679 hdr.magic != ELFHINTS_MAGIC || hdr.version != 1) {
1683 p = xmalloc(hdr.dirlistlen + 1);
1684 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1685 read(fd, p, hdr.dirlistlen + 1) != (ssize_t)hdr.dirlistlen + 1) {
1695 return (hints[0] != '\0' ? hints : NULL);
1697 if (filtered_path != NULL)
1700 smeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1702 hmeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1705 sargs.request = RTLD_DI_SERINFOSIZE;
1706 sargs.serinfo = &smeta;
1707 hargs.request = RTLD_DI_SERINFOSIZE;
1708 hargs.serinfo = &hmeta;
1710 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &sargs);
1711 path_enumerate(p, fill_search_info, &hargs);
1713 SLPinfo = malloc(smeta.dls_size);
1714 hintinfo = malloc(hmeta.dls_size);
1716 sargs.request = RTLD_DI_SERINFO;
1717 sargs.serinfo = SLPinfo;
1718 sargs.serpath = &SLPinfo->dls_serpath[0];
1719 sargs.strspace = (char *)&SLPinfo->dls_serpath[smeta.dls_cnt];
1721 hargs.request = RTLD_DI_SERINFO;
1722 hargs.serinfo = hintinfo;
1723 hargs.serpath = &hintinfo->dls_serpath[0];
1724 hargs.strspace = (char *)&hintinfo->dls_serpath[hmeta.dls_cnt];
1726 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &sargs);
1727 path_enumerate(p, fill_search_info, &hargs);
1731 filtered_path = xmalloc(hdr.dirlistlen + 1);
1732 hintpath = &hintinfo->dls_serpath[0];
1733 for (hintndx = 0; hintndx < hmeta.dls_cnt; hintndx++, hintpath++) {
1735 SLPpath = &SLPinfo->dls_serpath[0];
1736 for (SLPndx = 0; SLPndx < smeta.dls_cnt; SLPndx++, SLPpath++) {
1737 if (!strcmp(hintpath->dls_name, SLPpath->dls_name)) {
1745 filtered_path[fndx] = ':';
1749 flen = strlen(hintpath->dls_name);
1750 strncpy((filtered_path + fndx), hintpath->dls_name, flen);
1753 filtered_path[fndx] = '\0';
1759 return (filtered_path[0] != '\0' ? filtered_path : NULL);
1763 init_dag(Obj_Entry *root)
1765 const Needed_Entry *needed;
1766 const Objlist_Entry *elm;
1769 if (root->dag_inited)
1771 donelist_init(&donelist);
1773 /* Root object belongs to own DAG. */
1774 objlist_push_tail(&root->dldags, root);
1775 objlist_push_tail(&root->dagmembers, root);
1776 donelist_check(&donelist, root);
1779 * Add dependencies of root object to DAG in breadth order
1780 * by exploiting the fact that each new object get added
1781 * to the tail of the dagmembers list.
1783 STAILQ_FOREACH(elm, &root->dagmembers, link) {
1784 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
1785 if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
1787 objlist_push_tail(&needed->obj->dldags, root);
1788 objlist_push_tail(&root->dagmembers, needed->obj);
1791 root->dag_inited = true;
1795 process_nodelete(Obj_Entry *root)
1797 const Objlist_Entry *elm;
1800 * Walk over object DAG and process every dependent object that
1801 * is marked as DF_1_NODELETE. They need to grow their own DAG,
1802 * which then should have its reference upped separately.
1804 STAILQ_FOREACH(elm, &root->dagmembers, link) {
1805 if (elm->obj != NULL && elm->obj->z_nodelete &&
1806 !elm->obj->ref_nodel) {
1807 dbg("obj %s nodelete", elm->obj->path);
1810 elm->obj->ref_nodel = true;
1816 * Initialize the dynamic linker. The argument is the address at which
1817 * the dynamic linker has been mapped into memory. The primary task of
1818 * this function is to relocate the dynamic linker.
1821 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
1823 Obj_Entry objtmp; /* Temporary rtld object */
1824 const Elf_Dyn *dyn_rpath;
1825 const Elf_Dyn *dyn_soname;
1826 const Elf_Dyn *dyn_runpath;
1829 * Conjure up an Obj_Entry structure for the dynamic linker.
1831 * The "path" member can't be initialized yet because string constants
1832 * cannot yet be accessed. Below we will set it correctly.
1834 memset(&objtmp, 0, sizeof(objtmp));
1837 objtmp.mapbase = mapbase;
1839 objtmp.relocbase = mapbase;
1841 if (RTLD_IS_DYNAMIC()) {
1842 objtmp.dynamic = rtld_dynamic(&objtmp);
1843 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname, &dyn_runpath);
1844 assert(objtmp.needed == NULL);
1845 assert(!objtmp.textrel);
1848 * Temporarily put the dynamic linker entry into the object list, so
1849 * that symbols can be found.
1852 relocate_objects(&objtmp, true, &objtmp, 0, NULL);
1855 /* Initialize the object list. */
1856 obj_tail = &obj_list;
1858 /* Now that non-local variables can be accesses, copy out obj_rtld. */
1859 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1861 #ifdef ENABLE_OSRELDATE
1862 if (aux_info[AT_OSRELDATE] != NULL)
1863 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
1866 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname, dyn_runpath);
1868 /* Replace the path with a dynamically allocated copy. */
1869 obj_rtld.path = xstrdup(PATH_RTLD);
1871 r_debug.r_brk = r_debug_state;
1872 r_debug.r_state = RT_CONSISTENT;
1876 * Add the init functions from a needed object list (and its recursive
1877 * needed objects) to "list". This is not used directly; it is a helper
1878 * function for initlist_add_objects(). The write lock must be held
1879 * when this function is called.
1882 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1884 /* Recursively process the successor needed objects. */
1885 if (needed->next != NULL)
1886 initlist_add_neededs(needed->next, list);
1888 /* Process the current needed object. */
1889 if (needed->obj != NULL)
1890 initlist_add_objects(needed->obj, &needed->obj->next, list);
1894 * Scan all of the DAGs rooted in the range of objects from "obj" to
1895 * "tail" and add their init functions to "list". This recurses over
1896 * the DAGs and ensure the proper init ordering such that each object's
1897 * needed libraries are initialized before the object itself. At the
1898 * same time, this function adds the objects to the global finalization
1899 * list "list_fini" in the opposite order. The write lock must be
1900 * held when this function is called.
1903 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1906 if (obj->init_scanned || obj->init_done)
1908 obj->init_scanned = true;
1910 /* Recursively process the successor objects. */
1911 if (&obj->next != tail)
1912 initlist_add_objects(obj->next, tail, list);
1914 /* Recursively process the needed objects. */
1915 if (obj->needed != NULL)
1916 initlist_add_neededs(obj->needed, list);
1917 if (obj->needed_filtees != NULL)
1918 initlist_add_neededs(obj->needed_filtees, list);
1919 if (obj->needed_aux_filtees != NULL)
1920 initlist_add_neededs(obj->needed_aux_filtees, list);
1922 /* Add the object to the init list. */
1923 if (obj->preinit_array != (Elf_Addr)NULL || obj->init != (Elf_Addr)NULL ||
1924 obj->init_array != (Elf_Addr)NULL)
1925 objlist_push_tail(list, obj);
1927 /* Add the object to the global fini list in the reverse order. */
1928 if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL)
1929 && !obj->on_fini_list) {
1930 objlist_push_head(&list_fini, obj);
1931 obj->on_fini_list = true;
1936 #define FPTR_TARGET(f) ((Elf_Addr) (f))
1940 is_exported(const Elf_Sym *def)
1943 const func_ptr_type *p;
1945 value = (Elf_Addr)(obj_rtld.relocbase + def->st_value);
1946 for (p = exports; *p != NULL; p++)
1947 if (FPTR_TARGET(*p) == value)
1953 free_needed_filtees(Needed_Entry *n)
1955 Needed_Entry *needed, *needed1;
1957 for (needed = n; needed != NULL; needed = needed->next) {
1958 if (needed->obj != NULL) {
1959 dlclose(needed->obj);
1963 for (needed = n; needed != NULL; needed = needed1) {
1964 needed1 = needed->next;
1970 unload_filtees(Obj_Entry *obj)
1973 free_needed_filtees(obj->needed_filtees);
1974 obj->needed_filtees = NULL;
1975 free_needed_filtees(obj->needed_aux_filtees);
1976 obj->needed_aux_filtees = NULL;
1977 obj->filtees_loaded = false;
1981 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags,
1982 RtldLockState *lockstate)
1985 for (; needed != NULL; needed = needed->next) {
1986 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
1987 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
1988 RTLD_LOCAL, lockstate);
1993 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
1996 lock_restart_for_upgrade(lockstate);
1997 if (!obj->filtees_loaded) {
1998 load_filtee1(obj, obj->needed_filtees, flags, lockstate);
1999 load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate);
2000 obj->filtees_loaded = true;
2005 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
2009 for (; needed != NULL; needed = needed->next) {
2010 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
2011 flags & ~RTLD_LO_NOLOAD);
2012 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
2019 * Given a shared object, traverse its list of needed objects, and load
2020 * each of them. Returns 0 on success. Generates an error message and
2021 * returns -1 on failure.
2024 load_needed_objects(Obj_Entry *first, int flags)
2028 for (obj = first; obj != NULL; obj = obj->next) {
2029 if (process_needed(obj, obj->needed, flags) == -1)
2036 load_preload_objects(void)
2038 char *p = ld_preload;
2039 static const char delim[] = " \t:;";
2044 p += strspn(p, delim);
2045 while (*p != '\0') {
2046 size_t len = strcspn(p, delim);
2054 obj = load_object(p, -1, NULL, 0);
2056 return -1; /* XXX - cleanup */
2059 p += strspn(p, delim);
2061 /* Check for the magic tracing function */
2062 symlook_init(&req, RTLD_FUNCTRACE);
2063 res = symlook_obj(&req, obj);
2065 rtld_functrace = (void *)(req.defobj_out->relocbase +
2066 req.sym_out->st_value);
2067 rtld_functrace_obj = req.defobj_out;
2070 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
2075 printable_path(const char *path)
2078 return (path == NULL ? "<unknown>" : path);
2082 * Load a shared object into memory, if it is not already loaded. The
2083 * object may be specified by name or by user-supplied file descriptor
2084 * fd_u. In the later case, the fd_u descriptor is not closed, but its
2087 * Returns a pointer to the Obj_Entry for the object. Returns NULL
2091 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
2099 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
2100 if (object_match_name(obj, name))
2104 path = find_library(name, refobj);
2111 * If we didn't find a match by pathname, or the name is not
2112 * supplied, open the file and check again by device and inode.
2113 * This avoids false mismatches caused by multiple links or ".."
2116 * To avoid a race, we open the file and use fstat() rather than
2121 if ((fd = open(path, O_RDONLY)) == -1) {
2122 _rtld_error("Cannot open \"%s\"", path);
2129 _rtld_error("Cannot dup fd");
2134 if (fstat(fd, &sb) == -1) {
2135 _rtld_error("Cannot fstat \"%s\"", printable_path(path));
2140 for (obj = obj_list->next; obj != NULL; obj = obj->next)
2141 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
2143 if (obj != NULL && name != NULL) {
2144 object_add_name(obj, name);
2149 if (flags & RTLD_LO_NOLOAD) {
2155 /* First use of this object, so we must map it in */
2156 obj = do_load_object(fd, name, path, &sb, flags);
2165 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
2172 * but first, make sure that environment variables haven't been
2173 * used to circumvent the noexec flag on a filesystem.
2175 if (dangerous_ld_env) {
2176 if (fstatfs(fd, &fs) != 0) {
2177 _rtld_error("Cannot fstatfs \"%s\"", printable_path(path));
2180 if (fs.f_flags & MNT_NOEXEC) {
2181 _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
2185 dbg("loading \"%s\"", printable_path(path));
2186 obj = map_object(fd, printable_path(path), sbp);
2191 * If DT_SONAME is present in the object, digest_dynamic2 already
2192 * added it to the object names.
2195 object_add_name(obj, name);
2197 digest_dynamic(obj, 0);
2198 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path,
2199 obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount);
2200 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
2202 dbg("refusing to load non-loadable \"%s\"", obj->path);
2203 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
2204 munmap(obj->mapbase, obj->mapsize);
2210 obj_tail = &obj->next;
2213 linkmap_add(obj); /* for GDB & dlinfo() */
2214 max_stack_flags |= obj->stack_flags;
2216 dbg(" %p .. %p: %s", obj->mapbase,
2217 obj->mapbase + obj->mapsize - 1, obj->path);
2219 dbg(" WARNING: %s has impure text", obj->path);
2220 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
2227 obj_from_addr(const void *addr)
2231 for (obj = obj_list; obj != NULL; obj = obj->next) {
2232 if (addr < (void *) obj->mapbase)
2234 if (addr < (void *) (obj->mapbase + obj->mapsize))
2241 * Call the finalization functions for each of the objects in "list"
2242 * belonging to the DAG of "root" and referenced once. If NULL "root"
2243 * is specified, every finalization function will be called regardless
2244 * of the reference count and the list elements won't be freed. All of
2245 * the objects are expected to have non-NULL fini functions.
2248 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
2252 Elf_Addr *fini_addr;
2255 assert(root == NULL || root->refcount == 1);
2258 * Preserve the current error message since a fini function might
2259 * call into the dynamic linker and overwrite it.
2261 saved_msg = errmsg_save();
2263 STAILQ_FOREACH(elm, list, link) {
2264 if (root != NULL && (elm->obj->refcount != 1 ||
2265 objlist_find(&root->dagmembers, elm->obj) == NULL))
2268 /* Remove object from fini list to prevent recursive invocation. */
2269 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2271 * XXX: If a dlopen() call references an object while the
2272 * fini function is in progress, we might end up trying to
2273 * unload the referenced object in dlclose() or the object
2274 * won't be unloaded although its fini function has been
2277 lock_release(rtld_bind_lock, lockstate);
2280 * It is legal to have both DT_FINI and DT_FINI_ARRAY defined. When this
2281 * happens, DT_FINI_ARRAY is processed first, and it is also processed
2282 * backwards. It is possible to encounter DT_FINI_ARRAY elements with
2283 * values of 0 or 1, but they need to be ignored.
2285 fini_addr = (Elf_Addr *)elm->obj->fini_array;
2286 if (fini_addr != NULL && elm->obj->fini_array_num > 0) {
2287 for (index = elm->obj->fini_array_num - 1; index >= 0; index--) {
2288 if (fini_addr[index] != 0 && fini_addr[index] != 1) {
2289 dbg("calling fini array function for %s at %p",
2290 elm->obj->path, (void *)fini_addr[index]);
2291 LD_UTRACE(UTRACE_FINI_CALL, elm->obj,
2292 (void *)fini_addr[index], 0, 0, elm->obj->path);
2293 call_initfini_pointer(elm->obj, fini_addr[index]);
2297 if (elm->obj->fini != (Elf_Addr)NULL) {
2298 dbg("calling fini function for %s at %p", elm->obj->path,
2299 (void *)elm->obj->fini);
2300 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini,
2301 0, 0, elm->obj->path);
2302 call_initfini_pointer(elm->obj, elm->obj->fini);
2304 wlock_acquire(rtld_bind_lock, lockstate);
2305 /* No need to free anything if process is going down. */
2309 * We must restart the list traversal after every fini call
2310 * because a dlclose() call from the fini function or from
2311 * another thread might have modified the reference counts.
2315 } while (elm != NULL);
2316 errmsg_restore(saved_msg);
2320 * If the main program is defined with a .preinit_array section, call
2321 * each function in order. This must occur before the initialization
2322 * of any shared object or the main program.
2325 preinitialize_main_object (void)
2327 Elf_Addr *preinit_addr;
2330 preinit_addr = (Elf_Addr *)obj_main->preinit_array;
2331 if (preinit_addr == NULL)
2334 for (index = 0; index < obj_main->preinit_array_num; index++) {
2335 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) {
2336 dbg("calling preinit function for %s at %p", obj_main->path,
2337 (void *)preinit_addr[index]);
2338 LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index],
2339 0, 0, obj_main->path);
2340 call_init_pointer(obj_main, preinit_addr[index]);
2346 * Call the initialization functions for each of the objects in
2347 * "list". All of the objects are expected to have non-NULL init
2351 objlist_call_init(Objlist *list, RtldLockState *lockstate)
2356 Elf_Addr *init_addr;
2360 * Clean init_scanned flag so that objects can be rechecked and
2361 * possibly initialized earlier if any of vectors called below
2362 * cause the change by using dlopen.
2364 for (obj = obj_list; obj != NULL; obj = obj->next)
2365 obj->init_scanned = false;
2368 * Preserve the current error message since an init function might
2369 * call into the dynamic linker and overwrite it.
2371 saved_msg = errmsg_save();
2372 STAILQ_FOREACH(elm, list, link) {
2373 if (elm->obj->init_done) /* Initialized early. */
2377 * Race: other thread might try to use this object before current
2378 * one completes the initilization. Not much can be done here
2379 * without better locking.
2381 elm->obj->init_done = true;
2382 lock_release(rtld_bind_lock, lockstate);
2385 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined. When
2386 * this happens, DT_INIT is processed first. It is possible to
2387 * encounter DT_INIT_ARRAY elements with values of 0 or 1, but they
2388 * need to be ignored.
2390 if (elm->obj->init != (Elf_Addr)NULL) {
2391 dbg("calling init function for %s at %p", elm->obj->path,
2392 (void *)elm->obj->init);
2393 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init,
2394 0, 0, elm->obj->path);
2395 call_initfini_pointer(elm->obj, elm->obj->init);
2397 init_addr = (Elf_Addr *)elm->obj->init_array;
2398 if (init_addr != NULL) {
2399 for (index = 0; index < elm->obj->init_array_num; index++) {
2400 if (init_addr[index] != 0 && init_addr[index] != 1) {
2401 dbg("calling init array function for %s at %p", elm->obj->path,
2402 (void *)init_addr[index]);
2403 LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
2404 (void *)init_addr[index], 0, 0, elm->obj->path);
2405 call_init_pointer(elm->obj, init_addr[index]);
2409 wlock_acquire(rtld_bind_lock, lockstate);
2411 errmsg_restore(saved_msg);
2415 objlist_clear(Objlist *list)
2419 while (!STAILQ_EMPTY(list)) {
2420 elm = STAILQ_FIRST(list);
2421 STAILQ_REMOVE_HEAD(list, link);
2426 static Objlist_Entry *
2427 objlist_find(Objlist *list, const Obj_Entry *obj)
2431 STAILQ_FOREACH(elm, list, link)
2432 if (elm->obj == obj)
2438 objlist_init(Objlist *list)
2444 objlist_push_head(Objlist *list, Obj_Entry *obj)
2448 elm = NEW(Objlist_Entry);
2450 STAILQ_INSERT_HEAD(list, elm, link);
2454 objlist_push_tail(Objlist *list, Obj_Entry *obj)
2458 elm = NEW(Objlist_Entry);
2460 STAILQ_INSERT_TAIL(list, elm, link);
2464 objlist_remove(Objlist *list, Obj_Entry *obj)
2468 if ((elm = objlist_find(list, obj)) != NULL) {
2469 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2475 * Relocate dag rooted in the specified object.
2476 * Returns 0 on success, or -1 on failure.
2480 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj,
2481 int flags, RtldLockState *lockstate)
2487 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2488 error = relocate_object(elm->obj, bind_now, rtldobj, flags,
2497 * Relocate single object.
2498 * Returns 0 on success, or -1 on failure.
2502 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
2503 int flags, RtldLockState *lockstate)
2507 obj->relocated = true;
2509 dbg("relocating \"%s\"", obj->path);
2511 if (obj->symtab == NULL || obj->strtab == NULL ||
2512 !(obj->valid_hash_sysv || obj->valid_hash_gnu)) {
2513 _rtld_error("%s: Shared object has no run-time symbol table",
2519 /* There are relocations to the write-protected text segment. */
2520 if (mprotect(obj->mapbase, obj->textsize,
2521 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
2522 _rtld_error("%s: Cannot write-enable text segment: %s",
2523 obj->path, rtld_strerror(errno));
2528 /* Process the non-PLT relocations. */
2529 if (reloc_non_plt(obj, rtldobj, flags, lockstate))
2533 * Reprotect the text segment. Make sure it is included in the
2534 * core dump since we modified it. This unfortunately causes the
2535 * entire text segment to core-out but we don't have much of a
2536 * choice. We could try to only reenable core dumps on pages
2537 * in which relocations occured but that is likely most of the text
2538 * pages anyway, and even that would not work because the rest of
2539 * the text pages would wind up as a read-only OBJT_DEFAULT object
2540 * (created due to our modifications) backed by the original OBJT_VNODE
2541 * object, and the ELF coredump code is currently only able to dump
2542 * vnode records for pure vnode-backed mappings, not vnode backings
2543 * to memory objects.
2546 madvise(obj->mapbase, obj->textsize, MADV_CORE);
2547 if (mprotect(obj->mapbase, obj->textsize,
2548 PROT_READ|PROT_EXEC) == -1) {
2549 _rtld_error("%s: Cannot write-protect text segment: %s",
2550 obj->path, rtld_strerror(errno));
2556 /* Set the special PLT or GOT entries. */
2559 /* Process the PLT relocations. */
2560 if (reloc_plt(obj) == -1)
2562 /* Relocate the jump slots if we are doing immediate binding. */
2563 if (obj->bind_now || bind_now)
2564 if (reloc_jmpslots(obj, flags, lockstate) == -1)
2568 * Set up the magic number and version in the Obj_Entry. These
2569 * were checked in the crt1.o from the original ElfKit, so we
2570 * set them for backward compatibility.
2572 obj->magic = RTLD_MAGIC;
2573 obj->version = RTLD_VERSION;
2576 * Set relocated data to read-only status if protection specified
2579 if (obj->relro_size) {
2580 if (mprotect(obj->relro_page, obj->relro_size, PROT_READ) == -1) {
2581 _rtld_error("%s: Cannot enforce relro relocation: %s",
2582 obj->path, rtld_strerror(errno));
2590 * Relocate newly-loaded shared objects. The argument is a pointer to
2591 * the Obj_Entry for the first such object. All objects from the first
2592 * to the end of the list of objects are relocated. Returns 0 on success,
2596 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
2597 int flags, RtldLockState *lockstate)
2602 for (error = 0, obj = first; obj != NULL; obj = obj->next) {
2603 error = relocate_object(obj, bind_now, rtldobj, flags,
2612 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
2613 * referencing STT_GNU_IFUNC symbols is postponed till the other
2614 * relocations are done. The indirect functions specified as
2615 * ifunc are allowed to call other symbols, so we need to have
2616 * objects relocated before asking for resolution from indirects.
2618 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
2619 * instead of the usual lazy handling of PLT slots. It is
2620 * consistent with how GNU does it.
2623 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags,
2624 RtldLockState *lockstate)
2626 if (obj->irelative && reloc_iresolve(obj, lockstate) == -1)
2628 if ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
2629 reloc_gnu_ifunc(obj, flags, lockstate) == -1)
2635 resolve_objects_ifunc(Obj_Entry *first, bool bind_now, int flags,
2636 RtldLockState *lockstate)
2640 for (obj = first; obj != NULL; obj = obj->next) {
2641 if (resolve_object_ifunc(obj, bind_now, flags, lockstate) == -1)
2648 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags,
2649 RtldLockState *lockstate)
2653 STAILQ_FOREACH(elm, list, link) {
2654 if (resolve_object_ifunc(elm->obj, bind_now, flags,
2662 * Cleanup procedure. It will be called (by the atexit mechanism) just
2663 * before the process exits.
2668 RtldLockState lockstate;
2670 wlock_acquire(rtld_bind_lock, &lockstate);
2672 objlist_call_fini(&list_fini, NULL, &lockstate);
2673 /* No need to remove the items from the list, since we are exiting. */
2674 if (!libmap_disable)
2676 lock_release(rtld_bind_lock, &lockstate);
2680 path_enumerate(const char *path, path_enum_proc callback, void *arg)
2685 path += strspn(path, ":;");
2686 while (*path != '\0') {
2690 len = strcspn(path, ":;");
2691 res = callback(path, len, arg);
2697 path += strspn(path, ":;");
2703 struct try_library_args {
2711 try_library_path(const char *dir, size_t dirlen, void *param)
2713 struct try_library_args *arg;
2716 if (*dir == '/' || trust) {
2719 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
2722 pathname = arg->buffer;
2723 strncpy(pathname, dir, dirlen);
2724 pathname[dirlen] = '/';
2725 strcpy(pathname + dirlen + 1, arg->name);
2727 dbg(" Trying \"%s\"", pathname);
2728 if (access(pathname, F_OK) == 0) { /* We found it */
2729 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
2730 strcpy(pathname, arg->buffer);
2738 search_library_path(const char *name, const char *path)
2741 struct try_library_args arg;
2747 arg.namelen = strlen(name);
2748 arg.buffer = xmalloc(PATH_MAX);
2749 arg.buflen = PATH_MAX;
2751 p = path_enumerate(path, try_library_path, &arg);
2759 dlclose(void *handle)
2762 RtldLockState lockstate;
2764 wlock_acquire(rtld_bind_lock, &lockstate);
2765 root = dlcheck(handle);
2767 lock_release(rtld_bind_lock, &lockstate);
2770 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
2773 /* Unreference the object and its dependencies. */
2774 root->dl_refcount--;
2776 if (root->refcount == 1) {
2778 * The object will be no longer referenced, so we must unload it.
2779 * First, call the fini functions.
2781 objlist_call_fini(&list_fini, root, &lockstate);
2785 /* Finish cleaning up the newly-unreferenced objects. */
2786 GDB_STATE(RT_DELETE,&root->linkmap);
2787 unload_object(root);
2788 GDB_STATE(RT_CONSISTENT,NULL);
2792 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
2793 lock_release(rtld_bind_lock, &lockstate);
2800 char *msg = error_message;
2801 error_message = NULL;
2806 dlopen(const char *name, int mode)
2809 return (rtld_dlopen(name, -1, mode));
2813 fdlopen(int fd, int mode)
2816 return (rtld_dlopen(NULL, fd, mode));
2820 rtld_dlopen(const char *name, int fd, int mode)
2822 RtldLockState lockstate;
2825 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
2826 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
2827 if (ld_tracing != NULL) {
2828 rlock_acquire(rtld_bind_lock, &lockstate);
2829 if (sigsetjmp(lockstate.env, 0) != 0)
2830 lock_upgrade(rtld_bind_lock, &lockstate);
2831 environ = (char **)*get_program_var_addr("environ", &lockstate);
2832 lock_release(rtld_bind_lock, &lockstate);
2834 lo_flags = RTLD_LO_DLOPEN;
2835 if (mode & RTLD_NODELETE)
2836 lo_flags |= RTLD_LO_NODELETE;
2837 if (mode & RTLD_NOLOAD)
2838 lo_flags |= RTLD_LO_NOLOAD;
2839 if (ld_tracing != NULL)
2840 lo_flags |= RTLD_LO_TRACE;
2842 return (dlopen_object(name, fd, obj_main, lo_flags,
2843 mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL));
2847 dlopen_cleanup(Obj_Entry *obj)
2852 if (obj->refcount == 0)
2857 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
2858 int mode, RtldLockState *lockstate)
2860 Obj_Entry **old_obj_tail;
2863 RtldLockState mlockstate;
2866 objlist_init(&initlist);
2868 if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) {
2869 wlock_acquire(rtld_bind_lock, &mlockstate);
2870 lockstate = &mlockstate;
2872 GDB_STATE(RT_ADD,NULL);
2874 old_obj_tail = obj_tail;
2876 if (name == NULL && fd == -1) {
2880 obj = load_object(name, fd, refobj, lo_flags);
2885 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
2886 objlist_push_tail(&list_global, obj);
2887 if (*old_obj_tail != NULL) { /* We loaded something new. */
2888 assert(*old_obj_tail == obj);
2889 result = load_needed_objects(obj,
2890 lo_flags & (RTLD_LO_DLOPEN | RTLD_LO_EARLY));
2894 result = rtld_verify_versions(&obj->dagmembers);
2895 if (result != -1 && ld_tracing)
2897 if (result == -1 || relocate_object_dag(obj,
2898 (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld,
2899 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
2901 dlopen_cleanup(obj);
2903 } else if (lo_flags & RTLD_LO_EARLY) {
2905 * Do not call the init functions for early loaded
2906 * filtees. The image is still not initialized enough
2909 * Our object is found by the global object list and
2910 * will be ordered among all init calls done right
2911 * before transferring control to main.
2914 /* Make list of init functions to call. */
2915 initlist_add_objects(obj, &obj->next, &initlist);
2918 * Process all no_delete objects here, given them own
2919 * DAGs to prevent their dependencies from being unloaded.
2920 * This has to be done after we have loaded all of the
2921 * dependencies, so that we do not miss any.
2924 process_nodelete(obj);
2927 * Bump the reference counts for objects on this DAG. If
2928 * this is the first dlopen() call for the object that was
2929 * already loaded as a dependency, initialize the dag
2935 if ((lo_flags & RTLD_LO_TRACE) != 0)
2938 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
2939 obj->z_nodelete) && !obj->ref_nodel) {
2940 dbg("obj %s nodelete", obj->path);
2942 obj->z_nodelete = obj->ref_nodel = true;
2946 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
2948 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
2950 if (!(lo_flags & RTLD_LO_EARLY)) {
2951 map_stacks_exec(lockstate);
2954 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
2955 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
2957 objlist_clear(&initlist);
2958 dlopen_cleanup(obj);
2959 if (lockstate == &mlockstate)
2960 lock_release(rtld_bind_lock, lockstate);
2964 if (!(lo_flags & RTLD_LO_EARLY)) {
2965 /* Call the init functions. */
2966 objlist_call_init(&initlist, lockstate);
2968 objlist_clear(&initlist);
2969 if (lockstate == &mlockstate)
2970 lock_release(rtld_bind_lock, lockstate);
2973 trace_loaded_objects(obj);
2974 if (lockstate == &mlockstate)
2975 lock_release(rtld_bind_lock, lockstate);
2980 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
2984 const Obj_Entry *obj, *defobj;
2987 RtldLockState lockstate;
2992 symlook_init(&req, name);
2994 req.flags = flags | SYMLOOK_IN_PLT;
2995 req.lockstate = &lockstate;
2997 rlock_acquire(rtld_bind_lock, &lockstate);
2998 if (sigsetjmp(lockstate.env, 0) != 0)
2999 lock_upgrade(rtld_bind_lock, &lockstate);
3000 if (handle == NULL || handle == RTLD_NEXT ||
3001 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
3003 if ((obj = obj_from_addr(retaddr)) == NULL) {
3004 _rtld_error("Cannot determine caller's shared object");
3005 lock_release(rtld_bind_lock, &lockstate);
3008 if (handle == NULL) { /* Just the caller's shared object. */
3009 res = symlook_obj(&req, obj);
3012 defobj = req.defobj_out;
3014 } else if (handle == RTLD_NEXT || /* Objects after caller's */
3015 handle == RTLD_SELF) { /* ... caller included */
3016 if (handle == RTLD_NEXT)
3018 for (; obj != NULL; obj = obj->next) {
3019 res = symlook_obj(&req, obj);
3022 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) {
3024 defobj = req.defobj_out;
3025 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3031 * Search the dynamic linker itself, and possibly resolve the
3032 * symbol from there. This is how the application links to
3033 * dynamic linker services such as dlopen.
3035 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3036 res = symlook_obj(&req, &obj_rtld);
3037 if (res == 0 && is_exported(req.sym_out)) {
3039 defobj = req.defobj_out;
3043 assert(handle == RTLD_DEFAULT);
3044 res = symlook_default(&req, obj);
3046 defobj = req.defobj_out;
3051 if ((obj = dlcheck(handle)) == NULL) {
3052 lock_release(rtld_bind_lock, &lockstate);
3056 donelist_init(&donelist);
3057 if (obj->mainprog) {
3058 /* Handle obtained by dlopen(NULL, ...) implies global scope. */
3059 res = symlook_global(&req, &donelist);
3062 defobj = req.defobj_out;
3065 * Search the dynamic linker itself, and possibly resolve the
3066 * symbol from there. This is how the application links to
3067 * dynamic linker services such as dlopen.
3069 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3070 res = symlook_obj(&req, &obj_rtld);
3073 defobj = req.defobj_out;
3078 /* Search the whole DAG rooted at the given object. */
3079 res = symlook_list(&req, &obj->dagmembers, &donelist);
3082 defobj = req.defobj_out;
3088 lock_release(rtld_bind_lock, &lockstate);
3091 * The value required by the caller is derived from the value
3092 * of the symbol. For the ia64 architecture, we need to
3093 * construct a function descriptor which the caller can use to
3094 * call the function with the right 'gp' value. For other
3095 * architectures and for non-functions, the value is simply
3096 * the relocated value of the symbol.
3098 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
3099 return (make_function_pointer(def, defobj));
3100 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
3101 return (rtld_resolve_ifunc(defobj, def));
3102 else if (ELF_ST_TYPE(def->st_info) == STT_TLS) {
3104 ti.ti_module = defobj->tlsindex;
3105 ti.ti_offset = def->st_value;
3106 return (__tls_get_addr(&ti));
3108 return (defobj->relocbase + def->st_value);
3111 _rtld_error("Undefined symbol \"%s\"", name);
3112 lock_release(rtld_bind_lock, &lockstate);
3117 dlsym(void *handle, const char *name)
3119 return do_dlsym(handle, name, __builtin_return_address(0), NULL,
3124 dlfunc(void *handle, const char *name)
3131 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
3137 dlvsym(void *handle, const char *name, const char *version)
3141 ventry.name = version;
3143 ventry.hash = elf_hash(version);
3145 return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
3150 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
3152 const Obj_Entry *obj;
3153 RtldLockState lockstate;
3155 rlock_acquire(rtld_bind_lock, &lockstate);
3156 obj = obj_from_addr(addr);
3158 _rtld_error("No shared object contains address");
3159 lock_release(rtld_bind_lock, &lockstate);
3162 rtld_fill_dl_phdr_info(obj, phdr_info);
3163 lock_release(rtld_bind_lock, &lockstate);
3168 dladdr(const void *addr, Dl_info *info)
3170 const Obj_Entry *obj;
3173 unsigned long symoffset;
3174 RtldLockState lockstate;
3176 rlock_acquire(rtld_bind_lock, &lockstate);
3177 obj = obj_from_addr(addr);
3179 _rtld_error("No shared object contains address");
3180 lock_release(rtld_bind_lock, &lockstate);
3183 info->dli_fname = obj->path;
3184 info->dli_fbase = obj->mapbase;
3185 info->dli_saddr = NULL;
3186 info->dli_sname = NULL;
3189 * Walk the symbol list looking for the symbol whose address is
3190 * closest to the address sent in.
3192 for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) {
3193 def = obj->symtab + symoffset;
3196 * For skip the symbol if st_shndx is either SHN_UNDEF or
3199 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
3203 * If the symbol is greater than the specified address, or if it
3204 * is further away from addr than the current nearest symbol,
3207 symbol_addr = obj->relocbase + def->st_value;
3208 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
3211 /* Update our idea of the nearest symbol. */
3212 info->dli_sname = obj->strtab + def->st_name;
3213 info->dli_saddr = symbol_addr;
3216 if (info->dli_saddr == addr)
3219 lock_release(rtld_bind_lock, &lockstate);
3224 dlinfo(void *handle, int request, void *p)
3226 const Obj_Entry *obj;
3227 RtldLockState lockstate;
3230 rlock_acquire(rtld_bind_lock, &lockstate);
3232 if (handle == NULL || handle == RTLD_SELF) {
3235 retaddr = __builtin_return_address(0); /* __GNUC__ only */
3236 if ((obj = obj_from_addr(retaddr)) == NULL)
3237 _rtld_error("Cannot determine caller's shared object");
3239 obj = dlcheck(handle);
3242 lock_release(rtld_bind_lock, &lockstate);
3248 case RTLD_DI_LINKMAP:
3249 *((struct link_map const **)p) = &obj->linkmap;
3251 case RTLD_DI_ORIGIN:
3252 error = rtld_dirname(obj->path, p);
3255 case RTLD_DI_SERINFOSIZE:
3256 case RTLD_DI_SERINFO:
3257 error = do_search_info(obj, request, (struct dl_serinfo *)p);
3261 _rtld_error("Invalid request %d passed to dlinfo()", request);
3265 lock_release(rtld_bind_lock, &lockstate);
3271 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
3274 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
3275 phdr_info->dlpi_name = STAILQ_FIRST(&obj->names) ?
3276 STAILQ_FIRST(&obj->names)->name : obj->path;
3277 phdr_info->dlpi_phdr = obj->phdr;
3278 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
3279 phdr_info->dlpi_tls_modid = obj->tlsindex;
3280 phdr_info->dlpi_tls_data = obj->tlsinit;
3281 phdr_info->dlpi_adds = obj_loads;
3282 phdr_info->dlpi_subs = obj_loads - obj_count;
3286 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
3288 struct dl_phdr_info phdr_info;
3289 const Obj_Entry *obj;
3290 RtldLockState bind_lockstate, phdr_lockstate;
3293 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
3294 rlock_acquire(rtld_bind_lock, &bind_lockstate);
3298 for (obj = obj_list; obj != NULL; obj = obj->next) {
3299 rtld_fill_dl_phdr_info(obj, &phdr_info);
3300 if ((error = callback(&phdr_info, sizeof phdr_info, param)) != 0)
3304 lock_release(rtld_bind_lock, &bind_lockstate);
3305 lock_release(rtld_phdr_lock, &phdr_lockstate);
3311 fill_search_info(const char *dir, size_t dirlen, void *param)
3313 struct fill_search_info_args *arg;
3317 if (arg->request == RTLD_DI_SERINFOSIZE) {
3318 arg->serinfo->dls_cnt ++;
3319 arg->serinfo->dls_size += sizeof(struct dl_serpath) + dirlen + 1;
3321 struct dl_serpath *s_entry;
3323 s_entry = arg->serpath;
3324 s_entry->dls_name = arg->strspace;
3325 s_entry->dls_flags = arg->flags;
3327 strncpy(arg->strspace, dir, dirlen);
3328 arg->strspace[dirlen] = '\0';
3330 arg->strspace += dirlen + 1;
3338 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
3340 struct dl_serinfo _info;
3341 struct fill_search_info_args args;
3343 args.request = RTLD_DI_SERINFOSIZE;
3344 args.serinfo = &_info;
3346 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
3349 path_enumerate(obj->rpath, fill_search_info, &args);
3350 path_enumerate(ld_library_path, fill_search_info, &args);
3351 path_enumerate(obj->runpath, fill_search_info, &args);
3352 path_enumerate(gethints(obj->z_nodeflib), fill_search_info, &args);
3353 if (!obj->z_nodeflib)
3354 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
3357 if (request == RTLD_DI_SERINFOSIZE) {
3358 info->dls_size = _info.dls_size;
3359 info->dls_cnt = _info.dls_cnt;
3363 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
3364 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
3368 args.request = RTLD_DI_SERINFO;
3369 args.serinfo = info;
3370 args.serpath = &info->dls_serpath[0];
3371 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
3373 args.flags = LA_SER_RUNPATH;
3374 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
3377 args.flags = LA_SER_LIBPATH;
3378 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
3381 args.flags = LA_SER_RUNPATH;
3382 if (path_enumerate(obj->runpath, fill_search_info, &args) != NULL)
3385 args.flags = LA_SER_CONFIG;
3386 if (path_enumerate(gethints(obj->z_nodeflib), fill_search_info, &args)
3390 args.flags = LA_SER_DEFAULT;
3391 if (!obj->z_nodeflib &&
3392 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
3398 rtld_dirname(const char *path, char *bname)
3402 /* Empty or NULL string gets treated as "." */
3403 if (path == NULL || *path == '\0') {
3409 /* Strip trailing slashes */
3410 endp = path + strlen(path) - 1;
3411 while (endp > path && *endp == '/')
3414 /* Find the start of the dir */
3415 while (endp > path && *endp != '/')
3418 /* Either the dir is "/" or there are no slashes */
3420 bname[0] = *endp == '/' ? '/' : '.';
3426 } while (endp > path && *endp == '/');
3429 if (endp - path + 2 > PATH_MAX)
3431 _rtld_error("Filename is too long: %s", path);
3435 strncpy(bname, path, endp - path + 1);
3436 bname[endp - path + 1] = '\0';
3441 rtld_dirname_abs(const char *path, char *base)
3443 char base_rel[PATH_MAX];
3445 if (rtld_dirname(path, base) == -1)
3449 if (getcwd(base_rel, sizeof(base_rel)) == NULL ||
3450 strlcat(base_rel, "/", sizeof(base_rel)) >= sizeof(base_rel) ||
3451 strlcat(base_rel, base, sizeof(base_rel)) >= sizeof(base_rel))
3453 strcpy(base, base_rel);
3458 linkmap_add(Obj_Entry *obj)
3460 struct link_map *l = &obj->linkmap;
3461 struct link_map *prev;
3463 obj->linkmap.l_name = obj->path;
3464 obj->linkmap.l_addr = obj->mapbase;
3465 obj->linkmap.l_ld = obj->dynamic;
3467 /* GDB needs load offset on MIPS to use the symbols */
3468 obj->linkmap.l_offs = obj->relocbase;
3471 if (r_debug.r_map == NULL) {
3477 * Scan to the end of the list, but not past the entry for the
3478 * dynamic linker, which we want to keep at the very end.
3480 for (prev = r_debug.r_map;
3481 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
3482 prev = prev->l_next)
3485 /* Link in the new entry. */
3487 l->l_next = prev->l_next;
3488 if (l->l_next != NULL)
3489 l->l_next->l_prev = l;
3494 linkmap_delete(Obj_Entry *obj)
3496 struct link_map *l = &obj->linkmap;
3498 if (l->l_prev == NULL) {
3499 if ((r_debug.r_map = l->l_next) != NULL)
3500 l->l_next->l_prev = NULL;
3504 if ((l->l_prev->l_next = l->l_next) != NULL)
3505 l->l_next->l_prev = l->l_prev;
3509 * Function for the debugger to set a breakpoint on to gain control.
3511 * The two parameters allow the debugger to easily find and determine
3512 * what the runtime loader is doing and to whom it is doing it.
3514 * When the loadhook trap is hit (r_debug_state, set at program
3515 * initialization), the arguments can be found on the stack:
3517 * +8 struct link_map *m
3518 * +4 struct r_debug *rd
3522 r_debug_state(struct r_debug* rd, struct link_map *m)
3525 * The following is a hack to force the compiler to emit calls to
3526 * this function, even when optimizing. If the function is empty,
3527 * the compiler is not obliged to emit any code for calls to it,
3528 * even when marked __noinline. However, gdb depends on those
3531 __asm __volatile("" : : : "memory");
3535 * Get address of the pointer variable in the main program.
3536 * Prefer non-weak symbol over the weak one.
3538 static const void **
3539 get_program_var_addr(const char *name, RtldLockState *lockstate)
3544 symlook_init(&req, name);
3545 req.lockstate = lockstate;
3546 donelist_init(&donelist);
3547 if (symlook_global(&req, &donelist) != 0)
3549 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
3550 return ((const void **)make_function_pointer(req.sym_out,
3552 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
3553 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
3555 return ((const void **)(req.defobj_out->relocbase + req.sym_out->st_value));
3559 * Set a pointer variable in the main program to the given value. This
3560 * is used to set key variables such as "environ" before any of the
3561 * init functions are called.
3564 set_program_var(const char *name, const void *value)
3568 if ((addr = get_program_var_addr(name, NULL)) != NULL) {
3569 dbg("\"%s\": *%p <-- %p", name, addr, value);
3575 * Search the global objects, including dependencies and main object,
3576 * for the given symbol.
3579 symlook_global(SymLook *req, DoneList *donelist)
3582 const Objlist_Entry *elm;
3585 symlook_init_from_req(&req1, req);
3587 /* Search all objects loaded at program start up. */
3588 if (req->defobj_out == NULL ||
3589 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3590 res = symlook_list(&req1, &list_main, donelist);
3591 if (res == 0 && (req->defobj_out == NULL ||
3592 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3593 req->sym_out = req1.sym_out;
3594 req->defobj_out = req1.defobj_out;
3595 assert(req->defobj_out != NULL);
3599 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
3600 STAILQ_FOREACH(elm, &list_global, link) {
3601 if (req->defobj_out != NULL &&
3602 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3604 res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
3605 if (res == 0 && (req->defobj_out == NULL ||
3606 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3607 req->sym_out = req1.sym_out;
3608 req->defobj_out = req1.defobj_out;
3609 assert(req->defobj_out != NULL);
3613 return (req->sym_out != NULL ? 0 : ESRCH);
3617 * This is a special version of getenv which is far more efficient
3618 * at finding LD_ environment vars.
3622 _getenv_ld(const char *id)
3626 int idlen = strlen(id);
3628 if (ld_index == LD_ARY_CACHE)
3630 if (ld_index == 0) {
3631 for (i = j = 0; (envp = environ[i]) != NULL && j < LD_ARY_CACHE; ++i) {
3632 if (envp[0] == 'L' && envp[1] == 'D' && envp[2] == '_')
3639 for (i = ld_index - 1; i >= 0; --i) {
3640 if (strncmp(ld_ary[i], id, idlen) == 0 && ld_ary[i][idlen] == '=')
3641 return(ld_ary[i] + idlen + 1);
3647 * Given a symbol name in a referencing object, find the corresponding
3648 * definition of the symbol. Returns a pointer to the symbol, or NULL if
3649 * no definition was found. Returns a pointer to the Obj_Entry of the
3650 * defining object via the reference parameter DEFOBJ_OUT.
3653 symlook_default(SymLook *req, const Obj_Entry *refobj)
3656 const Objlist_Entry *elm;
3660 donelist_init(&donelist);
3661 symlook_init_from_req(&req1, req);
3663 /* Look first in the referencing object if linked symbolically. */
3664 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
3665 res = symlook_obj(&req1, refobj);
3667 req->sym_out = req1.sym_out;
3668 req->defobj_out = req1.defobj_out;
3669 assert(req->defobj_out != NULL);
3673 symlook_global(req, &donelist);
3675 /* Search all dlopened DAGs containing the referencing object. */
3676 STAILQ_FOREACH(elm, &refobj->dldags, link) {
3677 if (req->sym_out != NULL &&
3678 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3680 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
3681 if (res == 0 && (req->sym_out == NULL ||
3682 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3683 req->sym_out = req1.sym_out;
3684 req->defobj_out = req1.defobj_out;
3685 assert(req->defobj_out != NULL);
3690 * Search the dynamic linker itself, and possibly resolve the
3691 * symbol from there. This is how the application links to
3692 * dynamic linker services such as dlopen. Only the values listed
3693 * in the "exports" array can be resolved from the dynamic linker.
3695 if (req->sym_out == NULL ||
3696 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3697 res = symlook_obj(&req1, &obj_rtld);
3698 if (res == 0 && is_exported(req1.sym_out)) {
3699 req->sym_out = req1.sym_out;
3700 req->defobj_out = req1.defobj_out;
3701 assert(req->defobj_out != NULL);
3705 return (req->sym_out != NULL ? 0 : ESRCH);
3709 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
3712 const Obj_Entry *defobj;
3713 const Objlist_Entry *elm;
3719 STAILQ_FOREACH(elm, objlist, link) {
3720 if (donelist_check(dlp, elm->obj))
3722 symlook_init_from_req(&req1, req);
3723 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
3724 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3726 defobj = req1.defobj_out;
3727 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3734 req->defobj_out = defobj;
3741 * Search the chain of DAGS cointed to by the given Needed_Entry
3742 * for a symbol of the given name. Each DAG is scanned completely
3743 * before advancing to the next one. Returns a pointer to the symbol,
3744 * or NULL if no definition was found.
3747 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
3750 const Needed_Entry *n;
3751 const Obj_Entry *defobj;
3757 symlook_init_from_req(&req1, req);
3758 for (n = needed; n != NULL; n = n->next) {
3759 if (n->obj == NULL ||
3760 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
3762 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3764 defobj = req1.defobj_out;
3765 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3771 req->defobj_out = defobj;
3778 * Search the symbol table of a single shared object for a symbol of
3779 * the given name and version, if requested. Returns a pointer to the
3780 * symbol, or NULL if no definition was found. If the object is
3781 * filter, return filtered symbol from filtee.
3783 * The symbol's hash value is passed in for efficiency reasons; that
3784 * eliminates many recomputations of the hash value.
3787 symlook_obj(SymLook *req, const Obj_Entry *obj)
3791 int flags, res, mres;
3794 * There is at least one valid hash at this point, and we prefer to use
3795 * the faster GNU version if available.
3797 if (obj->valid_hash_gnu)
3798 mres = symlook_obj1_gnu(req, obj);
3800 mres = symlook_obj1_sysv(req, obj);
3803 if (obj->needed_filtees != NULL) {
3804 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
3805 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
3806 donelist_init(&donelist);
3807 symlook_init_from_req(&req1, req);
3808 res = symlook_needed(&req1, obj->needed_filtees, &donelist);
3810 req->sym_out = req1.sym_out;
3811 req->defobj_out = req1.defobj_out;
3815 if (obj->needed_aux_filtees != NULL) {
3816 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
3817 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
3818 donelist_init(&donelist);
3819 symlook_init_from_req(&req1, req);
3820 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
3822 req->sym_out = req1.sym_out;
3823 req->defobj_out = req1.defobj_out;
3831 /* Symbol match routine common to both hash functions */
3833 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result,
3834 const unsigned long symnum)
3837 const Elf_Sym *symp;
3840 symp = obj->symtab + symnum;
3841 strp = obj->strtab + symp->st_name;
3843 switch (ELF_ST_TYPE(symp->st_info)) {
3849 if (symp->st_value == 0)
3853 if (symp->st_shndx != SHN_UNDEF)
3855 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
3856 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
3862 if (strcmp(req->name, strp) != 0)
3865 if (req->ventry == NULL) {
3866 if (obj->versyms != NULL) {
3867 verndx = VER_NDX(obj->versyms[symnum]);
3868 if (verndx > obj->vernum) {
3870 "%s: symbol %s references wrong version %d",
3871 obj->path, obj->strtab + symnum, verndx);
3875 * If we are not called from dlsym (i.e. this
3876 * is a normal relocation from unversioned
3877 * binary), accept the symbol immediately if
3878 * it happens to have first version after this
3879 * shared object became versioned. Otherwise,
3880 * if symbol is versioned and not hidden,
3881 * remember it. If it is the only symbol with
3882 * this name exported by the shared object, it
3883 * will be returned as a match by the calling
3884 * function. If symbol is global (verndx < 2)
3885 * accept it unconditionally.
3887 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
3888 verndx == VER_NDX_GIVEN) {
3889 result->sym_out = symp;
3892 else if (verndx >= VER_NDX_GIVEN) {
3893 if ((obj->versyms[symnum] & VER_NDX_HIDDEN)
3895 if (result->vsymp == NULL)
3896 result->vsymp = symp;
3902 result->sym_out = symp;
3905 if (obj->versyms == NULL) {
3906 if (object_match_name(obj, req->ventry->name)) {
3907 _rtld_error("%s: object %s should provide version %s "
3908 "for symbol %s", obj_rtld.path, obj->path,
3909 req->ventry->name, obj->strtab + symnum);
3913 verndx = VER_NDX(obj->versyms[symnum]);
3914 if (verndx > obj->vernum) {
3915 _rtld_error("%s: symbol %s references wrong version %d",
3916 obj->path, obj->strtab + symnum, verndx);
3919 if (obj->vertab[verndx].hash != req->ventry->hash ||
3920 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
3922 * Version does not match. Look if this is a
3923 * global symbol and if it is not hidden. If
3924 * global symbol (verndx < 2) is available,
3925 * use it. Do not return symbol if we are
3926 * called by dlvsym, because dlvsym looks for
3927 * a specific version and default one is not
3928 * what dlvsym wants.
3930 if ((req->flags & SYMLOOK_DLSYM) ||
3931 (verndx >= VER_NDX_GIVEN) ||
3932 (obj->versyms[symnum] & VER_NDX_HIDDEN))
3936 result->sym_out = symp;
3941 * Search for symbol using SysV hash function.
3942 * obj->buckets is known not to be NULL at this point; the test for this was
3943 * performed with the obj->valid_hash_sysv assignment.
3946 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj)
3948 unsigned long symnum;
3949 Sym_Match_Result matchres;
3951 matchres.sym_out = NULL;
3952 matchres.vsymp = NULL;
3953 matchres.vcount = 0;
3955 for (symnum = obj->buckets[req->hash % obj->nbuckets];
3956 symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
3957 if (symnum >= obj->nchains)
3958 return (ESRCH); /* Bad object */
3960 if (matched_symbol(req, obj, &matchres, symnum)) {
3961 req->sym_out = matchres.sym_out;
3962 req->defobj_out = obj;
3966 if (matchres.vcount == 1) {
3967 req->sym_out = matchres.vsymp;
3968 req->defobj_out = obj;
3974 /* Search for symbol using GNU hash function */
3976 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj)
3978 Elf_Addr bloom_word;
3979 const Elf32_Word *hashval;
3981 Sym_Match_Result matchres;
3982 unsigned int h1, h2;
3983 unsigned long symnum;
3985 matchres.sym_out = NULL;
3986 matchres.vsymp = NULL;
3987 matchres.vcount = 0;
3989 /* Pick right bitmask word from Bloom filter array */
3990 bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) &
3991 obj->maskwords_bm_gnu];
3993 /* Calculate modulus word size of gnu hash and its derivative */
3994 h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1);
3995 h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1));
3997 /* Filter out the "definitely not in set" queries */
3998 if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0)
4001 /* Locate hash chain and corresponding value element*/
4002 bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu];
4005 hashval = &obj->chain_zero_gnu[bucket];
4007 if (((*hashval ^ req->hash_gnu) >> 1) == 0) {
4008 symnum = hashval - obj->chain_zero_gnu;
4009 if (matched_symbol(req, obj, &matchres, symnum)) {
4010 req->sym_out = matchres.sym_out;
4011 req->defobj_out = obj;
4015 } while ((*hashval++ & 1) == 0);
4016 if (matchres.vcount == 1) {
4017 req->sym_out = matchres.vsymp;
4018 req->defobj_out = obj;
4025 trace_loaded_objects(Obj_Entry *obj)
4027 const char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
4030 if ((main_local = _getenv_ld("LD_TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
4033 if ((fmt1 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT1")) == NULL)
4034 fmt1 = "\t%o => %p (%x)\n";
4036 if ((fmt2 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT2")) == NULL)
4037 fmt2 = "\t%o (%x)\n";
4039 list_containers = _getenv_ld("LD_TRACE_LOADED_OBJECTS_ALL");
4041 for (; obj; obj = obj->next) {
4042 Needed_Entry *needed;
4046 if (list_containers && obj->needed != NULL)
4047 rtld_printf("%s:\n", obj->path);
4048 for (needed = obj->needed; needed; needed = needed->next) {
4049 if (needed->obj != NULL) {
4050 if (needed->obj->traced && !list_containers)
4052 needed->obj->traced = true;
4053 path = needed->obj->path;
4057 name = (char *)obj->strtab + needed->name;
4058 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
4060 fmt = is_lib ? fmt1 : fmt2;
4061 while ((c = *fmt++) != '\0') {
4087 rtld_putstr(main_local);
4090 rtld_putstr(obj_main->path);
4099 rtld_printf("%p", needed->obj ? needed->obj->mapbase :
4112 * Unload a dlopened object and its dependencies from memory and from
4113 * our data structures. It is assumed that the DAG rooted in the
4114 * object has already been unreferenced, and that the object has a
4115 * reference count of 0.
4118 unload_object(Obj_Entry *root)
4123 assert(root->refcount == 0);
4126 * Pass over the DAG removing unreferenced objects from
4127 * appropriate lists.
4129 unlink_object(root);
4131 /* Unmap all objects that are no longer referenced. */
4132 linkp = &obj_list->next;
4133 while ((obj = *linkp) != NULL) {
4134 if (obj->refcount == 0) {
4135 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
4137 dbg("unloading \"%s\"", obj->path);
4138 unload_filtees(root);
4139 munmap(obj->mapbase, obj->mapsize);
4140 linkmap_delete(obj);
4151 unlink_object(Obj_Entry *root)
4155 if (root->refcount == 0) {
4156 /* Remove the object from the RTLD_GLOBAL list. */
4157 objlist_remove(&list_global, root);
4159 /* Remove the object from all objects' DAG lists. */
4160 STAILQ_FOREACH(elm, &root->dagmembers, link) {
4161 objlist_remove(&elm->obj->dldags, root);
4162 if (elm->obj != root)
4163 unlink_object(elm->obj);
4169 ref_dag(Obj_Entry *root)
4173 assert(root->dag_inited);
4174 STAILQ_FOREACH(elm, &root->dagmembers, link)
4175 elm->obj->refcount++;
4179 unref_dag(Obj_Entry *root)
4183 assert(root->dag_inited);
4184 STAILQ_FOREACH(elm, &root->dagmembers, link)
4185 elm->obj->refcount--;
4189 * Common code for MD __tls_get_addr().
4192 tls_get_addr_common(Elf_Addr** dtvp, int index, size_t offset)
4194 Elf_Addr* dtv = *dtvp;
4195 RtldLockState lockstate;
4197 /* Check dtv generation in case new modules have arrived */
4198 if (dtv[0] != tls_dtv_generation) {
4202 wlock_acquire(rtld_bind_lock, &lockstate);
4203 newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4205 if (to_copy > tls_max_index)
4206 to_copy = tls_max_index;
4207 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
4208 newdtv[0] = tls_dtv_generation;
4209 newdtv[1] = tls_max_index;
4211 lock_release(rtld_bind_lock, &lockstate);
4212 dtv = *dtvp = newdtv;
4215 /* Dynamically allocate module TLS if necessary */
4216 if (!dtv[index + 1]) {
4217 /* Signal safe, wlock will block out signals. */
4218 wlock_acquire(rtld_bind_lock, &lockstate);
4219 if (!dtv[index + 1])
4220 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
4221 lock_release(rtld_bind_lock, &lockstate);
4223 return (void*) (dtv[index + 1] + offset);
4226 #if defined(RTLD_STATIC_TLS_VARIANT_II)
4229 * Allocate the static TLS area. Return a pointer to the TCB. The
4230 * static area is based on negative offsets relative to the tcb.
4232 * The TCB contains an errno pointer for the system call layer, but because
4233 * we are the RTLD we really have no idea how the caller was compiled so
4234 * the information has to be passed in. errno can either be:
4236 * type 0 errno is a simple non-TLS global pointer.
4237 * (special case for e.g. libc_rtld)
4238 * type 1 errno accessed by GOT entry (dynamically linked programs)
4239 * type 2 errno accessed by %gs:OFFSET (statically linked programs)
4242 allocate_tls(Obj_Entry *objs)
4247 struct tls_tcb *tcb;
4252 * Allocate the new TCB. static TLS storage is placed just before the
4253 * TCB to support the %gs:OFFSET (negative offset) model.
4255 data_size = (tls_static_space + RTLD_STATIC_TLS_ALIGN_MASK) &
4256 ~RTLD_STATIC_TLS_ALIGN_MASK;
4257 tcb = malloc(data_size + sizeof(*tcb));
4258 tcb = (void *)((char *)tcb + data_size); /* actual tcb location */
4260 dtv_size = (tls_max_index + 2) * sizeof(Elf_Addr);
4261 dtv = malloc(dtv_size);
4262 bzero(dtv, dtv_size);
4264 #ifdef RTLD_TCB_HAS_SELF_POINTER
4265 tcb->tcb_self = tcb;
4268 tcb->tcb_pthread = NULL;
4270 dtv[0] = tls_dtv_generation;
4271 dtv[1] = tls_max_index;
4273 for (obj = objs; obj; obj = obj->next) {
4274 if (obj->tlsoffset) {
4275 addr = (Elf_Addr)tcb - obj->tlsoffset;
4276 memset((void *)(addr + obj->tlsinitsize),
4277 0, obj->tlssize - obj->tlsinitsize);
4279 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4280 dtv[obj->tlsindex + 1] = addr;
4287 free_tls(struct tls_tcb *tcb)
4291 Elf_Addr tls_start, tls_end;
4294 data_size = (tls_static_space + RTLD_STATIC_TLS_ALIGN_MASK) &
4295 ~RTLD_STATIC_TLS_ALIGN_MASK;
4299 tls_end = (Elf_Addr)tcb;
4300 tls_start = (Elf_Addr)tcb - data_size;
4301 for (i = 0; i < dtv_size; i++) {
4302 if (dtv[i+2] != 0 && (dtv[i+2] < tls_start || dtv[i+2] > tls_end)) {
4303 free((void *)dtv[i+2]);
4307 free((void*) tls_start);
4311 #error "Unsupported TLS layout"
4315 * Allocate TLS block for module with given index.
4318 allocate_module_tls(int index)
4323 for (obj = obj_list; obj; obj = obj->next) {
4324 if (obj->tlsindex == index)
4328 _rtld_error("Can't find module with TLS index %d", index);
4332 p = malloc(obj->tlssize);
4334 _rtld_error("Cannot allocate TLS block for index %d", index);
4337 memcpy(p, obj->tlsinit, obj->tlsinitsize);
4338 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
4344 allocate_tls_offset(Obj_Entry *obj)
4351 if (obj->tlssize == 0) {
4352 obj->tls_done = true;
4356 if (obj->tlsindex == 1)
4357 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
4359 off = calculate_tls_offset(tls_last_offset, tls_last_size,
4360 obj->tlssize, obj->tlsalign);
4363 * If we have already fixed the size of the static TLS block, we
4364 * must stay within that size. When allocating the static TLS, we
4365 * leave a small amount of space spare to be used for dynamically
4366 * loading modules which use static TLS.
4368 if (tls_static_space) {
4369 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
4373 tls_last_offset = obj->tlsoffset = off;
4374 tls_last_size = obj->tlssize;
4375 obj->tls_done = true;
4381 free_tls_offset(Obj_Entry *obj)
4383 #ifdef RTLD_STATIC_TLS_VARIANT_II
4385 * If we were the last thing to allocate out of the static TLS
4386 * block, we give our space back to the 'allocator'. This is a
4387 * simplistic workaround to allow libGL.so.1 to be loaded and
4388 * unloaded multiple times. We only handle the Variant II
4389 * mechanism for now - this really needs a proper allocator.
4391 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
4392 == calculate_tls_end(tls_last_offset, tls_last_size)) {
4393 tls_last_offset -= obj->tlssize;
4400 _rtld_allocate_tls(void)
4402 struct tls_tcb *new_tcb;
4403 RtldLockState lockstate;
4405 wlock_acquire(rtld_bind_lock, &lockstate);
4406 new_tcb = allocate_tls(obj_list);
4407 lock_release(rtld_bind_lock, &lockstate);
4412 _rtld_free_tls(struct tls_tcb *tcb)
4414 RtldLockState lockstate;
4416 wlock_acquire(rtld_bind_lock, &lockstate);
4418 lock_release(rtld_bind_lock, &lockstate);
4422 object_add_name(Obj_Entry *obj, const char *name)
4428 entry = malloc(sizeof(Name_Entry) + len);
4430 if (entry != NULL) {
4431 strcpy(entry->name, name);
4432 STAILQ_INSERT_TAIL(&obj->names, entry, link);
4437 object_match_name(const Obj_Entry *obj, const char *name)
4441 STAILQ_FOREACH(entry, &obj->names, link) {
4442 if (strcmp(name, entry->name) == 0)
4449 locate_dependency(const Obj_Entry *obj, const char *name)
4451 const Objlist_Entry *entry;
4452 const Needed_Entry *needed;
4454 STAILQ_FOREACH(entry, &list_main, link) {
4455 if (object_match_name(entry->obj, name))
4459 for (needed = obj->needed; needed != NULL; needed = needed->next) {
4460 if (strcmp(obj->strtab + needed->name, name) == 0 ||
4461 (needed->obj != NULL && object_match_name(needed->obj, name))) {
4463 * If there is DT_NEEDED for the name we are looking for,
4464 * we are all set. Note that object might not be found if
4465 * dependency was not loaded yet, so the function can
4466 * return NULL here. This is expected and handled
4467 * properly by the caller.
4469 return (needed->obj);
4472 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
4478 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
4479 const Elf_Vernaux *vna)
4481 const Elf_Verdef *vd;
4482 const char *vername;
4484 vername = refobj->strtab + vna->vna_name;
4485 vd = depobj->verdef;
4487 _rtld_error("%s: version %s required by %s not defined",
4488 depobj->path, vername, refobj->path);
4492 if (vd->vd_version != VER_DEF_CURRENT) {
4493 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
4494 depobj->path, vd->vd_version);
4497 if (vna->vna_hash == vd->vd_hash) {
4498 const Elf_Verdaux *aux = (const Elf_Verdaux *)
4499 ((char *)vd + vd->vd_aux);
4500 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
4503 if (vd->vd_next == 0)
4505 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4507 if (vna->vna_flags & VER_FLG_WEAK)
4509 _rtld_error("%s: version %s required by %s not found",
4510 depobj->path, vername, refobj->path);
4515 rtld_verify_object_versions(Obj_Entry *obj)
4517 const Elf_Verneed *vn;
4518 const Elf_Verdef *vd;
4519 const Elf_Verdaux *vda;
4520 const Elf_Vernaux *vna;
4521 const Obj_Entry *depobj;
4522 int maxvernum, vernum;
4524 if (obj->ver_checked)
4526 obj->ver_checked = true;
4530 * Walk over defined and required version records and figure out
4531 * max index used by any of them. Do very basic sanity checking
4535 while (vn != NULL) {
4536 if (vn->vn_version != VER_NEED_CURRENT) {
4537 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
4538 obj->path, vn->vn_version);
4541 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4543 vernum = VER_NEED_IDX(vna->vna_other);
4544 if (vernum > maxvernum)
4546 if (vna->vna_next == 0)
4548 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4550 if (vn->vn_next == 0)
4552 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4556 while (vd != NULL) {
4557 if (vd->vd_version != VER_DEF_CURRENT) {
4558 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
4559 obj->path, vd->vd_version);
4562 vernum = VER_DEF_IDX(vd->vd_ndx);
4563 if (vernum > maxvernum)
4565 if (vd->vd_next == 0)
4567 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4574 * Store version information in array indexable by version index.
4575 * Verify that object version requirements are satisfied along the
4578 obj->vernum = maxvernum + 1;
4579 obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry));
4582 while (vd != NULL) {
4583 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
4584 vernum = VER_DEF_IDX(vd->vd_ndx);
4585 assert(vernum <= maxvernum);
4586 vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
4587 obj->vertab[vernum].hash = vd->vd_hash;
4588 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
4589 obj->vertab[vernum].file = NULL;
4590 obj->vertab[vernum].flags = 0;
4592 if (vd->vd_next == 0)
4594 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4598 while (vn != NULL) {
4599 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
4602 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4604 if (check_object_provided_version(obj, depobj, vna))
4606 vernum = VER_NEED_IDX(vna->vna_other);
4607 assert(vernum <= maxvernum);
4608 obj->vertab[vernum].hash = vna->vna_hash;
4609 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
4610 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
4611 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
4612 VER_INFO_HIDDEN : 0;
4613 if (vna->vna_next == 0)
4615 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4617 if (vn->vn_next == 0)
4619 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4625 rtld_verify_versions(const Objlist *objlist)
4627 Objlist_Entry *entry;
4631 STAILQ_FOREACH(entry, objlist, link) {
4633 * Skip dummy objects or objects that have their version requirements
4636 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
4638 if (rtld_verify_object_versions(entry->obj) == -1) {
4640 if (ld_tracing == NULL)
4644 if (rc == 0 || ld_tracing != NULL)
4645 rc = rtld_verify_object_versions(&obj_rtld);
4650 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
4655 vernum = VER_NDX(obj->versyms[symnum]);
4656 if (vernum >= obj->vernum) {
4657 _rtld_error("%s: symbol %s has wrong verneed value %d",
4658 obj->path, obj->strtab + symnum, vernum);
4659 } else if (obj->vertab[vernum].hash != 0) {
4660 return &obj->vertab[vernum];
4667 _rtld_get_stack_prot(void)
4670 return (stack_prot);
4674 map_stacks_exec(RtldLockState *lockstate)
4678 * Stack protection must be implemented in the kernel before the dynamic
4679 * linker can handle PT_GNU_STACK sections.
4680 * The following is the FreeBSD implementation of map_stacks_exec()
4681 * void (*thr_map_stacks_exec)(void);
4683 * if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
4685 * thr_map_stacks_exec = (void (*)(void))(uintptr_t)
4686 * get_program_var_addr("__pthread_map_stacks_exec", lockstate);
4687 * if (thr_map_stacks_exec != NULL) {
4688 * stack_prot |= PROT_EXEC;
4689 * thr_map_stacks_exec();
4695 symlook_init(SymLook *dst, const char *name)
4698 bzero(dst, sizeof(*dst));
4700 dst->hash = elf_hash(name);
4701 dst->hash_gnu = gnu_hash(name);
4705 symlook_init_from_req(SymLook *dst, const SymLook *src)
4708 dst->name = src->name;
4709 dst->hash = src->hash;
4710 dst->hash_gnu = src->hash_gnu;
4711 dst->ventry = src->ventry;
4712 dst->flags = src->flags;
4713 dst->defobj_out = NULL;
4714 dst->sym_out = NULL;
4715 dst->lockstate = src->lockstate;
4718 #ifdef ENABLE_OSRELDATE
4720 * Overrides for libc_pic-provided functions.
4724 __getosreldate(void)
4734 oid[1] = KERN_OSRELDATE;
4736 len = sizeof(osrel);
4737 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
4738 if (error == 0 && osrel > 0 && len == sizeof(osrel))
4745 * No unresolved symbols for rtld.
4748 __pthread_cxa_finalize(struct dl_phdr_info *a)
4753 rtld_strerror(int errnum)
4756 if (errnum < 0 || errnum >= sys_nerr)
4757 return ("Unknown error");
4758 return (sys_errlist[errnum]);