1 //===-- asan_thread.cc ----------------------------------------------------===//
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
6 //===----------------------------------------------------------------------===//
8 // This file is a part of AddressSanitizer, an address sanity checker.
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 "sanitizer_common/sanitizer_tls_get_addr.h"
22 #include "lsan/lsan_common.h"
26 // AsanThreadContext implementation.
28 struct CreateThreadContextArgs
{
33 void AsanThreadContext::OnCreated(void *arg
) {
34 CreateThreadContextArgs
*args
= static_cast<CreateThreadContextArgs
*>(arg
);
36 stack_id
= StackDepotPut(*args
->stack
);
37 thread
= args
->thread
;
38 thread
->set_context(this);
41 void AsanThreadContext::OnFinished() {
42 // Drop the link to the AsanThread object.
46 // MIPS requires aligned address
47 static ALIGNED(16) char thread_registry_placeholder
[sizeof(ThreadRegistry
)];
48 static ThreadRegistry
*asan_thread_registry
;
50 static BlockingMutex
mu_for_thread_context(LINKER_INITIALIZED
);
51 static LowLevelAllocator allocator_for_thread_context
;
53 static ThreadContextBase
*GetAsanThreadContext(u32 tid
) {
54 BlockingMutexLock
lock(&mu_for_thread_context
);
55 return new(allocator_for_thread_context
) AsanThreadContext(tid
);
58 ThreadRegistry
&asanThreadRegistry() {
59 static bool initialized
;
60 // Don't worry about thread_safety - this should be called when there is
63 // Never reuse ASan threads: we store pointer to AsanThreadContext
64 // in TSD and can't reliably tell when no more TSD destructors will
65 // be called. It would be wrong to reuse AsanThreadContext for another
66 // thread before all TSD destructors will be called for it.
67 asan_thread_registry
= new(thread_registry_placeholder
) ThreadRegistry(
68 GetAsanThreadContext
, kMaxNumberOfThreads
, kMaxNumberOfThreads
);
71 return *asan_thread_registry
;
74 AsanThreadContext
*GetThreadContextByTidLocked(u32 tid
) {
75 return static_cast<AsanThreadContext
*>(
76 asanThreadRegistry().GetThreadLocked(tid
));
79 // AsanThread implementation.
81 AsanThread
*AsanThread::Create(thread_callback_t start_routine
, void *arg
,
82 u32 parent_tid
, StackTrace
*stack
,
84 uptr PageSize
= GetPageSizeCached();
85 uptr size
= RoundUpTo(sizeof(AsanThread
), PageSize
);
86 AsanThread
*thread
= (AsanThread
*)MmapOrDie(size
, __func__
);
87 thread
->start_routine_
= start_routine
;
89 CreateThreadContextArgs args
= { thread
, stack
};
90 asanThreadRegistry().CreateThread(*reinterpret_cast<uptr
*>(thread
), detached
,
96 void AsanThread::TSDDtor(void *tsd
) {
97 AsanThreadContext
*context
= (AsanThreadContext
*)tsd
;
98 VReport(1, "T%d TSDDtor\n", context
->tid
);
100 context
->thread
->Destroy();
103 void AsanThread::Destroy() {
104 int tid
= this->tid();
105 VReport(1, "T%d exited\n", tid
);
107 malloc_storage().CommitBack();
108 if (common_flags()->use_sigaltstack
) UnsetAlternateSignalStack();
109 asanThreadRegistry().FinishThread(tid
);
110 FlushToDeadThreadStats(&stats_
);
111 // We also clear the shadow on thread destruction because
112 // some code may still be executing in later TSD destructors
113 // and we don't want it to have any poisoned stack.
114 ClearShadowForThreadStackAndTLS();
115 DeleteFakeStack(tid
);
116 uptr size
= RoundUpTo(sizeof(AsanThread
), GetPageSizeCached());
117 UnmapOrDie(this, size
);
121 // We want to create the FakeStack lazyly on the first use, but not eralier
122 // than the stack size is known and the procedure has to be async-signal safe.
123 FakeStack
*AsanThread::AsyncSignalSafeLazyInitFakeStack() {
124 uptr stack_size
= this->stack_size();
125 if (stack_size
== 0) // stack_size is not yet available, don't use FakeStack.
128 // fake_stack_ has 3 states:
129 // 0 -- not initialized
130 // 1 -- being initialized
131 // ptr -- initialized
132 // This CAS checks if the state was 0 and if so changes it to state 1,
133 // if that was successful, it initializes the pointer.
134 if (atomic_compare_exchange_strong(
135 reinterpret_cast<atomic_uintptr_t
*>(&fake_stack_
), &old_val
, 1UL,
136 memory_order_relaxed
)) {
137 uptr stack_size_log
= Log2(RoundUpToPowerOfTwo(stack_size
));
138 CHECK_LE(flags()->min_uar_stack_size_log
, flags()->max_uar_stack_size_log
);
140 Min(stack_size_log
, static_cast<uptr
>(flags()->max_uar_stack_size_log
));
142 Max(stack_size_log
, static_cast<uptr
>(flags()->min_uar_stack_size_log
));
143 fake_stack_
= FakeStack::Create(stack_size_log
);
144 SetTLSFakeStack(fake_stack_
);
150 void AsanThread::Init() {
151 fake_stack_
= nullptr; // Will be initialized lazily if needed.
152 CHECK_EQ(this->stack_size(), 0U);
153 SetThreadStackAndTls();
154 CHECK_GT(this->stack_size(), 0U);
155 CHECK(AddrIsInMem(stack_bottom_
));
156 CHECK(AddrIsInMem(stack_top_
- 1));
157 ClearShadowForThreadStackAndTLS();
159 VReport(1, "T%d: stack [%p,%p) size 0x%zx; local=%p\n", tid(),
160 (void *)stack_bottom_
, (void *)stack_top_
, stack_top_
- stack_bottom_
,
164 thread_return_t
AsanThread::ThreadStart(
165 uptr os_id
, atomic_uintptr_t
*signal_thread_is_registered
) {
167 asanThreadRegistry().StartThread(tid(), os_id
, nullptr);
168 if (signal_thread_is_registered
)
169 atomic_store(signal_thread_is_registered
, 1, memory_order_release
);
171 if (common_flags()->use_sigaltstack
) SetAlternateSignalStack();
173 if (!start_routine_
) {
174 // start_routine_ == 0 if we're on the main thread or on one of the
175 // OS X libdispatch worker threads. But nobody is supposed to call
176 // ThreadStart() for the worker threads.
181 thread_return_t res
= start_routine_(arg_
);
183 // On POSIX systems we defer this to the TSD destructor. LSan will consider
184 // the thread's memory as non-live from the moment we call Destroy(), even
185 // though that memory might contain pointers to heap objects which will be
186 // cleaned up by a user-defined TSD destructor. Thus, calling Destroy() before
187 // the TSD destructors have run might cause false positives in LSan.
188 if (!SANITIZER_POSIX
)
194 void AsanThread::SetThreadStackAndTls() {
196 GetThreadStackAndTls(tid() == 0, &stack_bottom_
, &stack_size_
, &tls_begin_
,
198 stack_top_
= stack_bottom_
+ stack_size_
;
199 tls_end_
= tls_begin_
+ tls_size
;
202 CHECK(AddrIsInStack((uptr
)&local
));
205 void AsanThread::ClearShadowForThreadStackAndTLS() {
206 PoisonShadow(stack_bottom_
, stack_top_
- stack_bottom_
, 0);
207 if (tls_begin_
!= tls_end_
)
208 PoisonShadow(tls_begin_
, tls_end_
- tls_begin_
, 0);
211 bool AsanThread::GetStackFrameAccessByAddr(uptr addr
,
212 StackFrameAccess
*access
) {
214 if (AddrIsInStack(addr
)) {
215 bottom
= stack_bottom();
216 } else if (has_fake_stack()) {
217 bottom
= fake_stack()->AddrIsInFakeStack(addr
);
219 access
->offset
= addr
- bottom
;
220 access
->frame_pc
= ((uptr
*)bottom
)[2];
221 access
->frame_descr
= (const char *)((uptr
*)bottom
)[1];
224 uptr aligned_addr
= addr
& ~(SANITIZER_WORDSIZE
/8 - 1); // align addr.
225 u8
*shadow_ptr
= (u8
*)MemToShadow(aligned_addr
);
226 u8
*shadow_bottom
= (u8
*)MemToShadow(bottom
);
228 while (shadow_ptr
>= shadow_bottom
&&
229 *shadow_ptr
!= kAsanStackLeftRedzoneMagic
) {
233 while (shadow_ptr
>= shadow_bottom
&&
234 *shadow_ptr
== kAsanStackLeftRedzoneMagic
) {
238 if (shadow_ptr
< shadow_bottom
) {
242 uptr
* ptr
= (uptr
*)SHADOW_TO_MEM((uptr
)(shadow_ptr
+ 1));
243 CHECK(ptr
[0] == kCurrentStackFrameMagic
);
244 access
->offset
= addr
- (uptr
)ptr
;
245 access
->frame_pc
= ptr
[2];
246 access
->frame_descr
= (const char*)ptr
[1];
250 static bool ThreadStackContainsAddress(ThreadContextBase
*tctx_base
,
252 AsanThreadContext
*tctx
= static_cast<AsanThreadContext
*>(tctx_base
);
253 AsanThread
*t
= tctx
->thread
;
254 if (!t
) return false;
255 if (t
->AddrIsInStack((uptr
)addr
)) return true;
256 if (t
->has_fake_stack() && t
->fake_stack()->AddrIsInFakeStack((uptr
)addr
))
261 AsanThread
*GetCurrentThread() {
262 AsanThreadContext
*context
=
263 reinterpret_cast<AsanThreadContext
*>(AsanTSDGet());
265 if (SANITIZER_ANDROID
) {
266 // On Android, libc constructor is called _after_ asan_init, and cleans up
267 // TSD. Try to figure out if this is still the main thread by the stack
268 // address. We are not entirely sure that we have correct main thread
269 // limits, so only do this magic on Android, and only if the found thread
270 // is the main thread.
271 AsanThreadContext
*tctx
= GetThreadContextByTidLocked(0);
272 if (ThreadStackContainsAddress(tctx
, &context
)) {
273 SetCurrentThread(tctx
->thread
);
279 return context
->thread
;
282 void SetCurrentThread(AsanThread
*t
) {
284 VReport(2, "SetCurrentThread: %p for thread %p\n", t
->context(),
285 (void *)GetThreadSelf());
286 // Make sure we do not reset the current AsanThread.
287 CHECK_EQ(0, AsanTSDGet());
288 AsanTSDSet(t
->context());
289 CHECK_EQ(t
->context(), AsanTSDGet());
292 u32
GetCurrentTidOrInvalid() {
293 AsanThread
*t
= GetCurrentThread();
294 return t
? t
->tid() : kInvalidTid
;
297 AsanThread
*FindThreadByStackAddress(uptr addr
) {
298 asanThreadRegistry().CheckLocked();
299 AsanThreadContext
*tctx
= static_cast<AsanThreadContext
*>(
300 asanThreadRegistry().FindThreadContextLocked(ThreadStackContainsAddress
,
302 return tctx
? tctx
->thread
: nullptr;
305 void EnsureMainThreadIDIsCorrect() {
306 AsanThreadContext
*context
=
307 reinterpret_cast<AsanThreadContext
*>(AsanTSDGet());
308 if (context
&& (context
->tid
== 0))
309 context
->os_id
= GetTid();
312 __asan::AsanThread
*GetAsanThreadByOsIDLocked(uptr os_id
) {
313 __asan::AsanThreadContext
*context
= static_cast<__asan::AsanThreadContext
*>(
314 __asan::asanThreadRegistry().FindThreadContextByOsIDLocked(os_id
));
315 if (!context
) return nullptr;
316 return context
->thread
;
318 } // namespace __asan
320 // --- Implementation of LSan-specific functions --- {{{1
322 bool GetThreadRangesLocked(uptr os_id
, uptr
*stack_begin
, uptr
*stack_end
,
323 uptr
*tls_begin
, uptr
*tls_end
,
324 uptr
*cache_begin
, uptr
*cache_end
) {
325 __asan::AsanThread
*t
= __asan::GetAsanThreadByOsIDLocked(os_id
);
326 if (!t
) return false;
327 *stack_begin
= t
->stack_bottom();
328 *stack_end
= t
->stack_top();
329 *tls_begin
= t
->tls_begin();
330 *tls_end
= t
->tls_end();
331 // ASan doesn't keep allocator caches in TLS, so these are unused.
337 void ForEachExtraStackRange(uptr os_id
, RangeIteratorCallback callback
,
339 __asan::AsanThread
*t
= __asan::GetAsanThreadByOsIDLocked(os_id
);
340 if (t
&& t
->has_fake_stack())
341 t
->fake_stack()->ForEachFakeFrame(callback
, arg
);
344 void LockThreadRegistry() {
345 __asan::asanThreadRegistry().Lock();
348 void UnlockThreadRegistry() {
349 __asan::asanThreadRegistry().Unlock();
352 void EnsureMainThreadIDIsCorrect() {
353 __asan::EnsureMainThreadIDIsCorrect();
355 } // namespace __lsan