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 "mozilla/AlreadyAddRefed.h"
13 #include "mozilla/Assertions.h"
14 #include "mozilla/Atomics.h"
15 #include "mozilla/Attributes.h"
16 #include "mozilla/Move.h"
17 #include "mozilla/RefCountType.h"
18 #include "mozilla/TypeTraits.h"
22 #if defined(MOZILLA_INTERNAL_API)
26 #if defined(MOZILLA_INTERNAL_API) && \
27 (defined(DEBUG) || defined(FORCE_BUILD_REFCNT_LOGGING))
28 # define MOZ_REFCOUNTED_LEAK_CHECKING
34 * RefCounted<T> is a sort of a "mixin" for a class T. RefCounted
35 * manages, well, refcounting for T, and because RefCounted is
36 * parameterized on T, RefCounted<T> can call T's destructor directly.
37 * This means T doesn't need to have a virtual dtor and so doesn't
40 * RefCounted<T> is created with refcount == 0. Newly-allocated
41 * RefCounted<T> must immediately be assigned to a RefPtr to make the
42 * refcount > 0. It's an error to allocate and free a bare
43 * RefCounted<T>, i.e. outside of the RefPtr machinery. Attempts to
44 * do so will abort DEBUG builds.
46 * Live RefCounted<T> have refcount > 0. The lifetime (refcounts) of
47 * live RefCounted<T> are controlled by RefPtr<T> and
48 * RefPtr<super/subclass of T>. Upon a transition from refcounted==1
49 * to 0, the RefCounted<T> "dies" and is destroyed. The "destroyed"
50 * state is represented in DEBUG builds by refcount==0xffffdead. This
51 * state distinguishes use-before-ref (refcount==0) from
52 * use-after-destroy (refcount==0xffffdead).
54 * Note that when deriving from RefCounted or AtomicRefCounted, you
55 * should add MOZ_DECLARE_REFCOUNTED_TYPENAME(ClassName) to the public
56 * section of your class, where ClassName is the name of your class.
58 * Note: SpiderMonkey should use js::RefCounted instead since that type
59 * will use appropriate js_delete and also not break ref-count logging.
62 const MozRefCountType DEAD
= 0xffffdead;
64 // When building code that gets compiled into Gecko, try to use the
65 // trace-refcount leak logging facilities.
66 #ifdef MOZ_REFCOUNTED_LEAK_CHECKING
67 class RefCountLogger
{
69 static void logAddRef(const void* aPointer
, MozRefCountType aRefCount
,
70 const char* aTypeName
, uint32_t aInstanceSize
) {
71 MOZ_ASSERT(aRefCount
!= DEAD
);
72 NS_LogAddRef(const_cast<void*>(aPointer
), aRefCount
, aTypeName
,
76 static void logRelease(const void* aPointer
, MozRefCountType aRefCount
,
77 const char* aTypeName
) {
78 MOZ_ASSERT(aRefCount
!= DEAD
);
79 NS_LogRelease(const_cast<void*>(aPointer
), aRefCount
, aTypeName
);
84 // This is used WeakPtr.h as well as this file.
85 enum RefCountAtomicity
{ AtomicRefCount
, NonAtomicRefCount
};
87 template <typename T
, RefCountAtomicity Atomicity
,
88 recordreplay::Behavior Recording
>
91 explicit RC(T aCount
) : mValue(aCount
) {}
93 T
operator++() { return ++mValue
; }
94 T
operator--() { return --mValue
; }
96 void operator=(const T
& aValue
) { mValue
= aValue
; }
98 operator T() const { return mValue
; }
104 template <typename T
, recordreplay::Behavior Recording
>
105 class RC
<T
, AtomicRefCount
, Recording
> {
107 explicit RC(T aCount
) : mValue(aCount
) {}
110 // Memory synchronization is not required when incrementing a
111 // reference count. The first increment of a reference count on a
112 // thread is not important, since the first use of the object on a
113 // thread can happen before it. What is important is the transfer
114 // of the pointer to that thread, which may happen prior to the
115 // first increment on that thread. The necessary memory
116 // synchronization is done by the mechanism that transfers the
117 // pointer between threads.
118 AutoRecordAtomicAccess
<Recording
> record(this);
119 return mValue
.fetch_add(1, std::memory_order_relaxed
) + 1;
123 // Since this may be the last release on this thread, we need
124 // release semantics so that prior writes on this thread are visible
125 // to the thread that destroys the object when it reads mValue with
126 // acquire semantics.
127 AutoRecordAtomicAccess
<Recording
> record(this);
128 T result
= mValue
.fetch_sub(1, std::memory_order_release
) - 1;
130 // We're going to destroy the object on this thread, so we need
131 // acquire semantics to synchronize with the memory released by
132 // the last release on other threads, that is, to ensure that
133 // writes prior to that release are now visible on this thread.
134 std::atomic_thread_fence(std::memory_order_acquire
);
139 // This method is only called in debug builds, so we're not too concerned
140 // about its performance.
141 void operator=(const T
& aValue
) {
142 AutoRecordAtomicAccess
<Recording
> record(this);
143 mValue
.store(aValue
, std::memory_order_seq_cst
);
147 // Use acquire semantics since we're not sure what the caller is
149 AutoRecordAtomicAccess
<Recording
> record(this);
150 return mValue
.load(std::memory_order_acquire
);
154 std::atomic
<T
> mValue
;
157 template <typename T
, RefCountAtomicity Atomicity
,
158 recordreplay::Behavior Recording
= recordreplay::Behavior::Preserve
>
161 RefCounted() : mRefCnt(0) {}
162 ~RefCounted() { MOZ_ASSERT(mRefCnt
== detail::DEAD
); }
165 // Compatibility with nsRefPtr.
166 void AddRef() const {
167 // Note: this method must be thread safe for AtomicRefCounted.
168 MOZ_ASSERT(int32_t(mRefCnt
) >= 0);
169 #ifndef MOZ_REFCOUNTED_LEAK_CHECKING
172 const char* type
= static_cast<const T
*>(this)->typeName();
173 uint32_t size
= static_cast<const T
*>(this)->typeSize();
174 const void* ptr
= static_cast<const T
*>(this);
175 MozRefCountType cnt
= ++mRefCnt
;
176 detail::RefCountLogger::logAddRef(ptr
, cnt
, type
, size
);
180 void Release() const {
181 // Note: this method must be thread safe for AtomicRefCounted.
182 MOZ_ASSERT(int32_t(mRefCnt
) > 0);
183 #ifndef MOZ_REFCOUNTED_LEAK_CHECKING
184 MozRefCountType cnt
= --mRefCnt
;
186 const char* type
= static_cast<const T
*>(this)->typeName();
187 const void* ptr
= static_cast<const T
*>(this);
188 MozRefCountType cnt
= --mRefCnt
;
189 // Note: it's not safe to touch |this| after decrementing the refcount,
191 detail::RefCountLogger::logRelease(ptr
, cnt
, type
);
194 // Because we have atomically decremented the refcount above, only
195 // one thread can get a 0 count here, so as long as we can assume that
196 // everything else in the system is accessing this object through
197 // RefPtrs, it's safe to access |this| here.
199 mRefCnt
= detail::DEAD
;
201 delete static_cast<const T
*>(this);
205 // Compatibility with wtf::RefPtr.
206 void ref() { AddRef(); }
207 void deref() { Release(); }
208 MozRefCountType
refCount() const { return mRefCnt
; }
209 bool hasOneRef() const {
210 MOZ_ASSERT(mRefCnt
> 0);
215 mutable RC
<MozRefCountType
, Atomicity
, Recording
> mRefCnt
;
218 #ifdef MOZ_REFCOUNTED_LEAK_CHECKING
219 // Passing override for the optional argument marks the typeName and
220 // typeSize functions defined by this macro as overrides.
221 # define MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(T, ...) \
222 virtual const char* typeName() const __VA_ARGS__ { return #T; } \
223 virtual size_t typeSize() const __VA_ARGS__ { return sizeof(*this); }
225 # define MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(T, ...)
228 // Note that this macro is expanded unconditionally because it declares only
229 // two small inline functions which will hopefully get eliminated by the linker
230 // in non-leak-checking builds.
231 #define MOZ_DECLARE_REFCOUNTED_TYPENAME(T) \
232 const char* typeName() const { return #T; } \
233 size_t typeSize() const { return sizeof(*this); }
235 } // namespace detail
237 template <typename T
>
238 class RefCounted
: public detail::RefCounted
<T
, detail::NonAtomicRefCount
> {
241 static_assert(IsBaseOf
<RefCounted
, T
>::value
,
242 "T must derive from RefCounted<T>");
249 * AtomicRefCounted<T> is like RefCounted<T>, with an atomically updated
252 * NOTE: Please do not use this class, use NS_INLINE_DECL_THREADSAFE_REFCOUNTING
255 template <typename T
,
256 recordreplay::Behavior Recording
= recordreplay::Behavior::Preserve
>
257 class AtomicRefCounted
258 : public mozilla::detail::RefCounted
<T
, mozilla::detail::AtomicRefCount
,
261 ~AtomicRefCounted() {
262 static_assert(IsBaseOf
<AtomicRefCounted
, T
>::value
,
263 "T must derive from AtomicRefCounted<T>");
267 } // namespace external
269 } // namespace mozilla
271 #endif // mozilla_RefCounted_h