1 //===-- asan_thread.h -------------------------------------------*- C++ -*-===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file is a part of AddressSanitizer, an address sanity checker.
10 //
11 // ASan-private header for asan_thread.cpp.
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef ASAN_THREAD_H
15 #define ASAN_THREAD_H
16 
17 #include "asan_allocator.h"
18 #include "asan_internal.h"
19 #include "asan_fake_stack.h"
20 #include "asan_stats.h"
21 #include "sanitizer_common/sanitizer_common.h"
22 #include "sanitizer_common/sanitizer_libc.h"
23 #include "sanitizer_common/sanitizer_thread_registry.h"
24 
25 namespace __sanitizer {
26 struct DTLS;
27 }  // namespace __sanitizer
28 
29 namespace __asan {
30 
31 const u32 kInvalidTid = 0xffffff;  // Must fit into 24 bits.
32 const u32 kMaxNumberOfThreads = (1 << 22);  // 4M
33 
34 class AsanThread;
35 
36 // These objects are created for every thread and are never deleted,
37 // so we can find them by tid even if the thread is long dead.
38 class AsanThreadContext final : public ThreadContextBase {
39  public:
40   explicit AsanThreadContext(int tid)
41       : ThreadContextBase(tid), announced(false),
42         destructor_iterations(GetPthreadDestructorIterations()), stack_id(0),
43         thread(nullptr) {}
44   bool announced;
45   u8 destructor_iterations;
46   u32 stack_id;
47   AsanThread *thread;
48 
49   void OnCreated(void *arg) override;
50   void OnFinished() override;
51 
52   struct CreateThreadContextArgs {
53     AsanThread *thread;
54     StackTrace *stack;
55   };
56 };
57 
58 // AsanThreadContext objects are never freed, so we need many of them.
59 COMPILER_CHECK(sizeof(AsanThreadContext) <= 256);
60 
61 // AsanThread are stored in TSD and destroyed when the thread dies.
62 class AsanThread {
63  public:
64   static AsanThread *Create(thread_callback_t start_routine, void *arg,
65                             u32 parent_tid, StackTrace *stack, bool detached);
66   static void TSDDtor(void *tsd);
67   void Destroy();
68 
69   struct InitOptions;
70   void Init(const InitOptions *options = nullptr);
71 
72   thread_return_t ThreadStart(tid_t os_id);
73 
74   uptr stack_top();
75   uptr stack_bottom();
76   uptr stack_size();
77   uptr tls_begin() { return tls_begin_; }
78   uptr tls_end() { return tls_end_; }
79   DTLS *dtls() { return dtls_; }
80   u32 tid() { return context_->tid; }
81   AsanThreadContext *context() { return context_; }
82   void set_context(AsanThreadContext *context) { context_ = context; }
83 
84   struct StackFrameAccess {
85     uptr offset;
86     uptr frame_pc;
87     const char *frame_descr;
88   };
89   bool GetStackFrameAccessByAddr(uptr addr, StackFrameAccess *access);
90 
91   // Returns a pointer to the start of the stack variable's shadow memory.
92   uptr GetStackVariableShadowStart(uptr addr);
93 
94   bool AddrIsInStack(uptr addr);
95 
96   void DeleteFakeStack(int tid) {
97     if (!fake_stack_) return;
98     FakeStack *t = fake_stack_;
99     fake_stack_ = nullptr;
100     SetTLSFakeStack(nullptr);
101     t->Destroy(tid);
102   }
103 
104   void StartSwitchFiber(FakeStack **fake_stack_save, uptr bottom, uptr size);
105   void FinishSwitchFiber(FakeStack *fake_stack_save, uptr *bottom_old,
106                          uptr *size_old);
107 
108   bool has_fake_stack() {
109     return !atomic_load(&stack_switching_, memory_order_relaxed) &&
110            (reinterpret_cast<uptr>(fake_stack_) > 1);
111   }
112 
113   FakeStack *fake_stack() {
114     if (!__asan_option_detect_stack_use_after_return)
115       return nullptr;
116     if (atomic_load(&stack_switching_, memory_order_relaxed))
117       return nullptr;
118     if (!has_fake_stack())
119       return AsyncSignalSafeLazyInitFakeStack();
120     return fake_stack_;
121   }
122 
123   // True is this thread is currently unwinding stack (i.e. collecting a stack
124   // trace). Used to prevent deadlocks on platforms where libc unwinder calls
125   // malloc internally. See PR17116 for more details.
126   bool isUnwinding() const { return unwinding_; }
127   void setUnwinding(bool b) { unwinding_ = b; }
128 
129   AsanThreadLocalMallocStorage &malloc_storage() { return malloc_storage_; }
130   AsanStats &stats() { return stats_; }
131 
132   void *extra_spill_area() { return &extra_spill_area_; }
133 
134   void *get_arg() { return arg_; }
135 
136  private:
137   // NOTE: There is no AsanThread constructor. It is allocated
138   // via mmap() and *must* be valid in zero-initialized state.
139 
140   void SetThreadStackAndTls(const InitOptions *options);
141 
142   void ClearShadowForThreadStackAndTLS();
143   FakeStack *AsyncSignalSafeLazyInitFakeStack();
144 
145   struct StackBounds {
146     uptr bottom;
147     uptr top;
148   };
149   StackBounds GetStackBounds() const;
150 
151   AsanThreadContext *context_;
152   thread_callback_t start_routine_;
153   void *arg_;
154 
155   uptr stack_top_;
156   uptr stack_bottom_;
157   // these variables are used when the thread is about to switch stack
158   uptr next_stack_top_;
159   uptr next_stack_bottom_;
160   // true if switching is in progress
161   atomic_uint8_t stack_switching_;
162 
163   uptr tls_begin_;
164   uptr tls_end_;
165   DTLS *dtls_;
166 
167   FakeStack *fake_stack_;
168   AsanThreadLocalMallocStorage malloc_storage_;
169   AsanStats stats_;
170   bool unwinding_;
171   uptr extra_spill_area_;
172 };
173 
174 // Returns a single instance of registry.
175 ThreadRegistry &asanThreadRegistry();
176 
177 // Must be called under ThreadRegistryLock.
178 AsanThreadContext *GetThreadContextByTidLocked(u32 tid);
179 
180 // Get the current thread. May return 0.
181 AsanThread *GetCurrentThread();
182 void SetCurrentThread(AsanThread *t);
183 u32 GetCurrentTidOrInvalid();
184 AsanThread *FindThreadByStackAddress(uptr addr);
185 
186 // Used to handle fork().
187 void EnsureMainThreadIDIsCorrect();
188 } // namespace __asan
189 
190 #endif // ASAN_THREAD_H
191