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