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