asan_thread.cc revision 7c9ffde46a475d6dd739e977b547c27ac5968976
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  FlushToAccumulatedStats(&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  fake_stack().Cleanup();
106  uptr size = RoundUpTo(sizeof(AsanThread), GetPageSizeCached());
107  UnmapOrDie(this, size);
108}
109
110void AsanThread::Init() {
111  SetThreadStackAndTls();
112  lsan_disabled_ = 0;
113  CHECK(AddrIsInMem(stack_bottom_));
114  CHECK(AddrIsInMem(stack_top_ - 1));
115  ClearShadowForThreadStackAndTLS();
116  if (flags()->verbosity >= 1) {
117    int local = 0;
118    Report("T%d: stack [%p,%p) size 0x%zx; local=%p\n",
119           tid(), (void*)stack_bottom_, (void*)stack_top_,
120           stack_top_ - stack_bottom_, &local);
121  }
122  fake_stack_.Init(stack_size());
123  AsanPlatformThreadInit();
124}
125
126thread_return_t AsanThread::ThreadStart(uptr os_id) {
127  Init();
128  asanThreadRegistry().StartThread(tid(), os_id, 0);
129  if (flags()->use_sigaltstack) SetAlternateSignalStack();
130
131  if (!start_routine_) {
132    // start_routine_ == 0 if we're on the main thread or on one of the
133    // OS X libdispatch worker threads. But nobody is supposed to call
134    // ThreadStart() for the worker threads.
135    CHECK_EQ(tid(), 0);
136    return 0;
137  }
138
139  thread_return_t res = start_routine_(arg_);
140  malloc_storage().CommitBack();
141  if (flags()->use_sigaltstack) UnsetAlternateSignalStack();
142
143  this->Destroy();
144
145  return res;
146}
147
148void AsanThread::SetThreadStackAndTls() {
149  uptr stack_size = 0, tls_size = 0;
150  GetThreadStackAndTls(tid() == 0, &stack_bottom_, &stack_size, &tls_begin_,
151                       &tls_size);
152  stack_top_ = stack_bottom_ + stack_size;
153  tls_end_ = tls_begin_ + tls_size;
154
155  int local;
156  CHECK(AddrIsInStack((uptr)&local));
157}
158
159void AsanThread::ClearShadowForThreadStackAndTLS() {
160  PoisonShadow(stack_bottom_, stack_top_ - stack_bottom_, 0);
161  if (tls_begin_ != tls_end_)
162    PoisonShadow(tls_begin_, tls_end_ - tls_begin_, 0);
163}
164
165const char *AsanThread::GetFrameNameByAddr(uptr addr, uptr *offset,
166                                           uptr *frame_pc) {
167  uptr bottom = 0;
168  if (AddrIsInStack(addr)) {
169    bottom = stack_bottom();
170  } else {
171    bottom = fake_stack().AddrIsInFakeStack(addr);
172    CHECK(bottom);
173    *offset = addr - bottom;
174    *frame_pc = ((uptr*)bottom)[2];
175    return  (const char *)((uptr*)bottom)[1];
176  }
177  uptr aligned_addr = addr & ~(SANITIZER_WORDSIZE/8 - 1);  // align addr.
178  u8 *shadow_ptr = (u8*)MemToShadow(aligned_addr);
179  u8 *shadow_bottom = (u8*)MemToShadow(bottom);
180
181  while (shadow_ptr >= shadow_bottom &&
182         *shadow_ptr != kAsanStackLeftRedzoneMagic) {
183    shadow_ptr--;
184  }
185
186  while (shadow_ptr >= shadow_bottom &&
187         *shadow_ptr == kAsanStackLeftRedzoneMagic) {
188    shadow_ptr--;
189  }
190
191  if (shadow_ptr < shadow_bottom) {
192    *offset = 0;
193    return "UNKNOWN";
194  }
195
196  uptr* ptr = (uptr*)SHADOW_TO_MEM((uptr)(shadow_ptr + 1));
197  CHECK(ptr[0] == kCurrentStackFrameMagic);
198  *offset = addr - (uptr)ptr;
199  *frame_pc = ptr[2];
200  return (const char*)ptr[1];
201}
202
203static bool ThreadStackContainsAddress(ThreadContextBase *tctx_base,
204                                       void *addr) {
205  AsanThreadContext *tctx = static_cast<AsanThreadContext*>(tctx_base);
206  AsanThread *t = tctx->thread;
207  return (t && t->fake_stack().StackSize() &&
208          (t->fake_stack().AddrIsInFakeStack((uptr)addr) ||
209           t->AddrIsInStack((uptr)addr)));
210}
211
212AsanThread *GetCurrentThread() {
213  AsanThreadContext *context = (AsanThreadContext*)AsanTSDGet();
214  if (!context) {
215    if (SANITIZER_ANDROID) {
216      // On Android, libc constructor is called _after_ asan_init, and cleans up
217      // TSD. Try to figure out if this is still the main thread by the stack
218      // address. We are not entirely sure that we have correct main thread
219      // limits, so only do this magic on Android, and only if the found thread
220      // is the main thread.
221      AsanThreadContext *tctx = GetThreadContextByTidLocked(0);
222      if (ThreadStackContainsAddress(tctx, &context)) {
223        SetCurrentThread(tctx->thread);
224        return tctx->thread;
225      }
226    }
227    return 0;
228  }
229  return context->thread;
230}
231
232void SetCurrentThread(AsanThread *t) {
233  CHECK(t->context());
234  if (flags()->verbosity >= 2) {
235    Report("SetCurrentThread: %p for thread %p\n",
236           t->context(), (void*)GetThreadSelf());
237  }
238  // Make sure we do not reset the current AsanThread.
239  CHECK_EQ(0, AsanTSDGet());
240  AsanTSDSet(t->context());
241  CHECK_EQ(t->context(), AsanTSDGet());
242}
243
244u32 GetCurrentTidOrInvalid() {
245  AsanThread *t = GetCurrentThread();
246  return t ? t->tid() : kInvalidTid;
247}
248
249AsanThread *FindThreadByStackAddress(uptr addr) {
250  asanThreadRegistry().CheckLocked();
251  AsanThreadContext *tctx = static_cast<AsanThreadContext *>(
252      asanThreadRegistry().FindThreadContextLocked(ThreadStackContainsAddress,
253                                                   (void *)addr));
254  return tctx ? tctx->thread : 0;
255}
256}  // namespace __asan
257
258// --- Implementation of LSan-specific functions --- {{{1
259namespace __lsan {
260bool GetThreadRangesLocked(uptr os_id, uptr *stack_begin, uptr *stack_end,
261                           uptr *tls_begin, uptr *tls_end,
262                           uptr *cache_begin, uptr *cache_end) {
263  __asan::AsanThreadContext *context = static_cast<__asan::AsanThreadContext *>(
264      __asan::asanThreadRegistry().FindThreadContextByOsIDLocked(os_id));
265  if (!context) return false;
266  __asan::AsanThread *t = context->thread;
267  if (!t) return false;
268  *stack_begin = t->stack_bottom();
269  *stack_end = t->stack_top();
270  *tls_begin = t->tls_begin();
271  *tls_end = t->tls_end();
272  // ASan doesn't keep allocator caches in TLS, so these are unused.
273  *cache_begin = 0;
274  *cache_end = 0;
275  return true;
276}
277
278void LockThreadRegistry() {
279  __asan::asanThreadRegistry().Lock();
280}
281
282void UnlockThreadRegistry() {
283  __asan::asanThreadRegistry().Unlock();
284}
285}  // namespace __lsan
286