blob: 085b314c1ea629d1cda738363b6c863a24dd36bf [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 Boehme263e6c2016-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 Boehme263e6c2016-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
Chih-Hung Hsieh1c563d92016-04-29 15:44:04 -0700135 explicit weakref_impl(RefBase* base)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800136 : 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 Boehme263e6c2016-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 Boehme263e6c2016-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 Boehme263e6c2016-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 Boehme263e6c2016-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];
George Burgess IVe7aa2b22016-03-02 14:02:55 -0800254 snprintf(buf, sizeof(buf),
255 "Strong references on RefBase %p (weakref_type %p):\n",
256 mBase, this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800257 text.append(buf);
258 printRefsLocked(&text, mStrongRefs);
George Burgess IVe7aa2b22016-03-02 14:02:55 -0800259 snprintf(buf, sizeof(buf),
260 "Weak references on RefBase %p (weakref_type %p):\n",
261 mBase, this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800262 text.append(buf);
263 printRefsLocked(&text, mWeakRefs);
264 }
265
266 {
267 char name[100];
George Burgess IVe7aa2b22016-03-02 14:02:55 -0800268 snprintf(name, sizeof(name), DEBUG_REFS_CALLSTACK_PATH "/%p.stack",
269 this);
Mathias Agopian769828d2013-03-06 17:51:15 -0800270 int rc = open(name, O_RDWR | O_CREAT | O_APPEND, 644);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800271 if (rc >= 0) {
272 write(rc, text.string(), text.length());
273 close(rc);
Steve Blockeb095332011-12-20 16:23:08 +0000274 ALOGD("STACK TRACE for %p saved in %s", this, name);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800275 }
Steve Block1b781ab2012-01-06 19:20:56 +0000276 else ALOGE("FAILED TO PRINT STACK TRACE for %p in %s: %s", this,
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800277 name, strerror(errno));
278 }
279 }
280
281private:
282 struct ref_entry
283 {
284 ref_entry* next;
285 const void* id;
286#if DEBUG_REFS_CALLSTACK_ENABLED
287 CallStack stack;
288#endif
289 int32_t ref;
290 };
291
292 void addRef(ref_entry** refs, const void* id, int32_t mRef)
293 {
294 if (mTrackEnabled) {
295 AutoMutex _l(mMutex);
Mathias Agopianad099652011-08-10 21:07:02 -0700296
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800297 ref_entry* ref = new ref_entry;
298 // Reference count at the time of the snapshot, but before the
299 // update. Positive value means we increment, negative--we
300 // decrement the reference count.
301 ref->ref = mRef;
302 ref->id = id;
303#if DEBUG_REFS_CALLSTACK_ENABLED
304 ref->stack.update(2);
305#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800306 ref->next = *refs;
307 *refs = ref;
308 }
309 }
310
311 void removeRef(ref_entry** refs, const void* id)
312 {
313 if (mTrackEnabled) {
314 AutoMutex _l(mMutex);
315
Mathias Agopianad099652011-08-10 21:07:02 -0700316 ref_entry* const head = *refs;
317 ref_entry* ref = head;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800318 while (ref != NULL) {
319 if (ref->id == id) {
320 *refs = ref->next;
321 delete ref;
322 return;
323 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800324 refs = &ref->next;
325 ref = *refs;
326 }
Mathias Agopianad099652011-08-10 21:07:02 -0700327
Steve Block1b781ab2012-01-06 19:20:56 +0000328 ALOGE("RefBase: removing id %p on RefBase %p"
Mathias Agopianad099652011-08-10 21:07:02 -0700329 "(weakref_type %p) that doesn't exist!",
330 id, mBase, this);
331
332 ref = head;
333 while (ref) {
334 char inc = ref->ref >= 0 ? '+' : '-';
Steve Blockeb095332011-12-20 16:23:08 +0000335 ALOGD("\t%c ID %p (ref %d):", inc, ref->id, ref->ref);
Mathias Agopianad099652011-08-10 21:07:02 -0700336 ref = ref->next;
337 }
338
Mathias Agopiand34a8ca2013-03-21 17:12:40 -0700339 CallStack stack(LOG_TAG);
Mathias Agopianad099652011-08-10 21:07:02 -0700340 }
341 }
342
343 void renameRefsId(ref_entry* r, const void* old_id, const void* new_id)
344 {
345 if (mTrackEnabled) {
346 AutoMutex _l(mMutex);
347 ref_entry* ref = r;
348 while (ref != NULL) {
349 if (ref->id == old_id) {
350 ref->id = new_id;
351 }
352 ref = ref->next;
353 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800354 }
355 }
356
357 void printRefsLocked(String8* out, const ref_entry* refs) const
358 {
359 char buf[128];
360 while (refs) {
361 char inc = refs->ref >= 0 ? '+' : '-';
George Burgess IVe7aa2b22016-03-02 14:02:55 -0800362 snprintf(buf, sizeof(buf), "\t%c ID %p (ref %d):\n",
363 inc, refs->id, refs->ref);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800364 out->append(buf);
365#if DEBUG_REFS_CALLSTACK_ENABLED
366 out->append(refs->stack.toString("\t\t"));
367#else
368 out->append("\t\t(call stacks disabled)");
369#endif
370 refs = refs->next;
371 }
372 }
373
Mathias Agopianad099652011-08-10 21:07:02 -0700374 mutable Mutex mMutex;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800375 ref_entry* mStrongRefs;
376 ref_entry* mWeakRefs;
377
378 bool mTrackEnabled;
379 // Collect stack traces on addref and removeref, instead of deleting the stack references
380 // on removeref that match the address ones.
381 bool mRetain;
382
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800383#endif
384};
385
386// ---------------------------------------------------------------------------
387
388void RefBase::incStrong(const void* id) const
389{
390 weakref_impl* const refs = mRefs;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800391 refs->incWeak(id);
392
393 refs->addStrongRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700394 const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000395 ALOG_ASSERT(c > 0, "incStrong() called on %p after last strong ref", refs);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800396#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000397 ALOGD("incStrong of %p from %p: cnt=%d\n", this, id, c);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800398#endif
399 if (c != INITIAL_STRONG_VALUE) {
400 return;
401 }
402
Hans Boehme263e6c2016-05-11 18:15:12 -0700403 int32_t old = refs->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
404 std::memory_order_relaxed);
405 // A decStrong() must still happen after us.
406 ALOG_ASSERT(old > INITIAL_STRONG_VALUE, "0x%x too small", old);
Mathias Agopianad099652011-08-10 21:07:02 -0700407 refs->mBase->onFirstRef();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800408}
409
410void RefBase::decStrong(const void* id) const
411{
412 weakref_impl* const refs = mRefs;
413 refs->removeStrongRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700414 const int32_t c = refs->mStrong.fetch_sub(1, std::memory_order_release);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800415#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000416 ALOGD("decStrong of %p from %p: cnt=%d\n", this, id, c);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800417#endif
Steve Blockae074452012-01-09 18:35:44 +0000418 ALOG_ASSERT(c >= 1, "decStrong() called on %p too many times", refs);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800419 if (c == 1) {
Hans Boehme263e6c2016-05-11 18:15:12 -0700420 std::atomic_thread_fence(std::memory_order_acquire);
Mathias Agopianad099652011-08-10 21:07:02 -0700421 refs->mBase->onLastStrongRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700422 int32_t flags = refs->mFlags.load(std::memory_order_relaxed);
423 if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
Mathias Agopian9c8fa9e2011-06-15 20:42:47 -0700424 delete this;
Hans Boehme263e6c2016-05-11 18:15:12 -0700425 // Since mStrong had been incremented, the destructor did not
426 // delete refs.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800427 }
428 }
Hans Boehme263e6c2016-05-11 18:15:12 -0700429 // Note that even with only strong reference operations, the thread
430 // deallocating this may not be the same as the thread deallocating refs.
431 // That's OK: all accesses to this happen before its deletion here,
432 // and all accesses to refs happen before its deletion in the final decWeak.
433 // The destructor can safely access mRefs because either it's deleting
434 // mRefs itself, or it's running entirely before the final mWeak decrement.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800435 refs->decWeak(id);
436}
437
438void RefBase::forceIncStrong(const void* id) const
439{
Hans Boehme263e6c2016-05-11 18:15:12 -0700440 // Allows initial mStrong of 0 in addition to INITIAL_STRONG_VALUE.
441 // TODO: Better document assumptions.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800442 weakref_impl* const refs = mRefs;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800443 refs->incWeak(id);
444
445 refs->addStrongRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700446 const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000447 ALOG_ASSERT(c >= 0, "forceIncStrong called on %p after ref count underflow",
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800448 refs);
449#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000450 ALOGD("forceIncStrong of %p from %p: cnt=%d\n", this, id, c);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800451#endif
452
453 switch (c) {
454 case INITIAL_STRONG_VALUE:
Hans Boehme263e6c2016-05-11 18:15:12 -0700455 refs->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
456 std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800457 // fall through...
458 case 0:
Mathias Agopianad099652011-08-10 21:07:02 -0700459 refs->mBase->onFirstRef();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800460 }
461}
462
463int32_t RefBase::getStrongCount() const
464{
Hans Boehme263e6c2016-05-11 18:15:12 -0700465 // Debugging only; No memory ordering guarantees.
466 return mRefs->mStrong.load(std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800467}
468
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800469RefBase* RefBase::weakref_type::refBase() const
470{
471 return static_cast<const weakref_impl*>(this)->mBase;
472}
473
474void RefBase::weakref_type::incWeak(const void* id)
475{
476 weakref_impl* const impl = static_cast<weakref_impl*>(this);
477 impl->addWeakRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700478 const int32_t c __unused = impl->mWeak.fetch_add(1,
479 std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000480 ALOG_ASSERT(c >= 0, "incWeak called on %p after last weak ref", this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800481}
482
Mathias Agopianad099652011-08-10 21:07:02 -0700483
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800484void RefBase::weakref_type::decWeak(const void* id)
485{
486 weakref_impl* const impl = static_cast<weakref_impl*>(this);
487 impl->removeWeakRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700488 const int32_t c = impl->mWeak.fetch_sub(1, std::memory_order_release);
Steve Blockae074452012-01-09 18:35:44 +0000489 ALOG_ASSERT(c >= 1, "decWeak called on %p too many times", this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800490 if (c != 1) return;
Hans Boehme263e6c2016-05-11 18:15:12 -0700491 atomic_thread_fence(std::memory_order_acquire);
Mathias Agopianad099652011-08-10 21:07:02 -0700492
Hans Boehme263e6c2016-05-11 18:15:12 -0700493 int32_t flags = impl->mFlags.load(std::memory_order_relaxed);
494 if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
Mathias Agopianad099652011-08-10 21:07:02 -0700495 // This is the regular lifetime case. The object is destroyed
496 // when the last strong reference goes away. Since weakref_impl
497 // outlive the object, it is not destroyed in the dtor, and
498 // we'll have to do it here.
Hans Boehme263e6c2016-05-11 18:15:12 -0700499 if (impl->mStrong.load(std::memory_order_relaxed)
500 == INITIAL_STRONG_VALUE) {
Mathias Agopianad099652011-08-10 21:07:02 -0700501 // Special case: we never had a strong reference, so we need to
502 // destroy the object now.
Mathias Agopian9c8fa9e2011-06-15 20:42:47 -0700503 delete impl->mBase;
Mathias Agopianad099652011-08-10 21:07:02 -0700504 } else {
Steve Blockb37fbe92011-10-20 11:56:00 +0100505 // ALOGV("Freeing refs %p of old RefBase %p\n", this, impl->mBase);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800506 delete impl;
507 }
508 } else {
Hans Boehme263e6c2016-05-11 18:15:12 -0700509 // This is the OBJECT_LIFETIME_WEAK case. The last weak-reference
510 // is gone, we can destroy the object.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800511 impl->mBase->onLastWeakRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700512 delete impl->mBase;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800513 }
514}
515
516bool RefBase::weakref_type::attemptIncStrong(const void* id)
517{
518 incWeak(id);
519
520 weakref_impl* const impl = static_cast<weakref_impl*>(this);
Hans Boehme263e6c2016-05-11 18:15:12 -0700521 int32_t curCount = impl->mStrong.load(std::memory_order_relaxed);
Dianne Hackborna729ab12013-03-14 15:26:30 -0700522
523 ALOG_ASSERT(curCount >= 0,
524 "attemptIncStrong called on %p after underflow", this);
525
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800526 while (curCount > 0 && curCount != INITIAL_STRONG_VALUE) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700527 // we're in the easy/common case of promoting a weak-reference
528 // from an existing strong reference.
Hans Boehme263e6c2016-05-11 18:15:12 -0700529 if (impl->mStrong.compare_exchange_weak(curCount, curCount+1,
530 std::memory_order_relaxed)) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800531 break;
532 }
Dianne Hackborna729ab12013-03-14 15:26:30 -0700533 // the strong count has changed on us, we need to re-assert our
Hans Boehme263e6c2016-05-11 18:15:12 -0700534 // situation. curCount was updated by compare_exchange_weak.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800535 }
536
537 if (curCount <= 0 || curCount == INITIAL_STRONG_VALUE) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700538 // we're now in the harder case of either:
539 // - there never was a strong reference on us
540 // - or, all strong references have been released
Hans Boehme263e6c2016-05-11 18:15:12 -0700541 int32_t flags = impl->mFlags.load(std::memory_order_relaxed);
542 if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700543 // this object has a "normal" life-time, i.e.: it gets destroyed
544 // when the last strong reference goes away
545 if (curCount <= 0) {
546 // the last strong-reference got released, the object cannot
547 // be revived.
548 decWeak(id);
549 return false;
550 }
551
552 // here, curCount == INITIAL_STRONG_VALUE, which means
553 // there never was a strong-reference, so we can try to
554 // promote this object; we need to do that atomically.
555 while (curCount > 0) {
Hans Boehme263e6c2016-05-11 18:15:12 -0700556 if (impl->mStrong.compare_exchange_weak(curCount, curCount+1,
557 std::memory_order_relaxed)) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700558 break;
559 }
560 // the strong count has changed on us, we need to re-assert our
561 // situation (e.g.: another thread has inc/decStrong'ed us)
Hans Boehme263e6c2016-05-11 18:15:12 -0700562 // curCount has been updated.
Dianne Hackborna729ab12013-03-14 15:26:30 -0700563 }
564
565 if (curCount <= 0) {
566 // promote() failed, some other thread destroyed us in the
567 // meantime (i.e.: strong count reached zero).
568 decWeak(id);
569 return false;
570 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800571 } else {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700572 // this object has an "extended" life-time, i.e.: it can be
573 // revived from a weak-reference only.
574 // Ask the object's implementation if it agrees to be revived
575 if (!impl->mBase->onIncStrongAttempted(FIRST_INC_STRONG, id)) {
576 // it didn't so give-up.
577 decWeak(id);
578 return false;
579 }
580 // grab a strong-reference, which is always safe due to the
581 // extended life-time.
Hans Boehme263e6c2016-05-11 18:15:12 -0700582 curCount = impl->mStrong.fetch_add(1, std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800583 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800584
585 // If the strong reference count has already been incremented by
586 // someone else, the implementor of onIncStrongAttempted() is holding
587 // an unneeded reference. So call onLastStrongRef() here to remove it.
588 // (No, this is not pretty.) Note that we MUST NOT do this if we
589 // are in fact acquiring the first reference.
590 if (curCount > 0 && curCount < INITIAL_STRONG_VALUE) {
591 impl->mBase->onLastStrongRef(id);
592 }
593 }
594
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800595 impl->addStrongRef(id);
596
597#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000598 ALOGD("attemptIncStrong of %p from %p: cnt=%d\n", this, id, curCount);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800599#endif
600
Hans Boehme263e6c2016-05-11 18:15:12 -0700601 // curCount is the value of mStrong before we increment ed it.
602 // Now we need to fix-up the count if it was INITIAL_STRONG_VALUE.
603 // This must be done safely, i.e.: handle the case where several threads
Dianne Hackborna729ab12013-03-14 15:26:30 -0700604 // were here in attemptIncStrong().
Hans Boehme263e6c2016-05-11 18:15:12 -0700605 // curCount > INITIAL_STRONG_VALUE is OK, and can happen if we're doing
606 // this in the middle of another incStrong. The subtraction is handled
607 // by the thread that started with INITIAL_STRONG_VALUE.
608 if (curCount == INITIAL_STRONG_VALUE) {
609 impl->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
610 std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800611 }
Dianne Hackborna729ab12013-03-14 15:26:30 -0700612
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800613 return true;
614}
615
616bool RefBase::weakref_type::attemptIncWeak(const void* id)
617{
618 weakref_impl* const impl = static_cast<weakref_impl*>(this);
Mathias Agopianad099652011-08-10 21:07:02 -0700619
Hans Boehme263e6c2016-05-11 18:15:12 -0700620 int32_t curCount = impl->mWeak.load(std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000621 ALOG_ASSERT(curCount >= 0, "attemptIncWeak called on %p after underflow",
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800622 this);
623 while (curCount > 0) {
Hans Boehme263e6c2016-05-11 18:15:12 -0700624 if (impl->mWeak.compare_exchange_weak(curCount, curCount+1,
625 std::memory_order_relaxed)) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800626 break;
627 }
Hans Boehme263e6c2016-05-11 18:15:12 -0700628 // curCount has been updated.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800629 }
630
631 if (curCount > 0) {
632 impl->addWeakRef(id);
633 }
634
635 return curCount > 0;
636}
637
638int32_t RefBase::weakref_type::getWeakCount() const
639{
Hans Boehme263e6c2016-05-11 18:15:12 -0700640 // Debug only!
641 return static_cast<const weakref_impl*>(this)->mWeak
642 .load(std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800643}
644
645void RefBase::weakref_type::printRefs() const
646{
647 static_cast<const weakref_impl*>(this)->printRefs();
648}
649
650void RefBase::weakref_type::trackMe(bool enable, bool retain)
651{
Mathias Agopianad099652011-08-10 21:07:02 -0700652 static_cast<weakref_impl*>(this)->trackMe(enable, retain);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800653}
654
655RefBase::weakref_type* RefBase::createWeak(const void* id) const
656{
657 mRefs->incWeak(id);
658 return mRefs;
659}
660
661RefBase::weakref_type* RefBase::getWeakRefs() const
662{
663 return mRefs;
664}
665
666RefBase::RefBase()
667 : mRefs(new weakref_impl(this))
668{
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800669}
670
671RefBase::~RefBase()
672{
Hans Boehme263e6c2016-05-11 18:15:12 -0700673 if (mRefs->mStrong.load(std::memory_order_relaxed)
674 == INITIAL_STRONG_VALUE) {
Mathias Agopianad099652011-08-10 21:07:02 -0700675 // we never acquired a strong (and/or weak) reference on this object.
Mathias Agopian9c8fa9e2011-06-15 20:42:47 -0700676 delete mRefs;
Mathias Agopianad099652011-08-10 21:07:02 -0700677 } else {
Hans Boehme263e6c2016-05-11 18:15:12 -0700678 // life-time of this object is extended to WEAK, in
Mathias Agopianad099652011-08-10 21:07:02 -0700679 // which case weakref_impl doesn't out-live the object and we
680 // can free it now.
Hans Boehme263e6c2016-05-11 18:15:12 -0700681 int32_t flags = mRefs->mFlags.load(std::memory_order_relaxed);
682 if ((flags & OBJECT_LIFETIME_MASK) != OBJECT_LIFETIME_STRONG) {
Mathias Agopianad099652011-08-10 21:07:02 -0700683 // It's possible that the weak count is not 0 if the object
684 // re-acquired a weak reference in its destructor
Hans Boehme263e6c2016-05-11 18:15:12 -0700685 if (mRefs->mWeak.load(std::memory_order_relaxed) == 0) {
Mathias Agopianad099652011-08-10 21:07:02 -0700686 delete mRefs;
687 }
688 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800689 }
Mathias Agopianad099652011-08-10 21:07:02 -0700690 // for debugging purposes, clear this.
691 const_cast<weakref_impl*&>(mRefs) = NULL;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800692}
693
694void RefBase::extendObjectLifetime(int32_t mode)
695{
Hans Boehme263e6c2016-05-11 18:15:12 -0700696 // Must be happens-before ordered with respect to construction or any
697 // operation that could destroy the object.
698 mRefs->mFlags.fetch_or(mode, std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800699}
700
701void RefBase::onFirstRef()
702{
703}
704
705void RefBase::onLastStrongRef(const void* /*id*/)
706{
707}
708
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700709bool RefBase::onIncStrongAttempted(uint32_t flags, const void* /*id*/)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800710{
711 return (flags&FIRST_INC_STRONG) ? true : false;
712}
713
714void RefBase::onLastWeakRef(const void* /*id*/)
715{
716}
Mathias Agopianad099652011-08-10 21:07:02 -0700717
718// ---------------------------------------------------------------------------
719
Mathias Agopianad099652011-08-10 21:07:02 -0700720#if DEBUG_REFS
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700721void RefBase::renameRefs(size_t n, const ReferenceRenamer& renamer) {
Mathias Agopianad099652011-08-10 21:07:02 -0700722 for (size_t i=0 ; i<n ; i++) {
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700723 renamer(i);
Mathias Agopianad099652011-08-10 21:07:02 -0700724 }
Mathias Agopianad099652011-08-10 21:07:02 -0700725}
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700726#else
727void RefBase::renameRefs(size_t /*n*/, const ReferenceRenamer& /*renamer*/) { }
728#endif
Mathias Agopianad099652011-08-10 21:07:02 -0700729
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700730void RefBase::renameRefId(weakref_type* ref,
731 const void* old_id, const void* new_id) {
732 weakref_impl* const impl = static_cast<weakref_impl*>(ref);
733 impl->renameStrongRefId(old_id, new_id);
734 impl->renameWeakRefId(old_id, new_id);
735}
736
737void RefBase::renameRefId(RefBase* ref,
738 const void* old_id, const void* new_id) {
739 ref->mRefs->renameStrongRefId(old_id, new_id);
740 ref->mRefs->renameWeakRefId(old_id, new_id);
741}
742
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800743}; // namespace android