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