d2de2cb8f0b207be46b091365b1cc11ad2249db1
[musl] / src / thread / pthread_self.c
1 #include "pthread_impl.h"
2
3 static struct pthread main_thread;
4
5 /* pthread_key_create.c overrides this */
6 static const size_t dummy = 0;
7 weak_alias(dummy, __pthread_tsd_size);
8
9 #undef errno
10 static int *errno_location()
11 {
12         return __pthread_self()->errno_ptr;
13 }
14
15 static int init_main_thread()
16 {
17         void *tsd = 0;
18         if (__pthread_tsd_size) {
19                 tsd = mmap(0, __pthread_tsd_size, PROT_READ|PROT_WRITE,
20                         MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
21                 if (tsd == MAP_FAILED) return -1;
22         }
23         main_thread.tsd = tsd;
24         main_thread.self = &main_thread;
25         if (__set_thread_area(&main_thread) < 0)
26                 return -1;
27         main_thread.errno_ptr = __errno_location();
28         libc.errno_location = errno_location;
29         main_thread.tid = main_thread.pid = 
30                 syscall1(__NR_set_tid_address, (long)&main_thread.tid);
31         return 0;
32 }
33
34 pthread_t pthread_self()
35 {
36         static int init, failed;
37         if (!init) {
38                 if (failed) return 0;
39                 if (init_main_thread() < 0) failed = 1;
40                 if (failed) return 0;
41                 init = 1;
42         }
43         return __pthread_self();
44 }