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 ld_debug = getenv(LD_ "DEBUG");
347 libmap_disable = getenv(LD_ "LIBMAP_DISABLE") != NULL;
348 libmap_override = getenv(LD_ "LIBMAP");
349 ld_library_path = getenv(LD_ "LIBRARY_PATH");
350 ld_preload = getenv(LD_ "PRELOAD");
351 dangerous_ld_env = libmap_disable || (libmap_override != NULL) ||
352 (ld_library_path != NULL) || (ld_preload != NULL);
354 dangerous_ld_env = 0;
355 ld_tracing = getenv(LD_ "TRACE_LOADED_OBJECTS");
356 ld_utrace = getenv(LD_ "UTRACE");
358 if (ld_debug != NULL && *ld_debug != '\0')
360 dbg("%s is initialized, base address = %p", __progname,
361 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
362 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
363 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
366 * Load the main program, or process its program header if it is
369 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
370 int fd = aux_info[AT_EXECFD]->a_un.a_val;
371 dbg("loading main program");
372 obj_main = map_object(fd, argv0, NULL);
374 if (obj_main == NULL)
376 } else { /* Main program already loaded. */
377 const Elf_Phdr *phdr;
381 dbg("processing main program's program header");
382 assert(aux_info[AT_PHDR] != NULL);
383 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
384 assert(aux_info[AT_PHNUM] != NULL);
385 phnum = aux_info[AT_PHNUM]->a_un.a_val;
386 assert(aux_info[AT_PHENT] != NULL);
387 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
388 assert(aux_info[AT_ENTRY] != NULL);
389 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
390 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
394 obj_main->path = xstrdup(argv0);
395 obj_main->mainprog = true;
398 * Get the actual dynamic linker pathname from the executable if
399 * possible. (It should always be possible.) That ensures that
400 * gdb will find the right dynamic linker even if a non-standard
403 if (obj_main->interp != NULL &&
404 strcmp(obj_main->interp, obj_rtld.path) != 0) {
406 obj_rtld.path = xstrdup(obj_main->interp);
407 __progname = obj_rtld.path;
410 digest_dynamic(obj_main, 0);
412 linkmap_add(obj_main);
413 linkmap_add(&obj_rtld);
415 /* Link the main program into the list of objects. */
416 *obj_tail = obj_main;
417 obj_tail = &obj_main->next;
419 /* Make sure we don't call the main program's init and fini functions. */
420 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
422 /* Initialize a fake symbol for resolving undefined weak references. */
423 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
424 sym_zero.st_shndx = SHN_UNDEF;
427 libmap_disable = (bool)lm_init(libmap_override);
429 dbg("loading LD_PRELOAD libraries");
430 if (load_preload_objects() == -1)
432 preload_tail = obj_tail;
434 dbg("loading needed objects");
435 if (load_needed_objects(obj_main) == -1)
438 /* Make a list of all objects loaded at startup. */
439 for (obj = obj_list; obj != NULL; obj = obj->next) {
440 objlist_push_tail(&list_main, obj);
444 if (ld_tracing) { /* We're done */
445 trace_loaded_objects(obj_main);
449 if (getenv(LD_ "DUMP_REL_PRE") != NULL) {
450 dump_relocations(obj_main);
454 /* setup TLS for main thread */
455 dbg("initializing initial thread local storage");
456 STAILQ_FOREACH(entry, &list_main, link) {
458 * Allocate all the initial objects out of the static TLS
459 * block even if they didn't ask for it.
461 allocate_tls_offset(entry->obj);
463 allocate_initial_tls(obj_list);
465 if (relocate_objects(obj_main,
466 ld_bind_now != NULL && *ld_bind_now != '\0', &obj_rtld) == -1)
469 dbg("doing copy relocations");
470 if (do_copy_relocations(obj_main) == -1)
473 if (getenv(LD_ "DUMP_REL_POST") != NULL) {
474 dump_relocations(obj_main);
478 dbg("initializing key program variables");
479 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
480 set_program_var("environ", env);
482 dbg("initializing thread locks");
485 /* Make a list of init functions to call. */
486 objlist_init(&initlist);
487 initlist_add_objects(obj_list, preload_tail, &initlist);
489 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
491 objlist_call_init(&initlist);
492 lockstate = wlock_acquire(rtld_bind_lock);
493 objlist_clear(&initlist);
494 wlock_release(rtld_bind_lock, lockstate);
496 dbg("transferring control to program entry point = %p", obj_main->entry);
498 /* Return the exit procedure and the program entry point. */
499 *exit_proc = rtld_exit;
501 return (func_ptr_type) obj_main->entry;
505 _rtld_bind(Obj_Entry *obj, Elf_Size reloff)
509 const Obj_Entry *defobj;
514 lockstate = rlock_acquire(rtld_bind_lock);
516 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
518 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
520 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
521 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL);
525 target = (Elf_Addr)(defobj->relocbase + def->st_value);
527 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
528 defobj->strtab + def->st_name, basename(obj->path),
529 (void *)target, basename(defobj->path));
532 * Write the new contents for the jmpslot. Note that depending on
533 * architecture, the value which we need to return back to the
534 * lazy binding trampoline may or may not be the target
535 * address. The value returned from reloc_jmpslot() is the value
536 * that the trampoline needs.
538 target = reloc_jmpslot(where, target, defobj, obj, rel);
539 rlock_release(rtld_bind_lock, lockstate);
544 * Error reporting function. Use it like printf. If formats the message
545 * into a buffer, and sets things up so that the next call to dlerror()
546 * will return the message.
549 _rtld_error(const char *fmt, ...)
551 static char buf[512];
555 vsnprintf(buf, sizeof buf, fmt, ap);
561 * Return a dynamically-allocated copy of the current error message, if any.
566 return error_message == NULL ? NULL : xstrdup(error_message);
570 * Restore the current error message from a copy which was previously saved
571 * by errmsg_save(). The copy is freed.
574 errmsg_restore(char *saved_msg)
576 if (saved_msg == NULL)
577 error_message = NULL;
579 _rtld_error("%s", saved_msg);
585 basename(const char *name)
587 const char *p = strrchr(name, '/');
588 return p != NULL ? p + 1 : name;
594 const char *msg = dlerror();
602 * Process a shared object's DYNAMIC section, and save the important
603 * information in its Obj_Entry structure.
606 digest_dynamic(Obj_Entry *obj, int early)
609 Needed_Entry **needed_tail = &obj->needed;
610 const Elf_Dyn *dyn_rpath = NULL;
611 int plttype = DT_REL;
613 obj->bind_now = false;
614 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
615 switch (dynp->d_tag) {
618 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
622 obj->relsize = dynp->d_un.d_val;
626 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
630 obj->pltrel = (const Elf_Rel *)
631 (obj->relocbase + dynp->d_un.d_ptr);
635 obj->pltrelsize = dynp->d_un.d_val;
639 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
643 obj->relasize = dynp->d_un.d_val;
647 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
651 plttype = dynp->d_un.d_val;
652 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
656 obj->symtab = (const Elf_Sym *)
657 (obj->relocbase + dynp->d_un.d_ptr);
661 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
665 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
669 obj->strsize = dynp->d_un.d_val;
674 const Elf_Hashelt *hashtab = (const Elf_Hashelt *)
675 (obj->relocbase + dynp->d_un.d_ptr);
676 obj->nbuckets = hashtab[0];
677 obj->nchains = hashtab[1];
678 obj->buckets = hashtab + 2;
679 obj->chains = obj->buckets + obj->nbuckets;
685 Needed_Entry *nep = NEW(Needed_Entry);
686 nep->name = dynp->d_un.d_val;
691 needed_tail = &nep->next;
696 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
704 obj->symbolic = true;
708 case DT_RUNPATH: /* XXX: process separately */
710 * We have to wait until later to process this, because we
711 * might not have gotten the address of the string table yet.
717 /* Not used by the dynamic linker. */
721 obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
725 obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
729 /* XXX - not implemented yet */
731 dbg("Filling in DT_DEBUG entry");
732 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
736 if (dynp->d_un.d_val & DF_ORIGIN) {
737 obj->origin_path = xmalloc(PATH_MAX);
738 if (rtld_dirname(obj->path, obj->origin_path) == -1)
741 if (dynp->d_un.d_val & DF_SYMBOLIC)
742 obj->symbolic = true;
743 if (dynp->d_un.d_val & DF_TEXTREL)
745 if (dynp->d_un.d_val & DF_BIND_NOW)
746 obj->bind_now = true;
747 if (dynp->d_un.d_val & DF_STATIC_TLS)
753 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
762 if (plttype == DT_RELA) {
763 obj->pltrela = (const Elf_Rela *) obj->pltrel;
765 obj->pltrelasize = obj->pltrelsize;
769 if (dyn_rpath != NULL)
770 obj->rpath = obj->strtab + dyn_rpath->d_un.d_val;
774 * Process a shared object's program header. This is used only for the
775 * main program, when the kernel has already loaded the main program
776 * into memory before calling the dynamic linker. It creates and
777 * returns an Obj_Entry structure.
780 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
783 const Elf_Phdr *phlimit = phdr + phnum;
788 for (ph = phdr; ph < phlimit; ph++) {
789 switch (ph->p_type) {
792 if ((const Elf_Phdr *)ph->p_vaddr != phdr) {
793 _rtld_error("%s: invalid PT_PHDR", path);
796 obj->phdr = (const Elf_Phdr *) ph->p_vaddr;
797 obj->phsize = ph->p_memsz;
801 obj->interp = (const char *) ph->p_vaddr;
805 if (nsegs == 0) { /* First load segment */
806 obj->vaddrbase = trunc_page(ph->p_vaddr);
807 obj->mapbase = (caddr_t) obj->vaddrbase;
808 obj->relocbase = obj->mapbase - obj->vaddrbase;
809 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
811 } else { /* Last load segment */
812 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
819 obj->dynamic = (const Elf_Dyn *) ph->p_vaddr;
824 obj->tlssize = ph->p_memsz;
825 obj->tlsalign = ph->p_align;
826 obj->tlsinitsize = ph->p_filesz;
827 obj->tlsinit = (void*) ph->p_vaddr;
832 _rtld_error("%s: too few PT_LOAD segments", path);
841 dlcheck(void *handle)
845 for (obj = obj_list; obj != NULL; obj = obj->next)
846 if (obj == (Obj_Entry *) handle)
849 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
850 _rtld_error("Invalid shared object handle %p", handle);
857 * If the given object is already in the donelist, return true. Otherwise
858 * add the object to the list and return false.
861 donelist_check(DoneList *dlp, const Obj_Entry *obj)
865 for (i = 0; i < dlp->num_used; i++)
866 if (dlp->objs[i] == obj)
869 * Our donelist allocation should always be sufficient. But if
870 * our threads locking isn't working properly, more shared objects
871 * could have been loaded since we allocated the list. That should
872 * never happen, but we'll handle it properly just in case it does.
874 if (dlp->num_used < dlp->num_alloc)
875 dlp->objs[dlp->num_used++] = obj;
880 * Hash function for symbol table lookup. Don't even think about changing
881 * this. It is specified by the System V ABI.
884 elf_hash(const char *name)
886 const unsigned char *p = (const unsigned char *) name;
892 if ((g = h & 0xf0000000) != 0)
900 * Find the library with the given name, and return its full pathname.
901 * The returned string is dynamically allocated. Generates an error
902 * message and returns NULL if the library cannot be found.
904 * If the second argument is non-NULL, then it refers to an already-
905 * loaded shared object, whose library search path will be searched.
907 * The search order is:
909 * rpath in the referencing file
914 find_library(const char *xname, const Obj_Entry *refobj)
919 if (strchr(xname, '/') != NULL) { /* Hard coded pathname */
920 if (xname[0] != '/' && !trust) {
921 _rtld_error("Absolute pathname required for shared object \"%s\"",
925 return xstrdup(xname);
928 if (libmap_disable || (refobj == NULL) ||
929 (name = lm_find(refobj->path, xname)) == NULL)
930 name = (char *)xname;
932 dbg(" Searching for \"%s\"", name);
934 if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
936 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
937 (pathname = search_library_path(name, gethints())) != NULL ||
938 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
941 if(refobj != NULL && refobj->path != NULL) {
942 _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
943 name, basename(refobj->path));
945 _rtld_error("Shared object \"%s\" not found", name);
951 * Given a symbol number in a referencing object, find the corresponding
952 * definition of the symbol. Returns a pointer to the symbol, or NULL if
953 * no definition was found. Returns a pointer to the Obj_Entry of the
954 * defining object via the reference parameter DEFOBJ_OUT.
957 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
958 const Obj_Entry **defobj_out, bool in_plt, SymCache *cache)
962 const Obj_Entry *defobj;
967 * If we have already found this symbol, get the information from
970 if (symnum >= refobj->nchains)
971 return NULL; /* Bad object */
972 if (cache != NULL && cache[symnum].sym != NULL) {
973 *defobj_out = cache[symnum].obj;
974 return cache[symnum].sym;
977 ref = refobj->symtab + symnum;
978 name = refobj->strtab + ref->st_name;
982 * We don't have to do a full scale lookup if the symbol is local.
983 * We know it will bind to the instance in this load module; to
984 * which we already have a pointer (ie ref). By not doing a lookup,
985 * we not only improve performance, but it also avoids unresolvable
986 * symbols when local symbols are not in the hash table. This has
987 * been seen with the ia64 toolchain.
989 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
990 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
991 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
994 hash = elf_hash(name);
995 def = symlook_default(name, hash, refobj, &defobj, in_plt);
1002 * If we found no definition and the reference is weak, treat the
1003 * symbol as having the value zero.
1005 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1011 *defobj_out = defobj;
1012 /* Record the information in the cache to avoid subsequent lookups. */
1013 if (cache != NULL) {
1014 cache[symnum].sym = def;
1015 cache[symnum].obj = defobj;
1018 if (refobj != &obj_rtld)
1019 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1025 * Return the search path from the ldconfig hints file, reading it if
1026 * necessary. Returns NULL if there are problems with the hints file,
1027 * or if the search path there is empty.
1034 if (hints == NULL) {
1036 struct elfhints_hdr hdr;
1039 /* Keep from trying again in case the hints file is bad. */
1042 if ((fd = open(_PATH_ELF_HINTS, O_RDONLY)) == -1)
1044 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1045 hdr.magic != ELFHINTS_MAGIC ||
1050 p = xmalloc(hdr.dirlistlen + 1);
1051 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1052 read(fd, p, hdr.dirlistlen + 1) != (ssize_t)hdr.dirlistlen + 1) {
1060 return hints[0] != '\0' ? hints : NULL;
1064 init_dag(Obj_Entry *root)
1068 donelist_init(&donelist);
1069 init_dag1(root, root, &donelist);
1073 init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *dlp)
1075 const Needed_Entry *needed;
1077 if (donelist_check(dlp, obj))
1081 objlist_push_tail(&obj->dldags, root);
1082 objlist_push_tail(&root->dagmembers, obj);
1083 for (needed = obj->needed; needed != NULL; needed = needed->next)
1084 if (needed->obj != NULL)
1085 init_dag1(root, needed->obj, dlp);
1089 * Initialize the dynamic linker. The argument is the address at which
1090 * the dynamic linker has been mapped into memory. The primary task of
1091 * this function is to relocate the dynamic linker.
1094 init_rtld(caddr_t mapbase)
1096 Obj_Entry objtmp; /* Temporary rtld object */
1099 * Conjure up an Obj_Entry structure for the dynamic linker.
1101 * The "path" member can't be initialized yet because string constatns
1102 * cannot yet be acessed. Below we will set it correctly.
1104 memset(&objtmp, 0, sizeof(objtmp));
1107 objtmp.mapbase = mapbase;
1109 objtmp.relocbase = mapbase;
1111 if (RTLD_IS_DYNAMIC()) {
1112 objtmp.dynamic = rtld_dynamic(&objtmp);
1113 digest_dynamic(&objtmp, 1);
1114 assert(objtmp.needed == NULL);
1115 assert(!objtmp.textrel);
1118 * Temporarily put the dynamic linker entry into the object list, so
1119 * that symbols can be found.
1122 relocate_objects(&objtmp, true, &objtmp);
1125 /* Initialize the object list. */
1126 obj_tail = &obj_list;
1128 /* Now that non-local variables can be accesses, copy out obj_rtld. */
1129 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1131 /* Replace the path with a dynamically allocated copy. */
1132 obj_rtld.path = xstrdup(PATH_RTLD);
1134 r_debug.r_brk = r_debug_state;
1135 r_debug.r_state = RT_CONSISTENT;
1139 * Add the init functions from a needed object list (and its recursive
1140 * needed objects) to "list". This is not used directly; it is a helper
1141 * function for initlist_add_objects(). The write lock must be held
1142 * when this function is called.
1145 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1147 /* Recursively process the successor needed objects. */
1148 if (needed->next != NULL)
1149 initlist_add_neededs(needed->next, list);
1151 /* Process the current needed object. */
1152 if (needed->obj != NULL)
1153 initlist_add_objects(needed->obj, &needed->obj->next, list);
1157 * Scan all of the DAGs rooted in the range of objects from "obj" to
1158 * "tail" and add their init functions to "list". This recurses over
1159 * the DAGs and ensure the proper init ordering such that each object's
1160 * needed libraries are initialized before the object itself. At the
1161 * same time, this function adds the objects to the global finalization
1162 * list "list_fini" in the opposite order. The write lock must be
1163 * held when this function is called.
1166 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1170 obj->init_done = true;
1172 /* Recursively process the successor objects. */
1173 if (&obj->next != tail)
1174 initlist_add_objects(obj->next, tail, list);
1176 /* Recursively process the needed objects. */
1177 if (obj->needed != NULL)
1178 initlist_add_neededs(obj->needed, list);
1180 /* Add the object to the init list. */
1181 if (obj->init != (Elf_Addr)NULL)
1182 objlist_push_tail(list, obj);
1184 /* Add the object to the global fini list in the reverse order. */
1185 if (obj->fini != (Elf_Addr)NULL)
1186 objlist_push_head(&list_fini, obj);
1190 #define FPTR_TARGET(f) ((Elf_Addr) (f))
1194 is_exported(const Elf_Sym *def)
1197 const func_ptr_type *p;
1199 value = (Elf_Addr)(obj_rtld.relocbase + def->st_value);
1200 for (p = exports; *p != NULL; p++)
1201 if (FPTR_TARGET(*p) == value)
1207 * Given a shared object, traverse its list of needed objects, and load
1208 * each of them. Returns 0 on success. Generates an error message and
1209 * returns -1 on failure.
1212 load_needed_objects(Obj_Entry *first)
1216 for (obj = first; obj != NULL; obj = obj->next) {
1217 Needed_Entry *needed;
1219 for (needed = obj->needed; needed != NULL; needed = needed->next) {
1220 const char *name = obj->strtab + needed->name;
1221 char *path = find_library(name, obj);
1224 if (path == NULL && !ld_tracing)
1228 needed->obj = load_object(path);
1229 if (needed->obj == NULL && !ld_tracing)
1230 return -1; /* XXX - cleanup */
1239 load_preload_objects(void)
1241 char *p = ld_preload;
1242 static const char delim[] = " \t:;";
1247 p += strspn(p, delim);
1248 while (*p != '\0') {
1249 size_t len = strcspn(p, delim);
1255 if ((path = find_library(p, NULL)) == NULL)
1257 if (load_object(path) == NULL)
1258 return -1; /* XXX - cleanup */
1261 p += strspn(p, delim);
1263 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
1268 * Load a shared object into memory, if it is not already loaded. The
1269 * argument must be a string allocated on the heap. This function assumes
1270 * responsibility for freeing it when necessary.
1272 * Returns a pointer to the Obj_Entry for the object. Returns NULL
1276 load_object(char *path)
1283 for (obj = obj_list->next; obj != NULL; obj = obj->next)
1284 if (strcmp(obj->path, path) == 0)
1288 * If we didn't find a match by pathname, open the file and check
1289 * again by device and inode. This avoids false mismatches caused
1290 * by multiple links or ".." in pathnames.
1292 * To avoid a race, we open the file and use fstat() rather than
1296 if ((fd = open(path, O_RDONLY)) == -1) {
1297 _rtld_error("Cannot open \"%s\"", path);
1300 if (fstat(fd, &sb) == -1) {
1301 _rtld_error("Cannot fstat \"%s\"", path);
1305 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
1306 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev) {
1313 if (obj == NULL) { /* First use of this object, so we must map it in */
1315 * but first, make sure that environment variables haven't been
1316 * used to circumvent the noexec flag on a filesystem.
1318 if (dangerous_ld_env) {
1319 if (fstatfs(fd, &fs) != 0) {
1320 _rtld_error("Cannot fstatfs \"%s\"", path);
1324 if (fs.f_flags & MNT_NOEXEC) {
1325 _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
1330 dbg("loading \"%s\"", path);
1331 obj = map_object(fd, path, &sb);
1339 digest_dynamic(obj, 0);
1342 obj_tail = &obj->next;
1344 linkmap_add(obj); /* for GDB & dlinfo() */
1346 dbg(" %p .. %p: %s", obj->mapbase,
1347 obj->mapbase + obj->mapsize - 1, obj->path);
1349 dbg(" WARNING: %s has impure text", obj->path);
1350 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
1359 obj_from_addr(const void *addr)
1363 for (obj = obj_list; obj != NULL; obj = obj->next) {
1364 if (addr < (void *) obj->mapbase)
1366 if (addr < (void *) (obj->mapbase + obj->mapsize))
1373 * Call the finalization functions for each of the objects in "list"
1374 * which are unreferenced. All of the objects are expected to have
1375 * non-NULL fini functions.
1378 objlist_call_fini(Objlist *list)
1384 * Preserve the current error message since a fini function might
1385 * call into the dynamic linker and overwrite it.
1387 saved_msg = errmsg_save();
1388 STAILQ_FOREACH(elm, list, link) {
1389 if (elm->obj->refcount == 0) {
1390 dbg("calling fini function for %s at %p", elm->obj->path,
1391 (void *)elm->obj->fini);
1392 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini, 0, 0,
1394 call_initfini_pointer(elm->obj, elm->obj->fini);
1397 errmsg_restore(saved_msg);
1401 * Call the initialization functions for each of the objects in
1402 * "list". All of the objects are expected to have non-NULL init
1406 objlist_call_init(Objlist *list)
1412 * Preserve the current error message since an init function might
1413 * call into the dynamic linker and overwrite it.
1415 saved_msg = errmsg_save();
1416 STAILQ_FOREACH(elm, list, link) {
1417 dbg("calling init function for %s at %p", elm->obj->path,
1418 (void *)elm->obj->init);
1419 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init, 0, 0,
1421 call_initfini_pointer(elm->obj, elm->obj->init);
1423 errmsg_restore(saved_msg);
1427 objlist_clear(Objlist *list)
1431 while (!STAILQ_EMPTY(list)) {
1432 elm = STAILQ_FIRST(list);
1433 STAILQ_REMOVE_HEAD(list, link);
1438 static Objlist_Entry *
1439 objlist_find(Objlist *list, const Obj_Entry *obj)
1443 STAILQ_FOREACH(elm, list, link)
1444 if (elm->obj == obj)
1450 objlist_init(Objlist *list)
1456 objlist_push_head(Objlist *list, Obj_Entry *obj)
1460 elm = NEW(Objlist_Entry);
1462 STAILQ_INSERT_HEAD(list, elm, link);
1466 objlist_push_tail(Objlist *list, Obj_Entry *obj)
1470 elm = NEW(Objlist_Entry);
1472 STAILQ_INSERT_TAIL(list, elm, link);
1476 objlist_remove(Objlist *list, Obj_Entry *obj)
1480 if ((elm = objlist_find(list, obj)) != NULL) {
1481 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1487 * Remove all of the unreferenced objects from "list".
1490 objlist_remove_unref(Objlist *list)
1495 STAILQ_INIT(&newlist);
1496 while (!STAILQ_EMPTY(list)) {
1497 elm = STAILQ_FIRST(list);
1498 STAILQ_REMOVE_HEAD(list, link);
1499 if (elm->obj->refcount == 0)
1502 STAILQ_INSERT_TAIL(&newlist, elm, link);
1508 * Relocate newly-loaded shared objects. The argument is a pointer to
1509 * the Obj_Entry for the first such object. All objects from the first
1510 * to the end of the list of objects are relocated. Returns 0 on success,
1514 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj)
1518 for (obj = first; obj != NULL; obj = obj->next) {
1520 dbg("relocating \"%s\"", obj->path);
1521 if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
1522 obj->symtab == NULL || obj->strtab == NULL) {
1523 _rtld_error("%s: Shared object has no run-time symbol table",
1529 /* There are relocations to the write-protected text segment. */
1530 if (mprotect(obj->mapbase, obj->textsize,
1531 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
1532 _rtld_error("%s: Cannot write-enable text segment: %s",
1533 obj->path, strerror(errno));
1538 /* Process the non-PLT relocations. */
1539 if (reloc_non_plt(obj, rtldobj))
1542 if (obj->textrel) { /* Re-protected the text segment. */
1543 if (mprotect(obj->mapbase, obj->textsize,
1544 PROT_READ|PROT_EXEC) == -1) {
1545 _rtld_error("%s: Cannot write-protect text segment: %s",
1546 obj->path, strerror(errno));
1551 /* Process the PLT relocations. */
1552 if (reloc_plt(obj) == -1)
1554 /* Relocate the jump slots if we are doing immediate binding. */
1555 if (obj->bind_now || bind_now)
1556 if (reloc_jmpslots(obj) == -1)
1561 * Set up the magic number and version in the Obj_Entry. These
1562 * were checked in the crt1.o from the original ElfKit, so we
1563 * set them for backward compatibility.
1565 obj->magic = RTLD_MAGIC;
1566 obj->version = RTLD_VERSION;
1568 /* Set the special PLT or GOT entries. */
1576 * Cleanup procedure. It will be called (by the atexit mechanism) just
1577 * before the process exits.
1585 /* Clear all the reference counts so the fini functions will be called. */
1586 for (obj = obj_list; obj != NULL; obj = obj->next)
1588 objlist_call_fini(&list_fini);
1589 /* No need to remove the items from the list, since we are exiting. */
1590 if (!libmap_disable)
1595 path_enumerate(const char *path, path_enum_proc callback, void *arg)
1603 path += strspn(path, ":;");
1604 while (*path != '\0') {
1608 len = strcspn(path, ":;");
1610 trans = lm_findn(NULL, path, len);
1612 res = callback(trans, strlen(trans), arg);
1615 res = callback(path, len, arg);
1621 path += strspn(path, ":;");
1627 struct try_library_args {
1635 try_library_path(const char *dir, size_t dirlen, void *param)
1637 struct try_library_args *arg;
1640 if (*dir == '/' || trust) {
1643 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
1646 pathname = arg->buffer;
1647 strncpy(pathname, dir, dirlen);
1648 pathname[dirlen] = '/';
1649 strcpy(pathname + dirlen + 1, arg->name);
1651 dbg(" Trying \"%s\"", pathname);
1652 if (access(pathname, F_OK) == 0) { /* We found it */
1653 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
1654 strcpy(pathname, arg->buffer);
1662 search_library_path(const char *name, const char *path)
1665 struct try_library_args arg;
1671 arg.namelen = strlen(name);
1672 arg.buffer = xmalloc(PATH_MAX);
1673 arg.buflen = PATH_MAX;
1675 p = path_enumerate(path, try_library_path, &arg);
1683 dlclose(void *handle)
1688 lockstate = wlock_acquire(rtld_bind_lock);
1689 root = dlcheck(handle);
1691 wlock_release(rtld_bind_lock, lockstate);
1694 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
1697 /* Unreference the object and its dependencies. */
1698 root->dl_refcount--;
1702 if (root->refcount == 0) {
1704 * The object is no longer referenced, so we must unload it.
1705 * First, call the fini functions with no locks held.
1707 wlock_release(rtld_bind_lock, lockstate);
1708 objlist_call_fini(&list_fini);
1709 lockstate = wlock_acquire(rtld_bind_lock);
1710 objlist_remove_unref(&list_fini);
1712 /* Finish cleaning up the newly-unreferenced objects. */
1713 GDB_STATE(RT_DELETE,&root->linkmap);
1714 unload_object(root);
1715 GDB_STATE(RT_CONSISTENT,NULL);
1717 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
1718 wlock_release(rtld_bind_lock, lockstate);
1725 char *msg = error_message;
1726 error_message = NULL;
1731 * This function is deprecated and has no effect.
1734 dllockinit(void *context,
1735 void *(*lock_create)(void *context),
1736 void (*rlock_acquire)(void *lock),
1737 void (*wlock_acquire)(void *lock),
1738 void (*lock_release)(void *lock),
1739 void (*lock_destroy)(void *lock),
1740 void (*context_destroy)(void *context))
1742 static void *cur_context;
1743 static void (*cur_context_destroy)(void *);
1745 /* Just destroy the context from the previous call, if necessary. */
1746 if (cur_context_destroy != NULL)
1747 cur_context_destroy(cur_context);
1748 cur_context = context;
1749 cur_context_destroy = context_destroy;
1753 dlopen(const char *name, int mode)
1755 Obj_Entry **old_obj_tail;
1758 int result, lockstate;
1760 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
1761 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
1762 if (ld_tracing != NULL)
1763 environ = (char **)*get_program_var_addr("environ");
1765 objlist_init(&initlist);
1767 lockstate = wlock_acquire(rtld_bind_lock);
1768 GDB_STATE(RT_ADD,NULL);
1770 old_obj_tail = obj_tail;
1776 char *path = find_library(name, obj_main);
1778 obj = load_object(path);
1783 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
1784 objlist_push_tail(&list_global, obj);
1785 mode &= RTLD_MODEMASK;
1786 if (*old_obj_tail != NULL) { /* We loaded something new. */
1787 assert(*old_obj_tail == obj);
1789 result = load_needed_objects(obj);
1790 if (result != -1 && ld_tracing)
1794 (init_dag(obj), relocate_objects(obj, mode == RTLD_NOW,
1795 &obj_rtld)) == -1) {
1798 if (obj->refcount == 0)
1802 /* Make list of init functions to call. */
1803 initlist_add_objects(obj, &obj->next, &initlist);
1807 /* Bump the reference counts for objects on this DAG. */
1815 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
1817 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
1819 /* Call the init functions with no locks held. */
1820 wlock_release(rtld_bind_lock, lockstate);
1821 objlist_call_init(&initlist);
1822 lockstate = wlock_acquire(rtld_bind_lock);
1823 objlist_clear(&initlist);
1824 wlock_release(rtld_bind_lock, lockstate);
1827 trace_loaded_objects(obj);
1828 wlock_release(rtld_bind_lock, lockstate);
1833 dlsym(void *handle, const char *name)
1836 const Obj_Entry *obj, *defobj;
1841 hash = elf_hash(name);
1845 lockstate = rlock_acquire(rtld_bind_lock);
1846 if (handle == NULL || handle == RTLD_NEXT ||
1847 handle == RTLD_DEFAULT || handle == RTLD_SELF) {
1850 retaddr = __builtin_return_address(0); /* __GNUC__ only */
1851 if ((obj = obj_from_addr(retaddr)) == NULL) {
1852 _rtld_error("Cannot determine caller's shared object");
1853 rlock_release(rtld_bind_lock, lockstate);
1856 if (handle == NULL) { /* Just the caller's shared object. */
1857 def = symlook_obj(name, hash, obj, true);
1859 } else if (handle == RTLD_NEXT || /* Objects after caller's */
1860 handle == RTLD_SELF) { /* ... caller included */
1861 if (handle == RTLD_NEXT)
1863 for (; obj != NULL; obj = obj->next) {
1864 if ((def = symlook_obj(name, hash, obj, true)) != NULL) {
1870 assert(handle == RTLD_DEFAULT);
1871 def = symlook_default(name, hash, obj, &defobj, true);
1874 if ((obj = dlcheck(handle)) == NULL) {
1875 rlock_release(rtld_bind_lock, lockstate);
1879 donelist_init(&donelist);
1880 if (obj->mainprog) {
1881 /* Search main program and all libraries loaded by it. */
1882 def = symlook_list(name, hash, &list_main, &defobj, true,
1887 /* Search the whole DAG rooted at the given object. */
1889 fake.obj = (Obj_Entry *)obj;
1891 def = symlook_needed(name, hash, &fake, &defobj, true,
1897 rlock_release(rtld_bind_lock, lockstate);
1900 * The value required by the caller is derived from the value
1901 * of the symbol. For the ia64 architecture, we need to
1902 * construct a function descriptor which the caller can use to
1903 * call the function with the right 'gp' value. For other
1904 * architectures and for non-functions, the value is simply
1905 * the relocated value of the symbol.
1907 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
1908 return make_function_pointer(def, defobj);
1910 return defobj->relocbase + def->st_value;
1913 _rtld_error("Undefined symbol \"%s\"", name);
1914 rlock_release(rtld_bind_lock, lockstate);
1919 dladdr(const void *addr, Dl_info *info)
1921 const Obj_Entry *obj;
1924 unsigned long symoffset;
1927 lockstate = rlock_acquire(rtld_bind_lock);
1928 obj = obj_from_addr(addr);
1930 _rtld_error("No shared object contains address");
1931 rlock_release(rtld_bind_lock, lockstate);
1934 info->dli_fname = obj->path;
1935 info->dli_fbase = obj->mapbase;
1936 info->dli_saddr = (void *)0;
1937 info->dli_sname = NULL;
1940 * Walk the symbol list looking for the symbol whose address is
1941 * closest to the address sent in.
1943 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
1944 def = obj->symtab + symoffset;
1947 * For skip the symbol if st_shndx is either SHN_UNDEF or
1950 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
1954 * If the symbol is greater than the specified address, or if it
1955 * is further away from addr than the current nearest symbol,
1958 symbol_addr = obj->relocbase + def->st_value;
1959 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
1962 /* Update our idea of the nearest symbol. */
1963 info->dli_sname = obj->strtab + def->st_name;
1964 info->dli_saddr = symbol_addr;
1967 if (info->dli_saddr == addr)
1970 rlock_release(rtld_bind_lock, lockstate);
1975 dlinfo(void *handle, int request, void *p)
1977 const Obj_Entry *obj;
1978 int error, lockstate;
1980 lockstate = rlock_acquire(rtld_bind_lock);
1982 if (handle == NULL || handle == RTLD_SELF) {
1985 retaddr = __builtin_return_address(0); /* __GNUC__ only */
1986 if ((obj = obj_from_addr(retaddr)) == NULL)
1987 _rtld_error("Cannot determine caller's shared object");
1989 obj = dlcheck(handle);
1992 rlock_release(rtld_bind_lock, lockstate);
1998 case RTLD_DI_LINKMAP:
1999 *((struct link_map const **)p) = &obj->linkmap;
2001 case RTLD_DI_ORIGIN:
2002 error = rtld_dirname(obj->path, p);
2005 case RTLD_DI_SERINFOSIZE:
2006 case RTLD_DI_SERINFO:
2007 error = do_search_info(obj, request, (struct dl_serinfo *)p);
2011 _rtld_error("Invalid request %d passed to dlinfo()", request);
2015 rlock_release(rtld_bind_lock, lockstate);
2020 struct fill_search_info_args {
2023 Dl_serinfo *serinfo;
2024 Dl_serpath *serpath;
2029 fill_search_info(const char *dir, size_t dirlen, void *param)
2031 struct fill_search_info_args *arg;
2035 if (arg->request == RTLD_DI_SERINFOSIZE) {
2036 arg->serinfo->dls_cnt ++;
2037 arg->serinfo->dls_size += sizeof(Dl_serpath) + dirlen + 1;
2039 struct dl_serpath *s_entry;
2041 s_entry = arg->serpath;
2042 s_entry->dls_name = arg->strspace;
2043 s_entry->dls_flags = arg->flags;
2045 strncpy(arg->strspace, dir, dirlen);
2046 arg->strspace[dirlen] = '\0';
2048 arg->strspace += dirlen + 1;
2056 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
2058 struct dl_serinfo _info;
2059 struct fill_search_info_args args;
2061 args.request = RTLD_DI_SERINFOSIZE;
2062 args.serinfo = &_info;
2064 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2067 path_enumerate(ld_library_path, fill_search_info, &args);
2068 path_enumerate(obj->rpath, fill_search_info, &args);
2069 path_enumerate(gethints(), fill_search_info, &args);
2070 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
2073 if (request == RTLD_DI_SERINFOSIZE) {
2074 info->dls_size = _info.dls_size;
2075 info->dls_cnt = _info.dls_cnt;
2079 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
2080 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
2084 args.request = RTLD_DI_SERINFO;
2085 args.serinfo = info;
2086 args.serpath = &info->dls_serpath[0];
2087 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
2089 args.flags = LA_SER_LIBPATH;
2090 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
2093 args.flags = LA_SER_RUNPATH;
2094 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
2097 args.flags = LA_SER_CONFIG;
2098 if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
2101 args.flags = LA_SER_DEFAULT;
2102 if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
2108 rtld_dirname(const char *path, char *bname)
2112 /* Empty or NULL string gets treated as "." */
2113 if (path == NULL || *path == '\0') {
2119 /* Strip trailing slashes */
2120 endp = path + strlen(path) - 1;
2121 while (endp > path && *endp == '/')
2124 /* Find the start of the dir */
2125 while (endp > path && *endp != '/')
2128 /* Either the dir is "/" or there are no slashes */
2130 bname[0] = *endp == '/' ? '/' : '.';
2136 } while (endp > path && *endp == '/');
2139 if (endp - path + 2 > PATH_MAX)
2141 _rtld_error("Filename is too long: %s", path);
2145 strncpy(bname, path, endp - path + 1);
2146 bname[endp - path + 1] = '\0';
2151 linkmap_add(Obj_Entry *obj)
2153 struct link_map *l = &obj->linkmap;
2154 struct link_map *prev;
2156 obj->linkmap.l_name = obj->path;
2157 obj->linkmap.l_addr = obj->mapbase;
2158 obj->linkmap.l_ld = obj->dynamic;
2160 /* GDB needs load offset on MIPS to use the symbols */
2161 obj->linkmap.l_offs = obj->relocbase;
2164 if (r_debug.r_map == NULL) {
2170 * Scan to the end of the list, but not past the entry for the
2171 * dynamic linker, which we want to keep at the very end.
2173 for (prev = r_debug.r_map;
2174 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
2175 prev = prev->l_next)
2178 /* Link in the new entry. */
2180 l->l_next = prev->l_next;
2181 if (l->l_next != NULL)
2182 l->l_next->l_prev = l;
2187 linkmap_delete(Obj_Entry *obj)
2189 struct link_map *l = &obj->linkmap;
2191 if (l->l_prev == NULL) {
2192 if ((r_debug.r_map = l->l_next) != NULL)
2193 l->l_next->l_prev = NULL;
2197 if ((l->l_prev->l_next = l->l_next) != NULL)
2198 l->l_next->l_prev = l->l_prev;
2202 * Function for the debugger to set a breakpoint on to gain control.
2204 * The two parameters allow the debugger to easily find and determine
2205 * what the runtime loader is doing and to whom it is doing it.
2207 * When the loadhook trap is hit (r_debug_state, set at program
2208 * initialization), the arguments can be found on the stack:
2210 * +8 struct link_map *m
2211 * +4 struct r_debug *rd
2215 r_debug_state(struct r_debug* rd, struct link_map *m)
2220 * Get address of the pointer variable in the main program.
2222 static const void **
2223 get_program_var_addr(const char *name)
2225 const Obj_Entry *obj;
2228 hash = elf_hash(name);
2229 for (obj = obj_main; obj != NULL; obj = obj->next) {
2232 if ((def = symlook_obj(name, hash, obj, false)) != NULL) {
2235 addr = (const void **)(obj->relocbase + def->st_value);
2243 * Set a pointer variable in the main program to the given value. This
2244 * is used to set key variables such as "environ" before any of the
2245 * init functions are called.
2248 set_program_var(const char *name, const void *value)
2252 if ((addr = get_program_var_addr(name)) != NULL) {
2253 dbg("\"%s\": *%p <-- %p", name, addr, value);
2259 * Given a symbol name in a referencing object, find the corresponding
2260 * definition of the symbol. Returns a pointer to the symbol, or NULL if
2261 * no definition was found. Returns a pointer to the Obj_Entry of the
2262 * defining object via the reference parameter DEFOBJ_OUT.
2264 static const Elf_Sym *
2265 symlook_default(const char *name, unsigned long hash,
2266 const Obj_Entry *refobj, const Obj_Entry **defobj_out, bool in_plt)
2270 const Elf_Sym *symp;
2271 const Obj_Entry *obj;
2272 const Obj_Entry *defobj;
2273 const Objlist_Entry *elm;
2276 donelist_init(&donelist);
2278 /* Look first in the referencing object if linked symbolically. */
2279 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
2280 symp = symlook_obj(name, hash, refobj, in_plt);
2287 /* Search all objects loaded at program start up. */
2288 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2289 symp = symlook_list(name, hash, &list_main, &obj, in_plt, &donelist);
2291 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2297 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
2298 STAILQ_FOREACH(elm, &list_global, link) {
2299 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2301 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt,
2304 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2310 /* Search all dlopened DAGs containing the referencing object. */
2311 STAILQ_FOREACH(elm, &refobj->dldags, link) {
2312 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2314 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt,
2317 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2324 * Search the dynamic linker itself, and possibly resolve the
2325 * symbol from there. This is how the application links to
2326 * dynamic linker services such as dlopen. Only the values listed
2327 * in the "exports" array can be resolved from the dynamic linker.
2329 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2330 symp = symlook_obj(name, hash, &obj_rtld, in_plt);
2331 if (symp != NULL && is_exported(symp)) {
2338 *defobj_out = defobj;
2342 static const Elf_Sym *
2343 symlook_list(const char *name, unsigned long hash, const Objlist *objlist,
2344 const Obj_Entry **defobj_out, bool in_plt, DoneList *dlp)
2346 const Elf_Sym *symp;
2348 const Obj_Entry *defobj;
2349 const Objlist_Entry *elm;
2353 STAILQ_FOREACH(elm, objlist, link) {
2354 if (donelist_check(dlp, elm->obj))
2356 if ((symp = symlook_obj(name, hash, elm->obj, in_plt)) != NULL) {
2357 if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
2360 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2366 *defobj_out = defobj;
2371 * Search the symbol table of a shared object and all objects needed
2372 * by it for a symbol of the given name. Search order is
2373 * breadth-first. Returns a pointer to the symbol, or NULL if no
2374 * definition was found.
2376 static const Elf_Sym *
2377 symlook_needed(const char *name, unsigned long hash, const Needed_Entry *needed,
2378 const Obj_Entry **defobj_out, bool in_plt, DoneList *dlp)
2380 const Elf_Sym *def, *def_w;
2381 const Needed_Entry *n;
2382 const Obj_Entry *obj, *defobj, *defobj1;
2386 for (n = needed; n != NULL; n = n->next) {
2387 if ((obj = n->obj) == NULL ||
2388 donelist_check(dlp, obj) ||
2389 (def = symlook_obj(name, hash, obj, in_plt)) == NULL)
2392 if (ELF_ST_BIND(def->st_info) != STB_WEAK) {
2393 *defobj_out = defobj;
2398 * There we come when either symbol definition is not found in
2399 * directly needed objects, or found symbol is weak.
2401 for (n = needed; n != NULL; n = n->next) {
2402 if ((obj = n->obj) == NULL)
2404 def_w = symlook_needed(name, hash, obj->needed, &defobj1,
2408 if (def == NULL || ELF_ST_BIND(def_w->st_info) != STB_WEAK) {
2412 if (ELF_ST_BIND(def_w->st_info) != STB_WEAK)
2416 *defobj_out = defobj;
2421 * Search the symbol table of a single shared object for a symbol of
2422 * the given name. Returns a pointer to the symbol, or NULL if no
2423 * definition was found.
2425 * The symbol's hash value is passed in for efficiency reasons; that
2426 * eliminates many recomputations of the hash value.
2429 symlook_obj(const char *name, unsigned long hash, const Obj_Entry *obj,
2432 if (obj->buckets != NULL) {
2433 unsigned long symnum = obj->buckets[hash % obj->nbuckets];
2435 while (symnum != STN_UNDEF) {
2436 const Elf_Sym *symp;
2439 if (symnum >= obj->nchains)
2440 return NULL; /* Bad object */
2441 symp = obj->symtab + symnum;
2442 strp = obj->strtab + symp->st_name;
2444 if (name[0] == strp[0] && strcmp(name, strp) == 0)
2445 return symp->st_shndx != SHN_UNDEF ||
2446 (!in_plt && symp->st_value != 0 &&
2447 ELF_ST_TYPE(symp->st_info) == STT_FUNC) ? symp : NULL;
2449 symnum = obj->chains[symnum];
2456 trace_loaded_objects(Obj_Entry *obj)
2458 char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
2461 if ((main_local = getenv(LD_ "TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
2464 if ((fmt1 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT1")) == NULL)
2465 fmt1 = "\t%o => %p (%x)\n";
2467 if ((fmt2 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT2")) == NULL)
2468 fmt2 = "\t%o (%x)\n";
2470 list_containers = getenv(LD_ "TRACE_LOADED_OBJECTS_ALL");
2472 for (; obj; obj = obj->next) {
2473 Needed_Entry *needed;
2477 if (list_containers && obj->needed != NULL)
2478 printf("%s:\n", obj->path);
2479 for (needed = obj->needed; needed; needed = needed->next) {
2480 if (needed->obj != NULL) {
2481 if (needed->obj->traced && !list_containers)
2483 needed->obj->traced = true;
2484 path = needed->obj->path;
2488 name = (char *)obj->strtab + needed->name;
2489 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
2491 fmt = is_lib ? fmt1 : fmt2;
2492 while ((c = *fmt++) != '\0') {
2518 printf("%s", main_local);
2521 printf("%s", obj_main->path);
2528 printf("%d", sodp->sod_major);
2531 printf("%d", sodp->sod_minor);
2538 printf("%p", needed->obj ? needed->obj->mapbase : 0);
2550 * Unload a dlopened object and its dependencies from memory and from
2551 * our data structures. It is assumed that the DAG rooted in the
2552 * object has already been unreferenced, and that the object has a
2553 * reference count of 0.
2556 unload_object(Obj_Entry *root)
2561 assert(root->refcount == 0);
2564 * Pass over the DAG removing unreferenced objects from
2565 * appropriate lists.
2567 unlink_object(root);
2569 /* Unmap all objects that are no longer referenced. */
2570 linkp = &obj_list->next;
2571 while ((obj = *linkp) != NULL) {
2572 if (obj->refcount == 0) {
2573 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
2575 dbg("unloading \"%s\"", obj->path);
2576 munmap(obj->mapbase, obj->mapsize);
2577 linkmap_delete(obj);
2588 unlink_object(Obj_Entry *root)
2592 if (root->refcount == 0) {
2593 /* Remove the object from the RTLD_GLOBAL list. */
2594 objlist_remove(&list_global, root);
2596 /* Remove the object from all objects' DAG lists. */
2597 STAILQ_FOREACH(elm, &root->dagmembers , link) {
2598 objlist_remove(&elm->obj->dldags, root);
2599 if (elm->obj != root)
2600 unlink_object(elm->obj);
2606 ref_dag(Obj_Entry *root)
2610 STAILQ_FOREACH(elm, &root->dagmembers , link)
2611 elm->obj->refcount++;
2615 unref_dag(Obj_Entry *root)
2619 STAILQ_FOREACH(elm, &root->dagmembers , link)
2620 elm->obj->refcount--;
2624 * Common code for MD __tls_get_addr().
2627 tls_get_addr_common(Elf_Addr** dtvp, int index, size_t offset)
2629 Elf_Addr* dtv = *dtvp;
2632 /* Check dtv generation in case new modules have arrived */
2633 if (dtv[0] != tls_dtv_generation) {
2637 lockstate = wlock_acquire(rtld_bind_lock);
2638 newdtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
2640 if (to_copy > tls_max_index)
2641 to_copy = tls_max_index;
2642 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
2643 newdtv[0] = tls_dtv_generation;
2644 newdtv[1] = tls_max_index;
2646 wlock_release(rtld_bind_lock, lockstate);
2650 /* Dynamically allocate module TLS if necessary */
2651 if (!dtv[index + 1]) {
2652 /* Signal safe, wlock will block out signals. */
2653 lockstate = wlock_acquire(rtld_bind_lock);
2654 if (!dtv[index + 1])
2655 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
2656 wlock_release(rtld_bind_lock, lockstate);
2658 return (void*) (dtv[index + 1] + offset);
2661 /* XXX not sure what variants to use for arm. */
2663 #if defined(__ia64__) || defined(__alpha__) || defined(__powerpc__)
2666 * Allocate Static TLS using the Variant I method.
2669 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
2678 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
2681 assert(tcbsize >= TLS_TCB_SIZE);
2682 tcb = calloc(1, tls_static_space - TLS_TCB_SIZE + tcbsize);
2683 tls = (Elf_Addr **)(tcb + tcbsize - TLS_TCB_SIZE);
2685 if (oldtcb != NULL) {
2686 memcpy(tls, oldtcb, tls_static_space);
2689 /* Adjust the DTV. */
2691 for (i = 0; i < dtv[1]; i++) {
2692 if (dtv[i+2] >= (Elf_Addr)oldtcb &&
2693 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
2694 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tls;
2698 dtv = calloc(tls_max_index + 2, sizeof(Elf_Addr));
2700 dtv[0] = tls_dtv_generation;
2701 dtv[1] = tls_max_index;
2703 for (obj = objs; obj; obj = obj->next) {
2704 if (obj->tlsoffset) {
2705 addr = (Elf_Addr)tls + obj->tlsoffset;
2706 memset((void*) (addr + obj->tlsinitsize),
2707 0, obj->tlssize - obj->tlsinitsize);
2709 memcpy((void*) addr, obj->tlsinit,
2711 dtv[obj->tlsindex + 1] = addr;
2720 free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
2723 Elf_Addr tlsstart, tlsend;
2726 assert(tcbsize >= TLS_TCB_SIZE);
2728 tlsstart = (Elf_Addr)tcb + tcbsize - TLS_TCB_SIZE;
2729 tlsend = tlsstart + tls_static_space;
2731 dtv = *(Elf_Addr **)tlsstart;
2733 for (i = 0; i < dtvsize; i++) {
2734 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
2735 free((void*)dtv[i+2]);
2744 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) || \
2748 * Allocate Static TLS using the Variant II method.
2751 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
2756 Elf_Addr *dtv, *olddtv;
2757 Elf_Addr segbase, oldsegbase, addr;
2760 size = round(tls_static_space, tcbalign);
2762 assert(tcbsize >= 2*sizeof(Elf_Addr));
2763 tls = malloc(size + tcbsize);
2764 dtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
2766 segbase = (Elf_Addr)(tls + size);
2767 ((Elf_Addr*)segbase)[0] = segbase;
2768 ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
2770 dtv[0] = tls_dtv_generation;
2771 dtv[1] = tls_max_index;
2775 * Copy the static TLS block over whole.
2777 oldsegbase = (Elf_Addr) oldtls;
2778 memcpy((void *)(segbase - tls_static_space),
2779 (const void *)(oldsegbase - tls_static_space),
2783 * If any dynamic TLS blocks have been created tls_get_addr(),
2786 olddtv = ((Elf_Addr**)oldsegbase)[1];
2787 for (i = 0; i < olddtv[1]; i++) {
2788 if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
2789 dtv[i+2] = olddtv[i+2];
2795 * We assume that this block was the one we created with
2796 * allocate_initial_tls().
2798 free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
2800 for (obj = objs; obj; obj = obj->next) {
2801 if (obj->tlsoffset) {
2802 addr = segbase - obj->tlsoffset;
2803 memset((void*) (addr + obj->tlsinitsize),
2804 0, obj->tlssize - obj->tlsinitsize);
2806 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
2807 dtv[obj->tlsindex + 1] = addr;
2812 return (void*) segbase;
2816 free_tls(void *tls, size_t tcbsize, size_t tcbalign)
2821 Elf_Addr tlsstart, tlsend;
2824 * Figure out the size of the initial TLS block so that we can
2825 * find stuff which ___tls_get_addr() allocated dynamically.
2827 size = round(tls_static_space, tcbalign);
2829 dtv = ((Elf_Addr**)tls)[1];
2831 tlsend = (Elf_Addr) tls;
2832 tlsstart = tlsend - size;
2833 for (i = 0; i < dtvsize; i++) {
2834 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] > tlsend)) {
2835 free((void*) dtv[i+2]);
2839 free((void*) tlsstart);
2846 * Allocate TLS block for module with given index.
2849 allocate_module_tls(int index)
2854 for (obj = obj_list; obj; obj = obj->next) {
2855 if (obj->tlsindex == index)
2859 _rtld_error("Can't find module with TLS index %d", index);
2863 p = malloc(obj->tlssize);
2864 memcpy(p, obj->tlsinit, obj->tlsinitsize);
2865 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
2871 allocate_tls_offset(Obj_Entry *obj)
2878 if (obj->tlssize == 0) {
2879 obj->tls_done = true;
2883 if (obj->tlsindex == 1)
2884 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
2886 off = calculate_tls_offset(tls_last_offset, tls_last_size,
2887 obj->tlssize, obj->tlsalign);
2890 * If we have already fixed the size of the static TLS block, we
2891 * must stay within that size. When allocating the static TLS, we
2892 * leave a small amount of space spare to be used for dynamically
2893 * loading modules which use static TLS.
2895 if (tls_static_space) {
2896 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
2900 tls_last_offset = obj->tlsoffset = off;
2901 tls_last_size = obj->tlssize;
2902 obj->tls_done = true;
2908 free_tls_offset(Obj_Entry *obj)
2910 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) || \
2913 * If we were the last thing to allocate out of the static TLS
2914 * block, we give our space back to the 'allocator'. This is a
2915 * simplistic workaround to allow libGL.so.1 to be loaded and
2916 * unloaded multiple times. We only handle the Variant II
2917 * mechanism for now - this really needs a proper allocator.
2919 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
2920 == calculate_tls_end(tls_last_offset, tls_last_size)) {
2921 tls_last_offset -= obj->tlssize;
2928 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
2933 lockstate = wlock_acquire(rtld_bind_lock);
2934 ret = allocate_tls(obj_list, oldtls, tcbsize, tcbalign);
2935 wlock_release(rtld_bind_lock, lockstate);
2940 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
2944 lockstate = wlock_acquire(rtld_bind_lock);
2945 free_tls(tcb, tcbsize, tcbalign);
2946 wlock_release(rtld_bind_lock, lockstate);