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