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