TLS (GNU/C11 thread-local storage) support for static-linked programs
[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, bss, align;
11
12 void *__copy_tls(unsigned char *mem, size_t cnt)
13 {
14         mem += ((uintptr_t)image - (uintptr_t)mem) & (align-1);
15         memcpy(mem, image, len);
16         return mem + len + bss;
17 }
18
19 static void *simple(void *p)
20 {
21         *(void **)p = p;
22         return __set_thread_area(p) ? 0 : p;
23 }
24
25 weak_alias(simple, __install_initial_tls);
26
27 void *__mmap(void *, size_t, int, int, int, off_t);
28
29 #if ULONG_MAX == 0xffffffff
30 typedef Elf32_Phdr Phdr;
31 #else
32 typedef Elf64_Phdr Phdr;
33 #endif
34
35 #define AUX_CNT 6
36
37 void __init_tls(size_t *auxv)
38 {
39         size_t i, aux[AUX_CNT] = { 0 };
40         unsigned char *p, *mem;
41         size_t n, d;
42         Phdr *phdr, *tls_phdr=0;
43         size_t base = 0;
44
45         for (; auxv[0]; auxv+=2) if (auxv[0]<AUX_CNT) aux[auxv[0]] = auxv[1];
46         p = (void *)aux[AT_PHDR];
47         for (p=(void *)aux[AT_PHDR]; aux[AT_PHNUM]--; p+=aux[AT_PHENT]) {
48                 phdr = (void *)p;
49                 if (phdr->p_type == PT_PHDR)
50                         base = aux[AT_PHDR] - phdr->p_vaddr;
51                 if (phdr->p_type == PT_TLS)
52                         tls_phdr = phdr;
53         }
54         if (!tls_phdr) return;
55
56         libc.tls_size = len+bss+align+4*sizeof(size_t)+sizeof(struct pthread);
57
58         image = (void *)(base + tls_phdr->p_vaddr);
59         len = tls_phdr->p_filesz;
60         bss = tls_phdr->p_memsz - len;
61         align = tls_phdr->p_align;
62         if (align < 4*sizeof(size_t)) align = 4*sizeof(size_t);
63         mem = __mmap(0, libc.tls_size, PROT_READ|PROT_WRITE,
64                 MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
65         if (mem == MAP_FAILED) a_crash();
66
67         if (!__install_initial_tls(__copy_tls(mem, 0))) a_crash();
68 }
69 #else
70 void __init_tls(size_t *auxv) { }
71 #endif