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