21 static char errbuf[128];
25 #if ULONG_MAX == 0xffffffff
26 typedef Elf32_Ehdr Ehdr;
27 typedef Elf32_Phdr Phdr;
28 typedef Elf32_Sym Sym;
29 #define R_TYPE(x) ((x)&255)
30 #define R_SYM(x) ((x)>>8)
32 typedef Elf64_Ehdr Ehdr;
33 typedef Elf64_Phdr Phdr;
34 typedef Elf64_Sym Sym;
35 #define R_TYPE(x) ((x)&0xffffffff)
36 #define R_SYM(x) ((x)>>32)
51 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;
80 static jmp_buf rtld_fail;
81 static pthread_rwlock_t lock;
82 static struct debug debug;
84 struct debug *_dl_debug_addr = &debug;
89 static void decode_vec(size_t *v, size_t *a, size_t cnt)
91 memset(a, 0, cnt*sizeof(size_t));
92 for (; v[0]; v+=2) if (v[0]<cnt) {
98 static uint32_t hash(const char *s0)
100 const unsigned char *s = (void *)s0;
106 return h & 0xfffffff;
109 static Sym *lookup(const char *s, uint32_t h, struct dso *dso)
112 Sym *syms = dso->syms;
113 uint32_t *hashtab = dso->hashtab;
114 char *strings = dso->strings;
115 for (i=hashtab[2+h%hashtab[0]]; i; i=hashtab[2+hashtab[0]+i]) {
116 if (!strcmp(s, strings+syms[i].st_name))
122 #define OK_TYPES (1<<STT_NOTYPE | 1<<STT_OBJECT | 1<<STT_FUNC | 1<<STT_COMMON)
123 #define OK_BINDS (1<<STB_GLOBAL | 1<<STB_WEAK)
125 static void *find_sym(struct dso *dso, const char *s, int need_def)
127 uint32_t h = hash(s);
129 if (h==0x6b366be && !strcmp(s, "dlopen")) rtld_used = 1;
130 if (h==0x6b3afd && !strcmp(s, "dlsym")) rtld_used = 1;
131 if (h==0x595a4cc && !strcmp(s, "__stack_chk_fail")) ssp_used = 1;
132 for (; dso; dso=dso->next) {
134 if (!dso->global) continue;
135 sym = lookup(s, h, dso);
136 if (sym && (!need_def || sym->st_shndx) && sym->st_value
137 && (1<<(sym->st_info&0xf) & OK_TYPES)
138 && (1<<(sym->st_info>>4) & OK_BINDS)) {
139 if (def && sym->st_info>>4 == STB_WEAK) continue;
140 def = dso->base + sym->st_value;
141 if (sym->st_info>>4 == STB_GLOBAL) break;
147 static void do_relocs(struct dso *dso, size_t *rel, size_t rel_size, size_t stride)
149 unsigned char *base = dso->base;
150 Sym *syms = dso->syms;
151 char *strings = dso->strings;
154 size_t sym_val, sym_size;
160 for (; rel_size; rel+=stride, rel_size-=stride*sizeof(size_t)) {
161 reloc_addr = (void *)(base + rel[0]);
162 type = R_TYPE(rel[1]);
163 sym_index = R_SYM(rel[1]);
165 sym = syms + sym_index;
166 name = strings + sym->st_name;
167 ctx = IS_COPY(type) ? head->next : head;
168 sym_val = (size_t)find_sym(ctx, name, IS_PLT(type));
169 if (!sym_val && sym->st_info>>4 != STB_WEAK) {
170 snprintf(errbuf, sizeof errbuf,
171 "Error relocating %s: %s: symbol not found",
173 if (runtime) longjmp(rtld_fail, 1);
174 dprintf(2, "%s\n", errbuf);
178 sym_size = sym->st_size;
180 sym_val = sym_size = 0;
182 do_single_reloc(reloc_addr, type, sym_val, sym_size, base, rel[2]);
186 /* A huge hack: to make up for the wastefulness of shared libraries
187 * needing at least a page of dirty memory even if they have no global
188 * data, we reclaim the gaps at the beginning and end of writable maps
189 * and "donate" them to the heap by setting up minimal malloc
190 * structures and then freeing them. */
192 static void reclaim(unsigned char *base, size_t start, size_t end)
195 start = start + 6*sizeof(size_t)-1 & -4*sizeof(size_t);
196 end = (end & -4*sizeof(size_t)) - 2*sizeof(size_t);
197 if (start>end || end-start < 4*sizeof(size_t)) return;
198 a = (size_t *)(base + start);
199 z = (size_t *)(base + end);
201 a[-1] = z[0] = end-start + 2*sizeof(size_t) | 1;
206 static void reclaim_gaps(unsigned char *base, Phdr *ph, size_t phent, size_t phcnt)
208 for (; phcnt--; ph=(void *)((char *)ph+phent)) {
209 if (ph->p_type!=PT_LOAD) continue;
210 if ((ph->p_flags&(PF_R|PF_W))!=(PF_R|PF_W)) continue;
211 reclaim(base, ph->p_vaddr & -PAGE_SIZE, ph->p_vaddr);
212 reclaim(base, ph->p_vaddr+ph->p_memsz,
213 ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE);
217 static void *map_library(int fd, size_t *lenp, unsigned char **basep, size_t *dynp)
219 Ehdr buf[(896+sizeof(Ehdr))/sizeof(Ehdr)];
221 size_t addr_min=SIZE_MAX, addr_max=0, map_len;
222 size_t this_min, this_max;
227 unsigned char *map, *base;
231 ssize_t l = read(fd, buf, sizeof buf);
232 if (l<sizeof *eh) return 0;
234 phsize = eh->e_phentsize * eh->e_phnum;
235 if (phsize + sizeof *eh > l) return 0;
236 if (eh->e_phoff + phsize > l) {
237 l = pread(fd, buf+1, phsize, eh->e_phoff);
238 if (l != phsize) return 0;
239 eh->e_phoff = sizeof *eh;
241 ph = (void *)((char *)buf + eh->e_phoff);
242 for (i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
243 if (ph->p_type == PT_DYNAMIC)
245 if (ph->p_type != PT_LOAD) continue;
246 if (ph->p_vaddr < addr_min) {
247 addr_min = ph->p_vaddr;
248 off_start = ph->p_offset;
249 prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
250 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
251 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
253 if (ph->p_vaddr+ph->p_memsz > addr_max) {
254 addr_max = ph->p_vaddr+ph->p_memsz;
258 addr_max += PAGE_SIZE-1;
259 addr_max &= -PAGE_SIZE;
260 addr_min &= -PAGE_SIZE;
261 off_start &= -PAGE_SIZE;
262 map_len = addr_max - addr_min + off_start;
263 /* The first time, we map too much, possibly even more than
264 * the length of the file. This is okay because we will not
265 * use the invalid part; we just need to reserve the right
266 * amount of virtual address space to map over later. */
267 map = mmap((void *)addr_min, map_len, prot, MAP_PRIVATE, fd, off_start);
268 if (map==MAP_FAILED) return 0;
269 base = map - addr_min;
270 ph = (void *)((char *)buf + eh->e_phoff);
271 for (i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
272 if (ph->p_type != PT_LOAD) continue;
273 /* Reuse the existing mapping for the lowest-address LOAD */
274 if ((ph->p_vaddr & -PAGE_SIZE) == addr_min) continue;
275 this_min = ph->p_vaddr & -PAGE_SIZE;
276 this_max = ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE;
277 off_start = ph->p_offset & -PAGE_SIZE;
278 prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
279 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
280 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
281 if (mmap(base+this_min, this_max-this_min, prot, MAP_PRIVATE|MAP_FIXED, fd, off_start) == MAP_FAILED)
283 if (ph->p_memsz > ph->p_filesz) {
284 size_t brk = (size_t)base+ph->p_vaddr+ph->p_filesz;
285 size_t pgbrk = brk+PAGE_SIZE-1 & -PAGE_SIZE;
286 memset((void *)brk, 0, pgbrk-brk & PAGE_SIZE-1);
287 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)
291 for (i=0; ((size_t *)(base+dyn))[i]; i+=2)
292 if (((size_t *)(base+dyn))[i]==DT_TEXTREL) {
293 if (mprotect(map, map_len, PROT_READ|PROT_WRITE|PROT_EXEC) < 0)
297 if (!runtime) reclaim_gaps(base, (void *)((char *)buf + eh->e_phoff),
298 eh->e_phentsize, eh->e_phnum);
304 munmap(map, map_len);
308 static int path_open(const char *name, const char *search, char *buf, size_t buf_size)
310 const char *s=search, *z;
316 l = z ? z-s : strlen(s);
317 snprintf(buf, buf_size, "%.*s/%s", l, s, name);
318 if ((fd = open(buf, O_RDONLY))>=0) return fd;
323 static void decode_dyn(struct dso *p)
325 size_t dyn[DYN_CNT] = {0};
326 decode_vec(p->dynv, dyn, DYN_CNT);
327 p->syms = (void *)(p->base + dyn[DT_SYMTAB]);
328 p->hashtab = (void *)(p->base + dyn[DT_HASH]);
329 p->strings = (void *)(p->base + dyn[DT_STRTAB]);
332 static struct dso *load_library(const char *name)
334 char buf[2*NAME_MAX+2];
335 const char *pathname;
336 unsigned char *base, *map;
337 size_t dyno, map_len;
342 /* Catch and block attempts to reload the implementation itself */
343 if (name[0]=='l' && name[1]=='i' && name[2]=='b') {
344 static const char *rp, reserved[] =
345 "c\0pthread\0rt\0m\0dl\0util\0xnet\0";
346 char *z = strchr(name, '.');
349 for (rp=reserved; *rp && memcmp(name+3, rp, l-3); rp+=strlen(rp)+1);
354 tail = libc->next ? libc->next : libc;
360 if (strchr(name, '/')) {
362 fd = open(name, O_RDONLY);
364 /* Search for the name to see if it's already loaded */
365 for (p=head->next; p; p=p->next) {
366 if (p->shortname && !strcmp(p->shortname, name)) {
371 if (strlen(name) > NAME_MAX) return 0;
373 if (r_path) fd = path_open(name, r_path, buf, sizeof buf);
374 if (fd < 0 && env_path) fd = path_open(name, env_path, buf, sizeof buf);
377 FILE *f = fopen(ETC_LDSO_PATH, "r");
379 if (getline(&sys_path, (size_t[1]){0}, f) > 0)
380 sys_path[strlen(sys_path)-1]=0;
384 if (sys_path) fd = path_open(name, sys_path, buf, sizeof buf);
385 else fd = path_open(name, "/lib:/usr/local/lib:/usr/lib", buf, sizeof buf);
389 if (fd < 0) return 0;
390 if (fstat(fd, &st) < 0) {
394 for (p=head->next; p; p=p->next) {
395 if (p->dev == st.st_dev && p->ino == st.st_ino) {
396 /* If this library was previously loaded with a
397 * pathname but a search found the same inode,
398 * setup its shortname so it can be found by name. */
399 if (!p->shortname) p->shortname = strrchr(p->name, '/')+1;
405 map = map_library(fd, &map_len, &base, &dyno);
408 p = calloc(1, sizeof *p + strlen(pathname) + 1);
410 munmap(map, map_len);
415 p->map_len = map_len;
417 p->dynv = (void *)(base + dyno);
424 strcpy(p->name, pathname);
425 /* Add a shortname only if name arg was not an explicit pathname. */
426 if (pathname != name) p->shortname = strrchr(p->name, '/')+1;
432 if (ldd_mode) dprintf(1, "\t%s => %s (%p)\n", name, pathname, base);
437 static void load_deps(struct dso *p)
440 struct dso ***deps = &p->deps, **tmp, *dep;
441 for (; p; p=p->next) {
442 for (i=0; p->dynv[i]; i+=2) {
443 if (p->dynv[i] != DT_RPATH) continue;
444 r_path = (void *)(p->strings + p->dynv[i+1]);
446 for (i=0; p->dynv[i]; i+=2) {
447 if (p->dynv[i] != DT_NEEDED) continue;
448 dep = load_library(p->strings + p->dynv[i+1]);
450 snprintf(errbuf, sizeof errbuf,
451 "Error loading shared library %s: %m (needed by %s)",
452 p->strings + p->dynv[i+1], p->name);
453 if (runtime) longjmp(rtld_fail, 1);
454 dprintf(2, "%s\n", errbuf);
459 tmp = realloc(*deps, sizeof(*tmp)*(ndeps+2));
460 if (!tmp) longjmp(rtld_fail, 1);
470 static void load_preload(char *s)
475 for ( ; *s && isspace(*s); s++);
476 for (z=s; *z && !isspace(*z); z++);
484 static void make_global(struct dso *p)
486 for (; p; p=p->next) p->global = 1;
489 static void reloc_all(struct dso *p)
491 size_t dyn[DYN_CNT] = {0};
492 for (; p; p=p->next) {
493 if (p->relocated) continue;
494 decode_vec(p->dynv, dyn, DYN_CNT);
495 #ifdef NEED_ARCH_RELOCS
496 do_arch_relocs(p, head);
498 do_relocs(p, (void *)(p->base+dyn[DT_JMPREL]), dyn[DT_PLTRELSZ],
499 2+(dyn[DT_PLTREL]==DT_RELA));
500 do_relocs(p, (void *)(p->base+dyn[DT_REL]), dyn[DT_RELSZ], 2);
501 do_relocs(p, (void *)(p->base+dyn[DT_RELA]), dyn[DT_RELASZ], 3);
506 static void free_all(struct dso *p)
516 static size_t find_dyn(Phdr *ph, size_t cnt, size_t stride)
518 for (; cnt--; ph = (void *)((char *)ph + stride))
519 if (ph->p_type == PT_DYNAMIC)
524 static void do_init_fini(struct dso *p)
526 size_t dyn[DYN_CNT] = {0};
527 for (; p; p=p->prev) {
528 if (p->constructed) return;
529 decode_vec(p->dynv, dyn, DYN_CNT);
530 if (dyn[0] & (1<<DT_FINI))
531 atexit((void (*)(void))(p->base + dyn[DT_FINI]));
532 if (dyn[0] & (1<<DT_INIT))
533 ((void (*)(void))(p->base + dyn[DT_INIT]))();
538 void _dl_debug_state(void)
542 void *__dynlink(int argc, char **argv)
544 size_t *auxv, aux[AUX_CNT] = {0};
548 static struct dso builtin_dsos[3];
549 struct dso *const app = builtin_dsos+0;
550 struct dso *const lib = builtin_dsos+1;
551 struct dso *const vdso = builtin_dsos+2;
554 /* Find aux vector just past environ[] */
555 for (i=argc+1; argv[i]; i++)
556 if (!memcmp(argv[i], "LD_LIBRARY_PATH=", 16))
557 env_path = argv[i]+16;
558 else if (!memcmp(argv[i], "LD_PRELOAD=", 11))
559 env_preload = argv[i]+11;
560 auxv = (void *)(argv+i+1);
562 decode_vec(auxv, aux, AUX_CNT);
564 /* Only trust user/env if kernel says we're not suid/sgid */
565 if ((aux[0]&0x7800)!=0x7800 || aux[AT_UID]!=aux[AT_EUID]
566 || aux[AT_GID]!=aux[AT_EGID] || aux[AT_SECURE]) {
571 /* If the dynamic linker was invoked as a program itself, AT_BASE
572 * will not be set. In that case, we assume the base address is
573 * the start of the page containing the PHDRs; I don't know any
574 * better approach... */
576 aux[AT_BASE] = aux[AT_PHDR] & -PAGE_SIZE;
577 aux[AT_PHDR] = aux[AT_PHENT] = aux[AT_PHNUM] = 0;
580 /* The dynamic linker load address is passed by the kernel
581 * in the AUX vector, so this is easy. */
582 lib->base = (void *)aux[AT_BASE];
583 lib->name = lib->shortname = "libc.so";
585 ehdr = (void *)lib->base;
586 lib->dynv = (void *)(lib->base + find_dyn(
587 (void *)(aux[AT_BASE]+ehdr->e_phoff),
588 ehdr->e_phnum, ehdr->e_phentsize));
592 size_t interp_off = 0;
593 /* Find load address of the main program, via AT_PHDR vs PT_PHDR. */
594 phdr = (void *)aux[AT_PHDR];
595 for (i=aux[AT_PHNUM]; i; i--, phdr=(void *)((char *)phdr + aux[AT_PHENT])) {
596 if (phdr->p_type == PT_PHDR)
597 app->base = (void *)(aux[AT_PHDR] - phdr->p_vaddr);
598 else if (phdr->p_type == PT_INTERP)
599 interp_off = (size_t)phdr->p_vaddr;
601 if (interp_off) lib->name = (char *)app->base + interp_off;
603 app->dynv = (void *)(app->base + find_dyn(
604 (void *)aux[AT_PHDR], aux[AT_PHNUM], aux[AT_PHENT]));
607 char *ldname = argv[0];
608 size_t dyno, l = strlen(ldname);
609 if (l >= 3 && !strcmp(ldname+l-3, "ldd")) ldd_mode = 1;
610 *argv++ = (void *)-1;
611 if (argv[0] && !strcmp(argv[0], "--")) *argv++ = (void *)-1;
613 dprintf(2, "musl libc/dynamic program loader\n");
614 dprintf(2, "usage: %s pathname%s\n", ldname,
615 ldd_mode ? "" : " [args]");
618 fd = open(argv[0], O_RDONLY);
620 dprintf(2, "%s: cannot load %s: %s\n", ldname, argv[0], strerror(errno));
624 ehdr = (void *)map_library(fd, &app->map_len, &app->base, &dyno);
626 dprintf(2, "%s: %s: Not a valid dynamic program\n", ldname, argv[0]);
633 app->dynv = (void *)(app->base + dyno);
634 aux[AT_ENTRY] = ehdr->e_entry;
637 app->constructed = 1;
640 /* Attach to vdso, if provided by the kernel */
641 for (i=0; auxv[i]; i+=2) {
642 size_t vdso_base = auxv[i+1];
643 if (auxv[i] != AT_SYSINFO_EHDR) continue;
644 ehdr = (void *)vdso_base;
645 phdr = (void *)(vdso_base + ehdr->e_phoff);
646 for (i=ehdr->e_phnum; i; i--, phdr=(void *)((char *)phdr + ehdr->e_phentsize)) {
647 if (phdr->p_type == PT_DYNAMIC)
648 vdso->dynv = (void *)(vdso_base + phdr->p_offset);
649 if (phdr->p_type == PT_LOAD)
650 vdso->base = (void *)(vdso_base - phdr->p_vaddr + phdr->p_offset);
652 vdso->name = vdso->shortname = "linux-gate.so.1";
660 /* Initial dso chain consists only of the app. We temporarily
661 * append the dynamic linker/libc so we can relocate it, then
662 * restore the initial chain in preparation for loading third
663 * party libraries (preload/needed). */
670 /* PAST THIS POINT, ALL LIBC INTERFACES ARE FULLY USABLE. */
672 /* Donate unused parts of app and library mapping to malloc */
673 reclaim_gaps(app->base, (void *)aux[AT_PHDR], aux[AT_PHENT], aux[AT_PHNUM]);
674 ehdr = (void *)lib->base;
675 reclaim_gaps(lib->base, (void *)(lib->base+ehdr->e_phoff),
676 ehdr->e_phentsize, ehdr->e_phnum);
678 /* Load preload/needed libraries, add their symbols to the global
679 * namespace, and perform all remaining relocations. The main
680 * program must be relocated LAST since it may contain copy
681 * relocations which depend on libraries' relocations. */
682 if (env_preload) load_preload(env_preload);
685 reloc_all(app->next);
688 if (ldso_fail) _exit(127);
689 if (ldd_mode) _exit(0);
691 /* Switch to runtime mode: any further failures in the dynamic
692 * linker are a reportable failure rather than a fatal startup
693 * error. If the dynamic loader (dlopen) will not be used, free
694 * all memory used by the dynamic linker. */
697 #ifndef DYNAMIC_IS_RO
698 for (i=0; app->dynv[i]; i+=2)
699 if (app->dynv[i]==DT_DEBUG)
700 app->dynv[i+1] = (size_t)&debug;
703 debug.bp = _dl_debug_state;
705 debug.base = lib->base;
709 if (ssp_used) __init_ssp(auxv);
716 reclaim((void *)builtin_dsos, 0, sizeof builtin_dsos);
720 return (void *)aux[AT_ENTRY];
723 void *dlopen(const char *file, int mode)
725 struct dso *volatile p, *orig_tail = tail, *next;
729 if (!file) return head;
731 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
732 pthread_rwlock_wrlock(&lock);
734 if (setjmp(rtld_fail)) {
735 /* Clean up anything new that was (partially) loaded */
736 if (p->deps) for (i=0; p->deps[i]; i++)
737 if (p->deps[i]->global < 0)
738 p->deps[i]->global = 0;
739 for (p=orig_tail->next; p; p=next) {
741 munmap(p->map, p->map_len);
750 } else p = load_library(file);
753 snprintf(errbuf, sizeof errbuf,
754 "Error loading shared library %s: %m", file);
759 /* First load handling */
762 if (p->deps) for (i=0; p->deps[i]; i++)
763 if (!p->deps[i]->global)
764 p->deps[i]->global = -1;
765 if (!p->global) p->global = -1;
767 if (p->deps) for (i=0; p->deps[i]; i++)
768 if (p->deps[i]->global < 0)
769 p->deps[i]->global = 0;
770 if (p->global < 0) p->global = 0;
773 if (mode & RTLD_GLOBAL) {
774 if (p->deps) for (i=0; p->deps[i]; i++)
775 p->deps[i]->global = 1;
783 pthread_rwlock_unlock(&lock);
784 pthread_setcancelstate(cs, 0);
788 static void *do_dlsym(struct dso *p, const char *s, void *ra)
793 if (p == RTLD_NEXT) {
794 for (p=head; p && (unsigned char *)ra-p->map>p->map_len; p=p->next);
796 void *res = find_sym(p->next, s, 0);
797 if (!res) goto failed;
800 if (p == head || p == RTLD_DEFAULT) {
801 void *res = find_sym(head, s, 0);
802 if (!res) goto failed;
806 sym = lookup(s, h, p);
807 if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
808 return p->base + sym->st_value;
809 if (p->deps) for (i=0; p->deps[i]; i++) {
810 sym = lookup(s, h, p->deps[i]);
811 if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
812 return p->deps[i]->base + sym->st_value;
816 snprintf(errbuf, sizeof errbuf, "Symbol not found: %s", s);
820 void *__dlsym(void *p, const char *s, void *ra)
823 pthread_rwlock_rdlock(&lock);
824 res = do_dlsym(p, s, ra);
825 pthread_rwlock_unlock(&lock);
829 void *dlopen(const char *file, int mode)
833 void *__dlsym(void *p, const char *s, void *ra)
841 if (!errflag) return 0;