Bug 1854550 - pt 12. Allow inlining between mozjemalloc and PHC r=glandium
[gecko.git] / xpcom / threads / nsThreadManager.cpp
blobc33144158b96779378a7cb1f0b996c974f9c2c31
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/. */
7 #include "nsThreadManager.h"
8 #include "nsThread.h"
9 #include "nsThreadPool.h"
10 #include "nsThreadUtils.h"
11 #include "nsIClassInfoImpl.h"
12 #include "nsExceptionHandler.h"
13 #include "nsTArray.h"
14 #include "nsXULAppAPI.h"
15 #include "nsExceptionHandler.h"
16 #include "mozilla/AbstractThread.h"
17 #include "mozilla/AppShutdown.h"
18 #include "mozilla/ClearOnShutdown.h"
19 #include "mozilla/CycleCollectedJSContext.h" // nsAutoMicroTask
20 #include "mozilla/EventQueue.h"
21 #include "mozilla/InputTaskManager.h"
22 #include "mozilla/Mutex.h"
23 #include "mozilla/NeverDestroyed.h"
24 #include "mozilla/Preferences.h"
25 #include "mozilla/ProfilerMarkers.h"
26 #include "mozilla/SpinEventLoopUntil.h"
27 #include "mozilla/StaticPtr.h"
28 #include "mozilla/TaskQueue.h"
29 #include "mozilla/ThreadEventQueue.h"
30 #include "mozilla/ThreadLocal.h"
31 #include "TaskController.h"
32 #include "ThreadEventTarget.h"
33 #ifdef MOZ_CANARY
34 # include <fcntl.h>
35 # include <unistd.h>
36 #endif
38 #include "MainThreadIdlePeriod.h"
40 using namespace mozilla;
42 static MOZ_THREAD_LOCAL(bool) sTLSIsMainThread;
44 bool NS_IsMainThreadTLSInitialized() { return sTLSIsMainThread.initialized(); }
46 class BackgroundEventTarget final : public nsIEventTarget,
47 public TaskQueueTracker {
48 public:
49 NS_DECL_THREADSAFE_ISUPPORTS
50 NS_DECL_NSIEVENTTARGET_FULL
52 BackgroundEventTarget() = default;
54 nsresult Init();
56 already_AddRefed<TaskQueue> CreateBackgroundTaskQueue(const char* aName);
58 void BeginShutdown(nsTArray<RefPtr<ShutdownPromise>>&);
59 void FinishShutdown();
61 private:
62 ~BackgroundEventTarget() = default;
64 nsCOMPtr<nsIThreadPool> mPool;
65 nsCOMPtr<nsIThreadPool> mIOPool;
68 NS_IMPL_ISUPPORTS(BackgroundEventTarget, nsIEventTarget, TaskQueueTracker)
70 nsresult BackgroundEventTarget::Init() {
71 nsCOMPtr<nsIThreadPool> pool(new nsThreadPool());
72 NS_ENSURE_TRUE(pool, NS_ERROR_FAILURE);
74 nsresult rv = pool->SetName("BackgroundThreadPool"_ns);
75 NS_ENSURE_SUCCESS(rv, rv);
77 // Use potentially more conservative stack size.
78 rv = pool->SetThreadStackSize(nsIThreadManager::kThreadPoolStackSize);
79 NS_ENSURE_SUCCESS(rv, rv);
81 // Thread limit of 2 makes deadlock during synchronous dispatch less likely.
82 rv = pool->SetThreadLimit(2);
83 NS_ENSURE_SUCCESS(rv, rv);
85 rv = pool->SetIdleThreadLimit(1);
86 NS_ENSURE_SUCCESS(rv, rv);
88 // Leave threads alive for up to 5 minutes
89 rv = pool->SetIdleThreadTimeout(300000);
90 NS_ENSURE_SUCCESS(rv, rv);
92 // Initialize the background I/O event target.
93 nsCOMPtr<nsIThreadPool> ioPool(new nsThreadPool());
94 NS_ENSURE_TRUE(pool, NS_ERROR_FAILURE);
96 // The io pool spends a lot of its time blocking on io, so we want to offload
97 // these jobs on a lower priority if available.
98 rv = ioPool->SetQoSForThreads(nsIThread::QOS_PRIORITY_LOW);
99 NS_ENSURE_SUCCESS(
100 rv, rv); // note: currently infallible, keeping this for brevity.
102 rv = ioPool->SetName("BgIOThreadPool"_ns);
103 NS_ENSURE_SUCCESS(rv, rv);
105 // Use potentially more conservative stack size.
106 rv = ioPool->SetThreadStackSize(nsIThreadManager::kThreadPoolStackSize);
107 NS_ENSURE_SUCCESS(rv, rv);
109 // Thread limit of 4 makes deadlock during synchronous dispatch less likely.
110 rv = ioPool->SetThreadLimit(4);
111 NS_ENSURE_SUCCESS(rv, rv);
113 rv = ioPool->SetIdleThreadLimit(1);
114 NS_ENSURE_SUCCESS(rv, rv);
116 // Leave threads alive for up to 5 minutes
117 rv = ioPool->SetIdleThreadTimeout(300000);
118 NS_ENSURE_SUCCESS(rv, rv);
120 pool.swap(mPool);
121 ioPool.swap(mIOPool);
123 return NS_OK;
126 NS_IMETHODIMP_(bool)
127 BackgroundEventTarget::IsOnCurrentThreadInfallible() {
128 return mPool->IsOnCurrentThread() || mIOPool->IsOnCurrentThread();
131 NS_IMETHODIMP
132 BackgroundEventTarget::IsOnCurrentThread(bool* aValue) {
133 bool value = false;
134 if (NS_SUCCEEDED(mPool->IsOnCurrentThread(&value)) && value) {
135 *aValue = value;
136 return NS_OK;
138 return mIOPool->IsOnCurrentThread(aValue);
141 NS_IMETHODIMP
142 BackgroundEventTarget::Dispatch(already_AddRefed<nsIRunnable> aRunnable,
143 uint32_t aFlags) {
144 // We need to be careful here, because if an event is getting dispatched here
145 // from within TaskQueue::Runner::Run, it will be dispatched with
146 // NS_DISPATCH_AT_END, but we might not be running the event on the same
147 // pool, depending on which pool we were on and the dispatch flags. If we
148 // dispatch an event with NS_DISPATCH_AT_END to the wrong pool, the pool
149 // may not process the event in a timely fashion, which can lead to deadlock.
150 uint32_t flags = aFlags & ~NS_DISPATCH_EVENT_MAY_BLOCK;
151 bool mayBlock = bool(aFlags & NS_DISPATCH_EVENT_MAY_BLOCK);
152 nsCOMPtr<nsIThreadPool>& pool = mayBlock ? mIOPool : mPool;
154 // If we're already running on the pool we want to dispatch to, we can
155 // unconditionally add NS_DISPATCH_AT_END to indicate that we shouldn't spin
156 // up a new thread.
158 // Otherwise, we should remove NS_DISPATCH_AT_END so we don't run into issues
159 // like those in the above comment.
160 if (pool->IsOnCurrentThread()) {
161 flags |= NS_DISPATCH_AT_END;
162 } else {
163 flags &= ~NS_DISPATCH_AT_END;
166 return pool->Dispatch(std::move(aRunnable), flags);
169 NS_IMETHODIMP
170 BackgroundEventTarget::DispatchFromScript(nsIRunnable* aRunnable,
171 uint32_t aFlags) {
172 nsCOMPtr<nsIRunnable> runnable(aRunnable);
173 return Dispatch(runnable.forget(), aFlags);
176 NS_IMETHODIMP
177 BackgroundEventTarget::DelayedDispatch(already_AddRefed<nsIRunnable> aRunnable,
178 uint32_t) {
179 nsCOMPtr<nsIRunnable> dropRunnable(aRunnable);
180 return NS_ERROR_NOT_IMPLEMENTED;
183 NS_IMETHODIMP
184 BackgroundEventTarget::RegisterShutdownTask(nsITargetShutdownTask* aTask) {
185 return NS_ERROR_NOT_IMPLEMENTED;
188 NS_IMETHODIMP
189 BackgroundEventTarget::UnregisterShutdownTask(nsITargetShutdownTask* aTask) {
190 return NS_ERROR_NOT_IMPLEMENTED;
193 void BackgroundEventTarget::BeginShutdown(
194 nsTArray<RefPtr<ShutdownPromise>>& promises) {
195 auto queues = GetAllTrackedTaskQueues();
196 for (auto& queue : queues) {
197 promises.AppendElement(queue->BeginShutdown());
201 void BackgroundEventTarget::FinishShutdown() {
202 mPool->Shutdown();
203 mIOPool->Shutdown();
206 already_AddRefed<TaskQueue> BackgroundEventTarget::CreateBackgroundTaskQueue(
207 const char* aName) {
208 return TaskQueue::Create(do_AddRef(this), aName).forget();
211 extern "C" {
212 // This uses the C language linkage because it's exposed to Rust
213 // via the xpcom/rust/moz_task crate.
214 bool NS_IsMainThread() { return sTLSIsMainThread.get(); }
217 void NS_SetMainThread() {
218 if (!sTLSIsMainThread.init()) {
219 MOZ_CRASH();
221 sTLSIsMainThread.set(true);
222 MOZ_ASSERT(NS_IsMainThread());
223 // We initialize the SerialEventTargetGuard's TLS here for simplicity as it
224 // needs to be initialized around the same time you would initialize
225 // sTLSIsMainThread.
226 SerialEventTargetGuard::InitTLS();
227 nsThreadPool::InitTLS();
230 #ifdef DEBUG
232 namespace mozilla {
234 void AssertIsOnMainThread() { MOZ_ASSERT(NS_IsMainThread(), "Wrong thread!"); }
236 } // namespace mozilla
238 #endif
240 //-----------------------------------------------------------------------------
242 /* static */
243 void nsThreadManager::ReleaseThread(void* aData) {
244 static_cast<nsThread*>(aData)->Release();
247 // statically allocated instance
248 NS_IMETHODIMP_(MozExternalRefCountType)
249 nsThreadManager::AddRef() { return 2; }
250 NS_IMETHODIMP_(MozExternalRefCountType)
251 nsThreadManager::Release() { return 1; }
252 NS_IMPL_CLASSINFO(nsThreadManager, nullptr,
253 nsIClassInfo::THREADSAFE | nsIClassInfo::SINGLETON,
254 NS_THREADMANAGER_CID)
255 NS_IMPL_QUERY_INTERFACE_CI(nsThreadManager, nsIThreadManager)
256 NS_IMPL_CI_INTERFACE_GETTER(nsThreadManager, nsIThreadManager)
258 //-----------------------------------------------------------------------------
260 /*static*/ nsThreadManager& nsThreadManager::get() {
261 static NeverDestroyed<nsThreadManager> sInstance;
262 return *sInstance;
265 nsThreadManager::nsThreadManager()
266 : mCurThreadIndex(0),
267 mMutex("nsThreadManager::mMutex"),
268 mState(State::eUninit) {}
270 nsThreadManager::~nsThreadManager() = default;
272 nsresult nsThreadManager::Init() {
273 // Child processes need to initialize the thread manager before they
274 // initialize XPCOM in order to set up the crash reporter. This leads to
275 // situations where we get initialized twice.
277 OffTheBooksMutexAutoLock lock(mMutex);
278 if (mState > State::eUninit) {
279 return NS_OK;
283 if (PR_NewThreadPrivateIndex(&mCurThreadIndex, ReleaseThread) == PR_FAILURE) {
284 return NS_ERROR_FAILURE;
287 #ifdef MOZ_CANARY
288 const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NONBLOCK;
289 const mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
290 char* env_var_flag = getenv("MOZ_KILL_CANARIES");
291 sCanaryOutputFD =
292 env_var_flag
293 ? (env_var_flag[0] ? open(env_var_flag, flags, mode) : STDERR_FILENO)
294 : 0;
295 #endif
297 TaskController::Initialize();
299 // Initialize idle handling.
300 nsCOMPtr<nsIIdlePeriod> idlePeriod = new MainThreadIdlePeriod();
301 TaskController::Get()->SetIdleTaskManager(
302 new IdleTaskManager(idlePeriod.forget()));
304 // Create main thread queue that forwards events to TaskController and
305 // construct main thread.
306 UniquePtr<EventQueue> queue = MakeUnique<EventQueue>(true);
308 RefPtr<ThreadEventQueue> synchronizedQueue =
309 new ThreadEventQueue(std::move(queue), true);
311 mMainThread = new nsThread(WrapNotNull(synchronizedQueue),
312 nsThread::MAIN_THREAD, {.stackSize = 0});
314 nsresult rv = mMainThread->InitCurrentThread();
315 if (NS_FAILED(rv)) {
316 mMainThread = nullptr;
317 return rv;
319 #ifdef MOZ_MEMORY
320 jemalloc_set_main_thread();
321 #endif
323 // Init AbstractThread.
324 AbstractThread::InitTLS();
325 AbstractThread::InitMainThread();
327 // Initialize the background event target.
328 RefPtr<BackgroundEventTarget> target(new BackgroundEventTarget());
330 rv = target->Init();
331 NS_ENSURE_SUCCESS(rv, rv);
334 OffTheBooksMutexAutoLock lock(mMutex);
336 mBackgroundEventTarget = std::move(target);
338 mState = State::eActive;
341 return NS_OK;
344 void nsThreadManager::ShutdownNonMainThreads() {
345 MOZ_ASSERT(NS_IsMainThread(), "shutdown not called from main thread");
347 // Empty the main thread event queue before we begin shutting down threads.
348 NS_ProcessPendingEvents(mMainThread);
350 mMainThread->mEvents->RunShutdownTasks();
352 RefPtr<BackgroundEventTarget> backgroundEventTarget;
354 OffTheBooksMutexAutoLock lock(mMutex);
355 MOZ_ASSERT(mState == State::eActive, "shutdown called multiple times");
356 backgroundEventTarget = mBackgroundEventTarget;
359 nsTArray<RefPtr<ShutdownPromise>> promises;
360 backgroundEventTarget->BeginShutdown(promises);
362 bool taskQueuesShutdown = false;
363 // It's fine to capture everything by reference in the Then handler since it
364 // runs before we exit the nested event loop, thanks to the SpinEventLoopUntil
365 // below.
366 ShutdownPromise::All(mMainThread, promises)->Then(mMainThread, __func__, [&] {
367 backgroundEventTarget->FinishShutdown();
368 taskQueuesShutdown = true;
371 // Wait for task queues to shutdown, so we don't shut down the underlying
372 // threads of the background event target in the block below, thereby
373 // preventing the task queues from emptying, preventing the shutdown promises
374 // from resolving, and prevent anything checking `taskQueuesShutdown` from
375 // working.
376 mozilla::SpinEventLoopUntil(
377 "nsThreadManager::Shutdown"_ns, [&]() { return taskQueuesShutdown; },
378 mMainThread);
381 // Prevent new nsThreads from being created, and collect a list of threads
382 // which need to be shut down.
384 // We don't prevent new thread creation until we've shut down background
385 // task queues, to ensure that they are able to start thread pool threads
386 // for shutdown tasks.
387 nsTArray<RefPtr<nsThread>> threadsToShutdown;
389 OffTheBooksMutexAutoLock lock(mMutex);
390 mState = State::eShutdown;
392 for (auto* thread : mThreadList) {
393 if (thread->ShutdownRequired()) {
394 threadsToShutdown.AppendElement(thread);
399 // It's tempting to walk the list of threads here and tell them each to stop
400 // accepting new events, but that could lead to badness if one of those
401 // threads is stuck waiting for a response from another thread. To do it
402 // right, we'd need some way to interrupt the threads.
404 // Instead, we process events on the current thread while waiting for
405 // threads to shutdown. This means that we have to preserve a mostly
406 // functioning world until such time as the threads exit.
408 // As we're going to be waiting for all asynchronous shutdowns below, we
409 // can begin asynchronously shutting down all XPCOM threads here, rather
410 // than shutting each thread down one-at-a-time.
411 for (const auto& thread : threadsToShutdown) {
412 thread->AsyncShutdown();
416 // NB: It's possible that there are events in the queue that want to *start*
417 // an asynchronous shutdown. But we have already started async shutdown of
418 // the threads above, so there's no need to worry about them. We only have to
419 // wait for all in-flight asynchronous thread shutdowns to complete.
420 mMainThread->WaitForAllAsynchronousShutdowns();
422 // There are no more background threads at this point.
425 void nsThreadManager::ShutdownMainThread() {
426 #ifdef DEBUG
428 OffTheBooksMutexAutoLock lock(mMutex);
429 MOZ_ASSERT(mState == State::eShutdown, "Must have called BeginShutdown");
431 #endif
433 // Do NS_ProcessPendingEvents but with special handling to set
434 // mEventsAreDoomed atomically with the removal of the last event. This means
435 // that PutEvent cannot succeed if the event would be left in the main thread
436 // queue after our final call to NS_ProcessPendingEvents.
437 // See comments in `nsThread::ThreadFunc` for a more detailed explanation.
438 while (true) {
439 if (mMainThread->mEvents->ShutdownIfNoPendingEvents()) {
440 break;
442 NS_ProcessPendingEvents(mMainThread);
445 // Normally thread shutdown clears the observer for the thread, but since the
446 // main thread is special we do it manually here after we're sure all events
447 // have been processed.
448 mMainThread->SetObserver(nullptr);
450 OffTheBooksMutexAutoLock lock(mMutex);
451 mBackgroundEventTarget = nullptr;
454 void nsThreadManager::ReleaseMainThread() {
455 #ifdef DEBUG
457 OffTheBooksMutexAutoLock lock(mMutex);
458 MOZ_ASSERT(mState == State::eShutdown, "Must have called BeginShutdown");
459 MOZ_ASSERT(!mBackgroundEventTarget, "Must have called ShutdownMainThread");
461 #endif
462 MOZ_ASSERT(mMainThread);
464 // Release main thread object.
465 mMainThread = nullptr;
467 // Remove the TLS entry for the main thread.
468 PR_SetThreadPrivate(mCurThreadIndex, nullptr);
471 void nsThreadManager::RegisterCurrentThread(nsThread& aThread) {
472 MOZ_ASSERT(aThread.GetPRThread() == PR_GetCurrentThread(), "bad aThread");
474 aThread.AddRef(); // for TLS entry
475 PR_SetThreadPrivate(mCurThreadIndex, &aThread);
477 #ifdef DEBUG
479 OffTheBooksMutexAutoLock lock(mMutex);
480 MOZ_ASSERT(aThread.isInList(),
481 "Thread was not added to the thread list before registering!");
483 #endif
486 void nsThreadManager::UnregisterCurrentThread(nsThread& aThread) {
487 MOZ_ASSERT(aThread.GetPRThread() == PR_GetCurrentThread(), "bad aThread");
489 PR_SetThreadPrivate(mCurThreadIndex, nullptr);
490 // Ref-count balanced via ReleaseThread
493 nsThread* nsThreadManager::CreateCurrentThread(
494 SynchronizedEventQueue* aQueue, nsThread::MainThreadFlag aMainThread) {
495 // Make sure we don't have an nsThread yet.
496 MOZ_ASSERT(!PR_GetThreadPrivate(mCurThreadIndex));
498 if (!AllowNewXPCOMThreads()) {
499 return nullptr;
502 RefPtr<nsThread> thread =
503 new nsThread(WrapNotNull(aQueue), aMainThread, {.stackSize = 0});
504 if (NS_FAILED(thread->InitCurrentThread())) {
505 return nullptr;
508 return thread.get(); // reference held in TLS
511 nsresult nsThreadManager::DispatchToBackgroundThread(nsIRunnable* aEvent,
512 uint32_t aDispatchFlags) {
513 RefPtr<BackgroundEventTarget> backgroundTarget;
515 OffTheBooksMutexAutoLock lock(mMutex);
516 if (!AllowNewXPCOMThreadsLocked() || !mBackgroundEventTarget) {
517 return NS_ERROR_FAILURE;
519 backgroundTarget = mBackgroundEventTarget;
522 return backgroundTarget->Dispatch(aEvent, aDispatchFlags);
525 already_AddRefed<TaskQueue> nsThreadManager::CreateBackgroundTaskQueue(
526 const char* aName) {
527 RefPtr<BackgroundEventTarget> backgroundTarget;
529 OffTheBooksMutexAutoLock lock(mMutex);
530 if (!AllowNewXPCOMThreadsLocked() || !mBackgroundEventTarget) {
531 return nullptr;
533 backgroundTarget = mBackgroundEventTarget;
536 return backgroundTarget->CreateBackgroundTaskQueue(aName);
539 nsThread* nsThreadManager::GetCurrentThread() {
540 // read thread local storage
541 void* data = PR_GetThreadPrivate(mCurThreadIndex);
542 if (data) {
543 return static_cast<nsThread*>(data);
546 // Keep this function working early during startup or late during shutdown on
547 // the main thread.
548 if (!AllowNewXPCOMThreads() || NS_IsMainThread()) {
549 return nullptr;
552 // OK, that's fine. We'll dynamically create one :-)
554 // We assume that if we're implicitly creating a thread here that it doesn't
555 // want an event queue. Any thread which wants an event queue should
556 // explicitly create its nsThread wrapper.
558 // nsThread::InitCurrentThread() will check AllowNewXPCOMThreads, and return
559 // an error if we're too late in shutdown to create new XPCOM threads.
560 RefPtr<nsThread> thread = new nsThread();
561 if (NS_FAILED(thread->InitCurrentThread())) {
562 return nullptr;
565 return thread.get(); // reference held in TLS
568 bool nsThreadManager::IsNSThread() const {
570 OffTheBooksMutexAutoLock lock(mMutex);
571 if (mState == State::eUninit) {
572 return false;
575 if (auto* thread = (nsThread*)PR_GetThreadPrivate(mCurThreadIndex)) {
576 return thread->EventQueue();
578 return false;
581 NS_IMETHODIMP
582 nsThreadManager::NewNamedThread(
583 const nsACString& aName, nsIThreadManager::ThreadCreationOptions aOptions,
584 nsIThread** aResult) {
585 // Note: can be called from arbitrary threads
587 [[maybe_unused]] TimeStamp startTime = TimeStamp::Now();
589 RefPtr<ThreadEventQueue> queue =
590 new ThreadEventQueue(MakeUnique<EventQueue>());
591 RefPtr<nsThread> thr =
592 new nsThread(WrapNotNull(queue), nsThread::NOT_MAIN_THREAD, aOptions);
594 // Note: nsThread::Init() will check AllowNewXPCOMThreads, and return an
595 // error if we're too late in shutdown to create new XPCOM threads. If we
596 // aren't, the thread will be synchronously added to mThreadList.
597 nsresult rv = thr->Init(aName);
598 if (NS_FAILED(rv)) {
599 return rv;
602 PROFILER_MARKER_TEXT(
603 "NewThread", OTHER,
604 MarkerOptions(MarkerStack::Capture(),
605 MarkerTiming::IntervalUntilNowFrom(startTime)),
606 aName);
607 if (!NS_IsMainThread()) {
608 PROFILER_MARKER_TEXT(
609 "NewThread (non-main thread)", OTHER,
610 MarkerOptions(MarkerStack::Capture(), MarkerThreadId::MainThread(),
611 MarkerTiming::IntervalUntilNowFrom(startTime)),
612 aName);
615 thr.forget(aResult);
616 return NS_OK;
619 NS_IMETHODIMP
620 nsThreadManager::GetMainThread(nsIThread** aResult) {
621 // Keep this functioning during Shutdown
622 if (!mMainThread) {
623 if (!NS_IsMainThread()) {
624 NS_WARNING(
625 "Called GetMainThread but there isn't a main thread and "
626 "we're not the main thread.");
628 return NS_ERROR_NOT_INITIALIZED;
630 NS_ADDREF(*aResult = mMainThread);
631 return NS_OK;
634 NS_IMETHODIMP
635 nsThreadManager::GetCurrentThread(nsIThread** aResult) {
636 // Keep this functioning during Shutdown
637 if (!mMainThread) {
638 return NS_ERROR_NOT_INITIALIZED;
640 *aResult = GetCurrentThread();
641 if (!*aResult) {
642 return NS_ERROR_OUT_OF_MEMORY;
644 NS_ADDREF(*aResult);
645 return NS_OK;
648 NS_IMETHODIMP
649 nsThreadManager::SpinEventLoopUntil(const nsACString& aVeryGoodReasonToDoThis,
650 nsINestedEventLoopCondition* aCondition) {
651 return SpinEventLoopUntilInternal(aVeryGoodReasonToDoThis, aCondition,
652 ShutdownPhase::NotInShutdown);
655 NS_IMETHODIMP
656 nsThreadManager::SpinEventLoopUntilOrQuit(
657 const nsACString& aVeryGoodReasonToDoThis,
658 nsINestedEventLoopCondition* aCondition) {
659 return SpinEventLoopUntilInternal(aVeryGoodReasonToDoThis, aCondition,
660 ShutdownPhase::AppShutdownConfirmed);
663 // statics from SpinEventLoopUntil.h
664 AutoNestedEventLoopAnnotation* AutoNestedEventLoopAnnotation::sCurrent =
665 nullptr;
666 StaticMutex AutoNestedEventLoopAnnotation::sStackMutex;
668 // static from SpinEventLoopUntil.h
669 void AutoNestedEventLoopAnnotation::AnnotateXPCOMSpinEventLoopStack(
670 const nsACString& aStack) {
671 if (aStack.Length() > 0) {
672 nsCString prefixedStack(XRE_GetProcessTypeString());
673 prefixedStack += ": "_ns + aStack;
674 CrashReporter::AnnotateCrashReport(
675 CrashReporter::Annotation::XPCOMSpinEventLoopStack, prefixedStack);
676 } else {
677 CrashReporter::AnnotateCrashReport(
678 CrashReporter::Annotation::XPCOMSpinEventLoopStack, ""_ns);
682 nsresult nsThreadManager::SpinEventLoopUntilInternal(
683 const nsACString& aVeryGoodReasonToDoThis,
684 nsINestedEventLoopCondition* aCondition,
685 ShutdownPhase aShutdownPhaseToCheck) {
686 // XXX: We would want to AssertIsOnMainThread(); but that breaks some GTest.
687 nsCOMPtr<nsINestedEventLoopCondition> condition(aCondition);
688 nsresult rv = NS_OK;
690 if (!mozilla::SpinEventLoopUntil(aVeryGoodReasonToDoThis, [&]() -> bool {
691 // Check if an ongoing shutdown reached our limits.
692 if (aShutdownPhaseToCheck > ShutdownPhase::NotInShutdown &&
693 AppShutdown::GetCurrentShutdownPhase() >= aShutdownPhaseToCheck) {
694 return true;
697 bool isDone = false;
698 rv = condition->IsDone(&isDone);
699 // JS failure should be unusual, but we need to stop and propagate
700 // the error back to the caller.
701 if (NS_FAILED(rv)) {
702 return true;
705 return isDone;
706 })) {
707 // We stopped early for some reason, which is unexpected.
708 return NS_ERROR_UNEXPECTED;
711 // If we exited when the condition told us to, we need to return whether
712 // the condition encountered failure when executing.
713 return rv;
716 NS_IMETHODIMP
717 nsThreadManager::SpinEventLoopUntilEmpty() {
718 nsIThread* thread = NS_GetCurrentThread();
720 while (NS_HasPendingEvents(thread)) {
721 (void)NS_ProcessNextEvent(thread, false);
724 return NS_OK;
727 NS_IMETHODIMP
728 nsThreadManager::GetMainThreadEventTarget(nsIEventTarget** aTarget) {
729 nsCOMPtr<nsIEventTarget> target = GetMainThreadSerialEventTarget();
730 target.forget(aTarget);
731 return NS_OK;
734 NS_IMETHODIMP
735 nsThreadManager::DispatchToMainThread(nsIRunnable* aEvent, uint32_t aPriority,
736 uint8_t aArgc) {
737 // Note: C++ callers should instead use NS_DispatchToMainThread.
738 MOZ_ASSERT(NS_IsMainThread());
740 // Keep this functioning during Shutdown
741 if (NS_WARN_IF(!mMainThread)) {
742 return NS_ERROR_NOT_INITIALIZED;
744 // If aPriority wasn't explicitly passed, that means it should be treated as
745 // PRIORITY_NORMAL.
746 if (aArgc > 0 && aPriority != nsIRunnablePriority::PRIORITY_NORMAL) {
747 nsCOMPtr<nsIRunnable> event(aEvent);
748 return mMainThread->DispatchFromScript(
749 new PrioritizableRunnable(event.forget(), aPriority), 0);
751 return mMainThread->DispatchFromScript(aEvent, 0);
754 class AutoMicroTaskWrapperRunnable final : public Runnable {
755 public:
756 explicit AutoMicroTaskWrapperRunnable(nsIRunnable* aEvent)
757 : Runnable("AutoMicroTaskWrapperRunnable"), mEvent(aEvent) {
758 MOZ_ASSERT(aEvent);
761 private:
762 ~AutoMicroTaskWrapperRunnable() = default;
764 NS_IMETHOD Run() override {
765 nsAutoMicroTask mt;
767 return mEvent->Run();
770 RefPtr<nsIRunnable> mEvent;
773 NS_IMETHODIMP
774 nsThreadManager::DispatchToMainThreadWithMicroTask(nsIRunnable* aEvent,
775 uint32_t aPriority,
776 uint8_t aArgc) {
777 RefPtr<AutoMicroTaskWrapperRunnable> runnable =
778 new AutoMicroTaskWrapperRunnable(aEvent);
780 return DispatchToMainThread(runnable, aPriority, aArgc);
783 void nsThreadManager::EnableMainThreadEventPrioritization() {
784 MOZ_ASSERT(NS_IsMainThread());
785 InputTaskManager::Get()->EnableInputEventPrioritization();
788 void nsThreadManager::FlushInputEventPrioritization() {
789 MOZ_ASSERT(NS_IsMainThread());
790 InputTaskManager::Get()->FlushInputEventPrioritization();
793 void nsThreadManager::SuspendInputEventPrioritization() {
794 MOZ_ASSERT(NS_IsMainThread());
795 InputTaskManager::Get()->SuspendInputEventPrioritization();
798 void nsThreadManager::ResumeInputEventPrioritization() {
799 MOZ_ASSERT(NS_IsMainThread());
800 InputTaskManager::Get()->ResumeInputEventPrioritization();
803 // static
804 bool nsThreadManager::MainThreadHasPendingHighPriorityEvents() {
805 MOZ_ASSERT(NS_IsMainThread());
806 bool retVal = false;
807 if (get().mMainThread) {
808 get().mMainThread->HasPendingHighPriorityEvents(&retVal);
810 return retVal;
813 NS_IMETHODIMP
814 nsThreadManager::IdleDispatchToMainThread(nsIRunnable* aEvent,
815 uint32_t aTimeout) {
816 // Note: C++ callers should instead use NS_DispatchToThreadQueue or
817 // NS_DispatchToCurrentThreadQueue.
818 MOZ_ASSERT(NS_IsMainThread());
820 nsCOMPtr<nsIRunnable> event(aEvent);
821 if (aTimeout) {
822 return NS_DispatchToThreadQueue(event.forget(), aTimeout, mMainThread,
823 EventQueuePriority::Idle);
826 return NS_DispatchToThreadQueue(event.forget(), mMainThread,
827 EventQueuePriority::Idle);
830 NS_IMETHODIMP
831 nsThreadManager::DispatchDirectTaskToCurrentThread(nsIRunnable* aEvent) {
832 NS_ENSURE_STATE(aEvent);
833 nsCOMPtr<nsIRunnable> runnable = aEvent;
834 return GetCurrentThread()->DispatchDirectTask(runnable.forget());
837 bool nsThreadManager::AllowNewXPCOMThreads() {
838 mozilla::OffTheBooksMutexAutoLock lock(mMutex);
839 return AllowNewXPCOMThreadsLocked();