blob: 3f1e79a04b1e2d4b0bd79895477eb4c5845ff204 [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
Hans Boehm2a019ec2018-08-07 23:45:25 +000020#include <memory>
21
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080022#include <utils/RefBase.h>
23
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080024#include <utils/CallStack.h>
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080025
Hans Boehm2a019ec2018-08-07 23:45:25 +000026#include <utils/Mutex.h>
27
Mark Salyzyn5bed8032014-04-30 11:10:46 -070028#ifndef __unused
29#define __unused __attribute__((__unused__))
30#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080031
Hans Boehm2a019ec2018-08-07 23:45:25 +000032// Compile with refcounting debugging enabled.
33#define DEBUG_REFS 0
34
35// The following three are ignored unless DEBUG_REFS is set.
Mathias Agopian6d4419d2013-03-18 20:31:18 -070036
37// whether ref-tracking is enabled by default, if not, trackMe(true, false)
38// needs to be called explicitly
Hans Boehm2a019ec2018-08-07 23:45:25 +000039#define DEBUG_REFS_ENABLED_BY_DEFAULT 0
Mathias Agopian6d4419d2013-03-18 20:31:18 -070040
41// whether callstack are collected (significantly slows things down)
Hans Boehm2a019ec2018-08-07 23:45:25 +000042#define DEBUG_REFS_CALLSTACK_ENABLED 1
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080043
Mathias Agopian6d4419d2013-03-18 20:31:18 -070044// folder where stack traces are saved when DEBUG_REFS is enabled
45// this folder needs to exist and be writable
Hans Boehm2a019ec2018-08-07 23:45:25 +000046#define DEBUG_REFS_CALLSTACK_PATH "/data/debug"
Mathias Agopian6d4419d2013-03-18 20:31:18 -070047
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080048// log all reference counting operations
Hans Boehm2a019ec2018-08-07 23:45:25 +000049#define PRINT_REFS 0
50
51// Continue after logging a stack trace if ~RefBase discovers that reference
52// count has never been incremented. Normally we conspicuously crash in that
53// case.
54#define DEBUG_REFBASE_DESTRUCTION 1
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080055
56// ---------------------------------------------------------------------------
57
58namespace android {
59
Hans Boehm9ba71922016-07-21 18:56:55 -070060// Observations, invariants, etc:
Hans Boehme263e6c2016-05-11 18:15:12 -070061
Hans Boehm9ba71922016-07-21 18:56:55 -070062// By default, obects are destroyed when the last strong reference disappears
63// or, if the object never had a strong reference, when the last weak reference
64// disappears.
65//
Hans Boehme263e6c2016-05-11 18:15:12 -070066// OBJECT_LIFETIME_WEAK changes this behavior to retain the object
67// unconditionally until the last reference of either kind disappears. The
68// client ensures that the extendObjectLifetime call happens before the dec
69// call that would otherwise have deallocated the object, or before an
70// attemptIncStrong call that might rely on it. We do not worry about
71// concurrent changes to the object lifetime.
Hans Boehm9ba71922016-07-21 18:56:55 -070072//
73// AttemptIncStrong will succeed if the object has a strong reference, or if it
74// has a weak reference and has never had a strong reference.
75// AttemptIncWeak really does succeed only if there is already a WEAK
76// reference, and thus may fail when attemptIncStrong would succeed.
77//
Hans Boehme263e6c2016-05-11 18:15:12 -070078// mStrong is the strong reference count. mWeak is the weak reference count.
79// Between calls, and ignoring memory ordering effects, mWeak includes strong
80// references, and is thus >= mStrong.
81//
Hans Boehm9ba71922016-07-21 18:56:55 -070082// A weakref_impl holds all the information, including both reference counts,
83// required to perform wp<> operations. Thus these can continue to be performed
84// after the RefBase object has been destroyed.
85//
Hans Boehme263e6c2016-05-11 18:15:12 -070086// A weakref_impl is allocated as the value of mRefs in a RefBase object on
87// construction.
Hans Boehm23c857e2016-08-02 18:39:30 -070088// In the OBJECT_LIFETIME_STRONG case, it is normally deallocated in decWeak,
89// and hence lives as long as the last weak reference. (It can also be
90// deallocated in the RefBase destructor iff the strong reference count was
91// never incremented and the weak count is zero, e.g. if the RefBase object is
92// explicitly destroyed without decrementing the strong count. This should be
93// avoided.) In this case, the RefBase destructor should be invoked from
94// decStrong.
95// In the OBJECT_LIFETIME_WEAK case, the weakref_impl is always deallocated in
96// the RefBase destructor, which is always invoked by decWeak. DecStrong
97// explicitly avoids the deletion in this case.
Hans Boehme263e6c2016-05-11 18:15:12 -070098//
99// Memory ordering:
100// The client must ensure that every inc() call, together with all other
101// accesses to the object, happens before the corresponding dec() call.
102//
103// We try to keep memory ordering constraints on atomics as weak as possible,
104// since memory fences or ordered memory accesses are likely to be a major
105// performance cost for this code. All accesses to mStrong, mWeak, and mFlags
106// explicitly relax memory ordering in some way.
107//
108// The only operations that are not memory_order_relaxed are reference count
109// decrements. All reference count decrements are release operations. In
110// addition, the final decrement leading the deallocation is followed by an
111// acquire fence, which we can view informally as also turning it into an
112// acquire operation. (See 29.8p4 [atomics.fences] for details. We could
113// alternatively use acq_rel operations for all decrements. This is probably
114// slower on most current (2016) hardware, especially on ARMv7, but that may
115// not be true indefinitely.)
116//
117// This convention ensures that the second-to-last decrement synchronizes with
118// (in the language of 1.10 in the C++ standard) the final decrement of a
119// reference count. Since reference counts are only updated using atomic
120// read-modify-write operations, this also extends to any earlier decrements.
121// (See "release sequence" in 1.10.)
122//
123// Since all operations on an object happen before the corresponding reference
124// count decrement, and all reference count decrements happen before the final
125// one, we are guaranteed that all other object accesses happen before the
126// object is destroyed.
127
128
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800129#define INITIAL_STRONG_VALUE (1<<28)
130
Hans Boehm23c857e2016-08-02 18:39:30 -0700131#define MAX_COUNT 0xfffff
132
133// Test whether the argument is a clearly invalid strong reference count.
134// Used only for error checking on the value before an atomic decrement.
135// Intended to be very cheap.
136// Note that we cannot just check for excess decrements by comparing to zero
137// since the object would be deallocated before that.
138#define BAD_STRONG(c) \
139 ((c) == 0 || ((c) & (~(MAX_COUNT | INITIAL_STRONG_VALUE))) != 0)
140
141// Same for weak counts.
142#define BAD_WEAK(c) ((c) == 0 || ((c) & (~MAX_COUNT)) != 0)
143
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800144// ---------------------------------------------------------------------------
145
146class RefBase::weakref_impl : public RefBase::weakref_type
147{
148public:
Hans Boehme263e6c2016-05-11 18:15:12 -0700149 std::atomic<int32_t> mStrong;
150 std::atomic<int32_t> mWeak;
151 RefBase* const mBase;
152 std::atomic<int32_t> mFlags;
Mathias Agopian9c8fa9e2011-06-15 20:42:47 -0700153
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800154#if !DEBUG_REFS
155
Chih-Hung Hsieh1c563d92016-04-29 15:44:04 -0700156 explicit weakref_impl(RefBase* base)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800157 : mStrong(INITIAL_STRONG_VALUE)
158 , mWeak(0)
159 , mBase(base)
160 , mFlags(0)
161 {
162 }
163
164 void addStrongRef(const void* /*id*/) { }
165 void removeStrongRef(const void* /*id*/) { }
Mathias Agopianad099652011-08-10 21:07:02 -0700166 void renameStrongRefId(const void* /*old_id*/, const void* /*new_id*/) { }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800167 void addWeakRef(const void* /*id*/) { }
168 void removeWeakRef(const void* /*id*/) { }
Mathias Agopianad099652011-08-10 21:07:02 -0700169 void renameWeakRefId(const void* /*old_id*/, const void* /*new_id*/) { }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800170 void printRefs() const { }
171 void trackMe(bool, bool) { }
172
173#else
174
175 weakref_impl(RefBase* base)
176 : mStrong(INITIAL_STRONG_VALUE)
177 , mWeak(0)
178 , mBase(base)
179 , mFlags(0)
180 , mStrongRefs(NULL)
181 , mWeakRefs(NULL)
182 , mTrackEnabled(!!DEBUG_REFS_ENABLED_BY_DEFAULT)
183 , mRetain(false)
184 {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800185 }
186
187 ~weakref_impl()
188 {
Mathias Agopianad099652011-08-10 21:07:02 -0700189 bool dumpStack = false;
190 if (!mRetain && mStrongRefs != NULL) {
191 dumpStack = true;
Steve Block1b781ab2012-01-06 19:20:56 +0000192 ALOGE("Strong references remain:");
Mathias Agopianad099652011-08-10 21:07:02 -0700193 ref_entry* refs = mStrongRefs;
194 while (refs) {
195 char inc = refs->ref >= 0 ? '+' : '-';
Steve Blockeb095332011-12-20 16:23:08 +0000196 ALOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
Mathias Agopianad099652011-08-10 21:07:02 -0700197#if DEBUG_REFS_CALLSTACK_ENABLED
Hans Boehm2a019ec2018-08-07 23:45:25 +0000198 CallStack::logStack(LOG_TAG, refs->stack.get());
Mathias Agopianad099652011-08-10 21:07:02 -0700199#endif
200 refs = refs->next;
201 }
202 }
203
204 if (!mRetain && mWeakRefs != NULL) {
205 dumpStack = true;
Steve Block1b781ab2012-01-06 19:20:56 +0000206 ALOGE("Weak references remain!");
Mathias Agopianad099652011-08-10 21:07:02 -0700207 ref_entry* refs = mWeakRefs;
208 while (refs) {
209 char inc = refs->ref >= 0 ? '+' : '-';
Steve Blockeb095332011-12-20 16:23:08 +0000210 ALOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
Mathias Agopianad099652011-08-10 21:07:02 -0700211#if DEBUG_REFS_CALLSTACK_ENABLED
Hans Boehm2a019ec2018-08-07 23:45:25 +0000212 CallStack::logStack(LOG_TAG, refs->stack.get());
Mathias Agopianad099652011-08-10 21:07:02 -0700213#endif
214 refs = refs->next;
215 }
216 }
217 if (dumpStack) {
Steve Block1b781ab2012-01-06 19:20:56 +0000218 ALOGE("above errors at:");
Hans Boehm2a019ec2018-08-07 23:45:25 +0000219 CallStack::logStack(LOG_TAG);
Mathias Agopianad099652011-08-10 21:07:02 -0700220 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800221 }
222
Mathias Agopianad099652011-08-10 21:07:02 -0700223 void addStrongRef(const void* id) {
Steve Blockeb095332011-12-20 16:23:08 +0000224 //ALOGD_IF(mTrackEnabled,
Mathias Agopianad099652011-08-10 21:07:02 -0700225 // "addStrongRef: RefBase=%p, id=%p", mBase, id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700226 addRef(&mStrongRefs, id, mStrong.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 removeStrongRef(const void* id) {
Steve Blockeb095332011-12-20 16:23:08 +0000230 //ALOGD_IF(mTrackEnabled,
Mathias Agopianad099652011-08-10 21:07:02 -0700231 // "removeStrongRef: RefBase=%p, id=%p", mBase, id);
232 if (!mRetain) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800233 removeRef(&mStrongRefs, id);
Mathias Agopianad099652011-08-10 21:07:02 -0700234 } else {
Hans Boehme263e6c2016-05-11 18:15:12 -0700235 addRef(&mStrongRefs, id, -mStrong.load(std::memory_order_relaxed));
Mathias Agopianad099652011-08-10 21:07:02 -0700236 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800237 }
238
Mathias Agopianad099652011-08-10 21:07:02 -0700239 void renameStrongRefId(const void* old_id, const void* new_id) {
Steve Blockeb095332011-12-20 16:23:08 +0000240 //ALOGD_IF(mTrackEnabled,
Mathias Agopianad099652011-08-10 21:07:02 -0700241 // "renameStrongRefId: RefBase=%p, oid=%p, nid=%p",
242 // mBase, old_id, new_id);
243 renameRefsId(mStrongRefs, old_id, new_id);
244 }
245
246 void addWeakRef(const void* id) {
Hans Boehme263e6c2016-05-11 18:15:12 -0700247 addRef(&mWeakRefs, id, mWeak.load(std::memory_order_relaxed));
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800248 }
249
Mathias Agopianad099652011-08-10 21:07:02 -0700250 void removeWeakRef(const void* id) {
251 if (!mRetain) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800252 removeRef(&mWeakRefs, id);
Mathias Agopianad099652011-08-10 21:07:02 -0700253 } else {
Hans Boehme263e6c2016-05-11 18:15:12 -0700254 addRef(&mWeakRefs, id, -mWeak.load(std::memory_order_relaxed));
Mathias Agopianad099652011-08-10 21:07:02 -0700255 }
256 }
257
258 void renameWeakRefId(const void* old_id, const void* new_id) {
259 renameRefsId(mWeakRefs, old_id, new_id);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800260 }
261
262 void trackMe(bool track, bool retain)
263 {
264 mTrackEnabled = track;
265 mRetain = retain;
266 }
267
268 void printRefs() const
269 {
270 String8 text;
271
272 {
Mathias Agopianad099652011-08-10 21:07:02 -0700273 Mutex::Autolock _l(mMutex);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800274 char buf[128];
George Burgess IVe7aa2b22016-03-02 14:02:55 -0800275 snprintf(buf, sizeof(buf),
276 "Strong references on RefBase %p (weakref_type %p):\n",
277 mBase, this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800278 text.append(buf);
279 printRefsLocked(&text, mStrongRefs);
George Burgess IVe7aa2b22016-03-02 14:02:55 -0800280 snprintf(buf, sizeof(buf),
281 "Weak references on RefBase %p (weakref_type %p):\n",
282 mBase, this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800283 text.append(buf);
284 printRefsLocked(&text, mWeakRefs);
285 }
286
287 {
288 char name[100];
George Burgess IVe7aa2b22016-03-02 14:02:55 -0800289 snprintf(name, sizeof(name), DEBUG_REFS_CALLSTACK_PATH "/%p.stack",
290 this);
Mathias Agopian769828d2013-03-06 17:51:15 -0800291 int rc = open(name, O_RDWR | O_CREAT | O_APPEND, 644);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800292 if (rc >= 0) {
Hans Boehm2a019ec2018-08-07 23:45:25 +0000293 (void)write(rc, text.string(), text.length());
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800294 close(rc);
Steve Blockeb095332011-12-20 16:23:08 +0000295 ALOGD("STACK TRACE for %p saved in %s", this, name);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800296 }
Steve Block1b781ab2012-01-06 19:20:56 +0000297 else ALOGE("FAILED TO PRINT STACK TRACE for %p in %s: %s", this,
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800298 name, strerror(errno));
299 }
300 }
301
302private:
303 struct ref_entry
304 {
305 ref_entry* next;
306 const void* id;
307#if DEBUG_REFS_CALLSTACK_ENABLED
Hans Boehm2a019ec2018-08-07 23:45:25 +0000308 CallStack::CallStackUPtr stack;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800309#endif
310 int32_t ref;
311 };
312
313 void addRef(ref_entry** refs, const void* id, int32_t mRef)
314 {
315 if (mTrackEnabled) {
316 AutoMutex _l(mMutex);
Mathias Agopianad099652011-08-10 21:07:02 -0700317
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800318 ref_entry* ref = new ref_entry;
319 // Reference count at the time of the snapshot, but before the
320 // update. Positive value means we increment, negative--we
321 // decrement the reference count.
322 ref->ref = mRef;
323 ref->id = id;
324#if DEBUG_REFS_CALLSTACK_ENABLED
Hans Boehm2a019ec2018-08-07 23:45:25 +0000325 ref->stack = CallStack::getCurrent(2);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800326#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800327 ref->next = *refs;
328 *refs = ref;
329 }
330 }
331
332 void removeRef(ref_entry** refs, const void* id)
333 {
334 if (mTrackEnabled) {
335 AutoMutex _l(mMutex);
336
Mathias Agopianad099652011-08-10 21:07:02 -0700337 ref_entry* const head = *refs;
338 ref_entry* ref = head;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800339 while (ref != NULL) {
340 if (ref->id == id) {
341 *refs = ref->next;
342 delete ref;
343 return;
344 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800345 refs = &ref->next;
346 ref = *refs;
347 }
Mathias Agopianad099652011-08-10 21:07:02 -0700348
Steve Block1b781ab2012-01-06 19:20:56 +0000349 ALOGE("RefBase: removing id %p on RefBase %p"
Mathias Agopianad099652011-08-10 21:07:02 -0700350 "(weakref_type %p) that doesn't exist!",
351 id, mBase, this);
352
353 ref = head;
354 while (ref) {
355 char inc = ref->ref >= 0 ? '+' : '-';
Steve Blockeb095332011-12-20 16:23:08 +0000356 ALOGD("\t%c ID %p (ref %d):", inc, ref->id, ref->ref);
Mathias Agopianad099652011-08-10 21:07:02 -0700357 ref = ref->next;
358 }
359
Hans Boehm2a019ec2018-08-07 23:45:25 +0000360 CallStack::logStack(LOG_TAG);
Mathias Agopianad099652011-08-10 21:07:02 -0700361 }
362 }
363
364 void renameRefsId(ref_entry* r, const void* old_id, const void* new_id)
365 {
366 if (mTrackEnabled) {
367 AutoMutex _l(mMutex);
368 ref_entry* ref = r;
369 while (ref != NULL) {
370 if (ref->id == old_id) {
371 ref->id = new_id;
372 }
373 ref = ref->next;
374 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800375 }
376 }
377
378 void printRefsLocked(String8* out, const ref_entry* refs) const
379 {
380 char buf[128];
381 while (refs) {
382 char inc = refs->ref >= 0 ? '+' : '-';
George Burgess IVe7aa2b22016-03-02 14:02:55 -0800383 snprintf(buf, sizeof(buf), "\t%c ID %p (ref %d):\n",
384 inc, refs->id, refs->ref);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800385 out->append(buf);
386#if DEBUG_REFS_CALLSTACK_ENABLED
Hans Boehm2a019ec2018-08-07 23:45:25 +0000387 out->append(CallStack::stackToString("\t\t", refs->stack.get()));
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800388#else
389 out->append("\t\t(call stacks disabled)");
390#endif
391 refs = refs->next;
392 }
393 }
394
Mathias Agopianad099652011-08-10 21:07:02 -0700395 mutable Mutex mMutex;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800396 ref_entry* mStrongRefs;
397 ref_entry* mWeakRefs;
398
399 bool mTrackEnabled;
400 // Collect stack traces on addref and removeref, instead of deleting the stack references
401 // on removeref that match the address ones.
402 bool mRetain;
403
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800404#endif
405};
406
407// ---------------------------------------------------------------------------
408
409void RefBase::incStrong(const void* id) const
410{
411 weakref_impl* const refs = mRefs;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800412 refs->incWeak(id);
413
414 refs->addStrongRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700415 const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000416 ALOG_ASSERT(c > 0, "incStrong() called on %p after last strong ref", refs);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800417#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000418 ALOGD("incStrong of %p from %p: cnt=%d\n", this, id, c);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800419#endif
420 if (c != INITIAL_STRONG_VALUE) {
421 return;
422 }
423
Chih-Hung Hsieh122352d2017-10-02 15:20:07 -0700424 int32_t old __unused = refs->mStrong.fetch_sub(INITIAL_STRONG_VALUE, std::memory_order_relaxed);
Hans Boehme263e6c2016-05-11 18:15:12 -0700425 // A decStrong() must still happen after us.
426 ALOG_ASSERT(old > INITIAL_STRONG_VALUE, "0x%x too small", old);
Mathias Agopianad099652011-08-10 21:07:02 -0700427 refs->mBase->onFirstRef();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800428}
429
430void RefBase::decStrong(const void* id) const
431{
432 weakref_impl* const refs = mRefs;
433 refs->removeStrongRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700434 const int32_t c = refs->mStrong.fetch_sub(1, std::memory_order_release);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800435#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000436 ALOGD("decStrong of %p from %p: cnt=%d\n", this, id, c);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800437#endif
Hans Boehm23c857e2016-08-02 18:39:30 -0700438 LOG_ALWAYS_FATAL_IF(BAD_STRONG(c), "decStrong() called on %p too many times",
439 refs);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800440 if (c == 1) {
Hans Boehme263e6c2016-05-11 18:15:12 -0700441 std::atomic_thread_fence(std::memory_order_acquire);
Mathias Agopianad099652011-08-10 21:07:02 -0700442 refs->mBase->onLastStrongRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700443 int32_t flags = refs->mFlags.load(std::memory_order_relaxed);
444 if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
Mathias Agopian9c8fa9e2011-06-15 20:42:47 -0700445 delete this;
Hans Boehm23c857e2016-08-02 18:39:30 -0700446 // The destructor does not delete refs in this case.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800447 }
448 }
Hans Boehme263e6c2016-05-11 18:15:12 -0700449 // Note that even with only strong reference operations, the thread
450 // deallocating this may not be the same as the thread deallocating refs.
451 // That's OK: all accesses to this happen before its deletion here,
452 // and all accesses to refs happen before its deletion in the final decWeak.
453 // The destructor can safely access mRefs because either it's deleting
454 // mRefs itself, or it's running entirely before the final mWeak decrement.
George Burgess IV6753bc42017-10-01 12:38:44 -0700455 //
456 // Since we're doing atomic loads of `flags`, the static analyzer assumes
457 // they can change between `delete this;` and `refs->decWeak(id);`. This is
458 // not the case. The analyzer may become more okay with this patten when
459 // https://bugs.llvm.org/show_bug.cgi?id=34365 gets resolved. NOLINTNEXTLINE
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800460 refs->decWeak(id);
461}
462
463void RefBase::forceIncStrong(const void* id) const
464{
Hans Boehme263e6c2016-05-11 18:15:12 -0700465 // Allows initial mStrong of 0 in addition to INITIAL_STRONG_VALUE.
466 // TODO: Better document assumptions.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800467 weakref_impl* const refs = mRefs;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800468 refs->incWeak(id);
469
470 refs->addStrongRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700471 const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000472 ALOG_ASSERT(c >= 0, "forceIncStrong called on %p after ref count underflow",
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800473 refs);
474#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000475 ALOGD("forceIncStrong of %p from %p: cnt=%d\n", this, id, c);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800476#endif
477
478 switch (c) {
479 case INITIAL_STRONG_VALUE:
Hans Boehme263e6c2016-05-11 18:15:12 -0700480 refs->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
481 std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800482 // fall through...
483 case 0:
Mathias Agopianad099652011-08-10 21:07:02 -0700484 refs->mBase->onFirstRef();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800485 }
486}
487
488int32_t RefBase::getStrongCount() const
489{
Hans Boehme263e6c2016-05-11 18:15:12 -0700490 // Debugging only; No memory ordering guarantees.
491 return mRefs->mStrong.load(std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800492}
493
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800494RefBase* RefBase::weakref_type::refBase() const
495{
496 return static_cast<const weakref_impl*>(this)->mBase;
497}
498
499void RefBase::weakref_type::incWeak(const void* id)
500{
501 weakref_impl* const impl = static_cast<weakref_impl*>(this);
502 impl->addWeakRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700503 const int32_t c __unused = impl->mWeak.fetch_add(1,
504 std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000505 ALOG_ASSERT(c >= 0, "incWeak called on %p after last weak ref", this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800506}
507
Mathias Agopianad099652011-08-10 21:07:02 -0700508
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800509void RefBase::weakref_type::decWeak(const void* id)
510{
511 weakref_impl* const impl = static_cast<weakref_impl*>(this);
512 impl->removeWeakRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700513 const int32_t c = impl->mWeak.fetch_sub(1, std::memory_order_release);
Hans Boehm23c857e2016-08-02 18:39:30 -0700514 LOG_ALWAYS_FATAL_IF(BAD_WEAK(c), "decWeak called on %p too many times",
515 this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800516 if (c != 1) return;
Hans Boehme263e6c2016-05-11 18:15:12 -0700517 atomic_thread_fence(std::memory_order_acquire);
Mathias Agopianad099652011-08-10 21:07:02 -0700518
Hans Boehme263e6c2016-05-11 18:15:12 -0700519 int32_t flags = impl->mFlags.load(std::memory_order_relaxed);
520 if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
Mathias Agopianad099652011-08-10 21:07:02 -0700521 // This is the regular lifetime case. The object is destroyed
522 // when the last strong reference goes away. Since weakref_impl
Hans Boehm23c857e2016-08-02 18:39:30 -0700523 // outlives the object, it is not destroyed in the dtor, and
Mathias Agopianad099652011-08-10 21:07:02 -0700524 // we'll have to do it here.
Hans Boehme263e6c2016-05-11 18:15:12 -0700525 if (impl->mStrong.load(std::memory_order_relaxed)
526 == INITIAL_STRONG_VALUE) {
Hans Boehm23c857e2016-08-02 18:39:30 -0700527 // Decrementing a weak count to zero when object never had a strong
528 // reference. We assume it acquired a weak reference early, e.g.
529 // in the constructor, and will eventually be properly destroyed,
530 // usually via incrementing and decrementing the strong count.
531 // Thus we no longer do anything here. We log this case, since it
532 // seems to be extremely rare, and should not normally occur. We
533 // used to deallocate mBase here, so this may now indicate a leak.
534 ALOGW("RefBase: Object at %p lost last weak reference "
535 "before it had a strong reference", impl->mBase);
Mathias Agopianad099652011-08-10 21:07:02 -0700536 } else {
Steve Blockb37fbe92011-10-20 11:56:00 +0100537 // ALOGV("Freeing refs %p of old RefBase %p\n", this, impl->mBase);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800538 delete impl;
539 }
540 } else {
Hans Boehme263e6c2016-05-11 18:15:12 -0700541 // This is the OBJECT_LIFETIME_WEAK case. The last weak-reference
542 // is gone, we can destroy the object.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800543 impl->mBase->onLastWeakRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700544 delete impl->mBase;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800545 }
546}
547
548bool RefBase::weakref_type::attemptIncStrong(const void* id)
549{
550 incWeak(id);
551
552 weakref_impl* const impl = static_cast<weakref_impl*>(this);
Hans Boehme263e6c2016-05-11 18:15:12 -0700553 int32_t curCount = impl->mStrong.load(std::memory_order_relaxed);
Dianne Hackborna729ab12013-03-14 15:26:30 -0700554
555 ALOG_ASSERT(curCount >= 0,
556 "attemptIncStrong called on %p after underflow", this);
557
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800558 while (curCount > 0 && curCount != INITIAL_STRONG_VALUE) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700559 // we're in the easy/common case of promoting a weak-reference
560 // from an existing strong reference.
Hans Boehme263e6c2016-05-11 18:15:12 -0700561 if (impl->mStrong.compare_exchange_weak(curCount, curCount+1,
562 std::memory_order_relaxed)) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800563 break;
564 }
Dianne Hackborna729ab12013-03-14 15:26:30 -0700565 // the strong count has changed on us, we need to re-assert our
Hans Boehme263e6c2016-05-11 18:15:12 -0700566 // situation. curCount was updated by compare_exchange_weak.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800567 }
568
569 if (curCount <= 0 || curCount == INITIAL_STRONG_VALUE) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700570 // we're now in the harder case of either:
571 // - there never was a strong reference on us
572 // - or, all strong references have been released
Hans Boehme263e6c2016-05-11 18:15:12 -0700573 int32_t flags = impl->mFlags.load(std::memory_order_relaxed);
574 if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700575 // this object has a "normal" life-time, i.e.: it gets destroyed
576 // when the last strong reference goes away
577 if (curCount <= 0) {
578 // the last strong-reference got released, the object cannot
579 // be revived.
580 decWeak(id);
581 return false;
582 }
583
584 // here, curCount == INITIAL_STRONG_VALUE, which means
585 // there never was a strong-reference, so we can try to
586 // promote this object; we need to do that atomically.
587 while (curCount > 0) {
Hans Boehme263e6c2016-05-11 18:15:12 -0700588 if (impl->mStrong.compare_exchange_weak(curCount, curCount+1,
589 std::memory_order_relaxed)) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700590 break;
591 }
592 // the strong count has changed on us, we need to re-assert our
593 // situation (e.g.: another thread has inc/decStrong'ed us)
Hans Boehme263e6c2016-05-11 18:15:12 -0700594 // curCount has been updated.
Dianne Hackborna729ab12013-03-14 15:26:30 -0700595 }
596
597 if (curCount <= 0) {
598 // promote() failed, some other thread destroyed us in the
599 // meantime (i.e.: strong count reached zero).
600 decWeak(id);
601 return false;
602 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800603 } else {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700604 // this object has an "extended" life-time, i.e.: it can be
605 // revived from a weak-reference only.
606 // Ask the object's implementation if it agrees to be revived
607 if (!impl->mBase->onIncStrongAttempted(FIRST_INC_STRONG, id)) {
608 // it didn't so give-up.
609 decWeak(id);
610 return false;
611 }
612 // grab a strong-reference, which is always safe due to the
613 // extended life-time.
Hans Boehme263e6c2016-05-11 18:15:12 -0700614 curCount = impl->mStrong.fetch_add(1, std::memory_order_relaxed);
Hans Boehm7f27cbc2016-07-29 14:39:10 -0700615 // If the strong reference count has already been incremented by
616 // someone else, the implementor of onIncStrongAttempted() is holding
617 // an unneeded reference. So call onLastStrongRef() here to remove it.
618 // (No, this is not pretty.) Note that we MUST NOT do this if we
619 // are in fact acquiring the first reference.
620 if (curCount != 0 && curCount != INITIAL_STRONG_VALUE) {
621 impl->mBase->onLastStrongRef(id);
622 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800623 }
624 }
625
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800626 impl->addStrongRef(id);
627
628#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000629 ALOGD("attemptIncStrong of %p from %p: cnt=%d\n", this, id, curCount);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800630#endif
631
Hans Boehm7f27cbc2016-07-29 14:39:10 -0700632 // curCount is the value of mStrong before we incremented it.
Hans Boehme263e6c2016-05-11 18:15:12 -0700633 // Now we need to fix-up the count if it was INITIAL_STRONG_VALUE.
634 // This must be done safely, i.e.: handle the case where several threads
Dianne Hackborna729ab12013-03-14 15:26:30 -0700635 // were here in attemptIncStrong().
Hans Boehme263e6c2016-05-11 18:15:12 -0700636 // curCount > INITIAL_STRONG_VALUE is OK, and can happen if we're doing
637 // this in the middle of another incStrong. The subtraction is handled
638 // by the thread that started with INITIAL_STRONG_VALUE.
639 if (curCount == INITIAL_STRONG_VALUE) {
640 impl->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
641 std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800642 }
Dianne Hackborna729ab12013-03-14 15:26:30 -0700643
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800644 return true;
645}
646
647bool RefBase::weakref_type::attemptIncWeak(const void* id)
648{
649 weakref_impl* const impl = static_cast<weakref_impl*>(this);
Mathias Agopianad099652011-08-10 21:07:02 -0700650
Hans Boehme263e6c2016-05-11 18:15:12 -0700651 int32_t curCount = impl->mWeak.load(std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000652 ALOG_ASSERT(curCount >= 0, "attemptIncWeak called on %p after underflow",
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800653 this);
654 while (curCount > 0) {
Hans Boehme263e6c2016-05-11 18:15:12 -0700655 if (impl->mWeak.compare_exchange_weak(curCount, curCount+1,
656 std::memory_order_relaxed)) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800657 break;
658 }
Hans Boehme263e6c2016-05-11 18:15:12 -0700659 // curCount has been updated.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800660 }
661
662 if (curCount > 0) {
663 impl->addWeakRef(id);
664 }
665
666 return curCount > 0;
667}
668
669int32_t RefBase::weakref_type::getWeakCount() const
670{
Hans Boehme263e6c2016-05-11 18:15:12 -0700671 // Debug only!
672 return static_cast<const weakref_impl*>(this)->mWeak
673 .load(std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800674}
675
676void RefBase::weakref_type::printRefs() const
677{
678 static_cast<const weakref_impl*>(this)->printRefs();
679}
680
681void RefBase::weakref_type::trackMe(bool enable, bool retain)
682{
Mathias Agopianad099652011-08-10 21:07:02 -0700683 static_cast<weakref_impl*>(this)->trackMe(enable, retain);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800684}
685
686RefBase::weakref_type* RefBase::createWeak(const void* id) const
687{
688 mRefs->incWeak(id);
689 return mRefs;
690}
691
692RefBase::weakref_type* RefBase::getWeakRefs() const
693{
694 return mRefs;
695}
696
697RefBase::RefBase()
698 : mRefs(new weakref_impl(this))
699{
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800700}
701
702RefBase::~RefBase()
703{
Hans Boehm23c857e2016-08-02 18:39:30 -0700704 int32_t flags = mRefs->mFlags.load(std::memory_order_relaxed);
705 // Life-time of this object is extended to WEAK, in
706 // which case weakref_impl doesn't out-live the object and we
707 // can free it now.
708 if ((flags & OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_WEAK) {
709 // It's possible that the weak count is not 0 if the object
710 // re-acquired a weak reference in its destructor
711 if (mRefs->mWeak.load(std::memory_order_relaxed) == 0) {
712 delete mRefs;
713 }
Hans Boehm2a019ec2018-08-07 23:45:25 +0000714 } else if (mRefs->mStrong.load(std::memory_order_relaxed) == INITIAL_STRONG_VALUE) {
Hans Boehm9ba71922016-07-21 18:56:55 -0700715 // We never acquired a strong reference on this object.
Hans Boehm2a019ec2018-08-07 23:45:25 +0000716#if DEBUG_REFBASE_DESTRUCTION
717 // Treating this as fatal is prone to causing boot loops. For debugging, it's
718 // better to treat as non-fatal.
719 ALOGD("RefBase: Explicit destruction, weak count = %d (in %p)", mRefs->mWeak.load(), this);
720 CallStack::logStack(LOG_TAG);
721#else
722 LOG_ALWAYS_FATAL("RefBase: Explicit destruction, weak count = %d", mRefs->mWeak.load());
723#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800724 }
Hans Boehm23c857e2016-08-02 18:39:30 -0700725 // For debugging purposes, clear mRefs. Ineffective against outstanding wp's.
Yi Konge1731a42018-07-16 18:11:34 -0700726 const_cast<weakref_impl*&>(mRefs) = nullptr;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800727}
728
729void RefBase::extendObjectLifetime(int32_t mode)
730{
Hans Boehme263e6c2016-05-11 18:15:12 -0700731 // Must be happens-before ordered with respect to construction or any
732 // operation that could destroy the object.
733 mRefs->mFlags.fetch_or(mode, std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800734}
735
736void RefBase::onFirstRef()
737{
738}
739
740void RefBase::onLastStrongRef(const void* /*id*/)
741{
742}
743
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700744bool RefBase::onIncStrongAttempted(uint32_t flags, const void* /*id*/)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800745{
746 return (flags&FIRST_INC_STRONG) ? true : false;
747}
748
749void RefBase::onLastWeakRef(const void* /*id*/)
750{
751}
Mathias Agopianad099652011-08-10 21:07:02 -0700752
753// ---------------------------------------------------------------------------
754
Mathias Agopianad099652011-08-10 21:07:02 -0700755#if DEBUG_REFS
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700756void RefBase::renameRefs(size_t n, const ReferenceRenamer& renamer) {
Mathias Agopianad099652011-08-10 21:07:02 -0700757 for (size_t i=0 ; i<n ; i++) {
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700758 renamer(i);
Mathias Agopianad099652011-08-10 21:07:02 -0700759 }
Mathias Agopianad099652011-08-10 21:07:02 -0700760}
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700761#else
762void RefBase::renameRefs(size_t /*n*/, const ReferenceRenamer& /*renamer*/) { }
763#endif
Mathias Agopianad099652011-08-10 21:07:02 -0700764
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700765void RefBase::renameRefId(weakref_type* ref,
766 const void* old_id, const void* new_id) {
767 weakref_impl* const impl = static_cast<weakref_impl*>(ref);
768 impl->renameStrongRefId(old_id, new_id);
769 impl->renameWeakRefId(old_id, new_id);
770}
771
772void RefBase::renameRefId(RefBase* ref,
773 const void* old_id, const void* new_id) {
774 ref->mRefs->renameStrongRefId(old_id, new_id);
775 ref->mRefs->renameWeakRefId(old_id, new_id);
776}
777
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800778}; // namespace android