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