1
2/*
3 * Copyright 2006 The Android Open Source Project
4 *
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
7 */
8
9
10#ifndef SkRefCnt_DEFINED
11#define SkRefCnt_DEFINED
12
13#include "SkDynamicAnnotations.h"
14#include "SkThread.h"
15#include "SkInstCnt.h"
16#include "SkTemplates.h"
17
18/** \class SkRefCntBase
19
20    SkRefCntBase is the base class for objects that may be shared by multiple
21    objects. When an existing owner wants to share a reference, it calls ref().
22    When an owner wants to release its reference, it calls unref(). When the
23    shared object's reference count goes to zero as the result of an unref()
24    call, its (virtual) destructor is called. It is an error for the
25    destructor to be called explicitly (or via the object going out of scope on
26    the stack or calling delete) if getRefCnt() > 1.
27*/
28class SK_API SkRefCntBase : SkNoncopyable {
29public:
30    SK_DECLARE_INST_COUNT_ROOT(SkRefCntBase)
31
32    /** Default construct, initializing the reference count to 1.
33    */
34    SkRefCntBase() : fRefCnt(1) {}
35
36    /** Destruct, asserting that the reference count is 1.
37    */
38    virtual ~SkRefCntBase() {
39#ifdef SK_DEBUG
40        SkASSERTF(fRefCnt == 1, "fRefCnt was %d", fRefCnt);
41        fRefCnt = 0;    // illegal value, to catch us if we reuse after delete
42#endif
43    }
44
45    /** Return the reference count. Use only for debugging. */
46    int32_t getRefCnt() const { return fRefCnt; }
47
48    /** May return true if the caller is the only owner.
49     *  Ensures that all previous owner's actions are complete.
50     */
51    bool unique() const {
52        // We believe we're reading fRefCnt in a safe way here, so we stifle the TSAN warning about
53        // an unproctected read.  Generally, don't read fRefCnt, and don't stifle this warning.
54        bool const unique = (1 == SK_ANNOTATE_UNPROTECTED_READ(fRefCnt));
55        if (unique) {
56            // Acquire barrier (L/SL), if not provided by load of fRefCnt.
57            // Prevents user's 'unique' code from happening before decrements.
58            //TODO: issue the barrier.
59        }
60        return unique;
61    }
62
63    /** Increment the reference count. Must be balanced by a call to unref().
64    */
65    void ref() const {
66        SkASSERT(fRefCnt > 0);
67        sk_atomic_inc(&fRefCnt);  // No barrier required.
68    }
69
70    /** Decrement the reference count. If the reference count is 1 before the
71        decrement, then delete the object. Note that if this is the case, then
72        the object needs to have been allocated via new, and not on the stack.
73    */
74    void unref() const {
75        SkASSERT(fRefCnt > 0);
76        // Release barrier (SL/S), if not provided below.
77        if (sk_atomic_dec(&fRefCnt) == 1) {
78            // Acquire barrier (L/SL), if not provided above.
79            // Prevents code in dispose from happening before the decrement.
80            sk_membar_acquire__after_atomic_dec();
81            internal_dispose();
82        }
83    }
84
85#ifdef SK_DEBUG
86    void validate() const {
87        SkASSERT(fRefCnt > 0);
88    }
89#endif
90
91protected:
92    /**
93     *  Allow subclasses to call this if they've overridden internal_dispose
94     *  so they can reset fRefCnt before the destructor is called. Should only
95     *  be called right before calling through to inherited internal_dispose()
96     *  or before calling the destructor.
97     */
98    void internal_dispose_restore_refcnt_to_1() const {
99#ifdef SK_DEBUG
100        SkASSERT(0 == fRefCnt);
101        fRefCnt = 1;
102#endif
103    }
104
105private:
106    /**
107     *  Called when the ref count goes to 0.
108     */
109    virtual void internal_dispose() const {
110        this->internal_dispose_restore_refcnt_to_1();
111        SkDELETE(this);
112    }
113
114    // The following friends are those which override internal_dispose()
115    // and conditionally call SkRefCnt::internal_dispose().
116    friend class SkWeakRefCnt;
117
118    mutable int32_t fRefCnt;
119
120    typedef SkNoncopyable INHERITED;
121};
122
123#ifdef SK_REF_CNT_MIXIN_INCLUDE
124// It is the responsibility of the following include to define the type SkRefCnt.
125// This SkRefCnt should normally derive from SkRefCntBase.
126#include SK_REF_CNT_MIXIN_INCLUDE
127#else
128class SK_API SkRefCnt : public SkRefCntBase { };
129#endif
130
131///////////////////////////////////////////////////////////////////////////////
132
133/** Helper macro to safely assign one SkRefCnt[TS]* to another, checking for
134    null in on each side of the assignment, and ensuring that ref() is called
135    before unref(), in case the two pointers point to the same object.
136 */
137#define SkRefCnt_SafeAssign(dst, src)   \
138    do {                                \
139        if (src) src->ref();            \
140        if (dst) dst->unref();          \
141        dst = src;                      \
142    } while (0)
143
144
145/** Call obj->ref() and return obj. The obj must not be NULL.
146 */
147template <typename T> static inline T* SkRef(T* obj) {
148    SkASSERT(obj);
149    obj->ref();
150    return obj;
151}
152
153/** Check if the argument is non-null, and if so, call obj->ref() and return obj.
154 */
155template <typename T> static inline T* SkSafeRef(T* obj) {
156    if (obj) {
157        obj->ref();
158    }
159    return obj;
160}
161
162/** Check if the argument is non-null, and if so, call obj->unref()
163 */
164template <typename T> static inline void SkSafeUnref(T* obj) {
165    if (obj) {
166        obj->unref();
167    }
168}
169
170template<typename T> static inline void SkSafeSetNull(T*& obj) {
171    if (obj) {
172        obj->unref();
173        obj = NULL;
174    }
175}
176
177///////////////////////////////////////////////////////////////////////////////
178
179/**
180 *  Utility class that simply unref's its argument in the destructor.
181 */
182template <typename T> class SkAutoTUnref : SkNoncopyable {
183public:
184    explicit SkAutoTUnref(T* obj = NULL) : fObj(obj) {}
185    ~SkAutoTUnref() { SkSafeUnref(fObj); }
186
187    T* get() const { return fObj; }
188
189    T* reset(T* obj) {
190        SkSafeUnref(fObj);
191        fObj = obj;
192        return obj;
193    }
194
195    void swap(SkAutoTUnref* other) {
196        T* tmp = fObj;
197        fObj = other->fObj;
198        other->fObj = tmp;
199    }
200
201    /**
202     *  Return the hosted object (which may be null), transferring ownership.
203     *  The reference count is not modified, and the internal ptr is set to NULL
204     *  so unref() will not be called in our destructor. A subsequent call to
205     *  detach() will do nothing and return null.
206     */
207    T* detach() {
208        T* obj = fObj;
209        fObj = NULL;
210        return obj;
211    }
212
213    /**
214     *  BlockRef<B> is a type which inherits from B, cannot be created,
215     *  cannot be deleted, and makes ref and unref private.
216     */
217    template<typename B> class BlockRef : public B {
218    private:
219        BlockRef();
220        ~BlockRef();
221        void ref() const;
222        void unref() const;
223    };
224
225    /** If T is const, the type returned from operator-> will also be const. */
226    typedef typename SkTConstType<BlockRef<T>, SkTIsConst<T>::value>::type BlockRefType;
227
228    /**
229     *  SkAutoTUnref assumes ownership of the ref. As a result, it is an error
230     *  for the user to ref or unref through SkAutoTUnref. Therefore
231     *  SkAutoTUnref::operator-> returns BlockRef<T>*. This prevents use of
232     *  skAutoTUnrefInstance->ref() and skAutoTUnrefInstance->unref().
233     */
234    BlockRefType *operator->() const {
235        return static_cast<BlockRefType*>(fObj);
236    }
237    operator T*() const { return fObj; }
238
239private:
240    T*  fObj;
241};
242// Can't use the #define trick below to guard a bare SkAutoTUnref(...) because it's templated. :(
243
244class SkAutoUnref : public SkAutoTUnref<SkRefCnt> {
245public:
246    SkAutoUnref(SkRefCnt* obj) : SkAutoTUnref<SkRefCnt>(obj) {}
247};
248#define SkAutoUnref(...) SK_REQUIRE_LOCAL_VAR(SkAutoUnref)
249
250#endif
251