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/ktrace.h>
62 #define PATH_RTLD "/libexec/ld-elf.so.1"
64 #define PATH_RTLD "/libexec/ld-elf32.so.1"
68 typedef void (*func_ptr_type)();
69 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg);
72 * This structure provides a reentrant way to keep a list of objects and
73 * check which ones have already been processed in some way.
75 typedef struct Struct_DoneList {
76 const Obj_Entry **objs; /* Array of object pointers */
77 unsigned int num_alloc; /* Allocated size of the array */
78 unsigned int num_used; /* Number of array slots used */
82 * Function declarations.
84 static const char *basename(const char *);
85 static void die(void);
86 static void digest_dynamic(Obj_Entry *, int);
87 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
88 static Obj_Entry *dlcheck(void *);
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_dag1(Obj_Entry *, Obj_Entry *, DoneList *);
98 static void init_rtld(caddr_t);
99 static void initlist_add_neededs(Needed_Entry *, Objlist *);
100 static void initlist_add_objects(Obj_Entry *, Obj_Entry **, Objlist *);
101 static bool is_exported(const Elf_Sym *);
102 static void linkmap_add(Obj_Entry *);
103 static void linkmap_delete(Obj_Entry *);
104 static int load_needed_objects(Obj_Entry *);
105 static int load_preload_objects(void);
106 static Obj_Entry *load_object(char *);
107 static Obj_Entry *obj_from_addr(const void *);
108 static void objlist_call_fini(Objlist *);
109 static void objlist_call_init(Objlist *);
110 static void objlist_clear(Objlist *);
111 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
112 static void objlist_init(Objlist *);
113 static void objlist_push_head(Objlist *, Obj_Entry *);
114 static void objlist_push_tail(Objlist *, Obj_Entry *);
115 static void objlist_remove(Objlist *, Obj_Entry *);
116 static void objlist_remove_unref(Objlist *);
117 static void *path_enumerate(const char *, path_enum_proc, void *);
118 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *);
119 static int rtld_dirname(const char *, char *);
120 static void rtld_exit(void);
121 static char *search_library_path(const char *, const char *);
122 static const void **get_program_var_addr(const char *name);
123 static void set_program_var(const char *, const void *);
124 static const Elf_Sym *symlook_default(const char *, unsigned long,
125 const Obj_Entry *, const Obj_Entry **, bool);
126 static const Elf_Sym *symlook_list(const char *, unsigned long,
127 const Objlist *, const Obj_Entry **, bool, DoneList *);
128 static const Elf_Sym *symlook_needed(const char *, unsigned long,
129 const Needed_Entry *, const Obj_Entry **, bool, DoneList *);
130 static void trace_loaded_objects(Obj_Entry *);
131 static void unlink_object(Obj_Entry *);
132 static void unload_object(Obj_Entry *);
133 static void unref_dag(Obj_Entry *);
134 static void ref_dag(Obj_Entry *);
135 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
137 void r_debug_state(struct r_debug *, struct link_map *);
142 static char *error_message; /* Message for dlerror(), or NULL */
143 struct r_debug r_debug; /* for GDB; */
144 static bool libmap_disable; /* Disable libmap */
145 static char *libmap_override; /* Maps to use in addition to libmap.conf */
146 static bool trust; /* False for setuid and setgid programs */
147 static bool dangerous_ld_env; /* True if environment variables have been
148 used to affect the libraries loaded */
149 static char *ld_bind_now; /* Environment variable for immediate binding */
150 static char *ld_debug; /* Environment variable for debugging */
151 static char *ld_library_path; /* Environment variable for search path */
152 static char *ld_preload; /* Environment variable for libraries to
154 static char *ld_tracing; /* Called from ldd to print libs */
155 static char *ld_utrace; /* Use utrace() to log events. */
156 static Obj_Entry *obj_list; /* Head of linked list of shared objects */
157 static Obj_Entry **obj_tail; /* Link field of last object in list */
158 static Obj_Entry *obj_main; /* The main program shared object */
159 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
160 static unsigned int obj_count; /* Number of objects in obj_list */
162 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
163 STAILQ_HEAD_INITIALIZER(list_global);
164 static Objlist list_main = /* Objects loaded at program startup */
165 STAILQ_HEAD_INITIALIZER(list_main);
166 static Objlist list_fini = /* Objects needing fini() calls */
167 STAILQ_HEAD_INITIALIZER(list_fini);
169 static Elf_Sym sym_zero; /* For resolving undefined weak refs. */
171 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
173 extern Elf_Dyn _DYNAMIC;
174 #pragma weak _DYNAMIC
175 #ifndef RTLD_IS_DYNAMIC
176 #define RTLD_IS_DYNAMIC() (&_DYNAMIC != NULL)
180 * These are the functions the dynamic linker exports to application
181 * programs. They are the only symbols the dynamic linker is willing
182 * to export from itself.
184 static func_ptr_type exports[] = {
185 (func_ptr_type) &_rtld_error,
186 (func_ptr_type) &dlclose,
187 (func_ptr_type) &dlerror,
188 (func_ptr_type) &dlopen,
189 (func_ptr_type) &dlsym,
190 (func_ptr_type) &dladdr,
191 (func_ptr_type) &dllockinit,
192 (func_ptr_type) &dlinfo,
193 (func_ptr_type) &_rtld_thread_init,
195 (func_ptr_type) &___tls_get_addr,
197 (func_ptr_type) &__tls_get_addr,
198 (func_ptr_type) &_rtld_allocate_tls,
199 (func_ptr_type) &_rtld_free_tls,
204 * Global declarations normally provided by crt1. The dynamic linker is
205 * not built with crt1, so we have to provide them ourselves.
211 * Globals to control TLS allocation.
213 size_t tls_last_offset; /* Static TLS offset of last module */
214 size_t tls_last_size; /* Static TLS size of last module */
215 size_t tls_static_space; /* Static TLS space allocated */
216 int tls_dtv_generation = 1; /* Used to detect when dtv size changes */
217 int tls_max_index = 1; /* Largest module index allocated */
220 * Fill in a DoneList with an allocation large enough to hold all of
221 * the currently-loaded objects. Keep this as a macro since it calls
222 * alloca and we want that to occur within the scope of the caller.
224 #define donelist_init(dlp) \
225 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
226 assert((dlp)->objs != NULL), \
227 (dlp)->num_alloc = obj_count, \
230 #define UTRACE_DLOPEN_START 1
231 #define UTRACE_DLOPEN_STOP 2
232 #define UTRACE_DLCLOSE_START 3
233 #define UTRACE_DLCLOSE_STOP 4
234 #define UTRACE_LOAD_OBJECT 5
235 #define UTRACE_UNLOAD_OBJECT 6
236 #define UTRACE_ADD_RUNDEP 7
237 #define UTRACE_PRELOAD_FINISHED 8
238 #define UTRACE_INIT_CALL 9
239 #define UTRACE_FINI_CALL 10
242 char sig[4]; /* 'RTLD' */
245 void *mapbase; /* Used for 'parent' and 'init/fini' */
247 int refcnt; /* Used for 'mode' */
248 char name[MAXPATHLEN];
251 #define LD_UTRACE(e, h, mb, ms, r, n) do { \
252 if (ld_utrace != NULL) \
253 ld_utrace_log(e, h, mb, ms, r, n); \
257 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
258 int refcnt, const char *name)
260 struct utrace_rtld ut;
268 ut.mapbase = mapbase;
269 ut.mapsize = mapsize;
271 bzero(ut.name, sizeof(ut.name));
273 strlcpy(ut.name, name, sizeof(ut.name));
274 utrace(&ut, sizeof(ut));
278 * Main entry point for dynamic linking. The first argument is the
279 * stack pointer. The stack is expected to be laid out as described
280 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
281 * Specifically, the stack pointer points to a word containing
282 * ARGC. Following that in the stack is a null-terminated sequence
283 * of pointers to argument strings. Then comes a null-terminated
284 * sequence of pointers to environment strings. Finally, there is a
285 * sequence of "auxiliary vector" entries.
287 * The second argument points to a place to store the dynamic linker's
288 * exit procedure pointer and the third to a place to store the main
291 * The return value is the main program's entry point.
294 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
296 Elf_Auxinfo *aux_info[AT_COUNT];
304 Objlist_Entry *entry;
306 Obj_Entry **preload_tail;
311 * On entry, the dynamic linker itself has not been relocated yet.
312 * Be very careful not to reference any global data until after
313 * init_rtld has returned. It is OK to reference file-scope statics
314 * and string constants, and to call static and global functions.
317 /* Find the auxiliary vector on the stack. */
320 sp += argc + 1; /* Skip over arguments and NULL terminator */
322 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
324 aux = (Elf_Auxinfo *) sp;
326 /* Digest the auxiliary vector. */
327 for (i = 0; i < AT_COUNT; i++)
329 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
330 if (auxp->a_type < AT_COUNT)
331 aux_info[auxp->a_type] = auxp;
334 /* Initialize and relocate ourselves. */
335 assert(aux_info[AT_BASE] != NULL);
336 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
338 __progname = obj_rtld.path;
339 argv0 = argv[0] != NULL ? argv[0] : "(null)";
342 trust = !issetugid();
344 ld_bind_now = getenv(LD_ "BIND_NOW");
346 * If the process is tainted, then we un-set the dangerous environment
347 * variables. The process will be marked as tainted until setuid(2)
348 * is called. If any child process calls setuid(2) we do not want any
349 * future processes to honor the potentially un-safe variables.
352 unsetenv(LD_ "PRELOAD");
353 unsetenv(LD_ "LIBMAP");
354 unsetenv(LD_ "LIBRARY_PATH");
355 unsetenv(LD_ "LIBMAP_DISABLE");
356 unsetenv(LD_ "DEBUG");
358 ld_debug = getenv(LD_ "DEBUG");
359 libmap_disable = getenv(LD_ "LIBMAP_DISABLE") != NULL;
360 libmap_override = getenv(LD_ "LIBMAP");
361 ld_library_path = getenv(LD_ "LIBRARY_PATH");
362 ld_preload = getenv(LD_ "PRELOAD");
363 dangerous_ld_env = libmap_disable || (libmap_override != NULL) ||
364 (ld_library_path != NULL) || (ld_preload != NULL);
365 ld_tracing = getenv(LD_ "TRACE_LOADED_OBJECTS");
366 ld_utrace = getenv(LD_ "UTRACE");
368 if (ld_debug != NULL && *ld_debug != '\0')
370 dbg("%s is initialized, base address = %p", __progname,
371 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
372 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
373 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
376 * Load the main program, or process its program header if it is
379 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
380 int fd = aux_info[AT_EXECFD]->a_un.a_val;
381 dbg("loading main program");
382 obj_main = map_object(fd, argv0, NULL);
384 if (obj_main == NULL)
386 } else { /* Main program already loaded. */
387 const Elf_Phdr *phdr;
391 dbg("processing main program's program header");
392 assert(aux_info[AT_PHDR] != NULL);
393 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
394 assert(aux_info[AT_PHNUM] != NULL);
395 phnum = aux_info[AT_PHNUM]->a_un.a_val;
396 assert(aux_info[AT_PHENT] != NULL);
397 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
398 assert(aux_info[AT_ENTRY] != NULL);
399 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
400 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
404 obj_main->path = xstrdup(argv0);
405 obj_main->mainprog = true;
408 * Get the actual dynamic linker pathname from the executable if
409 * possible. (It should always be possible.) That ensures that
410 * gdb will find the right dynamic linker even if a non-standard
413 if (obj_main->interp != NULL &&
414 strcmp(obj_main->interp, obj_rtld.path) != 0) {
416 obj_rtld.path = xstrdup(obj_main->interp);
417 __progname = obj_rtld.path;
420 digest_dynamic(obj_main, 0);
422 linkmap_add(obj_main);
423 linkmap_add(&obj_rtld);
425 /* Link the main program into the list of objects. */
426 *obj_tail = obj_main;
427 obj_tail = &obj_main->next;
429 /* Make sure we don't call the main program's init and fini functions. */
430 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
432 /* Initialize a fake symbol for resolving undefined weak references. */
433 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
434 sym_zero.st_shndx = SHN_UNDEF;
437 libmap_disable = (bool)lm_init(libmap_override);
439 dbg("loading LD_PRELOAD libraries");
440 if (load_preload_objects() == -1)
442 preload_tail = obj_tail;
444 dbg("loading needed objects");
445 if (load_needed_objects(obj_main) == -1)
448 /* Make a list of all objects loaded at startup. */
449 for (obj = obj_list; obj != NULL; obj = obj->next) {
450 objlist_push_tail(&list_main, obj);
454 if (ld_tracing) { /* We're done */
455 trace_loaded_objects(obj_main);
459 if (getenv(LD_ "DUMP_REL_PRE") != NULL) {
460 dump_relocations(obj_main);
464 /* setup TLS for main thread */
465 dbg("initializing initial thread local storage");
466 STAILQ_FOREACH(entry, &list_main, link) {
468 * Allocate all the initial objects out of the static TLS
469 * block even if they didn't ask for it.
471 allocate_tls_offset(entry->obj);
473 allocate_initial_tls(obj_list);
475 if (relocate_objects(obj_main,
476 ld_bind_now != NULL && *ld_bind_now != '\0', &obj_rtld) == -1)
479 dbg("doing copy relocations");
480 if (do_copy_relocations(obj_main) == -1)
483 if (getenv(LD_ "DUMP_REL_POST") != NULL) {
484 dump_relocations(obj_main);
488 dbg("initializing key program variables");
489 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
490 set_program_var("environ", env);
492 dbg("initializing thread locks");
495 /* Make a list of init functions to call. */
496 objlist_init(&initlist);
497 initlist_add_objects(obj_list, preload_tail, &initlist);
499 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
501 objlist_call_init(&initlist);
502 lockstate = wlock_acquire(rtld_bind_lock);
503 objlist_clear(&initlist);
504 wlock_release(rtld_bind_lock, lockstate);
506 dbg("transferring control to program entry point = %p", obj_main->entry);
508 /* Return the exit procedure and the program entry point. */
509 *exit_proc = rtld_exit;
511 return (func_ptr_type) obj_main->entry;
515 _rtld_bind(Obj_Entry *obj, Elf_Size reloff)
519 const Obj_Entry *defobj;
524 lockstate = rlock_acquire(rtld_bind_lock);
526 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
528 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
530 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
531 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL);
535 target = (Elf_Addr)(defobj->relocbase + def->st_value);
537 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
538 defobj->strtab + def->st_name, basename(obj->path),
539 (void *)target, basename(defobj->path));
542 * Write the new contents for the jmpslot. Note that depending on
543 * architecture, the value which we need to return back to the
544 * lazy binding trampoline may or may not be the target
545 * address. The value returned from reloc_jmpslot() is the value
546 * that the trampoline needs.
548 target = reloc_jmpslot(where, target, defobj, obj, rel);
549 rlock_release(rtld_bind_lock, lockstate);
554 * Error reporting function. Use it like printf. If formats the message
555 * into a buffer, and sets things up so that the next call to dlerror()
556 * will return the message.
559 _rtld_error(const char *fmt, ...)
561 static char buf[512];
565 vsnprintf(buf, sizeof buf, fmt, ap);
571 * Return a dynamically-allocated copy of the current error message, if any.
576 return error_message == NULL ? NULL : xstrdup(error_message);
580 * Restore the current error message from a copy which was previously saved
581 * by errmsg_save(). The copy is freed.
584 errmsg_restore(char *saved_msg)
586 if (saved_msg == NULL)
587 error_message = NULL;
589 _rtld_error("%s", saved_msg);
595 basename(const char *name)
597 const char *p = strrchr(name, '/');
598 return p != NULL ? p + 1 : name;
604 const char *msg = dlerror();
612 * Process a shared object's DYNAMIC section, and save the important
613 * information in its Obj_Entry structure.
616 digest_dynamic(Obj_Entry *obj, int early)
619 Needed_Entry **needed_tail = &obj->needed;
620 const Elf_Dyn *dyn_rpath = NULL;
621 int plttype = DT_REL;
623 obj->bind_now = false;
624 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
625 switch (dynp->d_tag) {
628 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
632 obj->relsize = dynp->d_un.d_val;
636 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
640 obj->pltrel = (const Elf_Rel *)
641 (obj->relocbase + dynp->d_un.d_ptr);
645 obj->pltrelsize = dynp->d_un.d_val;
649 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
653 obj->relasize = dynp->d_un.d_val;
657 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
661 plttype = dynp->d_un.d_val;
662 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
666 obj->symtab = (const Elf_Sym *)
667 (obj->relocbase + dynp->d_un.d_ptr);
671 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
675 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
679 obj->strsize = dynp->d_un.d_val;
684 const Elf_Hashelt *hashtab = (const Elf_Hashelt *)
685 (obj->relocbase + dynp->d_un.d_ptr);
686 obj->nbuckets = hashtab[0];
687 obj->nchains = hashtab[1];
688 obj->buckets = hashtab + 2;
689 obj->chains = obj->buckets + obj->nbuckets;
695 Needed_Entry *nep = NEW(Needed_Entry);
696 nep->name = dynp->d_un.d_val;
701 needed_tail = &nep->next;
706 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
714 obj->symbolic = true;
718 case DT_RUNPATH: /* XXX: process separately */
720 * We have to wait until later to process this, because we
721 * might not have gotten the address of the string table yet.
727 /* Not used by the dynamic linker. */
731 obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
735 obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
739 /* XXX - not implemented yet */
741 dbg("Filling in DT_DEBUG entry");
742 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
746 if (dynp->d_un.d_val & DF_ORIGIN) {
747 obj->origin_path = xmalloc(PATH_MAX);
748 if (rtld_dirname(obj->path, obj->origin_path) == -1)
751 if (dynp->d_un.d_val & DF_SYMBOLIC)
752 obj->symbolic = true;
753 if (dynp->d_un.d_val & DF_TEXTREL)
755 if (dynp->d_un.d_val & DF_BIND_NOW)
756 obj->bind_now = true;
757 if (dynp->d_un.d_val & DF_STATIC_TLS)
763 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
772 if (plttype == DT_RELA) {
773 obj->pltrela = (const Elf_Rela *) obj->pltrel;
775 obj->pltrelasize = obj->pltrelsize;
779 if (dyn_rpath != NULL)
780 obj->rpath = obj->strtab + dyn_rpath->d_un.d_val;
784 * Process a shared object's program header. This is used only for the
785 * main program, when the kernel has already loaded the main program
786 * into memory before calling the dynamic linker. It creates and
787 * returns an Obj_Entry structure.
790 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
793 const Elf_Phdr *phlimit = phdr + phnum;
798 for (ph = phdr; ph < phlimit; ph++) {
799 switch (ph->p_type) {
802 if ((const Elf_Phdr *)ph->p_vaddr != phdr) {
803 _rtld_error("%s: invalid PT_PHDR", path);
806 obj->phdr = (const Elf_Phdr *) ph->p_vaddr;
807 obj->phsize = ph->p_memsz;
811 obj->interp = (const char *) ph->p_vaddr;
815 if (nsegs == 0) { /* First load segment */
816 obj->vaddrbase = trunc_page(ph->p_vaddr);
817 obj->mapbase = (caddr_t) obj->vaddrbase;
818 obj->relocbase = obj->mapbase - obj->vaddrbase;
819 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
821 } else { /* Last load segment */
822 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
829 obj->dynamic = (const Elf_Dyn *) ph->p_vaddr;
834 obj->tlssize = ph->p_memsz;
835 obj->tlsalign = ph->p_align;
836 obj->tlsinitsize = ph->p_filesz;
837 obj->tlsinit = (void*) ph->p_vaddr;
842 _rtld_error("%s: too few PT_LOAD segments", path);
851 dlcheck(void *handle)
855 for (obj = obj_list; obj != NULL; obj = obj->next)
856 if (obj == (Obj_Entry *) handle)
859 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
860 _rtld_error("Invalid shared object handle %p", handle);
867 * If the given object is already in the donelist, return true. Otherwise
868 * add the object to the list and return false.
871 donelist_check(DoneList *dlp, const Obj_Entry *obj)
875 for (i = 0; i < dlp->num_used; i++)
876 if (dlp->objs[i] == obj)
879 * Our donelist allocation should always be sufficient. But if
880 * our threads locking isn't working properly, more shared objects
881 * could have been loaded since we allocated the list. That should
882 * never happen, but we'll handle it properly just in case it does.
884 if (dlp->num_used < dlp->num_alloc)
885 dlp->objs[dlp->num_used++] = obj;
890 * Hash function for symbol table lookup. Don't even think about changing
891 * this. It is specified by the System V ABI.
894 elf_hash(const char *name)
896 const unsigned char *p = (const unsigned char *) name;
902 if ((g = h & 0xf0000000) != 0)
910 * Find the library with the given name, and return its full pathname.
911 * The returned string is dynamically allocated. Generates an error
912 * message and returns NULL if the library cannot be found.
914 * If the second argument is non-NULL, then it refers to an already-
915 * loaded shared object, whose library search path will be searched.
917 * The search order is:
919 * rpath in the referencing file
924 find_library(const char *xname, const Obj_Entry *refobj)
929 if (strchr(xname, '/') != NULL) { /* Hard coded pathname */
930 if (xname[0] != '/' && !trust) {
931 _rtld_error("Absolute pathname required for shared object \"%s\"",
935 return xstrdup(xname);
938 if (libmap_disable || (refobj == NULL) ||
939 (name = lm_find(refobj->path, xname)) == NULL)
940 name = (char *)xname;
942 dbg(" Searching for \"%s\"", name);
944 if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
946 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
947 (pathname = search_library_path(name, gethints())) != NULL ||
948 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
951 if(refobj != NULL && refobj->path != NULL) {
952 _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
953 name, basename(refobj->path));
955 _rtld_error("Shared object \"%s\" not found", name);
961 * Given a symbol number in a referencing object, find the corresponding
962 * definition of the symbol. Returns a pointer to the symbol, or NULL if
963 * no definition was found. Returns a pointer to the Obj_Entry of the
964 * defining object via the reference parameter DEFOBJ_OUT.
967 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
968 const Obj_Entry **defobj_out, bool in_plt, SymCache *cache)
972 const Obj_Entry *defobj;
977 * If we have already found this symbol, get the information from
980 if (symnum >= refobj->nchains)
981 return NULL; /* Bad object */
982 if (cache != NULL && cache[symnum].sym != NULL) {
983 *defobj_out = cache[symnum].obj;
984 return cache[symnum].sym;
987 ref = refobj->symtab + symnum;
988 name = refobj->strtab + ref->st_name;
992 * We don't have to do a full scale lookup if the symbol is local.
993 * We know it will bind to the instance in this load module; to
994 * which we already have a pointer (ie ref). By not doing a lookup,
995 * we not only improve performance, but it also avoids unresolvable
996 * symbols when local symbols are not in the hash table. This has
997 * been seen with the ia64 toolchain.
999 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1000 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1001 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1004 hash = elf_hash(name);
1005 def = symlook_default(name, hash, refobj, &defobj, in_plt);
1012 * If we found no definition and the reference is weak, treat the
1013 * symbol as having the value zero.
1015 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1021 *defobj_out = defobj;
1022 /* Record the information in the cache to avoid subsequent lookups. */
1023 if (cache != NULL) {
1024 cache[symnum].sym = def;
1025 cache[symnum].obj = defobj;
1028 if (refobj != &obj_rtld)
1029 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1035 * Return the search path from the ldconfig hints file, reading it if
1036 * necessary. Returns NULL if there are problems with the hints file,
1037 * or if the search path there is empty.
1044 if (hints == NULL) {
1046 struct elfhints_hdr hdr;
1049 /* Keep from trying again in case the hints file is bad. */
1052 if ((fd = open(_PATH_ELF_HINTS, O_RDONLY)) == -1)
1054 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1055 hdr.magic != ELFHINTS_MAGIC ||
1060 p = xmalloc(hdr.dirlistlen + 1);
1061 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1062 read(fd, p, hdr.dirlistlen + 1) != (ssize_t)hdr.dirlistlen + 1) {
1070 return hints[0] != '\0' ? hints : NULL;
1074 init_dag(Obj_Entry *root)
1078 donelist_init(&donelist);
1079 init_dag1(root, root, &donelist);
1083 init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *dlp)
1085 const Needed_Entry *needed;
1087 if (donelist_check(dlp, obj))
1091 objlist_push_tail(&obj->dldags, root);
1092 objlist_push_tail(&root->dagmembers, obj);
1093 for (needed = obj->needed; needed != NULL; needed = needed->next)
1094 if (needed->obj != NULL)
1095 init_dag1(root, needed->obj, dlp);
1099 * Initialize the dynamic linker. The argument is the address at which
1100 * the dynamic linker has been mapped into memory. The primary task of
1101 * this function is to relocate the dynamic linker.
1104 init_rtld(caddr_t mapbase)
1106 Obj_Entry objtmp; /* Temporary rtld object */
1109 * Conjure up an Obj_Entry structure for the dynamic linker.
1111 * The "path" member can't be initialized yet because string constatns
1112 * cannot yet be acessed. Below we will set it correctly.
1114 memset(&objtmp, 0, sizeof(objtmp));
1117 objtmp.mapbase = mapbase;
1119 objtmp.relocbase = mapbase;
1121 if (RTLD_IS_DYNAMIC()) {
1122 objtmp.dynamic = rtld_dynamic(&objtmp);
1123 digest_dynamic(&objtmp, 1);
1124 assert(objtmp.needed == NULL);
1125 assert(!objtmp.textrel);
1128 * Temporarily put the dynamic linker entry into the object list, so
1129 * that symbols can be found.
1132 relocate_objects(&objtmp, true, &objtmp);
1135 /* Initialize the object list. */
1136 obj_tail = &obj_list;
1138 /* Now that non-local variables can be accesses, copy out obj_rtld. */
1139 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1141 /* Replace the path with a dynamically allocated copy. */
1142 obj_rtld.path = xstrdup(PATH_RTLD);
1144 r_debug.r_brk = r_debug_state;
1145 r_debug.r_state = RT_CONSISTENT;
1149 * Add the init functions from a needed object list (and its recursive
1150 * needed objects) to "list". This is not used directly; it is a helper
1151 * function for initlist_add_objects(). The write lock must be held
1152 * when this function is called.
1155 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1157 /* Recursively process the successor needed objects. */
1158 if (needed->next != NULL)
1159 initlist_add_neededs(needed->next, list);
1161 /* Process the current needed object. */
1162 if (needed->obj != NULL)
1163 initlist_add_objects(needed->obj, &needed->obj->next, list);
1167 * Scan all of the DAGs rooted in the range of objects from "obj" to
1168 * "tail" and add their init functions to "list". This recurses over
1169 * the DAGs and ensure the proper init ordering such that each object's
1170 * needed libraries are initialized before the object itself. At the
1171 * same time, this function adds the objects to the global finalization
1172 * list "list_fini" in the opposite order. The write lock must be
1173 * held when this function is called.
1176 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1180 obj->init_done = true;
1182 /* Recursively process the successor objects. */
1183 if (&obj->next != tail)
1184 initlist_add_objects(obj->next, tail, list);
1186 /* Recursively process the needed objects. */
1187 if (obj->needed != NULL)
1188 initlist_add_neededs(obj->needed, list);
1190 /* Add the object to the init list. */
1191 if (obj->init != (Elf_Addr)NULL)
1192 objlist_push_tail(list, obj);
1194 /* Add the object to the global fini list in the reverse order. */
1195 if (obj->fini != (Elf_Addr)NULL)
1196 objlist_push_head(&list_fini, obj);
1200 #define FPTR_TARGET(f) ((Elf_Addr) (f))
1204 is_exported(const Elf_Sym *def)
1207 const func_ptr_type *p;
1209 value = (Elf_Addr)(obj_rtld.relocbase + def->st_value);
1210 for (p = exports; *p != NULL; p++)
1211 if (FPTR_TARGET(*p) == value)
1217 * Given a shared object, traverse its list of needed objects, and load
1218 * each of them. Returns 0 on success. Generates an error message and
1219 * returns -1 on failure.
1222 load_needed_objects(Obj_Entry *first)
1226 for (obj = first; obj != NULL; obj = obj->next) {
1227 Needed_Entry *needed;
1229 for (needed = obj->needed; needed != NULL; needed = needed->next) {
1230 const char *name = obj->strtab + needed->name;
1231 char *path = find_library(name, obj);
1234 if (path == NULL && !ld_tracing)
1238 needed->obj = load_object(path);
1239 if (needed->obj == NULL && !ld_tracing)
1240 return -1; /* XXX - cleanup */
1249 load_preload_objects(void)
1251 char *p = ld_preload;
1252 static const char delim[] = " \t:;";
1257 p += strspn(p, delim);
1258 while (*p != '\0') {
1259 size_t len = strcspn(p, delim);
1265 if ((path = find_library(p, NULL)) == NULL)
1267 if (load_object(path) == NULL)
1268 return -1; /* XXX - cleanup */
1271 p += strspn(p, delim);
1273 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
1278 * Load a shared object into memory, if it is not already loaded. The
1279 * argument must be a string allocated on the heap. This function assumes
1280 * responsibility for freeing it when necessary.
1282 * Returns a pointer to the Obj_Entry for the object. Returns NULL
1286 load_object(char *path)
1293 for (obj = obj_list->next; obj != NULL; obj = obj->next)
1294 if (strcmp(obj->path, path) == 0)
1298 * If we didn't find a match by pathname, open the file and check
1299 * again by device and inode. This avoids false mismatches caused
1300 * by multiple links or ".." in pathnames.
1302 * To avoid a race, we open the file and use fstat() rather than
1306 if ((fd = open(path, O_RDONLY)) == -1) {
1307 _rtld_error("Cannot open \"%s\"", path);
1310 if (fstat(fd, &sb) == -1) {
1311 _rtld_error("Cannot fstat \"%s\"", path);
1315 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
1316 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev) {
1323 if (obj == NULL) { /* First use of this object, so we must map it in */
1325 * but first, make sure that environment variables haven't been
1326 * used to circumvent the noexec flag on a filesystem.
1328 if (dangerous_ld_env) {
1329 if (fstatfs(fd, &fs) != 0) {
1330 _rtld_error("Cannot fstatfs \"%s\"", path);
1334 if (fs.f_flags & MNT_NOEXEC) {
1335 _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
1340 dbg("loading \"%s\"", path);
1341 obj = map_object(fd, path, &sb);
1349 digest_dynamic(obj, 0);
1352 obj_tail = &obj->next;
1354 linkmap_add(obj); /* for GDB & dlinfo() */
1356 dbg(" %p .. %p: %s", obj->mapbase,
1357 obj->mapbase + obj->mapsize - 1, obj->path);
1359 dbg(" WARNING: %s has impure text", obj->path);
1360 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
1369 obj_from_addr(const void *addr)
1373 for (obj = obj_list; obj != NULL; obj = obj->next) {
1374 if (addr < (void *) obj->mapbase)
1376 if (addr < (void *) (obj->mapbase + obj->mapsize))
1383 * Call the finalization functions for each of the objects in "list"
1384 * which are unreferenced. All of the objects are expected to have
1385 * non-NULL fini functions.
1388 objlist_call_fini(Objlist *list)
1394 * Preserve the current error message since a fini function might
1395 * call into the dynamic linker and overwrite it.
1397 saved_msg = errmsg_save();
1398 STAILQ_FOREACH(elm, list, link) {
1399 if (elm->obj->refcount == 0) {
1400 dbg("calling fini function for %s at %p", elm->obj->path,
1401 (void *)elm->obj->fini);
1402 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini, 0, 0,
1404 call_initfini_pointer(elm->obj, elm->obj->fini);
1407 errmsg_restore(saved_msg);
1411 * Call the initialization functions for each of the objects in
1412 * "list". All of the objects are expected to have non-NULL init
1416 objlist_call_init(Objlist *list)
1422 * Preserve the current error message since an init function might
1423 * call into the dynamic linker and overwrite it.
1425 saved_msg = errmsg_save();
1426 STAILQ_FOREACH(elm, list, link) {
1427 dbg("calling init function for %s at %p", elm->obj->path,
1428 (void *)elm->obj->init);
1429 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init, 0, 0,
1431 call_initfini_pointer(elm->obj, elm->obj->init);
1433 errmsg_restore(saved_msg);
1437 objlist_clear(Objlist *list)
1441 while (!STAILQ_EMPTY(list)) {
1442 elm = STAILQ_FIRST(list);
1443 STAILQ_REMOVE_HEAD(list, link);
1448 static Objlist_Entry *
1449 objlist_find(Objlist *list, const Obj_Entry *obj)
1453 STAILQ_FOREACH(elm, list, link)
1454 if (elm->obj == obj)
1460 objlist_init(Objlist *list)
1466 objlist_push_head(Objlist *list, Obj_Entry *obj)
1470 elm = NEW(Objlist_Entry);
1472 STAILQ_INSERT_HEAD(list, elm, link);
1476 objlist_push_tail(Objlist *list, Obj_Entry *obj)
1480 elm = NEW(Objlist_Entry);
1482 STAILQ_INSERT_TAIL(list, elm, link);
1486 objlist_remove(Objlist *list, Obj_Entry *obj)
1490 if ((elm = objlist_find(list, obj)) != NULL) {
1491 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1497 * Remove all of the unreferenced objects from "list".
1500 objlist_remove_unref(Objlist *list)
1505 STAILQ_INIT(&newlist);
1506 while (!STAILQ_EMPTY(list)) {
1507 elm = STAILQ_FIRST(list);
1508 STAILQ_REMOVE_HEAD(list, link);
1509 if (elm->obj->refcount == 0)
1512 STAILQ_INSERT_TAIL(&newlist, elm, link);
1518 * Relocate newly-loaded shared objects. The argument is a pointer to
1519 * the Obj_Entry for the first such object. All objects from the first
1520 * to the end of the list of objects are relocated. Returns 0 on success,
1524 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj)
1528 for (obj = first; obj != NULL; obj = obj->next) {
1530 dbg("relocating \"%s\"", obj->path);
1531 if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
1532 obj->symtab == NULL || obj->strtab == NULL) {
1533 _rtld_error("%s: Shared object has no run-time symbol table",
1539 /* There are relocations to the write-protected text segment. */
1540 if (mprotect(obj->mapbase, obj->textsize,
1541 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
1542 _rtld_error("%s: Cannot write-enable text segment: %s",
1543 obj->path, strerror(errno));
1548 /* Process the non-PLT relocations. */
1549 if (reloc_non_plt(obj, rtldobj))
1552 if (obj->textrel) { /* Re-protected the text segment. */
1553 if (mprotect(obj->mapbase, obj->textsize,
1554 PROT_READ|PROT_EXEC) == -1) {
1555 _rtld_error("%s: Cannot write-protect text segment: %s",
1556 obj->path, strerror(errno));
1561 /* Process the PLT relocations. */
1562 if (reloc_plt(obj) == -1)
1564 /* Relocate the jump slots if we are doing immediate binding. */
1565 if (obj->bind_now || bind_now)
1566 if (reloc_jmpslots(obj) == -1)
1571 * Set up the magic number and version in the Obj_Entry. These
1572 * were checked in the crt1.o from the original ElfKit, so we
1573 * set them for backward compatibility.
1575 obj->magic = RTLD_MAGIC;
1576 obj->version = RTLD_VERSION;
1578 /* Set the special PLT or GOT entries. */
1586 * Cleanup procedure. It will be called (by the atexit mechanism) just
1587 * before the process exits.
1595 /* Clear all the reference counts so the fini functions will be called. */
1596 for (obj = obj_list; obj != NULL; obj = obj->next)
1598 objlist_call_fini(&list_fini);
1599 /* No need to remove the items from the list, since we are exiting. */
1600 if (!libmap_disable)
1605 path_enumerate(const char *path, path_enum_proc callback, void *arg)
1613 path += strspn(path, ":;");
1614 while (*path != '\0') {
1618 len = strcspn(path, ":;");
1620 trans = lm_findn(NULL, path, len);
1622 res = callback(trans, strlen(trans), arg);
1625 res = callback(path, len, arg);
1631 path += strspn(path, ":;");
1637 struct try_library_args {
1645 try_library_path(const char *dir, size_t dirlen, void *param)
1647 struct try_library_args *arg;
1650 if (*dir == '/' || trust) {
1653 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
1656 pathname = arg->buffer;
1657 strncpy(pathname, dir, dirlen);
1658 pathname[dirlen] = '/';
1659 strcpy(pathname + dirlen + 1, arg->name);
1661 dbg(" Trying \"%s\"", pathname);
1662 if (access(pathname, F_OK) == 0) { /* We found it */
1663 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
1664 strcpy(pathname, arg->buffer);
1672 search_library_path(const char *name, const char *path)
1675 struct try_library_args arg;
1681 arg.namelen = strlen(name);
1682 arg.buffer = xmalloc(PATH_MAX);
1683 arg.buflen = PATH_MAX;
1685 p = path_enumerate(path, try_library_path, &arg);
1693 dlclose(void *handle)
1698 lockstate = wlock_acquire(rtld_bind_lock);
1699 root = dlcheck(handle);
1701 wlock_release(rtld_bind_lock, lockstate);
1704 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
1707 /* Unreference the object and its dependencies. */
1708 root->dl_refcount--;
1712 if (root->refcount == 0) {
1714 * The object is no longer referenced, so we must unload it.
1715 * First, call the fini functions with no locks held.
1717 wlock_release(rtld_bind_lock, lockstate);
1718 objlist_call_fini(&list_fini);
1719 lockstate = wlock_acquire(rtld_bind_lock);
1720 objlist_remove_unref(&list_fini);
1722 /* Finish cleaning up the newly-unreferenced objects. */
1723 GDB_STATE(RT_DELETE,&root->linkmap);
1724 unload_object(root);
1725 GDB_STATE(RT_CONSISTENT,NULL);
1727 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
1728 wlock_release(rtld_bind_lock, lockstate);
1735 char *msg = error_message;
1736 error_message = NULL;
1741 * This function is deprecated and has no effect.
1744 dllockinit(void *context,
1745 void *(*lock_create)(void *context),
1746 void (*rlock_acquire)(void *lock),
1747 void (*wlock_acquire)(void *lock),
1748 void (*lock_release)(void *lock),
1749 void (*lock_destroy)(void *lock),
1750 void (*context_destroy)(void *context))
1752 static void *cur_context;
1753 static void (*cur_context_destroy)(void *);
1755 /* Just destroy the context from the previous call, if necessary. */
1756 if (cur_context_destroy != NULL)
1757 cur_context_destroy(cur_context);
1758 cur_context = context;
1759 cur_context_destroy = context_destroy;
1763 dlopen(const char *name, int mode)
1765 Obj_Entry **old_obj_tail;
1768 int result, lockstate;
1770 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
1771 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
1772 if (ld_tracing != NULL)
1773 environ = (char **)*get_program_var_addr("environ");
1775 objlist_init(&initlist);
1777 lockstate = wlock_acquire(rtld_bind_lock);
1778 GDB_STATE(RT_ADD,NULL);
1780 old_obj_tail = obj_tail;
1786 char *path = find_library(name, obj_main);
1788 obj = load_object(path);
1793 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
1794 objlist_push_tail(&list_global, obj);
1795 mode &= RTLD_MODEMASK;
1796 if (*old_obj_tail != NULL) { /* We loaded something new. */
1797 assert(*old_obj_tail == obj);
1799 result = load_needed_objects(obj);
1800 if (result != -1 && ld_tracing)
1804 (init_dag(obj), relocate_objects(obj, mode == RTLD_NOW,
1805 &obj_rtld)) == -1) {
1808 if (obj->refcount == 0)
1812 /* Make list of init functions to call. */
1813 initlist_add_objects(obj, &obj->next, &initlist);
1817 /* Bump the reference counts for objects on this DAG. */
1825 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
1827 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
1829 /* Call the init functions with no locks held. */
1830 wlock_release(rtld_bind_lock, lockstate);
1831 objlist_call_init(&initlist);
1832 lockstate = wlock_acquire(rtld_bind_lock);
1833 objlist_clear(&initlist);
1834 wlock_release(rtld_bind_lock, lockstate);
1837 trace_loaded_objects(obj);
1838 wlock_release(rtld_bind_lock, lockstate);
1843 dlsym(void *handle, const char *name)
1846 const Obj_Entry *obj, *defobj;
1851 hash = elf_hash(name);
1855 lockstate = rlock_acquire(rtld_bind_lock);
1856 if (handle == NULL || handle == RTLD_NEXT ||
1857 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
1860 retaddr = __builtin_return_address(0); /* __GNUC__ only */
1861 if ((obj = obj_from_addr(retaddr)) == NULL) {
1862 _rtld_error("Cannot determine caller's shared object");
1863 rlock_release(rtld_bind_lock, lockstate);
1866 if (handle == NULL) { /* Just the caller's shared object. */
1867 def = symlook_obj(name, hash, obj, true);
1869 } else if (handle == RTLD_NEXT || /* Objects after caller's */
1870 handle == RTLD_SELF) { /* ... caller included */
1871 if (handle == RTLD_NEXT)
1873 for (; obj != NULL; obj = obj->next) {
1874 if ((def = symlook_obj(name, hash, obj, true)) != NULL) {
1880 assert(handle == RTLD_DEFAULT);
1881 def = symlook_default(name, hash, obj, &defobj, true);
1884 if ((obj = dlcheck(handle)) == NULL) {
1885 rlock_release(rtld_bind_lock, lockstate);
1889 donelist_init(&donelist);
1890 if (obj->mainprog) {
1891 /* Search main program and all libraries loaded by it. */
1892 def = symlook_list(name, hash, &list_main, &defobj, true,
1897 /* Search the whole DAG rooted at the given object. */
1899 fake.obj = (Obj_Entry *)obj;
1901 def = symlook_needed(name, hash, &fake, &defobj, true,
1907 rlock_release(rtld_bind_lock, lockstate);
1910 * The value required by the caller is derived from the value
1911 * of the symbol. For the ia64 architecture, we need to
1912 * construct a function descriptor which the caller can use to
1913 * call the function with the right 'gp' value. For other
1914 * architectures and for non-functions, the value is simply
1915 * the relocated value of the symbol.
1917 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
1918 return make_function_pointer(def, defobj);
1920 return defobj->relocbase + def->st_value;
1923 _rtld_error("Undefined symbol \"%s\"", name);
1924 rlock_release(rtld_bind_lock, lockstate);
1929 dladdr(const void *addr, Dl_info *info)
1931 const Obj_Entry *obj;
1934 unsigned long symoffset;
1937 lockstate = rlock_acquire(rtld_bind_lock);
1938 obj = obj_from_addr(addr);
1940 _rtld_error("No shared object contains address");
1941 rlock_release(rtld_bind_lock, lockstate);
1944 info->dli_fname = obj->path;
1945 info->dli_fbase = obj->mapbase;
1946 info->dli_saddr = (void *)0;
1947 info->dli_sname = NULL;
1950 * Walk the symbol list looking for the symbol whose address is
1951 * closest to the address sent in.
1953 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
1954 def = obj->symtab + symoffset;
1957 * For skip the symbol if st_shndx is either SHN_UNDEF or
1960 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
1964 * If the symbol is greater than the specified address, or if it
1965 * is further away from addr than the current nearest symbol,
1968 symbol_addr = obj->relocbase + def->st_value;
1969 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
1972 /* Update our idea of the nearest symbol. */
1973 info->dli_sname = obj->strtab + def->st_name;
1974 info->dli_saddr = symbol_addr;
1977 if (info->dli_saddr == addr)
1980 rlock_release(rtld_bind_lock, lockstate);
1985 dlinfo(void *handle, int request, void *p)
1987 const Obj_Entry *obj;
1988 int error, lockstate;
1990 lockstate = rlock_acquire(rtld_bind_lock);
1992 if (handle == NULL || handle == RTLD_SELF) {
1995 retaddr = __builtin_return_address(0); /* __GNUC__ only */
1996 if ((obj = obj_from_addr(retaddr)) == NULL)
1997 _rtld_error("Cannot determine caller's shared object");
1999 obj = dlcheck(handle);
2002 rlock_release(rtld_bind_lock, lockstate);
2008 case RTLD_DI_LINKMAP:
2009 *((struct link_map const **)p) = &obj->linkmap;
2011 case RTLD_DI_ORIGIN:
2012 error = rtld_dirname(obj->path, p);
2015 case RTLD_DI_SERINFOSIZE:
2016 case RTLD_DI_SERINFO:
2017 error = do_search_info(obj, request, (struct dl_serinfo *)p);
2021 _rtld_error("Invalid request %d passed to dlinfo()", request);
2025 rlock_release(rtld_bind_lock, lockstate);
2030 struct fill_search_info_args {
2033 Dl_serinfo *serinfo;
2034 Dl_serpath *serpath;
2039 fill_search_info(const char *dir, size_t dirlen, void *param)
2041 struct fill_search_info_args *arg;
2045 if (arg->request == RTLD_DI_SERINFOSIZE) {
2046 arg->serinfo->dls_cnt ++;
2047 arg->serinfo->dls_size += sizeof(Dl_serpath) + dirlen + 1;
2049 struct dl_serpath *s_entry;
2051 s_entry = arg->serpath;
2052 s_entry->dls_name = arg->strspace;
2053 s_entry->dls_flags = arg->flags;
2055 strncpy(arg->strspace, dir, dirlen);
2056 arg->strspace[dirlen] = '\0';
2058 arg->strspace += dirlen + 1;
2066 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
2068 struct dl_serinfo _info;
2069 struct fill_search_info_args args;
2071 args.request = RTLD_DI_SERINFOSIZE;
2072 args.serinfo = &_info;
2074 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2077 path_enumerate(ld_library_path, fill_search_info, &args);
2078 path_enumerate(obj->rpath, fill_search_info, &args);
2079 path_enumerate(gethints(), fill_search_info, &args);
2080 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
2083 if (request == RTLD_DI_SERINFOSIZE) {
2084 info->dls_size = _info.dls_size;
2085 info->dls_cnt = _info.dls_cnt;
2089 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
2090 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
2094 args.request = RTLD_DI_SERINFO;
2095 args.serinfo = info;
2096 args.serpath = &info->dls_serpath[0];
2097 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
2099 args.flags = LA_SER_LIBPATH;
2100 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
2103 args.flags = LA_SER_RUNPATH;
2104 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
2107 args.flags = LA_SER_CONFIG;
2108 if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
2111 args.flags = LA_SER_DEFAULT;
2112 if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
2118 rtld_dirname(const char *path, char *bname)
2122 /* Empty or NULL string gets treated as "." */
2123 if (path == NULL || *path == '\0') {
2129 /* Strip trailing slashes */
2130 endp = path + strlen(path) - 1;
2131 while (endp > path && *endp == '/')
2134 /* Find the start of the dir */
2135 while (endp > path && *endp != '/')
2138 /* Either the dir is "/" or there are no slashes */
2140 bname[0] = *endp == '/' ? '/' : '.';
2146 } while (endp > path && *endp == '/');
2149 if (endp - path + 2 > PATH_MAX)
2151 _rtld_error("Filename is too long: %s", path);
2155 strncpy(bname, path, endp - path + 1);
2156 bname[endp - path + 1] = '\0';
2161 linkmap_add(Obj_Entry *obj)
2163 struct link_map *l = &obj->linkmap;
2164 struct link_map *prev;
2166 obj->linkmap.l_name = obj->path;
2167 obj->linkmap.l_addr = obj->mapbase;
2168 obj->linkmap.l_ld = obj->dynamic;
2170 /* GDB needs load offset on MIPS to use the symbols */
2171 obj->linkmap.l_offs = obj->relocbase;
2174 if (r_debug.r_map == NULL) {
2180 * Scan to the end of the list, but not past the entry for the
2181 * dynamic linker, which we want to keep at the very end.
2183 for (prev = r_debug.r_map;
2184 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
2185 prev = prev->l_next)
2188 /* Link in the new entry. */
2190 l->l_next = prev->l_next;
2191 if (l->l_next != NULL)
2192 l->l_next->l_prev = l;
2197 linkmap_delete(Obj_Entry *obj)
2199 struct link_map *l = &obj->linkmap;
2201 if (l->l_prev == NULL) {
2202 if ((r_debug.r_map = l->l_next) != NULL)
2203 l->l_next->l_prev = NULL;
2207 if ((l->l_prev->l_next = l->l_next) != NULL)
2208 l->l_next->l_prev = l->l_prev;
2212 * Function for the debugger to set a breakpoint on to gain control.
2214 * The two parameters allow the debugger to easily find and determine
2215 * what the runtime loader is doing and to whom it is doing it.
2217 * When the loadhook trap is hit (r_debug_state, set at program
2218 * initialization), the arguments can be found on the stack:
2220 * +8 struct link_map *m
2221 * +4 struct r_debug *rd
2225 r_debug_state(struct r_debug* rd, struct link_map *m)
2230 * Get address of the pointer variable in the main program.
2232 static const void **
2233 get_program_var_addr(const char *name)
2235 const Obj_Entry *obj;
2238 hash = elf_hash(name);
2239 for (obj = obj_main; obj != NULL; obj = obj->next) {
2242 if ((def = symlook_obj(name, hash, obj, false)) != NULL) {
2245 addr = (const void **)(obj->relocbase + def->st_value);
2253 * Set a pointer variable in the main program to the given value. This
2254 * is used to set key variables such as "environ" before any of the
2255 * init functions are called.
2258 set_program_var(const char *name, const void *value)
2262 if ((addr = get_program_var_addr(name)) != NULL) {
2263 dbg("\"%s\": *%p <-- %p", name, addr, value);
2269 * Given a symbol name in a referencing object, find the corresponding
2270 * definition of the symbol. Returns a pointer to the symbol, or NULL if
2271 * no definition was found. Returns a pointer to the Obj_Entry of the
2272 * defining object via the reference parameter DEFOBJ_OUT.
2274 static const Elf_Sym *
2275 symlook_default(const char *name, unsigned long hash,
2276 const Obj_Entry *refobj, const Obj_Entry **defobj_out, bool in_plt)
2280 const Elf_Sym *symp;
2281 const Obj_Entry *obj;
2282 const Obj_Entry *defobj;
2283 const Objlist_Entry *elm;
2286 donelist_init(&donelist);
2288 /* Look first in the referencing object if linked symbolically. */
2289 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
2290 symp = symlook_obj(name, hash, refobj, in_plt);
2297 /* Search all objects loaded at program start up. */
2298 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2299 symp = symlook_list(name, hash, &list_main, &obj, in_plt, &donelist);
2301 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2307 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
2308 STAILQ_FOREACH(elm, &list_global, link) {
2309 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2311 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt,
2314 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2320 /* Search all dlopened DAGs containing the referencing object. */
2321 STAILQ_FOREACH(elm, &refobj->dldags, link) {
2322 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2324 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt,
2327 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2334 * Search the dynamic linker itself, and possibly resolve the
2335 * symbol from there. This is how the application links to
2336 * dynamic linker services such as dlopen. Only the values listed
2337 * in the "exports" array can be resolved from the dynamic linker.
2339 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2340 symp = symlook_obj(name, hash, &obj_rtld, in_plt);
2341 if (symp != NULL && is_exported(symp)) {
2348 *defobj_out = defobj;
2352 static const Elf_Sym *
2353 symlook_list(const char *name, unsigned long hash, const Objlist *objlist,
2354 const Obj_Entry **defobj_out, bool in_plt, DoneList *dlp)
2356 const Elf_Sym *symp;
2358 const Obj_Entry *defobj;
2359 const Objlist_Entry *elm;
2363 STAILQ_FOREACH(elm, objlist, link) {
2364 if (donelist_check(dlp, elm->obj))
2366 if ((symp = symlook_obj(name, hash, elm->obj, in_plt)) != NULL) {
2367 if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
2370 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2376 *defobj_out = defobj;
2381 * Search the symbol table of a shared object and all objects needed
2382 * by it for a symbol of the given name. Search order is
2383 * breadth-first. Returns a pointer to the symbol, or NULL if no
2384 * definition was found.
2386 static const Elf_Sym *
2387 symlook_needed(const char *name, unsigned long hash, const Needed_Entry *needed,
2388 const Obj_Entry **defobj_out, bool in_plt, DoneList *dlp)
2390 const Elf_Sym *def, *def_w;
2391 const Needed_Entry *n;
2392 const Obj_Entry *obj, *defobj, *defobj1;
2396 for (n = needed; n != NULL; n = n->next) {
2397 if ((obj = n->obj) == NULL ||
2398 donelist_check(dlp, obj) ||
2399 (def = symlook_obj(name, hash, obj, in_plt)) == NULL)
2402 if (ELF_ST_BIND(def->st_info) != STB_WEAK) {
2403 *defobj_out = defobj;
2408 * There we come when either symbol definition is not found in
2409 * directly needed objects, or found symbol is weak.
2411 for (n = needed; n != NULL; n = n->next) {
2412 if ((obj = n->obj) == NULL)
2414 def_w = symlook_needed(name, hash, obj->needed, &defobj1,
2418 if (def == NULL || ELF_ST_BIND(def_w->st_info) != STB_WEAK) {
2422 if (ELF_ST_BIND(def_w->st_info) != STB_WEAK)
2426 *defobj_out = defobj;
2431 * Search the symbol table of a single shared object for a symbol of
2432 * the given name. Returns a pointer to the symbol, or NULL if no
2433 * definition was found.
2435 * The symbol's hash value is passed in for efficiency reasons; that
2436 * eliminates many recomputations of the hash value.
2439 symlook_obj(const char *name, unsigned long hash, const Obj_Entry *obj,
2442 if (obj->buckets != NULL) {
2443 unsigned long symnum = obj->buckets[hash % obj->nbuckets];
2445 while (symnum != STN_UNDEF) {
2446 const Elf_Sym *symp;
2449 if (symnum >= obj->nchains)
2450 return NULL; /* Bad object */
2451 symp = obj->symtab + symnum;
2452 strp = obj->strtab + symp->st_name;
2454 if (name[0] == strp[0] && strcmp(name, strp) == 0)
2455 return symp->st_shndx != SHN_UNDEF ||
2456 (!in_plt && symp->st_value != 0 &&
2457 ELF_ST_TYPE(symp->st_info) == STT_FUNC) ? symp : NULL;
2459 symnum = obj->chains[symnum];
2466 trace_loaded_objects(Obj_Entry *obj)
2468 char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
2471 if ((main_local = getenv(LD_ "TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
2474 if ((fmt1 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT1")) == NULL)
2475 fmt1 = "\t%o => %p (%x)\n";
2477 if ((fmt2 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT2")) == NULL)
2478 fmt2 = "\t%o (%x)\n";
2480 list_containers = getenv(LD_ "TRACE_LOADED_OBJECTS_ALL");
2482 for (; obj; obj = obj->next) {
2483 Needed_Entry *needed;
2487 if (list_containers && obj->needed != NULL)
2488 printf("%s:\n", obj->path);
2489 for (needed = obj->needed; needed; needed = needed->next) {
2490 if (needed->obj != NULL) {
2491 if (needed->obj->traced && !list_containers)
2493 needed->obj->traced = true;
2494 path = needed->obj->path;
2498 name = (char *)obj->strtab + needed->name;
2499 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
2501 fmt = is_lib ? fmt1 : fmt2;
2502 while ((c = *fmt++) != '\0') {
2528 printf("%s", main_local);
2531 printf("%s", obj_main->path);
2538 printf("%d", sodp->sod_major);
2541 printf("%d", sodp->sod_minor);
2548 printf("%p", needed->obj ? needed->obj->mapbase : 0);
2560 * Unload a dlopened object and its dependencies from memory and from
2561 * our data structures. It is assumed that the DAG rooted in the
2562 * object has already been unreferenced, and that the object has a
2563 * reference count of 0.
2566 unload_object(Obj_Entry *root)
2571 assert(root->refcount == 0);
2574 * Pass over the DAG removing unreferenced objects from
2575 * appropriate lists.
2577 unlink_object(root);
2579 /* Unmap all objects that are no longer referenced. */
2580 linkp = &obj_list->next;
2581 while ((obj = *linkp) != NULL) {
2582 if (obj->refcount == 0) {
2583 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
2585 dbg("unloading \"%s\"", obj->path);
2586 munmap(obj->mapbase, obj->mapsize);
2587 linkmap_delete(obj);
2598 unlink_object(Obj_Entry *root)
2602 if (root->refcount == 0) {
2603 /* Remove the object from the RTLD_GLOBAL list. */
2604 objlist_remove(&list_global, root);
2606 /* Remove the object from all objects' DAG lists. */
2607 STAILQ_FOREACH(elm, &root->dagmembers , link) {
2608 objlist_remove(&elm->obj->dldags, root);
2609 if (elm->obj != root)
2610 unlink_object(elm->obj);
2616 ref_dag(Obj_Entry *root)
2620 STAILQ_FOREACH(elm, &root->dagmembers , link)
2621 elm->obj->refcount++;
2625 unref_dag(Obj_Entry *root)
2629 STAILQ_FOREACH(elm, &root->dagmembers , link)
2630 elm->obj->refcount--;
2634 * Common code for MD __tls_get_addr().
2637 tls_get_addr_common(Elf_Addr** dtvp, int index, size_t offset)
2639 Elf_Addr* dtv = *dtvp;
2642 /* Check dtv generation in case new modules have arrived */
2643 if (dtv[0] != tls_dtv_generation) {
2647 lockstate = wlock_acquire(rtld_bind_lock);
2648 newdtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
2650 if (to_copy > tls_max_index)
2651 to_copy = tls_max_index;
2652 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
2653 newdtv[0] = tls_dtv_generation;
2654 newdtv[1] = tls_max_index;
2656 wlock_release(rtld_bind_lock, lockstate);
2660 /* Dynamically allocate module TLS if necessary */
2661 if (!dtv[index + 1]) {
2662 /* Signal safe, wlock will block out signals. */
2663 lockstate = wlock_acquire(rtld_bind_lock);
2664 if (!dtv[index + 1])
2665 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
2666 wlock_release(rtld_bind_lock, lockstate);
2668 return (void*) (dtv[index + 1] + offset);
2671 /* XXX not sure what variants to use for arm. */
2673 #if defined(__ia64__) || defined(__alpha__) || defined(__powerpc__)
2676 * Allocate Static TLS using the Variant I method.
2679 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
2688 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
2691 assert(tcbsize >= TLS_TCB_SIZE);
2692 tcb = calloc(1, tls_static_space - TLS_TCB_SIZE + tcbsize);
2693 tls = (Elf_Addr **)(tcb + tcbsize - TLS_TCB_SIZE);
2695 if (oldtcb != NULL) {
2696 memcpy(tls, oldtcb, tls_static_space);
2699 /* Adjust the DTV. */
2701 for (i = 0; i < dtv[1]; i++) {
2702 if (dtv[i+2] >= (Elf_Addr)oldtcb &&
2703 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
2704 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tls;
2708 dtv = calloc(tls_max_index + 2, sizeof(Elf_Addr));
2710 dtv[0] = tls_dtv_generation;
2711 dtv[1] = tls_max_index;
2713 for (obj = objs; obj; obj = obj->next) {
2714 if (obj->tlsoffset) {
2715 addr = (Elf_Addr)tls + obj->tlsoffset;
2716 memset((void*) (addr + obj->tlsinitsize),
2717 0, obj->tlssize - obj->tlsinitsize);
2719 memcpy((void*) addr, obj->tlsinit,
2721 dtv[obj->tlsindex + 1] = addr;
2730 free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
2733 Elf_Addr tlsstart, tlsend;
2736 assert(tcbsize >= TLS_TCB_SIZE);
2738 tlsstart = (Elf_Addr)tcb + tcbsize - TLS_TCB_SIZE;
2739 tlsend = tlsstart + tls_static_space;
2741 dtv = *(Elf_Addr **)tlsstart;
2743 for (i = 0; i < dtvsize; i++) {
2744 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
2745 free((void*)dtv[i+2]);
2754 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) || \
2758 * Allocate Static TLS using the Variant II method.
2761 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
2766 Elf_Addr *dtv, *olddtv;
2767 Elf_Addr segbase, oldsegbase, addr;
2770 size = round(tls_static_space, tcbalign);
2772 assert(tcbsize >= 2*sizeof(Elf_Addr));
2773 tls = malloc(size + tcbsize);
2774 dtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
2776 segbase = (Elf_Addr)(tls + size);
2777 ((Elf_Addr*)segbase)[0] = segbase;
2778 ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
2780 dtv[0] = tls_dtv_generation;
2781 dtv[1] = tls_max_index;
2785 * Copy the static TLS block over whole.
2787 oldsegbase = (Elf_Addr) oldtls;
2788 memcpy((void *)(segbase - tls_static_space),
2789 (const void *)(oldsegbase - tls_static_space),
2793 * If any dynamic TLS blocks have been created tls_get_addr(),
2796 olddtv = ((Elf_Addr**)oldsegbase)[1];
2797 for (i = 0; i < olddtv[1]; i++) {
2798 if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
2799 dtv[i+2] = olddtv[i+2];
2805 * We assume that this block was the one we created with
2806 * allocate_initial_tls().
2808 free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
2810 for (obj = objs; obj; obj = obj->next) {
2811 if (obj->tlsoffset) {
2812 addr = segbase - obj->tlsoffset;
2813 memset((void*) (addr + obj->tlsinitsize),
2814 0, obj->tlssize - obj->tlsinitsize);
2816 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
2817 dtv[obj->tlsindex + 1] = addr;
2822 return (void*) segbase;
2826 free_tls(void *tls, size_t tcbsize, size_t tcbalign)
2831 Elf_Addr tlsstart, tlsend;
2834 * Figure out the size of the initial TLS block so that we can
2835 * find stuff which ___tls_get_addr() allocated dynamically.
2837 size = round(tls_static_space, tcbalign);
2839 dtv = ((Elf_Addr**)tls)[1];
2841 tlsend = (Elf_Addr) tls;
2842 tlsstart = tlsend - size;
2843 for (i = 0; i < dtvsize; i++) {
2844 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] > tlsend)) {
2845 free((void*) dtv[i+2]);
2849 free((void*) tlsstart);
2856 * Allocate TLS block for module with given index.
2859 allocate_module_tls(int index)
2864 for (obj = obj_list; obj; obj = obj->next) {
2865 if (obj->tlsindex == index)
2869 _rtld_error("Can't find module with TLS index %d", index);
2873 p = malloc(obj->tlssize);
2874 memcpy(p, obj->tlsinit, obj->tlsinitsize);
2875 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
2881 allocate_tls_offset(Obj_Entry *obj)
2888 if (obj->tlssize == 0) {
2889 obj->tls_done = true;
2893 if (obj->tlsindex == 1)
2894 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
2896 off = calculate_tls_offset(tls_last_offset, tls_last_size,
2897 obj->tlssize, obj->tlsalign);
2900 * If we have already fixed the size of the static TLS block, we
2901 * must stay within that size. When allocating the static TLS, we
2902 * leave a small amount of space spare to be used for dynamically
2903 * loading modules which use static TLS.
2905 if (tls_static_space) {
2906 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
2910 tls_last_offset = obj->tlsoffset = off;
2911 tls_last_size = obj->tlssize;
2912 obj->tls_done = true;
2918 free_tls_offset(Obj_Entry *obj)
2920 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) || \
2923 * If we were the last thing to allocate out of the static TLS
2924 * block, we give our space back to the 'allocator'. This is a
2925 * simplistic workaround to allow libGL.so.1 to be loaded and
2926 * unloaded multiple times. We only handle the Variant II
2927 * mechanism for now - this really needs a proper allocator.
2929 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
2930 == calculate_tls_end(tls_last_offset, tls_last_size)) {
2931 tls_last_offset -= obj->tlssize;
2938 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
2943 lockstate = wlock_acquire(rtld_bind_lock);
2944 ret = allocate_tls(obj_list, oldtls, tcbsize, tcbalign);
2945 wlock_release(rtld_bind_lock, lockstate);
2950 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
2954 lockstate = wlock_acquire(rtld_bind_lock);
2955 free_tls(tcb, tcbsize, tcbalign);
2956 wlock_release(rtld_bind_lock, lockstate);