18 #include "pthread_impl.h"
22 static char errbuf[128];
26 #if ULONG_MAX == 0xffffffff
27 typedef Elf32_Ehdr Ehdr;
28 typedef Elf32_Phdr Phdr;
29 typedef Elf32_Sym Sym;
30 #define R_TYPE(x) ((x)&255)
31 #define R_SYM(x) ((x)>>8)
33 typedef Elf64_Ehdr Ehdr;
34 typedef Elf64_Phdr Phdr;
35 typedef Elf64_Sym Sym;
36 #define R_TYPE(x) ((x)&0xffffffff)
37 #define R_SYM(x) ((x)>>32)
40 #define MAXP2(a,b) (-(-(a)&-(b)))
41 #define ALIGN(x,y) ((x)+(y)-1 & -(y))
55 struct dso *next, *prev;
73 struct dso **deps, *needed_by;
74 char *rpath_orig, *rpath;
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 *);
94 void __init_libc(char **, char *);
96 const char *__libc_get_version(void);
98 static struct dso *head, *tail, *ldso, *fini_head;
99 static char *env_path, *sys_path;
100 static unsigned long long gencnt;
104 static int ldso_fail;
106 static jmp_buf *rtld_fail;
107 static pthread_rwlock_t lock;
108 static struct debug debug;
109 static size_t tls_cnt, tls_offset, tls_align = 4*sizeof(size_t);
110 static pthread_mutex_t init_fini_lock = { ._m_type = PTHREAD_MUTEX_RECURSIVE };
112 struct debug *_dl_debug_addr = &debug;
117 static void decode_vec(size_t *v, size_t *a, size_t cnt)
119 memset(a, 0, cnt*sizeof(size_t));
120 for (; v[0]; v+=2) if (v[0]<cnt) {
126 static int search_vec(size_t *v, size_t *r, size_t key)
128 for (; v[0]!=key; v+=2)
134 static uint32_t sysv_hash(const char *s0)
136 const unsigned char *s = (void *)s0;
142 return h & 0xfffffff;
145 static uint32_t gnu_hash(const char *s0)
147 const unsigned char *s = (void *)s0;
148 uint_fast32_t h = 5381;
154 static Sym *sysv_lookup(const char *s, uint32_t h, struct dso *dso)
157 Sym *syms = dso->syms;
158 uint32_t *hashtab = dso->hashtab;
159 char *strings = dso->strings;
160 for (i=hashtab[2+h%hashtab[0]]; i; i=hashtab[2+hashtab[0]+i]) {
161 if ((!dso->versym || dso->versym[i] >= 0)
162 && (!strcmp(s, strings+syms[i].st_name)))
168 static Sym *gnu_lookup(const char *s, uint32_t h1, struct dso *dso)
170 Sym *syms = dso->syms;
171 char *strings = dso->strings;
172 uint32_t *hashtab = dso->ghashtab;
173 uint32_t nbuckets = hashtab[0];
174 uint32_t *buckets = hashtab + 4 + hashtab[2]*(sizeof(size_t)/4);
177 uint32_t i = buckets[h1 % nbuckets];
181 hashval = buckets + nbuckets + (i - hashtab[1]);
183 for (h1 |= 1; ; i++) {
185 if ((!dso->versym || dso->versym[i] >= 0)
186 && (h1 == (h2|1)) && !strcmp(s, strings + syms[i].st_name))
194 #define OK_TYPES (1<<STT_NOTYPE | 1<<STT_OBJECT | 1<<STT_FUNC | 1<<STT_COMMON | 1<<STT_TLS)
195 #define OK_BINDS (1<<STB_GLOBAL | 1<<STB_WEAK | 1<<STB_GNU_UNIQUE)
197 static struct symdef find_sym(struct dso *dso, const char *s, int need_def)
199 uint32_t h = 0, gh = 0;
200 struct symdef def = {0};
203 if (gh == 0x1f4039c9 && !strcmp(s, "__stack_chk_fail")) ssp_used = 1;
206 if (h == 0x595a4cc && !strcmp(s, "__stack_chk_fail")) ssp_used = 1;
208 for (; dso; dso=dso->next) {
210 if (!dso->global) continue;
212 if (!gh) gh = gnu_hash(s);
213 sym = gnu_lookup(s, gh, dso);
215 if (!h) h = sysv_hash(s);
216 sym = sysv_lookup(s, h, dso);
220 if (need_def || (sym->st_info&0xf) == STT_TLS)
223 if ((sym->st_info&0xf) != STT_TLS)
225 if (!(1<<(sym->st_info&0xf) & OK_TYPES)) continue;
226 if (!(1<<(sym->st_info>>4) & OK_BINDS)) continue;
228 if (def.sym && sym->st_info>>4 == STB_WEAK) continue;
231 if (sym->st_info>>4 == STB_GLOBAL) break;
236 static void do_relocs(struct dso *dso, size_t *rel, size_t rel_size, size_t stride)
238 unsigned char *base = dso->base;
239 Sym *syms = dso->syms;
240 char *strings = dso->strings;
248 for (; rel_size; rel+=stride, rel_size-=stride*sizeof(size_t)) {
249 type = R_TYPE(rel[1]);
250 sym_index = R_SYM(rel[1]);
252 sym = syms + sym_index;
253 name = strings + sym->st_name;
254 ctx = IS_COPY(type) ? head->next : head;
255 def = find_sym(ctx, name, IS_PLT(type));
256 if (!def.sym && sym->st_info>>4 != STB_WEAK) {
257 snprintf(errbuf, sizeof errbuf,
258 "Error relocating %s: %s: symbol not found",
260 if (runtime) longjmp(*rtld_fail, 1);
261 dprintf(2, "%s\n", errbuf);
270 do_single_reloc(dso, base, (void *)(base + rel[0]), type,
271 stride>2 ? rel[2] : 0, sym, sym?sym->st_size:0, def,
272 def.sym?(size_t)(def.dso->base+def.sym->st_value):0);
276 /* A huge hack: to make up for the wastefulness of shared libraries
277 * needing at least a page of dirty memory even if they have no global
278 * data, we reclaim the gaps at the beginning and end of writable maps
279 * and "donate" them to the heap by setting up minimal malloc
280 * structures and then freeing them. */
282 static void reclaim(unsigned char *base, size_t start, size_t end)
285 start = start + 6*sizeof(size_t)-1 & -4*sizeof(size_t);
286 end = (end & -4*sizeof(size_t)) - 2*sizeof(size_t);
287 if (start>end || end-start < 4*sizeof(size_t)) return;
288 a = (size_t *)(base + start);
289 z = (size_t *)(base + end);
291 a[-1] = z[0] = end-start + 2*sizeof(size_t) | 1;
296 static void reclaim_gaps(unsigned char *base, Phdr *ph, size_t phent, size_t phcnt)
298 for (; phcnt--; ph=(void *)((char *)ph+phent)) {
299 if (ph->p_type!=PT_LOAD) continue;
300 if ((ph->p_flags&(PF_R|PF_W))!=(PF_R|PF_W)) continue;
301 reclaim(base, ph->p_vaddr & -PAGE_SIZE, ph->p_vaddr);
302 reclaim(base, ph->p_vaddr+ph->p_memsz,
303 ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE);
307 static void *map_library(int fd, struct dso *dso)
309 Ehdr buf[(896+sizeof(Ehdr))/sizeof(Ehdr)];
310 void *allocated_buf=0;
312 size_t addr_min=SIZE_MAX, addr_max=0, map_len;
313 size_t this_min, this_max;
318 unsigned char *map=MAP_FAILED, *base;
323 ssize_t l = read(fd, buf, sizeof buf);
326 if (l<sizeof *eh || (eh->e_type != ET_DYN && eh->e_type != ET_EXEC))
328 phsize = eh->e_phentsize * eh->e_phnum;
329 if (phsize > sizeof buf - sizeof *eh) {
330 allocated_buf = malloc(phsize);
331 if (!allocated_buf) return 0;
332 l = pread(fd, allocated_buf, phsize, eh->e_phoff);
333 if (l < 0) goto error;
334 if (l != phsize) goto noexec;
335 ph = ph0 = allocated_buf;
336 } else if (eh->e_phoff + phsize > l) {
337 l = pread(fd, buf+1, phsize, eh->e_phoff);
338 if (l < 0) goto error;
339 if (l != phsize) goto noexec;
340 ph = ph0 = (void *)(buf + 1);
342 ph = ph0 = (void *)((char *)buf + eh->e_phoff);
344 for (i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
345 if (ph->p_type == PT_DYNAMIC)
347 if (ph->p_type == PT_TLS) {
348 tls_image = ph->p_vaddr;
349 dso->tls_align = ph->p_align;
350 dso->tls_len = ph->p_filesz;
351 dso->tls_size = ph->p_memsz;
353 if (ph->p_type != PT_LOAD) continue;
354 if (ph->p_vaddr < addr_min) {
355 addr_min = ph->p_vaddr;
356 off_start = ph->p_offset;
357 prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
358 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
359 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
361 if (ph->p_vaddr+ph->p_memsz > addr_max) {
362 addr_max = ph->p_vaddr+ph->p_memsz;
365 if (!dyn) goto noexec;
366 addr_max += PAGE_SIZE-1;
367 addr_max &= -PAGE_SIZE;
368 addr_min &= -PAGE_SIZE;
369 off_start &= -PAGE_SIZE;
370 map_len = addr_max - addr_min + off_start;
371 /* The first time, we map too much, possibly even more than
372 * the length of the file. This is okay because we will not
373 * use the invalid part; we just need to reserve the right
374 * amount of virtual address space to map over later. */
375 map = mmap((void *)addr_min, map_len, prot, MAP_PRIVATE, fd, off_start);
376 if (map==MAP_FAILED) goto error;
377 /* If the loaded file is not relocatable and the requested address is
378 * not available, then the load operation must fail. */
379 if (eh->e_type != ET_DYN && addr_min && map!=(void *)addr_min) {
383 base = map - addr_min;
386 for (ph=ph0, i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
387 if (ph->p_type != PT_LOAD) continue;
388 /* Check if the programs headers are in this load segment, and
389 * if so, record the address for use by dl_iterate_phdr. */
390 if (!dso->phdr && eh->e_phoff >= ph->p_offset
391 && eh->e_phoff+phsize <= ph->p_offset+ph->p_filesz) {
392 dso->phdr = (void *)(base + ph->p_vaddr
393 + (eh->e_phoff-ph->p_offset));
394 dso->phnum = eh->e_phnum;
396 /* Reuse the existing mapping for the lowest-address LOAD */
397 if ((ph->p_vaddr & -PAGE_SIZE) == addr_min) continue;
398 this_min = ph->p_vaddr & -PAGE_SIZE;
399 this_max = ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE;
400 off_start = ph->p_offset & -PAGE_SIZE;
401 prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
402 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
403 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
404 if (mmap(base+this_min, this_max-this_min, prot, MAP_PRIVATE|MAP_FIXED, fd, off_start) == MAP_FAILED)
406 if (ph->p_memsz > ph->p_filesz) {
407 size_t brk = (size_t)base+ph->p_vaddr+ph->p_filesz;
408 size_t pgbrk = brk+PAGE_SIZE-1 & -PAGE_SIZE;
409 memset((void *)brk, 0, pgbrk-brk & PAGE_SIZE-1);
410 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)
414 for (i=0; ((size_t *)(base+dyn))[i]; i+=2)
415 if (((size_t *)(base+dyn))[i]==DT_TEXTREL) {
416 if (mprotect(map, map_len, PROT_READ|PROT_WRITE|PROT_EXEC) < 0)
420 if (!runtime) reclaim_gaps(base, ph0, eh->e_phentsize, eh->e_phnum);
422 dso->map_len = map_len;
424 dso->dynv = (void *)(base+dyn);
425 if (dso->tls_size) dso->tls_image = (void *)(base+tls_image);
431 if (map!=MAP_FAILED) munmap(map, map_len);
436 static int path_open(const char *name, const char *s, char *buf, size_t buf_size)
441 s += strspn(s, ":\n");
442 l = strcspn(s, ":\n");
443 if (l-1 >= INT_MAX) return -1;
444 if (snprintf(buf, buf_size, "%.*s/%s", (int)l, s, name) >= buf_size)
446 if ((fd = open(buf, O_RDONLY|O_CLOEXEC))>=0) return fd;
451 static int fixup_rpath(struct dso *p, char *buf, size_t buf_size)
454 const char *s, *t, *origin;
456 if (p->rpath) return 0;
457 if (!p->rpath_orig) return -1;
458 if (!strchr(p->rpath_orig, '$')) {
459 p->rpath = p->rpath_orig;
464 while ((t=strchr(s, '$'))) {
465 if (strncmp(t, "$ORIGIN", 7) && strncmp(t, "${ORIGIN}", 9))
470 if (n > SSIZE_MAX/PATH_MAX) return -1;
472 if (p->kernel_mapped) {
473 /* $ORIGIN searches cannot be performed for the main program
474 * when it is suid/sgid/AT_SECURE. This is because the
475 * pathname is under the control of the caller of execve.
476 * For libraries, however, $ORIGIN can be processed safely
477 * since the library's pathname came from a trusted source
478 * (either system paths or a call to dlopen). */
481 l = readlink("/proc/self/exe", buf, buf_size);
489 t = strrchr(origin, '/');
490 l = t ? t-origin : 0;
491 p->rpath = malloc(strlen(p->rpath_orig) + n*l + 1);
492 if (!p->rpath) return -1;
496 while ((t=strchr(s, '$'))) {
499 memcpy(d, origin, l);
501 /* It was determined previously that the '$' is followed
502 * either by "ORIGIN" or "{ORIGIN}". */
503 s = t + 7 + 2*(t[1]=='{');
509 static void decode_dyn(struct dso *p)
511 size_t dyn[DYN_CNT] = {0};
512 decode_vec(p->dynv, dyn, DYN_CNT);
513 p->syms = (void *)(p->base + dyn[DT_SYMTAB]);
514 p->strings = (void *)(p->base + dyn[DT_STRTAB]);
515 if (dyn[0]&(1<<DT_HASH))
516 p->hashtab = (void *)(p->base + dyn[DT_HASH]);
517 if (dyn[0]&(1<<DT_RPATH))
518 p->rpath_orig = (void *)(p->strings + dyn[DT_RPATH]);
519 if (search_vec(p->dynv, dyn, DT_GNU_HASH))
520 p->ghashtab = (void *)(p->base + *dyn);
521 if (search_vec(p->dynv, dyn, DT_VERSYM))
522 p->versym = (void *)(p->base + *dyn);
525 static struct dso *load_library(const char *name, struct dso *needed_by)
527 char buf[2*NAME_MAX+2];
528 const char *pathname;
530 struct dso *p, temp_dso = {0};
537 /* Catch and block attempts to reload the implementation itself */
538 if (name[0]=='l' && name[1]=='i' && name[2]=='b') {
539 static const char *rp, reserved[] =
540 "c\0pthread\0rt\0m\0dl\0util\0xnet\0";
541 char *z = strchr(name, '.');
544 for (rp=reserved; *rp && strncmp(name+3, rp, l-3); rp+=strlen(rp)+1);
547 /* Track which names have been resolved
548 * and only report each one once. */
549 static unsigned reported;
550 unsigned mask = 1U<<(rp-reserved);
551 if (!(reported & mask)) {
553 dprintf(1, "\t%s => %s (%p)\n",
562 if (!strcmp(name, ldso->name)) is_self = 1;
567 tail = ldso->next ? ldso->next : ldso;
571 if (strchr(name, '/')) {
573 fd = open(name, O_RDONLY|O_CLOEXEC);
575 /* Search for the name to see if it's already loaded */
576 for (p=head->next; p; p=p->next) {
577 if (p->shortname && !strcmp(p->shortname, name)) {
582 if (strlen(name) > NAME_MAX) return 0;
584 if (env_path) fd = path_open(name, env_path, buf, sizeof buf);
585 for (p=needed_by; fd < 0 && p; p=p->needed_by)
586 if (!fixup_rpath(p, buf, sizeof buf))
587 fd = path_open(name, p->rpath, buf, sizeof buf);
592 if (ldso->name[0]=='/') {
594 for (s=t=z=ldso->name; *s; s++)
595 if (*s=='/') z=t, t=s;
596 prefix_len = z-ldso->name;
597 if (prefix_len < PATH_MAX)
604 char etc_ldso_path[prefix_len + 1
605 + sizeof "/etc/ld-musl-" LDSO_ARCH ".path"];
606 snprintf(etc_ldso_path, sizeof etc_ldso_path,
607 "%.*s/etc/ld-musl-" LDSO_ARCH ".path",
608 (int)prefix_len, prefix);
609 FILE *f = fopen(etc_ldso_path, "rbe");
611 if (getdelim(&sys_path, (size_t[1]){0}, 0, f) <= 0) {
616 } else if (errno != ENOENT) {
620 if (!sys_path) sys_path = "/lib:/usr/local/lib:/usr/lib";
621 fd = path_open(name, sys_path, buf, sizeof buf);
625 if (fd < 0) return 0;
626 if (fstat(fd, &st) < 0) {
630 for (p=head->next; p; p=p->next) {
631 if (p->dev == st.st_dev && p->ino == st.st_ino) {
632 /* If this library was previously loaded with a
633 * pathname but a search found the same inode,
634 * setup its shortname so it can be found by name. */
635 if (!p->shortname && pathname != name)
636 p->shortname = strrchr(p->name, '/')+1;
642 map = noload ? 0 : map_library(fd, &temp_dso);
646 /* Allocate storage for the new DSO. When there is TLS, this
647 * storage must include a reservation for all pre-existing
648 * threads to obtain copies of both the new TLS, and an
649 * extended DTV capable of storing an additional slot for
650 * the newly-loaded DSO. */
651 alloc_size = sizeof *p + strlen(pathname) + 1;
652 if (runtime && temp_dso.tls_image) {
653 size_t per_th = temp_dso.tls_size + temp_dso.tls_align
654 + sizeof(void *) * (tls_cnt+3);
655 n_th = libc.threads_minus_1 + 1;
656 if (n_th > SSIZE_MAX / per_th) alloc_size = SIZE_MAX;
657 else alloc_size += n_th * per_th;
659 p = calloc(1, alloc_size);
661 munmap(map, temp_dso.map_len);
664 memcpy(p, &temp_dso, sizeof temp_dso);
669 p->needed_by = needed_by;
671 strcpy(p->name, pathname);
672 /* Add a shortname only if name arg was not an explicit pathname. */
673 if (pathname != name) p->shortname = strrchr(p->name, '/')+1;
675 if (runtime && !__pthread_self_init()) {
676 munmap(map, p->map_len);
680 p->tls_id = ++tls_cnt;
681 tls_align = MAXP2(tls_align, p->tls_align);
683 p->tls_offset = tls_offset + ( (tls_align-1) &
684 -(tls_offset + (uintptr_t)p->tls_image) );
685 tls_offset += p->tls_size;
687 tls_offset += p->tls_size + p->tls_align - 1;
688 tls_offset -= (tls_offset + (uintptr_t)p->tls_image)
690 p->tls_offset = tls_offset;
692 p->new_dtv = (void *)(-sizeof(size_t) &
693 (uintptr_t)(p->name+strlen(p->name)+sizeof(size_t)));
694 p->new_tls = (void *)(p->new_dtv + n_th*(tls_cnt+1));
701 if (ldd_mode) dprintf(1, "\t%s => %s (%p)\n", name, pathname, p->base);
706 static void load_deps(struct dso *p)
709 struct dso ***deps = &p->deps, **tmp, *dep;
710 for (; p; p=p->next) {
711 for (i=0; p->dynv[i]; i+=2) {
712 if (p->dynv[i] != DT_NEEDED) continue;
713 dep = load_library(p->strings + p->dynv[i+1], p);
715 snprintf(errbuf, sizeof errbuf,
716 "Error loading shared library %s: %m (needed by %s)",
717 p->strings + p->dynv[i+1], p->name);
718 if (runtime) longjmp(*rtld_fail, 1);
719 dprintf(2, "%s\n", errbuf);
724 tmp = realloc(*deps, sizeof(*tmp)*(ndeps+2));
725 if (!tmp) longjmp(*rtld_fail, 1);
734 static void load_preload(char *s)
739 for ( ; *s && isspace(*s); s++);
740 for (z=s; *z && !isspace(*z); z++);
748 static void make_global(struct dso *p)
750 for (; p; p=p->next) p->global = 1;
753 static void reloc_all(struct dso *p)
755 size_t dyn[DYN_CNT] = {0};
756 for (; p; p=p->next) {
757 if (p->relocated) continue;
758 decode_vec(p->dynv, dyn, DYN_CNT);
759 #ifdef NEED_ARCH_RELOCS
760 do_arch_relocs(p, head);
762 do_relocs(p, (void *)(p->base+dyn[DT_JMPREL]), dyn[DT_PLTRELSZ],
763 2+(dyn[DT_PLTREL]==DT_RELA));
764 do_relocs(p, (void *)(p->base+dyn[DT_REL]), dyn[DT_RELSZ], 2);
765 do_relocs(p, (void *)(p->base+dyn[DT_RELA]), dyn[DT_RELASZ], 3);
770 static size_t find_dyn(Phdr *ph, size_t cnt, size_t stride)
772 for (; cnt--; ph = (void *)((char *)ph + stride))
773 if (ph->p_type == PT_DYNAMIC)
778 static void find_map_range(Phdr *ph, size_t cnt, size_t stride, struct dso *p)
780 size_t min_addr = -1, max_addr = 0;
781 for (; cnt--; ph = (void *)((char *)ph + stride)) {
782 if (ph->p_type != PT_LOAD) continue;
783 if (ph->p_vaddr < min_addr)
784 min_addr = ph->p_vaddr;
785 if (ph->p_vaddr+ph->p_memsz > max_addr)
786 max_addr = ph->p_vaddr+ph->p_memsz;
788 min_addr &= -PAGE_SIZE;
789 max_addr = (max_addr + PAGE_SIZE-1) & -PAGE_SIZE;
790 p->map = p->base + min_addr;
791 p->map_len = max_addr - min_addr;
794 static void do_fini()
797 size_t dyn[DYN_CNT] = {0};
798 for (p=fini_head; p; p=p->fini_next) {
799 if (!p->constructed) continue;
800 decode_vec(p->dynv, dyn, DYN_CNT);
801 if (dyn[0] & (1<<DT_FINI_ARRAY)) {
802 size_t n = dyn[DT_FINI_ARRAYSZ]/sizeof(size_t);
803 size_t *fn = (size_t *)(p->base + dyn[DT_FINI_ARRAY])+n;
804 while (n--) ((void (*)(void))*--fn)();
806 #ifndef NO_LEGACY_INITFINI
807 if ((dyn[0] & (1<<DT_FINI)) && dyn[DT_FINI])
808 ((void (*)(void))(p->base + dyn[DT_FINI]))();
813 static void do_init_fini(struct dso *p)
815 size_t dyn[DYN_CNT] = {0};
816 int need_locking = libc.threads_minus_1;
817 /* Allow recursive calls that arise when a library calls
818 * dlopen from one of its constructors, but block any
819 * other threads until all ctors have finished. */
820 if (need_locking) pthread_mutex_lock(&init_fini_lock);
821 for (; p; p=p->prev) {
822 if (p->constructed) continue;
824 decode_vec(p->dynv, dyn, DYN_CNT);
825 if (dyn[0] & ((1<<DT_FINI) | (1<<DT_FINI_ARRAY))) {
826 p->fini_next = fini_head;
829 #ifndef NO_LEGACY_INITFINI
830 if ((dyn[0] & (1<<DT_INIT)) && dyn[DT_INIT])
831 ((void (*)(void))(p->base + dyn[DT_INIT]))();
833 if (dyn[0] & (1<<DT_INIT_ARRAY)) {
834 size_t n = dyn[DT_INIT_ARRAYSZ]/sizeof(size_t);
835 size_t *fn = (void *)(p->base + dyn[DT_INIT_ARRAY]);
836 while (n--) ((void (*)(void))*fn++)();
838 if (!need_locking && libc.threads_minus_1) {
840 pthread_mutex_lock(&init_fini_lock);
843 if (need_locking) pthread_mutex_unlock(&init_fini_lock);
846 void _dl_debug_state(void)
852 pthread_t self = __pthread_self();
854 for (p=head; p; p=p->next) {
855 if (!p->tls_id || !self->dtv[p->tls_id]) continue;
856 memcpy(self->dtv[p->tls_id], p->tls_image, p->tls_len);
857 memset((char *)self->dtv[p->tls_id]+p->tls_len, 0,
858 p->tls_size - p->tls_len);
859 if (p->tls_id == (size_t)self->dtv[0]) break;
863 void *__copy_tls(unsigned char *mem)
868 if (!tls_cnt) return mem;
870 void **dtv = (void *)mem;
871 dtv[0] = (void *)tls_cnt;
874 mem += sizeof(void *) * (tls_cnt+1);
875 mem += -((uintptr_t)mem + sizeof(struct pthread)) & (tls_align-1);
877 mem += sizeof(struct pthread);
879 for (p=head; p; p=p->next) {
880 if (!p->tls_id) continue;
881 dtv[p->tls_id] = mem + p->tls_offset;
882 memcpy(dtv[p->tls_id], p->tls_image, p->tls_len);
885 mem += libc.tls_size - sizeof(struct pthread);
886 mem -= (uintptr_t)mem & (tls_align-1);
889 for (p=head; p; p=p->next) {
890 if (!p->tls_id) continue;
891 dtv[p->tls_id] = mem - p->tls_offset;
892 memcpy(dtv[p->tls_id], p->tls_image, p->tls_len);
899 void *__tls_get_addr(size_t *v)
901 pthread_t self = __pthread_self();
902 if (v[0]<=(size_t)self->dtv[0] && self->dtv[v[0]])
903 return (char *)self->dtv[v[0]]+v[1];
905 /* Block signals to make accessing new TLS async-signal-safe */
907 pthread_sigmask(SIG_BLOCK, SIGALL_SET, &set);
908 if (v[0]<=(size_t)self->dtv[0] && self->dtv[v[0]]) {
909 pthread_sigmask(SIG_SETMASK, &set, 0);
910 return (char *)self->dtv[v[0]]+v[1];
913 /* This is safe without any locks held because, if the caller
914 * is able to request the Nth entry of the DTV, the DSO list
915 * must be valid at least that far out and it was synchronized
916 * at program startup or by an already-completed call to dlopen. */
918 for (p=head; p->tls_id != v[0]; p=p->next);
920 /* Get new DTV space from new DSO if needed */
921 if (v[0] > (size_t)self->dtv[0]) {
922 void **newdtv = p->new_dtv +
923 (v[0]+1)*sizeof(void *)*a_fetch_add(&p->new_dtv_idx,1);
924 memcpy(newdtv, self->dtv,
925 ((size_t)self->dtv[0]+1) * sizeof(void *));
926 newdtv[0] = (void *)v[0];
930 /* Get new TLS memory from new DSO */
931 unsigned char *mem = p->new_tls +
932 (p->tls_size + p->tls_align) * a_fetch_add(&p->new_tls_idx,1);
933 mem += ((uintptr_t)p->tls_image - (uintptr_t)mem) & (p->tls_align-1);
934 self->dtv[v[0]] = mem;
935 memcpy(mem, p->tls_image, p->tls_len);
936 pthread_sigmask(SIG_SETMASK, &set, 0);
940 static void update_tls_size()
942 libc.tls_size = ALIGN(
943 (1+tls_cnt) * sizeof(void *) +
945 sizeof(struct pthread) +
950 void *__dynlink(int argc, char **argv)
952 size_t aux[AUX_CNT] = {0};
956 static struct dso builtin_dsos[3];
957 struct dso *const app = builtin_dsos+0;
958 struct dso *const lib = builtin_dsos+1;
959 struct dso *const vdso = builtin_dsos+2;
963 char **envp = argv+argc+1;
965 /* Find aux vector just past environ[] */
966 for (i=argc+1; argv[i]; i++)
967 if (!memcmp(argv[i], "LD_LIBRARY_PATH=", 16))
968 env_path = argv[i]+16;
969 else if (!memcmp(argv[i], "LD_PRELOAD=", 11))
970 env_preload = argv[i]+11;
971 auxv = (void *)(argv+i+1);
973 decode_vec(auxv, aux, AUX_CNT);
975 /* Only trust user/env if kernel says we're not suid/sgid */
976 if ((aux[0]&0x7800)!=0x7800 || aux[AT_UID]!=aux[AT_EUID]
977 || aux[AT_GID]!=aux[AT_EGID] || aux[AT_SECURE]) {
982 libc.page_size = aux[AT_PAGESZ];
984 /* If the dynamic linker was invoked as a program itself, AT_BASE
985 * will not be set. In that case, we assume the base address is
986 * the start of the page containing the PHDRs; I don't know any
987 * better approach... */
989 aux[AT_BASE] = aux[AT_PHDR] & -PAGE_SIZE;
990 aux[AT_PHDR] = aux[AT_PHENT] = aux[AT_PHNUM] = 0;
993 /* The dynamic linker load address is passed by the kernel
994 * in the AUX vector, so this is easy. */
995 lib->base = (void *)aux[AT_BASE];
996 lib->name = lib->shortname = "libc.so";
998 lib->kernel_mapped = 1;
999 ehdr = (void *)lib->base;
1000 lib->phnum = ehdr->e_phnum;
1001 lib->phdr = (void *)(aux[AT_BASE]+ehdr->e_phoff);
1002 find_map_range(lib->phdr, ehdr->e_phnum, ehdr->e_phentsize, lib);
1003 lib->dynv = (void *)(lib->base + find_dyn(lib->phdr,
1004 ehdr->e_phnum, ehdr->e_phentsize));
1008 size_t interp_off = 0;
1009 size_t tls_image = 0;
1010 /* Find load address of the main program, via AT_PHDR vs PT_PHDR. */
1011 app->phdr = phdr = (void *)aux[AT_PHDR];
1012 app->phnum = aux[AT_PHNUM];
1013 for (i=aux[AT_PHNUM]; i; i--, phdr=(void *)((char *)phdr + aux[AT_PHENT])) {
1014 if (phdr->p_type == PT_PHDR)
1015 app->base = (void *)(aux[AT_PHDR] - phdr->p_vaddr);
1016 else if (phdr->p_type == PT_INTERP)
1017 interp_off = (size_t)phdr->p_vaddr;
1018 else if (phdr->p_type == PT_TLS) {
1019 tls_image = phdr->p_vaddr;
1020 app->tls_len = phdr->p_filesz;
1021 app->tls_size = phdr->p_memsz;
1022 app->tls_align = phdr->p_align;
1025 if (app->tls_size) app->tls_image = (char *)app->base + tls_image;
1026 if (interp_off) lib->name = (char *)app->base + interp_off;
1027 if ((aux[0] & (1UL<<AT_EXECFN))
1028 && strncmp((char *)aux[AT_EXECFN], "/proc/", 6))
1029 app->name = (char *)aux[AT_EXECFN];
1031 app->name = argv[0];
1032 app->kernel_mapped = 1;
1033 app->dynv = (void *)(app->base + find_dyn(
1034 (void *)aux[AT_PHDR], aux[AT_PHNUM], aux[AT_PHENT]));
1035 find_map_range((void *)aux[AT_PHDR],
1036 aux[AT_PHNUM], aux[AT_PHENT], app);
1039 char *ldname = argv[0];
1040 size_t l = strlen(ldname);
1041 if (l >= 3 && !strcmp(ldname+l-3, "ldd")) ldd_mode = 1;
1042 *argv++ = (void *)-1;
1043 if (argv[0] && !strcmp(argv[0], "--")) *argv++ = (void *)-1;
1045 dprintf(2, "musl libc\n"
1047 "Dynamic Program Loader\n"
1048 "Usage: %s [--] pathname%s\n",
1049 __libc_get_version(), ldname,
1050 ldd_mode ? "" : " [args]");
1053 fd = open(argv[0], O_RDONLY);
1055 dprintf(2, "%s: cannot load %s: %s\n", ldname, argv[0], strerror(errno));
1059 ehdr = (void *)map_library(fd, app);
1061 dprintf(2, "%s: %s: Not a valid dynamic program\n", ldname, argv[0]);
1067 app->name = argv[0];
1068 aux[AT_ENTRY] = (size_t)app->base + ehdr->e_entry;
1069 /* Find the name that would have been used for the dynamic
1070 * linker had ldd not taken its place. */
1072 for (i=0; i<app->phnum; i++) {
1073 if (app->phdr[i].p_type == PT_INTERP)
1074 lib->name = (void *)(app->base
1075 + app->phdr[i].p_vaddr);
1077 dprintf(1, "\t%s (%p)\n", lib->name, lib->base);
1080 if (app->tls_size) {
1081 app->tls_id = tls_cnt = 1;
1083 app->tls_offset = 0;
1084 tls_offset = app->tls_size
1085 + ( -((uintptr_t)app->tls_image + app->tls_size)
1086 & (app->tls_align-1) );
1088 tls_offset = app->tls_offset = app->tls_size
1089 + ( -((uintptr_t)app->tls_image + app->tls_size)
1090 & (app->tls_align-1) );
1092 tls_align = MAXP2(tls_align, app->tls_align);
1097 /* Attach to vdso, if provided by the kernel */
1098 if (search_vec(auxv, &vdso_base, AT_SYSINFO_EHDR)) {
1099 ehdr = (void *)vdso_base;
1100 vdso->phdr = phdr = (void *)(vdso_base + ehdr->e_phoff);
1101 vdso->phnum = ehdr->e_phnum;
1102 for (i=ehdr->e_phnum; i; i--, phdr=(void *)((char *)phdr + ehdr->e_phentsize)) {
1103 if (phdr->p_type == PT_DYNAMIC)
1104 vdso->dynv = (void *)(vdso_base + phdr->p_offset);
1105 if (phdr->p_type == PT_LOAD)
1106 vdso->base = (void *)(vdso_base - phdr->p_vaddr + phdr->p_offset);
1109 vdso->shortname = "linux-gate.so.1";
1116 /* Initial dso chain consists only of the app. We temporarily
1117 * append the dynamic linker/libc so we can relocate it, then
1118 * restore the initial chain in preparation for loading third
1119 * party libraries (preload/needed). */
1126 /* PAST THIS POINT, ALL LIBC INTERFACES ARE FULLY USABLE. */
1128 /* Donate unused parts of app and library mapping to malloc */
1129 reclaim_gaps(app->base, (void *)aux[AT_PHDR], aux[AT_PHENT], aux[AT_PHNUM]);
1130 ehdr = (void *)lib->base;
1131 reclaim_gaps(lib->base, (void *)(lib->base+ehdr->e_phoff),
1132 ehdr->e_phentsize, ehdr->e_phnum);
1134 /* Load preload/needed libraries, add their symbols to the global
1135 * namespace, and perform all remaining relocations. The main
1136 * program must be relocated LAST since it may contain copy
1137 * relocations which depend on libraries' relocations. */
1138 if (env_preload) load_preload(env_preload);
1142 reloc_all(app->next);
1147 void *mem = mmap(0, libc.tls_size, PROT_READ|PROT_WRITE,
1148 MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
1149 if (mem==MAP_FAILED ||
1150 !__install_initial_tls(__copy_tls(mem))) {
1151 dprintf(2, "%s: Error getting %zu bytes thread-local storage: %m\n",
1152 argv[0], libc.tls_size);
1157 if (ldso_fail) _exit(127);
1158 if (ldd_mode) _exit(0);
1160 /* Switch to runtime mode: any further failures in the dynamic
1161 * linker are a reportable failure rather than a fatal startup
1162 * error. If the dynamic loader (dlopen) will not be used, free
1163 * all memory used by the dynamic linker. */
1166 #ifndef DYNAMIC_IS_RO
1167 for (i=0; app->dynv[i]; i+=2)
1168 if (app->dynv[i]==DT_DEBUG)
1169 app->dynv[i+1] = (size_t)&debug;
1172 debug.bp = _dl_debug_state;
1174 debug.base = lib->base;
1178 if (ssp_used) __init_ssp((void *)aux[AT_RANDOM]);
1179 __init_libc(envp, argv[0]);
1184 return (void *)aux[AT_ENTRY];
1187 void *dlopen(const char *file, int mode)
1189 struct dso *volatile p, *orig_tail, *next;
1190 size_t orig_tls_cnt, orig_tls_offset, orig_tls_align;
1195 if (!file) return head;
1197 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
1198 pthread_rwlock_wrlock(&lock);
1202 orig_tls_cnt = tls_cnt;
1203 orig_tls_offset = tls_offset;
1204 orig_tls_align = tls_align;
1206 noload = mode & RTLD_NOLOAD;
1209 if (setjmp(*rtld_fail)) {
1210 /* Clean up anything new that was (partially) loaded */
1211 if (p && p->deps) for (i=0; p->deps[i]; i++)
1212 if (p->deps[i]->global < 0)
1213 p->deps[i]->global = 0;
1214 for (p=orig_tail->next; p; p=next) {
1216 munmap(p->map, p->map_len);
1220 tls_cnt = orig_tls_cnt;
1221 tls_offset = orig_tls_offset;
1222 tls_align = orig_tls_align;
1228 } else p = load_library(file, head);
1231 snprintf(errbuf, sizeof errbuf, noload ?
1232 "Library %s is not already loaded" :
1233 "Error loading shared library %s: %m",
1239 /* First load handling */
1242 if (p->deps) for (i=0; p->deps[i]; i++)
1243 if (!p->deps[i]->global)
1244 p->deps[i]->global = -1;
1245 if (!p->global) p->global = -1;
1247 if (p->deps) for (i=0; p->deps[i]; i++)
1248 if (p->deps[i]->global < 0)
1249 p->deps[i]->global = 0;
1250 if (p->global < 0) p->global = 0;
1253 if (mode & RTLD_GLOBAL) {
1254 if (p->deps) for (i=0; p->deps[i]; i++)
1255 p->deps[i]->global = 1;
1261 if (ssp_used) __init_ssp(libc.auxv);
1268 pthread_rwlock_unlock(&lock);
1269 if (p) do_init_fini(orig_tail);
1270 pthread_setcancelstate(cs, 0);
1274 static int invalid_dso_handle(void *h)
1277 for (p=head; p; p=p->next) if (h==p) return 0;
1278 snprintf(errbuf, sizeof errbuf, "Invalid library handle %p", (void *)h);
1283 static void *do_dlsym(struct dso *p, const char *s, void *ra)
1286 uint32_t h = 0, gh = 0;
1288 if (p == head || p == RTLD_DEFAULT || p == RTLD_NEXT) {
1289 if (p == RTLD_DEFAULT) {
1291 } else if (p == RTLD_NEXT) {
1292 for (p=head; p && (unsigned char *)ra-p->map>p->map_len; p=p->next);
1296 struct symdef def = find_sym(p, s, 0);
1297 if (!def.sym) goto failed;
1298 if ((def.sym->st_info&0xf) == STT_TLS)
1299 return __tls_get_addr((size_t []){def.dso->tls_id, def.sym->st_value});
1300 return def.dso->base + def.sym->st_value;
1302 if (p != RTLD_DEFAULT && p != RTLD_NEXT && invalid_dso_handle(p))
1306 sym = gnu_lookup(s, gh, p);
1309 sym = sysv_lookup(s, h, p);
1311 if (sym && (sym->st_info&0xf) == STT_TLS)
1312 return __tls_get_addr((size_t []){p->tls_id, sym->st_value});
1313 if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
1314 return p->base + sym->st_value;
1315 if (p->deps) for (i=0; p->deps[i]; i++) {
1316 if (p->deps[i]->ghashtab) {
1317 if (!gh) gh = gnu_hash(s);
1318 sym = gnu_lookup(s, gh, p->deps[i]);
1320 if (!h) h = sysv_hash(s);
1321 sym = sysv_lookup(s, h, p->deps[i]);
1323 if (sym && (sym->st_info&0xf) == STT_TLS)
1324 return __tls_get_addr((size_t []){p->deps[i]->tls_id, sym->st_value});
1325 if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
1326 return p->deps[i]->base + sym->st_value;
1330 snprintf(errbuf, sizeof errbuf, "Symbol not found: %s", s);
1334 int __dladdr(const void *addr, Dl_info *info)
1344 pthread_rwlock_rdlock(&lock);
1345 for (p=head; p && (unsigned char *)addr-p->map>p->map_len; p=p->next);
1346 pthread_rwlock_unlock(&lock);
1351 strings = p->strings;
1353 nsym = p->hashtab[1];
1357 buckets = p->ghashtab + 4 + (p->ghashtab[2]*sizeof(size_t)/4);
1358 sym += p->ghashtab[1];
1359 for (i = nsym = 0; i < p->ghashtab[0]; i++) {
1360 if (buckets[i] > nsym)
1364 nsym -= p->ghashtab[1];
1365 hashval = buckets + p->ghashtab[0] + nsym;
1367 while (!(*hashval++ & 1));
1371 for (; nsym; nsym--, sym++) {
1373 && (1<<(sym->st_info&0xf) & OK_TYPES)
1374 && (1<<(sym->st_info>>4) & OK_BINDS)) {
1375 void *symaddr = p->base + sym->st_value;
1376 if (symaddr > addr || symaddr < best)
1379 bestname = strings + sym->st_name;
1380 if (addr == symaddr)
1385 if (!best) return 0;
1387 info->dli_fname = p->name;
1388 info->dli_fbase = p->base;
1389 info->dli_sname = bestname;
1390 info->dli_saddr = best;
1395 void *__dlsym(void *restrict p, const char *restrict s, void *restrict ra)
1398 pthread_rwlock_rdlock(&lock);
1399 res = do_dlsym(p, s, ra);
1400 pthread_rwlock_unlock(&lock);
1404 int dl_iterate_phdr(int(*callback)(struct dl_phdr_info *info, size_t size, void *data), void *data)
1406 struct dso *current;
1407 struct dl_phdr_info info;
1409 for(current = head; current;) {
1410 info.dlpi_addr = (uintptr_t)current->base;
1411 info.dlpi_name = current->name;
1412 info.dlpi_phdr = current->phdr;
1413 info.dlpi_phnum = current->phnum;
1414 info.dlpi_adds = gencnt;
1416 info.dlpi_tls_modid = current->tls_id;
1417 info.dlpi_tls_data = current->tls_image;
1419 ret = (callback)(&info, sizeof (info), data);
1421 if (ret != 0) break;
1423 pthread_rwlock_rdlock(&lock);
1424 current = current->next;
1425 pthread_rwlock_unlock(&lock);
1430 static int invalid_dso_handle(void *h)
1432 snprintf(errbuf, sizeof errbuf, "Invalid library handle %p", (void *)h);
1436 void *dlopen(const char *file, int mode)
1440 void *__dlsym(void *restrict p, const char *restrict s, void *restrict ra)
1444 int __dladdr (const void *addr, Dl_info *info)
1450 int __dlinfo(void *dso, int req, void *res)
1452 if (invalid_dso_handle(dso)) return -1;
1453 if (req != RTLD_DI_LINKMAP) {
1454 snprintf(errbuf, sizeof errbuf, "Unsupported request %d", req);
1458 *(struct link_map **)res = dso;
1464 if (!errflag) return 0;
1469 int dlclose(void *p)
1471 return invalid_dso_handle(p);