blob: 4ead19c11929781f553360266770cdfa311a1262 [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"
Mathias Agopianda8ec4b2013-03-19 17:36:57 -070018// #define LOG_NDEBUG 0
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080019
Mark Salyzyn5bed8032014-04-30 11:10:46 -070020#include <fcntl.h>
21#include <stdio.h>
22#include <stdlib.h>
23#include <sys/stat.h>
24#include <sys/types.h>
25#include <typeinfo>
26#include <unistd.h>
27
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080028#include <utils/RefBase.h>
29
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080030#include <utils/CallStack.h>
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080031#include <utils/Log.h>
32#include <utils/threads.h>
33
Mark Salyzyn5bed8032014-04-30 11:10:46 -070034#ifndef __unused
35#define __unused __attribute__((__unused__))
36#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080037
38// compile with refcounting debugging enabled
39#define DEBUG_REFS 0
Mathias Agopian6d4419d2013-03-18 20:31:18 -070040
41// whether ref-tracking is enabled by default, if not, trackMe(true, false)
42// needs to be called explicitly
43#define DEBUG_REFS_ENABLED_BY_DEFAULT 0
44
45// whether callstack are collected (significantly slows things down)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080046#define DEBUG_REFS_CALLSTACK_ENABLED 1
47
Mathias Agopian6d4419d2013-03-18 20:31:18 -070048// folder where stack traces are saved when DEBUG_REFS is enabled
49// this folder needs to exist and be writable
50#define DEBUG_REFS_CALLSTACK_PATH "/data/debug"
51
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080052// log all reference counting operations
53#define PRINT_REFS 0
54
55// ---------------------------------------------------------------------------
56
57namespace android {
58
Hans Boehm70a46d62016-05-11 18:15:12 -070059// Usage, invariants, etc:
60
61// It is normally OK just to keep weak pointers to an object. The object will
62// be deallocated by decWeak when the last weak reference disappears.
63// Once a a strong reference has been created, the object will disappear once
64// the last strong reference does (decStrong).
65// AttemptIncStrong will succeed if the object has a strong reference, or if it
66// has a weak reference and has never had a strong reference.
67// AttemptIncWeak really does succeed only if there is already a WEAK
68// reference, and thus may fail when attemptIncStrong would succeed.
69// OBJECT_LIFETIME_WEAK changes this behavior to retain the object
70// unconditionally until the last reference of either kind disappears. The
71// client ensures that the extendObjectLifetime call happens before the dec
72// call that would otherwise have deallocated the object, or before an
73// attemptIncStrong call that might rely on it. We do not worry about
74// concurrent changes to the object lifetime.
75// mStrong is the strong reference count. mWeak is the weak reference count.
76// Between calls, and ignoring memory ordering effects, mWeak includes strong
77// references, and is thus >= mStrong.
78//
79// A weakref_impl is allocated as the value of mRefs in a RefBase object on
80// construction.
81// In the OBJECT_LIFETIME_STRONG case, it is deallocated in the RefBase
82// destructor iff the strong reference count was never incremented. The
83// destructor can be invoked either from decStrong, or from decWeak if there
84// was never a strong reference. If the reference count had been incremented,
85// it is deallocated directly in decWeak, and hence still lives as long as
86// the last weak reference.
87// In the OBJECT_LIFETIME_WEAK case, it is always deallocated from the RefBase
88// destructor, which is always invoked by decWeak. DecStrong explicitly avoids
89// the deletion in this case.
90//
91// Memory ordering:
92// The client must ensure that every inc() call, together with all other
93// accesses to the object, happens before the corresponding dec() call.
94//
95// We try to keep memory ordering constraints on atomics as weak as possible,
96// since memory fences or ordered memory accesses are likely to be a major
97// performance cost for this code. All accesses to mStrong, mWeak, and mFlags
98// explicitly relax memory ordering in some way.
99//
100// The only operations that are not memory_order_relaxed are reference count
101// decrements. All reference count decrements are release operations. In
102// addition, the final decrement leading the deallocation is followed by an
103// acquire fence, which we can view informally as also turning it into an
104// acquire operation. (See 29.8p4 [atomics.fences] for details. We could
105// alternatively use acq_rel operations for all decrements. This is probably
106// slower on most current (2016) hardware, especially on ARMv7, but that may
107// not be true indefinitely.)
108//
109// This convention ensures that the second-to-last decrement synchronizes with
110// (in the language of 1.10 in the C++ standard) the final decrement of a
111// reference count. Since reference counts are only updated using atomic
112// read-modify-write operations, this also extends to any earlier decrements.
113// (See "release sequence" in 1.10.)
114//
115// Since all operations on an object happen before the corresponding reference
116// count decrement, and all reference count decrements happen before the final
117// one, we are guaranteed that all other object accesses happen before the
118// object is destroyed.
119
120
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800121#define INITIAL_STRONG_VALUE (1<<28)
122
123// ---------------------------------------------------------------------------
124
125class RefBase::weakref_impl : public RefBase::weakref_type
126{
127public:
Hans Boehm70a46d62016-05-11 18:15:12 -0700128 std::atomic<int32_t> mStrong;
129 std::atomic<int32_t> mWeak;
130 RefBase* const mBase;
131 std::atomic<int32_t> mFlags;
Mathias Agopian9c8fa9e2011-06-15 20:42:47 -0700132
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800133#if !DEBUG_REFS
134
135 weakref_impl(RefBase* base)
136 : mStrong(INITIAL_STRONG_VALUE)
137 , mWeak(0)
138 , mBase(base)
139 , mFlags(0)
140 {
141 }
142
143 void addStrongRef(const void* /*id*/) { }
144 void removeStrongRef(const void* /*id*/) { }
Mathias Agopianad099652011-08-10 21:07:02 -0700145 void renameStrongRefId(const void* /*old_id*/, const void* /*new_id*/) { }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800146 void addWeakRef(const void* /*id*/) { }
147 void removeWeakRef(const void* /*id*/) { }
Mathias Agopianad099652011-08-10 21:07:02 -0700148 void renameWeakRefId(const void* /*old_id*/, const void* /*new_id*/) { }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800149 void printRefs() const { }
150 void trackMe(bool, bool) { }
151
152#else
153
154 weakref_impl(RefBase* base)
155 : mStrong(INITIAL_STRONG_VALUE)
156 , mWeak(0)
157 , mBase(base)
158 , mFlags(0)
159 , mStrongRefs(NULL)
160 , mWeakRefs(NULL)
161 , mTrackEnabled(!!DEBUG_REFS_ENABLED_BY_DEFAULT)
162 , mRetain(false)
163 {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800164 }
165
166 ~weakref_impl()
167 {
Mathias Agopianad099652011-08-10 21:07:02 -0700168 bool dumpStack = false;
169 if (!mRetain && mStrongRefs != NULL) {
170 dumpStack = true;
Steve Block1b781ab2012-01-06 19:20:56 +0000171 ALOGE("Strong references remain:");
Mathias Agopianad099652011-08-10 21:07:02 -0700172 ref_entry* refs = mStrongRefs;
173 while (refs) {
174 char inc = refs->ref >= 0 ? '+' : '-';
Steve Blockeb095332011-12-20 16:23:08 +0000175 ALOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
Mathias Agopianad099652011-08-10 21:07:02 -0700176#if DEBUG_REFS_CALLSTACK_ENABLED
Ian McKellar55e0f1c2014-03-31 15:59:31 -0700177 refs->stack.log(LOG_TAG);
Mathias Agopianad099652011-08-10 21:07:02 -0700178#endif
179 refs = refs->next;
180 }
181 }
182
183 if (!mRetain && mWeakRefs != NULL) {
184 dumpStack = true;
Steve Block1b781ab2012-01-06 19:20:56 +0000185 ALOGE("Weak references remain!");
Mathias Agopianad099652011-08-10 21:07:02 -0700186 ref_entry* refs = mWeakRefs;
187 while (refs) {
188 char inc = refs->ref >= 0 ? '+' : '-';
Steve Blockeb095332011-12-20 16:23:08 +0000189 ALOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
Mathias Agopianad099652011-08-10 21:07:02 -0700190#if DEBUG_REFS_CALLSTACK_ENABLED
Ian McKellar55e0f1c2014-03-31 15:59:31 -0700191 refs->stack.log(LOG_TAG);
Mathias Agopianad099652011-08-10 21:07:02 -0700192#endif
193 refs = refs->next;
194 }
195 }
196 if (dumpStack) {
Steve Block1b781ab2012-01-06 19:20:56 +0000197 ALOGE("above errors at:");
Mathias Agopiand34a8ca2013-03-21 17:12:40 -0700198 CallStack stack(LOG_TAG);
Mathias Agopianad099652011-08-10 21:07:02 -0700199 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800200 }
201
Mathias Agopianad099652011-08-10 21:07:02 -0700202 void addStrongRef(const void* id) {
Steve Blockeb095332011-12-20 16:23:08 +0000203 //ALOGD_IF(mTrackEnabled,
Mathias Agopianad099652011-08-10 21:07:02 -0700204 // "addStrongRef: RefBase=%p, id=%p", mBase, id);
Hans Boehm70a46d62016-05-11 18:15:12 -0700205 addRef(&mStrongRefs, id, mStrong.load(std::memory_order_relaxed));
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800206 }
207
Mathias Agopianad099652011-08-10 21:07:02 -0700208 void removeStrongRef(const void* id) {
Steve Blockeb095332011-12-20 16:23:08 +0000209 //ALOGD_IF(mTrackEnabled,
Mathias Agopianad099652011-08-10 21:07:02 -0700210 // "removeStrongRef: RefBase=%p, id=%p", mBase, id);
211 if (!mRetain) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800212 removeRef(&mStrongRefs, id);
Mathias Agopianad099652011-08-10 21:07:02 -0700213 } else {
Hans Boehm70a46d62016-05-11 18:15:12 -0700214 addRef(&mStrongRefs, id, -mStrong.load(std::memory_order_relaxed));
Mathias Agopianad099652011-08-10 21:07:02 -0700215 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800216 }
217
Mathias Agopianad099652011-08-10 21:07:02 -0700218 void renameStrongRefId(const void* old_id, const void* new_id) {
Steve Blockeb095332011-12-20 16:23:08 +0000219 //ALOGD_IF(mTrackEnabled,
Mathias Agopianad099652011-08-10 21:07:02 -0700220 // "renameStrongRefId: RefBase=%p, oid=%p, nid=%p",
221 // mBase, old_id, new_id);
222 renameRefsId(mStrongRefs, old_id, new_id);
223 }
224
225 void addWeakRef(const void* id) {
Hans Boehm70a46d62016-05-11 18:15:12 -0700226 addRef(&mWeakRefs, id, mWeak.load(std::memory_order_relaxed));
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800227 }
228
Mathias Agopianad099652011-08-10 21:07:02 -0700229 void removeWeakRef(const void* id) {
230 if (!mRetain) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800231 removeRef(&mWeakRefs, id);
Mathias Agopianad099652011-08-10 21:07:02 -0700232 } else {
Hans Boehm70a46d62016-05-11 18:15:12 -0700233 addRef(&mWeakRefs, id, -mWeak.load(std::memory_order_relaxed));
Mathias Agopianad099652011-08-10 21:07:02 -0700234 }
235 }
236
237 void renameWeakRefId(const void* old_id, const void* new_id) {
238 renameRefsId(mWeakRefs, old_id, new_id);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800239 }
240
241 void trackMe(bool track, bool retain)
242 {
243 mTrackEnabled = track;
244 mRetain = retain;
245 }
246
247 void printRefs() const
248 {
249 String8 text;
250
251 {
Mathias Agopianad099652011-08-10 21:07:02 -0700252 Mutex::Autolock _l(mMutex);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800253 char buf[128];
254 sprintf(buf, "Strong references on RefBase %p (weakref_type %p):\n", mBase, this);
255 text.append(buf);
256 printRefsLocked(&text, mStrongRefs);
257 sprintf(buf, "Weak references on RefBase %p (weakref_type %p):\n", mBase, this);
258 text.append(buf);
259 printRefsLocked(&text, mWeakRefs);
260 }
261
262 {
263 char name[100];
Mathias Agopian6d4419d2013-03-18 20:31:18 -0700264 snprintf(name, 100, DEBUG_REFS_CALLSTACK_PATH "/%p.stack", this);
Mathias Agopian769828d2013-03-06 17:51:15 -0800265 int rc = open(name, O_RDWR | O_CREAT | O_APPEND, 644);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800266 if (rc >= 0) {
267 write(rc, text.string(), text.length());
268 close(rc);
Steve Blockeb095332011-12-20 16:23:08 +0000269 ALOGD("STACK TRACE for %p saved in %s", this, name);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800270 }
Steve Block1b781ab2012-01-06 19:20:56 +0000271 else ALOGE("FAILED TO PRINT STACK TRACE for %p in %s: %s", this,
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800272 name, strerror(errno));
273 }
274 }
275
276private:
277 struct ref_entry
278 {
279 ref_entry* next;
280 const void* id;
281#if DEBUG_REFS_CALLSTACK_ENABLED
282 CallStack stack;
283#endif
284 int32_t ref;
285 };
286
287 void addRef(ref_entry** refs, const void* id, int32_t mRef)
288 {
289 if (mTrackEnabled) {
290 AutoMutex _l(mMutex);
Mathias Agopianad099652011-08-10 21:07:02 -0700291
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800292 ref_entry* ref = new ref_entry;
293 // Reference count at the time of the snapshot, but before the
294 // update. Positive value means we increment, negative--we
295 // decrement the reference count.
296 ref->ref = mRef;
297 ref->id = id;
298#if DEBUG_REFS_CALLSTACK_ENABLED
299 ref->stack.update(2);
300#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800301 ref->next = *refs;
302 *refs = ref;
303 }
304 }
305
306 void removeRef(ref_entry** refs, const void* id)
307 {
308 if (mTrackEnabled) {
309 AutoMutex _l(mMutex);
310
Mathias Agopianad099652011-08-10 21:07:02 -0700311 ref_entry* const head = *refs;
312 ref_entry* ref = head;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800313 while (ref != NULL) {
314 if (ref->id == id) {
315 *refs = ref->next;
316 delete ref;
317 return;
318 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800319 refs = &ref->next;
320 ref = *refs;
321 }
Mathias Agopianad099652011-08-10 21:07:02 -0700322
Steve Block1b781ab2012-01-06 19:20:56 +0000323 ALOGE("RefBase: removing id %p on RefBase %p"
Mathias Agopianad099652011-08-10 21:07:02 -0700324 "(weakref_type %p) that doesn't exist!",
325 id, mBase, this);
326
327 ref = head;
328 while (ref) {
329 char inc = ref->ref >= 0 ? '+' : '-';
Steve Blockeb095332011-12-20 16:23:08 +0000330 ALOGD("\t%c ID %p (ref %d):", inc, ref->id, ref->ref);
Mathias Agopianad099652011-08-10 21:07:02 -0700331 ref = ref->next;
332 }
333
Mathias Agopiand34a8ca2013-03-21 17:12:40 -0700334 CallStack stack(LOG_TAG);
Mathias Agopianad099652011-08-10 21:07:02 -0700335 }
336 }
337
338 void renameRefsId(ref_entry* r, const void* old_id, const void* new_id)
339 {
340 if (mTrackEnabled) {
341 AutoMutex _l(mMutex);
342 ref_entry* ref = r;
343 while (ref != NULL) {
344 if (ref->id == old_id) {
345 ref->id = new_id;
346 }
347 ref = ref->next;
348 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800349 }
350 }
351
352 void printRefsLocked(String8* out, const ref_entry* refs) const
353 {
354 char buf[128];
355 while (refs) {
356 char inc = refs->ref >= 0 ? '+' : '-';
357 sprintf(buf, "\t%c ID %p (ref %d):\n",
358 inc, refs->id, refs->ref);
359 out->append(buf);
360#if DEBUG_REFS_CALLSTACK_ENABLED
361 out->append(refs->stack.toString("\t\t"));
362#else
363 out->append("\t\t(call stacks disabled)");
364#endif
365 refs = refs->next;
366 }
367 }
368
Mathias Agopianad099652011-08-10 21:07:02 -0700369 mutable Mutex mMutex;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800370 ref_entry* mStrongRefs;
371 ref_entry* mWeakRefs;
372
373 bool mTrackEnabled;
374 // Collect stack traces on addref and removeref, instead of deleting the stack references
375 // on removeref that match the address ones.
376 bool mRetain;
377
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800378#endif
379};
380
381// ---------------------------------------------------------------------------
382
383void RefBase::incStrong(const void* id) const
384{
385 weakref_impl* const refs = mRefs;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800386 refs->incWeak(id);
387
388 refs->addStrongRef(id);
Hans Boehm70a46d62016-05-11 18:15:12 -0700389 const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000390 ALOG_ASSERT(c > 0, "incStrong() called on %p after last strong ref", refs);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800391#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000392 ALOGD("incStrong of %p from %p: cnt=%d\n", this, id, c);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800393#endif
394 if (c != INITIAL_STRONG_VALUE) {
395 return;
396 }
397
Hans Boehm70a46d62016-05-11 18:15:12 -0700398 int32_t old = refs->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
399 std::memory_order_relaxed);
400 // A decStrong() must still happen after us.
401 ALOG_ASSERT(old > INITIAL_STRONG_VALUE, "0x%x too small", old);
Mathias Agopianad099652011-08-10 21:07:02 -0700402 refs->mBase->onFirstRef();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800403}
404
405void RefBase::decStrong(const void* id) const
406{
407 weakref_impl* const refs = mRefs;
408 refs->removeStrongRef(id);
Hans Boehm70a46d62016-05-11 18:15:12 -0700409 const int32_t c = refs->mStrong.fetch_sub(1, std::memory_order_release);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800410#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000411 ALOGD("decStrong of %p from %p: cnt=%d\n", this, id, c);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800412#endif
Steve Blockae074452012-01-09 18:35:44 +0000413 ALOG_ASSERT(c >= 1, "decStrong() called on %p too many times", refs);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800414 if (c == 1) {
Hans Boehm70a46d62016-05-11 18:15:12 -0700415 std::atomic_thread_fence(std::memory_order_acquire);
Mathias Agopianad099652011-08-10 21:07:02 -0700416 refs->mBase->onLastStrongRef(id);
Hans Boehm70a46d62016-05-11 18:15:12 -0700417 int32_t flags = refs->mFlags.load(std::memory_order_relaxed);
418 if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
Mathias Agopian9c8fa9e2011-06-15 20:42:47 -0700419 delete this;
Hans Boehm70a46d62016-05-11 18:15:12 -0700420 // Since mStrong had been incremented, the destructor did not
421 // delete refs.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800422 }
423 }
Hans Boehm70a46d62016-05-11 18:15:12 -0700424 // Note that even with only strong reference operations, the thread
425 // deallocating this may not be the same as the thread deallocating refs.
426 // That's OK: all accesses to this happen before its deletion here,
427 // and all accesses to refs happen before its deletion in the final decWeak.
428 // The destructor can safely access mRefs because either it's deleting
429 // mRefs itself, or it's running entirely before the final mWeak decrement.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800430 refs->decWeak(id);
431}
432
433void RefBase::forceIncStrong(const void* id) const
434{
Hans Boehm70a46d62016-05-11 18:15:12 -0700435 // Allows initial mStrong of 0 in addition to INITIAL_STRONG_VALUE.
436 // TODO: Better document assumptions.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800437 weakref_impl* const refs = mRefs;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800438 refs->incWeak(id);
439
440 refs->addStrongRef(id);
Hans Boehm70a46d62016-05-11 18:15:12 -0700441 const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000442 ALOG_ASSERT(c >= 0, "forceIncStrong called on %p after ref count underflow",
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800443 refs);
444#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000445 ALOGD("forceIncStrong of %p from %p: cnt=%d\n", this, id, c);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800446#endif
447
448 switch (c) {
449 case INITIAL_STRONG_VALUE:
Hans Boehm70a46d62016-05-11 18:15:12 -0700450 refs->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
451 std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800452 // fall through...
453 case 0:
Mathias Agopianad099652011-08-10 21:07:02 -0700454 refs->mBase->onFirstRef();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800455 }
456}
457
458int32_t RefBase::getStrongCount() const
459{
Hans Boehm70a46d62016-05-11 18:15:12 -0700460 // Debugging only; No memory ordering guarantees.
461 return mRefs->mStrong.load(std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800462}
463
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800464RefBase* RefBase::weakref_type::refBase() const
465{
466 return static_cast<const weakref_impl*>(this)->mBase;
467}
468
469void RefBase::weakref_type::incWeak(const void* id)
470{
471 weakref_impl* const impl = static_cast<weakref_impl*>(this);
472 impl->addWeakRef(id);
Hans Boehm70a46d62016-05-11 18:15:12 -0700473 const int32_t c __unused = impl->mWeak.fetch_add(1,
474 std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000475 ALOG_ASSERT(c >= 0, "incWeak called on %p after last weak ref", this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800476}
477
Mathias Agopianad099652011-08-10 21:07:02 -0700478
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800479void RefBase::weakref_type::decWeak(const void* id)
480{
481 weakref_impl* const impl = static_cast<weakref_impl*>(this);
482 impl->removeWeakRef(id);
Hans Boehm70a46d62016-05-11 18:15:12 -0700483 const int32_t c = impl->mWeak.fetch_sub(1, std::memory_order_release);
Steve Blockae074452012-01-09 18:35:44 +0000484 ALOG_ASSERT(c >= 1, "decWeak called on %p too many times", this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800485 if (c != 1) return;
Hans Boehm70a46d62016-05-11 18:15:12 -0700486 atomic_thread_fence(std::memory_order_acquire);
Mathias Agopianad099652011-08-10 21:07:02 -0700487
Hans Boehm70a46d62016-05-11 18:15:12 -0700488 int32_t flags = impl->mFlags.load(std::memory_order_relaxed);
489 if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
Mathias Agopianad099652011-08-10 21:07:02 -0700490 // This is the regular lifetime case. The object is destroyed
491 // when the last strong reference goes away. Since weakref_impl
492 // outlive the object, it is not destroyed in the dtor, and
493 // we'll have to do it here.
Hans Boehm70a46d62016-05-11 18:15:12 -0700494 if (impl->mStrong.load(std::memory_order_relaxed)
495 == INITIAL_STRONG_VALUE) {
Mathias Agopianad099652011-08-10 21:07:02 -0700496 // Special case: we never had a strong reference, so we need to
497 // destroy the object now.
Mathias Agopian9c8fa9e2011-06-15 20:42:47 -0700498 delete impl->mBase;
Mathias Agopianad099652011-08-10 21:07:02 -0700499 } else {
Steve Blockb37fbe92011-10-20 11:56:00 +0100500 // ALOGV("Freeing refs %p of old RefBase %p\n", this, impl->mBase);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800501 delete impl;
502 }
503 } else {
Hans Boehm70a46d62016-05-11 18:15:12 -0700504 // This is the OBJECT_LIFETIME_WEAK case. The last weak-reference
505 // is gone, we can destroy the object.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800506 impl->mBase->onLastWeakRef(id);
Hans Boehm70a46d62016-05-11 18:15:12 -0700507 delete impl->mBase;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800508 }
509}
510
511bool RefBase::weakref_type::attemptIncStrong(const void* id)
512{
513 incWeak(id);
514
515 weakref_impl* const impl = static_cast<weakref_impl*>(this);
Hans Boehm70a46d62016-05-11 18:15:12 -0700516 int32_t curCount = impl->mStrong.load(std::memory_order_relaxed);
Dianne Hackborna729ab12013-03-14 15:26:30 -0700517
518 ALOG_ASSERT(curCount >= 0,
519 "attemptIncStrong called on %p after underflow", this);
520
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800521 while (curCount > 0 && curCount != INITIAL_STRONG_VALUE) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700522 // we're in the easy/common case of promoting a weak-reference
523 // from an existing strong reference.
Hans Boehm70a46d62016-05-11 18:15:12 -0700524 if (impl->mStrong.compare_exchange_weak(curCount, curCount+1,
525 std::memory_order_relaxed)) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800526 break;
527 }
Dianne Hackborna729ab12013-03-14 15:26:30 -0700528 // the strong count has changed on us, we need to re-assert our
Hans Boehm70a46d62016-05-11 18:15:12 -0700529 // situation. curCount was updated by compare_exchange_weak.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800530 }
531
532 if (curCount <= 0 || curCount == INITIAL_STRONG_VALUE) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700533 // we're now in the harder case of either:
534 // - there never was a strong reference on us
535 // - or, all strong references have been released
Hans Boehm70a46d62016-05-11 18:15:12 -0700536 int32_t flags = impl->mFlags.load(std::memory_order_relaxed);
537 if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700538 // this object has a "normal" life-time, i.e.: it gets destroyed
539 // when the last strong reference goes away
540 if (curCount <= 0) {
541 // the last strong-reference got released, the object cannot
542 // be revived.
543 decWeak(id);
544 return false;
545 }
546
547 // here, curCount == INITIAL_STRONG_VALUE, which means
548 // there never was a strong-reference, so we can try to
549 // promote this object; we need to do that atomically.
550 while (curCount > 0) {
Hans Boehm70a46d62016-05-11 18:15:12 -0700551 if (impl->mStrong.compare_exchange_weak(curCount, curCount+1,
552 std::memory_order_relaxed)) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700553 break;
554 }
555 // the strong count has changed on us, we need to re-assert our
556 // situation (e.g.: another thread has inc/decStrong'ed us)
Hans Boehm70a46d62016-05-11 18:15:12 -0700557 // curCount has been updated.
Dianne Hackborna729ab12013-03-14 15:26:30 -0700558 }
559
560 if (curCount <= 0) {
561 // promote() failed, some other thread destroyed us in the
562 // meantime (i.e.: strong count reached zero).
563 decWeak(id);
564 return false;
565 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800566 } else {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700567 // this object has an "extended" life-time, i.e.: it can be
568 // revived from a weak-reference only.
569 // Ask the object's implementation if it agrees to be revived
570 if (!impl->mBase->onIncStrongAttempted(FIRST_INC_STRONG, id)) {
571 // it didn't so give-up.
572 decWeak(id);
573 return false;
574 }
575 // grab a strong-reference, which is always safe due to the
576 // extended life-time.
Hans Boehm70a46d62016-05-11 18:15:12 -0700577 curCount = impl->mStrong.fetch_add(1, std::memory_order_relaxed);
Hans Boehm1b07c952016-07-29 14:39:10 -0700578 // If the strong reference count has already been incremented by
579 // someone else, the implementor of onIncStrongAttempted() is holding
580 // an unneeded reference. So call onLastStrongRef() here to remove it.
581 // (No, this is not pretty.) Note that we MUST NOT do this if we
582 // are in fact acquiring the first reference.
583 if (curCount != 0 && curCount != INITIAL_STRONG_VALUE) {
584 impl->mBase->onLastStrongRef(id);
585 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800586 }
587 }
588
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800589 impl->addStrongRef(id);
590
591#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000592 ALOGD("attemptIncStrong of %p from %p: cnt=%d\n", this, id, curCount);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800593#endif
594
Hans Boehm1b07c952016-07-29 14:39:10 -0700595 // curCount is the value of mStrong before we incremented it.
Hans Boehm70a46d62016-05-11 18:15:12 -0700596 // Now we need to fix-up the count if it was INITIAL_STRONG_VALUE.
597 // This must be done safely, i.e.: handle the case where several threads
Dianne Hackborna729ab12013-03-14 15:26:30 -0700598 // were here in attemptIncStrong().
Hans Boehm70a46d62016-05-11 18:15:12 -0700599 // curCount > INITIAL_STRONG_VALUE is OK, and can happen if we're doing
600 // this in the middle of another incStrong. The subtraction is handled
601 // by the thread that started with INITIAL_STRONG_VALUE.
602 if (curCount == INITIAL_STRONG_VALUE) {
603 impl->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
604 std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800605 }
Dianne Hackborna729ab12013-03-14 15:26:30 -0700606
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800607 return true;
608}
609
610bool RefBase::weakref_type::attemptIncWeak(const void* id)
611{
612 weakref_impl* const impl = static_cast<weakref_impl*>(this);
Mathias Agopianad099652011-08-10 21:07:02 -0700613
Hans Boehm70a46d62016-05-11 18:15:12 -0700614 int32_t curCount = impl->mWeak.load(std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000615 ALOG_ASSERT(curCount >= 0, "attemptIncWeak called on %p after underflow",
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800616 this);
617 while (curCount > 0) {
Hans Boehm70a46d62016-05-11 18:15:12 -0700618 if (impl->mWeak.compare_exchange_weak(curCount, curCount+1,
619 std::memory_order_relaxed)) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800620 break;
621 }
Hans Boehm70a46d62016-05-11 18:15:12 -0700622 // curCount has been updated.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800623 }
624
625 if (curCount > 0) {
626 impl->addWeakRef(id);
627 }
628
629 return curCount > 0;
630}
631
632int32_t RefBase::weakref_type::getWeakCount() const
633{
Hans Boehm70a46d62016-05-11 18:15:12 -0700634 // Debug only!
635 return static_cast<const weakref_impl*>(this)->mWeak
636 .load(std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800637}
638
639void RefBase::weakref_type::printRefs() const
640{
641 static_cast<const weakref_impl*>(this)->printRefs();
642}
643
644void RefBase::weakref_type::trackMe(bool enable, bool retain)
645{
Mathias Agopianad099652011-08-10 21:07:02 -0700646 static_cast<weakref_impl*>(this)->trackMe(enable, retain);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800647}
648
649RefBase::weakref_type* RefBase::createWeak(const void* id) const
650{
651 mRefs->incWeak(id);
652 return mRefs;
653}
654
655RefBase::weakref_type* RefBase::getWeakRefs() const
656{
657 return mRefs;
658}
659
660RefBase::RefBase()
661 : mRefs(new weakref_impl(this))
662{
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800663}
664
665RefBase::~RefBase()
666{
Hans Boehm70a46d62016-05-11 18:15:12 -0700667 if (mRefs->mStrong.load(std::memory_order_relaxed)
668 == INITIAL_STRONG_VALUE) {
Mathias Agopianad099652011-08-10 21:07:02 -0700669 // we never acquired a strong (and/or weak) reference on this object.
Mathias Agopian9c8fa9e2011-06-15 20:42:47 -0700670 delete mRefs;
Mathias Agopianad099652011-08-10 21:07:02 -0700671 } else {
Hans Boehm70a46d62016-05-11 18:15:12 -0700672 // life-time of this object is extended to WEAK, in
Mathias Agopianad099652011-08-10 21:07:02 -0700673 // which case weakref_impl doesn't out-live the object and we
674 // can free it now.
Hans Boehm70a46d62016-05-11 18:15:12 -0700675 int32_t flags = mRefs->mFlags.load(std::memory_order_relaxed);
676 if ((flags & OBJECT_LIFETIME_MASK) != OBJECT_LIFETIME_STRONG) {
Mathias Agopianad099652011-08-10 21:07:02 -0700677 // It's possible that the weak count is not 0 if the object
678 // re-acquired a weak reference in its destructor
Hans Boehm70a46d62016-05-11 18:15:12 -0700679 if (mRefs->mWeak.load(std::memory_order_relaxed) == 0) {
Mathias Agopianad099652011-08-10 21:07:02 -0700680 delete mRefs;
681 }
682 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800683 }
Mathias Agopianad099652011-08-10 21:07:02 -0700684 // for debugging purposes, clear this.
685 const_cast<weakref_impl*&>(mRefs) = NULL;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800686}
687
688void RefBase::extendObjectLifetime(int32_t mode)
689{
Hans Boehm70a46d62016-05-11 18:15:12 -0700690 // Must be happens-before ordered with respect to construction or any
691 // operation that could destroy the object.
692 mRefs->mFlags.fetch_or(mode, std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800693}
694
695void RefBase::onFirstRef()
696{
697}
698
699void RefBase::onLastStrongRef(const void* /*id*/)
700{
701}
702
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700703bool RefBase::onIncStrongAttempted(uint32_t flags, const void* /*id*/)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800704{
705 return (flags&FIRST_INC_STRONG) ? true : false;
706}
707
708void RefBase::onLastWeakRef(const void* /*id*/)
709{
710}
Mathias Agopianad099652011-08-10 21:07:02 -0700711
712// ---------------------------------------------------------------------------
713
Mathias Agopianad099652011-08-10 21:07:02 -0700714#if DEBUG_REFS
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700715void RefBase::renameRefs(size_t n, const ReferenceRenamer& renamer) {
Mathias Agopianad099652011-08-10 21:07:02 -0700716 for (size_t i=0 ; i<n ; i++) {
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700717 renamer(i);
Mathias Agopianad099652011-08-10 21:07:02 -0700718 }
Mathias Agopianad099652011-08-10 21:07:02 -0700719}
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700720#else
721void RefBase::renameRefs(size_t /*n*/, const ReferenceRenamer& /*renamer*/) { }
722#endif
Mathias Agopianad099652011-08-10 21:07:02 -0700723
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700724void RefBase::renameRefId(weakref_type* ref,
725 const void* old_id, const void* new_id) {
726 weakref_impl* const impl = static_cast<weakref_impl*>(ref);
727 impl->renameStrongRefId(old_id, new_id);
728 impl->renameWeakRefId(old_id, new_id);
729}
730
731void RefBase::renameRefId(RefBase* ref,
732 const void* old_id, const void* new_id) {
733 ref->mRefs->renameStrongRefId(old_id, new_id);
734 ref->mRefs->renameWeakRefId(old_id, new_id);
735}
736
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800737}; // namespace android