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