asan_thread.cc revision 230e52f4e91b53f05ce19dbbf11047f4a0113483
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 "lsan/lsan_common.h"
23
24namespace __asan {
25
26// AsanThreadContext implementation.
27
28void AsanThreadContext::OnCreated(void *arg) {
29  CreateThreadContextArgs *args = static_cast<CreateThreadContextArgs*>(arg);
30  if (args->stack) {
31    internal_memcpy(&stack, args->stack, sizeof(stack));
32  }
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 ThreadContextBase *GetAsanThreadContext(u32 tid) {
47  void *mem = MmapOrDie(sizeof(AsanThreadContext), "AsanThreadContext");
48  return new(mem) AsanThreadContext(tid);
49}
50
51ThreadRegistry &asanThreadRegistry() {
52  static bool initialized;
53  // Don't worry about thread_safety - this should be called when there is
54  // a single thread.
55  if (!initialized) {
56    // Never reuse ASan threads: we store pointer to AsanThreadContext
57    // in TSD and can't reliably tell when no more TSD destructors will
58    // be called. It would be wrong to reuse AsanThreadContext for another
59    // thread before all TSD destructors will be called for it.
60    asan_thread_registry = new(thread_registry_placeholder) ThreadRegistry(
61        GetAsanThreadContext, kMaxNumberOfThreads, kMaxNumberOfThreads);
62    initialized = true;
63  }
64  return *asan_thread_registry;
65}
66
67AsanThreadContext *GetThreadContextByTidLocked(u32 tid) {
68  return static_cast<AsanThreadContext *>(
69      asanThreadRegistry().GetThreadLocked(tid));
70}
71
72// AsanThread implementation.
73
74AsanThread *AsanThread::Create(thread_callback_t start_routine,
75                               void *arg) {
76  uptr PageSize = GetPageSizeCached();
77  uptr size = RoundUpTo(sizeof(AsanThread), PageSize);
78  AsanThread *thread = (AsanThread*)MmapOrDie(size, __FUNCTION__);
79  thread->start_routine_ = start_routine;
80  thread->arg_ = arg;
81  thread->context_ = 0;
82
83  return thread;
84}
85
86void AsanThread::TSDDtor(void *tsd) {
87  AsanThreadContext *context = (AsanThreadContext*)tsd;
88  if (flags()->verbosity >= 1)
89    Report("T%d TSDDtor\n", context->tid);
90  if (context->thread)
91    context->thread->Destroy();
92}
93
94void AsanThread::Destroy() {
95  if (flags()->verbosity >= 1) {
96    Report("T%d exited\n", tid());
97  }
98
99  asanThreadRegistry().FinishThread(tid());
100  FlushToDeadThreadStats(&stats_);
101  // We also clear the shadow on thread destruction because
102  // some code may still be executing in later TSD destructors
103  // and we don't want it to have any poisoned stack.
104  ClearShadowForThreadStackAndTLS();
105  DeleteFakeStack();
106  uptr size = RoundUpTo(sizeof(AsanThread), GetPageSizeCached());
107  UnmapOrDie(this, size);
108}
109
110// We want to create the FakeStack lazyly on the first use, but not eralier
111// than the stack size is known and the procedure has to be async-signal safe.
112FakeStack *AsanThread::AsyncSignalSafeLazyInitFakeStack() {
113  uptr stack_size = this->stack_size();
114  if (stack_size == 0)  // stack_size is not yet available, don't use FakeStack.
115    return 0;
116  uptr old_val = 0;
117  // fake_stack_ has 3 states:
118  // 0   -- not initialized
119  // 1   -- being initialized
120  // ptr -- initialized
121  // This CAS checks if the state was 0 and if so changes it to state 1,
122  // if that was successfull, it initilizes the pointer.
123  if (atomic_compare_exchange_strong(
124      reinterpret_cast<atomic_uintptr_t *>(&fake_stack_), &old_val, 1UL,
125      memory_order_relaxed)) {
126    uptr stack_size_log = Log2(RoundUpToPowerOfTwo(stack_size));
127    fake_stack_ = FakeStack::Create(stack_size_log);
128    SetTLSFakeStack(fake_stack_);
129    if (flags()->verbosity) {
130      u8 *p = reinterpret_cast<u8 *>(fake_stack_);
131      Report("T%d: FakeStack created: %p -- %p\n", tid(), p,
132             p + FakeStack::RequiredSize(stack_size_log));
133    }
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 (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  this->Destroy();
172
173  return res;
174}
175
176void AsanThread::SetThreadStackAndTls() {
177  uptr stack_size = 0, tls_size = 0;
178  GetThreadStackAndTls(tid() == 0, &stack_bottom_, &stack_size, &tls_begin_,
179                       &tls_size);
180  stack_top_ = stack_bottom_ + stack_size;
181  tls_end_ = tls_begin_ + tls_size;
182
183  int local;
184  CHECK(AddrIsInStack((uptr)&local));
185}
186
187void AsanThread::ClearShadowForThreadStackAndTLS() {
188  PoisonShadow(stack_bottom_, stack_top_ - stack_bottom_, 0);
189  if (tls_begin_ != tls_end_)
190    PoisonShadow(tls_begin_, tls_end_ - tls_begin_, 0);
191}
192
193const char *AsanThread::GetFrameNameByAddr(uptr addr, uptr *offset,
194                                           uptr *frame_pc) {
195  uptr bottom = 0;
196  if (AddrIsInStack(addr)) {
197    bottom = stack_bottom();
198  } else if (has_fake_stack()) {
199    bottom = fake_stack()->AddrIsInFakeStack(addr);
200    CHECK(bottom);
201    *offset = addr - bottom;
202    *frame_pc = ((uptr*)bottom)[2];
203    return  (const char *)((uptr*)bottom)[1];
204  }
205  uptr aligned_addr = addr & ~(SANITIZER_WORDSIZE/8 - 1);  // align addr.
206  u8 *shadow_ptr = (u8*)MemToShadow(aligned_addr);
207  u8 *shadow_bottom = (u8*)MemToShadow(bottom);
208
209  while (shadow_ptr >= shadow_bottom &&
210         *shadow_ptr != kAsanStackLeftRedzoneMagic) {
211    shadow_ptr--;
212  }
213
214  while (shadow_ptr >= shadow_bottom &&
215         *shadow_ptr == kAsanStackLeftRedzoneMagic) {
216    shadow_ptr--;
217  }
218
219  if (shadow_ptr < shadow_bottom) {
220    *offset = 0;
221    return "UNKNOWN";
222  }
223
224  uptr* ptr = (uptr*)SHADOW_TO_MEM((uptr)(shadow_ptr + 1));
225  CHECK(ptr[0] == kCurrentStackFrameMagic);
226  *offset = addr - (uptr)ptr;
227  *frame_pc = ptr[2];
228  return (const char*)ptr[1];
229}
230
231static bool ThreadStackContainsAddress(ThreadContextBase *tctx_base,
232                                       void *addr) {
233  AsanThreadContext *tctx = static_cast<AsanThreadContext*>(tctx_base);
234  AsanThread *t = tctx->thread;
235  if (!t) return false;
236  if (t->AddrIsInStack((uptr)addr)) return true;
237  if (t->has_fake_stack() && t->fake_stack()->AddrIsInFakeStack((uptr)addr))
238    return true;
239  return false;
240}
241
242AsanThread *GetCurrentThread() {
243  AsanThreadContext *context =
244      reinterpret_cast<AsanThreadContext *>(AsanTSDGet());
245  if (!context) {
246    if (SANITIZER_ANDROID) {
247      // On Android, libc constructor is called _after_ asan_init, and cleans up
248      // TSD. Try to figure out if this is still the main thread by the stack
249      // address. We are not entirely sure that we have correct main thread
250      // limits, so only do this magic on Android, and only if the found thread
251      // is the main thread.
252      AsanThreadContext *tctx = GetThreadContextByTidLocked(0);
253      if (ThreadStackContainsAddress(tctx, &context)) {
254        SetCurrentThread(tctx->thread);
255        return tctx->thread;
256      }
257    }
258    return 0;
259  }
260  return context->thread;
261}
262
263void SetCurrentThread(AsanThread *t) {
264  CHECK(t->context());
265  if (flags()->verbosity >= 2) {
266    Report("SetCurrentThread: %p for thread %p\n",
267           t->context(), (void*)GetThreadSelf());
268  }
269  // Make sure we do not reset the current AsanThread.
270  CHECK_EQ(0, AsanTSDGet());
271  AsanTSDSet(t->context());
272  CHECK_EQ(t->context(), AsanTSDGet());
273}
274
275u32 GetCurrentTidOrInvalid() {
276  AsanThread *t = GetCurrentThread();
277  return t ? t->tid() : kInvalidTid;
278}
279
280AsanThread *FindThreadByStackAddress(uptr addr) {
281  asanThreadRegistry().CheckLocked();
282  AsanThreadContext *tctx = static_cast<AsanThreadContext *>(
283      asanThreadRegistry().FindThreadContextLocked(ThreadStackContainsAddress,
284                                                   (void *)addr));
285  return tctx ? tctx->thread : 0;
286}
287
288void EnsureMainThreadIDIsCorrect() {
289  AsanThreadContext *context =
290      reinterpret_cast<AsanThreadContext *>(AsanTSDGet());
291  if (context && (context->tid == 0))
292    context->os_id = GetTid();
293}
294}  // namespace __asan
295
296// --- Implementation of LSan-specific functions --- {{{1
297namespace __lsan {
298bool GetThreadRangesLocked(uptr os_id, uptr *stack_begin, uptr *stack_end,
299                           uptr *tls_begin, uptr *tls_end,
300                           uptr *cache_begin, uptr *cache_end) {
301  __asan::AsanThreadContext *context = static_cast<__asan::AsanThreadContext *>(
302      __asan::asanThreadRegistry().FindThreadContextByOsIDLocked(os_id));
303  if (!context) return false;
304  __asan::AsanThread *t = context->thread;
305  if (!t) return false;
306  *stack_begin = t->stack_bottom();
307  *stack_end = t->stack_top();
308  *tls_begin = t->tls_begin();
309  *tls_end = t->tls_end();
310  // ASan doesn't keep allocator caches in TLS, so these are unused.
311  *cache_begin = 0;
312  *cache_end = 0;
313  return true;
314}
315
316void LockThreadRegistry() {
317  __asan::asanThreadRegistry().Lock();
318}
319
320void UnlockThreadRegistry() {
321  __asan::asanThreadRegistry().Unlock();
322}
323
324void EnsureMainThreadIDIsCorrect() {
325  __asan::EnsureMainThreadIDIsCorrect();
326}
327}  // namespace __lsan
328