23 #if ULONG_MAX == 0xffffffff
24 typedef Elf32_Ehdr Ehdr;
25 typedef Elf32_Phdr Phdr;
26 typedef Elf32_Sym Sym;
27 #define R_TYPE(x) ((x)&255)
28 #define R_SYM(x) ((x)>>8)
30 typedef Elf64_Ehdr Ehdr;
31 typedef Elf64_Phdr Phdr;
32 typedef Elf64_Sym Sym;
33 #define R_TYPE(x) ((x)&0xffffffff)
34 #define R_SYM(x) ((x)>>32)
39 struct dso *next, *prev;
57 static struct dso *head, *tail, *libc;
58 static char *env_path, *sys_path, *r_path;
61 static jmp_buf rtld_fail;
62 static pthread_rwlock_t lock;
67 static void decode_vec(size_t *v, size_t *a, size_t cnt)
69 memset(a, 0, cnt*sizeof(size_t));
70 for (; v[0]; v+=2) if (v[0]<cnt) {
76 static uint32_t hash(const char *s0)
78 const unsigned char *s = (void *)s0;
87 static Sym *lookup(const char *s, uint32_t h, Sym *syms, uint32_t *hashtab, char *strings)
90 for (i=hashtab[2+h%hashtab[0]]; i; i=hashtab[2+hashtab[0]+i]) {
91 if (!strcmp(s, strings+syms[i].st_name))
97 #define OK_TYPES (1<<STT_NOTYPE | 1<<STT_OBJECT | 1<<STT_FUNC | 1<<STT_COMMON)
98 #define OK_BINDS (1<<STB_GLOBAL | 1<<STB_WEAK)
100 static void *find_sym(struct dso *dso, const char *s, int need_def)
102 uint32_t h = hash(s);
104 if (h==0x6b366be && !strcmp(s, "dlopen")) rtld_used = 1;
105 if (h==0x6b3afd && !strcmp(s, "dlsym")) rtld_used = 1;
106 for (; dso; dso=dso->next) {
108 if (!dso->global) continue;
109 sym = lookup(s, h, dso->syms, dso->hashtab, dso->strings);
110 if (sym && (!need_def || sym->st_shndx) && sym->st_value
111 && (1<<(sym->st_info&0xf) & OK_TYPES)
112 && (1<<(sym->st_info>>4) & OK_BINDS)) {
113 if (def && sym->st_info>>4 == STB_WEAK) continue;
114 def = dso->base + sym->st_value;
115 if (sym->st_info>>4 == STB_GLOBAL) break;
121 static void do_relocs(unsigned char *base, size_t *rel, size_t rel_size, size_t stride, Sym *syms, char *strings, struct dso *dso)
125 size_t sym_val, sym_size;
131 for (; rel_size; rel+=stride, rel_size-=stride*sizeof(size_t)) {
132 reloc_addr = (void *)(base + rel[0]);
133 type = R_TYPE(rel[1]);
134 sym_index = R_SYM(rel[1]);
136 sym = syms + sym_index;
137 name = strings + sym->st_name;
138 ctx = IS_COPY(type) ? dso->next : dso;
139 sym_val = (size_t)find_sym(ctx, name, IS_PLT(type));
140 if (!sym_val && sym->st_info>>4 != STB_WEAK) {
141 if (runtime) longjmp(rtld_fail, 1);
142 dprintf(2, "%s: symbol not found\n", name);
145 sym_size = sym->st_size;
147 do_single_reloc(reloc_addr, type, sym_val, sym_size, base, rel[2]);
151 /* A huge hack: to make up for the wastefulness of shared libraries
152 * needing at least a page of dirty memory even if they have no global
153 * data, we reclaim the gaps at the beginning and end of writable maps
154 * and "donate" them to the heap by setting up minimal malloc
155 * structures and then freeing them. */
157 static void reclaim(unsigned char *base, size_t start, size_t end)
160 start = start + 6*sizeof(size_t)-1 & -4*sizeof(size_t);
161 end = (end & -4*sizeof(size_t)) - 2*sizeof(size_t);
162 if (start>end || end-start < 4*sizeof(size_t)) return;
163 a = (size_t *)(base + start);
164 z = (size_t *)(base + end);
166 a[-1] = z[0] = end-start + 2*sizeof(size_t) | 1;
171 static void reclaim_gaps(unsigned char *base, Phdr *ph, size_t phent, size_t phcnt)
173 for (; phcnt--; ph=(void *)((char *)ph+phent)) {
174 if (ph->p_type!=PT_LOAD) continue;
175 if ((ph->p_flags&(PF_R|PF_W))!=(PF_R|PF_W)) continue;
176 reclaim(base, ph->p_vaddr & -PAGE_SIZE, ph->p_vaddr);
177 reclaim(base, ph->p_vaddr+ph->p_memsz,
178 ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE);
182 static void *map_library(int fd, size_t *lenp, unsigned char **basep, size_t *dynp)
184 Ehdr buf[(896+sizeof(Ehdr))/sizeof(Ehdr)];
186 size_t addr_min=SIZE_MAX, addr_max=0, map_len;
187 size_t this_min, this_max;
192 unsigned char *map, *base;
196 ssize_t l = read(fd, buf, sizeof buf);
197 if (l<sizeof *eh) return 0;
199 phsize = eh->e_phentsize * eh->e_phnum;
200 if (phsize + sizeof *eh > l) return 0;
201 if (eh->e_phoff + phsize > l) {
202 l = pread(fd, buf+1, phsize, eh->e_phoff);
203 if (l != phsize) return 0;
204 eh->e_phoff = sizeof *eh;
206 ph = (void *)((char *)buf + eh->e_phoff);
207 for (i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
208 if (ph->p_type == PT_DYNAMIC)
210 if (ph->p_type != PT_LOAD) continue;
211 if (ph->p_vaddr < addr_min) {
212 addr_min = ph->p_vaddr;
213 off_start = ph->p_offset;
214 prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
215 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
216 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
218 if (ph->p_vaddr+ph->p_memsz > addr_max) {
219 addr_max = ph->p_vaddr+ph->p_memsz;
223 addr_max += PAGE_SIZE-1;
224 addr_max &= -PAGE_SIZE;
225 addr_min &= -PAGE_SIZE;
226 off_start &= -PAGE_SIZE;
227 map_len = addr_max - addr_min + off_start;
228 /* The first time, we map too much, possibly even more than
229 * the length of the file. This is okay because we will not
230 * use the invalid part; we just need to reserve the right
231 * amount of virtual address space to map over later. */
232 map = mmap((void *)addr_min, map_len, prot, MAP_PRIVATE, fd, off_start);
233 if (map==MAP_FAILED) return 0;
234 base = map - addr_min;
235 ph = (void *)((char *)buf + eh->e_phoff);
236 for (i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
237 if (ph->p_type != PT_LOAD) continue;
238 /* Reuse the existing mapping for the lowest-address LOAD */
239 if ((ph->p_vaddr & -PAGE_SIZE) == addr_min) continue;
240 this_min = ph->p_vaddr & -PAGE_SIZE;
241 this_max = ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE;
242 off_start = ph->p_offset & -PAGE_SIZE;
243 prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
244 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
245 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
246 if (mmap(base+this_min, this_max-this_min, prot, MAP_PRIVATE|MAP_FIXED, fd, off_start) == MAP_FAILED) {
247 munmap(map, map_len);
250 if (ph->p_memsz > ph->p_filesz) {
251 size_t brk = (size_t)base+ph->p_vaddr+ph->p_filesz;
252 size_t pgbrk = brk+PAGE_SIZE-1 & -PAGE_SIZE;
253 memset((void *)brk, 0, pgbrk-brk & PAGE_SIZE-1);
254 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) {
255 munmap(map, map_len);
260 for (i=0; ((size_t *)(base+dyn))[i]; i+=2)
261 if (((size_t *)(base+dyn))[i]==DT_TEXTREL) {
262 mprotect(map, map_len, PROT_READ|PROT_WRITE|PROT_EXEC);
265 if (!runtime) reclaim_gaps(base, (void *)((char *)buf + eh->e_phoff),
266 eh->e_phentsize, eh->e_phnum);
273 static int path_open(const char *name, const char *search)
275 char buf[2*NAME_MAX+2];
276 const char *s=search, *z;
282 l = z ? z-s : strlen(s);
283 snprintf(buf, sizeof buf, "%.*s/%s", l, s, name);
284 if ((fd = open(buf, O_RDONLY))>=0) return fd;
289 static void decode_dyn(struct dso *p)
291 size_t dyn[DYN_CNT] = {0};
292 decode_vec(p->dynv, dyn, DYN_CNT);
293 p->syms = (void *)(p->base + dyn[DT_SYMTAB]);
294 p->hashtab = (void *)(p->base + dyn[DT_HASH]);
295 p->strings = (void *)(p->base + dyn[DT_STRTAB]);
298 static struct dso *load_library(const char *name)
300 unsigned char *base, *map;
301 size_t dyno, map_len;
306 /* Catch and block attempts to reload the implementation itself */
307 if (name[0]=='l' && name[1]=='i' && name[2]=='b') {
308 static const char *rp, reserved[] =
309 "c\0pthread\0rt\0m\0dl\0util\0xnet\0";
310 char *z = strchr(name, '.');
313 for (rp=reserved; *rp && memcmp(name+3, rp, l-3); rp+=strlen(rp)+1);
318 tail = libc->next ? libc->next : libc;
324 /* Search for the name to see if it's already loaded */
325 for (p=head->next; p; p=p->next) {
326 if (!strcmp(p->name, name)) {
331 if (strchr(name, '/')) {
332 fd = open(name, O_RDONLY);
334 if (strlen(name) > NAME_MAX) return 0;
336 if (r_path) fd = path_open(name, r_path);
337 if (fd < 0 && env_path) fd = path_open(name, env_path);
340 FILE *f = fopen(ETC_LDSO_PATH, "r");
342 if (getline(&sys_path, (size_t[1]){0}, f) > 0)
343 sys_path[strlen(sys_path)-1]=0;
347 if (sys_path) fd = path_open(name, sys_path);
348 else fd = path_open(name, "/lib:/usr/local/lib:/usr/lib");
351 if (fd < 0) return 0;
352 if (fstat(fd, &st) < 0) {
356 for (p=head->next; p; p=p->next) {
357 if (p->dev == st.st_dev && p->ino == st.st_ino) {
363 map = map_library(fd, &map_len, &base, &dyno);
366 p = calloc(1, sizeof *p + strlen(name) + 1);
368 munmap(map, map_len);
373 p->map_len = map_len;
375 p->dynv = (void *)(base + dyno);
382 strcpy(p->name, name);
391 static void load_deps(struct dso *p)
394 struct dso ***deps = &p->deps, **tmp, *dep;
395 for (; p; p=p->next) {
396 for (i=0; p->dynv[i]; i+=2) {
397 if (p->dynv[i] != DT_RPATH) continue;
398 r_path = (void *)(p->strings + p->dynv[i+1]);
400 for (i=0; p->dynv[i]; i+=2) {
401 if (p->dynv[i] != DT_NEEDED) continue;
402 dep = load_library(p->strings + p->dynv[i+1]);
404 if (runtime) longjmp(rtld_fail, 1);
405 dprintf(2, "%s: %m (needed by %s)\n",
406 p->strings + p->dynv[i+1], p->name);
410 tmp = realloc(*deps, sizeof(*tmp)*(ndeps+2));
411 if (!tmp) longjmp(rtld_fail, 1);
421 static void load_preload(char *s)
426 for ( ; *s && isspace(*s); s++);
427 for (z=s; *z && !isspace(*z); z++);
435 static void make_global(struct dso *p)
437 for (; p; p=p->next) p->global = 1;
440 static void reloc_all(struct dso *p)
442 size_t dyn[DYN_CNT] = {0};
443 for (; p; p=p->next) {
444 if (p->relocated) continue;
445 decode_vec(p->dynv, dyn, DYN_CNT);
446 do_relocs(p->base, (void *)(p->base+dyn[DT_JMPREL]), dyn[DT_PLTRELSZ],
447 2+(dyn[DT_PLTREL]==DT_RELA), p->syms, p->strings, head);
448 do_relocs(p->base, (void *)(p->base+dyn[DT_REL]), dyn[DT_RELSZ],
449 2, p->syms, p->strings, head);
450 do_relocs(p->base, (void *)(p->base+dyn[DT_RELA]), dyn[DT_RELASZ],
451 3, p->syms, p->strings, head);
456 static void free_all(struct dso *p)
466 static size_t find_dyn(Phdr *ph, size_t cnt, size_t stride)
468 for (; cnt--; ph = (void *)((char *)ph + stride))
469 if (ph->p_type == PT_DYNAMIC)
474 void *__dynlink(int argc, char **argv)
476 size_t *auxv, aux[AUX_CNT] = {0};
480 static struct dso builtin_dsos[3];
481 struct dso *const app = builtin_dsos+0;
482 struct dso *const lib = builtin_dsos+1;
483 struct dso *const vdso = builtin_dsos+2;
486 /* Find aux vector just past environ[] */
487 for (i=argc+1; argv[i]; i++)
488 if (!memcmp(argv[i], "LD_LIBRARY_PATH=", 16))
489 env_path = argv[i]+16;
490 else if (!memcmp(argv[i], "LD_PRELOAD=", 11))
491 env_preload = argv[i]+11;
492 auxv = (void *)(argv+i+1);
494 decode_vec(auxv, aux, AUX_CNT);
496 /* Only trust user/env if kernel says we're not suid/sgid */
497 if ((aux[0]&0x7800)!=0x7800 || aux[AT_UID]!=aux[AT_EUID]
498 || aux[AT_GID]!=aux[AT_EGID] || aux[AT_SECURE]) {
503 /* The dynamic linker load address is passed by the kernel
504 * in the AUX vector, so this is easy. */
505 lib->base = (void *)aux[AT_BASE];
506 lib->name = "libc.so";
508 ehdr = (void *)lib->base;
509 lib->dynv = (void *)(lib->base + find_dyn(
510 (void *)(aux[AT_BASE]+ehdr->e_phoff),
511 ehdr->e_phnum, ehdr->e_phentsize));
514 /* Find load address of the main program, via AT_PHDR vs PT_PHDR. */
516 phdr = (void *)aux[AT_PHDR];
517 for (i=aux[AT_PHNUM]; i; i--, phdr=(void *)((char *)phdr + aux[AT_PHENT])) {
518 if (phdr->p_type == PT_PHDR)
519 app->base = (void *)(aux[AT_PHDR] - phdr->p_vaddr);
523 app->dynv = (void *)(app->base + find_dyn(
524 (void *)aux[AT_PHDR], aux[AT_PHNUM], aux[AT_PHENT]));
527 /* Attach to vdso, if provided by the kernel */
528 for (i=0; auxv[i]; i+=2) {
529 size_t vdso_base = auxv[i+1];
530 if (auxv[i] != AT_SYSINFO_EHDR) continue;
531 ehdr = (void *)vdso_base;
532 phdr = (void *)(vdso_base + ehdr->e_phoff);
533 for (i=ehdr->e_phnum; i; i--, phdr=(void *)((char *)phdr + ehdr->e_phentsize)) {
534 if (phdr->p_type == PT_DYNAMIC)
535 vdso->dynv = (void *)(vdso_base + phdr->p_offset);
536 if (phdr->p_type == PT_LOAD)
537 vdso->base = (void *)(vdso_base - phdr->p_vaddr + phdr->p_offset);
539 vdso->name = "linux-gate.so.1";
547 /* Initial dso chain consists only of the app. We temporarily
548 * append the dynamic linker/libc so we can relocate it, then
549 * restore the initial chain in preparation for loading third
550 * party libraries (preload/needed). */
557 /* PAST THIS POINT, ALL LIBC INTERFACES ARE FULLY USABLE. */
559 /* Donate unused parts of app and library mapping to malloc */
560 reclaim_gaps(app->base, (void *)aux[AT_PHDR], aux[AT_PHENT], aux[AT_PHNUM]);
561 ehdr = (void *)lib->base;
562 reclaim_gaps(lib->base, (void *)(lib->base+ehdr->e_phoff),
563 ehdr->e_phentsize, ehdr->e_phnum);
565 /* Load preload/needed libraries, add their symbols to the global
566 * namespace, and perform all remaining relocations. The main
567 * program must be relocated LAST since it may contain copy
568 * relocations which depend on libraries' relocations. */
569 if (env_preload) load_preload(env_preload);
572 reloc_all(app->next);
575 /* Switch to runtime mode: any further failures in the dynamic
576 * linker are a reportable failure rather than a fatal startup
577 * error. If the dynamic loader (dlopen) will not be used, free
578 * all memory used by the dynamic linker. */
583 reclaim((void *)builtin_dsos, 0, sizeof builtin_dsos);
587 return (void *)aux[AT_ENTRY];
590 void *dlopen(const char *file, int mode)
592 struct dso *volatile p, *orig_tail = tail, *next;
595 if (!file) return head;
597 pthread_rwlock_wrlock(&lock);
599 if (setjmp(rtld_fail)) {
600 /* Clean up anything new that was (partially) loaded */
601 if (p->deps) for (i=0; p->deps[i]; i++)
602 if (p->deps[i]->global < 0)
603 p->deps[i]->global = 0;
604 for (p=orig_tail->next; p; p=next) {
606 munmap(p->map, p->map_len);
612 pthread_rwlock_unlock(&lock);
616 p = load_library(file);
619 /* First load handling */
622 if (p->deps) for (i=0; p->deps[i]; i++)
623 if (!p->deps[i]->global)
624 p->deps[i]->global = -1;
625 if (!p->global) p->global = -1;
627 if (p->deps) for (i=0; p->deps[i]; i++)
628 if (p->deps[i]->global < 0)
629 p->deps[i]->global = 0;
630 if (p->global < 0) p->global = 0;
633 if (mode & RTLD_GLOBAL) {
634 if (p->deps) for (i=0; p->deps[i]; i++)
635 p->deps[i]->global = 1;
640 pthread_rwlock_unlock(&lock);
644 static void *do_dlsym(struct dso *p, const char *s, void *ra)
649 if (p == RTLD_NEXT) {
650 for (p=head; p && (unsigned char *)ra-p->map>p->map_len; p=p->next);
654 if (p == head || p == RTLD_DEFAULT)
655 return find_sym(head, s, 0);
657 sym = lookup(s, h, p->syms, p->hashtab, p->strings);
658 if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
659 return p->base + sym->st_value;
660 if (p->deps) for (i=0; p->deps[i]; i++) {
661 sym = lookup(s, h, p->deps[i]->syms,
662 p->deps[i]->hashtab, p->deps[i]->strings);
663 if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
664 return p->deps[i]->base + sym->st_value;
669 void *__dlsym(void *p, const char *s, void *ra)
672 pthread_rwlock_rdlock(&lock);
673 res = do_dlsym(p, s, ra);
674 pthread_rwlock_unlock(&lock);
678 void *dlopen(const char *file, int mode)
682 void *__dlsym(void *p, const char *s, void *ra)
690 return "unknown error";