Bug 1845666 - Lock the media.utility-* prefs r=alwu
[gecko.git] / mfbt / RefCounted.h
blob5c083f3524fff7b0a2db83d2b9b1e8488ec53787
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 /* CRTP refcounting templates. Do not use unless you are an Expert. */
9 #ifndef mozilla_RefCounted_h
10 #define mozilla_RefCounted_h
12 #include <utility>
13 #include <type_traits>
15 #include "mozilla/AlreadyAddRefed.h"
16 #include "mozilla/Assertions.h"
17 #include "mozilla/Atomics.h"
18 #include "mozilla/Attributes.h"
19 #include "mozilla/RefCountType.h"
21 #ifdef __wasi__
22 # include "mozilla/WasiAtomic.h"
23 #else
24 # include <atomic>
25 #endif // __wasi__
27 #if defined(MOZILLA_INTERNAL_API)
28 # include "nsXPCOM.h"
29 #endif
31 #if defined(MOZILLA_INTERNAL_API) && defined(NS_BUILD_REFCNT_LOGGING)
32 # define MOZ_REFCOUNTED_LEAK_CHECKING
33 #endif
35 namespace mozilla {
37 /**
38 * RefCounted<T> is a sort of a "mixin" for a class T. RefCounted
39 * manages, well, refcounting for T, and because RefCounted is
40 * parameterized on T, RefCounted<T> can call T's destructor directly.
41 * This means T doesn't need to have a virtual dtor and so doesn't
42 * need a vtable.
44 * RefCounted<T> is created with refcount == 0. Newly-allocated
45 * RefCounted<T> must immediately be assigned to a RefPtr to make the
46 * refcount > 0. It's an error to allocate and free a bare
47 * RefCounted<T>, i.e. outside of the RefPtr machinery. Attempts to
48 * do so will abort DEBUG builds.
50 * Live RefCounted<T> have refcount > 0. The lifetime (refcounts) of
51 * live RefCounted<T> are controlled by RefPtr<T> and
52 * RefPtr<super/subclass of T>. Upon a transition from refcounted==1
53 * to 0, the RefCounted<T> "dies" and is destroyed. The "destroyed"
54 * state is represented in DEBUG builds by refcount==0xffffdead. This
55 * state distinguishes use-before-ref (refcount==0) from
56 * use-after-destroy (refcount==0xffffdead).
58 * Note that when deriving from RefCounted or AtomicRefCounted, you
59 * should add MOZ_DECLARE_REFCOUNTED_TYPENAME(ClassName) to the public
60 * section of your class, where ClassName is the name of your class.
62 * Note: SpiderMonkey should use js::RefCounted instead since that type
63 * will use appropriate js_delete and also not break ref-count logging.
65 namespace detail {
66 const MozRefCountType DEAD = 0xffffdead;
68 // When building code that gets compiled into Gecko, try to use the
69 // trace-refcount leak logging facilities.
70 class RefCountLogger {
71 public:
72 // Called by `RefCounted`-like classes to log a successful AddRef call in the
73 // Gecko leak-logging system. This call is a no-op outside of Gecko. Should be
74 // called afer incrementing the reference count.
75 template <class T>
76 static void logAddRef(const T* aPointer, MozRefCountType aRefCount) {
77 #ifdef MOZ_REFCOUNTED_LEAK_CHECKING
78 const void* pointer = aPointer;
79 const char* typeName = aPointer->typeName();
80 uint32_t typeSize = aPointer->typeSize();
81 NS_LogAddRef(const_cast<void*>(pointer), aRefCount, typeName, typeSize);
82 #endif
85 // Created by `RefCounted`-like classes to log a successful Release call in
86 // the Gecko leak-logging system. The constructor should be invoked before the
87 // refcount is decremented to avoid invoking `typeName()` with a zero
88 // reference count. This call is a no-op outside of Gecko.
89 class MOZ_STACK_CLASS ReleaseLogger final {
90 public:
91 template <class T>
92 explicit ReleaseLogger(const T* aPointer)
93 #ifdef MOZ_REFCOUNTED_LEAK_CHECKING
94 : mPointer(aPointer),
95 mTypeName(aPointer->typeName())
96 #endif
100 void logRelease(MozRefCountType aRefCount) {
101 #ifdef MOZ_REFCOUNTED_LEAK_CHECKING
102 MOZ_ASSERT(aRefCount != DEAD);
103 NS_LogRelease(const_cast<void*>(mPointer), aRefCount, mTypeName);
104 #endif
107 #ifdef MOZ_REFCOUNTED_LEAK_CHECKING
108 const void* mPointer;
109 const char* mTypeName;
110 #endif
114 // This is used WeakPtr.h as well as this file.
115 enum RefCountAtomicity { AtomicRefCount, NonAtomicRefCount };
117 template <typename T, RefCountAtomicity Atomicity>
118 class RC {
119 public:
120 explicit RC(T aCount) : mValue(aCount) {}
122 RC(const RC&) = delete;
123 RC& operator=(const RC&) = delete;
124 RC(RC&&) = delete;
125 RC& operator=(RC&&) = delete;
127 T operator++() { return ++mValue; }
128 T operator--() { return --mValue; }
130 #ifdef DEBUG
131 void operator=(const T& aValue) { mValue = aValue; }
132 #endif
134 operator T() const { return mValue; }
136 private:
137 T mValue;
140 template <typename T>
141 class RC<T, AtomicRefCount> {
142 public:
143 explicit RC(T aCount) : mValue(aCount) {}
145 RC(const RC&) = delete;
146 RC& operator=(const RC&) = delete;
147 RC(RC&&) = delete;
148 RC& operator=(RC&&) = delete;
150 T operator++() {
151 // Memory synchronization is not required when incrementing a
152 // reference count. The first increment of a reference count on a
153 // thread is not important, since the first use of the object on a
154 // thread can happen before it. What is important is the transfer
155 // of the pointer to that thread, which may happen prior to the
156 // first increment on that thread. The necessary memory
157 // synchronization is done by the mechanism that transfers the
158 // pointer between threads.
159 return mValue.fetch_add(1, std::memory_order_relaxed) + 1;
162 T operator--() {
163 // Since this may be the last release on this thread, we need
164 // release semantics so that prior writes on this thread are visible
165 // to the thread that destroys the object when it reads mValue with
166 // acquire semantics.
167 T result = mValue.fetch_sub(1, std::memory_order_release) - 1;
168 if (result == 0) {
169 // We're going to destroy the object on this thread, so we need
170 // acquire semantics to synchronize with the memory released by
171 // the last release on other threads, that is, to ensure that
172 // writes prior to that release are now visible on this thread.
173 #if defined(MOZ_TSAN) || defined(__wasi__)
174 // TSan doesn't understand std::atomic_thread_fence, so in order
175 // to avoid a false positive for every time a refcounted object
176 // is deleted, we replace the fence with an atomic operation.
177 mValue.load(std::memory_order_acquire);
178 #else
179 std::atomic_thread_fence(std::memory_order_acquire);
180 #endif
182 return result;
185 #ifdef DEBUG
186 // This method is only called in debug builds, so we're not too concerned
187 // about its performance.
188 void operator=(const T& aValue) {
189 mValue.store(aValue, std::memory_order_seq_cst);
191 #endif
193 operator T() const {
194 // Use acquire semantics since we're not sure what the caller is
195 // doing.
196 return mValue.load(std::memory_order_acquire);
199 T IncrementIfNonzero() {
200 // This can be a relaxed load as any write of 0 that we observe will leave
201 // the field in a permanently zero (or `DEAD`) state (so a "stale" read of 0
202 // is fine), and any other value is confirmed by the CAS below.
204 // This roughly matches rust's Arc::upgrade implementation as of rust 1.49.0
205 T prev = mValue.load(std::memory_order_relaxed);
206 while (prev != 0) {
207 MOZ_ASSERT(prev != detail::DEAD,
208 "Cannot IncrementIfNonzero if marked as dead!");
209 // TODO: It may be possible to use relaxed success ordering here?
210 if (mValue.compare_exchange_weak(prev, prev + 1,
211 std::memory_order_acquire,
212 std::memory_order_relaxed)) {
213 return prev + 1;
216 return 0;
219 private:
220 std::atomic<T> mValue;
223 template <typename T, RefCountAtomicity Atomicity>
224 class RefCounted {
225 protected:
226 RefCounted() : mRefCnt(0) {}
227 #ifdef DEBUG
228 ~RefCounted() { MOZ_ASSERT(mRefCnt == detail::DEAD); }
229 #endif
231 public:
232 // Compatibility with RefPtr.
233 void AddRef() const {
234 // Note: this method must be thread safe for AtomicRefCounted.
235 MOZ_ASSERT(int32_t(mRefCnt) >= 0);
236 MozRefCountType cnt = ++mRefCnt;
237 detail::RefCountLogger::logAddRef(static_cast<const T*>(this), cnt);
240 void Release() const {
241 // Note: this method must be thread safe for AtomicRefCounted.
242 MOZ_ASSERT(int32_t(mRefCnt) > 0);
243 detail::RefCountLogger::ReleaseLogger logger(static_cast<const T*>(this));
244 MozRefCountType cnt = --mRefCnt;
245 // Note: it's not safe to touch |this| after decrementing the refcount,
246 // except for below.
247 logger.logRelease(cnt);
248 if (0 == cnt) {
249 // Because we have atomically decremented the refcount above, only
250 // one thread can get a 0 count here, so as long as we can assume that
251 // everything else in the system is accessing this object through
252 // RefPtrs, it's safe to access |this| here.
253 #ifdef DEBUG
254 mRefCnt = detail::DEAD;
255 #endif
256 delete static_cast<const T*>(this);
260 using HasThreadSafeRefCnt =
261 std::integral_constant<bool, Atomicity == AtomicRefCount>;
263 // Compatibility with wtf::RefPtr.
264 void ref() { AddRef(); }
265 void deref() { Release(); }
266 MozRefCountType refCount() const { return mRefCnt; }
267 bool hasOneRef() const {
268 MOZ_ASSERT(mRefCnt > 0);
269 return mRefCnt == 1;
272 private:
273 mutable RC<MozRefCountType, Atomicity> mRefCnt;
276 #ifdef MOZ_REFCOUNTED_LEAK_CHECKING
277 // Passing override for the optional argument marks the typeName and
278 // typeSize functions defined by this macro as overrides.
279 # define MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(T, ...) \
280 virtual const char* typeName() const __VA_ARGS__ { return #T; } \
281 virtual size_t typeSize() const __VA_ARGS__ { return sizeof(*this); }
282 #else
283 # define MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(T, ...)
284 #endif
286 // Note that this macro is expanded unconditionally because it declares only
287 // two small inline functions which will hopefully get eliminated by the linker
288 // in non-leak-checking builds.
289 #define MOZ_DECLARE_REFCOUNTED_TYPENAME(T) \
290 const char* typeName() const { return #T; } \
291 size_t typeSize() const { return sizeof(*this); }
293 } // namespace detail
295 template <typename T>
296 class RefCounted : public detail::RefCounted<T, detail::NonAtomicRefCount> {
297 public:
298 ~RefCounted() {
299 static_assert(std::is_base_of<RefCounted, T>::value,
300 "T must derive from RefCounted<T>");
304 namespace external {
307 * AtomicRefCounted<T> is like RefCounted<T>, with an atomically updated
308 * reference counter.
310 * NOTE: Please do not use this class, use NS_INLINE_DECL_THREADSAFE_REFCOUNTING
311 * instead.
313 template <typename T>
314 class AtomicRefCounted
315 : public mozilla::detail::RefCounted<T, mozilla::detail::AtomicRefCount> {
316 public:
317 ~AtomicRefCounted() {
318 static_assert(std::is_base_of<AtomicRefCounted, T>::value,
319 "T must derive from AtomicRefCounted<T>");
323 } // namespace external
325 } // namespace mozilla
327 #endif // mozilla_RefCounted_h