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