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