20 #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)
55 struct dso *next, *prev;
71 size_t tls_len, tls_size, tls_align, tls_id, tls_offset;
73 unsigned char *new_tls;
74 int new_dtv_idx, new_tls_idx;
75 struct dso *fini_next;
87 void __init_ssp(size_t *);
88 void *__install_initial_tls(void *);
90 static struct dso *head, *tail, *libc, *fini_head;
91 static char *env_path, *sys_path, *r_path;
96 static jmp_buf rtld_fail;
97 static pthread_rwlock_t lock;
98 static struct debug debug;
100 static size_t tls_cnt, tls_size;
101 static pthread_mutex_t init_fini_lock = { ._m_type = PTHREAD_MUTEX_RECURSIVE };
103 struct debug *_dl_debug_addr = &debug;
108 static void decode_vec(size_t *v, size_t *a, size_t cnt)
110 memset(a, 0, cnt*sizeof(size_t));
111 for (; v[0]; v+=2) if (v[0]<cnt) {
117 static int search_vec(size_t *v, size_t *r, size_t key)
119 for (; v[0]!=key; v+=2)
125 static uint32_t sysv_hash(const char *s0)
127 const unsigned char *s = (void *)s0;
133 return h & 0xfffffff;
136 static uint32_t gnu_hash(const char *s0)
138 const unsigned char *s = (void *)s0;
139 uint_fast32_t h = 5381;
145 static Sym *sysv_lookup(const char *s, uint32_t h, struct dso *dso)
148 Sym *syms = dso->syms;
149 uint32_t *hashtab = dso->hashtab;
150 char *strings = dso->strings;
151 for (i=hashtab[2+h%hashtab[0]]; i; i=hashtab[2+hashtab[0]+i]) {
152 if (!strcmp(s, strings+syms[i].st_name))
158 static Sym *gnu_lookup(const char *s, uint32_t h1, struct dso *dso)
162 uint32_t *hashtab = dso->ghashtab;
163 uint32_t nbuckets = hashtab[0];
164 uint32_t *buckets = hashtab + 4 + hashtab[2]*(sizeof(size_t)/4);
167 uint32_t n = buckets[h1 % nbuckets];
171 strings = dso->strings;
173 hashval = buckets + nbuckets + (n - hashtab[1]);
175 for (h1 |= 1; ; sym++) {
177 if ((h1 == (h2|1)) && !strcmp(s, strings + sym->st_name))
185 #define OK_TYPES (1<<STT_NOTYPE | 1<<STT_OBJECT | 1<<STT_FUNC | 1<<STT_COMMON | 1<<STT_TLS)
186 #define OK_BINDS (1<<STB_GLOBAL | 1<<STB_WEAK)
188 static struct symdef find_sym(struct dso *dso, const char *s, int need_def)
190 uint32_t h = 0, gh = 0;
191 struct symdef def = {0};
194 if (gh == 0x1f4039c9 && !strcmp(s, "__stack_chk_fail")) ssp_used = 1;
197 if (h == 0x595a4cc && !strcmp(s, "__stack_chk_fail")) ssp_used = 1;
199 for (; dso; dso=dso->next) {
201 if (!dso->global) continue;
203 if (!gh) gh = gnu_hash(s);
204 sym = gnu_lookup(s, gh, dso);
206 if (!h) h = sysv_hash(s);
207 sym = sysv_lookup(s, h, dso);
209 if (sym && (!need_def || sym->st_shndx) && sym->st_value
210 && (1<<(sym->st_info&0xf) & OK_TYPES)
211 && (1<<(sym->st_info>>4) & OK_BINDS)) {
212 if (def.sym && sym->st_info>>4 == STB_WEAK) continue;
215 if (sym->st_info>>4 == STB_GLOBAL) break;
221 static void do_relocs(struct dso *dso, size_t *rel, size_t rel_size, size_t stride)
223 unsigned char *base = dso->base;
224 Sym *syms = dso->syms;
225 char *strings = dso->strings;
233 for (; rel_size; rel+=stride, rel_size-=stride*sizeof(size_t)) {
234 type = R_TYPE(rel[1]);
235 sym_index = R_SYM(rel[1]);
237 sym = syms + sym_index;
238 name = strings + sym->st_name;
239 ctx = IS_COPY(type) ? head->next : head;
240 def = find_sym(ctx, name, IS_PLT(type));
241 if (!def.sym && sym->st_info>>4 != STB_WEAK) {
242 snprintf(errbuf, sizeof errbuf,
243 "Error relocating %s: %s: symbol not found",
245 if (runtime) longjmp(rtld_fail, 1);
246 dprintf(2, "%s\n", errbuf);
255 do_single_reloc(dso, base, (void *)(base + rel[0]), type,
256 stride>2 ? rel[2] : 0, sym, sym?sym->st_size:0, def,
257 def.sym?(size_t)(def.dso->base+def.sym->st_value):0);
261 /* A huge hack: to make up for the wastefulness of shared libraries
262 * needing at least a page of dirty memory even if they have no global
263 * data, we reclaim the gaps at the beginning and end of writable maps
264 * and "donate" them to the heap by setting up minimal malloc
265 * structures and then freeing them. */
267 static void reclaim(unsigned char *base, size_t start, size_t end)
270 start = start + 6*sizeof(size_t)-1 & -4*sizeof(size_t);
271 end = (end & -4*sizeof(size_t)) - 2*sizeof(size_t);
272 if (start>end || end-start < 4*sizeof(size_t)) return;
273 a = (size_t *)(base + start);
274 z = (size_t *)(base + end);
276 a[-1] = z[0] = end-start + 2*sizeof(size_t) | 1;
281 static void reclaim_gaps(unsigned char *base, Phdr *ph, size_t phent, size_t phcnt)
283 for (; phcnt--; ph=(void *)((char *)ph+phent)) {
284 if (ph->p_type!=PT_LOAD) continue;
285 if ((ph->p_flags&(PF_R|PF_W))!=(PF_R|PF_W)) continue;
286 reclaim(base, ph->p_vaddr & -PAGE_SIZE, ph->p_vaddr);
287 reclaim(base, ph->p_vaddr+ph->p_memsz,
288 ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE);
292 static void *map_library(int fd, struct dso *dso)
294 Ehdr buf[(896+sizeof(Ehdr))/sizeof(Ehdr)];
296 size_t addr_min=SIZE_MAX, addr_max=0, map_len;
297 size_t this_min, this_max;
302 unsigned char *map, *base;
307 ssize_t l = read(fd, buf, sizeof buf);
308 if (l<sizeof *eh) return 0;
310 phsize = eh->e_phentsize * eh->e_phnum;
311 if (phsize + sizeof *eh > l) return 0;
312 if (eh->e_phoff + phsize > l) {
313 l = pread(fd, buf+1, phsize, eh->e_phoff);
314 if (l != phsize) return 0;
315 eh->e_phoff = sizeof *eh;
317 ph = (void *)((char *)buf + eh->e_phoff);
318 for (i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
319 if (ph->p_type == PT_DYNAMIC)
321 if (ph->p_type == PT_TLS) {
322 tls_image = ph->p_vaddr;
323 dso->tls_align = ph->p_align;
324 dso->tls_len = ph->p_filesz;
325 dso->tls_size = ph->p_memsz;
327 if (ph->p_type != PT_LOAD) continue;
328 if (ph->p_vaddr < addr_min) {
329 addr_min = ph->p_vaddr;
330 off_start = ph->p_offset;
331 prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
332 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
333 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
335 if (ph->p_vaddr+ph->p_memsz > addr_max) {
336 addr_max = ph->p_vaddr+ph->p_memsz;
340 addr_max += PAGE_SIZE-1;
341 addr_max &= -PAGE_SIZE;
342 addr_min &= -PAGE_SIZE;
343 off_start &= -PAGE_SIZE;
344 map_len = addr_max - addr_min + off_start;
345 /* The first time, we map too much, possibly even more than
346 * the length of the file. This is okay because we will not
347 * use the invalid part; we just need to reserve the right
348 * amount of virtual address space to map over later. */
349 map = mmap((void *)addr_min, map_len, prot, MAP_PRIVATE, fd, off_start);
350 if (map==MAP_FAILED) return 0;
351 base = map - addr_min;
352 ph = (void *)((char *)buf + eh->e_phoff);
353 for (i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
354 if (ph->p_type != PT_LOAD) continue;
355 /* Reuse the existing mapping for the lowest-address LOAD */
356 if ((ph->p_vaddr & -PAGE_SIZE) == addr_min) continue;
357 this_min = ph->p_vaddr & -PAGE_SIZE;
358 this_max = ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE;
359 off_start = ph->p_offset & -PAGE_SIZE;
360 prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
361 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
362 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
363 if (mmap(base+this_min, this_max-this_min, prot, MAP_PRIVATE|MAP_FIXED, fd, off_start) == MAP_FAILED)
365 if (ph->p_memsz > ph->p_filesz) {
366 size_t brk = (size_t)base+ph->p_vaddr+ph->p_filesz;
367 size_t pgbrk = brk+PAGE_SIZE-1 & -PAGE_SIZE;
368 memset((void *)brk, 0, pgbrk-brk & PAGE_SIZE-1);
369 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)
373 for (i=0; ((size_t *)(base+dyn))[i]; i+=2)
374 if (((size_t *)(base+dyn))[i]==DT_TEXTREL) {
375 if (mprotect(map, map_len, PROT_READ|PROT_WRITE|PROT_EXEC) < 0)
379 if (!runtime) reclaim_gaps(base, (void *)((char *)buf + eh->e_phoff),
380 eh->e_phentsize, eh->e_phnum);
382 dso->map_len = map_len;
384 dso->dynv = (void *)(base+dyn);
385 if (dso->tls_size) dso->tls_image = (void *)(base+tls_image);
388 munmap(map, map_len);
392 static int path_open(const char *name, const char *search, char *buf, size_t buf_size)
394 const char *s=search, *z;
400 l = z ? z-s : strlen(s);
401 snprintf(buf, buf_size, "%.*s/%s", l, s, name);
402 if ((fd = open(buf, O_RDONLY|O_CLOEXEC))>=0) return fd;
407 static void decode_dyn(struct dso *p)
409 size_t dyn[DYN_CNT] = {0};
410 decode_vec(p->dynv, dyn, DYN_CNT);
411 p->syms = (void *)(p->base + dyn[DT_SYMTAB]);
412 p->strings = (void *)(p->base + dyn[DT_STRTAB]);
413 if (dyn[0]&(1<<DT_HASH))
414 p->hashtab = (void *)(p->base + dyn[DT_HASH]);
415 if (search_vec(p->dynv, dyn, DT_GNU_HASH))
416 p->ghashtab = (void *)(p->base + *dyn);
419 static struct dso *load_library(const char *name)
421 char buf[2*NAME_MAX+2];
422 const char *pathname;
423 unsigned char *base, *map;
424 size_t dyno, map_len;
425 struct dso *p, temp_dso = {0};
431 /* Catch and block attempts to reload the implementation itself */
432 if (name[0]=='l' && name[1]=='i' && name[2]=='b') {
433 static const char *rp, reserved[] =
434 "c\0pthread\0rt\0m\0dl\0util\0xnet\0";
435 char *z = strchr(name, '.');
438 for (rp=reserved; *rp && memcmp(name+3, rp, l-3); rp+=strlen(rp)+1);
443 tail = libc->next ? libc->next : libc;
449 if (strchr(name, '/')) {
451 fd = open(name, O_RDONLY|O_CLOEXEC);
453 /* Search for the name to see if it's already loaded */
454 for (p=head->next; p; p=p->next) {
455 if (p->shortname && !strcmp(p->shortname, name)) {
460 if (strlen(name) > NAME_MAX) return 0;
462 if (r_path) fd = path_open(name, r_path, buf, sizeof buf);
463 if (fd < 0 && env_path) fd = path_open(name, env_path, buf, sizeof buf);
466 FILE *f = fopen(ETC_LDSO_PATH, "rbe");
468 if (getline(&sys_path, (size_t[1]){0}, f) > 0)
469 sys_path[strlen(sys_path)-1]=0;
473 if (sys_path) fd = path_open(name, sys_path, buf, sizeof buf);
474 else fd = path_open(name, "/lib:/usr/local/lib:/usr/lib", buf, sizeof buf);
478 if (fd < 0) return 0;
479 if (fstat(fd, &st) < 0) {
483 for (p=head->next; p; p=p->next) {
484 if (p->dev == st.st_dev && p->ino == st.st_ino) {
485 /* If this library was previously loaded with a
486 * pathname but a search found the same inode,
487 * setup its shortname so it can be found by name. */
488 if (!p->shortname && pathname != name)
489 p->shortname = strrchr(p->name, '/')+1;
495 map = map_library(fd, &temp_dso);
499 /* Allocate storage for the new DSO. When there is TLS, this
500 * storage must include a reservation for all pre-existing
501 * threads to obtain copies of both the new TLS, and an
502 * extended DTV capable of storing an additional slot for
503 * the newly-loaded DSO. */
504 alloc_size = sizeof *p + strlen(pathname) + 1;
505 if (runtime && temp_dso.tls_image) {
506 size_t per_th = temp_dso.tls_size + temp_dso.tls_align
507 + sizeof(void *) * (tls_cnt+3);
508 n_th = __libc.threads_minus_1 + 1;
509 if (n_th > SSIZE_MAX / per_th) alloc_size = SIZE_MAX;
510 else alloc_size += n_th * per_th;
512 p = calloc(1, alloc_size);
514 munmap(map, map_len);
517 memcpy(p, &temp_dso, sizeof temp_dso);
523 strcpy(p->name, pathname);
524 /* Add a shortname only if name arg was not an explicit pathname. */
525 if (pathname != name) p->shortname = strrchr(p->name, '/')+1;
527 p->tls_id = ++tls_cnt;
528 tls_size += p->tls_size + p->tls_align + 8*sizeof(size_t) - 1
530 p->new_dtv = (void *)(-sizeof(size_t) &
531 (uintptr_t)(p->name+strlen(p->name)+sizeof(size_t)));
532 p->new_tls = (void *)(p->new_dtv + n_th*(tls_cnt+1));
539 if (ldd_mode) dprintf(1, "\t%s => %s (%p)\n", name, pathname, base);
544 static void load_deps(struct dso *p)
547 struct dso ***deps = &p->deps, **tmp, *dep;
548 for (; p; p=p->next) {
549 for (i=0; p->dynv[i]; i+=2) {
550 if (p->dynv[i] != DT_RPATH) continue;
551 r_path = (void *)(p->strings + p->dynv[i+1]);
553 for (i=0; p->dynv[i]; i+=2) {
554 if (p->dynv[i] != DT_NEEDED) continue;
555 dep = load_library(p->strings + p->dynv[i+1]);
557 snprintf(errbuf, sizeof errbuf,
558 "Error loading shared library %s: %m (needed by %s)",
559 p->strings + p->dynv[i+1], p->name);
560 if (runtime) longjmp(rtld_fail, 1);
561 dprintf(2, "%s\n", errbuf);
566 tmp = realloc(*deps, sizeof(*tmp)*(ndeps+2));
567 if (!tmp) longjmp(rtld_fail, 1);
577 static void load_preload(char *s)
582 for ( ; *s && isspace(*s); s++);
583 for (z=s; *z && !isspace(*z); z++);
591 static void make_global(struct dso *p)
593 for (; p; p=p->next) p->global = 1;
596 static void reloc_all(struct dso *p)
598 size_t dyn[DYN_CNT] = {0};
599 for (; p; p=p->next) {
600 if (p->relocated) continue;
601 decode_vec(p->dynv, dyn, DYN_CNT);
602 #ifdef NEED_ARCH_RELOCS
603 do_arch_relocs(p, head);
605 do_relocs(p, (void *)(p->base+dyn[DT_JMPREL]), dyn[DT_PLTRELSZ],
606 2+(dyn[DT_PLTREL]==DT_RELA));
607 do_relocs(p, (void *)(p->base+dyn[DT_REL]), dyn[DT_RELSZ], 2);
608 do_relocs(p, (void *)(p->base+dyn[DT_RELA]), dyn[DT_RELASZ], 3);
613 static void free_all(struct dso *p)
618 if (p->map && p!=libc && p!=head) free(p);
623 static size_t find_dyn(Phdr *ph, size_t cnt, size_t stride)
625 for (; cnt--; ph = (void *)((char *)ph + stride))
626 if (ph->p_type == PT_DYNAMIC)
631 static void find_map_range(Phdr *ph, size_t cnt, size_t stride, struct dso *p)
633 size_t min_addr = -1, max_addr = 0;
634 for (; cnt--; ph = (void *)((char *)ph + stride)) {
635 if (ph->p_type != PT_LOAD) continue;
636 if (ph->p_vaddr < min_addr)
637 min_addr = ph->p_vaddr;
638 if (ph->p_vaddr+ph->p_memsz > max_addr)
639 max_addr = ph->p_vaddr+ph->p_memsz;
641 min_addr &= -PAGE_SIZE;
642 max_addr = (max_addr + PAGE_SIZE-1) & -PAGE_SIZE;
643 p->map = p->base + min_addr;
644 p->map_len = max_addr - min_addr;
647 static void do_fini()
650 size_t dyn[DYN_CNT] = {0};
651 for (p=fini_head; p; p=p->fini_next) {
652 if (!p->constructed) continue;
653 decode_vec(p->dynv, dyn, DYN_CNT);
654 ((void (*)(void))(p->base + dyn[DT_FINI]))();
658 static void do_init_fini(struct dso *p)
660 size_t dyn[DYN_CNT] = {0};
661 int need_locking = __libc.threads_minus_1;
662 /* Allow recursive calls that arise when a library calls
663 * dlopen from one of its constructors, but block any
664 * other threads until all ctors have finished. */
665 if (need_locking) pthread_mutex_lock(&init_fini_lock);
666 for (; p; p=p->prev) {
667 if (p->constructed) continue;
669 decode_vec(p->dynv, dyn, DYN_CNT);
670 if (dyn[0] & (1<<DT_FINI)) {
671 p->fini_next = fini_head;
674 if (dyn[0] & (1<<DT_INIT))
675 ((void (*)(void))(p->base + dyn[DT_INIT]))();
677 if (need_locking) pthread_mutex_unlock(&init_fini_lock);
680 void _dl_debug_state(void)
684 void *__copy_tls(unsigned char *mem)
687 void **dtv = (void *)mem;
688 dtv[0] = (void *)tls_cnt;
689 mem = (void *)(dtv + tls_cnt + 1);
690 for (p=tail; p; p=p->prev) {
691 if (!p->tls_id) continue;
692 mem += -p->tls_len & (4*sizeof(size_t)-1);
693 mem += ((uintptr_t)p->tls_image - (uintptr_t)mem)
695 dtv[p->tls_id] = mem;
696 memcpy(mem, p->tls_image, p->tls_len);
699 ((pthread_t)mem)->dtv = dtv;
703 void *__tls_get_addr(size_t *v)
705 pthread_t self = __pthread_self();
706 if (self->dtv && v[0]<=(size_t)self->dtv[0] && self->dtv[v[0]])
707 return (char *)self->dtv[v[0]]+v[1];
709 /* Block signals to make accessing new TLS async-signal-safe */
712 pthread_sigmask(SIG_BLOCK, &set, &set);
713 if (self->dtv && v[0]<=(size_t)self->dtv[0] && self->dtv[v[0]]) {
714 pthread_sigmask(SIG_SETMASK, &set, 0);
715 return (char *)self->dtv[v[0]]+v[1];
718 /* This is safe without any locks held because, if the caller
719 * is able to request the Nth entry of the DTV, the DSO list
720 * must be valid at least that far out and it was synchronized
721 * at program startup or by an already-completed call to dlopen. */
723 for (p=head; p->tls_id != v[0]; p=p->next);
725 /* Get new DTV space from new DSO if needed */
726 if (!self->dtv || v[0] > (size_t)self->dtv[0]) {
727 void **newdtv = p->new_dtv +
728 (v[0]+1)*sizeof(void *)*a_fetch_add(&p->new_dtv_idx,1);
729 if (self->dtv) memcpy(newdtv, self->dtv,
730 ((size_t)self->dtv[0]+1) * sizeof(void *));
731 newdtv[0] = (void *)v[0];
735 /* Get new TLS memory from new DSO */
736 unsigned char *mem = p->new_tls +
737 (p->tls_size + p->tls_align) * a_fetch_add(&p->new_tls_idx,1);
738 mem += ((uintptr_t)p->tls_image - (uintptr_t)mem) & (p->tls_align-1);
739 self->dtv[v[0]] = mem;
740 memcpy(mem, p->tls_image, p->tls_size);
741 pthread_sigmask(SIG_SETMASK, &set, 0);
745 void *__dynlink(int argc, char **argv)
747 size_t aux[AUX_CNT] = {0};
751 static struct dso builtin_dsos[3];
752 struct dso *const app = builtin_dsos+0;
753 struct dso *const lib = builtin_dsos+1;
754 struct dso *const vdso = builtin_dsos+2;
758 /* Find aux vector just past environ[] */
759 for (i=argc+1; argv[i]; i++)
760 if (!memcmp(argv[i], "LD_LIBRARY_PATH=", 16))
761 env_path = argv[i]+16;
762 else if (!memcmp(argv[i], "LD_PRELOAD=", 11))
763 env_preload = argv[i]+11;
764 auxv = (void *)(argv+i+1);
766 decode_vec(auxv, aux, AUX_CNT);
768 /* Only trust user/env if kernel says we're not suid/sgid */
769 if ((aux[0]&0x7800)!=0x7800 || aux[AT_UID]!=aux[AT_EUID]
770 || aux[AT_GID]!=aux[AT_EGID] || aux[AT_SECURE]) {
775 /* If the dynamic linker was invoked as a program itself, AT_BASE
776 * will not be set. In that case, we assume the base address is
777 * the start of the page containing the PHDRs; I don't know any
778 * better approach... */
780 aux[AT_BASE] = aux[AT_PHDR] & -PAGE_SIZE;
781 aux[AT_PHDR] = aux[AT_PHENT] = aux[AT_PHNUM] = 0;
784 /* The dynamic linker load address is passed by the kernel
785 * in the AUX vector, so this is easy. */
786 lib->base = (void *)aux[AT_BASE];
787 lib->name = lib->shortname = "libc.so";
789 ehdr = (void *)lib->base;
790 find_map_range((void *)(aux[AT_BASE]+ehdr->e_phoff),
791 ehdr->e_phnum, ehdr->e_phentsize, lib);
792 lib->dynv = (void *)(lib->base + find_dyn(
793 (void *)(aux[AT_BASE]+ehdr->e_phoff),
794 ehdr->e_phnum, ehdr->e_phentsize));
798 size_t interp_off = 0;
799 size_t tls_image = 0;
800 /* Find load address of the main program, via AT_PHDR vs PT_PHDR. */
801 phdr = (void *)aux[AT_PHDR];
802 for (i=aux[AT_PHNUM]; i; i--, phdr=(void *)((char *)phdr + aux[AT_PHENT])) {
803 if (phdr->p_type == PT_PHDR)
804 app->base = (void *)(aux[AT_PHDR] - phdr->p_vaddr);
805 else if (phdr->p_type == PT_INTERP)
806 interp_off = (size_t)phdr->p_vaddr;
807 else if (phdr->p_type == PT_TLS) {
808 tls_image = phdr->p_vaddr;
809 app->tls_len = phdr->p_filesz;
810 app->tls_size = phdr->p_memsz;
811 app->tls_align = phdr->p_align;
814 if (app->tls_size) app->tls_image = (char *)app->base + tls_image;
815 if (interp_off) lib->name = (char *)app->base + interp_off;
817 app->dynv = (void *)(app->base + find_dyn(
818 (void *)aux[AT_PHDR], aux[AT_PHNUM], aux[AT_PHENT]));
819 find_map_range((void *)aux[AT_PHDR],
820 aux[AT_PHNUM], aux[AT_PHENT], app);
823 char *ldname = argv[0];
824 size_t dyno, l = strlen(ldname);
825 if (l >= 3 && !strcmp(ldname+l-3, "ldd")) ldd_mode = 1;
826 *argv++ = (void *)-1;
827 if (argv[0] && !strcmp(argv[0], "--")) *argv++ = (void *)-1;
829 dprintf(2, "musl libc/dynamic program loader\n");
830 dprintf(2, "usage: %s pathname%s\n", ldname,
831 ldd_mode ? "" : " [args]");
834 fd = open(argv[0], O_RDONLY);
836 dprintf(2, "%s: cannot load %s: %s\n", ldname, argv[0], strerror(errno));
840 ehdr = (void *)map_library(fd, app);
842 dprintf(2, "%s: %s: Not a valid dynamic program\n", ldname, argv[0]);
849 aux[AT_ENTRY] = ehdr->e_entry;
852 app->tls_id = ++tls_cnt;
853 tls_size += app->tls_size+app->tls_align + 8*sizeof(size_t)-1
857 app->constructed = 1;
860 /* Attach to vdso, if provided by the kernel */
861 if (search_vec(auxv, &vdso_base, AT_SYSINFO_EHDR)) {
862 ehdr = (void *)vdso_base;
863 phdr = (void *)(vdso_base + ehdr->e_phoff);
864 for (i=ehdr->e_phnum; i; i--, phdr=(void *)((char *)phdr + ehdr->e_phentsize)) {
865 if (phdr->p_type == PT_DYNAMIC)
866 vdso->dynv = (void *)(vdso_base + phdr->p_offset);
867 if (phdr->p_type == PT_LOAD)
868 vdso->base = (void *)(vdso_base - phdr->p_vaddr + phdr->p_offset);
870 vdso->name = vdso->shortname = "linux-gate.so.1";
877 /* Initial dso chain consists only of the app. We temporarily
878 * append the dynamic linker/libc so we can relocate it, then
879 * restore the initial chain in preparation for loading third
880 * party libraries (preload/needed). */
887 /* PAST THIS POINT, ALL LIBC INTERFACES ARE FULLY USABLE. */
889 /* Donate unused parts of app and library mapping to malloc */
890 reclaim_gaps(app->base, (void *)aux[AT_PHDR], aux[AT_PHENT], aux[AT_PHNUM]);
891 ehdr = (void *)lib->base;
892 reclaim_gaps(lib->base, (void *)(lib->base+ehdr->e_phoff),
893 ehdr->e_phentsize, ehdr->e_phnum);
895 /* Load preload/needed libraries, add their symbols to the global
896 * namespace, and perform all remaining relocations. The main
897 * program must be relocated LAST since it may contain copy
898 * relocations which depend on libraries' relocations. */
899 if (env_preload) load_preload(env_preload);
903 /* Make an initial pass setting up TLS before performing relocs.
904 * This provides the TP-based offset of each DSO's TLS for
905 * use in TP-relative relocations. After relocations, we need
906 * to copy the TLS images again in case they had relocs. */
907 tls_size += sizeof(struct pthread) + 4*sizeof(size_t);
908 __libc.tls_size = tls_size;
911 void *mem = mmap(0, __libc.tls_size, PROT_READ|PROT_WRITE,
912 MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
913 if (mem==MAP_FAILED ||
914 !__install_initial_tls(__copy_tls(mem))) {
915 dprintf(2, "%s: Error getting %zu bytes thread-local storage: %m\n",
919 for (p=head; p; p=p->next) {
920 if (!p->tls_id) continue;
921 p->tls_offset = (char *)__pthread_self()
922 - (char *)__pthread_self()->dtv[p->tls_id];
926 reloc_all(app->next);
929 /* The initial DTV is located at the base of the memory
930 * allocated for TLS. Repeat copying TLS to pick up relocs. */
931 if (tls_cnt) __copy_tls((void *)__pthread_self()->dtv);
933 if (ldso_fail) _exit(127);
934 if (ldd_mode) _exit(0);
936 /* Switch to runtime mode: any further failures in the dynamic
937 * linker are a reportable failure rather than a fatal startup
938 * error. If the dynamic loader (dlopen) will not be used, free
939 * all memory used by the dynamic linker. */
942 #ifndef DYNAMIC_IS_RO
943 for (i=0; app->dynv[i]; i+=2)
944 if (app->dynv[i]==DT_DEBUG)
945 app->dynv[i+1] = (size_t)&debug;
948 debug.bp = _dl_debug_state;
950 debug.base = lib->base;
954 if (ssp_used) __init_ssp(auxv);
960 return (void *)aux[AT_ENTRY];
963 void *dlopen(const char *file, int mode)
965 struct dso *volatile p, *orig_tail, *next;
970 if (!file) return head;
972 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
973 pthread_rwlock_wrlock(&lock);
977 orig_tls_cnt = tls_cnt;
980 if (setjmp(rtld_fail)) {
981 /* Clean up anything new that was (partially) loaded */
982 if (p && p->deps) for (i=0; p->deps[i]; i++)
983 if (p->deps[i]->global < 0)
984 p->deps[i]->global = 0;
985 for (p=orig_tail->next; p; p=next) {
987 munmap(p->map, p->map_len);
991 tls_cnt = orig_tls_cnt;
992 tls_size = __libc.tls_size;
998 } else p = load_library(file);
1001 snprintf(errbuf, sizeof errbuf,
1002 "Error loading shared library %s: %m", file);
1007 /* First load handling */
1010 if (p->deps) for (i=0; p->deps[i]; i++)
1011 if (!p->deps[i]->global)
1012 p->deps[i]->global = -1;
1013 if (!p->global) p->global = -1;
1015 if (p->deps) for (i=0; p->deps[i]; i++)
1016 if (p->deps[i]->global < 0)
1017 p->deps[i]->global = 0;
1018 if (p->global < 0) p->global = 0;
1021 if (mode & RTLD_GLOBAL) {
1022 if (p->deps) for (i=0; p->deps[i]; i++)
1023 p->deps[i]->global = 1;
1027 __libc.tls_size = tls_size;
1029 if (ssp_used) __init_ssp(auxv);
1035 pthread_rwlock_unlock(&lock);
1036 if (p) do_init_fini(orig_tail);
1037 pthread_setcancelstate(cs, 0);
1041 static void *do_dlsym(struct dso *p, const char *s, void *ra)
1044 uint32_t h = 0, gh = 0;
1046 if (p == head || p == RTLD_DEFAULT || p == RTLD_NEXT) {
1047 if (p == RTLD_NEXT) {
1048 for (p=head; p && (unsigned char *)ra-p->map>p->map_len; p=p->next);
1051 struct symdef def = find_sym(p->next, s, 0);
1052 if (!def.sym) goto failed;
1053 return def.dso->base + def.sym->st_value;
1057 sym = gnu_lookup(s, gh, p);
1060 sym = sysv_lookup(s, h, p);
1062 if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
1063 return p->base + sym->st_value;
1064 if (p->deps) for (i=0; p->deps[i]; i++) {
1065 if (p->deps[i]->ghashtab) {
1066 if (!gh) gh = gnu_hash(s);
1067 sym = gnu_lookup(s, gh, p->deps[i]);
1069 if (!h) h = sysv_hash(s);
1070 sym = sysv_lookup(s, h, p->deps[i]);
1072 if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
1073 return p->deps[i]->base + sym->st_value;
1077 snprintf(errbuf, sizeof errbuf, "Symbol not found: %s", s);
1081 int __dladdr(void *addr, Dl_info *info)
1091 pthread_rwlock_rdlock(&lock);
1092 for (p=head; p && (unsigned char *)addr-p->map>p->map_len; p=p->next);
1093 pthread_rwlock_unlock(&lock);
1098 strings = p->strings;
1100 nsym = p->hashtab[1];
1104 buckets = p->ghashtab + 4 + (p->ghashtab[2]*sizeof(size_t)/4);
1105 sym += p->ghashtab[1];
1106 for (i = 0; i < p->ghashtab[0]; i++) {
1107 if (buckets[i] > nsym)
1111 nsym -= p->ghashtab[1];
1112 hashval = buckets + p->ghashtab[0] + nsym;
1114 while (!(*hashval++ & 1));
1118 for (; nsym; nsym--, sym++) {
1119 if (sym->st_shndx && sym->st_value
1120 && (1<<(sym->st_info&0xf) & OK_TYPES)
1121 && (1<<(sym->st_info>>4) & OK_BINDS)) {
1122 void *symaddr = p->base + sym->st_value;
1123 if (symaddr > addr || symaddr < best)
1126 bestname = strings + sym->st_name;
1127 if (addr == symaddr)
1132 if (!best) return 0;
1134 info->dli_fname = p->name;
1135 info->dli_fbase = p->base;
1136 info->dli_sname = bestname;
1137 info->dli_saddr = best;
1142 void *__dlsym(void *restrict p, const char *restrict s, void *restrict ra)
1145 pthread_rwlock_rdlock(&lock);
1146 res = do_dlsym(p, s, ra);
1147 pthread_rwlock_unlock(&lock);
1151 void *dlopen(const char *file, int mode)
1155 void *__dlsym(void *restrict p, const char *restrict s, void *restrict ra)
1159 int __dladdr (void *addr, Dl_info *info)
1167 if (!errflag) return 0;
1172 int dlclose(void *p)