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 void AsanThreadContext::OnCreated(void *arg) {
31 CreateThreadContextArgs *args = static_cast<CreateThreadContextArgs*>(arg);
33 stack_id = StackDepotPut(*args->stack);
34 thread = args->thread;
35 thread->set_context(this);
38 void AsanThreadContext::OnFinished() {
39 // Drop the link to the AsanThread object.
43 // MIPS requires aligned address
44 static ALIGNED(16) char thread_registry_placeholder[sizeof(ThreadRegistry)];
45 static ThreadRegistry *asan_thread_registry;
47 static BlockingMutex mu_for_thread_context(LINKER_INITIALIZED);
48 static LowLevelAllocator allocator_for_thread_context;
50 static ThreadContextBase *GetAsanThreadContext(u32 tid) {
51 BlockingMutexLock lock(&mu_for_thread_context);
52 return new(allocator_for_thread_context) AsanThreadContext(tid);
55 ThreadRegistry &asanThreadRegistry() {
56 static bool initialized;
57 // Don't worry about thread_safety - this should be called when there is
60 // Never reuse ASan threads: we store pointer to AsanThreadContext
61 // in TSD and can't reliably tell when no more TSD destructors will
62 // be called. It would be wrong to reuse AsanThreadContext for another
63 // thread before all TSD destructors will be called for it.
64 asan_thread_registry = new(thread_registry_placeholder) ThreadRegistry(
65 GetAsanThreadContext, kMaxNumberOfThreads, kMaxNumberOfThreads);
68 return *asan_thread_registry;
71 AsanThreadContext *GetThreadContextByTidLocked(u32 tid) {
72 return static_cast<AsanThreadContext *>(
73 asanThreadRegistry().GetThreadLocked(tid));
76 // AsanThread implementation.
78 AsanThread *AsanThread::Create(thread_callback_t start_routine, void *arg,
79 u32 parent_tid, StackTrace *stack,
81 uptr PageSize = GetPageSizeCached();
82 uptr size = RoundUpTo(sizeof(AsanThread), PageSize);
83 AsanThread *thread = (AsanThread*)MmapOrDie(size, __func__);
84 thread->start_routine_ = start_routine;
86 AsanThreadContext::CreateThreadContextArgs args = {thread, stack};
87 asanThreadRegistry().CreateThread(*reinterpret_cast<uptr *>(thread), detached,
93 void AsanThread::TSDDtor(void *tsd) {
94 AsanThreadContext *context = (AsanThreadContext*)tsd;
95 VReport(1, "T%d TSDDtor\n", context->tid);
97 context->thread->Destroy();
100 void AsanThread::Destroy() {
101 int tid = this->tid();
102 VReport(1, "T%d exited\n", tid);
104 malloc_storage().CommitBack();
105 if (common_flags()->use_sigaltstack) UnsetAlternateSignalStack();
106 asanThreadRegistry().FinishThread(tid);
107 FlushToDeadThreadStats(&stats_);
108 // We also clear the shadow on thread destruction because
109 // some code may still be executing in later TSD destructors
110 // and we don't want it to have any poisoned stack.
111 ClearShadowForThreadStackAndTLS();
112 DeleteFakeStack(tid);
113 uptr size = RoundUpTo(sizeof(AsanThread), GetPageSizeCached());
114 UnmapOrDie(this, size);
118 void AsanThread::StartSwitchFiber(FakeStack **fake_stack_save, uptr bottom,
120 if (atomic_load(&stack_switching_, memory_order_relaxed)) {
121 Report("ERROR: starting fiber switch while in fiber switch\n");
125 next_stack_bottom_ = bottom;
126 next_stack_top_ = bottom + size;
127 atomic_store(&stack_switching_, 1, memory_order_release);
129 FakeStack *current_fake_stack = fake_stack_;
131 *fake_stack_save = fake_stack_;
132 fake_stack_ = nullptr;
133 SetTLSFakeStack(nullptr);
134 // if fake_stack_save is null, the fiber will die, delete the fakestack
135 if (!fake_stack_save && current_fake_stack)
136 current_fake_stack->Destroy(this->tid());
139 void AsanThread::FinishSwitchFiber(FakeStack *fake_stack_save,
142 if (!atomic_load(&stack_switching_, memory_order_relaxed)) {
143 Report("ERROR: finishing a fiber switch that has not started\n");
147 if (fake_stack_save) {
148 SetTLSFakeStack(fake_stack_save);
149 fake_stack_ = fake_stack_save;
153 *bottom_old = stack_bottom_;
155 *size_old = stack_top_ - stack_bottom_;
156 stack_bottom_ = next_stack_bottom_;
157 stack_top_ = next_stack_top_;
158 atomic_store(&stack_switching_, 0, memory_order_release);
160 next_stack_bottom_ = 0;
163 inline AsanThread::StackBounds AsanThread::GetStackBounds() const {
164 if (!atomic_load(&stack_switching_, memory_order_acquire)) {
165 // Make sure the stack bounds are fully initialized.
166 if (stack_bottom_ >= stack_top_) return {0, 0};
167 return {stack_bottom_, stack_top_};
170 const uptr cur_stack = (uptr)&local;
171 // Note: need to check next stack first, because FinishSwitchFiber
172 // may be in process of overwriting stack_top_/bottom_. But in such case
173 // we are already on the next stack.
174 if (cur_stack >= next_stack_bottom_ && cur_stack < next_stack_top_)
175 return {next_stack_bottom_, next_stack_top_};
176 return {stack_bottom_, stack_top_};
179 uptr AsanThread::stack_top() {
180 return GetStackBounds().top;
183 uptr AsanThread::stack_bottom() {
184 return GetStackBounds().bottom;
187 uptr AsanThread::stack_size() {
188 const auto bounds = GetStackBounds();
189 return bounds.top - bounds.bottom;
192 // We want to create the FakeStack lazyly on the first use, but not eralier
193 // than the stack size is known and the procedure has to be async-signal safe.
194 FakeStack *AsanThread::AsyncSignalSafeLazyInitFakeStack() {
195 uptr stack_size = this->stack_size();
196 if (stack_size == 0) // stack_size is not yet available, don't use FakeStack.
199 // fake_stack_ has 3 states:
200 // 0 -- not initialized
201 // 1 -- being initialized
202 // ptr -- initialized
203 // This CAS checks if the state was 0 and if so changes it to state 1,
204 // if that was successful, it initializes the pointer.
205 if (atomic_compare_exchange_strong(
206 reinterpret_cast<atomic_uintptr_t *>(&fake_stack_), &old_val, 1UL,
207 memory_order_relaxed)) {
208 uptr stack_size_log = Log2(RoundUpToPowerOfTwo(stack_size));
209 CHECK_LE(flags()->min_uar_stack_size_log, flags()->max_uar_stack_size_log);
211 Min(stack_size_log, static_cast<uptr>(flags()->max_uar_stack_size_log));
213 Max(stack_size_log, static_cast<uptr>(flags()->min_uar_stack_size_log));
214 fake_stack_ = FakeStack::Create(stack_size_log);
215 SetTLSFakeStack(fake_stack_);
221 void AsanThread::Init(const InitOptions *options) {
222 next_stack_top_ = next_stack_bottom_ = 0;
223 atomic_store(&stack_switching_, false, memory_order_release);
224 CHECK_EQ(this->stack_size(), 0U);
225 SetThreadStackAndTls(options);
226 if (stack_top_ != stack_bottom_) {
227 CHECK_GT(this->stack_size(), 0U);
228 CHECK(AddrIsInMem(stack_bottom_));
229 CHECK(AddrIsInMem(stack_top_ - 1));
231 ClearShadowForThreadStackAndTLS();
232 fake_stack_ = nullptr;
233 if (__asan_option_detect_stack_use_after_return)
234 AsyncSignalSafeLazyInitFakeStack();
236 VReport(1, "T%d: stack [%p,%p) size 0x%zx; local=%p\n", tid(),
237 (void *)stack_bottom_, (void *)stack_top_, stack_top_ - stack_bottom_,
241 // Fuchsia and RTEMS don't use ThreadStart.
242 // asan_fuchsia.c/asan_rtems.c define CreateMainThread and
243 // SetThreadStackAndTls.
244 #if !SANITIZER_FUCHSIA && !SANITIZER_RTEMS
246 thread_return_t AsanThread::ThreadStart(
247 tid_t os_id, atomic_uintptr_t *signal_thread_is_registered) {
249 asanThreadRegistry().StartThread(tid(), os_id, /*workerthread*/ false,
251 if (signal_thread_is_registered)
252 atomic_store(signal_thread_is_registered, 1, memory_order_release);
254 if (common_flags()->use_sigaltstack) SetAlternateSignalStack();
256 if (!start_routine_) {
257 // start_routine_ == 0 if we're on the main thread or on one of the
258 // OS X libdispatch worker threads. But nobody is supposed to call
259 // ThreadStart() for the worker threads.
264 thread_return_t res = start_routine_(arg_);
266 // On POSIX systems we defer this to the TSD destructor. LSan will consider
267 // the thread's memory as non-live from the moment we call Destroy(), even
268 // though that memory might contain pointers to heap objects which will be
269 // cleaned up by a user-defined TSD destructor. Thus, calling Destroy() before
270 // the TSD destructors have run might cause false positives in LSan.
271 if (!SANITIZER_POSIX)
277 AsanThread *CreateMainThread() {
278 AsanThread *main_thread = AsanThread::Create(
279 /* start_routine */ nullptr, /* arg */ nullptr, /* parent_tid */ 0,
280 /* stack */ nullptr, /* detached */ true);
281 SetCurrentThread(main_thread);
282 main_thread->ThreadStart(internal_getpid(),
283 /* signal_thread_is_registered */ nullptr);
287 // This implementation doesn't use the argument, which is just passed down
288 // from the caller of Init (which see, above). It's only there to support
289 // OS-specific implementations that need more information passed through.
290 void AsanThread::SetThreadStackAndTls(const InitOptions *options) {
291 DCHECK_EQ(options, nullptr);
294 GetThreadStackAndTls(tid() == 0, &stack_bottom_, &stack_size, &tls_begin_,
296 stack_top_ = stack_bottom_ + stack_size;
297 tls_end_ = tls_begin_ + tls_size;
300 if (stack_top_ != stack_bottom_) {
302 CHECK(AddrIsInStack((uptr)&local));
306 #endif // !SANITIZER_FUCHSIA && !SANITIZER_RTEMS
308 void AsanThread::ClearShadowForThreadStackAndTLS() {
309 if (stack_top_ != stack_bottom_)
310 PoisonShadow(stack_bottom_, stack_top_ - stack_bottom_, 0);
311 if (tls_begin_ != tls_end_) {
312 uptr tls_begin_aligned = RoundDownTo(tls_begin_, SHADOW_GRANULARITY);
313 uptr tls_end_aligned = RoundUpTo(tls_end_, SHADOW_GRANULARITY);
314 FastPoisonShadowPartialRightRedzone(tls_begin_aligned,
315 tls_end_ - tls_begin_aligned,
316 tls_end_aligned - tls_end_, 0);
320 bool AsanThread::GetStackFrameAccessByAddr(uptr addr,
321 StackFrameAccess *access) {
322 if (stack_top_ == stack_bottom_)
326 if (AddrIsInStack(addr)) {
327 bottom = stack_bottom();
328 } else if (has_fake_stack()) {
329 bottom = fake_stack()->AddrIsInFakeStack(addr);
331 access->offset = addr - bottom;
332 access->frame_pc = ((uptr*)bottom)[2];
333 access->frame_descr = (const char *)((uptr*)bottom)[1];
336 uptr aligned_addr = RoundDownTo(addr, SANITIZER_WORDSIZE / 8); // align addr.
337 uptr mem_ptr = RoundDownTo(aligned_addr, SHADOW_GRANULARITY);
338 u8 *shadow_ptr = (u8*)MemToShadow(aligned_addr);
339 u8 *shadow_bottom = (u8*)MemToShadow(bottom);
341 while (shadow_ptr >= shadow_bottom &&
342 *shadow_ptr != kAsanStackLeftRedzoneMagic) {
344 mem_ptr -= SHADOW_GRANULARITY;
347 while (shadow_ptr >= shadow_bottom &&
348 *shadow_ptr == kAsanStackLeftRedzoneMagic) {
350 mem_ptr -= SHADOW_GRANULARITY;
353 if (shadow_ptr < shadow_bottom) {
357 uptr* ptr = (uptr*)(mem_ptr + SHADOW_GRANULARITY);
358 CHECK(ptr[0] == kCurrentStackFrameMagic);
359 access->offset = addr - (uptr)ptr;
360 access->frame_pc = ptr[2];
361 access->frame_descr = (const char*)ptr[1];
365 uptr AsanThread::GetStackVariableShadowStart(uptr addr) {
367 if (AddrIsInStack(addr)) {
368 bottom = stack_bottom();
369 } else if (has_fake_stack()) {
370 bottom = fake_stack()->AddrIsInFakeStack(addr);
375 uptr aligned_addr = RoundDownTo(addr, SANITIZER_WORDSIZE / 8); // align addr.
376 u8 *shadow_ptr = (u8*)MemToShadow(aligned_addr);
377 u8 *shadow_bottom = (u8*)MemToShadow(bottom);
379 while (shadow_ptr >= shadow_bottom &&
380 (*shadow_ptr != kAsanStackLeftRedzoneMagic &&
381 *shadow_ptr != kAsanStackMidRedzoneMagic &&
382 *shadow_ptr != kAsanStackRightRedzoneMagic))
385 return (uptr)shadow_ptr + 1;
388 bool AsanThread::AddrIsInStack(uptr addr) {
389 const auto bounds = GetStackBounds();
390 return addr >= bounds.bottom && addr < bounds.top;
393 static bool ThreadStackContainsAddress(ThreadContextBase *tctx_base,
395 AsanThreadContext *tctx = static_cast<AsanThreadContext*>(tctx_base);
396 AsanThread *t = tctx->thread;
397 if (!t) return false;
398 if (t->AddrIsInStack((uptr)addr)) return true;
399 if (t->has_fake_stack() && t->fake_stack()->AddrIsInFakeStack((uptr)addr))
404 AsanThread *GetCurrentThread() {
405 if (SANITIZER_RTEMS && !asan_inited)
408 AsanThreadContext *context =
409 reinterpret_cast<AsanThreadContext *>(AsanTSDGet());
411 if (SANITIZER_ANDROID) {
412 // On Android, libc constructor is called _after_ asan_init, and cleans up
413 // TSD. Try to figure out if this is still the main thread by the stack
414 // address. We are not entirely sure that we have correct main thread
415 // limits, so only do this magic on Android, and only if the found thread
416 // is the main thread.
417 AsanThreadContext *tctx = GetThreadContextByTidLocked(0);
418 if (tctx && ThreadStackContainsAddress(tctx, &context)) {
419 SetCurrentThread(tctx->thread);
425 return context->thread;
428 void SetCurrentThread(AsanThread *t) {
430 VReport(2, "SetCurrentThread: %p for thread %p\n", t->context(),
431 (void *)GetThreadSelf());
432 // Make sure we do not reset the current AsanThread.
433 CHECK_EQ(0, AsanTSDGet());
434 AsanTSDSet(t->context());
435 CHECK_EQ(t->context(), AsanTSDGet());
438 u32 GetCurrentTidOrInvalid() {
439 AsanThread *t = GetCurrentThread();
440 return t ? t->tid() : kInvalidTid;
443 AsanThread *FindThreadByStackAddress(uptr addr) {
444 asanThreadRegistry().CheckLocked();
445 AsanThreadContext *tctx = static_cast<AsanThreadContext *>(
446 asanThreadRegistry().FindThreadContextLocked(ThreadStackContainsAddress,
448 return tctx ? tctx->thread : nullptr;
451 void EnsureMainThreadIDIsCorrect() {
452 AsanThreadContext *context =
453 reinterpret_cast<AsanThreadContext *>(AsanTSDGet());
454 if (context && (context->tid == 0))
455 context->os_id = GetTid();
458 __asan::AsanThread *GetAsanThreadByOsIDLocked(tid_t os_id) {
459 __asan::AsanThreadContext *context = static_cast<__asan::AsanThreadContext *>(
460 __asan::asanThreadRegistry().FindThreadContextByOsIDLocked(os_id));
461 if (!context) return nullptr;
462 return context->thread;
464 } // namespace __asan
466 // --- Implementation of LSan-specific functions --- {{{1
468 bool GetThreadRangesLocked(tid_t os_id, uptr *stack_begin, uptr *stack_end,
469 uptr *tls_begin, uptr *tls_end, uptr *cache_begin,
470 uptr *cache_end, DTLS **dtls) {
471 __asan::AsanThread *t = __asan::GetAsanThreadByOsIDLocked(os_id);
472 if (!t) return false;
473 *stack_begin = t->stack_bottom();
474 *stack_end = t->stack_top();
475 *tls_begin = t->tls_begin();
476 *tls_end = t->tls_end();
477 // ASan doesn't keep allocator caches in TLS, so these are unused.
484 void ForEachExtraStackRange(tid_t os_id, RangeIteratorCallback callback,
486 __asan::AsanThread *t = __asan::GetAsanThreadByOsIDLocked(os_id);
487 if (t && t->has_fake_stack())
488 t->fake_stack()->ForEachFakeFrame(callback, arg);
491 void LockThreadRegistry() {
492 __asan::asanThreadRegistry().Lock();
495 void UnlockThreadRegistry() {
496 __asan::asanThreadRegistry().Unlock();
499 ThreadRegistry *GetThreadRegistryLocked() {
500 __asan::asanThreadRegistry().CheckLocked();
501 return &__asan::asanThreadRegistry();
504 void EnsureMainThreadIDIsCorrect() {
505 __asan::EnsureMainThreadIDIsCorrect();
507 } // namespace __lsan
509 // ---------------------- Interface ---------------- {{{1
510 using namespace __asan; // NOLINT
513 SANITIZER_INTERFACE_ATTRIBUTE
514 void __sanitizer_start_switch_fiber(void **fakestacksave, const void *bottom,
516 AsanThread *t = GetCurrentThread();
518 VReport(1, "__asan_start_switch_fiber called from unknown thread\n");
521 t->StartSwitchFiber((FakeStack**)fakestacksave, (uptr)bottom, size);
524 SANITIZER_INTERFACE_ATTRIBUTE
525 void __sanitizer_finish_switch_fiber(void* fakestack,
526 const void **bottom_old,
528 AsanThread *t = GetCurrentThread();
530 VReport(1, "__asan_finish_switch_fiber called from unknown thread\n");
533 t->FinishSwitchFiber((FakeStack*)fakestack,