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