blob: 1f8395b406769813201967a7dd6c735c2ef18f3d [file] [log] [blame]
The Android Open Source Projectcbb10112009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2005 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "RefBase"
Mathias Agopianda8ec4b2013-03-19 17:36:57 -070018// #define LOG_NDEBUG 0
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080019
Mark Salyzyn5bed8032014-04-30 11:10:46 -070020#include <fcntl.h>
21#include <stdio.h>
22#include <stdlib.h>
23#include <sys/stat.h>
24#include <sys/types.h>
25#include <typeinfo>
26#include <unistd.h>
27
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080028#include <utils/RefBase.h>
29
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080030#include <utils/CallStack.h>
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080031#include <utils/Log.h>
32#include <utils/threads.h>
33
Mark Salyzyn5bed8032014-04-30 11:10:46 -070034#ifndef __unused
35#define __unused __attribute__((__unused__))
36#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080037
38// compile with refcounting debugging enabled
39#define DEBUG_REFS 0
Mathias Agopian6d4419d2013-03-18 20:31:18 -070040
41// whether ref-tracking is enabled by default, if not, trackMe(true, false)
42// needs to be called explicitly
43#define DEBUG_REFS_ENABLED_BY_DEFAULT 0
44
45// whether callstack are collected (significantly slows things down)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080046#define DEBUG_REFS_CALLSTACK_ENABLED 1
47
Mathias Agopian6d4419d2013-03-18 20:31:18 -070048// folder where stack traces are saved when DEBUG_REFS is enabled
49// this folder needs to exist and be writable
50#define DEBUG_REFS_CALLSTACK_PATH "/data/debug"
51
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080052// log all reference counting operations
53#define PRINT_REFS 0
54
55// ---------------------------------------------------------------------------
56
57namespace android {
58
Hans Boehm9ba71922016-07-21 18:56:55 -070059// Observations, invariants, etc:
Hans Boehme263e6c2016-05-11 18:15:12 -070060
Hans Boehm9ba71922016-07-21 18:56:55 -070061// By default, obects are destroyed when the last strong reference disappears
62// or, if the object never had a strong reference, when the last weak reference
63// disappears.
64//
Hans Boehme263e6c2016-05-11 18:15:12 -070065// OBJECT_LIFETIME_WEAK changes this behavior to retain the object
66// unconditionally until the last reference of either kind disappears. The
67// client ensures that the extendObjectLifetime call happens before the dec
68// call that would otherwise have deallocated the object, or before an
69// attemptIncStrong call that might rely on it. We do not worry about
70// concurrent changes to the object lifetime.
Hans Boehm9ba71922016-07-21 18:56:55 -070071//
72// AttemptIncStrong will succeed if the object has a strong reference, or if it
73// has a weak reference and has never had a strong reference.
74// AttemptIncWeak really does succeed only if there is already a WEAK
75// reference, and thus may fail when attemptIncStrong would succeed.
76//
Hans Boehme263e6c2016-05-11 18:15:12 -070077// mStrong is the strong reference count. mWeak is the weak reference count.
78// Between calls, and ignoring memory ordering effects, mWeak includes strong
79// references, and is thus >= mStrong.
80//
Hans Boehm9ba71922016-07-21 18:56:55 -070081// A weakref_impl holds all the information, including both reference counts,
82// required to perform wp<> operations. Thus these can continue to be performed
83// after the RefBase object has been destroyed.
84//
Hans Boehme263e6c2016-05-11 18:15:12 -070085// A weakref_impl is allocated as the value of mRefs in a RefBase object on
86// construction.
Hans Boehm23c857e2016-08-02 18:39:30 -070087// In the OBJECT_LIFETIME_STRONG case, it is normally deallocated in decWeak,
88// and hence lives as long as the last weak reference. (It can also be
89// deallocated in the RefBase destructor iff the strong reference count was
90// never incremented and the weak count is zero, e.g. if the RefBase object is
91// explicitly destroyed without decrementing the strong count. This should be
92// avoided.) In this case, the RefBase destructor should be invoked from
93// decStrong.
94// In the OBJECT_LIFETIME_WEAK case, the weakref_impl is always deallocated in
95// the RefBase destructor, which is always invoked by decWeak. DecStrong
96// explicitly avoids the deletion in this case.
Hans Boehme263e6c2016-05-11 18:15:12 -070097//
98// Memory ordering:
99// The client must ensure that every inc() call, together with all other
100// accesses to the object, happens before the corresponding dec() call.
101//
102// We try to keep memory ordering constraints on atomics as weak as possible,
103// since memory fences or ordered memory accesses are likely to be a major
104// performance cost for this code. All accesses to mStrong, mWeak, and mFlags
105// explicitly relax memory ordering in some way.
106//
107// The only operations that are not memory_order_relaxed are reference count
108// decrements. All reference count decrements are release operations. In
109// addition, the final decrement leading the deallocation is followed by an
110// acquire fence, which we can view informally as also turning it into an
111// acquire operation. (See 29.8p4 [atomics.fences] for details. We could
112// alternatively use acq_rel operations for all decrements. This is probably
113// slower on most current (2016) hardware, especially on ARMv7, but that may
114// not be true indefinitely.)
115//
116// This convention ensures that the second-to-last decrement synchronizes with
117// (in the language of 1.10 in the C++ standard) the final decrement of a
118// reference count. Since reference counts are only updated using atomic
119// read-modify-write operations, this also extends to any earlier decrements.
120// (See "release sequence" in 1.10.)
121//
122// Since all operations on an object happen before the corresponding reference
123// count decrement, and all reference count decrements happen before the final
124// one, we are guaranteed that all other object accesses happen before the
125// object is destroyed.
126
127
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800128#define INITIAL_STRONG_VALUE (1<<28)
129
Hans Boehm23c857e2016-08-02 18:39:30 -0700130#define MAX_COUNT 0xfffff
131
132// Test whether the argument is a clearly invalid strong reference count.
133// Used only for error checking on the value before an atomic decrement.
134// Intended to be very cheap.
135// Note that we cannot just check for excess decrements by comparing to zero
136// since the object would be deallocated before that.
137#define BAD_STRONG(c) \
138 ((c) == 0 || ((c) & (~(MAX_COUNT | INITIAL_STRONG_VALUE))) != 0)
139
140// Same for weak counts.
141#define BAD_WEAK(c) ((c) == 0 || ((c) & (~MAX_COUNT)) != 0)
142
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800143// ---------------------------------------------------------------------------
144
145class RefBase::weakref_impl : public RefBase::weakref_type
146{
147public:
Hans Boehme263e6c2016-05-11 18:15:12 -0700148 std::atomic<int32_t> mStrong;
149 std::atomic<int32_t> mWeak;
150 RefBase* const mBase;
151 std::atomic<int32_t> mFlags;
Mathias Agopian9c8fa9e2011-06-15 20:42:47 -0700152
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800153#if !DEBUG_REFS
154
Chih-Hung Hsieh1c563d92016-04-29 15:44:04 -0700155 explicit weakref_impl(RefBase* base)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800156 : mStrong(INITIAL_STRONG_VALUE)
157 , mWeak(0)
158 , mBase(base)
159 , mFlags(0)
160 {
161 }
162
163 void addStrongRef(const void* /*id*/) { }
164 void removeStrongRef(const void* /*id*/) { }
Mathias Agopianad099652011-08-10 21:07:02 -0700165 void renameStrongRefId(const void* /*old_id*/, const void* /*new_id*/) { }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800166 void addWeakRef(const void* /*id*/) { }
167 void removeWeakRef(const void* /*id*/) { }
Mathias Agopianad099652011-08-10 21:07:02 -0700168 void renameWeakRefId(const void* /*old_id*/, const void* /*new_id*/) { }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800169 void printRefs() const { }
170 void trackMe(bool, bool) { }
171
172#else
173
174 weakref_impl(RefBase* base)
175 : mStrong(INITIAL_STRONG_VALUE)
176 , mWeak(0)
177 , mBase(base)
178 , mFlags(0)
179 , mStrongRefs(NULL)
180 , mWeakRefs(NULL)
181 , mTrackEnabled(!!DEBUG_REFS_ENABLED_BY_DEFAULT)
182 , mRetain(false)
183 {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800184 }
185
186 ~weakref_impl()
187 {
Mathias Agopianad099652011-08-10 21:07:02 -0700188 bool dumpStack = false;
189 if (!mRetain && mStrongRefs != NULL) {
190 dumpStack = true;
Steve Block1b781ab2012-01-06 19:20:56 +0000191 ALOGE("Strong references remain:");
Mathias Agopianad099652011-08-10 21:07:02 -0700192 ref_entry* refs = mStrongRefs;
193 while (refs) {
194 char inc = refs->ref >= 0 ? '+' : '-';
Steve Blockeb095332011-12-20 16:23:08 +0000195 ALOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
Mathias Agopianad099652011-08-10 21:07:02 -0700196#if DEBUG_REFS_CALLSTACK_ENABLED
Ian McKellar55e0f1c2014-03-31 15:59:31 -0700197 refs->stack.log(LOG_TAG);
Mathias Agopianad099652011-08-10 21:07:02 -0700198#endif
199 refs = refs->next;
200 }
201 }
202
203 if (!mRetain && mWeakRefs != NULL) {
204 dumpStack = true;
Steve Block1b781ab2012-01-06 19:20:56 +0000205 ALOGE("Weak references remain!");
Mathias Agopianad099652011-08-10 21:07:02 -0700206 ref_entry* refs = mWeakRefs;
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);
Mathias Agopianad099652011-08-10 21:07:02 -0700210#if DEBUG_REFS_CALLSTACK_ENABLED
Ian McKellar55e0f1c2014-03-31 15:59:31 -0700211 refs->stack.log(LOG_TAG);
Mathias Agopianad099652011-08-10 21:07:02 -0700212#endif
213 refs = refs->next;
214 }
215 }
216 if (dumpStack) {
Steve Block1b781ab2012-01-06 19:20:56 +0000217 ALOGE("above errors at:");
Mathias Agopiand34a8ca2013-03-21 17:12:40 -0700218 CallStack stack(LOG_TAG);
Mathias Agopianad099652011-08-10 21:07:02 -0700219 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800220 }
221
Mathias Agopianad099652011-08-10 21:07:02 -0700222 void addStrongRef(const void* id) {
Steve Blockeb095332011-12-20 16:23:08 +0000223 //ALOGD_IF(mTrackEnabled,
Mathias Agopianad099652011-08-10 21:07:02 -0700224 // "addStrongRef: RefBase=%p, id=%p", mBase, id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700225 addRef(&mStrongRefs, id, mStrong.load(std::memory_order_relaxed));
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800226 }
227
Mathias Agopianad099652011-08-10 21:07:02 -0700228 void removeStrongRef(const void* id) {
Steve Blockeb095332011-12-20 16:23:08 +0000229 //ALOGD_IF(mTrackEnabled,
Mathias Agopianad099652011-08-10 21:07:02 -0700230 // "removeStrongRef: RefBase=%p, id=%p", mBase, id);
231 if (!mRetain) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800232 removeRef(&mStrongRefs, id);
Mathias Agopianad099652011-08-10 21:07:02 -0700233 } else {
Hans Boehme263e6c2016-05-11 18:15:12 -0700234 addRef(&mStrongRefs, id, -mStrong.load(std::memory_order_relaxed));
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 renameStrongRefId(const void* old_id, const void* new_id) {
Steve Blockeb095332011-12-20 16:23:08 +0000239 //ALOGD_IF(mTrackEnabled,
Mathias Agopianad099652011-08-10 21:07:02 -0700240 // "renameStrongRefId: RefBase=%p, oid=%p, nid=%p",
241 // mBase, old_id, new_id);
242 renameRefsId(mStrongRefs, old_id, new_id);
243 }
244
245 void addWeakRef(const void* id) {
Hans Boehme263e6c2016-05-11 18:15:12 -0700246 addRef(&mWeakRefs, id, mWeak.load(std::memory_order_relaxed));
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800247 }
248
Mathias Agopianad099652011-08-10 21:07:02 -0700249 void removeWeakRef(const void* id) {
250 if (!mRetain) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800251 removeRef(&mWeakRefs, id);
Mathias Agopianad099652011-08-10 21:07:02 -0700252 } else {
Hans Boehme263e6c2016-05-11 18:15:12 -0700253 addRef(&mWeakRefs, id, -mWeak.load(std::memory_order_relaxed));
Mathias Agopianad099652011-08-10 21:07:02 -0700254 }
255 }
256
257 void renameWeakRefId(const void* old_id, const void* new_id) {
258 renameRefsId(mWeakRefs, old_id, new_id);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800259 }
260
261 void trackMe(bool track, bool retain)
262 {
263 mTrackEnabled = track;
264 mRetain = retain;
265 }
266
267 void printRefs() const
268 {
269 String8 text;
270
271 {
Mathias Agopianad099652011-08-10 21:07:02 -0700272 Mutex::Autolock _l(mMutex);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800273 char buf[128];
George Burgess IVe7aa2b22016-03-02 14:02:55 -0800274 snprintf(buf, sizeof(buf),
275 "Strong references on RefBase %p (weakref_type %p):\n",
276 mBase, this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800277 text.append(buf);
278 printRefsLocked(&text, mStrongRefs);
George Burgess IVe7aa2b22016-03-02 14:02:55 -0800279 snprintf(buf, sizeof(buf),
280 "Weak references on RefBase %p (weakref_type %p):\n",
281 mBase, this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800282 text.append(buf);
283 printRefsLocked(&text, mWeakRefs);
284 }
285
286 {
287 char name[100];
George Burgess IVe7aa2b22016-03-02 14:02:55 -0800288 snprintf(name, sizeof(name), DEBUG_REFS_CALLSTACK_PATH "/%p.stack",
289 this);
Mathias Agopian769828d2013-03-06 17:51:15 -0800290 int rc = open(name, O_RDWR | O_CREAT | O_APPEND, 644);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800291 if (rc >= 0) {
292 write(rc, text.string(), text.length());
293 close(rc);
Steve Blockeb095332011-12-20 16:23:08 +0000294 ALOGD("STACK TRACE for %p saved in %s", this, name);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800295 }
Steve Block1b781ab2012-01-06 19:20:56 +0000296 else ALOGE("FAILED TO PRINT STACK TRACE for %p in %s: %s", this,
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800297 name, strerror(errno));
298 }
299 }
300
301private:
302 struct ref_entry
303 {
304 ref_entry* next;
305 const void* id;
306#if DEBUG_REFS_CALLSTACK_ENABLED
307 CallStack stack;
308#endif
309 int32_t ref;
310 };
311
312 void addRef(ref_entry** refs, const void* id, int32_t mRef)
313 {
314 if (mTrackEnabled) {
315 AutoMutex _l(mMutex);
Mathias Agopianad099652011-08-10 21:07:02 -0700316
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800317 ref_entry* ref = new ref_entry;
318 // Reference count at the time of the snapshot, but before the
319 // update. Positive value means we increment, negative--we
320 // decrement the reference count.
321 ref->ref = mRef;
322 ref->id = id;
323#if DEBUG_REFS_CALLSTACK_ENABLED
324 ref->stack.update(2);
325#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800326 ref->next = *refs;
327 *refs = ref;
328 }
329 }
330
331 void removeRef(ref_entry** refs, const void* id)
332 {
333 if (mTrackEnabled) {
334 AutoMutex _l(mMutex);
335
Mathias Agopianad099652011-08-10 21:07:02 -0700336 ref_entry* const head = *refs;
337 ref_entry* ref = head;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800338 while (ref != NULL) {
339 if (ref->id == id) {
340 *refs = ref->next;
341 delete ref;
342 return;
343 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800344 refs = &ref->next;
345 ref = *refs;
346 }
Mathias Agopianad099652011-08-10 21:07:02 -0700347
Steve Block1b781ab2012-01-06 19:20:56 +0000348 ALOGE("RefBase: removing id %p on RefBase %p"
Mathias Agopianad099652011-08-10 21:07:02 -0700349 "(weakref_type %p) that doesn't exist!",
350 id, mBase, this);
351
352 ref = head;
353 while (ref) {
354 char inc = ref->ref >= 0 ? '+' : '-';
Steve Blockeb095332011-12-20 16:23:08 +0000355 ALOGD("\t%c ID %p (ref %d):", inc, ref->id, ref->ref);
Mathias Agopianad099652011-08-10 21:07:02 -0700356 ref = ref->next;
357 }
358
Mathias Agopiand34a8ca2013-03-21 17:12:40 -0700359 CallStack stack(LOG_TAG);
Mathias Agopianad099652011-08-10 21:07:02 -0700360 }
361 }
362
363 void renameRefsId(ref_entry* r, const void* old_id, const void* new_id)
364 {
365 if (mTrackEnabled) {
366 AutoMutex _l(mMutex);
367 ref_entry* ref = r;
368 while (ref != NULL) {
369 if (ref->id == old_id) {
370 ref->id = new_id;
371 }
372 ref = ref->next;
373 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800374 }
375 }
376
377 void printRefsLocked(String8* out, const ref_entry* refs) const
378 {
379 char buf[128];
380 while (refs) {
381 char inc = refs->ref >= 0 ? '+' : '-';
George Burgess IVe7aa2b22016-03-02 14:02:55 -0800382 snprintf(buf, sizeof(buf), "\t%c ID %p (ref %d):\n",
383 inc, refs->id, refs->ref);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800384 out->append(buf);
385#if DEBUG_REFS_CALLSTACK_ENABLED
386 out->append(refs->stack.toString("\t\t"));
387#else
388 out->append("\t\t(call stacks disabled)");
389#endif
390 refs = refs->next;
391 }
392 }
393
Mathias Agopianad099652011-08-10 21:07:02 -0700394 mutable Mutex mMutex;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800395 ref_entry* mStrongRefs;
396 ref_entry* mWeakRefs;
397
398 bool mTrackEnabled;
399 // Collect stack traces on addref and removeref, instead of deleting the stack references
400 // on removeref that match the address ones.
401 bool mRetain;
402
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800403#endif
404};
405
406// ---------------------------------------------------------------------------
407
408void RefBase::incStrong(const void* id) const
409{
410 weakref_impl* const refs = mRefs;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800411 refs->incWeak(id);
412
413 refs->addStrongRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700414 const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000415 ALOG_ASSERT(c > 0, "incStrong() called on %p after last strong ref", refs);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800416#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000417 ALOGD("incStrong of %p from %p: cnt=%d\n", this, id, c);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800418#endif
419 if (c != INITIAL_STRONG_VALUE) {
420 return;
421 }
422
Hans Boehme263e6c2016-05-11 18:15:12 -0700423 int32_t old = refs->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
424 std::memory_order_relaxed);
425 // 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.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800455 refs->decWeak(id);
456}
457
458void RefBase::forceIncStrong(const void* id) const
459{
Hans Boehme263e6c2016-05-11 18:15:12 -0700460 // Allows initial mStrong of 0 in addition to INITIAL_STRONG_VALUE.
461 // TODO: Better document assumptions.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800462 weakref_impl* const refs = mRefs;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800463 refs->incWeak(id);
464
465 refs->addStrongRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700466 const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000467 ALOG_ASSERT(c >= 0, "forceIncStrong called on %p after ref count underflow",
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800468 refs);
469#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000470 ALOGD("forceIncStrong of %p from %p: cnt=%d\n", this, id, c);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800471#endif
472
473 switch (c) {
474 case INITIAL_STRONG_VALUE:
Hans Boehme263e6c2016-05-11 18:15:12 -0700475 refs->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
476 std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800477 // fall through...
478 case 0:
Mathias Agopianad099652011-08-10 21:07:02 -0700479 refs->mBase->onFirstRef();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800480 }
481}
482
483int32_t RefBase::getStrongCount() const
484{
Hans Boehme263e6c2016-05-11 18:15:12 -0700485 // Debugging only; No memory ordering guarantees.
486 return mRefs->mStrong.load(std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800487}
488
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800489RefBase* RefBase::weakref_type::refBase() const
490{
491 return static_cast<const weakref_impl*>(this)->mBase;
492}
493
494void RefBase::weakref_type::incWeak(const void* id)
495{
496 weakref_impl* const impl = static_cast<weakref_impl*>(this);
497 impl->addWeakRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700498 const int32_t c __unused = impl->mWeak.fetch_add(1,
499 std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000500 ALOG_ASSERT(c >= 0, "incWeak called on %p after last weak ref", this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800501}
502
Mathias Agopianad099652011-08-10 21:07:02 -0700503
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800504void RefBase::weakref_type::decWeak(const void* id)
505{
506 weakref_impl* const impl = static_cast<weakref_impl*>(this);
507 impl->removeWeakRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700508 const int32_t c = impl->mWeak.fetch_sub(1, std::memory_order_release);
Hans Boehm23c857e2016-08-02 18:39:30 -0700509 LOG_ALWAYS_FATAL_IF(BAD_WEAK(c), "decWeak called on %p too many times",
510 this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800511 if (c != 1) return;
Hans Boehme263e6c2016-05-11 18:15:12 -0700512 atomic_thread_fence(std::memory_order_acquire);
Mathias Agopianad099652011-08-10 21:07:02 -0700513
Hans Boehme263e6c2016-05-11 18:15:12 -0700514 int32_t flags = impl->mFlags.load(std::memory_order_relaxed);
515 if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
Mathias Agopianad099652011-08-10 21:07:02 -0700516 // This is the regular lifetime case. The object is destroyed
517 // when the last strong reference goes away. Since weakref_impl
Hans Boehm23c857e2016-08-02 18:39:30 -0700518 // outlives the object, it is not destroyed in the dtor, and
Mathias Agopianad099652011-08-10 21:07:02 -0700519 // we'll have to do it here.
Hans Boehme263e6c2016-05-11 18:15:12 -0700520 if (impl->mStrong.load(std::memory_order_relaxed)
521 == INITIAL_STRONG_VALUE) {
Hans Boehm23c857e2016-08-02 18:39:30 -0700522 // Decrementing a weak count to zero when object never had a strong
523 // reference. We assume it acquired a weak reference early, e.g.
524 // in the constructor, and will eventually be properly destroyed,
525 // usually via incrementing and decrementing the strong count.
526 // Thus we no longer do anything here. We log this case, since it
527 // seems to be extremely rare, and should not normally occur. We
528 // used to deallocate mBase here, so this may now indicate a leak.
529 ALOGW("RefBase: Object at %p lost last weak reference "
530 "before it had a strong reference", impl->mBase);
Mathias Agopianad099652011-08-10 21:07:02 -0700531 } else {
Steve Blockb37fbe92011-10-20 11:56:00 +0100532 // ALOGV("Freeing refs %p of old RefBase %p\n", this, impl->mBase);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800533 delete impl;
534 }
535 } else {
Hans Boehme263e6c2016-05-11 18:15:12 -0700536 // This is the OBJECT_LIFETIME_WEAK case. The last weak-reference
537 // is gone, we can destroy the object.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800538 impl->mBase->onLastWeakRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700539 delete impl->mBase;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800540 }
541}
542
543bool RefBase::weakref_type::attemptIncStrong(const void* id)
544{
545 incWeak(id);
546
547 weakref_impl* const impl = static_cast<weakref_impl*>(this);
Hans Boehme263e6c2016-05-11 18:15:12 -0700548 int32_t curCount = impl->mStrong.load(std::memory_order_relaxed);
Dianne Hackborna729ab12013-03-14 15:26:30 -0700549
550 ALOG_ASSERT(curCount >= 0,
551 "attemptIncStrong called on %p after underflow", this);
552
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800553 while (curCount > 0 && curCount != INITIAL_STRONG_VALUE) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700554 // we're in the easy/common case of promoting a weak-reference
555 // from an existing strong reference.
Hans Boehme263e6c2016-05-11 18:15:12 -0700556 if (impl->mStrong.compare_exchange_weak(curCount, curCount+1,
557 std::memory_order_relaxed)) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800558 break;
559 }
Dianne Hackborna729ab12013-03-14 15:26:30 -0700560 // the strong count has changed on us, we need to re-assert our
Hans Boehme263e6c2016-05-11 18:15:12 -0700561 // situation. curCount was updated by compare_exchange_weak.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800562 }
563
564 if (curCount <= 0 || curCount == INITIAL_STRONG_VALUE) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700565 // we're now in the harder case of either:
566 // - there never was a strong reference on us
567 // - or, all strong references have been released
Hans Boehme263e6c2016-05-11 18:15:12 -0700568 int32_t flags = impl->mFlags.load(std::memory_order_relaxed);
569 if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700570 // this object has a "normal" life-time, i.e.: it gets destroyed
571 // when the last strong reference goes away
572 if (curCount <= 0) {
573 // the last strong-reference got released, the object cannot
574 // be revived.
575 decWeak(id);
576 return false;
577 }
578
579 // here, curCount == INITIAL_STRONG_VALUE, which means
580 // there never was a strong-reference, so we can try to
581 // promote this object; we need to do that atomically.
582 while (curCount > 0) {
Hans Boehme263e6c2016-05-11 18:15:12 -0700583 if (impl->mStrong.compare_exchange_weak(curCount, curCount+1,
584 std::memory_order_relaxed)) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700585 break;
586 }
587 // the strong count has changed on us, we need to re-assert our
588 // situation (e.g.: another thread has inc/decStrong'ed us)
Hans Boehme263e6c2016-05-11 18:15:12 -0700589 // curCount has been updated.
Dianne Hackborna729ab12013-03-14 15:26:30 -0700590 }
591
592 if (curCount <= 0) {
593 // promote() failed, some other thread destroyed us in the
594 // meantime (i.e.: strong count reached zero).
595 decWeak(id);
596 return false;
597 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800598 } else {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700599 // this object has an "extended" life-time, i.e.: it can be
600 // revived from a weak-reference only.
601 // Ask the object's implementation if it agrees to be revived
602 if (!impl->mBase->onIncStrongAttempted(FIRST_INC_STRONG, id)) {
603 // it didn't so give-up.
604 decWeak(id);
605 return false;
606 }
607 // grab a strong-reference, which is always safe due to the
608 // extended life-time.
Hans Boehme263e6c2016-05-11 18:15:12 -0700609 curCount = impl->mStrong.fetch_add(1, std::memory_order_relaxed);
Hans Boehm7f27cbc2016-07-29 14:39:10 -0700610 // If the strong reference count has already been incremented by
611 // someone else, the implementor of onIncStrongAttempted() is holding
612 // an unneeded reference. So call onLastStrongRef() here to remove it.
613 // (No, this is not pretty.) Note that we MUST NOT do this if we
614 // are in fact acquiring the first reference.
615 if (curCount != 0 && curCount != INITIAL_STRONG_VALUE) {
616 impl->mBase->onLastStrongRef(id);
617 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800618 }
619 }
620
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800621 impl->addStrongRef(id);
622
623#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000624 ALOGD("attemptIncStrong of %p from %p: cnt=%d\n", this, id, curCount);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800625#endif
626
Hans Boehm7f27cbc2016-07-29 14:39:10 -0700627 // curCount is the value of mStrong before we incremented it.
Hans Boehme263e6c2016-05-11 18:15:12 -0700628 // Now we need to fix-up the count if it was INITIAL_STRONG_VALUE.
629 // This must be done safely, i.e.: handle the case where several threads
Dianne Hackborna729ab12013-03-14 15:26:30 -0700630 // were here in attemptIncStrong().
Hans Boehme263e6c2016-05-11 18:15:12 -0700631 // curCount > INITIAL_STRONG_VALUE is OK, and can happen if we're doing
632 // this in the middle of another incStrong. The subtraction is handled
633 // by the thread that started with INITIAL_STRONG_VALUE.
634 if (curCount == INITIAL_STRONG_VALUE) {
635 impl->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
636 std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800637 }
Dianne Hackborna729ab12013-03-14 15:26:30 -0700638
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800639 return true;
640}
641
642bool RefBase::weakref_type::attemptIncWeak(const void* id)
643{
644 weakref_impl* const impl = static_cast<weakref_impl*>(this);
Mathias Agopianad099652011-08-10 21:07:02 -0700645
Hans Boehme263e6c2016-05-11 18:15:12 -0700646 int32_t curCount = impl->mWeak.load(std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000647 ALOG_ASSERT(curCount >= 0, "attemptIncWeak called on %p after underflow",
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800648 this);
649 while (curCount > 0) {
Hans Boehme263e6c2016-05-11 18:15:12 -0700650 if (impl->mWeak.compare_exchange_weak(curCount, curCount+1,
651 std::memory_order_relaxed)) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800652 break;
653 }
Hans Boehme263e6c2016-05-11 18:15:12 -0700654 // curCount has been updated.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800655 }
656
657 if (curCount > 0) {
658 impl->addWeakRef(id);
659 }
660
661 return curCount > 0;
662}
663
664int32_t RefBase::weakref_type::getWeakCount() const
665{
Hans Boehme263e6c2016-05-11 18:15:12 -0700666 // Debug only!
667 return static_cast<const weakref_impl*>(this)->mWeak
668 .load(std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800669}
670
671void RefBase::weakref_type::printRefs() const
672{
673 static_cast<const weakref_impl*>(this)->printRefs();
674}
675
676void RefBase::weakref_type::trackMe(bool enable, bool retain)
677{
Mathias Agopianad099652011-08-10 21:07:02 -0700678 static_cast<weakref_impl*>(this)->trackMe(enable, retain);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800679}
680
681RefBase::weakref_type* RefBase::createWeak(const void* id) const
682{
683 mRefs->incWeak(id);
684 return mRefs;
685}
686
687RefBase::weakref_type* RefBase::getWeakRefs() const
688{
689 return mRefs;
690}
691
692RefBase::RefBase()
693 : mRefs(new weakref_impl(this))
694{
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800695}
696
697RefBase::~RefBase()
698{
Hans Boehm23c857e2016-08-02 18:39:30 -0700699 int32_t flags = mRefs->mFlags.load(std::memory_order_relaxed);
700 // Life-time of this object is extended to WEAK, in
701 // which case weakref_impl doesn't out-live the object and we
702 // can free it now.
703 if ((flags & OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_WEAK) {
704 // It's possible that the weak count is not 0 if the object
705 // re-acquired a weak reference in its destructor
706 if (mRefs->mWeak.load(std::memory_order_relaxed) == 0) {
707 delete mRefs;
708 }
709 } else if (mRefs->mStrong.load(std::memory_order_relaxed)
Hans Boehme263e6c2016-05-11 18:15:12 -0700710 == INITIAL_STRONG_VALUE) {
Hans Boehm9ba71922016-07-21 18:56:55 -0700711 // We never acquired a strong reference on this object.
Hans Boehm23c857e2016-08-02 18:39:30 -0700712 LOG_ALWAYS_FATAL_IF(mRefs->mWeak.load() != 0,
713 "RefBase: Explicit destruction with non-zero weak "
714 "reference count");
715 // TODO: Always report if we get here. Currently MediaMetadataRetriever
716 // C++ objects are inconsistently managed and sometimes get here.
717 // There may be other cases, but we believe they should all be fixed.
Mathias Agopian9c8fa9e2011-06-15 20:42:47 -0700718 delete mRefs;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800719 }
Hans Boehm23c857e2016-08-02 18:39:30 -0700720 // For debugging purposes, clear mRefs. Ineffective against outstanding wp's.
Mathias Agopianad099652011-08-10 21:07:02 -0700721 const_cast<weakref_impl*&>(mRefs) = NULL;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800722}
723
724void RefBase::extendObjectLifetime(int32_t mode)
725{
Hans Boehme263e6c2016-05-11 18:15:12 -0700726 // Must be happens-before ordered with respect to construction or any
727 // operation that could destroy the object.
728 mRefs->mFlags.fetch_or(mode, std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800729}
730
731void RefBase::onFirstRef()
732{
733}
734
735void RefBase::onLastStrongRef(const void* /*id*/)
736{
737}
738
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700739bool RefBase::onIncStrongAttempted(uint32_t flags, const void* /*id*/)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800740{
741 return (flags&FIRST_INC_STRONG) ? true : false;
742}
743
744void RefBase::onLastWeakRef(const void* /*id*/)
745{
746}
Mathias Agopianad099652011-08-10 21:07:02 -0700747
748// ---------------------------------------------------------------------------
749
Mathias Agopianad099652011-08-10 21:07:02 -0700750#if DEBUG_REFS
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700751void RefBase::renameRefs(size_t n, const ReferenceRenamer& renamer) {
Mathias Agopianad099652011-08-10 21:07:02 -0700752 for (size_t i=0 ; i<n ; i++) {
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700753 renamer(i);
Mathias Agopianad099652011-08-10 21:07:02 -0700754 }
Mathias Agopianad099652011-08-10 21:07:02 -0700755}
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700756#else
757void RefBase::renameRefs(size_t /*n*/, const ReferenceRenamer& /*renamer*/) { }
758#endif
Mathias Agopianad099652011-08-10 21:07:02 -0700759
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700760void RefBase::renameRefId(weakref_type* ref,
761 const void* old_id, const void* new_id) {
762 weakref_impl* const impl = static_cast<weakref_impl*>(ref);
763 impl->renameStrongRefId(old_id, new_id);
764 impl->renameWeakRefId(old_id, new_id);
765}
766
767void RefBase::renameRefId(RefBase* ref,
768 const void* old_id, const void* new_id) {
769 ref->mRefs->renameStrongRefId(old_id, new_id);
770 ref->mRefs->renameWeakRefId(old_id, new_id);
771}
772
Colin Cross17b5b822016-09-15 18:15:37 -0700773VirtualLightRefBase::~VirtualLightRefBase() {}
774
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800775}; // namespace android