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