1 //=-- lsan_thread.cpp -----------------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file is a part of LeakSanitizer.
10 // See lsan_thread.h for details.
12 //===----------------------------------------------------------------------===//
14 #include "lsan_thread.h"
17 #include "lsan_allocator.h"
18 #include "lsan_common.h"
19 #include "sanitizer_common/sanitizer_common.h"
20 #include "sanitizer_common/sanitizer_placement_new.h"
21 #include "sanitizer_common/sanitizer_thread_registry.h"
22 #include "sanitizer_common/sanitizer_tls_get_addr.h"
26 static ThreadRegistry
*thread_registry
;
28 static Mutex mu_for_thread_context
;
29 static LowLevelAllocator allocator_for_thread_context
;
31 static ThreadContextBase
*CreateThreadContext(u32 tid
) {
32 Lock
lock(&mu_for_thread_context
);
33 return new (allocator_for_thread_context
) ThreadContext(tid
);
36 void InitializeThreadRegistry() {
37 static ALIGNED(64) char thread_registry_placeholder
[sizeof(ThreadRegistry
)];
39 new (thread_registry_placeholder
) ThreadRegistry(CreateThreadContext
);
42 ThreadContextLsanBase::ThreadContextLsanBase(int tid
)
43 : ThreadContextBase(tid
) {}
45 void ThreadContextLsanBase::OnStarted(void *arg
) { SetCurrentThread(this); }
47 void ThreadContextLsanBase::OnFinished() {
48 AllocatorThreadFinish();
50 SetCurrentThread(nullptr);
53 u32
ThreadCreate(u32 parent_tid
, bool detached
, void *arg
) {
54 return thread_registry
->CreateThread(0, detached
, parent_tid
, arg
);
57 void ThreadContextLsanBase::ThreadStart(u32 tid
, tid_t os_id
,
58 ThreadType thread_type
, void *arg
) {
59 thread_registry
->StartThread(tid
, os_id
, thread_type
, arg
);
62 void ThreadFinish() { thread_registry
->FinishThread(GetCurrentThreadId()); }
64 void EnsureMainThreadIDIsCorrect() {
65 if (GetCurrentThreadId() == kMainTid
)
66 GetCurrentThread()->os_id
= GetTid();
69 ///// Interface to the common LSan module. /////
71 void GetThreadExtraStackRangesLocked(tid_t os_id
,
72 InternalMmapVector
<Range
> *ranges
) {}
73 void GetThreadExtraStackRangesLocked(InternalMmapVector
<Range
> *ranges
) {}
75 void LockThreadRegistry() { thread_registry
->Lock(); }
77 void UnlockThreadRegistry() { thread_registry
->Unlock(); }
79 ThreadRegistry
*GetLsanThreadRegistryLocked() {
80 thread_registry
->CheckLocked();
81 return thread_registry
;
84 void GetRunningThreadsLocked(InternalMmapVector
<tid_t
> *threads
) {
85 GetLsanThreadRegistryLocked()->RunCallbackForEachThreadLocked(
86 [](ThreadContextBase
*tctx
, void *threads
) {
87 if (tctx
->status
== ThreadStatusRunning
) {
88 reinterpret_cast<InternalMmapVector
<tid_t
> *>(threads
)->push_back(