asan_thread.cc revision 53177247698bfba075f2d5b255a447fc3ced6976
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 "lsan/lsan_common.h"
24
25namespace __asan {
26
27// AsanThreadContext implementation.
28
29void AsanThreadContext::OnCreated(void *arg) {
30  CreateThreadContextArgs *args = static_cast<CreateThreadContextArgs*>(arg);
31  if (args->stack)
32    stack_id = StackDepotPut(args->stack->trace, args->stack->size);
33  thread = args->thread;
34  thread->set_context(this);
35}
36
37void AsanThreadContext::OnFinished() {
38  // Drop the link to the AsanThread object.
39  thread = 0;
40}
41
42// MIPS requires aligned address
43static ALIGNED(16) char thread_registry_placeholder[sizeof(ThreadRegistry)];
44static ThreadRegistry *asan_thread_registry;
45
46static BlockingMutex mu_for_thread_context(LINKER_INITIALIZED);
47static LowLevelAllocator allocator_for_thread_context;
48
49static ThreadContextBase *GetAsanThreadContext(u32 tid) {
50  BlockingMutexLock lock(&mu_for_thread_context);
51  return new(allocator_for_thread_context) AsanThreadContext(tid);
52}
53
54ThreadRegistry &asanThreadRegistry() {
55  static bool initialized;
56  // Don't worry about thread_safety - this should be called when there is
57  // a single thread.
58  if (!initialized) {
59    // Never reuse ASan threads: we store pointer to AsanThreadContext
60    // in TSD and can't reliably tell when no more TSD destructors will
61    // be called. It would be wrong to reuse AsanThreadContext for another
62    // thread before all TSD destructors will be called for it.
63    asan_thread_registry = new(thread_registry_placeholder) ThreadRegistry(
64        GetAsanThreadContext, kMaxNumberOfThreads, kMaxNumberOfThreads);
65    initialized = true;
66  }
67  return *asan_thread_registry;
68}
69
70AsanThreadContext *GetThreadContextByTidLocked(u32 tid) {
71  return static_cast<AsanThreadContext *>(
72      asanThreadRegistry().GetThreadLocked(tid));
73}
74
75// AsanThread implementation.
76
77AsanThread *AsanThread::Create(thread_callback_t start_routine,
78                               void *arg) {
79  uptr PageSize = GetPageSizeCached();
80  uptr size = RoundUpTo(sizeof(AsanThread), PageSize);
81  AsanThread *thread = (AsanThread*)MmapOrDie(size, __FUNCTION__);
82  thread->start_routine_ = start_routine;
83  thread->arg_ = arg;
84  thread->context_ = 0;
85
86  return thread;
87}
88
89void AsanThread::TSDDtor(void *tsd) {
90  AsanThreadContext *context = (AsanThreadContext*)tsd;
91  if (common_flags()->verbosity >= 1)
92    Report("T%d TSDDtor\n", context->tid);
93  if (context->thread)
94    context->thread->Destroy();
95}
96
97void AsanThread::Destroy() {
98  if (common_flags()->verbosity >= 1) {
99    Report("T%d exited\n", tid());
100  }
101
102  asanThreadRegistry().FinishThread(tid());
103  FlushToDeadThreadStats(&stats_);
104  // We also clear the shadow on thread destruction because
105  // some code may still be executing in later TSD destructors
106  // and we don't want it to have any poisoned stack.
107  ClearShadowForThreadStackAndTLS();
108  DeleteFakeStack();
109  uptr size = RoundUpTo(sizeof(AsanThread), GetPageSizeCached());
110  UnmapOrDie(this, size);
111}
112
113// We want to create the FakeStack lazyly on the first use, but not eralier
114// than the stack size is known and the procedure has to be async-signal safe.
115FakeStack *AsanThread::AsyncSignalSafeLazyInitFakeStack() {
116  uptr stack_size = this->stack_size();
117  if (stack_size == 0)  // stack_size is not yet available, don't use FakeStack.
118    return 0;
119  uptr old_val = 0;
120  // fake_stack_ has 3 states:
121  // 0   -- not initialized
122  // 1   -- being initialized
123  // ptr -- initialized
124  // This CAS checks if the state was 0 and if so changes it to state 1,
125  // if that was successfull, it initilizes the pointer.
126  if (atomic_compare_exchange_strong(
127      reinterpret_cast<atomic_uintptr_t *>(&fake_stack_), &old_val, 1UL,
128      memory_order_relaxed)) {
129    uptr stack_size_log = Log2(RoundUpToPowerOfTwo(stack_size));
130    if (flags()->uar_stack_size_log)
131      stack_size_log = static_cast<uptr>(flags()->uar_stack_size_log);
132    fake_stack_ = FakeStack::Create(stack_size_log);
133    SetTLSFakeStack(fake_stack_);
134    return fake_stack_;
135  }
136  return 0;
137}
138
139void AsanThread::Init() {
140  SetThreadStackAndTls();
141  CHECK(AddrIsInMem(stack_bottom_));
142  CHECK(AddrIsInMem(stack_top_ - 1));
143  ClearShadowForThreadStackAndTLS();
144  if (common_flags()->verbosity >= 1) {
145    int local = 0;
146    Report("T%d: stack [%p,%p) size 0x%zx; local=%p\n",
147           tid(), (void*)stack_bottom_, (void*)stack_top_,
148           stack_top_ - stack_bottom_, &local);
149  }
150  fake_stack_ = 0;  // Will be initialized lazily if needed.
151  AsanPlatformThreadInit();
152}
153
154thread_return_t AsanThread::ThreadStart(uptr os_id) {
155  Init();
156  asanThreadRegistry().StartThread(tid(), os_id, 0);
157  if (flags()->use_sigaltstack) SetAlternateSignalStack();
158
159  if (!start_routine_) {
160    // start_routine_ == 0 if we're on the main thread or on one of the
161    // OS X libdispatch worker threads. But nobody is supposed to call
162    // ThreadStart() for the worker threads.
163    CHECK_EQ(tid(), 0);
164    return 0;
165  }
166
167  thread_return_t res = start_routine_(arg_);
168  malloc_storage().CommitBack();
169  if (flags()->use_sigaltstack) UnsetAlternateSignalStack();
170
171  // On POSIX systems we defer this to the TSD destructor. LSan will consider
172  // the thread's memory as non-live from the moment we call Destroy(), even
173  // though that memory might contain pointers to heap objects which will be
174  // cleaned up by a user-defined TSD destructor. Thus, calling Destroy() before
175  // the TSD destructors have run might cause false positives in LSan.
176  if (!SANITIZER_POSIX)
177    this->Destroy();
178
179  return res;
180}
181
182void AsanThread::SetThreadStackAndTls() {
183  uptr tls_size = 0;
184  GetThreadStackAndTls(tid() == 0, &stack_bottom_, &stack_size_, &tls_begin_,
185                       &tls_size);
186  stack_top_ = stack_bottom_ + stack_size_;
187  tls_end_ = tls_begin_ + tls_size;
188
189  int local;
190  CHECK(AddrIsInStack((uptr)&local));
191}
192
193void AsanThread::ClearShadowForThreadStackAndTLS() {
194  PoisonShadow(stack_bottom_, stack_top_ - stack_bottom_, 0);
195  if (tls_begin_ != tls_end_)
196    PoisonShadow(tls_begin_, tls_end_ - tls_begin_, 0);
197}
198
199const char *AsanThread::GetFrameNameByAddr(uptr addr, uptr *offset,
200                                           uptr *frame_pc) {
201  uptr bottom = 0;
202  if (AddrIsInStack(addr)) {
203    bottom = stack_bottom();
204  } else if (has_fake_stack()) {
205    bottom = fake_stack()->AddrIsInFakeStack(addr);
206    CHECK(bottom);
207    *offset = addr - bottom;
208    *frame_pc = ((uptr*)bottom)[2];
209    return  (const char *)((uptr*)bottom)[1];
210  }
211  uptr aligned_addr = addr & ~(SANITIZER_WORDSIZE/8 - 1);  // align addr.
212  u8 *shadow_ptr = (u8*)MemToShadow(aligned_addr);
213  u8 *shadow_bottom = (u8*)MemToShadow(bottom);
214
215  while (shadow_ptr >= shadow_bottom &&
216         *shadow_ptr != kAsanStackLeftRedzoneMagic) {
217    shadow_ptr--;
218  }
219
220  while (shadow_ptr >= shadow_bottom &&
221         *shadow_ptr == kAsanStackLeftRedzoneMagic) {
222    shadow_ptr--;
223  }
224
225  if (shadow_ptr < shadow_bottom) {
226    *offset = 0;
227    return "UNKNOWN";
228  }
229
230  uptr* ptr = (uptr*)SHADOW_TO_MEM((uptr)(shadow_ptr + 1));
231  CHECK(ptr[0] == kCurrentStackFrameMagic);
232  *offset = addr - (uptr)ptr;
233  *frame_pc = ptr[2];
234  return (const char*)ptr[1];
235}
236
237static bool ThreadStackContainsAddress(ThreadContextBase *tctx_base,
238                                       void *addr) {
239  AsanThreadContext *tctx = static_cast<AsanThreadContext*>(tctx_base);
240  AsanThread *t = tctx->thread;
241  if (!t) return false;
242  if (t->AddrIsInStack((uptr)addr)) return true;
243  if (t->has_fake_stack() && t->fake_stack()->AddrIsInFakeStack((uptr)addr))
244    return true;
245  return false;
246}
247
248AsanThread *GetCurrentThread() {
249  AsanThreadContext *context =
250      reinterpret_cast<AsanThreadContext *>(AsanTSDGet());
251  if (!context) {
252    if (SANITIZER_ANDROID) {
253      // On Android, libc constructor is called _after_ asan_init, and cleans up
254      // TSD. Try to figure out if this is still the main thread by the stack
255      // address. We are not entirely sure that we have correct main thread
256      // limits, so only do this magic on Android, and only if the found thread
257      // is the main thread.
258      AsanThreadContext *tctx = GetThreadContextByTidLocked(0);
259      if (ThreadStackContainsAddress(tctx, &context)) {
260        SetCurrentThread(tctx->thread);
261        return tctx->thread;
262      }
263    }
264    return 0;
265  }
266  return context->thread;
267}
268
269void SetCurrentThread(AsanThread *t) {
270  CHECK(t->context());
271  if (common_flags()->verbosity >= 2) {
272    Report("SetCurrentThread: %p for thread %p\n",
273           t->context(), (void*)GetThreadSelf());
274  }
275  // Make sure we do not reset the current AsanThread.
276  CHECK_EQ(0, AsanTSDGet());
277  AsanTSDSet(t->context());
278  CHECK_EQ(t->context(), AsanTSDGet());
279}
280
281u32 GetCurrentTidOrInvalid() {
282  AsanThread *t = GetCurrentThread();
283  return t ? t->tid() : kInvalidTid;
284}
285
286AsanThread *FindThreadByStackAddress(uptr addr) {
287  asanThreadRegistry().CheckLocked();
288  AsanThreadContext *tctx = static_cast<AsanThreadContext *>(
289      asanThreadRegistry().FindThreadContextLocked(ThreadStackContainsAddress,
290                                                   (void *)addr));
291  return tctx ? tctx->thread : 0;
292}
293
294void EnsureMainThreadIDIsCorrect() {
295  AsanThreadContext *context =
296      reinterpret_cast<AsanThreadContext *>(AsanTSDGet());
297  if (context && (context->tid == 0))
298    context->os_id = GetTid();
299}
300
301__asan::AsanThread *GetAsanThreadByOsIDLocked(uptr os_id) {
302  __asan::AsanThreadContext *context = static_cast<__asan::AsanThreadContext *>(
303      __asan::asanThreadRegistry().FindThreadContextByOsIDLocked(os_id));
304  if (!context) return 0;
305  return context->thread;
306}
307}  // namespace __asan
308
309// --- Implementation of LSan-specific functions --- {{{1
310namespace __lsan {
311bool GetThreadRangesLocked(uptr os_id, uptr *stack_begin, uptr *stack_end,
312                           uptr *tls_begin, uptr *tls_end,
313                           uptr *cache_begin, uptr *cache_end) {
314  __asan::AsanThread *t = __asan::GetAsanThreadByOsIDLocked(os_id);
315  if (!t) return false;
316  *stack_begin = t->stack_bottom();
317  *stack_end = t->stack_top();
318  *tls_begin = t->tls_begin();
319  *tls_end = t->tls_end();
320  // ASan doesn't keep allocator caches in TLS, so these are unused.
321  *cache_begin = 0;
322  *cache_end = 0;
323  return true;
324}
325
326void ForEachExtraStackRange(uptr os_id, RangeIteratorCallback callback,
327                            void *arg) {
328  __asan::AsanThread *t = __asan::GetAsanThreadByOsIDLocked(os_id);
329  if (t && t->has_fake_stack())
330    t->fake_stack()->ForEachFakeFrame(callback, arg);
331}
332
333void LockThreadRegistry() {
334  __asan::asanThreadRegistry().Lock();
335}
336
337void UnlockThreadRegistry() {
338  __asan::asanThreadRegistry().Unlock();
339}
340
341void EnsureMainThreadIDIsCorrect() {
342  __asan::EnsureMainThreadIDIsCorrect();
343}
344}  // namespace __lsan
345