RefCounted.h 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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. /* CRTP refcounting templates. Do not use unless you are an Expert. */
  7. #ifndef mozilla_RefCounted_h
  8. #define mozilla_RefCounted_h
  9. #include "mozilla/AlreadyAddRefed.h"
  10. #include "mozilla/Assertions.h"
  11. #include "mozilla/Atomics.h"
  12. #include "mozilla/Attributes.h"
  13. #include "mozilla/Move.h"
  14. #include "mozilla/RefCountType.h"
  15. #include "mozilla/TypeTraits.h"
  16. #if defined(MOZILLA_INTERNAL_API)
  17. #include "nsXPCOM.h"
  18. #endif
  19. #if defined(MOZILLA_INTERNAL_API) && \
  20. (defined(DEBUG) || defined(FORCE_BUILD_REFCNT_LOGGING))
  21. #define MOZ_REFCOUNTED_LEAK_CHECKING
  22. #endif
  23. namespace mozilla {
  24. /**
  25. * RefCounted<T> is a sort of a "mixin" for a class T. RefCounted
  26. * manages, well, refcounting for T, and because RefCounted is
  27. * parameterized on T, RefCounted<T> can call T's destructor directly.
  28. * This means T doesn't need to have a virtual dtor and so doesn't
  29. * need a vtable.
  30. *
  31. * RefCounted<T> is created with refcount == 0. Newly-allocated
  32. * RefCounted<T> must immediately be assigned to a RefPtr to make the
  33. * refcount > 0. It's an error to allocate and free a bare
  34. * RefCounted<T>, i.e. outside of the RefPtr machinery. Attempts to
  35. * do so will abort DEBUG builds.
  36. *
  37. * Live RefCounted<T> have refcount > 0. The lifetime (refcounts) of
  38. * live RefCounted<T> are controlled by RefPtr<T> and
  39. * RefPtr<super/subclass of T>. Upon a transition from refcounted==1
  40. * to 0, the RefCounted<T> "dies" and is destroyed. The "destroyed"
  41. * state is represented in DEBUG builds by refcount==0xffffdead. This
  42. * state distinguishes use-before-ref (refcount==0) from
  43. * use-after-destroy (refcount==0xffffdead).
  44. *
  45. * Note that when deriving from RefCounted or AtomicRefCounted, you
  46. * should add MOZ_DECLARE_REFCOUNTED_TYPENAME(ClassName) to the public
  47. * section of your class, where ClassName is the name of your class.
  48. */
  49. namespace detail {
  50. const MozRefCountType DEAD = 0xffffdead;
  51. // When building code that gets compiled into Gecko, try to use the
  52. // trace-refcount leak logging facilities.
  53. #ifdef MOZ_REFCOUNTED_LEAK_CHECKING
  54. class RefCountLogger
  55. {
  56. public:
  57. static void logAddRef(const void* aPointer, MozRefCountType aRefCount,
  58. const char* aTypeName, uint32_t aInstanceSize)
  59. {
  60. MOZ_ASSERT(aRefCount != DEAD);
  61. NS_LogAddRef(const_cast<void*>(aPointer), aRefCount, aTypeName,
  62. aInstanceSize);
  63. }
  64. static void logRelease(const void* aPointer, MozRefCountType aRefCount,
  65. const char* aTypeName)
  66. {
  67. MOZ_ASSERT(aRefCount != DEAD);
  68. NS_LogRelease(const_cast<void*>(aPointer), aRefCount, aTypeName);
  69. }
  70. };
  71. #endif
  72. // This is used WeakPtr.h as well as this file.
  73. enum RefCountAtomicity
  74. {
  75. AtomicRefCount,
  76. NonAtomicRefCount
  77. };
  78. template<typename T, RefCountAtomicity Atomicity>
  79. class RefCounted
  80. {
  81. protected:
  82. RefCounted() : mRefCnt(0) {}
  83. ~RefCounted() { MOZ_ASSERT(mRefCnt == detail::DEAD); }
  84. public:
  85. // Compatibility with nsRefPtr.
  86. void AddRef() const
  87. {
  88. // Note: this method must be thread safe for AtomicRefCounted.
  89. MOZ_ASSERT(int32_t(mRefCnt) >= 0);
  90. #ifndef MOZ_REFCOUNTED_LEAK_CHECKING
  91. ++mRefCnt;
  92. #else
  93. const char* type = static_cast<const T*>(this)->typeName();
  94. uint32_t size = static_cast<const T*>(this)->typeSize();
  95. const void* ptr = static_cast<const T*>(this);
  96. MozRefCountType cnt = ++mRefCnt;
  97. detail::RefCountLogger::logAddRef(ptr, cnt, type, size);
  98. #endif
  99. }
  100. void Release() const
  101. {
  102. // Note: this method must be thread safe for AtomicRefCounted.
  103. MOZ_ASSERT(int32_t(mRefCnt) > 0);
  104. #ifndef MOZ_REFCOUNTED_LEAK_CHECKING
  105. MozRefCountType cnt = --mRefCnt;
  106. #else
  107. const char* type = static_cast<const T*>(this)->typeName();
  108. const void* ptr = static_cast<const T*>(this);
  109. MozRefCountType cnt = --mRefCnt;
  110. // Note: it's not safe to touch |this| after decrementing the refcount,
  111. // except for below.
  112. detail::RefCountLogger::logRelease(ptr, cnt, type);
  113. #endif
  114. if (0 == cnt) {
  115. // Because we have atomically decremented the refcount above, only
  116. // one thread can get a 0 count here, so as long as we can assume that
  117. // everything else in the system is accessing this object through
  118. // RefPtrs, it's safe to access |this| here.
  119. #ifdef DEBUG
  120. mRefCnt = detail::DEAD;
  121. #endif
  122. delete static_cast<const T*>(this);
  123. }
  124. }
  125. // Compatibility with wtf::RefPtr.
  126. void ref() { AddRef(); }
  127. void deref() { Release(); }
  128. MozRefCountType refCount() const { return mRefCnt; }
  129. bool hasOneRef() const
  130. {
  131. MOZ_ASSERT(mRefCnt > 0);
  132. return mRefCnt == 1;
  133. }
  134. private:
  135. mutable typename Conditional<Atomicity == AtomicRefCount,
  136. Atomic<MozRefCountType>,
  137. MozRefCountType>::Type mRefCnt;
  138. };
  139. #ifdef MOZ_REFCOUNTED_LEAK_CHECKING
  140. // Passing override for the optional argument marks the typeName and
  141. // typeSize functions defined by this macro as overrides.
  142. #define MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(T, ...) \
  143. virtual const char* typeName() const __VA_ARGS__ { return #T; } \
  144. virtual size_t typeSize() const __VA_ARGS__ { return sizeof(*this); }
  145. #else
  146. #define MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(T, ...)
  147. #endif
  148. // Note that this macro is expanded unconditionally because it declares only
  149. // two small inline functions which will hopefully get eliminated by the linker
  150. // in non-leak-checking builds.
  151. #define MOZ_DECLARE_REFCOUNTED_TYPENAME(T) \
  152. const char* typeName() const { return #T; } \
  153. size_t typeSize() const { return sizeof(*this); }
  154. } // namespace detail
  155. template<typename T>
  156. class RefCounted : public detail::RefCounted<T, detail::NonAtomicRefCount>
  157. {
  158. public:
  159. ~RefCounted()
  160. {
  161. static_assert(IsBaseOf<RefCounted, T>::value,
  162. "T must derive from RefCounted<T>");
  163. }
  164. };
  165. namespace external {
  166. /**
  167. * AtomicRefCounted<T> is like RefCounted<T>, with an atomically updated
  168. * reference counter.
  169. *
  170. * NOTE: Please do not use this class, use NS_INLINE_DECL_THREADSAFE_REFCOUNTING
  171. * instead.
  172. */
  173. template<typename T>
  174. class AtomicRefCounted :
  175. public mozilla::detail::RefCounted<T, mozilla::detail::AtomicRefCount>
  176. {
  177. public:
  178. ~AtomicRefCounted()
  179. {
  180. static_assert(IsBaseOf<AtomicRefCounted, T>::value,
  181. "T must derive from AtomicRefCounted<T>");
  182. }
  183. };
  184. } // namespace external
  185. } // namespace mozilla
  186. #endif // mozilla_RefCounted_h