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;
76 size_t tls_len, tls_size, tls_align, tls_id, tls_offset;
78 unsigned char *new_tls;
79 int new_dtv_idx, new_tls_idx;
80 struct dso *fini_next;
92 void __init_ssp(size_t *);
93 void *__install_initial_tls(void *);
95 static struct dso *head, *tail, *ldso, *fini_head;
96 static char *env_path, *sys_path, *r_path;
97 static unsigned long long gencnt;
101 static int ldso_fail;
103 static jmp_buf rtld_fail;
104 static pthread_rwlock_t lock;
105 static struct debug debug;
106 static size_t tls_cnt, tls_offset, tls_align = 4*sizeof(size_t);
107 static pthread_mutex_t init_fini_lock = { ._m_type = PTHREAD_MUTEX_RECURSIVE };
109 struct debug *_dl_debug_addr = &debug;
114 static void decode_vec(size_t *v, size_t *a, size_t cnt)
116 memset(a, 0, cnt*sizeof(size_t));
117 for (; v[0]; v+=2) if (v[0]<cnt) {
123 static int search_vec(size_t *v, size_t *r, size_t key)
125 for (; v[0]!=key; v+=2)
131 static uint32_t sysv_hash(const char *s0)
133 const unsigned char *s = (void *)s0;
139 return h & 0xfffffff;
142 static uint32_t gnu_hash(const char *s0)
144 const unsigned char *s = (void *)s0;
145 uint_fast32_t h = 5381;
151 static Sym *sysv_lookup(const char *s, uint32_t h, struct dso *dso)
154 Sym *syms = dso->syms;
155 uint32_t *hashtab = dso->hashtab;
156 char *strings = dso->strings;
157 for (i=hashtab[2+h%hashtab[0]]; i; i=hashtab[2+hashtab[0]+i]) {
158 if (!strcmp(s, strings+syms[i].st_name))
164 static Sym *gnu_lookup(const char *s, uint32_t h1, struct dso *dso)
168 uint32_t *hashtab = dso->ghashtab;
169 uint32_t nbuckets = hashtab[0];
170 uint32_t *buckets = hashtab + 4 + hashtab[2]*(sizeof(size_t)/4);
173 uint32_t n = buckets[h1 % nbuckets];
177 strings = dso->strings;
179 hashval = buckets + nbuckets + (n - hashtab[1]);
181 for (h1 |= 1; ; sym++) {
183 if ((h1 == (h2|1)) && !strcmp(s, strings + sym->st_name))
191 #define OK_TYPES (1<<STT_NOTYPE | 1<<STT_OBJECT | 1<<STT_FUNC | 1<<STT_COMMON | 1<<STT_TLS)
192 #define OK_BINDS (1<<STB_GLOBAL | 1<<STB_WEAK)
194 static struct symdef find_sym(struct dso *dso, const char *s, int need_def)
196 uint32_t h = 0, gh = 0;
197 struct symdef def = {0};
200 if (gh == 0x1f4039c9 && !strcmp(s, "__stack_chk_fail")) ssp_used = 1;
203 if (h == 0x595a4cc && !strcmp(s, "__stack_chk_fail")) ssp_used = 1;
205 for (; dso; dso=dso->next) {
207 if (!dso->global) continue;
209 if (!gh) gh = gnu_hash(s);
210 sym = gnu_lookup(s, gh, dso);
212 if (!h) h = sysv_hash(s);
213 sym = sysv_lookup(s, h, dso);
217 if (need_def || (sym->st_info&0xf) == STT_TLS)
220 if ((sym->st_info&0xf) != STT_TLS)
222 if (!(1<<(sym->st_info&0xf) & OK_TYPES)) continue;
223 if (!(1<<(sym->st_info>>4) & OK_BINDS)) continue;
225 if (def.sym && sym->st_info>>4 == STB_WEAK) continue;
228 if (sym->st_info>>4 == STB_GLOBAL) break;
233 static void do_relocs(struct dso *dso, size_t *rel, size_t rel_size, size_t stride)
235 unsigned char *base = dso->base;
236 Sym *syms = dso->syms;
237 char *strings = dso->strings;
245 for (; rel_size; rel+=stride, rel_size-=stride*sizeof(size_t)) {
246 type = R_TYPE(rel[1]);
247 sym_index = R_SYM(rel[1]);
249 sym = syms + sym_index;
250 name = strings + sym->st_name;
251 ctx = IS_COPY(type) ? head->next : head;
252 def = find_sym(ctx, name, IS_PLT(type));
253 if (!def.sym && sym->st_info>>4 != STB_WEAK) {
254 snprintf(errbuf, sizeof errbuf,
255 "Error relocating %s: %s: symbol not found",
257 if (runtime) longjmp(rtld_fail, 1);
258 dprintf(2, "%s\n", errbuf);
267 do_single_reloc(dso, base, (void *)(base + rel[0]), type,
268 stride>2 ? rel[2] : 0, sym, sym?sym->st_size:0, def,
269 def.sym?(size_t)(def.dso->base+def.sym->st_value):0);
273 /* A huge hack: to make up for the wastefulness of shared libraries
274 * needing at least a page of dirty memory even if they have no global
275 * data, we reclaim the gaps at the beginning and end of writable maps
276 * and "donate" them to the heap by setting up minimal malloc
277 * structures and then freeing them. */
279 static void reclaim(unsigned char *base, size_t start, size_t end)
282 start = start + 6*sizeof(size_t)-1 & -4*sizeof(size_t);
283 end = (end & -4*sizeof(size_t)) - 2*sizeof(size_t);
284 if (start>end || end-start < 4*sizeof(size_t)) return;
285 a = (size_t *)(base + start);
286 z = (size_t *)(base + end);
288 a[-1] = z[0] = end-start + 2*sizeof(size_t) | 1;
293 static void reclaim_gaps(unsigned char *base, Phdr *ph, size_t phent, size_t phcnt)
295 for (; phcnt--; ph=(void *)((char *)ph+phent)) {
296 if (ph->p_type!=PT_LOAD) continue;
297 if ((ph->p_flags&(PF_R|PF_W))!=(PF_R|PF_W)) continue;
298 reclaim(base, ph->p_vaddr & -PAGE_SIZE, ph->p_vaddr);
299 reclaim(base, ph->p_vaddr+ph->p_memsz,
300 ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE);
304 static void *map_library(int fd, struct dso *dso)
306 Ehdr buf[(896+sizeof(Ehdr))/sizeof(Ehdr)];
308 size_t addr_min=SIZE_MAX, addr_max=0, map_len;
309 size_t this_min, this_max;
314 unsigned char *map, *base;
319 ssize_t l = read(fd, buf, sizeof buf);
320 if (l<sizeof *eh) return 0;
322 phsize = eh->e_phentsize * eh->e_phnum;
323 if (phsize + sizeof *eh > l) return 0;
324 if (eh->e_phoff + phsize > l) {
325 l = pread(fd, buf+1, phsize, eh->e_phoff);
326 if (l != phsize) return 0;
327 ph = ph0 = (void *)(buf + 1);
329 ph = ph0 = (void *)((char *)buf + eh->e_phoff);
331 for (i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
332 if (ph->p_type == PT_DYNAMIC)
334 if (ph->p_type == PT_TLS) {
335 tls_image = ph->p_vaddr;
336 dso->tls_align = ph->p_align;
337 dso->tls_len = ph->p_filesz;
338 dso->tls_size = ph->p_memsz;
340 if (ph->p_type != PT_LOAD) continue;
341 if (ph->p_vaddr < addr_min) {
342 addr_min = ph->p_vaddr;
343 off_start = ph->p_offset;
344 prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
345 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
346 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
348 if (ph->p_vaddr+ph->p_memsz > addr_max) {
349 addr_max = ph->p_vaddr+ph->p_memsz;
353 addr_max += PAGE_SIZE-1;
354 addr_max &= -PAGE_SIZE;
355 addr_min &= -PAGE_SIZE;
356 off_start &= -PAGE_SIZE;
357 map_len = addr_max - addr_min + off_start;
358 /* The first time, we map too much, possibly even more than
359 * the length of the file. This is okay because we will not
360 * use the invalid part; we just need to reserve the right
361 * amount of virtual address space to map over later. */
362 map = mmap((void *)addr_min, map_len, prot, MAP_PRIVATE, fd, off_start);
363 if (map==MAP_FAILED) return 0;
364 base = map - addr_min;
367 for (ph=ph0, i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
368 if (ph->p_type != PT_LOAD) continue;
369 /* Check if the programs headers are in this load segment, and
370 * if so, record the address for use by dl_iterate_phdr. */
371 if (!dso->phdr && eh->e_phoff >= ph->p_offset
372 && eh->e_phoff+phsize <= ph->p_offset+ph->p_filesz) {
373 dso->phdr = (void *)(base + ph->p_vaddr
374 + (eh->e_phoff-ph->p_offset));
375 dso->phnum = eh->e_phnum;
377 /* Reuse the existing mapping for the lowest-address LOAD */
378 if ((ph->p_vaddr & -PAGE_SIZE) == addr_min) continue;
379 this_min = ph->p_vaddr & -PAGE_SIZE;
380 this_max = ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE;
381 off_start = ph->p_offset & -PAGE_SIZE;
382 prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
383 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
384 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
385 if (mmap(base+this_min, this_max-this_min, prot, MAP_PRIVATE|MAP_FIXED, fd, off_start) == MAP_FAILED)
387 if (ph->p_memsz > ph->p_filesz) {
388 size_t brk = (size_t)base+ph->p_vaddr+ph->p_filesz;
389 size_t pgbrk = brk+PAGE_SIZE-1 & -PAGE_SIZE;
390 memset((void *)brk, 0, pgbrk-brk & PAGE_SIZE-1);
391 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)
395 for (i=0; ((size_t *)(base+dyn))[i]; i+=2)
396 if (((size_t *)(base+dyn))[i]==DT_TEXTREL) {
397 if (mprotect(map, map_len, PROT_READ|PROT_WRITE|PROT_EXEC) < 0)
401 if (!runtime) reclaim_gaps(base, ph0, eh->e_phentsize, eh->e_phnum);
403 dso->map_len = map_len;
405 dso->dynv = (void *)(base+dyn);
406 if (dso->tls_size) dso->tls_image = (void *)(base+tls_image);
409 munmap(map, map_len);
413 static int path_open(const char *name, const char *s, char *buf, size_t buf_size)
418 s += strspn(s, ":\n");
419 l = strcspn(s, ":\n");
420 if (l-1 >= INT_MAX) return -1;
421 if (snprintf(buf, buf_size, "%.*s/%s", (int)l, s, name) >= buf_size)
423 if ((fd = open(buf, O_RDONLY|O_CLOEXEC))>=0) return fd;
428 static void decode_dyn(struct dso *p)
430 size_t dyn[DYN_CNT] = {0};
431 decode_vec(p->dynv, dyn, DYN_CNT);
432 p->syms = (void *)(p->base + dyn[DT_SYMTAB]);
433 p->strings = (void *)(p->base + dyn[DT_STRTAB]);
434 if (dyn[0]&(1<<DT_HASH))
435 p->hashtab = (void *)(p->base + dyn[DT_HASH]);
436 if (search_vec(p->dynv, dyn, DT_GNU_HASH))
437 p->ghashtab = (void *)(p->base + *dyn);
440 static struct dso *load_library(const char *name)
442 char buf[2*NAME_MAX+2];
443 const char *pathname;
445 struct dso *p, temp_dso = {0};
451 /* Catch and block attempts to reload the implementation itself */
452 if (name[0]=='l' && name[1]=='i' && name[2]=='b') {
453 static const char *rp, reserved[] =
454 "c\0pthread\0rt\0m\0dl\0util\0xnet\0";
455 char *z = strchr(name, '.');
458 for (rp=reserved; *rp && memcmp(name+3, rp, l-3); rp+=strlen(rp)+1);
463 tail = ldso->next ? ldso->next : ldso;
469 if (strchr(name, '/')) {
471 fd = open(name, O_RDONLY|O_CLOEXEC);
473 /* Search for the name to see if it's already loaded */
474 for (p=head->next; p; p=p->next) {
475 if (p->shortname && !strcmp(p->shortname, name)) {
480 if (strlen(name) > NAME_MAX) return 0;
482 if (r_path) fd = path_open(name, r_path, buf, sizeof buf);
483 if (fd < 0 && env_path) fd = path_open(name, env_path, buf, sizeof buf);
488 if (ldso->name[0]=='/') {
490 for (s=t=z=ldso->name; *s; s++)
491 if (*s=='/') z=t, t=s;
492 prefix_len = z-ldso->name;
493 if (prefix_len < PATH_MAX)
500 char etc_ldso_path[prefix_len + 1
501 + sizeof "/etc/ld-musl-" LDSO_ARCH ".path"];
502 snprintf(etc_ldso_path, sizeof etc_ldso_path,
503 "%.*s/etc/ld-musl-" LDSO_ARCH ".path",
504 (int)prefix_len, prefix);
505 FILE *f = fopen(etc_ldso_path, "rbe");
507 if (getdelim(&sys_path, (size_t[1]){0}, 0, f) <= 0) {
514 if (!sys_path) sys_path = "/lib:/usr/local/lib:/usr/lib";
515 fd = path_open(name, sys_path, buf, sizeof buf);
519 if (fd < 0) return 0;
520 if (fstat(fd, &st) < 0) {
524 for (p=head->next; p; p=p->next) {
525 if (p->dev == st.st_dev && p->ino == st.st_ino) {
526 /* If this library was previously loaded with a
527 * pathname but a search found the same inode,
528 * setup its shortname so it can be found by name. */
529 if (!p->shortname && pathname != name)
530 p->shortname = strrchr(p->name, '/')+1;
536 map = noload ? 0 : map_library(fd, &temp_dso);
540 /* Allocate storage for the new DSO. When there is TLS, this
541 * storage must include a reservation for all pre-existing
542 * threads to obtain copies of both the new TLS, and an
543 * extended DTV capable of storing an additional slot for
544 * the newly-loaded DSO. */
545 alloc_size = sizeof *p + strlen(pathname) + 1;
546 if (runtime && temp_dso.tls_image) {
547 size_t per_th = temp_dso.tls_size + temp_dso.tls_align
548 + sizeof(void *) * (tls_cnt+3);
549 n_th = libc.threads_minus_1 + 1;
550 if (n_th > SSIZE_MAX / per_th) alloc_size = SIZE_MAX;
551 else alloc_size += n_th * per_th;
553 p = calloc(1, alloc_size);
555 munmap(map, temp_dso.map_len);
558 memcpy(p, &temp_dso, sizeof temp_dso);
564 strcpy(p->name, pathname);
565 /* Add a shortname only if name arg was not an explicit pathname. */
566 if (pathname != name) p->shortname = strrchr(p->name, '/')+1;
568 if (runtime && !__pthread_self_init()) {
569 munmap(map, p->map_len);
573 p->tls_id = ++tls_cnt;
574 tls_align = MAXP2(tls_align, p->tls_align);
576 p->tls_offset = tls_offset + ( (tls_align-1) &
577 -(tls_offset + (uintptr_t)p->tls_image) );
578 tls_offset += p->tls_size;
580 tls_offset += p->tls_size + p->tls_align - 1;
581 tls_offset -= (tls_offset + (uintptr_t)p->tls_image)
583 p->tls_offset = tls_offset;
585 p->new_dtv = (void *)(-sizeof(size_t) &
586 (uintptr_t)(p->name+strlen(p->name)+sizeof(size_t)));
587 p->new_tls = (void *)(p->new_dtv + n_th*(tls_cnt+1));
594 if (ldd_mode) dprintf(1, "\t%s => %s (%p)\n", name, pathname, p->base);
599 static void load_deps(struct dso *p)
602 struct dso ***deps = &p->deps, **tmp, *dep;
603 for (; p; p=p->next) {
604 for (i=0; p->dynv[i]; i+=2) {
605 if (p->dynv[i] != DT_RPATH) continue;
606 r_path = (void *)(p->strings + p->dynv[i+1]);
608 for (i=0; p->dynv[i]; i+=2) {
609 if (p->dynv[i] != DT_NEEDED) continue;
610 dep = load_library(p->strings + p->dynv[i+1]);
612 snprintf(errbuf, sizeof errbuf,
613 "Error loading shared library %s: %m (needed by %s)",
614 p->strings + p->dynv[i+1], p->name);
615 if (runtime) longjmp(rtld_fail, 1);
616 dprintf(2, "%s\n", errbuf);
621 tmp = realloc(*deps, sizeof(*tmp)*(ndeps+2));
622 if (!tmp) longjmp(rtld_fail, 1);
632 static void load_preload(char *s)
637 for ( ; *s && isspace(*s); s++);
638 for (z=s; *z && !isspace(*z); z++);
646 static void make_global(struct dso *p)
648 for (; p; p=p->next) p->global = 1;
651 static void reloc_all(struct dso *p)
653 size_t dyn[DYN_CNT] = {0};
654 for (; p; p=p->next) {
655 if (p->relocated) continue;
656 decode_vec(p->dynv, dyn, DYN_CNT);
657 #ifdef NEED_ARCH_RELOCS
658 do_arch_relocs(p, head);
660 do_relocs(p, (void *)(p->base+dyn[DT_JMPREL]), dyn[DT_PLTRELSZ],
661 2+(dyn[DT_PLTREL]==DT_RELA));
662 do_relocs(p, (void *)(p->base+dyn[DT_REL]), dyn[DT_RELSZ], 2);
663 do_relocs(p, (void *)(p->base+dyn[DT_RELA]), dyn[DT_RELASZ], 3);
668 static size_t find_dyn(Phdr *ph, size_t cnt, size_t stride)
670 for (; cnt--; ph = (void *)((char *)ph + stride))
671 if (ph->p_type == PT_DYNAMIC)
676 static void find_map_range(Phdr *ph, size_t cnt, size_t stride, struct dso *p)
678 size_t min_addr = -1, max_addr = 0;
679 for (; cnt--; ph = (void *)((char *)ph + stride)) {
680 if (ph->p_type != PT_LOAD) continue;
681 if (ph->p_vaddr < min_addr)
682 min_addr = ph->p_vaddr;
683 if (ph->p_vaddr+ph->p_memsz > max_addr)
684 max_addr = ph->p_vaddr+ph->p_memsz;
686 min_addr &= -PAGE_SIZE;
687 max_addr = (max_addr + PAGE_SIZE-1) & -PAGE_SIZE;
688 p->map = p->base + min_addr;
689 p->map_len = max_addr - min_addr;
692 static void do_fini()
695 size_t dyn[DYN_CNT] = {0};
696 for (p=fini_head; p; p=p->fini_next) {
697 if (!p->constructed) continue;
698 decode_vec(p->dynv, dyn, DYN_CNT);
699 ((void (*)(void))(p->base + dyn[DT_FINI]))();
703 static void do_init_fini(struct dso *p)
705 size_t dyn[DYN_CNT] = {0};
706 int need_locking = libc.threads_minus_1;
707 /* Allow recursive calls that arise when a library calls
708 * dlopen from one of its constructors, but block any
709 * other threads until all ctors have finished. */
710 if (need_locking) pthread_mutex_lock(&init_fini_lock);
711 for (; p; p=p->prev) {
712 if (p->constructed) continue;
714 decode_vec(p->dynv, dyn, DYN_CNT);
715 if (dyn[0] & (1<<DT_FINI)) {
716 p->fini_next = fini_head;
719 if (dyn[0] & (1<<DT_INIT))
720 ((void (*)(void))(p->base + dyn[DT_INIT]))();
721 if (!need_locking && libc.threads_minus_1) {
723 pthread_mutex_lock(&init_fini_lock);
726 if (need_locking) pthread_mutex_unlock(&init_fini_lock);
729 void _dl_debug_state(void)
733 void *__copy_tls(unsigned char *mem)
738 if (!tls_cnt) return mem;
740 void **dtv = (void *)mem;
741 dtv[0] = (void *)tls_cnt;
744 mem += sizeof(void *) * (tls_cnt+1);
745 mem += -((uintptr_t)mem + sizeof(struct pthread)) & (tls_align-1);
747 mem += sizeof(struct pthread);
749 for (p=head; p; p=p->next) {
750 if (!p->tls_id) continue;
751 dtv[p->tls_id] = mem + p->tls_offset;
752 memcpy(dtv[p->tls_id], p->tls_image, p->tls_len);
755 mem += libc.tls_size - sizeof(struct pthread);
756 mem -= (uintptr_t)mem & (tls_align-1);
759 for (p=head; p; p=p->next) {
760 if (!p->tls_id) continue;
761 dtv[p->tls_id] = mem - p->tls_offset;
762 memcpy(dtv[p->tls_id], p->tls_image, p->tls_len);
769 void *__tls_get_addr(size_t *v)
771 pthread_t self = __pthread_self();
772 if (v[0]<=(size_t)self->dtv[0] && self->dtv[v[0]])
773 return (char *)self->dtv[v[0]]+v[1];
775 /* Block signals to make accessing new TLS async-signal-safe */
777 pthread_sigmask(SIG_BLOCK, SIGALL_SET, &set);
778 if (v[0]<=(size_t)self->dtv[0] && self->dtv[v[0]]) {
779 pthread_sigmask(SIG_SETMASK, &set, 0);
780 return (char *)self->dtv[v[0]]+v[1];
783 /* This is safe without any locks held because, if the caller
784 * is able to request the Nth entry of the DTV, the DSO list
785 * must be valid at least that far out and it was synchronized
786 * at program startup or by an already-completed call to dlopen. */
788 for (p=head; p->tls_id != v[0]; p=p->next);
790 /* Get new DTV space from new DSO if needed */
791 if (v[0] > (size_t)self->dtv[0]) {
792 void **newdtv = p->new_dtv +
793 (v[0]+1)*sizeof(void *)*a_fetch_add(&p->new_dtv_idx,1);
794 memcpy(newdtv, self->dtv,
795 ((size_t)self->dtv[0]+1) * sizeof(void *));
796 newdtv[0] = (void *)v[0];
800 /* Get new TLS memory from new DSO */
801 unsigned char *mem = p->new_tls +
802 (p->tls_size + p->tls_align) * a_fetch_add(&p->new_tls_idx,1);
803 mem += ((uintptr_t)p->tls_image - (uintptr_t)mem) & (p->tls_align-1);
804 self->dtv[v[0]] = mem;
805 memcpy(mem, p->tls_image, p->tls_len);
806 pthread_sigmask(SIG_SETMASK, &set, 0);
810 static void update_tls_size()
812 libc.tls_size = ALIGN(
813 (1+tls_cnt) * sizeof(void *) +
815 sizeof(struct pthread) +
820 void *__dynlink(int argc, char **argv)
822 size_t aux[AUX_CNT] = {0};
826 static struct dso builtin_dsos[3];
827 struct dso *const app = builtin_dsos+0;
828 struct dso *const lib = builtin_dsos+1;
829 struct dso *const vdso = builtin_dsos+2;
834 /* Find aux vector just past environ[] */
835 for (i=argc+1; argv[i]; i++)
836 if (!memcmp(argv[i], "LD_LIBRARY_PATH=", 16))
837 env_path = argv[i]+16;
838 else if (!memcmp(argv[i], "LD_PRELOAD=", 11))
839 env_preload = argv[i]+11;
840 auxv = (void *)(argv+i+1);
842 decode_vec(auxv, aux, AUX_CNT);
844 /* Only trust user/env if kernel says we're not suid/sgid */
845 if ((aux[0]&0x7800)!=0x7800 || aux[AT_UID]!=aux[AT_EUID]
846 || aux[AT_GID]!=aux[AT_EGID] || aux[AT_SECURE]) {
851 /* If the dynamic linker was invoked as a program itself, AT_BASE
852 * will not be set. In that case, we assume the base address is
853 * the start of the page containing the PHDRs; I don't know any
854 * better approach... */
856 aux[AT_BASE] = aux[AT_PHDR] & -PAGE_SIZE;
857 aux[AT_PHDR] = aux[AT_PHENT] = aux[AT_PHNUM] = 0;
860 /* The dynamic linker load address is passed by the kernel
861 * in the AUX vector, so this is easy. */
862 lib->base = (void *)aux[AT_BASE];
863 lib->name = lib->shortname = "libc.so";
865 ehdr = (void *)lib->base;
866 lib->phnum = ehdr->e_phnum;
867 lib->phdr = (void *)(aux[AT_BASE]+ehdr->e_phoff);
868 find_map_range(lib->phdr, ehdr->e_phnum, ehdr->e_phentsize, lib);
869 lib->dynv = (void *)(lib->base + find_dyn(lib->phdr,
870 ehdr->e_phnum, ehdr->e_phentsize));
874 size_t interp_off = 0;
875 size_t tls_image = 0;
876 /* Find load address of the main program, via AT_PHDR vs PT_PHDR. */
877 app->phdr = phdr = (void *)aux[AT_PHDR];
878 app->phnum = aux[AT_PHNUM];
879 for (i=aux[AT_PHNUM]; i; i--, phdr=(void *)((char *)phdr + aux[AT_PHENT])) {
880 if (phdr->p_type == PT_PHDR)
881 app->base = (void *)(aux[AT_PHDR] - phdr->p_vaddr);
882 else if (phdr->p_type == PT_INTERP)
883 interp_off = (size_t)phdr->p_vaddr;
884 else if (phdr->p_type == PT_TLS) {
885 tls_image = phdr->p_vaddr;
886 app->tls_len = phdr->p_filesz;
887 app->tls_size = phdr->p_memsz;
888 app->tls_align = phdr->p_align;
891 if (app->tls_size) app->tls_image = (char *)app->base + tls_image;
892 if (interp_off) lib->name = (char *)app->base + interp_off;
894 app->dynv = (void *)(app->base + find_dyn(
895 (void *)aux[AT_PHDR], aux[AT_PHNUM], aux[AT_PHENT]));
896 find_map_range((void *)aux[AT_PHDR],
897 aux[AT_PHNUM], aux[AT_PHENT], app);
900 char *ldname = argv[0];
901 size_t l = strlen(ldname);
902 if (l >= 3 && !strcmp(ldname+l-3, "ldd")) ldd_mode = 1;
903 *argv++ = (void *)-1;
904 if (argv[0] && !strcmp(argv[0], "--")) *argv++ = (void *)-1;
906 dprintf(2, "musl libc/dynamic program loader\n");
907 dprintf(2, "usage: %s pathname%s\n", ldname,
908 ldd_mode ? "" : " [args]");
911 fd = open(argv[0], O_RDONLY);
913 dprintf(2, "%s: cannot load %s: %s\n", ldname, argv[0], strerror(errno));
917 ehdr = (void *)map_library(fd, app);
919 dprintf(2, "%s: %s: Not a valid dynamic program\n", ldname, argv[0]);
926 app->phnum = ehdr->e_phnum;
927 app->phdr = (void *)(app->base + ehdr->e_phoff);
928 aux[AT_ENTRY] = ehdr->e_entry;
931 app->tls_id = tls_cnt = 1;
934 tls_offset = app->tls_size
935 + ( -((uintptr_t)app->tls_image + app->tls_size)
936 & (app->tls_align-1) );
938 tls_offset = app->tls_offset = app->tls_size
939 + ( -((uintptr_t)app->tls_image + app->tls_size)
940 & (app->tls_align-1) );
942 tls_align = MAXP2(tls_align, app->tls_align);
945 app->constructed = 1;
948 /* Attach to vdso, if provided by the kernel */
949 if (search_vec(auxv, &vdso_base, AT_SYSINFO_EHDR)) {
950 ehdr = (void *)vdso_base;
951 vdso->phdr = phdr = (void *)(vdso_base + ehdr->e_phoff);
952 vdso->phnum = ehdr->e_phnum;
953 for (i=ehdr->e_phnum; i; i--, phdr=(void *)((char *)phdr + ehdr->e_phentsize)) {
954 if (phdr->p_type == PT_DYNAMIC)
955 vdso->dynv = (void *)(vdso_base + phdr->p_offset);
956 if (phdr->p_type == PT_LOAD)
957 vdso->base = (void *)(vdso_base - phdr->p_vaddr + phdr->p_offset);
960 vdso->shortname = "linux-gate.so.1";
967 /* Initial dso chain consists only of the app. We temporarily
968 * append the dynamic linker/libc so we can relocate it, then
969 * restore the initial chain in preparation for loading third
970 * party libraries (preload/needed). */
977 /* PAST THIS POINT, ALL LIBC INTERFACES ARE FULLY USABLE. */
979 /* Donate unused parts of app and library mapping to malloc */
980 reclaim_gaps(app->base, (void *)aux[AT_PHDR], aux[AT_PHENT], aux[AT_PHNUM]);
981 ehdr = (void *)lib->base;
982 reclaim_gaps(lib->base, (void *)(lib->base+ehdr->e_phoff),
983 ehdr->e_phentsize, ehdr->e_phnum);
985 /* Load preload/needed libraries, add their symbols to the global
986 * namespace, and perform all remaining relocations. The main
987 * program must be relocated LAST since it may contain copy
988 * relocations which depend on libraries' relocations. */
989 if (env_preload) load_preload(env_preload);
993 reloc_all(app->next);
998 void *mem = mmap(0, libc.tls_size, PROT_READ|PROT_WRITE,
999 MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
1000 if (mem==MAP_FAILED ||
1001 !__install_initial_tls(__copy_tls(mem))) {
1002 dprintf(2, "%s: Error getting %zu bytes thread-local storage: %m\n",
1003 argv[0], libc.tls_size);
1008 if (ldso_fail) _exit(127);
1009 if (ldd_mode) _exit(0);
1011 /* Switch to runtime mode: any further failures in the dynamic
1012 * linker are a reportable failure rather than a fatal startup
1013 * error. If the dynamic loader (dlopen) will not be used, free
1014 * all memory used by the dynamic linker. */
1017 #ifndef DYNAMIC_IS_RO
1018 for (i=0; app->dynv[i]; i+=2)
1019 if (app->dynv[i]==DT_DEBUG)
1020 app->dynv[i+1] = (size_t)&debug;
1023 debug.bp = _dl_debug_state;
1025 debug.base = lib->base;
1029 if (ssp_used) __init_ssp((void *)aux[AT_RANDOM]);
1032 return (void *)aux[AT_ENTRY];
1035 void __init_ldso_ctors(void)
1041 void *dlopen(const char *file, int mode)
1043 struct dso *volatile p, *orig_tail, *next;
1044 size_t orig_tls_cnt, orig_tls_offset, orig_tls_align;
1048 if (!file) return head;
1050 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
1051 pthread_rwlock_wrlock(&lock);
1055 orig_tls_cnt = tls_cnt;
1056 orig_tls_offset = tls_offset;
1057 orig_tls_align = tls_align;
1059 noload = mode & RTLD_NOLOAD;
1061 if (setjmp(rtld_fail)) {
1062 /* Clean up anything new that was (partially) loaded */
1063 if (p && p->deps) for (i=0; p->deps[i]; i++)
1064 if (p->deps[i]->global < 0)
1065 p->deps[i]->global = 0;
1066 for (p=orig_tail->next; p; p=next) {
1068 munmap(p->map, p->map_len);
1072 tls_cnt = orig_tls_cnt;
1073 tls_offset = orig_tls_offset;
1074 tls_align = orig_tls_align;
1080 } else p = load_library(file);
1083 snprintf(errbuf, sizeof errbuf, noload ?
1084 "Library %s is not already loaded" :
1085 "Error loading shared library %s: %m",
1091 /* First load handling */
1094 if (p->deps) for (i=0; p->deps[i]; i++)
1095 if (!p->deps[i]->global)
1096 p->deps[i]->global = -1;
1097 if (!p->global) p->global = -1;
1099 if (p->deps) for (i=0; p->deps[i]; i++)
1100 if (p->deps[i]->global < 0)
1101 p->deps[i]->global = 0;
1102 if (p->global < 0) p->global = 0;
1105 if (mode & RTLD_GLOBAL) {
1106 if (p->deps) for (i=0; p->deps[i]; i++)
1107 p->deps[i]->global = 1;
1113 if (ssp_used) __init_ssp(libc.auxv);
1120 pthread_rwlock_unlock(&lock);
1121 if (p) do_init_fini(orig_tail);
1122 pthread_setcancelstate(cs, 0);
1126 static int invalid_dso_handle(void *h)
1129 for (p=head; p; p=p->next) if (h==p) return 0;
1130 snprintf(errbuf, sizeof errbuf, "Invalid library handle %p", (void *)h);
1135 static void *do_dlsym(struct dso *p, const char *s, void *ra)
1138 uint32_t h = 0, gh = 0;
1140 if (p == head || p == RTLD_DEFAULT || p == RTLD_NEXT) {
1141 if (p == RTLD_DEFAULT) {
1143 } else if (p == RTLD_NEXT) {
1144 for (p=head; p && (unsigned char *)ra-p->map>p->map_len; p=p->next);
1148 struct symdef def = find_sym(p, s, 0);
1149 if (!def.sym) goto failed;
1150 if ((def.sym->st_info&0xf) == STT_TLS)
1151 return __tls_get_addr((size_t []){def.dso->tls_id, def.sym->st_value});
1152 return def.dso->base + def.sym->st_value;
1154 if (p != RTLD_DEFAULT && p != RTLD_NEXT && invalid_dso_handle(p))
1158 sym = gnu_lookup(s, gh, p);
1161 sym = sysv_lookup(s, h, p);
1163 if (sym && (sym->st_info&0xf) == STT_TLS)
1164 return __tls_get_addr((size_t []){p->tls_id, sym->st_value});
1165 if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
1166 return p->base + sym->st_value;
1167 if (p->deps) for (i=0; p->deps[i]; i++) {
1168 if (p->deps[i]->ghashtab) {
1169 if (!gh) gh = gnu_hash(s);
1170 sym = gnu_lookup(s, gh, p->deps[i]);
1172 if (!h) h = sysv_hash(s);
1173 sym = sysv_lookup(s, h, p->deps[i]);
1175 if (sym && (sym->st_info&0xf) == STT_TLS)
1176 return __tls_get_addr((size_t []){p->deps[i]->tls_id, sym->st_value});
1177 if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
1178 return p->deps[i]->base + sym->st_value;
1182 snprintf(errbuf, sizeof errbuf, "Symbol not found: %s", s);
1186 int __dladdr(void *addr, Dl_info *info)
1196 pthread_rwlock_rdlock(&lock);
1197 for (p=head; p && (unsigned char *)addr-p->map>p->map_len; p=p->next);
1198 pthread_rwlock_unlock(&lock);
1203 strings = p->strings;
1205 nsym = p->hashtab[1];
1209 buckets = p->ghashtab + 4 + (p->ghashtab[2]*sizeof(size_t)/4);
1210 sym += p->ghashtab[1];
1211 for (i = 0; i < p->ghashtab[0]; i++) {
1212 if (buckets[i] > nsym)
1216 nsym -= p->ghashtab[1];
1217 hashval = buckets + p->ghashtab[0] + nsym;
1219 while (!(*hashval++ & 1));
1223 for (; nsym; nsym--, sym++) {
1225 && (1<<(sym->st_info&0xf) & OK_TYPES)
1226 && (1<<(sym->st_info>>4) & OK_BINDS)) {
1227 void *symaddr = p->base + sym->st_value;
1228 if (symaddr > addr || symaddr < best)
1231 bestname = strings + sym->st_name;
1232 if (addr == symaddr)
1237 if (!best) return 0;
1239 info->dli_fname = p->name;
1240 info->dli_fbase = p->base;
1241 info->dli_sname = bestname;
1242 info->dli_saddr = best;
1247 void *__dlsym(void *restrict p, const char *restrict s, void *restrict ra)
1250 pthread_rwlock_rdlock(&lock);
1251 res = do_dlsym(p, s, ra);
1252 pthread_rwlock_unlock(&lock);
1256 int dl_iterate_phdr(int(*callback)(struct dl_phdr_info *info, size_t size, void *data), void *data)
1258 struct dso *current;
1259 struct dl_phdr_info info;
1261 for(current = head; current;) {
1262 info.dlpi_addr = (uintptr_t)current->base;
1263 info.dlpi_name = current->name;
1264 info.dlpi_phdr = current->phdr;
1265 info.dlpi_phnum = current->phnum;
1266 info.dlpi_adds = gencnt;
1268 info.dlpi_tls_modid = current->tls_id;
1269 info.dlpi_tls_data = current->tls_image;
1271 ret = (callback)(&info, sizeof (info), data);
1273 if (ret != 0) break;
1275 pthread_rwlock_rdlock(&lock);
1276 current = current->next;
1277 pthread_rwlock_unlock(&lock);
1282 static int invalid_dso_handle(void *h)
1284 snprintf(errbuf, sizeof errbuf, "Invalid library handle %p", (void *)h);
1288 void *dlopen(const char *file, int mode)
1292 void *__dlsym(void *restrict p, const char *restrict s, void *restrict ra)
1296 int __dladdr (void *addr, Dl_info *info)
1302 int __dlinfo(void *dso, int req, void *res)
1304 if (invalid_dso_handle(dso)) return -1;
1305 if (req != RTLD_DI_LINKMAP) {
1306 snprintf(errbuf, sizeof errbuf, "Unsupported request %d", req);
1310 *(struct link_map **)res = dso;
1316 if (!errflag) return 0;
1321 int dlclose(void *p)
1323 return invalid_dso_handle(p);