]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/asan/asan_thread.cc
Merge compiler-rt r291274.
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / asan / asan_thread.cc
1 //===-- asan_thread.cc ----------------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file is a part of AddressSanitizer, an address sanity checker.
11 //
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"
25
26 namespace __asan {
27
28 // AsanThreadContext implementation.
29
30 struct CreateThreadContextArgs {
31   AsanThread *thread;
32   StackTrace *stack;
33 };
34
35 void AsanThreadContext::OnCreated(void *arg) {
36   CreateThreadContextArgs *args = static_cast<CreateThreadContextArgs*>(arg);
37   if (args->stack)
38     stack_id = StackDepotPut(*args->stack);
39   thread = args->thread;
40   thread->set_context(this);
41 }
42
43 void AsanThreadContext::OnFinished() {
44   // Drop the link to the AsanThread object.
45   thread = nullptr;
46 }
47
48 // MIPS requires aligned address
49 static ALIGNED(16) char thread_registry_placeholder[sizeof(ThreadRegistry)];
50 static ThreadRegistry *asan_thread_registry;
51
52 static BlockingMutex mu_for_thread_context(LINKER_INITIALIZED);
53 static LowLevelAllocator allocator_for_thread_context;
54
55 static ThreadContextBase *GetAsanThreadContext(u32 tid) {
56   BlockingMutexLock lock(&mu_for_thread_context);
57   return new(allocator_for_thread_context) AsanThreadContext(tid);
58 }
59
60 ThreadRegistry &asanThreadRegistry() {
61   static bool initialized;
62   // Don't worry about thread_safety - this should be called when there is
63   // a single thread.
64   if (!initialized) {
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);
71     initialized = true;
72   }
73   return *asan_thread_registry;
74 }
75
76 AsanThreadContext *GetThreadContextByTidLocked(u32 tid) {
77   return static_cast<AsanThreadContext *>(
78       asanThreadRegistry().GetThreadLocked(tid));
79 }
80
81 // AsanThread implementation.
82
83 AsanThread *AsanThread::Create(thread_callback_t start_routine, void *arg,
84                                u32 parent_tid, StackTrace *stack,
85                                bool detached) {
86   uptr PageSize = GetPageSizeCached();
87   uptr size = RoundUpTo(sizeof(AsanThread), PageSize);
88   AsanThread *thread = (AsanThread*)MmapOrDie(size, __func__);
89   thread->start_routine_ = start_routine;
90   thread->arg_ = arg;
91   CreateThreadContextArgs args = { thread, stack };
92   asanThreadRegistry().CreateThread(*reinterpret_cast<uptr *>(thread), detached,
93                                     parent_tid, &args);
94
95   return thread;
96 }
97
98 void AsanThread::TSDDtor(void *tsd) {
99   AsanThreadContext *context = (AsanThreadContext*)tsd;
100   VReport(1, "T%d TSDDtor\n", context->tid);
101   if (context->thread)
102     context->thread->Destroy();
103 }
104
105 void AsanThread::Destroy() {
106   int tid = this->tid();
107   VReport(1, "T%d exited\n", tid);
108
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);
120   DTLS_Destroy();
121 }
122
123 void AsanThread::StartSwitchFiber(FakeStack **fake_stack_save, uptr bottom,
124                                   uptr size) {
125   if (atomic_load(&stack_switching_, memory_order_relaxed)) {
126     Report("ERROR: starting fiber switch while in fiber switch\n");
127     Die();
128   }
129
130   next_stack_bottom_ = bottom;
131   next_stack_top_ = bottom + size;
132   atomic_store(&stack_switching_, 1, memory_order_release);
133
134   FakeStack *current_fake_stack = fake_stack_;
135   if (fake_stack_save)
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());
142 }
143
144 void AsanThread::FinishSwitchFiber(FakeStack *fake_stack_save,
145                                    uptr *bottom_old,
146                                    uptr *size_old) {
147   if (!atomic_load(&stack_switching_, memory_order_relaxed)) {
148     Report("ERROR: finishing a fiber switch that has not started\n");
149     Die();
150   }
151
152   if (fake_stack_save) {
153     SetTLSFakeStack(fake_stack_save);
154     fake_stack_ = fake_stack_save;
155   }
156
157   if (bottom_old)
158     *bottom_old = stack_bottom_;
159   if (size_old)
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);
164   next_stack_top_ = 0;
165   next_stack_bottom_ = 0;
166 }
167
168 inline AsanThread::StackBounds AsanThread::GetStackBounds() const {
169   if (!atomic_load(&stack_switching_, memory_order_acquire))
170     return StackBounds{stack_bottom_, stack_top_};  // NOLINT
171   char local;
172   const uptr cur_stack = (uptr)&local;
173   // Note: need to check next stack first, because FinishSwitchFiber
174   // may be in process of overwriting stack_top_/bottom_. But in such case
175   // we are already on the next stack.
176   if (cur_stack >= next_stack_bottom_ && cur_stack < next_stack_top_)
177     return StackBounds{next_stack_bottom_, next_stack_top_};  // NOLINT
178   return StackBounds{stack_bottom_, stack_top_};              // NOLINT
179 }
180
181 uptr AsanThread::stack_top() {
182   return GetStackBounds().top;
183 }
184
185 uptr AsanThread::stack_bottom() {
186   return GetStackBounds().bottom;
187 }
188
189 uptr AsanThread::stack_size() {
190   const auto bounds = GetStackBounds();
191   return bounds.top - bounds.bottom;
192 }
193
194 // We want to create the FakeStack lazyly on the first use, but not eralier
195 // than the stack size is known and the procedure has to be async-signal safe.
196 FakeStack *AsanThread::AsyncSignalSafeLazyInitFakeStack() {
197   uptr stack_size = this->stack_size();
198   if (stack_size == 0)  // stack_size is not yet available, don't use FakeStack.
199     return nullptr;
200   uptr old_val = 0;
201   // fake_stack_ has 3 states:
202   // 0   -- not initialized
203   // 1   -- being initialized
204   // ptr -- initialized
205   // This CAS checks if the state was 0 and if so changes it to state 1,
206   // if that was successful, it initializes the pointer.
207   if (atomic_compare_exchange_strong(
208       reinterpret_cast<atomic_uintptr_t *>(&fake_stack_), &old_val, 1UL,
209       memory_order_relaxed)) {
210     uptr stack_size_log = Log2(RoundUpToPowerOfTwo(stack_size));
211     CHECK_LE(flags()->min_uar_stack_size_log, flags()->max_uar_stack_size_log);
212     stack_size_log =
213         Min(stack_size_log, static_cast<uptr>(flags()->max_uar_stack_size_log));
214     stack_size_log =
215         Max(stack_size_log, static_cast<uptr>(flags()->min_uar_stack_size_log));
216     fake_stack_ = FakeStack::Create(stack_size_log);
217     SetTLSFakeStack(fake_stack_);
218     return fake_stack_;
219   }
220   return nullptr;
221 }
222
223 void AsanThread::Init() {
224   next_stack_top_ = next_stack_bottom_ = 0;
225   atomic_store(&stack_switching_, false, memory_order_release);
226   fake_stack_ = nullptr;  // Will be initialized lazily if needed.
227   CHECK_EQ(this->stack_size(), 0U);
228   SetThreadStackAndTls();
229   CHECK_GT(this->stack_size(), 0U);
230   CHECK(AddrIsInMem(stack_bottom_));
231   CHECK(AddrIsInMem(stack_top_ - 1));
232   ClearShadowForThreadStackAndTLS();
233   int local = 0;
234   VReport(1, "T%d: stack [%p,%p) size 0x%zx; local=%p\n", tid(),
235           (void *)stack_bottom_, (void *)stack_top_, stack_top_ - stack_bottom_,
236           &local);
237 }
238
239 thread_return_t AsanThread::ThreadStart(
240     uptr os_id, atomic_uintptr_t *signal_thread_is_registered) {
241   Init();
242   asanThreadRegistry().StartThread(tid(), os_id, nullptr);
243   if (signal_thread_is_registered)
244     atomic_store(signal_thread_is_registered, 1, memory_order_release);
245
246   if (common_flags()->use_sigaltstack) SetAlternateSignalStack();
247
248   if (!start_routine_) {
249     // start_routine_ == 0 if we're on the main thread or on one of the
250     // OS X libdispatch worker threads. But nobody is supposed to call
251     // ThreadStart() for the worker threads.
252     CHECK_EQ(tid(), 0);
253     return 0;
254   }
255
256   thread_return_t res = start_routine_(arg_);
257
258   // On POSIX systems we defer this to the TSD destructor. LSan will consider
259   // the thread's memory as non-live from the moment we call Destroy(), even
260   // though that memory might contain pointers to heap objects which will be
261   // cleaned up by a user-defined TSD destructor. Thus, calling Destroy() before
262   // the TSD destructors have run might cause false positives in LSan.
263   if (!SANITIZER_POSIX)
264     this->Destroy();
265
266   return res;
267 }
268
269 void AsanThread::SetThreadStackAndTls() {
270   uptr tls_size = 0;
271   uptr stack_size = 0;
272   GetThreadStackAndTls(tid() == 0, const_cast<uptr *>(&stack_bottom_),
273                        const_cast<uptr *>(&stack_size), &tls_begin_, &tls_size);
274   stack_top_ = stack_bottom_ + stack_size;
275   tls_end_ = tls_begin_ + tls_size;
276   dtls_ = DTLS_Get();
277
278   int local;
279   CHECK(AddrIsInStack((uptr)&local));
280 }
281
282 void AsanThread::ClearShadowForThreadStackAndTLS() {
283   PoisonShadow(stack_bottom_, stack_top_ - stack_bottom_, 0);
284   if (tls_begin_ != tls_end_)
285     PoisonShadow(tls_begin_, tls_end_ - tls_begin_, 0);
286 }
287
288 bool AsanThread::GetStackFrameAccessByAddr(uptr addr,
289                                            StackFrameAccess *access) {
290   uptr bottom = 0;
291   if (AddrIsInStack(addr)) {
292     bottom = stack_bottom();
293   } else if (has_fake_stack()) {
294     bottom = fake_stack()->AddrIsInFakeStack(addr);
295     CHECK(bottom);
296     access->offset = addr - bottom;
297     access->frame_pc = ((uptr*)bottom)[2];
298     access->frame_descr = (const char *)((uptr*)bottom)[1];
299     return true;
300   }
301   uptr aligned_addr = addr & ~(SANITIZER_WORDSIZE/8 - 1);  // align addr.
302   u8 *shadow_ptr = (u8*)MemToShadow(aligned_addr);
303   u8 *shadow_bottom = (u8*)MemToShadow(bottom);
304
305   while (shadow_ptr >= shadow_bottom &&
306          *shadow_ptr != kAsanStackLeftRedzoneMagic) {
307     shadow_ptr--;
308   }
309
310   while (shadow_ptr >= shadow_bottom &&
311          *shadow_ptr == kAsanStackLeftRedzoneMagic) {
312     shadow_ptr--;
313   }
314
315   if (shadow_ptr < shadow_bottom) {
316     return false;
317   }
318
319   uptr* ptr = (uptr*)SHADOW_TO_MEM((uptr)(shadow_ptr + 1));
320   CHECK(ptr[0] == kCurrentStackFrameMagic);
321   access->offset = addr - (uptr)ptr;
322   access->frame_pc = ptr[2];
323   access->frame_descr = (const char*)ptr[1];
324   return true;
325 }
326
327 bool AsanThread::AddrIsInStack(uptr addr) {
328   const auto bounds = GetStackBounds();
329   return addr >= bounds.bottom && addr < bounds.top;
330 }
331
332 static bool ThreadStackContainsAddress(ThreadContextBase *tctx_base,
333                                        void *addr) {
334   AsanThreadContext *tctx = static_cast<AsanThreadContext*>(tctx_base);
335   AsanThread *t = tctx->thread;
336   if (!t) return false;
337   if (t->AddrIsInStack((uptr)addr)) return true;
338   if (t->has_fake_stack() && t->fake_stack()->AddrIsInFakeStack((uptr)addr))
339     return true;
340   return false;
341 }
342
343 AsanThread *GetCurrentThread() {
344   AsanThreadContext *context =
345       reinterpret_cast<AsanThreadContext *>(AsanTSDGet());
346   if (!context) {
347     if (SANITIZER_ANDROID) {
348       // On Android, libc constructor is called _after_ asan_init, and cleans up
349       // TSD. Try to figure out if this is still the main thread by the stack
350       // address. We are not entirely sure that we have correct main thread
351       // limits, so only do this magic on Android, and only if the found thread
352       // is the main thread.
353       AsanThreadContext *tctx = GetThreadContextByTidLocked(0);
354       if (tctx && ThreadStackContainsAddress(tctx, &context)) {
355         SetCurrentThread(tctx->thread);
356         return tctx->thread;
357       }
358     }
359     return nullptr;
360   }
361   return context->thread;
362 }
363
364 void SetCurrentThread(AsanThread *t) {
365   CHECK(t->context());
366   VReport(2, "SetCurrentThread: %p for thread %p\n", t->context(),
367           (void *)GetThreadSelf());
368   // Make sure we do not reset the current AsanThread.
369   CHECK_EQ(0, AsanTSDGet());
370   AsanTSDSet(t->context());
371   CHECK_EQ(t->context(), AsanTSDGet());
372 }
373
374 u32 GetCurrentTidOrInvalid() {
375   AsanThread *t = GetCurrentThread();
376   return t ? t->tid() : kInvalidTid;
377 }
378
379 AsanThread *FindThreadByStackAddress(uptr addr) {
380   asanThreadRegistry().CheckLocked();
381   AsanThreadContext *tctx = static_cast<AsanThreadContext *>(
382       asanThreadRegistry().FindThreadContextLocked(ThreadStackContainsAddress,
383                                                    (void *)addr));
384   return tctx ? tctx->thread : nullptr;
385 }
386
387 void EnsureMainThreadIDIsCorrect() {
388   AsanThreadContext *context =
389       reinterpret_cast<AsanThreadContext *>(AsanTSDGet());
390   if (context && (context->tid == 0))
391     context->os_id = GetTid();
392 }
393
394 __asan::AsanThread *GetAsanThreadByOsIDLocked(uptr os_id) {
395   __asan::AsanThreadContext *context = static_cast<__asan::AsanThreadContext *>(
396       __asan::asanThreadRegistry().FindThreadContextByOsIDLocked(os_id));
397   if (!context) return nullptr;
398   return context->thread;
399 }
400 } // namespace __asan
401
402 // --- Implementation of LSan-specific functions --- {{{1
403 namespace __lsan {
404 bool GetThreadRangesLocked(uptr os_id, uptr *stack_begin, uptr *stack_end,
405                            uptr *tls_begin, uptr *tls_end, uptr *cache_begin,
406                            uptr *cache_end, DTLS **dtls) {
407   __asan::AsanThread *t = __asan::GetAsanThreadByOsIDLocked(os_id);
408   if (!t) return false;
409   *stack_begin = t->stack_bottom();
410   *stack_end = t->stack_top();
411   *tls_begin = t->tls_begin();
412   *tls_end = t->tls_end();
413   // ASan doesn't keep allocator caches in TLS, so these are unused.
414   *cache_begin = 0;
415   *cache_end = 0;
416   *dtls = t->dtls();
417   return true;
418 }
419
420 void ForEachExtraStackRange(uptr os_id, RangeIteratorCallback callback,
421                             void *arg) {
422   __asan::AsanThread *t = __asan::GetAsanThreadByOsIDLocked(os_id);
423   if (t && t->has_fake_stack())
424     t->fake_stack()->ForEachFakeFrame(callback, arg);
425 }
426
427 void LockThreadRegistry() {
428   __asan::asanThreadRegistry().Lock();
429 }
430
431 void UnlockThreadRegistry() {
432   __asan::asanThreadRegistry().Unlock();
433 }
434
435 void EnsureMainThreadIDIsCorrect() {
436   __asan::EnsureMainThreadIDIsCorrect();
437 }
438 } // namespace __lsan
439
440 // ---------------------- Interface ---------------- {{{1
441 using namespace __asan;  // NOLINT
442
443 extern "C" {
444 SANITIZER_INTERFACE_ATTRIBUTE
445 void __sanitizer_start_switch_fiber(void **fakestacksave, const void *bottom,
446                                     uptr size) {
447   AsanThread *t = GetCurrentThread();
448   if (!t) {
449     VReport(1, "__asan_start_switch_fiber called from unknown thread\n");
450     return;
451   }
452   t->StartSwitchFiber((FakeStack**)fakestacksave, (uptr)bottom, size);
453 }
454
455 SANITIZER_INTERFACE_ATTRIBUTE
456 void __sanitizer_finish_switch_fiber(void* fakestack,
457                                      const void **bottom_old,
458                                      uptr *size_old) {
459   AsanThread *t = GetCurrentThread();
460   if (!t) {
461     VReport(1, "__asan_finish_switch_fiber called from unknown thread\n");
462     return;
463   }
464   t->FinishSwitchFiber((FakeStack*)fakestack,
465                        (uptr*)bottom_old,
466                        (uptr*)size_old);
467 }
468 }