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_dag1(Obj_Entry *, Obj_Entry *, DoneList *);
98 static void init_rtld(caddr_t, Elf_Auxinfo **);
99 static void initlist_add_neededs(Needed_Entry *, Objlist *);
100 static void initlist_add_objects(Obj_Entry *, Obj_Entry **, Objlist *);
101 static bool is_exported(const Elf_Sym *);
102 static void linkmap_add(Obj_Entry *);
103 static void linkmap_delete(Obj_Entry *);
104 static void load_filtees(Obj_Entry *, int flags, RtldLockState *);
105 static void unload_filtees(Obj_Entry *);
106 static int load_needed_objects(Obj_Entry *, int);
107 static int load_preload_objects(void);
108 static Obj_Entry *load_object(const char *, const Obj_Entry *, int);
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 rtld_dirname(const char *, char *);
121 static int rtld_dirname_abs(const char *, char *);
122 static void rtld_exit(void);
123 static char *search_library_path(const char *, const char *);
124 static const void **get_program_var_addr(const char *);
125 static void set_program_var(const char *, const void *);
126 static int symlook_default(SymLook *, const Obj_Entry *refobj);
127 static void symlook_init_from_req(SymLook *, const SymLook *);
128 static int symlook_list(SymLook *, const Objlist *, DoneList *);
129 static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *);
130 static int symlook_obj1(SymLook *, const Obj_Entry *);
131 static void trace_loaded_objects(Obj_Entry *);
132 static void unlink_object(Obj_Entry *);
133 static void unload_object(Obj_Entry *);
134 static void unref_dag(Obj_Entry *);
135 static void ref_dag(Obj_Entry *);
136 static int origin_subst_one(char **, const char *, const char *,
137 const char *, char *);
138 static char *origin_subst(const char *, const char *);
139 static int rtld_verify_versions(const Objlist *);
140 static int rtld_verify_object_versions(Obj_Entry *);
141 static void object_add_name(Obj_Entry *, const char *);
142 static int object_match_name(const Obj_Entry *, const char *);
143 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
144 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
145 struct dl_phdr_info *phdr_info);
147 void r_debug_state(struct r_debug *, struct link_map *) __noinline;
152 static char *error_message; /* Message for dlerror(), or NULL */
153 struct r_debug r_debug; /* for GDB; */
154 static bool libmap_disable; /* Disable libmap */
155 static bool ld_loadfltr; /* Immediate filters processing */
156 static char *libmap_override; /* Maps to use in addition to libmap.conf */
157 static bool trust; /* False for setuid and setgid programs */
158 static bool dangerous_ld_env; /* True if environment variables have been
159 used to affect the libraries loaded */
160 static const char *ld_bind_now; /* Environment variable for immediate binding */
161 static const char *ld_debug; /* Environment variable for debugging */
162 static const char *ld_library_path; /* Environment variable for search path */
163 static char *ld_preload; /* Environment variable for libraries to
165 static const char *ld_elf_hints_path; /* Environment variable for alternative hints path */
166 static const char *ld_tracing; /* Called from ldd to print libs */
167 static const char *ld_utrace; /* Use utrace() to log events. */
168 static int (*rtld_functrace)( /* Optional function call tracing hook */
169 const char *caller_obj,
170 const char *callee_obj,
171 const char *callee_func,
173 static const Obj_Entry *rtld_functrace_obj; /* Object thereof */
174 static Obj_Entry *obj_list; /* Head of linked list of shared objects */
175 static Obj_Entry **obj_tail; /* Link field of last object in list */
176 static Obj_Entry **preload_tail;
177 static Obj_Entry *obj_main; /* The main program shared object */
178 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
179 static unsigned int obj_count; /* Number of objects in obj_list */
180 static unsigned int obj_loads; /* Number of objects in obj_list */
182 static int ld_resident; /* Non-zero if resident */
183 static const char *ld_ary[LD_ARY_CACHE];
185 static Objlist initlist;
187 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
188 STAILQ_HEAD_INITIALIZER(list_global);
189 static Objlist list_main = /* Objects loaded at program startup */
190 STAILQ_HEAD_INITIALIZER(list_main);
191 static Objlist list_fini = /* Objects needing fini() calls */
192 STAILQ_HEAD_INITIALIZER(list_fini);
194 static Elf_Sym sym_zero; /* For resolving undefined weak refs. */
196 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
198 extern Elf_Dyn _DYNAMIC;
199 #pragma weak _DYNAMIC
200 #ifndef RTLD_IS_DYNAMIC
201 #define RTLD_IS_DYNAMIC() (&_DYNAMIC != NULL)
204 #ifdef ENABLE_OSRELDATE
209 * These are the functions the dynamic linker exports to application
210 * programs. They are the only symbols the dynamic linker is willing
211 * to export from itself.
213 static func_ptr_type exports[] = {
214 (func_ptr_type) &_rtld_error,
215 (func_ptr_type) &dlclose,
216 (func_ptr_type) &dlerror,
217 (func_ptr_type) &dlopen,
218 (func_ptr_type) &dlfunc,
219 (func_ptr_type) &dlsym,
220 (func_ptr_type) &dlvsym,
221 (func_ptr_type) &dladdr,
222 (func_ptr_type) &dlinfo,
223 (func_ptr_type) &dl_iterate_phdr,
225 (func_ptr_type) &___tls_get_addr,
227 (func_ptr_type) &__tls_get_addr,
228 (func_ptr_type) &__tls_get_addr_tcb,
229 (func_ptr_type) &_rtld_allocate_tls,
230 (func_ptr_type) &_rtld_free_tls,
231 (func_ptr_type) &_rtld_call_init,
232 (func_ptr_type) &_rtld_thread_init,
233 (func_ptr_type) &_rtld_addr_phdr,
238 * Global declarations normally provided by crt1. The dynamic linker is
239 * not built with crt1, so we have to provide them ourselves.
245 * Globals to control TLS allocation.
247 size_t tls_last_offset; /* Static TLS offset of last module */
248 size_t tls_last_size; /* Static TLS size of last module */
249 size_t tls_static_space; /* Static TLS space allocated */
250 int tls_dtv_generation = 1; /* Used to detect when dtv size changes */
251 int tls_max_index = 1; /* Largest module index allocated */
254 * Fill in a DoneList with an allocation large enough to hold all of
255 * the currently-loaded objects. Keep this as a macro since it calls
256 * alloca and we want that to occur within the scope of the caller.
258 #define donelist_init(dlp) \
259 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
260 assert((dlp)->objs != NULL), \
261 (dlp)->num_alloc = obj_count, \
264 #define UTRACE_DLOPEN_START 1
265 #define UTRACE_DLOPEN_STOP 2
266 #define UTRACE_DLCLOSE_START 3
267 #define UTRACE_DLCLOSE_STOP 4
268 #define UTRACE_LOAD_OBJECT 5
269 #define UTRACE_UNLOAD_OBJECT 6
270 #define UTRACE_ADD_RUNDEP 7
271 #define UTRACE_PRELOAD_FINISHED 8
272 #define UTRACE_INIT_CALL 9
273 #define UTRACE_FINI_CALL 10
276 char sig[4]; /* 'RTLD' */
279 void *mapbase; /* Used for 'parent' and 'init/fini' */
281 int refcnt; /* Used for 'mode' */
282 char name[MAXPATHLEN];
285 #define LD_UTRACE(e, h, mb, ms, r, n) do { \
286 if (ld_utrace != NULL) \
287 ld_utrace_log(e, h, mb, ms, r, n); \
291 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
292 int refcnt, const char *name)
294 struct utrace_rtld ut;
302 ut.mapbase = mapbase;
303 ut.mapsize = mapsize;
305 bzero(ut.name, sizeof(ut.name));
307 strlcpy(ut.name, name, sizeof(ut.name));
308 utrace(&ut, sizeof(ut));
312 * Main entry point for dynamic linking. The first argument is the
313 * stack pointer. The stack is expected to be laid out as described
314 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
315 * Specifically, the stack pointer points to a word containing
316 * ARGC. Following that in the stack is a null-terminated sequence
317 * of pointers to argument strings. Then comes a null-terminated
318 * sequence of pointers to environment strings. Finally, there is a
319 * sequence of "auxiliary vector" entries.
321 * The second argument points to a place to store the dynamic linker's
322 * exit procedure pointer and the third to a place to store the main
325 * The return value is the main program's entry point.
328 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
330 Elf_Auxinfo *aux_info[AT_COUNT];
338 Objlist_Entry *entry;
341 /* marino: DO NOT MOVE THESE VARIABLES TO _rtld
342 Obj_Entry **preload_tail;
344 from global to here. It will break the DWARF2 unwind scheme.
345 The system compilers were unaffected, but not gcc 4.6
349 * On entry, the dynamic linker itself has not been relocated yet.
350 * Be very careful not to reference any global data until after
351 * init_rtld has returned. It is OK to reference file-scope statics
352 * and string constants, and to call static and global functions.
355 /* Find the auxiliary vector on the stack. */
358 sp += argc + 1; /* Skip over arguments and NULL terminator */
362 * If we aren't already resident we have to dig out some more info.
363 * Note that auxinfo does not exist when we are resident.
365 * I'm not sure about the ld_resident check. It seems to read zero
366 * prior to relocation, which is what we want. When running from a
367 * resident copy everything will be relocated so we are definitely
370 if (ld_resident == 0) {
371 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
373 aux = (Elf_Auxinfo *) sp;
375 /* Digest the auxiliary vector. */
376 for (i = 0; i < AT_COUNT; i++)
378 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
379 if (auxp->a_type < AT_COUNT)
380 aux_info[auxp->a_type] = auxp;
383 /* Initialize and relocate ourselves. */
384 assert(aux_info[AT_BASE] != NULL);
385 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
388 ld_index = 0; /* don't use old env cache in case we are resident */
389 __progname = obj_rtld.path;
390 argv0 = argv[0] != NULL ? argv[0] : "(null)";
393 trust = !issetugid();
395 ld_bind_now = _getenv_ld("LD_BIND_NOW");
397 * If the process is tainted, then we un-set the dangerous environment
398 * variables. The process will be marked as tainted until setuid(2)
399 * is called. If any child process calls setuid(2) we do not want any
400 * future processes to honor the potentially un-safe variables.
403 if ( unsetenv("LD_DEBUG")
404 || unsetenv("LD_PRELOAD")
405 || unsetenv("LD_LIBRARY_PATH")
406 || unsetenv("LD_ELF_HINTS_PATH")
407 || unsetenv("LD_LIBMAP")
408 || unsetenv("LD_LIBMAP_DISABLE")
409 || unsetenv("LD_LOADFLTR")
411 _rtld_error("environment corrupt; aborting");
415 ld_debug = _getenv_ld("LD_DEBUG");
416 libmap_disable = _getenv_ld("LD_LIBMAP_DISABLE") != NULL;
417 libmap_override = (char *)_getenv_ld("LD_LIBMAP");
418 ld_library_path = _getenv_ld("LD_LIBRARY_PATH");
419 ld_preload = (char *)_getenv_ld("LD_PRELOAD");
420 ld_elf_hints_path = _getenv_ld("LD_ELF_HINTS_PATH");
421 ld_loadfltr = _getenv_ld("LD_LOADFLTR") != NULL;
422 dangerous_ld_env = (ld_library_path != NULL)
423 || (ld_preload != NULL)
424 || (ld_elf_hints_path != NULL)
426 || (libmap_override != NULL)
429 ld_tracing = _getenv_ld("LD_TRACE_LOADED_OBJECTS");
430 ld_utrace = _getenv_ld("LD_UTRACE");
432 if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0)
433 ld_elf_hints_path = _PATH_ELF_HINTS;
435 if (ld_debug != NULL && *ld_debug != '\0')
437 dbg("%s is initialized, base address = %p", __progname,
438 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
439 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
440 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
442 dbg("initializing thread locks");
446 * If we are resident we can skip work that we have already done.
447 * Note that the stack is reset and there is no Elf_Auxinfo
448 * when running from a resident image, and the static globals setup
449 * between here and resident_skip will have already been setup.
455 * Load the main program, or process its program header if it is
458 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
459 int fd = aux_info[AT_EXECFD]->a_un.a_val;
460 dbg("loading main program");
461 obj_main = map_object(fd, argv0, NULL);
463 if (obj_main == NULL)
465 } else { /* Main program already loaded. */
466 const Elf_Phdr *phdr;
470 dbg("processing main program's program header");
471 assert(aux_info[AT_PHDR] != NULL);
472 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
473 assert(aux_info[AT_PHNUM] != NULL);
474 phnum = aux_info[AT_PHNUM]->a_un.a_val;
475 assert(aux_info[AT_PHENT] != NULL);
476 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
477 assert(aux_info[AT_ENTRY] != NULL);
478 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
479 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
483 char buf[MAXPATHLEN];
484 if (aux_info[AT_EXECPATH] != 0) {
487 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
488 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
489 if (kexecpath[0] == '/')
490 obj_main->path = kexecpath;
491 else if (getcwd(buf, sizeof(buf)) == NULL ||
492 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
493 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
494 obj_main->path = xstrdup(argv0);
496 obj_main->path = xstrdup(buf);
498 char resolved[MAXPATHLEN];
499 dbg("No AT_EXECPATH");
500 if (argv0[0] == '/') {
501 if (realpath(argv0, resolved) != NULL)
502 obj_main->path = xstrdup(resolved);
504 obj_main->path = xstrdup(argv0);
506 if (getcwd(buf, sizeof(buf)) != NULL
507 && strlcat(buf, "/", sizeof(buf)) < sizeof(buf)
508 && strlcat(buf, argv0, sizeof (buf)) < sizeof(buf)
509 && access(buf, R_OK) == 0
510 && realpath(buf, resolved) != NULL)
511 obj_main->path = xstrdup(resolved);
513 obj_main->path = xstrdup(argv0);
516 dbg("obj_main path %s", obj_main->path);
517 obj_main->mainprog = true;
520 * Get the actual dynamic linker pathname from the executable if
521 * possible. (It should always be possible.) That ensures that
522 * gdb will find the right dynamic linker even if a non-standard
525 if (obj_main->interp != NULL &&
526 strcmp(obj_main->interp, obj_rtld.path) != 0) {
528 obj_rtld.path = xstrdup(obj_main->interp);
529 __progname = obj_rtld.path;
532 digest_dynamic(obj_main, 0);
534 linkmap_add(obj_main);
535 linkmap_add(&obj_rtld);
537 /* Link the main program into the list of objects. */
538 *obj_tail = obj_main;
539 obj_tail = &obj_main->next;
542 /* Make sure we don't call the main program's init and fini functions. */
543 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
545 /* Initialize a fake symbol for resolving undefined weak references. */
546 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
547 sym_zero.st_shndx = SHN_UNDEF;
548 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
551 libmap_disable = (bool)lm_init(libmap_override);
553 dbg("loading LD_PRELOAD libraries");
554 if (load_preload_objects() == -1)
556 preload_tail = obj_tail;
558 dbg("loading needed objects");
559 if (load_needed_objects(obj_main, 0) == -1)
562 /* Make a list of all objects loaded at startup. */
563 for (obj = obj_list; obj != NULL; obj = obj->next) {
564 objlist_push_tail(&list_main, obj);
568 dbg("checking for required versions");
569 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
574 if (ld_tracing) { /* We're done */
575 trace_loaded_objects(obj_main);
579 if (ld_resident) /* XXX clean this up! */
582 if (_getenv_ld("LD_DUMP_REL_PRE") != NULL) {
583 dump_relocations(obj_main);
587 /* setup TLS for main thread */
588 dbg("initializing initial thread local storage");
589 STAILQ_FOREACH(entry, &list_main, link) {
591 * Allocate all the initial objects out of the static TLS
592 * block even if they didn't ask for it.
594 allocate_tls_offset(entry->obj);
597 tls_static_space = tls_last_offset + RTLD_STATIC_TLS_EXTRA;
600 * Do not try to allocate the TLS here, let libc do it itself.
601 * (crt1 for the program will call _init_tls())
604 if (relocate_objects(obj_main,
605 ld_bind_now != NULL && *ld_bind_now != '\0', &obj_rtld, NULL) == -1)
608 dbg("doing copy relocations");
609 if (do_copy_relocations(obj_main) == -1)
614 if (_getenv_ld("LD_RESIDENT_UNREGISTER_NOW")) {
615 if (exec_sys_unregister(-1) < 0) {
616 dbg("exec_sys_unregister failed %d\n", errno);
619 dbg("exec_sys_unregister success\n");
623 if (_getenv_ld("LD_DUMP_REL_POST") != NULL) {
624 dump_relocations(obj_main);
628 dbg("initializing key program variables");
629 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
630 set_program_var("environ", env);
631 set_program_var("__elf_aux_vector", aux);
633 if (_getenv_ld("LD_RESIDENT_REGISTER_NOW")) {
634 extern void resident_start(void);
636 if (exec_sys_register(resident_start) < 0) {
637 dbg("exec_sys_register failed %d\n", errno);
640 dbg("exec_sys_register success\n");
644 /* Make a list of init functions to call. */
645 objlist_init(&initlist);
646 initlist_add_objects(obj_list, preload_tail, &initlist);
648 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
651 * Do NOT call the initlist here, give libc a chance to set up
652 * the initial TLS segment. crt1 will then call _rtld_call_init().
655 dbg("transferring control to program entry point = %p", obj_main->entry);
657 /* Return the exit procedure and the program entry point. */
658 *exit_proc = rtld_exit;
660 return (func_ptr_type) obj_main->entry;
664 * Call the initialization list for dynamically loaded libraries.
665 * (called from crt1.c).
668 _rtld_call_init(void)
670 RtldLockState lockstate;
673 wlock_acquire(rtld_bind_lock, &lockstate);
674 objlist_call_init(&initlist, &lockstate);
675 objlist_clear(&initlist);
676 dbg("loading filtees");
677 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
678 if (ld_loadfltr || obj->z_loadfltr)
679 load_filtees(obj, 0, &lockstate);
681 lock_release(rtld_bind_lock, &lockstate);
685 _rtld_bind(Obj_Entry *obj, Elf_Size reloff, void *stack)
689 const Obj_Entry *defobj;
692 RtldLockState lockstate;
694 rlock_acquire(rtld_bind_lock, &lockstate);
695 if (sigsetjmp(lockstate.env, 0) != 0)
696 lock_upgrade(rtld_bind_lock, &lockstate);
698 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
700 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
702 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
703 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL,
708 target = (Elf_Addr)(defobj->relocbase + def->st_value);
710 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
711 defobj->strtab + def->st_name, basename(obj->path),
712 (void *)target, basename(defobj->path));
715 * If we have a function call tracing hook, and the
716 * hook would like to keep tracing this one function,
717 * prevent the relocation so we will wind up here
718 * the next time again.
720 * We don't want to functrace calls from the functracer
721 * to avoid recursive loops.
723 if (rtld_functrace != NULL && obj != rtld_functrace_obj) {
724 if (rtld_functrace(obj->path,
726 defobj->strtab + def->st_name,
728 lock_release(rtld_bind_lock, &lockstate);
733 * Write the new contents for the jmpslot. Note that depending on
734 * architecture, the value which we need to return back to the
735 * lazy binding trampoline may or may not be the target
736 * address. The value returned from reloc_jmpslot() is the value
737 * that the trampoline needs.
739 target = reloc_jmpslot(where, target, defobj, obj, rel);
740 lock_release(rtld_bind_lock, &lockstate);
745 * Error reporting function. Use it like printf. If formats the message
746 * into a buffer, and sets things up so that the next call to dlerror()
747 * will return the message.
750 _rtld_error(const char *fmt, ...)
752 static char buf[512];
756 rtld_vsnprintf(buf, sizeof buf, fmt, ap);
762 * Return a dynamically-allocated copy of the current error message, if any.
767 return error_message == NULL ? NULL : xstrdup(error_message);
771 * Restore the current error message from a copy which was previously saved
772 * by errmsg_save(). The copy is freed.
775 errmsg_restore(char *saved_msg)
777 if (saved_msg == NULL)
778 error_message = NULL;
780 _rtld_error("%s", saved_msg);
786 basename(const char *name)
788 const char *p = strrchr(name, '/');
789 return p != NULL ? p + 1 : name;
792 static struct utsname uts;
795 origin_subst_one(char **res, const char *real, const char *kw, const char *subst,
805 subst_len = kw_len = 0;
809 if (subst_len == 0) {
810 subst_len = strlen(subst);
814 *res = xmalloc(PATH_MAX);
817 if ((res1 - *res) + subst_len + (p1 - p) >= PATH_MAX) {
818 _rtld_error("Substitution of %s in %s cannot be performed",
820 if (may_free != NULL)
825 memcpy(res1, p, p1 - p);
827 memcpy(res1, subst, subst_len);
832 if (may_free != NULL)
835 *res = xstrdup(real);
839 if (may_free != NULL)
841 if (strlcat(res1, p, PATH_MAX - (res1 - *res)) >= PATH_MAX) {
851 origin_subst(const char *real, const char *origin_path)
853 char *res1, *res2, *res3, *res4;
855 if (uts.sysname[0] == '\0') {
856 if (uname(&uts) != 0) {
857 _rtld_error("utsname failed: %d", errno);
861 if (!origin_subst_one(&res1, real, "$ORIGIN", origin_path, NULL) ||
862 !origin_subst_one(&res2, res1, "$OSNAME", uts.sysname, res1) ||
863 !origin_subst_one(&res3, res2, "$OSREL", uts.release, res2) ||
864 !origin_subst_one(&res4, res3, "$PLATFORM", uts.machine, res3))
872 const char *msg = dlerror();
876 rtld_fdputstr(STDERR_FILENO, msg);
881 * Process a shared object's DYNAMIC section, and save the important
882 * information in its Obj_Entry structure.
885 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
886 const Elf_Dyn **dyn_soname)
889 Needed_Entry **needed_tail = &obj->needed;
890 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
891 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
892 int plttype = DT_REL;
897 obj->bind_now = false;
898 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
899 switch (dynp->d_tag) {
902 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
906 obj->relsize = dynp->d_un.d_val;
910 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
914 obj->pltrel = (const Elf_Rel *)
915 (obj->relocbase + dynp->d_un.d_ptr);
919 obj->pltrelsize = dynp->d_un.d_val;
923 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
927 obj->relasize = dynp->d_un.d_val;
931 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
935 plttype = dynp->d_un.d_val;
936 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
940 obj->symtab = (const Elf_Sym *)
941 (obj->relocbase + dynp->d_un.d_ptr);
945 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
949 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
953 obj->strsize = dynp->d_un.d_val;
957 obj->verneed = (const Elf_Verneed *) (obj->relocbase +
962 obj->verneednum = dynp->d_un.d_val;
966 obj->verdef = (const Elf_Verdef *) (obj->relocbase +
971 obj->verdefnum = dynp->d_un.d_val;
975 obj->versyms = (const Elf_Versym *)(obj->relocbase +
981 const Elf_Hashelt *hashtab = (const Elf_Hashelt *)
982 (obj->relocbase + dynp->d_un.d_ptr);
983 obj->nbuckets = hashtab[0];
984 obj->nchains = hashtab[1];
985 obj->buckets = hashtab + 2;
986 obj->chains = obj->buckets + obj->nbuckets;
992 Needed_Entry *nep = NEW(Needed_Entry);
993 nep->name = dynp->d_un.d_val;
998 needed_tail = &nep->next;
1004 Needed_Entry *nep = NEW(Needed_Entry);
1005 nep->name = dynp->d_un.d_val;
1009 *needed_filtees_tail = nep;
1010 needed_filtees_tail = &nep->next;
1016 Needed_Entry *nep = NEW(Needed_Entry);
1017 nep->name = dynp->d_un.d_val;
1021 *needed_aux_filtees_tail = nep;
1022 needed_aux_filtees_tail = &nep->next;
1027 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
1031 obj->textrel = true;
1035 obj->symbolic = true;
1039 case DT_RUNPATH: /* XXX: process separately */
1041 * We have to wait until later to process this, because we
1042 * might not have gotten the address of the string table yet.
1052 obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1056 obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1060 /* XXX - not implemented yet */
1062 dbg("Filling in DT_DEBUG entry");
1063 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
1067 if ((dynp->d_un.d_val & DF_ORIGIN) && trust)
1068 obj->z_origin = true;
1069 if (dynp->d_un.d_val & DF_SYMBOLIC)
1070 obj->symbolic = true;
1071 if (dynp->d_un.d_val & DF_TEXTREL)
1072 obj->textrel = true;
1073 if (dynp->d_un.d_val & DF_BIND_NOW)
1074 obj->bind_now = true;
1075 /*if (dynp->d_un.d_val & DF_STATIC_TLS)
1080 if (dynp->d_un.d_val & DF_1_NOOPEN)
1081 obj->z_noopen = true;
1082 if ((dynp->d_un.d_val & DF_1_ORIGIN) && trust)
1083 obj->z_origin = true;
1084 /*if (dynp->d_un.d_val & DF_1_GLOBAL)
1086 if (dynp->d_un.d_val & DF_1_BIND_NOW)
1087 obj->bind_now = true;
1088 if (dynp->d_un.d_val & DF_1_NODELETE)
1089 obj->z_nodelete = true;
1090 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1091 obj->z_loadfltr = true;
1096 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1103 obj->traced = false;
1105 if (plttype == DT_RELA) {
1106 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1108 obj->pltrelasize = obj->pltrelsize;
1109 obj->pltrelsize = 0;
1114 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1115 const Elf_Dyn *dyn_soname)
1118 if (obj->z_origin && obj->origin_path == NULL) {
1119 obj->origin_path = xmalloc(PATH_MAX);
1120 if (rtld_dirname_abs(obj->path, obj->origin_path) == -1)
1124 if (dyn_rpath != NULL) {
1125 obj->rpath = (char *)obj->strtab + dyn_rpath->d_un.d_val;
1127 obj->rpath = origin_subst(obj->rpath, obj->origin_path);
1130 if (dyn_soname != NULL)
1131 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1135 digest_dynamic(Obj_Entry *obj, int early)
1137 const Elf_Dyn *dyn_rpath;
1138 const Elf_Dyn *dyn_soname;
1140 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname);
1141 digest_dynamic2(obj, dyn_rpath, dyn_soname);
1145 * Process a shared object's program header. This is used only for the
1146 * main program, when the kernel has already loaded the main program
1147 * into memory before calling the dynamic linker. It creates and
1148 * returns an Obj_Entry structure.
1151 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1154 const Elf_Phdr *phlimit = phdr + phnum;
1159 for (ph = phdr; ph < phlimit; ph++) {
1160 if (ph->p_type != PT_PHDR)
1164 obj->phsize = ph->p_memsz;
1165 obj->relocbase = (caddr_t)phdr - ph->p_vaddr;
1169 for (ph = phdr; ph < phlimit; ph++) {
1170 switch (ph->p_type) {
1173 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1177 if (nsegs == 0) { /* First load segment */
1178 obj->vaddrbase = trunc_page(ph->p_vaddr);
1179 obj->mapbase = obj->vaddrbase + obj->relocbase;
1180 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
1182 } else { /* Last load segment */
1183 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1190 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1195 obj->tlssize = ph->p_memsz;
1196 obj->tlsalign = ph->p_align;
1197 obj->tlsinitsize = ph->p_filesz;
1198 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1202 obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1203 obj->relro_size = round_page(ph->p_memsz);
1208 _rtld_error("%s: too few PT_LOAD segments", path);
1217 dlcheck(void *handle)
1221 for (obj = obj_list; obj != NULL; obj = obj->next)
1222 if (obj == (Obj_Entry *) handle)
1225 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1226 _rtld_error("Invalid shared object handle %p", handle);
1233 * If the given object is already in the donelist, return true. Otherwise
1234 * add the object to the list and return false.
1237 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1241 for (i = 0; i < dlp->num_used; i++)
1242 if (dlp->objs[i] == obj)
1245 * Our donelist allocation should always be sufficient. But if
1246 * our threads locking isn't working properly, more shared objects
1247 * could have been loaded since we allocated the list. That should
1248 * never happen, but we'll handle it properly just in case it does.
1250 if (dlp->num_used < dlp->num_alloc)
1251 dlp->objs[dlp->num_used++] = obj;
1256 * Hash function for symbol table lookup. Don't even think about changing
1257 * this. It is specified by the System V ABI.
1260 elf_hash(const char *name)
1262 const unsigned char *p = (const unsigned char *) name;
1263 unsigned long h = 0;
1266 while (*p != '\0') {
1267 h = (h << 4) + *p++;
1268 if ((g = h & 0xf0000000) != 0)
1276 * Find the library with the given name, and return its full pathname.
1277 * The returned string is dynamically allocated. Generates an error
1278 * message and returns NULL if the library cannot be found.
1280 * If the second argument is non-NULL, then it refers to an already-
1281 * loaded shared object, whose library search path will be searched.
1283 * The search order is:
1285 * rpath in the referencing file
1290 find_library(const char *xname, const Obj_Entry *refobj)
1295 if (strchr(xname, '/') != NULL) { /* Hard coded pathname */
1296 if (xname[0] != '/' && !trust) {
1297 _rtld_error("Absolute pathname required for shared object \"%s\"",
1301 if (refobj != NULL && refobj->z_origin)
1302 return origin_subst(xname, refobj->origin_path);
1304 return xstrdup(xname);
1307 if (libmap_disable || (refobj == NULL) ||
1308 (name = lm_find(refobj->path, xname)) == NULL)
1309 name = (char *)xname;
1311 dbg(" Searching for \"%s\"", name);
1313 if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
1315 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
1316 (pathname = search_library_path(name, gethints())) != NULL ||
1317 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
1320 if(refobj != NULL && refobj->path != NULL) {
1321 _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
1322 name, basename(refobj->path));
1324 _rtld_error("Shared object \"%s\" not found", name);
1330 * Given a symbol number in a referencing object, find the corresponding
1331 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1332 * no definition was found. Returns a pointer to the Obj_Entry of the
1333 * defining object via the reference parameter DEFOBJ_OUT.
1336 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1337 const Obj_Entry **defobj_out, int flags, SymCache *cache,
1338 RtldLockState *lockstate)
1342 const Obj_Entry *defobj;
1348 * If we have already found this symbol, get the information from
1351 if (symnum >= refobj->nchains)
1352 return NULL; /* Bad object */
1353 if (cache != NULL && cache[symnum].sym != NULL) {
1354 *defobj_out = cache[symnum].obj;
1355 return cache[symnum].sym;
1358 ref = refobj->symtab + symnum;
1359 name = refobj->strtab + ref->st_name;
1364 * We don't have to do a full scale lookup if the symbol is local.
1365 * We know it will bind to the instance in this load module; to
1366 * which we already have a pointer (ie ref). By not doing a lookup,
1367 * we not only improve performance, but it also avoids unresolvable
1368 * symbols when local symbols are not in the hash table.
1370 * This might occur for TLS module relocations, which simply use
1373 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1374 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1375 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1378 symlook_init(&req, name);
1380 req.ventry = fetch_ventry(refobj, symnum);
1381 req.lockstate = lockstate;
1382 res = symlook_default(&req, refobj);
1385 defobj = req.defobj_out;
1393 * If we found no definition and the reference is weak, treat the
1394 * symbol as having the value zero.
1396 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1402 *defobj_out = defobj;
1403 /* Record the information in the cache to avoid subsequent lookups. */
1404 if (cache != NULL) {
1405 cache[symnum].sym = def;
1406 cache[symnum].obj = defobj;
1409 if (refobj != &obj_rtld)
1410 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1416 * Return the search path from the ldconfig hints file, reading it if
1417 * necessary. Returns NULL if there are problems with the hints file,
1418 * or if the search path there is empty.
1425 if (hints == NULL) {
1427 struct elfhints_hdr hdr;
1430 /* Keep from trying again in case the hints file is bad. */
1433 if ((fd = open(ld_elf_hints_path, O_RDONLY)) == -1)
1435 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1436 hdr.magic != ELFHINTS_MAGIC ||
1441 p = xmalloc(hdr.dirlistlen + 1);
1442 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1443 read(fd, p, hdr.dirlistlen + 1) != (ssize_t)hdr.dirlistlen + 1) {
1451 return hints[0] != '\0' ? hints : NULL;
1455 init_dag(Obj_Entry *root)
1459 if (root->dag_inited)
1461 donelist_init(&donelist);
1462 init_dag1(root, root, &donelist);
1463 root->dag_inited = true;
1467 init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *dlp)
1469 const Needed_Entry *needed;
1471 if (donelist_check(dlp, obj))
1474 objlist_push_tail(&obj->dldags, root);
1475 objlist_push_tail(&root->dagmembers, obj);
1476 for (needed = obj->needed; needed != NULL; needed = needed->next)
1477 if (needed->obj != NULL)
1478 init_dag1(root, needed->obj, dlp);
1482 * Initialize the dynamic linker. The argument is the address at which
1483 * the dynamic linker has been mapped into memory. The primary task of
1484 * this function is to relocate the dynamic linker.
1487 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
1489 Obj_Entry objtmp; /* Temporary rtld object */
1490 const Elf_Dyn *dyn_rpath;
1491 const Elf_Dyn *dyn_soname;
1494 * Conjure up an Obj_Entry structure for the dynamic linker.
1496 * The "path" member can't be initialized yet because string constants
1497 * cannot yet be accessed. Below we will set it correctly.
1499 memset(&objtmp, 0, sizeof(objtmp));
1502 objtmp.mapbase = mapbase;
1504 objtmp.relocbase = mapbase;
1506 if (RTLD_IS_DYNAMIC()) {
1507 objtmp.dynamic = rtld_dynamic(&objtmp);
1508 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname);
1509 assert(objtmp.needed == NULL);
1510 assert(!objtmp.textrel);
1513 * Temporarily put the dynamic linker entry into the object list, so
1514 * that symbols can be found.
1517 relocate_objects(&objtmp, true, &objtmp, NULL);
1520 /* Initialize the object list. */
1521 obj_tail = &obj_list;
1523 /* Now that non-local variables can be accesses, copy out obj_rtld. */
1524 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1526 #ifdef ENABLE_OSRELDATE
1527 if (aux_info[AT_OSRELDATE] != NULL)
1528 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
1531 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname);
1533 /* Replace the path with a dynamically allocated copy. */
1534 obj_rtld.path = xstrdup(PATH_RTLD);
1536 r_debug.r_brk = r_debug_state;
1537 r_debug.r_state = RT_CONSISTENT;
1541 * Add the init functions from a needed object list (and its recursive
1542 * needed objects) to "list". This is not used directly; it is a helper
1543 * function for initlist_add_objects(). The write lock must be held
1544 * when this function is called.
1547 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1549 /* Recursively process the successor needed objects. */
1550 if (needed->next != NULL)
1551 initlist_add_neededs(needed->next, list);
1553 /* Process the current needed object. */
1554 if (needed->obj != NULL)
1555 initlist_add_objects(needed->obj, &needed->obj->next, list);
1559 * Scan all of the DAGs rooted in the range of objects from "obj" to
1560 * "tail" and add their init functions to "list". This recurses over
1561 * the DAGs and ensure the proper init ordering such that each object's
1562 * needed libraries are initialized before the object itself. At the
1563 * same time, this function adds the objects to the global finalization
1564 * list "list_fini" in the opposite order. The write lock must be
1565 * held when this function is called.
1568 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1570 if (obj->init_scanned || obj->init_done)
1572 obj->init_scanned = true;
1574 /* Recursively process the successor objects. */
1575 if (&obj->next != tail)
1576 initlist_add_objects(obj->next, tail, list);
1578 /* Recursively process the needed objects. */
1579 if (obj->needed != NULL)
1580 initlist_add_neededs(obj->needed, list);
1582 /* Add the object to the init list. */
1583 if (obj->init != (Elf_Addr)NULL)
1584 objlist_push_tail(list, obj);
1586 /* Add the object to the global fini list in the reverse order. */
1587 if (obj->fini != (Elf_Addr)NULL && !obj->on_fini_list) {
1588 objlist_push_head(&list_fini, obj);
1589 obj->on_fini_list = true;
1594 #define FPTR_TARGET(f) ((Elf_Addr) (f))
1598 is_exported(const Elf_Sym *def)
1601 const func_ptr_type *p;
1603 value = (Elf_Addr)(obj_rtld.relocbase + def->st_value);
1604 for (p = exports; *p != NULL; p++)
1605 if (FPTR_TARGET(*p) == value)
1611 free_needed_filtees(Needed_Entry *n)
1613 Needed_Entry *needed, *needed1;
1615 for (needed = n; needed != NULL; needed = needed->next) {
1616 if (needed->obj != NULL) {
1617 dlclose(needed->obj);
1621 for (needed = n; needed != NULL; needed = needed1) {
1622 needed1 = needed->next;
1628 unload_filtees(Obj_Entry *obj)
1631 free_needed_filtees(obj->needed_filtees);
1632 obj->needed_filtees = NULL;
1633 free_needed_filtees(obj->needed_aux_filtees);
1634 obj->needed_aux_filtees = NULL;
1635 obj->filtees_loaded = false;
1639 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags)
1642 for (; needed != NULL; needed = needed->next) {
1643 needed->obj = dlopen_object(obj->strtab + needed->name, obj,
1644 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
1650 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
1653 lock_restart_for_upgrade(lockstate);
1654 if (!obj->filtees_loaded) {
1655 load_filtee1(obj, obj->needed_filtees, flags);
1656 load_filtee1(obj, obj->needed_aux_filtees, flags);
1657 obj->filtees_loaded = true;
1662 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
1666 for (; needed != NULL; needed = needed->next) {
1667 obj1 = needed->obj = load_object(obj->strtab + needed->name, obj,
1668 flags & ~RTLD_LO_NOLOAD);
1669 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
1671 if (obj1 != NULL && obj1->z_nodelete && !obj1->ref_nodel) {
1672 dbg("obj %s nodelete", obj1->path);
1675 obj1->ref_nodel = true;
1682 * Given a shared object, traverse its list of needed objects, and load
1683 * each of them. Returns 0 on success. Generates an error message and
1684 * returns -1 on failure.
1687 load_needed_objects(Obj_Entry *first, int flags)
1691 for (obj = first; obj != NULL; obj = obj->next) {
1692 if (process_needed(obj, obj->needed, flags) == -1)
1699 load_preload_objects(void)
1701 char *p = ld_preload;
1702 static const char delim[] = " \t:;";
1707 p += strspn(p, delim);
1708 while (*p != '\0') {
1709 size_t len = strcspn(p, delim);
1717 obj = load_object(p, NULL, 0);
1719 return -1; /* XXX - cleanup */
1722 p += strspn(p, delim);
1724 /* Check for the magic tracing function */
1725 symlook_init(&req, RTLD_FUNCTRACE);
1726 res = symlook_obj(&req, obj);
1728 rtld_functrace = (void *)(req.defobj_out->relocbase +
1729 req.sym_out->st_value);
1730 rtld_functrace_obj = req.defobj_out;
1733 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
1738 * Load a shared object into memory, if it is not already loaded.
1740 * Returns a pointer to the Obj_Entry for the object. Returns NULL
1744 load_object(const char *name, const Obj_Entry *refobj, int flags)
1751 for (obj = obj_list->next; obj != NULL; obj = obj->next)
1752 if (object_match_name(obj, name))
1755 path = find_library(name, refobj);
1760 * If we didn't find a match by pathname, open the file and check
1761 * again by device and inode. This avoids false mismatches caused
1762 * by multiple links or ".." in pathnames.
1764 * To avoid a race, we open the file and use fstat() rather than
1767 if ((fd = open(path, O_RDONLY)) == -1) {
1768 _rtld_error("Cannot open \"%s\"", path);
1772 if (fstat(fd, &sb) == -1) {
1773 _rtld_error("Cannot fstat \"%s\"", path);
1778 for (obj = obj_list->next; obj != NULL; obj = obj->next)
1779 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
1782 object_add_name(obj, name);
1787 if (flags & RTLD_LO_NOLOAD) {
1793 /* First use of this object, so we must map it in */
1794 obj = do_load_object(fd, name, path, &sb, flags);
1803 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
1810 * but first, make sure that environment variables haven't been
1811 * used to circumvent the noexec flag on a filesystem.
1813 if (dangerous_ld_env) {
1814 if (fstatfs(fd, &fs) != 0) {
1815 _rtld_error("Cannot fstatfs \"%s\"", path);
1818 if (fs.f_flags & MNT_NOEXEC) {
1819 _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
1823 dbg("loading \"%s\"", path);
1824 obj = map_object(fd, path, sbp);
1828 object_add_name(obj, name);
1830 digest_dynamic(obj, 0);
1831 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
1833 dbg("refusing to load non-loadable \"%s\"", obj->path);
1834 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
1835 munmap(obj->mapbase, obj->mapsize);
1841 obj_tail = &obj->next;
1844 linkmap_add(obj); /* for GDB & dlinfo() */
1846 dbg(" %p .. %p: %s", obj->mapbase,
1847 obj->mapbase + obj->mapsize - 1, obj->path);
1849 dbg(" WARNING: %s has impure text", obj->path);
1850 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
1857 obj_from_addr(const void *addr)
1861 for (obj = obj_list; obj != NULL; obj = obj->next) {
1862 if (addr < (void *) obj->mapbase)
1864 if (addr < (void *) (obj->mapbase + obj->mapsize))
1871 * Call the finalization functions for each of the objects in "list"
1872 * belonging to the DAG of "root" and referenced once. If NULL "root"
1873 * is specified, every finalization function will be called regardless
1874 * of the reference count and the list elements won't be freed. All of
1875 * the objects are expected to have non-NULL fini functions.
1878 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
1883 assert(root == NULL || root->refcount == 1);
1886 * Preserve the current error message since a fini function might
1887 * call into the dynamic linker and overwrite it.
1889 saved_msg = errmsg_save();
1891 STAILQ_FOREACH(elm, list, link) {
1892 if (root != NULL && (elm->obj->refcount != 1 ||
1893 objlist_find(&root->dagmembers, elm->obj) == NULL))
1895 dbg("calling fini function for %s at %p", elm->obj->path,
1896 (void *)elm->obj->fini);
1897 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini, 0, 0,
1899 /* Remove object from fini list to prevent recursive invocation. */
1900 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1902 * XXX: If a dlopen() call references an object while the
1903 * fini function is in progress, we might end up trying to
1904 * unload the referenced object in dlclose() or the object
1905 * won't be unloaded although its fini function has been
1908 lock_release(rtld_bind_lock, lockstate);
1909 call_initfini_pointer(elm->obj, elm->obj->fini);
1910 wlock_acquire(rtld_bind_lock, lockstate);
1911 /* No need to free anything if process is going down. */
1915 * We must restart the list traversal after every fini call
1916 * because a dlclose() call from the fini function or from
1917 * another thread might have modified the reference counts.
1921 } while (elm != NULL);
1922 errmsg_restore(saved_msg);
1926 * Call the initialization functions for each of the objects in
1927 * "list". All of the objects are expected to have non-NULL init
1931 objlist_call_init(Objlist *list, RtldLockState *lockstate)
1938 * Clean init_scanned flag so that objects can be rechecked and
1939 * possibly initialized earlier if any of vectors called below
1940 * cause the change by using dlopen.
1942 for (obj = obj_list; obj != NULL; obj = obj->next)
1943 obj->init_scanned = false;
1946 * Preserve the current error message since an init function might
1947 * call into the dynamic linker and overwrite it.
1949 saved_msg = errmsg_save();
1950 STAILQ_FOREACH(elm, list, link) {
1951 if (elm->obj->init_done) /* Initialized early. */
1953 dbg("calling init function for %s at %p", elm->obj->path,
1954 (void *)elm->obj->init);
1955 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init, 0, 0,
1958 * Race: other thread might try to use this object before current
1959 * one completes the initilization. Not much can be done here
1960 * without better locking.
1962 elm->obj->init_done = true;
1963 lock_release(rtld_bind_lock, lockstate);
1964 call_initfini_pointer(elm->obj, elm->obj->init);
1965 wlock_acquire(rtld_bind_lock, lockstate);
1967 errmsg_restore(saved_msg);
1971 objlist_clear(Objlist *list)
1975 while (!STAILQ_EMPTY(list)) {
1976 elm = STAILQ_FIRST(list);
1977 STAILQ_REMOVE_HEAD(list, link);
1982 static Objlist_Entry *
1983 objlist_find(Objlist *list, const Obj_Entry *obj)
1987 STAILQ_FOREACH(elm, list, link)
1988 if (elm->obj == obj)
1994 objlist_init(Objlist *list)
2000 objlist_push_head(Objlist *list, Obj_Entry *obj)
2004 elm = NEW(Objlist_Entry);
2006 STAILQ_INSERT_HEAD(list, elm, link);
2010 objlist_push_tail(Objlist *list, Obj_Entry *obj)
2014 elm = NEW(Objlist_Entry);
2016 STAILQ_INSERT_TAIL(list, elm, link);
2020 objlist_remove(Objlist *list, Obj_Entry *obj)
2024 if ((elm = objlist_find(list, obj)) != NULL) {
2025 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2031 * Relocate newly-loaded shared objects. The argument is a pointer to
2032 * the Obj_Entry for the first such object. All objects from the first
2033 * to the end of the list of objects are relocated. Returns 0 on success,
2037 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
2038 RtldLockState *lockstate)
2042 for (obj = first; obj != NULL; obj = obj->next) {
2044 dbg("relocating \"%s\"", obj->path);
2045 if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
2046 obj->symtab == NULL || obj->strtab == NULL) {
2047 _rtld_error("%s: Shared object has no run-time symbol table",
2053 /* There are relocations to the write-protected text segment. */
2054 if (mprotect(obj->mapbase, obj->textsize,
2055 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
2056 _rtld_error("%s: Cannot write-enable text segment: %s",
2057 obj->path, strerror(errno));
2062 /* Process the non-PLT relocations. */
2063 if (reloc_non_plt(obj, rtldobj, lockstate))
2067 * Reprotect the text segment. Make sure it is included in the
2068 * core dump since we modified it. This unfortunately causes the
2069 * entire text segment to core-out but we don't have much of a
2070 * choice. We could try to only reenable core dumps on pages
2071 * in which relocations occured but that is likely most of the text
2072 * pages anyway, and even that would not work because the rest of
2073 * the text pages would wind up as a read-only OBJT_DEFAULT object
2074 * (created due to our modifications) backed by the original OBJT_VNODE
2075 * object, and the ELF coredump code is currently only able to dump
2076 * vnode records for pure vnode-backed mappings, not vnode backings
2077 * to memory objects.
2080 madvise(obj->mapbase, obj->textsize, MADV_CORE);
2081 if (mprotect(obj->mapbase, obj->textsize,
2082 PROT_READ|PROT_EXEC) == -1) {
2083 _rtld_error("%s: Cannot write-protect text segment: %s",
2084 obj->path, strerror(errno));
2089 /* Process the PLT relocations. */
2090 if (reloc_plt(obj) == -1)
2092 /* Relocate the jump slots if we are doing immediate binding. */
2093 if (obj->bind_now || bind_now)
2094 if (reloc_jmpslots(obj, lockstate) == -1)
2097 /* Set the special PLT or GOT entries. */
2101 * Set up the magic number and version in the Obj_Entry. These
2102 * were checked in the crt1.o from the original ElfKit, so we
2103 * set them for backward compatibility.
2105 obj->magic = RTLD_MAGIC;
2106 obj->version = RTLD_VERSION;
2109 * Set relocated data to read-only status if protection specified
2112 if (obj->relro_size) {
2113 if (mprotect(obj->relro_page, obj->relro_size, PROT_READ) == -1) {
2114 _rtld_error("%s: Cannot enforce relro relocation: %s",
2115 obj->path, strerror(errno));
2125 * Cleanup procedure. It will be called (by the atexit mechanism) just
2126 * before the process exits.
2131 RtldLockState lockstate;
2133 wlock_acquire(rtld_bind_lock, &lockstate);
2135 objlist_call_fini(&list_fini, NULL, &lockstate);
2136 /* No need to remove the items from the list, since we are exiting. */
2137 if (!libmap_disable)
2139 lock_release(rtld_bind_lock, &lockstate);
2143 path_enumerate(const char *path, path_enum_proc callback, void *arg)
2148 path += strspn(path, ":;");
2149 while (*path != '\0') {
2153 len = strcspn(path, ":;");
2154 res = callback(path, len, arg);
2160 path += strspn(path, ":;");
2166 struct try_library_args {
2174 try_library_path(const char *dir, size_t dirlen, void *param)
2176 struct try_library_args *arg;
2179 if (*dir == '/' || trust) {
2182 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
2185 pathname = arg->buffer;
2186 strncpy(pathname, dir, dirlen);
2187 pathname[dirlen] = '/';
2188 strcpy(pathname + dirlen + 1, arg->name);
2190 dbg(" Trying \"%s\"", pathname);
2191 if (access(pathname, F_OK) == 0) { /* We found it */
2192 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
2193 strcpy(pathname, arg->buffer);
2201 search_library_path(const char *name, const char *path)
2204 struct try_library_args arg;
2210 arg.namelen = strlen(name);
2211 arg.buffer = xmalloc(PATH_MAX);
2212 arg.buflen = PATH_MAX;
2214 p = path_enumerate(path, try_library_path, &arg);
2222 dlclose(void *handle)
2225 RtldLockState lockstate;
2227 wlock_acquire(rtld_bind_lock, &lockstate);
2228 root = dlcheck(handle);
2230 lock_release(rtld_bind_lock, &lockstate);
2233 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
2236 /* Unreference the object and its dependencies. */
2237 root->dl_refcount--;
2239 if (root->refcount == 1) {
2241 * The object will be no longer referenced, so we must unload it.
2242 * First, call the fini functions.
2244 objlist_call_fini(&list_fini, root, &lockstate);
2248 /* Finish cleaning up the newly-unreferenced objects. */
2249 GDB_STATE(RT_DELETE,&root->linkmap);
2250 unload_object(root);
2251 GDB_STATE(RT_CONSISTENT,NULL);
2255 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
2256 lock_release(rtld_bind_lock, &lockstate);
2263 char *msg = error_message;
2264 error_message = NULL;
2269 dlopen(const char *name, int mode)
2273 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
2274 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
2275 if (ld_tracing != NULL)
2276 environ = (char **)*get_program_var_addr("environ");
2277 lo_flags = RTLD_LO_DLOPEN;
2278 if (mode & RTLD_NODELETE)
2279 lo_flags |= RTLD_LO_NODELETE;
2280 if (mode & RTLD_NOLOAD)
2281 lo_flags |= RTLD_LO_NOLOAD;
2282 if (ld_tracing != NULL)
2283 lo_flags |= RTLD_LO_TRACE;
2285 return (dlopen_object(name, obj_main, lo_flags,
2286 mode & (RTLD_MODEMASK | RTLD_GLOBAL)));
2290 dlopen_object(const char *name, Obj_Entry *refobj, int lo_flags, int mode)
2292 Obj_Entry **old_obj_tail;
2295 RtldLockState lockstate;
2298 objlist_init(&initlist);
2300 wlock_acquire(rtld_bind_lock, &lockstate);
2301 GDB_STATE(RT_ADD,NULL);
2303 old_obj_tail = obj_tail;
2309 obj = load_object(name, refobj, lo_flags);
2314 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
2315 objlist_push_tail(&list_global, obj);
2316 if (*old_obj_tail != NULL) { /* We loaded something new. */
2317 assert(*old_obj_tail == obj);
2318 result = load_needed_objects(obj, lo_flags & RTLD_LO_DLOPEN);
2322 result = rtld_verify_versions(&obj->dagmembers);
2323 if (result != -1 && ld_tracing)
2325 if (result == -1 || (relocate_objects(obj, (mode & RTLD_MODEMASK)
2326 == RTLD_NOW, &obj_rtld, &lockstate)) == -1) {
2329 if (obj->refcount == 0)
2333 /* Make list of init functions to call. */
2334 initlist_add_objects(obj, &obj->next, &initlist);
2339 * Bump the reference counts for objects on this DAG. If
2340 * this is the first dlopen() call for the object that was
2341 * already loaded as a dependency, initialize the dag
2347 if ((lo_flags & RTLD_LO_TRACE) != 0)
2350 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
2351 obj->z_nodelete) && !obj->ref_nodel) {
2352 dbg("obj %s nodelete", obj->path);
2354 obj->z_nodelete = obj->ref_nodel = true;
2358 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
2360 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
2362 /* Call the init functions. */
2363 objlist_call_init(&initlist, &lockstate);
2364 objlist_clear(&initlist);
2365 lock_release(rtld_bind_lock, &lockstate);
2368 trace_loaded_objects(obj);
2369 lock_release(rtld_bind_lock, &lockstate);
2374 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
2378 const Obj_Entry *obj, *defobj;
2381 RtldLockState lockstate;
2386 symlook_init(&req, name);
2388 req.flags = flags | SYMLOOK_IN_PLT;
2389 req.lockstate = &lockstate;
2391 rlock_acquire(rtld_bind_lock, &lockstate);
2392 if (sigsetjmp(lockstate.env, 0) != 0)
2393 lock_upgrade(rtld_bind_lock, &lockstate);
2394 if (handle == NULL || handle == RTLD_NEXT ||
2395 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
2397 if ((obj = obj_from_addr(retaddr)) == NULL) {
2398 _rtld_error("Cannot determine caller's shared object");
2399 lock_release(rtld_bind_lock, &lockstate);
2402 if (handle == NULL) { /* Just the caller's shared object. */
2403 res = symlook_obj(&req, obj);
2406 defobj = req.defobj_out;
2408 } else if (handle == RTLD_NEXT || /* Objects after caller's */
2409 handle == RTLD_SELF) { /* ... caller included */
2410 if (handle == RTLD_NEXT)
2412 for (; obj != NULL; obj = obj->next) {
2413 res = symlook_obj(&req, obj);
2416 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) {
2418 defobj = req.defobj_out;
2419 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2425 * Search the dynamic linker itself, and possibly resolve the
2426 * symbol from there. This is how the application links to
2427 * dynamic linker services such as dlopen.
2429 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2430 res = symlook_obj(&req, &obj_rtld);
2431 if (res == 0 && is_exported(req.sym_out)) {
2433 defobj = req.defobj_out;
2437 assert(handle == RTLD_DEFAULT);
2438 res = symlook_default(&req, obj);
2440 defobj = req.defobj_out;
2445 if ((obj = dlcheck(handle)) == NULL) {
2446 lock_release(rtld_bind_lock, &lockstate);
2450 donelist_init(&donelist);
2451 if (obj->mainprog) {
2452 /* Search main program and all libraries loaded by it. */
2453 res = symlook_list(&req, &list_main, &donelist);
2456 defobj = req.defobj_out;
2459 * We do not distinguish between 'main' object and
2460 * global scope. If symbol is not defined by objects
2461 * loaded at startup, continue search among
2462 * dynamically loaded objects with RTLD_GLOBAL scope.
2464 res = symlook_list(&req, &list_global, &donelist);
2467 defobj = req.defobj_out;
2473 /* Search the whole DAG rooted at the given object. */
2475 fake.obj = (Obj_Entry *)obj;
2477 res = symlook_needed(&req, &fake, &donelist);
2480 defobj = req.defobj_out;
2486 lock_release(rtld_bind_lock, &lockstate);
2489 * The value required by the caller is derived from the value
2490 * of the symbol. For the ia64 architecture, we need to
2491 * construct a function descriptor which the caller can use to
2492 * call the function with the right 'gp' value. For other
2493 * architectures and for non-functions, the value is simply
2494 * the relocated value of the symbol.
2496 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
2497 return (make_function_pointer(def, defobj));
2499 return (defobj->relocbase + def->st_value);
2502 _rtld_error("Undefined symbol \"%s\"", name);
2503 lock_release(rtld_bind_lock, &lockstate);
2508 dlsym(void *handle, const char *name)
2510 return do_dlsym(handle, name, __builtin_return_address(0), NULL,
2515 dlfunc(void *handle, const char *name)
2522 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
2528 dlvsym(void *handle, const char *name, const char *version)
2532 ventry.name = version;
2534 ventry.hash = elf_hash(version);
2536 return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
2541 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
2543 const Obj_Entry *obj;
2544 RtldLockState lockstate;
2546 rlock_acquire(rtld_bind_lock, &lockstate);
2547 obj = obj_from_addr(addr);
2549 _rtld_error("No shared object contains address");
2550 lock_release(rtld_bind_lock, &lockstate);
2553 rtld_fill_dl_phdr_info(obj, phdr_info);
2554 lock_release(rtld_bind_lock, &lockstate);
2559 dladdr(const void *addr, Dl_info *info)
2561 const Obj_Entry *obj;
2564 unsigned long symoffset;
2565 RtldLockState lockstate;
2567 rlock_acquire(rtld_bind_lock, &lockstate);
2568 obj = obj_from_addr(addr);
2570 _rtld_error("No shared object contains address");
2571 lock_release(rtld_bind_lock, &lockstate);
2574 info->dli_fname = obj->path;
2575 info->dli_fbase = obj->mapbase;
2576 info->dli_saddr = NULL;
2577 info->dli_sname = NULL;
2580 * Walk the symbol list looking for the symbol whose address is
2581 * closest to the address sent in.
2583 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
2584 def = obj->symtab + symoffset;
2587 * For skip the symbol if st_shndx is either SHN_UNDEF or
2590 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
2594 * If the symbol is greater than the specified address, or if it
2595 * is further away from addr than the current nearest symbol,
2598 symbol_addr = obj->relocbase + def->st_value;
2599 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
2602 /* Update our idea of the nearest symbol. */
2603 info->dli_sname = obj->strtab + def->st_name;
2604 info->dli_saddr = symbol_addr;
2607 if (info->dli_saddr == addr)
2610 lock_release(rtld_bind_lock, &lockstate);
2615 dlinfo(void *handle, int request, void *p)
2617 const Obj_Entry *obj;
2618 RtldLockState lockstate;
2621 rlock_acquire(rtld_bind_lock, &lockstate);
2623 if (handle == NULL || handle == RTLD_SELF) {
2626 retaddr = __builtin_return_address(0); /* __GNUC__ only */
2627 if ((obj = obj_from_addr(retaddr)) == NULL)
2628 _rtld_error("Cannot determine caller's shared object");
2630 obj = dlcheck(handle);
2633 lock_release(rtld_bind_lock, &lockstate);
2639 case RTLD_DI_LINKMAP:
2640 *((struct link_map const **)p) = &obj->linkmap;
2642 case RTLD_DI_ORIGIN:
2643 error = rtld_dirname(obj->path, p);
2646 case RTLD_DI_SERINFOSIZE:
2647 case RTLD_DI_SERINFO:
2648 error = do_search_info(obj, request, (struct dl_serinfo *)p);
2652 _rtld_error("Invalid request %d passed to dlinfo()", request);
2656 lock_release(rtld_bind_lock, &lockstate);
2662 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
2665 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
2666 phdr_info->dlpi_name = STAILQ_FIRST(&obj->names) ?
2667 STAILQ_FIRST(&obj->names)->name : obj->path;
2668 phdr_info->dlpi_phdr = obj->phdr;
2669 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
2670 phdr_info->dlpi_tls_modid = obj->tlsindex;
2671 phdr_info->dlpi_tls_data = obj->tlsinit;
2672 phdr_info->dlpi_adds = obj_loads;
2673 phdr_info->dlpi_subs = obj_loads - obj_count;
2677 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
2679 struct dl_phdr_info phdr_info;
2680 const Obj_Entry *obj;
2681 RtldLockState bind_lockstate, phdr_lockstate;
2684 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
2685 rlock_acquire(rtld_bind_lock, &bind_lockstate);
2689 for (obj = obj_list; obj != NULL; obj = obj->next) {
2690 rtld_fill_dl_phdr_info(obj, &phdr_info);
2691 if ((error = callback(&phdr_info, sizeof phdr_info, param)) != 0)
2695 lock_release(rtld_bind_lock, &bind_lockstate);
2696 lock_release(rtld_phdr_lock, &phdr_lockstate);
2701 struct fill_search_info_args {
2704 Dl_serinfo *serinfo;
2705 Dl_serpath *serpath;
2710 fill_search_info(const char *dir, size_t dirlen, void *param)
2712 struct fill_search_info_args *arg;
2716 if (arg->request == RTLD_DI_SERINFOSIZE) {
2717 arg->serinfo->dls_cnt ++;
2718 arg->serinfo->dls_size += sizeof(Dl_serpath) + dirlen + 1;
2720 struct dl_serpath *s_entry;
2722 s_entry = arg->serpath;
2723 s_entry->dls_name = arg->strspace;
2724 s_entry->dls_flags = arg->flags;
2726 strncpy(arg->strspace, dir, dirlen);
2727 arg->strspace[dirlen] = '\0';
2729 arg->strspace += dirlen + 1;
2737 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
2739 struct dl_serinfo _info;
2740 struct fill_search_info_args args;
2742 args.request = RTLD_DI_SERINFOSIZE;
2743 args.serinfo = &_info;
2745 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2748 path_enumerate(ld_library_path, fill_search_info, &args);
2749 path_enumerate(obj->rpath, fill_search_info, &args);
2750 path_enumerate(gethints(), fill_search_info, &args);
2751 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
2754 if (request == RTLD_DI_SERINFOSIZE) {
2755 info->dls_size = _info.dls_size;
2756 info->dls_cnt = _info.dls_cnt;
2760 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
2761 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
2765 args.request = RTLD_DI_SERINFO;
2766 args.serinfo = info;
2767 args.serpath = &info->dls_serpath[0];
2768 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
2770 args.flags = LA_SER_LIBPATH;
2771 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
2774 args.flags = LA_SER_RUNPATH;
2775 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
2778 args.flags = LA_SER_CONFIG;
2779 if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
2782 args.flags = LA_SER_DEFAULT;
2783 if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
2789 rtld_dirname(const char *path, char *bname)
2793 /* Empty or NULL string gets treated as "." */
2794 if (path == NULL || *path == '\0') {
2800 /* Strip trailing slashes */
2801 endp = path + strlen(path) - 1;
2802 while (endp > path && *endp == '/')
2805 /* Find the start of the dir */
2806 while (endp > path && *endp != '/')
2809 /* Either the dir is "/" or there are no slashes */
2811 bname[0] = *endp == '/' ? '/' : '.';
2817 } while (endp > path && *endp == '/');
2820 if (endp - path + 2 > PATH_MAX)
2822 _rtld_error("Filename is too long: %s", path);
2826 strncpy(bname, path, endp - path + 1);
2827 bname[endp - path + 1] = '\0';
2832 rtld_dirname_abs(const char *path, char *base)
2834 char base_rel[PATH_MAX];
2836 if (rtld_dirname(path, base) == -1)
2840 if (getcwd(base_rel, sizeof(base_rel)) == NULL ||
2841 strlcat(base_rel, "/", sizeof(base_rel)) >= sizeof(base_rel) ||
2842 strlcat(base_rel, base, sizeof(base_rel)) >= sizeof(base_rel))
2844 strcpy(base, base_rel);
2849 linkmap_add(Obj_Entry *obj)
2851 struct link_map *l = &obj->linkmap;
2852 struct link_map *prev;
2854 obj->linkmap.l_name = obj->path;
2855 obj->linkmap.l_addr = obj->mapbase;
2856 obj->linkmap.l_ld = obj->dynamic;
2858 /* GDB needs load offset on MIPS to use the symbols */
2859 obj->linkmap.l_offs = obj->relocbase;
2862 if (r_debug.r_map == NULL) {
2868 * Scan to the end of the list, but not past the entry for the
2869 * dynamic linker, which we want to keep at the very end.
2871 for (prev = r_debug.r_map;
2872 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
2873 prev = prev->l_next)
2876 /* Link in the new entry. */
2878 l->l_next = prev->l_next;
2879 if (l->l_next != NULL)
2880 l->l_next->l_prev = l;
2885 linkmap_delete(Obj_Entry *obj)
2887 struct link_map *l = &obj->linkmap;
2889 if (l->l_prev == NULL) {
2890 if ((r_debug.r_map = l->l_next) != NULL)
2891 l->l_next->l_prev = NULL;
2895 if ((l->l_prev->l_next = l->l_next) != NULL)
2896 l->l_next->l_prev = l->l_prev;
2900 * Function for the debugger to set a breakpoint on to gain control.
2902 * The two parameters allow the debugger to easily find and determine
2903 * what the runtime loader is doing and to whom it is doing it.
2905 * When the loadhook trap is hit (r_debug_state, set at program
2906 * initialization), the arguments can be found on the stack:
2908 * +8 struct link_map *m
2909 * +4 struct r_debug *rd
2913 r_debug_state(struct r_debug* rd, struct link_map *m)
2916 * The following is a hack to force the compiler to emit calls to
2917 * this function, even when optimizing. If the function is empty,
2918 * the compiler is not obliged to emit any code for calls to it,
2919 * even when marked __noinline. However, gdb depends on those
2922 __asm __volatile("" : : : "memory");
2926 * Get address of the pointer variable in the main program.
2928 static const void **
2929 get_program_var_addr(const char *name)
2931 const Obj_Entry *obj;
2934 symlook_init(&req, name);
2935 for (obj = obj_main; obj != NULL; obj = obj->next) {
2936 if (symlook_obj(&req, obj) == 0) {
2937 return ((const void **)(req.defobj_out->relocbase +
2938 req.sym_out->st_value));
2945 * Set a pointer variable in the main program to the given value. This
2946 * is used to set key variables such as "environ" before any of the
2947 * init functions are called.
2950 set_program_var(const char *name, const void *value)
2954 if ((addr = get_program_var_addr(name)) != NULL) {
2955 dbg("\"%s\": *%p <-- %p", name, addr, value);
2961 * This is a special version of getenv which is far more efficient
2962 * at finding LD_ environment vars.
2966 _getenv_ld(const char *id)
2970 int idlen = strlen(id);
2972 if (ld_index == LD_ARY_CACHE)
2974 if (ld_index == 0) {
2975 for (i = j = 0; (envp = environ[i]) != NULL && j < LD_ARY_CACHE; ++i) {
2976 if (envp[0] == 'L' && envp[1] == 'D' && envp[2] == '_')
2983 for (i = ld_index - 1; i >= 0; --i) {
2984 if (strncmp(ld_ary[i], id, idlen) == 0 && ld_ary[i][idlen] == '=')
2985 return(ld_ary[i] + idlen + 1);
2991 * Given a symbol name in a referencing object, find the corresponding
2992 * definition of the symbol. Returns a pointer to the symbol, or NULL if
2993 * no definition was found. Returns a pointer to the Obj_Entry of the
2994 * defining object via the reference parameter DEFOBJ_OUT.
2997 symlook_default(SymLook *req, const Obj_Entry *refobj)
3001 const Obj_Entry *defobj;
3002 const Objlist_Entry *elm;
3007 donelist_init(&donelist);
3008 symlook_init_from_req(&req1, req);
3010 /* Look first in the referencing object if linked symbolically. */
3011 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
3012 res = symlook_obj(&req1, refobj);
3015 defobj = req1.defobj_out;
3016 assert(defobj != NULL);
3020 /* Search all objects loaded at program start up. */
3021 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3022 res = symlook_list(&req1, &list_main, &donelist);
3024 (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3026 defobj = req1.defobj_out;
3027 assert(defobj != NULL);
3031 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
3032 STAILQ_FOREACH(elm, &list_global, link) {
3033 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
3035 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
3037 (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3039 defobj = req1.defobj_out;
3040 assert(defobj != NULL);
3044 /* Search all dlopened DAGs containing the referencing object. */
3045 STAILQ_FOREACH(elm, &refobj->dldags, link) {
3046 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
3048 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
3050 (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3052 defobj = req1.defobj_out;
3053 assert(defobj != NULL);
3058 * Search the dynamic linker itself, and possibly resolve the
3059 * symbol from there. This is how the application links to
3060 * dynamic linker services such as dlopen. Only the values listed
3061 * in the "exports" array can be resolved from the dynamic linker.
3063 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3064 res = symlook_obj(&req1, &obj_rtld);
3065 if (res == 0 && is_exported(req1.sym_out)) {
3067 defobj = req1.defobj_out;
3068 assert(defobj != NULL);
3073 assert(defobj != NULL);
3074 req->defobj_out = defobj;
3082 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
3085 const Obj_Entry *defobj;
3086 const Objlist_Entry *elm;
3092 STAILQ_FOREACH(elm, objlist, link) {
3093 if (donelist_check(dlp, elm->obj))
3095 symlook_init_from_req(&req1, req);
3096 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
3097 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3099 defobj = req1.defobj_out;
3100 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3107 req->defobj_out = defobj;
3114 * Search the symbol table of a shared object and all objects needed
3115 * by it for a symbol of the given name. Search order is
3116 * breadth-first. Returns a pointer to the symbol, or NULL if no
3117 * definition was found.
3120 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
3122 const Elf_Sym *def, *def_w;
3123 const Needed_Entry *n;
3124 const Obj_Entry *defobj, *defobj1;
3130 symlook_init_from_req(&req1, req);
3131 for (n = needed; n != NULL; n = n->next) {
3132 if (n->obj == NULL || donelist_check(dlp, n->obj) ||
3133 (res = symlook_obj(&req1, n->obj)) != 0)
3136 defobj = req1.defobj_out;
3137 if (ELF_ST_BIND(def->st_info) != STB_WEAK) {
3138 req->defobj_out = defobj;
3144 * There we come when either symbol definition is not found in
3145 * directly needed objects, or found symbol is weak.
3147 for (n = needed; n != NULL; n = n->next) {
3150 res = symlook_needed(&req1, n->obj->needed, dlp);
3153 def_w = req1.sym_out;
3154 defobj1 = req1.defobj_out;
3155 if (def == NULL || ELF_ST_BIND(def_w->st_info) != STB_WEAK) {
3159 if (ELF_ST_BIND(def_w->st_info) != STB_WEAK)
3164 req->defobj_out = defobj;
3171 * Search the symbol table of a single shared object for a symbol of
3172 * the given name and version, if requested. Returns a pointer to the
3173 * symbol, or NULL if no definition was found. If the object is
3174 * filter, return filtered symbol from filtee.
3176 * The symbol's hash value is passed in for efficiency reasons; that
3177 * eliminates many recomputations of the hash value.
3180 symlook_obj(SymLook *req, const Obj_Entry *obj)
3186 mres = symlook_obj1(req, obj);
3188 if (obj->needed_filtees != NULL) {
3189 load_filtees(__DECONST(Obj_Entry *, obj), 0, req->lockstate);
3190 donelist_init(&donelist);
3191 symlook_init_from_req(&req1, req);
3192 res = symlook_needed(&req1, obj->needed_filtees, &donelist);
3194 req->sym_out = req1.sym_out;
3195 req->defobj_out = req1.defobj_out;
3199 if (obj->needed_aux_filtees != NULL) {
3200 load_filtees(__DECONST(Obj_Entry *, obj), 0, req->lockstate);
3201 donelist_init(&donelist);
3202 symlook_init_from_req(&req1, req);
3203 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
3205 req->sym_out = req1.sym_out;
3206 req->defobj_out = req1.defobj_out;
3215 symlook_obj1(SymLook *req, const Obj_Entry *obj)
3217 unsigned long symnum;
3218 const Elf_Sym *vsymp;
3222 if (obj->buckets == NULL)
3227 symnum = obj->buckets[req->hash % obj->nbuckets];
3229 for (; symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
3230 const Elf_Sym *symp;
3233 if (symnum >= obj->nchains)
3234 return (ESRCH); /* Bad object */
3236 symp = obj->symtab + symnum;
3237 strp = obj->strtab + symp->st_name;
3239 switch (ELF_ST_TYPE(symp->st_info)) {
3243 if (symp->st_value == 0)
3247 if (symp->st_shndx != SHN_UNDEF)
3249 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
3250 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
3256 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
3259 if (req->ventry == NULL) {
3260 if (obj->versyms != NULL) {
3261 verndx = VER_NDX(obj->versyms[symnum]);
3262 if (verndx > obj->vernum) {
3263 _rtld_error("%s: symbol %s references wrong version %d",
3264 obj->path, obj->strtab + symnum, verndx);
3268 * If we are not called from dlsym (i.e. this is a normal
3269 * relocation from unversioned binary), accept the symbol
3270 * immediately if it happens to have first version after
3271 * this shared object became versioned. Otherwise, if
3272 * symbol is versioned and not hidden, remember it. If it
3273 * is the only symbol with this name exported by the
3274 * shared object, it will be returned as a match at the
3275 * end of the function. If symbol is global (verndx < 2)
3276 * accept it unconditionally.
3278 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
3279 verndx == VER_NDX_GIVEN) {
3280 req->sym_out = symp;
3281 req->defobj_out = obj;
3284 else if (verndx >= VER_NDX_GIVEN) {
3285 if ((obj->versyms[symnum] & VER_NDX_HIDDEN) == 0) {
3293 req->sym_out = symp;
3294 req->defobj_out = obj;
3297 if (obj->versyms == NULL) {
3298 if (object_match_name(obj, req->ventry->name)) {
3299 _rtld_error("%s: object %s should provide version %s for "
3300 "symbol %s", obj_rtld.path, obj->path,
3301 req->ventry->name, obj->strtab + symnum);
3305 verndx = VER_NDX(obj->versyms[symnum]);
3306 if (verndx > obj->vernum) {
3307 _rtld_error("%s: symbol %s references wrong version %d",
3308 obj->path, obj->strtab + symnum, verndx);
3311 if (obj->vertab[verndx].hash != req->ventry->hash ||
3312 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
3314 * Version does not match. Look if this is a global symbol
3315 * and if it is not hidden. If global symbol (verndx < 2)
3316 * is available, use it. Do not return symbol if we are
3317 * called by dlvsym, because dlvsym looks for a specific
3318 * version and default one is not what dlvsym wants.
3320 if ((req->flags & SYMLOOK_DLSYM) ||
3321 (obj->versyms[symnum] & VER_NDX_HIDDEN) ||
3322 (verndx >= VER_NDX_GIVEN))
3326 req->sym_out = symp;
3327 req->defobj_out = obj;
3332 req->sym_out = vsymp;
3333 req->defobj_out = obj;
3340 trace_loaded_objects(Obj_Entry *obj)
3342 const char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
3345 if ((main_local = _getenv_ld("LD_TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
3348 if ((fmt1 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT1")) == NULL)
3349 fmt1 = "\t%o => %p (%x)\n";
3351 if ((fmt2 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT2")) == NULL)
3352 fmt2 = "\t%o (%x)\n";
3354 list_containers = _getenv_ld("LD_TRACE_LOADED_OBJECTS_ALL");
3356 for (; obj; obj = obj->next) {
3357 Needed_Entry *needed;
3361 if (list_containers && obj->needed != NULL)
3362 rtld_printf("%s:\n", obj->path);
3363 for (needed = obj->needed; needed; needed = needed->next) {
3364 if (needed->obj != NULL) {
3365 if (needed->obj->traced && !list_containers)
3367 needed->obj->traced = true;
3368 path = needed->obj->path;
3372 name = (char *)obj->strtab + needed->name;
3373 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
3375 fmt = is_lib ? fmt1 : fmt2;
3376 while ((c = *fmt++) != '\0') {
3402 rtld_putstr(main_local);
3405 rtld_putstr(obj_main->path);
3414 rtld_printf("%p", needed->obj ? needed->obj->mapbase :
3427 * Unload a dlopened object and its dependencies from memory and from
3428 * our data structures. It is assumed that the DAG rooted in the
3429 * object has already been unreferenced, and that the object has a
3430 * reference count of 0.
3433 unload_object(Obj_Entry *root)
3438 assert(root->refcount == 0);
3441 * Pass over the DAG removing unreferenced objects from
3442 * appropriate lists.
3444 unlink_object(root);
3446 /* Unmap all objects that are no longer referenced. */
3447 linkp = &obj_list->next;
3448 while ((obj = *linkp) != NULL) {
3449 if (obj->refcount == 0) {
3450 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
3452 dbg("unloading \"%s\"", obj->path);
3453 unload_filtees(root);
3454 munmap(obj->mapbase, obj->mapsize);
3455 linkmap_delete(obj);
3466 unlink_object(Obj_Entry *root)
3470 if (root->refcount == 0) {
3471 /* Remove the object from the RTLD_GLOBAL list. */
3472 objlist_remove(&list_global, root);
3474 /* Remove the object from all objects' DAG lists. */
3475 STAILQ_FOREACH(elm, &root->dagmembers, link) {
3476 objlist_remove(&elm->obj->dldags, root);
3477 if (elm->obj != root)
3478 unlink_object(elm->obj);
3484 ref_dag(Obj_Entry *root)
3488 assert(root->dag_inited);
3489 STAILQ_FOREACH(elm, &root->dagmembers, link)
3490 elm->obj->refcount++;
3494 unref_dag(Obj_Entry *root)
3498 assert(root->dag_inited);
3499 STAILQ_FOREACH(elm, &root->dagmembers, link)
3500 elm->obj->refcount--;
3504 * Common code for MD __tls_get_addr().
3507 tls_get_addr_common(Elf_Addr** dtvp, int index, size_t offset)
3509 Elf_Addr* dtv = *dtvp;
3510 RtldLockState lockstate;
3512 /* Check dtv generation in case new modules have arrived */
3513 if (dtv[0] != tls_dtv_generation) {
3517 wlock_acquire(rtld_bind_lock, &lockstate);
3518 newdtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
3520 if (to_copy > tls_max_index)
3521 to_copy = tls_max_index;
3522 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
3523 newdtv[0] = tls_dtv_generation;
3524 newdtv[1] = tls_max_index;
3526 lock_release(rtld_bind_lock, &lockstate);
3527 dtv = *dtvp = newdtv;
3530 /* Dynamically allocate module TLS if necessary */
3531 if (!dtv[index + 1]) {
3532 /* Signal safe, wlock will block out signals. */
3533 wlock_acquire(rtld_bind_lock, &lockstate);
3534 if (!dtv[index + 1])
3535 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
3536 lock_release(rtld_bind_lock, &lockstate);
3538 return (void*) (dtv[index + 1] + offset);
3541 #if defined(RTLD_STATIC_TLS_VARIANT_II)
3544 * Allocate the static TLS area. Return a pointer to the TCB. The
3545 * static area is based on negative offsets relative to the tcb.
3547 * The TCB contains an errno pointer for the system call layer, but because
3548 * we are the RTLD we really have no idea how the caller was compiled so
3549 * the information has to be passed in. errno can either be:
3551 * type 0 errno is a simple non-TLS global pointer.
3552 * (special case for e.g. libc_rtld)
3553 * type 1 errno accessed by GOT entry (dynamically linked programs)
3554 * type 2 errno accessed by %gs:OFFSET (statically linked programs)
3557 allocate_tls(Obj_Entry *objs)
3562 struct tls_tcb *tcb;
3567 * Allocate the new TCB. static TLS storage is placed just before the
3568 * TCB to support the %gs:OFFSET (negative offset) model.
3570 data_size = (tls_static_space + RTLD_STATIC_TLS_ALIGN_MASK) &
3571 ~RTLD_STATIC_TLS_ALIGN_MASK;
3572 tcb = malloc(data_size + sizeof(*tcb));
3573 tcb = (void *)((char *)tcb + data_size); /* actual tcb location */
3575 dtv_size = (tls_max_index + 2) * sizeof(Elf_Addr);
3576 dtv = malloc(dtv_size);
3577 bzero(dtv, dtv_size);
3579 #ifdef RTLD_TCB_HAS_SELF_POINTER
3580 tcb->tcb_self = tcb;
3583 tcb->tcb_pthread = NULL;
3585 dtv[0] = tls_dtv_generation;
3586 dtv[1] = tls_max_index;
3588 for (obj = objs; obj; obj = obj->next) {
3589 if (obj->tlsoffset) {
3590 addr = (Elf_Addr)tcb - obj->tlsoffset;
3591 memset((void *)(addr + obj->tlsinitsize),
3592 0, obj->tlssize - obj->tlsinitsize);
3594 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
3595 dtv[obj->tlsindex + 1] = addr;
3602 free_tls(struct tls_tcb *tcb)
3606 Elf_Addr tls_start, tls_end;
3609 data_size = (tls_static_space + RTLD_STATIC_TLS_ALIGN_MASK) &
3610 ~RTLD_STATIC_TLS_ALIGN_MASK;
3614 tls_end = (Elf_Addr)tcb;
3615 tls_start = (Elf_Addr)tcb - data_size;
3616 for (i = 0; i < dtv_size; i++) {
3617 if (dtv[i+2] != 0 && (dtv[i+2] < tls_start || dtv[i+2] > tls_end)) {
3618 free((void *)dtv[i+2]);
3622 free((void*) tls_start);
3626 #error "Unsupported TLS layout"
3630 * Allocate TLS block for module with given index.
3633 allocate_module_tls(int index)
3638 for (obj = obj_list; obj; obj = obj->next) {
3639 if (obj->tlsindex == index)
3643 _rtld_error("Can't find module with TLS index %d", index);
3647 p = malloc(obj->tlssize);
3649 _rtld_error("Cannot allocate TLS block for index %d", index);
3652 memcpy(p, obj->tlsinit, obj->tlsinitsize);
3653 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
3659 allocate_tls_offset(Obj_Entry *obj)
3666 if (obj->tlssize == 0) {
3667 obj->tls_done = true;
3671 if (obj->tlsindex == 1)
3672 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
3674 off = calculate_tls_offset(tls_last_offset, tls_last_size,
3675 obj->tlssize, obj->tlsalign);
3678 * If we have already fixed the size of the static TLS block, we
3679 * must stay within that size. When allocating the static TLS, we
3680 * leave a small amount of space spare to be used for dynamically
3681 * loading modules which use static TLS.
3683 if (tls_static_space) {
3684 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
3688 tls_last_offset = obj->tlsoffset = off;
3689 tls_last_size = obj->tlssize;
3690 obj->tls_done = true;
3696 free_tls_offset(Obj_Entry *obj)
3698 #ifdef RTLD_STATIC_TLS_VARIANT_II
3700 * If we were the last thing to allocate out of the static TLS
3701 * block, we give our space back to the 'allocator'. This is a
3702 * simplistic workaround to allow libGL.so.1 to be loaded and
3703 * unloaded multiple times. We only handle the Variant II
3704 * mechanism for now - this really needs a proper allocator.
3706 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
3707 == calculate_tls_end(tls_last_offset, tls_last_size)) {
3708 tls_last_offset -= obj->tlssize;
3715 _rtld_allocate_tls(void)
3717 struct tls_tcb *new_tcb;
3718 RtldLockState lockstate;
3720 wlock_acquire(rtld_bind_lock, &lockstate);
3721 new_tcb = allocate_tls(obj_list);
3722 lock_release(rtld_bind_lock, &lockstate);
3727 _rtld_free_tls(struct tls_tcb *tcb)
3729 RtldLockState lockstate;
3731 wlock_acquire(rtld_bind_lock, &lockstate);
3733 lock_release(rtld_bind_lock, &lockstate);
3737 object_add_name(Obj_Entry *obj, const char *name)
3743 entry = malloc(sizeof(Name_Entry) + len);
3745 if (entry != NULL) {
3746 strcpy(entry->name, name);
3747 STAILQ_INSERT_TAIL(&obj->names, entry, link);
3752 object_match_name(const Obj_Entry *obj, const char *name)
3756 STAILQ_FOREACH(entry, &obj->names, link) {
3757 if (strcmp(name, entry->name) == 0)
3764 locate_dependency(const Obj_Entry *obj, const char *name)
3766 const Objlist_Entry *entry;
3767 const Needed_Entry *needed;
3769 STAILQ_FOREACH(entry, &list_main, link) {
3770 if (object_match_name(entry->obj, name))
3774 for (needed = obj->needed; needed != NULL; needed = needed->next) {
3775 if (strcmp(obj->strtab + needed->name, name) == 0 ||
3776 (needed->obj != NULL && object_match_name(needed->obj, name))) {
3778 * If there is DT_NEEDED for the name we are looking for,
3779 * we are all set. Note that object might not be found if
3780 * dependency was not loaded yet, so the function can
3781 * return NULL here. This is expected and handled
3782 * properly by the caller.
3784 return (needed->obj);
3787 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
3793 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
3794 const Elf_Vernaux *vna)
3796 const Elf_Verdef *vd;
3797 const char *vername;
3799 vername = refobj->strtab + vna->vna_name;
3800 vd = depobj->verdef;
3802 _rtld_error("%s: version %s required by %s not defined",
3803 depobj->path, vername, refobj->path);
3807 if (vd->vd_version != VER_DEF_CURRENT) {
3808 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
3809 depobj->path, vd->vd_version);
3812 if (vna->vna_hash == vd->vd_hash) {
3813 const Elf_Verdaux *aux = (const Elf_Verdaux *)
3814 ((char *)vd + vd->vd_aux);
3815 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
3818 if (vd->vd_next == 0)
3820 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3822 if (vna->vna_flags & VER_FLG_WEAK)
3824 _rtld_error("%s: version %s required by %s not found",
3825 depobj->path, vername, refobj->path);
3830 rtld_verify_object_versions(Obj_Entry *obj)
3832 const Elf_Verneed *vn;
3833 const Elf_Verdef *vd;
3834 const Elf_Verdaux *vda;
3835 const Elf_Vernaux *vna;
3836 const Obj_Entry *depobj;
3837 int maxvernum, vernum;
3841 * Walk over defined and required version records and figure out
3842 * max index used by any of them. Do very basic sanity checking
3846 while (vn != NULL) {
3847 if (vn->vn_version != VER_NEED_CURRENT) {
3848 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
3849 obj->path, vn->vn_version);
3852 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
3854 vernum = VER_NEED_IDX(vna->vna_other);
3855 if (vernum > maxvernum)
3857 if (vna->vna_next == 0)
3859 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
3861 if (vn->vn_next == 0)
3863 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
3867 while (vd != NULL) {
3868 if (vd->vd_version != VER_DEF_CURRENT) {
3869 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
3870 obj->path, vd->vd_version);
3873 vernum = VER_DEF_IDX(vd->vd_ndx);
3874 if (vernum > maxvernum)
3876 if (vd->vd_next == 0)
3878 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3885 * Store version information in array indexable by version index.
3886 * Verify that object version requirements are satisfied along the
3889 obj->vernum = maxvernum + 1;
3890 obj->vertab = calloc(obj->vernum, sizeof(Ver_Entry));
3893 while (vd != NULL) {
3894 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
3895 vernum = VER_DEF_IDX(vd->vd_ndx);
3896 assert(vernum <= maxvernum);
3897 vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
3898 obj->vertab[vernum].hash = vd->vd_hash;
3899 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
3900 obj->vertab[vernum].file = NULL;
3901 obj->vertab[vernum].flags = 0;
3903 if (vd->vd_next == 0)
3905 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3909 while (vn != NULL) {
3910 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
3913 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
3915 if (check_object_provided_version(obj, depobj, vna))
3917 vernum = VER_NEED_IDX(vna->vna_other);
3918 assert(vernum <= maxvernum);
3919 obj->vertab[vernum].hash = vna->vna_hash;
3920 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
3921 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
3922 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
3923 VER_INFO_HIDDEN : 0;
3924 if (vna->vna_next == 0)
3926 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
3928 if (vn->vn_next == 0)
3930 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
3936 rtld_verify_versions(const Objlist *objlist)
3938 Objlist_Entry *entry;
3942 STAILQ_FOREACH(entry, objlist, link) {
3944 * Skip dummy objects or objects that have their version requirements
3947 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
3949 if (rtld_verify_object_versions(entry->obj) == -1) {
3951 if (ld_tracing == NULL)
3955 if (rc == 0 || ld_tracing != NULL)
3956 rc = rtld_verify_object_versions(&obj_rtld);
3961 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
3966 vernum = VER_NDX(obj->versyms[symnum]);
3967 if (vernum >= obj->vernum) {
3968 _rtld_error("%s: symbol %s has wrong verneed value %d",
3969 obj->path, obj->strtab + symnum, vernum);
3970 } else if (obj->vertab[vernum].hash != 0) {
3971 return &obj->vertab[vernum];
3978 symlook_init(SymLook *dst, const char *name)
3981 bzero(dst, sizeof(*dst));
3983 dst->hash = elf_hash(name);
3987 symlook_init_from_req(SymLook *dst, const SymLook *src)
3990 dst->name = src->name;
3991 dst->hash = src->hash;
3992 dst->ventry = src->ventry;
3993 dst->flags = src->flags;
3994 dst->defobj_out = NULL;
3995 dst->sym_out = NULL;
3996 dst->lockstate = src->lockstate;
3999 #ifdef ENABLE_OSRELDATE
4001 * Overrides for libc_pic-provided functions.
4005 __getosreldate(void)
4015 oid[1] = KERN_OSRELDATE;
4017 len = sizeof(osrel);
4018 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
4019 if (error == 0 && osrel > 0 && len == sizeof(osrel))
4026 * No unresolved symbols for rtld.
4029 __pthread_cxa_finalize(struct dl_phdr_info *a)