6 #include "pthread_impl.h"
11 int __init_tp(void *p)
15 int r = __set_thread_area(TP_ADJ(p));
17 if (!r) libc.can_do_threads = 1;
18 td->detach_state = DT_JOINABLE;
19 td->tid = __syscall(SYS_set_tid_address, &td->detach_state);
20 td->locale = &libc.global_locale;
21 td->robust_list.head = &td->robust_list.head;
25 static struct builtin_tls {
30 #define MIN_TLS_ALIGN offsetof(struct builtin_tls, pt)
32 static struct tls_module main_tls;
34 void *__copy_tls(unsigned char *mem)
42 dtv = (uintptr_t*)(mem + libc.tls_size) - (libc.tls_cnt + 1);
44 mem += -((uintptr_t)mem + sizeof(struct pthread)) & (libc.tls_align-1);
46 mem += sizeof(struct pthread);
48 for (i=1, p=libc.tls_head; p; i++, p=p->next) {
49 dtv[i] = (uintptr_t)(mem + p->offset) + DTP_OFFSET;
50 memcpy(mem + p->offset, p->image, p->len);
53 dtv = (uintptr_t *)mem;
55 mem += libc.tls_size - sizeof(struct pthread);
56 mem -= (uintptr_t)mem & (libc.tls_align-1);
59 for (i=1, p=libc.tls_head; p; i++, p=p->next) {
60 dtv[i] = (uintptr_t)(mem - p->offset) + DTP_OFFSET;
61 memcpy(mem - p->offset, p->image, p->len);
64 dtv[0] = libc.tls_cnt;
65 td->dtv = td->dtv_copy = dtv;
69 #if ULONG_MAX == 0xffffffff
70 typedef Elf32_Phdr Phdr;
72 typedef Elf64_Phdr Phdr;
75 extern weak hidden const size_t _DYNAMIC[];
77 static void static_init_tls(size_t *aux)
81 Phdr *phdr, *tls_phdr=0;
85 for (p=(void *)aux[AT_PHDR],n=aux[AT_PHNUM]; n; n--,p+=aux[AT_PHENT]) {
87 if (phdr->p_type == PT_PHDR)
88 base = aux[AT_PHDR] - phdr->p_vaddr;
89 if (phdr->p_type == PT_DYNAMIC && _DYNAMIC)
90 base = (size_t)_DYNAMIC - phdr->p_vaddr;
91 if (phdr->p_type == PT_TLS)
93 if (phdr->p_type == PT_GNU_STACK &&
94 phdr->p_memsz > __default_stacksize)
96 phdr->p_memsz < DEFAULT_STACK_MAX ?
97 phdr->p_memsz : DEFAULT_STACK_MAX;
101 main_tls.image = (void *)(base + tls_phdr->p_vaddr);
102 main_tls.len = tls_phdr->p_filesz;
103 main_tls.size = tls_phdr->p_memsz;
104 main_tls.align = tls_phdr->p_align;
106 libc.tls_head = &main_tls;
109 main_tls.size += (-main_tls.size - (uintptr_t)main_tls.image)
110 & (main_tls.align-1);
112 main_tls.offset = GAP_ABOVE_TP;
113 main_tls.offset += -GAP_ABOVE_TP & (main_tls.align-1);
115 main_tls.offset = main_tls.size;
117 if (main_tls.align < MIN_TLS_ALIGN) main_tls.align = MIN_TLS_ALIGN;
119 libc.tls_align = main_tls.align;
120 libc.tls_size = 2*sizeof(void *) + sizeof(struct pthread)
124 + main_tls.size + main_tls.align
125 + MIN_TLS_ALIGN-1 & -MIN_TLS_ALIGN;
127 if (libc.tls_size > sizeof builtin_tls) {
129 #define SYS_mmap2 SYS_mmap
131 mem = (void *)__syscall(
133 0, libc.tls_size, PROT_READ|PROT_WRITE,
134 MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
135 /* -4095...-1 cast to void * will crash on dereference anyway,
136 * so don't bloat the init code checking for error codes and
137 * explicitly calling a_crash(). */
142 /* Failure to initialize thread pointer is always fatal. */
143 if (__init_tp(__copy_tls(mem)) < 0)
147 weak_alias(static_init_tls, __init_tls);