• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 #ifndef ANDROID_STRONG_POINTER_H
18 #define ANDROID_STRONG_POINTER_H
19 
20 #include <functional>
21 #include <type_traits>  // for common_type.
22 
23 // ---------------------------------------------------------------------------
24 namespace android {
25 
26 template<typename T> class wp;
27 
28 // ---------------------------------------------------------------------------
29 
30 template<typename T>
31 class sp {
32 public:
sp()33     inline sp() : m_ptr(nullptr) { }
34 
35     // The old way of using sp<> was like this. This is bad because it relies
36     // on implicit conversion to sp<>, which we would like to remove (if an
37     // object is being managed some other way, this is double-ownership). We
38     // want to move away from this:
39     //
40     //     sp<Foo> foo = new Foo(...); // DO NOT DO THIS
41     //
42     // Instead, prefer to do this:
43     //
44     //     sp<Foo> foo = sp<Foo>::make(...); // DO THIS
45     //
46     // Sometimes, in order to use this, when a constructor is marked as private,
47     // you may need to add this to your class:
48     //
49     //     friend class sp<Foo>;
50     template <typename... Args>
51     static inline sp<T> make(Args&&... args);
52 
53     // if nullptr, returns nullptr
54     //
55     // if a strong pointer is already available, this will retrieve it,
56     // otherwise, this will abort
57     static inline sp<T> fromExisting(T* other);
58 
59     // for more information about this macro and correct RefBase usage, see
60     // the comment at the top of utils/RefBase.h
61 #if defined(ANDROID_UTILS_REF_BASE_DISABLE_IMPLICIT_CONSTRUCTION)
sp(std::nullptr_t)62     sp(std::nullptr_t) : sp() {}
63 #else
64     sp(T* other);  // NOLINT(implicit)
65     template <typename U>
66     sp(U* other);  // NOLINT(implicit)
67     sp& operator=(T* other);
68     template <typename U>
69     sp& operator=(U* other);
70 #endif
71 
72     sp(const sp<T>& other);
73     sp(sp<T>&& other) noexcept;
74 
75     template<typename U> sp(const sp<U>& other);  // NOLINT(implicit)
76     template<typename U> sp(sp<U>&& other);  // NOLINT(implicit)
77 
78     // Cast a strong pointer directly from one type to another. Constructors
79     // allow changing types, but only if they are pointer-compatible. This does
80     // a static_cast internally.
81     template <typename U>
82     static inline sp<T> cast(const sp<U>& other);
83 
84     ~sp();
85 
86     // Assignment
87 
88     sp& operator = (const sp<T>& other);
89     sp& operator=(sp<T>&& other) noexcept;
90 
91     template<typename U> sp& operator = (const sp<U>& other);
92     template<typename U> sp& operator = (sp<U>&& other);
93 
94     //! Special optimization for use by ProcessState (and nobody else).
95     void force_set(T* other);
96 
97     // Reset
98 
99     void clear();
100 
101     // Accessors
102 
103     inline T&       operator* () const     { return *m_ptr; }
104     inline T*       operator-> () const    { return m_ptr;  }
get()105     inline T*       get() const            { return m_ptr; }
106     inline explicit operator bool () const { return m_ptr != nullptr; }
107 
108     // Punt these to the wp<> implementation.
109     template<typename U>
110     inline bool operator == (const wp<U>& o) const {
111         return o == *this;
112     }
113 
114     template<typename U>
115     inline bool operator != (const wp<U>& o) const {
116         return o != *this;
117     }
118 
119 private:
120     template<typename Y> friend class sp;
121     template<typename Y> friend class wp;
122     void set_pointer(T* ptr);
123     static inline void check_not_on_stack(const void* ptr);
124     T* m_ptr;
125 };
126 
127 #define COMPARE_STRONG(_op_)                                           \
128     template <typename T, typename U>                                  \
129     static inline bool operator _op_(const sp<T>& t, const sp<U>& u) { \
130         return t.get() _op_ u.get();                                   \
131     }                                                                  \
132     template <typename T, typename U>                                  \
133     static inline bool operator _op_(const T* t, const sp<U>& u) {     \
134         return t _op_ u.get();                                         \
135     }                                                                  \
136     template <typename T, typename U>                                  \
137     static inline bool operator _op_(const sp<T>& t, const U* u) {     \
138         return t.get() _op_ u;                                         \
139     }                                                                  \
140     template <typename T>                                              \
141     static inline bool operator _op_(const sp<T>& t, std::nullptr_t) { \
142         return t.get() _op_ nullptr;                                   \
143     }                                                                  \
144     template <typename T>                                              \
145     static inline bool operator _op_(std::nullptr_t, const sp<T>& t) { \
146         return nullptr _op_ t.get();                                   \
147     }
148 
149 template <template <typename C> class comparator, typename T, typename U>
_sp_compare_(T * a,U * b)150 static inline bool _sp_compare_(T* a, U* b) {
151     return comparator<typename std::common_type<T*, U*>::type>()(a, b);
152 }
153 
154 #define COMPARE_STRONG_FUNCTIONAL(_op_, _compare_)                     \
155     template <typename T, typename U>                                  \
156     static inline bool operator _op_(const sp<T>& t, const sp<U>& u) { \
157         return _sp_compare_<_compare_>(t.get(), u.get());              \
158     }                                                                  \
159     template <typename T, typename U>                                  \
160     static inline bool operator _op_(const T* t, const sp<U>& u) {     \
161         return _sp_compare_<_compare_>(t, u.get());                    \
162     }                                                                  \
163     template <typename T, typename U>                                  \
164     static inline bool operator _op_(const sp<T>& t, const U* u) {     \
165         return _sp_compare_<_compare_>(t.get(), u);                    \
166     }                                                                  \
167     template <typename T>                                              \
168     static inline bool operator _op_(const sp<T>& t, std::nullptr_t) { \
169         return _sp_compare_<_compare_>(t.get(), nullptr);              \
170     }                                                                  \
171     template <typename T>                                              \
172     static inline bool operator _op_(std::nullptr_t, const sp<T>& t) { \
173         return _sp_compare_<_compare_>(nullptr, t.get());              \
174     }
175 
176 COMPARE_STRONG(==)
177 COMPARE_STRONG(!=)
178 COMPARE_STRONG_FUNCTIONAL(>, std::greater)
179 COMPARE_STRONG_FUNCTIONAL(<, std::less)
180 COMPARE_STRONG_FUNCTIONAL(<=, std::less_equal)
181 COMPARE_STRONG_FUNCTIONAL(>=, std::greater_equal)
182 
183 #undef COMPARE_STRONG
184 #undef COMPARE_STRONG_FUNCTIONAL
185 
186 // For code size reasons, we do not want these inlined or templated.
187 void sp_report_race();
188 void sp_report_stack_pointer();
189 
190 // ---------------------------------------------------------------------------
191 // No user serviceable parts below here.
192 
193 // Check whether address is definitely on the calling stack.  We actually check whether it is on
194 // the same 4K page as the frame pointer.
195 //
196 // Assumptions:
197 // - Pages are never smaller than 4K (MIN_PAGE_SIZE)
198 // - Malloced memory never shares a page with a stack.
199 //
200 // It does not appear safe to broaden this check to include adjacent pages; apparently this code
201 // is used in environments where there may not be a guard page below (at higher addresses than)
202 // the bottom of the stack.
203 template <typename T>
check_not_on_stack(const void * ptr)204 void sp<T>::check_not_on_stack(const void* ptr) {
205     static constexpr int MIN_PAGE_SIZE = 0x1000;  // 4K. Safer than including sys/user.h.
206     static constexpr uintptr_t MIN_PAGE_MASK = ~static_cast<uintptr_t>(MIN_PAGE_SIZE - 1);
207     uintptr_t my_frame_address =
208             reinterpret_cast<uintptr_t>(__builtin_frame_address(0 /* this frame */));
209     if (((reinterpret_cast<uintptr_t>(ptr) ^ my_frame_address) & MIN_PAGE_MASK) == 0) {
210         sp_report_stack_pointer();
211     }
212 }
213 
214 // TODO: Ideally we should find a way to increment the reference count before running the
215 // constructor, so that generating an sp<> to this in the constructor is no longer dangerous.
216 template <typename T>
217 template <typename... Args>
make(Args &&...args)218 sp<T> sp<T>::make(Args&&... args) {
219     T* t = new T(std::forward<Args>(args)...);
220     sp<T> result;
221     result.m_ptr = t;
222     t->incStrong(t);  // bypass check_not_on_stack for heap allocation
223     return result;
224 }
225 
226 template <typename T>
fromExisting(T * other)227 sp<T> sp<T>::fromExisting(T* other) {
228     if (other) {
229         check_not_on_stack(other);
230         other->incStrongRequireStrong(other);
231         sp<T> result;
232         result.m_ptr = other;
233         return result;
234     }
235     return nullptr;
236 }
237 
238 #if !defined(ANDROID_UTILS_REF_BASE_DISABLE_IMPLICIT_CONSTRUCTION)
239 template<typename T>
sp(T * other)240 sp<T>::sp(T* other)
241         : m_ptr(other) {
242     if (other) {
243         check_not_on_stack(other);
244         other->incStrong(this);
245     }
246 }
247 
248 template <typename T>
249 template <typename U>
sp(U * other)250 sp<T>::sp(U* other) : m_ptr(other) {
251     if (other) {
252         check_not_on_stack(other);
253         (static_cast<T*>(other))->incStrong(this);
254     }
255 }
256 
257 template <typename T>
258 sp<T>& sp<T>::operator=(T* other) {
259     T* oldPtr(*const_cast<T* volatile*>(&m_ptr));
260     if (other) {
261         check_not_on_stack(other);
262         other->incStrong(this);
263     }
264     if (oldPtr) oldPtr->decStrong(this);
265     if (oldPtr != *const_cast<T* volatile*>(&m_ptr)) sp_report_race();
266     m_ptr = other;
267     return *this;
268 }
269 #endif
270 
271 template<typename T>
sp(const sp<T> & other)272 sp<T>::sp(const sp<T>& other)
273         : m_ptr(other.m_ptr) {
274     if (m_ptr)
275         m_ptr->incStrong(this);
276 }
277 
278 template <typename T>
sp(sp<T> && other)279 sp<T>::sp(sp<T>&& other) noexcept : m_ptr(other.m_ptr) {
280     other.m_ptr = nullptr;
281 }
282 
283 template<typename T> template<typename U>
sp(const sp<U> & other)284 sp<T>::sp(const sp<U>& other)
285         : m_ptr(other.m_ptr) {
286     if (m_ptr)
287         m_ptr->incStrong(this);
288 }
289 
290 template<typename T> template<typename U>
sp(sp<U> && other)291 sp<T>::sp(sp<U>&& other)
292         : m_ptr(other.m_ptr) {
293     other.m_ptr = nullptr;
294 }
295 
296 template <typename T>
297 template <typename U>
cast(const sp<U> & other)298 sp<T> sp<T>::cast(const sp<U>& other) {
299     return sp<T>::fromExisting(static_cast<T*>(other.get()));
300 }
301 
302 template<typename T>
~sp()303 sp<T>::~sp() {
304     if (m_ptr)
305         m_ptr->decStrong(this);
306 }
307 
308 template<typename T>
309 sp<T>& sp<T>::operator =(const sp<T>& other) {
310     // Force m_ptr to be read twice, to heuristically check for data races.
311     T* oldPtr(*const_cast<T* volatile*>(&m_ptr));
312     T* otherPtr(other.m_ptr);
313     if (otherPtr) otherPtr->incStrong(this);
314     if (oldPtr) oldPtr->decStrong(this);
315     if (oldPtr != *const_cast<T* volatile*>(&m_ptr)) sp_report_race();
316     m_ptr = otherPtr;
317     return *this;
318 }
319 
320 template <typename T>
321 sp<T>& sp<T>::operator=(sp<T>&& other) noexcept {
322     T* oldPtr(*const_cast<T* volatile*>(&m_ptr));
323     if (oldPtr) oldPtr->decStrong(this);
324     if (oldPtr != *const_cast<T* volatile*>(&m_ptr)) sp_report_race();
325     m_ptr = other.m_ptr;
326     other.m_ptr = nullptr;
327     return *this;
328 }
329 
330 template<typename T> template<typename U>
331 sp<T>& sp<T>::operator =(const sp<U>& other) {
332     T* oldPtr(*const_cast<T* volatile*>(&m_ptr));
333     T* otherPtr(other.m_ptr);
334     if (otherPtr) otherPtr->incStrong(this);
335     if (oldPtr) oldPtr->decStrong(this);
336     if (oldPtr != *const_cast<T* volatile*>(&m_ptr)) sp_report_race();
337     m_ptr = otherPtr;
338     return *this;
339 }
340 
341 template<typename T> template<typename U>
342 sp<T>& sp<T>::operator =(sp<U>&& other) {
343     T* oldPtr(*const_cast<T* volatile*>(&m_ptr));
344     if (m_ptr) m_ptr->decStrong(this);
345     if (oldPtr != *const_cast<T* volatile*>(&m_ptr)) sp_report_race();
346     m_ptr = other.m_ptr;
347     other.m_ptr = nullptr;
348     return *this;
349 }
350 
351 #if !defined(ANDROID_UTILS_REF_BASE_DISABLE_IMPLICIT_CONSTRUCTION)
352 template<typename T> template<typename U>
353 sp<T>& sp<T>::operator =(U* other) {
354     T* oldPtr(*const_cast<T* volatile*>(&m_ptr));
355     if (other) (static_cast<T*>(other))->incStrong(this);
356     if (oldPtr) oldPtr->decStrong(this);
357     if (oldPtr != *const_cast<T* volatile*>(&m_ptr)) sp_report_race();
358     m_ptr = other;
359     return *this;
360 }
361 #endif
362 
363 template<typename T>
force_set(T * other)364 void sp<T>::force_set(T* other) {
365     other->forceIncStrong(this);
366     m_ptr = other;
367 }
368 
369 template<typename T>
clear()370 void sp<T>::clear() {
371     T* oldPtr(*const_cast<T* volatile*>(&m_ptr));
372     if (oldPtr) {
373         oldPtr->decStrong(this);
374         if (oldPtr != *const_cast<T* volatile*>(&m_ptr)) sp_report_race();
375         m_ptr = nullptr;
376     }
377 }
378 
379 template<typename T>
set_pointer(T * ptr)380 void sp<T>::set_pointer(T* ptr) {
381     m_ptr = ptr;
382 }
383 
384 }  // namespace android
385 
386 // ---------------------------------------------------------------------------
387 
388 #endif // ANDROID_STRONG_POINTER_H
389