6b3cd28bb03699d6a71e32a9de276398389779c4
[musl] / src / env / __init_tls.c
1 #include <elf.h>
2 #include <limits.h>
3 #include "pthread_impl.h"
4 #include "libc.h"
5 #include "atomic.h"
6
7 #ifndef SHARED
8
9 static void *image;
10 static size_t len, size, align;
11
12 void *__copy_tls(unsigned char *mem)
13 {
14         pthread_t td;
15         if (!image) return mem;
16         void **dtv = (void *)mem;
17         dtv[0] = (void *)1;
18         mem += __libc.tls_size - sizeof(struct pthread);
19         mem -= (uintptr_t)mem & (align-1);
20         td = (pthread_t)mem;
21         td->dtv = dtv;
22         mem -= size;
23         dtv[1] = mem;
24         memcpy(mem, image, len);
25         return td;
26 }
27
28 void *__tls_get_addr(size_t *v)
29 {
30         return (char *)__pthread_self()->dtv[1]+v[1];
31 }
32
33 static void *simple(void *p)
34 {
35         *(void **)p = p;
36         return __set_thread_area(p) ? 0 : p;
37 }
38
39 weak_alias(simple, __install_initial_tls);
40
41 void *__mmap(void *, size_t, int, int, int, off_t);
42
43 #if ULONG_MAX == 0xffffffff
44 typedef Elf32_Phdr Phdr;
45 #else
46 typedef Elf64_Phdr Phdr;
47 #endif
48
49 #define AUX_CNT 6
50
51 void __init_tls(size_t *auxv)
52 {
53         size_t i, aux[AUX_CNT] = { 0 };
54         unsigned char *p, *mem;
55         size_t n, d;
56         Phdr *phdr, *tls_phdr=0;
57         size_t base = 0;
58
59         for (; auxv[0]; auxv+=2) if (auxv[0]<AUX_CNT) aux[auxv[0]] = auxv[1];
60         p = (void *)aux[AT_PHDR];
61         for (p=(void *)aux[AT_PHDR]; aux[AT_PHNUM]--; p+=aux[AT_PHENT]) {
62                 phdr = (void *)p;
63                 if (phdr->p_type == PT_PHDR)
64                         base = aux[AT_PHDR] - phdr->p_vaddr;
65                 if (phdr->p_type == PT_TLS)
66                         tls_phdr = phdr;
67         }
68         if (!tls_phdr) return;
69
70         image = (void *)(base + tls_phdr->p_vaddr);
71         len = tls_phdr->p_filesz;
72         size = tls_phdr->p_memsz;
73         align = tls_phdr->p_align;
74
75         size += (-size - (uintptr_t)image) & (align-1);
76         if (align < 4*sizeof(size_t)) align = 4*sizeof(size_t);
77
78         libc.tls_size = 2*sizeof(void *)+size+align+sizeof(struct pthread);
79
80         mem = __mmap(0, libc.tls_size, PROT_READ|PROT_WRITE,
81                 MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
82         if (mem == MAP_FAILED) a_crash();
83
84         if (!__install_initial_tls(__copy_tls(mem))) a_crash();
85 }
86 #else
87 void __init_tls(size_t *auxv) { }
88 #endif