]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/asan/asan_thread.cc
Merge clang 7.0.1 and several follow-up changes
[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 void AsanThreadContext::OnCreated(void *arg) {
31   CreateThreadContextArgs *args = static_cast<CreateThreadContextArgs*>(arg);
32   if (args->stack)
33     stack_id = StackDepotPut(*args->stack);
34   thread = args->thread;
35   thread->set_context(this);
36 }
37
38 void AsanThreadContext::OnFinished() {
39   // Drop the link to the AsanThread object.
40   thread = nullptr;
41 }
42
43 // MIPS requires aligned address
44 static ALIGNED(16) char thread_registry_placeholder[sizeof(ThreadRegistry)];
45 static ThreadRegistry *asan_thread_registry;
46
47 static BlockingMutex mu_for_thread_context(LINKER_INITIALIZED);
48 static LowLevelAllocator allocator_for_thread_context;
49
50 static ThreadContextBase *GetAsanThreadContext(u32 tid) {
51   BlockingMutexLock lock(&mu_for_thread_context);
52   return new(allocator_for_thread_context) AsanThreadContext(tid);
53 }
54
55 ThreadRegistry &asanThreadRegistry() {
56   static bool initialized;
57   // Don't worry about thread_safety - this should be called when there is
58   // a single thread.
59   if (!initialized) {
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);
66     initialized = true;
67   }
68   return *asan_thread_registry;
69 }
70
71 AsanThreadContext *GetThreadContextByTidLocked(u32 tid) {
72   return static_cast<AsanThreadContext *>(
73       asanThreadRegistry().GetThreadLocked(tid));
74 }
75
76 // AsanThread implementation.
77
78 AsanThread *AsanThread::Create(thread_callback_t start_routine, void *arg,
79                                u32 parent_tid, StackTrace *stack,
80                                bool detached) {
81   uptr PageSize = GetPageSizeCached();
82   uptr size = RoundUpTo(sizeof(AsanThread), PageSize);
83   AsanThread *thread = (AsanThread*)MmapOrDie(size, __func__);
84   thread->start_routine_ = start_routine;
85   thread->arg_ = arg;
86   AsanThreadContext::CreateThreadContextArgs args = {thread, stack};
87   asanThreadRegistry().CreateThread(*reinterpret_cast<uptr *>(thread), detached,
88                                     parent_tid, &args);
89
90   return thread;
91 }
92
93 void AsanThread::TSDDtor(void *tsd) {
94   AsanThreadContext *context = (AsanThreadContext*)tsd;
95   VReport(1, "T%d TSDDtor\n", context->tid);
96   if (context->thread)
97     context->thread->Destroy();
98 }
99
100 void AsanThread::Destroy() {
101   int tid = this->tid();
102   VReport(1, "T%d exited\n", tid);
103
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);
115   DTLS_Destroy();
116 }
117
118 void AsanThread::StartSwitchFiber(FakeStack **fake_stack_save, uptr bottom,
119                                   uptr size) {
120   if (atomic_load(&stack_switching_, memory_order_relaxed)) {
121     Report("ERROR: starting fiber switch while in fiber switch\n");
122     Die();
123   }
124
125   next_stack_bottom_ = bottom;
126   next_stack_top_ = bottom + size;
127   atomic_store(&stack_switching_, 1, memory_order_release);
128
129   FakeStack *current_fake_stack = fake_stack_;
130   if (fake_stack_save)
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());
137 }
138
139 void AsanThread::FinishSwitchFiber(FakeStack *fake_stack_save,
140                                    uptr *bottom_old,
141                                    uptr *size_old) {
142   if (!atomic_load(&stack_switching_, memory_order_relaxed)) {
143     Report("ERROR: finishing a fiber switch that has not started\n");
144     Die();
145   }
146
147   if (fake_stack_save) {
148     SetTLSFakeStack(fake_stack_save);
149     fake_stack_ = fake_stack_save;
150   }
151
152   if (bottom_old)
153     *bottom_old = stack_bottom_;
154   if (size_old)
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);
159   next_stack_top_ = 0;
160   next_stack_bottom_ = 0;
161 }
162
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_};
168   }
169   char local;
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_};
177 }
178
179 uptr AsanThread::stack_top() {
180   return GetStackBounds().top;
181 }
182
183 uptr AsanThread::stack_bottom() {
184   return GetStackBounds().bottom;
185 }
186
187 uptr AsanThread::stack_size() {
188   const auto bounds = GetStackBounds();
189   return bounds.top - bounds.bottom;
190 }
191
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.
197     return nullptr;
198   uptr old_val = 0;
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);
210     stack_size_log =
211         Min(stack_size_log, static_cast<uptr>(flags()->max_uar_stack_size_log));
212     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_);
216     return fake_stack_;
217   }
218   return nullptr;
219 }
220
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   CHECK_EQ(this->stack_size(), 0U);
225   SetThreadStackAndTls(options);
226   CHECK_GT(this->stack_size(), 0U);
227   CHECK(AddrIsInMem(stack_bottom_));
228   CHECK(AddrIsInMem(stack_top_ - 1));
229   ClearShadowForThreadStackAndTLS();
230   fake_stack_ = nullptr;
231   if (__asan_option_detect_stack_use_after_return)
232     AsyncSignalSafeLazyInitFakeStack();
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 // Fuchsia and RTEMS don't use ThreadStart.
240 // asan_fuchsia.c/asan_rtems.c define CreateMainThread and
241 // SetThreadStackAndTls.
242 #if !SANITIZER_FUCHSIA && !SANITIZER_RTEMS
243
244 thread_return_t AsanThread::ThreadStart(
245     tid_t os_id, atomic_uintptr_t *signal_thread_is_registered) {
246   Init();
247   asanThreadRegistry().StartThread(tid(), os_id, /*workerthread*/ false,
248                                    nullptr);
249   if (signal_thread_is_registered)
250     atomic_store(signal_thread_is_registered, 1, memory_order_release);
251
252   if (common_flags()->use_sigaltstack) SetAlternateSignalStack();
253
254   if (!start_routine_) {
255     // start_routine_ == 0 if we're on the main thread or on one of the
256     // OS X libdispatch worker threads. But nobody is supposed to call
257     // ThreadStart() for the worker threads.
258     CHECK_EQ(tid(), 0);
259     return 0;
260   }
261
262   thread_return_t res = start_routine_(arg_);
263
264   // On POSIX systems we defer this to the TSD destructor. LSan will consider
265   // the thread's memory as non-live from the moment we call Destroy(), even
266   // though that memory might contain pointers to heap objects which will be
267   // cleaned up by a user-defined TSD destructor. Thus, calling Destroy() before
268   // the TSD destructors have run might cause false positives in LSan.
269   if (!SANITIZER_POSIX)
270     this->Destroy();
271
272   return res;
273 }
274
275 AsanThread *CreateMainThread() {
276   AsanThread *main_thread = AsanThread::Create(
277       /* start_routine */ nullptr, /* arg */ nullptr, /* parent_tid */ 0,
278       /* stack */ nullptr, /* detached */ true);
279   SetCurrentThread(main_thread);
280   main_thread->ThreadStart(internal_getpid(),
281                            /* signal_thread_is_registered */ nullptr);
282   return main_thread;
283 }
284
285 // This implementation doesn't use the argument, which is just passed down
286 // from the caller of Init (which see, above).  It's only there to support
287 // OS-specific implementations that need more information passed through.
288 void AsanThread::SetThreadStackAndTls(const InitOptions *options) {
289   DCHECK_EQ(options, nullptr);
290   uptr tls_size = 0;
291   uptr stack_size = 0;
292   GetThreadStackAndTls(tid() == 0, const_cast<uptr *>(&stack_bottom_),
293                        const_cast<uptr *>(&stack_size), &tls_begin_, &tls_size);
294   stack_top_ = stack_bottom_ + stack_size;
295   tls_end_ = tls_begin_ + tls_size;
296   dtls_ = DTLS_Get();
297
298   int local;
299   CHECK(AddrIsInStack((uptr)&local));
300 }
301
302 #endif  // !SANITIZER_FUCHSIA && !SANITIZER_RTEMS
303
304 void AsanThread::ClearShadowForThreadStackAndTLS() {
305   PoisonShadow(stack_bottom_, stack_top_ - stack_bottom_, 0);
306   if (tls_begin_ != tls_end_) {
307     uptr tls_begin_aligned = RoundDownTo(tls_begin_, SHADOW_GRANULARITY);
308     uptr tls_end_aligned = RoundUpTo(tls_end_, SHADOW_GRANULARITY);
309     FastPoisonShadowPartialRightRedzone(tls_begin_aligned,
310                                         tls_end_ - tls_begin_aligned,
311                                         tls_end_aligned - tls_end_, 0);
312   }
313 }
314
315 bool AsanThread::GetStackFrameAccessByAddr(uptr addr,
316                                            StackFrameAccess *access) {
317   uptr bottom = 0;
318   if (AddrIsInStack(addr)) {
319     bottom = stack_bottom();
320   } else if (has_fake_stack()) {
321     bottom = fake_stack()->AddrIsInFakeStack(addr);
322     CHECK(bottom);
323     access->offset = addr - bottom;
324     access->frame_pc = ((uptr*)bottom)[2];
325     access->frame_descr = (const char *)((uptr*)bottom)[1];
326     return true;
327   }
328   uptr aligned_addr = RoundDownTo(addr, SANITIZER_WORDSIZE / 8);  // align addr.
329   uptr mem_ptr = RoundDownTo(aligned_addr, SHADOW_GRANULARITY);
330   u8 *shadow_ptr = (u8*)MemToShadow(aligned_addr);
331   u8 *shadow_bottom = (u8*)MemToShadow(bottom);
332
333   while (shadow_ptr >= shadow_bottom &&
334          *shadow_ptr != kAsanStackLeftRedzoneMagic) {
335     shadow_ptr--;
336     mem_ptr -= SHADOW_GRANULARITY;
337   }
338
339   while (shadow_ptr >= shadow_bottom &&
340          *shadow_ptr == kAsanStackLeftRedzoneMagic) {
341     shadow_ptr--;
342     mem_ptr -= SHADOW_GRANULARITY;
343   }
344
345   if (shadow_ptr < shadow_bottom) {
346     return false;
347   }
348
349   uptr* ptr = (uptr*)(mem_ptr + SHADOW_GRANULARITY);
350   CHECK(ptr[0] == kCurrentStackFrameMagic);
351   access->offset = addr - (uptr)ptr;
352   access->frame_pc = ptr[2];
353   access->frame_descr = (const char*)ptr[1];
354   return true;
355 }
356
357 uptr AsanThread::GetStackVariableShadowStart(uptr addr) {
358   uptr bottom = 0;
359   if (AddrIsInStack(addr)) {
360     bottom = stack_bottom();
361   } else if (has_fake_stack()) {
362     bottom = fake_stack()->AddrIsInFakeStack(addr);
363     CHECK(bottom);
364   } else
365     return 0;
366
367   uptr aligned_addr = RoundDownTo(addr, SANITIZER_WORDSIZE / 8);  // align addr.
368   u8 *shadow_ptr = (u8*)MemToShadow(aligned_addr);
369   u8 *shadow_bottom = (u8*)MemToShadow(bottom);
370
371   while (shadow_ptr >= shadow_bottom &&
372          (*shadow_ptr != kAsanStackLeftRedzoneMagic &&
373           *shadow_ptr != kAsanStackMidRedzoneMagic &&
374           *shadow_ptr != kAsanStackRightRedzoneMagic))
375     shadow_ptr--;
376
377   return (uptr)shadow_ptr + 1;
378 }
379
380 bool AsanThread::AddrIsInStack(uptr addr) {
381   const auto bounds = GetStackBounds();
382   return addr >= bounds.bottom && addr < bounds.top;
383 }
384
385 static bool ThreadStackContainsAddress(ThreadContextBase *tctx_base,
386                                        void *addr) {
387   AsanThreadContext *tctx = static_cast<AsanThreadContext*>(tctx_base);
388   AsanThread *t = tctx->thread;
389   if (!t) return false;
390   if (t->AddrIsInStack((uptr)addr)) return true;
391   if (t->has_fake_stack() && t->fake_stack()->AddrIsInFakeStack((uptr)addr))
392     return true;
393   return false;
394 }
395
396 AsanThread *GetCurrentThread() {
397   if (SANITIZER_RTEMS && !asan_inited)
398     return nullptr;
399
400   AsanThreadContext *context =
401       reinterpret_cast<AsanThreadContext *>(AsanTSDGet());
402   if (!context) {
403     if (SANITIZER_ANDROID) {
404       // On Android, libc constructor is called _after_ asan_init, and cleans up
405       // TSD. Try to figure out if this is still the main thread by the stack
406       // address. We are not entirely sure that we have correct main thread
407       // limits, so only do this magic on Android, and only if the found thread
408       // is the main thread.
409       AsanThreadContext *tctx = GetThreadContextByTidLocked(0);
410       if (tctx && ThreadStackContainsAddress(tctx, &context)) {
411         SetCurrentThread(tctx->thread);
412         return tctx->thread;
413       }
414     }
415     return nullptr;
416   }
417   return context->thread;
418 }
419
420 void SetCurrentThread(AsanThread *t) {
421   CHECK(t->context());
422   VReport(2, "SetCurrentThread: %p for thread %p\n", t->context(),
423           (void *)GetThreadSelf());
424   // Make sure we do not reset the current AsanThread.
425   CHECK_EQ(0, AsanTSDGet());
426   AsanTSDSet(t->context());
427   CHECK_EQ(t->context(), AsanTSDGet());
428 }
429
430 u32 GetCurrentTidOrInvalid() {
431   AsanThread *t = GetCurrentThread();
432   return t ? t->tid() : kInvalidTid;
433 }
434
435 AsanThread *FindThreadByStackAddress(uptr addr) {
436   asanThreadRegistry().CheckLocked();
437   AsanThreadContext *tctx = static_cast<AsanThreadContext *>(
438       asanThreadRegistry().FindThreadContextLocked(ThreadStackContainsAddress,
439                                                    (void *)addr));
440   return tctx ? tctx->thread : nullptr;
441 }
442
443 void EnsureMainThreadIDIsCorrect() {
444   AsanThreadContext *context =
445       reinterpret_cast<AsanThreadContext *>(AsanTSDGet());
446   if (context && (context->tid == 0))
447     context->os_id = GetTid();
448 }
449
450 __asan::AsanThread *GetAsanThreadByOsIDLocked(tid_t os_id) {
451   __asan::AsanThreadContext *context = static_cast<__asan::AsanThreadContext *>(
452       __asan::asanThreadRegistry().FindThreadContextByOsIDLocked(os_id));
453   if (!context) return nullptr;
454   return context->thread;
455 }
456 } // namespace __asan
457
458 // --- Implementation of LSan-specific functions --- {{{1
459 namespace __lsan {
460 bool GetThreadRangesLocked(tid_t os_id, uptr *stack_begin, uptr *stack_end,
461                            uptr *tls_begin, uptr *tls_end, uptr *cache_begin,
462                            uptr *cache_end, DTLS **dtls) {
463   __asan::AsanThread *t = __asan::GetAsanThreadByOsIDLocked(os_id);
464   if (!t) return false;
465   *stack_begin = t->stack_bottom();
466   *stack_end = t->stack_top();
467   *tls_begin = t->tls_begin();
468   *tls_end = t->tls_end();
469   // ASan doesn't keep allocator caches in TLS, so these are unused.
470   *cache_begin = 0;
471   *cache_end = 0;
472   *dtls = t->dtls();
473   return true;
474 }
475
476 void ForEachExtraStackRange(tid_t os_id, RangeIteratorCallback callback,
477                             void *arg) {
478   __asan::AsanThread *t = __asan::GetAsanThreadByOsIDLocked(os_id);
479   if (t && t->has_fake_stack())
480     t->fake_stack()->ForEachFakeFrame(callback, arg);
481 }
482
483 void LockThreadRegistry() {
484   __asan::asanThreadRegistry().Lock();
485 }
486
487 void UnlockThreadRegistry() {
488   __asan::asanThreadRegistry().Unlock();
489 }
490
491 ThreadRegistry *GetThreadRegistryLocked() {
492   __asan::asanThreadRegistry().CheckLocked();
493   return &__asan::asanThreadRegistry();
494 }
495
496 void EnsureMainThreadIDIsCorrect() {
497   __asan::EnsureMainThreadIDIsCorrect();
498 }
499 } // namespace __lsan
500
501 // ---------------------- Interface ---------------- {{{1
502 using namespace __asan;  // NOLINT
503
504 extern "C" {
505 SANITIZER_INTERFACE_ATTRIBUTE
506 void __sanitizer_start_switch_fiber(void **fakestacksave, const void *bottom,
507                                     uptr size) {
508   AsanThread *t = GetCurrentThread();
509   if (!t) {
510     VReport(1, "__asan_start_switch_fiber called from unknown thread\n");
511     return;
512   }
513   t->StartSwitchFiber((FakeStack**)fakestacksave, (uptr)bottom, size);
514 }
515
516 SANITIZER_INTERFACE_ATTRIBUTE
517 void __sanitizer_finish_switch_fiber(void* fakestack,
518                                      const void **bottom_old,
519                                      uptr *size_old) {
520   AsanThread *t = GetCurrentThread();
521   if (!t) {
522     VReport(1, "__asan_finish_switch_fiber called from unknown thread\n");
523     return;
524   }
525   t->FinishSwitchFiber((FakeStack*)fakestack,
526                        (uptr*)bottom_old,
527                        (uptr*)size_old);
528 }
529 }