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