1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
10 #include "MainThreadUtils.h"
11 #include "mozilla/AlreadyAddRefed.h"
12 #include "mozilla/Atomics.h"
13 #include "mozilla/Attributes.h"
14 #include "mozilla/DataMutex.h"
15 #include "mozilla/EventQueue.h"
16 #include "mozilla/LinkedList.h"
17 #include "mozilla/MemoryReporting.h"
18 #include "mozilla/Mutex.h"
19 #include "mozilla/NotNull.h"
20 #include "mozilla/RefPtr.h"
21 #include "mozilla/TaskDispatcher.h"
22 #include "mozilla/TimeStamp.h"
23 #include "mozilla/UniquePtr.h"
24 #include "nsIDirectTaskDispatcher.h"
25 #include "nsIEventTarget.h"
26 #include "nsISerialEventTarget.h"
27 #include "nsISupportsPriority.h"
28 #include "nsIThread.h"
29 #include "nsIThreadInternal.h"
33 class CycleCollectedJSContext
;
34 class DelayedRunnable
;
35 class SynchronizedEventQueue
;
36 class ThreadEventQueue
;
37 class ThreadEventTarget
;
39 template <typename T
, size_t Length
>
41 } // namespace mozilla
43 using mozilla::NotNull
;
46 class nsThreadShutdownContext
;
48 // See https://www.w3.org/TR/longtasks
49 #define LONGTASK_BUSY_WINDOW_MS 50
51 // Time a Runnable executes before we accumulate telemetry on it
52 #define LONGTASK_TELEMETRY_MS 30
54 // A class for managing performance counter state.
56 class PerformanceCounterState
{
58 explicit PerformanceCounterState(const uint32_t& aNestedEventLoopDepthRef
,
60 : mNestedEventLoopDepth(aNestedEventLoopDepthRef
),
61 mIsMainThread(aIsMainThread
),
62 // Does it really make sense to initialize these to "now" when we
63 // haven't run any tasks?
64 mLastLongTaskEnd(TimeStamp::Now()),
65 mLastLongNonIdleTaskEnd(mLastLongTaskEnd
) {}
69 Snapshot(uint32_t aOldEventLoopDepth
, bool aOldIsIdleRunnable
)
70 : mOldEventLoopDepth(aOldEventLoopDepth
),
71 mOldIsIdleRunnable(aOldIsIdleRunnable
) {}
73 Snapshot(const Snapshot
&) = default;
74 Snapshot(Snapshot
&&) = default;
77 friend class PerformanceCounterState
;
79 const uint32_t mOldEventLoopDepth
;
80 const bool mOldIsIdleRunnable
;
83 // Notification that a runnable is about to run. This captures a snapshot of
84 // our current state before we reset to prepare for the new runnable. This
85 // muast be called after mNestedEventLoopDepth has been incremented for the
86 // runnable execution. The performance counter passed in should be the one
87 // for the relevant runnable and may be null. aIsIdleRunnable should be true
88 // if and only if the runnable has idle priority.
89 Snapshot
RunnableWillRun(TimeStamp aNow
, bool aIsIdleRunnable
);
91 // Notification that a runnable finished executing. This must be passed the
92 // snapshot that RunnableWillRun returned for the same runnable. This must be
93 // called before mNestedEventLoopDepth is decremented after the runnable's
95 void RunnableDidRun(const nsCString
& aName
, Snapshot
&& aSnapshot
);
97 const TimeStamp
& LastLongTaskEnd() const { return mLastLongTaskEnd
; }
98 const TimeStamp
& LastLongNonIdleTaskEnd() const {
99 return mLastLongNonIdleTaskEnd
;
103 // Called to report accumulated time, as needed, when we're about to run a
104 // runnable or just finished running one.
105 void MaybeReportAccumulatedTime(const nsCString
& aName
, TimeStamp aNow
);
107 // Whether the runnable we are about to run, or just ran, is a nested
108 // runnable, in the sense that there is some other runnable up the stack
109 // spinning the event loop. This must be called before we change our
110 // mCurrentEventLoopDepth (when about to run a new event) or after we restore
111 // it (after we ran one).
112 bool IsNestedRunnable() const {
113 return mNestedEventLoopDepth
> mCurrentEventLoopDepth
;
116 // The event loop depth of the currently running runnable. Set to the max
117 // value of a uint32_t when there is no runnable running, so when starting to
118 // run a toplevel (not nested) runnable IsNestedRunnable() will test false.
119 uint32_t mCurrentEventLoopDepth
= std::numeric_limits
<uint32_t>::max();
121 // A reference to the nsThread's mNestedEventLoopDepth, so we can
122 // see what it is right now.
123 const uint32_t& mNestedEventLoopDepth
;
125 // A boolean that indicates whether the currently running runnable is an idle
126 // runnable. Only has a useful value between RunnableWillRun() being called
127 // and RunnableDidRun() returning.
128 bool mCurrentRunnableIsIdleRunnable
= false;
130 // Whether we're attached to the mainthread nsThread.
131 const bool mIsMainThread
;
133 // The timestamp from which time to be accounted for should be measured. This
134 // can be the start of a runnable running or the end of a nested runnable
136 TimeStamp mCurrentTimeSliceStart
;
138 // Information about when long tasks last ended.
139 TimeStamp mLastLongTaskEnd
;
140 TimeStamp mLastLongNonIdleTaskEnd
;
142 } // namespace mozilla
145 class nsThread
: public nsIThreadInternal
,
146 public nsISupportsPriority
,
147 public nsIDirectTaskDispatcher
,
148 private mozilla::LinkedListElement
<nsThread
> {
149 friend mozilla::LinkedList
<nsThread
>;
150 friend mozilla::LinkedListElement
<nsThread
>;
153 NS_DECL_THREADSAFE_ISUPPORTS
154 NS_DECL_NSIEVENTTARGET_FULL
156 NS_DECL_NSITHREADINTERNAL
157 NS_DECL_NSISUPPORTSPRIORITY
158 NS_DECL_NSIDIRECTTASKDISPATCHER
160 enum MainThreadFlag
{ MAIN_THREAD
, NOT_MAIN_THREAD
};
162 nsThread(NotNull
<mozilla::SynchronizedEventQueue
*> aQueue
,
163 MainThreadFlag aMainThread
,
164 nsIThreadManager::ThreadCreationOptions aOptions
);
170 // Initialize this as a named wrapper for a new PRThread.
171 nsresult
Init(const nsACString
& aName
);
173 // Initialize this as a wrapper for the current PRThread.
174 nsresult
InitCurrentThread();
176 // Get this thread's name, thread-safe.
177 void GetThreadName(nsACString
& aNameBuffer
);
179 // Set this thread's name. Consider using
180 // NS_SetCurrentThreadName if you are not sure.
181 void SetThreadNameInternal(const nsACString
& aName
);
184 // Initializes the mThreadId and stack base/size members, and adds the thread
185 // to the ThreadList().
189 // The PRThread corresponding to this thread.
190 PRThread
* GetPRThread() const { return mThread
; }
192 const void* StackBase() const { return mStackBase
; }
193 size_t StackSize() const { return mStackSize
; }
195 uint32_t ThreadId() const { return mThreadId
; }
197 // If this flag is true, then the nsThread was created using
198 // nsIThreadManager::NewThread.
199 bool ShutdownRequired() { return mShutdownRequired
; }
201 // Lets GetRunningEventDelay() determine if the pool this is part
202 // of has an unstarted thread
203 void SetPoolThreadFreePtr(mozilla::Atomic
<bool, mozilla::Relaxed
>* aPtr
) {
204 mIsAPoolThreadFree
= aPtr
;
207 void SetScriptObserver(mozilla::CycleCollectedJSContext
* aScriptObserver
);
209 uint32_t RecursionDepth() const;
211 void ShutdownComplete(NotNull
<nsThreadShutdownContext
*> aContext
);
213 void WaitForAllAsynchronousShutdowns();
215 static const uint32_t kRunnableNameBufSize
= 1000;
216 static mozilla::Array
<char, kRunnableNameBufSize
> sMainThreadRunnableName
;
218 mozilla::SynchronizedEventQueue
* EventQueue() { return mEvents
.get(); }
220 bool ShuttingDown() const { return mShutdownContext
!= nullptr; }
222 size_t SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf
) const;
224 // Returns the size of this object, its PRThread, and its shutdown contexts,
225 // but excluding its event queues.
226 size_t ShallowSizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf
) const;
228 size_t SizeOfEventQueues(mozilla::MallocSizeOf aMallocSizeOf
) const;
230 void SetUseHangMonitor(bool aValue
) {
231 MOZ_ASSERT(IsOnCurrentThread());
232 mUseHangMonitor
= aValue
;
236 void DoMainThreadSpecificProcessing() const;
239 friend class nsThreadShutdownEvent
;
243 static void ThreadFunc(void* aArg
);
246 already_AddRefed
<nsIThreadObserver
> GetObserver() {
247 nsIThreadObserver
* obs
;
248 nsThread::GetObserver(&obs
);
249 return already_AddRefed
<nsIThreadObserver
>(obs
);
252 already_AddRefed
<nsThreadShutdownContext
> ShutdownInternal(bool aSync
);
254 friend class nsThreadManager
;
255 friend class nsThreadPool
;
257 void MaybeRemoveFromThreadList();
259 // Whether or not these members have a value determines whether the nsThread
260 // is treated as a full XPCOM thread or as a thin wrapper.
262 // For full nsThreads, they will always contain valid pointers. For thin
263 // wrappers around non-XPCOM threads, they will be null, and event dispatch
264 // methods which rely on them will fail (and assert) if called.
265 RefPtr
<mozilla::SynchronizedEventQueue
> mEvents
;
266 RefPtr
<mozilla::ThreadEventTarget
> mEventTarget
;
268 // The number of outstanding nsThreadShutdownContext started by this thread.
269 // The thread will not be allowed to exit until this number reaches 0.
270 uint32_t mOutstandingShutdownContexts
;
271 // The shutdown context for ourselves.
272 RefPtr
<nsThreadShutdownContext
> mShutdownContext
;
274 mozilla::CycleCollectedJSContext
* mScriptObserver
;
277 mozilla::DataMutex
<nsCString
> mThreadName
;
279 void* mStackBase
= nullptr;
283 uint32_t mNestedEventLoopDepth
;
285 mozilla::Atomic
<bool> mShutdownRequired
;
289 const bool mIsMainThread
;
290 bool mUseHangMonitor
;
291 const bool mIsUiThread
;
292 mozilla::Atomic
<bool, mozilla::Relaxed
>* mIsAPoolThreadFree
;
294 // Set to true if this thread creates a JSRuntime.
297 // The time the currently running event spent in event queues, and
298 // when it started running. If no event is running, they are
299 // TimeDuration() & TimeStamp().
300 mozilla::TimeDuration mLastEventDelay
;
301 mozilla::TimeStamp mLastEventStart
;
303 #ifdef EARLY_BETA_OR_EARLIER
304 nsCString mNameForWakeupTelemetry
;
305 mozilla::TimeStamp mLastWakeupCheckTime
;
306 uint32_t mWakeupCount
= 0;
309 mozilla::PerformanceCounterState mPerformanceCounterState
;
311 mozilla::SimpleTaskQueue mDirectTasks
;
314 class nsThreadShutdownContext final
: public nsIThreadShutdown
{
316 NS_DECL_THREADSAFE_ISUPPORTS
317 NS_DECL_NSITHREADSHUTDOWN
320 friend class nsThread
;
321 friend class nsThreadShutdownEvent
;
322 friend class nsThreadShutdownAckEvent
;
324 nsThreadShutdownContext(NotNull
<nsThread
*> aTerminatingThread
,
325 nsThread
* aJoiningThread
)
326 : mTerminatingThread(aTerminatingThread
),
327 mTerminatingPRThread(aTerminatingThread
->GetPRThread()),
328 mJoiningThreadMutex("nsThreadShutdownContext::mJoiningThreadMutex"),
329 mJoiningThread(aJoiningThread
) {}
331 ~nsThreadShutdownContext() = default;
333 // Must be called on the joining thread.
334 void MarkCompleted();
336 // NB: This may be the last reference.
337 NotNull
<RefPtr
<nsThread
>> const mTerminatingThread
;
338 PRThread
* const mTerminatingPRThread
;
340 // May only be accessed on the joining thread.
341 bool mCompleted
= false;
342 nsTArray
<nsCOMPtr
<nsIRunnable
>> mCompletionCallbacks
;
344 // The thread waiting for this thread to shut down. Will either be cleared by
345 // the joining thread if `StopWaitingAndLeakThread` is called or by the
346 // terminating thread upon exiting and notifying the joining thread.
347 mozilla::Mutex mJoiningThreadMutex
;
348 RefPtr
<nsThread
> mJoiningThread
MOZ_GUARDED_BY(mJoiningThreadMutex
);
349 bool mThreadLeaked
MOZ_GUARDED_BY(mJoiningThreadMutex
) = false;
352 #if defined(XP_UNIX) && !defined(ANDROID) && !defined(DEBUG) && HAVE_UALARM && \
356 extern int sCanaryOutputFD
;
359 #endif // nsThread_h__