• 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 NULL) 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 //    Controller() : weak_factory_(this) {}
46 //    void SpawnWorker() { Worker::StartNew(weak_factory_.GetWeakPtr()); }
47 //    void WorkComplete(const Result& result) { ... }
48 //   private:
49 //    // Member variables should appear before the WeakPtrFactory, to ensure
50 //    // that any WeakPtrs to Controller are invalidated before its members
51 //    // variable's destructors are executed, rendering them invalid.
52 //    WeakPtrFactory<Controller> weak_factory_;
53 //  };
54 //
55 //  class Worker {
56 //   public:
57 //    static void StartNew(const WeakPtr<Controller>& controller) {
58 //      Worker* worker = new Worker(controller);
59 //      // Kick off asynchronous processing...
60 //    }
61 //   private:
62 //    Worker(const WeakPtr<Controller>& controller)
63 //        : controller_(controller) {}
64 //    void DidCompleteAsynchronousProcessing(const Result& result) {
65 //      if (controller_)
66 //        controller_->WorkComplete(result);
67 //    }
68 //    WeakPtr<Controller> controller_;
69 //  };
70 //
71 // With this implementation a caller may use SpawnWorker() to dispatch multiple
72 // Workers and subsequently delete the Controller, without waiting for all
73 // Workers to have completed.
74 
75 // ------------------------- IMPORTANT: Thread-safety -------------------------
76 
77 // Weak pointers may be passed safely between threads, but must always be
78 // dereferenced and invalidated on the same thread otherwise checking the
79 // pointer would be racey.
80 //
81 // To ensure correct use, the first time a WeakPtr issued by a WeakPtrFactory
82 // is dereferenced, the factory and its WeakPtrs become bound to the calling
83 // thread, and cannot be dereferenced or invalidated on any other thread. Bound
84 // WeakPtrs can still be handed off to other threads, e.g. to use to post tasks
85 // back to object on the bound thread.
86 //
87 // If all WeakPtr objects are destroyed or invalidated then the factory is
88 // unbound from the SequencedTaskRunner/Thread. The WeakPtrFactory may then be
89 // destroyed, or new WeakPtr objects may be used, from a different sequence.
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(BASE_MEMORY_WEAK_PTR_H_)
100 // Do nothing if the Chromium header has already been included.
101 // This can happen in cases where Chromium code is used directly by the
102 // client application. When using Chromium code directly always include
103 // the Chromium header first to avoid type conflicts.
104 #elif defined(USING_CHROMIUM_INCLUDES)
105 // When building CEF include the Chromium header directly.
106 #include "base/memory/weak_ptr.h"
107 #else  // !USING_CHROMIUM_INCLUDES
108 // The following is substantially similar to the Chromium implementation.
109 // If the Chromium implementation diverges the below implementation should be
110 // updated to match.
111 
112 #include "include/base/cef_basictypes.h"
113 #include "include/base/cef_logging.h"
114 #include "include/base/cef_ref_counted.h"
115 #include "include/base/cef_template_util.h"
116 #include "include/base/cef_thread_checker.h"
117 
118 namespace base {
119 
120 template <typename T>
121 class SupportsWeakPtr;
122 template <typename T>
123 class WeakPtr;
124 
125 namespace cef_internal {
126 // These classes are part of the WeakPtr implementation.
127 // DO NOT USE THESE CLASSES DIRECTLY YOURSELF.
128 
129 class WeakReference {
130  public:
131   // Although Flag is bound to a specific thread, it may be deleted from another
132   // via base::WeakPtr::~WeakPtr().
133   class Flag : public RefCountedThreadSafe<Flag> {
134    public:
135     Flag();
136 
137     void Invalidate();
138     bool IsValid() const;
139 
140    private:
141     friend class base::RefCountedThreadSafe<Flag>;
142 
143     ~Flag();
144 
145     // The current Chromium implementation uses SequenceChecker instead of
146     // ThreadChecker to support SequencedWorkerPools. CEF does not yet expose
147     // the concept of SequencedWorkerPools.
148     ThreadChecker thread_checker_;
149     bool is_valid_;
150   };
151 
152   WeakReference();
153   explicit WeakReference(const Flag* flag);
154   ~WeakReference();
155 
156   bool is_valid() const;
157 
158  private:
159   scoped_refptr<const Flag> flag_;
160 };
161 
162 class WeakReferenceOwner {
163  public:
164   WeakReferenceOwner();
165   ~WeakReferenceOwner();
166 
167   WeakReference GetRef() const;
168 
HasRefs()169   bool HasRefs() const { return flag_.get() && !flag_->HasOneRef(); }
170 
171   void Invalidate();
172 
173  private:
174   mutable scoped_refptr<WeakReference::Flag> flag_;
175 };
176 
177 // This class simplifies the implementation of WeakPtr's type conversion
178 // constructor by avoiding the need for a public accessor for ref_.  A
179 // WeakPtr<T> cannot access the private members of WeakPtr<U>, so this
180 // base class gives us a way to access ref_ in a protected fashion.
181 class WeakPtrBase {
182  public:
183   WeakPtrBase();
184   ~WeakPtrBase();
185 
186  protected:
187   explicit WeakPtrBase(const WeakReference& ref);
188 
189   WeakReference ref_;
190 };
191 
192 // This class provides a common implementation of common functions that would
193 // otherwise get instantiated separately for each distinct instantiation of
194 // SupportsWeakPtr<>.
195 class SupportsWeakPtrBase {
196  public:
197   // A safe static downcast of a WeakPtr<Base> to WeakPtr<Derived>. This
198   // conversion will only compile if there is exists a Base which inherits
199   // from SupportsWeakPtr<Base>. See base::AsWeakPtr() below for a helper
200   // function that makes calling this easier.
201   template <typename Derived>
StaticAsWeakPtr(Derived * t)202   static WeakPtr<Derived> StaticAsWeakPtr(Derived* t) {
203     typedef is_convertible<Derived, cef_internal::SupportsWeakPtrBase&>
204         convertible;
205     COMPILE_ASSERT(convertible::value,
206                    AsWeakPtr_argument_inherits_from_SupportsWeakPtr);
207     return AsWeakPtrImpl<Derived>(t, *t);
208   }
209 
210  private:
211   // This template function uses type inference to find a Base of Derived
212   // which is an instance of SupportsWeakPtr<Base>. We can then safely
213   // static_cast the Base* to a Derived*.
214   template <typename Derived, typename Base>
AsWeakPtrImpl(Derived * t,const SupportsWeakPtr<Base> &)215   static WeakPtr<Derived> AsWeakPtrImpl(Derived* t,
216                                         const SupportsWeakPtr<Base>&) {
217     WeakPtr<Base> ptr = t->Base::AsWeakPtr();
218     return WeakPtr<Derived>(ptr.ref_, static_cast<Derived*>(ptr.ptr_));
219   }
220 };
221 
222 }  // namespace cef_internal
223 
224 template <typename T>
225 class WeakPtrFactory;
226 
227 // The WeakPtr class holds a weak reference to |T*|.
228 //
229 // This class is designed to be used like a normal pointer.  You should always
230 // null-test an object of this class before using it or invoking a method that
231 // may result in the underlying object being destroyed.
232 //
233 // EXAMPLE:
234 //
235 //   class Foo { ... };
236 //   WeakPtr<Foo> foo;
237 //   if (foo)
238 //     foo->method();
239 //
240 template <typename T>
241 class WeakPtr : public cef_internal::WeakPtrBase {
242  public:
WeakPtr()243   WeakPtr() : ptr_(NULL) {}
244 
245   // Allow conversion from U to T provided U "is a" T. Note that this
246   // is separate from the (implicit) copy constructor.
247   template <typename U>
WeakPtr(const WeakPtr<U> & other)248   WeakPtr(const WeakPtr<U>& other) : WeakPtrBase(other), ptr_(other.ptr_) {}
249 
get()250   T* get() const { return ref_.is_valid() ? ptr_ : NULL; }
251 
252   T& operator*() const {
253     CHECK(ref_.is_valid());
254     return *get();
255   }
256   T* operator->() const {
257     CHECK(ref_.is_valid());
258     return get();
259   }
260 
261   // Allow WeakPtr<element_type> to be used in boolean expressions, but not
262   // implicitly convertible to a real bool (which is dangerous).
263   //
264   // Note that this trick is only safe when the == and != operators
265   // are declared explicitly, as otherwise "weak_ptr1 == weak_ptr2"
266   // will compile but do the wrong thing (i.e., convert to Testable
267   // and then do the comparison).
268  private:
269   typedef T* WeakPtr::*Testable;
270 
271  public:
Testable()272   operator Testable() const { return get() ? &WeakPtr::ptr_ : NULL; }
273 
reset()274   void reset() {
275     ref_ = cef_internal::WeakReference();
276     ptr_ = NULL;
277   }
278 
279  private:
280   // Explicitly declare comparison operators as required by the bool
281   // trick, but keep them private.
282   template <class U>
283   bool operator==(WeakPtr<U> const&) const;
284   template <class U>
285   bool operator!=(WeakPtr<U> const&) const;
286 
287   friend class cef_internal::SupportsWeakPtrBase;
288   template <typename U>
289   friend class WeakPtr;
290   friend class SupportsWeakPtr<T>;
291   friend class WeakPtrFactory<T>;
292 
WeakPtr(const cef_internal::WeakReference & ref,T * ptr)293   WeakPtr(const cef_internal::WeakReference& ref, T* ptr)
294       : WeakPtrBase(ref), ptr_(ptr) {}
295 
296   // This pointer is only valid when ref_.is_valid() is true.  Otherwise, its
297   // value is undefined (as opposed to NULL).
298   T* ptr_;
299 };
300 
301 // A class may be composed of a WeakPtrFactory and thereby
302 // control how it exposes weak pointers to itself.  This is helpful if you only
303 // need weak pointers within the implementation of a class.  This class is also
304 // useful when working with primitive types.  For example, you could have a
305 // WeakPtrFactory<bool> that is used to pass around a weak reference to a bool.
306 template <class T>
307 class WeakPtrFactory {
308  public:
WeakPtrFactory(T * ptr)309   explicit WeakPtrFactory(T* ptr) : ptr_(ptr) {}
310 
~WeakPtrFactory()311   ~WeakPtrFactory() { ptr_ = NULL; }
312 
GetWeakPtr()313   WeakPtr<T> GetWeakPtr() {
314     DCHECK(ptr_);
315     return WeakPtr<T>(weak_reference_owner_.GetRef(), ptr_);
316   }
317 
318   // Call this method to invalidate all existing weak pointers.
InvalidateWeakPtrs()319   void InvalidateWeakPtrs() {
320     DCHECK(ptr_);
321     weak_reference_owner_.Invalidate();
322   }
323 
324   // Call this method to determine if any weak pointers exist.
HasWeakPtrs()325   bool HasWeakPtrs() const {
326     DCHECK(ptr_);
327     return weak_reference_owner_.HasRefs();
328   }
329 
330  private:
331   cef_internal::WeakReferenceOwner weak_reference_owner_;
332   T* ptr_;
333   DISALLOW_IMPLICIT_CONSTRUCTORS(WeakPtrFactory);
334 };
335 
336 // A class may extend from SupportsWeakPtr to let others take weak pointers to
337 // it. This avoids the class itself implementing boilerplate to dispense weak
338 // pointers.  However, since SupportsWeakPtr's destructor won't invalidate
339 // weak pointers to the class until after the derived class' members have been
340 // destroyed, its use can lead to subtle use-after-destroy issues.
341 template <class T>
342 class SupportsWeakPtr : public cef_internal::SupportsWeakPtrBase {
343  public:
SupportsWeakPtr()344   SupportsWeakPtr() {}
345 
AsWeakPtr()346   WeakPtr<T> AsWeakPtr() {
347     return WeakPtr<T>(weak_reference_owner_.GetRef(), static_cast<T*>(this));
348   }
349 
350  protected:
~SupportsWeakPtr()351   ~SupportsWeakPtr() {}
352 
353  private:
354   cef_internal::WeakReferenceOwner weak_reference_owner_;
355   DISALLOW_COPY_AND_ASSIGN(SupportsWeakPtr);
356 };
357 
358 // Helper function that uses type deduction to safely return a WeakPtr<Derived>
359 // when Derived doesn't directly extend SupportsWeakPtr<Derived>, instead it
360 // extends a Base that extends SupportsWeakPtr<Base>.
361 //
362 // EXAMPLE:
363 //   class Base : public base::SupportsWeakPtr<Producer> {};
364 //   class Derived : public Base {};
365 //
366 //   Derived derived;
367 //   base::WeakPtr<Derived> ptr = base::AsWeakPtr(&derived);
368 //
369 // Note that the following doesn't work (invalid type conversion) since
370 // Derived::AsWeakPtr() is WeakPtr<Base> SupportsWeakPtr<Base>::AsWeakPtr(),
371 // and there's no way to safely cast WeakPtr<Base> to WeakPtr<Derived> at
372 // the caller.
373 //
374 //   base::WeakPtr<Derived> ptr = derived.AsWeakPtr();  // Fails.
375 
376 template <typename Derived>
AsWeakPtr(Derived * t)377 WeakPtr<Derived> AsWeakPtr(Derived* t) {
378   return cef_internal::SupportsWeakPtrBase::StaticAsWeakPtr<Derived>(t);
379 }
380 
381 }  // namespace base
382 
383 #endif  // !USING_CHROMIUM_INCLUDES
384 
385 #endif  // CEF_INCLUDE_BASE_CEF_WEAK_PTR_H_
386