1 //===-- sanitizer_thread_registry.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 shared between sanitizer tools.
10 //
11 // General thread bookkeeping functionality.
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef SANITIZER_THREAD_REGISTRY_H
15 #define SANITIZER_THREAD_REGISTRY_H
16 
17 #include "sanitizer_common.h"
18 #include "sanitizer_list.h"
19 #include "sanitizer_mutex.h"
20 
21 namespace __sanitizer {
22 
23 enum ThreadStatus {
24   ThreadStatusInvalid,   // Non-existent thread, data is invalid.
25   ThreadStatusCreated,   // Created but not yet running.
26   ThreadStatusRunning,   // The thread is currently running.
27   ThreadStatusFinished,  // Joinable thread is finished but not yet joined.
28   ThreadStatusDead       // Joined, but some info is still available.
29 };
30 
31 enum class ThreadType {
32   Regular, // Normal thread
33   Worker,  // macOS Grand Central Dispatch (GCD) worker thread
34   Fiber,   // Fiber
35 };
36 
37 // Generic thread context. Specific sanitizer tools may inherit from it.
38 // If thread is dead, context may optionally be reused for a new thread.
39 class ThreadContextBase {
40  public:
41   explicit ThreadContextBase(u32 tid);
42   const u32 tid;  // Thread ID. Main thread should have tid = 0.
43   u64 unique_id;  // Unique thread ID.
44   u32 reuse_count;  // Number of times this tid was reused.
45   tid_t os_id;     // PID (used for reporting).
46   uptr user_id;   // Some opaque user thread id (e.g. pthread_t).
47   char name[64];  // As annotated by user.
48 
49   ThreadStatus status;
50   bool detached;
51   ThreadType thread_type;
52 
53   u32 parent_tid;
54   ThreadContextBase *next;  // For storing thread contexts in a list.
55 
56   atomic_uint32_t thread_destroyed; // To address race of Joined vs Finished
57 
58   void SetName(const char *new_name);
59 
60   void SetDead();
61   void SetJoined(void *arg);
62   void SetFinished();
63   void SetStarted(tid_t _os_id, ThreadType _thread_type, void *arg);
64   void SetCreated(uptr _user_id, u64 _unique_id, bool _detached,
65                   u32 _parent_tid, void *arg);
66   void Reset();
67 
68   void SetDestroyed();
69   bool GetDestroyed();
70 
71   // The following methods may be overriden by subclasses.
72   // Some of them take opaque arg that may be optionally be used
73   // by subclasses.
74   virtual void OnDead() {}
75   virtual void OnJoined(void *arg) {}
76   virtual void OnFinished() {}
77   virtual void OnStarted(void *arg) {}
78   virtual void OnCreated(void *arg) {}
79   virtual void OnReset() {}
80   virtual void OnDetached(void *arg) {}
81 
82  protected:
83   ~ThreadContextBase();
84 };
85 
86 typedef ThreadContextBase* (*ThreadContextFactory)(u32 tid);
87 
88 class ThreadRegistry {
89  public:
90   static const u32 kUnknownTid;
91 
92   ThreadRegistry(ThreadContextFactory factory, u32 max_threads,
93                  u32 thread_quarantine_size, u32 max_reuse = 0);
94   void GetNumberOfThreads(uptr *total = nullptr, uptr *running = nullptr,
95                           uptr *alive = nullptr);
96   uptr GetMaxAliveThreads();
97 
98   void Lock() { mtx_.Lock(); }
99   void CheckLocked() { mtx_.CheckLocked(); }
100   void Unlock() { mtx_.Unlock(); }
101 
102   // Should be guarded by ThreadRegistryLock.
103   ThreadContextBase *GetThreadLocked(u32 tid) {
104     DCHECK_LT(tid, n_contexts_);
105     return threads_[tid];
106   }
107 
108   u32 CreateThread(uptr user_id, bool detached, u32 parent_tid, void *arg);
109 
110   typedef void (*ThreadCallback)(ThreadContextBase *tctx, void *arg);
111   // Invokes callback with a specified arg for each thread context.
112   // Should be guarded by ThreadRegistryLock.
113   void RunCallbackForEachThreadLocked(ThreadCallback cb, void *arg);
114 
115   typedef bool (*FindThreadCallback)(ThreadContextBase *tctx, void *arg);
116   // Finds a thread using the provided callback. Returns kUnknownTid if no
117   // thread is found.
118   u32 FindThread(FindThreadCallback cb, void *arg);
119   // Should be guarded by ThreadRegistryLock. Return 0 if no thread
120   // is found.
121   ThreadContextBase *FindThreadContextLocked(FindThreadCallback cb,
122                                              void *arg);
123   ThreadContextBase *FindThreadContextByOsIDLocked(tid_t os_id);
124 
125   void SetThreadName(u32 tid, const char *name);
126   void SetThreadNameByUserId(uptr user_id, const char *name);
127   void DetachThread(u32 tid, void *arg);
128   void JoinThread(u32 tid, void *arg);
129   void FinishThread(u32 tid);
130   void StartThread(u32 tid, tid_t os_id, ThreadType thread_type, void *arg);
131   void SetThreadUserId(u32 tid, uptr user_id);
132 
133  private:
134   const ThreadContextFactory context_factory_;
135   const u32 max_threads_;
136   const u32 thread_quarantine_size_;
137   const u32 max_reuse_;
138 
139   BlockingMutex mtx_;
140 
141   u32 n_contexts_;      // Number of created thread contexts,
142                         // at most max_threads_.
143   u64 total_threads_;   // Total number of created threads. May be greater than
144                         // max_threads_ if contexts were reused.
145   uptr alive_threads_;  // Created or running.
146   uptr max_alive_threads_;
147   uptr running_threads_;
148 
149   ThreadContextBase **threads_;  // Array of thread contexts is leaked.
150   IntrusiveList<ThreadContextBase> dead_threads_;
151   IntrusiveList<ThreadContextBase> invalid_threads_;
152 
153   void QuarantinePush(ThreadContextBase *tctx);
154   ThreadContextBase *QuarantinePop();
155 };
156 
157 typedef GenericScopedLock<ThreadRegistry> ThreadRegistryLock;
158 
159 } // namespace __sanitizer
160 
161 #endif // SANITIZER_THREAD_REGISTRY_H
162