blob: ae107893c8fd479203a7d8e2007c2820a2cb00c4 [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
Chih-Hung Hsieh502f4862018-09-13 11:08:41 -070022#include <android-base/macros.h>
23
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080024#include <utils/RefBase.h>
25
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080026#include <utils/CallStack.h>
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080027
Hans Boehm2a019ec2018-08-07 23:45:25 +000028#include <utils/Mutex.h>
29
Mark Salyzyn5bed8032014-04-30 11:10:46 -070030#ifndef __unused
31#define __unused __attribute__((__unused__))
32#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080033
Hans Boehm2a019ec2018-08-07 23:45:25 +000034// Compile with refcounting debugging enabled.
35#define DEBUG_REFS 0
36
37// The following three are ignored unless DEBUG_REFS is set.
Mathias Agopian6d4419d2013-03-18 20:31:18 -070038
39// whether ref-tracking is enabled by default, if not, trackMe(true, false)
40// needs to be called explicitly
Hans Boehm2a019ec2018-08-07 23:45:25 +000041#define DEBUG_REFS_ENABLED_BY_DEFAULT 0
Mathias Agopian6d4419d2013-03-18 20:31:18 -070042
43// whether callstack are collected (significantly slows things down)
Hans Boehm2a019ec2018-08-07 23:45:25 +000044#define DEBUG_REFS_CALLSTACK_ENABLED 1
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080045
Mathias Agopian6d4419d2013-03-18 20:31:18 -070046// folder where stack traces are saved when DEBUG_REFS is enabled
47// this folder needs to exist and be writable
Hans Boehm2a019ec2018-08-07 23:45:25 +000048#define DEBUG_REFS_CALLSTACK_PATH "/data/debug"
Mathias Agopian6d4419d2013-03-18 20:31:18 -070049
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080050// log all reference counting operations
Hans Boehm2a019ec2018-08-07 23:45:25 +000051#define PRINT_REFS 0
52
53// Continue after logging a stack trace if ~RefBase discovers that reference
54// count has never been incremented. Normally we conspicuously crash in that
55// case.
56#define DEBUG_REFBASE_DESTRUCTION 1
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080057
58// ---------------------------------------------------------------------------
59
60namespace android {
61
Hans Boehm9ba71922016-07-21 18:56:55 -070062// Observations, invariants, etc:
Hans Boehme263e6c2016-05-11 18:15:12 -070063
Hans Boehm9ba71922016-07-21 18:56:55 -070064// By default, obects are destroyed when the last strong reference disappears
65// or, if the object never had a strong reference, when the last weak reference
66// disappears.
67//
Hans Boehme263e6c2016-05-11 18:15:12 -070068// OBJECT_LIFETIME_WEAK changes this behavior to retain the object
69// unconditionally until the last reference of either kind disappears. The
70// client ensures that the extendObjectLifetime call happens before the dec
71// call that would otherwise have deallocated the object, or before an
72// attemptIncStrong call that might rely on it. We do not worry about
73// concurrent changes to the object lifetime.
Hans Boehm9ba71922016-07-21 18:56:55 -070074//
75// AttemptIncStrong will succeed if the object has a strong reference, or if it
76// has a weak reference and has never had a strong reference.
77// AttemptIncWeak really does succeed only if there is already a WEAK
78// reference, and thus may fail when attemptIncStrong would succeed.
79//
Hans Boehme263e6c2016-05-11 18:15:12 -070080// mStrong is the strong reference count. mWeak is the weak reference count.
81// Between calls, and ignoring memory ordering effects, mWeak includes strong
82// references, and is thus >= mStrong.
83//
Hans Boehm9ba71922016-07-21 18:56:55 -070084// A weakref_impl holds all the information, including both reference counts,
85// required to perform wp<> operations. Thus these can continue to be performed
86// after the RefBase object has been destroyed.
87//
Hans Boehme263e6c2016-05-11 18:15:12 -070088// A weakref_impl is allocated as the value of mRefs in a RefBase object on
89// construction.
Hans Boehm23c857e2016-08-02 18:39:30 -070090// In the OBJECT_LIFETIME_STRONG case, it is normally deallocated in decWeak,
91// and hence lives as long as the last weak reference. (It can also be
92// deallocated in the RefBase destructor iff the strong reference count was
93// never incremented and the weak count is zero, e.g. if the RefBase object is
94// explicitly destroyed without decrementing the strong count. This should be
95// avoided.) In this case, the RefBase destructor should be invoked from
96// decStrong.
97// In the OBJECT_LIFETIME_WEAK case, the weakref_impl is always deallocated in
98// the RefBase destructor, which is always invoked by decWeak. DecStrong
99// explicitly avoids the deletion in this case.
Hans Boehme263e6c2016-05-11 18:15:12 -0700100//
101// Memory ordering:
102// The client must ensure that every inc() call, together with all other
103// accesses to the object, happens before the corresponding dec() call.
104//
105// We try to keep memory ordering constraints on atomics as weak as possible,
106// since memory fences or ordered memory accesses are likely to be a major
107// performance cost for this code. All accesses to mStrong, mWeak, and mFlags
108// explicitly relax memory ordering in some way.
109//
110// The only operations that are not memory_order_relaxed are reference count
111// decrements. All reference count decrements are release operations. In
112// addition, the final decrement leading the deallocation is followed by an
113// acquire fence, which we can view informally as also turning it into an
114// acquire operation. (See 29.8p4 [atomics.fences] for details. We could
115// alternatively use acq_rel operations for all decrements. This is probably
116// slower on most current (2016) hardware, especially on ARMv7, but that may
117// not be true indefinitely.)
118//
119// This convention ensures that the second-to-last decrement synchronizes with
120// (in the language of 1.10 in the C++ standard) the final decrement of a
121// reference count. Since reference counts are only updated using atomic
122// read-modify-write operations, this also extends to any earlier decrements.
123// (See "release sequence" in 1.10.)
124//
125// Since all operations on an object happen before the corresponding reference
126// count decrement, and all reference count decrements happen before the final
127// one, we are guaranteed that all other object accesses happen before the
128// object is destroyed.
129
130
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800131#define INITIAL_STRONG_VALUE (1<<28)
132
Hans Boehm23c857e2016-08-02 18:39:30 -0700133#define MAX_COUNT 0xfffff
134
135// Test whether the argument is a clearly invalid strong reference count.
136// Used only for error checking on the value before an atomic decrement.
137// Intended to be very cheap.
138// Note that we cannot just check for excess decrements by comparing to zero
139// since the object would be deallocated before that.
140#define BAD_STRONG(c) \
141 ((c) == 0 || ((c) & (~(MAX_COUNT | INITIAL_STRONG_VALUE))) != 0)
142
143// Same for weak counts.
144#define BAD_WEAK(c) ((c) == 0 || ((c) & (~MAX_COUNT)) != 0)
145
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800146// ---------------------------------------------------------------------------
147
148class RefBase::weakref_impl : public RefBase::weakref_type
149{
150public:
Hans Boehme263e6c2016-05-11 18:15:12 -0700151 std::atomic<int32_t> mStrong;
152 std::atomic<int32_t> mWeak;
153 RefBase* const mBase;
154 std::atomic<int32_t> mFlags;
Mathias Agopian9c8fa9e2011-06-15 20:42:47 -0700155
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800156#if !DEBUG_REFS
157
Chih-Hung Hsieh1c563d92016-04-29 15:44:04 -0700158 explicit weakref_impl(RefBase* base)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800159 : mStrong(INITIAL_STRONG_VALUE)
160 , mWeak(0)
161 , mBase(base)
162 , mFlags(0)
163 {
164 }
165
166 void addStrongRef(const void* /*id*/) { }
167 void removeStrongRef(const void* /*id*/) { }
Mathias Agopianad099652011-08-10 21:07:02 -0700168 void renameStrongRefId(const void* /*old_id*/, const void* /*new_id*/) { }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800169 void addWeakRef(const void* /*id*/) { }
170 void removeWeakRef(const void* /*id*/) { }
Mathias Agopianad099652011-08-10 21:07:02 -0700171 void renameWeakRefId(const void* /*old_id*/, const void* /*new_id*/) { }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800172 void printRefs() const { }
173 void trackMe(bool, bool) { }
174
175#else
176
177 weakref_impl(RefBase* base)
178 : mStrong(INITIAL_STRONG_VALUE)
179 , mWeak(0)
180 , mBase(base)
181 , mFlags(0)
182 , mStrongRefs(NULL)
183 , mWeakRefs(NULL)
184 , mTrackEnabled(!!DEBUG_REFS_ENABLED_BY_DEFAULT)
185 , mRetain(false)
186 {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800187 }
188
189 ~weakref_impl()
190 {
Mathias Agopianad099652011-08-10 21:07:02 -0700191 bool dumpStack = false;
192 if (!mRetain && mStrongRefs != NULL) {
193 dumpStack = true;
Steve Block1b781ab2012-01-06 19:20:56 +0000194 ALOGE("Strong references remain:");
Mathias Agopianad099652011-08-10 21:07:02 -0700195 ref_entry* refs = mStrongRefs;
196 while (refs) {
197 char inc = refs->ref >= 0 ? '+' : '-';
Steve Blockeb095332011-12-20 16:23:08 +0000198 ALOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
Mathias Agopianad099652011-08-10 21:07:02 -0700199#if DEBUG_REFS_CALLSTACK_ENABLED
Hans Boehm2a019ec2018-08-07 23:45:25 +0000200 CallStack::logStack(LOG_TAG, refs->stack.get());
Mathias Agopianad099652011-08-10 21:07:02 -0700201#endif
202 refs = refs->next;
203 }
204 }
205
206 if (!mRetain && mWeakRefs != NULL) {
207 dumpStack = true;
Steve Block1b781ab2012-01-06 19:20:56 +0000208 ALOGE("Weak references remain!");
Mathias Agopianad099652011-08-10 21:07:02 -0700209 ref_entry* refs = mWeakRefs;
210 while (refs) {
211 char inc = refs->ref >= 0 ? '+' : '-';
Steve Blockeb095332011-12-20 16:23:08 +0000212 ALOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
Mathias Agopianad099652011-08-10 21:07:02 -0700213#if DEBUG_REFS_CALLSTACK_ENABLED
Hans Boehm2a019ec2018-08-07 23:45:25 +0000214 CallStack::logStack(LOG_TAG, refs->stack.get());
Mathias Agopianad099652011-08-10 21:07:02 -0700215#endif
216 refs = refs->next;
217 }
218 }
219 if (dumpStack) {
Steve Block1b781ab2012-01-06 19:20:56 +0000220 ALOGE("above errors at:");
Hans Boehm2a019ec2018-08-07 23:45:25 +0000221 CallStack::logStack(LOG_TAG);
Mathias Agopianad099652011-08-10 21:07:02 -0700222 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800223 }
224
Mathias Agopianad099652011-08-10 21:07:02 -0700225 void addStrongRef(const void* id) {
Steve Blockeb095332011-12-20 16:23:08 +0000226 //ALOGD_IF(mTrackEnabled,
Mathias Agopianad099652011-08-10 21:07:02 -0700227 // "addStrongRef: RefBase=%p, id=%p", mBase, id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700228 addRef(&mStrongRefs, id, mStrong.load(std::memory_order_relaxed));
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800229 }
230
Mathias Agopianad099652011-08-10 21:07:02 -0700231 void removeStrongRef(const void* id) {
Steve Blockeb095332011-12-20 16:23:08 +0000232 //ALOGD_IF(mTrackEnabled,
Mathias Agopianad099652011-08-10 21:07:02 -0700233 // "removeStrongRef: RefBase=%p, id=%p", mBase, id);
234 if (!mRetain) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800235 removeRef(&mStrongRefs, id);
Mathias Agopianad099652011-08-10 21:07:02 -0700236 } else {
Hans Boehme263e6c2016-05-11 18:15:12 -0700237 addRef(&mStrongRefs, id, -mStrong.load(std::memory_order_relaxed));
Mathias Agopianad099652011-08-10 21:07:02 -0700238 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800239 }
240
Mathias Agopianad099652011-08-10 21:07:02 -0700241 void renameStrongRefId(const void* old_id, const void* new_id) {
Steve Blockeb095332011-12-20 16:23:08 +0000242 //ALOGD_IF(mTrackEnabled,
Mathias Agopianad099652011-08-10 21:07:02 -0700243 // "renameStrongRefId: RefBase=%p, oid=%p, nid=%p",
244 // mBase, old_id, new_id);
245 renameRefsId(mStrongRefs, old_id, new_id);
246 }
247
248 void addWeakRef(const void* id) {
Hans Boehme263e6c2016-05-11 18:15:12 -0700249 addRef(&mWeakRefs, id, mWeak.load(std::memory_order_relaxed));
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800250 }
251
Mathias Agopianad099652011-08-10 21:07:02 -0700252 void removeWeakRef(const void* id) {
253 if (!mRetain) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800254 removeRef(&mWeakRefs, id);
Mathias Agopianad099652011-08-10 21:07:02 -0700255 } else {
Hans Boehme263e6c2016-05-11 18:15:12 -0700256 addRef(&mWeakRefs, id, -mWeak.load(std::memory_order_relaxed));
Mathias Agopianad099652011-08-10 21:07:02 -0700257 }
258 }
259
260 void renameWeakRefId(const void* old_id, const void* new_id) {
261 renameRefsId(mWeakRefs, old_id, new_id);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800262 }
263
264 void trackMe(bool track, bool retain)
265 {
266 mTrackEnabled = track;
267 mRetain = retain;
268 }
269
270 void printRefs() const
271 {
272 String8 text;
273
274 {
Mathias Agopianad099652011-08-10 21:07:02 -0700275 Mutex::Autolock _l(mMutex);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800276 char buf[128];
George Burgess IVe7aa2b22016-03-02 14:02:55 -0800277 snprintf(buf, sizeof(buf),
278 "Strong references on RefBase %p (weakref_type %p):\n",
279 mBase, this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800280 text.append(buf);
281 printRefsLocked(&text, mStrongRefs);
George Burgess IVe7aa2b22016-03-02 14:02:55 -0800282 snprintf(buf, sizeof(buf),
283 "Weak references on RefBase %p (weakref_type %p):\n",
284 mBase, this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800285 text.append(buf);
286 printRefsLocked(&text, mWeakRefs);
287 }
288
289 {
290 char name[100];
George Burgess IVe7aa2b22016-03-02 14:02:55 -0800291 snprintf(name, sizeof(name), DEBUG_REFS_CALLSTACK_PATH "/%p.stack",
292 this);
Mathias Agopian769828d2013-03-06 17:51:15 -0800293 int rc = open(name, O_RDWR | O_CREAT | O_APPEND, 644);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800294 if (rc >= 0) {
Hans Boehm2a019ec2018-08-07 23:45:25 +0000295 (void)write(rc, text.string(), text.length());
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800296 close(rc);
Steve Blockeb095332011-12-20 16:23:08 +0000297 ALOGD("STACK TRACE for %p saved in %s", this, name);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800298 }
Steve Block1b781ab2012-01-06 19:20:56 +0000299 else ALOGE("FAILED TO PRINT STACK TRACE for %p in %s: %s", this,
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800300 name, strerror(errno));
301 }
302 }
303
304private:
305 struct ref_entry
306 {
307 ref_entry* next;
308 const void* id;
309#if DEBUG_REFS_CALLSTACK_ENABLED
Hans Boehm2a019ec2018-08-07 23:45:25 +0000310 CallStack::CallStackUPtr stack;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800311#endif
312 int32_t ref;
313 };
314
315 void addRef(ref_entry** refs, const void* id, int32_t mRef)
316 {
317 if (mTrackEnabled) {
318 AutoMutex _l(mMutex);
Mathias Agopianad099652011-08-10 21:07:02 -0700319
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800320 ref_entry* ref = new ref_entry;
321 // Reference count at the time of the snapshot, but before the
322 // update. Positive value means we increment, negative--we
323 // decrement the reference count.
324 ref->ref = mRef;
325 ref->id = id;
326#if DEBUG_REFS_CALLSTACK_ENABLED
Hans Boehm2a019ec2018-08-07 23:45:25 +0000327 ref->stack = CallStack::getCurrent(2);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800328#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800329 ref->next = *refs;
330 *refs = ref;
331 }
332 }
333
334 void removeRef(ref_entry** refs, const void* id)
335 {
336 if (mTrackEnabled) {
337 AutoMutex _l(mMutex);
338
Mathias Agopianad099652011-08-10 21:07:02 -0700339 ref_entry* const head = *refs;
340 ref_entry* ref = head;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800341 while (ref != NULL) {
342 if (ref->id == id) {
343 *refs = ref->next;
344 delete ref;
345 return;
346 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800347 refs = &ref->next;
348 ref = *refs;
349 }
Mathias Agopianad099652011-08-10 21:07:02 -0700350
Steve Block1b781ab2012-01-06 19:20:56 +0000351 ALOGE("RefBase: removing id %p on RefBase %p"
Mathias Agopianad099652011-08-10 21:07:02 -0700352 "(weakref_type %p) that doesn't exist!",
353 id, mBase, this);
354
355 ref = head;
356 while (ref) {
357 char inc = ref->ref >= 0 ? '+' : '-';
Steve Blockeb095332011-12-20 16:23:08 +0000358 ALOGD("\t%c ID %p (ref %d):", inc, ref->id, ref->ref);
Mathias Agopianad099652011-08-10 21:07:02 -0700359 ref = ref->next;
360 }
361
Hans Boehm2a019ec2018-08-07 23:45:25 +0000362 CallStack::logStack(LOG_TAG);
Mathias Agopianad099652011-08-10 21:07:02 -0700363 }
364 }
365
366 void renameRefsId(ref_entry* r, const void* old_id, const void* new_id)
367 {
368 if (mTrackEnabled) {
369 AutoMutex _l(mMutex);
370 ref_entry* ref = r;
371 while (ref != NULL) {
372 if (ref->id == old_id) {
373 ref->id = new_id;
374 }
375 ref = ref->next;
376 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800377 }
378 }
379
380 void printRefsLocked(String8* out, const ref_entry* refs) const
381 {
382 char buf[128];
383 while (refs) {
384 char inc = refs->ref >= 0 ? '+' : '-';
George Burgess IVe7aa2b22016-03-02 14:02:55 -0800385 snprintf(buf, sizeof(buf), "\t%c ID %p (ref %d):\n",
386 inc, refs->id, refs->ref);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800387 out->append(buf);
388#if DEBUG_REFS_CALLSTACK_ENABLED
Hans Boehm2a019ec2018-08-07 23:45:25 +0000389 out->append(CallStack::stackToString("\t\t", refs->stack.get()));
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800390#else
391 out->append("\t\t(call stacks disabled)");
392#endif
393 refs = refs->next;
394 }
395 }
396
Mathias Agopianad099652011-08-10 21:07:02 -0700397 mutable Mutex mMutex;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800398 ref_entry* mStrongRefs;
399 ref_entry* mWeakRefs;
400
401 bool mTrackEnabled;
402 // Collect stack traces on addref and removeref, instead of deleting the stack references
403 // on removeref that match the address ones.
404 bool mRetain;
405
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800406#endif
407};
408
409// ---------------------------------------------------------------------------
410
411void RefBase::incStrong(const void* id) const
412{
413 weakref_impl* const refs = mRefs;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800414 refs->incWeak(id);
415
416 refs->addStrongRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700417 const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000418 ALOG_ASSERT(c > 0, "incStrong() called on %p after last strong ref", refs);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800419#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000420 ALOGD("incStrong of %p from %p: cnt=%d\n", this, id, c);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800421#endif
422 if (c != INITIAL_STRONG_VALUE) {
423 return;
424 }
425
Chih-Hung Hsieh122352d2017-10-02 15:20:07 -0700426 int32_t old __unused = refs->mStrong.fetch_sub(INITIAL_STRONG_VALUE, std::memory_order_relaxed);
Hans Boehme263e6c2016-05-11 18:15:12 -0700427 // A decStrong() must still happen after us.
428 ALOG_ASSERT(old > INITIAL_STRONG_VALUE, "0x%x too small", old);
Mathias Agopianad099652011-08-10 21:07:02 -0700429 refs->mBase->onFirstRef();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800430}
431
432void RefBase::decStrong(const void* id) const
433{
434 weakref_impl* const refs = mRefs;
435 refs->removeStrongRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700436 const int32_t c = refs->mStrong.fetch_sub(1, std::memory_order_release);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800437#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000438 ALOGD("decStrong of %p from %p: cnt=%d\n", this, id, c);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800439#endif
Hans Boehm23c857e2016-08-02 18:39:30 -0700440 LOG_ALWAYS_FATAL_IF(BAD_STRONG(c), "decStrong() called on %p too many times",
441 refs);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800442 if (c == 1) {
Hans Boehme263e6c2016-05-11 18:15:12 -0700443 std::atomic_thread_fence(std::memory_order_acquire);
Mathias Agopianad099652011-08-10 21:07:02 -0700444 refs->mBase->onLastStrongRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700445 int32_t flags = refs->mFlags.load(std::memory_order_relaxed);
446 if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
Mathias Agopian9c8fa9e2011-06-15 20:42:47 -0700447 delete this;
Hans Boehm23c857e2016-08-02 18:39:30 -0700448 // The destructor does not delete refs in this case.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800449 }
450 }
Hans Boehme263e6c2016-05-11 18:15:12 -0700451 // Note that even with only strong reference operations, the thread
452 // deallocating this may not be the same as the thread deallocating refs.
453 // That's OK: all accesses to this happen before its deletion here,
454 // and all accesses to refs happen before its deletion in the final decWeak.
455 // The destructor can safely access mRefs because either it's deleting
456 // mRefs itself, or it's running entirely before the final mWeak decrement.
George Burgess IV6753bc42017-10-01 12:38:44 -0700457 //
458 // Since we're doing atomic loads of `flags`, the static analyzer assumes
459 // they can change between `delete this;` and `refs->decWeak(id);`. This is
460 // not the case. The analyzer may become more okay with this patten when
461 // https://bugs.llvm.org/show_bug.cgi?id=34365 gets resolved. NOLINTNEXTLINE
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800462 refs->decWeak(id);
463}
464
465void RefBase::forceIncStrong(const void* id) const
466{
Hans Boehme263e6c2016-05-11 18:15:12 -0700467 // Allows initial mStrong of 0 in addition to INITIAL_STRONG_VALUE.
468 // TODO: Better document assumptions.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800469 weakref_impl* const refs = mRefs;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800470 refs->incWeak(id);
471
472 refs->addStrongRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700473 const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000474 ALOG_ASSERT(c >= 0, "forceIncStrong called on %p after ref count underflow",
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800475 refs);
476#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000477 ALOGD("forceIncStrong of %p from %p: cnt=%d\n", this, id, c);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800478#endif
479
480 switch (c) {
481 case INITIAL_STRONG_VALUE:
Hans Boehme263e6c2016-05-11 18:15:12 -0700482 refs->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
483 std::memory_order_relaxed);
Chih-Hung Hsieh502f4862018-09-13 11:08:41 -0700484 FALLTHROUGH_INTENDED;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800485 case 0:
Mathias Agopianad099652011-08-10 21:07:02 -0700486 refs->mBase->onFirstRef();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800487 }
488}
489
490int32_t RefBase::getStrongCount() const
491{
Hans Boehme263e6c2016-05-11 18:15:12 -0700492 // Debugging only; No memory ordering guarantees.
493 return mRefs->mStrong.load(std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800494}
495
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800496RefBase* RefBase::weakref_type::refBase() const
497{
498 return static_cast<const weakref_impl*>(this)->mBase;
499}
500
501void RefBase::weakref_type::incWeak(const void* id)
502{
503 weakref_impl* const impl = static_cast<weakref_impl*>(this);
504 impl->addWeakRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700505 const int32_t c __unused = impl->mWeak.fetch_add(1,
506 std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000507 ALOG_ASSERT(c >= 0, "incWeak called on %p after last weak ref", this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800508}
509
Mathias Agopianad099652011-08-10 21:07:02 -0700510
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800511void RefBase::weakref_type::decWeak(const void* id)
512{
513 weakref_impl* const impl = static_cast<weakref_impl*>(this);
514 impl->removeWeakRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700515 const int32_t c = impl->mWeak.fetch_sub(1, std::memory_order_release);
Hans Boehm23c857e2016-08-02 18:39:30 -0700516 LOG_ALWAYS_FATAL_IF(BAD_WEAK(c), "decWeak called on %p too many times",
517 this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800518 if (c != 1) return;
Hans Boehme263e6c2016-05-11 18:15:12 -0700519 atomic_thread_fence(std::memory_order_acquire);
Mathias Agopianad099652011-08-10 21:07:02 -0700520
Hans Boehme263e6c2016-05-11 18:15:12 -0700521 int32_t flags = impl->mFlags.load(std::memory_order_relaxed);
522 if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
Mathias Agopianad099652011-08-10 21:07:02 -0700523 // This is the regular lifetime case. The object is destroyed
524 // when the last strong reference goes away. Since weakref_impl
Hans Boehm23c857e2016-08-02 18:39:30 -0700525 // outlives the object, it is not destroyed in the dtor, and
Mathias Agopianad099652011-08-10 21:07:02 -0700526 // we'll have to do it here.
Hans Boehme263e6c2016-05-11 18:15:12 -0700527 if (impl->mStrong.load(std::memory_order_relaxed)
528 == INITIAL_STRONG_VALUE) {
Hans Boehm23c857e2016-08-02 18:39:30 -0700529 // Decrementing a weak count to zero when object never had a strong
530 // reference. We assume it acquired a weak reference early, e.g.
531 // in the constructor, and will eventually be properly destroyed,
532 // usually via incrementing and decrementing the strong count.
533 // Thus we no longer do anything here. We log this case, since it
534 // seems to be extremely rare, and should not normally occur. We
535 // used to deallocate mBase here, so this may now indicate a leak.
536 ALOGW("RefBase: Object at %p lost last weak reference "
537 "before it had a strong reference", impl->mBase);
Mathias Agopianad099652011-08-10 21:07:02 -0700538 } else {
Steve Blockb37fbe92011-10-20 11:56:00 +0100539 // ALOGV("Freeing refs %p of old RefBase %p\n", this, impl->mBase);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800540 delete impl;
541 }
542 } else {
Hans Boehme263e6c2016-05-11 18:15:12 -0700543 // This is the OBJECT_LIFETIME_WEAK case. The last weak-reference
544 // is gone, we can destroy the object.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800545 impl->mBase->onLastWeakRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700546 delete impl->mBase;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800547 }
548}
549
550bool RefBase::weakref_type::attemptIncStrong(const void* id)
551{
552 incWeak(id);
553
554 weakref_impl* const impl = static_cast<weakref_impl*>(this);
Hans Boehme263e6c2016-05-11 18:15:12 -0700555 int32_t curCount = impl->mStrong.load(std::memory_order_relaxed);
Dianne Hackborna729ab12013-03-14 15:26:30 -0700556
557 ALOG_ASSERT(curCount >= 0,
558 "attemptIncStrong called on %p after underflow", this);
559
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800560 while (curCount > 0 && curCount != INITIAL_STRONG_VALUE) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700561 // we're in the easy/common case of promoting a weak-reference
562 // from an existing strong reference.
Hans Boehme263e6c2016-05-11 18:15:12 -0700563 if (impl->mStrong.compare_exchange_weak(curCount, curCount+1,
564 std::memory_order_relaxed)) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800565 break;
566 }
Dianne Hackborna729ab12013-03-14 15:26:30 -0700567 // the strong count has changed on us, we need to re-assert our
Hans Boehme263e6c2016-05-11 18:15:12 -0700568 // situation. curCount was updated by compare_exchange_weak.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800569 }
570
571 if (curCount <= 0 || curCount == INITIAL_STRONG_VALUE) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700572 // we're now in the harder case of either:
573 // - there never was a strong reference on us
574 // - or, all strong references have been released
Hans Boehme263e6c2016-05-11 18:15:12 -0700575 int32_t flags = impl->mFlags.load(std::memory_order_relaxed);
576 if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700577 // this object has a "normal" life-time, i.e.: it gets destroyed
578 // when the last strong reference goes away
579 if (curCount <= 0) {
580 // the last strong-reference got released, the object cannot
581 // be revived.
582 decWeak(id);
583 return false;
584 }
585
586 // here, curCount == INITIAL_STRONG_VALUE, which means
587 // there never was a strong-reference, so we can try to
588 // promote this object; we need to do that atomically.
589 while (curCount > 0) {
Hans Boehme263e6c2016-05-11 18:15:12 -0700590 if (impl->mStrong.compare_exchange_weak(curCount, curCount+1,
591 std::memory_order_relaxed)) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700592 break;
593 }
594 // the strong count has changed on us, we need to re-assert our
595 // situation (e.g.: another thread has inc/decStrong'ed us)
Hans Boehme263e6c2016-05-11 18:15:12 -0700596 // curCount has been updated.
Dianne Hackborna729ab12013-03-14 15:26:30 -0700597 }
598
599 if (curCount <= 0) {
600 // promote() failed, some other thread destroyed us in the
601 // meantime (i.e.: strong count reached zero).
602 decWeak(id);
603 return false;
604 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800605 } else {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700606 // this object has an "extended" life-time, i.e.: it can be
607 // revived from a weak-reference only.
608 // Ask the object's implementation if it agrees to be revived
609 if (!impl->mBase->onIncStrongAttempted(FIRST_INC_STRONG, id)) {
610 // it didn't so give-up.
611 decWeak(id);
612 return false;
613 }
614 // grab a strong-reference, which is always safe due to the
615 // extended life-time.
Hans Boehme263e6c2016-05-11 18:15:12 -0700616 curCount = impl->mStrong.fetch_add(1, std::memory_order_relaxed);
Hans Boehm7f27cbc2016-07-29 14:39:10 -0700617 // If the strong reference count has already been incremented by
618 // someone else, the implementor of onIncStrongAttempted() is holding
619 // an unneeded reference. So call onLastStrongRef() here to remove it.
620 // (No, this is not pretty.) Note that we MUST NOT do this if we
621 // are in fact acquiring the first reference.
622 if (curCount != 0 && curCount != INITIAL_STRONG_VALUE) {
623 impl->mBase->onLastStrongRef(id);
624 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800625 }
626 }
627
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800628 impl->addStrongRef(id);
629
630#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000631 ALOGD("attemptIncStrong of %p from %p: cnt=%d\n", this, id, curCount);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800632#endif
633
Hans Boehm7f27cbc2016-07-29 14:39:10 -0700634 // curCount is the value of mStrong before we incremented it.
Hans Boehme263e6c2016-05-11 18:15:12 -0700635 // Now we need to fix-up the count if it was INITIAL_STRONG_VALUE.
636 // This must be done safely, i.e.: handle the case where several threads
Dianne Hackborna729ab12013-03-14 15:26:30 -0700637 // were here in attemptIncStrong().
Hans Boehme263e6c2016-05-11 18:15:12 -0700638 // curCount > INITIAL_STRONG_VALUE is OK, and can happen if we're doing
639 // this in the middle of another incStrong. The subtraction is handled
640 // by the thread that started with INITIAL_STRONG_VALUE.
641 if (curCount == INITIAL_STRONG_VALUE) {
642 impl->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
643 std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800644 }
Dianne Hackborna729ab12013-03-14 15:26:30 -0700645
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800646 return true;
647}
648
649bool RefBase::weakref_type::attemptIncWeak(const void* id)
650{
651 weakref_impl* const impl = static_cast<weakref_impl*>(this);
Mathias Agopianad099652011-08-10 21:07:02 -0700652
Hans Boehme263e6c2016-05-11 18:15:12 -0700653 int32_t curCount = impl->mWeak.load(std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000654 ALOG_ASSERT(curCount >= 0, "attemptIncWeak called on %p after underflow",
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800655 this);
656 while (curCount > 0) {
Hans Boehme263e6c2016-05-11 18:15:12 -0700657 if (impl->mWeak.compare_exchange_weak(curCount, curCount+1,
658 std::memory_order_relaxed)) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800659 break;
660 }
Hans Boehme263e6c2016-05-11 18:15:12 -0700661 // curCount has been updated.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800662 }
663
664 if (curCount > 0) {
665 impl->addWeakRef(id);
666 }
667
668 return curCount > 0;
669}
670
671int32_t RefBase::weakref_type::getWeakCount() const
672{
Hans Boehme263e6c2016-05-11 18:15:12 -0700673 // Debug only!
674 return static_cast<const weakref_impl*>(this)->mWeak
675 .load(std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800676}
677
678void RefBase::weakref_type::printRefs() const
679{
680 static_cast<const weakref_impl*>(this)->printRefs();
681}
682
683void RefBase::weakref_type::trackMe(bool enable, bool retain)
684{
Mathias Agopianad099652011-08-10 21:07:02 -0700685 static_cast<weakref_impl*>(this)->trackMe(enable, retain);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800686}
687
688RefBase::weakref_type* RefBase::createWeak(const void* id) const
689{
690 mRefs->incWeak(id);
691 return mRefs;
692}
693
694RefBase::weakref_type* RefBase::getWeakRefs() const
695{
696 return mRefs;
697}
698
699RefBase::RefBase()
700 : mRefs(new weakref_impl(this))
701{
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800702}
703
704RefBase::~RefBase()
705{
Hans Boehm23c857e2016-08-02 18:39:30 -0700706 int32_t flags = mRefs->mFlags.load(std::memory_order_relaxed);
707 // Life-time of this object is extended to WEAK, in
708 // which case weakref_impl doesn't out-live the object and we
709 // can free it now.
710 if ((flags & OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_WEAK) {
711 // It's possible that the weak count is not 0 if the object
712 // re-acquired a weak reference in its destructor
713 if (mRefs->mWeak.load(std::memory_order_relaxed) == 0) {
714 delete mRefs;
715 }
Hans Boehm2a019ec2018-08-07 23:45:25 +0000716 } else if (mRefs->mStrong.load(std::memory_order_relaxed) == INITIAL_STRONG_VALUE) {
Hans Boehm9ba71922016-07-21 18:56:55 -0700717 // We never acquired a strong reference on this object.
Hans Boehm2a019ec2018-08-07 23:45:25 +0000718#if DEBUG_REFBASE_DESTRUCTION
719 // Treating this as fatal is prone to causing boot loops. For debugging, it's
720 // better to treat as non-fatal.
721 ALOGD("RefBase: Explicit destruction, weak count = %d (in %p)", mRefs->mWeak.load(), this);
722 CallStack::logStack(LOG_TAG);
723#else
724 LOG_ALWAYS_FATAL("RefBase: Explicit destruction, weak count = %d", mRefs->mWeak.load());
725#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800726 }
Hans Boehm23c857e2016-08-02 18:39:30 -0700727 // For debugging purposes, clear mRefs. Ineffective against outstanding wp's.
Yi Konge1731a42018-07-16 18:11:34 -0700728 const_cast<weakref_impl*&>(mRefs) = nullptr;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800729}
730
731void RefBase::extendObjectLifetime(int32_t mode)
732{
Hans Boehme263e6c2016-05-11 18:15:12 -0700733 // Must be happens-before ordered with respect to construction or any
734 // operation that could destroy the object.
735 mRefs->mFlags.fetch_or(mode, std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800736}
737
738void RefBase::onFirstRef()
739{
740}
741
742void RefBase::onLastStrongRef(const void* /*id*/)
743{
744}
745
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700746bool RefBase::onIncStrongAttempted(uint32_t flags, const void* /*id*/)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800747{
748 return (flags&FIRST_INC_STRONG) ? true : false;
749}
750
751void RefBase::onLastWeakRef(const void* /*id*/)
752{
753}
Mathias Agopianad099652011-08-10 21:07:02 -0700754
755// ---------------------------------------------------------------------------
756
Mathias Agopianad099652011-08-10 21:07:02 -0700757#if DEBUG_REFS
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700758void RefBase::renameRefs(size_t n, const ReferenceRenamer& renamer) {
Mathias Agopianad099652011-08-10 21:07:02 -0700759 for (size_t i=0 ; i<n ; i++) {
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700760 renamer(i);
Mathias Agopianad099652011-08-10 21:07:02 -0700761 }
Mathias Agopianad099652011-08-10 21:07:02 -0700762}
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700763#else
764void RefBase::renameRefs(size_t /*n*/, const ReferenceRenamer& /*renamer*/) { }
765#endif
Mathias Agopianad099652011-08-10 21:07:02 -0700766
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700767void RefBase::renameRefId(weakref_type* ref,
768 const void* old_id, const void* new_id) {
769 weakref_impl* const impl = static_cast<weakref_impl*>(ref);
770 impl->renameStrongRefId(old_id, new_id);
771 impl->renameWeakRefId(old_id, new_id);
772}
773
774void RefBase::renameRefId(RefBase* ref,
775 const void* old_id, const void* new_id) {
776 ref->mRefs->renameStrongRefId(old_id, new_id);
777 ref->mRefs->renameWeakRefId(old_id, new_id);
778}
779
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800780}; // namespace android