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