Debian Codegraph @

libc-top-half/musl/ldso/dynlink.c

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