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 * This structure provides a reentrant way to keep a list of objects and
77 * check which ones have already been processed in some way.
79 typedef struct Struct_DoneList {
80 const Obj_Entry **objs; /* Array of object pointers */
81 unsigned int num_alloc; /* Allocated size of the array */
82 unsigned int num_used; /* Number of array slots used */
86 * Function declarations.
88 static const char *_getenv_ld(const char *id);
89 static void die(void) __dead2;
90 static void digest_dynamic1(Obj_Entry *, int, const Elf_Dyn **,
92 static void digest_dynamic2(Obj_Entry *, const Elf_Dyn *, const Elf_Dyn *);
93 static void digest_dynamic(Obj_Entry *, int);
94 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
95 static Obj_Entry *dlcheck(void *);
96 static Obj_Entry *do_load_object(int, const char *, char *, struct stat *, int);
97 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
98 static bool donelist_check(DoneList *, const Obj_Entry *);
99 static void errmsg_restore(char *);
100 static char *errmsg_save(void);
101 static void *fill_search_info(const char *, size_t, void *);
102 static char *find_library(const char *, const Obj_Entry *);
103 static const char *gethints(void);
104 static void init_dag(Obj_Entry *);
105 static void init_dag1(Obj_Entry *, Obj_Entry *, DoneList *);
106 static void init_rtld(caddr_t, Elf_Auxinfo **);
107 static void initlist_add_neededs(Needed_Entry *, Objlist *);
108 static void initlist_add_objects(Obj_Entry *, Obj_Entry **, Objlist *);
109 static bool is_exported(const Elf_Sym *);
110 static void linkmap_add(Obj_Entry *);
111 static void linkmap_delete(Obj_Entry *);
112 static int load_needed_objects(Obj_Entry *, int);
113 static int load_preload_objects(void);
114 static Obj_Entry *load_object(const char *, const Obj_Entry *, int);
115 static Obj_Entry *obj_from_addr(const void *);
116 static void objlist_call_fini(Objlist *, Obj_Entry *, RtldLockState *);
117 static void objlist_call_init(Objlist *, RtldLockState *);
118 static void objlist_clear(Objlist *);
119 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
120 static void objlist_init(Objlist *);
121 static void objlist_push_head(Objlist *, Obj_Entry *);
122 static void objlist_push_tail(Objlist *, Obj_Entry *);
123 static void objlist_remove(Objlist *, Obj_Entry *);
124 static void *path_enumerate(const char *, path_enum_proc, void *);
125 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *);
126 static int rtld_dirname(const char *, char *);
127 static int rtld_dirname_abs(const char *, char *);
128 static void rtld_exit(void);
129 static char *search_library_path(const char *, const char *);
130 static const void **get_program_var_addr(const char *);
131 static void set_program_var(const char *, const void *);
132 static const Elf_Sym *symlook_default(const char *, unsigned long,
133 const Obj_Entry *, const Obj_Entry **, const Ver_Entry *, int);
134 static const Elf_Sym *symlook_list(const char *, unsigned long, const Objlist *,
135 const Obj_Entry **, const Ver_Entry *, int, DoneList *);
136 static const Elf_Sym *symlook_needed(const char *, unsigned long,
137 const Needed_Entry *, const Obj_Entry **, const Ver_Entry *,
139 static void trace_loaded_objects(Obj_Entry *);
140 static void unlink_object(Obj_Entry *);
141 static void unload_object(Obj_Entry *);
142 static void unref_dag(Obj_Entry *);
143 static void ref_dag(Obj_Entry *);
144 static int origin_subst_one(char **, const char *, const char *,
145 const char *, char *);
146 static char *origin_subst(const char *, const char *);
147 static int rtld_verify_versions(const Objlist *);
148 static int rtld_verify_object_versions(Obj_Entry *);
149 static void object_add_name(Obj_Entry *, const char *);
150 static int object_match_name(const Obj_Entry *, const char *);
151 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
152 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
153 struct dl_phdr_info *phdr_info);
155 void r_debug_state(struct r_debug *, struct link_map *) __noinline;
160 static char *error_message; /* Message for dlerror(), or NULL */
161 struct r_debug r_debug; /* for GDB; */
162 static bool libmap_disable; /* Disable libmap */
163 static char *libmap_override; /* Maps to use in addition to libmap.conf */
164 static bool trust; /* False for setuid and setgid programs */
165 static bool dangerous_ld_env; /* True if environment variables have been
166 used to affect the libraries loaded */
167 static const char *ld_bind_now; /* Environment variable for immediate binding */
168 static const char *ld_debug; /* Environment variable for debugging */
169 static const char *ld_library_path; /* Environment variable for search path */
170 static char *ld_preload; /* Environment variable for libraries to
172 static const char *ld_elf_hints_path; /* Environment variable for alternative hints path */
173 static const char *ld_tracing; /* Called from ldd to print libs */
174 static const char *ld_utrace; /* Use utrace() to log events. */
175 static int (*rtld_functrace)( /* Optional function call tracing hook */
176 const char *caller_obj,
177 const char *callee_obj,
178 const char *callee_func,
180 static Obj_Entry *rtld_functrace_obj; /* Object thereof */
181 static Obj_Entry *obj_list; /* Head of linked list of shared objects */
182 static Obj_Entry **obj_tail; /* Link field of last object in list */
183 static Obj_Entry **preload_tail;
184 static Obj_Entry *obj_main; /* The main program shared object */
185 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
186 static unsigned int obj_count; /* Number of objects in obj_list */
187 static unsigned int obj_loads; /* Number of objects in obj_list */
189 static int ld_resident; /* Non-zero if resident */
190 static const char *ld_ary[LD_ARY_CACHE];
192 static Objlist initlist;
194 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
195 STAILQ_HEAD_INITIALIZER(list_global);
196 static Objlist list_main = /* Objects loaded at program startup */
197 STAILQ_HEAD_INITIALIZER(list_main);
198 static Objlist list_fini = /* Objects needing fini() calls */
199 STAILQ_HEAD_INITIALIZER(list_fini);
201 static Elf_Sym sym_zero; /* For resolving undefined weak refs. */
203 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
205 extern Elf_Dyn _DYNAMIC;
206 #pragma weak _DYNAMIC
207 #ifndef RTLD_IS_DYNAMIC
208 #define RTLD_IS_DYNAMIC() (&_DYNAMIC != NULL)
211 #ifdef ENABLE_OSRELDATE
216 * These are the functions the dynamic linker exports to application
217 * programs. They are the only symbols the dynamic linker is willing
218 * to export from itself.
220 static func_ptr_type exports[] = {
221 (func_ptr_type) &_rtld_error,
222 (func_ptr_type) &dlclose,
223 (func_ptr_type) &dlerror,
224 (func_ptr_type) &dlopen,
225 (func_ptr_type) &dlfunc,
226 (func_ptr_type) &dlsym,
227 (func_ptr_type) &dlvsym,
228 (func_ptr_type) &dladdr,
229 (func_ptr_type) &dlinfo,
230 (func_ptr_type) &dl_iterate_phdr,
232 (func_ptr_type) &___tls_get_addr,
234 (func_ptr_type) &__tls_get_addr,
235 (func_ptr_type) &__tls_get_addr_tcb,
236 (func_ptr_type) &_rtld_allocate_tls,
237 (func_ptr_type) &_rtld_free_tls,
238 (func_ptr_type) &_rtld_call_init,
239 (func_ptr_type) &_rtld_thread_init,
240 (func_ptr_type) &_rtld_addr_phdr,
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 DRAWF2 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")
417 _rtld_error("environment corrupt; aborting");
421 ld_debug = _getenv_ld("LD_DEBUG");
422 ld_library_path = _getenv_ld("LD_LIBRARY_PATH");
423 ld_preload = (char *)_getenv_ld("LD_PRELOAD");
424 ld_elf_hints_path = _getenv_ld("LD_ELF_HINTS_PATH");
425 libmap_override = (char *)_getenv_ld("LD_LIBMAP");
426 libmap_disable = _getenv_ld("LD_LIBMAP_DISABLE") != NULL;
427 dangerous_ld_env = (ld_library_path != NULL)
428 || (ld_preload != NULL)
429 || (ld_elf_hints_path != NULL)
430 || (libmap_override != NULL)
433 ld_tracing = _getenv_ld("LD_TRACE_LOADED_OBJECTS");
434 ld_utrace = _getenv_ld("LD_UTRACE");
436 if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0)
437 ld_elf_hints_path = _PATH_ELF_HINTS;
439 if (ld_debug != NULL && *ld_debug != '\0')
441 dbg("%s is initialized, base address = %p", __progname,
442 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
443 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
444 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
446 dbg("initializing thread locks");
450 * If we are resident we can skip work that we have already done.
451 * Note that the stack is reset and there is no Elf_Auxinfo
452 * when running from a resident image, and the static globals setup
453 * between here and resident_skip will have already been setup.
459 * Load the main program, or process its program header if it is
462 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
463 int fd = aux_info[AT_EXECFD]->a_un.a_val;
464 dbg("loading main program");
465 obj_main = map_object(fd, argv0, NULL);
467 if (obj_main == NULL)
469 } else { /* Main program already loaded. */
470 const Elf_Phdr *phdr;
474 dbg("processing main program's program header");
475 assert(aux_info[AT_PHDR] != NULL);
476 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
477 assert(aux_info[AT_PHNUM] != NULL);
478 phnum = aux_info[AT_PHNUM]->a_un.a_val;
479 assert(aux_info[AT_PHENT] != NULL);
480 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
481 assert(aux_info[AT_ENTRY] != NULL);
482 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
483 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
487 char buf[MAXPATHLEN];
488 if (aux_info[AT_EXECPATH] != 0) {
491 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
492 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
493 if (kexecpath[0] == '/')
494 obj_main->path = kexecpath;
495 else if (getcwd(buf, sizeof(buf)) == NULL ||
496 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
497 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
498 obj_main->path = xstrdup(argv0);
500 obj_main->path = xstrdup(buf);
502 char resolved[MAXPATHLEN];
503 dbg("No AT_EXECPATH");
504 if (argv0[0] == '/') {
505 if (realpath(argv0, resolved) != NULL)
506 obj_main->path = xstrdup(resolved);
508 obj_main->path = xstrdup(argv0);
510 if (getcwd(buf, sizeof(buf)) != NULL
511 && strlcat(buf, "/", sizeof(buf)) < sizeof(buf)
512 && strlcat(buf, argv0, sizeof (buf)) < sizeof(buf)
513 && access(buf, R_OK) == 0
514 && realpath(buf, resolved) != NULL)
515 obj_main->path = xstrdup(resolved);
517 obj_main->path = xstrdup(argv0);
520 dbg("obj_main path %s", obj_main->path);
521 obj_main->mainprog = true;
524 * Get the actual dynamic linker pathname from the executable if
525 * possible. (It should always be possible.) That ensures that
526 * gdb will find the right dynamic linker even if a non-standard
529 if (obj_main->interp != NULL &&
530 strcmp(obj_main->interp, obj_rtld.path) != 0) {
532 obj_rtld.path = xstrdup(obj_main->interp);
533 __progname = obj_rtld.path;
536 digest_dynamic(obj_main, 0);
538 linkmap_add(obj_main);
539 linkmap_add(&obj_rtld);
541 /* Link the main program into the list of objects. */
542 *obj_tail = obj_main;
543 obj_tail = &obj_main->next;
546 /* Make sure we don't call the main program's init and fini functions. */
547 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
549 /* Initialize a fake symbol for resolving undefined weak references. */
550 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
551 sym_zero.st_shndx = SHN_UNDEF;
552 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
555 libmap_disable = (bool)lm_init(libmap_override);
557 dbg("loading LD_PRELOAD libraries");
558 if (load_preload_objects() == -1)
560 preload_tail = obj_tail;
562 dbg("loading needed objects");
563 if (load_needed_objects(obj_main, 0) == -1)
566 /* Make a list of all objects loaded at startup. */
567 for (obj = obj_list; obj != NULL; obj = obj->next) {
568 objlist_push_tail(&list_main, obj);
572 dbg("checking for required versions");
573 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
578 if (ld_tracing) { /* We're done */
579 trace_loaded_objects(obj_main);
583 if (ld_resident) /* XXX clean this up! */
586 if (_getenv_ld("LD_DUMP_REL_PRE") != NULL) {
587 dump_relocations(obj_main);
591 /* setup TLS for main thread */
592 dbg("initializing initial thread local storage");
593 STAILQ_FOREACH(entry, &list_main, link) {
595 * Allocate all the initial objects out of the static TLS
596 * block even if they didn't ask for it.
598 allocate_tls_offset(entry->obj);
601 tls_static_space = tls_last_offset + RTLD_STATIC_TLS_EXTRA;
604 * Do not try to allocate the TLS here, let libc do it itself.
605 * (crt1 for the program will call _init_tls())
608 if (relocate_objects(obj_main,
609 ld_bind_now != NULL && *ld_bind_now != '\0', &obj_rtld) == -1)
612 dbg("doing copy relocations");
613 if (do_copy_relocations(obj_main) == -1)
618 if (_getenv_ld("LD_RESIDENT_UNREGISTER_NOW")) {
619 if (exec_sys_unregister(-1) < 0) {
620 dbg("exec_sys_unregister failed %d\n", errno);
623 dbg("exec_sys_unregister success\n");
627 if (_getenv_ld("LD_DUMP_REL_POST") != NULL) {
628 dump_relocations(obj_main);
632 dbg("initializing key program variables");
633 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
634 set_program_var("environ", env);
635 set_program_var("__elf_aux_vector", aux);
637 if (_getenv_ld("LD_RESIDENT_REGISTER_NOW")) {
638 extern void resident_start(void);
640 if (exec_sys_register(resident_start) < 0) {
641 dbg("exec_sys_register failed %d\n", errno);
644 dbg("exec_sys_register success\n");
648 /* Make a list of init functions to call. */
649 objlist_init(&initlist);
650 initlist_add_objects(obj_list, preload_tail, &initlist);
652 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
655 * Do NOT call the initlist here, give libc a chance to set up
656 * the initial TLS segment. crt1 will then call _rtld_call_init().
659 dbg("transferring control to program entry point = %p", obj_main->entry);
661 /* Return the exit procedure and the program entry point. */
662 *exit_proc = rtld_exit;
664 return (func_ptr_type) obj_main->entry;
668 * Call the initialization list for dynamically loaded libraries.
669 * (called from crt1.c).
672 _rtld_call_init(void)
674 RtldLockState lockstate;
676 wlock_acquire(rtld_bind_lock, &lockstate);
677 objlist_call_init(&initlist, &lockstate);
678 objlist_clear(&initlist);
679 lock_release(rtld_bind_lock, &lockstate);
683 _rtld_bind(Obj_Entry *obj, Elf_Size reloff, void *stack)
687 const Obj_Entry *defobj;
690 RtldLockState lockstate;
693 rlock_acquire(rtld_bind_lock, &lockstate);
694 if (sigsetjmp(lockstate.env, 0) != 0)
695 lock_upgrade(rtld_bind_lock, &lockstate);
697 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
699 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
701 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
702 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL);
706 target = (Elf_Addr)(defobj->relocbase + def->st_value);
708 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
709 defobj->strtab + def->st_name, basename(obj->path),
710 (void *)target, basename(defobj->path));
713 * If we have a function call tracing hook, and the
714 * hook would like to keep tracing this one function,
715 * prevent the relocation so we will wind up here
716 * the next time again.
718 * We don't want to functrace calls from the functracer
719 * to avoid recursive loops.
721 if (rtld_functrace != NULL && obj != rtld_functrace_obj) {
722 if (rtld_functrace(obj->path,
724 defobj->strtab + def->st_name,
730 target = reloc_jmpslot(where, target, defobj, obj, rel);
731 lock_release(rtld_bind_lock, &lockstate);
736 * Error reporting function. Use it like printf. If formats the message
737 * into a buffer, and sets things up so that the next call to dlerror()
738 * will return the message.
741 _rtld_error(const char *fmt, ...)
743 static char buf[512];
747 rtld_vsnprintf(buf, sizeof buf, fmt, ap);
753 * Return a dynamically-allocated copy of the current error message, if any.
758 return error_message == NULL ? NULL : xstrdup(error_message);
762 * Restore the current error message from a copy which was previously saved
763 * by errmsg_save(). The copy is freed.
766 errmsg_restore(char *saved_msg)
768 if (saved_msg == NULL)
769 error_message = NULL;
771 _rtld_error("%s", saved_msg);
777 basename(const char *name)
779 const char *p = strrchr(name, '/');
780 return p != NULL ? p + 1 : name;
783 static struct utsname uts;
786 origin_subst_one(char **res, const char *real, const char *kw, const char *subst,
796 subst_len = kw_len = 0;
800 if (subst_len == 0) {
801 subst_len = strlen(subst);
805 *res = xmalloc(PATH_MAX);
808 if ((res1 - *res) + subst_len + (p1 - p) >= PATH_MAX) {
809 _rtld_error("Substitution of %s in %s cannot be performed",
811 if (may_free != NULL)
816 memcpy(res1, p, p1 - p);
818 memcpy(res1, subst, subst_len);
823 if (may_free != NULL)
826 *res = xstrdup(real);
830 if (may_free != NULL)
832 if (strlcat(res1, p, PATH_MAX - (res1 - *res)) >= PATH_MAX) {
842 origin_subst(const char *real, const char *origin_path)
844 char *res1, *res2, *res3, *res4;
846 if (uts.sysname[0] == '\0') {
847 if (uname(&uts) != 0) {
848 _rtld_error("utsname failed: %d", errno);
852 if (!origin_subst_one(&res1, real, "$ORIGIN", origin_path, NULL) ||
853 !origin_subst_one(&res2, res1, "$OSNAME", uts.sysname, res1) ||
854 !origin_subst_one(&res3, res2, "$OSREL", uts.release, res2) ||
855 !origin_subst_one(&res4, res3, "$PLATFORM", uts.machine, res3))
863 const char *msg = dlerror();
867 rtld_fdputstr(STDERR_FILENO, msg);
872 * Process a shared object's DYNAMIC section, and save the important
873 * information in its Obj_Entry structure.
876 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
877 const Elf_Dyn **dyn_soname)
880 Needed_Entry **needed_tail = &obj->needed;
881 int plttype = DT_REL;
886 obj->bind_now = false;
887 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
888 switch (dynp->d_tag) {
891 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
895 obj->relsize = dynp->d_un.d_val;
899 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
903 obj->pltrel = (const Elf_Rel *)
904 (obj->relocbase + dynp->d_un.d_ptr);
908 obj->pltrelsize = dynp->d_un.d_val;
912 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
916 obj->relasize = dynp->d_un.d_val;
920 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
924 plttype = dynp->d_un.d_val;
925 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
929 obj->symtab = (const Elf_Sym *)
930 (obj->relocbase + dynp->d_un.d_ptr);
934 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
938 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
942 obj->strsize = dynp->d_un.d_val;
946 obj->verneed = (const Elf_Verneed *) (obj->relocbase +
951 obj->verneednum = dynp->d_un.d_val;
955 obj->verdef = (const Elf_Verdef *) (obj->relocbase +
960 obj->verdefnum = dynp->d_un.d_val;
964 obj->versyms = (const Elf_Versym *)(obj->relocbase +
970 const Elf_Hashelt *hashtab = (const Elf_Hashelt *)
971 (obj->relocbase + dynp->d_un.d_ptr);
972 obj->nbuckets = hashtab[0];
973 obj->nchains = hashtab[1];
974 obj->buckets = hashtab + 2;
975 obj->chains = obj->buckets + obj->nbuckets;
981 Needed_Entry *nep = NEW(Needed_Entry);
982 nep->name = dynp->d_un.d_val;
987 needed_tail = &nep->next;
992 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
1000 obj->symbolic = true;
1004 case DT_RUNPATH: /* XXX: process separately */
1006 * We have to wait until later to process this, because we
1007 * might not have gotten the address of the string table yet.
1017 obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1021 obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1025 /* XXX - not implemented yet */
1027 dbg("Filling in DT_DEBUG entry");
1028 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
1032 if ((dynp->d_un.d_val & DF_ORIGIN) && trust)
1033 obj->z_origin = true;
1034 if (dynp->d_un.d_val & DF_SYMBOLIC)
1035 obj->symbolic = true;
1036 if (dynp->d_un.d_val & DF_TEXTREL)
1037 obj->textrel = true;
1038 if (dynp->d_un.d_val & DF_BIND_NOW)
1039 obj->bind_now = true;
1040 /*if (dynp->d_un.d_val & DF_STATIC_TLS)
1045 if (dynp->d_un.d_val & DF_1_NOOPEN)
1046 obj->z_noopen = true;
1047 if ((dynp->d_un.d_val & DF_1_ORIGIN) && trust)
1048 obj->z_origin = true;
1049 /*if (dynp->d_un.d_val & DF_1_GLOBAL)
1051 if (dynp->d_un.d_val & DF_1_BIND_NOW)
1052 obj->bind_now = true;
1053 if (dynp->d_un.d_val & DF_1_NODELETE)
1054 obj->z_nodelete = true;
1059 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1066 obj->traced = false;
1068 if (plttype == DT_RELA) {
1069 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1071 obj->pltrelasize = obj->pltrelsize;
1072 obj->pltrelsize = 0;
1077 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1078 const Elf_Dyn *dyn_soname)
1081 if (obj->z_origin && obj->origin_path == NULL) {
1082 obj->origin_path = xmalloc(PATH_MAX);
1083 if (rtld_dirname_abs(obj->path, obj->origin_path) == -1)
1087 if (dyn_rpath != NULL) {
1088 obj->rpath = (char *)obj->strtab + dyn_rpath->d_un.d_val;
1090 obj->rpath = origin_subst(obj->rpath, obj->origin_path);
1093 if (dyn_soname != NULL)
1094 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1098 digest_dynamic(Obj_Entry *obj, int early)
1100 const Elf_Dyn *dyn_rpath;
1101 const Elf_Dyn *dyn_soname;
1103 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname);
1104 digest_dynamic2(obj, dyn_rpath, dyn_soname);
1108 * Process a shared object's program header. This is used only for the
1109 * main program, when the kernel has already loaded the main program
1110 * into memory before calling the dynamic linker. It creates and
1111 * returns an Obj_Entry structure.
1114 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1117 const Elf_Phdr *phlimit = phdr + phnum;
1122 for (ph = phdr; ph < phlimit; ph++) {
1123 if (ph->p_type != PT_PHDR)
1127 obj->phsize = ph->p_memsz;
1128 obj->relocbase = (caddr_t)phdr - ph->p_vaddr;
1132 for (ph = phdr; ph < phlimit; ph++) {
1133 switch (ph->p_type) {
1136 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1140 if (nsegs == 0) { /* First load segment */
1141 obj->vaddrbase = trunc_page(ph->p_vaddr);
1142 obj->mapbase = obj->vaddrbase + obj->relocbase;
1143 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
1145 } else { /* Last load segment */
1146 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1153 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1158 obj->tlssize = ph->p_memsz;
1159 obj->tlsalign = ph->p_align;
1160 obj->tlsinitsize = ph->p_filesz;
1161 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1165 obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1166 obj->relro_size = round_page(ph->p_memsz);
1171 _rtld_error("%s: too few PT_LOAD segments", path);
1180 dlcheck(void *handle)
1184 for (obj = obj_list; obj != NULL; obj = obj->next)
1185 if (obj == (Obj_Entry *) handle)
1188 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1189 _rtld_error("Invalid shared object handle %p", handle);
1196 * If the given object is already in the donelist, return true. Otherwise
1197 * add the object to the list and return false.
1200 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1204 for (i = 0; i < dlp->num_used; i++)
1205 if (dlp->objs[i] == obj)
1208 * Our donelist allocation should always be sufficient. But if
1209 * our threads locking isn't working properly, more shared objects
1210 * could have been loaded since we allocated the list. That should
1211 * never happen, but we'll handle it properly just in case it does.
1213 if (dlp->num_used < dlp->num_alloc)
1214 dlp->objs[dlp->num_used++] = obj;
1219 * Hash function for symbol table lookup. Don't even think about changing
1220 * this. It is specified by the System V ABI.
1223 elf_hash(const char *name)
1225 const unsigned char *p = (const unsigned char *) name;
1226 unsigned long h = 0;
1229 while (*p != '\0') {
1230 h = (h << 4) + *p++;
1231 if ((g = h & 0xf0000000) != 0)
1239 * Find the library with the given name, and return its full pathname.
1240 * The returned string is dynamically allocated. Generates an error
1241 * message and returns NULL if the library cannot be found.
1243 * If the second argument is non-NULL, then it refers to an already-
1244 * loaded shared object, whose library search path will be searched.
1246 * The search order is:
1248 * rpath in the referencing file
1253 find_library(const char *xname, const Obj_Entry *refobj)
1258 if (strchr(xname, '/') != NULL) { /* Hard coded pathname */
1259 if (xname[0] != '/' && !trust) {
1260 _rtld_error("Absolute pathname required for shared object \"%s\"",
1264 if (refobj != NULL && refobj->z_origin)
1265 return origin_subst(xname, refobj->origin_path);
1267 return xstrdup(xname);
1270 if (libmap_disable || (refobj == NULL) ||
1271 (name = lm_find(refobj->path, xname)) == NULL)
1272 name = (char *)xname;
1274 dbg(" Searching for \"%s\"", name);
1276 if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
1278 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
1279 (pathname = search_library_path(name, gethints())) != NULL ||
1280 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
1283 if(refobj != NULL && refobj->path != NULL) {
1284 _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
1285 name, basename(refobj->path));
1287 _rtld_error("Shared object \"%s\" not found", name);
1293 * Given a symbol number in a referencing object, find the corresponding
1294 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1295 * no definition was found. Returns a pointer to the Obj_Entry of the
1296 * defining object via the reference parameter DEFOBJ_OUT.
1299 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1300 const Obj_Entry **defobj_out, int flags, SymCache *cache)
1304 const Obj_Entry *defobj;
1305 const Ver_Entry *ventry;
1310 * If we have already found this symbol, get the information from
1313 if (symnum >= refobj->nchains)
1314 return NULL; /* Bad object */
1315 if (cache != NULL && cache[symnum].sym != NULL) {
1316 *defobj_out = cache[symnum].obj;
1317 return cache[symnum].sym;
1320 ref = refobj->symtab + symnum;
1321 name = refobj->strtab + ref->st_name;
1325 * We don't have to do a full scale lookup if the symbol is local.
1326 * We know it will bind to the instance in this load module; to
1327 * which we already have a pointer (ie ref). By not doing a lookup,
1328 * we not only improve performance, but it also avoids unresolvable
1329 * symbols when local symbols are not in the hash table.
1331 * This might occur for TLS module relocations, which simply use
1334 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1335 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1336 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1339 ventry = fetch_ventry(refobj, symnum);
1340 hash = elf_hash(name);
1341 def = symlook_default(name, hash, refobj, &defobj, ventry, flags);
1348 * If we found no definition and the reference is weak, treat the
1349 * symbol as having the value zero.
1351 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1357 *defobj_out = defobj;
1358 /* Record the information in the cache to avoid subsequent lookups. */
1359 if (cache != NULL) {
1360 cache[symnum].sym = def;
1361 cache[symnum].obj = defobj;
1364 if (refobj != &obj_rtld)
1365 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1371 * Return the search path from the ldconfig hints file, reading it if
1372 * necessary. Returns NULL if there are problems with the hints file,
1373 * or if the search path there is empty.
1380 if (hints == NULL) {
1382 struct elfhints_hdr hdr;
1385 /* Keep from trying again in case the hints file is bad. */
1388 if ((fd = open(ld_elf_hints_path, O_RDONLY)) == -1)
1390 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1391 hdr.magic != ELFHINTS_MAGIC ||
1396 p = xmalloc(hdr.dirlistlen + 1);
1397 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1398 read(fd, p, hdr.dirlistlen + 1) != (ssize_t)hdr.dirlistlen + 1) {
1406 return hints[0] != '\0' ? hints : NULL;
1410 init_dag(Obj_Entry *root)
1414 if (root->dag_inited)
1416 donelist_init(&donelist);
1417 init_dag1(root, root, &donelist);
1421 init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *dlp)
1423 const Needed_Entry *needed;
1425 if (donelist_check(dlp, obj))
1428 objlist_push_tail(&obj->dldags, root);
1429 objlist_push_tail(&root->dagmembers, obj);
1430 for (needed = obj->needed; needed != NULL; needed = needed->next)
1431 if (needed->obj != NULL)
1432 init_dag1(root, needed->obj, dlp);
1433 root->dag_inited = true;
1437 * Initialize the dynamic linker. The argument is the address at which
1438 * the dynamic linker has been mapped into memory. The primary task of
1439 * this function is to relocate the dynamic linker.
1442 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
1444 Obj_Entry objtmp; /* Temporary rtld object */
1445 const Elf_Dyn *dyn_rpath;
1446 const Elf_Dyn *dyn_soname;
1449 * Conjure up an Obj_Entry structure for the dynamic linker.
1451 * The "path" member can't be initialized yet because string constants
1452 * cannot yet be accessed. Below we will set it correctly.
1454 memset(&objtmp, 0, sizeof(objtmp));
1457 objtmp.mapbase = mapbase;
1459 objtmp.relocbase = mapbase;
1461 if (RTLD_IS_DYNAMIC()) {
1462 objtmp.dynamic = rtld_dynamic(&objtmp);
1463 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname);
1464 assert(objtmp.needed == NULL);
1465 assert(!objtmp.textrel);
1468 * Temporarily put the dynamic linker entry into the object list, so
1469 * that symbols can be found.
1472 relocate_objects(&objtmp, true, &objtmp);
1475 /* Initialize the object list. */
1476 obj_tail = &obj_list;
1478 /* Now that non-local variables can be accesses, copy out obj_rtld. */
1479 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1481 #ifdef ENABLE_OSRELDATE
1482 if (aux_info[AT_OSRELDATE] != NULL)
1483 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
1486 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname);
1488 /* Replace the path with a dynamically allocated copy. */
1489 obj_rtld.path = xstrdup(PATH_RTLD);
1491 r_debug.r_brk = r_debug_state;
1492 r_debug.r_state = RT_CONSISTENT;
1496 * Add the init functions from a needed object list (and its recursive
1497 * needed objects) to "list". This is not used directly; it is a helper
1498 * function for initlist_add_objects(). The write lock must be held
1499 * when this function is called.
1502 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1504 /* Recursively process the successor needed objects. */
1505 if (needed->next != NULL)
1506 initlist_add_neededs(needed->next, list);
1508 /* Process the current needed object. */
1509 if (needed->obj != NULL)
1510 initlist_add_objects(needed->obj, &needed->obj->next, list);
1514 * Scan all of the DAGs rooted in the range of objects from "obj" to
1515 * "tail" and add their init functions to "list". This recurses over
1516 * the DAGs and ensure the proper init ordering such that each object's
1517 * needed libraries are initialized before the object itself. At the
1518 * same time, this function adds the objects to the global finalization
1519 * list "list_fini" in the opposite order. The write lock must be
1520 * held when this function is called.
1523 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1525 if (obj->init_scanned || obj->init_done)
1527 obj->init_scanned = true;
1529 /* Recursively process the successor objects. */
1530 if (&obj->next != tail)
1531 initlist_add_objects(obj->next, tail, list);
1533 /* Recursively process the needed objects. */
1534 if (obj->needed != NULL)
1535 initlist_add_neededs(obj->needed, list);
1537 /* Add the object to the init list. */
1538 if (obj->init != (Elf_Addr)NULL)
1539 objlist_push_tail(list, obj);
1541 /* Add the object to the global fini list in the reverse order. */
1542 if (obj->fini != (Elf_Addr)NULL && !obj->on_fini_list) {
1543 objlist_push_head(&list_fini, obj);
1544 obj->on_fini_list = true;
1549 #define FPTR_TARGET(f) ((Elf_Addr) (f))
1553 is_exported(const Elf_Sym *def)
1556 const func_ptr_type *p;
1558 value = (Elf_Addr)(obj_rtld.relocbase + def->st_value);
1559 for (p = exports; *p != NULL; p++)
1560 if (FPTR_TARGET(*p) == value)
1566 * Given a shared object, traverse its list of needed objects, and load
1567 * each of them. Returns 0 on success. Generates an error message and
1568 * returns -1 on failure.
1571 load_needed_objects(Obj_Entry *first, int flags)
1573 Obj_Entry *obj, *obj1;
1575 for (obj = first; obj != NULL; obj = obj->next) {
1576 Needed_Entry *needed;
1578 for (needed = obj->needed; needed != NULL; needed = needed->next) {
1579 obj1 = needed->obj = load_object(obj->strtab + needed->name, obj,
1580 flags & ~RTLD_LO_NOLOAD);
1581 if (obj1 == NULL && !ld_tracing)
1583 if (obj1 != NULL && obj1->z_nodelete && !obj1->ref_nodel) {
1584 dbg("obj %s nodelete", obj1->path);
1587 obj1->ref_nodel = true;
1594 #define RTLD_FUNCTRACE "_rtld_functrace"
1597 load_preload_objects(void)
1599 char *p = ld_preload;
1600 static const char delim[] = " \t:;";
1605 p += strspn(p, delim);
1606 while (*p != '\0') {
1607 size_t len = strcspn(p, delim);
1614 obj = load_object(p, NULL, 0);
1616 return -1; /* XXX - cleanup */
1619 p += strspn(p, delim);
1621 /* Check for the magic tracing function */
1622 sym = symlook_obj(RTLD_FUNCTRACE, elf_hash(RTLD_FUNCTRACE), obj, NULL, 1);
1624 rtld_functrace = (void *)(obj->relocbase + sym->st_value);
1625 rtld_functrace_obj = obj;
1628 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
1633 * Load a shared object into memory, if it is not already loaded.
1635 * Returns a pointer to the Obj_Entry for the object. Returns NULL
1639 load_object(const char *name, const Obj_Entry *refobj, int flags)
1646 for (obj = obj_list->next; obj != NULL; obj = obj->next)
1647 if (object_match_name(obj, name))
1650 path = find_library(name, refobj);
1655 * If we didn't find a match by pathname, open the file and check
1656 * again by device and inode. This avoids false mismatches caused
1657 * by multiple links or ".." in pathnames.
1659 * To avoid a race, we open the file and use fstat() rather than
1662 if ((fd = open(path, O_RDONLY)) == -1) {
1663 _rtld_error("Cannot open \"%s\"", path);
1667 if (fstat(fd, &sb) == -1) {
1668 _rtld_error("Cannot fstat \"%s\"", path);
1673 for (obj = obj_list->next; obj != NULL; obj = obj->next)
1674 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
1677 object_add_name(obj, name);
1682 if (flags & RTLD_LO_NOLOAD) {
1688 /* First use of this object, so we must map it in */
1689 obj = do_load_object(fd, name, path, &sb, flags);
1698 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
1705 * but first, make sure that environment variables haven't been
1706 * used to circumvent the noexec flag on a filesystem.
1708 if (dangerous_ld_env) {
1709 if (fstatfs(fd, &fs) != 0) {
1710 _rtld_error("Cannot fstatfs \"%s\"", path);
1713 if (fs.f_flags & MNT_NOEXEC) {
1714 _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
1718 dbg("loading \"%s\"", path);
1719 obj = map_object(fd, path, sbp);
1723 object_add_name(obj, name);
1725 digest_dynamic(obj, 0);
1726 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
1728 dbg("refusing to load non-loadable \"%s\"", obj->path);
1729 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
1730 munmap(obj->mapbase, obj->mapsize);
1736 obj_tail = &obj->next;
1739 linkmap_add(obj); /* for GDB & dlinfo() */
1741 dbg(" %p .. %p: %s", obj->mapbase,
1742 obj->mapbase + obj->mapsize - 1, obj->path);
1744 dbg(" WARNING: %s has impure text", obj->path);
1745 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
1752 obj_from_addr(const void *addr)
1756 for (obj = obj_list; obj != NULL; obj = obj->next) {
1757 if (addr < (void *) obj->mapbase)
1759 if (addr < (void *) (obj->mapbase + obj->mapsize))
1766 * Call the finalization functions for each of the objects in "list"
1767 * belonging to the DAG of "root" and referenced once. If NULL "root"
1768 * is specified, every finalization function will be called regardless
1769 * of the reference count and the list elements won't be freed. All of
1770 * the objects are expected to have non-NULL fini functions.
1773 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
1778 assert(root == NULL || root->refcount == 1);
1781 * Preserve the current error message since a fini function might
1782 * call into the dynamic linker and overwrite it.
1784 saved_msg = errmsg_save();
1786 STAILQ_FOREACH(elm, list, link) {
1787 if (root != NULL && (elm->obj->refcount != 1 ||
1788 objlist_find(&root->dagmembers, elm->obj) == NULL))
1790 dbg("calling fini function for %s at %p", elm->obj->path,
1791 (void *)elm->obj->fini);
1792 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini, 0, 0,
1794 /* Remove object from fini list to prevent recursive invocation. */
1795 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1797 * XXX: If a dlopen() call references an object while the
1798 * fini function is in progress, we might end up trying to
1799 * unload the referenced object in dlclose() or the object
1800 * won't be unloaded although its fini function has been
1803 lock_release(rtld_bind_lock, lockstate);
1804 call_initfini_pointer(elm->obj, elm->obj->fini);
1805 wlock_acquire(rtld_bind_lock, lockstate);
1806 /* No need to free anything if process is going down. */
1810 * We must restart the list traversal after every fini call
1811 * because a dlclose() call from the fini function or from
1812 * another thread might have modified the reference counts.
1816 } while (elm != NULL);
1817 errmsg_restore(saved_msg);
1821 * Call the initialization functions for each of the objects in
1822 * "list". All of the objects are expected to have non-NULL init
1826 objlist_call_init(Objlist *list, RtldLockState *lockstate)
1833 * Clean init_scanned flag so that objects can be rechecked and
1834 * possibly initialized earlier if any of vectors called below
1835 * cause the change by using dlopen.
1837 for (obj = obj_list; obj != NULL; obj = obj->next)
1838 obj->init_scanned = false;
1841 * Preserve the current error message since an init function might
1842 * call into the dynamic linker and overwrite it.
1844 saved_msg = errmsg_save();
1845 STAILQ_FOREACH(elm, list, link) {
1846 if (elm->obj->init_done) /* Initialized early. */
1848 dbg("calling init function for %s at %p", elm->obj->path,
1849 (void *)elm->obj->init);
1850 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init, 0, 0,
1853 * Race: other thread might try to use this object before current
1854 * one completes the initilization. Not much can be done here
1855 * without better locking.
1857 elm->obj->init_done = true;
1858 lock_release(rtld_bind_lock, lockstate);
1859 call_initfini_pointer(elm->obj, elm->obj->init);
1860 wlock_acquire(rtld_bind_lock, lockstate);
1862 errmsg_restore(saved_msg);
1866 objlist_clear(Objlist *list)
1870 while (!STAILQ_EMPTY(list)) {
1871 elm = STAILQ_FIRST(list);
1872 STAILQ_REMOVE_HEAD(list, link);
1877 static Objlist_Entry *
1878 objlist_find(Objlist *list, const Obj_Entry *obj)
1882 STAILQ_FOREACH(elm, list, link)
1883 if (elm->obj == obj)
1889 objlist_init(Objlist *list)
1895 objlist_push_head(Objlist *list, Obj_Entry *obj)
1899 elm = NEW(Objlist_Entry);
1901 STAILQ_INSERT_HEAD(list, elm, link);
1905 objlist_push_tail(Objlist *list, Obj_Entry *obj)
1909 elm = NEW(Objlist_Entry);
1911 STAILQ_INSERT_TAIL(list, elm, link);
1915 objlist_remove(Objlist *list, Obj_Entry *obj)
1919 if ((elm = objlist_find(list, obj)) != NULL) {
1920 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1926 * Relocate newly-loaded shared objects. The argument is a pointer to
1927 * the Obj_Entry for the first such object. All objects from the first
1928 * to the end of the list of objects are relocated. Returns 0 on success,
1932 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj)
1936 for (obj = first; obj != NULL; obj = obj->next) {
1938 dbg("relocating \"%s\"", obj->path);
1939 if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
1940 obj->symtab == NULL || obj->strtab == NULL) {
1941 _rtld_error("%s: Shared object has no run-time symbol table",
1947 /* There are relocations to the write-protected text segment. */
1948 if (mprotect(obj->mapbase, obj->textsize,
1949 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
1950 _rtld_error("%s: Cannot write-enable text segment: %s",
1951 obj->path, strerror(errno));
1956 /* Process the non-PLT relocations. */
1957 if (reloc_non_plt(obj, rtldobj))
1961 * Reprotect the text segment. Make sure it is included in the
1962 * core dump since we modified it. This unfortunately causes the
1963 * entire text segment to core-out but we don't have much of a
1964 * choice. We could try to only reenable core dumps on pages
1965 * in which relocations occured but that is likely most of the text
1966 * pages anyway, and even that would not work because the rest of
1967 * the text pages would wind up as a read-only OBJT_DEFAULT object
1968 * (created due to our modifications) backed by the original OBJT_VNODE
1969 * object, and the ELF coredump code is currently only able to dump
1970 * vnode records for pure vnode-backed mappings, not vnode backings
1971 * to memory objects.
1974 madvise(obj->mapbase, obj->textsize, MADV_CORE);
1975 if (mprotect(obj->mapbase, obj->textsize,
1976 PROT_READ|PROT_EXEC) == -1) {
1977 _rtld_error("%s: Cannot write-protect text segment: %s",
1978 obj->path, strerror(errno));
1983 /* Process the PLT relocations. */
1984 if (reloc_plt(obj) == -1)
1986 /* Relocate the jump slots if we are doing immediate binding. */
1987 if (obj->bind_now || bind_now)
1988 if (reloc_jmpslots(obj) == -1)
1991 /* Set the special PLT or GOT entries. */
1995 * Set up the magic number and version in the Obj_Entry. These
1996 * were checked in the crt1.o from the original ElfKit, so we
1997 * set them for backward compatibility.
1999 obj->magic = RTLD_MAGIC;
2000 obj->version = RTLD_VERSION;
2003 * Set relocated data to read-only status if protection specified
2006 if (obj->relro_size) {
2007 if (mprotect(obj->relro_page, obj->relro_size, PROT_READ) == -1) {
2008 _rtld_error("%s: Cannot enforce relro relocation: %s",
2009 obj->path, strerror(errno));
2019 * Cleanup procedure. It will be called (by the atexit mechanism) just
2020 * before the process exits.
2025 RtldLockState lockstate;
2027 wlock_acquire(rtld_bind_lock, &lockstate);
2029 objlist_call_fini(&list_fini, NULL, &lockstate);
2030 /* No need to remove the items from the list, since we are exiting. */
2031 if (!libmap_disable)
2033 lock_release(rtld_bind_lock, &lockstate);
2037 path_enumerate(const char *path, path_enum_proc callback, void *arg)
2042 path += strspn(path, ":;");
2043 while (*path != '\0') {
2047 len = strcspn(path, ":;");
2048 res = callback(path, len, arg);
2054 path += strspn(path, ":;");
2060 struct try_library_args {
2068 try_library_path(const char *dir, size_t dirlen, void *param)
2070 struct try_library_args *arg;
2073 if (*dir == '/' || trust) {
2076 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
2079 pathname = arg->buffer;
2080 strncpy(pathname, dir, dirlen);
2081 pathname[dirlen] = '/';
2082 strcpy(pathname + dirlen + 1, arg->name);
2084 dbg(" Trying \"%s\"", pathname);
2085 if (access(pathname, F_OK) == 0) { /* We found it */
2086 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
2087 strcpy(pathname, arg->buffer);
2095 search_library_path(const char *name, const char *path)
2098 struct try_library_args arg;
2104 arg.namelen = strlen(name);
2105 arg.buffer = xmalloc(PATH_MAX);
2106 arg.buflen = PATH_MAX;
2108 p = path_enumerate(path, try_library_path, &arg);
2116 dlclose(void *handle)
2119 RtldLockState lockstate;
2121 wlock_acquire(rtld_bind_lock, &lockstate);
2122 root = dlcheck(handle);
2124 lock_release(rtld_bind_lock, &lockstate);
2127 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
2130 /* Unreference the object and its dependencies. */
2131 root->dl_refcount--;
2133 if (root->refcount == 1) {
2135 * The object will be no longer referenced, so we must unload it.
2136 * First, call the fini functions.
2138 objlist_call_fini(&list_fini, root, &lockstate);
2142 /* Finish cleaning up the newly-unreferenced objects. */
2143 GDB_STATE(RT_DELETE,&root->linkmap);
2144 unload_object(root);
2145 GDB_STATE(RT_CONSISTENT,NULL);
2149 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
2150 lock_release(rtld_bind_lock, &lockstate);
2157 char *msg = error_message;
2158 error_message = NULL;
2163 dlopen(const char *name, int mode)
2165 Obj_Entry **old_obj_tail;
2168 RtldLockState lockstate;
2169 int result, lo_flags;
2171 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
2172 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
2173 if (ld_tracing != NULL)
2174 environ = (char **)*get_program_var_addr("environ");
2175 lo_flags = RTLD_LO_DLOPEN;
2176 if (mode & RTLD_NODELETE)
2177 lo_flags |= RTLD_LO_NODELETE;
2178 if (mode & RTLD_NOLOAD)
2179 lo_flags |= RTLD_LO_NOLOAD;
2180 if (ld_tracing != NULL)
2181 lo_flags |= RTLD_LO_TRACE;
2183 objlist_init(&initlist);
2185 wlock_acquire(rtld_bind_lock, &lockstate);
2186 GDB_STATE(RT_ADD,NULL);
2188 old_obj_tail = obj_tail;
2194 obj = load_object(name, obj_main, lo_flags);
2199 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
2200 objlist_push_tail(&list_global, obj);
2201 mode &= RTLD_MODEMASK;
2202 if (*old_obj_tail != NULL) { /* We loaded something new. */
2203 assert(*old_obj_tail == obj);
2204 result = load_needed_objects(obj, RTLD_LO_DLOPEN);
2208 result = rtld_verify_versions(&obj->dagmembers);
2209 if (result != -1 && ld_tracing)
2212 (relocate_objects(obj, mode == RTLD_NOW, &obj_rtld)) == -1) {
2215 if (obj->refcount == 0)
2219 /* Make list of init functions to call. */
2220 initlist_add_objects(obj, &obj->next, &initlist);
2225 * Bump the reference counts for objects on this DAG. If
2226 * this is the first dlopen() call for the object that was
2227 * already loaded as a dependency, initialize the dag
2233 if ((lo_flags & RTLD_LO_TRACE) != 0)
2236 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
2237 obj->z_nodelete) && !obj->ref_nodel) {
2238 dbg("obj %s nodelete", obj->path);
2240 obj->z_nodelete = obj->ref_nodel = true;
2244 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
2246 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
2248 /* Call the init functions. */
2249 objlist_call_init(&initlist, &lockstate);
2250 objlist_clear(&initlist);
2251 lock_release(rtld_bind_lock, &lockstate);
2254 trace_loaded_objects(obj);
2255 lock_release(rtld_bind_lock, &lockstate);
2260 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
2264 const Obj_Entry *obj, *defobj;
2265 const Elf_Sym *def, *symp;
2267 RtldLockState lockstate;
2269 hash = elf_hash(name);
2272 flags |= SYMLOOK_IN_PLT;
2274 rlock_acquire(rtld_bind_lock, &lockstate);
2275 if (sigsetjmp(lockstate.env, 0) != 0)
2276 lock_upgrade(rtld_bind_lock, &lockstate);
2277 if (handle == NULL || handle == RTLD_NEXT ||
2278 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
2280 if ((obj = obj_from_addr(retaddr)) == NULL) {
2281 _rtld_error("Cannot determine caller's shared object");
2282 lock_release(rtld_bind_lock, &lockstate);
2285 if (handle == NULL) { /* Just the caller's shared object. */
2286 def = symlook_obj(name, hash, obj, ve, flags);
2288 } else if (handle == RTLD_NEXT || /* Objects after caller's */
2289 handle == RTLD_SELF) { /* ... caller included */
2290 if (handle == RTLD_NEXT)
2292 for (; obj != NULL; obj = obj->next) {
2293 if ((symp = symlook_obj(name, hash, obj, ve, flags)) != NULL) {
2294 if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
2297 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2303 * Search the dynamic linker itself, and possibly resolve the
2304 * symbol from there. This is how the application links to
2305 * dynamic linker services such as dlopen.
2307 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2308 symp = symlook_obj(name, hash, &obj_rtld, ve, flags);
2315 assert(handle == RTLD_DEFAULT);
2316 def = symlook_default(name, hash, obj, &defobj, ve, flags);
2319 if ((obj = dlcheck(handle)) == NULL) {
2320 lock_release(rtld_bind_lock, &lockstate);
2324 donelist_init(&donelist);
2325 if (obj->mainprog) {
2326 /* Search main program and all libraries loaded by it. */
2327 def = symlook_list(name, hash, &list_main, &defobj, ve, flags,
2331 * We do not distinguish between 'main' object and global scope.
2332 * If symbol is not defined by objects loaded at startup, continue
2333 * search among dynamically loaded objects with RTLD_GLOBAL
2337 def = symlook_list(name, hash, &list_global, &defobj, ve,
2342 /* Search the whole DAG rooted at the given object. */
2344 fake.obj = (Obj_Entry *)obj;
2346 def = symlook_needed(name, hash, &fake, &defobj, ve, flags,
2352 lock_release(rtld_bind_lock, &lockstate);
2355 * The value required by the caller is derived from the value
2356 * of the symbol. For the ia64 architecture, we need to
2357 * construct a function descriptor which the caller can use to
2358 * call the function with the right 'gp' value. For other
2359 * architectures and for non-functions, the value is simply
2360 * the relocated value of the symbol.
2362 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
2363 return (make_function_pointer(def, defobj));
2365 return (defobj->relocbase + def->st_value);
2368 _rtld_error("Undefined symbol \"%s\"", name);
2369 lock_release(rtld_bind_lock, &lockstate);
2374 dlsym(void *handle, const char *name)
2376 return do_dlsym(handle, name, __builtin_return_address(0), NULL,
2381 dlfunc(void *handle, const char *name)
2388 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
2394 dlvsym(void *handle, const char *name, const char *version)
2398 ventry.name = version;
2400 ventry.hash = elf_hash(version);
2402 return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
2407 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
2409 const Obj_Entry *obj;
2410 RtldLockState lockstate;
2412 rlock_acquire(rtld_bind_lock, &lockstate);
2413 obj = obj_from_addr(addr);
2415 _rtld_error("No shared object contains address");
2416 lock_release(rtld_bind_lock, &lockstate);
2419 rtld_fill_dl_phdr_info(obj, phdr_info);
2420 lock_release(rtld_bind_lock, &lockstate);
2425 dladdr(const void *addr, Dl_info *info)
2427 const Obj_Entry *obj;
2430 unsigned long symoffset;
2431 RtldLockState lockstate;
2433 rlock_acquire(rtld_bind_lock, &lockstate);
2434 obj = obj_from_addr(addr);
2436 _rtld_error("No shared object contains address");
2437 lock_release(rtld_bind_lock, &lockstate);
2440 info->dli_fname = obj->path;
2441 info->dli_fbase = obj->mapbase;
2442 info->dli_saddr = NULL;
2443 info->dli_sname = NULL;
2446 * Walk the symbol list looking for the symbol whose address is
2447 * closest to the address sent in.
2449 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
2450 def = obj->symtab + symoffset;
2453 * For skip the symbol if st_shndx is either SHN_UNDEF or
2456 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
2460 * If the symbol is greater than the specified address, or if it
2461 * is further away from addr than the current nearest symbol,
2464 symbol_addr = obj->relocbase + def->st_value;
2465 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
2468 /* Update our idea of the nearest symbol. */
2469 info->dli_sname = obj->strtab + def->st_name;
2470 info->dli_saddr = symbol_addr;
2473 if (info->dli_saddr == addr)
2476 lock_release(rtld_bind_lock, &lockstate);
2481 dlinfo(void *handle, int request, void *p)
2483 const Obj_Entry *obj;
2484 RtldLockState lockstate;
2487 rlock_acquire(rtld_bind_lock, &lockstate);
2489 if (handle == NULL || handle == RTLD_SELF) {
2492 retaddr = __builtin_return_address(0); /* __GNUC__ only */
2493 if ((obj = obj_from_addr(retaddr)) == NULL)
2494 _rtld_error("Cannot determine caller's shared object");
2496 obj = dlcheck(handle);
2499 lock_release(rtld_bind_lock, &lockstate);
2505 case RTLD_DI_LINKMAP:
2506 *((struct link_map const **)p) = &obj->linkmap;
2508 case RTLD_DI_ORIGIN:
2509 error = rtld_dirname(obj->path, p);
2512 case RTLD_DI_SERINFOSIZE:
2513 case RTLD_DI_SERINFO:
2514 error = do_search_info(obj, request, (struct dl_serinfo *)p);
2518 _rtld_error("Invalid request %d passed to dlinfo()", request);
2522 lock_release(rtld_bind_lock, &lockstate);
2528 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
2531 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
2532 phdr_info->dlpi_name = STAILQ_FIRST(&obj->names) ?
2533 STAILQ_FIRST(&obj->names)->name : obj->path;
2534 phdr_info->dlpi_phdr = obj->phdr;
2535 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
2536 phdr_info->dlpi_tls_modid = obj->tlsindex;
2537 phdr_info->dlpi_tls_data = obj->tlsinit;
2538 phdr_info->dlpi_adds = obj_loads;
2539 phdr_info->dlpi_subs = obj_loads - obj_count;
2543 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
2545 struct dl_phdr_info phdr_info;
2546 const Obj_Entry *obj;
2547 RtldLockState bind_lockstate, phdr_lockstate;
2550 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
2551 rlock_acquire(rtld_bind_lock, &bind_lockstate);
2555 for (obj = obj_list; obj != NULL; obj = obj->next) {
2556 rtld_fill_dl_phdr_info(obj, &phdr_info);
2557 if ((error = callback(&phdr_info, sizeof phdr_info, param)) != 0)
2561 lock_release(rtld_bind_lock, &bind_lockstate);
2562 lock_release(rtld_phdr_lock, &phdr_lockstate);
2567 struct fill_search_info_args {
2570 Dl_serinfo *serinfo;
2571 Dl_serpath *serpath;
2576 fill_search_info(const char *dir, size_t dirlen, void *param)
2578 struct fill_search_info_args *arg;
2582 if (arg->request == RTLD_DI_SERINFOSIZE) {
2583 arg->serinfo->dls_cnt ++;
2584 arg->serinfo->dls_size += sizeof(Dl_serpath) + dirlen + 1;
2586 struct dl_serpath *s_entry;
2588 s_entry = arg->serpath;
2589 s_entry->dls_name = arg->strspace;
2590 s_entry->dls_flags = arg->flags;
2592 strncpy(arg->strspace, dir, dirlen);
2593 arg->strspace[dirlen] = '\0';
2595 arg->strspace += dirlen + 1;
2603 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
2605 struct dl_serinfo _info;
2606 struct fill_search_info_args args;
2608 args.request = RTLD_DI_SERINFOSIZE;
2609 args.serinfo = &_info;
2611 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2614 path_enumerate(ld_library_path, fill_search_info, &args);
2615 path_enumerate(obj->rpath, fill_search_info, &args);
2616 path_enumerate(gethints(), fill_search_info, &args);
2617 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
2620 if (request == RTLD_DI_SERINFOSIZE) {
2621 info->dls_size = _info.dls_size;
2622 info->dls_cnt = _info.dls_cnt;
2626 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
2627 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
2631 args.request = RTLD_DI_SERINFO;
2632 args.serinfo = info;
2633 args.serpath = &info->dls_serpath[0];
2634 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
2636 args.flags = LA_SER_LIBPATH;
2637 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
2640 args.flags = LA_SER_RUNPATH;
2641 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
2644 args.flags = LA_SER_CONFIG;
2645 if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
2648 args.flags = LA_SER_DEFAULT;
2649 if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
2655 rtld_dirname(const char *path, char *bname)
2659 /* Empty or NULL string gets treated as "." */
2660 if (path == NULL || *path == '\0') {
2666 /* Strip trailing slashes */
2667 endp = path + strlen(path) - 1;
2668 while (endp > path && *endp == '/')
2671 /* Find the start of the dir */
2672 while (endp > path && *endp != '/')
2675 /* Either the dir is "/" or there are no slashes */
2677 bname[0] = *endp == '/' ? '/' : '.';
2683 } while (endp > path && *endp == '/');
2686 if (endp - path + 2 > PATH_MAX)
2688 _rtld_error("Filename is too long: %s", path);
2692 strncpy(bname, path, endp - path + 1);
2693 bname[endp - path + 1] = '\0';
2698 rtld_dirname_abs(const char *path, char *base)
2700 char base_rel[PATH_MAX];
2702 if (rtld_dirname(path, base) == -1)
2706 if (getcwd(base_rel, sizeof(base_rel)) == NULL ||
2707 strlcat(base_rel, "/", sizeof(base_rel)) >= sizeof(base_rel) ||
2708 strlcat(base_rel, base, sizeof(base_rel)) >= sizeof(base_rel))
2710 strcpy(base, base_rel);
2715 linkmap_add(Obj_Entry *obj)
2717 struct link_map *l = &obj->linkmap;
2718 struct link_map *prev;
2720 obj->linkmap.l_name = obj->path;
2721 obj->linkmap.l_addr = obj->mapbase;
2722 obj->linkmap.l_ld = obj->dynamic;
2724 /* GDB needs load offset on MIPS to use the symbols */
2725 obj->linkmap.l_offs = obj->relocbase;
2728 if (r_debug.r_map == NULL) {
2734 * Scan to the end of the list, but not past the entry for the
2735 * dynamic linker, which we want to keep at the very end.
2737 for (prev = r_debug.r_map;
2738 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
2739 prev = prev->l_next)
2742 /* Link in the new entry. */
2744 l->l_next = prev->l_next;
2745 if (l->l_next != NULL)
2746 l->l_next->l_prev = l;
2751 linkmap_delete(Obj_Entry *obj)
2753 struct link_map *l = &obj->linkmap;
2755 if (l->l_prev == NULL) {
2756 if ((r_debug.r_map = l->l_next) != NULL)
2757 l->l_next->l_prev = NULL;
2761 if ((l->l_prev->l_next = l->l_next) != NULL)
2762 l->l_next->l_prev = l->l_prev;
2766 * Function for the debugger to set a breakpoint on to gain control.
2768 * The two parameters allow the debugger to easily find and determine
2769 * what the runtime loader is doing and to whom it is doing it.
2771 * When the loadhook trap is hit (r_debug_state, set at program
2772 * initialization), the arguments can be found on the stack:
2774 * +8 struct link_map *m
2775 * +4 struct r_debug *rd
2779 r_debug_state(struct r_debug* rd, struct link_map *m)
2782 * The following is a hack to force the compiler to emit calls to
2783 * this function, even when optimizing. If the function is empty,
2784 * the compiler is not obliged to emit any code for calls to it,
2785 * even when marked __noinline. However, gdb depends on those
2788 __asm __volatile("" : : : "memory");
2792 * Get address of the pointer variable in the main program.
2794 static const void **
2795 get_program_var_addr(const char *name)
2797 const Obj_Entry *obj;
2800 hash = elf_hash(name);
2801 for (obj = obj_main; obj != NULL; obj = obj->next) {
2804 if ((def = symlook_obj(name, hash, obj, NULL, 0)) != NULL) {
2807 addr = (const void **)(obj->relocbase + def->st_value);
2815 * Set a pointer variable in the main program to the given value. This
2816 * is used to set key variables such as "environ" before any of the
2817 * init functions are called.
2820 set_program_var(const char *name, const void *value)
2824 if ((addr = get_program_var_addr(name)) != NULL) {
2825 dbg("\"%s\": *%p <-- %p", name, addr, value);
2831 * This is a special version of getenv which is far more efficient
2832 * at finding LD_ environment vars.
2836 _getenv_ld(const char *id)
2840 int idlen = strlen(id);
2842 if (ld_index == LD_ARY_CACHE)
2844 if (ld_index == 0) {
2845 for (i = j = 0; (envp = environ[i]) != NULL && j < LD_ARY_CACHE; ++i) {
2846 if (envp[0] == 'L' && envp[1] == 'D' && envp[2] == '_')
2853 for (i = ld_index - 1; i >= 0; --i) {
2854 if (strncmp(ld_ary[i], id, idlen) == 0 && ld_ary[i][idlen] == '=')
2855 return(ld_ary[i] + idlen + 1);
2861 * Given a symbol name in a referencing object, find the corresponding
2862 * definition of the symbol. Returns a pointer to the symbol, or NULL if
2863 * no definition was found. Returns a pointer to the Obj_Entry of the
2864 * defining object via the reference parameter DEFOBJ_OUT.
2866 static const Elf_Sym *
2867 symlook_default(const char *name, unsigned long hash, const Obj_Entry *refobj,
2868 const Obj_Entry **defobj_out, const Ver_Entry *ventry, int flags)
2872 const Elf_Sym *symp;
2873 const Obj_Entry *obj;
2874 const Obj_Entry *defobj;
2875 const Objlist_Entry *elm;
2878 donelist_init(&donelist);
2880 /* Look first in the referencing object if linked symbolically. */
2881 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
2882 symp = symlook_obj(name, hash, refobj, ventry, flags);
2889 /* Search all objects loaded at program start up. */
2890 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2891 symp = symlook_list(name, hash, &list_main, &obj, ventry, flags,
2894 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2900 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
2901 STAILQ_FOREACH(elm, &list_global, link) {
2902 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2904 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, ventry,
2907 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2913 /* Search all dlopened DAGs containing the referencing object. */
2914 STAILQ_FOREACH(elm, &refobj->dldags, link) {
2915 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2917 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, ventry,
2920 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2927 * Search the dynamic linker itself, and possibly resolve the
2928 * symbol from there. This is how the application links to
2929 * dynamic linker services such as dlopen. Only the values listed
2930 * in the "exports" array can be resolved from the dynamic linker.
2932 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2933 symp = symlook_obj(name, hash, &obj_rtld, ventry, flags);
2934 if (symp != NULL && is_exported(symp)) {
2941 *defobj_out = defobj;
2945 static const Elf_Sym *
2946 symlook_list(const char *name, unsigned long hash, const Objlist *objlist,
2947 const Obj_Entry **defobj_out, const Ver_Entry *ventry, int flags,
2950 const Elf_Sym *symp;
2952 const Obj_Entry *defobj;
2953 const Objlist_Entry *elm;
2957 STAILQ_FOREACH(elm, objlist, link) {
2958 if (donelist_check(dlp, elm->obj))
2960 if ((symp = symlook_obj(name, hash, elm->obj, ventry, flags)) != NULL) {
2961 if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
2964 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2970 *defobj_out = defobj;
2975 * Search the symbol table of a shared object and all objects needed
2976 * by it for a symbol of the given name. Search order is
2977 * breadth-first. Returns a pointer to the symbol, or NULL if no
2978 * definition was found.
2980 static const Elf_Sym *
2981 symlook_needed(const char *name, unsigned long hash, const Needed_Entry *needed,
2982 const Obj_Entry **defobj_out, const Ver_Entry *ventry, int flags,
2985 const Elf_Sym *def, *def_w;
2986 const Needed_Entry *n;
2987 const Obj_Entry *obj, *defobj, *defobj1;
2991 for (n = needed; n != NULL; n = n->next) {
2992 if ((obj = n->obj) == NULL ||
2993 donelist_check(dlp, obj) ||
2994 (def = symlook_obj(name, hash, obj, ventry, flags)) == NULL)
2997 if (ELF_ST_BIND(def->st_info) != STB_WEAK) {
2998 *defobj_out = defobj;
3003 * There we come when either symbol definition is not found in
3004 * directly needed objects, or found symbol is weak.
3006 for (n = needed; n != NULL; n = n->next) {
3007 if ((obj = n->obj) == NULL)
3009 def_w = symlook_needed(name, hash, obj->needed, &defobj1,
3010 ventry, flags, dlp);
3013 if (def == NULL || ELF_ST_BIND(def_w->st_info) != STB_WEAK) {
3017 if (ELF_ST_BIND(def_w->st_info) != STB_WEAK)
3021 *defobj_out = defobj;
3026 * Search the symbol table of a single shared object for a symbol of
3027 * the given name and version, if requested. Returns a pointer to the
3028 * symbol, or NULL if no definition was found.
3030 * The symbol's hash value is passed in for efficiency reasons; that
3031 * eliminates many recomputations of the hash value.
3034 symlook_obj(const char *name, unsigned long hash, const Obj_Entry *obj,
3035 const Ver_Entry *ventry, int flags)
3037 unsigned long symnum;
3038 const Elf_Sym *vsymp;
3042 if (obj->buckets == NULL)
3047 symnum = obj->buckets[hash % obj->nbuckets];
3049 for (; symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
3050 const Elf_Sym *symp;
3053 if (symnum >= obj->nchains)
3054 return NULL; /* Bad object */
3056 symp = obj->symtab + symnum;
3057 strp = obj->strtab + symp->st_name;
3059 switch (ELF_ST_TYPE(symp->st_info)) {
3063 if (symp->st_value == 0)
3067 if (symp->st_shndx != SHN_UNDEF)
3069 else if (((flags & SYMLOOK_IN_PLT) == 0) &&
3070 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
3076 if (name[0] != strp[0] || strcmp(name, strp) != 0)
3079 if (ventry == NULL) {
3080 if (obj->versyms != NULL) {
3081 verndx = VER_NDX(obj->versyms[symnum]);
3082 if (verndx > obj->vernum) {
3083 _rtld_error("%s: symbol %s references wrong version %d",
3084 obj->path, obj->strtab + symnum, verndx);
3088 * If we are not called from dlsym (i.e. this is a normal
3089 * relocation from unversioned binary), accept the symbol
3090 * immediately if it happens to have first version after
3091 * this shared object became versioned. Otherwise, if
3092 * symbol is versioned and not hidden, remember it. If it
3093 * is the only symbol with this name exported by the
3094 * shared object, it will be returned as a match at the
3095 * end of the function. If symbol is global (verndx < 2)
3096 * accept it unconditionally.
3098 if ((flags & SYMLOOK_DLSYM) == 0 && verndx == VER_NDX_GIVEN)
3100 else if (verndx >= VER_NDX_GIVEN) {
3101 if ((obj->versyms[symnum] & VER_NDX_HIDDEN) == 0) {
3111 if (obj->versyms == NULL) {
3112 if (object_match_name(obj, ventry->name)) {
3113 _rtld_error("%s: object %s should provide version %s for "
3114 "symbol %s", obj_rtld.path, obj->path, ventry->name,
3115 obj->strtab + symnum);
3119 verndx = VER_NDX(obj->versyms[symnum]);
3120 if (verndx > obj->vernum) {
3121 _rtld_error("%s: symbol %s references wrong version %d",
3122 obj->path, obj->strtab + symnum, verndx);
3125 if (obj->vertab[verndx].hash != ventry->hash ||
3126 strcmp(obj->vertab[verndx].name, ventry->name)) {
3128 * Version does not match. Look if this is a global symbol
3129 * and if it is not hidden. If global symbol (verndx < 2)
3130 * is available, use it. Do not return symbol if we are
3131 * called by dlvsym, because dlvsym looks for a specific
3132 * version and default one is not what dlvsym wants.
3134 if ((flags & SYMLOOK_DLSYM) ||
3135 (obj->versyms[symnum] & VER_NDX_HIDDEN) ||
3136 (verndx >= VER_NDX_GIVEN))
3143 return (vcount == 1) ? vsymp : NULL;
3147 trace_loaded_objects(Obj_Entry *obj)
3149 const char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
3152 if ((main_local = _getenv_ld("LD_TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
3155 if ((fmt1 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT1")) == NULL)
3156 fmt1 = "\t%o => %p (%x)\n";
3158 if ((fmt2 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT2")) == NULL)
3159 fmt2 = "\t%o (%x)\n";
3161 list_containers = _getenv_ld("LD_TRACE_LOADED_OBJECTS_ALL");
3163 for (; obj; obj = obj->next) {
3164 Needed_Entry *needed;
3168 if (list_containers && obj->needed != NULL)
3169 rtld_printf("%s:\n", obj->path);
3170 for (needed = obj->needed; needed; needed = needed->next) {
3171 if (needed->obj != NULL) {
3172 if (needed->obj->traced && !list_containers)
3174 needed->obj->traced = true;
3175 path = needed->obj->path;
3179 name = (char *)obj->strtab + needed->name;
3180 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
3182 fmt = is_lib ? fmt1 : fmt2;
3183 while ((c = *fmt++) != '\0') {
3209 rtld_putstr(main_local);
3212 rtld_putstr(obj_main->path);
3221 rtld_printf("%p", needed->obj ? needed->obj->mapbase :
3234 * Unload a dlopened object and its dependencies from memory and from
3235 * our data structures. It is assumed that the DAG rooted in the
3236 * object has already been unreferenced, and that the object has a
3237 * reference count of 0.
3240 unload_object(Obj_Entry *root)
3245 assert(root->refcount == 0);
3248 * Pass over the DAG removing unreferenced objects from
3249 * appropriate lists.
3251 unlink_object(root);
3253 /* Unmap all objects that are no longer referenced. */
3254 linkp = &obj_list->next;
3255 while ((obj = *linkp) != NULL) {
3256 if (obj->refcount == 0) {
3257 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
3259 dbg("unloading \"%s\"", obj->path);
3260 munmap(obj->mapbase, obj->mapsize);
3261 linkmap_delete(obj);
3272 unlink_object(Obj_Entry *root)
3276 if (root->refcount == 0) {
3277 /* Remove the object from the RTLD_GLOBAL list. */
3278 objlist_remove(&list_global, root);
3280 /* Remove the object from all objects' DAG lists. */
3281 STAILQ_FOREACH(elm, &root->dagmembers, link) {
3282 objlist_remove(&elm->obj->dldags, root);
3283 if (elm->obj != root)
3284 unlink_object(elm->obj);
3290 ref_dag(Obj_Entry *root)
3294 assert(root->dag_inited);
3295 STAILQ_FOREACH(elm, &root->dagmembers, link)
3296 elm->obj->refcount++;
3300 unref_dag(Obj_Entry *root)
3304 assert(root->dag_inited);
3305 STAILQ_FOREACH(elm, &root->dagmembers, link)
3306 elm->obj->refcount--;
3310 * Common code for MD __tls_get_addr().
3313 tls_get_addr_common(Elf_Addr** dtvp, int index, size_t offset)
3315 Elf_Addr* dtv = *dtvp;
3316 RtldLockState lockstate;
3318 /* Check dtv generation in case new modules have arrived */
3319 if (dtv[0] != tls_dtv_generation) {
3323 wlock_acquire(rtld_bind_lock, &lockstate);
3324 newdtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
3326 if (to_copy > tls_max_index)
3327 to_copy = tls_max_index;
3328 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
3329 newdtv[0] = tls_dtv_generation;
3330 newdtv[1] = tls_max_index;
3332 lock_release(rtld_bind_lock, &lockstate);
3333 dtv = *dtvp = newdtv;
3336 /* Dynamically allocate module TLS if necessary */
3337 if (!dtv[index + 1]) {
3338 /* Signal safe, wlock will block out signals. */
3339 wlock_acquire(rtld_bind_lock, &lockstate);
3340 if (!dtv[index + 1])
3341 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
3342 lock_release(rtld_bind_lock, &lockstate);
3344 return (void*) (dtv[index + 1] + offset);
3347 #if defined(RTLD_STATIC_TLS_VARIANT_II)
3350 * Allocate the static TLS area. Return a pointer to the TCB. The
3351 * static area is based on negative offsets relative to the tcb.
3353 * The TCB contains an errno pointer for the system call layer, but because
3354 * we are the RTLD we really have no idea how the caller was compiled so
3355 * the information has to be passed in. errno can either be:
3357 * type 0 errno is a simple non-TLS global pointer.
3358 * (special case for e.g. libc_rtld)
3359 * type 1 errno accessed by GOT entry (dynamically linked programs)
3360 * type 2 errno accessed by %gs:OFFSET (statically linked programs)
3363 allocate_tls(Obj_Entry *objs)
3368 struct tls_tcb *tcb;
3373 * Allocate the new TCB. static TLS storage is placed just before the
3374 * TCB to support the %gs:OFFSET (negative offset) model.
3376 data_size = (tls_static_space + RTLD_STATIC_TLS_ALIGN_MASK) &
3377 ~RTLD_STATIC_TLS_ALIGN_MASK;
3378 tcb = malloc(data_size + sizeof(*tcb));
3379 tcb = (void *)((char *)tcb + data_size); /* actual tcb location */
3381 dtv_size = (tls_max_index + 2) * sizeof(Elf_Addr);
3382 dtv = malloc(dtv_size);
3383 bzero(dtv, dtv_size);
3385 #ifdef RTLD_TCB_HAS_SELF_POINTER
3386 tcb->tcb_self = tcb;
3389 tcb->tcb_pthread = NULL;
3391 dtv[0] = tls_dtv_generation;
3392 dtv[1] = tls_max_index;
3394 for (obj = objs; obj; obj = obj->next) {
3395 if (obj->tlsoffset) {
3396 addr = (Elf_Addr)tcb - obj->tlsoffset;
3397 memset((void *)(addr + obj->tlsinitsize),
3398 0, obj->tlssize - obj->tlsinitsize);
3400 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
3401 dtv[obj->tlsindex + 1] = addr;
3408 free_tls(struct tls_tcb *tcb)
3412 Elf_Addr tls_start, tls_end;
3415 data_size = (tls_static_space + RTLD_STATIC_TLS_ALIGN_MASK) &
3416 ~RTLD_STATIC_TLS_ALIGN_MASK;
3420 tls_end = (Elf_Addr)tcb;
3421 tls_start = (Elf_Addr)tcb - data_size;
3422 for (i = 0; i < dtv_size; i++) {
3423 if (dtv[i+2] != 0 && (dtv[i+2] < tls_start || dtv[i+2] > tls_end)) {
3424 free((void *)dtv[i+2]);
3428 free((void*) tls_start);
3432 #error "Unsupported TLS layout"
3436 * Allocate TLS block for module with given index.
3439 allocate_module_tls(int index)
3444 for (obj = obj_list; obj; obj = obj->next) {
3445 if (obj->tlsindex == index)
3449 _rtld_error("Can't find module with TLS index %d", index);
3453 p = malloc(obj->tlssize);
3455 _rtld_error("Cannot allocate TLS block for index %d", index);
3458 memcpy(p, obj->tlsinit, obj->tlsinitsize);
3459 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
3465 allocate_tls_offset(Obj_Entry *obj)
3472 if (obj->tlssize == 0) {
3473 obj->tls_done = true;
3477 if (obj->tlsindex == 1)
3478 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
3480 off = calculate_tls_offset(tls_last_offset, tls_last_size,
3481 obj->tlssize, obj->tlsalign);
3484 * If we have already fixed the size of the static TLS block, we
3485 * must stay within that size. When allocating the static TLS, we
3486 * leave a small amount of space spare to be used for dynamically
3487 * loading modules which use static TLS.
3489 if (tls_static_space) {
3490 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
3494 tls_last_offset = obj->tlsoffset = off;
3495 tls_last_size = obj->tlssize;
3496 obj->tls_done = true;
3502 free_tls_offset(Obj_Entry *obj)
3504 #ifdef RTLD_STATIC_TLS_VARIANT_II
3506 * If we were the last thing to allocate out of the static TLS
3507 * block, we give our space back to the 'allocator'. This is a
3508 * simplistic workaround to allow libGL.so.1 to be loaded and
3509 * unloaded multiple times. We only handle the Variant II
3510 * mechanism for now - this really needs a proper allocator.
3512 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
3513 == calculate_tls_end(tls_last_offset, tls_last_size)) {
3514 tls_last_offset -= obj->tlssize;
3521 _rtld_allocate_tls(void)
3523 struct tls_tcb *new_tcb;
3524 RtldLockState lockstate;
3526 wlock_acquire(rtld_bind_lock, &lockstate);
3527 new_tcb = allocate_tls(obj_list);
3528 lock_release(rtld_bind_lock, &lockstate);
3533 _rtld_free_tls(struct tls_tcb *tcb)
3535 RtldLockState lockstate;
3537 wlock_acquire(rtld_bind_lock, &lockstate);
3539 lock_release(rtld_bind_lock, &lockstate);
3543 object_add_name(Obj_Entry *obj, const char *name)
3549 entry = malloc(sizeof(Name_Entry) + len);
3551 if (entry != NULL) {
3552 strcpy(entry->name, name);
3553 STAILQ_INSERT_TAIL(&obj->names, entry, link);
3558 object_match_name(const Obj_Entry *obj, const char *name)
3562 STAILQ_FOREACH(entry, &obj->names, link) {
3563 if (strcmp(name, entry->name) == 0)
3570 locate_dependency(const Obj_Entry *obj, const char *name)
3572 const Objlist_Entry *entry;
3573 const Needed_Entry *needed;
3575 STAILQ_FOREACH(entry, &list_main, link) {
3576 if (object_match_name(entry->obj, name))
3580 for (needed = obj->needed; needed != NULL; needed = needed->next) {
3581 if (strcmp(obj->strtab + needed->name, name) == 0 ||
3582 (needed->obj != NULL && object_match_name(needed->obj, name))) {
3584 * If there is DT_NEEDED for the name we are looking for,
3585 * we are all set. Note that object might not be found if
3586 * dependency was not loaded yet, so the function can
3587 * return NULL here. This is expected and handled
3588 * properly by the caller.
3590 return (needed->obj);
3593 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
3599 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
3600 const Elf_Vernaux *vna)
3602 const Elf_Verdef *vd;
3603 const char *vername;
3605 vername = refobj->strtab + vna->vna_name;
3606 vd = depobj->verdef;
3608 _rtld_error("%s: version %s required by %s not defined",
3609 depobj->path, vername, refobj->path);
3613 if (vd->vd_version != VER_DEF_CURRENT) {
3614 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
3615 depobj->path, vd->vd_version);
3618 if (vna->vna_hash == vd->vd_hash) {
3619 const Elf_Verdaux *aux = (const Elf_Verdaux *)
3620 ((char *)vd + vd->vd_aux);
3621 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
3624 if (vd->vd_next == 0)
3626 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3628 if (vna->vna_flags & VER_FLG_WEAK)
3630 _rtld_error("%s: version %s required by %s not found",
3631 depobj->path, vername, refobj->path);
3636 rtld_verify_object_versions(Obj_Entry *obj)
3638 const Elf_Verneed *vn;
3639 const Elf_Verdef *vd;
3640 const Elf_Verdaux *vda;
3641 const Elf_Vernaux *vna;
3642 const Obj_Entry *depobj;
3643 int maxvernum, vernum;
3647 * Walk over defined and required version records and figure out
3648 * max index used by any of them. Do very basic sanity checking
3652 while (vn != NULL) {
3653 if (vn->vn_version != VER_NEED_CURRENT) {
3654 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
3655 obj->path, vn->vn_version);
3658 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
3660 vernum = VER_NEED_IDX(vna->vna_other);
3661 if (vernum > maxvernum)
3663 if (vna->vna_next == 0)
3665 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
3667 if (vn->vn_next == 0)
3669 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
3673 while (vd != NULL) {
3674 if (vd->vd_version != VER_DEF_CURRENT) {
3675 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
3676 obj->path, vd->vd_version);
3679 vernum = VER_DEF_IDX(vd->vd_ndx);
3680 if (vernum > maxvernum)
3682 if (vd->vd_next == 0)
3684 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3691 * Store version information in array indexable by version index.
3692 * Verify that object version requirements are satisfied along the
3695 obj->vernum = maxvernum + 1;
3696 obj->vertab = calloc(obj->vernum, sizeof(Ver_Entry));
3699 while (vd != NULL) {
3700 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
3701 vernum = VER_DEF_IDX(vd->vd_ndx);
3702 assert(vernum <= maxvernum);
3703 vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
3704 obj->vertab[vernum].hash = vd->vd_hash;
3705 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
3706 obj->vertab[vernum].file = NULL;
3707 obj->vertab[vernum].flags = 0;
3709 if (vd->vd_next == 0)
3711 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3715 while (vn != NULL) {
3716 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
3719 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
3721 if (check_object_provided_version(obj, depobj, vna))
3723 vernum = VER_NEED_IDX(vna->vna_other);
3724 assert(vernum <= maxvernum);
3725 obj->vertab[vernum].hash = vna->vna_hash;
3726 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
3727 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
3728 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
3729 VER_INFO_HIDDEN : 0;
3730 if (vna->vna_next == 0)
3732 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
3734 if (vn->vn_next == 0)
3736 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
3742 rtld_verify_versions(const Objlist *objlist)
3744 Objlist_Entry *entry;
3748 STAILQ_FOREACH(entry, objlist, link) {
3750 * Skip dummy objects or objects that have their version requirements
3753 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
3755 if (rtld_verify_object_versions(entry->obj) == -1) {
3757 if (ld_tracing == NULL)
3761 if (rc == 0 || ld_tracing != NULL)
3762 rc = rtld_verify_object_versions(&obj_rtld);
3767 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
3772 vernum = VER_NDX(obj->versyms[symnum]);
3773 if (vernum >= obj->vernum) {
3774 _rtld_error("%s: symbol %s has wrong verneed value %d",
3775 obj->path, obj->strtab + symnum, vernum);
3776 } else if (obj->vertab[vernum].hash != 0) {
3777 return &obj->vertab[vernum];
3783 #ifdef ENABLE_OSRELDATE
3785 __getosreldate(void)
3795 oid[1] = KERN_OSRELDATE;
3797 len = sizeof(osrel);
3798 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
3799 if (error == 0 && osrel > 0 && len == sizeof(osrel))
3806 * No unresolved symbols for rtld.
3809 __pthread_cxa_finalize(struct dl_phdr_info *a)