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