2 #define SYSCALL_NO_TLS 1
20 #include <semaphore.h>
21 #include <sys/membarrier.h>
22 #include "pthread_impl.h"
23 #include "fork_impl.h"
26 static size_t ldso_page_size;
28 #define PAGE_SIZE ldso_page_size
33 #define malloc __libc_malloc
34 #define calloc __libc_calloc
35 #define realloc __libc_realloc
36 #define free __libc_free
38 static void error_impl(const char *, ...);
39 static void error_noop(const char *, ...);
40 static void (*error)(const char *, ...) = error_noop;
42 #define MAXP2(a,b) (-(-(a)&-(b)))
43 #define ALIGN(x,y) ((x)+(y)-1 & -(y))
45 #define container_of(p,t,m) ((t*)((char *)(p)-offsetof(t,m)))
46 #define countof(a) ((sizeof (a))/(sizeof (a)[0]))
58 struct td_index *next;
63 struct fdpic_loadmap *loadmap;
69 struct dso *next, *prev;
79 struct dso *syms_next, *lazy_next;
80 size_t *lazy, lazy_cnt;
91 struct dso **deps, *needed_by;
94 pthread_t ctor_visitor;
95 char *rpath_orig, *rpath;
96 struct tls_module tls;
98 size_t relro_start, relro_end;
100 unsigned char *new_tls;
101 struct td_index *td_index;
102 struct dso *fini_next;
107 struct fdpic_loadmap *loadmap;
122 typedef void (*stage3_func)(size_t *, size_t *);
124 static struct builtin_tls {
129 #define MIN_TLS_ALIGN offsetof(struct builtin_tls, pt)
131 #define ADDEND_LIMIT 4096
132 static size_t *saved_addends, *apply_addends_to;
134 static struct dso ldso;
135 static struct dso *head, *tail, *fini_head, *syms_tail, *lazy_head;
136 static char *env_path, *sys_path;
137 static unsigned long long gencnt;
140 static int ldso_fail;
142 static int shutting_down;
143 static jmp_buf *rtld_fail;
144 static pthread_rwlock_t lock;
145 static struct debug debug;
146 static struct tls_module *tls_tail;
147 static size_t tls_cnt, tls_offset, tls_align = MIN_TLS_ALIGN;
148 static size_t static_tls_cnt;
149 static pthread_mutex_t init_fini_lock;
150 static pthread_cond_t ctor_cond;
151 static struct dso *builtin_deps[2];
152 static struct dso *const no_deps[1];
153 static struct dso *builtin_ctor_queue[4];
154 static struct dso **main_ctor_queue;
155 static struct fdpic_loadmap *app_loadmap;
156 static struct fdpic_dummy_loadmap app_dummy_loadmap;
158 struct debug *_dl_debug_addr = &debug;
160 extern hidden int __malloc_replaced;
162 hidden void (*const __init_array_start)(void)=0, (*const __fini_array_start)(void)=0;
164 extern hidden void (*const __init_array_end)(void), (*const __fini_array_end)(void);
166 weak_alias(__init_array_start, __init_array_end);
167 weak_alias(__fini_array_start, __fini_array_end);
169 static int dl_strcmp(const char *l, const char *r)
171 for (; *l==*r && *l; l++, r++);
172 return *(unsigned char *)l - *(unsigned char *)r;
174 #define strcmp(l,r) dl_strcmp(l,r)
176 /* Compute load address for a virtual address in a given dso. */
178 static void *laddr(const struct dso *p, size_t v)
181 if (!p->loadmap) return p->base + v;
182 for (j=0; v-p->loadmap->segs[j].p_vaddr >= p->loadmap->segs[j].p_memsz; j++);
183 return (void *)(v - p->loadmap->segs[j].p_vaddr + p->loadmap->segs[j].addr);
185 static void *laddr_pg(const struct dso *p, size_t v)
188 size_t pgsz = PAGE_SIZE;
189 if (!p->loadmap) return p->base + v;
191 size_t a = p->loadmap->segs[j].p_vaddr;
192 size_t b = a + p->loadmap->segs[j].p_memsz;
198 return (void *)(v - p->loadmap->segs[j].p_vaddr + p->loadmap->segs[j].addr);
200 static void (*fdbarrier(void *p))()
203 __asm__("" : "=r"(fd) : "0"(p));
206 #define fpaddr(p, v) fdbarrier((&(struct funcdesc){ \
207 laddr(p, v), (p)->got }))
209 #define laddr(p, v) (void *)((p)->base + (v))
210 #define laddr_pg(p, v) laddr(p, v)
211 #define fpaddr(p, v) ((void (*)())laddr(p, v))
214 static void decode_vec(size_t *v, size_t *a, size_t cnt)
217 for (i=0; i<cnt; i++) a[i] = 0;
218 for (; v[0]; v+=2) if (v[0]-1<cnt-1) {
219 if (v[0] < 8*sizeof(long))
225 static int search_vec(size_t *v, size_t *r, size_t key)
227 for (; v[0]!=key; v+=2)
233 static uint32_t sysv_hash(const char *s0)
235 const unsigned char *s = (void *)s0;
241 return h & 0xfffffff;
244 static uint32_t gnu_hash(const char *s0)
246 const unsigned char *s = (void *)s0;
247 uint_fast32_t h = 5381;
253 static Sym *sysv_lookup(const char *s, uint32_t h, struct dso *dso)
256 Sym *syms = dso->syms;
257 Elf_Symndx *hashtab = dso->hashtab;
258 char *strings = dso->strings;
259 for (i=hashtab[2+h%hashtab[0]]; i; i=hashtab[2+hashtab[0]+i]) {
260 if ((!dso->versym || dso->versym[i] >= 0)
261 && (!strcmp(s, strings+syms[i].st_name)))
267 static Sym *gnu_lookup(uint32_t h1, uint32_t *hashtab, struct dso *dso, const char *s)
269 uint32_t nbuckets = hashtab[0];
270 uint32_t *buckets = hashtab + 4 + hashtab[2]*(sizeof(size_t)/4);
271 uint32_t i = buckets[h1 % nbuckets];
275 uint32_t *hashval = buckets + nbuckets + (i - hashtab[1]);
277 for (h1 |= 1; ; i++) {
278 uint32_t h2 = *hashval++;
279 if ((h1 == (h2|1)) && (!dso->versym || dso->versym[i] >= 0)
280 && !strcmp(s, dso->strings + dso->syms[i].st_name))
288 static Sym *gnu_lookup_filtered(uint32_t h1, uint32_t *hashtab, struct dso *dso, const char *s, uint32_t fofs, size_t fmask)
290 const size_t *bloomwords = (const void *)(hashtab+4);
291 size_t f = bloomwords[fofs & (hashtab[2]-1)];
292 if (!(f & fmask)) return 0;
294 f >>= (h1 >> hashtab[3]) % (8 * sizeof f);
295 if (!(f & 1)) return 0;
297 return gnu_lookup(h1, hashtab, dso, s);
300 #define OK_TYPES (1<<STT_NOTYPE | 1<<STT_OBJECT | 1<<STT_FUNC | 1<<STT_COMMON | 1<<STT_TLS)
301 #define OK_BINDS (1<<STB_GLOBAL | 1<<STB_WEAK | 1<<STB_GNU_UNIQUE)
303 #ifndef ARCH_SYM_REJECT_UND
304 #define ARCH_SYM_REJECT_UND(s) 0
307 #if defined(__GNUC__)
308 __attribute__((always_inline))
310 static inline struct symdef find_sym2(struct dso *dso, const char *s, int need_def, int use_deps)
312 uint32_t h = 0, gh = gnu_hash(s), gho = gh / (8*sizeof(size_t)), *ght;
313 size_t ghm = 1ul << gh % (8*sizeof(size_t));
314 struct symdef def = {0};
315 struct dso **deps = use_deps ? dso->deps : 0;
316 for (; dso; dso=use_deps ? *deps++ : dso->syms_next) {
318 if ((ght = dso->ghashtab)) {
319 sym = gnu_lookup_filtered(gh, ght, dso, s, gho, ghm);
321 if (!h) h = sysv_hash(s);
322 sym = sysv_lookup(s, h, dso);
326 if (need_def || (sym->st_info&0xf) == STT_TLS
327 || ARCH_SYM_REJECT_UND(sym))
330 if ((sym->st_info&0xf) != STT_TLS)
332 if (!(1<<(sym->st_info&0xf) & OK_TYPES)) continue;
333 if (!(1<<(sym->st_info>>4) & OK_BINDS)) continue;
341 static struct symdef find_sym(struct dso *dso, const char *s, int need_def)
343 return find_sym2(dso, s, need_def, 0);
346 static struct symdef get_lfs64(const char *name)
349 static const char lfs64_list[] =
350 "aio_cancel\0aio_error\0aio_fsync\0aio_read\0aio_return\0"
351 "aio_suspend\0aio_write\0alphasort\0creat\0fallocate\0"
352 "fgetpos\0fopen\0freopen\0fseeko\0fsetpos\0fstat\0"
353 "fstatat\0fstatfs\0fstatvfs\0ftello\0ftruncate\0ftw\0"
354 "getdents\0getrlimit\0glob\0globfree\0lio_listio\0"
355 "lockf\0lseek\0lstat\0mkostemp\0mkostemps\0mkstemp\0"
356 "mkstemps\0mmap\0nftw\0open\0openat\0posix_fadvise\0"
357 "posix_fallocate\0pread\0preadv\0prlimit\0pwrite\0"
358 "pwritev\0readdir\0scandir\0sendfile\0setrlimit\0"
359 "stat\0statfs\0statvfs\0tmpfile\0truncate\0versionsort\0"
360 "__fxstat\0__fxstatat\0__lxstat\0__xstat\0";
363 for (l=0; name[l]; l++) {
364 if (l >= sizeof buf) goto nomatch;
367 if (!strcmp(name, "readdir64_r"))
368 return find_sym(&ldso, "readdir_r", 1);
369 if (l<2 || name[l-2]!='6' || name[l-1]!='4')
372 for (p=lfs64_list; *p; p++) {
373 if (!strcmp(buf, p)) return find_sym(&ldso, buf, 1);
377 return (struct symdef){ 0 };
380 static void do_relocs(struct dso *dso, size_t *rel, size_t rel_size, size_t stride)
382 unsigned char *base = dso->base;
383 Sym *syms = dso->syms;
384 char *strings = dso->strings;
395 int skip_relative = 0, reuse_addends = 0, save_slot = 0;
398 /* Only ldso's REL table needs addend saving/reuse. */
399 if (rel == apply_addends_to)
404 for (; rel_size; rel+=stride, rel_size-=stride*sizeof(size_t)) {
405 if (skip_relative && IS_RELATIVE(rel[1], dso->syms)) continue;
406 type = R_TYPE(rel[1]);
407 if (type == REL_NONE) continue;
408 reloc_addr = laddr(dso, rel[0]);
412 } else if (type==REL_GOT || type==REL_PLT|| type==REL_COPY) {
414 } else if (reuse_addends) {
415 /* Save original addend in stage 2 where the dso
416 * chain consists of just ldso; otherwise read back
417 * saved addend since the inline one was clobbered. */
419 saved_addends[save_slot] = *reloc_addr;
420 addend = saved_addends[save_slot++];
422 addend = *reloc_addr;
425 sym_index = R_SYM(rel[1]);
427 sym = syms + sym_index;
428 name = strings + sym->st_name;
429 ctx = type==REL_COPY ? head->syms_next : head;
430 def = (sym->st_info>>4) == STB_LOCAL
431 ? (struct symdef){ .dso = dso, .sym = sym }
432 : find_sym(ctx, name, type==REL_PLT);
433 if (!def.sym) def = get_lfs64(name);
434 if (!def.sym && (sym->st_shndx != SHN_UNDEF
435 || sym->st_info>>4 != STB_WEAK)) {
436 if (dso->lazy && (type==REL_PLT || type==REL_GOT)) {
437 dso->lazy[3*dso->lazy_cnt+0] = rel[0];
438 dso->lazy[3*dso->lazy_cnt+1] = rel[1];
439 dso->lazy[3*dso->lazy_cnt+2] = addend;
443 error("Error relocating %s: %s: symbol not found",
445 if (runtime) longjmp(*rtld_fail, 1);
454 sym_val = def.sym ? (size_t)laddr(def.dso, def.sym->st_value) : 0;
455 tls_val = def.sym ? def.sym->st_value : 0;
457 if ((type == REL_TPOFF || type == REL_TPOFF_NEG)
458 && def.dso->tls_id > static_tls_cnt) {
459 error("Error relocating %s: %s: initial-exec TLS "
460 "resolves to dynamic definition in %s",
461 dso->name, name, def.dso->name);
462 longjmp(*rtld_fail, 1);
467 addend -= (size_t)reloc_addr;
471 *reloc_addr = sym_val + addend;
474 memcpy(reloc_addr, &(size_t){sym_val + addend}, sizeof(size_t));
477 *reloc_addr = (size_t)base + addend;
480 if (sym) *reloc_addr = sym_val + addend;
481 else *reloc_addr = (size_t)base + addend;
484 memcpy(reloc_addr, (void *)sym_val, sym->st_size);
487 *(uint32_t *)reloc_addr = sym_val + addend
488 - (size_t)reloc_addr;
491 *reloc_addr = def.sym ? (size_t)(def.dso->funcdescs
492 + (def.sym - def.dso->syms)) : 0;
494 case REL_FUNCDESC_VAL:
495 if ((sym->st_info&0xf) == STT_SECTION) *reloc_addr += sym_val;
496 else *reloc_addr = sym_val;
497 reloc_addr[1] = def.sym ? (size_t)def.dso->got : 0;
500 *reloc_addr = def.dso->tls_id;
503 *reloc_addr = tls_val + addend - DTP_OFFSET;
507 *reloc_addr = tls_val + def.dso->tls.offset + TPOFF_K + addend;
511 *reloc_addr = tls_val - def.dso->tls.offset + addend;
514 *reloc_addr = def.dso->tls.offset - tls_val + addend;
518 if (stride<3) addend = reloc_addr[1];
519 if (def.dso->tls_id > static_tls_cnt) {
520 struct td_index *new = malloc(sizeof *new);
523 "Error relocating %s: cannot allocate TLSDESC for %s",
524 dso->name, sym ? name : "(local)" );
525 longjmp(*rtld_fail, 1);
527 new->next = dso->td_index;
529 new->args[0] = def.dso->tls_id;
530 new->args[1] = tls_val + addend - DTP_OFFSET;
531 reloc_addr[0] = (size_t)__tlsdesc_dynamic;
532 reloc_addr[1] = (size_t)new;
534 reloc_addr[0] = (size_t)__tlsdesc_static;
536 reloc_addr[1] = tls_val + def.dso->tls.offset
539 reloc_addr[1] = tls_val - def.dso->tls.offset
543 #ifdef TLSDESC_BACKWARDS
544 /* Some archs (32-bit ARM at least) invert the order of
545 * the descriptor members. Fix them up here. */
546 size_t tmp = reloc_addr[0];
547 reloc_addr[0] = reloc_addr[1];
552 error("Error relocating %s: unsupported relocation type %d",
554 if (runtime) longjmp(*rtld_fail, 1);
560 static void do_relr_relocs(struct dso *dso, size_t *relr, size_t relr_size)
562 if (dso == &ldso) return; /* self-relocation was done in _dlstart */
563 unsigned char *base = dso->base;
565 for (; relr_size; relr++, relr_size-=sizeof(size_t))
566 if ((relr[0]&1) == 0) {
567 reloc_addr = laddr(dso, relr[0]);
568 *reloc_addr++ += (size_t)base;
571 for (size_t bitmap=relr[0]; (bitmap>>=1); i++)
573 reloc_addr[i] += (size_t)base;
574 reloc_addr += 8*sizeof(size_t)-1;
578 static void redo_lazy_relocs()
580 struct dso *p = lazy_head, *next;
584 size_t size = p->lazy_cnt*3*sizeof(size_t);
586 do_relocs(p, p->lazy, size, 3);
588 p->lazy_next = lazy_head;
598 /* A huge hack: to make up for the wastefulness of shared libraries
599 * needing at least a page of dirty memory even if they have no global
600 * data, we reclaim the gaps at the beginning and end of writable maps
601 * and "donate" them to the heap. */
603 static void reclaim(struct dso *dso, size_t start, size_t end)
605 if (start >= dso->relro_start && start < dso->relro_end) start = dso->relro_end;
606 if (end >= dso->relro_start && end < dso->relro_end) end = dso->relro_start;
607 if (start >= end) return;
608 char *base = laddr_pg(dso, start);
609 __malloc_donate(base, base+(end-start));
612 static void reclaim_gaps(struct dso *dso)
614 Phdr *ph = dso->phdr;
615 size_t phcnt = dso->phnum;
617 for (; phcnt--; ph=(void *)((char *)ph+dso->phentsize)) {
618 if (ph->p_type!=PT_LOAD) continue;
619 if ((ph->p_flags&(PF_R|PF_W))!=(PF_R|PF_W)) continue;
620 reclaim(dso, ph->p_vaddr & -PAGE_SIZE, ph->p_vaddr);
621 reclaim(dso, ph->p_vaddr+ph->p_memsz,
622 ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE);
626 static ssize_t read_loop(int fd, void *p, size_t n)
628 for (size_t i=0; i<n; ) {
629 ssize_t l = read(fd, (char *)p+i, n-i);
631 if (errno==EINTR) continue;
640 static void *mmap_fixed(void *p, size_t n, int prot, int flags, int fd, off_t off)
642 static int no_map_fixed;
646 q = mmap(p, n, prot, flags|MAP_FIXED, fd, off);
647 if (!DL_NOMMU_SUPPORT || q != MAP_FAILED || errno != EINVAL)
651 /* Fallbacks for MAP_FIXED failure on NOMMU kernels. */
652 if (flags & MAP_ANONYMOUS) {
657 if (lseek(fd, off, SEEK_SET) < 0) return MAP_FAILED;
658 for (q=p; n; q+=r, off+=r, n-=r) {
660 if (r < 0 && errno != EINTR) return MAP_FAILED;
669 static void unmap_library(struct dso *dso)
673 for (i=0; i<dso->loadmap->nsegs; i++) {
674 if (!dso->loadmap->segs[i].p_memsz)
676 munmap((void *)dso->loadmap->segs[i].addr,
677 dso->loadmap->segs[i].p_memsz);
680 } else if (dso->map && dso->map_len) {
681 munmap(dso->map, dso->map_len);
685 static void *map_library(int fd, struct dso *dso)
687 Ehdr buf[(896+sizeof(Ehdr))/sizeof(Ehdr)];
688 void *allocated_buf=0;
690 size_t addr_min=SIZE_MAX, addr_max=0, map_len;
691 size_t this_min, this_max;
697 unsigned char *map=MAP_FAILED, *base;
702 ssize_t l = read(fd, buf, sizeof buf);
705 if (l<sizeof *eh || (eh->e_type != ET_DYN && eh->e_type != ET_EXEC))
707 phsize = eh->e_phentsize * eh->e_phnum;
708 if (phsize > sizeof buf - sizeof *eh) {
709 allocated_buf = malloc(phsize);
710 if (!allocated_buf) return 0;
711 l = pread(fd, allocated_buf, phsize, eh->e_phoff);
712 if (l < 0) goto error;
713 if (l != phsize) goto noexec;
714 ph = ph0 = allocated_buf;
715 } else if (eh->e_phoff + phsize > l) {
716 l = pread(fd, buf+1, phsize, eh->e_phoff);
717 if (l < 0) goto error;
718 if (l != phsize) goto noexec;
719 ph = ph0 = (void *)(buf + 1);
721 ph = ph0 = (void *)((char *)buf + eh->e_phoff);
723 for (i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
724 if (ph->p_type == PT_DYNAMIC) {
726 } else if (ph->p_type == PT_TLS) {
727 tls_image = ph->p_vaddr;
728 dso->tls.align = ph->p_align;
729 dso->tls.len = ph->p_filesz;
730 dso->tls.size = ph->p_memsz;
731 } else if (ph->p_type == PT_GNU_RELRO) {
732 dso->relro_start = ph->p_vaddr & -PAGE_SIZE;
733 dso->relro_end = (ph->p_vaddr + ph->p_memsz) & -PAGE_SIZE;
734 } else if (ph->p_type == PT_GNU_STACK) {
735 if (!runtime && ph->p_memsz > __default_stacksize) {
736 __default_stacksize =
737 ph->p_memsz < DEFAULT_STACK_MAX ?
738 ph->p_memsz : DEFAULT_STACK_MAX;
741 if (ph->p_type != PT_LOAD) continue;
743 if (ph->p_vaddr < addr_min) {
744 addr_min = ph->p_vaddr;
745 off_start = ph->p_offset;
746 prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
747 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
748 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
750 if (ph->p_vaddr+ph->p_memsz > addr_max) {
751 addr_max = ph->p_vaddr+ph->p_memsz;
754 if (!dyn) goto noexec;
755 if (DL_FDPIC && !(eh->e_flags & FDPIC_CONSTDISP_FLAG)) {
756 dso->loadmap = calloc(1, sizeof *dso->loadmap
757 + nsegs * sizeof *dso->loadmap->segs);
758 if (!dso->loadmap) goto error;
759 dso->loadmap->nsegs = nsegs;
760 for (ph=ph0, i=0; i<nsegs; ph=(void *)((char *)ph+eh->e_phentsize)) {
761 if (ph->p_type != PT_LOAD) continue;
762 prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
763 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
764 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
765 map = mmap(0, ph->p_memsz + (ph->p_vaddr & PAGE_SIZE-1),
767 fd, ph->p_offset & -PAGE_SIZE);
768 if (map == MAP_FAILED) {
772 dso->loadmap->segs[i].addr = (size_t)map +
773 (ph->p_vaddr & PAGE_SIZE-1);
774 dso->loadmap->segs[i].p_vaddr = ph->p_vaddr;
775 dso->loadmap->segs[i].p_memsz = ph->p_memsz;
777 if (prot & PROT_WRITE) {
778 size_t brk = (ph->p_vaddr & PAGE_SIZE-1)
780 size_t pgbrk = brk + PAGE_SIZE-1 & -PAGE_SIZE;
781 size_t pgend = brk + ph->p_memsz - ph->p_filesz
782 + PAGE_SIZE-1 & -PAGE_SIZE;
783 if (pgend > pgbrk && mmap_fixed(map+pgbrk,
785 MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS,
786 -1, off_start) == MAP_FAILED)
788 memset(map + brk, 0, pgbrk-brk);
791 map = (void *)dso->loadmap->segs[0].addr;
795 addr_max += PAGE_SIZE-1;
796 addr_max &= -PAGE_SIZE;
797 addr_min &= -PAGE_SIZE;
798 off_start &= -PAGE_SIZE;
799 map_len = addr_max - addr_min + off_start;
800 /* The first time, we map too much, possibly even more than
801 * the length of the file. This is okay because we will not
802 * use the invalid part; we just need to reserve the right
803 * amount of virtual address space to map over later. */
804 map = DL_NOMMU_SUPPORT
805 ? mmap((void *)addr_min, map_len, PROT_READ|PROT_WRITE|PROT_EXEC,
806 MAP_PRIVATE|MAP_ANONYMOUS, -1, 0)
807 : mmap((void *)addr_min, map_len, prot,
808 MAP_PRIVATE, fd, off_start);
809 if (map==MAP_FAILED) goto error;
811 dso->map_len = map_len;
812 /* If the loaded file is not relocatable and the requested address is
813 * not available, then the load operation must fail. */
814 if (eh->e_type != ET_DYN && addr_min && map!=(void *)addr_min) {
818 base = map - addr_min;
821 for (ph=ph0, i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
822 if (ph->p_type != PT_LOAD) continue;
823 /* Check if the programs headers are in this load segment, and
824 * if so, record the address for use by dl_iterate_phdr. */
825 if (!dso->phdr && eh->e_phoff >= ph->p_offset
826 && eh->e_phoff+phsize <= ph->p_offset+ph->p_filesz) {
827 dso->phdr = (void *)(base + ph->p_vaddr
828 + (eh->e_phoff-ph->p_offset));
829 dso->phnum = eh->e_phnum;
830 dso->phentsize = eh->e_phentsize;
832 this_min = ph->p_vaddr & -PAGE_SIZE;
833 this_max = ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE;
834 off_start = ph->p_offset & -PAGE_SIZE;
835 prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
836 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
837 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
838 /* Reuse the existing mapping for the lowest-address LOAD */
839 if ((ph->p_vaddr & -PAGE_SIZE) != addr_min || DL_NOMMU_SUPPORT)
840 if (mmap_fixed(base+this_min, this_max-this_min, prot, MAP_PRIVATE|MAP_FIXED, fd, off_start) == MAP_FAILED)
842 if (ph->p_memsz > ph->p_filesz && (ph->p_flags&PF_W)) {
843 size_t brk = (size_t)base+ph->p_vaddr+ph->p_filesz;
844 size_t pgbrk = brk+PAGE_SIZE-1 & -PAGE_SIZE;
845 memset((void *)brk, 0, pgbrk-brk & PAGE_SIZE-1);
846 if (pgbrk-(size_t)base < this_max && mmap_fixed((void *)pgbrk, (size_t)base+this_max-pgbrk, prot, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) == MAP_FAILED)
850 for (i=0; ((size_t *)(base+dyn))[i]; i+=2)
851 if (((size_t *)(base+dyn))[i]==DT_TEXTREL) {
852 if (mprotect(map, map_len, PROT_READ|PROT_WRITE|PROT_EXEC)
859 dso->dynv = laddr(dso, dyn);
860 if (dso->tls.size) dso->tls.image = laddr(dso, tls_image);
866 if (map!=MAP_FAILED) unmap_library(dso);
871 static int path_open(const char *name, const char *s, char *buf, size_t buf_size)
876 s += strspn(s, ":\n");
877 l = strcspn(s, ":\n");
878 if (l-1 >= INT_MAX) return -1;
879 if (snprintf(buf, buf_size, "%.*s/%s", (int)l, s, name) < buf_size) {
880 if ((fd = open(buf, O_RDONLY|O_CLOEXEC))>=0) return fd;
888 /* Any negative value but -1 will inhibit
889 * futher path search. */
897 static int fixup_rpath(struct dso *p, char *buf, size_t buf_size)
900 const char *s, *t, *origin;
902 if (p->rpath || !p->rpath_orig) return 0;
903 if (!strchr(p->rpath_orig, '$')) {
904 p->rpath = p->rpath_orig;
909 while ((t=strchr(s, '$'))) {
910 if (strncmp(t, "$ORIGIN", 7) && strncmp(t, "${ORIGIN}", 9))
915 if (n > SSIZE_MAX/PATH_MAX) return 0;
917 if (p->kernel_mapped) {
918 /* $ORIGIN searches cannot be performed for the main program
919 * when it is suid/sgid/AT_SECURE. This is because the
920 * pathname is under the control of the caller of execve.
921 * For libraries, however, $ORIGIN can be processed safely
922 * since the library's pathname came from a trusted source
923 * (either system paths or a call to dlopen). */
926 l = readlink("/proc/self/exe", buf, buf_size);
927 if (l == -1) switch (errno) {
942 t = strrchr(origin, '/');
946 /* Normally p->name will always be an absolute or relative
947 * pathname containing at least one '/' character, but in the
948 * case where ldso was invoked as a command to execute a
949 * program in the working directory, app.name may not. Fix. */
953 /* Disallow non-absolute origins for suid/sgid/AT_SECURE. */
954 if (libc.secure && *origin != '/')
956 p->rpath = malloc(strlen(p->rpath_orig) + n*l + 1);
957 if (!p->rpath) return -1;
961 while ((t=strchr(s, '$'))) {
964 memcpy(d, origin, l);
966 /* It was determined previously that the '$' is followed
967 * either by "ORIGIN" or "{ORIGIN}". */
968 s = t + 7 + 2*(t[1]=='{');
974 static void decode_dyn(struct dso *p)
977 decode_vec(p->dynv, dyn, DYN_CNT);
978 p->syms = laddr(p, dyn[DT_SYMTAB]);
979 p->strings = laddr(p, dyn[DT_STRTAB]);
980 if (dyn[0]&(1<<DT_HASH))
981 p->hashtab = laddr(p, dyn[DT_HASH]);
982 if (dyn[0]&(1<<DT_RPATH))
983 p->rpath_orig = p->strings + dyn[DT_RPATH];
984 if (dyn[0]&(1<<DT_RUNPATH))
985 p->rpath_orig = p->strings + dyn[DT_RUNPATH];
986 if (dyn[0]&(1<<DT_PLTGOT))
987 p->got = laddr(p, dyn[DT_PLTGOT]);
988 if (search_vec(p->dynv, dyn, DT_GNU_HASH))
989 p->ghashtab = laddr(p, *dyn);
990 if (search_vec(p->dynv, dyn, DT_VERSYM))
991 p->versym = laddr(p, *dyn);
994 static size_t count_syms(struct dso *p)
996 if (p->hashtab) return p->hashtab[1];
999 uint32_t *buckets = p->ghashtab + 4 + (p->ghashtab[2]*sizeof(size_t)/4);
1001 for (i = nsym = 0; i < p->ghashtab[0]; i++) {
1002 if (buckets[i] > nsym)
1006 hashval = buckets + p->ghashtab[0] + (nsym - p->ghashtab[1]);
1008 while (!(*hashval++ & 1));
1013 static void *dl_mmap(size_t n)
1016 int prot = PROT_READ|PROT_WRITE, flags = MAP_ANONYMOUS|MAP_PRIVATE;
1018 p = (void *)__syscall(SYS_mmap2, 0, n, prot, flags, -1, 0);
1020 p = (void *)__syscall(SYS_mmap, 0, n, prot, flags, -1, 0);
1022 return (unsigned long)p > -4096UL ? 0 : p;
1025 static void makefuncdescs(struct dso *p)
1027 static int self_done;
1028 size_t nsym = count_syms(p);
1029 size_t i, size = nsym * sizeof(*p->funcdescs);
1032 p->funcdescs = dl_mmap(size);
1035 p->funcdescs = malloc(size);
1037 if (!p->funcdescs) {
1038 if (!runtime) a_crash();
1039 error("Error allocating function descriptors for %s", p->name);
1040 longjmp(*rtld_fail, 1);
1042 for (i=0; i<nsym; i++) {
1043 if ((p->syms[i].st_info&0xf)==STT_FUNC && p->syms[i].st_shndx) {
1044 p->funcdescs[i].addr = laddr(p, p->syms[i].st_value);
1045 p->funcdescs[i].got = p->got;
1047 p->funcdescs[i].addr = 0;
1048 p->funcdescs[i].got = 0;
1053 static struct dso *load_library(const char *name, struct dso *needed_by)
1055 char buf[2*NAME_MAX+2];
1056 const char *pathname;
1058 struct dso *p, temp_dso = {0};
1070 /* Catch and block attempts to reload the implementation itself */
1071 if (name[0]=='l' && name[1]=='i' && name[2]=='b') {
1072 static const char reserved[] =
1073 "c.pthread.rt.m.dl.util.xnet.";
1074 const char *rp, *next;
1075 for (rp=reserved; *rp; rp=next) {
1076 next = strchr(rp, '.') + 1;
1077 if (strncmp(name+3, rp, next-rp) == 0)
1082 /* Track which names have been resolved
1083 * and only report each one once. */
1084 static unsigned reported;
1085 unsigned mask = 1U<<(rp-reserved);
1086 if (!(reported & mask)) {
1088 dprintf(1, "\t%s => %s (%p)\n",
1096 if (!strcmp(name, ldso.name)) is_self = 1;
1105 if (strchr(name, '/')) {
1107 fd = open(name, O_RDONLY|O_CLOEXEC);
1109 /* Search for the name to see if it's already loaded */
1110 for (p=head->next; p; p=p->next) {
1111 if (p->shortname && !strcmp(p->shortname, name)) {
1115 if (strlen(name) > NAME_MAX) return 0;
1117 if (env_path) fd = path_open(name, env_path, buf, sizeof buf);
1118 for (p=needed_by; fd == -1 && p; p=p->needed_by) {
1119 if (fixup_rpath(p, buf, sizeof buf) < 0)
1120 fd = -2; /* Inhibit further search. */
1122 fd = path_open(name, p->rpath, buf, sizeof buf);
1128 if (ldso.name[0]=='/') {
1130 for (s=t=z=ldso.name; *s; s++)
1131 if (*s=='/') z=t, t=s;
1132 prefix_len = z-ldso.name;
1133 if (prefix_len < PATH_MAX)
1140 char etc_ldso_path[prefix_len + 1
1141 + sizeof "/etc/ld-musl-" LDSO_ARCH ".path"];
1142 snprintf(etc_ldso_path, sizeof etc_ldso_path,
1143 "%.*s/etc/ld-musl-" LDSO_ARCH ".path",
1144 (int)prefix_len, prefix);
1145 fd = open(etc_ldso_path, O_RDONLY|O_CLOEXEC);
1148 if (!fstat(fd, &st)) n = st.st_size;
1149 if ((sys_path = malloc(n+1)))
1151 if (!sys_path || read_loop(fd, sys_path, n)<0) {
1156 } else if (errno != ENOENT) {
1160 if (!sys_path) sys_path = "/lib:/usr/local/lib:/usr/lib";
1161 fd = path_open(name, sys_path, buf, sizeof buf);
1165 if (fd < 0) return 0;
1166 if (fstat(fd, &st) < 0) {
1170 for (p=head->next; p; p=p->next) {
1171 if (p->dev == st.st_dev && p->ino == st.st_ino) {
1172 /* If this library was previously loaded with a
1173 * pathname but a search found the same inode,
1174 * setup its shortname so it can be found by name. */
1175 if (!p->shortname && pathname != name)
1176 p->shortname = strrchr(p->name, '/')+1;
1181 map = noload ? 0 : map_library(fd, &temp_dso);
1185 /* Avoid the danger of getting two versions of libc mapped into the
1186 * same process when an absolute pathname was used. The symbols
1187 * checked are chosen to catch both musl and glibc, and to avoid
1188 * false positives from interposition-hack libraries. */
1189 decode_dyn(&temp_dso);
1190 if (find_sym(&temp_dso, "__libc_start_main", 1).sym &&
1191 find_sym(&temp_dso, "stdin", 1).sym) {
1192 unmap_library(&temp_dso);
1193 return load_library("libc.so", needed_by);
1195 /* Past this point, if we haven't reached runtime yet, ldso has
1196 * committed either to use the mapped library or to abort execution.
1197 * Unmapping is not possible, so we can safely reclaim gaps. */
1198 if (!runtime) reclaim_gaps(&temp_dso);
1200 /* Allocate storage for the new DSO. When there is TLS, this
1201 * storage must include a reservation for all pre-existing
1202 * threads to obtain copies of both the new TLS, and an
1203 * extended DTV capable of storing an additional slot for
1204 * the newly-loaded DSO. */
1205 alloc_size = sizeof *p + strlen(pathname) + 1;
1206 if (runtime && temp_dso.tls.image) {
1207 size_t per_th = temp_dso.tls.size + temp_dso.tls.align
1208 + sizeof(void *) * (tls_cnt+3);
1209 n_th = libc.threads_minus_1 + 1;
1210 if (n_th > SSIZE_MAX / per_th) alloc_size = SIZE_MAX;
1211 else alloc_size += n_th * per_th;
1213 p = calloc(1, alloc_size);
1215 unmap_library(&temp_dso);
1218 memcpy(p, &temp_dso, sizeof temp_dso);
1221 p->needed_by = needed_by;
1223 p->runtime_loaded = runtime;
1224 strcpy(p->name, pathname);
1225 /* Add a shortname only if name arg was not an explicit pathname. */
1226 if (pathname != name) p->shortname = strrchr(p->name, '/')+1;
1228 p->tls_id = ++tls_cnt;
1229 tls_align = MAXP2(tls_align, p->tls.align);
1231 p->tls.offset = tls_offset + ( (p->tls.align-1) &
1232 (-tls_offset + (uintptr_t)p->tls.image) );
1233 tls_offset = p->tls.offset + p->tls.size;
1235 tls_offset += p->tls.size + p->tls.align - 1;
1236 tls_offset -= (tls_offset + (uintptr_t)p->tls.image)
1238 p->tls.offset = tls_offset;
1240 p->new_dtv = (void *)(-sizeof(size_t) &
1241 (uintptr_t)(p->name+strlen(p->name)+sizeof(size_t)));
1242 p->new_tls = (void *)(p->new_dtv + n_th*(tls_cnt+1));
1243 if (tls_tail) tls_tail->next = &p->tls;
1244 else libc.tls_head = &p->tls;
1252 if (DL_FDPIC) makefuncdescs(p);
1254 if (ldd_mode) dprintf(1, "\t%s => %s (%p)\n", name, pathname, p->base);
1259 static void load_direct_deps(struct dso *p)
1263 if (p->deps) return;
1264 /* For head, all preloads are direct pseudo-dependencies.
1265 * Count and include them now to avoid realloc later. */
1266 if (p==head) for (struct dso *q=p->next; q; q=q->next)
1268 for (i=0; p->dynv[i]; i+=2)
1269 if (p->dynv[i] == DT_NEEDED) cnt++;
1270 /* Use builtin buffer for apps with no external deps, to
1271 * preserve property of no runtime failure paths. */
1272 p->deps = (p==head && cnt<2) ? builtin_deps :
1273 calloc(cnt+1, sizeof *p->deps);
1275 error("Error loading dependencies for %s", p->name);
1276 if (runtime) longjmp(*rtld_fail, 1);
1279 if (p==head) for (struct dso *q=p->next; q; q=q->next)
1281 for (i=0; p->dynv[i]; i+=2) {
1282 if (p->dynv[i] != DT_NEEDED) continue;
1283 struct dso *dep = load_library(p->strings + p->dynv[i+1], p);
1285 error("Error loading shared library %s: %m (needed by %s)",
1286 p->strings + p->dynv[i+1], p->name);
1287 if (runtime) longjmp(*rtld_fail, 1);
1290 p->deps[cnt++] = dep;
1293 p->ndeps_direct = cnt;
1296 static void load_deps(struct dso *p)
1298 if (p->deps) return;
1299 for (; p; p=p->next)
1300 load_direct_deps(p);
1303 static void extend_bfs_deps(struct dso *p)
1305 size_t i, j, cnt, ndeps_all;
1308 /* Can't use realloc if the original p->deps was allocated at
1309 * program entry and malloc has been replaced, or if it's
1310 * the builtin non-allocated trivial main program deps array. */
1311 int no_realloc = (__malloc_replaced && !p->runtime_loaded)
1312 || p->deps == builtin_deps;
1314 if (p->bfs_built) return;
1315 ndeps_all = p->ndeps_direct;
1317 /* Mark existing (direct) deps so they won't be duplicated. */
1318 for (i=0; p->deps[i]; i++)
1319 p->deps[i]->mark = 1;
1321 /* For each dependency already in the list, copy its list of direct
1322 * dependencies to the list, excluding any items already in the
1323 * list. Note that the list this loop iterates over will grow during
1324 * the loop, but since duplicates are excluded, growth is bounded. */
1325 for (i=0; p->deps[i]; i++) {
1326 struct dso *dep = p->deps[i];
1327 for (j=cnt=0; j<dep->ndeps_direct; j++)
1328 if (!dep->deps[j]->mark) cnt++;
1330 malloc(sizeof(*tmp) * (ndeps_all+cnt+1)) :
1331 realloc(p->deps, sizeof(*tmp) * (ndeps_all+cnt+1));
1333 error("Error recording dependencies for %s", p->name);
1334 if (runtime) longjmp(*rtld_fail, 1);
1338 memcpy(tmp, p->deps, sizeof(*tmp) * (ndeps_all+1));
1342 for (j=0; j<dep->ndeps_direct; j++) {
1343 if (dep->deps[j]->mark) continue;
1344 dep->deps[j]->mark = 1;
1345 p->deps[ndeps_all++] = dep->deps[j];
1347 p->deps[ndeps_all] = 0;
1350 for (p=head; p; p=p->next)
1354 static void load_preload(char *s)
1358 for (z=s; *z; s=z) {
1359 for ( ; *s && (isspace(*s) || *s==':'); s++);
1360 for (z=s; *z && !isspace(*z) && *z!=':'; z++);
1368 static void add_syms(struct dso *p)
1370 if (!p->syms_next && syms_tail != p) {
1371 syms_tail->syms_next = p;
1376 static void revert_syms(struct dso *old_tail)
1378 struct dso *p, *next;
1379 /* Chop off the tail of the list of dsos that participate in
1380 * the global symbol table, reverting them to RTLD_LOCAL. */
1381 for (p=old_tail; p; p=next) {
1382 next = p->syms_next;
1385 syms_tail = old_tail;
1388 static void do_mips_relocs(struct dso *p, size_t *got)
1390 size_t i, j, rel[2];
1391 unsigned char *base = p->base;
1392 i=0; search_vec(p->dynv, &i, DT_MIPS_LOCAL_GOTNO);
1396 while (i--) *got++ += (size_t)base;
1398 j=0; search_vec(p->dynv, &j, DT_MIPS_GOTSYM);
1399 i=0; search_vec(p->dynv, &i, DT_MIPS_SYMTABNO);
1400 Sym *sym = p->syms + j;
1401 rel[0] = (unsigned char *)got - base;
1402 for (i-=j; i; i--, sym++, rel[0]+=sizeof(size_t)) {
1403 rel[1] = R_INFO(sym-p->syms, R_MIPS_JUMP_SLOT);
1404 do_relocs(p, rel, sizeof rel, 2);
1408 static void reloc_all(struct dso *p)
1410 size_t dyn[DYN_CNT];
1411 for (; p; p=p->next) {
1412 if (p->relocated) continue;
1413 decode_vec(p->dynv, dyn, DYN_CNT);
1414 if (NEED_MIPS_GOT_RELOCS)
1415 do_mips_relocs(p, laddr(p, dyn[DT_PLTGOT]));
1416 do_relocs(p, laddr(p, dyn[DT_JMPREL]), dyn[DT_PLTRELSZ],
1417 2+(dyn[DT_PLTREL]==DT_RELA));
1418 do_relocs(p, laddr(p, dyn[DT_REL]), dyn[DT_RELSZ], 2);
1419 do_relocs(p, laddr(p, dyn[DT_RELA]), dyn[DT_RELASZ], 3);
1421 do_relr_relocs(p, laddr(p, dyn[DT_RELR]), dyn[DT_RELRSZ]);
1423 if (head != &ldso && p->relro_start != p->relro_end) {
1424 long ret = __syscall(SYS_mprotect, laddr(p, p->relro_start),
1425 p->relro_end-p->relro_start, PROT_READ);
1426 if (ret != 0 && ret != -ENOSYS) {
1427 error("Error relocating %s: RELRO protection failed: %m",
1429 if (runtime) longjmp(*rtld_fail, 1);
1437 static void kernel_mapped_dso(struct dso *p)
1439 size_t min_addr = -1, max_addr = 0, cnt;
1441 for (cnt = p->phnum; cnt--; ph = (void *)((char *)ph + p->phentsize)) {
1442 if (ph->p_type == PT_DYNAMIC) {
1443 p->dynv = laddr(p, ph->p_vaddr);
1444 } else if (ph->p_type == PT_GNU_RELRO) {
1445 p->relro_start = ph->p_vaddr & -PAGE_SIZE;
1446 p->relro_end = (ph->p_vaddr + ph->p_memsz) & -PAGE_SIZE;
1447 } else if (ph->p_type == PT_GNU_STACK) {
1448 if (!runtime && ph->p_memsz > __default_stacksize) {
1449 __default_stacksize =
1450 ph->p_memsz < DEFAULT_STACK_MAX ?
1451 ph->p_memsz : DEFAULT_STACK_MAX;
1454 if (ph->p_type != PT_LOAD) continue;
1455 if (ph->p_vaddr < min_addr)
1456 min_addr = ph->p_vaddr;
1457 if (ph->p_vaddr+ph->p_memsz > max_addr)
1458 max_addr = ph->p_vaddr+ph->p_memsz;
1460 min_addr &= -PAGE_SIZE;
1461 max_addr = (max_addr + PAGE_SIZE-1) & -PAGE_SIZE;
1462 p->map = p->base + min_addr;
1463 p->map_len = max_addr - min_addr;
1464 p->kernel_mapped = 1;
1467 void __libc_exit_fini()
1470 size_t dyn[DYN_CNT];
1471 pthread_t self = __pthread_self();
1473 /* Take both locks before setting shutting_down, so that
1474 * either lock is sufficient to read its value. The lock
1475 * order matches that in dlopen to avoid deadlock. */
1476 pthread_rwlock_wrlock(&lock);
1477 pthread_mutex_lock(&init_fini_lock);
1479 pthread_rwlock_unlock(&lock);
1480 for (p=fini_head; p; p=p->fini_next) {
1481 while (p->ctor_visitor && p->ctor_visitor!=self)
1482 pthread_cond_wait(&ctor_cond, &init_fini_lock);
1483 if (!p->constructed) continue;
1484 decode_vec(p->dynv, dyn, DYN_CNT);
1485 if (dyn[0] & (1<<DT_FINI_ARRAY)) {
1486 size_t n = dyn[DT_FINI_ARRAYSZ]/sizeof(size_t);
1487 size_t *fn = (size_t *)laddr(p, dyn[DT_FINI_ARRAY])+n;
1488 while (n--) ((void (*)(void))*--fn)();
1490 #ifndef NO_LEGACY_INITFINI
1491 if ((dyn[0] & (1<<DT_FINI)) && dyn[DT_FINI])
1492 fpaddr(p, dyn[DT_FINI])();
1497 void __ldso_atfork(int who)
1500 pthread_rwlock_wrlock(&lock);
1501 pthread_mutex_lock(&init_fini_lock);
1503 pthread_mutex_unlock(&init_fini_lock);
1504 pthread_rwlock_unlock(&lock);
1508 static struct dso **queue_ctors(struct dso *dso)
1510 size_t cnt, qpos, spos, i;
1511 struct dso *p, **queue, **stack;
1513 if (ldd_mode) return 0;
1515 /* Bound on queue size is the total number of indirect deps.
1516 * If a bfs deps list was built, we can use it. Otherwise,
1517 * bound by the total number of DSOs, which is always safe and
1518 * is reasonable we use it (for main app at startup). */
1519 if (dso->bfs_built) {
1520 for (cnt=0; dso->deps[cnt]; cnt++)
1521 dso->deps[cnt]->mark = 0;
1522 cnt++; /* self, not included in deps */
1524 for (cnt=0, p=head; p; cnt++, p=p->next)
1527 cnt++; /* termination slot */
1528 if (dso==head && cnt <= countof(builtin_ctor_queue))
1529 queue = builtin_ctor_queue;
1531 queue = calloc(cnt, sizeof *queue);
1534 error("Error allocating constructor queue: %m\n");
1535 if (runtime) longjmp(*rtld_fail, 1);
1539 /* Opposite ends of the allocated buffer serve as an output queue
1540 * and a working stack. Setup initial stack with just the argument
1541 * dso and initial queue empty... */
1545 stack[--spos] = dso;
1549 /* Then perform pseudo-DFS sort, but ignoring circular deps. */
1552 while (p->next_dep < p->ndeps_direct) {
1553 if (p->deps[p->next_dep]->mark) {
1557 p = p->deps[p->next_dep];
1565 for (i=0; i<qpos; i++) queue[i]->mark = 0;
1566 for (i=0; i<qpos; i++)
1567 if (queue[i]->ctor_visitor && queue[i]->ctor_visitor->tid < 0) {
1568 error("State of %s is inconsistent due to multithreaded fork\n",
1571 if (runtime) longjmp(*rtld_fail, 1);
1577 static void do_init_fini(struct dso **queue)
1580 size_t dyn[DYN_CNT], i;
1581 pthread_t self = __pthread_self();
1583 pthread_mutex_lock(&init_fini_lock);
1584 for (i=0; (p=queue[i]); i++) {
1585 while ((p->ctor_visitor && p->ctor_visitor!=self) || shutting_down)
1586 pthread_cond_wait(&ctor_cond, &init_fini_lock);
1587 if (p->ctor_visitor || p->constructed)
1589 p->ctor_visitor = self;
1591 decode_vec(p->dynv, dyn, DYN_CNT);
1592 if (dyn[0] & ((1<<DT_FINI) | (1<<DT_FINI_ARRAY))) {
1593 p->fini_next = fini_head;
1597 pthread_mutex_unlock(&init_fini_lock);
1599 #ifndef NO_LEGACY_INITFINI
1600 if ((dyn[0] & (1<<DT_INIT)) && dyn[DT_INIT])
1601 fpaddr(p, dyn[DT_INIT])();
1603 if (dyn[0] & (1<<DT_INIT_ARRAY)) {
1604 size_t n = dyn[DT_INIT_ARRAYSZ]/sizeof(size_t);
1605 size_t *fn = laddr(p, dyn[DT_INIT_ARRAY]);
1606 while (n--) ((void (*)(void))*fn++)();
1609 pthread_mutex_lock(&init_fini_lock);
1610 p->ctor_visitor = 0;
1612 pthread_cond_broadcast(&ctor_cond);
1614 pthread_mutex_unlock(&init_fini_lock);
1617 void __libc_start_init(void)
1619 do_init_fini(main_ctor_queue);
1620 if (!__malloc_replaced && main_ctor_queue != builtin_ctor_queue)
1621 free(main_ctor_queue);
1622 main_ctor_queue = 0;
1625 static void dl_debug_state(void)
1629 weak_alias(dl_debug_state, _dl_debug_state);
1631 void __init_tls(size_t *auxv)
1635 static void update_tls_size()
1637 libc.tls_cnt = tls_cnt;
1638 libc.tls_align = tls_align;
1639 libc.tls_size = ALIGN(
1640 (1+tls_cnt) * sizeof(void *) +
1642 sizeof(struct pthread) +
1647 static void install_new_tls(void)
1650 pthread_t self = __pthread_self(), td;
1651 struct dso *dtv_provider = container_of(tls_tail, struct dso, tls);
1652 uintptr_t (*newdtv)[tls_cnt+1] = (void *)dtv_provider->new_dtv;
1655 size_t old_cnt = self->dtv[0];
1657 __block_app_sigs(&set);
1659 /* Copy existing dtv contents from all existing threads. */
1660 for (i=0, td=self; !i || td!=self; i++, td=td->next) {
1661 memcpy(newdtv+i, td->dtv,
1662 (old_cnt+1)*sizeof(uintptr_t));
1663 newdtv[i][0] = tls_cnt;
1665 /* Install new dtls into the enlarged, uninstalled dtv copies. */
1666 for (p=head; ; p=p->next) {
1667 if (p->tls_id <= old_cnt) continue;
1668 unsigned char *mem = p->new_tls;
1669 for (j=0; j<i; j++) {
1670 unsigned char *new = mem;
1671 new += ((uintptr_t)p->tls.image - (uintptr_t)mem)
1673 memcpy(new, p->tls.image, p->tls.len);
1674 newdtv[j][p->tls_id] =
1675 (uintptr_t)new + DTP_OFFSET;
1676 mem += p->tls.size + p->tls.align;
1678 if (p->tls_id == tls_cnt) break;
1681 /* Broadcast barrier to ensure contents of new dtv is visible
1682 * if the new dtv pointer is. The __membarrier function has a
1683 * fallback emulation using signals for kernels that lack the
1684 * feature at the syscall level. */
1686 __membarrier(MEMBARRIER_CMD_PRIVATE_EXPEDITED, 0);
1688 /* Install new dtv for each thread. */
1689 for (j=0, td=self; !j || td!=self; j++, td=td->next) {
1690 td->dtv = newdtv[j];
1694 __restore_sigs(&set);
1697 /* Stage 1 of the dynamic linker is defined in dlstart.c. It calls the
1698 * following stage 2 and stage 3 functions via primitive symbolic lookup
1699 * since it does not have access to their addresses to begin with. */
1701 /* Stage 2 of the dynamic linker is called after relative relocations
1702 * have been processed. It can make function calls to static functions
1703 * and access string literals and static data, but cannot use extern
1704 * symbols. Its job is to perform symbolic relocations on the dynamic
1705 * linker itself, but some of the relocations performed may need to be
1706 * replaced later due to copy relocations in the main program. */
1708 hidden void __dls2(unsigned char *base, size_t *sp)
1711 for (auxv=sp+1+*sp+1; *auxv; auxv++);
1714 void *p1 = (void *)sp[-2];
1715 void *p2 = (void *)sp[-1];
1717 size_t aux[AUX_CNT];
1718 decode_vec(auxv, aux, AUX_CNT);
1719 if (aux[AT_BASE]) ldso.base = (void *)aux[AT_BASE];
1720 else ldso.base = (void *)(aux[AT_PHDR] & -4096);
1722 app_loadmap = p2 ? p1 : 0;
1723 ldso.loadmap = p2 ? p2 : p1;
1724 ldso.base = laddr(&ldso, 0);
1728 Ehdr *ehdr = (void *)ldso.base;
1729 ldso.name = ldso.shortname = "libc.so";
1730 ldso.phnum = ehdr->e_phnum;
1731 ldso.phdr = laddr(&ldso, ehdr->e_phoff);
1732 ldso.phentsize = ehdr->e_phentsize;
1733 search_vec(auxv, &ldso_page_size, AT_PAGESZ);
1734 kernel_mapped_dso(&ldso);
1737 if (DL_FDPIC) makefuncdescs(&ldso);
1739 /* Prepare storage for to save clobbered REL addends so they
1740 * can be reused in stage 3. There should be very few. If
1741 * something goes wrong and there are a huge number, abort
1742 * instead of risking stack overflow. */
1743 size_t dyn[DYN_CNT];
1744 decode_vec(ldso.dynv, dyn, DYN_CNT);
1745 size_t *rel = laddr(&ldso, dyn[DT_REL]);
1746 size_t rel_size = dyn[DT_RELSZ];
1747 size_t symbolic_rel_cnt = 0;
1748 apply_addends_to = rel;
1749 for (; rel_size; rel+=2, rel_size-=2*sizeof(size_t))
1750 if (!IS_RELATIVE(rel[1], ldso.syms)) symbolic_rel_cnt++;
1751 if (symbolic_rel_cnt >= ADDEND_LIMIT) a_crash();
1752 size_t addends[symbolic_rel_cnt+1];
1753 saved_addends = addends;
1760 /* Call dynamic linker stage-2b, __dls2b, looking it up
1761 * symbolically as a barrier against moving the address
1762 * load across the above relocation processing. */
1763 struct symdef dls2b_def = find_sym(&ldso, "__dls2b", 0);
1764 if (DL_FDPIC) ((stage3_func)&ldso.funcdescs[dls2b_def.sym-ldso.syms])(sp, auxv);
1765 else ((stage3_func)laddr(&ldso, dls2b_def.sym->st_value))(sp, auxv);
1768 /* Stage 2b sets up a valid thread pointer, which requires relocations
1769 * completed in stage 2, and on which stage 3 is permitted to depend.
1770 * This is done as a separate stage, with symbolic lookup as a barrier,
1771 * so that loads of the thread pointer and &errno can be pure/const and
1772 * thereby hoistable. */
1774 void __dls2b(size_t *sp, size_t *auxv)
1776 /* Setup early thread pointer in builtin_tls for ldso/libc itself to
1777 * use during dynamic linking. If possible it will also serve as the
1778 * thread pointer at runtime. */
1779 search_vec(auxv, &__hwcap, AT_HWCAP);
1781 libc.tls_size = sizeof builtin_tls;
1782 libc.tls_align = tls_align;
1783 if (__init_tp(__copy_tls((void *)builtin_tls)) < 0) {
1787 struct symdef dls3_def = find_sym(&ldso, "__dls3", 0);
1788 if (DL_FDPIC) ((stage3_func)&ldso.funcdescs[dls3_def.sym-ldso.syms])(sp, auxv);
1789 else ((stage3_func)laddr(&ldso, dls3_def.sym->st_value))(sp, auxv);
1792 /* Stage 3 of the dynamic linker is called with the dynamic linker/libc
1793 * fully functional. Its job is to load (if not already loaded) and
1794 * process dependencies and relocations for the main application and
1795 * transfer control to its entry point. */
1797 void __dls3(size_t *sp, size_t *auxv)
1799 static struct dso app, vdso;
1800 size_t aux[AUX_CNT];
1802 char *env_preload=0;
1803 char *replace_argv0=0;
1806 char **argv = (void *)(sp+1);
1807 char **argv_orig = argv;
1808 char **envp = argv+argc+1;
1810 /* Find aux vector just past environ[] and use it to initialize
1811 * global data that may be needed before we can make syscalls. */
1813 decode_vec(auxv, aux, AUX_CNT);
1814 search_vec(auxv, &__sysinfo, AT_SYSINFO);
1815 __pthread_self()->sysinfo = __sysinfo;
1816 libc.page_size = aux[AT_PAGESZ];
1817 libc.secure = ((aux[0]&0x7800)!=0x7800 || aux[AT_UID]!=aux[AT_EUID]
1818 || aux[AT_GID]!=aux[AT_EGID] || aux[AT_SECURE]);
1820 /* Only trust user/env if kernel says we're not suid/sgid */
1822 env_path = getenv("LD_LIBRARY_PATH");
1823 env_preload = getenv("LD_PRELOAD");
1826 /* Activate error handler function */
1829 /* If the main program was already loaded by the kernel,
1830 * AT_PHDR will point to some location other than the dynamic
1831 * linker's program headers. */
1832 if (aux[AT_PHDR] != (size_t)ldso.phdr) {
1833 size_t interp_off = 0;
1834 size_t tls_image = 0;
1835 /* Find load address of the main program, via AT_PHDR vs PT_PHDR. */
1836 Phdr *phdr = app.phdr = (void *)aux[AT_PHDR];
1837 app.phnum = aux[AT_PHNUM];
1838 app.phentsize = aux[AT_PHENT];
1839 for (i=aux[AT_PHNUM]; i; i--, phdr=(void *)((char *)phdr + aux[AT_PHENT])) {
1840 if (phdr->p_type == PT_PHDR)
1841 app.base = (void *)(aux[AT_PHDR] - phdr->p_vaddr);
1842 else if (phdr->p_type == PT_INTERP)
1843 interp_off = (size_t)phdr->p_vaddr;
1844 else if (phdr->p_type == PT_TLS) {
1845 tls_image = phdr->p_vaddr;
1846 app.tls.len = phdr->p_filesz;
1847 app.tls.size = phdr->p_memsz;
1848 app.tls.align = phdr->p_align;
1851 if (DL_FDPIC) app.loadmap = app_loadmap;
1852 if (app.tls.size) app.tls.image = laddr(&app, tls_image);
1853 if (interp_off) ldso.name = laddr(&app, interp_off);
1854 if ((aux[0] & (1UL<<AT_EXECFN))
1855 && strncmp((char *)aux[AT_EXECFN], "/proc/", 6))
1856 app.name = (char *)aux[AT_EXECFN];
1859 kernel_mapped_dso(&app);
1862 char *ldname = argv[0];
1863 size_t l = strlen(ldname);
1864 if (l >= 3 && !strcmp(ldname+l-3, "ldd")) ldd_mode = 1;
1866 while (argv[0] && argv[0][0]=='-' && argv[0][1]=='-') {
1867 char *opt = argv[0]+2;
1868 *argv++ = (void *)-1;
1871 } else if (!memcmp(opt, "list", 5)) {
1873 } else if (!memcmp(opt, "library-path", 12)) {
1874 if (opt[12]=='=') env_path = opt+13;
1875 else if (opt[12]) *argv = 0;
1876 else if (*argv) env_path = *argv++;
1877 } else if (!memcmp(opt, "preload", 7)) {
1878 if (opt[7]=='=') env_preload = opt+8;
1879 else if (opt[7]) *argv = 0;
1880 else if (*argv) env_preload = *argv++;
1881 } else if (!memcmp(opt, "argv0", 5)) {
1882 if (opt[5]=='=') replace_argv0 = opt+6;
1883 else if (opt[5]) *argv = 0;
1884 else if (*argv) replace_argv0 = *argv++;
1889 argv[-1] = (void *)(argc - (argv-argv_orig));
1891 dprintf(2, "musl libc (" LDSO_ARCH ")\n"
1893 "Dynamic Program Loader\n"
1894 "Usage: %s [options] [--] pathname%s\n",
1895 __libc_version, ldname,
1896 ldd_mode ? "" : " [args]");
1899 fd = open(argv[0], O_RDONLY);
1901 dprintf(2, "%s: cannot load %s: %s\n", ldname, argv[0], strerror(errno));
1904 Ehdr *ehdr = map_library(fd, &app);
1906 dprintf(2, "%s: %s: Not a valid dynamic program\n", ldname, argv[0]);
1912 aux[AT_ENTRY] = (size_t)laddr(&app, ehdr->e_entry);
1913 /* Find the name that would have been used for the dynamic
1914 * linker had ldd not taken its place. */
1916 for (i=0; i<app.phnum; i++) {
1917 if (app.phdr[i].p_type == PT_INTERP)
1918 ldso.name = laddr(&app, app.phdr[i].p_vaddr);
1920 dprintf(1, "\t%s (%p)\n", ldso.name, ldso.base);
1924 libc.tls_head = tls_tail = &app.tls;
1925 app.tls_id = tls_cnt = 1;
1927 app.tls.offset = GAP_ABOVE_TP;
1928 app.tls.offset += (-GAP_ABOVE_TP + (uintptr_t)app.tls.image)
1929 & (app.tls.align-1);
1930 tls_offset = app.tls.offset + app.tls.size;
1932 tls_offset = app.tls.offset = app.tls.size
1933 + ( -((uintptr_t)app.tls.image + app.tls.size)
1934 & (app.tls.align-1) );
1936 tls_align = MAXP2(tls_align, app.tls.align);
1940 makefuncdescs(&app);
1942 app.loadmap = (void *)&app_dummy_loadmap;
1943 app.loadmap->nsegs = 1;
1944 app.loadmap->segs[0].addr = (size_t)app.map;
1945 app.loadmap->segs[0].p_vaddr = (size_t)app.map
1947 app.loadmap->segs[0].p_memsz = app.map_len;
1949 argv[-3] = (void *)app.loadmap;
1952 /* Initial dso chain consists only of the app. */
1953 head = tail = syms_tail = &app;
1955 /* Donate unused parts of app and library mapping to malloc */
1957 reclaim_gaps(&ldso);
1959 /* Load preload/needed libraries, add symbols to global namespace. */
1960 ldso.deps = (struct dso **)no_deps;
1961 if (env_preload) load_preload(env_preload);
1963 for (struct dso *p=head; p; p=p->next)
1966 /* Attach to vdso, if provided by the kernel, last so that it does
1967 * not become part of the global namespace. */
1968 if (search_vec(auxv, &vdso_base, AT_SYSINFO_EHDR) && vdso_base) {
1969 Ehdr *ehdr = (void *)vdso_base;
1970 Phdr *phdr = vdso.phdr = (void *)(vdso_base + ehdr->e_phoff);
1971 vdso.phnum = ehdr->e_phnum;
1972 vdso.phentsize = ehdr->e_phentsize;
1973 for (i=ehdr->e_phnum; i; i--, phdr=(void *)((char *)phdr + ehdr->e_phentsize)) {
1974 if (phdr->p_type == PT_DYNAMIC)
1975 vdso.dynv = (void *)(vdso_base + phdr->p_offset);
1976 if (phdr->p_type == PT_LOAD)
1977 vdso.base = (void *)(vdso_base - phdr->p_vaddr + phdr->p_offset);
1980 vdso.shortname = "linux-gate.so.1";
1982 vdso.deps = (struct dso **)no_deps;
1989 for (i=0; app.dynv[i]; i+=2) {
1990 if (!DT_DEBUG_INDIRECT && app.dynv[i]==DT_DEBUG)
1991 app.dynv[i+1] = (size_t)&debug;
1992 if (DT_DEBUG_INDIRECT && app.dynv[i]==DT_DEBUG_INDIRECT) {
1993 size_t *ptr = (size_t *) app.dynv[i+1];
1994 *ptr = (size_t)&debug;
1996 if (app.dynv[i]==DT_DEBUG_INDIRECT_REL) {
1997 size_t *ptr = (size_t *)((size_t)&app.dynv[i] + app.dynv[i+1]);
1998 *ptr = (size_t)&debug;
2002 /* This must be done before final relocations, since it calls
2003 * malloc, which may be provided by the application. Calling any
2004 * application code prior to the jump to its entry point is not
2005 * valid in our model and does not work with FDPIC, where there
2006 * are additional relocation-like fixups that only the entry point
2007 * code can see to perform. */
2008 main_ctor_queue = queue_ctors(&app);
2010 /* Initial TLS must also be allocated before final relocations
2011 * might result in calloc being a call to application code. */
2013 void *initial_tls = builtin_tls;
2014 if (libc.tls_size > sizeof builtin_tls || tls_align > MIN_TLS_ALIGN) {
2015 initial_tls = calloc(libc.tls_size, 1);
2017 dprintf(2, "%s: Error getting %zu bytes thread-local storage: %m\n",
2018 argv[0], libc.tls_size);
2022 static_tls_cnt = tls_cnt;
2024 /* The main program must be relocated LAST since it may contain
2025 * copy relocations which depend on libraries' relocations. */
2026 reloc_all(app.next);
2029 /* Actual copying to new TLS needs to happen after relocations,
2030 * since the TLS images might have contained relocated addresses. */
2031 if (initial_tls != builtin_tls) {
2032 if (__init_tp(__copy_tls(initial_tls)) < 0) {
2036 size_t tmp_tls_size = libc.tls_size;
2037 pthread_t self = __pthread_self();
2038 /* Temporarily set the tls size to the full size of
2039 * builtin_tls so that __copy_tls will use the same layout
2040 * as it did for before. Then check, just to be safe. */
2041 libc.tls_size = sizeof builtin_tls;
2042 if (__copy_tls((void*)builtin_tls) != self) a_crash();
2043 libc.tls_size = tmp_tls_size;
2046 if (ldso_fail) _exit(127);
2047 if (ldd_mode) _exit(0);
2049 /* Determine if malloc was interposed by a replacement implementation
2050 * so that calloc and the memalign family can harden against the
2051 * possibility of incomplete replacement. */
2052 if (find_sym(head, "malloc", 1).dso != &ldso)
2053 __malloc_replaced = 1;
2054 if (find_sym(head, "aligned_alloc", 1).dso != &ldso)
2055 __aligned_alloc_replaced = 1;
2057 /* Switch to runtime mode: any further failures in the dynamic
2058 * linker are a reportable failure rather than a fatal startup
2063 debug.bp = dl_debug_state;
2065 debug.base = ldso.base;
2066 debug.state = RT_CONSISTENT;
2069 if (replace_argv0) argv[0] = replace_argv0;
2073 CRTJMP((void *)aux[AT_ENTRY], argv-1);
2077 static void prepare_lazy(struct dso *p)
2079 size_t dyn[DYN_CNT], n, flags1=0;
2080 decode_vec(p->dynv, dyn, DYN_CNT);
2081 search_vec(p->dynv, &flags1, DT_FLAGS_1);
2082 if (dyn[DT_BIND_NOW] || (dyn[DT_FLAGS] & DF_BIND_NOW) || (flags1 & DF_1_NOW))
2084 n = dyn[DT_RELSZ]/2 + dyn[DT_RELASZ]/3 + dyn[DT_PLTRELSZ]/2 + 1;
2085 if (NEED_MIPS_GOT_RELOCS) {
2086 size_t j=0; search_vec(p->dynv, &j, DT_MIPS_GOTSYM);
2087 size_t i=0; search_vec(p->dynv, &i, DT_MIPS_SYMTABNO);
2090 p->lazy = calloc(n, 3*sizeof(size_t));
2092 error("Error preparing lazy relocation for %s: %m", p->name);
2093 longjmp(*rtld_fail, 1);
2095 p->lazy_next = lazy_head;
2099 void *dlopen(const char *file, int mode)
2101 struct dso *volatile p, *orig_tail, *orig_syms_tail, *orig_lazy_head, *next;
2102 struct tls_module *orig_tls_tail;
2103 size_t orig_tls_cnt, orig_tls_offset, orig_tls_align;
2107 struct dso **volatile ctor_queue = 0;
2109 if (!file) return head;
2111 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
2112 pthread_rwlock_wrlock(&lock);
2115 debug.state = RT_ADD;
2119 if (shutting_down) {
2120 error("Cannot dlopen while program is exiting.");
2123 orig_tls_tail = tls_tail;
2124 orig_tls_cnt = tls_cnt;
2125 orig_tls_offset = tls_offset;
2126 orig_tls_align = tls_align;
2127 orig_lazy_head = lazy_head;
2128 orig_syms_tail = syms_tail;
2130 noload = mode & RTLD_NOLOAD;
2133 if (setjmp(*rtld_fail)) {
2134 /* Clean up anything new that was (partially) loaded */
2135 revert_syms(orig_syms_tail);
2136 for (p=orig_tail->next; p; p=next) {
2138 while (p->td_index) {
2139 void *tmp = p->td_index->next;
2144 if (p->rpath != p->rpath_orig)
2152 if (!orig_tls_tail) libc.tls_head = 0;
2153 tls_tail = orig_tls_tail;
2154 if (tls_tail) tls_tail->next = 0;
2155 tls_cnt = orig_tls_cnt;
2156 tls_offset = orig_tls_offset;
2157 tls_align = orig_tls_align;
2158 lazy_head = orig_lazy_head;
2163 } else p = load_library(file, head);
2167 "Library %s is not already loaded" :
2168 "Error loading shared library %s: %m",
2173 /* First load handling */
2176 pthread_mutex_lock(&init_fini_lock);
2177 int constructed = p->constructed;
2178 pthread_mutex_unlock(&init_fini_lock);
2179 if (!constructed) ctor_queue = queue_ctors(p);
2180 if (!p->relocated && (mode & RTLD_LAZY)) {
2182 for (i=0; p->deps[i]; i++)
2183 if (!p->deps[i]->relocated)
2184 prepare_lazy(p->deps[i]);
2186 if (!p->relocated || (mode & RTLD_GLOBAL)) {
2187 /* Make new symbols global, at least temporarily, so we can do
2188 * relocations. If not RTLD_GLOBAL, this is reverted below. */
2190 for (i=0; p->deps[i]; i++)
2191 add_syms(p->deps[i]);
2193 if (!p->relocated) {
2197 /* If RTLD_GLOBAL was not specified, undo any new additions
2198 * to the global symbol table. This is a nop if the library was
2199 * previously loaded and already global. */
2200 if (!(mode & RTLD_GLOBAL))
2201 revert_syms(orig_syms_tail);
2203 /* Processing of deferred lazy relocations must not happen until
2204 * the new libraries are committed; otherwise we could end up with
2205 * relocations resolved to symbol definitions that get removed. */
2209 if (tls_cnt != orig_tls_cnt)
2213 debug.state = RT_CONSISTENT;
2217 pthread_rwlock_unlock(&lock);
2219 do_init_fini(ctor_queue);
2222 pthread_setcancelstate(cs, 0);
2226 hidden int __dl_invalid_handle(void *h)
2229 for (p=head; p; p=p->next) if (h==p) return 0;
2230 error("Invalid library handle %p", (void *)h);
2234 static void *addr2dso(size_t a)
2238 if (DL_FDPIC) for (p=head; p; p=p->next) {
2240 if (a-(size_t)p->funcdescs < i*sizeof(*p->funcdescs))
2243 for (p=head; p; p=p->next) {
2244 if (DL_FDPIC && p->loadmap) {
2245 for (i=0; i<p->loadmap->nsegs; i++) {
2246 if (a-p->loadmap->segs[i].p_vaddr
2247 < p->loadmap->segs[i].p_memsz)
2252 size_t phcnt = p->phnum;
2253 size_t entsz = p->phentsize;
2254 size_t base = (size_t)p->base;
2255 for (; phcnt--; ph=(void *)((char *)ph+entsz)) {
2256 if (ph->p_type != PT_LOAD) continue;
2257 if (a-base-ph->p_vaddr < ph->p_memsz)
2260 if (a-(size_t)p->map < p->map_len)
2267 static void *do_dlsym(struct dso *p, const char *s, void *ra)
2270 if (p == head || p == RTLD_DEFAULT) {
2272 } else if (p == RTLD_NEXT) {
2273 p = addr2dso((size_t)ra);
2276 } else if (__dl_invalid_handle(p)) {
2280 struct symdef def = find_sym2(p, s, 0, use_deps);
2282 error("Symbol not found: %s", s);
2285 if ((def.sym->st_info&0xf) == STT_TLS)
2286 return __tls_get_addr((tls_mod_off_t []){def.dso->tls_id, def.sym->st_value-DTP_OFFSET});
2287 if (DL_FDPIC && (def.sym->st_info&0xf) == STT_FUNC)
2288 return def.dso->funcdescs + (def.sym - def.dso->syms);
2289 return laddr(def.dso, def.sym->st_value);
2292 int dladdr(const void *addr_arg, Dl_info *info)
2294 size_t addr = (size_t)addr_arg;
2300 size_t besterr = -1;
2302 pthread_rwlock_rdlock(&lock);
2304 pthread_rwlock_unlock(&lock);
2309 strings = p->strings;
2310 nsym = count_syms(p);
2313 size_t idx = (addr-(size_t)p->funcdescs)
2314 / sizeof(*p->funcdescs);
2315 if (idx < nsym && (sym[idx].st_info&0xf) == STT_FUNC) {
2316 best = (size_t)(p->funcdescs + idx);
2317 bestsym = sym + idx;
2322 if (!best) for (; nsym; nsym--, sym++) {
2324 && (1<<(sym->st_info&0xf) & OK_TYPES)
2325 && (1<<(sym->st_info>>4) & OK_BINDS)) {
2326 size_t symaddr = (size_t)laddr(p, sym->st_value);
2327 if (symaddr > addr || symaddr <= best)
2331 besterr = addr - symaddr;
2332 if (addr == symaddr)
2337 if (best && besterr > bestsym->st_size-1) {
2342 info->dli_fname = p->name;
2343 info->dli_fbase = p->map;
2346 info->dli_sname = 0;
2347 info->dli_saddr = 0;
2351 if (DL_FDPIC && (bestsym->st_info&0xf) == STT_FUNC)
2352 best = (size_t)(p->funcdescs + (bestsym - p->syms));
2353 info->dli_sname = strings + bestsym->st_name;
2354 info->dli_saddr = (void *)best;
2359 hidden void *__dlsym(void *restrict p, const char *restrict s, void *restrict ra)
2362 pthread_rwlock_rdlock(&lock);
2363 res = do_dlsym(p, s, ra);
2364 pthread_rwlock_unlock(&lock);
2368 hidden void *__dlsym_redir_time64(void *restrict p, const char *restrict s, void *restrict ra)
2371 const char *suffix, *suffix2 = "";
2374 /* Map the symbol name to a time64 version of itself according to the
2375 * pattern used for naming the redirected time64 symbols. */
2376 size_t l = strnlen(s, sizeof redir);
2377 if (l<4 || l==sizeof redir) goto no_redir;
2378 if (s[l-2]=='_' && s[l-1]=='r') {
2382 if (l<4) goto no_redir;
2383 if (!strcmp(s+l-4, "time")) suffix = "64";
2384 else suffix = "_time64";
2386 /* Use the presence of the remapped symbol name in libc to determine
2387 * whether it's one that requires time64 redirection; replace if so. */
2388 snprintf(redir, sizeof redir, "__%.*s%s%s", (int)l, s, suffix, suffix2);
2389 if (find_sym(&ldso, redir, 1).sym) s = redir;
2392 return __dlsym(p, s, ra);
2395 int dl_iterate_phdr(int(*callback)(struct dl_phdr_info *info, size_t size, void *data), void *data)
2397 struct dso *current;
2398 struct dl_phdr_info info;
2400 for(current = head; current;) {
2401 info.dlpi_addr = (uintptr_t)current->base;
2402 info.dlpi_name = current->name;
2403 info.dlpi_phdr = current->phdr;
2404 info.dlpi_phnum = current->phnum;
2405 info.dlpi_adds = gencnt;
2407 info.dlpi_tls_modid = current->tls_id;
2408 info.dlpi_tls_data = !current->tls_id ? 0 :
2409 __tls_get_addr((tls_mod_off_t[]){current->tls_id,0});
2411 ret = (callback)(&info, sizeof (info), data);
2413 if (ret != 0) break;
2415 pthread_rwlock_rdlock(&lock);
2416 current = current->next;
2417 pthread_rwlock_unlock(&lock);
2422 static void error_impl(const char *fmt, ...)
2427 vdprintf(2, fmt, ap);
2433 __dl_vseterr(fmt, ap);
2437 static void error_noop(const char *fmt, ...)