| 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 |
#include <type_traits> |
| 14 |
|
| 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" |
| 20 |
|
| 21 |
#ifdef __wasi__ |
| 22 |
# include "mozilla/WasiAtomic.h" |
| 23 |
#else |
| 24 |
# include <atomic> |
| 25 |
#endif // __wasi__ |
| 26 |
|
| 27 |
#if defined(MOZ_SUPPORT_LEAKCHECKING) && defined(NS_BUILD_REFCNT_LOGGING) |
| 28 |
# define MOZ_REFCOUNTED_LEAK_CHECKING |
| 29 |
#endif |
| 30 |
|
| 31 |
namespace mozilla { |
| 32 |
|
| 33 |
/** |
| 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 |
| 38 |
* need a vtable. |
| 39 |
* |
| 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. |
| 45 |
* |
| 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). |
| 53 |
* |
| 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. |
| 57 |
*/ |
| 58 |
namespace detail { |
| 59 |
const MozRefCountType DEAD = 0xffffdead; |
| 60 |
|
| 61 |
#ifdef MOZ_REFCOUNTED_LEAK_CHECKING |
| 62 |
// When this header is included in SpiderMonkey code, NS_LogAddRef and |
| 63 |
// NS_LogRelease are not available. To work around this, we call these |
| 64 |
// functions through a function pointer set by SetLeakCheckingFunctions. |
| 65 |
// Note: these are globals because GCC on Linux reports undefined-reference |
| 66 |
// errors when they're static members of the RefCountLogger class. |
| 67 |
using LogAddRefFunc = void (*)(void* aPtr, MozRefCountType aNewRefCnt, |
| 68 |
const char* aTypeName, uint32_t aClassSize); |
| 69 |
using LogReleaseFunc = void (*)(void* aPtr, MozRefCountType aNewRefCnt, |
| 70 |
const char* aTypeName); |
| 71 |
extern MFBT_DATA LogAddRefFunc gLogAddRefFunc; |
| 72 |
extern MFBT_DATA LogReleaseFunc gLogReleaseFunc; |
| 73 |
extern MFBT_DATA size_t gNumStaticCtors; |
| 74 |
extern MFBT_DATA const char* gLastStaticCtorTypeName; |
| 75 |
#endif |
| 76 |
|
| 77 |
// When building code that gets compiled into Gecko, try to use the |
| 78 |
// trace-refcount leak logging facilities. |
| 79 |
class RefCountLogger { |
| 80 |
public: |
| 81 |
// Called by `RefCounted`-like classes to log a successful AddRef call in the |
| 82 |
// Gecko leak-logging system. This call is a no-op outside of Gecko. Should be |
| 83 |
// called afer incrementing the reference count. |
| 84 |
template <class T> |
| 85 |
static void logAddRef(const T* aPointer, MozRefCountType aRefCount) { |
| 86 |
#ifdef MOZ_REFCOUNTED_LEAK_CHECKING |
| 87 |
const void* pointer = aPointer; |
| 88 |
const char* typeName = aPointer->typeName(); |
| 89 |
uint32_t typeSize = aPointer->typeSize(); |
| 90 |
if (gLogAddRefFunc) { |
| 91 |
gLogAddRefFunc(const_cast<void*>(pointer), aRefCount, typeName, typeSize); |
| 92 |
} else { |
| 93 |
gNumStaticCtors++; |
| 94 |
gLastStaticCtorTypeName = typeName; |
| 95 |
} |
| 96 |
#endif |
| 97 |
} |
| 98 |
|
| 99 |
#ifdef MOZ_REFCOUNTED_LEAK_CHECKING |
| 100 |
static MFBT_API void SetLeakCheckingFunctions(LogAddRefFunc aLogAddRefFunc, |
| 101 |
LogReleaseFunc aLogReleaseFunc); |
| 102 |
#endif |
| 103 |
|
| 104 |
// Created by `RefCounted`-like classes to log a successful Release call in |
| 105 |
// the Gecko leak-logging system. The constructor should be invoked before the |
| 106 |
// refcount is decremented to avoid invoking `typeName()` with a zero |
| 107 |
// reference count. This call is a no-op outside of Gecko. |
| 108 |
class MOZ_STACK_CLASS ReleaseLogger final { |
| 109 |
public: |
| 110 |
template <class T> |
| 111 |
explicit ReleaseLogger(const T* aPointer) |
| 112 |
#ifdef MOZ_REFCOUNTED_LEAK_CHECKING |
| 113 |
: mPointer(aPointer), |
| 114 |
mTypeName(aPointer->typeName()) |
| 115 |
#endif |
| 116 |
{ |
| 117 |
} |
| 118 |
|
| 119 |
void logRelease(MozRefCountType aRefCount) { |
| 120 |
#ifdef MOZ_REFCOUNTED_LEAK_CHECKING |
| 121 |
MOZ_ASSERT(aRefCount != DEAD); |
| 122 |
if (gLogReleaseFunc) { |
| 123 |
gLogReleaseFunc(const_cast<void*>(mPointer), aRefCount, mTypeName); |
| 124 |
} else { |
| 125 |
gNumStaticCtors++; |
| 126 |
gLastStaticCtorTypeName = mTypeName; |
| 127 |
} |
| 128 |
#endif |
| 129 |
} |
| 130 |
|
| 131 |
#ifdef MOZ_REFCOUNTED_LEAK_CHECKING |
| 132 |
const void* mPointer; |
| 133 |
const char* mTypeName; |
| 134 |
#endif |
| 135 |
}; |
| 136 |
}; |
| 137 |
|
| 138 |
// This is used WeakPtr.h as well as this file. |
| 139 |
enum RefCountAtomicity { AtomicRefCount, NonAtomicRefCount }; |
| 140 |
|
| 141 |
template <typename T, RefCountAtomicity Atomicity> |
| 142 |
class RC { |
| 143 |
public: |
| 144 |
explicit RC(T aCount) : mValue(aCount) {} |
| 145 |
|
| 146 |
RC(const RC&) = delete; |
| 147 |
RC& operator=(const RC&) = delete; |
| 148 |
RC(RC&&) = delete; |
| 149 |
RC& operator=(RC&&) = delete; |
| 150 |
|
| 151 |
T operator++() { return ++mValue; } |
| 152 |
T operator--() { return --mValue; } |
| 153 |
|
| 154 |
#ifdef DEBUG |
| 155 |
void operator=(const T& aValue) { mValue = aValue; } |
| 156 |
#endif |
| 157 |
|
| 158 |
operator T() const { return mValue; } |
| 159 |
|
| 160 |
private: |
| 161 |
T mValue; |
| 162 |
}; |
| 163 |
|
| 164 |
template <typename T> |
| 165 |
class RC<T, AtomicRefCount> { |
| 166 |
public: |
| 167 |
explicit RC(T aCount) : mValue(aCount) {} |
| 168 |
|
| 169 |
RC(const RC&) = delete; |
| 170 |
RC& operator=(const RC&) = delete; |
| 171 |
RC(RC&&) = delete; |
| 172 |
RC& operator=(RC&&) = delete; |
| 173 |
|
| 174 |
T operator++() { |
| 175 |
// Memory synchronization is not required when incrementing a |
| 176 |
// reference count. The first increment of a reference count on a |
| 177 |
// thread is not important, since the first use of the object on a |
| 178 |
// thread can happen before it. What is important is the transfer |
| 179 |
// of the pointer to that thread, which may happen prior to the |
| 180 |
// first increment on that thread. The necessary memory |
| 181 |
// synchronization is done by the mechanism that transfers the |
| 182 |
// pointer between threads. |
| 183 |
return mValue.fetch_add(1, std::memory_order_relaxed) + 1; |
| 184 |
} |
| 185 |
|
| 186 |
T operator--() { |
| 187 |
// Since this may be the last release on this thread, we need |
| 188 |
// release semantics so that prior writes on this thread are visible |
| 189 |
// to the thread that destroys the object when it reads mValue with |
| 190 |
// acquire semantics. |
| 191 |
T result = mValue.fetch_sub(1, std::memory_order_release) - 1; |
| 192 |
if (result == 0) { |
| 193 |
// We're going to destroy the object on this thread, so we need |
| 194 |
// acquire semantics to synchronize with the memory released by |
| 195 |
// the last release on other threads, that is, to ensure that |
| 196 |
// writes prior to that release are now visible on this thread. |
| 197 |
#if defined(MOZ_TSAN) || defined(__wasi__) |
| 198 |
// TSan doesn't understand std::atomic_thread_fence, so in order |
| 199 |
// to avoid a false positive for every time a refcounted object |
| 200 |
// is deleted, we replace the fence with an atomic operation. |
| 201 |
mValue.load(std::memory_order_acquire); |
| 202 |
#else |
| 203 |
std::atomic_thread_fence(std::memory_order_acquire); |
| 204 |
#endif |
| 205 |
} |
| 206 |
return result; |
| 207 |
} |
| 208 |
|
| 209 |
#ifdef DEBUG |
| 210 |
// This method is only called in debug builds, so we're not too concerned |
| 211 |
// about its performance. |
| 212 |
void operator=(const T& aValue) { |
| 213 |
mValue.store(aValue, std::memory_order_seq_cst); |
| 214 |
} |
| 215 |
#endif |
| 216 |
|
| 217 |
operator T() const { |
| 218 |
// Use acquire semantics since we're not sure what the caller is |
| 219 |
// doing. |
| 220 |
return mValue.load(std::memory_order_acquire); |
| 221 |
} |
| 222 |
|
| 223 |
T IncrementIfNonzero() { |
| 224 |
// This can be a relaxed load as any write of 0 that we observe will leave |
| 225 |
// the field in a permanently zero (or `DEAD`) state (so a "stale" read of 0 |
| 226 |
// is fine), and any other value is confirmed by the CAS below. |
| 227 |
// |
| 228 |
// This roughly matches rust's Arc::upgrade implementation as of rust 1.49.0 |
| 229 |
T prev = mValue.load(std::memory_order_relaxed); |
| 230 |
while (prev != 0) { |
| 231 |
MOZ_ASSERT(prev != detail::DEAD, |
| 232 |
"Cannot IncrementIfNonzero if marked as dead!"); |
| 233 |
// TODO: It may be possible to use relaxed success ordering here? |
| 234 |
if (mValue.compare_exchange_weak(prev, prev + 1, |
| 235 |
std::memory_order_acquire, |
| 236 |
std::memory_order_relaxed)) { |
| 237 |
return prev + 1; |
| 238 |
} |
| 239 |
} |
| 240 |
return 0; |
| 241 |
} |
| 242 |
|
| 243 |
private: |
| 244 |
std::atomic<T> mValue; |
| 245 |
}; |
| 246 |
|
| 247 |
template <typename T, RefCountAtomicity Atomicity> |
| 248 |
class RefCounted { |
| 249 |
protected: |
| 250 |
RefCounted() : mRefCnt(0) {} |
| 251 |
#ifdef DEBUG |
| 252 |
~RefCounted() { MOZ_ASSERT(mRefCnt == detail::DEAD); } |
| 253 |
#endif |
| 254 |
|
| 255 |
public: |
| 256 |
// Compatibility with RefPtr. |
| 257 |
void AddRef() const { |
| 258 |
// Note: this method must be thread safe for AtomicRefCounted. |
| 259 |
MOZ_ASSERT(int32_t(mRefCnt) >= 0); |
| 260 |
MozRefCountType cnt = ++mRefCnt; |
| 261 |
detail::RefCountLogger::logAddRef(static_cast<const T*>(this), cnt); |
| 262 |
} |
| 263 |
|
| 264 |
void Release() const { |
| 265 |
// Note: this method must be thread safe for AtomicRefCounted. |
| 266 |
MOZ_ASSERT(int32_t(mRefCnt) > 0); |
| 267 |
detail::RefCountLogger::ReleaseLogger logger(static_cast<const T*>(this)); |
| 268 |
MozRefCountType cnt = --mRefCnt; |
| 269 |
// Note: it's not safe to touch |this| after decrementing the refcount, |
| 270 |
// except for below. |
| 271 |
logger.logRelease(cnt); |
| 272 |
if (0 == cnt) { |
| 273 |
// Because we have atomically decremented the refcount above, only |
| 274 |
// one thread can get a 0 count here, so as long as we can assume that |
| 275 |
// everything else in the system is accessing this object through |
| 276 |
// RefPtrs, it's safe to access |this| here. |
| 277 |
#ifdef DEBUG |
| 278 |
mRefCnt = detail::DEAD; |
| 279 |
#endif |
| 280 |
delete static_cast<const T*>(this); |
| 281 |
} |
| 282 |
} |
| 283 |
|
| 284 |
using HasThreadSafeRefCnt = |
| 285 |
std::integral_constant<bool, Atomicity == AtomicRefCount>; |
| 286 |
|
| 287 |
// Compatibility with wtf::RefPtr. |
| 288 |
void ref() { AddRef(); } |
| 289 |
void deref() { Release(); } |
| 290 |
MozRefCountType refCount() const { return mRefCnt; } |
| 291 |
bool hasOneRef() const { |
| 292 |
MOZ_ASSERT(mRefCnt > 0); |
| 293 |
return mRefCnt == 1; |
| 294 |
} |
| 295 |
|
| 296 |
private: |
| 297 |
mutable RC<MozRefCountType, Atomicity> mRefCnt; |
| 298 |
}; |
| 299 |
|
| 300 |
#ifdef MOZ_REFCOUNTED_LEAK_CHECKING |
| 301 |
// Passing override for the optional argument marks the typeName and |
| 302 |
// typeSize functions defined by this macro as overrides. |
| 303 |
# define MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(T, ...) \ |
| 304 |
virtual const char* typeName() const __VA_ARGS__ { return #T; } \ |
| 305 |
virtual size_t typeSize() const __VA_ARGS__ { return sizeof(*this); } |
| 306 |
#else |
| 307 |
# define MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(T, ...) |
| 308 |
#endif |
| 309 |
|
| 310 |
// Note that this macro is expanded unconditionally because it declares only |
| 311 |
// two small inline functions which will hopefully get eliminated by the linker |
| 312 |
// in non-leak-checking builds. |
| 313 |
#define MOZ_DECLARE_REFCOUNTED_TYPENAME(T) \ |
| 314 |
const char* typeName() const { return #T; } \ |
| 315 |
size_t typeSize() const { return sizeof(*this); } |
| 316 |
|
| 317 |
} // namespace detail |
| 318 |
|
| 319 |
template <typename T> |
| 320 |
class RefCounted : public detail::RefCounted<T, detail::NonAtomicRefCount> { |
| 321 |
public: |
| 322 |
~RefCounted() { |
| 323 |
static_assert(std::is_base_of<RefCounted, T>::value, |
| 324 |
"T must derive from RefCounted<T>"); |
| 325 |
} |
| 326 |
}; |
| 327 |
|
| 328 |
namespace external { |
| 329 |
|
| 330 |
/** |
| 331 |
* AtomicRefCounted<T> is like RefCounted<T>, with an atomically updated |
| 332 |
* reference counter. |
| 333 |
* |
| 334 |
* NOTE: Please do not use this class, use NS_INLINE_DECL_THREADSAFE_REFCOUNTING |
| 335 |
* instead. |
| 336 |
*/ |
| 337 |
template <typename T> |
| 338 |
class AtomicRefCounted |
| 339 |
: public mozilla::detail::RefCounted<T, mozilla::detail::AtomicRefCount> { |
| 340 |
public: |
| 341 |
~AtomicRefCounted() { |
| 342 |
static_assert(std::is_base_of<AtomicRefCounted, T>::value, |
| 343 |
"T must derive from AtomicRefCounted<T>"); |
| 344 |
} |
| 345 |
}; |
| 346 |
|
| 347 |
} // namespace external |
| 348 |
|
| 349 |
} // namespace mozilla |
| 350 |
|
| 351 |
#endif // mozilla_RefCounted_h |