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