21 static char errbuf[128];
27 #if ULONG_MAX == 0xffffffff
28 typedef Elf32_Ehdr Ehdr;
29 typedef Elf32_Phdr Phdr;
30 typedef Elf32_Sym Sym;
31 #define R_TYPE(x) ((x)&255)
32 #define R_SYM(x) ((x)>>8)
34 typedef Elf64_Ehdr Ehdr;
35 typedef Elf64_Phdr Phdr;
36 typedef Elf64_Sym Sym;
37 #define R_TYPE(x) ((x)&0xffffffff)
38 #define R_SYM(x) ((x)>>32)
53 struct dso *next, *prev;
71 void __init_ssp(size_t *);
73 static struct dso *head, *tail, *libc;
74 static char *env_path, *sys_path, *r_path;
79 static jmp_buf rtld_fail;
80 static pthread_rwlock_t lock;
81 static struct debug debug;
83 struct debug *_dl_debug_addr = &debug;
88 static void decode_vec(size_t *v, size_t *a, size_t cnt)
90 memset(a, 0, cnt*sizeof(size_t));
91 for (; v[0]; v+=2) if (v[0]<cnt) {
97 static uint32_t hash(const char *s0)
99 const unsigned char *s = (void *)s0;
105 return h & 0xfffffff;
108 static Sym *lookup(const char *s, uint32_t h, struct dso *dso)
111 Sym *syms = dso->syms;
112 uint32_t *hashtab = dso->hashtab;
113 char *strings = dso->strings;
114 for (i=hashtab[2+h%hashtab[0]]; i; i=hashtab[2+hashtab[0]+i]) {
115 if (!strcmp(s, strings+syms[i].st_name))
121 #define OK_TYPES (1<<STT_NOTYPE | 1<<STT_OBJECT | 1<<STT_FUNC | 1<<STT_COMMON)
122 #define OK_BINDS (1<<STB_GLOBAL | 1<<STB_WEAK)
124 static void *find_sym(struct dso *dso, const char *s, int need_def)
126 uint32_t h = hash(s);
128 if (h==0x6b366be && !strcmp(s, "dlopen")) rtld_used = 1;
129 if (h==0x6b3afd && !strcmp(s, "dlsym")) rtld_used = 1;
130 if (h==0x595a4cc && !strcmp(s, "__stack_chk_fail")) ssp_used = 1;
131 for (; dso; dso=dso->next) {
133 if (!dso->global) continue;
134 sym = lookup(s, h, dso);
135 if (sym && (!need_def || sym->st_shndx) && sym->st_value
136 && (1<<(sym->st_info&0xf) & OK_TYPES)
137 && (1<<(sym->st_info>>4) & OK_BINDS)) {
138 if (def && sym->st_info>>4 == STB_WEAK) continue;
139 def = dso->base + sym->st_value;
140 if (sym->st_info>>4 == STB_GLOBAL) break;
146 static void do_relocs(struct dso *dso, size_t *rel, size_t rel_size, size_t stride)
148 unsigned char *base = dso->base;
149 Sym *syms = dso->syms;
150 char *strings = dso->strings;
153 size_t sym_val, sym_size;
159 for (; rel_size; rel+=stride, rel_size-=stride*sizeof(size_t)) {
160 reloc_addr = (void *)(base + rel[0]);
161 type = R_TYPE(rel[1]);
162 sym_index = R_SYM(rel[1]);
164 sym = syms + sym_index;
165 name = strings + sym->st_name;
166 ctx = IS_COPY(type) ? head->next : head;
167 sym_val = (size_t)find_sym(ctx, name, IS_PLT(type));
168 if (!sym_val && sym->st_info>>4 != STB_WEAK) {
169 snprintf(errbuf, sizeof errbuf,
170 "Error relocating %s: %s: symbol not found",
172 if (runtime) longjmp(rtld_fail, 1);
173 dprintf(2, "%s\n", errbuf);
176 sym_size = sym->st_size;
178 do_single_reloc(reloc_addr, type, sym_val, sym_size, base, rel[2]);
182 /* A huge hack: to make up for the wastefulness of shared libraries
183 * needing at least a page of dirty memory even if they have no global
184 * data, we reclaim the gaps at the beginning and end of writable maps
185 * and "donate" them to the heap by setting up minimal malloc
186 * structures and then freeing them. */
188 static void reclaim(unsigned char *base, size_t start, size_t end)
191 start = start + 6*sizeof(size_t)-1 & -4*sizeof(size_t);
192 end = (end & -4*sizeof(size_t)) - 2*sizeof(size_t);
193 if (start>end || end-start < 4*sizeof(size_t)) return;
194 a = (size_t *)(base + start);
195 z = (size_t *)(base + end);
197 a[-1] = z[0] = end-start + 2*sizeof(size_t) | 1;
202 static void reclaim_gaps(unsigned char *base, Phdr *ph, size_t phent, size_t phcnt)
204 for (; phcnt--; ph=(void *)((char *)ph+phent)) {
205 if (ph->p_type!=PT_LOAD) continue;
206 if ((ph->p_flags&(PF_R|PF_W))!=(PF_R|PF_W)) continue;
207 reclaim(base, ph->p_vaddr & -PAGE_SIZE, ph->p_vaddr);
208 reclaim(base, ph->p_vaddr+ph->p_memsz,
209 ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE);
213 static void *map_library(int fd, size_t *lenp, unsigned char **basep, size_t *dynp)
215 Ehdr buf[(896+sizeof(Ehdr))/sizeof(Ehdr)];
217 size_t addr_min=SIZE_MAX, addr_max=0, map_len;
218 size_t this_min, this_max;
223 unsigned char *map, *base;
227 ssize_t l = read(fd, buf, sizeof buf);
228 if (l<sizeof *eh) return 0;
230 phsize = eh->e_phentsize * eh->e_phnum;
231 if (phsize + sizeof *eh > l) return 0;
232 if (eh->e_phoff + phsize > l) {
233 l = pread(fd, buf+1, phsize, eh->e_phoff);
234 if (l != phsize) return 0;
235 eh->e_phoff = sizeof *eh;
237 ph = (void *)((char *)buf + eh->e_phoff);
238 for (i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
239 if (ph->p_type == PT_DYNAMIC)
241 if (ph->p_type != PT_LOAD) continue;
242 if (ph->p_vaddr < addr_min) {
243 addr_min = ph->p_vaddr;
244 off_start = ph->p_offset;
245 prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
246 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
247 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
249 if (ph->p_vaddr+ph->p_memsz > addr_max) {
250 addr_max = ph->p_vaddr+ph->p_memsz;
254 addr_max += PAGE_SIZE-1;
255 addr_max &= -PAGE_SIZE;
256 addr_min &= -PAGE_SIZE;
257 off_start &= -PAGE_SIZE;
258 map_len = addr_max - addr_min + off_start;
259 /* The first time, we map too much, possibly even more than
260 * the length of the file. This is okay because we will not
261 * use the invalid part; we just need to reserve the right
262 * amount of virtual address space to map over later. */
263 map = mmap((void *)addr_min, map_len, prot, MAP_PRIVATE, fd, off_start);
264 if (map==MAP_FAILED) return 0;
265 base = map - addr_min;
266 ph = (void *)((char *)buf + eh->e_phoff);
267 for (i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
268 if (ph->p_type != PT_LOAD) continue;
269 /* Reuse the existing mapping for the lowest-address LOAD */
270 if ((ph->p_vaddr & -PAGE_SIZE) == addr_min) continue;
271 this_min = ph->p_vaddr & -PAGE_SIZE;
272 this_max = ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE;
273 off_start = ph->p_offset & -PAGE_SIZE;
274 prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
275 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
276 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
277 if (mmap(base+this_min, this_max-this_min, prot, MAP_PRIVATE|MAP_FIXED, fd, off_start) == MAP_FAILED)
279 if (ph->p_memsz > ph->p_filesz) {
280 size_t brk = (size_t)base+ph->p_vaddr+ph->p_filesz;
281 size_t pgbrk = brk+PAGE_SIZE-1 & -PAGE_SIZE;
282 memset((void *)brk, 0, pgbrk-brk & PAGE_SIZE-1);
283 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)
287 for (i=0; ((size_t *)(base+dyn))[i]; i+=2)
288 if (((size_t *)(base+dyn))[i]==DT_TEXTREL) {
289 if (mprotect(map, map_len, PROT_READ|PROT_WRITE|PROT_EXEC) < 0)
293 if (!runtime) reclaim_gaps(base, (void *)((char *)buf + eh->e_phoff),
294 eh->e_phentsize, eh->e_phnum);
300 munmap(map, map_len);
304 static int path_open(const char *name, const char *search, char *buf, size_t buf_size)
306 const char *s=search, *z;
312 l = z ? z-s : strlen(s);
313 snprintf(buf, buf_size, "%.*s/%s", l, s, name);
314 if ((fd = open(buf, O_RDONLY))>=0) return fd;
319 static void decode_dyn(struct dso *p)
321 size_t dyn[DYN_CNT] = {0};
322 decode_vec(p->dynv, dyn, DYN_CNT);
323 p->syms = (void *)(p->base + dyn[DT_SYMTAB]);
324 p->hashtab = (void *)(p->base + dyn[DT_HASH]);
325 p->strings = (void *)(p->base + dyn[DT_STRTAB]);
328 static struct dso *load_library(const char *name)
330 char buf[2*NAME_MAX+2];
331 const char *pathname;
332 unsigned char *base, *map;
333 size_t dyno, map_len;
338 /* Catch and block attempts to reload the implementation itself */
339 if (name[0]=='l' && name[1]=='i' && name[2]=='b') {
340 static const char *rp, reserved[] =
341 "c\0pthread\0rt\0m\0dl\0util\0xnet\0";
342 char *z = strchr(name, '.');
345 for (rp=reserved; *rp && memcmp(name+3, rp, l-3); rp+=strlen(rp)+1);
350 tail = libc->next ? libc->next : libc;
356 if (strchr(name, '/')) {
358 fd = open(name, O_RDONLY);
360 /* Search for the name to see if it's already loaded */
361 for (p=head->next; p; p=p->next) {
362 if (p->shortname && !strcmp(p->shortname, name)) {
367 if (strlen(name) > NAME_MAX) return 0;
369 if (r_path) fd = path_open(name, r_path, buf, sizeof buf);
370 if (fd < 0 && env_path) fd = path_open(name, env_path, buf, sizeof buf);
373 FILE *f = fopen(ETC_LDSO_PATH, "r");
375 if (getline(&sys_path, (size_t[1]){0}, f) > 0)
376 sys_path[strlen(sys_path)-1]=0;
380 if (sys_path) fd = path_open(name, sys_path, buf, sizeof buf);
381 else fd = path_open(name, "/lib:/usr/local/lib:/usr/lib", buf, sizeof buf);
385 if (fd < 0) return 0;
386 if (fstat(fd, &st) < 0) {
390 for (p=head->next; p; p=p->next) {
391 if (p->dev == st.st_dev && p->ino == st.st_ino) {
392 /* If this library was previously loaded with a
393 * pathname but a search found the same inode,
394 * setup its shortname so it can be found by name. */
395 if (!p->shortname) p->shortname = strrchr(p->name, '/')+1;
401 map = map_library(fd, &map_len, &base, &dyno);
404 p = calloc(1, sizeof *p + strlen(pathname) + 1);
406 munmap(map, map_len);
411 p->map_len = map_len;
413 p->dynv = (void *)(base + dyno);
420 strcpy(p->name, pathname);
421 /* Add a shortname only if name arg was not an explicit pathname. */
422 if (pathname != name) p->shortname = strrchr(p->name, '/')+1;
428 if (ldd_mode) dprintf(1, "\t%s => %s (%p)\n", name, pathname, base);
433 static void load_deps(struct dso *p)
436 struct dso ***deps = &p->deps, **tmp, *dep;
437 for (; p; p=p->next) {
438 for (i=0; p->dynv[i]; i+=2) {
439 if (p->dynv[i] != DT_RPATH) continue;
440 r_path = (void *)(p->strings + p->dynv[i+1]);
442 for (i=0; p->dynv[i]; i+=2) {
443 if (p->dynv[i] != DT_NEEDED) continue;
444 dep = load_library(p->strings + p->dynv[i+1]);
446 snprintf(errbuf, sizeof errbuf,
447 "Error loading shared library %s: %m (needed by %s)",
448 p->strings + p->dynv[i+1], p->name);
449 if (runtime) longjmp(rtld_fail, 1);
450 dprintf(2, "%s\n", errbuf);
454 tmp = realloc(*deps, sizeof(*tmp)*(ndeps+2));
455 if (!tmp) longjmp(rtld_fail, 1);
465 static void load_preload(char *s)
470 for ( ; *s && isspace(*s); s++);
471 for (z=s; *z && !isspace(*z); z++);
479 static void make_global(struct dso *p)
481 for (; p; p=p->next) p->global = 1;
484 static void reloc_all(struct dso *p)
486 size_t dyn[DYN_CNT] = {0};
487 for (; p; p=p->next) {
488 if (p->relocated) continue;
489 decode_vec(p->dynv, dyn, DYN_CNT);
490 #ifdef NEED_ARCH_RELOCS
491 do_arch_relocs(p, head);
493 do_relocs(p, (void *)(p->base+dyn[DT_JMPREL]), dyn[DT_PLTRELSZ],
494 2+(dyn[DT_PLTREL]==DT_RELA));
495 do_relocs(p, (void *)(p->base+dyn[DT_REL]), dyn[DT_RELSZ], 2);
496 do_relocs(p, (void *)(p->base+dyn[DT_RELA]), dyn[DT_RELASZ], 3);
501 static void free_all(struct dso *p)
511 static size_t find_dyn(Phdr *ph, size_t cnt, size_t stride)
513 for (; cnt--; ph = (void *)((char *)ph + stride))
514 if (ph->p_type == PT_DYNAMIC)
519 static void do_init_fini(struct dso *p)
521 size_t dyn[DYN_CNT] = {0};
522 for (; p; p=p->prev) {
523 if (p->constructed) return;
524 decode_vec(p->dynv, dyn, DYN_CNT);
525 if (dyn[0] & (1<<DT_FINI))
526 atexit((void (*)(void))(p->base + dyn[DT_FINI]));
527 if (dyn[0] & (1<<DT_INIT))
528 ((void (*)(void))(p->base + dyn[DT_INIT]))();
533 void _dl_debug_state(void)
537 void *__dynlink(int argc, char **argv)
539 size_t *auxv, aux[AUX_CNT] = {0};
543 static struct dso builtin_dsos[3];
544 struct dso *const app = builtin_dsos+0;
545 struct dso *const lib = builtin_dsos+1;
546 struct dso *const vdso = builtin_dsos+2;
549 /* Find aux vector just past environ[] */
550 for (i=argc+1; argv[i]; i++)
551 if (!memcmp(argv[i], "LD_LIBRARY_PATH=", 16))
552 env_path = argv[i]+16;
553 else if (!memcmp(argv[i], "LD_PRELOAD=", 11))
554 env_preload = argv[i]+11;
555 auxv = (void *)(argv+i+1);
557 decode_vec(auxv, aux, AUX_CNT);
559 /* Only trust user/env if kernel says we're not suid/sgid */
560 if ((aux[0]&0x7800)!=0x7800 || aux[AT_UID]!=aux[AT_EUID]
561 || aux[AT_GID]!=aux[AT_EGID] || aux[AT_SECURE]) {
566 /* If the dynamic linker was invoked as a program itself, AT_BASE
567 * will not be set. In that case, we assume the base address is
568 * the start of the page containing the PHDRs; I don't know any
569 * better approach... */
571 aux[AT_BASE] = aux[AT_PHDR] & -PAGE_SIZE;
572 aux[AT_PHDR] = aux[AT_PHENT] = aux[AT_PHNUM] = 0;
575 /* The dynamic linker load address is passed by the kernel
576 * in the AUX vector, so this is easy. */
577 lib->base = (void *)aux[AT_BASE];
578 lib->name = lib->shortname = "libc.so";
580 ehdr = (void *)lib->base;
581 lib->dynv = (void *)(lib->base + find_dyn(
582 (void *)(aux[AT_BASE]+ehdr->e_phoff),
583 ehdr->e_phnum, ehdr->e_phentsize));
587 size_t interp_off = 0;
588 /* Find load address of the main program, via AT_PHDR vs PT_PHDR. */
589 phdr = (void *)aux[AT_PHDR];
590 for (i=aux[AT_PHNUM]; i; i--, phdr=(void *)((char *)phdr + aux[AT_PHENT])) {
591 if (phdr->p_type == PT_PHDR)
592 app->base = (void *)(aux[AT_PHDR] - phdr->p_vaddr);
593 else if (phdr->p_type == PT_INTERP)
594 interp_off = (size_t)phdr->p_vaddr;
596 if (interp_off) lib->name = (char *)app->base + interp_off;
598 app->dynv = (void *)(app->base + find_dyn(
599 (void *)aux[AT_PHDR], aux[AT_PHNUM], aux[AT_PHENT]));
602 char *ldname = argv[0];
603 size_t dyno, l = strlen(ldname);
604 if (l >= 3 && !strcmp(ldname+l-3, "ldd")) ldd_mode = 1;
605 *argv++ = (void *)-1;
606 if (argv[0] && !strcmp(argv[0], "--")) *argv++ = (void *)-1;
608 dprintf(2, "musl libc/dynamic program loader\n");
609 dprintf(2, "usage: %s pathname%s\n", ldname,
610 ldd_mode ? "" : " [args]");
613 fd = open(argv[0], O_RDONLY);
615 dprintf(2, "%s: cannot load %s: %s\n", ldname, argv[0], strerror(errno));
619 ehdr = (void *)map_library(fd, &app->map_len, &app->base, &dyno);
621 dprintf(2, "%s: %s: Not a valid dynamic program\n", ldname, argv[0]);
628 app->dynv = (void *)(app->base + dyno);
629 aux[AT_ENTRY] = ehdr->e_entry;
632 app->constructed = 1;
635 /* Attach to vdso, if provided by the kernel */
636 for (i=0; auxv[i]; i+=2) {
637 size_t vdso_base = auxv[i+1];
638 if (auxv[i] != AT_SYSINFO_EHDR) continue;
639 ehdr = (void *)vdso_base;
640 phdr = (void *)(vdso_base + ehdr->e_phoff);
641 for (i=ehdr->e_phnum; i; i--, phdr=(void *)((char *)phdr + ehdr->e_phentsize)) {
642 if (phdr->p_type == PT_DYNAMIC)
643 vdso->dynv = (void *)(vdso_base + phdr->p_offset);
644 if (phdr->p_type == PT_LOAD)
645 vdso->base = (void *)(vdso_base - phdr->p_vaddr + phdr->p_offset);
647 vdso->name = vdso->shortname = "linux-gate.so.1";
655 /* Initial dso chain consists only of the app. We temporarily
656 * append the dynamic linker/libc so we can relocate it, then
657 * restore the initial chain in preparation for loading third
658 * party libraries (preload/needed). */
665 /* PAST THIS POINT, ALL LIBC INTERFACES ARE FULLY USABLE. */
667 /* Donate unused parts of app and library mapping to malloc */
668 reclaim_gaps(app->base, (void *)aux[AT_PHDR], aux[AT_PHENT], aux[AT_PHNUM]);
669 ehdr = (void *)lib->base;
670 reclaim_gaps(lib->base, (void *)(lib->base+ehdr->e_phoff),
671 ehdr->e_phentsize, ehdr->e_phnum);
673 /* Load preload/needed libraries, add their symbols to the global
674 * namespace, and perform all remaining relocations. The main
675 * program must be relocated LAST since it may contain copy
676 * relocations which depend on libraries' relocations. */
677 if (env_preload) load_preload(env_preload);
680 reloc_all(app->next);
683 if (ldd_mode) _exit(0);
685 /* Switch to runtime mode: any further failures in the dynamic
686 * linker are a reportable failure rather than a fatal startup
687 * error. If the dynamic loader (dlopen) will not be used, free
688 * all memory used by the dynamic linker. */
691 for (i=0; app->dynv[i]; i+=2)
692 if (app->dynv[i]==DT_DEBUG)
693 app->dynv[i+1] = (size_t)&debug;
695 debug.bp = _dl_debug_state;
697 debug.base = lib->base;
701 if (ssp_used) __init_ssp(auxv);
708 reclaim((void *)builtin_dsos, 0, sizeof builtin_dsos);
712 return (void *)aux[AT_ENTRY];
715 void *dlopen(const char *file, int mode)
717 struct dso *volatile p, *orig_tail = tail, *next;
721 if (!file) return head;
723 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
724 pthread_rwlock_wrlock(&lock);
726 if (setjmp(rtld_fail)) {
727 /* Clean up anything new that was (partially) loaded */
728 if (p->deps) for (i=0; p->deps[i]; i++)
729 if (p->deps[i]->global < 0)
730 p->deps[i]->global = 0;
731 for (p=orig_tail->next; p; p=next) {
733 munmap(p->map, p->map_len);
742 } else p = load_library(file);
745 snprintf(errbuf, sizeof errbuf,
746 "Error loading shared library %s: %m", file);
751 /* First load handling */
754 if (p->deps) for (i=0; p->deps[i]; i++)
755 if (!p->deps[i]->global)
756 p->deps[i]->global = -1;
757 if (!p->global) p->global = -1;
759 if (p->deps) for (i=0; p->deps[i]; i++)
760 if (p->deps[i]->global < 0)
761 p->deps[i]->global = 0;
762 if (p->global < 0) p->global = 0;
765 if (mode & RTLD_GLOBAL) {
766 if (p->deps) for (i=0; p->deps[i]; i++)
767 p->deps[i]->global = 1;
775 pthread_rwlock_unlock(&lock);
776 pthread_setcancelstate(cs, 0);
780 static void *do_dlsym(struct dso *p, const char *s, void *ra)
785 if (p == RTLD_NEXT) {
786 for (p=head; p && (unsigned char *)ra-p->map>p->map_len; p=p->next);
788 void *res = find_sym(p->next, s, 0);
789 if (!res) goto failed;
792 if (p == head || p == RTLD_DEFAULT) {
793 void *res = find_sym(head, s, 0);
794 if (!res) goto failed;
798 sym = lookup(s, h, p);
799 if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
800 return p->base + sym->st_value;
801 if (p->deps) for (i=0; p->deps[i]; i++) {
802 sym = lookup(s, h, p);
803 if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
804 return p->deps[i]->base + sym->st_value;
808 snprintf(errbuf, sizeof errbuf, "Symbol not found: %s", s);
812 void *__dlsym(void *p, const char *s, void *ra)
815 pthread_rwlock_rdlock(&lock);
816 res = do_dlsym(p, s, ra);
817 pthread_rwlock_unlock(&lock);
821 void *dlopen(const char *file, int mode)
825 void *__dlsym(void *p, const char *s, void *ra)
833 if (!errflag) return 0;