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