• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2012
2 // Google Inc. All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 //    * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 //    * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 //    * Neither the name of Google Inc. nor the name Chromium Embedded
15 // Framework nor the names of its contributors may be used to endorse
16 // or promote products derived from this software without specific prior
17 // written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 
31 // Weak pointers are pointers to an object that do not affect its lifetime,
32 // and which may be invalidated (i.e. reset to nullptr) by the object, or its
33 // owner, at any time, most commonly when the object is about to be deleted.
34 
35 // Weak pointers are useful when an object needs to be accessed safely by one
36 // or more objects other than its owner, and those callers can cope with the
37 // object vanishing and e.g. tasks posted to it being silently dropped.
38 // Reference-counting such an object would complicate the ownership graph and
39 // make it harder to reason about the object's lifetime.
40 
41 // EXAMPLE:
42 //
43 //  class Controller {
44 //   public:
45 //    void SpawnWorker() { Worker::StartNew(weak_factory_.GetWeakPtr()); }
46 //    void WorkComplete(const Result& result) { ... }
47 //   private:
48 //    // Member variables should appear before the WeakPtrFactory, to ensure
49 //    // that any WeakPtrs to Controller are invalidated before its members
50 //    // variable's destructors are executed, rendering them invalid.
51 //    WeakPtrFactory<Controller> weak_factory_{this};
52 //  };
53 //
54 //  class Worker {
55 //   public:
56 //    static void StartNew(WeakPtr<Controller> controller) {
57 //      Worker* worker = new Worker(std::move(controller));
58 //      // Kick off asynchronous processing...
59 //    }
60 //   private:
61 //    Worker(WeakPtr<Controller> controller)
62 //        : controller_(std::move(controller)) {}
63 //    void DidCompleteAsynchronousProcessing(const Result& result) {
64 //      if (controller_)
65 //        controller_->WorkComplete(result);
66 //    }
67 //    WeakPtr<Controller> controller_;
68 //  };
69 //
70 // With this implementation a caller may use SpawnWorker() to dispatch multiple
71 // Workers and subsequently delete the Controller, without waiting for all
72 // Workers to have completed.
73 
74 // ------------------------- IMPORTANT: Thread-safety -------------------------
75 
76 // Weak pointers may be passed safely between threads, but must always be
77 // dereferenced and invalidated on the same ThreaddTaskRunner otherwise
78 // checking the pointer would be racey.
79 //
80 // To ensure correct use, the first time a WeakPtr issued by a WeakPtrFactory
81 // is dereferenced, the factory and its WeakPtrs become bound to the calling
82 // thread or current ThreaddWorkerPool token, and cannot be dereferenced or
83 // invalidated on any other task runner. Bound WeakPtrs can still be handed
84 // off to other task runners, e.g. to use to post tasks back to object on the
85 // bound thread.
86 //
87 // If all WeakPtr objects are destroyed or invalidated then the factory is
88 // unbound from the ThreaddTaskRunner/Thread. The WeakPtrFactory may then be
89 // destroyed, or new WeakPtr objects may be used, from a different thread.
90 //
91 // Thus, at least one WeakPtr object must exist and have been dereferenced on
92 // the correct thread to enforce that other WeakPtr objects will enforce they
93 // are used on the desired thread.
94 
95 #ifndef CEF_INCLUDE_BASE_CEF_WEAK_PTR_H_
96 #define CEF_INCLUDE_BASE_CEF_WEAK_PTR_H_
97 #pragma once
98 
99 #if defined(USING_CHROMIUM_INCLUDES)
100 // When building CEF include the Chromium header directly.
101 #include "base/memory/weak_ptr.h"
102 #else  // !USING_CHROMIUM_INCLUDES
103 // The following is substantially similar to the Chromium implementation.
104 // If the Chromium implementation diverges the below implementation should be
105 // updated to match.
106 
107 #include <cstddef>
108 #include <type_traits>
109 
110 #include "include/base/cef_atomic_flag.h"
111 #include "include/base/cef_logging.h"
112 #include "include/base/cef_ref_counted.h"
113 #include "include/base/cef_thread_checker.h"
114 
115 namespace base {
116 
117 template <typename T>
118 class SupportsWeakPtr;
119 template <typename T>
120 class WeakPtr;
121 
122 namespace internal {
123 // These classes are part of the WeakPtr implementation.
124 // DO NOT USE THESE CLASSES DIRECTLY YOURSELF.
125 
126 class WeakReference {
127  public:
128   // Although Flag is bound to a specific ThreaddTaskRunner, it may be
129   // deleted from another via base::WeakPtr::~WeakPtr().
130   class Flag : public RefCountedThreadSafe<Flag> {
131    public:
132     Flag();
133 
134     void Invalidate();
135     bool IsValid() const;
136 
137     bool MaybeValid() const;
138 
139     void DetachFromThread();
140 
141    private:
142     friend class base::RefCountedThreadSafe<Flag>;
143 
144     ~Flag();
145 
146     base::ThreadChecker thread_checker_;
147     AtomicFlag invalidated_;
148   };
149 
150   WeakReference();
151   explicit WeakReference(const scoped_refptr<Flag>& flag);
152   ~WeakReference();
153 
154   WeakReference(WeakReference&& other) noexcept;
155   WeakReference(const WeakReference& other);
156   WeakReference& operator=(WeakReference&& other) noexcept = default;
157   WeakReference& operator=(const WeakReference& other) = default;
158 
159   bool IsValid() const;
160   bool MaybeValid() const;
161 
162  private:
163   scoped_refptr<const Flag> flag_;
164 };
165 
166 class WeakReferenceOwner {
167  public:
168   WeakReferenceOwner();
169   ~WeakReferenceOwner();
170 
171   WeakReference GetRef() const;
172 
HasRefs()173   bool HasRefs() const { return !flag_->HasOneRef(); }
174 
175   void Invalidate();
176 
177  private:
178   scoped_refptr<WeakReference::Flag> flag_;
179 };
180 
181 // This class simplifies the implementation of WeakPtr's type conversion
182 // constructor by avoiding the need for a public accessor for ref_.  A
183 // WeakPtr<T> cannot access the private members of WeakPtr<U>, so this
184 // base class gives us a way to access ref_ in a protected fashion.
185 class WeakPtrBase {
186  public:
187   WeakPtrBase();
188   ~WeakPtrBase();
189 
190   WeakPtrBase(const WeakPtrBase& other) = default;
191   WeakPtrBase(WeakPtrBase&& other) noexcept = default;
192   WeakPtrBase& operator=(const WeakPtrBase& other) = default;
193   WeakPtrBase& operator=(WeakPtrBase&& other) noexcept = default;
194 
reset()195   void reset() {
196     ref_ = internal::WeakReference();
197     ptr_ = 0;
198   }
199 
200  protected:
201   WeakPtrBase(const WeakReference& ref, uintptr_t ptr);
202 
203   WeakReference ref_;
204 
205   // This pointer is only valid when ref_.is_valid() is true.  Otherwise, its
206   // value is undefined (as opposed to nullptr).
207   uintptr_t ptr_;
208 };
209 
210 // This class provides a common implementation of common functions that would
211 // otherwise get instantiated separately for each distinct instantiation of
212 // SupportsWeakPtr<>.
213 class SupportsWeakPtrBase {
214  public:
215   // A safe static downcast of a WeakPtr<Base> to WeakPtr<Derived>. This
216   // conversion will only compile if there is exists a Base which inherits
217   // from SupportsWeakPtr<Base>. See base::AsWeakPtr() below for a helper
218   // function that makes calling this easier.
219   //
220   // Precondition: t != nullptr
221   template <typename Derived>
StaticAsWeakPtr(Derived * t)222   static WeakPtr<Derived> StaticAsWeakPtr(Derived* t) {
223     static_assert(
224         std::is_base_of<internal::SupportsWeakPtrBase, Derived>::value,
225         "AsWeakPtr argument must inherit from SupportsWeakPtr");
226     return AsWeakPtrImpl<Derived>(t);
227   }
228 
229  private:
230   // This template function uses type inference to find a Base of Derived
231   // which is an instance of SupportsWeakPtr<Base>. We can then safely
232   // static_cast the Base* to a Derived*.
233   template <typename Derived, typename Base>
AsWeakPtrImpl(SupportsWeakPtr<Base> * t)234   static WeakPtr<Derived> AsWeakPtrImpl(SupportsWeakPtr<Base>* t) {
235     WeakPtr<Base> ptr = t->AsWeakPtr();
236     return WeakPtr<Derived>(
237         ptr.ref_, static_cast<Derived*>(reinterpret_cast<Base*>(ptr.ptr_)));
238   }
239 };
240 
241 }  // namespace internal
242 
243 template <typename T>
244 class WeakPtrFactory;
245 
246 // The WeakPtr class holds a weak reference to |T*|.
247 //
248 // This class is designed to be used like a normal pointer.  You should always
249 // null-test an object of this class before using it or invoking a method that
250 // may result in the underlying object being destroyed.
251 //
252 // EXAMPLE:
253 //
254 //   class Foo { ... };
255 //   WeakPtr<Foo> foo;
256 //   if (foo)
257 //     foo->method();
258 //
259 template <typename T>
260 class WeakPtr : public internal::WeakPtrBase {
261  public:
262   WeakPtr() = default;
WeakPtr(std::nullptr_t)263   WeakPtr(std::nullptr_t) {}
264 
265   // Allow conversion from U to T provided U "is a" T. Note that this
266   // is separate from the (implicit) copy and move constructors.
267   template <typename U>
WeakPtr(const WeakPtr<U> & other)268   WeakPtr(const WeakPtr<U>& other) : WeakPtrBase(other) {
269     // Need to cast from U* to T* to do pointer adjustment in case of multiple
270     // inheritance. This also enforces the "U is a T" rule.
271     T* t = reinterpret_cast<U*>(other.ptr_);
272     ptr_ = reinterpret_cast<uintptr_t>(t);
273   }
274   template <typename U>
WeakPtr(WeakPtr<U> && other)275   WeakPtr(WeakPtr<U>&& other) noexcept : WeakPtrBase(std::move(other)) {
276     // Need to cast from U* to T* to do pointer adjustment in case of multiple
277     // inheritance. This also enforces the "U is a T" rule.
278     T* t = reinterpret_cast<U*>(other.ptr_);
279     ptr_ = reinterpret_cast<uintptr_t>(t);
280   }
281 
get()282   T* get() const {
283     return ref_.IsValid() ? reinterpret_cast<T*>(ptr_) : nullptr;
284   }
285 
286   T& operator*() const {
287     CHECK(ref_.IsValid());
288     return *get();
289   }
290   T* operator->() const {
291     CHECK(ref_.IsValid());
292     return get();
293   }
294 
295   // Allow conditionals to test validity, e.g. if (weak_ptr) {...};
296   explicit operator bool() const { return get() != nullptr; }
297 
298   // Returns false if the WeakPtr is confirmed to be invalid. This call is safe
299   // to make from any thread, e.g. to optimize away unnecessary work, but
300   // operator bool() must always be called, on the correct thread, before
301   // actually using the pointer.
302   //
303   // Warning: as with any object, this call is only thread-safe if the WeakPtr
304   // instance isn't being re-assigned or reset() racily with this call.
MaybeValid()305   bool MaybeValid() const { return ref_.MaybeValid(); }
306 
307   // Returns whether the object |this| points to has been invalidated. This can
308   // be used to distinguish a WeakPtr to a destroyed object from one that has
309   // been explicitly set to null.
WasInvalidated()310   bool WasInvalidated() const { return ptr_ && !ref_.IsValid(); }
311 
312  private:
313   friend class internal::SupportsWeakPtrBase;
314   template <typename U>
315   friend class WeakPtr;
316   friend class SupportsWeakPtr<T>;
317   friend class WeakPtrFactory<T>;
318 
WeakPtr(const internal::WeakReference & ref,T * ptr)319   WeakPtr(const internal::WeakReference& ref, T* ptr)
320       : WeakPtrBase(ref, reinterpret_cast<uintptr_t>(ptr)) {}
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 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<T> GetWeakPtr() const {
370     return WeakPtr<T>(weak_reference_owner_.GetRef(),
371                       reinterpret_cast<T*>(ptr_));
372   }
373 
374   // Call this method to invalidate all existing weak pointers.
InvalidateWeakPtrs()375   void InvalidateWeakPtrs() {
376     DCHECK(ptr_);
377     weak_reference_owner_.Invalidate();
378   }
379 
380   // Call this method to determine if any weak pointers exist.
HasWeakPtrs()381   bool HasWeakPtrs() const {
382     DCHECK(ptr_);
383     return weak_reference_owner_.HasRefs();
384   }
385 };
386 
387 // A class may extend from SupportsWeakPtr to let others take weak pointers to
388 // it. This avoids the class itself implementing boilerplate to dispense weak
389 // pointers.  However, since SupportsWeakPtr's destructor won't invalidate
390 // weak pointers to the class until after the derived class' members have been
391 // destroyed, its use can lead to subtle use-after-destroy issues.
392 template <class T>
393 class SupportsWeakPtr : public internal::SupportsWeakPtrBase {
394  public:
395   SupportsWeakPtr() = default;
396 
397   SupportsWeakPtr(const SupportsWeakPtr&) = delete;
398   SupportsWeakPtr& operator=(const SupportsWeakPtr&) = delete;
399 
AsWeakPtr()400   WeakPtr<T> AsWeakPtr() {
401     return WeakPtr<T>(weak_reference_owner_.GetRef(), static_cast<T*>(this));
402   }
403 
404  protected:
405   ~SupportsWeakPtr() = default;
406 
407  private:
408   internal::WeakReferenceOwner weak_reference_owner_;
409 };
410 
411 // Helper function that uses type deduction to safely return a WeakPtr<Derived>
412 // when Derived doesn't directly extend SupportsWeakPtr<Derived>, instead it
413 // extends a Base that extends SupportsWeakPtr<Base>.
414 //
415 // EXAMPLE:
416 //   class Base : public base::SupportsWeakPtr<Producer> {};
417 //   class Derived : public Base {};
418 //
419 //   Derived derived;
420 //   base::WeakPtr<Derived> ptr = base::AsWeakPtr(&derived);
421 //
422 // Note that the following doesn't work (invalid type conversion) since
423 // Derived::AsWeakPtr() is WeakPtr<Base> SupportsWeakPtr<Base>::AsWeakPtr(),
424 // and there's no way to safely cast WeakPtr<Base> to WeakPtr<Derived> at
425 // the caller.
426 //
427 //   base::WeakPtr<Derived> ptr = derived.AsWeakPtr();  // Fails.
428 
429 template <typename Derived>
AsWeakPtr(Derived * t)430 WeakPtr<Derived> AsWeakPtr(Derived* t) {
431   return internal::SupportsWeakPtrBase::StaticAsWeakPtr<Derived>(t);
432 }
433 
434 }  // namespace base
435 
436 #endif  // !USING_CHROMIUM_INCLUDES
437 
438 #endif  // CEF_INCLUDE_BASE_CEF_WEAK_PTR_H_
439