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