2 * Copyright 1996, 1997, 1998, 1999, 2000 John D. Polstra.
3 * Copyright 2003 Alexander Kabaev <kan@FreeBSD.ORG>.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 * Dynamic linker for ELF.
32 * John Polstra <jdp@polstra.com>.
36 #error "GCC is needed to compile this file"
39 #include <sys/param.h>
40 #include <sys/mount.h>
44 #include <sys/utsname.h>
45 #include <sys/ktrace.h>
63 #define PATH_RTLD "/libexec/ld-elf.so.1"
65 #define PATH_RTLD "/libexec/ld-elf32.so.1"
69 typedef void (*func_ptr_type)();
70 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg);
73 * This structure provides a reentrant way to keep a list of objects and
74 * check which ones have already been processed in some way.
76 typedef struct Struct_DoneList {
77 const Obj_Entry **objs; /* Array of object pointers */
78 unsigned int num_alloc; /* Allocated size of the array */
79 unsigned int num_used; /* Number of array slots used */
83 * Function declarations.
85 static const char *basename(const char *);
86 static void die(void) __dead2;
87 static void digest_dynamic(Obj_Entry *, int);
88 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
89 static Obj_Entry *dlcheck(void *);
90 static Obj_Entry *do_load_object(int, const char *, char *, struct stat *, int);
91 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
92 static bool donelist_check(DoneList *, const Obj_Entry *);
93 static void errmsg_restore(char *);
94 static char *errmsg_save(void);
95 static void *fill_search_info(const char *, size_t, void *);
96 static char *find_library(const char *, const Obj_Entry *);
97 static const char *gethints(void);
98 static void init_dag(Obj_Entry *);
99 static void init_dag1(Obj_Entry *, Obj_Entry *, DoneList *);
100 static void init_rtld(caddr_t);
101 static void initlist_add_neededs(Needed_Entry *, Objlist *);
102 static void initlist_add_objects(Obj_Entry *, Obj_Entry **, Objlist *);
103 static bool is_exported(const Elf_Sym *);
104 static void linkmap_add(Obj_Entry *);
105 static void linkmap_delete(Obj_Entry *);
106 static int load_needed_objects(Obj_Entry *, int);
107 static int load_preload_objects(void);
108 static Obj_Entry *load_object(const char *, const Obj_Entry *, int);
109 static Obj_Entry *obj_from_addr(const void *);
110 static void objlist_call_fini(Objlist *, bool, int *);
111 static void objlist_call_init(Objlist *, int *);
112 static void objlist_clear(Objlist *);
113 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
114 static void objlist_init(Objlist *);
115 static void objlist_push_head(Objlist *, Obj_Entry *);
116 static void objlist_push_tail(Objlist *, Obj_Entry *);
117 static void objlist_remove(Objlist *, Obj_Entry *);
118 static void *path_enumerate(const char *, path_enum_proc, void *);
119 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *);
120 static int rtld_dirname(const char *, char *);
121 static int rtld_dirname_abs(const char *, char *);
122 static void rtld_exit(void);
123 static char *search_library_path(const char *, const char *);
124 static const void **get_program_var_addr(const char *);
125 static void set_program_var(const char *, const void *);
126 static const Elf_Sym *symlook_default(const char *, unsigned long,
127 const Obj_Entry *, const Obj_Entry **, const Ver_Entry *, int);
128 static const Elf_Sym *symlook_list(const char *, unsigned long, const Objlist *,
129 const Obj_Entry **, const Ver_Entry *, int, DoneList *);
130 static const Elf_Sym *symlook_needed(const char *, unsigned long,
131 const Needed_Entry *, const Obj_Entry **, const Ver_Entry *,
133 static void trace_loaded_objects(Obj_Entry *);
134 static void unlink_object(Obj_Entry *);
135 static void unload_object(Obj_Entry *);
136 static void unref_dag(Obj_Entry *);
137 static void ref_dag(Obj_Entry *);
138 static int origin_subst_one(char **, const char *, const char *,
139 const char *, char *);
140 static char *origin_subst(const char *, const char *);
141 static int rtld_verify_versions(const Objlist *);
142 static int rtld_verify_object_versions(Obj_Entry *);
143 static void object_add_name(Obj_Entry *, const char *);
144 static int object_match_name(const Obj_Entry *, const char *);
145 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
147 void r_debug_state(struct r_debug *, struct link_map *);
152 static char *error_message; /* Message for dlerror(), or NULL */
153 struct r_debug r_debug; /* for GDB; */
154 static bool libmap_disable; /* Disable libmap */
155 static char *libmap_override; /* Maps to use in addition to libmap.conf */
156 static bool trust; /* False for setuid and setgid programs */
157 static bool dangerous_ld_env; /* True if environment variables have been
158 used to affect the libraries loaded */
159 static char *ld_bind_now; /* Environment variable for immediate binding */
160 static char *ld_debug; /* Environment variable for debugging */
161 static char *ld_library_path; /* Environment variable for search path */
162 static char *ld_preload; /* Environment variable for libraries to
164 static char *ld_elf_hints_path; /* Environment variable for alternative hints path */
165 static char *ld_tracing; /* Called from ldd to print libs */
166 static char *ld_utrace; /* Use utrace() to log events. */
167 static Obj_Entry *obj_list; /* Head of linked list of shared objects */
168 static Obj_Entry **obj_tail; /* Link field of last object in list */
169 static Obj_Entry *obj_main; /* The main program shared object */
170 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
171 static unsigned int obj_count; /* Number of objects in obj_list */
172 static unsigned int obj_loads; /* Number of objects in obj_list */
174 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
175 STAILQ_HEAD_INITIALIZER(list_global);
176 static Objlist list_main = /* Objects loaded at program startup */
177 STAILQ_HEAD_INITIALIZER(list_main);
178 static Objlist list_fini = /* Objects needing fini() calls */
179 STAILQ_HEAD_INITIALIZER(list_fini);
181 static Elf_Sym sym_zero; /* For resolving undefined weak refs. */
183 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
185 extern Elf_Dyn _DYNAMIC;
186 #pragma weak _DYNAMIC
187 #ifndef RTLD_IS_DYNAMIC
188 #define RTLD_IS_DYNAMIC() (&_DYNAMIC != NULL)
192 * These are the functions the dynamic linker exports to application
193 * programs. They are the only symbols the dynamic linker is willing
194 * to export from itself.
196 static func_ptr_type exports[] = {
197 (func_ptr_type) &_rtld_error,
198 (func_ptr_type) &dlclose,
199 (func_ptr_type) &dlerror,
200 (func_ptr_type) &dlopen,
201 (func_ptr_type) &dlsym,
202 (func_ptr_type) &dlfunc,
203 (func_ptr_type) &dlvsym,
204 (func_ptr_type) &dladdr,
205 (func_ptr_type) &dllockinit,
206 (func_ptr_type) &dlinfo,
207 (func_ptr_type) &_rtld_thread_init,
209 (func_ptr_type) &___tls_get_addr,
211 (func_ptr_type) &__tls_get_addr,
212 (func_ptr_type) &_rtld_allocate_tls,
213 (func_ptr_type) &_rtld_free_tls,
214 (func_ptr_type) &dl_iterate_phdr,
215 (func_ptr_type) &_rtld_atfork_pre,
216 (func_ptr_type) &_rtld_atfork_post,
221 * Global declarations normally provided by crt1. The dynamic linker is
222 * not built with crt1, so we have to provide them ourselves.
228 * Globals to control TLS allocation.
230 size_t tls_last_offset; /* Static TLS offset of last module */
231 size_t tls_last_size; /* Static TLS size of last module */
232 size_t tls_static_space; /* Static TLS space allocated */
233 int tls_dtv_generation = 1; /* Used to detect when dtv size changes */
234 int tls_max_index = 1; /* Largest module index allocated */
237 * Fill in a DoneList with an allocation large enough to hold all of
238 * the currently-loaded objects. Keep this as a macro since it calls
239 * alloca and we want that to occur within the scope of the caller.
241 #define donelist_init(dlp) \
242 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
243 assert((dlp)->objs != NULL), \
244 (dlp)->num_alloc = obj_count, \
247 #define UTRACE_DLOPEN_START 1
248 #define UTRACE_DLOPEN_STOP 2
249 #define UTRACE_DLCLOSE_START 3
250 #define UTRACE_DLCLOSE_STOP 4
251 #define UTRACE_LOAD_OBJECT 5
252 #define UTRACE_UNLOAD_OBJECT 6
253 #define UTRACE_ADD_RUNDEP 7
254 #define UTRACE_PRELOAD_FINISHED 8
255 #define UTRACE_INIT_CALL 9
256 #define UTRACE_FINI_CALL 10
259 char sig[4]; /* 'RTLD' */
262 void *mapbase; /* Used for 'parent' and 'init/fini' */
264 int refcnt; /* Used for 'mode' */
265 char name[MAXPATHLEN];
268 #define LD_UTRACE(e, h, mb, ms, r, n) do { \
269 if (ld_utrace != NULL) \
270 ld_utrace_log(e, h, mb, ms, r, n); \
274 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
275 int refcnt, const char *name)
277 struct utrace_rtld ut;
285 ut.mapbase = mapbase;
286 ut.mapsize = mapsize;
288 bzero(ut.name, sizeof(ut.name));
290 strlcpy(ut.name, name, sizeof(ut.name));
291 utrace(&ut, sizeof(ut));
295 * Main entry point for dynamic linking. The first argument is the
296 * stack pointer. The stack is expected to be laid out as described
297 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
298 * Specifically, the stack pointer points to a word containing
299 * ARGC. Following that in the stack is a null-terminated sequence
300 * of pointers to argument strings. Then comes a null-terminated
301 * sequence of pointers to environment strings. Finally, there is a
302 * sequence of "auxiliary vector" entries.
304 * The second argument points to a place to store the dynamic linker's
305 * exit procedure pointer and the third to a place to store the main
308 * The return value is the main program's entry point.
311 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
313 Elf_Auxinfo *aux_info[AT_COUNT];
321 Objlist_Entry *entry;
323 Obj_Entry **preload_tail;
328 * On entry, the dynamic linker itself has not been relocated yet.
329 * Be very careful not to reference any global data until after
330 * init_rtld has returned. It is OK to reference file-scope statics
331 * and string constants, and to call static and global functions.
334 /* Find the auxiliary vector on the stack. */
337 sp += argc + 1; /* Skip over arguments and NULL terminator */
339 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
341 aux = (Elf_Auxinfo *) sp;
343 /* Digest the auxiliary vector. */
344 for (i = 0; i < AT_COUNT; i++)
346 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
347 if (auxp->a_type < AT_COUNT)
348 aux_info[auxp->a_type] = auxp;
351 /* Initialize and relocate ourselves. */
352 assert(aux_info[AT_BASE] != NULL);
353 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
355 __progname = obj_rtld.path;
356 argv0 = argv[0] != NULL ? argv[0] : "(null)";
359 trust = !issetugid();
361 ld_bind_now = getenv(LD_ "BIND_NOW");
363 * If the process is tainted, then we un-set the dangerous environment
364 * variables. The process will be marked as tainted until setuid(2)
365 * is called. If any child process calls setuid(2) we do not want any
366 * future processes to honor the potentially un-safe variables.
369 if (unsetenv(LD_ "PRELOAD") || unsetenv(LD_ "LIBMAP") ||
370 unsetenv(LD_ "LIBRARY_PATH") || unsetenv(LD_ "LIBMAP_DISABLE") ||
371 unsetenv(LD_ "DEBUG") || unsetenv(LD_ "ELF_HINTS_PATH")) {
372 _rtld_error("environment corrupt; aborting");
376 ld_debug = getenv(LD_ "DEBUG");
377 libmap_disable = getenv(LD_ "LIBMAP_DISABLE") != NULL;
378 libmap_override = getenv(LD_ "LIBMAP");
379 ld_library_path = getenv(LD_ "LIBRARY_PATH");
380 ld_preload = getenv(LD_ "PRELOAD");
381 ld_elf_hints_path = getenv(LD_ "ELF_HINTS_PATH");
382 dangerous_ld_env = libmap_disable || (libmap_override != NULL) ||
383 (ld_library_path != NULL) || (ld_preload != NULL) ||
384 (ld_elf_hints_path != NULL);
385 ld_tracing = getenv(LD_ "TRACE_LOADED_OBJECTS");
386 ld_utrace = getenv(LD_ "UTRACE");
388 if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0)
389 ld_elf_hints_path = _PATH_ELF_HINTS;
391 if (ld_debug != NULL && *ld_debug != '\0')
393 dbg("%s is initialized, base address = %p", __progname,
394 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
395 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
396 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
399 * Load the main program, or process its program header if it is
402 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
403 int fd = aux_info[AT_EXECFD]->a_un.a_val;
404 dbg("loading main program");
405 obj_main = map_object(fd, argv0, NULL);
407 if (obj_main == NULL)
409 } else { /* Main program already loaded. */
410 const Elf_Phdr *phdr;
414 dbg("processing main program's program header");
415 assert(aux_info[AT_PHDR] != NULL);
416 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
417 assert(aux_info[AT_PHNUM] != NULL);
418 phnum = aux_info[AT_PHNUM]->a_un.a_val;
419 assert(aux_info[AT_PHENT] != NULL);
420 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
421 assert(aux_info[AT_ENTRY] != NULL);
422 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
423 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
427 if (aux_info[AT_EXECPATH] != 0) {
429 char buf[MAXPATHLEN];
431 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
432 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
433 if (kexecpath[0] == '/')
434 obj_main->path = kexecpath;
435 else if (getcwd(buf, sizeof(buf)) == NULL ||
436 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
437 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
438 obj_main->path = xstrdup(argv0);
440 obj_main->path = xstrdup(buf);
442 dbg("No AT_EXECPATH");
443 obj_main->path = xstrdup(argv0);
445 dbg("obj_main path %s", obj_main->path);
446 obj_main->mainprog = true;
449 * Get the actual dynamic linker pathname from the executable if
450 * possible. (It should always be possible.) That ensures that
451 * gdb will find the right dynamic linker even if a non-standard
454 if (obj_main->interp != NULL &&
455 strcmp(obj_main->interp, obj_rtld.path) != 0) {
457 obj_rtld.path = xstrdup(obj_main->interp);
458 __progname = obj_rtld.path;
461 digest_dynamic(obj_main, 0);
463 linkmap_add(obj_main);
464 linkmap_add(&obj_rtld);
466 /* Link the main program into the list of objects. */
467 *obj_tail = obj_main;
468 obj_tail = &obj_main->next;
471 /* Make sure we don't call the main program's init and fini functions. */
472 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
474 /* Initialize a fake symbol for resolving undefined weak references. */
475 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
476 sym_zero.st_shndx = SHN_UNDEF;
477 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
480 libmap_disable = (bool)lm_init(libmap_override);
482 dbg("loading LD_PRELOAD libraries");
483 if (load_preload_objects() == -1)
485 preload_tail = obj_tail;
487 dbg("loading needed objects");
488 if (load_needed_objects(obj_main, 0) == -1)
491 /* Make a list of all objects loaded at startup. */
492 for (obj = obj_list; obj != NULL; obj = obj->next) {
493 objlist_push_tail(&list_main, obj);
497 dbg("checking for required versions");
498 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
501 if (ld_tracing) { /* We're done */
502 trace_loaded_objects(obj_main);
506 if (getenv(LD_ "DUMP_REL_PRE") != NULL) {
507 dump_relocations(obj_main);
511 /* setup TLS for main thread */
512 dbg("initializing initial thread local storage");
513 STAILQ_FOREACH(entry, &list_main, link) {
515 * Allocate all the initial objects out of the static TLS
516 * block even if they didn't ask for it.
518 allocate_tls_offset(entry->obj);
520 allocate_initial_tls(obj_list);
522 if (relocate_objects(obj_main,
523 ld_bind_now != NULL && *ld_bind_now != '\0', &obj_rtld) == -1)
526 dbg("doing copy relocations");
527 if (do_copy_relocations(obj_main) == -1)
530 if (getenv(LD_ "DUMP_REL_POST") != NULL) {
531 dump_relocations(obj_main);
535 dbg("initializing key program variables");
536 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
537 set_program_var("environ", env);
539 dbg("initializing thread locks");
542 /* Make a list of init functions to call. */
543 objlist_init(&initlist);
544 initlist_add_objects(obj_list, preload_tail, &initlist);
546 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
548 lockstate = wlock_acquire(rtld_bind_lock);
549 objlist_call_init(&initlist, &lockstate);
550 objlist_clear(&initlist);
551 wlock_release(rtld_bind_lock, lockstate);
553 dbg("transferring control to program entry point = %p", obj_main->entry);
555 /* Return the exit procedure and the program entry point. */
556 *exit_proc = rtld_exit;
558 return (func_ptr_type) obj_main->entry;
562 _rtld_bind(Obj_Entry *obj, Elf_Size reloff)
566 const Obj_Entry *defobj;
571 lockstate = rlock_acquire(rtld_bind_lock);
573 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
575 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
577 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
578 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL);
582 target = (Elf_Addr)(defobj->relocbase + def->st_value);
584 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
585 defobj->strtab + def->st_name, basename(obj->path),
586 (void *)target, basename(defobj->path));
589 * Write the new contents for the jmpslot. Note that depending on
590 * architecture, the value which we need to return back to the
591 * lazy binding trampoline may or may not be the target
592 * address. The value returned from reloc_jmpslot() is the value
593 * that the trampoline needs.
595 target = reloc_jmpslot(where, target, defobj, obj, rel);
596 rlock_release(rtld_bind_lock, lockstate);
601 * Error reporting function. Use it like printf. If formats the message
602 * into a buffer, and sets things up so that the next call to dlerror()
603 * will return the message.
606 _rtld_error(const char *fmt, ...)
608 static char buf[512];
612 vsnprintf(buf, sizeof buf, fmt, ap);
618 * Return a dynamically-allocated copy of the current error message, if any.
623 return error_message == NULL ? NULL : xstrdup(error_message);
627 * Restore the current error message from a copy which was previously saved
628 * by errmsg_save(). The copy is freed.
631 errmsg_restore(char *saved_msg)
633 if (saved_msg == NULL)
634 error_message = NULL;
636 _rtld_error("%s", saved_msg);
642 basename(const char *name)
644 const char *p = strrchr(name, '/');
645 return p != NULL ? p + 1 : name;
648 static struct utsname uts;
651 origin_subst_one(char **res, const char *real, const char *kw, const char *subst,
661 subst_len = kw_len = 0;
665 if (subst_len == 0) {
666 subst_len = strlen(subst);
670 *res = xmalloc(PATH_MAX);
673 if ((res1 - *res) + subst_len + (p1 - p) >= PATH_MAX) {
674 _rtld_error("Substitution of %s in %s cannot be performed",
676 if (may_free != NULL)
681 memcpy(res1, p, p1 - p);
683 memcpy(res1, subst, subst_len);
688 if (may_free != NULL)
691 *res = xstrdup(real);
695 if (may_free != NULL)
697 if (strlcat(res1, p, PATH_MAX - (res1 - *res)) >= PATH_MAX) {
707 origin_subst(const char *real, const char *origin_path)
709 char *res1, *res2, *res3, *res4;
711 if (uts.sysname[0] == '\0') {
712 if (uname(&uts) != 0) {
713 _rtld_error("utsname failed: %d", errno);
717 if (!origin_subst_one(&res1, real, "$ORIGIN", origin_path, NULL) ||
718 !origin_subst_one(&res2, res1, "$OSNAME", uts.sysname, res1) ||
719 !origin_subst_one(&res3, res2, "$OSREL", uts.release, res2) ||
720 !origin_subst_one(&res4, res3, "$PLATFORM", uts.machine, res3))
728 const char *msg = dlerror();
736 * Process a shared object's DYNAMIC section, and save the important
737 * information in its Obj_Entry structure.
740 digest_dynamic(Obj_Entry *obj, int early)
743 Needed_Entry **needed_tail = &obj->needed;
744 const Elf_Dyn *dyn_rpath = NULL;
745 const Elf_Dyn *dyn_soname = NULL;
746 int plttype = DT_REL;
748 obj->bind_now = false;
749 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
750 switch (dynp->d_tag) {
753 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
757 obj->relsize = dynp->d_un.d_val;
761 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
765 obj->pltrel = (const Elf_Rel *)
766 (obj->relocbase + dynp->d_un.d_ptr);
770 obj->pltrelsize = dynp->d_un.d_val;
774 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
778 obj->relasize = dynp->d_un.d_val;
782 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
786 plttype = dynp->d_un.d_val;
787 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
791 obj->symtab = (const Elf_Sym *)
792 (obj->relocbase + dynp->d_un.d_ptr);
796 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
800 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
804 obj->strsize = dynp->d_un.d_val;
808 obj->verneed = (const Elf_Verneed *) (obj->relocbase +
813 obj->verneednum = dynp->d_un.d_val;
817 obj->verdef = (const Elf_Verdef *) (obj->relocbase +
822 obj->verdefnum = dynp->d_un.d_val;
826 obj->versyms = (const Elf_Versym *)(obj->relocbase +
832 const Elf_Hashelt *hashtab = (const Elf_Hashelt *)
833 (obj->relocbase + dynp->d_un.d_ptr);
834 obj->nbuckets = hashtab[0];
835 obj->nchains = hashtab[1];
836 obj->buckets = hashtab + 2;
837 obj->chains = obj->buckets + obj->nbuckets;
843 Needed_Entry *nep = NEW(Needed_Entry);
844 nep->name = dynp->d_un.d_val;
849 needed_tail = &nep->next;
854 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
862 obj->symbolic = true;
866 case DT_RUNPATH: /* XXX: process separately */
868 * We have to wait until later to process this, because we
869 * might not have gotten the address of the string table yet.
879 obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
883 obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
887 * Don't process DT_DEBUG on MIPS as the dynamic section
888 * is mapped read-only. DT_MIPS_RLD_MAP is used instead.
893 /* XXX - not implemented yet */
895 dbg("Filling in DT_DEBUG entry");
896 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
901 if ((dynp->d_un.d_val & DF_ORIGIN) && trust)
902 obj->z_origin = true;
903 if (dynp->d_un.d_val & DF_SYMBOLIC)
904 obj->symbolic = true;
905 if (dynp->d_un.d_val & DF_TEXTREL)
907 if (dynp->d_un.d_val & DF_BIND_NOW)
908 obj->bind_now = true;
909 if (dynp->d_un.d_val & DF_STATIC_TLS)
913 case DT_MIPS_LOCAL_GOTNO:
914 obj->local_gotno = dynp->d_un.d_val;
917 case DT_MIPS_SYMTABNO:
918 obj->symtabno = dynp->d_un.d_val;
922 obj->gotsym = dynp->d_un.d_val;
925 case DT_MIPS_RLD_MAP:
928 dbg("Filling in DT_DEBUG entry");
929 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
935 if (dynp->d_un.d_val & DF_1_NOOPEN)
936 obj->z_noopen = true;
937 if ((dynp->d_un.d_val & DF_1_ORIGIN) && trust)
938 obj->z_origin = true;
939 if (dynp->d_un.d_val & DF_1_GLOBAL)
941 if (dynp->d_un.d_val & DF_1_BIND_NOW)
942 obj->bind_now = true;
943 if (dynp->d_un.d_val & DF_1_NODELETE)
944 obj->z_nodelete = true;
949 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
958 if (plttype == DT_RELA) {
959 obj->pltrela = (const Elf_Rela *) obj->pltrel;
961 obj->pltrelasize = obj->pltrelsize;
965 if (obj->z_origin && obj->origin_path == NULL) {
966 obj->origin_path = xmalloc(PATH_MAX);
967 if (rtld_dirname_abs(obj->path, obj->origin_path) == -1)
971 if (dyn_rpath != NULL) {
972 obj->rpath = (char *)obj->strtab + dyn_rpath->d_un.d_val;
974 obj->rpath = origin_subst(obj->rpath, obj->origin_path);
977 if (dyn_soname != NULL)
978 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
982 * Process a shared object's program header. This is used only for the
983 * main program, when the kernel has already loaded the main program
984 * into memory before calling the dynamic linker. It creates and
985 * returns an Obj_Entry structure.
988 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
991 const Elf_Phdr *phlimit = phdr + phnum;
996 for (ph = phdr; ph < phlimit; ph++) {
997 if (ph->p_type != PT_PHDR)
1001 obj->phsize = ph->p_memsz;
1002 obj->relocbase = (caddr_t)phdr - ph->p_vaddr;
1006 for (ph = phdr; ph < phlimit; ph++) {
1007 switch (ph->p_type) {
1010 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1014 if (nsegs == 0) { /* First load segment */
1015 obj->vaddrbase = trunc_page(ph->p_vaddr);
1016 obj->mapbase = obj->vaddrbase + obj->relocbase;
1017 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
1019 } else { /* Last load segment */
1020 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1027 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1032 obj->tlssize = ph->p_memsz;
1033 obj->tlsalign = ph->p_align;
1034 obj->tlsinitsize = ph->p_filesz;
1035 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1040 _rtld_error("%s: too few PT_LOAD segments", path);
1049 dlcheck(void *handle)
1053 for (obj = obj_list; obj != NULL; obj = obj->next)
1054 if (obj == (Obj_Entry *) handle)
1057 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1058 _rtld_error("Invalid shared object handle %p", handle);
1065 * If the given object is already in the donelist, return true. Otherwise
1066 * add the object to the list and return false.
1069 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1073 for (i = 0; i < dlp->num_used; i++)
1074 if (dlp->objs[i] == obj)
1077 * Our donelist allocation should always be sufficient. But if
1078 * our threads locking isn't working properly, more shared objects
1079 * could have been loaded since we allocated the list. That should
1080 * never happen, but we'll handle it properly just in case it does.
1082 if (dlp->num_used < dlp->num_alloc)
1083 dlp->objs[dlp->num_used++] = obj;
1088 * Hash function for symbol table lookup. Don't even think about changing
1089 * this. It is specified by the System V ABI.
1092 elf_hash(const char *name)
1094 const unsigned char *p = (const unsigned char *) name;
1095 unsigned long h = 0;
1098 while (*p != '\0') {
1099 h = (h << 4) + *p++;
1100 if ((g = h & 0xf0000000) != 0)
1108 * Find the library with the given name, and return its full pathname.
1109 * The returned string is dynamically allocated. Generates an error
1110 * message and returns NULL if the library cannot be found.
1112 * If the second argument is non-NULL, then it refers to an already-
1113 * loaded shared object, whose library search path will be searched.
1115 * The search order is:
1117 * rpath in the referencing file
1122 find_library(const char *xname, const Obj_Entry *refobj)
1127 if (strchr(xname, '/') != NULL) { /* Hard coded pathname */
1128 if (xname[0] != '/' && !trust) {
1129 _rtld_error("Absolute pathname required for shared object \"%s\"",
1133 if (refobj != NULL && refobj->z_origin)
1134 return origin_subst(xname, refobj->origin_path);
1136 return xstrdup(xname);
1139 if (libmap_disable || (refobj == NULL) ||
1140 (name = lm_find(refobj->path, xname)) == NULL)
1141 name = (char *)xname;
1143 dbg(" Searching for \"%s\"", name);
1145 if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
1147 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
1148 (pathname = search_library_path(name, gethints())) != NULL ||
1149 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
1152 if(refobj != NULL && refobj->path != NULL) {
1153 _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
1154 name, basename(refobj->path));
1156 _rtld_error("Shared object \"%s\" not found", name);
1162 * Given a symbol number in a referencing object, find the corresponding
1163 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1164 * no definition was found. Returns a pointer to the Obj_Entry of the
1165 * defining object via the reference parameter DEFOBJ_OUT.
1168 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1169 const Obj_Entry **defobj_out, int flags, SymCache *cache)
1173 const Obj_Entry *defobj;
1174 const Ver_Entry *ventry;
1179 * If we have already found this symbol, get the information from
1182 if (symnum >= refobj->nchains)
1183 return NULL; /* Bad object */
1184 if (cache != NULL && cache[symnum].sym != NULL) {
1185 *defobj_out = cache[symnum].obj;
1186 return cache[symnum].sym;
1189 ref = refobj->symtab + symnum;
1190 name = refobj->strtab + ref->st_name;
1194 * We don't have to do a full scale lookup if the symbol is local.
1195 * We know it will bind to the instance in this load module; to
1196 * which we already have a pointer (ie ref). By not doing a lookup,
1197 * we not only improve performance, but it also avoids unresolvable
1198 * symbols when local symbols are not in the hash table. This has
1199 * been seen with the ia64 toolchain.
1201 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1202 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1203 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1206 ventry = fetch_ventry(refobj, symnum);
1207 hash = elf_hash(name);
1208 def = symlook_default(name, hash, refobj, &defobj, ventry, flags);
1215 * If we found no definition and the reference is weak, treat the
1216 * symbol as having the value zero.
1218 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1224 *defobj_out = defobj;
1225 /* Record the information in the cache to avoid subsequent lookups. */
1226 if (cache != NULL) {
1227 cache[symnum].sym = def;
1228 cache[symnum].obj = defobj;
1231 if (refobj != &obj_rtld)
1232 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1238 * Return the search path from the ldconfig hints file, reading it if
1239 * necessary. Returns NULL if there are problems with the hints file,
1240 * or if the search path there is empty.
1247 if (hints == NULL) {
1249 struct elfhints_hdr hdr;
1252 /* Keep from trying again in case the hints file is bad. */
1255 if ((fd = open(ld_elf_hints_path, O_RDONLY)) == -1)
1257 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1258 hdr.magic != ELFHINTS_MAGIC ||
1263 p = xmalloc(hdr.dirlistlen + 1);
1264 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1265 read(fd, p, hdr.dirlistlen + 1) != (ssize_t)hdr.dirlistlen + 1) {
1273 return hints[0] != '\0' ? hints : NULL;
1277 init_dag(Obj_Entry *root)
1281 if (root->dag_inited)
1283 donelist_init(&donelist);
1284 init_dag1(root, root, &donelist);
1285 root->dag_inited = true;
1289 init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *dlp)
1291 const Needed_Entry *needed;
1293 if (donelist_check(dlp, obj))
1296 objlist_push_tail(&obj->dldags, root);
1297 objlist_push_tail(&root->dagmembers, obj);
1298 for (needed = obj->needed; needed != NULL; needed = needed->next)
1299 if (needed->obj != NULL)
1300 init_dag1(root, needed->obj, dlp);
1304 * Initialize the dynamic linker. The argument is the address at which
1305 * the dynamic linker has been mapped into memory. The primary task of
1306 * this function is to relocate the dynamic linker.
1309 init_rtld(caddr_t mapbase)
1311 Obj_Entry objtmp; /* Temporary rtld object */
1314 * Conjure up an Obj_Entry structure for the dynamic linker.
1316 * The "path" member can't be initialized yet because string constants
1317 * cannot yet be accessed. Below we will set it correctly.
1319 memset(&objtmp, 0, sizeof(objtmp));
1322 objtmp.mapbase = mapbase;
1324 objtmp.relocbase = mapbase;
1326 if (RTLD_IS_DYNAMIC()) {
1327 objtmp.dynamic = rtld_dynamic(&objtmp);
1328 digest_dynamic(&objtmp, 1);
1329 assert(objtmp.needed == NULL);
1330 #if !defined(__mips__)
1331 /* MIPS and SH{3,5} have a bogus DT_TEXTREL. */
1332 assert(!objtmp.textrel);
1336 * Temporarily put the dynamic linker entry into the object list, so
1337 * that symbols can be found.
1340 relocate_objects(&objtmp, true, &objtmp);
1343 /* Initialize the object list. */
1344 obj_tail = &obj_list;
1346 /* Now that non-local variables can be accesses, copy out obj_rtld. */
1347 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1349 /* Replace the path with a dynamically allocated copy. */
1350 obj_rtld.path = xstrdup(PATH_RTLD);
1352 r_debug.r_brk = r_debug_state;
1353 r_debug.r_state = RT_CONSISTENT;
1357 * Add the init functions from a needed object list (and its recursive
1358 * needed objects) to "list". This is not used directly; it is a helper
1359 * function for initlist_add_objects(). The write lock must be held
1360 * when this function is called.
1363 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1365 /* Recursively process the successor needed objects. */
1366 if (needed->next != NULL)
1367 initlist_add_neededs(needed->next, list);
1369 /* Process the current needed object. */
1370 if (needed->obj != NULL)
1371 initlist_add_objects(needed->obj, &needed->obj->next, list);
1375 * Scan all of the DAGs rooted in the range of objects from "obj" to
1376 * "tail" and add their init functions to "list". This recurses over
1377 * the DAGs and ensure the proper init ordering such that each object's
1378 * needed libraries are initialized before the object itself. At the
1379 * same time, this function adds the objects to the global finalization
1380 * list "list_fini" in the opposite order. The write lock must be
1381 * held when this function is called.
1384 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1386 if (obj->init_scanned || obj->init_done)
1388 obj->init_scanned = true;
1390 /* Recursively process the successor objects. */
1391 if (&obj->next != tail)
1392 initlist_add_objects(obj->next, tail, list);
1394 /* Recursively process the needed objects. */
1395 if (obj->needed != NULL)
1396 initlist_add_neededs(obj->needed, list);
1398 /* Add the object to the init list. */
1399 if (obj->init != (Elf_Addr)NULL)
1400 objlist_push_tail(list, obj);
1402 /* Add the object to the global fini list in the reverse order. */
1403 if (obj->fini != (Elf_Addr)NULL && !obj->on_fini_list) {
1404 objlist_push_head(&list_fini, obj);
1405 obj->on_fini_list = true;
1410 #define FPTR_TARGET(f) ((Elf_Addr) (f))
1414 is_exported(const Elf_Sym *def)
1417 const func_ptr_type *p;
1419 value = (Elf_Addr)(obj_rtld.relocbase + def->st_value);
1420 for (p = exports; *p != NULL; p++)
1421 if (FPTR_TARGET(*p) == value)
1427 * Given a shared object, traverse its list of needed objects, and load
1428 * each of them. Returns 0 on success. Generates an error message and
1429 * returns -1 on failure.
1432 load_needed_objects(Obj_Entry *first, int flags)
1434 Obj_Entry *obj, *obj1;
1436 for (obj = first; obj != NULL; obj = obj->next) {
1437 Needed_Entry *needed;
1439 for (needed = obj->needed; needed != NULL; needed = needed->next) {
1440 obj1 = needed->obj = load_object(obj->strtab + needed->name, obj,
1441 flags & ~RTLD_LO_NOLOAD);
1442 if (obj1 == NULL && !ld_tracing)
1444 if (obj1 != NULL && obj1->z_nodelete && !obj1->ref_nodel) {
1445 dbg("obj %s nodelete", obj1->path);
1448 obj1->ref_nodel = true;
1457 load_preload_objects(void)
1459 char *p = ld_preload;
1460 static const char delim[] = " \t:;";
1465 p += strspn(p, delim);
1466 while (*p != '\0') {
1467 size_t len = strcspn(p, delim);
1472 if (load_object(p, NULL, 0) == NULL)
1473 return -1; /* XXX - cleanup */
1476 p += strspn(p, delim);
1478 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
1483 * Load a shared object into memory, if it is not already loaded.
1485 * Returns a pointer to the Obj_Entry for the object. Returns NULL
1489 load_object(const char *name, const Obj_Entry *refobj, int flags)
1496 for (obj = obj_list->next; obj != NULL; obj = obj->next)
1497 if (object_match_name(obj, name))
1500 path = find_library(name, refobj);
1505 * If we didn't find a match by pathname, open the file and check
1506 * again by device and inode. This avoids false mismatches caused
1507 * by multiple links or ".." in pathnames.
1509 * To avoid a race, we open the file and use fstat() rather than
1512 if ((fd = open(path, O_RDONLY)) == -1) {
1513 _rtld_error("Cannot open \"%s\"", path);
1517 if (fstat(fd, &sb) == -1) {
1518 _rtld_error("Cannot fstat \"%s\"", path);
1523 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
1524 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev) {
1530 object_add_name(obj, name);
1535 if (flags & RTLD_LO_NOLOAD) {
1540 /* First use of this object, so we must map it in */
1541 obj = do_load_object(fd, name, path, &sb, flags);
1550 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
1557 * but first, make sure that environment variables haven't been
1558 * used to circumvent the noexec flag on a filesystem.
1560 if (dangerous_ld_env) {
1561 if (fstatfs(fd, &fs) != 0) {
1562 _rtld_error("Cannot fstatfs \"%s\"", path);
1565 if (fs.f_flags & MNT_NOEXEC) {
1566 _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
1570 dbg("loading \"%s\"", path);
1571 obj = map_object(fd, path, sbp);
1575 object_add_name(obj, name);
1577 digest_dynamic(obj, 0);
1578 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
1580 dbg("refusing to load non-loadable \"%s\"", obj->path);
1581 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
1582 munmap(obj->mapbase, obj->mapsize);
1588 obj_tail = &obj->next;
1591 linkmap_add(obj); /* for GDB & dlinfo() */
1593 dbg(" %p .. %p: %s", obj->mapbase,
1594 obj->mapbase + obj->mapsize - 1, obj->path);
1596 dbg(" WARNING: %s has impure text", obj->path);
1597 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
1604 obj_from_addr(const void *addr)
1608 for (obj = obj_list; obj != NULL; obj = obj->next) {
1609 if (addr < (void *) obj->mapbase)
1611 if (addr < (void *) (obj->mapbase + obj->mapsize))
1618 * Call the finalization functions for each of the objects in "list"
1619 * which are unreferenced. All of the objects are expected to have
1620 * non-NULL fini functions.
1623 objlist_call_fini(Objlist *list, bool force, int *lockstate)
1625 Objlist_Entry *elm, *elm_tmp;
1629 * Preserve the current error message since a fini function might
1630 * call into the dynamic linker and overwrite it.
1632 saved_msg = errmsg_save();
1633 STAILQ_FOREACH_SAFE(elm, list, link, elm_tmp) {
1634 if (elm->obj->refcount == 0 || force) {
1635 dbg("calling fini function for %s at %p", elm->obj->path,
1636 (void *)elm->obj->fini);
1637 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini, 0, 0,
1639 /* Remove object from fini list to prevent recursive invocation. */
1640 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1641 wlock_release(rtld_bind_lock, *lockstate);
1642 call_initfini_pointer(elm->obj, elm->obj->fini);
1643 *lockstate = wlock_acquire(rtld_bind_lock);
1644 /* No need to free anything if process is going down. */
1649 errmsg_restore(saved_msg);
1653 * Call the initialization functions for each of the objects in
1654 * "list". All of the objects are expected to have non-NULL init
1658 objlist_call_init(Objlist *list, int *lockstate)
1665 * Clean init_scanned flag so that objects can be rechecked and
1666 * possibly initialized earlier if any of vectors called below
1667 * cause the change by using dlopen.
1669 for (obj = obj_list; obj != NULL; obj = obj->next)
1670 obj->init_scanned = false;
1673 * Preserve the current error message since an init function might
1674 * call into the dynamic linker and overwrite it.
1676 saved_msg = errmsg_save();
1677 STAILQ_FOREACH(elm, list, link) {
1678 if (elm->obj->init_done) /* Initialized early. */
1680 dbg("calling init function for %s at %p", elm->obj->path,
1681 (void *)elm->obj->init);
1682 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init, 0, 0,
1685 * Race: other thread might try to use this object before current
1686 * one completes the initilization. Not much can be done here
1687 * without better locking.
1689 elm->obj->init_done = true;
1690 wlock_release(rtld_bind_lock, *lockstate);
1691 call_initfini_pointer(elm->obj, elm->obj->init);
1692 *lockstate = wlock_acquire(rtld_bind_lock);
1694 errmsg_restore(saved_msg);
1698 objlist_clear(Objlist *list)
1702 while (!STAILQ_EMPTY(list)) {
1703 elm = STAILQ_FIRST(list);
1704 STAILQ_REMOVE_HEAD(list, link);
1709 static Objlist_Entry *
1710 objlist_find(Objlist *list, const Obj_Entry *obj)
1714 STAILQ_FOREACH(elm, list, link)
1715 if (elm->obj == obj)
1721 objlist_init(Objlist *list)
1727 objlist_push_head(Objlist *list, Obj_Entry *obj)
1731 elm = NEW(Objlist_Entry);
1733 STAILQ_INSERT_HEAD(list, elm, link);
1737 objlist_push_tail(Objlist *list, Obj_Entry *obj)
1741 elm = NEW(Objlist_Entry);
1743 STAILQ_INSERT_TAIL(list, elm, link);
1747 objlist_remove(Objlist *list, Obj_Entry *obj)
1751 if ((elm = objlist_find(list, obj)) != NULL) {
1752 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1758 * Relocate newly-loaded shared objects. The argument is a pointer to
1759 * the Obj_Entry for the first such object. All objects from the first
1760 * to the end of the list of objects are relocated. Returns 0 on success,
1764 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj)
1768 for (obj = first; obj != NULL; obj = obj->next) {
1770 dbg("relocating \"%s\"", obj->path);
1771 if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
1772 obj->symtab == NULL || obj->strtab == NULL) {
1773 _rtld_error("%s: Shared object has no run-time symbol table",
1779 /* There are relocations to the write-protected text segment. */
1780 if (mprotect(obj->mapbase, obj->textsize,
1781 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
1782 _rtld_error("%s: Cannot write-enable text segment: %s",
1783 obj->path, strerror(errno));
1788 /* Process the non-PLT relocations. */
1789 if (reloc_non_plt(obj, rtldobj))
1792 if (obj->textrel) { /* Re-protected the text segment. */
1793 if (mprotect(obj->mapbase, obj->textsize,
1794 PROT_READ|PROT_EXEC) == -1) {
1795 _rtld_error("%s: Cannot write-protect text segment: %s",
1796 obj->path, strerror(errno));
1801 /* Process the PLT relocations. */
1802 if (reloc_plt(obj) == -1)
1804 /* Relocate the jump slots if we are doing immediate binding. */
1805 if (obj->bind_now || bind_now)
1806 if (reloc_jmpslots(obj) == -1)
1811 * Set up the magic number and version in the Obj_Entry. These
1812 * were checked in the crt1.o from the original ElfKit, so we
1813 * set them for backward compatibility.
1815 obj->magic = RTLD_MAGIC;
1816 obj->version = RTLD_VERSION;
1818 /* Set the special PLT or GOT entries. */
1826 * Cleanup procedure. It will be called (by the atexit mechanism) just
1827 * before the process exits.
1834 lockstate = wlock_acquire(rtld_bind_lock);
1836 objlist_call_fini(&list_fini, true, &lockstate);
1837 /* No need to remove the items from the list, since we are exiting. */
1838 if (!libmap_disable)
1840 wlock_release(rtld_bind_lock, lockstate);
1844 path_enumerate(const char *path, path_enum_proc callback, void *arg)
1852 path += strspn(path, ":;");
1853 while (*path != '\0') {
1857 len = strcspn(path, ":;");
1859 trans = lm_findn(NULL, path, len);
1861 res = callback(trans, strlen(trans), arg);
1864 res = callback(path, len, arg);
1870 path += strspn(path, ":;");
1876 struct try_library_args {
1884 try_library_path(const char *dir, size_t dirlen, void *param)
1886 struct try_library_args *arg;
1889 if (*dir == '/' || trust) {
1892 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
1895 pathname = arg->buffer;
1896 strncpy(pathname, dir, dirlen);
1897 pathname[dirlen] = '/';
1898 strcpy(pathname + dirlen + 1, arg->name);
1900 dbg(" Trying \"%s\"", pathname);
1901 if (access(pathname, F_OK) == 0) { /* We found it */
1902 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
1903 strcpy(pathname, arg->buffer);
1911 search_library_path(const char *name, const char *path)
1914 struct try_library_args arg;
1920 arg.namelen = strlen(name);
1921 arg.buffer = xmalloc(PATH_MAX);
1922 arg.buflen = PATH_MAX;
1924 p = path_enumerate(path, try_library_path, &arg);
1932 dlclose(void *handle)
1937 lockstate = wlock_acquire(rtld_bind_lock);
1938 root = dlcheck(handle);
1940 wlock_release(rtld_bind_lock, lockstate);
1943 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
1946 /* Unreference the object and its dependencies. */
1947 root->dl_refcount--;
1951 if (root->refcount == 0) {
1953 * The object is no longer referenced, so we must unload it.
1954 * First, call the fini functions.
1956 objlist_call_fini(&list_fini, false, &lockstate);
1958 /* Finish cleaning up the newly-unreferenced objects. */
1959 GDB_STATE(RT_DELETE,&root->linkmap);
1960 unload_object(root);
1961 GDB_STATE(RT_CONSISTENT,NULL);
1963 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
1964 wlock_release(rtld_bind_lock, lockstate);
1971 char *msg = error_message;
1972 error_message = NULL;
1977 * This function is deprecated and has no effect.
1980 dllockinit(void *context,
1981 void *(*lock_create)(void *context),
1982 void (*rlock_acquire)(void *lock),
1983 void (*wlock_acquire)(void *lock),
1984 void (*lock_release)(void *lock),
1985 void (*lock_destroy)(void *lock),
1986 void (*context_destroy)(void *context))
1988 static void *cur_context;
1989 static void (*cur_context_destroy)(void *);
1991 /* Just destroy the context from the previous call, if necessary. */
1992 if (cur_context_destroy != NULL)
1993 cur_context_destroy(cur_context);
1994 cur_context = context;
1995 cur_context_destroy = context_destroy;
1999 dlopen(const char *name, int mode)
2001 Obj_Entry **old_obj_tail;
2004 int result, lockstate, nodelete, lo_flags;
2006 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
2007 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
2008 if (ld_tracing != NULL)
2009 environ = (char **)*get_program_var_addr("environ");
2010 nodelete = mode & RTLD_NODELETE;
2011 lo_flags = RTLD_LO_DLOPEN;
2012 if (mode & RTLD_NOLOAD)
2013 lo_flags |= RTLD_LO_NOLOAD;
2014 if (ld_tracing != NULL)
2015 lo_flags |= RTLD_LO_TRACE;
2017 objlist_init(&initlist);
2019 lockstate = wlock_acquire(rtld_bind_lock);
2020 GDB_STATE(RT_ADD,NULL);
2022 old_obj_tail = obj_tail;
2028 obj = load_object(name, obj_main, lo_flags);
2033 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
2034 objlist_push_tail(&list_global, obj);
2035 mode &= RTLD_MODEMASK;
2036 if (*old_obj_tail != NULL) { /* We loaded something new. */
2037 assert(*old_obj_tail == obj);
2038 result = load_needed_objects(obj, RTLD_LO_DLOPEN);
2042 result = rtld_verify_versions(&obj->dagmembers);
2043 if (result != -1 && ld_tracing)
2046 (relocate_objects(obj, mode == RTLD_NOW, &obj_rtld)) == -1) {
2049 if (obj->refcount == 0)
2053 /* Make list of init functions to call. */
2054 initlist_add_objects(obj, &obj->next, &initlist);
2059 * Bump the reference counts for objects on this DAG. If
2060 * this is the first dlopen() call for the object that was
2061 * already loaded as a dependency, initialize the dag
2070 if (obj != NULL && (nodelete || obj->z_nodelete) && !obj->ref_nodel) {
2071 dbg("obj %s nodelete", obj->path);
2073 obj->z_nodelete = obj->ref_nodel = true;
2077 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
2079 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
2081 /* Call the init functions. */
2082 objlist_call_init(&initlist, &lockstate);
2083 objlist_clear(&initlist);
2084 wlock_release(rtld_bind_lock, lockstate);
2087 trace_loaded_objects(obj);
2088 wlock_release(rtld_bind_lock, lockstate);
2093 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
2097 const Obj_Entry *obj, *defobj;
2098 const Elf_Sym *def, *symp;
2102 hash = elf_hash(name);
2105 flags |= SYMLOOK_IN_PLT;
2107 lockstate = rlock_acquire(rtld_bind_lock);
2108 if (handle == NULL || handle == RTLD_NEXT ||
2109 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
2111 if ((obj = obj_from_addr(retaddr)) == NULL) {
2112 _rtld_error("Cannot determine caller's shared object");
2113 rlock_release(rtld_bind_lock, lockstate);
2116 if (handle == NULL) { /* Just the caller's shared object. */
2117 def = symlook_obj(name, hash, obj, ve, flags);
2119 } else if (handle == RTLD_NEXT || /* Objects after caller's */
2120 handle == RTLD_SELF) { /* ... caller included */
2121 if (handle == RTLD_NEXT)
2123 for (; obj != NULL; obj = obj->next) {
2124 if ((symp = symlook_obj(name, hash, obj, ve, flags)) != NULL) {
2125 if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
2128 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2134 * Search the dynamic linker itself, and possibly resolve the
2135 * symbol from there. This is how the application links to
2136 * dynamic linker services such as dlopen. Only the values listed
2137 * in the "exports" array can be resolved from the dynamic linker.
2139 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2140 symp = symlook_obj(name, hash, &obj_rtld, ve, flags);
2141 if (symp != NULL && is_exported(symp)) {
2147 assert(handle == RTLD_DEFAULT);
2148 def = symlook_default(name, hash, obj, &defobj, ve, flags);
2151 if ((obj = dlcheck(handle)) == NULL) {
2152 rlock_release(rtld_bind_lock, lockstate);
2156 donelist_init(&donelist);
2157 if (obj->mainprog) {
2158 /* Search main program and all libraries loaded by it. */
2159 def = symlook_list(name, hash, &list_main, &defobj, ve, flags,
2163 * We do not distinguish between 'main' object and global scope.
2164 * If symbol is not defined by objects loaded at startup, continue
2165 * search among dynamically loaded objects with RTLD_GLOBAL
2169 def = symlook_list(name, hash, &list_global, &defobj, ve,
2174 /* Search the whole DAG rooted at the given object. */
2176 fake.obj = (Obj_Entry *)obj;
2178 def = symlook_needed(name, hash, &fake, &defobj, ve, flags,
2184 rlock_release(rtld_bind_lock, lockstate);
2187 * The value required by the caller is derived from the value
2188 * of the symbol. For the ia64 architecture, we need to
2189 * construct a function descriptor which the caller can use to
2190 * call the function with the right 'gp' value. For other
2191 * architectures and for non-functions, the value is simply
2192 * the relocated value of the symbol.
2194 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
2195 return make_function_pointer(def, defobj);
2197 return defobj->relocbase + def->st_value;
2200 _rtld_error("Undefined symbol \"%s\"", name);
2201 rlock_release(rtld_bind_lock, lockstate);
2206 dlsym(void *handle, const char *name)
2208 return do_dlsym(handle, name, __builtin_return_address(0), NULL,
2213 dlfunc(void *handle, const char *name)
2220 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
2226 dlvsym(void *handle, const char *name, const char *version)
2230 ventry.name = version;
2232 ventry.hash = elf_hash(version);
2234 return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
2239 dladdr(const void *addr, Dl_info *info)
2241 const Obj_Entry *obj;
2244 unsigned long symoffset;
2247 lockstate = rlock_acquire(rtld_bind_lock);
2248 obj = obj_from_addr(addr);
2250 _rtld_error("No shared object contains address");
2251 rlock_release(rtld_bind_lock, lockstate);
2254 info->dli_fname = obj->path;
2255 info->dli_fbase = obj->mapbase;
2256 info->dli_saddr = (void *)0;
2257 info->dli_sname = NULL;
2260 * Walk the symbol list looking for the symbol whose address is
2261 * closest to the address sent in.
2263 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
2264 def = obj->symtab + symoffset;
2267 * For skip the symbol if st_shndx is either SHN_UNDEF or
2270 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
2274 * If the symbol is greater than the specified address, or if it
2275 * is further away from addr than the current nearest symbol,
2278 symbol_addr = obj->relocbase + def->st_value;
2279 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
2282 /* Update our idea of the nearest symbol. */
2283 info->dli_sname = obj->strtab + def->st_name;
2284 info->dli_saddr = symbol_addr;
2287 if (info->dli_saddr == addr)
2290 rlock_release(rtld_bind_lock, lockstate);
2295 dlinfo(void *handle, int request, void *p)
2297 const Obj_Entry *obj;
2298 int error, lockstate;
2300 lockstate = rlock_acquire(rtld_bind_lock);
2302 if (handle == NULL || handle == RTLD_SELF) {
2305 retaddr = __builtin_return_address(0); /* __GNUC__ only */
2306 if ((obj = obj_from_addr(retaddr)) == NULL)
2307 _rtld_error("Cannot determine caller's shared object");
2309 obj = dlcheck(handle);
2312 rlock_release(rtld_bind_lock, lockstate);
2318 case RTLD_DI_LINKMAP:
2319 *((struct link_map const **)p) = &obj->linkmap;
2321 case RTLD_DI_ORIGIN:
2322 error = rtld_dirname(obj->path, p);
2325 case RTLD_DI_SERINFOSIZE:
2326 case RTLD_DI_SERINFO:
2327 error = do_search_info(obj, request, (struct dl_serinfo *)p);
2331 _rtld_error("Invalid request %d passed to dlinfo()", request);
2335 rlock_release(rtld_bind_lock, lockstate);
2341 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
2343 struct dl_phdr_info phdr_info;
2344 const Obj_Entry *obj;
2345 int error, bind_lockstate, phdr_lockstate;
2347 phdr_lockstate = wlock_acquire(rtld_phdr_lock);
2348 bind_lockstate = rlock_acquire(rtld_bind_lock);
2352 for (obj = obj_list; obj != NULL; obj = obj->next) {
2353 phdr_info.dlpi_addr = (Elf_Addr)obj->relocbase;
2354 phdr_info.dlpi_name = STAILQ_FIRST(&obj->names) ?
2355 STAILQ_FIRST(&obj->names)->name : obj->path;
2356 phdr_info.dlpi_phdr = obj->phdr;
2357 phdr_info.dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
2358 phdr_info.dlpi_tls_modid = obj->tlsindex;
2359 phdr_info.dlpi_tls_data = obj->tlsinit;
2360 phdr_info.dlpi_adds = obj_loads;
2361 phdr_info.dlpi_subs = obj_loads - obj_count;
2363 if ((error = callback(&phdr_info, sizeof phdr_info, param)) != 0)
2367 rlock_release(rtld_bind_lock, bind_lockstate);
2368 wlock_release(rtld_phdr_lock, phdr_lockstate);
2373 struct fill_search_info_args {
2376 Dl_serinfo *serinfo;
2377 Dl_serpath *serpath;
2382 fill_search_info(const char *dir, size_t dirlen, void *param)
2384 struct fill_search_info_args *arg;
2388 if (arg->request == RTLD_DI_SERINFOSIZE) {
2389 arg->serinfo->dls_cnt ++;
2390 arg->serinfo->dls_size += sizeof(Dl_serpath) + dirlen + 1;
2392 struct dl_serpath *s_entry;
2394 s_entry = arg->serpath;
2395 s_entry->dls_name = arg->strspace;
2396 s_entry->dls_flags = arg->flags;
2398 strncpy(arg->strspace, dir, dirlen);
2399 arg->strspace[dirlen] = '\0';
2401 arg->strspace += dirlen + 1;
2409 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
2411 struct dl_serinfo _info;
2412 struct fill_search_info_args args;
2414 args.request = RTLD_DI_SERINFOSIZE;
2415 args.serinfo = &_info;
2417 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2420 path_enumerate(ld_library_path, fill_search_info, &args);
2421 path_enumerate(obj->rpath, fill_search_info, &args);
2422 path_enumerate(gethints(), fill_search_info, &args);
2423 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
2426 if (request == RTLD_DI_SERINFOSIZE) {
2427 info->dls_size = _info.dls_size;
2428 info->dls_cnt = _info.dls_cnt;
2432 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
2433 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
2437 args.request = RTLD_DI_SERINFO;
2438 args.serinfo = info;
2439 args.serpath = &info->dls_serpath[0];
2440 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
2442 args.flags = LA_SER_LIBPATH;
2443 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
2446 args.flags = LA_SER_RUNPATH;
2447 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
2450 args.flags = LA_SER_CONFIG;
2451 if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
2454 args.flags = LA_SER_DEFAULT;
2455 if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
2461 rtld_dirname(const char *path, char *bname)
2465 /* Empty or NULL string gets treated as "." */
2466 if (path == NULL || *path == '\0') {
2472 /* Strip trailing slashes */
2473 endp = path + strlen(path) - 1;
2474 while (endp > path && *endp == '/')
2477 /* Find the start of the dir */
2478 while (endp > path && *endp != '/')
2481 /* Either the dir is "/" or there are no slashes */
2483 bname[0] = *endp == '/' ? '/' : '.';
2489 } while (endp > path && *endp == '/');
2492 if (endp - path + 2 > PATH_MAX)
2494 _rtld_error("Filename is too long: %s", path);
2498 strncpy(bname, path, endp - path + 1);
2499 bname[endp - path + 1] = '\0';
2504 rtld_dirname_abs(const char *path, char *base)
2506 char base_rel[PATH_MAX];
2508 if (rtld_dirname(path, base) == -1)
2512 if (getcwd(base_rel, sizeof(base_rel)) == NULL ||
2513 strlcat(base_rel, "/", sizeof(base_rel)) >= sizeof(base_rel) ||
2514 strlcat(base_rel, base, sizeof(base_rel)) >= sizeof(base_rel))
2516 strcpy(base, base_rel);
2521 linkmap_add(Obj_Entry *obj)
2523 struct link_map *l = &obj->linkmap;
2524 struct link_map *prev;
2526 obj->linkmap.l_name = obj->path;
2527 obj->linkmap.l_addr = obj->mapbase;
2528 obj->linkmap.l_ld = obj->dynamic;
2530 /* GDB needs load offset on MIPS to use the symbols */
2531 obj->linkmap.l_offs = obj->relocbase;
2534 if (r_debug.r_map == NULL) {
2540 * Scan to the end of the list, but not past the entry for the
2541 * dynamic linker, which we want to keep at the very end.
2543 for (prev = r_debug.r_map;
2544 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
2545 prev = prev->l_next)
2548 /* Link in the new entry. */
2550 l->l_next = prev->l_next;
2551 if (l->l_next != NULL)
2552 l->l_next->l_prev = l;
2557 linkmap_delete(Obj_Entry *obj)
2559 struct link_map *l = &obj->linkmap;
2561 if (l->l_prev == NULL) {
2562 if ((r_debug.r_map = l->l_next) != NULL)
2563 l->l_next->l_prev = NULL;
2567 if ((l->l_prev->l_next = l->l_next) != NULL)
2568 l->l_next->l_prev = l->l_prev;
2572 * Function for the debugger to set a breakpoint on to gain control.
2574 * The two parameters allow the debugger to easily find and determine
2575 * what the runtime loader is doing and to whom it is doing it.
2577 * When the loadhook trap is hit (r_debug_state, set at program
2578 * initialization), the arguments can be found on the stack:
2580 * +8 struct link_map *m
2581 * +4 struct r_debug *rd
2585 r_debug_state(struct r_debug* rd, struct link_map *m)
2590 * Get address of the pointer variable in the main program.
2592 static const void **
2593 get_program_var_addr(const char *name)
2595 const Obj_Entry *obj;
2598 hash = elf_hash(name);
2599 for (obj = obj_main; obj != NULL; obj = obj->next) {
2602 if ((def = symlook_obj(name, hash, obj, NULL, 0)) != NULL) {
2605 addr = (const void **)(obj->relocbase + def->st_value);
2613 * Set a pointer variable in the main program to the given value. This
2614 * is used to set key variables such as "environ" before any of the
2615 * init functions are called.
2618 set_program_var(const char *name, const void *value)
2622 if ((addr = get_program_var_addr(name)) != NULL) {
2623 dbg("\"%s\": *%p <-- %p", name, addr, value);
2629 * Given a symbol name in a referencing object, find the corresponding
2630 * definition of the symbol. Returns a pointer to the symbol, or NULL if
2631 * no definition was found. Returns a pointer to the Obj_Entry of the
2632 * defining object via the reference parameter DEFOBJ_OUT.
2634 static const Elf_Sym *
2635 symlook_default(const char *name, unsigned long hash, const Obj_Entry *refobj,
2636 const Obj_Entry **defobj_out, const Ver_Entry *ventry, int flags)
2640 const Elf_Sym *symp;
2641 const Obj_Entry *obj;
2642 const Obj_Entry *defobj;
2643 const Objlist_Entry *elm;
2646 donelist_init(&donelist);
2648 /* Look first in the referencing object if linked symbolically. */
2649 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
2650 symp = symlook_obj(name, hash, refobj, ventry, flags);
2657 /* Search all objects loaded at program start up. */
2658 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2659 symp = symlook_list(name, hash, &list_main, &obj, ventry, flags,
2662 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2668 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
2669 STAILQ_FOREACH(elm, &list_global, link) {
2670 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2672 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, ventry,
2675 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2681 /* Search all dlopened DAGs containing the referencing object. */
2682 STAILQ_FOREACH(elm, &refobj->dldags, link) {
2683 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2685 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, ventry,
2688 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2695 * Search the dynamic linker itself, and possibly resolve the
2696 * symbol from there. This is how the application links to
2697 * dynamic linker services such as dlopen. Only the values listed
2698 * in the "exports" array can be resolved from the dynamic linker.
2700 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2701 symp = symlook_obj(name, hash, &obj_rtld, ventry, flags);
2702 if (symp != NULL && is_exported(symp)) {
2709 *defobj_out = defobj;
2713 static const Elf_Sym *
2714 symlook_list(const char *name, unsigned long hash, const Objlist *objlist,
2715 const Obj_Entry **defobj_out, const Ver_Entry *ventry, int flags,
2718 const Elf_Sym *symp;
2720 const Obj_Entry *defobj;
2721 const Objlist_Entry *elm;
2725 STAILQ_FOREACH(elm, objlist, link) {
2726 if (donelist_check(dlp, elm->obj))
2728 if ((symp = symlook_obj(name, hash, elm->obj, ventry, flags)) != NULL) {
2729 if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
2732 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2738 *defobj_out = defobj;
2743 * Search the symbol table of a shared object and all objects needed
2744 * by it for a symbol of the given name. Search order is
2745 * breadth-first. Returns a pointer to the symbol, or NULL if no
2746 * definition was found.
2748 static const Elf_Sym *
2749 symlook_needed(const char *name, unsigned long hash, const Needed_Entry *needed,
2750 const Obj_Entry **defobj_out, const Ver_Entry *ventry, int flags,
2753 const Elf_Sym *def, *def_w;
2754 const Needed_Entry *n;
2755 const Obj_Entry *obj, *defobj, *defobj1;
2759 for (n = needed; n != NULL; n = n->next) {
2760 if ((obj = n->obj) == NULL ||
2761 donelist_check(dlp, obj) ||
2762 (def = symlook_obj(name, hash, obj, ventry, flags)) == NULL)
2765 if (ELF_ST_BIND(def->st_info) != STB_WEAK) {
2766 *defobj_out = defobj;
2771 * There we come when either symbol definition is not found in
2772 * directly needed objects, or found symbol is weak.
2774 for (n = needed; n != NULL; n = n->next) {
2775 if ((obj = n->obj) == NULL)
2777 def_w = symlook_needed(name, hash, obj->needed, &defobj1,
2778 ventry, flags, dlp);
2781 if (def == NULL || ELF_ST_BIND(def_w->st_info) != STB_WEAK) {
2785 if (ELF_ST_BIND(def_w->st_info) != STB_WEAK)
2789 *defobj_out = defobj;
2794 * Search the symbol table of a single shared object for a symbol of
2795 * the given name and version, if requested. Returns a pointer to the
2796 * symbol, or NULL if no definition was found.
2798 * The symbol's hash value is passed in for efficiency reasons; that
2799 * eliminates many recomputations of the hash value.
2802 symlook_obj(const char *name, unsigned long hash, const Obj_Entry *obj,
2803 const Ver_Entry *ventry, int flags)
2805 unsigned long symnum;
2806 const Elf_Sym *vsymp;
2810 if (obj->buckets == NULL)
2815 symnum = obj->buckets[hash % obj->nbuckets];
2817 for (; symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
2818 const Elf_Sym *symp;
2821 if (symnum >= obj->nchains)
2822 return NULL; /* Bad object */
2824 symp = obj->symtab + symnum;
2825 strp = obj->strtab + symp->st_name;
2827 switch (ELF_ST_TYPE(symp->st_info)) {
2831 if (symp->st_value == 0)
2835 if (symp->st_shndx != SHN_UNDEF)
2838 else if (((flags & SYMLOOK_IN_PLT) == 0) &&
2839 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
2846 if (name[0] != strp[0] || strcmp(name, strp) != 0)
2849 if (ventry == NULL) {
2850 if (obj->versyms != NULL) {
2851 verndx = VER_NDX(obj->versyms[symnum]);
2852 if (verndx > obj->vernum) {
2853 _rtld_error("%s: symbol %s references wrong version %d",
2854 obj->path, obj->strtab + symnum, verndx);
2858 * If we are not called from dlsym (i.e. this is a normal
2859 * relocation from unversioned binary, accept the symbol
2860 * immediately if it happens to have first version after
2861 * this shared object became versioned. Otherwise, if
2862 * symbol is versioned and not hidden, remember it. If it
2863 * is the only symbol with this name exported by the
2864 * shared object, it will be returned as a match at the
2865 * end of the function. If symbol is global (verndx < 2)
2866 * accept it unconditionally.
2868 if ((flags & SYMLOOK_DLSYM) == 0 && verndx == VER_NDX_GIVEN)
2870 else if (verndx >= VER_NDX_GIVEN) {
2871 if ((obj->versyms[symnum] & VER_NDX_HIDDEN) == 0) {
2881 if (obj->versyms == NULL) {
2882 if (object_match_name(obj, ventry->name)) {
2883 _rtld_error("%s: object %s should provide version %s for "
2884 "symbol %s", obj_rtld.path, obj->path, ventry->name,
2885 obj->strtab + symnum);
2889 verndx = VER_NDX(obj->versyms[symnum]);
2890 if (verndx > obj->vernum) {
2891 _rtld_error("%s: symbol %s references wrong version %d",
2892 obj->path, obj->strtab + symnum, verndx);
2895 if (obj->vertab[verndx].hash != ventry->hash ||
2896 strcmp(obj->vertab[verndx].name, ventry->name)) {
2898 * Version does not match. Look if this is a global symbol
2899 * and if it is not hidden. If global symbol (verndx < 2)
2900 * is available, use it. Do not return symbol if we are
2901 * called by dlvsym, because dlvsym looks for a specific
2902 * version and default one is not what dlvsym wants.
2904 if ((flags & SYMLOOK_DLSYM) ||
2905 (obj->versyms[symnum] & VER_NDX_HIDDEN) ||
2906 (verndx >= VER_NDX_GIVEN))
2913 return (vcount == 1) ? vsymp : NULL;
2917 trace_loaded_objects(Obj_Entry *obj)
2919 char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
2922 if ((main_local = getenv(LD_ "TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
2925 if ((fmt1 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT1")) == NULL)
2926 fmt1 = "\t%o => %p (%x)\n";
2928 if ((fmt2 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT2")) == NULL)
2929 fmt2 = "\t%o (%x)\n";
2931 list_containers = getenv(LD_ "TRACE_LOADED_OBJECTS_ALL");
2933 for (; obj; obj = obj->next) {
2934 Needed_Entry *needed;
2938 if (list_containers && obj->needed != NULL)
2939 printf("%s:\n", obj->path);
2940 for (needed = obj->needed; needed; needed = needed->next) {
2941 if (needed->obj != NULL) {
2942 if (needed->obj->traced && !list_containers)
2944 needed->obj->traced = true;
2945 path = needed->obj->path;
2949 name = (char *)obj->strtab + needed->name;
2950 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
2952 fmt = is_lib ? fmt1 : fmt2;
2953 while ((c = *fmt++) != '\0') {
2979 printf("%s", main_local);
2982 printf("%s", obj_main->path);
2989 printf("%d", sodp->sod_major);
2992 printf("%d", sodp->sod_minor);
2999 printf("%p", needed->obj ? needed->obj->mapbase : 0);
3011 * Unload a dlopened object and its dependencies from memory and from
3012 * our data structures. It is assumed that the DAG rooted in the
3013 * object has already been unreferenced, and that the object has a
3014 * reference count of 0.
3017 unload_object(Obj_Entry *root)
3022 assert(root->refcount == 0);
3025 * Pass over the DAG removing unreferenced objects from
3026 * appropriate lists.
3028 unlink_object(root);
3030 /* Unmap all objects that are no longer referenced. */
3031 linkp = &obj_list->next;
3032 while ((obj = *linkp) != NULL) {
3033 if (obj->refcount == 0) {
3034 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
3036 dbg("unloading \"%s\"", obj->path);
3037 munmap(obj->mapbase, obj->mapsize);
3038 linkmap_delete(obj);
3049 unlink_object(Obj_Entry *root)
3053 if (root->refcount == 0) {
3054 /* Remove the object from the RTLD_GLOBAL list. */
3055 objlist_remove(&list_global, root);
3057 /* Remove the object from all objects' DAG lists. */
3058 STAILQ_FOREACH(elm, &root->dagmembers, link) {
3059 objlist_remove(&elm->obj->dldags, root);
3060 if (elm->obj != root)
3061 unlink_object(elm->obj);
3067 ref_dag(Obj_Entry *root)
3071 assert(root->dag_inited);
3072 STAILQ_FOREACH(elm, &root->dagmembers, link)
3073 elm->obj->refcount++;
3077 unref_dag(Obj_Entry *root)
3081 assert(root->dag_inited);
3082 STAILQ_FOREACH(elm, &root->dagmembers, link)
3083 elm->obj->refcount--;
3087 * Common code for MD __tls_get_addr().
3090 tls_get_addr_common(Elf_Addr** dtvp, int index, size_t offset)
3092 Elf_Addr* dtv = *dtvp;
3095 /* Check dtv generation in case new modules have arrived */
3096 if (dtv[0] != tls_dtv_generation) {
3100 lockstate = wlock_acquire(rtld_bind_lock);
3101 newdtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
3103 if (to_copy > tls_max_index)
3104 to_copy = tls_max_index;
3105 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
3106 newdtv[0] = tls_dtv_generation;
3107 newdtv[1] = tls_max_index;
3109 wlock_release(rtld_bind_lock, lockstate);
3113 /* Dynamically allocate module TLS if necessary */
3114 if (!dtv[index + 1]) {
3115 /* Signal safe, wlock will block out signals. */
3116 lockstate = wlock_acquire(rtld_bind_lock);
3117 if (!dtv[index + 1])
3118 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
3119 wlock_release(rtld_bind_lock, lockstate);
3121 return (void*) (dtv[index + 1] + offset);
3124 /* XXX not sure what variants to use for arm. */
3126 #if defined(__ia64__) || defined(__powerpc__)
3129 * Allocate Static TLS using the Variant I method.
3132 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
3141 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
3144 assert(tcbsize >= TLS_TCB_SIZE);
3145 tcb = calloc(1, tls_static_space - TLS_TCB_SIZE + tcbsize);
3146 tls = (Elf_Addr **)(tcb + tcbsize - TLS_TCB_SIZE);
3148 if (oldtcb != NULL) {
3149 memcpy(tls, oldtcb, tls_static_space);
3152 /* Adjust the DTV. */
3154 for (i = 0; i < dtv[1]; i++) {
3155 if (dtv[i+2] >= (Elf_Addr)oldtcb &&
3156 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
3157 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tls;
3161 dtv = calloc(tls_max_index + 2, sizeof(Elf_Addr));
3163 dtv[0] = tls_dtv_generation;
3164 dtv[1] = tls_max_index;
3166 for (obj = objs; obj; obj = obj->next) {
3167 if (obj->tlsoffset) {
3168 addr = (Elf_Addr)tls + obj->tlsoffset;
3169 memset((void*) (addr + obj->tlsinitsize),
3170 0, obj->tlssize - obj->tlsinitsize);
3172 memcpy((void*) addr, obj->tlsinit,
3174 dtv[obj->tlsindex + 1] = addr;
3183 free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
3186 Elf_Addr tlsstart, tlsend;
3189 assert(tcbsize >= TLS_TCB_SIZE);
3191 tlsstart = (Elf_Addr)tcb + tcbsize - TLS_TCB_SIZE;
3192 tlsend = tlsstart + tls_static_space;
3194 dtv = *(Elf_Addr **)tlsstart;
3196 for (i = 0; i < dtvsize; i++) {
3197 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
3198 free((void*)dtv[i+2]);
3207 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) || \
3208 defined(__arm__) || defined(__mips__)
3211 * Allocate Static TLS using the Variant II method.
3214 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
3219 Elf_Addr *dtv, *olddtv;
3220 Elf_Addr segbase, oldsegbase, addr;
3223 size = round(tls_static_space, tcbalign);
3225 assert(tcbsize >= 2*sizeof(Elf_Addr));
3226 tls = calloc(1, size + tcbsize);
3227 dtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
3229 segbase = (Elf_Addr)(tls + size);
3230 ((Elf_Addr*)segbase)[0] = segbase;
3231 ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
3233 dtv[0] = tls_dtv_generation;
3234 dtv[1] = tls_max_index;
3238 * Copy the static TLS block over whole.
3240 oldsegbase = (Elf_Addr) oldtls;
3241 memcpy((void *)(segbase - tls_static_space),
3242 (const void *)(oldsegbase - tls_static_space),
3246 * If any dynamic TLS blocks have been created tls_get_addr(),
3249 olddtv = ((Elf_Addr**)oldsegbase)[1];
3250 for (i = 0; i < olddtv[1]; i++) {
3251 if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
3252 dtv[i+2] = olddtv[i+2];
3258 * We assume that this block was the one we created with
3259 * allocate_initial_tls().
3261 free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
3263 for (obj = objs; obj; obj = obj->next) {
3264 if (obj->tlsoffset) {
3265 addr = segbase - obj->tlsoffset;
3266 memset((void*) (addr + obj->tlsinitsize),
3267 0, obj->tlssize - obj->tlsinitsize);
3269 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
3270 dtv[obj->tlsindex + 1] = addr;
3275 return (void*) segbase;
3279 free_tls(void *tls, size_t tcbsize, size_t tcbalign)
3284 Elf_Addr tlsstart, tlsend;
3287 * Figure out the size of the initial TLS block so that we can
3288 * find stuff which ___tls_get_addr() allocated dynamically.
3290 size = round(tls_static_space, tcbalign);
3292 dtv = ((Elf_Addr**)tls)[1];
3294 tlsend = (Elf_Addr) tls;
3295 tlsstart = tlsend - size;
3296 for (i = 0; i < dtvsize; i++) {
3297 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] > tlsend)) {
3298 free((void*) dtv[i+2]);
3302 free((void*) tlsstart);
3309 * Allocate TLS block for module with given index.
3312 allocate_module_tls(int index)
3317 for (obj = obj_list; obj; obj = obj->next) {
3318 if (obj->tlsindex == index)
3322 _rtld_error("Can't find module with TLS index %d", index);
3326 p = malloc(obj->tlssize);
3327 memcpy(p, obj->tlsinit, obj->tlsinitsize);
3328 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
3334 allocate_tls_offset(Obj_Entry *obj)
3341 if (obj->tlssize == 0) {
3342 obj->tls_done = true;
3346 if (obj->tlsindex == 1)
3347 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
3349 off = calculate_tls_offset(tls_last_offset, tls_last_size,
3350 obj->tlssize, obj->tlsalign);
3353 * If we have already fixed the size of the static TLS block, we
3354 * must stay within that size. When allocating the static TLS, we
3355 * leave a small amount of space spare to be used for dynamically
3356 * loading modules which use static TLS.
3358 if (tls_static_space) {
3359 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
3363 tls_last_offset = obj->tlsoffset = off;
3364 tls_last_size = obj->tlssize;
3365 obj->tls_done = true;
3371 free_tls_offset(Obj_Entry *obj)
3373 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) || \
3374 defined(__arm__) || defined(__mips__)
3376 * If we were the last thing to allocate out of the static TLS
3377 * block, we give our space back to the 'allocator'. This is a
3378 * simplistic workaround to allow libGL.so.1 to be loaded and
3379 * unloaded multiple times. We only handle the Variant II
3380 * mechanism for now - this really needs a proper allocator.
3382 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
3383 == calculate_tls_end(tls_last_offset, tls_last_size)) {
3384 tls_last_offset -= obj->tlssize;
3391 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
3396 lockstate = wlock_acquire(rtld_bind_lock);
3397 ret = allocate_tls(obj_list, oldtls, tcbsize, tcbalign);
3398 wlock_release(rtld_bind_lock, lockstate);
3403 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
3407 lockstate = wlock_acquire(rtld_bind_lock);
3408 free_tls(tcb, tcbsize, tcbalign);
3409 wlock_release(rtld_bind_lock, lockstate);
3413 object_add_name(Obj_Entry *obj, const char *name)
3419 entry = malloc(sizeof(Name_Entry) + len);
3421 if (entry != NULL) {
3422 strcpy(entry->name, name);
3423 STAILQ_INSERT_TAIL(&obj->names, entry, link);
3428 object_match_name(const Obj_Entry *obj, const char *name)
3432 STAILQ_FOREACH(entry, &obj->names, link) {
3433 if (strcmp(name, entry->name) == 0)
3440 locate_dependency(const Obj_Entry *obj, const char *name)
3442 const Objlist_Entry *entry;
3443 const Needed_Entry *needed;
3445 STAILQ_FOREACH(entry, &list_main, link) {
3446 if (object_match_name(entry->obj, name))
3450 for (needed = obj->needed; needed != NULL; needed = needed->next) {
3451 if (needed->obj == NULL)
3453 if (object_match_name(needed->obj, name))
3456 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
3462 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
3463 const Elf_Vernaux *vna)
3465 const Elf_Verdef *vd;
3466 const char *vername;
3468 vername = refobj->strtab + vna->vna_name;
3469 vd = depobj->verdef;
3471 _rtld_error("%s: version %s required by %s not defined",
3472 depobj->path, vername, refobj->path);
3476 if (vd->vd_version != VER_DEF_CURRENT) {
3477 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
3478 depobj->path, vd->vd_version);
3481 if (vna->vna_hash == vd->vd_hash) {
3482 const Elf_Verdaux *aux = (const Elf_Verdaux *)
3483 ((char *)vd + vd->vd_aux);
3484 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
3487 if (vd->vd_next == 0)
3489 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3491 if (vna->vna_flags & VER_FLG_WEAK)
3493 _rtld_error("%s: version %s required by %s not found",
3494 depobj->path, vername, refobj->path);
3499 rtld_verify_object_versions(Obj_Entry *obj)
3501 const Elf_Verneed *vn;
3502 const Elf_Verdef *vd;
3503 const Elf_Verdaux *vda;
3504 const Elf_Vernaux *vna;
3505 const Obj_Entry *depobj;
3506 int maxvernum, vernum;
3510 * Walk over defined and required version records and figure out
3511 * max index used by any of them. Do very basic sanity checking
3515 while (vn != NULL) {
3516 if (vn->vn_version != VER_NEED_CURRENT) {
3517 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
3518 obj->path, vn->vn_version);
3521 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
3523 vernum = VER_NEED_IDX(vna->vna_other);
3524 if (vernum > maxvernum)
3526 if (vna->vna_next == 0)
3528 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
3530 if (vn->vn_next == 0)
3532 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
3536 while (vd != NULL) {
3537 if (vd->vd_version != VER_DEF_CURRENT) {
3538 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
3539 obj->path, vd->vd_version);
3542 vernum = VER_DEF_IDX(vd->vd_ndx);
3543 if (vernum > maxvernum)
3545 if (vd->vd_next == 0)
3547 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3554 * Store version information in array indexable by version index.
3555 * Verify that object version requirements are satisfied along the
3558 obj->vernum = maxvernum + 1;
3559 obj->vertab = calloc(obj->vernum, sizeof(Ver_Entry));
3562 while (vd != NULL) {
3563 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
3564 vernum = VER_DEF_IDX(vd->vd_ndx);
3565 assert(vernum <= maxvernum);
3566 vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
3567 obj->vertab[vernum].hash = vd->vd_hash;
3568 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
3569 obj->vertab[vernum].file = NULL;
3570 obj->vertab[vernum].flags = 0;
3572 if (vd->vd_next == 0)
3574 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3578 while (vn != NULL) {
3579 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
3580 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
3582 if (check_object_provided_version(obj, depobj, vna))
3584 vernum = VER_NEED_IDX(vna->vna_other);
3585 assert(vernum <= maxvernum);
3586 obj->vertab[vernum].hash = vna->vna_hash;
3587 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
3588 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
3589 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
3590 VER_INFO_HIDDEN : 0;
3591 if (vna->vna_next == 0)
3593 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
3595 if (vn->vn_next == 0)
3597 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
3603 rtld_verify_versions(const Objlist *objlist)
3605 Objlist_Entry *entry;
3609 STAILQ_FOREACH(entry, objlist, link) {
3611 * Skip dummy objects or objects that have their version requirements
3614 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
3616 if (rtld_verify_object_versions(entry->obj) == -1) {
3618 if (ld_tracing == NULL)
3622 if (rc == 0 || ld_tracing != NULL)
3623 rc = rtld_verify_object_versions(&obj_rtld);
3628 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
3633 vernum = VER_NDX(obj->versyms[symnum]);
3634 if (vernum >= obj->vernum) {
3635 _rtld_error("%s: symbol %s has wrong verneed value %d",
3636 obj->path, obj->strtab + symnum, vernum);
3637 } else if (obj->vertab[vernum].hash != 0) {
3638 return &obj->vertab[vernum];