2 * Copyright 1996, 1997, 1998, 1999, 2000 John D. Polstra.
3 * Copyright 2003 Alexander Kabaev <kan@FreeBSD.ORG>.
4 * Copyright 2009, 2010, 2011 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, Obj_Entry *refobj,
90 int lo_flags, int mode);
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(const Obj_Entry *);
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 *, 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 preinitialize_main_object (void);
116 static void objlist_clear(Objlist *);
117 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
118 static void objlist_init(Objlist *);
119 static void objlist_push_head(Objlist *, Obj_Entry *);
120 static void objlist_push_tail(Objlist *, Obj_Entry *);
121 static void objlist_remove(Objlist *, Obj_Entry *);
122 static void *path_enumerate(const char *, path_enum_proc, void *);
123 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, int,
125 static int resolve_objects_ifunc(Obj_Entry *first, bool bind_now,
126 int flags, RtldLockState *lockstate);
127 static int rtld_dirname(const char *, char *);
128 static int rtld_dirname_abs(const char *, char *);
129 static void rtld_exit(void);
130 static char *search_library_path(const char *, const char *);
131 static const void **get_program_var_addr(const char *, RtldLockState *);
132 static void set_program_var(const char *, const void *);
133 static int symlook_default(SymLook *, const Obj_Entry *refobj);
134 static int symlook_global(SymLook *, DoneList *);
135 static void symlook_init_from_req(SymLook *, const SymLook *);
136 static int symlook_list(SymLook *, const Objlist *, DoneList *);
137 static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *);
138 static int symlook_obj1(SymLook *, const Obj_Entry *);
139 static int symlook_obj2(SymLook *, const Obj_Entry *);
140 static void trace_loaded_objects(Obj_Entry *);
141 static void unlink_object(Obj_Entry *);
142 static void unload_object(Obj_Entry *);
143 static void unref_dag(Obj_Entry *);
144 static void ref_dag(Obj_Entry *);
145 static int origin_subst_one(char **, const char *, const char *,
146 const char *, char *);
147 static char *origin_subst(const char *, const char *);
148 static int rtld_verify_versions(const Objlist *);
149 static int rtld_verify_object_versions(Obj_Entry *);
150 static void object_add_name(Obj_Entry *, const char *);
151 static int object_match_name(const Obj_Entry *, const char *);
152 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
153 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
154 struct dl_phdr_info *phdr_info);
155 static uint_fast32_t gnu_hash (const char *);
156 static bool matched_symbol(SymLook *, const Obj_Entry *, Sym_Match_Result *,
157 const unsigned long);
159 void r_debug_state(struct r_debug *, struct link_map *) __noinline;
164 static char *error_message; /* Message for dlerror(), or NULL */
165 struct r_debug r_debug; /* for GDB; */
166 static bool libmap_disable; /* Disable libmap */
167 static bool ld_loadfltr; /* Immediate filters processing */
168 static char *libmap_override; /* Maps to use in addition to libmap.conf */
169 static bool trust; /* False for setuid and setgid programs */
170 static bool dangerous_ld_env; /* True if environment variables have been
171 used to affect the libraries loaded */
172 static const char *ld_bind_now; /* Environment variable for immediate binding */
173 static const char *ld_debug; /* Environment variable for debugging */
174 static const char *ld_library_path; /* Environment variable for search path */
175 static char *ld_preload; /* Environment variable for libraries to
177 static const char *ld_elf_hints_path; /* Environment variable for alternative hints path */
178 static const char *ld_tracing; /* Called from ldd to print libs */
179 static const char *ld_utrace; /* Use utrace() to log events. */
180 static int (*rtld_functrace)( /* Optional function call tracing hook */
181 const char *caller_obj,
182 const char *callee_obj,
183 const char *callee_func,
185 static const Obj_Entry *rtld_functrace_obj; /* Object thereof */
186 static Obj_Entry *obj_list; /* Head of linked list of shared objects */
187 static Obj_Entry **obj_tail; /* Link field of last object in list */
188 static Obj_Entry **preload_tail;
189 static Obj_Entry *obj_main; /* The main program shared object */
190 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
191 static unsigned int obj_count; /* Number of objects in obj_list */
192 static unsigned int obj_loads; /* Number of objects in obj_list */
194 static int ld_resident; /* Non-zero if resident */
195 static const char *ld_ary[LD_ARY_CACHE];
197 static Objlist initlist;
199 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
200 STAILQ_HEAD_INITIALIZER(list_global);
201 static Objlist list_main = /* Objects loaded at program startup */
202 STAILQ_HEAD_INITIALIZER(list_main);
203 static Objlist list_fini = /* Objects needing fini() calls */
204 STAILQ_HEAD_INITIALIZER(list_fini);
206 static Elf_Sym sym_zero; /* For resolving undefined weak refs. */
208 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
210 extern Elf_Dyn _DYNAMIC;
211 #pragma weak _DYNAMIC
212 #ifndef RTLD_IS_DYNAMIC
213 #define RTLD_IS_DYNAMIC() (&_DYNAMIC != NULL)
216 #ifdef ENABLE_OSRELDATE
220 static int stack_prot = PROT_READ | PROT_WRITE | RTLD_DEFAULT_STACK_EXEC;
221 static int max_stack_flags;
224 * These are the functions the dynamic linker exports to application
225 * programs. They are the only symbols the dynamic linker is willing
226 * to export from itself.
228 static func_ptr_type exports[] = {
229 (func_ptr_type) &_rtld_error,
230 (func_ptr_type) &dlclose,
231 (func_ptr_type) &dlerror,
232 (func_ptr_type) &dlopen,
233 (func_ptr_type) &dlfunc,
234 (func_ptr_type) &dlsym,
235 (func_ptr_type) &dlvsym,
236 (func_ptr_type) &dladdr,
237 (func_ptr_type) &dlinfo,
238 (func_ptr_type) &dl_iterate_phdr,
240 (func_ptr_type) &___tls_get_addr,
242 (func_ptr_type) &__tls_get_addr,
243 (func_ptr_type) &__tls_get_addr_tcb,
244 (func_ptr_type) &_rtld_allocate_tls,
245 (func_ptr_type) &_rtld_free_tls,
246 (func_ptr_type) &_rtld_call_init,
247 (func_ptr_type) &_rtld_thread_init,
248 (func_ptr_type) &_rtld_addr_phdr,
249 (func_ptr_type) &_rtld_get_stack_prot,
254 * Global declarations normally provided by crt1. The dynamic linker is
255 * not built with crt1, so we have to provide them ourselves.
261 * Used to pass argc, argv to init functions.
267 * Globals to control TLS allocation.
269 size_t tls_last_offset; /* Static TLS offset of last module */
270 size_t tls_last_size; /* Static TLS size of last module */
271 size_t tls_static_space; /* Static TLS space allocated */
272 int tls_dtv_generation = 1; /* Used to detect when dtv size changes */
273 int tls_max_index = 1; /* Largest module index allocated */
276 * Fill in a DoneList with an allocation large enough to hold all of
277 * the currently-loaded objects. Keep this as a macro since it calls
278 * alloca and we want that to occur within the scope of the caller.
280 #define donelist_init(dlp) \
281 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
282 assert((dlp)->objs != NULL), \
283 (dlp)->num_alloc = obj_count, \
286 #define UTRACE_DLOPEN_START 1
287 #define UTRACE_DLOPEN_STOP 2
288 #define UTRACE_DLCLOSE_START 3
289 #define UTRACE_DLCLOSE_STOP 4
290 #define UTRACE_LOAD_OBJECT 5
291 #define UTRACE_UNLOAD_OBJECT 6
292 #define UTRACE_ADD_RUNDEP 7
293 #define UTRACE_PRELOAD_FINISHED 8
294 #define UTRACE_INIT_CALL 9
295 #define UTRACE_FINI_CALL 10
298 char sig[4]; /* 'RTLD' */
301 void *mapbase; /* Used for 'parent' and 'init/fini' */
303 int refcnt; /* Used for 'mode' */
304 char name[MAXPATHLEN];
307 #define LD_UTRACE(e, h, mb, ms, r, n) do { \
308 if (ld_utrace != NULL) \
309 ld_utrace_log(e, h, mb, ms, r, n); \
313 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
314 int refcnt, const char *name)
316 struct utrace_rtld ut;
324 ut.mapbase = mapbase;
325 ut.mapsize = mapsize;
327 bzero(ut.name, sizeof(ut.name));
329 strlcpy(ut.name, name, sizeof(ut.name));
330 utrace(&ut, sizeof(ut));
334 * Main entry point for dynamic linking. The first argument is the
335 * stack pointer. The stack is expected to be laid out as described
336 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
337 * Specifically, the stack pointer points to a word containing
338 * ARGC. Following that in the stack is a null-terminated sequence
339 * of pointers to argument strings. Then comes a null-terminated
340 * sequence of pointers to environment strings. Finally, there is a
341 * sequence of "auxiliary vector" entries.
343 * The second argument points to a place to store the dynamic linker's
344 * exit procedure pointer and the third to a place to store the main
347 * The return value is the main program's entry point.
350 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
352 Elf_Auxinfo *aux_info[AT_COUNT];
360 Objlist_Entry *entry;
363 /* marino: DO NOT MOVE THESE VARIABLES TO _rtld
364 Obj_Entry **preload_tail;
366 from global to here. It will break the DWARF2 unwind scheme.
367 The system compilers were unaffected, but not gcc 4.6
371 * On entry, the dynamic linker itself has not been relocated yet.
372 * Be very careful not to reference any global data until after
373 * init_rtld has returned. It is OK to reference file-scope statics
374 * and string constants, and to call static and global functions.
377 /* Find the auxiliary vector on the stack. */
380 sp += argc + 1; /* Skip over arguments and NULL terminator */
384 * If we aren't already resident we have to dig out some more info.
385 * Note that auxinfo does not exist when we are resident.
387 * I'm not sure about the ld_resident check. It seems to read zero
388 * prior to relocation, which is what we want. When running from a
389 * resident copy everything will be relocated so we are definitely
392 if (ld_resident == 0) {
393 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
395 aux = (Elf_Auxinfo *) sp;
397 /* Digest the auxiliary vector. */
398 for (i = 0; i < AT_COUNT; i++)
400 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
401 if (auxp->a_type < AT_COUNT)
402 aux_info[auxp->a_type] = auxp;
405 /* Initialize and relocate ourselves. */
406 assert(aux_info[AT_BASE] != NULL);
407 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
410 ld_index = 0; /* don't use old env cache in case we are resident */
411 __progname = obj_rtld.path;
412 argv0 = argv[0] != NULL ? argv[0] : "(null)";
417 trust = !issetugid();
419 ld_bind_now = _getenv_ld("LD_BIND_NOW");
421 * If the process is tainted, then we un-set the dangerous environment
422 * variables. The process will be marked as tainted until setuid(2)
423 * is called. If any child process calls setuid(2) we do not want any
424 * future processes to honor the potentially un-safe variables.
427 if ( unsetenv("LD_DEBUG")
428 || unsetenv("LD_PRELOAD")
429 || unsetenv("LD_LIBRARY_PATH")
430 || unsetenv("LD_ELF_HINTS_PATH")
431 || unsetenv("LD_LIBMAP")
432 || unsetenv("LD_LIBMAP_DISABLE")
433 || unsetenv("LD_LOADFLTR")
435 _rtld_error("environment corrupt; aborting");
439 ld_debug = _getenv_ld("LD_DEBUG");
440 libmap_disable = _getenv_ld("LD_LIBMAP_DISABLE") != NULL;
441 libmap_override = (char *)_getenv_ld("LD_LIBMAP");
442 ld_library_path = _getenv_ld("LD_LIBRARY_PATH");
443 ld_preload = (char *)_getenv_ld("LD_PRELOAD");
444 ld_elf_hints_path = _getenv_ld("LD_ELF_HINTS_PATH");
445 ld_loadfltr = _getenv_ld("LD_LOADFLTR") != NULL;
446 dangerous_ld_env = (ld_library_path != NULL)
447 || (ld_preload != NULL)
448 || (ld_elf_hints_path != NULL)
450 || (libmap_override != NULL)
453 ld_tracing = _getenv_ld("LD_TRACE_LOADED_OBJECTS");
454 ld_utrace = _getenv_ld("LD_UTRACE");
456 if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0)
457 ld_elf_hints_path = _PATH_ELF_HINTS;
459 if (ld_debug != NULL && *ld_debug != '\0')
461 dbg("%s is initialized, base address = %p", __progname,
462 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
463 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
464 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
466 dbg("initializing thread locks");
470 * If we are resident we can skip work that we have already done.
471 * Note that the stack is reset and there is no Elf_Auxinfo
472 * when running from a resident image, and the static globals setup
473 * between here and resident_skip will have already been setup.
479 * Load the main program, or process its program header if it is
482 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
483 int fd = aux_info[AT_EXECFD]->a_un.a_val;
484 dbg("loading main program");
485 obj_main = map_object(fd, argv0, NULL);
487 if (obj_main == NULL)
489 max_stack_flags = obj->stack_flags;
490 } else { /* Main program already loaded. */
491 const Elf_Phdr *phdr;
495 dbg("processing main program's program header");
496 assert(aux_info[AT_PHDR] != NULL);
497 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
498 assert(aux_info[AT_PHNUM] != NULL);
499 phnum = aux_info[AT_PHNUM]->a_un.a_val;
500 assert(aux_info[AT_PHENT] != NULL);
501 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
502 assert(aux_info[AT_ENTRY] != NULL);
503 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
504 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
508 char buf[MAXPATHLEN];
509 if (aux_info[AT_EXECPATH] != NULL) {
512 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
513 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
514 if (kexecpath[0] == '/')
515 obj_main->path = kexecpath;
516 else if (getcwd(buf, sizeof(buf)) == NULL ||
517 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
518 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
519 obj_main->path = xstrdup(argv0);
521 obj_main->path = xstrdup(buf);
523 char resolved[MAXPATHLEN];
524 dbg("No AT_EXECPATH");
525 if (argv0[0] == '/') {
526 if (realpath(argv0, resolved) != NULL)
527 obj_main->path = xstrdup(resolved);
529 obj_main->path = xstrdup(argv0);
531 if (getcwd(buf, sizeof(buf)) != NULL
532 && strlcat(buf, "/", sizeof(buf)) < sizeof(buf)
533 && strlcat(buf, argv0, sizeof (buf)) < sizeof(buf)
534 && access(buf, R_OK) == 0
535 && realpath(buf, resolved) != NULL)
536 obj_main->path = xstrdup(resolved);
538 obj_main->path = xstrdup(argv0);
541 dbg("obj_main path %s", obj_main->path);
542 obj_main->mainprog = true;
544 if (aux_info[AT_STACKPROT] != NULL &&
545 aux_info[AT_STACKPROT]->a_un.a_val != 0)
546 stack_prot = aux_info[AT_STACKPROT]->a_un.a_val;
549 * Get the actual dynamic linker pathname from the executable if
550 * possible. (It should always be possible.) That ensures that
551 * gdb will find the right dynamic linker even if a non-standard
554 if (obj_main->interp != NULL &&
555 strcmp(obj_main->interp, obj_rtld.path) != 0) {
557 obj_rtld.path = xstrdup(obj_main->interp);
558 __progname = obj_rtld.path;
561 digest_dynamic(obj_main, 0);
563 linkmap_add(obj_main);
564 linkmap_add(&obj_rtld);
566 /* Link the main program into the list of objects. */
567 *obj_tail = obj_main;
568 obj_tail = &obj_main->next;
572 /* Initialize a fake symbol for resolving undefined weak references. */
573 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
574 sym_zero.st_shndx = SHN_UNDEF;
575 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
578 libmap_disable = (bool)lm_init(libmap_override);
580 dbg("loading LD_PRELOAD libraries");
581 if (load_preload_objects() == -1)
583 preload_tail = obj_tail;
585 dbg("loading needed objects");
586 if (load_needed_objects(obj_main, 0) == -1)
589 /* Make a list of all objects loaded at startup. */
590 for (obj = obj_list; obj != NULL; obj = obj->next) {
591 objlist_push_tail(&list_main, obj);
595 dbg("checking for required versions");
596 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
601 if (ld_tracing) { /* We're done */
602 trace_loaded_objects(obj_main);
606 if (ld_resident) /* XXX clean this up! */
609 if (_getenv_ld("LD_DUMP_REL_PRE") != NULL) {
610 dump_relocations(obj_main);
614 /* setup TLS for main thread */
615 dbg("initializing initial thread local storage");
616 STAILQ_FOREACH(entry, &list_main, link) {
618 * Allocate all the initial objects out of the static TLS
619 * block even if they didn't ask for it.
621 allocate_tls_offset(entry->obj);
624 tls_static_space = tls_last_offset + RTLD_STATIC_TLS_EXTRA;
627 * Do not try to allocate the TLS here, let libc do it itself.
628 * (crt1 for the program will call _init_tls())
631 if (relocate_objects(obj_main,
632 ld_bind_now != NULL && *ld_bind_now != '\0',
633 &obj_rtld, SYMLOOK_EARLY, NULL) == -1)
636 dbg("doing copy relocations");
637 if (do_copy_relocations(obj_main) == -1)
642 if (_getenv_ld("LD_RESIDENT_UNREGISTER_NOW")) {
643 if (exec_sys_unregister(-1) < 0) {
644 dbg("exec_sys_unregister failed %d\n", errno);
647 dbg("exec_sys_unregister success\n");
651 if (_getenv_ld("LD_DUMP_REL_POST") != NULL) {
652 dump_relocations(obj_main);
656 dbg("initializing key program variables");
657 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
658 set_program_var("environ", env);
659 set_program_var("__elf_aux_vector", aux);
661 if (_getenv_ld("LD_RESIDENT_REGISTER_NOW")) {
662 extern void resident_start(void);
664 if (exec_sys_register(resident_start) < 0) {
665 dbg("exec_sys_register failed %d\n", errno);
668 dbg("exec_sys_register success\n");
672 /* Make a list of init functions to call. */
673 objlist_init(&initlist);
674 initlist_add_objects(obj_list, preload_tail, &initlist);
676 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
678 map_stacks_exec(NULL);
680 dbg("resolving ifuncs");
681 if (resolve_objects_ifunc(obj_main,
682 ld_bind_now != NULL && *ld_bind_now != '\0', SYMLOOK_EARLY,
687 * Do NOT call the initlist here, give libc a chance to set up
688 * the initial TLS segment. crt1 will then call _rtld_call_init().
691 dbg("transferring control to program entry point = %p", obj_main->entry);
693 /* Return the exit procedure and the program entry point. */
694 *exit_proc = rtld_exit;
696 return (func_ptr_type) obj_main->entry;
700 * Call the initialization list for dynamically loaded libraries.
701 * (called from crt1.c).
704 _rtld_call_init(void)
706 RtldLockState lockstate;
709 if (!obj_main->note_present && obj_main->valid_hash_gnu) {
711 * The use of a linker script with a PHDRS directive that does not include
712 * PT_NOTE will block the crt_no_init note. In this case we'll look for the
713 * recently added GNU hash dynamic tag which gets built by default. It is
714 * extremely unlikely to find a pre-3.1 binary without a PT_NOTE header and
715 * a gnu hash tag. If gnu hash found, consider binary to use new crt code.
717 obj_main->crt_no_init = true;
718 dbg("Setting crt_no_init without presence of PT_NOTE header");
721 wlock_acquire(rtld_bind_lock, &lockstate);
722 if (obj_main->crt_no_init) {
723 preinitialize_main_object();
727 * Make sure we don't call the main program's init and fini functions
728 * for binaries linked with old crt1 which calls _init itself.
730 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
731 obj_main->init_array = obj_main->fini_array = (Elf_Addr)NULL;
733 objlist_call_init(&initlist, &lockstate);
734 objlist_clear(&initlist);
735 dbg("loading filtees");
736 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
737 if (ld_loadfltr || obj->z_loadfltr)
738 load_filtees(obj, 0, &lockstate);
740 lock_release(rtld_bind_lock, &lockstate);
744 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def)
749 ptr = (void *)make_function_pointer(def, obj);
750 target = ((Elf_Addr (*)(void))ptr)();
751 return ((void *)target);
755 _rtld_bind(Obj_Entry *obj, Elf_Size reloff, void *stack)
759 const Obj_Entry *defobj;
762 RtldLockState lockstate;
764 rlock_acquire(rtld_bind_lock, &lockstate);
765 if (sigsetjmp(lockstate.env, 0) != 0)
766 lock_upgrade(rtld_bind_lock, &lockstate);
768 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
770 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
772 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
773 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL,
777 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
778 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
780 target = (Elf_Addr)(defobj->relocbase + def->st_value);
782 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
783 defobj->strtab + def->st_name, basename(obj->path),
784 (void *)target, basename(defobj->path));
787 * If we have a function call tracing hook, and the
788 * hook would like to keep tracing this one function,
789 * prevent the relocation so we will wind up here
790 * the next time again.
792 * We don't want to functrace calls from the functracer
793 * to avoid recursive loops.
795 if (rtld_functrace != NULL && obj != rtld_functrace_obj) {
796 if (rtld_functrace(obj->path,
798 defobj->strtab + def->st_name,
800 lock_release(rtld_bind_lock, &lockstate);
805 * Write the new contents for the jmpslot. Note that depending on
806 * architecture, the value which we need to return back to the
807 * lazy binding trampoline may or may not be the target
808 * address. The value returned from reloc_jmpslot() is the value
809 * that the trampoline needs.
811 target = reloc_jmpslot(where, target, defobj, obj, rel);
812 lock_release(rtld_bind_lock, &lockstate);
817 * Error reporting function. Use it like printf. If formats the message
818 * into a buffer, and sets things up so that the next call to dlerror()
819 * will return the message.
822 _rtld_error(const char *fmt, ...)
824 static char buf[512];
828 rtld_vsnprintf(buf, sizeof buf, fmt, ap);
834 * Return a dynamically-allocated copy of the current error message, if any.
839 return error_message == NULL ? NULL : xstrdup(error_message);
843 * Restore the current error message from a copy which was previously saved
844 * by errmsg_save(). The copy is freed.
847 errmsg_restore(char *saved_msg)
849 if (saved_msg == NULL)
850 error_message = NULL;
852 _rtld_error("%s", saved_msg);
858 basename(const char *name)
860 const char *p = strrchr(name, '/');
861 return p != NULL ? p + 1 : name;
864 static struct utsname uts;
867 origin_subst_one(char **res, const char *real, const char *kw, const char *subst,
877 subst_len = kw_len = 0;
881 if (subst_len == 0) {
882 subst_len = strlen(subst);
886 *res = xmalloc(PATH_MAX);
889 if ((res1 - *res) + subst_len + (p1 - p) >= PATH_MAX) {
890 _rtld_error("Substitution of %s in %s cannot be performed",
892 if (may_free != NULL)
897 memcpy(res1, p, p1 - p);
899 memcpy(res1, subst, subst_len);
904 if (may_free != NULL)
907 *res = xstrdup(real);
911 if (may_free != NULL)
913 if (strlcat(res1, p, PATH_MAX - (res1 - *res)) >= PATH_MAX) {
923 origin_subst(const char *real, const char *origin_path)
925 char *res1, *res2, *res3, *res4;
927 if (uts.sysname[0] == '\0') {
928 if (uname(&uts) != 0) {
929 _rtld_error("utsname failed: %d", errno);
933 if (!origin_subst_one(&res1, real, "$ORIGIN", origin_path, NULL) ||
934 !origin_subst_one(&res2, res1, "$OSNAME", uts.sysname, res1) ||
935 !origin_subst_one(&res3, res2, "$OSREL", uts.release, res2) ||
936 !origin_subst_one(&res4, res3, "$PLATFORM", uts.machine, res3))
944 const char *msg = dlerror();
948 rtld_fdputstr(STDERR_FILENO, msg);
949 rtld_fdputchar(STDERR_FILENO, '\n');
954 * Process a shared object's DYNAMIC section, and save the important
955 * information in its Obj_Entry structure.
958 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
959 const Elf_Dyn **dyn_soname, const Elf_Dyn **dyn_runpath)
962 Needed_Entry **needed_tail = &obj->needed;
963 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
964 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
965 int plttype = DT_REL;
971 obj->bind_now = false;
972 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
973 switch (dynp->d_tag) {
976 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
980 obj->relsize = dynp->d_un.d_val;
984 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
988 obj->pltrel = (const Elf_Rel *)
989 (obj->relocbase + dynp->d_un.d_ptr);
993 obj->pltrelsize = dynp->d_un.d_val;
997 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
1001 obj->relasize = dynp->d_un.d_val;
1005 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
1009 plttype = dynp->d_un.d_val;
1010 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
1014 obj->symtab = (const Elf_Sym *)
1015 (obj->relocbase + dynp->d_un.d_ptr);
1019 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
1023 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
1027 obj->strsize = dynp->d_un.d_val;
1031 obj->verneed = (const Elf_Verneed *) (obj->relocbase +
1036 obj->verneednum = dynp->d_un.d_val;
1040 obj->verdef = (const Elf_Verdef *) (obj->relocbase +
1045 obj->verdefnum = dynp->d_un.d_val;
1049 obj->versyms = (const Elf_Versym *)(obj->relocbase +
1055 const Elf_Hashelt *hashtab = (const Elf_Hashelt *)
1056 (obj->relocbase + dynp->d_un.d_ptr);
1057 obj->nbuckets = hashtab[0];
1058 obj->nchains = hashtab[1];
1059 obj->buckets = hashtab + 2;
1060 obj->chains = obj->buckets + obj->nbuckets;
1061 obj->valid_hash_sysv = obj->nbuckets > 0 && obj->nchains > 0 &&
1062 obj->buckets != NULL;
1068 const Elf_Hashelt *hashtab = (const Elf_Hashelt *)
1069 (obj->relocbase + dynp->d_un.d_ptr);
1070 obj->nbuckets_gnu = hashtab[0];
1071 obj->symndx_gnu = hashtab[1];
1072 const Elf32_Word nmaskwords = hashtab[2];
1073 const int bloom_size32 = (__ELF_WORD_SIZE / 32) * nmaskwords;
1074 /* Number of bitmask words is required to be power of 2 */
1075 const bool nmw_power2 = ((nmaskwords & (nmaskwords - 1)) == 0);
1076 obj->maskwords_bm_gnu = nmaskwords - 1;
1077 obj->shift2_gnu = hashtab[3];
1078 obj->bloom_gnu = (Elf_Addr *) (hashtab + 4);
1079 obj->buckets_gnu = hashtab + 4 + bloom_size32;
1080 obj->chain_zero_gnu = obj->buckets_gnu + obj->nbuckets_gnu -
1082 obj->valid_hash_gnu = nmw_power2 && obj->nbuckets_gnu > 0 &&
1083 obj->buckets_gnu != NULL;
1089 Needed_Entry *nep = NEW(Needed_Entry);
1090 nep->name = dynp->d_un.d_val;
1095 needed_tail = &nep->next;
1101 Needed_Entry *nep = NEW(Needed_Entry);
1102 nep->name = dynp->d_un.d_val;
1106 *needed_filtees_tail = nep;
1107 needed_filtees_tail = &nep->next;
1113 Needed_Entry *nep = NEW(Needed_Entry);
1114 nep->name = dynp->d_un.d_val;
1118 *needed_aux_filtees_tail = nep;
1119 needed_aux_filtees_tail = &nep->next;
1124 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
1128 obj->textrel = true;
1132 obj->symbolic = true;
1137 * We have to wait until later to process this, because we
1138 * might not have gotten the address of the string table yet.
1148 *dyn_runpath = dynp;
1152 obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1156 obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1159 case DT_PREINIT_ARRAY:
1160 obj->preinit_array = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1164 obj->init_array = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1168 obj->fini_array = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1171 case DT_PREINIT_ARRAYSZ:
1172 obj->preinit_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1175 case DT_INIT_ARRAYSZ:
1176 obj->init_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1179 case DT_FINI_ARRAYSZ:
1180 obj->fini_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1184 /* XXX - not implemented yet */
1186 dbg("Filling in DT_DEBUG entry");
1187 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
1191 if ((dynp->d_un.d_val & DF_ORIGIN) && trust)
1192 obj->z_origin = true;
1193 if (dynp->d_un.d_val & DF_SYMBOLIC)
1194 obj->symbolic = true;
1195 if (dynp->d_un.d_val & DF_TEXTREL)
1196 obj->textrel = true;
1197 if (dynp->d_un.d_val & DF_BIND_NOW)
1198 obj->bind_now = true;
1199 /*if (dynp->d_un.d_val & DF_STATIC_TLS)
1204 if (dynp->d_un.d_val & DF_1_NOOPEN)
1205 obj->z_noopen = true;
1206 if ((dynp->d_un.d_val & DF_1_ORIGIN) && trust)
1207 obj->z_origin = true;
1208 /*if (dynp->d_un.d_val & DF_1_GLOBAL)
1210 if (dynp->d_un.d_val & DF_1_BIND_NOW)
1211 obj->bind_now = true;
1212 if (dynp->d_un.d_val & DF_1_NODELETE)
1213 obj->z_nodelete = true;
1214 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1215 obj->z_loadfltr = true;
1216 if (dynp->d_un.d_val & DF_1_NODEFLIB)
1217 obj->z_nodeflib = true;
1222 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1229 obj->traced = false;
1231 if (plttype == DT_RELA) {
1232 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1234 obj->pltrelasize = obj->pltrelsize;
1235 obj->pltrelsize = 0;
1238 /* Determine size of dynsym table (equal to nchains of sysv hash) */
1239 if (obj->valid_hash_sysv)
1240 obj->dynsymcount = obj->nchains;
1241 else if (obj->valid_hash_gnu) {
1242 obj->dynsymcount = 0;
1243 for (Elf32_Word bkt = 0; bkt < obj->nbuckets_gnu; bkt++) {
1244 if (obj->buckets_gnu[bkt] == 0)
1246 const Elf32_Word *hashval = &obj->chain_zero_gnu[obj->buckets_gnu[bkt]];
1249 while ((*hashval++ & 1u) == 0);
1251 obj->dynsymcount += obj->symndx_gnu;
1256 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1257 const Elf_Dyn *dyn_soname, const Elf_Dyn *dyn_runpath)
1260 if (obj->z_origin && obj->origin_path == NULL) {
1261 obj->origin_path = xmalloc(PATH_MAX);
1262 if (rtld_dirname_abs(obj->path, obj->origin_path) == -1)
1266 if (dyn_runpath != NULL) {
1267 obj->runpath = (char *)obj->strtab + dyn_runpath->d_un.d_val;
1269 obj->runpath = origin_subst(obj->runpath, obj->origin_path);
1271 else if (dyn_rpath != NULL) {
1272 obj->rpath = (char *)obj->strtab + dyn_rpath->d_un.d_val;
1274 obj->rpath = origin_subst(obj->rpath, obj->origin_path);
1277 if (dyn_soname != NULL)
1278 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1282 digest_dynamic(Obj_Entry *obj, int early)
1284 const Elf_Dyn *dyn_rpath;
1285 const Elf_Dyn *dyn_soname;
1286 const Elf_Dyn *dyn_runpath;
1288 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname, &dyn_runpath);
1289 digest_dynamic2(obj, dyn_rpath, dyn_soname, dyn_runpath);
1293 * Process a shared object's program header. This is used only for the
1294 * main program, when the kernel has already loaded the main program
1295 * into memory before calling the dynamic linker. It creates and
1296 * returns an Obj_Entry structure.
1299 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1302 const Elf_Phdr *phlimit = phdr + phnum;
1304 Elf_Addr note_start, note_end;
1308 for (ph = phdr; ph < phlimit; ph++) {
1309 if (ph->p_type != PT_PHDR)
1313 obj->phsize = ph->p_memsz;
1314 obj->relocbase = (caddr_t)phdr - ph->p_vaddr;
1318 obj->stack_flags = PF_X | PF_R | PF_W;
1320 for (ph = phdr; ph < phlimit; ph++) {
1321 switch (ph->p_type) {
1324 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1328 if (nsegs == 0) { /* First load segment */
1329 obj->vaddrbase = trunc_page(ph->p_vaddr);
1330 obj->mapbase = obj->vaddrbase + obj->relocbase;
1331 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
1333 } else { /* Last load segment */
1334 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1341 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1346 obj->tlssize = ph->p_memsz;
1347 obj->tlsalign = ph->p_align;
1348 obj->tlsinitsize = ph->p_filesz;
1349 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1353 obj->stack_flags = ph->p_flags;
1357 obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1358 obj->relro_size = round_page(ph->p_memsz);
1362 obj->note_present = true;
1363 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
1364 note_end = note_start + ph->p_filesz;
1365 digest_notes(obj, note_start, note_end);
1370 _rtld_error("%s: too few PT_LOAD segments", path);
1379 digest_notes(Obj_Entry *obj, Elf_Addr note_start, Elf_Addr note_end)
1381 const Elf_Note *note;
1382 const char *note_name;
1385 for (note = (const Elf_Note *)note_start; (Elf_Addr)note < note_end;
1386 note = (const Elf_Note *)((const char *)(note + 1) +
1387 roundup2(note->n_namesz, sizeof(Elf32_Addr)) +
1388 roundup2(note->n_descsz, sizeof(Elf32_Addr)))) {
1389 if (note->n_namesz != sizeof(NOTE_VENDOR) ||
1390 note->n_descsz != sizeof(int32_t))
1392 if (note->n_type != ABI_NOTETYPE && note->n_type != CRT_NOINIT_NOTETYPE)
1394 note_name = (const char *)(note + 1);
1395 if (strncmp(NOTE_VENDOR, note_name, sizeof(NOTE_VENDOR)) != 0)
1397 switch (note->n_type) {
1399 /* DragonFly osrel note */
1400 p = (uintptr_t)(note + 1);
1401 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1402 obj->osrel = *(const int32_t *)(p);
1403 dbg("note osrel %d", obj->osrel);
1405 case CRT_NOINIT_NOTETYPE:
1406 /* DragonFly 'crt does not call init' note */
1407 obj->crt_no_init = true;
1408 dbg("note crt_no_init");
1415 dlcheck(void *handle)
1419 for (obj = obj_list; obj != NULL; obj = obj->next)
1420 if (obj == (Obj_Entry *) handle)
1423 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1424 _rtld_error("Invalid shared object handle %p", handle);
1431 * If the given object is already in the donelist, return true. Otherwise
1432 * add the object to the list and return false.
1435 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1439 for (i = 0; i < dlp->num_used; i++)
1440 if (dlp->objs[i] == obj)
1443 * Our donelist allocation should always be sufficient. But if
1444 * our threads locking isn't working properly, more shared objects
1445 * could have been loaded since we allocated the list. That should
1446 * never happen, but we'll handle it properly just in case it does.
1448 if (dlp->num_used < dlp->num_alloc)
1449 dlp->objs[dlp->num_used++] = obj;
1454 * Hash function for symbol table lookup. Don't even think about changing
1455 * this. It is specified by the System V ABI.
1458 elf_hash(const char *name)
1460 const unsigned char *p = (const unsigned char *) name;
1461 unsigned long h = 0;
1464 while (*p != '\0') {
1465 h = (h << 4) + *p++;
1466 if ((g = h & 0xf0000000) != 0)
1474 * The GNU hash function is the Daniel J. Bernstein hash clipped to 32 bits
1475 * unsigned in case it's implemented with a wider type.
1477 static uint_fast32_t
1478 gnu_hash (const char *s)
1480 uint_fast32_t h = 5381;
1481 for (unsigned char c = *s; c != '\0'; c = *++s)
1483 return h & 0xffffffff;
1487 * Find the library with the given name, and return its full pathname.
1488 * The returned string is dynamically allocated. Generates an error
1489 * message and returns NULL if the library cannot be found.
1491 * If the second argument is non-NULL, then it refers to an already-
1492 * loaded shared object, whose library search path will be searched.
1494 * The search order is:
1495 * DT_RPATH in the referencing file _unless_ DT_RUNPATH is present (1)
1496 * DT_RPATH of the main object if DSO without defined DT_RUNPATH (1)
1498 * DT_RUNPATH in the referencing file
1499 * ldconfig hints (if -z nodefaultlib, filter out /usr/lib from list)
1500 * /usr/lib _unless_ the referencing file is linked with -z nodefaultlib
1502 * (1) Handled in digest_dynamic2 - rpath left NULL if runpath defined.
1505 find_library(const char *xname, const Obj_Entry *refobj)
1509 bool objgiven = (refobj != NULL);
1511 if (strchr(xname, '/') != NULL) { /* Hard coded pathname */
1512 if (xname[0] != '/' && !trust) {
1513 _rtld_error("Absolute pathname required for shared object \"%s\"",
1517 if (objgiven && refobj->z_origin)
1518 return origin_subst(xname, refobj->origin_path);
1520 return xstrdup(xname);
1523 if (libmap_disable || !objgiven ||
1524 (name = lm_find(refobj->path, xname)) == NULL)
1525 name = (char *)xname;
1527 dbg(" Searching for \"%s\"", name);
1530 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
1531 (objgiven && (refobj->runpath == NULL) && (refobj != obj_main) &&
1532 (pathname = search_library_path(name, obj_main->rpath)) != NULL) ||
1533 (pathname = search_library_path(name, ld_library_path)) != NULL ||
1535 (pathname = search_library_path(name, refobj->runpath)) != NULL) ||
1536 (pathname = search_library_path(name, gethints(refobj))) != NULL ||
1537 (objgiven && !refobj->z_nodeflib &&
1538 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL))
1541 if(objgiven && refobj->path != NULL) {
1542 _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
1543 name, basename(refobj->path));
1545 _rtld_error("Shared object \"%s\" not found", name);
1551 * Given a symbol number in a referencing object, find the corresponding
1552 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1553 * no definition was found. Returns a pointer to the Obj_Entry of the
1554 * defining object via the reference parameter DEFOBJ_OUT.
1557 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1558 const Obj_Entry **defobj_out, int flags, SymCache *cache,
1559 RtldLockState *lockstate)
1563 const Obj_Entry *defobj;
1569 * If we have already found this symbol, get the information from
1572 if (symnum >= refobj->dynsymcount)
1573 return NULL; /* Bad object */
1574 if (cache != NULL && cache[symnum].sym != NULL) {
1575 *defobj_out = cache[symnum].obj;
1576 return cache[symnum].sym;
1579 ref = refobj->symtab + symnum;
1580 name = refobj->strtab + ref->st_name;
1585 * We don't have to do a full scale lookup if the symbol is local.
1586 * We know it will bind to the instance in this load module; to
1587 * which we already have a pointer (ie ref). By not doing a lookup,
1588 * we not only improve performance, but it also avoids unresolvable
1589 * symbols when local symbols are not in the hash table.
1591 * This might occur for TLS module relocations, which simply use
1594 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1595 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1596 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1599 symlook_init(&req, name);
1601 req.ventry = fetch_ventry(refobj, symnum);
1602 req.lockstate = lockstate;
1603 res = symlook_default(&req, refobj);
1606 defobj = req.defobj_out;
1614 * If we found no definition and the reference is weak, treat the
1615 * symbol as having the value zero.
1617 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1623 *defobj_out = defobj;
1624 /* Record the information in the cache to avoid subsequent lookups. */
1625 if (cache != NULL) {
1626 cache[symnum].sym = def;
1627 cache[symnum].obj = defobj;
1630 if (refobj != &obj_rtld)
1631 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1637 * Return the search path from the ldconfig hints file, reading it if
1638 * necessary. Returns NULL if there are problems with the hints file,
1639 * or if the search path there is empty.
1640 * If DF_1_NODEFLIB flag set, omit STANDARD_LIBRARY_PATH directories
1643 gethints(const Obj_Entry *obj)
1647 if (hints == NULL) {
1649 struct elfhints_hdr hdr;
1652 /* Keep from trying again in case the hints file is bad. */
1655 if ((fd = open(ld_elf_hints_path, O_RDONLY)) == -1)
1657 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1658 hdr.magic != ELFHINTS_MAGIC ||
1663 p = xmalloc(hdr.dirlistlen + 1);
1664 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1665 read(fd, p, hdr.dirlistlen + 1) != (ssize_t)hdr.dirlistlen + 1) {
1670 /* skip stdlib if compiled with -z nodeflib */
1671 if ((obj != NULL) && obj->z_nodeflib) {
1672 struct fill_search_info_args sargs, hargs;
1673 struct dl_serinfo smeta, hmeta, *SLPinfo, *hintinfo;
1674 struct dl_serpath *SLPpath, *hintpath;
1675 unsigned int SLPndx, hintndx, fndx, fcount;
1676 char *filtered_path;
1680 smeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1682 hmeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1685 sargs.request = RTLD_DI_SERINFOSIZE;
1686 sargs.serinfo = &smeta;
1687 hargs.request = RTLD_DI_SERINFOSIZE;
1688 hargs.serinfo = &hmeta;
1690 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &sargs);
1691 path_enumerate(p, fill_search_info, &hargs);
1693 SLPinfo = malloc(smeta.dls_size);
1694 hintinfo = malloc(hmeta.dls_size);
1696 sargs.request = RTLD_DI_SERINFO;
1697 sargs.serinfo = SLPinfo;
1698 sargs.serpath = &SLPinfo->dls_serpath[0];
1699 sargs.strspace = (char *)&SLPinfo->dls_serpath[smeta.dls_cnt];
1701 hargs.request = RTLD_DI_SERINFO;
1702 hargs.serinfo = hintinfo;
1703 hargs.serpath = &hintinfo->dls_serpath[0];
1704 hargs.strspace = (char *)&hintinfo->dls_serpath[hmeta.dls_cnt];
1706 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &sargs);
1707 path_enumerate(p, fill_search_info, &hargs);
1711 filtered_path = xmalloc(hdr.dirlistlen + 1);
1712 hintpath = &hintinfo->dls_serpath[0];
1713 for (hintndx = 0; hintndx < hmeta.dls_cnt; hintndx++) {
1715 SLPpath = &SLPinfo->dls_serpath[0];
1716 for (SLPndx = 0; SLPndx < smeta.dls_cnt; SLPndx++) {
1717 if (strcmp(hintpath->dls_name, SLPpath->dls_name) == 0)
1723 filtered_path[fndx] = ':';
1727 flen = strlen(hintpath->dls_name);
1728 strncpy((filtered_path + fndx), hintpath->dls_name, flen);
1733 filtered_path[fndx] = '\0';
1738 hints = filtered_path;
1744 return hints[0] != '\0' ? hints : NULL;
1748 init_dag(Obj_Entry *root)
1750 const Needed_Entry *needed;
1751 const Objlist_Entry *elm;
1754 if (root->dag_inited)
1756 donelist_init(&donelist);
1758 /* Root object belongs to own DAG. */
1759 objlist_push_tail(&root->dldags, root);
1760 objlist_push_tail(&root->dagmembers, root);
1761 donelist_check(&donelist, root);
1764 * Add dependencies of root object to DAG in breadth order
1765 * by exploiting the fact that each new object get added
1766 * to the tail of the dagmembers list.
1768 STAILQ_FOREACH(elm, &root->dagmembers, link) {
1769 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
1770 if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
1772 objlist_push_tail(&needed->obj->dldags, root);
1773 objlist_push_tail(&root->dagmembers, needed->obj);
1776 root->dag_inited = true;
1780 * Initialize the dynamic linker. The argument is the address at which
1781 * the dynamic linker has been mapped into memory. The primary task of
1782 * this function is to relocate the dynamic linker.
1785 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
1787 Obj_Entry objtmp; /* Temporary rtld object */
1788 const Elf_Dyn *dyn_rpath;
1789 const Elf_Dyn *dyn_soname;
1790 const Elf_Dyn *dyn_runpath;
1793 * Conjure up an Obj_Entry structure for the dynamic linker.
1795 * The "path" member can't be initialized yet because string constants
1796 * cannot yet be accessed. Below we will set it correctly.
1798 memset(&objtmp, 0, sizeof(objtmp));
1801 objtmp.mapbase = mapbase;
1803 objtmp.relocbase = mapbase;
1805 if (RTLD_IS_DYNAMIC()) {
1806 objtmp.dynamic = rtld_dynamic(&objtmp);
1807 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname, &dyn_runpath);
1808 assert(objtmp.needed == NULL);
1809 assert(!objtmp.textrel);
1812 * Temporarily put the dynamic linker entry into the object list, so
1813 * that symbols can be found.
1816 relocate_objects(&objtmp, true, &objtmp, 0, NULL);
1819 /* Initialize the object list. */
1820 obj_tail = &obj_list;
1822 /* Now that non-local variables can be accesses, copy out obj_rtld. */
1823 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1825 #ifdef ENABLE_OSRELDATE
1826 if (aux_info[AT_OSRELDATE] != NULL)
1827 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
1830 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname, dyn_runpath);
1832 /* Replace the path with a dynamically allocated copy. */
1833 obj_rtld.path = xstrdup(PATH_RTLD);
1835 r_debug.r_brk = r_debug_state;
1836 r_debug.r_state = RT_CONSISTENT;
1840 * Add the init functions from a needed object list (and its recursive
1841 * needed objects) to "list". This is not used directly; it is a helper
1842 * function for initlist_add_objects(). The write lock must be held
1843 * when this function is called.
1846 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1848 /* Recursively process the successor needed objects. */
1849 if (needed->next != NULL)
1850 initlist_add_neededs(needed->next, list);
1852 /* Process the current needed object. */
1853 if (needed->obj != NULL)
1854 initlist_add_objects(needed->obj, &needed->obj->next, list);
1858 * Scan all of the DAGs rooted in the range of objects from "obj" to
1859 * "tail" and add their init functions to "list". This recurses over
1860 * the DAGs and ensure the proper init ordering such that each object's
1861 * needed libraries are initialized before the object itself. At the
1862 * same time, this function adds the objects to the global finalization
1863 * list "list_fini" in the opposite order. The write lock must be
1864 * held when this function is called.
1867 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1870 if (obj->init_scanned || obj->init_done)
1872 obj->init_scanned = true;
1874 /* Recursively process the successor objects. */
1875 if (&obj->next != tail)
1876 initlist_add_objects(obj->next, tail, list);
1878 /* Recursively process the needed objects. */
1879 if (obj->needed != NULL)
1880 initlist_add_neededs(obj->needed, list);
1881 if (obj->needed_filtees != NULL)
1882 initlist_add_neededs(obj->needed_filtees, list);
1883 if (obj->needed_aux_filtees != NULL)
1884 initlist_add_neededs(obj->needed_aux_filtees, list);
1886 /* Add the object to the init list. */
1887 if (obj->preinit_array != (Elf_Addr)NULL || obj->init != (Elf_Addr)NULL ||
1888 obj->init_array != (Elf_Addr)NULL)
1889 objlist_push_tail(list, obj);
1891 /* Add the object to the global fini list in the reverse order. */
1892 if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL)
1893 && !obj->on_fini_list) {
1894 objlist_push_head(&list_fini, obj);
1895 obj->on_fini_list = true;
1900 #define FPTR_TARGET(f) ((Elf_Addr) (f))
1904 is_exported(const Elf_Sym *def)
1907 const func_ptr_type *p;
1909 value = (Elf_Addr)(obj_rtld.relocbase + def->st_value);
1910 for (p = exports; *p != NULL; p++)
1911 if (FPTR_TARGET(*p) == value)
1917 free_needed_filtees(Needed_Entry *n)
1919 Needed_Entry *needed, *needed1;
1921 for (needed = n; needed != NULL; needed = needed->next) {
1922 if (needed->obj != NULL) {
1923 dlclose(needed->obj);
1927 for (needed = n; needed != NULL; needed = needed1) {
1928 needed1 = needed->next;
1934 unload_filtees(Obj_Entry *obj)
1937 free_needed_filtees(obj->needed_filtees);
1938 obj->needed_filtees = NULL;
1939 free_needed_filtees(obj->needed_aux_filtees);
1940 obj->needed_aux_filtees = NULL;
1941 obj->filtees_loaded = false;
1945 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags)
1948 for (; needed != NULL; needed = needed->next) {
1949 needed->obj = dlopen_object(obj->strtab + needed->name, obj,
1950 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
1956 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
1959 lock_restart_for_upgrade(lockstate);
1960 if (!obj->filtees_loaded) {
1961 load_filtee1(obj, obj->needed_filtees, flags);
1962 load_filtee1(obj, obj->needed_aux_filtees, flags);
1963 obj->filtees_loaded = true;
1968 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
1972 for (; needed != NULL; needed = needed->next) {
1973 obj1 = needed->obj = load_object(obj->strtab + needed->name, obj,
1974 flags & ~RTLD_LO_NOLOAD);
1975 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
1977 if (obj1 != NULL && obj1->z_nodelete && !obj1->ref_nodel) {
1978 dbg("obj %s nodelete", obj1->path);
1981 obj1->ref_nodel = true;
1988 * Given a shared object, traverse its list of needed objects, and load
1989 * each of them. Returns 0 on success. Generates an error message and
1990 * returns -1 on failure.
1993 load_needed_objects(Obj_Entry *first, int flags)
1997 for (obj = first; obj != NULL; obj = obj->next) {
1998 if (process_needed(obj, obj->needed, flags) == -1)
2005 load_preload_objects(void)
2007 char *p = ld_preload;
2008 static const char delim[] = " \t:;";
2013 p += strspn(p, delim);
2014 while (*p != '\0') {
2015 size_t len = strcspn(p, delim);
2023 obj = load_object(p, NULL, 0);
2025 return -1; /* XXX - cleanup */
2028 p += strspn(p, delim);
2030 /* Check for the magic tracing function */
2031 symlook_init(&req, RTLD_FUNCTRACE);
2032 res = symlook_obj(&req, obj);
2034 rtld_functrace = (void *)(req.defobj_out->relocbase +
2035 req.sym_out->st_value);
2036 rtld_functrace_obj = req.defobj_out;
2039 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
2044 * Load a shared object into memory, if it is not already loaded.
2046 * Returns a pointer to the Obj_Entry for the object. Returns NULL
2050 load_object(const char *name, const Obj_Entry *refobj, int flags)
2057 for (obj = obj_list->next; obj != NULL; obj = obj->next)
2058 if (object_match_name(obj, name))
2061 path = find_library(name, refobj);
2066 * If we didn't find a match by pathname, open the file and check
2067 * again by device and inode. This avoids false mismatches caused
2068 * by multiple links or ".." in pathnames.
2070 * To avoid a race, we open the file and use fstat() rather than
2073 if ((fd = open(path, O_RDONLY)) == -1) {
2074 _rtld_error("Cannot open \"%s\"", path);
2078 if (fstat(fd, &sb) == -1) {
2079 _rtld_error("Cannot fstat \"%s\"", path);
2084 for (obj = obj_list->next; obj != NULL; obj = obj->next)
2085 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
2088 object_add_name(obj, name);
2093 if (flags & RTLD_LO_NOLOAD) {
2099 /* First use of this object, so we must map it in */
2100 obj = do_load_object(fd, name, path, &sb, flags);
2109 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
2116 * but first, make sure that environment variables haven't been
2117 * used to circumvent the noexec flag on a filesystem.
2119 if (dangerous_ld_env) {
2120 if (fstatfs(fd, &fs) != 0) {
2121 _rtld_error("Cannot fstatfs \"%s\"", path);
2124 if (fs.f_flags & MNT_NOEXEC) {
2125 _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
2129 dbg("loading \"%s\"", path);
2130 obj = map_object(fd, path, sbp);
2134 object_add_name(obj, name);
2136 digest_dynamic(obj, 0);
2137 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
2139 dbg("refusing to load non-loadable \"%s\"", obj->path);
2140 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
2141 munmap(obj->mapbase, obj->mapsize);
2147 obj_tail = &obj->next;
2150 linkmap_add(obj); /* for GDB & dlinfo() */
2151 max_stack_flags |= obj->stack_flags;
2153 dbg(" %p .. %p: %s", obj->mapbase,
2154 obj->mapbase + obj->mapsize - 1, obj->path);
2156 dbg(" WARNING: %s has impure text", obj->path);
2157 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
2164 obj_from_addr(const void *addr)
2168 for (obj = obj_list; obj != NULL; obj = obj->next) {
2169 if (addr < (void *) obj->mapbase)
2171 if (addr < (void *) (obj->mapbase + obj->mapsize))
2178 * Call the finalization functions for each of the objects in "list"
2179 * belonging to the DAG of "root" and referenced once. If NULL "root"
2180 * is specified, every finalization function will be called regardless
2181 * of the reference count and the list elements won't be freed. All of
2182 * the objects are expected to have non-NULL fini functions.
2185 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
2189 Elf_Addr *fini_addr;
2192 assert(root == NULL || root->refcount == 1);
2195 * Preserve the current error message since a fini function might
2196 * call into the dynamic linker and overwrite it.
2198 saved_msg = errmsg_save();
2200 STAILQ_FOREACH(elm, list, link) {
2201 if (root != NULL && (elm->obj->refcount != 1 ||
2202 objlist_find(&root->dagmembers, elm->obj) == NULL))
2205 /* Remove object from fini list to prevent recursive invocation. */
2206 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2208 * XXX: If a dlopen() call references an object while the
2209 * fini function is in progress, we might end up trying to
2210 * unload the referenced object in dlclose() or the object
2211 * won't be unloaded although its fini function has been
2214 lock_release(rtld_bind_lock, lockstate);
2217 * It is legal to have both DT_FINI and DT_FINI_ARRAY defined. When this
2218 * happens, DT_FINI_ARRAY is processed first, and it is also processed
2219 * backwards. It is possible to encounter DT_FINI_ARRAY elements with
2220 * values of 0 or 1, but they need to be ignored.
2222 fini_addr = (Elf_Addr *)elm->obj->fini_array;
2223 if (fini_addr != NULL && elm->obj->fini_array_num > 0) {
2224 for (index = elm->obj->fini_array_num - 1; index >= 0; index--) {
2225 if (fini_addr[index] != 0 && fini_addr[index] != 1) {
2226 dbg("calling fini array function for %s at %p",
2227 elm->obj->path, (void *)fini_addr[index]);
2228 LD_UTRACE(UTRACE_FINI_CALL, elm->obj,
2229 (void *)fini_addr[index], 0, 0, elm->obj->path);
2230 call_initfini_pointer(elm->obj, fini_addr[index]);
2234 if (elm->obj->fini != (Elf_Addr)NULL) {
2235 dbg("calling fini function for %s at %p", elm->obj->path,
2236 (void *)elm->obj->fini);
2237 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini,
2238 0, 0, elm->obj->path);
2239 call_initfini_pointer(elm->obj, elm->obj->fini);
2241 wlock_acquire(rtld_bind_lock, lockstate);
2242 /* No need to free anything if process is going down. */
2246 * We must restart the list traversal after every fini call
2247 * because a dlclose() call from the fini function or from
2248 * another thread might have modified the reference counts.
2252 } while (elm != NULL);
2253 errmsg_restore(saved_msg);
2257 * If the main program is defined with a .preinit_array section, call
2258 * each function in order. This must occur before the initialization
2259 * of any shared object or the main program.
2262 preinitialize_main_object (void)
2264 Elf_Addr *preinit_addr;
2267 preinit_addr = (Elf_Addr *)obj_main->preinit_array;
2268 if (preinit_addr == NULL)
2271 for (index = 0; index < obj_main->preinit_array_num; index++) {
2272 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) {
2273 dbg("calling preinit function for %s at %p", obj_main->path,
2274 (void *)preinit_addr[index]);
2275 LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index],
2276 0, 0, obj_main->path);
2277 call_init_pointer(obj_main, preinit_addr[index]);
2283 * Call the initialization functions for each of the objects in
2284 * "list". All of the objects are expected to have non-NULL init
2288 objlist_call_init(Objlist *list, RtldLockState *lockstate)
2293 Elf_Addr *init_addr;
2297 * Clean init_scanned flag so that objects can be rechecked and
2298 * possibly initialized earlier if any of vectors called below
2299 * cause the change by using dlopen.
2301 for (obj = obj_list; obj != NULL; obj = obj->next)
2302 obj->init_scanned = false;
2305 * Preserve the current error message since an init function might
2306 * call into the dynamic linker and overwrite it.
2308 saved_msg = errmsg_save();
2309 STAILQ_FOREACH(elm, list, link) {
2310 if (elm->obj->init_done) /* Initialized early. */
2314 * Race: other thread might try to use this object before current
2315 * one completes the initilization. Not much can be done here
2316 * without better locking.
2318 elm->obj->init_done = true;
2319 lock_release(rtld_bind_lock, lockstate);
2322 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined. When
2323 * this happens, DT_INIT is processed first. It is possible to
2324 * encounter DT_INIT_ARRAY elements with values of 0 or 1, but they
2325 * need to be ignored.
2327 if (elm->obj->init != (Elf_Addr)NULL) {
2328 dbg("calling init function for %s at %p", elm->obj->path,
2329 (void *)elm->obj->init);
2330 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init,
2331 0, 0, elm->obj->path);
2332 call_initfini_pointer(elm->obj, elm->obj->init);
2334 init_addr = (Elf_Addr *)elm->obj->init_array;
2335 if (init_addr != NULL) {
2336 for (index = 0; index < elm->obj->init_array_num; index++) {
2337 if (init_addr[index] != 0 && init_addr[index] != 1) {
2338 dbg("calling init array function for %s at %p", elm->obj->path,
2339 (void *)init_addr[index]);
2340 LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
2341 (void *)init_addr[index], 0, 0, elm->obj->path);
2342 call_init_pointer(elm->obj, init_addr[index]);
2346 wlock_acquire(rtld_bind_lock, lockstate);
2348 errmsg_restore(saved_msg);
2352 objlist_clear(Objlist *list)
2356 while (!STAILQ_EMPTY(list)) {
2357 elm = STAILQ_FIRST(list);
2358 STAILQ_REMOVE_HEAD(list, link);
2363 static Objlist_Entry *
2364 objlist_find(Objlist *list, const Obj_Entry *obj)
2368 STAILQ_FOREACH(elm, list, link)
2369 if (elm->obj == obj)
2375 objlist_init(Objlist *list)
2381 objlist_push_head(Objlist *list, Obj_Entry *obj)
2385 elm = NEW(Objlist_Entry);
2387 STAILQ_INSERT_HEAD(list, elm, link);
2391 objlist_push_tail(Objlist *list, Obj_Entry *obj)
2395 elm = NEW(Objlist_Entry);
2397 STAILQ_INSERT_TAIL(list, elm, link);
2401 objlist_remove(Objlist *list, Obj_Entry *obj)
2405 if ((elm = objlist_find(list, obj)) != NULL) {
2406 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2412 * Relocate newly-loaded shared objects. The argument is a pointer to
2413 * the Obj_Entry for the first such object. All objects from the first
2414 * to the end of the list of objects are relocated. Returns 0 on success,
2418 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
2419 int flags, RtldLockState *lockstate)
2423 for (obj = first; obj != NULL; obj = obj->next) {
2426 obj->relocated = true;
2428 dbg("relocating \"%s\"", obj->path);
2430 if (obj->symtab == NULL || obj->strtab == NULL ||
2431 !(obj->valid_hash_sysv || obj->valid_hash_gnu)) {
2432 _rtld_error("%s: Shared object has no run-time symbol table",
2438 /* There are relocations to the write-protected text segment. */
2439 if (mprotect(obj->mapbase, obj->textsize,
2440 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
2441 _rtld_error("%s: Cannot write-enable text segment: %s",
2442 obj->path, rtld_strerror(errno));
2447 /* Process the non-PLT relocations. */
2448 if (reloc_non_plt(obj, rtldobj, flags, lockstate))
2452 * Reprotect the text segment. Make sure it is included in the
2453 * core dump since we modified it. This unfortunately causes the
2454 * entire text segment to core-out but we don't have much of a
2455 * choice. We could try to only reenable core dumps on pages
2456 * in which relocations occured but that is likely most of the text
2457 * pages anyway, and even that would not work because the rest of
2458 * the text pages would wind up as a read-only OBJT_DEFAULT object
2459 * (created due to our modifications) backed by the original OBJT_VNODE
2460 * object, and the ELF coredump code is currently only able to dump
2461 * vnode records for pure vnode-backed mappings, not vnode backings
2462 * to memory objects.
2465 madvise(obj->mapbase, obj->textsize, MADV_CORE);
2466 if (mprotect(obj->mapbase, obj->textsize,
2467 PROT_READ|PROT_EXEC) == -1) {
2468 _rtld_error("%s: Cannot write-protect text segment: %s",
2469 obj->path, rtld_strerror(errno));
2475 /* Set the special PLT or GOT entries. */
2478 /* Process the PLT relocations. */
2479 if (reloc_plt(obj) == -1)
2481 /* Relocate the jump slots if we are doing immediate binding. */
2482 if (obj->bind_now || bind_now)
2483 if (reloc_jmpslots(obj, flags, lockstate) == -1)
2487 * Set up the magic number and version in the Obj_Entry. These
2488 * were checked in the crt1.o from the original ElfKit, so we
2489 * set them for backward compatibility.
2491 obj->magic = RTLD_MAGIC;
2492 obj->version = RTLD_VERSION;
2495 * Set relocated data to read-only status if protection specified
2498 if (obj->relro_size) {
2499 if (mprotect(obj->relro_page, obj->relro_size, PROT_READ) == -1) {
2500 _rtld_error("%s: Cannot enforce relro relocation: %s",
2501 obj->path, rtld_strerror(errno));
2511 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
2512 * referencing STT_GNU_IFUNC symbols is postponed till the other
2513 * relocations are done. The indirect functions specified as
2514 * ifunc are allowed to call other symbols, so we need to have
2515 * objects relocated before asking for resolution from indirects.
2517 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
2518 * instead of the usual lazy handling of PLT slots. It is
2519 * consistent with how GNU does it.
2522 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags,
2523 RtldLockState *lockstate)
2525 if (obj->irelative && reloc_iresolve(obj, lockstate) == -1)
2527 if ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
2528 reloc_gnu_ifunc(obj, flags, lockstate) == -1)
2534 resolve_objects_ifunc(Obj_Entry *first, bool bind_now, int flags,
2535 RtldLockState *lockstate)
2539 for (obj = first; obj != NULL; obj = obj->next) {
2540 if (resolve_object_ifunc(obj, bind_now, flags, lockstate) == -1)
2547 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags,
2548 RtldLockState *lockstate)
2552 STAILQ_FOREACH(elm, list, link) {
2553 if (resolve_object_ifunc(elm->obj, bind_now, flags,
2561 * Cleanup procedure. It will be called (by the atexit mechanism) just
2562 * before the process exits.
2567 RtldLockState lockstate;
2569 wlock_acquire(rtld_bind_lock, &lockstate);
2571 objlist_call_fini(&list_fini, NULL, &lockstate);
2572 /* No need to remove the items from the list, since we are exiting. */
2573 if (!libmap_disable)
2575 lock_release(rtld_bind_lock, &lockstate);
2579 path_enumerate(const char *path, path_enum_proc callback, void *arg)
2584 path += strspn(path, ":;");
2585 while (*path != '\0') {
2589 len = strcspn(path, ":;");
2590 res = callback(path, len, arg);
2596 path += strspn(path, ":;");
2602 struct try_library_args {
2610 try_library_path(const char *dir, size_t dirlen, void *param)
2612 struct try_library_args *arg;
2615 if (*dir == '/' || trust) {
2618 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
2621 pathname = arg->buffer;
2622 strncpy(pathname, dir, dirlen);
2623 pathname[dirlen] = '/';
2624 strcpy(pathname + dirlen + 1, arg->name);
2626 dbg(" Trying \"%s\"", pathname);
2627 if (access(pathname, F_OK) == 0) { /* We found it */
2628 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
2629 strcpy(pathname, arg->buffer);
2637 search_library_path(const char *name, const char *path)
2640 struct try_library_args arg;
2646 arg.namelen = strlen(name);
2647 arg.buffer = xmalloc(PATH_MAX);
2648 arg.buflen = PATH_MAX;
2650 p = path_enumerate(path, try_library_path, &arg);
2658 dlclose(void *handle)
2661 RtldLockState lockstate;
2663 wlock_acquire(rtld_bind_lock, &lockstate);
2664 root = dlcheck(handle);
2666 lock_release(rtld_bind_lock, &lockstate);
2669 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
2672 /* Unreference the object and its dependencies. */
2673 root->dl_refcount--;
2675 if (root->refcount == 1) {
2677 * The object will be no longer referenced, so we must unload it.
2678 * First, call the fini functions.
2680 objlist_call_fini(&list_fini, root, &lockstate);
2684 /* Finish cleaning up the newly-unreferenced objects. */
2685 GDB_STATE(RT_DELETE,&root->linkmap);
2686 unload_object(root);
2687 GDB_STATE(RT_CONSISTENT,NULL);
2691 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
2692 lock_release(rtld_bind_lock, &lockstate);
2699 char *msg = error_message;
2700 error_message = NULL;
2705 dlopen(const char *name, int mode)
2707 RtldLockState lockstate;
2710 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
2711 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
2712 if (ld_tracing != NULL) {
2713 rlock_acquire(rtld_bind_lock, &lockstate);
2714 if (sigsetjmp(lockstate.env, 0) != 0)
2715 lock_upgrade(rtld_bind_lock, &lockstate);
2716 environ = (char **)*get_program_var_addr("environ", &lockstate);
2717 lock_release(rtld_bind_lock, &lockstate);
2719 lo_flags = RTLD_LO_DLOPEN;
2720 if (mode & RTLD_NODELETE)
2721 lo_flags |= RTLD_LO_NODELETE;
2722 if (mode & RTLD_NOLOAD)
2723 lo_flags |= RTLD_LO_NOLOAD;
2724 if (ld_tracing != NULL)
2725 lo_flags |= RTLD_LO_TRACE;
2727 return (dlopen_object(name, obj_main, lo_flags,
2728 mode & (RTLD_MODEMASK | RTLD_GLOBAL)));
2732 dlopen_cleanup(Obj_Entry *obj)
2737 if (obj->refcount == 0)
2742 dlopen_object(const char *name, Obj_Entry *refobj, int lo_flags, int mode)
2744 Obj_Entry **old_obj_tail;
2747 RtldLockState lockstate;
2750 objlist_init(&initlist);
2752 wlock_acquire(rtld_bind_lock, &lockstate);
2753 GDB_STATE(RT_ADD,NULL);
2755 old_obj_tail = obj_tail;
2761 obj = load_object(name, refobj, lo_flags);
2766 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
2767 objlist_push_tail(&list_global, obj);
2768 if (*old_obj_tail != NULL) { /* We loaded something new. */
2769 assert(*old_obj_tail == obj);
2770 result = load_needed_objects(obj,
2771 lo_flags & (RTLD_LO_DLOPEN | RTLD_LO_EARLY));
2775 result = rtld_verify_versions(&obj->dagmembers);
2776 if (result != -1 && ld_tracing)
2778 if (result == -1 || (relocate_objects(obj,
2779 (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld,
2780 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
2781 &lockstate)) == -1) {
2782 dlopen_cleanup(obj);
2784 } else if (lo_flags & RTLD_LO_EARLY) {
2786 * Do not call the init functions for early loaded
2787 * filtees. The image is still not initialized enough
2790 * Our object is found by the global object list and
2791 * will be ordered among all init calls done right
2792 * before transferring control to main.
2795 /* Make list of init functions to call. */
2796 initlist_add_objects(obj, &obj->next, &initlist);
2801 * Bump the reference counts for objects on this DAG. If
2802 * this is the first dlopen() call for the object that was
2803 * already loaded as a dependency, initialize the dag
2809 if ((lo_flags & RTLD_LO_TRACE) != 0)
2812 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
2813 obj->z_nodelete) && !obj->ref_nodel) {
2814 dbg("obj %s nodelete", obj->path);
2816 obj->z_nodelete = obj->ref_nodel = true;
2820 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
2822 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
2824 map_stacks_exec(&lockstate);
2826 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
2827 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
2828 &lockstate) == -1) {
2829 objlist_clear(&initlist);
2830 dlopen_cleanup(obj);
2831 lock_release(rtld_bind_lock, &lockstate);
2835 if (!(lo_flags & RTLD_LO_EARLY)) {
2836 /* Call the init functions. */
2837 objlist_call_init(&initlist, &lockstate);
2839 objlist_clear(&initlist);
2840 lock_release(rtld_bind_lock, &lockstate);
2843 trace_loaded_objects(obj);
2844 lock_release(rtld_bind_lock, &lockstate);
2849 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
2853 const Obj_Entry *obj, *defobj;
2856 RtldLockState lockstate;
2861 symlook_init(&req, name);
2863 req.flags = flags | SYMLOOK_IN_PLT;
2864 req.lockstate = &lockstate;
2866 rlock_acquire(rtld_bind_lock, &lockstate);
2867 if (sigsetjmp(lockstate.env, 0) != 0)
2868 lock_upgrade(rtld_bind_lock, &lockstate);
2869 if (handle == NULL || handle == RTLD_NEXT ||
2870 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
2872 if ((obj = obj_from_addr(retaddr)) == NULL) {
2873 _rtld_error("Cannot determine caller's shared object");
2874 lock_release(rtld_bind_lock, &lockstate);
2877 if (handle == NULL) { /* Just the caller's shared object. */
2878 res = symlook_obj(&req, obj);
2881 defobj = req.defobj_out;
2883 } else if (handle == RTLD_NEXT || /* Objects after caller's */
2884 handle == RTLD_SELF) { /* ... caller included */
2885 if (handle == RTLD_NEXT)
2887 for (; obj != NULL; obj = obj->next) {
2888 res = symlook_obj(&req, obj);
2891 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) {
2893 defobj = req.defobj_out;
2894 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2900 * Search the dynamic linker itself, and possibly resolve the
2901 * symbol from there. This is how the application links to
2902 * dynamic linker services such as dlopen.
2904 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2905 res = symlook_obj(&req, &obj_rtld);
2906 if (res == 0 && is_exported(req.sym_out)) {
2908 defobj = req.defobj_out;
2912 assert(handle == RTLD_DEFAULT);
2913 res = symlook_default(&req, obj);
2915 defobj = req.defobj_out;
2920 if ((obj = dlcheck(handle)) == NULL) {
2921 lock_release(rtld_bind_lock, &lockstate);
2925 donelist_init(&donelist);
2926 if (obj->mainprog) {
2927 /* Handle obtained by dlopen(NULL, ...) implies global scope. */
2928 res = symlook_global(&req, &donelist);
2931 defobj = req.defobj_out;
2934 * Search the dynamic linker itself, and possibly resolve the
2935 * symbol from there. This is how the application links to
2936 * dynamic linker services such as dlopen.
2938 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2939 res = symlook_obj(&req, &obj_rtld);
2942 defobj = req.defobj_out;
2947 /* Search the whole DAG rooted at the given object. */
2948 res = symlook_list(&req, &obj->dagmembers, &donelist);
2951 defobj = req.defobj_out;
2957 lock_release(rtld_bind_lock, &lockstate);
2960 * The value required by the caller is derived from the value
2961 * of the symbol. For the ia64 architecture, we need to
2962 * construct a function descriptor which the caller can use to
2963 * call the function with the right 'gp' value. For other
2964 * architectures and for non-functions, the value is simply
2965 * the relocated value of the symbol.
2967 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
2968 return (make_function_pointer(def, defobj));
2969 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
2970 return (rtld_resolve_ifunc(defobj, def));
2971 else if (ELF_ST_TYPE(def->st_info) == STT_TLS) {
2973 ti.ti_module = defobj->tlsindex;
2974 ti.ti_offset = def->st_value;
2975 return (__tls_get_addr(&ti));
2977 return (defobj->relocbase + def->st_value);
2980 _rtld_error("Undefined symbol \"%s\"", name);
2981 lock_release(rtld_bind_lock, &lockstate);
2986 dlsym(void *handle, const char *name)
2988 return do_dlsym(handle, name, __builtin_return_address(0), NULL,
2993 dlfunc(void *handle, const char *name)
3000 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
3006 dlvsym(void *handle, const char *name, const char *version)
3010 ventry.name = version;
3012 ventry.hash = elf_hash(version);
3014 return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
3019 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
3021 const Obj_Entry *obj;
3022 RtldLockState lockstate;
3024 rlock_acquire(rtld_bind_lock, &lockstate);
3025 obj = obj_from_addr(addr);
3027 _rtld_error("No shared object contains address");
3028 lock_release(rtld_bind_lock, &lockstate);
3031 rtld_fill_dl_phdr_info(obj, phdr_info);
3032 lock_release(rtld_bind_lock, &lockstate);
3037 dladdr(const void *addr, Dl_info *info)
3039 const Obj_Entry *obj;
3042 unsigned long symoffset;
3043 RtldLockState lockstate;
3045 rlock_acquire(rtld_bind_lock, &lockstate);
3046 obj = obj_from_addr(addr);
3048 _rtld_error("No shared object contains address");
3049 lock_release(rtld_bind_lock, &lockstate);
3052 info->dli_fname = obj->path;
3053 info->dli_fbase = obj->mapbase;
3054 info->dli_saddr = NULL;
3055 info->dli_sname = NULL;
3058 * Walk the symbol list looking for the symbol whose address is
3059 * closest to the address sent in.
3061 for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) {
3062 def = obj->symtab + symoffset;
3065 * For skip the symbol if st_shndx is either SHN_UNDEF or
3068 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
3072 * If the symbol is greater than the specified address, or if it
3073 * is further away from addr than the current nearest symbol,
3076 symbol_addr = obj->relocbase + def->st_value;
3077 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
3080 /* Update our idea of the nearest symbol. */
3081 info->dli_sname = obj->strtab + def->st_name;
3082 info->dli_saddr = symbol_addr;
3085 if (info->dli_saddr == addr)
3088 lock_release(rtld_bind_lock, &lockstate);
3093 dlinfo(void *handle, int request, void *p)
3095 const Obj_Entry *obj;
3096 RtldLockState lockstate;
3099 rlock_acquire(rtld_bind_lock, &lockstate);
3101 if (handle == NULL || handle == RTLD_SELF) {
3104 retaddr = __builtin_return_address(0); /* __GNUC__ only */
3105 if ((obj = obj_from_addr(retaddr)) == NULL)
3106 _rtld_error("Cannot determine caller's shared object");
3108 obj = dlcheck(handle);
3111 lock_release(rtld_bind_lock, &lockstate);
3117 case RTLD_DI_LINKMAP:
3118 *((struct link_map const **)p) = &obj->linkmap;
3120 case RTLD_DI_ORIGIN:
3121 error = rtld_dirname(obj->path, p);
3124 case RTLD_DI_SERINFOSIZE:
3125 case RTLD_DI_SERINFO:
3126 error = do_search_info(obj, request, (struct dl_serinfo *)p);
3130 _rtld_error("Invalid request %d passed to dlinfo()", request);
3134 lock_release(rtld_bind_lock, &lockstate);
3140 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
3143 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
3144 phdr_info->dlpi_name = STAILQ_FIRST(&obj->names) ?
3145 STAILQ_FIRST(&obj->names)->name : obj->path;
3146 phdr_info->dlpi_phdr = obj->phdr;
3147 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
3148 phdr_info->dlpi_tls_modid = obj->tlsindex;
3149 phdr_info->dlpi_tls_data = obj->tlsinit;
3150 phdr_info->dlpi_adds = obj_loads;
3151 phdr_info->dlpi_subs = obj_loads - obj_count;
3155 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
3157 struct dl_phdr_info phdr_info;
3158 const Obj_Entry *obj;
3159 RtldLockState bind_lockstate, phdr_lockstate;
3162 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
3163 rlock_acquire(rtld_bind_lock, &bind_lockstate);
3167 for (obj = obj_list; obj != NULL; obj = obj->next) {
3168 rtld_fill_dl_phdr_info(obj, &phdr_info);
3169 if ((error = callback(&phdr_info, sizeof phdr_info, param)) != 0)
3173 lock_release(rtld_bind_lock, &bind_lockstate);
3174 lock_release(rtld_phdr_lock, &phdr_lockstate);
3180 fill_search_info(const char *dir, size_t dirlen, void *param)
3182 struct fill_search_info_args *arg;
3186 if (arg->request == RTLD_DI_SERINFOSIZE) {
3187 arg->serinfo->dls_cnt ++;
3188 arg->serinfo->dls_size += sizeof(struct dl_serpath) + dirlen + 1;
3190 struct dl_serpath *s_entry;
3192 s_entry = arg->serpath;
3193 s_entry->dls_name = arg->strspace;
3194 s_entry->dls_flags = arg->flags;
3196 strncpy(arg->strspace, dir, dirlen);
3197 arg->strspace[dirlen] = '\0';
3199 arg->strspace += dirlen + 1;
3207 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
3209 struct dl_serinfo _info;
3210 struct fill_search_info_args args;
3212 args.request = RTLD_DI_SERINFOSIZE;
3213 args.serinfo = &_info;
3215 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
3218 path_enumerate(obj->rpath, fill_search_info, &args);
3219 path_enumerate(ld_library_path, fill_search_info, &args);
3220 path_enumerate(obj->runpath, fill_search_info, &args);
3221 path_enumerate(gethints(obj), fill_search_info, &args);
3222 if (!obj->z_nodeflib)
3223 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
3226 if (request == RTLD_DI_SERINFOSIZE) {
3227 info->dls_size = _info.dls_size;
3228 info->dls_cnt = _info.dls_cnt;
3232 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
3233 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
3237 args.request = RTLD_DI_SERINFO;
3238 args.serinfo = info;
3239 args.serpath = &info->dls_serpath[0];
3240 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
3242 args.flags = LA_SER_RUNPATH;
3243 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
3246 args.flags = LA_SER_LIBPATH;
3247 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
3250 args.flags = LA_SER_RUNPATH;
3251 if (path_enumerate(obj->runpath, fill_search_info, &args) != NULL)
3254 args.flags = LA_SER_CONFIG;
3255 if (path_enumerate(gethints(obj), fill_search_info, &args) != NULL)
3258 args.flags = LA_SER_DEFAULT;
3259 if (!obj->z_nodeflib &&
3260 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
3266 rtld_dirname(const char *path, char *bname)
3270 /* Empty or NULL string gets treated as "." */
3271 if (path == NULL || *path == '\0') {
3277 /* Strip trailing slashes */
3278 endp = path + strlen(path) - 1;
3279 while (endp > path && *endp == '/')
3282 /* Find the start of the dir */
3283 while (endp > path && *endp != '/')
3286 /* Either the dir is "/" or there are no slashes */
3288 bname[0] = *endp == '/' ? '/' : '.';
3294 } while (endp > path && *endp == '/');
3297 if (endp - path + 2 > PATH_MAX)
3299 _rtld_error("Filename is too long: %s", path);
3303 strncpy(bname, path, endp - path + 1);
3304 bname[endp - path + 1] = '\0';
3309 rtld_dirname_abs(const char *path, char *base)
3311 char base_rel[PATH_MAX];
3313 if (rtld_dirname(path, base) == -1)
3317 if (getcwd(base_rel, sizeof(base_rel)) == NULL ||
3318 strlcat(base_rel, "/", sizeof(base_rel)) >= sizeof(base_rel) ||
3319 strlcat(base_rel, base, sizeof(base_rel)) >= sizeof(base_rel))
3321 strcpy(base, base_rel);
3326 linkmap_add(Obj_Entry *obj)
3328 struct link_map *l = &obj->linkmap;
3329 struct link_map *prev;
3331 obj->linkmap.l_name = obj->path;
3332 obj->linkmap.l_addr = obj->mapbase;
3333 obj->linkmap.l_ld = obj->dynamic;
3335 /* GDB needs load offset on MIPS to use the symbols */
3336 obj->linkmap.l_offs = obj->relocbase;
3339 if (r_debug.r_map == NULL) {
3345 * Scan to the end of the list, but not past the entry for the
3346 * dynamic linker, which we want to keep at the very end.
3348 for (prev = r_debug.r_map;
3349 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
3350 prev = prev->l_next)
3353 /* Link in the new entry. */
3355 l->l_next = prev->l_next;
3356 if (l->l_next != NULL)
3357 l->l_next->l_prev = l;
3362 linkmap_delete(Obj_Entry *obj)
3364 struct link_map *l = &obj->linkmap;
3366 if (l->l_prev == NULL) {
3367 if ((r_debug.r_map = l->l_next) != NULL)
3368 l->l_next->l_prev = NULL;
3372 if ((l->l_prev->l_next = l->l_next) != NULL)
3373 l->l_next->l_prev = l->l_prev;
3377 * Function for the debugger to set a breakpoint on to gain control.
3379 * The two parameters allow the debugger to easily find and determine
3380 * what the runtime loader is doing and to whom it is doing it.
3382 * When the loadhook trap is hit (r_debug_state, set at program
3383 * initialization), the arguments can be found on the stack:
3385 * +8 struct link_map *m
3386 * +4 struct r_debug *rd
3390 r_debug_state(struct r_debug* rd, struct link_map *m)
3393 * The following is a hack to force the compiler to emit calls to
3394 * this function, even when optimizing. If the function is empty,
3395 * the compiler is not obliged to emit any code for calls to it,
3396 * even when marked __noinline. However, gdb depends on those
3399 __asm __volatile("" : : : "memory");
3403 * Get address of the pointer variable in the main program.
3404 * Prefer non-weak symbol over the weak one.
3406 static const void **
3407 get_program_var_addr(const char *name, RtldLockState *lockstate)
3412 symlook_init(&req, name);
3413 req.lockstate = lockstate;
3414 donelist_init(&donelist);
3415 if (symlook_global(&req, &donelist) != 0)
3417 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
3418 return ((const void **)make_function_pointer(req.sym_out,
3420 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
3421 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
3423 return ((const void **)(req.defobj_out->relocbase + req.sym_out->st_value));
3427 * Set a pointer variable in the main program to the given value. This
3428 * is used to set key variables such as "environ" before any of the
3429 * init functions are called.
3432 set_program_var(const char *name, const void *value)
3436 if ((addr = get_program_var_addr(name, NULL)) != NULL) {
3437 dbg("\"%s\": *%p <-- %p", name, addr, value);
3443 * Search the global objects, including dependencies and main object,
3444 * for the given symbol.
3447 symlook_global(SymLook *req, DoneList *donelist)
3450 const Objlist_Entry *elm;
3453 symlook_init_from_req(&req1, req);
3455 /* Search all objects loaded at program start up. */
3456 if (req->defobj_out == NULL ||
3457 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3458 res = symlook_list(&req1, &list_main, donelist);
3459 if (res == 0 && (req->defobj_out == NULL ||
3460 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3461 req->sym_out = req1.sym_out;
3462 req->defobj_out = req1.defobj_out;
3463 assert(req->defobj_out != NULL);
3467 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
3468 STAILQ_FOREACH(elm, &list_global, link) {
3469 if (req->defobj_out != NULL &&
3470 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3472 res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
3473 if (res == 0 && (req->defobj_out == NULL ||
3474 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3475 req->sym_out = req1.sym_out;
3476 req->defobj_out = req1.defobj_out;
3477 assert(req->defobj_out != NULL);
3481 return (req->sym_out != NULL ? 0 : ESRCH);
3485 * This is a special version of getenv which is far more efficient
3486 * at finding LD_ environment vars.
3490 _getenv_ld(const char *id)
3494 int idlen = strlen(id);
3496 if (ld_index == LD_ARY_CACHE)
3498 if (ld_index == 0) {
3499 for (i = j = 0; (envp = environ[i]) != NULL && j < LD_ARY_CACHE; ++i) {
3500 if (envp[0] == 'L' && envp[1] == 'D' && envp[2] == '_')
3507 for (i = ld_index - 1; i >= 0; --i) {
3508 if (strncmp(ld_ary[i], id, idlen) == 0 && ld_ary[i][idlen] == '=')
3509 return(ld_ary[i] + idlen + 1);
3515 * Given a symbol name in a referencing object, find the corresponding
3516 * definition of the symbol. Returns a pointer to the symbol, or NULL if
3517 * no definition was found. Returns a pointer to the Obj_Entry of the
3518 * defining object via the reference parameter DEFOBJ_OUT.
3521 symlook_default(SymLook *req, const Obj_Entry *refobj)
3524 const Objlist_Entry *elm;
3528 donelist_init(&donelist);
3529 symlook_init_from_req(&req1, req);
3531 /* Look first in the referencing object if linked symbolically. */
3532 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
3533 res = symlook_obj(&req1, refobj);
3535 req->sym_out = req1.sym_out;
3536 req->defobj_out = req1.defobj_out;
3537 assert(req->defobj_out != NULL);
3541 symlook_global(req, &donelist);
3543 /* Search all dlopened DAGs containing the referencing object. */
3544 STAILQ_FOREACH(elm, &refobj->dldags, link) {
3545 if (req->sym_out != NULL &&
3546 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3548 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
3549 if (res == 0 && (req->sym_out == NULL ||
3550 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3551 req->sym_out = req1.sym_out;
3552 req->defobj_out = req1.defobj_out;
3553 assert(req->defobj_out != NULL);
3558 * Search the dynamic linker itself, and possibly resolve the
3559 * symbol from there. This is how the application links to
3560 * dynamic linker services such as dlopen. Only the values listed
3561 * in the "exports" array can be resolved from the dynamic linker.
3563 if (req->sym_out == NULL ||
3564 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3565 res = symlook_obj(&req1, &obj_rtld);
3566 if (res == 0 && is_exported(req1.sym_out)) {
3567 req->sym_out = req1.sym_out;
3568 req->defobj_out = req1.defobj_out;
3569 assert(req->defobj_out != NULL);
3573 return (req->sym_out != NULL ? 0 : ESRCH);
3577 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
3580 const Obj_Entry *defobj;
3581 const Objlist_Entry *elm;
3587 STAILQ_FOREACH(elm, objlist, link) {
3588 if (donelist_check(dlp, elm->obj))
3590 symlook_init_from_req(&req1, req);
3591 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
3592 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3594 defobj = req1.defobj_out;
3595 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3602 req->defobj_out = defobj;
3609 * Search the chain of DAGS cointed to by the given Needed_Entry
3610 * for a symbol of the given name. Each DAG is scanned completely
3611 * before advancing to the next one. Returns a pointer to the symbol,
3612 * or NULL if no definition was found.
3615 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
3618 const Needed_Entry *n;
3619 const Obj_Entry *defobj;
3625 symlook_init_from_req(&req1, req);
3626 for (n = needed; n != NULL; n = n->next) {
3627 if (n->obj == NULL ||
3628 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
3630 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3632 defobj = req1.defobj_out;
3633 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3639 req->defobj_out = defobj;
3646 * Search the symbol table of a single shared object for a symbol of
3647 * the given name and version, if requested. Returns a pointer to the
3648 * symbol, or NULL if no definition was found. If the object is
3649 * filter, return filtered symbol from filtee.
3651 * The symbol's hash value is passed in for efficiency reasons; that
3652 * eliminates many recomputations of the hash value.
3655 symlook_obj(SymLook *req, const Obj_Entry *obj)
3659 int flags, res, mres;
3662 * There is at least one valid hash at this point, and we prefer to use
3663 * the faster GNU version if available.
3665 if (obj->valid_hash_gnu)
3666 mres = symlook_obj2(req, obj);
3668 mres = symlook_obj1(req, obj);
3671 if (obj->needed_filtees != NULL) {
3672 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
3673 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
3674 donelist_init(&donelist);
3675 symlook_init_from_req(&req1, req);
3676 res = symlook_needed(&req1, obj->needed_filtees, &donelist);
3678 req->sym_out = req1.sym_out;
3679 req->defobj_out = req1.defobj_out;
3683 if (obj->needed_aux_filtees != NULL) {
3684 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
3685 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
3686 donelist_init(&donelist);
3687 symlook_init_from_req(&req1, req);
3688 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
3690 req->sym_out = req1.sym_out;
3691 req->defobj_out = req1.defobj_out;
3699 /* Symbol match routine common to both hash functions */
3701 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result,
3702 const unsigned long symnum)
3705 const Elf_Sym *symp = obj->symtab + symnum;
3706 const char *strp = obj->strtab + symp->st_name;
3708 switch (ELF_ST_TYPE(symp->st_info)) {
3714 if (symp->st_value == 0)
3718 if (symp->st_shndx != SHN_UNDEF)
3720 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
3721 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
3727 if (strcmp(req->name, strp) != 0)
3730 if (req->ventry == NULL) {
3731 if (obj->versyms != NULL) {
3732 verndx = VER_NDX(obj->versyms[symnum]);
3733 if (verndx > obj->vernum) {
3734 _rtld_error("%s: symbol %s references wrong version %d",
3735 obj->path, obj->strtab + symnum, verndx);
3739 * If we are not called from dlsym (i.e. this is a normal relocation
3740 * from unversioned binary), accept the symbol immediately if it happens
3741 * to have first version after this shared object became versioned.
3742 * Otherwise, if symbol is versioned and not hidden, remember it. If it
3743 * is the only symbol with this name exported by the shared object, it
3744 * will be returned as a match by the calling function. If symbol is
3745 * global (verndx < 2) accept it unconditionally.
3747 if ((req->flags & SYMLOOK_DLSYM) == 0 && verndx == VER_NDX_GIVEN) {
3748 result->sym_out = symp;
3751 else if (verndx >= VER_NDX_GIVEN) {
3752 if ((obj->versyms[symnum] & VER_NDX_HIDDEN) == 0) {
3753 if (result->vsymp == NULL)
3754 result->vsymp = symp;
3760 result->sym_out = symp;
3763 if (obj->versyms == NULL) {
3764 if (object_match_name(obj, req->ventry->name)) {
3765 _rtld_error("%s: object %s should provide version %s for "
3766 "symbol %s", obj_rtld.path, obj->path,
3767 req->ventry->name, obj->strtab + symnum);
3771 verndx = VER_NDX(obj->versyms[symnum]);
3772 if (verndx > obj->vernum) {
3773 _rtld_error("%s: symbol %s references wrong version %d",
3774 obj->path, obj->strtab + symnum, verndx);
3777 if (obj->vertab[verndx].hash != req->ventry->hash ||
3778 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
3780 * Version does not match. Look if this is a global symbol and if it is
3781 * not hidden. If global symbol (verndx < 2) is available, use it. Do not
3782 * return symbol if we are called by dlvsym, because dlvsym looks for a
3783 * specific version and default one is not what dlvsym wants.
3785 if ((req->flags & SYMLOOK_DLSYM) || (verndx >= VER_NDX_GIVEN) ||
3786 (obj->versyms[symnum] & VER_NDX_HIDDEN))
3790 result->sym_out = symp;
3795 * Search for symbol using SysV hash function.
3796 * obj->buckets is known not to be NULL at this point; the test for this was
3797 * performed with the obj->valid_hash_sysv assignment.
3800 symlook_obj1(SymLook *req, const Obj_Entry *obj)
3802 unsigned long symnum;
3803 Sym_Match_Result matchres;
3805 matchres.sym_out = NULL;
3806 matchres.vsymp = NULL;
3807 matchres.vcount = 0;
3809 for (symnum = obj->buckets[req->hash % obj->nbuckets];
3810 symnum != STN_UNDEF;
3811 symnum = obj->chains[symnum]) {
3813 if (symnum >= obj->nchains)
3814 return (ESRCH); /* Bad object */
3816 if (matched_symbol(req, obj, &matchres, symnum)) {
3817 req->sym_out = matchres.sym_out;
3818 req->defobj_out = obj;
3822 if (matchres.vcount == 1) {
3823 req->sym_out = matchres.vsymp;
3824 req->defobj_out = obj;
3830 /* Search for symbol using GNU hash function */
3832 symlook_obj2(SymLook *req, const Obj_Entry *obj)
3834 Elf_Addr bloom_word;
3836 unsigned int h1, h2;
3837 unsigned long symnum;
3838 const int c = __ELF_WORD_SIZE;
3839 Sym_Match_Result matchres;
3841 matchres.sym_out = NULL;
3842 matchres.vsymp = NULL;
3843 matchres.vcount = 0;
3845 /* pick right bitmask word from Bloom filter array*/
3846 bloom_word = obj->bloom_gnu[(req->hash_gnu / c) & obj->maskwords_bm_gnu];
3848 /* calculate modulus 32 (64 for x86_64) of gnu hash and its derivative */
3849 h1 = req->hash_gnu & (c - 1);
3850 h2 = ((req->hash_gnu >> obj->shift2_gnu) & (c - 1));
3852 /* Filter out the "definitely not in set" queries */
3853 if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0)
3856 /* Locate hash chain and corresponding value element*/
3857 bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu];
3860 const Elf32_Word *hashval = &obj->chain_zero_gnu[bucket];
3862 if (((*hashval ^ req->hash_gnu) >> 1) == 0)
3864 symnum = hashval - obj->chain_zero_gnu;
3865 if (matched_symbol(req, obj, &matchres, symnum)) {
3866 req->sym_out = matchres.sym_out;
3867 req->defobj_out = obj;
3871 while ((*hashval++ & 1u) == 0);
3872 if (matchres.vcount == 1) {
3873 req->sym_out = matchres.vsymp;
3874 req->defobj_out = obj;
3881 trace_loaded_objects(Obj_Entry *obj)
3883 const char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
3886 if ((main_local = _getenv_ld("LD_TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
3889 if ((fmt1 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT1")) == NULL)
3890 fmt1 = "\t%o => %p (%x)\n";
3892 if ((fmt2 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT2")) == NULL)
3893 fmt2 = "\t%o (%x)\n";
3895 list_containers = _getenv_ld("LD_TRACE_LOADED_OBJECTS_ALL");
3897 for (; obj; obj = obj->next) {
3898 Needed_Entry *needed;
3902 if (list_containers && obj->needed != NULL)
3903 rtld_printf("%s:\n", obj->path);
3904 for (needed = obj->needed; needed; needed = needed->next) {
3905 if (needed->obj != NULL) {
3906 if (needed->obj->traced && !list_containers)
3908 needed->obj->traced = true;
3909 path = needed->obj->path;
3913 name = (char *)obj->strtab + needed->name;
3914 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
3916 fmt = is_lib ? fmt1 : fmt2;
3917 while ((c = *fmt++) != '\0') {
3943 rtld_putstr(main_local);
3946 rtld_putstr(obj_main->path);
3955 rtld_printf("%p", needed->obj ? needed->obj->mapbase :
3968 * Unload a dlopened object and its dependencies from memory and from
3969 * our data structures. It is assumed that the DAG rooted in the
3970 * object has already been unreferenced, and that the object has a
3971 * reference count of 0.
3974 unload_object(Obj_Entry *root)
3979 assert(root->refcount == 0);
3982 * Pass over the DAG removing unreferenced objects from
3983 * appropriate lists.
3985 unlink_object(root);
3987 /* Unmap all objects that are no longer referenced. */
3988 linkp = &obj_list->next;
3989 while ((obj = *linkp) != NULL) {
3990 if (obj->refcount == 0) {
3991 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
3993 dbg("unloading \"%s\"", obj->path);
3994 unload_filtees(root);
3995 munmap(obj->mapbase, obj->mapsize);
3996 linkmap_delete(obj);
4007 unlink_object(Obj_Entry *root)
4011 if (root->refcount == 0) {
4012 /* Remove the object from the RTLD_GLOBAL list. */
4013 objlist_remove(&list_global, root);
4015 /* Remove the object from all objects' DAG lists. */
4016 STAILQ_FOREACH(elm, &root->dagmembers, link) {
4017 objlist_remove(&elm->obj->dldags, root);
4018 if (elm->obj != root)
4019 unlink_object(elm->obj);
4025 ref_dag(Obj_Entry *root)
4029 assert(root->dag_inited);
4030 STAILQ_FOREACH(elm, &root->dagmembers, link)
4031 elm->obj->refcount++;
4035 unref_dag(Obj_Entry *root)
4039 assert(root->dag_inited);
4040 STAILQ_FOREACH(elm, &root->dagmembers, link)
4041 elm->obj->refcount--;
4045 * Common code for MD __tls_get_addr().
4048 tls_get_addr_common(Elf_Addr** dtvp, int index, size_t offset)
4050 Elf_Addr* dtv = *dtvp;
4051 RtldLockState lockstate;
4053 /* Check dtv generation in case new modules have arrived */
4054 if (dtv[0] != tls_dtv_generation) {
4058 wlock_acquire(rtld_bind_lock, &lockstate);
4059 newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4061 if (to_copy > tls_max_index)
4062 to_copy = tls_max_index;
4063 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
4064 newdtv[0] = tls_dtv_generation;
4065 newdtv[1] = tls_max_index;
4067 lock_release(rtld_bind_lock, &lockstate);
4068 dtv = *dtvp = newdtv;
4071 /* Dynamically allocate module TLS if necessary */
4072 if (!dtv[index + 1]) {
4073 /* Signal safe, wlock will block out signals. */
4074 wlock_acquire(rtld_bind_lock, &lockstate);
4075 if (!dtv[index + 1])
4076 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
4077 lock_release(rtld_bind_lock, &lockstate);
4079 return (void*) (dtv[index + 1] + offset);
4082 #if defined(RTLD_STATIC_TLS_VARIANT_II)
4085 * Allocate the static TLS area. Return a pointer to the TCB. The
4086 * static area is based on negative offsets relative to the tcb.
4088 * The TCB contains an errno pointer for the system call layer, but because
4089 * we are the RTLD we really have no idea how the caller was compiled so
4090 * the information has to be passed in. errno can either be:
4092 * type 0 errno is a simple non-TLS global pointer.
4093 * (special case for e.g. libc_rtld)
4094 * type 1 errno accessed by GOT entry (dynamically linked programs)
4095 * type 2 errno accessed by %gs:OFFSET (statically linked programs)
4098 allocate_tls(Obj_Entry *objs)
4103 struct tls_tcb *tcb;
4108 * Allocate the new TCB. static TLS storage is placed just before the
4109 * TCB to support the %gs:OFFSET (negative offset) model.
4111 data_size = (tls_static_space + RTLD_STATIC_TLS_ALIGN_MASK) &
4112 ~RTLD_STATIC_TLS_ALIGN_MASK;
4113 tcb = malloc(data_size + sizeof(*tcb));
4114 tcb = (void *)((char *)tcb + data_size); /* actual tcb location */
4116 dtv_size = (tls_max_index + 2) * sizeof(Elf_Addr);
4117 dtv = malloc(dtv_size);
4118 bzero(dtv, dtv_size);
4120 #ifdef RTLD_TCB_HAS_SELF_POINTER
4121 tcb->tcb_self = tcb;
4124 tcb->tcb_pthread = NULL;
4126 dtv[0] = tls_dtv_generation;
4127 dtv[1] = tls_max_index;
4129 for (obj = objs; obj; obj = obj->next) {
4130 if (obj->tlsoffset) {
4131 addr = (Elf_Addr)tcb - obj->tlsoffset;
4132 memset((void *)(addr + obj->tlsinitsize),
4133 0, obj->tlssize - obj->tlsinitsize);
4135 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4136 dtv[obj->tlsindex + 1] = addr;
4143 free_tls(struct tls_tcb *tcb)
4147 Elf_Addr tls_start, tls_end;
4150 data_size = (tls_static_space + RTLD_STATIC_TLS_ALIGN_MASK) &
4151 ~RTLD_STATIC_TLS_ALIGN_MASK;
4155 tls_end = (Elf_Addr)tcb;
4156 tls_start = (Elf_Addr)tcb - data_size;
4157 for (i = 0; i < dtv_size; i++) {
4158 if (dtv[i+2] != 0 && (dtv[i+2] < tls_start || dtv[i+2] > tls_end)) {
4159 free((void *)dtv[i+2]);
4163 free((void*) tls_start);
4167 #error "Unsupported TLS layout"
4171 * Allocate TLS block for module with given index.
4174 allocate_module_tls(int index)
4179 for (obj = obj_list; obj; obj = obj->next) {
4180 if (obj->tlsindex == index)
4184 _rtld_error("Can't find module with TLS index %d", index);
4188 p = malloc(obj->tlssize);
4190 _rtld_error("Cannot allocate TLS block for index %d", index);
4193 memcpy(p, obj->tlsinit, obj->tlsinitsize);
4194 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
4200 allocate_tls_offset(Obj_Entry *obj)
4207 if (obj->tlssize == 0) {
4208 obj->tls_done = true;
4212 if (obj->tlsindex == 1)
4213 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
4215 off = calculate_tls_offset(tls_last_offset, tls_last_size,
4216 obj->tlssize, obj->tlsalign);
4219 * If we have already fixed the size of the static TLS block, we
4220 * must stay within that size. When allocating the static TLS, we
4221 * leave a small amount of space spare to be used for dynamically
4222 * loading modules which use static TLS.
4224 if (tls_static_space) {
4225 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
4229 tls_last_offset = obj->tlsoffset = off;
4230 tls_last_size = obj->tlssize;
4231 obj->tls_done = true;
4237 free_tls_offset(Obj_Entry *obj)
4239 #ifdef RTLD_STATIC_TLS_VARIANT_II
4241 * If we were the last thing to allocate out of the static TLS
4242 * block, we give our space back to the 'allocator'. This is a
4243 * simplistic workaround to allow libGL.so.1 to be loaded and
4244 * unloaded multiple times. We only handle the Variant II
4245 * mechanism for now - this really needs a proper allocator.
4247 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
4248 == calculate_tls_end(tls_last_offset, tls_last_size)) {
4249 tls_last_offset -= obj->tlssize;
4256 _rtld_allocate_tls(void)
4258 struct tls_tcb *new_tcb;
4259 RtldLockState lockstate;
4261 wlock_acquire(rtld_bind_lock, &lockstate);
4262 new_tcb = allocate_tls(obj_list);
4263 lock_release(rtld_bind_lock, &lockstate);
4268 _rtld_free_tls(struct tls_tcb *tcb)
4270 RtldLockState lockstate;
4272 wlock_acquire(rtld_bind_lock, &lockstate);
4274 lock_release(rtld_bind_lock, &lockstate);
4278 object_add_name(Obj_Entry *obj, const char *name)
4284 entry = malloc(sizeof(Name_Entry) + len);
4286 if (entry != NULL) {
4287 strcpy(entry->name, name);
4288 STAILQ_INSERT_TAIL(&obj->names, entry, link);
4293 object_match_name(const Obj_Entry *obj, const char *name)
4297 STAILQ_FOREACH(entry, &obj->names, link) {
4298 if (strcmp(name, entry->name) == 0)
4305 locate_dependency(const Obj_Entry *obj, const char *name)
4307 const Objlist_Entry *entry;
4308 const Needed_Entry *needed;
4310 STAILQ_FOREACH(entry, &list_main, link) {
4311 if (object_match_name(entry->obj, name))
4315 for (needed = obj->needed; needed != NULL; needed = needed->next) {
4316 if (strcmp(obj->strtab + needed->name, name) == 0 ||
4317 (needed->obj != NULL && object_match_name(needed->obj, name))) {
4319 * If there is DT_NEEDED for the name we are looking for,
4320 * we are all set. Note that object might not be found if
4321 * dependency was not loaded yet, so the function can
4322 * return NULL here. This is expected and handled
4323 * properly by the caller.
4325 return (needed->obj);
4328 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
4334 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
4335 const Elf_Vernaux *vna)
4337 const Elf_Verdef *vd;
4338 const char *vername;
4340 vername = refobj->strtab + vna->vna_name;
4341 vd = depobj->verdef;
4343 _rtld_error("%s: version %s required by %s not defined",
4344 depobj->path, vername, refobj->path);
4348 if (vd->vd_version != VER_DEF_CURRENT) {
4349 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
4350 depobj->path, vd->vd_version);
4353 if (vna->vna_hash == vd->vd_hash) {
4354 const Elf_Verdaux *aux = (const Elf_Verdaux *)
4355 ((char *)vd + vd->vd_aux);
4356 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
4359 if (vd->vd_next == 0)
4361 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4363 if (vna->vna_flags & VER_FLG_WEAK)
4365 _rtld_error("%s: version %s required by %s not found",
4366 depobj->path, vername, refobj->path);
4371 rtld_verify_object_versions(Obj_Entry *obj)
4373 const Elf_Verneed *vn;
4374 const Elf_Verdef *vd;
4375 const Elf_Verdaux *vda;
4376 const Elf_Vernaux *vna;
4377 const Obj_Entry *depobj;
4378 int maxvernum, vernum;
4382 * Walk over defined and required version records and figure out
4383 * max index used by any of them. Do very basic sanity checking
4387 while (vn != NULL) {
4388 if (vn->vn_version != VER_NEED_CURRENT) {
4389 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
4390 obj->path, vn->vn_version);
4393 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4395 vernum = VER_NEED_IDX(vna->vna_other);
4396 if (vernum > maxvernum)
4398 if (vna->vna_next == 0)
4400 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4402 if (vn->vn_next == 0)
4404 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4408 while (vd != NULL) {
4409 if (vd->vd_version != VER_DEF_CURRENT) {
4410 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
4411 obj->path, vd->vd_version);
4414 vernum = VER_DEF_IDX(vd->vd_ndx);
4415 if (vernum > maxvernum)
4417 if (vd->vd_next == 0)
4419 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4426 * Store version information in array indexable by version index.
4427 * Verify that object version requirements are satisfied along the
4430 obj->vernum = maxvernum + 1;
4431 obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry));
4434 while (vd != NULL) {
4435 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
4436 vernum = VER_DEF_IDX(vd->vd_ndx);
4437 assert(vernum <= maxvernum);
4438 vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
4439 obj->vertab[vernum].hash = vd->vd_hash;
4440 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
4441 obj->vertab[vernum].file = NULL;
4442 obj->vertab[vernum].flags = 0;
4444 if (vd->vd_next == 0)
4446 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4450 while (vn != NULL) {
4451 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
4454 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4456 if (check_object_provided_version(obj, depobj, vna))
4458 vernum = VER_NEED_IDX(vna->vna_other);
4459 assert(vernum <= maxvernum);
4460 obj->vertab[vernum].hash = vna->vna_hash;
4461 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
4462 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
4463 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
4464 VER_INFO_HIDDEN : 0;
4465 if (vna->vna_next == 0)
4467 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4469 if (vn->vn_next == 0)
4471 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4477 rtld_verify_versions(const Objlist *objlist)
4479 Objlist_Entry *entry;
4483 STAILQ_FOREACH(entry, objlist, link) {
4485 * Skip dummy objects or objects that have their version requirements
4488 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
4490 if (rtld_verify_object_versions(entry->obj) == -1) {
4492 if (ld_tracing == NULL)
4496 if (rc == 0 || ld_tracing != NULL)
4497 rc = rtld_verify_object_versions(&obj_rtld);
4502 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
4507 vernum = VER_NDX(obj->versyms[symnum]);
4508 if (vernum >= obj->vernum) {
4509 _rtld_error("%s: symbol %s has wrong verneed value %d",
4510 obj->path, obj->strtab + symnum, vernum);
4511 } else if (obj->vertab[vernum].hash != 0) {
4512 return &obj->vertab[vernum];
4519 _rtld_get_stack_prot(void)
4522 return (stack_prot);
4526 map_stacks_exec(RtldLockState *lockstate)
4530 * Stack protection must be implemented in the kernel before the dynamic
4531 * linker can handle PT_GNU_STACK sections.
4532 * The following is the FreeBSD implementation of map_stacks_exec()
4533 * void (*thr_map_stacks_exec)(void);
4535 * if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
4537 * thr_map_stacks_exec = (void (*)(void))(uintptr_t)
4538 * get_program_var_addr("__pthread_map_stacks_exec", lockstate);
4539 * if (thr_map_stacks_exec != NULL) {
4540 * stack_prot |= PROT_EXEC;
4541 * thr_map_stacks_exec();
4547 symlook_init(SymLook *dst, const char *name)
4550 bzero(dst, sizeof(*dst));
4552 dst->hash = elf_hash(name);
4553 dst->hash_gnu = gnu_hash(name);
4557 symlook_init_from_req(SymLook *dst, const SymLook *src)
4560 dst->name = src->name;
4561 dst->hash = src->hash;
4562 dst->hash_gnu = src->hash_gnu;
4563 dst->ventry = src->ventry;
4564 dst->flags = src->flags;
4565 dst->defobj_out = NULL;
4566 dst->sym_out = NULL;
4567 dst->lockstate = src->lockstate;
4570 #ifdef ENABLE_OSRELDATE
4572 * Overrides for libc_pic-provided functions.
4576 __getosreldate(void)
4586 oid[1] = KERN_OSRELDATE;
4588 len = sizeof(osrel);
4589 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
4590 if (error == 0 && osrel > 0 && len == sizeof(osrel))
4597 * No unresolved symbols for rtld.
4600 __pthread_cxa_finalize(struct dl_phdr_info *a)
4605 rtld_strerror(int errnum)
4608 if (errnum < 0 || errnum >= sys_nerr)
4609 return ("Unknown error");
4610 return (sys_errlist[errnum]);