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