2 * Copyright (C) 2005 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #define LOG_TAG "RefBase"
19 #include <utils/RefBase.h>
21 #include <utils/Atomic.h>
22 #include <utils/CallStack.h>
23 #include <utils/Log.h>
24 #include <utils/threads.h>
25 #include <utils/TextOutput.h>
30 #include <sys/types.h>
35 // compile with refcounting debugging enabled
37 #define DEBUG_REFS_FATAL_SANITY_CHECKS 0
38 #define DEBUG_REFS_ENABLED_BY_DEFAULT 1
39 #define DEBUG_REFS_CALLSTACK_ENABLED 1
41 // log all reference counting operations
44 // ---------------------------------------------------------------------------
48 #define INITIAL_STRONG_VALUE (1<<28)
50 // ---------------------------------------------------------------------------
52 RefBase::Destroyer::~Destroyer() {
55 // ---------------------------------------------------------------------------
57 class RefBase::weakref_impl : public RefBase::weakref_type
60 volatile int32_t mStrong;
61 volatile int32_t mWeak;
63 volatile int32_t mFlags;
64 Destroyer* mDestroyer;
68 weakref_impl(RefBase* base)
69 : mStrong(INITIAL_STRONG_VALUE)
77 void addStrongRef(const void* /*id*/) { }
78 void removeStrongRef(const void* /*id*/) { }
79 void renameStrongRefId(const void* /*old_id*/, const void* /*new_id*/) { }
80 void addWeakRef(const void* /*id*/) { }
81 void removeWeakRef(const void* /*id*/) { }
82 void renameWeakRefId(const void* /*old_id*/, const void* /*new_id*/) { }
83 void printRefs() const { }
84 void trackMe(bool, bool) { }
88 weakref_impl(RefBase* base)
89 : mStrong(INITIAL_STRONG_VALUE)
95 , mTrackEnabled(!!DEBUG_REFS_ENABLED_BY_DEFAULT)
102 bool dumpStack = false;
103 if (!mRetain && mStrongRefs != NULL) {
105 #if DEBUG_REFS_FATAL_SANITY_CHECKS
106 LOG_ALWAYS_FATAL("Strong references remain!");
108 LOGE("Strong references remain:");
110 ref_entry* refs = mStrongRefs;
112 char inc = refs->ref >= 0 ? '+' : '-';
113 LOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
114 #if DEBUG_REFS_CALLSTACK_ENABLED
121 if (!mRetain && mWeakRefs != NULL) {
123 #if DEBUG_REFS_FATAL_SANITY_CHECKS
124 LOG_ALWAYS_FATAL("Weak references remain:");
126 LOGE("Weak references remain!");
128 ref_entry* refs = mWeakRefs;
130 char inc = refs->ref >= 0 ? '+' : '-';
131 LOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
132 #if DEBUG_REFS_CALLSTACK_ENABLED
139 LOGE("above errors at:");
146 void addStrongRef(const void* id) {
147 //LOGD_IF(mTrackEnabled,
148 // "addStrongRef: RefBase=%p, id=%p", mBase, id);
149 addRef(&mStrongRefs, id, mStrong);
152 void removeStrongRef(const void* id) {
153 //LOGD_IF(mTrackEnabled,
154 // "removeStrongRef: RefBase=%p, id=%p", mBase, id);
156 removeRef(&mStrongRefs, id);
158 addRef(&mStrongRefs, id, -mStrong);
162 void renameStrongRefId(const void* old_id, const void* new_id) {
163 //LOGD_IF(mTrackEnabled,
164 // "renameStrongRefId: RefBase=%p, oid=%p, nid=%p",
165 // mBase, old_id, new_id);
166 renameRefsId(mStrongRefs, old_id, new_id);
169 void addWeakRef(const void* id) {
170 addRef(&mWeakRefs, id, mWeak);
173 void removeWeakRef(const void* id) {
175 removeRef(&mWeakRefs, id);
177 addRef(&mWeakRefs, id, -mWeak);
181 void renameWeakRefId(const void* old_id, const void* new_id) {
182 renameRefsId(mWeakRefs, old_id, new_id);
185 void trackMe(bool track, bool retain)
187 mTrackEnabled = track;
191 void printRefs() const
196 Mutex::Autolock _l(const_cast<weakref_impl*>(this)->mMutex);
198 sprintf(buf, "Strong references on RefBase %p (weakref_type %p):\n", mBase, this);
200 printRefsLocked(&text, mStrongRefs);
201 sprintf(buf, "Weak references on RefBase %p (weakref_type %p):\n", mBase, this);
203 printRefsLocked(&text, mWeakRefs);
208 snprintf(name, 100, "/data/%p.stack", this);
209 int rc = open(name, O_RDWR | O_CREAT | O_APPEND);
211 write(rc, text.string(), text.length());
213 LOGD("STACK TRACE for %p saved in %s", this, name);
215 else LOGE("FAILED TO PRINT STACK TRACE for %p in %s: %s", this,
216 name, strerror(errno));
225 #if DEBUG_REFS_CALLSTACK_ENABLED
231 void addRef(ref_entry** refs, const void* id, int32_t mRef)
234 AutoMutex _l(mMutex);
236 ref_entry* ref = new ref_entry;
237 // Reference count at the time of the snapshot, but before the
238 // update. Positive value means we increment, negative--we
239 // decrement the reference count.
242 #if DEBUG_REFS_CALLSTACK_ENABLED
243 ref->stack.update(2);
250 void removeRef(ref_entry** refs, const void* id)
253 AutoMutex _l(mMutex);
255 ref_entry* const head = *refs;
256 ref_entry* ref = head;
257 while (ref != NULL) {
267 #if DEBUG_REFS_FATAL_SANITY_CHECKS
268 LOG_ALWAYS_FATAL("RefBase: removing id %p on RefBase %p"
269 "(weakref_type %p) that doesn't exist!",
273 LOGE("RefBase: removing id %p on RefBase %p"
274 "(weakref_type %p) that doesn't exist!",
279 char inc = ref->ref >= 0 ? '+' : '-';
280 LOGD("\t%c ID %p (ref %d):", inc, ref->id, ref->ref);
290 void renameRefsId(ref_entry* r, const void* old_id, const void* new_id)
293 AutoMutex _l(mMutex);
295 while (ref != NULL) {
296 if (ref->id == old_id) {
304 void printRefsLocked(String8* out, const ref_entry* refs) const
308 char inc = refs->ref >= 0 ? '+' : '-';
309 sprintf(buf, "\t%c ID %p (ref %d):\n",
310 inc, refs->id, refs->ref);
312 #if DEBUG_REFS_CALLSTACK_ENABLED
313 out->append(refs->stack.toString("\t\t"));
315 out->append("\t\t(call stacks disabled)");
322 ref_entry* mStrongRefs;
323 ref_entry* mWeakRefs;
326 // Collect stack traces on addref and removeref, instead of deleting the stack references
327 // on removeref that match the address ones.
333 // ---------------------------------------------------------------------------
335 void RefBase::incStrong(const void* id) const
337 weakref_impl* const refs = mRefs;
340 refs->addStrongRef(id);
341 const int32_t c = android_atomic_inc(&refs->mStrong);
342 LOG_ASSERT(c > 0, "incStrong() called on %p after last strong ref", refs);
344 LOGD("incStrong of %p from %p: cnt=%d\n", this, id, c);
346 if (c != INITIAL_STRONG_VALUE) {
350 android_atomic_add(-INITIAL_STRONG_VALUE, &refs->mStrong);
351 const_cast<RefBase*>(this)->onFirstRef();
354 void RefBase::decStrong(const void* id) const
356 weakref_impl* const refs = mRefs;
357 refs->removeStrongRef(id);
358 const int32_t c = android_atomic_dec(&refs->mStrong);
360 LOGD("decStrong of %p from %p: cnt=%d\n", this, id, c);
362 LOG_ASSERT(c >= 1, "decStrong() called on %p too many times", refs);
364 const_cast<RefBase*>(this)->onLastStrongRef(id);
365 if ((refs->mFlags&OBJECT_LIFETIME_WEAK) != OBJECT_LIFETIME_WEAK) {
366 if (refs->mDestroyer) {
367 refs->mDestroyer->destroy(this);
376 void RefBase::forceIncStrong(const void* id) const
378 weakref_impl* const refs = mRefs;
381 refs->addStrongRef(id);
382 const int32_t c = android_atomic_inc(&refs->mStrong);
383 LOG_ASSERT(c >= 0, "forceIncStrong called on %p after ref count underflow",
386 LOGD("forceIncStrong of %p from %p: cnt=%d\n", this, id, c);
390 case INITIAL_STRONG_VALUE:
391 android_atomic_add(-INITIAL_STRONG_VALUE, &refs->mStrong);
394 const_cast<RefBase*>(this)->onFirstRef();
398 int32_t RefBase::getStrongCount() const
400 return mRefs->mStrong;
403 void RefBase::setDestroyer(RefBase::Destroyer* destroyer) {
404 mRefs->mDestroyer = destroyer;
407 RefBase* RefBase::weakref_type::refBase() const
409 return static_cast<const weakref_impl*>(this)->mBase;
412 void RefBase::weakref_type::incWeak(const void* id)
414 weakref_impl* const impl = static_cast<weakref_impl*>(this);
415 impl->addWeakRef(id);
416 const int32_t c = android_atomic_inc(&impl->mWeak);
417 LOG_ASSERT(c >= 0, "incWeak called on %p after last weak ref", this);
420 void RefBase::weakref_type::decWeak(const void* id)
422 weakref_impl* const impl = static_cast<weakref_impl*>(this);
423 impl->removeWeakRef(id);
424 const int32_t c = android_atomic_dec(&impl->mWeak);
425 LOG_ASSERT(c >= 1, "decWeak called on %p too many times", this);
428 if ((impl->mFlags&OBJECT_LIFETIME_WEAK) != OBJECT_LIFETIME_WEAK) {
429 if (impl->mStrong == INITIAL_STRONG_VALUE) {
431 if (impl->mDestroyer) {
432 impl->mDestroyer->destroy(impl->mBase);
438 // LOGV("Freeing refs %p of old RefBase %p\n", this, impl->mBase);
442 impl->mBase->onLastWeakRef(id);
443 if ((impl->mFlags&OBJECT_LIFETIME_FOREVER) != OBJECT_LIFETIME_FOREVER) {
445 if (impl->mDestroyer) {
446 impl->mDestroyer->destroy(impl->mBase);
455 bool RefBase::weakref_type::attemptIncStrong(const void* id)
459 weakref_impl* const impl = static_cast<weakref_impl*>(this);
461 int32_t curCount = impl->mStrong;
462 LOG_ASSERT(curCount >= 0, "attemptIncStrong called on %p after underflow",
464 while (curCount > 0 && curCount != INITIAL_STRONG_VALUE) {
465 if (android_atomic_cmpxchg(curCount, curCount+1, &impl->mStrong) == 0) {
468 curCount = impl->mStrong;
471 if (curCount <= 0 || curCount == INITIAL_STRONG_VALUE) {
473 if (curCount == INITIAL_STRONG_VALUE) {
474 // Attempting to acquire first strong reference... this is allowed
475 // if the object does NOT have a longer lifetime (meaning the
476 // implementation doesn't need to see this), or if the implementation
477 // allows it to happen.
478 allow = (impl->mFlags&OBJECT_LIFETIME_WEAK) != OBJECT_LIFETIME_WEAK
479 || impl->mBase->onIncStrongAttempted(FIRST_INC_STRONG, id);
481 // Attempting to revive the object... this is allowed
482 // if the object DOES have a longer lifetime (so we can safely
483 // call the object with only a weak ref) and the implementation
484 // allows it to happen.
485 allow = (impl->mFlags&OBJECT_LIFETIME_WEAK) == OBJECT_LIFETIME_WEAK
486 && impl->mBase->onIncStrongAttempted(FIRST_INC_STRONG, id);
492 curCount = android_atomic_inc(&impl->mStrong);
494 // If the strong reference count has already been incremented by
495 // someone else, the implementor of onIncStrongAttempted() is holding
496 // an unneeded reference. So call onLastStrongRef() here to remove it.
497 // (No, this is not pretty.) Note that we MUST NOT do this if we
498 // are in fact acquiring the first reference.
499 if (curCount > 0 && curCount < INITIAL_STRONG_VALUE) {
500 impl->mBase->onLastStrongRef(id);
504 impl->addStrongRef(id);
507 LOGD("attemptIncStrong of %p from %p: cnt=%d\n", this, id, curCount);
510 if (curCount == INITIAL_STRONG_VALUE) {
511 android_atomic_add(-INITIAL_STRONG_VALUE, &impl->mStrong);
512 impl->mBase->onFirstRef();
518 bool RefBase::weakref_type::attemptIncWeak(const void* id)
520 weakref_impl* const impl = static_cast<weakref_impl*>(this);
522 int32_t curCount = impl->mWeak;
523 LOG_ASSERT(curCount >= 0, "attemptIncWeak called on %p after underflow",
525 while (curCount > 0) {
526 if (android_atomic_cmpxchg(curCount, curCount+1, &impl->mWeak) == 0) {
529 curCount = impl->mWeak;
533 impl->addWeakRef(id);
539 int32_t RefBase::weakref_type::getWeakCount() const
541 return static_cast<const weakref_impl*>(this)->mWeak;
544 void RefBase::weakref_type::printRefs() const
546 static_cast<const weakref_impl*>(this)->printRefs();
549 void RefBase::weakref_type::trackMe(bool enable, bool retain)
551 static_cast<const weakref_impl*>(this)->trackMe(enable, retain);
554 RefBase::weakref_type* RefBase::createWeak(const void* id) const
560 RefBase::weakref_type* RefBase::getWeakRefs() const
566 : mRefs(new weakref_impl(this))
572 if ((mRefs->mFlags & OBJECT_LIFETIME_WEAK) == OBJECT_LIFETIME_WEAK) {
573 if (mRefs->mWeak == 0) {
579 void RefBase::extendObjectLifetime(int32_t mode)
581 android_atomic_or(mode, &mRefs->mFlags);
584 void RefBase::onFirstRef()
588 void RefBase::onLastStrongRef(const void* /*id*/)
592 bool RefBase::onIncStrongAttempted(uint32_t flags, const void* id)
594 return (flags&FIRST_INC_STRONG) ? true : false;
597 void RefBase::onLastWeakRef(const void* /*id*/)
601 // ---------------------------------------------------------------------------
603 void RefBase::moveReferences(void* dst, void const* src, size_t n,
604 const ReferenceConverterBase& caster)
607 const size_t itemSize = caster.getReferenceTypeSize();
608 for (size_t i=0 ; i<n ; i++) {
609 void* d = reinterpret_cast<void *>(intptr_t(dst) + i*itemSize);
610 void const* s = reinterpret_cast<void const*>(intptr_t(src) + i*itemSize);
611 RefBase* ref(reinterpret_cast<RefBase*>(caster.getReferenceBase(d)));
612 ref->mRefs->renameStrongRefId(s, d);
613 ref->mRefs->renameWeakRefId(s, d);
618 // ---------------------------------------------------------------------------
620 TextOutput& printStrongPointer(TextOutput& to, const void* val)
622 to << "sp<>(" << val << ")";
626 TextOutput& printWeakPointer(TextOutput& to, const void* val)
628 to << "wp<>(" << val << ")";
633 }; // namespace android