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.
OnDead()74   virtual void OnDead() {}
OnJoined(void * arg)75   virtual void OnJoined(void *arg) {}
OnFinished()76   virtual void OnFinished() {}
OnStarted(void * arg)77   virtual void OnStarted(void *arg) {}
OnCreated(void * arg)78   virtual void OnCreated(void *arg) {}
OnReset()79   virtual void OnReset() {}
OnDetached(void * arg)80   virtual void OnDetached(void *arg) {}
81 
82  protected:
83   ~ThreadContextBase();
84 };
85 
86 typedef ThreadContextBase* (*ThreadContextFactory)(u32 tid);
87 
88 class MUTEX ThreadRegistry {
89  public:
90   ThreadRegistry(ThreadContextFactory factory);
91   ThreadRegistry(ThreadContextFactory factory, u32 max_threads,
92                  u32 thread_quarantine_size, u32 max_reuse);
93   void GetNumberOfThreads(uptr *total = nullptr, uptr *running = nullptr,
94                           uptr *alive = nullptr);
95   uptr GetMaxAliveThreads();
96 
Lock()97   void Lock() ACQUIRE() { mtx_.Lock(); }
CheckLocked()98   void CheckLocked() const CHECK_LOCKED() { mtx_.CheckLocked(); }
Unlock()99   void Unlock() RELEASE() { mtx_.Unlock(); }
100 
101   // Should be guarded by ThreadRegistryLock.
GetThreadLocked(u32 tid)102   ThreadContextBase *GetThreadLocked(u32 tid) {
103     return threads_.empty() ? nullptr : threads_[tid];
104   }
105 
106   u32 CreateThread(uptr user_id, bool detached, u32 parent_tid, void *arg);
107 
108   typedef void (*ThreadCallback)(ThreadContextBase *tctx, void *arg);
109   // Invokes callback with a specified arg for each thread context.
110   // Should be guarded by ThreadRegistryLock.
111   void RunCallbackForEachThreadLocked(ThreadCallback cb, void *arg);
112 
113   typedef bool (*FindThreadCallback)(ThreadContextBase *tctx, void *arg);
114   // Finds a thread using the provided callback. Returns kInvalidTid if no
115   // thread is found.
116   u32 FindThread(FindThreadCallback cb, void *arg);
117   // Should be guarded by ThreadRegistryLock. Return 0 if no thread
118   // is found.
119   ThreadContextBase *FindThreadContextLocked(FindThreadCallback cb,
120                                              void *arg);
121   ThreadContextBase *FindThreadContextByOsIDLocked(tid_t os_id);
122 
123   void SetThreadName(u32 tid, const char *name);
124   void SetThreadNameByUserId(uptr user_id, const char *name);
125   void DetachThread(u32 tid, void *arg);
126   void JoinThread(u32 tid, void *arg);
127   // Finishes thread and returns previous status.
128   ThreadStatus FinishThread(u32 tid);
129   void StartThread(u32 tid, tid_t os_id, ThreadType thread_type, void *arg);
130   void SetThreadUserId(u32 tid, uptr user_id);
131 
132  private:
133   const ThreadContextFactory context_factory_;
134   const u32 max_threads_;
135   const u32 thread_quarantine_size_;
136   const u32 max_reuse_;
137 
138   Mutex mtx_;
139 
140   u64 total_threads_;   // Total number of created threads. May be greater than
141                         // max_threads_ if contexts were reused.
142   uptr alive_threads_;  // Created or running.
143   uptr max_alive_threads_;
144   uptr running_threads_;
145 
146   InternalMmapVector<ThreadContextBase *> threads_;
147   IntrusiveList<ThreadContextBase> dead_threads_;
148   IntrusiveList<ThreadContextBase> invalid_threads_;
149 
150   void QuarantinePush(ThreadContextBase *tctx);
151   ThreadContextBase *QuarantinePop();
152 };
153 
154 typedef GenericScopedLock<ThreadRegistry> ThreadRegistryLock;
155 
156 } // namespace __sanitizer
157 
158 #endif // SANITIZER_THREAD_REGISTRY_H
159