OSDN Git Service

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