Backed out 3 changesets (bug 1854934) for causing build bustages on widget/windows...
[gecko.git] / xpcom / threads / nsProxyRelease.h
blob00f69e32875f55bcf7d757cc9176da588b929c20
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__
10 #include <utility>
12 #include "MainThreadUtils.h"
13 #include "mozilla/Likely.h"
14 #include "mozilla/Unused.h"
15 #include "nsCOMPtr.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.
24 #endif
26 class nsIRunnable;
28 namespace detail {
30 template <typename T>
31 class ProxyReleaseEvent : public mozilla::CancelableRunnable {
32 public:
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);
38 return NS_OK;
41 nsresult Cancel() override { return Run(); }
43 #ifdef MOZ_COLLECTING_RUNNABLE_TELEMETRY
44 NS_IMETHOD GetName(nsACString& aName) override {
45 if (mName) {
46 aName.Append(nsPrintfCString("ProxyReleaseEvent for %s", mName));
47 } else {
48 aName.AssignLiteral("ProxyReleaseEvent");
50 return NS_OK;
52 #endif
54 private:
55 T* MOZ_OWNING_REF mDoomed;
58 template <typename T>
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;
63 nsresult rv;
65 if (!doomed || !aTarget) {
66 return NS_ERROR_INVALID_ARG;
69 if (!aAlwaysProxy) {
70 bool onCurrentThread = false;
71 rv = aTarget->IsOnCurrentThread(&onCurrentThread);
72 if (NS_SUCCEEDED(rv) && onCurrentThread) {
73 return NS_OK;
77 nsCOMPtr<nsIRunnable> ev = new ProxyReleaseEvent<T>(aName, doomed.forget());
79 rv = aTarget->Dispatch(ev, NS_DISPATCH_NORMAL);
80 if (NS_FAILED(rv)) {
81 NS_WARNING(nsPrintfCString(
82 "failed to post proxy release event for %s, leaking!", aName)
83 .get());
84 // It is better to leak the aDoomed object than risk crashing as
85 // a result of deleting it on the wrong thread.
87 return rv;
90 template <bool nsISupportsBased>
91 struct ProxyReleaseChooser {
92 template <typename T>
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),
96 aAlwaysProxy);
100 template <>
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()),
108 aAlwaysProxy);
111 static nsresult ProxyReleaseISupports(const char* aName,
112 nsIEventTarget* aTarget,
113 nsISupports* aDoomed,
114 bool aAlwaysProxy);
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
124 * @param aName
125 * the labelling name of the runnable involved in the releasing.
126 * @param aTarget
127 * the target thread where the doomed object should be released.
128 * @param aDoomed
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()
139 * manually.
141 template <class T>
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,
147 std::move(aDoomed),
148 aAlwaysProxy);
152 * Ensures that the delete of a smart pointer occurs on the main thread.
154 * @param aName
155 * the labelling name of the runnable involved in the releasing
156 * @param aDoomed
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.
164 template <class T>
165 inline NS_HIDDEN_(void)
166 NS_ReleaseOnMainThread(const char* aName, already_AddRefed<T> aDoomed,
167 bool aAlwaysProxy = false) {
168 RefPtr<T> doomed = aDoomed;
169 if (!doomed) {
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();
180 if (!target) {
181 MOZ_ASSERT_UNREACHABLE("Could not get main thread; leaking an object!");
182 mozilla::Unused << doomed.forget().take();
183 return;
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
216 * is as follows.
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
223 * // threads.
225 * All structs and classes that might be accessed on other threads should store
226 * an nsMainThreadPtrHandle<T> rather than an nsCOMPtr<T>.
228 template <class T>
229 class MOZ_IS_SMARTPTR_TO_REFCOUNTED nsMainThreadPtrHolder final {
230 public:
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)
238 : mRawPtr(aPtr),
239 mStrict(aStrict),
240 mMainThreadEventTarget(aMainThreadEventTarget)
241 #ifndef RELEASE_OR_BETA
243 mName(aName)
244 #endif
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,
252 bool aStrict = true,
253 nsIEventTarget* aMainThreadEventTarget = nullptr)
254 : mRawPtr(aPtr.take()),
255 mStrict(aStrict),
256 mMainThreadEventTarget(aMainThreadEventTarget)
257 #ifndef RELEASE_OR_BETA
259 mName(aName)
260 #endif
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
267 // immutable.
268 T& operator=(nsMainThreadPtrHolder& aOther) = delete;
269 nsMainThreadPtrHolder(const nsMainThreadPtrHolder& aOther) = delete;
271 private:
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);
281 NS_ProxyRelease(
282 #ifdef RELEASE_OR_BETA
283 nullptr,
284 #else
285 mName,
286 #endif
287 mMainThreadEventTarget, dont_AddRef(mRawPtr));
291 public:
292 T* get() const {
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");
296 MOZ_CRASH();
298 return mRawPtr;
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>)
308 private:
309 // Our wrapped pointer.
310 T* mRawPtr = nullptr;
312 // Whether to strictly enforce thread invariants in this class.
313 bool mStrict = true;
315 nsCOMPtr<nsIEventTarget> mMainThreadEventTarget;
317 #ifndef RELEASE_OR_BETA
318 const char* mName = nullptr;
319 #endif
322 template <class T>
323 class MOZ_IS_SMARTPTR_TO_REFCOUNTED nsMainThreadPtrHandle {
324 public:
325 nsMainThreadPtrHandle() : mPtr(nullptr) {}
326 MOZ_IMPLICIT nsMainThreadPtrHandle(decltype(nullptr)) : mPtr(nullptr) {}
327 explicit nsMainThreadPtrHandle(nsMainThreadPtrHolder<T>* aHolder)
328 : mPtr(aHolder) {}
329 explicit nsMainThreadPtrHandle(
330 already_AddRefed<nsMainThreadPtrHolder<T>> aHolder)
331 : mPtr(aHolder) {}
332 nsMainThreadPtrHandle(const nsMainThreadPtrHandle& aOther) = default;
333 nsMainThreadPtrHandle(nsMainThreadPtrHandle&& aOther) = default;
334 nsMainThreadPtrHandle& operator=(const nsMainThreadPtrHandle& aOther) =
335 default;
336 nsMainThreadPtrHandle& operator=(nsMainThreadPtrHandle&& aOther) = default;
337 nsMainThreadPtrHandle& operator=(nsMainThreadPtrHolder<T>* aHolder) {
338 mPtr = aHolder;
339 return *this;
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.
345 T* get() const {
346 if (mPtr) {
347 return mPtr.get()->get();
349 return nullptr;
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; }
369 private:
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) {
387 aField = nullptr;
390 #endif