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);
760 rtld_fdputchar(STDERR_FILENO, '\n');
765 * Process a shared object's DYNAMIC section, and save the important
766 * information in its Obj_Entry structure.
769 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
770 const Elf_Dyn **dyn_soname)
773 Needed_Entry **needed_tail = &obj->needed;
774 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
775 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
776 int plttype = DT_REL;
781 obj->bind_now = false;
782 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
783 switch (dynp->d_tag) {
786 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
790 obj->relsize = dynp->d_un.d_val;
794 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
798 obj->pltrel = (const Elf_Rel *)
799 (obj->relocbase + dynp->d_un.d_ptr);
803 obj->pltrelsize = dynp->d_un.d_val;
807 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
811 obj->relasize = dynp->d_un.d_val;
815 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
819 plttype = dynp->d_un.d_val;
820 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
824 obj->symtab = (const Elf_Sym *)
825 (obj->relocbase + dynp->d_un.d_ptr);
829 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
833 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
837 obj->strsize = dynp->d_un.d_val;
841 obj->verneed = (const Elf_Verneed *) (obj->relocbase +
846 obj->verneednum = dynp->d_un.d_val;
850 obj->verdef = (const Elf_Verdef *) (obj->relocbase +
855 obj->verdefnum = dynp->d_un.d_val;
859 obj->versyms = (const Elf_Versym *)(obj->relocbase +
865 const Elf_Hashelt *hashtab = (const Elf_Hashelt *)
866 (obj->relocbase + dynp->d_un.d_ptr);
867 obj->nbuckets = hashtab[0];
868 obj->nchains = hashtab[1];
869 obj->buckets = hashtab + 2;
870 obj->chains = obj->buckets + obj->nbuckets;
876 Needed_Entry *nep = NEW(Needed_Entry);
877 nep->name = dynp->d_un.d_val;
882 needed_tail = &nep->next;
888 Needed_Entry *nep = NEW(Needed_Entry);
889 nep->name = dynp->d_un.d_val;
893 *needed_filtees_tail = nep;
894 needed_filtees_tail = &nep->next;
900 Needed_Entry *nep = NEW(Needed_Entry);
901 nep->name = dynp->d_un.d_val;
905 *needed_aux_filtees_tail = nep;
906 needed_aux_filtees_tail = &nep->next;
911 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
919 obj->symbolic = true;
923 case DT_RUNPATH: /* XXX: process separately */
925 * We have to wait until later to process this, because we
926 * might not have gotten the address of the string table yet.
936 obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
940 obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
944 * Don't process DT_DEBUG on MIPS as the dynamic section
945 * is mapped read-only. DT_MIPS_RLD_MAP is used instead.
950 /* XXX - not implemented yet */
952 dbg("Filling in DT_DEBUG entry");
953 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
958 if ((dynp->d_un.d_val & DF_ORIGIN) && trust)
959 obj->z_origin = true;
960 if (dynp->d_un.d_val & DF_SYMBOLIC)
961 obj->symbolic = true;
962 if (dynp->d_un.d_val & DF_TEXTREL)
964 if (dynp->d_un.d_val & DF_BIND_NOW)
965 obj->bind_now = true;
966 /*if (dynp->d_un.d_val & DF_STATIC_TLS)
970 case DT_MIPS_LOCAL_GOTNO:
971 obj->local_gotno = dynp->d_un.d_val;
974 case DT_MIPS_SYMTABNO:
975 obj->symtabno = dynp->d_un.d_val;
979 obj->gotsym = dynp->d_un.d_val;
982 case DT_MIPS_RLD_MAP:
985 dbg("Filling in DT_DEBUG entry");
986 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
992 if (dynp->d_un.d_val & DF_1_NOOPEN)
993 obj->z_noopen = true;
994 if ((dynp->d_un.d_val & DF_1_ORIGIN) && trust)
995 obj->z_origin = true;
996 /*if (dynp->d_un.d_val & DF_1_GLOBAL)
998 if (dynp->d_un.d_val & DF_1_BIND_NOW)
999 obj->bind_now = true;
1000 if (dynp->d_un.d_val & DF_1_NODELETE)
1001 obj->z_nodelete = true;
1002 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1003 obj->z_loadfltr = true;
1008 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1015 obj->traced = false;
1017 if (plttype == DT_RELA) {
1018 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1020 obj->pltrelasize = obj->pltrelsize;
1021 obj->pltrelsize = 0;
1026 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1027 const Elf_Dyn *dyn_soname)
1030 if (obj->z_origin && obj->origin_path == NULL) {
1031 obj->origin_path = xmalloc(PATH_MAX);
1032 if (rtld_dirname_abs(obj->path, obj->origin_path) == -1)
1036 if (dyn_rpath != NULL) {
1037 obj->rpath = (char *)obj->strtab + dyn_rpath->d_un.d_val;
1039 obj->rpath = origin_subst(obj->rpath, obj->origin_path);
1042 if (dyn_soname != NULL)
1043 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1047 digest_dynamic(Obj_Entry *obj, int early)
1049 const Elf_Dyn *dyn_rpath;
1050 const Elf_Dyn *dyn_soname;
1052 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname);
1053 digest_dynamic2(obj, dyn_rpath, dyn_soname);
1057 * Process a shared object's program header. This is used only for the
1058 * main program, when the kernel has already loaded the main program
1059 * into memory before calling the dynamic linker. It creates and
1060 * returns an Obj_Entry structure.
1063 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1066 const Elf_Phdr *phlimit = phdr + phnum;
1071 for (ph = phdr; ph < phlimit; ph++) {
1072 if (ph->p_type != PT_PHDR)
1076 obj->phsize = ph->p_memsz;
1077 obj->relocbase = (caddr_t)phdr - ph->p_vaddr;
1081 obj->stack_flags = PF_X | PF_R | PF_W;
1083 for (ph = phdr; ph < phlimit; ph++) {
1084 switch (ph->p_type) {
1087 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1091 if (nsegs == 0) { /* First load segment */
1092 obj->vaddrbase = trunc_page(ph->p_vaddr);
1093 obj->mapbase = obj->vaddrbase + obj->relocbase;
1094 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
1096 } else { /* Last load segment */
1097 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1104 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1109 obj->tlssize = ph->p_memsz;
1110 obj->tlsalign = ph->p_align;
1111 obj->tlsinitsize = ph->p_filesz;
1112 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1116 obj->stack_flags = ph->p_flags;
1120 obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1121 obj->relro_size = round_page(ph->p_memsz);
1126 _rtld_error("%s: too few PT_LOAD segments", path);
1135 dlcheck(void *handle)
1139 for (obj = obj_list; obj != NULL; obj = obj->next)
1140 if (obj == (Obj_Entry *) handle)
1143 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1144 _rtld_error("Invalid shared object handle %p", handle);
1151 * If the given object is already in the donelist, return true. Otherwise
1152 * add the object to the list and return false.
1155 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1159 for (i = 0; i < dlp->num_used; i++)
1160 if (dlp->objs[i] == obj)
1163 * Our donelist allocation should always be sufficient. But if
1164 * our threads locking isn't working properly, more shared objects
1165 * could have been loaded since we allocated the list. That should
1166 * never happen, but we'll handle it properly just in case it does.
1168 if (dlp->num_used < dlp->num_alloc)
1169 dlp->objs[dlp->num_used++] = obj;
1174 * Hash function for symbol table lookup. Don't even think about changing
1175 * this. It is specified by the System V ABI.
1178 elf_hash(const char *name)
1180 const unsigned char *p = (const unsigned char *) name;
1181 unsigned long h = 0;
1184 while (*p != '\0') {
1185 h = (h << 4) + *p++;
1186 if ((g = h & 0xf0000000) != 0)
1194 * Find the library with the given name, and return its full pathname.
1195 * The returned string is dynamically allocated. Generates an error
1196 * message and returns NULL if the library cannot be found.
1198 * If the second argument is non-NULL, then it refers to an already-
1199 * loaded shared object, whose library search path will be searched.
1201 * The search order is:
1203 * rpath in the referencing file
1208 find_library(const char *xname, const Obj_Entry *refobj)
1213 if (strchr(xname, '/') != NULL) { /* Hard coded pathname */
1214 if (xname[0] != '/' && !trust) {
1215 _rtld_error("Absolute pathname required for shared object \"%s\"",
1219 if (refobj != NULL && refobj->z_origin)
1220 return origin_subst(xname, refobj->origin_path);
1222 return xstrdup(xname);
1225 if (libmap_disable || (refobj == NULL) ||
1226 (name = lm_find(refobj->path, xname)) == NULL)
1227 name = (char *)xname;
1229 dbg(" Searching for \"%s\"", name);
1231 if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
1233 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
1234 (pathname = search_library_path(name, gethints())) != NULL ||
1235 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
1238 if(refobj != NULL && refobj->path != NULL) {
1239 _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
1240 name, basename(refobj->path));
1242 _rtld_error("Shared object \"%s\" not found", name);
1248 * Given a symbol number in a referencing object, find the corresponding
1249 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1250 * no definition was found. Returns a pointer to the Obj_Entry of the
1251 * defining object via the reference parameter DEFOBJ_OUT.
1254 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1255 const Obj_Entry **defobj_out, int flags, SymCache *cache,
1256 RtldLockState *lockstate)
1260 const Obj_Entry *defobj;
1266 * If we have already found this symbol, get the information from
1269 if (symnum >= refobj->nchains)
1270 return NULL; /* Bad object */
1271 if (cache != NULL && cache[symnum].sym != NULL) {
1272 *defobj_out = cache[symnum].obj;
1273 return cache[symnum].sym;
1276 ref = refobj->symtab + symnum;
1277 name = refobj->strtab + ref->st_name;
1282 * We don't have to do a full scale lookup if the symbol is local.
1283 * We know it will bind to the instance in this load module; to
1284 * which we already have a pointer (ie ref). By not doing a lookup,
1285 * we not only improve performance, but it also avoids unresolvable
1286 * symbols when local symbols are not in the hash table. This has
1287 * been seen with the ia64 toolchain.
1289 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1290 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1291 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1294 symlook_init(&req, name);
1296 req.ventry = fetch_ventry(refobj, symnum);
1297 req.lockstate = lockstate;
1298 res = symlook_default(&req, refobj);
1301 defobj = req.defobj_out;
1309 * If we found no definition and the reference is weak, treat the
1310 * symbol as having the value zero.
1312 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1318 *defobj_out = defobj;
1319 /* Record the information in the cache to avoid subsequent lookups. */
1320 if (cache != NULL) {
1321 cache[symnum].sym = def;
1322 cache[symnum].obj = defobj;
1325 if (refobj != &obj_rtld)
1326 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1332 * Return the search path from the ldconfig hints file, reading it if
1333 * necessary. Returns NULL if there are problems with the hints file,
1334 * or if the search path there is empty.
1341 if (hints == NULL) {
1343 struct elfhints_hdr hdr;
1346 /* Keep from trying again in case the hints file is bad. */
1349 if ((fd = open(ld_elf_hints_path, O_RDONLY)) == -1)
1351 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1352 hdr.magic != ELFHINTS_MAGIC ||
1357 p = xmalloc(hdr.dirlistlen + 1);
1358 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1359 read(fd, p, hdr.dirlistlen + 1) != (ssize_t)hdr.dirlistlen + 1) {
1367 return hints[0] != '\0' ? hints : NULL;
1371 init_dag(Obj_Entry *root)
1373 const Needed_Entry *needed;
1374 const Objlist_Entry *elm;
1377 if (root->dag_inited)
1379 donelist_init(&donelist);
1381 /* Root object belongs to own DAG. */
1382 objlist_push_tail(&root->dldags, root);
1383 objlist_push_tail(&root->dagmembers, root);
1384 donelist_check(&donelist, root);
1387 * Add dependencies of root object to DAG in breadth order
1388 * by exploiting the fact that each new object get added
1389 * to the tail of the dagmembers list.
1391 STAILQ_FOREACH(elm, &root->dagmembers, link) {
1392 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
1393 if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
1395 objlist_push_tail(&needed->obj->dldags, root);
1396 objlist_push_tail(&root->dagmembers, needed->obj);
1399 root->dag_inited = true;
1403 * Initialize the dynamic linker. The argument is the address at which
1404 * the dynamic linker has been mapped into memory. The primary task of
1405 * this function is to relocate the dynamic linker.
1408 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
1410 Obj_Entry objtmp; /* Temporary rtld object */
1411 const Elf_Dyn *dyn_rpath;
1412 const Elf_Dyn *dyn_soname;
1415 * Conjure up an Obj_Entry structure for the dynamic linker.
1417 * The "path" member can't be initialized yet because string constants
1418 * cannot yet be accessed. Below we will set it correctly.
1420 memset(&objtmp, 0, sizeof(objtmp));
1423 objtmp.mapbase = mapbase;
1425 objtmp.relocbase = mapbase;
1427 if (RTLD_IS_DYNAMIC()) {
1428 objtmp.dynamic = rtld_dynamic(&objtmp);
1429 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname);
1430 assert(objtmp.needed == NULL);
1431 #if !defined(__mips__)
1432 /* MIPS has a bogus DT_TEXTREL. */
1433 assert(!objtmp.textrel);
1437 * Temporarily put the dynamic linker entry into the object list, so
1438 * that symbols can be found.
1441 relocate_objects(&objtmp, true, &objtmp, NULL);
1444 /* Initialize the object list. */
1445 obj_tail = &obj_list;
1447 /* Now that non-local variables can be accesses, copy out obj_rtld. */
1448 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1450 if (aux_info[AT_PAGESZ] != NULL)
1451 pagesize = aux_info[AT_PAGESZ]->a_un.a_val;
1452 if (aux_info[AT_OSRELDATE] != NULL)
1453 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
1455 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname);
1457 /* Replace the path with a dynamically allocated copy. */
1458 obj_rtld.path = xstrdup(PATH_RTLD);
1460 r_debug.r_brk = r_debug_state;
1461 r_debug.r_state = RT_CONSISTENT;
1465 * Add the init functions from a needed object list (and its recursive
1466 * needed objects) to "list". This is not used directly; it is a helper
1467 * function for initlist_add_objects(). The write lock must be held
1468 * when this function is called.
1471 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1473 /* Recursively process the successor needed objects. */
1474 if (needed->next != NULL)
1475 initlist_add_neededs(needed->next, list);
1477 /* Process the current needed object. */
1478 if (needed->obj != NULL)
1479 initlist_add_objects(needed->obj, &needed->obj->next, list);
1483 * Scan all of the DAGs rooted in the range of objects from "obj" to
1484 * "tail" and add their init functions to "list". This recurses over
1485 * the DAGs and ensure the proper init ordering such that each object's
1486 * needed libraries are initialized before the object itself. At the
1487 * same time, this function adds the objects to the global finalization
1488 * list "list_fini" in the opposite order. The write lock must be
1489 * held when this function is called.
1492 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1494 if (obj->init_scanned || obj->init_done)
1496 obj->init_scanned = true;
1498 /* Recursively process the successor objects. */
1499 if (&obj->next != tail)
1500 initlist_add_objects(obj->next, tail, list);
1502 /* Recursively process the needed objects. */
1503 if (obj->needed != NULL)
1504 initlist_add_neededs(obj->needed, list);
1506 /* Add the object to the init list. */
1507 if (obj->init != (Elf_Addr)NULL)
1508 objlist_push_tail(list, obj);
1510 /* Add the object to the global fini list in the reverse order. */
1511 if (obj->fini != (Elf_Addr)NULL && !obj->on_fini_list) {
1512 objlist_push_head(&list_fini, obj);
1513 obj->on_fini_list = true;
1518 #define FPTR_TARGET(f) ((Elf_Addr) (f))
1522 free_needed_filtees(Needed_Entry *n)
1524 Needed_Entry *needed, *needed1;
1526 for (needed = n; needed != NULL; needed = needed->next) {
1527 if (needed->obj != NULL) {
1528 dlclose(needed->obj);
1532 for (needed = n; needed != NULL; needed = needed1) {
1533 needed1 = needed->next;
1539 unload_filtees(Obj_Entry *obj)
1542 free_needed_filtees(obj->needed_filtees);
1543 obj->needed_filtees = NULL;
1544 free_needed_filtees(obj->needed_aux_filtees);
1545 obj->needed_aux_filtees = NULL;
1546 obj->filtees_loaded = false;
1550 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags)
1553 for (; needed != NULL; needed = needed->next) {
1554 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
1555 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
1561 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
1564 lock_restart_for_upgrade(lockstate);
1565 if (!obj->filtees_loaded) {
1566 load_filtee1(obj, obj->needed_filtees, flags);
1567 load_filtee1(obj, obj->needed_aux_filtees, flags);
1568 obj->filtees_loaded = true;
1573 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
1577 for (; needed != NULL; needed = needed->next) {
1578 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
1579 flags & ~RTLD_LO_NOLOAD);
1580 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
1582 if (obj1 != NULL && obj1->z_nodelete && !obj1->ref_nodel) {
1583 dbg("obj %s nodelete", obj1->path);
1586 obj1->ref_nodel = true;
1593 * Given a shared object, traverse its list of needed objects, and load
1594 * each of them. Returns 0 on success. Generates an error message and
1595 * returns -1 on failure.
1598 load_needed_objects(Obj_Entry *first, int flags)
1602 for (obj = first; obj != NULL; obj = obj->next) {
1603 if (process_needed(obj, obj->needed, flags) == -1)
1610 load_preload_objects(void)
1612 char *p = ld_preload;
1613 static const char delim[] = " \t:;";
1618 p += strspn(p, delim);
1619 while (*p != '\0') {
1620 size_t len = strcspn(p, delim);
1625 if (load_object(p, -1, NULL, 0) == NULL)
1626 return -1; /* XXX - cleanup */
1629 p += strspn(p, delim);
1631 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
1636 printable_path(const char *path)
1639 return (path == NULL ? "<unknown>" : path);
1643 * Load a shared object into memory, if it is not already loaded. The
1644 * object may be specified by name or by user-supplied file descriptor
1645 * fd_u. In the later case, the fd_u descriptor is not closed, but its
1648 * Returns a pointer to the Obj_Entry for the object. Returns NULL
1652 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
1660 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
1661 if (object_match_name(obj, name))
1665 path = find_library(name, refobj);
1672 * If we didn't find a match by pathname, or the name is not
1673 * supplied, open the file and check again by device and inode.
1674 * This avoids false mismatches caused by multiple links or ".."
1677 * To avoid a race, we open the file and use fstat() rather than
1682 if ((fd = open(path, O_RDONLY)) == -1) {
1683 _rtld_error("Cannot open \"%s\"", path);
1690 _rtld_error("Cannot dup fd");
1695 if (fstat(fd, &sb) == -1) {
1696 _rtld_error("Cannot fstat \"%s\"", printable_path(path));
1701 for (obj = obj_list->next; obj != NULL; obj = obj->next)
1702 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
1704 if (obj != NULL && name != NULL) {
1705 object_add_name(obj, name);
1710 if (flags & RTLD_LO_NOLOAD) {
1716 /* First use of this object, so we must map it in */
1717 obj = do_load_object(fd, name, path, &sb, flags);
1726 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
1733 * but first, make sure that environment variables haven't been
1734 * used to circumvent the noexec flag on a filesystem.
1736 if (dangerous_ld_env) {
1737 if (fstatfs(fd, &fs) != 0) {
1738 _rtld_error("Cannot fstatfs \"%s\"", printable_path(path));
1741 if (fs.f_flags & MNT_NOEXEC) {
1742 _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
1746 dbg("loading \"%s\"", printable_path(path));
1747 obj = map_object(fd, printable_path(path), sbp);
1752 * If DT_SONAME is present in the object, digest_dynamic2 already
1753 * added it to the object names.
1756 object_add_name(obj, name);
1758 digest_dynamic(obj, 0);
1759 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
1761 dbg("refusing to load non-loadable \"%s\"", obj->path);
1762 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
1763 munmap(obj->mapbase, obj->mapsize);
1769 obj_tail = &obj->next;
1772 linkmap_add(obj); /* for GDB & dlinfo() */
1773 max_stack_flags |= obj->stack_flags;
1775 dbg(" %p .. %p: %s", obj->mapbase,
1776 obj->mapbase + obj->mapsize - 1, obj->path);
1778 dbg(" WARNING: %s has impure text", obj->path);
1779 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
1786 obj_from_addr(const void *addr)
1790 for (obj = obj_list; obj != NULL; obj = obj->next) {
1791 if (addr < (void *) obj->mapbase)
1793 if (addr < (void *) (obj->mapbase + obj->mapsize))
1800 * Call the finalization functions for each of the objects in "list"
1801 * belonging to the DAG of "root" and referenced once. If NULL "root"
1802 * is specified, every finalization function will be called regardless
1803 * of the reference count and the list elements won't be freed. All of
1804 * the objects are expected to have non-NULL fini functions.
1807 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
1812 assert(root == NULL || root->refcount == 1);
1815 * Preserve the current error message since a fini function might
1816 * call into the dynamic linker and overwrite it.
1818 saved_msg = errmsg_save();
1820 STAILQ_FOREACH(elm, list, link) {
1821 if (root != NULL && (elm->obj->refcount != 1 ||
1822 objlist_find(&root->dagmembers, elm->obj) == NULL))
1824 dbg("calling fini function for %s at %p", elm->obj->path,
1825 (void *)elm->obj->fini);
1826 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini, 0, 0,
1828 /* Remove object from fini list to prevent recursive invocation. */
1829 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1831 * XXX: If a dlopen() call references an object while the
1832 * fini function is in progress, we might end up trying to
1833 * unload the referenced object in dlclose() or the object
1834 * won't be unloaded although its fini function has been
1837 lock_release(rtld_bind_lock, lockstate);
1838 call_initfini_pointer(elm->obj, elm->obj->fini);
1839 wlock_acquire(rtld_bind_lock, lockstate);
1840 /* No need to free anything if process is going down. */
1844 * We must restart the list traversal after every fini call
1845 * because a dlclose() call from the fini function or from
1846 * another thread might have modified the reference counts.
1850 } while (elm != NULL);
1851 errmsg_restore(saved_msg);
1855 * Call the initialization functions for each of the objects in
1856 * "list". All of the objects are expected to have non-NULL init
1860 objlist_call_init(Objlist *list, RtldLockState *lockstate)
1867 * Clean init_scanned flag so that objects can be rechecked and
1868 * possibly initialized earlier if any of vectors called below
1869 * cause the change by using dlopen.
1871 for (obj = obj_list; obj != NULL; obj = obj->next)
1872 obj->init_scanned = false;
1875 * Preserve the current error message since an init function might
1876 * call into the dynamic linker and overwrite it.
1878 saved_msg = errmsg_save();
1879 STAILQ_FOREACH(elm, list, link) {
1880 if (elm->obj->init_done) /* Initialized early. */
1882 dbg("calling init function for %s at %p", elm->obj->path,
1883 (void *)elm->obj->init);
1884 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init, 0, 0,
1887 * Race: other thread might try to use this object before current
1888 * one completes the initilization. Not much can be done here
1889 * without better locking.
1891 elm->obj->init_done = true;
1892 lock_release(rtld_bind_lock, lockstate);
1893 call_initfini_pointer(elm->obj, elm->obj->init);
1894 wlock_acquire(rtld_bind_lock, lockstate);
1896 errmsg_restore(saved_msg);
1900 objlist_clear(Objlist *list)
1904 while (!STAILQ_EMPTY(list)) {
1905 elm = STAILQ_FIRST(list);
1906 STAILQ_REMOVE_HEAD(list, link);
1911 static Objlist_Entry *
1912 objlist_find(Objlist *list, const Obj_Entry *obj)
1916 STAILQ_FOREACH(elm, list, link)
1917 if (elm->obj == obj)
1923 objlist_init(Objlist *list)
1929 objlist_push_head(Objlist *list, Obj_Entry *obj)
1933 elm = NEW(Objlist_Entry);
1935 STAILQ_INSERT_HEAD(list, elm, link);
1939 objlist_push_tail(Objlist *list, Obj_Entry *obj)
1943 elm = NEW(Objlist_Entry);
1945 STAILQ_INSERT_TAIL(list, elm, link);
1949 objlist_remove(Objlist *list, Obj_Entry *obj)
1953 if ((elm = objlist_find(list, obj)) != NULL) {
1954 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1960 * Relocate newly-loaded shared objects. The argument is a pointer to
1961 * the Obj_Entry for the first such object. All objects from the first
1962 * to the end of the list of objects are relocated. Returns 0 on success,
1966 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
1967 RtldLockState *lockstate)
1971 for (obj = first; obj != NULL; obj = obj->next) {
1973 dbg("relocating \"%s\"", obj->path);
1974 if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
1975 obj->symtab == NULL || obj->strtab == NULL) {
1976 _rtld_error("%s: Shared object has no run-time symbol table",
1982 /* There are relocations to the write-protected text segment. */
1983 if (mprotect(obj->mapbase, obj->textsize,
1984 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
1985 _rtld_error("%s: Cannot write-enable text segment: %s",
1986 obj->path, strerror(errno));
1991 /* Process the non-PLT relocations. */
1992 if (reloc_non_plt(obj, rtldobj, lockstate))
1995 if (obj->textrel) { /* Re-protected the text segment. */
1996 if (mprotect(obj->mapbase, obj->textsize,
1997 PROT_READ|PROT_EXEC) == -1) {
1998 _rtld_error("%s: Cannot write-protect text segment: %s",
1999 obj->path, strerror(errno));
2005 /* Set the special PLT or GOT entries. */
2008 /* Process the PLT relocations. */
2009 if (reloc_plt(obj) == -1)
2011 /* Relocate the jump slots if we are doing immediate binding. */
2012 if (obj->bind_now || bind_now)
2013 if (reloc_jmpslots(obj, lockstate) == -1)
2016 if (obj->relro_size > 0) {
2017 if (mprotect(obj->relro_page, obj->relro_size, PROT_READ) == -1) {
2018 _rtld_error("%s: Cannot enforce relro protection: %s",
2019 obj->path, strerror(errno));
2025 * Set up the magic number and version in the Obj_Entry. These
2026 * were checked in the crt1.o from the original ElfKit, so we
2027 * set them for backward compatibility.
2029 obj->magic = RTLD_MAGIC;
2030 obj->version = RTLD_VERSION;
2037 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
2038 * referencing STT_GNU_IFUNC symbols is postponed till the other
2039 * relocations are done. The indirect functions specified as
2040 * ifunc are allowed to call other symbols, so we need to have
2041 * objects relocated before asking for resolution from indirects.
2043 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
2044 * instead of the usual lazy handling of PLT slots. It is
2045 * consistent with how GNU does it.
2048 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, RtldLockState *lockstate)
2050 if (obj->irelative && reloc_iresolve(obj, lockstate) == -1)
2052 if ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
2053 reloc_gnu_ifunc(obj, lockstate) == -1)
2059 resolve_objects_ifunc(Obj_Entry *first, bool bind_now, RtldLockState *lockstate)
2063 for (obj = first; obj != NULL; obj = obj->next) {
2064 if (resolve_object_ifunc(obj, bind_now, lockstate) == -1)
2071 initlist_objects_ifunc(Objlist *list, bool bind_now, RtldLockState *lockstate)
2075 STAILQ_FOREACH(elm, list, link) {
2076 if (resolve_object_ifunc(elm->obj, bind_now, lockstate) == -1)
2083 * Cleanup procedure. It will be called (by the atexit mechanism) just
2084 * before the process exits.
2089 RtldLockState lockstate;
2091 wlock_acquire(rtld_bind_lock, &lockstate);
2093 objlist_call_fini(&list_fini, NULL, &lockstate);
2094 /* No need to remove the items from the list, since we are exiting. */
2095 if (!libmap_disable)
2097 lock_release(rtld_bind_lock, &lockstate);
2101 path_enumerate(const char *path, path_enum_proc callback, void *arg)
2109 path += strspn(path, ":;");
2110 while (*path != '\0') {
2114 len = strcspn(path, ":;");
2116 trans = lm_findn(NULL, path, len);
2118 res = callback(trans, strlen(trans), arg);
2121 res = callback(path, len, arg);
2127 path += strspn(path, ":;");
2133 struct try_library_args {
2141 try_library_path(const char *dir, size_t dirlen, void *param)
2143 struct try_library_args *arg;
2146 if (*dir == '/' || trust) {
2149 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
2152 pathname = arg->buffer;
2153 strncpy(pathname, dir, dirlen);
2154 pathname[dirlen] = '/';
2155 strcpy(pathname + dirlen + 1, arg->name);
2157 dbg(" Trying \"%s\"", pathname);
2158 if (access(pathname, F_OK) == 0) { /* We found it */
2159 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
2160 strcpy(pathname, arg->buffer);
2168 search_library_path(const char *name, const char *path)
2171 struct try_library_args arg;
2177 arg.namelen = strlen(name);
2178 arg.buffer = xmalloc(PATH_MAX);
2179 arg.buflen = PATH_MAX;
2181 p = path_enumerate(path, try_library_path, &arg);
2189 dlclose(void *handle)
2192 RtldLockState lockstate;
2194 wlock_acquire(rtld_bind_lock, &lockstate);
2195 root = dlcheck(handle);
2197 lock_release(rtld_bind_lock, &lockstate);
2200 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
2203 /* Unreference the object and its dependencies. */
2204 root->dl_refcount--;
2206 if (root->refcount == 1) {
2208 * The object will be no longer referenced, so we must unload it.
2209 * First, call the fini functions.
2211 objlist_call_fini(&list_fini, root, &lockstate);
2215 /* Finish cleaning up the newly-unreferenced objects. */
2216 GDB_STATE(RT_DELETE,&root->linkmap);
2217 unload_object(root);
2218 GDB_STATE(RT_CONSISTENT,NULL);
2222 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
2223 lock_release(rtld_bind_lock, &lockstate);
2230 char *msg = error_message;
2231 error_message = NULL;
2236 * This function is deprecated and has no effect.
2239 dllockinit(void *context,
2240 void *(*lock_create)(void *context),
2241 void (*rlock_acquire)(void *lock),
2242 void (*wlock_acquire)(void *lock),
2243 void (*lock_release)(void *lock),
2244 void (*lock_destroy)(void *lock),
2245 void (*context_destroy)(void *context))
2247 static void *cur_context;
2248 static void (*cur_context_destroy)(void *);
2250 /* Just destroy the context from the previous call, if necessary. */
2251 if (cur_context_destroy != NULL)
2252 cur_context_destroy(cur_context);
2253 cur_context = context;
2254 cur_context_destroy = context_destroy;
2258 dlopen(const char *name, int mode)
2261 return (rtld_dlopen(name, -1, mode));
2265 fdlopen(int fd, int mode)
2268 return (rtld_dlopen(NULL, fd, mode));
2272 rtld_dlopen(const char *name, int fd, int mode)
2274 RtldLockState lockstate;
2277 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
2278 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
2279 if (ld_tracing != NULL) {
2280 rlock_acquire(rtld_bind_lock, &lockstate);
2281 if (sigsetjmp(lockstate.env, 0) != 0)
2282 lock_upgrade(rtld_bind_lock, &lockstate);
2283 environ = (char **)*get_program_var_addr("environ", &lockstate);
2284 lock_release(rtld_bind_lock, &lockstate);
2286 lo_flags = RTLD_LO_DLOPEN;
2287 if (mode & RTLD_NODELETE)
2288 lo_flags |= RTLD_LO_NODELETE;
2289 if (mode & RTLD_NOLOAD)
2290 lo_flags |= RTLD_LO_NOLOAD;
2291 if (ld_tracing != NULL)
2292 lo_flags |= RTLD_LO_TRACE;
2294 return (dlopen_object(name, fd, obj_main, lo_flags,
2295 mode & (RTLD_MODEMASK | RTLD_GLOBAL)));
2299 dlopen_cleanup(Obj_Entry *obj)
2304 if (obj->refcount == 0)
2309 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
2312 Obj_Entry **old_obj_tail;
2315 RtldLockState lockstate;
2318 objlist_init(&initlist);
2320 wlock_acquire(rtld_bind_lock, &lockstate);
2321 GDB_STATE(RT_ADD,NULL);
2323 old_obj_tail = obj_tail;
2325 if (name == NULL && fd == -1) {
2329 obj = load_object(name, fd, refobj, lo_flags);
2334 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
2335 objlist_push_tail(&list_global, obj);
2336 if (*old_obj_tail != NULL) { /* We loaded something new. */
2337 assert(*old_obj_tail == obj);
2338 result = load_needed_objects(obj, lo_flags & RTLD_LO_DLOPEN);
2342 result = rtld_verify_versions(&obj->dagmembers);
2343 if (result != -1 && ld_tracing)
2345 if (result == -1 || (relocate_objects(obj, (mode & RTLD_MODEMASK)
2346 == RTLD_NOW, &obj_rtld, &lockstate)) == -1) {
2347 dlopen_cleanup(obj);
2350 /* Make list of init functions to call. */
2351 initlist_add_objects(obj, &obj->next, &initlist);
2356 * Bump the reference counts for objects on this DAG. If
2357 * this is the first dlopen() call for the object that was
2358 * already loaded as a dependency, initialize the dag
2364 if ((lo_flags & RTLD_LO_TRACE) != 0)
2367 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
2368 obj->z_nodelete) && !obj->ref_nodel) {
2369 dbg("obj %s nodelete", obj->path);
2371 obj->z_nodelete = obj->ref_nodel = true;
2375 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
2377 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
2379 map_stacks_exec(&lockstate);
2381 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
2382 &lockstate) == -1) {
2383 objlist_clear(&initlist);
2384 dlopen_cleanup(obj);
2385 lock_release(rtld_bind_lock, &lockstate);
2389 /* Call the init functions. */
2390 objlist_call_init(&initlist, &lockstate);
2391 objlist_clear(&initlist);
2392 lock_release(rtld_bind_lock, &lockstate);
2395 trace_loaded_objects(obj);
2396 lock_release(rtld_bind_lock, &lockstate);
2401 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
2405 const Obj_Entry *obj, *defobj;
2408 RtldLockState lockstate;
2413 symlook_init(&req, name);
2415 req.flags = flags | SYMLOOK_IN_PLT;
2416 req.lockstate = &lockstate;
2418 rlock_acquire(rtld_bind_lock, &lockstate);
2419 if (sigsetjmp(lockstate.env, 0) != 0)
2420 lock_upgrade(rtld_bind_lock, &lockstate);
2421 if (handle == NULL || handle == RTLD_NEXT ||
2422 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
2424 if ((obj = obj_from_addr(retaddr)) == NULL) {
2425 _rtld_error("Cannot determine caller's shared object");
2426 lock_release(rtld_bind_lock, &lockstate);
2429 if (handle == NULL) { /* Just the caller's shared object. */
2430 res = symlook_obj(&req, obj);
2433 defobj = req.defobj_out;
2435 } else if (handle == RTLD_NEXT || /* Objects after caller's */
2436 handle == RTLD_SELF) { /* ... caller included */
2437 if (handle == RTLD_NEXT)
2439 for (; obj != NULL; obj = obj->next) {
2440 res = symlook_obj(&req, obj);
2443 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) {
2445 defobj = req.defobj_out;
2446 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2452 * Search the dynamic linker itself, and possibly resolve the
2453 * symbol from there. This is how the application links to
2454 * dynamic linker services such as dlopen.
2456 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2457 res = symlook_obj(&req, &obj_rtld);
2460 defobj = req.defobj_out;
2464 assert(handle == RTLD_DEFAULT);
2465 res = symlook_default(&req, obj);
2467 defobj = req.defobj_out;
2472 if ((obj = dlcheck(handle)) == NULL) {
2473 lock_release(rtld_bind_lock, &lockstate);
2477 donelist_init(&donelist);
2478 if (obj->mainprog) {
2479 /* Handle obtained by dlopen(NULL, ...) implies global scope. */
2480 res = symlook_global(&req, &donelist);
2483 defobj = req.defobj_out;
2486 * Search the dynamic linker itself, and possibly resolve the
2487 * symbol from there. This is how the application links to
2488 * dynamic linker services such as dlopen.
2490 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2491 res = symlook_obj(&req, &obj_rtld);
2494 defobj = req.defobj_out;
2499 /* Search the whole DAG rooted at the given object. */
2500 res = symlook_list(&req, &obj->dagmembers, &donelist);
2503 defobj = req.defobj_out;
2509 lock_release(rtld_bind_lock, &lockstate);
2512 * The value required by the caller is derived from the value
2513 * of the symbol. For the ia64 architecture, we need to
2514 * construct a function descriptor which the caller can use to
2515 * call the function with the right 'gp' value. For other
2516 * architectures and for non-functions, the value is simply
2517 * the relocated value of the symbol.
2519 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
2520 return (make_function_pointer(def, defobj));
2521 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
2522 return (rtld_resolve_ifunc(defobj, def));
2524 return (defobj->relocbase + def->st_value);
2527 _rtld_error("Undefined symbol \"%s\"", name);
2528 lock_release(rtld_bind_lock, &lockstate);
2533 dlsym(void *handle, const char *name)
2535 return do_dlsym(handle, name, __builtin_return_address(0), NULL,
2540 dlfunc(void *handle, const char *name)
2547 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
2553 dlvsym(void *handle, const char *name, const char *version)
2557 ventry.name = version;
2559 ventry.hash = elf_hash(version);
2561 return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
2566 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
2568 const Obj_Entry *obj;
2569 RtldLockState lockstate;
2571 rlock_acquire(rtld_bind_lock, &lockstate);
2572 obj = obj_from_addr(addr);
2574 _rtld_error("No shared object contains address");
2575 lock_release(rtld_bind_lock, &lockstate);
2578 rtld_fill_dl_phdr_info(obj, phdr_info);
2579 lock_release(rtld_bind_lock, &lockstate);
2584 dladdr(const void *addr, Dl_info *info)
2586 const Obj_Entry *obj;
2589 unsigned long symoffset;
2590 RtldLockState lockstate;
2592 rlock_acquire(rtld_bind_lock, &lockstate);
2593 obj = obj_from_addr(addr);
2595 _rtld_error("No shared object contains address");
2596 lock_release(rtld_bind_lock, &lockstate);
2599 info->dli_fname = obj->path;
2600 info->dli_fbase = obj->mapbase;
2601 info->dli_saddr = (void *)0;
2602 info->dli_sname = NULL;
2605 * Walk the symbol list looking for the symbol whose address is
2606 * closest to the address sent in.
2608 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
2609 def = obj->symtab + symoffset;
2612 * For skip the symbol if st_shndx is either SHN_UNDEF or
2615 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
2619 * If the symbol is greater than the specified address, or if it
2620 * is further away from addr than the current nearest symbol,
2623 symbol_addr = obj->relocbase + def->st_value;
2624 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
2627 /* Update our idea of the nearest symbol. */
2628 info->dli_sname = obj->strtab + def->st_name;
2629 info->dli_saddr = symbol_addr;
2632 if (info->dli_saddr == addr)
2635 lock_release(rtld_bind_lock, &lockstate);
2640 dlinfo(void *handle, int request, void *p)
2642 const Obj_Entry *obj;
2643 RtldLockState lockstate;
2646 rlock_acquire(rtld_bind_lock, &lockstate);
2648 if (handle == NULL || handle == RTLD_SELF) {
2651 retaddr = __builtin_return_address(0); /* __GNUC__ only */
2652 if ((obj = obj_from_addr(retaddr)) == NULL)
2653 _rtld_error("Cannot determine caller's shared object");
2655 obj = dlcheck(handle);
2658 lock_release(rtld_bind_lock, &lockstate);
2664 case RTLD_DI_LINKMAP:
2665 *((struct link_map const **)p) = &obj->linkmap;
2667 case RTLD_DI_ORIGIN:
2668 error = rtld_dirname(obj->path, p);
2671 case RTLD_DI_SERINFOSIZE:
2672 case RTLD_DI_SERINFO:
2673 error = do_search_info(obj, request, (struct dl_serinfo *)p);
2677 _rtld_error("Invalid request %d passed to dlinfo()", request);
2681 lock_release(rtld_bind_lock, &lockstate);
2687 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
2690 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
2691 phdr_info->dlpi_name = STAILQ_FIRST(&obj->names) ?
2692 STAILQ_FIRST(&obj->names)->name : obj->path;
2693 phdr_info->dlpi_phdr = obj->phdr;
2694 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
2695 phdr_info->dlpi_tls_modid = obj->tlsindex;
2696 phdr_info->dlpi_tls_data = obj->tlsinit;
2697 phdr_info->dlpi_adds = obj_loads;
2698 phdr_info->dlpi_subs = obj_loads - obj_count;
2702 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
2704 struct dl_phdr_info phdr_info;
2705 const Obj_Entry *obj;
2706 RtldLockState bind_lockstate, phdr_lockstate;
2709 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
2710 rlock_acquire(rtld_bind_lock, &bind_lockstate);
2714 for (obj = obj_list; obj != NULL; obj = obj->next) {
2715 rtld_fill_dl_phdr_info(obj, &phdr_info);
2716 if ((error = callback(&phdr_info, sizeof phdr_info, param)) != 0)
2720 lock_release(rtld_bind_lock, &bind_lockstate);
2721 lock_release(rtld_phdr_lock, &phdr_lockstate);
2726 struct fill_search_info_args {
2729 Dl_serinfo *serinfo;
2730 Dl_serpath *serpath;
2735 fill_search_info(const char *dir, size_t dirlen, void *param)
2737 struct fill_search_info_args *arg;
2741 if (arg->request == RTLD_DI_SERINFOSIZE) {
2742 arg->serinfo->dls_cnt ++;
2743 arg->serinfo->dls_size += sizeof(Dl_serpath) + dirlen + 1;
2745 struct dl_serpath *s_entry;
2747 s_entry = arg->serpath;
2748 s_entry->dls_name = arg->strspace;
2749 s_entry->dls_flags = arg->flags;
2751 strncpy(arg->strspace, dir, dirlen);
2752 arg->strspace[dirlen] = '\0';
2754 arg->strspace += dirlen + 1;
2762 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
2764 struct dl_serinfo _info;
2765 struct fill_search_info_args args;
2767 args.request = RTLD_DI_SERINFOSIZE;
2768 args.serinfo = &_info;
2770 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2773 path_enumerate(ld_library_path, fill_search_info, &args);
2774 path_enumerate(obj->rpath, fill_search_info, &args);
2775 path_enumerate(gethints(), fill_search_info, &args);
2776 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
2779 if (request == RTLD_DI_SERINFOSIZE) {
2780 info->dls_size = _info.dls_size;
2781 info->dls_cnt = _info.dls_cnt;
2785 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
2786 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
2790 args.request = RTLD_DI_SERINFO;
2791 args.serinfo = info;
2792 args.serpath = &info->dls_serpath[0];
2793 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
2795 args.flags = LA_SER_LIBPATH;
2796 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
2799 args.flags = LA_SER_RUNPATH;
2800 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
2803 args.flags = LA_SER_CONFIG;
2804 if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
2807 args.flags = LA_SER_DEFAULT;
2808 if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
2814 rtld_dirname(const char *path, char *bname)
2818 /* Empty or NULL string gets treated as "." */
2819 if (path == NULL || *path == '\0') {
2825 /* Strip trailing slashes */
2826 endp = path + strlen(path) - 1;
2827 while (endp > path && *endp == '/')
2830 /* Find the start of the dir */
2831 while (endp > path && *endp != '/')
2834 /* Either the dir is "/" or there are no slashes */
2836 bname[0] = *endp == '/' ? '/' : '.';
2842 } while (endp > path && *endp == '/');
2845 if (endp - path + 2 > PATH_MAX)
2847 _rtld_error("Filename is too long: %s", path);
2851 strncpy(bname, path, endp - path + 1);
2852 bname[endp - path + 1] = '\0';
2857 rtld_dirname_abs(const char *path, char *base)
2859 char base_rel[PATH_MAX];
2861 if (rtld_dirname(path, base) == -1)
2865 if (getcwd(base_rel, sizeof(base_rel)) == NULL ||
2866 strlcat(base_rel, "/", sizeof(base_rel)) >= sizeof(base_rel) ||
2867 strlcat(base_rel, base, sizeof(base_rel)) >= sizeof(base_rel))
2869 strcpy(base, base_rel);
2874 linkmap_add(Obj_Entry *obj)
2876 struct link_map *l = &obj->linkmap;
2877 struct link_map *prev;
2879 obj->linkmap.l_name = obj->path;
2880 obj->linkmap.l_addr = obj->mapbase;
2881 obj->linkmap.l_ld = obj->dynamic;
2883 /* GDB needs load offset on MIPS to use the symbols */
2884 obj->linkmap.l_offs = obj->relocbase;
2887 if (r_debug.r_map == NULL) {
2893 * Scan to the end of the list, but not past the entry for the
2894 * dynamic linker, which we want to keep at the very end.
2896 for (prev = r_debug.r_map;
2897 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
2898 prev = prev->l_next)
2901 /* Link in the new entry. */
2903 l->l_next = prev->l_next;
2904 if (l->l_next != NULL)
2905 l->l_next->l_prev = l;
2910 linkmap_delete(Obj_Entry *obj)
2912 struct link_map *l = &obj->linkmap;
2914 if (l->l_prev == NULL) {
2915 if ((r_debug.r_map = l->l_next) != NULL)
2916 l->l_next->l_prev = NULL;
2920 if ((l->l_prev->l_next = l->l_next) != NULL)
2921 l->l_next->l_prev = l->l_prev;
2925 * Function for the debugger to set a breakpoint on to gain control.
2927 * The two parameters allow the debugger to easily find and determine
2928 * what the runtime loader is doing and to whom it is doing it.
2930 * When the loadhook trap is hit (r_debug_state, set at program
2931 * initialization), the arguments can be found on the stack:
2933 * +8 struct link_map *m
2934 * +4 struct r_debug *rd
2938 r_debug_state(struct r_debug* rd, struct link_map *m)
2941 * The following is a hack to force the compiler to emit calls to
2942 * this function, even when optimizing. If the function is empty,
2943 * the compiler is not obliged to emit any code for calls to it,
2944 * even when marked __noinline. However, gdb depends on those
2947 __asm __volatile("" : : : "memory");
2951 * Get address of the pointer variable in the main program.
2952 * Prefer non-weak symbol over the weak one.
2954 static const void **
2955 get_program_var_addr(const char *name, RtldLockState *lockstate)
2960 symlook_init(&req, name);
2961 req.lockstate = lockstate;
2962 donelist_init(&donelist);
2963 if (symlook_global(&req, &donelist) != 0)
2965 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
2966 return ((const void **)make_function_pointer(req.sym_out,
2968 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
2969 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
2971 return ((const void **)(req.defobj_out->relocbase +
2972 req.sym_out->st_value));
2976 * Set a pointer variable in the main program to the given value. This
2977 * is used to set key variables such as "environ" before any of the
2978 * init functions are called.
2981 set_program_var(const char *name, const void *value)
2985 if ((addr = get_program_var_addr(name, NULL)) != NULL) {
2986 dbg("\"%s\": *%p <-- %p", name, addr, value);
2992 * Search the global objects, including dependencies and main object,
2993 * for the given symbol.
2996 symlook_global(SymLook *req, DoneList *donelist)
2999 const Objlist_Entry *elm;
3002 symlook_init_from_req(&req1, req);
3004 /* Search all objects loaded at program start up. */
3005 if (req->defobj_out == NULL ||
3006 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3007 res = symlook_list(&req1, &list_main, donelist);
3008 if (res == 0 && (req->defobj_out == NULL ||
3009 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3010 req->sym_out = req1.sym_out;
3011 req->defobj_out = req1.defobj_out;
3012 assert(req->defobj_out != NULL);
3016 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
3017 STAILQ_FOREACH(elm, &list_global, link) {
3018 if (req->defobj_out != NULL &&
3019 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3021 res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
3022 if (res == 0 && (req->defobj_out == NULL ||
3023 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3024 req->sym_out = req1.sym_out;
3025 req->defobj_out = req1.defobj_out;
3026 assert(req->defobj_out != NULL);
3030 return (req->sym_out != NULL ? 0 : ESRCH);
3034 * Given a symbol name in a referencing object, find the corresponding
3035 * definition of the symbol. Returns a pointer to the symbol, or NULL if
3036 * no definition was found. Returns a pointer to the Obj_Entry of the
3037 * defining object via the reference parameter DEFOBJ_OUT.
3040 symlook_default(SymLook *req, const Obj_Entry *refobj)
3043 const Objlist_Entry *elm;
3047 donelist_init(&donelist);
3048 symlook_init_from_req(&req1, req);
3050 /* Look first in the referencing object if linked symbolically. */
3051 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
3052 res = symlook_obj(&req1, refobj);
3054 req->sym_out = req1.sym_out;
3055 req->defobj_out = req1.defobj_out;
3056 assert(req->defobj_out != NULL);
3060 symlook_global(req, &donelist);
3062 /* Search all dlopened DAGs containing the referencing object. */
3063 STAILQ_FOREACH(elm, &refobj->dldags, link) {
3064 if (req->sym_out != NULL &&
3065 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3067 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
3068 if (res == 0 && (req->sym_out == NULL ||
3069 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3070 req->sym_out = req1.sym_out;
3071 req->defobj_out = req1.defobj_out;
3072 assert(req->defobj_out != NULL);
3077 * Search the dynamic linker itself, and possibly resolve the
3078 * symbol from there. This is how the application links to
3079 * dynamic linker services such as dlopen.
3081 if (req->sym_out == NULL ||
3082 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3083 res = symlook_obj(&req1, &obj_rtld);
3085 req->sym_out = req1.sym_out;
3086 req->defobj_out = req1.defobj_out;
3087 assert(req->defobj_out != NULL);
3091 return (req->sym_out != NULL ? 0 : ESRCH);
3095 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
3098 const Obj_Entry *defobj;
3099 const Objlist_Entry *elm;
3105 STAILQ_FOREACH(elm, objlist, link) {
3106 if (donelist_check(dlp, elm->obj))
3108 symlook_init_from_req(&req1, req);
3109 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
3110 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3112 defobj = req1.defobj_out;
3113 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3120 req->defobj_out = defobj;
3127 * Search the chain of DAGS cointed to by the given Needed_Entry
3128 * for a symbol of the given name. Each DAG is scanned completely
3129 * before advancing to the next one. Returns a pointer to the symbol,
3130 * or NULL if no definition was found.
3133 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
3136 const Needed_Entry *n;
3137 const Obj_Entry *defobj;
3143 symlook_init_from_req(&req1, req);
3144 for (n = needed; n != NULL; n = n->next) {
3145 if (n->obj == NULL ||
3146 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
3148 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3150 defobj = req1.defobj_out;
3151 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3157 req->defobj_out = defobj;
3164 * Search the symbol table of a single shared object for a symbol of
3165 * the given name and version, if requested. Returns a pointer to the
3166 * symbol, or NULL if no definition was found. If the object is
3167 * filter, return filtered symbol from filtee.
3169 * The symbol's hash value is passed in for efficiency reasons; that
3170 * eliminates many recomputations of the hash value.
3173 symlook_obj(SymLook *req, const Obj_Entry *obj)
3179 mres = symlook_obj1(req, obj);
3181 if (obj->needed_filtees != NULL) {
3182 load_filtees(__DECONST(Obj_Entry *, obj), 0, req->lockstate);
3183 donelist_init(&donelist);
3184 symlook_init_from_req(&req1, req);
3185 res = symlook_needed(&req1, obj->needed_filtees, &donelist);
3187 req->sym_out = req1.sym_out;
3188 req->defobj_out = req1.defobj_out;
3192 if (obj->needed_aux_filtees != NULL) {
3193 load_filtees(__DECONST(Obj_Entry *, obj), 0, req->lockstate);
3194 donelist_init(&donelist);
3195 symlook_init_from_req(&req1, req);
3196 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
3198 req->sym_out = req1.sym_out;
3199 req->defobj_out = req1.defobj_out;
3208 symlook_obj1(SymLook *req, const Obj_Entry *obj)
3210 unsigned long symnum;
3211 const Elf_Sym *vsymp;
3215 if (obj->buckets == NULL)
3220 symnum = obj->buckets[req->hash % obj->nbuckets];
3222 for (; symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
3223 const Elf_Sym *symp;
3226 if (symnum >= obj->nchains)
3227 return (ESRCH); /* Bad object */
3229 symp = obj->symtab + symnum;
3230 strp = obj->strtab + symp->st_name;
3232 switch (ELF_ST_TYPE(symp->st_info)) {
3237 if (symp->st_value == 0)
3241 if (symp->st_shndx != SHN_UNDEF)
3244 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
3245 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
3252 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
3255 if (req->ventry == NULL) {
3256 if (obj->versyms != NULL) {
3257 verndx = VER_NDX(obj->versyms[symnum]);
3258 if (verndx > obj->vernum) {
3259 _rtld_error("%s: symbol %s references wrong version %d",
3260 obj->path, obj->strtab + symnum, verndx);
3264 * If we are not called from dlsym (i.e. this is a normal
3265 * relocation from unversioned binary), accept the symbol
3266 * immediately if it happens to have first version after
3267 * this shared object became versioned. Otherwise, if
3268 * symbol is versioned and not hidden, remember it. If it
3269 * is the only symbol with this name exported by the
3270 * shared object, it will be returned as a match at the
3271 * end of the function. If symbol is global (verndx < 2)
3272 * accept it unconditionally.
3274 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
3275 verndx == VER_NDX_GIVEN) {
3276 req->sym_out = symp;
3277 req->defobj_out = obj;
3280 else if (verndx >= VER_NDX_GIVEN) {
3281 if ((obj->versyms[symnum] & VER_NDX_HIDDEN) == 0) {
3289 req->sym_out = symp;
3290 req->defobj_out = obj;
3293 if (obj->versyms == NULL) {
3294 if (object_match_name(obj, req->ventry->name)) {
3295 _rtld_error("%s: object %s should provide version %s for "
3296 "symbol %s", obj_rtld.path, obj->path,
3297 req->ventry->name, obj->strtab + symnum);
3301 verndx = VER_NDX(obj->versyms[symnum]);
3302 if (verndx > obj->vernum) {
3303 _rtld_error("%s: symbol %s references wrong version %d",
3304 obj->path, obj->strtab + symnum, verndx);
3307 if (obj->vertab[verndx].hash != req->ventry->hash ||
3308 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
3310 * Version does not match. Look if this is a global symbol
3311 * and if it is not hidden. If global symbol (verndx < 2)
3312 * is available, use it. Do not return symbol if we are
3313 * called by dlvsym, because dlvsym looks for a specific
3314 * version and default one is not what dlvsym wants.
3316 if ((req->flags & SYMLOOK_DLSYM) ||
3317 (obj->versyms[symnum] & VER_NDX_HIDDEN) ||
3318 (verndx >= VER_NDX_GIVEN))
3322 req->sym_out = symp;
3323 req->defobj_out = obj;
3328 req->sym_out = vsymp;
3329 req->defobj_out = obj;
3336 trace_loaded_objects(Obj_Entry *obj)
3338 char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
3341 if ((main_local = getenv(LD_ "TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
3344 if ((fmt1 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT1")) == NULL)
3345 fmt1 = "\t%o => %p (%x)\n";
3347 if ((fmt2 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT2")) == NULL)
3348 fmt2 = "\t%o (%x)\n";
3350 list_containers = getenv(LD_ "TRACE_LOADED_OBJECTS_ALL");
3352 for (; obj; obj = obj->next) {
3353 Needed_Entry *needed;
3357 if (list_containers && obj->needed != NULL)
3358 rtld_printf("%s:\n", obj->path);
3359 for (needed = obj->needed; needed; needed = needed->next) {
3360 if (needed->obj != NULL) {
3361 if (needed->obj->traced && !list_containers)
3363 needed->obj->traced = true;
3364 path = needed->obj->path;
3368 name = (char *)obj->strtab + needed->name;
3369 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
3371 fmt = is_lib ? fmt1 : fmt2;
3372 while ((c = *fmt++) != '\0') {
3398 rtld_putstr(main_local);
3401 rtld_putstr(obj_main->path);
3408 rtld_printf("%d", sodp->sod_major);
3411 rtld_printf("%d", sodp->sod_minor);
3418 rtld_printf("%p", needed->obj ? needed->obj->mapbase :
3431 * Unload a dlopened object and its dependencies from memory and from
3432 * our data structures. It is assumed that the DAG rooted in the
3433 * object has already been unreferenced, and that the object has a
3434 * reference count of 0.
3437 unload_object(Obj_Entry *root)
3442 assert(root->refcount == 0);
3445 * Pass over the DAG removing unreferenced objects from
3446 * appropriate lists.
3448 unlink_object(root);
3450 /* Unmap all objects that are no longer referenced. */
3451 linkp = &obj_list->next;
3452 while ((obj = *linkp) != NULL) {
3453 if (obj->refcount == 0) {
3454 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
3456 dbg("unloading \"%s\"", obj->path);
3457 unload_filtees(root);
3458 munmap(obj->mapbase, obj->mapsize);
3459 linkmap_delete(obj);
3470 unlink_object(Obj_Entry *root)
3474 if (root->refcount == 0) {
3475 /* Remove the object from the RTLD_GLOBAL list. */
3476 objlist_remove(&list_global, root);
3478 /* Remove the object from all objects' DAG lists. */
3479 STAILQ_FOREACH(elm, &root->dagmembers, link) {
3480 objlist_remove(&elm->obj->dldags, root);
3481 if (elm->obj != root)
3482 unlink_object(elm->obj);
3488 ref_dag(Obj_Entry *root)
3492 assert(root->dag_inited);
3493 STAILQ_FOREACH(elm, &root->dagmembers, link)
3494 elm->obj->refcount++;
3498 unref_dag(Obj_Entry *root)
3502 assert(root->dag_inited);
3503 STAILQ_FOREACH(elm, &root->dagmembers, link)
3504 elm->obj->refcount--;
3508 * Common code for MD __tls_get_addr().
3510 static void *tls_get_addr_slow(Elf_Addr **, int, size_t) __noinline;
3512 tls_get_addr_slow(Elf_Addr **dtvp, int index, size_t offset)
3514 Elf_Addr *newdtv, *dtv;
3515 RtldLockState lockstate;
3519 /* Check dtv generation in case new modules have arrived */
3520 if (dtv[0] != tls_dtv_generation) {
3521 wlock_acquire(rtld_bind_lock, &lockstate);
3522 newdtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
3524 if (to_copy > tls_max_index)
3525 to_copy = tls_max_index;
3526 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
3527 newdtv[0] = tls_dtv_generation;
3528 newdtv[1] = tls_max_index;
3530 lock_release(rtld_bind_lock, &lockstate);
3531 dtv = *dtvp = newdtv;
3534 /* Dynamically allocate module TLS if necessary */
3535 if (dtv[index + 1] == 0) {
3536 /* Signal safe, wlock will block out signals. */
3537 wlock_acquire(rtld_bind_lock, &lockstate);
3538 if (!dtv[index + 1])
3539 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
3540 lock_release(rtld_bind_lock, &lockstate);
3542 return ((void *)(dtv[index + 1] + offset));
3546 tls_get_addr_common(Elf_Addr **dtvp, int index, size_t offset)
3551 /* Check dtv generation in case new modules have arrived */
3552 if (__predict_true(dtv[0] == tls_dtv_generation &&
3553 dtv[index + 1] != 0))
3554 return ((void *)(dtv[index + 1] + offset));
3555 return (tls_get_addr_slow(dtvp, index, offset));
3558 /* XXX not sure what variants to use for arm. */
3560 #if defined(__ia64__) || defined(__powerpc__)
3563 * Allocate Static TLS using the Variant I method.
3566 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
3575 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
3578 assert(tcbsize >= TLS_TCB_SIZE);
3579 tcb = calloc(1, tls_static_space - TLS_TCB_SIZE + tcbsize);
3580 tls = (Elf_Addr **)(tcb + tcbsize - TLS_TCB_SIZE);
3582 if (oldtcb != NULL) {
3583 memcpy(tls, oldtcb, tls_static_space);
3586 /* Adjust the DTV. */
3588 for (i = 0; i < dtv[1]; i++) {
3589 if (dtv[i+2] >= (Elf_Addr)oldtcb &&
3590 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
3591 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tls;
3595 dtv = calloc(tls_max_index + 2, sizeof(Elf_Addr));
3597 dtv[0] = tls_dtv_generation;
3598 dtv[1] = tls_max_index;
3600 for (obj = objs; obj; obj = obj->next) {
3601 if (obj->tlsoffset > 0) {
3602 addr = (Elf_Addr)tls + obj->tlsoffset;
3603 if (obj->tlsinitsize > 0)
3604 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
3605 if (obj->tlssize > obj->tlsinitsize)
3606 memset((void*) (addr + obj->tlsinitsize), 0,
3607 obj->tlssize - obj->tlsinitsize);
3608 dtv[obj->tlsindex + 1] = addr;
3617 free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
3620 Elf_Addr tlsstart, tlsend;
3623 assert(tcbsize >= TLS_TCB_SIZE);
3625 tlsstart = (Elf_Addr)tcb + tcbsize - TLS_TCB_SIZE;
3626 tlsend = tlsstart + tls_static_space;
3628 dtv = *(Elf_Addr **)tlsstart;
3630 for (i = 0; i < dtvsize; i++) {
3631 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
3632 free((void*)dtv[i+2]);
3641 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) || \
3642 defined(__arm__) || defined(__mips__)
3645 * Allocate Static TLS using the Variant II method.
3648 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
3653 Elf_Addr *dtv, *olddtv;
3654 Elf_Addr segbase, oldsegbase, addr;
3657 size = round(tls_static_space, tcbalign);
3659 assert(tcbsize >= 2*sizeof(Elf_Addr));
3660 tls = calloc(1, size + tcbsize);
3661 dtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
3663 segbase = (Elf_Addr)(tls + size);
3664 ((Elf_Addr*)segbase)[0] = segbase;
3665 ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
3667 dtv[0] = tls_dtv_generation;
3668 dtv[1] = tls_max_index;
3672 * Copy the static TLS block over whole.
3674 oldsegbase = (Elf_Addr) oldtls;
3675 memcpy((void *)(segbase - tls_static_space),
3676 (const void *)(oldsegbase - tls_static_space),
3680 * If any dynamic TLS blocks have been created tls_get_addr(),
3683 olddtv = ((Elf_Addr**)oldsegbase)[1];
3684 for (i = 0; i < olddtv[1]; i++) {
3685 if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
3686 dtv[i+2] = olddtv[i+2];
3692 * We assume that this block was the one we created with
3693 * allocate_initial_tls().
3695 free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
3697 for (obj = objs; obj; obj = obj->next) {
3698 if (obj->tlsoffset) {
3699 addr = segbase - obj->tlsoffset;
3700 memset((void*) (addr + obj->tlsinitsize),
3701 0, obj->tlssize - obj->tlsinitsize);
3703 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
3704 dtv[obj->tlsindex + 1] = addr;
3709 return (void*) segbase;
3713 free_tls(void *tls, size_t tcbsize, size_t tcbalign)
3718 Elf_Addr tlsstart, tlsend;
3721 * Figure out the size of the initial TLS block so that we can
3722 * find stuff which ___tls_get_addr() allocated dynamically.
3724 size = round(tls_static_space, tcbalign);
3726 dtv = ((Elf_Addr**)tls)[1];
3728 tlsend = (Elf_Addr) tls;
3729 tlsstart = tlsend - size;
3730 for (i = 0; i < dtvsize; i++) {
3731 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] > tlsend)) {
3732 free((void*) dtv[i+2]);
3736 free((void*) tlsstart);
3743 * Allocate TLS block for module with given index.
3746 allocate_module_tls(int index)
3751 for (obj = obj_list; obj; obj = obj->next) {
3752 if (obj->tlsindex == index)
3756 _rtld_error("Can't find module with TLS index %d", index);
3760 p = malloc(obj->tlssize);
3762 _rtld_error("Cannot allocate TLS block for index %d", index);
3765 memcpy(p, obj->tlsinit, obj->tlsinitsize);
3766 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
3772 allocate_tls_offset(Obj_Entry *obj)
3779 if (obj->tlssize == 0) {
3780 obj->tls_done = true;
3784 if (obj->tlsindex == 1)
3785 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
3787 off = calculate_tls_offset(tls_last_offset, tls_last_size,
3788 obj->tlssize, obj->tlsalign);
3791 * If we have already fixed the size of the static TLS block, we
3792 * must stay within that size. When allocating the static TLS, we
3793 * leave a small amount of space spare to be used for dynamically
3794 * loading modules which use static TLS.
3796 if (tls_static_space) {
3797 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
3801 tls_last_offset = obj->tlsoffset = off;
3802 tls_last_size = obj->tlssize;
3803 obj->tls_done = true;
3809 free_tls_offset(Obj_Entry *obj)
3813 * If we were the last thing to allocate out of the static TLS
3814 * block, we give our space back to the 'allocator'. This is a
3815 * simplistic workaround to allow libGL.so.1 to be loaded and
3816 * unloaded multiple times.
3818 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
3819 == calculate_tls_end(tls_last_offset, tls_last_size)) {
3820 tls_last_offset -= obj->tlssize;
3826 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
3829 RtldLockState lockstate;
3831 wlock_acquire(rtld_bind_lock, &lockstate);
3832 ret = allocate_tls(obj_list, oldtls, tcbsize, tcbalign);
3833 lock_release(rtld_bind_lock, &lockstate);
3838 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
3840 RtldLockState lockstate;
3842 wlock_acquire(rtld_bind_lock, &lockstate);
3843 free_tls(tcb, tcbsize, tcbalign);
3844 lock_release(rtld_bind_lock, &lockstate);
3848 object_add_name(Obj_Entry *obj, const char *name)
3854 entry = malloc(sizeof(Name_Entry) + len);
3856 if (entry != NULL) {
3857 strcpy(entry->name, name);
3858 STAILQ_INSERT_TAIL(&obj->names, entry, link);
3863 object_match_name(const Obj_Entry *obj, const char *name)
3867 STAILQ_FOREACH(entry, &obj->names, link) {
3868 if (strcmp(name, entry->name) == 0)
3875 locate_dependency(const Obj_Entry *obj, const char *name)
3877 const Objlist_Entry *entry;
3878 const Needed_Entry *needed;
3880 STAILQ_FOREACH(entry, &list_main, link) {
3881 if (object_match_name(entry->obj, name))
3885 for (needed = obj->needed; needed != NULL; needed = needed->next) {
3886 if (strcmp(obj->strtab + needed->name, name) == 0 ||
3887 (needed->obj != NULL && object_match_name(needed->obj, name))) {
3889 * If there is DT_NEEDED for the name we are looking for,
3890 * we are all set. Note that object might not be found if
3891 * dependency was not loaded yet, so the function can
3892 * return NULL here. This is expected and handled
3893 * properly by the caller.
3895 return (needed->obj);
3898 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
3904 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
3905 const Elf_Vernaux *vna)
3907 const Elf_Verdef *vd;
3908 const char *vername;
3910 vername = refobj->strtab + vna->vna_name;
3911 vd = depobj->verdef;
3913 _rtld_error("%s: version %s required by %s not defined",
3914 depobj->path, vername, refobj->path);
3918 if (vd->vd_version != VER_DEF_CURRENT) {
3919 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
3920 depobj->path, vd->vd_version);
3923 if (vna->vna_hash == vd->vd_hash) {
3924 const Elf_Verdaux *aux = (const Elf_Verdaux *)
3925 ((char *)vd + vd->vd_aux);
3926 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
3929 if (vd->vd_next == 0)
3931 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3933 if (vna->vna_flags & VER_FLG_WEAK)
3935 _rtld_error("%s: version %s required by %s not found",
3936 depobj->path, vername, refobj->path);
3941 rtld_verify_object_versions(Obj_Entry *obj)
3943 const Elf_Verneed *vn;
3944 const Elf_Verdef *vd;
3945 const Elf_Verdaux *vda;
3946 const Elf_Vernaux *vna;
3947 const Obj_Entry *depobj;
3948 int maxvernum, vernum;
3952 * Walk over defined and required version records and figure out
3953 * max index used by any of them. Do very basic sanity checking
3957 while (vn != NULL) {
3958 if (vn->vn_version != VER_NEED_CURRENT) {
3959 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
3960 obj->path, vn->vn_version);
3963 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
3965 vernum = VER_NEED_IDX(vna->vna_other);
3966 if (vernum > maxvernum)
3968 if (vna->vna_next == 0)
3970 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
3972 if (vn->vn_next == 0)
3974 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
3978 while (vd != NULL) {
3979 if (vd->vd_version != VER_DEF_CURRENT) {
3980 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
3981 obj->path, vd->vd_version);
3984 vernum = VER_DEF_IDX(vd->vd_ndx);
3985 if (vernum > maxvernum)
3987 if (vd->vd_next == 0)
3989 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3996 * Store version information in array indexable by version index.
3997 * Verify that object version requirements are satisfied along the
4000 obj->vernum = maxvernum + 1;
4001 obj->vertab = calloc(obj->vernum, sizeof(Ver_Entry));
4004 while (vd != NULL) {
4005 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
4006 vernum = VER_DEF_IDX(vd->vd_ndx);
4007 assert(vernum <= maxvernum);
4008 vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
4009 obj->vertab[vernum].hash = vd->vd_hash;
4010 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
4011 obj->vertab[vernum].file = NULL;
4012 obj->vertab[vernum].flags = 0;
4014 if (vd->vd_next == 0)
4016 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4020 while (vn != NULL) {
4021 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
4024 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4026 if (check_object_provided_version(obj, depobj, vna))
4028 vernum = VER_NEED_IDX(vna->vna_other);
4029 assert(vernum <= maxvernum);
4030 obj->vertab[vernum].hash = vna->vna_hash;
4031 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
4032 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
4033 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
4034 VER_INFO_HIDDEN : 0;
4035 if (vna->vna_next == 0)
4037 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4039 if (vn->vn_next == 0)
4041 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4047 rtld_verify_versions(const Objlist *objlist)
4049 Objlist_Entry *entry;
4053 STAILQ_FOREACH(entry, objlist, link) {
4055 * Skip dummy objects or objects that have their version requirements
4058 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
4060 if (rtld_verify_object_versions(entry->obj) == -1) {
4062 if (ld_tracing == NULL)
4066 if (rc == 0 || ld_tracing != NULL)
4067 rc = rtld_verify_object_versions(&obj_rtld);
4072 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
4077 vernum = VER_NDX(obj->versyms[symnum]);
4078 if (vernum >= obj->vernum) {
4079 _rtld_error("%s: symbol %s has wrong verneed value %d",
4080 obj->path, obj->strtab + symnum, vernum);
4081 } else if (obj->vertab[vernum].hash != 0) {
4082 return &obj->vertab[vernum];
4089 _rtld_get_stack_prot(void)
4092 return (stack_prot);
4096 map_stacks_exec(RtldLockState *lockstate)
4098 void (*thr_map_stacks_exec)(void);
4100 if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
4102 thr_map_stacks_exec = (void (*)(void))(uintptr_t)
4103 get_program_var_addr("__pthread_map_stacks_exec", lockstate);
4104 if (thr_map_stacks_exec != NULL) {
4105 stack_prot |= PROT_EXEC;
4106 thr_map_stacks_exec();
4111 symlook_init(SymLook *dst, const char *name)
4114 bzero(dst, sizeof(*dst));
4116 dst->hash = elf_hash(name);
4120 symlook_init_from_req(SymLook *dst, const SymLook *src)
4123 dst->name = src->name;
4124 dst->hash = src->hash;
4125 dst->ventry = src->ventry;
4126 dst->flags = src->flags;
4127 dst->defobj_out = NULL;
4128 dst->sym_out = NULL;
4129 dst->lockstate = src->lockstate;
4133 * Overrides for libc_pic-provided functions.
4137 __getosreldate(void)
4147 oid[1] = KERN_OSRELDATE;
4149 len = sizeof(osrel);
4150 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
4151 if (error == 0 && osrel > 0 && len == sizeof(osrel))
4157 * No unresolved symbols for rtld.
4160 __pthread_cxa_finalize(struct dl_phdr_info *a)