3 #include "hwasan_mapping.h"
4 #include "hwasan_thread.h"
5 #include "hwasan_poisoning.h"
6 #include "hwasan_interface_internal.h"
8 #include "sanitizer_common/sanitizer_tls_get_addr.h"
12 static u32 RandomSeed() {
15 if (UNLIKELY(!GetRandom(reinterpret_cast<void *>(&seed), sizeof(seed),
16 /*blocking=*/false))) {
17 seed = static_cast<u32>(
19 (reinterpret_cast<uptr>(__builtin_frame_address(0)) >> 4));
25 HwasanThread *HwasanThread::Create(thread_callback_t start_routine,
27 uptr PageSize = GetPageSizeCached();
28 uptr size = RoundUpTo(sizeof(HwasanThread), PageSize);
29 HwasanThread *thread = (HwasanThread*)MmapOrDie(size, __func__);
30 thread->start_routine_ = start_routine;
32 thread->destructor_iterations_ = GetPthreadDestructorIterations();
33 thread->random_state_ = flags()->random_tags ? RandomSeed() : 0;
38 void HwasanThread::SetThreadStackAndTls() {
41 GetThreadStackAndTls(IsMainThread(), &stack_bottom_, &stack_size,
42 &tls_begin_, &tls_size);
43 stack_top_ = stack_bottom_ + stack_size;
44 tls_end_ = tls_begin_ + tls_size;
47 CHECK(AddrIsInStack((uptr)&local));
50 void HwasanThread::Init() {
51 SetThreadStackAndTls();
52 CHECK(MEM_IS_APP(stack_bottom_));
53 CHECK(MEM_IS_APP(stack_top_ - 1));
56 void HwasanThread::TSDDtor(void *tsd) {
57 HwasanThread *t = (HwasanThread*)tsd;
61 void HwasanThread::ClearShadowForThreadStackAndTLS() {
62 TagMemory(stack_bottom_, stack_top_ - stack_bottom_, 0);
63 if (tls_begin_ != tls_end_)
64 TagMemory(tls_begin_, tls_end_ - tls_begin_, 0);
67 void HwasanThread::Destroy() {
68 malloc_storage().CommitBack();
69 ClearShadowForThreadStackAndTLS();
70 uptr size = RoundUpTo(sizeof(HwasanThread), GetPageSizeCached());
71 UnmapOrDie(this, size);
75 thread_return_t HwasanThread::ThreadStart() {
78 if (!start_routine_) {
79 // start_routine_ == 0 if we're on the main thread or on one of the
80 // OS X libdispatch worker threads. But nobody is supposed to call
81 // ThreadStart() for the worker threads.
85 thread_return_t res = start_routine_(arg_);
90 static u32 xorshift(u32 state) {
97 // Generate a (pseudo-)random non-zero tag.
98 tag_t HwasanThread::GenerateRandomTag() {
101 if (flags()->random_tags) {
103 random_buffer_ = random_state_ = xorshift(random_state_);
104 CHECK(random_buffer_);
105 tag = random_buffer_ & 0xFF;
106 random_buffer_ >>= 8;
108 tag = random_state_ = (random_state_ + 1) & 0xFF;
114 } // namespace __hwasan