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