• 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 
17 #define LOG_TAG "RefBase"
18 // #define LOG_NDEBUG 0
19 
20 #include <memory>
21 
22 #include <android-base/macros.h>
23 
24 #include <fcntl.h>
25 #include <log/log.h>
26 
27 #include <utils/RefBase.h>
28 #include <utils/String8.h>
29 
30 #include <utils/Mutex.h>
31 
32 #ifndef __unused
33 #define __unused __attribute__((__unused__))
34 #endif
35 
36 // Compile with refcounting debugging enabled.
37 #ifndef DEBUG_REFS
38 #define DEBUG_REFS 0
39 #endif
40 
41 // The following three are ignored unless DEBUG_REFS is set.
42 
43 // whether ref-tracking is enabled by default, if not, trackMe(true, false)
44 // needs to be called explicitly
45 #define DEBUG_REFS_ENABLED_BY_DEFAULT 0
46 
47 // whether callstack are collected (significantly slows things down)
48 #define DEBUG_REFS_CALLSTACK_ENABLED 1
49 
50 // folder where stack traces are saved when DEBUG_REFS is enabled
51 // this folder needs to exist and be writable
52 #ifdef __ANDROID__
53 #define DEBUG_REFS_CALLSTACK_PATH "/data/debug"
54 #else
55 #define DEBUG_REFS_CALLSTACK_PATH "."
56 #endif
57 
58 // log all reference counting operations
59 #define PRINT_REFS 0
60 
61 #if defined(__linux__)
62 // CallStack is only supported on linux type platforms.
63 #define CALLSTACK_ENABLED 1
64 #else
65 #define CALLSTACK_ENABLED 0
66 #endif
67 
68 #if CALLSTACK_ENABLED
69 #include <utils/CallStack.h>
70 #endif
71 
72 // ---------------------------------------------------------------------------
73 
74 namespace android {
75 
76 // Observations, invariants, etc:
77 
78 // By default, obects are destroyed when the last strong reference disappears
79 // or, if the object never had a strong reference, when the last weak reference
80 // disappears.
81 //
82 // OBJECT_LIFETIME_WEAK changes this behavior to retain the object
83 // unconditionally until the last reference of either kind disappears.  The
84 // client ensures that the extendObjectLifetime call happens before the dec
85 // call that would otherwise have deallocated the object, or before an
86 // attemptIncStrong call that might rely on it.  We do not worry about
87 // concurrent changes to the object lifetime.
88 //
89 // AttemptIncStrong will succeed if the object has a strong reference, or if it
90 // has a weak reference and has never had a strong reference.
91 // AttemptIncWeak really does succeed only if there is already a WEAK
92 // reference, and thus may fail when attemptIncStrong would succeed.
93 //
94 // mStrong is the strong reference count.  mWeak is the weak reference count.
95 // Between calls, and ignoring memory ordering effects, mWeak includes strong
96 // references, and is thus >= mStrong.
97 //
98 // A weakref_impl holds all the information, including both reference counts,
99 // required to perform wp<> operations.  Thus these can continue to be performed
100 // after the RefBase object has been destroyed.
101 //
102 // A weakref_impl is allocated as the value of mRefs in a RefBase object on
103 // construction.
104 // In the OBJECT_LIFETIME_STRONG case, it is normally deallocated in decWeak,
105 // and hence lives as long as the last weak reference. (It can also be
106 // deallocated in the RefBase destructor iff the strong reference count was
107 // never incremented and the weak count is zero, e.g.  if the RefBase object is
108 // explicitly destroyed without decrementing the strong count.  This should be
109 // avoided.) In this case, the RefBase destructor should be invoked from
110 // decStrong.
111 // In the OBJECT_LIFETIME_WEAK case, the weakref_impl is always deallocated in
112 // the RefBase destructor, which is always invoked by decWeak. DecStrong
113 // explicitly avoids the deletion in this case.
114 //
115 // Memory ordering:
116 // The client must ensure that every inc() call, together with all other
117 // accesses to the object, happens before the corresponding dec() call.
118 //
119 // We try to keep memory ordering constraints on atomics as weak as possible,
120 // since memory fences or ordered memory accesses are likely to be a major
121 // performance cost for this code. All accesses to mStrong, mWeak, and mFlags
122 // explicitly relax memory ordering in some way.
123 //
124 // The only operations that are not memory_order_relaxed are reference count
125 // decrements. All reference count decrements are release operations.  In
126 // addition, the final decrement leading the deallocation is followed by an
127 // acquire fence, which we can view informally as also turning it into an
128 // acquire operation.  (See 29.8p4 [atomics.fences] for details. We could
129 // alternatively use acq_rel operations for all decrements. This is probably
130 // slower on most current (2016) hardware, especially on ARMv7, but that may
131 // not be true indefinitely.)
132 //
133 // This convention ensures that the second-to-last decrement synchronizes with
134 // (in the language of 1.10 in the C++ standard) the final decrement of a
135 // reference count. Since reference counts are only updated using atomic
136 // read-modify-write operations, this also extends to any earlier decrements.
137 // (See "release sequence" in 1.10.)
138 //
139 // Since all operations on an object happen before the corresponding reference
140 // count decrement, and all reference count decrements happen before the final
141 // one, we are guaranteed that all other object accesses happen before the
142 // object is destroyed.
143 
144 
145 #define INITIAL_STRONG_VALUE (1<<28)
146 
147 #define MAX_COUNT 0xfffff
148 
149 // Test whether the argument is a clearly invalid strong reference count.
150 // Used only for error checking on the value before an atomic decrement.
151 // Intended to be very cheap.
152 // Note that we cannot just check for excess decrements by comparing to zero
153 // since the object would be deallocated before that.
154 #define BAD_STRONG(c) \
155         ((c) == 0 || ((c) & (~(MAX_COUNT | INITIAL_STRONG_VALUE))) != 0)
156 
157 // Same for weak counts.
158 #define BAD_WEAK(c) ((c) == 0 || ((c) & (~MAX_COUNT)) != 0)
159 
160 // name kept because prebuilts used to use it from inlining sp<> code
sp_report_stack_pointer()161 void sp_report_stack_pointer() { LOG_ALWAYS_FATAL("RefBase used with stack pointer argument"); }
162 
163 // Check whether address is definitely on the calling stack.  We actually check whether it is on
164 // the same 4K page as the frame pointer.
165 //
166 // Assumptions:
167 // - Pages are never smaller than 4K (MIN_PAGE_SIZE)
168 // - Malloced memory never shares a page with a stack.
169 //
170 // It does not appear safe to broaden this check to include adjacent pages; apparently this code
171 // is used in environments where there may not be a guard page below (at higher addresses than)
172 // the bottom of the stack.
check_not_on_stack(const void * ptr)173 static void check_not_on_stack(const void* ptr) {
174     static constexpr int MIN_PAGE_SIZE = 0x1000;  // 4K. Safer than including sys/user.h.
175     static constexpr uintptr_t MIN_PAGE_MASK = ~static_cast<uintptr_t>(MIN_PAGE_SIZE - 1);
176     uintptr_t my_frame_address =
177             reinterpret_cast<uintptr_t>(__builtin_frame_address(0 /* this frame */));
178     if (((reinterpret_cast<uintptr_t>(ptr) ^ my_frame_address) & MIN_PAGE_MASK) == 0) {
179         sp_report_stack_pointer();
180     }
181 }
182 
183 // ---------------------------------------------------------------------------
184 
185 class RefBase::weakref_impl : public RefBase::weakref_type
186 {
187 public:
188     std::atomic<int32_t>    mStrong;
189     std::atomic<int32_t>    mWeak;
190     RefBase* const          mBase;
191     std::atomic<int32_t>    mFlags;
192 
193 #if !DEBUG_REFS
194 
weakref_impl(RefBase * base)195     explicit weakref_impl(RefBase* base)
196         : mStrong(INITIAL_STRONG_VALUE)
197         , mWeak(0)
198         , mBase(base)
199         , mFlags(OBJECT_LIFETIME_STRONG)
200     {
201     }
202 
addStrongRef(const void *)203     void addStrongRef(const void* /*id*/) { }
removeStrongRef(const void *)204     void removeStrongRef(const void* /*id*/) { }
renameStrongRefId(const void *,const void *)205     void renameStrongRefId(const void* /*old_id*/, const void* /*new_id*/) { }
addWeakRef(const void *)206     void addWeakRef(const void* /*id*/) { }
removeWeakRef(const void *)207     void removeWeakRef(const void* /*id*/) { }
renameWeakRefId(const void *,const void *)208     void renameWeakRefId(const void* /*old_id*/, const void* /*new_id*/) { }
printRefs() const209     void printRefs() const { }
trackMe(bool,bool)210     void trackMe(bool, bool) { }
211 
212 #else
213 
weakref_impl(RefBase * base)214     weakref_impl(RefBase* base)
215         : mStrong(INITIAL_STRONG_VALUE)
216         , mWeak(0)
217         , mBase(base)
218         , mFlags(OBJECT_LIFETIME_STRONG)
219         , mStrongRefs(NULL)
220         , mWeakRefs(NULL)
221         , mTrackEnabled(!!DEBUG_REFS_ENABLED_BY_DEFAULT)
222         , mRetain(false)
223     {
224     }
225 
~weakref_impl()226     ~weakref_impl()
227     {
228         bool dumpStack = false;
229         if (!mRetain && mStrongRefs != NULL) {
230             dumpStack = true;
231             ALOGE("Strong references remain:");
232             ref_entry* refs = mStrongRefs;
233             while (refs) {
234                 char inc = refs->ref >= 0 ? '+' : '-';
235                 ALOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
236 #if DEBUG_REFS_CALLSTACK_ENABLED && CALLSTACK_ENABLED
237                 CallStack::logStack(LOG_TAG, refs->stack.get());
238 #endif
239                 refs = refs->next;
240             }
241         }
242 
243         if (!mRetain && mWeakRefs != NULL) {
244             dumpStack = true;
245             ALOGE("Weak references remain!");
246             ref_entry* refs = mWeakRefs;
247             while (refs) {
248                 char inc = refs->ref >= 0 ? '+' : '-';
249                 ALOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
250 #if DEBUG_REFS_CALLSTACK_ENABLED && CALLSTACK_ENABLED
251                 CallStack::logStack(LOG_TAG, refs->stack.get());
252 #endif
253                 refs = refs->next;
254             }
255         }
256         if (dumpStack) {
257             ALOGE("above errors at:");
258 #if CALLSTACK_ENABLED
259             CallStack::logStack(LOG_TAG);
260 #endif
261         }
262     }
263 
addStrongRef(const void * id)264     void addStrongRef(const void* id) {
265         //ALOGD_IF(mTrackEnabled,
266         //        "addStrongRef: RefBase=%p, id=%p", mBase, id);
267         addRef(&mStrongRefs, id, mStrong.load(std::memory_order_relaxed));
268     }
269 
removeStrongRef(const void * id)270     void removeStrongRef(const void* id) {
271         //ALOGD_IF(mTrackEnabled,
272         //        "removeStrongRef: RefBase=%p, id=%p", mBase, id);
273         if (!mRetain) {
274             removeRef(&mStrongRefs, id);
275         } else {
276             addRef(&mStrongRefs, id, -mStrong.load(std::memory_order_relaxed));
277         }
278     }
279 
renameStrongRefId(const void * old_id,const void * new_id)280     void renameStrongRefId(const void* old_id, const void* new_id) {
281         //ALOGD_IF(mTrackEnabled,
282         //        "renameStrongRefId: RefBase=%p, oid=%p, nid=%p",
283         //        mBase, old_id, new_id);
284         renameRefsId(mStrongRefs, old_id, new_id);
285     }
286 
addWeakRef(const void * id)287     void addWeakRef(const void* id) {
288         addRef(&mWeakRefs, id, mWeak.load(std::memory_order_relaxed));
289     }
290 
removeWeakRef(const void * id)291     void removeWeakRef(const void* id) {
292         if (!mRetain) {
293             removeRef(&mWeakRefs, id);
294         } else {
295             addRef(&mWeakRefs, id, -mWeak.load(std::memory_order_relaxed));
296         }
297     }
298 
renameWeakRefId(const void * old_id,const void * new_id)299     void renameWeakRefId(const void* old_id, const void* new_id) {
300         renameRefsId(mWeakRefs, old_id, new_id);
301     }
302 
trackMe(bool track,bool retain)303     void trackMe(bool track, bool retain) {
304         mTrackEnabled = track;
305         mRetain = retain;
306     }
307 
printRefs() const308     void printRefs() const
309     {
310         String8 text;
311 
312         {
313             Mutex::Autolock _l(mMutex);
314             char buf[128];
315             snprintf(buf, sizeof(buf),
316                      "Strong references on RefBase %p (weakref_type %p):\n",
317                      mBase, this);
318             text.append(buf);
319             printRefsLocked(&text, mStrongRefs);
320             snprintf(buf, sizeof(buf),
321                      "Weak references on RefBase %p (weakref_type %p):\n",
322                      mBase, this);
323             text.append(buf);
324             printRefsLocked(&text, mWeakRefs);
325         }
326 
327         {
328             char name[100];
329             snprintf(name, sizeof(name), DEBUG_REFS_CALLSTACK_PATH "/%p.stack",
330                      this);
331             int rc = open(name, O_RDWR | O_CREAT | O_APPEND, 0644);
332             if (rc >= 0) {
333                 (void)write(rc, text.string(), text.length());
334                 close(rc);
335                 ALOGI("STACK TRACE for %p saved in %s", this, name);
336             }
337             else ALOGE("FAILED TO PRINT STACK TRACE for %p in %s: %s", this,
338                       name, strerror(errno));
339         }
340     }
341 
342 private:
343     struct ref_entry
344     {
345         ref_entry* next;
346         const void* id;
347 #if DEBUG_REFS_CALLSTACK_ENABLED && CALLSTACK_ENABLED
348         CallStack::CallStackUPtr stack;
349 #endif
350         int32_t ref;
351     };
352 
addRef(ref_entry ** refs,const void * id,int32_t mRef)353     void addRef(ref_entry** refs, const void* id, int32_t mRef)
354     {
355         if (mTrackEnabled) {
356             AutoMutex _l(mMutex);
357 
358             ref_entry* ref = new ref_entry;
359             // Reference count at the time of the snapshot, but before the
360             // update.  Positive value means we increment, negative--we
361             // decrement the reference count.
362             ref->ref = mRef;
363             ref->id = id;
364 #if DEBUG_REFS_CALLSTACK_ENABLED && CALLSTACK_ENABLED
365             ref->stack = CallStack::getCurrent(2);
366 #endif
367             ref->next = *refs;
368             *refs = ref;
369         }
370     }
371 
removeRef(ref_entry ** refs,const void * id)372     void removeRef(ref_entry** refs, const void* id)
373     {
374         if (mTrackEnabled) {
375             AutoMutex _l(mMutex);
376 
377             ref_entry* const head = *refs;
378             ref_entry* ref = head;
379             while (ref != NULL) {
380                 if (ref->id == id) {
381                     *refs = ref->next;
382                     delete ref;
383                     return;
384                 }
385                 refs = &ref->next;
386                 ref = *refs;
387             }
388 
389             ALOGE("RefBase: removing id %p on RefBase %p"
390                     "(weakref_type %p) that doesn't exist!",
391                     id, mBase, this);
392 
393             ref = head;
394             while (ref) {
395                 char inc = ref->ref >= 0 ? '+' : '-';
396                 ALOGD("\t%c ID %p (ref %d):", inc, ref->id, ref->ref);
397                 ref = ref->next;
398             }
399 
400 #if CALLSTACK_ENABLED
401             CallStack::logStack(LOG_TAG);
402 #endif
403         }
404     }
405 
renameRefsId(ref_entry * r,const void * old_id,const void * new_id)406     void renameRefsId(ref_entry* r, const void* old_id, const void* new_id)
407     {
408         if (mTrackEnabled) {
409             AutoMutex _l(mMutex);
410             ref_entry* ref = r;
411             while (ref != NULL) {
412                 if (ref->id == old_id) {
413                     ref->id = new_id;
414                 }
415                 ref = ref->next;
416             }
417         }
418     }
419 
printRefsLocked(String8 * out,const ref_entry * refs) const420     void printRefsLocked(String8* out, const ref_entry* refs) const
421     {
422         char buf[128];
423         while (refs) {
424             char inc = refs->ref >= 0 ? '+' : '-';
425             snprintf(buf, sizeof(buf), "\t%c ID %p (ref %d):\n",
426                      inc, refs->id, refs->ref);
427             out->append(buf);
428 #if DEBUG_REFS_CALLSTACK_ENABLED && CALLSTACK_ENABLED
429             out->append(CallStack::stackToString("\t\t", refs->stack.get()));
430 #else
431             out->append("\t\t(call stacks disabled)");
432 #endif
433             refs = refs->next;
434         }
435     }
436 
437     mutable Mutex mMutex;
438     ref_entry* mStrongRefs;
439     ref_entry* mWeakRefs;
440 
441     bool mTrackEnabled;
442     // Collect stack traces on addref and removeref, instead of deleting the stack references
443     // on removeref that match the address ones.
444     bool mRetain;
445 
446 #endif
447 };
448 
449 // ---------------------------------------------------------------------------
450 
incStrong(const void * id) const451 void RefBase::incStrong(const void* id) const
452 {
453     weakref_impl* const refs = mRefs;
454     refs->incWeak(id);
455 
456     refs->addStrongRef(id);
457     const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
458     ALOG_ASSERT(c > 0, "incStrong() called on %p after last strong ref", refs);
459 #if PRINT_REFS
460     ALOGD("incStrong of %p from %p: cnt=%d\n", this, id, c);
461 #endif
462     if (c != INITIAL_STRONG_VALUE)  {
463         return;
464     }
465 
466     check_not_on_stack(this);
467 
468     int32_t old __unused = refs->mStrong.fetch_sub(INITIAL_STRONG_VALUE, std::memory_order_relaxed);
469     // A decStrong() must still happen after us.
470     ALOG_ASSERT(old > INITIAL_STRONG_VALUE, "0x%x too small", old);
471     refs->mBase->onFirstRef();
472 }
473 
incStrongRequireStrong(const void * id) const474 void RefBase::incStrongRequireStrong(const void* id) const {
475     weakref_impl* const refs = mRefs;
476     refs->incWeak(id);
477 
478     refs->addStrongRef(id);
479     const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
480 
481     LOG_ALWAYS_FATAL_IF(c <= 0 || c == INITIAL_STRONG_VALUE,
482                         "incStrongRequireStrong() called on %p which isn't already owned", refs);
483 #if PRINT_REFS
484     ALOGD("incStrong (requiring strong) of %p from %p: cnt=%d\n", this, id, c);
485 #endif
486 }
487 
decStrong(const void * id) const488 void RefBase::decStrong(const void* id) const
489 {
490     weakref_impl* const refs = mRefs;
491     refs->removeStrongRef(id);
492     const int32_t c = refs->mStrong.fetch_sub(1, std::memory_order_release);
493 #if PRINT_REFS
494     ALOGD("decStrong of %p from %p: cnt=%d\n", this, id, c);
495 #endif
496     LOG_ALWAYS_FATAL_IF(BAD_STRONG(c), "decStrong() called on %p too many times",
497             refs);
498     if (c == 1) {
499         std::atomic_thread_fence(std::memory_order_acquire);
500         refs->mBase->onLastStrongRef(id);
501         int32_t flags = refs->mFlags.load(std::memory_order_relaxed);
502         if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
503             delete this;
504             // The destructor does not delete refs in this case.
505         }
506     }
507     // Note that even with only strong reference operations, the thread
508     // deallocating this may not be the same as the thread deallocating refs.
509     // That's OK: all accesses to this happen before its deletion here,
510     // and all accesses to refs happen before its deletion in the final decWeak.
511     // The destructor can safely access mRefs because either it's deleting
512     // mRefs itself, or it's running entirely before the final mWeak decrement.
513     //
514     // Since we're doing atomic loads of `flags`, the static analyzer assumes
515     // they can change between `delete this;` and `refs->decWeak(id);`. This is
516     // not the case. The analyzer may become more okay with this patten when
517     // https://bugs.llvm.org/show_bug.cgi?id=34365 gets resolved. NOLINTNEXTLINE
518     refs->decWeak(id);
519 }
520 
forceIncStrong(const void * id) const521 void RefBase::forceIncStrong(const void* id) const
522 {
523     // Allows initial mStrong of 0 in addition to INITIAL_STRONG_VALUE.
524     // TODO: Better document assumptions.
525     weakref_impl* const refs = mRefs;
526     refs->incWeak(id);
527 
528     refs->addStrongRef(id);
529     const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
530     ALOG_ASSERT(c >= 0, "forceIncStrong called on %p after ref count underflow",
531                refs);
532 #if PRINT_REFS
533     ALOGD("forceIncStrong of %p from %p: cnt=%d\n", this, id, c);
534 #endif
535 
536     switch (c) {
537     case INITIAL_STRONG_VALUE:
538         refs->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
539                 std::memory_order_relaxed);
540         FALLTHROUGH_INTENDED;
541     case 0:
542         refs->mBase->onFirstRef();
543     }
544 }
545 
getStrongCount() const546 int32_t RefBase::getStrongCount() const
547 {
548     // Debugging only; No memory ordering guarantees.
549     return mRefs->mStrong.load(std::memory_order_relaxed);
550 }
551 
refBase() const552 RefBase* RefBase::weakref_type::refBase() const
553 {
554     return static_cast<const weakref_impl*>(this)->mBase;
555 }
556 
incWeak(const void * id)557 void RefBase::weakref_type::incWeak(const void* id)
558 {
559     weakref_impl* const impl = static_cast<weakref_impl*>(this);
560     impl->addWeakRef(id);
561     const int32_t c __unused = impl->mWeak.fetch_add(1,
562             std::memory_order_relaxed);
563     ALOG_ASSERT(c >= 0, "incWeak called on %p after last weak ref", this);
564 }
565 
incWeakRequireWeak(const void * id)566 void RefBase::weakref_type::incWeakRequireWeak(const void* id)
567 {
568     weakref_impl* const impl = static_cast<weakref_impl*>(this);
569     impl->addWeakRef(id);
570     const int32_t c __unused = impl->mWeak.fetch_add(1,
571             std::memory_order_relaxed);
572     LOG_ALWAYS_FATAL_IF(c <= 0, "incWeakRequireWeak called on %p which has no weak refs", this);
573 }
574 
decWeak(const void * id)575 void RefBase::weakref_type::decWeak(const void* id)
576 {
577     weakref_impl* const impl = static_cast<weakref_impl*>(this);
578     impl->removeWeakRef(id);
579     const int32_t c = impl->mWeak.fetch_sub(1, std::memory_order_release);
580     LOG_ALWAYS_FATAL_IF(BAD_WEAK(c), "decWeak called on %p too many times",
581             this);
582     if (c != 1) return;
583     atomic_thread_fence(std::memory_order_acquire);
584 
585     int32_t flags = impl->mFlags.load(std::memory_order_relaxed);
586     if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
587         // This is the regular lifetime case. The object is destroyed
588         // when the last strong reference goes away. Since weakref_impl
589         // outlives the object, it is not destroyed in the dtor, and
590         // we'll have to do it here.
591         if (impl->mStrong.load(std::memory_order_relaxed)
592                 == INITIAL_STRONG_VALUE) {
593             // Decrementing a weak count to zero when object never had a strong
594             // reference.  We assume it acquired a weak reference early, e.g.
595             // in the constructor, and will eventually be properly destroyed,
596             // usually via incrementing and decrementing the strong count.
597             // Thus we no longer do anything here.  We log this case, since it
598             // seems to be extremely rare, and should not normally occur. We
599             // used to deallocate mBase here, so this may now indicate a leak.
600             ALOGW("RefBase: Object at %p lost last weak reference "
601                     "before it had a strong reference", impl->mBase);
602         } else {
603             // ALOGV("Freeing refs %p of old RefBase %p\n", this, impl->mBase);
604             delete impl;
605         }
606     } else {
607         // This is the OBJECT_LIFETIME_WEAK case. The last weak-reference
608         // is gone, we can destroy the object.
609         impl->mBase->onLastWeakRef(id);
610         delete impl->mBase;
611     }
612 }
613 
attemptIncStrong(const void * id)614 bool RefBase::weakref_type::attemptIncStrong(const void* id)
615 {
616     incWeak(id);
617 
618     weakref_impl* const impl = static_cast<weakref_impl*>(this);
619     int32_t curCount = impl->mStrong.load(std::memory_order_relaxed);
620 
621     ALOG_ASSERT(curCount >= 0,
622             "attemptIncStrong called on %p after underflow", this);
623 
624     while (curCount > 0 && curCount != INITIAL_STRONG_VALUE) {
625         // we're in the easy/common case of promoting a weak-reference
626         // from an existing strong reference.
627         if (impl->mStrong.compare_exchange_weak(curCount, curCount+1,
628                 std::memory_order_relaxed)) {
629             break;
630         }
631         // the strong count has changed on us, we need to re-assert our
632         // situation. curCount was updated by compare_exchange_weak.
633     }
634 
635     if (curCount <= 0 || curCount == INITIAL_STRONG_VALUE) {
636         // we're now in the harder case of either:
637         // - there never was a strong reference on us
638         // - or, all strong references have been released
639         int32_t flags = impl->mFlags.load(std::memory_order_relaxed);
640         if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
641             // this object has a "normal" life-time, i.e.: it gets destroyed
642             // when the last strong reference goes away
643             if (curCount <= 0) {
644                 // the last strong-reference got released, the object cannot
645                 // be revived.
646                 decWeak(id);
647                 return false;
648             }
649 
650             // here, curCount == INITIAL_STRONG_VALUE, which means
651             // there never was a strong-reference, so we can try to
652             // promote this object; we need to do that atomically.
653             while (curCount > 0) {
654                 if (impl->mStrong.compare_exchange_weak(curCount, curCount+1,
655                         std::memory_order_relaxed)) {
656                     break;
657                 }
658                 // the strong count has changed on us, we need to re-assert our
659                 // situation (e.g.: another thread has inc/decStrong'ed us)
660                 // curCount has been updated.
661             }
662 
663             if (curCount <= 0) {
664                 // promote() failed, some other thread destroyed us in the
665                 // meantime (i.e.: strong count reached zero).
666                 decWeak(id);
667                 return false;
668             }
669         } else {
670             // this object has an "extended" life-time, i.e.: it can be
671             // revived from a weak-reference only.
672             // Ask the object's implementation if it agrees to be revived
673             if (!impl->mBase->onIncStrongAttempted(FIRST_INC_STRONG, id)) {
674                 // it didn't so give-up.
675                 decWeak(id);
676                 return false;
677             }
678             // grab a strong-reference, which is always safe due to the
679             // extended life-time.
680             curCount = impl->mStrong.fetch_add(1, std::memory_order_relaxed);
681             // If the strong reference count has already been incremented by
682             // someone else, the implementor of onIncStrongAttempted() is holding
683             // an unneeded reference.  So call onLastStrongRef() here to remove it.
684             // (No, this is not pretty.)  Note that we MUST NOT do this if we
685             // are in fact acquiring the first reference.
686             if (curCount != 0 && curCount != INITIAL_STRONG_VALUE) {
687                 impl->mBase->onLastStrongRef(id);
688             }
689         }
690     }
691 
692     impl->addStrongRef(id);
693 
694 #if PRINT_REFS
695     ALOGD("attemptIncStrong of %p from %p: cnt=%d\n", this, id, curCount);
696 #endif
697 
698     // curCount is the value of mStrong before we incremented it.
699     // Now we need to fix-up the count if it was INITIAL_STRONG_VALUE.
700     // This must be done safely, i.e.: handle the case where several threads
701     // were here in attemptIncStrong().
702     // curCount > INITIAL_STRONG_VALUE is OK, and can happen if we're doing
703     // this in the middle of another incStrong.  The subtraction is handled
704     // by the thread that started with INITIAL_STRONG_VALUE.
705     if (curCount == INITIAL_STRONG_VALUE) {
706         impl->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
707                 std::memory_order_relaxed);
708     }
709 
710     return true;
711 }
712 
attemptIncWeak(const void * id)713 bool RefBase::weakref_type::attemptIncWeak(const void* id)
714 {
715     weakref_impl* const impl = static_cast<weakref_impl*>(this);
716 
717     int32_t curCount = impl->mWeak.load(std::memory_order_relaxed);
718     ALOG_ASSERT(curCount >= 0, "attemptIncWeak called on %p after underflow",
719                this);
720     while (curCount > 0) {
721         if (impl->mWeak.compare_exchange_weak(curCount, curCount+1,
722                 std::memory_order_relaxed)) {
723             break;
724         }
725         // curCount has been updated.
726     }
727 
728     if (curCount > 0) {
729         impl->addWeakRef(id);
730     }
731 
732     return curCount > 0;
733 }
734 
getWeakCount() const735 int32_t RefBase::weakref_type::getWeakCount() const
736 {
737     // Debug only!
738     return static_cast<const weakref_impl*>(this)->mWeak
739             .load(std::memory_order_relaxed);
740 }
741 
printRefs() const742 void RefBase::weakref_type::printRefs() const
743 {
744     static_cast<const weakref_impl*>(this)->printRefs();
745 }
746 
trackMe(bool enable,bool retain)747 void RefBase::weakref_type::trackMe(bool enable, bool retain)
748 {
749     static_cast<weakref_impl*>(this)->trackMe(enable, retain);
750 }
751 
createWeak(const void * id) const752 RefBase::weakref_type* RefBase::createWeak(const void* id) const
753 {
754     mRefs->incWeak(id);
755     return mRefs;
756 }
757 
getWeakRefs() const758 RefBase::weakref_type* RefBase::getWeakRefs() const
759 {
760     return mRefs;
761 }
762 
RefBase()763 RefBase::RefBase()
764     : mRefs(new weakref_impl(this))
765 {
766 }
767 
~RefBase()768 RefBase::~RefBase()
769 {
770     int32_t flags = mRefs->mFlags.load(std::memory_order_relaxed);
771     // Life-time of this object is extended to WEAK, in
772     // which case weakref_impl doesn't out-live the object and we
773     // can free it now.
774     if ((flags & OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_WEAK) {
775         // It's possible that the weak count is not 0 if the object
776         // re-acquired a weak reference in its destructor
777         if (mRefs->mWeak.load(std::memory_order_relaxed) == 0) {
778             delete mRefs;
779         }
780     } else {
781         int32_t strongs = mRefs->mStrong.load(std::memory_order_relaxed);
782 
783         if (strongs == INITIAL_STRONG_VALUE) {
784             // We never acquired a strong reference on this object.
785 
786             // It would be nice to make this fatal, but many places use RefBase on the stack.
787             // However, this is dangerous because it's also common for code to use the
788             // sp<T>(T*) constructor, assuming that if the object is around, it is already
789             // owned by an sp<>.
790             ALOGW("RefBase: Explicit destruction, weak count = %d (in %p). Use sp<> to manage this "
791                   "object.",
792                   mRefs->mWeak.load(), this);
793 
794 #if CALLSTACK_ENABLED
795             CallStack::logStack(LOG_TAG);
796 #endif
797         } else if (strongs != 0) {
798             LOG_ALWAYS_FATAL("RefBase: object %p with strong count %d deleted. Double owned?", this,
799                              strongs);
800         }
801     }
802     // For debugging purposes, clear mRefs.  Ineffective against outstanding wp's.
803     const_cast<weakref_impl*&>(mRefs) = nullptr;
804 }
805 
extendObjectLifetime(int32_t mode)806 void RefBase::extendObjectLifetime(int32_t mode)
807 {
808     check_not_on_stack(this);
809 
810     // Must be happens-before ordered with respect to construction or any
811     // operation that could destroy the object.
812     mRefs->mFlags.fetch_or(mode, std::memory_order_relaxed);
813 }
814 
onFirstRef()815 void RefBase::onFirstRef()
816 {
817 }
818 
onLastStrongRef(const void *)819 void RefBase::onLastStrongRef(const void* /*id*/)
820 {
821 }
822 
onIncStrongAttempted(uint32_t flags,const void *)823 bool RefBase::onIncStrongAttempted(uint32_t flags, const void* /*id*/)
824 {
825     return (flags&FIRST_INC_STRONG) ? true : false;
826 }
827 
onLastWeakRef(const void *)828 void RefBase::onLastWeakRef(const void* /*id*/)
829 {
830 }
831 
832 // ---------------------------------------------------------------------------
833 
834 #if DEBUG_REFS
renameRefs(size_t n,const ReferenceRenamer & renamer)835 void RefBase::renameRefs(size_t n, const ReferenceRenamer& renamer) {
836     for (size_t i=0 ; i<n ; i++) {
837         renamer(i);
838     }
839 }
840 #else
renameRefs(size_t,const ReferenceRenamer &)841 void RefBase::renameRefs(size_t /*n*/, const ReferenceRenamer& /*renamer*/) { }
842 #endif
843 
renameRefId(weakref_type * ref,const void * old_id,const void * new_id)844 void RefBase::renameRefId(weakref_type* ref,
845         const void* old_id, const void* new_id) {
846     weakref_impl* const impl = static_cast<weakref_impl*>(ref);
847     impl->renameStrongRefId(old_id, new_id);
848     impl->renameWeakRefId(old_id, new_id);
849 }
850 
renameRefId(RefBase * ref,const void * old_id,const void * new_id)851 void RefBase::renameRefId(RefBase* ref,
852         const void* old_id, const void* new_id) {
853     ref->mRefs->renameStrongRefId(old_id, new_id);
854     ref->mRefs->renameWeakRefId(old_id, new_id);
855 }
856 
857 }; // namespace android
858