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)
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 : mRawPtr(aPtr
.take()),
253 #ifndef RELEASE_OR_BETA
258 // Since we don't need to AddRef the pointer, this constructor is safe to
259 // call on any thread.
262 // Copy constructor and operator= deleted. Once constructed, the holder is
264 T
& operator=(nsMainThreadPtrHolder
& aOther
) = delete;
265 nsMainThreadPtrHolder(const nsMainThreadPtrHolder
& aOther
) = delete;
268 // We can be released on any thread.
269 ~nsMainThreadPtrHolder() {
270 if (NS_IsMainThread()) {
271 NS_IF_RELEASE(mRawPtr
);
272 } else if (mRawPtr
) {
273 NS_ReleaseOnMainThread(
274 #ifdef RELEASE_OR_BETA
279 dont_AddRef(mRawPtr
));
285 // Nobody should be touching the raw pointer off-main-thread.
286 if (mStrict
&& MOZ_UNLIKELY(!NS_IsMainThread())) {
287 NS_ERROR("Can't dereference nsMainThreadPtrHolder off main thread");
293 bool operator==(const nsMainThreadPtrHolder
<T
>& aOther
) const {
294 return mRawPtr
== aOther
.mRawPtr
;
296 bool operator!() const { return !mRawPtr
; }
298 NS_INLINE_DECL_THREADSAFE_REFCOUNTING(nsMainThreadPtrHolder
<T
>)
301 // Our wrapped pointer.
302 T
* mRawPtr
= nullptr;
304 // Whether to strictly enforce thread invariants in this class.
307 #ifndef RELEASE_OR_BETA
308 const char* mName
= nullptr;
313 class MOZ_IS_SMARTPTR_TO_REFCOUNTED nsMainThreadPtrHandle
{
315 nsMainThreadPtrHandle() : mPtr(nullptr) {}
316 MOZ_IMPLICIT
nsMainThreadPtrHandle(decltype(nullptr)) : mPtr(nullptr) {}
317 explicit nsMainThreadPtrHandle(nsMainThreadPtrHolder
<T
>* aHolder
)
319 explicit nsMainThreadPtrHandle(
320 already_AddRefed
<nsMainThreadPtrHolder
<T
>> aHolder
)
322 nsMainThreadPtrHandle(const nsMainThreadPtrHandle
& aOther
) = default;
323 nsMainThreadPtrHandle(nsMainThreadPtrHandle
&& aOther
) = default;
324 nsMainThreadPtrHandle
& operator=(const nsMainThreadPtrHandle
& aOther
) =
326 nsMainThreadPtrHandle
& operator=(nsMainThreadPtrHandle
&& aOther
) = default;
327 nsMainThreadPtrHandle
& operator=(nsMainThreadPtrHolder
<T
>* aHolder
) {
332 // These all call through to nsMainThreadPtrHolder, and thus implicitly
333 // assert that we're on the main thread (if strict). Off-main-thread consumers
334 // must treat these handles as opaque.
337 return mPtr
.get()->get();
342 operator T
*() const { return get(); }
343 T
* operator->() const MOZ_NO_ADDREF_RELEASE_ON_RETURN
{ return get(); }
345 // These are safe to call on other threads with appropriate external locking.
346 bool operator==(const nsMainThreadPtrHandle
<T
>& aOther
) const {
347 if (!mPtr
|| !aOther
.mPtr
) {
348 return mPtr
== aOther
.mPtr
;
350 return *mPtr
== *aOther
.mPtr
;
352 bool operator!=(const nsMainThreadPtrHandle
<T
>& aOther
) const {
353 return !operator==(aOther
);
355 bool operator==(decltype(nullptr)) const { return mPtr
== nullptr; }
356 bool operator!=(decltype(nullptr)) const { return mPtr
!= nullptr; }
357 bool operator!() const { return !mPtr
|| !*mPtr
; }
360 RefPtr
<nsMainThreadPtrHolder
<T
>> mPtr
;
363 class nsCycleCollectionTraversalCallback
;
364 template <typename T
>
365 void CycleCollectionNoteChild(nsCycleCollectionTraversalCallback
& aCallback
,
366 T
* aChild
, const char* aName
, uint32_t aFlags
);
368 template <typename T
>
369 inline void ImplCycleCollectionTraverse(
370 nsCycleCollectionTraversalCallback
& aCallback
,
371 nsMainThreadPtrHandle
<T
>& aField
, const char* aName
, uint32_t aFlags
= 0) {
372 CycleCollectionNoteChild(aCallback
, aField
.get(), aName
, aFlags
);
375 template <typename T
>
376 inline void ImplCycleCollectionUnlink(nsMainThreadPtrHandle
<T
>& aField
) {