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 eh->e_phoff = sizeof *eh;
329 ph = (void *)((char *)buf + eh->e_phoff);
331 dso->phnum = eh->e_phnum;
332 for (i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
333 if (ph->p_type == PT_DYNAMIC)
335 if (ph->p_type == PT_TLS) {
336 tls_image = ph->p_vaddr;
337 dso->tls_align = ph->p_align;
338 dso->tls_len = ph->p_filesz;
339 dso->tls_size = ph->p_memsz;
341 if (ph->p_type != PT_LOAD) continue;
342 if (ph->p_vaddr < addr_min) {
343 addr_min = ph->p_vaddr;
344 off_start = ph->p_offset;
345 prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
346 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
347 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
349 if (ph->p_vaddr+ph->p_memsz > addr_max) {
350 addr_max = ph->p_vaddr+ph->p_memsz;
354 addr_max += PAGE_SIZE-1;
355 addr_max &= -PAGE_SIZE;
356 addr_min &= -PAGE_SIZE;
357 off_start &= -PAGE_SIZE;
358 map_len = addr_max - addr_min + off_start;
359 /* The first time, we map too much, possibly even more than
360 * the length of the file. This is okay because we will not
361 * use the invalid part; we just need to reserve the right
362 * amount of virtual address space to map over later. */
363 map = mmap((void *)addr_min, map_len, prot, MAP_PRIVATE, fd, off_start);
364 if (map==MAP_FAILED) return 0;
365 base = map - addr_min;
366 ph = (void *)((char *)buf + eh->e_phoff);
367 for (i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
368 if (ph->p_type != PT_LOAD) continue;
369 /* Reuse the existing mapping for the lowest-address LOAD */
370 if ((ph->p_vaddr & -PAGE_SIZE) == addr_min) continue;
371 this_min = ph->p_vaddr & -PAGE_SIZE;
372 this_max = ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE;
373 off_start = ph->p_offset & -PAGE_SIZE;
374 prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
375 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
376 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
377 if (mmap(base+this_min, this_max-this_min, prot, MAP_PRIVATE|MAP_FIXED, fd, off_start) == MAP_FAILED)
379 if (ph->p_memsz > ph->p_filesz) {
380 size_t brk = (size_t)base+ph->p_vaddr+ph->p_filesz;
381 size_t pgbrk = brk+PAGE_SIZE-1 & -PAGE_SIZE;
382 memset((void *)brk, 0, pgbrk-brk & PAGE_SIZE-1);
383 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)
387 for (i=0; ((size_t *)(base+dyn))[i]; i+=2)
388 if (((size_t *)(base+dyn))[i]==DT_TEXTREL) {
389 if (mprotect(map, map_len, PROT_READ|PROT_WRITE|PROT_EXEC) < 0)
393 if (!runtime) reclaim_gaps(base, (void *)((char *)buf + eh->e_phoff),
394 eh->e_phentsize, eh->e_phnum);
396 dso->map_len = map_len;
398 dso->dynv = (void *)(base+dyn);
399 if (dso->tls_size) dso->tls_image = (void *)(base+tls_image);
402 munmap(map, map_len);
406 static int path_open(const char *name, const char *s, char *buf, size_t buf_size)
411 s += strspn(s, ":\n");
412 l = strcspn(s, ":\n");
413 if (l-1 >= INT_MAX) return -1;
414 if (snprintf(buf, buf_size, "%.*s/%s", (int)l, s, name) >= buf_size)
416 if ((fd = open(buf, O_RDONLY|O_CLOEXEC))>=0) return fd;
421 static void decode_dyn(struct dso *p)
423 size_t dyn[DYN_CNT] = {0};
424 decode_vec(p->dynv, dyn, DYN_CNT);
425 p->syms = (void *)(p->base + dyn[DT_SYMTAB]);
426 p->strings = (void *)(p->base + dyn[DT_STRTAB]);
427 if (dyn[0]&(1<<DT_HASH))
428 p->hashtab = (void *)(p->base + dyn[DT_HASH]);
429 if (search_vec(p->dynv, dyn, DT_GNU_HASH))
430 p->ghashtab = (void *)(p->base + *dyn);
433 static struct dso *load_library(const char *name)
435 char buf[2*NAME_MAX+2];
436 const char *pathname;
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 (getdelim(&sys_path, (size_t[1]){0}, 0, f) <= 0) {
488 if (!sys_path) sys_path = "/lib:/usr/local/lib:/usr/lib";
489 fd = path_open(name, sys_path, buf, sizeof buf);
493 if (fd < 0) return 0;
494 if (fstat(fd, &st) < 0) {
498 for (p=head->next; p; p=p->next) {
499 if (p->dev == st.st_dev && p->ino == st.st_ino) {
500 /* If this library was previously loaded with a
501 * pathname but a search found the same inode,
502 * setup its shortname so it can be found by name. */
503 if (!p->shortname && pathname != name)
504 p->shortname = strrchr(p->name, '/')+1;
510 map = noload ? 0 : map_library(fd, &temp_dso);
514 /* Allocate storage for the new DSO. When there is TLS, this
515 * storage must include a reservation for all pre-existing
516 * threads to obtain copies of both the new TLS, and an
517 * extended DTV capable of storing an additional slot for
518 * the newly-loaded DSO. */
519 alloc_size = sizeof *p + strlen(pathname) + 1;
520 if (runtime && temp_dso.tls_image) {
521 size_t per_th = temp_dso.tls_size + temp_dso.tls_align
522 + sizeof(void *) * (tls_cnt+3);
523 n_th = libc.threads_minus_1 + 1;
524 if (n_th > SSIZE_MAX / per_th) alloc_size = SIZE_MAX;
525 else alloc_size += n_th * per_th;
527 p = calloc(1, alloc_size);
529 munmap(map, temp_dso.map_len);
532 memcpy(p, &temp_dso, sizeof temp_dso);
538 strcpy(p->name, pathname);
539 /* Add a shortname only if name arg was not an explicit pathname. */
540 if (pathname != name) p->shortname = strrchr(p->name, '/')+1;
542 if (runtime && !__pthread_self_init()) {
543 munmap(map, p->map_len);
547 p->tls_id = ++tls_cnt;
548 tls_align = MAXP2(tls_align, p->tls_align);
550 p->tls_offset = tls_offset + ( (tls_align-1) &
551 -(tls_offset + (uintptr_t)p->tls_image) );
552 tls_offset += p->tls_size;
554 tls_offset += p->tls_size + p->tls_align - 1;
555 tls_offset -= (tls_offset + (uintptr_t)p->tls_image)
557 p->tls_offset = tls_offset;
559 p->new_dtv = (void *)(-sizeof(size_t) &
560 (uintptr_t)(p->name+strlen(p->name)+sizeof(size_t)));
561 p->new_tls = (void *)(p->new_dtv + n_th*(tls_cnt+1));
568 if (ldd_mode) dprintf(1, "\t%s => %s (%p)\n", name, pathname, p->base);
573 static void load_deps(struct dso *p)
576 struct dso ***deps = &p->deps, **tmp, *dep;
577 for (; p; p=p->next) {
578 for (i=0; p->dynv[i]; i+=2) {
579 if (p->dynv[i] != DT_RPATH) continue;
580 r_path = (void *)(p->strings + p->dynv[i+1]);
582 for (i=0; p->dynv[i]; i+=2) {
583 if (p->dynv[i] != DT_NEEDED) continue;
584 dep = load_library(p->strings + p->dynv[i+1]);
586 snprintf(errbuf, sizeof errbuf,
587 "Error loading shared library %s: %m (needed by %s)",
588 p->strings + p->dynv[i+1], p->name);
589 if (runtime) longjmp(rtld_fail, 1);
590 dprintf(2, "%s\n", errbuf);
595 tmp = realloc(*deps, sizeof(*tmp)*(ndeps+2));
596 if (!tmp) longjmp(rtld_fail, 1);
606 static void load_preload(char *s)
611 for ( ; *s && isspace(*s); s++);
612 for (z=s; *z && !isspace(*z); z++);
620 static void make_global(struct dso *p)
622 for (; p; p=p->next) p->global = 1;
625 static void reloc_all(struct dso *p)
627 size_t dyn[DYN_CNT] = {0};
628 for (; p; p=p->next) {
629 if (p->relocated) continue;
630 decode_vec(p->dynv, dyn, DYN_CNT);
631 #ifdef NEED_ARCH_RELOCS
632 do_arch_relocs(p, head);
634 do_relocs(p, (void *)(p->base+dyn[DT_JMPREL]), dyn[DT_PLTRELSZ],
635 2+(dyn[DT_PLTREL]==DT_RELA));
636 do_relocs(p, (void *)(p->base+dyn[DT_REL]), dyn[DT_RELSZ], 2);
637 do_relocs(p, (void *)(p->base+dyn[DT_RELA]), dyn[DT_RELASZ], 3);
642 static size_t find_dyn(Phdr *ph, size_t cnt, size_t stride)
644 for (; cnt--; ph = (void *)((char *)ph + stride))
645 if (ph->p_type == PT_DYNAMIC)
650 static void find_map_range(Phdr *ph, size_t cnt, size_t stride, struct dso *p)
652 size_t min_addr = -1, max_addr = 0;
653 for (; cnt--; ph = (void *)((char *)ph + stride)) {
654 if (ph->p_type != PT_LOAD) continue;
655 if (ph->p_vaddr < min_addr)
656 min_addr = ph->p_vaddr;
657 if (ph->p_vaddr+ph->p_memsz > max_addr)
658 max_addr = ph->p_vaddr+ph->p_memsz;
660 min_addr &= -PAGE_SIZE;
661 max_addr = (max_addr + PAGE_SIZE-1) & -PAGE_SIZE;
662 p->map = p->base + min_addr;
663 p->map_len = max_addr - min_addr;
666 static void do_fini()
669 size_t dyn[DYN_CNT] = {0};
670 for (p=fini_head; p; p=p->fini_next) {
671 if (!p->constructed) continue;
672 decode_vec(p->dynv, dyn, DYN_CNT);
673 ((void (*)(void))(p->base + dyn[DT_FINI]))();
677 static void do_init_fini(struct dso *p)
679 size_t dyn[DYN_CNT] = {0};
680 int need_locking = libc.threads_minus_1;
681 /* Allow recursive calls that arise when a library calls
682 * dlopen from one of its constructors, but block any
683 * other threads until all ctors have finished. */
684 if (need_locking) pthread_mutex_lock(&init_fini_lock);
685 for (; p; p=p->prev) {
686 if (p->constructed) continue;
688 decode_vec(p->dynv, dyn, DYN_CNT);
689 if (dyn[0] & (1<<DT_FINI)) {
690 p->fini_next = fini_head;
693 if (dyn[0] & (1<<DT_INIT))
694 ((void (*)(void))(p->base + dyn[DT_INIT]))();
695 if (!need_locking && libc.threads_minus_1) {
697 pthread_mutex_lock(&init_fini_lock);
700 if (need_locking) pthread_mutex_unlock(&init_fini_lock);
703 void _dl_debug_state(void)
707 void *__copy_tls(unsigned char *mem)
712 if (!tls_cnt) return mem;
714 void **dtv = (void *)mem;
715 dtv[0] = (void *)tls_cnt;
718 mem += sizeof(void *) * (tls_cnt+1);
719 mem += -((uintptr_t)mem + sizeof(struct pthread)) & (tls_align-1);
721 mem += sizeof(struct pthread);
723 for (p=head; p; p=p->next) {
724 if (!p->tls_id) continue;
725 dtv[p->tls_id] = mem + p->tls_offset;
726 memcpy(dtv[p->tls_id], p->tls_image, p->tls_len);
729 mem += libc.tls_size - sizeof(struct pthread);
730 mem -= (uintptr_t)mem & (tls_align-1);
733 for (p=head; p; p=p->next) {
734 if (!p->tls_id) continue;
735 dtv[p->tls_id] = mem - p->tls_offset;
736 memcpy(dtv[p->tls_id], p->tls_image, p->tls_len);
743 void *__tls_get_addr(size_t *v)
745 pthread_t self = __pthread_self();
746 if (v[0]<=(size_t)self->dtv[0] && self->dtv[v[0]])
747 return (char *)self->dtv[v[0]]+v[1];
749 /* Block signals to make accessing new TLS async-signal-safe */
751 pthread_sigmask(SIG_BLOCK, SIGALL_SET, &set);
752 if (v[0]<=(size_t)self->dtv[0] && self->dtv[v[0]]) {
753 pthread_sigmask(SIG_SETMASK, &set, 0);
754 return (char *)self->dtv[v[0]]+v[1];
757 /* This is safe without any locks held because, if the caller
758 * is able to request the Nth entry of the DTV, the DSO list
759 * must be valid at least that far out and it was synchronized
760 * at program startup or by an already-completed call to dlopen. */
762 for (p=head; p->tls_id != v[0]; p=p->next);
764 /* Get new DTV space from new DSO if needed */
765 if (v[0] > (size_t)self->dtv[0]) {
766 void **newdtv = p->new_dtv +
767 (v[0]+1)*sizeof(void *)*a_fetch_add(&p->new_dtv_idx,1);
768 memcpy(newdtv, self->dtv,
769 ((size_t)self->dtv[0]+1) * sizeof(void *));
770 newdtv[0] = (void *)v[0];
774 /* Get new TLS memory from new DSO */
775 unsigned char *mem = p->new_tls +
776 (p->tls_size + p->tls_align) * a_fetch_add(&p->new_tls_idx,1);
777 mem += ((uintptr_t)p->tls_image - (uintptr_t)mem) & (p->tls_align-1);
778 self->dtv[v[0]] = mem;
779 memcpy(mem, p->tls_image, p->tls_len);
780 pthread_sigmask(SIG_SETMASK, &set, 0);
784 static void update_tls_size()
786 libc.tls_size = ALIGN(
787 (1+tls_cnt) * sizeof(void *) +
789 sizeof(struct pthread) +
794 void *__dynlink(int argc, char **argv)
796 size_t aux[AUX_CNT] = {0};
800 static struct dso builtin_dsos[3];
801 struct dso *const app = builtin_dsos+0;
802 struct dso *const lib = builtin_dsos+1;
803 struct dso *const vdso = builtin_dsos+2;
808 /* Find aux vector just past environ[] */
809 for (i=argc+1; argv[i]; i++)
810 if (!memcmp(argv[i], "LD_LIBRARY_PATH=", 16))
811 env_path = argv[i]+16;
812 else if (!memcmp(argv[i], "LD_PRELOAD=", 11))
813 env_preload = argv[i]+11;
814 auxv = (void *)(argv+i+1);
816 decode_vec(auxv, aux, AUX_CNT);
818 /* Only trust user/env if kernel says we're not suid/sgid */
819 if ((aux[0]&0x7800)!=0x7800 || aux[AT_UID]!=aux[AT_EUID]
820 || aux[AT_GID]!=aux[AT_EGID] || aux[AT_SECURE]) {
825 /* If the dynamic linker was invoked as a program itself, AT_BASE
826 * will not be set. In that case, we assume the base address is
827 * the start of the page containing the PHDRs; I don't know any
828 * better approach... */
830 aux[AT_BASE] = aux[AT_PHDR] & -PAGE_SIZE;
831 aux[AT_PHDR] = aux[AT_PHENT] = aux[AT_PHNUM] = 0;
834 /* The dynamic linker load address is passed by the kernel
835 * in the AUX vector, so this is easy. */
836 lib->base = (void *)aux[AT_BASE];
837 lib->name = lib->shortname = "libc.so";
839 ehdr = (void *)lib->base;
840 lib->phnum = ehdr->e_phnum;
841 lib->phdr = (void *)(aux[AT_BASE]+ehdr->e_phoff);
842 find_map_range(lib->phdr, ehdr->e_phnum, ehdr->e_phentsize, lib);
843 lib->dynv = (void *)(lib->base + find_dyn(lib->phdr,
844 ehdr->e_phnum, ehdr->e_phentsize));
848 size_t interp_off = 0;
849 size_t tls_image = 0;
850 /* Find load address of the main program, via AT_PHDR vs PT_PHDR. */
851 app->phdr = phdr = (void *)aux[AT_PHDR];
852 app->phnum = aux[AT_PHNUM];
853 for (i=aux[AT_PHNUM]; i; i--, phdr=(void *)((char *)phdr + aux[AT_PHENT])) {
854 if (phdr->p_type == PT_PHDR)
855 app->base = (void *)(aux[AT_PHDR] - phdr->p_vaddr);
856 else if (phdr->p_type == PT_INTERP)
857 interp_off = (size_t)phdr->p_vaddr;
858 else if (phdr->p_type == PT_TLS) {
859 tls_image = phdr->p_vaddr;
860 app->tls_len = phdr->p_filesz;
861 app->tls_size = phdr->p_memsz;
862 app->tls_align = phdr->p_align;
865 if (app->tls_size) app->tls_image = (char *)app->base + tls_image;
866 if (interp_off) lib->name = (char *)app->base + interp_off;
868 app->dynv = (void *)(app->base + find_dyn(
869 (void *)aux[AT_PHDR], aux[AT_PHNUM], aux[AT_PHENT]));
870 find_map_range((void *)aux[AT_PHDR],
871 aux[AT_PHNUM], aux[AT_PHENT], app);
874 char *ldname = argv[0];
875 size_t l = strlen(ldname);
876 if (l >= 3 && !strcmp(ldname+l-3, "ldd")) ldd_mode = 1;
877 *argv++ = (void *)-1;
878 if (argv[0] && !strcmp(argv[0], "--")) *argv++ = (void *)-1;
880 dprintf(2, "musl libc/dynamic program loader\n");
881 dprintf(2, "usage: %s pathname%s\n", ldname,
882 ldd_mode ? "" : " [args]");
885 fd = open(argv[0], O_RDONLY);
887 dprintf(2, "%s: cannot load %s: %s\n", ldname, argv[0], strerror(errno));
891 ehdr = (void *)map_library(fd, app);
893 dprintf(2, "%s: %s: Not a valid dynamic program\n", ldname, argv[0]);
900 app->phnum = ehdr->e_phnum;
901 app->phdr = (void *)(app->base + ehdr->e_phoff);
902 aux[AT_ENTRY] = ehdr->e_entry;
905 app->tls_id = tls_cnt = 1;
908 tls_offset = app->tls_size
909 + ( -((uintptr_t)app->tls_image + app->tls_size)
910 & (app->tls_align-1) );
912 tls_offset = app->tls_offset = app->tls_size
913 + ( -((uintptr_t)app->tls_image + app->tls_size)
914 & (app->tls_align-1) );
916 tls_align = MAXP2(tls_align, app->tls_align);
919 app->constructed = 1;
922 /* Attach to vdso, if provided by the kernel */
923 if (search_vec(auxv, &vdso_base, AT_SYSINFO_EHDR)) {
924 ehdr = (void *)vdso_base;
925 vdso->phdr = phdr = (void *)(vdso_base + ehdr->e_phoff);
926 vdso->phnum = ehdr->e_phnum;
927 for (i=ehdr->e_phnum; i; i--, phdr=(void *)((char *)phdr + ehdr->e_phentsize)) {
928 if (phdr->p_type == PT_DYNAMIC)
929 vdso->dynv = (void *)(vdso_base + phdr->p_offset);
930 if (phdr->p_type == PT_LOAD)
931 vdso->base = (void *)(vdso_base - phdr->p_vaddr + phdr->p_offset);
934 vdso->shortname = "linux-gate.so.1";
941 /* Initial dso chain consists only of the app. We temporarily
942 * append the dynamic linker/libc so we can relocate it, then
943 * restore the initial chain in preparation for loading third
944 * party libraries (preload/needed). */
951 /* PAST THIS POINT, ALL LIBC INTERFACES ARE FULLY USABLE. */
953 /* Donate unused parts of app and library mapping to malloc */
954 reclaim_gaps(app->base, (void *)aux[AT_PHDR], aux[AT_PHENT], aux[AT_PHNUM]);
955 ehdr = (void *)lib->base;
956 reclaim_gaps(lib->base, (void *)(lib->base+ehdr->e_phoff),
957 ehdr->e_phentsize, ehdr->e_phnum);
959 /* Load preload/needed libraries, add their symbols to the global
960 * namespace, and perform all remaining relocations. The main
961 * program must be relocated LAST since it may contain copy
962 * relocations which depend on libraries' relocations. */
963 if (env_preload) load_preload(env_preload);
967 reloc_all(app->next);
972 void *mem = mmap(0, libc.tls_size, PROT_READ|PROT_WRITE,
973 MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
974 if (mem==MAP_FAILED ||
975 !__install_initial_tls(__copy_tls(mem))) {
976 dprintf(2, "%s: Error getting %zu bytes thread-local storage: %m\n",
977 argv[0], libc.tls_size);
982 if (ldso_fail) _exit(127);
983 if (ldd_mode) _exit(0);
985 /* Switch to runtime mode: any further failures in the dynamic
986 * linker are a reportable failure rather than a fatal startup
987 * error. If the dynamic loader (dlopen) will not be used, free
988 * all memory used by the dynamic linker. */
991 #ifndef DYNAMIC_IS_RO
992 for (i=0; app->dynv[i]; i+=2)
993 if (app->dynv[i]==DT_DEBUG)
994 app->dynv[i+1] = (size_t)&debug;
997 debug.bp = _dl_debug_state;
999 debug.base = lib->base;
1003 if (ssp_used) __init_ssp((void *)aux[AT_RANDOM]);
1006 return (void *)aux[AT_ENTRY];
1009 void __init_ldso_ctors(void)
1015 void *dlopen(const char *file, int mode)
1017 struct dso *volatile p, *orig_tail, *next;
1018 size_t orig_tls_cnt, orig_tls_offset, orig_tls_align;
1022 if (!file) return head;
1024 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
1025 pthread_rwlock_wrlock(&lock);
1029 orig_tls_cnt = tls_cnt;
1030 orig_tls_offset = tls_offset;
1031 orig_tls_align = tls_align;
1033 noload = mode & RTLD_NOLOAD;
1035 if (setjmp(rtld_fail)) {
1036 /* Clean up anything new that was (partially) loaded */
1037 if (p && p->deps) for (i=0; p->deps[i]; i++)
1038 if (p->deps[i]->global < 0)
1039 p->deps[i]->global = 0;
1040 for (p=orig_tail->next; p; p=next) {
1042 munmap(p->map, p->map_len);
1046 tls_cnt = orig_tls_cnt;
1047 tls_offset = orig_tls_offset;
1048 tls_align = orig_tls_align;
1054 } else p = load_library(file);
1057 snprintf(errbuf, sizeof errbuf, noload ?
1058 "Library %s is not already loaded" :
1059 "Error loading shared library %s: %m",
1065 /* First load handling */
1068 if (p->deps) for (i=0; p->deps[i]; i++)
1069 if (!p->deps[i]->global)
1070 p->deps[i]->global = -1;
1071 if (!p->global) p->global = -1;
1073 if (p->deps) for (i=0; p->deps[i]; i++)
1074 if (p->deps[i]->global < 0)
1075 p->deps[i]->global = 0;
1076 if (p->global < 0) p->global = 0;
1079 if (mode & RTLD_GLOBAL) {
1080 if (p->deps) for (i=0; p->deps[i]; i++)
1081 p->deps[i]->global = 1;
1087 if (ssp_used) __init_ssp(libc.auxv);
1094 pthread_rwlock_unlock(&lock);
1095 if (p) do_init_fini(orig_tail);
1096 pthread_setcancelstate(cs, 0);
1100 static int invalid_dso_handle(void *h)
1103 for (p=head; p; p=p->next) if (h==p) return 0;
1104 snprintf(errbuf, sizeof errbuf, "Invalid library handle %p", (void *)h);
1109 static void *do_dlsym(struct dso *p, const char *s, void *ra)
1112 uint32_t h = 0, gh = 0;
1114 if (p == head || p == RTLD_DEFAULT || p == RTLD_NEXT) {
1115 if (p == RTLD_DEFAULT) {
1117 } else if (p == RTLD_NEXT) {
1118 for (p=head; p && (unsigned char *)ra-p->map>p->map_len; p=p->next);
1122 struct symdef def = find_sym(p, s, 0);
1123 if (!def.sym) goto failed;
1124 if ((def.sym->st_info&0xf) == STT_TLS)
1125 return __tls_get_addr((size_t []){def.dso->tls_id, def.sym->st_value});
1126 return def.dso->base + def.sym->st_value;
1128 if (p != RTLD_DEFAULT && p != RTLD_NEXT && invalid_dso_handle(p))
1132 sym = gnu_lookup(s, gh, p);
1135 sym = sysv_lookup(s, h, p);
1137 if (sym && (sym->st_info&0xf) == STT_TLS)
1138 return __tls_get_addr((size_t []){p->tls_id, sym->st_value});
1139 if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
1140 return p->base + sym->st_value;
1141 if (p->deps) for (i=0; p->deps[i]; i++) {
1142 if (p->deps[i]->ghashtab) {
1143 if (!gh) gh = gnu_hash(s);
1144 sym = gnu_lookup(s, gh, p->deps[i]);
1146 if (!h) h = sysv_hash(s);
1147 sym = sysv_lookup(s, h, p->deps[i]);
1149 if (sym && (sym->st_info&0xf) == STT_TLS)
1150 return __tls_get_addr((size_t []){p->deps[i]->tls_id, sym->st_value});
1151 if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
1152 return p->deps[i]->base + sym->st_value;
1156 snprintf(errbuf, sizeof errbuf, "Symbol not found: %s", s);
1160 int __dladdr(void *addr, Dl_info *info)
1170 pthread_rwlock_rdlock(&lock);
1171 for (p=head; p && (unsigned char *)addr-p->map>p->map_len; p=p->next);
1172 pthread_rwlock_unlock(&lock);
1177 strings = p->strings;
1179 nsym = p->hashtab[1];
1183 buckets = p->ghashtab + 4 + (p->ghashtab[2]*sizeof(size_t)/4);
1184 sym += p->ghashtab[1];
1185 for (i = 0; i < p->ghashtab[0]; i++) {
1186 if (buckets[i] > nsym)
1190 nsym -= p->ghashtab[1];
1191 hashval = buckets + p->ghashtab[0] + nsym;
1193 while (!(*hashval++ & 1));
1197 for (; nsym; nsym--, sym++) {
1199 && (1<<(sym->st_info&0xf) & OK_TYPES)
1200 && (1<<(sym->st_info>>4) & OK_BINDS)) {
1201 void *symaddr = p->base + sym->st_value;
1202 if (symaddr > addr || symaddr < best)
1205 bestname = strings + sym->st_name;
1206 if (addr == symaddr)
1211 if (!best) return 0;
1213 info->dli_fname = p->name;
1214 info->dli_fbase = p->base;
1215 info->dli_sname = bestname;
1216 info->dli_saddr = best;
1221 void *__dlsym(void *restrict p, const char *restrict s, void *restrict ra)
1224 pthread_rwlock_rdlock(&lock);
1225 res = do_dlsym(p, s, ra);
1226 pthread_rwlock_unlock(&lock);
1230 int dl_iterate_phdr(int(*callback)(struct dl_phdr_info *info, size_t size, void *data), void *data)
1232 struct dso *current;
1233 struct dl_phdr_info info;
1235 for(current = head; current;) {
1236 info.dlpi_addr = (uintptr_t)current->base;
1237 info.dlpi_name = current->name;
1238 info.dlpi_phdr = current->phdr;
1239 info.dlpi_phnum = current->phnum;
1240 info.dlpi_adds = gencnt;
1242 info.dlpi_tls_modid = current->tls_id;
1243 info.dlpi_tls_data = current->tls_image;
1245 ret = (callback)(&info, sizeof (info), data);
1247 if (ret != 0) break;
1249 pthread_rwlock_rdlock(&lock);
1250 current = current->next;
1251 pthread_rwlock_unlock(&lock);
1256 static int invalid_dso_handle(void *h)
1258 snprintf(errbuf, sizeof errbuf, "Invalid library handle %p", (void *)h);
1262 void *dlopen(const char *file, int mode)
1266 void *__dlsym(void *restrict p, const char *restrict s, void *restrict ra)
1270 int __dladdr (void *addr, Dl_info *info)
1278 if (!errflag) return 0;
1283 int dlclose(void *p)
1285 return invalid_dso_handle(p);