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