#ifndef RefCounted_h
#define RefCounted_h
#include "wtf/FastAllocBase.h"
#include "wtf/InstanceCounter.h"
#include "wtf/Noncopyable.h"
#include "wtf/WTFExport.h"
#ifdef NDEBUG
#define CHECK_REF_COUNTED_LIFECYCLE 0
#else
#define CHECK_REF_COUNTED_LIFECYCLE 1
#include "wtf/Assertions.h"
#include "wtf/ThreadRestrictionVerifier.h"
#endif
namespace WTF {
class WTF_EXPORT RefCountedBase {
public:
void ref()
{
#if CHECK_REF_COUNTED_LIFECYCLE
if (m_refCount == 1)
m_verifier.setShared(true);
ASSERT(m_verifier.isSafeToUse());
ASSERT(!m_adoptionIsRequired);
#endif
ASSERT_WITH_SECURITY_IMPLICATION(!m_deletionHasBegun);
++m_refCount;
}
bool hasOneRef() const
{
ASSERT_WITH_SECURITY_IMPLICATION(!m_deletionHasBegun);
#if CHECK_REF_COUNTED_LIFECYCLE
ASSERT(m_verifier.isSafeToUse());
#endif
return m_refCount == 1;
}
int refCount() const
{
#if CHECK_REF_COUNTED_LIFECYCLE
ASSERT(m_verifier.isSafeToUse());
#endif
return m_refCount;
}
void relaxAdoptionRequirement()
{
ASSERT_WITH_SECURITY_IMPLICATION(!m_deletionHasBegun);
#if CHECK_REF_COUNTED_LIFECYCLE
ASSERT(m_adoptionIsRequired);
m_adoptionIsRequired = false;
#endif
}
protected:
RefCountedBase()
: m_refCount(1)
#if SECURITY_ASSERT_ENABLED
, m_deletionHasBegun(false)
#endif
#if CHECK_REF_COUNTED_LIFECYCLE
, m_adoptionIsRequired(true)
#endif
{
}
~RefCountedBase()
{
ASSERT_WITH_SECURITY_IMPLICATION(m_deletionHasBegun);
#if CHECK_REF_COUNTED_LIFECYCLE
ASSERT(!m_adoptionIsRequired);
#endif
}
bool derefBase()
{
ASSERT_WITH_SECURITY_IMPLICATION(!m_deletionHasBegun);
#if CHECK_REF_COUNTED_LIFECYCLE
ASSERT(m_verifier.isSafeToUse());
ASSERT(!m_adoptionIsRequired);
#endif
ASSERT(m_refCount > 0);
--m_refCount;
if (!m_refCount) {
#if SECURITY_ASSERT_ENABLED
m_deletionHasBegun = true;
#endif
return true;
}
#if CHECK_REF_COUNTED_LIFECYCLE
if (m_refCount == 1)
m_verifier.setShared(false);
#endif
return false;
}
#if CHECK_REF_COUNTED_LIFECYCLE
bool deletionHasBegun() const
{
return m_deletionHasBegun;
}
#endif
private:
#if CHECK_REF_COUNTED_LIFECYCLE || SECURITY_ASSERT_ENABLED
friend void adopted(RefCountedBase*);
#endif
int m_refCount;
#if SECURITY_ASSERT_ENABLED
bool m_deletionHasBegun;
#endif
#if CHECK_REF_COUNTED_LIFECYCLE
bool m_adoptionIsRequired;
ThreadRestrictionVerifier m_verifier;
#endif
};
#if CHECK_REF_COUNTED_LIFECYCLE || SECURITY_ASSERT_ENABLED
inline void adopted(RefCountedBase* object)
{
if (!object)
return;
ASSERT_WITH_SECURITY_IMPLICATION(!object->m_deletionHasBegun);
#if CHECK_REF_COUNTED_LIFECYCLE
object->m_adoptionIsRequired = false;
#endif
}
#endif
template<typename T> class RefCounted : public RefCountedBase {
WTF_MAKE_NONCOPYABLE(RefCounted);
WTF_MAKE_FAST_ALLOCATED;
public:
void deref()
{
if (derefBase())
delete static_cast<T*>(this);
}
protected:
#ifdef ENABLE_INSTANCE_COUNTER
RefCounted()
{
incrementInstanceCount<T>(static_cast<T*>(this));
}
~RefCounted()
{
decrementInstanceCount<T>(static_cast<T*>(this));
}
#else
RefCounted()
{
}
#endif
};
}
using WTF::RefCounted;
#endif