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;
70 void __init_ssp(size_t *);
72 static struct dso *head, *tail, *libc;
73 static char *env_path, *sys_path, *r_path;
77 static jmp_buf rtld_fail;
78 static pthread_rwlock_t lock;
79 static struct debug debug;
81 struct debug *_dl_debug_addr = &debug;
86 static void decode_vec(size_t *v, size_t *a, size_t cnt)
88 memset(a, 0, cnt*sizeof(size_t));
89 for (; v[0]; v+=2) if (v[0]<cnt) {
95 static uint32_t hash(const char *s0)
97 const unsigned char *s = (void *)s0;
103 return h & 0xfffffff;
106 static Sym *lookup(const char *s, uint32_t h, Sym *syms, uint32_t *hashtab, char *strings)
109 for (i=hashtab[2+h%hashtab[0]]; i; i=hashtab[2+hashtab[0]+i]) {
110 if (!strcmp(s, strings+syms[i].st_name))
116 #define OK_TYPES (1<<STT_NOTYPE | 1<<STT_OBJECT | 1<<STT_FUNC | 1<<STT_COMMON)
117 #define OK_BINDS (1<<STB_GLOBAL | 1<<STB_WEAK)
119 static void *find_sym(struct dso *dso, const char *s, int need_def)
121 uint32_t h = hash(s);
123 if (h==0x6b366be && !strcmp(s, "dlopen")) rtld_used = 1;
124 if (h==0x6b3afd && !strcmp(s, "dlsym")) rtld_used = 1;
125 if (h==0x595a4cc && !strcmp(s, "__stack_chk_fail")) ssp_used = 1;
126 for (; dso; dso=dso->next) {
128 if (!dso->global) continue;
129 sym = lookup(s, h, dso->syms, dso->hashtab, dso->strings);
130 if (sym && (!need_def || sym->st_shndx) && sym->st_value
131 && (1<<(sym->st_info&0xf) & OK_TYPES)
132 && (1<<(sym->st_info>>4) & OK_BINDS)) {
133 if (def && sym->st_info>>4 == STB_WEAK) continue;
134 def = dso->base + sym->st_value;
135 if (sym->st_info>>4 == STB_GLOBAL) break;
141 static void do_relocs(unsigned char *base, size_t *rel, size_t rel_size, size_t stride, Sym *syms, char *strings, struct dso *dso)
145 size_t sym_val, sym_size;
151 for (; rel_size; rel+=stride, rel_size-=stride*sizeof(size_t)) {
152 reloc_addr = (void *)(base + rel[0]);
153 type = R_TYPE(rel[1]);
154 sym_index = R_SYM(rel[1]);
156 sym = syms + sym_index;
157 name = strings + sym->st_name;
158 ctx = IS_COPY(type) ? dso->next : dso;
159 sym_val = (size_t)find_sym(ctx, name, IS_PLT(type));
160 if (!sym_val && sym->st_info>>4 != STB_WEAK) {
161 snprintf(errbuf, sizeof errbuf,
162 "Error relocating %s: %s: symbol not found",
164 if (runtime) longjmp(rtld_fail, 1);
165 dprintf(2, "%s\n", errbuf);
168 sym_size = sym->st_size;
170 do_single_reloc(reloc_addr, type, sym_val, sym_size, base, rel[2]);
174 /* A huge hack: to make up for the wastefulness of shared libraries
175 * needing at least a page of dirty memory even if they have no global
176 * data, we reclaim the gaps at the beginning and end of writable maps
177 * and "donate" them to the heap by setting up minimal malloc
178 * structures and then freeing them. */
180 static void reclaim(unsigned char *base, size_t start, size_t end)
183 start = start + 6*sizeof(size_t)-1 & -4*sizeof(size_t);
184 end = (end & -4*sizeof(size_t)) - 2*sizeof(size_t);
185 if (start>end || end-start < 4*sizeof(size_t)) return;
186 a = (size_t *)(base + start);
187 z = (size_t *)(base + end);
189 a[-1] = z[0] = end-start + 2*sizeof(size_t) | 1;
194 static void reclaim_gaps(unsigned char *base, Phdr *ph, size_t phent, size_t phcnt)
196 for (; phcnt--; ph=(void *)((char *)ph+phent)) {
197 if (ph->p_type!=PT_LOAD) continue;
198 if ((ph->p_flags&(PF_R|PF_W))!=(PF_R|PF_W)) continue;
199 reclaim(base, ph->p_vaddr & -PAGE_SIZE, ph->p_vaddr);
200 reclaim(base, ph->p_vaddr+ph->p_memsz,
201 ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE);
205 static void *map_library(int fd, size_t *lenp, unsigned char **basep, size_t *dynp)
207 Ehdr buf[(896+sizeof(Ehdr))/sizeof(Ehdr)];
209 size_t addr_min=SIZE_MAX, addr_max=0, map_len;
210 size_t this_min, this_max;
215 unsigned char *map, *base;
219 ssize_t l = read(fd, buf, sizeof buf);
220 if (l<sizeof *eh) return 0;
222 phsize = eh->e_phentsize * eh->e_phnum;
223 if (phsize + sizeof *eh > l) return 0;
224 if (eh->e_phoff + phsize > l) {
225 l = pread(fd, buf+1, phsize, eh->e_phoff);
226 if (l != phsize) return 0;
227 eh->e_phoff = sizeof *eh;
229 ph = (void *)((char *)buf + eh->e_phoff);
230 for (i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
231 if (ph->p_type == PT_DYNAMIC)
233 if (ph->p_type != PT_LOAD) continue;
234 if (ph->p_vaddr < addr_min) {
235 addr_min = ph->p_vaddr;
236 off_start = ph->p_offset;
237 prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
238 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
239 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
241 if (ph->p_vaddr+ph->p_memsz > addr_max) {
242 addr_max = ph->p_vaddr+ph->p_memsz;
246 addr_max += PAGE_SIZE-1;
247 addr_max &= -PAGE_SIZE;
248 addr_min &= -PAGE_SIZE;
249 off_start &= -PAGE_SIZE;
250 map_len = addr_max - addr_min + off_start;
251 /* The first time, we map too much, possibly even more than
252 * the length of the file. This is okay because we will not
253 * use the invalid part; we just need to reserve the right
254 * amount of virtual address space to map over later. */
255 map = mmap((void *)addr_min, map_len, prot, MAP_PRIVATE, fd, off_start);
256 if (map==MAP_FAILED) return 0;
257 base = map - addr_min;
258 ph = (void *)((char *)buf + eh->e_phoff);
259 for (i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
260 if (ph->p_type != PT_LOAD) continue;
261 /* Reuse the existing mapping for the lowest-address LOAD */
262 if ((ph->p_vaddr & -PAGE_SIZE) == addr_min) continue;
263 this_min = ph->p_vaddr & -PAGE_SIZE;
264 this_max = ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE;
265 off_start = ph->p_offset & -PAGE_SIZE;
266 prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
267 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
268 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
269 if (mmap(base+this_min, this_max-this_min, prot, MAP_PRIVATE|MAP_FIXED, fd, off_start) == MAP_FAILED) {
270 munmap(map, map_len);
273 if (ph->p_memsz > ph->p_filesz) {
274 size_t brk = (size_t)base+ph->p_vaddr+ph->p_filesz;
275 size_t pgbrk = brk+PAGE_SIZE-1 & -PAGE_SIZE;
276 memset((void *)brk, 0, pgbrk-brk & PAGE_SIZE-1);
277 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) {
278 munmap(map, map_len);
283 for (i=0; ((size_t *)(base+dyn))[i]; i+=2)
284 if (((size_t *)(base+dyn))[i]==DT_TEXTREL) {
285 mprotect(map, map_len, PROT_READ|PROT_WRITE|PROT_EXEC);
288 if (!runtime) reclaim_gaps(base, (void *)((char *)buf + eh->e_phoff),
289 eh->e_phentsize, eh->e_phnum);
296 static int path_open(const char *name, const char *search)
298 char buf[2*NAME_MAX+2];
299 const char *s=search, *z;
305 l = z ? z-s : strlen(s);
306 snprintf(buf, sizeof buf, "%.*s/%s", l, s, name);
307 if ((fd = open(buf, O_RDONLY))>=0) return fd;
312 static void decode_dyn(struct dso *p)
314 size_t dyn[DYN_CNT] = {0};
315 decode_vec(p->dynv, dyn, DYN_CNT);
316 p->syms = (void *)(p->base + dyn[DT_SYMTAB]);
317 p->hashtab = (void *)(p->base + dyn[DT_HASH]);
318 p->strings = (void *)(p->base + dyn[DT_STRTAB]);
321 static struct dso *load_library(const char *name)
323 unsigned char *base, *map;
324 size_t dyno, map_len;
329 /* Catch and block attempts to reload the implementation itself */
330 if (name[0]=='l' && name[1]=='i' && name[2]=='b') {
331 static const char *rp, reserved[] =
332 "c\0pthread\0rt\0m\0dl\0util\0xnet\0";
333 char *z = strchr(name, '.');
336 for (rp=reserved; *rp && memcmp(name+3, rp, l-3); rp+=strlen(rp)+1);
341 tail = libc->next ? libc->next : libc;
347 /* Search for the name to see if it's already loaded */
348 for (p=head->next; p; p=p->next) {
349 if (!strcmp(p->name, name)) {
354 if (strchr(name, '/')) {
355 fd = open(name, O_RDONLY);
357 if (strlen(name) > NAME_MAX) return 0;
359 if (r_path) fd = path_open(name, r_path);
360 if (fd < 0 && env_path) fd = path_open(name, env_path);
363 FILE *f = fopen(ETC_LDSO_PATH, "r");
365 if (getline(&sys_path, (size_t[1]){0}, f) > 0)
366 sys_path[strlen(sys_path)-1]=0;
370 if (sys_path) fd = path_open(name, sys_path);
371 else fd = path_open(name, "/lib:/usr/local/lib:/usr/lib");
374 if (fd < 0) return 0;
375 if (fstat(fd, &st) < 0) {
379 for (p=head->next; p; p=p->next) {
380 if (p->dev == st.st_dev && p->ino == st.st_ino) {
386 map = map_library(fd, &map_len, &base, &dyno);
389 p = calloc(1, sizeof *p + strlen(name) + 1);
391 munmap(map, map_len);
396 p->map_len = map_len;
398 p->dynv = (void *)(base + dyno);
405 strcpy(p->name, name);
414 static void load_deps(struct dso *p)
417 struct dso ***deps = &p->deps, **tmp, *dep;
418 for (; p; p=p->next) {
419 for (i=0; p->dynv[i]; i+=2) {
420 if (p->dynv[i] != DT_RPATH) continue;
421 r_path = (void *)(p->strings + p->dynv[i+1]);
423 for (i=0; p->dynv[i]; i+=2) {
424 if (p->dynv[i] != DT_NEEDED) continue;
425 dep = load_library(p->strings + p->dynv[i+1]);
427 snprintf(errbuf, sizeof errbuf,
428 "Error loading shared library %s: %m (needed by %s)",
429 p->strings + p->dynv[i+1], p->name);
430 if (runtime) longjmp(rtld_fail, 1);
431 dprintf(2, "%s\n", errbuf);
435 tmp = realloc(*deps, sizeof(*tmp)*(ndeps+2));
436 if (!tmp) longjmp(rtld_fail, 1);
446 static void load_preload(char *s)
451 for ( ; *s && isspace(*s); s++);
452 for (z=s; *z && !isspace(*z); z++);
460 static void make_global(struct dso *p)
462 for (; p; p=p->next) p->global = 1;
465 static void reloc_all(struct dso *p)
467 size_t dyn[DYN_CNT] = {0};
468 for (; p; p=p->next) {
469 if (p->relocated) continue;
470 decode_vec(p->dynv, dyn, DYN_CNT);
471 do_relocs(p->base, (void *)(p->base+dyn[DT_JMPREL]), dyn[DT_PLTRELSZ],
472 2+(dyn[DT_PLTREL]==DT_RELA), p->syms, p->strings, head);
473 do_relocs(p->base, (void *)(p->base+dyn[DT_REL]), dyn[DT_RELSZ],
474 2, p->syms, p->strings, head);
475 do_relocs(p->base, (void *)(p->base+dyn[DT_RELA]), dyn[DT_RELASZ],
476 3, p->syms, p->strings, head);
481 static void free_all(struct dso *p)
491 static size_t find_dyn(Phdr *ph, size_t cnt, size_t stride)
493 for (; cnt--; ph = (void *)((char *)ph + stride))
494 if (ph->p_type == PT_DYNAMIC)
499 static void do_init_fini(struct dso *p)
501 size_t dyn[DYN_CNT] = {0};
502 for (; p; p=p->prev) {
503 if (p->constructed) return;
504 decode_vec(p->dynv, dyn, DYN_CNT);
505 if (dyn[0] & (1<<DT_FINI))
506 atexit((void (*)(void))(p->base + dyn[DT_FINI]));
507 if (dyn[0] & (1<<DT_INIT))
508 ((void (*)(void))(p->base + dyn[DT_INIT]))();
513 void _dl_debug_state(void)
517 void *__dynlink(int argc, char **argv)
519 size_t *auxv, aux[AUX_CNT] = {0};
523 static struct dso builtin_dsos[3];
524 struct dso *const app = builtin_dsos+0;
525 struct dso *const lib = builtin_dsos+1;
526 struct dso *const vdso = builtin_dsos+2;
529 /* Find aux vector just past environ[] */
530 for (i=argc+1; argv[i]; i++)
531 if (!memcmp(argv[i], "LD_LIBRARY_PATH=", 16))
532 env_path = argv[i]+16;
533 else if (!memcmp(argv[i], "LD_PRELOAD=", 11))
534 env_preload = argv[i]+11;
535 auxv = (void *)(argv+i+1);
537 decode_vec(auxv, aux, AUX_CNT);
539 /* Only trust user/env if kernel says we're not suid/sgid */
540 if ((aux[0]&0x7800)!=0x7800 || aux[AT_UID]!=aux[AT_EUID]
541 || aux[AT_GID]!=aux[AT_EGID] || aux[AT_SECURE]) {
546 /* The dynamic linker load address is passed by the kernel
547 * in the AUX vector, so this is easy. */
548 lib->base = (void *)aux[AT_BASE];
549 lib->name = "libc.so";
551 ehdr = (void *)lib->base;
552 lib->dynv = (void *)(lib->base + find_dyn(
553 (void *)(aux[AT_BASE]+ehdr->e_phoff),
554 ehdr->e_phnum, ehdr->e_phentsize));
557 /* Find load address of the main program, via AT_PHDR vs PT_PHDR. */
559 phdr = (void *)aux[AT_PHDR];
560 for (i=aux[AT_PHNUM]; i; i--, phdr=(void *)((char *)phdr + aux[AT_PHENT])) {
561 if (phdr->p_type == PT_PHDR)
562 app->base = (void *)(aux[AT_PHDR] - phdr->p_vaddr);
566 app->constructed = 1;
567 app->dynv = (void *)(app->base + find_dyn(
568 (void *)aux[AT_PHDR], aux[AT_PHNUM], aux[AT_PHENT]));
571 /* Attach to vdso, if provided by the kernel */
572 for (i=0; auxv[i]; i+=2) {
573 size_t vdso_base = auxv[i+1];
574 if (auxv[i] != AT_SYSINFO_EHDR) continue;
575 ehdr = (void *)vdso_base;
576 phdr = (void *)(vdso_base + ehdr->e_phoff);
577 for (i=ehdr->e_phnum; i; i--, phdr=(void *)((char *)phdr + ehdr->e_phentsize)) {
578 if (phdr->p_type == PT_DYNAMIC)
579 vdso->dynv = (void *)(vdso_base + phdr->p_offset);
580 if (phdr->p_type == PT_LOAD)
581 vdso->base = (void *)(vdso_base - phdr->p_vaddr + phdr->p_offset);
583 vdso->name = "linux-gate.so.1";
591 /* Initial dso chain consists only of the app. We temporarily
592 * append the dynamic linker/libc so we can relocate it, then
593 * restore the initial chain in preparation for loading third
594 * party libraries (preload/needed). */
601 /* PAST THIS POINT, ALL LIBC INTERFACES ARE FULLY USABLE. */
603 /* Donate unused parts of app and library mapping to malloc */
604 reclaim_gaps(app->base, (void *)aux[AT_PHDR], aux[AT_PHENT], aux[AT_PHNUM]);
605 ehdr = (void *)lib->base;
606 reclaim_gaps(lib->base, (void *)(lib->base+ehdr->e_phoff),
607 ehdr->e_phentsize, ehdr->e_phnum);
609 /* Load preload/needed libraries, add their symbols to the global
610 * namespace, and perform all remaining relocations. The main
611 * program must be relocated LAST since it may contain copy
612 * relocations which depend on libraries' relocations. */
613 if (env_preload) load_preload(env_preload);
616 reloc_all(app->next);
619 /* Switch to runtime mode: any further failures in the dynamic
620 * linker are a reportable failure rather than a fatal startup
621 * error. If the dynamic loader (dlopen) will not be used, free
622 * all memory used by the dynamic linker. */
625 for (i=0; app->dynv[i]; i+=2)
626 if (app->dynv[i]==DT_DEBUG)
627 app->dynv[i+1] = (size_t)&debug;
629 debug.bp = _dl_debug_state;
631 debug.base = lib->base;
635 if (ssp_used) __init_ssp(auxv);
642 reclaim((void *)builtin_dsos, 0, sizeof builtin_dsos);
646 return (void *)aux[AT_ENTRY];
649 void *dlopen(const char *file, int mode)
651 struct dso *volatile p, *orig_tail = tail, *next;
655 if (!file) return head;
657 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
658 pthread_rwlock_wrlock(&lock);
660 if (setjmp(rtld_fail)) {
661 /* Clean up anything new that was (partially) loaded */
662 if (p->deps) for (i=0; p->deps[i]; i++)
663 if (p->deps[i]->global < 0)
664 p->deps[i]->global = 0;
665 for (p=orig_tail->next; p; p=next) {
667 munmap(p->map, p->map_len);
676 } else p = load_library(file);
679 snprintf(errbuf, sizeof errbuf,
680 "Error loading shared library %s: %m", file);
685 /* First load handling */
688 if (p->deps) for (i=0; p->deps[i]; i++)
689 if (!p->deps[i]->global)
690 p->deps[i]->global = -1;
691 if (!p->global) p->global = -1;
693 if (p->deps) for (i=0; p->deps[i]; i++)
694 if (p->deps[i]->global < 0)
695 p->deps[i]->global = 0;
696 if (p->global < 0) p->global = 0;
699 if (mode & RTLD_GLOBAL) {
700 if (p->deps) for (i=0; p->deps[i]; i++)
701 p->deps[i]->global = 1;
709 pthread_rwlock_unlock(&lock);
710 pthread_setcancelstate(cs, 0);
714 static void *do_dlsym(struct dso *p, const char *s, void *ra)
719 if (p == RTLD_NEXT) {
720 for (p=head; p && (unsigned char *)ra-p->map>p->map_len; p=p->next);
724 if (p == head || p == RTLD_DEFAULT) {
725 void *res = find_sym(head, s, 0);
726 if (!res) goto failed;
730 sym = lookup(s, h, p->syms, p->hashtab, p->strings);
731 if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
732 return p->base + sym->st_value;
733 if (p->deps) for (i=0; p->deps[i]; i++) {
734 sym = lookup(s, h, p->deps[i]->syms,
735 p->deps[i]->hashtab, p->deps[i]->strings);
736 if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
737 return p->deps[i]->base + sym->st_value;
741 snprintf(errbuf, sizeof errbuf, "Symbol not found: %s", s);
745 void *__dlsym(void *p, const char *s, void *ra)
748 pthread_rwlock_rdlock(&lock);
749 res = do_dlsym(p, s, ra);
750 pthread_rwlock_unlock(&lock);
754 void *dlopen(const char *file, int mode)
758 void *__dlsym(void *p, const char *s, void *ra)
766 if (!errflag) return 0;