]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/asan/asan_thread.cc
Merge ^/head r318658 through r318963.
[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     tid_t os_id, atomic_uintptr_t *signal_thread_is_registered) {
241   Init();
242   asanThreadRegistry().StartThread(tid(), os_id, /*workerthread*/ false,
243                                    nullptr);
244   if (signal_thread_is_registered)
245     atomic_store(signal_thread_is_registered, 1, memory_order_release);
246
247   if (common_flags()->use_sigaltstack) SetAlternateSignalStack();
248
249   if (!start_routine_) {
250     // start_routine_ == 0 if we're on the main thread or on one of the
251     // OS X libdispatch worker threads. But nobody is supposed to call
252     // ThreadStart() for the worker threads.
253     CHECK_EQ(tid(), 0);
254     return 0;
255   }
256
257   thread_return_t res = start_routine_(arg_);
258
259   // On POSIX systems we defer this to the TSD destructor. LSan will consider
260   // the thread's memory as non-live from the moment we call Destroy(), even
261   // though that memory might contain pointers to heap objects which will be
262   // cleaned up by a user-defined TSD destructor. Thus, calling Destroy() before
263   // the TSD destructors have run might cause false positives in LSan.
264   if (!SANITIZER_POSIX)
265     this->Destroy();
266
267   return res;
268 }
269
270 void AsanThread::SetThreadStackAndTls() {
271   uptr tls_size = 0;
272   uptr stack_size = 0;
273   GetThreadStackAndTls(tid() == 0, const_cast<uptr *>(&stack_bottom_),
274                        const_cast<uptr *>(&stack_size), &tls_begin_, &tls_size);
275   stack_top_ = stack_bottom_ + stack_size;
276   tls_end_ = tls_begin_ + tls_size;
277   dtls_ = DTLS_Get();
278
279   int local;
280   CHECK(AddrIsInStack((uptr)&local));
281 }
282
283 void AsanThread::ClearShadowForThreadStackAndTLS() {
284   PoisonShadow(stack_bottom_, stack_top_ - stack_bottom_, 0);
285   if (tls_begin_ != tls_end_)
286     PoisonShadow(tls_begin_, tls_end_ - tls_begin_, 0);
287 }
288
289 bool AsanThread::GetStackFrameAccessByAddr(uptr addr,
290                                            StackFrameAccess *access) {
291   uptr bottom = 0;
292   if (AddrIsInStack(addr)) {
293     bottom = stack_bottom();
294   } else if (has_fake_stack()) {
295     bottom = fake_stack()->AddrIsInFakeStack(addr);
296     CHECK(bottom);
297     access->offset = addr - bottom;
298     access->frame_pc = ((uptr*)bottom)[2];
299     access->frame_descr = (const char *)((uptr*)bottom)[1];
300     return true;
301   }
302   uptr aligned_addr = addr & ~(SANITIZER_WORDSIZE/8 - 1);  // align addr.
303   uptr mem_ptr = RoundDownTo(aligned_addr, SHADOW_GRANULARITY);
304   u8 *shadow_ptr = (u8*)MemToShadow(aligned_addr);
305   u8 *shadow_bottom = (u8*)MemToShadow(bottom);
306
307   while (shadow_ptr >= shadow_bottom &&
308          *shadow_ptr != kAsanStackLeftRedzoneMagic) {
309     shadow_ptr--;
310     mem_ptr -= SHADOW_GRANULARITY;
311   }
312
313   while (shadow_ptr >= shadow_bottom &&
314          *shadow_ptr == kAsanStackLeftRedzoneMagic) {
315     shadow_ptr--;
316     mem_ptr -= SHADOW_GRANULARITY;
317   }
318
319   if (shadow_ptr < shadow_bottom) {
320     return false;
321   }
322
323   uptr* ptr = (uptr*)(mem_ptr + SHADOW_GRANULARITY);
324   CHECK(ptr[0] == kCurrentStackFrameMagic);
325   access->offset = addr - (uptr)ptr;
326   access->frame_pc = ptr[2];
327   access->frame_descr = (const char*)ptr[1];
328   return true;
329 }
330
331 bool AsanThread::AddrIsInStack(uptr addr) {
332   const auto bounds = GetStackBounds();
333   return addr >= bounds.bottom && addr < bounds.top;
334 }
335
336 static bool ThreadStackContainsAddress(ThreadContextBase *tctx_base,
337                                        void *addr) {
338   AsanThreadContext *tctx = static_cast<AsanThreadContext*>(tctx_base);
339   AsanThread *t = tctx->thread;
340   if (!t) return false;
341   if (t->AddrIsInStack((uptr)addr)) return true;
342   if (t->has_fake_stack() && t->fake_stack()->AddrIsInFakeStack((uptr)addr))
343     return true;
344   return false;
345 }
346
347 AsanThread *GetCurrentThread() {
348   AsanThreadContext *context =
349       reinterpret_cast<AsanThreadContext *>(AsanTSDGet());
350   if (!context) {
351     if (SANITIZER_ANDROID) {
352       // On Android, libc constructor is called _after_ asan_init, and cleans up
353       // TSD. Try to figure out if this is still the main thread by the stack
354       // address. We are not entirely sure that we have correct main thread
355       // limits, so only do this magic on Android, and only if the found thread
356       // is the main thread.
357       AsanThreadContext *tctx = GetThreadContextByTidLocked(0);
358       if (tctx && ThreadStackContainsAddress(tctx, &context)) {
359         SetCurrentThread(tctx->thread);
360         return tctx->thread;
361       }
362     }
363     return nullptr;
364   }
365   return context->thread;
366 }
367
368 void SetCurrentThread(AsanThread *t) {
369   CHECK(t->context());
370   VReport(2, "SetCurrentThread: %p for thread %p\n", t->context(),
371           (void *)GetThreadSelf());
372   // Make sure we do not reset the current AsanThread.
373   CHECK_EQ(0, AsanTSDGet());
374   AsanTSDSet(t->context());
375   CHECK_EQ(t->context(), AsanTSDGet());
376 }
377
378 u32 GetCurrentTidOrInvalid() {
379   AsanThread *t = GetCurrentThread();
380   return t ? t->tid() : kInvalidTid;
381 }
382
383 AsanThread *FindThreadByStackAddress(uptr addr) {
384   asanThreadRegistry().CheckLocked();
385   AsanThreadContext *tctx = static_cast<AsanThreadContext *>(
386       asanThreadRegistry().FindThreadContextLocked(ThreadStackContainsAddress,
387                                                    (void *)addr));
388   return tctx ? tctx->thread : nullptr;
389 }
390
391 void EnsureMainThreadIDIsCorrect() {
392   AsanThreadContext *context =
393       reinterpret_cast<AsanThreadContext *>(AsanTSDGet());
394   if (context && (context->tid == 0))
395     context->os_id = GetTid();
396 }
397
398 __asan::AsanThread *GetAsanThreadByOsIDLocked(tid_t os_id) {
399   __asan::AsanThreadContext *context = static_cast<__asan::AsanThreadContext *>(
400       __asan::asanThreadRegistry().FindThreadContextByOsIDLocked(os_id));
401   if (!context) return nullptr;
402   return context->thread;
403 }
404 } // namespace __asan
405
406 // --- Implementation of LSan-specific functions --- {{{1
407 namespace __lsan {
408 bool GetThreadRangesLocked(tid_t os_id, uptr *stack_begin, uptr *stack_end,
409                            uptr *tls_begin, uptr *tls_end, uptr *cache_begin,
410                            uptr *cache_end, DTLS **dtls) {
411   __asan::AsanThread *t = __asan::GetAsanThreadByOsIDLocked(os_id);
412   if (!t) return false;
413   *stack_begin = t->stack_bottom();
414   *stack_end = t->stack_top();
415   *tls_begin = t->tls_begin();
416   *tls_end = t->tls_end();
417   // ASan doesn't keep allocator caches in TLS, so these are unused.
418   *cache_begin = 0;
419   *cache_end = 0;
420   *dtls = t->dtls();
421   return true;
422 }
423
424 void ForEachExtraStackRange(tid_t os_id, RangeIteratorCallback callback,
425                             void *arg) {
426   __asan::AsanThread *t = __asan::GetAsanThreadByOsIDLocked(os_id);
427   if (t && t->has_fake_stack())
428     t->fake_stack()->ForEachFakeFrame(callback, arg);
429 }
430
431 void LockThreadRegistry() {
432   __asan::asanThreadRegistry().Lock();
433 }
434
435 void UnlockThreadRegistry() {
436   __asan::asanThreadRegistry().Unlock();
437 }
438
439 void EnsureMainThreadIDIsCorrect() {
440   __asan::EnsureMainThreadIDIsCorrect();
441 }
442 } // namespace __lsan
443
444 // ---------------------- Interface ---------------- {{{1
445 using namespace __asan;  // NOLINT
446
447 extern "C" {
448 SANITIZER_INTERFACE_ATTRIBUTE
449 void __sanitizer_start_switch_fiber(void **fakestacksave, const void *bottom,
450                                     uptr size) {
451   AsanThread *t = GetCurrentThread();
452   if (!t) {
453     VReport(1, "__asan_start_switch_fiber called from unknown thread\n");
454     return;
455   }
456   t->StartSwitchFiber((FakeStack**)fakestacksave, (uptr)bottom, size);
457 }
458
459 SANITIZER_INTERFACE_ATTRIBUTE
460 void __sanitizer_finish_switch_fiber(void* fakestack,
461                                      const void **bottom_old,
462                                      uptr *size_old) {
463   AsanThread *t = GetCurrentThread();
464   if (!t) {
465     VReport(1, "__asan_finish_switch_fiber called from unknown thread\n");
466     return;
467   }
468   t->FinishSwitchFiber((FakeStack*)fakestack,
469                        (uptr*)bottom_old,
470                        (uptr*)size_old);
471 }
472 }