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/. */
6 
7 /* CRTP refcounting templates.  Do not use unless you are an Expert. */
8 
9 #ifndef mozilla_RefCounted_h
10 #define mozilla_RefCounted_h
11 
12 #include <utility>
13 
14 #include "mozilla/AlreadyAddRefed.h"
15 #include "mozilla/Assertions.h"
16 #include "mozilla/Atomics.h"
17 #include "mozilla/Attributes.h"
18 #include "mozilla/RefCountType.h"
19 
20 #ifdef __wasi__
21 #  include "mozilla/WasiAtomic.h"
22 #else
23 #  include <atomic>
24 #endif  // __wasi__
25 
26 #if defined(MOZILLA_INTERNAL_API)
27 #  include "nsXPCOM.h"
28 #endif
29 
30 #if defined(MOZILLA_INTERNAL_API) && \
31     (defined(DEBUG) || defined(FORCE_BUILD_REFCNT_LOGGING))
32 #  define MOZ_REFCOUNTED_LEAK_CHECKING
33 #endif
34 
35 namespace mozilla {
36 
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.
43  *
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.
49  *
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).
57  *
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.
61  *
62  * Note: SpiderMonkey should use js::RefCounted instead since that type
63  * will use appropriate js_delete and also not break ref-count logging.
64  */
65 namespace detail {
66 const MozRefCountType DEAD = 0xffffdead;
67 
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>
logAddRef(const T * aPointer,MozRefCountType aRefCount)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
83   }
84 
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>
ReleaseLogger(const T * aPointer)92     explicit ReleaseLogger(const T* aPointer)
93 #ifdef MOZ_REFCOUNTED_LEAK_CHECKING
94         : mPointer(aPointer),
95           mTypeName(aPointer->typeName())
96 #endif
97     {
98     }
99 
logRelease(MozRefCountType aRefCount)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
105     }
106 
107 #ifdef MOZ_REFCOUNTED_LEAK_CHECKING
108     const void* mPointer;
109     const char* mTypeName;
110 #endif
111   };
112 };
113 
114 // This is used WeakPtr.h as well as this file.
115 enum RefCountAtomicity { AtomicRefCount, NonAtomicRefCount };
116 
117 template <typename T, RefCountAtomicity Atomicity>
118 class RC {
119  public:
RC(T aCount)120   explicit RC(T aCount) : mValue(aCount) {}
121 
122   RC(const RC&) = delete;
123   RC& operator=(const RC&) = delete;
124   RC(RC&&) = delete;
125   RC& operator=(RC&&) = delete;
126 
127   T operator++() { return ++mValue; }
128   T operator--() { return --mValue; }
129 
130 #ifdef DEBUG
131   void operator=(const T& aValue) { mValue = aValue; }
132 #endif
133 
T()134   operator T() const { return mValue; }
135 
136  private:
137   T mValue;
138 };
139 
140 template <typename T>
141 class RC<T, AtomicRefCount> {
142  public:
RC(T aCount)143   explicit RC(T aCount) : mValue(aCount) {}
144 
145   RC(const RC&) = delete;
146   RC& operator=(const RC&) = delete;
147   RC(RC&&) = delete;
148   RC& operator=(RC&&) = delete;
149 
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;
160   }
161 
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
181     }
182     return result;
183   }
184 
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);
190   }
191 #endif
192 
T()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);
197   }
198 
IncrementIfNonzero()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.
203     //
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;
214       }
215     }
216     return 0;
217   }
218 
219  private:
220   std::atomic<T> mValue;
221 };
222 
223 template <typename T, RefCountAtomicity Atomicity>
224 class RefCounted {
225  protected:
RefCounted()226   RefCounted() : mRefCnt(0) {}
227 #ifdef DEBUG
~RefCounted()228   ~RefCounted() { MOZ_ASSERT(mRefCnt == detail::DEAD); }
229 #endif
230 
231  public:
232   // Compatibility with RefPtr.
AddRef()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);
238   }
239 
Release()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);
257     }
258   }
259 
260   // Compatibility with wtf::RefPtr.
ref()261   void ref() { AddRef(); }
deref()262   void deref() { Release(); }
refCount()263   MozRefCountType refCount() const { return mRefCnt; }
hasOneRef()264   bool hasOneRef() const {
265     MOZ_ASSERT(mRefCnt > 0);
266     return mRefCnt == 1;
267   }
268 
269  private:
270   mutable RC<MozRefCountType, Atomicity> mRefCnt;
271 };
272 
273 #ifdef MOZ_REFCOUNTED_LEAK_CHECKING
274 // Passing override for the optional argument marks the typeName and
275 // typeSize functions defined by this macro as overrides.
276 #  define MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(T, ...)           \
277     virtual const char* typeName() const __VA_ARGS__ { return #T; } \
278     virtual size_t typeSize() const __VA_ARGS__ { return sizeof(*this); }
279 #else
280 #  define MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(T, ...)
281 #endif
282 
283 // Note that this macro is expanded unconditionally because it declares only
284 // two small inline functions which will hopefully get eliminated by the linker
285 // in non-leak-checking builds.
286 #define MOZ_DECLARE_REFCOUNTED_TYPENAME(T)    \
287   const char* typeName() const { return #T; } \
288   size_t typeSize() const { return sizeof(*this); }
289 
290 }  // namespace detail
291 
292 template <typename T>
293 class RefCounted : public detail::RefCounted<T, detail::NonAtomicRefCount> {
294  public:
~RefCounted()295   ~RefCounted() {
296     static_assert(std::is_base_of<RefCounted, T>::value,
297                   "T must derive from RefCounted<T>");
298   }
299 };
300 
301 namespace external {
302 
303 /**
304  * AtomicRefCounted<T> is like RefCounted<T>, with an atomically updated
305  * reference counter.
306  *
307  * NOTE: Please do not use this class, use NS_INLINE_DECL_THREADSAFE_REFCOUNTING
308  * instead.
309  */
310 template <typename T>
311 class AtomicRefCounted
312     : public mozilla::detail::RefCounted<T, mozilla::detail::AtomicRefCount> {
313  public:
~AtomicRefCounted()314   ~AtomicRefCounted() {
315     static_assert(std::is_base_of<AtomicRefCounted, T>::value,
316                   "T must derive from AtomicRefCounted<T>");
317   }
318 };
319 
320 }  // namespace external
321 
322 }  // namespace mozilla
323 
324 #endif  // mozilla_RefCounted_h
325