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