Bug 1867190 - Initialise the PHC allocate delay later r=glandium
[gecko.git] / xpcom / threads / nsProxyRelease.h
blobc125eae2aa70d297c1e1db7117a39257640ec855
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 : mRawPtr(aPtr),
238 mStrict(aStrict)
239 #ifndef RELEASE_OR_BETA
241 mName(aName)
242 #endif
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,
250 bool aStrict = true)
251 : mRawPtr(aPtr.take()),
252 mStrict(aStrict)
253 #ifndef RELEASE_OR_BETA
255 mName(aName)
256 #endif
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
263 // immutable.
264 T& operator=(nsMainThreadPtrHolder& aOther) = delete;
265 nsMainThreadPtrHolder(const nsMainThreadPtrHolder& aOther) = delete;
267 private:
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
275 nullptr,
276 #else
277 mName,
278 #endif
279 dont_AddRef(mRawPtr));
283 public:
284 T* get() const {
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");
288 MOZ_CRASH();
290 return mRawPtr;
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>)
300 private:
301 // Our wrapped pointer.
302 T* mRawPtr = nullptr;
304 // Whether to strictly enforce thread invariants in this class.
305 bool mStrict = true;
307 #ifndef RELEASE_OR_BETA
308 const char* mName = nullptr;
309 #endif
312 template <class T>
313 class MOZ_IS_SMARTPTR_TO_REFCOUNTED nsMainThreadPtrHandle {
314 public:
315 nsMainThreadPtrHandle() : mPtr(nullptr) {}
316 MOZ_IMPLICIT nsMainThreadPtrHandle(decltype(nullptr)) : mPtr(nullptr) {}
317 explicit nsMainThreadPtrHandle(nsMainThreadPtrHolder<T>* aHolder)
318 : mPtr(aHolder) {}
319 explicit nsMainThreadPtrHandle(
320 already_AddRefed<nsMainThreadPtrHolder<T>> aHolder)
321 : mPtr(aHolder) {}
322 nsMainThreadPtrHandle(const nsMainThreadPtrHandle& aOther) = default;
323 nsMainThreadPtrHandle(nsMainThreadPtrHandle&& aOther) = default;
324 nsMainThreadPtrHandle& operator=(const nsMainThreadPtrHandle& aOther) =
325 default;
326 nsMainThreadPtrHandle& operator=(nsMainThreadPtrHandle&& aOther) = default;
327 nsMainThreadPtrHandle& operator=(nsMainThreadPtrHolder<T>* aHolder) {
328 mPtr = aHolder;
329 return *this;
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.
335 T* get() const {
336 if (mPtr) {
337 return mPtr.get()->get();
339 return nullptr;
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; }
359 private:
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) {
377 aField = nullptr;
380 #endif