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