• 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 						free(sys_path);
1104 						sys_path = "";
1105 					}
1106 					close(fd);
1107 				} else if (errno != ENOENT) {
1108 					sys_path = "";
1109 				}
1110 			}
1111 			if (!sys_path || sys_path[0] == 0) sys_path = "/usr/lib:/lib:/usr/local/lib";
1112 			fd = path_open(name, sys_path, buf, sizeof buf);
1113 		}
1114 		pathname = buf;
1115 	}
1116 	if (fd < 0) return 0;
1117 
1118 	if (pathname[0] != '/') {
1119 		if (!realpath(pathname, fullpath)) {
1120 			close(fd);
1121 			return 0;
1122 		}
1123 		pathname = fullpath;
1124 	}
1125 
1126 	for (p=head->next; p; p=p->next) {
1127 		if (!strcmp(p->name, pathname)) {
1128 			/* If this library was previously loaded with a
1129 			 * pathname but a search found the same inode,
1130 			 * setup its shortname so it can be found by name. */
1131 			if (!p->shortname && pathname != name)
1132 				p->shortname = strrchr(p->name, '/')+1;
1133 			close(fd);
1134 			return p;
1135 		}
1136 	}
1137 	map = noload ? 0 : map_library(fd, &temp_dso);
1138 	close(fd);
1139 	if (!map) return 0;
1140 
1141 	/* Avoid the danger of getting two versions of libc mapped into the
1142 	 * same process when an absolute pathname was used. The symbols
1143 	 * checked are chosen to catch both musl and glibc, and to avoid
1144 	 * false positives from interposition-hack libraries. */
1145 	decode_dyn(&temp_dso);
1146 	if (find_sym(&temp_dso, "__libc_start_main", 1).sym &&
1147 	    find_sym(&temp_dso, "stdin", 1).sym) {
1148 		unmap_library(&temp_dso);
1149 		return load_library("libc.so", needed_by);
1150 	}
1151 	/* Past this point, if we haven't reached runtime yet, ldso has
1152 	 * committed either to use the mapped library or to abort execution.
1153 	 * Unmapping is not possible, so we can safely reclaim gaps. */
1154 	if (!runtime) reclaim_gaps(&temp_dso);
1155 
1156 	/* Allocate storage for the new DSO. When there is TLS, this
1157 	 * storage must include a reservation for all pre-existing
1158 	 * threads to obtain copies of both the new TLS, and an
1159 	 * extended DTV capable of storing an additional slot for
1160 	 * the newly-loaded DSO. */
1161 	alloc_size = sizeof *p + strlen(pathname) + 1;
1162 	if (runtime && temp_dso.tls.image) {
1163 		size_t per_th = temp_dso.tls.size + temp_dso.tls.align
1164 			+ sizeof(void *) * (tls_cnt+3);
1165 		n_th = libc.threads_minus_1 + 1;
1166 		if (n_th > SSIZE_MAX / per_th) alloc_size = SIZE_MAX;
1167 		else alloc_size += n_th * per_th;
1168 	}
1169 	p = calloc(1, alloc_size);
1170 	if (!p) {
1171 		unmap_library(&temp_dso);
1172 		return 0;
1173 	}
1174 	memcpy(p, &temp_dso, sizeof temp_dso);
1175 	p->needed_by = needed_by;
1176 	p->name = p->buf;
1177 	p->runtime_loaded = runtime;
1178 	strcpy(p->name, pathname);
1179 	/* Add a shortname only if name arg was not an explicit pathname. */
1180 	if (pathname != name) p->shortname = strrchr(p->name, '/')+1;
1181 	if (p->tls.image) {
1182 		p->tls_id = ++tls_cnt;
1183 		tls_align = MAXP2(tls_align, p->tls.align);
1184 #ifdef TLS_ABOVE_TP
1185 		p->tls.offset = tls_offset + ( (p->tls.align-1) &
1186 			(-tls_offset + (uintptr_t)p->tls.image) );
1187 		tls_offset = p->tls.offset + p->tls.size;
1188 #else
1189 		tls_offset += p->tls.size + p->tls.align - 1;
1190 		tls_offset -= (tls_offset + (uintptr_t)p->tls.image)
1191 			& (p->tls.align-1);
1192 		p->tls.offset = tls_offset;
1193 #endif
1194 		p->new_dtv = (void *)(-sizeof(size_t) &
1195 			(uintptr_t)(p->name+strlen(p->name)+sizeof(size_t)));
1196 		p->new_tls = (void *)(p->new_dtv + n_th*(tls_cnt+1));
1197 		if (tls_tail) tls_tail->next = &p->tls;
1198 		else libc.tls_head = &p->tls;
1199 		tls_tail = &p->tls;
1200 	}
1201 
1202 	tail->next = p;
1203 	p->prev = tail;
1204 	tail = p;
1205 
1206 	if (DL_FDPIC) makefuncdescs(p);
1207 
1208 	if (ldd_mode) dprintf(1, "\t%s => %s (%p)\n", name, pathname, p->base);
1209 
1210 	return p;
1211 }
1212 
load_direct_deps(struct dso * p)1213 static void load_direct_deps(struct dso *p)
1214 {
1215 	size_t i, cnt=0;
1216 
1217 	if (p->deps) return;
1218 	/* For head, all preloads are direct pseudo-dependencies.
1219 	 * Count and include them now to avoid realloc later. */
1220 	if (p==head) for (struct dso *q=p->next; q; q=q->next)
1221 		cnt++;
1222 	for (i=0; p->dynv[i]; i+=2)
1223 		if (p->dynv[i] == DT_NEEDED) cnt++;
1224 	/* Use builtin buffer for apps with no external deps, to
1225 	 * preserve property of no runtime failure paths. */
1226 	p->deps = (p==head && cnt<2) ? builtin_deps :
1227 		calloc(cnt+1, sizeof *p->deps);
1228 	if (!p->deps) {
1229 		error("Error loading dependencies for %s", p->name);
1230 		if (runtime) longjmp(*rtld_fail, 1);
1231 	}
1232 	cnt=0;
1233 	if (p==head) for (struct dso *q=p->next; q; q=q->next)
1234 		p->deps[cnt++] = q;
1235 	for (i=0; p->dynv[i]; i+=2) {
1236 		if (p->dynv[i] != DT_NEEDED) continue;
1237 		struct dso *dep = load_library(p->strings + p->dynv[i+1], p);
1238 		if (!dep) {
1239 			error("Error loading shared library %s: %m (needed by %s)",
1240 				p->strings + p->dynv[i+1], p->name);
1241 			if (runtime) longjmp(*rtld_fail, 1);
1242 			continue;
1243 		}
1244 		p->deps[cnt++] = dep;
1245 	}
1246 	p->deps[cnt] = 0;
1247 	p->ndeps_direct = cnt;
1248 }
1249 
load_deps(struct dso * p)1250 static void load_deps(struct dso *p)
1251 {
1252 	if (p->deps) return;
1253 	for (; p; p=p->next)
1254 		load_direct_deps(p);
1255 }
1256 
extend_bfs_deps(struct dso * p)1257 static void extend_bfs_deps(struct dso *p)
1258 {
1259 	size_t i, j, cnt, ndeps_all;
1260 	struct dso **tmp;
1261 
1262 	/* Can't use realloc if the original p->deps was allocated at
1263 	 * program entry and malloc has been replaced, or if it's
1264 	 * the builtin non-allocated trivial main program deps array. */
1265 	int no_realloc = (__malloc_replaced && !p->runtime_loaded)
1266 		|| p->deps == builtin_deps;
1267 
1268 	if (p->bfs_built) return;
1269 	ndeps_all = p->ndeps_direct;
1270 
1271 	/* Mark existing (direct) deps so they won't be duplicated. */
1272 	for (i=0; p->deps[i]; i++)
1273 		p->deps[i]->mark = 1;
1274 
1275 	/* For each dependency already in the list, copy its list of direct
1276 	 * dependencies to the list, excluding any items already in the
1277 	 * list. Note that the list this loop iterates over will grow during
1278 	 * the loop, but since duplicates are excluded, growth is bounded. */
1279 	for (i=0; p->deps[i]; i++) {
1280 		struct dso *dep = p->deps[i];
1281 		for (j=cnt=0; j<dep->ndeps_direct; j++)
1282 			if (!dep->deps[j]->mark) cnt++;
1283 		tmp = no_realloc ?
1284 			malloc(sizeof(*tmp) * (ndeps_all+cnt+1)) :
1285 			realloc(p->deps, sizeof(*tmp) * (ndeps_all+cnt+1));
1286 		if (!tmp) {
1287 			error("Error recording dependencies for %s", p->name);
1288 			if (runtime) longjmp(*rtld_fail, 1);
1289 			continue;
1290 		}
1291 		if (no_realloc) {
1292 			memcpy(tmp, p->deps, sizeof(*tmp) * (ndeps_all+1));
1293 			no_realloc = 0;
1294 		}
1295 		p->deps = tmp;
1296 		for (j=0; j<dep->ndeps_direct; j++) {
1297 			if (dep->deps[j]->mark) continue;
1298 			dep->deps[j]->mark = 1;
1299 			p->deps[ndeps_all++] = dep->deps[j];
1300 		}
1301 		p->deps[ndeps_all] = 0;
1302 	}
1303 	p->bfs_built = 1;
1304 	for (p=head; p; p=p->next)
1305 		p->mark = 0;
1306 }
1307 
load_preload(char * s)1308 static void load_preload(char *s)
1309 {
1310 	int tmp;
1311 	char *z;
1312 	for (z=s; *z; s=z) {
1313 		for (   ; *s && (isspace(*s) || *s==':'); s++);
1314 		for (z=s; *z && !isspace(*z) && *z!=':'; z++);
1315 		tmp = *z;
1316 		*z = 0;
1317 		load_library(s, 0);
1318 		*z = tmp;
1319 	}
1320 }
1321 
add_syms(struct dso * p)1322 static void add_syms(struct dso *p)
1323 {
1324 	if (!p->syms_next && syms_tail != p) {
1325 		syms_tail->syms_next = p;
1326 		syms_tail = p;
1327 	}
1328 }
1329 
revert_syms(struct dso * old_tail)1330 static void revert_syms(struct dso *old_tail)
1331 {
1332 	struct dso *p, *next;
1333 	/* Chop off the tail of the list of dsos that participate in
1334 	 * the global symbol table, reverting them to RTLD_LOCAL. */
1335 	for (p=old_tail; p; p=next) {
1336 		next = p->syms_next;
1337 		p->syms_next = 0;
1338 	}
1339 	syms_tail = old_tail;
1340 }
1341 
do_mips_relocs(struct dso * p,size_t * got)1342 static void do_mips_relocs(struct dso *p, size_t *got)
1343 {
1344 	size_t i, j, rel[2];
1345 	unsigned char *base = p->base;
1346 	i=0; search_vec(p->dynv, &i, DT_MIPS_LOCAL_GOTNO);
1347 	if (p==&ldso) {
1348 		got += i;
1349 	} else {
1350 		while (i--) *got++ += (size_t)base;
1351 	}
1352 	j=0; search_vec(p->dynv, &j, DT_MIPS_GOTSYM);
1353 	i=0; search_vec(p->dynv, &i, DT_MIPS_SYMTABNO);
1354 	Sym *sym = p->syms + j;
1355 	rel[0] = (unsigned char *)got - base;
1356 	for (i-=j; i; i--, sym++, rel[0]+=sizeof(size_t)) {
1357 		rel[1] = R_INFO(sym-p->syms, R_MIPS_JUMP_SLOT);
1358 		do_relocs(p, rel, sizeof rel, 2);
1359 	}
1360 }
1361 
reloc_all(struct dso * p)1362 static void reloc_all(struct dso *p)
1363 {
1364 	size_t dyn[DYN_CNT];
1365 	for (; p; p=p->next) {
1366 		if (p->relocated) continue;
1367 		decode_vec(p->dynv, dyn, DYN_CNT);
1368 		if (NEED_MIPS_GOT_RELOCS)
1369 			do_mips_relocs(p, laddr(p, dyn[DT_PLTGOT]));
1370 		do_relocs(p, laddr(p, dyn[DT_JMPREL]), dyn[DT_PLTRELSZ],
1371 			2+(dyn[DT_PLTREL]==DT_RELA));
1372 		do_relocs(p, laddr(p, dyn[DT_REL]), dyn[DT_RELSZ], 2);
1373 		do_relocs(p, laddr(p, dyn[DT_RELA]), dyn[DT_RELASZ], 3);
1374 
1375 		if (head != &ldso && p->relro_start != p->relro_end &&
1376 		    mprotect(laddr(p, p->relro_start), p->relro_end-p->relro_start, PROT_READ)
1377 		    && errno != ENOSYS) {
1378 			error("Error relocating %s: RELRO protection failed: %m",
1379 				p->name);
1380 			if (runtime) longjmp(*rtld_fail, 1);
1381 		}
1382 
1383 		p->relocated = 1;
1384 	}
1385 }
1386 
kernel_mapped_dso(struct dso * p)1387 static void kernel_mapped_dso(struct dso *p)
1388 {
1389 	size_t min_addr = -1, max_addr = 0, cnt;
1390 	Phdr *ph = p->phdr;
1391 	for (cnt = p->phnum; cnt--; ph = (void *)((char *)ph + p->phentsize)) {
1392 		if (ph->p_type == PT_DYNAMIC) {
1393 			p->dynv = laddr(p, ph->p_vaddr);
1394 		} else if (ph->p_type == PT_GNU_RELRO) {
1395 			p->relro_start = ph->p_vaddr & -PAGE_SIZE;
1396 			p->relro_end = (ph->p_vaddr + ph->p_memsz) & -PAGE_SIZE;
1397 		} else if (ph->p_type == PT_GNU_STACK) {
1398 			if (!runtime && ph->p_memsz > __default_stacksize) {
1399 				__default_stacksize =
1400 					ph->p_memsz < DEFAULT_STACK_MAX ?
1401 					ph->p_memsz : DEFAULT_STACK_MAX;
1402 			}
1403 		}
1404 		if (ph->p_type != PT_LOAD) continue;
1405 		if (ph->p_vaddr < min_addr)
1406 			min_addr = ph->p_vaddr;
1407 		if (ph->p_vaddr+ph->p_memsz > max_addr)
1408 			max_addr = ph->p_vaddr+ph->p_memsz;
1409 	}
1410 	min_addr &= -PAGE_SIZE;
1411 	max_addr = (max_addr + PAGE_SIZE-1) & -PAGE_SIZE;
1412 	p->map = p->base + min_addr;
1413 	p->map_len = max_addr - min_addr;
1414 	p->kernel_mapped = 1;
1415 }
1416 
__libc_exit_fini()1417 void __libc_exit_fini()
1418 {
1419 	struct dso *p;
1420 	size_t dyn[DYN_CNT];
1421 	pthread_t self = __pthread_self();
1422 
1423 	/* Take both locks before setting shutting_down, so that
1424 	 * either lock is sufficient to read its value. The lock
1425 	 * order matches that in dlopen to avoid deadlock. */
1426 	pthread_rwlock_wrlock(&lock);
1427 	pthread_mutex_lock(&init_fini_lock);
1428 	shutting_down = 1;
1429 	pthread_rwlock_unlock(&lock);
1430 	for (p=fini_head; p; p=p->fini_next) {
1431 		while (p->ctor_visitor && p->ctor_visitor!=self)
1432 			pthread_cond_wait(&ctor_cond, &init_fini_lock);
1433 		if (!p->constructed) continue;
1434 		decode_vec(p->dynv, dyn, DYN_CNT);
1435 		if (dyn[0] & (1<<DT_FINI_ARRAY)) {
1436 			size_t n = dyn[DT_FINI_ARRAYSZ]/sizeof(size_t);
1437 			size_t *fn = (size_t *)laddr(p, dyn[DT_FINI_ARRAY])+n;
1438 			while (n--) ((void (*)(void))*--fn)();
1439 		}
1440 #ifndef NO_LEGACY_INITFINI
1441 		if ((dyn[0] & (1<<DT_FINI)) && dyn[DT_FINI])
1442 			fpaddr(p, dyn[DT_FINI])();
1443 #endif
1444 	}
1445 }
1446 
__ldso_atfork(int who)1447 void __ldso_atfork(int who)
1448 {
1449 	if (who<0) {
1450 		pthread_rwlock_wrlock(&lock);
1451 		pthread_mutex_lock(&init_fini_lock);
1452 	} else {
1453 		pthread_mutex_unlock(&init_fini_lock);
1454 		pthread_rwlock_unlock(&lock);
1455 	}
1456 }
1457 
queue_ctors(struct dso * dso)1458 static struct dso **queue_ctors(struct dso *dso)
1459 {
1460 	size_t cnt, qpos, spos, i;
1461 	struct dso *p, **queue, **stack;
1462 
1463 	if (ldd_mode) return 0;
1464 
1465 	/* Bound on queue size is the total number of indirect deps.
1466 	 * If a bfs deps list was built, we can use it. Otherwise,
1467 	 * bound by the total number of DSOs, which is always safe and
1468 	 * is reasonable we use it (for main app at startup). */
1469 	if (dso->bfs_built) {
1470 		for (cnt=0; dso->deps[cnt]; cnt++)
1471 			dso->deps[cnt]->mark = 0;
1472 		cnt++; /* self, not included in deps */
1473 	} else {
1474 		for (cnt=0, p=head; p; cnt++, p=p->next)
1475 			p->mark = 0;
1476 	}
1477 	cnt++; /* termination slot */
1478 	if (dso==head && cnt <= countof(builtin_ctor_queue))
1479 		queue = builtin_ctor_queue;
1480 	else
1481 		queue = calloc(cnt, sizeof *queue);
1482 
1483 	if (!queue) {
1484 		error("Error allocating constructor queue: %m\n");
1485 		if (runtime) longjmp(*rtld_fail, 1);
1486 		return 0;
1487 	}
1488 
1489 	/* Opposite ends of the allocated buffer serve as an output queue
1490 	 * and a working stack. Setup initial stack with just the argument
1491 	 * dso and initial queue empty... */
1492 	stack = queue;
1493 	qpos = 0;
1494 	spos = cnt;
1495 	stack[--spos] = dso;
1496 	dso->next_dep = 0;
1497 	dso->mark = 1;
1498 
1499 	/* Then perform pseudo-DFS sort, but ignoring circular deps. */
1500 	while (spos<cnt) {
1501 		p = stack[spos++];
1502 		while (p->next_dep < p->ndeps_direct) {
1503 			if (p->deps[p->next_dep]->mark) {
1504 				p->next_dep++;
1505 			} else {
1506 				stack[--spos] = p;
1507 				p = p->deps[p->next_dep];
1508 				p->next_dep = 0;
1509 				p->mark = 1;
1510 			}
1511 		}
1512 		queue[qpos++] = p;
1513 	}
1514 	queue[qpos] = 0;
1515 	for (i=0; i<qpos; i++) queue[i]->mark = 0;
1516 	for (i=0; i<qpos; i++)
1517 		if (queue[i]->ctor_visitor && queue[i]->ctor_visitor->tid < 0) {
1518 			error("State of %s is inconsistent due to multithreaded fork\n",
1519 				queue[i]->name);
1520 			free(queue);
1521 			if (runtime) longjmp(*rtld_fail, 1);
1522 		}
1523 
1524 	return queue;
1525 }
1526 
do_init_fini(struct dso ** queue)1527 static void do_init_fini(struct dso **queue)
1528 {
1529 	struct dso *p;
1530 	size_t dyn[DYN_CNT], i;
1531 	pthread_t self = __pthread_self();
1532 
1533 	pthread_mutex_lock(&init_fini_lock);
1534 	for (i=0; (p=queue[i]); i++) {
1535 		while ((p->ctor_visitor && p->ctor_visitor!=self) || shutting_down)
1536 			pthread_cond_wait(&ctor_cond, &init_fini_lock);
1537 		if (p->ctor_visitor || p->constructed)
1538 			continue;
1539 		p->ctor_visitor = self;
1540 
1541 		decode_vec(p->dynv, dyn, DYN_CNT);
1542 		if (dyn[0] & ((1<<DT_FINI) | (1<<DT_FINI_ARRAY))) {
1543 			p->fini_next = fini_head;
1544 			fini_head = p;
1545 		}
1546 
1547 		pthread_mutex_unlock(&init_fini_lock);
1548 
1549 #ifndef NO_LEGACY_INITFINI
1550 		if ((dyn[0] & (1<<DT_INIT)) && dyn[DT_INIT])
1551 			fpaddr(p, dyn[DT_INIT])();
1552 #endif
1553 		if (dyn[0] & (1<<DT_INIT_ARRAY)) {
1554 			size_t n = dyn[DT_INIT_ARRAYSZ]/sizeof(size_t);
1555 			size_t *fn = laddr(p, dyn[DT_INIT_ARRAY]);
1556 			while (n--) ((void (*)(void))*fn++)();
1557 		}
1558 
1559 		pthread_mutex_lock(&init_fini_lock);
1560 		p->ctor_visitor = 0;
1561 		p->constructed = 1;
1562 		pthread_cond_broadcast(&ctor_cond);
1563 	}
1564 	pthread_mutex_unlock(&init_fini_lock);
1565 }
1566 
__libc_start_init(void)1567 void __libc_start_init(void)
1568 {
1569 	do_init_fini(main_ctor_queue);
1570 	if (!__malloc_replaced && main_ctor_queue != builtin_ctor_queue)
1571 		free(main_ctor_queue);
1572 	main_ctor_queue = 0;
1573 }
1574 
dl_debug_state(void)1575 static void dl_debug_state(void)
1576 {
1577 }
1578 
1579 weak_alias(dl_debug_state, _dl_debug_state);
1580 
__init_tls(size_t * auxv)1581 void __init_tls(size_t *auxv)
1582 {
1583 }
1584 
update_tls_size()1585 static void update_tls_size()
1586 {
1587 	libc.tls_cnt = tls_cnt;
1588 	libc.tls_align = tls_align;
1589 	libc.tls_size = ALIGN(
1590 		(1+tls_cnt) * sizeof(void *) +
1591 		tls_offset +
1592 		sizeof(struct pthread) +
1593 		tls_align * 2,
1594 	tls_align);
1595 }
1596 
install_new_tls(void)1597 static void install_new_tls(void)
1598 {
1599 	sigset_t set;
1600 	pthread_t self = __pthread_self(), td;
1601 	struct dso *dtv_provider = container_of(tls_tail, struct dso, tls);
1602 	uintptr_t (*newdtv)[tls_cnt+1] = (void *)dtv_provider->new_dtv;
1603 	struct dso *p;
1604 	size_t i, j;
1605 	size_t old_cnt = self->dtv[0];
1606 
1607 	__block_app_sigs(&set);
1608 	__tl_lock();
1609 	/* Copy existing dtv contents from all existing threads. */
1610 	for (i=0, td=self; !i || td!=self; i++, td=td->next) {
1611 		memcpy(newdtv+i, td->dtv,
1612 			(old_cnt+1)*sizeof(uintptr_t));
1613 		newdtv[i][0] = tls_cnt;
1614 	}
1615 	/* Install new dtls into the enlarged, uninstalled dtv copies. */
1616 	for (p=head; ; p=p->next) {
1617 		if (p->tls_id <= old_cnt) continue;
1618 		unsigned char *mem = p->new_tls;
1619 		for (j=0; j<i; j++) {
1620 			unsigned char *new = mem;
1621 			new += ((uintptr_t)p->tls.image - (uintptr_t)mem)
1622 				& (p->tls.align-1);
1623 			memcpy(new, p->tls.image, p->tls.len);
1624 			newdtv[j][p->tls_id] =
1625 				(uintptr_t)new + DTP_OFFSET;
1626 			mem += p->tls.size + p->tls.align;
1627 		}
1628 		if (p->tls_id == tls_cnt) break;
1629 	}
1630 
1631 	/* Broadcast barrier to ensure contents of new dtv is visible
1632 	 * if the new dtv pointer is. The __membarrier function has a
1633 	 * fallback emulation using signals for kernels that lack the
1634 	 * feature at the syscall level. */
1635 
1636 	__membarrier(MEMBARRIER_CMD_PRIVATE_EXPEDITED, 0);
1637 
1638 	/* Install new dtv for each thread. */
1639 	for (j=0, td=self; !j || td!=self; j++, td=td->next) {
1640 		td->dtv = newdtv[j];
1641 	}
1642 
1643 	__tl_unlock();
1644 	__restore_sigs(&set);
1645 }
1646 
1647 /* Stage 1 of the dynamic linker is defined in dlstart.c. It calls the
1648  * following stage 2 and stage 3 functions via primitive symbolic lookup
1649  * since it does not have access to their addresses to begin with. */
1650 
1651 /* Stage 2 of the dynamic linker is called after relative relocations
1652  * have been processed. It can make function calls to static functions
1653  * and access string literals and static data, but cannot use extern
1654  * symbols. Its job is to perform symbolic relocations on the dynamic
1655  * linker itself, but some of the relocations performed may need to be
1656  * replaced later due to copy relocations in the main program. */
1657 
__dls2(unsigned char * base,size_t * sp)1658 hidden void __dls2(unsigned char *base, size_t *sp)
1659 {
1660 	size_t *auxv;
1661 	for (auxv=sp+1+*sp+1; *auxv; auxv++);
1662 	auxv++;
1663 	if (DL_FDPIC) {
1664 		void *p1 = (void *)sp[-2];
1665 		void *p2 = (void *)sp[-1];
1666 		if (!p1) {
1667 			size_t aux[AUX_CNT];
1668 			decode_vec(auxv, aux, AUX_CNT);
1669 			if (aux[AT_BASE]) ldso.base = (void *)aux[AT_BASE];
1670 			else ldso.base = (void *)(aux[AT_PHDR] & -4096);
1671 		}
1672 		app_loadmap = p2 ? p1 : 0;
1673 		ldso.loadmap = p2 ? p2 : p1;
1674 		ldso.base = laddr(&ldso, 0);
1675 	} else {
1676 		ldso.base = base;
1677 	}
1678 	Ehdr *ehdr = (void *)ldso.base;
1679 	ldso.name = ldso.shortname = "libc.so";
1680 	ldso.phnum = ehdr->e_phnum;
1681 	ldso.phdr = laddr(&ldso, ehdr->e_phoff);
1682 	ldso.phentsize = ehdr->e_phentsize;
1683 	kernel_mapped_dso(&ldso);
1684 	decode_dyn(&ldso);
1685 
1686 	if (DL_FDPIC) makefuncdescs(&ldso);
1687 
1688 	/* Prepare storage for to save clobbered REL addends so they
1689 	 * can be reused in stage 3. There should be very few. If
1690 	 * something goes wrong and there are a huge number, abort
1691 	 * instead of risking stack overflow. */
1692 	size_t dyn[DYN_CNT];
1693 	decode_vec(ldso.dynv, dyn, DYN_CNT);
1694 	size_t *rel = laddr(&ldso, dyn[DT_REL]);
1695 	size_t rel_size = dyn[DT_RELSZ];
1696 	size_t symbolic_rel_cnt = 0;
1697 	apply_addends_to = rel;
1698 	for (; rel_size; rel+=2, rel_size-=2*sizeof(size_t))
1699 		if (!IS_RELATIVE(rel[1], ldso.syms)) symbolic_rel_cnt++;
1700 	if (symbolic_rel_cnt >= ADDEND_LIMIT) a_crash();
1701 	size_t addends[symbolic_rel_cnt+1];
1702 	saved_addends = addends;
1703 
1704 	head = &ldso;
1705 	reloc_all(&ldso);
1706 
1707 	ldso.relocated = 0;
1708 
1709 	/* Call dynamic linker stage-2b, __dls2b, looking it up
1710 	 * symbolically as a barrier against moving the address
1711 	 * load across the above relocation processing. */
1712 	struct symdef dls2b_def = find_sym(&ldso, "__dls2b", 0);
1713 	if (DL_FDPIC) ((stage3_func)&ldso.funcdescs[dls2b_def.sym-ldso.syms])(sp, auxv);
1714 	else ((stage3_func)laddr(&ldso, dls2b_def.sym->st_value))(sp, auxv);
1715 }
1716 
1717 /* Stage 2b sets up a valid thread pointer, which requires relocations
1718  * completed in stage 2, and on which stage 3 is permitted to depend.
1719  * This is done as a separate stage, with symbolic lookup as a barrier,
1720  * so that loads of the thread pointer and &errno can be pure/const and
1721  * thereby hoistable. */
1722 
__dls2b(size_t * sp,size_t * auxv)1723 void __dls2b(size_t *sp, size_t *auxv)
1724 {
1725 	/* Setup early thread pointer in builtin_tls for ldso/libc itself to
1726 	 * use during dynamic linking. If possible it will also serve as the
1727 	 * thread pointer at runtime. */
1728 	search_vec(auxv, &__hwcap, AT_HWCAP);
1729 	libc.auxv = auxv;
1730 	libc.tls_size = sizeof builtin_tls;
1731 	libc.tls_align = tls_align;
1732 	if (__init_tp(__copy_tls((void *)builtin_tls)) < 0) {
1733 		a_crash();
1734 	}
1735 
1736 	struct symdef dls3_def = find_sym(&ldso, "__dls3", 0);
1737 	if (DL_FDPIC) ((stage3_func)&ldso.funcdescs[dls3_def.sym-ldso.syms])(sp, auxv);
1738 	else ((stage3_func)laddr(&ldso, dls3_def.sym->st_value))(sp, auxv);
1739 }
1740 
1741 /* Stage 3 of the dynamic linker is called with the dynamic linker/libc
1742  * fully functional. Its job is to load (if not already loaded) and
1743  * process dependencies and relocations for the main application and
1744  * transfer control to its entry point. */
1745 
__dls3(size_t * sp,size_t * auxv)1746 void __dls3(size_t *sp, size_t *auxv)
1747 {
1748 	static struct dso app, vdso;
1749 	size_t aux[AUX_CNT];
1750 	size_t i;
1751 	char *env_preload=0;
1752 	char *replace_argv0=0;
1753 	size_t vdso_base;
1754 	int argc = *sp;
1755 	char **argv = (void *)(sp+1);
1756 	char **argv_orig = argv;
1757 	char **envp = argv+argc+1;
1758 
1759 	/* Find aux vector just past environ[] and use it to initialize
1760 	 * global data that may be needed before we can make syscalls. */
1761 	__environ = envp;
1762 	decode_vec(auxv, aux, AUX_CNT);
1763 	search_vec(auxv, &__sysinfo, AT_SYSINFO);
1764 	__pthread_self()->sysinfo = __sysinfo;
1765 	libc.page_size = aux[AT_PAGESZ];
1766 	libc.secure = ((aux[0]&0x7800)!=0x7800 || aux[AT_UID]!=aux[AT_EUID]
1767 		|| aux[AT_GID]!=aux[AT_EGID] || aux[AT_SECURE]);
1768 
1769 	/* Only trust user/env if kernel says we're not suid/sgid */
1770 	if (!libc.secure) {
1771 		env_path = getenv("LD_LIBRARY_PATH");
1772 		env_preload = getenv("LD_PRELOAD");
1773 	}
1774 
1775 	/* If the main program was already loaded by the kernel,
1776 	 * AT_PHDR will point to some location other than the dynamic
1777 	 * linker's program headers. */
1778 	if (aux[AT_PHDR] != (size_t)ldso.phdr) {
1779 		size_t interp_off = 0;
1780 		size_t tls_image = 0;
1781 		/* Find load address of the main program, via AT_PHDR vs PT_PHDR. */
1782 		Phdr *phdr = app.phdr = (void *)aux[AT_PHDR];
1783 		app.phnum = aux[AT_PHNUM];
1784 		app.phentsize = aux[AT_PHENT];
1785 		for (i=aux[AT_PHNUM]; i; i--, phdr=(void *)((char *)phdr + aux[AT_PHENT])) {
1786 			if (phdr->p_type == PT_PHDR)
1787 				app.base = (void *)(aux[AT_PHDR] - phdr->p_vaddr);
1788 			else if (phdr->p_type == PT_INTERP)
1789 				interp_off = (size_t)phdr->p_vaddr;
1790 			else if (phdr->p_type == PT_TLS) {
1791 				tls_image = phdr->p_vaddr;
1792 				app.tls.len = phdr->p_filesz;
1793 				app.tls.size = phdr->p_memsz;
1794 				app.tls.align = phdr->p_align;
1795 			}
1796 		}
1797 		if (DL_FDPIC) app.loadmap = app_loadmap;
1798 		if (app.tls.size) app.tls.image = laddr(&app, tls_image);
1799 		if (interp_off) ldso.name = "/lib/libc.so";
1800 #if 0
1801 		if ((aux[0] & (1UL<<AT_EXECFN))
1802 		    && strncmp((char *)aux[AT_EXECFN], "/proc/", 6))
1803 			app.name = (char *)aux[AT_EXECFN];
1804 		else
1805 			app.name = argv[0];
1806 #else
1807 		if (argv[0])
1808 			app.name = argv[0];
1809 		else
1810 			app.name = "none";
1811 #endif
1812 		kernel_mapped_dso(&app);
1813 	} else {
1814 		int fd;
1815 		char *ldname = argv[0];
1816 		size_t l = strlen(ldname);
1817 		if (l >= 3 && !strcmp(ldname+l-3, "ldd")) ldd_mode = 1;
1818 		argv++;
1819 		while (argv[0] && argv[0][0]=='-' && argv[0][1]=='-') {
1820 			char *opt = argv[0]+2;
1821 			*argv++ = (void *)-1;
1822 			if (!*opt) {
1823 				break;
1824 			} else if (!memcmp(opt, "list", 5)) {
1825 				ldd_mode = 1;
1826 			} else if (!memcmp(opt, "library-path", 12)) {
1827 				if (opt[12]=='=') env_path = opt+13;
1828 				else if (opt[12]) *argv = 0;
1829 				else if (*argv) env_path = *argv++;
1830 			} else if (!memcmp(opt, "preload", 7)) {
1831 				if (opt[7]=='=') env_preload = opt+8;
1832 				else if (opt[7]) *argv = 0;
1833 				else if (*argv) env_preload = *argv++;
1834 			} else if (!memcmp(opt, "argv0", 5)) {
1835 				if (opt[5]=='=') replace_argv0 = opt+6;
1836 				else if (opt[5]) *argv = 0;
1837 				else if (*argv) replace_argv0 = *argv++;
1838 			} else {
1839 				argv[0] = 0;
1840 			}
1841 		}
1842 		argv[-1] = (void *)(argc - (argv-argv_orig));
1843 		if (!argv[0]) {
1844 			dprintf(2, "musl libc (" LDSO_ARCH ")\n"
1845 				"Version %s\n"
1846 				"Dynamic Program Loader\n"
1847 				"Usage: %s [options] [--] pathname%s\n",
1848 				__libc_version, ldname,
1849 				ldd_mode ? "" : " [args]");
1850 			_exit(1);
1851 		}
1852 		fd = open(argv[0], O_RDONLY);
1853 		if (fd < 0) {
1854 			dprintf(2, "%s: cannot load %s: %s\n", ldname, argv[0], strerror(errno));
1855 			_exit(1);
1856 		}
1857 		Ehdr *ehdr = map_library(fd, &app);
1858 		if (!ehdr) {
1859 			dprintf(2, "%s: %s: Not a valid dynamic program\n", ldname, argv[0]);
1860 			_exit(1);
1861 		}
1862 		close(fd);
1863 		ldso.name = ldname;
1864 		app.name = argv[0];
1865 		aux[AT_ENTRY] = (size_t)laddr(&app, ehdr->e_entry);
1866 		/* Find the name that would have been used for the dynamic
1867 		 * linker had ldd not taken its place. */
1868 		if (ldd_mode) {
1869 			for (i=0; i<app.phnum; i++) {
1870 				if (app.phdr[i].p_type == PT_INTERP)
1871 					ldso.name = laddr(&app, app.phdr[i].p_vaddr);
1872 			}
1873 			dprintf(1, "\t%s (%p)\n", ldso.name, ldso.base);
1874 		}
1875 	}
1876 	if (app.tls.size) {
1877 		libc.tls_head = tls_tail = &app.tls;
1878 		app.tls_id = tls_cnt = 1;
1879 #ifdef TLS_ABOVE_TP
1880 		app.tls.offset = GAP_ABOVE_TP;
1881 		app.tls.offset += (-GAP_ABOVE_TP + (uintptr_t)app.tls.image)
1882 			& (app.tls.align-1);
1883 		tls_offset = app.tls.offset + app.tls.size;
1884 #else
1885 		tls_offset = app.tls.offset = app.tls.size
1886 			+ ( -((uintptr_t)app.tls.image + app.tls.size)
1887 			& (app.tls.align-1) );
1888 #endif
1889 		tls_align = MAXP2(tls_align, app.tls.align);
1890 	}
1891 	decode_dyn(&app);
1892 	if (DL_FDPIC) {
1893 		makefuncdescs(&app);
1894 		if (!app.loadmap) {
1895 			app.loadmap = (void *)&app_dummy_loadmap;
1896 			app.loadmap->nsegs = 1;
1897 			app.loadmap->segs[0].addr = (size_t)app.map;
1898 			app.loadmap->segs[0].p_vaddr = (size_t)app.map
1899 				- (size_t)app.base;
1900 			app.loadmap->segs[0].p_memsz = app.map_len;
1901 		}
1902 		argv[-3] = (void *)app.loadmap;
1903 	}
1904 
1905 	/* Initial dso chain consists only of the app. */
1906 	head = tail = syms_tail = &app;
1907 
1908 	/* Donate unused parts of app and library mapping to malloc */
1909 	reclaim_gaps(&app);
1910 	reclaim_gaps(&ldso);
1911 
1912 	/* Load preload/needed libraries, add symbols to global namespace. */
1913 	ldso.deps = (struct dso **)no_deps;
1914 	if (env_preload) load_preload(env_preload);
1915  	load_deps(&app);
1916 	for (struct dso *p=head; p; p=p->next)
1917 		add_syms(p);
1918 
1919 	/* Attach to vdso, if provided by the kernel, last so that it does
1920 	 * not become part of the global namespace.  */
1921 	if (search_vec(auxv, &vdso_base, AT_SYSINFO_EHDR) && vdso_base) {
1922 		Ehdr *ehdr = (void *)vdso_base;
1923 		Phdr *phdr = vdso.phdr = (void *)(vdso_base + ehdr->e_phoff);
1924 		vdso.phnum = ehdr->e_phnum;
1925 		vdso.phentsize = ehdr->e_phentsize;
1926 		for (i=ehdr->e_phnum; i; i--, phdr=(void *)((char *)phdr + ehdr->e_phentsize)) {
1927 			if (phdr->p_type == PT_DYNAMIC)
1928 				vdso.dynv = (void *)(vdso_base + phdr->p_offset);
1929 			if (phdr->p_type == PT_LOAD)
1930 				vdso.base = (void *)(vdso_base - phdr->p_vaddr + phdr->p_offset);
1931 		}
1932 		vdso.name = "";
1933 		vdso.shortname = "OHOS-vdso.so";
1934 		vdso.relocated = 1;
1935 		vdso.deps = (struct dso **)no_deps;
1936 		decode_dyn(&vdso);
1937 		vdso.prev = tail;
1938 		tail->next = &vdso;
1939 		tail = &vdso;
1940 	}
1941 
1942 	for (i=0; app.dynv[i]; i+=2) {
1943 		if (!DT_DEBUG_INDIRECT && app.dynv[i]==DT_DEBUG)
1944 			app.dynv[i+1] = (size_t)&debug;
1945 		if (DT_DEBUG_INDIRECT && app.dynv[i]==DT_DEBUG_INDIRECT) {
1946 			size_t *ptr = (size_t *) app.dynv[i+1];
1947 			*ptr = (size_t)&debug;
1948 		}
1949 	}
1950 
1951 	/* This must be done before final relocations, since it calls
1952 	 * malloc, which may be provided by the application. Calling any
1953 	 * application code prior to the jump to its entry point is not
1954 	 * valid in our model and does not work with FDPIC, where there
1955 	 * are additional relocation-like fixups that only the entry point
1956 	 * code can see to perform. */
1957 	main_ctor_queue = queue_ctors(&app);
1958 
1959 	/* Initial TLS must also be allocated before final relocations
1960 	 * might result in calloc being a call to application code. */
1961 	update_tls_size();
1962 	void *initial_tls = builtin_tls;
1963 	if (libc.tls_size > sizeof builtin_tls || tls_align > MIN_TLS_ALIGN) {
1964 		initial_tls = calloc(libc.tls_size, 1);
1965 		if (!initial_tls) {
1966 			dprintf(2, "%s: Error getting %zu bytes thread-local storage: %m\n",
1967 				argv[0], libc.tls_size);
1968 			_exit(127);
1969 		}
1970 	}
1971 	static_tls_cnt = tls_cnt;
1972 
1973 	/* The main program must be relocated LAST since it may contain
1974 	 * copy relocations which depend on libraries' relocations. */
1975 	reloc_all(app.next);
1976 	reloc_all(&app);
1977 
1978 	/* Actual copying to new TLS needs to happen after relocations,
1979 	 * since the TLS images might have contained relocated addresses. */
1980 	if (initial_tls != builtin_tls) {
1981 		if (__init_tp(__copy_tls(initial_tls)) < 0) {
1982 			a_crash();
1983 		}
1984 	} else {
1985 		size_t tmp_tls_size = libc.tls_size;
1986 		pthread_t self = __pthread_self();
1987 		/* Temporarily set the tls size to the full size of
1988 		 * builtin_tls so that __copy_tls will use the same layout
1989 		 * as it did for before. Then check, just to be safe. */
1990 		libc.tls_size = sizeof builtin_tls;
1991 		if (__copy_tls((void*)builtin_tls) != self) a_crash();
1992 		libc.tls_size = tmp_tls_size;
1993 	}
1994 
1995 	if (ldso_fail) _exit(127);
1996 	if (ldd_mode) _exit(0);
1997 
1998 	/* Determine if malloc was interposed by a replacement implementation
1999 	 * so that calloc and the memalign family can harden against the
2000 	 * possibility of incomplete replacement. */
2001 	if (find_sym(head, "malloc", 1).dso != &ldso)
2002 		__malloc_replaced = 1;
2003 	if (find_sym(head, "aligned_alloc", 1).dso != &ldso)
2004 		__aligned_alloc_replaced = 1;
2005 
2006 	/* Switch to runtime mode: any further failures in the dynamic
2007 	 * linker are a reportable failure rather than a fatal startup
2008 	 * error. */
2009 	runtime = 1;
2010 
2011 	debug.ver = 1;
2012 	debug.bp = dl_debug_state;
2013 	debug.head = head;
2014 	debug.base = ldso.base;
2015 	debug.state = RT_CONSISTENT;
2016 	_dl_debug_state();
2017 
2018 	if (replace_argv0) argv[0] = replace_argv0;
2019 
2020 	errno = 0;
2021 
2022 	CRTJMP((void *)aux[AT_ENTRY], argv-1);
2023 	for(;;);
2024 }
2025 
prepare_lazy(struct dso * p)2026 static void prepare_lazy(struct dso *p)
2027 {
2028 	size_t dyn[DYN_CNT], n, flags1=0;
2029 	decode_vec(p->dynv, dyn, DYN_CNT);
2030 	search_vec(p->dynv, &flags1, DT_FLAGS_1);
2031 	if (dyn[DT_BIND_NOW] || (dyn[DT_FLAGS] & DF_BIND_NOW) || (flags1 & DF_1_NOW))
2032 		return;
2033 	n = dyn[DT_RELSZ]/2 + dyn[DT_RELASZ]/3 + dyn[DT_PLTRELSZ]/2 + 1;
2034 	if (NEED_MIPS_GOT_RELOCS) {
2035 		size_t j=0; search_vec(p->dynv, &j, DT_MIPS_GOTSYM);
2036 		size_t i=0; search_vec(p->dynv, &i, DT_MIPS_SYMTABNO);
2037 		n += i-j;
2038 	}
2039 	p->lazy = calloc(n, 3*sizeof(size_t));
2040 	if (!p->lazy) {
2041 		error("Error preparing lazy relocation for %s: %m", p->name);
2042 		longjmp(*rtld_fail, 1);
2043 	}
2044 	p->lazy_next = lazy_head;
2045 	lazy_head = p;
2046 }
2047 
dlopen(const char * file,int mode)2048 void *dlopen(const char *file, int mode)
2049 {
2050 	struct dso *volatile p, *orig_tail, *orig_syms_tail, *orig_lazy_head, *next;
2051 	struct tls_module *orig_tls_tail;
2052 	size_t orig_tls_cnt, orig_tls_offset, orig_tls_align;
2053 	size_t i;
2054 	int cs;
2055 	jmp_buf jb;
2056 	struct dso **volatile ctor_queue = 0;
2057 
2058 	if (mode & ~(RTLD_LAZY | RTLD_NOW | RTLD_NOLOAD | RTLD_GLOBAL | RTLD_LOCAL | RTLD_NODELETE)) {
2059 		error("invalid mode parameter for dlopen().");
2060 		return NULL;
2061 	}
2062 
2063 	if ((mode & (RTLD_LAZY | RTLD_NOW)) == 0) {
2064 		error("invalid mode, one of RTLD_LAZY and RTLD_NOW must be set.");
2065 		return NULL;
2066 	}
2067 
2068 	if (!file) return head;
2069 
2070 	pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
2071 	pthread_rwlock_wrlock(&lock);
2072 	__inhibit_ptc();
2073 
2074 	debug.state = RT_ADD;
2075 	_dl_debug_state();
2076 
2077 	p = 0;
2078 	if (shutting_down) {
2079 		error("Cannot dlopen while program is exiting.");
2080 		goto end;
2081 	}
2082 	orig_tls_tail = tls_tail;
2083 	orig_tls_cnt = tls_cnt;
2084 	orig_tls_offset = tls_offset;
2085 	orig_tls_align = tls_align;
2086 	orig_lazy_head = lazy_head;
2087 	orig_syms_tail = syms_tail;
2088 	orig_tail = tail;
2089 	noload = mode & RTLD_NOLOAD;
2090 
2091 	rtld_fail = &jb;
2092 	if (setjmp(*rtld_fail)) {
2093 		/* Clean up anything new that was (partially) loaded */
2094 		revert_syms(orig_syms_tail);
2095 		for (p=orig_tail->next; p; p=next) {
2096 			next = p->next;
2097 			while (p->td_index) {
2098 				void *tmp = p->td_index->next;
2099 				free(p->td_index);
2100 				p->td_index = tmp;
2101 			}
2102 			free(p->funcdescs);
2103 			if (p->rpath != p->rpath_orig)
2104 				free(p->rpath);
2105 			free(p->deps);
2106 			unmap_library(p);
2107 			free(p);
2108 		}
2109 		free(ctor_queue);
2110 		ctor_queue = 0;
2111 		if (!orig_tls_tail) libc.tls_head = 0;
2112 		tls_tail = orig_tls_tail;
2113 		if (tls_tail) tls_tail->next = 0;
2114 		tls_cnt = orig_tls_cnt;
2115 		tls_offset = orig_tls_offset;
2116 		tls_align = orig_tls_align;
2117 		lazy_head = orig_lazy_head;
2118 		tail = orig_tail;
2119 		tail->next = 0;
2120 		p = 0;
2121 		goto end;
2122 	} else p = load_library(file, head);
2123 
2124 	if (!p) {
2125 		error(noload ?
2126 			"Library %s is not already loaded" :
2127 			"Error loading shared library %s: %m",
2128 			file);
2129 		goto end;
2130 	}
2131 
2132 	/* First load handling */
2133 	load_deps(p);
2134 	extend_bfs_deps(p);
2135 	pthread_mutex_lock(&init_fini_lock);
2136 	int constructed = p->constructed;
2137 	pthread_mutex_unlock(&init_fini_lock);
2138 	if (!constructed) ctor_queue = queue_ctors(p);
2139 	if (!p->relocated && (mode & RTLD_LAZY)) {
2140 		prepare_lazy(p);
2141 		for (i=0; p->deps[i]; i++)
2142 			if (!p->deps[i]->relocated)
2143 				prepare_lazy(p->deps[i]);
2144 	}
2145 	if (!p->relocated || (mode & RTLD_GLOBAL)) {
2146 		/* Make new symbols global, at least temporarily, so we can do
2147 		 * relocations. If not RTLD_GLOBAL, this is reverted below. */
2148 		add_syms(p);
2149 		for (i=0; p->deps[i]; i++)
2150 			add_syms(p->deps[i]);
2151 	}
2152 	if (!p->relocated) {
2153 		reloc_all(p);
2154 	}
2155 
2156 	/* If RTLD_GLOBAL was not specified, undo any new additions
2157 	 * to the global symbol table. This is a nop if the library was
2158 	 * previously loaded and already global. */
2159 	if (!(mode & RTLD_GLOBAL))
2160 		revert_syms(orig_syms_tail);
2161 
2162 	/* Processing of deferred lazy relocations must not happen until
2163 	 * the new libraries are committed; otherwise we could end up with
2164 	 * relocations resolved to symbol definitions that get removed. */
2165 	redo_lazy_relocs();
2166 
2167 	update_tls_size();
2168 	if (tls_cnt != orig_tls_cnt)
2169 		install_new_tls();
2170 	orig_tail = tail;
2171 end:
2172 	debug.state = RT_CONSISTENT;
2173 	_dl_debug_state();
2174 	__release_ptc();
2175 	if (p) gencnt++;
2176 	pthread_rwlock_unlock(&lock);
2177 	if (ctor_queue) {
2178 		do_init_fini(ctor_queue);
2179 		free(ctor_queue);
2180 	}
2181 	pthread_setcancelstate(cs, 0);
2182 	return p;
2183 }
2184 
__dl_invalid_handle(void * h)2185 hidden int __dl_invalid_handle(void *h)
2186 {
2187 	struct dso *p;
2188 	for (p=head; p; p=p->next) if (h==p) return 0;
2189 	error("Invalid library handle %p", (void *)h);
2190 	return 1;
2191 }
2192 
addr2dso(size_t a)2193 static void *addr2dso(size_t a)
2194 {
2195 	struct dso *p;
2196 	size_t i;
2197 	if (DL_FDPIC) for (p=head; p; p=p->next) {
2198 		i = count_syms(p);
2199 		if (a-(size_t)p->funcdescs < i*sizeof(*p->funcdescs))
2200 			return p;
2201 	}
2202 	for (p=head; p; p=p->next) {
2203 		if (DL_FDPIC && p->loadmap) {
2204 			for (i=0; i<p->loadmap->nsegs; i++) {
2205 				if (a-p->loadmap->segs[i].p_vaddr
2206 				    < p->loadmap->segs[i].p_memsz)
2207 					return p;
2208 			}
2209 		} else {
2210 			Phdr *ph = p->phdr;
2211 			size_t phcnt = p->phnum;
2212 			size_t entsz = p->phentsize;
2213 			size_t base = (size_t)p->base;
2214 			for (; phcnt--; ph=(void *)((char *)ph+entsz)) {
2215 				if (ph->p_type != PT_LOAD) continue;
2216 				if (a-base-ph->p_vaddr < ph->p_memsz)
2217 					return p;
2218 			}
2219 			if (a-(size_t)p->map < p->map_len)
2220 				return 0;
2221 		}
2222 	}
2223 	return 0;
2224 }
2225 
do_dlsym(struct dso * p,const char * s,void * ra)2226 static void *do_dlsym(struct dso *p, const char *s, void *ra)
2227 {
2228 	int use_deps = 0;
2229 	if (p == head || p == RTLD_DEFAULT) {
2230 		p = head;
2231 	} else if (p == RTLD_NEXT) {
2232 		p = addr2dso((size_t)ra);
2233 		if (!p) p=head;
2234 		p = p->next;
2235 	} else if (__dl_invalid_handle(p)) {
2236 		return 0;
2237 	} else
2238 		use_deps = 1;
2239 	struct symdef def = find_sym2(p, s, 0, use_deps);
2240 	if (!def.sym) {
2241 		error("Symbol not found: %s", s);
2242 		return 0;
2243 	}
2244 	if ((def.sym->st_info&0xf) == STT_TLS)
2245 		return __tls_get_addr((tls_mod_off_t []){def.dso->tls_id, def.sym->st_value-DTP_OFFSET});
2246 	if (DL_FDPIC && (def.sym->st_info&0xf) == STT_FUNC)
2247 		return def.dso->funcdescs + (def.sym - def.dso->syms);
2248 	return laddr(def.dso, def.sym->st_value);
2249 }
2250 
dladdr(const void * addr_arg,Dl_info * info)2251 int dladdr(const void *addr_arg, Dl_info *info)
2252 {
2253 	size_t addr = (size_t)addr_arg;
2254 	struct dso *p;
2255 	Sym *sym, *bestsym;
2256 	uint32_t nsym;
2257 	char *strings;
2258 	size_t best = 0;
2259 	size_t besterr = -1;
2260 
2261 	pthread_rwlock_rdlock(&lock);
2262 	p = addr2dso(addr);
2263 	pthread_rwlock_unlock(&lock);
2264 
2265 	if (!p) return 0;
2266 
2267 	sym = p->syms;
2268 	strings = p->strings;
2269 	nsym = count_syms(p);
2270 
2271 	if (DL_FDPIC) {
2272 		size_t idx = (addr-(size_t)p->funcdescs)
2273 			/ sizeof(*p->funcdescs);
2274 		if (idx < nsym && (sym[idx].st_info&0xf) == STT_FUNC) {
2275 			best = (size_t)(p->funcdescs + idx);
2276 			bestsym = sym + idx;
2277 			besterr = 0;
2278 		}
2279 	}
2280 
2281 	if (!best) for (; nsym; nsym--, sym++) {
2282 		if (sym->st_value
2283 		 && (1<<(sym->st_info&0xf) & OK_TYPES)
2284 		 && (1<<(sym->st_info>>4) & OK_BINDS)) {
2285 			size_t symaddr = (size_t)laddr(p, sym->st_value);
2286 			if (symaddr > addr || symaddr <= best)
2287 				continue;
2288 			best = symaddr;
2289 			bestsym = sym;
2290 			besterr = addr - symaddr;
2291 			if (addr == symaddr)
2292 				break;
2293 		}
2294 	}
2295 
2296 	if (best && besterr > bestsym->st_size-1) {
2297 		best = 0;
2298 		bestsym = 0;
2299 	}
2300 
2301 	info->dli_fname = p->name;
2302 	info->dli_fbase = p->map;
2303 
2304 	if (!best) {
2305 		info->dli_sname = 0;
2306 		info->dli_saddr = 0;
2307 		return 1;
2308 	}
2309 
2310 	if (DL_FDPIC && (bestsym->st_info&0xf) == STT_FUNC)
2311 		best = (size_t)(p->funcdescs + (bestsym - p->syms));
2312 	info->dli_sname = strings + bestsym->st_name;
2313 	info->dli_saddr = (void *)best;
2314 
2315 	return 1;
2316 }
2317 
__dlsym(void * restrict p,const char * restrict s,void * restrict ra)2318 hidden void *__dlsym(void *restrict p, const char *restrict s, void *restrict ra)
2319 {
2320 	void *res;
2321 	pthread_rwlock_rdlock(&lock);
2322 	res = do_dlsym(p, s, ra);
2323 	pthread_rwlock_unlock(&lock);
2324 	return res;
2325 }
2326 
__dlsym_redir_time64(void * restrict p,const char * restrict s,void * restrict ra)2327 hidden void *__dlsym_redir_time64(void *restrict p, const char *restrict s, void *restrict ra)
2328 {
2329 #if _REDIR_TIME64
2330 	const char *suffix, *suffix2 = "";
2331 	char redir[36];
2332 
2333 	/* Map the symbol name to a time64 version of itself according to the
2334 	 * pattern used for naming the redirected time64 symbols. */
2335 	size_t l = strnlen(s, sizeof redir);
2336 	if (l<4 || l==sizeof redir) goto no_redir;
2337 	if (s[l-2]=='_' && s[l-1]=='r') {
2338 		l -= 2;
2339 		suffix2 = s+l;
2340 	}
2341 	if (l<4) goto no_redir;
2342 	if (!strcmp(s+l-4, "time")) suffix = "64";
2343 	else suffix = "_time64";
2344 
2345 	/* Use the presence of the remapped symbol name in libc to determine
2346 	 * whether it's one that requires time64 redirection; replace if so. */
2347 	snprintf(redir, sizeof redir, "__%.*s%s%s", (int)l, s, suffix, suffix2);
2348 	if (find_sym(&ldso, redir, 1).sym) s = redir;
2349 no_redir:
2350 #endif
2351 	return __dlsym(p, s, ra);
2352 }
2353 
dl_iterate_phdr(int (* callback)(struct dl_phdr_info * info,size_t size,void * data),void * data)2354 int dl_iterate_phdr(int(*callback)(struct dl_phdr_info *info, size_t size, void *data), void *data)
2355 {
2356 	struct dso *current;
2357 	struct dl_phdr_info info;
2358 	int ret = 0;
2359 	for(current = head; current;) {
2360 		info.dlpi_addr      = (uintptr_t)current->base;
2361 		info.dlpi_name      = current->name;
2362 		info.dlpi_phdr      = current->phdr;
2363 		info.dlpi_phnum     = current->phnum;
2364 		info.dlpi_adds      = gencnt;
2365 		info.dlpi_subs      = 0;
2366 		info.dlpi_tls_modid = current->tls_id;
2367 		info.dlpi_tls_data = !current->tls_id ? 0 :
2368 			__tls_get_addr((tls_mod_off_t[]){current->tls_id,0});
2369 
2370 		ret = (callback)(&info, sizeof (info), data);
2371 
2372 		if (ret != 0) break;
2373 
2374 		pthread_rwlock_rdlock(&lock);
2375 		current = current->next;
2376 		pthread_rwlock_unlock(&lock);
2377 	}
2378 	return ret;
2379 }
2380 
error(const char * fmt,...)2381 static void error(const char *fmt, ...)
2382 {
2383 	va_list ap;
2384 	va_start(ap, fmt);
2385 	if (!runtime) {
2386 		vdprintf(2, fmt, ap);
2387 		dprintf(2, "\n");
2388 		ldso_fail = 1;
2389 		va_end(ap);
2390 		return;
2391 	}
2392 	__dl_vseterr(fmt, ap);
2393 	va_end(ap);
2394 }
2395