| 6 | #define BASE_THREADING_HANG_WATCHER_H_ |
| 7 |
| 8 | #include <atomic> |
| 9 | #include <memory> |
| 10 | #include <vector> |
| 11 |
| 12 | #include "base/atomicops.h" |
| 13 | #include "base/callback.h" |
| 14 | #include "base/callback_helpers.h" |
| 15 | #include "base/feature_list.h" |
| 16 | #include "base/synchronization/lock.h" |
| 17 | #include "base/threading/simple_thread.h" |
| 18 | #include "base/threading/thread_checker.h" |
| 19 | #include "base/threading/thread_local.h" |
| 20 | #include "base/time/time.h" |
| 21 |
| 22 | namespace base { |
| 23 | class HangWatchScope; |
| 24 | namespace internal { |
| 25 | class HangWatchState; |
| 26 | } // namespace internal |
| 27 | } // namespace base |
| 28 |
| 29 | namespace base { |
| 30 |
| 31 | // Instantiate a HangWatchScope in a scope to register to be |
| 32 | // watched for hangs of more than |timeout| by the HangWatcher. |
| 33 | // |
| 34 | // Example usage: |
| 35 | // |
| 36 | // void FooBar(){ |
| 37 | // HangWatchScope scope(base::TimeDelta::FromSeconds(5)); |
| 38 | // DoSomeWork(); |
| 39 | // } |
| 40 | // |
| 41 | // If DoSomeWork() takes more than 5s to run and the HangWatcher |
| 42 | // inspects the thread state before Foobar returns a hang will be |
| 43 | // reported. |
| 44 | // |
| 45 | // HangWatchScopes are typically meant to live on the stack. In some cases it's |
| 46 | // necessary to keep a HangWatchScope instance as a class member but special |
| 47 | // care is required when doing so as a HangWatchScope that stays alive longer |
| 48 | // than intended will generate non-actionable hang reports. |
| 49 | class BASE_EXPORT HangWatchScope { |
| 50 | public: |
| 51 | // A good default value needs to be large enough to represent a significant |
| 52 | // hang and avoid noise while being small enough to not exclude too many |
| 53 | // hangs. The nature of the work that gets executed on the thread is also |
| 54 | // important. We can be much stricter when monitoring a UI thread compared tp |
| 55 | // a ThreadPool thread for example. |
| 56 | static const base::TimeDelta kDefaultHangWatchTime; |
| 57 |
| 58 | // Constructing/destructing thread must be the same thread. |
| 59 | explicit HangWatchScope(TimeDelta timeout); |
| 60 | ~HangWatchScope(); |
| 61 |
| 62 | HangWatchScope(const HangWatchScope&) = delete; |
| 63 | HangWatchScope& operator=(const HangWatchScope&) = delete; |
| 64 |
| 65 | private: |
| 66 | // This object should always be constructed and destructed on the same thread. |
| 67 | THREAD_CHECKER(thread_checker_); |
| 68 |
| 69 | // The deadline set by the previous HangWatchScope created on this thread. |
| 70 | // Stored so it can be restored when this HangWatchScope is destroyed. |
| 71 | TimeTicks previous_deadline_; |
| 72 |
| 73 | #if DCHECK_IS_ON() |
| 74 | // The previous HangWatchScope created on this thread. |
| 75 | HangWatchScope* previous_scope_; |
| 76 | #endif |
| 77 | }; |
| 78 |
| 79 | // Monitors registered threads for hangs by inspecting their associated |
| 80 | // HangWatchStates for deadline overruns. This happens at a regular interval on |
| 81 | // a separate thread. Only one instance of HangWatcher can exist at a time |
| 82 | // within a single process. This instance must outlive all monitored threads. |
| 83 | class BASE_EXPORT HangWatcher : public DelegateSimpleThread::Delegate { |
| 84 | public: |
| 85 | static const base::Feature kEnableHangWatcher; |
| 86 |
| 87 | // The first invocation of the constructor will set the global instance |
| 88 | // accessible through GetInstance(). This means that only one instance can |
| 89 | // exist at a time. |
| 90 | explicit HangWatcher(RepeatingClosure on_hang_closure); |
| 91 |
| 92 | // Clears the global instance for the class. |
| 93 | ~HangWatcher() override; |
| 94 |
| 95 | HangWatcher(const HangWatcher&) = delete; |
| 96 | HangWatcher& operator=(const HangWatcher&) = delete; |
| 97 |
| 98 | // Returns a non-owning pointer to the global HangWatcher instance. |
| 99 | static HangWatcher* GetInstance(); |
| 100 |
| 101 | // Invoke base::debug::DumpWithoutCrashing() insuring that the stack frame |
| 102 | // right under it in the trace belongs to HangWatcher for easier attribution. |
| 103 | NOINLINE static void RecordHang(); |
| 104 |
| 105 | // Sets up the calling thread to be monitored for threads. Returns a |
| 106 | // ScopedClosureRunner that unregisters the thread. This closure has to be |
| 107 | // called from the registered thread before it's joined. |
| 108 | ScopedClosureRunner RegisterThread() |
| 109 | LOCKS_EXCLUDED(watch_state_lock_) WARN_UNUSED_RESULT; |
| 110 |
| 111 | // Choose a closure to be run at the end of each call to Monitor(). Use only |
| 112 | // for testing. |
| 113 | void SetAfterMonitorClosureForTesting(base::RepeatingClosure closure); |
| 114 |
| 115 | // Set a monitoring period other than the default. Use only for |
| 116 | // testing. |
| 117 | void SetMonitoringPeriodForTesting(base::TimeDelta period); |
| 118 |
| 119 | // Force the monitoring loop to resume and evaluate whether to continue. |
| 120 | // This can trigger a call to Monitor() or not depending on why the |
| 121 | // HangWatcher thread is sleeping. Use only for testing. |
| 122 | void SignalMonitorEventForTesting(); |
| 123 |
| 124 | // Use to block until the hang is recorded. Allows the caller to halt |
| 125 | // execution so it does not overshoot the hang watch target and result in a |
| 126 | // non-actionable stack trace in the crash recorded. |
| 127 | void BlockIfCaptureInProgress(); |
| 128 |
| 129 | private: |
| 130 | THREAD_CHECKER(thread_checker_); |
| 131 |
| 132 | // Inspects the state of all registered threads to check if they are hung and |
| 133 | // invokes the appropriate closure if so. |
| 134 | void Monitor(); |
| 135 |
| 136 | // Call Run() on the HangWatcher thread. |
| 137 | void Start(); |
| 138 |
| 139 | // Stop all monitoring and join the HangWatcher thread. |
| 140 | void Stop(); |
| 141 |
| 142 | // Run the loop that periodically monitors the registered thread at a |
| 143 | // set time interval. |
| 144 | void Run() override; |
| 145 |
| 146 | base::TimeDelta monitor_period_; |
| 147 |
| 148 | // Indicates whether Run() should return after the next monitoring. |
| 149 | std::atomic<bool> keep_monitoring_{true}; |
| 150 |
| 151 | // Use to make the HangWatcher thread wake or sleep to schedule the |
| 152 | // appropriate monitoring frequency. |
| 153 | WaitableEvent should_monitor_; |
| 154 |
| 155 | bool IsWatchListEmpty() LOCKS_EXCLUDED(watch_state_lock_); |
| 156 |
| 157 | // Stops hang watching on the calling thread by removing the entry from the |
| 158 | // watch list. |
| 159 | void UnregisterThread() LOCKS_EXCLUDED(watch_state_lock_); |
| 160 |
| 161 | const RepeatingClosure on_hang_closure_; |
| 162 | Lock watch_state_lock_; |
| 163 |
| 164 | std::vector<std::unique_ptr<internal::HangWatchState>> watch_states_ |
| 165 | GUARDED_BY(watch_state_lock_); |
| 166 |
| 167 | base::DelegateSimpleThread thread_; |
| 168 |
| 169 | base::RepeatingClosure after_monitor_closure_for_testing_; |
| 170 |
| 171 | base::Lock capture_lock_; |
| 172 | std::atomic<bool> capture_in_progress{false}; |
| 173 |
| 174 | FRIEND_TEST_ALL_PREFIXES(HangWatcherTest, NestedScopes); |
| 175 | }; |
| 176 |
| 177 | // Classes here are exposed in the header only for testing. They are not |
| 178 | // intended to be used outside of base. |
| 179 | namespace internal { |
| 180 |
| 181 | // Contains the information necessary for hang watching a specific |
| 182 | // thread. Instances of this class are accessed concurrently by the associated |
| 183 | // thread and the HangWatcher. The HangWatcher owns instances of this |
| 184 | // class and outside of it they are accessed through |
| 185 | // GetHangWatchStateForCurrentThread(). |
| 186 | class BASE_EXPORT HangWatchState { |
| 187 | public: |
| 188 | HangWatchState(); |
| 189 | ~HangWatchState(); |
| 190 |
| 191 | HangWatchState(const HangWatchState&) = delete; |
| 192 | HangWatchState& operator=(const HangWatchState&) = delete; |
| 193 |
| 194 | // Allocates a new state object bound to the calling thread and returns an |
| 195 | // owning pointer to it. |
| 196 | static std::unique_ptr<HangWatchState> CreateHangWatchStateForCurrentThread(); |
| 197 |
| 198 | // Retrieves the hang watch state associated with the calling thread. |
| 199 | // Returns nullptr if no HangWatchState exists for the current thread (see |
| 200 | // CreateHangWatchStateForCurrentThread()). |
| 201 | static ThreadLocalPointer<HangWatchState>* |
| 202 | GetHangWatchStateForCurrentThread(); |
| 203 |
| 204 | // Returns the value of the current deadline. Use this function if you need to |
| 205 | // store the value. To test if the deadline has expired use IsOverDeadline(). |
| 206 | TimeTicks GetDeadline() const; |
| 207 |
| 208 | // Atomically sets the deadline to a new value and return the previous value. |
| 209 | void SetDeadline(TimeTicks deadline); |
| 210 |
| 211 | // Tests whether the associated thread's execution has gone over the deadline. |
| 212 | bool IsOverDeadline() const; |
| 213 |
| 214 | #if DCHECK_IS_ON() |
| 215 | // Saves the supplied HangWatchScope as the currently active scope. |
| 216 | void SetCurrentHangWatchScope(HangWatchScope* scope); |
| 217 |
| 218 | // Retrieve the currently active scope. |
| 219 | HangWatchScope* GetCurrentHangWatchScope(); |
| 220 | #endif |
| 221 |
| 222 | private: |
| 223 | // The thread that creates the instance should be the class that updates |
| 224 | // the deadline. |
| 225 | THREAD_CHECKER(thread_checker_); |
| 226 |
| 227 | // If the deadline fails to be updated before TimeTicks::Now() ever |
| 228 | // reaches the value contained in it this constistutes a hang. |
| 229 | std::atomic<TimeTicks> deadline_{base::TimeTicks::Max()}; |
| 230 |
| 231 | #if DCHECK_IS_ON() |
| 232 | // Used to keep track of the current HangWatchScope and detect improper usage. |
| 233 | // Scopes should always be destructed in reverse order from the one they were |
| 234 | // constructed in. Example of improper use: |
| 235 | // |
| 236 | // { |
| 237 | // std::unique_ptr<Scope> scope = std::make_unique<Scope>(...); |
| 238 | // Scope other_scope; |
| 239 | // |scope| gets deallocated first, violating reverse destruction order. |
| 240 | // scope.reset(); |
| 241 | // } |
| 242 | HangWatchScope* current_hang_watch_scope_{nullptr}; |
| 243 | #endif |
| 244 | }; |
| 245 |
| 246 | } // namespace internal |
| 247 | } // namespace base |
| 248 |
| 249 | #endif // BASE_THREADING_HANG_WATCHER_H_ |
| 250 |