blob: 4252ba6b2dbc87787e66e7939f4274200de89c74 [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>
Mark Salyzyn5bed8032014-04-30 11:10:46 -070025#include <unistd.h>
26
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080027#include <utils/RefBase.h>
28
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080029#include <utils/CallStack.h>
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080030#include <utils/Log.h>
31#include <utils/threads.h>
32
Mark Salyzyn5bed8032014-04-30 11:10:46 -070033#ifndef __unused
34#define __unused __attribute__((__unused__))
35#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080036
37// compile with refcounting debugging enabled
38#define DEBUG_REFS 0
Mathias Agopian6d4419d2013-03-18 20:31:18 -070039
40// whether ref-tracking is enabled by default, if not, trackMe(true, false)
41// needs to be called explicitly
42#define DEBUG_REFS_ENABLED_BY_DEFAULT 0
43
44// whether callstack are collected (significantly slows things down)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080045#define DEBUG_REFS_CALLSTACK_ENABLED 1
46
Mathias Agopian6d4419d2013-03-18 20:31:18 -070047// folder where stack traces are saved when DEBUG_REFS is enabled
48// this folder needs to exist and be writable
49#define DEBUG_REFS_CALLSTACK_PATH "/data/debug"
50
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080051// log all reference counting operations
52#define PRINT_REFS 0
53
54// ---------------------------------------------------------------------------
55
56namespace android {
57
Hans Boehm9ba71922016-07-21 18:56:55 -070058// Observations, invariants, etc:
Hans Boehme263e6c2016-05-11 18:15:12 -070059
Hans Boehm9ba71922016-07-21 18:56:55 -070060// By default, obects are destroyed when the last strong reference disappears
61// or, if the object never had a strong reference, when the last weak reference
62// disappears.
63//
Hans Boehme263e6c2016-05-11 18:15:12 -070064// OBJECT_LIFETIME_WEAK changes this behavior to retain the object
65// unconditionally until the last reference of either kind disappears. The
66// client ensures that the extendObjectLifetime call happens before the dec
67// call that would otherwise have deallocated the object, or before an
68// attemptIncStrong call that might rely on it. We do not worry about
69// concurrent changes to the object lifetime.
Hans Boehm9ba71922016-07-21 18:56:55 -070070//
71// AttemptIncStrong will succeed if the object has a strong reference, or if it
72// has a weak reference and has never had a strong reference.
73// AttemptIncWeak really does succeed only if there is already a WEAK
74// reference, and thus may fail when attemptIncStrong would succeed.
75//
Hans Boehme263e6c2016-05-11 18:15:12 -070076// mStrong is the strong reference count. mWeak is the weak reference count.
77// Between calls, and ignoring memory ordering effects, mWeak includes strong
78// references, and is thus >= mStrong.
79//
Hans Boehm9ba71922016-07-21 18:56:55 -070080// A weakref_impl holds all the information, including both reference counts,
81// required to perform wp<> operations. Thus these can continue to be performed
82// after the RefBase object has been destroyed.
83//
Hans Boehme263e6c2016-05-11 18:15:12 -070084// A weakref_impl is allocated as the value of mRefs in a RefBase object on
85// construction.
Hans Boehm23c857e2016-08-02 18:39:30 -070086// In the OBJECT_LIFETIME_STRONG case, it is normally deallocated in decWeak,
87// and hence lives as long as the last weak reference. (It can also be
88// deallocated in the RefBase destructor iff the strong reference count was
89// never incremented and the weak count is zero, e.g. if the RefBase object is
90// explicitly destroyed without decrementing the strong count. This should be
91// avoided.) In this case, the RefBase destructor should be invoked from
92// decStrong.
93// In the OBJECT_LIFETIME_WEAK case, the weakref_impl is always deallocated in
94// the RefBase destructor, which is always invoked by decWeak. DecStrong
95// explicitly avoids the deletion in this case.
Hans Boehme263e6c2016-05-11 18:15:12 -070096//
97// Memory ordering:
98// The client must ensure that every inc() call, together with all other
99// accesses to the object, happens before the corresponding dec() call.
100//
101// We try to keep memory ordering constraints on atomics as weak as possible,
102// since memory fences or ordered memory accesses are likely to be a major
103// performance cost for this code. All accesses to mStrong, mWeak, and mFlags
104// explicitly relax memory ordering in some way.
105//
106// The only operations that are not memory_order_relaxed are reference count
107// decrements. All reference count decrements are release operations. In
108// addition, the final decrement leading the deallocation is followed by an
109// acquire fence, which we can view informally as also turning it into an
110// acquire operation. (See 29.8p4 [atomics.fences] for details. We could
111// alternatively use acq_rel operations for all decrements. This is probably
112// slower on most current (2016) hardware, especially on ARMv7, but that may
113// not be true indefinitely.)
114//
115// This convention ensures that the second-to-last decrement synchronizes with
116// (in the language of 1.10 in the C++ standard) the final decrement of a
117// reference count. Since reference counts are only updated using atomic
118// read-modify-write operations, this also extends to any earlier decrements.
119// (See "release sequence" in 1.10.)
120//
121// Since all operations on an object happen before the corresponding reference
122// count decrement, and all reference count decrements happen before the final
123// one, we are guaranteed that all other object accesses happen before the
124// object is destroyed.
125
126
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800127#define INITIAL_STRONG_VALUE (1<<28)
128
Hans Boehm23c857e2016-08-02 18:39:30 -0700129#define MAX_COUNT 0xfffff
130
131// Test whether the argument is a clearly invalid strong reference count.
132// Used only for error checking on the value before an atomic decrement.
133// Intended to be very cheap.
134// Note that we cannot just check for excess decrements by comparing to zero
135// since the object would be deallocated before that.
136#define BAD_STRONG(c) \
137 ((c) == 0 || ((c) & (~(MAX_COUNT | INITIAL_STRONG_VALUE))) != 0)
138
139// Same for weak counts.
140#define BAD_WEAK(c) ((c) == 0 || ((c) & (~MAX_COUNT)) != 0)
141
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800142// ---------------------------------------------------------------------------
143
144class RefBase::weakref_impl : public RefBase::weakref_type
145{
146public:
Hans Boehme263e6c2016-05-11 18:15:12 -0700147 std::atomic<int32_t> mStrong;
148 std::atomic<int32_t> mWeak;
149 RefBase* const mBase;
150 std::atomic<int32_t> mFlags;
Mathias Agopian9c8fa9e2011-06-15 20:42:47 -0700151
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800152#if !DEBUG_REFS
153
Chih-Hung Hsieh1c563d92016-04-29 15:44:04 -0700154 explicit weakref_impl(RefBase* base)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800155 : mStrong(INITIAL_STRONG_VALUE)
156 , mWeak(0)
157 , mBase(base)
158 , mFlags(0)
159 {
160 }
161
162 void addStrongRef(const void* /*id*/) { }
163 void removeStrongRef(const void* /*id*/) { }
Mathias Agopianad099652011-08-10 21:07:02 -0700164 void renameStrongRefId(const void* /*old_id*/, const void* /*new_id*/) { }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800165 void addWeakRef(const void* /*id*/) { }
166 void removeWeakRef(const void* /*id*/) { }
Mathias Agopianad099652011-08-10 21:07:02 -0700167 void renameWeakRefId(const void* /*old_id*/, const void* /*new_id*/) { }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800168 void printRefs() const { }
169 void trackMe(bool, bool) { }
170
171#else
172
173 weakref_impl(RefBase* base)
174 : mStrong(INITIAL_STRONG_VALUE)
175 , mWeak(0)
176 , mBase(base)
177 , mFlags(0)
178 , mStrongRefs(NULL)
179 , mWeakRefs(NULL)
180 , mTrackEnabled(!!DEBUG_REFS_ENABLED_BY_DEFAULT)
181 , mRetain(false)
182 {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800183 }
184
185 ~weakref_impl()
186 {
Mathias Agopianad099652011-08-10 21:07:02 -0700187 bool dumpStack = false;
188 if (!mRetain && mStrongRefs != NULL) {
189 dumpStack = true;
Steve Block1b781ab2012-01-06 19:20:56 +0000190 ALOGE("Strong references remain:");
Mathias Agopianad099652011-08-10 21:07:02 -0700191 ref_entry* refs = mStrongRefs;
192 while (refs) {
193 char inc = refs->ref >= 0 ? '+' : '-';
Steve Blockeb095332011-12-20 16:23:08 +0000194 ALOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
Mathias Agopianad099652011-08-10 21:07:02 -0700195#if DEBUG_REFS_CALLSTACK_ENABLED
Ian McKellar55e0f1c2014-03-31 15:59:31 -0700196 refs->stack.log(LOG_TAG);
Mathias Agopianad099652011-08-10 21:07:02 -0700197#endif
198 refs = refs->next;
199 }
200 }
201
202 if (!mRetain && mWeakRefs != NULL) {
203 dumpStack = true;
Steve Block1b781ab2012-01-06 19:20:56 +0000204 ALOGE("Weak references remain!");
Mathias Agopianad099652011-08-10 21:07:02 -0700205 ref_entry* refs = mWeakRefs;
206 while (refs) {
207 char inc = refs->ref >= 0 ? '+' : '-';
Steve Blockeb095332011-12-20 16:23:08 +0000208 ALOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
Mathias Agopianad099652011-08-10 21:07:02 -0700209#if DEBUG_REFS_CALLSTACK_ENABLED
Ian McKellar55e0f1c2014-03-31 15:59:31 -0700210 refs->stack.log(LOG_TAG);
Mathias Agopianad099652011-08-10 21:07:02 -0700211#endif
212 refs = refs->next;
213 }
214 }
215 if (dumpStack) {
Steve Block1b781ab2012-01-06 19:20:56 +0000216 ALOGE("above errors at:");
Mathias Agopiand34a8ca2013-03-21 17:12:40 -0700217 CallStack stack(LOG_TAG);
Mathias Agopianad099652011-08-10 21:07:02 -0700218 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800219 }
220
Mathias Agopianad099652011-08-10 21:07:02 -0700221 void addStrongRef(const void* id) {
Steve Blockeb095332011-12-20 16:23:08 +0000222 //ALOGD_IF(mTrackEnabled,
Mathias Agopianad099652011-08-10 21:07:02 -0700223 // "addStrongRef: RefBase=%p, id=%p", mBase, id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700224 addRef(&mStrongRefs, id, mStrong.load(std::memory_order_relaxed));
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800225 }
226
Mathias Agopianad099652011-08-10 21:07:02 -0700227 void removeStrongRef(const void* id) {
Steve Blockeb095332011-12-20 16:23:08 +0000228 //ALOGD_IF(mTrackEnabled,
Mathias Agopianad099652011-08-10 21:07:02 -0700229 // "removeStrongRef: RefBase=%p, id=%p", mBase, id);
230 if (!mRetain) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800231 removeRef(&mStrongRefs, id);
Mathias Agopianad099652011-08-10 21:07:02 -0700232 } else {
Hans Boehme263e6c2016-05-11 18:15:12 -0700233 addRef(&mStrongRefs, id, -mStrong.load(std::memory_order_relaxed));
Mathias Agopianad099652011-08-10 21:07:02 -0700234 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800235 }
236
Mathias Agopianad099652011-08-10 21:07:02 -0700237 void renameStrongRefId(const void* old_id, const void* new_id) {
Steve Blockeb095332011-12-20 16:23:08 +0000238 //ALOGD_IF(mTrackEnabled,
Mathias Agopianad099652011-08-10 21:07:02 -0700239 // "renameStrongRefId: RefBase=%p, oid=%p, nid=%p",
240 // mBase, old_id, new_id);
241 renameRefsId(mStrongRefs, old_id, new_id);
242 }
243
244 void addWeakRef(const void* id) {
Hans Boehme263e6c2016-05-11 18:15:12 -0700245 addRef(&mWeakRefs, id, mWeak.load(std::memory_order_relaxed));
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800246 }
247
Mathias Agopianad099652011-08-10 21:07:02 -0700248 void removeWeakRef(const void* id) {
249 if (!mRetain) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800250 removeRef(&mWeakRefs, id);
Mathias Agopianad099652011-08-10 21:07:02 -0700251 } else {
Hans Boehme263e6c2016-05-11 18:15:12 -0700252 addRef(&mWeakRefs, id, -mWeak.load(std::memory_order_relaxed));
Mathias Agopianad099652011-08-10 21:07:02 -0700253 }
254 }
255
256 void renameWeakRefId(const void* old_id, const void* new_id) {
257 renameRefsId(mWeakRefs, old_id, new_id);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800258 }
259
260 void trackMe(bool track, bool retain)
261 {
262 mTrackEnabled = track;
263 mRetain = retain;
264 }
265
266 void printRefs() const
267 {
268 String8 text;
269
270 {
Mathias Agopianad099652011-08-10 21:07:02 -0700271 Mutex::Autolock _l(mMutex);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800272 char buf[128];
George Burgess IVe7aa2b22016-03-02 14:02:55 -0800273 snprintf(buf, sizeof(buf),
274 "Strong references on RefBase %p (weakref_type %p):\n",
275 mBase, this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800276 text.append(buf);
277 printRefsLocked(&text, mStrongRefs);
George Burgess IVe7aa2b22016-03-02 14:02:55 -0800278 snprintf(buf, sizeof(buf),
279 "Weak references on RefBase %p (weakref_type %p):\n",
280 mBase, this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800281 text.append(buf);
282 printRefsLocked(&text, mWeakRefs);
283 }
284
285 {
286 char name[100];
George Burgess IVe7aa2b22016-03-02 14:02:55 -0800287 snprintf(name, sizeof(name), DEBUG_REFS_CALLSTACK_PATH "/%p.stack",
288 this);
Mathias Agopian769828d2013-03-06 17:51:15 -0800289 int rc = open(name, O_RDWR | O_CREAT | O_APPEND, 644);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800290 if (rc >= 0) {
291 write(rc, text.string(), text.length());
292 close(rc);
Steve Blockeb095332011-12-20 16:23:08 +0000293 ALOGD("STACK TRACE for %p saved in %s", this, name);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800294 }
Steve Block1b781ab2012-01-06 19:20:56 +0000295 else ALOGE("FAILED TO PRINT STACK TRACE for %p in %s: %s", this,
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800296 name, strerror(errno));
297 }
298 }
299
300private:
301 struct ref_entry
302 {
303 ref_entry* next;
304 const void* id;
305#if DEBUG_REFS_CALLSTACK_ENABLED
306 CallStack stack;
307#endif
308 int32_t ref;
309 };
310
311 void addRef(ref_entry** refs, const void* id, int32_t mRef)
312 {
313 if (mTrackEnabled) {
314 AutoMutex _l(mMutex);
Mathias Agopianad099652011-08-10 21:07:02 -0700315
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800316 ref_entry* ref = new ref_entry;
317 // Reference count at the time of the snapshot, but before the
318 // update. Positive value means we increment, negative--we
319 // decrement the reference count.
320 ref->ref = mRef;
321 ref->id = id;
322#if DEBUG_REFS_CALLSTACK_ENABLED
323 ref->stack.update(2);
324#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800325 ref->next = *refs;
326 *refs = ref;
327 }
328 }
329
330 void removeRef(ref_entry** refs, const void* id)
331 {
332 if (mTrackEnabled) {
333 AutoMutex _l(mMutex);
334
Mathias Agopianad099652011-08-10 21:07:02 -0700335 ref_entry* const head = *refs;
336 ref_entry* ref = head;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800337 while (ref != NULL) {
338 if (ref->id == id) {
339 *refs = ref->next;
340 delete ref;
341 return;
342 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800343 refs = &ref->next;
344 ref = *refs;
345 }
Mathias Agopianad099652011-08-10 21:07:02 -0700346
Steve Block1b781ab2012-01-06 19:20:56 +0000347 ALOGE("RefBase: removing id %p on RefBase %p"
Mathias Agopianad099652011-08-10 21:07:02 -0700348 "(weakref_type %p) that doesn't exist!",
349 id, mBase, this);
350
351 ref = head;
352 while (ref) {
353 char inc = ref->ref >= 0 ? '+' : '-';
Steve Blockeb095332011-12-20 16:23:08 +0000354 ALOGD("\t%c ID %p (ref %d):", inc, ref->id, ref->ref);
Mathias Agopianad099652011-08-10 21:07:02 -0700355 ref = ref->next;
356 }
357
Mathias Agopiand34a8ca2013-03-21 17:12:40 -0700358 CallStack stack(LOG_TAG);
Mathias Agopianad099652011-08-10 21:07:02 -0700359 }
360 }
361
362 void renameRefsId(ref_entry* r, const void* old_id, const void* new_id)
363 {
364 if (mTrackEnabled) {
365 AutoMutex _l(mMutex);
366 ref_entry* ref = r;
367 while (ref != NULL) {
368 if (ref->id == old_id) {
369 ref->id = new_id;
370 }
371 ref = ref->next;
372 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800373 }
374 }
375
376 void printRefsLocked(String8* out, const ref_entry* refs) const
377 {
378 char buf[128];
379 while (refs) {
380 char inc = refs->ref >= 0 ? '+' : '-';
George Burgess IVe7aa2b22016-03-02 14:02:55 -0800381 snprintf(buf, sizeof(buf), "\t%c ID %p (ref %d):\n",
382 inc, refs->id, refs->ref);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800383 out->append(buf);
384#if DEBUG_REFS_CALLSTACK_ENABLED
385 out->append(refs->stack.toString("\t\t"));
386#else
387 out->append("\t\t(call stacks disabled)");
388#endif
389 refs = refs->next;
390 }
391 }
392
Mathias Agopianad099652011-08-10 21:07:02 -0700393 mutable Mutex mMutex;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800394 ref_entry* mStrongRefs;
395 ref_entry* mWeakRefs;
396
397 bool mTrackEnabled;
398 // Collect stack traces on addref and removeref, instead of deleting the stack references
399 // on removeref that match the address ones.
400 bool mRetain;
401
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800402#endif
403};
404
405// ---------------------------------------------------------------------------
406
407void RefBase::incStrong(const void* id) const
408{
409 weakref_impl* const refs = mRefs;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800410 refs->incWeak(id);
411
412 refs->addStrongRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700413 const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000414 ALOG_ASSERT(c > 0, "incStrong() called on %p after last strong ref", refs);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800415#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000416 ALOGD("incStrong of %p from %p: cnt=%d\n", this, id, c);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800417#endif
418 if (c != INITIAL_STRONG_VALUE) {
419 return;
420 }
421
Hans Boehme263e6c2016-05-11 18:15:12 -0700422 int32_t old = refs->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
423 std::memory_order_relaxed);
424 // A decStrong() must still happen after us.
425 ALOG_ASSERT(old > INITIAL_STRONG_VALUE, "0x%x too small", old);
Mathias Agopianad099652011-08-10 21:07:02 -0700426 refs->mBase->onFirstRef();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800427}
428
429void RefBase::decStrong(const void* id) const
430{
431 weakref_impl* const refs = mRefs;
432 refs->removeStrongRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700433 const int32_t c = refs->mStrong.fetch_sub(1, std::memory_order_release);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800434#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000435 ALOGD("decStrong of %p from %p: cnt=%d\n", this, id, c);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800436#endif
Hans Boehm23c857e2016-08-02 18:39:30 -0700437 LOG_ALWAYS_FATAL_IF(BAD_STRONG(c), "decStrong() called on %p too many times",
438 refs);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800439 if (c == 1) {
Hans Boehme263e6c2016-05-11 18:15:12 -0700440 std::atomic_thread_fence(std::memory_order_acquire);
Mathias Agopianad099652011-08-10 21:07:02 -0700441 refs->mBase->onLastStrongRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700442 int32_t flags = refs->mFlags.load(std::memory_order_relaxed);
443 if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
Mathias Agopian9c8fa9e2011-06-15 20:42:47 -0700444 delete this;
Hans Boehm23c857e2016-08-02 18:39:30 -0700445 // The destructor does not delete refs in this case.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800446 }
447 }
Hans Boehme263e6c2016-05-11 18:15:12 -0700448 // Note that even with only strong reference operations, the thread
449 // deallocating this may not be the same as the thread deallocating refs.
450 // That's OK: all accesses to this happen before its deletion here,
451 // and all accesses to refs happen before its deletion in the final decWeak.
452 // The destructor can safely access mRefs because either it's deleting
453 // mRefs itself, or it's running entirely before the final mWeak decrement.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800454 refs->decWeak(id);
455}
456
457void RefBase::forceIncStrong(const void* id) const
458{
Hans Boehme263e6c2016-05-11 18:15:12 -0700459 // Allows initial mStrong of 0 in addition to INITIAL_STRONG_VALUE.
460 // TODO: Better document assumptions.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800461 weakref_impl* const refs = mRefs;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800462 refs->incWeak(id);
463
464 refs->addStrongRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700465 const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000466 ALOG_ASSERT(c >= 0, "forceIncStrong called on %p after ref count underflow",
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800467 refs);
468#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000469 ALOGD("forceIncStrong of %p from %p: cnt=%d\n", this, id, c);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800470#endif
471
472 switch (c) {
473 case INITIAL_STRONG_VALUE:
Hans Boehme263e6c2016-05-11 18:15:12 -0700474 refs->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
475 std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800476 // fall through...
477 case 0:
Mathias Agopianad099652011-08-10 21:07:02 -0700478 refs->mBase->onFirstRef();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800479 }
480}
481
482int32_t RefBase::getStrongCount() const
483{
Hans Boehme263e6c2016-05-11 18:15:12 -0700484 // Debugging only; No memory ordering guarantees.
485 return mRefs->mStrong.load(std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800486}
487
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800488RefBase* RefBase::weakref_type::refBase() const
489{
490 return static_cast<const weakref_impl*>(this)->mBase;
491}
492
493void RefBase::weakref_type::incWeak(const void* id)
494{
495 weakref_impl* const impl = static_cast<weakref_impl*>(this);
496 impl->addWeakRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700497 const int32_t c __unused = impl->mWeak.fetch_add(1,
498 std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000499 ALOG_ASSERT(c >= 0, "incWeak called on %p after last weak ref", this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800500}
501
Mathias Agopianad099652011-08-10 21:07:02 -0700502
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800503void RefBase::weakref_type::decWeak(const void* id)
504{
505 weakref_impl* const impl = static_cast<weakref_impl*>(this);
506 impl->removeWeakRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700507 const int32_t c = impl->mWeak.fetch_sub(1, std::memory_order_release);
Hans Boehm23c857e2016-08-02 18:39:30 -0700508 LOG_ALWAYS_FATAL_IF(BAD_WEAK(c), "decWeak called on %p too many times",
509 this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800510 if (c != 1) return;
Hans Boehme263e6c2016-05-11 18:15:12 -0700511 atomic_thread_fence(std::memory_order_acquire);
Mathias Agopianad099652011-08-10 21:07:02 -0700512
Hans Boehme263e6c2016-05-11 18:15:12 -0700513 int32_t flags = impl->mFlags.load(std::memory_order_relaxed);
514 if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
Mathias Agopianad099652011-08-10 21:07:02 -0700515 // This is the regular lifetime case. The object is destroyed
516 // when the last strong reference goes away. Since weakref_impl
Hans Boehm23c857e2016-08-02 18:39:30 -0700517 // outlives the object, it is not destroyed in the dtor, and
Mathias Agopianad099652011-08-10 21:07:02 -0700518 // we'll have to do it here.
Hans Boehme263e6c2016-05-11 18:15:12 -0700519 if (impl->mStrong.load(std::memory_order_relaxed)
520 == INITIAL_STRONG_VALUE) {
Hans Boehm23c857e2016-08-02 18:39:30 -0700521 // Decrementing a weak count to zero when object never had a strong
522 // reference. We assume it acquired a weak reference early, e.g.
523 // in the constructor, and will eventually be properly destroyed,
524 // usually via incrementing and decrementing the strong count.
525 // Thus we no longer do anything here. We log this case, since it
526 // seems to be extremely rare, and should not normally occur. We
527 // used to deallocate mBase here, so this may now indicate a leak.
528 ALOGW("RefBase: Object at %p lost last weak reference "
529 "before it had a strong reference", impl->mBase);
Mathias Agopianad099652011-08-10 21:07:02 -0700530 } else {
Steve Blockb37fbe92011-10-20 11:56:00 +0100531 // ALOGV("Freeing refs %p of old RefBase %p\n", this, impl->mBase);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800532 delete impl;
533 }
534 } else {
Hans Boehme263e6c2016-05-11 18:15:12 -0700535 // This is the OBJECT_LIFETIME_WEAK case. The last weak-reference
536 // is gone, we can destroy the object.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800537 impl->mBase->onLastWeakRef(id);
Hans Boehme263e6c2016-05-11 18:15:12 -0700538 delete impl->mBase;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800539 }
540}
541
542bool RefBase::weakref_type::attemptIncStrong(const void* id)
543{
544 incWeak(id);
545
546 weakref_impl* const impl = static_cast<weakref_impl*>(this);
Hans Boehme263e6c2016-05-11 18:15:12 -0700547 int32_t curCount = impl->mStrong.load(std::memory_order_relaxed);
Dianne Hackborna729ab12013-03-14 15:26:30 -0700548
549 ALOG_ASSERT(curCount >= 0,
550 "attemptIncStrong called on %p after underflow", this);
551
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800552 while (curCount > 0 && curCount != INITIAL_STRONG_VALUE) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700553 // we're in the easy/common case of promoting a weak-reference
554 // from an existing strong reference.
Hans Boehme263e6c2016-05-11 18:15:12 -0700555 if (impl->mStrong.compare_exchange_weak(curCount, curCount+1,
556 std::memory_order_relaxed)) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800557 break;
558 }
Dianne Hackborna729ab12013-03-14 15:26:30 -0700559 // the strong count has changed on us, we need to re-assert our
Hans Boehme263e6c2016-05-11 18:15:12 -0700560 // situation. curCount was updated by compare_exchange_weak.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800561 }
562
563 if (curCount <= 0 || curCount == INITIAL_STRONG_VALUE) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700564 // we're now in the harder case of either:
565 // - there never was a strong reference on us
566 // - or, all strong references have been released
Hans Boehme263e6c2016-05-11 18:15:12 -0700567 int32_t flags = impl->mFlags.load(std::memory_order_relaxed);
568 if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700569 // this object has a "normal" life-time, i.e.: it gets destroyed
570 // when the last strong reference goes away
571 if (curCount <= 0) {
572 // the last strong-reference got released, the object cannot
573 // be revived.
574 decWeak(id);
575 return false;
576 }
577
578 // here, curCount == INITIAL_STRONG_VALUE, which means
579 // there never was a strong-reference, so we can try to
580 // promote this object; we need to do that atomically.
581 while (curCount > 0) {
Hans Boehme263e6c2016-05-11 18:15:12 -0700582 if (impl->mStrong.compare_exchange_weak(curCount, curCount+1,
583 std::memory_order_relaxed)) {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700584 break;
585 }
586 // the strong count has changed on us, we need to re-assert our
587 // situation (e.g.: another thread has inc/decStrong'ed us)
Hans Boehme263e6c2016-05-11 18:15:12 -0700588 // curCount has been updated.
Dianne Hackborna729ab12013-03-14 15:26:30 -0700589 }
590
591 if (curCount <= 0) {
592 // promote() failed, some other thread destroyed us in the
593 // meantime (i.e.: strong count reached zero).
594 decWeak(id);
595 return false;
596 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800597 } else {
Dianne Hackborna729ab12013-03-14 15:26:30 -0700598 // this object has an "extended" life-time, i.e.: it can be
599 // revived from a weak-reference only.
600 // Ask the object's implementation if it agrees to be revived
601 if (!impl->mBase->onIncStrongAttempted(FIRST_INC_STRONG, id)) {
602 // it didn't so give-up.
603 decWeak(id);
604 return false;
605 }
606 // grab a strong-reference, which is always safe due to the
607 // extended life-time.
Hans Boehme263e6c2016-05-11 18:15:12 -0700608 curCount = impl->mStrong.fetch_add(1, std::memory_order_relaxed);
Hans Boehm7f27cbc2016-07-29 14:39:10 -0700609 // If the strong reference count has already been incremented by
610 // someone else, the implementor of onIncStrongAttempted() is holding
611 // an unneeded reference. So call onLastStrongRef() here to remove it.
612 // (No, this is not pretty.) Note that we MUST NOT do this if we
613 // are in fact acquiring the first reference.
614 if (curCount != 0 && curCount != INITIAL_STRONG_VALUE) {
615 impl->mBase->onLastStrongRef(id);
616 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800617 }
618 }
619
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800620 impl->addStrongRef(id);
621
622#if PRINT_REFS
Steve Blockeb095332011-12-20 16:23:08 +0000623 ALOGD("attemptIncStrong of %p from %p: cnt=%d\n", this, id, curCount);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800624#endif
625
Hans Boehm7f27cbc2016-07-29 14:39:10 -0700626 // curCount is the value of mStrong before we incremented it.
Hans Boehme263e6c2016-05-11 18:15:12 -0700627 // Now we need to fix-up the count if it was INITIAL_STRONG_VALUE.
628 // This must be done safely, i.e.: handle the case where several threads
Dianne Hackborna729ab12013-03-14 15:26:30 -0700629 // were here in attemptIncStrong().
Hans Boehme263e6c2016-05-11 18:15:12 -0700630 // curCount > INITIAL_STRONG_VALUE is OK, and can happen if we're doing
631 // this in the middle of another incStrong. The subtraction is handled
632 // by the thread that started with INITIAL_STRONG_VALUE.
633 if (curCount == INITIAL_STRONG_VALUE) {
634 impl->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
635 std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800636 }
Dianne Hackborna729ab12013-03-14 15:26:30 -0700637
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800638 return true;
639}
640
641bool RefBase::weakref_type::attemptIncWeak(const void* id)
642{
643 weakref_impl* const impl = static_cast<weakref_impl*>(this);
Mathias Agopianad099652011-08-10 21:07:02 -0700644
Hans Boehme263e6c2016-05-11 18:15:12 -0700645 int32_t curCount = impl->mWeak.load(std::memory_order_relaxed);
Steve Blockae074452012-01-09 18:35:44 +0000646 ALOG_ASSERT(curCount >= 0, "attemptIncWeak called on %p after underflow",
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800647 this);
648 while (curCount > 0) {
Hans Boehme263e6c2016-05-11 18:15:12 -0700649 if (impl->mWeak.compare_exchange_weak(curCount, curCount+1,
650 std::memory_order_relaxed)) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800651 break;
652 }
Hans Boehme263e6c2016-05-11 18:15:12 -0700653 // curCount has been updated.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800654 }
655
656 if (curCount > 0) {
657 impl->addWeakRef(id);
658 }
659
660 return curCount > 0;
661}
662
663int32_t RefBase::weakref_type::getWeakCount() const
664{
Hans Boehme263e6c2016-05-11 18:15:12 -0700665 // Debug only!
666 return static_cast<const weakref_impl*>(this)->mWeak
667 .load(std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800668}
669
670void RefBase::weakref_type::printRefs() const
671{
672 static_cast<const weakref_impl*>(this)->printRefs();
673}
674
675void RefBase::weakref_type::trackMe(bool enable, bool retain)
676{
Mathias Agopianad099652011-08-10 21:07:02 -0700677 static_cast<weakref_impl*>(this)->trackMe(enable, retain);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800678}
679
680RefBase::weakref_type* RefBase::createWeak(const void* id) const
681{
682 mRefs->incWeak(id);
683 return mRefs;
684}
685
686RefBase::weakref_type* RefBase::getWeakRefs() const
687{
688 return mRefs;
689}
690
691RefBase::RefBase()
692 : mRefs(new weakref_impl(this))
693{
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800694}
695
696RefBase::~RefBase()
697{
Hans Boehm23c857e2016-08-02 18:39:30 -0700698 int32_t flags = mRefs->mFlags.load(std::memory_order_relaxed);
699 // Life-time of this object is extended to WEAK, in
700 // which case weakref_impl doesn't out-live the object and we
701 // can free it now.
702 if ((flags & OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_WEAK) {
703 // It's possible that the weak count is not 0 if the object
704 // re-acquired a weak reference in its destructor
705 if (mRefs->mWeak.load(std::memory_order_relaxed) == 0) {
706 delete mRefs;
707 }
708 } else if (mRefs->mStrong.load(std::memory_order_relaxed)
Hans Boehme263e6c2016-05-11 18:15:12 -0700709 == INITIAL_STRONG_VALUE) {
Hans Boehm9ba71922016-07-21 18:56:55 -0700710 // We never acquired a strong reference on this object.
Hans Boehm23c857e2016-08-02 18:39:30 -0700711 LOG_ALWAYS_FATAL_IF(mRefs->mWeak.load() != 0,
712 "RefBase: Explicit destruction with non-zero weak "
713 "reference count");
714 // TODO: Always report if we get here. Currently MediaMetadataRetriever
715 // C++ objects are inconsistently managed and sometimes get here.
716 // There may be other cases, but we believe they should all be fixed.
Mathias Agopian9c8fa9e2011-06-15 20:42:47 -0700717 delete mRefs;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800718 }
Hans Boehm23c857e2016-08-02 18:39:30 -0700719 // For debugging purposes, clear mRefs. Ineffective against outstanding wp's.
Mathias Agopianad099652011-08-10 21:07:02 -0700720 const_cast<weakref_impl*&>(mRefs) = NULL;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800721}
722
723void RefBase::extendObjectLifetime(int32_t mode)
724{
Hans Boehme263e6c2016-05-11 18:15:12 -0700725 // Must be happens-before ordered with respect to construction or any
726 // operation that could destroy the object.
727 mRefs->mFlags.fetch_or(mode, std::memory_order_relaxed);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800728}
729
730void RefBase::onFirstRef()
731{
732}
733
734void RefBase::onLastStrongRef(const void* /*id*/)
735{
736}
737
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700738bool RefBase::onIncStrongAttempted(uint32_t flags, const void* /*id*/)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800739{
740 return (flags&FIRST_INC_STRONG) ? true : false;
741}
742
743void RefBase::onLastWeakRef(const void* /*id*/)
744{
745}
Mathias Agopianad099652011-08-10 21:07:02 -0700746
747// ---------------------------------------------------------------------------
748
Mathias Agopianad099652011-08-10 21:07:02 -0700749#if DEBUG_REFS
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700750void RefBase::renameRefs(size_t n, const ReferenceRenamer& renamer) {
Mathias Agopianad099652011-08-10 21:07:02 -0700751 for (size_t i=0 ; i<n ; i++) {
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700752 renamer(i);
Mathias Agopianad099652011-08-10 21:07:02 -0700753 }
Mathias Agopianad099652011-08-10 21:07:02 -0700754}
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700755#else
756void RefBase::renameRefs(size_t /*n*/, const ReferenceRenamer& /*renamer*/) { }
757#endif
Mathias Agopianad099652011-08-10 21:07:02 -0700758
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700759void RefBase::renameRefId(weakref_type* ref,
760 const void* old_id, const void* new_id) {
761 weakref_impl* const impl = static_cast<weakref_impl*>(ref);
762 impl->renameStrongRefId(old_id, new_id);
763 impl->renameWeakRefId(old_id, new_id);
764}
765
766void RefBase::renameRefId(RefBase* ref,
767 const void* old_id, const void* new_id) {
768 ref->mRefs->renameStrongRefId(old_id, new_id);
769 ref->mRefs->renameWeakRefId(old_id, new_id);
770}
771
Colin Cross17b5b822016-09-15 18:15:37 -0700772VirtualLightRefBase::~VirtualLightRefBase() {}
773
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800774}; // namespace android