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>
63 #include "rtld_printf.h"
66 #define PATH_RTLD "/libexec/ld-elf.so.1"
68 #define PATH_RTLD "/libexec/ld-elf32.so.1"
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 *basename(const char *);
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, int fd, Obj_Entry *refobj,
87 int lo_flags, int mode);
88 static Obj_Entry *do_load_object(int, const char *, char *, struct stat *, int);
89 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
90 static bool donelist_check(DoneList *, const Obj_Entry *);
91 static void errmsg_restore(char *);
92 static char *errmsg_save(void);
93 static void *fill_search_info(const char *, size_t, void *);
94 static char *find_library(const char *, const Obj_Entry *);
95 static const char *gethints(void);
96 static void init_dag(Obj_Entry *);
97 static void init_rtld(caddr_t, Elf_Auxinfo **);
98 static void initlist_add_neededs(Needed_Entry *, Objlist *);
99 static void initlist_add_objects(Obj_Entry *, Obj_Entry **, Objlist *);
100 static void linkmap_add(Obj_Entry *);
101 static void linkmap_delete(Obj_Entry *);
102 static void load_filtees(Obj_Entry *, int flags, RtldLockState *);
103 static void unload_filtees(Obj_Entry *);
104 static int load_needed_objects(Obj_Entry *, int);
105 static int load_preload_objects(void);
106 static Obj_Entry *load_object(const char *, int fd, const Obj_Entry *, int);
107 static void map_stacks_exec(RtldLockState *);
108 static Obj_Entry *obj_from_addr(const void *);
109 static void objlist_call_fini(Objlist *, Obj_Entry *, RtldLockState *);
110 static void objlist_call_init(Objlist *, RtldLockState *);
111 static void objlist_clear(Objlist *);
112 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
113 static void objlist_init(Objlist *);
114 static void objlist_push_head(Objlist *, Obj_Entry *);
115 static void objlist_push_tail(Objlist *, Obj_Entry *);
116 static void objlist_remove(Objlist *, Obj_Entry *);
117 static void *path_enumerate(const char *, path_enum_proc, void *);
118 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, RtldLockState *);
119 static int resolve_objects_ifunc(Obj_Entry *first, bool bind_now,
120 RtldLockState *lockstate);
121 static int rtld_dirname(const char *, char *);
122 static int rtld_dirname_abs(const char *, char *);
123 static void *rtld_dlopen(const char *name, int fd, int mode);
124 static void rtld_exit(void);
125 static char *search_library_path(const char *, const char *);
126 static const void **get_program_var_addr(const char *, RtldLockState *);
127 static void set_program_var(const char *, const void *);
128 static int symlook_default(SymLook *, const Obj_Entry *refobj);
129 static int symlook_global(SymLook *, DoneList *);
130 static void symlook_init_from_req(SymLook *, const SymLook *);
131 static int symlook_list(SymLook *, const Objlist *, DoneList *);
132 static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *);
133 static int symlook_obj1(SymLook *, const Obj_Entry *);
134 static void trace_loaded_objects(Obj_Entry *);
135 static void unlink_object(Obj_Entry *);
136 static void unload_object(Obj_Entry *);
137 static void unref_dag(Obj_Entry *);
138 static void ref_dag(Obj_Entry *);
139 static int origin_subst_one(char **, const char *, const char *,
140 const char *, char *);
141 static char *origin_subst(const char *, const char *);
142 static int rtld_verify_versions(const Objlist *);
143 static int rtld_verify_object_versions(Obj_Entry *);
144 static void object_add_name(Obj_Entry *, const char *);
145 static int object_match_name(const Obj_Entry *, const char *);
146 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
147 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
148 struct dl_phdr_info *phdr_info);
150 void r_debug_state(struct r_debug *, struct link_map *) __noinline;
155 static char *error_message; /* Message for dlerror(), or NULL */
156 struct r_debug r_debug; /* for GDB; */
157 static bool libmap_disable; /* Disable libmap */
158 static bool ld_loadfltr; /* Immediate filters processing */
159 static char *libmap_override; /* Maps to use in addition to libmap.conf */
160 static bool trust; /* False for setuid and setgid programs */
161 static bool dangerous_ld_env; /* True if environment variables have been
162 used to affect the libraries loaded */
163 static char *ld_bind_now; /* Environment variable for immediate binding */
164 static char *ld_debug; /* Environment variable for debugging */
165 static char *ld_library_path; /* Environment variable for search path */
166 static char *ld_preload; /* Environment variable for libraries to
168 static char *ld_elf_hints_path; /* Environment variable for alternative hints path */
169 static char *ld_tracing; /* Called from ldd to print libs */
170 static char *ld_utrace; /* Use utrace() to log events. */
171 static Obj_Entry *obj_list; /* Head of linked list of shared objects */
172 static Obj_Entry **obj_tail; /* Link field of last object in list */
173 static Obj_Entry *obj_main; /* The main program shared object */
174 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
175 static unsigned int obj_count; /* Number of objects in obj_list */
176 static unsigned int obj_loads; /* Number of objects in obj_list */
178 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
179 STAILQ_HEAD_INITIALIZER(list_global);
180 static Objlist list_main = /* Objects loaded at program startup */
181 STAILQ_HEAD_INITIALIZER(list_main);
182 static Objlist list_fini = /* Objects needing fini() calls */
183 STAILQ_HEAD_INITIALIZER(list_fini);
185 Elf_Sym sym_zero; /* For resolving undefined weak refs. */
187 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
189 extern Elf_Dyn _DYNAMIC;
190 #pragma weak _DYNAMIC
191 #ifndef RTLD_IS_DYNAMIC
192 #define RTLD_IS_DYNAMIC() (&_DYNAMIC != NULL)
195 int osreldate, pagesize;
197 static int stack_prot = PROT_READ | PROT_WRITE | RTLD_DEFAULT_STACK_EXEC;
198 static int max_stack_flags;
201 * Global declarations normally provided by crt1. The dynamic linker is
202 * not built with crt1, so we have to provide them ourselves.
208 * Globals to control TLS allocation.
210 size_t tls_last_offset; /* Static TLS offset of last module */
211 size_t tls_last_size; /* Static TLS size of last module */
212 size_t tls_static_space; /* Static TLS space allocated */
213 int tls_dtv_generation = 1; /* Used to detect when dtv size changes */
214 int tls_max_index = 1; /* Largest module index allocated */
217 * Fill in a DoneList with an allocation large enough to hold all of
218 * the currently-loaded objects. Keep this as a macro since it calls
219 * alloca and we want that to occur within the scope of the caller.
221 #define donelist_init(dlp) \
222 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
223 assert((dlp)->objs != NULL), \
224 (dlp)->num_alloc = obj_count, \
227 #define UTRACE_DLOPEN_START 1
228 #define UTRACE_DLOPEN_STOP 2
229 #define UTRACE_DLCLOSE_START 3
230 #define UTRACE_DLCLOSE_STOP 4
231 #define UTRACE_LOAD_OBJECT 5
232 #define UTRACE_UNLOAD_OBJECT 6
233 #define UTRACE_ADD_RUNDEP 7
234 #define UTRACE_PRELOAD_FINISHED 8
235 #define UTRACE_INIT_CALL 9
236 #define UTRACE_FINI_CALL 10
239 char sig[4]; /* 'RTLD' */
242 void *mapbase; /* Used for 'parent' and 'init/fini' */
244 int refcnt; /* Used for 'mode' */
245 char name[MAXPATHLEN];
248 #define LD_UTRACE(e, h, mb, ms, r, n) do { \
249 if (ld_utrace != NULL) \
250 ld_utrace_log(e, h, mb, ms, r, n); \
254 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
255 int refcnt, const char *name)
257 struct utrace_rtld ut;
265 ut.mapbase = mapbase;
266 ut.mapsize = mapsize;
268 bzero(ut.name, sizeof(ut.name));
270 strlcpy(ut.name, name, sizeof(ut.name));
271 utrace(&ut, sizeof(ut));
275 * Main entry point for dynamic linking. The first argument is the
276 * stack pointer. The stack is expected to be laid out as described
277 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
278 * Specifically, the stack pointer points to a word containing
279 * ARGC. Following that in the stack is a null-terminated sequence
280 * of pointers to argument strings. Then comes a null-terminated
281 * sequence of pointers to environment strings. Finally, there is a
282 * sequence of "auxiliary vector" entries.
284 * The second argument points to a place to store the dynamic linker's
285 * exit procedure pointer and the third to a place to store the main
288 * The return value is the main program's entry point.
291 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
293 Elf_Auxinfo *aux_info[AT_COUNT];
301 Objlist_Entry *entry;
303 Obj_Entry **preload_tail;
305 RtldLockState lockstate;
308 * On entry, the dynamic linker itself has not been relocated yet.
309 * Be very careful not to reference any global data until after
310 * init_rtld has returned. It is OK to reference file-scope statics
311 * and string constants, and to call static and global functions.
314 /* Find the auxiliary vector on the stack. */
317 sp += argc + 1; /* Skip over arguments and NULL terminator */
319 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
321 aux = (Elf_Auxinfo *) sp;
323 /* Digest the auxiliary vector. */
324 for (i = 0; i < AT_COUNT; i++)
326 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
327 if (auxp->a_type < AT_COUNT)
328 aux_info[auxp->a_type] = auxp;
331 /* Initialize and relocate ourselves. */
332 assert(aux_info[AT_BASE] != NULL);
333 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
335 __progname = obj_rtld.path;
336 argv0 = argv[0] != NULL ? argv[0] : "(null)";
339 trust = !issetugid();
341 ld_bind_now = getenv(LD_ "BIND_NOW");
343 * If the process is tainted, then we un-set the dangerous environment
344 * variables. The process will be marked as tainted until setuid(2)
345 * is called. If any child process calls setuid(2) we do not want any
346 * future processes to honor the potentially un-safe variables.
349 if (unsetenv(LD_ "PRELOAD") || unsetenv(LD_ "LIBMAP") ||
350 unsetenv(LD_ "LIBRARY_PATH") || unsetenv(LD_ "LIBMAP_DISABLE") ||
351 unsetenv(LD_ "DEBUG") || unsetenv(LD_ "ELF_HINTS_PATH") ||
352 unsetenv(LD_ "LOADFLTR")) {
353 _rtld_error("environment corrupt; aborting");
357 ld_debug = getenv(LD_ "DEBUG");
358 libmap_disable = getenv(LD_ "LIBMAP_DISABLE") != NULL;
359 libmap_override = getenv(LD_ "LIBMAP");
360 ld_library_path = getenv(LD_ "LIBRARY_PATH");
361 ld_preload = getenv(LD_ "PRELOAD");
362 ld_elf_hints_path = getenv(LD_ "ELF_HINTS_PATH");
363 ld_loadfltr = getenv(LD_ "LOADFLTR") != NULL;
364 dangerous_ld_env = libmap_disable || (libmap_override != NULL) ||
365 (ld_library_path != NULL) || (ld_preload != NULL) ||
366 (ld_elf_hints_path != NULL) || ld_loadfltr;
367 ld_tracing = getenv(LD_ "TRACE_LOADED_OBJECTS");
368 ld_utrace = getenv(LD_ "UTRACE");
370 if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0)
371 ld_elf_hints_path = _PATH_ELF_HINTS;
373 if (ld_debug != NULL && *ld_debug != '\0')
375 dbg("%s is initialized, base address = %p", __progname,
376 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
377 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
378 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
380 dbg("initializing thread locks");
384 * Load the main program, or process its program header if it is
387 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
388 int fd = aux_info[AT_EXECFD]->a_un.a_val;
389 dbg("loading main program");
390 obj_main = map_object(fd, argv0, NULL);
392 if (obj_main == NULL)
394 max_stack_flags = obj->stack_flags;
395 } else { /* Main program already loaded. */
396 const Elf_Phdr *phdr;
400 dbg("processing main program's program header");
401 assert(aux_info[AT_PHDR] != NULL);
402 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
403 assert(aux_info[AT_PHNUM] != NULL);
404 phnum = aux_info[AT_PHNUM]->a_un.a_val;
405 assert(aux_info[AT_PHENT] != NULL);
406 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
407 assert(aux_info[AT_ENTRY] != NULL);
408 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
409 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
413 if (aux_info[AT_EXECPATH] != 0) {
415 char buf[MAXPATHLEN];
417 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
418 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
419 if (kexecpath[0] == '/')
420 obj_main->path = kexecpath;
421 else if (getcwd(buf, sizeof(buf)) == NULL ||
422 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
423 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
424 obj_main->path = xstrdup(argv0);
426 obj_main->path = xstrdup(buf);
428 dbg("No AT_EXECPATH");
429 obj_main->path = xstrdup(argv0);
431 dbg("obj_main path %s", obj_main->path);
432 obj_main->mainprog = true;
434 if (aux_info[AT_STACKPROT] != NULL &&
435 aux_info[AT_STACKPROT]->a_un.a_val != 0)
436 stack_prot = aux_info[AT_STACKPROT]->a_un.a_val;
439 * Get the actual dynamic linker pathname from the executable if
440 * possible. (It should always be possible.) That ensures that
441 * gdb will find the right dynamic linker even if a non-standard
444 if (obj_main->interp != NULL &&
445 strcmp(obj_main->interp, obj_rtld.path) != 0) {
447 obj_rtld.path = xstrdup(obj_main->interp);
448 __progname = obj_rtld.path;
451 digest_dynamic(obj_main, 0);
453 linkmap_add(obj_main);
454 linkmap_add(&obj_rtld);
456 /* Link the main program into the list of objects. */
457 *obj_tail = obj_main;
458 obj_tail = &obj_main->next;
461 /* Make sure we don't call the main program's init and fini functions. */
462 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
464 /* Initialize a fake symbol for resolving undefined weak references. */
465 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
466 sym_zero.st_shndx = SHN_UNDEF;
467 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
470 libmap_disable = (bool)lm_init(libmap_override);
472 dbg("loading LD_PRELOAD libraries");
473 if (load_preload_objects() == -1)
475 preload_tail = obj_tail;
477 dbg("loading needed objects");
478 if (load_needed_objects(obj_main, 0) == -1)
481 /* Make a list of all objects loaded at startup. */
482 for (obj = obj_list; obj != NULL; obj = obj->next) {
483 objlist_push_tail(&list_main, obj);
487 dbg("checking for required versions");
488 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
491 if (ld_tracing) { /* We're done */
492 trace_loaded_objects(obj_main);
496 if (getenv(LD_ "DUMP_REL_PRE") != NULL) {
497 dump_relocations(obj_main);
502 * Processing tls relocations requires having the tls offsets
503 * initialized. Prepare offsets before starting initial
504 * relocation processing.
506 dbg("initializing initial thread local storage offsets");
507 STAILQ_FOREACH(entry, &list_main, link) {
509 * Allocate all the initial objects out of the static TLS
510 * block even if they didn't ask for it.
512 allocate_tls_offset(entry->obj);
515 if (relocate_objects(obj_main,
516 ld_bind_now != NULL && *ld_bind_now != '\0', &obj_rtld, NULL) == -1)
519 dbg("doing copy relocations");
520 if (do_copy_relocations(obj_main) == -1)
523 if (getenv(LD_ "DUMP_REL_POST") != NULL) {
524 dump_relocations(obj_main);
529 * Setup TLS for main thread. This must be done after the
530 * relocations are processed, since tls initialization section
531 * might be the subject for relocations.
533 dbg("initializing initial thread local storage");
534 allocate_initial_tls(obj_list);
536 dbg("initializing key program variables");
537 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
538 set_program_var("environ", env);
539 set_program_var("__elf_aux_vector", aux);
541 /* Make a list of init functions to call. */
542 objlist_init(&initlist);
543 initlist_add_objects(obj_list, preload_tail, &initlist);
545 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
547 map_stacks_exec(NULL);
549 dbg("resolving ifuncs");
550 if (resolve_objects_ifunc(obj_main,
551 ld_bind_now != NULL && *ld_bind_now != '\0', NULL) == -1)
554 wlock_acquire(rtld_bind_lock, &lockstate);
555 objlist_call_init(&initlist, &lockstate);
556 objlist_clear(&initlist);
557 dbg("loading filtees");
558 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
559 if (ld_loadfltr || obj->z_loadfltr)
560 load_filtees(obj, 0, &lockstate);
562 lock_release(rtld_bind_lock, &lockstate);
564 dbg("transferring control to program entry point = %p", obj_main->entry);
566 /* Return the exit procedure and the program entry point. */
567 *exit_proc = rtld_exit;
569 return (func_ptr_type) obj_main->entry;
573 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def)
578 ptr = (void *)make_function_pointer(def, obj);
579 target = ((Elf_Addr (*)(void))ptr)();
580 return ((void *)target);
584 _rtld_bind(Obj_Entry *obj, Elf_Size reloff)
588 const Obj_Entry *defobj;
591 RtldLockState lockstate;
593 rlock_acquire(rtld_bind_lock, &lockstate);
594 if (sigsetjmp(lockstate.env, 0) != 0)
595 lock_upgrade(rtld_bind_lock, &lockstate);
597 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
599 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
601 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
602 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL,
606 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
607 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
609 target = (Elf_Addr)(defobj->relocbase + def->st_value);
611 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
612 defobj->strtab + def->st_name, basename(obj->path),
613 (void *)target, basename(defobj->path));
616 * Write the new contents for the jmpslot. Note that depending on
617 * architecture, the value which we need to return back to the
618 * lazy binding trampoline may or may not be the target
619 * address. The value returned from reloc_jmpslot() is the value
620 * that the trampoline needs.
622 target = reloc_jmpslot(where, target, defobj, obj, rel);
623 lock_release(rtld_bind_lock, &lockstate);
628 * Error reporting function. Use it like printf. If formats the message
629 * into a buffer, and sets things up so that the next call to dlerror()
630 * will return the message.
633 _rtld_error(const char *fmt, ...)
635 static char buf[512];
639 rtld_vsnprintf(buf, sizeof buf, fmt, ap);
645 * Return a dynamically-allocated copy of the current error message, if any.
650 return error_message == NULL ? NULL : xstrdup(error_message);
654 * Restore the current error message from a copy which was previously saved
655 * by errmsg_save(). The copy is freed.
658 errmsg_restore(char *saved_msg)
660 if (saved_msg == NULL)
661 error_message = NULL;
663 _rtld_error("%s", saved_msg);
669 basename(const char *name)
671 const char *p = strrchr(name, '/');
672 return p != NULL ? p + 1 : name;
675 static struct utsname uts;
678 origin_subst_one(char **res, const char *real, const char *kw, const char *subst,
688 subst_len = kw_len = 0;
692 if (subst_len == 0) {
693 subst_len = strlen(subst);
697 *res = xmalloc(PATH_MAX);
700 if ((res1 - *res) + subst_len + (p1 - p) >= PATH_MAX) {
701 _rtld_error("Substitution of %s in %s cannot be performed",
703 if (may_free != NULL)
708 memcpy(res1, p, p1 - p);
710 memcpy(res1, subst, subst_len);
715 if (may_free != NULL)
718 *res = xstrdup(real);
722 if (may_free != NULL)
724 if (strlcat(res1, p, PATH_MAX - (res1 - *res)) >= PATH_MAX) {
734 origin_subst(const char *real, const char *origin_path)
736 char *res1, *res2, *res3, *res4;
738 if (uts.sysname[0] == '\0') {
739 if (uname(&uts) != 0) {
740 _rtld_error("utsname failed: %d", errno);
744 if (!origin_subst_one(&res1, real, "$ORIGIN", origin_path, NULL) ||
745 !origin_subst_one(&res2, res1, "$OSNAME", uts.sysname, res1) ||
746 !origin_subst_one(&res3, res2, "$OSREL", uts.release, res2) ||
747 !origin_subst_one(&res4, res3, "$PLATFORM", uts.machine, res3))
755 const char *msg = dlerror();
759 rtld_fdputstr(STDERR_FILENO, msg);
764 * Process a shared object's DYNAMIC section, and save the important
765 * information in its Obj_Entry structure.
768 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
769 const Elf_Dyn **dyn_soname)
772 Needed_Entry **needed_tail = &obj->needed;
773 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
774 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
775 int plttype = DT_REL;
780 obj->bind_now = false;
781 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
782 switch (dynp->d_tag) {
785 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
789 obj->relsize = dynp->d_un.d_val;
793 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
797 obj->pltrel = (const Elf_Rel *)
798 (obj->relocbase + dynp->d_un.d_ptr);
802 obj->pltrelsize = dynp->d_un.d_val;
806 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
810 obj->relasize = dynp->d_un.d_val;
814 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
818 plttype = dynp->d_un.d_val;
819 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
823 obj->symtab = (const Elf_Sym *)
824 (obj->relocbase + dynp->d_un.d_ptr);
828 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
832 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
836 obj->strsize = dynp->d_un.d_val;
840 obj->verneed = (const Elf_Verneed *) (obj->relocbase +
845 obj->verneednum = dynp->d_un.d_val;
849 obj->verdef = (const Elf_Verdef *) (obj->relocbase +
854 obj->verdefnum = dynp->d_un.d_val;
858 obj->versyms = (const Elf_Versym *)(obj->relocbase +
864 const Elf_Hashelt *hashtab = (const Elf_Hashelt *)
865 (obj->relocbase + dynp->d_un.d_ptr);
866 obj->nbuckets = hashtab[0];
867 obj->nchains = hashtab[1];
868 obj->buckets = hashtab + 2;
869 obj->chains = obj->buckets + obj->nbuckets;
875 Needed_Entry *nep = NEW(Needed_Entry);
876 nep->name = dynp->d_un.d_val;
881 needed_tail = &nep->next;
887 Needed_Entry *nep = NEW(Needed_Entry);
888 nep->name = dynp->d_un.d_val;
892 *needed_filtees_tail = nep;
893 needed_filtees_tail = &nep->next;
899 Needed_Entry *nep = NEW(Needed_Entry);
900 nep->name = dynp->d_un.d_val;
904 *needed_aux_filtees_tail = nep;
905 needed_aux_filtees_tail = &nep->next;
910 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
918 obj->symbolic = true;
922 case DT_RUNPATH: /* XXX: process separately */
924 * We have to wait until later to process this, because we
925 * might not have gotten the address of the string table yet.
935 obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
939 obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
943 * Don't process DT_DEBUG on MIPS as the dynamic section
944 * is mapped read-only. DT_MIPS_RLD_MAP is used instead.
949 /* XXX - not implemented yet */
951 dbg("Filling in DT_DEBUG entry");
952 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
957 if ((dynp->d_un.d_val & DF_ORIGIN) && trust)
958 obj->z_origin = true;
959 if (dynp->d_un.d_val & DF_SYMBOLIC)
960 obj->symbolic = true;
961 if (dynp->d_un.d_val & DF_TEXTREL)
963 if (dynp->d_un.d_val & DF_BIND_NOW)
964 obj->bind_now = true;
965 /*if (dynp->d_un.d_val & DF_STATIC_TLS)
969 case DT_MIPS_LOCAL_GOTNO:
970 obj->local_gotno = dynp->d_un.d_val;
973 case DT_MIPS_SYMTABNO:
974 obj->symtabno = dynp->d_un.d_val;
978 obj->gotsym = dynp->d_un.d_val;
981 case DT_MIPS_RLD_MAP:
984 dbg("Filling in DT_DEBUG entry");
985 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
991 if (dynp->d_un.d_val & DF_1_NOOPEN)
992 obj->z_noopen = true;
993 if ((dynp->d_un.d_val & DF_1_ORIGIN) && trust)
994 obj->z_origin = true;
995 /*if (dynp->d_un.d_val & DF_1_GLOBAL)
997 if (dynp->d_un.d_val & DF_1_BIND_NOW)
998 obj->bind_now = true;
999 if (dynp->d_un.d_val & DF_1_NODELETE)
1000 obj->z_nodelete = true;
1001 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1002 obj->z_loadfltr = true;
1007 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1014 obj->traced = false;
1016 if (plttype == DT_RELA) {
1017 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1019 obj->pltrelasize = obj->pltrelsize;
1020 obj->pltrelsize = 0;
1025 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1026 const Elf_Dyn *dyn_soname)
1029 if (obj->z_origin && obj->origin_path == NULL) {
1030 obj->origin_path = xmalloc(PATH_MAX);
1031 if (rtld_dirname_abs(obj->path, obj->origin_path) == -1)
1035 if (dyn_rpath != NULL) {
1036 obj->rpath = (char *)obj->strtab + dyn_rpath->d_un.d_val;
1038 obj->rpath = origin_subst(obj->rpath, obj->origin_path);
1041 if (dyn_soname != NULL)
1042 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1046 digest_dynamic(Obj_Entry *obj, int early)
1048 const Elf_Dyn *dyn_rpath;
1049 const Elf_Dyn *dyn_soname;
1051 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname);
1052 digest_dynamic2(obj, dyn_rpath, dyn_soname);
1056 * Process a shared object's program header. This is used only for the
1057 * main program, when the kernel has already loaded the main program
1058 * into memory before calling the dynamic linker. It creates and
1059 * returns an Obj_Entry structure.
1062 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1065 const Elf_Phdr *phlimit = phdr + phnum;
1070 for (ph = phdr; ph < phlimit; ph++) {
1071 if (ph->p_type != PT_PHDR)
1075 obj->phsize = ph->p_memsz;
1076 obj->relocbase = (caddr_t)phdr - ph->p_vaddr;
1080 obj->stack_flags = PF_X | PF_R | PF_W;
1082 for (ph = phdr; ph < phlimit; ph++) {
1083 switch (ph->p_type) {
1086 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1090 if (nsegs == 0) { /* First load segment */
1091 obj->vaddrbase = trunc_page(ph->p_vaddr);
1092 obj->mapbase = obj->vaddrbase + obj->relocbase;
1093 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
1095 } else { /* Last load segment */
1096 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1103 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1108 obj->tlssize = ph->p_memsz;
1109 obj->tlsalign = ph->p_align;
1110 obj->tlsinitsize = ph->p_filesz;
1111 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1115 obj->stack_flags = ph->p_flags;
1119 obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1120 obj->relro_size = round_page(ph->p_memsz);
1125 _rtld_error("%s: too few PT_LOAD segments", path);
1134 dlcheck(void *handle)
1138 for (obj = obj_list; obj != NULL; obj = obj->next)
1139 if (obj == (Obj_Entry *) handle)
1142 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1143 _rtld_error("Invalid shared object handle %p", handle);
1150 * If the given object is already in the donelist, return true. Otherwise
1151 * add the object to the list and return false.
1154 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1158 for (i = 0; i < dlp->num_used; i++)
1159 if (dlp->objs[i] == obj)
1162 * Our donelist allocation should always be sufficient. But if
1163 * our threads locking isn't working properly, more shared objects
1164 * could have been loaded since we allocated the list. That should
1165 * never happen, but we'll handle it properly just in case it does.
1167 if (dlp->num_used < dlp->num_alloc)
1168 dlp->objs[dlp->num_used++] = obj;
1173 * Hash function for symbol table lookup. Don't even think about changing
1174 * this. It is specified by the System V ABI.
1177 elf_hash(const char *name)
1179 const unsigned char *p = (const unsigned char *) name;
1180 unsigned long h = 0;
1183 while (*p != '\0') {
1184 h = (h << 4) + *p++;
1185 if ((g = h & 0xf0000000) != 0)
1193 * Find the library with the given name, and return its full pathname.
1194 * The returned string is dynamically allocated. Generates an error
1195 * message and returns NULL if the library cannot be found.
1197 * If the second argument is non-NULL, then it refers to an already-
1198 * loaded shared object, whose library search path will be searched.
1200 * The search order is:
1202 * rpath in the referencing file
1207 find_library(const char *xname, const Obj_Entry *refobj)
1212 if (strchr(xname, '/') != NULL) { /* Hard coded pathname */
1213 if (xname[0] != '/' && !trust) {
1214 _rtld_error("Absolute pathname required for shared object \"%s\"",
1218 if (refobj != NULL && refobj->z_origin)
1219 return origin_subst(xname, refobj->origin_path);
1221 return xstrdup(xname);
1224 if (libmap_disable || (refobj == NULL) ||
1225 (name = lm_find(refobj->path, xname)) == NULL)
1226 name = (char *)xname;
1228 dbg(" Searching for \"%s\"", name);
1230 if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
1232 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
1233 (pathname = search_library_path(name, gethints())) != NULL ||
1234 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
1237 if(refobj != NULL && refobj->path != NULL) {
1238 _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
1239 name, basename(refobj->path));
1241 _rtld_error("Shared object \"%s\" not found", name);
1247 * Given a symbol number in a referencing object, find the corresponding
1248 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1249 * no definition was found. Returns a pointer to the Obj_Entry of the
1250 * defining object via the reference parameter DEFOBJ_OUT.
1253 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1254 const Obj_Entry **defobj_out, int flags, SymCache *cache,
1255 RtldLockState *lockstate)
1259 const Obj_Entry *defobj;
1265 * If we have already found this symbol, get the information from
1268 if (symnum >= refobj->nchains)
1269 return NULL; /* Bad object */
1270 if (cache != NULL && cache[symnum].sym != NULL) {
1271 *defobj_out = cache[symnum].obj;
1272 return cache[symnum].sym;
1275 ref = refobj->symtab + symnum;
1276 name = refobj->strtab + ref->st_name;
1281 * We don't have to do a full scale lookup if the symbol is local.
1282 * We know it will bind to the instance in this load module; to
1283 * which we already have a pointer (ie ref). By not doing a lookup,
1284 * we not only improve performance, but it also avoids unresolvable
1285 * symbols when local symbols are not in the hash table. This has
1286 * been seen with the ia64 toolchain.
1288 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1289 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1290 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1293 symlook_init(&req, name);
1295 req.ventry = fetch_ventry(refobj, symnum);
1296 req.lockstate = lockstate;
1297 res = symlook_default(&req, refobj);
1300 defobj = req.defobj_out;
1308 * If we found no definition and the reference is weak, treat the
1309 * symbol as having the value zero.
1311 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1317 *defobj_out = defobj;
1318 /* Record the information in the cache to avoid subsequent lookups. */
1319 if (cache != NULL) {
1320 cache[symnum].sym = def;
1321 cache[symnum].obj = defobj;
1324 if (refobj != &obj_rtld)
1325 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1331 * Return the search path from the ldconfig hints file, reading it if
1332 * necessary. Returns NULL if there are problems with the hints file,
1333 * or if the search path there is empty.
1340 if (hints == NULL) {
1342 struct elfhints_hdr hdr;
1345 /* Keep from trying again in case the hints file is bad. */
1348 if ((fd = open(ld_elf_hints_path, O_RDONLY)) == -1)
1350 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1351 hdr.magic != ELFHINTS_MAGIC ||
1356 p = xmalloc(hdr.dirlistlen + 1);
1357 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1358 read(fd, p, hdr.dirlistlen + 1) != (ssize_t)hdr.dirlistlen + 1) {
1366 return hints[0] != '\0' ? hints : NULL;
1370 init_dag(Obj_Entry *root)
1372 const Needed_Entry *needed;
1373 const Objlist_Entry *elm;
1376 if (root->dag_inited)
1378 donelist_init(&donelist);
1380 /* Root object belongs to own DAG. */
1381 objlist_push_tail(&root->dldags, root);
1382 objlist_push_tail(&root->dagmembers, root);
1383 donelist_check(&donelist, root);
1386 * Add dependencies of root object to DAG in breadth order
1387 * by exploiting the fact that each new object get added
1388 * to the tail of the dagmembers list.
1390 STAILQ_FOREACH(elm, &root->dagmembers, link) {
1391 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
1392 if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
1394 objlist_push_tail(&needed->obj->dldags, root);
1395 objlist_push_tail(&root->dagmembers, needed->obj);
1398 root->dag_inited = true;
1402 * Initialize the dynamic linker. The argument is the address at which
1403 * the dynamic linker has been mapped into memory. The primary task of
1404 * this function is to relocate the dynamic linker.
1407 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
1409 Obj_Entry objtmp; /* Temporary rtld object */
1410 const Elf_Dyn *dyn_rpath;
1411 const Elf_Dyn *dyn_soname;
1414 * Conjure up an Obj_Entry structure for the dynamic linker.
1416 * The "path" member can't be initialized yet because string constants
1417 * cannot yet be accessed. Below we will set it correctly.
1419 memset(&objtmp, 0, sizeof(objtmp));
1422 objtmp.mapbase = mapbase;
1424 objtmp.relocbase = mapbase;
1426 if (RTLD_IS_DYNAMIC()) {
1427 objtmp.dynamic = rtld_dynamic(&objtmp);
1428 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname);
1429 assert(objtmp.needed == NULL);
1430 #if !defined(__mips__)
1431 /* MIPS has a bogus DT_TEXTREL. */
1432 assert(!objtmp.textrel);
1436 * Temporarily put the dynamic linker entry into the object list, so
1437 * that symbols can be found.
1440 relocate_objects(&objtmp, true, &objtmp, NULL);
1443 /* Initialize the object list. */
1444 obj_tail = &obj_list;
1446 /* Now that non-local variables can be accesses, copy out obj_rtld. */
1447 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1449 if (aux_info[AT_PAGESZ] != NULL)
1450 pagesize = aux_info[AT_PAGESZ]->a_un.a_val;
1451 if (aux_info[AT_OSRELDATE] != NULL)
1452 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
1454 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname);
1456 /* Replace the path with a dynamically allocated copy. */
1457 obj_rtld.path = xstrdup(PATH_RTLD);
1459 r_debug.r_brk = r_debug_state;
1460 r_debug.r_state = RT_CONSISTENT;
1464 * Add the init functions from a needed object list (and its recursive
1465 * needed objects) to "list". This is not used directly; it is a helper
1466 * function for initlist_add_objects(). The write lock must be held
1467 * when this function is called.
1470 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1472 /* Recursively process the successor needed objects. */
1473 if (needed->next != NULL)
1474 initlist_add_neededs(needed->next, list);
1476 /* Process the current needed object. */
1477 if (needed->obj != NULL)
1478 initlist_add_objects(needed->obj, &needed->obj->next, list);
1482 * Scan all of the DAGs rooted in the range of objects from "obj" to
1483 * "tail" and add their init functions to "list". This recurses over
1484 * the DAGs and ensure the proper init ordering such that each object's
1485 * needed libraries are initialized before the object itself. At the
1486 * same time, this function adds the objects to the global finalization
1487 * list "list_fini" in the opposite order. The write lock must be
1488 * held when this function is called.
1491 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1493 if (obj->init_scanned || obj->init_done)
1495 obj->init_scanned = true;
1497 /* Recursively process the successor objects. */
1498 if (&obj->next != tail)
1499 initlist_add_objects(obj->next, tail, list);
1501 /* Recursively process the needed objects. */
1502 if (obj->needed != NULL)
1503 initlist_add_neededs(obj->needed, list);
1505 /* Add the object to the init list. */
1506 if (obj->init != (Elf_Addr)NULL)
1507 objlist_push_tail(list, obj);
1509 /* Add the object to the global fini list in the reverse order. */
1510 if (obj->fini != (Elf_Addr)NULL && !obj->on_fini_list) {
1511 objlist_push_head(&list_fini, obj);
1512 obj->on_fini_list = true;
1517 #define FPTR_TARGET(f) ((Elf_Addr) (f))
1521 free_needed_filtees(Needed_Entry *n)
1523 Needed_Entry *needed, *needed1;
1525 for (needed = n; needed != NULL; needed = needed->next) {
1526 if (needed->obj != NULL) {
1527 dlclose(needed->obj);
1531 for (needed = n; needed != NULL; needed = needed1) {
1532 needed1 = needed->next;
1538 unload_filtees(Obj_Entry *obj)
1541 free_needed_filtees(obj->needed_filtees);
1542 obj->needed_filtees = NULL;
1543 free_needed_filtees(obj->needed_aux_filtees);
1544 obj->needed_aux_filtees = NULL;
1545 obj->filtees_loaded = false;
1549 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags)
1552 for (; needed != NULL; needed = needed->next) {
1553 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
1554 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
1560 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
1563 lock_restart_for_upgrade(lockstate);
1564 if (!obj->filtees_loaded) {
1565 load_filtee1(obj, obj->needed_filtees, flags);
1566 load_filtee1(obj, obj->needed_aux_filtees, flags);
1567 obj->filtees_loaded = true;
1572 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
1576 for (; needed != NULL; needed = needed->next) {
1577 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
1578 flags & ~RTLD_LO_NOLOAD);
1579 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
1581 if (obj1 != NULL && obj1->z_nodelete && !obj1->ref_nodel) {
1582 dbg("obj %s nodelete", obj1->path);
1585 obj1->ref_nodel = true;
1592 * Given a shared object, traverse its list of needed objects, and load
1593 * each of them. Returns 0 on success. Generates an error message and
1594 * returns -1 on failure.
1597 load_needed_objects(Obj_Entry *first, int flags)
1601 for (obj = first; obj != NULL; obj = obj->next) {
1602 if (process_needed(obj, obj->needed, flags) == -1)
1609 load_preload_objects(void)
1611 char *p = ld_preload;
1612 static const char delim[] = " \t:;";
1617 p += strspn(p, delim);
1618 while (*p != '\0') {
1619 size_t len = strcspn(p, delim);
1624 if (load_object(p, -1, NULL, 0) == NULL)
1625 return -1; /* XXX - cleanup */
1628 p += strspn(p, delim);
1630 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
1635 printable_path(const char *path)
1638 return (path == NULL ? "<unknown>" : path);
1642 * Load a shared object into memory, if it is not already loaded. The
1643 * object may be specified by name or by user-supplied file descriptor
1644 * fd_u. In the later case, the fd_u descriptor is not closed, but its
1647 * Returns a pointer to the Obj_Entry for the object. Returns NULL
1651 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
1659 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
1660 if (object_match_name(obj, name))
1664 path = find_library(name, refobj);
1671 * If we didn't find a match by pathname, or the name is not
1672 * supplied, open the file and check again by device and inode.
1673 * This avoids false mismatches caused by multiple links or ".."
1676 * To avoid a race, we open the file and use fstat() rather than
1681 if ((fd = open(path, O_RDONLY)) == -1) {
1682 _rtld_error("Cannot open \"%s\"", path);
1689 _rtld_error("Cannot dup fd");
1694 if (fstat(fd, &sb) == -1) {
1695 _rtld_error("Cannot fstat \"%s\"", printable_path(path));
1700 for (obj = obj_list->next; obj != NULL; obj = obj->next)
1701 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
1703 if (obj != NULL && name != NULL) {
1704 object_add_name(obj, name);
1709 if (flags & RTLD_LO_NOLOAD) {
1715 /* First use of this object, so we must map it in */
1716 obj = do_load_object(fd, name, path, &sb, flags);
1725 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
1732 * but first, make sure that environment variables haven't been
1733 * used to circumvent the noexec flag on a filesystem.
1735 if (dangerous_ld_env) {
1736 if (fstatfs(fd, &fs) != 0) {
1737 _rtld_error("Cannot fstatfs \"%s\"", printable_path(path));
1740 if (fs.f_flags & MNT_NOEXEC) {
1741 _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
1745 dbg("loading \"%s\"", printable_path(path));
1746 obj = map_object(fd, printable_path(path), sbp);
1751 * If DT_SONAME is present in the object, digest_dynamic2 already
1752 * added it to the object names.
1755 object_add_name(obj, name);
1757 digest_dynamic(obj, 0);
1758 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
1760 dbg("refusing to load non-loadable \"%s\"", obj->path);
1761 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
1762 munmap(obj->mapbase, obj->mapsize);
1768 obj_tail = &obj->next;
1771 linkmap_add(obj); /* for GDB & dlinfo() */
1772 max_stack_flags |= obj->stack_flags;
1774 dbg(" %p .. %p: %s", obj->mapbase,
1775 obj->mapbase + obj->mapsize - 1, obj->path);
1777 dbg(" WARNING: %s has impure text", obj->path);
1778 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
1785 obj_from_addr(const void *addr)
1789 for (obj = obj_list; obj != NULL; obj = obj->next) {
1790 if (addr < (void *) obj->mapbase)
1792 if (addr < (void *) (obj->mapbase + obj->mapsize))
1799 * Call the finalization functions for each of the objects in "list"
1800 * belonging to the DAG of "root" and referenced once. If NULL "root"
1801 * is specified, every finalization function will be called regardless
1802 * of the reference count and the list elements won't be freed. All of
1803 * the objects are expected to have non-NULL fini functions.
1806 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
1811 assert(root == NULL || root->refcount == 1);
1814 * Preserve the current error message since a fini function might
1815 * call into the dynamic linker and overwrite it.
1817 saved_msg = errmsg_save();
1819 STAILQ_FOREACH(elm, list, link) {
1820 if (root != NULL && (elm->obj->refcount != 1 ||
1821 objlist_find(&root->dagmembers, elm->obj) == NULL))
1823 dbg("calling fini function for %s at %p", elm->obj->path,
1824 (void *)elm->obj->fini);
1825 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini, 0, 0,
1827 /* Remove object from fini list to prevent recursive invocation. */
1828 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1830 * XXX: If a dlopen() call references an object while the
1831 * fini function is in progress, we might end up trying to
1832 * unload the referenced object in dlclose() or the object
1833 * won't be unloaded although its fini function has been
1836 lock_release(rtld_bind_lock, lockstate);
1837 call_initfini_pointer(elm->obj, elm->obj->fini);
1838 wlock_acquire(rtld_bind_lock, lockstate);
1839 /* No need to free anything if process is going down. */
1843 * We must restart the list traversal after every fini call
1844 * because a dlclose() call from the fini function or from
1845 * another thread might have modified the reference counts.
1849 } while (elm != NULL);
1850 errmsg_restore(saved_msg);
1854 * Call the initialization functions for each of the objects in
1855 * "list". All of the objects are expected to have non-NULL init
1859 objlist_call_init(Objlist *list, RtldLockState *lockstate)
1866 * Clean init_scanned flag so that objects can be rechecked and
1867 * possibly initialized earlier if any of vectors called below
1868 * cause the change by using dlopen.
1870 for (obj = obj_list; obj != NULL; obj = obj->next)
1871 obj->init_scanned = false;
1874 * Preserve the current error message since an init function might
1875 * call into the dynamic linker and overwrite it.
1877 saved_msg = errmsg_save();
1878 STAILQ_FOREACH(elm, list, link) {
1879 if (elm->obj->init_done) /* Initialized early. */
1881 dbg("calling init function for %s at %p", elm->obj->path,
1882 (void *)elm->obj->init);
1883 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init, 0, 0,
1886 * Race: other thread might try to use this object before current
1887 * one completes the initilization. Not much can be done here
1888 * without better locking.
1890 elm->obj->init_done = true;
1891 lock_release(rtld_bind_lock, lockstate);
1892 call_initfini_pointer(elm->obj, elm->obj->init);
1893 wlock_acquire(rtld_bind_lock, lockstate);
1895 errmsg_restore(saved_msg);
1899 objlist_clear(Objlist *list)
1903 while (!STAILQ_EMPTY(list)) {
1904 elm = STAILQ_FIRST(list);
1905 STAILQ_REMOVE_HEAD(list, link);
1910 static Objlist_Entry *
1911 objlist_find(Objlist *list, const Obj_Entry *obj)
1915 STAILQ_FOREACH(elm, list, link)
1916 if (elm->obj == obj)
1922 objlist_init(Objlist *list)
1928 objlist_push_head(Objlist *list, Obj_Entry *obj)
1932 elm = NEW(Objlist_Entry);
1934 STAILQ_INSERT_HEAD(list, elm, link);
1938 objlist_push_tail(Objlist *list, Obj_Entry *obj)
1942 elm = NEW(Objlist_Entry);
1944 STAILQ_INSERT_TAIL(list, elm, link);
1948 objlist_remove(Objlist *list, Obj_Entry *obj)
1952 if ((elm = objlist_find(list, obj)) != NULL) {
1953 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1959 * Relocate newly-loaded shared objects. The argument is a pointer to
1960 * the Obj_Entry for the first such object. All objects from the first
1961 * to the end of the list of objects are relocated. Returns 0 on success,
1965 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
1966 RtldLockState *lockstate)
1970 for (obj = first; obj != NULL; obj = obj->next) {
1972 dbg("relocating \"%s\"", obj->path);
1973 if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
1974 obj->symtab == NULL || obj->strtab == NULL) {
1975 _rtld_error("%s: Shared object has no run-time symbol table",
1981 /* There are relocations to the write-protected text segment. */
1982 if (mprotect(obj->mapbase, obj->textsize,
1983 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
1984 _rtld_error("%s: Cannot write-enable text segment: %s",
1985 obj->path, strerror(errno));
1990 /* Process the non-PLT relocations. */
1991 if (reloc_non_plt(obj, rtldobj, lockstate))
1994 if (obj->textrel) { /* Re-protected the text segment. */
1995 if (mprotect(obj->mapbase, obj->textsize,
1996 PROT_READ|PROT_EXEC) == -1) {
1997 _rtld_error("%s: Cannot write-protect text segment: %s",
1998 obj->path, strerror(errno));
2004 /* Set the special PLT or GOT entries. */
2007 /* Process the PLT relocations. */
2008 if (reloc_plt(obj) == -1)
2010 /* Relocate the jump slots if we are doing immediate binding. */
2011 if (obj->bind_now || bind_now)
2012 if (reloc_jmpslots(obj, lockstate) == -1)
2015 if (obj->relro_size > 0) {
2016 if (mprotect(obj->relro_page, obj->relro_size, PROT_READ) == -1) {
2017 _rtld_error("%s: Cannot enforce relro protection: %s",
2018 obj->path, strerror(errno));
2024 * Set up the magic number and version in the Obj_Entry. These
2025 * were checked in the crt1.o from the original ElfKit, so we
2026 * set them for backward compatibility.
2028 obj->magic = RTLD_MAGIC;
2029 obj->version = RTLD_VERSION;
2036 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
2037 * referencing STT_GNU_IFUNC symbols is postponed till the other
2038 * relocations are done. The indirect functions specified as
2039 * ifunc are allowed to call other symbols, so we need to have
2040 * objects relocated before asking for resolution from indirects.
2042 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
2043 * instead of the usual lazy handling of PLT slots. It is
2044 * consistent with how GNU does it.
2047 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, RtldLockState *lockstate)
2049 if (obj->irelative && reloc_iresolve(obj, lockstate) == -1)
2051 if ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
2052 reloc_gnu_ifunc(obj, lockstate) == -1)
2058 resolve_objects_ifunc(Obj_Entry *first, bool bind_now, RtldLockState *lockstate)
2062 for (obj = first; obj != NULL; obj = obj->next) {
2063 if (resolve_object_ifunc(obj, bind_now, lockstate) == -1)
2070 initlist_objects_ifunc(Objlist *list, bool bind_now, RtldLockState *lockstate)
2074 STAILQ_FOREACH(elm, list, link) {
2075 if (resolve_object_ifunc(elm->obj, bind_now, lockstate) == -1)
2082 * Cleanup procedure. It will be called (by the atexit mechanism) just
2083 * before the process exits.
2088 RtldLockState lockstate;
2090 wlock_acquire(rtld_bind_lock, &lockstate);
2092 objlist_call_fini(&list_fini, NULL, &lockstate);
2093 /* No need to remove the items from the list, since we are exiting. */
2094 if (!libmap_disable)
2096 lock_release(rtld_bind_lock, &lockstate);
2100 path_enumerate(const char *path, path_enum_proc callback, void *arg)
2108 path += strspn(path, ":;");
2109 while (*path != '\0') {
2113 len = strcspn(path, ":;");
2115 trans = lm_findn(NULL, path, len);
2117 res = callback(trans, strlen(trans), arg);
2120 res = callback(path, len, arg);
2126 path += strspn(path, ":;");
2132 struct try_library_args {
2140 try_library_path(const char *dir, size_t dirlen, void *param)
2142 struct try_library_args *arg;
2145 if (*dir == '/' || trust) {
2148 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
2151 pathname = arg->buffer;
2152 strncpy(pathname, dir, dirlen);
2153 pathname[dirlen] = '/';
2154 strcpy(pathname + dirlen + 1, arg->name);
2156 dbg(" Trying \"%s\"", pathname);
2157 if (access(pathname, F_OK) == 0) { /* We found it */
2158 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
2159 strcpy(pathname, arg->buffer);
2167 search_library_path(const char *name, const char *path)
2170 struct try_library_args arg;
2176 arg.namelen = strlen(name);
2177 arg.buffer = xmalloc(PATH_MAX);
2178 arg.buflen = PATH_MAX;
2180 p = path_enumerate(path, try_library_path, &arg);
2188 dlclose(void *handle)
2191 RtldLockState lockstate;
2193 wlock_acquire(rtld_bind_lock, &lockstate);
2194 root = dlcheck(handle);
2196 lock_release(rtld_bind_lock, &lockstate);
2199 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
2202 /* Unreference the object and its dependencies. */
2203 root->dl_refcount--;
2205 if (root->refcount == 1) {
2207 * The object will be no longer referenced, so we must unload it.
2208 * First, call the fini functions.
2210 objlist_call_fini(&list_fini, root, &lockstate);
2214 /* Finish cleaning up the newly-unreferenced objects. */
2215 GDB_STATE(RT_DELETE,&root->linkmap);
2216 unload_object(root);
2217 GDB_STATE(RT_CONSISTENT,NULL);
2221 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
2222 lock_release(rtld_bind_lock, &lockstate);
2229 char *msg = error_message;
2230 error_message = NULL;
2235 * This function is deprecated and has no effect.
2238 dllockinit(void *context,
2239 void *(*lock_create)(void *context),
2240 void (*rlock_acquire)(void *lock),
2241 void (*wlock_acquire)(void *lock),
2242 void (*lock_release)(void *lock),
2243 void (*lock_destroy)(void *lock),
2244 void (*context_destroy)(void *context))
2246 static void *cur_context;
2247 static void (*cur_context_destroy)(void *);
2249 /* Just destroy the context from the previous call, if necessary. */
2250 if (cur_context_destroy != NULL)
2251 cur_context_destroy(cur_context);
2252 cur_context = context;
2253 cur_context_destroy = context_destroy;
2257 dlopen(const char *name, int mode)
2260 return (rtld_dlopen(name, -1, mode));
2264 fdlopen(int fd, int mode)
2267 return (rtld_dlopen(NULL, fd, mode));
2271 rtld_dlopen(const char *name, int fd, int mode)
2273 RtldLockState lockstate;
2276 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
2277 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
2278 if (ld_tracing != NULL) {
2279 rlock_acquire(rtld_bind_lock, &lockstate);
2280 if (sigsetjmp(lockstate.env, 0) != 0)
2281 lock_upgrade(rtld_bind_lock, &lockstate);
2282 environ = (char **)*get_program_var_addr("environ", &lockstate);
2283 lock_release(rtld_bind_lock, &lockstate);
2285 lo_flags = RTLD_LO_DLOPEN;
2286 if (mode & RTLD_NODELETE)
2287 lo_flags |= RTLD_LO_NODELETE;
2288 if (mode & RTLD_NOLOAD)
2289 lo_flags |= RTLD_LO_NOLOAD;
2290 if (ld_tracing != NULL)
2291 lo_flags |= RTLD_LO_TRACE;
2293 return (dlopen_object(name, fd, obj_main, lo_flags,
2294 mode & (RTLD_MODEMASK | RTLD_GLOBAL)));
2298 dlopen_cleanup(Obj_Entry *obj)
2303 if (obj->refcount == 0)
2308 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
2311 Obj_Entry **old_obj_tail;
2314 RtldLockState lockstate;
2317 objlist_init(&initlist);
2319 wlock_acquire(rtld_bind_lock, &lockstate);
2320 GDB_STATE(RT_ADD,NULL);
2322 old_obj_tail = obj_tail;
2324 if (name == NULL && fd == -1) {
2328 obj = load_object(name, fd, refobj, lo_flags);
2333 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
2334 objlist_push_tail(&list_global, obj);
2335 if (*old_obj_tail != NULL) { /* We loaded something new. */
2336 assert(*old_obj_tail == obj);
2337 result = load_needed_objects(obj, lo_flags & RTLD_LO_DLOPEN);
2341 result = rtld_verify_versions(&obj->dagmembers);
2342 if (result != -1 && ld_tracing)
2344 if (result == -1 || (relocate_objects(obj, (mode & RTLD_MODEMASK)
2345 == RTLD_NOW, &obj_rtld, &lockstate)) == -1) {
2346 dlopen_cleanup(obj);
2349 /* Make list of init functions to call. */
2350 initlist_add_objects(obj, &obj->next, &initlist);
2355 * Bump the reference counts for objects on this DAG. If
2356 * this is the first dlopen() call for the object that was
2357 * already loaded as a dependency, initialize the dag
2363 if ((lo_flags & RTLD_LO_TRACE) != 0)
2366 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
2367 obj->z_nodelete) && !obj->ref_nodel) {
2368 dbg("obj %s nodelete", obj->path);
2370 obj->z_nodelete = obj->ref_nodel = true;
2374 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
2376 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
2378 map_stacks_exec(&lockstate);
2380 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
2381 &lockstate) == -1) {
2382 objlist_clear(&initlist);
2383 dlopen_cleanup(obj);
2384 lock_release(rtld_bind_lock, &lockstate);
2388 /* Call the init functions. */
2389 objlist_call_init(&initlist, &lockstate);
2390 objlist_clear(&initlist);
2391 lock_release(rtld_bind_lock, &lockstate);
2394 trace_loaded_objects(obj);
2395 lock_release(rtld_bind_lock, &lockstate);
2400 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
2404 const Obj_Entry *obj, *defobj;
2407 RtldLockState lockstate;
2412 symlook_init(&req, name);
2414 req.flags = flags | SYMLOOK_IN_PLT;
2415 req.lockstate = &lockstate;
2417 rlock_acquire(rtld_bind_lock, &lockstate);
2418 if (sigsetjmp(lockstate.env, 0) != 0)
2419 lock_upgrade(rtld_bind_lock, &lockstate);
2420 if (handle == NULL || handle == RTLD_NEXT ||
2421 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
2423 if ((obj = obj_from_addr(retaddr)) == NULL) {
2424 _rtld_error("Cannot determine caller's shared object");
2425 lock_release(rtld_bind_lock, &lockstate);
2428 if (handle == NULL) { /* Just the caller's shared object. */
2429 res = symlook_obj(&req, obj);
2432 defobj = req.defobj_out;
2434 } else if (handle == RTLD_NEXT || /* Objects after caller's */
2435 handle == RTLD_SELF) { /* ... caller included */
2436 if (handle == RTLD_NEXT)
2438 for (; obj != NULL; obj = obj->next) {
2439 res = symlook_obj(&req, obj);
2442 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) {
2444 defobj = req.defobj_out;
2445 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2451 * Search the dynamic linker itself, and possibly resolve the
2452 * symbol from there. This is how the application links to
2453 * dynamic linker services such as dlopen.
2455 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2456 res = symlook_obj(&req, &obj_rtld);
2459 defobj = req.defobj_out;
2463 assert(handle == RTLD_DEFAULT);
2464 res = symlook_default(&req, obj);
2466 defobj = req.defobj_out;
2471 if ((obj = dlcheck(handle)) == NULL) {
2472 lock_release(rtld_bind_lock, &lockstate);
2476 donelist_init(&donelist);
2477 if (obj->mainprog) {
2478 /* Handle obtained by dlopen(NULL, ...) implies global scope. */
2479 res = symlook_global(&req, &donelist);
2482 defobj = req.defobj_out;
2485 * Search the dynamic linker itself, and possibly resolve the
2486 * symbol from there. This is how the application links to
2487 * dynamic linker services such as dlopen.
2489 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2490 res = symlook_obj(&req, &obj_rtld);
2493 defobj = req.defobj_out;
2498 /* Search the whole DAG rooted at the given object. */
2499 res = symlook_list(&req, &obj->dagmembers, &donelist);
2502 defobj = req.defobj_out;
2508 lock_release(rtld_bind_lock, &lockstate);
2511 * The value required by the caller is derived from the value
2512 * of the symbol. For the ia64 architecture, we need to
2513 * construct a function descriptor which the caller can use to
2514 * call the function with the right 'gp' value. For other
2515 * architectures and for non-functions, the value is simply
2516 * the relocated value of the symbol.
2518 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
2519 return (make_function_pointer(def, defobj));
2520 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
2521 return (rtld_resolve_ifunc(defobj, def));
2523 return (defobj->relocbase + def->st_value);
2526 _rtld_error("Undefined symbol \"%s\"", name);
2527 lock_release(rtld_bind_lock, &lockstate);
2532 dlsym(void *handle, const char *name)
2534 return do_dlsym(handle, name, __builtin_return_address(0), NULL,
2539 dlfunc(void *handle, const char *name)
2546 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
2552 dlvsym(void *handle, const char *name, const char *version)
2556 ventry.name = version;
2558 ventry.hash = elf_hash(version);
2560 return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
2565 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
2567 const Obj_Entry *obj;
2568 RtldLockState lockstate;
2570 rlock_acquire(rtld_bind_lock, &lockstate);
2571 obj = obj_from_addr(addr);
2573 _rtld_error("No shared object contains address");
2574 lock_release(rtld_bind_lock, &lockstate);
2577 rtld_fill_dl_phdr_info(obj, phdr_info);
2578 lock_release(rtld_bind_lock, &lockstate);
2583 dladdr(const void *addr, Dl_info *info)
2585 const Obj_Entry *obj;
2588 unsigned long symoffset;
2589 RtldLockState lockstate;
2591 rlock_acquire(rtld_bind_lock, &lockstate);
2592 obj = obj_from_addr(addr);
2594 _rtld_error("No shared object contains address");
2595 lock_release(rtld_bind_lock, &lockstate);
2598 info->dli_fname = obj->path;
2599 info->dli_fbase = obj->mapbase;
2600 info->dli_saddr = (void *)0;
2601 info->dli_sname = NULL;
2604 * Walk the symbol list looking for the symbol whose address is
2605 * closest to the address sent in.
2607 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
2608 def = obj->symtab + symoffset;
2611 * For skip the symbol if st_shndx is either SHN_UNDEF or
2614 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
2618 * If the symbol is greater than the specified address, or if it
2619 * is further away from addr than the current nearest symbol,
2622 symbol_addr = obj->relocbase + def->st_value;
2623 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
2626 /* Update our idea of the nearest symbol. */
2627 info->dli_sname = obj->strtab + def->st_name;
2628 info->dli_saddr = symbol_addr;
2631 if (info->dli_saddr == addr)
2634 lock_release(rtld_bind_lock, &lockstate);
2639 dlinfo(void *handle, int request, void *p)
2641 const Obj_Entry *obj;
2642 RtldLockState lockstate;
2645 rlock_acquire(rtld_bind_lock, &lockstate);
2647 if (handle == NULL || handle == RTLD_SELF) {
2650 retaddr = __builtin_return_address(0); /* __GNUC__ only */
2651 if ((obj = obj_from_addr(retaddr)) == NULL)
2652 _rtld_error("Cannot determine caller's shared object");
2654 obj = dlcheck(handle);
2657 lock_release(rtld_bind_lock, &lockstate);
2663 case RTLD_DI_LINKMAP:
2664 *((struct link_map const **)p) = &obj->linkmap;
2666 case RTLD_DI_ORIGIN:
2667 error = rtld_dirname(obj->path, p);
2670 case RTLD_DI_SERINFOSIZE:
2671 case RTLD_DI_SERINFO:
2672 error = do_search_info(obj, request, (struct dl_serinfo *)p);
2676 _rtld_error("Invalid request %d passed to dlinfo()", request);
2680 lock_release(rtld_bind_lock, &lockstate);
2686 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
2689 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
2690 phdr_info->dlpi_name = STAILQ_FIRST(&obj->names) ?
2691 STAILQ_FIRST(&obj->names)->name : obj->path;
2692 phdr_info->dlpi_phdr = obj->phdr;
2693 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
2694 phdr_info->dlpi_tls_modid = obj->tlsindex;
2695 phdr_info->dlpi_tls_data = obj->tlsinit;
2696 phdr_info->dlpi_adds = obj_loads;
2697 phdr_info->dlpi_subs = obj_loads - obj_count;
2701 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
2703 struct dl_phdr_info phdr_info;
2704 const Obj_Entry *obj;
2705 RtldLockState bind_lockstate, phdr_lockstate;
2708 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
2709 rlock_acquire(rtld_bind_lock, &bind_lockstate);
2713 for (obj = obj_list; obj != NULL; obj = obj->next) {
2714 rtld_fill_dl_phdr_info(obj, &phdr_info);
2715 if ((error = callback(&phdr_info, sizeof phdr_info, param)) != 0)
2719 lock_release(rtld_bind_lock, &bind_lockstate);
2720 lock_release(rtld_phdr_lock, &phdr_lockstate);
2725 struct fill_search_info_args {
2728 Dl_serinfo *serinfo;
2729 Dl_serpath *serpath;
2734 fill_search_info(const char *dir, size_t dirlen, void *param)
2736 struct fill_search_info_args *arg;
2740 if (arg->request == RTLD_DI_SERINFOSIZE) {
2741 arg->serinfo->dls_cnt ++;
2742 arg->serinfo->dls_size += sizeof(Dl_serpath) + dirlen + 1;
2744 struct dl_serpath *s_entry;
2746 s_entry = arg->serpath;
2747 s_entry->dls_name = arg->strspace;
2748 s_entry->dls_flags = arg->flags;
2750 strncpy(arg->strspace, dir, dirlen);
2751 arg->strspace[dirlen] = '\0';
2753 arg->strspace += dirlen + 1;
2761 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
2763 struct dl_serinfo _info;
2764 struct fill_search_info_args args;
2766 args.request = RTLD_DI_SERINFOSIZE;
2767 args.serinfo = &_info;
2769 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2772 path_enumerate(ld_library_path, fill_search_info, &args);
2773 path_enumerate(obj->rpath, fill_search_info, &args);
2774 path_enumerate(gethints(), fill_search_info, &args);
2775 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
2778 if (request == RTLD_DI_SERINFOSIZE) {
2779 info->dls_size = _info.dls_size;
2780 info->dls_cnt = _info.dls_cnt;
2784 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
2785 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
2789 args.request = RTLD_DI_SERINFO;
2790 args.serinfo = info;
2791 args.serpath = &info->dls_serpath[0];
2792 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
2794 args.flags = LA_SER_LIBPATH;
2795 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
2798 args.flags = LA_SER_RUNPATH;
2799 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
2802 args.flags = LA_SER_CONFIG;
2803 if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
2806 args.flags = LA_SER_DEFAULT;
2807 if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
2813 rtld_dirname(const char *path, char *bname)
2817 /* Empty or NULL string gets treated as "." */
2818 if (path == NULL || *path == '\0') {
2824 /* Strip trailing slashes */
2825 endp = path + strlen(path) - 1;
2826 while (endp > path && *endp == '/')
2829 /* Find the start of the dir */
2830 while (endp > path && *endp != '/')
2833 /* Either the dir is "/" or there are no slashes */
2835 bname[0] = *endp == '/' ? '/' : '.';
2841 } while (endp > path && *endp == '/');
2844 if (endp - path + 2 > PATH_MAX)
2846 _rtld_error("Filename is too long: %s", path);
2850 strncpy(bname, path, endp - path + 1);
2851 bname[endp - path + 1] = '\0';
2856 rtld_dirname_abs(const char *path, char *base)
2858 char base_rel[PATH_MAX];
2860 if (rtld_dirname(path, base) == -1)
2864 if (getcwd(base_rel, sizeof(base_rel)) == NULL ||
2865 strlcat(base_rel, "/", sizeof(base_rel)) >= sizeof(base_rel) ||
2866 strlcat(base_rel, base, sizeof(base_rel)) >= sizeof(base_rel))
2868 strcpy(base, base_rel);
2873 linkmap_add(Obj_Entry *obj)
2875 struct link_map *l = &obj->linkmap;
2876 struct link_map *prev;
2878 obj->linkmap.l_name = obj->path;
2879 obj->linkmap.l_addr = obj->mapbase;
2880 obj->linkmap.l_ld = obj->dynamic;
2882 /* GDB needs load offset on MIPS to use the symbols */
2883 obj->linkmap.l_offs = obj->relocbase;
2886 if (r_debug.r_map == NULL) {
2892 * Scan to the end of the list, but not past the entry for the
2893 * dynamic linker, which we want to keep at the very end.
2895 for (prev = r_debug.r_map;
2896 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
2897 prev = prev->l_next)
2900 /* Link in the new entry. */
2902 l->l_next = prev->l_next;
2903 if (l->l_next != NULL)
2904 l->l_next->l_prev = l;
2909 linkmap_delete(Obj_Entry *obj)
2911 struct link_map *l = &obj->linkmap;
2913 if (l->l_prev == NULL) {
2914 if ((r_debug.r_map = l->l_next) != NULL)
2915 l->l_next->l_prev = NULL;
2919 if ((l->l_prev->l_next = l->l_next) != NULL)
2920 l->l_next->l_prev = l->l_prev;
2924 * Function for the debugger to set a breakpoint on to gain control.
2926 * The two parameters allow the debugger to easily find and determine
2927 * what the runtime loader is doing and to whom it is doing it.
2929 * When the loadhook trap is hit (r_debug_state, set at program
2930 * initialization), the arguments can be found on the stack:
2932 * +8 struct link_map *m
2933 * +4 struct r_debug *rd
2937 r_debug_state(struct r_debug* rd, struct link_map *m)
2940 * The following is a hack to force the compiler to emit calls to
2941 * this function, even when optimizing. If the function is empty,
2942 * the compiler is not obliged to emit any code for calls to it,
2943 * even when marked __noinline. However, gdb depends on those
2946 __asm __volatile("" : : : "memory");
2950 * Get address of the pointer variable in the main program.
2951 * Prefer non-weak symbol over the weak one.
2953 static const void **
2954 get_program_var_addr(const char *name, RtldLockState *lockstate)
2959 symlook_init(&req, name);
2960 req.lockstate = lockstate;
2961 donelist_init(&donelist);
2962 if (symlook_global(&req, &donelist) != 0)
2964 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
2965 return ((const void **)make_function_pointer(req.sym_out,
2967 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
2968 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
2970 return ((const void **)(req.defobj_out->relocbase +
2971 req.sym_out->st_value));
2975 * Set a pointer variable in the main program to the given value. This
2976 * is used to set key variables such as "environ" before any of the
2977 * init functions are called.
2980 set_program_var(const char *name, const void *value)
2984 if ((addr = get_program_var_addr(name, NULL)) != NULL) {
2985 dbg("\"%s\": *%p <-- %p", name, addr, value);
2991 * Search the global objects, including dependencies and main object,
2992 * for the given symbol.
2995 symlook_global(SymLook *req, DoneList *donelist)
2998 const Objlist_Entry *elm;
3001 symlook_init_from_req(&req1, req);
3003 /* Search all objects loaded at program start up. */
3004 if (req->defobj_out == NULL ||
3005 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3006 res = symlook_list(&req1, &list_main, donelist);
3007 if (res == 0 && (req->defobj_out == NULL ||
3008 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3009 req->sym_out = req1.sym_out;
3010 req->defobj_out = req1.defobj_out;
3011 assert(req->defobj_out != NULL);
3015 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
3016 STAILQ_FOREACH(elm, &list_global, link) {
3017 if (req->defobj_out != NULL &&
3018 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3020 res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
3021 if (res == 0 && (req->defobj_out == NULL ||
3022 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3023 req->sym_out = req1.sym_out;
3024 req->defobj_out = req1.defobj_out;
3025 assert(req->defobj_out != NULL);
3029 return (req->sym_out != NULL ? 0 : ESRCH);
3033 * Given a symbol name in a referencing object, find the corresponding
3034 * definition of the symbol. Returns a pointer to the symbol, or NULL if
3035 * no definition was found. Returns a pointer to the Obj_Entry of the
3036 * defining object via the reference parameter DEFOBJ_OUT.
3039 symlook_default(SymLook *req, const Obj_Entry *refobj)
3042 const Objlist_Entry *elm;
3046 donelist_init(&donelist);
3047 symlook_init_from_req(&req1, req);
3049 /* Look first in the referencing object if linked symbolically. */
3050 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
3051 res = symlook_obj(&req1, refobj);
3053 req->sym_out = req1.sym_out;
3054 req->defobj_out = req1.defobj_out;
3055 assert(req->defobj_out != NULL);
3059 symlook_global(req, &donelist);
3061 /* Search all dlopened DAGs containing the referencing object. */
3062 STAILQ_FOREACH(elm, &refobj->dldags, link) {
3063 if (req->sym_out != NULL &&
3064 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3066 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
3067 if (res == 0 && (req->sym_out == NULL ||
3068 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3069 req->sym_out = req1.sym_out;
3070 req->defobj_out = req1.defobj_out;
3071 assert(req->defobj_out != NULL);
3076 * Search the dynamic linker itself, and possibly resolve the
3077 * symbol from there. This is how the application links to
3078 * dynamic linker services such as dlopen.
3080 if (req->sym_out == NULL ||
3081 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3082 res = symlook_obj(&req1, &obj_rtld);
3084 req->sym_out = req1.sym_out;
3085 req->defobj_out = req1.defobj_out;
3086 assert(req->defobj_out != NULL);
3090 return (req->sym_out != NULL ? 0 : ESRCH);
3094 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
3097 const Obj_Entry *defobj;
3098 const Objlist_Entry *elm;
3104 STAILQ_FOREACH(elm, objlist, link) {
3105 if (donelist_check(dlp, elm->obj))
3107 symlook_init_from_req(&req1, req);
3108 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
3109 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3111 defobj = req1.defobj_out;
3112 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3119 req->defobj_out = defobj;
3126 * Search the chain of DAGS cointed to by the given Needed_Entry
3127 * for a symbol of the given name. Each DAG is scanned completely
3128 * before advancing to the next one. Returns a pointer to the symbol,
3129 * or NULL if no definition was found.
3132 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
3135 const Needed_Entry *n;
3136 const Obj_Entry *defobj;
3142 symlook_init_from_req(&req1, req);
3143 for (n = needed; n != NULL; n = n->next) {
3144 if (n->obj == NULL ||
3145 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
3147 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3149 defobj = req1.defobj_out;
3150 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3156 req->defobj_out = defobj;
3163 * Search the symbol table of a single shared object for a symbol of
3164 * the given name and version, if requested. Returns a pointer to the
3165 * symbol, or NULL if no definition was found. If the object is
3166 * filter, return filtered symbol from filtee.
3168 * The symbol's hash value is passed in for efficiency reasons; that
3169 * eliminates many recomputations of the hash value.
3172 symlook_obj(SymLook *req, const Obj_Entry *obj)
3178 mres = symlook_obj1(req, obj);
3180 if (obj->needed_filtees != NULL) {
3181 load_filtees(__DECONST(Obj_Entry *, obj), 0, req->lockstate);
3182 donelist_init(&donelist);
3183 symlook_init_from_req(&req1, req);
3184 res = symlook_needed(&req1, obj->needed_filtees, &donelist);
3186 req->sym_out = req1.sym_out;
3187 req->defobj_out = req1.defobj_out;
3191 if (obj->needed_aux_filtees != NULL) {
3192 load_filtees(__DECONST(Obj_Entry *, obj), 0, req->lockstate);
3193 donelist_init(&donelist);
3194 symlook_init_from_req(&req1, req);
3195 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
3197 req->sym_out = req1.sym_out;
3198 req->defobj_out = req1.defobj_out;
3207 symlook_obj1(SymLook *req, const Obj_Entry *obj)
3209 unsigned long symnum;
3210 const Elf_Sym *vsymp;
3214 if (obj->buckets == NULL)
3219 symnum = obj->buckets[req->hash % obj->nbuckets];
3221 for (; symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
3222 const Elf_Sym *symp;
3225 if (symnum >= obj->nchains)
3226 return (ESRCH); /* Bad object */
3228 symp = obj->symtab + symnum;
3229 strp = obj->strtab + symp->st_name;
3231 switch (ELF_ST_TYPE(symp->st_info)) {
3236 if (symp->st_value == 0)
3240 if (symp->st_shndx != SHN_UNDEF)
3243 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
3244 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
3251 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
3254 if (req->ventry == NULL) {
3255 if (obj->versyms != NULL) {
3256 verndx = VER_NDX(obj->versyms[symnum]);
3257 if (verndx > obj->vernum) {
3258 _rtld_error("%s: symbol %s references wrong version %d",
3259 obj->path, obj->strtab + symnum, verndx);
3263 * If we are not called from dlsym (i.e. this is a normal
3264 * relocation from unversioned binary), accept the symbol
3265 * immediately if it happens to have first version after
3266 * this shared object became versioned. Otherwise, if
3267 * symbol is versioned and not hidden, remember it. If it
3268 * is the only symbol with this name exported by the
3269 * shared object, it will be returned as a match at the
3270 * end of the function. If symbol is global (verndx < 2)
3271 * accept it unconditionally.
3273 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
3274 verndx == VER_NDX_GIVEN) {
3275 req->sym_out = symp;
3276 req->defobj_out = obj;
3279 else if (verndx >= VER_NDX_GIVEN) {
3280 if ((obj->versyms[symnum] & VER_NDX_HIDDEN) == 0) {
3288 req->sym_out = symp;
3289 req->defobj_out = obj;
3292 if (obj->versyms == NULL) {
3293 if (object_match_name(obj, req->ventry->name)) {
3294 _rtld_error("%s: object %s should provide version %s for "
3295 "symbol %s", obj_rtld.path, obj->path,
3296 req->ventry->name, obj->strtab + symnum);
3300 verndx = VER_NDX(obj->versyms[symnum]);
3301 if (verndx > obj->vernum) {
3302 _rtld_error("%s: symbol %s references wrong version %d",
3303 obj->path, obj->strtab + symnum, verndx);
3306 if (obj->vertab[verndx].hash != req->ventry->hash ||
3307 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
3309 * Version does not match. Look if this is a global symbol
3310 * and if it is not hidden. If global symbol (verndx < 2)
3311 * is available, use it. Do not return symbol if we are
3312 * called by dlvsym, because dlvsym looks for a specific
3313 * version and default one is not what dlvsym wants.
3315 if ((req->flags & SYMLOOK_DLSYM) ||
3316 (obj->versyms[symnum] & VER_NDX_HIDDEN) ||
3317 (verndx >= VER_NDX_GIVEN))
3321 req->sym_out = symp;
3322 req->defobj_out = obj;
3327 req->sym_out = vsymp;
3328 req->defobj_out = obj;
3335 trace_loaded_objects(Obj_Entry *obj)
3337 char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
3340 if ((main_local = getenv(LD_ "TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
3343 if ((fmt1 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT1")) == NULL)
3344 fmt1 = "\t%o => %p (%x)\n";
3346 if ((fmt2 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT2")) == NULL)
3347 fmt2 = "\t%o (%x)\n";
3349 list_containers = getenv(LD_ "TRACE_LOADED_OBJECTS_ALL");
3351 for (; obj; obj = obj->next) {
3352 Needed_Entry *needed;
3356 if (list_containers && obj->needed != NULL)
3357 rtld_printf("%s:\n", obj->path);
3358 for (needed = obj->needed; needed; needed = needed->next) {
3359 if (needed->obj != NULL) {
3360 if (needed->obj->traced && !list_containers)
3362 needed->obj->traced = true;
3363 path = needed->obj->path;
3367 name = (char *)obj->strtab + needed->name;
3368 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
3370 fmt = is_lib ? fmt1 : fmt2;
3371 while ((c = *fmt++) != '\0') {
3397 rtld_putstr(main_local);
3400 rtld_putstr(obj_main->path);
3407 rtld_printf("%d", sodp->sod_major);
3410 rtld_printf("%d", sodp->sod_minor);
3417 rtld_printf("%p", needed->obj ? needed->obj->mapbase :
3430 * Unload a dlopened object and its dependencies from memory and from
3431 * our data structures. It is assumed that the DAG rooted in the
3432 * object has already been unreferenced, and that the object has a
3433 * reference count of 0.
3436 unload_object(Obj_Entry *root)
3441 assert(root->refcount == 0);
3444 * Pass over the DAG removing unreferenced objects from
3445 * appropriate lists.
3447 unlink_object(root);
3449 /* Unmap all objects that are no longer referenced. */
3450 linkp = &obj_list->next;
3451 while ((obj = *linkp) != NULL) {
3452 if (obj->refcount == 0) {
3453 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
3455 dbg("unloading \"%s\"", obj->path);
3456 unload_filtees(root);
3457 munmap(obj->mapbase, obj->mapsize);
3458 linkmap_delete(obj);
3469 unlink_object(Obj_Entry *root)
3473 if (root->refcount == 0) {
3474 /* Remove the object from the RTLD_GLOBAL list. */
3475 objlist_remove(&list_global, root);
3477 /* Remove the object from all objects' DAG lists. */
3478 STAILQ_FOREACH(elm, &root->dagmembers, link) {
3479 objlist_remove(&elm->obj->dldags, root);
3480 if (elm->obj != root)
3481 unlink_object(elm->obj);
3487 ref_dag(Obj_Entry *root)
3491 assert(root->dag_inited);
3492 STAILQ_FOREACH(elm, &root->dagmembers, link)
3493 elm->obj->refcount++;
3497 unref_dag(Obj_Entry *root)
3501 assert(root->dag_inited);
3502 STAILQ_FOREACH(elm, &root->dagmembers, link)
3503 elm->obj->refcount--;
3507 * Common code for MD __tls_get_addr().
3510 tls_get_addr_common(Elf_Addr** dtvp, int index, size_t offset)
3512 Elf_Addr* dtv = *dtvp;
3513 RtldLockState lockstate;
3515 /* Check dtv generation in case new modules have arrived */
3516 if (dtv[0] != tls_dtv_generation) {
3520 wlock_acquire(rtld_bind_lock, &lockstate);
3521 newdtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
3523 if (to_copy > tls_max_index)
3524 to_copy = tls_max_index;
3525 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
3526 newdtv[0] = tls_dtv_generation;
3527 newdtv[1] = tls_max_index;
3529 lock_release(rtld_bind_lock, &lockstate);
3530 dtv = *dtvp = newdtv;
3533 /* Dynamically allocate module TLS if necessary */
3534 if (!dtv[index + 1]) {
3535 /* Signal safe, wlock will block out signals. */
3536 wlock_acquire(rtld_bind_lock, &lockstate);
3537 if (!dtv[index + 1])
3538 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
3539 lock_release(rtld_bind_lock, &lockstate);
3541 return (void*) (dtv[index + 1] + offset);
3544 /* XXX not sure what variants to use for arm. */
3546 #if defined(__ia64__) || defined(__powerpc__)
3549 * Allocate Static TLS using the Variant I method.
3552 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
3561 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
3564 assert(tcbsize >= TLS_TCB_SIZE);
3565 tcb = calloc(1, tls_static_space - TLS_TCB_SIZE + tcbsize);
3566 tls = (Elf_Addr **)(tcb + tcbsize - TLS_TCB_SIZE);
3568 if (oldtcb != NULL) {
3569 memcpy(tls, oldtcb, tls_static_space);
3572 /* Adjust the DTV. */
3574 for (i = 0; i < dtv[1]; i++) {
3575 if (dtv[i+2] >= (Elf_Addr)oldtcb &&
3576 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
3577 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tls;
3581 dtv = calloc(tls_max_index + 2, sizeof(Elf_Addr));
3583 dtv[0] = tls_dtv_generation;
3584 dtv[1] = tls_max_index;
3586 for (obj = objs; obj; obj = obj->next) {
3587 if (obj->tlsoffset > 0) {
3588 addr = (Elf_Addr)tls + obj->tlsoffset;
3589 if (obj->tlsinitsize > 0)
3590 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
3591 if (obj->tlssize > obj->tlsinitsize)
3592 memset((void*) (addr + obj->tlsinitsize), 0,
3593 obj->tlssize - obj->tlsinitsize);
3594 dtv[obj->tlsindex + 1] = addr;
3603 free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
3606 Elf_Addr tlsstart, tlsend;
3609 assert(tcbsize >= TLS_TCB_SIZE);
3611 tlsstart = (Elf_Addr)tcb + tcbsize - TLS_TCB_SIZE;
3612 tlsend = tlsstart + tls_static_space;
3614 dtv = *(Elf_Addr **)tlsstart;
3616 for (i = 0; i < dtvsize; i++) {
3617 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
3618 free((void*)dtv[i+2]);
3627 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) || \
3628 defined(__arm__) || defined(__mips__)
3631 * Allocate Static TLS using the Variant II method.
3634 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
3639 Elf_Addr *dtv, *olddtv;
3640 Elf_Addr segbase, oldsegbase, addr;
3643 size = round(tls_static_space, tcbalign);
3645 assert(tcbsize >= 2*sizeof(Elf_Addr));
3646 tls = calloc(1, size + tcbsize);
3647 dtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
3649 segbase = (Elf_Addr)(tls + size);
3650 ((Elf_Addr*)segbase)[0] = segbase;
3651 ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
3653 dtv[0] = tls_dtv_generation;
3654 dtv[1] = tls_max_index;
3658 * Copy the static TLS block over whole.
3660 oldsegbase = (Elf_Addr) oldtls;
3661 memcpy((void *)(segbase - tls_static_space),
3662 (const void *)(oldsegbase - tls_static_space),
3666 * If any dynamic TLS blocks have been created tls_get_addr(),
3669 olddtv = ((Elf_Addr**)oldsegbase)[1];
3670 for (i = 0; i < olddtv[1]; i++) {
3671 if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
3672 dtv[i+2] = olddtv[i+2];
3678 * We assume that this block was the one we created with
3679 * allocate_initial_tls().
3681 free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
3683 for (obj = objs; obj; obj = obj->next) {
3684 if (obj->tlsoffset) {
3685 addr = segbase - obj->tlsoffset;
3686 memset((void*) (addr + obj->tlsinitsize),
3687 0, obj->tlssize - obj->tlsinitsize);
3689 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
3690 dtv[obj->tlsindex + 1] = addr;
3695 return (void*) segbase;
3699 free_tls(void *tls, size_t tcbsize, size_t tcbalign)
3704 Elf_Addr tlsstart, tlsend;
3707 * Figure out the size of the initial TLS block so that we can
3708 * find stuff which ___tls_get_addr() allocated dynamically.
3710 size = round(tls_static_space, tcbalign);
3712 dtv = ((Elf_Addr**)tls)[1];
3714 tlsend = (Elf_Addr) tls;
3715 tlsstart = tlsend - size;
3716 for (i = 0; i < dtvsize; i++) {
3717 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] > tlsend)) {
3718 free((void*) dtv[i+2]);
3722 free((void*) tlsstart);
3729 * Allocate TLS block for module with given index.
3732 allocate_module_tls(int index)
3737 for (obj = obj_list; obj; obj = obj->next) {
3738 if (obj->tlsindex == index)
3742 _rtld_error("Can't find module with TLS index %d", index);
3746 p = malloc(obj->tlssize);
3748 _rtld_error("Cannot allocate TLS block for index %d", index);
3751 memcpy(p, obj->tlsinit, obj->tlsinitsize);
3752 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
3758 allocate_tls_offset(Obj_Entry *obj)
3765 if (obj->tlssize == 0) {
3766 obj->tls_done = true;
3770 if (obj->tlsindex == 1)
3771 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
3773 off = calculate_tls_offset(tls_last_offset, tls_last_size,
3774 obj->tlssize, obj->tlsalign);
3777 * If we have already fixed the size of the static TLS block, we
3778 * must stay within that size. When allocating the static TLS, we
3779 * leave a small amount of space spare to be used for dynamically
3780 * loading modules which use static TLS.
3782 if (tls_static_space) {
3783 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
3787 tls_last_offset = obj->tlsoffset = off;
3788 tls_last_size = obj->tlssize;
3789 obj->tls_done = true;
3795 free_tls_offset(Obj_Entry *obj)
3799 * If we were the last thing to allocate out of the static TLS
3800 * block, we give our space back to the 'allocator'. This is a
3801 * simplistic workaround to allow libGL.so.1 to be loaded and
3802 * unloaded multiple times.
3804 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
3805 == calculate_tls_end(tls_last_offset, tls_last_size)) {
3806 tls_last_offset -= obj->tlssize;
3812 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
3815 RtldLockState lockstate;
3817 wlock_acquire(rtld_bind_lock, &lockstate);
3818 ret = allocate_tls(obj_list, oldtls, tcbsize, tcbalign);
3819 lock_release(rtld_bind_lock, &lockstate);
3824 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
3826 RtldLockState lockstate;
3828 wlock_acquire(rtld_bind_lock, &lockstate);
3829 free_tls(tcb, tcbsize, tcbalign);
3830 lock_release(rtld_bind_lock, &lockstate);
3834 object_add_name(Obj_Entry *obj, const char *name)
3840 entry = malloc(sizeof(Name_Entry) + len);
3842 if (entry != NULL) {
3843 strcpy(entry->name, name);
3844 STAILQ_INSERT_TAIL(&obj->names, entry, link);
3849 object_match_name(const Obj_Entry *obj, const char *name)
3853 STAILQ_FOREACH(entry, &obj->names, link) {
3854 if (strcmp(name, entry->name) == 0)
3861 locate_dependency(const Obj_Entry *obj, const char *name)
3863 const Objlist_Entry *entry;
3864 const Needed_Entry *needed;
3866 STAILQ_FOREACH(entry, &list_main, link) {
3867 if (object_match_name(entry->obj, name))
3871 for (needed = obj->needed; needed != NULL; needed = needed->next) {
3872 if (strcmp(obj->strtab + needed->name, name) == 0 ||
3873 (needed->obj != NULL && object_match_name(needed->obj, name))) {
3875 * If there is DT_NEEDED for the name we are looking for,
3876 * we are all set. Note that object might not be found if
3877 * dependency was not loaded yet, so the function can
3878 * return NULL here. This is expected and handled
3879 * properly by the caller.
3881 return (needed->obj);
3884 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
3890 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
3891 const Elf_Vernaux *vna)
3893 const Elf_Verdef *vd;
3894 const char *vername;
3896 vername = refobj->strtab + vna->vna_name;
3897 vd = depobj->verdef;
3899 _rtld_error("%s: version %s required by %s not defined",
3900 depobj->path, vername, refobj->path);
3904 if (vd->vd_version != VER_DEF_CURRENT) {
3905 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
3906 depobj->path, vd->vd_version);
3909 if (vna->vna_hash == vd->vd_hash) {
3910 const Elf_Verdaux *aux = (const Elf_Verdaux *)
3911 ((char *)vd + vd->vd_aux);
3912 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
3915 if (vd->vd_next == 0)
3917 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3919 if (vna->vna_flags & VER_FLG_WEAK)
3921 _rtld_error("%s: version %s required by %s not found",
3922 depobj->path, vername, refobj->path);
3927 rtld_verify_object_versions(Obj_Entry *obj)
3929 const Elf_Verneed *vn;
3930 const Elf_Verdef *vd;
3931 const Elf_Verdaux *vda;
3932 const Elf_Vernaux *vna;
3933 const Obj_Entry *depobj;
3934 int maxvernum, vernum;
3938 * Walk over defined and required version records and figure out
3939 * max index used by any of them. Do very basic sanity checking
3943 while (vn != NULL) {
3944 if (vn->vn_version != VER_NEED_CURRENT) {
3945 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
3946 obj->path, vn->vn_version);
3949 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
3951 vernum = VER_NEED_IDX(vna->vna_other);
3952 if (vernum > maxvernum)
3954 if (vna->vna_next == 0)
3956 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
3958 if (vn->vn_next == 0)
3960 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
3964 while (vd != NULL) {
3965 if (vd->vd_version != VER_DEF_CURRENT) {
3966 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
3967 obj->path, vd->vd_version);
3970 vernum = VER_DEF_IDX(vd->vd_ndx);
3971 if (vernum > maxvernum)
3973 if (vd->vd_next == 0)
3975 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3982 * Store version information in array indexable by version index.
3983 * Verify that object version requirements are satisfied along the
3986 obj->vernum = maxvernum + 1;
3987 obj->vertab = calloc(obj->vernum, sizeof(Ver_Entry));
3990 while (vd != NULL) {
3991 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
3992 vernum = VER_DEF_IDX(vd->vd_ndx);
3993 assert(vernum <= maxvernum);
3994 vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
3995 obj->vertab[vernum].hash = vd->vd_hash;
3996 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
3997 obj->vertab[vernum].file = NULL;
3998 obj->vertab[vernum].flags = 0;
4000 if (vd->vd_next == 0)
4002 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4006 while (vn != NULL) {
4007 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
4010 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4012 if (check_object_provided_version(obj, depobj, vna))
4014 vernum = VER_NEED_IDX(vna->vna_other);
4015 assert(vernum <= maxvernum);
4016 obj->vertab[vernum].hash = vna->vna_hash;
4017 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
4018 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
4019 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
4020 VER_INFO_HIDDEN : 0;
4021 if (vna->vna_next == 0)
4023 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4025 if (vn->vn_next == 0)
4027 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4033 rtld_verify_versions(const Objlist *objlist)
4035 Objlist_Entry *entry;
4039 STAILQ_FOREACH(entry, objlist, link) {
4041 * Skip dummy objects or objects that have their version requirements
4044 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
4046 if (rtld_verify_object_versions(entry->obj) == -1) {
4048 if (ld_tracing == NULL)
4052 if (rc == 0 || ld_tracing != NULL)
4053 rc = rtld_verify_object_versions(&obj_rtld);
4058 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
4063 vernum = VER_NDX(obj->versyms[symnum]);
4064 if (vernum >= obj->vernum) {
4065 _rtld_error("%s: symbol %s has wrong verneed value %d",
4066 obj->path, obj->strtab + symnum, vernum);
4067 } else if (obj->vertab[vernum].hash != 0) {
4068 return &obj->vertab[vernum];
4075 _rtld_get_stack_prot(void)
4078 return (stack_prot);
4082 map_stacks_exec(RtldLockState *lockstate)
4084 void (*thr_map_stacks_exec)(void);
4086 if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
4088 thr_map_stacks_exec = (void (*)(void))(uintptr_t)
4089 get_program_var_addr("__pthread_map_stacks_exec", lockstate);
4090 if (thr_map_stacks_exec != NULL) {
4091 stack_prot |= PROT_EXEC;
4092 thr_map_stacks_exec();
4097 symlook_init(SymLook *dst, const char *name)
4100 bzero(dst, sizeof(*dst));
4102 dst->hash = elf_hash(name);
4106 symlook_init_from_req(SymLook *dst, const SymLook *src)
4109 dst->name = src->name;
4110 dst->hash = src->hash;
4111 dst->ventry = src->ventry;
4112 dst->flags = src->flags;
4113 dst->defobj_out = NULL;
4114 dst->sym_out = NULL;
4115 dst->lockstate = src->lockstate;
4119 * Overrides for libc_pic-provided functions.
4123 __getosreldate(void)
4133 oid[1] = KERN_OSRELDATE;
4135 len = sizeof(osrel);
4136 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
4137 if (error == 0 && osrel > 0 && len == sizeof(osrel))
4143 * No unresolved symbols for rtld.
4146 __pthread_cxa_finalize(struct dl_phdr_info *a)