blob: df49a2f94e5241cb60caeb7db6971202625be53e [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 Boehm9ba71922016-07-21 18:56:55 -070059// Observations, invariants, etc:
Hans Boehme263e6c2016-05-11 18:15:12 -070060
Hans Boehm9ba71922016-07-21 18:56:55 -070061// By default, obects are destroyed when the last strong reference disappears
62// or, if the object never had a strong reference, when the last weak reference
63// disappears.
64//
Hans Boehme263e6c2016-05-11 18:15:12 -070065// OBJECT_LIFETIME_WEAK changes this behavior to retain the object
66// unconditionally until the last reference of either kind disappears. The
67// client ensures that the extendObjectLifetime call happens before the dec
68// call that would otherwise have deallocated the object, or before an
69// attemptIncStrong call that might rely on it. We do not worry about
70// concurrent changes to the object lifetime.
Hans Boehm9ba71922016-07-21 18:56:55 -070071//
72// AttemptIncStrong will succeed if the object has a strong reference, or if it
73// has a weak reference and has never had a strong reference.
74// AttemptIncWeak really does succeed only if there is already a WEAK
75// reference, and thus may fail when attemptIncStrong would succeed.
76//
Hans Boehme263e6c2016-05-11 18:15:12 -070077// mStrong is the strong reference count. mWeak is the weak reference count.
78// Between calls, and ignoring memory ordering effects, mWeak includes strong
79// references, and is thus >= mStrong.
80//
Hans Boehm9ba71922016-07-21 18:56:55 -070081// A weakref_impl holds all the information, including both reference counts,
82// required to perform wp<> operations. Thus these can continue to be performed
83// after the RefBase object has been destroyed.
84//
Hans Boehme263e6c2016-05-11 18:15:12 -070085// A weakref_impl is allocated as the value of mRefs in a RefBase object on
86// construction.
87// In the OBJECT_LIFETIME_STRONG case, it is deallocated in the RefBase
88// destructor iff the strong reference count was never incremented. The
89// destructor can be invoked either from decStrong, or from decWeak if there
90// was never a strong reference. If the reference count had been incremented,
91// it is deallocated directly in decWeak, and hence still lives as long as
92// the last weak reference.
93// In the OBJECT_LIFETIME_WEAK case, it is always deallocated from the RefBase
94// destructor, which is always invoked by decWeak. DecStrong explicitly avoids
95// the deletion in this case.
96//
97// Memory ordering:
98// The client must ensure that every inc() call, together with all other
99// accesses to the object, happens before the corresponding dec() call.
100//
101// We try to keep memory ordering constraints on atomics as weak as possible,
102// since memory fences or ordered memory accesses are likely to be a major
103// performance cost for this code. All accesses to mStrong, mWeak, and mFlags
104// explicitly relax memory ordering in some way.
105//
106// The only operations that are not memory_order_relaxed are reference count
107// decrements. All reference count decrements are release operations. In
108// addition, the final decrement leading the deallocation is followed by an
109// acquire fence, which we can view informally as also turning it into an
110// acquire operation. (See 29.8p4 [atomics.fences] for details. We could
111// alternatively use acq_rel operations for all decrements. This is probably
112// slower on most current (2016) hardware, especially on ARMv7, but that may
113// not be true indefinitely.)
114//
115// This convention ensures that the second-to-last decrement synchronizes with
116// (in the language of 1.10 in the C++ standard) the final decrement of a
117// reference count. Since reference counts are only updated using atomic
118// read-modify-write operations, this also extends to any earlier decrements.
119// (See "release sequence" in 1.10.)
120//
121// Since all operations on an object happen before the corresponding reference
122// count decrement, and all reference count decrements happen before the final
123// one, we are guaranteed that all other object accesses happen before the
124// object is destroyed.
125
126
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800127#define INITIAL_STRONG_VALUE (1<<28)
128
129// ---------------------------------------------------------------------------
130
131class RefBase::weakref_impl : public RefBase::weakref_type
132{
133public:
Hans Boehme263e6c2016-05-11 18:15:12 -0700134 std::atomic<int32_t> mStrong;
135 std::atomic<int32_t> mWeak;
136 RefBase* const mBase;
137 std::atomic<int32_t> mFlags;
Mathias Agopian9c8fa9e2011-06-15 20:42:47 -0700138
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800139#if !DEBUG_REFS
140
Chih-Hung Hsieh1c563d92016-04-29 15:44:04 -0700141 explicit weakref_impl(RefBase* base)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800142 : mStrong(INITIAL_STRONG_VALUE)
143 , mWeak(0)
144 , mBase(base)
145 , mFlags(0)
146 {
147 }
148
149 void addStrongRef(const void* /*id*/) { }
150 void removeStrongRef(const void* /*id*/) { }
Mathias Agopianad099652011-08-10 21:07:02 -0700151 void renameStrongRefId(const void* /*old_id*/, const void* /*new_id*/) { }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800152 void addWeakRef(const void* /*id*/) { }
153 void removeWeakRef(const void* /*id*/) { }
Mathias Agopianad099652011-08-10 21:07:02 -0700154 void renameWeakRefId(const void* /*old_id*/, const void* /*new_id*/) { }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800155 void printRefs() const { }
156 void trackMe(bool, bool) { }
157
158#else
159
160 weakref_impl(RefBase* base)
161 : mStrong(INITIAL_STRONG_VALUE)
162 , mWeak(0)
163 , mBase(base)
164 , mFlags(0)
165 , mStrongRefs(NULL)
166 , mWeakRefs(NULL)
167 , mTrackEnabled(!!DEBUG_REFS_ENABLED_BY_DEFAULT)
168 , mRetain(false)
169 {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800170 }
171
172 ~weakref_impl()
173 {
Mathias Agopianad099652011-08-10 21:07:02 -0700174 bool dumpStack = false;
175 if (!mRetain && mStrongRefs != NULL) {
176 dumpStack = true;
Steve Block1b781ab2012-01-06 19:20:56 +0000177 ALOGE("Strong references remain:");
Mathias Agopianad099652011-08-10 21:07:02 -0700178 ref_entry* refs = mStrongRefs;
179 while (refs) {
180 char inc = refs->ref >= 0 ? '+' : '-';
Steve Blockeb095332011-12-20 16:23:08 +0000181 ALOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
Mathias Agopianad099652011-08-10 21:07:02 -0700182#if DEBUG_REFS_CALLSTACK_ENABLED
Ian McKellar55e0f1c2014-03-31 15:59:31 -0700183 refs->stack.log(LOG_TAG);
Mathias Agopianad099652011-08-10 21:07:02 -0700184#endif
185 refs = refs->next;
186 }
187 }
188
189 if (!mRetain && mWeakRefs != NULL) {
190 dumpStack = true;
Steve Block1b781ab2012-01-06 19:20:56 +0000191 ALOGE("Weak references remain!");
Mathias Agopianad099652011-08-10 21:07:02 -0700192 ref_entry* refs = mWeakRefs;
193 while (refs) {
194 char inc = refs->ref >= 0 ? '+' : '-';
Steve Blockeb095332011-12-20 16:23:08 +0000195 ALOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
Mathias Agopianad099652011-08-10 21:07:02 -0700196#if DEBUG_REFS_CALLSTACK_ENABLED
Ian McKellar55e0f1c2014-03-31 15:59:31 -0700197 refs->stack.log(LOG_TAG);
Mathias Agopianad099652011-08-10 21:07:02 -0700198#endif
199 refs = refs->next;
200 }
201 }
202 if (dumpStack) {
Steve Block1b781ab2012-01-06 19:20:56 +0000203 ALOGE("above errors at:");
Mathias Agopiand34a8ca2013-03-21 17:12:40 -0700204 CallStack stack(LOG_TAG);
Mathias Agopianad099652011-08-10 21:07:02 -0700205 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800206 }
207
Mathias Agopianad099652011-08-10 21:07:02 -0700208 void addStrongRef(const void* id) {
Steve Blockeb095332011-12-20 16:23:08 +0000209 //ALOGD_IF(mTrackEnabled,
Mathias Agopianad099652011-08-10 21:07:02 -0700210 // "addStrongRef: RefBase=%p, id=%p", mBase, id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700211 addRef(&mStrongRefs, id, mStrong.load(std::memory_order_relaxed));
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800212 }
213
Mathias Agopianad099652011-08-10 21:07:02 -0700214 void removeStrongRef(const void* id) {
Steve Blockeb095332011-12-20 16:23:08 +0000215 //ALOGD_IF(mTrackEnabled,
Mathias Agopianad099652011-08-10 21:07:02 -0700216 // "removeStrongRef: RefBase=%p, id=%p", mBase, id);
217 if (!mRetain) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800218 removeRef(&mStrongRefs, id);
Mathias Agopianad099652011-08-10 21:07:02 -0700219 } else {
Hans Boehme263e6c2016-05-11 18:15:12 -0700220 addRef(&mStrongRefs, id, -mStrong.load(std::memory_order_relaxed));
Mathias Agopianad099652011-08-10 21:07:02 -0700221 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800222 }
223
Mathias Agopianad099652011-08-10 21:07:02 -0700224 void renameStrongRefId(const void* old_id, const void* new_id) {
Steve Blockeb095332011-12-20 16:23:08 +0000225 //ALOGD_IF(mTrackEnabled,
Mathias Agopianad099652011-08-10 21:07:02 -0700226 // "renameStrongRefId: RefBase=%p, oid=%p, nid=%p",
227 // mBase, old_id, new_id);
228 renameRefsId(mStrongRefs, old_id, new_id);
229 }
230
231 void addWeakRef(const void* id) {
Hans Boehme263e6c2016-05-11 18:15:12 -0700232 addRef(&mWeakRefs, id, mWeak.load(std::memory_order_relaxed));
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800233 }
234
Mathias Agopianad099652011-08-10 21:07:02 -0700235 void removeWeakRef(const void* id) {
236 if (!mRetain) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800237 removeRef(&mWeakRefs, id);
Mathias Agopianad099652011-08-10 21:07:02 -0700238 } else {
Hans Boehme263e6c2016-05-11 18:15:12 -0700239 addRef(&mWeakRefs, id, -mWeak.load(std::memory_order_relaxed));
Mathias Agopianad099652011-08-10 21:07:02 -0700240 }
241 }
242
243 void renameWeakRefId(const void* old_id, const void* new_id) {
244 renameRefsId(mWeakRefs, old_id, new_id);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800245 }
246
247 void trackMe(bool track, bool retain)
248 {
249 mTrackEnabled = track;
250 mRetain = retain;
251 }
252
253 void printRefs() const
254 {
255 String8 text;
256
257 {
Mathias Agopianad099652011-08-10 21:07:02 -0700258 Mutex::Autolock _l(mMutex);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800259 char buf[128];
George Burgess IVe7aa2b22016-03-02 14:02:55 -0800260 snprintf(buf, sizeof(buf),
261 "Strong references on RefBase %p (weakref_type %p):\n",
262 mBase, this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800263 text.append(buf);
264 printRefsLocked(&text, mStrongRefs);
George Burgess IVe7aa2b22016-03-02 14:02:55 -0800265 snprintf(buf, sizeof(buf),
266 "Weak references on RefBase %p (weakref_type %p):\n",
267 mBase, this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800268 text.append(buf);
269 printRefsLocked(&text, mWeakRefs);
270 }
271
272 {
273 char name[100];
George Burgess IVe7aa2b22016-03-02 14:02:55 -0800274 snprintf(name, sizeof(name), DEBUG_REFS_CALLSTACK_PATH "/%p.stack",
275 this);
Mathias Agopian769828d2013-03-06 17:51:15 -0800276 int rc = open(name, O_RDWR | O_CREAT | O_APPEND, 644);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800277 if (rc >= 0) {
278 write(rc, text.string(), text.length());
279 close(rc);
Steve Blockeb095332011-12-20 16:23:08 +0000280 ALOGD("STACK TRACE for %p saved in %s", this, name);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800281 }
Steve Block1b781ab2012-01-06 19:20:56 +0000282 else ALOGE("FAILED TO PRINT STACK TRACE for %p in %s: %s", this,
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800283 name, strerror(errno));
284 }
285 }
286
287private:
288 struct ref_entry
289 {
290 ref_entry* next;
291 const void* id;
292#if DEBUG_REFS_CALLSTACK_ENABLED
293 CallStack stack;
294#endif
295 int32_t ref;
296 };
297
298 void addRef(ref_entry** refs, const void* id, int32_t mRef)
299 {
300 if (mTrackEnabled) {
301 AutoMutex _l(mMutex);
Mathias Agopianad099652011-08-10 21:07:02 -0700302
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800303 ref_entry* ref = new ref_entry;
304 // Reference count at the time of the snapshot, but before the
305 // update. Positive value means we increment, negative--we
306 // decrement the reference count.
307 ref->ref = mRef;
308 ref->id = id;
309#if DEBUG_REFS_CALLSTACK_ENABLED
310 ref->stack.update(2);
311#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800312 ref->next = *refs;
313 *refs = ref;
314 }
315 }
316
317 void removeRef(ref_entry** refs, const void* id)
318 {
319 if (mTrackEnabled) {
320 AutoMutex _l(mMutex);
321
Mathias Agopianad099652011-08-10 21:07:02 -0700322 ref_entry* const head = *refs;
323 ref_entry* ref = head;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800324 while (ref != NULL) {
325 if (ref->id == id) {
326 *refs = ref->next;
327 delete ref;
328 return;
329 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800330 refs = &ref->next;
331 ref = *refs;
332 }
Mathias Agopianad099652011-08-10 21:07:02 -0700333
Steve Block1b781ab2012-01-06 19:20:56 +0000334 ALOGE("RefBase: removing id %p on RefBase %p"
Mathias Agopianad099652011-08-10 21:07:02 -0700335 "(weakref_type %p) that doesn't exist!",
336 id, mBase, this);
337
338 ref = head;
339 while (ref) {
340 char inc = ref->ref >= 0 ? '+' : '-';
Steve Blockeb095332011-12-20 16:23:08 +0000341 ALOGD("\t%c ID %p (ref %d):", inc, ref->id, ref->ref);
Mathias Agopianad099652011-08-10 21:07:02 -0700342 ref = ref->next;
343 }
344
Mathias Agopiand34a8ca2013-03-21 17:12:40 -0700345 CallStack stack(LOG_TAG);
Mathias Agopianad099652011-08-10 21:07:02 -0700346 }
347 }
348
349 void renameRefsId(ref_entry* r, const void* old_id, const void* new_id)
350 {
351 if (mTrackEnabled) {
352 AutoMutex _l(mMutex);
353 ref_entry* ref = r;
354 while (ref != NULL) {
355 if (ref->id == old_id) {
356 ref->id = new_id;
357 }
358 ref = ref->next;
359 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800360 }
361 }
362
363 void printRefsLocked(String8* out, const ref_entry* refs) const
364 {
365 char buf[128];
366 while (refs) {
367 char inc = refs->ref >= 0 ? '+' : '-';
George Burgess IVe7aa2b22016-03-02 14:02:55 -0800368 snprintf(buf, sizeof(buf), "\t%c ID %p (ref %d):\n",
369 inc, refs->id, refs->ref);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800370 out->append(buf);
371#if DEBUG_REFS_CALLSTACK_ENABLED
372 out->append(refs->stack.toString("\t\t"));
373#else
374 out->append("\t\t(call stacks disabled)");
375#endif
376 refs = refs->next;
377 }
378 }
379
Mathias Agopianad099652011-08-10 21:07:02 -0700380 mutable Mutex mMutex;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800381 ref_entry* mStrongRefs;
382 ref_entry* mWeakRefs;
383
384 bool mTrackEnabled;
385 // Collect stack traces on addref and removeref, instead of deleting the stack references
386 // on removeref that match the address ones.
387 bool mRetain;
388
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800389#endif
390};
391
392// ---------------------------------------------------------------------------
393
394void RefBase::incStrong(const void* id) const
395{
396 weakref_impl* const refs = mRefs;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800397 refs->incWeak(id);
398
399 refs->addStrongRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700400 const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000401 ALOG_ASSERT(c > 0, "incStrong() called on %p after last strong ref", refs);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800402#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000403 ALOGD("incStrong of %p from %p: cnt=%d\n", this, id, c);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800404#endif
405 if (c != INITIAL_STRONG_VALUE) {
406 return;
407 }
408
Hans Boehme263e6c2016-05-11 18:15:12 -0700409 int32_t old = refs->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
410 std::memory_order_relaxed);
411 // A decStrong() must still happen after us.
412 ALOG_ASSERT(old > INITIAL_STRONG_VALUE, "0x%x too small", old);
Mathias Agopianad099652011-08-10 21:07:02 -0700413 refs->mBase->onFirstRef();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800414}
415
416void RefBase::decStrong(const void* id) const
417{
418 weakref_impl* const refs = mRefs;
419 refs->removeStrongRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700420 const int32_t c = refs->mStrong.fetch_sub(1, std::memory_order_release);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800421#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000422 ALOGD("decStrong of %p from %p: cnt=%d\n", this, id, c);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800423#endif
Steve Blockae074452012-01-09 18:35:44 +0000424 ALOG_ASSERT(c >= 1, "decStrong() called on %p too many times", refs);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800425 if (c == 1) {
Hans Boehme263e6c2016-05-11 18:15:12 -0700426 std::atomic_thread_fence(std::memory_order_acquire);
Mathias Agopianad099652011-08-10 21:07:02 -0700427 refs->mBase->onLastStrongRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700428 int32_t flags = refs->mFlags.load(std::memory_order_relaxed);
429 if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
Mathias Agopian9c8fa9e2011-06-15 20:42:47 -0700430 delete this;
Hans Boehme263e6c2016-05-11 18:15:12 -0700431 // Since mStrong had been incremented, the destructor did not
432 // delete refs.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800433 }
434 }
Hans Boehme263e6c2016-05-11 18:15:12 -0700435 // Note that even with only strong reference operations, the thread
436 // deallocating this may not be the same as the thread deallocating refs.
437 // That's OK: all accesses to this happen before its deletion here,
438 // and all accesses to refs happen before its deletion in the final decWeak.
439 // The destructor can safely access mRefs because either it's deleting
440 // mRefs itself, or it's running entirely before the final mWeak decrement.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800441 refs->decWeak(id);
442}
443
444void RefBase::forceIncStrong(const void* id) const
445{
Hans Boehme263e6c2016-05-11 18:15:12 -0700446 // Allows initial mStrong of 0 in addition to INITIAL_STRONG_VALUE.
447 // TODO: Better document assumptions.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800448 weakref_impl* const refs = mRefs;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800449 refs->incWeak(id);
450
451 refs->addStrongRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700452 const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000453 ALOG_ASSERT(c >= 0, "forceIncStrong called on %p after ref count underflow",
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800454 refs);
455#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000456 ALOGD("forceIncStrong of %p from %p: cnt=%d\n", this, id, c);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800457#endif
458
459 switch (c) {
460 case INITIAL_STRONG_VALUE:
Hans Boehme263e6c2016-05-11 18:15:12 -0700461 refs->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
462 std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800463 // fall through...
464 case 0:
Mathias Agopianad099652011-08-10 21:07:02 -0700465 refs->mBase->onFirstRef();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800466 }
467}
468
469int32_t RefBase::getStrongCount() const
470{
Hans Boehme263e6c2016-05-11 18:15:12 -0700471 // Debugging only; No memory ordering guarantees.
472 return mRefs->mStrong.load(std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800473}
474
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800475RefBase* RefBase::weakref_type::refBase() const
476{
477 return static_cast<const weakref_impl*>(this)->mBase;
478}
479
480void RefBase::weakref_type::incWeak(const void* id)
481{
482 weakref_impl* const impl = static_cast<weakref_impl*>(this);
483 impl->addWeakRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700484 const int32_t c __unused = impl->mWeak.fetch_add(1,
485 std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000486 ALOG_ASSERT(c >= 0, "incWeak called on %p after last weak ref", this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800487}
488
Mathias Agopianad099652011-08-10 21:07:02 -0700489
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800490void RefBase::weakref_type::decWeak(const void* id)
491{
492 weakref_impl* const impl = static_cast<weakref_impl*>(this);
493 impl->removeWeakRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700494 const int32_t c = impl->mWeak.fetch_sub(1, std::memory_order_release);
Steve Blockae074452012-01-09 18:35:44 +0000495 ALOG_ASSERT(c >= 1, "decWeak called on %p too many times", this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800496 if (c != 1) return;
Hans Boehme263e6c2016-05-11 18:15:12 -0700497 atomic_thread_fence(std::memory_order_acquire);
Mathias Agopianad099652011-08-10 21:07:02 -0700498
Hans Boehme263e6c2016-05-11 18:15:12 -0700499 int32_t flags = impl->mFlags.load(std::memory_order_relaxed);
500 if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
Mathias Agopianad099652011-08-10 21:07:02 -0700501 // This is the regular lifetime case. The object is destroyed
502 // when the last strong reference goes away. Since weakref_impl
503 // outlive the object, it is not destroyed in the dtor, and
504 // we'll have to do it here.
Hans Boehme263e6c2016-05-11 18:15:12 -0700505 if (impl->mStrong.load(std::memory_order_relaxed)
506 == INITIAL_STRONG_VALUE) {
Mathias Agopianad099652011-08-10 21:07:02 -0700507 // Special case: we never had a strong reference, so we need to
508 // destroy the object now.
Mathias Agopian9c8fa9e2011-06-15 20:42:47 -0700509 delete impl->mBase;
Mathias Agopianad099652011-08-10 21:07:02 -0700510 } else {
Steve Blockb37fbe92011-10-20 11:56:00 +0100511 // ALOGV("Freeing refs %p of old RefBase %p\n", this, impl->mBase);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800512 delete impl;
513 }
514 } else {
Hans Boehme263e6c2016-05-11 18:15:12 -0700515 // This is the OBJECT_LIFETIME_WEAK case. The last weak-reference
516 // is gone, we can destroy the object.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800517 impl->mBase->onLastWeakRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700518 delete impl->mBase;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800519 }
520}
521
522bool RefBase::weakref_type::attemptIncStrong(const void* id)
523{
524 incWeak(id);
525
526 weakref_impl* const impl = static_cast<weakref_impl*>(this);
Hans Boehme263e6c2016-05-11 18:15:12 -0700527 int32_t curCount = impl->mStrong.load(std::memory_order_relaxed);
Dianne Hackborna729ab12013-03-14 15:26:30 -0700528
529 ALOG_ASSERT(curCount >= 0,
530 "attemptIncStrong called on %p after underflow", this);
531
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800532 while (curCount > 0 && curCount != INITIAL_STRONG_VALUE) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700533 // we're in the easy/common case of promoting a weak-reference
534 // from an existing strong reference.
Hans Boehme263e6c2016-05-11 18:15:12 -0700535 if (impl->mStrong.compare_exchange_weak(curCount, curCount+1,
536 std::memory_order_relaxed)) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800537 break;
538 }
Dianne Hackborna729ab12013-03-14 15:26:30 -0700539 // the strong count has changed on us, we need to re-assert our
Hans Boehme263e6c2016-05-11 18:15:12 -0700540 // situation. curCount was updated by compare_exchange_weak.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800541 }
542
543 if (curCount <= 0 || curCount == INITIAL_STRONG_VALUE) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700544 // we're now in the harder case of either:
545 // - there never was a strong reference on us
546 // - or, all strong references have been released
Hans Boehme263e6c2016-05-11 18:15:12 -0700547 int32_t flags = impl->mFlags.load(std::memory_order_relaxed);
548 if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700549 // this object has a "normal" life-time, i.e.: it gets destroyed
550 // when the last strong reference goes away
551 if (curCount <= 0) {
552 // the last strong-reference got released, the object cannot
553 // be revived.
554 decWeak(id);
555 return false;
556 }
557
558 // here, curCount == INITIAL_STRONG_VALUE, which means
559 // there never was a strong-reference, so we can try to
560 // promote this object; we need to do that atomically.
561 while (curCount > 0) {
Hans Boehme263e6c2016-05-11 18:15:12 -0700562 if (impl->mStrong.compare_exchange_weak(curCount, curCount+1,
563 std::memory_order_relaxed)) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700564 break;
565 }
566 // the strong count has changed on us, we need to re-assert our
567 // situation (e.g.: another thread has inc/decStrong'ed us)
Hans Boehme263e6c2016-05-11 18:15:12 -0700568 // curCount has been updated.
Dianne Hackborna729ab12013-03-14 15:26:30 -0700569 }
570
571 if (curCount <= 0) {
572 // promote() failed, some other thread destroyed us in the
573 // meantime (i.e.: strong count reached zero).
574 decWeak(id);
575 return false;
576 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800577 } else {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700578 // this object has an "extended" life-time, i.e.: it can be
579 // revived from a weak-reference only.
580 // Ask the object's implementation if it agrees to be revived
581 if (!impl->mBase->onIncStrongAttempted(FIRST_INC_STRONG, id)) {
582 // it didn't so give-up.
583 decWeak(id);
584 return false;
585 }
586 // grab a strong-reference, which is always safe due to the
587 // extended life-time.
Hans Boehme263e6c2016-05-11 18:15:12 -0700588 curCount = impl->mStrong.fetch_add(1, std::memory_order_relaxed);
Hans Boehm7f27cbc2016-07-29 14:39:10 -0700589 // If the strong reference count has already been incremented by
590 // someone else, the implementor of onIncStrongAttempted() is holding
591 // an unneeded reference. So call onLastStrongRef() here to remove it.
592 // (No, this is not pretty.) Note that we MUST NOT do this if we
593 // are in fact acquiring the first reference.
594 if (curCount != 0 && curCount != INITIAL_STRONG_VALUE) {
595 impl->mBase->onLastStrongRef(id);
596 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800597 }
598 }
599
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800600 impl->addStrongRef(id);
601
602#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000603 ALOGD("attemptIncStrong of %p from %p: cnt=%d\n", this, id, curCount);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800604#endif
605
Hans Boehm7f27cbc2016-07-29 14:39:10 -0700606 // curCount is the value of mStrong before we incremented it.
Hans Boehme263e6c2016-05-11 18:15:12 -0700607 // Now we need to fix-up the count if it was INITIAL_STRONG_VALUE.
608 // This must be done safely, i.e.: handle the case where several threads
Dianne Hackborna729ab12013-03-14 15:26:30 -0700609 // were here in attemptIncStrong().
Hans Boehme263e6c2016-05-11 18:15:12 -0700610 // curCount > INITIAL_STRONG_VALUE is OK, and can happen if we're doing
611 // this in the middle of another incStrong. The subtraction is handled
612 // by the thread that started with INITIAL_STRONG_VALUE.
613 if (curCount == INITIAL_STRONG_VALUE) {
614 impl->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
615 std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800616 }
Dianne Hackborna729ab12013-03-14 15:26:30 -0700617
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800618 return true;
619}
620
621bool RefBase::weakref_type::attemptIncWeak(const void* id)
622{
623 weakref_impl* const impl = static_cast<weakref_impl*>(this);
Mathias Agopianad099652011-08-10 21:07:02 -0700624
Hans Boehme263e6c2016-05-11 18:15:12 -0700625 int32_t curCount = impl->mWeak.load(std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000626 ALOG_ASSERT(curCount >= 0, "attemptIncWeak called on %p after underflow",
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800627 this);
628 while (curCount > 0) {
Hans Boehme263e6c2016-05-11 18:15:12 -0700629 if (impl->mWeak.compare_exchange_weak(curCount, curCount+1,
630 std::memory_order_relaxed)) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800631 break;
632 }
Hans Boehme263e6c2016-05-11 18:15:12 -0700633 // curCount has been updated.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800634 }
635
636 if (curCount > 0) {
637 impl->addWeakRef(id);
638 }
639
640 return curCount > 0;
641}
642
643int32_t RefBase::weakref_type::getWeakCount() const
644{
Hans Boehme263e6c2016-05-11 18:15:12 -0700645 // Debug only!
646 return static_cast<const weakref_impl*>(this)->mWeak
647 .load(std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800648}
649
650void RefBase::weakref_type::printRefs() const
651{
652 static_cast<const weakref_impl*>(this)->printRefs();
653}
654
655void RefBase::weakref_type::trackMe(bool enable, bool retain)
656{
Mathias Agopianad099652011-08-10 21:07:02 -0700657 static_cast<weakref_impl*>(this)->trackMe(enable, retain);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800658}
659
660RefBase::weakref_type* RefBase::createWeak(const void* id) const
661{
662 mRefs->incWeak(id);
663 return mRefs;
664}
665
666RefBase::weakref_type* RefBase::getWeakRefs() const
667{
668 return mRefs;
669}
670
671RefBase::RefBase()
672 : mRefs(new weakref_impl(this))
673{
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800674}
675
676RefBase::~RefBase()
677{
Hans Boehme263e6c2016-05-11 18:15:12 -0700678 if (mRefs->mStrong.load(std::memory_order_relaxed)
679 == INITIAL_STRONG_VALUE) {
Hans Boehm9ba71922016-07-21 18:56:55 -0700680 // We never acquired a strong reference on this object.
681 // We assume there are no outstanding weak references.
Mathias Agopian9c8fa9e2011-06-15 20:42:47 -0700682 delete mRefs;
Mathias Agopianad099652011-08-10 21:07:02 -0700683 } else {
Hans Boehme263e6c2016-05-11 18:15:12 -0700684 // life-time of this object is extended to WEAK, in
Mathias Agopianad099652011-08-10 21:07:02 -0700685 // which case weakref_impl doesn't out-live the object and we
686 // can free it now.
Hans Boehme263e6c2016-05-11 18:15:12 -0700687 int32_t flags = mRefs->mFlags.load(std::memory_order_relaxed);
688 if ((flags & OBJECT_LIFETIME_MASK) != OBJECT_LIFETIME_STRONG) {
Mathias Agopianad099652011-08-10 21:07:02 -0700689 // It's possible that the weak count is not 0 if the object
690 // re-acquired a weak reference in its destructor
Hans Boehme263e6c2016-05-11 18:15:12 -0700691 if (mRefs->mWeak.load(std::memory_order_relaxed) == 0) {
Mathias Agopianad099652011-08-10 21:07:02 -0700692 delete mRefs;
693 }
694 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800695 }
Mathias Agopianad099652011-08-10 21:07:02 -0700696 // for debugging purposes, clear this.
697 const_cast<weakref_impl*&>(mRefs) = NULL;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800698}
699
700void RefBase::extendObjectLifetime(int32_t mode)
701{
Hans Boehme263e6c2016-05-11 18:15:12 -0700702 // Must be happens-before ordered with respect to construction or any
703 // operation that could destroy the object.
704 mRefs->mFlags.fetch_or(mode, std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800705}
706
707void RefBase::onFirstRef()
708{
709}
710
711void RefBase::onLastStrongRef(const void* /*id*/)
712{
713}
714
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700715bool RefBase::onIncStrongAttempted(uint32_t flags, const void* /*id*/)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800716{
717 return (flags&FIRST_INC_STRONG) ? true : false;
718}
719
720void RefBase::onLastWeakRef(const void* /*id*/)
721{
722}
Mathias Agopianad099652011-08-10 21:07:02 -0700723
724// ---------------------------------------------------------------------------
725
Mathias Agopianad099652011-08-10 21:07:02 -0700726#if DEBUG_REFS
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700727void RefBase::renameRefs(size_t n, const ReferenceRenamer& renamer) {
Mathias Agopianad099652011-08-10 21:07:02 -0700728 for (size_t i=0 ; i<n ; i++) {
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700729 renamer(i);
Mathias Agopianad099652011-08-10 21:07:02 -0700730 }
Mathias Agopianad099652011-08-10 21:07:02 -0700731}
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700732#else
733void RefBase::renameRefs(size_t /*n*/, const ReferenceRenamer& /*renamer*/) { }
734#endif
Mathias Agopianad099652011-08-10 21:07:02 -0700735
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700736void RefBase::renameRefId(weakref_type* ref,
737 const void* old_id, const void* new_id) {
738 weakref_impl* const impl = static_cast<weakref_impl*>(ref);
739 impl->renameStrongRefId(old_id, new_id);
740 impl->renameWeakRefId(old_id, new_id);
741}
742
743void RefBase::renameRefId(RefBase* ref,
744 const void* old_id, const void* new_id) {
745 ref->mRefs->renameStrongRefId(old_id, new_id);
746 ref->mRefs->renameWeakRefId(old_id, new_id);
747}
748
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800749}; // namespace android