1 // Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2011 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 // This defines a set of argument wrappers and related factory methods that 32 // can be used specify the refcounting and reference semantics of arguments 33 // that are bound by the Bind() function in base/bind.h. 34 // 35 // It also defines a set of simple functions and utilities that people want 36 // when using Callback<> and Bind(). 37 // 38 // 39 // ARGUMENT BINDING WRAPPERS 40 // 41 // The wrapper functions are base::Unretained(), base::Owned(), base::Passed(), 42 // base::ConstRef(), and base::IgnoreResult(). 43 // 44 // Unretained() allows Bind() to bind a non-refcounted class, and to disable 45 // refcounting on arguments that are refcounted objects. 46 // 47 // Owned() transfers ownership of an object to the Callback resulting from 48 // bind; the object will be deleted when the Callback is deleted. 49 // 50 // Passed() is for transferring movable-but-not-copyable types (eg. scoped_ptr) 51 // through a Callback. Logically, this signifies a destructive transfer of 52 // the state of the argument into the target function. Invoking 53 // Callback::Run() twice on a Callback that was created with a Passed() 54 // argument will CHECK() because the first invocation would have already 55 // transferred ownership to the target function. 56 // 57 // ConstRef() allows binding a constant reference to an argument rather 58 // than a copy. 59 // 60 // IgnoreResult() is used to adapt a function or Callback with a return type to 61 // one with a void return. This is most useful if you have a function with, 62 // say, a pesky ignorable bool return that you want to use with PostTask or 63 // something else that expect a Callback with a void return. 64 // 65 // EXAMPLE OF Unretained(): 66 // 67 // class Foo { 68 // public: 69 // void func() { cout << "Foo:f" << endl; } 70 // }; 71 // 72 // // In some function somewhere. 73 // Foo foo; 74 // Closure foo_callback = 75 // Bind(&Foo::func, Unretained(&foo)); 76 // foo_callback.Run(); // Prints "Foo:f". 77 // 78 // Without the Unretained() wrapper on |&foo|, the above call would fail 79 // to compile because Foo does not support the AddRef() and Release() methods. 80 // 81 // 82 // EXAMPLE OF Owned(): 83 // 84 // void foo(int* arg) { cout << *arg << endl } 85 // 86 // int* pn = new int(1); 87 // Closure foo_callback = Bind(&foo, Owned(pn)); 88 // 89 // foo_callback.Run(); // Prints "1" 90 // foo_callback.Run(); // Prints "1" 91 // *n = 2; 92 // foo_callback.Run(); // Prints "2" 93 // 94 // foo_callback.Reset(); // |pn| is deleted. Also will happen when 95 // // |foo_callback| goes out of scope. 96 // 97 // Without Owned(), someone would have to know to delete |pn| when the last 98 // reference to the Callback is deleted. 99 // 100 // 101 // EXAMPLE OF ConstRef(): 102 // 103 // void foo(int arg) { cout << arg << endl } 104 // 105 // int n = 1; 106 // Closure no_ref = Bind(&foo, n); 107 // Closure has_ref = Bind(&foo, ConstRef(n)); 108 // 109 // no_ref.Run(); // Prints "1" 110 // has_ref.Run(); // Prints "1" 111 // 112 // n = 2; 113 // no_ref.Run(); // Prints "1" 114 // has_ref.Run(); // Prints "2" 115 // 116 // Note that because ConstRef() takes a reference on |n|, |n| must outlive all 117 // its bound callbacks. 118 // 119 // 120 // EXAMPLE OF IgnoreResult(): 121 // 122 // int DoSomething(int arg) { cout << arg << endl; } 123 // 124 // // Assign to a Callback with a void return type. 125 // Callback<void(int)> cb = Bind(IgnoreResult(&DoSomething)); 126 // cb->Run(1); // Prints "1". 127 // 128 // // Prints "1" on |ml|. 129 // ml->PostTask(FROM_HERE, Bind(IgnoreResult(&DoSomething), 1); 130 // 131 // 132 // EXAMPLE OF Passed(): 133 // 134 // void TakesOwnership(scoped_ptr<Foo> arg) { } 135 // scoped_ptr<Foo> CreateFoo() { return scoped_ptr<Foo>(new Foo()); } 136 // 137 // scoped_ptr<Foo> f(new Foo()); 138 // 139 // // |cb| is given ownership of Foo(). |f| is now NULL. 140 // // You can use f.Pass() in place of &f, but it's more verbose. 141 // Closure cb = Bind(&TakesOwnership, Passed(&f)); 142 // 143 // // Run was never called so |cb| still owns Foo() and deletes 144 // // it on Reset(). 145 // cb.Reset(); 146 // 147 // // |cb| is given a new Foo created by CreateFoo(). 148 // cb = Bind(&TakesOwnership, Passed(CreateFoo())); 149 // 150 // // |arg| in TakesOwnership() is given ownership of Foo(). |cb| 151 // // no longer owns Foo() and, if reset, would not delete Foo(). 152 // cb.Run(); // Foo() is now transferred to |arg| and deleted. 153 // cb.Run(); // This CHECK()s since Foo() already been used once. 154 // 155 // Passed() is particularly useful with PostTask() when you are transferring 156 // ownership of an argument into a task, but don't necessarily know if the 157 // task will always be executed. This can happen if the task is cancellable 158 // or if it is posted to a MessageLoopProxy. 159 // 160 // 161 // SIMPLE FUNCTIONS AND UTILITIES. 162 // 163 // DoNothing() - Useful for creating a Closure that does nothing when called. 164 // DeletePointer<T>() - Useful for creating a Closure that will delete a 165 // pointer when invoked. Only use this when necessary. 166 // In most cases MessageLoop::DeleteSoon() is a better 167 // fit. 168 169 #ifndef CEF_INCLUDE_BASE_CEF_BIND_HELPERS_H_ 170 #define CEF_INCLUDE_BASE_CEF_BIND_HELPERS_H_ 171 #pragma once 172 173 #if defined(BASE_BIND_HELPERS_H_) 174 // Do nothing if the Chromium header has already been included. 175 // This can happen in cases where Chromium code is used directly by the 176 // client application. When using Chromium code directly always include 177 // the Chromium header first to avoid type conflicts. 178 #elif defined(USING_CHROMIUM_INCLUDES) 179 // When building CEF include the Chromium header directly. 180 #include "base/bind_helpers.h" 181 #else // !USING_CHROMIUM_INCLUDES 182 // The following is substantially similar to the Chromium implementation. 183 // If the Chromium implementation diverges the below implementation should be 184 // updated to match. 185 186 #include "include/base/cef_basictypes.h" 187 #include "include/base/cef_callback.h" 188 #include "include/base/cef_template_util.h" 189 #include "include/base/cef_weak_ptr.h" 190 191 namespace base { 192 namespace cef_internal { 193 194 // Use the Substitution Failure Is Not An Error (SFINAE) trick to inspect T 195 // for the existence of AddRef() and Release() functions of the correct 196 // signature. 197 // 198 // http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error 199 // http://stackoverflow.com/questions/257288/is-it-possible-to-write-a-c-template-to-check-for-a-functions-existence 200 // http://stackoverflow.com/questions/4358584/sfinae-approach-comparison 201 // http://stackoverflow.com/questions/1966362/sfinae-to-check-for-inherited-member-functions 202 // 203 // The last link in particular show the method used below. 204 // 205 // For SFINAE to work with inherited methods, we need to pull some extra tricks 206 // with multiple inheritance. In the more standard formulation, the overloads 207 // of Check would be: 208 // 209 // template <typename C> 210 // Yes NotTheCheckWeWant(Helper<&C::TargetFunc>*); 211 // 212 // template <typename C> 213 // No NotTheCheckWeWant(...); 214 // 215 // static const bool value = sizeof(NotTheCheckWeWant<T>(0)) == sizeof(Yes); 216 // 217 // The problem here is that template resolution will not match 218 // C::TargetFunc if TargetFunc does not exist directly in C. That is, if 219 // TargetFunc in inherited from an ancestor, &C::TargetFunc will not match, 220 // |value| will be false. This formulation only checks for whether or 221 // not TargetFunc exist directly in the class being introspected. 222 // 223 // To get around this, we play a dirty trick with multiple inheritance. 224 // First, We create a class BaseMixin that declares each function that we 225 // want to probe for. Then we create a class Base that inherits from both T 226 // (the class we wish to probe) and BaseMixin. Note that the function 227 // signature in BaseMixin does not need to match the signature of the function 228 // we are probing for; thus it's easiest to just use void(void). 229 // 230 // Now, if TargetFunc exists somewhere in T, then &Base::TargetFunc has an 231 // ambiguous resolution between BaseMixin and T. This lets us write the 232 // following: 233 // 234 // template <typename C> 235 // No GoodCheck(Helper<&C::TargetFunc>*); 236 // 237 // template <typename C> 238 // Yes GoodCheck(...); 239 // 240 // static const bool value = sizeof(GoodCheck<Base>(0)) == sizeof(Yes); 241 // 242 // Notice here that the variadic version of GoodCheck() returns Yes here 243 // instead of No like the previous one. Also notice that we calculate |value| 244 // by specializing GoodCheck() on Base instead of T. 245 // 246 // We've reversed the roles of the variadic, and Helper overloads. 247 // GoodCheck(Helper<&C::TargetFunc>*), when C = Base, fails to be a valid 248 // substitution if T::TargetFunc exists. Thus GoodCheck<Base>(0) will resolve 249 // to the variadic version if T has TargetFunc. If T::TargetFunc does not 250 // exist, then &C::TargetFunc is not ambiguous, and the overload resolution 251 // will prefer GoodCheck(Helper<&C::TargetFunc>*). 252 // 253 // This method of SFINAE will correctly probe for inherited names, but it cannot 254 // typecheck those names. It's still a good enough sanity check though. 255 // 256 // Works on gcc-4.2, gcc-4.4, and Visual Studio 2008. 257 // 258 // TODO(ajwong): Move to ref_counted.h or template_util.h when we've vetted 259 // this works well. 260 // 261 // TODO(ajwong): Make this check for Release() as well. 262 // See http://crbug.com/82038. 263 template <typename T> 264 class SupportsAddRefAndRelease { 265 typedef char Yes[1]; 266 typedef char No[2]; 267 268 struct BaseMixin { 269 void AddRef(); 270 }; 271 272 // MSVC warns when you try to use Base if T has a private destructor, the 273 // common pattern for refcounted types. It does this even though no attempt to 274 // instantiate Base is made. We disable the warning for this definition. 275 #if defined(OS_WIN) 276 #pragma warning(push) 277 #pragma warning(disable : 4624) 278 #endif 279 struct Base : public T, public BaseMixin {}; 280 #if defined(OS_WIN) 281 #pragma warning(pop) 282 #endif 283 284 template <void (BaseMixin::*)(void)> 285 struct Helper {}; 286 287 template <typename C> 288 static No& Check(Helper<&C::AddRef>*); 289 290 template <typename> 291 static Yes& Check(...); 292 293 public: 294 static const bool value = sizeof(Check<Base>(0)) == sizeof(Yes); 295 }; 296 297 // Helpers to assert that arguments of a recounted type are bound with a 298 // scoped_refptr. 299 template <bool IsClasstype, typename T> 300 struct UnsafeBindtoRefCountedArgHelper : false_type {}; 301 302 template <typename T> 303 struct UnsafeBindtoRefCountedArgHelper<true, T> 304 : integral_constant<bool, SupportsAddRefAndRelease<T>::value> {}; 305 306 template <typename T> 307 struct UnsafeBindtoRefCountedArg : false_type {}; 308 309 template <typename T> 310 struct UnsafeBindtoRefCountedArg<T*> 311 : UnsafeBindtoRefCountedArgHelper<is_class<T>::value, T> {}; 312 313 template <typename T> 314 class HasIsMethodTag { 315 typedef char Yes[1]; 316 typedef char No[2]; 317 318 template <typename U> 319 static Yes& Check(typename U::IsMethod*); 320 321 template <typename U> 322 static No& Check(...); 323 324 public: 325 static const bool value = sizeof(Check<T>(0)) == sizeof(Yes); 326 }; 327 328 template <typename T> 329 class UnretainedWrapper { 330 public: 331 explicit UnretainedWrapper(T* o) : ptr_(o) {} 332 T* get() const { return ptr_; } 333 334 private: 335 T* ptr_; 336 }; 337 338 template <typename T> 339 class ConstRefWrapper { 340 public: 341 explicit ConstRefWrapper(const T& o) : ptr_(&o) {} 342 const T& get() const { return *ptr_; } 343 344 private: 345 const T* ptr_; 346 }; 347 348 template <typename T> 349 struct IgnoreResultHelper { 350 explicit IgnoreResultHelper(T functor) : functor_(functor) {} 351 352 T functor_; 353 }; 354 355 template <typename T> 356 struct IgnoreResultHelper<Callback<T>> { 357 explicit IgnoreResultHelper(const Callback<T>& functor) : functor_(functor) {} 358 359 const Callback<T>& functor_; 360 }; 361 362 // An alternate implementation is to avoid the destructive copy, and instead 363 // specialize ParamTraits<> for OwnedWrapper<> to change the StorageType to 364 // a class that is essentially a scoped_ptr<>. 365 // 366 // The current implementation has the benefit though of leaving ParamTraits<> 367 // fully in callback_internal.h as well as avoiding type conversions during 368 // storage. 369 template <typename T> 370 class OwnedWrapper { 371 public: 372 explicit OwnedWrapper(T* o) : ptr_(o) {} 373 ~OwnedWrapper() { delete ptr_; } 374 T* get() const { return ptr_; } 375 OwnedWrapper(const OwnedWrapper& other) { 376 ptr_ = other.ptr_; 377 other.ptr_ = NULL; 378 } 379 380 private: 381 mutable T* ptr_; 382 }; 383 384 // PassedWrapper is a copyable adapter for a scoper that ignores const. 385 // 386 // It is needed to get around the fact that Bind() takes a const reference to 387 // all its arguments. Because Bind() takes a const reference to avoid 388 // unnecessary copies, it is incompatible with movable-but-not-copyable 389 // types; doing a destructive "move" of the type into Bind() would violate 390 // the const correctness. 391 // 392 // This conundrum cannot be solved without either C++11 rvalue references or 393 // a O(2^n) blowup of Bind() templates to handle each combination of regular 394 // types and movable-but-not-copyable types. Thus we introduce a wrapper type 395 // that is copyable to transmit the correct type information down into 396 // BindState<>. Ignoring const in this type makes sense because it is only 397 // created when we are explicitly trying to do a destructive move. 398 // 399 // Two notes: 400 // 1) PassedWrapper supports any type that has a "Pass()" function. 401 // This is intentional. The whitelisting of which specific types we 402 // support is maintained by CallbackParamTraits<>. 403 // 2) is_valid_ is distinct from NULL because it is valid to bind a "NULL" 404 // scoper to a Callback and allow the Callback to execute once. 405 template <typename T> 406 class PassedWrapper { 407 public: 408 explicit PassedWrapper(T scoper) : is_valid_(true), scoper_(scoper.Pass()) {} 409 PassedWrapper(const PassedWrapper& other) 410 : is_valid_(other.is_valid_), scoper_(other.scoper_.Pass()) {} 411 T Pass() const { 412 CHECK(is_valid_); 413 is_valid_ = false; 414 return scoper_.Pass(); 415 } 416 417 private: 418 mutable bool is_valid_; 419 mutable T scoper_; 420 }; 421 422 // Unwrap the stored parameters for the wrappers above. 423 template <typename T> 424 struct UnwrapTraits { 425 typedef const T& ForwardType; 426 static ForwardType Unwrap(const T& o) { return o; } 427 }; 428 429 template <typename T> 430 struct UnwrapTraits<UnretainedWrapper<T>> { 431 typedef T* ForwardType; 432 static ForwardType Unwrap(UnretainedWrapper<T> unretained) { 433 return unretained.get(); 434 } 435 }; 436 437 template <typename T> 438 struct UnwrapTraits<ConstRefWrapper<T>> { 439 typedef const T& ForwardType; 440 static ForwardType Unwrap(ConstRefWrapper<T> const_ref) { 441 return const_ref.get(); 442 } 443 }; 444 445 template <typename T> 446 struct UnwrapTraits<scoped_refptr<T>> { 447 typedef T* ForwardType; 448 static ForwardType Unwrap(const scoped_refptr<T>& o) { return o.get(); } 449 }; 450 451 template <typename T> 452 struct UnwrapTraits<WeakPtr<T>> { 453 typedef const WeakPtr<T>& ForwardType; 454 static ForwardType Unwrap(const WeakPtr<T>& o) { return o; } 455 }; 456 457 template <typename T> 458 struct UnwrapTraits<OwnedWrapper<T>> { 459 typedef T* ForwardType; 460 static ForwardType Unwrap(const OwnedWrapper<T>& o) { return o.get(); } 461 }; 462 463 template <typename T> 464 struct UnwrapTraits<PassedWrapper<T>> { 465 typedef T ForwardType; 466 static T Unwrap(PassedWrapper<T>& o) { return o.Pass(); } 467 }; 468 469 // Utility for handling different refcounting semantics in the Bind() 470 // function. 471 template <bool is_method, typename T> 472 struct MaybeRefcount; 473 474 template <typename T> 475 struct MaybeRefcount<false, T> { 476 static void AddRef(const T&) {} 477 static void Release(const T&) {} 478 }; 479 480 template <typename T, size_t n> 481 struct MaybeRefcount<false, T[n]> { 482 static void AddRef(const T*) {} 483 static void Release(const T*) {} 484 }; 485 486 template <typename T> 487 struct MaybeRefcount<true, T> { 488 static void AddRef(const T&) {} 489 static void Release(const T&) {} 490 }; 491 492 template <typename T> 493 struct MaybeRefcount<true, T*> { 494 static void AddRef(T* o) { o->AddRef(); } 495 static void Release(T* o) { o->Release(); } 496 }; 497 498 // No need to additionally AddRef() and Release() since we are storing a 499 // scoped_refptr<> inside the storage object already. 500 template <typename T> 501 struct MaybeRefcount<true, scoped_refptr<T>> { 502 static void AddRef(const scoped_refptr<T>& o) {} 503 static void Release(const scoped_refptr<T>& o) {} 504 }; 505 506 template <typename T> 507 struct MaybeRefcount<true, const T*> { 508 static void AddRef(const T* o) { o->AddRef(); } 509 static void Release(const T* o) { o->Release(); } 510 }; 511 512 // IsWeakMethod is a helper that determine if we are binding a WeakPtr<> to a 513 // method. It is used internally by Bind() to select the correct 514 // InvokeHelper that will no-op itself in the event the WeakPtr<> for 515 // the target object is invalidated. 516 // 517 // P1 should be the type of the object that will be received of the method. 518 template <bool IsMethod, typename P1> 519 struct IsWeakMethod : public false_type {}; 520 521 template <typename T> 522 struct IsWeakMethod<true, WeakPtr<T>> : public true_type {}; 523 524 template <typename T> 525 struct IsWeakMethod<true, ConstRefWrapper<WeakPtr<T>>> : public true_type {}; 526 527 } // namespace cef_internal 528 529 template <typename T> 530 static inline cef_internal::UnretainedWrapper<T> Unretained(T* o) { 531 return cef_internal::UnretainedWrapper<T>(o); 532 } 533 534 template <typename T> 535 static inline cef_internal::ConstRefWrapper<T> ConstRef(const T& o) { 536 return cef_internal::ConstRefWrapper<T>(o); 537 } 538 539 template <typename T> 540 static inline cef_internal::OwnedWrapper<T> Owned(T* o) { 541 return cef_internal::OwnedWrapper<T>(o); 542 } 543 544 // We offer 2 syntaxes for calling Passed(). The first takes a temporary and 545 // is best suited for use with the return value of a function. The second 546 // takes a pointer to the scoper and is just syntactic sugar to avoid having 547 // to write Passed(scoper.Pass()). 548 template <typename T> 549 static inline cef_internal::PassedWrapper<T> Passed(T scoper) { 550 return cef_internal::PassedWrapper<T>(scoper.Pass()); 551 } 552 template <typename T> 553 static inline cef_internal::PassedWrapper<T> Passed(T* scoper) { 554 return cef_internal::PassedWrapper<T>(scoper->Pass()); 555 } 556 557 template <typename T> 558 static inline cef_internal::IgnoreResultHelper<T> IgnoreResult(T data) { 559 return cef_internal::IgnoreResultHelper<T>(data); 560 } 561 562 template <typename T> 563 static inline cef_internal::IgnoreResultHelper<Callback<T>> IgnoreResult( 564 const Callback<T>& data) { 565 return cef_internal::IgnoreResultHelper<Callback<T>>(data); 566 } 567 568 void DoNothing(); 569 570 template <typename T> 571 void DeletePointer(T* obj) { 572 delete obj; 573 } 574 575 } // namespace base 576 577 #endif // !USING_CHROMIUM_INCLUDES 578 579 #endif // CEF_INCLUDE_BASE_CEF_BIND_HELPERS_H_ 580