1 //===-- dfsan_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 DataFlowSanitizer.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef DFSAN_THREAD_H
14 #define DFSAN_THREAD_H
15 
16 #include "dfsan_allocator.h"
17 #include "sanitizer_common/sanitizer_common.h"
18 
19 namespace __dfsan {
20 
21 class DFsanThread {
22  public:
23   // NOTE: There is no DFsanThread constructor. It is allocated
24   // via mmap() and *must* be valid in zero-initialized state.
25 
26   static DFsanThread *Create(void *start_routine_trampoline,
27                              thread_callback_t start_routine, void *arg,
28                              bool track_origins = false);
29   static void TSDDtor(void *tsd);
30   void Destroy();
31 
32   void Init();  // Should be called from the thread itself.
33   thread_return_t ThreadStart();
34 
35   uptr stack_top();
36   uptr stack_bottom();
tls_begin()37   uptr tls_begin() { return tls_begin_; }
tls_end()38   uptr tls_end() { return tls_end_; }
IsMainThread()39   bool IsMainThread() { return start_routine_ == nullptr; }
40 
InSignalHandler()41   bool InSignalHandler() { return in_signal_handler_; }
EnterSignalHandler()42   void EnterSignalHandler() { in_signal_handler_++; }
LeaveSignalHandler()43   void LeaveSignalHandler() { in_signal_handler_--; }
44 
malloc_storage()45   DFsanThreadLocalMallocStorage &malloc_storage() { return malloc_storage_; }
46 
47   int destructor_iterations_;
48 
49  private:
50   void SetThreadStackAndTls();
51   void ClearShadowForThreadStackAndTLS();
52   struct StackBounds {
53     uptr bottom;
54     uptr top;
55   };
56   StackBounds GetStackBounds() const;
57 
58   bool AddrIsInStack(uptr addr);
59 
60   void *start_routine_trampoline_;
61   thread_callback_t start_routine_;
62   void *arg_;
63   bool track_origins_;
64 
65   StackBounds stack_;
66 
67   uptr tls_begin_;
68   uptr tls_end_;
69 
70   unsigned in_signal_handler_;
71 
72   DFsanThreadLocalMallocStorage malloc_storage_;
73 };
74 
75 DFsanThread *GetCurrentThread();
76 void SetCurrentThread(DFsanThread *t);
77 void DFsanTSDInit(void (*destructor)(void *tsd));
78 void DFsanTSDDtor(void *tsd);
79 
80 }  // namespace __dfsan
81 
82 #endif  // DFSAN_THREAD_H
83