1 // COPY OF RefBase.h from system/core/libutils/include/utils.
2 /*
3  * Copyright (C) 2013 The Android Open Source Project
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 
18 #ifndef RS_REF_BASE_H
19 #define RS_REF_BASE_H
20 
21 
22 #include <stdint.h>
23 #include <sys/types.h>
24 #include <stdlib.h>
25 #include <string.h>
26 
27 #include "StrongPointer.h"
28 #include "TypeHelpers.h"
29 
30 // ---------------------------------------------------------------------------
31 namespace android{
32 namespace RSC {
33 
34 class TextOutput;
35 TextOutput& printWeakPointer(TextOutput& to, const void* val);
36 
37 // ---------------------------------------------------------------------------
38 
39 #define COMPARE_WEAK(_op_)                                      \
40 inline bool operator _op_ (const sp<T>& o) const {              \
41     return m_ptr _op_ o.m_ptr;                                  \
42 }                                                               \
43 inline bool operator _op_ (const T* o) const {                  \
44     return m_ptr _op_ o;                                        \
45 }                                                               \
46 template<typename U>                                            \
47 inline bool operator _op_ (const sp<U>& o) const {              \
48     return m_ptr _op_ o.m_ptr;                                  \
49 }                                                               \
50 template<typename U>                                            \
51 inline bool operator _op_ (const U* o) const {                  \
52     return m_ptr _op_ o;                                        \
53 }
54 
55 // ---------------------------------------------------------------------------
56 class ReferenceMover;
57 class ReferenceConverterBase {
58 public:
59     virtual size_t getReferenceTypeSize() const = 0;
60     virtual void* getReferenceBase(void const*) const = 0;
~ReferenceConverterBase()61     inline virtual ~ReferenceConverterBase() { }
62 };
63 
64 // ---------------------------------------------------------------------------
65 
66 class RefBase
67 {
68 public:
69             void            incStrong(const void* id) const;
70             void            decStrong(const void* id) const;
71 
72             void            forceIncStrong(const void* id) const;
73 
74             //! DEBUGGING ONLY: Get current strong ref count.
75             int32_t         getStrongCount() const;
76 
77     class weakref_type
78     {
79     public:
80         RefBase*            refBase() const;
81 
82         void                incWeak(const void* id);
83         void                decWeak(const void* id);
84 
85         // acquires a strong reference if there is already one.
86         bool                attemptIncStrong(const void* id);
87 
88         // acquires a weak reference if there is already one.
89         // This is not always safe. see ProcessState.cpp and BpBinder.cpp
90         // for proper use.
91         bool                attemptIncWeak(const void* id);
92 
93         //! DEBUGGING ONLY: Get current weak ref count.
94         int32_t             getWeakCount() const;
95 
96         //! DEBUGGING ONLY: Print references held on object.
97         void                printRefs() const;
98 
99         //! DEBUGGING ONLY: Enable tracking for this object.
100         // enable -- enable/disable tracking
101         // retain -- when tracking is enable, if true, then we save a stack trace
102         //           for each reference and dereference; when retain == false, we
103         //           match up references and dereferences and keep only the
104         //           outstanding ones.
105 
106         void                trackMe(bool enable, bool retain);
107     };
108 
109             weakref_type*   createWeak(const void* id) const;
110 
111             weakref_type*   getWeakRefs() const;
112 
113             //! DEBUGGING ONLY: Print references held on object.
printRefs()114     inline  void            printRefs() const { getWeakRefs()->printRefs(); }
115 
116             //! DEBUGGING ONLY: Enable tracking of object.
trackMe(bool enable,bool retain)117     inline  void            trackMe(bool enable, bool retain)
118     {
119         getWeakRefs()->trackMe(enable, retain);
120     }
121 
122     typedef RefBase basetype;
123 
124 protected:
125                             RefBase();
126     virtual                 ~RefBase();
127 
128     //! Flags for extendObjectLifetime()
129     enum {
130         OBJECT_LIFETIME_STRONG  = 0x0000,
131         OBJECT_LIFETIME_WEAK    = 0x0001,
132         OBJECT_LIFETIME_MASK    = 0x0001
133     };
134 
135             void            extendObjectLifetime(int32_t mode);
136 
137     //! Flags for onIncStrongAttempted()
138     enum {
139         FIRST_INC_STRONG = 0x0001
140     };
141 
142     virtual void            onFirstRef();
143     virtual void            onLastStrongRef(const void* id);
144     virtual bool            onIncStrongAttempted(uint32_t flags, const void* id);
145     virtual void            onLastWeakRef(const void* id);
146 
147 private:
148     friend class ReferenceMover;
149     static void moveReferences(void* d, void const* s, size_t n,
150             const ReferenceConverterBase& caster);
151 
152 private:
153     friend class weakref_type;
154     class weakref_impl;
155 
156                             RefBase(const RefBase& o);
157             RefBase&        operator=(const RefBase& o);
158 
159         weakref_impl* const mRefs;
160 };
161 
162 // ---------------------------------------------------------------------------
163 
164 template <class T>
165 class LightRefBase
166 {
167 public:
LightRefBase()168     inline LightRefBase() : mCount(0) { }
incStrong(const void * id)169     inline void incStrong(__attribute__((unused)) const void* id) const {
170         __sync_fetch_and_add(&mCount, 1);
171     }
decStrong(const void * id)172     inline void decStrong(__attribute__((unused)) const void* id) const {
173         if (__sync_fetch_and_sub(&mCount, 1) == 1) {
174             delete static_cast<const T*>(this);
175         }
176     }
177     //! DEBUGGING ONLY: Get current strong ref count.
getStrongCount()178     inline int32_t getStrongCount() const {
179         return mCount;
180     }
181 
182     typedef LightRefBase<T> basetype;
183 
184 protected:
~LightRefBase()185     inline ~LightRefBase() { }
186 
187 private:
188     friend class ReferenceMover;
moveReferences(void *,void const *,size_t,const ReferenceConverterBase &)189     inline static void moveReferences(void*, void const*, size_t,
190             const ReferenceConverterBase&) { }
191 
192 private:
193     mutable volatile int32_t mCount;
194 };
195 
196 // ---------------------------------------------------------------------------
197 
198 template <typename T>
199 class wp
200 {
201 public:
202     typedef typename RefBase::weakref_type weakref_type;
203 
wp()204     inline wp() : m_ptr(0) { }
205 
206     explicit wp(T* other);
207     wp(const wp<T>& other);
208     explicit wp(const sp<T>& other);
209     template<typename U> explicit wp(U* other);
210     template<typename U> explicit wp(const sp<U>& other);
211     template<typename U> explicit wp(const wp<U>& other);
212 
213     ~wp();
214 
215     // Assignment
216 
217     wp& operator = (T* other);
218     wp& operator = (const wp<T>& other);
219     wp& operator = (const sp<T>& other);
220 
221     template<typename U> wp& operator = (U* other);
222     template<typename U> wp& operator = (const wp<U>& other);
223     template<typename U> wp& operator = (const sp<U>& other);
224 
225     void set_object_and_refs(T* other, weakref_type* refs);
226 
227     // promotion to sp
228 
229     sp<T> promote() const;
230 
231     // Reset
232 
233     void clear();
234 
235     // Accessors
236 
get_refs()237     inline  weakref_type* get_refs() const { return m_refs; }
238 
unsafe_get()239     inline  T* unsafe_get() const { return m_ptr; }
240 
241     // Operators
242 
243     COMPARE_WEAK(==)
244     COMPARE_WEAK(!=)
245     COMPARE_WEAK(>)
246     COMPARE_WEAK(<)
247     COMPARE_WEAK(<=)
248     COMPARE_WEAK(>=)
249 
250     inline bool operator == (const wp<T>& o) const {
251         return (m_ptr == o.m_ptr) && (m_refs == o.m_refs);
252     }
253     template<typename U>
254     inline bool operator == (const wp<U>& o) const {
255         return m_ptr == o.m_ptr;
256     }
257 
258     inline bool operator > (const wp<T>& o) const {
259         return (m_ptr == o.m_ptr) ? (m_refs > o.m_refs) : (m_ptr > o.m_ptr);
260     }
261     template<typename U>
262     inline bool operator > (const wp<U>& o) const {
263         return (m_ptr == o.m_ptr) ? (m_refs > o.m_refs) : (m_ptr > o.m_ptr);
264     }
265 
266     inline bool operator < (const wp<T>& o) const {
267         return (m_ptr == o.m_ptr) ? (m_refs < o.m_refs) : (m_ptr < o.m_ptr);
268     }
269     template<typename U>
270     inline bool operator < (const wp<U>& o) const {
271         return (m_ptr == o.m_ptr) ? (m_refs < o.m_refs) : (m_ptr < o.m_ptr);
272     }
273                          inline bool operator != (const wp<T>& o) const { return m_refs != o.m_refs; }
274     template<typename U> inline bool operator != (const wp<U>& o) const { return !operator == (o); }
275                          inline bool operator <= (const wp<T>& o) const { return !operator > (o); }
276     template<typename U> inline bool operator <= (const wp<U>& o) const { return !operator > (o); }
277                          inline bool operator >= (const wp<T>& o) const { return !operator < (o); }
278     template<typename U> inline bool operator >= (const wp<U>& o) const { return !operator < (o); }
279 
280 private:
281     template<typename Y> friend class sp;
282     template<typename Y> friend class wp;
283 
284     T*              m_ptr;
285     weakref_type*   m_refs;
286 };
287 
288 template <typename T>
289 TextOutput& operator<<(TextOutput& to, const wp<T>& val);
290 
291 #undef COMPARE_WEAK
292 
293 // ---------------------------------------------------------------------------
294 // No user serviceable parts below here.
295 
296 template<typename T>
wp(T * other)297 wp<T>::wp(T* other)
298     : m_ptr(other)
299 {
300     if (other) m_refs = other->createWeak(this);
301 }
302 
303 template<typename T>
wp(const wp<T> & other)304 wp<T>::wp(const wp<T>& other)
305     : m_ptr(other.m_ptr), m_refs(other.m_refs)
306 {
307     if (m_ptr) m_refs->incWeak(this);
308 }
309 
310 template<typename T>
wp(const sp<T> & other)311 wp<T>::wp(const sp<T>& other)
312     : m_ptr(other.m_ptr)
313 {
314     if (m_ptr) {
315         m_refs = m_ptr->createWeak(this);
316     }
317 }
318 
319 template<typename T> template<typename U>
wp(U * other)320 wp<T>::wp(U* other)
321     : m_ptr(other)
322 {
323     if (other) m_refs = other->createWeak(this);
324 }
325 
326 template<typename T> template<typename U>
wp(const wp<U> & other)327 wp<T>::wp(const wp<U>& other)
328     : m_ptr(other.m_ptr)
329 {
330     if (m_ptr) {
331         m_refs = other.m_refs;
332         m_refs->incWeak(this);
333     }
334 }
335 
336 template<typename T> template<typename U>
wp(const sp<U> & other)337 wp<T>::wp(const sp<U>& other)
338     : m_ptr(other.m_ptr)
339 {
340     if (m_ptr) {
341         m_refs = m_ptr->createWeak(this);
342     }
343 }
344 
345 template<typename T>
~wp()346 wp<T>::~wp()
347 {
348     if (m_ptr) m_refs->decWeak(this);
349 }
350 
351 template<typename T>
352 wp<T>& wp<T>::operator = (T* other)
353 {
354     weakref_type* newRefs =
355         other ? other->createWeak(this) : 0;
356     if (m_ptr) m_refs->decWeak(this);
357     m_ptr = other;
358     m_refs = newRefs;
359     return *this;
360 }
361 
362 template<typename T>
363 wp<T>& wp<T>::operator = (const wp<T>& other)
364 {
365     weakref_type* otherRefs(other.m_refs);
366     T* otherPtr(other.m_ptr);
367     if (otherPtr) otherRefs->incWeak(this);
368     if (m_ptr) m_refs->decWeak(this);
369     m_ptr = otherPtr;
370     m_refs = otherRefs;
371     return *this;
372 }
373 
374 template<typename T>
375 wp<T>& wp<T>::operator = (const sp<T>& other)
376 {
377     weakref_type* newRefs =
378         other != NULL ? other->createWeak(this) : NULL;
379     T* otherPtr(other.m_ptr);
380     if (m_ptr) m_refs->decWeak(this);
381     m_ptr = otherPtr;
382     m_refs = newRefs;
383     return *this;
384 }
385 
386 template<typename T> template<typename U>
387 wp<T>& wp<T>::operator = (U* other)
388 {
389     weakref_type* newRefs =
390         other ? other->createWeak(this) : NULL;
391     if (m_ptr) m_refs->decWeak(this);
392     m_ptr = other;
393     m_refs = newRefs;
394     return *this;
395 }
396 
397 template<typename T> template<typename U>
398 wp<T>& wp<T>::operator = (const wp<U>& other)
399 {
400     weakref_type* otherRefs(other.m_refs);
401     U* otherPtr(other.m_ptr);
402     if (otherPtr) otherRefs->incWeak(this);
403     if (m_ptr) m_refs->decWeak(this);
404     m_ptr = otherPtr;
405     m_refs = otherRefs;
406     return *this;
407 }
408 
409 template<typename T> template<typename U>
410 wp<T>& wp<T>::operator = (const sp<U>& other)
411 {
412     weakref_type* newRefs =
413         other != NULL ? other->createWeak(this) : NULL;
414     U* otherPtr(other.m_ptr);
415     if (m_ptr) m_refs->decWeak(this);
416     m_ptr = otherPtr;
417     m_refs = newRefs;
418     return *this;
419 }
420 
421 template<typename T>
set_object_and_refs(T * other,weakref_type * refs)422 void wp<T>::set_object_and_refs(T* other, weakref_type* refs)
423 {
424     if (other) refs->incWeak(this);
425     if (m_ptr) m_refs->decWeak(this);
426     m_ptr = other;
427     m_refs = refs;
428 }
429 
430 template<typename T>
promote()431 sp<T> wp<T>::promote() const
432 {
433     sp<T> result;
434     if (m_ptr && m_refs->attemptIncStrong(&result)) {
435         result.set_pointer(m_ptr);
436     }
437     return result;
438 }
439 
440 template<typename T>
clear()441 void wp<T>::clear()
442 {
443     if (m_ptr) {
444         m_refs->decWeak(this);
445         m_ptr = 0;
446     }
447 }
448 
449 template <typename T>
450 inline TextOutput& operator<<(TextOutput& to, const wp<T>& val)
451 {
452     return printWeakPointer(to, val.unsafe_get());
453 }
454 
455 // ---------------------------------------------------------------------------
456 
457 // this class just serves as a namespace so TYPE::moveReferences can stay
458 // private.
459 
460 class ReferenceMover {
461     // StrongReferenceCast and WeakReferenceCast do the impedance matching
462     // between the generic (void*) implementation in Refbase and the strongly typed
463     // template specializations below.
464 
465     template <typename TYPE>
466     struct StrongReferenceCast : public ReferenceConverterBase {
getReferenceTypeSizeStrongReferenceCast467         virtual size_t getReferenceTypeSize() const { return sizeof( sp<TYPE> ); }
getReferenceBaseStrongReferenceCast468         virtual void* getReferenceBase(void const* p) const {
469             sp<TYPE> const* sptr(reinterpret_cast<sp<TYPE> const*>(p));
470             return static_cast<typename TYPE::basetype *>(sptr->get());
471         }
472     };
473 
474     template <typename TYPE>
475     struct WeakReferenceCast : public ReferenceConverterBase {
getReferenceTypeSizeWeakReferenceCast476         virtual size_t getReferenceTypeSize() const { return sizeof( wp<TYPE> ); }
getReferenceBaseWeakReferenceCast477         virtual void* getReferenceBase(void const* p) const {
478             wp<TYPE> const* sptr(reinterpret_cast<wp<TYPE> const*>(p));
479             return static_cast<typename TYPE::basetype *>(sptr->unsafe_get());
480         }
481     };
482 
483 public:
484     template<typename TYPE> static inline
move_references(sp<TYPE> * d,sp<TYPE> const * s,size_t n)485     void move_references(sp<TYPE>* d, sp<TYPE> const* s, size_t n) {
486         memmove(d, s, n*sizeof(sp<TYPE>));
487         StrongReferenceCast<TYPE> caster;
488         TYPE::moveReferences(d, s, n, caster);
489     }
490     template<typename TYPE> static inline
move_references(wp<TYPE> * d,wp<TYPE> const * s,size_t n)491     void move_references(wp<TYPE>* d, wp<TYPE> const* s, size_t n) {
492         memmove(d, s, n*sizeof(wp<TYPE>));
493         WeakReferenceCast<TYPE> caster;
494         TYPE::moveReferences(d, s, n, caster);
495     }
496 };
497 
498 // specialization for moving sp<> and wp<> types.
499 // these are used by the [Sorted|Keyed]Vector<> implementations
500 // sp<> and wp<> need to be handled specially, because they do not
501 // have trivial copy operation in the general case (see RefBase.cpp
502 // when DEBUG ops are enabled), but can be implemented very
503 // efficiently in most cases.
504 
505 template<typename TYPE> inline
move_forward_type(sp<TYPE> * d,sp<TYPE> const * s,size_t n)506 void move_forward_type(sp<TYPE>* d, sp<TYPE> const* s, size_t n) {
507     ReferenceMover::move_references(d, s, n);
508 }
509 
510 template<typename TYPE> inline
move_backward_type(sp<TYPE> * d,sp<TYPE> const * s,size_t n)511 void move_backward_type(sp<TYPE>* d, sp<TYPE> const* s, size_t n) {
512     ReferenceMover::move_references(d, s, n);
513 }
514 
515 template<typename TYPE> inline
move_forward_type(wp<TYPE> * d,wp<TYPE> const * s,size_t n)516 void move_forward_type(wp<TYPE>* d, wp<TYPE> const* s, size_t n) {
517     ReferenceMover::move_references(d, s, n);
518 }
519 
520 template<typename TYPE> inline
move_backward_type(wp<TYPE> * d,wp<TYPE> const * s,size_t n)521 void move_backward_type(wp<TYPE>* d, wp<TYPE> const* s, size_t n) {
522     ReferenceMover::move_references(d, s, n);
523 }
524 
525 
526 }; // namespace RSC
527 }; // namespace android
528 // ---------------------------------------------------------------------------
529 
530 #endif // RS_REF_BASE_H
531