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