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