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 class RefBase::weakref_impl : public RefBase::weakref_type
55 volatile int32_t mStrong;
56 volatile int32_t mWeak;
58 volatile int32_t mFlags;
63 weakref_impl(RefBase* base)
64 : mStrong(INITIAL_STRONG_VALUE)
71 void addStrongRef(const void* /*id*/) { }
72 void removeStrongRef(const void* /*id*/) { }
73 void renameStrongRefId(const void* /*old_id*/, const void* /*new_id*/) { }
74 void addWeakRef(const void* /*id*/) { }
75 void removeWeakRef(const void* /*id*/) { }
76 void renameWeakRefId(const void* /*old_id*/, const void* /*new_id*/) { }
77 void printRefs() const { }
78 void trackMe(bool, bool) { }
82 weakref_impl(RefBase* base)
83 : mStrong(INITIAL_STRONG_VALUE)
89 , mTrackEnabled(!!DEBUG_REFS_ENABLED_BY_DEFAULT)
96 bool dumpStack = false;
97 if (!mRetain && mStrongRefs != NULL) {
99 #if DEBUG_REFS_FATAL_SANITY_CHECKS
100 LOG_ALWAYS_FATAL("Strong references remain!");
102 LOGE("Strong references remain:");
104 ref_entry* refs = mStrongRefs;
106 char inc = refs->ref >= 0 ? '+' : '-';
107 LOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
108 #if DEBUG_REFS_CALLSTACK_ENABLED
115 if (!mRetain && mWeakRefs != NULL) {
117 #if DEBUG_REFS_FATAL_SANITY_CHECKS
118 LOG_ALWAYS_FATAL("Weak references remain:");
120 LOGE("Weak references remain!");
122 ref_entry* refs = mWeakRefs;
124 char inc = refs->ref >= 0 ? '+' : '-';
125 LOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
126 #if DEBUG_REFS_CALLSTACK_ENABLED
133 LOGE("above errors at:");
140 void addStrongRef(const void* id) {
141 //LOGD_IF(mTrackEnabled,
142 // "addStrongRef: RefBase=%p, id=%p", mBase, id);
143 addRef(&mStrongRefs, id, mStrong);
146 void removeStrongRef(const void* id) {
147 //LOGD_IF(mTrackEnabled,
148 // "removeStrongRef: RefBase=%p, id=%p", mBase, id);
150 removeRef(&mStrongRefs, id);
152 addRef(&mStrongRefs, id, -mStrong);
156 void renameStrongRefId(const void* old_id, const void* new_id) {
157 //LOGD_IF(mTrackEnabled,
158 // "renameStrongRefId: RefBase=%p, oid=%p, nid=%p",
159 // mBase, old_id, new_id);
160 renameRefsId(mStrongRefs, old_id, new_id);
163 void addWeakRef(const void* id) {
164 addRef(&mWeakRefs, id, mWeak);
167 void removeWeakRef(const void* id) {
169 removeRef(&mWeakRefs, id);
171 addRef(&mWeakRefs, id, -mWeak);
175 void renameWeakRefId(const void* old_id, const void* new_id) {
176 renameRefsId(mWeakRefs, old_id, new_id);
179 void trackMe(bool track, bool retain)
181 mTrackEnabled = track;
185 void printRefs() const
190 Mutex::Autolock _l(const_cast<weakref_impl*>(this)->mMutex);
192 sprintf(buf, "Strong references on RefBase %p (weakref_type %p):\n", mBase, this);
194 printRefsLocked(&text, mStrongRefs);
195 sprintf(buf, "Weak references on RefBase %p (weakref_type %p):\n", mBase, this);
197 printRefsLocked(&text, mWeakRefs);
202 snprintf(name, 100, "/data/%p.stack", this);
203 int rc = open(name, O_RDWR | O_CREAT | O_APPEND);
205 write(rc, text.string(), text.length());
207 LOGD("STACK TRACE for %p saved in %s", this, name);
209 else LOGE("FAILED TO PRINT STACK TRACE for %p in %s: %s", this,
210 name, strerror(errno));
219 #if DEBUG_REFS_CALLSTACK_ENABLED
225 void addRef(ref_entry** refs, const void* id, int32_t mRef)
228 AutoMutex _l(mMutex);
230 ref_entry* ref = new ref_entry;
231 // Reference count at the time of the snapshot, but before the
232 // update. Positive value means we increment, negative--we
233 // decrement the reference count.
236 #if DEBUG_REFS_CALLSTACK_ENABLED
237 ref->stack.update(2);
244 void removeRef(ref_entry** refs, const void* id)
247 AutoMutex _l(mMutex);
249 ref_entry* const head = *refs;
250 ref_entry* ref = head;
251 while (ref != NULL) {
261 #if DEBUG_REFS_FATAL_SANITY_CHECKS
262 LOG_ALWAYS_FATAL("RefBase: removing id %p on RefBase %p"
263 "(weakref_type %p) that doesn't exist!",
267 LOGE("RefBase: removing id %p on RefBase %p"
268 "(weakref_type %p) that doesn't exist!",
273 char inc = ref->ref >= 0 ? '+' : '-';
274 LOGD("\t%c ID %p (ref %d):", inc, ref->id, ref->ref);
284 void renameRefsId(ref_entry* r, const void* old_id, const void* new_id)
287 AutoMutex _l(mMutex);
289 while (ref != NULL) {
290 if (ref->id == old_id) {
298 void printRefsLocked(String8* out, const ref_entry* refs) const
302 char inc = refs->ref >= 0 ? '+' : '-';
303 sprintf(buf, "\t%c ID %p (ref %d):\n",
304 inc, refs->id, refs->ref);
306 #if DEBUG_REFS_CALLSTACK_ENABLED
307 out->append(refs->stack.toString("\t\t"));
309 out->append("\t\t(call stacks disabled)");
316 ref_entry* mStrongRefs;
317 ref_entry* mWeakRefs;
320 // Collect stack traces on addref and removeref, instead of deleting the stack references
321 // on removeref that match the address ones.
327 // ---------------------------------------------------------------------------
329 void RefBase::incStrong(const void* id) const
331 weakref_impl* const refs = mRefs;
334 refs->addStrongRef(id);
335 const int32_t c = android_atomic_inc(&refs->mStrong);
336 LOG_ASSERT(c > 0, "incStrong() called on %p after last strong ref", refs);
338 LOGD("incStrong of %p from %p: cnt=%d\n", this, id, c);
340 if (c != INITIAL_STRONG_VALUE) {
344 android_atomic_add(-INITIAL_STRONG_VALUE, &refs->mStrong);
345 const_cast<RefBase*>(this)->onFirstRef();
348 void RefBase::decStrong(const void* id) const
350 weakref_impl* const refs = mRefs;
351 refs->removeStrongRef(id);
352 const int32_t c = android_atomic_dec(&refs->mStrong);
354 LOGD("decStrong of %p from %p: cnt=%d\n", this, id, c);
356 LOG_ASSERT(c >= 1, "decStrong() called on %p too many times", refs);
358 const_cast<RefBase*>(this)->onLastStrongRef(id);
359 if ((refs->mFlags&OBJECT_LIFETIME_WEAK) != OBJECT_LIFETIME_WEAK) {
366 void RefBase::forceIncStrong(const void* id) const
368 weakref_impl* const refs = mRefs;
371 refs->addStrongRef(id);
372 const int32_t c = android_atomic_inc(&refs->mStrong);
373 LOG_ASSERT(c >= 0, "forceIncStrong called on %p after ref count underflow",
376 LOGD("forceIncStrong of %p from %p: cnt=%d\n", this, id, c);
380 case INITIAL_STRONG_VALUE:
381 android_atomic_add(-INITIAL_STRONG_VALUE, &refs->mStrong);
384 const_cast<RefBase*>(this)->onFirstRef();
388 int32_t RefBase::getStrongCount() const
390 return mRefs->mStrong;
395 RefBase* RefBase::weakref_type::refBase() const
397 return static_cast<const weakref_impl*>(this)->mBase;
400 void RefBase::weakref_type::incWeak(const void* id)
402 weakref_impl* const impl = static_cast<weakref_impl*>(this);
403 impl->addWeakRef(id);
404 const int32_t c = android_atomic_inc(&impl->mWeak);
405 LOG_ASSERT(c >= 0, "incWeak called on %p after last weak ref", this);
408 void RefBase::weakref_type::decWeak(const void* id)
410 weakref_impl* const impl = static_cast<weakref_impl*>(this);
411 impl->removeWeakRef(id);
412 const int32_t c = android_atomic_dec(&impl->mWeak);
413 LOG_ASSERT(c >= 1, "decWeak called on %p too many times", this);
416 if ((impl->mFlags&OBJECT_LIFETIME_WEAK) != OBJECT_LIFETIME_WEAK) {
417 if (impl->mStrong == INITIAL_STRONG_VALUE)
420 // LOGV("Freeing refs %p of old RefBase %p\n", this, impl->mBase);
424 impl->mBase->onLastWeakRef(id);
425 if ((impl->mFlags&OBJECT_LIFETIME_FOREVER) != OBJECT_LIFETIME_FOREVER) {
431 bool RefBase::weakref_type::attemptIncStrong(const void* id)
435 weakref_impl* const impl = static_cast<weakref_impl*>(this);
437 int32_t curCount = impl->mStrong;
438 LOG_ASSERT(curCount >= 0, "attemptIncStrong called on %p after underflow",
440 while (curCount > 0 && curCount != INITIAL_STRONG_VALUE) {
441 if (android_atomic_cmpxchg(curCount, curCount+1, &impl->mStrong) == 0) {
444 curCount = impl->mStrong;
447 if (curCount <= 0 || curCount == INITIAL_STRONG_VALUE) {
449 if (curCount == INITIAL_STRONG_VALUE) {
450 // Attempting to acquire first strong reference... this is allowed
451 // if the object does NOT have a longer lifetime (meaning the
452 // implementation doesn't need to see this), or if the implementation
453 // allows it to happen.
454 allow = (impl->mFlags&OBJECT_LIFETIME_WEAK) != OBJECT_LIFETIME_WEAK
455 || impl->mBase->onIncStrongAttempted(FIRST_INC_STRONG, id);
457 // Attempting to revive the object... this is allowed
458 // if the object DOES have a longer lifetime (so we can safely
459 // call the object with only a weak ref) and the implementation
460 // allows it to happen.
461 allow = (impl->mFlags&OBJECT_LIFETIME_WEAK) == OBJECT_LIFETIME_WEAK
462 && impl->mBase->onIncStrongAttempted(FIRST_INC_STRONG, id);
468 curCount = android_atomic_inc(&impl->mStrong);
470 // If the strong reference count has already been incremented by
471 // someone else, the implementor of onIncStrongAttempted() is holding
472 // an unneeded reference. So call onLastStrongRef() here to remove it.
473 // (No, this is not pretty.) Note that we MUST NOT do this if we
474 // are in fact acquiring the first reference.
475 if (curCount > 0 && curCount < INITIAL_STRONG_VALUE) {
476 impl->mBase->onLastStrongRef(id);
480 impl->addStrongRef(id);
483 LOGD("attemptIncStrong of %p from %p: cnt=%d\n", this, id, curCount);
486 if (curCount == INITIAL_STRONG_VALUE) {
487 android_atomic_add(-INITIAL_STRONG_VALUE, &impl->mStrong);
488 impl->mBase->onFirstRef();
494 bool RefBase::weakref_type::attemptIncWeak(const void* id)
496 weakref_impl* const impl = static_cast<weakref_impl*>(this);
498 int32_t curCount = impl->mWeak;
499 LOG_ASSERT(curCount >= 0, "attemptIncWeak called on %p after underflow",
501 while (curCount > 0) {
502 if (android_atomic_cmpxchg(curCount, curCount+1, &impl->mWeak) == 0) {
505 curCount = impl->mWeak;
509 impl->addWeakRef(id);
515 int32_t RefBase::weakref_type::getWeakCount() const
517 return static_cast<const weakref_impl*>(this)->mWeak;
520 void RefBase::weakref_type::printRefs() const
522 static_cast<const weakref_impl*>(this)->printRefs();
525 void RefBase::weakref_type::trackMe(bool enable, bool retain)
527 static_cast<const weakref_impl*>(this)->trackMe(enable, retain);
530 RefBase::weakref_type* RefBase::createWeak(const void* id) const
536 RefBase::weakref_type* RefBase::getWeakRefs() const
542 : mRefs(new weakref_impl(this))
548 if (mRefs->mWeak == 0) {
553 void RefBase::extendObjectLifetime(int32_t mode)
555 android_atomic_or(mode, &mRefs->mFlags);
558 void RefBase::onFirstRef()
562 void RefBase::onLastStrongRef(const void* /*id*/)
566 bool RefBase::onIncStrongAttempted(uint32_t flags, const void* id)
568 return (flags&FIRST_INC_STRONG) ? true : false;
571 void RefBase::onLastWeakRef(const void* /*id*/)
575 // ---------------------------------------------------------------------------
577 void RefBase::moveReferences(void* dst, void const* src, size_t n,
578 const ReferenceConverterBase& caster)
581 const size_t itemSize = caster.getReferenceTypeSize();
582 for (size_t i=0 ; i<n ; i++) {
583 void* d = reinterpret_cast<void *>(intptr_t(dst) + i*itemSize);
584 void const* s = reinterpret_cast<void const*>(intptr_t(src) + i*itemSize);
585 RefBase* ref(reinterpret_cast<RefBase*>(caster.getReferenceBase(d)));
586 ref->mRefs->renameStrongRefId(s, d);
587 ref->mRefs->renameWeakRefId(s, d);
592 // ---------------------------------------------------------------------------
594 TextOutput& printStrongPointer(TextOutput& to, const void* val)
596 to << "sp<>(" << val << ")";
600 TextOutput& printWeakPointer(TextOutput& to, const void* val)
602 to << "wp<>(" << val << ")";
607 }; // namespace android