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;
62
weakref_impl(RefBase* base)
63
: mStrong(INITIAL_STRONG_VALUE)
70
void addStrongRef(const void* /*id*/) { }
71
void removeStrongRef(const void* /*id*/) { }
72
void renameStrongRefId(const void* /*old_id*/, const void* /*new_id*/) { }
73
void addWeakRef(const void* /*id*/) { }
74
void removeWeakRef(const void* /*id*/) { }
75
void renameWeakRefId(const void* /*old_id*/, const void* /*new_id*/) { }
76
void printRefs() const { }
77
void trackMe(bool, bool) { }
81
weakref_impl(RefBase* base)
82
: mStrong(INITIAL_STRONG_VALUE)
88
, mTrackEnabled(!!DEBUG_REFS_ENABLED_BY_DEFAULT)
95
bool dumpStack = false;
96
if (!mRetain && mStrongRefs != NULL) {
98
#if DEBUG_REFS_FATAL_SANITY_CHECKS
99
LOG_ALWAYS_FATAL("Strong references remain!");
101
ALOGE("Strong references remain:");
103
ref_entry* refs = mStrongRefs;
105
char inc = refs->ref >= 0 ? '+' : '-';
106
ALOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
107
#if DEBUG_REFS_CALLSTACK_ENABLED
114
if (!mRetain && mWeakRefs != NULL) {
116
#if DEBUG_REFS_FATAL_SANITY_CHECKS
117
LOG_ALWAYS_FATAL("Weak references remain:");
119
ALOGE("Weak references remain!");
121
ref_entry* refs = mWeakRefs;
123
char inc = refs->ref >= 0 ? '+' : '-';
124
ALOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
125
#if DEBUG_REFS_CALLSTACK_ENABLED
132
ALOGE("above errors at:");
139
void addStrongRef(const void* id) {
140
//ALOGD_IF(mTrackEnabled,
141
// "addStrongRef: RefBase=%p, id=%p", mBase, id);
142
addRef(&mStrongRefs, id, mStrong);
145
void removeStrongRef(const void* id) {
146
//ALOGD_IF(mTrackEnabled,
147
// "removeStrongRef: RefBase=%p, id=%p", mBase, id);
149
removeRef(&mStrongRefs, id);
151
addRef(&mStrongRefs, id, -mStrong);
155
void renameStrongRefId(const void* old_id, const void* new_id) {
156
//ALOGD_IF(mTrackEnabled,
157
// "renameStrongRefId: RefBase=%p, oid=%p, nid=%p",
158
// mBase, old_id, new_id);
159
renameRefsId(mStrongRefs, old_id, new_id);
162
void addWeakRef(const void* id) {
163
addRef(&mWeakRefs, id, mWeak);
166
void removeWeakRef(const void* id) {
168
removeRef(&mWeakRefs, id);
170
addRef(&mWeakRefs, id, -mWeak);
174
void renameWeakRefId(const void* old_id, const void* new_id) {
175
renameRefsId(mWeakRefs, old_id, new_id);
178
void trackMe(bool track, bool retain)
180
mTrackEnabled = track;
184
void printRefs() const
189
Mutex::Autolock _l(mMutex);
191
sprintf(buf, "Strong references on RefBase %p (weakref_type %p):\n", mBase, this);
193
printRefsLocked(&text, mStrongRefs);
194
sprintf(buf, "Weak references on RefBase %p (weakref_type %p):\n", mBase, this);
196
printRefsLocked(&text, mWeakRefs);
201
snprintf(name, 100, "/data/%p.stack", this);
202
int rc = open(name, O_RDWR | O_CREAT | O_APPEND);
204
write(rc, text.string(), text.length());
206
ALOGD("STACK TRACE for %p saved in %s", this, name);
208
else ALOGE("FAILED TO PRINT STACK TRACE for %p in %s: %s", this,
209
name, strerror(errno));
218
#if DEBUG_REFS_CALLSTACK_ENABLED
224
void addRef(ref_entry** refs, const void* id, int32_t mRef)
227
AutoMutex _l(mMutex);
229
ref_entry* ref = new ref_entry;
230
// Reference count at the time of the snapshot, but before the
231
// update. Positive value means we increment, negative--we
232
// decrement the reference count.
235
#if DEBUG_REFS_CALLSTACK_ENABLED
236
ref->stack.update(2);
243
void removeRef(ref_entry** refs, const void* id)
246
AutoMutex _l(mMutex);
248
ref_entry* const head = *refs;
249
ref_entry* ref = head;
250
while (ref != NULL) {
260
#if DEBUG_REFS_FATAL_SANITY_CHECKS
261
LOG_ALWAYS_FATAL("RefBase: removing id %p on RefBase %p"
262
"(weakref_type %p) that doesn't exist!",
266
ALOGE("RefBase: removing id %p on RefBase %p"
267
"(weakref_type %p) that doesn't exist!",
272
char inc = ref->ref >= 0 ? '+' : '-';
273
ALOGD("\t%c ID %p (ref %d):", inc, ref->id, ref->ref);
283
void renameRefsId(ref_entry* r, const void* old_id, const void* new_id)
286
AutoMutex _l(mMutex);
288
while (ref != NULL) {
289
if (ref->id == old_id) {
297
void printRefsLocked(String8* out, const ref_entry* refs) const
301
char inc = refs->ref >= 0 ? '+' : '-';
302
sprintf(buf, "\t%c ID %p (ref %d):\n",
303
inc, refs->id, refs->ref);
305
#if DEBUG_REFS_CALLSTACK_ENABLED
306
out->append(refs->stack.toString("\t\t"));
308
out->append("\t\t(call stacks disabled)");
314
mutable Mutex mMutex;
315
ref_entry* mStrongRefs;
316
ref_entry* mWeakRefs;
319
// Collect stack traces on addref and removeref, instead of deleting the stack references
320
// on removeref that match the address ones.
326
// ---------------------------------------------------------------------------
328
void RefBase::incStrong(const void* id) const
330
weakref_impl* const refs = mRefs;
333
refs->addStrongRef(id);
334
const int32_t c = android_atomic_inc(&refs->mStrong);
335
ALOG_ASSERT(c > 0, "incStrong() called on %p after last strong ref", refs);
337
ALOGD("incStrong of %p from %p: cnt=%d\n", this, id, c);
339
if (c != INITIAL_STRONG_VALUE) {
343
android_atomic_add(-INITIAL_STRONG_VALUE, &refs->mStrong);
344
refs->mBase->onFirstRef();
347
void RefBase::decStrong(const void* id) const
349
weakref_impl* const refs = mRefs;
350
refs->removeStrongRef(id);
351
const int32_t c = android_atomic_dec(&refs->mStrong);
353
ALOGD("decStrong of %p from %p: cnt=%d\n", this, id, c);
355
ALOG_ASSERT(c >= 1, "decStrong() called on %p too many times", refs);
357
refs->mBase->onLastStrongRef(id);
358
if ((refs->mFlags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
365
void RefBase::forceIncStrong(const void* id) const
367
weakref_impl* const refs = mRefs;
370
refs->addStrongRef(id);
371
const int32_t c = android_atomic_inc(&refs->mStrong);
372
ALOG_ASSERT(c >= 0, "forceIncStrong called on %p after ref count underflow",
375
ALOGD("forceIncStrong of %p from %p: cnt=%d\n", this, id, c);
379
case INITIAL_STRONG_VALUE:
380
android_atomic_add(-INITIAL_STRONG_VALUE, &refs->mStrong);
383
refs->mBase->onFirstRef();
387
int32_t RefBase::getStrongCount() const
389
return mRefs->mStrong;
392
RefBase* RefBase::weakref_type::refBase() const
394
return static_cast<const weakref_impl*>(this)->mBase;
397
void RefBase::weakref_type::incWeak(const void* id)
399
weakref_impl* const impl = static_cast<weakref_impl*>(this);
400
impl->addWeakRef(id);
401
const int32_t c = android_atomic_inc(&impl->mWeak);
402
ALOG_ASSERT(c >= 0, "incWeak called on %p after last weak ref", this);
406
void RefBase::weakref_type::decWeak(const void* id)
408
weakref_impl* const impl = static_cast<weakref_impl*>(this);
409
impl->removeWeakRef(id);
410
const int32_t c = android_atomic_dec(&impl->mWeak);
411
ALOG_ASSERT(c >= 1, "decWeak called on %p too many times", this);
414
if ((impl->mFlags&OBJECT_LIFETIME_WEAK) == OBJECT_LIFETIME_STRONG) {
415
// This is the regular lifetime case. The object is destroyed
416
// when the last strong reference goes away. Since weakref_impl
417
// outlive the object, it is not destroyed in the dtor, and
418
// we'll have to do it here.
419
if (impl->mStrong == INITIAL_STRONG_VALUE) {
420
// Special case: we never had a strong reference, so we need to
421
// destroy the object now.
424
// ALOGV("Freeing refs %p of old RefBase %p\n", this, impl->mBase);
428
// less common case: lifetime is OBJECT_LIFETIME_{WEAK|FOREVER}
429
impl->mBase->onLastWeakRef(id);
430
if ((impl->mFlags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_WEAK) {
431
// this is the OBJECT_LIFETIME_WEAK case. The last weak-reference
432
// is gone, we can destroy the object.
438
bool RefBase::weakref_type::attemptIncStrong(const void* id)
442
weakref_impl* const impl = static_cast<weakref_impl*>(this);
444
int32_t curCount = impl->mStrong;
445
ALOG_ASSERT(curCount >= 0, "attemptIncStrong called on %p after underflow",
447
while (curCount > 0 && curCount != INITIAL_STRONG_VALUE) {
448
if (android_atomic_cmpxchg(curCount, curCount+1, &impl->mStrong) == 0) {
451
curCount = impl->mStrong;
454
if (curCount <= 0 || curCount == INITIAL_STRONG_VALUE) {
456
if (curCount == INITIAL_STRONG_VALUE) {
457
// Attempting to acquire first strong reference... this is allowed
458
// if the object does NOT have a longer lifetime (meaning the
459
// implementation doesn't need to see this), or if 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);
464
// Attempting to revive the object... this is allowed
465
// if the object DOES have a longer lifetime (so we can safely
466
// call the object with only a weak ref) and the implementation
467
// allows it to happen.
468
allow = (impl->mFlags&OBJECT_LIFETIME_WEAK) == OBJECT_LIFETIME_WEAK
469
&& impl->mBase->onIncStrongAttempted(FIRST_INC_STRONG, id);
475
curCount = android_atomic_inc(&impl->mStrong);
477
// If the strong reference count has already been incremented by
478
// someone else, the implementor of onIncStrongAttempted() is holding
479
// an unneeded reference. So call onLastStrongRef() here to remove it.
480
// (No, this is not pretty.) Note that we MUST NOT do this if we
481
// are in fact acquiring the first reference.
482
if (curCount > 0 && curCount < INITIAL_STRONG_VALUE) {
483
impl->mBase->onLastStrongRef(id);
487
impl->addStrongRef(id);
490
ALOGD("attemptIncStrong of %p from %p: cnt=%d\n", this, id, curCount);
493
if (curCount == INITIAL_STRONG_VALUE) {
494
android_atomic_add(-INITIAL_STRONG_VALUE, &impl->mStrong);
495
impl->mBase->onFirstRef();
501
bool RefBase::weakref_type::attemptIncWeak(const void* id)
503
weakref_impl* const impl = static_cast<weakref_impl*>(this);
505
int32_t curCount = impl->mWeak;
506
ALOG_ASSERT(curCount >= 0, "attemptIncWeak called on %p after underflow",
508
while (curCount > 0) {
509
if (android_atomic_cmpxchg(curCount, curCount+1, &impl->mWeak) == 0) {
512
curCount = impl->mWeak;
516
impl->addWeakRef(id);
522
int32_t RefBase::weakref_type::getWeakCount() const
524
return static_cast<const weakref_impl*>(this)->mWeak;
527
void RefBase::weakref_type::printRefs() const
529
static_cast<const weakref_impl*>(this)->printRefs();
532
void RefBase::weakref_type::trackMe(bool enable, bool retain)
534
static_cast<weakref_impl*>(this)->trackMe(enable, retain);
537
RefBase::weakref_type* RefBase::createWeak(const void* id) const
543
RefBase::weakref_type* RefBase::getWeakRefs() const
549
: mRefs(new weakref_impl(this))
555
if (mRefs->mStrong == INITIAL_STRONG_VALUE) {
556
// we never acquired a strong (and/or weak) reference on this object.
559
// life-time of this object is extended to WEAK or FOREVER, in
560
// which case weakref_impl doesn't out-live the object and we
562
if ((mRefs->mFlags & OBJECT_LIFETIME_MASK) != OBJECT_LIFETIME_STRONG) {
563
// It's possible that the weak count is not 0 if the object
564
// re-acquired a weak reference in its destructor
565
if (mRefs->mWeak == 0) {
570
// for debugging purposes, clear this.
571
const_cast<weakref_impl*&>(mRefs) = NULL;
574
void RefBase::extendObjectLifetime(int32_t mode)
576
android_atomic_or(mode, &mRefs->mFlags);
579
void RefBase::onFirstRef()
583
void RefBase::onLastStrongRef(const void* /*id*/)
587
bool RefBase::onIncStrongAttempted(uint32_t flags, const void* id)
589
return (flags&FIRST_INC_STRONG) ? true : false;
592
void RefBase::onLastWeakRef(const void* /*id*/)
596
// ---------------------------------------------------------------------------
598
void RefBase::moveReferences(void* dst, void const* src, size_t n,
599
const ReferenceConverterBase& caster)
602
const size_t itemSize = caster.getReferenceTypeSize();
603
for (size_t i=0 ; i<n ; i++) {
604
void* d = reinterpret_cast<void *>(intptr_t(dst) + i*itemSize);
605
void const* s = reinterpret_cast<void const*>(intptr_t(src) + i*itemSize);
606
RefBase* ref(reinterpret_cast<RefBase*>(caster.getReferenceBase(d)));
607
ref->mRefs->renameStrongRefId(s, d);
608
ref->mRefs->renameWeakRefId(s, d);
613
// ---------------------------------------------------------------------------
615
TextOutput& printStrongPointer(TextOutput& to, const void* val)
617
to << "sp<>(" << val << ")";
621
TextOutput& printWeakPointer(TextOutput& to, const void* val)
623
to << "wp<>(" << val << ")";
628
}; // namespace android