Bug 1755481: correct documentation of `nsIClipboard::getData`. r=mccr8
[gecko.git] / xpcom / threads / nsThreadUtils.cpp
blob41cf181a0cd260a3ed689546619a1ce35f32c2bb
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 "nsThreadUtils.h"
9 #include "chrome/common/ipc_message.h" // for IPC::Message
10 #include "LeakRefPtr.h"
11 #include "mozilla/Attributes.h"
12 #include "mozilla/Likely.h"
13 #include "mozilla/TimeStamp.h"
14 #include "nsComponentManagerUtils.h"
15 #include "nsExceptionHandler.h"
16 #include "nsITimer.h"
17 #include "nsTimerImpl.h"
18 #include "prsystem.h"
20 #include "nsThreadManager.h"
21 #include "TaskController.h"
23 #ifdef XP_WIN
24 # include <windows.h>
25 #elif defined(XP_MACOSX)
26 # include <sys/resource.h>
27 #endif
29 #if defined(ANDROID)
30 # include <sys/prctl.h>
31 #endif
33 static mozilla::LazyLogModule sEventDispatchAndRunLog("events");
34 #ifdef LOG1
35 # undef LOG1
36 #endif
37 #define LOG1(args) \
38 MOZ_LOG(sEventDispatchAndRunLog, mozilla::LogLevel::Error, args)
39 #define LOG1_ENABLED() \
40 MOZ_LOG_TEST(sEventDispatchAndRunLog, mozilla::LogLevel::Error)
42 using namespace mozilla;
44 NS_IMPL_ISUPPORTS(TailDispatchingTarget, nsIEventTarget, nsISerialEventTarget)
46 #ifndef XPCOM_GLUE_AVOID_NSPR
48 NS_IMPL_ISUPPORTS(IdlePeriod, nsIIdlePeriod)
50 NS_IMETHODIMP
51 IdlePeriod::GetIdlePeriodHint(TimeStamp* aIdleDeadline) {
52 *aIdleDeadline = TimeStamp();
53 return NS_OK;
56 // NS_IMPL_NAMED_* relies on the mName field, which is not present on
57 // release or beta. Instead, fall back to using "Runnable" for all
58 // runnables.
59 # ifndef MOZ_COLLECTING_RUNNABLE_TELEMETRY
60 NS_IMPL_ISUPPORTS(Runnable, nsIRunnable)
61 # else
62 NS_IMPL_NAMED_ADDREF(Runnable, mName)
63 NS_IMPL_NAMED_RELEASE(Runnable, mName)
64 NS_IMPL_QUERY_INTERFACE(Runnable, nsIRunnable, nsINamed)
65 # endif
67 NS_IMETHODIMP
68 Runnable::Run() {
69 // Do nothing
70 return NS_OK;
73 # ifdef MOZ_COLLECTING_RUNNABLE_TELEMETRY
74 NS_IMETHODIMP
75 Runnable::GetName(nsACString& aName) {
76 if (mName) {
77 aName.AssignASCII(mName);
78 } else {
79 aName.Truncate();
81 return NS_OK;
83 # endif
85 NS_IMPL_ISUPPORTS_INHERITED(DiscardableRunnable, Runnable,
86 nsIDiscardableRunnable)
88 NS_IMPL_ISUPPORTS_INHERITED(CancelableRunnable, DiscardableRunnable,
89 nsICancelableRunnable)
91 void CancelableRunnable::OnDiscard() {
92 // Tasks that implement Cancel() can be safely cleaned up if it turns out
93 // that the task will not run.
94 (void)NS_WARN_IF(NS_FAILED(Cancel()));
97 NS_IMPL_ISUPPORTS_INHERITED(IdleRunnable, DiscardableRunnable, nsIIdleRunnable)
99 NS_IMPL_ISUPPORTS_INHERITED(CancelableIdleRunnable, CancelableRunnable,
100 nsIIdleRunnable)
102 NS_IMPL_ISUPPORTS_INHERITED(PrioritizableRunnable, Runnable,
103 nsIRunnablePriority)
105 PrioritizableRunnable::PrioritizableRunnable(
106 already_AddRefed<nsIRunnable>&& aRunnable, uint32_t aPriority)
107 // Real runnable name is managed by overridding the GetName function.
108 : Runnable("PrioritizableRunnable"),
109 mRunnable(std::move(aRunnable)),
110 mPriority(aPriority) {
111 # if DEBUG
112 nsCOMPtr<nsIRunnablePriority> runnablePrio = do_QueryInterface(mRunnable);
113 MOZ_ASSERT(!runnablePrio);
114 # endif
117 # ifdef MOZ_COLLECTING_RUNNABLE_TELEMETRY
118 NS_IMETHODIMP
119 PrioritizableRunnable::GetName(nsACString& aName) {
120 // Try to get a name from the underlying runnable.
121 nsCOMPtr<nsINamed> named = do_QueryInterface(mRunnable);
122 if (named) {
123 named->GetName(aName);
125 return NS_OK;
127 # endif
129 NS_IMETHODIMP
130 PrioritizableRunnable::Run() {
131 MOZ_RELEASE_ASSERT(NS_IsMainThread());
132 return mRunnable->Run();
135 NS_IMETHODIMP
136 PrioritizableRunnable::GetPriority(uint32_t* aPriority) {
137 *aPriority = mPriority;
138 return NS_OK;
141 already_AddRefed<nsIRunnable> mozilla::CreateRenderBlockingRunnable(
142 already_AddRefed<nsIRunnable>&& aRunnable) {
143 nsCOMPtr<nsIRunnable> runnable = new PrioritizableRunnable(
144 std::move(aRunnable), nsIRunnablePriority::PRIORITY_RENDER_BLOCKING);
145 return runnable.forget();
148 #endif // XPCOM_GLUE_AVOID_NSPR
150 //-----------------------------------------------------------------------------
152 nsresult NS_NewNamedThread(const nsACString& aName, nsIThread** aResult,
153 nsIRunnable* aInitialEvent, uint32_t aStackSize) {
154 nsCOMPtr<nsIRunnable> event = aInitialEvent;
155 return NS_NewNamedThread(aName, aResult, event.forget(), aStackSize);
158 nsresult NS_NewNamedThread(const nsACString& aName, nsIThread** aResult,
159 already_AddRefed<nsIRunnable> aInitialEvent,
160 uint32_t aStackSize) {
161 nsCOMPtr<nsIRunnable> event = std::move(aInitialEvent);
162 nsCOMPtr<nsIThread> thread;
163 nsresult rv = nsThreadManager::get().nsThreadManager::NewNamedThread(
164 aName, aStackSize, getter_AddRefs(thread));
165 if (NS_WARN_IF(NS_FAILED(rv))) {
166 return rv;
169 if (event) {
170 rv = thread->Dispatch(event.forget(), NS_DISPATCH_NORMAL);
171 if (NS_WARN_IF(NS_FAILED(rv))) {
172 return rv;
176 *aResult = nullptr;
177 thread.swap(*aResult);
178 return NS_OK;
181 nsresult NS_GetCurrentThread(nsIThread** aResult) {
182 return nsThreadManager::get().nsThreadManager::GetCurrentThread(aResult);
185 nsresult NS_GetMainThread(nsIThread** aResult) {
186 return nsThreadManager::get().nsThreadManager::GetMainThread(aResult);
189 nsresult NS_DispatchToCurrentThread(already_AddRefed<nsIRunnable>&& aEvent) {
190 nsresult rv;
191 nsCOMPtr<nsIRunnable> event(aEvent);
192 nsIEventTarget* thread = GetCurrentEventTarget();
193 if (!thread) {
194 return NS_ERROR_UNEXPECTED;
196 // To keep us from leaking the runnable if dispatch method fails,
197 // we grab the reference on failures and release it.
198 nsIRunnable* temp = event.get();
199 rv = thread->Dispatch(event.forget(), NS_DISPATCH_NORMAL);
200 if (NS_WARN_IF(NS_FAILED(rv))) {
201 // Dispatch() leaked the reference to the event, but due to caller's
202 // assumptions, we shouldn't leak here. And given we are on the same
203 // thread as the dispatch target, it's mostly safe to do it here.
204 NS_RELEASE(temp);
206 return rv;
209 // It is common to call NS_DispatchToCurrentThread with a newly
210 // allocated runnable with a refcount of zero. To keep us from leaking
211 // the runnable if the dispatch method fails, we take a death grip.
212 nsresult NS_DispatchToCurrentThread(nsIRunnable* aEvent) {
213 nsCOMPtr<nsIRunnable> event(aEvent);
214 return NS_DispatchToCurrentThread(event.forget());
217 nsresult NS_DispatchToMainThread(already_AddRefed<nsIRunnable>&& aEvent,
218 uint32_t aDispatchFlags) {
219 LeakRefPtr<nsIRunnable> event(std::move(aEvent));
220 nsCOMPtr<nsIThread> thread;
221 nsresult rv = NS_GetMainThread(getter_AddRefs(thread));
222 if (NS_WARN_IF(NS_FAILED(rv))) {
223 NS_ASSERTION(false,
224 "Failed NS_DispatchToMainThread() in shutdown; leaking");
225 // NOTE: if you stop leaking here, adjust Promise::MaybeReportRejected(),
226 // which assumes a leak here, or split into leaks and no-leaks versions
227 return rv;
229 return thread->Dispatch(event.take(), aDispatchFlags);
232 // In the case of failure with a newly allocated runnable with a
233 // refcount of zero, we intentionally leak the runnable, because it is
234 // likely that the runnable is being dispatched to the main thread
235 // because it owns main thread only objects, so it is not safe to
236 // release them here.
237 nsresult NS_DispatchToMainThread(nsIRunnable* aEvent, uint32_t aDispatchFlags) {
238 nsCOMPtr<nsIRunnable> event(aEvent);
239 return NS_DispatchToMainThread(event.forget(), aDispatchFlags);
242 nsresult NS_DelayedDispatchToCurrentThread(
243 already_AddRefed<nsIRunnable>&& aEvent, uint32_t aDelayMs) {
244 nsCOMPtr<nsIRunnable> event(aEvent);
245 nsIEventTarget* thread = GetCurrentEventTarget();
246 if (!thread) {
247 return NS_ERROR_UNEXPECTED;
250 return thread->DelayedDispatch(event.forget(), aDelayMs);
253 nsresult NS_DispatchToThreadQueue(already_AddRefed<nsIRunnable>&& aEvent,
254 nsIThread* aThread,
255 EventQueuePriority aQueue) {
256 nsresult rv;
257 nsCOMPtr<nsIRunnable> event(aEvent);
258 NS_ENSURE_TRUE(event, NS_ERROR_INVALID_ARG);
259 if (!aThread) {
260 return NS_ERROR_UNEXPECTED;
262 // To keep us from leaking the runnable if dispatch method fails,
263 // we grab the reference on failures and release it.
264 nsIRunnable* temp = event.get();
265 rv = aThread->DispatchToQueue(event.forget(), aQueue);
266 if (NS_WARN_IF(NS_FAILED(rv))) {
267 // Dispatch() leaked the reference to the event, but due to caller's
268 // assumptions, we shouldn't leak here. And given we are on the same
269 // thread as the dispatch target, it's mostly safe to do it here.
270 NS_RELEASE(temp);
273 return rv;
276 nsresult NS_DispatchToCurrentThreadQueue(already_AddRefed<nsIRunnable>&& aEvent,
277 EventQueuePriority aQueue) {
278 return NS_DispatchToThreadQueue(std::move(aEvent), NS_GetCurrentThread(),
279 aQueue);
282 extern nsresult NS_DispatchToMainThreadQueue(
283 already_AddRefed<nsIRunnable>&& aEvent, EventQueuePriority aQueue) {
284 nsCOMPtr<nsIThread> mainThread;
285 nsresult rv = NS_GetMainThread(getter_AddRefs(mainThread));
286 if (NS_SUCCEEDED(rv)) {
287 return NS_DispatchToThreadQueue(std::move(aEvent), mainThread, aQueue);
289 return rv;
292 class IdleRunnableWrapper final : public Runnable,
293 public nsIDiscardableRunnable,
294 public nsIIdleRunnable {
295 public:
296 explicit IdleRunnableWrapper(already_AddRefed<nsIRunnable>&& aEvent)
297 : Runnable("IdleRunnableWrapper"),
298 mRunnable(std::move(aEvent)),
299 mDiscardable(do_QueryInterface(mRunnable)) {}
301 NS_DECL_ISUPPORTS_INHERITED
303 NS_IMETHOD Run() override {
304 if (!mRunnable) {
305 return NS_OK;
307 CancelTimer();
308 // Don't clear mDiscardable because that would cause QueryInterface to
309 // change behavior during the lifetime of an instance.
310 nsCOMPtr<nsIRunnable> runnable = std::move(mRunnable);
311 return runnable->Run();
314 // nsIDiscardableRunnable
315 void OnDiscard() override {
316 if (!mRunnable) {
317 // Run() was already called from TimedOut().
318 return;
320 mDiscardable->OnDiscard();
321 mRunnable = nullptr;
324 static void TimedOut(nsITimer* aTimer, void* aClosure) {
325 RefPtr<IdleRunnableWrapper> runnable =
326 static_cast<IdleRunnableWrapper*>(aClosure);
327 LogRunnable::Run log(runnable);
328 runnable->Run();
329 runnable = nullptr;
332 void SetTimer(uint32_t aDelay, nsIEventTarget* aTarget) override {
333 MOZ_ASSERT(aTarget);
334 MOZ_ASSERT(!mTimer);
335 NS_NewTimerWithFuncCallback(getter_AddRefs(mTimer), TimedOut, this, aDelay,
336 nsITimer::TYPE_ONE_SHOT,
337 "IdleRunnableWrapper::SetTimer", aTarget);
340 #ifdef MOZ_COLLECTING_RUNNABLE_TELEMETRY
341 NS_IMETHOD GetName(nsACString& aName) override {
342 aName.AssignLiteral("IdleRunnableWrapper");
343 if (nsCOMPtr<nsINamed> named = do_QueryInterface(mRunnable)) {
344 nsAutoCString name;
345 named->GetName(name);
346 if (!name.IsEmpty()) {
347 aName.AppendLiteral(" for ");
348 aName.Append(name);
351 return NS_OK;
353 #endif
355 private:
356 ~IdleRunnableWrapper() { CancelTimer(); }
358 void CancelTimer() {
359 if (mTimer) {
360 mTimer->Cancel();
364 nsCOMPtr<nsITimer> mTimer;
365 nsCOMPtr<nsIRunnable> mRunnable;
366 nsCOMPtr<nsIDiscardableRunnable> mDiscardable;
369 NS_IMPL_ADDREF_INHERITED(IdleRunnableWrapper, Runnable)
370 NS_IMPL_RELEASE_INHERITED(IdleRunnableWrapper, Runnable)
372 NS_INTERFACE_MAP_BEGIN(IdleRunnableWrapper)
373 NS_INTERFACE_MAP_ENTRY(nsIIdleRunnable)
374 NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIDiscardableRunnable, mDiscardable)
375 NS_INTERFACE_MAP_END_INHERITING(Runnable)
377 extern nsresult NS_DispatchToThreadQueue(already_AddRefed<nsIRunnable>&& aEvent,
378 uint32_t aTimeout, nsIThread* aThread,
379 EventQueuePriority aQueue) {
380 nsCOMPtr<nsIRunnable> event(std::move(aEvent));
381 NS_ENSURE_TRUE(event, NS_ERROR_INVALID_ARG);
382 MOZ_ASSERT(aQueue == EventQueuePriority::Idle ||
383 aQueue == EventQueuePriority::DeferredTimers);
385 // XXX Using current thread for now as the nsIEventTarget.
386 nsIEventTarget* target = mozilla::GetCurrentEventTarget();
387 if (!target) {
388 return NS_ERROR_UNEXPECTED;
391 nsCOMPtr<nsIIdleRunnable> idleEvent = do_QueryInterface(event);
393 if (!idleEvent) {
394 idleEvent = new IdleRunnableWrapper(event.forget());
395 event = do_QueryInterface(idleEvent);
396 MOZ_DIAGNOSTIC_ASSERT(event);
398 idleEvent->SetTimer(aTimeout, target);
400 nsresult rv = NS_DispatchToThreadQueue(event.forget(), aThread, aQueue);
401 if (NS_SUCCEEDED(rv)) {
402 // This is intended to bind with the "DISP" log made from inside
403 // NS_DispatchToThreadQueue for the `event`. There is no possibly to inject
404 // another "DISP" for a different event on this thread.
405 LOG1(("TIMEOUT %u", aTimeout));
408 return rv;
411 extern nsresult NS_DispatchToCurrentThreadQueue(
412 already_AddRefed<nsIRunnable>&& aEvent, uint32_t aTimeout,
413 EventQueuePriority aQueue) {
414 return NS_DispatchToThreadQueue(std::move(aEvent), aTimeout,
415 NS_GetCurrentThread(), aQueue);
418 #ifndef XPCOM_GLUE_AVOID_NSPR
419 nsresult NS_ProcessPendingEvents(nsIThread* aThread, PRIntervalTime aTimeout) {
420 nsresult rv = NS_OK;
422 if (!aThread) {
423 aThread = NS_GetCurrentThread();
424 if (NS_WARN_IF(!aThread)) {
425 return NS_ERROR_UNEXPECTED;
429 PRIntervalTime start = PR_IntervalNow();
430 for (;;) {
431 bool processedEvent;
432 rv = aThread->ProcessNextEvent(false, &processedEvent);
433 if (NS_FAILED(rv) || !processedEvent) {
434 break;
436 if (PR_IntervalNow() - start > aTimeout) {
437 break;
440 return rv;
442 #endif // XPCOM_GLUE_AVOID_NSPR
444 inline bool hasPendingEvents(nsIThread* aThread) {
445 bool val;
446 return NS_SUCCEEDED(aThread->HasPendingEvents(&val)) && val;
449 bool NS_HasPendingEvents(nsIThread* aThread) {
450 if (!aThread) {
451 aThread = NS_GetCurrentThread();
452 if (NS_WARN_IF(!aThread)) {
453 return false;
456 return hasPendingEvents(aThread);
459 bool NS_ProcessNextEvent(nsIThread* aThread, bool aMayWait) {
460 if (!aThread) {
461 aThread = NS_GetCurrentThread();
462 if (NS_WARN_IF(!aThread)) {
463 return false;
466 bool val;
467 return NS_SUCCEEDED(aThread->ProcessNextEvent(aMayWait, &val)) && val;
470 void NS_SetCurrentThreadName(const char* aName) {
471 #if defined(ANDROID)
472 // Workaround for Bug 1541216 - PR_SetCurrentThreadName() Fails to set the
473 // thread name on Android.
474 prctl(PR_SET_NAME, reinterpret_cast<unsigned long>(aName));
475 #else
476 PR_SetCurrentThreadName(aName);
477 #endif
478 if (nsThreadManager::get().IsNSThread()) {
479 nsThread* thread = nsThreadManager::get().GetCurrentThread();
480 thread->SetThreadNameInternal(nsDependentCString(aName));
482 CrashReporter::SetCurrentThreadName(aName);
485 nsIThread* NS_GetCurrentThread() {
486 return nsThreadManager::get().GetCurrentThread();
489 nsIThread* NS_GetCurrentThreadNoCreate() {
490 if (nsThreadManager::get().IsNSThread()) {
491 return NS_GetCurrentThread();
493 return nullptr;
496 // nsThreadPoolNaming
497 nsCString nsThreadPoolNaming::GetNextThreadName(const nsACString& aPoolName) {
498 nsCString name(aPoolName);
499 name.AppendLiteral(" #");
500 name.AppendInt(++mCounter, 10); // The counter is declared as atomic
501 return name;
504 nsresult NS_DispatchBackgroundTask(already_AddRefed<nsIRunnable> aEvent,
505 uint32_t aDispatchFlags) {
506 nsCOMPtr<nsIRunnable> event(aEvent);
507 return nsThreadManager::get().DispatchToBackgroundThread(event,
508 aDispatchFlags);
511 // nsAutoLowPriorityIO
512 nsAutoLowPriorityIO::nsAutoLowPriorityIO() {
513 #if defined(XP_WIN)
514 lowIOPrioritySet =
515 SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN);
516 #elif defined(XP_MACOSX)
517 oldPriority = getiopolicy_np(IOPOL_TYPE_DISK, IOPOL_SCOPE_THREAD);
518 lowIOPrioritySet =
519 oldPriority != -1 &&
520 setiopolicy_np(IOPOL_TYPE_DISK, IOPOL_SCOPE_THREAD, IOPOL_THROTTLE) != -1;
521 #else
522 lowIOPrioritySet = false;
523 #endif
526 nsAutoLowPriorityIO::~nsAutoLowPriorityIO() {
527 #if defined(XP_WIN)
528 if (MOZ_LIKELY(lowIOPrioritySet)) {
529 // On Windows the old thread priority is automatically restored
530 SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_END);
532 #elif defined(XP_MACOSX)
533 if (MOZ_LIKELY(lowIOPrioritySet)) {
534 setiopolicy_np(IOPOL_TYPE_DISK, IOPOL_SCOPE_THREAD, oldPriority);
536 #endif
539 namespace mozilla {
541 nsIEventTarget* GetCurrentEventTarget() {
542 nsCOMPtr<nsIThread> thread;
543 nsresult rv = NS_GetCurrentThread(getter_AddRefs(thread));
544 if (NS_FAILED(rv)) {
545 return nullptr;
548 return thread->EventTarget();
551 nsIEventTarget* GetMainThreadEventTarget() {
552 return GetMainThreadSerialEventTarget();
555 nsISerialEventTarget* GetCurrentSerialEventTarget() {
556 if (nsISerialEventTarget* current =
557 SerialEventTargetGuard::GetCurrentSerialEventTarget()) {
558 return current;
561 nsCOMPtr<nsIThread> thread;
562 nsresult rv = NS_GetCurrentThread(getter_AddRefs(thread));
563 if (NS_FAILED(rv)) {
564 return nullptr;
567 return thread->SerialEventTarget();
570 nsISerialEventTarget* GetMainThreadSerialEventTarget() {
571 return static_cast<nsThread*>(nsThreadManager::get().GetMainThreadWeak());
574 size_t GetNumberOfProcessors() {
575 #if defined(XP_LINUX) && defined(MOZ_SANDBOX)
576 static const PRInt32 procs = PR_GetNumberOfProcessors();
577 #else
578 PRInt32 procs = PR_GetNumberOfProcessors();
579 #endif
580 MOZ_ASSERT(procs > 0);
581 return static_cast<size_t>(procs);
584 template <typename T>
585 void LogTaskBase<T>::LogDispatch(T* aEvent) {
586 LOG1(("DISP %p", aEvent));
588 template <typename T>
589 void LogTaskBase<T>::LogDispatch(T* aEvent, void* aContext) {
590 LOG1(("DISP %p (%p)", aEvent, aContext));
593 template <>
594 void LogTaskBase<IPC::Message>::LogDispatchWithPid(IPC::Message* aEvent,
595 int32_t aPid) {
596 if (aEvent->seqno() && aPid > 0) {
597 LOG1(("SEND %p %d %d", aEvent, aEvent->seqno(), aPid));
601 template <typename T>
602 LogTaskBase<T>::Run::Run(T* aEvent, bool aWillRunAgain)
603 : mWillRunAgain(aWillRunAgain) {
604 // Logging address of this RAII so that we can use it to identify the DONE log
605 // while not keeping any ref to the event that could be invalid at the dtor
606 // time.
607 LOG1(("EXEC %p %p", aEvent, this));
609 template <typename T>
610 LogTaskBase<T>::Run::Run(T* aEvent, void* aContext, bool aWillRunAgain)
611 : mWillRunAgain(aWillRunAgain) {
612 LOG1(("EXEC %p (%p) %p", aEvent, aContext, this));
615 template <>
616 LogTaskBase<nsIRunnable>::Run::Run(nsIRunnable* aEvent, bool aWillRunAgain)
617 : mWillRunAgain(aWillRunAgain) {
618 if (!LOG1_ENABLED()) {
619 return;
622 nsCOMPtr<nsINamed> named(do_QueryInterface(aEvent));
623 if (!named) {
624 LOG1(("EXEC %p %p", aEvent, this));
625 return;
628 nsAutoCString name;
629 named->GetName(name);
630 LOG1(("EXEC %p %p [%s]", aEvent, this, name.BeginReading()));
633 template <>
634 LogTaskBase<Task>::Run::Run(Task* aTask, bool aWillRunAgain)
635 : mWillRunAgain(aWillRunAgain) {
636 if (!LOG1_ENABLED()) {
637 return;
640 nsAutoCString name;
641 if (!aTask->GetName(name)) {
642 LOG1(("EXEC %p %p", aTask, this));
643 return;
646 LOG1(("EXEC %p %p [%s]", aTask, this, name.BeginReading()));
649 template <>
650 LogTaskBase<IPC::Message>::Run::Run(IPC::Message* aMessage, bool aWillRunAgain)
651 : mWillRunAgain(aWillRunAgain) {
652 LOG1(("RECV %p %p %d [%s]", aMessage, this, aMessage->seqno(),
653 aMessage->name()));
656 template <>
657 LogTaskBase<nsTimerImpl>::Run::Run(nsTimerImpl* aEvent, bool aWillRunAgain)
658 : mWillRunAgain(aWillRunAgain) {
659 // The name of the timer will be logged when running it on the target thread.
660 // Logging it here (on the `Timer` thread) would be redundant.
661 LOG1(("EXEC %p %p [nsTimerImpl]", aEvent, this));
664 template <typename T>
665 LogTaskBase<T>::Run::~Run() {
666 LOG1((mWillRunAgain ? "INTERRUPTED %p" : "DONE %p", this));
669 template class LogTaskBase<nsIRunnable>;
670 template class LogTaskBase<MicroTaskRunnable>;
671 template class LogTaskBase<IPC::Message>;
672 template class LogTaskBase<nsTimerImpl>;
673 template class LogTaskBase<Task>;
674 template class LogTaskBase<PresShell>;
675 template class LogTaskBase<dom::FrameRequestCallback>;
677 MOZ_THREAD_LOCAL(nsISerialEventTarget*)
678 SerialEventTargetGuard::sCurrentThreadTLS;
679 void SerialEventTargetGuard::InitTLS() {
680 MOZ_ASSERT(NS_IsMainThread());
681 if (!sCurrentThreadTLS.init()) {
682 MOZ_CRASH();
686 } // namespace mozilla
688 bool nsIEventTarget::IsOnCurrentThread() {
689 if (mThread) {
690 return mThread == PR_GetCurrentThread();
692 return IsOnCurrentThreadInfallible();
695 extern "C" {
696 // These functions use the C language linkage because they're exposed to Rust
697 // via the xpcom/rust/moz_task crate, which wraps them in safe Rust functions
698 // that enable Rust code to get/create threads and dispatch runnables on them.
700 nsresult NS_GetCurrentThreadRust(nsIThread** aResult) {
701 return NS_GetCurrentThread(aResult);
704 nsresult NS_GetMainThreadRust(nsIThread** aResult) {
705 return NS_GetMainThread(aResult);
708 // NS_NewNamedThread's aStackSize parameter has the default argument
709 // nsIThreadManager::DEFAULT_STACK_SIZE, but we can't omit default arguments
710 // when calling a C++ function from Rust, and we can't access
711 // nsIThreadManager::DEFAULT_STACK_SIZE in Rust to pass it explicitly,
712 // since it is defined in a %{C++ ... %} block within nsIThreadManager.idl.
713 // So we indirect through this function.
714 nsresult NS_NewNamedThreadWithDefaultStackSize(const nsACString& aName,
715 nsIThread** aResult,
716 nsIRunnable* aEvent) {
717 return NS_NewNamedThread(aName, aResult, aEvent);
720 bool NS_IsOnCurrentThread(nsIEventTarget* aTarget) {
721 return aTarget->IsOnCurrentThread();
724 nsresult NS_DispatchBackgroundTask(nsIRunnable* aEvent,
725 uint32_t aDispatchFlags) {
726 return nsThreadManager::get().DispatchToBackgroundThread(aEvent,
727 aDispatchFlags);
730 nsresult NS_CreateBackgroundTaskQueue(const char* aName,
731 nsISerialEventTarget** aTarget) {
732 nsCOMPtr<nsISerialEventTarget> target =
733 nsThreadManager::get().CreateBackgroundTaskQueue(aName);
734 if (!target) {
735 return NS_ERROR_FAILURE;
738 target.forget(aTarget);
739 return NS_OK;
742 } // extern "C"