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
70 static void logAddRef(const void* aPointer
, MozRefCountType aRefCount
,
71 const char* aTypeName
, uint32_t aInstanceSize
)
73 MOZ_ASSERT(aRefCount
!= DEAD
);
74 NS_LogAddRef(const_cast<void*>(aPointer
), aRefCount
, aTypeName
,
78 static void logRelease(const void* aPointer
, MozRefCountType aRefCount
,
79 const char* aTypeName
)
81 MOZ_ASSERT(aRefCount
!= DEAD
);
82 NS_LogRelease(const_cast<void*>(aPointer
), aRefCount
, aTypeName
);
87 // This is used WeakPtr.h as well as this file.
88 enum RefCountAtomicity
94 template<typename T
, RefCountAtomicity Atomicity
>
98 explicit RC(T aCount
) : mValue(aCount
) {}
100 T
operator++() { return ++mValue
; }
101 T
operator--() { return --mValue
; }
103 void operator=(const T
& aValue
) { mValue
= aValue
; }
105 operator T() const { return mValue
; }
112 class RC
<T
, AtomicRefCount
>
115 explicit RC(T aCount
) : mValue(aCount
) {}
119 // Memory synchronization is not required when incrementing a
120 // reference count. The first increment of a reference count on a
121 // thread is not important, since the first use of the object on a
122 // thread can happen before it. What is important is the transfer
123 // of the pointer to that thread, which may happen prior to the
124 // first increment on that thread. The necessary memory
125 // synchronization is done by the mechanism that transfers the
126 // pointer between threads.
127 return mValue
.fetch_add(1, std::memory_order_relaxed
) + 1;
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;
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 std::atomic_thread_fence(std::memory_order_acquire
);
147 // This method is only called in debug builds, so we're not too concerned
148 // about its performance.
149 void operator=(const T
& aValue
) { mValue
.store(aValue
, std::memory_order_seq_cst
); }
153 // Use acquire semantics since we're not sure what the caller is
155 return mValue
.load(std::memory_order_acquire
);
159 std::atomic
<T
> mValue
;
162 template<typename T
, RefCountAtomicity Atomicity
>
166 RefCounted() : mRefCnt(0) {}
167 ~RefCounted() { MOZ_ASSERT(mRefCnt
== detail::DEAD
); }
170 // Compatibility with nsRefPtr.
173 // Note: this method must be thread safe for AtomicRefCounted.
174 MOZ_ASSERT(int32_t(mRefCnt
) >= 0);
175 #ifndef MOZ_REFCOUNTED_LEAK_CHECKING
178 const char* type
= static_cast<const T
*>(this)->typeName();
179 uint32_t size
= static_cast<const T
*>(this)->typeSize();
180 const void* ptr
= static_cast<const T
*>(this);
181 MozRefCountType cnt
= ++mRefCnt
;
182 detail::RefCountLogger::logAddRef(ptr
, cnt
, type
, size
);
188 // Note: this method must be thread safe for AtomicRefCounted.
189 MOZ_ASSERT(int32_t(mRefCnt
) > 0);
190 #ifndef MOZ_REFCOUNTED_LEAK_CHECKING
191 MozRefCountType cnt
= --mRefCnt
;
193 const char* type
= static_cast<const T
*>(this)->typeName();
194 const void* ptr
= static_cast<const T
*>(this);
195 MozRefCountType cnt
= --mRefCnt
;
196 // Note: it's not safe to touch |this| after decrementing the refcount,
198 detail::RefCountLogger::logRelease(ptr
, cnt
, type
);
201 // Because we have atomically decremented the refcount above, only
202 // one thread can get a 0 count here, so as long as we can assume that
203 // everything else in the system is accessing this object through
204 // RefPtrs, it's safe to access |this| here.
206 mRefCnt
= detail::DEAD
;
208 delete static_cast<const T
*>(this);
212 // Compatibility with wtf::RefPtr.
213 void ref() { AddRef(); }
214 void deref() { Release(); }
215 MozRefCountType
refCount() const { return mRefCnt
; }
216 bool hasOneRef() const
218 MOZ_ASSERT(mRefCnt
> 0);
223 mutable RC
<MozRefCountType
, Atomicity
> mRefCnt
;
226 #ifdef MOZ_REFCOUNTED_LEAK_CHECKING
227 // Passing override for the optional argument marks the typeName and
228 // typeSize functions defined by this macro as overrides.
229 #define MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(T, ...) \
230 virtual const char* typeName() const __VA_ARGS__ { return #T; } \
231 virtual size_t typeSize() const __VA_ARGS__ { return sizeof(*this); }
233 #define MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(T, ...)
236 // Note that this macro is expanded unconditionally because it declares only
237 // two small inline functions which will hopefully get eliminated by the linker
238 // in non-leak-checking builds.
239 #define MOZ_DECLARE_REFCOUNTED_TYPENAME(T) \
240 const char* typeName() const { return #T; } \
241 size_t typeSize() const { return sizeof(*this); }
243 } // namespace detail
246 class RefCounted
: public detail::RefCounted
<T
, detail::NonAtomicRefCount
>
251 static_assert(IsBaseOf
<RefCounted
, T
>::value
,
252 "T must derive from RefCounted<T>");
259 * AtomicRefCounted<T> is like RefCounted<T>, with an atomically updated
262 * NOTE: Please do not use this class, use NS_INLINE_DECL_THREADSAFE_REFCOUNTING
266 class AtomicRefCounted
:
267 public mozilla::detail::RefCounted
<T
, mozilla::detail::AtomicRefCount
>
272 static_assert(IsBaseOf
<AtomicRefCounted
, T
>::value
,
273 "T must derive from AtomicRefCounted<T>");
277 } // namespace external
279 } // namespace mozilla
281 #endif // mozilla_RefCounted_h