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