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;
102 static jmp_buf rtld_fail;
103 static pthread_rwlock_t lock;
104 static struct debug debug;
105 static size_t tls_cnt, tls_offset, tls_align = 4*sizeof(size_t);
106 static pthread_mutex_t init_fini_lock = { ._m_type = PTHREAD_MUTEX_RECURSIVE };
108 struct debug *_dl_debug_addr = &debug;
113 static void decode_vec(size_t *v, size_t *a, size_t cnt)
115 memset(a, 0, cnt*sizeof(size_t));
116 for (; v[0]; v+=2) if (v[0]<cnt) {
122 static int search_vec(size_t *v, size_t *r, size_t key)
124 for (; v[0]!=key; v+=2)
130 static uint32_t sysv_hash(const char *s0)
132 const unsigned char *s = (void *)s0;
138 return h & 0xfffffff;
141 static uint32_t gnu_hash(const char *s0)
143 const unsigned char *s = (void *)s0;
144 uint_fast32_t h = 5381;
150 static Sym *sysv_lookup(const char *s, uint32_t h, struct dso *dso)
153 Sym *syms = dso->syms;
154 uint32_t *hashtab = dso->hashtab;
155 char *strings = dso->strings;
156 for (i=hashtab[2+h%hashtab[0]]; i; i=hashtab[2+hashtab[0]+i]) {
157 if (!strcmp(s, strings+syms[i].st_name))
163 static Sym *gnu_lookup(const char *s, uint32_t h1, struct dso *dso)
167 uint32_t *hashtab = dso->ghashtab;
168 uint32_t nbuckets = hashtab[0];
169 uint32_t *buckets = hashtab + 4 + hashtab[2]*(sizeof(size_t)/4);
172 uint32_t n = buckets[h1 % nbuckets];
176 strings = dso->strings;
178 hashval = buckets + nbuckets + (n - hashtab[1]);
180 for (h1 |= 1; ; sym++) {
182 if ((h1 == (h2|1)) && !strcmp(s, strings + sym->st_name))
190 #define OK_TYPES (1<<STT_NOTYPE | 1<<STT_OBJECT | 1<<STT_FUNC | 1<<STT_COMMON | 1<<STT_TLS)
191 #define OK_BINDS (1<<STB_GLOBAL | 1<<STB_WEAK)
193 static struct symdef find_sym(struct dso *dso, const char *s, int need_def)
195 uint32_t h = 0, gh = 0;
196 struct symdef def = {0};
199 if (gh == 0x1f4039c9 && !strcmp(s, "__stack_chk_fail")) ssp_used = 1;
202 if (h == 0x595a4cc && !strcmp(s, "__stack_chk_fail")) ssp_used = 1;
204 for (; dso; dso=dso->next) {
206 if (!dso->global) continue;
208 if (!gh) gh = gnu_hash(s);
209 sym = gnu_lookup(s, gh, dso);
211 if (!h) h = sysv_hash(s);
212 sym = sysv_lookup(s, h, dso);
216 if (need_def || (sym->st_info&0xf) == STT_TLS)
219 if ((sym->st_info&0xf) != STT_TLS)
221 if (!(1<<(sym->st_info&0xf) & OK_TYPES)) continue;
222 if (!(1<<(sym->st_info>>4) & OK_BINDS)) continue;
224 if (def.sym && sym->st_info>>4 == STB_WEAK) continue;
227 if (sym->st_info>>4 == STB_GLOBAL) break;
232 static void do_relocs(struct dso *dso, size_t *rel, size_t rel_size, size_t stride)
234 unsigned char *base = dso->base;
235 Sym *syms = dso->syms;
236 char *strings = dso->strings;
244 for (; rel_size; rel+=stride, rel_size-=stride*sizeof(size_t)) {
245 type = R_TYPE(rel[1]);
246 sym_index = R_SYM(rel[1]);
248 sym = syms + sym_index;
249 name = strings + sym->st_name;
250 ctx = IS_COPY(type) ? head->next : head;
251 def = find_sym(ctx, name, IS_PLT(type));
252 if (!def.sym && sym->st_info>>4 != STB_WEAK) {
253 snprintf(errbuf, sizeof errbuf,
254 "Error relocating %s: %s: symbol not found",
256 if (runtime) longjmp(rtld_fail, 1);
257 dprintf(2, "%s\n", errbuf);
266 do_single_reloc(dso, base, (void *)(base + rel[0]), type,
267 stride>2 ? rel[2] : 0, sym, sym?sym->st_size:0, def,
268 def.sym?(size_t)(def.dso->base+def.sym->st_value):0);
272 /* A huge hack: to make up for the wastefulness of shared libraries
273 * needing at least a page of dirty memory even if they have no global
274 * data, we reclaim the gaps at the beginning and end of writable maps
275 * and "donate" them to the heap by setting up minimal malloc
276 * structures and then freeing them. */
278 static void reclaim(unsigned char *base, size_t start, size_t end)
281 start = start + 6*sizeof(size_t)-1 & -4*sizeof(size_t);
282 end = (end & -4*sizeof(size_t)) - 2*sizeof(size_t);
283 if (start>end || end-start < 4*sizeof(size_t)) return;
284 a = (size_t *)(base + start);
285 z = (size_t *)(base + end);
287 a[-1] = z[0] = end-start + 2*sizeof(size_t) | 1;
292 static void reclaim_gaps(unsigned char *base, Phdr *ph, size_t phent, size_t phcnt)
294 for (; phcnt--; ph=(void *)((char *)ph+phent)) {
295 if (ph->p_type!=PT_LOAD) continue;
296 if ((ph->p_flags&(PF_R|PF_W))!=(PF_R|PF_W)) continue;
297 reclaim(base, ph->p_vaddr & -PAGE_SIZE, ph->p_vaddr);
298 reclaim(base, ph->p_vaddr+ph->p_memsz,
299 ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE);
303 static void *map_library(int fd, struct dso *dso)
305 Ehdr buf[(896+sizeof(Ehdr))/sizeof(Ehdr)];
307 size_t addr_min=SIZE_MAX, addr_max=0, map_len;
308 size_t this_min, this_max;
313 unsigned char *map, *base;
318 ssize_t l = read(fd, buf, sizeof buf);
319 if (l<sizeof *eh) return 0;
321 phsize = eh->e_phentsize * eh->e_phnum;
322 if (phsize + sizeof *eh > l) return 0;
323 if (eh->e_phoff + phsize > l) {
324 l = pread(fd, buf+1, phsize, eh->e_phoff);
325 if (l != phsize) return 0;
326 eh->e_phoff = sizeof *eh;
328 ph = (void *)((char *)buf + eh->e_phoff);
330 dso->phnum = eh->e_phnum;
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;
365 ph = (void *)((char *)buf + eh->e_phoff);
366 for (i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
367 if (ph->p_type != PT_LOAD) continue;
368 /* Reuse the existing mapping for the lowest-address LOAD */
369 if ((ph->p_vaddr & -PAGE_SIZE) == addr_min) continue;
370 this_min = ph->p_vaddr & -PAGE_SIZE;
371 this_max = ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE;
372 off_start = ph->p_offset & -PAGE_SIZE;
373 prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
374 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
375 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
376 if (mmap(base+this_min, this_max-this_min, prot, MAP_PRIVATE|MAP_FIXED, fd, off_start) == MAP_FAILED)
378 if (ph->p_memsz > ph->p_filesz) {
379 size_t brk = (size_t)base+ph->p_vaddr+ph->p_filesz;
380 size_t pgbrk = brk+PAGE_SIZE-1 & -PAGE_SIZE;
381 memset((void *)brk, 0, pgbrk-brk & PAGE_SIZE-1);
382 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)
386 for (i=0; ((size_t *)(base+dyn))[i]; i+=2)
387 if (((size_t *)(base+dyn))[i]==DT_TEXTREL) {
388 if (mprotect(map, map_len, PROT_READ|PROT_WRITE|PROT_EXEC) < 0)
392 if (!runtime) reclaim_gaps(base, (void *)((char *)buf + eh->e_phoff),
393 eh->e_phentsize, eh->e_phnum);
395 dso->map_len = map_len;
397 dso->dynv = (void *)(base+dyn);
398 if (dso->tls_size) dso->tls_image = (void *)(base+tls_image);
401 munmap(map, map_len);
405 static int path_open(const char *name, const char *search, char *buf, size_t buf_size)
407 const char *s=search, *z;
413 l = z ? z-s : strlen(s);
414 snprintf(buf, buf_size, "%.*s/%s", l, s, name);
415 if ((fd = open(buf, O_RDONLY|O_CLOEXEC))>=0) return fd;
420 static void decode_dyn(struct dso *p)
422 size_t dyn[DYN_CNT] = {0};
423 decode_vec(p->dynv, dyn, DYN_CNT);
424 p->syms = (void *)(p->base + dyn[DT_SYMTAB]);
425 p->strings = (void *)(p->base + dyn[DT_STRTAB]);
426 if (dyn[0]&(1<<DT_HASH))
427 p->hashtab = (void *)(p->base + dyn[DT_HASH]);
428 if (search_vec(p->dynv, dyn, DT_GNU_HASH))
429 p->ghashtab = (void *)(p->base + *dyn);
432 static struct dso *load_library(const char *name)
434 char buf[2*NAME_MAX+2];
435 const char *pathname;
436 unsigned char *base, *map;
438 struct dso *p, temp_dso = {0};
444 /* Catch and block attempts to reload the implementation itself */
445 if (name[0]=='l' && name[1]=='i' && name[2]=='b') {
446 static const char *rp, reserved[] =
447 "c\0pthread\0rt\0m\0dl\0util\0xnet\0";
448 char *z = strchr(name, '.');
451 for (rp=reserved; *rp && memcmp(name+3, rp, l-3); rp+=strlen(rp)+1);
456 tail = ldso->next ? ldso->next : ldso;
462 if (strchr(name, '/')) {
464 fd = open(name, O_RDONLY|O_CLOEXEC);
466 /* Search for the name to see if it's already loaded */
467 for (p=head->next; p; p=p->next) {
468 if (p->shortname && !strcmp(p->shortname, name)) {
473 if (strlen(name) > NAME_MAX) return 0;
475 if (r_path) fd = path_open(name, r_path, buf, sizeof buf);
476 if (fd < 0 && env_path) fd = path_open(name, env_path, buf, sizeof buf);
479 FILE *f = fopen(ETC_LDSO_PATH, "rbe");
481 if (getline(&sys_path, (size_t[1]){0}, f) > 0)
482 sys_path[strlen(sys_path)-1]=0;
486 if (sys_path) fd = path_open(name, sys_path, buf, sizeof buf);
487 else fd = path_open(name, "/lib:/usr/local/lib:/usr/lib", buf, sizeof buf);
491 if (fd < 0) return 0;
492 if (fstat(fd, &st) < 0) {
496 for (p=head->next; p; p=p->next) {
497 if (p->dev == st.st_dev && p->ino == st.st_ino) {
498 /* If this library was previously loaded with a
499 * pathname but a search found the same inode,
500 * setup its shortname so it can be found by name. */
501 if (!p->shortname && pathname != name)
502 p->shortname = strrchr(p->name, '/')+1;
508 map = map_library(fd, &temp_dso);
512 /* Allocate storage for the new DSO. When there is TLS, this
513 * storage must include a reservation for all pre-existing
514 * threads to obtain copies of both the new TLS, and an
515 * extended DTV capable of storing an additional slot for
516 * the newly-loaded DSO. */
517 alloc_size = sizeof *p + strlen(pathname) + 1;
518 if (runtime && temp_dso.tls_image) {
519 size_t per_th = temp_dso.tls_size + temp_dso.tls_align
520 + sizeof(void *) * (tls_cnt+3);
521 n_th = libc.threads_minus_1 + 1;
522 if (n_th > SSIZE_MAX / per_th) alloc_size = SIZE_MAX;
523 else alloc_size += n_th * per_th;
525 p = calloc(1, alloc_size);
527 munmap(map, map_len);
530 memcpy(p, &temp_dso, sizeof temp_dso);
536 strcpy(p->name, pathname);
537 /* Add a shortname only if name arg was not an explicit pathname. */
538 if (pathname != name) p->shortname = strrchr(p->name, '/')+1;
540 if (runtime && !__pthread_self_init()) {
542 munmap(map, map_len);
545 p->tls_id = ++tls_cnt;
546 tls_align = MAXP2(tls_align, p->tls_align);
548 p->tls_offset = tls_offset + ( (tls_align-1) &
549 -(tls_offset + (uintptr_t)p->tls_image) );
550 tls_offset += p->tls_size;
552 tls_offset += p->tls_size + p->tls_align - 1;
553 tls_offset -= (tls_offset + (uintptr_t)p->tls_image)
555 p->tls_offset = tls_offset;
557 p->new_dtv = (void *)(-sizeof(size_t) &
558 (uintptr_t)(p->name+strlen(p->name)+sizeof(size_t)));
559 p->new_tls = (void *)(p->new_dtv + n_th*(tls_cnt+1));
566 if (ldd_mode) dprintf(1, "\t%s => %s (%p)\n", name, pathname, base);
571 static void load_deps(struct dso *p)
574 struct dso ***deps = &p->deps, **tmp, *dep;
575 for (; p; p=p->next) {
576 for (i=0; p->dynv[i]; i+=2) {
577 if (p->dynv[i] != DT_RPATH) continue;
578 r_path = (void *)(p->strings + p->dynv[i+1]);
580 for (i=0; p->dynv[i]; i+=2) {
581 if (p->dynv[i] != DT_NEEDED) continue;
582 dep = load_library(p->strings + p->dynv[i+1]);
584 snprintf(errbuf, sizeof errbuf,
585 "Error loading shared library %s: %m (needed by %s)",
586 p->strings + p->dynv[i+1], p->name);
587 if (runtime) longjmp(rtld_fail, 1);
588 dprintf(2, "%s\n", errbuf);
593 tmp = realloc(*deps, sizeof(*tmp)*(ndeps+2));
594 if (!tmp) longjmp(rtld_fail, 1);
604 static void load_preload(char *s)
609 for ( ; *s && isspace(*s); s++);
610 for (z=s; *z && !isspace(*z); z++);
618 static void make_global(struct dso *p)
620 for (; p; p=p->next) p->global = 1;
623 static void reloc_all(struct dso *p)
625 size_t dyn[DYN_CNT] = {0};
626 for (; p; p=p->next) {
627 if (p->relocated) continue;
628 decode_vec(p->dynv, dyn, DYN_CNT);
629 #ifdef NEED_ARCH_RELOCS
630 do_arch_relocs(p, head);
632 do_relocs(p, (void *)(p->base+dyn[DT_JMPREL]), dyn[DT_PLTRELSZ],
633 2+(dyn[DT_PLTREL]==DT_RELA));
634 do_relocs(p, (void *)(p->base+dyn[DT_REL]), dyn[DT_RELSZ], 2);
635 do_relocs(p, (void *)(p->base+dyn[DT_RELA]), dyn[DT_RELASZ], 3);
640 static size_t find_dyn(Phdr *ph, size_t cnt, size_t stride)
642 for (; cnt--; ph = (void *)((char *)ph + stride))
643 if (ph->p_type == PT_DYNAMIC)
648 static void find_map_range(Phdr *ph, size_t cnt, size_t stride, struct dso *p)
650 size_t min_addr = -1, max_addr = 0;
651 for (; cnt--; ph = (void *)((char *)ph + stride)) {
652 if (ph->p_type != PT_LOAD) continue;
653 if (ph->p_vaddr < min_addr)
654 min_addr = ph->p_vaddr;
655 if (ph->p_vaddr+ph->p_memsz > max_addr)
656 max_addr = ph->p_vaddr+ph->p_memsz;
658 min_addr &= -PAGE_SIZE;
659 max_addr = (max_addr + PAGE_SIZE-1) & -PAGE_SIZE;
660 p->map = p->base + min_addr;
661 p->map_len = max_addr - min_addr;
664 static void do_fini()
667 size_t dyn[DYN_CNT] = {0};
668 for (p=fini_head; p; p=p->fini_next) {
669 if (!p->constructed) continue;
670 decode_vec(p->dynv, dyn, DYN_CNT);
671 ((void (*)(void))(p->base + dyn[DT_FINI]))();
675 static void do_init_fini(struct dso *p)
677 size_t dyn[DYN_CNT] = {0};
678 int need_locking = libc.threads_minus_1;
679 /* Allow recursive calls that arise when a library calls
680 * dlopen from one of its constructors, but block any
681 * other threads until all ctors have finished. */
682 if (need_locking) pthread_mutex_lock(&init_fini_lock);
683 for (; p; p=p->prev) {
684 if (p->constructed) continue;
686 decode_vec(p->dynv, dyn, DYN_CNT);
687 if (dyn[0] & (1<<DT_FINI)) {
688 p->fini_next = fini_head;
691 if (dyn[0] & (1<<DT_INIT))
692 ((void (*)(void))(p->base + dyn[DT_INIT]))();
694 if (need_locking) pthread_mutex_unlock(&init_fini_lock);
697 void _dl_debug_state(void)
701 void *__copy_tls(unsigned char *mem)
706 if (!tls_cnt) return mem;
708 void **dtv = (void *)mem;
709 dtv[0] = (void *)tls_cnt;
712 mem += sizeof(void *) * (tls_cnt+1);
713 mem += -((uintptr_t)mem + sizeof(struct pthread)) & (tls_align-1);
715 mem += sizeof(struct pthread);
717 for (p=head; p; p=p->next) {
718 if (!p->tls_id) continue;
719 dtv[p->tls_id] = mem + p->tls_offset;
720 memcpy(dtv[p->tls_id], p->tls_image, p->tls_len);
723 mem += libc.tls_size - sizeof(struct pthread);
724 mem -= (uintptr_t)mem & (tls_align-1);
727 for (p=head; p; p=p->next) {
728 if (!p->tls_id) continue;
729 dtv[p->tls_id] = mem - p->tls_offset;
730 memcpy(dtv[p->tls_id], p->tls_image, p->tls_len);
737 void *__tls_get_addr(size_t *v)
739 pthread_t self = __pthread_self();
740 if (self->dtv && v[0]<=(size_t)self->dtv[0] && self->dtv[v[0]])
741 return (char *)self->dtv[v[0]]+v[1];
743 /* Block signals to make accessing new TLS async-signal-safe */
745 pthread_sigmask(SIG_BLOCK, SIGALL_SET, &set);
746 if (self->dtv && v[0]<=(size_t)self->dtv[0] && self->dtv[v[0]]) {
747 pthread_sigmask(SIG_SETMASK, &set, 0);
748 return (char *)self->dtv[v[0]]+v[1];
751 /* This is safe without any locks held because, if the caller
752 * is able to request the Nth entry of the DTV, the DSO list
753 * must be valid at least that far out and it was synchronized
754 * at program startup or by an already-completed call to dlopen. */
756 for (p=head; p->tls_id != v[0]; p=p->next);
758 /* Get new DTV space from new DSO if needed */
759 if (!self->dtv || v[0] > (size_t)self->dtv[0]) {
760 void **newdtv = p->new_dtv +
761 (v[0]+1)*sizeof(void *)*a_fetch_add(&p->new_dtv_idx,1);
762 if (self->dtv) memcpy(newdtv, self->dtv,
763 ((size_t)self->dtv[0]+1) * sizeof(void *));
764 newdtv[0] = (void *)v[0];
768 /* Get new TLS memory from new DSO */
769 unsigned char *mem = p->new_tls +
770 (p->tls_size + p->tls_align) * a_fetch_add(&p->new_tls_idx,1);
771 mem += ((uintptr_t)p->tls_image - (uintptr_t)mem) & (p->tls_align-1);
772 self->dtv[v[0]] = mem;
773 memcpy(mem, p->tls_image, p->tls_len);
774 pthread_sigmask(SIG_SETMASK, &set, 0);
778 static void update_tls_size()
780 libc.tls_size = ALIGN(
781 (1+tls_cnt) * sizeof(void *) +
783 sizeof(struct pthread) +
788 void *__dynlink(int argc, char **argv)
790 size_t aux[AUX_CNT] = {0};
794 static struct dso builtin_dsos[3];
795 struct dso *const app = builtin_dsos+0;
796 struct dso *const lib = builtin_dsos+1;
797 struct dso *const vdso = builtin_dsos+2;
802 /* Find aux vector just past environ[] */
803 for (i=argc+1; argv[i]; i++)
804 if (!memcmp(argv[i], "LD_LIBRARY_PATH=", 16))
805 env_path = argv[i]+16;
806 else if (!memcmp(argv[i], "LD_PRELOAD=", 11))
807 env_preload = argv[i]+11;
808 auxv = (void *)(argv+i+1);
810 decode_vec(auxv, aux, AUX_CNT);
812 /* Only trust user/env if kernel says we're not suid/sgid */
813 if ((aux[0]&0x7800)!=0x7800 || aux[AT_UID]!=aux[AT_EUID]
814 || aux[AT_GID]!=aux[AT_EGID] || aux[AT_SECURE]) {
819 /* If the dynamic linker was invoked as a program itself, AT_BASE
820 * will not be set. In that case, we assume the base address is
821 * the start of the page containing the PHDRs; I don't know any
822 * better approach... */
824 aux[AT_BASE] = aux[AT_PHDR] & -PAGE_SIZE;
825 aux[AT_PHDR] = aux[AT_PHENT] = aux[AT_PHNUM] = 0;
828 /* The dynamic linker load address is passed by the kernel
829 * in the AUX vector, so this is easy. */
830 lib->base = (void *)aux[AT_BASE];
831 lib->name = lib->shortname = "libc.so";
833 ehdr = (void *)lib->base;
834 lib->phnum = ehdr->e_phnum;
835 lib->phdr = (void *)(aux[AT_BASE]+ehdr->e_phoff);
836 find_map_range(lib->phdr, ehdr->e_phnum, ehdr->e_phentsize, lib);
837 lib->dynv = (void *)(lib->base + find_dyn(lib->phdr,
838 ehdr->e_phnum, ehdr->e_phentsize));
842 size_t interp_off = 0;
843 size_t tls_image = 0;
844 /* Find load address of the main program, via AT_PHDR vs PT_PHDR. */
845 app->phdr = phdr = (void *)aux[AT_PHDR];
846 app->phnum = aux[AT_PHNUM];
847 for (i=aux[AT_PHNUM]; i; i--, phdr=(void *)((char *)phdr + aux[AT_PHENT])) {
848 if (phdr->p_type == PT_PHDR)
849 app->base = (void *)(aux[AT_PHDR] - phdr->p_vaddr);
850 else if (phdr->p_type == PT_INTERP)
851 interp_off = (size_t)phdr->p_vaddr;
852 else if (phdr->p_type == PT_TLS) {
853 tls_image = phdr->p_vaddr;
854 app->tls_len = phdr->p_filesz;
855 app->tls_size = phdr->p_memsz;
856 app->tls_align = phdr->p_align;
859 if (app->tls_size) app->tls_image = (char *)app->base + tls_image;
860 if (interp_off) lib->name = (char *)app->base + interp_off;
862 app->dynv = (void *)(app->base + find_dyn(
863 (void *)aux[AT_PHDR], aux[AT_PHNUM], aux[AT_PHENT]));
864 find_map_range((void *)aux[AT_PHDR],
865 aux[AT_PHNUM], aux[AT_PHENT], app);
868 char *ldname = argv[0];
869 size_t l = strlen(ldname);
870 if (l >= 3 && !strcmp(ldname+l-3, "ldd")) ldd_mode = 1;
871 *argv++ = (void *)-1;
872 if (argv[0] && !strcmp(argv[0], "--")) *argv++ = (void *)-1;
874 dprintf(2, "musl libc/dynamic program loader\n");
875 dprintf(2, "usage: %s pathname%s\n", ldname,
876 ldd_mode ? "" : " [args]");
879 fd = open(argv[0], O_RDONLY);
881 dprintf(2, "%s: cannot load %s: %s\n", ldname, argv[0], strerror(errno));
885 ehdr = (void *)map_library(fd, app);
887 dprintf(2, "%s: %s: Not a valid dynamic program\n", ldname, argv[0]);
894 app->phnum = ehdr->e_phnum;
895 app->phdr = (void *)(app->base + ehdr->e_phoff);
896 aux[AT_ENTRY] = ehdr->e_entry;
899 app->tls_id = tls_cnt = 1;
902 tls_offset = app->tls_size
903 + ( -((uintptr_t)app->tls_image + app->tls_size)
904 & (app->tls_align-1) );
906 tls_offset = app->tls_offset = app->tls_size
907 + ( -((uintptr_t)app->tls_image + app->tls_size)
908 & (app->tls_align-1) );
910 tls_align = MAXP2(tls_align, app->tls_align);
913 app->constructed = 1;
916 /* Attach to vdso, if provided by the kernel */
917 if (search_vec(auxv, &vdso_base, AT_SYSINFO_EHDR)) {
918 ehdr = (void *)vdso_base;
919 vdso->phdr = phdr = (void *)(vdso_base + ehdr->e_phoff);
920 vdso->phnum = ehdr->e_phnum;
921 for (i=ehdr->e_phnum; i; i--, phdr=(void *)((char *)phdr + ehdr->e_phentsize)) {
922 if (phdr->p_type == PT_DYNAMIC)
923 vdso->dynv = (void *)(vdso_base + phdr->p_offset);
924 if (phdr->p_type == PT_LOAD)
925 vdso->base = (void *)(vdso_base - phdr->p_vaddr + phdr->p_offset);
927 vdso->name = vdso->shortname = "linux-gate.so.1";
934 /* Initial dso chain consists only of the app. We temporarily
935 * append the dynamic linker/libc so we can relocate it, then
936 * restore the initial chain in preparation for loading third
937 * party libraries (preload/needed). */
944 /* PAST THIS POINT, ALL LIBC INTERFACES ARE FULLY USABLE. */
946 /* Donate unused parts of app and library mapping to malloc */
947 reclaim_gaps(app->base, (void *)aux[AT_PHDR], aux[AT_PHENT], aux[AT_PHNUM]);
948 ehdr = (void *)lib->base;
949 reclaim_gaps(lib->base, (void *)(lib->base+ehdr->e_phoff),
950 ehdr->e_phentsize, ehdr->e_phnum);
952 /* Load preload/needed libraries, add their symbols to the global
953 * namespace, and perform all remaining relocations. The main
954 * program must be relocated LAST since it may contain copy
955 * relocations which depend on libraries' relocations. */
956 if (env_preload) load_preload(env_preload);
960 reloc_all(app->next);
965 void *mem = mmap(0, libc.tls_size, PROT_READ|PROT_WRITE,
966 MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
967 if (mem==MAP_FAILED ||
968 !__install_initial_tls(__copy_tls(mem))) {
969 dprintf(2, "%s: Error getting %zu bytes thread-local storage: %m\n",
970 argv[0], libc.tls_size);
975 if (ldso_fail) _exit(127);
976 if (ldd_mode) _exit(0);
978 /* Switch to runtime mode: any further failures in the dynamic
979 * linker are a reportable failure rather than a fatal startup
980 * error. If the dynamic loader (dlopen) will not be used, free
981 * all memory used by the dynamic linker. */
984 #ifndef DYNAMIC_IS_RO
985 for (i=0; app->dynv[i]; i+=2)
986 if (app->dynv[i]==DT_DEBUG)
987 app->dynv[i+1] = (size_t)&debug;
990 debug.bp = _dl_debug_state;
992 debug.base = lib->base;
996 if (ssp_used) __init_ssp((void *)aux[AT_RANDOM]);
1002 return (void *)aux[AT_ENTRY];
1005 void *dlopen(const char *file, int mode)
1007 struct dso *volatile p, *orig_tail, *next;
1008 size_t orig_tls_cnt, orig_tls_offset, orig_tls_align;
1012 if (!file) return head;
1014 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
1015 pthread_rwlock_wrlock(&lock);
1019 orig_tls_cnt = tls_cnt;
1020 orig_tls_offset = tls_offset;
1021 orig_tls_align = tls_align;
1024 if (setjmp(rtld_fail)) {
1025 /* Clean up anything new that was (partially) loaded */
1026 if (p && p->deps) for (i=0; p->deps[i]; i++)
1027 if (p->deps[i]->global < 0)
1028 p->deps[i]->global = 0;
1029 for (p=orig_tail->next; p; p=next) {
1031 munmap(p->map, p->map_len);
1035 tls_cnt = orig_tls_cnt;
1036 tls_offset = orig_tls_offset;
1037 tls_align = orig_tls_align;
1043 } else p = load_library(file);
1046 snprintf(errbuf, sizeof errbuf,
1047 "Error loading shared library %s: %m", file);
1052 /* First load handling */
1055 if (p->deps) for (i=0; p->deps[i]; i++)
1056 if (!p->deps[i]->global)
1057 p->deps[i]->global = -1;
1058 if (!p->global) p->global = -1;
1060 if (p->deps) for (i=0; p->deps[i]; i++)
1061 if (p->deps[i]->global < 0)
1062 p->deps[i]->global = 0;
1063 if (p->global < 0) p->global = 0;
1066 if (mode & RTLD_GLOBAL) {
1067 if (p->deps) for (i=0; p->deps[i]; i++)
1068 p->deps[i]->global = 1;
1074 if (ssp_used) __init_ssp(libc.auxv);
1081 pthread_rwlock_unlock(&lock);
1082 if (p) do_init_fini(orig_tail);
1083 pthread_setcancelstate(cs, 0);
1087 static void *do_dlsym(struct dso *p, const char *s, void *ra)
1090 uint32_t h = 0, gh = 0;
1092 if (p == head || p == RTLD_DEFAULT || p == RTLD_NEXT) {
1093 if (p == RTLD_DEFAULT) {
1095 } else if (p == RTLD_NEXT) {
1096 for (p=head; p && (unsigned char *)ra-p->map>p->map_len; p=p->next);
1100 struct symdef def = find_sym(p, s, 0);
1101 if (!def.sym) goto failed;
1102 if ((def.sym->st_info&0xf) == STT_TLS)
1103 return __tls_get_addr((size_t []){def.dso->tls_id, def.sym->st_value});
1104 return def.dso->base + def.sym->st_value;
1108 sym = gnu_lookup(s, gh, p);
1111 sym = sysv_lookup(s, h, p);
1113 if (sym && (sym->st_info&0xf) == STT_TLS)
1114 return __tls_get_addr((size_t []){p->tls_id, sym->st_value});
1115 if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
1116 return p->base + sym->st_value;
1117 if (p->deps) for (i=0; p->deps[i]; i++) {
1118 if (p->deps[i]->ghashtab) {
1119 if (!gh) gh = gnu_hash(s);
1120 sym = gnu_lookup(s, gh, p->deps[i]);
1122 if (!h) h = sysv_hash(s);
1123 sym = sysv_lookup(s, h, p->deps[i]);
1125 if (sym && (sym->st_info&0xf) == STT_TLS)
1126 return __tls_get_addr((size_t []){p->deps[i]->tls_id, sym->st_value});
1127 if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
1128 return p->deps[i]->base + sym->st_value;
1132 snprintf(errbuf, sizeof errbuf, "Symbol not found: %s", s);
1136 int __dladdr(void *addr, Dl_info *info)
1146 pthread_rwlock_rdlock(&lock);
1147 for (p=head; p && (unsigned char *)addr-p->map>p->map_len; p=p->next);
1148 pthread_rwlock_unlock(&lock);
1153 strings = p->strings;
1155 nsym = p->hashtab[1];
1159 buckets = p->ghashtab + 4 + (p->ghashtab[2]*sizeof(size_t)/4);
1160 sym += p->ghashtab[1];
1161 for (i = 0; i < p->ghashtab[0]; i++) {
1162 if (buckets[i] > nsym)
1166 nsym -= p->ghashtab[1];
1167 hashval = buckets + p->ghashtab[0] + nsym;
1169 while (!(*hashval++ & 1));
1173 for (; nsym; nsym--, sym++) {
1174 if (sym->st_shndx && sym->st_value
1175 && (1<<(sym->st_info&0xf) & OK_TYPES)
1176 && (1<<(sym->st_info>>4) & OK_BINDS)) {
1177 void *symaddr = p->base + sym->st_value;
1178 if (symaddr > addr || symaddr < best)
1181 bestname = strings + sym->st_name;
1182 if (addr == symaddr)
1187 if (!best) return 0;
1189 info->dli_fname = p->name;
1190 info->dli_fbase = p->base;
1191 info->dli_sname = bestname;
1192 info->dli_saddr = best;
1197 void *__dlsym(void *restrict p, const char *restrict s, void *restrict ra)
1200 pthread_rwlock_rdlock(&lock);
1201 res = do_dlsym(p, s, ra);
1202 pthread_rwlock_unlock(&lock);
1206 int dl_iterate_phdr(int(*callback)(struct dl_phdr_info *info, size_t size, void *data), void *data)
1208 struct dso *current;
1209 struct dl_phdr_info info;
1211 for(current = head; current;) {
1212 info.dlpi_addr = (uintptr_t)current->base;
1213 info.dlpi_name = current->name;
1214 info.dlpi_phdr = current->phdr;
1215 info.dlpi_phnum = current->phnum;
1216 info.dlpi_adds = gencnt;
1218 info.dlpi_tls_modid = current->tls_id;
1219 info.dlpi_tls_data = current->tls_image;
1221 ret = (callback)(&info, sizeof (info), data);
1223 if (ret != 0) break;
1225 pthread_rwlock_rdlock(&lock);
1226 current = current->next;
1227 pthread_rwlock_unlock(&lock);
1232 void *dlopen(const char *file, int mode)
1236 void *__dlsym(void *restrict p, const char *restrict s, void *restrict ra)
1240 int __dladdr (void *addr, Dl_info *info)
1248 if (!errflag) return 0;
1253 int dlclose(void *p)