Bug 1907460 - Disable overflow/underflow events in release r=emilio,extension-reviewe...
[gecko.git] / xpcom / threads / nsThreadUtils.h
blob4a03b50e8300cc50efbcae213bde28119eb514dd
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 T>
566 struct RemoveSmartPointerHelper {
567 using Type = T;
570 template <typename T>
571 struct RemoveSmartPointerHelper<RefPtr<T>> {
572 using Type = T;
575 template <typename T>
576 struct RemoveSmartPointerHelper<nsCOMPtr<T>> {
577 using Type = T;
580 template <typename T>
581 struct RemoveRawOrSmartPointerHelper {
582 using Type = typename RemoveSmartPointerHelper<T>::Type;
585 template <typename T>
586 struct RemoveRawOrSmartPointerHelper<T*> {
587 using Type = T;
590 } // namespace detail
592 template <typename T>
593 using RemoveSmartPointer =
594 typename detail::RemoveSmartPointerHelper<std::remove_cv_t<T>>::Type;
596 template <typename T>
597 using RemoveRawOrSmartPointer =
598 typename detail::RemoveRawOrSmartPointerHelper<std::remove_cv_t<T>>::Type;
600 } // namespace mozilla
602 inline nsISupports* ToSupports(mozilla::Runnable* p) {
603 return static_cast<nsIRunnable*>(p);
606 template <typename Function>
607 already_AddRefed<mozilla::Runnable> NS_NewRunnableFunction(
608 const char* aName, Function&& aFunction) {
609 // We store a non-reference in RunnableFunction, but still forward aFunction
610 // to move if possible.
611 return do_AddRef(new mozilla::detail::RunnableFunctionImpl<Function>(
612 aName, std::forward<Function>(aFunction)));
615 // Creates a new object implementing nsIRunnable and nsICancelableRunnable,
616 // which runs a given function on Run and clears the stored function object on a
617 // call to `Cancel` (and thus destroys all objects it holds).
618 template <typename Function>
619 already_AddRefed<mozilla::CancelableRunnable> NS_NewCancelableRunnableFunction(
620 const char* aName, Function&& aFunc) {
621 class FuncCancelableRunnable final : public mozilla::CancelableRunnable {
622 public:
623 static_assert(
624 std::is_void_v<
625 decltype(std::declval<std::remove_reference_t<Function>>()())>);
627 NS_INLINE_DECL_REFCOUNTING_INHERITED(FuncCancelableRunnable,
628 CancelableRunnable)
630 explicit FuncCancelableRunnable(const char* aName, Function&& aFunc)
631 : CancelableRunnable{aName},
632 mFunc{mozilla::Some(std::forward<Function>(aFunc))} {}
634 NS_IMETHOD Run() override {
635 if (mFunc) {
636 (*mFunc)();
639 return NS_OK;
642 nsresult Cancel() override {
643 mFunc.reset();
644 return NS_OK;
647 private:
648 ~FuncCancelableRunnable() = default;
650 mozilla::Maybe<std::remove_reference_t<Function>> mFunc;
653 return mozilla::MakeAndAddRef<FuncCancelableRunnable>(
654 aName, std::forward<Function>(aFunc));
657 namespace mozilla {
658 namespace detail {
660 template <RunnableKind Kind>
661 class TimerBehaviour {
662 public:
663 nsITimer* GetTimer() { return nullptr; }
664 void CancelTimer() {}
666 protected:
667 ~TimerBehaviour() = default;
670 template <>
671 class TimerBehaviour<RunnableKind::IdleWithTimer> {
672 public:
673 nsITimer* GetTimer() {
674 if (!mTimer) {
675 mTimer = NS_NewTimer();
678 return mTimer;
681 void CancelTimer() {
682 if (mTimer) {
683 mTimer->Cancel();
687 protected:
688 ~TimerBehaviour() { CancelTimer(); }
690 private:
691 nsCOMPtr<nsITimer> mTimer;
694 } // namespace detail
695 } // namespace mozilla
697 // An event that can be used to call a method on a class. The class type must
698 // support reference counting. This event supports Revoke for use
699 // with nsRevocableEventPtr.
700 template <class ClassType, typename ReturnType = void, bool Owning = true,
701 mozilla::RunnableKind Kind = mozilla::RunnableKind::Standard>
702 class nsRunnableMethod
703 : public std::conditional_t<
704 Kind == mozilla::RunnableKind::Standard, mozilla::Runnable,
705 std::conditional_t<Kind == mozilla::RunnableKind::Cancelable,
706 mozilla::CancelableRunnable,
707 mozilla::CancelableIdleRunnable>>,
708 protected mozilla::detail::TimerBehaviour<Kind> {
709 using BaseType = std::conditional_t<
710 Kind == mozilla::RunnableKind::Standard, mozilla::Runnable,
711 std::conditional_t<Kind == mozilla::RunnableKind::Cancelable,
712 mozilla::CancelableRunnable,
713 mozilla::CancelableIdleRunnable>>;
715 public:
716 nsRunnableMethod(const char* aName) : BaseType(aName) {}
718 virtual void Revoke() = 0;
720 // These ReturnTypeEnforcer classes disallow return types that
721 // we know are not safe. The default ReturnTypeEnforcer compiles just fine but
722 // already_AddRefed will not.
723 template <typename OtherReturnType>
724 class ReturnTypeEnforcer {
725 public:
726 typedef int ReturnTypeIsSafe;
729 template <class T>
730 class ReturnTypeEnforcer<already_AddRefed<T>> {
731 // No ReturnTypeIsSafe makes this illegal!
734 // Make sure this return type is safe.
735 typedef typename ReturnTypeEnforcer<ReturnType>::ReturnTypeIsSafe check;
738 template <class ClassType, bool Owning>
739 struct nsRunnableMethodReceiver {
740 RefPtr<ClassType> mObj;
741 explicit nsRunnableMethodReceiver(ClassType* aObj) : mObj(aObj) {}
742 explicit nsRunnableMethodReceiver(RefPtr<ClassType>&& aObj)
743 : mObj(std::move(aObj)) {}
744 ~nsRunnableMethodReceiver() { Revoke(); }
745 ClassType* Get() const { return mObj.get(); }
746 void Revoke() { mObj = nullptr; }
749 template <class ClassType>
750 struct nsRunnableMethodReceiver<ClassType, false> {
751 ClassType* MOZ_NON_OWNING_REF mObj;
752 explicit nsRunnableMethodReceiver(ClassType* aObj) : mObj(aObj) {}
753 ClassType* Get() const { return mObj; }
754 void Revoke() { mObj = nullptr; }
757 static inline constexpr bool IsIdle(mozilla::RunnableKind aKind) {
758 return aKind == mozilla::RunnableKind::Idle ||
759 aKind == mozilla::RunnableKind::IdleWithTimer;
762 template <typename PtrType, typename Method, bool Owning,
763 mozilla::RunnableKind Kind>
764 struct nsRunnableMethodTraits;
766 template <typename PtrType, class C, typename R, bool Owning,
767 mozilla::RunnableKind Kind, typename... As>
768 struct nsRunnableMethodTraits<PtrType, R (C::*)(As...), Owning, Kind> {
769 using class_type = mozilla::RemoveRawOrSmartPointer<PtrType>;
770 static_assert(std::is_base_of<C, class_type>::value,
771 "Stored class must inherit from method's class");
772 using return_type = R;
773 using base_type = nsRunnableMethod<C, R, Owning, Kind>;
774 static const bool can_cancel = Kind == mozilla::RunnableKind::Cancelable;
777 template <typename PtrType, class C, typename R, bool Owning,
778 mozilla::RunnableKind Kind, typename... As>
779 struct nsRunnableMethodTraits<PtrType, R (C::*)(As...) const, Owning, Kind> {
780 using class_type = const mozilla::RemoveRawOrSmartPointer<PtrType>;
781 static_assert(std::is_base_of<C, class_type>::value,
782 "Stored class must inherit from method's class");
783 using return_type = R;
784 using base_type = nsRunnableMethod<C, R, Owning, Kind>;
785 static const bool can_cancel = Kind == mozilla::RunnableKind::Cancelable;
788 # ifdef NS_HAVE_STDCALL
789 template <typename PtrType, class C, typename R, bool Owning,
790 mozilla::RunnableKind Kind, typename... As>
791 struct nsRunnableMethodTraits<PtrType, R (__stdcall C::*)(As...), Owning,
792 Kind> {
793 using class_type = mozilla::RemoveRawOrSmartPointer<PtrType>;
794 static_assert(std::is_base_of<C, class_type>::value,
795 "Stored class must inherit from method's class");
796 using return_type = R;
797 using base_type = nsRunnableMethod<C, R, Owning, Kind>;
798 static const bool can_cancel = Kind == mozilla::RunnableKind::Cancelable;
801 template <typename PtrType, class C, typename R, bool Owning,
802 mozilla::RunnableKind Kind>
803 struct nsRunnableMethodTraits<PtrType, R (NS_STDCALL C::*)(), Owning, Kind> {
804 using class_type = mozilla::RemoveRawOrSmartPointer<PtrType>;
805 static_assert(std::is_base_of<C, class_type>::value,
806 "Stored class must inherit from method's class");
807 using return_type = R;
808 using base_type = nsRunnableMethod<C, R, Owning, Kind>;
809 static const bool can_cancel = Kind == mozilla::RunnableKind::Cancelable;
812 template <typename PtrType, class C, typename R, bool Owning,
813 mozilla::RunnableKind Kind, typename... As>
814 struct nsRunnableMethodTraits<PtrType, R (__stdcall C::*)(As...) const, Owning,
815 Kind> {
816 using class_type = const mozilla::RemoveRawOrSmartPointer<PtrType>;
817 static_assert(std::is_base_of<C, class_type>::value,
818 "Stored class must inherit from method's class");
819 using return_type = R;
820 using base_type = nsRunnableMethod<C, R, Owning, Kind>;
821 static const bool can_cancel = Kind == mozilla::RunnableKind::Cancelable;
824 template <typename PtrType, class C, typename R, bool Owning,
825 mozilla::RunnableKind Kind>
826 struct nsRunnableMethodTraits<PtrType, R (NS_STDCALL C::*)() const, Owning,
827 Kind> {
828 using class_type = const mozilla::RemoveRawOrSmartPointer<PtrType>;
829 static_assert(std::is_base_of<C, class_type>::value,
830 "Stored class must inherit from method's class");
831 using return_type = R;
832 using base_type = nsRunnableMethod<C, R, Owning, Kind>;
833 static const bool can_cancel = Kind == mozilla::RunnableKind::Cancelable;
835 # endif
837 // IsParameterStorageClass<T>::value is true if T is a parameter-storage class
838 // that will be recognized by NS_New[NonOwning]RunnableMethodWithArg[s] to
839 // force a specific storage&passing strategy (instead of inferring one,
840 // see ParameterStorage).
841 // When creating a new storage class, add a specialization for it to be
842 // recognized.
843 template <typename T>
844 struct IsParameterStorageClass : public std::false_type {};
846 // StoreXPassByY structs used to inform nsRunnableMethodArguments how to
847 // store arguments, and how to pass them to the target method.
849 template <typename T>
850 struct StoreCopyPassByConstLRef {
851 using stored_type = std::decay_t<T>;
852 typedef const stored_type& passed_type;
853 stored_type m;
854 template <typename A>
855 MOZ_IMPLICIT StoreCopyPassByConstLRef(A&& a) : m(std::forward<A>(a)) {}
856 passed_type PassAsParameter() { return m; }
858 template <typename S>
859 struct IsParameterStorageClass<StoreCopyPassByConstLRef<S>>
860 : public std::true_type {};
862 template <typename T>
863 struct StoreCopyPassByRRef {
864 using stored_type = std::decay_t<T>;
865 typedef stored_type&& passed_type;
866 stored_type m;
867 template <typename A>
868 MOZ_IMPLICIT StoreCopyPassByRRef(A&& a) : m(std::forward<A>(a)) {}
869 passed_type PassAsParameter() { return std::move(m); }
871 template <typename S>
872 struct IsParameterStorageClass<StoreCopyPassByRRef<S>> : public std::true_type {
875 template <typename T>
876 struct StoreRefPassByLRef {
877 typedef T& stored_type;
878 typedef T& passed_type;
879 stored_type m;
880 template <typename A>
881 MOZ_IMPLICIT StoreRefPassByLRef(A& a) : m(a) {}
882 passed_type PassAsParameter() { return m; }
884 template <typename S>
885 struct IsParameterStorageClass<StoreRefPassByLRef<S>> : public std::true_type {
888 template <typename T>
889 struct StoreConstRefPassByConstLRef {
890 typedef const T& stored_type;
891 typedef const T& passed_type;
892 stored_type m;
893 template <typename A>
894 MOZ_IMPLICIT StoreConstRefPassByConstLRef(const A& a) : m(a) {}
895 passed_type PassAsParameter() { return m; }
897 template <typename S>
898 struct IsParameterStorageClass<StoreConstRefPassByConstLRef<S>>
899 : public std::true_type {};
901 template <typename T>
902 struct StoreRefPtrPassByPtr {
903 typedef RefPtr<T> stored_type;
904 typedef T* passed_type;
905 stored_type m;
906 template <typename A>
907 MOZ_IMPLICIT StoreRefPtrPassByPtr(A&& a) : m(std::forward<A>(a)) {}
908 passed_type PassAsParameter() { return m.get(); }
910 template <typename S>
911 struct IsParameterStorageClass<StoreRefPtrPassByPtr<S>>
912 : public std::true_type {};
914 template <typename T>
915 struct StorePtrPassByPtr {
916 typedef T* stored_type;
917 typedef T* passed_type;
918 stored_type m;
919 template <typename A>
920 MOZ_IMPLICIT StorePtrPassByPtr(A a) : m(a) {}
921 passed_type PassAsParameter() { return m; }
923 template <typename S>
924 struct IsParameterStorageClass<StorePtrPassByPtr<S>> : public std::true_type {};
926 template <typename T>
927 struct StoreConstPtrPassByConstPtr {
928 typedef const T* stored_type;
929 typedef const T* passed_type;
930 stored_type m;
931 template <typename A>
932 MOZ_IMPLICIT StoreConstPtrPassByConstPtr(A a) : m(a) {}
933 passed_type PassAsParameter() { return m; }
935 template <typename S>
936 struct IsParameterStorageClass<StoreConstPtrPassByConstPtr<S>>
937 : public std::true_type {};
939 namespace detail {
941 template <typename>
942 struct SFINAE1True : std::true_type {};
944 template <class T>
945 static auto HasRefCountMethodsTest(int)
946 -> SFINAE1True<decltype(std::declval<T>().AddRef(),
947 std::declval<T>().Release())>;
948 template <class>
949 static auto HasRefCountMethodsTest(long) -> std::false_type;
951 template <class T>
952 constexpr static bool HasRefCountMethods =
953 decltype(HasRefCountMethodsTest<T>(0))::value;
955 // Choose storage&passing strategy based on preferred storage type:
956 // - If IsParameterStorageClass<T>::value is true, use as-is.
957 // - RC* -> StoreRefPtrPassByPtr<RC> :Store RefPtr<RC>, pass RC*
958 // ^^ RC quacks like a ref-counted type (i.e., has AddRef and Release methods)
959 // - const T* -> StoreConstPtrPassByConstPtr<T> :Store const T*, pass const T*
960 // - T* -> StorePtrPassByPtr<T> :Store T*, pass T*.
961 // - const T& -> StoreConstRefPassByConstLRef<T>:Store const T&, pass const T&.
962 // - T& -> StoreRefPassByLRef<T> :Store T&, pass T&.
963 // - T&& -> StoreCopyPassByRRef<T> :Store T, pass std::move(T).
964 // - RefPtr<T>, nsCOMPtr<T>
965 // -> StoreRefPtrPassByPtr<T> :Store RefPtr<T>, pass T*
966 // - Other T -> StoreCopyPassByConstLRef<T> :Store T, pass const T&.
968 // For anything less common, please use a lambda function rather than devising
969 // new parameter-storage classes. (In fact, consider doing that anyway.)
971 template <typename T>
972 struct OtherParameterStorage;
974 // The `IsParameterStorageClass` and `RC*` cases must be handled separately (see
975 // `ParameterStorageHelper`, below) until we can use C++20 concepts.
977 template <typename T>
978 struct OtherParameterStorage<const T*> {
979 using Type = StoreConstPtrPassByConstPtr<T>;
982 template <typename T>
983 struct OtherParameterStorage<T*> {
984 using Type = StorePtrPassByPtr<T>;
987 template <typename T>
988 struct OtherParameterStorage<const T&> {
989 using Type = StoreConstRefPassByConstLRef<T>;
992 template <typename T>
993 struct OtherParameterStorage<T&> {
994 using Type = StoreRefPassByLRef<T>;
997 template <typename T>
998 struct OtherParameterStorage<RefPtr<T>> {
999 using Type = StoreRefPtrPassByPtr<T>;
1002 template <typename T>
1003 struct OtherParameterStorage<nsCOMPtr<T>> {
1004 using Type = StoreRefPtrPassByPtr<T>;
1007 template <typename T>
1008 struct OtherParameterStorage<T&&> {
1009 using Type = StoreCopyPassByRRef<T>;
1012 template <typename T>
1013 struct OtherParameterStorage<const T&&> {
1014 // This is good advice regardless of the types you're handling.
1015 static_assert(!SFINAE1True<T>::value, "please use a lambda function");
1018 // default impl.
1019 template <typename T>
1020 struct OtherParameterStorage {
1021 using Type = StoreCopyPassByConstLRef<T>;
1024 template <typename T, bool A = IsParameterStorageClass<T>::value,
1025 bool B = std::is_pointer_v<T> &&
1026 HasRefCountMethods<std::remove_pointer_t<T>>>
1027 struct ParameterStorageHelper;
1029 template <typename T, bool B>
1030 struct ParameterStorageHelper<T, true, B> {
1031 using Type = T;
1034 template <typename T>
1035 struct ParameterStorageHelper<T, false, true> {
1036 using Type = StoreRefPtrPassByPtr<std::remove_pointer_t<T>>;
1039 template <typename T>
1040 struct ParameterStorageHelper<T, false, false> {
1041 using Type = typename OtherParameterStorage<std::remove_cv_t<T>>::Type;
1044 template <typename T>
1045 struct ParameterStorage {
1046 using Type = typename ParameterStorageHelper<T>::Type;
1049 template <class T>
1050 static auto HasSetDeadlineTest(int)
1051 -> SFINAE1True<decltype(std::declval<T>().SetDeadline(
1052 std::declval<mozilla::TimeStamp>()))>;
1054 template <class T>
1055 static auto HasSetDeadlineTest(long) -> std::false_type;
1057 template <class T>
1058 struct HasSetDeadline : decltype(HasSetDeadlineTest<T>(0)) {};
1060 template <class T>
1061 std::enable_if_t<::detail::HasSetDeadline<T>::value> SetDeadlineImpl(
1062 T* aObj, mozilla::TimeStamp aTimeStamp) {
1063 aObj->SetDeadline(aTimeStamp);
1066 template <class T>
1067 std::enable_if_t<!::detail::HasSetDeadline<T>::value> SetDeadlineImpl(
1068 T* aObj, mozilla::TimeStamp aTimeStamp) {}
1069 } /* namespace detail */
1071 namespace mozilla {
1072 namespace detail {
1074 // struct used to store arguments and later apply them to a method.
1075 template <typename... Ts>
1076 struct RunnableMethodArguments final {
1077 std::tuple<typename ::detail::ParameterStorage<Ts>::Type...> mArguments;
1078 template <typename... As>
1079 explicit RunnableMethodArguments(As&&... aArguments)
1080 : mArguments(std::forward<As>(aArguments)...) {}
1081 template <class C, typename M>
1082 decltype(auto) apply(C* o, M m) {
1083 return std::apply(
1084 [&o, m](auto&&... args) {
1085 return ((*o).*m)(args.PassAsParameter()...);
1087 mArguments);
1091 template <typename PtrType, typename Method, bool Owning, RunnableKind Kind,
1092 typename... Storages>
1093 class RunnableMethodImpl final
1094 : public ::nsRunnableMethodTraits<PtrType, Method, Owning,
1095 Kind>::base_type {
1096 typedef typename ::nsRunnableMethodTraits<PtrType, Method, Owning, Kind>
1097 Traits;
1099 typedef typename Traits::class_type ClassType;
1100 typedef typename Traits::base_type BaseType;
1101 ::nsRunnableMethodReceiver<ClassType, Owning> mReceiver;
1102 Method mMethod;
1103 RunnableMethodArguments<Storages...> mArgs;
1104 using BaseType::CancelTimer;
1105 using BaseType::GetTimer;
1107 private:
1108 virtual ~RunnableMethodImpl() { Revoke(); };
1109 static void TimedOut(nsITimer* aTimer, void* aClosure) {
1110 static_assert(IsIdle(Kind), "Don't use me!");
1111 RefPtr<CancelableIdleRunnable> r =
1112 static_cast<CancelableIdleRunnable*>(aClosure);
1113 r->SetDeadline(TimeStamp());
1114 r->Run();
1115 r->Cancel();
1118 public:
1119 template <typename ForwardedPtrType, typename... Args>
1120 explicit RunnableMethodImpl(const char* aName, ForwardedPtrType&& aObj,
1121 Method aMethod, Args&&... aArgs)
1122 : BaseType(aName),
1123 mReceiver(std::forward<ForwardedPtrType>(aObj)),
1124 mMethod(aMethod),
1125 mArgs(std::forward<Args>(aArgs)...) {
1126 static_assert(sizeof...(Storages) == sizeof...(Args),
1127 "Storages and Args should have equal sizes");
1130 NS_IMETHOD Run() {
1131 CancelTimer();
1133 if (MOZ_LIKELY(mReceiver.Get())) {
1134 mArgs.apply(mReceiver.Get(), mMethod);
1137 return NS_OK;
1140 nsresult Cancel() {
1141 static_assert(Kind >= RunnableKind::Cancelable, "Don't use me!");
1142 Revoke();
1143 return NS_OK;
1146 void Revoke() {
1147 CancelTimer();
1148 mReceiver.Revoke();
1151 void SetDeadline(TimeStamp aDeadline) {
1152 if (MOZ_LIKELY(mReceiver.Get())) {
1153 ::detail::SetDeadlineImpl(mReceiver.Get(), aDeadline);
1157 void SetTimer(uint32_t aDelay, nsIEventTarget* aTarget) {
1158 MOZ_ASSERT(aTarget);
1160 if (nsCOMPtr<nsITimer> timer = GetTimer()) {
1161 timer->Cancel();
1162 timer->SetTarget(aTarget);
1163 timer->InitWithNamedFuncCallback(TimedOut, this, aDelay,
1164 nsITimer::TYPE_ONE_SHOT,
1165 "detail::RunnableMethodImpl::SetTimer");
1170 // Type aliases for NewRunnableMethod.
1171 template <typename PtrType, typename Method>
1172 using OwningRunnableMethod =
1173 typename ::nsRunnableMethodTraits<std::remove_reference_t<PtrType>, Method,
1174 true, RunnableKind::Standard>::base_type;
1175 template <typename PtrType, typename Method, typename... Storages>
1176 using OwningRunnableMethodImpl =
1177 RunnableMethodImpl<std::remove_reference_t<PtrType>, Method, true,
1178 RunnableKind::Standard, Storages...>;
1180 // Type aliases for NewCancelableRunnableMethod.
1181 template <typename PtrType, typename Method>
1182 using CancelableRunnableMethod =
1183 typename ::nsRunnableMethodTraits<std::remove_reference_t<PtrType>, Method,
1184 true,
1185 RunnableKind::Cancelable>::base_type;
1186 template <typename PtrType, typename Method, typename... Storages>
1187 using CancelableRunnableMethodImpl =
1188 RunnableMethodImpl<std::remove_reference_t<PtrType>, Method, true,
1189 RunnableKind::Cancelable, Storages...>;
1191 // Type aliases for NewIdleRunnableMethod.
1192 template <typename PtrType, typename Method>
1193 using IdleRunnableMethod =
1194 typename ::nsRunnableMethodTraits<std::remove_reference_t<PtrType>, Method,
1195 true, RunnableKind::Idle>::base_type;
1196 template <typename PtrType, typename Method, typename... Storages>
1197 using IdleRunnableMethodImpl =
1198 RunnableMethodImpl<std::remove_reference_t<PtrType>, Method, true,
1199 RunnableKind::Idle, Storages...>;
1201 // Type aliases for NewIdleRunnableMethodWithTimer.
1202 template <typename PtrType, typename Method>
1203 using IdleRunnableMethodWithTimer =
1204 typename ::nsRunnableMethodTraits<std::remove_reference_t<PtrType>, Method,
1205 true,
1206 RunnableKind::IdleWithTimer>::base_type;
1207 template <typename PtrType, typename Method, typename... Storages>
1208 using IdleRunnableMethodWithTimerImpl =
1209 RunnableMethodImpl<std::remove_reference_t<PtrType>, Method, true,
1210 RunnableKind::IdleWithTimer, Storages...>;
1212 // Type aliases for NewNonOwningRunnableMethod.
1213 template <typename PtrType, typename Method>
1214 using NonOwningRunnableMethod =
1215 typename ::nsRunnableMethodTraits<std::remove_reference_t<PtrType>, Method,
1216 false, RunnableKind::Standard>::base_type;
1217 template <typename PtrType, typename Method, typename... Storages>
1218 using NonOwningRunnableMethodImpl =
1219 RunnableMethodImpl<std::remove_reference_t<PtrType>, Method, false,
1220 RunnableKind::Standard, Storages...>;
1222 // Type aliases for NonOwningCancelableRunnableMethod
1223 template <typename PtrType, typename Method>
1224 using NonOwningCancelableRunnableMethod =
1225 typename ::nsRunnableMethodTraits<std::remove_reference_t<PtrType>, Method,
1226 false,
1227 RunnableKind::Cancelable>::base_type;
1228 template <typename PtrType, typename Method, typename... Storages>
1229 using NonOwningCancelableRunnableMethodImpl =
1230 RunnableMethodImpl<std::remove_reference_t<PtrType>, Method, false,
1231 RunnableKind::Cancelable, Storages...>;
1233 // Type aliases for NonOwningIdleRunnableMethod
1234 template <typename PtrType, typename Method>
1235 using NonOwningIdleRunnableMethod =
1236 typename ::nsRunnableMethodTraits<std::remove_reference_t<PtrType>, Method,
1237 false, RunnableKind::Idle>::base_type;
1238 template <typename PtrType, typename Method, typename... Storages>
1239 using NonOwningIdleRunnableMethodImpl =
1240 RunnableMethodImpl<std::remove_reference_t<PtrType>, Method, false,
1241 RunnableKind::Idle, Storages...>;
1243 // Type aliases for NewIdleRunnableMethodWithTimer.
1244 template <typename PtrType, typename Method>
1245 using NonOwningIdleRunnableMethodWithTimer =
1246 typename ::nsRunnableMethodTraits<std::remove_reference_t<PtrType>, Method,
1247 false,
1248 RunnableKind::IdleWithTimer>::base_type;
1249 template <typename PtrType, typename Method, typename... Storages>
1250 using NonOwningIdleRunnableMethodWithTimerImpl =
1251 RunnableMethodImpl<std::remove_reference_t<PtrType>, Method, false,
1252 RunnableKind::IdleWithTimer, Storages...>;
1254 } // namespace detail
1256 // NewRunnableMethod and friends
1258 // Very often in Gecko, you'll find yourself in a situation where you want
1259 // to invoke a method (with or without arguments) asynchronously. You
1260 // could write a small helper class inheriting from nsRunnable to handle
1261 // all these details, or you could let NewRunnableMethod take care of all
1262 // those details for you.
1264 // The simplest use of NewRunnableMethod looks like:
1266 // nsCOMPtr<nsIRunnable> event =
1267 // mozilla::NewRunnableMethod("description", myObject,
1268 // &MyClass::HandleEvent);
1269 // NS_DispatchToCurrentThread(event);
1271 // Statically enforced constraints:
1272 // - myObject must be of (or implicitly convertible to) type MyClass
1273 // - MyClass must define AddRef and Release methods
1275 // The "description" string should specify a human-readable name for the
1276 // runnable; the provided string is used by various introspection tools
1277 // in the browser.
1279 // The created runnable will take a strong reference to `myObject`. For
1280 // non-refcounted objects, or refcounted objects with unusual refcounting
1281 // requirements, and if and only if you are 110% certain that `myObject`
1282 // will live long enough, you can use NewNonOwningRunnableMethod instead,
1283 // which will, as its name implies, take a non-owning reference. If you
1284 // find yourself having to use this function, you should accompany your use
1285 // with a proof comment describing why the runnable will not lead to
1286 // use-after-frees.
1288 // (If you find yourself writing contorted code to Release() an object
1289 // asynchronously on a different thread, you should use the
1290 // NS_ProxyRelease function.)
1292 // Invoking a method with arguments takes a little more care. The
1293 // natural extension of the above:
1295 // nsCOMPtr<nsIRunnable> event =
1296 // mozilla::NewRunnableMethod("description", myObject,
1297 // &MyClass::HandleEvent,
1298 // arg1, arg2, ...);
1300 // can lead to security hazards (e.g. passing in raw pointers to refcounted
1301 // objects and storing those raw pointers in the runnable). We therefore
1302 // require you to specify the storage types used by the runnable, just as
1303 // you would if you were writing out the class by hand:
1305 // nsCOMPtr<nsIRunnable> event =
1306 // mozilla::NewRunnableMethod<RefPtr<T>, nsTArray<U>>
1307 // ("description", myObject, &MyClass::HandleEvent, arg1, arg2);
1309 // Please note that you do not have to pass the same argument type as you
1310 // specify in the template arguments. For example, if you want to transfer
1311 // ownership to a runnable, you can write:
1313 // RefPtr<T> ptr = ...;
1314 // nsTArray<U> array = ...;
1315 // nsCOMPtr<nsIRunnable> event =
1316 // mozilla::NewRunnableMethod<RefPtr<T>, nsTArray<U>>
1317 // ("description", myObject, &MyClass::DoSomething,
1318 // std::move(ptr), std::move(array));
1320 // and there will be no extra AddRef/Release traffic, or copying of the array.
1322 // Each type that you specify as a template argument to NewRunnableMethod
1323 // comes with its own style of storage in the runnable and its own style
1324 // of argument passing to the invoked method. See the comment for
1325 // ParameterStorage above for more details.
1327 // If you need to customize the storage type and/or argument passing type,
1328 // you can write your own class to use as a template argument to
1329 // NewRunnableMethod. If you find yourself having to do that frequently,
1330 // please file a bug in Core::XPCOM about adding the custom type to the
1331 // core code in this file, and/or for custom rules for ParameterStorage
1332 // to select that strategy.
1334 // For places that require you to use cancelable runnables, such as
1335 // workers, there's also NewCancelableRunnableMethod and its non-owning
1336 // counterpart. The runnables returned by these methods additionally
1337 // implement nsICancelableRunnable.
1339 // Finally, all of the functions discussed above have additional overloads
1340 // that do not take a `const char*` as their first parameter; you may see
1341 // these in older code. The `const char*` overload is preferred and
1342 // should be used in new code exclusively.
1344 template <typename PtrType, typename Method>
1345 already_AddRefed<detail::OwningRunnableMethod<PtrType, Method>>
1346 NewRunnableMethod(const char* aName, PtrType&& aPtr, Method aMethod) {
1347 return do_AddRef(new detail::OwningRunnableMethodImpl<PtrType, Method>(
1348 aName, std::forward<PtrType>(aPtr), aMethod));
1351 template <typename PtrType, typename Method>
1352 already_AddRefed<detail::CancelableRunnableMethod<PtrType, Method>>
1353 NewCancelableRunnableMethod(const char* aName, PtrType&& aPtr, Method aMethod) {
1354 return do_AddRef(new detail::CancelableRunnableMethodImpl<PtrType, Method>(
1355 aName, std::forward<PtrType>(aPtr), aMethod));
1358 template <typename PtrType, typename Method>
1359 already_AddRefed<detail::IdleRunnableMethod<PtrType, Method>>
1360 NewIdleRunnableMethod(const char* aName, PtrType&& aPtr, Method aMethod) {
1361 return do_AddRef(new detail::IdleRunnableMethodImpl<PtrType, Method>(
1362 aName, std::forward<PtrType>(aPtr), aMethod));
1365 template <typename PtrType, typename Method>
1366 already_AddRefed<detail::IdleRunnableMethodWithTimer<PtrType, Method>>
1367 NewIdleRunnableMethodWithTimer(const char* aName, PtrType&& aPtr,
1368 Method aMethod) {
1369 return do_AddRef(new detail::IdleRunnableMethodWithTimerImpl<PtrType, Method>(
1370 aName, std::forward<PtrType>(aPtr), aMethod));
1373 template <typename PtrType, typename Method>
1374 already_AddRefed<detail::NonOwningRunnableMethod<PtrType, Method>>
1375 NewNonOwningRunnableMethod(const char* aName, PtrType&& aPtr, Method aMethod) {
1376 return do_AddRef(new detail::NonOwningRunnableMethodImpl<PtrType, Method>(
1377 aName, std::forward<PtrType>(aPtr), aMethod));
1380 template <typename PtrType, typename Method>
1381 already_AddRefed<detail::NonOwningCancelableRunnableMethod<PtrType, Method>>
1382 NewNonOwningCancelableRunnableMethod(const char* aName, PtrType&& aPtr,
1383 Method aMethod) {
1384 return do_AddRef(
1385 new detail::NonOwningCancelableRunnableMethodImpl<PtrType, Method>(
1386 aName, std::forward<PtrType>(aPtr), aMethod));
1389 template <typename PtrType, typename Method>
1390 already_AddRefed<detail::NonOwningIdleRunnableMethod<PtrType, Method>>
1391 NewNonOwningIdleRunnableMethod(const char* aName, PtrType&& aPtr,
1392 Method aMethod) {
1393 return do_AddRef(new detail::NonOwningIdleRunnableMethodImpl<PtrType, Method>(
1394 aName, std::forward<PtrType>(aPtr), aMethod));
1397 template <typename PtrType, typename Method>
1398 already_AddRefed<detail::NonOwningIdleRunnableMethodWithTimer<PtrType, Method>>
1399 NewNonOwningIdleRunnableMethodWithTimer(const char* aName, PtrType&& aPtr,
1400 Method aMethod) {
1401 return do_AddRef(
1402 new detail::NonOwningIdleRunnableMethodWithTimerImpl<PtrType, Method>(
1403 aName, std::forward<PtrType>(aPtr), aMethod));
1406 // Similar to NewRunnableMethod. Call like so:
1407 // nsCOMPtr<nsIRunnable> event =
1408 // NewRunnableMethod<Types,...>(myObject, &MyClass::HandleEvent, myArg1,...);
1409 // 'Types' are the stored type for each argument, see ParameterStorage for
1410 // details.
1411 template <typename... Storages, typename PtrType, typename Method,
1412 typename... Args>
1413 already_AddRefed<detail::OwningRunnableMethod<PtrType, Method>>
1414 NewRunnableMethod(const char* aName, PtrType&& aPtr, Method aMethod,
1415 Args&&... aArgs) {
1416 static_assert(sizeof...(Storages) == sizeof...(Args),
1417 "<Storages...> size should be equal to number of arguments");
1418 return do_AddRef(
1419 new detail::OwningRunnableMethodImpl<PtrType, Method, Storages...>(
1420 aName, std::forward<PtrType>(aPtr), aMethod,
1421 std::forward<Args>(aArgs)...));
1424 template <typename... Storages, typename PtrType, typename Method,
1425 typename... Args>
1426 already_AddRefed<detail::NonOwningRunnableMethod<PtrType, Method>>
1427 NewNonOwningRunnableMethod(const char* aName, PtrType&& aPtr, Method aMethod,
1428 Args&&... aArgs) {
1429 static_assert(sizeof...(Storages) == sizeof...(Args),
1430 "<Storages...> size should be equal to number of arguments");
1431 return do_AddRef(
1432 new detail::NonOwningRunnableMethodImpl<PtrType, Method, Storages...>(
1433 aName, std::forward<PtrType>(aPtr), aMethod,
1434 std::forward<Args>(aArgs)...));
1437 template <typename... Storages, typename PtrType, typename Method,
1438 typename... Args>
1439 already_AddRefed<detail::CancelableRunnableMethod<PtrType, Method>>
1440 NewCancelableRunnableMethod(const char* aName, PtrType&& aPtr, Method aMethod,
1441 Args&&... aArgs) {
1442 static_assert(sizeof...(Storages) == sizeof...(Args),
1443 "<Storages...> size should be equal to number of arguments");
1444 return do_AddRef(
1445 new detail::CancelableRunnableMethodImpl<PtrType, Method, Storages...>(
1446 aName, std::forward<PtrType>(aPtr), aMethod,
1447 std::forward<Args>(aArgs)...));
1450 template <typename... Storages, typename PtrType, typename Method,
1451 typename... Args>
1452 already_AddRefed<detail::NonOwningCancelableRunnableMethod<PtrType, Method>>
1453 NewNonOwningCancelableRunnableMethod(const char* aName, PtrType&& aPtr,
1454 Method aMethod, Args&&... aArgs) {
1455 static_assert(sizeof...(Storages) == sizeof...(Args),
1456 "<Storages...> size should be equal to number of arguments");
1457 return do_AddRef(
1458 new detail::NonOwningCancelableRunnableMethodImpl<PtrType, Method,
1459 Storages...>(
1460 aName, std::forward<PtrType>(aPtr), aMethod,
1461 std::forward<Args>(aArgs)...));
1464 template <typename... Storages, typename PtrType, typename Method,
1465 typename... Args>
1466 already_AddRefed<detail::IdleRunnableMethod<PtrType, Method>>
1467 NewIdleRunnableMethod(const char* aName, PtrType&& aPtr, Method aMethod,
1468 Args&&... aArgs) {
1469 static_assert(sizeof...(Storages) == sizeof...(Args),
1470 "<Storages...> size should be equal to number of arguments");
1471 return do_AddRef(
1472 new detail::IdleRunnableMethodImpl<PtrType, Method, Storages...>(
1473 aName, std::forward<PtrType>(aPtr), aMethod,
1474 std::forward<Args>(aArgs)...));
1477 template <typename... Storages, typename PtrType, typename Method,
1478 typename... Args>
1479 already_AddRefed<detail::NonOwningIdleRunnableMethod<PtrType, Method>>
1480 NewNonOwningIdleRunnableMethod(const char* aName, PtrType&& aPtr,
1481 Method aMethod, Args&&... aArgs) {
1482 static_assert(sizeof...(Storages) == sizeof...(Args),
1483 "<Storages...> size should be equal to number of arguments");
1484 return do_AddRef(
1485 new detail::NonOwningIdleRunnableMethodImpl<PtrType, Method, Storages...>(
1486 aName, std::forward<PtrType>(aPtr), aMethod,
1487 std::forward<Args>(aArgs)...));
1490 } // namespace mozilla
1492 #endif // XPCOM_GLUE_AVOID_NSPR
1494 // This class is designed to be used when you have an event class E that has a
1495 // pointer back to resource class R. If R goes away while E is still pending,
1496 // then it is important to "revoke" E so that it does not try use R after R has
1497 // been destroyed. nsRevocableEventPtr makes it easy for R to manage such
1498 // situations:
1500 // class R;
1502 // class E : public mozilla::Runnable {
1503 // public:
1504 // void Revoke() {
1505 // mResource = nullptr;
1506 // }
1507 // private:
1508 // R *mResource;
1509 // };
1511 // class R {
1512 // public:
1513 // void EventHandled() {
1514 // mEvent.Forget();
1515 // }
1516 // private:
1517 // nsRevocableEventPtr<E> mEvent;
1518 // };
1520 // void R::PostEvent() {
1521 // // Make sure any pending event is revoked.
1522 // mEvent->Revoke();
1524 // nsCOMPtr<nsIRunnable> event = new E();
1525 // if (NS_SUCCEEDED(NS_DispatchToCurrentThread(event))) {
1526 // // Keep pointer to event so we can revoke it.
1527 // mEvent = event;
1528 // }
1529 // }
1531 // NS_IMETHODIMP E::Run() {
1532 // if (!mResource)
1533 // return NS_OK;
1534 // ...
1535 // mResource->EventHandled();
1536 // return NS_OK;
1537 // }
1539 template <class T>
1540 class nsRevocableEventPtr {
1541 public:
1542 nsRevocableEventPtr() : mEvent(nullptr) {}
1543 ~nsRevocableEventPtr() { Revoke(); }
1545 const nsRevocableEventPtr& operator=(RefPtr<T>&& aEvent) {
1546 if (mEvent != aEvent) {
1547 Revoke();
1548 mEvent = std::move(aEvent);
1550 return *this;
1553 void Revoke() {
1554 if (mEvent) {
1555 mEvent->Revoke();
1556 mEvent = nullptr;
1560 void Forget() { mEvent = nullptr; }
1561 bool IsPending() { return mEvent != nullptr; }
1562 T* get() { return mEvent; }
1564 private:
1565 // Not implemented
1566 nsRevocableEventPtr(const nsRevocableEventPtr&);
1567 nsRevocableEventPtr& operator=(const nsRevocableEventPtr&);
1569 RefPtr<T> mEvent;
1572 template <class T>
1573 inline already_AddRefed<T> do_AddRef(nsRevocableEventPtr<T>& aObj) {
1574 return do_AddRef(aObj.get());
1578 * A simple helper to suffix thread pool name
1579 * with incremental numbers.
1581 class nsThreadPoolNaming {
1582 public:
1583 nsThreadPoolNaming() = default;
1586 * Returns a thread name as "<aPoolName> #<n>" and increments the counter.
1588 nsCString GetNextThreadName(const nsACString& aPoolName);
1590 template <size_t LEN>
1591 nsCString GetNextThreadName(const char (&aPoolName)[LEN]) {
1592 return GetNextThreadName(nsDependentCString(aPoolName, LEN - 1));
1595 private:
1596 mozilla::Atomic<uint32_t> mCounter{0};
1598 nsThreadPoolNaming(const nsThreadPoolNaming&) = delete;
1599 void operator=(const nsThreadPoolNaming&) = delete;
1603 * Thread priority in most operating systems affect scheduling, not IO. This
1604 * helper is used to set the current thread to low IO priority for the lifetime
1605 * of the created object. You can only use this low priority IO setting within
1606 * the context of the current thread.
1608 class MOZ_STACK_CLASS nsAutoLowPriorityIO {
1609 public:
1610 nsAutoLowPriorityIO();
1611 ~nsAutoLowPriorityIO();
1613 private:
1614 bool lowIOPrioritySet;
1615 #if defined(XP_MACOSX)
1616 int oldPriority;
1617 #endif
1620 void NS_SetMainThread();
1622 // Used only on cooperatively scheduled "main" threads. Causes the thread to be
1623 // considered a main thread and also causes GetCurrentVirtualThread to return
1624 // aVirtualThread.
1625 void NS_SetMainThread(PRThread* aVirtualThread);
1627 // Used only on cooperatively scheduled "main" threads. Causes the thread to no
1628 // longer be considered a main thread. Also causes GetCurrentVirtualThread() to
1629 // return a unique value.
1630 void NS_UnsetMainThread();
1633 * Return the expiration time of the next timer to run on the current
1634 * thread. If that expiration time is greater than aDefault, then
1635 * return aDefault. aSearchBound specifies a maximum number of timers
1636 * to examine to find a timer on the current thread. If no timer that
1637 * will run on the current thread is found after examining
1638 * aSearchBound timers, return the highest seen expiration time as a
1639 * best effort guess.
1641 * Timers with either the type nsITimer::TYPE_ONE_SHOT_LOW_PRIORITY or
1642 * nsITIMER::TYPE_REPEATING_SLACK_LOW_PRIORITY will be skipped when
1643 * searching for the next expiration time. This enables timers to
1644 * have lower priority than callbacks dispatched from
1645 * nsIThread::IdleDispatch.
1647 extern mozilla::TimeStamp NS_GetTimerDeadlineHintOnCurrentThread(
1648 mozilla::TimeStamp aDefault, uint32_t aSearchBound);
1651 * Dispatches the given event to a background thread. The primary benefit of
1652 * this API is that you do not have to manage the lifetime of your own thread
1653 * for running your own events; the thread manager will take care of the
1654 * background thread's lifetime. Not having to manage your own thread also
1655 * means less resource usage, as the underlying implementation here can manage
1656 * spinning up and shutting down threads appropriately.
1658 * NOTE: there is no guarantee that events dispatched via these APIs are run
1659 * serially, in dispatch order; several dispatched events may run in parallel.
1660 * If you depend on serial execution of dispatched events, you should use
1661 * NS_CreateBackgroundTaskQueue instead, and dispatch events to the returned
1662 * event target.
1664 extern nsresult NS_DispatchBackgroundTask(
1665 already_AddRefed<nsIRunnable> aEvent,
1666 uint32_t aDispatchFlags = NS_DISPATCH_NORMAL);
1667 extern "C" nsresult NS_DispatchBackgroundTask(
1668 nsIRunnable* aEvent, uint32_t aDispatchFlags = NS_DISPATCH_NORMAL);
1671 * Obtain a new serial event target that dispatches runnables to a background
1672 * thread. In many cases, this is a straight replacement for creating your
1673 * own, private thread, and is generally preferred to creating your own,
1674 * private thread.
1676 extern "C" nsresult NS_CreateBackgroundTaskQueue(
1677 const char* aName, nsISerialEventTarget** aTarget);
1680 * Dispatch the given runnable to the given event target, spinning the current
1681 * thread's event loop until the runnable has finished executing.
1683 * This is roughly equivalent to the previously-supported `NS_DISPATCH_SYNC`
1684 * flag.
1686 extern nsresult NS_DispatchAndSpinEventLoopUntilComplete(
1687 const nsACString& aVeryGoodReasonToDoThis, nsIEventTarget* aEventTarget,
1688 already_AddRefed<nsIRunnable> aEvent);
1690 // Predeclaration for logging function below
1691 namespace IPC {
1692 class Message;
1693 class MessageReader;
1694 class MessageWriter;
1695 } // namespace IPC
1697 class nsTimerImpl;
1699 namespace mozilla {
1701 // RAII class that will set the TLS entry to return the currently running
1702 // nsISerialEventTarget.
1703 // It should be used from inner event loop implementation.
1704 class SerialEventTargetGuard {
1705 public:
1706 explicit SerialEventTargetGuard(nsISerialEventTarget* aThread)
1707 : mLastCurrentThread(sCurrentThreadTLS.get()) {
1708 Set(aThread);
1711 ~SerialEventTargetGuard() { sCurrentThreadTLS.set(mLastCurrentThread); }
1713 static void InitTLS();
1714 static nsISerialEventTarget* GetCurrentSerialEventTarget() {
1715 return sCurrentThreadTLS.get();
1718 protected:
1719 friend class ::MessageLoop;
1720 static void Set(nsISerialEventTarget* aThread) {
1721 MOZ_ASSERT(aThread->IsOnCurrentThread());
1722 sCurrentThreadTLS.set(aThread);
1725 private:
1726 static MOZ_THREAD_LOCAL(nsISerialEventTarget*) sCurrentThreadTLS;
1727 nsISerialEventTarget* mLastCurrentThread;
1730 // Get the serial event target corresponding to the currently executing task
1731 // queue or thread. This method will assert if called on a thread pool without
1732 // an active task queue.
1734 // This function should generally be preferred over NS_GetCurrentThread since it
1735 // will return a more useful answer when called from a task queue running on a
1736 // thread pool or on a non-xpcom thread which accepts runnable dispatches.
1738 // NOTE: The returned nsISerialEventTarget may not accept runnable dispatches
1739 // (e.g. if it corresponds to a non-xpcom thread), however it may still be used
1740 // to check if you're on the given thread/queue using IsOnCurrentThread().
1742 nsISerialEventTarget* GetCurrentSerialEventTarget();
1744 // Get a weak reference to a serial event target which can be used to dispatch
1745 // runnables to the main thread.
1747 // NOTE: While this is currently a weak pointer to the nsIThread* returned from
1748 // NS_GetMainThread(), this may change in the future.
1750 nsISerialEventTarget* GetMainThreadSerialEventTarget();
1752 // Returns the number of CPUs, like PR_GetNumberOfProcessors, except
1753 // that it can return a cached value on platforms where sandboxing
1754 // would prevent reading the current value (currently Linux). CPU
1755 // hotplugging is uncommon, so this is unlikely to make a difference
1756 // in practice.
1757 size_t GetNumberOfProcessors();
1760 * A helper class to log tasks dispatch and run with "MOZ_LOG=events:1". The
1761 * output is more machine readable and creates a link between dispatch and run.
1763 * Usage example for the concrete template type nsIRunnable.
1764 * To log a dispatch, which means putting an event to a queue:
1765 * LogRunnable::LogDispatch(event);
1766 * theQueue.putEvent(event);
1768 * To log execution (running) of the event:
1769 * nsCOMPtr<nsIRunnable> event = theQueue.popEvent();
1771 * LogRunnable::Run log(event);
1772 * event->Run();
1773 * event = null; // to include the destructor code in the span
1776 * The class is a template so that we can support various specific super-types
1777 * of tasks in the future. We can't use void* because it may cast differently
1778 * and tracking the pointer in logs would then be impossible.
1780 template <typename T>
1781 class LogTaskBase {
1782 public:
1783 LogTaskBase() = delete;
1785 // Adds a simple log about dispatch of this runnable.
1786 static void LogDispatch(T* aEvent);
1787 // The `aContext` pointer adds another uniqe identifier, nothing more
1788 static void LogDispatch(T* aEvent, void* aContext);
1790 // Logs dispatch of the message and along that also the PID of the target
1791 // proccess, purposed for uniquely identifying IPC messages.
1792 static void LogDispatchWithPid(T* aEvent, int32_t aPid);
1794 // This is designed to surround a call to `Run()` or any code representing
1795 // execution of the task body.
1796 // The constructor adds a simple log about start of the runnable execution and
1797 // the destructor adds a log about ending the execution.
1798 class MOZ_RAII Run {
1799 public:
1800 Run() = delete;
1801 explicit Run(T* aEvent, bool aWillRunAgain = false);
1802 explicit Run(T* aEvent, void* aContext, bool aWillRunAgain = false);
1803 ~Run();
1805 // When this is called, the log in this RAII dtor will only say
1806 // "interrupted" expecting that the event will run again.
1807 void WillRunAgain() { mWillRunAgain = true; }
1809 private:
1810 bool mWillRunAgain = false;
1814 class MicroTaskRunnable;
1815 class Task; // TaskController
1816 class PresShell;
1817 namespace dom {
1818 class FrameRequestCallback;
1819 class VideoFrameRequestCallback;
1820 } // namespace dom
1822 // Specialized methods must be explicitly predeclared.
1823 template <>
1824 LogTaskBase<nsIRunnable>::Run::Run(nsIRunnable* aEvent, bool aWillRunAgain);
1825 template <>
1826 LogTaskBase<Task>::Run::Run(Task* aTask, bool aWillRunAgain);
1827 template <>
1828 void LogTaskBase<IPC::Message>::LogDispatchWithPid(IPC::Message* aEvent,
1829 int32_t aPid);
1830 template <>
1831 LogTaskBase<IPC::Message>::Run::Run(IPC::Message* aMessage, bool aWillRunAgain);
1832 template <>
1833 LogTaskBase<nsTimerImpl>::Run::Run(nsTimerImpl* aEvent, bool aWillRunAgain);
1835 typedef LogTaskBase<nsIRunnable> LogRunnable;
1836 typedef LogTaskBase<MicroTaskRunnable> LogMicroTaskRunnable;
1837 typedef LogTaskBase<IPC::Message> LogIPCMessage;
1838 typedef LogTaskBase<nsTimerImpl> LogTimerEvent;
1839 typedef LogTaskBase<Task> LogTask;
1840 typedef LogTaskBase<PresShell> LogPresShellObserver;
1841 typedef LogTaskBase<dom::FrameRequestCallback> LogFrameRequestCallback;
1842 typedef LogTaskBase<dom::VideoFrameRequestCallback>
1843 LogVideoFrameRequestCallback;
1844 // If you add new types don't forget to add:
1845 // `template class LogTaskBase<YourType>;` to nsThreadUtils.cpp
1847 } // namespace mozilla
1849 #endif // nsThreadUtils_h__