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