21 #include "pthread_impl.h"
25 static char errbuf[128];
29 #if ULONG_MAX == 0xffffffff
30 typedef Elf32_Ehdr Ehdr;
31 typedef Elf32_Phdr Phdr;
32 typedef Elf32_Sym Sym;
33 #define R_TYPE(x) ((x)&255)
34 #define R_SYM(x) ((x)>>8)
36 typedef Elf64_Ehdr Ehdr;
37 typedef Elf64_Phdr Phdr;
38 typedef Elf64_Sym Sym;
39 #define R_TYPE(x) ((x)&0xffffffff)
40 #define R_SYM(x) ((x)>>32)
43 #define MAXP2(a,b) (-(-(a)&-(b)))
44 #define ALIGN(x,y) ((x)+(y)-1 & -(y))
58 struct dso *next, *prev;
77 size_t tls_len, tls_size, tls_align, tls_id, tls_offset;
79 unsigned char *new_tls;
80 int new_dtv_idx, new_tls_idx;
81 struct dso *fini_next;
93 void __init_ssp(size_t *);
94 void *__install_initial_tls(void *);
95 void __init_libc(char **, char *);
97 static struct dso *head, *tail, *ldso, *fini_head;
98 static char *env_path, *sys_path, *r_path;
99 static unsigned long long gencnt;
103 static int ldso_fail;
105 static jmp_buf *rtld_fail;
106 static pthread_rwlock_t lock;
107 static struct debug debug;
108 static size_t tls_cnt, tls_offset, tls_align = 4*sizeof(size_t);
109 static pthread_mutex_t init_fini_lock = { ._m_type = PTHREAD_MUTEX_RECURSIVE };
111 struct debug *_dl_debug_addr = &debug;
116 static void decode_vec(size_t *v, size_t *a, size_t cnt)
118 memset(a, 0, cnt*sizeof(size_t));
119 for (; v[0]; v+=2) if (v[0]<cnt) {
125 static int search_vec(size_t *v, size_t *r, size_t key)
127 for (; v[0]!=key; v+=2)
133 static uint32_t sysv_hash(const char *s0)
135 const unsigned char *s = (void *)s0;
141 return h & 0xfffffff;
144 static uint32_t gnu_hash(const char *s0)
146 const unsigned char *s = (void *)s0;
147 uint_fast32_t h = 5381;
153 static Sym *sysv_lookup(const char *s, uint32_t h, struct dso *dso)
156 Sym *syms = dso->syms;
157 uint32_t *hashtab = dso->hashtab;
158 char *strings = dso->strings;
159 for (i=hashtab[2+h%hashtab[0]]; i; i=hashtab[2+hashtab[0]+i]) {
160 if ((!dso->versym || dso->versym[i] >= 0)
161 && (!strcmp(s, strings+syms[i].st_name)))
167 static Sym *gnu_lookup(const char *s, uint32_t h1, struct dso *dso)
169 Sym *syms = dso->syms;
170 char *strings = dso->strings;
171 uint32_t *hashtab = dso->ghashtab;
172 uint32_t nbuckets = hashtab[0];
173 uint32_t *buckets = hashtab + 4 + hashtab[2]*(sizeof(size_t)/4);
176 uint32_t i = buckets[h1 % nbuckets];
180 hashval = buckets + nbuckets + (i - hashtab[1]);
182 for (h1 |= 1; ; i++) {
184 if ((!dso->versym || dso->versym[i] >= 0)
185 && (h1 == (h2|1)) && !strcmp(s, strings + syms[i].st_name))
193 #define OK_TYPES (1<<STT_NOTYPE | 1<<STT_OBJECT | 1<<STT_FUNC | 1<<STT_COMMON | 1<<STT_TLS)
194 #define OK_BINDS (1<<STB_GLOBAL | 1<<STB_WEAK | 1<<STB_GNU_UNIQUE)
196 static struct symdef find_sym(struct dso *dso, const char *s, int need_def)
198 uint32_t h = 0, gh = 0;
199 struct symdef def = {0};
202 if (gh == 0x1f4039c9 && !strcmp(s, "__stack_chk_fail")) ssp_used = 1;
205 if (h == 0x595a4cc && !strcmp(s, "__stack_chk_fail")) ssp_used = 1;
207 for (; dso; dso=dso->next) {
209 if (!dso->global) continue;
211 if (!gh) gh = gnu_hash(s);
212 sym = gnu_lookup(s, gh, dso);
214 if (!h) h = sysv_hash(s);
215 sym = sysv_lookup(s, h, dso);
219 if (need_def || (sym->st_info&0xf) == STT_TLS)
222 if ((sym->st_info&0xf) != STT_TLS)
224 if (!(1<<(sym->st_info&0xf) & OK_TYPES)) continue;
225 if (!(1<<(sym->st_info>>4) & OK_BINDS)) continue;
227 if (def.sym && sym->st_info>>4 == STB_WEAK) continue;
230 if (sym->st_info>>4 == STB_GLOBAL) break;
235 static void do_relocs(struct dso *dso, size_t *rel, size_t rel_size, size_t stride)
237 unsigned char *base = dso->base;
238 Sym *syms = dso->syms;
239 char *strings = dso->strings;
247 for (; rel_size; rel+=stride, rel_size-=stride*sizeof(size_t)) {
248 type = R_TYPE(rel[1]);
249 sym_index = R_SYM(rel[1]);
251 sym = syms + sym_index;
252 name = strings + sym->st_name;
253 ctx = IS_COPY(type) ? head->next : head;
254 def = find_sym(ctx, name, IS_PLT(type));
255 if (!def.sym && sym->st_info>>4 != STB_WEAK) {
256 snprintf(errbuf, sizeof errbuf,
257 "Error relocating %s: %s: symbol not found",
259 if (runtime) longjmp(*rtld_fail, 1);
260 dprintf(2, "%s\n", errbuf);
269 do_single_reloc(dso, base, (void *)(base + rel[0]), type,
270 stride>2 ? rel[2] : 0, sym, sym?sym->st_size:0, def,
271 def.sym?(size_t)(def.dso->base+def.sym->st_value):0);
275 /* A huge hack: to make up for the wastefulness of shared libraries
276 * needing at least a page of dirty memory even if they have no global
277 * data, we reclaim the gaps at the beginning and end of writable maps
278 * and "donate" them to the heap by setting up minimal malloc
279 * structures and then freeing them. */
281 static void reclaim(unsigned char *base, size_t start, size_t end)
284 start = start + 6*sizeof(size_t)-1 & -4*sizeof(size_t);
285 end = (end & -4*sizeof(size_t)) - 2*sizeof(size_t);
286 if (start>end || end-start < 4*sizeof(size_t)) return;
287 a = (size_t *)(base + start);
288 z = (size_t *)(base + end);
290 a[-1] = z[0] = end-start + 2*sizeof(size_t) | 1;
295 static void reclaim_gaps(unsigned char *base, Phdr *ph, size_t phent, size_t phcnt)
297 for (; phcnt--; ph=(void *)((char *)ph+phent)) {
298 if (ph->p_type!=PT_LOAD) continue;
299 if ((ph->p_flags&(PF_R|PF_W))!=(PF_R|PF_W)) continue;
300 reclaim(base, ph->p_vaddr & -PAGE_SIZE, ph->p_vaddr);
301 reclaim(base, ph->p_vaddr+ph->p_memsz,
302 ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE);
306 static void *map_library(int fd, struct dso *dso)
308 Ehdr buf[(896+sizeof(Ehdr))/sizeof(Ehdr)];
309 void *allocated_buf=0;
311 size_t addr_min=SIZE_MAX, addr_max=0, map_len;
312 size_t this_min, this_max;
317 unsigned char *map=MAP_FAILED, *base;
322 ssize_t l = read(fd, buf, sizeof buf);
325 if (l<sizeof *eh || (eh->e_type != ET_DYN && eh->e_type != ET_EXEC))
327 phsize = eh->e_phentsize * eh->e_phnum;
328 if (phsize > sizeof buf - sizeof *eh) {
329 allocated_buf = malloc(phsize);
330 if (!allocated_buf) return 0;
331 l = pread(fd, allocated_buf, phsize, eh->e_phoff);
332 if (l < 0) goto error;
333 if (l != phsize) goto noexec;
334 ph = ph0 = allocated_buf;
335 } else if (eh->e_phoff + phsize > l) {
336 l = pread(fd, buf+1, phsize, eh->e_phoff);
337 if (l < 0) goto error;
338 if (l != phsize) goto noexec;
339 ph = ph0 = (void *)(buf + 1);
341 ph = ph0 = (void *)((char *)buf + eh->e_phoff);
343 for (i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
344 if (ph->p_type == PT_DYNAMIC)
346 if (ph->p_type == PT_TLS) {
347 tls_image = ph->p_vaddr;
348 dso->tls_align = ph->p_align;
349 dso->tls_len = ph->p_filesz;
350 dso->tls_size = ph->p_memsz;
352 if (ph->p_type != PT_LOAD) continue;
353 if (ph->p_vaddr < addr_min) {
354 addr_min = ph->p_vaddr;
355 off_start = ph->p_offset;
356 prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
357 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
358 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
360 if (ph->p_vaddr+ph->p_memsz > addr_max) {
361 addr_max = ph->p_vaddr+ph->p_memsz;
364 if (!dyn) goto noexec;
365 addr_max += PAGE_SIZE-1;
366 addr_max &= -PAGE_SIZE;
367 addr_min &= -PAGE_SIZE;
368 off_start &= -PAGE_SIZE;
369 map_len = addr_max - addr_min + off_start;
370 /* The first time, we map too much, possibly even more than
371 * the length of the file. This is okay because we will not
372 * use the invalid part; we just need to reserve the right
373 * amount of virtual address space to map over later. */
374 map = mmap((void *)addr_min, map_len, prot, MAP_PRIVATE, fd, off_start);
375 if (map==MAP_FAILED) goto error;
376 /* If the loaded file is not relocatable and the requested address is
377 * not available, then the load operation must fail. */
378 if (eh->e_type != ET_DYN && addr_min && map!=(void *)addr_min) {
382 base = map - addr_min;
385 for (ph=ph0, i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
386 if (ph->p_type != PT_LOAD) continue;
387 /* Check if the programs headers are in this load segment, and
388 * if so, record the address for use by dl_iterate_phdr. */
389 if (!dso->phdr && eh->e_phoff >= ph->p_offset
390 && eh->e_phoff+phsize <= ph->p_offset+ph->p_filesz) {
391 dso->phdr = (void *)(base + ph->p_vaddr
392 + (eh->e_phoff-ph->p_offset));
393 dso->phnum = eh->e_phnum;
395 /* Reuse the existing mapping for the lowest-address LOAD */
396 if ((ph->p_vaddr & -PAGE_SIZE) == addr_min) continue;
397 this_min = ph->p_vaddr & -PAGE_SIZE;
398 this_max = ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE;
399 off_start = ph->p_offset & -PAGE_SIZE;
400 prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
401 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
402 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
403 if (mmap(base+this_min, this_max-this_min, prot, MAP_PRIVATE|MAP_FIXED, fd, off_start) == MAP_FAILED)
405 if (ph->p_memsz > ph->p_filesz) {
406 size_t brk = (size_t)base+ph->p_vaddr+ph->p_filesz;
407 size_t pgbrk = brk+PAGE_SIZE-1 & -PAGE_SIZE;
408 memset((void *)brk, 0, pgbrk-brk & PAGE_SIZE-1);
409 if (pgbrk-(size_t)base < this_max && mmap((void *)pgbrk, (size_t)base+this_max-pgbrk, prot, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) == MAP_FAILED)
413 for (i=0; ((size_t *)(base+dyn))[i]; i+=2)
414 if (((size_t *)(base+dyn))[i]==DT_TEXTREL) {
415 if (mprotect(map, map_len, PROT_READ|PROT_WRITE|PROT_EXEC) < 0)
419 if (!runtime) reclaim_gaps(base, ph0, eh->e_phentsize, eh->e_phnum);
421 dso->map_len = map_len;
423 dso->dynv = (void *)(base+dyn);
424 if (dso->tls_size) dso->tls_image = (void *)(base+tls_image);
430 if (map!=MAP_FAILED) munmap(map, map_len);
435 static int path_open(const char *name, const char *s, char *buf, size_t buf_size)
440 s += strspn(s, ":\n");
441 l = strcspn(s, ":\n");
442 if (l-1 >= INT_MAX) return -1;
443 if (snprintf(buf, buf_size, "%.*s/%s", (int)l, s, name) >= buf_size)
445 if ((fd = open(buf, O_RDONLY|O_CLOEXEC))>=0) return fd;
450 static void decode_dyn(struct dso *p)
452 size_t dyn[DYN_CNT] = {0};
453 decode_vec(p->dynv, dyn, DYN_CNT);
454 p->syms = (void *)(p->base + dyn[DT_SYMTAB]);
455 p->strings = (void *)(p->base + dyn[DT_STRTAB]);
456 if (dyn[0]&(1<<DT_HASH))
457 p->hashtab = (void *)(p->base + dyn[DT_HASH]);
458 if (search_vec(p->dynv, dyn, DT_GNU_HASH))
459 p->ghashtab = (void *)(p->base + *dyn);
460 if (search_vec(p->dynv, dyn, DT_VERSYM))
461 p->versym = (void *)(p->base + *dyn);
464 static struct dso *load_library(const char *name)
466 char buf[2*NAME_MAX+2];
467 const char *pathname;
469 struct dso *p, temp_dso = {0};
476 /* Catch and block attempts to reload the implementation itself */
477 if (name[0]=='l' && name[1]=='i' && name[2]=='b') {
478 static const char *rp, reserved[] =
479 "c\0pthread\0rt\0m\0dl\0util\0xnet\0";
480 char *z = strchr(name, '.');
483 for (rp=reserved; *rp && strncmp(name+3, rp, l-3); rp+=strlen(rp)+1);
486 /* Track which names have been resolved
487 * and only report each one once. */
488 static unsigned reported;
489 unsigned mask = 1U<<(rp-reserved);
490 if (!(reported & mask)) {
492 dprintf(1, "\t%s => %s (%p)\n",
501 if (!strcmp(name, ldso->name)) is_self = 1;
506 tail = ldso->next ? ldso->next : ldso;
510 if (strchr(name, '/')) {
512 fd = open(name, O_RDONLY|O_CLOEXEC);
514 /* Search for the name to see if it's already loaded */
515 for (p=head->next; p; p=p->next) {
516 if (p->shortname && !strcmp(p->shortname, name)) {
521 if (strlen(name) > NAME_MAX) return 0;
523 if (env_path) fd = path_open(name, env_path, buf, sizeof buf);
524 if (fd < 0 && r_path) fd = path_open(name, r_path, buf, sizeof buf);
529 if (ldso->name[0]=='/') {
531 for (s=t=z=ldso->name; *s; s++)
532 if (*s=='/') z=t, t=s;
533 prefix_len = z-ldso->name;
534 if (prefix_len < PATH_MAX)
541 char etc_ldso_path[prefix_len + 1
542 + sizeof "/etc/ld-musl-" LDSO_ARCH ".path"];
543 snprintf(etc_ldso_path, sizeof etc_ldso_path,
544 "%.*s/etc/ld-musl-" LDSO_ARCH ".path",
545 (int)prefix_len, prefix);
546 FILE *f = fopen(etc_ldso_path, "rbe");
548 if (getdelim(&sys_path, (size_t[1]){0}, 0, f) <= 0) {
555 if (!sys_path) sys_path = "/lib:/usr/local/lib:/usr/lib";
556 fd = path_open(name, sys_path, buf, sizeof buf);
560 if (fd < 0) return 0;
561 if (fstat(fd, &st) < 0) {
565 for (p=head->next; p; p=p->next) {
566 if (p->dev == st.st_dev && p->ino == st.st_ino) {
567 /* If this library was previously loaded with a
568 * pathname but a search found the same inode,
569 * setup its shortname so it can be found by name. */
570 if (!p->shortname && pathname != name)
571 p->shortname = strrchr(p->name, '/')+1;
577 map = noload ? 0 : map_library(fd, &temp_dso);
581 /* Allocate storage for the new DSO. When there is TLS, this
582 * storage must include a reservation for all pre-existing
583 * threads to obtain copies of both the new TLS, and an
584 * extended DTV capable of storing an additional slot for
585 * the newly-loaded DSO. */
586 alloc_size = sizeof *p + strlen(pathname) + 1;
587 if (runtime && temp_dso.tls_image) {
588 size_t per_th = temp_dso.tls_size + temp_dso.tls_align
589 + sizeof(void *) * (tls_cnt+3);
590 n_th = libc.threads_minus_1 + 1;
591 if (n_th > SSIZE_MAX / per_th) alloc_size = SIZE_MAX;
592 else alloc_size += n_th * per_th;
594 p = calloc(1, alloc_size);
596 munmap(map, temp_dso.map_len);
599 memcpy(p, &temp_dso, sizeof temp_dso);
605 strcpy(p->name, pathname);
606 /* Add a shortname only if name arg was not an explicit pathname. */
607 if (pathname != name) p->shortname = strrchr(p->name, '/')+1;
609 if (runtime && !__pthread_self_init()) {
610 munmap(map, p->map_len);
614 p->tls_id = ++tls_cnt;
615 tls_align = MAXP2(tls_align, p->tls_align);
617 p->tls_offset = tls_offset + ( (tls_align-1) &
618 -(tls_offset + (uintptr_t)p->tls_image) );
619 tls_offset += p->tls_size;
621 tls_offset += p->tls_size + p->tls_align - 1;
622 tls_offset -= (tls_offset + (uintptr_t)p->tls_image)
624 p->tls_offset = tls_offset;
626 p->new_dtv = (void *)(-sizeof(size_t) &
627 (uintptr_t)(p->name+strlen(p->name)+sizeof(size_t)));
628 p->new_tls = (void *)(p->new_dtv + n_th*(tls_cnt+1));
635 if (ldd_mode) dprintf(1, "\t%s => %s (%p)\n", name, pathname, p->base);
640 static void load_deps(struct dso *p)
643 struct dso ***deps = &p->deps, **tmp, *dep;
644 for (; p; p=p->next) {
645 for (i=0; p->dynv[i]; i+=2) {
646 if (p->dynv[i] != DT_RPATH) continue;
647 r_path = (void *)(p->strings + p->dynv[i+1]);
649 for (i=0; p->dynv[i]; i+=2) {
650 if (p->dynv[i] != DT_NEEDED) continue;
651 dep = load_library(p->strings + p->dynv[i+1]);
653 snprintf(errbuf, sizeof errbuf,
654 "Error loading shared library %s: %m (needed by %s)",
655 p->strings + p->dynv[i+1], p->name);
656 if (runtime) longjmp(*rtld_fail, 1);
657 dprintf(2, "%s\n", errbuf);
662 tmp = realloc(*deps, sizeof(*tmp)*(ndeps+2));
663 if (!tmp) longjmp(*rtld_fail, 1);
673 static void load_preload(char *s)
678 for ( ; *s && isspace(*s); s++);
679 for (z=s; *z && !isspace(*z); z++);
687 static void make_global(struct dso *p)
689 for (; p; p=p->next) p->global = 1;
692 static void reloc_all(struct dso *p)
694 size_t dyn[DYN_CNT] = {0};
695 for (; p; p=p->next) {
696 if (p->relocated) continue;
697 decode_vec(p->dynv, dyn, DYN_CNT);
698 #ifdef NEED_ARCH_RELOCS
699 do_arch_relocs(p, head);
701 do_relocs(p, (void *)(p->base+dyn[DT_JMPREL]), dyn[DT_PLTRELSZ],
702 2+(dyn[DT_PLTREL]==DT_RELA));
703 do_relocs(p, (void *)(p->base+dyn[DT_REL]), dyn[DT_RELSZ], 2);
704 do_relocs(p, (void *)(p->base+dyn[DT_RELA]), dyn[DT_RELASZ], 3);
709 static size_t find_dyn(Phdr *ph, size_t cnt, size_t stride)
711 for (; cnt--; ph = (void *)((char *)ph + stride))
712 if (ph->p_type == PT_DYNAMIC)
717 static void find_map_range(Phdr *ph, size_t cnt, size_t stride, struct dso *p)
719 size_t min_addr = -1, max_addr = 0;
720 for (; cnt--; ph = (void *)((char *)ph + stride)) {
721 if (ph->p_type != PT_LOAD) continue;
722 if (ph->p_vaddr < min_addr)
723 min_addr = ph->p_vaddr;
724 if (ph->p_vaddr+ph->p_memsz > max_addr)
725 max_addr = ph->p_vaddr+ph->p_memsz;
727 min_addr &= -PAGE_SIZE;
728 max_addr = (max_addr + PAGE_SIZE-1) & -PAGE_SIZE;
729 p->map = p->base + min_addr;
730 p->map_len = max_addr - min_addr;
733 static void do_fini()
736 size_t dyn[DYN_CNT] = {0};
737 for (p=fini_head; p; p=p->fini_next) {
738 if (!p->constructed) continue;
739 decode_vec(p->dynv, dyn, DYN_CNT);
740 if (dyn[0] & (1<<DT_FINI_ARRAY)) {
741 size_t n = dyn[DT_FINI_ARRAYSZ]/sizeof(size_t);
742 size_t *fn = (size_t *)(p->base + dyn[DT_FINI_ARRAY])+n;
743 while (n--) ((void (*)(void))*--fn)();
745 #ifndef NO_LEGACY_INITFINI
746 if ((dyn[0] & (1<<DT_FINI)) && dyn[DT_FINI])
747 ((void (*)(void))(p->base + dyn[DT_FINI]))();
752 static void do_init_fini(struct dso *p)
754 size_t dyn[DYN_CNT] = {0};
755 int need_locking = libc.threads_minus_1;
756 /* Allow recursive calls that arise when a library calls
757 * dlopen from one of its constructors, but block any
758 * other threads until all ctors have finished. */
759 if (need_locking) pthread_mutex_lock(&init_fini_lock);
760 for (; p; p=p->prev) {
761 if (p->constructed) continue;
763 decode_vec(p->dynv, dyn, DYN_CNT);
764 if (dyn[0] & ((1<<DT_FINI) | (1<<DT_FINI_ARRAY))) {
765 p->fini_next = fini_head;
768 #ifndef NO_LEGACY_INITFINI
769 if ((dyn[0] & (1<<DT_INIT)) && dyn[DT_INIT])
770 ((void (*)(void))(p->base + dyn[DT_INIT]))();
772 if (dyn[0] & (1<<DT_INIT_ARRAY)) {
773 size_t n = dyn[DT_INIT_ARRAYSZ]/sizeof(size_t);
774 size_t *fn = (void *)(p->base + dyn[DT_INIT_ARRAY]);
775 while (n--) ((void (*)(void))*fn++)();
777 if (!need_locking && libc.threads_minus_1) {
779 pthread_mutex_lock(&init_fini_lock);
782 if (need_locking) pthread_mutex_unlock(&init_fini_lock);
785 void _dl_debug_state(void)
791 pthread_t self = __pthread_self();
793 for (p=head; p; p=p->next) {
794 if (!p->tls_id || !self->dtv[p->tls_id]) continue;
795 memcpy(self->dtv[p->tls_id], p->tls_image, p->tls_len);
796 memset((char *)self->dtv[p->tls_id]+p->tls_len, 0,
797 p->tls_size - p->tls_len);
798 if (p->tls_id == (size_t)self->dtv[0]) break;
802 void *__copy_tls(unsigned char *mem)
807 if (!tls_cnt) return mem;
809 void **dtv = (void *)mem;
810 dtv[0] = (void *)tls_cnt;
813 mem += sizeof(void *) * (tls_cnt+1);
814 mem += -((uintptr_t)mem + sizeof(struct pthread)) & (tls_align-1);
816 mem += sizeof(struct pthread);
818 for (p=head; p; p=p->next) {
819 if (!p->tls_id) continue;
820 dtv[p->tls_id] = mem + p->tls_offset;
821 memcpy(dtv[p->tls_id], p->tls_image, p->tls_len);
824 mem += libc.tls_size - sizeof(struct pthread);
825 mem -= (uintptr_t)mem & (tls_align-1);
828 for (p=head; p; p=p->next) {
829 if (!p->tls_id) continue;
830 dtv[p->tls_id] = mem - p->tls_offset;
831 memcpy(dtv[p->tls_id], p->tls_image, p->tls_len);
838 void *__tls_get_addr(size_t *v)
840 pthread_t self = __pthread_self();
841 if (v[0]<=(size_t)self->dtv[0] && self->dtv[v[0]])
842 return (char *)self->dtv[v[0]]+v[1];
844 /* Block signals to make accessing new TLS async-signal-safe */
846 pthread_sigmask(SIG_BLOCK, SIGALL_SET, &set);
847 if (v[0]<=(size_t)self->dtv[0] && self->dtv[v[0]]) {
848 pthread_sigmask(SIG_SETMASK, &set, 0);
849 return (char *)self->dtv[v[0]]+v[1];
852 /* This is safe without any locks held because, if the caller
853 * is able to request the Nth entry of the DTV, the DSO list
854 * must be valid at least that far out and it was synchronized
855 * at program startup or by an already-completed call to dlopen. */
857 for (p=head; p->tls_id != v[0]; p=p->next);
859 /* Get new DTV space from new DSO if needed */
860 if (v[0] > (size_t)self->dtv[0]) {
861 void **newdtv = p->new_dtv +
862 (v[0]+1)*sizeof(void *)*a_fetch_add(&p->new_dtv_idx,1);
863 memcpy(newdtv, self->dtv,
864 ((size_t)self->dtv[0]+1) * sizeof(void *));
865 newdtv[0] = (void *)v[0];
869 /* Get new TLS memory from new DSO */
870 unsigned char *mem = p->new_tls +
871 (p->tls_size + p->tls_align) * a_fetch_add(&p->new_tls_idx,1);
872 mem += ((uintptr_t)p->tls_image - (uintptr_t)mem) & (p->tls_align-1);
873 self->dtv[v[0]] = mem;
874 memcpy(mem, p->tls_image, p->tls_len);
875 pthread_sigmask(SIG_SETMASK, &set, 0);
879 static void update_tls_size()
881 libc.tls_size = ALIGN(
882 (1+tls_cnt) * sizeof(void *) +
884 sizeof(struct pthread) +
889 void *__dynlink(int argc, char **argv)
891 size_t aux[AUX_CNT] = {0};
895 static struct dso builtin_dsos[3];
896 struct dso *const app = builtin_dsos+0;
897 struct dso *const lib = builtin_dsos+1;
898 struct dso *const vdso = builtin_dsos+2;
902 char **envp = argv+argc+1;
904 /* Find aux vector just past environ[] */
905 for (i=argc+1; argv[i]; i++)
906 if (!memcmp(argv[i], "LD_LIBRARY_PATH=", 16))
907 env_path = argv[i]+16;
908 else if (!memcmp(argv[i], "LD_PRELOAD=", 11))
909 env_preload = argv[i]+11;
910 auxv = (void *)(argv+i+1);
912 decode_vec(auxv, aux, AUX_CNT);
914 /* Only trust user/env if kernel says we're not suid/sgid */
915 if ((aux[0]&0x7800)!=0x7800 || aux[AT_UID]!=aux[AT_EUID]
916 || aux[AT_GID]!=aux[AT_EGID] || aux[AT_SECURE]) {
921 /* If the dynamic linker was invoked as a program itself, AT_BASE
922 * will not be set. In that case, we assume the base address is
923 * the start of the page containing the PHDRs; I don't know any
924 * better approach... */
926 aux[AT_BASE] = aux[AT_PHDR] & -PAGE_SIZE;
927 aux[AT_PHDR] = aux[AT_PHENT] = aux[AT_PHNUM] = 0;
930 /* The dynamic linker load address is passed by the kernel
931 * in the AUX vector, so this is easy. */
932 lib->base = (void *)aux[AT_BASE];
933 lib->name = lib->shortname = "libc.so";
935 ehdr = (void *)lib->base;
936 lib->phnum = ehdr->e_phnum;
937 lib->phdr = (void *)(aux[AT_BASE]+ehdr->e_phoff);
938 find_map_range(lib->phdr, ehdr->e_phnum, ehdr->e_phentsize, lib);
939 lib->dynv = (void *)(lib->base + find_dyn(lib->phdr,
940 ehdr->e_phnum, ehdr->e_phentsize));
944 size_t interp_off = 0;
945 size_t tls_image = 0;
946 /* Find load address of the main program, via AT_PHDR vs PT_PHDR. */
947 app->phdr = phdr = (void *)aux[AT_PHDR];
948 app->phnum = aux[AT_PHNUM];
949 for (i=aux[AT_PHNUM]; i; i--, phdr=(void *)((char *)phdr + aux[AT_PHENT])) {
950 if (phdr->p_type == PT_PHDR)
951 app->base = (void *)(aux[AT_PHDR] - phdr->p_vaddr);
952 else if (phdr->p_type == PT_INTERP)
953 interp_off = (size_t)phdr->p_vaddr;
954 else if (phdr->p_type == PT_TLS) {
955 tls_image = phdr->p_vaddr;
956 app->tls_len = phdr->p_filesz;
957 app->tls_size = phdr->p_memsz;
958 app->tls_align = phdr->p_align;
961 if (app->tls_size) app->tls_image = (char *)app->base + tls_image;
962 if (interp_off) lib->name = (char *)app->base + interp_off;
964 app->dynv = (void *)(app->base + find_dyn(
965 (void *)aux[AT_PHDR], aux[AT_PHNUM], aux[AT_PHENT]));
966 find_map_range((void *)aux[AT_PHDR],
967 aux[AT_PHNUM], aux[AT_PHENT], app);
970 char *ldname = argv[0];
971 size_t l = strlen(ldname);
972 if (l >= 3 && !strcmp(ldname+l-3, "ldd")) ldd_mode = 1;
973 *argv++ = (void *)-1;
974 if (argv[0] && !strcmp(argv[0], "--")) *argv++ = (void *)-1;
976 dprintf(2, "musl libc/dynamic program loader\n");
977 dprintf(2, "usage: %s pathname%s\n", ldname,
978 ldd_mode ? "" : " [args]");
981 fd = open(argv[0], O_RDONLY);
983 dprintf(2, "%s: cannot load %s: %s\n", ldname, argv[0], strerror(errno));
987 ehdr = (void *)map_library(fd, app);
989 dprintf(2, "%s: %s: Not a valid dynamic program\n", ldname, argv[0]);
996 aux[AT_ENTRY] = (size_t)app->base + ehdr->e_entry;
997 /* Find the name that would have been used for the dynamic
998 * linker had ldd not taken its place. */
1000 for (i=0; i<app->phnum; i++) {
1001 if (app->phdr[i].p_type == PT_INTERP)
1002 lib->name = (void *)(app->base
1003 + app->phdr[i].p_vaddr);
1005 dprintf(1, "\t%s (%p)\n", lib->name, lib->base);
1008 if (app->tls_size) {
1009 app->tls_id = tls_cnt = 1;
1011 app->tls_offset = 0;
1012 tls_offset = app->tls_size
1013 + ( -((uintptr_t)app->tls_image + app->tls_size)
1014 & (app->tls_align-1) );
1016 tls_offset = app->tls_offset = app->tls_size
1017 + ( -((uintptr_t)app->tls_image + app->tls_size)
1018 & (app->tls_align-1) );
1020 tls_align = MAXP2(tls_align, app->tls_align);
1025 /* Attach to vdso, if provided by the kernel */
1026 if (search_vec(auxv, &vdso_base, AT_SYSINFO_EHDR)) {
1027 ehdr = (void *)vdso_base;
1028 vdso->phdr = phdr = (void *)(vdso_base + ehdr->e_phoff);
1029 vdso->phnum = ehdr->e_phnum;
1030 for (i=ehdr->e_phnum; i; i--, phdr=(void *)((char *)phdr + ehdr->e_phentsize)) {
1031 if (phdr->p_type == PT_DYNAMIC)
1032 vdso->dynv = (void *)(vdso_base + phdr->p_offset);
1033 if (phdr->p_type == PT_LOAD)
1034 vdso->base = (void *)(vdso_base - phdr->p_vaddr + phdr->p_offset);
1037 vdso->shortname = "linux-gate.so.1";
1044 /* Initial dso chain consists only of the app. We temporarily
1045 * append the dynamic linker/libc so we can relocate it, then
1046 * restore the initial chain in preparation for loading third
1047 * party libraries (preload/needed). */
1054 /* PAST THIS POINT, ALL LIBC INTERFACES ARE FULLY USABLE. */
1056 /* Donate unused parts of app and library mapping to malloc */
1057 reclaim_gaps(app->base, (void *)aux[AT_PHDR], aux[AT_PHENT], aux[AT_PHNUM]);
1058 ehdr = (void *)lib->base;
1059 reclaim_gaps(lib->base, (void *)(lib->base+ehdr->e_phoff),
1060 ehdr->e_phentsize, ehdr->e_phnum);
1062 /* Load preload/needed libraries, add their symbols to the global
1063 * namespace, and perform all remaining relocations. The main
1064 * program must be relocated LAST since it may contain copy
1065 * relocations which depend on libraries' relocations. */
1066 if (env_preload) load_preload(env_preload);
1070 reloc_all(app->next);
1075 void *mem = mmap(0, libc.tls_size, PROT_READ|PROT_WRITE,
1076 MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
1077 if (mem==MAP_FAILED ||
1078 !__install_initial_tls(__copy_tls(mem))) {
1079 dprintf(2, "%s: Error getting %zu bytes thread-local storage: %m\n",
1080 argv[0], libc.tls_size);
1085 if (ldso_fail) _exit(127);
1086 if (ldd_mode) _exit(0);
1088 /* Switch to runtime mode: any further failures in the dynamic
1089 * linker are a reportable failure rather than a fatal startup
1090 * error. If the dynamic loader (dlopen) will not be used, free
1091 * all memory used by the dynamic linker. */
1094 #ifndef DYNAMIC_IS_RO
1095 for (i=0; app->dynv[i]; i+=2)
1096 if (app->dynv[i]==DT_DEBUG)
1097 app->dynv[i+1] = (size_t)&debug;
1100 debug.bp = _dl_debug_state;
1102 debug.base = lib->base;
1106 if (ssp_used) __init_ssp((void *)aux[AT_RANDOM]);
1107 __init_libc(envp, argv[0]);
1112 return (void *)aux[AT_ENTRY];
1115 void *dlopen(const char *file, int mode)
1117 struct dso *volatile p, *orig_tail, *next;
1118 size_t orig_tls_cnt, orig_tls_offset, orig_tls_align;
1123 if (!file) return head;
1125 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
1126 pthread_rwlock_wrlock(&lock);
1130 orig_tls_cnt = tls_cnt;
1131 orig_tls_offset = tls_offset;
1132 orig_tls_align = tls_align;
1134 noload = mode & RTLD_NOLOAD;
1137 if (setjmp(*rtld_fail)) {
1138 /* Clean up anything new that was (partially) loaded */
1139 if (p && p->deps) for (i=0; p->deps[i]; i++)
1140 if (p->deps[i]->global < 0)
1141 p->deps[i]->global = 0;
1142 for (p=orig_tail->next; p; p=next) {
1144 munmap(p->map, p->map_len);
1148 tls_cnt = orig_tls_cnt;
1149 tls_offset = orig_tls_offset;
1150 tls_align = orig_tls_align;
1156 } else p = load_library(file);
1159 snprintf(errbuf, sizeof errbuf, noload ?
1160 "Library %s is not already loaded" :
1161 "Error loading shared library %s: %m",
1167 /* First load handling */
1170 if (p->deps) for (i=0; p->deps[i]; i++)
1171 if (!p->deps[i]->global)
1172 p->deps[i]->global = -1;
1173 if (!p->global) p->global = -1;
1175 if (p->deps) for (i=0; p->deps[i]; i++)
1176 if (p->deps[i]->global < 0)
1177 p->deps[i]->global = 0;
1178 if (p->global < 0) p->global = 0;
1181 if (mode & RTLD_GLOBAL) {
1182 if (p->deps) for (i=0; p->deps[i]; i++)
1183 p->deps[i]->global = 1;
1189 if (ssp_used) __init_ssp(libc.auxv);
1196 pthread_rwlock_unlock(&lock);
1197 if (p) do_init_fini(orig_tail);
1198 pthread_setcancelstate(cs, 0);
1202 static int invalid_dso_handle(void *h)
1205 for (p=head; p; p=p->next) if (h==p) return 0;
1206 snprintf(errbuf, sizeof errbuf, "Invalid library handle %p", (void *)h);
1211 static void *do_dlsym(struct dso *p, const char *s, void *ra)
1214 uint32_t h = 0, gh = 0;
1216 if (p == head || p == RTLD_DEFAULT || p == RTLD_NEXT) {
1217 if (p == RTLD_DEFAULT) {
1219 } else if (p == RTLD_NEXT) {
1220 for (p=head; p && (unsigned char *)ra-p->map>p->map_len; p=p->next);
1224 struct symdef def = find_sym(p, s, 0);
1225 if (!def.sym) goto failed;
1226 if ((def.sym->st_info&0xf) == STT_TLS)
1227 return __tls_get_addr((size_t []){def.dso->tls_id, def.sym->st_value});
1228 return def.dso->base + def.sym->st_value;
1230 if (p != RTLD_DEFAULT && p != RTLD_NEXT && invalid_dso_handle(p))
1234 sym = gnu_lookup(s, gh, p);
1237 sym = sysv_lookup(s, h, p);
1239 if (sym && (sym->st_info&0xf) == STT_TLS)
1240 return __tls_get_addr((size_t []){p->tls_id, sym->st_value});
1241 if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
1242 return p->base + sym->st_value;
1243 if (p->deps) for (i=0; p->deps[i]; i++) {
1244 if (p->deps[i]->ghashtab) {
1245 if (!gh) gh = gnu_hash(s);
1246 sym = gnu_lookup(s, gh, p->deps[i]);
1248 if (!h) h = sysv_hash(s);
1249 sym = sysv_lookup(s, h, p->deps[i]);
1251 if (sym && (sym->st_info&0xf) == STT_TLS)
1252 return __tls_get_addr((size_t []){p->deps[i]->tls_id, sym->st_value});
1253 if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
1254 return p->deps[i]->base + sym->st_value;
1258 snprintf(errbuf, sizeof errbuf, "Symbol not found: %s", s);
1262 int __dladdr(void *addr, Dl_info *info)
1272 pthread_rwlock_rdlock(&lock);
1273 for (p=head; p && (unsigned char *)addr-p->map>p->map_len; p=p->next);
1274 pthread_rwlock_unlock(&lock);
1279 strings = p->strings;
1281 nsym = p->hashtab[1];
1285 buckets = p->ghashtab + 4 + (p->ghashtab[2]*sizeof(size_t)/4);
1286 sym += p->ghashtab[1];
1287 for (i = 0; i < p->ghashtab[0]; i++) {
1288 if (buckets[i] > nsym)
1292 nsym -= p->ghashtab[1];
1293 hashval = buckets + p->ghashtab[0] + nsym;
1295 while (!(*hashval++ & 1));
1299 for (; nsym; nsym--, sym++) {
1301 && (1<<(sym->st_info&0xf) & OK_TYPES)
1302 && (1<<(sym->st_info>>4) & OK_BINDS)) {
1303 void *symaddr = p->base + sym->st_value;
1304 if (symaddr > addr || symaddr < best)
1307 bestname = strings + sym->st_name;
1308 if (addr == symaddr)
1313 if (!best) return 0;
1315 info->dli_fname = p->name;
1316 info->dli_fbase = p->base;
1317 info->dli_sname = bestname;
1318 info->dli_saddr = best;
1323 void *__dlsym(void *restrict p, const char *restrict s, void *restrict ra)
1326 pthread_rwlock_rdlock(&lock);
1327 res = do_dlsym(p, s, ra);
1328 pthread_rwlock_unlock(&lock);
1332 int dl_iterate_phdr(int(*callback)(struct dl_phdr_info *info, size_t size, void *data), void *data)
1334 struct dso *current;
1335 struct dl_phdr_info info;
1337 for(current = head; current;) {
1338 info.dlpi_addr = (uintptr_t)current->base;
1339 info.dlpi_name = current->name;
1340 info.dlpi_phdr = current->phdr;
1341 info.dlpi_phnum = current->phnum;
1342 info.dlpi_adds = gencnt;
1344 info.dlpi_tls_modid = current->tls_id;
1345 info.dlpi_tls_data = current->tls_image;
1347 ret = (callback)(&info, sizeof (info), data);
1349 if (ret != 0) break;
1351 pthread_rwlock_rdlock(&lock);
1352 current = current->next;
1353 pthread_rwlock_unlock(&lock);
1358 static int invalid_dso_handle(void *h)
1360 snprintf(errbuf, sizeof errbuf, "Invalid library handle %p", (void *)h);
1364 void *dlopen(const char *file, int mode)
1368 void *__dlsym(void *restrict p, const char *restrict s, void *restrict ra)
1372 int __dladdr (void *addr, Dl_info *info)
1378 int __dlinfo(void *dso, int req, void *res)
1380 if (invalid_dso_handle(dso)) return -1;
1381 if (req != RTLD_DI_LINKMAP) {
1382 snprintf(errbuf, sizeof errbuf, "Unsupported request %d", req);
1386 *(struct link_map **)res = dso;
1392 if (!errflag) return 0;
1397 int dlclose(void *p)
1399 return invalid_dso_handle(p);