• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2011 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 #ifndef BASE_FUNCTIONAL_BIND_INTERNAL_H_
6 #define BASE_FUNCTIONAL_BIND_INTERNAL_H_
7 
8 #include <stddef.h>
9 
10 #include <functional>
11 #include <memory>
12 #include <tuple>
13 #include <type_traits>
14 #include <utility>
15 
16 #include "base/allocator/partition_allocator/partition_alloc_buildflags.h"
17 #include "base/allocator/partition_allocator/partition_alloc_config.h"
18 #include "base/allocator/partition_allocator/pointers/raw_ptr.h"
19 #include "base/check.h"
20 #include "base/compiler_specific.h"
21 #include "base/functional/callback_internal.h"
22 #include "base/functional/disallow_unretained.h"
23 #include "base/functional/unretained_traits.h"
24 #include "base/memory/raw_ptr.h"
25 #include "base/memory/raw_ptr_asan_bound_arg_tracker.h"
26 #include "base/memory/raw_ptr_asan_service.h"
27 #include "base/memory/raw_ref.h"
28 #include "base/memory/raw_scoped_refptr_mismatch_checker.h"
29 #include "base/memory/weak_ptr.h"
30 #include "base/notreached.h"
31 #include "base/types/always_false.h"
32 #include "build/build_config.h"
33 #include "third_party/abseil-cpp/absl/functional/function_ref.h"
34 
35 #if BUILDFLAG(IS_APPLE) && !HAS_FEATURE(objc_arc)
36 #include "base/mac/scoped_block.h"
37 #endif
38 
39 // See base/functional/callback.h for user documentation.
40 //
41 //
42 // CONCEPTS:
43 //  Functor -- A movable type representing something that should be called.
44 //             All function pointers and Callback<> are functors even if the
45 //             invocation syntax differs.
46 //  RunType -- A function type (as opposed to function _pointer_ type) for
47 //             a Callback<>::Run().  Usually just a convenience typedef.
48 //  (Bound)Args -- A set of types that stores the arguments.
49 //
50 // Types:
51 //  ForceVoidReturn<> -- Helper class for translating function signatures to
52 //                       equivalent forms with a "void" return type.
53 //  FunctorTraits<> -- Type traits used to determine the correct RunType and
54 //                     invocation manner for a Functor.  This is where function
55 //                     signature adapters are applied.
56 //  StorageTraits<> -- Type traits that determine how a bound argument is
57 //                     stored in BindState.
58 //  InvokeHelper<> -- Take a Functor + arguments and actually invokes it.
59 //                    Handle the differing syntaxes needed for WeakPtr<>
60 //                    support.  This is separate from Invoker to avoid creating
61 //                    multiple version of Invoker<>.
62 //  Invoker<> -- Unwraps the curried parameters and executes the Functor.
63 //  BindState<> -- Stores the curried parameters, and is the main entry point
64 //                 into the Bind() system.
65 
66 #if BUILDFLAG(IS_WIN)
67 namespace Microsoft {
68 namespace WRL {
69 template <typename>
70 class ComPtr;
71 }  // namespace WRL
72 }  // namespace Microsoft
73 #endif
74 
75 namespace base {
76 
77 template <typename T>
78 struct IsWeakReceiver;
79 
80 template <typename>
81 struct BindUnwrapTraits;
82 
83 template <typename Functor, typename BoundArgsTuple, typename SFINAE = void>
84 struct CallbackCancellationTraits;
85 
86 template <typename Signature>
87 class FunctionRef;
88 
89 namespace unretained_traits {
90 
91 // UnretainedWrapper will check and report if pointer is dangling upon
92 // invocation.
93 struct MayNotDangle {};
94 // UnretainedWrapper won't check if pointer is dangling upon invocation. For
95 // extra safety, the receiver must be of type MayBeDangling<>.
96 struct MayDangle {};
97 // UnretainedWrapper won't check if pointer is dangling upon invocation. The
98 // receiver doesn't have to be a raw_ptr<>. This is just a temporary state, to
99 // allow dangling pointers that would otherwise crash if MayNotDangle was used.
100 // It should be replaced ASAP with MayNotDangle (after fixing the dangling
101 // pointers) or with MayDangle if there is really no other way (after making
102 // receivers MayBeDangling<>).
103 struct MayDangleUntriaged {};
104 
105 }  // namespace unretained_traits
106 
107 namespace internal {
108 
109 template <typename Functor, typename SFINAE = void>
110 struct FunctorTraits;
111 
112 template <typename T,
113           typename UnretainedTrait,
114           RawPtrTraits PtrTraits = RawPtrTraits::kEmpty>
115 class UnretainedWrapper {
116   // Note that if PtrTraits already includes MayDangle, DanglingRawPtrType
117   // will be identical to `raw_ptr<T, PtrTraits>`.
118   using DanglingRawPtrType = MayBeDangling<T, PtrTraits>;
119 
120  public:
121   // We want the getter type to match the receiver parameter that it is passed
122   // into, to minimize `raw_ptr<T>` <-> `T*` conversions. We also would like to
123   // match `StorageType`, but sometimes we can't have both, as shown in
124   // https://docs.google.com/document/d/1dLM34aKqbNBfRdOYxxV_T-zQU4J5wjmXwIBJZr7JvZM/edit
125   // When we can't have both, prefer the former, mostly because
126   // `GetPtrType`=`raw_ptr<T>` would break if e.g. UnretainedWrapper() is
127   // constructed using `char*`, but the receiver is of type `std::string&`.
128   // This is enforced by static_asserts in base::internal::AssertConstructible.
129   using GetPtrType = std::conditional_t<
130       raw_ptr_traits::IsSupportedType<T>::value &&
131           std::is_same_v<UnretainedTrait, unretained_traits::MayDangle>,
132       DanglingRawPtrType,
133       T*>;
134 
135   static_assert(TypeSupportsUnretainedV<T>,
136                 "Callback cannot capture an unprotected C++ pointer since this "
137                 "Type is annotated with DISALLOW_UNRETAINED(). Please see "
138                 "base/functional/disallow_unretained.h for alternatives.");
139 
140   // Raw pointer makes sense only if there are no PtrTraits. If there are,
141   // it means that a `raw_ptr` is being passed, so use the ctors below instead.
142   template <RawPtrTraits PTraits = PtrTraits,
143             typename = std::enable_if_t<PTraits == RawPtrTraits::kEmpty>>
UnretainedWrapper(T * o)144   explicit UnretainedWrapper(T* o) : ptr_(o) {}
145 
146   // Trick to only instantiate these constructors if they are used. Otherwise,
147   // instantiating UnretainedWrapper with a T that is not supported by
148   // raw_ptr would trigger raw_ptr<T>'s static_assert.
149   template <typename U = T>
UnretainedWrapper(const raw_ptr<U,PtrTraits> & o)150   explicit UnretainedWrapper(const raw_ptr<U, PtrTraits>& o) : ptr_(o) {}
151   template <typename U = T>
UnretainedWrapper(raw_ptr<U,PtrTraits> && o)152   explicit UnretainedWrapper(raw_ptr<U, PtrTraits>&& o) : ptr_(std::move(o)) {}
153 
get()154   GetPtrType get() const { return GetInternal(ptr_); }
155 
156  private:
157   // `ptr_` is either a `raw_ptr` or a regular C++ pointer.
158   template <typename U>
GetInternal(U * ptr)159   static GetPtrType GetInternal(U* ptr) {
160     static_assert(std::is_same_v<T, U>);
161     return ptr;
162   }
163   template <typename U, RawPtrTraits Traits>
GetInternal(const raw_ptr<U,Traits> & ptr)164   static GetPtrType GetInternal(const raw_ptr<U, Traits>& ptr) {
165     static_assert(std::is_same_v<T, U>);
166     if constexpr (std::is_same_v<UnretainedTrait,
167                                  unretained_traits::MayNotDangle>) {
168       ptr.ReportIfDangling();
169     }
170     return ptr;
171   }
172 
173   // `Unretained()` arguments often dangle by design (a common design pattern
174   // is to manage an object's lifetime inside the callback itself, using
175   // stateful information), so disable direct dangling pointer detection
176   // of `ptr_`.
177   //
178   // If the callback is invoked, dangling pointer detection will be triggered
179   // before invoking the bound functor (unless stated otherwise, see
180   // `UnsafeDangling()` and `UnsafeDanglingUntriaged()`), when retrieving the
181   // pointer value via `get()` above.
182   using StorageType =
183       std::conditional_t<raw_ptr_traits::IsSupportedType<T>::value,
184                          DanglingRawPtrType,
185                          T*>;
186   // Avoid converting between different `raw_ptr` types when calling `get()`.
187   // It is allowable to convert `raw_ptr<T>` -> `T*`, but not in the other
188   // direction. See the comment by `GetPtrType` describing for more details.
189   static_assert(std::is_pointer_v<GetPtrType> ||
190                 std::is_same_v<GetPtrType, StorageType>);
191   StorageType ptr_;
192 };
193 
194 // Storage type for std::reference_wrapper so `BindState` can internally store
195 // unprotected references using raw_ref.
196 //
197 // std::reference_wrapper<T> and T& do not work, since the reference lifetime is
198 // not safely protected by MiraclePtr.
199 //
200 // UnretainedWrapper<T> and raw_ptr<T> do not work, since BindUnwrapTraits would
201 // try to pass by T* rather than T&.
202 template <typename T,
203           typename UnretainedTrait,
204           RawPtrTraits PtrTraits = RawPtrTraits::kEmpty>
205 class UnretainedRefWrapper {
206  public:
207   static_assert(
208       TypeSupportsUnretainedV<T>,
209       "Callback cannot capture an unprotected C++ reference since this "
210       "type is annotated with DISALLOW_UNRETAINED(). Please see "
211       "base/functional/disallow_unretained.h for alternatives.");
212 
213   // Raw reference makes sense only if there are no PtrTraits. If there are,
214   // it means that a `raw_ref` is being passed, so use the ctors below instead.
215   template <RawPtrTraits PTraits = PtrTraits,
216             typename = std::enable_if_t<PTraits == RawPtrTraits::kEmpty>>
UnretainedRefWrapper(T & o)217   explicit UnretainedRefWrapper(T& o) : ref_(o) {}
218 
219   // Trick to only instantiate these constructors if they are used. Otherwise,
220   // instantiating UnretainedWrapper with a T that is not supported by
221   // raw_ref would trigger raw_ref<T>'s static_assert.
222   template <typename U = T>
UnretainedRefWrapper(const raw_ref<U,PtrTraits> & o)223   explicit UnretainedRefWrapper(const raw_ref<U, PtrTraits>& o) : ref_(o) {}
224   template <typename U = T>
UnretainedRefWrapper(raw_ref<U,PtrTraits> && o)225   explicit UnretainedRefWrapper(raw_ref<U, PtrTraits>&& o)
226       : ref_(std::move(o)) {}
227 
get()228   T& get() const { return GetInternal(ref_); }
229 
230  private:
231   // `ref_` is either a `raw_ref` or a regular C++ reference.
232   template <typename U>
GetInternal(U & ref)233   static T& GetInternal(U& ref) {
234     static_assert(std::is_same_v<T, U>);
235     return ref;
236   }
237   template <typename U, RawPtrTraits Traits>
GetInternal(const raw_ref<U,Traits> & ref)238   static T& GetInternal(const raw_ref<U, Traits>& ref) {
239     static_assert(std::is_same_v<T, U>);
240     // The ultimate goal is to crash when a callback is invoked with a
241     // dangling pointer. This is checked here. For now, it is configured to
242     // either crash, DumpWithoutCrashing or be ignored. This depends on the
243     // PartitionAllocUnretainedDanglingPtr feature.
244     if constexpr (std::is_same_v<UnretainedTrait,
245                                  unretained_traits::MayNotDangle>) {
246       ref.ReportIfDangling();
247     }
248     // We can't use operator* here, we need to use raw_ptr's GetForExtraction
249     // instead of GetForDereference. If we did use GetForDereference then we'd
250     // crash in ASAN builds on calling a bound callback with a dangling
251     // reference parameter even if that parameter is not used. This could hide
252     // a later unprotected issue that would be reached in release builds.
253     return ref.get();
254   }
255 
256   // `Unretained()` arguments often dangle by design (a common design pattern
257   // is to manage an object's lifetime inside the callback itself, using
258   // stateful information), so disable direct dangling pointer detection
259   // of `ref_`.
260   //
261   // If the callback is invoked, dangling pointer detection will be triggered
262   // before invoking the bound functor (unless stated otherwise, see
263   // `UnsafeDangling()` and `UnsafeDanglingUntriaged()`), when retrieving the
264   // pointer value via `get()` above.
265   using StorageType =
266       std::conditional_t<raw_ptr_traits::IsSupportedType<T>::value,
267                          raw_ref<T, DisableDanglingPtrDetection>,
268                          T&>;
269 
270   StorageType ref_;
271 };
272 
273 // The class is used to wrap `UnretainedRefWrapper` when the latter is used as
274 // a method receiver (a reference on `this` argument). This is needed because
275 // the internal callback mechanism expects the receiver to have the type
276 // `MyClass*` and to have `operator*`.
277 // This is used as storage.
278 template <typename T, typename UnretainedTrait, RawPtrTraits PtrTraits>
279 class UnretainedRefWrapperReceiver {
280  public:
281   // NOLINTNEXTLINE(google-explicit-constructor)
UnretainedRefWrapperReceiver(UnretainedRefWrapper<T,UnretainedTrait,PtrTraits> && o)282   UnretainedRefWrapperReceiver(
283       UnretainedRefWrapper<T, UnretainedTrait, PtrTraits>&& o)
284       : obj_(std::move(o)) {}
285   // NOLINTNEXTLINE(google-explicit-constructor)
286   T& operator*() const { return obj_.get(); }
287 
288  private:
289   UnretainedRefWrapper<T, UnretainedTrait, PtrTraits> obj_;
290 };
291 
292 // MethodReceiverStorageType converts the current receiver type to its stored
293 // type. For instance, it converts pointers to `scoped_refptr`, and wraps
294 // `UnretainedRefWrapper` to make it compliant with the internal callback
295 // invocation mechanism.
296 template <typename T>
297 struct MethodReceiverStorageType {
298   using Type =
299       std::conditional_t<IsPointerV<T>, scoped_refptr<RemovePointerT<T>>, T>;
300 };
301 
302 template <typename T, typename UnretainedTrait, RawPtrTraits PtrTraits>
303 struct MethodReceiverStorageType<
304     UnretainedRefWrapper<T, UnretainedTrait, PtrTraits>> {
305   // We can't use UnretainedRefWrapper as a receiver directly (see
306   // UnretainedRefWrapperReceiver for why).
307   using Type = UnretainedRefWrapperReceiver<T, UnretainedTrait, PtrTraits>;
308 };
309 
310 template <typename T>
311 class RetainedRefWrapper {
312  public:
313   explicit RetainedRefWrapper(T* o) : ptr_(o) {}
314   explicit RetainedRefWrapper(scoped_refptr<T> o) : ptr_(std::move(o)) {}
315   T* get() const { return ptr_.get(); }
316 
317  private:
318   scoped_refptr<T> ptr_;
319 };
320 
321 template <typename T>
322 struct IgnoreResultHelper {
323   explicit IgnoreResultHelper(T functor) : functor_(std::move(functor)) {}
324   explicit operator bool() const { return !!functor_; }
325 
326   T functor_;
327 };
328 
329 template <typename T, typename Deleter = std::default_delete<T>>
330 class OwnedWrapper {
331  public:
332   explicit OwnedWrapper(T* o) : ptr_(o) {}
333   explicit OwnedWrapper(std::unique_ptr<T, Deleter>&& ptr)
334       : ptr_(std::move(ptr)) {}
335   T* get() const { return ptr_.get(); }
336 
337  private:
338   std::unique_ptr<T, Deleter> ptr_;
339 };
340 
341 template <typename T>
342 class OwnedRefWrapper {
343  public:
344   explicit OwnedRefWrapper(const T& t) : t_(t) {}
345   explicit OwnedRefWrapper(T&& t) : t_(std::move(t)) {}
346   T& get() const { return t_; }
347 
348  private:
349   mutable T t_;
350 };
351 
352 // PassedWrapper is a copyable adapter for a scoper that ignores const.
353 //
354 // It is needed to get around the fact that Bind() takes a const reference to
355 // all its arguments.  Because Bind() takes a const reference to avoid
356 // unnecessary copies, it is incompatible with movable-but-not-copyable
357 // types; doing a destructive "move" of the type into Bind() would violate
358 // the const correctness.
359 //
360 // This conundrum cannot be solved without either C++11 rvalue references or
361 // a O(2^n) blowup of Bind() templates to handle each combination of regular
362 // types and movable-but-not-copyable types.  Thus we introduce a wrapper type
363 // that is copyable to transmit the correct type information down into
364 // BindState<>. Ignoring const in this type makes sense because it is only
365 // created when we are explicitly trying to do a destructive move.
366 //
367 // Two notes:
368 //  1) PassedWrapper supports any type that has a move constructor, however
369 //     the type will need to be specifically allowed in order for it to be
370 //     bound to a Callback. We guard this explicitly at the call of Passed()
371 //     to make for clear errors. Things not given to Passed() will be forwarded
372 //     and stored by value which will not work for general move-only types.
373 //  2) is_valid_ is distinct from NULL because it is valid to bind a "NULL"
374 //     scoper to a Callback and allow the Callback to execute once.
375 template <typename T>
376 class PassedWrapper {
377  public:
378   explicit PassedWrapper(T&& scoper) : scoper_(std::move(scoper)) {}
379   PassedWrapper(PassedWrapper&& other)
380       : is_valid_(other.is_valid_), scoper_(std::move(other.scoper_)) {}
381   T Take() const {
382     CHECK(is_valid_);
383     is_valid_ = false;
384     return std::move(scoper_);
385   }
386 
387  private:
388   mutable bool is_valid_ = true;
389   mutable T scoper_;
390 };
391 
392 template <typename T>
393 using Unwrapper = BindUnwrapTraits<std::decay_t<T>>;
394 
395 template <typename T>
396 decltype(auto) Unwrap(T&& o) {
397   return Unwrapper<T>::Unwrap(std::forward<T>(o));
398 }
399 
400 // IsWeakMethod is a helper that determine if we are binding a WeakPtr<> to a
401 // method.  It is used internally by Bind() to select the correct
402 // InvokeHelper that will no-op itself in the event the WeakPtr<> for
403 // the target object is invalidated.
404 //
405 // The first argument should be the type of the object that will be received by
406 // the method.
407 template <bool is_method, typename... Args>
408 struct IsWeakMethod : std::false_type {};
409 
410 template <typename T, typename... Args>
411 struct IsWeakMethod<true, T, Args...> : IsWeakReceiver<T> {};
412 
413 // Packs a list of types to hold them in a single type.
414 template <typename... Types>
415 struct TypeList {};
416 
417 // Used for DropTypeListItem implementation.
418 template <size_t n, typename List>
419 struct DropTypeListItemImpl;
420 
421 // Do not use enable_if and SFINAE here to avoid MSVC2013 compile failure.
422 template <size_t n, typename T, typename... List>
423 struct DropTypeListItemImpl<n, TypeList<T, List...>>
424     : DropTypeListItemImpl<n - 1, TypeList<List...>> {};
425 
426 template <typename T, typename... List>
427 struct DropTypeListItemImpl<0, TypeList<T, List...>> {
428   using Type = TypeList<T, List...>;
429 };
430 
431 template <>
432 struct DropTypeListItemImpl<0, TypeList<>> {
433   using Type = TypeList<>;
434 };
435 
436 // A type-level function that drops |n| list item from given TypeList.
437 template <size_t n, typename List>
438 using DropTypeListItem = typename DropTypeListItemImpl<n, List>::Type;
439 
440 // Used for TakeTypeListItem implementation.
441 template <size_t n, typename List, typename... Accum>
442 struct TakeTypeListItemImpl;
443 
444 // Do not use enable_if and SFINAE here to avoid MSVC2013 compile failure.
445 template <size_t n, typename T, typename... List, typename... Accum>
446 struct TakeTypeListItemImpl<n, TypeList<T, List...>, Accum...>
447     : TakeTypeListItemImpl<n - 1, TypeList<List...>, Accum..., T> {};
448 
449 template <typename T, typename... List, typename... Accum>
450 struct TakeTypeListItemImpl<0, TypeList<T, List...>, Accum...> {
451   using Type = TypeList<Accum...>;
452 };
453 
454 template <typename... Accum>
455 struct TakeTypeListItemImpl<0, TypeList<>, Accum...> {
456   using Type = TypeList<Accum...>;
457 };
458 
459 // A type-level function that takes first |n| list item from given TypeList.
460 // E.g. TakeTypeListItem<3, TypeList<A, B, C, D>> is evaluated to
461 // TypeList<A, B, C>.
462 template <size_t n, typename List>
463 using TakeTypeListItem = typename TakeTypeListItemImpl<n, List>::Type;
464 
465 // Used for ConcatTypeLists implementation.
466 template <typename List1, typename List2>
467 struct ConcatTypeListsImpl;
468 
469 template <typename... Types1, typename... Types2>
470 struct ConcatTypeListsImpl<TypeList<Types1...>, TypeList<Types2...>> {
471   using Type = TypeList<Types1..., Types2...>;
472 };
473 
474 // A type-level function that concats two TypeLists.
475 template <typename List1, typename List2>
476 using ConcatTypeLists = typename ConcatTypeListsImpl<List1, List2>::Type;
477 
478 // Used for MakeFunctionType implementation.
479 template <typename R, typename ArgList>
480 struct MakeFunctionTypeImpl;
481 
482 template <typename R, typename... Args>
483 struct MakeFunctionTypeImpl<R, TypeList<Args...>> {
484   // MSVC 2013 doesn't support Type Alias of function types.
485   // Revisit this after we update it to newer version.
486   typedef R Type(Args...);
487 };
488 
489 // A type-level function that constructs a function type that has |R| as its
490 // return type and has TypeLists items as its arguments.
491 template <typename R, typename ArgList>
492 using MakeFunctionType = typename MakeFunctionTypeImpl<R, ArgList>::Type;
493 
494 // Used for ExtractArgs and ExtractReturnType.
495 template <typename Signature>
496 struct ExtractArgsImpl;
497 
498 template <typename R, typename... Args>
499 struct ExtractArgsImpl<R(Args...)> {
500   using ReturnType = R;
501   using ArgsList = TypeList<Args...>;
502 };
503 
504 // A type-level function that extracts function arguments into a TypeList.
505 // E.g. ExtractArgs<R(A, B, C)> is evaluated to TypeList<A, B, C>.
506 template <typename Signature>
507 using ExtractArgs = typename ExtractArgsImpl<Signature>::ArgsList;
508 
509 // A type-level function that extracts the return type of a function.
510 // E.g. ExtractReturnType<R(A, B, C)> is evaluated to R.
511 template <typename Signature>
512 using ExtractReturnType = typename ExtractArgsImpl<Signature>::ReturnType;
513 
514 template <typename Callable,
515           typename Signature = decltype(&Callable::operator())>
516 struct ExtractCallableRunTypeImpl;
517 
518 template <typename Callable, typename R, typename... Args>
519 struct ExtractCallableRunTypeImpl<Callable, R (Callable::*)(Args...)> {
520   using Type = R(Args...);
521 };
522 
523 template <typename Callable, typename R, typename... Args>
524 struct ExtractCallableRunTypeImpl<Callable, R (Callable::*)(Args...) const> {
525   using Type = R(Args...);
526 };
527 
528 template <typename Callable, typename R, typename... Args>
529 struct ExtractCallableRunTypeImpl<Callable, R (Callable::*)(Args...) noexcept> {
530   using Type = R(Args...);
531 };
532 
533 template <typename Callable, typename R, typename... Args>
534 struct ExtractCallableRunTypeImpl<Callable,
535                                   R (Callable::*)(Args...) const noexcept> {
536   using Type = R(Args...);
537 };
538 
539 // Evaluated to RunType of the given callable type.
540 // Example:
541 //   auto f = [](int, char*) { return 0.1; };
542 //   ExtractCallableRunType<decltype(f)>
543 //   is evaluated to
544 //   double(int, char*);
545 template <typename Callable>
546 using ExtractCallableRunType =
547     typename ExtractCallableRunTypeImpl<Callable>::Type;
548 
549 // IsCallableObject<Functor> is std::true_type if |Functor| has operator().
550 // Otherwise, it's std::false_type.
551 // Example:
552 //   IsCallableObject<void(*)()>::value is false.
553 //
554 //   struct Foo {};
555 //   IsCallableObject<void(Foo::*)()>::value is false.
556 //
557 //   int i = 0;
558 //   auto f = [i]() {};
559 //   IsCallableObject<decltype(f)>::value is false.
560 template <typename Functor, typename SFINAE = void>
561 struct IsCallableObject : std::false_type {};
562 
563 template <typename Callable>
564 struct IsCallableObject<Callable, std::void_t<decltype(&Callable::operator())>>
565     : std::true_type {};
566 
567 // HasRefCountedTypeAsRawPtr inherits from true_type when any of the |Args| is a
568 // raw pointer to a RefCounted type.
569 template <typename... Ts>
570 struct HasRefCountedTypeAsRawPtr
571     : std::disjunction<NeedsScopedRefptrButGetsRawPtr<Ts>...> {};
572 
573 // ForceVoidReturn<>
574 //
575 // Set of templates that support forcing the function return type to void.
576 template <typename Sig>
577 struct ForceVoidReturn;
578 
579 template <typename R, typename... Args>
580 struct ForceVoidReturn<R(Args...)> {
581   using RunType = void(Args...);
582 };
583 
584 // FunctorTraits<>
585 //
586 // See description at top of file.
587 template <typename Functor, typename SFINAE>
588 struct FunctorTraits;
589 
590 // For callable types.
591 // This specialization handles lambdas (captureless and capturing) and functors
592 // with a call operator. Capturing lambdas and stateful functors are explicitly
593 // disallowed by BindImpl().
594 //
595 // Example:
596 //
597 //   // Captureless lambdas are allowed.
598 //   []() {return 42;};
599 //
600 //   // Capturing lambdas are *not* allowed.
601 //   int x;
602 //   [x]() {return x;};
603 //
604 //   // Any empty class with operator() is allowed.
605 //   struct Foo {
606 //     void operator()() const {}
607 //     // No non-static member variable and no virtual functions.
608 //   };
609 template <typename Functor>
610 struct FunctorTraits<Functor,
611                      std::enable_if_t<IsCallableObject<Functor>::value>> {
612   using RunType = ExtractCallableRunType<Functor>;
613   static constexpr bool is_method = false;
614   static constexpr bool is_nullable = false;
615   static constexpr bool is_callback = false;
616   static constexpr bool is_stateless = std::is_empty_v<Functor>;
617 
618   template <typename RunFunctor, typename... RunArgs>
619   static ExtractReturnType<RunType> Invoke(RunFunctor&& functor,
620                                            RunArgs&&... args) {
621     return std::forward<RunFunctor>(functor)(std::forward<RunArgs>(args)...);
622   }
623 };
624 
625 // For functions.
626 template <typename R, typename... Args>
627 struct FunctorTraits<R (*)(Args...)> {
628   using RunType = R(Args...);
629   static constexpr bool is_method = false;
630   static constexpr bool is_nullable = true;
631   static constexpr bool is_callback = false;
632   static constexpr bool is_stateless = true;
633 
634   template <typename Function, typename... RunArgs>
635   static R Invoke(Function&& function, RunArgs&&... args) {
636     return std::forward<Function>(function)(std::forward<RunArgs>(args)...);
637   }
638 };
639 
640 #if BUILDFLAG(IS_WIN) && !defined(ARCH_CPU_64_BITS)
641 
642 // For functions.
643 template <typename R, typename... Args>
644 struct FunctorTraits<R(__stdcall*)(Args...)> {
645   using RunType = R(Args...);
646   static constexpr bool is_method = false;
647   static constexpr bool is_nullable = true;
648   static constexpr bool is_callback = false;
649   static constexpr bool is_stateless = true;
650 
651   template <typename... RunArgs>
652   static R Invoke(R(__stdcall* function)(Args...), RunArgs&&... args) {
653     return function(std::forward<RunArgs>(args)...);
654   }
655 };
656 
657 // For functions.
658 template <typename R, typename... Args>
659 struct FunctorTraits<R(__fastcall*)(Args...)> {
660   using RunType = R(Args...);
661   static constexpr bool is_method = false;
662   static constexpr bool is_nullable = true;
663   static constexpr bool is_callback = false;
664   static constexpr bool is_stateless = true;
665 
666   template <typename... RunArgs>
667   static R Invoke(R(__fastcall* function)(Args...), RunArgs&&... args) {
668     return function(std::forward<RunArgs>(args)...);
669   }
670 };
671 
672 #endif  // BUILDFLAG(IS_WIN) && !defined(ARCH_CPU_64_BITS)
673 
674 #if BUILDFLAG(IS_APPLE)
675 
676 // Support for Objective-C blocks. There are two implementation depending
677 // on whether Automated Reference Counting (ARC) is enabled. When ARC is
678 // enabled, then the block itself can be bound as the compiler will ensure
679 // its lifetime will be correctly managed. Otherwise, require the block to
680 // be wrapped in a base::mac::ScopedBlock (via base::RetainBlock) that will
681 // correctly manage the block lifetime.
682 //
683 // The two implementation ensure that the One Definition Rule (ODR) is not
684 // broken (it is not possible to write a template base::RetainBlock that would
685 // work correctly both with ARC enabled and disabled).
686 
687 #if HAS_FEATURE(objc_arc)
688 
689 template <typename R, typename... Args>
690 struct FunctorTraits<R (^)(Args...)> {
691   using RunType = R(Args...);
692   static constexpr bool is_method = false;
693   static constexpr bool is_nullable = true;
694   static constexpr bool is_callback = false;
695   static constexpr bool is_stateless = true;
696 
697   template <typename BlockType, typename... RunArgs>
698   static R Invoke(BlockType&& block, RunArgs&&... args) {
699     // According to LLVM documentation (§ 6.3), "local variables of automatic
700     // storage duration do not have precise lifetime." Use objc_precise_lifetime
701     // to ensure that the Objective-C block is not deallocated until it has
702     // finished executing even if the Callback<> is destroyed during the block
703     // execution.
704     // https://clang.llvm.org/docs/AutomaticReferenceCounting.html#precise-lifetime-semantics
705     __attribute__((objc_precise_lifetime)) R (^scoped_block)(Args...) = block;
706     return scoped_block(std::forward<RunArgs>(args)...);
707   }
708 };
709 
710 #else  // HAS_FEATURE(objc_arc)
711 
712 template <typename R, typename... Args>
713 struct FunctorTraits<base::mac::ScopedBlock<R (^)(Args...)>> {
714   using RunType = R(Args...);
715   static constexpr bool is_method = false;
716   static constexpr bool is_nullable = true;
717   static constexpr bool is_callback = false;
718   static constexpr bool is_stateless = true;
719 
720   template <typename BlockType, typename... RunArgs>
721   static R Invoke(BlockType&& block, RunArgs&&... args) {
722     // Copy the block to ensure that the Objective-C block is not deallocated
723     // until it has finished executing even if the Callback<> is destroyed
724     // during the block execution.
725     base::mac::ScopedBlock<R (^)(Args...)> scoped_block(block);
726     return scoped_block.get()(std::forward<RunArgs>(args)...);
727   }
728 };
729 
730 #endif  // HAS_FEATURE(objc_arc)
731 #endif  // BUILDFLAG(IS_APPLE)
732 
733 // For methods.
734 template <typename R, typename Receiver, typename... Args>
735 struct FunctorTraits<R (Receiver::*)(Args...)> {
736   using RunType = R(Receiver*, Args...);
737   static constexpr bool is_method = true;
738   static constexpr bool is_nullable = true;
739   static constexpr bool is_callback = false;
740   static constexpr bool is_stateless = true;
741 
742   template <typename Method, typename ReceiverPtr, typename... RunArgs>
743   static R Invoke(Method method,
744                   ReceiverPtr&& receiver_ptr,
745                   RunArgs&&... args) {
746     return ((*receiver_ptr).*method)(std::forward<RunArgs>(args)...);
747   }
748 };
749 
750 // For const methods.
751 template <typename R, typename Receiver, typename... Args>
752 struct FunctorTraits<R (Receiver::*)(Args...) const> {
753   using RunType = R(const Receiver*, Args...);
754   static constexpr bool is_method = true;
755   static constexpr bool is_nullable = true;
756   static constexpr bool is_callback = false;
757   static constexpr bool is_stateless = true;
758 
759   template <typename Method, typename ReceiverPtr, typename... RunArgs>
760   static R Invoke(Method method,
761                   ReceiverPtr&& receiver_ptr,
762                   RunArgs&&... args) {
763     return ((*receiver_ptr).*method)(std::forward<RunArgs>(args)...);
764   }
765 };
766 
767 #if BUILDFLAG(IS_WIN) && !defined(ARCH_CPU_64_BITS)
768 
769 // For __stdcall methods.
770 template <typename R, typename Receiver, typename... Args>
771 struct FunctorTraits<R (__stdcall Receiver::*)(Args...)> {
772   using RunType = R(Receiver*, Args...);
773   static constexpr bool is_method = true;
774   static constexpr bool is_nullable = true;
775   static constexpr bool is_callback = false;
776   static constexpr bool is_stateless = true;
777 
778   template <typename Method, typename ReceiverPtr, typename... RunArgs>
779   static R Invoke(Method method,
780                   ReceiverPtr&& receiver_ptr,
781                   RunArgs&&... args) {
782     return ((*receiver_ptr).*method)(std::forward<RunArgs>(args)...);
783   }
784 };
785 
786 // For __stdcall const methods.
787 template <typename R, typename Receiver, typename... Args>
788 struct FunctorTraits<R (__stdcall Receiver::*)(Args...) const> {
789   using RunType = R(const Receiver*, Args...);
790   static constexpr bool is_method = true;
791   static constexpr bool is_nullable = true;
792   static constexpr bool is_callback = false;
793   static constexpr bool is_stateless = true;
794 
795   template <typename Method, typename ReceiverPtr, typename... RunArgs>
796   static R Invoke(Method method,
797                   ReceiverPtr&& receiver_ptr,
798                   RunArgs&&... args) {
799     return ((*receiver_ptr).*method)(std::forward<RunArgs>(args)...);
800   }
801 };
802 
803 #endif  // BUILDFLAG(IS_WIN) && !defined(ARCH_CPU_64_BITS)
804 
805 #ifdef __cpp_noexcept_function_type
806 // noexcept makes a distinct function type in C++17.
807 // I.e. `void(*)()` and `void(*)() noexcept` are same in pre-C++17, and
808 // different in C++17.
809 template <typename R, typename... Args>
810 struct FunctorTraits<R (*)(Args...) noexcept> : FunctorTraits<R (*)(Args...)> {
811 };
812 
813 template <typename R, typename Receiver, typename... Args>
814 struct FunctorTraits<R (Receiver::*)(Args...) noexcept>
815     : FunctorTraits<R (Receiver::*)(Args...)> {};
816 
817 template <typename R, typename Receiver, typename... Args>
818 struct FunctorTraits<R (Receiver::*)(Args...) const noexcept>
819     : FunctorTraits<R (Receiver::*)(Args...) const> {};
820 #endif
821 
822 // For IgnoreResults.
823 template <typename T>
824 struct FunctorTraits<IgnoreResultHelper<T>> : FunctorTraits<T> {
825   using RunType =
826       typename ForceVoidReturn<typename FunctorTraits<T>::RunType>::RunType;
827 
828   template <typename IgnoreResultType, typename... RunArgs>
829   static void Invoke(IgnoreResultType&& ignore_result_helper,
830                      RunArgs&&... args) {
831     FunctorTraits<T>::Invoke(
832         std::forward<IgnoreResultType>(ignore_result_helper).functor_,
833         std::forward<RunArgs>(args)...);
834   }
835 };
836 
837 // For OnceCallbacks.
838 template <typename R, typename... Args>
839 struct FunctorTraits<OnceCallback<R(Args...)>> {
840   using RunType = R(Args...);
841   static constexpr bool is_method = false;
842   static constexpr bool is_nullable = true;
843   static constexpr bool is_callback = true;
844   static constexpr bool is_stateless = true;
845 
846   template <typename CallbackType, typename... RunArgs>
847   static R Invoke(CallbackType&& callback, RunArgs&&... args) {
848     DCHECK(!callback.is_null());
849     return std::forward<CallbackType>(callback).Run(
850         std::forward<RunArgs>(args)...);
851   }
852 };
853 
854 // For RepeatingCallbacks.
855 template <typename R, typename... Args>
856 struct FunctorTraits<RepeatingCallback<R(Args...)>> {
857   using RunType = R(Args...);
858   static constexpr bool is_method = false;
859   static constexpr bool is_nullable = true;
860   static constexpr bool is_callback = true;
861   static constexpr bool is_stateless = true;
862 
863   template <typename CallbackType, typename... RunArgs>
864   static R Invoke(CallbackType&& callback, RunArgs&&... args) {
865     DCHECK(!callback.is_null());
866     return std::forward<CallbackType>(callback).Run(
867         std::forward<RunArgs>(args)...);
868   }
869 };
870 
871 template <typename Functor>
872 using MakeFunctorTraits = FunctorTraits<std::decay_t<Functor>>;
873 
874 // StorageTraits<>
875 //
876 // See description at top of file.
877 template <typename T>
878 struct StorageTraits {
879   using Type = T;
880 };
881 
882 // For T*, store as UnretainedWrapper<T> for safety, as it internally uses
883 // raw_ptr<T> (when possible).
884 template <typename T>
885 struct StorageTraits<T*> {
886   using Type = UnretainedWrapper<T, unretained_traits::MayNotDangle>;
887 };
888 
889 // For raw_ptr<T>, store as UnretainedWrapper<T> for safety. This may seem
890 // contradictory, but this ensures guaranteed protection for the pointer even
891 // during execution of callbacks with parameters of type raw_ptr<T>.
892 template <typename T, RawPtrTraits PtrTraits>
893 struct StorageTraits<raw_ptr<T, PtrTraits>> {
894   using Type = UnretainedWrapper<T, unretained_traits::MayNotDangle, PtrTraits>;
895 };
896 
897 // Unwrap std::reference_wrapper and store it in a custom wrapper so that
898 // references are also protected with raw_ptr<T>.
899 template <typename T>
900 struct StorageTraits<std::reference_wrapper<T>> {
901   using Type = UnretainedRefWrapper<T, unretained_traits::MayNotDangle>;
902 };
903 
904 template <typename T>
905 using MakeStorageType = typename StorageTraits<std::decay_t<T>>::Type;
906 
907 // InvokeHelper<>
908 //
909 // There are 2 logical InvokeHelper<> specializations: normal, WeakCalls.
910 //
911 // The normal type just calls the underlying runnable.
912 //
913 // WeakCalls need special syntax that is applied to the first argument to check
914 // if they should no-op themselves.
915 template <bool is_weak_call, typename ReturnType, size_t... indices>
916 struct InvokeHelper;
917 
918 template <typename ReturnType, size_t... indices>
919 struct InvokeHelper<false, ReturnType, indices...> {
920   template <typename Functor, typename BoundArgsTuple, typename... RunArgs>
921   static inline ReturnType MakeItSo(Functor&& functor,
922                                     BoundArgsTuple&& bound,
923                                     RunArgs&&... args) {
924     using Traits = MakeFunctorTraits<Functor>;
925     return Traits::Invoke(
926         std::forward<Functor>(functor),
927         Unwrap(std::get<indices>(std::forward<BoundArgsTuple>(bound)))...,
928         std::forward<RunArgs>(args)...);
929   }
930 };
931 
932 template <typename ReturnType, size_t index_target, size_t... index_tail>
933 struct InvokeHelper<true, ReturnType, index_target, index_tail...> {
934   // WeakCalls are only supported for functions with a void return type.
935   // Otherwise, the function result would be undefined if the WeakPtr<>
936   // is invalidated.
937   static_assert(std::is_void_v<ReturnType>,
938                 "weak_ptrs can only bind to methods without return values");
939 
940   template <typename Functor, typename BoundArgsTuple, typename... RunArgs>
941   static inline void MakeItSo(Functor&& functor,
942                               BoundArgsTuple&& bound,
943                               RunArgs&&... args) {
944     static_assert(index_target == 0);
945     // Note the validity of the weak pointer should be tested _after_ it is
946     // unwrapped, otherwise it creates a race for weak pointer implementations
947     // that allow cross-thread usage and perform `Lock()` in Unwrap() traits.
948     const auto& target = Unwrap(std::get<0>(bound));
949     if (!target) {
950       return;
951     }
952     using Traits = MakeFunctorTraits<Functor>;
953     Traits::Invoke(
954         std::forward<Functor>(functor), target,
955         Unwrap(std::get<index_tail>(std::forward<BoundArgsTuple>(bound)))...,
956         std::forward<RunArgs>(args)...);
957   }
958 };
959 
960 // Invoker<>
961 //
962 // See description at the top of the file.
963 template <typename StorageType, typename UnboundRunType>
964 struct Invoker;
965 
966 template <typename StorageType, typename R, typename... UnboundArgs>
967 struct Invoker<StorageType, R(UnboundArgs...)> {
968   static R RunOnce(BindStateBase* base,
969                    PassingType<UnboundArgs>... unbound_args) {
970     // Local references to make debugger stepping easier. If in a debugger,
971     // you really want to warp ahead and step through the
972     // InvokeHelper<>::MakeItSo() call below.
973     StorageType* storage = static_cast<StorageType*>(base);
974     static constexpr size_t num_bound_args =
975         std::tuple_size_v<decltype(storage->bound_args_)>;
976     return RunImpl(std::move(storage->functor_),
977                    std::move(storage->bound_args_),
978                    std::make_index_sequence<num_bound_args>(),
979                    std::forward<UnboundArgs>(unbound_args)...);
980   }
981 
982   static R Run(BindStateBase* base, PassingType<UnboundArgs>... unbound_args) {
983     // Local references to make debugger stepping easier. If in a debugger,
984     // you really want to warp ahead and step through the
985     // InvokeHelper<>::MakeItSo() call below.
986     const StorageType* storage = static_cast<StorageType*>(base);
987     static constexpr size_t num_bound_args =
988         std::tuple_size_v<decltype(storage->bound_args_)>;
989     return RunImpl(storage->functor_, storage->bound_args_,
990                    std::make_index_sequence<num_bound_args>(),
991                    std::forward<UnboundArgs>(unbound_args)...);
992   }
993 
994  private:
995   template <typename Functor, typename BoundArgsTuple, size_t... indices>
996   static inline R RunImpl(Functor&& functor,
997                           BoundArgsTuple&& bound,
998                           std::index_sequence<indices...> seq,
999                           UnboundArgs&&... unbound_args) {
1000     static constexpr bool is_method = MakeFunctorTraits<Functor>::is_method;
1001 
1002     using DecayedArgsTuple = std::decay_t<BoundArgsTuple>;
1003 
1004 #if BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
1005     RawPtrAsanBoundArgTracker raw_ptr_asan_bound_arg_tracker;
1006     raw_ptr_asan_bound_arg_tracker.AddArgs(
1007         std::get<indices>(std::forward<BoundArgsTuple>(bound))...,
1008         std::forward<UnboundArgs>(unbound_args)...);
1009 #endif  // BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
1010 
1011     static constexpr bool is_weak_call =
1012         IsWeakMethod<is_method,
1013                      std::tuple_element_t<indices, DecayedArgsTuple>...>();
1014 
1015     // Do not `Unwrap()` here, as that immediately triggers dangling pointer
1016     // detection. Dangling pointer detection should only be triggered if the
1017     // callback is not cancelled, but cancellation status is not determined
1018     // until later inside the InvokeHelper::MakeItSo specialization for weak
1019     // calls.
1020     //
1021     // Dangling pointers when invoking a cancelled callback are not considered
1022     // a memory safety error because protecting raw pointers usage with weak
1023     // receivers (where the weak receiver usually own the pointed objects) is a
1024     // common and broadly used pattern in the codebase.
1025     return InvokeHelper<is_weak_call, R, indices...>::MakeItSo(
1026         std::forward<Functor>(functor), std::forward<BoundArgsTuple>(bound),
1027         std::forward<UnboundArgs>(unbound_args)...);
1028   }
1029 };
1030 
1031 // Extracts necessary type info from Functor and BoundArgs.
1032 // Used to implement MakeUnboundRunType, BindOnce and BindRepeating.
1033 template <typename Functor, typename... BoundArgs>
1034 struct BindTypeHelper {
1035   static constexpr size_t num_bounds = sizeof...(BoundArgs);
1036   using FunctorTraits = MakeFunctorTraits<Functor>;
1037 
1038   // Example:
1039   //   When Functor is `double (Foo::*)(int, const std::string&)`, and BoundArgs
1040   //   is a template pack of `Foo*` and `int16_t`:
1041   //    - RunType is `double(Foo*, int, const std::string&)`,
1042   //    - ReturnType is `double`,
1043   //    - RunParamsList is `TypeList<Foo*, int, const std::string&>`,
1044   //    - BoundParamsList is `TypeList<Foo*, int>`,
1045   //    - UnboundParamsList is `TypeList<const std::string&>`,
1046   //    - BoundArgsList is `TypeList<Foo*, int16_t>`,
1047   //    - UnboundRunType is `double(const std::string&)`.
1048   using RunType = typename FunctorTraits::RunType;
1049   using ReturnType = ExtractReturnType<RunType>;
1050 
1051   using RunParamsList = ExtractArgs<RunType>;
1052   using BoundParamsList = TakeTypeListItem<num_bounds, RunParamsList>;
1053   using UnboundParamsList = DropTypeListItem<num_bounds, RunParamsList>;
1054 
1055   using BoundArgsList = TypeList<BoundArgs...>;
1056 
1057   using UnboundRunType = MakeFunctionType<ReturnType, UnboundParamsList>;
1058 };
1059 
1060 template <typename Functor>
1061 std::enable_if_t<FunctorTraits<Functor>::is_nullable, bool> IsNull(
1062     const Functor& functor) {
1063   return !functor;
1064 }
1065 
1066 template <typename Functor>
1067 std::enable_if_t<!FunctorTraits<Functor>::is_nullable, bool> IsNull(
1068     const Functor&) {
1069   return false;
1070 }
1071 
1072 // Used by QueryCancellationTraits below.
1073 template <typename Functor, typename BoundArgsTuple, size_t... indices>
1074 bool QueryCancellationTraitsImpl(BindStateBase::CancellationQueryMode mode,
1075                                  const Functor& functor,
1076                                  const BoundArgsTuple& bound_args,
1077                                  std::index_sequence<indices...>) {
1078   switch (mode) {
1079     case BindStateBase::IS_CANCELLED:
1080       return CallbackCancellationTraits<Functor, BoundArgsTuple>::IsCancelled(
1081           functor, std::get<indices>(bound_args)...);
1082     case BindStateBase::MAYBE_VALID:
1083       return CallbackCancellationTraits<Functor, BoundArgsTuple>::MaybeValid(
1084           functor, std::get<indices>(bound_args)...);
1085   }
1086   NOTREACHED();
1087   return false;
1088 }
1089 
1090 // Relays |base| to corresponding CallbackCancellationTraits<>::Run(). Returns
1091 // true if the callback |base| represents is canceled.
1092 template <typename BindStateType>
1093 bool QueryCancellationTraits(const BindStateBase* base,
1094                              BindStateBase::CancellationQueryMode mode) {
1095   const BindStateType* storage = static_cast<const BindStateType*>(base);
1096   static constexpr size_t num_bound_args =
1097       std::tuple_size_v<decltype(storage->bound_args_)>;
1098   return QueryCancellationTraitsImpl(
1099       mode, storage->functor_, storage->bound_args_,
1100       std::make_index_sequence<num_bound_args>());
1101 }
1102 
1103 // The base case of BanUnconstructedRefCountedReceiver that checks nothing.
1104 template <typename Functor, typename Receiver, typename... Unused>
1105 std::enable_if_t<
1106     !(MakeFunctorTraits<Functor>::is_method &&
1107       IsPointerV<std::decay_t<Receiver>> &&
1108       IsRefCountedType<RemovePointerT<std::decay_t<Receiver>>>::value)>
1109 BanUnconstructedRefCountedReceiver(const Receiver& receiver, Unused&&...) {}
1110 
1111 template <typename Functor>
1112 void BanUnconstructedRefCountedReceiver() {}
1113 
1114 // Asserts that Callback is not the first owner of a ref-counted receiver.
1115 template <typename Functor, typename Receiver, typename... Unused>
1116 std::enable_if_t<
1117     MakeFunctorTraits<Functor>::is_method &&
1118     IsPointerV<std::decay_t<Receiver>> &&
1119     IsRefCountedType<RemovePointerT<std::decay_t<Receiver>>>::value>
1120 BanUnconstructedRefCountedReceiver(const Receiver& receiver, Unused&&...) {
1121   DCHECK(receiver);
1122 
1123   // It's error prone to make the implicit first reference to ref-counted types.
1124   // In the example below, base::BindOnce() would make the implicit first
1125   // reference to the ref-counted Foo. If PostTask() failed or the posted task
1126   // ran fast enough, the newly created instance could be destroyed before `oo`
1127   // makes another reference.
1128   //   Foo::Foo() {
1129   //     base::ThreadPool::PostTask(FROM_HERE, base::BindOnce(&Foo::Bar, this));
1130   //   }
1131   //
1132   //   scoped_refptr<Foo> oo = new Foo();
1133   //
1134   // Hence, base::Bind{Once,Repeating}() refuses to create the first reference
1135   // to ref-counted objects, and DCHECK()s otherwise. As above, that typically
1136   // happens around PostTask() in their constructor, and such objects can be
1137   // destroyed before `new` returns if the task resolves fast enough.
1138   //
1139   // Instead of doing the above, please consider adding a static constructor,
1140   // and keep the first reference alive explicitly.
1141   //   // static
1142   //   scoped_refptr<Foo> Foo::Create() {
1143   //     auto foo = base::WrapRefCounted(new Foo());
1144   //     base::ThreadPool::PostTask(FROM_HERE, base::BindOnce(&Foo::Bar, foo));
1145   //     return foo;
1146   //   }
1147   //
1148   //   Foo::Foo() {}
1149   //
1150   //   scoped_refptr<Foo> oo = Foo::Create();
1151   //
1152   DCHECK(receiver->HasAtLeastOneRef());
1153 }
1154 
1155 // BindState<>
1156 //
1157 // This stores all the state passed into Bind().
1158 template <typename Functor, typename... BoundArgs>
1159 struct BindState final : BindStateBase {
1160   using IsCancellable = std::bool_constant<
1161       CallbackCancellationTraits<Functor,
1162                                  std::tuple<BoundArgs...>>::is_cancellable>;
1163   template <typename ForwardFunctor, typename... ForwardBoundArgs>
1164   static BindState* Create(BindStateBase::InvokeFuncStorage invoke_func,
1165                            ForwardFunctor&& functor,
1166                            ForwardBoundArgs&&... bound_args) {
1167     // Ban ref counted receivers that were not yet fully constructed to avoid
1168     // a common pattern of racy situation.
1169     BanUnconstructedRefCountedReceiver<ForwardFunctor>(bound_args...);
1170 
1171     // IsCancellable is std::false_type if
1172     // CallbackCancellationTraits<>::IsCancelled returns always false.
1173     // Otherwise, it's std::true_type.
1174     return new BindState(IsCancellable{}, invoke_func,
1175                          std::forward<ForwardFunctor>(functor),
1176                          std::forward<ForwardBoundArgs>(bound_args)...);
1177   }
1178 
1179   Functor functor_;
1180   std::tuple<BoundArgs...> bound_args_;
1181 
1182  private:
1183   static constexpr bool is_nested_callback =
1184       MakeFunctorTraits<Functor>::is_callback;
1185 
1186   template <typename ForwardFunctor, typename... ForwardBoundArgs>
1187   explicit BindState(std::true_type,
1188                      BindStateBase::InvokeFuncStorage invoke_func,
1189                      ForwardFunctor&& functor,
1190                      ForwardBoundArgs&&... bound_args)
1191       : BindStateBase(invoke_func,
1192                       &Destroy,
1193                       &QueryCancellationTraits<BindState>),
1194         functor_(std::forward<ForwardFunctor>(functor)),
1195         bound_args_(std::forward<ForwardBoundArgs>(bound_args)...) {
1196     // We check the validity of nested callbacks (e.g., Bind(callback, ...)) in
1197     // release builds to avoid null pointers from ending up in posted tasks,
1198     // causing hard-to-diagnose crashes. Ideally we'd do this for all functors
1199     // here, but that would have a large binary size impact.
1200     if (is_nested_callback) {
1201       CHECK(!IsNull(functor_));
1202     } else {
1203       DCHECK(!IsNull(functor_));
1204     }
1205   }
1206 
1207   template <typename ForwardFunctor, typename... ForwardBoundArgs>
1208   explicit BindState(std::false_type,
1209                      BindStateBase::InvokeFuncStorage invoke_func,
1210                      ForwardFunctor&& functor,
1211                      ForwardBoundArgs&&... bound_args)
1212       : BindStateBase(invoke_func, &Destroy),
1213         functor_(std::forward<ForwardFunctor>(functor)),
1214         bound_args_(std::forward<ForwardBoundArgs>(bound_args)...) {
1215     // See above for CHECK/DCHECK rationale.
1216     if (is_nested_callback) {
1217       CHECK(!IsNull(functor_));
1218     } else {
1219       DCHECK(!IsNull(functor_));
1220     }
1221   }
1222 
1223   ~BindState() = default;
1224 
1225   static void Destroy(const BindStateBase* self) {
1226     delete static_cast<const BindState*>(self);
1227   }
1228 };
1229 
1230 // Used to implement MakeBindStateType.
1231 template <bool is_method, typename Functor, typename... BoundArgs>
1232 struct MakeBindStateTypeImpl;
1233 
1234 template <typename Functor, typename... BoundArgs>
1235 struct MakeBindStateTypeImpl<false, Functor, BoundArgs...> {
1236   static_assert(!HasRefCountedTypeAsRawPtr<std::decay_t<BoundArgs>...>::value,
1237                 "A parameter is a refcounted type and needs scoped_refptr.");
1238   using Type = BindState<std::decay_t<Functor>, MakeStorageType<BoundArgs>...>;
1239 };
1240 
1241 template <typename Functor>
1242 struct MakeBindStateTypeImpl<true, Functor> {
1243   using Type = BindState<std::decay_t<Functor>>;
1244 };
1245 
1246 template <typename Functor, typename Receiver, typename... BoundArgs>
1247 struct MakeBindStateTypeImpl<true, Functor, Receiver, BoundArgs...> {
1248  private:
1249   using DecayedReceiver = std::decay_t<Receiver>;
1250   static_assert(!std::is_array_v<std::remove_reference_t<Receiver>>,
1251                 "First bound argument to a method cannot be an array.");
1252   static_assert(
1253       !IsRawRefV<DecayedReceiver>,
1254       "Receivers may not be raw_ref<T>. If using a raw_ref<T> here is safe"
1255       " and has no lifetime concerns, use base::Unretained() and document why"
1256       " it's safe.");
1257   static_assert(
1258       !IsPointerV<DecayedReceiver> ||
1259           IsRefCountedType<RemovePointerT<DecayedReceiver>>::value,
1260       "Receivers may not be raw pointers. If using a raw pointer here is safe"
1261       " and has no lifetime concerns, use base::Unretained() and document why"
1262       " it's safe.");
1263 
1264   static_assert(!HasRefCountedTypeAsRawPtr<std::decay_t<BoundArgs>...>::value,
1265                 "A parameter is a refcounted type and needs scoped_refptr.");
1266 
1267   using ReceiverStorageType =
1268       typename MethodReceiverStorageType<DecayedReceiver>::Type;
1269 
1270  public:
1271   using Type = BindState<std::decay_t<Functor>,
1272                          ReceiverStorageType,
1273                          MakeStorageType<BoundArgs>...>;
1274 };
1275 
1276 template <typename Functor, typename... BoundArgs>
1277 using MakeBindStateType =
1278     typename MakeBindStateTypeImpl<MakeFunctorTraits<Functor>::is_method,
1279                                    Functor,
1280                                    BoundArgs...>::Type;
1281 
1282 // Returns a RunType of bound functor.
1283 // E.g. MakeUnboundRunType<R(A, B, C), A, B> is evaluated to R(C).
1284 template <typename Functor, typename... BoundArgs>
1285 using MakeUnboundRunType =
1286     typename BindTypeHelper<Functor, BoundArgs...>::UnboundRunType;
1287 
1288 // The implementation of TransformToUnwrappedType below.
1289 template <bool is_once, typename T>
1290 struct TransformToUnwrappedTypeImpl;
1291 
1292 template <typename T>
1293 struct TransformToUnwrappedTypeImpl<true, T> {
1294   using StoredType = std::decay_t<T>;
1295   using ForwardType = StoredType&&;
1296   using Unwrapped = decltype(Unwrap(std::declval<ForwardType>()));
1297 };
1298 
1299 template <typename T>
1300 struct TransformToUnwrappedTypeImpl<false, T> {
1301   using StoredType = std::decay_t<T>;
1302   using ForwardType = const StoredType&;
1303   using Unwrapped = decltype(Unwrap(std::declval<ForwardType>()));
1304 };
1305 
1306 // Transform |T| into `Unwrapped` type, which is passed to the target function.
1307 // Example:
1308 //   In is_once == true case,
1309 //     `int&&` -> `int&&`,
1310 //     `const int&` -> `int&&`,
1311 //     `OwnedWrapper<int>&` -> `int*&&`.
1312 //   In is_once == false case,
1313 //     `int&&` -> `const int&`,
1314 //     `const int&` -> `const int&`,
1315 //     `OwnedWrapper<int>&` -> `int* const &`.
1316 template <bool is_once, typename T>
1317 using TransformToUnwrappedType =
1318     typename TransformToUnwrappedTypeImpl<is_once, T>::Unwrapped;
1319 
1320 // Transforms |Args| into `Unwrapped` types, and packs them into a TypeList.
1321 // If |is_method| is true, tries to dereference the first argument to support
1322 // smart pointers.
1323 template <bool is_once, bool is_method, typename... Args>
1324 struct MakeUnwrappedTypeListImpl {
1325   using Type = TypeList<TransformToUnwrappedType<is_once, Args>...>;
1326 };
1327 
1328 // Performs special handling for this pointers.
1329 // Example:
1330 //   int* -> int*,
1331 //   std::unique_ptr<int> -> int*.
1332 template <bool is_once, typename Receiver, typename... Args>
1333 struct MakeUnwrappedTypeListImpl<is_once, true, Receiver, Args...> {
1334   using ReceiverStorageType =
1335       typename MethodReceiverStorageType<std::decay_t<Receiver>>::Type;
1336   using UnwrappedReceiver =
1337       TransformToUnwrappedType<is_once, ReceiverStorageType>;
1338   using Type = TypeList<decltype(&*std::declval<UnwrappedReceiver>()),
1339                         TransformToUnwrappedType<is_once, Args>...>;
1340 };
1341 
1342 template <bool is_once, bool is_method, typename... Args>
1343 using MakeUnwrappedTypeList =
1344     typename MakeUnwrappedTypeListImpl<is_once, is_method, Args...>::Type;
1345 
1346 // IsOnceCallback<T> is a std::true_type if |T| is a OnceCallback.
1347 template <typename T>
1348 struct IsOnceCallback : std::false_type {};
1349 
1350 template <typename Signature>
1351 struct IsOnceCallback<OnceCallback<Signature>> : std::true_type {};
1352 
1353 // IsUnretainedMayDangle is true if StorageType is of type
1354 // `UnretainedWrapper<T, unretained_traits::MayDangle, PtrTraits>.
1355 // Note that it is false for unretained_traits::MayDangleUntriaged.
1356 template <typename StorageType>
1357 inline constexpr bool IsUnretainedMayDangle = false;
1358 template <typename T, RawPtrTraits PtrTraits>
1359 inline constexpr bool IsUnretainedMayDangle<
1360     UnretainedWrapper<T, unretained_traits::MayDangle, PtrTraits>> = true;
1361 
1362 // UnretainedAndRawPtrHaveCompatibleTraits is true if StorageType is of type
1363 // `UnretainedWrapper<T, unretained_traits::MayDangle, PtrTraits1>` and
1364 // FunctionParamType is of type `raw_ptr<T, PtrTraits2>`, and the former's
1365 // ::GetPtrType is the same type as the latter.
1366 template <typename StorageType, typename FunctionParamType>
1367 inline constexpr bool UnretainedAndRawPtrHaveCompatibleTraits = false;
1368 template <typename T,
1369           RawPtrTraits PtrTraitsInUnretained,
1370           RawPtrTraits PtrTraitsInReceiver>
1371 inline constexpr bool UnretainedAndRawPtrHaveCompatibleTraits<
1372     UnretainedWrapper<T, unretained_traits::MayDangle, PtrTraitsInUnretained>,
1373     raw_ptr<T, PtrTraitsInReceiver>> =
1374     std::is_same_v<
1375         typename UnretainedWrapper<T,
1376                                    unretained_traits::MayDangle,
1377                                    PtrTraitsInUnretained>::GetPtrType,
1378         raw_ptr<T, PtrTraitsInReceiver>>;
1379 
1380 // Helpers to make error messages slightly more readable.
1381 template <int i>
1382 struct BindArgument {
1383   template <typename ForwardingType>
1384   struct ForwardedAs {
1385     template <typename FunctorParamType>
1386     struct ToParamWithType {
1387       static constexpr bool kNotARawPtr = !IsRawPtrV<FunctorParamType>;
1388 
1389       static constexpr bool kCanBeForwardedToBoundFunctor =
1390           std::is_constructible_v<FunctorParamType, ForwardingType>;
1391 
1392       // If the bound type can't be forwarded then test if `FunctorParamType` is
1393       // a non-const lvalue reference and a reference to the unwrapped type
1394       // *could* have been successfully forwarded.
1395       static constexpr bool kNonConstRefParamMustBeWrapped =
1396           kCanBeForwardedToBoundFunctor ||
1397           !(std::is_lvalue_reference_v<FunctorParamType> &&
1398             !std::is_const_v<std::remove_reference_t<FunctorParamType>> &&
1399             std::is_convertible_v<std::decay_t<ForwardingType>&,
1400                                   FunctorParamType>);
1401 
1402       // Note that this intentionally drops the const qualifier from
1403       // `ForwardingType`, to test if it *could* have been successfully
1404       // forwarded if `Passed()` had been used.
1405       static constexpr bool kMoveOnlyTypeMustUseBasePassed =
1406           kCanBeForwardedToBoundFunctor ||
1407           !std::is_constructible_v<FunctorParamType,
1408                                    std::decay_t<ForwardingType>&&>;
1409     };
1410   };
1411 
1412   template <typename BoundAsType>
1413   struct BoundAs {
1414     template <typename StorageType>
1415     struct StoredAs {
1416       static constexpr bool kBindArgumentCanBeCaptured =
1417           std::is_constructible_v<StorageType, BoundAsType>;
1418       // Note that this intentionally drops the const qualifier from
1419       // `BoundAsType`, to test if it *could* have been successfully bound if
1420       // `std::move()` had been used.
1421       static constexpr bool kMoveOnlyTypeMustUseStdMove =
1422           kBindArgumentCanBeCaptured ||
1423           !std::is_constructible_v<StorageType, std::decay_t<BoundAsType>&&>;
1424     };
1425   };
1426 
1427   template <typename FunctionParamType>
1428   struct ToParamWithType {
1429     template <typename StorageType>
1430     struct StoredAs {
1431       template <bool is_method>
1432       // true if we are handling `this` parameter.
1433       static constexpr bool kParamIsThisPointer = is_method && i == 0;
1434       // true if the current parameter is of type `raw_ptr<T>` with
1435       // `RawPtrTraits::kMayDangle` trait (e.g. `MayBeDangling<T>`).
1436       static constexpr bool kParamIsDanglingRawPtr =
1437           IsRawPtrMayDangleV<FunctionParamType>;
1438       // true if the bound parameter is of type
1439       // `UnretainedWrapper<T, unretained_traits::MayDangle, PtrTraits>`.
1440       static constexpr bool kBoundPtrMayDangle =
1441           IsUnretainedMayDangle<StorageType>;
1442       // true if bound parameter of type `UnretainedWrapper` and parameter of
1443       // type `raw_ptr` have compatible `RawPtrTraits`.
1444       static constexpr bool kMayBeDanglingTraitsCorrectness =
1445           UnretainedAndRawPtrHaveCompatibleTraits<StorageType,
1446                                                   FunctionParamType>;
1447       // true if the receiver argument **must** be of type `MayBeDangling<T>`.
1448       static constexpr bool kMayBeDanglingMustBeUsed =
1449           kBoundPtrMayDangle && kParamIsDanglingRawPtr;
1450 
1451       // true iff:
1452       // - bound parameter is of type
1453       //   `UnretainedWrapper<T, unretained_traits::MayDangle, PtrTraits>`
1454       // - the receiving argument is of type `MayBeDangling<T>`
1455       template <bool is_method>
1456       static constexpr bool kMayBeDanglingPtrPassedCorrectly =
1457           kParamIsThisPointer<is_method> ||
1458           kBoundPtrMayDangle == kParamIsDanglingRawPtr;
1459 
1460       // true if:
1461       // - MayBeDangling<T> must not be used as receiver parameter.
1462       // OR
1463       // - MayBeDangling<T> must be used as receiver parameter and its traits
1464       // are matching Unretained traits.
1465       static constexpr bool kUnsafeDanglingAndMayBeDanglingHaveMatchingTraits =
1466           !kMayBeDanglingMustBeUsed || kMayBeDanglingTraitsCorrectness;
1467     };
1468   };
1469 };
1470 
1471 // Helper to assert that parameter |i| of type |Arg| can be bound, which means:
1472 // - |Arg| can be retained internally as |Storage|.
1473 // - |Arg| can be forwarded as |Unwrapped| to |Param|.
1474 template <int i,
1475           bool is_method,
1476           typename Arg,
1477           typename Storage,
1478           typename Unwrapped,
1479           typename Param>
1480 struct AssertConstructible {
1481  private:
1482   // With `BindRepeating`, there are two decision points for how to handle a
1483   // move-only type:
1484   //
1485   // 1. Whether the move-only argument should be moved into the internal
1486   //    `BindState`. Either `std::move()` or `Passed` is sufficient to trigger
1487   //    move-only semantics.
1488   // 2. Whether or not the bound, move-only argument should be moved to the
1489   //    bound functor when invoked. When the argument is bound with `Passed`,
1490   //    invoking the callback will destructively move the bound, move-only
1491   //    argument to the bound functor. In contrast, if the argument is bound
1492   //    with `std::move()`, `RepeatingCallback` will attempt to call the bound
1493   //    functor with a constant reference to the bound, move-only argument. This
1494   //    will fail if the bound functor accepts that argument by value, since the
1495   //    argument cannot be copied. It is this latter case that this
1496   //    static_assert aims to catch.
1497   //
1498   // In contrast, `BindOnce()` only has one decision point. Once a move-only
1499   // type is captured by value into the internal `BindState`, the bound,
1500   // move-only argument will always be moved to the functor when invoked.
1501   // Failure to use std::move will simply fail the `kMoveOnlyTypeMustUseStdMove`
1502   // assert below instead.
1503   //
1504   // Note: `Passed()` is a legacy of supporting move-only types when repeating
1505   // callbacks were the only callback type. A `RepeatingCallback` with a
1506   // `Passed()` argument is really a `OnceCallback` and should eventually be
1507   // migrated.
1508   static_assert(
1509       BindArgument<i>::template ForwardedAs<Unwrapped>::
1510           template ToParamWithType<Param>::kMoveOnlyTypeMustUseBasePassed,
1511       "base::BindRepeating() argument is a move-only type. Use base::Passed() "
1512       "instead of std::move() to transfer ownership from the callback to the "
1513       "bound functor.");
1514   static_assert(
1515       BindArgument<i>::template ForwardedAs<Unwrapped>::
1516           template ToParamWithType<Param>::kNonConstRefParamMustBeWrapped,
1517       "Bound argument for non-const reference parameter must be wrapped in "
1518       "std::ref() or base::OwnedRef().");
1519   static_assert(
1520       BindArgument<i>::template ForwardedAs<Unwrapped>::
1521           template ToParamWithType<Param>::kCanBeForwardedToBoundFunctor,
1522       "Type mismatch between bound argument and bound functor's parameter.");
1523 
1524   static_assert(BindArgument<i>::template BoundAs<Arg>::template StoredAs<
1525                     Storage>::kMoveOnlyTypeMustUseStdMove,
1526                 "Attempting to bind a move-only type. Use std::move() to "
1527                 "transfer ownership to the created callback.");
1528   // In practice, this static_assert should be quite rare as the storage type
1529   // is deduced from the arguments passed to `BindOnce()`/`BindRepeating()`.
1530   static_assert(
1531       BindArgument<i>::template BoundAs<Arg>::template StoredAs<
1532           Storage>::kBindArgumentCanBeCaptured,
1533       "Cannot capture argument: is the argument copyable or movable?");
1534 
1535   // We forbid callbacks to use raw_ptr as a parameter. However, we allow
1536   // MayBeDangling<T> iff the callback argument was created using
1537   // `base::UnsafeDangling`.
1538   static_assert(
1539       BindArgument<i>::template ForwardedAs<
1540           Unwrapped>::template ToParamWithType<Param>::kNotARawPtr ||
1541           BindArgument<i>::template ToParamWithType<Param>::template StoredAs<
1542               Storage>::kMayBeDanglingMustBeUsed,
1543       "base::Bind() target functor has a parameter of type raw_ptr<T>. "
1544       "raw_ptr<T> should not be used for function parameters, please use T* or "
1545       "T& instead.");
1546 
1547   // A bound functor must take a dangling pointer argument (e.g. bound using the
1548   // UnsafeDangling helper) as a MayBeDangling<T>, to make it clear that the
1549   // pointee's lifetime must be externally validated before using it. For
1550   // methods, exempt a bound receiver (i.e. the this pointer) as it is not
1551   // passed as a regular function argument.
1552   static_assert(
1553       BindArgument<i>::template ToParamWithType<Param>::template StoredAs<
1554           Storage>::template kMayBeDanglingPtrPassedCorrectly<is_method>,
1555       "base::UnsafeDangling() pointers must be received by functors with "
1556       "MayBeDangling<T> as parameter.");
1557 
1558   static_assert(
1559       BindArgument<i>::template ToParamWithType<Param>::template StoredAs<
1560           Storage>::kUnsafeDanglingAndMayBeDanglingHaveMatchingTraits,
1561       "MayBeDangling<T> parameter must receive the same RawPtrTraits as the "
1562       "one passed to the corresponding base::UnsafeDangling() call.");
1563 };
1564 
1565 // Takes three same-length TypeLists, and applies AssertConstructible for each
1566 // triples.
1567 template <bool is_method,
1568           typename Index,
1569           typename Args,
1570           typename UnwrappedTypeList,
1571           typename ParamsList>
1572 struct AssertBindArgsValidity;
1573 
1574 template <bool is_method,
1575           size_t... Ns,
1576           typename... Args,
1577           typename... Unwrapped,
1578           typename... Params>
1579 struct AssertBindArgsValidity<is_method,
1580                               std::index_sequence<Ns...>,
1581                               TypeList<Args...>,
1582                               TypeList<Unwrapped...>,
1583                               TypeList<Params...>>
1584     : AssertConstructible<Ns,
1585                           is_method,
1586                           Args,
1587                           std::decay_t<Args>,
1588                           Unwrapped,
1589                           Params>... {
1590   static constexpr bool ok = true;
1591 };
1592 
1593 template <typename T>
1594 struct AssertBindArgIsNotBasePassed : public std::true_type {};
1595 
1596 template <typename T>
1597 struct AssertBindArgIsNotBasePassed<PassedWrapper<T>> : public std::false_type {
1598 };
1599 
1600 template <template <typename> class CallbackT,
1601           typename Functor,
1602           typename... Args>
1603 decltype(auto) BindImpl(Functor&& functor, Args&&... args) {
1604   // This block checks if each |args| matches to the corresponding params of the
1605   // target function. This check does not affect the behavior of Bind, but its
1606   // error message should be more readable.
1607   static constexpr bool kIsOnce = IsOnceCallback<CallbackT<void()>>::value;
1608   using Helper = BindTypeHelper<Functor, Args...>;
1609   using FunctorTraits = typename Helper::FunctorTraits;
1610   using BoundArgsList = typename Helper::BoundArgsList;
1611   using UnwrappedArgsList =
1612       MakeUnwrappedTypeList<kIsOnce, FunctorTraits::is_method, Args&&...>;
1613   using BoundParamsList = typename Helper::BoundParamsList;
1614   static_assert(
1615       MakeFunctorTraits<Functor>::is_stateless,
1616       "Capturing lambdas and stateful lambdas are intentionally not supported. "
1617       "Please use base::Bind{Once,Repeating} directly to bind arguments.");
1618   static_assert(
1619       AssertBindArgsValidity<FunctorTraits::is_method,
1620                              std::make_index_sequence<Helper::num_bounds>,
1621                              BoundArgsList, UnwrappedArgsList,
1622                              BoundParamsList>::ok,
1623       "The bound args need to be convertible to the target params.");
1624 
1625   using BindState = MakeBindStateType<Functor, Args...>;
1626   using UnboundRunType = MakeUnboundRunType<Functor, Args...>;
1627   using Invoker = Invoker<BindState, UnboundRunType>;
1628   using CallbackType = CallbackT<UnboundRunType>;
1629 
1630   // Store the invoke func into PolymorphicInvoke before casting it to
1631   // InvokeFuncStorage, so that we can ensure its type matches to
1632   // PolymorphicInvoke, to which CallbackType will cast back.
1633   using PolymorphicInvoke = typename CallbackType::PolymorphicInvoke;
1634   PolymorphicInvoke invoke_func;
1635   if constexpr (kIsOnce) {
1636     invoke_func = Invoker::RunOnce;
1637   } else {
1638     invoke_func = Invoker::Run;
1639   }
1640 
1641   using InvokeFuncStorage = BindStateBase::InvokeFuncStorage;
1642   return CallbackType(BindState::Create(
1643       reinterpret_cast<InvokeFuncStorage>(invoke_func),
1644       std::forward<Functor>(functor), std::forward<Args>(args)...));
1645 }
1646 
1647 // Special cases for binding to a base::{Once, Repeating}Callback without extra
1648 // bound arguments. We CHECK() the validity of callback to guard against null
1649 // pointers accidentally ending up in posted tasks, causing hard-to-debug
1650 // crashes.
1651 template <template <typename> class CallbackT,
1652           typename Signature,
1653           std::enable_if_t<std::is_same_v<CallbackT<Signature>,
1654                                           OnceCallback<Signature>>>* = nullptr>
1655 OnceCallback<Signature> BindImpl(OnceCallback<Signature> callback) {
1656   CHECK(callback);
1657   return callback;
1658 }
1659 
1660 template <template <typename> class CallbackT,
1661           typename Signature,
1662           std::enable_if_t<std::is_same_v<CallbackT<Signature>,
1663                                           OnceCallback<Signature>>>* = nullptr>
1664 OnceCallback<Signature> BindImpl(RepeatingCallback<Signature> callback) {
1665   CHECK(callback);
1666   return callback;
1667 }
1668 
1669 template <template <typename> class CallbackT,
1670           typename Signature,
1671           std::enable_if_t<std::is_same_v<CallbackT<Signature>,
1672                                           RepeatingCallback<Signature>>>* =
1673               nullptr>
1674 RepeatingCallback<Signature> BindImpl(RepeatingCallback<Signature> callback) {
1675   CHECK(callback);
1676   return callback;
1677 }
1678 
1679 template <template <typename> class CallbackT, typename Signature>
1680 auto BindImpl(absl::FunctionRef<Signature>, ...) {
1681   static_assert(
1682       AlwaysFalse<Signature>,
1683       "base::Bind{Once,Repeating} require strong ownership: non-owning "
1684       "function references may not bound as the functor due to potential "
1685       "lifetime issues.");
1686   return nullptr;
1687 }
1688 
1689 template <template <typename> class CallbackT, typename Signature>
1690 auto BindImpl(FunctionRef<Signature>, ...) {
1691   static_assert(
1692       AlwaysFalse<Signature>,
1693       "base::Bind{Once,Repeating} require strong ownership: non-owning "
1694       "function references may not bound as the functor due to potential "
1695       "lifetime issues.");
1696   return nullptr;
1697 }
1698 
1699 }  // namespace internal
1700 
1701 // An injection point to control |this| pointer behavior on a method invocation.
1702 // If IsWeakReceiver<> is true_type for |T| and |T| is used for a receiver of a
1703 // method, base::Bind cancels the method invocation if the receiver is tested as
1704 // false.
1705 // E.g. Foo::bar() is not called:
1706 //   struct Foo : base::SupportsWeakPtr<Foo> {
1707 //     void bar() {}
1708 //   };
1709 //
1710 //   WeakPtr<Foo> oo = nullptr;
1711 //   base::BindOnce(&Foo::bar, oo).Run();
1712 template <typename T>
1713 struct IsWeakReceiver : std::false_type {};
1714 
1715 template <typename T>
1716 struct IsWeakReceiver<std::reference_wrapper<T>> : IsWeakReceiver<T> {};
1717 
1718 template <typename T>
1719 struct IsWeakReceiver<WeakPtr<T>> : std::true_type {};
1720 
1721 // An injection point to control how objects are checked for maybe validity,
1722 // which is an optimistic thread-safe check for full validity.
1723 template <typename>
1724 struct MaybeValidTraits {
1725   template <typename T>
1726   static bool MaybeValid(const T& o) {
1727     return o.MaybeValid();
1728   }
1729 };
1730 
1731 // An injection point to control how bound objects passed to the target
1732 // function. BindUnwrapTraits<>::Unwrap() is called for each bound objects right
1733 // before the target function is invoked.
1734 template <typename>
1735 struct BindUnwrapTraits {
1736   template <typename T>
1737   static T&& Unwrap(T&& o) {
1738     return std::forward<T>(o);
1739   }
1740 };
1741 
1742 template <typename T, typename UnretainedTrait, RawPtrTraits PtrTraits>
1743 struct BindUnwrapTraits<
1744     internal::UnretainedWrapper<T, UnretainedTrait, PtrTraits>> {
1745   static auto Unwrap(
1746       const internal::UnretainedWrapper<T, UnretainedTrait, PtrTraits>& o) {
1747     return o.get();
1748   }
1749 };
1750 
1751 template <typename T, typename UnretainedTrait, RawPtrTraits PtrTraits>
1752 struct BindUnwrapTraits<
1753     internal::UnretainedRefWrapper<T, UnretainedTrait, PtrTraits>> {
1754   static T& Unwrap(
1755       const internal::UnretainedRefWrapper<T, UnretainedTrait, PtrTraits>& o) {
1756     return o.get();
1757   }
1758 };
1759 
1760 template <typename T>
1761 struct BindUnwrapTraits<internal::RetainedRefWrapper<T>> {
1762   static T* Unwrap(const internal::RetainedRefWrapper<T>& o) { return o.get(); }
1763 };
1764 
1765 template <typename T, typename Deleter>
1766 struct BindUnwrapTraits<internal::OwnedWrapper<T, Deleter>> {
1767   static T* Unwrap(const internal::OwnedWrapper<T, Deleter>& o) {
1768     return o.get();
1769   }
1770 };
1771 
1772 template <typename T>
1773 struct BindUnwrapTraits<internal::OwnedRefWrapper<T>> {
1774   static T& Unwrap(const internal::OwnedRefWrapper<T>& o) { return o.get(); }
1775 };
1776 
1777 template <typename T>
1778 struct BindUnwrapTraits<internal::PassedWrapper<T>> {
1779   static T Unwrap(const internal::PassedWrapper<T>& o) { return o.Take(); }
1780 };
1781 
1782 #if BUILDFLAG(IS_WIN)
1783 template <typename T>
1784 struct BindUnwrapTraits<Microsoft::WRL::ComPtr<T>> {
1785   static T* Unwrap(const Microsoft::WRL::ComPtr<T>& ptr) { return ptr.Get(); }
1786 };
1787 #endif
1788 
1789 // CallbackCancellationTraits allows customization of Callback's cancellation
1790 // semantics. By default, callbacks are not cancellable. A specialization should
1791 // set is_cancellable = true and implement an IsCancelled() that returns if the
1792 // callback should be cancelled.
1793 template <typename Functor, typename BoundArgsTuple, typename SFINAE>
1794 struct CallbackCancellationTraits {
1795   static constexpr bool is_cancellable = false;
1796 };
1797 
1798 // Specialization for method bound to weak pointer receiver.
1799 template <typename Functor, typename... BoundArgs>
1800 struct CallbackCancellationTraits<
1801     Functor,
1802     std::tuple<BoundArgs...>,
1803     std::enable_if_t<
1804         internal::IsWeakMethod<internal::FunctorTraits<Functor>::is_method,
1805                                BoundArgs...>::value>> {
1806   static constexpr bool is_cancellable = true;
1807 
1808   template <typename Receiver, typename... Args>
1809   static bool IsCancelled(const Functor&,
1810                           const Receiver& receiver,
1811                           const Args&...) {
1812     return !receiver;
1813   }
1814 
1815   template <typename Receiver, typename... Args>
1816   static bool MaybeValid(const Functor&,
1817                          const Receiver& receiver,
1818                          const Args&...) {
1819     return MaybeValidTraits<Receiver>::MaybeValid(receiver);
1820   }
1821 };
1822 
1823 // Specialization for a nested bind.
1824 template <typename Signature, typename... BoundArgs>
1825 struct CallbackCancellationTraits<OnceCallback<Signature>,
1826                                   std::tuple<BoundArgs...>> {
1827   static constexpr bool is_cancellable = true;
1828 
1829   template <typename Functor>
1830   static bool IsCancelled(const Functor& functor, const BoundArgs&...) {
1831     return functor.IsCancelled();
1832   }
1833 
1834   template <typename Functor>
1835   static bool MaybeValid(const Functor& functor, const BoundArgs&...) {
1836     return MaybeValidTraits<Functor>::MaybeValid(functor);
1837   }
1838 };
1839 
1840 template <typename Signature, typename... BoundArgs>
1841 struct CallbackCancellationTraits<RepeatingCallback<Signature>,
1842                                   std::tuple<BoundArgs...>> {
1843   static constexpr bool is_cancellable = true;
1844 
1845   template <typename Functor>
1846   static bool IsCancelled(const Functor& functor, const BoundArgs&...) {
1847     return functor.IsCancelled();
1848   }
1849 
1850   template <typename Functor>
1851   static bool MaybeValid(const Functor& functor, const BoundArgs&...) {
1852     return MaybeValidTraits<Functor>::MaybeValid(functor);
1853   }
1854 };
1855 
1856 }  // namespace base
1857 
1858 #endif  // BASE_FUNCTIONAL_BIND_INTERNAL_H_
1859