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