1 //===-- Implementation of tls for riscv -----------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "src/__support/OSUtil/syscall.h"
10 #include "src/__support/threads/thread.h"
11 #include "src/string/memory_utils/inline_memcpy.h"
12 #include "startup/linux/do_start.h"
15 #include <sys/syscall.h>
17 namespace LIBC_NAMESPACE
{
20 static constexpr long MMAP_SYSCALL_NUMBER
= SYS_mmap2
;
22 static constexpr long MMAP_SYSCALL_NUMBER
= SYS_mmap
;
24 #error "mmap and mmap2 syscalls not available."
27 void init_tls(TLSDescriptor
&tls_descriptor
) {
28 if (app
.tls
.size
== 0) {
29 tls_descriptor
.size
= 0;
30 tls_descriptor
.tp
= 0;
34 // riscv64 follows the variant 1 TLS layout:
35 const uintptr_t size_of_pointers
= 2 * sizeof(uintptr_t);
36 uintptr_t padding
= 0;
37 const uintptr_t ALIGNMENT_MASK
= app
.tls
.align
- 1;
38 uintptr_t diff
= size_of_pointers
& ALIGNMENT_MASK
;
40 padding
+= (ALIGNMENT_MASK
- diff
) + 1;
42 uintptr_t alloc_size
= size_of_pointers
+ padding
+ app
.tls
.size
;
44 // We cannot call the mmap function here as the functions set errno on
45 // failure. Since errno is implemented via a thread local variable, we cannot
46 // use errno before TLS is setup.
47 long mmap_ret_val
= syscall_impl
<long>(MMAP_SYSCALL_NUMBER
, nullptr,
48 alloc_size
, PROT_READ
| PROT_WRITE
,
49 MAP_ANONYMOUS
| MAP_PRIVATE
, -1, 0);
50 // We cannot check the return value with MAP_FAILED as that is the return
51 // of the mmap function and not the mmap syscall.
52 if (mmap_ret_val
< 0 && static_cast<uintptr_t>(mmap_ret_val
) > -app
.page_size
)
53 syscall_impl
<long>(SYS_exit
, 1);
54 uintptr_t thread_ptr
= uintptr_t(reinterpret_cast<uintptr_t *>(mmap_ret_val
));
55 uintptr_t tls_addr
= thread_ptr
+ size_of_pointers
+ padding
;
56 inline_memcpy(reinterpret_cast<char *>(tls_addr
),
57 reinterpret_cast<const char *>(app
.tls
.address
),
59 tls_descriptor
.size
= alloc_size
;
60 tls_descriptor
.addr
= thread_ptr
;
61 tls_descriptor
.tp
= tls_addr
;
64 void cleanup_tls(uintptr_t addr
, uintptr_t size
) {
67 syscall_impl
<long>(SYS_munmap
, addr
, size
);
70 bool set_thread_ptr(uintptr_t val
) {
71 LIBC_INLINE_ASM("mv tp, %0\n\t" : : "r"(val
));
74 } // namespace LIBC_NAMESPACE