adapt static dl_iterate_phdr not to depend on !defined(SHARED)
[oweals/musl.git] / src / ldso / dynlink.c
1 #ifdef SHARED
2 #define _GNU_SOURCE
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <stdarg.h>
6 #include <stddef.h>
7 #include <string.h>
8 #include <unistd.h>
9 #include <stdint.h>
10 #include <elf.h>
11 #include <sys/mman.h>
12 #include <limits.h>
13 #include <fcntl.h>
14 #include <sys/stat.h>
15 #include <errno.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 #include "dynlink.h"
24
25 static void error(const char *, ...);
26
27 #define MAXP2(a,b) (-(-(a)&-(b)))
28 #define ALIGN(x,y) ((x)+(y)-1 & -(y))
29
30 struct debug {
31         int ver;
32         void *head;
33         void (*bp)(void);
34         int state;
35         void *base;
36 };
37
38 struct td_index {
39         size_t args[2];
40         struct td_index *next;
41 };
42
43 struct dso {
44 #if DL_FDPIC
45         struct fdpic_loadmap *loadmap;
46 #else
47         unsigned char *base;
48 #endif
49         char *name;
50         size_t *dynv;
51         struct dso *next, *prev;
52
53         Phdr *phdr;
54         int phnum;
55         size_t phentsize;
56         int refcnt;
57         Sym *syms;
58         uint32_t *hashtab;
59         uint32_t *ghashtab;
60         int16_t *versym;
61         char *strings;
62         unsigned char *map;
63         size_t map_len;
64         dev_t dev;
65         ino_t ino;
66         signed char global;
67         char relocated;
68         char constructed;
69         char kernel_mapped;
70         struct dso **deps, *needed_by;
71         char *rpath_orig, *rpath;
72         struct tls_module tls;
73         size_t tls_id;
74         size_t relro_start, relro_end;
75         void **new_dtv;
76         unsigned char *new_tls;
77         volatile int new_dtv_idx, new_tls_idx;
78         struct td_index *td_index;
79         struct dso *fini_next;
80         char *shortname;
81 #if DL_FDPIC
82         unsigned char *base;
83 #else
84         struct fdpic_loadmap *loadmap;
85 #endif
86         struct funcdesc {
87                 void *addr;
88                 size_t *got;
89         } *funcdescs;
90         size_t *got;
91         char buf[];
92 };
93
94 struct symdef {
95         Sym *sym;
96         struct dso *dso;
97 };
98
99 int __init_tp(void *);
100 void __init_libc(char **, char *);
101 void *__copy_tls(unsigned char *);
102
103 __attribute__((__visibility__("hidden")))
104 const char *__libc_get_version(void);
105
106 static struct builtin_tls {
107         char c;
108         struct pthread pt;
109         void *space[16];
110 } builtin_tls[1];
111 #define MIN_TLS_ALIGN offsetof(struct builtin_tls, pt)
112
113 #define ADDEND_LIMIT 4096
114 static size_t *saved_addends, *apply_addends_to;
115
116 static struct dso ldso;
117 static struct dso *head, *tail, *fini_head;
118 static char *env_path, *sys_path;
119 static unsigned long long gencnt;
120 static int runtime;
121 static int ldd_mode;
122 static int ldso_fail;
123 static int noload;
124 static jmp_buf *rtld_fail;
125 static pthread_rwlock_t lock;
126 static struct debug debug;
127 static struct tls_module *tls_tail;
128 static size_t tls_cnt, tls_offset, tls_align = MIN_TLS_ALIGN;
129 static size_t static_tls_cnt;
130 static pthread_mutex_t init_fini_lock = { ._m_type = PTHREAD_MUTEX_RECURSIVE };
131 static struct fdpic_loadmap *app_loadmap;
132 static struct fdpic_dummy_loadmap app_dummy_loadmap;
133
134 struct debug *_dl_debug_addr = &debug;
135
136 __attribute__((__visibility__("hidden")))
137 void (*const __init_array_start)(void)=0, (*const __fini_array_start)(void)=0;
138
139 __attribute__((__visibility__("hidden")))
140 extern void (*const __init_array_end)(void), (*const __fini_array_end)(void);
141
142 weak_alias(__init_array_start, __init_array_end);
143 weak_alias(__fini_array_start, __fini_array_end);
144
145 static int dl_strcmp(const char *l, const char *r)
146 {
147         for (; *l==*r && *l; l++, r++);
148         return *(unsigned char *)l - *(unsigned char *)r;
149 }
150 #define strcmp(l,r) dl_strcmp(l,r)
151
152 /* Compute load address for a virtual address in a given dso. */
153 #if DL_FDPIC
154 static void *laddr(const struct dso *p, size_t v)
155 {
156         size_t j=0;
157         if (!p->loadmap) return p->base + v;
158         for (j=0; v-p->loadmap->segs[j].p_vaddr >= p->loadmap->segs[j].p_memsz; j++);
159         return (void *)(v - p->loadmap->segs[j].p_vaddr + p->loadmap->segs[j].addr);
160 }
161 #define fpaddr(p, v) ((void (*)())&(struct funcdesc){ \
162         laddr(p, v), (p)->got })
163 #else
164 #define laddr(p, v) (void *)((p)->base + (v))
165 #define fpaddr(p, v) ((void (*)())laddr(p, v))
166 #endif
167
168 static void decode_vec(size_t *v, size_t *a, size_t cnt)
169 {
170         size_t i;
171         for (i=0; i<cnt; i++) a[i] = 0;
172         for (; v[0]; v+=2) if (v[0]-1<cnt-1) {
173                 a[0] |= 1UL<<v[0];
174                 a[v[0]] = v[1];
175         }
176 }
177
178 static int search_vec(size_t *v, size_t *r, size_t key)
179 {
180         for (; v[0]!=key; v+=2)
181                 if (!v[0]) return 0;
182         *r = v[1];
183         return 1;
184 }
185
186 static uint32_t sysv_hash(const char *s0)
187 {
188         const unsigned char *s = (void *)s0;
189         uint_fast32_t h = 0;
190         while (*s) {
191                 h = 16*h + *s++;
192                 h ^= h>>24 & 0xf0;
193         }
194         return h & 0xfffffff;
195 }
196
197 static uint32_t gnu_hash(const char *s0)
198 {
199         const unsigned char *s = (void *)s0;
200         uint_fast32_t h = 5381;
201         for (; *s; s++)
202                 h += h*32 + *s;
203         return h;
204 }
205
206 static Sym *sysv_lookup(const char *s, uint32_t h, struct dso *dso)
207 {
208         size_t i;
209         Sym *syms = dso->syms;
210         uint32_t *hashtab = dso->hashtab;
211         char *strings = dso->strings;
212         for (i=hashtab[2+h%hashtab[0]]; i; i=hashtab[2+hashtab[0]+i]) {
213                 if ((!dso->versym || dso->versym[i] >= 0)
214                     && (!strcmp(s, strings+syms[i].st_name)))
215                         return syms+i;
216         }
217         return 0;
218 }
219
220 static Sym *gnu_lookup(uint32_t h1, uint32_t *hashtab, struct dso *dso, const char *s)
221 {
222         uint32_t nbuckets = hashtab[0];
223         uint32_t *buckets = hashtab + 4 + hashtab[2]*(sizeof(size_t)/4);
224         uint32_t i = buckets[h1 % nbuckets];
225
226         if (!i) return 0;
227
228         uint32_t *hashval = buckets + nbuckets + (i - hashtab[1]);
229
230         for (h1 |= 1; ; i++) {
231                 uint32_t h2 = *hashval++;
232                 if ((h1 == (h2|1)) && (!dso->versym || dso->versym[i] >= 0)
233                     && !strcmp(s, dso->strings + dso->syms[i].st_name))
234                         return dso->syms+i;
235                 if (h2 & 1) break;
236         }
237
238         return 0;
239 }
240
241 static Sym *gnu_lookup_filtered(uint32_t h1, uint32_t *hashtab, struct dso *dso, const char *s, uint32_t fofs, size_t fmask)
242 {
243         const size_t *bloomwords = (const void *)(hashtab+4);
244         size_t f = bloomwords[fofs & (hashtab[2]-1)];
245         if (!(f & fmask)) return 0;
246
247         f >>= (h1 >> hashtab[3]) % (8 * sizeof f);
248         if (!(f & 1)) return 0;
249
250         return gnu_lookup(h1, hashtab, dso, s);
251 }
252
253 #define OK_TYPES (1<<STT_NOTYPE | 1<<STT_OBJECT | 1<<STT_FUNC | 1<<STT_COMMON | 1<<STT_TLS)
254 #define OK_BINDS (1<<STB_GLOBAL | 1<<STB_WEAK | 1<<STB_GNU_UNIQUE)
255
256 #ifndef ARCH_SYM_REJECT_UND
257 #define ARCH_SYM_REJECT_UND(s) 0
258 #endif
259
260 static struct symdef find_sym(struct dso *dso, const char *s, int need_def)
261 {
262         uint32_t h = 0, gh, gho, *ght;
263         size_t ghm = 0;
264         struct symdef def = {0};
265         for (; dso; dso=dso->next) {
266                 Sym *sym;
267                 if (!dso->global) continue;
268                 if ((ght = dso->ghashtab)) {
269                         if (!ghm) {
270                                 gh = gnu_hash(s);
271                                 int maskbits = 8 * sizeof ghm;
272                                 gho = gh / maskbits;
273                                 ghm = 1ul << gh % maskbits;
274                         }
275                         sym = gnu_lookup_filtered(gh, ght, dso, s, gho, ghm);
276                 } else {
277                         if (!h) h = sysv_hash(s);
278                         sym = sysv_lookup(s, h, dso);
279                 }
280                 if (!sym) continue;
281                 if (!sym->st_shndx)
282                         if (need_def || (sym->st_info&0xf) == STT_TLS
283                             || ARCH_SYM_REJECT_UND(sym))
284                                 continue;
285                 if (!sym->st_value)
286                         if ((sym->st_info&0xf) != STT_TLS)
287                                 continue;
288                 if (!(1<<(sym->st_info&0xf) & OK_TYPES)) continue;
289                 if (!(1<<(sym->st_info>>4) & OK_BINDS)) continue;
290
291                 if (def.sym && sym->st_info>>4 == STB_WEAK) continue;
292                 def.sym = sym;
293                 def.dso = dso;
294                 if (sym->st_info>>4 == STB_GLOBAL) break;
295         }
296         return def;
297 }
298
299 __attribute__((__visibility__("hidden")))
300 ptrdiff_t __tlsdesc_static(), __tlsdesc_dynamic();
301
302 static void do_relocs(struct dso *dso, size_t *rel, size_t rel_size, size_t stride)
303 {
304         unsigned char *base = dso->base;
305         Sym *syms = dso->syms;
306         char *strings = dso->strings;
307         Sym *sym;
308         const char *name;
309         void *ctx;
310         int type;
311         int sym_index;
312         struct symdef def;
313         size_t *reloc_addr;
314         size_t sym_val;
315         size_t tls_val;
316         size_t addend;
317         int skip_relative = 0, reuse_addends = 0, save_slot = 0;
318
319         if (dso == &ldso) {
320                 /* Only ldso's REL table needs addend saving/reuse. */
321                 if (rel == apply_addends_to)
322                         reuse_addends = 1;
323                 skip_relative = 1;
324         }
325
326         for (; rel_size; rel+=stride, rel_size-=stride*sizeof(size_t)) {
327                 if (skip_relative && IS_RELATIVE(rel[1], dso->syms)) continue;
328                 type = R_TYPE(rel[1]);
329                 if (type == REL_NONE) continue;
330                 sym_index = R_SYM(rel[1]);
331                 reloc_addr = laddr(dso, rel[0]);
332                 if (sym_index) {
333                         sym = syms + sym_index;
334                         name = strings + sym->st_name;
335                         ctx = type==REL_COPY ? head->next : head;
336                         def = (sym->st_info&0xf) == STT_SECTION
337                                 ? (struct symdef){ .dso = dso, .sym = sym }
338                                 : find_sym(ctx, name, type==REL_PLT);
339                         if (!def.sym && (sym->st_shndx != SHN_UNDEF
340                             || sym->st_info>>4 != STB_WEAK)) {
341                                 error("Error relocating %s: %s: symbol not found",
342                                         dso->name, name);
343                                 if (runtime) longjmp(*rtld_fail, 1);
344                                 continue;
345                         }
346                 } else {
347                         sym = 0;
348                         def.sym = 0;
349                         def.dso = dso;
350                 }
351
352                 if (stride > 2) {
353                         addend = rel[2];
354                 } else if (type==REL_GOT || type==REL_PLT|| type==REL_COPY) {
355                         addend = 0;
356                 } else if (reuse_addends) {
357                         /* Save original addend in stage 2 where the dso
358                          * chain consists of just ldso; otherwise read back
359                          * saved addend since the inline one was clobbered. */
360                         if (head==&ldso)
361                                 saved_addends[save_slot] = *reloc_addr;
362                         addend = saved_addends[save_slot++];
363                 } else {
364                         addend = *reloc_addr;
365                 }
366
367                 sym_val = def.sym ? (size_t)laddr(def.dso, def.sym->st_value) : 0;
368                 tls_val = def.sym ? def.sym->st_value : 0;
369
370                 switch(type) {
371                 case REL_NONE:
372                         break;
373                 case REL_OFFSET:
374                         addend -= (size_t)reloc_addr;
375                 case REL_SYMBOLIC:
376                 case REL_GOT:
377                 case REL_PLT:
378                         *reloc_addr = sym_val + addend;
379                         break;
380                 case REL_RELATIVE:
381                         *reloc_addr = (size_t)base + addend;
382                         break;
383                 case REL_SYM_OR_REL:
384                         if (sym) *reloc_addr = sym_val + addend;
385                         else *reloc_addr = (size_t)base + addend;
386                         break;
387                 case REL_COPY:
388                         memcpy(reloc_addr, (void *)sym_val, sym->st_size);
389                         break;
390                 case REL_OFFSET32:
391                         *(uint32_t *)reloc_addr = sym_val + addend
392                                 - (size_t)reloc_addr;
393                         break;
394                 case REL_FUNCDESC:
395                         *reloc_addr = def.sym ? (size_t)(def.dso->funcdescs
396                                 + (def.sym - def.dso->syms)) : 0;
397                         break;
398                 case REL_FUNCDESC_VAL:
399                         if ((sym->st_info&0xf) == STT_SECTION) *reloc_addr += sym_val;
400                         else *reloc_addr = sym_val;
401                         reloc_addr[1] = def.sym ? (size_t)def.dso->got : 0;
402                         break;
403                 case REL_DTPMOD:
404                         *reloc_addr = def.dso->tls_id;
405                         break;
406                 case REL_DTPOFF:
407                         *reloc_addr = tls_val + addend - DTP_OFFSET;
408                         break;
409 #ifdef TLS_ABOVE_TP
410                 case REL_TPOFF:
411                         *reloc_addr = tls_val + def.dso->tls.offset + TPOFF_K + addend;
412                         break;
413 #else
414                 case REL_TPOFF:
415                         *reloc_addr = tls_val - def.dso->tls.offset + addend;
416                         break;
417                 case REL_TPOFF_NEG:
418                         *reloc_addr = def.dso->tls.offset - tls_val + addend;
419                         break;
420 #endif
421                 case REL_TLSDESC:
422                         if (stride<3) addend = reloc_addr[1];
423                         if (runtime && def.dso->tls_id >= static_tls_cnt) {
424                                 struct td_index *new = malloc(sizeof *new);
425                                 if (!new) {
426                                         error(
427                                         "Error relocating %s: cannot allocate TLSDESC for %s",
428                                         dso->name, sym ? name : "(local)" );
429                                         longjmp(*rtld_fail, 1);
430                                 }
431                                 new->next = dso->td_index;
432                                 dso->td_index = new;
433                                 new->args[0] = def.dso->tls_id;
434                                 new->args[1] = tls_val + addend;
435                                 reloc_addr[0] = (size_t)__tlsdesc_dynamic;
436                                 reloc_addr[1] = (size_t)new;
437                         } else {
438                                 reloc_addr[0] = (size_t)__tlsdesc_static;
439 #ifdef TLS_ABOVE_TP
440                                 reloc_addr[1] = tls_val + def.dso->tls.offset
441                                         + TPOFF_K + addend;
442 #else
443                                 reloc_addr[1] = tls_val - def.dso->tls.offset
444                                         + addend;
445 #endif
446                         }
447                         break;
448                 default:
449                         error("Error relocating %s: unsupported relocation type %d",
450                                 dso->name, type);
451                         if (runtime) longjmp(*rtld_fail, 1);
452                         continue;
453                 }
454         }
455 }
456
457 /* A huge hack: to make up for the wastefulness of shared libraries
458  * needing at least a page of dirty memory even if they have no global
459  * data, we reclaim the gaps at the beginning and end of writable maps
460  * and "donate" them to the heap by setting up minimal malloc
461  * structures and then freeing them. */
462
463 static void reclaim(struct dso *dso, size_t start, size_t end)
464 {
465         size_t *a, *z;
466         if (start >= dso->relro_start && start < dso->relro_end) start = dso->relro_end;
467         if (end   >= dso->relro_start && end   < dso->relro_end) end = dso->relro_start;
468         start = start + 6*sizeof(size_t)-1 & -4*sizeof(size_t);
469         end = (end & -4*sizeof(size_t)) - 2*sizeof(size_t);
470         if (start>end || end-start < 4*sizeof(size_t)) return;
471         a = laddr(dso, start);
472         z = laddr(dso, end);
473         a[-2] = 1;
474         a[-1] = z[0] = end-start + 2*sizeof(size_t) | 1;
475         z[1] = 1;
476         free(a);
477 }
478
479 static void reclaim_gaps(struct dso *dso)
480 {
481         Phdr *ph = dso->phdr;
482         size_t phcnt = dso->phnum;
483
484         if (DL_FDPIC) return; // FIXME
485         for (; phcnt--; ph=(void *)((char *)ph+dso->phentsize)) {
486                 if (ph->p_type!=PT_LOAD) continue;
487                 if ((ph->p_flags&(PF_R|PF_W))!=(PF_R|PF_W)) continue;
488                 reclaim(dso, ph->p_vaddr & -PAGE_SIZE, ph->p_vaddr);
489                 reclaim(dso, ph->p_vaddr+ph->p_memsz,
490                         ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE);
491         }
492 }
493
494 static void *mmap_fixed(void *p, size_t n, int prot, int flags, int fd, off_t off)
495 {
496         static int no_map_fixed;
497         char *q;
498         if (!no_map_fixed) {
499                 q = mmap(p, n, prot, flags|MAP_FIXED, fd, off);
500                 if (!DL_NOMMU_SUPPORT || q != MAP_FAILED || errno != EINVAL)
501                         return q;
502                 no_map_fixed = 1;
503         }
504         /* Fallbacks for MAP_FIXED failure on NOMMU kernels. */
505         if (flags & MAP_ANONYMOUS) {
506                 memset(p, 0, n);
507                 return p;
508         }
509         ssize_t r;
510         if (lseek(fd, off, SEEK_SET) < 0) return MAP_FAILED;
511         for (q=p; n; q+=r, off+=r, n-=r) {
512                 r = read(fd, q, n);
513                 if (r < 0 && errno != EINTR) return MAP_FAILED;
514                 if (!r) {
515                         memset(q, 0, n);
516                         break;
517                 }
518         }
519         return p;
520 }
521
522 static void unmap_library(struct dso *dso)
523 {
524         if (dso->loadmap) {
525                 size_t i;
526                 for (i=0; i<dso->loadmap->nsegs; i++) {
527                         if (!dso->loadmap->segs[i].p_memsz)
528                                 continue;
529                         munmap((void *)dso->loadmap->segs[i].addr,
530                                 dso->loadmap->segs[i].p_memsz);
531                 }
532                 free(dso->loadmap);
533         } else if (dso->map && dso->map_len) {
534                 munmap(dso->map, dso->map_len);
535         }
536 }
537
538 static void *map_library(int fd, struct dso *dso)
539 {
540         Ehdr buf[(896+sizeof(Ehdr))/sizeof(Ehdr)];
541         void *allocated_buf=0;
542         size_t phsize;
543         size_t addr_min=SIZE_MAX, addr_max=0, map_len;
544         size_t this_min, this_max;
545         size_t nsegs = 0;
546         off_t off_start;
547         Ehdr *eh;
548         Phdr *ph, *ph0;
549         unsigned prot;
550         unsigned char *map=MAP_FAILED, *base;
551         size_t dyn=0;
552         size_t tls_image=0;
553         size_t i;
554
555         ssize_t l = read(fd, buf, sizeof buf);
556         eh = buf;
557         if (l<0) return 0;
558         if (l<sizeof *eh || (eh->e_type != ET_DYN && eh->e_type != ET_EXEC))
559                 goto noexec;
560         phsize = eh->e_phentsize * eh->e_phnum;
561         if (phsize > sizeof buf - sizeof *eh) {
562                 allocated_buf = malloc(phsize);
563                 if (!allocated_buf) return 0;
564                 l = pread(fd, allocated_buf, phsize, eh->e_phoff);
565                 if (l < 0) goto error;
566                 if (l != phsize) goto noexec;
567                 ph = ph0 = allocated_buf;
568         } else if (eh->e_phoff + phsize > l) {
569                 l = pread(fd, buf+1, phsize, eh->e_phoff);
570                 if (l < 0) goto error;
571                 if (l != phsize) goto noexec;
572                 ph = ph0 = (void *)(buf + 1);
573         } else {
574                 ph = ph0 = (void *)((char *)buf + eh->e_phoff);
575         }
576         for (i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
577                 if (ph->p_type == PT_DYNAMIC) {
578                         dyn = ph->p_vaddr;
579                 } else if (ph->p_type == PT_TLS) {
580                         tls_image = ph->p_vaddr;
581                         dso->tls.align = ph->p_align;
582                         dso->tls.len = ph->p_filesz;
583                         dso->tls.size = ph->p_memsz;
584                 } else if (ph->p_type == PT_GNU_RELRO) {
585                         dso->relro_start = ph->p_vaddr & -PAGE_SIZE;
586                         dso->relro_end = (ph->p_vaddr + ph->p_memsz) & -PAGE_SIZE;
587                 }
588                 if (ph->p_type != PT_LOAD) continue;
589                 nsegs++;
590                 if (ph->p_vaddr < addr_min) {
591                         addr_min = ph->p_vaddr;
592                         off_start = ph->p_offset;
593                         prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
594                                 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
595                                 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
596                 }
597                 if (ph->p_vaddr+ph->p_memsz > addr_max) {
598                         addr_max = ph->p_vaddr+ph->p_memsz;
599                 }
600         }
601         if (!dyn) goto noexec;
602         if (DL_FDPIC && !(eh->e_flags & FDPIC_CONSTDISP_FLAG)) {
603                 dso->loadmap = calloc(1, sizeof *dso->loadmap
604                         + nsegs * sizeof *dso->loadmap->segs);
605                 if (!dso->loadmap) goto error;
606                 dso->loadmap->nsegs = nsegs;
607                 for (ph=ph0, i=0; i<nsegs; ph=(void *)((char *)ph+eh->e_phentsize)) {
608                         if (ph->p_type != PT_LOAD) continue;
609                         prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
610                                 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
611                                 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
612                         map = mmap(0, ph->p_memsz + (ph->p_vaddr & PAGE_SIZE-1),
613                                 prot, MAP_PRIVATE,
614                                 fd, ph->p_offset & -PAGE_SIZE);
615                         if (map == MAP_FAILED) {
616                                 unmap_library(dso);
617                                 goto error;
618                         }
619                         dso->loadmap->segs[i].addr = (size_t)map +
620                                 (ph->p_vaddr & PAGE_SIZE-1);
621                         dso->loadmap->segs[i].p_vaddr = ph->p_vaddr;
622                         dso->loadmap->segs[i].p_memsz = ph->p_memsz;
623                         i++;
624                         if (prot & PROT_WRITE) {
625                                 size_t brk = (ph->p_vaddr & PAGE_SIZE-1)
626                                         + ph->p_filesz;
627                                 size_t pgbrk = brk + PAGE_SIZE-1 & -PAGE_SIZE;
628                                 size_t pgend = brk + ph->p_memsz - ph->p_filesz
629                                         + PAGE_SIZE-1 & -PAGE_SIZE;
630                                 if (pgend > pgbrk && mmap_fixed(map+pgbrk,
631                                         pgend-pgbrk, prot,
632                                         MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS,
633                                         -1, off_start) == MAP_FAILED)
634                                         goto error;
635                                 memset(map + brk, 0, pgbrk-brk);
636                         }
637                 }
638                 map = (void *)dso->loadmap->segs[0].addr;
639                 map_len = 0;
640                 goto done_mapping;
641         }
642         addr_max += PAGE_SIZE-1;
643         addr_max &= -PAGE_SIZE;
644         addr_min &= -PAGE_SIZE;
645         off_start &= -PAGE_SIZE;
646         map_len = addr_max - addr_min + off_start;
647         /* The first time, we map too much, possibly even more than
648          * the length of the file. This is okay because we will not
649          * use the invalid part; we just need to reserve the right
650          * amount of virtual address space to map over later. */
651         map = DL_NOMMU_SUPPORT
652                 ? mmap((void *)addr_min, map_len, PROT_READ|PROT_WRITE|PROT_EXEC,
653                         MAP_PRIVATE|MAP_ANONYMOUS, -1, 0)
654                 : mmap((void *)addr_min, map_len, prot,
655                         MAP_PRIVATE, fd, off_start);
656         if (map==MAP_FAILED) goto error;
657         dso->map = map;
658         dso->map_len = map_len;
659         /* If the loaded file is not relocatable and the requested address is
660          * not available, then the load operation must fail. */
661         if (eh->e_type != ET_DYN && addr_min && map!=(void *)addr_min) {
662                 errno = EBUSY;
663                 goto error;
664         }
665         base = map - addr_min;
666         dso->phdr = 0;
667         dso->phnum = 0;
668         for (ph=ph0, i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
669                 if (ph->p_type != PT_LOAD) continue;
670                 /* Check if the programs headers are in this load segment, and
671                  * if so, record the address for use by dl_iterate_phdr. */
672                 if (!dso->phdr && eh->e_phoff >= ph->p_offset
673                     && eh->e_phoff+phsize <= ph->p_offset+ph->p_filesz) {
674                         dso->phdr = (void *)(base + ph->p_vaddr
675                                 + (eh->e_phoff-ph->p_offset));
676                         dso->phnum = eh->e_phnum;
677                         dso->phentsize = eh->e_phentsize;
678                 }
679                 /* Reuse the existing mapping for the lowest-address LOAD */
680                 if ((ph->p_vaddr & -PAGE_SIZE) == addr_min && !DL_NOMMU_SUPPORT)
681                         continue;
682                 this_min = ph->p_vaddr & -PAGE_SIZE;
683                 this_max = ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE;
684                 off_start = ph->p_offset & -PAGE_SIZE;
685                 prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
686                         ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
687                         ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
688                 if (mmap_fixed(base+this_min, this_max-this_min, prot, MAP_PRIVATE|MAP_FIXED, fd, off_start) == MAP_FAILED)
689                         goto error;
690                 if (ph->p_memsz > ph->p_filesz) {
691                         size_t brk = (size_t)base+ph->p_vaddr+ph->p_filesz;
692                         size_t pgbrk = brk+PAGE_SIZE-1 & -PAGE_SIZE;
693                         memset((void *)brk, 0, pgbrk-brk & PAGE_SIZE-1);
694                         if (pgbrk-(size_t)base < this_max && mmap_fixed((void *)pgbrk, (size_t)base+this_max-pgbrk, prot, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) == MAP_FAILED)
695                                 goto error;
696                 }
697         }
698         for (i=0; ((size_t *)(base+dyn))[i]; i+=2)
699                 if (((size_t *)(base+dyn))[i]==DT_TEXTREL) {
700                         if (mprotect(map, map_len, PROT_READ|PROT_WRITE|PROT_EXEC)
701                             && errno != ENOSYS)
702                                 goto error;
703                         break;
704                 }
705 done_mapping:
706         dso->base = base;
707         dso->dynv = laddr(dso, dyn);
708         if (dso->tls.size) dso->tls.image = laddr(dso, tls_image);
709         if (!runtime) reclaim_gaps(dso);
710         free(allocated_buf);
711         return map;
712 noexec:
713         errno = ENOEXEC;
714 error:
715         if (map!=MAP_FAILED) unmap_library(dso);
716         free(allocated_buf);
717         return 0;
718 }
719
720 static int path_open(const char *name, const char *s, char *buf, size_t buf_size)
721 {
722         size_t l;
723         int fd;
724         for (;;) {
725                 s += strspn(s, ":\n");
726                 l = strcspn(s, ":\n");
727                 if (l-1 >= INT_MAX) return -1;
728                 if (snprintf(buf, buf_size, "%.*s/%s", (int)l, s, name) < buf_size) {
729                         if ((fd = open(buf, O_RDONLY|O_CLOEXEC))>=0) return fd;
730                         switch (errno) {
731                         case ENOENT:
732                         case ENOTDIR:
733                         case EACCES:
734                         case ENAMETOOLONG:
735                                 break;
736                         default:
737                                 /* Any negative value but -1 will inhibit
738                                  * futher path search. */
739                                 return -2;
740                         }
741                 }
742                 s += l;
743         }
744 }
745
746 static int fixup_rpath(struct dso *p, char *buf, size_t buf_size)
747 {
748         size_t n, l;
749         const char *s, *t, *origin;
750         char *d;
751         if (p->rpath || !p->rpath_orig) return 0;
752         if (!strchr(p->rpath_orig, '$')) {
753                 p->rpath = p->rpath_orig;
754                 return 0;
755         }
756         n = 0;
757         s = p->rpath_orig;
758         while ((t=strchr(s, '$'))) {
759                 if (strncmp(t, "$ORIGIN", 7) && strncmp(t, "${ORIGIN}", 9))
760                         return 0;
761                 s = t+1;
762                 n++;
763         }
764         if (n > SSIZE_MAX/PATH_MAX) return 0;
765
766         if (p->kernel_mapped) {
767                 /* $ORIGIN searches cannot be performed for the main program
768                  * when it is suid/sgid/AT_SECURE. This is because the
769                  * pathname is under the control of the caller of execve.
770                  * For libraries, however, $ORIGIN can be processed safely
771                  * since the library's pathname came from a trusted source
772                  * (either system paths or a call to dlopen). */
773                 if (libc.secure)
774                         return 0;
775                 l = readlink("/proc/self/exe", buf, buf_size);
776                 if (l == -1) switch (errno) {
777                 case ENOENT:
778                 case ENOTDIR:
779                 case EACCES:
780                         break;
781                 default:
782                         return -1;
783                 }
784                 if (l >= buf_size)
785                         return 0;
786                 buf[l] = 0;
787                 origin = buf;
788         } else {
789                 origin = p->name;
790         }
791         t = strrchr(origin, '/');
792         l = t ? t-origin : 0;
793         p->rpath = malloc(strlen(p->rpath_orig) + n*l + 1);
794         if (!p->rpath) return -1;
795
796         d = p->rpath;
797         s = p->rpath_orig;
798         while ((t=strchr(s, '$'))) {
799                 memcpy(d, s, t-s);
800                 d += t-s;
801                 memcpy(d, origin, l);
802                 d += l;
803                 /* It was determined previously that the '$' is followed
804                  * either by "ORIGIN" or "{ORIGIN}". */
805                 s = t + 7 + 2*(t[1]=='{');
806         }
807         strcpy(d, s);
808         return 0;
809 }
810
811 static void decode_dyn(struct dso *p)
812 {
813         size_t dyn[DYN_CNT];
814         decode_vec(p->dynv, dyn, DYN_CNT);
815         p->syms = laddr(p, dyn[DT_SYMTAB]);
816         p->strings = laddr(p, dyn[DT_STRTAB]);
817         if (dyn[0]&(1<<DT_HASH))
818                 p->hashtab = laddr(p, dyn[DT_HASH]);
819         if (dyn[0]&(1<<DT_RPATH))
820                 p->rpath_orig = p->strings + dyn[DT_RPATH];
821         if (dyn[0]&(1<<DT_RUNPATH))
822                 p->rpath_orig = p->strings + dyn[DT_RUNPATH];
823         if (dyn[0]&(1<<DT_PLTGOT))
824                 p->got = laddr(p, dyn[DT_PLTGOT]);
825         if (search_vec(p->dynv, dyn, DT_GNU_HASH))
826                 p->ghashtab = laddr(p, *dyn);
827         if (search_vec(p->dynv, dyn, DT_VERSYM))
828                 p->versym = laddr(p, *dyn);
829 }
830
831 static size_t count_syms(struct dso *p)
832 {
833         if (p->hashtab) return p->hashtab[1];
834
835         size_t nsym, i;
836         uint32_t *buckets = p->ghashtab + 4 + (p->ghashtab[2]*sizeof(size_t)/4);
837         uint32_t *hashval;
838         for (i = nsym = 0; i < p->ghashtab[0]; i++) {
839                 if (buckets[i] > nsym)
840                         nsym = buckets[i];
841         }
842         if (nsym) {
843                 hashval = buckets + p->ghashtab[0] + (nsym - p->ghashtab[1]);
844                 do nsym++;
845                 while (!(*hashval++ & 1));
846         }
847         return nsym;
848 }
849
850 static void *dl_mmap(size_t n)
851 {
852         void *p;
853         int prot = PROT_READ|PROT_WRITE, flags = MAP_ANONYMOUS|MAP_PRIVATE;
854 #ifdef SYS_mmap2
855         p = (void *)__syscall(SYS_mmap2, 0, n, prot, flags, -1, 0);
856 #else
857         p = (void *)__syscall(SYS_mmap, 0, n, prot, flags, -1, 0);
858 #endif
859         return p == MAP_FAILED ? 0 : p;
860 }
861
862 static void makefuncdescs(struct dso *p)
863 {
864         static int self_done;
865         size_t nsym = count_syms(p);
866         size_t i, size = nsym * sizeof(*p->funcdescs);
867
868         if (!self_done) {
869                 p->funcdescs = dl_mmap(size);
870                 self_done = 1;
871         } else {
872                 p->funcdescs = malloc(size);
873         }
874         if (!p->funcdescs) {
875                 if (!runtime) a_crash();
876                 error("Error allocating function descriptors for %s", p->name);
877                 longjmp(*rtld_fail, 1);
878         }
879         for (i=0; i<nsym; i++) {
880                 if ((p->syms[i].st_info&0xf)==STT_FUNC && p->syms[i].st_shndx) {
881                         p->funcdescs[i].addr = laddr(p, p->syms[i].st_value);
882                         p->funcdescs[i].got = p->got;
883                 } else {
884                         p->funcdescs[i].addr = 0;
885                         p->funcdescs[i].got = 0;
886                 }
887         }
888 }
889
890 static struct dso *load_library(const char *name, struct dso *needed_by)
891 {
892         char buf[2*NAME_MAX+2];
893         const char *pathname;
894         unsigned char *map;
895         struct dso *p, temp_dso = {0};
896         int fd;
897         struct stat st;
898         size_t alloc_size;
899         int n_th = 0;
900         int is_self = 0;
901
902         if (!*name) {
903                 errno = EINVAL;
904                 return 0;
905         }
906
907         /* Catch and block attempts to reload the implementation itself */
908         if (name[0]=='l' && name[1]=='i' && name[2]=='b') {
909                 static const char *rp, reserved[] =
910                         "c\0pthread\0rt\0m\0dl\0util\0xnet\0";
911                 char *z = strchr(name, '.');
912                 if (z) {
913                         size_t l = z-name;
914                         for (rp=reserved; *rp && strncmp(name+3, rp, l-3); rp+=strlen(rp)+1);
915                         if (*rp) {
916                                 if (ldd_mode) {
917                                         /* Track which names have been resolved
918                                          * and only report each one once. */
919                                         static unsigned reported;
920                                         unsigned mask = 1U<<(rp-reserved);
921                                         if (!(reported & mask)) {
922                                                 reported |= mask;
923                                                 dprintf(1, "\t%s => %s (%p)\n",
924                                                         name, ldso.name,
925                                                         ldso.base);
926                                         }
927                                 }
928                                 is_self = 1;
929                         }
930                 }
931         }
932         if (!strcmp(name, ldso.name)) is_self = 1;
933         if (is_self) {
934                 if (!ldso.prev) {
935                         tail->next = &ldso;
936                         ldso.prev = tail;
937                         tail = ldso.next ? ldso.next : &ldso;
938                 }
939                 return &ldso;
940         }
941         if (strchr(name, '/')) {
942                 pathname = name;
943                 fd = open(name, O_RDONLY|O_CLOEXEC);
944         } else {
945                 /* Search for the name to see if it's already loaded */
946                 for (p=head->next; p; p=p->next) {
947                         if (p->shortname && !strcmp(p->shortname, name)) {
948                                 p->refcnt++;
949                                 return p;
950                         }
951                 }
952                 if (strlen(name) > NAME_MAX) return 0;
953                 fd = -1;
954                 if (env_path) fd = path_open(name, env_path, buf, sizeof buf);
955                 for (p=needed_by; fd == -1 && p; p=p->needed_by) {
956                         if (fixup_rpath(p, buf, sizeof buf) < 0)
957                                 fd = -2; /* Inhibit further search. */
958                         if (p->rpath)
959                                 fd = path_open(name, p->rpath, buf, sizeof buf);
960                 }
961                 if (fd == -1) {
962                         if (!sys_path) {
963                                 char *prefix = 0;
964                                 size_t prefix_len;
965                                 if (ldso.name[0]=='/') {
966                                         char *s, *t, *z;
967                                         for (s=t=z=ldso.name; *s; s++)
968                                                 if (*s=='/') z=t, t=s;
969                                         prefix_len = z-ldso.name;
970                                         if (prefix_len < PATH_MAX)
971                                                 prefix = ldso.name;
972                                 }
973                                 if (!prefix) {
974                                         prefix = "";
975                                         prefix_len = 0;
976                                 }
977                                 char etc_ldso_path[prefix_len + 1
978                                         + sizeof "/etc/ld-musl-" LDSO_ARCH ".path"];
979                                 snprintf(etc_ldso_path, sizeof etc_ldso_path,
980                                         "%.*s/etc/ld-musl-" LDSO_ARCH ".path",
981                                         (int)prefix_len, prefix);
982                                 FILE *f = fopen(etc_ldso_path, "rbe");
983                                 if (f) {
984                                         if (getdelim(&sys_path, (size_t[1]){0}, 0, f) <= 0) {
985                                                 free(sys_path);
986                                                 sys_path = "";
987                                         }
988                                         fclose(f);
989                                 } else if (errno != ENOENT) {
990                                         sys_path = "";
991                                 }
992                         }
993                         if (!sys_path) sys_path = "/lib:/usr/local/lib:/usr/lib";
994                         fd = path_open(name, sys_path, buf, sizeof buf);
995                 }
996                 pathname = buf;
997         }
998         if (fd < 0) return 0;
999         if (fstat(fd, &st) < 0) {
1000                 close(fd);
1001                 return 0;
1002         }
1003         for (p=head->next; p; p=p->next) {
1004                 if (p->dev == st.st_dev && p->ino == st.st_ino) {
1005                         /* If this library was previously loaded with a
1006                          * pathname but a search found the same inode,
1007                          * setup its shortname so it can be found by name. */
1008                         if (!p->shortname && pathname != name)
1009                                 p->shortname = strrchr(p->name, '/')+1;
1010                         close(fd);
1011                         p->refcnt++;
1012                         return p;
1013                 }
1014         }
1015         map = noload ? 0 : map_library(fd, &temp_dso);
1016         close(fd);
1017         if (!map) return 0;
1018
1019         /* Allocate storage for the new DSO. When there is TLS, this
1020          * storage must include a reservation for all pre-existing
1021          * threads to obtain copies of both the new TLS, and an
1022          * extended DTV capable of storing an additional slot for
1023          * the newly-loaded DSO. */
1024         alloc_size = sizeof *p + strlen(pathname) + 1;
1025         if (runtime && temp_dso.tls.image) {
1026                 size_t per_th = temp_dso.tls.size + temp_dso.tls.align
1027                         + sizeof(void *) * (tls_cnt+3);
1028                 n_th = libc.threads_minus_1 + 1;
1029                 if (n_th > SSIZE_MAX / per_th) alloc_size = SIZE_MAX;
1030                 else alloc_size += n_th * per_th;
1031         }
1032         p = calloc(1, alloc_size);
1033         if (!p) {
1034                 unmap_library(&temp_dso);
1035                 return 0;
1036         }
1037         memcpy(p, &temp_dso, sizeof temp_dso);
1038         decode_dyn(p);
1039         p->dev = st.st_dev;
1040         p->ino = st.st_ino;
1041         p->refcnt = 1;
1042         p->needed_by = needed_by;
1043         p->name = p->buf;
1044         strcpy(p->name, pathname);
1045         /* Add a shortname only if name arg was not an explicit pathname. */
1046         if (pathname != name) p->shortname = strrchr(p->name, '/')+1;
1047         if (p->tls.image) {
1048                 p->tls_id = ++tls_cnt;
1049                 tls_align = MAXP2(tls_align, p->tls.align);
1050 #ifdef TLS_ABOVE_TP
1051                 p->tls.offset = tls_offset + ( (tls_align-1) &
1052                         -(tls_offset + (uintptr_t)p->tls.image) );
1053                 tls_offset += p->tls.size;
1054 #else
1055                 tls_offset += p->tls.size + p->tls.align - 1;
1056                 tls_offset -= (tls_offset + (uintptr_t)p->tls.image)
1057                         & (p->tls.align-1);
1058                 p->tls.offset = tls_offset;
1059 #endif
1060                 p->new_dtv = (void *)(-sizeof(size_t) &
1061                         (uintptr_t)(p->name+strlen(p->name)+sizeof(size_t)));
1062                 p->new_tls = (void *)(p->new_dtv + n_th*(tls_cnt+1));
1063                 if (tls_tail) tls_tail->next = &p->tls;
1064                 else libc.tls_head = &p->tls;
1065                 tls_tail = &p->tls;
1066         }
1067
1068         tail->next = p;
1069         p->prev = tail;
1070         tail = p;
1071
1072         if (DL_FDPIC) makefuncdescs(p);
1073
1074         if (ldd_mode) dprintf(1, "\t%s => %s (%p)\n", name, pathname, p->base);
1075
1076         return p;
1077 }
1078
1079 static void load_deps(struct dso *p)
1080 {
1081         size_t i, ndeps=0;
1082         struct dso ***deps = &p->deps, **tmp, *dep;
1083         for (; p; p=p->next) {
1084                 for (i=0; p->dynv[i]; i+=2) {
1085                         if (p->dynv[i] != DT_NEEDED) continue;
1086                         dep = load_library(p->strings + p->dynv[i+1], p);
1087                         if (!dep) {
1088                                 error("Error loading shared library %s: %m (needed by %s)",
1089                                         p->strings + p->dynv[i+1], p->name);
1090                                 if (runtime) longjmp(*rtld_fail, 1);
1091                                 continue;
1092                         }
1093                         if (runtime) {
1094                                 tmp = realloc(*deps, sizeof(*tmp)*(ndeps+2));
1095                                 if (!tmp) longjmp(*rtld_fail, 1);
1096                                 tmp[ndeps++] = dep;
1097                                 tmp[ndeps] = 0;
1098                                 *deps = tmp;
1099                         }
1100                 }
1101         }
1102 }
1103
1104 static void load_preload(char *s)
1105 {
1106         int tmp;
1107         char *z;
1108         for (z=s; *z; s=z) {
1109                 for (   ; *s && (isspace(*s) || *s==':'); s++);
1110                 for (z=s; *z && !isspace(*z) && *z!=':'; z++);
1111                 tmp = *z;
1112                 *z = 0;
1113                 load_library(s, 0);
1114                 *z = tmp;
1115         }
1116 }
1117
1118 static void make_global(struct dso *p)
1119 {
1120         for (; p; p=p->next) p->global = 1;
1121 }
1122
1123 static void do_mips_relocs(struct dso *p, size_t *got)
1124 {
1125         size_t i, j, rel[2];
1126         unsigned char *base = p->base;
1127         i=0; search_vec(p->dynv, &i, DT_MIPS_LOCAL_GOTNO);
1128         if (p==&ldso) {
1129                 got += i;
1130         } else {
1131                 while (i--) *got++ += (size_t)base;
1132         }
1133         j=0; search_vec(p->dynv, &j, DT_MIPS_GOTSYM);
1134         i=0; search_vec(p->dynv, &i, DT_MIPS_SYMTABNO);
1135         Sym *sym = p->syms + j;
1136         rel[0] = (unsigned char *)got - base;
1137         for (i-=j; i; i--, sym++, rel[0]+=sizeof(size_t)) {
1138                 rel[1] = sym-p->syms << 8 | R_MIPS_JUMP_SLOT;
1139                 do_relocs(p, rel, sizeof rel, 2);
1140         }
1141 }
1142
1143 static void reloc_all(struct dso *p)
1144 {
1145         size_t dyn[DYN_CNT];
1146         for (; p; p=p->next) {
1147                 if (p->relocated) continue;
1148                 decode_vec(p->dynv, dyn, DYN_CNT);
1149                 if (NEED_MIPS_GOT_RELOCS)
1150                         do_mips_relocs(p, laddr(p, dyn[DT_PLTGOT]));
1151                 do_relocs(p, laddr(p, dyn[DT_JMPREL]), dyn[DT_PLTRELSZ],
1152                         2+(dyn[DT_PLTREL]==DT_RELA));
1153                 do_relocs(p, laddr(p, dyn[DT_REL]), dyn[DT_RELSZ], 2);
1154                 do_relocs(p, laddr(p, dyn[DT_RELA]), dyn[DT_RELASZ], 3);
1155
1156                 if (head != &ldso && p->relro_start != p->relro_end &&
1157                     mprotect(laddr(p, p->relro_start), p->relro_end-p->relro_start, PROT_READ)
1158                     && errno != ENOSYS) {
1159                         error("Error relocating %s: RELRO protection failed: %m",
1160                                 p->name);
1161                         if (runtime) longjmp(*rtld_fail, 1);
1162                 }
1163
1164                 p->relocated = 1;
1165         }
1166 }
1167
1168 static void kernel_mapped_dso(struct dso *p)
1169 {
1170         size_t min_addr = -1, max_addr = 0, cnt;
1171         Phdr *ph = p->phdr;
1172         for (cnt = p->phnum; cnt--; ph = (void *)((char *)ph + p->phentsize)) {
1173                 if (ph->p_type == PT_DYNAMIC) {
1174                         p->dynv = laddr(p, ph->p_vaddr);
1175                 } else if (ph->p_type == PT_GNU_RELRO) {
1176                         p->relro_start = ph->p_vaddr & -PAGE_SIZE;
1177                         p->relro_end = (ph->p_vaddr + ph->p_memsz) & -PAGE_SIZE;
1178                 }
1179                 if (ph->p_type != PT_LOAD) continue;
1180                 if (ph->p_vaddr < min_addr)
1181                         min_addr = ph->p_vaddr;
1182                 if (ph->p_vaddr+ph->p_memsz > max_addr)
1183                         max_addr = ph->p_vaddr+ph->p_memsz;
1184         }
1185         min_addr &= -PAGE_SIZE;
1186         max_addr = (max_addr + PAGE_SIZE-1) & -PAGE_SIZE;
1187         p->map = p->base + min_addr;
1188         p->map_len = max_addr - min_addr;
1189         p->kernel_mapped = 1;
1190 }
1191
1192 void __libc_exit_fini()
1193 {
1194         struct dso *p;
1195         size_t dyn[DYN_CNT];
1196         for (p=fini_head; p; p=p->fini_next) {
1197                 if (!p->constructed) continue;
1198                 decode_vec(p->dynv, dyn, DYN_CNT);
1199                 if (dyn[0] & (1<<DT_FINI_ARRAY)) {
1200                         size_t n = dyn[DT_FINI_ARRAYSZ]/sizeof(size_t);
1201                         size_t *fn = (size_t *)laddr(p, dyn[DT_FINI_ARRAY])+n;
1202                         while (n--) ((void (*)(void))*--fn)();
1203                 }
1204 #ifndef NO_LEGACY_INITFINI
1205                 if ((dyn[0] & (1<<DT_FINI)) && dyn[DT_FINI])
1206                         fpaddr(p, dyn[DT_FINI])();
1207 #endif
1208         }
1209 }
1210
1211 static void do_init_fini(struct dso *p)
1212 {
1213         size_t dyn[DYN_CNT];
1214         int need_locking = libc.threads_minus_1;
1215         /* Allow recursive calls that arise when a library calls
1216          * dlopen from one of its constructors, but block any
1217          * other threads until all ctors have finished. */
1218         if (need_locking) pthread_mutex_lock(&init_fini_lock);
1219         for (; p; p=p->prev) {
1220                 if (p->constructed) continue;
1221                 p->constructed = 1;
1222                 decode_vec(p->dynv, dyn, DYN_CNT);
1223                 if (dyn[0] & ((1<<DT_FINI) | (1<<DT_FINI_ARRAY))) {
1224                         p->fini_next = fini_head;
1225                         fini_head = p;
1226                 }
1227 #ifndef NO_LEGACY_INITFINI
1228                 if ((dyn[0] & (1<<DT_INIT)) && dyn[DT_INIT])
1229                         fpaddr(p, dyn[DT_INIT])();
1230 #endif
1231                 if (dyn[0] & (1<<DT_INIT_ARRAY)) {
1232                         size_t n = dyn[DT_INIT_ARRAYSZ]/sizeof(size_t);
1233                         size_t *fn = laddr(p, dyn[DT_INIT_ARRAY]);
1234                         while (n--) ((void (*)(void))*fn++)();
1235                 }
1236                 if (!need_locking && libc.threads_minus_1) {
1237                         need_locking = 1;
1238                         pthread_mutex_lock(&init_fini_lock);
1239                 }
1240         }
1241         if (need_locking) pthread_mutex_unlock(&init_fini_lock);
1242 }
1243
1244 void __libc_start_init(void)
1245 {
1246         do_init_fini(tail);
1247 }
1248
1249 static void dl_debug_state(void)
1250 {
1251 }
1252
1253 weak_alias(dl_debug_state, _dl_debug_state);
1254
1255 void __init_tls(size_t *auxv)
1256 {
1257 }
1258
1259 __attribute__((__visibility__("hidden")))
1260 void *__tls_get_new(size_t *v)
1261 {
1262         pthread_t self = __pthread_self();
1263
1264         /* Block signals to make accessing new TLS async-signal-safe */
1265         sigset_t set;
1266         __block_all_sigs(&set);
1267         if (v[0]<=(size_t)self->dtv[0]) {
1268                 __restore_sigs(&set);
1269                 return (char *)self->dtv[v[0]]+v[1]+DTP_OFFSET;
1270         }
1271
1272         /* This is safe without any locks held because, if the caller
1273          * is able to request the Nth entry of the DTV, the DSO list
1274          * must be valid at least that far out and it was synchronized
1275          * at program startup or by an already-completed call to dlopen. */
1276         struct dso *p;
1277         for (p=head; p->tls_id != v[0]; p=p->next);
1278
1279         /* Get new DTV space from new DSO if needed */
1280         if (v[0] > (size_t)self->dtv[0]) {
1281                 void **newdtv = p->new_dtv +
1282                         (v[0]+1)*a_fetch_add(&p->new_dtv_idx,1);
1283                 memcpy(newdtv, self->dtv,
1284                         ((size_t)self->dtv[0]+1) * sizeof(void *));
1285                 newdtv[0] = (void *)v[0];
1286                 self->dtv = self->dtv_copy = newdtv;
1287         }
1288
1289         /* Get new TLS memory from all new DSOs up to the requested one */
1290         unsigned char *mem;
1291         for (p=head; ; p=p->next) {
1292                 if (!p->tls_id || self->dtv[p->tls_id]) continue;
1293                 mem = p->new_tls + (p->tls.size + p->tls.align)
1294                         * a_fetch_add(&p->new_tls_idx,1);
1295                 mem += ((uintptr_t)p->tls.image - (uintptr_t)mem)
1296                         & (p->tls.align-1);
1297                 self->dtv[p->tls_id] = mem;
1298                 memcpy(mem, p->tls.image, p->tls.len);
1299                 if (p->tls_id == v[0]) break;
1300         }
1301         __restore_sigs(&set);
1302         return mem + v[1] + DTP_OFFSET;
1303 }
1304
1305 static void update_tls_size()
1306 {
1307         libc.tls_cnt = tls_cnt;
1308         libc.tls_align = tls_align;
1309         libc.tls_size = ALIGN(
1310                 (1+tls_cnt) * sizeof(void *) +
1311                 tls_offset +
1312                 sizeof(struct pthread) +
1313                 tls_align * 2,
1314         tls_align);
1315 }
1316
1317 /* Stage 1 of the dynamic linker is defined in dlstart.c. It calls the
1318  * following stage 2 and stage 3 functions via primitive symbolic lookup
1319  * since it does not have access to their addresses to begin with. */
1320
1321 /* Stage 2 of the dynamic linker is called after relative relocations 
1322  * have been processed. It can make function calls to static functions
1323  * and access string literals and static data, but cannot use extern
1324  * symbols. Its job is to perform symbolic relocations on the dynamic
1325  * linker itself, but some of the relocations performed may need to be
1326  * replaced later due to copy relocations in the main program. */
1327
1328 __attribute__((__visibility__("hidden")))
1329 void __dls2(unsigned char *base, size_t *sp)
1330 {
1331         if (DL_FDPIC) {
1332                 void *p1 = (void *)sp[-2];
1333                 void *p2 = (void *)sp[-1];
1334                 if (!p1) {
1335                         size_t *auxv, aux[AUX_CNT];
1336                         for (auxv=sp+1+*sp+1; *auxv; auxv++); auxv++;
1337                         decode_vec(auxv, aux, AUX_CNT);
1338                         if (aux[AT_BASE]) ldso.base = (void *)aux[AT_BASE];
1339                         else ldso.base = (void *)(aux[AT_PHDR] & -4096);
1340                 }
1341                 app_loadmap = p2 ? p1 : 0;
1342                 ldso.loadmap = p2 ? p2 : p1;
1343                 ldso.base = laddr(&ldso, 0);
1344         } else {
1345                 ldso.base = base;
1346         }
1347         Ehdr *ehdr = (void *)ldso.base;
1348         ldso.name = ldso.shortname = "libc.so";
1349         ldso.global = 1;
1350         ldso.phnum = ehdr->e_phnum;
1351         ldso.phdr = laddr(&ldso, ehdr->e_phoff);
1352         ldso.phentsize = ehdr->e_phentsize;
1353         kernel_mapped_dso(&ldso);
1354         decode_dyn(&ldso);
1355
1356         if (DL_FDPIC) makefuncdescs(&ldso);
1357
1358         /* Prepare storage for to save clobbered REL addends so they
1359          * can be reused in stage 3. There should be very few. If
1360          * something goes wrong and there are a huge number, abort
1361          * instead of risking stack overflow. */
1362         size_t dyn[DYN_CNT];
1363         decode_vec(ldso.dynv, dyn, DYN_CNT);
1364         size_t *rel = laddr(&ldso, dyn[DT_REL]);
1365         size_t rel_size = dyn[DT_RELSZ];
1366         size_t symbolic_rel_cnt = 0;
1367         apply_addends_to = rel;
1368         for (; rel_size; rel+=2, rel_size-=2*sizeof(size_t))
1369                 if (!IS_RELATIVE(rel[1], ldso.syms)) symbolic_rel_cnt++;
1370         if (symbolic_rel_cnt >= ADDEND_LIMIT) a_crash();
1371         size_t addends[symbolic_rel_cnt+1];
1372         saved_addends = addends;
1373
1374         head = &ldso;
1375         reloc_all(&ldso);
1376
1377         ldso.relocated = 0;
1378
1379         /* Call dynamic linker stage-3, __dls3, looking it up
1380          * symbolically as a barrier against moving the address
1381          * load across the above relocation processing. */
1382         struct symdef dls3_def = find_sym(&ldso, "__dls3", 0);
1383         if (DL_FDPIC) ((stage3_func)&ldso.funcdescs[dls3_def.sym-ldso.syms])(sp);
1384         else ((stage3_func)laddr(&ldso, dls3_def.sym->st_value))(sp);
1385 }
1386
1387 /* Stage 3 of the dynamic linker is called with the dynamic linker/libc
1388  * fully functional. Its job is to load (if not already loaded) and
1389  * process dependencies and relocations for the main application and
1390  * transfer control to its entry point. */
1391
1392 _Noreturn void __dls3(size_t *sp)
1393 {
1394         static struct dso app, vdso;
1395         size_t aux[AUX_CNT], *auxv;
1396         size_t i;
1397         char *env_preload=0;
1398         size_t vdso_base;
1399         int argc = *sp;
1400         char **argv = (void *)(sp+1);
1401         char **argv_orig = argv;
1402         char **envp = argv+argc+1;
1403
1404         /* Find aux vector just past environ[] and use it to initialize
1405          * global data that may be needed before we can make syscalls. */
1406         __environ = envp;
1407         for (i=argc+1; argv[i]; i++);
1408         libc.auxv = auxv = (void *)(argv+i+1);
1409         decode_vec(auxv, aux, AUX_CNT);
1410         __hwcap = aux[AT_HWCAP];
1411         libc.page_size = aux[AT_PAGESZ];
1412         libc.secure = ((aux[0]&0x7800)!=0x7800 || aux[AT_UID]!=aux[AT_EUID]
1413                 || aux[AT_GID]!=aux[AT_EGID] || aux[AT_SECURE]);
1414
1415         /* Setup early thread pointer in builtin_tls for ldso/libc itself to
1416          * use during dynamic linking. If possible it will also serve as the
1417          * thread pointer at runtime. */
1418         libc.tls_size = sizeof builtin_tls;
1419         libc.tls_align = tls_align;
1420         if (__init_tp(__copy_tls((void *)builtin_tls)) < 0) {
1421                 a_crash();
1422         }
1423
1424         /* Only trust user/env if kernel says we're not suid/sgid */
1425         if (!libc.secure) {
1426                 env_path = getenv("LD_LIBRARY_PATH");
1427                 env_preload = getenv("LD_PRELOAD");
1428         }
1429
1430         /* If the main program was already loaded by the kernel,
1431          * AT_PHDR will point to some location other than the dynamic
1432          * linker's program headers. */
1433         if (aux[AT_PHDR] != (size_t)ldso.phdr) {
1434                 size_t interp_off = 0;
1435                 size_t tls_image = 0;
1436                 /* Find load address of the main program, via AT_PHDR vs PT_PHDR. */
1437                 Phdr *phdr = app.phdr = (void *)aux[AT_PHDR];
1438                 app.phnum = aux[AT_PHNUM];
1439                 app.phentsize = aux[AT_PHENT];
1440                 for (i=aux[AT_PHNUM]; i; i--, phdr=(void *)((char *)phdr + aux[AT_PHENT])) {
1441                         if (phdr->p_type == PT_PHDR)
1442                                 app.base = (void *)(aux[AT_PHDR] - phdr->p_vaddr);
1443                         else if (phdr->p_type == PT_INTERP)
1444                                 interp_off = (size_t)phdr->p_vaddr;
1445                         else if (phdr->p_type == PT_TLS) {
1446                                 tls_image = phdr->p_vaddr;
1447                                 app.tls.len = phdr->p_filesz;
1448                                 app.tls.size = phdr->p_memsz;
1449                                 app.tls.align = phdr->p_align;
1450                         }
1451                 }
1452                 if (DL_FDPIC) app.loadmap = app_loadmap;
1453                 if (app.tls.size) app.tls.image = laddr(&app, tls_image);
1454                 if (interp_off) ldso.name = laddr(&app, interp_off);
1455                 if ((aux[0] & (1UL<<AT_EXECFN))
1456                     && strncmp((char *)aux[AT_EXECFN], "/proc/", 6))
1457                         app.name = (char *)aux[AT_EXECFN];
1458                 else
1459                         app.name = argv[0];
1460                 kernel_mapped_dso(&app);
1461         } else {
1462                 int fd;
1463                 char *ldname = argv[0];
1464                 size_t l = strlen(ldname);
1465                 if (l >= 3 && !strcmp(ldname+l-3, "ldd")) ldd_mode = 1;
1466                 argv++;
1467                 while (argv[0] && argv[0][0]=='-' && argv[0][1]=='-') {
1468                         char *opt = argv[0]+2;
1469                         *argv++ = (void *)-1;
1470                         if (!*opt) {
1471                                 break;
1472                         } else if (!memcmp(opt, "list", 5)) {
1473                                 ldd_mode = 1;
1474                         } else if (!memcmp(opt, "library-path", 12)) {
1475                                 if (opt[12]=='=') env_path = opt+13;
1476                                 else if (opt[12]) *argv = 0;
1477                                 else if (*argv) env_path = *argv++;
1478                         } else if (!memcmp(opt, "preload", 7)) {
1479                                 if (opt[7]=='=') env_preload = opt+8;
1480                                 else if (opt[7]) *argv = 0;
1481                                 else if (*argv) env_preload = *argv++;
1482                         } else {
1483                                 argv[0] = 0;
1484                         }
1485                 }
1486                 argv[-1] = (void *)(argc - (argv-argv_orig));
1487                 if (!argv[0]) {
1488                         dprintf(2, "musl libc (" LDSO_ARCH ")\n"
1489                                 "Version %s\n"
1490                                 "Dynamic Program Loader\n"
1491                                 "Usage: %s [options] [--] pathname%s\n",
1492                                 __libc_get_version(), ldname,
1493                                 ldd_mode ? "" : " [args]");
1494                         _exit(1);
1495                 }
1496                 fd = open(argv[0], O_RDONLY);
1497                 if (fd < 0) {
1498                         dprintf(2, "%s: cannot load %s: %s\n", ldname, argv[0], strerror(errno));
1499                         _exit(1);
1500                 }
1501                 runtime = 1;
1502                 Ehdr *ehdr = (void *)map_library(fd, &app);
1503                 if (!ehdr) {
1504                         dprintf(2, "%s: %s: Not a valid dynamic program\n", ldname, argv[0]);
1505                         _exit(1);
1506                 }
1507                 runtime = 0;
1508                 close(fd);
1509                 ldso.name = ldname;
1510                 app.name = argv[0];
1511                 aux[AT_ENTRY] = (size_t)laddr(&app, ehdr->e_entry);
1512                 /* Find the name that would have been used for the dynamic
1513                  * linker had ldd not taken its place. */
1514                 if (ldd_mode) {
1515                         for (i=0; i<app.phnum; i++) {
1516                                 if (app.phdr[i].p_type == PT_INTERP)
1517                                         ldso.name = laddr(&app, app.phdr[i].p_vaddr);
1518                         }
1519                         dprintf(1, "\t%s (%p)\n", ldso.name, ldso.base);
1520                 }
1521         }
1522         if (app.tls.size) {
1523                 libc.tls_head = &app.tls;
1524                 app.tls_id = tls_cnt = 1;
1525 #ifdef TLS_ABOVE_TP
1526                 app.tls.offset = 0;
1527                 tls_offset = app.tls.size
1528                         + ( -((uintptr_t)app.tls.image + app.tls.size)
1529                         & (app.tls.align-1) );
1530 #else
1531                 tls_offset = app.tls.offset = app.tls.size
1532                         + ( -((uintptr_t)app.tls.image + app.tls.size)
1533                         & (app.tls.align-1) );
1534 #endif
1535                 tls_align = MAXP2(tls_align, app.tls.align);
1536         }
1537         app.global = 1;
1538         decode_dyn(&app);
1539         if (DL_FDPIC) {
1540                 makefuncdescs(&app);
1541                 if (!app.loadmap) {
1542                         app.loadmap = (void *)&app_dummy_loadmap;
1543                         app.loadmap->nsegs = 1;
1544                         app.loadmap->segs[0].addr = (size_t)app.map;
1545                         app.loadmap->segs[0].p_vaddr = (size_t)app.map
1546                                 - (size_t)app.base;
1547                         app.loadmap->segs[0].p_memsz = app.map_len;
1548                 }
1549                 argv[-3] = (void *)app.loadmap;
1550         }
1551
1552         /* Attach to vdso, if provided by the kernel */
1553         if (search_vec(auxv, &vdso_base, AT_SYSINFO_EHDR)) {
1554                 Ehdr *ehdr = (void *)vdso_base;
1555                 Phdr *phdr = vdso.phdr = (void *)(vdso_base + ehdr->e_phoff);
1556                 vdso.phnum = ehdr->e_phnum;
1557                 vdso.phentsize = ehdr->e_phentsize;
1558                 for (i=ehdr->e_phnum; i; i--, phdr=(void *)((char *)phdr + ehdr->e_phentsize)) {
1559                         if (phdr->p_type == PT_DYNAMIC)
1560                                 vdso.dynv = (void *)(vdso_base + phdr->p_offset);
1561                         if (phdr->p_type == PT_LOAD)
1562                                 vdso.base = (void *)(vdso_base - phdr->p_vaddr + phdr->p_offset);
1563                 }
1564                 vdso.name = "";
1565                 vdso.shortname = "linux-gate.so.1";
1566                 vdso.global = 1;
1567                 vdso.relocated = 1;
1568                 decode_dyn(&vdso);
1569                 vdso.prev = &ldso;
1570                 ldso.next = &vdso;
1571         }
1572
1573         /* Initial dso chain consists only of the app. */
1574         head = tail = &app;
1575
1576         /* Donate unused parts of app and library mapping to malloc */
1577         reclaim_gaps(&app);
1578         reclaim_gaps(&ldso);
1579
1580         /* Load preload/needed libraries, add their symbols to the global
1581          * namespace, and perform all remaining relocations. */
1582         if (env_preload) load_preload(env_preload);
1583         load_deps(&app);
1584         make_global(&app);
1585
1586 #ifndef DYNAMIC_IS_RO
1587         for (i=0; app.dynv[i]; i+=2)
1588                 if (app.dynv[i]==DT_DEBUG)
1589                         app.dynv[i+1] = (size_t)&debug;
1590 #endif
1591
1592         /* The main program must be relocated LAST since it may contin
1593          * copy relocations which depend on libraries' relocations. */
1594         reloc_all(app.next);
1595         reloc_all(&app);
1596
1597         update_tls_size();
1598         if (libc.tls_size > sizeof builtin_tls || tls_align > MIN_TLS_ALIGN) {
1599                 void *initial_tls = calloc(libc.tls_size, 1);
1600                 if (!initial_tls) {
1601                         dprintf(2, "%s: Error getting %zu bytes thread-local storage: %m\n",
1602                                 argv[0], libc.tls_size);
1603                         _exit(127);
1604                 }
1605                 if (__init_tp(__copy_tls(initial_tls)) < 0) {
1606                         a_crash();
1607                 }
1608         } else {
1609                 size_t tmp_tls_size = libc.tls_size;
1610                 pthread_t self = __pthread_self();
1611                 /* Temporarily set the tls size to the full size of
1612                  * builtin_tls so that __copy_tls will use the same layout
1613                  * as it did for before. Then check, just to be safe. */
1614                 libc.tls_size = sizeof builtin_tls;
1615                 if (__copy_tls((void*)builtin_tls) != self) a_crash();
1616                 libc.tls_size = tmp_tls_size;
1617         }
1618         static_tls_cnt = tls_cnt;
1619
1620         if (ldso_fail) _exit(127);
1621         if (ldd_mode) _exit(0);
1622
1623         /* Switch to runtime mode: any further failures in the dynamic
1624          * linker are a reportable failure rather than a fatal startup
1625          * error. */
1626         runtime = 1;
1627
1628         debug.ver = 1;
1629         debug.bp = dl_debug_state;
1630         debug.head = head;
1631         debug.base = ldso.base;
1632         debug.state = 0;
1633         _dl_debug_state();
1634
1635         errno = 0;
1636
1637         CRTJMP((void *)aux[AT_ENTRY], argv-1);
1638         for(;;);
1639 }
1640
1641 void *dlopen(const char *file, int mode)
1642 {
1643         struct dso *volatile p, *orig_tail, *next;
1644         struct tls_module *orig_tls_tail;
1645         size_t orig_tls_cnt, orig_tls_offset, orig_tls_align;
1646         size_t i;
1647         int cs;
1648         jmp_buf jb;
1649
1650         if (!file) return head;
1651
1652         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
1653         pthread_rwlock_wrlock(&lock);
1654         __inhibit_ptc();
1655
1656         p = 0;
1657         orig_tls_tail = tls_tail;
1658         orig_tls_cnt = tls_cnt;
1659         orig_tls_offset = tls_offset;
1660         orig_tls_align = tls_align;
1661         orig_tail = tail;
1662         noload = mode & RTLD_NOLOAD;
1663
1664         rtld_fail = &jb;
1665         if (setjmp(*rtld_fail)) {
1666                 /* Clean up anything new that was (partially) loaded */
1667                 if (p && p->deps) for (i=0; p->deps[i]; i++)
1668                         if (p->deps[i]->global < 0)
1669                                 p->deps[i]->global = 0;
1670                 for (p=orig_tail->next; p; p=next) {
1671                         next = p->next;
1672                         while (p->td_index) {
1673                                 void *tmp = p->td_index->next;
1674                                 free(p->td_index);
1675                                 p->td_index = tmp;
1676                         }
1677                         free(p->funcdescs);
1678                         if (p->rpath != p->rpath_orig)
1679                                 free(p->rpath);
1680                         free(p->deps);
1681                         unmap_library(p);
1682                         free(p);
1683                 }
1684                 if (!orig_tls_tail) libc.tls_head = 0;
1685                 tls_tail = orig_tls_tail;
1686                 tls_cnt = orig_tls_cnt;
1687                 tls_offset = orig_tls_offset;
1688                 tls_align = orig_tls_align;
1689                 tail = orig_tail;
1690                 tail->next = 0;
1691                 p = 0;
1692                 goto end;
1693         } else p = load_library(file, head);
1694
1695         if (!p) {
1696                 error(noload ?
1697                         "Library %s is not already loaded" :
1698                         "Error loading shared library %s: %m",
1699                         file);
1700                 goto end;
1701         }
1702
1703         /* First load handling */
1704         if (!p->deps) {
1705                 load_deps(p);
1706                 if (p->deps) for (i=0; p->deps[i]; i++)
1707                         if (!p->deps[i]->global)
1708                                 p->deps[i]->global = -1;
1709                 if (!p->global) p->global = -1;
1710                 reloc_all(p);
1711                 if (p->deps) for (i=0; p->deps[i]; i++)
1712                         if (p->deps[i]->global < 0)
1713                                 p->deps[i]->global = 0;
1714                 if (p->global < 0) p->global = 0;
1715         }
1716
1717         if (mode & RTLD_GLOBAL) {
1718                 if (p->deps) for (i=0; p->deps[i]; i++)
1719                         p->deps[i]->global = 1;
1720                 p->global = 1;
1721         }
1722
1723         update_tls_size();
1724         _dl_debug_state();
1725         orig_tail = tail;
1726 end:
1727         __release_ptc();
1728         if (p) gencnt++;
1729         pthread_rwlock_unlock(&lock);
1730         if (p) do_init_fini(orig_tail);
1731         pthread_setcancelstate(cs, 0);
1732         return p;
1733 }
1734
1735 __attribute__((__visibility__("hidden")))
1736 int __dl_invalid_handle(void *h)
1737 {
1738         struct dso *p;
1739         for (p=head; p; p=p->next) if (h==p) return 0;
1740         error("Invalid library handle %p", (void *)h);
1741         return 1;
1742 }
1743
1744 static void *addr2dso(size_t a)
1745 {
1746         struct dso *p;
1747         size_t i;
1748         if (DL_FDPIC) for (p=head; p; p=p->next) {
1749                 i = count_syms(p);
1750                 if (a-(size_t)p->funcdescs < i*sizeof(*p->funcdescs))
1751                         return p;
1752         }
1753         for (p=head; p; p=p->next) {
1754                 if (DL_FDPIC && p->loadmap) {
1755                         for (i=0; i<p->loadmap->nsegs; i++) {
1756                                 if (a-p->loadmap->segs[i].p_vaddr
1757                                     < p->loadmap->segs[i].p_memsz)
1758                                         return p;
1759                         }
1760                 } else {
1761                         if (a-(size_t)p->map < p->map_len)
1762                                 return p;
1763                 }
1764         }
1765         return 0;
1766 }
1767
1768 void *__tls_get_addr(size_t *);
1769
1770 static void *do_dlsym(struct dso *p, const char *s, void *ra)
1771 {
1772         size_t i;
1773         uint32_t h = 0, gh = 0, *ght;
1774         Sym *sym;
1775         if (p == head || p == RTLD_DEFAULT || p == RTLD_NEXT) {
1776                 if (p == RTLD_DEFAULT) {
1777                         p = head;
1778                 } else if (p == RTLD_NEXT) {
1779                         p = addr2dso((size_t)ra);
1780                         if (!p) p=head;
1781                         p = p->next;
1782                 }
1783                 struct symdef def = find_sym(p, s, 0);
1784                 if (!def.sym) goto failed;
1785                 if ((def.sym->st_info&0xf) == STT_TLS)
1786                         return __tls_get_addr((size_t []){def.dso->tls_id, def.sym->st_value});
1787                 if (DL_FDPIC && (def.sym->st_info&0xf) == STT_FUNC)
1788                         return def.dso->funcdescs + (def.sym - def.dso->syms);
1789                 return laddr(def.dso, def.sym->st_value);
1790         }
1791         if (__dl_invalid_handle(p))
1792                 return 0;
1793         if ((ght = p->ghashtab)) {
1794                 gh = gnu_hash(s);
1795                 sym = gnu_lookup(gh, ght, p, s);
1796         } else {
1797                 h = sysv_hash(s);
1798                 sym = sysv_lookup(s, h, p);
1799         }
1800         if (sym && (sym->st_info&0xf) == STT_TLS)
1801                 return __tls_get_addr((size_t []){p->tls_id, sym->st_value});
1802         if (DL_FDPIC && sym && sym->st_shndx && (sym->st_info&0xf) == STT_FUNC)
1803                 return p->funcdescs + (sym - p->syms);
1804         if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
1805                 return laddr(p, sym->st_value);
1806         if (p->deps) for (i=0; p->deps[i]; i++) {
1807                 if ((ght = p->deps[i]->ghashtab)) {
1808                         if (!gh) gh = gnu_hash(s);
1809                         sym = gnu_lookup(gh, ght, p->deps[i], s);
1810                 } else {
1811                         if (!h) h = sysv_hash(s);
1812                         sym = sysv_lookup(s, h, p->deps[i]);
1813                 }
1814                 if (sym && (sym->st_info&0xf) == STT_TLS)
1815                         return __tls_get_addr((size_t []){p->deps[i]->tls_id, sym->st_value});
1816                 if (DL_FDPIC && sym && sym->st_shndx && (sym->st_info&0xf) == STT_FUNC)
1817                         return p->deps[i]->funcdescs + (sym - p->deps[i]->syms);
1818                 if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
1819                         return laddr(p->deps[i], sym->st_value);
1820         }
1821 failed:
1822         error("Symbol not found: %s", s);
1823         return 0;
1824 }
1825
1826 int dladdr(const void *addr, Dl_info *info)
1827 {
1828         struct dso *p;
1829         Sym *sym, *bestsym;
1830         uint32_t nsym;
1831         char *strings;
1832         void *best = 0;
1833
1834         pthread_rwlock_rdlock(&lock);
1835         p = addr2dso((size_t)addr);
1836         pthread_rwlock_unlock(&lock);
1837
1838         if (!p) return 0;
1839
1840         sym = p->syms;
1841         strings = p->strings;
1842         nsym = count_syms(p);
1843
1844         if (DL_FDPIC) {
1845                 size_t idx = ((size_t)addr-(size_t)p->funcdescs)
1846                         / sizeof(*p->funcdescs);
1847                 if (idx < nsym && (sym[idx].st_info&0xf) == STT_FUNC) {
1848                         best = p->funcdescs + idx;
1849                         bestsym = sym + idx;
1850                 }
1851         }
1852
1853         if (!best) for (; nsym; nsym--, sym++) {
1854                 if (sym->st_value
1855                  && (1<<(sym->st_info&0xf) & OK_TYPES)
1856                  && (1<<(sym->st_info>>4) & OK_BINDS)) {
1857                         void *symaddr = laddr(p, sym->st_value);
1858                         if (symaddr > addr || symaddr < best)
1859                                 continue;
1860                         best = symaddr;
1861                         bestsym = sym;
1862                         if (addr == symaddr)
1863                                 break;
1864                 }
1865         }
1866
1867         if (!best) return 0;
1868
1869         if (DL_FDPIC && (bestsym->st_info&0xf) == STT_FUNC)
1870                 best = p->funcdescs + (bestsym - p->syms);
1871
1872         info->dli_fname = p->name;
1873         info->dli_fbase = p->base;
1874         info->dli_sname = strings + bestsym->st_name;
1875         info->dli_saddr = best;
1876
1877         return 1;
1878 }
1879
1880 __attribute__((__visibility__("hidden")))
1881 void *__dlsym(void *restrict p, const char *restrict s, void *restrict ra)
1882 {
1883         void *res;
1884         pthread_rwlock_rdlock(&lock);
1885         res = do_dlsym(p, s, ra);
1886         pthread_rwlock_unlock(&lock);
1887         return res;
1888 }
1889
1890 int dl_iterate_phdr(int(*callback)(struct dl_phdr_info *info, size_t size, void *data), void *data)
1891 {
1892         struct dso *current;
1893         struct dl_phdr_info info;
1894         int ret = 0;
1895         for(current = head; current;) {
1896                 info.dlpi_addr      = (uintptr_t)current->base;
1897                 info.dlpi_name      = current->name;
1898                 info.dlpi_phdr      = current->phdr;
1899                 info.dlpi_phnum     = current->phnum;
1900                 info.dlpi_adds      = gencnt;
1901                 info.dlpi_subs      = 0;
1902                 info.dlpi_tls_modid = current->tls_id;
1903                 info.dlpi_tls_data  = current->tls.image;
1904
1905                 ret = (callback)(&info, sizeof (info), data);
1906
1907                 if (ret != 0) break;
1908
1909                 pthread_rwlock_rdlock(&lock);
1910                 current = current->next;
1911                 pthread_rwlock_unlock(&lock);
1912         }
1913         return ret;
1914 }
1915
1916 __attribute__((__visibility__("hidden")))
1917 void __dl_vseterr(const char *, va_list);
1918
1919 static void error(const char *fmt, ...)
1920 {
1921         va_list ap;
1922         va_start(ap, fmt);
1923         if (!runtime) {
1924                 vdprintf(2, fmt, ap);
1925                 dprintf(2, "\n");
1926                 ldso_fail = 1;
1927                 va_end(ap);
1928                 return;
1929         }
1930         __dl_vseterr(fmt, ap);
1931         va_end(ap);
1932 }
1933 #endif