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(nsPrintfCString(
82 "failed to post proxy release event for %s, leaking!", aName
)
84 // It is better to leak the aDoomed object than risk crashing as
85 // a result of deleting it on the wrong thread.
90 template <bool nsISupportsBased
>
91 struct ProxyReleaseChooser
{
93 static nsresult
ProxyRelease(const char* aName
, nsIEventTarget
* aTarget
,
94 already_AddRefed
<T
> aDoomed
, bool aAlwaysProxy
) {
95 return ::detail::ProxyRelease(aName
, aTarget
, std::move(aDoomed
),
101 struct ProxyReleaseChooser
<true> {
102 // We need an intermediate step for handling classes with ambiguous
103 // inheritance to nsISupports.
104 template <typename T
>
105 static nsresult
ProxyRelease(const char* aName
, nsIEventTarget
* aTarget
,
106 already_AddRefed
<T
> aDoomed
, bool aAlwaysProxy
) {
107 return ProxyReleaseISupports(aName
, aTarget
, ToSupports(aDoomed
.take()),
111 static nsresult
ProxyReleaseISupports(const char* aName
,
112 nsIEventTarget
* aTarget
,
113 nsISupports
* aDoomed
,
117 } // namespace detail
120 * Ensures that the delete of a smart pointer occurs on the target thread.
121 * Note: The doomed object will be leaked if dispatch to the target thread
122 * fails, as releasing it on the current thread may be unsafe
125 * the labelling name of the runnable involved in the releasing.
127 * the target thread where the doomed object should be released.
129 * the doomed object; the object to be released on the target thread.
130 * @param aAlwaysProxy
131 * normally, if NS_ProxyRelease is called on the target thread, then the
132 * doomed object will be released directly. However, if this parameter is
133 * true, then an event will always be posted to the target thread for
134 * asynchronous release.
135 * @return result of the task which is dispatched to delete the smart pointer
136 * on the target thread.
137 * Note: The caller should not attempt to recover from an
138 * error code returned by trying to perform the final ->Release()
142 inline NS_HIDDEN_(nsresult
)
143 NS_ProxyRelease(const char* aName
, nsIEventTarget
* aTarget
,
144 already_AddRefed
<T
> aDoomed
, bool aAlwaysProxy
= false) {
145 return ::detail::ProxyReleaseChooser
<
146 std::is_base_of
<nsISupports
, T
>::value
>::ProxyRelease(aName
, aTarget
,
152 * Ensures that the delete of a smart pointer occurs on the main thread.
155 * the labelling name of the runnable involved in the releasing
157 * the doomed object; the object to be released on the main thread.
158 * @param aAlwaysProxy
159 * normally, if NS_ReleaseOnMainThread is called on the main
160 * thread, then the doomed object will be released directly. However, if
161 * this parameter is true, then an event will always be posted to the
162 * main thread for asynchronous release.
165 inline NS_HIDDEN_(void)
166 NS_ReleaseOnMainThread(const char* aName
, already_AddRefed
<T
> aDoomed
,
167 bool aAlwaysProxy
= false) {
168 RefPtr
<T
> doomed
= aDoomed
;
170 return; // Nothing to do.
173 // NS_ProxyRelease treats a null event target as "the current thread". So a
174 // handle on the main thread is only necessary when we're not already on the
175 // main thread or the release must happen asynchronously.
176 nsCOMPtr
<nsIEventTarget
> target
;
177 if (!NS_IsMainThread() || aAlwaysProxy
) {
178 target
= mozilla::GetMainThreadSerialEventTarget();
181 MOZ_ASSERT_UNREACHABLE("Could not get main thread; leaking an object!");
182 mozilla::Unused
<< doomed
.forget().take();
187 NS_ProxyRelease(aName
, target
, doomed
.forget(), aAlwaysProxy
);
191 * Class to safely handle main-thread-only pointers off the main thread.
193 * Classes like XPCWrappedJS are main-thread-only, which means that it is
194 * forbidden to call methods on instances of these classes off the main thread.
195 * For various reasons (see bug 771074), this restriction applies to
196 * AddRef/Release as well.
198 * This presents a problem for consumers that wish to hold a callback alive
199 * on non-main-thread code. A common example of this is the proxy callback
200 * pattern, where non-main-thread code holds a strong-reference to the callback
201 * object, and dispatches new Runnables (also with a strong reference) to the
202 * main thread in order to execute the callback. This involves several AddRef
203 * and Release calls on the other thread, which is verboten.
205 * The basic idea of this class is to introduce a layer of indirection.
206 * nsMainThreadPtrHolder is a threadsafe reference-counted class that internally
207 * maintains one strong reference to the main-thread-only object. It must be
208 * instantiated on the main thread (so that the AddRef of the underlying object
209 * happens on the main thread), but consumers may subsequently pass references
210 * to the holder anywhere they please. These references are meant to be opaque
211 * when accessed off-main-thread (assertions enforce this).
213 * The semantics of RefPtr<nsMainThreadPtrHolder<T>> would be cumbersome, so we
214 * also introduce nsMainThreadPtrHandle<T>, which is conceptually identical to
215 * the above (though it includes various convenience methods). The basic pattern
218 * // On the main thread:
219 * nsCOMPtr<nsIFooCallback> callback = ...;
220 * nsMainThreadPtrHandle<nsIFooCallback> callbackHandle =
221 * new nsMainThreadPtrHolder<nsIFooCallback>(callback);
222 * // Pass callbackHandle to structs/classes that might be accessed on other
225 * All structs and classes that might be accessed on other threads should store
226 * an nsMainThreadPtrHandle<T> rather than an nsCOMPtr<T>.
229 class MOZ_IS_SMARTPTR_TO_REFCOUNTED nsMainThreadPtrHolder final
{
231 // We can only acquire a pointer on the main thread. We want to fail fast for
232 // threading bugs, so by default we assert if our pointer is used or acquired
233 // off-main-thread. But some consumers need to use the same pointer for
234 // multiple classes, some of which are main-thread-only and some of which
235 // aren't. So we allow them to explicitly disable this strict checking.
236 nsMainThreadPtrHolder(const char* aName
, T
* aPtr
, bool aStrict
= true,
237 nsIEventTarget
* aMainThreadEventTarget
= nullptr)
240 mMainThreadEventTarget(aMainThreadEventTarget
)
241 #ifndef RELEASE_OR_BETA
246 // We can only AddRef our pointer on the main thread, which means that the
247 // holder must be constructed on the main thread.
248 MOZ_ASSERT(!mStrict
|| NS_IsMainThread());
249 NS_IF_ADDREF(mRawPtr
);
251 nsMainThreadPtrHolder(const char* aName
, already_AddRefed
<T
> aPtr
,
253 nsIEventTarget
* aMainThreadEventTarget
= nullptr)
254 : mRawPtr(aPtr
.take()),
256 mMainThreadEventTarget(aMainThreadEventTarget
)
257 #ifndef RELEASE_OR_BETA
262 // Since we don't need to AddRef the pointer, this constructor is safe to
263 // call on any thread.
266 // Copy constructor and operator= deleted. Once constructed, the holder is
268 T
& operator=(nsMainThreadPtrHolder
& aOther
) = delete;
269 nsMainThreadPtrHolder(const nsMainThreadPtrHolder
& aOther
) = delete;
272 // We can be released on any thread.
273 ~nsMainThreadPtrHolder() {
274 if (NS_IsMainThread()) {
275 NS_IF_RELEASE(mRawPtr
);
276 } else if (mRawPtr
) {
277 if (!mMainThreadEventTarget
) {
278 mMainThreadEventTarget
= do_GetMainThread();
280 MOZ_ASSERT(mMainThreadEventTarget
);
282 #ifdef RELEASE_OR_BETA
287 mMainThreadEventTarget
, dont_AddRef(mRawPtr
));
293 // Nobody should be touching the raw pointer off-main-thread.
294 if (mStrict
&& MOZ_UNLIKELY(!NS_IsMainThread())) {
295 NS_ERROR("Can't dereference nsMainThreadPtrHolder off main thread");
301 bool operator==(const nsMainThreadPtrHolder
<T
>& aOther
) const {
302 return mRawPtr
== aOther
.mRawPtr
;
304 bool operator!() const { return !mRawPtr
; }
306 NS_INLINE_DECL_THREADSAFE_REFCOUNTING(nsMainThreadPtrHolder
<T
>)
309 // Our wrapped pointer.
310 T
* mRawPtr
= nullptr;
312 // Whether to strictly enforce thread invariants in this class.
315 nsCOMPtr
<nsIEventTarget
> mMainThreadEventTarget
;
317 #ifndef RELEASE_OR_BETA
318 const char* mName
= nullptr;
323 class MOZ_IS_SMARTPTR_TO_REFCOUNTED nsMainThreadPtrHandle
{
325 nsMainThreadPtrHandle() : mPtr(nullptr) {}
326 MOZ_IMPLICIT
nsMainThreadPtrHandle(decltype(nullptr)) : mPtr(nullptr) {}
327 explicit nsMainThreadPtrHandle(nsMainThreadPtrHolder
<T
>* aHolder
)
329 explicit nsMainThreadPtrHandle(
330 already_AddRefed
<nsMainThreadPtrHolder
<T
>> aHolder
)
332 nsMainThreadPtrHandle(const nsMainThreadPtrHandle
& aOther
) = default;
333 nsMainThreadPtrHandle(nsMainThreadPtrHandle
&& aOther
) = default;
334 nsMainThreadPtrHandle
& operator=(const nsMainThreadPtrHandle
& aOther
) =
336 nsMainThreadPtrHandle
& operator=(nsMainThreadPtrHandle
&& aOther
) = default;
337 nsMainThreadPtrHandle
& operator=(nsMainThreadPtrHolder
<T
>* aHolder
) {
342 // These all call through to nsMainThreadPtrHolder, and thus implicitly
343 // assert that we're on the main thread (if strict). Off-main-thread consumers
344 // must treat these handles as opaque.
347 return mPtr
.get()->get();
352 operator T
*() const { return get(); }
353 T
* operator->() const MOZ_NO_ADDREF_RELEASE_ON_RETURN
{ return get(); }
355 // These are safe to call on other threads with appropriate external locking.
356 bool operator==(const nsMainThreadPtrHandle
<T
>& aOther
) const {
357 if (!mPtr
|| !aOther
.mPtr
) {
358 return mPtr
== aOther
.mPtr
;
360 return *mPtr
== *aOther
.mPtr
;
362 bool operator!=(const nsMainThreadPtrHandle
<T
>& aOther
) const {
363 return !operator==(aOther
);
365 bool operator==(decltype(nullptr)) const { return mPtr
== nullptr; }
366 bool operator!=(decltype(nullptr)) const { return mPtr
!= nullptr; }
367 bool operator!() const { return !mPtr
|| !*mPtr
; }
370 RefPtr
<nsMainThreadPtrHolder
<T
>> mPtr
;
373 class nsCycleCollectionTraversalCallback
;
374 template <typename T
>
375 void CycleCollectionNoteChild(nsCycleCollectionTraversalCallback
& aCallback
,
376 T
* aChild
, const char* aName
, uint32_t aFlags
);
378 template <typename T
>
379 inline void ImplCycleCollectionTraverse(
380 nsCycleCollectionTraversalCallback
& aCallback
,
381 nsMainThreadPtrHandle
<T
>& aField
, const char* aName
, uint32_t aFlags
= 0) {
382 CycleCollectionNoteChild(aCallback
, aField
.get(), aName
, aFlags
);
385 template <typename T
>
386 inline void ImplCycleCollectionUnlink(nsMainThreadPtrHandle
<T
>& aField
) {