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