• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2005 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #define LOG_TAG "RefBase"
17 // #define LOG_NDEBUG 0
18 #include <memory>
19 // #include <android-base/macros.h>
20 #include <utils/RefBase.h>
21 #include <utils/CallStack.h>
22 #include <utils/Mutex.h>
23 #ifndef __unused
24 #define __unused __attribute__((__unused__))
25 #endif
26 // Compile with refcounting debugging enabled.
27 #define DEBUG_REFS 0
28 // The following three are ignored unless DEBUG_REFS is set.
29 // whether ref-tracking is enabled by default, if not, trackMe(true, false)
30 // needs to be called explicitly
31 #define DEBUG_REFS_ENABLED_BY_DEFAULT 0
32 // whether callstack are collected (significantly slows things down)
33 #define DEBUG_REFS_CALLSTACK_ENABLED 1
34 // folder where stack traces are saved when DEBUG_REFS is enabled
35 // this folder needs to exist and be writable
36 #define DEBUG_REFS_CALLSTACK_PATH "/data/debug"
37 // log all reference counting operations
38 #define PRINT_REFS 0
39 // Continue after logging a stack trace if ~RefBase discovers that reference
40 // count has never been incremented. Normally we conspicuously crash in that
41 // case.
42 #define DEBUG_REFBASE_DESTRUCTION 1
43 // ---------------------------------------------------------------------------
44 namespace android {
45 // Observations, invariants, etc:
46 // By default, obects are destroyed when the last strong reference disappears
47 // or, if the object never had a strong reference, when the last weak reference
48 // disappears.
49 //
50 // OBJECT_LIFETIME_WEAK changes this behavior to retain the object
51 // unconditionally until the last reference of either kind disappears.  The
52 // client ensures that the extendObjectLifetime call happens before the dec
53 // call that would otherwise have deallocated the object, or before an
54 // attemptIncStrong call that might rely on it.  We do not worry about
55 // concurrent changes to the object lifetime.
56 //
57 // AttemptIncStrong will succeed if the object has a strong reference, or if it
58 // has a weak reference and has never had a strong reference.
59 // AttemptIncWeak really does succeed only if there is already a WEAK
60 // reference, and thus may fail when attemptIncStrong would succeed.
61 //
62 // mStrong is the strong reference count.  mWeak is the weak reference count.
63 // Between calls, and ignoring memory ordering effects, mWeak includes strong
64 // references, and is thus >= mStrong.
65 //
66 // A weakref_impl holds all the information, including both reference counts,
67 // required to perform wp<> operations.  Thus these can continue to be performed
68 // after the RefBase object has been destroyed.
69 //
70 // A weakref_impl is allocated as the value of mRefs in a RefBase object on
71 // construction.
72 // In the OBJECT_LIFETIME_STRONG case, it is normally deallocated in decWeak,
73 // and hence lives as long as the last weak reference. (It can also be
74 // deallocated in the RefBase destructor iff the strong reference count was
75 // never incremented and the weak count is zero, e.g.  if the RefBase object is
76 // explicitly destroyed without decrementing the strong count.  This should be
77 // avoided.) In this case, the RefBase destructor should be invoked from
78 // decStrong.
79 // In the OBJECT_LIFETIME_WEAK case, the weakref_impl is always deallocated in
80 // the RefBase destructor, which is always invoked by decWeak. DecStrong
81 // explicitly avoids the deletion in this case.
82 //
83 // Memory ordering:
84 // The client must ensure that every inc() call, together with all other
85 // accesses to the object, happens before the corresponding dec() call.
86 //
87 // We try to keep memory ordering constraints on atomics as weak as possible,
88 // since memory fences or ordered memory accesses are likely to be a major
89 // performance cost for this code. All accesses to mStrong, mWeak, and mFlags
90 // explicitly relax memory ordering in some way.
91 //
92 // The only operations that are not memory_order_relaxed are reference count
93 // decrements. All reference count decrements are release operations.  In
94 // addition, the final decrement leading the deallocation is followed by an
95 // acquire fence, which we can view informally as also turning it into an
96 // acquire operation.  (See 29.8p4 [atomics.fences] for details. We could
97 // alternatively use acq_rel operations for all decrements. This is probably
98 // slower on most current (2016) hardware, especially on ARMv7, but that may
99 // not be true indefinitely.)
100 //
101 // This convention ensures that the second-to-last decrement synchronizes with
102 // (in the language of 1.10 in the C++ standard) the final decrement of a
103 // reference count. Since reference counts are only updated using atomic
104 // read-modify-write operations, this also extends to any earlier decrements.
105 // (See "release sequence" in 1.10.)
106 //
107 // Since all operations on an object happen before the corresponding reference
108 // count decrement, and all reference count decrements happen before the final
109 // one, we are guaranteed that all other object accesses happen before the
110 // object is destroyed.
111 #define INITIAL_STRONG_VALUE (1<<28)
112 #define MAX_COUNT 0xfffff
113 // Test whether the argument is a clearly invalid strong reference count.
114 // Used only for error checking on the value before an atomic decrement.
115 // Intended to be very cheap.
116 // Note that we cannot just check for excess decrements by comparing to zero
117 // since the object would be deallocated before that.
118 #define BAD_STRONG(c) \
119         ((c) == 0 || ((c) & (~(MAX_COUNT | INITIAL_STRONG_VALUE))) != 0)
120 // Same for weak counts.
121 #define BAD_WEAK(c) ((c) == 0 || ((c) & (~MAX_COUNT)) != 0)
122 // ---------------------------------------------------------------------------
123 class RefBase::weakref_impl : public RefBase::weakref_type
124 {
125 public:
126     std::atomic<int32_t>    mStrong;
127     std::atomic<int32_t>    mWeak;
128     RefBase* const          mBase;
129     std::atomic<int32_t>    mFlags;
130 #if !DEBUG_REFS
weakref_impl(RefBase * base)131     explicit weakref_impl(RefBase* base)
132         : mStrong(INITIAL_STRONG_VALUE)
133         , mWeak(0)
134         , mBase(base)
135         , mFlags(0)
136     {
137     }
addStrongRef(const void *)138     void addStrongRef(const void* /*id*/) { }
removeStrongRef(const void *)139     void removeStrongRef(const void* /*id*/) { }
renameStrongRefId(const void *,const void *)140     void renameStrongRefId(const void* /*old_id*/, const void* /*new_id*/) { }
addWeakRef(const void *)141     void addWeakRef(const void* /*id*/) { }
removeWeakRef(const void *)142     void removeWeakRef(const void* /*id*/) { }
renameWeakRefId(const void *,const void *)143     void renameWeakRefId(const void* /*old_id*/, const void* /*new_id*/) { }
printRefs() const144     void printRefs() const { }
trackMe(bool,bool)145     void trackMe(bool, bool) { }
146 #else
weakref_impl(RefBase * base)147     weakref_impl(RefBase* base)
148         : mStrong(INITIAL_STRONG_VALUE)
149         , mWeak(0)
150         , mBase(base)
151         , mFlags(0)
152         , mStrongRefs(NULL)
153         , mWeakRefs(NULL)
154         , mTrackEnabled(!!DEBUG_REFS_ENABLED_BY_DEFAULT)
155         , mRetain(false)
156     {
157     }
158 
~weakref_impl()159     ~weakref_impl()
160     {
161         bool dumpStack = false;
162         if (!mRetain && mStrongRefs != NULL) {
163             dumpStack = true;
164             ALOGE("Strong references remain:");
165             ref_entry* refs = mStrongRefs;
166             while (refs) {
167                 char inc = refs->ref >= 0 ? '+' : '-';
168                 ALOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
169 #if DEBUG_REFS_CALLSTACK_ENABLED
170                 CallStack::logStack(LOG_TAG, refs->stack.get());
171 #endif
172                 refs = refs->next;
173             }
174         }
175         if (!mRetain && mWeakRefs != NULL) {
176             dumpStack = true;
177             ALOGE("Weak references remain!");
178             ref_entry* refs = mWeakRefs;
179             while (refs) {
180                 char inc = refs->ref >= 0 ? '+' : '-';
181                 ALOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
182 #if DEBUG_REFS_CALLSTACK_ENABLED
183                 CallStack::logStack(LOG_TAG, refs->stack.get());
184 #endif
185                 refs = refs->next;
186             }
187         }
188         if (dumpStack) {
189             ALOGE("above errors at:");
190             CallStack::logStack(LOG_TAG);
191         }
192     }
addStrongRef(const void * id)193     void addStrongRef(const void* id) {
194         //ALOGD_IF(mTrackEnabled,
195         //        "addStrongRef: RefBase=%p, id=%p", mBase, id);
196         addRef(&mStrongRefs, id, mStrong.load(std::memory_order_relaxed));
197     }
removeStrongRef(const void * id)198     void removeStrongRef(const void* id) {
199         //ALOGD_IF(mTrackEnabled,
200         //        "removeStrongRef: RefBase=%p, id=%p", mBase, id);
201         if (!mRetain) {
202             removeRef(&mStrongRefs, id);
203         } else {
204             addRef(&mStrongRefs, id, -mStrong.load(std::memory_order_relaxed));
205         }
206     }
renameStrongRefId(const void * old_id,const void * new_id)207     void renameStrongRefId(const void* old_id, const void* new_id) {
208         //ALOGD_IF(mTrackEnabled,
209         //        "renameStrongRefId: RefBase=%p, oid=%p, nid=%p",
210         //        mBase, old_id, new_id);
211         renameRefsId(mStrongRefs, old_id, new_id);
212     }
addWeakRef(const void * id)213     void addWeakRef(const void* id) {
214         addRef(&mWeakRefs, id, mWeak.load(std::memory_order_relaxed));
215     }
removeWeakRef(const void * id)216     void removeWeakRef(const void* id) {
217         if (!mRetain) {
218             removeRef(&mWeakRefs, id);
219         } else {
220             addRef(&mWeakRefs, id, -mWeak.load(std::memory_order_relaxed));
221         }
222     }
renameWeakRefId(const void * old_id,const void * new_id)223     void renameWeakRefId(const void* old_id, const void* new_id) {
224         renameRefsId(mWeakRefs, old_id, new_id);
225     }
trackMe(bool track,bool retain)226     void trackMe(bool track, bool retain)
227     {
228         mTrackEnabled = track;
229         mRetain = retain;
230     }
printRefs() const231     void printRefs() const
232     {
233         String8 text;
234         {
235             Mutex::Autolock _l(mMutex);
236             char buf[128];
237             snprintf(buf, sizeof(buf),
238                      "Strong references on RefBase %p (weakref_type %p):\n",
239                      mBase, this);
240             text.append(buf);
241             printRefsLocked(&text, mStrongRefs);
242             snprintf(buf, sizeof(buf),
243                      "Weak references on RefBase %p (weakref_type %p):\n",
244                      mBase, this);
245             text.append(buf);
246             printRefsLocked(&text, mWeakRefs);
247         }
248         {
249             char name[100];
250             snprintf(name, sizeof(name), DEBUG_REFS_CALLSTACK_PATH "/%p.stack",
251                      this);
252             int rc = open(name, O_RDWR | O_CREAT | O_APPEND, 644);
253             if (rc >= 0) {
254                 (void)write(rc, text.string(), text.length());
255                 close(rc);
256                 ALOGD("STACK TRACE for %p saved in %s", this, name);
257             }
258             else ALOGE("FAILED TO PRINT STACK TRACE for %p in %s: %s", this,
259                       name, strerror(errno));
260         }
261     }
262 private:
263     struct ref_entry
264     {
265         ref_entry* next;
266         const void* id;
267 #if DEBUG_REFS_CALLSTACK_ENABLED
268         CallStack::CallStackUPtr stack;
269 #endif
270         int32_t ref;
271     };
addRef(ref_entry ** refs,const void * id,int32_t mRef)272     void addRef(ref_entry** refs, const void* id, int32_t mRef)
273     {
274         if (mTrackEnabled) {
275             AutoMutex _l(mMutex);
276             ref_entry* ref = new ref_entry;
277             // Reference count at the time of the snapshot, but before the
278             // update.  Positive value means we increment, negative--we
279             // decrement the reference count.
280             ref->ref = mRef;
281             ref->id = id;
282 #if DEBUG_REFS_CALLSTACK_ENABLED
283             ref->stack = CallStack::getCurrent(2);
284 #endif
285             ref->next = *refs;
286             *refs = ref;
287         }
288     }
removeRef(ref_entry ** refs,const void * id)289     void removeRef(ref_entry** refs, const void* id)
290     {
291         if (mTrackEnabled) {
292             AutoMutex _l(mMutex);
293 
294             ref_entry* const head = *refs;
295             ref_entry* ref = head;
296             while (ref != NULL) {
297                 if (ref->id == id) {
298                     *refs = ref->next;
299                     delete ref;
300                     return;
301                 }
302                 refs = &ref->next;
303                 ref = *refs;
304             }
305             ALOGE("RefBase: removing id %p on RefBase %p"
306                     "(weakref_type %p) that doesn't exist!",
307                     id, mBase, this);
308             ref = head;
309             while (ref) {
310                 char inc = ref->ref >= 0 ? '+' : '-';
311                 ALOGD("\t%c ID %p (ref %d):", inc, ref->id, ref->ref);
312                 ref = ref->next;
313             }
314             CallStack::logStack(LOG_TAG);
315         }
316     }
renameRefsId(ref_entry * r,const void * old_id,const void * new_id)317     void renameRefsId(ref_entry* r, const void* old_id, const void* new_id)
318     {
319         if (mTrackEnabled) {
320             AutoMutex _l(mMutex);
321             ref_entry* ref = r;
322             while (ref != NULL) {
323                 if (ref->id == old_id) {
324                     ref->id = new_id;
325                 }
326                 ref = ref->next;
327             }
328         }
329     }
printRefsLocked(String8 * out,const ref_entry * refs) const330     void printRefsLocked(String8* out, const ref_entry* refs) const
331     {
332         char buf[128];
333         while (refs) {
334             char inc = refs->ref >= 0 ? '+' : '-';
335             snprintf(buf, sizeof(buf), "\t%c ID %p (ref %d):\n",
336                      inc, refs->id, refs->ref);
337             out->append(buf);
338 #if DEBUG_REFS_CALLSTACK_ENABLED
339             out->append(CallStack::stackToString("\t\t", refs->stack.get()));
340 #else
341             out->append("\t\t(call stacks disabled)");
342 #endif
343             refs = refs->next;
344         }
345     }
346     mutable Mutex mMutex;
347     ref_entry* mStrongRefs;
348     ref_entry* mWeakRefs;
349     bool mTrackEnabled;
350     // Collect stack traces on addref and removeref, instead of deleting the stack references
351     // on removeref that match the address ones.
352     bool mRetain;
353 #endif
354 };
355 // ---------------------------------------------------------------------------
incStrong(const void * id) const356 void RefBase::incStrong(const void* id) const
357 {
358     weakref_impl* const refs = mRefs;
359     refs->incWeak(id);
360 
361     refs->addStrongRef(id);
362     const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
363     ALOG_ASSERT(c > 0, "incStrong() called on %p after last strong ref", refs);
364 #if PRINT_REFS
365     ALOGD("incStrong of %p from %p: cnt=%d\n", this, id, c);
366 #endif
367     if (c != INITIAL_STRONG_VALUE)  {
368         return;
369     }
370     int32_t old __unused = refs->mStrong.fetch_sub(INITIAL_STRONG_VALUE, std::memory_order_relaxed);
371     // A decStrong() must still happen after us.
372     ALOG_ASSERT(old > INITIAL_STRONG_VALUE, "0x%x too small", old);
373     refs->mBase->onFirstRef();
374 }
decStrong(const void * id) const375 void RefBase::decStrong(const void* id) const
376 {
377     weakref_impl* const refs = mRefs;
378     refs->removeStrongRef(id);
379     const int32_t c = refs->mStrong.fetch_sub(1, std::memory_order_release);
380 #if PRINT_REFS
381     ALOGD("decStrong of %p from %p: cnt=%d\n", this, id, c);
382 #endif
383     LOG_ALWAYS_FATAL_IF(BAD_STRONG(c), "decStrong() called on %p too many times",
384             refs);
385     if (c == 1) {
386         std::atomic_thread_fence(std::memory_order_acquire);
387         refs->mBase->onLastStrongRef(id);
388         int32_t flags = refs->mFlags.load(std::memory_order_relaxed);
389         if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
390             delete this;
391             // The destructor does not delete refs in this case.
392         }
393     }
394     // Note that even with only strong reference operations, the thread
395     // deallocating this may not be the same as the thread deallocating refs.
396     // That's OK: all accesses to this happen before its deletion here,
397     // and all accesses to refs happen before its deletion in the final decWeak.
398     // The destructor can safely access mRefs because either it's deleting
399     // mRefs itself, or it's running entirely before the final mWeak decrement.
400     //
401     // Since we're doing atomic loads of `flags`, the static analyzer assumes
402     // they can change between `delete this;` and `refs->decWeak(id);`. This is
403     // not the case. The analyzer may become more okay with this patten when
404     // https://bugs.llvm.org/show_bug.cgi?id=34365 gets resolved. NOLINTNEXTLINE
405     refs->decWeak(id);
406 }
forceIncStrong(const void * id) const407 void RefBase::forceIncStrong(const void* id) const
408 {
409     // Allows initial mStrong of 0 in addition to INITIAL_STRONG_VALUE.
410     // TODO: Better document assumptions.
411     weakref_impl* const refs = mRefs;
412     refs->incWeak(id);
413 
414     refs->addStrongRef(id);
415     const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
416     ALOG_ASSERT(c >= 0, "forceIncStrong called on %p after ref count underflow",
417                refs);
418 #if PRINT_REFS
419     ALOGD("forceIncStrong of %p from %p: cnt=%d\n", this, id, c);
420 #endif
421     switch (c) {
422     case INITIAL_STRONG_VALUE:
423         refs->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
424                 std::memory_order_relaxed);
425         FALLTHROUGH_INTENDED;
426     case 0:
427         refs->mBase->onFirstRef();
428     }
429 }
getStrongCount() const430 int32_t RefBase::getStrongCount() const
431 {
432     // Debugging only; No memory ordering guarantees.
433     return mRefs->mStrong.load(std::memory_order_relaxed);
434 }
refBase() const435 RefBase* RefBase::weakref_type::refBase() const
436 {
437     return static_cast<const weakref_impl*>(this)->mBase;
438 }
incWeak(const void * id)439 void RefBase::weakref_type::incWeak(const void* id)
440 {
441     weakref_impl* const impl = static_cast<weakref_impl*>(this);
442     impl->addWeakRef(id);
443     const int32_t c __unused = impl->mWeak.fetch_add(1,
444             std::memory_order_relaxed);
445     ALOG_ASSERT(c >= 0, "incWeak called on %p after last weak ref", this);
446 }
decWeak(const void * id)447 void RefBase::weakref_type::decWeak(const void* id)
448 {
449     weakref_impl* const impl = static_cast<weakref_impl*>(this);
450     impl->removeWeakRef(id);
451     const int32_t c = impl->mWeak.fetch_sub(1, std::memory_order_release);
452     LOG_ALWAYS_FATAL_IF(BAD_WEAK(c), "decWeak called on %p too many times",
453             this);
454     if (c != 1) return;
455     atomic_thread_fence(std::memory_order_acquire);
456     int32_t flags = impl->mFlags.load(std::memory_order_relaxed);
457     if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
458         // This is the regular lifetime case. The object is destroyed
459         // when the last strong reference goes away. Since weakref_impl
460         // outlives the object, it is not destroyed in the dtor, and
461         // we'll have to do it here.
462         if (impl->mStrong.load(std::memory_order_relaxed)
463                 == INITIAL_STRONG_VALUE) {
464             // Decrementing a weak count to zero when object never had a strong
465             // reference.  We assume it acquired a weak reference early, e.g.
466             // in the constructor, and will eventually be properly destroyed,
467             // usually via incrementing and decrementing the strong count.
468             // Thus we no longer do anything here.  We log this case, since it
469             // seems to be extremely rare, and should not normally occur. We
470             // used to deallocate mBase here, so this may now indicate a leak.
471             ALOGW("RefBase: Object at %p lost last weak reference "
472                     "before it had a strong reference", impl->mBase);
473         } else {
474             // ALOGV("Freeing refs %p of old RefBase %p\n", this, impl->mBase);
475             delete impl;
476         }
477     } else {
478         // This is the OBJECT_LIFETIME_WEAK case. The last weak-reference
479         // is gone, we can destroy the object.
480         impl->mBase->onLastWeakRef(id);
481         delete impl->mBase;
482     }
483 }
attemptIncStrong(const void * id)484 bool RefBase::weakref_type::attemptIncStrong(const void* id)
485 {
486     incWeak(id);
487 
488     weakref_impl* const impl = static_cast<weakref_impl*>(this);
489     int32_t curCount = impl->mStrong.load(std::memory_order_relaxed);
490     ALOG_ASSERT(curCount >= 0,
491             "attemptIncStrong called on %p after underflow", this);
492     while (curCount > 0 && curCount != INITIAL_STRONG_VALUE) {
493         // we're in the easy/common case of promoting a weak-reference
494         // from an existing strong reference.
495         if (impl->mStrong.compare_exchange_weak(curCount, curCount+1,
496                 std::memory_order_relaxed)) {
497             break;
498         }
499         // the strong count has changed on us, we need to re-assert our
500         // situation. curCount was updated by compare_exchange_weak.
501     }
502 
503     if (curCount <= 0 || curCount == INITIAL_STRONG_VALUE) {
504         // we're now in the harder case of either:
505         // - there never was a strong reference on us
506         // - or, all strong references have been released
507         int32_t flags = impl->mFlags.load(std::memory_order_relaxed);
508         if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
509             // this object has a "normal" life-time, i.e.: it gets destroyed
510             // when the last strong reference goes away
511             if (curCount <= 0) {
512                 // the last strong-reference got released, the object cannot
513                 // be revived.
514                 decWeak(id);
515                 return false;
516             }
517             // here, curCount == INITIAL_STRONG_VALUE, which means
518             // there never was a strong-reference, so we can try to
519             // promote this object; we need to do that atomically.
520             while (curCount > 0) {
521                 if (impl->mStrong.compare_exchange_weak(curCount, curCount+1,
522                         std::memory_order_relaxed)) {
523                     break;
524                 }
525                 // the strong count has changed on us, we need to re-assert our
526                 // situation (e.g.: another thread has inc/decStrong'ed us)
527                 // curCount has been updated.
528             }
529             if (curCount <= 0) {
530                 // promote() failed, some other thread destroyed us in the
531                 // meantime (i.e.: strong count reached zero).
532                 decWeak(id);
533                 return false;
534             }
535         } else {
536             // this object has an "extended" life-time, i.e.: it can be
537             // revived from a weak-reference only.
538             // Ask the object's implementation if it agrees to be revived
539             if (!impl->mBase->onIncStrongAttempted(FIRST_INC_STRONG, id)) {
540                 // it didn't so give-up.
541                 decWeak(id);
542                 return false;
543             }
544             // grab a strong-reference, which is always safe due to the
545             // extended life-time.
546             curCount = impl->mStrong.fetch_add(1, std::memory_order_relaxed);
547             // If the strong reference count has already been incremented by
548             // someone else, the implementor of onIncStrongAttempted() is holding
549             // an unneeded reference.  So call onLastStrongRef() here to remove it.
550             // (No, this is not pretty.)  Note that we MUST NOT do this if we
551             // are in fact acquiring the first reference.
552             if (curCount != 0 && curCount != INITIAL_STRONG_VALUE) {
553                 impl->mBase->onLastStrongRef(id);
554             }
555         }
556     }
557 
558     impl->addStrongRef(id);
559 #if PRINT_REFS
560     ALOGD("attemptIncStrong of %p from %p: cnt=%d\n", this, id, curCount);
561 #endif
562     // curCount is the value of mStrong before we incremented it.
563     // Now we need to fix-up the count if it was INITIAL_STRONG_VALUE.
564     // This must be done safely, i.e.: handle the case where several threads
565     // were here in attemptIncStrong().
566     // curCount > INITIAL_STRONG_VALUE is OK, and can happen if we're doing
567     // this in the middle of another incStrong.  The subtraction is handled
568     // by the thread that started with INITIAL_STRONG_VALUE.
569     if (curCount == INITIAL_STRONG_VALUE) {
570         impl->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
571                 std::memory_order_relaxed);
572     }
573     return true;
574 }
attemptIncWeak(const void * id)575 bool RefBase::weakref_type::attemptIncWeak(const void* id)
576 {
577     weakref_impl* const impl = static_cast<weakref_impl*>(this);
578     int32_t curCount = impl->mWeak.load(std::memory_order_relaxed);
579     ALOG_ASSERT(curCount >= 0, "attemptIncWeak called on %p after underflow",
580                this);
581     while (curCount > 0) {
582         if (impl->mWeak.compare_exchange_weak(curCount, curCount+1,
583                 std::memory_order_relaxed)) {
584             break;
585         }
586         // curCount has been updated.
587     }
588     if (curCount > 0) {
589         impl->addWeakRef(id);
590     }
591     return curCount > 0;
592 }
getWeakCount() const593 int32_t RefBase::weakref_type::getWeakCount() const
594 {
595     // Debug only!
596     return static_cast<const weakref_impl*>(this)->mWeak
597             .load(std::memory_order_relaxed);
598 }
printRefs() const599 void RefBase::weakref_type::printRefs() const
600 {
601     static_cast<const weakref_impl*>(this)->printRefs();
602 }
trackMe(bool enable,bool retain)603 void RefBase::weakref_type::trackMe(bool enable, bool retain)
604 {
605     static_cast<weakref_impl*>(this)->trackMe(enable, retain);
606 }
createWeak(const void * id) const607 RefBase::weakref_type* RefBase::createWeak(const void* id) const
608 {
609     mRefs->incWeak(id);
610     return mRefs;
611 }
getWeakRefs() const612 RefBase::weakref_type* RefBase::getWeakRefs() const
613 {
614     return mRefs;
615 }
RefBase()616 RefBase::RefBase()
617     : mRefs(new weakref_impl(this))
618 {
619 }
~RefBase()620 RefBase::~RefBase()
621 {
622     int32_t flags = mRefs->mFlags.load(std::memory_order_relaxed);
623     // Life-time of this object is extended to WEAK, in
624     // which case weakref_impl doesn't out-live the object and we
625     // can free it now.
626     if ((flags & OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_WEAK) {
627         // It's possible that the weak count is not 0 if the object
628         // re-acquired a weak reference in its destructor
629         if (mRefs->mWeak.load(std::memory_order_relaxed) == 0) {
630             delete mRefs;
631         }
632     } else if (mRefs->mStrong.load(std::memory_order_relaxed) == INITIAL_STRONG_VALUE) {
633         // We never acquired a strong reference on this object.
634 #if DEBUG_REFBASE_DESTRUCTION
635         // Treating this as fatal is prone to causing boot loops. For debugging, it's
636         // better to treat as non-fatal.
637         ALOGD("RefBase: Explicit destruction, weak count = %d (in %p)", mRefs->mWeak.load(), this);
638         // CallStack::logStack(LOG_TAG);
639 #else
640         LOG_ALWAYS_FATAL("RefBase: Explicit destruction, weak count = %d", mRefs->mWeak.load());
641 #endif
642     }
643     // For debugging purposes, clear mRefs.  Ineffective against outstanding wp's.
644     const_cast<weakref_impl*&>(mRefs) = nullptr;
645 }
extendObjectLifetime(int32_t mode)646 void RefBase::extendObjectLifetime(int32_t mode)
647 {
648     // Must be happens-before ordered with respect to construction or any
649     // operation that could destroy the object.
650     mRefs->mFlags.fetch_or(mode, std::memory_order_relaxed);
651 }
onFirstRef()652 void RefBase::onFirstRef()
653 {
654 }
onLastStrongRef(const void *)655 void RefBase::onLastStrongRef(const void* /*id*/)
656 {
657 }
onIncStrongAttempted(uint32_t flags,const void *)658 bool RefBase::onIncStrongAttempted(uint32_t flags, const void* /*id*/)
659 {
660     return (flags&FIRST_INC_STRONG) ? true : false;
661 }
onLastWeakRef(const void *)662 void RefBase::onLastWeakRef(const void* /*id*/)
663 {
664 }
665 // ---------------------------------------------------------------------------
666 #if DEBUG_REFS
renameRefs(size_t n,const ReferenceRenamer & renamer)667 void RefBase::renameRefs(size_t n, const ReferenceRenamer& renamer) {
668     for (size_t i=0 ; i<n ; i++) {
669         renamer(i);
670     }
671 }
672 #else
renameRefs(size_t,const ReferenceRenamer &)673 void RefBase::renameRefs(size_t /*n*/, const ReferenceRenamer& /*renamer*/) { }
674 #endif
renameRefId(weakref_type * ref,const void * old_id,const void * new_id)675 void RefBase::renameRefId(weakref_type* ref,
676         const void* old_id, const void* new_id) {
677     weakref_impl* const impl = static_cast<weakref_impl*>(ref);
678     impl->renameStrongRefId(old_id, new_id);
679     impl->renameWeakRefId(old_id, new_id);
680 }
renameRefId(RefBase * ref,const void * old_id,const void * new_id)681 void RefBase::renameRefId(RefBase* ref,
682         const void* old_id, const void* new_id) {
683     ref->mRefs->renameStrongRefId(old_id, new_id);
684     ref->mRefs->renameWeakRefId(old_id, new_id);
685 }
686 }; // namespace android
687