Bug 1642579 [wpt PR 23909] - [COOP access reporting] Preliminary WPT tests., a=testonly
[gecko.git] / mfbt / RefCounted.h
blob771ff3cb612f57ced61b770d569e13b52c850d7a
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 <atomic>
13 #include <utility>
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 #if defined(MOZILLA_INTERNAL_API)
22 # include "nsXPCOM.h"
23 #endif
25 #if defined(MOZILLA_INTERNAL_API) && \
26 (defined(DEBUG) || defined(FORCE_BUILD_REFCNT_LOGGING))
27 # define MOZ_REFCOUNTED_LEAK_CHECKING
28 #endif
30 namespace mozilla {
32 /**
33 * RefCounted<T> is a sort of a "mixin" for a class T. RefCounted
34 * manages, well, refcounting for T, and because RefCounted is
35 * parameterized on T, RefCounted<T> can call T's destructor directly.
36 * This means T doesn't need to have a virtual dtor and so doesn't
37 * need a vtable.
39 * RefCounted<T> is created with refcount == 0. Newly-allocated
40 * RefCounted<T> must immediately be assigned to a RefPtr to make the
41 * refcount > 0. It's an error to allocate and free a bare
42 * RefCounted<T>, i.e. outside of the RefPtr machinery. Attempts to
43 * do so will abort DEBUG builds.
45 * Live RefCounted<T> have refcount > 0. The lifetime (refcounts) of
46 * live RefCounted<T> are controlled by RefPtr<T> and
47 * RefPtr<super/subclass of T>. Upon a transition from refcounted==1
48 * to 0, the RefCounted<T> "dies" and is destroyed. The "destroyed"
49 * state is represented in DEBUG builds by refcount==0xffffdead. This
50 * state distinguishes use-before-ref (refcount==0) from
51 * use-after-destroy (refcount==0xffffdead).
53 * Note that when deriving from RefCounted or AtomicRefCounted, you
54 * should add MOZ_DECLARE_REFCOUNTED_TYPENAME(ClassName) to the public
55 * section of your class, where ClassName is the name of your class.
57 * Note: SpiderMonkey should use js::RefCounted instead since that type
58 * will use appropriate js_delete and also not break ref-count logging.
60 namespace detail {
61 const MozRefCountType DEAD = 0xffffdead;
63 // When building code that gets compiled into Gecko, try to use the
64 // trace-refcount leak logging facilities.
65 #ifdef MOZ_REFCOUNTED_LEAK_CHECKING
66 class RefCountLogger {
67 public:
68 static void logAddRef(const void* aPointer, MozRefCountType aRefCount,
69 const char* aTypeName, uint32_t aInstanceSize) {
70 MOZ_ASSERT(aRefCount != DEAD);
71 NS_LogAddRef(const_cast<void*>(aPointer), aRefCount, aTypeName,
72 aInstanceSize);
75 static void logRelease(const void* aPointer, MozRefCountType aRefCount,
76 const char* aTypeName) {
77 MOZ_ASSERT(aRefCount != DEAD);
78 NS_LogRelease(const_cast<void*>(aPointer), aRefCount, aTypeName);
81 #endif
83 // This is used WeakPtr.h as well as this file.
84 enum RefCountAtomicity { AtomicRefCount, NonAtomicRefCount };
86 template <typename T, RefCountAtomicity Atomicity>
87 class RC {
88 public:
89 explicit RC(T aCount) : mValue(aCount) {}
91 RC(const RC&) = delete;
92 RC& operator=(const RC&) = delete;
93 RC(RC&&) = delete;
94 RC& operator=(RC&&) = delete;
96 T operator++() { return ++mValue; }
97 T operator--() { return --mValue; }
99 #ifdef DEBUG
100 void operator=(const T& aValue) { mValue = aValue; }
101 #endif
103 operator T() const { return mValue; }
105 private:
106 T mValue;
109 template <typename T>
110 class RC<T, AtomicRefCount> {
111 public:
112 explicit RC(T aCount) : mValue(aCount) {}
114 RC(const RC&) = delete;
115 RC& operator=(const RC&) = delete;
116 RC(RC&&) = delete;
117 RC& operator=(RC&&) = delete;
119 T operator++() {
120 // Memory synchronization is not required when incrementing a
121 // reference count. The first increment of a reference count on a
122 // thread is not important, since the first use of the object on a
123 // thread can happen before it. What is important is the transfer
124 // of the pointer to that thread, which may happen prior to the
125 // first increment on that thread. The necessary memory
126 // synchronization is done by the mechanism that transfers the
127 // pointer between threads.
128 return mValue.fetch_add(1, std::memory_order_relaxed) + 1;
131 T operator--() {
132 // Since this may be the last release on this thread, we need
133 // release semantics so that prior writes on this thread are visible
134 // to the thread that destroys the object when it reads mValue with
135 // acquire semantics.
136 T result = mValue.fetch_sub(1, std::memory_order_release) - 1;
137 if (result == 0) {
138 // We're going to destroy the object on this thread, so we need
139 // acquire semantics to synchronize with the memory released by
140 // the last release on other threads, that is, to ensure that
141 // writes prior to that release are now visible on this thread.
142 #ifdef MOZ_TSAN
143 // TSan doesn't understand std::atomic_thread_fence, so in order
144 // to avoid a false positive for every time a refcounted object
145 // is deleted, we replace the fence with an atomic operation.
146 mValue.load(std::memory_order_acquire);
147 #else
148 std::atomic_thread_fence(std::memory_order_acquire);
149 #endif
151 return result;
154 #ifdef DEBUG
155 // This method is only called in debug builds, so we're not too concerned
156 // about its performance.
157 void operator=(const T& aValue) {
158 mValue.store(aValue, std::memory_order_seq_cst);
160 #endif
162 operator T() const {
163 // Use acquire semantics since we're not sure what the caller is
164 // doing.
165 return mValue.load(std::memory_order_acquire);
168 private:
169 std::atomic<T> mValue;
172 template <typename T, RefCountAtomicity Atomicity>
173 class RefCounted {
174 protected:
175 RefCounted() : mRefCnt(0) {}
176 #ifdef DEBUG
177 ~RefCounted() { MOZ_ASSERT(mRefCnt == detail::DEAD); }
178 #endif
180 public:
181 // Compatibility with nsRefPtr.
182 void AddRef() const {
183 // Note: this method must be thread safe for AtomicRefCounted.
184 MOZ_ASSERT(int32_t(mRefCnt) >= 0);
185 #ifndef MOZ_REFCOUNTED_LEAK_CHECKING
186 ++mRefCnt;
187 #else
188 const char* type = static_cast<const T*>(this)->typeName();
189 uint32_t size = static_cast<const T*>(this)->typeSize();
190 const void* ptr = static_cast<const T*>(this);
191 MozRefCountType cnt = ++mRefCnt;
192 detail::RefCountLogger::logAddRef(ptr, cnt, type, size);
193 #endif
196 void Release() const {
197 // Note: this method must be thread safe for AtomicRefCounted.
198 MOZ_ASSERT(int32_t(mRefCnt) > 0);
199 #ifndef MOZ_REFCOUNTED_LEAK_CHECKING
200 MozRefCountType cnt = --mRefCnt;
201 #else
202 const char* type = static_cast<const T*>(this)->typeName();
203 const void* ptr = static_cast<const T*>(this);
204 MozRefCountType cnt = --mRefCnt;
205 // Note: it's not safe to touch |this| after decrementing the refcount,
206 // except for below.
207 detail::RefCountLogger::logRelease(ptr, cnt, type);
208 #endif
209 if (0 == cnt) {
210 // Because we have atomically decremented the refcount above, only
211 // one thread can get a 0 count here, so as long as we can assume that
212 // everything else in the system is accessing this object through
213 // RefPtrs, it's safe to access |this| here.
214 #ifdef DEBUG
215 mRefCnt = detail::DEAD;
216 #endif
217 delete static_cast<const T*>(this);
221 // Compatibility with wtf::RefPtr.
222 void ref() { AddRef(); }
223 void deref() { Release(); }
224 MozRefCountType refCount() const { return mRefCnt; }
225 bool hasOneRef() const {
226 MOZ_ASSERT(mRefCnt > 0);
227 return mRefCnt == 1;
230 private:
231 mutable RC<MozRefCountType, Atomicity> mRefCnt;
234 #ifdef MOZ_REFCOUNTED_LEAK_CHECKING
235 // Passing override for the optional argument marks the typeName and
236 // typeSize functions defined by this macro as overrides.
237 # define MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(T, ...) \
238 virtual const char* typeName() const __VA_ARGS__ { return #T; } \
239 virtual size_t typeSize() const __VA_ARGS__ { return sizeof(*this); }
240 #else
241 # define MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(T, ...)
242 #endif
244 // Note that this macro is expanded unconditionally because it declares only
245 // two small inline functions which will hopefully get eliminated by the linker
246 // in non-leak-checking builds.
247 #define MOZ_DECLARE_REFCOUNTED_TYPENAME(T) \
248 const char* typeName() const { return #T; } \
249 size_t typeSize() const { return sizeof(*this); }
251 } // namespace detail
253 template <typename T>
254 class RefCounted : public detail::RefCounted<T, detail::NonAtomicRefCount> {
255 public:
256 ~RefCounted() {
257 static_assert(std::is_base_of<RefCounted, T>::value,
258 "T must derive from RefCounted<T>");
262 namespace external {
265 * AtomicRefCounted<T> is like RefCounted<T>, with an atomically updated
266 * reference counter.
268 * NOTE: Please do not use this class, use NS_INLINE_DECL_THREADSAFE_REFCOUNTING
269 * instead.
271 template <typename T>
272 class AtomicRefCounted
273 : public mozilla::detail::RefCounted<T, mozilla::detail::AtomicRefCount> {
274 public:
275 ~AtomicRefCounted() {
276 static_assert(std::is_base_of<AtomicRefCounted, T>::value,
277 "T must derive from AtomicRefCounted<T>");
281 } // namespace external
283 } // namespace mozilla
285 #endif // mozilla_RefCounted_h