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