| 6 | #define BASE_THREADING_SEQUENCE_BOUND_H_ |
| 7 |
| 8 | #include <new> |
| 9 | #include <type_traits> |
| 10 |
| 11 | #include "base/bind.h" |
| 12 | #include "base/callback.h" |
| 13 | #include "base/compiler_specific.h" |
| 14 | #include "base/location.h" |
| 15 | #include "base/memory/aligned_memory.h" |
| 16 | #include "base/memory/ptr_util.h" |
| 17 | #include "base/sequenced_task_runner.h" |
| 18 |
| 19 | namespace base { |
| 20 |
| 21 | // SequenceBound facilitates owning objects that live on a specified sequence, |
| 22 | // which is potentially different than the owner's sequence. It encapsulates |
| 23 | // the work of posting tasks to the specified sequence to construct T, call |
| 24 | // methods on T, and destroy T. |
| 25 | // |
| 26 | // It does not provide explicit access to the underlying object directly, to |
| 27 | // prevent accidentally using it from the wrong sequence. |
| 28 | // |
| 29 | // Like std::unique_ptr<T>, a SequenceBound<T> may be moved between owners, |
| 30 | // and posted across threads. It may also be up-casted (only), to permit |
| 31 | // SequenceBound to be used with interfaces. |
| 32 | // |
| 33 | // Basic usage looks like this: |
| 34 | // |
| 35 | // // Some class that lives on |main_task_runner|. |
| 36 | // class MyClass { |
| 37 | // public: |
| 38 | // explicit MyClass(const char* widget_title) {} |
| 39 | // virtual ~MyClass() { ... } |
| 40 | // virtual void DoSomething(int arg) { ... } |
| 41 | // }; |
| 42 | // |
| 43 | // // On any thread... |
| 44 | // scoped_refptr<SequencedTaskRunner> main_task_runner = ...; |
| 45 | // auto widget = SequenceBound<MyClass>(main_task_runner, "My Title"); |
| 46 | // |
| 47 | // // Execute a single method on the object, on |main_task_runner|. |
| 48 | // widget.Post(FROM_HERE, &MyClass::DoSomething, 1234); |
| 49 | // |
| 50 | // // Execute an arbitrary task on |main_task_runner| with a non-const pointer |
| 51 | // // to the object. |
| 52 | // widget.PostTaskWithThisObject( |
| 53 | // FROM_HERE, |
| 54 | // base::BindOnce([](MyClass* widget) { |
| 55 | // // Unlike with Post, we can issue multiple calls on |widget| within |
| 56 | // // the same stack frame. |
| 57 | // widget->DoSomething(42); |
| 58 | // widget->DoSomething(13); |
| 59 | // })); |
| 60 | // |
| 61 | // // Execute an arbitrary task on |main_task_runner| with a const reference |
| 62 | // // to the object. |
| 63 | // widget.PostTaskWithThisObject( |
| 64 | // FROM_HERE, |
| 65 | // base::BindOnce([](const MyClass& widget) { ... })); |
| 66 | // |
| 67 | // Note that |widget| is constructed asynchronously on |main_task_runner|, |
| 68 | // but calling Post() immediately is safe, since the actual call is posted |
| 69 | // to |main_task_runner| as well. |
| 70 | // |
| 71 | // |widget| will be deleted on |main_task_runner| asynchronously when it goes |
| 72 | // out of scope, or when Reset() is called. |
| 73 | // |
| 74 | // Here is a more complicated example that shows injection and upcasting: |
| 75 | // |
| 76 | // // Some unrelated class that uses a |MyClass| to do something. |
| 77 | // class SomeConsumer { |
| 78 | // public: |
| 79 | // // Note that ownership of |widget| is given to us! |
| 80 | // explicit SomeConsumer(SequenceBound<MyClass> widget) |
| 81 | // : widget_(std::move(widget)) { ... } |
| 82 | // |
| 83 | // ~SomeConsumer() { |
| 84 | // // |widget_| will be destroyed on the associated task runner. |
| 85 | // } |
| 86 | // |
| 87 | // SequenceBound<MyClass> widget_; |
| 88 | // }; |
| 89 | // |
| 90 | // // Implementation of MyClass. |
| 91 | // class MyDerivedClass : public MyClass { ... }; |
| 92 | // |
| 93 | // auto widget = |
| 94 | // SequenceBound<MyDerivedClass>(main_task_runner, ctor args); |
| 95 | // auto c = new SomeConsumer(std::move(widget)); // upcasts to MyClass |
| 96 |
| 97 | namespace internal { |
| 98 |
| 99 | // If we can't cast |Base*| into |Derived*|, then it's a virtual base if and |
| 100 | // only if |Base| is actually a base class of |Derived|. Otherwise (including |
| 101 | // unrelated types), it isn't. We default to Derived* so that the |
| 102 | // specialization below will apply when the cast to |Derived*| is valid. |
| 103 | template <typename Base, typename Derived, typename = Derived*> |
| 104 | struct is_virtual_base_of : public std::is_base_of<Base, Derived> {}; |
| 105 |
| 106 | // If we can cast |Base*| into |Derived*|, then it's definitely not a virtual |
| 107 | // base. When this happens, we'll match the default third template argument. |
| 108 | template <typename Base, typename Derived> |
| 109 | struct is_virtual_base_of<Base, |
| 110 | Derived, |
| 111 | decltype(static_cast<Derived*>( |
| 112 | static_cast<Base*>(nullptr)))> : std::false_type { |
| 113 | }; |
| 114 |
| 115 | } // namespace internal |
| 116 |
| 117 | template <typename T> |
| 118 | class SequenceBound { |
| 119 | public: |
| 120 | // Allow explicit null. |
| 121 | SequenceBound() = default; |
| 122 |
| 123 | // Construct a new instance of |T| that will be accessed only on |
| 124 | // |task_runner|. One may post calls to it immediately upon return. |
| 125 | // This is marked as NO_SANITIZE because cfi doesn't like that we're casting |
| 126 | // uninitialized memory to a |T*|. However, it's safe since (a) the cast is |
| 127 | // defined (see http://eel.is/c++draft/basic.life#6 for details), and (b) we |
| 128 | // don't use the resulting pointer in any way that requries it to be |
| 129 | // constructed, except by posting such a access to |impl_task_runner_| after |
| 130 | // posting construction there as well. |
| 131 | template <typename... Args> |
| 132 | NO_SANITIZE("cfi-unrelated-cast") |
| 133 | SequenceBound(scoped_refptr<base::SequencedTaskRunner> task_runner, |
| 134 | Args&&... args) |
| 135 | : impl_task_runner_(std::move(task_runner)) { |
| 136 | // Allocate space for but do not construct an instance of |T|. |
| 137 | storage_ = AlignedAlloc(sizeof(T), alignof(T)); |
| 138 | t_ = reinterpret_cast<T*>(storage_); |
| 139 |
| 140 | // Post construction to the impl thread. |
| 141 | impl_task_runner_->PostTask( |
| 142 | FROM_HERE, |
| 143 | base::BindOnce(&ConstructOwnerRecord<Args...>, base::Unretained(t_), |
| 144 | std::forward<Args>(args)...)); |
| 145 | } |
| 146 |
| 147 | ~SequenceBound() { Reset(); } |
| 148 |
| 149 | // Move construction from the same type can just take the pointer without |
| 150 | // adjusting anything. This is required in addition to the move conversion |
| 151 | // constructor below. |
| 152 | SequenceBound(SequenceBound&& other) { MoveRecordFrom(other); } |
| 153 |
| 154 | // Move construction is supported from any type that's compatible with |T|. |
| 155 | // This case handles |From| != |T|, so we must adjust the pointer offset. |
| 156 | template <typename From> |
| 157 | SequenceBound(SequenceBound<From>&& other) { |
| 158 | MoveRecordFrom(other); |
| 159 | } |
| 160 |
| 161 | SequenceBound& operator=(SequenceBound&& other) { |
| 162 | // Clean up any object we currently own. |
| 163 | Reset(); |
| 164 | MoveRecordFrom(other); |
| 165 | return *this; |
| 166 | } |
| 167 |
| 168 | template <typename From> |
| 169 | SequenceBound<T>& operator=(SequenceBound<From>&& other) { |
| 170 | // Clean up any object that we currently own. |
| 171 | Reset(); |
| 172 | MoveRecordFrom(other); |
| 173 | return *this; |
| 174 | } |
| 175 |
| 176 | // Post a call to |method| to |impl_task_runner_|. |
| 177 | template <typename... MethodArgs, typename... Args> |
| 178 | void Post(const base::Location& from_here, |
| 179 | void (T::*method)(MethodArgs...), |
| 180 | Args&&... args) const { |
| 181 | DCHECK(t_); |
| 182 | impl_task_runner_->PostTask(from_here, |
| 183 | base::BindOnce(method, base::Unretained(t_), |
| 184 | std::forward<Args>(args)...)); |
| 185 | } |
| 186 |
| 187 | // Posts |task| to |impl_task_runner_|, passing it a reference to the wrapped |
| 188 | // object. This allows arbitrary logic to be safely executed on the object's |
| 189 | // task runner. The object is guaranteed to remain alive for the duration of |
| 190 | // the task. |
| 191 | using ConstPostTaskCallback = base::OnceCallback<void(const T&)>; |
| 192 | void PostTaskWithThisObject(const base::Location& from_here, |
| 193 | ConstPostTaskCallback callback) const { |
| 194 | DCHECK(t_); |
| 195 | impl_task_runner_->PostTask( |
| 196 | from_here, |
| 197 | base::BindOnce([](ConstPostTaskCallback callback, |
| 198 | const T* t) { std::move(callback).Run(*t); }, |
| 199 | std::move(callback), t_)); |
| 200 | } |
| 201 |
| 202 | // Same as above, but for non-const operations. The callback takes a pointer |
| 203 | // to the wrapped object rather than a const ref. |
| 204 | using PostTaskCallback = base::OnceCallback<void(T*)>; |
| 205 | void PostTaskWithThisObject(const base::Location& from_here, |
| 206 | PostTaskCallback callback) const { |
| 207 | DCHECK(t_); |
| 208 | impl_task_runner_->PostTask(from_here, |
| 209 | base::BindOnce(std::move(callback), t_)); |
| 210 | } |
| 211 |
| 212 | // TODO(liberato): Add PostOrCall(), to support cases where synchronous calls |
| 213 | // are okay if it's the same task runner. |
| 214 |
| 215 | // TODO(liberato): Add PostAndReply() |
| 216 |
| 217 | // TODO(liberato): Allow creation of callbacks that bind to a weak pointer, |
| 218 | // and thread-hop to |impl_task_runner_| if needed. |
| 219 |
| 220 | // Post destruction of any object we own, and return to the null state. |
| 221 | void Reset() { |
| 222 | if (is_null()) |
| 223 | return; |
| 224 |
| 225 | // Destruct the object on the impl thread. |
| 226 | impl_task_runner_->PostTask( |
| 227 | FROM_HERE, base::BindOnce(&DeleteOwnerRecord, base::Unretained(t_), |
| 228 | base::Unretained(storage_))); |
| 229 |
| 230 | impl_task_runner_ = nullptr; |
| 231 | t_ = nullptr; |
| 232 | storage_ = nullptr; |
| 233 | } |
| 234 |
| 235 | // Same as above, but allows the caller to provide a closure to be invoked |
| 236 | // immediately after destruction. The Closure is invoked on |
| 237 | // |impl_task_runner_|, iff the owned object was non-null. |
| 238 | void ResetWithCallbackAfterDestruction(base::OnceClosure callback) { |
| 239 | if (is_null()) |
| 240 | return; |
| 241 |
| 242 | impl_task_runner_->PostTask( |
| 243 | FROM_HERE, base::BindOnce( |
| 244 | [](base::OnceClosure callback, T* t, void* storage) { |
| 245 | DeleteOwnerRecord(t, storage); |
| 246 | std::move(callback).Run(); |
| 247 | }, |
| 248 | std::move(callback), t_, storage_)); |
| 249 |
| 250 | impl_task_runner_ = nullptr; |
| 251 | t_ = nullptr; |
| 252 | storage_ = nullptr; |
| 253 | } |
| 254 |
| 255 | // Return whether we own anything. Note that this does not guarantee that any |
| 256 | // previously owned object has been destroyed. In particular, it will return |
| 257 | // true immediately after a call to Reset(), though the underlying object |
| 258 | // might still be pending destruction on the impl thread. |
| 259 | bool is_null() const { return !t_; } |
| 260 |
| 261 | // True if and only if we have an object, with the same caveats as is_null(). |
| 262 | explicit operator bool() const { return !is_null(); } |
| 263 |
| 264 | private: |
| 265 | // Move everything from |other|, doing pointer adjustment as needed. |
| 266 | // This method is marked as NO_SANITIZE since (a) it might run before the |
| 267 | // posted ctor runs on |impl_task_runner_|, and (b) implicit conversions to |
| 268 | // non-virtual base classes are allowed before construction by the standard. |
| 269 | // See http://eel.is/c++draft/basic.life#6 for more information. |
| 270 | template <typename From> |
| 271 | void NO_SANITIZE("cfi-unrelated-cast") MoveRecordFrom(From&& other) { |
| 272 | // |other| might be is_null(), but that's okay. |
| 273 | impl_task_runner_ = std::move(other.impl_task_runner_); |
| 274 |
| 275 | // Note that static_cast<> isn't, in general, safe, since |other| might not |
| 276 | // be constructed yet. Implicit conversion is supported, as long as it |
| 277 | // doesn't convert to a virtual base. Of course, it allows only upcasts. |
| 278 | t_ = other.t_; |
| 279 |
| 280 | // The original storage is kept unmodified, so we can free it later. |
| 281 | storage_ = other.storage_; |
| 282 |
| 283 | other.storage_ = nullptr; |
| 284 | other.t_ = nullptr; |
| 285 | } |
| 286 |
| 287 | // Pointer to the object, Pointer may be modified on the owning thread. |
| 288 | T* t_ = nullptr; |
| 289 |
| 290 | // Original allocated storage for the object. |
| 291 | void* storage_ = nullptr; |
| 292 |
| 293 | // The task runner on which all access to |t_| should happen. |
| 294 | scoped_refptr<base::SequencedTaskRunner> impl_task_runner_; |
| 295 |
| 296 | // For move conversion. |
| 297 | template <typename U> |
| 298 | friend class SequenceBound; |
| 299 |
| 300 | // Run on impl thread to construct |t|'s storage. |
| 301 | template <typename... Args> |
| 302 | static void ConstructOwnerRecord(T* t, std::decay_t<Args>&&... args) { |
| 303 | new (t) T(std::move(args)...); |
| 304 | } |
| 305 |
| 306 | // Destruct the object associated with |t|, and delete |storage|. |
| 307 | static void DeleteOwnerRecord(T* t, void* storage) { |
| 308 | t->~T(); |
| 309 | AlignedFree(storage); |
| 310 | } |
| 311 |
| 312 | // To preserve ownership semantics, we disallow copy construction / copy |
| 313 | // assignment. Move construction / assignment is fine. |
| 314 | DISALLOW_COPY_AND_ASSIGN(SequenceBound); |
| 315 | }; |
| 316 |
| 317 | } // namespace base |
| 318 |
| 319 | #endif // BASE_THREADING_SEQUENCE_BOUND_H_ |
| 320 |