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