Bumping manifests a=b2g-bump
[gecko.git] / mfbt / RefPtr.h
blobb185e786539070edda142de2d58022ce5fd5f2e8
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 /* Helpers for defining and using refcounted objects. */
9 #ifndef mozilla_RefPtr_h
10 #define mozilla_RefPtr_h
12 #include "mozilla/Assertions.h"
13 #include "mozilla/Atomics.h"
14 #include "mozilla/Attributes.h"
15 #include "mozilla/RefCountType.h"
16 #include "mozilla/TypeTraits.h"
17 #if defined(MOZILLA_INTERNAL_API)
18 #include "nsXPCOM.h"
19 #endif
21 #if defined(MOZILLA_INTERNAL_API) && \
22 (defined(DEBUG) || defined(FORCE_BUILD_REFCNT_LOGGING))
23 #define MOZ_REFCOUNTED_LEAK_CHECKING
24 #endif
26 namespace mozilla {
28 template<typename T> class RefCounted;
29 template<typename T> class RefPtr;
30 template<typename T> class TemporaryRef;
31 template<typename T> class OutParamRef;
32 template<typename T> OutParamRef<T> byRef(RefPtr<T>&);
34 /**
35 * RefCounted<T> is a sort of a "mixin" for a class T. RefCounted
36 * manages, well, refcounting for T, and because RefCounted is
37 * parameterized on T, RefCounted<T> can call T's destructor directly.
38 * This means T doesn't need to have a virtual dtor and so doesn't
39 * need a vtable.
41 * RefCounted<T> is created with refcount == 0. Newly-allocated
42 * RefCounted<T> must immediately be assigned to a RefPtr to make the
43 * refcount > 0. It's an error to allocate and free a bare
44 * RefCounted<T>, i.e. outside of the RefPtr machinery. Attempts to
45 * do so will abort DEBUG builds.
47 * Live RefCounted<T> have refcount > 0. The lifetime (refcounts) of
48 * live RefCounted<T> are controlled by RefPtr<T> and
49 * RefPtr<super/subclass of T>. Upon a transition from refcounted==1
50 * to 0, the RefCounted<T> "dies" and is destroyed. The "destroyed"
51 * state is represented in DEBUG builds by refcount==0xffffdead. This
52 * state distinguishes use-before-ref (refcount==0) from
53 * use-after-destroy (refcount==0xffffdead).
55 * Note that when deriving from RefCounted or AtomicRefCounted, you
56 * should add MOZ_DECLARE_REFCOUNTED_TYPENAME(ClassName) to the public
57 * section of your class, where ClassName is the name of your class.
59 namespace detail {
60 #ifdef DEBUG
61 const MozRefCountType DEAD = 0xffffdead;
62 #endif
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 public:
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,
75 aInstanceSize);
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);
85 #endif
87 // This is used WeakPtr.h as well as this file.
88 enum RefCountAtomicity
90 AtomicRefCount,
91 NonAtomicRefCount
94 template<typename T, RefCountAtomicity Atomicity>
95 class RefCounted
97 friend class RefPtr<T>;
99 protected:
100 RefCounted() : mRefCnt(0) {}
101 ~RefCounted() { MOZ_ASSERT(mRefCnt == detail::DEAD); }
103 public:
104 // Compatibility with nsRefPtr.
105 void AddRef() const
107 // Note: this method must be thread safe for AtomicRefCounted.
108 MOZ_ASSERT(int32_t(mRefCnt) >= 0);
109 #ifndef MOZ_REFCOUNTED_LEAK_CHECKING
110 ++mRefCnt;
111 #else
112 const char* type = static_cast<const T*>(this)->typeName();
113 uint32_t size = static_cast<const T*>(this)->typeSize();
114 const void* ptr = static_cast<const T*>(this);
115 MozRefCountType cnt = ++mRefCnt;
116 detail::RefCountLogger::logAddRef(ptr, cnt, type, size);
117 #endif
120 void Release() const
122 // Note: this method must be thread safe for AtomicRefCounted.
123 MOZ_ASSERT(int32_t(mRefCnt) > 0);
124 #ifndef MOZ_REFCOUNTED_LEAK_CHECKING
125 MozRefCountType cnt = --mRefCnt;
126 #else
127 const char* type = static_cast<const T*>(this)->typeName();
128 const void* ptr = static_cast<const T*>(this);
129 MozRefCountType cnt = --mRefCnt;
130 // Note: it's not safe to touch |this| after decrementing the refcount,
131 // except for below.
132 detail::RefCountLogger::logRelease(ptr, cnt, type);
133 #endif
134 if (0 == cnt) {
135 // Because we have atomically decremented the refcount above, only
136 // one thread can get a 0 count here, so as long as we can assume that
137 // everything else in the system is accessing this object through
138 // RefPtrs, it's safe to access |this| here.
139 #ifdef DEBUG
140 mRefCnt = detail::DEAD;
141 #endif
142 delete static_cast<const T*>(this);
146 // Compatibility with wtf::RefPtr.
147 void ref() { AddRef(); }
148 void deref() { Release(); }
149 MozRefCountType refCount() const { return mRefCnt; }
150 bool hasOneRef() const
152 MOZ_ASSERT(mRefCnt > 0);
153 return mRefCnt == 1;
156 private:
157 mutable typename Conditional<Atomicity == AtomicRefCount,
158 Atomic<MozRefCountType>,
159 MozRefCountType>::Type mRefCnt;
162 #ifdef MOZ_REFCOUNTED_LEAK_CHECKING
163 // Passing MOZ_OVERRIDE for the optional argument marks the typeName and
164 // typeSize functions defined by this macro as overrides.
165 #define MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(T, ...) \
166 virtual const char* typeName() const __VA_ARGS__ { return #T; } \
167 virtual size_t typeSize() const __VA_ARGS__ { return sizeof(*this); }
168 #else
169 #define MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(T, ...)
170 #endif
172 // Note that this macro is expanded unconditionally because it declares only
173 // two small inline functions which will hopefully get eliminated by the linker
174 // in non-leak-checking builds.
175 #define MOZ_DECLARE_REFCOUNTED_TYPENAME(T) \
176 const char* typeName() const { return #T; } \
177 size_t typeSize() const { return sizeof(*this); }
179 } // namespace detail
181 template<typename T>
182 class RefCounted : public detail::RefCounted<T, detail::NonAtomicRefCount>
184 public:
185 ~RefCounted()
187 static_assert(IsBaseOf<RefCounted, T>::value,
188 "T must derive from RefCounted<T>");
192 namespace external {
195 * AtomicRefCounted<T> is like RefCounted<T>, with an atomically updated
196 * reference counter.
198 * NOTE: Please do not use this class, use NS_INLINE_DECL_THREADSAFE_REFCOUNTING
199 * instead.
201 template<typename T>
202 class AtomicRefCounted :
203 public mozilla::detail::RefCounted<T, mozilla::detail::AtomicRefCount>
205 public:
206 ~AtomicRefCounted()
208 static_assert(IsBaseOf<AtomicRefCounted, T>::value,
209 "T must derive from AtomicRefCounted<T>");
213 } // namespace external
216 * RefPtr points to a refcounted thing that has AddRef and Release
217 * methods to increase/decrease the refcount, respectively. After a
218 * RefPtr<T> is assigned a T*, the T* can be used through the RefPtr
219 * as if it were a T*.
221 * A RefPtr can forget its underlying T*, which results in the T*
222 * being wrapped in a temporary object until the T* is either
223 * re-adopted from or released by the temporary.
225 template<typename T>
226 class RefPtr
228 // To allow them to use unref()
229 friend class TemporaryRef<T>;
230 friend class OutParamRef<T>;
232 struct DontRef {};
234 public:
235 RefPtr() : mPtr(0) {}
236 RefPtr(const RefPtr& aOther) : mPtr(ref(aOther.mPtr)) {}
237 MOZ_IMPLICIT RefPtr(const TemporaryRef<T>& aOther) : mPtr(aOther.take()) {}
238 MOZ_IMPLICIT RefPtr(T* aVal) : mPtr(ref(aVal)) {}
240 template<typename U>
241 RefPtr(const RefPtr<U>& aOther) : mPtr(ref(aOther.get())) {}
243 ~RefPtr() { unref(mPtr); }
245 RefPtr& operator=(const RefPtr& aOther)
247 assign(ref(aOther.mPtr));
248 return *this;
250 RefPtr& operator=(const TemporaryRef<T>& aOther)
252 assign(aOther.take());
253 return *this;
255 RefPtr& operator=(T* aVal)
257 assign(ref(aVal));
258 return *this;
261 template<typename U>
262 RefPtr& operator=(const RefPtr<U>& aOther)
264 assign(ref(aOther.get()));
265 return *this;
268 TemporaryRef<T> forget()
270 T* tmp = mPtr;
271 mPtr = nullptr;
272 return TemporaryRef<T>(tmp, DontRef());
275 T* get() const { return mPtr; }
276 operator T*() const { return mPtr; }
277 T* operator->() const MOZ_NO_ADDREF_RELEASE_ON_RETURN { return mPtr; }
278 T& operator*() const { return *mPtr; }
279 template<typename U>
280 operator TemporaryRef<U>() { return TemporaryRef<U>(mPtr); }
282 private:
283 void assign(T* aVal)
285 unref(mPtr);
286 mPtr = aVal;
289 T* MOZ_OWNING_REF mPtr;
291 static MOZ_ALWAYS_INLINE T* ref(T* aVal)
293 if (aVal) {
294 aVal->AddRef();
296 return aVal;
299 static MOZ_ALWAYS_INLINE void unref(T* aVal)
301 if (aVal) {
302 aVal->Release();
308 * TemporaryRef<T> represents an object that holds a temporary
309 * reference to a T. TemporaryRef objects can't be manually ref'd or
310 * unref'd (being temporaries, not lvalues), so can only relinquish
311 * references to other objects, or unref on destruction.
313 template<typename T>
314 class TemporaryRef
316 // To allow it to construct TemporaryRef from a bare T*
317 friend class RefPtr<T>;
319 typedef typename RefPtr<T>::DontRef DontRef;
321 public:
322 MOZ_IMPLICIT TemporaryRef(T* aVal) : mPtr(RefPtr<T>::ref(aVal)) {}
323 TemporaryRef(const TemporaryRef& aOther) : mPtr(aOther.take()) {}
325 template<typename U>
326 TemporaryRef(const TemporaryRef<U>& aOther) : mPtr(aOther.take()) {}
328 ~TemporaryRef() { RefPtr<T>::unref(mPtr); }
330 MOZ_WARN_UNUSED_RESULT T* take() const
332 T* tmp = mPtr;
333 mPtr = nullptr;
334 return tmp;
337 private:
338 TemporaryRef(T* aVal, const DontRef&) : mPtr(aVal) {}
340 mutable T* MOZ_OWNING_REF mPtr;
342 TemporaryRef() = delete;
343 void operator=(const TemporaryRef&) = delete;
347 * OutParamRef is a wrapper that tracks a refcounted pointer passed as
348 * an outparam argument to a function. OutParamRef implements COM T**
349 * outparam semantics: this requires the callee to AddRef() the T*
350 * returned through the T** outparam on behalf of the caller. This
351 * means the caller (through OutParamRef) must Release() the old
352 * object contained in the tracked RefPtr. It's OK if the callee
353 * returns the same T* passed to it through the T** outparam, as long
354 * as the callee obeys the COM discipline.
356 * Prefer returning TemporaryRef<T> from functions over creating T**
357 * outparams and passing OutParamRef<T> to T**. Prefer RefPtr<T>*
358 * outparams over T** outparams.
360 template<typename T>
361 class OutParamRef
363 friend OutParamRef byRef<T>(RefPtr<T>&);
365 public:
366 ~OutParamRef()
368 RefPtr<T>::unref(mRefPtr.mPtr);
369 mRefPtr.mPtr = mTmp;
372 operator T**() { return &mTmp; }
374 private:
375 explicit OutParamRef(RefPtr<T>& p) : mRefPtr(p), mTmp(p.get()) {}
377 RefPtr<T>& mRefPtr;
378 T* mTmp;
380 OutParamRef() = delete;
381 OutParamRef& operator=(const OutParamRef&) = delete;
385 * byRef cooperates with OutParamRef to implement COM outparam semantics.
387 template<typename T>
388 OutParamRef<T>
389 byRef(RefPtr<T>& aPtr)
391 return OutParamRef<T>(aPtr);
394 } // namespace mozilla
396 #endif /* mozilla_RefPtr_h */