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>.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 * Dynamic linker for ELF.
33 * John Polstra <jdp@polstra.com>.
37 #error "GCC is needed to compile this file"
40 #include <sys/param.h>
41 #include <sys/mount.h>
44 #include <sys/sysctl.h>
46 #include <sys/utsname.h>
47 #include <sys/ktrace.h>
48 #include <sys/resident.h>
51 #include <machine/tls.h>
66 #include "rtld_printf.h"
68 #define PATH_RTLD "/usr/libexec/ld-elf.so.2"
69 #define LD_ARY_CACHE 16
72 typedef void (*func_ptr_type)();
73 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg);
76 * Function declarations.
78 static const char *_getenv_ld(const char *id);
79 static void die(void) __dead2;
80 static void digest_dynamic1(Obj_Entry *, int, const Elf_Dyn **,
82 static void digest_dynamic2(Obj_Entry *, const Elf_Dyn *, const Elf_Dyn *);
83 static void digest_dynamic(Obj_Entry *, int);
84 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
85 static Obj_Entry *dlcheck(void *);
86 static Obj_Entry *dlopen_object(const char *name, Obj_Entry *refobj,
87 int lo_flags, int mode);
88 static Obj_Entry *do_load_object(int, const char *, char *, struct stat *, int);
89 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
90 static bool donelist_check(DoneList *, const Obj_Entry *);
91 static void errmsg_restore(char *);
92 static char *errmsg_save(void);
93 static void *fill_search_info(const char *, size_t, void *);
94 static char *find_library(const char *, const Obj_Entry *);
95 static const char *gethints(void);
96 static void init_dag(Obj_Entry *);
97 static void init_rtld(caddr_t, Elf_Auxinfo **);
98 static void initlist_add_neededs(Needed_Entry *, Objlist *);
99 static void initlist_add_objects(Obj_Entry *, Obj_Entry **, Objlist *);
100 static bool is_exported(const Elf_Sym *);
101 static void linkmap_add(Obj_Entry *);
102 static void linkmap_delete(Obj_Entry *);
103 static void load_filtees(Obj_Entry *, int flags, RtldLockState *);
104 static void unload_filtees(Obj_Entry *);
105 static int load_needed_objects(Obj_Entry *, int);
106 static int load_preload_objects(void);
107 static Obj_Entry *load_object(const char *, const Obj_Entry *, int);
108 static void map_stacks_exec(RtldLockState *);
109 static Obj_Entry *obj_from_addr(const void *);
110 static void objlist_call_fini(Objlist *, Obj_Entry *, RtldLockState *);
111 static void objlist_call_init(Objlist *, RtldLockState *);
112 static void objlist_clear(Objlist *);
113 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
114 static void objlist_init(Objlist *);
115 static void objlist_push_head(Objlist *, Obj_Entry *);
116 static void objlist_push_tail(Objlist *, Obj_Entry *);
117 static void objlist_remove(Objlist *, Obj_Entry *);
118 static void *path_enumerate(const char *, path_enum_proc, void *);
119 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, RtldLockState *);
120 static int resolve_objects_ifunc(Obj_Entry *first, bool bind_now,
121 RtldLockState *lockstate);
122 static int rtld_dirname(const char *, char *);
123 static int rtld_dirname_abs(const char *, char *);
124 static void rtld_exit(void);
125 static char *search_library_path(const char *, const char *);
126 static const void **get_program_var_addr(const char *, RtldLockState *);
127 static void set_program_var(const char *, const void *);
128 static int symlook_default(SymLook *, const Obj_Entry *refobj);
129 static int symlook_global(SymLook *, DoneList *);
130 static void symlook_init_from_req(SymLook *, const SymLook *);
131 static int symlook_list(SymLook *, const Objlist *, DoneList *);
132 static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *);
133 static int symlook_obj1(SymLook *, const Obj_Entry *);
134 static void trace_loaded_objects(Obj_Entry *);
135 static void unlink_object(Obj_Entry *);
136 static void unload_object(Obj_Entry *);
137 static void unref_dag(Obj_Entry *);
138 static void ref_dag(Obj_Entry *);
139 static int origin_subst_one(char **, const char *, const char *,
140 const char *, char *);
141 static char *origin_subst(const char *, const char *);
142 static int rtld_verify_versions(const Objlist *);
143 static int rtld_verify_object_versions(Obj_Entry *);
144 static void object_add_name(Obj_Entry *, const char *);
145 static int object_match_name(const Obj_Entry *, const char *);
146 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
147 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
148 struct dl_phdr_info *phdr_info);
150 void r_debug_state(struct r_debug *, struct link_map *) __noinline;
155 static char *error_message; /* Message for dlerror(), or NULL */
156 struct r_debug r_debug; /* for GDB; */
157 static bool libmap_disable; /* Disable libmap */
158 static bool ld_loadfltr; /* Immediate filters processing */
159 static char *libmap_override; /* Maps to use in addition to libmap.conf */
160 static bool trust; /* False for setuid and setgid programs */
161 static bool dangerous_ld_env; /* True if environment variables have been
162 used to affect the libraries loaded */
163 static const char *ld_bind_now; /* Environment variable for immediate binding */
164 static const char *ld_debug; /* Environment variable for debugging */
165 static const char *ld_library_path; /* Environment variable for search path */
166 static char *ld_preload; /* Environment variable for libraries to
168 static const char *ld_elf_hints_path; /* Environment variable for alternative hints path */
169 static const char *ld_tracing; /* Called from ldd to print libs */
170 static const char *ld_utrace; /* Use utrace() to log events. */
171 static int (*rtld_functrace)( /* Optional function call tracing hook */
172 const char *caller_obj,
173 const char *callee_obj,
174 const char *callee_func,
176 static const Obj_Entry *rtld_functrace_obj; /* Object thereof */
177 static Obj_Entry *obj_list; /* Head of linked list of shared objects */
178 static Obj_Entry **obj_tail; /* Link field of last object in list */
179 static Obj_Entry **preload_tail;
180 static Obj_Entry *obj_main; /* The main program shared object */
181 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
182 static unsigned int obj_count; /* Number of objects in obj_list */
183 static unsigned int obj_loads; /* Number of objects in obj_list */
185 static int ld_resident; /* Non-zero if resident */
186 static const char *ld_ary[LD_ARY_CACHE];
188 static Objlist initlist;
190 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
191 STAILQ_HEAD_INITIALIZER(list_global);
192 static Objlist list_main = /* Objects loaded at program startup */
193 STAILQ_HEAD_INITIALIZER(list_main);
194 static Objlist list_fini = /* Objects needing fini() calls */
195 STAILQ_HEAD_INITIALIZER(list_fini);
197 static Elf_Sym sym_zero; /* For resolving undefined weak refs. */
199 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
201 extern Elf_Dyn _DYNAMIC;
202 #pragma weak _DYNAMIC
203 #ifndef RTLD_IS_DYNAMIC
204 #define RTLD_IS_DYNAMIC() (&_DYNAMIC != NULL)
207 #ifdef ENABLE_OSRELDATE
211 static int stack_prot = PROT_READ | PROT_WRITE | RTLD_DEFAULT_STACK_EXEC;
212 static int max_stack_flags;
215 * These are the functions the dynamic linker exports to application
216 * programs. They are the only symbols the dynamic linker is willing
217 * to export from itself.
219 static func_ptr_type exports[] = {
220 (func_ptr_type) &_rtld_error,
221 (func_ptr_type) &dlclose,
222 (func_ptr_type) &dlerror,
223 (func_ptr_type) &dlopen,
224 (func_ptr_type) &dlfunc,
225 (func_ptr_type) &dlsym,
226 (func_ptr_type) &dlvsym,
227 (func_ptr_type) &dladdr,
228 (func_ptr_type) &dlinfo,
229 (func_ptr_type) &dl_iterate_phdr,
231 (func_ptr_type) &___tls_get_addr,
233 (func_ptr_type) &__tls_get_addr,
234 (func_ptr_type) &__tls_get_addr_tcb,
235 (func_ptr_type) &_rtld_allocate_tls,
236 (func_ptr_type) &_rtld_free_tls,
237 (func_ptr_type) &_rtld_call_init,
238 (func_ptr_type) &_rtld_thread_init,
239 (func_ptr_type) &_rtld_addr_phdr,
240 (func_ptr_type) &_rtld_get_stack_prot,
245 * Global declarations normally provided by crt1. The dynamic linker is
246 * not built with crt1, so we have to provide them ourselves.
252 * Globals to control TLS allocation.
254 size_t tls_last_offset; /* Static TLS offset of last module */
255 size_t tls_last_size; /* Static TLS size of last module */
256 size_t tls_static_space; /* Static TLS space allocated */
257 int tls_dtv_generation = 1; /* Used to detect when dtv size changes */
258 int tls_max_index = 1; /* Largest module index allocated */
261 * Fill in a DoneList with an allocation large enough to hold all of
262 * the currently-loaded objects. Keep this as a macro since it calls
263 * alloca and we want that to occur within the scope of the caller.
265 #define donelist_init(dlp) \
266 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
267 assert((dlp)->objs != NULL), \
268 (dlp)->num_alloc = obj_count, \
271 #define UTRACE_DLOPEN_START 1
272 #define UTRACE_DLOPEN_STOP 2
273 #define UTRACE_DLCLOSE_START 3
274 #define UTRACE_DLCLOSE_STOP 4
275 #define UTRACE_LOAD_OBJECT 5
276 #define UTRACE_UNLOAD_OBJECT 6
277 #define UTRACE_ADD_RUNDEP 7
278 #define UTRACE_PRELOAD_FINISHED 8
279 #define UTRACE_INIT_CALL 9
280 #define UTRACE_FINI_CALL 10
283 char sig[4]; /* 'RTLD' */
286 void *mapbase; /* Used for 'parent' and 'init/fini' */
288 int refcnt; /* Used for 'mode' */
289 char name[MAXPATHLEN];
292 #define LD_UTRACE(e, h, mb, ms, r, n) do { \
293 if (ld_utrace != NULL) \
294 ld_utrace_log(e, h, mb, ms, r, n); \
298 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
299 int refcnt, const char *name)
301 struct utrace_rtld ut;
309 ut.mapbase = mapbase;
310 ut.mapsize = mapsize;
312 bzero(ut.name, sizeof(ut.name));
314 strlcpy(ut.name, name, sizeof(ut.name));
315 utrace(&ut, sizeof(ut));
319 * Main entry point for dynamic linking. The first argument is the
320 * stack pointer. The stack is expected to be laid out as described
321 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
322 * Specifically, the stack pointer points to a word containing
323 * ARGC. Following that in the stack is a null-terminated sequence
324 * of pointers to argument strings. Then comes a null-terminated
325 * sequence of pointers to environment strings. Finally, there is a
326 * sequence of "auxiliary vector" entries.
328 * The second argument points to a place to store the dynamic linker's
329 * exit procedure pointer and the third to a place to store the main
332 * The return value is the main program's entry point.
335 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
337 Elf_Auxinfo *aux_info[AT_COUNT];
345 Objlist_Entry *entry;
348 /* marino: DO NOT MOVE THESE VARIABLES TO _rtld
349 Obj_Entry **preload_tail;
351 from global to here. It will break the DWARF2 unwind scheme.
352 The system compilers were unaffected, but not gcc 4.6
356 * On entry, the dynamic linker itself has not been relocated yet.
357 * Be very careful not to reference any global data until after
358 * init_rtld has returned. It is OK to reference file-scope statics
359 * and string constants, and to call static and global functions.
362 /* Find the auxiliary vector on the stack. */
365 sp += argc + 1; /* Skip over arguments and NULL terminator */
369 * If we aren't already resident we have to dig out some more info.
370 * Note that auxinfo does not exist when we are resident.
372 * I'm not sure about the ld_resident check. It seems to read zero
373 * prior to relocation, which is what we want. When running from a
374 * resident copy everything will be relocated so we are definitely
377 if (ld_resident == 0) {
378 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
380 aux = (Elf_Auxinfo *) sp;
382 /* Digest the auxiliary vector. */
383 for (i = 0; i < AT_COUNT; i++)
385 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
386 if (auxp->a_type < AT_COUNT)
387 aux_info[auxp->a_type] = auxp;
390 /* Initialize and relocate ourselves. */
391 assert(aux_info[AT_BASE] != NULL);
392 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
395 ld_index = 0; /* don't use old env cache in case we are resident */
396 __progname = obj_rtld.path;
397 argv0 = argv[0] != NULL ? argv[0] : "(null)";
400 trust = !issetugid();
402 ld_bind_now = _getenv_ld("LD_BIND_NOW");
404 * If the process is tainted, then we un-set the dangerous environment
405 * variables. The process will be marked as tainted until setuid(2)
406 * is called. If any child process calls setuid(2) we do not want any
407 * future processes to honor the potentially un-safe variables.
410 if ( unsetenv("LD_DEBUG")
411 || unsetenv("LD_PRELOAD")
412 || unsetenv("LD_LIBRARY_PATH")
413 || unsetenv("LD_ELF_HINTS_PATH")
414 || unsetenv("LD_LIBMAP")
415 || unsetenv("LD_LIBMAP_DISABLE")
416 || unsetenv("LD_LOADFLTR")
418 _rtld_error("environment corrupt; aborting");
422 ld_debug = _getenv_ld("LD_DEBUG");
423 libmap_disable = _getenv_ld("LD_LIBMAP_DISABLE") != NULL;
424 libmap_override = (char *)_getenv_ld("LD_LIBMAP");
425 ld_library_path = _getenv_ld("LD_LIBRARY_PATH");
426 ld_preload = (char *)_getenv_ld("LD_PRELOAD");
427 ld_elf_hints_path = _getenv_ld("LD_ELF_HINTS_PATH");
428 ld_loadfltr = _getenv_ld("LD_LOADFLTR") != NULL;
429 dangerous_ld_env = (ld_library_path != NULL)
430 || (ld_preload != NULL)
431 || (ld_elf_hints_path != NULL)
433 || (libmap_override != NULL)
436 ld_tracing = _getenv_ld("LD_TRACE_LOADED_OBJECTS");
437 ld_utrace = _getenv_ld("LD_UTRACE");
439 if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0)
440 ld_elf_hints_path = _PATH_ELF_HINTS;
442 if (ld_debug != NULL && *ld_debug != '\0')
444 dbg("%s is initialized, base address = %p", __progname,
445 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
446 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
447 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
449 dbg("initializing thread locks");
453 * If we are resident we can skip work that we have already done.
454 * Note that the stack is reset and there is no Elf_Auxinfo
455 * when running from a resident image, and the static globals setup
456 * between here and resident_skip will have already been setup.
462 * Load the main program, or process its program header if it is
465 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
466 int fd = aux_info[AT_EXECFD]->a_un.a_val;
467 dbg("loading main program");
468 obj_main = map_object(fd, argv0, NULL);
470 if (obj_main == NULL)
472 max_stack_flags = obj->stack_flags;
473 } else { /* Main program already loaded. */
474 const Elf_Phdr *phdr;
478 dbg("processing main program's program header");
479 assert(aux_info[AT_PHDR] != NULL);
480 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
481 assert(aux_info[AT_PHNUM] != NULL);
482 phnum = aux_info[AT_PHNUM]->a_un.a_val;
483 assert(aux_info[AT_PHENT] != NULL);
484 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
485 assert(aux_info[AT_ENTRY] != NULL);
486 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
487 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
491 char buf[MAXPATHLEN];
492 if (aux_info[AT_EXECPATH] != 0) {
495 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
496 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
497 if (kexecpath[0] == '/')
498 obj_main->path = kexecpath;
499 else if (getcwd(buf, sizeof(buf)) == NULL ||
500 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
501 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
502 obj_main->path = xstrdup(argv0);
504 obj_main->path = xstrdup(buf);
506 char resolved[MAXPATHLEN];
507 dbg("No AT_EXECPATH");
508 if (argv0[0] == '/') {
509 if (realpath(argv0, resolved) != NULL)
510 obj_main->path = xstrdup(resolved);
512 obj_main->path = xstrdup(argv0);
514 if (getcwd(buf, sizeof(buf)) != NULL
515 && strlcat(buf, "/", sizeof(buf)) < sizeof(buf)
516 && strlcat(buf, argv0, sizeof (buf)) < sizeof(buf)
517 && access(buf, R_OK) == 0
518 && realpath(buf, resolved) != NULL)
519 obj_main->path = xstrdup(resolved);
521 obj_main->path = xstrdup(argv0);
524 dbg("obj_main path %s", obj_main->path);
525 obj_main->mainprog = true;
527 if (aux_info[AT_STACKPROT] != NULL &&
528 aux_info[AT_STACKPROT]->a_un.a_val != 0)
529 stack_prot = aux_info[AT_STACKPROT]->a_un.a_val;
532 * Get the actual dynamic linker pathname from the executable if
533 * possible. (It should always be possible.) That ensures that
534 * gdb will find the right dynamic linker even if a non-standard
537 if (obj_main->interp != NULL &&
538 strcmp(obj_main->interp, obj_rtld.path) != 0) {
540 obj_rtld.path = xstrdup(obj_main->interp);
541 __progname = obj_rtld.path;
544 digest_dynamic(obj_main, 0);
546 linkmap_add(obj_main);
547 linkmap_add(&obj_rtld);
549 /* Link the main program into the list of objects. */
550 *obj_tail = obj_main;
551 obj_tail = &obj_main->next;
554 /* Make sure we don't call the main program's init and fini functions. */
555 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
557 /* Initialize a fake symbol for resolving undefined weak references. */
558 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
559 sym_zero.st_shndx = SHN_UNDEF;
560 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
563 libmap_disable = (bool)lm_init(libmap_override);
565 dbg("loading LD_PRELOAD libraries");
566 if (load_preload_objects() == -1)
568 preload_tail = obj_tail;
570 dbg("loading needed objects");
571 if (load_needed_objects(obj_main, 0) == -1)
574 /* Make a list of all objects loaded at startup. */
575 for (obj = obj_list; obj != NULL; obj = obj->next) {
576 objlist_push_tail(&list_main, obj);
580 dbg("checking for required versions");
581 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
586 if (ld_tracing) { /* We're done */
587 trace_loaded_objects(obj_main);
591 if (ld_resident) /* XXX clean this up! */
594 if (_getenv_ld("LD_DUMP_REL_PRE") != NULL) {
595 dump_relocations(obj_main);
599 /* setup TLS for main thread */
600 dbg("initializing initial thread local storage");
601 STAILQ_FOREACH(entry, &list_main, link) {
603 * Allocate all the initial objects out of the static TLS
604 * block even if they didn't ask for it.
606 allocate_tls_offset(entry->obj);
609 tls_static_space = tls_last_offset + RTLD_STATIC_TLS_EXTRA;
612 * Do not try to allocate the TLS here, let libc do it itself.
613 * (crt1 for the program will call _init_tls())
616 if (relocate_objects(obj_main,
617 ld_bind_now != NULL && *ld_bind_now != '\0', &obj_rtld, NULL) == -1)
620 dbg("doing copy relocations");
621 if (do_copy_relocations(obj_main) == -1)
626 if (_getenv_ld("LD_RESIDENT_UNREGISTER_NOW")) {
627 if (exec_sys_unregister(-1) < 0) {
628 dbg("exec_sys_unregister failed %d\n", errno);
631 dbg("exec_sys_unregister success\n");
635 if (_getenv_ld("LD_DUMP_REL_POST") != NULL) {
636 dump_relocations(obj_main);
640 dbg("initializing key program variables");
641 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
642 set_program_var("environ", env);
643 set_program_var("__elf_aux_vector", aux);
645 if (_getenv_ld("LD_RESIDENT_REGISTER_NOW")) {
646 extern void resident_start(void);
648 if (exec_sys_register(resident_start) < 0) {
649 dbg("exec_sys_register failed %d\n", errno);
652 dbg("exec_sys_register success\n");
656 /* Make a list of init functions to call. */
657 objlist_init(&initlist);
658 initlist_add_objects(obj_list, preload_tail, &initlist);
660 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
662 map_stacks_exec(NULL);
664 dbg("resolving ifuncs");
665 if (resolve_objects_ifunc(obj_main,
666 ld_bind_now != NULL && *ld_bind_now != '\0', NULL) == -1)
670 * Do NOT call the initlist here, give libc a chance to set up
671 * the initial TLS segment. crt1 will then call _rtld_call_init().
674 dbg("transferring control to program entry point = %p", obj_main->entry);
676 /* Return the exit procedure and the program entry point. */
677 *exit_proc = rtld_exit;
679 return (func_ptr_type) obj_main->entry;
683 * Call the initialization list for dynamically loaded libraries.
684 * (called from crt1.c).
687 _rtld_call_init(void)
689 RtldLockState lockstate;
692 wlock_acquire(rtld_bind_lock, &lockstate);
693 objlist_call_init(&initlist, &lockstate);
694 objlist_clear(&initlist);
695 dbg("loading filtees");
696 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
697 if (ld_loadfltr || obj->z_loadfltr)
698 load_filtees(obj, 0, &lockstate);
700 lock_release(rtld_bind_lock, &lockstate);
704 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def)
709 ptr = (void *)make_function_pointer(def, obj);
710 target = ((Elf_Addr (*)(void))ptr)();
711 return ((void *)target);
715 _rtld_bind(Obj_Entry *obj, Elf_Size reloff, void *stack)
719 const Obj_Entry *defobj;
722 RtldLockState lockstate;
724 rlock_acquire(rtld_bind_lock, &lockstate);
725 if (sigsetjmp(lockstate.env, 0) != 0)
726 lock_upgrade(rtld_bind_lock, &lockstate);
728 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
730 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
732 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
733 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL,
737 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
738 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
740 target = (Elf_Addr)(defobj->relocbase + def->st_value);
742 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
743 defobj->strtab + def->st_name, basename(obj->path),
744 (void *)target, basename(defobj->path));
747 * If we have a function call tracing hook, and the
748 * hook would like to keep tracing this one function,
749 * prevent the relocation so we will wind up here
750 * the next time again.
752 * We don't want to functrace calls from the functracer
753 * to avoid recursive loops.
755 if (rtld_functrace != NULL && obj != rtld_functrace_obj) {
756 if (rtld_functrace(obj->path,
758 defobj->strtab + def->st_name,
760 lock_release(rtld_bind_lock, &lockstate);
765 * Write the new contents for the jmpslot. Note that depending on
766 * architecture, the value which we need to return back to the
767 * lazy binding trampoline may or may not be the target
768 * address. The value returned from reloc_jmpslot() is the value
769 * that the trampoline needs.
771 target = reloc_jmpslot(where, target, defobj, obj, rel);
772 lock_release(rtld_bind_lock, &lockstate);
777 * Error reporting function. Use it like printf. If formats the message
778 * into a buffer, and sets things up so that the next call to dlerror()
779 * will return the message.
782 _rtld_error(const char *fmt, ...)
784 static char buf[512];
788 rtld_vsnprintf(buf, sizeof buf, fmt, ap);
794 * Return a dynamically-allocated copy of the current error message, if any.
799 return error_message == NULL ? NULL : xstrdup(error_message);
803 * Restore the current error message from a copy which was previously saved
804 * by errmsg_save(). The copy is freed.
807 errmsg_restore(char *saved_msg)
809 if (saved_msg == NULL)
810 error_message = NULL;
812 _rtld_error("%s", saved_msg);
818 basename(const char *name)
820 const char *p = strrchr(name, '/');
821 return p != NULL ? p + 1 : name;
824 static struct utsname uts;
827 origin_subst_one(char **res, const char *real, const char *kw, const char *subst,
837 subst_len = kw_len = 0;
841 if (subst_len == 0) {
842 subst_len = strlen(subst);
846 *res = xmalloc(PATH_MAX);
849 if ((res1 - *res) + subst_len + (p1 - p) >= PATH_MAX) {
850 _rtld_error("Substitution of %s in %s cannot be performed",
852 if (may_free != NULL)
857 memcpy(res1, p, p1 - p);
859 memcpy(res1, subst, subst_len);
864 if (may_free != NULL)
867 *res = xstrdup(real);
871 if (may_free != NULL)
873 if (strlcat(res1, p, PATH_MAX - (res1 - *res)) >= PATH_MAX) {
883 origin_subst(const char *real, const char *origin_path)
885 char *res1, *res2, *res3, *res4;
887 if (uts.sysname[0] == '\0') {
888 if (uname(&uts) != 0) {
889 _rtld_error("utsname failed: %d", errno);
893 if (!origin_subst_one(&res1, real, "$ORIGIN", origin_path, NULL) ||
894 !origin_subst_one(&res2, res1, "$OSNAME", uts.sysname, res1) ||
895 !origin_subst_one(&res3, res2, "$OSREL", uts.release, res2) ||
896 !origin_subst_one(&res4, res3, "$PLATFORM", uts.machine, res3))
904 const char *msg = dlerror();
908 rtld_fdputstr(STDERR_FILENO, msg);
913 * Process a shared object's DYNAMIC section, and save the important
914 * information in its Obj_Entry structure.
917 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
918 const Elf_Dyn **dyn_soname)
921 Needed_Entry **needed_tail = &obj->needed;
922 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
923 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
924 int plttype = DT_REL;
929 obj->bind_now = false;
930 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
931 switch (dynp->d_tag) {
934 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
938 obj->relsize = dynp->d_un.d_val;
942 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
946 obj->pltrel = (const Elf_Rel *)
947 (obj->relocbase + dynp->d_un.d_ptr);
951 obj->pltrelsize = dynp->d_un.d_val;
955 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
959 obj->relasize = dynp->d_un.d_val;
963 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
967 plttype = dynp->d_un.d_val;
968 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
972 obj->symtab = (const Elf_Sym *)
973 (obj->relocbase + dynp->d_un.d_ptr);
977 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
981 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
985 obj->strsize = dynp->d_un.d_val;
989 obj->verneed = (const Elf_Verneed *) (obj->relocbase +
994 obj->verneednum = dynp->d_un.d_val;
998 obj->verdef = (const Elf_Verdef *) (obj->relocbase +
1003 obj->verdefnum = dynp->d_un.d_val;
1007 obj->versyms = (const Elf_Versym *)(obj->relocbase +
1013 const Elf_Hashelt *hashtab = (const Elf_Hashelt *)
1014 (obj->relocbase + dynp->d_un.d_ptr);
1015 obj->nbuckets = hashtab[0];
1016 obj->nchains = hashtab[1];
1017 obj->buckets = hashtab + 2;
1018 obj->chains = obj->buckets + obj->nbuckets;
1024 Needed_Entry *nep = NEW(Needed_Entry);
1025 nep->name = dynp->d_un.d_val;
1030 needed_tail = &nep->next;
1036 Needed_Entry *nep = NEW(Needed_Entry);
1037 nep->name = dynp->d_un.d_val;
1041 *needed_filtees_tail = nep;
1042 needed_filtees_tail = &nep->next;
1048 Needed_Entry *nep = NEW(Needed_Entry);
1049 nep->name = dynp->d_un.d_val;
1053 *needed_aux_filtees_tail = nep;
1054 needed_aux_filtees_tail = &nep->next;
1059 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
1063 obj->textrel = true;
1067 obj->symbolic = true;
1071 case DT_RUNPATH: /* XXX: process separately */
1073 * We have to wait until later to process this, because we
1074 * might not have gotten the address of the string table yet.
1084 obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1088 obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1092 /* XXX - not implemented yet */
1094 dbg("Filling in DT_DEBUG entry");
1095 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
1099 if ((dynp->d_un.d_val & DF_ORIGIN) && trust)
1100 obj->z_origin = true;
1101 if (dynp->d_un.d_val & DF_SYMBOLIC)
1102 obj->symbolic = true;
1103 if (dynp->d_un.d_val & DF_TEXTREL)
1104 obj->textrel = true;
1105 if (dynp->d_un.d_val & DF_BIND_NOW)
1106 obj->bind_now = true;
1107 /*if (dynp->d_un.d_val & DF_STATIC_TLS)
1112 if (dynp->d_un.d_val & DF_1_NOOPEN)
1113 obj->z_noopen = true;
1114 if ((dynp->d_un.d_val & DF_1_ORIGIN) && trust)
1115 obj->z_origin = true;
1116 /*if (dynp->d_un.d_val & DF_1_GLOBAL)
1118 if (dynp->d_un.d_val & DF_1_BIND_NOW)
1119 obj->bind_now = true;
1120 if (dynp->d_un.d_val & DF_1_NODELETE)
1121 obj->z_nodelete = true;
1122 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1123 obj->z_loadfltr = true;
1128 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1135 obj->traced = false;
1137 if (plttype == DT_RELA) {
1138 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1140 obj->pltrelasize = obj->pltrelsize;
1141 obj->pltrelsize = 0;
1146 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1147 const Elf_Dyn *dyn_soname)
1150 if (obj->z_origin && obj->origin_path == NULL) {
1151 obj->origin_path = xmalloc(PATH_MAX);
1152 if (rtld_dirname_abs(obj->path, obj->origin_path) == -1)
1156 if (dyn_rpath != NULL) {
1157 obj->rpath = (char *)obj->strtab + dyn_rpath->d_un.d_val;
1159 obj->rpath = origin_subst(obj->rpath, obj->origin_path);
1162 if (dyn_soname != NULL)
1163 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1167 digest_dynamic(Obj_Entry *obj, int early)
1169 const Elf_Dyn *dyn_rpath;
1170 const Elf_Dyn *dyn_soname;
1172 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname);
1173 digest_dynamic2(obj, dyn_rpath, dyn_soname);
1177 * Process a shared object's program header. This is used only for the
1178 * main program, when the kernel has already loaded the main program
1179 * into memory before calling the dynamic linker. It creates and
1180 * returns an Obj_Entry structure.
1183 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1186 const Elf_Phdr *phlimit = phdr + phnum;
1191 for (ph = phdr; ph < phlimit; ph++) {
1192 if (ph->p_type != PT_PHDR)
1196 obj->phsize = ph->p_memsz;
1197 obj->relocbase = (caddr_t)phdr - ph->p_vaddr;
1201 obj->stack_flags = PF_X | PF_R | PF_W;
1203 for (ph = phdr; ph < phlimit; ph++) {
1204 switch (ph->p_type) {
1207 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1211 if (nsegs == 0) { /* First load segment */
1212 obj->vaddrbase = trunc_page(ph->p_vaddr);
1213 obj->mapbase = obj->vaddrbase + obj->relocbase;
1214 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
1216 } else { /* Last load segment */
1217 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1224 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1229 obj->tlssize = ph->p_memsz;
1230 obj->tlsalign = ph->p_align;
1231 obj->tlsinitsize = ph->p_filesz;
1232 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1236 obj->stack_flags = ph->p_flags;
1240 obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1241 obj->relro_size = round_page(ph->p_memsz);
1246 _rtld_error("%s: too few PT_LOAD segments", path);
1255 dlcheck(void *handle)
1259 for (obj = obj_list; obj != NULL; obj = obj->next)
1260 if (obj == (Obj_Entry *) handle)
1263 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1264 _rtld_error("Invalid shared object handle %p", handle);
1271 * If the given object is already in the donelist, return true. Otherwise
1272 * add the object to the list and return false.
1275 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1279 for (i = 0; i < dlp->num_used; i++)
1280 if (dlp->objs[i] == obj)
1283 * Our donelist allocation should always be sufficient. But if
1284 * our threads locking isn't working properly, more shared objects
1285 * could have been loaded since we allocated the list. That should
1286 * never happen, but we'll handle it properly just in case it does.
1288 if (dlp->num_used < dlp->num_alloc)
1289 dlp->objs[dlp->num_used++] = obj;
1294 * Hash function for symbol table lookup. Don't even think about changing
1295 * this. It is specified by the System V ABI.
1298 elf_hash(const char *name)
1300 const unsigned char *p = (const unsigned char *) name;
1301 unsigned long h = 0;
1304 while (*p != '\0') {
1305 h = (h << 4) + *p++;
1306 if ((g = h & 0xf0000000) != 0)
1314 * Find the library with the given name, and return its full pathname.
1315 * The returned string is dynamically allocated. Generates an error
1316 * message and returns NULL if the library cannot be found.
1318 * If the second argument is non-NULL, then it refers to an already-
1319 * loaded shared object, whose library search path will be searched.
1321 * The search order is:
1323 * rpath in the referencing file
1328 find_library(const char *xname, const Obj_Entry *refobj)
1333 if (strchr(xname, '/') != NULL) { /* Hard coded pathname */
1334 if (xname[0] != '/' && !trust) {
1335 _rtld_error("Absolute pathname required for shared object \"%s\"",
1339 if (refobj != NULL && refobj->z_origin)
1340 return origin_subst(xname, refobj->origin_path);
1342 return xstrdup(xname);
1345 if (libmap_disable || (refobj == NULL) ||
1346 (name = lm_find(refobj->path, xname)) == NULL)
1347 name = (char *)xname;
1349 dbg(" Searching for \"%s\"", name);
1351 if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
1353 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
1354 (pathname = search_library_path(name, gethints())) != NULL ||
1355 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
1358 if(refobj != NULL && refobj->path != NULL) {
1359 _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
1360 name, basename(refobj->path));
1362 _rtld_error("Shared object \"%s\" not found", name);
1368 * Given a symbol number in a referencing object, find the corresponding
1369 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1370 * no definition was found. Returns a pointer to the Obj_Entry of the
1371 * defining object via the reference parameter DEFOBJ_OUT.
1374 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1375 const Obj_Entry **defobj_out, int flags, SymCache *cache,
1376 RtldLockState *lockstate)
1380 const Obj_Entry *defobj;
1386 * If we have already found this symbol, get the information from
1389 if (symnum >= refobj->nchains)
1390 return NULL; /* Bad object */
1391 if (cache != NULL && cache[symnum].sym != NULL) {
1392 *defobj_out = cache[symnum].obj;
1393 return cache[symnum].sym;
1396 ref = refobj->symtab + symnum;
1397 name = refobj->strtab + ref->st_name;
1402 * We don't have to do a full scale lookup if the symbol is local.
1403 * We know it will bind to the instance in this load module; to
1404 * which we already have a pointer (ie ref). By not doing a lookup,
1405 * we not only improve performance, but it also avoids unresolvable
1406 * symbols when local symbols are not in the hash table.
1408 * This might occur for TLS module relocations, which simply use
1411 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1412 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1413 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1416 symlook_init(&req, name);
1418 req.ventry = fetch_ventry(refobj, symnum);
1419 req.lockstate = lockstate;
1420 res = symlook_default(&req, refobj);
1423 defobj = req.defobj_out;
1431 * If we found no definition and the reference is weak, treat the
1432 * symbol as having the value zero.
1434 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1440 *defobj_out = defobj;
1441 /* Record the information in the cache to avoid subsequent lookups. */
1442 if (cache != NULL) {
1443 cache[symnum].sym = def;
1444 cache[symnum].obj = defobj;
1447 if (refobj != &obj_rtld)
1448 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1454 * Return the search path from the ldconfig hints file, reading it if
1455 * necessary. Returns NULL if there are problems with the hints file,
1456 * or if the search path there is empty.
1463 if (hints == NULL) {
1465 struct elfhints_hdr hdr;
1468 /* Keep from trying again in case the hints file is bad. */
1471 if ((fd = open(ld_elf_hints_path, O_RDONLY)) == -1)
1473 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1474 hdr.magic != ELFHINTS_MAGIC ||
1479 p = xmalloc(hdr.dirlistlen + 1);
1480 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1481 read(fd, p, hdr.dirlistlen + 1) != (ssize_t)hdr.dirlistlen + 1) {
1489 return hints[0] != '\0' ? hints : NULL;
1493 init_dag(Obj_Entry *root)
1495 const Needed_Entry *needed;
1496 const Objlist_Entry *elm;
1499 if (root->dag_inited)
1501 donelist_init(&donelist);
1503 /* Root object belongs to own DAG. */
1504 objlist_push_tail(&root->dldags, root);
1505 objlist_push_tail(&root->dagmembers, root);
1506 donelist_check(&donelist, root);
1509 * Add dependencies of root object to DAG in breadth order
1510 * by exploiting the fact that each new object get added
1511 * to the tail of the dagmembers list.
1513 STAILQ_FOREACH(elm, &root->dagmembers, link) {
1514 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
1515 if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
1517 objlist_push_tail(&needed->obj->dldags, root);
1518 objlist_push_tail(&root->dagmembers, needed->obj);
1521 root->dag_inited = true;
1525 * Initialize the dynamic linker. The argument is the address at which
1526 * the dynamic linker has been mapped into memory. The primary task of
1527 * this function is to relocate the dynamic linker.
1530 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
1532 Obj_Entry objtmp; /* Temporary rtld object */
1533 const Elf_Dyn *dyn_rpath;
1534 const Elf_Dyn *dyn_soname;
1537 * Conjure up an Obj_Entry structure for the dynamic linker.
1539 * The "path" member can't be initialized yet because string constants
1540 * cannot yet be accessed. Below we will set it correctly.
1542 memset(&objtmp, 0, sizeof(objtmp));
1545 objtmp.mapbase = mapbase;
1547 objtmp.relocbase = mapbase;
1549 if (RTLD_IS_DYNAMIC()) {
1550 objtmp.dynamic = rtld_dynamic(&objtmp);
1551 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname);
1552 assert(objtmp.needed == NULL);
1553 assert(!objtmp.textrel);
1556 * Temporarily put the dynamic linker entry into the object list, so
1557 * that symbols can be found.
1560 relocate_objects(&objtmp, true, &objtmp, NULL);
1563 /* Initialize the object list. */
1564 obj_tail = &obj_list;
1566 /* Now that non-local variables can be accesses, copy out obj_rtld. */
1567 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1569 #ifdef ENABLE_OSRELDATE
1570 if (aux_info[AT_OSRELDATE] != NULL)
1571 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
1574 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname);
1576 /* Replace the path with a dynamically allocated copy. */
1577 obj_rtld.path = xstrdup(PATH_RTLD);
1579 r_debug.r_brk = r_debug_state;
1580 r_debug.r_state = RT_CONSISTENT;
1584 * Add the init functions from a needed object list (and its recursive
1585 * needed objects) to "list". This is not used directly; it is a helper
1586 * function for initlist_add_objects(). The write lock must be held
1587 * when this function is called.
1590 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1592 /* Recursively process the successor needed objects. */
1593 if (needed->next != NULL)
1594 initlist_add_neededs(needed->next, list);
1596 /* Process the current needed object. */
1597 if (needed->obj != NULL)
1598 initlist_add_objects(needed->obj, &needed->obj->next, list);
1602 * Scan all of the DAGs rooted in the range of objects from "obj" to
1603 * "tail" and add their init functions to "list". This recurses over
1604 * the DAGs and ensure the proper init ordering such that each object's
1605 * needed libraries are initialized before the object itself. At the
1606 * same time, this function adds the objects to the global finalization
1607 * list "list_fini" in the opposite order. The write lock must be
1608 * held when this function is called.
1611 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1613 if (obj->init_scanned || obj->init_done)
1615 obj->init_scanned = true;
1617 /* Recursively process the successor objects. */
1618 if (&obj->next != tail)
1619 initlist_add_objects(obj->next, tail, list);
1621 /* Recursively process the needed objects. */
1622 if (obj->needed != NULL)
1623 initlist_add_neededs(obj->needed, list);
1625 /* Add the object to the init list. */
1626 if (obj->init != (Elf_Addr)NULL)
1627 objlist_push_tail(list, obj);
1629 /* Add the object to the global fini list in the reverse order. */
1630 if (obj->fini != (Elf_Addr)NULL && !obj->on_fini_list) {
1631 objlist_push_head(&list_fini, obj);
1632 obj->on_fini_list = true;
1637 #define FPTR_TARGET(f) ((Elf_Addr) (f))
1641 is_exported(const Elf_Sym *def)
1644 const func_ptr_type *p;
1646 value = (Elf_Addr)(obj_rtld.relocbase + def->st_value);
1647 for (p = exports; *p != NULL; p++)
1648 if (FPTR_TARGET(*p) == value)
1654 free_needed_filtees(Needed_Entry *n)
1656 Needed_Entry *needed, *needed1;
1658 for (needed = n; needed != NULL; needed = needed->next) {
1659 if (needed->obj != NULL) {
1660 dlclose(needed->obj);
1664 for (needed = n; needed != NULL; needed = needed1) {
1665 needed1 = needed->next;
1671 unload_filtees(Obj_Entry *obj)
1674 free_needed_filtees(obj->needed_filtees);
1675 obj->needed_filtees = NULL;
1676 free_needed_filtees(obj->needed_aux_filtees);
1677 obj->needed_aux_filtees = NULL;
1678 obj->filtees_loaded = false;
1682 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags)
1685 for (; needed != NULL; needed = needed->next) {
1686 needed->obj = dlopen_object(obj->strtab + needed->name, obj,
1687 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
1693 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
1696 lock_restart_for_upgrade(lockstate);
1697 if (!obj->filtees_loaded) {
1698 load_filtee1(obj, obj->needed_filtees, flags);
1699 load_filtee1(obj, obj->needed_aux_filtees, flags);
1700 obj->filtees_loaded = true;
1705 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
1709 for (; needed != NULL; needed = needed->next) {
1710 obj1 = needed->obj = load_object(obj->strtab + needed->name, obj,
1711 flags & ~RTLD_LO_NOLOAD);
1712 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
1714 if (obj1 != NULL && obj1->z_nodelete && !obj1->ref_nodel) {
1715 dbg("obj %s nodelete", obj1->path);
1718 obj1->ref_nodel = true;
1725 * Given a shared object, traverse its list of needed objects, and load
1726 * each of them. Returns 0 on success. Generates an error message and
1727 * returns -1 on failure.
1730 load_needed_objects(Obj_Entry *first, int flags)
1734 for (obj = first; obj != NULL; obj = obj->next) {
1735 if (process_needed(obj, obj->needed, flags) == -1)
1742 load_preload_objects(void)
1744 char *p = ld_preload;
1745 static const char delim[] = " \t:;";
1750 p += strspn(p, delim);
1751 while (*p != '\0') {
1752 size_t len = strcspn(p, delim);
1760 obj = load_object(p, NULL, 0);
1762 return -1; /* XXX - cleanup */
1765 p += strspn(p, delim);
1767 /* Check for the magic tracing function */
1768 symlook_init(&req, RTLD_FUNCTRACE);
1769 res = symlook_obj(&req, obj);
1771 rtld_functrace = (void *)(req.defobj_out->relocbase +
1772 req.sym_out->st_value);
1773 rtld_functrace_obj = req.defobj_out;
1776 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
1781 * Load a shared object into memory, if it is not already loaded.
1783 * Returns a pointer to the Obj_Entry for the object. Returns NULL
1787 load_object(const char *name, const Obj_Entry *refobj, int flags)
1794 for (obj = obj_list->next; obj != NULL; obj = obj->next)
1795 if (object_match_name(obj, name))
1798 path = find_library(name, refobj);
1803 * If we didn't find a match by pathname, open the file and check
1804 * again by device and inode. This avoids false mismatches caused
1805 * by multiple links or ".." in pathnames.
1807 * To avoid a race, we open the file and use fstat() rather than
1810 if ((fd = open(path, O_RDONLY)) == -1) {
1811 _rtld_error("Cannot open \"%s\"", path);
1815 if (fstat(fd, &sb) == -1) {
1816 _rtld_error("Cannot fstat \"%s\"", path);
1821 for (obj = obj_list->next; obj != NULL; obj = obj->next)
1822 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
1825 object_add_name(obj, name);
1830 if (flags & RTLD_LO_NOLOAD) {
1836 /* First use of this object, so we must map it in */
1837 obj = do_load_object(fd, name, path, &sb, flags);
1846 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
1853 * but first, make sure that environment variables haven't been
1854 * used to circumvent the noexec flag on a filesystem.
1856 if (dangerous_ld_env) {
1857 if (fstatfs(fd, &fs) != 0) {
1858 _rtld_error("Cannot fstatfs \"%s\"", path);
1861 if (fs.f_flags & MNT_NOEXEC) {
1862 _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
1866 dbg("loading \"%s\"", path);
1867 obj = map_object(fd, path, sbp);
1871 object_add_name(obj, name);
1873 digest_dynamic(obj, 0);
1874 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
1876 dbg("refusing to load non-loadable \"%s\"", obj->path);
1877 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
1878 munmap(obj->mapbase, obj->mapsize);
1884 obj_tail = &obj->next;
1887 linkmap_add(obj); /* for GDB & dlinfo() */
1888 max_stack_flags |= obj->stack_flags;
1890 dbg(" %p .. %p: %s", obj->mapbase,
1891 obj->mapbase + obj->mapsize - 1, obj->path);
1893 dbg(" WARNING: %s has impure text", obj->path);
1894 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
1901 obj_from_addr(const void *addr)
1905 for (obj = obj_list; obj != NULL; obj = obj->next) {
1906 if (addr < (void *) obj->mapbase)
1908 if (addr < (void *) (obj->mapbase + obj->mapsize))
1915 * Call the finalization functions for each of the objects in "list"
1916 * belonging to the DAG of "root" and referenced once. If NULL "root"
1917 * is specified, every finalization function will be called regardless
1918 * of the reference count and the list elements won't be freed. All of
1919 * the objects are expected to have non-NULL fini functions.
1922 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
1927 assert(root == NULL || root->refcount == 1);
1930 * Preserve the current error message since a fini function might
1931 * call into the dynamic linker and overwrite it.
1933 saved_msg = errmsg_save();
1935 STAILQ_FOREACH(elm, list, link) {
1936 if (root != NULL && (elm->obj->refcount != 1 ||
1937 objlist_find(&root->dagmembers, elm->obj) == NULL))
1939 dbg("calling fini function for %s at %p", elm->obj->path,
1940 (void *)elm->obj->fini);
1941 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini, 0, 0,
1943 /* Remove object from fini list to prevent recursive invocation. */
1944 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1946 * XXX: If a dlopen() call references an object while the
1947 * fini function is in progress, we might end up trying to
1948 * unload the referenced object in dlclose() or the object
1949 * won't be unloaded although its fini function has been
1952 lock_release(rtld_bind_lock, lockstate);
1953 call_initfini_pointer(elm->obj, elm->obj->fini);
1954 wlock_acquire(rtld_bind_lock, lockstate);
1955 /* No need to free anything if process is going down. */
1959 * We must restart the list traversal after every fini call
1960 * because a dlclose() call from the fini function or from
1961 * another thread might have modified the reference counts.
1965 } while (elm != NULL);
1966 errmsg_restore(saved_msg);
1970 * Call the initialization functions for each of the objects in
1971 * "list". All of the objects are expected to have non-NULL init
1975 objlist_call_init(Objlist *list, RtldLockState *lockstate)
1982 * Clean init_scanned flag so that objects can be rechecked and
1983 * possibly initialized earlier if any of vectors called below
1984 * cause the change by using dlopen.
1986 for (obj = obj_list; obj != NULL; obj = obj->next)
1987 obj->init_scanned = false;
1990 * Preserve the current error message since an init function might
1991 * call into the dynamic linker and overwrite it.
1993 saved_msg = errmsg_save();
1994 STAILQ_FOREACH(elm, list, link) {
1995 if (elm->obj->init_done) /* Initialized early. */
1997 dbg("calling init function for %s at %p", elm->obj->path,
1998 (void *)elm->obj->init);
1999 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init, 0, 0,
2002 * Race: other thread might try to use this object before current
2003 * one completes the initilization. Not much can be done here
2004 * without better locking.
2006 elm->obj->init_done = true;
2007 lock_release(rtld_bind_lock, lockstate);
2008 call_initfini_pointer(elm->obj, elm->obj->init);
2009 wlock_acquire(rtld_bind_lock, lockstate);
2011 errmsg_restore(saved_msg);
2015 objlist_clear(Objlist *list)
2019 while (!STAILQ_EMPTY(list)) {
2020 elm = STAILQ_FIRST(list);
2021 STAILQ_REMOVE_HEAD(list, link);
2026 static Objlist_Entry *
2027 objlist_find(Objlist *list, const Obj_Entry *obj)
2031 STAILQ_FOREACH(elm, list, link)
2032 if (elm->obj == obj)
2038 objlist_init(Objlist *list)
2044 objlist_push_head(Objlist *list, Obj_Entry *obj)
2048 elm = NEW(Objlist_Entry);
2050 STAILQ_INSERT_HEAD(list, elm, link);
2054 objlist_push_tail(Objlist *list, Obj_Entry *obj)
2058 elm = NEW(Objlist_Entry);
2060 STAILQ_INSERT_TAIL(list, elm, link);
2064 objlist_remove(Objlist *list, Obj_Entry *obj)
2068 if ((elm = objlist_find(list, obj)) != NULL) {
2069 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2075 * Relocate newly-loaded shared objects. The argument is a pointer to
2076 * the Obj_Entry for the first such object. All objects from the first
2077 * to the end of the list of objects are relocated. Returns 0 on success,
2081 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
2082 RtldLockState *lockstate)
2086 for (obj = first; obj != NULL; obj = obj->next) {
2088 dbg("relocating \"%s\"", obj->path);
2089 if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
2090 obj->symtab == NULL || obj->strtab == NULL) {
2091 _rtld_error("%s: Shared object has no run-time symbol table",
2097 /* There are relocations to the write-protected text segment. */
2098 if (mprotect(obj->mapbase, obj->textsize,
2099 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
2100 _rtld_error("%s: Cannot write-enable text segment: %s",
2101 obj->path, strerror(errno));
2106 /* Process the non-PLT relocations. */
2107 if (reloc_non_plt(obj, rtldobj, lockstate))
2111 * Reprotect the text segment. Make sure it is included in the
2112 * core dump since we modified it. This unfortunately causes the
2113 * entire text segment to core-out but we don't have much of a
2114 * choice. We could try to only reenable core dumps on pages
2115 * in which relocations occured but that is likely most of the text
2116 * pages anyway, and even that would not work because the rest of
2117 * the text pages would wind up as a read-only OBJT_DEFAULT object
2118 * (created due to our modifications) backed by the original OBJT_VNODE
2119 * object, and the ELF coredump code is currently only able to dump
2120 * vnode records for pure vnode-backed mappings, not vnode backings
2121 * to memory objects.
2124 madvise(obj->mapbase, obj->textsize, MADV_CORE);
2125 if (mprotect(obj->mapbase, obj->textsize,
2126 PROT_READ|PROT_EXEC) == -1) {
2127 _rtld_error("%s: Cannot write-protect text segment: %s",
2128 obj->path, strerror(errno));
2134 /* Set the special PLT or GOT entries. */
2137 /* Process the PLT relocations. */
2138 if (reloc_plt(obj) == -1)
2140 /* Relocate the jump slots if we are doing immediate binding. */
2141 if (obj->bind_now || bind_now)
2142 if (reloc_jmpslots(obj, lockstate) == -1)
2146 * Set up the magic number and version in the Obj_Entry. These
2147 * were checked in the crt1.o from the original ElfKit, so we
2148 * set them for backward compatibility.
2150 obj->magic = RTLD_MAGIC;
2151 obj->version = RTLD_VERSION;
2154 * Set relocated data to read-only status if protection specified
2157 if (obj->relro_size) {
2158 if (mprotect(obj->relro_page, obj->relro_size, PROT_READ) == -1) {
2159 _rtld_error("%s: Cannot enforce relro relocation: %s",
2160 obj->path, strerror(errno));
2170 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
2171 * referencing STT_GNU_IFUNC symbols is postponed till the other
2172 * relocations are done. The indirect functions specified as
2173 * ifunc are allowed to call other symbols, so we need to have
2174 * objects relocated before asking for resolution from indirects.
2176 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
2177 * instead of the usual lazy handling of PLT slots. It is
2178 * consistent with how GNU does it.
2181 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, RtldLockState *lockstate)
2183 if (obj->irelative && reloc_iresolve(obj, lockstate) == -1)
2185 if ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
2186 reloc_gnu_ifunc(obj, lockstate) == -1)
2192 resolve_objects_ifunc(Obj_Entry *first, bool bind_now, RtldLockState *lockstate)
2196 for (obj = first; obj != NULL; obj = obj->next) {
2197 if (resolve_object_ifunc(obj, bind_now, lockstate) == -1)
2204 initlist_objects_ifunc(Objlist *list, bool bind_now, RtldLockState *lockstate)
2208 STAILQ_FOREACH(elm, list, link) {
2209 if (resolve_object_ifunc(elm->obj, bind_now, lockstate) == -1)
2216 * Cleanup procedure. It will be called (by the atexit mechanism) just
2217 * before the process exits.
2222 RtldLockState lockstate;
2224 wlock_acquire(rtld_bind_lock, &lockstate);
2226 objlist_call_fini(&list_fini, NULL, &lockstate);
2227 /* No need to remove the items from the list, since we are exiting. */
2228 if (!libmap_disable)
2230 lock_release(rtld_bind_lock, &lockstate);
2234 path_enumerate(const char *path, path_enum_proc callback, void *arg)
2239 path += strspn(path, ":;");
2240 while (*path != '\0') {
2244 len = strcspn(path, ":;");
2245 res = callback(path, len, arg);
2251 path += strspn(path, ":;");
2257 struct try_library_args {
2265 try_library_path(const char *dir, size_t dirlen, void *param)
2267 struct try_library_args *arg;
2270 if (*dir == '/' || trust) {
2273 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
2276 pathname = arg->buffer;
2277 strncpy(pathname, dir, dirlen);
2278 pathname[dirlen] = '/';
2279 strcpy(pathname + dirlen + 1, arg->name);
2281 dbg(" Trying \"%s\"", pathname);
2282 if (access(pathname, F_OK) == 0) { /* We found it */
2283 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
2284 strcpy(pathname, arg->buffer);
2292 search_library_path(const char *name, const char *path)
2295 struct try_library_args arg;
2301 arg.namelen = strlen(name);
2302 arg.buffer = xmalloc(PATH_MAX);
2303 arg.buflen = PATH_MAX;
2305 p = path_enumerate(path, try_library_path, &arg);
2313 dlclose(void *handle)
2316 RtldLockState lockstate;
2318 wlock_acquire(rtld_bind_lock, &lockstate);
2319 root = dlcheck(handle);
2321 lock_release(rtld_bind_lock, &lockstate);
2324 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
2327 /* Unreference the object and its dependencies. */
2328 root->dl_refcount--;
2330 if (root->refcount == 1) {
2332 * The object will be no longer referenced, so we must unload it.
2333 * First, call the fini functions.
2335 objlist_call_fini(&list_fini, root, &lockstate);
2339 /* Finish cleaning up the newly-unreferenced objects. */
2340 GDB_STATE(RT_DELETE,&root->linkmap);
2341 unload_object(root);
2342 GDB_STATE(RT_CONSISTENT,NULL);
2346 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
2347 lock_release(rtld_bind_lock, &lockstate);
2354 char *msg = error_message;
2355 error_message = NULL;
2360 dlopen(const char *name, int mode)
2362 RtldLockState lockstate;
2365 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
2366 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
2367 if (ld_tracing != NULL) {
2368 rlock_acquire(rtld_bind_lock, &lockstate);
2369 if (sigsetjmp(lockstate.env, 0) != 0)
2370 lock_upgrade(rtld_bind_lock, &lockstate);
2371 environ = (char **)*get_program_var_addr("environ", &lockstate);
2372 lock_release(rtld_bind_lock, &lockstate);
2374 lo_flags = RTLD_LO_DLOPEN;
2375 if (mode & RTLD_NODELETE)
2376 lo_flags |= RTLD_LO_NODELETE;
2377 if (mode & RTLD_NOLOAD)
2378 lo_flags |= RTLD_LO_NOLOAD;
2379 if (ld_tracing != NULL)
2380 lo_flags |= RTLD_LO_TRACE;
2382 return (dlopen_object(name, obj_main, lo_flags,
2383 mode & (RTLD_MODEMASK | RTLD_GLOBAL)));
2387 dlopen_cleanup(Obj_Entry *obj)
2392 if (obj->refcount == 0)
2397 dlopen_object(const char *name, Obj_Entry *refobj, int lo_flags, int mode)
2399 Obj_Entry **old_obj_tail;
2402 RtldLockState lockstate;
2405 objlist_init(&initlist);
2407 wlock_acquire(rtld_bind_lock, &lockstate);
2408 GDB_STATE(RT_ADD,NULL);
2410 old_obj_tail = obj_tail;
2416 obj = load_object(name, refobj, lo_flags);
2421 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
2422 objlist_push_tail(&list_global, obj);
2423 if (*old_obj_tail != NULL) { /* We loaded something new. */
2424 assert(*old_obj_tail == obj);
2425 result = load_needed_objects(obj, lo_flags & RTLD_LO_DLOPEN);
2429 result = rtld_verify_versions(&obj->dagmembers);
2430 if (result != -1 && ld_tracing)
2432 if (result == -1 || (relocate_objects(obj, (mode & RTLD_MODEMASK)
2433 == RTLD_NOW, &obj_rtld, &lockstate)) == -1) {
2434 dlopen_cleanup(obj);
2437 /* Make list of init functions to call. */
2438 initlist_add_objects(obj, &obj->next, &initlist);
2443 * Bump the reference counts for objects on this DAG. If
2444 * this is the first dlopen() call for the object that was
2445 * already loaded as a dependency, initialize the dag
2451 if ((lo_flags & RTLD_LO_TRACE) != 0)
2454 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
2455 obj->z_nodelete) && !obj->ref_nodel) {
2456 dbg("obj %s nodelete", obj->path);
2458 obj->z_nodelete = obj->ref_nodel = true;
2462 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
2464 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
2466 map_stacks_exec(&lockstate);
2468 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
2469 &lockstate) == -1) {
2470 objlist_clear(&initlist);
2471 dlopen_cleanup(obj);
2472 lock_release(rtld_bind_lock, &lockstate);
2476 /* Call the init functions. */
2477 objlist_call_init(&initlist, &lockstate);
2478 objlist_clear(&initlist);
2479 lock_release(rtld_bind_lock, &lockstate);
2482 trace_loaded_objects(obj);
2483 lock_release(rtld_bind_lock, &lockstate);
2488 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
2492 const Obj_Entry *obj, *defobj;
2495 RtldLockState lockstate;
2500 symlook_init(&req, name);
2502 req.flags = flags | SYMLOOK_IN_PLT;
2503 req.lockstate = &lockstate;
2505 rlock_acquire(rtld_bind_lock, &lockstate);
2506 if (sigsetjmp(lockstate.env, 0) != 0)
2507 lock_upgrade(rtld_bind_lock, &lockstate);
2508 if (handle == NULL || handle == RTLD_NEXT ||
2509 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
2511 if ((obj = obj_from_addr(retaddr)) == NULL) {
2512 _rtld_error("Cannot determine caller's shared object");
2513 lock_release(rtld_bind_lock, &lockstate);
2516 if (handle == NULL) { /* Just the caller's shared object. */
2517 res = symlook_obj(&req, obj);
2520 defobj = req.defobj_out;
2522 } else if (handle == RTLD_NEXT || /* Objects after caller's */
2523 handle == RTLD_SELF) { /* ... caller included */
2524 if (handle == RTLD_NEXT)
2526 for (; obj != NULL; obj = obj->next) {
2527 res = symlook_obj(&req, obj);
2530 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) {
2532 defobj = req.defobj_out;
2533 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2539 * Search the dynamic linker itself, and possibly resolve the
2540 * symbol from there. This is how the application links to
2541 * dynamic linker services such as dlopen.
2543 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2544 res = symlook_obj(&req, &obj_rtld);
2545 if (res == 0 && is_exported(req.sym_out)) {
2547 defobj = req.defobj_out;
2551 assert(handle == RTLD_DEFAULT);
2552 res = symlook_default(&req, obj);
2554 defobj = req.defobj_out;
2559 if ((obj = dlcheck(handle)) == NULL) {
2560 lock_release(rtld_bind_lock, &lockstate);
2564 donelist_init(&donelist);
2565 if (obj->mainprog) {
2566 /* Handle obtained by dlopen(NULL, ...) implies global scope. */
2567 res = symlook_global(&req, &donelist);
2570 defobj = req.defobj_out;
2573 * Search the dynamic linker itself, and possibly resolve the
2574 * symbol from there. This is how the application links to
2575 * dynamic linker services such as dlopen.
2577 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2578 res = symlook_obj(&req, &obj_rtld);
2581 defobj = req.defobj_out;
2586 /* Search the whole DAG rooted at the given object. */
2587 res = symlook_list(&req, &obj->dagmembers, &donelist);
2590 defobj = req.defobj_out;
2596 lock_release(rtld_bind_lock, &lockstate);
2599 * The value required by the caller is derived from the value
2600 * of the symbol. For the ia64 architecture, we need to
2601 * construct a function descriptor which the caller can use to
2602 * call the function with the right 'gp' value. For other
2603 * architectures and for non-functions, the value is simply
2604 * the relocated value of the symbol.
2606 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
2607 return (make_function_pointer(def, defobj));
2608 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
2609 return (rtld_resolve_ifunc(defobj, def));
2611 return (defobj->relocbase + def->st_value);
2614 _rtld_error("Undefined symbol \"%s\"", name);
2615 lock_release(rtld_bind_lock, &lockstate);
2620 dlsym(void *handle, const char *name)
2622 return do_dlsym(handle, name, __builtin_return_address(0), NULL,
2627 dlfunc(void *handle, const char *name)
2634 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
2640 dlvsym(void *handle, const char *name, const char *version)
2644 ventry.name = version;
2646 ventry.hash = elf_hash(version);
2648 return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
2653 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
2655 const Obj_Entry *obj;
2656 RtldLockState lockstate;
2658 rlock_acquire(rtld_bind_lock, &lockstate);
2659 obj = obj_from_addr(addr);
2661 _rtld_error("No shared object contains address");
2662 lock_release(rtld_bind_lock, &lockstate);
2665 rtld_fill_dl_phdr_info(obj, phdr_info);
2666 lock_release(rtld_bind_lock, &lockstate);
2671 dladdr(const void *addr, Dl_info *info)
2673 const Obj_Entry *obj;
2676 unsigned long symoffset;
2677 RtldLockState lockstate;
2679 rlock_acquire(rtld_bind_lock, &lockstate);
2680 obj = obj_from_addr(addr);
2682 _rtld_error("No shared object contains address");
2683 lock_release(rtld_bind_lock, &lockstate);
2686 info->dli_fname = obj->path;
2687 info->dli_fbase = obj->mapbase;
2688 info->dli_saddr = NULL;
2689 info->dli_sname = NULL;
2692 * Walk the symbol list looking for the symbol whose address is
2693 * closest to the address sent in.
2695 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
2696 def = obj->symtab + symoffset;
2699 * For skip the symbol if st_shndx is either SHN_UNDEF or
2702 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
2706 * If the symbol is greater than the specified address, or if it
2707 * is further away from addr than the current nearest symbol,
2710 symbol_addr = obj->relocbase + def->st_value;
2711 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
2714 /* Update our idea of the nearest symbol. */
2715 info->dli_sname = obj->strtab + def->st_name;
2716 info->dli_saddr = symbol_addr;
2719 if (info->dli_saddr == addr)
2722 lock_release(rtld_bind_lock, &lockstate);
2727 dlinfo(void *handle, int request, void *p)
2729 const Obj_Entry *obj;
2730 RtldLockState lockstate;
2733 rlock_acquire(rtld_bind_lock, &lockstate);
2735 if (handle == NULL || handle == RTLD_SELF) {
2738 retaddr = __builtin_return_address(0); /* __GNUC__ only */
2739 if ((obj = obj_from_addr(retaddr)) == NULL)
2740 _rtld_error("Cannot determine caller's shared object");
2742 obj = dlcheck(handle);
2745 lock_release(rtld_bind_lock, &lockstate);
2751 case RTLD_DI_LINKMAP:
2752 *((struct link_map const **)p) = &obj->linkmap;
2754 case RTLD_DI_ORIGIN:
2755 error = rtld_dirname(obj->path, p);
2758 case RTLD_DI_SERINFOSIZE:
2759 case RTLD_DI_SERINFO:
2760 error = do_search_info(obj, request, (struct dl_serinfo *)p);
2764 _rtld_error("Invalid request %d passed to dlinfo()", request);
2768 lock_release(rtld_bind_lock, &lockstate);
2774 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
2777 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
2778 phdr_info->dlpi_name = STAILQ_FIRST(&obj->names) ?
2779 STAILQ_FIRST(&obj->names)->name : obj->path;
2780 phdr_info->dlpi_phdr = obj->phdr;
2781 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
2782 phdr_info->dlpi_tls_modid = obj->tlsindex;
2783 phdr_info->dlpi_tls_data = obj->tlsinit;
2784 phdr_info->dlpi_adds = obj_loads;
2785 phdr_info->dlpi_subs = obj_loads - obj_count;
2789 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
2791 struct dl_phdr_info phdr_info;
2792 const Obj_Entry *obj;
2793 RtldLockState bind_lockstate, phdr_lockstate;
2796 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
2797 rlock_acquire(rtld_bind_lock, &bind_lockstate);
2801 for (obj = obj_list; obj != NULL; obj = obj->next) {
2802 rtld_fill_dl_phdr_info(obj, &phdr_info);
2803 if ((error = callback(&phdr_info, sizeof phdr_info, param)) != 0)
2807 lock_release(rtld_bind_lock, &bind_lockstate);
2808 lock_release(rtld_phdr_lock, &phdr_lockstate);
2813 struct fill_search_info_args {
2816 Dl_serinfo *serinfo;
2817 Dl_serpath *serpath;
2822 fill_search_info(const char *dir, size_t dirlen, void *param)
2824 struct fill_search_info_args *arg;
2828 if (arg->request == RTLD_DI_SERINFOSIZE) {
2829 arg->serinfo->dls_cnt ++;
2830 arg->serinfo->dls_size += sizeof(Dl_serpath) + dirlen + 1;
2832 struct dl_serpath *s_entry;
2834 s_entry = arg->serpath;
2835 s_entry->dls_name = arg->strspace;
2836 s_entry->dls_flags = arg->flags;
2838 strncpy(arg->strspace, dir, dirlen);
2839 arg->strspace[dirlen] = '\0';
2841 arg->strspace += dirlen + 1;
2849 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
2851 struct dl_serinfo _info;
2852 struct fill_search_info_args args;
2854 args.request = RTLD_DI_SERINFOSIZE;
2855 args.serinfo = &_info;
2857 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2860 path_enumerate(ld_library_path, fill_search_info, &args);
2861 path_enumerate(obj->rpath, fill_search_info, &args);
2862 path_enumerate(gethints(), fill_search_info, &args);
2863 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
2866 if (request == RTLD_DI_SERINFOSIZE) {
2867 info->dls_size = _info.dls_size;
2868 info->dls_cnt = _info.dls_cnt;
2872 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
2873 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
2877 args.request = RTLD_DI_SERINFO;
2878 args.serinfo = info;
2879 args.serpath = &info->dls_serpath[0];
2880 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
2882 args.flags = LA_SER_LIBPATH;
2883 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
2886 args.flags = LA_SER_RUNPATH;
2887 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
2890 args.flags = LA_SER_CONFIG;
2891 if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
2894 args.flags = LA_SER_DEFAULT;
2895 if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
2901 rtld_dirname(const char *path, char *bname)
2905 /* Empty or NULL string gets treated as "." */
2906 if (path == NULL || *path == '\0') {
2912 /* Strip trailing slashes */
2913 endp = path + strlen(path) - 1;
2914 while (endp > path && *endp == '/')
2917 /* Find the start of the dir */
2918 while (endp > path && *endp != '/')
2921 /* Either the dir is "/" or there are no slashes */
2923 bname[0] = *endp == '/' ? '/' : '.';
2929 } while (endp > path && *endp == '/');
2932 if (endp - path + 2 > PATH_MAX)
2934 _rtld_error("Filename is too long: %s", path);
2938 strncpy(bname, path, endp - path + 1);
2939 bname[endp - path + 1] = '\0';
2944 rtld_dirname_abs(const char *path, char *base)
2946 char base_rel[PATH_MAX];
2948 if (rtld_dirname(path, base) == -1)
2952 if (getcwd(base_rel, sizeof(base_rel)) == NULL ||
2953 strlcat(base_rel, "/", sizeof(base_rel)) >= sizeof(base_rel) ||
2954 strlcat(base_rel, base, sizeof(base_rel)) >= sizeof(base_rel))
2956 strcpy(base, base_rel);
2961 linkmap_add(Obj_Entry *obj)
2963 struct link_map *l = &obj->linkmap;
2964 struct link_map *prev;
2966 obj->linkmap.l_name = obj->path;
2967 obj->linkmap.l_addr = obj->mapbase;
2968 obj->linkmap.l_ld = obj->dynamic;
2970 /* GDB needs load offset on MIPS to use the symbols */
2971 obj->linkmap.l_offs = obj->relocbase;
2974 if (r_debug.r_map == NULL) {
2980 * Scan to the end of the list, but not past the entry for the
2981 * dynamic linker, which we want to keep at the very end.
2983 for (prev = r_debug.r_map;
2984 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
2985 prev = prev->l_next)
2988 /* Link in the new entry. */
2990 l->l_next = prev->l_next;
2991 if (l->l_next != NULL)
2992 l->l_next->l_prev = l;
2997 linkmap_delete(Obj_Entry *obj)
2999 struct link_map *l = &obj->linkmap;
3001 if (l->l_prev == NULL) {
3002 if ((r_debug.r_map = l->l_next) != NULL)
3003 l->l_next->l_prev = NULL;
3007 if ((l->l_prev->l_next = l->l_next) != NULL)
3008 l->l_next->l_prev = l->l_prev;
3012 * Function for the debugger to set a breakpoint on to gain control.
3014 * The two parameters allow the debugger to easily find and determine
3015 * what the runtime loader is doing and to whom it is doing it.
3017 * When the loadhook trap is hit (r_debug_state, set at program
3018 * initialization), the arguments can be found on the stack:
3020 * +8 struct link_map *m
3021 * +4 struct r_debug *rd
3025 r_debug_state(struct r_debug* rd, struct link_map *m)
3028 * The following is a hack to force the compiler to emit calls to
3029 * this function, even when optimizing. If the function is empty,
3030 * the compiler is not obliged to emit any code for calls to it,
3031 * even when marked __noinline. However, gdb depends on those
3034 __asm __volatile("" : : : "memory");
3038 * Get address of the pointer variable in the main program.
3039 * Prefer non-weak symbol over the weak one.
3041 static const void **
3042 get_program_var_addr(const char *name, RtldLockState *lockstate)
3047 symlook_init(&req, name);
3048 req.lockstate = lockstate;
3049 donelist_init(&donelist);
3050 if (symlook_global(&req, &donelist) != 0)
3052 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
3053 return ((const void **)make_function_pointer(req.sym_out,
3055 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
3056 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
3058 return ((const void **)(req.defobj_out->relocbase +
3059 req.sym_out->st_value));
3063 * Set a pointer variable in the main program to the given value. This
3064 * is used to set key variables such as "environ" before any of the
3065 * init functions are called.
3068 set_program_var(const char *name, const void *value)
3072 if ((addr = get_program_var_addr(name, NULL)) != NULL) {
3073 dbg("\"%s\": *%p <-- %p", name, addr, value);
3079 * Search the global objects, including dependencies and main object,
3080 * for the given symbol.
3083 symlook_global(SymLook *req, DoneList *donelist)
3086 const Objlist_Entry *elm;
3089 symlook_init_from_req(&req1, req);
3091 /* Search all objects loaded at program start up. */
3092 if (req->defobj_out == NULL ||
3093 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3094 res = symlook_list(&req1, &list_main, donelist);
3095 if (res == 0 && (req->defobj_out == NULL ||
3096 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3097 req->sym_out = req1.sym_out;
3098 req->defobj_out = req1.defobj_out;
3099 assert(req->defobj_out != NULL);
3103 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
3104 STAILQ_FOREACH(elm, &list_global, link) {
3105 if (req->defobj_out != NULL &&
3106 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3108 res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
3109 if (res == 0 && (req->defobj_out == NULL ||
3110 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3111 req->sym_out = req1.sym_out;
3112 req->defobj_out = req1.defobj_out;
3113 assert(req->defobj_out != NULL);
3117 return (req->sym_out != NULL ? 0 : ESRCH);
3121 * This is a special version of getenv which is far more efficient
3122 * at finding LD_ environment vars.
3126 _getenv_ld(const char *id)
3130 int idlen = strlen(id);
3132 if (ld_index == LD_ARY_CACHE)
3134 if (ld_index == 0) {
3135 for (i = j = 0; (envp = environ[i]) != NULL && j < LD_ARY_CACHE; ++i) {
3136 if (envp[0] == 'L' && envp[1] == 'D' && envp[2] == '_')
3143 for (i = ld_index - 1; i >= 0; --i) {
3144 if (strncmp(ld_ary[i], id, idlen) == 0 && ld_ary[i][idlen] == '=')
3145 return(ld_ary[i] + idlen + 1);
3151 * Given a symbol name in a referencing object, find the corresponding
3152 * definition of the symbol. Returns a pointer to the symbol, or NULL if
3153 * no definition was found. Returns a pointer to the Obj_Entry of the
3154 * defining object via the reference parameter DEFOBJ_OUT.
3157 symlook_default(SymLook *req, const Obj_Entry *refobj)
3160 const Objlist_Entry *elm;
3164 donelist_init(&donelist);
3165 symlook_init_from_req(&req1, req);
3167 /* Look first in the referencing object if linked symbolically. */
3168 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
3169 res = symlook_obj(&req1, refobj);
3171 req->sym_out = req1.sym_out;
3172 req->defobj_out = req1.defobj_out;
3173 assert(req->defobj_out != NULL);
3177 symlook_global(req, &donelist);
3179 /* Search all dlopened DAGs containing the referencing object. */
3180 STAILQ_FOREACH(elm, &refobj->dldags, link) {
3181 if (req->sym_out != NULL &&
3182 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3184 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
3185 if (res == 0 && (req->sym_out == NULL ||
3186 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3187 req->sym_out = req1.sym_out;
3188 req->defobj_out = req1.defobj_out;
3189 assert(req->defobj_out != NULL);
3194 * Search the dynamic linker itself, and possibly resolve the
3195 * symbol from there. This is how the application links to
3196 * dynamic linker services such as dlopen. Only the values listed
3197 * in the "exports" array can be resolved from the dynamic linker.
3199 if (req->sym_out == NULL ||
3200 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3201 res = symlook_obj(&req1, &obj_rtld);
3202 if (res == 0 && is_exported(req1.sym_out)) {
3203 req->sym_out = req1.sym_out;
3204 req->defobj_out = req1.defobj_out;
3205 assert(req->defobj_out != NULL);
3209 return (req->sym_out != NULL ? 0 : ESRCH);
3213 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
3216 const Obj_Entry *defobj;
3217 const Objlist_Entry *elm;
3223 STAILQ_FOREACH(elm, objlist, link) {
3224 if (donelist_check(dlp, elm->obj))
3226 symlook_init_from_req(&req1, req);
3227 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
3228 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3230 defobj = req1.defobj_out;
3231 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3238 req->defobj_out = defobj;
3245 * Search the chain of DAGS cointed to by the given Needed_Entry
3246 * for a symbol of the given name. Each DAG is scanned completely
3247 * before advancing to the next one. Returns a pointer to the symbol,
3248 * or NULL if no definition was found.
3251 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
3254 const Needed_Entry *n;
3255 const Obj_Entry *defobj;
3261 symlook_init_from_req(&req1, req);
3262 for (n = needed; n != NULL; n = n->next) {
3263 if (n->obj == NULL ||
3264 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
3266 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3268 defobj = req1.defobj_out;
3269 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3275 req->defobj_out = defobj;
3282 * Search the symbol table of a single shared object for a symbol of
3283 * the given name and version, if requested. Returns a pointer to the
3284 * symbol, or NULL if no definition was found. If the object is
3285 * filter, return filtered symbol from filtee.
3287 * The symbol's hash value is passed in for efficiency reasons; that
3288 * eliminates many recomputations of the hash value.
3291 symlook_obj(SymLook *req, const Obj_Entry *obj)
3297 mres = symlook_obj1(req, obj);
3299 if (obj->needed_filtees != NULL) {
3300 load_filtees(__DECONST(Obj_Entry *, obj), 0, req->lockstate);
3301 donelist_init(&donelist);
3302 symlook_init_from_req(&req1, req);
3303 res = symlook_needed(&req1, obj->needed_filtees, &donelist);
3305 req->sym_out = req1.sym_out;
3306 req->defobj_out = req1.defobj_out;
3310 if (obj->needed_aux_filtees != NULL) {
3311 load_filtees(__DECONST(Obj_Entry *, obj), 0, req->lockstate);
3312 donelist_init(&donelist);
3313 symlook_init_from_req(&req1, req);
3314 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
3316 req->sym_out = req1.sym_out;
3317 req->defobj_out = req1.defobj_out;
3326 symlook_obj1(SymLook *req, const Obj_Entry *obj)
3328 unsigned long symnum;
3329 const Elf_Sym *vsymp;
3333 if (obj->buckets == NULL)
3338 symnum = obj->buckets[req->hash % obj->nbuckets];
3340 for (; symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
3341 const Elf_Sym *symp;
3344 if (symnum >= obj->nchains)
3345 return (ESRCH); /* Bad object */
3347 symp = obj->symtab + symnum;
3348 strp = obj->strtab + symp->st_name;
3350 switch (ELF_ST_TYPE(symp->st_info)) {
3355 if (symp->st_value == 0)
3359 if (symp->st_shndx != SHN_UNDEF)
3361 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
3362 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
3368 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
3371 if (req->ventry == NULL) {
3372 if (obj->versyms != NULL) {
3373 verndx = VER_NDX(obj->versyms[symnum]);
3374 if (verndx > obj->vernum) {
3375 _rtld_error("%s: symbol %s references wrong version %d",
3376 obj->path, obj->strtab + symnum, verndx);
3380 * If we are not called from dlsym (i.e. this is a normal
3381 * relocation from unversioned binary), accept the symbol
3382 * immediately if it happens to have first version after
3383 * this shared object became versioned. Otherwise, if
3384 * symbol is versioned and not hidden, remember it. If it
3385 * is the only symbol with this name exported by the
3386 * shared object, it will be returned as a match at the
3387 * end of the function. If symbol is global (verndx < 2)
3388 * accept it unconditionally.
3390 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
3391 verndx == VER_NDX_GIVEN) {
3392 req->sym_out = symp;
3393 req->defobj_out = obj;
3396 else if (verndx >= VER_NDX_GIVEN) {
3397 if ((obj->versyms[symnum] & VER_NDX_HIDDEN) == 0) {
3405 req->sym_out = symp;
3406 req->defobj_out = obj;
3409 if (obj->versyms == NULL) {
3410 if (object_match_name(obj, req->ventry->name)) {
3411 _rtld_error("%s: object %s should provide version %s for "
3412 "symbol %s", obj_rtld.path, obj->path,
3413 req->ventry->name, obj->strtab + symnum);
3417 verndx = VER_NDX(obj->versyms[symnum]);
3418 if (verndx > obj->vernum) {
3419 _rtld_error("%s: symbol %s references wrong version %d",
3420 obj->path, obj->strtab + symnum, verndx);
3423 if (obj->vertab[verndx].hash != req->ventry->hash ||
3424 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
3426 * Version does not match. Look if this is a global symbol
3427 * and if it is not hidden. If global symbol (verndx < 2)
3428 * is available, use it. Do not return symbol if we are
3429 * called by dlvsym, because dlvsym looks for a specific
3430 * version and default one is not what dlvsym wants.
3432 if ((req->flags & SYMLOOK_DLSYM) ||
3433 (obj->versyms[symnum] & VER_NDX_HIDDEN) ||
3434 (verndx >= VER_NDX_GIVEN))
3438 req->sym_out = symp;
3439 req->defobj_out = obj;
3444 req->sym_out = vsymp;
3445 req->defobj_out = obj;
3452 trace_loaded_objects(Obj_Entry *obj)
3454 const char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
3457 if ((main_local = _getenv_ld("LD_TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
3460 if ((fmt1 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT1")) == NULL)
3461 fmt1 = "\t%o => %p (%x)\n";
3463 if ((fmt2 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT2")) == NULL)
3464 fmt2 = "\t%o (%x)\n";
3466 list_containers = _getenv_ld("LD_TRACE_LOADED_OBJECTS_ALL");
3468 for (; obj; obj = obj->next) {
3469 Needed_Entry *needed;
3473 if (list_containers && obj->needed != NULL)
3474 rtld_printf("%s:\n", obj->path);
3475 for (needed = obj->needed; needed; needed = needed->next) {
3476 if (needed->obj != NULL) {
3477 if (needed->obj->traced && !list_containers)
3479 needed->obj->traced = true;
3480 path = needed->obj->path;
3484 name = (char *)obj->strtab + needed->name;
3485 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
3487 fmt = is_lib ? fmt1 : fmt2;
3488 while ((c = *fmt++) != '\0') {
3514 rtld_putstr(main_local);
3517 rtld_putstr(obj_main->path);
3526 rtld_printf("%p", needed->obj ? needed->obj->mapbase :
3539 * Unload a dlopened object and its dependencies from memory and from
3540 * our data structures. It is assumed that the DAG rooted in the
3541 * object has already been unreferenced, and that the object has a
3542 * reference count of 0.
3545 unload_object(Obj_Entry *root)
3550 assert(root->refcount == 0);
3553 * Pass over the DAG removing unreferenced objects from
3554 * appropriate lists.
3556 unlink_object(root);
3558 /* Unmap all objects that are no longer referenced. */
3559 linkp = &obj_list->next;
3560 while ((obj = *linkp) != NULL) {
3561 if (obj->refcount == 0) {
3562 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
3564 dbg("unloading \"%s\"", obj->path);
3565 unload_filtees(root);
3566 munmap(obj->mapbase, obj->mapsize);
3567 linkmap_delete(obj);
3578 unlink_object(Obj_Entry *root)
3582 if (root->refcount == 0) {
3583 /* Remove the object from the RTLD_GLOBAL list. */
3584 objlist_remove(&list_global, root);
3586 /* Remove the object from all objects' DAG lists. */
3587 STAILQ_FOREACH(elm, &root->dagmembers, link) {
3588 objlist_remove(&elm->obj->dldags, root);
3589 if (elm->obj != root)
3590 unlink_object(elm->obj);
3596 ref_dag(Obj_Entry *root)
3600 assert(root->dag_inited);
3601 STAILQ_FOREACH(elm, &root->dagmembers, link)
3602 elm->obj->refcount++;
3606 unref_dag(Obj_Entry *root)
3610 assert(root->dag_inited);
3611 STAILQ_FOREACH(elm, &root->dagmembers, link)
3612 elm->obj->refcount--;
3616 * Common code for MD __tls_get_addr().
3619 tls_get_addr_common(Elf_Addr** dtvp, int index, size_t offset)
3621 Elf_Addr* dtv = *dtvp;
3622 RtldLockState lockstate;
3624 /* Check dtv generation in case new modules have arrived */
3625 if (dtv[0] != tls_dtv_generation) {
3629 wlock_acquire(rtld_bind_lock, &lockstate);
3630 newdtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
3632 if (to_copy > tls_max_index)
3633 to_copy = tls_max_index;
3634 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
3635 newdtv[0] = tls_dtv_generation;
3636 newdtv[1] = tls_max_index;
3638 lock_release(rtld_bind_lock, &lockstate);
3639 dtv = *dtvp = newdtv;
3642 /* Dynamically allocate module TLS if necessary */
3643 if (!dtv[index + 1]) {
3644 /* Signal safe, wlock will block out signals. */
3645 wlock_acquire(rtld_bind_lock, &lockstate);
3646 if (!dtv[index + 1])
3647 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
3648 lock_release(rtld_bind_lock, &lockstate);
3650 return (void*) (dtv[index + 1] + offset);
3653 #if defined(RTLD_STATIC_TLS_VARIANT_II)
3656 * Allocate the static TLS area. Return a pointer to the TCB. The
3657 * static area is based on negative offsets relative to the tcb.
3659 * The TCB contains an errno pointer for the system call layer, but because
3660 * we are the RTLD we really have no idea how the caller was compiled so
3661 * the information has to be passed in. errno can either be:
3663 * type 0 errno is a simple non-TLS global pointer.
3664 * (special case for e.g. libc_rtld)
3665 * type 1 errno accessed by GOT entry (dynamically linked programs)
3666 * type 2 errno accessed by %gs:OFFSET (statically linked programs)
3669 allocate_tls(Obj_Entry *objs)
3674 struct tls_tcb *tcb;
3679 * Allocate the new TCB. static TLS storage is placed just before the
3680 * TCB to support the %gs:OFFSET (negative offset) model.
3682 data_size = (tls_static_space + RTLD_STATIC_TLS_ALIGN_MASK) &
3683 ~RTLD_STATIC_TLS_ALIGN_MASK;
3684 tcb = malloc(data_size + sizeof(*tcb));
3685 tcb = (void *)((char *)tcb + data_size); /* actual tcb location */
3687 dtv_size = (tls_max_index + 2) * sizeof(Elf_Addr);
3688 dtv = malloc(dtv_size);
3689 bzero(dtv, dtv_size);
3691 #ifdef RTLD_TCB_HAS_SELF_POINTER
3692 tcb->tcb_self = tcb;
3695 tcb->tcb_pthread = NULL;
3697 dtv[0] = tls_dtv_generation;
3698 dtv[1] = tls_max_index;
3700 for (obj = objs; obj; obj = obj->next) {
3701 if (obj->tlsoffset) {
3702 addr = (Elf_Addr)tcb - obj->tlsoffset;
3703 memset((void *)(addr + obj->tlsinitsize),
3704 0, obj->tlssize - obj->tlsinitsize);
3706 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
3707 dtv[obj->tlsindex + 1] = addr;
3714 free_tls(struct tls_tcb *tcb)
3718 Elf_Addr tls_start, tls_end;
3721 data_size = (tls_static_space + RTLD_STATIC_TLS_ALIGN_MASK) &
3722 ~RTLD_STATIC_TLS_ALIGN_MASK;
3726 tls_end = (Elf_Addr)tcb;
3727 tls_start = (Elf_Addr)tcb - data_size;
3728 for (i = 0; i < dtv_size; i++) {
3729 if (dtv[i+2] != 0 && (dtv[i+2] < tls_start || dtv[i+2] > tls_end)) {
3730 free((void *)dtv[i+2]);
3734 free((void*) tls_start);
3738 #error "Unsupported TLS layout"
3742 * Allocate TLS block for module with given index.
3745 allocate_module_tls(int index)
3750 for (obj = obj_list; obj; obj = obj->next) {
3751 if (obj->tlsindex == index)
3755 _rtld_error("Can't find module with TLS index %d", index);
3759 p = malloc(obj->tlssize);
3761 _rtld_error("Cannot allocate TLS block for index %d", index);
3764 memcpy(p, obj->tlsinit, obj->tlsinitsize);
3765 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
3771 allocate_tls_offset(Obj_Entry *obj)
3778 if (obj->tlssize == 0) {
3779 obj->tls_done = true;
3783 if (obj->tlsindex == 1)
3784 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
3786 off = calculate_tls_offset(tls_last_offset, tls_last_size,
3787 obj->tlssize, obj->tlsalign);
3790 * If we have already fixed the size of the static TLS block, we
3791 * must stay within that size. When allocating the static TLS, we
3792 * leave a small amount of space spare to be used for dynamically
3793 * loading modules which use static TLS.
3795 if (tls_static_space) {
3796 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
3800 tls_last_offset = obj->tlsoffset = off;
3801 tls_last_size = obj->tlssize;
3802 obj->tls_done = true;
3808 free_tls_offset(Obj_Entry *obj)
3810 #ifdef RTLD_STATIC_TLS_VARIANT_II
3812 * If we were the last thing to allocate out of the static TLS
3813 * block, we give our space back to the 'allocator'. This is a
3814 * simplistic workaround to allow libGL.so.1 to be loaded and
3815 * unloaded multiple times. We only handle the Variant II
3816 * mechanism for now - this really needs a proper allocator.
3818 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
3819 == calculate_tls_end(tls_last_offset, tls_last_size)) {
3820 tls_last_offset -= obj->tlssize;
3827 _rtld_allocate_tls(void)
3829 struct tls_tcb *new_tcb;
3830 RtldLockState lockstate;
3832 wlock_acquire(rtld_bind_lock, &lockstate);
3833 new_tcb = allocate_tls(obj_list);
3834 lock_release(rtld_bind_lock, &lockstate);
3839 _rtld_free_tls(struct tls_tcb *tcb)
3841 RtldLockState lockstate;
3843 wlock_acquire(rtld_bind_lock, &lockstate);
3845 lock_release(rtld_bind_lock, &lockstate);
3849 object_add_name(Obj_Entry *obj, const char *name)
3855 entry = malloc(sizeof(Name_Entry) + len);
3857 if (entry != NULL) {
3858 strcpy(entry->name, name);
3859 STAILQ_INSERT_TAIL(&obj->names, entry, link);
3864 object_match_name(const Obj_Entry *obj, const char *name)
3868 STAILQ_FOREACH(entry, &obj->names, link) {
3869 if (strcmp(name, entry->name) == 0)
3876 locate_dependency(const Obj_Entry *obj, const char *name)
3878 const Objlist_Entry *entry;
3879 const Needed_Entry *needed;
3881 STAILQ_FOREACH(entry, &list_main, link) {
3882 if (object_match_name(entry->obj, name))
3886 for (needed = obj->needed; needed != NULL; needed = needed->next) {
3887 if (strcmp(obj->strtab + needed->name, name) == 0 ||
3888 (needed->obj != NULL && object_match_name(needed->obj, name))) {
3890 * If there is DT_NEEDED for the name we are looking for,
3891 * we are all set. Note that object might not be found if
3892 * dependency was not loaded yet, so the function can
3893 * return NULL here. This is expected and handled
3894 * properly by the caller.
3896 return (needed->obj);
3899 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
3905 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
3906 const Elf_Vernaux *vna)
3908 const Elf_Verdef *vd;
3909 const char *vername;
3911 vername = refobj->strtab + vna->vna_name;
3912 vd = depobj->verdef;
3914 _rtld_error("%s: version %s required by %s not defined",
3915 depobj->path, vername, refobj->path);
3919 if (vd->vd_version != VER_DEF_CURRENT) {
3920 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
3921 depobj->path, vd->vd_version);
3924 if (vna->vna_hash == vd->vd_hash) {
3925 const Elf_Verdaux *aux = (const Elf_Verdaux *)
3926 ((char *)vd + vd->vd_aux);
3927 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
3930 if (vd->vd_next == 0)
3932 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3934 if (vna->vna_flags & VER_FLG_WEAK)
3936 _rtld_error("%s: version %s required by %s not found",
3937 depobj->path, vername, refobj->path);
3942 rtld_verify_object_versions(Obj_Entry *obj)
3944 const Elf_Verneed *vn;
3945 const Elf_Verdef *vd;
3946 const Elf_Verdaux *vda;
3947 const Elf_Vernaux *vna;
3948 const Obj_Entry *depobj;
3949 int maxvernum, vernum;
3953 * Walk over defined and required version records and figure out
3954 * max index used by any of them. Do very basic sanity checking
3958 while (vn != NULL) {
3959 if (vn->vn_version != VER_NEED_CURRENT) {
3960 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
3961 obj->path, vn->vn_version);
3964 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
3966 vernum = VER_NEED_IDX(vna->vna_other);
3967 if (vernum > maxvernum)
3969 if (vna->vna_next == 0)
3971 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
3973 if (vn->vn_next == 0)
3975 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
3979 while (vd != NULL) {
3980 if (vd->vd_version != VER_DEF_CURRENT) {
3981 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
3982 obj->path, vd->vd_version);
3985 vernum = VER_DEF_IDX(vd->vd_ndx);
3986 if (vernum > maxvernum)
3988 if (vd->vd_next == 0)
3990 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3997 * Store version information in array indexable by version index.
3998 * Verify that object version requirements are satisfied along the
4001 obj->vernum = maxvernum + 1;
4002 obj->vertab = calloc(obj->vernum, sizeof(Ver_Entry));
4005 while (vd != NULL) {
4006 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
4007 vernum = VER_DEF_IDX(vd->vd_ndx);
4008 assert(vernum <= maxvernum);
4009 vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
4010 obj->vertab[vernum].hash = vd->vd_hash;
4011 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
4012 obj->vertab[vernum].file = NULL;
4013 obj->vertab[vernum].flags = 0;
4015 if (vd->vd_next == 0)
4017 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4021 while (vn != NULL) {
4022 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
4025 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4027 if (check_object_provided_version(obj, depobj, vna))
4029 vernum = VER_NEED_IDX(vna->vna_other);
4030 assert(vernum <= maxvernum);
4031 obj->vertab[vernum].hash = vna->vna_hash;
4032 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
4033 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
4034 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
4035 VER_INFO_HIDDEN : 0;
4036 if (vna->vna_next == 0)
4038 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4040 if (vn->vn_next == 0)
4042 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4048 rtld_verify_versions(const Objlist *objlist)
4050 Objlist_Entry *entry;
4054 STAILQ_FOREACH(entry, objlist, link) {
4056 * Skip dummy objects or objects that have their version requirements
4059 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
4061 if (rtld_verify_object_versions(entry->obj) == -1) {
4063 if (ld_tracing == NULL)
4067 if (rc == 0 || ld_tracing != NULL)
4068 rc = rtld_verify_object_versions(&obj_rtld);
4073 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
4078 vernum = VER_NDX(obj->versyms[symnum]);
4079 if (vernum >= obj->vernum) {
4080 _rtld_error("%s: symbol %s has wrong verneed value %d",
4081 obj->path, obj->strtab + symnum, vernum);
4082 } else if (obj->vertab[vernum].hash != 0) {
4083 return &obj->vertab[vernum];
4090 _rtld_get_stack_prot(void)
4093 return (stack_prot);
4097 map_stacks_exec(RtldLockState *lockstate)
4101 * Stack protection must be implemented in the kernel before the dynamic
4102 * linker can handle PT_GNU_STACK sections.
4103 * The following is the FreeBSD implementation of map_stacks_exec()
4104 * void (*thr_map_stacks_exec)(void);
4106 * if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
4108 * thr_map_stacks_exec = (void (*)(void))(uintptr_t)
4109 * get_program_var_addr("__pthread_map_stacks_exec", lockstate);
4110 * if (thr_map_stacks_exec != NULL) {
4111 * stack_prot |= PROT_EXEC;
4112 * thr_map_stacks_exec();
4118 symlook_init(SymLook *dst, const char *name)
4121 bzero(dst, sizeof(*dst));
4123 dst->hash = elf_hash(name);
4127 symlook_init_from_req(SymLook *dst, const SymLook *src)
4130 dst->name = src->name;
4131 dst->hash = src->hash;
4132 dst->ventry = src->ventry;
4133 dst->flags = src->flags;
4134 dst->defobj_out = NULL;
4135 dst->sym_out = NULL;
4136 dst->lockstate = src->lockstate;
4139 #ifdef ENABLE_OSRELDATE
4141 * Overrides for libc_pic-provided functions.
4145 __getosreldate(void)
4155 oid[1] = KERN_OSRELDATE;
4157 len = sizeof(osrel);
4158 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
4159 if (error == 0 && osrel > 0 && len == sizeof(osrel))
4166 * No unresolved symbols for rtld.
4169 __pthread_cxa_finalize(struct dl_phdr_info *a)