llvm-project
592 строки · 19.6 Кб
1//===-- asan_thread.cpp ---------------------------------------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file is a part of AddressSanitizer, an address sanity checker.
10//
11// Thread-related code.
12//===----------------------------------------------------------------------===//
13#include "asan_thread.h"
14
15#include "asan_allocator.h"
16#include "asan_interceptors.h"
17#include "asan_mapping.h"
18#include "asan_poisoning.h"
19#include "asan_stack.h"
20#include "lsan/lsan_common.h"
21#include "sanitizer_common/sanitizer_common.h"
22#include "sanitizer_common/sanitizer_placement_new.h"
23#include "sanitizer_common/sanitizer_stackdepot.h"
24#include "sanitizer_common/sanitizer_tls_get_addr.h"
25
26namespace __asan {
27
28// AsanThreadContext implementation.
29
30void AsanThreadContext::OnCreated(void *arg) {
31CreateThreadContextArgs *args = static_cast<CreateThreadContextArgs *>(arg);
32if (args->stack)
33stack_id = StackDepotPut(*args->stack);
34thread = args->thread;
35thread->set_context(this);
36}
37
38void AsanThreadContext::OnFinished() {
39// Drop the link to the AsanThread object.
40thread = nullptr;
41}
42
43static ThreadRegistry *asan_thread_registry;
44static ThreadArgRetval *thread_data;
45
46static Mutex mu_for_thread_context;
47// TODO(leonardchan@): It should be possible to make LowLevelAllocator
48// threadsafe and consolidate this one into the GlobalLoweLevelAllocator.
49// We should be able to do something similar to what's in
50// sanitizer_stack_store.cpp.
51static LowLevelAllocator allocator_for_thread_context;
52
53static ThreadContextBase *GetAsanThreadContext(u32 tid) {
54Lock lock(&mu_for_thread_context);
55return new (allocator_for_thread_context) AsanThreadContext(tid);
56}
57
58static void InitThreads() {
59static bool initialized;
60// Don't worry about thread_safety - this should be called when there is
61// a single thread.
62if (LIKELY(initialized))
63return;
64// Never reuse ASan threads: we store pointer to AsanThreadContext
65// in TSD and can't reliably tell when no more TSD destructors will
66// be called. It would be wrong to reuse AsanThreadContext for another
67// thread before all TSD destructors will be called for it.
68
69// MIPS requires aligned address
70static ALIGNED(alignof(
71ThreadRegistry)) char thread_registry_placeholder[sizeof(ThreadRegistry)];
72static ALIGNED(alignof(
73ThreadArgRetval)) char thread_data_placeholder[sizeof(ThreadArgRetval)];
74
75asan_thread_registry =
76new (thread_registry_placeholder) ThreadRegistry(GetAsanThreadContext);
77thread_data = new (thread_data_placeholder) ThreadArgRetval();
78initialized = true;
79}
80
81ThreadRegistry &asanThreadRegistry() {
82InitThreads();
83return *asan_thread_registry;
84}
85
86ThreadArgRetval &asanThreadArgRetval() {
87InitThreads();
88return *thread_data;
89}
90
91AsanThreadContext *GetThreadContextByTidLocked(u32 tid) {
92return static_cast<AsanThreadContext *>(
93asanThreadRegistry().GetThreadLocked(tid));
94}
95
96// AsanThread implementation.
97
98AsanThread *AsanThread::Create(const void *start_data, uptr data_size,
99u32 parent_tid, StackTrace *stack,
100bool detached) {
101uptr PageSize = GetPageSizeCached();
102uptr size = RoundUpTo(sizeof(AsanThread), PageSize);
103AsanThread *thread = (AsanThread *)MmapOrDie(size, __func__);
104if (data_size) {
105uptr availible_size = (uptr)thread + size - (uptr)(thread->start_data_);
106CHECK_LE(data_size, availible_size);
107internal_memcpy(thread->start_data_, start_data, data_size);
108}
109AsanThreadContext::CreateThreadContextArgs args = {thread, stack};
110asanThreadRegistry().CreateThread(0, detached, parent_tid, &args);
111
112return thread;
113}
114
115void AsanThread::GetStartData(void *out, uptr out_size) const {
116internal_memcpy(out, start_data_, out_size);
117}
118
119void AsanThread::TSDDtor(void *tsd) {
120AsanThreadContext *context = (AsanThreadContext *)tsd;
121VReport(1, "T%d TSDDtor\n", context->tid);
122if (context->thread)
123context->thread->Destroy();
124}
125
126void AsanThread::Destroy() {
127int tid = this->tid();
128VReport(1, "T%d exited\n", tid);
129
130bool was_running =
131(asanThreadRegistry().FinishThread(tid) == ThreadStatusRunning);
132if (was_running) {
133if (AsanThread *thread = GetCurrentThread())
134CHECK_EQ(this, thread);
135malloc_storage().CommitBack();
136if (common_flags()->use_sigaltstack)
137UnsetAlternateSignalStack();
138FlushToDeadThreadStats(&stats_);
139// We also clear the shadow on thread destruction because
140// some code may still be executing in later TSD destructors
141// and we don't want it to have any poisoned stack.
142ClearShadowForThreadStackAndTLS();
143DeleteFakeStack(tid);
144} else {
145CHECK_NE(this, GetCurrentThread());
146}
147uptr size = RoundUpTo(sizeof(AsanThread), GetPageSizeCached());
148UnmapOrDie(this, size);
149if (was_running)
150DTLS_Destroy();
151}
152
153void AsanThread::StartSwitchFiber(FakeStack **fake_stack_save, uptr bottom,
154uptr size) {
155if (atomic_load(&stack_switching_, memory_order_relaxed)) {
156Report("ERROR: starting fiber switch while in fiber switch\n");
157Die();
158}
159
160next_stack_bottom_ = bottom;
161next_stack_top_ = bottom + size;
162atomic_store(&stack_switching_, 1, memory_order_release);
163
164FakeStack *current_fake_stack = fake_stack_;
165if (fake_stack_save)
166*fake_stack_save = fake_stack_;
167fake_stack_ = nullptr;
168SetTLSFakeStack(nullptr);
169// if fake_stack_save is null, the fiber will die, delete the fakestack
170if (!fake_stack_save && current_fake_stack)
171current_fake_stack->Destroy(this->tid());
172}
173
174void AsanThread::FinishSwitchFiber(FakeStack *fake_stack_save, uptr *bottom_old,
175uptr *size_old) {
176if (!atomic_load(&stack_switching_, memory_order_relaxed)) {
177Report("ERROR: finishing a fiber switch that has not started\n");
178Die();
179}
180
181if (fake_stack_save) {
182SetTLSFakeStack(fake_stack_save);
183fake_stack_ = fake_stack_save;
184}
185
186if (bottom_old)
187*bottom_old = stack_bottom_;
188if (size_old)
189*size_old = stack_top_ - stack_bottom_;
190stack_bottom_ = next_stack_bottom_;
191stack_top_ = next_stack_top_;
192atomic_store(&stack_switching_, 0, memory_order_release);
193next_stack_top_ = 0;
194next_stack_bottom_ = 0;
195}
196
197inline AsanThread::StackBounds AsanThread::GetStackBounds() const {
198if (!atomic_load(&stack_switching_, memory_order_acquire)) {
199// Make sure the stack bounds are fully initialized.
200if (stack_bottom_ >= stack_top_)
201return {0, 0};
202return {stack_bottom_, stack_top_};
203}
204char local;
205const uptr cur_stack = (uptr)&local;
206// Note: need to check next stack first, because FinishSwitchFiber
207// may be in process of overwriting stack_top_/bottom_. But in such case
208// we are already on the next stack.
209if (cur_stack >= next_stack_bottom_ && cur_stack < next_stack_top_)
210return {next_stack_bottom_, next_stack_top_};
211return {stack_bottom_, stack_top_};
212}
213
214uptr AsanThread::stack_top() { return GetStackBounds().top; }
215
216uptr AsanThread::stack_bottom() { return GetStackBounds().bottom; }
217
218uptr AsanThread::stack_size() {
219const auto bounds = GetStackBounds();
220return bounds.top - bounds.bottom;
221}
222
223// We want to create the FakeStack lazily on the first use, but not earlier
224// than the stack size is known and the procedure has to be async-signal safe.
225FakeStack *AsanThread::AsyncSignalSafeLazyInitFakeStack() {
226uptr stack_size = this->stack_size();
227if (stack_size == 0) // stack_size is not yet available, don't use FakeStack.
228return nullptr;
229uptr old_val = 0;
230// fake_stack_ has 3 states:
231// 0 -- not initialized
232// 1 -- being initialized
233// ptr -- initialized
234// This CAS checks if the state was 0 and if so changes it to state 1,
235// if that was successful, it initializes the pointer.
236if (atomic_compare_exchange_strong(
237reinterpret_cast<atomic_uintptr_t *>(&fake_stack_), &old_val, 1UL,
238memory_order_relaxed)) {
239uptr stack_size_log = Log2(RoundUpToPowerOfTwo(stack_size));
240CHECK_LE(flags()->min_uar_stack_size_log, flags()->max_uar_stack_size_log);
241stack_size_log =
242Min(stack_size_log, static_cast<uptr>(flags()->max_uar_stack_size_log));
243stack_size_log =
244Max(stack_size_log, static_cast<uptr>(flags()->min_uar_stack_size_log));
245fake_stack_ = FakeStack::Create(stack_size_log);
246DCHECK_EQ(GetCurrentThread(), this);
247SetTLSFakeStack(fake_stack_);
248return fake_stack_;
249}
250return nullptr;
251}
252
253void AsanThread::Init(const InitOptions *options) {
254DCHECK_NE(tid(), kInvalidTid);
255next_stack_top_ = next_stack_bottom_ = 0;
256atomic_store(&stack_switching_, false, memory_order_release);
257CHECK_EQ(this->stack_size(), 0U);
258SetThreadStackAndTls(options);
259if (stack_top_ != stack_bottom_) {
260CHECK_GT(this->stack_size(), 0U);
261CHECK(AddrIsInMem(stack_bottom_));
262CHECK(AddrIsInMem(stack_top_ - 1));
263}
264ClearShadowForThreadStackAndTLS();
265fake_stack_ = nullptr;
266if (__asan_option_detect_stack_use_after_return &&
267tid() == GetCurrentTidOrInvalid()) {
268// AsyncSignalSafeLazyInitFakeStack makes use of threadlocals and must be
269// called from the context of the thread it is initializing, not its parent.
270// Most platforms call AsanThread::Init on the newly-spawned thread, but
271// Fuchsia calls this function from the parent thread. To support that
272// approach, we avoid calling AsyncSignalSafeLazyInitFakeStack here; it will
273// be called by the new thread when it first attempts to access the fake
274// stack.
275AsyncSignalSafeLazyInitFakeStack();
276}
277int local = 0;
278VReport(1, "T%d: stack [%p,%p) size 0x%zx; local=%p\n", tid(),
279(void *)stack_bottom_, (void *)stack_top_, stack_top_ - stack_bottom_,
280(void *)&local);
281}
282
283// Fuchsia doesn't use ThreadStart.
284// asan_fuchsia.c definies CreateMainThread and SetThreadStackAndTls.
285#if !SANITIZER_FUCHSIA
286
287void AsanThread::ThreadStart(tid_t os_id) {
288Init();
289asanThreadRegistry().StartThread(tid(), os_id, ThreadType::Regular, nullptr);
290
291if (common_flags()->use_sigaltstack)
292SetAlternateSignalStack();
293}
294
295AsanThread *CreateMainThread() {
296AsanThread *main_thread = AsanThread::Create(
297/* parent_tid */ kMainTid,
298/* stack */ nullptr, /* detached */ true);
299SetCurrentThread(main_thread);
300main_thread->ThreadStart(internal_getpid());
301return main_thread;
302}
303
304// This implementation doesn't use the argument, which is just passed down
305// from the caller of Init (which see, above). It's only there to support
306// OS-specific implementations that need more information passed through.
307void AsanThread::SetThreadStackAndTls(const InitOptions *options) {
308DCHECK_EQ(options, nullptr);
309uptr tls_size = 0;
310uptr stack_size = 0;
311GetThreadStackAndTls(tid() == kMainTid, &stack_bottom_, &stack_size,
312&tls_begin_, &tls_size);
313stack_top_ = RoundDownTo(stack_bottom_ + stack_size, ASAN_SHADOW_GRANULARITY);
314stack_bottom_ = RoundDownTo(stack_bottom_, ASAN_SHADOW_GRANULARITY);
315tls_end_ = tls_begin_ + tls_size;
316dtls_ = DTLS_Get();
317
318if (stack_top_ != stack_bottom_) {
319int local;
320CHECK(AddrIsInStack((uptr)&local));
321}
322}
323
324#endif // !SANITIZER_FUCHSIA
325
326void AsanThread::ClearShadowForThreadStackAndTLS() {
327if (stack_top_ != stack_bottom_)
328PoisonShadow(stack_bottom_, stack_top_ - stack_bottom_, 0);
329if (tls_begin_ != tls_end_) {
330uptr tls_begin_aligned = RoundDownTo(tls_begin_, ASAN_SHADOW_GRANULARITY);
331uptr tls_end_aligned = RoundUpTo(tls_end_, ASAN_SHADOW_GRANULARITY);
332FastPoisonShadow(tls_begin_aligned, tls_end_aligned - tls_begin_aligned, 0);
333}
334}
335
336bool AsanThread::GetStackFrameAccessByAddr(uptr addr,
337StackFrameAccess *access) {
338if (stack_top_ == stack_bottom_)
339return false;
340
341uptr bottom = 0;
342if (AddrIsInStack(addr)) {
343bottom = stack_bottom();
344} else if (FakeStack *fake_stack = get_fake_stack()) {
345bottom = fake_stack->AddrIsInFakeStack(addr);
346CHECK(bottom);
347access->offset = addr - bottom;
348access->frame_pc = ((uptr *)bottom)[2];
349access->frame_descr = (const char *)((uptr *)bottom)[1];
350return true;
351}
352uptr aligned_addr = RoundDownTo(addr, SANITIZER_WORDSIZE / 8); // align addr.
353uptr mem_ptr = RoundDownTo(aligned_addr, ASAN_SHADOW_GRANULARITY);
354u8 *shadow_ptr = (u8 *)MemToShadow(aligned_addr);
355u8 *shadow_bottom = (u8 *)MemToShadow(bottom);
356
357while (shadow_ptr >= shadow_bottom &&
358*shadow_ptr != kAsanStackLeftRedzoneMagic) {
359shadow_ptr--;
360mem_ptr -= ASAN_SHADOW_GRANULARITY;
361}
362
363while (shadow_ptr >= shadow_bottom &&
364*shadow_ptr == kAsanStackLeftRedzoneMagic) {
365shadow_ptr--;
366mem_ptr -= ASAN_SHADOW_GRANULARITY;
367}
368
369if (shadow_ptr < shadow_bottom) {
370return false;
371}
372
373uptr *ptr = (uptr *)(mem_ptr + ASAN_SHADOW_GRANULARITY);
374CHECK(ptr[0] == kCurrentStackFrameMagic);
375access->offset = addr - (uptr)ptr;
376access->frame_pc = ptr[2];
377access->frame_descr = (const char *)ptr[1];
378return true;
379}
380
381uptr AsanThread::GetStackVariableShadowStart(uptr addr) {
382uptr bottom = 0;
383if (AddrIsInStack(addr)) {
384bottom = stack_bottom();
385} else if (FakeStack *fake_stack = get_fake_stack()) {
386bottom = fake_stack->AddrIsInFakeStack(addr);
387if (bottom == 0) {
388return 0;
389}
390} else {
391return 0;
392}
393
394uptr aligned_addr = RoundDownTo(addr, SANITIZER_WORDSIZE / 8); // align addr.
395u8 *shadow_ptr = (u8 *)MemToShadow(aligned_addr);
396u8 *shadow_bottom = (u8 *)MemToShadow(bottom);
397
398while (shadow_ptr >= shadow_bottom &&
399(*shadow_ptr != kAsanStackLeftRedzoneMagic &&
400*shadow_ptr != kAsanStackMidRedzoneMagic &&
401*shadow_ptr != kAsanStackRightRedzoneMagic))
402shadow_ptr--;
403
404return (uptr)shadow_ptr + 1;
405}
406
407bool AsanThread::AddrIsInStack(uptr addr) {
408const auto bounds = GetStackBounds();
409return addr >= bounds.bottom && addr < bounds.top;
410}
411
412static bool ThreadStackContainsAddress(ThreadContextBase *tctx_base,
413void *addr) {
414AsanThreadContext *tctx = static_cast<AsanThreadContext *>(tctx_base);
415AsanThread *t = tctx->thread;
416if (!t)
417return false;
418if (t->AddrIsInStack((uptr)addr))
419return true;
420FakeStack *fake_stack = t->get_fake_stack();
421if (!fake_stack)
422return false;
423return fake_stack->AddrIsInFakeStack((uptr)addr);
424}
425
426AsanThread *GetCurrentThread() {
427AsanThreadContext *context =
428reinterpret_cast<AsanThreadContext *>(AsanTSDGet());
429if (!context) {
430if (SANITIZER_ANDROID) {
431// On Android, libc constructor is called _after_ asan_init, and cleans up
432// TSD. Try to figure out if this is still the main thread by the stack
433// address. We are not entirely sure that we have correct main thread
434// limits, so only do this magic on Android, and only if the found thread
435// is the main thread.
436AsanThreadContext *tctx = GetThreadContextByTidLocked(kMainTid);
437if (tctx && ThreadStackContainsAddress(tctx, &context)) {
438SetCurrentThread(tctx->thread);
439return tctx->thread;
440}
441}
442return nullptr;
443}
444return context->thread;
445}
446
447void SetCurrentThread(AsanThread *t) {
448CHECK(t->context());
449VReport(2, "SetCurrentThread: %p for thread %p\n", (void *)t->context(),
450(void *)GetThreadSelf());
451// Make sure we do not reset the current AsanThread.
452CHECK_EQ(0, AsanTSDGet());
453AsanTSDSet(t->context());
454CHECK_EQ(t->context(), AsanTSDGet());
455}
456
457u32 GetCurrentTidOrInvalid() {
458AsanThread *t = GetCurrentThread();
459return t ? t->tid() : kInvalidTid;
460}
461
462AsanThread *FindThreadByStackAddress(uptr addr) {
463asanThreadRegistry().CheckLocked();
464AsanThreadContext *tctx = static_cast<AsanThreadContext *>(
465asanThreadRegistry().FindThreadContextLocked(ThreadStackContainsAddress,
466(void *)addr));
467return tctx ? tctx->thread : nullptr;
468}
469
470void EnsureMainThreadIDIsCorrect() {
471AsanThreadContext *context =
472reinterpret_cast<AsanThreadContext *>(AsanTSDGet());
473if (context && (context->tid == kMainTid))
474context->os_id = GetTid();
475}
476
477__asan::AsanThread *GetAsanThreadByOsIDLocked(tid_t os_id) {
478__asan::AsanThreadContext *context = static_cast<__asan::AsanThreadContext *>(
479__asan::asanThreadRegistry().FindThreadContextByOsIDLocked(os_id));
480if (!context)
481return nullptr;
482return context->thread;
483}
484} // namespace __asan
485
486// --- Implementation of LSan-specific functions --- {{{1
487namespace __lsan {
488void LockThreads() {
489__asan::asanThreadRegistry().Lock();
490__asan::asanThreadArgRetval().Lock();
491}
492
493void UnlockThreads() {
494__asan::asanThreadArgRetval().Unlock();
495__asan::asanThreadRegistry().Unlock();
496}
497
498static ThreadRegistry *GetAsanThreadRegistryLocked() {
499__asan::asanThreadRegistry().CheckLocked();
500return &__asan::asanThreadRegistry();
501}
502
503void EnsureMainThreadIDIsCorrect() { __asan::EnsureMainThreadIDIsCorrect(); }
504
505bool GetThreadRangesLocked(tid_t os_id, uptr *stack_begin, uptr *stack_end,
506uptr *tls_begin, uptr *tls_end, uptr *cache_begin,
507uptr *cache_end, DTLS **dtls) {
508__asan::AsanThread *t = __asan::GetAsanThreadByOsIDLocked(os_id);
509if (!t)
510return false;
511*stack_begin = t->stack_bottom();
512*stack_end = t->stack_top();
513*tls_begin = t->tls_begin();
514*tls_end = t->tls_end();
515// ASan doesn't keep allocator caches in TLS, so these are unused.
516*cache_begin = 0;
517*cache_end = 0;
518*dtls = t->dtls();
519return true;
520}
521
522void GetAllThreadAllocatorCachesLocked(InternalMmapVector<uptr> *caches) {}
523
524void GetThreadExtraStackRangesLocked(tid_t os_id,
525InternalMmapVector<Range> *ranges) {
526__asan::AsanThread *t = __asan::GetAsanThreadByOsIDLocked(os_id);
527if (!t)
528return;
529__asan::FakeStack *fake_stack = t->get_fake_stack();
530if (!fake_stack)
531return;
532
533fake_stack->ForEachFakeFrame(
534[](uptr begin, uptr end, void *arg) {
535reinterpret_cast<InternalMmapVector<Range> *>(arg)->push_back(
536{begin, end});
537},
538ranges);
539}
540
541void GetThreadExtraStackRangesLocked(InternalMmapVector<Range> *ranges) {
542GetAsanThreadRegistryLocked()->RunCallbackForEachThreadLocked(
543[](ThreadContextBase *tctx, void *arg) {
544GetThreadExtraStackRangesLocked(
545tctx->os_id, reinterpret_cast<InternalMmapVector<Range> *>(arg));
546},
547ranges);
548}
549
550void GetAdditionalThreadContextPtrsLocked(InternalMmapVector<uptr> *ptrs) {
551__asan::asanThreadArgRetval().GetAllPtrsLocked(ptrs);
552}
553
554void GetRunningThreadsLocked(InternalMmapVector<tid_t> *threads) {
555GetAsanThreadRegistryLocked()->RunCallbackForEachThreadLocked(
556[](ThreadContextBase *tctx, void *threads) {
557if (tctx->status == ThreadStatusRunning)
558reinterpret_cast<InternalMmapVector<tid_t> *>(threads)->push_back(
559tctx->os_id);
560},
561threads);
562}
563
564} // namespace __lsan
565
566// ---------------------- Interface ---------------- {{{1
567using namespace __asan;
568
569extern "C" {
570SANITIZER_INTERFACE_ATTRIBUTE
571void __sanitizer_start_switch_fiber(void **fakestacksave, const void *bottom,
572uptr size) {
573AsanThread *t = GetCurrentThread();
574if (!t) {
575VReport(1, "__asan_start_switch_fiber called from unknown thread\n");
576return;
577}
578t->StartSwitchFiber((FakeStack **)fakestacksave, (uptr)bottom, size);
579}
580
581SANITIZER_INTERFACE_ATTRIBUTE
582void __sanitizer_finish_switch_fiber(void *fakestack, const void **bottom_old,
583uptr *size_old) {
584AsanThread *t = GetCurrentThread();
585if (!t) {
586VReport(1, "__asan_finish_switch_fiber called from unknown thread\n");
587return;
588}
589t->FinishSwitchFiber((FakeStack *)fakestack, (uptr *)bottom_old,
590(uptr *)size_old);
591}
592}
593