7b47b1635944432159a22f3fb02d27516910cc1c
[musl] / ldso / dynlink.c
1 #define _GNU_SOURCE
2 #define SYSCALL_NO_TLS 1
3 #include <stdlib.h>
4 #include <stdarg.h>
5 #include <stddef.h>
6 #include <string.h>
7 #include <unistd.h>
8 #include <stdint.h>
9 #include <elf.h>
10 #include <sys/mman.h>
11 #include <limits.h>
12 #include <fcntl.h>
13 #include <sys/stat.h>
14 #include <errno.h>
15 #include <link.h>
16 #include <setjmp.h>
17 #include <pthread.h>
18 #include <ctype.h>
19 #include <dlfcn.h>
20 #include <semaphore.h>
21 #include <sys/membarrier.h>
22 #include "pthread_impl.h"
23 #include "fork_impl.h"
24 #include "libc.h"
25 #include "dynlink.h"
26
27 #define malloc __libc_malloc
28 #define calloc __libc_calloc
29 #define realloc __libc_realloc
30 #define free __libc_free
31
32 static void error_impl(const char *, ...);
33 static void error_noop(const char *, ...);
34 static void (*error)(const char *, ...) = error_noop;
35
36 #define MAXP2(a,b) (-(-(a)&-(b)))
37 #define ALIGN(x,y) ((x)+(y)-1 & -(y))
38
39 #define container_of(p,t,m) ((t*)((char *)(p)-offsetof(t,m)))
40 #define countof(a) ((sizeof (a))/(sizeof (a)[0]))
41
42 struct debug {
43         int ver;
44         void *head;
45         void (*bp)(void);
46         int state;
47         void *base;
48 };
49
50 struct td_index {
51         size_t args[2];
52         struct td_index *next;
53 };
54
55 struct dso {
56 #if DL_FDPIC
57         struct fdpic_loadmap *loadmap;
58 #else
59         unsigned char *base;
60 #endif
61         char *name;
62         size_t *dynv;
63         struct dso *next, *prev;
64
65         Phdr *phdr;
66         int phnum;
67         size_t phentsize;
68         Sym *syms;
69         Elf_Symndx *hashtab;
70         uint32_t *ghashtab;
71         int16_t *versym;
72         char *strings;
73         struct dso *syms_next, *lazy_next;
74         size_t *lazy, lazy_cnt;
75         unsigned char *map;
76         size_t map_len;
77         dev_t dev;
78         ino_t ino;
79         char relocated;
80         char constructed;
81         char kernel_mapped;
82         char mark;
83         char bfs_built;
84         char runtime_loaded;
85         struct dso **deps, *needed_by;
86         size_t ndeps_direct;
87         size_t next_dep;
88         pthread_t ctor_visitor;
89         char *rpath_orig, *rpath;
90         struct tls_module tls;
91         size_t tls_id;
92         size_t relro_start, relro_end;
93         uintptr_t *new_dtv;
94         unsigned char *new_tls;
95         struct td_index *td_index;
96         struct dso *fini_next;
97         char *shortname;
98 #if DL_FDPIC
99         unsigned char *base;
100 #else
101         struct fdpic_loadmap *loadmap;
102 #endif
103         struct funcdesc {
104                 void *addr;
105                 size_t *got;
106         } *funcdescs;
107         size_t *got;
108         char buf[];
109 };
110
111 struct symdef {
112         Sym *sym;
113         struct dso *dso;
114 };
115
116 typedef void (*stage3_func)(size_t *, size_t *);
117
118 static struct builtin_tls {
119         char c;
120         struct pthread pt;
121         void *space[16];
122 } builtin_tls[1];
123 #define MIN_TLS_ALIGN offsetof(struct builtin_tls, pt)
124
125 #define ADDEND_LIMIT 4096
126 static size_t *saved_addends, *apply_addends_to;
127
128 static struct dso ldso;
129 static struct dso *head, *tail, *fini_head, *syms_tail, *lazy_head;
130 static char *env_path, *sys_path;
131 static unsigned long long gencnt;
132 static int runtime;
133 static int ldd_mode;
134 static int ldso_fail;
135 static int noload;
136 static int shutting_down;
137 static jmp_buf *rtld_fail;
138 static pthread_rwlock_t lock;
139 static struct debug debug;
140 static struct tls_module *tls_tail;
141 static size_t tls_cnt, tls_offset, tls_align = MIN_TLS_ALIGN;
142 static size_t static_tls_cnt;
143 static pthread_mutex_t init_fini_lock;
144 static pthread_cond_t ctor_cond;
145 static struct dso *builtin_deps[2];
146 static struct dso *const no_deps[1];
147 static struct dso *builtin_ctor_queue[4];
148 static struct dso **main_ctor_queue;
149 static struct fdpic_loadmap *app_loadmap;
150 static struct fdpic_dummy_loadmap app_dummy_loadmap;
151
152 struct debug *_dl_debug_addr = &debug;
153
154 extern hidden int __malloc_replaced;
155
156 hidden void (*const __init_array_start)(void)=0, (*const __fini_array_start)(void)=0;
157
158 extern hidden void (*const __init_array_end)(void), (*const __fini_array_end)(void);
159
160 weak_alias(__init_array_start, __init_array_end);
161 weak_alias(__fini_array_start, __fini_array_end);
162
163 static int dl_strcmp(const char *l, const char *r)
164 {
165         for (; *l==*r && *l; l++, r++);
166         return *(unsigned char *)l - *(unsigned char *)r;
167 }
168 #define strcmp(l,r) dl_strcmp(l,r)
169
170 /* Compute load address for a virtual address in a given dso. */
171 #if DL_FDPIC
172 static void *laddr(const struct dso *p, size_t v)
173 {
174         size_t j=0;
175         if (!p->loadmap) return p->base + v;
176         for (j=0; v-p->loadmap->segs[j].p_vaddr >= p->loadmap->segs[j].p_memsz; j++);
177         return (void *)(v - p->loadmap->segs[j].p_vaddr + p->loadmap->segs[j].addr);
178 }
179 static void *laddr_pg(const struct dso *p, size_t v)
180 {
181         size_t j=0;
182         size_t pgsz = PAGE_SIZE;
183         if (!p->loadmap) return p->base + v;
184         for (j=0; ; j++) {
185                 size_t a = p->loadmap->segs[j].p_vaddr;
186                 size_t b = a + p->loadmap->segs[j].p_memsz;
187                 a &= -pgsz;
188                 b += pgsz-1;
189                 b &= -pgsz;
190                 if (v-a<b-a) break;
191         }
192         return (void *)(v - p->loadmap->segs[j].p_vaddr + p->loadmap->segs[j].addr);
193 }
194 static void (*fdbarrier(void *p))()
195 {
196         void (*fd)();
197         __asm__("" : "=r"(fd) : "0"(p));
198         return fd;
199 }
200 #define fpaddr(p, v) fdbarrier((&(struct funcdesc){ \
201         laddr(p, v), (p)->got }))
202 #else
203 #define laddr(p, v) (void *)((p)->base + (v))
204 #define laddr_pg(p, v) laddr(p, v)
205 #define fpaddr(p, v) ((void (*)())laddr(p, v))
206 #endif
207
208 static void decode_vec(size_t *v, size_t *a, size_t cnt)
209 {
210         size_t i;
211         for (i=0; i<cnt; i++) a[i] = 0;
212         for (; v[0]; v+=2) if (v[0]-1<cnt-1) {
213                 if (v[0] < 8*sizeof(long))
214                         a[0] |= 1UL<<v[0];
215                 a[v[0]] = v[1];
216         }
217 }
218
219 static int search_vec(size_t *v, size_t *r, size_t key)
220 {
221         for (; v[0]!=key; v+=2)
222                 if (!v[0]) return 0;
223         *r = v[1];
224         return 1;
225 }
226
227 static uint32_t sysv_hash(const char *s0)
228 {
229         const unsigned char *s = (void *)s0;
230         uint_fast32_t h = 0;
231         while (*s) {
232                 h = 16*h + *s++;
233                 h ^= h>>24 & 0xf0;
234         }
235         return h & 0xfffffff;
236 }
237
238 static uint32_t gnu_hash(const char *s0)
239 {
240         const unsigned char *s = (void *)s0;
241         uint_fast32_t h = 5381;
242         for (; *s; s++)
243                 h += h*32 + *s;
244         return h;
245 }
246
247 static Sym *sysv_lookup(const char *s, uint32_t h, struct dso *dso)
248 {
249         size_t i;
250         Sym *syms = dso->syms;
251         Elf_Symndx *hashtab = dso->hashtab;
252         char *strings = dso->strings;
253         for (i=hashtab[2+h%hashtab[0]]; i; i=hashtab[2+hashtab[0]+i]) {
254                 if ((!dso->versym || dso->versym[i] >= 0)
255                     && (!strcmp(s, strings+syms[i].st_name)))
256                         return syms+i;
257         }
258         return 0;
259 }
260
261 static Sym *gnu_lookup(uint32_t h1, uint32_t *hashtab, struct dso *dso, const char *s)
262 {
263         uint32_t nbuckets = hashtab[0];
264         uint32_t *buckets = hashtab + 4 + hashtab[2]*(sizeof(size_t)/4);
265         uint32_t i = buckets[h1 % nbuckets];
266
267         if (!i) return 0;
268
269         uint32_t *hashval = buckets + nbuckets + (i - hashtab[1]);
270
271         for (h1 |= 1; ; i++) {
272                 uint32_t h2 = *hashval++;
273                 if ((h1 == (h2|1)) && (!dso->versym || dso->versym[i] >= 0)
274                     && !strcmp(s, dso->strings + dso->syms[i].st_name))
275                         return dso->syms+i;
276                 if (h2 & 1) break;
277         }
278
279         return 0;
280 }
281
282 static Sym *gnu_lookup_filtered(uint32_t h1, uint32_t *hashtab, struct dso *dso, const char *s, uint32_t fofs, size_t fmask)
283 {
284         const size_t *bloomwords = (const void *)(hashtab+4);
285         size_t f = bloomwords[fofs & (hashtab[2]-1)];
286         if (!(f & fmask)) return 0;
287
288         f >>= (h1 >> hashtab[3]) % (8 * sizeof f);
289         if (!(f & 1)) return 0;
290
291         return gnu_lookup(h1, hashtab, dso, s);
292 }
293
294 #define OK_TYPES (1<<STT_NOTYPE | 1<<STT_OBJECT | 1<<STT_FUNC | 1<<STT_COMMON | 1<<STT_TLS)
295 #define OK_BINDS (1<<STB_GLOBAL | 1<<STB_WEAK | 1<<STB_GNU_UNIQUE)
296
297 #ifndef ARCH_SYM_REJECT_UND
298 #define ARCH_SYM_REJECT_UND(s) 0
299 #endif
300
301 #if defined(__GNUC__)
302 __attribute__((always_inline))
303 #endif
304 static inline struct symdef find_sym2(struct dso *dso, const char *s, int need_def, int use_deps)
305 {
306         uint32_t h = 0, gh = gnu_hash(s), gho = gh / (8*sizeof(size_t)), *ght;
307         size_t ghm = 1ul << gh % (8*sizeof(size_t));
308         struct symdef def = {0};
309         struct dso **deps = use_deps ? dso->deps : 0;
310         for (; dso; dso=use_deps ? *deps++ : dso->syms_next) {
311                 Sym *sym;
312                 if ((ght = dso->ghashtab)) {
313                         sym = gnu_lookup_filtered(gh, ght, dso, s, gho, ghm);
314                 } else {
315                         if (!h) h = sysv_hash(s);
316                         sym = sysv_lookup(s, h, dso);
317                 }
318                 if (!sym) continue;
319                 if (!sym->st_shndx)
320                         if (need_def || (sym->st_info&0xf) == STT_TLS
321                             || ARCH_SYM_REJECT_UND(sym))
322                                 continue;
323                 if (!sym->st_value)
324                         if ((sym->st_info&0xf) != STT_TLS)
325                                 continue;
326                 if (!(1<<(sym->st_info&0xf) & OK_TYPES)) continue;
327                 if (!(1<<(sym->st_info>>4) & OK_BINDS)) continue;
328                 def.sym = sym;
329                 def.dso = dso;
330                 break;
331         }
332         return def;
333 }
334
335 static struct symdef find_sym(struct dso *dso, const char *s, int need_def)
336 {
337         return find_sym2(dso, s, need_def, 0);
338 }
339
340 static struct symdef get_lfs64(const char *name)
341 {
342         static const char *p, lfs64_list[] =
343                 "aio_cancel\0aio_error\0aio_fsync\0aio_read\0aio_return\0"
344                 "aio_suspend\0aio_write\0alphasort\0creat\0fallocate\0"
345                 "fgetpos\0fopen\0freopen\0fseeko\0fsetpos\0fstat\0"
346                 "fstatat\0fstatfs\0fstatvfs\0ftello\0ftruncate\0ftw\0"
347                 "getdents\0getrlimit\0glob\0globfree\0lio_listio\0"
348                 "lockf\0lseek\0lstat\0mkostemp\0mkostemps\0mkstemp\0"
349                 "mkstemps\0mmap\0nftw\0open\0openat\0posix_fadvise\0"
350                 "posix_fallocate\0pread\0preadv\0prlimit\0pwrite\0"
351                 "pwritev\0readdir\0scandir\0sendfile\0setrlimit\0"
352                 "stat\0statfs\0statvfs\0tmpfile\0truncate\0versionsort\0"
353                 "__fxstat\0__fxstatat\0__lxstat\0__xstat\0";
354         size_t l;
355         char buf[16];
356         for (l=0; name[l]; l++) {
357                 if (l >= sizeof buf) goto nomatch;
358                 buf[l] = name[l];
359         }
360         if (!strcmp(name, "readdir64_r"))
361                 return find_sym(&ldso, "readdir_r", 1);
362         if (l<2 || name[l-2]!='6' || name[l-1]!='4')
363                 goto nomatch;
364         buf[l-=2] = 0;
365         for (p=lfs64_list; *p; p++) {
366                 if (!strcmp(buf, p)) return find_sym(&ldso, buf, 1);
367                 while (*p) p++;
368         }
369 nomatch:
370         return (struct symdef){ 0 };
371 }
372
373 static void do_relocs(struct dso *dso, size_t *rel, size_t rel_size, size_t stride)
374 {
375         unsigned char *base = dso->base;
376         Sym *syms = dso->syms;
377         char *strings = dso->strings;
378         Sym *sym;
379         const char *name;
380         void *ctx;
381         int type;
382         int sym_index;
383         struct symdef def;
384         size_t *reloc_addr;
385         size_t sym_val;
386         size_t tls_val;
387         size_t addend;
388         int skip_relative = 0, reuse_addends = 0, save_slot = 0;
389
390         if (dso == &ldso) {
391                 /* Only ldso's REL table needs addend saving/reuse. */
392                 if (rel == apply_addends_to)
393                         reuse_addends = 1;
394                 skip_relative = 1;
395         }
396
397         for (; rel_size; rel+=stride, rel_size-=stride*sizeof(size_t)) {
398                 if (skip_relative && IS_RELATIVE(rel[1], dso->syms)) continue;
399                 type = R_TYPE(rel[1]);
400                 if (type == REL_NONE) continue;
401                 reloc_addr = laddr(dso, rel[0]);
402
403                 if (stride > 2) {
404                         addend = rel[2];
405                 } else if (type==REL_GOT || type==REL_PLT|| type==REL_COPY) {
406                         addend = 0;
407                 } else if (reuse_addends) {
408                         /* Save original addend in stage 2 where the dso
409                          * chain consists of just ldso; otherwise read back
410                          * saved addend since the inline one was clobbered. */
411                         if (head==&ldso)
412                                 saved_addends[save_slot] = *reloc_addr;
413                         addend = saved_addends[save_slot++];
414                 } else {
415                         addend = *reloc_addr;
416                 }
417
418                 sym_index = R_SYM(rel[1]);
419                 if (sym_index) {
420                         sym = syms + sym_index;
421                         name = strings + sym->st_name;
422                         ctx = type==REL_COPY ? head->syms_next : head;
423                         def = (sym->st_info>>4) == STB_LOCAL
424                                 ? (struct symdef){ .dso = dso, .sym = sym }
425                                 : find_sym(ctx, name, type==REL_PLT);
426                         if (!def.sym) def = get_lfs64(name);
427                         if (!def.sym && (sym->st_shndx != SHN_UNDEF
428                             || sym->st_info>>4 != STB_WEAK)) {
429                                 if (dso->lazy && (type==REL_PLT || type==REL_GOT)) {
430                                         dso->lazy[3*dso->lazy_cnt+0] = rel[0];
431                                         dso->lazy[3*dso->lazy_cnt+1] = rel[1];
432                                         dso->lazy[3*dso->lazy_cnt+2] = addend;
433                                         dso->lazy_cnt++;
434                                         continue;
435                                 }
436                                 error("Error relocating %s: %s: symbol not found",
437                                         dso->name, name);
438                                 if (runtime) longjmp(*rtld_fail, 1);
439                                 continue;
440                         }
441                 } else {
442                         sym = 0;
443                         def.sym = 0;
444                         def.dso = dso;
445                 }
446
447                 sym_val = def.sym ? (size_t)laddr(def.dso, def.sym->st_value) : 0;
448                 tls_val = def.sym ? def.sym->st_value : 0;
449
450                 if ((type == REL_TPOFF || type == REL_TPOFF_NEG)
451                     && def.dso->tls_id > static_tls_cnt) {
452                         error("Error relocating %s: %s: initial-exec TLS "
453                                 "resolves to dynamic definition in %s",
454                                 dso->name, name, def.dso->name);
455                         longjmp(*rtld_fail, 1);
456                 }
457
458                 switch(type) {
459                 case REL_OFFSET:
460                         addend -= (size_t)reloc_addr;
461                 case REL_SYMBOLIC:
462                 case REL_GOT:
463                 case REL_PLT:
464                         *reloc_addr = sym_val + addend;
465                         break;
466                 case REL_USYMBOLIC:
467                         memcpy(reloc_addr, &(size_t){sym_val + addend}, sizeof(size_t));
468                         break;
469                 case REL_RELATIVE:
470                         *reloc_addr = (size_t)base + addend;
471                         break;
472                 case REL_SYM_OR_REL:
473                         if (sym) *reloc_addr = sym_val + addend;
474                         else *reloc_addr = (size_t)base + addend;
475                         break;
476                 case REL_COPY:
477                         memcpy(reloc_addr, (void *)sym_val, sym->st_size);
478                         break;
479                 case REL_OFFSET32:
480                         *(uint32_t *)reloc_addr = sym_val + addend
481                                 - (size_t)reloc_addr;
482                         break;
483                 case REL_FUNCDESC:
484                         *reloc_addr = def.sym ? (size_t)(def.dso->funcdescs
485                                 + (def.sym - def.dso->syms)) : 0;
486                         break;
487                 case REL_FUNCDESC_VAL:
488                         if ((sym->st_info&0xf) == STT_SECTION) *reloc_addr += sym_val;
489                         else *reloc_addr = sym_val;
490                         reloc_addr[1] = def.sym ? (size_t)def.dso->got : 0;
491                         break;
492                 case REL_DTPMOD:
493                         *reloc_addr = def.dso->tls_id;
494                         break;
495                 case REL_DTPOFF:
496                         *reloc_addr = tls_val + addend - DTP_OFFSET;
497                         break;
498 #ifdef TLS_ABOVE_TP
499                 case REL_TPOFF:
500                         *reloc_addr = tls_val + def.dso->tls.offset + TPOFF_K + addend;
501                         break;
502 #else
503                 case REL_TPOFF:
504                         *reloc_addr = tls_val - def.dso->tls.offset + addend;
505                         break;
506                 case REL_TPOFF_NEG:
507                         *reloc_addr = def.dso->tls.offset - tls_val + addend;
508                         break;
509 #endif
510                 case REL_TLSDESC:
511                         if (stride<3) addend = reloc_addr[1];
512                         if (def.dso->tls_id > static_tls_cnt) {
513                                 struct td_index *new = malloc(sizeof *new);
514                                 if (!new) {
515                                         error(
516                                         "Error relocating %s: cannot allocate TLSDESC for %s",
517                                         dso->name, sym ? name : "(local)" );
518                                         longjmp(*rtld_fail, 1);
519                                 }
520                                 new->next = dso->td_index;
521                                 dso->td_index = new;
522                                 new->args[0] = def.dso->tls_id;
523                                 new->args[1] = tls_val + addend - DTP_OFFSET;
524                                 reloc_addr[0] = (size_t)__tlsdesc_dynamic;
525                                 reloc_addr[1] = (size_t)new;
526                         } else {
527                                 reloc_addr[0] = (size_t)__tlsdesc_static;
528 #ifdef TLS_ABOVE_TP
529                                 reloc_addr[1] = tls_val + def.dso->tls.offset
530                                         + TPOFF_K + addend;
531 #else
532                                 reloc_addr[1] = tls_val - def.dso->tls.offset
533                                         + addend;
534 #endif
535                         }
536 #ifdef TLSDESC_BACKWARDS
537                         /* Some archs (32-bit ARM at least) invert the order of
538                          * the descriptor members. Fix them up here. */
539                         size_t tmp = reloc_addr[0];
540                         reloc_addr[0] = reloc_addr[1];
541                         reloc_addr[1] = tmp;
542 #endif
543                         break;
544                 default:
545                         error("Error relocating %s: unsupported relocation type %d",
546                                 dso->name, type);
547                         if (runtime) longjmp(*rtld_fail, 1);
548                         continue;
549                 }
550         }
551 }
552
553 static void do_relr_relocs(struct dso *dso, size_t *relr, size_t relr_size)
554 {
555         unsigned char *base = dso->base;
556         size_t *reloc_addr;
557         for (; relr_size; relr++, relr_size-=sizeof(size_t))
558                 if ((relr[0]&1) == 0) {
559                         reloc_addr = laddr(dso, relr[0]);
560                         *reloc_addr++ += (size_t)base;
561                 } else {
562                         int i = 0;
563                         for (size_t bitmap=relr[0]; (bitmap>>=1); i++)
564                                 if (bitmap&1)
565                                         reloc_addr[i] += (size_t)base;
566                         reloc_addr += 8*sizeof(size_t)-1;
567                 }
568 }
569
570 static void redo_lazy_relocs()
571 {
572         struct dso *p = lazy_head, *next;
573         lazy_head = 0;
574         for (; p; p=next) {
575                 next = p->lazy_next;
576                 size_t size = p->lazy_cnt*3*sizeof(size_t);
577                 p->lazy_cnt = 0;
578                 do_relocs(p, p->lazy, size, 3);
579                 if (p->lazy_cnt) {
580                         p->lazy_next = lazy_head;
581                         lazy_head = p;
582                 } else {
583                         free(p->lazy);
584                         p->lazy = 0;
585                         p->lazy_next = 0;
586                 }
587         }
588 }
589
590 /* A huge hack: to make up for the wastefulness of shared libraries
591  * needing at least a page of dirty memory even if they have no global
592  * data, we reclaim the gaps at the beginning and end of writable maps
593  * and "donate" them to the heap. */
594
595 static void reclaim(struct dso *dso, size_t start, size_t end)
596 {
597         if (start >= dso->relro_start && start < dso->relro_end) start = dso->relro_end;
598         if (end   >= dso->relro_start && end   < dso->relro_end) end = dso->relro_start;
599         if (start >= end) return;
600         char *base = laddr_pg(dso, start);
601         __malloc_donate(base, base+(end-start));
602 }
603
604 static void reclaim_gaps(struct dso *dso)
605 {
606         Phdr *ph = dso->phdr;
607         size_t phcnt = dso->phnum;
608
609         for (; phcnt--; ph=(void *)((char *)ph+dso->phentsize)) {
610                 if (ph->p_type!=PT_LOAD) continue;
611                 if ((ph->p_flags&(PF_R|PF_W))!=(PF_R|PF_W)) continue;
612                 reclaim(dso, ph->p_vaddr & -PAGE_SIZE, ph->p_vaddr);
613                 reclaim(dso, ph->p_vaddr+ph->p_memsz,
614                         ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE);
615         }
616 }
617
618 static ssize_t read_loop(int fd, void *p, size_t n)
619 {
620         for (size_t i=0; i<n; ) {
621                 ssize_t l = read(fd, (char *)p+i, n-i);
622                 if (l<0) {
623                         if (errno==EINTR) continue;
624                         else return -1;
625                 }
626                 if (l==0) return i;
627                 i += l;
628         }
629         return n;
630 }
631
632 static void *mmap_fixed(void *p, size_t n, int prot, int flags, int fd, off_t off)
633 {
634         static int no_map_fixed;
635         char *q;
636         if (!n) return p;
637         if (!no_map_fixed) {
638                 q = mmap(p, n, prot, flags|MAP_FIXED, fd, off);
639                 if (!DL_NOMMU_SUPPORT || q != MAP_FAILED || errno != EINVAL)
640                         return q;
641                 no_map_fixed = 1;
642         }
643         /* Fallbacks for MAP_FIXED failure on NOMMU kernels. */
644         if (flags & MAP_ANONYMOUS) {
645                 memset(p, 0, n);
646                 return p;
647         }
648         ssize_t r;
649         if (lseek(fd, off, SEEK_SET) < 0) return MAP_FAILED;
650         for (q=p; n; q+=r, off+=r, n-=r) {
651                 r = read(fd, q, n);
652                 if (r < 0 && errno != EINTR) return MAP_FAILED;
653                 if (!r) {
654                         memset(q, 0, n);
655                         break;
656                 }
657         }
658         return p;
659 }
660
661 static void unmap_library(struct dso *dso)
662 {
663         if (dso->loadmap) {
664                 size_t i;
665                 for (i=0; i<dso->loadmap->nsegs; i++) {
666                         if (!dso->loadmap->segs[i].p_memsz)
667                                 continue;
668                         munmap((void *)dso->loadmap->segs[i].addr,
669                                 dso->loadmap->segs[i].p_memsz);
670                 }
671                 free(dso->loadmap);
672         } else if (dso->map && dso->map_len) {
673                 munmap(dso->map, dso->map_len);
674         }
675 }
676
677 static void *map_library(int fd, struct dso *dso)
678 {
679         Ehdr buf[(896+sizeof(Ehdr))/sizeof(Ehdr)];
680         void *allocated_buf=0;
681         size_t phsize;
682         size_t addr_min=SIZE_MAX, addr_max=0, map_len;
683         size_t this_min, this_max;
684         size_t nsegs = 0;
685         off_t off_start;
686         Ehdr *eh;
687         Phdr *ph, *ph0;
688         unsigned prot;
689         unsigned char *map=MAP_FAILED, *base;
690         size_t dyn=0;
691         size_t tls_image=0;
692         size_t i;
693
694         ssize_t l = read(fd, buf, sizeof buf);
695         eh = buf;
696         if (l<0) return 0;
697         if (l<sizeof *eh || (eh->e_type != ET_DYN && eh->e_type != ET_EXEC))
698                 goto noexec;
699         phsize = eh->e_phentsize * eh->e_phnum;
700         if (phsize > sizeof buf - sizeof *eh) {
701                 allocated_buf = malloc(phsize);
702                 if (!allocated_buf) return 0;
703                 l = pread(fd, allocated_buf, phsize, eh->e_phoff);
704                 if (l < 0) goto error;
705                 if (l != phsize) goto noexec;
706                 ph = ph0 = allocated_buf;
707         } else if (eh->e_phoff + phsize > l) {
708                 l = pread(fd, buf+1, phsize, eh->e_phoff);
709                 if (l < 0) goto error;
710                 if (l != phsize) goto noexec;
711                 ph = ph0 = (void *)(buf + 1);
712         } else {
713                 ph = ph0 = (void *)((char *)buf + eh->e_phoff);
714         }
715         for (i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
716                 if (ph->p_type == PT_DYNAMIC) {
717                         dyn = ph->p_vaddr;
718                 } else if (ph->p_type == PT_TLS) {
719                         tls_image = ph->p_vaddr;
720                         dso->tls.align = ph->p_align;
721                         dso->tls.len = ph->p_filesz;
722                         dso->tls.size = ph->p_memsz;
723                 } else if (ph->p_type == PT_GNU_RELRO) {
724                         dso->relro_start = ph->p_vaddr & -PAGE_SIZE;
725                         dso->relro_end = (ph->p_vaddr + ph->p_memsz) & -PAGE_SIZE;
726                 } else if (ph->p_type == PT_GNU_STACK) {
727                         if (!runtime && ph->p_memsz > __default_stacksize) {
728                                 __default_stacksize =
729                                         ph->p_memsz < DEFAULT_STACK_MAX ?
730                                         ph->p_memsz : DEFAULT_STACK_MAX;
731                         }
732                 }
733                 if (ph->p_type != PT_LOAD) continue;
734                 nsegs++;
735                 if (ph->p_vaddr < addr_min) {
736                         addr_min = ph->p_vaddr;
737                         off_start = ph->p_offset;
738                         prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
739                                 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
740                                 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
741                 }
742                 if (ph->p_vaddr+ph->p_memsz > addr_max) {
743                         addr_max = ph->p_vaddr+ph->p_memsz;
744                 }
745         }
746         if (!dyn) goto noexec;
747         if (DL_FDPIC && !(eh->e_flags & FDPIC_CONSTDISP_FLAG)) {
748                 dso->loadmap = calloc(1, sizeof *dso->loadmap
749                         + nsegs * sizeof *dso->loadmap->segs);
750                 if (!dso->loadmap) goto error;
751                 dso->loadmap->nsegs = nsegs;
752                 for (ph=ph0, i=0; i<nsegs; ph=(void *)((char *)ph+eh->e_phentsize)) {
753                         if (ph->p_type != PT_LOAD) continue;
754                         prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
755                                 ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
756                                 ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
757                         map = mmap(0, ph->p_memsz + (ph->p_vaddr & PAGE_SIZE-1),
758                                 prot, MAP_PRIVATE,
759                                 fd, ph->p_offset & -PAGE_SIZE);
760                         if (map == MAP_FAILED) {
761                                 unmap_library(dso);
762                                 goto error;
763                         }
764                         dso->loadmap->segs[i].addr = (size_t)map +
765                                 (ph->p_vaddr & PAGE_SIZE-1);
766                         dso->loadmap->segs[i].p_vaddr = ph->p_vaddr;
767                         dso->loadmap->segs[i].p_memsz = ph->p_memsz;
768                         i++;
769                         if (prot & PROT_WRITE) {
770                                 size_t brk = (ph->p_vaddr & PAGE_SIZE-1)
771                                         + ph->p_filesz;
772                                 size_t pgbrk = brk + PAGE_SIZE-1 & -PAGE_SIZE;
773                                 size_t pgend = brk + ph->p_memsz - ph->p_filesz
774                                         + PAGE_SIZE-1 & -PAGE_SIZE;
775                                 if (pgend > pgbrk && mmap_fixed(map+pgbrk,
776                                         pgend-pgbrk, prot,
777                                         MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS,
778                                         -1, off_start) == MAP_FAILED)
779                                         goto error;
780                                 memset(map + brk, 0, pgbrk-brk);
781                         }
782                 }
783                 map = (void *)dso->loadmap->segs[0].addr;
784                 map_len = 0;
785                 goto done_mapping;
786         }
787         addr_max += PAGE_SIZE-1;
788         addr_max &= -PAGE_SIZE;
789         addr_min &= -PAGE_SIZE;
790         off_start &= -PAGE_SIZE;
791         map_len = addr_max - addr_min + off_start;
792         /* The first time, we map too much, possibly even more than
793          * the length of the file. This is okay because we will not
794          * use the invalid part; we just need to reserve the right
795          * amount of virtual address space to map over later. */
796         map = DL_NOMMU_SUPPORT
797                 ? mmap((void *)addr_min, map_len, PROT_READ|PROT_WRITE|PROT_EXEC,
798                         MAP_PRIVATE|MAP_ANONYMOUS, -1, 0)
799                 : mmap((void *)addr_min, map_len, prot,
800                         MAP_PRIVATE, fd, off_start);
801         if (map==MAP_FAILED) goto error;
802         dso->map = map;
803         dso->map_len = map_len;
804         /* If the loaded file is not relocatable and the requested address is
805          * not available, then the load operation must fail. */
806         if (eh->e_type != ET_DYN && addr_min && map!=(void *)addr_min) {
807                 errno = EBUSY;
808                 goto error;
809         }
810         base = map - addr_min;
811         dso->phdr = 0;
812         dso->phnum = 0;
813         for (ph=ph0, i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
814                 if (ph->p_type != PT_LOAD) continue;
815                 /* Check if the programs headers are in this load segment, and
816                  * if so, record the address for use by dl_iterate_phdr. */
817                 if (!dso->phdr && eh->e_phoff >= ph->p_offset
818                     && eh->e_phoff+phsize <= ph->p_offset+ph->p_filesz) {
819                         dso->phdr = (void *)(base + ph->p_vaddr
820                                 + (eh->e_phoff-ph->p_offset));
821                         dso->phnum = eh->e_phnum;
822                         dso->phentsize = eh->e_phentsize;
823                 }
824                 this_min = ph->p_vaddr & -PAGE_SIZE;
825                 this_max = ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE;
826                 off_start = ph->p_offset & -PAGE_SIZE;
827                 prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
828                         ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
829                         ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
830                 /* Reuse the existing mapping for the lowest-address LOAD */
831                 if ((ph->p_vaddr & -PAGE_SIZE) != addr_min || DL_NOMMU_SUPPORT)
832                         if (mmap_fixed(base+this_min, this_max-this_min, prot, MAP_PRIVATE|MAP_FIXED, fd, off_start) == MAP_FAILED)
833                                 goto error;
834                 if (ph->p_memsz > ph->p_filesz && (ph->p_flags&PF_W)) {
835                         size_t brk = (size_t)base+ph->p_vaddr+ph->p_filesz;
836                         size_t pgbrk = brk+PAGE_SIZE-1 & -PAGE_SIZE;
837                         memset((void *)brk, 0, pgbrk-brk & PAGE_SIZE-1);
838                         if (pgbrk-(size_t)base < this_max && mmap_fixed((void *)pgbrk, (size_t)base+this_max-pgbrk, prot, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) == MAP_FAILED)
839                                 goto error;
840                 }
841         }
842         for (i=0; ((size_t *)(base+dyn))[i]; i+=2)
843                 if (((size_t *)(base+dyn))[i]==DT_TEXTREL) {
844                         if (mprotect(map, map_len, PROT_READ|PROT_WRITE|PROT_EXEC)
845                             && errno != ENOSYS)
846                                 goto error;
847                         break;
848                 }
849 done_mapping:
850         dso->base = base;
851         dso->dynv = laddr(dso, dyn);
852         if (dso->tls.size) dso->tls.image = laddr(dso, tls_image);
853         free(allocated_buf);
854         return map;
855 noexec:
856         errno = ENOEXEC;
857 error:
858         if (map!=MAP_FAILED) unmap_library(dso);
859         free(allocated_buf);
860         return 0;
861 }
862
863 static int path_open(const char *name, const char *s, char *buf, size_t buf_size)
864 {
865         size_t l;
866         int fd;
867         for (;;) {
868                 s += strspn(s, ":\n");
869                 l = strcspn(s, ":\n");
870                 if (l-1 >= INT_MAX) return -1;
871                 if (snprintf(buf, buf_size, "%.*s/%s", (int)l, s, name) < buf_size) {
872                         if ((fd = open(buf, O_RDONLY|O_CLOEXEC))>=0) return fd;
873                         switch (errno) {
874                         case ENOENT:
875                         case ENOTDIR:
876                         case EACCES:
877                         case ENAMETOOLONG:
878                                 break;
879                         default:
880                                 /* Any negative value but -1 will inhibit
881                                  * futher path search. */
882                                 return -2;
883                         }
884                 }
885                 s += l;
886         }
887 }
888
889 static int fixup_rpath(struct dso *p, char *buf, size_t buf_size)
890 {
891         size_t n, l;
892         const char *s, *t, *origin;
893         char *d;
894         if (p->rpath || !p->rpath_orig) return 0;
895         if (!strchr(p->rpath_orig, '$')) {
896                 p->rpath = p->rpath_orig;
897                 return 0;
898         }
899         n = 0;
900         s = p->rpath_orig;
901         while ((t=strchr(s, '$'))) {
902                 if (strncmp(t, "$ORIGIN", 7) && strncmp(t, "${ORIGIN}", 9))
903                         return 0;
904                 s = t+1;
905                 n++;
906         }
907         if (n > SSIZE_MAX/PATH_MAX) return 0;
908
909         if (p->kernel_mapped) {
910                 /* $ORIGIN searches cannot be performed for the main program
911                  * when it is suid/sgid/AT_SECURE. This is because the
912                  * pathname is under the control of the caller of execve.
913                  * For libraries, however, $ORIGIN can be processed safely
914                  * since the library's pathname came from a trusted source
915                  * (either system paths or a call to dlopen). */
916                 if (libc.secure)
917                         return 0;
918                 l = readlink("/proc/self/exe", buf, buf_size);
919                 if (l == -1) switch (errno) {
920                 case ENOENT:
921                 case ENOTDIR:
922                 case EACCES:
923                         return 0;
924                 default:
925                         return -1;
926                 }
927                 if (l >= buf_size)
928                         return 0;
929                 buf[l] = 0;
930                 origin = buf;
931         } else {
932                 origin = p->name;
933         }
934         t = strrchr(origin, '/');
935         if (t) {
936                 l = t-origin;
937         } else {
938                 /* Normally p->name will always be an absolute or relative
939                  * pathname containing at least one '/' character, but in the
940                  * case where ldso was invoked as a command to execute a
941                  * program in the working directory, app.name may not. Fix. */
942                 origin = ".";
943                 l = 1;
944         }
945         /* Disallow non-absolute origins for suid/sgid/AT_SECURE. */
946         if (libc.secure && *origin != '/')
947                 return 0;
948         p->rpath = malloc(strlen(p->rpath_orig) + n*l + 1);
949         if (!p->rpath) return -1;
950
951         d = p->rpath;
952         s = p->rpath_orig;
953         while ((t=strchr(s, '$'))) {
954                 memcpy(d, s, t-s);
955                 d += t-s;
956                 memcpy(d, origin, l);
957                 d += l;
958                 /* It was determined previously that the '$' is followed
959                  * either by "ORIGIN" or "{ORIGIN}". */
960                 s = t + 7 + 2*(t[1]=='{');
961         }
962         strcpy(d, s);
963         return 0;
964 }
965
966 static void decode_dyn(struct dso *p)
967 {
968         size_t dyn[DYN_CNT];
969         decode_vec(p->dynv, dyn, DYN_CNT);
970         p->syms = laddr(p, dyn[DT_SYMTAB]);
971         p->strings = laddr(p, dyn[DT_STRTAB]);
972         if (dyn[0]&(1<<DT_HASH))
973                 p->hashtab = laddr(p, dyn[DT_HASH]);
974         if (dyn[0]&(1<<DT_RPATH))
975                 p->rpath_orig = p->strings + dyn[DT_RPATH];
976         if (dyn[0]&(1<<DT_RUNPATH))
977                 p->rpath_orig = p->strings + dyn[DT_RUNPATH];
978         if (dyn[0]&(1<<DT_PLTGOT))
979                 p->got = laddr(p, dyn[DT_PLTGOT]);
980         if (search_vec(p->dynv, dyn, DT_GNU_HASH))
981                 p->ghashtab = laddr(p, *dyn);
982         if (search_vec(p->dynv, dyn, DT_VERSYM))
983                 p->versym = laddr(p, *dyn);
984 }
985
986 static size_t count_syms(struct dso *p)
987 {
988         if (p->hashtab) return p->hashtab[1];
989
990         size_t nsym, i;
991         uint32_t *buckets = p->ghashtab + 4 + (p->ghashtab[2]*sizeof(size_t)/4);
992         uint32_t *hashval;
993         for (i = nsym = 0; i < p->ghashtab[0]; i++) {
994                 if (buckets[i] > nsym)
995                         nsym = buckets[i];
996         }
997         if (nsym) {
998                 hashval = buckets + p->ghashtab[0] + (nsym - p->ghashtab[1]);
999                 do nsym++;
1000                 while (!(*hashval++ & 1));
1001         }
1002         return nsym;
1003 }
1004
1005 static void *dl_mmap(size_t n)
1006 {
1007         void *p;
1008         int prot = PROT_READ|PROT_WRITE, flags = MAP_ANONYMOUS|MAP_PRIVATE;
1009 #ifdef SYS_mmap2
1010         p = (void *)__syscall(SYS_mmap2, 0, n, prot, flags, -1, 0);
1011 #else
1012         p = (void *)__syscall(SYS_mmap, 0, n, prot, flags, -1, 0);
1013 #endif
1014         return (unsigned long)p > -4096UL ? 0 : p;
1015 }
1016
1017 static void makefuncdescs(struct dso *p)
1018 {
1019         static int self_done;
1020         size_t nsym = count_syms(p);
1021         size_t i, size = nsym * sizeof(*p->funcdescs);
1022
1023         if (!self_done) {
1024                 p->funcdescs = dl_mmap(size);
1025                 self_done = 1;
1026         } else {
1027                 p->funcdescs = malloc(size);
1028         }
1029         if (!p->funcdescs) {
1030                 if (!runtime) a_crash();
1031                 error("Error allocating function descriptors for %s", p->name);
1032                 longjmp(*rtld_fail, 1);
1033         }
1034         for (i=0; i<nsym; i++) {
1035                 if ((p->syms[i].st_info&0xf)==STT_FUNC && p->syms[i].st_shndx) {
1036                         p->funcdescs[i].addr = laddr(p, p->syms[i].st_value);
1037                         p->funcdescs[i].got = p->got;
1038                 } else {
1039                         p->funcdescs[i].addr = 0;
1040                         p->funcdescs[i].got = 0;
1041                 }
1042         }
1043 }
1044
1045 static struct dso *load_library(const char *name, struct dso *needed_by)
1046 {
1047         char buf[2*NAME_MAX+2];
1048         const char *pathname;
1049         unsigned char *map;
1050         struct dso *p, temp_dso = {0};
1051         int fd;
1052         struct stat st;
1053         size_t alloc_size;
1054         int n_th = 0;
1055         int is_self = 0;
1056
1057         if (!*name) {
1058                 errno = EINVAL;
1059                 return 0;
1060         }
1061
1062         /* Catch and block attempts to reload the implementation itself */
1063         if (name[0]=='l' && name[1]=='i' && name[2]=='b') {
1064                 static const char reserved[] =
1065                         "c.pthread.rt.m.dl.util.xnet.";
1066                 const char *rp, *next;
1067                 for (rp=reserved; *rp; rp=next) {
1068                         next = strchr(rp, '.') + 1;
1069                         if (strncmp(name+3, rp, next-rp) == 0)
1070                                 break;
1071                 }
1072                 if (*rp) {
1073                         if (ldd_mode) {
1074                                 /* Track which names have been resolved
1075                                  * and only report each one once. */
1076                                 static unsigned reported;
1077                                 unsigned mask = 1U<<(rp-reserved);
1078                                 if (!(reported & mask)) {
1079                                         reported |= mask;
1080                                         dprintf(1, "\t%s => %s (%p)\n",
1081                                                 name, ldso.name,
1082                                                 ldso.base);
1083                                 }
1084                         }
1085                         is_self = 1;
1086                 }
1087         }
1088         if (!strcmp(name, ldso.name)) is_self = 1;
1089         if (is_self) {
1090                 if (!ldso.prev) {
1091                         tail->next = &ldso;
1092                         ldso.prev = tail;
1093                         tail = &ldso;
1094                 }
1095                 return &ldso;
1096         }
1097         if (strchr(name, '/')) {
1098                 pathname = name;
1099                 fd = open(name, O_RDONLY|O_CLOEXEC);
1100         } else {
1101                 /* Search for the name to see if it's already loaded */
1102                 for (p=head->next; p; p=p->next) {
1103                         if (p->shortname && !strcmp(p->shortname, name)) {
1104                                 return p;
1105                         }
1106                 }
1107                 if (strlen(name) > NAME_MAX) return 0;
1108                 fd = -1;
1109                 if (env_path) fd = path_open(name, env_path, buf, sizeof buf);
1110                 for (p=needed_by; fd == -1 && p; p=p->needed_by) {
1111                         if (fixup_rpath(p, buf, sizeof buf) < 0)
1112                                 fd = -2; /* Inhibit further search. */
1113                         if (p->rpath)
1114                                 fd = path_open(name, p->rpath, buf, sizeof buf);
1115                 }
1116                 if (fd == -1) {
1117                         if (!sys_path) {
1118                                 char *prefix = 0;
1119                                 size_t prefix_len;
1120                                 if (ldso.name[0]=='/') {
1121                                         char *s, *t, *z;
1122                                         for (s=t=z=ldso.name; *s; s++)
1123                                                 if (*s=='/') z=t, t=s;
1124                                         prefix_len = z-ldso.name;
1125                                         if (prefix_len < PATH_MAX)
1126                                                 prefix = ldso.name;
1127                                 }
1128                                 if (!prefix) {
1129                                         prefix = "";
1130                                         prefix_len = 0;
1131                                 }
1132                                 char etc_ldso_path[prefix_len + 1
1133                                         + sizeof "/etc/ld-musl-" LDSO_ARCH ".path"];
1134                                 snprintf(etc_ldso_path, sizeof etc_ldso_path,
1135                                         "%.*s/etc/ld-musl-" LDSO_ARCH ".path",
1136                                         (int)prefix_len, prefix);
1137                                 fd = open(etc_ldso_path, O_RDONLY|O_CLOEXEC);
1138                                 if (fd>=0) {
1139                                         size_t n = 0;
1140                                         if (!fstat(fd, &st)) n = st.st_size;
1141                                         if ((sys_path = malloc(n+1)))
1142                                                 sys_path[n] = 0;
1143                                         if (!sys_path || read_loop(fd, sys_path, n)<0) {
1144                                                 free(sys_path);
1145                                                 sys_path = "";
1146                                         }
1147                                         close(fd);
1148                                 } else if (errno != ENOENT) {
1149                                         sys_path = "";
1150                                 }
1151                         }
1152                         if (!sys_path) sys_path = "/lib:/usr/local/lib:/usr/lib";
1153                         fd = path_open(name, sys_path, buf, sizeof buf);
1154                 }
1155                 pathname = buf;
1156         }
1157         if (fd < 0) return 0;
1158         if (fstat(fd, &st) < 0) {
1159                 close(fd);
1160                 return 0;
1161         }
1162         for (p=head->next; p; p=p->next) {
1163                 if (p->dev == st.st_dev && p->ino == st.st_ino) {
1164                         /* If this library was previously loaded with a
1165                          * pathname but a search found the same inode,
1166                          * setup its shortname so it can be found by name. */
1167                         if (!p->shortname && pathname != name)
1168                                 p->shortname = strrchr(p->name, '/')+1;
1169                         close(fd);
1170                         return p;
1171                 }
1172         }
1173         map = noload ? 0 : map_library(fd, &temp_dso);
1174         close(fd);
1175         if (!map) return 0;
1176
1177         /* Avoid the danger of getting two versions of libc mapped into the
1178          * same process when an absolute pathname was used. The symbols
1179          * checked are chosen to catch both musl and glibc, and to avoid
1180          * false positives from interposition-hack libraries. */
1181         decode_dyn(&temp_dso);
1182         if (find_sym(&temp_dso, "__libc_start_main", 1).sym &&
1183             find_sym(&temp_dso, "stdin", 1).sym) {
1184                 unmap_library(&temp_dso);
1185                 return load_library("libc.so", needed_by);
1186         }
1187         /* Past this point, if we haven't reached runtime yet, ldso has
1188          * committed either to use the mapped library or to abort execution.
1189          * Unmapping is not possible, so we can safely reclaim gaps. */
1190         if (!runtime) reclaim_gaps(&temp_dso);
1191
1192         /* Allocate storage for the new DSO. When there is TLS, this
1193          * storage must include a reservation for all pre-existing
1194          * threads to obtain copies of both the new TLS, and an
1195          * extended DTV capable of storing an additional slot for
1196          * the newly-loaded DSO. */
1197         alloc_size = sizeof *p + strlen(pathname) + 1;
1198         if (runtime && temp_dso.tls.image) {
1199                 size_t per_th = temp_dso.tls.size + temp_dso.tls.align
1200                         + sizeof(void *) * (tls_cnt+3);
1201                 n_th = libc.threads_minus_1 + 1;
1202                 if (n_th > SSIZE_MAX / per_th) alloc_size = SIZE_MAX;
1203                 else alloc_size += n_th * per_th;
1204         }
1205         p = calloc(1, alloc_size);
1206         if (!p) {
1207                 unmap_library(&temp_dso);
1208                 return 0;
1209         }
1210         memcpy(p, &temp_dso, sizeof temp_dso);
1211         p->dev = st.st_dev;
1212         p->ino = st.st_ino;
1213         p->needed_by = needed_by;
1214         p->name = p->buf;
1215         p->runtime_loaded = runtime;
1216         strcpy(p->name, pathname);
1217         /* Add a shortname only if name arg was not an explicit pathname. */
1218         if (pathname != name) p->shortname = strrchr(p->name, '/')+1;
1219         if (p->tls.image) {
1220                 p->tls_id = ++tls_cnt;
1221                 tls_align = MAXP2(tls_align, p->tls.align);
1222 #ifdef TLS_ABOVE_TP
1223                 p->tls.offset = tls_offset + ( (p->tls.align-1) &
1224                         (-tls_offset + (uintptr_t)p->tls.image) );
1225                 tls_offset = p->tls.offset + p->tls.size;
1226 #else
1227                 tls_offset += p->tls.size + p->tls.align - 1;
1228                 tls_offset -= (tls_offset + (uintptr_t)p->tls.image)
1229                         & (p->tls.align-1);
1230                 p->tls.offset = tls_offset;
1231 #endif
1232                 p->new_dtv = (void *)(-sizeof(size_t) &
1233                         (uintptr_t)(p->name+strlen(p->name)+sizeof(size_t)));
1234                 p->new_tls = (void *)(p->new_dtv + n_th*(tls_cnt+1));
1235                 if (tls_tail) tls_tail->next = &p->tls;
1236                 else libc.tls_head = &p->tls;
1237                 tls_tail = &p->tls;
1238         }
1239
1240         tail->next = p;
1241         p->prev = tail;
1242         tail = p;
1243
1244         if (DL_FDPIC) makefuncdescs(p);
1245
1246         if (ldd_mode) dprintf(1, "\t%s => %s (%p)\n", name, pathname, p->base);
1247
1248         return p;
1249 }
1250
1251 static void load_direct_deps(struct dso *p)
1252 {
1253         size_t i, cnt=0;
1254
1255         if (p->deps) return;
1256         /* For head, all preloads are direct pseudo-dependencies.
1257          * Count and include them now to avoid realloc later. */
1258         if (p==head) for (struct dso *q=p->next; q; q=q->next)
1259                 cnt++;
1260         for (i=0; p->dynv[i]; i+=2)
1261                 if (p->dynv[i] == DT_NEEDED) cnt++;
1262         /* Use builtin buffer for apps with no external deps, to
1263          * preserve property of no runtime failure paths. */
1264         p->deps = (p==head && cnt<2) ? builtin_deps :
1265                 calloc(cnt+1, sizeof *p->deps);
1266         if (!p->deps) {
1267                 error("Error loading dependencies for %s", p->name);
1268                 if (runtime) longjmp(*rtld_fail, 1);
1269         }
1270         cnt=0;
1271         if (p==head) for (struct dso *q=p->next; q; q=q->next)
1272                 p->deps[cnt++] = q;
1273         for (i=0; p->dynv[i]; i+=2) {
1274                 if (p->dynv[i] != DT_NEEDED) continue;
1275                 struct dso *dep = load_library(p->strings + p->dynv[i+1], p);
1276                 if (!dep) {
1277                         error("Error loading shared library %s: %m (needed by %s)",
1278                                 p->strings + p->dynv[i+1], p->name);
1279                         if (runtime) longjmp(*rtld_fail, 1);
1280                         continue;
1281                 }
1282                 p->deps[cnt++] = dep;
1283         }
1284         p->deps[cnt] = 0;
1285         p->ndeps_direct = cnt;
1286 }
1287
1288 static void load_deps(struct dso *p)
1289 {
1290         if (p->deps) return;
1291         for (; p; p=p->next)
1292                 load_direct_deps(p);
1293 }
1294
1295 static void extend_bfs_deps(struct dso *p)
1296 {
1297         size_t i, j, cnt, ndeps_all;
1298         struct dso **tmp;
1299
1300         /* Can't use realloc if the original p->deps was allocated at
1301          * program entry and malloc has been replaced, or if it's
1302          * the builtin non-allocated trivial main program deps array. */
1303         int no_realloc = (__malloc_replaced && !p->runtime_loaded)
1304                 || p->deps == builtin_deps;
1305
1306         if (p->bfs_built) return;
1307         ndeps_all = p->ndeps_direct;
1308
1309         /* Mark existing (direct) deps so they won't be duplicated. */
1310         for (i=0; p->deps[i]; i++)
1311                 p->deps[i]->mark = 1;
1312
1313         /* For each dependency already in the list, copy its list of direct
1314          * dependencies to the list, excluding any items already in the
1315          * list. Note that the list this loop iterates over will grow during
1316          * the loop, but since duplicates are excluded, growth is bounded. */
1317         for (i=0; p->deps[i]; i++) {
1318                 struct dso *dep = p->deps[i];
1319                 for (j=cnt=0; j<dep->ndeps_direct; j++)
1320                         if (!dep->deps[j]->mark) cnt++;
1321                 tmp = no_realloc ? 
1322                         malloc(sizeof(*tmp) * (ndeps_all+cnt+1)) :
1323                         realloc(p->deps, sizeof(*tmp) * (ndeps_all+cnt+1));
1324                 if (!tmp) {
1325                         error("Error recording dependencies for %s", p->name);
1326                         if (runtime) longjmp(*rtld_fail, 1);
1327                         continue;
1328                 }
1329                 if (no_realloc) {
1330                         memcpy(tmp, p->deps, sizeof(*tmp) * (ndeps_all+1));
1331                         no_realloc = 0;
1332                 }
1333                 p->deps = tmp;
1334                 for (j=0; j<dep->ndeps_direct; j++) {
1335                         if (dep->deps[j]->mark) continue;
1336                         dep->deps[j]->mark = 1;
1337                         p->deps[ndeps_all++] = dep->deps[j];
1338                 }
1339                 p->deps[ndeps_all] = 0;
1340         }
1341         p->bfs_built = 1;
1342         for (p=head; p; p=p->next)
1343                 p->mark = 0;
1344 }
1345
1346 static void load_preload(char *s)
1347 {
1348         int tmp;
1349         char *z;
1350         for (z=s; *z; s=z) {
1351                 for (   ; *s && (isspace(*s) || *s==':'); s++);
1352                 for (z=s; *z && !isspace(*z) && *z!=':'; z++);
1353                 tmp = *z;
1354                 *z = 0;
1355                 load_library(s, 0);
1356                 *z = tmp;
1357         }
1358 }
1359
1360 static void add_syms(struct dso *p)
1361 {
1362         if (!p->syms_next && syms_tail != p) {
1363                 syms_tail->syms_next = p;
1364                 syms_tail = p;
1365         }
1366 }
1367
1368 static void revert_syms(struct dso *old_tail)
1369 {
1370         struct dso *p, *next;
1371         /* Chop off the tail of the list of dsos that participate in
1372          * the global symbol table, reverting them to RTLD_LOCAL. */
1373         for (p=old_tail; p; p=next) {
1374                 next = p->syms_next;
1375                 p->syms_next = 0;
1376         }
1377         syms_tail = old_tail;
1378 }
1379
1380 static void do_mips_relocs(struct dso *p, size_t *got)
1381 {
1382         size_t i, j, rel[2];
1383         unsigned char *base = p->base;
1384         i=0; search_vec(p->dynv, &i, DT_MIPS_LOCAL_GOTNO);
1385         if (p==&ldso) {
1386                 got += i;
1387         } else {
1388                 while (i--) *got++ += (size_t)base;
1389         }
1390         j=0; search_vec(p->dynv, &j, DT_MIPS_GOTSYM);
1391         i=0; search_vec(p->dynv, &i, DT_MIPS_SYMTABNO);
1392         Sym *sym = p->syms + j;
1393         rel[0] = (unsigned char *)got - base;
1394         for (i-=j; i; i--, sym++, rel[0]+=sizeof(size_t)) {
1395                 rel[1] = R_INFO(sym-p->syms, R_MIPS_JUMP_SLOT);
1396                 do_relocs(p, rel, sizeof rel, 2);
1397         }
1398 }
1399
1400 static void reloc_all(struct dso *p)
1401 {
1402         size_t dyn[DYN_CNT];
1403         for (; p; p=p->next) {
1404                 if (p->relocated) continue;
1405                 decode_vec(p->dynv, dyn, DYN_CNT);
1406                 if (NEED_MIPS_GOT_RELOCS)
1407                         do_mips_relocs(p, laddr(p, dyn[DT_PLTGOT]));
1408                 do_relocs(p, laddr(p, dyn[DT_JMPREL]), dyn[DT_PLTRELSZ],
1409                         2+(dyn[DT_PLTREL]==DT_RELA));
1410                 do_relocs(p, laddr(p, dyn[DT_REL]), dyn[DT_RELSZ], 2);
1411                 do_relocs(p, laddr(p, dyn[DT_RELA]), dyn[DT_RELASZ], 3);
1412                 if (!DL_FDPIC)
1413                         do_relr_relocs(p, laddr(p, dyn[DT_RELR]), dyn[DT_RELRSZ]);
1414
1415                 if (head != &ldso && p->relro_start != p->relro_end) {
1416                         long ret = __syscall(SYS_mprotect, laddr(p, p->relro_start),
1417                                 p->relro_end-p->relro_start, PROT_READ);
1418                         if (ret != 0 && ret != -ENOSYS) {
1419                                 error("Error relocating %s: RELRO protection failed: %m",
1420                                         p->name);
1421                                 if (runtime) longjmp(*rtld_fail, 1);
1422                         }
1423                 }
1424
1425                 p->relocated = 1;
1426         }
1427 }
1428
1429 static void kernel_mapped_dso(struct dso *p)
1430 {
1431         size_t min_addr = -1, max_addr = 0, cnt;
1432         Phdr *ph = p->phdr;
1433         for (cnt = p->phnum; cnt--; ph = (void *)((char *)ph + p->phentsize)) {
1434                 if (ph->p_type == PT_DYNAMIC) {
1435                         p->dynv = laddr(p, ph->p_vaddr);
1436                 } else if (ph->p_type == PT_GNU_RELRO) {
1437                         p->relro_start = ph->p_vaddr & -PAGE_SIZE;
1438                         p->relro_end = (ph->p_vaddr + ph->p_memsz) & -PAGE_SIZE;
1439                 } else if (ph->p_type == PT_GNU_STACK) {
1440                         if (!runtime && ph->p_memsz > __default_stacksize) {
1441                                 __default_stacksize =
1442                                         ph->p_memsz < DEFAULT_STACK_MAX ?
1443                                         ph->p_memsz : DEFAULT_STACK_MAX;
1444                         }
1445                 }
1446                 if (ph->p_type != PT_LOAD) continue;
1447                 if (ph->p_vaddr < min_addr)
1448                         min_addr = ph->p_vaddr;
1449                 if (ph->p_vaddr+ph->p_memsz > max_addr)
1450                         max_addr = ph->p_vaddr+ph->p_memsz;
1451         }
1452         min_addr &= -PAGE_SIZE;
1453         max_addr = (max_addr + PAGE_SIZE-1) & -PAGE_SIZE;
1454         p->map = p->base + min_addr;
1455         p->map_len = max_addr - min_addr;
1456         p->kernel_mapped = 1;
1457 }
1458
1459 void __libc_exit_fini()
1460 {
1461         struct dso *p;
1462         size_t dyn[DYN_CNT];
1463         pthread_t self = __pthread_self();
1464
1465         /* Take both locks before setting shutting_down, so that
1466          * either lock is sufficient to read its value. The lock
1467          * order matches that in dlopen to avoid deadlock. */
1468         pthread_rwlock_wrlock(&lock);
1469         pthread_mutex_lock(&init_fini_lock);
1470         shutting_down = 1;
1471         pthread_rwlock_unlock(&lock);
1472         for (p=fini_head; p; p=p->fini_next) {
1473                 while (p->ctor_visitor && p->ctor_visitor!=self)
1474                         pthread_cond_wait(&ctor_cond, &init_fini_lock);
1475                 if (!p->constructed) continue;
1476                 decode_vec(p->dynv, dyn, DYN_CNT);
1477                 if (dyn[0] & (1<<DT_FINI_ARRAY)) {
1478                         size_t n = dyn[DT_FINI_ARRAYSZ]/sizeof(size_t);
1479                         size_t *fn = (size_t *)laddr(p, dyn[DT_FINI_ARRAY])+n;
1480                         while (n--) ((void (*)(void))*--fn)();
1481                 }
1482 #ifndef NO_LEGACY_INITFINI
1483                 if ((dyn[0] & (1<<DT_FINI)) && dyn[DT_FINI])
1484                         fpaddr(p, dyn[DT_FINI])();
1485 #endif
1486         }
1487 }
1488
1489 void __ldso_atfork(int who)
1490 {
1491         if (who<0) {
1492                 pthread_rwlock_wrlock(&lock);
1493                 pthread_mutex_lock(&init_fini_lock);
1494         } else {
1495                 pthread_mutex_unlock(&init_fini_lock);
1496                 pthread_rwlock_unlock(&lock);
1497         }
1498 }
1499
1500 static struct dso **queue_ctors(struct dso *dso)
1501 {
1502         size_t cnt, qpos, spos, i;
1503         struct dso *p, **queue, **stack;
1504
1505         if (ldd_mode) return 0;
1506
1507         /* Bound on queue size is the total number of indirect deps.
1508          * If a bfs deps list was built, we can use it. Otherwise,
1509          * bound by the total number of DSOs, which is always safe and
1510          * is reasonable we use it (for main app at startup). */
1511         if (dso->bfs_built) {
1512                 for (cnt=0; dso->deps[cnt]; cnt++)
1513                         dso->deps[cnt]->mark = 0;
1514                 cnt++; /* self, not included in deps */
1515         } else {
1516                 for (cnt=0, p=head; p; cnt++, p=p->next)
1517                         p->mark = 0;
1518         }
1519         cnt++; /* termination slot */
1520         if (dso==head && cnt <= countof(builtin_ctor_queue))
1521                 queue = builtin_ctor_queue;
1522         else
1523                 queue = calloc(cnt, sizeof *queue);
1524
1525         if (!queue) {
1526                 error("Error allocating constructor queue: %m\n");
1527                 if (runtime) longjmp(*rtld_fail, 1);
1528                 return 0;
1529         }
1530
1531         /* Opposite ends of the allocated buffer serve as an output queue
1532          * and a working stack. Setup initial stack with just the argument
1533          * dso and initial queue empty... */
1534         stack = queue;
1535         qpos = 0;
1536         spos = cnt;
1537         stack[--spos] = dso;
1538         dso->next_dep = 0;
1539         dso->mark = 1;
1540
1541         /* Then perform pseudo-DFS sort, but ignoring circular deps. */
1542         while (spos<cnt) {
1543                 p = stack[spos++];
1544                 while (p->next_dep < p->ndeps_direct) {
1545                         if (p->deps[p->next_dep]->mark) {
1546                                 p->next_dep++;
1547                         } else {
1548                                 stack[--spos] = p;
1549                                 p = p->deps[p->next_dep];
1550                                 p->next_dep = 0;
1551                                 p->mark = 1;
1552                         }
1553                 }
1554                 queue[qpos++] = p;
1555         }
1556         queue[qpos] = 0;
1557         for (i=0; i<qpos; i++) queue[i]->mark = 0;
1558         for (i=0; i<qpos; i++)
1559                 if (queue[i]->ctor_visitor && queue[i]->ctor_visitor->tid < 0) {
1560                         error("State of %s is inconsistent due to multithreaded fork\n",
1561                                 queue[i]->name);
1562                         free(queue);
1563                         if (runtime) longjmp(*rtld_fail, 1);
1564                 }
1565
1566         return queue;
1567 }
1568
1569 static void do_init_fini(struct dso **queue)
1570 {
1571         struct dso *p;
1572         size_t dyn[DYN_CNT], i;
1573         pthread_t self = __pthread_self();
1574
1575         pthread_mutex_lock(&init_fini_lock);
1576         for (i=0; (p=queue[i]); i++) {
1577                 while ((p->ctor_visitor && p->ctor_visitor!=self) || shutting_down)
1578                         pthread_cond_wait(&ctor_cond, &init_fini_lock);
1579                 if (p->ctor_visitor || p->constructed)
1580                         continue;
1581                 p->ctor_visitor = self;
1582                 
1583                 decode_vec(p->dynv, dyn, DYN_CNT);
1584                 if (dyn[0] & ((1<<DT_FINI) | (1<<DT_FINI_ARRAY))) {
1585                         p->fini_next = fini_head;
1586                         fini_head = p;
1587                 }
1588
1589                 pthread_mutex_unlock(&init_fini_lock);
1590
1591 #ifndef NO_LEGACY_INITFINI
1592                 if ((dyn[0] & (1<<DT_INIT)) && dyn[DT_INIT])
1593                         fpaddr(p, dyn[DT_INIT])();
1594 #endif
1595                 if (dyn[0] & (1<<DT_INIT_ARRAY)) {
1596                         size_t n = dyn[DT_INIT_ARRAYSZ]/sizeof(size_t);
1597                         size_t *fn = laddr(p, dyn[DT_INIT_ARRAY]);
1598                         while (n--) ((void (*)(void))*fn++)();
1599                 }
1600
1601                 pthread_mutex_lock(&init_fini_lock);
1602                 p->ctor_visitor = 0;
1603                 p->constructed = 1;
1604                 pthread_cond_broadcast(&ctor_cond);
1605         }
1606         pthread_mutex_unlock(&init_fini_lock);
1607 }
1608
1609 void __libc_start_init(void)
1610 {
1611         do_init_fini(main_ctor_queue);
1612         if (!__malloc_replaced && main_ctor_queue != builtin_ctor_queue)
1613                 free(main_ctor_queue);
1614         main_ctor_queue = 0;
1615 }
1616
1617 static void dl_debug_state(void)
1618 {
1619 }
1620
1621 weak_alias(dl_debug_state, _dl_debug_state);
1622
1623 void __init_tls(size_t *auxv)
1624 {
1625 }
1626
1627 static void update_tls_size()
1628 {
1629         libc.tls_cnt = tls_cnt;
1630         libc.tls_align = tls_align;
1631         libc.tls_size = ALIGN(
1632                 (1+tls_cnt) * sizeof(void *) +
1633                 tls_offset +
1634                 sizeof(struct pthread) +
1635                 tls_align * 2,
1636         tls_align);
1637 }
1638
1639 static void install_new_tls(void)
1640 {
1641         sigset_t set;
1642         pthread_t self = __pthread_self(), td;
1643         struct dso *dtv_provider = container_of(tls_tail, struct dso, tls);
1644         uintptr_t (*newdtv)[tls_cnt+1] = (void *)dtv_provider->new_dtv;
1645         struct dso *p;
1646         size_t i, j;
1647         size_t old_cnt = self->dtv[0];
1648
1649         __block_app_sigs(&set);
1650         __tl_lock();
1651         /* Copy existing dtv contents from all existing threads. */
1652         for (i=0, td=self; !i || td!=self; i++, td=td->next) {
1653                 memcpy(newdtv+i, td->dtv,
1654                         (old_cnt+1)*sizeof(uintptr_t));
1655                 newdtv[i][0] = tls_cnt;
1656         }
1657         /* Install new dtls into the enlarged, uninstalled dtv copies. */
1658         for (p=head; ; p=p->next) {
1659                 if (p->tls_id <= old_cnt) continue;
1660                 unsigned char *mem = p->new_tls;
1661                 for (j=0; j<i; j++) {
1662                         unsigned char *new = mem;
1663                         new += ((uintptr_t)p->tls.image - (uintptr_t)mem)
1664                                 & (p->tls.align-1);
1665                         memcpy(new, p->tls.image, p->tls.len);
1666                         newdtv[j][p->tls_id] =
1667                                 (uintptr_t)new + DTP_OFFSET;
1668                         mem += p->tls.size + p->tls.align;
1669                 }
1670                 if (p->tls_id == tls_cnt) break;
1671         }
1672
1673         /* Broadcast barrier to ensure contents of new dtv is visible
1674          * if the new dtv pointer is. The __membarrier function has a
1675          * fallback emulation using signals for kernels that lack the
1676          * feature at the syscall level. */
1677
1678         __membarrier(MEMBARRIER_CMD_PRIVATE_EXPEDITED, 0);
1679
1680         /* Install new dtv for each thread. */
1681         for (j=0, td=self; !j || td!=self; j++, td=td->next) {
1682                 td->dtv = newdtv[j];
1683         }
1684
1685         __tl_unlock();
1686         __restore_sigs(&set);
1687 }
1688
1689 /* Stage 1 of the dynamic linker is defined in dlstart.c. It calls the
1690  * following stage 2 and stage 3 functions via primitive symbolic lookup
1691  * since it does not have access to their addresses to begin with. */
1692
1693 /* Stage 2 of the dynamic linker is called after relative relocations 
1694  * have been processed. It can make function calls to static functions
1695  * and access string literals and static data, but cannot use extern
1696  * symbols. Its job is to perform symbolic relocations on the dynamic
1697  * linker itself, but some of the relocations performed may need to be
1698  * replaced later due to copy relocations in the main program. */
1699
1700 hidden void __dls2(unsigned char *base, size_t *sp)
1701 {
1702         size_t *auxv;
1703         for (auxv=sp+1+*sp+1; *auxv; auxv++);
1704         auxv++;
1705         if (DL_FDPIC) {
1706                 void *p1 = (void *)sp[-2];
1707                 void *p2 = (void *)sp[-1];
1708                 if (!p1) {
1709                         size_t aux[AUX_CNT];
1710                         decode_vec(auxv, aux, AUX_CNT);
1711                         if (aux[AT_BASE]) ldso.base = (void *)aux[AT_BASE];
1712                         else ldso.base = (void *)(aux[AT_PHDR] & -4096);
1713                 }
1714                 app_loadmap = p2 ? p1 : 0;
1715                 ldso.loadmap = p2 ? p2 : p1;
1716                 ldso.base = laddr(&ldso, 0);
1717         } else {
1718                 ldso.base = base;
1719         }
1720         Ehdr *ehdr = (void *)ldso.base;
1721         ldso.name = ldso.shortname = "libc.so";
1722         ldso.phnum = ehdr->e_phnum;
1723         ldso.phdr = laddr(&ldso, ehdr->e_phoff);
1724         ldso.phentsize = ehdr->e_phentsize;
1725         kernel_mapped_dso(&ldso);
1726         decode_dyn(&ldso);
1727
1728         if (DL_FDPIC) makefuncdescs(&ldso);
1729
1730         /* Prepare storage for to save clobbered REL addends so they
1731          * can be reused in stage 3. There should be very few. If
1732          * something goes wrong and there are a huge number, abort
1733          * instead of risking stack overflow. */
1734         size_t dyn[DYN_CNT];
1735         decode_vec(ldso.dynv, dyn, DYN_CNT);
1736         size_t *rel = laddr(&ldso, dyn[DT_REL]);
1737         size_t rel_size = dyn[DT_RELSZ];
1738         size_t symbolic_rel_cnt = 0;
1739         apply_addends_to = rel;
1740         for (; rel_size; rel+=2, rel_size-=2*sizeof(size_t))
1741                 if (!IS_RELATIVE(rel[1], ldso.syms)) symbolic_rel_cnt++;
1742         if (symbolic_rel_cnt >= ADDEND_LIMIT) a_crash();
1743         size_t addends[symbolic_rel_cnt+1];
1744         saved_addends = addends;
1745
1746         head = &ldso;
1747         reloc_all(&ldso);
1748
1749         ldso.relocated = 0;
1750
1751         /* Call dynamic linker stage-2b, __dls2b, looking it up
1752          * symbolically as a barrier against moving the address
1753          * load across the above relocation processing. */
1754         struct symdef dls2b_def = find_sym(&ldso, "__dls2b", 0);
1755         if (DL_FDPIC) ((stage3_func)&ldso.funcdescs[dls2b_def.sym-ldso.syms])(sp, auxv);
1756         else ((stage3_func)laddr(&ldso, dls2b_def.sym->st_value))(sp, auxv);
1757 }
1758
1759 /* Stage 2b sets up a valid thread pointer, which requires relocations
1760  * completed in stage 2, and on which stage 3 is permitted to depend.
1761  * This is done as a separate stage, with symbolic lookup as a barrier,
1762  * so that loads of the thread pointer and &errno can be pure/const and
1763  * thereby hoistable. */
1764
1765 void __dls2b(size_t *sp, size_t *auxv)
1766 {
1767         /* Setup early thread pointer in builtin_tls for ldso/libc itself to
1768          * use during dynamic linking. If possible it will also serve as the
1769          * thread pointer at runtime. */
1770         search_vec(auxv, &__hwcap, AT_HWCAP);
1771         libc.auxv = auxv;
1772         libc.tls_size = sizeof builtin_tls;
1773         libc.tls_align = tls_align;
1774         if (__init_tp(__copy_tls((void *)builtin_tls)) < 0) {
1775                 a_crash();
1776         }
1777
1778         struct symdef dls3_def = find_sym(&ldso, "__dls3", 0);
1779         if (DL_FDPIC) ((stage3_func)&ldso.funcdescs[dls3_def.sym-ldso.syms])(sp, auxv);
1780         else ((stage3_func)laddr(&ldso, dls3_def.sym->st_value))(sp, auxv);
1781 }
1782
1783 /* Stage 3 of the dynamic linker is called with the dynamic linker/libc
1784  * fully functional. Its job is to load (if not already loaded) and
1785  * process dependencies and relocations for the main application and
1786  * transfer control to its entry point. */
1787
1788 void __dls3(size_t *sp, size_t *auxv)
1789 {
1790         static struct dso app, vdso;
1791         size_t aux[AUX_CNT];
1792         size_t i;
1793         char *env_preload=0;
1794         char *replace_argv0=0;
1795         size_t vdso_base;
1796         int argc = *sp;
1797         char **argv = (void *)(sp+1);
1798         char **argv_orig = argv;
1799         char **envp = argv+argc+1;
1800
1801         /* Find aux vector just past environ[] and use it to initialize
1802          * global data that may be needed before we can make syscalls. */
1803         __environ = envp;
1804         decode_vec(auxv, aux, AUX_CNT);
1805         search_vec(auxv, &__sysinfo, AT_SYSINFO);
1806         __pthread_self()->sysinfo = __sysinfo;
1807         libc.page_size = aux[AT_PAGESZ];
1808         libc.secure = ((aux[0]&0x7800)!=0x7800 || aux[AT_UID]!=aux[AT_EUID]
1809                 || aux[AT_GID]!=aux[AT_EGID] || aux[AT_SECURE]);
1810
1811         /* Only trust user/env if kernel says we're not suid/sgid */
1812         if (!libc.secure) {
1813                 env_path = getenv("LD_LIBRARY_PATH");
1814                 env_preload = getenv("LD_PRELOAD");
1815         }
1816
1817         /* Activate error handler function */
1818         error = error_impl;
1819
1820         /* If the main program was already loaded by the kernel,
1821          * AT_PHDR will point to some location other than the dynamic
1822          * linker's program headers. */
1823         if (aux[AT_PHDR] != (size_t)ldso.phdr) {
1824                 size_t interp_off = 0;
1825                 size_t tls_image = 0;
1826                 /* Find load address of the main program, via AT_PHDR vs PT_PHDR. */
1827                 Phdr *phdr = app.phdr = (void *)aux[AT_PHDR];
1828                 app.phnum = aux[AT_PHNUM];
1829                 app.phentsize = aux[AT_PHENT];
1830                 for (i=aux[AT_PHNUM]; i; i--, phdr=(void *)((char *)phdr + aux[AT_PHENT])) {
1831                         if (phdr->p_type == PT_PHDR)
1832                                 app.base = (void *)(aux[AT_PHDR] - phdr->p_vaddr);
1833                         else if (phdr->p_type == PT_INTERP)
1834                                 interp_off = (size_t)phdr->p_vaddr;
1835                         else if (phdr->p_type == PT_TLS) {
1836                                 tls_image = phdr->p_vaddr;
1837                                 app.tls.len = phdr->p_filesz;
1838                                 app.tls.size = phdr->p_memsz;
1839                                 app.tls.align = phdr->p_align;
1840                         }
1841                 }
1842                 if (DL_FDPIC) app.loadmap = app_loadmap;
1843                 if (app.tls.size) app.tls.image = laddr(&app, tls_image);
1844                 if (interp_off) ldso.name = laddr(&app, interp_off);
1845                 if ((aux[0] & (1UL<<AT_EXECFN))
1846                     && strncmp((char *)aux[AT_EXECFN], "/proc/", 6))
1847                         app.name = (char *)aux[AT_EXECFN];
1848                 else
1849                         app.name = argv[0];
1850                 kernel_mapped_dso(&app);
1851         } else {
1852                 int fd;
1853                 char *ldname = argv[0];
1854                 size_t l = strlen(ldname);
1855                 if (l >= 3 && !strcmp(ldname+l-3, "ldd")) ldd_mode = 1;
1856                 argv++;
1857                 while (argv[0] && argv[0][0]=='-' && argv[0][1]=='-') {
1858                         char *opt = argv[0]+2;
1859                         *argv++ = (void *)-1;
1860                         if (!*opt) {
1861                                 break;
1862                         } else if (!memcmp(opt, "list", 5)) {
1863                                 ldd_mode = 1;
1864                         } else if (!memcmp(opt, "library-path", 12)) {
1865                                 if (opt[12]=='=') env_path = opt+13;
1866                                 else if (opt[12]) *argv = 0;
1867                                 else if (*argv) env_path = *argv++;
1868                         } else if (!memcmp(opt, "preload", 7)) {
1869                                 if (opt[7]=='=') env_preload = opt+8;
1870                                 else if (opt[7]) *argv = 0;
1871                                 else if (*argv) env_preload = *argv++;
1872                         } else if (!memcmp(opt, "argv0", 5)) {
1873                                 if (opt[5]=='=') replace_argv0 = opt+6;
1874                                 else if (opt[5]) *argv = 0;
1875                                 else if (*argv) replace_argv0 = *argv++;
1876                         } else {
1877                                 argv[0] = 0;
1878                         }
1879                 }
1880                 argv[-1] = (void *)(argc - (argv-argv_orig));
1881                 if (!argv[0]) {
1882                         dprintf(2, "musl libc (" LDSO_ARCH ")\n"
1883                                 "Version %s\n"
1884                                 "Dynamic Program Loader\n"
1885                                 "Usage: %s [options] [--] pathname%s\n",
1886                                 __libc_version, ldname,
1887                                 ldd_mode ? "" : " [args]");
1888                         _exit(1);
1889                 }
1890                 fd = open(argv[0], O_RDONLY);
1891                 if (fd < 0) {
1892                         dprintf(2, "%s: cannot load %s: %s\n", ldname, argv[0], strerror(errno));
1893                         _exit(1);
1894                 }
1895                 Ehdr *ehdr = map_library(fd, &app);
1896                 if (!ehdr) {
1897                         dprintf(2, "%s: %s: Not a valid dynamic program\n", ldname, argv[0]);
1898                         _exit(1);
1899                 }
1900                 close(fd);
1901                 ldso.name = ldname;
1902                 app.name = argv[0];
1903                 aux[AT_ENTRY] = (size_t)laddr(&app, ehdr->e_entry);
1904                 /* Find the name that would have been used for the dynamic
1905                  * linker had ldd not taken its place. */
1906                 if (ldd_mode) {
1907                         for (i=0; i<app.phnum; i++) {
1908                                 if (app.phdr[i].p_type == PT_INTERP)
1909                                         ldso.name = laddr(&app, app.phdr[i].p_vaddr);
1910                         }
1911                         dprintf(1, "\t%s (%p)\n", ldso.name, ldso.base);
1912                 }
1913         }
1914         if (app.tls.size) {
1915                 libc.tls_head = tls_tail = &app.tls;
1916                 app.tls_id = tls_cnt = 1;
1917 #ifdef TLS_ABOVE_TP
1918                 app.tls.offset = GAP_ABOVE_TP;
1919                 app.tls.offset += (-GAP_ABOVE_TP + (uintptr_t)app.tls.image)
1920                         & (app.tls.align-1);
1921                 tls_offset = app.tls.offset + app.tls.size;
1922 #else
1923                 tls_offset = app.tls.offset = app.tls.size
1924                         + ( -((uintptr_t)app.tls.image + app.tls.size)
1925                         & (app.tls.align-1) );
1926 #endif
1927                 tls_align = MAXP2(tls_align, app.tls.align);
1928         }
1929         decode_dyn(&app);
1930         if (DL_FDPIC) {
1931                 makefuncdescs(&app);
1932                 if (!app.loadmap) {
1933                         app.loadmap = (void *)&app_dummy_loadmap;
1934                         app.loadmap->nsegs = 1;
1935                         app.loadmap->segs[0].addr = (size_t)app.map;
1936                         app.loadmap->segs[0].p_vaddr = (size_t)app.map
1937                                 - (size_t)app.base;
1938                         app.loadmap->segs[0].p_memsz = app.map_len;
1939                 }
1940                 argv[-3] = (void *)app.loadmap;
1941         }
1942
1943         /* Initial dso chain consists only of the app. */
1944         head = tail = syms_tail = &app;
1945
1946         /* Donate unused parts of app and library mapping to malloc */
1947         reclaim_gaps(&app);
1948         reclaim_gaps(&ldso);
1949
1950         /* Load preload/needed libraries, add symbols to global namespace. */
1951         ldso.deps = (struct dso **)no_deps;
1952         if (env_preload) load_preload(env_preload);
1953         load_deps(&app);
1954         for (struct dso *p=head; p; p=p->next)
1955                 add_syms(p);
1956
1957         /* Attach to vdso, if provided by the kernel, last so that it does
1958          * not become part of the global namespace.  */
1959         if (search_vec(auxv, &vdso_base, AT_SYSINFO_EHDR) && vdso_base) {
1960                 Ehdr *ehdr = (void *)vdso_base;
1961                 Phdr *phdr = vdso.phdr = (void *)(vdso_base + ehdr->e_phoff);
1962                 vdso.phnum = ehdr->e_phnum;
1963                 vdso.phentsize = ehdr->e_phentsize;
1964                 for (i=ehdr->e_phnum; i; i--, phdr=(void *)((char *)phdr + ehdr->e_phentsize)) {
1965                         if (phdr->p_type == PT_DYNAMIC)
1966                                 vdso.dynv = (void *)(vdso_base + phdr->p_offset);
1967                         if (phdr->p_type == PT_LOAD)
1968                                 vdso.base = (void *)(vdso_base - phdr->p_vaddr + phdr->p_offset);
1969                 }
1970                 vdso.name = "";
1971                 vdso.shortname = "linux-gate.so.1";
1972                 vdso.relocated = 1;
1973                 vdso.deps = (struct dso **)no_deps;
1974                 decode_dyn(&vdso);
1975                 vdso.prev = tail;
1976                 tail->next = &vdso;
1977                 tail = &vdso;
1978         }
1979
1980         for (i=0; app.dynv[i]; i+=2) {
1981                 if (!DT_DEBUG_INDIRECT && app.dynv[i]==DT_DEBUG)
1982                         app.dynv[i+1] = (size_t)&debug;
1983                 if (DT_DEBUG_INDIRECT && app.dynv[i]==DT_DEBUG_INDIRECT) {
1984                         size_t *ptr = (size_t *) app.dynv[i+1];
1985                         *ptr = (size_t)&debug;
1986                 }
1987         }
1988
1989         /* This must be done before final relocations, since it calls
1990          * malloc, which may be provided by the application. Calling any
1991          * application code prior to the jump to its entry point is not
1992          * valid in our model and does not work with FDPIC, where there
1993          * are additional relocation-like fixups that only the entry point
1994          * code can see to perform. */
1995         main_ctor_queue = queue_ctors(&app);
1996
1997         /* Initial TLS must also be allocated before final relocations
1998          * might result in calloc being a call to application code. */
1999         update_tls_size();
2000         void *initial_tls = builtin_tls;
2001         if (libc.tls_size > sizeof builtin_tls || tls_align > MIN_TLS_ALIGN) {
2002                 initial_tls = calloc(libc.tls_size, 1);
2003                 if (!initial_tls) {
2004                         dprintf(2, "%s: Error getting %zu bytes thread-local storage: %m\n",
2005                                 argv[0], libc.tls_size);
2006                         _exit(127);
2007                 }
2008         }
2009         static_tls_cnt = tls_cnt;
2010
2011         /* The main program must be relocated LAST since it may contain
2012          * copy relocations which depend on libraries' relocations. */
2013         reloc_all(app.next);
2014         reloc_all(&app);
2015
2016         /* Actual copying to new TLS needs to happen after relocations,
2017          * since the TLS images might have contained relocated addresses. */
2018         if (initial_tls != builtin_tls) {
2019                 if (__init_tp(__copy_tls(initial_tls)) < 0) {
2020                         a_crash();
2021                 }
2022         } else {
2023                 size_t tmp_tls_size = libc.tls_size;
2024                 pthread_t self = __pthread_self();
2025                 /* Temporarily set the tls size to the full size of
2026                  * builtin_tls so that __copy_tls will use the same layout
2027                  * as it did for before. Then check, just to be safe. */
2028                 libc.tls_size = sizeof builtin_tls;
2029                 if (__copy_tls((void*)builtin_tls) != self) a_crash();
2030                 libc.tls_size = tmp_tls_size;
2031         }
2032
2033         if (ldso_fail) _exit(127);
2034         if (ldd_mode) _exit(0);
2035
2036         /* Determine if malloc was interposed by a replacement implementation
2037          * so that calloc and the memalign family can harden against the
2038          * possibility of incomplete replacement. */
2039         if (find_sym(head, "malloc", 1).dso != &ldso)
2040                 __malloc_replaced = 1;
2041         if (find_sym(head, "aligned_alloc", 1).dso != &ldso)
2042                 __aligned_alloc_replaced = 1;
2043
2044         /* Switch to runtime mode: any further failures in the dynamic
2045          * linker are a reportable failure rather than a fatal startup
2046          * error. */
2047         runtime = 1;
2048
2049         debug.ver = 1;
2050         debug.bp = dl_debug_state;
2051         debug.head = head;
2052         debug.base = ldso.base;
2053         debug.state = RT_CONSISTENT;
2054         _dl_debug_state();
2055
2056         if (replace_argv0) argv[0] = replace_argv0;
2057
2058         errno = 0;
2059
2060         CRTJMP((void *)aux[AT_ENTRY], argv-1);
2061         for(;;);
2062 }
2063
2064 static void prepare_lazy(struct dso *p)
2065 {
2066         size_t dyn[DYN_CNT], n, flags1=0;
2067         decode_vec(p->dynv, dyn, DYN_CNT);
2068         search_vec(p->dynv, &flags1, DT_FLAGS_1);
2069         if (dyn[DT_BIND_NOW] || (dyn[DT_FLAGS] & DF_BIND_NOW) || (flags1 & DF_1_NOW))
2070                 return;
2071         n = dyn[DT_RELSZ]/2 + dyn[DT_RELASZ]/3 + dyn[DT_PLTRELSZ]/2 + 1;
2072         if (NEED_MIPS_GOT_RELOCS) {
2073                 size_t j=0; search_vec(p->dynv, &j, DT_MIPS_GOTSYM);
2074                 size_t i=0; search_vec(p->dynv, &i, DT_MIPS_SYMTABNO);
2075                 n += i-j;
2076         }
2077         p->lazy = calloc(n, 3*sizeof(size_t));
2078         if (!p->lazy) {
2079                 error("Error preparing lazy relocation for %s: %m", p->name);
2080                 longjmp(*rtld_fail, 1);
2081         }
2082         p->lazy_next = lazy_head;
2083         lazy_head = p;
2084 }
2085
2086 void *dlopen(const char *file, int mode)
2087 {
2088         struct dso *volatile p, *orig_tail, *orig_syms_tail, *orig_lazy_head, *next;
2089         struct tls_module *orig_tls_tail;
2090         size_t orig_tls_cnt, orig_tls_offset, orig_tls_align;
2091         size_t i;
2092         int cs;
2093         jmp_buf jb;
2094         struct dso **volatile ctor_queue = 0;
2095
2096         if (!file) return head;
2097
2098         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
2099         pthread_rwlock_wrlock(&lock);
2100         __inhibit_ptc();
2101
2102         debug.state = RT_ADD;
2103         _dl_debug_state();
2104
2105         p = 0;
2106         if (shutting_down) {
2107                 error("Cannot dlopen while program is exiting.");
2108                 goto end;
2109         }
2110         orig_tls_tail = tls_tail;
2111         orig_tls_cnt = tls_cnt;
2112         orig_tls_offset = tls_offset;
2113         orig_tls_align = tls_align;
2114         orig_lazy_head = lazy_head;
2115         orig_syms_tail = syms_tail;
2116         orig_tail = tail;
2117         noload = mode & RTLD_NOLOAD;
2118
2119         rtld_fail = &jb;
2120         if (setjmp(*rtld_fail)) {
2121                 /* Clean up anything new that was (partially) loaded */
2122                 revert_syms(orig_syms_tail);
2123                 for (p=orig_tail->next; p; p=next) {
2124                         next = p->next;
2125                         while (p->td_index) {
2126                                 void *tmp = p->td_index->next;
2127                                 free(p->td_index);
2128                                 p->td_index = tmp;
2129                         }
2130                         free(p->funcdescs);
2131                         if (p->rpath != p->rpath_orig)
2132                                 free(p->rpath);
2133                         free(p->deps);
2134                         unmap_library(p);
2135                         free(p);
2136                 }
2137                 free(ctor_queue);
2138                 ctor_queue = 0;
2139                 if (!orig_tls_tail) libc.tls_head = 0;
2140                 tls_tail = orig_tls_tail;
2141                 if (tls_tail) tls_tail->next = 0;
2142                 tls_cnt = orig_tls_cnt;
2143                 tls_offset = orig_tls_offset;
2144                 tls_align = orig_tls_align;
2145                 lazy_head = orig_lazy_head;
2146                 tail = orig_tail;
2147                 tail->next = 0;
2148                 p = 0;
2149                 goto end;
2150         } else p = load_library(file, head);
2151
2152         if (!p) {
2153                 error(noload ?
2154                         "Library %s is not already loaded" :
2155                         "Error loading shared library %s: %m",
2156                         file);
2157                 goto end;
2158         }
2159
2160         /* First load handling */
2161         load_deps(p);
2162         extend_bfs_deps(p);
2163         pthread_mutex_lock(&init_fini_lock);
2164         int constructed = p->constructed;
2165         pthread_mutex_unlock(&init_fini_lock);
2166         if (!constructed) ctor_queue = queue_ctors(p);
2167         if (!p->relocated && (mode & RTLD_LAZY)) {
2168                 prepare_lazy(p);
2169                 for (i=0; p->deps[i]; i++)
2170                         if (!p->deps[i]->relocated)
2171                                 prepare_lazy(p->deps[i]);
2172         }
2173         if (!p->relocated || (mode & RTLD_GLOBAL)) {
2174                 /* Make new symbols global, at least temporarily, so we can do
2175                  * relocations. If not RTLD_GLOBAL, this is reverted below. */
2176                 add_syms(p);
2177                 for (i=0; p->deps[i]; i++)
2178                         add_syms(p->deps[i]);
2179         }
2180         if (!p->relocated) {
2181                 reloc_all(p);
2182         }
2183
2184         /* If RTLD_GLOBAL was not specified, undo any new additions
2185          * to the global symbol table. This is a nop if the library was
2186          * previously loaded and already global. */
2187         if (!(mode & RTLD_GLOBAL))
2188                 revert_syms(orig_syms_tail);
2189
2190         /* Processing of deferred lazy relocations must not happen until
2191          * the new libraries are committed; otherwise we could end up with
2192          * relocations resolved to symbol definitions that get removed. */
2193         redo_lazy_relocs();
2194
2195         update_tls_size();
2196         if (tls_cnt != orig_tls_cnt)
2197                 install_new_tls();
2198         orig_tail = tail;
2199 end:
2200         debug.state = RT_CONSISTENT;
2201         _dl_debug_state();
2202         __release_ptc();
2203         if (p) gencnt++;
2204         pthread_rwlock_unlock(&lock);
2205         if (ctor_queue) {
2206                 do_init_fini(ctor_queue);
2207                 free(ctor_queue);
2208         }
2209         pthread_setcancelstate(cs, 0);
2210         return p;
2211 }
2212
2213 hidden int __dl_invalid_handle(void *h)
2214 {
2215         struct dso *p;
2216         for (p=head; p; p=p->next) if (h==p) return 0;
2217         error("Invalid library handle %p", (void *)h);
2218         return 1;
2219 }
2220
2221 static void *addr2dso(size_t a)
2222 {
2223         struct dso *p;
2224         size_t i;
2225         if (DL_FDPIC) for (p=head; p; p=p->next) {
2226                 i = count_syms(p);
2227                 if (a-(size_t)p->funcdescs < i*sizeof(*p->funcdescs))
2228                         return p;
2229         }
2230         for (p=head; p; p=p->next) {
2231                 if (DL_FDPIC && p->loadmap) {
2232                         for (i=0; i<p->loadmap->nsegs; i++) {
2233                                 if (a-p->loadmap->segs[i].p_vaddr
2234                                     < p->loadmap->segs[i].p_memsz)
2235                                         return p;
2236                         }
2237                 } else {
2238                         Phdr *ph = p->phdr;
2239                         size_t phcnt = p->phnum;
2240                         size_t entsz = p->phentsize;
2241                         size_t base = (size_t)p->base;
2242                         for (; phcnt--; ph=(void *)((char *)ph+entsz)) {
2243                                 if (ph->p_type != PT_LOAD) continue;
2244                                 if (a-base-ph->p_vaddr < ph->p_memsz)
2245                                         return p;
2246                         }
2247                         if (a-(size_t)p->map < p->map_len)
2248                                 return 0;
2249                 }
2250         }
2251         return 0;
2252 }
2253
2254 static void *do_dlsym(struct dso *p, const char *s, void *ra)
2255 {
2256         int use_deps = 0;
2257         if (p == head || p == RTLD_DEFAULT) {
2258                 p = head;
2259         } else if (p == RTLD_NEXT) {
2260                 p = addr2dso((size_t)ra);
2261                 if (!p) p=head;
2262                 p = p->next;
2263         } else if (__dl_invalid_handle(p)) {
2264                 return 0;
2265         } else
2266                 use_deps = 1;
2267         struct symdef def = find_sym2(p, s, 0, use_deps);
2268         if (!def.sym) {
2269                 error("Symbol not found: %s", s);
2270                 return 0;
2271         }
2272         if ((def.sym->st_info&0xf) == STT_TLS)
2273                 return __tls_get_addr((tls_mod_off_t []){def.dso->tls_id, def.sym->st_value-DTP_OFFSET});
2274         if (DL_FDPIC && (def.sym->st_info&0xf) == STT_FUNC)
2275                 return def.dso->funcdescs + (def.sym - def.dso->syms);
2276         return laddr(def.dso, def.sym->st_value);
2277 }
2278
2279 int dladdr(const void *addr_arg, Dl_info *info)
2280 {
2281         size_t addr = (size_t)addr_arg;
2282         struct dso *p;
2283         Sym *sym, *bestsym;
2284         uint32_t nsym;
2285         char *strings;
2286         size_t best = 0;
2287         size_t besterr = -1;
2288
2289         pthread_rwlock_rdlock(&lock);
2290         p = addr2dso(addr);
2291         pthread_rwlock_unlock(&lock);
2292
2293         if (!p) return 0;
2294
2295         sym = p->syms;
2296         strings = p->strings;
2297         nsym = count_syms(p);
2298
2299         if (DL_FDPIC) {
2300                 size_t idx = (addr-(size_t)p->funcdescs)
2301                         / sizeof(*p->funcdescs);
2302                 if (idx < nsym && (sym[idx].st_info&0xf) == STT_FUNC) {
2303                         best = (size_t)(p->funcdescs + idx);
2304                         bestsym = sym + idx;
2305                         besterr = 0;
2306                 }
2307         }
2308
2309         if (!best) for (; nsym; nsym--, sym++) {
2310                 if (sym->st_value
2311                  && (1<<(sym->st_info&0xf) & OK_TYPES)
2312                  && (1<<(sym->st_info>>4) & OK_BINDS)) {
2313                         size_t symaddr = (size_t)laddr(p, sym->st_value);
2314                         if (symaddr > addr || symaddr <= best)
2315                                 continue;
2316                         best = symaddr;
2317                         bestsym = sym;
2318                         besterr = addr - symaddr;
2319                         if (addr == symaddr)
2320                                 break;
2321                 }
2322         }
2323
2324         if (best && besterr > bestsym->st_size-1) {
2325                 best = 0;
2326                 bestsym = 0;
2327         }
2328
2329         info->dli_fname = p->name;
2330         info->dli_fbase = p->map;
2331
2332         if (!best) {
2333                 info->dli_sname = 0;
2334                 info->dli_saddr = 0;
2335                 return 1;
2336         }
2337
2338         if (DL_FDPIC && (bestsym->st_info&0xf) == STT_FUNC)
2339                 best = (size_t)(p->funcdescs + (bestsym - p->syms));
2340         info->dli_sname = strings + bestsym->st_name;
2341         info->dli_saddr = (void *)best;
2342
2343         return 1;
2344 }
2345
2346 hidden void *__dlsym(void *restrict p, const char *restrict s, void *restrict ra)
2347 {
2348         void *res;
2349         pthread_rwlock_rdlock(&lock);
2350         res = do_dlsym(p, s, ra);
2351         pthread_rwlock_unlock(&lock);
2352         return res;
2353 }
2354
2355 hidden void *__dlsym_redir_time64(void *restrict p, const char *restrict s, void *restrict ra)
2356 {
2357 #if _REDIR_TIME64
2358         const char *suffix, *suffix2 = "";
2359         char redir[36];
2360
2361         /* Map the symbol name to a time64 version of itself according to the
2362          * pattern used for naming the redirected time64 symbols. */
2363         size_t l = strnlen(s, sizeof redir);
2364         if (l<4 || l==sizeof redir) goto no_redir;
2365         if (s[l-2]=='_' && s[l-1]=='r') {
2366                 l -= 2;
2367                 suffix2 = s+l;
2368         }
2369         if (l<4) goto no_redir;
2370         if (!strcmp(s+l-4, "time")) suffix = "64";
2371         else suffix = "_time64";
2372
2373         /* Use the presence of the remapped symbol name in libc to determine
2374          * whether it's one that requires time64 redirection; replace if so. */
2375         snprintf(redir, sizeof redir, "__%.*s%s%s", (int)l, s, suffix, suffix2);
2376         if (find_sym(&ldso, redir, 1).sym) s = redir;
2377 no_redir:
2378 #endif
2379         return __dlsym(p, s, ra);
2380 }
2381
2382 int dl_iterate_phdr(int(*callback)(struct dl_phdr_info *info, size_t size, void *data), void *data)
2383 {
2384         struct dso *current;
2385         struct dl_phdr_info info;
2386         int ret = 0;
2387         for(current = head; current;) {
2388                 info.dlpi_addr      = (uintptr_t)current->base;
2389                 info.dlpi_name      = current->name;
2390                 info.dlpi_phdr      = current->phdr;
2391                 info.dlpi_phnum     = current->phnum;
2392                 info.dlpi_adds      = gencnt;
2393                 info.dlpi_subs      = 0;
2394                 info.dlpi_tls_modid = current->tls_id;
2395                 info.dlpi_tls_data = !current->tls_id ? 0 :
2396                         __tls_get_addr((tls_mod_off_t[]){current->tls_id,0});
2397
2398                 ret = (callback)(&info, sizeof (info), data);
2399
2400                 if (ret != 0) break;
2401
2402                 pthread_rwlock_rdlock(&lock);
2403                 current = current->next;
2404                 pthread_rwlock_unlock(&lock);
2405         }
2406         return ret;
2407 }
2408
2409 static void error_impl(const char *fmt, ...)
2410 {
2411         va_list ap;
2412         va_start(ap, fmt);
2413         if (!runtime) {
2414                 vdprintf(2, fmt, ap);
2415                 dprintf(2, "\n");
2416                 ldso_fail = 1;
2417                 va_end(ap);
2418                 return;
2419         }
2420         __dl_vseterr(fmt, ap);
2421         va_end(ap);
2422 }
2423
2424 static void error_noop(const char *fmt, ...)
2425 {
2426 }