2 * Copyright 1996, 1997, 1998, 1999, 2000 John D. Polstra.
3 * Copyright 2003 Alexander Kabaev <kan@FreeBSD.ORG>.
4 * Copyright 2009, 2010, 2011 Konstantin Belousov <kib@FreeBSD.ORG>.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 * Dynamic linker for ELF.
33 * John Polstra <jdp@polstra.com>.
37 #error "GCC is needed to compile this file"
40 #include <sys/param.h>
41 #include <sys/mount.h>
44 #include <sys/sysctl.h>
46 #include <sys/utsname.h>
47 #include <sys/ktrace.h>
63 #include "rtld_printf.h"
66 #define PATH_RTLD "/libexec/ld-elf.so.1"
68 #define PATH_RTLD "/libexec/ld-elf32.so.1"
72 typedef void (*func_ptr_type)();
73 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg);
76 * Function declarations.
78 static const char *basename(const char *);
79 static void die(void) __dead2;
80 static void digest_dynamic1(Obj_Entry *, int, const Elf_Dyn **,
82 static void digest_dynamic2(Obj_Entry *, const Elf_Dyn *, const Elf_Dyn *);
83 static void digest_dynamic(Obj_Entry *, int);
84 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
85 static Obj_Entry *dlcheck(void *);
86 static Obj_Entry *dlopen_object(const char *name, int fd, Obj_Entry *refobj,
87 int lo_flags, int mode);
88 static Obj_Entry *do_load_object(int, const char *, char *, struct stat *, int);
89 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
90 static bool donelist_check(DoneList *, const Obj_Entry *);
91 static void errmsg_restore(char *);
92 static char *errmsg_save(void);
93 static void *fill_search_info(const char *, size_t, void *);
94 static char *find_library(const char *, const Obj_Entry *);
95 static const char *gethints(void);
96 static void init_dag(Obj_Entry *);
97 static void init_rtld(caddr_t, Elf_Auxinfo **);
98 static void initlist_add_neededs(Needed_Entry *, Objlist *);
99 static void initlist_add_objects(Obj_Entry *, Obj_Entry **, Objlist *);
100 static void linkmap_add(Obj_Entry *);
101 static void linkmap_delete(Obj_Entry *);
102 static void load_filtees(Obj_Entry *, int flags, RtldLockState *);
103 static void unload_filtees(Obj_Entry *);
104 static int load_needed_objects(Obj_Entry *, int);
105 static int load_preload_objects(void);
106 static Obj_Entry *load_object(const char *, int fd, const Obj_Entry *, int);
107 static void map_stacks_exec(RtldLockState *);
108 static Obj_Entry *obj_from_addr(const void *);
109 static void objlist_call_fini(Objlist *, Obj_Entry *, RtldLockState *);
110 static void objlist_call_init(Objlist *, RtldLockState *);
111 static void objlist_clear(Objlist *);
112 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
113 static void objlist_init(Objlist *);
114 static void objlist_push_head(Objlist *, Obj_Entry *);
115 static void objlist_push_tail(Objlist *, Obj_Entry *);
116 static void objlist_remove(Objlist *, Obj_Entry *);
117 static void *path_enumerate(const char *, path_enum_proc, void *);
118 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, RtldLockState *);
119 static int resolve_objects_ifunc(Obj_Entry *first, bool bind_now,
120 RtldLockState *lockstate);
121 static int rtld_dirname(const char *, char *);
122 static int rtld_dirname_abs(const char *, char *);
123 static void *rtld_dlopen(const char *name, int fd, int mode);
124 static void rtld_exit(void);
125 static char *search_library_path(const char *, const char *);
126 static const void **get_program_var_addr(const char *, RtldLockState *);
127 static void set_program_var(const char *, const void *);
128 static int symlook_default(SymLook *, const Obj_Entry *refobj);
129 static int symlook_global(SymLook *, DoneList *);
130 static void symlook_init_from_req(SymLook *, const SymLook *);
131 static int symlook_list(SymLook *, const Objlist *, DoneList *);
132 static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *);
133 static int symlook_obj1(SymLook *, const Obj_Entry *);
134 static void trace_loaded_objects(Obj_Entry *);
135 static void unlink_object(Obj_Entry *);
136 static void unload_object(Obj_Entry *);
137 static void unref_dag(Obj_Entry *);
138 static void ref_dag(Obj_Entry *);
139 static int origin_subst_one(char **, const char *, const char *,
140 const char *, char *);
141 static char *origin_subst(const char *, const char *);
142 static int rtld_verify_versions(const Objlist *);
143 static int rtld_verify_object_versions(Obj_Entry *);
144 static void object_add_name(Obj_Entry *, const char *);
145 static int object_match_name(const Obj_Entry *, const char *);
146 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
147 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
148 struct dl_phdr_info *phdr_info);
150 void r_debug_state(struct r_debug *, struct link_map *) __noinline;
155 static char *error_message; /* Message for dlerror(), or NULL */
156 struct r_debug r_debug; /* for GDB; */
157 static bool libmap_disable; /* Disable libmap */
158 static bool ld_loadfltr; /* Immediate filters processing */
159 static char *libmap_override; /* Maps to use in addition to libmap.conf */
160 static bool trust; /* False for setuid and setgid programs */
161 static bool dangerous_ld_env; /* True if environment variables have been
162 used to affect the libraries loaded */
163 static char *ld_bind_now; /* Environment variable for immediate binding */
164 static char *ld_debug; /* Environment variable for debugging */
165 static char *ld_library_path; /* Environment variable for search path */
166 static char *ld_preload; /* Environment variable for libraries to
168 static char *ld_elf_hints_path; /* Environment variable for alternative hints path */
169 static char *ld_tracing; /* Called from ldd to print libs */
170 static char *ld_utrace; /* Use utrace() to log events. */
171 static Obj_Entry *obj_list; /* Head of linked list of shared objects */
172 static Obj_Entry **obj_tail; /* Link field of last object in list */
173 static Obj_Entry *obj_main; /* The main program shared object */
174 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
175 static unsigned int obj_count; /* Number of objects in obj_list */
176 static unsigned int obj_loads; /* Number of objects in obj_list */
178 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
179 STAILQ_HEAD_INITIALIZER(list_global);
180 static Objlist list_main = /* Objects loaded at program startup */
181 STAILQ_HEAD_INITIALIZER(list_main);
182 static Objlist list_fini = /* Objects needing fini() calls */
183 STAILQ_HEAD_INITIALIZER(list_fini);
185 Elf_Sym sym_zero; /* For resolving undefined weak refs. */
187 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
189 extern Elf_Dyn _DYNAMIC;
190 #pragma weak _DYNAMIC
191 #ifndef RTLD_IS_DYNAMIC
192 #define RTLD_IS_DYNAMIC() (&_DYNAMIC != NULL)
195 int osreldate, pagesize;
197 static int stack_prot = PROT_READ | PROT_WRITE | RTLD_DEFAULT_STACK_EXEC;
198 static int max_stack_flags;
201 * Global declarations normally provided by crt1. The dynamic linker is
202 * not built with crt1, so we have to provide them ourselves.
208 * Globals to control TLS allocation.
210 size_t tls_last_offset; /* Static TLS offset of last module */
211 size_t tls_last_size; /* Static TLS size of last module */
212 size_t tls_static_space; /* Static TLS space allocated */
213 int tls_dtv_generation = 1; /* Used to detect when dtv size changes */
214 int tls_max_index = 1; /* Largest module index allocated */
217 * Fill in a DoneList with an allocation large enough to hold all of
218 * the currently-loaded objects. Keep this as a macro since it calls
219 * alloca and we want that to occur within the scope of the caller.
221 #define donelist_init(dlp) \
222 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
223 assert((dlp)->objs != NULL), \
224 (dlp)->num_alloc = obj_count, \
227 #define UTRACE_DLOPEN_START 1
228 #define UTRACE_DLOPEN_STOP 2
229 #define UTRACE_DLCLOSE_START 3
230 #define UTRACE_DLCLOSE_STOP 4
231 #define UTRACE_LOAD_OBJECT 5
232 #define UTRACE_UNLOAD_OBJECT 6
233 #define UTRACE_ADD_RUNDEP 7
234 #define UTRACE_PRELOAD_FINISHED 8
235 #define UTRACE_INIT_CALL 9
236 #define UTRACE_FINI_CALL 10
239 char sig[4]; /* 'RTLD' */
242 void *mapbase; /* Used for 'parent' and 'init/fini' */
244 int refcnt; /* Used for 'mode' */
245 char name[MAXPATHLEN];
248 #define LD_UTRACE(e, h, mb, ms, r, n) do { \
249 if (ld_utrace != NULL) \
250 ld_utrace_log(e, h, mb, ms, r, n); \
254 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
255 int refcnt, const char *name)
257 struct utrace_rtld ut;
265 ut.mapbase = mapbase;
266 ut.mapsize = mapsize;
268 bzero(ut.name, sizeof(ut.name));
270 strlcpy(ut.name, name, sizeof(ut.name));
271 utrace(&ut, sizeof(ut));
275 * Main entry point for dynamic linking. The first argument is the
276 * stack pointer. The stack is expected to be laid out as described
277 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
278 * Specifically, the stack pointer points to a word containing
279 * ARGC. Following that in the stack is a null-terminated sequence
280 * of pointers to argument strings. Then comes a null-terminated
281 * sequence of pointers to environment strings. Finally, there is a
282 * sequence of "auxiliary vector" entries.
284 * The second argument points to a place to store the dynamic linker's
285 * exit procedure pointer and the third to a place to store the main
288 * The return value is the main program's entry point.
291 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
293 Elf_Auxinfo *aux_info[AT_COUNT];
301 Objlist_Entry *entry;
303 Obj_Entry **preload_tail;
305 RtldLockState lockstate;
308 * On entry, the dynamic linker itself has not been relocated yet.
309 * Be very careful not to reference any global data until after
310 * init_rtld has returned. It is OK to reference file-scope statics
311 * and string constants, and to call static and global functions.
314 /* Find the auxiliary vector on the stack. */
317 sp += argc + 1; /* Skip over arguments and NULL terminator */
319 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
321 aux = (Elf_Auxinfo *) sp;
323 /* Digest the auxiliary vector. */
324 for (i = 0; i < AT_COUNT; i++)
326 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
327 if (auxp->a_type < AT_COUNT)
328 aux_info[auxp->a_type] = auxp;
331 /* Initialize and relocate ourselves. */
332 assert(aux_info[AT_BASE] != NULL);
333 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
335 __progname = obj_rtld.path;
336 argv0 = argv[0] != NULL ? argv[0] : "(null)";
339 trust = !issetugid();
341 ld_bind_now = getenv(LD_ "BIND_NOW");
343 * If the process is tainted, then we un-set the dangerous environment
344 * variables. The process will be marked as tainted until setuid(2)
345 * is called. If any child process calls setuid(2) we do not want any
346 * future processes to honor the potentially un-safe variables.
349 if (unsetenv(LD_ "PRELOAD") || unsetenv(LD_ "LIBMAP") ||
350 unsetenv(LD_ "LIBRARY_PATH") || unsetenv(LD_ "LIBMAP_DISABLE") ||
351 unsetenv(LD_ "DEBUG") || unsetenv(LD_ "ELF_HINTS_PATH") ||
352 unsetenv(LD_ "LOADFLTR")) {
353 _rtld_error("environment corrupt; aborting");
357 ld_debug = getenv(LD_ "DEBUG");
358 libmap_disable = getenv(LD_ "LIBMAP_DISABLE") != NULL;
359 libmap_override = getenv(LD_ "LIBMAP");
360 ld_library_path = getenv(LD_ "LIBRARY_PATH");
361 ld_preload = getenv(LD_ "PRELOAD");
362 ld_elf_hints_path = getenv(LD_ "ELF_HINTS_PATH");
363 ld_loadfltr = getenv(LD_ "LOADFLTR") != NULL;
364 dangerous_ld_env = libmap_disable || (libmap_override != NULL) ||
365 (ld_library_path != NULL) || (ld_preload != NULL) ||
366 (ld_elf_hints_path != NULL) || ld_loadfltr;
367 ld_tracing = getenv(LD_ "TRACE_LOADED_OBJECTS");
368 ld_utrace = getenv(LD_ "UTRACE");
370 if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0)
371 ld_elf_hints_path = _PATH_ELF_HINTS;
373 if (ld_debug != NULL && *ld_debug != '\0')
375 dbg("%s is initialized, base address = %p", __progname,
376 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
377 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
378 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
380 dbg("initializing thread locks");
384 * Load the main program, or process its program header if it is
387 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
388 int fd = aux_info[AT_EXECFD]->a_un.a_val;
389 dbg("loading main program");
390 obj_main = map_object(fd, argv0, NULL);
392 if (obj_main == NULL)
394 max_stack_flags = obj->stack_flags;
395 } else { /* Main program already loaded. */
396 const Elf_Phdr *phdr;
400 dbg("processing main program's program header");
401 assert(aux_info[AT_PHDR] != NULL);
402 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
403 assert(aux_info[AT_PHNUM] != NULL);
404 phnum = aux_info[AT_PHNUM]->a_un.a_val;
405 assert(aux_info[AT_PHENT] != NULL);
406 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
407 assert(aux_info[AT_ENTRY] != NULL);
408 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
409 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
413 if (aux_info[AT_EXECPATH] != 0) {
415 char buf[MAXPATHLEN];
417 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
418 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
419 if (kexecpath[0] == '/')
420 obj_main->path = kexecpath;
421 else if (getcwd(buf, sizeof(buf)) == NULL ||
422 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
423 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
424 obj_main->path = xstrdup(argv0);
426 obj_main->path = xstrdup(buf);
428 dbg("No AT_EXECPATH");
429 obj_main->path = xstrdup(argv0);
431 dbg("obj_main path %s", obj_main->path);
432 obj_main->mainprog = true;
434 if (aux_info[AT_STACKPROT] != NULL &&
435 aux_info[AT_STACKPROT]->a_un.a_val != 0)
436 stack_prot = aux_info[AT_STACKPROT]->a_un.a_val;
439 * Get the actual dynamic linker pathname from the executable if
440 * possible. (It should always be possible.) That ensures that
441 * gdb will find the right dynamic linker even if a non-standard
444 if (obj_main->interp != NULL &&
445 strcmp(obj_main->interp, obj_rtld.path) != 0) {
447 obj_rtld.path = xstrdup(obj_main->interp);
448 __progname = obj_rtld.path;
451 digest_dynamic(obj_main, 0);
453 linkmap_add(obj_main);
454 linkmap_add(&obj_rtld);
456 /* Link the main program into the list of objects. */
457 *obj_tail = obj_main;
458 obj_tail = &obj_main->next;
461 /* Make sure we don't call the main program's init and fini functions. */
462 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
464 /* Initialize a fake symbol for resolving undefined weak references. */
465 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
466 sym_zero.st_shndx = SHN_UNDEF;
467 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
470 libmap_disable = (bool)lm_init(libmap_override);
472 dbg("loading LD_PRELOAD libraries");
473 if (load_preload_objects() == -1)
475 preload_tail = obj_tail;
477 dbg("loading needed objects");
478 if (load_needed_objects(obj_main, 0) == -1)
481 /* Make a list of all objects loaded at startup. */
482 for (obj = obj_list; obj != NULL; obj = obj->next) {
483 objlist_push_tail(&list_main, obj);
487 dbg("checking for required versions");
488 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
491 if (ld_tracing) { /* We're done */
492 trace_loaded_objects(obj_main);
496 if (getenv(LD_ "DUMP_REL_PRE") != NULL) {
497 dump_relocations(obj_main);
502 * Processing tls relocations requires having the tls offsets
503 * initialized. Prepare offsets before starting initial
504 * relocation processing.
506 dbg("initializing initial thread local storage offsets");
507 STAILQ_FOREACH(entry, &list_main, link) {
509 * Allocate all the initial objects out of the static TLS
510 * block even if they didn't ask for it.
512 allocate_tls_offset(entry->obj);
515 if (relocate_objects(obj_main,
516 ld_bind_now != NULL && *ld_bind_now != '\0', &obj_rtld, NULL) == -1)
519 dbg("doing copy relocations");
520 if (do_copy_relocations(obj_main) == -1)
523 if (getenv(LD_ "DUMP_REL_POST") != NULL) {
524 dump_relocations(obj_main);
529 * Setup TLS for main thread. This must be done after the
530 * relocations are processed, since tls initialization section
531 * might be the subject for relocations.
533 dbg("initializing initial thread local storage");
534 allocate_initial_tls(obj_list);
536 dbg("initializing key program variables");
537 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
538 set_program_var("environ", env);
539 set_program_var("__elf_aux_vector", aux);
541 /* Make a list of init functions to call. */
542 objlist_init(&initlist);
543 initlist_add_objects(obj_list, preload_tail, &initlist);
545 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
547 map_stacks_exec(NULL);
549 dbg("resolving ifuncs");
550 if (resolve_objects_ifunc(obj_main,
551 ld_bind_now != NULL && *ld_bind_now != '\0', NULL) == -1)
554 wlock_acquire(rtld_bind_lock, &lockstate);
555 objlist_call_init(&initlist, &lockstate);
556 objlist_clear(&initlist);
557 dbg("loading filtees");
558 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
559 if (ld_loadfltr || obj->z_loadfltr)
560 load_filtees(obj, 0, &lockstate);
562 lock_release(rtld_bind_lock, &lockstate);
564 dbg("transferring control to program entry point = %p", obj_main->entry);
566 /* Return the exit procedure and the program entry point. */
567 *exit_proc = rtld_exit;
569 return (func_ptr_type) obj_main->entry;
573 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def)
578 ptr = (void *)make_function_pointer(def, obj);
579 target = ((Elf_Addr (*)(void))ptr)();
580 return ((void *)target);
584 _rtld_bind(Obj_Entry *obj, Elf_Size reloff)
588 const Obj_Entry *defobj;
591 RtldLockState lockstate;
593 rlock_acquire(rtld_bind_lock, &lockstate);
594 if (sigsetjmp(lockstate.env, 0) != 0)
595 lock_upgrade(rtld_bind_lock, &lockstate);
597 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
599 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
601 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
602 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL,
606 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
607 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
609 target = (Elf_Addr)(defobj->relocbase + def->st_value);
611 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
612 defobj->strtab + def->st_name, basename(obj->path),
613 (void *)target, basename(defobj->path));
616 * Write the new contents for the jmpslot. Note that depending on
617 * architecture, the value which we need to return back to the
618 * lazy binding trampoline may or may not be the target
619 * address. The value returned from reloc_jmpslot() is the value
620 * that the trampoline needs.
622 target = reloc_jmpslot(where, target, defobj, obj, rel);
623 lock_release(rtld_bind_lock, &lockstate);
628 * Error reporting function. Use it like printf. If formats the message
629 * into a buffer, and sets things up so that the next call to dlerror()
630 * will return the message.
633 _rtld_error(const char *fmt, ...)
635 static char buf[512];
639 rtld_vsnprintf(buf, sizeof buf, fmt, ap);
645 * Return a dynamically-allocated copy of the current error message, if any.
650 return error_message == NULL ? NULL : xstrdup(error_message);
654 * Restore the current error message from a copy which was previously saved
655 * by errmsg_save(). The copy is freed.
658 errmsg_restore(char *saved_msg)
660 if (saved_msg == NULL)
661 error_message = NULL;
663 _rtld_error("%s", saved_msg);
669 basename(const char *name)
671 const char *p = strrchr(name, '/');
672 return p != NULL ? p + 1 : name;
675 static struct utsname uts;
678 origin_subst_one(char **res, const char *real, const char *kw, const char *subst,
688 subst_len = kw_len = 0;
692 if (subst_len == 0) {
693 subst_len = strlen(subst);
697 *res = xmalloc(PATH_MAX);
700 if ((res1 - *res) + subst_len + (p1 - p) >= PATH_MAX) {
701 _rtld_error("Substitution of %s in %s cannot be performed",
703 if (may_free != NULL)
708 memcpy(res1, p, p1 - p);
710 memcpy(res1, subst, subst_len);
715 if (may_free != NULL)
718 *res = xstrdup(real);
722 if (may_free != NULL)
724 if (strlcat(res1, p, PATH_MAX - (res1 - *res)) >= PATH_MAX) {
734 origin_subst(const char *real, const char *origin_path)
736 char *res1, *res2, *res3, *res4;
738 if (uts.sysname[0] == '\0') {
739 if (uname(&uts) != 0) {
740 _rtld_error("utsname failed: %d", errno);
744 if (!origin_subst_one(&res1, real, "$ORIGIN", origin_path, NULL) ||
745 !origin_subst_one(&res2, res1, "$OSNAME", uts.sysname, res1) ||
746 !origin_subst_one(&res3, res2, "$OSREL", uts.release, res2) ||
747 !origin_subst_one(&res4, res3, "$PLATFORM", uts.machine, res3))
755 const char *msg = dlerror();
759 rtld_fdputstr(STDERR_FILENO, msg);
764 * Process a shared object's DYNAMIC section, and save the important
765 * information in its Obj_Entry structure.
768 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
769 const Elf_Dyn **dyn_soname)
772 Needed_Entry **needed_tail = &obj->needed;
773 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
774 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
775 int plttype = DT_REL;
780 obj->bind_now = false;
781 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
782 switch (dynp->d_tag) {
785 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
789 obj->relsize = dynp->d_un.d_val;
793 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
797 obj->pltrel = (const Elf_Rel *)
798 (obj->relocbase + dynp->d_un.d_ptr);
802 obj->pltrelsize = dynp->d_un.d_val;
806 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
810 obj->relasize = dynp->d_un.d_val;
814 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
818 plttype = dynp->d_un.d_val;
819 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
823 obj->symtab = (const Elf_Sym *)
824 (obj->relocbase + dynp->d_un.d_ptr);
828 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
832 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
836 obj->strsize = dynp->d_un.d_val;
840 obj->verneed = (const Elf_Verneed *) (obj->relocbase +
845 obj->verneednum = dynp->d_un.d_val;
849 obj->verdef = (const Elf_Verdef *) (obj->relocbase +
854 obj->verdefnum = dynp->d_un.d_val;
858 obj->versyms = (const Elf_Versym *)(obj->relocbase +
864 const Elf_Hashelt *hashtab = (const Elf_Hashelt *)
865 (obj->relocbase + dynp->d_un.d_ptr);
866 obj->nbuckets = hashtab[0];
867 obj->nchains = hashtab[1];
868 obj->buckets = hashtab + 2;
869 obj->chains = obj->buckets + obj->nbuckets;
875 Needed_Entry *nep = NEW(Needed_Entry);
876 nep->name = dynp->d_un.d_val;
881 needed_tail = &nep->next;
887 Needed_Entry *nep = NEW(Needed_Entry);
888 nep->name = dynp->d_un.d_val;
892 *needed_filtees_tail = nep;
893 needed_filtees_tail = &nep->next;
899 Needed_Entry *nep = NEW(Needed_Entry);
900 nep->name = dynp->d_un.d_val;
904 *needed_aux_filtees_tail = nep;
905 needed_aux_filtees_tail = &nep->next;
910 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
918 obj->symbolic = true;
922 case DT_RUNPATH: /* XXX: process separately */
924 * We have to wait until later to process this, because we
925 * might not have gotten the address of the string table yet.
935 obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
939 obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
943 * Don't process DT_DEBUG on MIPS as the dynamic section
944 * is mapped read-only. DT_MIPS_RLD_MAP is used instead.
949 /* XXX - not implemented yet */
951 dbg("Filling in DT_DEBUG entry");
952 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
957 if ((dynp->d_un.d_val & DF_ORIGIN) && trust)
958 obj->z_origin = true;
959 if (dynp->d_un.d_val & DF_SYMBOLIC)
960 obj->symbolic = true;
961 if (dynp->d_un.d_val & DF_TEXTREL)
963 if (dynp->d_un.d_val & DF_BIND_NOW)
964 obj->bind_now = true;
965 /*if (dynp->d_un.d_val & DF_STATIC_TLS)
969 case DT_MIPS_LOCAL_GOTNO:
970 obj->local_gotno = dynp->d_un.d_val;
973 case DT_MIPS_SYMTABNO:
974 obj->symtabno = dynp->d_un.d_val;
978 obj->gotsym = dynp->d_un.d_val;
981 case DT_MIPS_RLD_MAP:
984 dbg("Filling in DT_DEBUG entry");
985 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
991 if (dynp->d_un.d_val & DF_1_NOOPEN)
992 obj->z_noopen = true;
993 if ((dynp->d_un.d_val & DF_1_ORIGIN) && trust)
994 obj->z_origin = true;
995 /*if (dynp->d_un.d_val & DF_1_GLOBAL)
997 if (dynp->d_un.d_val & DF_1_BIND_NOW)
998 obj->bind_now = true;
999 if (dynp->d_un.d_val & DF_1_NODELETE)
1000 obj->z_nodelete = true;
1001 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1002 obj->z_loadfltr = true;
1007 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1014 obj->traced = false;
1016 if (plttype == DT_RELA) {
1017 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1019 obj->pltrelasize = obj->pltrelsize;
1020 obj->pltrelsize = 0;
1025 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1026 const Elf_Dyn *dyn_soname)
1029 if (obj->z_origin && obj->origin_path == NULL) {
1030 obj->origin_path = xmalloc(PATH_MAX);
1031 if (rtld_dirname_abs(obj->path, obj->origin_path) == -1)
1035 if (dyn_rpath != NULL) {
1036 obj->rpath = (char *)obj->strtab + dyn_rpath->d_un.d_val;
1038 obj->rpath = origin_subst(obj->rpath, obj->origin_path);
1041 if (dyn_soname != NULL)
1042 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1046 digest_dynamic(Obj_Entry *obj, int early)
1048 const Elf_Dyn *dyn_rpath;
1049 const Elf_Dyn *dyn_soname;
1051 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname);
1052 digest_dynamic2(obj, dyn_rpath, dyn_soname);
1056 * Process a shared object's program header. This is used only for the
1057 * main program, when the kernel has already loaded the main program
1058 * into memory before calling the dynamic linker. It creates and
1059 * returns an Obj_Entry structure.
1062 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1065 const Elf_Phdr *phlimit = phdr + phnum;
1070 for (ph = phdr; ph < phlimit; ph++) {
1071 if (ph->p_type != PT_PHDR)
1075 obj->phsize = ph->p_memsz;
1076 obj->relocbase = (caddr_t)phdr - ph->p_vaddr;
1080 obj->stack_flags = PF_X | PF_R | PF_W;
1082 for (ph = phdr; ph < phlimit; ph++) {
1083 switch (ph->p_type) {
1086 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1090 if (nsegs == 0) { /* First load segment */
1091 obj->vaddrbase = trunc_page(ph->p_vaddr);
1092 obj->mapbase = obj->vaddrbase + obj->relocbase;
1093 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
1095 } else { /* Last load segment */
1096 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1103 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1108 obj->tlssize = ph->p_memsz;
1109 obj->tlsalign = ph->p_align;
1110 obj->tlsinitsize = ph->p_filesz;
1111 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1115 obj->stack_flags = ph->p_flags;
1120 _rtld_error("%s: too few PT_LOAD segments", path);
1129 dlcheck(void *handle)
1133 for (obj = obj_list; obj != NULL; obj = obj->next)
1134 if (obj == (Obj_Entry *) handle)
1137 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1138 _rtld_error("Invalid shared object handle %p", handle);
1145 * If the given object is already in the donelist, return true. Otherwise
1146 * add the object to the list and return false.
1149 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1153 for (i = 0; i < dlp->num_used; i++)
1154 if (dlp->objs[i] == obj)
1157 * Our donelist allocation should always be sufficient. But if
1158 * our threads locking isn't working properly, more shared objects
1159 * could have been loaded since we allocated the list. That should
1160 * never happen, but we'll handle it properly just in case it does.
1162 if (dlp->num_used < dlp->num_alloc)
1163 dlp->objs[dlp->num_used++] = obj;
1168 * Hash function for symbol table lookup. Don't even think about changing
1169 * this. It is specified by the System V ABI.
1172 elf_hash(const char *name)
1174 const unsigned char *p = (const unsigned char *) name;
1175 unsigned long h = 0;
1178 while (*p != '\0') {
1179 h = (h << 4) + *p++;
1180 if ((g = h & 0xf0000000) != 0)
1188 * Find the library with the given name, and return its full pathname.
1189 * The returned string is dynamically allocated. Generates an error
1190 * message and returns NULL if the library cannot be found.
1192 * If the second argument is non-NULL, then it refers to an already-
1193 * loaded shared object, whose library search path will be searched.
1195 * The search order is:
1197 * rpath in the referencing file
1202 find_library(const char *xname, const Obj_Entry *refobj)
1207 if (strchr(xname, '/') != NULL) { /* Hard coded pathname */
1208 if (xname[0] != '/' && !trust) {
1209 _rtld_error("Absolute pathname required for shared object \"%s\"",
1213 if (refobj != NULL && refobj->z_origin)
1214 return origin_subst(xname, refobj->origin_path);
1216 return xstrdup(xname);
1219 if (libmap_disable || (refobj == NULL) ||
1220 (name = lm_find(refobj->path, xname)) == NULL)
1221 name = (char *)xname;
1223 dbg(" Searching for \"%s\"", name);
1225 if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
1227 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
1228 (pathname = search_library_path(name, gethints())) != NULL ||
1229 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
1232 if(refobj != NULL && refobj->path != NULL) {
1233 _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
1234 name, basename(refobj->path));
1236 _rtld_error("Shared object \"%s\" not found", name);
1242 * Given a symbol number in a referencing object, find the corresponding
1243 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1244 * no definition was found. Returns a pointer to the Obj_Entry of the
1245 * defining object via the reference parameter DEFOBJ_OUT.
1248 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1249 const Obj_Entry **defobj_out, int flags, SymCache *cache,
1250 RtldLockState *lockstate)
1254 const Obj_Entry *defobj;
1260 * If we have already found this symbol, get the information from
1263 if (symnum >= refobj->nchains)
1264 return NULL; /* Bad object */
1265 if (cache != NULL && cache[symnum].sym != NULL) {
1266 *defobj_out = cache[symnum].obj;
1267 return cache[symnum].sym;
1270 ref = refobj->symtab + symnum;
1271 name = refobj->strtab + ref->st_name;
1276 * We don't have to do a full scale lookup if the symbol is local.
1277 * We know it will bind to the instance in this load module; to
1278 * which we already have a pointer (ie ref). By not doing a lookup,
1279 * we not only improve performance, but it also avoids unresolvable
1280 * symbols when local symbols are not in the hash table. This has
1281 * been seen with the ia64 toolchain.
1283 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1284 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1285 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1288 symlook_init(&req, name);
1290 req.ventry = fetch_ventry(refobj, symnum);
1291 req.lockstate = lockstate;
1292 res = symlook_default(&req, refobj);
1295 defobj = req.defobj_out;
1303 * If we found no definition and the reference is weak, treat the
1304 * symbol as having the value zero.
1306 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1312 *defobj_out = defobj;
1313 /* Record the information in the cache to avoid subsequent lookups. */
1314 if (cache != NULL) {
1315 cache[symnum].sym = def;
1316 cache[symnum].obj = defobj;
1319 if (refobj != &obj_rtld)
1320 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1326 * Return the search path from the ldconfig hints file, reading it if
1327 * necessary. Returns NULL if there are problems with the hints file,
1328 * or if the search path there is empty.
1335 if (hints == NULL) {
1337 struct elfhints_hdr hdr;
1340 /* Keep from trying again in case the hints file is bad. */
1343 if ((fd = open(ld_elf_hints_path, O_RDONLY)) == -1)
1345 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1346 hdr.magic != ELFHINTS_MAGIC ||
1351 p = xmalloc(hdr.dirlistlen + 1);
1352 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1353 read(fd, p, hdr.dirlistlen + 1) != (ssize_t)hdr.dirlistlen + 1) {
1361 return hints[0] != '\0' ? hints : NULL;
1365 init_dag(Obj_Entry *root)
1367 const Needed_Entry *needed;
1368 const Objlist_Entry *elm;
1371 if (root->dag_inited)
1373 donelist_init(&donelist);
1375 /* Root object belongs to own DAG. */
1376 objlist_push_tail(&root->dldags, root);
1377 objlist_push_tail(&root->dagmembers, root);
1378 donelist_check(&donelist, root);
1381 * Add dependencies of root object to DAG in breadth order
1382 * by exploiting the fact that each new object get added
1383 * to the tail of the dagmembers list.
1385 STAILQ_FOREACH(elm, &root->dagmembers, link) {
1386 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
1387 if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
1389 objlist_push_tail(&needed->obj->dldags, root);
1390 objlist_push_tail(&root->dagmembers, needed->obj);
1393 root->dag_inited = true;
1397 * Initialize the dynamic linker. The argument is the address at which
1398 * the dynamic linker has been mapped into memory. The primary task of
1399 * this function is to relocate the dynamic linker.
1402 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
1404 Obj_Entry objtmp; /* Temporary rtld object */
1405 const Elf_Dyn *dyn_rpath;
1406 const Elf_Dyn *dyn_soname;
1409 * Conjure up an Obj_Entry structure for the dynamic linker.
1411 * The "path" member can't be initialized yet because string constants
1412 * cannot yet be accessed. Below we will set it correctly.
1414 memset(&objtmp, 0, sizeof(objtmp));
1417 objtmp.mapbase = mapbase;
1419 objtmp.relocbase = mapbase;
1421 if (RTLD_IS_DYNAMIC()) {
1422 objtmp.dynamic = rtld_dynamic(&objtmp);
1423 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname);
1424 assert(objtmp.needed == NULL);
1425 #if !defined(__mips__)
1426 /* MIPS has a bogus DT_TEXTREL. */
1427 assert(!objtmp.textrel);
1431 * Temporarily put the dynamic linker entry into the object list, so
1432 * that symbols can be found.
1435 relocate_objects(&objtmp, true, &objtmp, NULL);
1438 /* Initialize the object list. */
1439 obj_tail = &obj_list;
1441 /* Now that non-local variables can be accesses, copy out obj_rtld. */
1442 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1444 if (aux_info[AT_PAGESZ] != NULL)
1445 pagesize = aux_info[AT_PAGESZ]->a_un.a_val;
1446 if (aux_info[AT_OSRELDATE] != NULL)
1447 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
1449 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname);
1451 /* Replace the path with a dynamically allocated copy. */
1452 obj_rtld.path = xstrdup(PATH_RTLD);
1454 r_debug.r_brk = r_debug_state;
1455 r_debug.r_state = RT_CONSISTENT;
1459 * Add the init functions from a needed object list (and its recursive
1460 * needed objects) to "list". This is not used directly; it is a helper
1461 * function for initlist_add_objects(). The write lock must be held
1462 * when this function is called.
1465 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1467 /* Recursively process the successor needed objects. */
1468 if (needed->next != NULL)
1469 initlist_add_neededs(needed->next, list);
1471 /* Process the current needed object. */
1472 if (needed->obj != NULL)
1473 initlist_add_objects(needed->obj, &needed->obj->next, list);
1477 * Scan all of the DAGs rooted in the range of objects from "obj" to
1478 * "tail" and add their init functions to "list". This recurses over
1479 * the DAGs and ensure the proper init ordering such that each object's
1480 * needed libraries are initialized before the object itself. At the
1481 * same time, this function adds the objects to the global finalization
1482 * list "list_fini" in the opposite order. The write lock must be
1483 * held when this function is called.
1486 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1488 if (obj->init_scanned || obj->init_done)
1490 obj->init_scanned = true;
1492 /* Recursively process the successor objects. */
1493 if (&obj->next != tail)
1494 initlist_add_objects(obj->next, tail, list);
1496 /* Recursively process the needed objects. */
1497 if (obj->needed != NULL)
1498 initlist_add_neededs(obj->needed, list);
1500 /* Add the object to the init list. */
1501 if (obj->init != (Elf_Addr)NULL)
1502 objlist_push_tail(list, obj);
1504 /* Add the object to the global fini list in the reverse order. */
1505 if (obj->fini != (Elf_Addr)NULL && !obj->on_fini_list) {
1506 objlist_push_head(&list_fini, obj);
1507 obj->on_fini_list = true;
1512 #define FPTR_TARGET(f) ((Elf_Addr) (f))
1516 free_needed_filtees(Needed_Entry *n)
1518 Needed_Entry *needed, *needed1;
1520 for (needed = n; needed != NULL; needed = needed->next) {
1521 if (needed->obj != NULL) {
1522 dlclose(needed->obj);
1526 for (needed = n; needed != NULL; needed = needed1) {
1527 needed1 = needed->next;
1533 unload_filtees(Obj_Entry *obj)
1536 free_needed_filtees(obj->needed_filtees);
1537 obj->needed_filtees = NULL;
1538 free_needed_filtees(obj->needed_aux_filtees);
1539 obj->needed_aux_filtees = NULL;
1540 obj->filtees_loaded = false;
1544 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags)
1547 for (; needed != NULL; needed = needed->next) {
1548 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
1549 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
1555 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
1558 lock_restart_for_upgrade(lockstate);
1559 if (!obj->filtees_loaded) {
1560 load_filtee1(obj, obj->needed_filtees, flags);
1561 load_filtee1(obj, obj->needed_aux_filtees, flags);
1562 obj->filtees_loaded = true;
1567 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
1571 for (; needed != NULL; needed = needed->next) {
1572 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
1573 flags & ~RTLD_LO_NOLOAD);
1574 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
1576 if (obj1 != NULL && obj1->z_nodelete && !obj1->ref_nodel) {
1577 dbg("obj %s nodelete", obj1->path);
1580 obj1->ref_nodel = true;
1587 * Given a shared object, traverse its list of needed objects, and load
1588 * each of them. Returns 0 on success. Generates an error message and
1589 * returns -1 on failure.
1592 load_needed_objects(Obj_Entry *first, int flags)
1596 for (obj = first; obj != NULL; obj = obj->next) {
1597 if (process_needed(obj, obj->needed, flags) == -1)
1604 load_preload_objects(void)
1606 char *p = ld_preload;
1607 static const char delim[] = " \t:;";
1612 p += strspn(p, delim);
1613 while (*p != '\0') {
1614 size_t len = strcspn(p, delim);
1619 if (load_object(p, -1, NULL, 0) == NULL)
1620 return -1; /* XXX - cleanup */
1623 p += strspn(p, delim);
1625 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
1630 printable_path(const char *path)
1633 return (path == NULL ? "<unknown>" : path);
1637 * Load a shared object into memory, if it is not already loaded. The
1638 * object may be specified by name or by user-supplied file descriptor
1639 * fd_u. In the later case, the fd_u descriptor is not closed, but its
1642 * Returns a pointer to the Obj_Entry for the object. Returns NULL
1646 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
1654 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
1655 if (object_match_name(obj, name))
1659 path = find_library(name, refobj);
1666 * If we didn't find a match by pathname, or the name is not
1667 * supplied, open the file and check again by device and inode.
1668 * This avoids false mismatches caused by multiple links or ".."
1671 * To avoid a race, we open the file and use fstat() rather than
1676 if ((fd = open(path, O_RDONLY)) == -1) {
1677 _rtld_error("Cannot open \"%s\"", path);
1684 _rtld_error("Cannot dup fd");
1689 if (fstat(fd, &sb) == -1) {
1690 _rtld_error("Cannot fstat \"%s\"", printable_path(path));
1695 for (obj = obj_list->next; obj != NULL; obj = obj->next)
1696 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
1698 if (obj != NULL && name != NULL) {
1699 object_add_name(obj, name);
1704 if (flags & RTLD_LO_NOLOAD) {
1710 /* First use of this object, so we must map it in */
1711 obj = do_load_object(fd, name, path, &sb, flags);
1720 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
1727 * but first, make sure that environment variables haven't been
1728 * used to circumvent the noexec flag on a filesystem.
1730 if (dangerous_ld_env) {
1731 if (fstatfs(fd, &fs) != 0) {
1732 _rtld_error("Cannot fstatfs \"%s\"", printable_path(path));
1735 if (fs.f_flags & MNT_NOEXEC) {
1736 _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
1740 dbg("loading \"%s\"", printable_path(path));
1741 obj = map_object(fd, printable_path(path), sbp);
1746 * If DT_SONAME is present in the object, digest_dynamic2 already
1747 * added it to the object names.
1750 object_add_name(obj, name);
1752 digest_dynamic(obj, 0);
1753 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
1755 dbg("refusing to load non-loadable \"%s\"", obj->path);
1756 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
1757 munmap(obj->mapbase, obj->mapsize);
1763 obj_tail = &obj->next;
1766 linkmap_add(obj); /* for GDB & dlinfo() */
1767 max_stack_flags |= obj->stack_flags;
1769 dbg(" %p .. %p: %s", obj->mapbase,
1770 obj->mapbase + obj->mapsize - 1, obj->path);
1772 dbg(" WARNING: %s has impure text", obj->path);
1773 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
1780 obj_from_addr(const void *addr)
1784 for (obj = obj_list; obj != NULL; obj = obj->next) {
1785 if (addr < (void *) obj->mapbase)
1787 if (addr < (void *) (obj->mapbase + obj->mapsize))
1794 * Call the finalization functions for each of the objects in "list"
1795 * belonging to the DAG of "root" and referenced once. If NULL "root"
1796 * is specified, every finalization function will be called regardless
1797 * of the reference count and the list elements won't be freed. All of
1798 * the objects are expected to have non-NULL fini functions.
1801 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
1806 assert(root == NULL || root->refcount == 1);
1809 * Preserve the current error message since a fini function might
1810 * call into the dynamic linker and overwrite it.
1812 saved_msg = errmsg_save();
1814 STAILQ_FOREACH(elm, list, link) {
1815 if (root != NULL && (elm->obj->refcount != 1 ||
1816 objlist_find(&root->dagmembers, elm->obj) == NULL))
1818 dbg("calling fini function for %s at %p", elm->obj->path,
1819 (void *)elm->obj->fini);
1820 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini, 0, 0,
1822 /* Remove object from fini list to prevent recursive invocation. */
1823 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1825 * XXX: If a dlopen() call references an object while the
1826 * fini function is in progress, we might end up trying to
1827 * unload the referenced object in dlclose() or the object
1828 * won't be unloaded although its fini function has been
1831 lock_release(rtld_bind_lock, lockstate);
1832 call_initfini_pointer(elm->obj, elm->obj->fini);
1833 wlock_acquire(rtld_bind_lock, lockstate);
1834 /* No need to free anything if process is going down. */
1838 * We must restart the list traversal after every fini call
1839 * because a dlclose() call from the fini function or from
1840 * another thread might have modified the reference counts.
1844 } while (elm != NULL);
1845 errmsg_restore(saved_msg);
1849 * Call the initialization functions for each of the objects in
1850 * "list". All of the objects are expected to have non-NULL init
1854 objlist_call_init(Objlist *list, RtldLockState *lockstate)
1861 * Clean init_scanned flag so that objects can be rechecked and
1862 * possibly initialized earlier if any of vectors called below
1863 * cause the change by using dlopen.
1865 for (obj = obj_list; obj != NULL; obj = obj->next)
1866 obj->init_scanned = false;
1869 * Preserve the current error message since an init function might
1870 * call into the dynamic linker and overwrite it.
1872 saved_msg = errmsg_save();
1873 STAILQ_FOREACH(elm, list, link) {
1874 if (elm->obj->init_done) /* Initialized early. */
1876 dbg("calling init function for %s at %p", elm->obj->path,
1877 (void *)elm->obj->init);
1878 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init, 0, 0,
1881 * Race: other thread might try to use this object before current
1882 * one completes the initilization. Not much can be done here
1883 * without better locking.
1885 elm->obj->init_done = true;
1886 lock_release(rtld_bind_lock, lockstate);
1887 call_initfini_pointer(elm->obj, elm->obj->init);
1888 wlock_acquire(rtld_bind_lock, lockstate);
1890 errmsg_restore(saved_msg);
1894 objlist_clear(Objlist *list)
1898 while (!STAILQ_EMPTY(list)) {
1899 elm = STAILQ_FIRST(list);
1900 STAILQ_REMOVE_HEAD(list, link);
1905 static Objlist_Entry *
1906 objlist_find(Objlist *list, const Obj_Entry *obj)
1910 STAILQ_FOREACH(elm, list, link)
1911 if (elm->obj == obj)
1917 objlist_init(Objlist *list)
1923 objlist_push_head(Objlist *list, Obj_Entry *obj)
1927 elm = NEW(Objlist_Entry);
1929 STAILQ_INSERT_HEAD(list, elm, link);
1933 objlist_push_tail(Objlist *list, Obj_Entry *obj)
1937 elm = NEW(Objlist_Entry);
1939 STAILQ_INSERT_TAIL(list, elm, link);
1943 objlist_remove(Objlist *list, Obj_Entry *obj)
1947 if ((elm = objlist_find(list, obj)) != NULL) {
1948 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1954 * Relocate newly-loaded shared objects. The argument is a pointer to
1955 * the Obj_Entry for the first such object. All objects from the first
1956 * to the end of the list of objects are relocated. Returns 0 on success,
1960 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
1961 RtldLockState *lockstate)
1965 for (obj = first; obj != NULL; obj = obj->next) {
1967 dbg("relocating \"%s\"", obj->path);
1968 if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
1969 obj->symtab == NULL || obj->strtab == NULL) {
1970 _rtld_error("%s: Shared object has no run-time symbol table",
1976 /* There are relocations to the write-protected text segment. */
1977 if (mprotect(obj->mapbase, obj->textsize,
1978 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
1979 _rtld_error("%s: Cannot write-enable text segment: %s",
1980 obj->path, strerror(errno));
1985 /* Process the non-PLT relocations. */
1986 if (reloc_non_plt(obj, rtldobj, lockstate))
1989 if (obj->textrel) { /* Re-protected the text segment. */
1990 if (mprotect(obj->mapbase, obj->textsize,
1991 PROT_READ|PROT_EXEC) == -1) {
1992 _rtld_error("%s: Cannot write-protect text segment: %s",
1993 obj->path, strerror(errno));
1999 /* Set the special PLT or GOT entries. */
2002 /* Process the PLT relocations. */
2003 if (reloc_plt(obj) == -1)
2005 /* Relocate the jump slots if we are doing immediate binding. */
2006 if (obj->bind_now || bind_now)
2007 if (reloc_jmpslots(obj, lockstate) == -1)
2011 * Set up the magic number and version in the Obj_Entry. These
2012 * were checked in the crt1.o from the original ElfKit, so we
2013 * set them for backward compatibility.
2015 obj->magic = RTLD_MAGIC;
2016 obj->version = RTLD_VERSION;
2023 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
2024 * referencing STT_GNU_IFUNC symbols is postponed till the other
2025 * relocations are done. The indirect functions specified as
2026 * ifunc are allowed to call other symbols, so we need to have
2027 * objects relocated before asking for resolution from indirects.
2029 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
2030 * instead of the usual lazy handling of PLT slots. It is
2031 * consistent with how GNU does it.
2034 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, RtldLockState *lockstate)
2036 if (obj->irelative && reloc_iresolve(obj, lockstate) == -1)
2038 if ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
2039 reloc_gnu_ifunc(obj, lockstate) == -1)
2045 resolve_objects_ifunc(Obj_Entry *first, bool bind_now, RtldLockState *lockstate)
2049 for (obj = first; obj != NULL; obj = obj->next) {
2050 if (resolve_object_ifunc(obj, bind_now, lockstate) == -1)
2057 initlist_objects_ifunc(Objlist *list, bool bind_now, RtldLockState *lockstate)
2061 STAILQ_FOREACH(elm, list, link) {
2062 if (resolve_object_ifunc(elm->obj, bind_now, lockstate) == -1)
2069 * Cleanup procedure. It will be called (by the atexit mechanism) just
2070 * before the process exits.
2075 RtldLockState lockstate;
2077 wlock_acquire(rtld_bind_lock, &lockstate);
2079 objlist_call_fini(&list_fini, NULL, &lockstate);
2080 /* No need to remove the items from the list, since we are exiting. */
2081 if (!libmap_disable)
2083 lock_release(rtld_bind_lock, &lockstate);
2087 path_enumerate(const char *path, path_enum_proc callback, void *arg)
2095 path += strspn(path, ":;");
2096 while (*path != '\0') {
2100 len = strcspn(path, ":;");
2102 trans = lm_findn(NULL, path, len);
2104 res = callback(trans, strlen(trans), arg);
2107 res = callback(path, len, arg);
2113 path += strspn(path, ":;");
2119 struct try_library_args {
2127 try_library_path(const char *dir, size_t dirlen, void *param)
2129 struct try_library_args *arg;
2132 if (*dir == '/' || trust) {
2135 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
2138 pathname = arg->buffer;
2139 strncpy(pathname, dir, dirlen);
2140 pathname[dirlen] = '/';
2141 strcpy(pathname + dirlen + 1, arg->name);
2143 dbg(" Trying \"%s\"", pathname);
2144 if (access(pathname, F_OK) == 0) { /* We found it */
2145 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
2146 strcpy(pathname, arg->buffer);
2154 search_library_path(const char *name, const char *path)
2157 struct try_library_args arg;
2163 arg.namelen = strlen(name);
2164 arg.buffer = xmalloc(PATH_MAX);
2165 arg.buflen = PATH_MAX;
2167 p = path_enumerate(path, try_library_path, &arg);
2175 dlclose(void *handle)
2178 RtldLockState lockstate;
2180 wlock_acquire(rtld_bind_lock, &lockstate);
2181 root = dlcheck(handle);
2183 lock_release(rtld_bind_lock, &lockstate);
2186 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
2189 /* Unreference the object and its dependencies. */
2190 root->dl_refcount--;
2192 if (root->refcount == 1) {
2194 * The object will be no longer referenced, so we must unload it.
2195 * First, call the fini functions.
2197 objlist_call_fini(&list_fini, root, &lockstate);
2201 /* Finish cleaning up the newly-unreferenced objects. */
2202 GDB_STATE(RT_DELETE,&root->linkmap);
2203 unload_object(root);
2204 GDB_STATE(RT_CONSISTENT,NULL);
2208 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
2209 lock_release(rtld_bind_lock, &lockstate);
2216 char *msg = error_message;
2217 error_message = NULL;
2222 * This function is deprecated and has no effect.
2225 dllockinit(void *context,
2226 void *(*lock_create)(void *context),
2227 void (*rlock_acquire)(void *lock),
2228 void (*wlock_acquire)(void *lock),
2229 void (*lock_release)(void *lock),
2230 void (*lock_destroy)(void *lock),
2231 void (*context_destroy)(void *context))
2233 static void *cur_context;
2234 static void (*cur_context_destroy)(void *);
2236 /* Just destroy the context from the previous call, if necessary. */
2237 if (cur_context_destroy != NULL)
2238 cur_context_destroy(cur_context);
2239 cur_context = context;
2240 cur_context_destroy = context_destroy;
2244 dlopen(const char *name, int mode)
2247 return (rtld_dlopen(name, -1, mode));
2251 fdlopen(int fd, int mode)
2254 return (rtld_dlopen(NULL, fd, mode));
2258 rtld_dlopen(const char *name, int fd, int mode)
2260 RtldLockState lockstate;
2263 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
2264 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
2265 if (ld_tracing != NULL) {
2266 rlock_acquire(rtld_bind_lock, &lockstate);
2267 if (sigsetjmp(lockstate.env, 0) != 0)
2268 lock_upgrade(rtld_bind_lock, &lockstate);
2269 environ = (char **)*get_program_var_addr("environ", &lockstate);
2270 lock_release(rtld_bind_lock, &lockstate);
2272 lo_flags = RTLD_LO_DLOPEN;
2273 if (mode & RTLD_NODELETE)
2274 lo_flags |= RTLD_LO_NODELETE;
2275 if (mode & RTLD_NOLOAD)
2276 lo_flags |= RTLD_LO_NOLOAD;
2277 if (ld_tracing != NULL)
2278 lo_flags |= RTLD_LO_TRACE;
2280 return (dlopen_object(name, fd, obj_main, lo_flags,
2281 mode & (RTLD_MODEMASK | RTLD_GLOBAL)));
2285 dlopen_cleanup(Obj_Entry *obj)
2290 if (obj->refcount == 0)
2295 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
2298 Obj_Entry **old_obj_tail;
2301 RtldLockState lockstate;
2304 objlist_init(&initlist);
2306 wlock_acquire(rtld_bind_lock, &lockstate);
2307 GDB_STATE(RT_ADD,NULL);
2309 old_obj_tail = obj_tail;
2311 if (name == NULL && fd == -1) {
2315 obj = load_object(name, fd, refobj, lo_flags);
2320 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
2321 objlist_push_tail(&list_global, obj);
2322 if (*old_obj_tail != NULL) { /* We loaded something new. */
2323 assert(*old_obj_tail == obj);
2324 result = load_needed_objects(obj, lo_flags & RTLD_LO_DLOPEN);
2328 result = rtld_verify_versions(&obj->dagmembers);
2329 if (result != -1 && ld_tracing)
2331 if (result == -1 || (relocate_objects(obj, (mode & RTLD_MODEMASK)
2332 == RTLD_NOW, &obj_rtld, &lockstate)) == -1) {
2333 dlopen_cleanup(obj);
2336 /* Make list of init functions to call. */
2337 initlist_add_objects(obj, &obj->next, &initlist);
2342 * Bump the reference counts for objects on this DAG. If
2343 * this is the first dlopen() call for the object that was
2344 * already loaded as a dependency, initialize the dag
2350 if ((lo_flags & RTLD_LO_TRACE) != 0)
2353 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
2354 obj->z_nodelete) && !obj->ref_nodel) {
2355 dbg("obj %s nodelete", obj->path);
2357 obj->z_nodelete = obj->ref_nodel = true;
2361 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
2363 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
2365 map_stacks_exec(&lockstate);
2367 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
2368 &lockstate) == -1) {
2369 objlist_clear(&initlist);
2370 dlopen_cleanup(obj);
2371 lock_release(rtld_bind_lock, &lockstate);
2375 /* Call the init functions. */
2376 objlist_call_init(&initlist, &lockstate);
2377 objlist_clear(&initlist);
2378 lock_release(rtld_bind_lock, &lockstate);
2381 trace_loaded_objects(obj);
2382 lock_release(rtld_bind_lock, &lockstate);
2387 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
2391 const Obj_Entry *obj, *defobj;
2394 RtldLockState lockstate;
2399 symlook_init(&req, name);
2401 req.flags = flags | SYMLOOK_IN_PLT;
2402 req.lockstate = &lockstate;
2404 rlock_acquire(rtld_bind_lock, &lockstate);
2405 if (sigsetjmp(lockstate.env, 0) != 0)
2406 lock_upgrade(rtld_bind_lock, &lockstate);
2407 if (handle == NULL || handle == RTLD_NEXT ||
2408 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
2410 if ((obj = obj_from_addr(retaddr)) == NULL) {
2411 _rtld_error("Cannot determine caller's shared object");
2412 lock_release(rtld_bind_lock, &lockstate);
2415 if (handle == NULL) { /* Just the caller's shared object. */
2416 res = symlook_obj(&req, obj);
2419 defobj = req.defobj_out;
2421 } else if (handle == RTLD_NEXT || /* Objects after caller's */
2422 handle == RTLD_SELF) { /* ... caller included */
2423 if (handle == RTLD_NEXT)
2425 for (; obj != NULL; obj = obj->next) {
2426 res = symlook_obj(&req, obj);
2429 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) {
2431 defobj = req.defobj_out;
2432 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2438 * Search the dynamic linker itself, and possibly resolve the
2439 * symbol from there. This is how the application links to
2440 * dynamic linker services such as dlopen.
2442 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2443 res = symlook_obj(&req, &obj_rtld);
2446 defobj = req.defobj_out;
2450 assert(handle == RTLD_DEFAULT);
2451 res = symlook_default(&req, obj);
2453 defobj = req.defobj_out;
2458 if ((obj = dlcheck(handle)) == NULL) {
2459 lock_release(rtld_bind_lock, &lockstate);
2463 donelist_init(&donelist);
2464 if (obj->mainprog) {
2465 /* Handle obtained by dlopen(NULL, ...) implies global scope. */
2466 res = symlook_global(&req, &donelist);
2469 defobj = req.defobj_out;
2472 * Search the dynamic linker itself, and possibly resolve the
2473 * symbol from there. This is how the application links to
2474 * dynamic linker services such as dlopen.
2476 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2477 res = symlook_obj(&req, &obj_rtld);
2480 defobj = req.defobj_out;
2485 /* Search the whole DAG rooted at the given object. */
2486 res = symlook_list(&req, &obj->dagmembers, &donelist);
2489 defobj = req.defobj_out;
2495 lock_release(rtld_bind_lock, &lockstate);
2498 * The value required by the caller is derived from the value
2499 * of the symbol. For the ia64 architecture, we need to
2500 * construct a function descriptor which the caller can use to
2501 * call the function with the right 'gp' value. For other
2502 * architectures and for non-functions, the value is simply
2503 * the relocated value of the symbol.
2505 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
2506 return (make_function_pointer(def, defobj));
2507 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
2508 return (rtld_resolve_ifunc(defobj, def));
2510 return (defobj->relocbase + def->st_value);
2513 _rtld_error("Undefined symbol \"%s\"", name);
2514 lock_release(rtld_bind_lock, &lockstate);
2519 dlsym(void *handle, const char *name)
2521 return do_dlsym(handle, name, __builtin_return_address(0), NULL,
2526 dlfunc(void *handle, const char *name)
2533 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
2539 dlvsym(void *handle, const char *name, const char *version)
2543 ventry.name = version;
2545 ventry.hash = elf_hash(version);
2547 return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
2552 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
2554 const Obj_Entry *obj;
2555 RtldLockState lockstate;
2557 rlock_acquire(rtld_bind_lock, &lockstate);
2558 obj = obj_from_addr(addr);
2560 _rtld_error("No shared object contains address");
2561 lock_release(rtld_bind_lock, &lockstate);
2564 rtld_fill_dl_phdr_info(obj, phdr_info);
2565 lock_release(rtld_bind_lock, &lockstate);
2570 dladdr(const void *addr, Dl_info *info)
2572 const Obj_Entry *obj;
2575 unsigned long symoffset;
2576 RtldLockState lockstate;
2578 rlock_acquire(rtld_bind_lock, &lockstate);
2579 obj = obj_from_addr(addr);
2581 _rtld_error("No shared object contains address");
2582 lock_release(rtld_bind_lock, &lockstate);
2585 info->dli_fname = obj->path;
2586 info->dli_fbase = obj->mapbase;
2587 info->dli_saddr = (void *)0;
2588 info->dli_sname = NULL;
2591 * Walk the symbol list looking for the symbol whose address is
2592 * closest to the address sent in.
2594 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
2595 def = obj->symtab + symoffset;
2598 * For skip the symbol if st_shndx is either SHN_UNDEF or
2601 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
2605 * If the symbol is greater than the specified address, or if it
2606 * is further away from addr than the current nearest symbol,
2609 symbol_addr = obj->relocbase + def->st_value;
2610 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
2613 /* Update our idea of the nearest symbol. */
2614 info->dli_sname = obj->strtab + def->st_name;
2615 info->dli_saddr = symbol_addr;
2618 if (info->dli_saddr == addr)
2621 lock_release(rtld_bind_lock, &lockstate);
2626 dlinfo(void *handle, int request, void *p)
2628 const Obj_Entry *obj;
2629 RtldLockState lockstate;
2632 rlock_acquire(rtld_bind_lock, &lockstate);
2634 if (handle == NULL || handle == RTLD_SELF) {
2637 retaddr = __builtin_return_address(0); /* __GNUC__ only */
2638 if ((obj = obj_from_addr(retaddr)) == NULL)
2639 _rtld_error("Cannot determine caller's shared object");
2641 obj = dlcheck(handle);
2644 lock_release(rtld_bind_lock, &lockstate);
2650 case RTLD_DI_LINKMAP:
2651 *((struct link_map const **)p) = &obj->linkmap;
2653 case RTLD_DI_ORIGIN:
2654 error = rtld_dirname(obj->path, p);
2657 case RTLD_DI_SERINFOSIZE:
2658 case RTLD_DI_SERINFO:
2659 error = do_search_info(obj, request, (struct dl_serinfo *)p);
2663 _rtld_error("Invalid request %d passed to dlinfo()", request);
2667 lock_release(rtld_bind_lock, &lockstate);
2673 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
2676 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
2677 phdr_info->dlpi_name = STAILQ_FIRST(&obj->names) ?
2678 STAILQ_FIRST(&obj->names)->name : obj->path;
2679 phdr_info->dlpi_phdr = obj->phdr;
2680 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
2681 phdr_info->dlpi_tls_modid = obj->tlsindex;
2682 phdr_info->dlpi_tls_data = obj->tlsinit;
2683 phdr_info->dlpi_adds = obj_loads;
2684 phdr_info->dlpi_subs = obj_loads - obj_count;
2688 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
2690 struct dl_phdr_info phdr_info;
2691 const Obj_Entry *obj;
2692 RtldLockState bind_lockstate, phdr_lockstate;
2695 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
2696 rlock_acquire(rtld_bind_lock, &bind_lockstate);
2700 for (obj = obj_list; obj != NULL; obj = obj->next) {
2701 rtld_fill_dl_phdr_info(obj, &phdr_info);
2702 if ((error = callback(&phdr_info, sizeof phdr_info, param)) != 0)
2706 lock_release(rtld_bind_lock, &bind_lockstate);
2707 lock_release(rtld_phdr_lock, &phdr_lockstate);
2712 struct fill_search_info_args {
2715 Dl_serinfo *serinfo;
2716 Dl_serpath *serpath;
2721 fill_search_info(const char *dir, size_t dirlen, void *param)
2723 struct fill_search_info_args *arg;
2727 if (arg->request == RTLD_DI_SERINFOSIZE) {
2728 arg->serinfo->dls_cnt ++;
2729 arg->serinfo->dls_size += sizeof(Dl_serpath) + dirlen + 1;
2731 struct dl_serpath *s_entry;
2733 s_entry = arg->serpath;
2734 s_entry->dls_name = arg->strspace;
2735 s_entry->dls_flags = arg->flags;
2737 strncpy(arg->strspace, dir, dirlen);
2738 arg->strspace[dirlen] = '\0';
2740 arg->strspace += dirlen + 1;
2748 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
2750 struct dl_serinfo _info;
2751 struct fill_search_info_args args;
2753 args.request = RTLD_DI_SERINFOSIZE;
2754 args.serinfo = &_info;
2756 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2759 path_enumerate(ld_library_path, fill_search_info, &args);
2760 path_enumerate(obj->rpath, fill_search_info, &args);
2761 path_enumerate(gethints(), fill_search_info, &args);
2762 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
2765 if (request == RTLD_DI_SERINFOSIZE) {
2766 info->dls_size = _info.dls_size;
2767 info->dls_cnt = _info.dls_cnt;
2771 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
2772 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
2776 args.request = RTLD_DI_SERINFO;
2777 args.serinfo = info;
2778 args.serpath = &info->dls_serpath[0];
2779 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
2781 args.flags = LA_SER_LIBPATH;
2782 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
2785 args.flags = LA_SER_RUNPATH;
2786 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
2789 args.flags = LA_SER_CONFIG;
2790 if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
2793 args.flags = LA_SER_DEFAULT;
2794 if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
2800 rtld_dirname(const char *path, char *bname)
2804 /* Empty or NULL string gets treated as "." */
2805 if (path == NULL || *path == '\0') {
2811 /* Strip trailing slashes */
2812 endp = path + strlen(path) - 1;
2813 while (endp > path && *endp == '/')
2816 /* Find the start of the dir */
2817 while (endp > path && *endp != '/')
2820 /* Either the dir is "/" or there are no slashes */
2822 bname[0] = *endp == '/' ? '/' : '.';
2828 } while (endp > path && *endp == '/');
2831 if (endp - path + 2 > PATH_MAX)
2833 _rtld_error("Filename is too long: %s", path);
2837 strncpy(bname, path, endp - path + 1);
2838 bname[endp - path + 1] = '\0';
2843 rtld_dirname_abs(const char *path, char *base)
2845 char base_rel[PATH_MAX];
2847 if (rtld_dirname(path, base) == -1)
2851 if (getcwd(base_rel, sizeof(base_rel)) == NULL ||
2852 strlcat(base_rel, "/", sizeof(base_rel)) >= sizeof(base_rel) ||
2853 strlcat(base_rel, base, sizeof(base_rel)) >= sizeof(base_rel))
2855 strcpy(base, base_rel);
2860 linkmap_add(Obj_Entry *obj)
2862 struct link_map *l = &obj->linkmap;
2863 struct link_map *prev;
2865 obj->linkmap.l_name = obj->path;
2866 obj->linkmap.l_addr = obj->mapbase;
2867 obj->linkmap.l_ld = obj->dynamic;
2869 /* GDB needs load offset on MIPS to use the symbols */
2870 obj->linkmap.l_offs = obj->relocbase;
2873 if (r_debug.r_map == NULL) {
2879 * Scan to the end of the list, but not past the entry for the
2880 * dynamic linker, which we want to keep at the very end.
2882 for (prev = r_debug.r_map;
2883 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
2884 prev = prev->l_next)
2887 /* Link in the new entry. */
2889 l->l_next = prev->l_next;
2890 if (l->l_next != NULL)
2891 l->l_next->l_prev = l;
2896 linkmap_delete(Obj_Entry *obj)
2898 struct link_map *l = &obj->linkmap;
2900 if (l->l_prev == NULL) {
2901 if ((r_debug.r_map = l->l_next) != NULL)
2902 l->l_next->l_prev = NULL;
2906 if ((l->l_prev->l_next = l->l_next) != NULL)
2907 l->l_next->l_prev = l->l_prev;
2911 * Function for the debugger to set a breakpoint on to gain control.
2913 * The two parameters allow the debugger to easily find and determine
2914 * what the runtime loader is doing and to whom it is doing it.
2916 * When the loadhook trap is hit (r_debug_state, set at program
2917 * initialization), the arguments can be found on the stack:
2919 * +8 struct link_map *m
2920 * +4 struct r_debug *rd
2924 r_debug_state(struct r_debug* rd, struct link_map *m)
2927 * The following is a hack to force the compiler to emit calls to
2928 * this function, even when optimizing. If the function is empty,
2929 * the compiler is not obliged to emit any code for calls to it,
2930 * even when marked __noinline. However, gdb depends on those
2933 __asm __volatile("" : : : "memory");
2937 * Get address of the pointer variable in the main program.
2938 * Prefer non-weak symbol over the weak one.
2940 static const void **
2941 get_program_var_addr(const char *name, RtldLockState *lockstate)
2946 symlook_init(&req, name);
2947 req.lockstate = lockstate;
2948 donelist_init(&donelist);
2949 if (symlook_global(&req, &donelist) != 0)
2951 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
2952 return ((const void **)make_function_pointer(req.sym_out,
2954 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
2955 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
2957 return ((const void **)(req.defobj_out->relocbase +
2958 req.sym_out->st_value));
2962 * Set a pointer variable in the main program to the given value. This
2963 * is used to set key variables such as "environ" before any of the
2964 * init functions are called.
2967 set_program_var(const char *name, const void *value)
2971 if ((addr = get_program_var_addr(name, NULL)) != NULL) {
2972 dbg("\"%s\": *%p <-- %p", name, addr, value);
2978 * Search the global objects, including dependencies and main object,
2979 * for the given symbol.
2982 symlook_global(SymLook *req, DoneList *donelist)
2985 const Objlist_Entry *elm;
2988 symlook_init_from_req(&req1, req);
2990 /* Search all objects loaded at program start up. */
2991 if (req->defobj_out == NULL ||
2992 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
2993 res = symlook_list(&req1, &list_main, donelist);
2994 if (res == 0 && (req->defobj_out == NULL ||
2995 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
2996 req->sym_out = req1.sym_out;
2997 req->defobj_out = req1.defobj_out;
2998 assert(req->defobj_out != NULL);
3002 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
3003 STAILQ_FOREACH(elm, &list_global, link) {
3004 if (req->defobj_out != NULL &&
3005 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3007 res = symlook_list(&req1, &elm->obj->dagmembers, 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 return (req->sym_out != NULL ? 0 : ESRCH);
3020 * Given a symbol name in a referencing object, find the corresponding
3021 * definition of the symbol. Returns a pointer to the symbol, or NULL if
3022 * no definition was found. Returns a pointer to the Obj_Entry of the
3023 * defining object via the reference parameter DEFOBJ_OUT.
3026 symlook_default(SymLook *req, const Obj_Entry *refobj)
3029 const Objlist_Entry *elm;
3033 donelist_init(&donelist);
3034 symlook_init_from_req(&req1, req);
3036 /* Look first in the referencing object if linked symbolically. */
3037 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
3038 res = symlook_obj(&req1, refobj);
3040 req->sym_out = req1.sym_out;
3041 req->defobj_out = req1.defobj_out;
3042 assert(req->defobj_out != NULL);
3046 symlook_global(req, &donelist);
3048 /* Search all dlopened DAGs containing the referencing object. */
3049 STAILQ_FOREACH(elm, &refobj->dldags, link) {
3050 if (req->sym_out != NULL &&
3051 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3053 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
3054 if (res == 0 && (req->sym_out == NULL ||
3055 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3056 req->sym_out = req1.sym_out;
3057 req->defobj_out = req1.defobj_out;
3058 assert(req->defobj_out != NULL);
3063 * Search the dynamic linker itself, and possibly resolve the
3064 * symbol from there. This is how the application links to
3065 * dynamic linker services such as dlopen.
3067 if (req->sym_out == NULL ||
3068 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3069 res = symlook_obj(&req1, &obj_rtld);
3071 req->sym_out = req1.sym_out;
3072 req->defobj_out = req1.defobj_out;
3073 assert(req->defobj_out != NULL);
3077 return (req->sym_out != NULL ? 0 : ESRCH);
3081 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
3084 const Obj_Entry *defobj;
3085 const Objlist_Entry *elm;
3091 STAILQ_FOREACH(elm, objlist, link) {
3092 if (donelist_check(dlp, elm->obj))
3094 symlook_init_from_req(&req1, req);
3095 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
3096 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3098 defobj = req1.defobj_out;
3099 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3106 req->defobj_out = defobj;
3113 * Search the chain of DAGS cointed to by the given Needed_Entry
3114 * for a symbol of the given name. Each DAG is scanned completely
3115 * before advancing to the next one. Returns a pointer to the symbol,
3116 * or NULL if no definition was found.
3119 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
3122 const Needed_Entry *n;
3123 const Obj_Entry *defobj;
3129 symlook_init_from_req(&req1, req);
3130 for (n = needed; n != NULL; n = n->next) {
3131 if (n->obj == NULL ||
3132 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
3134 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3136 defobj = req1.defobj_out;
3137 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3143 req->defobj_out = defobj;
3150 * Search the symbol table of a single shared object for a symbol of
3151 * the given name and version, if requested. Returns a pointer to the
3152 * symbol, or NULL if no definition was found. If the object is
3153 * filter, return filtered symbol from filtee.
3155 * The symbol's hash value is passed in for efficiency reasons; that
3156 * eliminates many recomputations of the hash value.
3159 symlook_obj(SymLook *req, const Obj_Entry *obj)
3165 mres = symlook_obj1(req, obj);
3167 if (obj->needed_filtees != NULL) {
3168 load_filtees(__DECONST(Obj_Entry *, obj), 0, req->lockstate);
3169 donelist_init(&donelist);
3170 symlook_init_from_req(&req1, req);
3171 res = symlook_needed(&req1, obj->needed_filtees, &donelist);
3173 req->sym_out = req1.sym_out;
3174 req->defobj_out = req1.defobj_out;
3178 if (obj->needed_aux_filtees != NULL) {
3179 load_filtees(__DECONST(Obj_Entry *, obj), 0, req->lockstate);
3180 donelist_init(&donelist);
3181 symlook_init_from_req(&req1, req);
3182 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
3184 req->sym_out = req1.sym_out;
3185 req->defobj_out = req1.defobj_out;
3194 symlook_obj1(SymLook *req, const Obj_Entry *obj)
3196 unsigned long symnum;
3197 const Elf_Sym *vsymp;
3201 if (obj->buckets == NULL)
3206 symnum = obj->buckets[req->hash % obj->nbuckets];
3208 for (; symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
3209 const Elf_Sym *symp;
3212 if (symnum >= obj->nchains)
3213 return (ESRCH); /* Bad object */
3215 symp = obj->symtab + symnum;
3216 strp = obj->strtab + symp->st_name;
3218 switch (ELF_ST_TYPE(symp->st_info)) {
3223 if (symp->st_value == 0)
3227 if (symp->st_shndx != SHN_UNDEF)
3230 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
3231 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
3238 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
3241 if (req->ventry == NULL) {
3242 if (obj->versyms != NULL) {
3243 verndx = VER_NDX(obj->versyms[symnum]);
3244 if (verndx > obj->vernum) {
3245 _rtld_error("%s: symbol %s references wrong version %d",
3246 obj->path, obj->strtab + symnum, verndx);
3250 * If we are not called from dlsym (i.e. this is a normal
3251 * relocation from unversioned binary), accept the symbol
3252 * immediately if it happens to have first version after
3253 * this shared object became versioned. Otherwise, if
3254 * symbol is versioned and not hidden, remember it. If it
3255 * is the only symbol with this name exported by the
3256 * shared object, it will be returned as a match at the
3257 * end of the function. If symbol is global (verndx < 2)
3258 * accept it unconditionally.
3260 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
3261 verndx == VER_NDX_GIVEN) {
3262 req->sym_out = symp;
3263 req->defobj_out = obj;
3266 else if (verndx >= VER_NDX_GIVEN) {
3267 if ((obj->versyms[symnum] & VER_NDX_HIDDEN) == 0) {
3275 req->sym_out = symp;
3276 req->defobj_out = obj;
3279 if (obj->versyms == NULL) {
3280 if (object_match_name(obj, req->ventry->name)) {
3281 _rtld_error("%s: object %s should provide version %s for "
3282 "symbol %s", obj_rtld.path, obj->path,
3283 req->ventry->name, obj->strtab + symnum);
3287 verndx = VER_NDX(obj->versyms[symnum]);
3288 if (verndx > obj->vernum) {
3289 _rtld_error("%s: symbol %s references wrong version %d",
3290 obj->path, obj->strtab + symnum, verndx);
3293 if (obj->vertab[verndx].hash != req->ventry->hash ||
3294 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
3296 * Version does not match. Look if this is a global symbol
3297 * and if it is not hidden. If global symbol (verndx < 2)
3298 * is available, use it. Do not return symbol if we are
3299 * called by dlvsym, because dlvsym looks for a specific
3300 * version and default one is not what dlvsym wants.
3302 if ((req->flags & SYMLOOK_DLSYM) ||
3303 (obj->versyms[symnum] & VER_NDX_HIDDEN) ||
3304 (verndx >= VER_NDX_GIVEN))
3308 req->sym_out = symp;
3309 req->defobj_out = obj;
3314 req->sym_out = vsymp;
3315 req->defobj_out = obj;
3322 trace_loaded_objects(Obj_Entry *obj)
3324 char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
3327 if ((main_local = getenv(LD_ "TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
3330 if ((fmt1 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT1")) == NULL)
3331 fmt1 = "\t%o => %p (%x)\n";
3333 if ((fmt2 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT2")) == NULL)
3334 fmt2 = "\t%o (%x)\n";
3336 list_containers = getenv(LD_ "TRACE_LOADED_OBJECTS_ALL");
3338 for (; obj; obj = obj->next) {
3339 Needed_Entry *needed;
3343 if (list_containers && obj->needed != NULL)
3344 rtld_printf("%s:\n", obj->path);
3345 for (needed = obj->needed; needed; needed = needed->next) {
3346 if (needed->obj != NULL) {
3347 if (needed->obj->traced && !list_containers)
3349 needed->obj->traced = true;
3350 path = needed->obj->path;
3354 name = (char *)obj->strtab + needed->name;
3355 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
3357 fmt = is_lib ? fmt1 : fmt2;
3358 while ((c = *fmt++) != '\0') {
3384 rtld_putstr(main_local);
3387 rtld_putstr(obj_main->path);
3394 rtld_printf("%d", sodp->sod_major);
3397 rtld_printf("%d", sodp->sod_minor);
3404 rtld_printf("%p", needed->obj ? needed->obj->mapbase :
3417 * Unload a dlopened object and its dependencies from memory and from
3418 * our data structures. It is assumed that the DAG rooted in the
3419 * object has already been unreferenced, and that the object has a
3420 * reference count of 0.
3423 unload_object(Obj_Entry *root)
3428 assert(root->refcount == 0);
3431 * Pass over the DAG removing unreferenced objects from
3432 * appropriate lists.
3434 unlink_object(root);
3436 /* Unmap all objects that are no longer referenced. */
3437 linkp = &obj_list->next;
3438 while ((obj = *linkp) != NULL) {
3439 if (obj->refcount == 0) {
3440 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
3442 dbg("unloading \"%s\"", obj->path);
3443 unload_filtees(root);
3444 munmap(obj->mapbase, obj->mapsize);
3445 linkmap_delete(obj);
3456 unlink_object(Obj_Entry *root)
3460 if (root->refcount == 0) {
3461 /* Remove the object from the RTLD_GLOBAL list. */
3462 objlist_remove(&list_global, root);
3464 /* Remove the object from all objects' DAG lists. */
3465 STAILQ_FOREACH(elm, &root->dagmembers, link) {
3466 objlist_remove(&elm->obj->dldags, root);
3467 if (elm->obj != root)
3468 unlink_object(elm->obj);
3474 ref_dag(Obj_Entry *root)
3478 assert(root->dag_inited);
3479 STAILQ_FOREACH(elm, &root->dagmembers, link)
3480 elm->obj->refcount++;
3484 unref_dag(Obj_Entry *root)
3488 assert(root->dag_inited);
3489 STAILQ_FOREACH(elm, &root->dagmembers, link)
3490 elm->obj->refcount--;
3494 * Common code for MD __tls_get_addr().
3497 tls_get_addr_common(Elf_Addr** dtvp, int index, size_t offset)
3499 Elf_Addr* dtv = *dtvp;
3500 RtldLockState lockstate;
3502 /* Check dtv generation in case new modules have arrived */
3503 if (dtv[0] != tls_dtv_generation) {
3507 wlock_acquire(rtld_bind_lock, &lockstate);
3508 newdtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
3510 if (to_copy > tls_max_index)
3511 to_copy = tls_max_index;
3512 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
3513 newdtv[0] = tls_dtv_generation;
3514 newdtv[1] = tls_max_index;
3516 lock_release(rtld_bind_lock, &lockstate);
3517 dtv = *dtvp = newdtv;
3520 /* Dynamically allocate module TLS if necessary */
3521 if (!dtv[index + 1]) {
3522 /* Signal safe, wlock will block out signals. */
3523 wlock_acquire(rtld_bind_lock, &lockstate);
3524 if (!dtv[index + 1])
3525 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
3526 lock_release(rtld_bind_lock, &lockstate);
3528 return (void*) (dtv[index + 1] + offset);
3531 /* XXX not sure what variants to use for arm. */
3533 #if defined(__ia64__) || defined(__powerpc__)
3536 * Allocate Static TLS using the Variant I method.
3539 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
3548 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
3551 assert(tcbsize >= TLS_TCB_SIZE);
3552 tcb = calloc(1, tls_static_space - TLS_TCB_SIZE + tcbsize);
3553 tls = (Elf_Addr **)(tcb + tcbsize - TLS_TCB_SIZE);
3555 if (oldtcb != NULL) {
3556 memcpy(tls, oldtcb, tls_static_space);
3559 /* Adjust the DTV. */
3561 for (i = 0; i < dtv[1]; i++) {
3562 if (dtv[i+2] >= (Elf_Addr)oldtcb &&
3563 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
3564 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tls;
3568 dtv = calloc(tls_max_index + 2, sizeof(Elf_Addr));
3570 dtv[0] = tls_dtv_generation;
3571 dtv[1] = tls_max_index;
3573 for (obj = objs; obj; obj = obj->next) {
3574 if (obj->tlsoffset > 0) {
3575 addr = (Elf_Addr)tls + obj->tlsoffset;
3576 if (obj->tlsinitsize > 0)
3577 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
3578 if (obj->tlssize > obj->tlsinitsize)
3579 memset((void*) (addr + obj->tlsinitsize), 0,
3580 obj->tlssize - obj->tlsinitsize);
3581 dtv[obj->tlsindex + 1] = addr;
3590 free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
3593 Elf_Addr tlsstart, tlsend;
3596 assert(tcbsize >= TLS_TCB_SIZE);
3598 tlsstart = (Elf_Addr)tcb + tcbsize - TLS_TCB_SIZE;
3599 tlsend = tlsstart + tls_static_space;
3601 dtv = *(Elf_Addr **)tlsstart;
3603 for (i = 0; i < dtvsize; i++) {
3604 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
3605 free((void*)dtv[i+2]);
3614 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) || \
3615 defined(__arm__) || defined(__mips__)
3618 * Allocate Static TLS using the Variant II method.
3621 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
3626 Elf_Addr *dtv, *olddtv;
3627 Elf_Addr segbase, oldsegbase, addr;
3630 size = round(tls_static_space, tcbalign);
3632 assert(tcbsize >= 2*sizeof(Elf_Addr));
3633 tls = calloc(1, size + tcbsize);
3634 dtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
3636 segbase = (Elf_Addr)(tls + size);
3637 ((Elf_Addr*)segbase)[0] = segbase;
3638 ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
3640 dtv[0] = tls_dtv_generation;
3641 dtv[1] = tls_max_index;
3645 * Copy the static TLS block over whole.
3647 oldsegbase = (Elf_Addr) oldtls;
3648 memcpy((void *)(segbase - tls_static_space),
3649 (const void *)(oldsegbase - tls_static_space),
3653 * If any dynamic TLS blocks have been created tls_get_addr(),
3656 olddtv = ((Elf_Addr**)oldsegbase)[1];
3657 for (i = 0; i < olddtv[1]; i++) {
3658 if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
3659 dtv[i+2] = olddtv[i+2];
3665 * We assume that this block was the one we created with
3666 * allocate_initial_tls().
3668 free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
3670 for (obj = objs; obj; obj = obj->next) {
3671 if (obj->tlsoffset) {
3672 addr = segbase - obj->tlsoffset;
3673 memset((void*) (addr + obj->tlsinitsize),
3674 0, obj->tlssize - obj->tlsinitsize);
3676 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
3677 dtv[obj->tlsindex + 1] = addr;
3682 return (void*) segbase;
3686 free_tls(void *tls, size_t tcbsize, size_t tcbalign)
3691 Elf_Addr tlsstart, tlsend;
3694 * Figure out the size of the initial TLS block so that we can
3695 * find stuff which ___tls_get_addr() allocated dynamically.
3697 size = round(tls_static_space, tcbalign);
3699 dtv = ((Elf_Addr**)tls)[1];
3701 tlsend = (Elf_Addr) tls;
3702 tlsstart = tlsend - size;
3703 for (i = 0; i < dtvsize; i++) {
3704 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] > tlsend)) {
3705 free((void*) dtv[i+2]);
3709 free((void*) tlsstart);
3716 * Allocate TLS block for module with given index.
3719 allocate_module_tls(int index)
3724 for (obj = obj_list; obj; obj = obj->next) {
3725 if (obj->tlsindex == index)
3729 _rtld_error("Can't find module with TLS index %d", index);
3733 p = malloc(obj->tlssize);
3735 _rtld_error("Cannot allocate TLS block for index %d", index);
3738 memcpy(p, obj->tlsinit, obj->tlsinitsize);
3739 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
3745 allocate_tls_offset(Obj_Entry *obj)
3752 if (obj->tlssize == 0) {
3753 obj->tls_done = true;
3757 if (obj->tlsindex == 1)
3758 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
3760 off = calculate_tls_offset(tls_last_offset, tls_last_size,
3761 obj->tlssize, obj->tlsalign);
3764 * If we have already fixed the size of the static TLS block, we
3765 * must stay within that size. When allocating the static TLS, we
3766 * leave a small amount of space spare to be used for dynamically
3767 * loading modules which use static TLS.
3769 if (tls_static_space) {
3770 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
3774 tls_last_offset = obj->tlsoffset = off;
3775 tls_last_size = obj->tlssize;
3776 obj->tls_done = true;
3782 free_tls_offset(Obj_Entry *obj)
3786 * If we were the last thing to allocate out of the static TLS
3787 * block, we give our space back to the 'allocator'. This is a
3788 * simplistic workaround to allow libGL.so.1 to be loaded and
3789 * unloaded multiple times.
3791 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
3792 == calculate_tls_end(tls_last_offset, tls_last_size)) {
3793 tls_last_offset -= obj->tlssize;
3799 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
3802 RtldLockState lockstate;
3804 wlock_acquire(rtld_bind_lock, &lockstate);
3805 ret = allocate_tls(obj_list, oldtls, tcbsize, tcbalign);
3806 lock_release(rtld_bind_lock, &lockstate);
3811 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
3813 RtldLockState lockstate;
3815 wlock_acquire(rtld_bind_lock, &lockstate);
3816 free_tls(tcb, tcbsize, tcbalign);
3817 lock_release(rtld_bind_lock, &lockstate);
3821 object_add_name(Obj_Entry *obj, const char *name)
3827 entry = malloc(sizeof(Name_Entry) + len);
3829 if (entry != NULL) {
3830 strcpy(entry->name, name);
3831 STAILQ_INSERT_TAIL(&obj->names, entry, link);
3836 object_match_name(const Obj_Entry *obj, const char *name)
3840 STAILQ_FOREACH(entry, &obj->names, link) {
3841 if (strcmp(name, entry->name) == 0)
3848 locate_dependency(const Obj_Entry *obj, const char *name)
3850 const Objlist_Entry *entry;
3851 const Needed_Entry *needed;
3853 STAILQ_FOREACH(entry, &list_main, link) {
3854 if (object_match_name(entry->obj, name))
3858 for (needed = obj->needed; needed != NULL; needed = needed->next) {
3859 if (strcmp(obj->strtab + needed->name, name) == 0 ||
3860 (needed->obj != NULL && object_match_name(needed->obj, name))) {
3862 * If there is DT_NEEDED for the name we are looking for,
3863 * we are all set. Note that object might not be found if
3864 * dependency was not loaded yet, so the function can
3865 * return NULL here. This is expected and handled
3866 * properly by the caller.
3868 return (needed->obj);
3871 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
3877 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
3878 const Elf_Vernaux *vna)
3880 const Elf_Verdef *vd;
3881 const char *vername;
3883 vername = refobj->strtab + vna->vna_name;
3884 vd = depobj->verdef;
3886 _rtld_error("%s: version %s required by %s not defined",
3887 depobj->path, vername, refobj->path);
3891 if (vd->vd_version != VER_DEF_CURRENT) {
3892 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
3893 depobj->path, vd->vd_version);
3896 if (vna->vna_hash == vd->vd_hash) {
3897 const Elf_Verdaux *aux = (const Elf_Verdaux *)
3898 ((char *)vd + vd->vd_aux);
3899 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
3902 if (vd->vd_next == 0)
3904 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3906 if (vna->vna_flags & VER_FLG_WEAK)
3908 _rtld_error("%s: version %s required by %s not found",
3909 depobj->path, vername, refobj->path);
3914 rtld_verify_object_versions(Obj_Entry *obj)
3916 const Elf_Verneed *vn;
3917 const Elf_Verdef *vd;
3918 const Elf_Verdaux *vda;
3919 const Elf_Vernaux *vna;
3920 const Obj_Entry *depobj;
3921 int maxvernum, vernum;
3925 * Walk over defined and required version records and figure out
3926 * max index used by any of them. Do very basic sanity checking
3930 while (vn != NULL) {
3931 if (vn->vn_version != VER_NEED_CURRENT) {
3932 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
3933 obj->path, vn->vn_version);
3936 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
3938 vernum = VER_NEED_IDX(vna->vna_other);
3939 if (vernum > maxvernum)
3941 if (vna->vna_next == 0)
3943 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
3945 if (vn->vn_next == 0)
3947 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
3951 while (vd != NULL) {
3952 if (vd->vd_version != VER_DEF_CURRENT) {
3953 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
3954 obj->path, vd->vd_version);
3957 vernum = VER_DEF_IDX(vd->vd_ndx);
3958 if (vernum > maxvernum)
3960 if (vd->vd_next == 0)
3962 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3969 * Store version information in array indexable by version index.
3970 * Verify that object version requirements are satisfied along the
3973 obj->vernum = maxvernum + 1;
3974 obj->vertab = calloc(obj->vernum, sizeof(Ver_Entry));
3977 while (vd != NULL) {
3978 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
3979 vernum = VER_DEF_IDX(vd->vd_ndx);
3980 assert(vernum <= maxvernum);
3981 vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
3982 obj->vertab[vernum].hash = vd->vd_hash;
3983 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
3984 obj->vertab[vernum].file = NULL;
3985 obj->vertab[vernum].flags = 0;
3987 if (vd->vd_next == 0)
3989 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3993 while (vn != NULL) {
3994 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
3997 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
3999 if (check_object_provided_version(obj, depobj, vna))
4001 vernum = VER_NEED_IDX(vna->vna_other);
4002 assert(vernum <= maxvernum);
4003 obj->vertab[vernum].hash = vna->vna_hash;
4004 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
4005 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
4006 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
4007 VER_INFO_HIDDEN : 0;
4008 if (vna->vna_next == 0)
4010 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4012 if (vn->vn_next == 0)
4014 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4020 rtld_verify_versions(const Objlist *objlist)
4022 Objlist_Entry *entry;
4026 STAILQ_FOREACH(entry, objlist, link) {
4028 * Skip dummy objects or objects that have their version requirements
4031 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
4033 if (rtld_verify_object_versions(entry->obj) == -1) {
4035 if (ld_tracing == NULL)
4039 if (rc == 0 || ld_tracing != NULL)
4040 rc = rtld_verify_object_versions(&obj_rtld);
4045 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
4050 vernum = VER_NDX(obj->versyms[symnum]);
4051 if (vernum >= obj->vernum) {
4052 _rtld_error("%s: symbol %s has wrong verneed value %d",
4053 obj->path, obj->strtab + symnum, vernum);
4054 } else if (obj->vertab[vernum].hash != 0) {
4055 return &obj->vertab[vernum];
4062 _rtld_get_stack_prot(void)
4065 return (stack_prot);
4069 map_stacks_exec(RtldLockState *lockstate)
4071 void (*thr_map_stacks_exec)(void);
4073 if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
4075 thr_map_stacks_exec = (void (*)(void))(uintptr_t)
4076 get_program_var_addr("__pthread_map_stacks_exec", lockstate);
4077 if (thr_map_stacks_exec != NULL) {
4078 stack_prot |= PROT_EXEC;
4079 thr_map_stacks_exec();
4084 symlook_init(SymLook *dst, const char *name)
4087 bzero(dst, sizeof(*dst));
4089 dst->hash = elf_hash(name);
4093 symlook_init_from_req(SymLook *dst, const SymLook *src)
4096 dst->name = src->name;
4097 dst->hash = src->hash;
4098 dst->ventry = src->ventry;
4099 dst->flags = src->flags;
4100 dst->defobj_out = NULL;
4101 dst->sym_out = NULL;
4102 dst->lockstate = src->lockstate;
4106 * Overrides for libc_pic-provided functions.
4110 __getosreldate(void)
4120 oid[1] = KERN_OSRELDATE;
4122 len = sizeof(osrel);
4123 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
4124 if (error == 0 && osrel > 0 && len == sizeof(osrel))
4130 * No unresolved symbols for rtld.
4133 __pthread_cxa_finalize(struct dl_phdr_info *a)