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
21namespace __sanitizer {
22
23enum 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
31enum 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.
39class ThreadContextBase {
40 public:
41  explicit ThreadContextBase(u32 tid);
42  ~ThreadContextBase();  // Should never be called.
43
44  const u32 tid;  // Thread ID. Main thread should have tid = 0.
45  u64 unique_id;  // Unique thread ID.
46  u32 reuse_count;  // Number of times this tid was reused.
47  tid_t os_id;     // PID (used for reporting).
48  uptr user_id;   // Some opaque user thread id (e.g. pthread_t).
49  char name[64];  // As annotated by user.
50
51  ThreadStatus status;
52  bool detached;
53  ThreadType thread_type;
54
55  u32 parent_tid;
56  ThreadContextBase *next;  // For storing thread contexts in a list.
57
58  atomic_uint32_t thread_destroyed; // To address race of Joined vs Finished
59
60  void SetName(const char *new_name);
61
62  void SetDead();
63  void SetJoined(void *arg);
64  void SetFinished();
65  void SetStarted(tid_t _os_id, ThreadType _thread_type, void *arg);
66  void SetCreated(uptr _user_id, u64 _unique_id, bool _detached,
67                  u32 _parent_tid, void *arg);
68  void Reset();
69
70  void SetDestroyed();
71  bool GetDestroyed();
72
73  // The following methods may be overriden by subclasses.
74  // Some of them take opaque arg that may be optionally be used
75  // by subclasses.
76  virtual void OnDead() {}
77  virtual void OnJoined(void *arg) {}
78  virtual void OnFinished() {}
79  virtual void OnStarted(void *arg) {}
80  virtual void OnCreated(void *arg) {}
81  virtual void OnReset() {}
82  virtual void OnDetached(void *arg) {}
83};
84
85typedef ThreadContextBase* (*ThreadContextFactory)(u32 tid);
86
87class ThreadRegistry {
88 public:
89  static const u32 kUnknownTid;
90
91  ThreadRegistry(ThreadContextFactory factory, u32 max_threads,
92                 u32 thread_quarantine_size, u32 max_reuse = 0);
93  void GetNumberOfThreads(uptr *total = nullptr, uptr *running = nullptr,
94                          uptr *alive = nullptr);
95  uptr GetMaxAliveThreads();
96
97  void Lock() { mtx_.Lock(); }
98  void CheckLocked() { mtx_.CheckLocked(); }
99  void Unlock() { mtx_.Unlock(); }
100
101  // Should be guarded by ThreadRegistryLock.
102  ThreadContextBase *GetThreadLocked(u32 tid) {
103    DCHECK_LT(tid, n_contexts_);
104    return threads_[tid];
105  }
106
107  u32 CreateThread(uptr user_id, bool detached, u32 parent_tid, void *arg);
108
109  typedef void (*ThreadCallback)(ThreadContextBase *tctx, void *arg);
110  // Invokes callback with a specified arg for each thread context.
111  // Should be guarded by ThreadRegistryLock.
112  void RunCallbackForEachThreadLocked(ThreadCallback cb, void *arg);
113
114  typedef bool (*FindThreadCallback)(ThreadContextBase *tctx, void *arg);
115  // Finds a thread using the provided callback. Returns kUnknownTid if no
116  // thread is found.
117  u32 FindThread(FindThreadCallback cb, void *arg);
118  // Should be guarded by ThreadRegistryLock. Return 0 if no thread
119  // is found.
120  ThreadContextBase *FindThreadContextLocked(FindThreadCallback cb,
121                                             void *arg);
122  ThreadContextBase *FindThreadContextByOsIDLocked(tid_t os_id);
123
124  void SetThreadName(u32 tid, const char *name);
125  void SetThreadNameByUserId(uptr user_id, const char *name);
126  void DetachThread(u32 tid, void *arg);
127  void JoinThread(u32 tid, void *arg);
128  void 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  BlockingMutex mtx_;
139
140  u32 n_contexts_;      // Number of created thread contexts,
141                        // at most max_threads_.
142  u64 total_threads_;   // Total number of created threads. May be greater than
143                        // max_threads_ if contexts were reused.
144  uptr alive_threads_;  // Created or running.
145  uptr max_alive_threads_;
146  uptr running_threads_;
147
148  ThreadContextBase **threads_;  // Array of thread contexts is leaked.
149  IntrusiveList<ThreadContextBase> dead_threads_;
150  IntrusiveList<ThreadContextBase> invalid_threads_;
151
152  void QuarantinePush(ThreadContextBase *tctx);
153  ThreadContextBase *QuarantinePop();
154};
155
156typedef GenericScopedLock<ThreadRegistry> ThreadRegistryLock;
157
158} // namespace __sanitizer
159
160#endif // SANITIZER_THREAD_REGISTRY_H
161