1 /*
2 * Copyright (C) 2016 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
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
108 // 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.
116
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
127 // 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().
134 // Explicitly deleting or otherwise destroying a RefBase object with outstanding
135 // 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. See below on
144 // ANDROID_UTILS_REF_BASE_DISABLE_IMPLICIT_CONSTRUCTION for a compile time
145 // option which helps avoid this case.
146
147 // Extra Features:
148
149 // RefBase::extendObjectLifetime() can be used to prevent destruction of the
150 // object while there are still weak references. This is really special purpose
151 // functionality to support Binder.
152
153 // Wp::promote(), implemented via the attemptIncStrong() member function, is
154 // used to try to convert a weak pointer back to a strong pointer. It's the
155 // normal way to try to access the fields of an object referenced only through
156 // a wp<>. Binder code also sometimes uses attemptIncStrong() directly.
157
158 // RefBase provides a number of additional callbacks for certain reference count
159 // events, as well as some debugging facilities.
160
161 // Debugging support can be enabled by turning on DEBUG_REFS in RefBase.cpp.
162 // Otherwise little checking is provided.
163
164 // Thread safety:
165
166 // Like std::shared_ptr, sp<> and wp<> allow concurrent accesses to DIFFERENT
167 // sp<> and wp<> instances that happen to refer to the same underlying object.
168 // They do NOT support concurrent access (where at least one access is a write)
169 // to THE SAME sp<> or wp<>. In effect, their thread-safety properties are
170 // exactly like those of T*, NOT atomic<T*>.
171
172 // Safety option: ANDROID_UTILS_REF_BASE_DISABLE_IMPLICIT_CONSTRUCTION
173 //
174 // This flag makes the semantics for using a RefBase object with wp<> and sp<>
175 // much stricter by disabling implicit conversion from raw pointers to these
176 // objects. In order to use this, apply this flag in Android.bp like so:
177 //
178 // cflags: [
179 // "-DANDROID_UTILS_REF_BASE_DISABLE_IMPLICIT_CONSTRUCTION",
180 // ],
181 //
182 // REGARDLESS of whether this flag is on, best usage of sp<> is shown below. If
183 // this flag is on, no other usage is possible (directly calling RefBase methods
184 // is possible, but seeing code using 'incStrong' instead of 'sp<>', for
185 // instance, should already set off big alarm bells. With carefully constructed
186 // data structures, it should NEVER be necessary to directly use RefBase
187 // methods). Proper RefBase usage:
188 //
189 // class Foo : virtual public RefBase { ... };
190 //
191 // // always construct an sp object with sp::make
192 // sp<Foo> myFoo = sp<Foo>::make(/*args*/);
193 //
194 // // if you need a weak pointer, it must be constructed from a strong
195 // // pointer
196 // wp<Foo> weakFoo = myFoo; // NOT myFoo.get()
197 //
198 // // If you are inside of a method of Foo and need access to a strong
199 // // explicitly call this function. This documents your intention to code
200 // // readers, and it will give a runtime error for what otherwise would
201 // // be potential double ownership
202 // .... Foo::someMethod(...) {
203 // // asserts if there is a memory issue
204 // sp<Foo> thiz = sp<Foo>::fromExisting(this);
205 // }
206 //
207
208 #ifndef ANDROID_REF_BASE_H
209 #define ANDROID_REF_BASE_H
210
211 #include <atomic>
212 #include <functional>
213 #include <memory>
214 #include <type_traits> // for common_type.
215
216 #include <stdint.h>
217 #include <sys/types.h>
218 #include <stdlib.h>
219 #include <string.h>
220
221 // LightRefBase used to be declared in this header, so we have to include it
222 #include <utils/LightRefBase.h>
223
224 #include <utils/StrongPointer.h>
225 #include <utils/TypeHelpers.h>
226
227 // ---------------------------------------------------------------------------
228 namespace android {
229
230 // ---------------------------------------------------------------------------
231
232 #define COMPARE_WEAK(_op_) \
233 template<typename U> \
234 inline bool operator _op_ (const U* o) const { \
235 return m_ptr _op_ o; \
236 } \
237 /* Needed to handle type inference for nullptr: */ \
238 inline bool operator _op_ (const T* o) const { \
239 return m_ptr _op_ o; \
240 }
241
242 template<template<typename C> class comparator, typename T, typename U>
_wp_compare_(T * a,U * b)243 static inline bool _wp_compare_(T* a, U* b) {
244 return comparator<typename std::common_type<T*, U*>::type>()(a, b);
245 }
246
247 // Use std::less and friends to avoid undefined behavior when ordering pointers
248 // to different objects.
249 #define COMPARE_WEAK_FUNCTIONAL(_op_, _compare_) \
250 template<typename U> \
251 inline bool operator _op_ (const U* o) const { \
252 return _wp_compare_<_compare_>(m_ptr, o); \
253 }
254
255 // ---------------------------------------------------------------------------
256
257 // RefererenceRenamer is pure abstract, there is no virtual method
258 // implementation to put in a translation unit in order to silence the
259 // weak vtables warning.
260 #if defined(__clang__)
261 #pragma clang diagnostic push
262 #pragma clang diagnostic ignored "-Wweak-vtables"
263 #endif
264
265 class ReferenceRenamer {
266 protected:
267 // destructor is purposely not virtual so we avoid code overhead from
268 // subclasses; we have to make it protected to guarantee that it
269 // cannot be called from this base class (and to make strict compilers
270 // happy).
~ReferenceRenamer()271 ~ReferenceRenamer() { }
272 public:
273 virtual void operator()(size_t i) const = 0;
274 };
275
276 #if defined(__clang__)
277 #pragma clang diagnostic pop
278 #endif
279
280 // ---------------------------------------------------------------------------
281
282 class RefBase
283 {
284 public:
285 void incStrong(const void* id) const;
286 void incStrongRequireStrong(const void* id) const;
287 void decStrong(const void* id) const;
288
289 void forceIncStrong(const void* id) const;
290
291 //! DEBUGGING ONLY: Get current strong ref count.
292 int32_t getStrongCount() const;
293
294 class weakref_type
295 {
296 public:
297 RefBase* refBase() const;
298
299 void incWeak(const void* id);
300 void incWeakRequireWeak(const void* id);
301 void decWeak(const void* id);
302
303 // acquires a strong reference if there is already one.
304 bool attemptIncStrong(const void* id);
305
306 // acquires a weak reference if there is already one.
307 // This is not always safe. see ProcessState.cpp and BpBinder.cpp
308 // for proper use.
309 bool attemptIncWeak(const void* id);
310
311 //! DEBUGGING ONLY: Get current weak ref count.
312 int32_t getWeakCount() const;
313
314 //! DEBUGGING ONLY: Print references held on object.
315 void printRefs() const;
316
317 //! DEBUGGING ONLY: Enable tracking for this object.
318 // enable -- enable/disable tracking
319 // retain -- when tracking is enable, if true, then we save a stack trace
320 // for each reference and dereference; when retain == false, we
321 // match up references and dereferences and keep only the
322 // outstanding ones.
323
324 void trackMe(bool enable, bool retain);
325 };
326
327 weakref_type* createWeak(const void* id) const;
328
329 weakref_type* getWeakRefs() const;
330
331 //! DEBUGGING ONLY: Print references held on object.
printRefs()332 inline void printRefs() const { getWeakRefs()->printRefs(); }
333
334 //! DEBUGGING ONLY: Enable tracking of object.
trackMe(bool enable,bool retain)335 inline void trackMe(bool enable, bool retain)
336 {
337 getWeakRefs()->trackMe(enable, retain);
338 }
339
340 protected:
341 // When constructing these objects, prefer using sp::make<>. Using a RefBase
342 // object on the stack or with other refcount mechanisms (e.g.
343 // std::shared_ptr) is inherently wrong. RefBase types have an implicit
344 // ownership model and cannot be safely used with other ownership models.
345
346 RefBase();
347 virtual ~RefBase();
348
349 //! Flags for extendObjectLifetime()
350 enum {
351 OBJECT_LIFETIME_STRONG = 0x0000,
352 OBJECT_LIFETIME_WEAK = 0x0001,
353 OBJECT_LIFETIME_MASK = 0x0001
354 };
355
356 void extendObjectLifetime(int32_t mode);
357
358 //! Flags for onIncStrongAttempted()
359 enum {
360 FIRST_INC_STRONG = 0x0001
361 };
362
363 // Invoked after creation of initial strong pointer/reference.
364 virtual void onFirstRef();
365 // Invoked when either the last strong reference goes away, or we need to undo
366 // the effect of an unnecessary onIncStrongAttempted.
367 virtual void onLastStrongRef(const void* id);
368 // Only called in OBJECT_LIFETIME_WEAK case. Returns true if OK to promote to
369 // strong reference. May have side effects if it returns true.
370 // The first flags argument is always FIRST_INC_STRONG.
371 // TODO: Remove initial flag argument.
372 virtual bool onIncStrongAttempted(uint32_t flags, const void* id);
373 // Invoked in the OBJECT_LIFETIME_WEAK case when the last reference of either
374 // kind goes away. Unused.
375 // TODO: Remove.
376 virtual void onLastWeakRef(const void* id);
377
378 private:
379 friend class weakref_type;
380 class weakref_impl;
381
382 RefBase(const RefBase& o);
383 RefBase& operator=(const RefBase& o);
384
385 private:
386 friend class ReferenceMover;
387
388 static void renameRefs(size_t n, const ReferenceRenamer& renamer);
389
390 static void renameRefId(weakref_type* ref,
391 const void* old_id, const void* new_id);
392
393 static void renameRefId(RefBase* ref,
394 const void* old_id, const void* new_id);
395
396 weakref_impl* const mRefs;
397 };
398
399 // ---------------------------------------------------------------------------
400
401 template <typename T>
402 class wp
403 {
404 public:
405 typedef typename RefBase::weakref_type weakref_type;
406
wp()407 inline constexpr wp() : m_ptr(nullptr), m_refs(nullptr) { }
408
409 // if nullptr, returns nullptr
410 //
411 // if a weak pointer is already available, this will retrieve it,
412 // otherwise, this will abort
413 static inline wp<T> fromExisting(T* other);
414
415 // for more information about this flag, see above
416 #if defined(ANDROID_UTILS_REF_BASE_DISABLE_IMPLICIT_CONSTRUCTION)
wp(std::nullptr_t)417 wp(std::nullptr_t) : wp() {}
418 #else
419 wp(T* other); // NOLINT(implicit)
420 template <typename U>
421 wp(U* other); // NOLINT(implicit)
422 wp& operator=(T* other);
423 template <typename U>
424 wp& operator=(U* other);
425 #endif
426
427 wp(const wp<T>& other);
428 explicit wp(const sp<T>& other);
429
430 template<typename U> wp(const sp<U>& other); // NOLINT(implicit)
431 template<typename U> wp(const wp<U>& other); // NOLINT(implicit)
432
433 ~wp();
434
435 // Assignment
436
437 wp& operator = (const wp<T>& other);
438 wp& operator = (const sp<T>& other);
439
440 template<typename U> wp& operator = (const wp<U>& other);
441 template<typename U> wp& operator = (const sp<U>& other);
442
443 void set_object_and_refs(T* other, weakref_type* refs);
444
445 // promotion to sp
446
447 sp<T> promote() const;
448
449 // Reset
450
451 void clear();
452
453 // Accessors
454
get_refs()455 inline weakref_type* get_refs() const { return m_refs; }
456
unsafe_get()457 inline T* unsafe_get() const { return m_ptr; }
458
459 // Operators
460
461 COMPARE_WEAK(==)
462 COMPARE_WEAK(!=)
463 COMPARE_WEAK_FUNCTIONAL(>, std::greater)
464 COMPARE_WEAK_FUNCTIONAL(<, std::less)
465 COMPARE_WEAK_FUNCTIONAL(<=, std::less_equal)
466 COMPARE_WEAK_FUNCTIONAL(>=, std::greater_equal)
467
468 template<typename U>
469 inline bool operator == (const wp<U>& o) const {
470 return m_refs == o.m_refs; // Implies m_ptr == o.mptr; see invariants below.
471 }
472
473 template<typename U>
474 inline bool operator == (const sp<U>& o) const {
475 // Just comparing m_ptr fields is often dangerous, since wp<> may refer to an older
476 // object at the same address.
477 if (o == nullptr) {
478 return m_ptr == nullptr;
479 } else {
480 return m_refs == o->getWeakRefs(); // Implies m_ptr == o.mptr.
481 }
482 }
483
484 template<typename U>
485 inline bool operator != (const sp<U>& o) const {
486 return !(*this == o);
487 }
488
489 template<typename U>
490 inline bool operator > (const wp<U>& o) const {
491 if (m_ptr == o.m_ptr) {
492 return _wp_compare_<std::greater>(m_refs, o.m_refs);
493 } else {
494 return _wp_compare_<std::greater>(m_ptr, o.m_ptr);
495 }
496 }
497
498 template<typename U>
499 inline bool operator < (const wp<U>& o) const {
500 if (m_ptr == o.m_ptr) {
501 return _wp_compare_<std::less>(m_refs, o.m_refs);
502 } else {
503 return _wp_compare_<std::less>(m_ptr, o.m_ptr);
504 }
505 }
506 template<typename U> inline bool operator != (const wp<U>& o) const { return !operator == (o); }
507 template<typename U> inline bool operator <= (const wp<U>& o) const { return !operator > (o); }
508 template<typename U> inline bool operator >= (const wp<U>& o) const { return !operator < (o); }
509
510 private:
511 template<typename Y> friend class sp;
512 template<typename Y> friend class wp;
513
514 T* m_ptr;
515 weakref_type* m_refs;
516 };
517
518 #undef COMPARE_WEAK
519 #undef COMPARE_WEAK_FUNCTIONAL
520
521 // ---------------------------------------------------------------------------
522 // No user serviceable parts below here.
523
524 // Implementation invariants:
525 // Either
526 // 1) m_ptr and m_refs are both null, or
527 // 2) m_refs == m_ptr->mRefs, or
528 // 3) *m_ptr is no longer live, and m_refs points to the weakref_type object that corresponded
529 // to m_ptr while it was live. *m_refs remains live while a wp<> refers to it.
530 //
531 // The m_refs field in a RefBase object is allocated on construction, unique to that RefBase
532 // object, and never changes. Thus if two wp's have identical m_refs fields, they are either both
533 // null or point to the same object. If two wp's have identical m_ptr fields, they either both
534 // point to the same live object and thus have the same m_ref fields, or at least one of the
535 // objects is no longer live.
536 //
537 // Note that the above comparison operations go out of their way to provide an ordering consistent
538 // with ordinary pointer comparison; otherwise they could ignore m_ptr, and just compare m_refs.
539
540 template <typename T>
fromExisting(T * other)541 wp<T> wp<T>::fromExisting(T* other) {
542 if (!other) return nullptr;
543
544 auto refs = other->getWeakRefs();
545 refs->incWeakRequireWeak(other);
546
547 wp<T> ret;
548 ret.m_ptr = other;
549 ret.m_refs = refs;
550 return ret;
551 }
552
553 #if !defined(ANDROID_UTILS_REF_BASE_DISABLE_IMPLICIT_CONSTRUCTION)
554 template<typename T>
wp(T * other)555 wp<T>::wp(T* other)
556 : m_ptr(other)
557 {
558 m_refs = other ? other->createWeak(this) : nullptr;
559 }
560
561 template <typename T>
562 template <typename U>
wp(U * other)563 wp<T>::wp(U* other) : m_ptr(other) {
564 m_refs = other ? other->createWeak(this) : nullptr;
565 }
566
567 template <typename T>
568 wp<T>& wp<T>::operator=(T* other) {
569 weakref_type* newRefs = other ? other->createWeak(this) : nullptr;
570 if (m_ptr) m_refs->decWeak(this);
571 m_ptr = other;
572 m_refs = newRefs;
573 return *this;
574 }
575
576 template <typename T>
577 template <typename U>
578 wp<T>& wp<T>::operator=(U* other) {
579 weakref_type* newRefs = other ? other->createWeak(this) : 0;
580 if (m_ptr) m_refs->decWeak(this);
581 m_ptr = other;
582 m_refs = newRefs;
583 return *this;
584 }
585 #endif
586
587 template<typename T>
wp(const wp<T> & other)588 wp<T>::wp(const wp<T>& other)
589 : m_ptr(other.m_ptr), m_refs(other.m_refs)
590 {
591 if (m_ptr) m_refs->incWeak(this);
592 }
593
594 template<typename T>
wp(const sp<T> & other)595 wp<T>::wp(const sp<T>& other)
596 : m_ptr(other.m_ptr)
597 {
598 m_refs = m_ptr ? m_ptr->createWeak(this) : nullptr;
599 }
600
601 template<typename T> template<typename U>
wp(const wp<U> & other)602 wp<T>::wp(const wp<U>& other)
603 : m_ptr(other.m_ptr)
604 {
605 if (m_ptr) {
606 m_refs = other.m_refs;
607 m_refs->incWeak(this);
608 } else {
609 m_refs = nullptr;
610 }
611 }
612
613 template<typename T> template<typename U>
wp(const sp<U> & other)614 wp<T>::wp(const sp<U>& other)
615 : m_ptr(other.m_ptr)
616 {
617 m_refs = m_ptr ? m_ptr->createWeak(this) : nullptr;
618 }
619
620 template<typename T>
~wp()621 wp<T>::~wp()
622 {
623 if (m_ptr) m_refs->decWeak(this);
624 }
625
626 template<typename T>
627 wp<T>& wp<T>::operator = (const wp<T>& other)
628 {
629 weakref_type* otherRefs(other.m_refs);
630 T* otherPtr(other.m_ptr);
631 if (otherPtr) otherRefs->incWeak(this);
632 if (m_ptr) m_refs->decWeak(this);
633 m_ptr = otherPtr;
634 m_refs = otherRefs;
635 return *this;
636 }
637
638 template<typename T>
639 wp<T>& wp<T>::operator = (const sp<T>& other)
640 {
641 weakref_type* newRefs =
642 other != nullptr ? other->createWeak(this) : nullptr;
643 T* otherPtr(other.m_ptr);
644 if (m_ptr) m_refs->decWeak(this);
645 m_ptr = otherPtr;
646 m_refs = newRefs;
647 return *this;
648 }
649
650 template<typename T> template<typename U>
651 wp<T>& wp<T>::operator = (const wp<U>& other)
652 {
653 weakref_type* otherRefs(other.m_refs);
654 U* otherPtr(other.m_ptr);
655 if (otherPtr) otherRefs->incWeak(this);
656 if (m_ptr) m_refs->decWeak(this);
657 m_ptr = otherPtr;
658 m_refs = otherRefs;
659 return *this;
660 }
661
662 template<typename T> template<typename U>
663 wp<T>& wp<T>::operator = (const sp<U>& other)
664 {
665 weakref_type* newRefs = other != nullptr ? other->createWeak(this) : nullptr;
666 U* otherPtr(other.m_ptr);
667 if (m_ptr) m_refs->decWeak(this);
668 m_ptr = otherPtr;
669 m_refs = newRefs;
670 return *this;
671 }
672
673 template<typename T>
set_object_and_refs(T * other,weakref_type * refs)674 void wp<T>::set_object_and_refs(T* other, weakref_type* refs)
675 {
676 if (other) refs->incWeak(this);
677 if (m_ptr) m_refs->decWeak(this);
678 m_ptr = other;
679 m_refs = refs;
680 }
681
682 template<typename T>
promote()683 sp<T> wp<T>::promote() const
684 {
685 sp<T> result;
686 if (m_ptr && m_refs->attemptIncStrong(&result)) {
687 result.set_pointer(m_ptr);
688 }
689 return result;
690 }
691
692 template<typename T>
clear()693 void wp<T>::clear()
694 {
695 if (m_ptr) {
696 m_refs->decWeak(this);
697 m_refs = nullptr;
698 m_ptr = nullptr;
699 }
700 }
701
702 // ---------------------------------------------------------------------------
703
704 // this class just serves as a namespace so TYPE::moveReferences can stay
705 // private.
706 class ReferenceMover {
707 public:
708 // it would be nice if we could make sure no extra code is generated
709 // for sp<TYPE> or wp<TYPE> when TYPE is a descendant of RefBase:
710 // Using a sp<RefBase> override doesn't work; it's a bit like we wanted
711 // a template<typename TYPE inherits RefBase> template...
712
713 template<typename TYPE> static inline
move_references(sp<TYPE> * dest,sp<TYPE> const * src,size_t n)714 void move_references(sp<TYPE>* dest, sp<TYPE> const* src, size_t n) {
715
716 class Renamer : public ReferenceRenamer {
717 sp<TYPE>* d_;
718 sp<TYPE> const* s_;
719 virtual void operator()(size_t i) const {
720 // The id are known to be the sp<>'s this pointer
721 TYPE::renameRefId(d_[i].get(), &s_[i], &d_[i]);
722 }
723 public:
724 Renamer(sp<TYPE>* d, sp<TYPE> const* s) : d_(d), s_(s) { }
725 virtual ~Renamer() { }
726 };
727
728 memmove(dest, src, n*sizeof(sp<TYPE>));
729 TYPE::renameRefs(n, Renamer(dest, src));
730 }
731
732
733 template<typename TYPE> static inline
move_references(wp<TYPE> * dest,wp<TYPE> const * src,size_t n)734 void move_references(wp<TYPE>* dest, wp<TYPE> const* src, size_t n) {
735
736 class Renamer : public ReferenceRenamer {
737 wp<TYPE>* d_;
738 wp<TYPE> const* s_;
739 virtual void operator()(size_t i) const {
740 // The id are known to be the wp<>'s this pointer
741 TYPE::renameRefId(d_[i].get_refs(), &s_[i], &d_[i]);
742 }
743 public:
744 Renamer(wp<TYPE>* rd, wp<TYPE> const* rs) : d_(rd), s_(rs) { }
745 virtual ~Renamer() { }
746 };
747
748 memmove(dest, src, n*sizeof(wp<TYPE>));
749 TYPE::renameRefs(n, Renamer(dest, src));
750 }
751 };
752
753 // specialization for moving sp<> and wp<> types.
754 // these are used by the [Sorted|Keyed]Vector<> implementations
755 // sp<> and wp<> need to be handled specially, because they do not
756 // have trivial copy operation in the general case (see RefBase.cpp
757 // when DEBUG ops are enabled), but can be implemented very
758 // efficiently in most cases.
759
760 template<typename TYPE> inline
move_forward_type(sp<TYPE> * d,sp<TYPE> const * s,size_t n)761 void move_forward_type(sp<TYPE>* d, sp<TYPE> const* s, size_t n) {
762 ReferenceMover::move_references(d, s, n);
763 }
764
765 template<typename TYPE> inline
move_backward_type(sp<TYPE> * d,sp<TYPE> const * s,size_t n)766 void move_backward_type(sp<TYPE>* d, sp<TYPE> const* s, size_t n) {
767 ReferenceMover::move_references(d, s, n);
768 }
769
770 template<typename TYPE> inline
move_forward_type(wp<TYPE> * d,wp<TYPE> const * s,size_t n)771 void move_forward_type(wp<TYPE>* d, wp<TYPE> const* s, size_t n) {
772 ReferenceMover::move_references(d, s, n);
773 }
774
775 template<typename TYPE> inline
move_backward_type(wp<TYPE> * d,wp<TYPE> const * s,size_t n)776 void move_backward_type(wp<TYPE>* d, wp<TYPE> const* s, size_t n) {
777 ReferenceMover::move_references(d, s, n);
778 }
779
780 } // namespace android
781
782 namespace libutilsinternal {
783 template <typename T, typename = void>
784 struct is_complete_type : std::false_type {};
785
786 template <typename T>
787 struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {};
788 } // namespace libutilsinternal
789
790 namespace std {
791
792 // Define `RefBase` specific versions of `std::make_shared` and
793 // `std::make_unique` to block people from using them. Using them to allocate
794 // `RefBase` objects results in double ownership. Use
795 // `sp<T>::make(...)` instead.
796 //
797 // Note: We exclude incomplete types because `std::is_base_of` is undefined in
798 // that case.
799
800 template <typename T, typename... Args,
801 typename std::enable_if<libutilsinternal::is_complete_type<T>::value, bool>::value = true,
802 typename std::enable_if<std::is_base_of<android::RefBase, T>::value, bool>::value = true>
803 shared_ptr<T> make_shared(Args...) { // SEE COMMENT ABOVE.
804 static_assert(!std::is_base_of<android::RefBase, T>::value, "Must use RefBase with sp<>");
805 }
806
807 template <typename T, typename... Args,
808 typename std::enable_if<libutilsinternal::is_complete_type<T>::value, bool>::value = true,
809 typename std::enable_if<std::is_base_of<android::RefBase, T>::value, bool>::value = true>
810 unique_ptr<T> make_unique(Args...) { // SEE COMMENT ABOVE.
811 static_assert(!std::is_base_of<android::RefBase, T>::value, "Must use RefBase with sp<>");
812 }
813
814 } // namespace std
815
816 // ---------------------------------------------------------------------------
817
818 #endif // ANDROID_REF_BASE_H
819