Bug 1882593 [wpt PR 44836] - Add test for unknown, invalid ancillary chunk which...
[gecko.git] / xpcom / threads / nsThreadUtils.h
blob72041da295abcf89980108db96be349d2ebdc42e
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 #ifndef nsThreadUtils_h__
8 #define nsThreadUtils_h__
10 #include <type_traits>
11 #include <tuple>
12 #include <utility>
14 #include "MainThreadUtils.h"
15 #include "mozilla/EventQueue.h"
16 #include "mozilla/AbstractThread.h"
17 #include "mozilla/Atomics.h"
18 #include "mozilla/Likely.h"
19 #include "mozilla/Maybe.h"
20 #include "mozilla/ThreadLocal.h"
21 #include "mozilla/TimeStamp.h"
23 #include "nsCOMPtr.h"
24 #include "nsICancelableRunnable.h"
25 #include "nsIDiscardableRunnable.h"
26 #include "nsIIdlePeriod.h"
27 #include "nsIIdleRunnable.h"
28 #include "nsINamed.h"
29 #include "nsIRunnable.h"
30 #include "nsIThreadManager.h"
31 #include "nsITimer.h"
32 #include "nsString.h"
33 #include "prinrval.h"
34 #include "prthread.h"
36 class MessageLoop;
37 class nsIThread;
39 //-----------------------------------------------------------------------------
40 // These methods are alternatives to the methods on nsIThreadManager, provided
41 // for convenience.
43 /**
44 * Create a new thread, and optionally provide an initial event for the thread.
46 * @param aName
47 * The name of the thread.
48 * @param aResult
49 * The resulting nsIThread object.
50 * @param aInitialEvent
51 * The initial event to run on this thread. This parameter may be null.
52 * @param aOptions
53 * Options used to configure thread creation.
54 * Options are documented in nsIThreadManager.idl.
56 * @returns NS_ERROR_INVALID_ARG
57 * Indicates that the given name is not unique.
60 extern nsresult NS_NewNamedThread(
61 const nsACString& aName, nsIThread** aResult,
62 nsIRunnable* aInitialEvent = nullptr,
63 nsIThreadManager::ThreadCreationOptions aOptions = {});
65 extern nsresult NS_NewNamedThread(
66 const nsACString& aName, nsIThread** aResult,
67 already_AddRefed<nsIRunnable> aInitialEvent,
68 nsIThreadManager::ThreadCreationOptions aOptions = {});
70 template <size_t LEN>
71 inline nsresult NS_NewNamedThread(
72 const char (&aName)[LEN], nsIThread** aResult,
73 already_AddRefed<nsIRunnable> aInitialEvent,
74 nsIThreadManager::ThreadCreationOptions aOptions = {}) {
75 static_assert(LEN <= 16, "Thread name must be no more than 16 characters");
76 return NS_NewNamedThread(nsDependentCString(aName, LEN - 1), aResult,
77 std::move(aInitialEvent), aOptions);
80 template <size_t LEN>
81 inline nsresult NS_NewNamedThread(
82 const char (&aName)[LEN], nsIThread** aResult,
83 nsIRunnable* aInitialEvent = nullptr,
84 nsIThreadManager::ThreadCreationOptions aOptions = {}) {
85 nsCOMPtr<nsIRunnable> event = aInitialEvent;
86 static_assert(LEN <= 16, "Thread name must be no more than 16 characters");
87 return NS_NewNamedThread(nsDependentCString(aName, LEN - 1), aResult,
88 event.forget(), aOptions);
91 /**
92 * Get a reference to the current thread, creating it if it does not exist yet.
94 * @param aResult
95 * The resulting nsIThread object.
97 extern nsresult NS_GetCurrentThread(nsIThread** aResult);
99 /**
100 * Dispatch the given event to the current thread.
102 * @param aEvent
103 * The event to dispatch.
105 * @returns NS_ERROR_INVALID_ARG
106 * If event is null.
108 extern nsresult NS_DispatchToCurrentThread(nsIRunnable* aEvent);
109 extern nsresult NS_DispatchToCurrentThread(
110 already_AddRefed<nsIRunnable>&& aEvent);
113 * Dispatch the given event to the main thread.
115 * @param aEvent
116 * The event to dispatch.
117 * @param aDispatchFlags
118 * The flags to pass to the main thread's dispatch method.
120 * @returns NS_ERROR_INVALID_ARG
121 * If event is null.
123 extern nsresult NS_DispatchToMainThread(
124 nsIRunnable* aEvent, uint32_t aDispatchFlags = NS_DISPATCH_NORMAL);
125 extern nsresult NS_DispatchToMainThread(
126 already_AddRefed<nsIRunnable>&& aEvent,
127 uint32_t aDispatchFlags = NS_DISPATCH_NORMAL);
129 extern nsresult NS_DelayedDispatchToCurrentThread(
130 already_AddRefed<nsIRunnable>&& aEvent, uint32_t aDelayMs);
133 * Dispatch the given event to the specified queue of the current thread.
135 * @param aEvent The event to dispatch.
136 * @param aQueue The event queue for the thread to use
138 * @returns NS_ERROR_INVALID_ARG
139 * If event is null.
140 * @returns NS_ERROR_UNEXPECTED
141 * If the thread is shutting down.
143 extern nsresult NS_DispatchToCurrentThreadQueue(
144 already_AddRefed<nsIRunnable>&& aEvent, mozilla::EventQueuePriority aQueue);
147 * Dispatch the given event to the specified queue of the main thread.
149 * @param aEvent The event to dispatch.
150 * @param aQueue The event queue for the thread to use
152 * @returns NS_ERROR_INVALID_ARG
153 * If event is null.
154 * @returns NS_ERROR_UNEXPECTED
155 * If the thread is shutting down.
157 extern nsresult NS_DispatchToMainThreadQueue(
158 already_AddRefed<nsIRunnable>&& aEvent, mozilla::EventQueuePriority aQueue);
161 * Dispatch the given event to an idle queue of the current thread.
163 * @param aEvent The event to dispatch. If the event implements
164 * nsIIdleRunnable, it will receive a call on
165 * nsIIdleRunnable::SetTimer when dispatched, with the value of
166 * aTimeout.
168 * @param aTimeout The time in milliseconds until the event should be
169 * moved from an idle queue to the regular queue, if it hasn't been
170 * executed. If aEvent is also an nsIIdleRunnable, it is expected
171 * that it should handle the timeout itself, after a call to
172 * nsIIdleRunnable::SetTimer.
174 * @param aQueue
175 * The event queue for the thread to use. Must be an idle queue
176 * (Idle or DeferredTimers)
178 * @returns NS_ERROR_INVALID_ARG
179 * If event is null.
180 * @returns NS_ERROR_UNEXPECTED
181 * If the thread is shutting down.
183 extern nsresult NS_DispatchToCurrentThreadQueue(
184 already_AddRefed<nsIRunnable>&& aEvent, uint32_t aTimeout,
185 mozilla::EventQueuePriority aQueue);
188 * Dispatch the given event to a queue of a thread.
190 * @param aEvent The event to dispatch.
191 * @param aThread The target thread for the dispatch.
192 * @param aQueue The event queue for the thread to use.
194 * @returns NS_ERROR_INVALID_ARG
195 * If event is null.
196 * @returns NS_ERROR_UNEXPECTED
197 * If the thread is shutting down.
199 extern nsresult NS_DispatchToThreadQueue(already_AddRefed<nsIRunnable>&& aEvent,
200 nsIThread* aThread,
201 mozilla::EventQueuePriority aQueue);
204 * Dispatch the given event to an idle queue of a thread.
206 * @param aEvent The event to dispatch. If the event implements
207 * nsIIdleRunnable, it will receive a call on
208 * nsIIdleRunnable::SetTimer when dispatched, with the value of
209 * aTimeout.
211 * @param aTimeout The time in milliseconds until the event should be
212 * moved from an idle queue to the regular queue, if it hasn't been
213 * executed. If aEvent is also an nsIIdleRunnable, it is expected
214 * that it should handle the timeout itself, after a call to
215 * nsIIdleRunnable::SetTimer.
217 * @param aThread The target thread for the dispatch.
219 * @param aQueue
220 * The event queue for the thread to use. Must be an idle queue
221 * (Idle or DeferredTimers)
223 * @returns NS_ERROR_INVALID_ARG
224 * If event is null.
225 * @returns NS_ERROR_UNEXPECTED
226 * If the thread is shutting down.
228 extern nsresult NS_DispatchToThreadQueue(already_AddRefed<nsIRunnable>&& aEvent,
229 uint32_t aTimeout, nsIThread* aThread,
230 mozilla::EventQueuePriority aQueue);
232 #ifndef XPCOM_GLUE_AVOID_NSPR
234 * Process all pending events for the given thread before returning. This
235 * method simply calls ProcessNextEvent on the thread while HasPendingEvents
236 * continues to return true and the time spent in NS_ProcessPendingEvents
237 * does not exceed the given timeout value.
239 * @param aThread
240 * The thread object for which to process pending events. If null, then
241 * events will be processed for the current thread.
242 * @param aTimeout
243 * The maximum number of milliseconds to spend processing pending events.
244 * Events are not pre-empted to honor this timeout. Rather, the timeout
245 * value is simply used to determine whether or not to process another event.
246 * Pass PR_INTERVAL_NO_TIMEOUT to specify no timeout.
248 extern nsresult NS_ProcessPendingEvents(
249 nsIThread* aThread, PRIntervalTime aTimeout = PR_INTERVAL_NO_TIMEOUT);
250 #endif
253 * Shortcut for nsIThread::HasPendingEvents.
255 * It is an error to call this function when the given thread is not the
256 * current thread. This function will return false if called from some
257 * other thread.
259 * @param aThread
260 * The current thread or null.
262 * @returns
263 * A boolean value that if "true" indicates that there are pending events
264 * in the current thread's event queue.
266 extern bool NS_HasPendingEvents(nsIThread* aThread = nullptr);
269 * Shortcut for nsIThread::ProcessNextEvent.
271 * It is an error to call this function when the given thread is not the
272 * current thread. This function will simply return false if called
273 * from some other thread.
275 * @param aThread
276 * The current thread or null.
277 * @param aMayWait
278 * A boolean parameter that if "true" indicates that the method may block
279 * the calling thread to wait for a pending event.
281 * @returns
282 * A boolean value that if "true" indicates that an event from the current
283 * thread's event queue was processed.
285 extern bool NS_ProcessNextEvent(nsIThread* aThread = nullptr,
286 bool aMayWait = true);
289 * Returns true if we're in the compositor thread.
291 * We declare this here because the headers required to invoke
292 * CompositorThreadHolder::IsInCompositorThread() also pull in a bunch of system
293 * headers that #define various tokens in a way that can break the build.
295 extern bool NS_IsInCompositorThread();
297 extern bool NS_IsInCanvasThreadOrWorker();
299 extern bool NS_IsInVRThread();
301 //-----------------------------------------------------------------------------
302 // Helpers that work with nsCOMPtr:
304 inline already_AddRefed<nsIThread> do_GetCurrentThread() {
305 nsIThread* thread = nullptr;
306 NS_GetCurrentThread(&thread);
307 return already_AddRefed<nsIThread>(thread);
310 inline already_AddRefed<nsIThread> do_GetMainThread() {
311 nsIThread* thread = nullptr;
312 NS_GetMainThread(&thread);
313 return already_AddRefed<nsIThread>(thread);
316 //-----------------------------------------------------------------------------
318 // Fast access to the current thread. Will create an nsIThread if one does not
319 // exist already! Do not release the returned pointer! If you want to use this
320 // pointer from some other thread, then you will need to AddRef it. Otherwise,
321 // you should only consider this pointer valid from code running on the current
322 // thread.
323 extern nsIThread* NS_GetCurrentThread();
325 // Exactly the same as NS_GetCurrentThread, except it will not create an
326 // nsThread if one does not exist yet. This is useful in cases where you have
327 // code that runs on threads that may or may not not be driven by an nsThread
328 // event loop, and wish to avoid inadvertently creating a superfluous nsThread.
329 extern nsIThread* NS_GetCurrentThreadNoCreate();
332 * Set the name of the current thread. Prefer this function over
333 * PR_SetCurrentThreadName() if possible. The name will also be included in the
334 * crash report.
336 * @param aName
337 * Name of the thread. A C language null-terminated string.
339 extern void NS_SetCurrentThreadName(const char* aName);
341 //-----------------------------------------------------------------------------
343 #ifndef XPCOM_GLUE_AVOID_NSPR
345 namespace mozilla {
347 // This class is designed to be subclassed.
348 class IdlePeriod : public nsIIdlePeriod {
349 public:
350 NS_DECL_THREADSAFE_ISUPPORTS
351 NS_DECL_NSIIDLEPERIOD
353 IdlePeriod() = default;
355 protected:
356 virtual ~IdlePeriod() = default;
358 private:
359 IdlePeriod(const IdlePeriod&) = delete;
360 IdlePeriod& operator=(const IdlePeriod&) = delete;
361 IdlePeriod& operator=(const IdlePeriod&&) = delete;
364 // Cancelable runnable methods implement nsICancelableRunnable, and
365 // Idle and IdleWithTimer also nsIIdleRunnable.
366 enum class RunnableKind { Standard, Cancelable, Idle, IdleWithTimer };
368 // Implementing nsINamed on Runnable bloats vtables for the hundreds of
369 // Runnable subclasses that we have, so we want to avoid that overhead
370 // when we're not using nsINamed for anything.
371 # ifndef RELEASE_OR_BETA
372 # define MOZ_COLLECTING_RUNNABLE_TELEMETRY
373 # endif
375 // This class is designed to be subclassed.
376 class Runnable : public nsIRunnable
377 # ifdef MOZ_COLLECTING_RUNNABLE_TELEMETRY
379 public nsINamed
380 # endif
382 public:
383 NS_DECL_THREADSAFE_ISUPPORTS
384 NS_DECL_NSIRUNNABLE
385 # ifdef MOZ_COLLECTING_RUNNABLE_TELEMETRY
386 NS_DECL_NSINAMED
387 # endif
389 Runnable() = delete;
391 # ifdef MOZ_COLLECTING_RUNNABLE_TELEMETRY
392 explicit Runnable(const char* aName) : mName(aName) {}
393 # else
394 explicit Runnable(const char* aName) {}
395 # endif
397 protected:
398 virtual ~Runnable() = default;
400 # ifdef MOZ_COLLECTING_RUNNABLE_TELEMETRY
401 const char* mName = nullptr;
402 # endif
404 private:
405 Runnable(const Runnable&) = delete;
406 Runnable& operator=(const Runnable&) = delete;
407 Runnable& operator=(const Runnable&&) = delete;
410 // This is a base class for tasks that might not be run, such as those that may
411 // be dispatched to workers.
412 // The owner of an event target will call either Run() or OnDiscard()
413 // exactly once.
414 // Derived classes should override Run(). An OnDiscard() override may
415 // provide cleanup when Run() will not be called.
416 class DiscardableRunnable : public Runnable, public nsIDiscardableRunnable {
417 public:
418 NS_DECL_ISUPPORTS_INHERITED
419 // nsIDiscardableRunnable
420 void OnDiscard() override {}
422 DiscardableRunnable() = delete;
423 explicit DiscardableRunnable(const char* aName) : Runnable(aName) {}
425 protected:
426 virtual ~DiscardableRunnable() = default;
428 private:
429 DiscardableRunnable(const DiscardableRunnable&) = delete;
430 DiscardableRunnable& operator=(const DiscardableRunnable&) = delete;
431 DiscardableRunnable& operator=(const DiscardableRunnable&&) = delete;
434 // This class is designed to be subclassed.
435 // Derived classes should override Run() and Cancel() to provide that
436 // calling Run() after Cancel() is a no-op.
437 class CancelableRunnable : public DiscardableRunnable,
438 public nsICancelableRunnable {
439 public:
440 NS_DECL_ISUPPORTS_INHERITED
441 // nsIDiscardableRunnable
442 void OnDiscard() override;
443 // nsICancelableRunnable
444 virtual nsresult Cancel() override = 0;
446 CancelableRunnable() = delete;
447 explicit CancelableRunnable(const char* aName) : DiscardableRunnable(aName) {}
449 protected:
450 virtual ~CancelableRunnable() = default;
452 private:
453 CancelableRunnable(const CancelableRunnable&) = delete;
454 CancelableRunnable& operator=(const CancelableRunnable&) = delete;
455 CancelableRunnable& operator=(const CancelableRunnable&&) = delete;
458 // This class is designed to be subclassed.
459 class IdleRunnable : public DiscardableRunnable, public nsIIdleRunnable {
460 public:
461 NS_DECL_ISUPPORTS_INHERITED
463 explicit IdleRunnable(const char* aName) : DiscardableRunnable(aName) {}
465 protected:
466 virtual ~IdleRunnable() = default;
468 private:
469 IdleRunnable(const IdleRunnable&) = delete;
470 IdleRunnable& operator=(const IdleRunnable&) = delete;
471 IdleRunnable& operator=(const IdleRunnable&&) = delete;
474 // This class is designed to be subclassed.
475 class CancelableIdleRunnable : public CancelableRunnable,
476 public nsIIdleRunnable {
477 public:
478 NS_DECL_ISUPPORTS_INHERITED
480 CancelableIdleRunnable() : CancelableRunnable("CancelableIdleRunnable") {}
481 explicit CancelableIdleRunnable(const char* aName)
482 : CancelableRunnable(aName) {}
484 protected:
485 virtual ~CancelableIdleRunnable() = default;
487 private:
488 CancelableIdleRunnable(const CancelableIdleRunnable&) = delete;
489 CancelableIdleRunnable& operator=(const CancelableIdleRunnable&) = delete;
490 CancelableIdleRunnable& operator=(const CancelableIdleRunnable&&) = delete;
493 // This class is designed to be a wrapper of a real runnable to support event
494 // prioritizable.
495 class PrioritizableRunnable : public Runnable, public nsIRunnablePriority {
496 public:
497 PrioritizableRunnable(already_AddRefed<nsIRunnable>&& aRunnable,
498 uint32_t aPriority);
500 # ifdef MOZ_COLLECTING_RUNNABLE_TELEMETRY
501 NS_IMETHOD GetName(nsACString& aName) override;
502 # endif
504 NS_DECL_ISUPPORTS_INHERITED
505 NS_DECL_NSIRUNNABLE
506 NS_DECL_NSIRUNNABLEPRIORITY
508 protected:
509 virtual ~PrioritizableRunnable() = default;
511 nsCOMPtr<nsIRunnable> mRunnable;
512 uint32_t mPriority;
515 class PrioritizableCancelableRunnable : public CancelableRunnable,
516 public nsIRunnablePriority {
517 public:
518 PrioritizableCancelableRunnable(uint32_t aPriority, const char* aName)
519 : CancelableRunnable(aName), mPriority(aPriority) {}
521 NS_DECL_ISUPPORTS_INHERITED
522 NS_DECL_NSIRUNNABLEPRIORITY
524 protected:
525 virtual ~PrioritizableCancelableRunnable() = default;
527 const uint32_t mPriority;
530 extern already_AddRefed<nsIRunnable> CreateRenderBlockingRunnable(
531 already_AddRefed<nsIRunnable>&& aRunnable);
533 namespace detail {
535 // An event that can be used to call a C++11 functions or function objects,
536 // including lambdas. The function must have no required arguments, and must
537 // return void.
538 template <typename StoredFunction>
539 class RunnableFunction : public Runnable {
540 public:
541 template <typename F>
542 explicit RunnableFunction(const char* aName, F&& aFunction)
543 : Runnable(aName), mFunction(std::forward<F>(aFunction)) {}
545 NS_IMETHOD Run() override {
546 static_assert(std::is_void_v<decltype(mFunction())>,
547 "The lambda must return void!");
548 mFunction();
549 return NS_OK;
552 private:
553 StoredFunction mFunction;
556 // Type alias for NS_NewRunnableFunction
557 template <typename Function>
558 using RunnableFunctionImpl =
559 // Make sure we store a non-reference in nsRunnableFunction.
560 typename detail::RunnableFunction<std::remove_reference_t<Function>>;
561 } // namespace detail
563 namespace detail {
565 template <typename CVRemoved>
566 struct IsRefcountedSmartPointerHelper : std::false_type {};
568 template <typename Pointee>
569 struct IsRefcountedSmartPointerHelper<RefPtr<Pointee>> : std::true_type {};
571 template <typename Pointee>
572 struct IsRefcountedSmartPointerHelper<nsCOMPtr<Pointee>> : std::true_type {};
574 } // namespace detail
576 template <typename T>
577 struct IsRefcountedSmartPointer
578 : detail::IsRefcountedSmartPointerHelper<std::remove_cv_t<T>> {};
580 namespace detail {
582 template <typename T, typename CVRemoved>
583 struct RemoveSmartPointerHelper {
584 typedef T Type;
587 template <typename T, typename Pointee>
588 struct RemoveSmartPointerHelper<T, RefPtr<Pointee>> {
589 typedef Pointee Type;
592 template <typename T, typename Pointee>
593 struct RemoveSmartPointerHelper<T, nsCOMPtr<Pointee>> {
594 typedef Pointee Type;
597 } // namespace detail
599 template <typename T>
600 struct RemoveSmartPointer
601 : detail::RemoveSmartPointerHelper<T, std::remove_cv_t<T>> {};
603 namespace detail {
605 template <typename T, typename CVRemoved>
606 struct RemoveRawOrSmartPointerHelper {
607 typedef T Type;
610 template <typename T, typename Pointee>
611 struct RemoveRawOrSmartPointerHelper<T, Pointee*> {
612 typedef Pointee Type;
615 template <typename T, typename Pointee>
616 struct RemoveRawOrSmartPointerHelper<T, RefPtr<Pointee>> {
617 typedef Pointee Type;
620 template <typename T, typename Pointee>
621 struct RemoveRawOrSmartPointerHelper<T, nsCOMPtr<Pointee>> {
622 typedef Pointee Type;
625 } // namespace detail
627 template <typename T>
628 struct RemoveRawOrSmartPointer
629 : detail::RemoveRawOrSmartPointerHelper<T, std::remove_cv_t<T>> {};
631 } // namespace mozilla
633 inline nsISupports* ToSupports(mozilla::Runnable* p) {
634 return static_cast<nsIRunnable*>(p);
637 template <typename Function>
638 already_AddRefed<mozilla::Runnable> NS_NewRunnableFunction(
639 const char* aName, Function&& aFunction) {
640 // We store a non-reference in RunnableFunction, but still forward aFunction
641 // to move if possible.
642 return do_AddRef(new mozilla::detail::RunnableFunctionImpl<Function>(
643 aName, std::forward<Function>(aFunction)));
646 // Creates a new object implementing nsIRunnable and nsICancelableRunnable,
647 // which runs a given function on Run and clears the stored function object on a
648 // call to `Cancel` (and thus destroys all objects it holds).
649 template <typename Function>
650 already_AddRefed<mozilla::CancelableRunnable> NS_NewCancelableRunnableFunction(
651 const char* aName, Function&& aFunc) {
652 class FuncCancelableRunnable final : public mozilla::CancelableRunnable {
653 public:
654 static_assert(
655 std::is_void_v<
656 decltype(std::declval<std::remove_reference_t<Function>>()())>);
658 NS_INLINE_DECL_REFCOUNTING_INHERITED(FuncCancelableRunnable,
659 CancelableRunnable)
661 explicit FuncCancelableRunnable(const char* aName, Function&& aFunc)
662 : CancelableRunnable{aName},
663 mFunc{mozilla::Some(std::forward<Function>(aFunc))} {}
665 NS_IMETHOD Run() override {
666 if (mFunc) {
667 (*mFunc)();
670 return NS_OK;
673 nsresult Cancel() override {
674 mFunc.reset();
675 return NS_OK;
678 private:
679 ~FuncCancelableRunnable() = default;
681 mozilla::Maybe<std::remove_reference_t<Function>> mFunc;
684 return mozilla::MakeAndAddRef<FuncCancelableRunnable>(
685 aName, std::forward<Function>(aFunc));
688 namespace mozilla {
689 namespace detail {
691 template <RunnableKind Kind>
692 class TimerBehaviour {
693 public:
694 nsITimer* GetTimer() { return nullptr; }
695 void CancelTimer() {}
697 protected:
698 ~TimerBehaviour() = default;
701 template <>
702 class TimerBehaviour<RunnableKind::IdleWithTimer> {
703 public:
704 nsITimer* GetTimer() {
705 if (!mTimer) {
706 mTimer = NS_NewTimer();
709 return mTimer;
712 void CancelTimer() {
713 if (mTimer) {
714 mTimer->Cancel();
718 protected:
719 ~TimerBehaviour() { CancelTimer(); }
721 private:
722 nsCOMPtr<nsITimer> mTimer;
725 } // namespace detail
726 } // namespace mozilla
728 // An event that can be used to call a method on a class. The class type must
729 // support reference counting. This event supports Revoke for use
730 // with nsRevocableEventPtr.
731 template <class ClassType, typename ReturnType = void, bool Owning = true,
732 mozilla::RunnableKind Kind = mozilla::RunnableKind::Standard>
733 class nsRunnableMethod
734 : public std::conditional_t<
735 Kind == mozilla::RunnableKind::Standard, mozilla::Runnable,
736 std::conditional_t<Kind == mozilla::RunnableKind::Cancelable,
737 mozilla::CancelableRunnable,
738 mozilla::CancelableIdleRunnable>>,
739 protected mozilla::detail::TimerBehaviour<Kind> {
740 using BaseType = std::conditional_t<
741 Kind == mozilla::RunnableKind::Standard, mozilla::Runnable,
742 std::conditional_t<Kind == mozilla::RunnableKind::Cancelable,
743 mozilla::CancelableRunnable,
744 mozilla::CancelableIdleRunnable>>;
746 public:
747 nsRunnableMethod(const char* aName) : BaseType(aName) {}
749 virtual void Revoke() = 0;
751 // These ReturnTypeEnforcer classes disallow return types that
752 // we know are not safe. The default ReturnTypeEnforcer compiles just fine but
753 // already_AddRefed will not.
754 template <typename OtherReturnType>
755 class ReturnTypeEnforcer {
756 public:
757 typedef int ReturnTypeIsSafe;
760 template <class T>
761 class ReturnTypeEnforcer<already_AddRefed<T>> {
762 // No ReturnTypeIsSafe makes this illegal!
765 // Make sure this return type is safe.
766 typedef typename ReturnTypeEnforcer<ReturnType>::ReturnTypeIsSafe check;
769 template <class ClassType, bool Owning>
770 struct nsRunnableMethodReceiver {
771 RefPtr<ClassType> mObj;
772 explicit nsRunnableMethodReceiver(ClassType* aObj) : mObj(aObj) {}
773 explicit nsRunnableMethodReceiver(RefPtr<ClassType>&& aObj)
774 : mObj(std::move(aObj)) {}
775 ~nsRunnableMethodReceiver() { Revoke(); }
776 ClassType* Get() const { return mObj.get(); }
777 void Revoke() { mObj = nullptr; }
780 template <class ClassType>
781 struct nsRunnableMethodReceiver<ClassType, false> {
782 ClassType* MOZ_NON_OWNING_REF mObj;
783 explicit nsRunnableMethodReceiver(ClassType* aObj) : mObj(aObj) {}
784 ClassType* Get() const { return mObj; }
785 void Revoke() { mObj = nullptr; }
788 static inline constexpr bool IsIdle(mozilla::RunnableKind aKind) {
789 return aKind == mozilla::RunnableKind::Idle ||
790 aKind == mozilla::RunnableKind::IdleWithTimer;
793 template <typename PtrType, typename Method, bool Owning,
794 mozilla::RunnableKind Kind>
795 struct nsRunnableMethodTraits;
797 template <typename PtrType, class C, typename R, bool Owning,
798 mozilla::RunnableKind Kind, typename... As>
799 struct nsRunnableMethodTraits<PtrType, R (C::*)(As...), Owning, Kind> {
800 typedef typename mozilla::RemoveRawOrSmartPointer<PtrType>::Type class_type;
801 static_assert(std::is_base_of<C, class_type>::value,
802 "Stored class must inherit from method's class");
803 typedef R return_type;
804 typedef nsRunnableMethod<C, R, Owning, Kind> base_type;
805 static const bool can_cancel = Kind == mozilla::RunnableKind::Cancelable;
808 template <typename PtrType, class C, typename R, bool Owning,
809 mozilla::RunnableKind Kind, typename... As>
810 struct nsRunnableMethodTraits<PtrType, R (C::*)(As...) const, Owning, Kind> {
811 typedef const typename mozilla::RemoveRawOrSmartPointer<PtrType>::Type
812 class_type;
813 static_assert(std::is_base_of<C, class_type>::value,
814 "Stored class must inherit from method's class");
815 typedef R return_type;
816 typedef nsRunnableMethod<C, R, Owning, Kind> base_type;
817 static const bool can_cancel = Kind == mozilla::RunnableKind::Cancelable;
820 # ifdef NS_HAVE_STDCALL
821 template <typename PtrType, class C, typename R, bool Owning,
822 mozilla::RunnableKind Kind, typename... As>
823 struct nsRunnableMethodTraits<PtrType, R (__stdcall C::*)(As...), Owning,
824 Kind> {
825 typedef typename mozilla::RemoveRawOrSmartPointer<PtrType>::Type class_type;
826 static_assert(std::is_base_of<C, class_type>::value,
827 "Stored class must inherit from method's class");
828 typedef R return_type;
829 typedef nsRunnableMethod<C, R, Owning, Kind> base_type;
830 static const bool can_cancel = Kind == mozilla::RunnableKind::Cancelable;
833 template <typename PtrType, class C, typename R, bool Owning,
834 mozilla::RunnableKind Kind>
835 struct nsRunnableMethodTraits<PtrType, R (NS_STDCALL C::*)(), Owning, Kind> {
836 typedef typename mozilla::RemoveRawOrSmartPointer<PtrType>::Type class_type;
837 static_assert(std::is_base_of<C, class_type>::value,
838 "Stored class must inherit from method's class");
839 typedef R return_type;
840 typedef nsRunnableMethod<C, R, Owning, Kind> base_type;
841 static const bool can_cancel = Kind == mozilla::RunnableKind::Cancelable;
844 template <typename PtrType, class C, typename R, bool Owning,
845 mozilla::RunnableKind Kind, typename... As>
846 struct nsRunnableMethodTraits<PtrType, R (__stdcall C::*)(As...) const, Owning,
847 Kind> {
848 typedef const typename mozilla::RemoveRawOrSmartPointer<PtrType>::Type
849 class_type;
850 static_assert(std::is_base_of<C, class_type>::value,
851 "Stored class must inherit from method's class");
852 typedef R return_type;
853 typedef nsRunnableMethod<C, R, Owning, Kind> base_type;
854 static const bool can_cancel = Kind == mozilla::RunnableKind::Cancelable;
857 template <typename PtrType, class C, typename R, bool Owning,
858 mozilla::RunnableKind Kind>
859 struct nsRunnableMethodTraits<PtrType, R (NS_STDCALL C::*)() const, Owning,
860 Kind> {
861 typedef const typename mozilla::RemoveRawOrSmartPointer<PtrType>::Type
862 class_type;
863 static_assert(std::is_base_of<C, class_type>::value,
864 "Stored class must inherit from method's class");
865 typedef R return_type;
866 typedef nsRunnableMethod<C, R, Owning, Kind> base_type;
867 static const bool can_cancel = Kind == mozilla::RunnableKind::Cancelable;
869 # endif
871 // IsParameterStorageClass<T>::value is true if T is a parameter-storage class
872 // that will be recognized by NS_New[NonOwning]RunnableMethodWithArg[s] to
873 // force a specific storage&passing strategy (instead of inferring one,
874 // see ParameterStorage).
875 // When creating a new storage class, add a specialization for it to be
876 // recognized.
877 template <typename T>
878 struct IsParameterStorageClass : public std::false_type {};
880 // StoreXPassByY structs used to inform nsRunnableMethodArguments how to
881 // store arguments, and how to pass them to the target method.
883 template <typename T>
884 struct StoreCopyPassByValue {
885 using stored_type = std::decay_t<T>;
886 typedef stored_type passed_type;
887 stored_type m;
888 template <typename A>
889 MOZ_IMPLICIT StoreCopyPassByValue(A&& a) : m(std::forward<A>(a)) {}
890 passed_type PassAsParameter() { return m; }
892 template <typename S>
893 struct IsParameterStorageClass<StoreCopyPassByValue<S>>
894 : public std::true_type {};
896 template <typename T>
897 struct StoreCopyPassByConstLRef {
898 using stored_type = std::decay_t<T>;
899 typedef const stored_type& passed_type;
900 stored_type m;
901 template <typename A>
902 MOZ_IMPLICIT StoreCopyPassByConstLRef(A&& a) : m(std::forward<A>(a)) {}
903 passed_type PassAsParameter() { return m; }
905 template <typename S>
906 struct IsParameterStorageClass<StoreCopyPassByConstLRef<S>>
907 : public std::true_type {};
909 template <typename T>
910 struct StoreCopyPassByLRef {
911 using stored_type = std::decay_t<T>;
912 typedef stored_type& passed_type;
913 stored_type m;
914 template <typename A>
915 MOZ_IMPLICIT StoreCopyPassByLRef(A&& a) : m(std::forward<A>(a)) {}
916 passed_type PassAsParameter() { return m; }
918 template <typename S>
919 struct IsParameterStorageClass<StoreCopyPassByLRef<S>> : public std::true_type {
922 template <typename T>
923 struct StoreCopyPassByRRef {
924 using stored_type = std::decay_t<T>;
925 typedef stored_type&& passed_type;
926 stored_type m;
927 template <typename A>
928 MOZ_IMPLICIT StoreCopyPassByRRef(A&& a) : m(std::forward<A>(a)) {}
929 passed_type PassAsParameter() { return std::move(m); }
931 template <typename S>
932 struct IsParameterStorageClass<StoreCopyPassByRRef<S>> : public std::true_type {
935 template <typename T>
936 struct StoreRefPassByLRef {
937 typedef T& stored_type;
938 typedef T& passed_type;
939 stored_type m;
940 template <typename A>
941 MOZ_IMPLICIT StoreRefPassByLRef(A& a) : m(a) {}
942 passed_type PassAsParameter() { return m; }
944 template <typename S>
945 struct IsParameterStorageClass<StoreRefPassByLRef<S>> : public std::true_type {
948 template <typename T>
949 struct StoreConstRefPassByConstLRef {
950 typedef const T& stored_type;
951 typedef const T& passed_type;
952 stored_type m;
953 template <typename A>
954 MOZ_IMPLICIT StoreConstRefPassByConstLRef(const A& a) : m(a) {}
955 passed_type PassAsParameter() { return m; }
957 template <typename S>
958 struct IsParameterStorageClass<StoreConstRefPassByConstLRef<S>>
959 : public std::true_type {};
961 template <typename T>
962 struct StoreRefPtrPassByPtr {
963 typedef RefPtr<T> stored_type;
964 typedef T* passed_type;
965 stored_type m;
966 template <typename A>
967 MOZ_IMPLICIT StoreRefPtrPassByPtr(A&& a) : m(std::forward<A>(a)) {}
968 passed_type PassAsParameter() { return m.get(); }
970 template <typename S>
971 struct IsParameterStorageClass<StoreRefPtrPassByPtr<S>>
972 : public std::true_type {};
974 template <typename T>
975 struct StorePtrPassByPtr {
976 typedef T* stored_type;
977 typedef T* passed_type;
978 stored_type m;
979 template <typename A>
980 MOZ_IMPLICIT StorePtrPassByPtr(A a) : m(a) {}
981 passed_type PassAsParameter() { return m; }
983 template <typename S>
984 struct IsParameterStorageClass<StorePtrPassByPtr<S>> : public std::true_type {};
986 template <typename T>
987 struct StoreConstPtrPassByConstPtr {
988 typedef const T* stored_type;
989 typedef const T* passed_type;
990 stored_type m;
991 template <typename A>
992 MOZ_IMPLICIT StoreConstPtrPassByConstPtr(A a) : m(a) {}
993 passed_type PassAsParameter() { return m; }
995 template <typename S>
996 struct IsParameterStorageClass<StoreConstPtrPassByConstPtr<S>>
997 : public std::true_type {};
999 template <typename T>
1000 struct StoreCopyPassByConstPtr {
1001 typedef T stored_type;
1002 typedef const T* passed_type;
1003 stored_type m;
1004 template <typename A>
1005 MOZ_IMPLICIT StoreCopyPassByConstPtr(A&& a) : m(std::forward<A>(a)) {}
1006 passed_type PassAsParameter() { return &m; }
1008 template <typename S>
1009 struct IsParameterStorageClass<StoreCopyPassByConstPtr<S>>
1010 : public std::true_type {};
1012 template <typename T>
1013 struct StoreCopyPassByPtr {
1014 typedef T stored_type;
1015 typedef T* passed_type;
1016 stored_type m;
1017 template <typename A>
1018 MOZ_IMPLICIT StoreCopyPassByPtr(A&& a) : m(std::forward<A>(a)) {}
1019 passed_type PassAsParameter() { return &m; }
1021 template <typename S>
1022 struct IsParameterStorageClass<StoreCopyPassByPtr<S>> : public std::true_type {
1025 namespace detail {
1027 template <typename>
1028 struct SFINAE1True : std::true_type {};
1030 template <class T>
1031 static auto HasRefCountMethodsTest(int)
1032 -> SFINAE1True<decltype(std::declval<T>().AddRef(),
1033 std::declval<T>().Release())>;
1034 template <class>
1035 static auto HasRefCountMethodsTest(long) -> std::false_type;
1037 template <class T>
1038 struct HasRefCountMethods : decltype(HasRefCountMethodsTest<T>(0)) {};
1040 template <typename TWithoutPointer>
1041 struct NonnsISupportsPointerStorageClass
1042 : std::conditional<
1043 std::is_const_v<TWithoutPointer>,
1044 StoreConstPtrPassByConstPtr<std::remove_const_t<TWithoutPointer>>,
1045 StorePtrPassByPtr<TWithoutPointer>> {
1046 using Type = typename NonnsISupportsPointerStorageClass::conditional::type;
1049 template <typename TWithoutPointer>
1050 struct PointerStorageClass
1051 : std::conditional<
1052 HasRefCountMethods<TWithoutPointer>::value,
1053 StoreRefPtrPassByPtr<TWithoutPointer>,
1054 typename NonnsISupportsPointerStorageClass<TWithoutPointer>::Type> {
1055 using Type = typename PointerStorageClass::conditional::type;
1058 template <typename TWithoutRef>
1059 struct LValueReferenceStorageClass
1060 : std::conditional<
1061 std::is_const_v<TWithoutRef>,
1062 StoreConstRefPassByConstLRef<std::remove_const_t<TWithoutRef>>,
1063 StoreRefPassByLRef<TWithoutRef>> {
1064 using Type = typename LValueReferenceStorageClass::conditional::type;
1067 template <typename T>
1068 struct SmartPointerStorageClass
1069 : std::conditional<
1070 mozilla::IsRefcountedSmartPointer<T>::value,
1071 StoreRefPtrPassByPtr<typename mozilla::RemoveSmartPointer<T>::Type>,
1072 StoreCopyPassByConstLRef<T>> {
1073 using Type = typename SmartPointerStorageClass::conditional::type;
1076 template <typename T>
1077 struct NonLValueReferenceStorageClass
1078 : std::conditional<std::is_rvalue_reference_v<T>,
1079 StoreCopyPassByRRef<std::remove_reference_t<T>>,
1080 typename SmartPointerStorageClass<T>::Type> {
1081 using Type = typename NonLValueReferenceStorageClass::conditional::type;
1084 template <typename T>
1085 struct NonPointerStorageClass
1086 : std::conditional<std::is_lvalue_reference_v<T>,
1087 typename LValueReferenceStorageClass<
1088 std::remove_reference_t<T>>::Type,
1089 typename NonLValueReferenceStorageClass<T>::Type> {
1090 using Type = typename NonPointerStorageClass::conditional::type;
1093 template <typename T>
1094 struct NonParameterStorageClass
1095 : std::conditional<
1096 std::is_pointer_v<T>,
1097 typename PointerStorageClass<std::remove_pointer_t<T>>::Type,
1098 typename NonPointerStorageClass<T>::Type> {
1099 using Type = typename NonParameterStorageClass::conditional::type;
1102 // Choose storage&passing strategy based on preferred storage type:
1103 // - If IsParameterStorageClass<T>::value is true, use as-is.
1104 // - RC* -> StoreRefPtrPassByPtr<RC> :Store RefPtr<RC>, pass RC*
1105 // ^^ RC quacks like a ref-counted type (i.e., has AddRef and Release methods)
1106 // - const T* -> StoreConstPtrPassByConstPtr<T> :Store const T*, pass const T*
1107 // - T* -> StorePtrPassByPtr<T> :Store T*, pass T*.
1108 // - const T& -> StoreConstRefPassByConstLRef<T>:Store const T&, pass const T&.
1109 // - T& -> StoreRefPassByLRef<T> :Store T&, pass T&.
1110 // - T&& -> StoreCopyPassByRRef<T> :Store T, pass std::move(T).
1111 // - RefPtr<T>, nsCOMPtr<T>
1112 // -> StoreRefPtrPassByPtr<T> :Store RefPtr<T>, pass T*
1113 // - Other T -> StoreCopyPassByConstLRef<T> :Store T, pass const T&.
1114 // Other available explicit options:
1115 // - StoreCopyPassByValue<T> :Store T, pass T.
1116 // - StoreCopyPassByLRef<T> :Store T, pass T& (of copy!)
1117 // - StoreCopyPassByConstPtr<T> :Store T, pass const T*
1118 // - StoreCopyPassByPtr<T> :Store T, pass T* (of copy!)
1119 // Or create your own class with PassAsParameter() method, optional
1120 // clean-up in destructor, and with associated IsParameterStorageClass<>.
1121 template <typename T>
1122 struct ParameterStorage
1123 : std::conditional<IsParameterStorageClass<T>::value, T,
1124 typename NonParameterStorageClass<T>::Type> {
1125 using Type = typename ParameterStorage::conditional::type;
1128 template <class T>
1129 static auto HasSetDeadlineTest(int)
1130 -> SFINAE1True<decltype(std::declval<T>().SetDeadline(
1131 std::declval<mozilla::TimeStamp>()))>;
1133 template <class T>
1134 static auto HasSetDeadlineTest(long) -> std::false_type;
1136 template <class T>
1137 struct HasSetDeadline : decltype(HasSetDeadlineTest<T>(0)) {};
1139 template <class T>
1140 std::enable_if_t<::detail::HasSetDeadline<T>::value> SetDeadlineImpl(
1141 T* aObj, mozilla::TimeStamp aTimeStamp) {
1142 aObj->SetDeadline(aTimeStamp);
1145 template <class T>
1146 std::enable_if_t<!::detail::HasSetDeadline<T>::value> SetDeadlineImpl(
1147 T* aObj, mozilla::TimeStamp aTimeStamp) {}
1148 } /* namespace detail */
1150 namespace mozilla {
1151 namespace detail {
1153 // struct used to store arguments and later apply them to a method.
1154 template <typename... Ts>
1155 struct RunnableMethodArguments final {
1156 std::tuple<typename ::detail::ParameterStorage<Ts>::Type...> mArguments;
1157 template <typename... As>
1158 explicit RunnableMethodArguments(As&&... aArguments)
1159 : mArguments(std::forward<As>(aArguments)...) {}
1160 template <class C, typename M>
1161 decltype(auto) apply(C* o, M m) {
1162 return std::apply(
1163 [&o, m](auto&&... args) {
1164 return ((*o).*m)(args.PassAsParameter()...);
1166 mArguments);
1170 template <typename PtrType, typename Method, bool Owning, RunnableKind Kind,
1171 typename... Storages>
1172 class RunnableMethodImpl final
1173 : public ::nsRunnableMethodTraits<PtrType, Method, Owning,
1174 Kind>::base_type {
1175 typedef typename ::nsRunnableMethodTraits<PtrType, Method, Owning, Kind>
1176 Traits;
1178 typedef typename Traits::class_type ClassType;
1179 typedef typename Traits::base_type BaseType;
1180 ::nsRunnableMethodReceiver<ClassType, Owning> mReceiver;
1181 Method mMethod;
1182 RunnableMethodArguments<Storages...> mArgs;
1183 using BaseType::CancelTimer;
1184 using BaseType::GetTimer;
1186 private:
1187 virtual ~RunnableMethodImpl() { Revoke(); };
1188 static void TimedOut(nsITimer* aTimer, void* aClosure) {
1189 static_assert(IsIdle(Kind), "Don't use me!");
1190 RefPtr<CancelableIdleRunnable> r =
1191 static_cast<CancelableIdleRunnable*>(aClosure);
1192 r->SetDeadline(TimeStamp());
1193 r->Run();
1194 r->Cancel();
1197 public:
1198 template <typename ForwardedPtrType, typename... Args>
1199 explicit RunnableMethodImpl(const char* aName, ForwardedPtrType&& aObj,
1200 Method aMethod, Args&&... aArgs)
1201 : BaseType(aName),
1202 mReceiver(std::forward<ForwardedPtrType>(aObj)),
1203 mMethod(aMethod),
1204 mArgs(std::forward<Args>(aArgs)...) {
1205 static_assert(sizeof...(Storages) == sizeof...(Args),
1206 "Storages and Args should have equal sizes");
1209 NS_IMETHOD Run() {
1210 CancelTimer();
1212 if (MOZ_LIKELY(mReceiver.Get())) {
1213 mArgs.apply(mReceiver.Get(), mMethod);
1216 return NS_OK;
1219 nsresult Cancel() {
1220 static_assert(Kind >= RunnableKind::Cancelable, "Don't use me!");
1221 Revoke();
1222 return NS_OK;
1225 void Revoke() {
1226 CancelTimer();
1227 mReceiver.Revoke();
1230 void SetDeadline(TimeStamp aDeadline) {
1231 if (MOZ_LIKELY(mReceiver.Get())) {
1232 ::detail::SetDeadlineImpl(mReceiver.Get(), aDeadline);
1236 void SetTimer(uint32_t aDelay, nsIEventTarget* aTarget) {
1237 MOZ_ASSERT(aTarget);
1239 if (nsCOMPtr<nsITimer> timer = GetTimer()) {
1240 timer->Cancel();
1241 timer->SetTarget(aTarget);
1242 timer->InitWithNamedFuncCallback(TimedOut, this, aDelay,
1243 nsITimer::TYPE_ONE_SHOT,
1244 "detail::RunnableMethodImpl::SetTimer");
1249 // Type aliases for NewRunnableMethod.
1250 template <typename PtrType, typename Method>
1251 using OwningRunnableMethod =
1252 typename ::nsRunnableMethodTraits<std::remove_reference_t<PtrType>, Method,
1253 true, RunnableKind::Standard>::base_type;
1254 template <typename PtrType, typename Method, typename... Storages>
1255 using OwningRunnableMethodImpl =
1256 RunnableMethodImpl<std::remove_reference_t<PtrType>, Method, true,
1257 RunnableKind::Standard, Storages...>;
1259 // Type aliases for NewCancelableRunnableMethod.
1260 template <typename PtrType, typename Method>
1261 using CancelableRunnableMethod =
1262 typename ::nsRunnableMethodTraits<std::remove_reference_t<PtrType>, Method,
1263 true,
1264 RunnableKind::Cancelable>::base_type;
1265 template <typename PtrType, typename Method, typename... Storages>
1266 using CancelableRunnableMethodImpl =
1267 RunnableMethodImpl<std::remove_reference_t<PtrType>, Method, true,
1268 RunnableKind::Cancelable, Storages...>;
1270 // Type aliases for NewIdleRunnableMethod.
1271 template <typename PtrType, typename Method>
1272 using IdleRunnableMethod =
1273 typename ::nsRunnableMethodTraits<std::remove_reference_t<PtrType>, Method,
1274 true, RunnableKind::Idle>::base_type;
1275 template <typename PtrType, typename Method, typename... Storages>
1276 using IdleRunnableMethodImpl =
1277 RunnableMethodImpl<std::remove_reference_t<PtrType>, Method, true,
1278 RunnableKind::Idle, Storages...>;
1280 // Type aliases for NewIdleRunnableMethodWithTimer.
1281 template <typename PtrType, typename Method>
1282 using IdleRunnableMethodWithTimer =
1283 typename ::nsRunnableMethodTraits<std::remove_reference_t<PtrType>, Method,
1284 true,
1285 RunnableKind::IdleWithTimer>::base_type;
1286 template <typename PtrType, typename Method, typename... Storages>
1287 using IdleRunnableMethodWithTimerImpl =
1288 RunnableMethodImpl<std::remove_reference_t<PtrType>, Method, true,
1289 RunnableKind::IdleWithTimer, Storages...>;
1291 // Type aliases for NewNonOwningRunnableMethod.
1292 template <typename PtrType, typename Method>
1293 using NonOwningRunnableMethod =
1294 typename ::nsRunnableMethodTraits<std::remove_reference_t<PtrType>, Method,
1295 false, RunnableKind::Standard>::base_type;
1296 template <typename PtrType, typename Method, typename... Storages>
1297 using NonOwningRunnableMethodImpl =
1298 RunnableMethodImpl<std::remove_reference_t<PtrType>, Method, false,
1299 RunnableKind::Standard, Storages...>;
1301 // Type aliases for NonOwningCancelableRunnableMethod
1302 template <typename PtrType, typename Method>
1303 using NonOwningCancelableRunnableMethod =
1304 typename ::nsRunnableMethodTraits<std::remove_reference_t<PtrType>, Method,
1305 false,
1306 RunnableKind::Cancelable>::base_type;
1307 template <typename PtrType, typename Method, typename... Storages>
1308 using NonOwningCancelableRunnableMethodImpl =
1309 RunnableMethodImpl<std::remove_reference_t<PtrType>, Method, false,
1310 RunnableKind::Cancelable, Storages...>;
1312 // Type aliases for NonOwningIdleRunnableMethod
1313 template <typename PtrType, typename Method>
1314 using NonOwningIdleRunnableMethod =
1315 typename ::nsRunnableMethodTraits<std::remove_reference_t<PtrType>, Method,
1316 false, RunnableKind::Idle>::base_type;
1317 template <typename PtrType, typename Method, typename... Storages>
1318 using NonOwningIdleRunnableMethodImpl =
1319 RunnableMethodImpl<std::remove_reference_t<PtrType>, Method, false,
1320 RunnableKind::Idle, Storages...>;
1322 // Type aliases for NewIdleRunnableMethodWithTimer.
1323 template <typename PtrType, typename Method>
1324 using NonOwningIdleRunnableMethodWithTimer =
1325 typename ::nsRunnableMethodTraits<std::remove_reference_t<PtrType>, Method,
1326 false,
1327 RunnableKind::IdleWithTimer>::base_type;
1328 template <typename PtrType, typename Method, typename... Storages>
1329 using NonOwningIdleRunnableMethodWithTimerImpl =
1330 RunnableMethodImpl<std::remove_reference_t<PtrType>, Method, false,
1331 RunnableKind::IdleWithTimer, Storages...>;
1333 } // namespace detail
1335 // NewRunnableMethod and friends
1337 // Very often in Gecko, you'll find yourself in a situation where you want
1338 // to invoke a method (with or without arguments) asynchronously. You
1339 // could write a small helper class inheriting from nsRunnable to handle
1340 // all these details, or you could let NewRunnableMethod take care of all
1341 // those details for you.
1343 // The simplest use of NewRunnableMethod looks like:
1345 // nsCOMPtr<nsIRunnable> event =
1346 // mozilla::NewRunnableMethod("description", myObject,
1347 // &MyClass::HandleEvent);
1348 // NS_DispatchToCurrentThread(event);
1350 // Statically enforced constraints:
1351 // - myObject must be of (or implicitly convertible to) type MyClass
1352 // - MyClass must define AddRef and Release methods
1354 // The "description" string should specify a human-readable name for the
1355 // runnable; the provided string is used by various introspection tools
1356 // in the browser.
1358 // The created runnable will take a strong reference to `myObject`. For
1359 // non-refcounted objects, or refcounted objects with unusual refcounting
1360 // requirements, and if and only if you are 110% certain that `myObject`
1361 // will live long enough, you can use NewNonOwningRunnableMethod instead,
1362 // which will, as its name implies, take a non-owning reference. If you
1363 // find yourself having to use this function, you should accompany your use
1364 // with a proof comment describing why the runnable will not lead to
1365 // use-after-frees.
1367 // (If you find yourself writing contorted code to Release() an object
1368 // asynchronously on a different thread, you should use the
1369 // NS_ProxyRelease function.)
1371 // Invoking a method with arguments takes a little more care. The
1372 // natural extension of the above:
1374 // nsCOMPtr<nsIRunnable> event =
1375 // mozilla::NewRunnableMethod("description", myObject,
1376 // &MyClass::HandleEvent,
1377 // arg1, arg2, ...);
1379 // can lead to security hazards (e.g. passing in raw pointers to refcounted
1380 // objects and storing those raw pointers in the runnable). We therefore
1381 // require you to specify the storage types used by the runnable, just as
1382 // you would if you were writing out the class by hand:
1384 // nsCOMPtr<nsIRunnable> event =
1385 // mozilla::NewRunnableMethod<RefPtr<T>, nsTArray<U>>
1386 // ("description", myObject, &MyClass::HandleEvent, arg1, arg2);
1388 // Please note that you do not have to pass the same argument type as you
1389 // specify in the template arguments. For example, if you want to transfer
1390 // ownership to a runnable, you can write:
1392 // RefPtr<T> ptr = ...;
1393 // nsTArray<U> array = ...;
1394 // nsCOMPtr<nsIRunnable> event =
1395 // mozilla::NewRunnableMethod<RefPtr<T>, nsTArray<U>>
1396 // ("description", myObject, &MyClass::DoSomething,
1397 // std::move(ptr), std::move(array));
1399 // and there will be no extra AddRef/Release traffic, or copying of the array.
1401 // Each type that you specify as a template argument to NewRunnableMethod
1402 // comes with its own style of storage in the runnable and its own style
1403 // of argument passing to the invoked method. See the comment for
1404 // ParameterStorage above for more details.
1406 // If you need to customize the storage type and/or argument passing type,
1407 // you can write your own class to use as a template argument to
1408 // NewRunnableMethod. If you find yourself having to do that frequently,
1409 // please file a bug in Core::XPCOM about adding the custom type to the
1410 // core code in this file, and/or for custom rules for ParameterStorage
1411 // to select that strategy.
1413 // For places that require you to use cancelable runnables, such as
1414 // workers, there's also NewCancelableRunnableMethod and its non-owning
1415 // counterpart. The runnables returned by these methods additionally
1416 // implement nsICancelableRunnable.
1418 // Finally, all of the functions discussed above have additional overloads
1419 // that do not take a `const char*` as their first parameter; you may see
1420 // these in older code. The `const char*` overload is preferred and
1421 // should be used in new code exclusively.
1423 template <typename PtrType, typename Method>
1424 already_AddRefed<detail::OwningRunnableMethod<PtrType, Method>>
1425 NewRunnableMethod(const char* aName, PtrType&& aPtr, Method aMethod) {
1426 return do_AddRef(new detail::OwningRunnableMethodImpl<PtrType, Method>(
1427 aName, std::forward<PtrType>(aPtr), aMethod));
1430 template <typename PtrType, typename Method>
1431 already_AddRefed<detail::CancelableRunnableMethod<PtrType, Method>>
1432 NewCancelableRunnableMethod(const char* aName, PtrType&& aPtr, Method aMethod) {
1433 return do_AddRef(new detail::CancelableRunnableMethodImpl<PtrType, Method>(
1434 aName, std::forward<PtrType>(aPtr), aMethod));
1437 template <typename PtrType, typename Method>
1438 already_AddRefed<detail::IdleRunnableMethod<PtrType, Method>>
1439 NewIdleRunnableMethod(const char* aName, PtrType&& aPtr, Method aMethod) {
1440 return do_AddRef(new detail::IdleRunnableMethodImpl<PtrType, Method>(
1441 aName, std::forward<PtrType>(aPtr), aMethod));
1444 template <typename PtrType, typename Method>
1445 already_AddRefed<detail::IdleRunnableMethodWithTimer<PtrType, Method>>
1446 NewIdleRunnableMethodWithTimer(const char* aName, PtrType&& aPtr,
1447 Method aMethod) {
1448 return do_AddRef(new detail::IdleRunnableMethodWithTimerImpl<PtrType, Method>(
1449 aName, std::forward<PtrType>(aPtr), aMethod));
1452 template <typename PtrType, typename Method>
1453 already_AddRefed<detail::NonOwningRunnableMethod<PtrType, Method>>
1454 NewNonOwningRunnableMethod(const char* aName, PtrType&& aPtr, Method aMethod) {
1455 return do_AddRef(new detail::NonOwningRunnableMethodImpl<PtrType, Method>(
1456 aName, std::forward<PtrType>(aPtr), aMethod));
1459 template <typename PtrType, typename Method>
1460 already_AddRefed<detail::NonOwningCancelableRunnableMethod<PtrType, Method>>
1461 NewNonOwningCancelableRunnableMethod(const char* aName, PtrType&& aPtr,
1462 Method aMethod) {
1463 return do_AddRef(
1464 new detail::NonOwningCancelableRunnableMethodImpl<PtrType, Method>(
1465 aName, std::forward<PtrType>(aPtr), aMethod));
1468 template <typename PtrType, typename Method>
1469 already_AddRefed<detail::NonOwningIdleRunnableMethod<PtrType, Method>>
1470 NewNonOwningIdleRunnableMethod(const char* aName, PtrType&& aPtr,
1471 Method aMethod) {
1472 return do_AddRef(new detail::NonOwningIdleRunnableMethodImpl<PtrType, Method>(
1473 aName, std::forward<PtrType>(aPtr), aMethod));
1476 template <typename PtrType, typename Method>
1477 already_AddRefed<detail::NonOwningIdleRunnableMethodWithTimer<PtrType, Method>>
1478 NewNonOwningIdleRunnableMethodWithTimer(const char* aName, PtrType&& aPtr,
1479 Method aMethod) {
1480 return do_AddRef(
1481 new detail::NonOwningIdleRunnableMethodWithTimerImpl<PtrType, Method>(
1482 aName, std::forward<PtrType>(aPtr), aMethod));
1485 // Similar to NewRunnableMethod. Call like so:
1486 // nsCOMPtr<nsIRunnable> event =
1487 // NewRunnableMethod<Types,...>(myObject, &MyClass::HandleEvent, myArg1,...);
1488 // 'Types' are the stored type for each argument, see ParameterStorage for
1489 // details.
1490 template <typename... Storages, typename PtrType, typename Method,
1491 typename... Args>
1492 already_AddRefed<detail::OwningRunnableMethod<PtrType, Method>>
1493 NewRunnableMethod(const char* aName, PtrType&& aPtr, Method aMethod,
1494 Args&&... aArgs) {
1495 static_assert(sizeof...(Storages) == sizeof...(Args),
1496 "<Storages...> size should be equal to number of arguments");
1497 return do_AddRef(
1498 new detail::OwningRunnableMethodImpl<PtrType, Method, Storages...>(
1499 aName, std::forward<PtrType>(aPtr), aMethod,
1500 std::forward<Args>(aArgs)...));
1503 template <typename... Storages, typename PtrType, typename Method,
1504 typename... Args>
1505 already_AddRefed<detail::NonOwningRunnableMethod<PtrType, Method>>
1506 NewNonOwningRunnableMethod(const char* aName, PtrType&& aPtr, Method aMethod,
1507 Args&&... aArgs) {
1508 static_assert(sizeof...(Storages) == sizeof...(Args),
1509 "<Storages...> size should be equal to number of arguments");
1510 return do_AddRef(
1511 new detail::NonOwningRunnableMethodImpl<PtrType, Method, Storages...>(
1512 aName, std::forward<PtrType>(aPtr), aMethod,
1513 std::forward<Args>(aArgs)...));
1516 template <typename... Storages, typename PtrType, typename Method,
1517 typename... Args>
1518 already_AddRefed<detail::CancelableRunnableMethod<PtrType, Method>>
1519 NewCancelableRunnableMethod(const char* aName, PtrType&& aPtr, Method aMethod,
1520 Args&&... aArgs) {
1521 static_assert(sizeof...(Storages) == sizeof...(Args),
1522 "<Storages...> size should be equal to number of arguments");
1523 return do_AddRef(
1524 new detail::CancelableRunnableMethodImpl<PtrType, Method, Storages...>(
1525 aName, std::forward<PtrType>(aPtr), aMethod,
1526 std::forward<Args>(aArgs)...));
1529 template <typename... Storages, typename PtrType, typename Method,
1530 typename... Args>
1531 already_AddRefed<detail::NonOwningCancelableRunnableMethod<PtrType, Method>>
1532 NewNonOwningCancelableRunnableMethod(const char* aName, PtrType&& aPtr,
1533 Method aMethod, Args&&... aArgs) {
1534 static_assert(sizeof...(Storages) == sizeof...(Args),
1535 "<Storages...> size should be equal to number of arguments");
1536 return do_AddRef(
1537 new detail::NonOwningCancelableRunnableMethodImpl<PtrType, Method,
1538 Storages...>(
1539 aName, std::forward<PtrType>(aPtr), aMethod,
1540 std::forward<Args>(aArgs)...));
1543 template <typename... Storages, typename PtrType, typename Method,
1544 typename... Args>
1545 already_AddRefed<detail::IdleRunnableMethod<PtrType, Method>>
1546 NewIdleRunnableMethod(const char* aName, PtrType&& aPtr, Method aMethod,
1547 Args&&... aArgs) {
1548 static_assert(sizeof...(Storages) == sizeof...(Args),
1549 "<Storages...> size should be equal to number of arguments");
1550 return do_AddRef(
1551 new detail::IdleRunnableMethodImpl<PtrType, Method, Storages...>(
1552 aName, std::forward<PtrType>(aPtr), aMethod,
1553 std::forward<Args>(aArgs)...));
1556 template <typename... Storages, typename PtrType, typename Method,
1557 typename... Args>
1558 already_AddRefed<detail::NonOwningIdleRunnableMethod<PtrType, Method>>
1559 NewNonOwningIdleRunnableMethod(const char* aName, PtrType&& aPtr,
1560 Method aMethod, Args&&... aArgs) {
1561 static_assert(sizeof...(Storages) == sizeof...(Args),
1562 "<Storages...> size should be equal to number of arguments");
1563 return do_AddRef(
1564 new detail::NonOwningIdleRunnableMethodImpl<PtrType, Method, Storages...>(
1565 aName, std::forward<PtrType>(aPtr), aMethod,
1566 std::forward<Args>(aArgs)...));
1569 } // namespace mozilla
1571 #endif // XPCOM_GLUE_AVOID_NSPR
1573 // This class is designed to be used when you have an event class E that has a
1574 // pointer back to resource class R. If R goes away while E is still pending,
1575 // then it is important to "revoke" E so that it does not try use R after R has
1576 // been destroyed. nsRevocableEventPtr makes it easy for R to manage such
1577 // situations:
1579 // class R;
1581 // class E : public mozilla::Runnable {
1582 // public:
1583 // void Revoke() {
1584 // mResource = nullptr;
1585 // }
1586 // private:
1587 // R *mResource;
1588 // };
1590 // class R {
1591 // public:
1592 // void EventHandled() {
1593 // mEvent.Forget();
1594 // }
1595 // private:
1596 // nsRevocableEventPtr<E> mEvent;
1597 // };
1599 // void R::PostEvent() {
1600 // // Make sure any pending event is revoked.
1601 // mEvent->Revoke();
1603 // nsCOMPtr<nsIRunnable> event = new E();
1604 // if (NS_SUCCEEDED(NS_DispatchToCurrentThread(event))) {
1605 // // Keep pointer to event so we can revoke it.
1606 // mEvent = event;
1607 // }
1608 // }
1610 // NS_IMETHODIMP E::Run() {
1611 // if (!mResource)
1612 // return NS_OK;
1613 // ...
1614 // mResource->EventHandled();
1615 // return NS_OK;
1616 // }
1618 template <class T>
1619 class nsRevocableEventPtr {
1620 public:
1621 nsRevocableEventPtr() : mEvent(nullptr) {}
1622 ~nsRevocableEventPtr() { Revoke(); }
1624 const nsRevocableEventPtr& operator=(RefPtr<T>&& aEvent) {
1625 if (mEvent != aEvent) {
1626 Revoke();
1627 mEvent = std::move(aEvent);
1629 return *this;
1632 void Revoke() {
1633 if (mEvent) {
1634 mEvent->Revoke();
1635 mEvent = nullptr;
1639 void Forget() { mEvent = nullptr; }
1640 bool IsPending() { return mEvent != nullptr; }
1641 T* get() { return mEvent; }
1643 private:
1644 // Not implemented
1645 nsRevocableEventPtr(const nsRevocableEventPtr&);
1646 nsRevocableEventPtr& operator=(const nsRevocableEventPtr&);
1648 RefPtr<T> mEvent;
1651 template <class T>
1652 inline already_AddRefed<T> do_AddRef(nsRevocableEventPtr<T>& aObj) {
1653 return do_AddRef(aObj.get());
1657 * A simple helper to suffix thread pool name
1658 * with incremental numbers.
1660 class nsThreadPoolNaming {
1661 public:
1662 nsThreadPoolNaming() = default;
1665 * Returns a thread name as "<aPoolName> #<n>" and increments the counter.
1667 nsCString GetNextThreadName(const nsACString& aPoolName);
1669 template <size_t LEN>
1670 nsCString GetNextThreadName(const char (&aPoolName)[LEN]) {
1671 return GetNextThreadName(nsDependentCString(aPoolName, LEN - 1));
1674 private:
1675 mozilla::Atomic<uint32_t> mCounter{0};
1677 nsThreadPoolNaming(const nsThreadPoolNaming&) = delete;
1678 void operator=(const nsThreadPoolNaming&) = delete;
1682 * Thread priority in most operating systems affect scheduling, not IO. This
1683 * helper is used to set the current thread to low IO priority for the lifetime
1684 * of the created object. You can only use this low priority IO setting within
1685 * the context of the current thread.
1687 class MOZ_STACK_CLASS nsAutoLowPriorityIO {
1688 public:
1689 nsAutoLowPriorityIO();
1690 ~nsAutoLowPriorityIO();
1692 private:
1693 bool lowIOPrioritySet;
1694 #if defined(XP_MACOSX)
1695 int oldPriority;
1696 #endif
1699 void NS_SetMainThread();
1701 // Used only on cooperatively scheduled "main" threads. Causes the thread to be
1702 // considered a main thread and also causes GetCurrentVirtualThread to return
1703 // aVirtualThread.
1704 void NS_SetMainThread(PRThread* aVirtualThread);
1706 // Used only on cooperatively scheduled "main" threads. Causes the thread to no
1707 // longer be considered a main thread. Also causes GetCurrentVirtualThread() to
1708 // return a unique value.
1709 void NS_UnsetMainThread();
1712 * Return the expiration time of the next timer to run on the current
1713 * thread. If that expiration time is greater than aDefault, then
1714 * return aDefault. aSearchBound specifies a maximum number of timers
1715 * to examine to find a timer on the current thread. If no timer that
1716 * will run on the current thread is found after examining
1717 * aSearchBound timers, return the highest seen expiration time as a
1718 * best effort guess.
1720 * Timers with either the type nsITimer::TYPE_ONE_SHOT_LOW_PRIORITY or
1721 * nsITIMER::TYPE_REPEATING_SLACK_LOW_PRIORITY will be skipped when
1722 * searching for the next expiration time. This enables timers to
1723 * have lower priority than callbacks dispatched from
1724 * nsIThread::IdleDispatch.
1726 extern mozilla::TimeStamp NS_GetTimerDeadlineHintOnCurrentThread(
1727 mozilla::TimeStamp aDefault, uint32_t aSearchBound);
1730 * Dispatches the given event to a background thread. The primary benefit of
1731 * this API is that you do not have to manage the lifetime of your own thread
1732 * for running your own events; the thread manager will take care of the
1733 * background thread's lifetime. Not having to manage your own thread also
1734 * means less resource usage, as the underlying implementation here can manage
1735 * spinning up and shutting down threads appropriately.
1737 * NOTE: there is no guarantee that events dispatched via these APIs are run
1738 * serially, in dispatch order; several dispatched events may run in parallel.
1739 * If you depend on serial execution of dispatched events, you should use
1740 * NS_CreateBackgroundTaskQueue instead, and dispatch events to the returned
1741 * event target.
1743 extern nsresult NS_DispatchBackgroundTask(
1744 already_AddRefed<nsIRunnable> aEvent,
1745 uint32_t aDispatchFlags = NS_DISPATCH_NORMAL);
1746 extern "C" nsresult NS_DispatchBackgroundTask(
1747 nsIRunnable* aEvent, uint32_t aDispatchFlags = NS_DISPATCH_NORMAL);
1750 * Obtain a new serial event target that dispatches runnables to a background
1751 * thread. In many cases, this is a straight replacement for creating your
1752 * own, private thread, and is generally preferred to creating your own,
1753 * private thread.
1755 extern "C" nsresult NS_CreateBackgroundTaskQueue(
1756 const char* aName, nsISerialEventTarget** aTarget);
1759 * Dispatch the given runnable to the given event target, spinning the current
1760 * thread's event loop until the runnable has finished executing.
1762 * This is roughly equivalent to the previously-supported `NS_DISPATCH_SYNC`
1763 * flag.
1765 extern nsresult NS_DispatchAndSpinEventLoopUntilComplete(
1766 const nsACString& aVeryGoodReasonToDoThis, nsIEventTarget* aEventTarget,
1767 already_AddRefed<nsIRunnable> aEvent);
1769 // Predeclaration for logging function below
1770 namespace IPC {
1771 class Message;
1772 class MessageReader;
1773 class MessageWriter;
1774 } // namespace IPC
1776 class nsTimerImpl;
1778 namespace mozilla {
1780 // RAII class that will set the TLS entry to return the currently running
1781 // nsISerialEventTarget.
1782 // It should be used from inner event loop implementation.
1783 class SerialEventTargetGuard {
1784 public:
1785 explicit SerialEventTargetGuard(nsISerialEventTarget* aThread)
1786 : mLastCurrentThread(sCurrentThreadTLS.get()) {
1787 Set(aThread);
1790 ~SerialEventTargetGuard() { sCurrentThreadTLS.set(mLastCurrentThread); }
1792 static void InitTLS();
1793 static nsISerialEventTarget* GetCurrentSerialEventTarget() {
1794 return sCurrentThreadTLS.get();
1797 protected:
1798 friend class ::MessageLoop;
1799 static void Set(nsISerialEventTarget* aThread) {
1800 MOZ_ASSERT(aThread->IsOnCurrentThread());
1801 sCurrentThreadTLS.set(aThread);
1804 private:
1805 static MOZ_THREAD_LOCAL(nsISerialEventTarget*) sCurrentThreadTLS;
1806 nsISerialEventTarget* mLastCurrentThread;
1809 // Get the serial event target corresponding to the currently executing task
1810 // queue or thread. This method will assert if called on a thread pool without
1811 // an active task queue.
1813 // This function should generally be preferred over NS_GetCurrentThread since it
1814 // will return a more useful answer when called from a task queue running on a
1815 // thread pool or on a non-xpcom thread which accepts runnable dispatches.
1817 // NOTE: The returned nsISerialEventTarget may not accept runnable dispatches
1818 // (e.g. if it corresponds to a non-xpcom thread), however it may still be used
1819 // to check if you're on the given thread/queue using IsOnCurrentThread().
1821 nsISerialEventTarget* GetCurrentSerialEventTarget();
1823 // Get a weak reference to a serial event target which can be used to dispatch
1824 // runnables to the main thread.
1826 // NOTE: While this is currently a weak pointer to the nsIThread* returned from
1827 // NS_GetMainThread(), this may change in the future.
1829 nsISerialEventTarget* GetMainThreadSerialEventTarget();
1831 // Returns the number of CPUs, like PR_GetNumberOfProcessors, except
1832 // that it can return a cached value on platforms where sandboxing
1833 // would prevent reading the current value (currently Linux). CPU
1834 // hotplugging is uncommon, so this is unlikely to make a difference
1835 // in practice.
1836 size_t GetNumberOfProcessors();
1839 * A helper class to log tasks dispatch and run with "MOZ_LOG=events:1". The
1840 * output is more machine readable and creates a link between dispatch and run.
1842 * Usage example for the concrete template type nsIRunnable.
1843 * To log a dispatch, which means putting an event to a queue:
1844 * LogRunnable::LogDispatch(event);
1845 * theQueue.putEvent(event);
1847 * To log execution (running) of the event:
1848 * nsCOMPtr<nsIRunnable> event = theQueue.popEvent();
1850 * LogRunnable::Run log(event);
1851 * event->Run();
1852 * event = null; // to include the destructor code in the span
1855 * The class is a template so that we can support various specific super-types
1856 * of tasks in the future. We can't use void* because it may cast differently
1857 * and tracking the pointer in logs would then be impossible.
1859 template <typename T>
1860 class LogTaskBase {
1861 public:
1862 LogTaskBase() = delete;
1864 // Adds a simple log about dispatch of this runnable.
1865 static void LogDispatch(T* aEvent);
1866 // The `aContext` pointer adds another uniqe identifier, nothing more
1867 static void LogDispatch(T* aEvent, void* aContext);
1869 // Logs dispatch of the message and along that also the PID of the target
1870 // proccess, purposed for uniquely identifying IPC messages.
1871 static void LogDispatchWithPid(T* aEvent, int32_t aPid);
1873 // This is designed to surround a call to `Run()` or any code representing
1874 // execution of the task body.
1875 // The constructor adds a simple log about start of the runnable execution and
1876 // the destructor adds a log about ending the execution.
1877 class MOZ_RAII Run {
1878 public:
1879 Run() = delete;
1880 explicit Run(T* aEvent, bool aWillRunAgain = false);
1881 explicit Run(T* aEvent, void* aContext, bool aWillRunAgain = false);
1882 ~Run();
1884 // When this is called, the log in this RAII dtor will only say
1885 // "interrupted" expecting that the event will run again.
1886 void WillRunAgain() { mWillRunAgain = true; }
1888 private:
1889 bool mWillRunAgain = false;
1893 class MicroTaskRunnable;
1894 class Task; // TaskController
1895 class PresShell;
1896 namespace dom {
1897 class FrameRequestCallback;
1898 } // namespace dom
1900 // Specialized methods must be explicitly predeclared.
1901 template <>
1902 LogTaskBase<nsIRunnable>::Run::Run(nsIRunnable* aEvent, bool aWillRunAgain);
1903 template <>
1904 LogTaskBase<Task>::Run::Run(Task* aTask, bool aWillRunAgain);
1905 template <>
1906 void LogTaskBase<IPC::Message>::LogDispatchWithPid(IPC::Message* aEvent,
1907 int32_t aPid);
1908 template <>
1909 LogTaskBase<IPC::Message>::Run::Run(IPC::Message* aMessage, bool aWillRunAgain);
1910 template <>
1911 LogTaskBase<nsTimerImpl>::Run::Run(nsTimerImpl* aEvent, bool aWillRunAgain);
1913 typedef LogTaskBase<nsIRunnable> LogRunnable;
1914 typedef LogTaskBase<MicroTaskRunnable> LogMicroTaskRunnable;
1915 typedef LogTaskBase<IPC::Message> LogIPCMessage;
1916 typedef LogTaskBase<nsTimerImpl> LogTimerEvent;
1917 typedef LogTaskBase<Task> LogTask;
1918 typedef LogTaskBase<PresShell> LogPresShellObserver;
1919 typedef LogTaskBase<dom::FrameRequestCallback> LogFrameRequestCallback;
1920 // If you add new types don't forget to add:
1921 // `template class LogTaskBase<YourType>;` to nsThreadUtils.cpp
1923 } // namespace mozilla
1925 #endif // nsThreadUtils_h__