Home | History | Annotate | Download | only in core
      1 /*
      2  * Copyright 2006 The Android Open Source Project
      3  *
      4  * Use of this source code is governed by a BSD-style license that can be
      5  * found in the LICENSE file.
      6  */
      7 
      8 #ifndef SkRefCnt_DEFINED
      9 #define SkRefCnt_DEFINED
     10 
     11 #include "../private/SkAtomics.h"
     12 #include "../private/SkUniquePtr.h"
     13 #include "SkTypes.h"
     14 
     15 /** \class SkRefCntBase
     16 
     17     SkRefCntBase is the base class for objects that may be shared by multiple
     18     objects. When an existing owner wants to share a reference, it calls ref().
     19     When an owner wants to release its reference, it calls unref(). When the
     20     shared object's reference count goes to zero as the result of an unref()
     21     call, its (virtual) destructor is called. It is an error for the
     22     destructor to be called explicitly (or via the object going out of scope on
     23     the stack or calling delete) if getRefCnt() > 1.
     24 */
     25 class SK_API SkRefCntBase : SkNoncopyable {
     26 public:
     27     /** Default construct, initializing the reference count to 1.
     28     */
     29     SkRefCntBase() : fRefCnt(1) {}
     30 
     31     /** Destruct, asserting that the reference count is 1.
     32     */
     33     virtual ~SkRefCntBase() {
     34 #ifdef SK_DEBUG
     35         SkASSERTF(fRefCnt == 1, "fRefCnt was %d", fRefCnt);
     36         fRefCnt = 0;    // illegal value, to catch us if we reuse after delete
     37 #endif
     38     }
     39 
     40 #ifdef SK_DEBUG
     41     /** Return the reference count. Use only for debugging. */
     42     int32_t getRefCnt() const { return fRefCnt; }
     43 #endif
     44 
     45     /** May return true if the caller is the only owner.
     46      *  Ensures that all previous owner's actions are complete.
     47      */
     48     bool unique() const {
     49         if (1 == sk_atomic_load(&fRefCnt, sk_memory_order_acquire)) {
     50             // The acquire barrier is only really needed if we return true.  It
     51             // prevents code conditioned on the result of unique() from running
     52             // until previous owners are all totally done calling unref().
     53             return true;
     54         }
     55         return false;
     56     }
     57 
     58     /** Increment the reference count. Must be balanced by a call to unref().
     59     */
     60     void ref() const {
     61 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
     62         // Android employs some special subclasses that enable the fRefCnt to
     63         // go to zero, but not below, prior to reusing the object.  This breaks
     64         // the use of unique() on such objects and as such should be removed
     65         // once the Android code is fixed.
     66         SkASSERT(fRefCnt >= 0);
     67 #else
     68         SkASSERT(fRefCnt > 0);
     69 #endif
     70         (void)sk_atomic_fetch_add(&fRefCnt, +1, sk_memory_order_relaxed);  // No barrier required.
     71     }
     72 
     73     /** Decrement the reference count. If the reference count is 1 before the
     74         decrement, then delete the object. Note that if this is the case, then
     75         the object needs to have been allocated via new, and not on the stack.
     76     */
     77     void unref() const {
     78         SkASSERT(fRefCnt > 0);
     79         // A release here acts in place of all releases we "should" have been doing in ref().
     80         if (1 == sk_atomic_fetch_add(&fRefCnt, -1, sk_memory_order_acq_rel)) {
     81             // Like unique(), the acquire is only needed on success, to make sure
     82             // code in internal_dispose() doesn't happen before the decrement.
     83             this->internal_dispose();
     84         }
     85     }
     86 
     87 #ifdef SK_DEBUG
     88     void validate() const {
     89         SkASSERT(fRefCnt > 0);
     90     }
     91 #endif
     92 
     93 protected:
     94     /**
     95      *  Allow subclasses to call this if they've overridden internal_dispose
     96      *  so they can reset fRefCnt before the destructor is called. Should only
     97      *  be called right before calling through to inherited internal_dispose()
     98      *  or before calling the destructor.
     99      */
    100     void internal_dispose_restore_refcnt_to_1() const {
    101 #ifdef SK_DEBUG
    102         SkASSERT(0 == fRefCnt);
    103         fRefCnt = 1;
    104 #endif
    105     }
    106 
    107 private:
    108     /**
    109      *  Called when the ref count goes to 0.
    110      */
    111     virtual void internal_dispose() const {
    112         this->internal_dispose_restore_refcnt_to_1();
    113         delete this;
    114     }
    115 
    116     // The following friends are those which override internal_dispose()
    117     // and conditionally call SkRefCnt::internal_dispose().
    118     friend class SkWeakRefCnt;
    119 
    120     mutable int32_t fRefCnt;
    121 
    122     typedef SkNoncopyable INHERITED;
    123 };
    124 
    125 #ifdef SK_REF_CNT_MIXIN_INCLUDE
    126 // It is the responsibility of the following include to define the type SkRefCnt.
    127 // This SkRefCnt should normally derive from SkRefCntBase.
    128 #include SK_REF_CNT_MIXIN_INCLUDE
    129 #else
    130 class SK_API SkRefCnt : public SkRefCntBase { };
    131 #endif
    132 
    133 ///////////////////////////////////////////////////////////////////////////////
    134 
    135 /** Helper macro to safely assign one SkRefCnt[TS]* to another, checking for
    136     null in on each side of the assignment, and ensuring that ref() is called
    137     before unref(), in case the two pointers point to the same object.
    138  */
    139 
    140 #if defined(SK_BUILD_FOR_ANDROID_FRAMEWORK) || defined(SK_DEBUG)
    141 // This version heuristically detects data races, since those otherwise result
    142 // in redundant reference count decrements, which are exceedingly
    143 // difficult to debug.
    144 
    145 #define SkRefCnt_SafeAssign(dst, src)   \
    146     do {                                \
    147         typedef typename std::remove_reference<decltype(dst)>::type \
    148                 SkRefCntPtrT;  \
    149         SkRefCntPtrT old_dst = *const_cast<SkRefCntPtrT volatile *>(&dst); \
    150         if (src) src->ref();            \
    151         if (old_dst) old_dst->unref();          \
    152         if (old_dst != *const_cast<SkRefCntPtrT volatile *>(&dst)) { \
    153             SkDebugf("Detected racing Skia calls at %s:%d\n", \
    154                     __FILE__, __LINE__); \
    155         } \
    156         dst = src;                      \
    157     } while (0)
    158 
    159 #else /* !(SK_BUILD_FOR_ANDROID_FRAMEWORK || SK_DEBUG) */
    160 
    161 #define SkRefCnt_SafeAssign(dst, src)   \
    162     do {                                \
    163         if (src) src->ref();            \
    164         if (dst) dst->unref();          \
    165         dst = src;                      \
    166     } while (0)
    167 
    168 #endif
    169 
    170 
    171 /** Call obj->ref() and return obj. The obj must not be nullptr.
    172  */
    173 template <typename T> static inline T* SkRef(T* obj) {
    174     SkASSERT(obj);
    175     obj->ref();
    176     return obj;
    177 }
    178 
    179 /** Check if the argument is non-null, and if so, call obj->ref() and return obj.
    180  */
    181 template <typename T> static inline T* SkSafeRef(T* obj) {
    182     if (obj) {
    183         obj->ref();
    184     }
    185     return obj;
    186 }
    187 
    188 /** Check if the argument is non-null, and if so, call obj->unref()
    189  */
    190 template <typename T> static inline void SkSafeUnref(T* obj) {
    191     if (obj) {
    192         obj->unref();
    193     }
    194 }
    195 
    196 template<typename T> static inline void SkSafeSetNull(T*& obj) {
    197     if (obj) {
    198         obj->unref();
    199         obj = nullptr;
    200     }
    201 }
    202 
    203 ///////////////////////////////////////////////////////////////////////////////
    204 
    205 template <typename T> struct SkTUnref {
    206     void operator()(T* t) { t->unref(); }
    207 };
    208 
    209 /**
    210  *  Utility class that simply unref's its argument in the destructor.
    211  */
    212 template <typename T> class SkAutoTUnref : public skstd::unique_ptr<T, SkTUnref<T>> {
    213 public:
    214     explicit SkAutoTUnref(T* obj = nullptr) : skstd::unique_ptr<T, SkTUnref<T>>(obj) {}
    215 
    216     T* detach() { return this->release(); }
    217     operator T*() const { return this->get(); }
    218 };
    219 // Can't use the #define trick below to guard a bare SkAutoTUnref(...) because it's templated. :(
    220 
    221 class SkAutoUnref : public SkAutoTUnref<SkRefCnt> {
    222 public:
    223     SkAutoUnref(SkRefCnt* obj) : SkAutoTUnref<SkRefCnt>(obj) {}
    224 };
    225 #define SkAutoUnref(...) SK_REQUIRE_LOCAL_VAR(SkAutoUnref)
    226 
    227 // This is a variant of SkRefCnt that's Not Virtual, so weighs 4 bytes instead of 8 or 16.
    228 // There's only benefit to using this if the deriving class does not otherwise need a vtable.
    229 template <typename Derived>
    230 class SkNVRefCnt : SkNoncopyable {
    231 public:
    232     SkNVRefCnt() : fRefCnt(1) {}
    233     ~SkNVRefCnt() { SkASSERTF(1 == fRefCnt, "NVRefCnt was %d", fRefCnt); }
    234 
    235     // Implementation is pretty much the same as SkRefCntBase. All required barriers are the same:
    236     //   - unique() needs acquire when it returns true, and no barrier if it returns false;
    237     //   - ref() doesn't need any barrier;
    238     //   - unref() needs a release barrier, and an acquire if it's going to call delete.
    239 
    240     bool unique() const { return 1 == sk_atomic_load(&fRefCnt, sk_memory_order_acquire); }
    241     void    ref() const { (void)sk_atomic_fetch_add(&fRefCnt, +1, sk_memory_order_relaxed); }
    242     void  unref() const {
    243         if (1 == sk_atomic_fetch_add(&fRefCnt, -1, sk_memory_order_acq_rel)) {
    244             SkDEBUGCODE(fRefCnt = 1;)  // restore the 1 for our destructor's assert
    245             delete (const Derived*)this;
    246         }
    247     }
    248     void  deref() const { this->unref(); }
    249 
    250 private:
    251     mutable int32_t fRefCnt;
    252 };
    253 
    254 #endif
    255