blob: b19bdb6493a3c00e6e646c9c9d13d9e0ea46de56 [file] [log] [blame]
Rich Felker8431d792012-10-04 16:35:46 -04001#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
9static void *image;
Rich Felkerbc6a35f2012-10-04 20:04:13 -040010static size_t len, size, align;
Rich Felker8431d792012-10-04 16:35:46 -040011
Rich Felkerdcd60372012-10-05 11:51:50 -040012void *__copy_tls(unsigned char *mem)
Rich Felker8431d792012-10-04 16:35:46 -040013{
Rich Felkerbc6a35f2012-10-04 20:04:13 -040014 mem += -size & (4*sizeof(size_t)-1);
Rich Felker8431d792012-10-04 16:35:46 -040015 mem += ((uintptr_t)image - (uintptr_t)mem) & (align-1);
16 memcpy(mem, image, len);
Rich Felkerbc6a35f2012-10-04 20:04:13 -040017 return mem + size;
Rich Felker8431d792012-10-04 16:35:46 -040018}
19
20static void *simple(void *p)
21{
22 *(void **)p = p;
23 return __set_thread_area(p) ? 0 : p;
24}
25
26weak_alias(simple, __install_initial_tls);
27
28void *__mmap(void *, size_t, int, int, int, off_t);
29
30#if ULONG_MAX == 0xffffffff
31typedef Elf32_Phdr Phdr;
32#else
33typedef Elf64_Phdr Phdr;
34#endif
35
36#define AUX_CNT 6
37
38void __init_tls(size_t *auxv)
39{
40 size_t i, aux[AUX_CNT] = { 0 };
41 unsigned char *p, *mem;
42 size_t n, d;
43 Phdr *phdr, *tls_phdr=0;
44 size_t base = 0;
45
46 for (; auxv[0]; auxv+=2) if (auxv[0]<AUX_CNT) aux[auxv[0]] = auxv[1];
47 p = (void *)aux[AT_PHDR];
48 for (p=(void *)aux[AT_PHDR]; aux[AT_PHNUM]--; p+=aux[AT_PHENT]) {
49 phdr = (void *)p;
50 if (phdr->p_type == PT_PHDR)
51 base = aux[AT_PHDR] - phdr->p_vaddr;
52 if (phdr->p_type == PT_TLS)
53 tls_phdr = phdr;
54 }
55 if (!tls_phdr) return;
56
Rich Felkerbc6a35f2012-10-04 20:04:13 -040057 libc.tls_size = size+align+8*sizeof(size_t)+sizeof(struct pthread);
Rich Felker8431d792012-10-04 16:35:46 -040058
59 image = (void *)(base + tls_phdr->p_vaddr);
60 len = tls_phdr->p_filesz;
Rich Felkerbc6a35f2012-10-04 20:04:13 -040061 size = tls_phdr->p_memsz;
Rich Felker8431d792012-10-04 16:35:46 -040062 align = tls_phdr->p_align;
Rich Felker8431d792012-10-04 16:35:46 -040063 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
Rich Felkerdcd60372012-10-05 11:51:50 -040067 if (!__install_initial_tls(__copy_tls(mem))) a_crash();
Rich Felker8431d792012-10-04 16:35:46 -040068}
69#else
70void __init_tls(size_t *auxv) { }
71#endif