blob: 2523097958ce2935ff22018c33c323e01c63de18 [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
Christopher Ferris0e691602020-10-14 14:13:58 -070024#include <log/log.h>
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080025
Christopher Ferris0e691602020-10-14 14:13:58 -070026#include <utils/RefBase.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
Christopher Ferris0e691602020-10-14 14:13:58 -070058#if !defined(_WIN32)
59// CallStack is only supported on linux type platforms.
60#define CALLSTACK_ENABLED 1
61#else
62#define CALLSTACK_ENABLED 0
63#endif
64
65#if CALLSTACK_ENABLED
66#include <utils/CallStack.h>
67#endif
68
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080069// ---------------------------------------------------------------------------
70
71namespace android {
72
Hans Boehm9ba71922016-07-21 18:56:55 -070073// Observations, invariants, etc:
Hans Boehme263e6c2016-05-11 18:15:12 -070074
Hans Boehm9ba71922016-07-21 18:56:55 -070075// By default, obects are destroyed when the last strong reference disappears
76// or, if the object never had a strong reference, when the last weak reference
77// disappears.
78//
Hans Boehme263e6c2016-05-11 18:15:12 -070079// OBJECT_LIFETIME_WEAK changes this behavior to retain the object
80// unconditionally until the last reference of either kind disappears. The
81// client ensures that the extendObjectLifetime call happens before the dec
82// call that would otherwise have deallocated the object, or before an
83// attemptIncStrong call that might rely on it. We do not worry about
84// concurrent changes to the object lifetime.
Hans Boehm9ba71922016-07-21 18:56:55 -070085//
86// AttemptIncStrong will succeed if the object has a strong reference, or if it
87// has a weak reference and has never had a strong reference.
88// AttemptIncWeak really does succeed only if there is already a WEAK
89// reference, and thus may fail when attemptIncStrong would succeed.
90//
Hans Boehme263e6c2016-05-11 18:15:12 -070091// mStrong is the strong reference count. mWeak is the weak reference count.
92// Between calls, and ignoring memory ordering effects, mWeak includes strong
93// references, and is thus >= mStrong.
94//
Hans Boehm9ba71922016-07-21 18:56:55 -070095// A weakref_impl holds all the information, including both reference counts,
96// required to perform wp<> operations. Thus these can continue to be performed
97// after the RefBase object has been destroyed.
98//
Hans Boehme263e6c2016-05-11 18:15:12 -070099// A weakref_impl is allocated as the value of mRefs in a RefBase object on
100// construction.
Hans Boehm23c857e2016-08-02 18:39:30 -0700101// In the OBJECT_LIFETIME_STRONG case, it is normally deallocated in decWeak,
102// and hence lives as long as the last weak reference. (It can also be
103// deallocated in the RefBase destructor iff the strong reference count was
104// never incremented and the weak count is zero, e.g. if the RefBase object is
105// explicitly destroyed without decrementing the strong count. This should be
106// avoided.) In this case, the RefBase destructor should be invoked from
107// decStrong.
108// In the OBJECT_LIFETIME_WEAK case, the weakref_impl is always deallocated in
109// the RefBase destructor, which is always invoked by decWeak. DecStrong
110// explicitly avoids the deletion in this case.
Hans Boehme263e6c2016-05-11 18:15:12 -0700111//
112// Memory ordering:
113// The client must ensure that every inc() call, together with all other
114// accesses to the object, happens before the corresponding dec() call.
115//
116// We try to keep memory ordering constraints on atomics as weak as possible,
117// since memory fences or ordered memory accesses are likely to be a major
118// performance cost for this code. All accesses to mStrong, mWeak, and mFlags
119// explicitly relax memory ordering in some way.
120//
121// The only operations that are not memory_order_relaxed are reference count
122// decrements. All reference count decrements are release operations. In
123// addition, the final decrement leading the deallocation is followed by an
124// acquire fence, which we can view informally as also turning it into an
125// acquire operation. (See 29.8p4 [atomics.fences] for details. We could
126// alternatively use acq_rel operations for all decrements. This is probably
127// slower on most current (2016) hardware, especially on ARMv7, but that may
128// not be true indefinitely.)
129//
130// This convention ensures that the second-to-last decrement synchronizes with
131// (in the language of 1.10 in the C++ standard) the final decrement of a
132// reference count. Since reference counts are only updated using atomic
133// read-modify-write operations, this also extends to any earlier decrements.
134// (See "release sequence" in 1.10.)
135//
136// Since all operations on an object happen before the corresponding reference
137// count decrement, and all reference count decrements happen before the final
138// one, we are guaranteed that all other object accesses happen before the
139// object is destroyed.
140
141
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800142#define INITIAL_STRONG_VALUE (1<<28)
143
Hans Boehm23c857e2016-08-02 18:39:30 -0700144#define MAX_COUNT 0xfffff
145
146// Test whether the argument is a clearly invalid strong reference count.
147// Used only for error checking on the value before an atomic decrement.
148// Intended to be very cheap.
149// Note that we cannot just check for excess decrements by comparing to zero
150// since the object would be deallocated before that.
151#define BAD_STRONG(c) \
152 ((c) == 0 || ((c) & (~(MAX_COUNT | INITIAL_STRONG_VALUE))) != 0)
153
154// Same for weak counts.
155#define BAD_WEAK(c) ((c) == 0 || ((c) & (~MAX_COUNT)) != 0)
156
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800157// ---------------------------------------------------------------------------
158
159class RefBase::weakref_impl : public RefBase::weakref_type
160{
161public:
Hans Boehme263e6c2016-05-11 18:15:12 -0700162 std::atomic<int32_t> mStrong;
163 std::atomic<int32_t> mWeak;
164 RefBase* const mBase;
165 std::atomic<int32_t> mFlags;
Mathias Agopian9c8fa9e2011-06-15 20:42:47 -0700166
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800167#if !DEBUG_REFS
168
Chih-Hung Hsieh1c563d92016-04-29 15:44:04 -0700169 explicit weakref_impl(RefBase* base)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800170 : mStrong(INITIAL_STRONG_VALUE)
171 , mWeak(0)
172 , mBase(base)
173 , mFlags(0)
174 {
175 }
176
177 void addStrongRef(const void* /*id*/) { }
178 void removeStrongRef(const void* /*id*/) { }
Mathias Agopianad099652011-08-10 21:07:02 -0700179 void renameStrongRefId(const void* /*old_id*/, const void* /*new_id*/) { }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800180 void addWeakRef(const void* /*id*/) { }
181 void removeWeakRef(const void* /*id*/) { }
Mathias Agopianad099652011-08-10 21:07:02 -0700182 void renameWeakRefId(const void* /*old_id*/, const void* /*new_id*/) { }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800183 void printRefs() const { }
184 void trackMe(bool, bool) { }
185
186#else
187
188 weakref_impl(RefBase* base)
189 : mStrong(INITIAL_STRONG_VALUE)
190 , mWeak(0)
191 , mBase(base)
192 , mFlags(0)
193 , mStrongRefs(NULL)
194 , mWeakRefs(NULL)
195 , mTrackEnabled(!!DEBUG_REFS_ENABLED_BY_DEFAULT)
196 , mRetain(false)
197 {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800198 }
Christopher Ferris0e691602020-10-14 14:13:58 -0700199
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800200 ~weakref_impl()
201 {
Mathias Agopianad099652011-08-10 21:07:02 -0700202 bool dumpStack = false;
203 if (!mRetain && mStrongRefs != NULL) {
204 dumpStack = true;
Steve Block1b781ab2012-01-06 19:20:56 +0000205 ALOGE("Strong references remain:");
Mathias Agopianad099652011-08-10 21:07:02 -0700206 ref_entry* refs = mStrongRefs;
207 while (refs) {
208 char inc = refs->ref >= 0 ? '+' : '-';
Steve Blockeb095332011-12-20 16:23:08 +0000209 ALOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
Christopher Ferris0e691602020-10-14 14:13:58 -0700210#if DEBUG_REFS_CALLSTACK_ENABLED && CALLSTACK_ENABLED
Hans Boehm2a019ec2018-08-07 23:45:25 +0000211 CallStack::logStack(LOG_TAG, refs->stack.get());
Mathias Agopianad099652011-08-10 21:07:02 -0700212#endif
213 refs = refs->next;
214 }
215 }
216
217 if (!mRetain && mWeakRefs != NULL) {
218 dumpStack = true;
Steve Block1b781ab2012-01-06 19:20:56 +0000219 ALOGE("Weak references remain!");
Mathias Agopianad099652011-08-10 21:07:02 -0700220 ref_entry* refs = mWeakRefs;
221 while (refs) {
222 char inc = refs->ref >= 0 ? '+' : '-';
Steve Blockeb095332011-12-20 16:23:08 +0000223 ALOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
Christopher Ferris0e691602020-10-14 14:13:58 -0700224#if DEBUG_REFS_CALLSTACK_ENABLED && CALLSTACK_ENABLED
Hans Boehm2a019ec2018-08-07 23:45:25 +0000225 CallStack::logStack(LOG_TAG, refs->stack.get());
Mathias Agopianad099652011-08-10 21:07:02 -0700226#endif
227 refs = refs->next;
228 }
229 }
230 if (dumpStack) {
Steve Block1b781ab2012-01-06 19:20:56 +0000231 ALOGE("above errors at:");
Christopher Ferris0e691602020-10-14 14:13:58 -0700232#if CALLSTACK_ENABLED
Hans Boehm2a019ec2018-08-07 23:45:25 +0000233 CallStack::logStack(LOG_TAG);
Christopher Ferris0e691602020-10-14 14:13:58 -0700234#endif
Mathias Agopianad099652011-08-10 21:07:02 -0700235 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800236 }
237
Mathias Agopianad099652011-08-10 21:07:02 -0700238 void addStrongRef(const void* id) {
Steve Blockeb095332011-12-20 16:23:08 +0000239 //ALOGD_IF(mTrackEnabled,
Mathias Agopianad099652011-08-10 21:07:02 -0700240 // "addStrongRef: RefBase=%p, id=%p", mBase, id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700241 addRef(&mStrongRefs, id, mStrong.load(std::memory_order_relaxed));
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800242 }
243
Mathias Agopianad099652011-08-10 21:07:02 -0700244 void removeStrongRef(const void* id) {
Steve Blockeb095332011-12-20 16:23:08 +0000245 //ALOGD_IF(mTrackEnabled,
Mathias Agopianad099652011-08-10 21:07:02 -0700246 // "removeStrongRef: RefBase=%p, id=%p", mBase, id);
247 if (!mRetain) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800248 removeRef(&mStrongRefs, id);
Mathias Agopianad099652011-08-10 21:07:02 -0700249 } else {
Hans Boehme263e6c2016-05-11 18:15:12 -0700250 addRef(&mStrongRefs, id, -mStrong.load(std::memory_order_relaxed));
Mathias Agopianad099652011-08-10 21:07:02 -0700251 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800252 }
253
Mathias Agopianad099652011-08-10 21:07:02 -0700254 void renameStrongRefId(const void* old_id, const void* new_id) {
Steve Blockeb095332011-12-20 16:23:08 +0000255 //ALOGD_IF(mTrackEnabled,
Mathias Agopianad099652011-08-10 21:07:02 -0700256 // "renameStrongRefId: RefBase=%p, oid=%p, nid=%p",
257 // mBase, old_id, new_id);
258 renameRefsId(mStrongRefs, old_id, new_id);
259 }
260
261 void addWeakRef(const void* id) {
Hans Boehme263e6c2016-05-11 18:15:12 -0700262 addRef(&mWeakRefs, id, mWeak.load(std::memory_order_relaxed));
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800263 }
264
Mathias Agopianad099652011-08-10 21:07:02 -0700265 void removeWeakRef(const void* id) {
266 if (!mRetain) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800267 removeRef(&mWeakRefs, id);
Mathias Agopianad099652011-08-10 21:07:02 -0700268 } else {
Hans Boehme263e6c2016-05-11 18:15:12 -0700269 addRef(&mWeakRefs, id, -mWeak.load(std::memory_order_relaxed));
Mathias Agopianad099652011-08-10 21:07:02 -0700270 }
271 }
272
273 void renameWeakRefId(const void* old_id, const void* new_id) {
274 renameRefsId(mWeakRefs, old_id, new_id);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800275 }
276
Christopher Ferris0e691602020-10-14 14:13:58 -0700277 void trackMe(bool track, bool retain) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800278 mTrackEnabled = track;
279 mRetain = retain;
280 }
281
282 void printRefs() const
283 {
284 String8 text;
285
286 {
Mathias Agopianad099652011-08-10 21:07:02 -0700287 Mutex::Autolock _l(mMutex);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800288 char buf[128];
George Burgess IVe7aa2b22016-03-02 14:02:55 -0800289 snprintf(buf, sizeof(buf),
290 "Strong references on RefBase %p (weakref_type %p):\n",
291 mBase, this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800292 text.append(buf);
293 printRefsLocked(&text, mStrongRefs);
George Burgess IVe7aa2b22016-03-02 14:02:55 -0800294 snprintf(buf, sizeof(buf),
295 "Weak references on RefBase %p (weakref_type %p):\n",
296 mBase, this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800297 text.append(buf);
298 printRefsLocked(&text, mWeakRefs);
299 }
300
301 {
302 char name[100];
George Burgess IVe7aa2b22016-03-02 14:02:55 -0800303 snprintf(name, sizeof(name), DEBUG_REFS_CALLSTACK_PATH "/%p.stack",
304 this);
Mathias Agopian769828d2013-03-06 17:51:15 -0800305 int rc = open(name, O_RDWR | O_CREAT | O_APPEND, 644);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800306 if (rc >= 0) {
Hans Boehm2a019ec2018-08-07 23:45:25 +0000307 (void)write(rc, text.string(), text.length());
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800308 close(rc);
Steve Blockeb095332011-12-20 16:23:08 +0000309 ALOGD("STACK TRACE for %p saved in %s", this, name);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800310 }
Steve Block1b781ab2012-01-06 19:20:56 +0000311 else ALOGE("FAILED TO PRINT STACK TRACE for %p in %s: %s", this,
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800312 name, strerror(errno));
313 }
314 }
315
316private:
317 struct ref_entry
318 {
319 ref_entry* next;
320 const void* id;
Christopher Ferris0e691602020-10-14 14:13:58 -0700321#if DEBUG_REFS_CALLSTACK_ENABLED && CALLSTACK_ENABLED
Hans Boehm2a019ec2018-08-07 23:45:25 +0000322 CallStack::CallStackUPtr stack;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800323#endif
324 int32_t ref;
325 };
326
327 void addRef(ref_entry** refs, const void* id, int32_t mRef)
328 {
329 if (mTrackEnabled) {
330 AutoMutex _l(mMutex);
Mathias Agopianad099652011-08-10 21:07:02 -0700331
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800332 ref_entry* ref = new ref_entry;
333 // Reference count at the time of the snapshot, but before the
334 // update. Positive value means we increment, negative--we
335 // decrement the reference count.
336 ref->ref = mRef;
337 ref->id = id;
Christopher Ferris0e691602020-10-14 14:13:58 -0700338#if DEBUG_REFS_CALLSTACK_ENABLED && CALLSTACK_ENABLED
Hans Boehm2a019ec2018-08-07 23:45:25 +0000339 ref->stack = CallStack::getCurrent(2);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800340#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800341 ref->next = *refs;
342 *refs = ref;
343 }
344 }
345
346 void removeRef(ref_entry** refs, const void* id)
347 {
348 if (mTrackEnabled) {
349 AutoMutex _l(mMutex);
Christopher Ferris0e691602020-10-14 14:13:58 -0700350
Mathias Agopianad099652011-08-10 21:07:02 -0700351 ref_entry* const head = *refs;
352 ref_entry* ref = head;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800353 while (ref != NULL) {
354 if (ref->id == id) {
355 *refs = ref->next;
356 delete ref;
357 return;
358 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800359 refs = &ref->next;
360 ref = *refs;
361 }
Mathias Agopianad099652011-08-10 21:07:02 -0700362
Steve Block1b781ab2012-01-06 19:20:56 +0000363 ALOGE("RefBase: removing id %p on RefBase %p"
Mathias Agopianad099652011-08-10 21:07:02 -0700364 "(weakref_type %p) that doesn't exist!",
365 id, mBase, this);
366
367 ref = head;
368 while (ref) {
369 char inc = ref->ref >= 0 ? '+' : '-';
Steve Blockeb095332011-12-20 16:23:08 +0000370 ALOGD("\t%c ID %p (ref %d):", inc, ref->id, ref->ref);
Mathias Agopianad099652011-08-10 21:07:02 -0700371 ref = ref->next;
372 }
373
Christopher Ferris0e691602020-10-14 14:13:58 -0700374#if CALLSTACK_ENABLED
Hans Boehm2a019ec2018-08-07 23:45:25 +0000375 CallStack::logStack(LOG_TAG);
Christopher Ferris0e691602020-10-14 14:13:58 -0700376#endif
Mathias Agopianad099652011-08-10 21:07:02 -0700377 }
378 }
379
380 void renameRefsId(ref_entry* r, const void* old_id, const void* new_id)
381 {
382 if (mTrackEnabled) {
383 AutoMutex _l(mMutex);
384 ref_entry* ref = r;
385 while (ref != NULL) {
386 if (ref->id == old_id) {
387 ref->id = new_id;
388 }
389 ref = ref->next;
390 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800391 }
392 }
393
394 void printRefsLocked(String8* out, const ref_entry* refs) const
395 {
396 char buf[128];
397 while (refs) {
398 char inc = refs->ref >= 0 ? '+' : '-';
George Burgess IVe7aa2b22016-03-02 14:02:55 -0800399 snprintf(buf, sizeof(buf), "\t%c ID %p (ref %d):\n",
400 inc, refs->id, refs->ref);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800401 out->append(buf);
Christopher Ferris0e691602020-10-14 14:13:58 -0700402#if DEBUG_REFS_CALLSTACK_ENABLED && CALLSTACK_ENABLED
Hans Boehm2a019ec2018-08-07 23:45:25 +0000403 out->append(CallStack::stackToString("\t\t", refs->stack.get()));
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800404#else
405 out->append("\t\t(call stacks disabled)");
406#endif
407 refs = refs->next;
408 }
409 }
410
Mathias Agopianad099652011-08-10 21:07:02 -0700411 mutable Mutex mMutex;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800412 ref_entry* mStrongRefs;
413 ref_entry* mWeakRefs;
414
415 bool mTrackEnabled;
416 // Collect stack traces on addref and removeref, instead of deleting the stack references
417 // on removeref that match the address ones.
418 bool mRetain;
419
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800420#endif
421};
422
423// ---------------------------------------------------------------------------
424
425void RefBase::incStrong(const void* id) const
426{
427 weakref_impl* const refs = mRefs;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800428 refs->incWeak(id);
Christopher Ferris0e691602020-10-14 14:13:58 -0700429
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800430 refs->addStrongRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700431 const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000432 ALOG_ASSERT(c > 0, "incStrong() called on %p after last strong ref", refs);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800433#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000434 ALOGD("incStrong of %p from %p: cnt=%d\n", this, id, c);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800435#endif
436 if (c != INITIAL_STRONG_VALUE) {
437 return;
438 }
439
Chih-Hung Hsieh122352d2017-10-02 15:20:07 -0700440 int32_t old __unused = refs->mStrong.fetch_sub(INITIAL_STRONG_VALUE, std::memory_order_relaxed);
Hans Boehme263e6c2016-05-11 18:15:12 -0700441 // A decStrong() must still happen after us.
442 ALOG_ASSERT(old > INITIAL_STRONG_VALUE, "0x%x too small", old);
Mathias Agopianad099652011-08-10 21:07:02 -0700443 refs->mBase->onFirstRef();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800444}
445
446void RefBase::decStrong(const void* id) const
447{
448 weakref_impl* const refs = mRefs;
449 refs->removeStrongRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700450 const int32_t c = refs->mStrong.fetch_sub(1, std::memory_order_release);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800451#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000452 ALOGD("decStrong of %p from %p: cnt=%d\n", this, id, c);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800453#endif
Hans Boehm23c857e2016-08-02 18:39:30 -0700454 LOG_ALWAYS_FATAL_IF(BAD_STRONG(c), "decStrong() called on %p too many times",
455 refs);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800456 if (c == 1) {
Hans Boehme263e6c2016-05-11 18:15:12 -0700457 std::atomic_thread_fence(std::memory_order_acquire);
Mathias Agopianad099652011-08-10 21:07:02 -0700458 refs->mBase->onLastStrongRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700459 int32_t flags = refs->mFlags.load(std::memory_order_relaxed);
460 if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
Mathias Agopian9c8fa9e2011-06-15 20:42:47 -0700461 delete this;
Hans Boehm23c857e2016-08-02 18:39:30 -0700462 // The destructor does not delete refs in this case.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800463 }
464 }
Hans Boehme263e6c2016-05-11 18:15:12 -0700465 // Note that even with only strong reference operations, the thread
466 // deallocating this may not be the same as the thread deallocating refs.
467 // That's OK: all accesses to this happen before its deletion here,
468 // and all accesses to refs happen before its deletion in the final decWeak.
469 // The destructor can safely access mRefs because either it's deleting
470 // mRefs itself, or it's running entirely before the final mWeak decrement.
George Burgess IV6753bc42017-10-01 12:38:44 -0700471 //
472 // Since we're doing atomic loads of `flags`, the static analyzer assumes
473 // they can change between `delete this;` and `refs->decWeak(id);`. This is
474 // not the case. The analyzer may become more okay with this patten when
475 // https://bugs.llvm.org/show_bug.cgi?id=34365 gets resolved. NOLINTNEXTLINE
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800476 refs->decWeak(id);
477}
478
479void RefBase::forceIncStrong(const void* id) const
480{
Hans Boehme263e6c2016-05-11 18:15:12 -0700481 // Allows initial mStrong of 0 in addition to INITIAL_STRONG_VALUE.
482 // TODO: Better document assumptions.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800483 weakref_impl* const refs = mRefs;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800484 refs->incWeak(id);
Christopher Ferris0e691602020-10-14 14:13:58 -0700485
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800486 refs->addStrongRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700487 const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000488 ALOG_ASSERT(c >= 0, "forceIncStrong called on %p after ref count underflow",
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800489 refs);
490#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000491 ALOGD("forceIncStrong of %p from %p: cnt=%d\n", this, id, c);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800492#endif
493
494 switch (c) {
495 case INITIAL_STRONG_VALUE:
Hans Boehme263e6c2016-05-11 18:15:12 -0700496 refs->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
497 std::memory_order_relaxed);
Chih-Hung Hsieh502f4862018-09-13 11:08:41 -0700498 FALLTHROUGH_INTENDED;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800499 case 0:
Mathias Agopianad099652011-08-10 21:07:02 -0700500 refs->mBase->onFirstRef();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800501 }
502}
503
504int32_t RefBase::getStrongCount() const
505{
Hans Boehme263e6c2016-05-11 18:15:12 -0700506 // Debugging only; No memory ordering guarantees.
507 return mRefs->mStrong.load(std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800508}
509
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800510RefBase* RefBase::weakref_type::refBase() const
511{
512 return static_cast<const weakref_impl*>(this)->mBase;
513}
514
515void RefBase::weakref_type::incWeak(const void* id)
516{
517 weakref_impl* const impl = static_cast<weakref_impl*>(this);
518 impl->addWeakRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700519 const int32_t c __unused = impl->mWeak.fetch_add(1,
520 std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000521 ALOG_ASSERT(c >= 0, "incWeak called on %p after last weak ref", this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800522}
523
Mathias Agopianad099652011-08-10 21:07:02 -0700524
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800525void RefBase::weakref_type::decWeak(const void* id)
526{
527 weakref_impl* const impl = static_cast<weakref_impl*>(this);
528 impl->removeWeakRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700529 const int32_t c = impl->mWeak.fetch_sub(1, std::memory_order_release);
Hans Boehm23c857e2016-08-02 18:39:30 -0700530 LOG_ALWAYS_FATAL_IF(BAD_WEAK(c), "decWeak called on %p too many times",
531 this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800532 if (c != 1) return;
Hans Boehme263e6c2016-05-11 18:15:12 -0700533 atomic_thread_fence(std::memory_order_acquire);
Mathias Agopianad099652011-08-10 21:07:02 -0700534
Hans Boehme263e6c2016-05-11 18:15:12 -0700535 int32_t flags = impl->mFlags.load(std::memory_order_relaxed);
536 if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
Mathias Agopianad099652011-08-10 21:07:02 -0700537 // This is the regular lifetime case. The object is destroyed
538 // when the last strong reference goes away. Since weakref_impl
Hans Boehm23c857e2016-08-02 18:39:30 -0700539 // outlives the object, it is not destroyed in the dtor, and
Mathias Agopianad099652011-08-10 21:07:02 -0700540 // we'll have to do it here.
Hans Boehme263e6c2016-05-11 18:15:12 -0700541 if (impl->mStrong.load(std::memory_order_relaxed)
542 == INITIAL_STRONG_VALUE) {
Hans Boehm23c857e2016-08-02 18:39:30 -0700543 // Decrementing a weak count to zero when object never had a strong
544 // reference. We assume it acquired a weak reference early, e.g.
545 // in the constructor, and will eventually be properly destroyed,
546 // usually via incrementing and decrementing the strong count.
547 // Thus we no longer do anything here. We log this case, since it
548 // seems to be extremely rare, and should not normally occur. We
549 // used to deallocate mBase here, so this may now indicate a leak.
550 ALOGW("RefBase: Object at %p lost last weak reference "
551 "before it had a strong reference", impl->mBase);
Mathias Agopianad099652011-08-10 21:07:02 -0700552 } else {
Steve Blockb37fbe92011-10-20 11:56:00 +0100553 // ALOGV("Freeing refs %p of old RefBase %p\n", this, impl->mBase);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800554 delete impl;
555 }
556 } else {
Hans Boehme263e6c2016-05-11 18:15:12 -0700557 // This is the OBJECT_LIFETIME_WEAK case. The last weak-reference
558 // is gone, we can destroy the object.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800559 impl->mBase->onLastWeakRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700560 delete impl->mBase;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800561 }
562}
563
564bool RefBase::weakref_type::attemptIncStrong(const void* id)
565{
566 incWeak(id);
Christopher Ferris0e691602020-10-14 14:13:58 -0700567
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800568 weakref_impl* const impl = static_cast<weakref_impl*>(this);
Hans Boehme263e6c2016-05-11 18:15:12 -0700569 int32_t curCount = impl->mStrong.load(std::memory_order_relaxed);
Dianne Hackborna729ab12013-03-14 15:26:30 -0700570
571 ALOG_ASSERT(curCount >= 0,
572 "attemptIncStrong called on %p after underflow", this);
573
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800574 while (curCount > 0 && curCount != INITIAL_STRONG_VALUE) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700575 // we're in the easy/common case of promoting a weak-reference
576 // from an existing strong reference.
Hans Boehme263e6c2016-05-11 18:15:12 -0700577 if (impl->mStrong.compare_exchange_weak(curCount, curCount+1,
578 std::memory_order_relaxed)) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800579 break;
580 }
Dianne Hackborna729ab12013-03-14 15:26:30 -0700581 // the strong count has changed on us, we need to re-assert our
Hans Boehme263e6c2016-05-11 18:15:12 -0700582 // situation. curCount was updated by compare_exchange_weak.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800583 }
Christopher Ferris0e691602020-10-14 14:13:58 -0700584
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800585 if (curCount <= 0 || curCount == INITIAL_STRONG_VALUE) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700586 // we're now in the harder case of either:
587 // - there never was a strong reference on us
588 // - or, all strong references have been released
Hans Boehme263e6c2016-05-11 18:15:12 -0700589 int32_t flags = impl->mFlags.load(std::memory_order_relaxed);
590 if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700591 // this object has a "normal" life-time, i.e.: it gets destroyed
592 // when the last strong reference goes away
593 if (curCount <= 0) {
594 // the last strong-reference got released, the object cannot
595 // be revived.
596 decWeak(id);
597 return false;
598 }
599
600 // here, curCount == INITIAL_STRONG_VALUE, which means
601 // there never was a strong-reference, so we can try to
602 // promote this object; we need to do that atomically.
603 while (curCount > 0) {
Hans Boehme263e6c2016-05-11 18:15:12 -0700604 if (impl->mStrong.compare_exchange_weak(curCount, curCount+1,
605 std::memory_order_relaxed)) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700606 break;
607 }
608 // the strong count has changed on us, we need to re-assert our
609 // situation (e.g.: another thread has inc/decStrong'ed us)
Hans Boehme263e6c2016-05-11 18:15:12 -0700610 // curCount has been updated.
Dianne Hackborna729ab12013-03-14 15:26:30 -0700611 }
612
613 if (curCount <= 0) {
614 // promote() failed, some other thread destroyed us in the
615 // meantime (i.e.: strong count reached zero).
616 decWeak(id);
617 return false;
618 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800619 } else {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700620 // this object has an "extended" life-time, i.e.: it can be
621 // revived from a weak-reference only.
622 // Ask the object's implementation if it agrees to be revived
623 if (!impl->mBase->onIncStrongAttempted(FIRST_INC_STRONG, id)) {
624 // it didn't so give-up.
625 decWeak(id);
626 return false;
627 }
628 // grab a strong-reference, which is always safe due to the
629 // extended life-time.
Hans Boehme263e6c2016-05-11 18:15:12 -0700630 curCount = impl->mStrong.fetch_add(1, std::memory_order_relaxed);
Hans Boehm7f27cbc2016-07-29 14:39:10 -0700631 // If the strong reference count has already been incremented by
632 // someone else, the implementor of onIncStrongAttempted() is holding
633 // an unneeded reference. So call onLastStrongRef() here to remove it.
634 // (No, this is not pretty.) Note that we MUST NOT do this if we
635 // are in fact acquiring the first reference.
636 if (curCount != 0 && curCount != INITIAL_STRONG_VALUE) {
637 impl->mBase->onLastStrongRef(id);
638 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800639 }
640 }
Christopher Ferris0e691602020-10-14 14:13:58 -0700641
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800642 impl->addStrongRef(id);
643
644#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000645 ALOGD("attemptIncStrong of %p from %p: cnt=%d\n", this, id, curCount);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800646#endif
647
Hans Boehm7f27cbc2016-07-29 14:39:10 -0700648 // curCount is the value of mStrong before we incremented it.
Hans Boehme263e6c2016-05-11 18:15:12 -0700649 // Now we need to fix-up the count if it was INITIAL_STRONG_VALUE.
650 // This must be done safely, i.e.: handle the case where several threads
Dianne Hackborna729ab12013-03-14 15:26:30 -0700651 // were here in attemptIncStrong().
Hans Boehme263e6c2016-05-11 18:15:12 -0700652 // curCount > INITIAL_STRONG_VALUE is OK, and can happen if we're doing
653 // this in the middle of another incStrong. The subtraction is handled
654 // by the thread that started with INITIAL_STRONG_VALUE.
655 if (curCount == INITIAL_STRONG_VALUE) {
656 impl->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
657 std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800658 }
Dianne Hackborna729ab12013-03-14 15:26:30 -0700659
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800660 return true;
661}
662
663bool RefBase::weakref_type::attemptIncWeak(const void* id)
664{
665 weakref_impl* const impl = static_cast<weakref_impl*>(this);
Mathias Agopianad099652011-08-10 21:07:02 -0700666
Hans Boehme263e6c2016-05-11 18:15:12 -0700667 int32_t curCount = impl->mWeak.load(std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000668 ALOG_ASSERT(curCount >= 0, "attemptIncWeak called on %p after underflow",
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800669 this);
670 while (curCount > 0) {
Hans Boehme263e6c2016-05-11 18:15:12 -0700671 if (impl->mWeak.compare_exchange_weak(curCount, curCount+1,
672 std::memory_order_relaxed)) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800673 break;
674 }
Hans Boehme263e6c2016-05-11 18:15:12 -0700675 // curCount has been updated.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800676 }
677
678 if (curCount > 0) {
679 impl->addWeakRef(id);
680 }
681
682 return curCount > 0;
683}
684
685int32_t RefBase::weakref_type::getWeakCount() const
686{
Hans Boehme263e6c2016-05-11 18:15:12 -0700687 // Debug only!
688 return static_cast<const weakref_impl*>(this)->mWeak
689 .load(std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800690}
691
692void RefBase::weakref_type::printRefs() const
693{
694 static_cast<const weakref_impl*>(this)->printRefs();
695}
696
697void RefBase::weakref_type::trackMe(bool enable, bool retain)
698{
Mathias Agopianad099652011-08-10 21:07:02 -0700699 static_cast<weakref_impl*>(this)->trackMe(enable, retain);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800700}
701
702RefBase::weakref_type* RefBase::createWeak(const void* id) const
703{
704 mRefs->incWeak(id);
705 return mRefs;
706}
707
708RefBase::weakref_type* RefBase::getWeakRefs() const
709{
710 return mRefs;
711}
712
713RefBase::RefBase()
714 : mRefs(new weakref_impl(this))
715{
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800716}
717
718RefBase::~RefBase()
719{
Hans Boehm23c857e2016-08-02 18:39:30 -0700720 int32_t flags = mRefs->mFlags.load(std::memory_order_relaxed);
721 // Life-time of this object is extended to WEAK, in
722 // which case weakref_impl doesn't out-live the object and we
723 // can free it now.
724 if ((flags & OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_WEAK) {
725 // It's possible that the weak count is not 0 if the object
726 // re-acquired a weak reference in its destructor
727 if (mRefs->mWeak.load(std::memory_order_relaxed) == 0) {
728 delete mRefs;
729 }
Hans Boehm2a019ec2018-08-07 23:45:25 +0000730 } else if (mRefs->mStrong.load(std::memory_order_relaxed) == INITIAL_STRONG_VALUE) {
Hans Boehm9ba71922016-07-21 18:56:55 -0700731 // We never acquired a strong reference on this object.
Hans Boehm2a019ec2018-08-07 23:45:25 +0000732#if DEBUG_REFBASE_DESTRUCTION
733 // Treating this as fatal is prone to causing boot loops. For debugging, it's
734 // better to treat as non-fatal.
735 ALOGD("RefBase: Explicit destruction, weak count = %d (in %p)", mRefs->mWeak.load(), this);
Christopher Ferris0e691602020-10-14 14:13:58 -0700736
737#if CALLSTACK_ENABLED
Hans Boehm2a019ec2018-08-07 23:45:25 +0000738 CallStack::logStack(LOG_TAG);
Christopher Ferris0e691602020-10-14 14:13:58 -0700739#endif
Hans Boehm2a019ec2018-08-07 23:45:25 +0000740#else
741 LOG_ALWAYS_FATAL("RefBase: Explicit destruction, weak count = %d", mRefs->mWeak.load());
742#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800743 }
Hans Boehm23c857e2016-08-02 18:39:30 -0700744 // For debugging purposes, clear mRefs. Ineffective against outstanding wp's.
Yi Konge1731a42018-07-16 18:11:34 -0700745 const_cast<weakref_impl*&>(mRefs) = nullptr;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800746}
747
748void RefBase::extendObjectLifetime(int32_t mode)
749{
Hans Boehme263e6c2016-05-11 18:15:12 -0700750 // Must be happens-before ordered with respect to construction or any
751 // operation that could destroy the object.
752 mRefs->mFlags.fetch_or(mode, std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800753}
754
755void RefBase::onFirstRef()
756{
757}
758
759void RefBase::onLastStrongRef(const void* /*id*/)
760{
761}
762
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700763bool RefBase::onIncStrongAttempted(uint32_t flags, const void* /*id*/)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800764{
765 return (flags&FIRST_INC_STRONG) ? true : false;
766}
767
768void RefBase::onLastWeakRef(const void* /*id*/)
769{
770}
Mathias Agopianad099652011-08-10 21:07:02 -0700771
772// ---------------------------------------------------------------------------
773
Mathias Agopianad099652011-08-10 21:07:02 -0700774#if DEBUG_REFS
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700775void RefBase::renameRefs(size_t n, const ReferenceRenamer& renamer) {
Mathias Agopianad099652011-08-10 21:07:02 -0700776 for (size_t i=0 ; i<n ; i++) {
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700777 renamer(i);
Mathias Agopianad099652011-08-10 21:07:02 -0700778 }
Mathias Agopianad099652011-08-10 21:07:02 -0700779}
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700780#else
781void RefBase::renameRefs(size_t /*n*/, const ReferenceRenamer& /*renamer*/) { }
782#endif
Mathias Agopianad099652011-08-10 21:07:02 -0700783
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700784void RefBase::renameRefId(weakref_type* ref,
785 const void* old_id, const void* new_id) {
786 weakref_impl* const impl = static_cast<weakref_impl*>(ref);
787 impl->renameStrongRefId(old_id, new_id);
788 impl->renameWeakRefId(old_id, new_id);
789}
790
791void RefBase::renameRefId(RefBase* ref,
792 const void* old_id, const void* new_id) {
793 ref->mRefs->renameStrongRefId(old_id, new_id);
794 ref->mRefs->renameWeakRefId(old_id, new_id);
795}
796
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800797}; // namespace android