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