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