2 #define SYSCALL_NO_TLS 1
21 #include <semaphore.h>
22 #include <sys/membarrier.h>
23 #include "pthread_impl.h"
26 #include "malloc_impl.h"
28 static void error(const char *, ...);
30 #define MAXP2(a,b) (-(-(a)&-(b)))
31 #define ALIGN(x,y) ((x)+(y)-1 & -(y))
33 #define container_of(p,t,m) ((t*)((char *)(p)-offsetof(t,m)))
34 #define countof(a) ((sizeof (a))/(sizeof (a)[0]))
46 struct td_index
*next
;
51 struct fdpic_loadmap
*loadmap
;
57 struct dso
*next
, *prev
;
67 struct dso
*syms_next
, *lazy_next
;
68 size_t *lazy
, lazy_cnt
;
79 struct dso
**deps
, *needed_by
;
83 char *rpath_orig
, *rpath
;
84 struct tls_module tls
;
86 size_t relro_start
, relro_end
;
88 unsigned char *new_tls
;
89 struct td_index
*td_index
;
90 struct dso
*fini_next
;
95 struct fdpic_loadmap
*loadmap
;
110 typedef void (*stage3_func
)(size_t *, size_t *);
112 static struct builtin_tls
{
117 #define MIN_TLS_ALIGN offsetof(struct builtin_tls, pt)
119 #define ADDEND_LIMIT 4096
120 static size_t *saved_addends
, *apply_addends_to
;
122 static struct dso ldso
;
123 static struct dso
*head
, *tail
, *fini_head
, *syms_tail
, *lazy_head
;
124 static char *env_path
, *sys_path
;
125 static unsigned long long gencnt
;
128 static int ldso_fail
;
130 static int shutting_down
;
131 static jmp_buf *rtld_fail
;
132 static pthread_rwlock_t lock
;
133 static struct debug debug
;
134 static struct tls_module
*tls_tail
;
135 static size_t tls_cnt
, tls_offset
, tls_align
= MIN_TLS_ALIGN
;
136 static size_t static_tls_cnt
;
137 static pthread_mutex_t init_fini_lock
;
138 static pthread_cond_t ctor_cond
;
139 static struct dso
*builtin_deps
[2];
140 static struct dso
*const no_deps
[1];
141 static struct dso
*builtin_ctor_queue
[4];
142 static struct dso
**main_ctor_queue
;
143 static struct fdpic_loadmap
*app_loadmap
;
144 static struct fdpic_dummy_loadmap app_dummy_loadmap
;
146 struct debug
*_dl_debug_addr
= &debug
;
148 extern hidden
int __malloc_replaced
;
150 hidden
void (*const __init_array_start
)(void)=0, (*const __fini_array_start
)(void)=0;
152 extern hidden
void (*const __init_array_end
)(void), (*const __fini_array_end
)(void);
154 weak_alias(__init_array_start
, __init_array_end
);
155 weak_alias(__fini_array_start
, __fini_array_end
);
157 static int dl_strcmp(const char *l
, const char *r
)
159 for (; *l
==*r
&& *l
; l
++, r
++);
160 return *(unsigned char *)l
- *(unsigned char *)r
;
162 #define strcmp(l,r) dl_strcmp(l,r)
164 /* Compute load address for a virtual address in a given dso. */
166 static void *laddr(const struct dso
*p
, size_t v
)
169 if (!p
->loadmap
) return p
->base
+ v
;
170 for (j
=0; v
-p
->loadmap
->segs
[j
].p_vaddr
>= p
->loadmap
->segs
[j
].p_memsz
; j
++);
171 return (void *)(v
- p
->loadmap
->segs
[j
].p_vaddr
+ p
->loadmap
->segs
[j
].addr
);
173 static void *laddr_pg(const struct dso
*p
, size_t v
)
176 size_t pgsz
= PAGE_SIZE
;
177 if (!p
->loadmap
) return p
->base
+ v
;
179 size_t a
= p
->loadmap
->segs
[j
].p_vaddr
;
180 size_t b
= a
+ p
->loadmap
->segs
[j
].p_memsz
;
186 return (void *)(v
- p
->loadmap
->segs
[j
].p_vaddr
+ p
->loadmap
->segs
[j
].addr
);
188 static void (*fdbarrier(void *p
))()
191 __asm__("" : "=r"(fd
) : "0"(p
));
194 #define fpaddr(p, v) fdbarrier((&(struct funcdesc){ \
195 laddr(p, v), (p)->got }))
197 #define laddr(p, v) (void *)((p)->base + (v))
198 #define laddr_pg(p, v) laddr(p, v)
199 #define fpaddr(p, v) ((void (*)())laddr(p, v))
202 static void decode_vec(size_t *v
, size_t *a
, size_t cnt
)
205 for (i
=0; i
<cnt
; i
++) a
[i
] = 0;
206 for (; v
[0]; v
+=2) if (v
[0]-1<cnt
-1) {
212 static int search_vec(size_t *v
, size_t *r
, size_t key
)
214 for (; v
[0]!=key
; v
+=2)
220 static uint32_t sysv_hash(const char *s0
)
222 const unsigned char *s
= (void *)s0
;
228 return h
& 0xfffffff;
231 static uint32_t gnu_hash(const char *s0
)
233 const unsigned char *s
= (void *)s0
;
234 uint_fast32_t h
= 5381;
240 static Sym
*sysv_lookup(const char *s
, uint32_t h
, struct dso
*dso
)
243 Sym
*syms
= dso
->syms
;
244 Elf_Symndx
*hashtab
= dso
->hashtab
;
245 char *strings
= dso
->strings
;
246 for (i
=hashtab
[2+h
%hashtab
[0]]; i
; i
=hashtab
[2+hashtab
[0]+i
]) {
247 if ((!dso
->versym
|| dso
->versym
[i
] >= 0)
248 && (!strcmp(s
, strings
+syms
[i
].st_name
)))
254 static Sym
*gnu_lookup(uint32_t h1
, uint32_t *hashtab
, struct dso
*dso
, const char *s
)
256 uint32_t nbuckets
= hashtab
[0];
257 uint32_t *buckets
= hashtab
+ 4 + hashtab
[2]*(sizeof(size_t)/4);
258 uint32_t i
= buckets
[h1
% nbuckets
];
262 uint32_t *hashval
= buckets
+ nbuckets
+ (i
- hashtab
[1]);
264 for (h1
|= 1; ; i
++) {
265 uint32_t h2
= *hashval
++;
266 if ((h1
== (h2
|1)) && (!dso
->versym
|| dso
->versym
[i
] >= 0)
267 && !strcmp(s
, dso
->strings
+ dso
->syms
[i
].st_name
))
275 static Sym
*gnu_lookup_filtered(uint32_t h1
, uint32_t *hashtab
, struct dso
*dso
, const char *s
, uint32_t fofs
, size_t fmask
)
277 const size_t *bloomwords
= (const void *)(hashtab
+4);
278 size_t f
= bloomwords
[fofs
& (hashtab
[2]-1)];
279 if (!(f
& fmask
)) return 0;
281 f
>>= (h1
>> hashtab
[3]) % (8 * sizeof f
);
282 if (!(f
& 1)) return 0;
284 return gnu_lookup(h1
, hashtab
, dso
, s
);
287 #define OK_TYPES (1<<STT_NOTYPE | 1<<STT_OBJECT | 1<<STT_FUNC | 1<<STT_COMMON | 1<<STT_TLS)
288 #define OK_BINDS (1<<STB_GLOBAL | 1<<STB_WEAK | 1<<STB_GNU_UNIQUE)
290 #ifndef ARCH_SYM_REJECT_UND
291 #define ARCH_SYM_REJECT_UND(s) 0
294 #if defined(__GNUC__)
295 __attribute__((always_inline
))
297 static inline struct symdef
find_sym2(struct dso
*dso
, const char *s
, int need_def
, int use_deps
)
299 uint32_t h
= 0, gh
= gnu_hash(s
), gho
= gh
/ (8*sizeof(size_t)), *ght
;
300 size_t ghm
= 1ul << gh
% (8*sizeof(size_t));
301 struct symdef def
= {0};
302 struct dso
**deps
= use_deps
? dso
->deps
: 0;
303 for (; dso
; dso
=use_deps
? *deps
++ : dso
->syms_next
) {
305 if ((ght
= dso
->ghashtab
)) {
306 sym
= gnu_lookup_filtered(gh
, ght
, dso
, s
, gho
, ghm
);
308 if (!h
) h
= sysv_hash(s
);
309 sym
= sysv_lookup(s
, h
, dso
);
313 if (need_def
|| (sym
->st_info
&0xf) == STT_TLS
314 || ARCH_SYM_REJECT_UND(sym
))
317 if ((sym
->st_info
&0xf) != STT_TLS
)
319 if (!(1<<(sym
->st_info
&0xf) & OK_TYPES
)) continue;
320 if (!(1<<(sym
->st_info
>>4) & OK_BINDS
)) continue;
328 static struct symdef
find_sym(struct dso
*dso
, const char *s
, int need_def
)
330 return find_sym2(dso
, s
, need_def
, 0);
333 static void do_relocs(struct dso
*dso
, size_t *rel
, size_t rel_size
, size_t stride
)
335 unsigned char *base
= dso
->base
;
336 Sym
*syms
= dso
->syms
;
337 char *strings
= dso
->strings
;
348 int skip_relative
= 0, reuse_addends
= 0, save_slot
= 0;
351 /* Only ldso's REL table needs addend saving/reuse. */
352 if (rel
== apply_addends_to
)
357 for (; rel_size
; rel
+=stride
, rel_size
-=stride
*sizeof(size_t)) {
358 if (skip_relative
&& IS_RELATIVE(rel
[1], dso
->syms
)) continue;
359 type
= R_TYPE(rel
[1]);
360 if (type
== REL_NONE
) continue;
361 reloc_addr
= laddr(dso
, rel
[0]);
365 } else if (type
==REL_GOT
|| type
==REL_PLT
|| type
==REL_COPY
) {
367 } else if (reuse_addends
) {
368 /* Save original addend in stage 2 where the dso
369 * chain consists of just ldso; otherwise read back
370 * saved addend since the inline one was clobbered. */
372 saved_addends
[save_slot
] = *reloc_addr
;
373 addend
= saved_addends
[save_slot
++];
375 addend
= *reloc_addr
;
378 sym_index
= R_SYM(rel
[1]);
380 sym
= syms
+ sym_index
;
381 name
= strings
+ sym
->st_name
;
382 ctx
= type
==REL_COPY
? head
->syms_next
: head
;
383 def
= (sym
->st_info
>>4) == STB_LOCAL
384 ? (struct symdef
){ .dso
= dso
, .sym
= sym
}
385 : find_sym(ctx
, name
, type
==REL_PLT
);
386 if (!def
.sym
&& (sym
->st_shndx
!= SHN_UNDEF
387 || sym
->st_info
>>4 != STB_WEAK
)) {
388 if (dso
->lazy
&& (type
==REL_PLT
|| type
==REL_GOT
)) {
389 dso
->lazy
[3*dso
->lazy_cnt
+0] = rel
[0];
390 dso
->lazy
[3*dso
->lazy_cnt
+1] = rel
[1];
391 dso
->lazy
[3*dso
->lazy_cnt
+2] = addend
;
395 error("Error relocating %s: %s: symbol not found",
397 if (runtime
) longjmp(*rtld_fail
, 1);
406 sym_val
= def
.sym
? (size_t)laddr(def
.dso
, def
.sym
->st_value
) : 0;
407 tls_val
= def
.sym
? def
.sym
->st_value
: 0;
409 if ((type
== REL_TPOFF
|| type
== REL_TPOFF_NEG
)
410 && def
.dso
->tls_id
> static_tls_cnt
) {
411 error("Error relocating %s: %s: initial-exec TLS "
412 "resolves to dynamic definition in %s",
413 dso
->name
, name
, def
.dso
->name
);
414 longjmp(*rtld_fail
, 1);
419 addend
-= (size_t)reloc_addr
;
423 *reloc_addr
= sym_val
+ addend
;
426 memcpy(reloc_addr
, &(size_t){sym_val
+ addend
}, sizeof(size_t));
429 *reloc_addr
= (size_t)base
+ addend
;
432 if (sym
) *reloc_addr
= sym_val
+ addend
;
433 else *reloc_addr
= (size_t)base
+ addend
;
436 memcpy(reloc_addr
, (void *)sym_val
, sym
->st_size
);
439 *(uint32_t *)reloc_addr
= sym_val
+ addend
440 - (size_t)reloc_addr
;
443 *reloc_addr
= def
.sym
? (size_t)(def
.dso
->funcdescs
444 + (def
.sym
- def
.dso
->syms
)) : 0;
446 case REL_FUNCDESC_VAL
:
447 if ((sym
->st_info
&0xf) == STT_SECTION
) *reloc_addr
+= sym_val
;
448 else *reloc_addr
= sym_val
;
449 reloc_addr
[1] = def
.sym
? (size_t)def
.dso
->got
: 0;
452 *reloc_addr
= def
.dso
->tls_id
;
455 *reloc_addr
= tls_val
+ addend
- DTP_OFFSET
;
459 *reloc_addr
= tls_val
+ def
.dso
->tls
.offset
+ TPOFF_K
+ addend
;
463 *reloc_addr
= tls_val
- def
.dso
->tls
.offset
+ addend
;
466 *reloc_addr
= def
.dso
->tls
.offset
- tls_val
+ addend
;
470 if (stride
<3) addend
= reloc_addr
[1];
471 if (def
.dso
->tls_id
> static_tls_cnt
) {
472 struct td_index
*new = malloc(sizeof *new);
475 "Error relocating %s: cannot allocate TLSDESC for %s",
476 dso
->name
, sym
? name
: "(local)" );
477 longjmp(*rtld_fail
, 1);
479 new->next
= dso
->td_index
;
481 new->args
[0] = def
.dso
->tls_id
;
482 new->args
[1] = tls_val
+ addend
- DTP_OFFSET
;
483 reloc_addr
[0] = (size_t)__tlsdesc_dynamic
;
484 reloc_addr
[1] = (size_t)new;
486 reloc_addr
[0] = (size_t)__tlsdesc_static
;
488 reloc_addr
[1] = tls_val
+ def
.dso
->tls
.offset
491 reloc_addr
[1] = tls_val
- def
.dso
->tls
.offset
495 #ifdef TLSDESC_BACKWARDS
496 /* Some archs (32-bit ARM at least) invert the order of
497 * the descriptor members. Fix them up here. */
498 size_t tmp
= reloc_addr
[0];
499 reloc_addr
[0] = reloc_addr
[1];
504 error("Error relocating %s: unsupported relocation type %d",
506 if (runtime
) longjmp(*rtld_fail
, 1);
512 static void redo_lazy_relocs()
514 struct dso
*p
= lazy_head
, *next
;
518 size_t size
= p
->lazy_cnt
*3*sizeof(size_t);
520 do_relocs(p
, p
->lazy
, size
, 3);
522 p
->lazy_next
= lazy_head
;
532 /* A huge hack: to make up for the wastefulness of shared libraries
533 * needing at least a page of dirty memory even if they have no global
534 * data, we reclaim the gaps at the beginning and end of writable maps
535 * and "donate" them to the heap. */
537 static void reclaim(struct dso
*dso
, size_t start
, size_t end
)
539 if (start
>= dso
->relro_start
&& start
< dso
->relro_end
) start
= dso
->relro_end
;
540 if (end
>= dso
->relro_start
&& end
< dso
->relro_end
) end
= dso
->relro_start
;
541 if (start
>= end
) return;
542 char *base
= laddr_pg(dso
, start
);
543 __malloc_donate(base
, base
+(end
-start
));
546 static void reclaim_gaps(struct dso
*dso
)
548 Phdr
*ph
= dso
->phdr
;
549 size_t phcnt
= dso
->phnum
;
551 for (; phcnt
--; ph
=(void *)((char *)ph
+dso
->phentsize
)) {
552 if (ph
->p_type
!=PT_LOAD
) continue;
553 if ((ph
->p_flags
&(PF_R
|PF_W
))!=(PF_R
|PF_W
)) continue;
554 reclaim(dso
, ph
->p_vaddr
& -PAGE_SIZE
, ph
->p_vaddr
);
555 reclaim(dso
, ph
->p_vaddr
+ph
->p_memsz
,
556 ph
->p_vaddr
+ph
->p_memsz
+PAGE_SIZE
-1 & -PAGE_SIZE
);
560 static void *mmap_fixed(void *p
, size_t n
, int prot
, int flags
, int fd
, off_t off
)
562 static int no_map_fixed
;
565 q
= mmap(p
, n
, prot
, flags
|MAP_FIXED
, fd
, off
);
566 if (!DL_NOMMU_SUPPORT
|| q
!= MAP_FAILED
|| errno
!= EINVAL
)
570 /* Fallbacks for MAP_FIXED failure on NOMMU kernels. */
571 if (flags
& MAP_ANONYMOUS
) {
576 if (lseek(fd
, off
, SEEK_SET
) < 0) return MAP_FAILED
;
577 for (q
=p
; n
; q
+=r
, off
+=r
, n
-=r
) {
579 if (r
< 0 && errno
!= EINTR
) return MAP_FAILED
;
588 static void unmap_library(struct dso
*dso
)
592 for (i
=0; i
<dso
->loadmap
->nsegs
; i
++) {
593 if (!dso
->loadmap
->segs
[i
].p_memsz
)
595 munmap((void *)dso
->loadmap
->segs
[i
].addr
,
596 dso
->loadmap
->segs
[i
].p_memsz
);
599 } else if (dso
->map
&& dso
->map_len
) {
600 munmap(dso
->map
, dso
->map_len
);
604 static void *map_library(int fd
, struct dso
*dso
)
606 Ehdr buf
[(896+sizeof(Ehdr
))/sizeof(Ehdr
)];
607 void *allocated_buf
=0;
609 size_t addr_min
=SIZE_MAX
, addr_max
=0, map_len
;
610 size_t this_min
, this_max
;
616 unsigned char *map
=MAP_FAILED
, *base
;
621 ssize_t l
= read(fd
, buf
, sizeof buf
);
624 if (l
<sizeof *eh
|| (eh
->e_type
!= ET_DYN
&& eh
->e_type
!= ET_EXEC
))
626 phsize
= eh
->e_phentsize
* eh
->e_phnum
;
627 if (phsize
> sizeof buf
- sizeof *eh
) {
628 allocated_buf
= malloc(phsize
);
629 if (!allocated_buf
) return 0;
630 l
= pread(fd
, allocated_buf
, phsize
, eh
->e_phoff
);
631 if (l
< 0) goto error
;
632 if (l
!= phsize
) goto noexec
;
633 ph
= ph0
= allocated_buf
;
634 } else if (eh
->e_phoff
+ phsize
> l
) {
635 l
= pread(fd
, buf
+1, phsize
, eh
->e_phoff
);
636 if (l
< 0) goto error
;
637 if (l
!= phsize
) goto noexec
;
638 ph
= ph0
= (void *)(buf
+ 1);
640 ph
= ph0
= (void *)((char *)buf
+ eh
->e_phoff
);
642 for (i
=eh
->e_phnum
; i
; i
--, ph
=(void *)((char *)ph
+eh
->e_phentsize
)) {
643 if (ph
->p_type
== PT_DYNAMIC
) {
645 } else if (ph
->p_type
== PT_TLS
) {
646 tls_image
= ph
->p_vaddr
;
647 dso
->tls
.align
= ph
->p_align
;
648 dso
->tls
.len
= ph
->p_filesz
;
649 dso
->tls
.size
= ph
->p_memsz
;
650 } else if (ph
->p_type
== PT_GNU_RELRO
) {
651 dso
->relro_start
= ph
->p_vaddr
& -PAGE_SIZE
;
652 dso
->relro_end
= (ph
->p_vaddr
+ ph
->p_memsz
) & -PAGE_SIZE
;
653 } else if (ph
->p_type
== PT_GNU_STACK
) {
654 if (!runtime
&& ph
->p_memsz
> __default_stacksize
) {
655 __default_stacksize
=
656 ph
->p_memsz
< DEFAULT_STACK_MAX
?
657 ph
->p_memsz
: DEFAULT_STACK_MAX
;
660 if (ph
->p_type
!= PT_LOAD
) continue;
662 if (ph
->p_vaddr
< addr_min
) {
663 addr_min
= ph
->p_vaddr
;
664 off_start
= ph
->p_offset
;
665 prot
= (((ph
->p_flags
&PF_R
) ? PROT_READ
: 0) |
666 ((ph
->p_flags
&PF_W
) ? PROT_WRITE
: 0) |
667 ((ph
->p_flags
&PF_X
) ? PROT_EXEC
: 0));
669 if (ph
->p_vaddr
+ph
->p_memsz
> addr_max
) {
670 addr_max
= ph
->p_vaddr
+ph
->p_memsz
;
673 if (!dyn
) goto noexec
;
674 if (DL_FDPIC
&& !(eh
->e_flags
& FDPIC_CONSTDISP_FLAG
)) {
675 dso
->loadmap
= calloc(1, sizeof *dso
->loadmap
676 + nsegs
* sizeof *dso
->loadmap
->segs
);
677 if (!dso
->loadmap
) goto error
;
678 dso
->loadmap
->nsegs
= nsegs
;
679 for (ph
=ph0
, i
=0; i
<nsegs
; ph
=(void *)((char *)ph
+eh
->e_phentsize
)) {
680 if (ph
->p_type
!= PT_LOAD
) continue;
681 prot
= (((ph
->p_flags
&PF_R
) ? PROT_READ
: 0) |
682 ((ph
->p_flags
&PF_W
) ? PROT_WRITE
: 0) |
683 ((ph
->p_flags
&PF_X
) ? PROT_EXEC
: 0));
684 map
= mmap(0, ph
->p_memsz
+ (ph
->p_vaddr
& PAGE_SIZE
-1),
686 fd
, ph
->p_offset
& -PAGE_SIZE
);
687 if (map
== MAP_FAILED
) {
691 dso
->loadmap
->segs
[i
].addr
= (size_t)map
+
692 (ph
->p_vaddr
& PAGE_SIZE
-1);
693 dso
->loadmap
->segs
[i
].p_vaddr
= ph
->p_vaddr
;
694 dso
->loadmap
->segs
[i
].p_memsz
= ph
->p_memsz
;
696 if (prot
& PROT_WRITE
) {
697 size_t brk
= (ph
->p_vaddr
& PAGE_SIZE
-1)
699 size_t pgbrk
= brk
+ PAGE_SIZE
-1 & -PAGE_SIZE
;
700 size_t pgend
= brk
+ ph
->p_memsz
- ph
->p_filesz
701 + PAGE_SIZE
-1 & -PAGE_SIZE
;
702 if (pgend
> pgbrk
&& mmap_fixed(map
+pgbrk
,
704 MAP_PRIVATE
|MAP_FIXED
|MAP_ANONYMOUS
,
705 -1, off_start
) == MAP_FAILED
)
707 memset(map
+ brk
, 0, pgbrk
-brk
);
710 map
= (void *)dso
->loadmap
->segs
[0].addr
;
714 addr_max
+= PAGE_SIZE
-1;
715 addr_max
&= -PAGE_SIZE
;
716 addr_min
&= -PAGE_SIZE
;
717 off_start
&= -PAGE_SIZE
;
718 map_len
= addr_max
- addr_min
+ off_start
;
719 /* The first time, we map too much, possibly even more than
720 * the length of the file. This is okay because we will not
721 * use the invalid part; we just need to reserve the right
722 * amount of virtual address space to map over later. */
723 map
= DL_NOMMU_SUPPORT
724 ? mmap((void *)addr_min
, map_len
, PROT_READ
|PROT_WRITE
|PROT_EXEC
,
725 MAP_PRIVATE
|MAP_ANONYMOUS
, -1, 0)
726 : mmap((void *)addr_min
, map_len
, prot
,
727 MAP_PRIVATE
, fd
, off_start
);
728 if (map
==MAP_FAILED
) goto error
;
730 dso
->map_len
= map_len
;
731 /* If the loaded file is not relocatable and the requested address is
732 * not available, then the load operation must fail. */
733 if (eh
->e_type
!= ET_DYN
&& addr_min
&& map
!=(void *)addr_min
) {
737 base
= map
- addr_min
;
740 for (ph
=ph0
, i
=eh
->e_phnum
; i
; i
--, ph
=(void *)((char *)ph
+eh
->e_phentsize
)) {
741 if (ph
->p_type
!= PT_LOAD
) continue;
742 /* Check if the programs headers are in this load segment, and
743 * if so, record the address for use by dl_iterate_phdr. */
744 if (!dso
->phdr
&& eh
->e_phoff
>= ph
->p_offset
745 && eh
->e_phoff
+phsize
<= ph
->p_offset
+ph
->p_filesz
) {
746 dso
->phdr
= (void *)(base
+ ph
->p_vaddr
747 + (eh
->e_phoff
-ph
->p_offset
));
748 dso
->phnum
= eh
->e_phnum
;
749 dso
->phentsize
= eh
->e_phentsize
;
751 this_min
= ph
->p_vaddr
& -PAGE_SIZE
;
752 this_max
= ph
->p_vaddr
+ph
->p_memsz
+PAGE_SIZE
-1 & -PAGE_SIZE
;
753 off_start
= ph
->p_offset
& -PAGE_SIZE
;
754 prot
= (((ph
->p_flags
&PF_R
) ? PROT_READ
: 0) |
755 ((ph
->p_flags
&PF_W
) ? PROT_WRITE
: 0) |
756 ((ph
->p_flags
&PF_X
) ? PROT_EXEC
: 0));
757 /* Reuse the existing mapping for the lowest-address LOAD */
758 if ((ph
->p_vaddr
& -PAGE_SIZE
) != addr_min
|| DL_NOMMU_SUPPORT
)
759 if (mmap_fixed(base
+this_min
, this_max
-this_min
, prot
, MAP_PRIVATE
|MAP_FIXED
, fd
, off_start
) == MAP_FAILED
)
761 if (ph
->p_memsz
> ph
->p_filesz
&& (ph
->p_flags
&PF_W
)) {
762 size_t brk
= (size_t)base
+ph
->p_vaddr
+ph
->p_filesz
;
763 size_t pgbrk
= brk
+PAGE_SIZE
-1 & -PAGE_SIZE
;
764 memset((void *)brk
, 0, pgbrk
-brk
& PAGE_SIZE
-1);
765 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
)
769 for (i
=0; ((size_t *)(base
+dyn
))[i
]; i
+=2)
770 if (((size_t *)(base
+dyn
))[i
]==DT_TEXTREL
) {
771 if (mprotect(map
, map_len
, PROT_READ
|PROT_WRITE
|PROT_EXEC
)
778 dso
->dynv
= laddr(dso
, dyn
);
779 if (dso
->tls
.size
) dso
->tls
.image
= laddr(dso
, tls_image
);
785 if (map
!=MAP_FAILED
) unmap_library(dso
);
790 static int path_open(const char *name
, const char *s
, char *buf
, size_t buf_size
)
795 s
+= strspn(s
, ":\n");
796 l
= strcspn(s
, ":\n");
797 if (l
-1 >= INT_MAX
) return -1;
798 if (snprintf(buf
, buf_size
, "%.*s/%s", (int)l
, s
, name
) < buf_size
) {
799 if ((fd
= open(buf
, O_RDONLY
|O_CLOEXEC
))>=0) return fd
;
807 /* Any negative value but -1 will inhibit
808 * futher path search. */
816 static int fixup_rpath(struct dso
*p
, char *buf
, size_t buf_size
)
819 const char *s
, *t
, *origin
;
821 if (p
->rpath
|| !p
->rpath_orig
) return 0;
822 if (!strchr(p
->rpath_orig
, '$')) {
823 p
->rpath
= p
->rpath_orig
;
828 while ((t
=strchr(s
, '$'))) {
829 if (strncmp(t
, "$ORIGIN", 7) && strncmp(t
, "${ORIGIN}", 9))
834 if (n
> SSIZE_MAX
/PATH_MAX
) return 0;
836 if (p
->kernel_mapped
) {
837 /* $ORIGIN searches cannot be performed for the main program
838 * when it is suid/sgid/AT_SECURE. This is because the
839 * pathname is under the control of the caller of execve.
840 * For libraries, however, $ORIGIN can be processed safely
841 * since the library's pathname came from a trusted source
842 * (either system paths or a call to dlopen). */
845 l
= readlink("/proc/self/exe", buf
, buf_size
);
846 if (l
== -1) switch (errno
) {
861 t
= strrchr(origin
, '/');
865 /* Normally p->name will always be an absolute or relative
866 * pathname containing at least one '/' character, but in the
867 * case where ldso was invoked as a command to execute a
868 * program in the working directory, app.name may not. Fix. */
872 /* Disallow non-absolute origins for suid/sgid/AT_SECURE. */
873 if (libc
.secure
&& *origin
!= '/')
875 p
->rpath
= malloc(strlen(p
->rpath_orig
) + n
*l
+ 1);
876 if (!p
->rpath
) return -1;
880 while ((t
=strchr(s
, '$'))) {
883 memcpy(d
, origin
, l
);
885 /* It was determined previously that the '$' is followed
886 * either by "ORIGIN" or "{ORIGIN}". */
887 s
= t
+ 7 + 2*(t
[1]=='{');
893 static void decode_dyn(struct dso
*p
)
896 decode_vec(p
->dynv
, dyn
, DYN_CNT
);
897 p
->syms
= laddr(p
, dyn
[DT_SYMTAB
]);
898 p
->strings
= laddr(p
, dyn
[DT_STRTAB
]);
899 if (dyn
[0]&(1<<DT_HASH
))
900 p
->hashtab
= laddr(p
, dyn
[DT_HASH
]);
901 if (dyn
[0]&(1<<DT_RPATH
))
902 p
->rpath_orig
= p
->strings
+ dyn
[DT_RPATH
];
903 if (dyn
[0]&(1<<DT_RUNPATH
))
904 p
->rpath_orig
= p
->strings
+ dyn
[DT_RUNPATH
];
905 if (dyn
[0]&(1<<DT_PLTGOT
))
906 p
->got
= laddr(p
, dyn
[DT_PLTGOT
]);
907 if (search_vec(p
->dynv
, dyn
, DT_GNU_HASH
))
908 p
->ghashtab
= laddr(p
, *dyn
);
909 if (search_vec(p
->dynv
, dyn
, DT_VERSYM
))
910 p
->versym
= laddr(p
, *dyn
);
913 static size_t count_syms(struct dso
*p
)
915 if (p
->hashtab
) return p
->hashtab
[1];
918 uint32_t *buckets
= p
->ghashtab
+ 4 + (p
->ghashtab
[2]*sizeof(size_t)/4);
920 for (i
= nsym
= 0; i
< p
->ghashtab
[0]; i
++) {
921 if (buckets
[i
] > nsym
)
925 hashval
= buckets
+ p
->ghashtab
[0] + (nsym
- p
->ghashtab
[1]);
927 while (!(*hashval
++ & 1));
932 static void *dl_mmap(size_t n
)
935 int prot
= PROT_READ
|PROT_WRITE
, flags
= MAP_ANONYMOUS
|MAP_PRIVATE
;
937 p
= (void *)__syscall(SYS_mmap2
, 0, n
, prot
, flags
, -1, 0);
939 p
= (void *)__syscall(SYS_mmap
, 0, n
, prot
, flags
, -1, 0);
941 return (unsigned long)p
> -4096UL ? 0 : p
;
944 static void makefuncdescs(struct dso
*p
)
946 static int self_done
;
947 size_t nsym
= count_syms(p
);
948 size_t i
, size
= nsym
* sizeof(*p
->funcdescs
);
951 p
->funcdescs
= dl_mmap(size
);
954 p
->funcdescs
= malloc(size
);
957 if (!runtime
) a_crash();
958 error("Error allocating function descriptors for %s", p
->name
);
959 longjmp(*rtld_fail
, 1);
961 for (i
=0; i
<nsym
; i
++) {
962 if ((p
->syms
[i
].st_info
&0xf)==STT_FUNC
&& p
->syms
[i
].st_shndx
) {
963 p
->funcdescs
[i
].addr
= laddr(p
, p
->syms
[i
].st_value
);
964 p
->funcdescs
[i
].got
= p
->got
;
966 p
->funcdescs
[i
].addr
= 0;
967 p
->funcdescs
[i
].got
= 0;
972 static struct dso
*load_library(const char *name
, struct dso
*needed_by
)
974 char buf
[2*NAME_MAX
+2];
975 const char *pathname
;
977 struct dso
*p
, temp_dso
= {0};
989 /* Catch and block attempts to reload the implementation itself */
990 if (name
[0]=='l' && name
[1]=='i' && name
[2]=='b') {
991 static const char reserved
[] =
992 "c.pthread.rt.m.dl.util.xnet.";
993 const char *rp
, *next
;
994 for (rp
=reserved
; *rp
; rp
=next
) {
995 next
= strchr(rp
, '.') + 1;
996 if (strncmp(name
+3, rp
, next
-rp
) == 0)
1001 /* Track which names have been resolved
1002 * and only report each one once. */
1003 static unsigned reported
;
1004 unsigned mask
= 1U<<(rp
-reserved
);
1005 if (!(reported
& mask
)) {
1007 dprintf(1, "\t%s => %s (%p)\n",
1015 if (!strcmp(name
, ldso
.name
)) is_self
= 1;
1024 if (strchr(name
, '/')) {
1026 fd
= open(name
, O_RDONLY
|O_CLOEXEC
);
1028 /* Search for the name to see if it's already loaded */
1029 for (p
=head
->next
; p
; p
=p
->next
) {
1030 if (p
->shortname
&& !strcmp(p
->shortname
, name
)) {
1034 if (strlen(name
) > NAME_MAX
) return 0;
1036 if (env_path
) fd
= path_open(name
, env_path
, buf
, sizeof buf
);
1037 for (p
=needed_by
; fd
== -1 && p
; p
=p
->needed_by
) {
1038 if (fixup_rpath(p
, buf
, sizeof buf
) < 0)
1039 fd
= -2; /* Inhibit further search. */
1041 fd
= path_open(name
, p
->rpath
, buf
, sizeof buf
);
1047 if (ldso
.name
[0]=='/') {
1049 for (s
=t
=z
=ldso
.name
; *s
; s
++)
1050 if (*s
=='/') z
=t
, t
=s
;
1051 prefix_len
= z
-ldso
.name
;
1052 if (prefix_len
< PATH_MAX
)
1059 char etc_ldso_path
[prefix_len
+ 1
1060 + sizeof "/etc/ld-musl-" LDSO_ARCH
".path"];
1061 snprintf(etc_ldso_path
, sizeof etc_ldso_path
,
1062 "%.*s/etc/ld-musl-" LDSO_ARCH
".path",
1063 (int)prefix_len
, prefix
);
1064 FILE *f
= fopen(etc_ldso_path
, "rbe");
1066 if (getdelim(&sys_path
, (size_t[1]){0}, 0, f
) <= 0) {
1071 } else if (errno
!= ENOENT
) {
1075 if (!sys_path
) sys_path
= "/lib:/usr/local/lib:/usr/lib";
1076 fd
= path_open(name
, sys_path
, buf
, sizeof buf
);
1080 if (fd
< 0) return 0;
1081 if (fstat(fd
, &st
) < 0) {
1085 for (p
=head
->next
; p
; p
=p
->next
) {
1086 if (p
->dev
== st
.st_dev
&& p
->ino
== st
.st_ino
) {
1087 /* If this library was previously loaded with a
1088 * pathname but a search found the same inode,
1089 * setup its shortname so it can be found by name. */
1090 if (!p
->shortname
&& pathname
!= name
)
1091 p
->shortname
= strrchr(p
->name
, '/')+1;
1096 map
= noload
? 0 : map_library(fd
, &temp_dso
);
1100 /* Avoid the danger of getting two versions of libc mapped into the
1101 * same process when an absolute pathname was used. The symbols
1102 * checked are chosen to catch both musl and glibc, and to avoid
1103 * false positives from interposition-hack libraries. */
1104 decode_dyn(&temp_dso
);
1105 if (find_sym(&temp_dso
, "__libc_start_main", 1).sym
&&
1106 find_sym(&temp_dso
, "stdin", 1).sym
) {
1107 unmap_library(&temp_dso
);
1108 return load_library("libc.so", needed_by
);
1110 /* Past this point, if we haven't reached runtime yet, ldso has
1111 * committed either to use the mapped library or to abort execution.
1112 * Unmapping is not possible, so we can safely reclaim gaps. */
1113 if (!runtime
) reclaim_gaps(&temp_dso
);
1115 /* Allocate storage for the new DSO. When there is TLS, this
1116 * storage must include a reservation for all pre-existing
1117 * threads to obtain copies of both the new TLS, and an
1118 * extended DTV capable of storing an additional slot for
1119 * the newly-loaded DSO. */
1120 alloc_size
= sizeof *p
+ strlen(pathname
) + 1;
1121 if (runtime
&& temp_dso
.tls
.image
) {
1122 size_t per_th
= temp_dso
.tls
.size
+ temp_dso
.tls
.align
1123 + sizeof(void *) * (tls_cnt
+3);
1124 n_th
= libc
.threads_minus_1
+ 1;
1125 if (n_th
> SSIZE_MAX
/ per_th
) alloc_size
= SIZE_MAX
;
1126 else alloc_size
+= n_th
* per_th
;
1128 p
= calloc(1, alloc_size
);
1130 unmap_library(&temp_dso
);
1133 memcpy(p
, &temp_dso
, sizeof temp_dso
);
1136 p
->needed_by
= needed_by
;
1138 p
->runtime_loaded
= runtime
;
1139 strcpy(p
->name
, pathname
);
1140 /* Add a shortname only if name arg was not an explicit pathname. */
1141 if (pathname
!= name
) p
->shortname
= strrchr(p
->name
, '/')+1;
1143 p
->tls_id
= ++tls_cnt
;
1144 tls_align
= MAXP2(tls_align
, p
->tls
.align
);
1146 p
->tls
.offset
= tls_offset
+ ( (p
->tls
.align
-1) &
1147 (-tls_offset
+ (uintptr_t)p
->tls
.image
) );
1148 tls_offset
= p
->tls
.offset
+ p
->tls
.size
;
1150 tls_offset
+= p
->tls
.size
+ p
->tls
.align
- 1;
1151 tls_offset
-= (tls_offset
+ (uintptr_t)p
->tls
.image
)
1153 p
->tls
.offset
= tls_offset
;
1155 p
->new_dtv
= (void *)(-sizeof(size_t) &
1156 (uintptr_t)(p
->name
+strlen(p
->name
)+sizeof(size_t)));
1157 p
->new_tls
= (void *)(p
->new_dtv
+ n_th
*(tls_cnt
+1));
1158 if (tls_tail
) tls_tail
->next
= &p
->tls
;
1159 else libc
.tls_head
= &p
->tls
;
1167 if (DL_FDPIC
) makefuncdescs(p
);
1169 if (ldd_mode
) dprintf(1, "\t%s => %s (%p)\n", name
, pathname
, p
->base
);
1174 static void load_direct_deps(struct dso
*p
)
1178 if (p
->deps
) return;
1179 /* For head, all preloads are direct pseudo-dependencies.
1180 * Count and include them now to avoid realloc later. */
1181 if (p
==head
) for (struct dso
*q
=p
->next
; q
; q
=q
->next
)
1183 for (i
=0; p
->dynv
[i
]; i
+=2)
1184 if (p
->dynv
[i
] == DT_NEEDED
) cnt
++;
1185 /* Use builtin buffer for apps with no external deps, to
1186 * preserve property of no runtime failure paths. */
1187 p
->deps
= (p
==head
&& cnt
<2) ? builtin_deps
:
1188 calloc(cnt
+1, sizeof *p
->deps
);
1190 error("Error loading dependencies for %s", p
->name
);
1191 if (runtime
) longjmp(*rtld_fail
, 1);
1194 if (p
==head
) for (struct dso
*q
=p
->next
; q
; q
=q
->next
)
1196 for (i
=0; p
->dynv
[i
]; i
+=2) {
1197 if (p
->dynv
[i
] != DT_NEEDED
) continue;
1198 struct dso
*dep
= load_library(p
->strings
+ p
->dynv
[i
+1], p
);
1200 error("Error loading shared library %s: %m (needed by %s)",
1201 p
->strings
+ p
->dynv
[i
+1], p
->name
);
1202 if (runtime
) longjmp(*rtld_fail
, 1);
1205 p
->deps
[cnt
++] = dep
;
1208 p
->ndeps_direct
= cnt
;
1211 static void load_deps(struct dso
*p
)
1213 if (p
->deps
) return;
1214 for (; p
; p
=p
->next
)
1215 load_direct_deps(p
);
1218 static void extend_bfs_deps(struct dso
*p
)
1220 size_t i
, j
, cnt
, ndeps_all
;
1223 /* Can't use realloc if the original p->deps was allocated at
1224 * program entry and malloc has been replaced, or if it's
1225 * the builtin non-allocated trivial main program deps array. */
1226 int no_realloc
= (__malloc_replaced
&& !p
->runtime_loaded
)
1227 || p
->deps
== builtin_deps
;
1229 if (p
->bfs_built
) return;
1230 ndeps_all
= p
->ndeps_direct
;
1232 /* Mark existing (direct) deps so they won't be duplicated. */
1233 for (i
=0; p
->deps
[i
]; i
++)
1234 p
->deps
[i
]->mark
= 1;
1236 /* For each dependency already in the list, copy its list of direct
1237 * dependencies to the list, excluding any items already in the
1238 * list. Note that the list this loop iterates over will grow during
1239 * the loop, but since duplicates are excluded, growth is bounded. */
1240 for (i
=0; p
->deps
[i
]; i
++) {
1241 struct dso
*dep
= p
->deps
[i
];
1242 for (j
=cnt
=0; j
<dep
->ndeps_direct
; j
++)
1243 if (!dep
->deps
[j
]->mark
) cnt
++;
1245 malloc(sizeof(*tmp
) * (ndeps_all
+cnt
+1)) :
1246 realloc(p
->deps
, sizeof(*tmp
) * (ndeps_all
+cnt
+1));
1248 error("Error recording dependencies for %s", p
->name
);
1249 if (runtime
) longjmp(*rtld_fail
, 1);
1253 memcpy(tmp
, p
->deps
, sizeof(*tmp
) * (ndeps_all
+1));
1257 for (j
=0; j
<dep
->ndeps_direct
; j
++) {
1258 if (dep
->deps
[j
]->mark
) continue;
1259 dep
->deps
[j
]->mark
= 1;
1260 p
->deps
[ndeps_all
++] = dep
->deps
[j
];
1262 p
->deps
[ndeps_all
] = 0;
1265 for (p
=head
; p
; p
=p
->next
)
1269 static void load_preload(char *s
)
1273 for (z
=s
; *z
; s
=z
) {
1274 for ( ; *s
&& (isspace(*s
) || *s
==':'); s
++);
1275 for (z
=s
; *z
&& !isspace(*z
) && *z
!=':'; z
++);
1283 static void add_syms(struct dso
*p
)
1285 if (!p
->syms_next
&& syms_tail
!= p
) {
1286 syms_tail
->syms_next
= p
;
1291 static void revert_syms(struct dso
*old_tail
)
1293 struct dso
*p
, *next
;
1294 /* Chop off the tail of the list of dsos that participate in
1295 * the global symbol table, reverting them to RTLD_LOCAL. */
1296 for (p
=old_tail
; p
; p
=next
) {
1297 next
= p
->syms_next
;
1300 syms_tail
= old_tail
;
1303 static void do_mips_relocs(struct dso
*p
, size_t *got
)
1305 size_t i
, j
, rel
[2];
1306 unsigned char *base
= p
->base
;
1307 i
=0; search_vec(p
->dynv
, &i
, DT_MIPS_LOCAL_GOTNO
);
1311 while (i
--) *got
++ += (size_t)base
;
1313 j
=0; search_vec(p
->dynv
, &j
, DT_MIPS_GOTSYM
);
1314 i
=0; search_vec(p
->dynv
, &i
, DT_MIPS_SYMTABNO
);
1315 Sym
*sym
= p
->syms
+ j
;
1316 rel
[0] = (unsigned char *)got
- base
;
1317 for (i
-=j
; i
; i
--, sym
++, rel
[0]+=sizeof(size_t)) {
1318 rel
[1] = R_INFO(sym
-p
->syms
, R_MIPS_JUMP_SLOT
);
1319 do_relocs(p
, rel
, sizeof rel
, 2);
1323 static void reloc_all(struct dso
*p
)
1325 size_t dyn
[DYN_CNT
];
1326 for (; p
; p
=p
->next
) {
1327 if (p
->relocated
) continue;
1328 decode_vec(p
->dynv
, dyn
, DYN_CNT
);
1329 if (NEED_MIPS_GOT_RELOCS
)
1330 do_mips_relocs(p
, laddr(p
, dyn
[DT_PLTGOT
]));
1331 do_relocs(p
, laddr(p
, dyn
[DT_JMPREL
]), dyn
[DT_PLTRELSZ
],
1332 2+(dyn
[DT_PLTREL
]==DT_RELA
));
1333 do_relocs(p
, laddr(p
, dyn
[DT_REL
]), dyn
[DT_RELSZ
], 2);
1334 do_relocs(p
, laddr(p
, dyn
[DT_RELA
]), dyn
[DT_RELASZ
], 3);
1336 if (head
!= &ldso
&& p
->relro_start
!= p
->relro_end
&&
1337 mprotect(laddr(p
, p
->relro_start
), p
->relro_end
-p
->relro_start
, PROT_READ
)
1338 && errno
!= ENOSYS
) {
1339 error("Error relocating %s: RELRO protection failed: %m",
1341 if (runtime
) longjmp(*rtld_fail
, 1);
1348 static void kernel_mapped_dso(struct dso
*p
)
1350 size_t min_addr
= -1, max_addr
= 0, cnt
;
1352 for (cnt
= p
->phnum
; cnt
--; ph
= (void *)((char *)ph
+ p
->phentsize
)) {
1353 if (ph
->p_type
== PT_DYNAMIC
) {
1354 p
->dynv
= laddr(p
, ph
->p_vaddr
);
1355 } else if (ph
->p_type
== PT_GNU_RELRO
) {
1356 p
->relro_start
= ph
->p_vaddr
& -PAGE_SIZE
;
1357 p
->relro_end
= (ph
->p_vaddr
+ ph
->p_memsz
) & -PAGE_SIZE
;
1358 } else if (ph
->p_type
== PT_GNU_STACK
) {
1359 if (!runtime
&& ph
->p_memsz
> __default_stacksize
) {
1360 __default_stacksize
=
1361 ph
->p_memsz
< DEFAULT_STACK_MAX
?
1362 ph
->p_memsz
: DEFAULT_STACK_MAX
;
1365 if (ph
->p_type
!= PT_LOAD
) continue;
1366 if (ph
->p_vaddr
< min_addr
)
1367 min_addr
= ph
->p_vaddr
;
1368 if (ph
->p_vaddr
+ph
->p_memsz
> max_addr
)
1369 max_addr
= ph
->p_vaddr
+ph
->p_memsz
;
1371 min_addr
&= -PAGE_SIZE
;
1372 max_addr
= (max_addr
+ PAGE_SIZE
-1) & -PAGE_SIZE
;
1373 p
->map
= p
->base
+ min_addr
;
1374 p
->map_len
= max_addr
- min_addr
;
1375 p
->kernel_mapped
= 1;
1378 void __libc_exit_fini()
1381 size_t dyn
[DYN_CNT
];
1382 int self
= __pthread_self()->tid
;
1384 /* Take both locks before setting shutting_down, so that
1385 * either lock is sufficient to read its value. The lock
1386 * order matches that in dlopen to avoid deadlock. */
1387 pthread_rwlock_wrlock(&lock
);
1388 pthread_mutex_lock(&init_fini_lock
);
1390 pthread_rwlock_unlock(&lock
);
1391 for (p
=fini_head
; p
; p
=p
->fini_next
) {
1392 while (p
->ctor_visitor
&& p
->ctor_visitor
!=self
)
1393 pthread_cond_wait(&ctor_cond
, &init_fini_lock
);
1394 if (!p
->constructed
) continue;
1395 decode_vec(p
->dynv
, dyn
, DYN_CNT
);
1396 if (dyn
[0] & (1<<DT_FINI_ARRAY
)) {
1397 size_t n
= dyn
[DT_FINI_ARRAYSZ
]/sizeof(size_t);
1398 size_t *fn
= (size_t *)laddr(p
, dyn
[DT_FINI_ARRAY
])+n
;
1399 while (n
--) ((void (*)(void))*--fn
)();
1401 #ifndef NO_LEGACY_INITFINI
1402 if ((dyn
[0] & (1<<DT_FINI
)) && dyn
[DT_FINI
])
1403 fpaddr(p
, dyn
[DT_FINI
])();
1408 static struct dso
**queue_ctors(struct dso
*dso
)
1410 size_t cnt
, qpos
, spos
, i
;
1411 struct dso
*p
, **queue
, **stack
;
1413 if (ldd_mode
) return 0;
1415 /* Bound on queue size is the total number of indirect deps.
1416 * If a bfs deps list was built, we can use it. Otherwise,
1417 * bound by the total number of DSOs, which is always safe and
1418 * is reasonable we use it (for main app at startup). */
1419 if (dso
->bfs_built
) {
1420 for (cnt
=0; dso
->deps
[cnt
]; cnt
++)
1421 dso
->deps
[cnt
]->mark
= 0;
1422 cnt
++; /* self, not included in deps */
1424 for (cnt
=0, p
=head
; p
; cnt
++, p
=p
->next
)
1427 cnt
++; /* termination slot */
1428 if (dso
==head
&& cnt
<= countof(builtin_ctor_queue
))
1429 queue
= builtin_ctor_queue
;
1431 queue
= calloc(cnt
, sizeof *queue
);
1434 error("Error allocating constructor queue: %m\n");
1435 if (runtime
) longjmp(*rtld_fail
, 1);
1439 /* Opposite ends of the allocated buffer serve as an output queue
1440 * and a working stack. Setup initial stack with just the argument
1441 * dso and initial queue empty... */
1445 stack
[--spos
] = dso
;
1449 /* Then perform pseudo-DFS sort, but ignoring circular deps. */
1452 while (p
->next_dep
< p
->ndeps_direct
) {
1453 if (p
->deps
[p
->next_dep
]->mark
) {
1457 p
= p
->deps
[p
->next_dep
];
1465 for (i
=0; i
<qpos
; i
++) queue
[i
]->mark
= 0;
1470 static void do_init_fini(struct dso
**queue
)
1473 size_t dyn
[DYN_CNT
], i
;
1474 int self
= __pthread_self()->tid
;
1476 pthread_mutex_lock(&init_fini_lock
);
1477 for (i
=0; (p
=queue
[i
]); i
++) {
1478 while ((p
->ctor_visitor
&& p
->ctor_visitor
!=self
) || shutting_down
)
1479 pthread_cond_wait(&ctor_cond
, &init_fini_lock
);
1480 if (p
->ctor_visitor
|| p
->constructed
)
1482 p
->ctor_visitor
= self
;
1484 decode_vec(p
->dynv
, dyn
, DYN_CNT
);
1485 if (dyn
[0] & ((1<<DT_FINI
) | (1<<DT_FINI_ARRAY
))) {
1486 p
->fini_next
= fini_head
;
1490 pthread_mutex_unlock(&init_fini_lock
);
1492 #ifndef NO_LEGACY_INITFINI
1493 if ((dyn
[0] & (1<<DT_INIT
)) && dyn
[DT_INIT
])
1494 fpaddr(p
, dyn
[DT_INIT
])();
1496 if (dyn
[0] & (1<<DT_INIT_ARRAY
)) {
1497 size_t n
= dyn
[DT_INIT_ARRAYSZ
]/sizeof(size_t);
1498 size_t *fn
= laddr(p
, dyn
[DT_INIT_ARRAY
]);
1499 while (n
--) ((void (*)(void))*fn
++)();
1502 pthread_mutex_lock(&init_fini_lock
);
1503 p
->ctor_visitor
= 0;
1505 pthread_cond_broadcast(&ctor_cond
);
1507 pthread_mutex_unlock(&init_fini_lock
);
1510 void __libc_start_init(void)
1512 do_init_fini(main_ctor_queue
);
1513 if (!__malloc_replaced
&& main_ctor_queue
!= builtin_ctor_queue
)
1514 free(main_ctor_queue
);
1515 main_ctor_queue
= 0;
1518 static void dl_debug_state(void)
1522 weak_alias(dl_debug_state
, _dl_debug_state
);
1524 void __init_tls(size_t *auxv
)
1528 static void update_tls_size()
1530 libc
.tls_cnt
= tls_cnt
;
1531 libc
.tls_align
= tls_align
;
1532 libc
.tls_size
= ALIGN(
1533 (1+tls_cnt
) * sizeof(void *) +
1535 sizeof(struct pthread
) +
1540 static void install_new_tls(void)
1543 pthread_t self
= __pthread_self(), td
;
1544 struct dso
*dtv_provider
= container_of(tls_tail
, struct dso
, tls
);
1545 uintptr_t (*newdtv
)[tls_cnt
+1] = (void *)dtv_provider
->new_dtv
;
1548 size_t old_cnt
= self
->dtv
[0];
1550 __block_app_sigs(&set
);
1552 /* Copy existing dtv contents from all existing threads. */
1553 for (i
=0, td
=self
; !i
|| td
!=self
; i
++, td
=td
->next
) {
1554 memcpy(newdtv
+i
, td
->dtv
,
1555 (old_cnt
+1)*sizeof(uintptr_t));
1556 newdtv
[i
][0] = tls_cnt
;
1558 /* Install new dtls into the enlarged, uninstalled dtv copies. */
1559 for (p
=head
; ; p
=p
->next
) {
1560 if (p
->tls_id
<= old_cnt
) continue;
1561 unsigned char *mem
= p
->new_tls
;
1562 for (j
=0; j
<i
; j
++) {
1563 unsigned char *new = mem
;
1564 new += ((uintptr_t)p
->tls
.image
- (uintptr_t)mem
)
1566 memcpy(new, p
->tls
.image
, p
->tls
.len
);
1567 newdtv
[j
][p
->tls_id
] =
1568 (uintptr_t)new + DTP_OFFSET
;
1569 mem
+= p
->tls
.size
+ p
->tls
.align
;
1571 if (p
->tls_id
== tls_cnt
) break;
1574 /* Broadcast barrier to ensure contents of new dtv is visible
1575 * if the new dtv pointer is. The __membarrier function has a
1576 * fallback emulation using signals for kernels that lack the
1577 * feature at the syscall level. */
1579 __membarrier(MEMBARRIER_CMD_PRIVATE_EXPEDITED
, 0);
1581 /* Install new dtv for each thread. */
1582 for (j
=0, td
=self
; !j
|| td
!=self
; j
++, td
=td
->next
) {
1583 td
->dtv
= td
->dtv_copy
= newdtv
[j
];
1587 __restore_sigs(&set
);
1590 /* Stage 1 of the dynamic linker is defined in dlstart.c. It calls the
1591 * following stage 2 and stage 3 functions via primitive symbolic lookup
1592 * since it does not have access to their addresses to begin with. */
1594 /* Stage 2 of the dynamic linker is called after relative relocations
1595 * have been processed. It can make function calls to static functions
1596 * and access string literals and static data, but cannot use extern
1597 * symbols. Its job is to perform symbolic relocations on the dynamic
1598 * linker itself, but some of the relocations performed may need to be
1599 * replaced later due to copy relocations in the main program. */
1601 hidden
void __dls2(unsigned char *base
, size_t *sp
)
1604 for (auxv
=sp
+1+*sp
+1; *auxv
; auxv
++);
1607 void *p1
= (void *)sp
[-2];
1608 void *p2
= (void *)sp
[-1];
1610 size_t aux
[AUX_CNT
];
1611 decode_vec(auxv
, aux
, AUX_CNT
);
1612 if (aux
[AT_BASE
]) ldso
.base
= (void *)aux
[AT_BASE
];
1613 else ldso
.base
= (void *)(aux
[AT_PHDR
] & -4096);
1615 app_loadmap
= p2
? p1
: 0;
1616 ldso
.loadmap
= p2
? p2
: p1
;
1617 ldso
.base
= laddr(&ldso
, 0);
1621 Ehdr
*ehdr
= (void *)ldso
.base
;
1622 ldso
.name
= ldso
.shortname
= "libc.so";
1623 ldso
.phnum
= ehdr
->e_phnum
;
1624 ldso
.phdr
= laddr(&ldso
, ehdr
->e_phoff
);
1625 ldso
.phentsize
= ehdr
->e_phentsize
;
1626 kernel_mapped_dso(&ldso
);
1629 if (DL_FDPIC
) makefuncdescs(&ldso
);
1631 /* Prepare storage for to save clobbered REL addends so they
1632 * can be reused in stage 3. There should be very few. If
1633 * something goes wrong and there are a huge number, abort
1634 * instead of risking stack overflow. */
1635 size_t dyn
[DYN_CNT
];
1636 decode_vec(ldso
.dynv
, dyn
, DYN_CNT
);
1637 size_t *rel
= laddr(&ldso
, dyn
[DT_REL
]);
1638 size_t rel_size
= dyn
[DT_RELSZ
];
1639 size_t symbolic_rel_cnt
= 0;
1640 apply_addends_to
= rel
;
1641 for (; rel_size
; rel
+=2, rel_size
-=2*sizeof(size_t))
1642 if (!IS_RELATIVE(rel
[1], ldso
.syms
)) symbolic_rel_cnt
++;
1643 if (symbolic_rel_cnt
>= ADDEND_LIMIT
) a_crash();
1644 size_t addends
[symbolic_rel_cnt
+1];
1645 saved_addends
= addends
;
1652 /* Call dynamic linker stage-2b, __dls2b, looking it up
1653 * symbolically as a barrier against moving the address
1654 * load across the above relocation processing. */
1655 struct symdef dls2b_def
= find_sym(&ldso
, "__dls2b", 0);
1656 if (DL_FDPIC
) ((stage3_func
)&ldso
.funcdescs
[dls2b_def
.sym
-ldso
.syms
])(sp
, auxv
);
1657 else ((stage3_func
)laddr(&ldso
, dls2b_def
.sym
->st_value
))(sp
, auxv
);
1660 /* Stage 2b sets up a valid thread pointer, which requires relocations
1661 * completed in stage 2, and on which stage 3 is permitted to depend.
1662 * This is done as a separate stage, with symbolic lookup as a barrier,
1663 * so that loads of the thread pointer and &errno can be pure/const and
1664 * thereby hoistable. */
1666 void __dls2b(size_t *sp
, size_t *auxv
)
1668 /* Setup early thread pointer in builtin_tls for ldso/libc itself to
1669 * use during dynamic linking. If possible it will also serve as the
1670 * thread pointer at runtime. */
1671 search_vec(auxv
, &__hwcap
, AT_HWCAP
);
1673 libc
.tls_size
= sizeof builtin_tls
;
1674 libc
.tls_align
= tls_align
;
1675 if (__init_tp(__copy_tls((void *)builtin_tls
)) < 0) {
1679 struct symdef dls3_def
= find_sym(&ldso
, "__dls3", 0);
1680 if (DL_FDPIC
) ((stage3_func
)&ldso
.funcdescs
[dls3_def
.sym
-ldso
.syms
])(sp
, auxv
);
1681 else ((stage3_func
)laddr(&ldso
, dls3_def
.sym
->st_value
))(sp
, auxv
);
1684 /* Stage 3 of the dynamic linker is called with the dynamic linker/libc
1685 * fully functional. Its job is to load (if not already loaded) and
1686 * process dependencies and relocations for the main application and
1687 * transfer control to its entry point. */
1689 void __dls3(size_t *sp
, size_t *auxv
)
1691 static struct dso app
, vdso
;
1692 size_t aux
[AUX_CNT
];
1694 char *env_preload
=0;
1695 char *replace_argv0
=0;
1698 char **argv
= (void *)(sp
+1);
1699 char **argv_orig
= argv
;
1700 char **envp
= argv
+argc
+1;
1702 /* Find aux vector just past environ[] and use it to initialize
1703 * global data that may be needed before we can make syscalls. */
1705 decode_vec(auxv
, aux
, AUX_CNT
);
1706 search_vec(auxv
, &__sysinfo
, AT_SYSINFO
);
1707 __pthread_self()->sysinfo
= __sysinfo
;
1708 libc
.page_size
= aux
[AT_PAGESZ
];
1709 libc
.secure
= ((aux
[0]&0x7800)!=0x7800 || aux
[AT_UID
]!=aux
[AT_EUID
]
1710 || aux
[AT_GID
]!=aux
[AT_EGID
] || aux
[AT_SECURE
]);
1712 /* Only trust user/env if kernel says we're not suid/sgid */
1714 env_path
= getenv("LD_LIBRARY_PATH");
1715 env_preload
= getenv("LD_PRELOAD");
1718 /* If the main program was already loaded by the kernel,
1719 * AT_PHDR will point to some location other than the dynamic
1720 * linker's program headers. */
1721 if (aux
[AT_PHDR
] != (size_t)ldso
.phdr
) {
1722 size_t interp_off
= 0;
1723 size_t tls_image
= 0;
1724 /* Find load address of the main program, via AT_PHDR vs PT_PHDR. */
1725 Phdr
*phdr
= app
.phdr
= (void *)aux
[AT_PHDR
];
1726 app
.phnum
= aux
[AT_PHNUM
];
1727 app
.phentsize
= aux
[AT_PHENT
];
1728 for (i
=aux
[AT_PHNUM
]; i
; i
--, phdr
=(void *)((char *)phdr
+ aux
[AT_PHENT
])) {
1729 if (phdr
->p_type
== PT_PHDR
)
1730 app
.base
= (void *)(aux
[AT_PHDR
] - phdr
->p_vaddr
);
1731 else if (phdr
->p_type
== PT_INTERP
)
1732 interp_off
= (size_t)phdr
->p_vaddr
;
1733 else if (phdr
->p_type
== PT_TLS
) {
1734 tls_image
= phdr
->p_vaddr
;
1735 app
.tls
.len
= phdr
->p_filesz
;
1736 app
.tls
.size
= phdr
->p_memsz
;
1737 app
.tls
.align
= phdr
->p_align
;
1740 if (DL_FDPIC
) app
.loadmap
= app_loadmap
;
1741 if (app
.tls
.size
) app
.tls
.image
= laddr(&app
, tls_image
);
1742 if (interp_off
) ldso
.name
= laddr(&app
, interp_off
);
1743 if ((aux
[0] & (1UL<<AT_EXECFN
))
1744 && strncmp((char *)aux
[AT_EXECFN
], "/proc/", 6))
1745 app
.name
= (char *)aux
[AT_EXECFN
];
1748 kernel_mapped_dso(&app
);
1751 char *ldname
= argv
[0];
1752 size_t l
= strlen(ldname
);
1753 if (l
>= 3 && !strcmp(ldname
+l
-3, "ldd")) ldd_mode
= 1;
1755 while (argv
[0] && argv
[0][0]=='-' && argv
[0][1]=='-') {
1756 char *opt
= argv
[0]+2;
1757 *argv
++ = (void *)-1;
1760 } else if (!memcmp(opt
, "list", 5)) {
1762 } else if (!memcmp(opt
, "library-path", 12)) {
1763 if (opt
[12]=='=') env_path
= opt
+13;
1764 else if (opt
[12]) *argv
= 0;
1765 else if (*argv
) env_path
= *argv
++;
1766 } else if (!memcmp(opt
, "preload", 7)) {
1767 if (opt
[7]=='=') env_preload
= opt
+8;
1768 else if (opt
[7]) *argv
= 0;
1769 else if (*argv
) env_preload
= *argv
++;
1770 } else if (!memcmp(opt
, "argv0", 5)) {
1771 if (opt
[5]=='=') replace_argv0
= opt
+6;
1772 else if (opt
[5]) *argv
= 0;
1773 else if (*argv
) replace_argv0
= *argv
++;
1778 argv
[-1] = (void *)(argc
- (argv
-argv_orig
));
1780 dprintf(2, "musl libc (" LDSO_ARCH
")\n"
1782 "Dynamic Program Loader\n"
1783 "Usage: %s [options] [--] pathname%s\n",
1784 __libc_version
, ldname
,
1785 ldd_mode
? "" : " [args]");
1788 fd
= open(argv
[0], O_RDONLY
);
1790 dprintf(2, "%s: cannot load %s: %s\n", ldname
, argv
[0], strerror(errno
));
1793 Ehdr
*ehdr
= (void *)map_library(fd
, &app
);
1795 dprintf(2, "%s: %s: Not a valid dynamic program\n", ldname
, argv
[0]);
1801 aux
[AT_ENTRY
] = (size_t)laddr(&app
, ehdr
->e_entry
);
1802 /* Find the name that would have been used for the dynamic
1803 * linker had ldd not taken its place. */
1805 for (i
=0; i
<app
.phnum
; i
++) {
1806 if (app
.phdr
[i
].p_type
== PT_INTERP
)
1807 ldso
.name
= laddr(&app
, app
.phdr
[i
].p_vaddr
);
1809 dprintf(1, "\t%s (%p)\n", ldso
.name
, ldso
.base
);
1813 libc
.tls_head
= tls_tail
= &app
.tls
;
1814 app
.tls_id
= tls_cnt
= 1;
1816 app
.tls
.offset
= GAP_ABOVE_TP
;
1817 app
.tls
.offset
+= (-GAP_ABOVE_TP
+ (uintptr_t)app
.tls
.image
)
1818 & (app
.tls
.align
-1);
1819 tls_offset
= app
.tls
.offset
+ app
.tls
.size
;
1821 tls_offset
= app
.tls
.offset
= app
.tls
.size
1822 + ( -((uintptr_t)app
.tls
.image
+ app
.tls
.size
)
1823 & (app
.tls
.align
-1) );
1825 tls_align
= MAXP2(tls_align
, app
.tls
.align
);
1829 makefuncdescs(&app
);
1831 app
.loadmap
= (void *)&app_dummy_loadmap
;
1832 app
.loadmap
->nsegs
= 1;
1833 app
.loadmap
->segs
[0].addr
= (size_t)app
.map
;
1834 app
.loadmap
->segs
[0].p_vaddr
= (size_t)app
.map
1836 app
.loadmap
->segs
[0].p_memsz
= app
.map_len
;
1838 argv
[-3] = (void *)app
.loadmap
;
1841 /* Initial dso chain consists only of the app. */
1842 head
= tail
= syms_tail
= &app
;
1844 /* Donate unused parts of app and library mapping to malloc */
1846 reclaim_gaps(&ldso
);
1848 /* Load preload/needed libraries, add symbols to global namespace. */
1849 ldso
.deps
= (struct dso
**)no_deps
;
1850 if (env_preload
) load_preload(env_preload
);
1852 for (struct dso
*p
=head
; p
; p
=p
->next
)
1855 /* Attach to vdso, if provided by the kernel, last so that it does
1856 * not become part of the global namespace. */
1857 if (search_vec(auxv
, &vdso_base
, AT_SYSINFO_EHDR
) && vdso_base
) {
1858 Ehdr
*ehdr
= (void *)vdso_base
;
1859 Phdr
*phdr
= vdso
.phdr
= (void *)(vdso_base
+ ehdr
->e_phoff
);
1860 vdso
.phnum
= ehdr
->e_phnum
;
1861 vdso
.phentsize
= ehdr
->e_phentsize
;
1862 for (i
=ehdr
->e_phnum
; i
; i
--, phdr
=(void *)((char *)phdr
+ ehdr
->e_phentsize
)) {
1863 if (phdr
->p_type
== PT_DYNAMIC
)
1864 vdso
.dynv
= (void *)(vdso_base
+ phdr
->p_offset
);
1865 if (phdr
->p_type
== PT_LOAD
)
1866 vdso
.base
= (void *)(vdso_base
- phdr
->p_vaddr
+ phdr
->p_offset
);
1869 vdso
.shortname
= "linux-gate.so.1";
1871 vdso
.deps
= (struct dso
**)no_deps
;
1878 for (i
=0; app
.dynv
[i
]; i
+=2) {
1879 if (!DT_DEBUG_INDIRECT
&& app
.dynv
[i
]==DT_DEBUG
)
1880 app
.dynv
[i
+1] = (size_t)&debug
;
1881 if (DT_DEBUG_INDIRECT
&& app
.dynv
[i
]==DT_DEBUG_INDIRECT
) {
1882 size_t *ptr
= (size_t *) app
.dynv
[i
+1];
1883 *ptr
= (size_t)&debug
;
1887 /* This must be done before final relocations, since it calls
1888 * malloc, which may be provided by the application. Calling any
1889 * application code prior to the jump to its entry point is not
1890 * valid in our model and does not work with FDPIC, where there
1891 * are additional relocation-like fixups that only the entry point
1892 * code can see to perform. */
1893 main_ctor_queue
= queue_ctors(&app
);
1895 /* Initial TLS must also be allocated before final relocations
1896 * might result in calloc being a call to application code. */
1898 void *initial_tls
= builtin_tls
;
1899 if (libc
.tls_size
> sizeof builtin_tls
|| tls_align
> MIN_TLS_ALIGN
) {
1900 initial_tls
= calloc(libc
.tls_size
, 1);
1902 dprintf(2, "%s: Error getting %zu bytes thread-local storage: %m\n",
1903 argv
[0], libc
.tls_size
);
1907 static_tls_cnt
= tls_cnt
;
1909 /* The main program must be relocated LAST since it may contain
1910 * copy relocations which depend on libraries' relocations. */
1911 reloc_all(app
.next
);
1914 /* Actual copying to new TLS needs to happen after relocations,
1915 * since the TLS images might have contained relocated addresses. */
1916 if (initial_tls
!= builtin_tls
) {
1917 if (__init_tp(__copy_tls(initial_tls
)) < 0) {
1921 size_t tmp_tls_size
= libc
.tls_size
;
1922 pthread_t self
= __pthread_self();
1923 /* Temporarily set the tls size to the full size of
1924 * builtin_tls so that __copy_tls will use the same layout
1925 * as it did for before. Then check, just to be safe. */
1926 libc
.tls_size
= sizeof builtin_tls
;
1927 if (__copy_tls((void*)builtin_tls
) != self
) a_crash();
1928 libc
.tls_size
= tmp_tls_size
;
1931 if (ldso_fail
) _exit(127);
1932 if (ldd_mode
) _exit(0);
1934 /* Determine if malloc was interposed by a replacement implementation
1935 * so that calloc and the memalign family can harden against the
1936 * possibility of incomplete replacement. */
1937 if (find_sym(head
, "malloc", 1).dso
!= &ldso
)
1938 __malloc_replaced
= 1;
1940 /* Switch to runtime mode: any further failures in the dynamic
1941 * linker are a reportable failure rather than a fatal startup
1946 debug
.bp
= dl_debug_state
;
1948 debug
.base
= ldso
.base
;
1952 if (replace_argv0
) argv
[0] = replace_argv0
;
1956 CRTJMP((void *)aux
[AT_ENTRY
], argv
-1);
1960 static void prepare_lazy(struct dso
*p
)
1962 size_t dyn
[DYN_CNT
], n
, flags1
=0;
1963 decode_vec(p
->dynv
, dyn
, DYN_CNT
);
1964 search_vec(p
->dynv
, &flags1
, DT_FLAGS_1
);
1965 if (dyn
[DT_BIND_NOW
] || (dyn
[DT_FLAGS
] & DF_BIND_NOW
) || (flags1
& DF_1_NOW
))
1967 n
= dyn
[DT_RELSZ
]/2 + dyn
[DT_RELASZ
]/3 + dyn
[DT_PLTRELSZ
]/2 + 1;
1968 if (NEED_MIPS_GOT_RELOCS
) {
1969 size_t j
=0; search_vec(p
->dynv
, &j
, DT_MIPS_GOTSYM
);
1970 size_t i
=0; search_vec(p
->dynv
, &i
, DT_MIPS_SYMTABNO
);
1973 p
->lazy
= calloc(n
, 3*sizeof(size_t));
1975 error("Error preparing lazy relocation for %s: %m", p
->name
);
1976 longjmp(*rtld_fail
, 1);
1978 p
->lazy_next
= lazy_head
;
1982 void *dlopen(const char *file
, int mode
)
1984 struct dso
*volatile p
, *orig_tail
, *orig_syms_tail
, *orig_lazy_head
, *next
;
1985 struct tls_module
*orig_tls_tail
;
1986 size_t orig_tls_cnt
, orig_tls_offset
, orig_tls_align
;
1990 struct dso
**volatile ctor_queue
= 0;
1992 if (!file
) return head
;
1994 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE
, &cs
);
1995 pthread_rwlock_wrlock(&lock
);
1999 if (shutting_down
) {
2000 error("Cannot dlopen while program is exiting.");
2003 orig_tls_tail
= tls_tail
;
2004 orig_tls_cnt
= tls_cnt
;
2005 orig_tls_offset
= tls_offset
;
2006 orig_tls_align
= tls_align
;
2007 orig_lazy_head
= lazy_head
;
2008 orig_syms_tail
= syms_tail
;
2010 noload
= mode
& RTLD_NOLOAD
;
2013 if (setjmp(*rtld_fail
)) {
2014 /* Clean up anything new that was (partially) loaded */
2015 revert_syms(orig_syms_tail
);
2016 for (p
=orig_tail
->next
; p
; p
=next
) {
2018 while (p
->td_index
) {
2019 void *tmp
= p
->td_index
->next
;
2024 if (p
->rpath
!= p
->rpath_orig
)
2032 if (!orig_tls_tail
) libc
.tls_head
= 0;
2033 tls_tail
= orig_tls_tail
;
2034 if (tls_tail
) tls_tail
->next
= 0;
2035 tls_cnt
= orig_tls_cnt
;
2036 tls_offset
= orig_tls_offset
;
2037 tls_align
= orig_tls_align
;
2038 lazy_head
= orig_lazy_head
;
2043 } else p
= load_library(file
, head
);
2047 "Library %s is not already loaded" :
2048 "Error loading shared library %s: %m",
2053 /* First load handling */
2056 pthread_mutex_lock(&init_fini_lock
);
2057 if (!p
->constructed
) ctor_queue
= queue_ctors(p
);
2058 pthread_mutex_unlock(&init_fini_lock
);
2059 if (!p
->relocated
&& (mode
& RTLD_LAZY
)) {
2061 for (i
=0; p
->deps
[i
]; i
++)
2062 if (!p
->deps
[i
]->relocated
)
2063 prepare_lazy(p
->deps
[i
]);
2065 if (!p
->relocated
|| (mode
& RTLD_GLOBAL
)) {
2066 /* Make new symbols global, at least temporarily, so we can do
2067 * relocations. If not RTLD_GLOBAL, this is reverted below. */
2069 for (i
=0; p
->deps
[i
]; i
++)
2070 add_syms(p
->deps
[i
]);
2072 if (!p
->relocated
) {
2076 /* If RTLD_GLOBAL was not specified, undo any new additions
2077 * to the global symbol table. This is a nop if the library was
2078 * previously loaded and already global. */
2079 if (!(mode
& RTLD_GLOBAL
))
2080 revert_syms(orig_syms_tail
);
2082 /* Processing of deferred lazy relocations must not happen until
2083 * the new libraries are committed; otherwise we could end up with
2084 * relocations resolved to symbol definitions that get removed. */
2088 if (tls_cnt
!= orig_tls_cnt
)
2095 pthread_rwlock_unlock(&lock
);
2097 do_init_fini(ctor_queue
);
2100 pthread_setcancelstate(cs
, 0);
2104 hidden
int __dl_invalid_handle(void *h
)
2107 for (p
=head
; p
; p
=p
->next
) if (h
==p
) return 0;
2108 error("Invalid library handle %p", (void *)h
);
2112 static void *addr2dso(size_t a
)
2116 if (DL_FDPIC
) for (p
=head
; p
; p
=p
->next
) {
2118 if (a
-(size_t)p
->funcdescs
< i
*sizeof(*p
->funcdescs
))
2121 for (p
=head
; p
; p
=p
->next
) {
2122 if (DL_FDPIC
&& p
->loadmap
) {
2123 for (i
=0; i
<p
->loadmap
->nsegs
; i
++) {
2124 if (a
-p
->loadmap
->segs
[i
].p_vaddr
2125 < p
->loadmap
->segs
[i
].p_memsz
)
2130 size_t phcnt
= p
->phnum
;
2131 size_t entsz
= p
->phentsize
;
2132 size_t base
= (size_t)p
->base
;
2133 for (; phcnt
--; ph
=(void *)((char *)ph
+entsz
)) {
2134 if (ph
->p_type
!= PT_LOAD
) continue;
2135 if (a
-base
-ph
->p_vaddr
< ph
->p_memsz
)
2138 if (a
-(size_t)p
->map
< p
->map_len
)
2145 static void *do_dlsym(struct dso
*p
, const char *s
, void *ra
)
2148 if (p
== head
|| p
== RTLD_DEFAULT
) {
2150 } else if (p
== RTLD_NEXT
) {
2151 p
= addr2dso((size_t)ra
);
2154 } else if (__dl_invalid_handle(p
)) {
2158 struct symdef def
= find_sym2(p
, s
, 0, use_deps
);
2160 error("Symbol not found: %s", s
);
2163 if ((def
.sym
->st_info
&0xf) == STT_TLS
)
2164 return __tls_get_addr((tls_mod_off_t
[]){def
.dso
->tls_id
, def
.sym
->st_value
-DTP_OFFSET
});
2165 if (DL_FDPIC
&& (def
.sym
->st_info
&0xf) == STT_FUNC
)
2166 return def
.dso
->funcdescs
+ (def
.sym
- def
.dso
->syms
);
2167 return laddr(def
.dso
, def
.sym
->st_value
);
2170 int dladdr(const void *addr_arg
, Dl_info
*info
)
2172 size_t addr
= (size_t)addr_arg
;
2178 size_t besterr
= -1;
2180 pthread_rwlock_rdlock(&lock
);
2182 pthread_rwlock_unlock(&lock
);
2187 strings
= p
->strings
;
2188 nsym
= count_syms(p
);
2191 size_t idx
= (addr
-(size_t)p
->funcdescs
)
2192 / sizeof(*p
->funcdescs
);
2193 if (idx
< nsym
&& (sym
[idx
].st_info
&0xf) == STT_FUNC
) {
2194 best
= (size_t)(p
->funcdescs
+ idx
);
2195 bestsym
= sym
+ idx
;
2200 if (!best
) for (; nsym
; nsym
--, sym
++) {
2202 && (1<<(sym
->st_info
&0xf) & OK_TYPES
)
2203 && (1<<(sym
->st_info
>>4) & OK_BINDS
)) {
2204 size_t symaddr
= (size_t)laddr(p
, sym
->st_value
);
2205 if (symaddr
> addr
|| symaddr
<= best
)
2209 besterr
= addr
- symaddr
;
2210 if (addr
== symaddr
)
2215 if (best
&& besterr
> bestsym
->st_size
-1) {
2220 info
->dli_fname
= p
->name
;
2221 info
->dli_fbase
= p
->map
;
2224 info
->dli_sname
= 0;
2225 info
->dli_saddr
= 0;
2229 if (DL_FDPIC
&& (bestsym
->st_info
&0xf) == STT_FUNC
)
2230 best
= (size_t)(p
->funcdescs
+ (bestsym
- p
->syms
));
2231 info
->dli_sname
= strings
+ bestsym
->st_name
;
2232 info
->dli_saddr
= (void *)best
;
2237 hidden
void *__dlsym(void *restrict p
, const char *restrict s
, void *restrict ra
)
2240 pthread_rwlock_rdlock(&lock
);
2241 res
= do_dlsym(p
, s
, ra
);
2242 pthread_rwlock_unlock(&lock
);
2246 hidden
void *__dlsym_redir_time64(void *restrict p
, const char *restrict s
, void *restrict ra
)
2249 const char *suffix
, *suffix2
= "";
2252 /* Map the symbol name to a time64 version of itself according to the
2253 * pattern used for naming the redirected time64 symbols. */
2254 size_t l
= strnlen(s
, sizeof redir
);
2255 if (l
<4 || l
==sizeof redir
) goto no_redir
;
2256 if (s
[l
-2]=='_' && s
[l
-1]=='r') {
2260 if (l
<4) goto no_redir
;
2261 if (!strcmp(s
+l
-4, "time")) suffix
= "64";
2262 else suffix
= "_time64";
2264 /* Use the presence of the remapped symbol name in libc to determine
2265 * whether it's one that requires time64 redirection; replace if so. */
2266 snprintf(redir
, sizeof redir
, "__%.*s%s%s", (int)l
, s
, suffix
, suffix2
);
2267 if (find_sym(&ldso
, redir
, 1).sym
) s
= redir
;
2270 return __dlsym(p
, s
, ra
);
2273 int dl_iterate_phdr(int(*callback
)(struct dl_phdr_info
*info
, size_t size
, void *data
), void *data
)
2275 struct dso
*current
;
2276 struct dl_phdr_info info
;
2278 for(current
= head
; current
;) {
2279 info
.dlpi_addr
= (uintptr_t)current
->base
;
2280 info
.dlpi_name
= current
->name
;
2281 info
.dlpi_phdr
= current
->phdr
;
2282 info
.dlpi_phnum
= current
->phnum
;
2283 info
.dlpi_adds
= gencnt
;
2285 info
.dlpi_tls_modid
= current
->tls_id
;
2286 info
.dlpi_tls_data
= current
->tls
.image
;
2288 ret
= (callback
)(&info
, sizeof (info
), data
);
2290 if (ret
!= 0) break;
2292 pthread_rwlock_rdlock(&lock
);
2293 current
= current
->next
;
2294 pthread_rwlock_unlock(&lock
);
2299 static void error(const char *fmt
, ...)
2304 vdprintf(2, fmt
, ap
);
2310 __dl_vseterr(fmt
, ap
);