blob: a105474bb8471a8617673a26a9bf04a0a71827d3 [file] [log] [blame]
The Android Open Source Projectcbb10112009-03-03 19:31:44 -08001/*
Hans Boehm9ba71922016-07-21 18:56:55 -07002 * Copyright (C) 2016 The Android Open Source Project
The Android Open Source Projectcbb10112009-03-03 19:31:44 -08003 *
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
Hans Boehm9ba71922016-07-21 18:56:55 -070017
18// SOME COMMENTS ABOUT USAGE:
19
20// This provides primarily wp<> weak pointer types and RefBase, which work
21// together with sp<> from <StrongPointer.h>.
22
23// sp<> (and wp<>) are a type of smart pointer that use a well defined protocol
24// to operate. As long as the object they are templated with implements that
25// protocol, these smart pointers work. In several places the platform
26// instantiates sp<> with non-RefBase objects; the two are not tied to each
27// other.
28
29// RefBase is such an implementation and it supports strong pointers, weak
30// pointers and some magic features for the binder.
31
32// So, when using RefBase objects, you have the ability to use strong and weak
33// pointers through sp<> and wp<>.
34
35// Normally, when the last strong pointer goes away, the object is destroyed,
36// i.e. it's destructor is called. HOWEVER, parts of its associated memory is not
37// freed until the last weak pointer is released.
38
39// Weak pointers are essentially "safe" pointers. They are always safe to
40// access through promote(). They may return nullptr if the object was
41// destroyed because it ran out of strong pointers. This makes them good candidates
42// for keys in a cache for instance.
43
44// Weak pointers remain valid for comparison purposes even after the underlying
45// object has been destroyed. Even if object A is destroyed and its memory reused
46// for B, A remaining weak pointer to A will not compare equal to one to B.
47// This again makes them attractive for use as keys.
48
49// How is this supposed / intended to be used?
50
51// Our recommendation is to use strong references (sp<>) when there is an
52// ownership relation. e.g. when an object "owns" another one, use a strong
53// ref. And of course use strong refs as arguments of functions (it's extremely
54// rare that a function will take a wp<>).
55
56// Typically a newly allocated object will immediately be used to initialize
57// a strong pointer, which may then be used to construct or assign to other
58// strong and weak pointers.
59
60// Use weak references when there are no ownership relation. e.g. the keys in a
61// cache (you cannot use plain pointers because there is no safe way to acquire
62// a strong reference from a vanilla pointer).
63
64// This implies that two objects should never (or very rarely) have sp<> on
65// each other, because they can't both own each other.
66
67
68// Caveats with reference counting
69
70// Obviously, circular strong references are a big problem; this creates leaks
71// and it's hard to debug -- except it's in fact really easy because RefBase has
72// tons of debugging code for that. It can basically tell you exactly where the
73// leak is.
74
75// Another problem has to do with destructors with side effects. You must
76// assume that the destructor of reference counted objects can be called AT ANY
77// TIME. For instance code as simple as this:
78
79// void setStuff(const sp<Stuff>& stuff) {
80// std::lock_guard<std::mutex> lock(mMutex);
81// mStuff = stuff;
82// }
83
84// is very dangerous. This code WILL deadlock one day or another.
85
86// What isn't obvious is that ~Stuff() can be called as a result of the
87// assignment. And it gets called with the lock held. First of all, the lock is
88// protecting mStuff, not ~Stuff(). Secondly, if ~Stuff() uses its own internal
89// mutex, now you have mutex ordering issues. Even worse, if ~Stuff() is
90// virtual, now you're calling into "user" code (potentially), by that, I mean,
91// code you didn't even write.
92
93// A correct way to write this code is something like:
94
95// void setStuff(const sp<Stuff>& stuff) {
96// std::unique_lock<std::mutex> lock(mMutex);
97// sp<Stuff> hold = mStuff;
98// mStuff = stuff;
99// lock.unlock();
100// }
101
102// More importantly, reference counted objects should do as little work as
103// possible in their destructor, or at least be mindful that their destructor
104// could be called from very weird and unintended places.
105
106// Other more specific restrictions for wp<> and sp<>:
107
Hans Boehm23c857e2016-08-02 18:39:30 -0700108// Do not construct a strong pointer to "this" in an object's constructor.
109// The onFirstRef() callback would be made on an incompletely constructed
110// object.
111// Construction of a weak pointer to "this" in an object's constructor is also
112// discouraged. But the implementation was recently changed so that, in the
113// absence of extendObjectLifetime() calls, weak pointers no longer impact
114// object lifetime, and hence this no longer risks premature deallocation,
115// and hence usually works correctly.
Hans Boehm9ba71922016-07-21 18:56:55 -0700116
117// Such strong or weak pointers can be safely created in the RefBase onFirstRef()
118// callback.
119
120// Use of wp::unsafe_get() for any purpose other than debugging is almost
121// always wrong. Unless you somehow know that there is a longer-lived sp<> to
122// the same object, it may well return a pointer to a deallocated object that
123// has since been reallocated for a different purpose. (And if you know there
124// is a longer-lived sp<>, why not use an sp<> directly?) A wp<> should only be
125// dereferenced by using promote().
126
Hans Boehm23c857e2016-08-02 18:39:30 -0700127// Any object inheriting from RefBase should always be destroyed as the result
128// of a reference count decrement, not via any other means. Such objects
129// should never be stack allocated, or appear directly as data members in other
130// objects. Objects inheriting from RefBase should have their strong reference
131// count incremented as soon as possible after construction. Usually this
132// will be done via construction of an sp<> to the object, but may instead
133// involve other means of calling RefBase::incStrong().
Hans Boehm9ba71922016-07-21 18:56:55 -0700134// Explicitly deleting or otherwise destroying a RefBase object with outstanding
Hans Boehm23c857e2016-08-02 18:39:30 -0700135// wp<> or sp<> pointers to it will result in an abort or heap corruption.
136
137// It is particularly important not to mix sp<> and direct storage management
138// since the sp from raw pointer constructor is implicit. Thus if a RefBase-
139// -derived object of type T is managed without ever incrementing its strong
140// count, and accidentally passed to f(sp<T>), a strong pointer to the object
141// will be temporarily constructed and destroyed, prematurely deallocating the
142// object, and resulting in heap corruption. None of this would be easily
143// visible in the source.
Hans Boehm9ba71922016-07-21 18:56:55 -0700144
145// Extra Features:
146
147// RefBase::extendObjectLifetime() can be used to prevent destruction of the
148// object while there are still weak references. This is really special purpose
149// functionality to support Binder.
150
151// Wp::promote(), implemented via the attemptIncStrong() member function, is
152// used to try to convert a weak pointer back to a strong pointer. It's the
153// normal way to try to access the fields of an object referenced only through
154// a wp<>. Binder code also sometimes uses attemptIncStrong() directly.
155
156// RefBase provides a number of additional callbacks for certain reference count
157// events, as well as some debugging facilities.
158
159// Debugging support can be enabled by turning on DEBUG_REFS in RefBase.cpp.
Hans Boehm23c857e2016-08-02 18:39:30 -0700160// Otherwise little checking is provided.
Hans Boehm9ba71922016-07-21 18:56:55 -0700161
162// Thread safety:
163
164// Like std::shared_ptr, sp<> and wp<> allow concurrent accesses to DIFFERENT
165// sp<> and wp<> instances that happen to refer to the same underlying object.
166// They do NOT support concurrent access (where at least one access is a write)
167// to THE SAME sp<> or wp<>. In effect, their thread-safety properties are
168// exactly like those of T*, NOT atomic<T*>.
169
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800170#ifndef ANDROID_REF_BASE_H
171#define ANDROID_REF_BASE_H
172
Hans Boehme263e6c2016-05-11 18:15:12 -0700173#include <atomic>
Hans Boehm6e75ad62019-03-13 17:34:46 +0000174#include <functional>
175#include <type_traits> // for common_type.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800176
177#include <stdint.h>
178#include <sys/types.h>
179#include <stdlib.h>
Mathias Agopianb26ea8b2011-02-16 20:23:43 -0800180#include <string.h>
181
Mathias Agopian44cee052017-03-27 17:59:01 -0700182// LightRefBase used to be declared in this header, so we have to include it
183#include <utils/LightRefBase.h>
184
Mathias Agopianb26ea8b2011-02-16 20:23:43 -0800185#include <utils/StrongPointer.h>
Jeff Brown9a0a76d2012-03-16 14:45:49 -0700186#include <utils/TypeHelpers.h>
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800187
188// ---------------------------------------------------------------------------
189namespace android {
190
Mathias Agopian84a23fa2011-02-16 15:23:08 -0800191class TextOutput;
Mathias Agopian84a23fa2011-02-16 15:23:08 -0800192TextOutput& printWeakPointer(TextOutput& to, const void* val);
193
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800194// ---------------------------------------------------------------------------
195
Mathias Agopianff49de72011-02-09 18:38:55 -0800196#define COMPARE_WEAK(_op_) \
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800197template<typename U> \
Mathias Agopianff49de72011-02-09 18:38:55 -0800198inline bool operator _op_ (const U* o) const { \
199 return m_ptr _op_ o; \
Hans Boehm6e75ad62019-03-13 17:34:46 +0000200} \
201/* Needed to handle type inference for nullptr: */ \
202inline bool operator _op_ (const T* o) const { \
203 return m_ptr _op_ o; \
204}
205
206template<template<typename C> class comparator, typename T, typename U>
207static inline bool _wp_compare_(T* a, U* b) {
208 return comparator<typename std::common_type<T*, U*>::type>()(a, b);
209}
210
211// Use std::less and friends to avoid undefined behavior when ordering pointers
212// to different objects.
213#define COMPARE_WEAK_FUNCTIONAL(_op_, _compare_) \
214template<typename U> \
215inline bool operator _op_ (const U* o) const { \
216 return _wp_compare_<_compare_>(m_ptr, o); \
Mathias Agopianff49de72011-02-09 18:38:55 -0800217}
218
Mathias Agopianb26ea8b2011-02-16 20:23:43 -0800219// ---------------------------------------------------------------------------
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700220
Colin Cross1811d152016-09-26 14:24:48 -0700221// RefererenceRenamer is pure abstract, there is no virtual method
222// implementation to put in a translation unit in order to silence the
223// weak vtables warning.
224#if defined(__clang__)
225#pragma clang diagnostic push
226#pragma clang diagnostic ignored "-Wweak-vtables"
227#endif
228
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700229class ReferenceRenamer {
230protected:
Mathias Agopian44cee052017-03-27 17:59:01 -0700231 // destructor is purposely not virtual so we avoid code overhead from
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700232 // subclasses; we have to make it protected to guarantee that it
233 // cannot be called from this base class (and to make strict compilers
234 // happy).
Colin Cross1811d152016-09-26 14:24:48 -0700235 ~ReferenceRenamer() { }
Mathias Agopianb26ea8b2011-02-16 20:23:43 -0800236public:
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700237 virtual void operator()(size_t i) const = 0;
Mathias Agopianb26ea8b2011-02-16 20:23:43 -0800238};
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800239
Colin Cross1811d152016-09-26 14:24:48 -0700240#if defined(__clang__)
241#pragma clang diagnostic pop
242#endif
243
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800244// ---------------------------------------------------------------------------
245
246class RefBase
247{
248public:
249 void incStrong(const void* id) const;
250 void decStrong(const void* id) const;
251
252 void forceIncStrong(const void* id) const;
253
254 //! DEBUGGING ONLY: Get current strong ref count.
255 int32_t getStrongCount() const;
256
257 class weakref_type
258 {
259 public:
260 RefBase* refBase() const;
Mathias Agopian44cee052017-03-27 17:59:01 -0700261
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800262 void incWeak(const void* id);
263 void decWeak(const void* id);
Mathias Agopian44cee052017-03-27 17:59:01 -0700264
Mathias Agopianad099652011-08-10 21:07:02 -0700265 // acquires a strong reference if there is already one.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800266 bool attemptIncStrong(const void* id);
Mathias Agopian44cee052017-03-27 17:59:01 -0700267
Mathias Agopianad099652011-08-10 21:07:02 -0700268 // acquires a weak reference if there is already one.
269 // This is not always safe. see ProcessState.cpp and BpBinder.cpp
270 // for proper use.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800271 bool attemptIncWeak(const void* id);
272
273 //! DEBUGGING ONLY: Get current weak ref count.
274 int32_t getWeakCount() const;
275
276 //! DEBUGGING ONLY: Print references held on object.
277 void printRefs() const;
278
279 //! DEBUGGING ONLY: Enable tracking for this object.
280 // enable -- enable/disable tracking
281 // retain -- when tracking is enable, if true, then we save a stack trace
282 // for each reference and dereference; when retain == false, we
Mathias Agopian44cee052017-03-27 17:59:01 -0700283 // match up references and dereferences and keep only the
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800284 // outstanding ones.
Mathias Agopian44cee052017-03-27 17:59:01 -0700285
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800286 void trackMe(bool enable, bool retain);
287 };
Mathias Agopian44cee052017-03-27 17:59:01 -0700288
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800289 weakref_type* createWeak(const void* id) const;
290
291 weakref_type* getWeakRefs() const;
292
293 //! DEBUGGING ONLY: Print references held on object.
294 inline void printRefs() const { getWeakRefs()->printRefs(); }
295
296 //! DEBUGGING ONLY: Enable tracking of object.
297 inline void trackMe(bool enable, bool retain)
298 {
299 getWeakRefs()->trackMe(enable, retain);
300 }
301
Mathias Agopianb26ea8b2011-02-16 20:23:43 -0800302 typedef RefBase basetype;
303
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800304protected:
305 RefBase();
306 virtual ~RefBase();
Mathias Agopian7f57eac2011-06-16 17:15:51 -0700307
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800308 //! Flags for extendObjectLifetime()
309 enum {
Mathias Agopianad099652011-08-10 21:07:02 -0700310 OBJECT_LIFETIME_STRONG = 0x0000,
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800311 OBJECT_LIFETIME_WEAK = 0x0001,
Mathias Agopianad099652011-08-10 21:07:02 -0700312 OBJECT_LIFETIME_MASK = 0x0001
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800313 };
314
315 void extendObjectLifetime(int32_t mode);
316
317 //! Flags for onIncStrongAttempted()
318 enum {
319 FIRST_INC_STRONG = 0x0001
320 };
321
Hans Boehm9ba71922016-07-21 18:56:55 -0700322 // Invoked after creation of initial strong pointer/reference.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800323 virtual void onFirstRef();
Hans Boehm9ba71922016-07-21 18:56:55 -0700324 // Invoked when either the last strong reference goes away, or we need to undo
325 // the effect of an unnecessary onIncStrongAttempted.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800326 virtual void onLastStrongRef(const void* id);
Hans Boehm9ba71922016-07-21 18:56:55 -0700327 // Only called in OBJECT_LIFETIME_WEAK case. Returns true if OK to promote to
328 // strong reference. May have side effects if it returns true.
329 // The first flags argument is always FIRST_INC_STRONG.
330 // TODO: Remove initial flag argument.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800331 virtual bool onIncStrongAttempted(uint32_t flags, const void* id);
Hans Boehm9ba71922016-07-21 18:56:55 -0700332 // Invoked in the OBJECT_LIFETIME_WEAK case when the last reference of either
333 // kind goes away. Unused.
334 // TODO: Remove.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800335 virtual void onLastWeakRef(const void* id);
336
337private:
338 friend class weakref_type;
339 class weakref_impl;
340
341 RefBase(const RefBase& o);
342 RefBase& operator=(const RefBase& o);
Mathias Agopianad099652011-08-10 21:07:02 -0700343
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700344private:
345 friend class ReferenceMover;
346
347 static void renameRefs(size_t n, const ReferenceRenamer& renamer);
348
349 static void renameRefId(weakref_type* ref,
350 const void* old_id, const void* new_id);
351
352 static void renameRefId(RefBase* ref,
353 const void* old_id, const void* new_id);
354
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800355 weakref_impl* const mRefs;
356};
357
358// ---------------------------------------------------------------------------
359
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800360template <typename T>
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800361class wp
362{
363public:
364 typedef typename RefBase::weakref_type weakref_type;
Mathias Agopian44cee052017-03-27 17:59:01 -0700365
Hans Boehm6e75ad62019-03-13 17:34:46 +0000366 inline wp() : m_ptr(nullptr), m_refs(nullptr) { }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800367
Chih-Hung Hsieh2a929962016-08-02 12:14:47 -0700368 wp(T* other); // NOLINT(implicit)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800369 wp(const wp<T>& other);
Chih-Hung Hsieh2a929962016-08-02 12:14:47 -0700370 explicit wp(const sp<T>& other);
371 template<typename U> wp(U* other); // NOLINT(implicit)
372 template<typename U> wp(const sp<U>& other); // NOLINT(implicit)
373 template<typename U> wp(const wp<U>& other); // NOLINT(implicit)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800374
375 ~wp();
Mathias Agopian44cee052017-03-27 17:59:01 -0700376
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800377 // Assignment
378
379 wp& operator = (T* other);
380 wp& operator = (const wp<T>& other);
381 wp& operator = (const sp<T>& other);
Mathias Agopian44cee052017-03-27 17:59:01 -0700382
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800383 template<typename U> wp& operator = (U* other);
384 template<typename U> wp& operator = (const wp<U>& other);
385 template<typename U> wp& operator = (const sp<U>& other);
Mathias Agopian44cee052017-03-27 17:59:01 -0700386
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800387 void set_object_and_refs(T* other, weakref_type* refs);
388
389 // promotion to sp
Mathias Agopian44cee052017-03-27 17:59:01 -0700390
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800391 sp<T> promote() const;
392
393 // Reset
Mathias Agopian44cee052017-03-27 17:59:01 -0700394
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800395 void clear();
396
397 // Accessors
Mathias Agopian44cee052017-03-27 17:59:01 -0700398
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800399 inline weakref_type* get_refs() const { return m_refs; }
Mathias Agopian44cee052017-03-27 17:59:01 -0700400
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800401 inline T* unsafe_get() const { return m_ptr; }
402
403 // Operators
Mathias Agopianff49de72011-02-09 18:38:55 -0800404
405 COMPARE_WEAK(==)
406 COMPARE_WEAK(!=)
Hans Boehm6e75ad62019-03-13 17:34:46 +0000407 COMPARE_WEAK_FUNCTIONAL(>, std::greater)
408 COMPARE_WEAK_FUNCTIONAL(<, std::less)
409 COMPARE_WEAK_FUNCTIONAL(<=, std::less_equal)
410 COMPARE_WEAK_FUNCTIONAL(>=, std::greater_equal)
Mathias Agopianff49de72011-02-09 18:38:55 -0800411
Mathias Agopianff49de72011-02-09 18:38:55 -0800412 template<typename U>
413 inline bool operator == (const wp<U>& o) const {
Hans Boehm6e75ad62019-03-13 17:34:46 +0000414 return m_refs == o.m_refs; // Implies m_ptr == o.mptr; see invariants below.
Mathias Agopianff49de72011-02-09 18:38:55 -0800415 }
416
Hans Boehm6e75ad62019-03-13 17:34:46 +0000417 template<typename U>
418 inline bool operator == (const sp<U>& o) const {
419 // Just comparing m_ptr fields is often dangerous, since wp<> may refer to an older
420 // object at the same address.
421 if (o == nullptr) {
422 return m_ptr == nullptr;
423 } else {
424 return m_refs == o->getWeakRefs(); // Implies m_ptr == o.mptr.
425 }
Mathias Agopianff49de72011-02-09 18:38:55 -0800426 }
Hans Boehm6e75ad62019-03-13 17:34:46 +0000427
428 template<typename U>
429 inline bool operator != (const sp<U>& o) const {
430 return !(*this == o);
431 }
432
Mathias Agopianff49de72011-02-09 18:38:55 -0800433 template<typename U>
434 inline bool operator > (const wp<U>& o) const {
Hans Boehm6e75ad62019-03-13 17:34:46 +0000435 if (m_ptr == o.m_ptr) {
436 return _wp_compare_<std::greater>(m_refs, o.m_refs);
437 } else {
438 return _wp_compare_<std::greater>(m_ptr, o.m_ptr);
439 }
Mathias Agopianff49de72011-02-09 18:38:55 -0800440 }
441
Mathias Agopianff49de72011-02-09 18:38:55 -0800442 template<typename U>
443 inline bool operator < (const wp<U>& o) const {
Hans Boehm6e75ad62019-03-13 17:34:46 +0000444 if (m_ptr == o.m_ptr) {
445 return _wp_compare_<std::less>(m_refs, o.m_refs);
446 } else {
447 return _wp_compare_<std::less>(m_ptr, o.m_ptr);
448 }
Mathias Agopianff49de72011-02-09 18:38:55 -0800449 }
Mathias Agopianff49de72011-02-09 18:38:55 -0800450 template<typename U> inline bool operator != (const wp<U>& o) const { return !operator == (o); }
Mathias Agopianff49de72011-02-09 18:38:55 -0800451 template<typename U> inline bool operator <= (const wp<U>& o) const { return !operator > (o); }
Mathias Agopianff49de72011-02-09 18:38:55 -0800452 template<typename U> inline bool operator >= (const wp<U>& o) const { return !operator < (o); }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800453
454private:
455 template<typename Y> friend class sp;
456 template<typename Y> friend class wp;
457
458 T* m_ptr;
459 weakref_type* m_refs;
460};
461
462template <typename T>
463TextOutput& operator<<(TextOutput& to, const wp<T>& val);
464
Mathias Agopianff49de72011-02-09 18:38:55 -0800465#undef COMPARE_WEAK
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800466
467// ---------------------------------------------------------------------------
468// No user serviceable parts below here.
469
Hans Boehm6e75ad62019-03-13 17:34:46 +0000470// Implementation invariants:
471// Either
472// 1) m_ptr and m_refs are both null, or
473// 2) m_refs == m_ptr->mRefs, or
474// 3) *m_ptr is no longer live, and m_refs points to the weakref_type object that corresponded
475// to m_ptr while it was live. *m_refs remains live while a wp<> refers to it.
476//
477// The m_refs field in a RefBase object is allocated on construction, unique to that RefBase
478// object, and never changes. Thus if two wp's have identical m_refs fields, they are either both
479// null or point to the same object. If two wp's have identical m_ptr fields, they either both
480// point to the same live object and thus have the same m_ref fields, or at least one of the
481// objects is no longer live.
482//
483// Note that the above comparison operations go out of their way to provide an ordering consistent
484// with ordinary pointer comparison; otherwise they could ignore m_ptr, and just compare m_refs.
485
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800486template<typename T>
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800487wp<T>::wp(T* other)
488 : m_ptr(other)
489{
Hans Boehm6e75ad62019-03-13 17:34:46 +0000490 m_refs = other ? m_refs = other->createWeak(this) : nullptr;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800491}
492
493template<typename T>
494wp<T>::wp(const wp<T>& other)
495 : m_ptr(other.m_ptr), m_refs(other.m_refs)
496{
497 if (m_ptr) m_refs->incWeak(this);
498}
499
500template<typename T>
501wp<T>::wp(const sp<T>& other)
502 : m_ptr(other.m_ptr)
503{
Hans Boehm6e75ad62019-03-13 17:34:46 +0000504 m_refs = m_ptr ? m_ptr->createWeak(this) : nullptr;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800505}
506
507template<typename T> template<typename U>
508wp<T>::wp(U* other)
509 : m_ptr(other)
510{
Hans Boehm6e75ad62019-03-13 17:34:46 +0000511 m_refs = other ? other->createWeak(this) : nullptr;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800512}
513
514template<typename T> template<typename U>
515wp<T>::wp(const wp<U>& other)
516 : m_ptr(other.m_ptr)
517{
518 if (m_ptr) {
519 m_refs = other.m_refs;
520 m_refs->incWeak(this);
Hans Boehm6e75ad62019-03-13 17:34:46 +0000521 } else {
522 m_refs = nullptr;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800523 }
524}
525
526template<typename T> template<typename U>
527wp<T>::wp(const sp<U>& other)
528 : m_ptr(other.m_ptr)
529{
Hans Boehm6e75ad62019-03-13 17:34:46 +0000530 m_refs = m_ptr ? m_ptr->createWeak(this) : nullptr;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800531}
532
533template<typename T>
534wp<T>::~wp()
535{
536 if (m_ptr) m_refs->decWeak(this);
537}
538
539template<typename T>
540wp<T>& wp<T>::operator = (T* other)
541{
542 weakref_type* newRefs =
Yi Kongc1a15622018-07-11 17:37:34 -0700543 other ? other->createWeak(this) : nullptr;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800544 if (m_ptr) m_refs->decWeak(this);
545 m_ptr = other;
546 m_refs = newRefs;
547 return *this;
548}
549
550template<typename T>
551wp<T>& wp<T>::operator = (const wp<T>& other)
552{
Mathias Agopian7b151672010-06-24 21:49:02 -0700553 weakref_type* otherRefs(other.m_refs);
554 T* otherPtr(other.m_ptr);
555 if (otherPtr) otherRefs->incWeak(this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800556 if (m_ptr) m_refs->decWeak(this);
Mathias Agopian7b151672010-06-24 21:49:02 -0700557 m_ptr = otherPtr;
558 m_refs = otherRefs;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800559 return *this;
560}
561
562template<typename T>
563wp<T>& wp<T>::operator = (const sp<T>& other)
564{
565 weakref_type* newRefs =
Yi Kongc1a15622018-07-11 17:37:34 -0700566 other != nullptr ? other->createWeak(this) : nullptr;
Mathias Agopian7b151672010-06-24 21:49:02 -0700567 T* otherPtr(other.m_ptr);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800568 if (m_ptr) m_refs->decWeak(this);
Mathias Agopian7b151672010-06-24 21:49:02 -0700569 m_ptr = otherPtr;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800570 m_refs = newRefs;
571 return *this;
572}
573
574template<typename T> template<typename U>
575wp<T>& wp<T>::operator = (U* other)
576{
577 weakref_type* newRefs =
578 other ? other->createWeak(this) : 0;
579 if (m_ptr) m_refs->decWeak(this);
580 m_ptr = other;
581 m_refs = newRefs;
582 return *this;
583}
584
585template<typename T> template<typename U>
586wp<T>& wp<T>::operator = (const wp<U>& other)
587{
Mathias Agopian7b151672010-06-24 21:49:02 -0700588 weakref_type* otherRefs(other.m_refs);
589 U* otherPtr(other.m_ptr);
590 if (otherPtr) otherRefs->incWeak(this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800591 if (m_ptr) m_refs->decWeak(this);
Mathias Agopian7b151672010-06-24 21:49:02 -0700592 m_ptr = otherPtr;
593 m_refs = otherRefs;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800594 return *this;
595}
596
597template<typename T> template<typename U>
598wp<T>& wp<T>::operator = (const sp<U>& other)
599{
600 weakref_type* newRefs =
Yi Konge1731a42018-07-16 18:11:34 -0700601 other != nullptr ? other->createWeak(this) : 0;
Mathias Agopian7b151672010-06-24 21:49:02 -0700602 U* otherPtr(other.m_ptr);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800603 if (m_ptr) m_refs->decWeak(this);
Mathias Agopian7b151672010-06-24 21:49:02 -0700604 m_ptr = otherPtr;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800605 m_refs = newRefs;
606 return *this;
607}
608
609template<typename T>
610void wp<T>::set_object_and_refs(T* other, weakref_type* refs)
611{
612 if (other) refs->incWeak(this);
613 if (m_ptr) m_refs->decWeak(this);
614 m_ptr = other;
615 m_refs = refs;
616}
617
618template<typename T>
619sp<T> wp<T>::promote() const
620{
Mathias Agopian3e0f8752011-02-24 18:12:34 -0800621 sp<T> result;
622 if (m_ptr && m_refs->attemptIncStrong(&result)) {
623 result.set_pointer(m_ptr);
624 }
625 return result;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800626}
627
628template<typename T>
629void wp<T>::clear()
630{
631 if (m_ptr) {
632 m_refs->decWeak(this);
Hans Boehm6e75ad62019-03-13 17:34:46 +0000633 m_refs = 0;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800634 m_ptr = 0;
635 }
636}
637
638template <typename T>
639inline TextOutput& operator<<(TextOutput& to, const wp<T>& val)
640{
Mathias Agopian84a23fa2011-02-16 15:23:08 -0800641 return printWeakPointer(to, val.unsafe_get());
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800642}
643
Mathias Agopianb26ea8b2011-02-16 20:23:43 -0800644// ---------------------------------------------------------------------------
645
646// this class just serves as a namespace so TYPE::moveReferences can stay
647// private.
Mathias Agopianb26ea8b2011-02-16 20:23:43 -0800648class ReferenceMover {
Mathias Agopianb26ea8b2011-02-16 20:23:43 -0800649public:
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700650 // it would be nice if we could make sure no extra code is generated
651 // for sp<TYPE> or wp<TYPE> when TYPE is a descendant of RefBase:
652 // Using a sp<RefBase> override doesn't work; it's a bit like we wanted
653 // a template<typename TYPE inherits RefBase> template...
654
Mathias Agopianb26ea8b2011-02-16 20:23:43 -0800655 template<typename TYPE> static inline
Colin Cross17b5b822016-09-15 18:15:37 -0700656 void move_references(sp<TYPE>* dest, sp<TYPE> const* src, size_t n) {
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700657
658 class Renamer : public ReferenceRenamer {
Colin Cross17b5b822016-09-15 18:15:37 -0700659 sp<TYPE>* d_;
660 sp<TYPE> const* s_;
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700661 virtual void operator()(size_t i) const {
662 // The id are known to be the sp<>'s this pointer
Colin Cross17b5b822016-09-15 18:15:37 -0700663 TYPE::renameRefId(d_[i].get(), &s_[i], &d_[i]);
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700664 }
665 public:
Colin Cross17b5b822016-09-15 18:15:37 -0700666 Renamer(sp<TYPE>* d, sp<TYPE> const* s) : d_(d), s_(s) { }
Ukri Niemimuukko00e56a22014-04-29 06:25:28 +0800667 virtual ~Renamer() { }
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700668 };
669
Colin Cross17b5b822016-09-15 18:15:37 -0700670 memmove(dest, src, n*sizeof(sp<TYPE>));
671 TYPE::renameRefs(n, Renamer(dest, src));
Mathias Agopianb26ea8b2011-02-16 20:23:43 -0800672 }
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700673
674
Mathias Agopianb26ea8b2011-02-16 20:23:43 -0800675 template<typename TYPE> static inline
Colin Cross17b5b822016-09-15 18:15:37 -0700676 void move_references(wp<TYPE>* dest, wp<TYPE> const* src, size_t n) {
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700677
678 class Renamer : public ReferenceRenamer {
Colin Cross17b5b822016-09-15 18:15:37 -0700679 wp<TYPE>* d_;
680 wp<TYPE> const* s_;
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700681 virtual void operator()(size_t i) const {
682 // The id are known to be the wp<>'s this pointer
Colin Cross17b5b822016-09-15 18:15:37 -0700683 TYPE::renameRefId(d_[i].get_refs(), &s_[i], &d_[i]);
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700684 }
685 public:
Colin Cross17b5b822016-09-15 18:15:37 -0700686 Renamer(wp<TYPE>* rd, wp<TYPE> const* rs) : d_(rd), s_(rs) { }
Ukri Niemimuukko00e56a22014-04-29 06:25:28 +0800687 virtual ~Renamer() { }
Mathias Agopian6cd548c2013-03-18 22:27:41 -0700688 };
689
Colin Cross17b5b822016-09-15 18:15:37 -0700690 memmove(dest, src, n*sizeof(wp<TYPE>));
691 TYPE::renameRefs(n, Renamer(dest, src));
Mathias Agopianb26ea8b2011-02-16 20:23:43 -0800692 }
693};
694
695// specialization for moving sp<> and wp<> types.
696// these are used by the [Sorted|Keyed]Vector<> implementations
697// sp<> and wp<> need to be handled specially, because they do not
698// have trivial copy operation in the general case (see RefBase.cpp
699// when DEBUG ops are enabled), but can be implemented very
700// efficiently in most cases.
701
702template<typename TYPE> inline
703void move_forward_type(sp<TYPE>* d, sp<TYPE> const* s, size_t n) {
704 ReferenceMover::move_references(d, s, n);
705}
706
707template<typename TYPE> inline
708void move_backward_type(sp<TYPE>* d, sp<TYPE> const* s, size_t n) {
709 ReferenceMover::move_references(d, s, n);
710}
711
712template<typename TYPE> inline
713void move_forward_type(wp<TYPE>* d, wp<TYPE> const* s, size_t n) {
714 ReferenceMover::move_references(d, s, n);
715}
716
717template<typename TYPE> inline
718void move_backward_type(wp<TYPE>* d, wp<TYPE> const* s, size_t n) {
719 ReferenceMover::move_references(d, s, n);
720}
721
Pirama Arumuga Nainareab48ce2018-04-10 14:31:29 -0700722} // namespace android
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800723
724// ---------------------------------------------------------------------------
725
726#endif // ANDROID_REF_BASE_H