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 fake_stack_ = nullptr; // Will be initialized lazily if needed.
225 CHECK_EQ(this->stack_size(), 0U);
226 SetThreadStackAndTls(options);
227 CHECK_GT(this->stack_size(), 0U);
228 CHECK(AddrIsInMem(stack_bottom_));
229 CHECK(AddrIsInMem(stack_top_ - 1));
230 ClearShadowForThreadStackAndTLS();
232 VReport(1, "T%d: stack [%p,%p) size 0x%zx; local=%p\n", tid(),
233 (void *)stack_bottom_, (void *)stack_top_, stack_top_ - stack_bottom_,
237 // Fuchsia doesn't use ThreadStart.
238 // asan_fuchsia.c defines CreateMainThread and SetThreadStackAndTls.
239 #if !SANITIZER_FUCHSIA
241 thread_return_t AsanThread::ThreadStart(
242 tid_t os_id, atomic_uintptr_t *signal_thread_is_registered) {
244 asanThreadRegistry().StartThread(tid(), os_id, /*workerthread*/ false,
246 if (signal_thread_is_registered)
247 atomic_store(signal_thread_is_registered, 1, memory_order_release);
249 if (common_flags()->use_sigaltstack) SetAlternateSignalStack();
251 if (!start_routine_) {
252 // start_routine_ == 0 if we're on the main thread or on one of the
253 // OS X libdispatch worker threads. But nobody is supposed to call
254 // ThreadStart() for the worker threads.
259 thread_return_t res = start_routine_(arg_);
261 // On POSIX systems we defer this to the TSD destructor. LSan will consider
262 // the thread's memory as non-live from the moment we call Destroy(), even
263 // though that memory might contain pointers to heap objects which will be
264 // cleaned up by a user-defined TSD destructor. Thus, calling Destroy() before
265 // the TSD destructors have run might cause false positives in LSan.
266 if (!SANITIZER_POSIX)
272 AsanThread *CreateMainThread() {
273 AsanThread *main_thread = AsanThread::Create(
274 /* start_routine */ nullptr, /* arg */ nullptr, /* parent_tid */ 0,
275 /* stack */ nullptr, /* detached */ true);
276 SetCurrentThread(main_thread);
277 main_thread->ThreadStart(internal_getpid(),
278 /* signal_thread_is_registered */ nullptr);
282 // This implementation doesn't use the argument, which is just passed down
283 // from the caller of Init (which see, above). It's only there to support
284 // OS-specific implementations that need more information passed through.
285 void AsanThread::SetThreadStackAndTls(const InitOptions *options) {
286 DCHECK_EQ(options, nullptr);
289 GetThreadStackAndTls(tid() == 0, const_cast<uptr *>(&stack_bottom_),
290 const_cast<uptr *>(&stack_size), &tls_begin_, &tls_size);
291 stack_top_ = stack_bottom_ + stack_size;
292 tls_end_ = tls_begin_ + tls_size;
296 CHECK(AddrIsInStack((uptr)&local));
299 #endif // !SANITIZER_FUCHSIA
301 void AsanThread::ClearShadowForThreadStackAndTLS() {
302 PoisonShadow(stack_bottom_, stack_top_ - stack_bottom_, 0);
303 if (tls_begin_ != tls_end_)
304 PoisonShadow(tls_begin_, tls_end_ - tls_begin_, 0);
307 bool AsanThread::GetStackFrameAccessByAddr(uptr addr,
308 StackFrameAccess *access) {
310 if (AddrIsInStack(addr)) {
311 bottom = stack_bottom();
312 } else if (has_fake_stack()) {
313 bottom = fake_stack()->AddrIsInFakeStack(addr);
315 access->offset = addr - bottom;
316 access->frame_pc = ((uptr*)bottom)[2];
317 access->frame_descr = (const char *)((uptr*)bottom)[1];
320 uptr aligned_addr = RoundDownTo(addr, SANITIZER_WORDSIZE / 8); // align addr.
321 uptr mem_ptr = RoundDownTo(aligned_addr, SHADOW_GRANULARITY);
322 u8 *shadow_ptr = (u8*)MemToShadow(aligned_addr);
323 u8 *shadow_bottom = (u8*)MemToShadow(bottom);
325 while (shadow_ptr >= shadow_bottom &&
326 *shadow_ptr != kAsanStackLeftRedzoneMagic) {
328 mem_ptr -= SHADOW_GRANULARITY;
331 while (shadow_ptr >= shadow_bottom &&
332 *shadow_ptr == kAsanStackLeftRedzoneMagic) {
334 mem_ptr -= SHADOW_GRANULARITY;
337 if (shadow_ptr < shadow_bottom) {
341 uptr* ptr = (uptr*)(mem_ptr + SHADOW_GRANULARITY);
342 CHECK(ptr[0] == kCurrentStackFrameMagic);
343 access->offset = addr - (uptr)ptr;
344 access->frame_pc = ptr[2];
345 access->frame_descr = (const char*)ptr[1];
349 uptr AsanThread::GetStackVariableShadowStart(uptr addr) {
351 if (AddrIsInStack(addr)) {
352 bottom = stack_bottom();
353 } else if (has_fake_stack()) {
354 bottom = fake_stack()->AddrIsInFakeStack(addr);
359 uptr aligned_addr = RoundDownTo(addr, SANITIZER_WORDSIZE / 8); // align addr.
360 u8 *shadow_ptr = (u8*)MemToShadow(aligned_addr);
361 u8 *shadow_bottom = (u8*)MemToShadow(bottom);
363 while (shadow_ptr >= shadow_bottom &&
364 (*shadow_ptr != kAsanStackLeftRedzoneMagic &&
365 *shadow_ptr != kAsanStackMidRedzoneMagic &&
366 *shadow_ptr != kAsanStackRightRedzoneMagic))
369 return (uptr)shadow_ptr + 1;
372 bool AsanThread::AddrIsInStack(uptr addr) {
373 const auto bounds = GetStackBounds();
374 return addr >= bounds.bottom && addr < bounds.top;
377 static bool ThreadStackContainsAddress(ThreadContextBase *tctx_base,
379 AsanThreadContext *tctx = static_cast<AsanThreadContext*>(tctx_base);
380 AsanThread *t = tctx->thread;
381 if (!t) return false;
382 if (t->AddrIsInStack((uptr)addr)) return true;
383 if (t->has_fake_stack() && t->fake_stack()->AddrIsInFakeStack((uptr)addr))
388 AsanThread *GetCurrentThread() {
389 AsanThreadContext *context =
390 reinterpret_cast<AsanThreadContext *>(AsanTSDGet());
392 if (SANITIZER_ANDROID) {
393 // On Android, libc constructor is called _after_ asan_init, and cleans up
394 // TSD. Try to figure out if this is still the main thread by the stack
395 // address. We are not entirely sure that we have correct main thread
396 // limits, so only do this magic on Android, and only if the found thread
397 // is the main thread.
398 AsanThreadContext *tctx = GetThreadContextByTidLocked(0);
399 if (tctx && ThreadStackContainsAddress(tctx, &context)) {
400 SetCurrentThread(tctx->thread);
406 return context->thread;
409 void SetCurrentThread(AsanThread *t) {
411 VReport(2, "SetCurrentThread: %p for thread %p\n", t->context(),
412 (void *)GetThreadSelf());
413 // Make sure we do not reset the current AsanThread.
414 CHECK_EQ(0, AsanTSDGet());
415 AsanTSDSet(t->context());
416 CHECK_EQ(t->context(), AsanTSDGet());
419 u32 GetCurrentTidOrInvalid() {
420 AsanThread *t = GetCurrentThread();
421 return t ? t->tid() : kInvalidTid;
424 AsanThread *FindThreadByStackAddress(uptr addr) {
425 asanThreadRegistry().CheckLocked();
426 AsanThreadContext *tctx = static_cast<AsanThreadContext *>(
427 asanThreadRegistry().FindThreadContextLocked(ThreadStackContainsAddress,
429 return tctx ? tctx->thread : nullptr;
432 void EnsureMainThreadIDIsCorrect() {
433 AsanThreadContext *context =
434 reinterpret_cast<AsanThreadContext *>(AsanTSDGet());
435 if (context && (context->tid == 0))
436 context->os_id = GetTid();
439 __asan::AsanThread *GetAsanThreadByOsIDLocked(tid_t os_id) {
440 __asan::AsanThreadContext *context = static_cast<__asan::AsanThreadContext *>(
441 __asan::asanThreadRegistry().FindThreadContextByOsIDLocked(os_id));
442 if (!context) return nullptr;
443 return context->thread;
445 } // namespace __asan
447 // --- Implementation of LSan-specific functions --- {{{1
449 bool GetThreadRangesLocked(tid_t os_id, uptr *stack_begin, uptr *stack_end,
450 uptr *tls_begin, uptr *tls_end, uptr *cache_begin,
451 uptr *cache_end, DTLS **dtls) {
452 __asan::AsanThread *t = __asan::GetAsanThreadByOsIDLocked(os_id);
453 if (!t) return false;
454 *stack_begin = t->stack_bottom();
455 *stack_end = t->stack_top();
456 *tls_begin = t->tls_begin();
457 *tls_end = t->tls_end();
458 // ASan doesn't keep allocator caches in TLS, so these are unused.
465 void ForEachExtraStackRange(tid_t os_id, RangeIteratorCallback callback,
467 __asan::AsanThread *t = __asan::GetAsanThreadByOsIDLocked(os_id);
468 if (t && t->has_fake_stack())
469 t->fake_stack()->ForEachFakeFrame(callback, arg);
472 void LockThreadRegistry() {
473 __asan::asanThreadRegistry().Lock();
476 void UnlockThreadRegistry() {
477 __asan::asanThreadRegistry().Unlock();
480 void EnsureMainThreadIDIsCorrect() {
481 __asan::EnsureMainThreadIDIsCorrect();
483 } // namespace __lsan
485 // ---------------------- Interface ---------------- {{{1
486 using namespace __asan; // NOLINT
489 SANITIZER_INTERFACE_ATTRIBUTE
490 void __sanitizer_start_switch_fiber(void **fakestacksave, const void *bottom,
492 AsanThread *t = GetCurrentThread();
494 VReport(1, "__asan_start_switch_fiber called from unknown thread\n");
497 t->StartSwitchFiber((FakeStack**)fakestacksave, (uptr)bottom, size);
500 SANITIZER_INTERFACE_ATTRIBUTE
501 void __sanitizer_finish_switch_fiber(void* fakestack,
502 const void **bottom_old,
504 AsanThread *t = GetCurrentThread();
506 VReport(1, "__asan_finish_switch_fiber called from unknown thread\n");
509 t->FinishSwitchFiber((FakeStack*)fakestack,