1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 // Weak pointers are pointers to an object that do not affect its lifetime,
6 // and which may be invalidated (i.e. reset to nullptr) by the object, or its
7 // owner, at any time, most commonly when the object is about to be deleted.
8
9 // Weak pointers are useful when an object needs to be accessed safely by one
10 // or more objects other than its owner, and those callers can cope with the
11 // object vanishing and e.g. tasks posted to it being silently dropped.
12 // Reference-counting such an object would complicate the ownership graph and
13 // make it harder to reason about the object's lifetime.
14
15 // EXAMPLE:
16 //
17 // class Controller {
18 // public:
19 // void SpawnWorker() { Worker::StartNew(weak_factory_.GetWeakPtr()); }
20 // void WorkComplete(const Result& result) { ... }
21 // private:
22 // // Member variables should appear before the WeakPtrFactory, to ensure
23 // // that any WeakPtrs to Controller are invalidated before its members
24 // // variable's destructors are executed, rendering them invalid.
25 // WeakPtrFactory<Controller> weak_factory_{this};
26 // };
27 //
28 // class Worker {
29 // public:
30 // static void StartNew(WeakPtr<Controller> controller) {
31 // // Move WeakPtr when possible to avoid atomic refcounting churn on its
32 // // internal state.
33 // Worker* worker = new Worker(std::move(controller));
34 // // Kick off asynchronous processing...
35 // }
36 // private:
37 // Worker(WeakPtr<Controller> controller)
38 // : controller_(std::move(controller)) {}
39 // void DidCompleteAsynchronousProcessing(const Result& result) {
40 // if (controller_)
41 // controller_->WorkComplete(result);
42 // }
43 // WeakPtr<Controller> controller_;
44 // };
45 //
46 // With this implementation a caller may use SpawnWorker() to dispatch multiple
47 // Workers and subsequently delete the Controller, without waiting for all
48 // Workers to have completed.
49
50 // ------------------------- IMPORTANT: Thread-safety -------------------------
51
52 // Weak pointers may be passed safely between sequences, but must always be
53 // dereferenced and invalidated on the same SequencedTaskRunner otherwise
54 // checking the pointer would be racey.
55 //
56 // To ensure correct use, the first time a WeakPtr issued by a WeakPtrFactory
57 // is dereferenced, the factory and its WeakPtrs become bound to the calling
58 // sequence or current SequencedWorkerPool token, and cannot be dereferenced or
59 // invalidated on any other task runner. Bound WeakPtrs can still be handed
60 // off to other task runners, e.g. to use to post tasks back to object on the
61 // bound sequence.
62 //
63 // If all WeakPtr objects are destroyed or invalidated then the factory is
64 // unbound from the SequencedTaskRunner/Thread. The WeakPtrFactory may then be
65 // destroyed, or new WeakPtr objects may be used, from a different sequence.
66 //
67 // Thus, at least one WeakPtr object must exist and have been dereferenced on
68 // the correct sequence to enforce that other WeakPtr objects will enforce they
69 // are used on the desired sequence.
70
71 #ifndef BASE_MEMORY_WEAK_PTR_H_
72 #define BASE_MEMORY_WEAK_PTR_H_
73
74 #include <cstddef>
75 #include <type_traits>
76 #include <utility>
77
78 #include "base/base_export.h"
79 #include "base/check.h"
80 #include "base/compiler_specific.h"
81 #include "base/dcheck_is_on.h"
82 #include "base/memory/raw_ptr.h"
83 #include "base/memory/ref_counted.h"
84 #include "base/sequence_checker.h"
85 #include "base/synchronization/atomic_flag.h"
86
87 namespace base {
88
89 template <typename T>
90 class SafeRef;
91 template <typename T> class SupportsWeakPtr;
92 template <typename T> class WeakPtr;
93
94 namespace internal {
95 // These classes are part of the WeakPtr implementation.
96 // DO NOT USE THESE CLASSES DIRECTLY YOURSELF.
97
98 class BASE_EXPORT TRIVIAL_ABI WeakReference {
99 public:
100 // Although Flag is bound to a specific SequencedTaskRunner, it may be
101 // deleted from another via base::WeakPtr::~WeakPtr().
102 class BASE_EXPORT Flag : public RefCountedThreadSafe<Flag> {
103 public:
104 Flag();
105
106 void Invalidate();
107 bool IsValid() const;
108
109 bool MaybeValid() const;
110
111 #if DCHECK_IS_ON()
112 void DetachFromSequence();
113 #endif
114
115 private:
116 friend class base::RefCountedThreadSafe<Flag>;
117
118 ~Flag();
119
120 SEQUENCE_CHECKER(sequence_checker_);
121 AtomicFlag invalidated_;
122 };
123
124 WeakReference();
125 explicit WeakReference(const scoped_refptr<Flag>& flag);
126 ~WeakReference();
127
128 WeakReference(const WeakReference& other);
129 WeakReference& operator=(const WeakReference& other);
130
131 WeakReference(WeakReference&& other) noexcept;
132 WeakReference& operator=(WeakReference&& other) noexcept;
133
134 void Reset();
135 // Returns whether the WeakReference is valid, meaning the WeakPtrFactory has
136 // not invalidated the pointer. Unlike, RefIsMaybeValid(), this may only be
137 // called from the same sequence as where the WeakPtr was created.
138 bool IsValid() const;
139 // Returns false if the WeakReference is confirmed to be invalid. This call is
140 // safe to make from any thread, e.g. to optimize away unnecessary work, but
141 // RefIsValid() must always be called, on the correct sequence, before
142 // actually using the pointer.
143 //
144 // Warning: as with any object, this call is only thread-safe if the WeakPtr
145 // instance isn't being re-assigned or reset() racily with this call.
146 bool MaybeValid() const;
147
148 private:
149 scoped_refptr<const Flag> flag_;
150 };
151
152 class BASE_EXPORT WeakReferenceOwner {
153 public:
154 WeakReferenceOwner();
155 ~WeakReferenceOwner();
156
157 WeakReference GetRef() const;
158
HasRefs()159 bool HasRefs() const { return !flag_->HasOneRef(); }
160
161 void Invalidate();
162
163 private:
164 scoped_refptr<WeakReference::Flag> flag_;
165 };
166
167 // This class provides a common implementation of common functions that would
168 // otherwise get instantiated separately for each distinct instantiation of
169 // SupportsWeakPtr<>.
170 class SupportsWeakPtrBase {
171 public:
172 // A safe static downcast of a WeakPtr<Base> to WeakPtr<Derived>. This
173 // conversion will only compile if there is exists a Base which inherits
174 // from SupportsWeakPtr<Base>. See base::AsWeakPtr() below for a helper
175 // function that makes calling this easier.
176 //
177 // Precondition: t != nullptr
178 template<typename Derived>
StaticAsWeakPtr(Derived * t)179 static WeakPtr<Derived> StaticAsWeakPtr(Derived* t) {
180 static_assert(
181 std::is_base_of<internal::SupportsWeakPtrBase, Derived>::value,
182 "AsWeakPtr argument must inherit from SupportsWeakPtr");
183 return AsWeakPtrImpl<Derived>(t);
184 }
185
186 private:
187 // This template function uses type inference to find a Base of Derived
188 // which is an instance of SupportsWeakPtr<Base>. We can then safely
189 // static_cast the Base* to a Derived*.
190 template <typename Derived, typename Base>
AsWeakPtrImpl(SupportsWeakPtr<Base> * t)191 static WeakPtr<Derived> AsWeakPtrImpl(SupportsWeakPtr<Base>* t) {
192 WeakPtr<Base> weak = t->AsWeakPtr();
193 return WeakPtr<Derived>(weak.CloneWeakReference(),
194 static_cast<Derived*>(weak.ptr_));
195 }
196 };
197
198 // Forward declaration from safe_ptr.h.
199 template <typename T>
200 SafeRef<T> MakeSafeRefFromWeakPtrInternals(internal::WeakReference&& ref,
201 T* ptr);
202
203 } // namespace internal
204
205 template <typename T> class WeakPtrFactory;
206
207 // The WeakPtr class holds a weak reference to |T*|.
208 //
209 // This class is designed to be used like a normal pointer. You should always
210 // null-test an object of this class before using it or invoking a method that
211 // may result in the underlying object being destroyed.
212 //
213 // EXAMPLE:
214 //
215 // class Foo { ... };
216 // WeakPtr<Foo> foo;
217 // if (foo)
218 // foo->method();
219 //
220 template <typename T>
221 class TRIVIAL_ABI WeakPtr {
222 public:
223 WeakPtr() = default;
224 // NOLINTNEXTLINE(google-explicit-constructor)
WeakPtr(std::nullptr_t)225 WeakPtr(std::nullptr_t) {}
226
227 // Allow conversion from U to T provided U "is a" T. Note that this
228 // is separate from the (implicit) copy and move constructors.
229 template <typename U,
230 typename = std::enable_if_t<std::is_convertible_v<U*, T*>>>
231 // NOLINTNEXTLINE(google-explicit-constructor)
WeakPtr(const WeakPtr<U> & other)232 WeakPtr(const WeakPtr<U>& other) : ref_(other.ref_), ptr_(other.ptr_) {}
233 template <typename U,
234 typename = std::enable_if_t<std::is_convertible_v<U*, T*>>>
235 // NOLINTNEXTLINE(google-explicit-constructor)
236 WeakPtr& operator=(const WeakPtr<U>& other) {
237 ref_ = other.ref_;
238 ptr_ = other.ptr_;
239 return *this;
240 }
241
242 template <typename U,
243 typename = std::enable_if_t<std::is_convertible_v<U*, T*>>>
244 // NOLINTNEXTLINE(google-explicit-constructor)
WeakPtr(WeakPtr<U> && other)245 WeakPtr(WeakPtr<U>&& other)
246 : ref_(std::move(other.ref_)), ptr_(std::move(other.ptr_)) {}
247 template <typename U,
248 typename = std::enable_if_t<std::is_convertible_v<U*, T*>>>
249 // NOLINTNEXTLINE(google-explicit-constructor)
250 WeakPtr& operator=(WeakPtr<U>&& other) {
251 ref_ = std::move(other.ref_);
252 ptr_ = std::move(other.ptr_);
253 return *this;
254 }
255
get()256 T* get() const { return ref_.IsValid() ? ptr_ : nullptr; }
257
258 // Provide access to the underlying T as a reference. Will CHECK() if the T
259 // pointee is no longer alive.
260 T& operator*() const {
261 CHECK(ref_.IsValid());
262 return *ptr_;
263 }
264
265 // Used to call methods on the underlying T. Will CHECK() if the T pointee is
266 // no longer alive.
267 T* operator->() const {
268 CHECK(ref_.IsValid());
269 return ptr_;
270 }
271
272 // Allow conditionals to test validity, e.g. if (weak_ptr) {...};
273 explicit operator bool() const { return get() != nullptr; }
274
275 // Resets the WeakPtr to hold nothing.
276 //
277 // The `get()` method will return `nullptr` thereafter, and `MaybeValid()`
278 // will be `false`.
reset()279 void reset() {
280 ref_.Reset();
281 ptr_ = nullptr;
282 }
283
284 // Returns false if the WeakPtr is confirmed to be invalid. This call is safe
285 // to make from any thread, e.g. to optimize away unnecessary work, but
286 // RefIsValid() must always be called, on the correct sequence, before
287 // actually using the pointer.
288 //
289 // Warning: as with any object, this call is only thread-safe if the WeakPtr
290 // instance isn't being re-assigned or reset() racily with this call.
MaybeValid()291 bool MaybeValid() const { return ref_.MaybeValid(); }
292
293 // Returns whether the object |this| points to has been invalidated. This can
294 // be used to distinguish a WeakPtr to a destroyed object from one that has
295 // been explicitly set to null.
WasInvalidated()296 bool WasInvalidated() const { return ptr_ && !ref_.IsValid(); }
297
298 private:
299 friend class internal::SupportsWeakPtrBase;
300 template <typename U> friend class WeakPtr;
301 friend class SupportsWeakPtr<T>;
302 friend class WeakPtrFactory<T>;
303 friend class WeakPtrFactory<std::remove_const_t<T>>;
304
WeakPtr(internal::WeakReference && ref,T * ptr)305 WeakPtr(internal::WeakReference&& ref, T* ptr)
306 : ref_(std::move(ref)), ptr_(ptr) {
307 DCHECK(ptr);
308 }
309
CloneWeakReference()310 internal::WeakReference CloneWeakReference() const { return ref_; }
311
312 internal::WeakReference ref_;
313
314 // This pointer is only valid when ref_.is_valid() is true. Otherwise, its
315 // value is undefined (as opposed to nullptr). The pointer is allowed to
316 // dangle as we verify its liveness through `ref_` before allowing access to
317 // the pointee. We don't use raw_ptr<T> here to prevent WeakPtr from keeping
318 // the memory allocation in quarantine, as it can't be accessed through the
319 // WeakPtr.
320 RAW_PTR_EXCLUSION T* ptr_ = nullptr;
321 };
322
323 // Allow callers to compare WeakPtrs against nullptr to test validity.
324 template <class T>
325 bool operator!=(const WeakPtr<T>& weak_ptr, std::nullptr_t) {
326 return !(weak_ptr == nullptr);
327 }
328 template <class T>
329 bool operator!=(std::nullptr_t, const WeakPtr<T>& weak_ptr) {
330 return weak_ptr != nullptr;
331 }
332 template <class T>
333 bool operator==(const WeakPtr<T>& weak_ptr, std::nullptr_t) {
334 return weak_ptr.get() == nullptr;
335 }
336 template <class T>
337 bool operator==(std::nullptr_t, const WeakPtr<T>& weak_ptr) {
338 return weak_ptr == nullptr;
339 }
340
341 namespace internal {
342 class BASE_EXPORT WeakPtrFactoryBase {
343 protected:
344 WeakPtrFactoryBase(uintptr_t ptr);
345 ~WeakPtrFactoryBase();
346 internal::WeakReferenceOwner weak_reference_owner_;
347 uintptr_t ptr_;
348 };
349 } // namespace internal
350
351 // A class may be composed of a WeakPtrFactory and thereby
352 // control how it exposes weak pointers to itself. This is helpful if you only
353 // need weak pointers within the implementation of a class. This class is also
354 // useful when working with primitive types. For example, you could have a
355 // WeakPtrFactory<bool> that is used to pass around a weak reference to a bool.
356 template <class T>
357 class WeakPtrFactory : public internal::WeakPtrFactoryBase {
358 public:
359 WeakPtrFactory() = delete;
360
WeakPtrFactory(T * ptr)361 explicit WeakPtrFactory(T* ptr)
362 : WeakPtrFactoryBase(reinterpret_cast<uintptr_t>(ptr)) {}
363
364 WeakPtrFactory(const WeakPtrFactory&) = delete;
365 WeakPtrFactory& operator=(const WeakPtrFactory&) = delete;
366
367 ~WeakPtrFactory() = default;
368
GetWeakPtr()369 WeakPtr<const T> GetWeakPtr() const {
370 return WeakPtr<const T>(weak_reference_owner_.GetRef(),
371 reinterpret_cast<const T*>(ptr_));
372 }
373
374 template <int&... ExplicitArgumentBarrier,
375 typename U = T,
376 typename = std::enable_if_t<!std::is_const_v<U>>>
GetWeakPtr()377 WeakPtr<T> GetWeakPtr() {
378 return WeakPtr<T>(weak_reference_owner_.GetRef(),
379 reinterpret_cast<T*>(ptr_));
380 }
381
382 template <int&... ExplicitArgumentBarrier,
383 typename U = T,
384 typename = std::enable_if_t<!std::is_const_v<U>>>
GetMutableWeakPtr()385 WeakPtr<T> GetMutableWeakPtr() const {
386 return WeakPtr<T>(weak_reference_owner_.GetRef(),
387 reinterpret_cast<T*>(ptr_));
388 }
389
390 // Returns a smart pointer that is valid until the WeakPtrFactory is
391 // invalidated. Unlike WeakPtr, this smart pointer cannot be null, and cannot
392 // be checked to see if the WeakPtrFactory is invalidated. It's intended to
393 // express that the pointer will not (intentionally) outlive the `T` object it
394 // points to, and to crash safely in the case of a bug instead of causing a
395 // use-after-free. This type provides an alternative to WeakPtr to prevent
396 // use-after-free bugs without also introducing "fuzzy lifetimes" that can be
397 // checked for at runtime.
GetSafeRef()398 SafeRef<T> GetSafeRef() const {
399 return internal::MakeSafeRefFromWeakPtrInternals(
400 weak_reference_owner_.GetRef(), reinterpret_cast<T*>(ptr_));
401 }
402
403 // Call this method to invalidate all existing weak pointers.
InvalidateWeakPtrs()404 void InvalidateWeakPtrs() {
405 DCHECK(ptr_);
406 weak_reference_owner_.Invalidate();
407 }
408
409 // Call this method to determine if any weak pointers exist.
HasWeakPtrs()410 bool HasWeakPtrs() const {
411 DCHECK(ptr_);
412 return weak_reference_owner_.HasRefs();
413 }
414 };
415
416 // A class may extend from SupportsWeakPtr to let others take weak pointers to
417 // it. This avoids the class itself implementing boilerplate to dispense weak
418 // pointers. However, since SupportsWeakPtr's destructor won't invalidate
419 // weak pointers to the class until after the derived class' members have been
420 // destroyed, its use can lead to subtle use-after-destroy issues.
421 template <class T>
422 class SupportsWeakPtr : public internal::SupportsWeakPtrBase {
423 public:
424 SupportsWeakPtr() = default;
425
426 SupportsWeakPtr(const SupportsWeakPtr&) = delete;
427 SupportsWeakPtr& operator=(const SupportsWeakPtr&) = delete;
428
AsWeakPtr()429 WeakPtr<T> AsWeakPtr() {
430 return WeakPtr<T>(weak_reference_owner_.GetRef(), static_cast<T*>(this));
431 }
432
433 protected:
434 ~SupportsWeakPtr() = default;
435
436 private:
437 internal::WeakReferenceOwner weak_reference_owner_;
438 };
439
440 // Helper function that uses type deduction to safely return a WeakPtr<Derived>
441 // when Derived doesn't directly extend SupportsWeakPtr<Derived>, instead it
442 // extends a Base that extends SupportsWeakPtr<Base>.
443 //
444 // EXAMPLE:
445 // class Base : public base::SupportsWeakPtr<Producer> {};
446 // class Derived : public Base {};
447 //
448 // Derived derived;
449 // base::WeakPtr<Derived> ptr = base::AsWeakPtr(&derived);
450 //
451 // Note that the following doesn't work (invalid type conversion) since
452 // Derived::AsWeakPtr() is WeakPtr<Base> SupportsWeakPtr<Base>::AsWeakPtr(),
453 // and there's no way to safely cast WeakPtr<Base> to WeakPtr<Derived> at
454 // the caller.
455 //
456 // base::WeakPtr<Derived> ptr = derived.AsWeakPtr(); // Fails.
457
458 template <typename Derived>
AsWeakPtr(Derived * t)459 WeakPtr<Derived> AsWeakPtr(Derived* t) {
460 return internal::SupportsWeakPtrBase::StaticAsWeakPtr<Derived>(t);
461 }
462
463 } // namespace base
464
465 #endif // BASE_MEMORY_WEAK_PTR_H_
466