work around libraries with versioned symbols in dynamic linker
[musl] / src / ldso / dynlink.c
1 #define _GNU_SOURCE
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <unistd.h>
6 #include <stdint.h>
7 #include <elf.h>
8 #include <sys/mman.h>
9 #include <limits.h>
10 #include <stdint.h>
11 #include <fcntl.h>
12 #include <sys/stat.h>
13 #include <errno.h>
14 #include <limits.h>
15 #include <elf.h>
16 #include <link.h>
17 #include <setjmp.h>
18 #include <pthread.h>
19 #include <ctype.h>
20 #include <dlfcn.h>
21 #include "pthread_impl.h"
22 #include "libc.h"
23
24 static int errflag;
25 static char errbuf[128];
26
27 #ifdef SHARED
28
29 #if ULONG_MAX == 0xffffffff
30 typedef Elf32_Ehdr Ehdr;
31 typedef Elf32_Phdr Phdr;
32 typedef Elf32_Sym Sym;
33 #define R_TYPE(x) ((x)&255)
34 #define R_SYM(x) ((x)>>8)
35 #else
36 typedef Elf64_Ehdr Ehdr;
37 typedef Elf64_Phdr Phdr;
38 typedef Elf64_Sym Sym;
39 #define R_TYPE(x) ((x)&0xffffffff)
40 #define R_SYM(x) ((x)>>32)
41 #endif
42
43 #define MAXP2(a,b) (-(-(a)&-(b)))
44 #define ALIGN(x,y) ((x)+(y)-1 & -(y))
45
46 struct debug {
47         int ver;
48         void *head;
49         void (*bp)(void);
50         int state;
51         void *base;
52 };
53
54 struct dso {
55         unsigned char *base;
56         char *name;
57         size_t *dynv;
58         struct dso *next, *prev;
59
60         Phdr *phdr;
61         int phnum;
62         int refcnt;
63         Sym *syms;
64         uint32_t *hashtab;
65         uint32_t *ghashtab;
66         int16_t *versym;
67         char *strings;
68         unsigned char *map;
69         size_t map_len;
70         dev_t dev;
71         ino_t ino;
72         signed char global;
73         char relocated;
74         char constructed;
75         struct dso **deps;
76         void *tls_image;
77         size_t tls_len, tls_size, tls_align, tls_id, tls_offset;
78         void **new_dtv;
79         unsigned char *new_tls;
80         int new_dtv_idx, new_tls_idx;
81         struct dso *fini_next;
82         char *shortname;
83         char buf[];
84 };
85
86 struct symdef {
87         Sym *sym;
88         struct dso *dso;
89 };
90
91 #include "reloc.h"
92
93 void __init_ssp(size_t *);
94 void *__install_initial_tls(void *);
95 void __init_libc(char **, char *);
96
97 static struct dso *head, *tail, *ldso, *fini_head;
98 static char *env_path, *sys_path, *r_path;
99 static unsigned long long gencnt;
100 static int ssp_used;
101 static int runtime;
102 static int ldd_mode;
103 static int ldso_fail;
104 static int noload;
105 static jmp_buf *rtld_fail;
106 static pthread_rwlock_t lock;
107 static struct debug debug;
108 static size_t tls_cnt, tls_offset, tls_align = 4*sizeof(size_t);
109 static pthread_mutex_t init_fini_lock = { ._m_type = PTHREAD_MUTEX_RECURSIVE };
110
111 struct debug *_dl_debug_addr = &debug;
112
113 #define AUX_CNT 38
114 #define DYN_CNT 34
115
116 static void decode_vec(size_t *v, size_t *a, size_t cnt)
117 {
118         memset(a, 0, cnt*sizeof(size_t));
119         for (; v[0]; v+=2) if (v[0]<cnt) {
120                 a[0] |= 1ULL<<v[0];
121                 a[v[0]] = v[1];
122         }
123 }
124
125 static int search_vec(size_t *v, size_t *r, size_t key)
126 {
127         for (; v[0]!=key; v+=2)
128                 if (!v[0]) return 0;
129         *r = v[1];
130         return 1;
131 }
132
133 static uint32_t sysv_hash(const char *s0)
134 {
135         const unsigned char *s = (void *)s0;
136         uint_fast32_t h = 0;
137         while (*s) {
138                 h = 16*h + *s++;
139                 h ^= h>>24 & 0xf0;
140         }
141         return h & 0xfffffff;
142 }
143
144 static uint32_t gnu_hash(const char *s0)
145 {
146         const unsigned char *s = (void *)s0;
147         uint_fast32_t h = 5381;
148         for (; *s; s++)
149                 h = h*33 + *s;
150         return h;
151 }
152
153 static Sym *sysv_lookup(const char *s, uint32_t h, struct dso *dso)
154 {
155         size_t i;
156         Sym *syms = dso->syms;
157         uint32_t *hashtab = dso->hashtab;
158         char *strings = dso->strings;
159         for (i=hashtab[2+h%hashtab[0]]; i; i=hashtab[2+hashtab[0]+i]) {
160                 if ((!dso->versym || dso->versym[i] >= 0)
161                     && (!strcmp(s, strings+syms[i].st_name)))
162                         return syms+i;
163         }
164         return 0;
165 }
166
167 static Sym *gnu_lookup(const char *s, uint32_t h1, struct dso *dso)
168 {
169         Sym *syms = dso->syms;
170         char *strings = dso->strings;
171         uint32_t *hashtab = dso->ghashtab;
172         uint32_t nbuckets = hashtab[0];
173         uint32_t *buckets = hashtab + 4 + hashtab[2]*(sizeof(size_t)/4);
174         uint32_t h2;
175         uint32_t *hashval;
176         uint32_t i = buckets[h1 % nbuckets];
177
178         if (!i) return 0;
179
180         hashval = buckets + nbuckets + (i - hashtab[1]);
181
182         for (h1 |= 1; ; i++) {
183                 h2 = *hashval++;
184                 if ((!dso->versym || dso->versym[i] >= 0)
185                     && (h1 == (h2|1)) && !strcmp(s, strings + syms[i].st_name))
186                         return syms+i;
187                 if (h2 & 1) break;
188         }
189
190         return 0;
191 }
192
193 #define OK_TYPES (1<<STT_NOTYPE | 1<<STT_OBJECT | 1<<STT_FUNC | 1<<STT_COMMON | 1<<STT_TLS)
194 #define OK_BINDS (1<<STB_GLOBAL | 1<<STB_WEAK | 1<<STB_GNU_UNIQUE)
195
196 static struct symdef find_sym(struct dso *dso, const char *s, int need_def)
197 {
198         uint32_t h = 0, gh = 0;
199         struct symdef def = {0};
200         if (dso->ghashtab) {
201                 gh = gnu_hash(s);
202                 if (gh == 0x1f4039c9 && !strcmp(s, "__stack_chk_fail")) ssp_used = 1;
203         } else {
204                 h = sysv_hash(s);
205                 if (h == 0x595a4cc && !strcmp(s, "__stack_chk_fail")) ssp_used = 1;
206         }
207         for (; dso; dso=dso->next) {
208                 Sym *sym;
209                 if (!dso->global) continue;
210                 if (dso->ghashtab) {
211                         if (!gh) gh = gnu_hash(s);
212                         sym = gnu_lookup(s, gh, dso);
213                 } else {
214                         if (!h) h = sysv_hash(s);
215                         sym = sysv_lookup(s, h, dso);
216                 }
217                 if (!sym) continue;
218                 if (!sym->st_shndx)
219                         if (need_def || (sym->st_info&0xf) == STT_TLS)
220                                 continue;
221                 if (!sym->st_value)
222                         if ((sym->st_info&0xf) != STT_TLS)
223                                 continue;
224                 if (!(1<<(sym->st_info&0xf) & OK_TYPES)) continue;
225                 if (!(1<<(sym->st_info>>4) & OK_BINDS)) continue;
226
227                 if (def.sym && sym->st_info>>4 == STB_WEAK) continue;
228                 def.sym = sym;
229                 def.dso = dso;
230                 if (sym->st_info>>4 == STB_GLOBAL) break;
231         }
232         return def;
233 }
234
235 static void do_relocs(struct dso *dso, size_t *rel, size_t rel_size, size_t stride)
236 {
237         unsigned char *base = dso->base;
238         Sym *syms = dso->syms;
239         char *strings = dso->strings;
240         Sym *sym;
241         const char *name;
242         void *ctx;
243         int type;
244         int sym_index;
245         struct symdef def;
246
247         for (; rel_size; rel+=stride, rel_size-=stride*sizeof(size_t)) {
248                 type = R_TYPE(rel[1]);
249                 sym_index = R_SYM(rel[1]);
250                 if (sym_index) {
251                         sym = syms + sym_index;
252                         name = strings + sym->st_name;
253                         ctx = IS_COPY(type) ? head->next : head;
254                         def = find_sym(ctx, name, IS_PLT(type));
255                         if (!def.sym && sym->st_info>>4 != STB_WEAK) {
256                                 snprintf(errbuf, sizeof errbuf,
257                                         "Error relocating %s: %s: symbol not found",
258                                         dso->name, name);
259                                 if (runtime) longjmp(*rtld_fail, 1);
260                                 dprintf(2, "%s\n", errbuf);
261                                 ldso_fail = 1;
262                                 continue;
263                         }
264                 } else {
265                         sym = 0;
266                         def.sym = 0;
267                         def.dso = 0;
268                 }
269                 do_single_reloc(dso, base, (void *)(base + rel[0]), type,
270                         stride>2 ? rel[2] : 0, sym, sym?sym->st_size:0, def,
271                         def.sym?(size_t)(def.dso->base+def.sym->st_value):0);
272         }
273 }
274
275 /* A huge hack: to make up for the wastefulness of shared libraries
276  * needing at least a page of dirty memory even if they have no global
277  * data, we reclaim the gaps at the beginning and end of writable maps
278  * and "donate" them to the heap by setting up minimal malloc
279  * structures and then freeing them. */
280
281 static void reclaim(unsigned char *base, size_t start, size_t end)
282 {
283         size_t *a, *z;
284         start = start + 6*sizeof(size_t)-1 & -4*sizeof(size_t);
285         end = (end & -4*sizeof(size_t)) - 2*sizeof(size_t);
286         if (start>end || end-start < 4*sizeof(size_t)) return;
287         a = (size_t *)(base + start);
288         z = (size_t *)(base + end);
289         a[-2] = 1;
290         a[-1] = z[0] = end-start + 2*sizeof(size_t) | 1;
291         z[1] = 1;
292         free(a);
293 }
294
295 static void reclaim_gaps(unsigned char *base, Phdr *ph, size_t phent, size_t phcnt)
296 {
297         for (; phcnt--; ph=(void *)((char *)ph+phent)) {
298                 if (ph->p_type!=PT_LOAD) continue;
299                 if ((ph->p_flags&(PF_R|PF_W))!=(PF_R|PF_W)) continue;
300                 reclaim(base, ph->p_vaddr & -PAGE_SIZE, ph->p_vaddr);
301                 reclaim(base, ph->p_vaddr+ph->p_memsz,
302                         ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE);
303         }
304 }
305
306 static void *map_library(int fd, struct dso *dso)
307 {
308         Ehdr buf[(896+sizeof(Ehdr))/sizeof(Ehdr)];
309         void *allocated_buf=0;
310         size_t phsize;
311         size_t addr_min=SIZE_MAX, addr_max=0, map_len;
312         size_t this_min, this_max;
313         off_t off_start;
314         Ehdr *eh;
315         Phdr *ph, *ph0;
316         unsigned prot;
317         unsigned char *map=MAP_FAILED, *base;
318         size_t dyn=0;
319         size_t tls_image=0;
320         size_t i;
321
322         ssize_t l = read(fd, buf, sizeof buf);
323         eh = buf;
324         if (l<0) return 0;
325         if (l<sizeof *eh || (eh->e_type != ET_DYN && eh->e_type != ET_EXEC))
326                 goto noexec;
327         phsize = eh->e_phentsize * eh->e_phnum;
328         if (phsize > sizeof buf - sizeof *eh) {
329                 allocated_buf = malloc(phsize);
330                 if (!allocated_buf) return 0;
331                 l = pread(fd, allocated_buf, phsize, eh->e_phoff);
332                 if (l < 0) goto error;
333                 if (l != phsize) goto noexec;
334                 ph = ph0 = allocated_buf;
335         } else if (eh->e_phoff + phsize > l) {
336                 l = pread(fd, buf+1, phsize, eh->e_phoff);
337                 if (l < 0) goto error;
338                 if (l != phsize) goto noexec;
339                 ph = ph0 = (void *)(buf + 1);
340         } else {
341                 ph = ph0 = (void *)((char *)buf + eh->e_phoff);
342         }
343         for (i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
344                 if (ph->p_type == PT_DYNAMIC)
345                         dyn = ph->p_vaddr;
346                 if (ph->p_type == PT_TLS) {
347                         tls_image = ph->p_vaddr;
348                         dso->tls_align = ph->p_align;
349                         dso->tls_len = ph->p_filesz;
350                         dso->tls_size = ph->p_memsz;
351                 }
352                 if (ph->p_type != PT_LOAD) continue;
353                 if (ph->p_vaddr < addr_min) {
354                         addr_min = ph->p_vaddr;
355                         off_start = ph->p_offset;
356                         prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
357                                 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
358                                 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
359                 }
360                 if (ph->p_vaddr+ph->p_memsz > addr_max) {
361                         addr_max = ph->p_vaddr+ph->p_memsz;
362                 }
363         }
364         if (!dyn) goto noexec;
365         addr_max += PAGE_SIZE-1;
366         addr_max &= -PAGE_SIZE;
367         addr_min &= -PAGE_SIZE;
368         off_start &= -PAGE_SIZE;
369         map_len = addr_max - addr_min + off_start;
370         /* The first time, we map too much, possibly even more than
371          * the length of the file. This is okay because we will not
372          * use the invalid part; we just need to reserve the right
373          * amount of virtual address space to map over later. */
374         map = mmap((void *)addr_min, map_len, prot, MAP_PRIVATE, fd, off_start);
375         if (map==MAP_FAILED) goto error;
376         /* If the loaded file is not relocatable and the requested address is
377          * not available, then the load operation must fail. */
378         if (eh->e_type != ET_DYN && addr_min && map!=(void *)addr_min) {
379                 errno = EBUSY;
380                 goto error;
381         }
382         base = map - addr_min;
383         dso->phdr = 0;
384         dso->phnum = 0;
385         for (ph=ph0, i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
386                 if (ph->p_type != PT_LOAD) continue;
387                 /* Check if the programs headers are in this load segment, and
388                  * if so, record the address for use by dl_iterate_phdr. */
389                 if (!dso->phdr && eh->e_phoff >= ph->p_offset
390                     && eh->e_phoff+phsize <= ph->p_offset+ph->p_filesz) {
391                         dso->phdr = (void *)(base + ph->p_vaddr
392                                 + (eh->e_phoff-ph->p_offset));
393                         dso->phnum = eh->e_phnum;
394                 }
395                 /* Reuse the existing mapping for the lowest-address LOAD */
396                 if ((ph->p_vaddr & -PAGE_SIZE) == addr_min) continue;
397                 this_min = ph->p_vaddr & -PAGE_SIZE;
398                 this_max = ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE;
399                 off_start = ph->p_offset & -PAGE_SIZE;
400                 prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
401                         ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
402                         ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
403                 if (mmap(base+this_min, this_max-this_min, prot, MAP_PRIVATE|MAP_FIXED, fd, off_start) == MAP_FAILED)
404                         goto error;
405                 if (ph->p_memsz > ph->p_filesz) {
406                         size_t brk = (size_t)base+ph->p_vaddr+ph->p_filesz;
407                         size_t pgbrk = brk+PAGE_SIZE-1 & -PAGE_SIZE;
408                         memset((void *)brk, 0, pgbrk-brk & PAGE_SIZE-1);
409                         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)
410                                 goto error;
411                 }
412         }
413         for (i=0; ((size_t *)(base+dyn))[i]; i+=2)
414                 if (((size_t *)(base+dyn))[i]==DT_TEXTREL) {
415                         if (mprotect(map, map_len, PROT_READ|PROT_WRITE|PROT_EXEC) < 0)
416                                 goto error;
417                         break;
418                 }
419         if (!runtime) reclaim_gaps(base, ph0, eh->e_phentsize, eh->e_phnum);
420         dso->map = map;
421         dso->map_len = map_len;
422         dso->base = base;
423         dso->dynv = (void *)(base+dyn);
424         if (dso->tls_size) dso->tls_image = (void *)(base+tls_image);
425         free(allocated_buf);
426         return map;
427 noexec:
428         errno = ENOEXEC;
429 error:
430         if (map!=MAP_FAILED) munmap(map, map_len);
431         free(allocated_buf);
432         return 0;
433 }
434
435 static int path_open(const char *name, const char *s, char *buf, size_t buf_size)
436 {
437         size_t l;
438         int fd;
439         for (;;) {
440                 s += strspn(s, ":\n");
441                 l = strcspn(s, ":\n");
442                 if (l-1 >= INT_MAX) return -1;
443                 if (snprintf(buf, buf_size, "%.*s/%s", (int)l, s, name) >= buf_size)
444                         continue;
445                 if ((fd = open(buf, O_RDONLY|O_CLOEXEC))>=0) return fd;
446                 s += l;
447         }
448 }
449
450 static void decode_dyn(struct dso *p)
451 {
452         size_t dyn[DYN_CNT] = {0};
453         decode_vec(p->dynv, dyn, DYN_CNT);
454         p->syms = (void *)(p->base + dyn[DT_SYMTAB]);
455         p->strings = (void *)(p->base + dyn[DT_STRTAB]);
456         if (dyn[0]&(1<<DT_HASH))
457                 p->hashtab = (void *)(p->base + dyn[DT_HASH]);
458         if (search_vec(p->dynv, dyn, DT_GNU_HASH))
459                 p->ghashtab = (void *)(p->base + *dyn);
460         if (search_vec(p->dynv, dyn, DT_VERSYM))
461                 p->versym = (void *)(p->base + *dyn);
462 }
463
464 static struct dso *load_library(const char *name)
465 {
466         char buf[2*NAME_MAX+2];
467         const char *pathname;
468         unsigned char *map;
469         struct dso *p, temp_dso = {0};
470         int fd;
471         struct stat st;
472         size_t alloc_size;
473         int n_th = 0;
474         int is_self = 0;
475
476         /* Catch and block attempts to reload the implementation itself */
477         if (name[0]=='l' && name[1]=='i' && name[2]=='b') {
478                 static const char *rp, reserved[] =
479                         "c\0pthread\0rt\0m\0dl\0util\0xnet\0";
480                 char *z = strchr(name, '.');
481                 if (z) {
482                         size_t l = z-name;
483                         for (rp=reserved; *rp && strncmp(name+3, rp, l-3); rp+=strlen(rp)+1);
484                         if (*rp) {
485                                 if (ldd_mode) {
486                                         /* Track which names have been resolved
487                                          * and only report each one once. */
488                                         static unsigned reported;
489                                         unsigned mask = 1U<<(rp-reserved);
490                                         if (!(reported & mask)) {
491                                                 reported |= mask;
492                                                 dprintf(1, "\t%s => %s (%p)\n",
493                                                         name, ldso->name,
494                                                         ldso->base);
495                                         }
496                                 }
497                                 is_self = 1;
498                         }
499                 }
500         }
501         if (!strcmp(name, ldso->name)) is_self = 1;
502         if (is_self) {
503                 if (!ldso->prev) {
504                         tail->next = ldso;
505                         ldso->prev = tail;
506                         tail = ldso->next ? ldso->next : ldso;
507                 }
508                 return ldso;
509         }
510         if (strchr(name, '/')) {
511                 pathname = name;
512                 fd = open(name, O_RDONLY|O_CLOEXEC);
513         } else {
514                 /* Search for the name to see if it's already loaded */
515                 for (p=head->next; p; p=p->next) {
516                         if (p->shortname && !strcmp(p->shortname, name)) {
517                                 p->refcnt++;
518                                 return p;
519                         }
520                 }
521                 if (strlen(name) > NAME_MAX) return 0;
522                 fd = -1;
523                 if (env_path) fd = path_open(name, env_path, buf, sizeof buf);
524                 if (fd < 0 && r_path) fd = path_open(name, r_path, buf, sizeof buf);
525                 if (fd < 0) {
526                         if (!sys_path) {
527                                 char *prefix = 0;
528                                 size_t prefix_len;
529                                 if (ldso->name[0]=='/') {
530                                         char *s, *t, *z;
531                                         for (s=t=z=ldso->name; *s; s++)
532                                                 if (*s=='/') z=t, t=s;
533                                         prefix_len = z-ldso->name;
534                                         if (prefix_len < PATH_MAX)
535                                                 prefix = ldso->name;
536                                 }
537                                 if (!prefix) {
538                                         prefix = "";
539                                         prefix_len = 0;
540                                 }
541                                 char etc_ldso_path[prefix_len + 1
542                                         + sizeof "/etc/ld-musl-" LDSO_ARCH ".path"];
543                                 snprintf(etc_ldso_path, sizeof etc_ldso_path,
544                                         "%.*s/etc/ld-musl-" LDSO_ARCH ".path",
545                                         (int)prefix_len, prefix);
546                                 FILE *f = fopen(etc_ldso_path, "rbe");
547                                 if (f) {
548                                         if (getdelim(&sys_path, (size_t[1]){0}, 0, f) <= 0) {
549                                                 free(sys_path);
550                                                 sys_path = "";
551                                         }
552                                         fclose(f);
553                                 }
554                         }
555                         if (!sys_path) sys_path = "/lib:/usr/local/lib:/usr/lib";
556                         fd = path_open(name, sys_path, buf, sizeof buf);
557                 }
558                 pathname = buf;
559         }
560         if (fd < 0) return 0;
561         if (fstat(fd, &st) < 0) {
562                 close(fd);
563                 return 0;
564         }
565         for (p=head->next; p; p=p->next) {
566                 if (p->dev == st.st_dev && p->ino == st.st_ino) {
567                         /* If this library was previously loaded with a
568                          * pathname but a search found the same inode,
569                          * setup its shortname so it can be found by name. */
570                         if (!p->shortname && pathname != name)
571                                 p->shortname = strrchr(p->name, '/')+1;
572                         close(fd);
573                         p->refcnt++;
574                         return p;
575                 }
576         }
577         map = noload ? 0 : map_library(fd, &temp_dso);
578         close(fd);
579         if (!map) return 0;
580
581         /* Allocate storage for the new DSO. When there is TLS, this
582          * storage must include a reservation for all pre-existing
583          * threads to obtain copies of both the new TLS, and an
584          * extended DTV capable of storing an additional slot for
585          * the newly-loaded DSO. */
586         alloc_size = sizeof *p + strlen(pathname) + 1;
587         if (runtime && temp_dso.tls_image) {
588                 size_t per_th = temp_dso.tls_size + temp_dso.tls_align
589                         + sizeof(void *) * (tls_cnt+3);
590                 n_th = libc.threads_minus_1 + 1;
591                 if (n_th > SSIZE_MAX / per_th) alloc_size = SIZE_MAX;
592                 else alloc_size += n_th * per_th;
593         }
594         p = calloc(1, alloc_size);
595         if (!p) {
596                 munmap(map, temp_dso.map_len);
597                 return 0;
598         }
599         memcpy(p, &temp_dso, sizeof temp_dso);
600         decode_dyn(p);
601         p->dev = st.st_dev;
602         p->ino = st.st_ino;
603         p->refcnt = 1;
604         p->name = p->buf;
605         strcpy(p->name, pathname);
606         /* Add a shortname only if name arg was not an explicit pathname. */
607         if (pathname != name) p->shortname = strrchr(p->name, '/')+1;
608         if (p->tls_image) {
609                 if (runtime && !__pthread_self_init()) {
610                         munmap(map, p->map_len);
611                         free(p);
612                         return 0;
613                 }
614                 p->tls_id = ++tls_cnt;
615                 tls_align = MAXP2(tls_align, p->tls_align);
616 #ifdef TLS_ABOVE_TP
617                 p->tls_offset = tls_offset + ( (tls_align-1) &
618                         -(tls_offset + (uintptr_t)p->tls_image) );
619                 tls_offset += p->tls_size;
620 #else
621                 tls_offset += p->tls_size + p->tls_align - 1;
622                 tls_offset -= (tls_offset + (uintptr_t)p->tls_image)
623                         & (p->tls_align-1);
624                 p->tls_offset = tls_offset;
625 #endif
626                 p->new_dtv = (void *)(-sizeof(size_t) &
627                         (uintptr_t)(p->name+strlen(p->name)+sizeof(size_t)));
628                 p->new_tls = (void *)(p->new_dtv + n_th*(tls_cnt+1));
629         }
630
631         tail->next = p;
632         p->prev = tail;
633         tail = p;
634
635         if (ldd_mode) dprintf(1, "\t%s => %s (%p)\n", name, pathname, p->base);
636
637         return p;
638 }
639
640 static void load_deps(struct dso *p)
641 {
642         size_t i, ndeps=0;
643         struct dso ***deps = &p->deps, **tmp, *dep;
644         for (; p; p=p->next) {
645                 for (i=0; p->dynv[i]; i+=2) {
646                         if (p->dynv[i] != DT_RPATH) continue;
647                         r_path = (void *)(p->strings + p->dynv[i+1]);
648                 }
649                 for (i=0; p->dynv[i]; i+=2) {
650                         if (p->dynv[i] != DT_NEEDED) continue;
651                         dep = load_library(p->strings + p->dynv[i+1]);
652                         if (!dep) {
653                                 snprintf(errbuf, sizeof errbuf,
654                                         "Error loading shared library %s: %m (needed by %s)",
655                                         p->strings + p->dynv[i+1], p->name);
656                                 if (runtime) longjmp(*rtld_fail, 1);
657                                 dprintf(2, "%s\n", errbuf);
658                                 ldso_fail = 1;
659                                 continue;
660                         }
661                         if (runtime) {
662                                 tmp = realloc(*deps, sizeof(*tmp)*(ndeps+2));
663                                 if (!tmp) longjmp(*rtld_fail, 1);
664                                 tmp[ndeps++] = dep;
665                                 tmp[ndeps] = 0;
666                                 *deps = tmp;
667                         }
668                 }
669                 r_path = 0;
670         }
671 }
672
673 static void load_preload(char *s)
674 {
675         int tmp;
676         char *z;
677         for (z=s; *z; s=z) {
678                 for (   ; *s && isspace(*s); s++);
679                 for (z=s; *z && !isspace(*z); z++);
680                 tmp = *z;
681                 *z = 0;
682                 load_library(s);
683                 *z = tmp;
684         }
685 }
686
687 static void make_global(struct dso *p)
688 {
689         for (; p; p=p->next) p->global = 1;
690 }
691
692 static void reloc_all(struct dso *p)
693 {
694         size_t dyn[DYN_CNT] = {0};
695         for (; p; p=p->next) {
696                 if (p->relocated) continue;
697                 decode_vec(p->dynv, dyn, DYN_CNT);
698 #ifdef NEED_ARCH_RELOCS
699                 do_arch_relocs(p, head);
700 #endif
701                 do_relocs(p, (void *)(p->base+dyn[DT_JMPREL]), dyn[DT_PLTRELSZ],
702                         2+(dyn[DT_PLTREL]==DT_RELA));
703                 do_relocs(p, (void *)(p->base+dyn[DT_REL]), dyn[DT_RELSZ], 2);
704                 do_relocs(p, (void *)(p->base+dyn[DT_RELA]), dyn[DT_RELASZ], 3);
705                 p->relocated = 1;
706         }
707 }
708
709 static size_t find_dyn(Phdr *ph, size_t cnt, size_t stride)
710 {
711         for (; cnt--; ph = (void *)((char *)ph + stride))
712                 if (ph->p_type == PT_DYNAMIC)
713                         return ph->p_vaddr;
714         return 0;
715 }
716
717 static void find_map_range(Phdr *ph, size_t cnt, size_t stride, struct dso *p)
718 {
719         size_t min_addr = -1, max_addr = 0;
720         for (; cnt--; ph = (void *)((char *)ph + stride)) {
721                 if (ph->p_type != PT_LOAD) continue;
722                 if (ph->p_vaddr < min_addr)
723                         min_addr = ph->p_vaddr;
724                 if (ph->p_vaddr+ph->p_memsz > max_addr)
725                         max_addr = ph->p_vaddr+ph->p_memsz;
726         }
727         min_addr &= -PAGE_SIZE;
728         max_addr = (max_addr + PAGE_SIZE-1) & -PAGE_SIZE;
729         p->map = p->base + min_addr;
730         p->map_len = max_addr - min_addr;
731 }
732
733 static void do_fini()
734 {
735         struct dso *p;
736         size_t dyn[DYN_CNT] = {0};
737         for (p=fini_head; p; p=p->fini_next) {
738                 if (!p->constructed) continue;
739                 decode_vec(p->dynv, dyn, DYN_CNT);
740                 if (dyn[0] & (1<<DT_FINI_ARRAY)) {
741                         size_t n = dyn[DT_FINI_ARRAYSZ]/sizeof(size_t);
742                         size_t *fn = (size_t *)(p->base + dyn[DT_FINI_ARRAY])+n;
743                         while (n--) ((void (*)(void))*--fn)();
744                 }
745 #ifndef NO_LEGACY_INITFINI
746                 if ((dyn[0] & (1<<DT_FINI)) && dyn[DT_FINI])
747                         ((void (*)(void))(p->base + dyn[DT_FINI]))();
748 #endif
749         }
750 }
751
752 static void do_init_fini(struct dso *p)
753 {
754         size_t dyn[DYN_CNT] = {0};
755         int need_locking = libc.threads_minus_1;
756         /* Allow recursive calls that arise when a library calls
757          * dlopen from one of its constructors, but block any
758          * other threads until all ctors have finished. */
759         if (need_locking) pthread_mutex_lock(&init_fini_lock);
760         for (; p; p=p->prev) {
761                 if (p->constructed) continue;
762                 p->constructed = 1;
763                 decode_vec(p->dynv, dyn, DYN_CNT);
764                 if (dyn[0] & ((1<<DT_FINI) | (1<<DT_FINI_ARRAY))) {
765                         p->fini_next = fini_head;
766                         fini_head = p;
767                 }
768 #ifndef NO_LEGACY_INITFINI
769                 if ((dyn[0] & (1<<DT_INIT)) && dyn[DT_INIT])
770                         ((void (*)(void))(p->base + dyn[DT_INIT]))();
771 #endif
772                 if (dyn[0] & (1<<DT_INIT_ARRAY)) {
773                         size_t n = dyn[DT_INIT_ARRAYSZ]/sizeof(size_t);
774                         size_t *fn = (void *)(p->base + dyn[DT_INIT_ARRAY]);
775                         while (n--) ((void (*)(void))*fn++)();
776                 }
777                 if (!need_locking && libc.threads_minus_1) {
778                         need_locking = 1;
779                         pthread_mutex_lock(&init_fini_lock);
780                 }
781         }
782         if (need_locking) pthread_mutex_unlock(&init_fini_lock);
783 }
784
785 void _dl_debug_state(void)
786 {
787 }
788
789 void __reset_tls()
790 {
791         pthread_t self = __pthread_self();
792         struct dso *p;
793         for (p=head; p; p=p->next) {
794                 if (!p->tls_id || !self->dtv[p->tls_id]) continue;
795                 memcpy(self->dtv[p->tls_id], p->tls_image, p->tls_len);
796                 memset((char *)self->dtv[p->tls_id]+p->tls_len, 0,
797                         p->tls_size - p->tls_len);
798                 if (p->tls_id == (size_t)self->dtv[0]) break;
799         }
800 }
801
802 void *__copy_tls(unsigned char *mem)
803 {
804         pthread_t td;
805         struct dso *p;
806
807         if (!tls_cnt) return mem;
808
809         void **dtv = (void *)mem;
810         dtv[0] = (void *)tls_cnt;
811
812 #ifdef TLS_ABOVE_TP
813         mem += sizeof(void *) * (tls_cnt+1);
814         mem += -((uintptr_t)mem + sizeof(struct pthread)) & (tls_align-1);
815         td = (pthread_t)mem;
816         mem += sizeof(struct pthread);
817
818         for (p=head; p; p=p->next) {
819                 if (!p->tls_id) continue;
820                 dtv[p->tls_id] = mem + p->tls_offset;
821                 memcpy(dtv[p->tls_id], p->tls_image, p->tls_len);
822         }
823 #else
824         mem += libc.tls_size - sizeof(struct pthread);
825         mem -= (uintptr_t)mem & (tls_align-1);
826         td = (pthread_t)mem;
827
828         for (p=head; p; p=p->next) {
829                 if (!p->tls_id) continue;
830                 dtv[p->tls_id] = mem - p->tls_offset;
831                 memcpy(dtv[p->tls_id], p->tls_image, p->tls_len);
832         }
833 #endif
834         td->dtv = dtv;
835         return td;
836 }
837
838 void *__tls_get_addr(size_t *v)
839 {
840         pthread_t self = __pthread_self();
841         if (v[0]<=(size_t)self->dtv[0] && self->dtv[v[0]])
842                 return (char *)self->dtv[v[0]]+v[1];
843
844         /* Block signals to make accessing new TLS async-signal-safe */
845         sigset_t set;
846         pthread_sigmask(SIG_BLOCK, SIGALL_SET, &set);
847         if (v[0]<=(size_t)self->dtv[0] && self->dtv[v[0]]) {
848                 pthread_sigmask(SIG_SETMASK, &set, 0);
849                 return (char *)self->dtv[v[0]]+v[1];
850         }
851
852         /* This is safe without any locks held because, if the caller
853          * is able to request the Nth entry of the DTV, the DSO list
854          * must be valid at least that far out and it was synchronized
855          * at program startup or by an already-completed call to dlopen. */
856         struct dso *p;
857         for (p=head; p->tls_id != v[0]; p=p->next);
858
859         /* Get new DTV space from new DSO if needed */
860         if (v[0] > (size_t)self->dtv[0]) {
861                 void **newdtv = p->new_dtv +
862                         (v[0]+1)*sizeof(void *)*a_fetch_add(&p->new_dtv_idx,1);
863                 memcpy(newdtv, self->dtv,
864                         ((size_t)self->dtv[0]+1) * sizeof(void *));
865                 newdtv[0] = (void *)v[0];
866                 self->dtv = newdtv;
867         }
868
869         /* Get new TLS memory from new DSO */
870         unsigned char *mem = p->new_tls +
871                 (p->tls_size + p->tls_align) * a_fetch_add(&p->new_tls_idx,1);
872         mem += ((uintptr_t)p->tls_image - (uintptr_t)mem) & (p->tls_align-1);
873         self->dtv[v[0]] = mem;
874         memcpy(mem, p->tls_image, p->tls_len);
875         pthread_sigmask(SIG_SETMASK, &set, 0);
876         return mem + v[1];
877 }
878
879 static void update_tls_size()
880 {
881         libc.tls_size = ALIGN(
882                 (1+tls_cnt) * sizeof(void *) +
883                 tls_offset +
884                 sizeof(struct pthread) +
885                 tls_align * 2,
886         tls_align);
887 }
888
889 void *__dynlink(int argc, char **argv)
890 {
891         size_t aux[AUX_CNT] = {0};
892         size_t i;
893         Phdr *phdr;
894         Ehdr *ehdr;
895         static struct dso builtin_dsos[3];
896         struct dso *const app = builtin_dsos+0;
897         struct dso *const lib = builtin_dsos+1;
898         struct dso *const vdso = builtin_dsos+2;
899         char *env_preload=0;
900         size_t vdso_base;
901         size_t *auxv;
902         char **envp = argv+argc+1;
903
904         /* Find aux vector just past environ[] */
905         for (i=argc+1; argv[i]; i++)
906                 if (!memcmp(argv[i], "LD_LIBRARY_PATH=", 16))
907                         env_path = argv[i]+16;
908                 else if (!memcmp(argv[i], "LD_PRELOAD=", 11))
909                         env_preload = argv[i]+11;
910         auxv = (void *)(argv+i+1);
911
912         decode_vec(auxv, aux, AUX_CNT);
913
914         /* Only trust user/env if kernel says we're not suid/sgid */
915         if ((aux[0]&0x7800)!=0x7800 || aux[AT_UID]!=aux[AT_EUID]
916           || aux[AT_GID]!=aux[AT_EGID] || aux[AT_SECURE]) {
917                 env_path = 0;
918                 env_preload = 0;
919         }
920
921         /* If the dynamic linker was invoked as a program itself, AT_BASE
922          * will not be set. In that case, we assume the base address is
923          * the start of the page containing the PHDRs; I don't know any
924          * better approach... */
925         if (!aux[AT_BASE]) {
926                 aux[AT_BASE] = aux[AT_PHDR] & -PAGE_SIZE;
927                 aux[AT_PHDR] = aux[AT_PHENT] = aux[AT_PHNUM] = 0;
928         }
929
930         /* The dynamic linker load address is passed by the kernel
931          * in the AUX vector, so this is easy. */
932         lib->base = (void *)aux[AT_BASE];
933         lib->name = lib->shortname = "libc.so";
934         lib->global = 1;
935         ehdr = (void *)lib->base;
936         lib->phnum = ehdr->e_phnum;
937         lib->phdr = (void *)(aux[AT_BASE]+ehdr->e_phoff);
938         find_map_range(lib->phdr, ehdr->e_phnum, ehdr->e_phentsize, lib);
939         lib->dynv = (void *)(lib->base + find_dyn(lib->phdr,
940                 ehdr->e_phnum, ehdr->e_phentsize));
941         decode_dyn(lib);
942
943         if (aux[AT_PHDR]) {
944                 size_t interp_off = 0;
945                 size_t tls_image = 0;
946                 /* Find load address of the main program, via AT_PHDR vs PT_PHDR. */
947                 app->phdr = phdr = (void *)aux[AT_PHDR];
948                 app->phnum = aux[AT_PHNUM];
949                 for (i=aux[AT_PHNUM]; i; i--, phdr=(void *)((char *)phdr + aux[AT_PHENT])) {
950                         if (phdr->p_type == PT_PHDR)
951                                 app->base = (void *)(aux[AT_PHDR] - phdr->p_vaddr);
952                         else if (phdr->p_type == PT_INTERP)
953                                 interp_off = (size_t)phdr->p_vaddr;
954                         else if (phdr->p_type == PT_TLS) {
955                                 tls_image = phdr->p_vaddr;
956                                 app->tls_len = phdr->p_filesz;
957                                 app->tls_size = phdr->p_memsz;
958                                 app->tls_align = phdr->p_align;
959                         }
960                 }
961                 if (app->tls_size) app->tls_image = (char *)app->base + tls_image;
962                 if (interp_off) lib->name = (char *)app->base + interp_off;
963                 app->name = argv[0];
964                 app->dynv = (void *)(app->base + find_dyn(
965                         (void *)aux[AT_PHDR], aux[AT_PHNUM], aux[AT_PHENT]));
966                 find_map_range((void *)aux[AT_PHDR],
967                         aux[AT_PHNUM], aux[AT_PHENT], app);
968         } else {
969                 int fd;
970                 char *ldname = argv[0];
971                 size_t l = strlen(ldname);
972                 if (l >= 3 && !strcmp(ldname+l-3, "ldd")) ldd_mode = 1;
973                 *argv++ = (void *)-1;
974                 if (argv[0] && !strcmp(argv[0], "--")) *argv++ = (void *)-1;
975                 if (!argv[0]) {
976                         dprintf(2, "musl libc/dynamic program loader\n");
977                         dprintf(2, "usage: %s pathname%s\n", ldname,
978                                 ldd_mode ? "" : " [args]");
979                         _exit(1);
980                 }
981                 fd = open(argv[0], O_RDONLY);
982                 if (fd < 0) {
983                         dprintf(2, "%s: cannot load %s: %s\n", ldname, argv[0], strerror(errno));
984                         _exit(1);
985                 }
986                 runtime = 1;
987                 ehdr = (void *)map_library(fd, app);
988                 if (!ehdr) {
989                         dprintf(2, "%s: %s: Not a valid dynamic program\n", ldname, argv[0]);
990                         _exit(1);
991                 }
992                 runtime = 0;
993                 close(fd);
994                 lib->name = ldname;
995                 app->name = argv[0];
996                 aux[AT_ENTRY] = (size_t)app->base + ehdr->e_entry;
997                 /* Find the name that would have been used for the dynamic
998                  * linker had ldd not taken its place. */
999                 if (ldd_mode) {
1000                         for (i=0; i<app->phnum; i++) {
1001                                 if (app->phdr[i].p_type == PT_INTERP)
1002                                         lib->name = (void *)(app->base
1003                                                 + app->phdr[i].p_vaddr);
1004                         }
1005                         dprintf(1, "\t%s (%p)\n", lib->name, lib->base);
1006                 }
1007         }
1008         if (app->tls_size) {
1009                 app->tls_id = tls_cnt = 1;
1010 #ifdef TLS_ABOVE_TP
1011                 app->tls_offset = 0;
1012                 tls_offset = app->tls_size
1013                         + ( -((uintptr_t)app->tls_image + app->tls_size)
1014                         & (app->tls_align-1) );
1015 #else
1016                 tls_offset = app->tls_offset = app->tls_size
1017                         + ( -((uintptr_t)app->tls_image + app->tls_size)
1018                         & (app->tls_align-1) );
1019 #endif
1020                 tls_align = MAXP2(tls_align, app->tls_align);
1021         }
1022         app->global = 1;
1023         decode_dyn(app);
1024
1025         /* Attach to vdso, if provided by the kernel */
1026         if (search_vec(auxv, &vdso_base, AT_SYSINFO_EHDR)) {
1027                 ehdr = (void *)vdso_base;
1028                 vdso->phdr = phdr = (void *)(vdso_base + ehdr->e_phoff);
1029                 vdso->phnum = ehdr->e_phnum;
1030                 for (i=ehdr->e_phnum; i; i--, phdr=(void *)((char *)phdr + ehdr->e_phentsize)) {
1031                         if (phdr->p_type == PT_DYNAMIC)
1032                                 vdso->dynv = (void *)(vdso_base + phdr->p_offset);
1033                         if (phdr->p_type == PT_LOAD)
1034                                 vdso->base = (void *)(vdso_base - phdr->p_vaddr + phdr->p_offset);
1035                 }
1036                 vdso->name = "";
1037                 vdso->shortname = "linux-gate.so.1";
1038                 vdso->global = 1;
1039                 decode_dyn(vdso);
1040                 vdso->prev = lib;
1041                 lib->next = vdso;
1042         }
1043
1044         /* Initial dso chain consists only of the app. We temporarily
1045          * append the dynamic linker/libc so we can relocate it, then
1046          * restore the initial chain in preparation for loading third
1047          * party libraries (preload/needed). */
1048         head = tail = app;
1049         ldso = lib;
1050         app->next = lib;
1051         reloc_all(lib);
1052         app->next = 0;
1053
1054         /* PAST THIS POINT, ALL LIBC INTERFACES ARE FULLY USABLE. */
1055
1056         /* Donate unused parts of app and library mapping to malloc */
1057         reclaim_gaps(app->base, (void *)aux[AT_PHDR], aux[AT_PHENT], aux[AT_PHNUM]);
1058         ehdr = (void *)lib->base;
1059         reclaim_gaps(lib->base, (void *)(lib->base+ehdr->e_phoff),
1060                 ehdr->e_phentsize, ehdr->e_phnum);
1061
1062         /* Load preload/needed libraries, add their symbols to the global
1063          * namespace, and perform all remaining relocations. The main
1064          * program must be relocated LAST since it may contain copy
1065          * relocations which depend on libraries' relocations. */
1066         if (env_preload) load_preload(env_preload);
1067         load_deps(app);
1068         make_global(app);
1069
1070         reloc_all(app->next);
1071         reloc_all(app);
1072
1073         update_tls_size();
1074         if (tls_cnt) {
1075                 void *mem = mmap(0, libc.tls_size, PROT_READ|PROT_WRITE,
1076                         MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
1077                 if (mem==MAP_FAILED ||
1078                     !__install_initial_tls(__copy_tls(mem))) {
1079                         dprintf(2, "%s: Error getting %zu bytes thread-local storage: %m\n",
1080                                 argv[0], libc.tls_size);
1081                         _exit(127);
1082                 }
1083         }
1084
1085         if (ldso_fail) _exit(127);
1086         if (ldd_mode) _exit(0);
1087
1088         /* Switch to runtime mode: any further failures in the dynamic
1089          * linker are a reportable failure rather than a fatal startup
1090          * error. If the dynamic loader (dlopen) will not be used, free
1091          * all memory used by the dynamic linker. */
1092         runtime = 1;
1093
1094 #ifndef DYNAMIC_IS_RO
1095         for (i=0; app->dynv[i]; i+=2)
1096                 if (app->dynv[i]==DT_DEBUG)
1097                         app->dynv[i+1] = (size_t)&debug;
1098 #endif
1099         debug.ver = 1;
1100         debug.bp = _dl_debug_state;
1101         debug.head = head;
1102         debug.base = lib->base;
1103         debug.state = 0;
1104         _dl_debug_state();
1105
1106         if (ssp_used) __init_ssp((void *)aux[AT_RANDOM]);
1107         __init_libc(envp, argv[0]);
1108         atexit(do_fini);
1109         errno = 0;
1110         do_init_fini(tail);
1111
1112         return (void *)aux[AT_ENTRY];
1113 }
1114
1115 void *dlopen(const char *file, int mode)
1116 {
1117         struct dso *volatile p, *orig_tail, *next;
1118         size_t orig_tls_cnt, orig_tls_offset, orig_tls_align;
1119         size_t i;
1120         int cs;
1121         jmp_buf jb;
1122
1123         if (!file) return head;
1124
1125         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
1126         pthread_rwlock_wrlock(&lock);
1127         __inhibit_ptc();
1128
1129         p = 0;
1130         orig_tls_cnt = tls_cnt;
1131         orig_tls_offset = tls_offset;
1132         orig_tls_align = tls_align;
1133         orig_tail = tail;
1134         noload = mode & RTLD_NOLOAD;
1135
1136         rtld_fail = &jb;
1137         if (setjmp(*rtld_fail)) {
1138                 /* Clean up anything new that was (partially) loaded */
1139                 if (p && p->deps) for (i=0; p->deps[i]; i++)
1140                         if (p->deps[i]->global < 0)
1141                                 p->deps[i]->global = 0;
1142                 for (p=orig_tail->next; p; p=next) {
1143                         next = p->next;
1144                         munmap(p->map, p->map_len);
1145                         free(p->deps);
1146                         free(p);
1147                 }
1148                 tls_cnt = orig_tls_cnt;
1149                 tls_offset = orig_tls_offset;
1150                 tls_align = orig_tls_align;
1151                 tail = orig_tail;
1152                 tail->next = 0;
1153                 p = 0;
1154                 errflag = 1;
1155                 goto end;
1156         } else p = load_library(file);
1157
1158         if (!p) {
1159                 snprintf(errbuf, sizeof errbuf, noload ?
1160                         "Library %s is not already loaded" :
1161                         "Error loading shared library %s: %m",
1162                         file);
1163                 errflag = 1;
1164                 goto end;
1165         }
1166
1167         /* First load handling */
1168         if (!p->deps) {
1169                 load_deps(p);
1170                 if (p->deps) for (i=0; p->deps[i]; i++)
1171                         if (!p->deps[i]->global)
1172                                 p->deps[i]->global = -1;
1173                 if (!p->global) p->global = -1;
1174                 reloc_all(p);
1175                 if (p->deps) for (i=0; p->deps[i]; i++)
1176                         if (p->deps[i]->global < 0)
1177                                 p->deps[i]->global = 0;
1178                 if (p->global < 0) p->global = 0;
1179         }
1180
1181         if (mode & RTLD_GLOBAL) {
1182                 if (p->deps) for (i=0; p->deps[i]; i++)
1183                         p->deps[i]->global = 1;
1184                 p->global = 1;
1185         }
1186
1187         update_tls_size();
1188
1189         if (ssp_used) __init_ssp(libc.auxv);
1190
1191         _dl_debug_state();
1192         orig_tail = tail;
1193 end:
1194         __release_ptc();
1195         if (p) gencnt++;
1196         pthread_rwlock_unlock(&lock);
1197         if (p) do_init_fini(orig_tail);
1198         pthread_setcancelstate(cs, 0);
1199         return p;
1200 }
1201
1202 static int invalid_dso_handle(void *h)
1203 {
1204         struct dso *p;
1205         for (p=head; p; p=p->next) if (h==p) return 0;
1206         snprintf(errbuf, sizeof errbuf, "Invalid library handle %p", (void *)h);
1207         errflag = 1;
1208         return 1;
1209 }
1210
1211 static void *do_dlsym(struct dso *p, const char *s, void *ra)
1212 {
1213         size_t i;
1214         uint32_t h = 0, gh = 0;
1215         Sym *sym;
1216         if (p == head || p == RTLD_DEFAULT || p == RTLD_NEXT) {
1217                 if (p == RTLD_DEFAULT) {
1218                         p = head;
1219                 } else if (p == RTLD_NEXT) {
1220                         for (p=head; p && (unsigned char *)ra-p->map>p->map_len; p=p->next);
1221                         if (!p) p=head;
1222                         p = p->next;
1223                 }
1224                 struct symdef def = find_sym(p, s, 0);
1225                 if (!def.sym) goto failed;
1226                 if ((def.sym->st_info&0xf) == STT_TLS)
1227                         return __tls_get_addr((size_t []){def.dso->tls_id, def.sym->st_value});
1228                 return def.dso->base + def.sym->st_value;
1229         }
1230         if (p != RTLD_DEFAULT && p != RTLD_NEXT && invalid_dso_handle(p))
1231                 return 0;
1232         if (p->ghashtab) {
1233                 gh = gnu_hash(s);
1234                 sym = gnu_lookup(s, gh, p);
1235         } else {
1236                 h = sysv_hash(s);
1237                 sym = sysv_lookup(s, h, p);
1238         }
1239         if (sym && (sym->st_info&0xf) == STT_TLS)
1240                 return __tls_get_addr((size_t []){p->tls_id, sym->st_value});
1241         if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
1242                 return p->base + sym->st_value;
1243         if (p->deps) for (i=0; p->deps[i]; i++) {
1244                 if (p->deps[i]->ghashtab) {
1245                         if (!gh) gh = gnu_hash(s);
1246                         sym = gnu_lookup(s, gh, p->deps[i]);
1247                 } else {
1248                         if (!h) h = sysv_hash(s);
1249                         sym = sysv_lookup(s, h, p->deps[i]);
1250                 }
1251                 if (sym && (sym->st_info&0xf) == STT_TLS)
1252                         return __tls_get_addr((size_t []){p->deps[i]->tls_id, sym->st_value});
1253                 if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
1254                         return p->deps[i]->base + sym->st_value;
1255         }
1256 failed:
1257         errflag = 1;
1258         snprintf(errbuf, sizeof errbuf, "Symbol not found: %s", s);
1259         return 0;
1260 }
1261
1262 int __dladdr(void *addr, Dl_info *info)
1263 {
1264         struct dso *p;
1265         Sym *sym;
1266         uint32_t nsym;
1267         char *strings;
1268         size_t i;
1269         void *best = 0;
1270         char *bestname;
1271
1272         pthread_rwlock_rdlock(&lock);
1273         for (p=head; p && (unsigned char *)addr-p->map>p->map_len; p=p->next);
1274         pthread_rwlock_unlock(&lock);
1275
1276         if (!p) return 0;
1277
1278         sym = p->syms;
1279         strings = p->strings;
1280         if (p->hashtab) {
1281                 nsym = p->hashtab[1];
1282         } else {
1283                 uint32_t *buckets;
1284                 uint32_t *hashval;
1285                 buckets = p->ghashtab + 4 + (p->ghashtab[2]*sizeof(size_t)/4);
1286                 sym += p->ghashtab[1];
1287                 for (i = 0; i < p->ghashtab[0]; i++) {
1288                         if (buckets[i] > nsym)
1289                                 nsym = buckets[i];
1290                 }
1291                 if (nsym) {
1292                         nsym -= p->ghashtab[1];
1293                         hashval = buckets + p->ghashtab[0] + nsym;
1294                         do nsym++;
1295                         while (!(*hashval++ & 1));
1296                 }
1297         }
1298
1299         for (; nsym; nsym--, sym++) {
1300                 if (sym->st_value
1301                  && (1<<(sym->st_info&0xf) & OK_TYPES)
1302                  && (1<<(sym->st_info>>4) & OK_BINDS)) {
1303                         void *symaddr = p->base + sym->st_value;
1304                         if (symaddr > addr || symaddr < best)
1305                                 continue;
1306                         best = symaddr;
1307                         bestname = strings + sym->st_name;
1308                         if (addr == symaddr)
1309                                 break;
1310                 }
1311         }
1312
1313         if (!best) return 0;
1314
1315         info->dli_fname = p->name;
1316         info->dli_fbase = p->base;
1317         info->dli_sname = bestname;
1318         info->dli_saddr = best;
1319
1320         return 1;
1321 }
1322
1323 void *__dlsym(void *restrict p, const char *restrict s, void *restrict ra)
1324 {
1325         void *res;
1326         pthread_rwlock_rdlock(&lock);
1327         res = do_dlsym(p, s, ra);
1328         pthread_rwlock_unlock(&lock);
1329         return res;
1330 }
1331
1332 int dl_iterate_phdr(int(*callback)(struct dl_phdr_info *info, size_t size, void *data), void *data)
1333 {
1334         struct dso *current;
1335         struct dl_phdr_info info;
1336         int ret = 0;
1337         for(current = head; current;) {
1338                 info.dlpi_addr      = (uintptr_t)current->base;
1339                 info.dlpi_name      = current->name;
1340                 info.dlpi_phdr      = current->phdr;
1341                 info.dlpi_phnum     = current->phnum;
1342                 info.dlpi_adds      = gencnt;
1343                 info.dlpi_subs      = 0;
1344                 info.dlpi_tls_modid = current->tls_id;
1345                 info.dlpi_tls_data  = current->tls_image;
1346
1347                 ret = (callback)(&info, sizeof (info), data);
1348
1349                 if (ret != 0) break;
1350
1351                 pthread_rwlock_rdlock(&lock);
1352                 current = current->next;
1353                 pthread_rwlock_unlock(&lock);
1354         }
1355         return ret;
1356 }
1357 #else
1358 static int invalid_dso_handle(void *h)
1359 {
1360         snprintf(errbuf, sizeof errbuf, "Invalid library handle %p", (void *)h);
1361         errflag = 1;
1362         return 1;
1363 }
1364 void *dlopen(const char *file, int mode)
1365 {
1366         return 0;
1367 }
1368 void *__dlsym(void *restrict p, const char *restrict s, void *restrict ra)
1369 {
1370         return 0;
1371 }
1372 int __dladdr (void *addr, Dl_info *info)
1373 {
1374         return 0;
1375 }
1376 #endif
1377
1378 int __dlinfo(void *dso, int req, void *res)
1379 {
1380         if (invalid_dso_handle(dso)) return -1;
1381         if (req != RTLD_DI_LINKMAP) {
1382                 snprintf(errbuf, sizeof errbuf, "Unsupported request %d", req);
1383                 errflag = 1;
1384                 return -1;
1385         }
1386         *(struct link_map **)res = dso;
1387         return 0;
1388 }
1389
1390 char *dlerror()
1391 {
1392         if (!errflag) return 0;
1393         errflag = 0;
1394         return errbuf;
1395 }
1396
1397 int dlclose(void *p)
1398 {
1399         return invalid_dso_handle(p);
1400 }