]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/asan/asan_thread.cc
Merge OpenSSL 1.0.2n.
[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     // Make sure the stack bounds are fully initialized.
171     if (stack_bottom_ >= stack_top_) return {0, 0};
172     return {stack_bottom_, stack_top_};
173   }
174   char local;
175   const uptr cur_stack = (uptr)&local;
176   // Note: need to check next stack first, because FinishSwitchFiber
177   // may be in process of overwriting stack_top_/bottom_. But in such case
178   // we are already on the next stack.
179   if (cur_stack >= next_stack_bottom_ && cur_stack < next_stack_top_)
180     return {next_stack_bottom_, next_stack_top_};
181   return {stack_bottom_, stack_top_};
182 }
183
184 uptr AsanThread::stack_top() {
185   return GetStackBounds().top;
186 }
187
188 uptr AsanThread::stack_bottom() {
189   return GetStackBounds().bottom;
190 }
191
192 uptr AsanThread::stack_size() {
193   const auto bounds = GetStackBounds();
194   return bounds.top - bounds.bottom;
195 }
196
197 // We want to create the FakeStack lazyly on the first use, but not eralier
198 // than the stack size is known and the procedure has to be async-signal safe.
199 FakeStack *AsanThread::AsyncSignalSafeLazyInitFakeStack() {
200   uptr stack_size = this->stack_size();
201   if (stack_size == 0)  // stack_size is not yet available, don't use FakeStack.
202     return nullptr;
203   uptr old_val = 0;
204   // fake_stack_ has 3 states:
205   // 0   -- not initialized
206   // 1   -- being initialized
207   // ptr -- initialized
208   // This CAS checks if the state was 0 and if so changes it to state 1,
209   // if that was successful, it initializes the pointer.
210   if (atomic_compare_exchange_strong(
211       reinterpret_cast<atomic_uintptr_t *>(&fake_stack_), &old_val, 1UL,
212       memory_order_relaxed)) {
213     uptr stack_size_log = Log2(RoundUpToPowerOfTwo(stack_size));
214     CHECK_LE(flags()->min_uar_stack_size_log, flags()->max_uar_stack_size_log);
215     stack_size_log =
216         Min(stack_size_log, static_cast<uptr>(flags()->max_uar_stack_size_log));
217     stack_size_log =
218         Max(stack_size_log, static_cast<uptr>(flags()->min_uar_stack_size_log));
219     fake_stack_ = FakeStack::Create(stack_size_log);
220     SetTLSFakeStack(fake_stack_);
221     return fake_stack_;
222   }
223   return nullptr;
224 }
225
226 void AsanThread::Init() {
227   next_stack_top_ = next_stack_bottom_ = 0;
228   atomic_store(&stack_switching_, false, memory_order_release);
229   fake_stack_ = nullptr;  // Will be initialized lazily if needed.
230   CHECK_EQ(this->stack_size(), 0U);
231   SetThreadStackAndTls();
232   CHECK_GT(this->stack_size(), 0U);
233   CHECK(AddrIsInMem(stack_bottom_));
234   CHECK(AddrIsInMem(stack_top_ - 1));
235   ClearShadowForThreadStackAndTLS();
236   int local = 0;
237   VReport(1, "T%d: stack [%p,%p) size 0x%zx; local=%p\n", tid(),
238           (void *)stack_bottom_, (void *)stack_top_, stack_top_ - stack_bottom_,
239           &local);
240 }
241
242 thread_return_t AsanThread::ThreadStart(
243     tid_t os_id, atomic_uintptr_t *signal_thread_is_registered) {
244   Init();
245   asanThreadRegistry().StartThread(tid(), os_id, /*workerthread*/ false,
246                                    nullptr);
247   if (signal_thread_is_registered)
248     atomic_store(signal_thread_is_registered, 1, memory_order_release);
249
250   if (common_flags()->use_sigaltstack) SetAlternateSignalStack();
251
252   if (!start_routine_) {
253     // start_routine_ == 0 if we're on the main thread or on one of the
254     // OS X libdispatch worker threads. But nobody is supposed to call
255     // ThreadStart() for the worker threads.
256     CHECK_EQ(tid(), 0);
257     return 0;
258   }
259
260   thread_return_t res = start_routine_(arg_);
261
262   // On POSIX systems we defer this to the TSD destructor. LSan will consider
263   // the thread's memory as non-live from the moment we call Destroy(), even
264   // though that memory might contain pointers to heap objects which will be
265   // cleaned up by a user-defined TSD destructor. Thus, calling Destroy() before
266   // the TSD destructors have run might cause false positives in LSan.
267   if (!SANITIZER_POSIX)
268     this->Destroy();
269
270   return res;
271 }
272
273 void AsanThread::SetThreadStackAndTls() {
274   uptr tls_size = 0;
275   uptr stack_size = 0;
276   GetThreadStackAndTls(tid() == 0, const_cast<uptr *>(&stack_bottom_),
277                        const_cast<uptr *>(&stack_size), &tls_begin_, &tls_size);
278   stack_top_ = stack_bottom_ + stack_size;
279   tls_end_ = tls_begin_ + tls_size;
280   dtls_ = DTLS_Get();
281
282   int local;
283   CHECK(AddrIsInStack((uptr)&local));
284 }
285
286 void AsanThread::ClearShadowForThreadStackAndTLS() {
287   PoisonShadow(stack_bottom_, stack_top_ - stack_bottom_, 0);
288   if (tls_begin_ != tls_end_)
289     PoisonShadow(tls_begin_, tls_end_ - tls_begin_, 0);
290 }
291
292 bool AsanThread::GetStackFrameAccessByAddr(uptr addr,
293                                            StackFrameAccess *access) {
294   uptr bottom = 0;
295   if (AddrIsInStack(addr)) {
296     bottom = stack_bottom();
297   } else if (has_fake_stack()) {
298     bottom = fake_stack()->AddrIsInFakeStack(addr);
299     CHECK(bottom);
300     access->offset = addr - bottom;
301     access->frame_pc = ((uptr*)bottom)[2];
302     access->frame_descr = (const char *)((uptr*)bottom)[1];
303     return true;
304   }
305   uptr aligned_addr = addr & ~(SANITIZER_WORDSIZE/8 - 1);  // align addr.
306   uptr mem_ptr = RoundDownTo(aligned_addr, SHADOW_GRANULARITY);
307   u8 *shadow_ptr = (u8*)MemToShadow(aligned_addr);
308   u8 *shadow_bottom = (u8*)MemToShadow(bottom);
309
310   while (shadow_ptr >= shadow_bottom &&
311          *shadow_ptr != kAsanStackLeftRedzoneMagic) {
312     shadow_ptr--;
313     mem_ptr -= SHADOW_GRANULARITY;
314   }
315
316   while (shadow_ptr >= shadow_bottom &&
317          *shadow_ptr == kAsanStackLeftRedzoneMagic) {
318     shadow_ptr--;
319     mem_ptr -= SHADOW_GRANULARITY;
320   }
321
322   if (shadow_ptr < shadow_bottom) {
323     return false;
324   }
325
326   uptr* ptr = (uptr*)(mem_ptr + SHADOW_GRANULARITY);
327   CHECK(ptr[0] == kCurrentStackFrameMagic);
328   access->offset = addr - (uptr)ptr;
329   access->frame_pc = ptr[2];
330   access->frame_descr = (const char*)ptr[1];
331   return true;
332 }
333
334 bool AsanThread::AddrIsInStack(uptr addr) {
335   const auto bounds = GetStackBounds();
336   return addr >= bounds.bottom && addr < bounds.top;
337 }
338
339 static bool ThreadStackContainsAddress(ThreadContextBase *tctx_base,
340                                        void *addr) {
341   AsanThreadContext *tctx = static_cast<AsanThreadContext*>(tctx_base);
342   AsanThread *t = tctx->thread;
343   if (!t) return false;
344   if (t->AddrIsInStack((uptr)addr)) return true;
345   if (t->has_fake_stack() && t->fake_stack()->AddrIsInFakeStack((uptr)addr))
346     return true;
347   return false;
348 }
349
350 AsanThread *GetCurrentThread() {
351   AsanThreadContext *context =
352       reinterpret_cast<AsanThreadContext *>(AsanTSDGet());
353   if (!context) {
354     if (SANITIZER_ANDROID) {
355       // On Android, libc constructor is called _after_ asan_init, and cleans up
356       // TSD. Try to figure out if this is still the main thread by the stack
357       // address. We are not entirely sure that we have correct main thread
358       // limits, so only do this magic on Android, and only if the found thread
359       // is the main thread.
360       AsanThreadContext *tctx = GetThreadContextByTidLocked(0);
361       if (tctx && ThreadStackContainsAddress(tctx, &context)) {
362         SetCurrentThread(tctx->thread);
363         return tctx->thread;
364       }
365     }
366     return nullptr;
367   }
368   return context->thread;
369 }
370
371 void SetCurrentThread(AsanThread *t) {
372   CHECK(t->context());
373   VReport(2, "SetCurrentThread: %p for thread %p\n", t->context(),
374           (void *)GetThreadSelf());
375   // Make sure we do not reset the current AsanThread.
376   CHECK_EQ(0, AsanTSDGet());
377   AsanTSDSet(t->context());
378   CHECK_EQ(t->context(), AsanTSDGet());
379 }
380
381 u32 GetCurrentTidOrInvalid() {
382   AsanThread *t = GetCurrentThread();
383   return t ? t->tid() : kInvalidTid;
384 }
385
386 AsanThread *FindThreadByStackAddress(uptr addr) {
387   asanThreadRegistry().CheckLocked();
388   AsanThreadContext *tctx = static_cast<AsanThreadContext *>(
389       asanThreadRegistry().FindThreadContextLocked(ThreadStackContainsAddress,
390                                                    (void *)addr));
391   return tctx ? tctx->thread : nullptr;
392 }
393
394 void EnsureMainThreadIDIsCorrect() {
395   AsanThreadContext *context =
396       reinterpret_cast<AsanThreadContext *>(AsanTSDGet());
397   if (context && (context->tid == 0))
398     context->os_id = GetTid();
399 }
400
401 __asan::AsanThread *GetAsanThreadByOsIDLocked(tid_t os_id) {
402   __asan::AsanThreadContext *context = static_cast<__asan::AsanThreadContext *>(
403       __asan::asanThreadRegistry().FindThreadContextByOsIDLocked(os_id));
404   if (!context) return nullptr;
405   return context->thread;
406 }
407 } // namespace __asan
408
409 // --- Implementation of LSan-specific functions --- {{{1
410 namespace __lsan {
411 bool GetThreadRangesLocked(tid_t os_id, uptr *stack_begin, uptr *stack_end,
412                            uptr *tls_begin, uptr *tls_end, uptr *cache_begin,
413                            uptr *cache_end, DTLS **dtls) {
414   __asan::AsanThread *t = __asan::GetAsanThreadByOsIDLocked(os_id);
415   if (!t) return false;
416   *stack_begin = t->stack_bottom();
417   *stack_end = t->stack_top();
418   *tls_begin = t->tls_begin();
419   *tls_end = t->tls_end();
420   // ASan doesn't keep allocator caches in TLS, so these are unused.
421   *cache_begin = 0;
422   *cache_end = 0;
423   *dtls = t->dtls();
424   return true;
425 }
426
427 void ForEachExtraStackRange(tid_t os_id, RangeIteratorCallback callback,
428                             void *arg) {
429   __asan::AsanThread *t = __asan::GetAsanThreadByOsIDLocked(os_id);
430   if (t && t->has_fake_stack())
431     t->fake_stack()->ForEachFakeFrame(callback, arg);
432 }
433
434 void LockThreadRegistry() {
435   __asan::asanThreadRegistry().Lock();
436 }
437
438 void UnlockThreadRegistry() {
439   __asan::asanThreadRegistry().Unlock();
440 }
441
442 void EnsureMainThreadIDIsCorrect() {
443   __asan::EnsureMainThreadIDIsCorrect();
444 }
445 } // namespace __lsan
446
447 // ---------------------- Interface ---------------- {{{1
448 using namespace __asan;  // NOLINT
449
450 extern "C" {
451 SANITIZER_INTERFACE_ATTRIBUTE
452 void __sanitizer_start_switch_fiber(void **fakestacksave, const void *bottom,
453                                     uptr size) {
454   AsanThread *t = GetCurrentThread();
455   if (!t) {
456     VReport(1, "__asan_start_switch_fiber called from unknown thread\n");
457     return;
458   }
459   t->StartSwitchFiber((FakeStack**)fakestacksave, (uptr)bottom, size);
460 }
461
462 SANITIZER_INTERFACE_ATTRIBUTE
463 void __sanitizer_finish_switch_fiber(void* fakestack,
464                                      const void **bottom_old,
465                                      uptr *size_old) {
466   AsanThread *t = GetCurrentThread();
467   if (!t) {
468     VReport(1, "__asan_finish_switch_fiber called from unknown thread\n");
469     return;
470   }
471   t->FinishSwitchFiber((FakeStack*)fakestack,
472                        (uptr*)bottom_old,
473                        (uptr*)size_old);
474 }
475 }