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