partial TLS support for dynamic-linked programs
[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 *__dynlink(int argc, char **argv)
658 {
659         size_t aux[AUX_CNT] = {0};
660         size_t i;
661         Phdr *phdr;
662         Ehdr *ehdr;
663         static struct dso builtin_dsos[3];
664         struct dso *const app = builtin_dsos+0;
665         struct dso *const lib = builtin_dsos+1;
666         struct dso *const vdso = builtin_dsos+2;
667         char *env_preload=0;
668         size_t vdso_base;
669
670         /* Find aux vector just past environ[] */
671         for (i=argc+1; argv[i]; i++)
672                 if (!memcmp(argv[i], "LD_LIBRARY_PATH=", 16))
673                         env_path = argv[i]+16;
674                 else if (!memcmp(argv[i], "LD_PRELOAD=", 11))
675                         env_preload = argv[i]+11;
676         auxv = (void *)(argv+i+1);
677
678         decode_vec(auxv, aux, AUX_CNT);
679
680         /* Only trust user/env if kernel says we're not suid/sgid */
681         if ((aux[0]&0x7800)!=0x7800 || aux[AT_UID]!=aux[AT_EUID]
682           || aux[AT_GID]!=aux[AT_EGID] || aux[AT_SECURE]) {
683                 env_path = 0;
684                 env_preload = 0;
685         }
686
687         /* If the dynamic linker was invoked as a program itself, AT_BASE
688          * will not be set. In that case, we assume the base address is
689          * the start of the page containing the PHDRs; I don't know any
690          * better approach... */
691         if (!aux[AT_BASE]) {
692                 aux[AT_BASE] = aux[AT_PHDR] & -PAGE_SIZE;
693                 aux[AT_PHDR] = aux[AT_PHENT] = aux[AT_PHNUM] = 0;
694         }
695
696         /* The dynamic linker load address is passed by the kernel
697          * in the AUX vector, so this is easy. */
698         lib->base = (void *)aux[AT_BASE];
699         lib->name = lib->shortname = "libc.so";
700         lib->global = 1;
701         ehdr = (void *)lib->base;
702         find_map_range((void *)(aux[AT_BASE]+ehdr->e_phoff),
703                 ehdr->e_phnum, ehdr->e_phentsize, lib);
704         lib->dynv = (void *)(lib->base + find_dyn(
705                 (void *)(aux[AT_BASE]+ehdr->e_phoff),
706                 ehdr->e_phnum, ehdr->e_phentsize));
707         decode_dyn(lib);
708
709         if (aux[AT_PHDR]) {
710                 size_t interp_off = 0;
711                 size_t tls_image = 0;
712                 /* Find load address of the main program, via AT_PHDR vs PT_PHDR. */
713                 phdr = (void *)aux[AT_PHDR];
714                 for (i=aux[AT_PHNUM]; i; i--, phdr=(void *)((char *)phdr + aux[AT_PHENT])) {
715                         if (phdr->p_type == PT_PHDR)
716                                 app->base = (void *)(aux[AT_PHDR] - phdr->p_vaddr);
717                         else if (phdr->p_type == PT_INTERP)
718                                 interp_off = (size_t)phdr->p_vaddr;
719                         else if (phdr->p_type == PT_TLS) {
720                                 tls_image = phdr->p_vaddr;
721                                 app->tls_len = phdr->p_filesz;
722                                 app->tls_size = phdr->p_memsz;
723                                 app->tls_align = phdr->p_align;
724                         }
725                 }
726                 if (app->tls_size) app->tls_image = (char *)app->base + tls_image;
727                 if (interp_off) lib->name = (char *)app->base + interp_off;
728                 app->name = argv[0];
729                 app->dynv = (void *)(app->base + find_dyn(
730                         (void *)aux[AT_PHDR], aux[AT_PHNUM], aux[AT_PHENT]));
731                 find_map_range((void *)aux[AT_PHDR],
732                         aux[AT_PHNUM], aux[AT_PHENT], app);
733         } else {
734                 int fd;
735                 char *ldname = argv[0];
736                 size_t dyno, l = strlen(ldname);
737                 if (l >= 3 && !strcmp(ldname+l-3, "ldd")) ldd_mode = 1;
738                 *argv++ = (void *)-1;
739                 if (argv[0] && !strcmp(argv[0], "--")) *argv++ = (void *)-1;
740                 if (!argv[0]) {
741                         dprintf(2, "musl libc/dynamic program loader\n");
742                         dprintf(2, "usage: %s pathname%s\n", ldname,
743                                 ldd_mode ? "" : " [args]");
744                         _exit(1);
745                 }
746                 fd = open(argv[0], O_RDONLY);
747                 if (fd < 0) {
748                         dprintf(2, "%s: cannot load %s: %s\n", ldname, argv[0], strerror(errno));
749                         _exit(1);
750                 }
751                 runtime = 1;
752                 ehdr = (void *)map_library(fd, app);
753                 if (!ehdr) {
754                         dprintf(2, "%s: %s: Not a valid dynamic program\n", ldname, argv[0]);
755                         _exit(1);
756                 }
757                 runtime = 0;
758                 close(fd);
759                 lib->name = ldname;
760                 app->name = argv[0];
761                 aux[AT_ENTRY] = ehdr->e_entry;
762         }
763         if (app->tls_size) {
764                 app->tls_id = ++tls_cnt;
765                 tls_size += app->tls_size+app->tls_align + 8*sizeof(size_t)-1
766                         & -4*sizeof(size_t);
767         }
768         app->global = 1;
769         app->constructed = 1;
770         decode_dyn(app);
771
772         /* Attach to vdso, if provided by the kernel */
773         if (search_vec(auxv, &vdso_base, AT_SYSINFO_EHDR)) {
774                 ehdr = (void *)vdso_base;
775                 phdr = (void *)(vdso_base + ehdr->e_phoff);
776                 for (i=ehdr->e_phnum; i; i--, phdr=(void *)((char *)phdr + ehdr->e_phentsize)) {
777                         if (phdr->p_type == PT_DYNAMIC)
778                                 vdso->dynv = (void *)(vdso_base + phdr->p_offset);
779                         if (phdr->p_type == PT_LOAD)
780                                 vdso->base = (void *)(vdso_base - phdr->p_vaddr + phdr->p_offset);
781                 }
782                 vdso->name = vdso->shortname = "linux-gate.so.1";
783                 vdso->global = 1;
784                 decode_dyn(vdso);
785                 vdso->prev = lib;
786                 lib->next = vdso;
787         }
788
789         /* Initial dso chain consists only of the app. We temporarily
790          * append the dynamic linker/libc so we can relocate it, then
791          * restore the initial chain in preparation for loading third
792          * party libraries (preload/needed). */
793         head = tail = app;
794         libc = lib;
795         app->next = lib;
796         reloc_all(lib);
797         app->next = 0;
798
799         /* PAST THIS POINT, ALL LIBC INTERFACES ARE FULLY USABLE. */
800
801         /* Donate unused parts of app and library mapping to malloc */
802         reclaim_gaps(app->base, (void *)aux[AT_PHDR], aux[AT_PHENT], aux[AT_PHNUM]);
803         ehdr = (void *)lib->base;
804         reclaim_gaps(lib->base, (void *)(lib->base+ehdr->e_phoff),
805                 ehdr->e_phentsize, ehdr->e_phnum);
806
807         /* Load preload/needed libraries, add their symbols to the global
808          * namespace, and perform all remaining relocations. The main
809          * program must be relocated LAST since it may contain copy
810          * relocations which depend on libraries' relocations. */
811         if (env_preload) load_preload(env_preload);
812         load_deps(app);
813         make_global(app);
814         reloc_all(app->next);
815         reloc_all(app);
816
817         if (ldso_fail) _exit(127);
818         if (ldd_mode) _exit(0);
819
820         /* Switch to runtime mode: any further failures in the dynamic
821          * linker are a reportable failure rather than a fatal startup
822          * error. If the dynamic loader (dlopen) will not be used, free
823          * all memory used by the dynamic linker. */
824         runtime = 1;
825
826 #ifndef DYNAMIC_IS_RO
827         for (i=0; app->dynv[i]; i+=2)
828                 if (app->dynv[i]==DT_DEBUG)
829                         app->dynv[i+1] = (size_t)&debug;
830 #endif
831         debug.ver = 1;
832         debug.bp = _dl_debug_state;
833         debug.head = head;
834         debug.base = lib->base;
835         debug.state = 0;
836         _dl_debug_state();
837
838         tls_size += sizeof(struct pthread) + 4*sizeof(size_t);
839         __libc.tls_size = tls_size;
840         __libc.tls_cnt = tls_cnt;
841         if (tls_cnt) {
842                 void *mem = mmap(0, __libc.tls_size, PROT_READ|PROT_WRITE,
843                         MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
844                 if (mem==MAP_FAILED ||
845                     !__install_initial_tls(__copy_tls(mem, tls_cnt))) {
846                         dprintf(2, "%s: Error getting %zu bytes thread-local storage: %m\n",
847                                 argv[0], tls_size);
848                         _exit(127);
849                 }
850         }
851         if (ssp_used) __init_ssp(auxv);
852
853         do_init_fini(tail);
854
855         if (!rtld_used) {
856                 free_all(head);
857                 free(sys_path);
858                 reclaim((void *)builtin_dsos, 0, sizeof builtin_dsos);
859         }
860
861         errno = 0;
862         return (void *)aux[AT_ENTRY];
863 }
864
865 void *dlopen(const char *file, int mode)
866 {
867         struct dso *volatile p, *orig_tail = tail, *next;
868         size_t i;
869         int cs;
870
871         if (!file) return head;
872
873         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
874         pthread_rwlock_wrlock(&lock);
875
876         if (setjmp(rtld_fail)) {
877                 /* Clean up anything new that was (partially) loaded */
878                 if (p->deps) for (i=0; p->deps[i]; i++)
879                         if (p->deps[i]->global < 0)
880                                 p->deps[i]->global = 0;
881                 for (p=orig_tail->next; p; p=next) {
882                         next = p->next;
883                         munmap(p->map, p->map_len);
884                         free(p->deps);
885                         free(p);
886                 }
887                 tail = orig_tail;
888                 tail->next = 0;
889                 p = 0;
890                 errflag = 1;
891                 goto end;
892         } else p = load_library(file);
893
894         if (!p) {
895                 snprintf(errbuf, sizeof errbuf,
896                         "Error loading shared library %s: %m", file);
897                 errflag = 1;
898                 goto end;
899         }
900
901         /* First load handling */
902         if (!p->deps) {
903                 load_deps(p);
904                 if (p->deps) for (i=0; p->deps[i]; i++)
905                         if (!p->deps[i]->global)
906                                 p->deps[i]->global = -1;
907                 if (!p->global) p->global = -1;
908                 reloc_all(p);
909                 if (p->deps) for (i=0; p->deps[i]; i++)
910                         if (p->deps[i]->global < 0)
911                                 p->deps[i]->global = 0;
912                 if (p->global < 0) p->global = 0;
913         }
914
915         if (mode & RTLD_GLOBAL) {
916                 if (p->deps) for (i=0; p->deps[i]; i++)
917                         p->deps[i]->global = 1;
918                 p->global = 1;
919         }
920
921         if (ssp_used) __init_ssp(auxv);
922
923         _dl_debug_state();
924
925         do_init_fini(tail);
926 end:
927         pthread_rwlock_unlock(&lock);
928         pthread_setcancelstate(cs, 0);
929         return p;
930 }
931
932 static void *do_dlsym(struct dso *p, const char *s, void *ra)
933 {
934         size_t i;
935         uint32_t h = 0, gh = 0;
936         Sym *sym;
937         if (p == RTLD_NEXT) {
938                 for (p=head; p && (unsigned char *)ra-p->map>p->map_len; p=p->next);
939                 if (!p) p=head;
940                 void *res = find_sym(p->next, s, 0);
941                 if (!res) goto failed;
942                 return res;
943         }
944         if (p == head || p == RTLD_DEFAULT) {
945                 void *res = find_sym(head, s, 0);
946                 if (!res) goto failed;
947                 return res;
948         }
949         if (p->ghashtab) {
950                 gh = gnu_hash(s);
951                 sym = gnu_lookup(s, gh, p);
952         } else {
953                 h = sysv_hash(s);
954                 sym = sysv_lookup(s, h, p);
955         }
956         if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
957                 return p->base + sym->st_value;
958         if (p->deps) for (i=0; p->deps[i]; i++) {
959                 if (p->deps[i]->ghashtab) {
960                         if (!gh) gh = gnu_hash(s);
961                         sym = gnu_lookup(s, gh, p->deps[i]);
962                 } else {
963                         if (!h) h = sysv_hash(s);
964                         sym = sysv_lookup(s, h, p->deps[i]);
965                 }
966                 if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
967                         return p->deps[i]->base + sym->st_value;
968         }
969 failed:
970         errflag = 1;
971         snprintf(errbuf, sizeof errbuf, "Symbol not found: %s", s);
972         return 0;
973 }
974
975 int __dladdr(void *addr, Dl_info *info)
976 {
977         struct dso *p;
978         Sym *sym;
979         uint32_t nsym;
980         char *strings;
981         size_t i;
982         void *best = 0;
983         char *bestname;
984
985         pthread_rwlock_rdlock(&lock);
986         for (p=head; p && (unsigned char *)addr-p->map>p->map_len; p=p->next);
987         pthread_rwlock_unlock(&lock);
988
989         if (!p) return 0;
990
991         sym = p->syms;
992         strings = p->strings;
993         if (p->hashtab) {
994                 nsym = p->hashtab[1];
995         } else {
996                 uint32_t *buckets;
997                 uint32_t *hashval;
998                 buckets = p->ghashtab + 4 + (p->ghashtab[2]*sizeof(size_t)/4);
999                 sym += p->ghashtab[1];
1000                 for (i = 0; i < p->ghashtab[0]; i++) {
1001                         if (buckets[i] > nsym)
1002                                 nsym = buckets[i];
1003                 }
1004                 if (nsym) {
1005                         nsym -= p->ghashtab[1];
1006                         hashval = buckets + p->ghashtab[0] + nsym;
1007                         do nsym++;
1008                         while (!(*hashval++ & 1));
1009                 }
1010         }
1011
1012         for (; nsym; nsym--, sym++) {
1013                 if (sym->st_shndx && sym->st_value
1014                  && (1<<(sym->st_info&0xf) & OK_TYPES)
1015                  && (1<<(sym->st_info>>4) & OK_BINDS)) {
1016                         void *symaddr = p->base + sym->st_value;
1017                         if (symaddr > addr || symaddr < best)
1018                                 continue;
1019                         best = symaddr;
1020                         bestname = strings + sym->st_name;
1021                         if (addr == symaddr)
1022                                 break;
1023                 }
1024         }
1025
1026         if (!best) return 0;
1027
1028         info->dli_fname = p->name;
1029         info->dli_fbase = p->base;
1030         info->dli_sname = bestname;
1031         info->dli_saddr = best;
1032
1033         return 1;
1034 }
1035
1036 void *__dlsym(void *restrict p, const char *restrict s, void *restrict ra)
1037 {
1038         void *res;
1039         pthread_rwlock_rdlock(&lock);
1040         res = do_dlsym(p, s, ra);
1041         pthread_rwlock_unlock(&lock);
1042         return res;
1043 }
1044 #else
1045 void *dlopen(const char *file, int mode)
1046 {
1047         return 0;
1048 }
1049 void *__dlsym(void *restrict p, const char *restrict s, void *restrict ra)
1050 {
1051         return 0;
1052 }
1053 int __dladdr (void *addr, Dl_info *info)
1054 {
1055         return 0;
1056 }
1057 #endif
1058
1059 char *dlerror()
1060 {
1061         if (!errflag) return 0;
1062         errflag = 0;
1063         return errbuf;
1064 }
1065
1066 int dlclose(void *p)
1067 {
1068         return 0;
1069 }