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