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)
42 struct dso *next, *prev;
61 static struct dso *head, *tail, *libc;
62 static char *env_path, *sys_path, *r_path;
65 static jmp_buf rtld_fail;
66 static pthread_rwlock_t lock;
71 static void decode_vec(size_t *v, size_t *a, size_t cnt)
73 memset(a, 0, cnt*sizeof(size_t));
74 for (; v[0]; v+=2) if (v[0]<cnt) {
80 static uint32_t hash(const char *s0)
82 const unsigned char *s = (void *)s0;
91 static Sym *lookup(const char *s, uint32_t h, Sym *syms, uint32_t *hashtab, char *strings)
94 for (i=hashtab[2+h%hashtab[0]]; i; i=hashtab[2+hashtab[0]+i]) {
95 if (!strcmp(s, strings+syms[i].st_name))
101 #define OK_TYPES (1<<STT_NOTYPE | 1<<STT_OBJECT | 1<<STT_FUNC | 1<<STT_COMMON)
102 #define OK_BINDS (1<<STB_GLOBAL | 1<<STB_WEAK)
104 static void *find_sym(struct dso *dso, const char *s, int need_def)
106 uint32_t h = hash(s);
108 if (h==0x6b366be && !strcmp(s, "dlopen")) rtld_used = 1;
109 if (h==0x6b3afd && !strcmp(s, "dlsym")) rtld_used = 1;
110 for (; dso; dso=dso->next) {
112 if (!dso->global) continue;
113 sym = lookup(s, h, dso->syms, dso->hashtab, dso->strings);
114 if (sym && (!need_def || sym->st_shndx) && sym->st_value
115 && (1<<(sym->st_info&0xf) & OK_TYPES)
116 && (1<<(sym->st_info>>4) & OK_BINDS)) {
117 if (def && sym->st_info>>4 == STB_WEAK) continue;
118 def = dso->base + sym->st_value;
119 if (sym->st_info>>4 == STB_GLOBAL) break;
125 static void do_relocs(unsigned char *base, size_t *rel, size_t rel_size, size_t stride, Sym *syms, char *strings, struct dso *dso)
129 size_t sym_val, sym_size;
135 for (; rel_size; rel+=stride, rel_size-=stride*sizeof(size_t)) {
136 reloc_addr = (void *)(base + rel[0]);
137 type = R_TYPE(rel[1]);
138 sym_index = R_SYM(rel[1]);
140 sym = syms + sym_index;
141 name = strings + sym->st_name;
142 ctx = IS_COPY(type) ? dso->next : dso;
143 sym_val = (size_t)find_sym(ctx, name, IS_PLT(type));
144 if (!sym_val && sym->st_info>>4 != STB_WEAK) {
145 if (runtime) longjmp(rtld_fail, 1);
146 dprintf(2, "%s: symbol not found\n", name);
149 sym_size = sym->st_size;
151 do_single_reloc(reloc_addr, type, sym_val, sym_size, base, rel[2]);
155 /* A huge hack: to make up for the wastefulness of shared libraries
156 * needing at least a page of dirty memory even if they have no global
157 * data, we reclaim the gaps at the beginning and end of writable maps
158 * and "donate" them to the heap by setting up minimal malloc
159 * structures and then freeing them. */
161 static void reclaim(unsigned char *base, size_t start, size_t end)
164 start = start + 6*sizeof(size_t)-1 & -4*sizeof(size_t);
165 end = (end & -4*sizeof(size_t)) - 2*sizeof(size_t);
166 if (start>end || end-start < 4*sizeof(size_t)) return;
167 a = (size_t *)(base + start);
168 z = (size_t *)(base + end);
170 a[-1] = z[0] = end-start + 2*sizeof(size_t) | 1;
175 static void reclaim_gaps(unsigned char *base, Phdr *ph, size_t phent, size_t phcnt)
177 for (; phcnt--; ph=(void *)((char *)ph+phent)) {
178 if (ph->p_type!=PT_LOAD) continue;
179 if ((ph->p_flags&(PF_R|PF_W))!=(PF_R|PF_W)) continue;
180 reclaim(base, ph->p_vaddr & -PAGE_SIZE, ph->p_vaddr);
181 reclaim(base, ph->p_vaddr+ph->p_memsz,
182 ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE);
186 static void *map_library(int fd, size_t *lenp, unsigned char **basep, size_t *dynp)
188 Ehdr buf[(896+sizeof(Ehdr))/sizeof(Ehdr)];
190 size_t addr_min=SIZE_MAX, addr_max=0, map_len;
191 size_t this_min, this_max;
196 unsigned char *map, *base;
200 ssize_t l = read(fd, buf, sizeof buf);
201 if (l<sizeof *eh) return 0;
203 phsize = eh->e_phentsize * eh->e_phnum;
204 if (phsize + sizeof *eh > l) return 0;
205 if (eh->e_phoff + phsize > l) {
206 l = pread(fd, buf+1, phsize, eh->e_phoff);
207 if (l != phsize) return 0;
208 eh->e_phoff = sizeof *eh;
210 ph = (void *)((char *)buf + eh->e_phoff);
211 for (i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
212 if (ph->p_type == PT_DYNAMIC)
214 if (ph->p_type != PT_LOAD) continue;
215 if (ph->p_vaddr < addr_min) {
216 addr_min = ph->p_vaddr;
217 off_start = ph->p_offset;
218 prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
219 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
220 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
222 if (ph->p_vaddr+ph->p_memsz > addr_max) {
223 addr_max = ph->p_vaddr+ph->p_memsz;
227 addr_max += PAGE_SIZE-1;
228 addr_max &= -PAGE_SIZE;
229 addr_min &= -PAGE_SIZE;
230 off_start &= -PAGE_SIZE;
231 map_len = addr_max - addr_min + off_start;
232 /* The first time, we map too much, possibly even more than
233 * the length of the file. This is okay because we will not
234 * use the invalid part; we just need to reserve the right
235 * amount of virtual address space to map over later. */
236 map = mmap((void *)addr_min, map_len, prot, MAP_PRIVATE, fd, off_start);
237 if (map==MAP_FAILED) return 0;
238 base = map - addr_min;
239 ph = (void *)((char *)buf + eh->e_phoff);
240 for (i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
241 if (ph->p_type != PT_LOAD) continue;
242 /* Reuse the existing mapping for the lowest-address LOAD */
243 if ((ph->p_vaddr & -PAGE_SIZE) == addr_min) continue;
244 this_min = ph->p_vaddr & -PAGE_SIZE;
245 this_max = ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE;
246 off_start = ph->p_offset & -PAGE_SIZE;
247 prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
248 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
249 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
250 if (mmap(base+this_min, this_max-this_min, prot, MAP_PRIVATE|MAP_FIXED, fd, off_start) == MAP_FAILED) {
251 munmap(map, map_len);
254 if (ph->p_memsz > ph->p_filesz) {
255 size_t brk = (size_t)base+ph->p_vaddr+ph->p_filesz;
256 size_t pgbrk = brk+PAGE_SIZE-1 & -PAGE_SIZE;
257 memset((void *)brk, 0, pgbrk-brk & PAGE_SIZE-1);
258 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) {
259 munmap(map, map_len);
264 for (i=0; ((size_t *)(base+dyn))[i]; i+=2)
265 if (((size_t *)(base+dyn))[i]==DT_TEXTREL) {
266 mprotect(map, map_len, PROT_READ|PROT_WRITE|PROT_EXEC);
269 if (!runtime) reclaim_gaps(base, (void *)((char *)buf + eh->e_phoff),
270 eh->e_phentsize, eh->e_phnum);
277 static int path_open(const char *name, const char *search)
279 char buf[2*NAME_MAX+2];
280 const char *s=search, *z;
286 l = z ? z-s : strlen(s);
287 snprintf(buf, sizeof buf, "%.*s/%s", l, s, name);
288 if ((fd = open(buf, O_RDONLY))>=0) return fd;
293 static void decode_dyn(struct dso *p)
295 size_t dyn[DYN_CNT] = {0};
296 decode_vec(p->dynv, dyn, DYN_CNT);
297 p->syms = (void *)(p->base + dyn[DT_SYMTAB]);
298 p->hashtab = (void *)(p->base + dyn[DT_HASH]);
299 p->strings = (void *)(p->base + dyn[DT_STRTAB]);
302 static struct dso *load_library(const char *name)
304 unsigned char *base, *map;
305 size_t dyno, map_len;
310 /* Catch and block attempts to reload the implementation itself */
311 if (name[0]=='l' && name[1]=='i' && name[2]=='b') {
312 static const char *rp, reserved[] =
313 "c\0pthread\0rt\0m\0dl\0util\0xnet\0";
314 char *z = strchr(name, '.');
317 for (rp=reserved; *rp && memcmp(name+3, rp, l-3); rp+=strlen(rp)+1);
322 tail = libc->next ? libc->next : libc;
328 /* Search for the name to see if it's already loaded */
329 for (p=head->next; p; p=p->next) {
330 if (!strcmp(p->name, name)) {
335 if (strchr(name, '/')) {
336 fd = open(name, O_RDONLY);
338 if (strlen(name) > NAME_MAX) return 0;
340 if (r_path) fd = path_open(name, r_path);
341 if (fd < 0 && env_path) fd = path_open(name, env_path);
344 FILE *f = fopen(ETC_LDSO_PATH, "r");
346 if (getline(&sys_path, (size_t[1]){0}, f) > 0)
347 sys_path[strlen(sys_path)-1]=0;
351 if (sys_path) fd = path_open(name, sys_path);
352 else fd = path_open(name, "/lib:/usr/local/lib:/usr/lib");
355 if (fd < 0) return 0;
356 if (fstat(fd, &st) < 0) {
360 for (p=head->next; p; p=p->next) {
361 if (p->dev == st.st_dev && p->ino == st.st_ino) {
367 map = map_library(fd, &map_len, &base, &dyno);
370 p = calloc(1, sizeof *p + strlen(name) + 1);
372 munmap(map, map_len);
377 p->map_len = map_len;
379 p->dynv = (void *)(base + dyno);
386 strcpy(p->name, name);
395 static void load_deps(struct dso *p)
398 struct dso ***deps = &p->deps, **tmp, *dep;
399 for (; p; p=p->next) {
400 for (i=0; p->dynv[i]; i+=2) {
401 if (p->dynv[i] != DT_RPATH) continue;
402 r_path = (void *)(p->strings + p->dynv[i+1]);
404 for (i=0; p->dynv[i]; i+=2) {
405 if (p->dynv[i] != DT_NEEDED) continue;
406 dep = load_library(p->strings + p->dynv[i+1]);
408 if (runtime) longjmp(rtld_fail, 1);
409 dprintf(2, "%s: %m (needed by %s)\n",
410 p->strings + p->dynv[i+1], p->name);
414 tmp = realloc(*deps, sizeof(*tmp)*(ndeps+2));
415 if (!tmp) longjmp(rtld_fail, 1);
425 static void load_preload(char *s)
430 for ( ; *s && isspace(*s); s++);
431 for (z=s; *z && !isspace(*z); z++);
439 static void make_global(struct dso *p)
441 for (; p; p=p->next) p->global = 1;
444 static void reloc_all(struct dso *p)
446 size_t dyn[DYN_CNT] = {0};
447 for (; p; p=p->next) {
448 if (p->relocated) continue;
449 decode_vec(p->dynv, dyn, DYN_CNT);
450 do_relocs(p->base, (void *)(p->base+dyn[DT_JMPREL]), dyn[DT_PLTRELSZ],
451 2+(dyn[DT_PLTREL]==DT_RELA), p->syms, p->strings, head);
452 do_relocs(p->base, (void *)(p->base+dyn[DT_REL]), dyn[DT_RELSZ],
453 2, p->syms, p->strings, head);
454 do_relocs(p->base, (void *)(p->base+dyn[DT_RELA]), dyn[DT_RELASZ],
455 3, p->syms, p->strings, head);
460 static void free_all(struct dso *p)
470 static size_t find_dyn(Phdr *ph, size_t cnt, size_t stride)
472 for (; cnt--; ph = (void *)((char *)ph + stride))
473 if (ph->p_type == PT_DYNAMIC)
478 static void do_init_fini(struct dso *p)
480 size_t dyn[DYN_CNT] = {0};
481 for (; p; p=p->prev) {
482 if (p->constructed) return;
483 decode_vec(p->dynv, dyn, DYN_CNT);
484 if (dyn[0] & (1<<DT_FINI))
485 atexit((void (*)(void))(p->base + dyn[DT_FINI]));
486 if (dyn[0] & (1<<DT_INIT))
487 ((void (*)(void))(p->base + dyn[DT_INIT]))();
492 void *__dynlink(int argc, char **argv)
494 size_t *auxv, aux[AUX_CNT] = {0};
498 static struct dso builtin_dsos[3];
499 struct dso *const app = builtin_dsos+0;
500 struct dso *const lib = builtin_dsos+1;
501 struct dso *const vdso = builtin_dsos+2;
504 /* Find aux vector just past environ[] */
505 for (i=argc+1; argv[i]; i++)
506 if (!memcmp(argv[i], "LD_LIBRARY_PATH=", 16))
507 env_path = argv[i]+16;
508 else if (!memcmp(argv[i], "LD_PRELOAD=", 11))
509 env_preload = argv[i]+11;
510 auxv = (void *)(argv+i+1);
512 decode_vec(auxv, aux, AUX_CNT);
514 /* Only trust user/env if kernel says we're not suid/sgid */
515 if ((aux[0]&0x7800)!=0x7800 || aux[AT_UID]!=aux[AT_EUID]
516 || aux[AT_GID]!=aux[AT_EGID] || aux[AT_SECURE]) {
521 /* The dynamic linker load address is passed by the kernel
522 * in the AUX vector, so this is easy. */
523 lib->base = (void *)aux[AT_BASE];
524 lib->name = "libc.so";
526 ehdr = (void *)lib->base;
527 lib->dynv = (void *)(lib->base + find_dyn(
528 (void *)(aux[AT_BASE]+ehdr->e_phoff),
529 ehdr->e_phnum, ehdr->e_phentsize));
532 /* Find load address of the main program, via AT_PHDR vs PT_PHDR. */
534 phdr = (void *)aux[AT_PHDR];
535 for (i=aux[AT_PHNUM]; i; i--, phdr=(void *)((char *)phdr + aux[AT_PHENT])) {
536 if (phdr->p_type == PT_PHDR)
537 app->base = (void *)(aux[AT_PHDR] - phdr->p_vaddr);
541 app->constructed = 1;
542 app->dynv = (void *)(app->base + find_dyn(
543 (void *)aux[AT_PHDR], aux[AT_PHNUM], aux[AT_PHENT]));
546 /* Attach to vdso, if provided by the kernel */
547 for (i=0; auxv[i]; i+=2) {
548 size_t vdso_base = auxv[i+1];
549 if (auxv[i] != AT_SYSINFO_EHDR) continue;
550 ehdr = (void *)vdso_base;
551 phdr = (void *)(vdso_base + ehdr->e_phoff);
552 for (i=ehdr->e_phnum; i; i--, phdr=(void *)((char *)phdr + ehdr->e_phentsize)) {
553 if (phdr->p_type == PT_DYNAMIC)
554 vdso->dynv = (void *)(vdso_base + phdr->p_offset);
555 if (phdr->p_type == PT_LOAD)
556 vdso->base = (void *)(vdso_base - phdr->p_vaddr + phdr->p_offset);
558 vdso->name = "linux-gate.so.1";
566 /* Initial dso chain consists only of the app. We temporarily
567 * append the dynamic linker/libc so we can relocate it, then
568 * restore the initial chain in preparation for loading third
569 * party libraries (preload/needed). */
576 /* PAST THIS POINT, ALL LIBC INTERFACES ARE FULLY USABLE. */
578 /* Donate unused parts of app and library mapping to malloc */
579 reclaim_gaps(app->base, (void *)aux[AT_PHDR], aux[AT_PHENT], aux[AT_PHNUM]);
580 ehdr = (void *)lib->base;
581 reclaim_gaps(lib->base, (void *)(lib->base+ehdr->e_phoff),
582 ehdr->e_phentsize, ehdr->e_phnum);
584 /* Load preload/needed libraries, add their symbols to the global
585 * namespace, and perform all remaining relocations. The main
586 * program must be relocated LAST since it may contain copy
587 * relocations which depend on libraries' relocations. */
588 if (env_preload) load_preload(env_preload);
591 reloc_all(app->next);
594 /* Switch to runtime mode: any further failures in the dynamic
595 * linker are a reportable failure rather than a fatal startup
596 * error. If the dynamic loader (dlopen) will not be used, free
597 * all memory used by the dynamic linker. */
605 reclaim((void *)builtin_dsos, 0, sizeof builtin_dsos);
609 return (void *)aux[AT_ENTRY];
612 void *dlopen(const char *file, int mode)
614 struct dso *volatile p, *orig_tail = tail, *next;
618 if (!file) return head;
620 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
621 pthread_rwlock_wrlock(&lock);
623 if (setjmp(rtld_fail)) {
624 /* Clean up anything new that was (partially) loaded */
625 if (p->deps) for (i=0; p->deps[i]; i++)
626 if (p->deps[i]->global < 0)
627 p->deps[i]->global = 0;
628 for (p=orig_tail->next; p; p=next) {
630 munmap(p->map, p->map_len);
637 } else p = load_library(file);
644 /* First load handling */
647 if (p->deps) for (i=0; p->deps[i]; i++)
648 if (!p->deps[i]->global)
649 p->deps[i]->global = -1;
650 if (!p->global) p->global = -1;
652 if (p->deps) for (i=0; p->deps[i]; i++)
653 if (p->deps[i]->global < 0)
654 p->deps[i]->global = 0;
655 if (p->global < 0) p->global = 0;
658 if (mode & RTLD_GLOBAL) {
659 if (p->deps) for (i=0; p->deps[i]; i++)
660 p->deps[i]->global = 1;
666 pthread_rwlock_unlock(&lock);
667 pthread_setcancelstate(cs, 0);
671 static void *do_dlsym(struct dso *p, const char *s, void *ra)
676 if (p == RTLD_NEXT) {
677 for (p=head; p && (unsigned char *)ra-p->map>p->map_len; p=p->next);
681 if (p == head || p == RTLD_DEFAULT) {
682 void *res = find_sym(head, s, 0);
683 if (!res) errflag = 1;
687 sym = lookup(s, h, p->syms, p->hashtab, p->strings);
688 if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
689 return p->base + sym->st_value;
690 if (p->deps) for (i=0; p->deps[i]; i++) {
691 sym = lookup(s, h, p->deps[i]->syms,
692 p->deps[i]->hashtab, p->deps[i]->strings);
693 if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
694 return p->deps[i]->base + sym->st_value;
700 void *__dlsym(void *p, const char *s, void *ra)
703 pthread_rwlock_rdlock(&lock);
704 res = do_dlsym(p, s, ra);
705 pthread_rwlock_unlock(&lock);
709 void *dlopen(const char *file, int mode)
713 void *__dlsym(void *p, const char *s, void *ra)
721 if (!errflag) return 0;
723 return "unknown error";