1 //===-- asan_thread.cc ----------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is a part of AddressSanitizer, an address sanity checker.
12 // Thread-related code.
13 //===----------------------------------------------------------------------===//
14 #include "asan_allocator.h"
15 #include "asan_interceptors.h"
16 #include "asan_poisoning.h"
17 #include "asan_stack.h"
18 #include "asan_thread.h"
19 #include "asan_mapping.h"
20 #include "sanitizer_common/sanitizer_common.h"
21 #include "sanitizer_common/sanitizer_placement_new.h"
22 #include "sanitizer_common/sanitizer_stackdepot.h"
23 #include "sanitizer_common/sanitizer_tls_get_addr.h"
24 #include "lsan/lsan_common.h"
28 // AsanThreadContext implementation.
30 struct CreateThreadContextArgs {
35 void AsanThreadContext::OnCreated(void *arg) {
36 CreateThreadContextArgs *args = static_cast<CreateThreadContextArgs*>(arg);
38 stack_id = StackDepotPut(*args->stack);
39 thread = args->thread;
40 thread->set_context(this);
43 void AsanThreadContext::OnFinished() {
44 // Drop the link to the AsanThread object.
48 // MIPS requires aligned address
49 static ALIGNED(16) char thread_registry_placeholder[sizeof(ThreadRegistry)];
50 static ThreadRegistry *asan_thread_registry;
52 static BlockingMutex mu_for_thread_context(LINKER_INITIALIZED);
53 static LowLevelAllocator allocator_for_thread_context;
55 static ThreadContextBase *GetAsanThreadContext(u32 tid) {
56 BlockingMutexLock lock(&mu_for_thread_context);
57 return new(allocator_for_thread_context) AsanThreadContext(tid);
60 ThreadRegistry &asanThreadRegistry() {
61 static bool initialized;
62 // Don't worry about thread_safety - this should be called when there is
65 // Never reuse ASan threads: we store pointer to AsanThreadContext
66 // in TSD and can't reliably tell when no more TSD destructors will
67 // be called. It would be wrong to reuse AsanThreadContext for another
68 // thread before all TSD destructors will be called for it.
69 asan_thread_registry = new(thread_registry_placeholder) ThreadRegistry(
70 GetAsanThreadContext, kMaxNumberOfThreads, kMaxNumberOfThreads);
73 return *asan_thread_registry;
76 AsanThreadContext *GetThreadContextByTidLocked(u32 tid) {
77 return static_cast<AsanThreadContext *>(
78 asanThreadRegistry().GetThreadLocked(tid));
81 // AsanThread implementation.
83 AsanThread *AsanThread::Create(thread_callback_t start_routine, void *arg,
84 u32 parent_tid, StackTrace *stack,
86 uptr PageSize = GetPageSizeCached();
87 uptr size = RoundUpTo(sizeof(AsanThread), PageSize);
88 AsanThread *thread = (AsanThread*)MmapOrDie(size, __func__);
89 thread->start_routine_ = start_routine;
91 CreateThreadContextArgs args = { thread, stack };
92 asanThreadRegistry().CreateThread(*reinterpret_cast<uptr *>(thread), detached,
98 void AsanThread::TSDDtor(void *tsd) {
99 AsanThreadContext *context = (AsanThreadContext*)tsd;
100 VReport(1, "T%d TSDDtor\n", context->tid);
102 context->thread->Destroy();
105 void AsanThread::Destroy() {
106 int tid = this->tid();
107 VReport(1, "T%d exited\n", tid);
109 malloc_storage().CommitBack();
110 if (common_flags()->use_sigaltstack) UnsetAlternateSignalStack();
111 asanThreadRegistry().FinishThread(tid);
112 FlushToDeadThreadStats(&stats_);
113 // We also clear the shadow on thread destruction because
114 // some code may still be executing in later TSD destructors
115 // and we don't want it to have any poisoned stack.
116 ClearShadowForThreadStackAndTLS();
117 DeleteFakeStack(tid);
118 uptr size = RoundUpTo(sizeof(AsanThread), GetPageSizeCached());
119 UnmapOrDie(this, size);
123 void AsanThread::StartSwitchFiber(FakeStack **fake_stack_save, uptr bottom,
125 if (atomic_load(&stack_switching_, memory_order_relaxed)) {
126 Report("ERROR: starting fiber switch while in fiber switch\n");
130 next_stack_bottom_ = bottom;
131 next_stack_top_ = bottom + size;
132 atomic_store(&stack_switching_, 1, memory_order_release);
134 FakeStack *current_fake_stack = fake_stack_;
136 *fake_stack_save = fake_stack_;
137 fake_stack_ = nullptr;
138 SetTLSFakeStack(nullptr);
139 // if fake_stack_save is null, the fiber will die, delete the fakestack
140 if (!fake_stack_save && current_fake_stack)
141 current_fake_stack->Destroy(this->tid());
144 void AsanThread::FinishSwitchFiber(FakeStack *fake_stack_save,
147 if (!atomic_load(&stack_switching_, memory_order_relaxed)) {
148 Report("ERROR: finishing a fiber switch that has not started\n");
152 if (fake_stack_save) {
153 SetTLSFakeStack(fake_stack_save);
154 fake_stack_ = fake_stack_save;
158 *bottom_old = stack_bottom_;
160 *size_old = stack_top_ - stack_bottom_;
161 stack_bottom_ = next_stack_bottom_;
162 stack_top_ = next_stack_top_;
163 atomic_store(&stack_switching_, 0, memory_order_release);
165 next_stack_bottom_ = 0;
168 inline AsanThread::StackBounds AsanThread::GetStackBounds() const {
169 if (!atomic_load(&stack_switching_, memory_order_acquire)) {
170 // Make sure the stack bounds are fully initialized.
171 if (stack_bottom_ >= stack_top_) return {0, 0};
172 return {stack_bottom_, stack_top_};
175 const uptr cur_stack = (uptr)&local;
176 // Note: need to check next stack first, because FinishSwitchFiber
177 // may be in process of overwriting stack_top_/bottom_. But in such case
178 // we are already on the next stack.
179 if (cur_stack >= next_stack_bottom_ && cur_stack < next_stack_top_)
180 return {next_stack_bottom_, next_stack_top_};
181 return {stack_bottom_, stack_top_};
184 uptr AsanThread::stack_top() {
185 return GetStackBounds().top;
188 uptr AsanThread::stack_bottom() {
189 return GetStackBounds().bottom;
192 uptr AsanThread::stack_size() {
193 const auto bounds = GetStackBounds();
194 return bounds.top - bounds.bottom;
197 // We want to create the FakeStack lazyly on the first use, but not eralier
198 // than the stack size is known and the procedure has to be async-signal safe.
199 FakeStack *AsanThread::AsyncSignalSafeLazyInitFakeStack() {
200 uptr stack_size = this->stack_size();
201 if (stack_size == 0) // stack_size is not yet available, don't use FakeStack.
204 // fake_stack_ has 3 states:
205 // 0 -- not initialized
206 // 1 -- being initialized
207 // ptr -- initialized
208 // This CAS checks if the state was 0 and if so changes it to state 1,
209 // if that was successful, it initializes the pointer.
210 if (atomic_compare_exchange_strong(
211 reinterpret_cast<atomic_uintptr_t *>(&fake_stack_), &old_val, 1UL,
212 memory_order_relaxed)) {
213 uptr stack_size_log = Log2(RoundUpToPowerOfTwo(stack_size));
214 CHECK_LE(flags()->min_uar_stack_size_log, flags()->max_uar_stack_size_log);
216 Min(stack_size_log, static_cast<uptr>(flags()->max_uar_stack_size_log));
218 Max(stack_size_log, static_cast<uptr>(flags()->min_uar_stack_size_log));
219 fake_stack_ = FakeStack::Create(stack_size_log);
220 SetTLSFakeStack(fake_stack_);
226 void AsanThread::Init() {
227 next_stack_top_ = next_stack_bottom_ = 0;
228 atomic_store(&stack_switching_, false, memory_order_release);
229 fake_stack_ = nullptr; // Will be initialized lazily if needed.
230 CHECK_EQ(this->stack_size(), 0U);
231 SetThreadStackAndTls();
232 CHECK_GT(this->stack_size(), 0U);
233 CHECK(AddrIsInMem(stack_bottom_));
234 CHECK(AddrIsInMem(stack_top_ - 1));
235 ClearShadowForThreadStackAndTLS();
237 VReport(1, "T%d: stack [%p,%p) size 0x%zx; local=%p\n", tid(),
238 (void *)stack_bottom_, (void *)stack_top_, stack_top_ - stack_bottom_,
242 thread_return_t AsanThread::ThreadStart(
243 tid_t os_id, atomic_uintptr_t *signal_thread_is_registered) {
245 asanThreadRegistry().StartThread(tid(), os_id, /*workerthread*/ false,
247 if (signal_thread_is_registered)
248 atomic_store(signal_thread_is_registered, 1, memory_order_release);
250 if (common_flags()->use_sigaltstack) SetAlternateSignalStack();
252 if (!start_routine_) {
253 // start_routine_ == 0 if we're on the main thread or on one of the
254 // OS X libdispatch worker threads. But nobody is supposed to call
255 // ThreadStart() for the worker threads.
260 thread_return_t res = start_routine_(arg_);
262 // On POSIX systems we defer this to the TSD destructor. LSan will consider
263 // the thread's memory as non-live from the moment we call Destroy(), even
264 // though that memory might contain pointers to heap objects which will be
265 // cleaned up by a user-defined TSD destructor. Thus, calling Destroy() before
266 // the TSD destructors have run might cause false positives in LSan.
267 if (!SANITIZER_POSIX)
273 void AsanThread::SetThreadStackAndTls() {
276 GetThreadStackAndTls(tid() == 0, const_cast<uptr *>(&stack_bottom_),
277 const_cast<uptr *>(&stack_size), &tls_begin_, &tls_size);
278 stack_top_ = stack_bottom_ + stack_size;
279 tls_end_ = tls_begin_ + tls_size;
283 CHECK(AddrIsInStack((uptr)&local));
286 void AsanThread::ClearShadowForThreadStackAndTLS() {
287 PoisonShadow(stack_bottom_, stack_top_ - stack_bottom_, 0);
288 if (tls_begin_ != tls_end_)
289 PoisonShadow(tls_begin_, tls_end_ - tls_begin_, 0);
292 bool AsanThread::GetStackFrameAccessByAddr(uptr addr,
293 StackFrameAccess *access) {
295 if (AddrIsInStack(addr)) {
296 bottom = stack_bottom();
297 } else if (has_fake_stack()) {
298 bottom = fake_stack()->AddrIsInFakeStack(addr);
300 access->offset = addr - bottom;
301 access->frame_pc = ((uptr*)bottom)[2];
302 access->frame_descr = (const char *)((uptr*)bottom)[1];
305 uptr aligned_addr = addr & ~(SANITIZER_WORDSIZE/8 - 1); // align addr.
306 uptr mem_ptr = RoundDownTo(aligned_addr, SHADOW_GRANULARITY);
307 u8 *shadow_ptr = (u8*)MemToShadow(aligned_addr);
308 u8 *shadow_bottom = (u8*)MemToShadow(bottom);
310 while (shadow_ptr >= shadow_bottom &&
311 *shadow_ptr != kAsanStackLeftRedzoneMagic) {
313 mem_ptr -= SHADOW_GRANULARITY;
316 while (shadow_ptr >= shadow_bottom &&
317 *shadow_ptr == kAsanStackLeftRedzoneMagic) {
319 mem_ptr -= SHADOW_GRANULARITY;
322 if (shadow_ptr < shadow_bottom) {
326 uptr* ptr = (uptr*)(mem_ptr + SHADOW_GRANULARITY);
327 CHECK(ptr[0] == kCurrentStackFrameMagic);
328 access->offset = addr - (uptr)ptr;
329 access->frame_pc = ptr[2];
330 access->frame_descr = (const char*)ptr[1];
334 bool AsanThread::AddrIsInStack(uptr addr) {
335 const auto bounds = GetStackBounds();
336 return addr >= bounds.bottom && addr < bounds.top;
339 static bool ThreadStackContainsAddress(ThreadContextBase *tctx_base,
341 AsanThreadContext *tctx = static_cast<AsanThreadContext*>(tctx_base);
342 AsanThread *t = tctx->thread;
343 if (!t) return false;
344 if (t->AddrIsInStack((uptr)addr)) return true;
345 if (t->has_fake_stack() && t->fake_stack()->AddrIsInFakeStack((uptr)addr))
350 AsanThread *GetCurrentThread() {
351 AsanThreadContext *context =
352 reinterpret_cast<AsanThreadContext *>(AsanTSDGet());
354 if (SANITIZER_ANDROID) {
355 // On Android, libc constructor is called _after_ asan_init, and cleans up
356 // TSD. Try to figure out if this is still the main thread by the stack
357 // address. We are not entirely sure that we have correct main thread
358 // limits, so only do this magic on Android, and only if the found thread
359 // is the main thread.
360 AsanThreadContext *tctx = GetThreadContextByTidLocked(0);
361 if (tctx && ThreadStackContainsAddress(tctx, &context)) {
362 SetCurrentThread(tctx->thread);
368 return context->thread;
371 void SetCurrentThread(AsanThread *t) {
373 VReport(2, "SetCurrentThread: %p for thread %p\n", t->context(),
374 (void *)GetThreadSelf());
375 // Make sure we do not reset the current AsanThread.
376 CHECK_EQ(0, AsanTSDGet());
377 AsanTSDSet(t->context());
378 CHECK_EQ(t->context(), AsanTSDGet());
381 u32 GetCurrentTidOrInvalid() {
382 AsanThread *t = GetCurrentThread();
383 return t ? t->tid() : kInvalidTid;
386 AsanThread *FindThreadByStackAddress(uptr addr) {
387 asanThreadRegistry().CheckLocked();
388 AsanThreadContext *tctx = static_cast<AsanThreadContext *>(
389 asanThreadRegistry().FindThreadContextLocked(ThreadStackContainsAddress,
391 return tctx ? tctx->thread : nullptr;
394 void EnsureMainThreadIDIsCorrect() {
395 AsanThreadContext *context =
396 reinterpret_cast<AsanThreadContext *>(AsanTSDGet());
397 if (context && (context->tid == 0))
398 context->os_id = GetTid();
401 __asan::AsanThread *GetAsanThreadByOsIDLocked(tid_t os_id) {
402 __asan::AsanThreadContext *context = static_cast<__asan::AsanThreadContext *>(
403 __asan::asanThreadRegistry().FindThreadContextByOsIDLocked(os_id));
404 if (!context) return nullptr;
405 return context->thread;
407 } // namespace __asan
409 // --- Implementation of LSan-specific functions --- {{{1
411 bool GetThreadRangesLocked(tid_t os_id, uptr *stack_begin, uptr *stack_end,
412 uptr *tls_begin, uptr *tls_end, uptr *cache_begin,
413 uptr *cache_end, DTLS **dtls) {
414 __asan::AsanThread *t = __asan::GetAsanThreadByOsIDLocked(os_id);
415 if (!t) return false;
416 *stack_begin = t->stack_bottom();
417 *stack_end = t->stack_top();
418 *tls_begin = t->tls_begin();
419 *tls_end = t->tls_end();
420 // ASan doesn't keep allocator caches in TLS, so these are unused.
427 void ForEachExtraStackRange(tid_t os_id, RangeIteratorCallback callback,
429 __asan::AsanThread *t = __asan::GetAsanThreadByOsIDLocked(os_id);
430 if (t && t->has_fake_stack())
431 t->fake_stack()->ForEachFakeFrame(callback, arg);
434 void LockThreadRegistry() {
435 __asan::asanThreadRegistry().Lock();
438 void UnlockThreadRegistry() {
439 __asan::asanThreadRegistry().Unlock();
442 void EnsureMainThreadIDIsCorrect() {
443 __asan::EnsureMainThreadIDIsCorrect();
445 } // namespace __lsan
447 // ---------------------- Interface ---------------- {{{1
448 using namespace __asan; // NOLINT
451 SANITIZER_INTERFACE_ATTRIBUTE
452 void __sanitizer_start_switch_fiber(void **fakestacksave, const void *bottom,
454 AsanThread *t = GetCurrentThread();
456 VReport(1, "__asan_start_switch_fiber called from unknown thread\n");
459 t->StartSwitchFiber((FakeStack**)fakestacksave, (uptr)bottom, size);
462 SANITIZER_INTERFACE_ATTRIBUTE
463 void __sanitizer_finish_switch_fiber(void* fakestack,
464 const void **bottom_old,
466 AsanThread *t = GetCurrentThread();
468 VReport(1, "__asan_finish_switch_fiber called from unknown thread\n");
471 t->FinishSwitchFiber((FakeStack*)fakestack,