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