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 nsProxyRelease_h__
8 #define nsProxyRelease_h__
12 #include "MainThreadUtils.h"
13 #include "mozilla/Likely.h"
14 #include "mozilla/Unused.h"
16 #include "nsIEventTarget.h"
17 #include "nsISerialEventTarget.h"
18 #include "nsIThread.h"
19 #include "nsPrintfCString.h"
20 #include "nsThreadUtils.h"
22 #ifdef XPCOM_GLUE_AVOID_NSPR
23 # error NS_ProxyRelease implementation depends on NSPR.
31 class ProxyReleaseEvent
: public mozilla::CancelableRunnable
{
33 ProxyReleaseEvent(const char* aName
, already_AddRefed
<T
> aDoomed
)
34 : CancelableRunnable(aName
), mDoomed(aDoomed
.take()) {}
36 NS_IMETHOD
Run() override
{
37 NS_IF_RELEASE(mDoomed
);
41 nsresult
Cancel() override
{ return Run(); }
43 #ifdef MOZ_COLLECTING_RUNNABLE_TELEMETRY
44 NS_IMETHOD
GetName(nsACString
& aName
) override
{
46 aName
.Append(nsPrintfCString("ProxyReleaseEvent for %s", mName
));
48 aName
.AssignLiteral("ProxyReleaseEvent");
55 T
* MOZ_OWNING_REF mDoomed
;
59 nsresult
ProxyRelease(const char* aName
, nsIEventTarget
* aTarget
,
60 already_AddRefed
<T
> aDoomed
, bool aAlwaysProxy
) {
61 // Auto-managing release of the pointer.
62 RefPtr
<T
> doomed
= aDoomed
;
65 if (!doomed
|| !aTarget
) {
66 return NS_ERROR_INVALID_ARG
;
70 bool onCurrentThread
= false;
71 rv
= aTarget
->IsOnCurrentThread(&onCurrentThread
);
72 if (NS_SUCCEEDED(rv
) && onCurrentThread
) {
77 nsCOMPtr
<nsIRunnable
> ev
= new ProxyReleaseEvent
<T
>(aName
, doomed
.forget());
79 rv
= aTarget
->Dispatch(ev
, NS_DISPATCH_NORMAL
);
81 NS_WARNING("failed to post proxy release event, leaking!");
82 // It is better to leak the aDoomed object than risk crashing as
83 // a result of deleting it on the wrong thread.
88 template <bool nsISupportsBased
>
89 struct ProxyReleaseChooser
{
91 static nsresult
ProxyRelease(const char* aName
, nsIEventTarget
* aTarget
,
92 already_AddRefed
<T
> aDoomed
, bool aAlwaysProxy
) {
93 return ::detail::ProxyRelease(aName
, aTarget
, std::move(aDoomed
),
99 struct ProxyReleaseChooser
<true> {
100 // We need an intermediate step for handling classes with ambiguous
101 // inheritance to nsISupports.
102 template <typename T
>
103 static nsresult
ProxyRelease(const char* aName
, nsIEventTarget
* aTarget
,
104 already_AddRefed
<T
> aDoomed
, bool aAlwaysProxy
) {
105 return ProxyReleaseISupports(aName
, aTarget
, ToSupports(aDoomed
.take()),
109 static nsresult
ProxyReleaseISupports(const char* aName
,
110 nsIEventTarget
* aTarget
,
111 nsISupports
* aDoomed
,
115 } // namespace detail
118 * Ensures that the delete of a smart pointer occurs on the target thread.
119 * Note: The doomed object will be leaked if dispatch to the target thread
120 * fails, as releasing it on the current thread may be unsafe
123 * the labelling name of the runnable involved in the releasing.
125 * the target thread where the doomed object should be released.
127 * the doomed object; the object to be released on the target thread.
128 * @param aAlwaysProxy
129 * normally, if NS_ProxyRelease is called on the target thread, then the
130 * doomed object will be released directly. However, if this parameter is
131 * true, then an event will always be posted to the target thread for
132 * asynchronous release.
133 * @return result of the task which is dispatched to delete the smart pointer
134 * on the target thread.
135 * Note: The caller should not attempt to recover from an
136 * error code returned by trying to perform the final ->Release()
140 inline NS_HIDDEN_(nsresult
)
141 NS_ProxyRelease(const char* aName
, nsIEventTarget
* aTarget
,
142 already_AddRefed
<T
> aDoomed
, bool aAlwaysProxy
= false) {
143 return ::detail::ProxyReleaseChooser
<
144 std::is_base_of
<nsISupports
, T
>::value
>::ProxyRelease(aName
, aTarget
,
150 * Ensures that the delete of a smart pointer occurs on the main thread.
153 * the labelling name of the runnable involved in the releasing
155 * the doomed object; the object to be released on the main thread.
156 * @param aAlwaysProxy
157 * normally, if NS_ReleaseOnMainThread is called on the main
158 * thread, then the doomed object will be released directly. However, if
159 * this parameter is true, then an event will always be posted to the
160 * main thread for asynchronous release.
163 inline NS_HIDDEN_(void)
164 NS_ReleaseOnMainThread(const char* aName
, already_AddRefed
<T
> aDoomed
,
165 bool aAlwaysProxy
= false) {
166 RefPtr
<T
> doomed
= aDoomed
;
168 return; // Nothing to do.
171 // NS_ProxyRelease treats a null event target as "the current thread". So a
172 // handle on the main thread is only necessary when we're not already on the
173 // main thread or the release must happen asynchronously.
174 nsCOMPtr
<nsIEventTarget
> target
;
175 if (!NS_IsMainThread() || aAlwaysProxy
) {
176 target
= mozilla::GetMainThreadSerialEventTarget();
179 MOZ_ASSERT_UNREACHABLE("Could not get main thread; leaking an object!");
180 mozilla::Unused
<< doomed
.forget().take();
185 NS_ProxyRelease(aName
, target
, doomed
.forget(), aAlwaysProxy
);
189 * Class to safely handle main-thread-only pointers off the main thread.
191 * Classes like XPCWrappedJS are main-thread-only, which means that it is
192 * forbidden to call methods on instances of these classes off the main thread.
193 * For various reasons (see bug 771074), this restriction applies to
194 * AddRef/Release as well.
196 * This presents a problem for consumers that wish to hold a callback alive
197 * on non-main-thread code. A common example of this is the proxy callback
198 * pattern, where non-main-thread code holds a strong-reference to the callback
199 * object, and dispatches new Runnables (also with a strong reference) to the
200 * main thread in order to execute the callback. This involves several AddRef
201 * and Release calls on the other thread, which is verboten.
203 * The basic idea of this class is to introduce a layer of indirection.
204 * nsMainThreadPtrHolder is a threadsafe reference-counted class that internally
205 * maintains one strong reference to the main-thread-only object. It must be
206 * instantiated on the main thread (so that the AddRef of the underlying object
207 * happens on the main thread), but consumers may subsequently pass references
208 * to the holder anywhere they please. These references are meant to be opaque
209 * when accessed off-main-thread (assertions enforce this).
211 * The semantics of RefPtr<nsMainThreadPtrHolder<T>> would be cumbersome, so we
212 * also introduce nsMainThreadPtrHandle<T>, which is conceptually identical to
213 * the above (though it includes various convenience methods). The basic pattern
216 * // On the main thread:
217 * nsCOMPtr<nsIFooCallback> callback = ...;
218 * nsMainThreadPtrHandle<nsIFooCallback> callbackHandle =
219 * new nsMainThreadPtrHolder<nsIFooCallback>(callback);
220 * // Pass callbackHandle to structs/classes that might be accessed on other
223 * All structs and classes that might be accessed on other threads should store
224 * an nsMainThreadPtrHandle<T> rather than an nsCOMPtr<T>.
227 class MOZ_IS_SMARTPTR_TO_REFCOUNTED nsMainThreadPtrHolder final
{
229 // We can only acquire a pointer on the main thread. We want to fail fast for
230 // threading bugs, so by default we assert if our pointer is used or acquired
231 // off-main-thread. But some consumers need to use the same pointer for
232 // multiple classes, some of which are main-thread-only and some of which
233 // aren't. So we allow them to explicitly disable this strict checking.
234 nsMainThreadPtrHolder(const char* aName
, T
* aPtr
, bool aStrict
= true,
235 nsIEventTarget
* aMainThreadEventTarget
= nullptr)
238 mMainThreadEventTarget(aMainThreadEventTarget
)
239 #ifndef RELEASE_OR_BETA
244 // We can only AddRef our pointer on the main thread, which means that the
245 // holder must be constructed on the main thread.
246 MOZ_ASSERT(!mStrict
|| NS_IsMainThread());
247 NS_IF_ADDREF(mRawPtr
);
249 nsMainThreadPtrHolder(const char* aName
, already_AddRefed
<T
> aPtr
,
251 nsIEventTarget
* aMainThreadEventTarget
= nullptr)
252 : mRawPtr(aPtr
.take()),
254 mMainThreadEventTarget(aMainThreadEventTarget
)
255 #ifndef RELEASE_OR_BETA
260 // Since we don't need to AddRef the pointer, this constructor is safe to
261 // call on any thread.
264 // Copy constructor and operator= deleted. Once constructed, the holder is
266 T
& operator=(nsMainThreadPtrHolder
& aOther
) = delete;
267 nsMainThreadPtrHolder(const nsMainThreadPtrHolder
& aOther
) = delete;
270 // We can be released on any thread.
271 ~nsMainThreadPtrHolder() {
272 if (NS_IsMainThread()) {
273 NS_IF_RELEASE(mRawPtr
);
274 } else if (mRawPtr
) {
275 if (!mMainThreadEventTarget
) {
276 mMainThreadEventTarget
= do_GetMainThread();
278 MOZ_ASSERT(mMainThreadEventTarget
);
280 #ifdef RELEASE_OR_BETA
285 mMainThreadEventTarget
, dont_AddRef(mRawPtr
));
291 // Nobody should be touching the raw pointer off-main-thread.
292 if (mStrict
&& MOZ_UNLIKELY(!NS_IsMainThread())) {
293 NS_ERROR("Can't dereference nsMainThreadPtrHolder off main thread");
299 bool operator==(const nsMainThreadPtrHolder
<T
>& aOther
) const {
300 return mRawPtr
== aOther
.mRawPtr
;
302 bool operator!() const { return !mRawPtr
; }
304 NS_INLINE_DECL_THREADSAFE_REFCOUNTING(nsMainThreadPtrHolder
<T
>)
307 // Our wrapped pointer.
308 T
* mRawPtr
= nullptr;
310 // Whether to strictly enforce thread invariants in this class.
313 nsCOMPtr
<nsIEventTarget
> mMainThreadEventTarget
;
315 #ifndef RELEASE_OR_BETA
316 const char* mName
= nullptr;
321 class MOZ_IS_SMARTPTR_TO_REFCOUNTED nsMainThreadPtrHandle
{
323 nsMainThreadPtrHandle() : mPtr(nullptr) {}
324 MOZ_IMPLICIT
nsMainThreadPtrHandle(decltype(nullptr)) : mPtr(nullptr) {}
325 explicit nsMainThreadPtrHandle(nsMainThreadPtrHolder
<T
>* aHolder
)
327 explicit nsMainThreadPtrHandle(
328 already_AddRefed
<nsMainThreadPtrHolder
<T
>> aHolder
)
330 nsMainThreadPtrHandle(const nsMainThreadPtrHandle
& aOther
) = default;
331 nsMainThreadPtrHandle(nsMainThreadPtrHandle
&& aOther
) = default;
332 nsMainThreadPtrHandle
& operator=(const nsMainThreadPtrHandle
& aOther
) =
334 nsMainThreadPtrHandle
& operator=(nsMainThreadPtrHandle
&& aOther
) = default;
335 nsMainThreadPtrHandle
& operator=(nsMainThreadPtrHolder
<T
>* aHolder
) {
340 // These all call through to nsMainThreadPtrHolder, and thus implicitly
341 // assert that we're on the main thread (if strict). Off-main-thread consumers
342 // must treat these handles as opaque.
345 return mPtr
.get()->get();
350 operator T
*() const { return get(); }
351 T
* operator->() const MOZ_NO_ADDREF_RELEASE_ON_RETURN
{ return get(); }
353 // These are safe to call on other threads with appropriate external locking.
354 bool operator==(const nsMainThreadPtrHandle
<T
>& aOther
) const {
355 if (!mPtr
|| !aOther
.mPtr
) {
356 return mPtr
== aOther
.mPtr
;
358 return *mPtr
== *aOther
.mPtr
;
360 bool operator!=(const nsMainThreadPtrHandle
<T
>& aOther
) const {
361 return !operator==(aOther
);
363 bool operator==(decltype(nullptr)) const { return mPtr
== nullptr; }
364 bool operator!=(decltype(nullptr)) const { return mPtr
!= nullptr; }
365 bool operator!() const { return !mPtr
|| !*mPtr
; }
368 RefPtr
<nsMainThreadPtrHolder
<T
>> mPtr
;
371 class nsCycleCollectionTraversalCallback
;
372 template <typename T
>
373 void CycleCollectionNoteChild(nsCycleCollectionTraversalCallback
& aCallback
,
374 T
* aChild
, const char* aName
, uint32_t aFlags
);
376 template <typename T
>
377 inline void ImplCycleCollectionTraverse(
378 nsCycleCollectionTraversalCallback
& aCallback
,
379 nsMainThreadPtrHandle
<T
>& aField
, const char* aName
, uint32_t aFlags
= 0) {
380 CycleCollectionNoteChild(aCallback
, aField
.get(), aName
, aFlags
);
383 template <typename T
>
384 inline void ImplCycleCollectionUnlink(nsMainThreadPtrHandle
<T
>& aField
) {