blob: 1c870cf7835772aeabc956daffbab19fee1a9f5f [file] [log] [blame]
The Android Open Source Projectcbb10112009-03-03 19:31:44 -08001/*
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
19#include <utils/RefBase.h>
20
21#include <utils/Atomic.h>
22#include <utils/CallStack.h>
Mathias Agopian45711432011-06-08 16:05:30 -070023#include <utils/KeyedVector.h>
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080024#include <utils/Log.h>
25#include <utils/threads.h>
26
27#include <stdlib.h>
28#include <stdio.h>
29#include <typeinfo>
30#include <sys/types.h>
31#include <sys/stat.h>
32#include <fcntl.h>
33#include <unistd.h>
34
35// compile with refcounting debugging enabled
36#define DEBUG_REFS 0
37#define DEBUG_REFS_ENABLED_BY_DEFAULT 1
38#define DEBUG_REFS_CALLSTACK_ENABLED 1
39
40// log all reference counting operations
41#define PRINT_REFS 0
42
43// ---------------------------------------------------------------------------
44
45namespace android {
46
47#define INITIAL_STRONG_VALUE (1<<28)
48
49// ---------------------------------------------------------------------------
50
51class RefBase::weakref_impl : public RefBase::weakref_type
52{
53public:
54 volatile int32_t mStrong;
55 volatile int32_t mWeak;
56 RefBase* const mBase;
57 volatile int32_t mFlags;
58
59
60#if !DEBUG_REFS
61
62 weakref_impl(RefBase* base)
63 : mStrong(INITIAL_STRONG_VALUE)
64 , mWeak(0)
65 , mBase(base)
66 , mFlags(0)
67 {
68 }
69
70 void addStrongRef(const void* /*id*/) { }
71 void removeStrongRef(const void* /*id*/) { }
72 void addWeakRef(const void* /*id*/) { }
73 void removeWeakRef(const void* /*id*/) { }
74 void printRefs() const { }
75 void trackMe(bool, bool) { }
76
77#else
78
79 weakref_impl(RefBase* base)
80 : mStrong(INITIAL_STRONG_VALUE)
81 , mWeak(0)
82 , mBase(base)
83 , mFlags(0)
84 , mStrongRefs(NULL)
85 , mWeakRefs(NULL)
86 , mTrackEnabled(!!DEBUG_REFS_ENABLED_BY_DEFAULT)
87 , mRetain(false)
88 {
Mathias Agopian45711432011-06-08 16:05:30 -070089 //LOGI("NEW weakref_impl %p for RefBase %p", this, base);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080090 }
91
92 ~weakref_impl()
93 {
Mathias Agopian45711432011-06-08 16:05:30 -070094 LOG_ALWAYS_FATAL_IF(!mRetain && mStrongRefs != NULL, "Strong references remain!");
95 LOG_ALWAYS_FATAL_IF(!mRetain && mWeakRefs != NULL, "Weak references remain!");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080096 }
97
Mathias Agopian45711432011-06-08 16:05:30 -070098 void addStrongRef(const void* id)
99 {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800100 addRef(&mStrongRefs, id, mStrong);
101 }
102
Mathias Agopian45711432011-06-08 16:05:30 -0700103 void removeStrongRef(const void* id)
104 {
105 if (!mRetain)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800106 removeRef(&mStrongRefs, id);
Mathias Agopian45711432011-06-08 16:05:30 -0700107 else
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800108 addRef(&mStrongRefs, id, -mStrong);
109 }
110
Mathias Agopian45711432011-06-08 16:05:30 -0700111 void addWeakRef(const void* id)
112 {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800113 addRef(&mWeakRefs, id, mWeak);
114 }
115
Mathias Agopian45711432011-06-08 16:05:30 -0700116 void removeWeakRef(const void* id)
117 {
118 if (!mRetain)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800119 removeRef(&mWeakRefs, id);
Mathias Agopian45711432011-06-08 16:05:30 -0700120 else
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800121 addRef(&mWeakRefs, id, -mWeak);
122 }
123
124 void trackMe(bool track, bool retain)
125 {
126 mTrackEnabled = track;
127 mRetain = retain;
128 }
129
130 void printRefs() const
131 {
132 String8 text;
133
134 {
Mathias Agopian45711432011-06-08 16:05:30 -0700135 AutoMutex _l(const_cast<weakref_impl*>(this)->mMutex);
136
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800137 char buf[128];
138 sprintf(buf, "Strong references on RefBase %p (weakref_type %p):\n", mBase, this);
139 text.append(buf);
140 printRefsLocked(&text, mStrongRefs);
141 sprintf(buf, "Weak references on RefBase %p (weakref_type %p):\n", mBase, this);
142 text.append(buf);
143 printRefsLocked(&text, mWeakRefs);
144 }
145
146 {
147 char name[100];
148 snprintf(name, 100, "/data/%p.stack", this);
149 int rc = open(name, O_RDWR | O_CREAT | O_APPEND);
150 if (rc >= 0) {
151 write(rc, text.string(), text.length());
152 close(rc);
153 LOGD("STACK TRACE for %p saved in %s", this, name);
154 }
155 else LOGE("FAILED TO PRINT STACK TRACE for %p in %s: %s", this,
156 name, strerror(errno));
157 }
158 }
159
160private:
161 struct ref_entry
162 {
163 ref_entry* next;
164 const void* id;
165#if DEBUG_REFS_CALLSTACK_ENABLED
166 CallStack stack;
167#endif
168 int32_t ref;
169 };
170
171 void addRef(ref_entry** refs, const void* id, int32_t mRef)
172 {
173 if (mTrackEnabled) {
174 AutoMutex _l(mMutex);
175 ref_entry* ref = new ref_entry;
176 // Reference count at the time of the snapshot, but before the
177 // update. Positive value means we increment, negative--we
178 // decrement the reference count.
179 ref->ref = mRef;
180 ref->id = id;
181#if DEBUG_REFS_CALLSTACK_ENABLED
182 ref->stack.update(2);
183#endif
Mathias Agopian45711432011-06-08 16:05:30 -0700184
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800185 ref->next = *refs;
186 *refs = ref;
187 }
188 }
189
190 void removeRef(ref_entry** refs, const void* id)
191 {
192 if (mTrackEnabled) {
193 AutoMutex _l(mMutex);
194
Mathias Agopian45711432011-06-08 16:05:30 -0700195 ref_entry* ref = *refs;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800196 while (ref != NULL) {
197 if (ref->id == id) {
198 *refs = ref->next;
199 delete ref;
200 return;
201 }
Mathias Agopian45711432011-06-08 16:05:30 -0700202
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800203 refs = &ref->next;
204 ref = *refs;
205 }
Mathias Agopian45711432011-06-08 16:05:30 -0700206
207 LOG_ALWAYS_FATAL("RefBase: removing id %p on RefBase %p (weakref_type %p) that doesn't exist!",
208 id, mBase, this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800209 }
210 }
211
212 void printRefsLocked(String8* out, const ref_entry* refs) const
213 {
214 char buf[128];
215 while (refs) {
216 char inc = refs->ref >= 0 ? '+' : '-';
217 sprintf(buf, "\t%c ID %p (ref %d):\n",
218 inc, refs->id, refs->ref);
219 out->append(buf);
220#if DEBUG_REFS_CALLSTACK_ENABLED
221 out->append(refs->stack.toString("\t\t"));
222#else
223 out->append("\t\t(call stacks disabled)");
224#endif
225 refs = refs->next;
226 }
227 }
228
229 Mutex mMutex;
230 ref_entry* mStrongRefs;
231 ref_entry* mWeakRefs;
232
233 bool mTrackEnabled;
234 // Collect stack traces on addref and removeref, instead of deleting the stack references
235 // on removeref that match the address ones.
236 bool mRetain;
237
Mathias Agopian45711432011-06-08 16:05:30 -0700238#if 0
239 void addRef(KeyedVector<const void*, int32_t>* refs, const void* id)
240 {
241 AutoMutex _l(mMutex);
242 ssize_t i = refs->indexOfKey(id);
243 if (i >= 0) {
244 ++(refs->editValueAt(i));
245 } else {
246 i = refs->add(id, 1);
247 }
248 }
249
250 void removeRef(KeyedVector<const void*, int32_t>* refs, const void* id)
251 {
252 AutoMutex _l(mMutex);
253 ssize_t i = refs->indexOfKey(id);
254 LOG_ALWAYS_FATAL_IF(i < 0, "RefBase: removing id %p that doesn't exist!", id);
255 if (i >= 0) {
256 int32_t val = --(refs->editValueAt(i));
257 if (val == 0) {
258 refs->removeItemsAt(i);
259 }
260 }
261 }
262
263 void printRefs(const KeyedVector<const void*, int32_t>& refs)
264 {
265 const size_t N=refs.size();
266 for (size_t i=0; i<N; i++) {
267 printf("\tID %p: %d remain\n", refs.keyAt(i), refs.valueAt(i));
268 }
269 }
270
271 mutable Mutex mMutex;
272 KeyedVector<const void*, int32_t> mStrongRefs;
273 KeyedVector<const void*, int32_t> mWeakRefs;
274#endif
275
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800276#endif
277};
278
279// ---------------------------------------------------------------------------
280
281void RefBase::incStrong(const void* id) const
282{
283 weakref_impl* const refs = mRefs;
Mathias Agopian45711432011-06-08 16:05:30 -0700284 refs->addWeakRef(id);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800285 refs->incWeak(id);
286
287 refs->addStrongRef(id);
288 const int32_t c = android_atomic_inc(&refs->mStrong);
289 LOG_ASSERT(c > 0, "incStrong() called on %p after last strong ref", refs);
290#if PRINT_REFS
291 LOGD("incStrong of %p from %p: cnt=%d\n", this, id, c);
292#endif
293 if (c != INITIAL_STRONG_VALUE) {
294 return;
295 }
296
297 android_atomic_add(-INITIAL_STRONG_VALUE, &refs->mStrong);
298 const_cast<RefBase*>(this)->onFirstRef();
299}
300
Mathias Agopiand7811372011-05-19 18:03:31 -0700301void RefBase::destroy() const {
302 delete this;
303}
304
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800305void RefBase::decStrong(const void* id) const
306{
307 weakref_impl* const refs = mRefs;
308 refs->removeStrongRef(id);
309 const int32_t c = android_atomic_dec(&refs->mStrong);
310#if PRINT_REFS
311 LOGD("decStrong of %p from %p: cnt=%d\n", this, id, c);
312#endif
313 LOG_ASSERT(c >= 1, "decStrong() called on %p too many times", refs);
314 if (c == 1) {
315 const_cast<RefBase*>(this)->onLastStrongRef(id);
316 if ((refs->mFlags&OBJECT_LIFETIME_WEAK) != OBJECT_LIFETIME_WEAK) {
Mathias Agopiand7811372011-05-19 18:03:31 -0700317 destroy();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800318 }
319 }
Mathias Agopian45711432011-06-08 16:05:30 -0700320 refs->removeWeakRef(id);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800321 refs->decWeak(id);
322}
323
324void RefBase::forceIncStrong(const void* id) const
325{
326 weakref_impl* const refs = mRefs;
Mathias Agopian45711432011-06-08 16:05:30 -0700327 refs->addWeakRef(id);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800328 refs->incWeak(id);
329
330 refs->addStrongRef(id);
331 const int32_t c = android_atomic_inc(&refs->mStrong);
332 LOG_ASSERT(c >= 0, "forceIncStrong called on %p after ref count underflow",
333 refs);
334#if PRINT_REFS
335 LOGD("forceIncStrong of %p from %p: cnt=%d\n", this, id, c);
336#endif
337
338 switch (c) {
339 case INITIAL_STRONG_VALUE:
340 android_atomic_add(-INITIAL_STRONG_VALUE, &refs->mStrong);
341 // fall through...
342 case 0:
343 const_cast<RefBase*>(this)->onFirstRef();
344 }
345}
346
347int32_t RefBase::getStrongCount() const
348{
349 return mRefs->mStrong;
350}
351
352
353
354RefBase* RefBase::weakref_type::refBase() const
355{
356 return static_cast<const weakref_impl*>(this)->mBase;
357}
358
359void RefBase::weakref_type::incWeak(const void* id)
360{
361 weakref_impl* const impl = static_cast<weakref_impl*>(this);
362 impl->addWeakRef(id);
363 const int32_t c = android_atomic_inc(&impl->mWeak);
364 LOG_ASSERT(c >= 0, "incWeak called on %p after last weak ref", this);
365}
366
367void RefBase::weakref_type::decWeak(const void* id)
368{
369 weakref_impl* const impl = static_cast<weakref_impl*>(this);
370 impl->removeWeakRef(id);
371 const int32_t c = android_atomic_dec(&impl->mWeak);
372 LOG_ASSERT(c >= 1, "decWeak called on %p too many times", this);
373 if (c != 1) return;
374
375 if ((impl->mFlags&OBJECT_LIFETIME_WEAK) != OBJECT_LIFETIME_WEAK) {
Mathias Agopian45711432011-06-08 16:05:30 -0700376 if (impl->mStrong == INITIAL_STRONG_VALUE) {
377 if (impl->mBase) {
Mathias Agopian2be848d2011-05-19 20:41:27 -0700378 impl->mBase->destroy();
Mathias Agopian45711432011-06-08 16:05:30 -0700379 }
380 } else {
Mathias Agopianb26ea8b2011-02-16 20:23:43 -0800381 // LOGV("Freeing refs %p of old RefBase %p\n", this, impl->mBase);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800382 delete impl;
383 }
384 } else {
385 impl->mBase->onLastWeakRef(id);
386 if ((impl->mFlags&OBJECT_LIFETIME_FOREVER) != OBJECT_LIFETIME_FOREVER) {
Mathias Agopian45711432011-06-08 16:05:30 -0700387 if (impl->mBase) {
Mathias Agopian2be848d2011-05-19 20:41:27 -0700388 impl->mBase->destroy();
Mathias Agopian45711432011-06-08 16:05:30 -0700389 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800390 }
391 }
392}
393
394bool RefBase::weakref_type::attemptIncStrong(const void* id)
395{
396 incWeak(id);
397
398 weakref_impl* const impl = static_cast<weakref_impl*>(this);
399
400 int32_t curCount = impl->mStrong;
401 LOG_ASSERT(curCount >= 0, "attemptIncStrong called on %p after underflow",
402 this);
403 while (curCount > 0 && curCount != INITIAL_STRONG_VALUE) {
404 if (android_atomic_cmpxchg(curCount, curCount+1, &impl->mStrong) == 0) {
405 break;
406 }
407 curCount = impl->mStrong;
408 }
409
410 if (curCount <= 0 || curCount == INITIAL_STRONG_VALUE) {
411 bool allow;
412 if (curCount == INITIAL_STRONG_VALUE) {
413 // Attempting to acquire first strong reference... this is allowed
414 // if the object does NOT have a longer lifetime (meaning the
415 // implementation doesn't need to see this), or if the implementation
416 // allows it to happen.
417 allow = (impl->mFlags&OBJECT_LIFETIME_WEAK) != OBJECT_LIFETIME_WEAK
418 || impl->mBase->onIncStrongAttempted(FIRST_INC_STRONG, id);
419 } else {
420 // Attempting to revive the object... this is allowed
421 // if the object DOES have a longer lifetime (so we can safely
422 // call the object with only a weak ref) and the implementation
423 // allows it to happen.
424 allow = (impl->mFlags&OBJECT_LIFETIME_WEAK) == OBJECT_LIFETIME_WEAK
425 && impl->mBase->onIncStrongAttempted(FIRST_INC_STRONG, id);
426 }
427 if (!allow) {
428 decWeak(id);
429 return false;
430 }
431 curCount = android_atomic_inc(&impl->mStrong);
432
433 // If the strong reference count has already been incremented by
434 // someone else, the implementor of onIncStrongAttempted() is holding
435 // an unneeded reference. So call onLastStrongRef() here to remove it.
436 // (No, this is not pretty.) Note that we MUST NOT do this if we
437 // are in fact acquiring the first reference.
438 if (curCount > 0 && curCount < INITIAL_STRONG_VALUE) {
439 impl->mBase->onLastStrongRef(id);
440 }
441 }
442
Mathias Agopian45711432011-06-08 16:05:30 -0700443 impl->addWeakRef(id);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800444 impl->addStrongRef(id);
445
446#if PRINT_REFS
447 LOGD("attemptIncStrong of %p from %p: cnt=%d\n", this, id, curCount);
448#endif
449
450 if (curCount == INITIAL_STRONG_VALUE) {
451 android_atomic_add(-INITIAL_STRONG_VALUE, &impl->mStrong);
452 impl->mBase->onFirstRef();
453 }
454
455 return true;
456}
457
458bool RefBase::weakref_type::attemptIncWeak(const void* id)
459{
460 weakref_impl* const impl = static_cast<weakref_impl*>(this);
Mathias Agopian45711432011-06-08 16:05:30 -0700461
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800462 int32_t curCount = impl->mWeak;
463 LOG_ASSERT(curCount >= 0, "attemptIncWeak called on %p after underflow",
464 this);
465 while (curCount > 0) {
466 if (android_atomic_cmpxchg(curCount, curCount+1, &impl->mWeak) == 0) {
467 break;
468 }
469 curCount = impl->mWeak;
470 }
471
472 if (curCount > 0) {
473 impl->addWeakRef(id);
474 }
475
476 return curCount > 0;
477}
478
479int32_t RefBase::weakref_type::getWeakCount() const
480{
481 return static_cast<const weakref_impl*>(this)->mWeak;
482}
483
484void RefBase::weakref_type::printRefs() const
485{
486 static_cast<const weakref_impl*>(this)->printRefs();
487}
488
489void RefBase::weakref_type::trackMe(bool enable, bool retain)
490{
Mathias Agopian45711432011-06-08 16:05:30 -0700491 static_cast<const weakref_impl*>(this)->trackMe(enable, retain);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800492}
493
494RefBase::weakref_type* RefBase::createWeak(const void* id) const
495{
496 mRefs->incWeak(id);
497 return mRefs;
498}
499
500RefBase::weakref_type* RefBase::getWeakRefs() const
501{
502 return mRefs;
503}
504
505RefBase::RefBase()
506 : mRefs(new weakref_impl(this))
507{
Mathias Agopian45711432011-06-08 16:05:30 -0700508// LOGV("Creating refs %p with RefBase %p\n", mRefs, this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800509}
510
511RefBase::~RefBase()
512{
Mathias Agopian45711432011-06-08 16:05:30 -0700513 if ((mRefs->mFlags & OBJECT_LIFETIME_WEAK) == OBJECT_LIFETIME_WEAK) {
514 if (mRefs->mWeak == 0) {
515 delete mRefs;
516 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800517 }
518}
519
520void RefBase::extendObjectLifetime(int32_t mode)
521{
522 android_atomic_or(mode, &mRefs->mFlags);
523}
524
525void RefBase::onFirstRef()
526{
527}
528
529void RefBase::onLastStrongRef(const void* /*id*/)
530{
531}
532
533bool RefBase::onIncStrongAttempted(uint32_t flags, const void* id)
534{
535 return (flags&FIRST_INC_STRONG) ? true : false;
536}
537
538void RefBase::onLastWeakRef(const void* /*id*/)
539{
540}
Mathias Agopian45711432011-06-08 16:05:30 -0700541
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800542}; // namespace android