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