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