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