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