add gnu hash support in the dynamic linker
[musl] / src / ldso / dynlink.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <unistd.h>
5 #include <stdint.h>
6 #include <elf.h>
7 #include <sys/mman.h>
8 #include <limits.h>
9 #include <stdint.h>
10 #include <fcntl.h>
11 #include <sys/stat.h>
12 #include <errno.h>
13 #include <limits.h>
14 #include <elf.h>
15 #include <setjmp.h>
16 #include <pthread.h>
17 #include <ctype.h>
18 #include <dlfcn.h>
19
20 static int errflag;
21 static char errbuf[128];
22
23 #ifdef SHARED
24
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)
31 #else
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)
37 #endif
38
39 struct debug {
40         int ver;
41         void *head;
42         void (*bp)(void);
43         int state;
44         void *base;
45 };
46
47 struct dso {
48         unsigned char *base;
49         char *name;
50         size_t *dynv;
51         struct dso *next, *prev;
52
53         int refcnt;
54         Sym *syms;
55         uint32_t *hashtab;
56         uint32_t *ghashtab;
57         char *strings;
58         unsigned char *map;
59         size_t map_len;
60         dev_t dev;
61         ino_t ino;
62         signed char global;
63         char relocated;
64         char constructed;
65         struct dso **deps;
66         char *shortname;
67         char buf[];
68 };
69
70 #include "reloc.h"
71
72 void __init_ssp(size_t *);
73
74 static struct dso *head, *tail, *libc;
75 static char *env_path, *sys_path, *r_path;
76 static int rtld_used;
77 static int ssp_used;
78 static int runtime;
79 static int ldd_mode;
80 static int ldso_fail;
81 static jmp_buf rtld_fail;
82 static pthread_rwlock_t lock;
83 static struct debug debug;
84
85 struct debug *_dl_debug_addr = &debug;
86
87 #define AUX_CNT 24
88 #define DYN_CNT 34
89
90 static void decode_vec(size_t *v, size_t *a, size_t cnt)
91 {
92         memset(a, 0, cnt*sizeof(size_t));
93         for (; v[0]; v+=2) if (v[0]<cnt) {
94                 a[0] |= 1ULL<<v[0];
95                 a[v[0]] = v[1];
96         }
97 }
98
99 static int search_vec(size_t *v, size_t *r, size_t key)
100 {
101         for (; v[0]!=key; v+=2)
102                 if (!v[0]) return 0;
103         *r = v[1];
104         return 1;
105 }
106
107 static uint32_t sysv_hash(const char *s0)
108 {
109         const unsigned char *s = (void *)s0;
110         uint_fast32_t h = 0;
111         while (*s) {
112                 h = 16*h + *s++;
113                 h ^= h>>24 & 0xf0;
114         }
115         return h & 0xfffffff;
116 }
117
118 static uint32_t gnu_hash(const char *s0)
119 {
120         const unsigned char *s = (void *)s0;
121         uint_fast32_t h = 5381;
122         for (; *s; s++)
123                 h = h*33 + *s;
124         return h;
125 }
126
127 static Sym *sysv_lookup(const char *s, uint32_t h, struct dso *dso)
128 {
129         size_t i;
130         Sym *syms = dso->syms;
131         uint32_t *hashtab = dso->hashtab;
132         char *strings = dso->strings;
133         for (i=hashtab[2+h%hashtab[0]]; i; i=hashtab[2+hashtab[0]+i]) {
134                 if (!strcmp(s, strings+syms[i].st_name))
135                         return syms+i;
136         }
137         return 0;
138 }
139
140 static Sym *gnu_lookup(const char *s, uint32_t h1, struct dso *dso)
141 {
142         Sym *sym;
143         char *strings;
144         uint32_t *hashtab = dso->ghashtab;
145         uint32_t nbuckets = hashtab[0];
146         uint32_t *buckets = hashtab + 4 + hashtab[2]*(sizeof(size_t)/4);
147         uint32_t h2;
148         uint32_t *hashval;
149         uint32_t n = buckets[h1 % nbuckets];
150
151         if (!n) return 0;
152
153         strings = dso->strings;
154         sym = dso->syms + n;
155         hashval = buckets + nbuckets + (n - hashtab[1]);
156
157         for (h1 |= 1; ; sym++) {
158                 h2 = *hashval++;
159                 if ((h1 == (h2|1)) && !strcmp(s, strings + sym->st_name))
160                         return sym;
161                 if (h2 & 1) break;
162         }
163
164         return 0;
165 }
166
167 #define OK_TYPES (1<<STT_NOTYPE | 1<<STT_OBJECT | 1<<STT_FUNC | 1<<STT_COMMON)
168 #define OK_BINDS (1<<STB_GLOBAL | 1<<STB_WEAK)
169
170 static void *find_sym(struct dso *dso, const char *s, int need_def)
171 {
172         uint32_t h = 0, gh = 0;
173         void *def = 0;
174         if (dso->ghashtab) {
175                 gh = gnu_hash(s);
176                 if (gh == 0xf9040207 && !strcmp(s, "dlopen")) rtld_used = 1;
177                 if (gh == 0xf4dc4ae && !strcmp(s, "dlsym")) rtld_used = 1;
178                 if (gh == 0x1f4039c9 && !strcmp(s, "__stack_chk_fail")) ssp_used = 1;
179         } else {
180                 h = sysv_hash(s);
181                 if (h == 0x6b366be && !strcmp(s, "dlopen")) rtld_used = 1;
182                 if (h == 0x6b3afd && !strcmp(s, "dlsym")) rtld_used = 1;
183                 if (h == 0x595a4cc && !strcmp(s, "__stack_chk_fail")) ssp_used = 1;
184         }
185         for (; dso; dso=dso->next) {
186                 Sym *sym;
187                 if (!dso->global) continue;
188                 if (dso->ghashtab) {
189                         if (!gh) gh = gnu_hash(s);
190                         sym = gnu_lookup(s, gh, dso);
191                 } else {
192                         if (!h) h = sysv_hash(s);
193                         sym = sysv_lookup(s, h, dso);
194                 }
195                 if (sym && (!need_def || sym->st_shndx) && sym->st_value
196                  && (1<<(sym->st_info&0xf) & OK_TYPES)
197                  && (1<<(sym->st_info>>4) & OK_BINDS)) {
198                         if (def && sym->st_info>>4 == STB_WEAK) continue;
199                         def = dso->base + sym->st_value;
200                         if (sym->st_info>>4 == STB_GLOBAL) break;
201                 }
202         }
203         return def;
204 }
205
206 static void do_relocs(struct dso *dso, size_t *rel, size_t rel_size, size_t stride)
207 {
208         unsigned char *base = dso->base;
209         Sym *syms = dso->syms;
210         char *strings = dso->strings;
211         Sym *sym;
212         const char *name;
213         size_t sym_val, sym_size;
214         size_t *reloc_addr;
215         void *ctx;
216         int type;
217         int sym_index;
218
219         for (; rel_size; rel+=stride, rel_size-=stride*sizeof(size_t)) {
220                 reloc_addr = (void *)(base + rel[0]);
221                 type = R_TYPE(rel[1]);
222                 sym_index = R_SYM(rel[1]);
223                 if (sym_index) {
224                         sym = syms + sym_index;
225                         name = strings + sym->st_name;
226                         ctx = IS_COPY(type) ? head->next : head;
227                         sym_val = (size_t)find_sym(ctx, name, IS_PLT(type));
228                         if (!sym_val && sym->st_info>>4 != STB_WEAK) {
229                                 snprintf(errbuf, sizeof errbuf,
230                                         "Error relocating %s: %s: symbol not found",
231                                         dso->name, name);
232                                 if (runtime) longjmp(rtld_fail, 1);
233                                 dprintf(2, "%s\n", errbuf);
234                                 ldso_fail = 1;
235                                 continue;
236                         }
237                         sym_size = sym->st_size;
238                 } else {
239                         sym_val = sym_size = 0;
240                 }
241                 do_single_reloc(reloc_addr, type, sym_val, sym_size, base, rel[2]);
242         }
243 }
244
245 /* A huge hack: to make up for the wastefulness of shared libraries
246  * needing at least a page of dirty memory even if they have no global
247  * data, we reclaim the gaps at the beginning and end of writable maps
248  * and "donate" them to the heap by setting up minimal malloc
249  * structures and then freeing them. */
250
251 static void reclaim(unsigned char *base, size_t start, size_t end)
252 {
253         size_t *a, *z;
254         start = start + 6*sizeof(size_t)-1 & -4*sizeof(size_t);
255         end = (end & -4*sizeof(size_t)) - 2*sizeof(size_t);
256         if (start>end || end-start < 4*sizeof(size_t)) return;
257         a = (size_t *)(base + start);
258         z = (size_t *)(base + end);
259         a[-2] = 1;
260         a[-1] = z[0] = end-start + 2*sizeof(size_t) | 1;
261         z[1] = 1;
262         free(a);
263 }
264
265 static void reclaim_gaps(unsigned char *base, Phdr *ph, size_t phent, size_t phcnt)
266 {
267         for (; phcnt--; ph=(void *)((char *)ph+phent)) {
268                 if (ph->p_type!=PT_LOAD) continue;
269                 if ((ph->p_flags&(PF_R|PF_W))!=(PF_R|PF_W)) continue;
270                 reclaim(base, ph->p_vaddr & -PAGE_SIZE, ph->p_vaddr);
271                 reclaim(base, ph->p_vaddr+ph->p_memsz,
272                         ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE);
273         }
274 }
275
276 static void *map_library(int fd, size_t *lenp, unsigned char **basep, size_t *dynp)
277 {
278         Ehdr buf[(896+sizeof(Ehdr))/sizeof(Ehdr)];
279         size_t phsize;
280         size_t addr_min=SIZE_MAX, addr_max=0, map_len;
281         size_t this_min, this_max;
282         off_t off_start;
283         Ehdr *eh;
284         Phdr *ph;
285         unsigned prot;
286         unsigned char *map, *base;
287         size_t dyn;
288         size_t i;
289
290         ssize_t l = read(fd, buf, sizeof buf);
291         if (l<sizeof *eh) return 0;
292         eh = buf;
293         phsize = eh->e_phentsize * eh->e_phnum;
294         if (phsize + sizeof *eh > l) return 0;
295         if (eh->e_phoff + phsize > l) {
296                 l = pread(fd, buf+1, phsize, eh->e_phoff);
297                 if (l != phsize) return 0;
298                 eh->e_phoff = sizeof *eh;
299         }
300         ph = (void *)((char *)buf + eh->e_phoff);
301         for (i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
302                 if (ph->p_type == PT_DYNAMIC)
303                         dyn = ph->p_vaddr;
304                 if (ph->p_type != PT_LOAD) continue;
305                 if (ph->p_vaddr < addr_min) {
306                         addr_min = ph->p_vaddr;
307                         off_start = ph->p_offset;
308                         prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
309                                 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
310                                 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
311                 }
312                 if (ph->p_vaddr+ph->p_memsz > addr_max) {
313                         addr_max = ph->p_vaddr+ph->p_memsz;
314                 }
315         }
316         if (!dyn) return 0;
317         addr_max += PAGE_SIZE-1;
318         addr_max &= -PAGE_SIZE;
319         addr_min &= -PAGE_SIZE;
320         off_start &= -PAGE_SIZE;
321         map_len = addr_max - addr_min + off_start;
322         /* The first time, we map too much, possibly even more than
323          * the length of the file. This is okay because we will not
324          * use the invalid part; we just need to reserve the right
325          * amount of virtual address space to map over later. */
326         map = mmap((void *)addr_min, map_len, prot, MAP_PRIVATE, fd, off_start);
327         if (map==MAP_FAILED) return 0;
328         base = map - addr_min;
329         ph = (void *)((char *)buf + eh->e_phoff);
330         for (i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
331                 if (ph->p_type != PT_LOAD) continue;
332                 /* Reuse the existing mapping for the lowest-address LOAD */
333                 if ((ph->p_vaddr & -PAGE_SIZE) == addr_min) continue;
334                 this_min = ph->p_vaddr & -PAGE_SIZE;
335                 this_max = ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE;
336                 off_start = ph->p_offset & -PAGE_SIZE;
337                 prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
338                         ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
339                         ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
340                 if (mmap(base+this_min, this_max-this_min, prot, MAP_PRIVATE|MAP_FIXED, fd, off_start) == MAP_FAILED)
341                         goto error;
342                 if (ph->p_memsz > ph->p_filesz) {
343                         size_t brk = (size_t)base+ph->p_vaddr+ph->p_filesz;
344                         size_t pgbrk = brk+PAGE_SIZE-1 & -PAGE_SIZE;
345                         memset((void *)brk, 0, pgbrk-brk & PAGE_SIZE-1);
346                         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)
347                                 goto error;
348                 }
349         }
350         for (i=0; ((size_t *)(base+dyn))[i]; i+=2)
351                 if (((size_t *)(base+dyn))[i]==DT_TEXTREL) {
352                         if (mprotect(map, map_len, PROT_READ|PROT_WRITE|PROT_EXEC) < 0)
353                                 goto error;
354                         break;
355                 }
356         if (!runtime) reclaim_gaps(base, (void *)((char *)buf + eh->e_phoff),
357                 eh->e_phentsize, eh->e_phnum);
358         *lenp = map_len;
359         *basep = base;
360         *dynp = dyn;
361         return map;
362 error:
363         munmap(map, map_len);
364         return 0;
365 }
366
367 static int path_open(const char *name, const char *search, char *buf, size_t buf_size)
368 {
369         const char *s=search, *z;
370         int l, fd;
371         for (;;) {
372                 while (*s==':') s++;
373                 if (!*s) return -1;
374                 z = strchr(s, ':');
375                 l = z ? z-s : strlen(s);
376                 snprintf(buf, buf_size, "%.*s/%s", l, s, name);
377                 if ((fd = open(buf, O_RDONLY))>=0) return fd;
378                 s += l;
379         }
380 }
381
382 static void decode_dyn(struct dso *p)
383 {
384         size_t dyn[DYN_CNT] = {0};
385         decode_vec(p->dynv, dyn, DYN_CNT);
386         p->syms = (void *)(p->base + dyn[DT_SYMTAB]);
387         p->strings = (void *)(p->base + dyn[DT_STRTAB]);
388         if (dyn[0]&(1<<DT_HASH))
389                 p->hashtab = (void *)(p->base + dyn[DT_HASH]);
390         if (search_vec(p->dynv, dyn, DT_GNU_HASH))
391                 p->ghashtab = (void *)(p->base + *dyn);
392 }
393
394 static struct dso *load_library(const char *name)
395 {
396         char buf[2*NAME_MAX+2];
397         const char *pathname;
398         unsigned char *base, *map;
399         size_t dyno, map_len;
400         struct dso *p;
401         int fd;
402         struct stat st;
403
404         /* Catch and block attempts to reload the implementation itself */
405         if (name[0]=='l' && name[1]=='i' && name[2]=='b') {
406                 static const char *rp, reserved[] =
407                         "c\0pthread\0rt\0m\0dl\0util\0xnet\0";
408                 char *z = strchr(name, '.');
409                 if (z) {
410                         size_t l = z-name;
411                         for (rp=reserved; *rp && memcmp(name+3, rp, l-3); rp+=strlen(rp)+1);
412                         if (*rp) {
413                                 if (!libc->prev) {
414                                         tail->next = libc;
415                                         libc->prev = tail;
416                                         tail = libc->next ? libc->next : libc;
417                                 }
418                                 return libc;
419                         }
420                 }
421         }
422         if (strchr(name, '/')) {
423                 pathname = name;
424                 fd = open(name, O_RDONLY);
425         } else {
426                 /* Search for the name to see if it's already loaded */
427                 for (p=head->next; p; p=p->next) {
428                         if (p->shortname && !strcmp(p->shortname, name)) {
429                                 p->refcnt++;
430                                 return p;
431                         }
432                 }
433                 if (strlen(name) > NAME_MAX) return 0;
434                 fd = -1;
435                 if (r_path) fd = path_open(name, r_path, buf, sizeof buf);
436                 if (fd < 0 && env_path) fd = path_open(name, env_path, buf, sizeof buf);
437                 if (fd < 0) {
438                         if (!sys_path) {
439                                 FILE *f = fopen(ETC_LDSO_PATH, "r");
440                                 if (f) {
441                                         if (getline(&sys_path, (size_t[1]){0}, f) > 0)
442                                                 sys_path[strlen(sys_path)-1]=0;
443                                         fclose(f);
444                                 }
445                         }
446                         if (sys_path) fd = path_open(name, sys_path, buf, sizeof buf);
447                         else fd = path_open(name, "/lib:/usr/local/lib:/usr/lib", buf, sizeof buf);
448                 }
449                 pathname = buf;
450         }
451         if (fd < 0) return 0;
452         if (fstat(fd, &st) < 0) {
453                 close(fd);
454                 return 0;
455         }
456         for (p=head->next; p; p=p->next) {
457                 if (p->dev == st.st_dev && p->ino == st.st_ino) {
458                         /* If this library was previously loaded with a
459                          * pathname but a search found the same inode,
460                          * setup its shortname so it can be found by name. */
461                         if (!p->shortname) p->shortname = strrchr(p->name, '/')+1;
462                         close(fd);
463                         p->refcnt++;
464                         return p;
465                 }
466         }
467         map = map_library(fd, &map_len, &base, &dyno);
468         close(fd);
469         if (!map) return 0;
470         p = calloc(1, sizeof *p + strlen(pathname) + 1);
471         if (!p) {
472                 munmap(map, map_len);
473                 return 0;
474         }
475
476         p->map = map;
477         p->map_len = map_len;
478         p->base = base;
479         p->dynv = (void *)(base + dyno);
480         decode_dyn(p);
481
482         p->dev = st.st_dev;
483         p->ino = st.st_ino;
484         p->refcnt = 1;
485         p->name = p->buf;
486         strcpy(p->name, pathname);
487         /* Add a shortname only if name arg was not an explicit pathname. */
488         if (pathname != name) p->shortname = strrchr(p->name, '/')+1;
489
490         tail->next = p;
491         p->prev = tail;
492         tail = p;
493
494         if (ldd_mode) dprintf(1, "\t%s => %s (%p)\n", name, pathname, base);
495
496         return p;
497 }
498
499 static void load_deps(struct dso *p)
500 {
501         size_t i, ndeps=0;
502         struct dso ***deps = &p->deps, **tmp, *dep;
503         for (; p; p=p->next) {
504                 for (i=0; p->dynv[i]; i+=2) {
505                         if (p->dynv[i] != DT_RPATH) continue;
506                         r_path = (void *)(p->strings + p->dynv[i+1]);
507                 }
508                 for (i=0; p->dynv[i]; i+=2) {
509                         if (p->dynv[i] != DT_NEEDED) continue;
510                         dep = load_library(p->strings + p->dynv[i+1]);
511                         if (!dep) {
512                                 snprintf(errbuf, sizeof errbuf,
513                                         "Error loading shared library %s: %m (needed by %s)",
514                                         p->strings + p->dynv[i+1], p->name);
515                                 if (runtime) longjmp(rtld_fail, 1);
516                                 dprintf(2, "%s\n", errbuf);
517                                 ldso_fail = 1;
518                                 continue;
519                         }
520                         if (runtime) {
521                                 tmp = realloc(*deps, sizeof(*tmp)*(ndeps+2));
522                                 if (!tmp) longjmp(rtld_fail, 1);
523                                 tmp[ndeps++] = dep;
524                                 tmp[ndeps] = 0;
525                                 *deps = tmp;
526                         }
527                 }
528                 r_path = 0;
529         }
530 }
531
532 static void load_preload(char *s)
533 {
534         int tmp;
535         char *z;
536         for (z=s; *z; s=z) {
537                 for (   ; *s && isspace(*s); s++);
538                 for (z=s; *z && !isspace(*z); z++);
539                 tmp = *z;
540                 *z = 0;
541                 load_library(s);
542                 *z = tmp;
543         }
544 }
545
546 static void make_global(struct dso *p)
547 {
548         for (; p; p=p->next) p->global = 1;
549 }
550
551 static void reloc_all(struct dso *p)
552 {
553         size_t dyn[DYN_CNT] = {0};
554         for (; p; p=p->next) {
555                 if (p->relocated) continue;
556                 decode_vec(p->dynv, dyn, DYN_CNT);
557 #ifdef NEED_ARCH_RELOCS
558                 do_arch_relocs(p, head);
559 #endif
560                 do_relocs(p, (void *)(p->base+dyn[DT_JMPREL]), dyn[DT_PLTRELSZ],
561                         2+(dyn[DT_PLTREL]==DT_RELA));
562                 do_relocs(p, (void *)(p->base+dyn[DT_REL]), dyn[DT_RELSZ], 2);
563                 do_relocs(p, (void *)(p->base+dyn[DT_RELA]), dyn[DT_RELASZ], 3);
564                 p->relocated = 1;
565         }
566 }
567
568 static void free_all(struct dso *p)
569 {
570         struct dso *n;
571         while (p) {
572                 n = p->next;
573                 if (p->map) free(p);
574                 p = n;
575         }
576 }
577
578 static size_t find_dyn(Phdr *ph, size_t cnt, size_t stride)
579 {
580         for (; cnt--; ph = (void *)((char *)ph + stride))
581                 if (ph->p_type == PT_DYNAMIC)
582                         return ph->p_vaddr;
583         return 0;
584 }
585
586 static void do_init_fini(struct dso *p)
587 {
588         size_t dyn[DYN_CNT] = {0};
589         for (; p; p=p->prev) {
590                 if (p->constructed) return;
591                 decode_vec(p->dynv, dyn, DYN_CNT);
592                 if (dyn[0] & (1<<DT_FINI))
593                         atexit((void (*)(void))(p->base + dyn[DT_FINI]));
594                 if (dyn[0] & (1<<DT_INIT))
595                         ((void (*)(void))(p->base + dyn[DT_INIT]))();
596                 p->constructed = 1;
597         }
598 }
599
600 void _dl_debug_state(void)
601 {
602 }
603
604 void *__dynlink(int argc, char **argv)
605 {
606         size_t *auxv, aux[AUX_CNT] = {0};
607         size_t i;
608         Phdr *phdr;
609         Ehdr *ehdr;
610         static struct dso builtin_dsos[3];
611         struct dso *const app = builtin_dsos+0;
612         struct dso *const lib = builtin_dsos+1;
613         struct dso *const vdso = builtin_dsos+2;
614         char *env_preload=0;
615
616         /* Find aux vector just past environ[] */
617         for (i=argc+1; argv[i]; i++)
618                 if (!memcmp(argv[i], "LD_LIBRARY_PATH=", 16))
619                         env_path = argv[i]+16;
620                 else if (!memcmp(argv[i], "LD_PRELOAD=", 11))
621                         env_preload = argv[i]+11;
622         auxv = (void *)(argv+i+1);
623
624         decode_vec(auxv, aux, AUX_CNT);
625
626         /* Only trust user/env if kernel says we're not suid/sgid */
627         if ((aux[0]&0x7800)!=0x7800 || aux[AT_UID]!=aux[AT_EUID]
628           || aux[AT_GID]!=aux[AT_EGID] || aux[AT_SECURE]) {
629                 env_path = 0;
630                 env_preload = 0;
631         }
632
633         /* If the dynamic linker was invoked as a program itself, AT_BASE
634          * will not be set. In that case, we assume the base address is
635          * the start of the page containing the PHDRs; I don't know any
636          * better approach... */
637         if (!aux[AT_BASE]) {
638                 aux[AT_BASE] = aux[AT_PHDR] & -PAGE_SIZE;
639                 aux[AT_PHDR] = aux[AT_PHENT] = aux[AT_PHNUM] = 0;
640         }
641
642         /* The dynamic linker load address is passed by the kernel
643          * in the AUX vector, so this is easy. */
644         lib->base = (void *)aux[AT_BASE];
645         lib->name = lib->shortname = "libc.so";
646         lib->global = 1;
647         ehdr = (void *)lib->base;
648         lib->dynv = (void *)(lib->base + find_dyn(
649                 (void *)(aux[AT_BASE]+ehdr->e_phoff),
650                 ehdr->e_phnum, ehdr->e_phentsize));
651         decode_dyn(lib);
652
653         if (aux[AT_PHDR]) {
654                 size_t interp_off = 0;
655                 /* Find load address of the main program, via AT_PHDR vs PT_PHDR. */
656                 phdr = (void *)aux[AT_PHDR];
657                 for (i=aux[AT_PHNUM]; i; i--, phdr=(void *)((char *)phdr + aux[AT_PHENT])) {
658                         if (phdr->p_type == PT_PHDR)
659                                 app->base = (void *)(aux[AT_PHDR] - phdr->p_vaddr);
660                         else if (phdr->p_type == PT_INTERP)
661                                 interp_off = (size_t)phdr->p_vaddr;
662                 }
663                 if (interp_off) lib->name = (char *)app->base + interp_off;
664                 app->name = argv[0];
665                 app->dynv = (void *)(app->base + find_dyn(
666                         (void *)aux[AT_PHDR], aux[AT_PHNUM], aux[AT_PHENT]));
667         } else {
668                 int fd;
669                 char *ldname = argv[0];
670                 size_t dyno, l = strlen(ldname);
671                 if (l >= 3 && !strcmp(ldname+l-3, "ldd")) ldd_mode = 1;
672                 *argv++ = (void *)-1;
673                 if (argv[0] && !strcmp(argv[0], "--")) *argv++ = (void *)-1;
674                 if (!argv[0]) {
675                         dprintf(2, "musl libc/dynamic program loader\n");
676                         dprintf(2, "usage: %s pathname%s\n", ldname,
677                                 ldd_mode ? "" : " [args]");
678                         _exit(1);
679                 }
680                 fd = open(argv[0], O_RDONLY);
681                 if (fd < 0) {
682                         dprintf(2, "%s: cannot load %s: %s\n", ldname, argv[0], strerror(errno));
683                         _exit(1);
684                 }
685                 runtime = 1;
686                 ehdr = (void *)map_library(fd, &app->map_len, &app->base, &dyno);
687                 if (!ehdr) {
688                         dprintf(2, "%s: %s: Not a valid dynamic program\n", ldname, argv[0]);
689                         _exit(1);
690                 }
691                 runtime = 0;
692                 close(fd);
693                 lib->name = ldname;
694                 app->name = argv[0];
695                 app->dynv = (void *)(app->base + dyno);
696                 aux[AT_ENTRY] = ehdr->e_entry;
697         }
698         app->global = 1;
699         app->constructed = 1;
700         decode_dyn(app);
701
702         /* Attach to vdso, if provided by the kernel */
703         for (i=0; auxv[i]; i+=2) {
704                 size_t vdso_base = auxv[i+1];
705                 if (auxv[i] != AT_SYSINFO_EHDR) continue;
706                 ehdr = (void *)vdso_base;
707                 phdr = (void *)(vdso_base + ehdr->e_phoff);
708                 for (i=ehdr->e_phnum; i; i--, phdr=(void *)((char *)phdr + ehdr->e_phentsize)) {
709                         if (phdr->p_type == PT_DYNAMIC)
710                                 vdso->dynv = (void *)(vdso_base + phdr->p_offset);
711                         if (phdr->p_type == PT_LOAD)
712                                 vdso->base = (void *)(vdso_base - phdr->p_vaddr + phdr->p_offset);
713                 }
714                 vdso->name = vdso->shortname = "linux-gate.so.1";
715                 vdso->global = 1;
716                 decode_dyn(vdso);
717                 vdso->prev = lib;
718                 lib->next = vdso;
719                 break;
720         }
721
722         /* Initial dso chain consists only of the app. We temporarily
723          * append the dynamic linker/libc so we can relocate it, then
724          * restore the initial chain in preparation for loading third
725          * party libraries (preload/needed). */
726         head = tail = app;
727         libc = lib;
728         app->next = lib;
729         reloc_all(lib);
730         app->next = 0;
731
732         /* PAST THIS POINT, ALL LIBC INTERFACES ARE FULLY USABLE. */
733
734         /* Donate unused parts of app and library mapping to malloc */
735         reclaim_gaps(app->base, (void *)aux[AT_PHDR], aux[AT_PHENT], aux[AT_PHNUM]);
736         ehdr = (void *)lib->base;
737         reclaim_gaps(lib->base, (void *)(lib->base+ehdr->e_phoff),
738                 ehdr->e_phentsize, ehdr->e_phnum);
739
740         /* Load preload/needed libraries, add their symbols to the global
741          * namespace, and perform all remaining relocations. The main
742          * program must be relocated LAST since it may contain copy
743          * relocations which depend on libraries' relocations. */
744         if (env_preload) load_preload(env_preload);
745         load_deps(app);
746         make_global(app);
747         reloc_all(app->next);
748         reloc_all(app);
749
750         if (ldso_fail) _exit(127);
751         if (ldd_mode) _exit(0);
752
753         /* Switch to runtime mode: any further failures in the dynamic
754          * linker are a reportable failure rather than a fatal startup
755          * error. If the dynamic loader (dlopen) will not be used, free
756          * all memory used by the dynamic linker. */
757         runtime = 1;
758
759 #ifndef DYNAMIC_IS_RO
760         for (i=0; app->dynv[i]; i+=2)
761                 if (app->dynv[i]==DT_DEBUG)
762                         app->dynv[i+1] = (size_t)&debug;
763 #endif
764         debug.ver = 1;
765         debug.bp = _dl_debug_state;
766         debug.head = head;
767         debug.base = lib->base;
768         debug.state = 0;
769         _dl_debug_state();
770
771         if (ssp_used) __init_ssp(auxv);
772
773         do_init_fini(tail);
774
775         if (!rtld_used) {
776                 free_all(head);
777                 free(sys_path);
778                 reclaim((void *)builtin_dsos, 0, sizeof builtin_dsos);
779         }
780
781         errno = 0;
782         return (void *)aux[AT_ENTRY];
783 }
784
785 void *dlopen(const char *file, int mode)
786 {
787         struct dso *volatile p, *orig_tail = tail, *next;
788         size_t i;
789         int cs;
790
791         if (!file) return head;
792
793         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
794         pthread_rwlock_wrlock(&lock);
795
796         if (setjmp(rtld_fail)) {
797                 /* Clean up anything new that was (partially) loaded */
798                 if (p->deps) for (i=0; p->deps[i]; i++)
799                         if (p->deps[i]->global < 0)
800                                 p->deps[i]->global = 0;
801                 for (p=orig_tail->next; p; p=next) {
802                         next = p->next;
803                         munmap(p->map, p->map_len);
804                         free(p->deps);
805                         free(p);
806                 }
807                 tail = orig_tail;
808                 tail->next = 0;
809                 p = 0;
810                 errflag = 1;
811                 goto end;
812         } else p = load_library(file);
813
814         if (!p) {
815                 snprintf(errbuf, sizeof errbuf,
816                         "Error loading shared library %s: %m", file);
817                 errflag = 1;
818                 goto end;
819         }
820
821         /* First load handling */
822         if (!p->deps) {
823                 load_deps(p);
824                 if (p->deps) for (i=0; p->deps[i]; i++)
825                         if (!p->deps[i]->global)
826                                 p->deps[i]->global = -1;
827                 if (!p->global) p->global = -1;
828                 reloc_all(p);
829                 if (p->deps) for (i=0; p->deps[i]; i++)
830                         if (p->deps[i]->global < 0)
831                                 p->deps[i]->global = 0;
832                 if (p->global < 0) p->global = 0;
833         }
834
835         if (mode & RTLD_GLOBAL) {
836                 if (p->deps) for (i=0; p->deps[i]; i++)
837                         p->deps[i]->global = 1;
838                 p->global = 1;
839         }
840
841         _dl_debug_state();
842
843         do_init_fini(tail);
844 end:
845         pthread_rwlock_unlock(&lock);
846         pthread_setcancelstate(cs, 0);
847         return p;
848 }
849
850 static void *do_dlsym(struct dso *p, const char *s, void *ra)
851 {
852         size_t i;
853         uint32_t h = 0, gh = 0;
854         Sym *sym;
855         if (p == RTLD_NEXT) {
856                 for (p=head; p && (unsigned char *)ra-p->map>p->map_len; p=p->next);
857                 if (!p) p=head;
858                 void *res = find_sym(p->next, s, 0);
859                 if (!res) goto failed;
860                 return res;
861         }
862         if (p == head || p == RTLD_DEFAULT) {
863                 void *res = find_sym(head, s, 0);
864                 if (!res) goto failed;
865                 return res;
866         }
867         if (p->ghashtab) {
868                 gh = gnu_hash(s);
869                 sym = gnu_lookup(s, gh, p);
870         } else {
871                 h = sysv_hash(s);
872                 sym = sysv_lookup(s, h, p);
873         }
874         if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
875                 return p->base + sym->st_value;
876         if (p->deps) for (i=0; p->deps[i]; i++) {
877                 if (p->deps[i]->ghashtab) {
878                         if (!gh) gh = gnu_hash(s);
879                         sym = gnu_lookup(s, h, p->deps[i]);
880                 } else {
881                         if (!h) h = sysv_hash(s);
882                         sym = sysv_lookup(s, h, p->deps[i]);
883                 }
884                 if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
885                         return p->deps[i]->base + sym->st_value;
886         }
887 failed:
888         errflag = 1;
889         snprintf(errbuf, sizeof errbuf, "Symbol not found: %s", s);
890         return 0;
891 }
892
893 void *__dlsym(void *p, const char *s, void *ra)
894 {
895         void *res;
896         pthread_rwlock_rdlock(&lock);
897         res = do_dlsym(p, s, ra);
898         pthread_rwlock_unlock(&lock);
899         return res;
900 }
901 #else
902 void *dlopen(const char *file, int mode)
903 {
904         return 0;
905 }
906 void *__dlsym(void *p, const char *s, void *ra)
907 {
908         return 0;
909 }
910 #endif
911
912 char *dlerror()
913 {
914         if (!errflag) return 0;
915         errflag = 0;
916         return errbuf;
917 }
918
919 int dlclose(void *p)
920 {
921         return 0;
922 }