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