bind_internal.h 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565
  1. // Copyright (c) 2011 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_BIND_INTERNAL_H_
  5. #define BASE_BIND_INTERNAL_H_
  6. #include <stddef.h>
  7. #include <functional>
  8. #include <memory>
  9. #include <tuple>
  10. #include <type_traits>
  11. #include <utility>
  12. #include "base/allocator/buildflags.h"
  13. #include "base/allocator/partition_allocator/partition_alloc_config.h"
  14. #include "base/callback_internal.h"
  15. #include "base/check.h"
  16. #include "base/compiler_specific.h"
  17. #include "base/memory/raw_ptr.h"
  18. #include "base/memory/raw_ref.h"
  19. #include "base/memory/raw_scoped_refptr_mismatch_checker.h"
  20. #include "base/memory/weak_ptr.h"
  21. #include "base/notreached.h"
  22. #include "base/types/always_false.h"
  23. #include "build/build_config.h"
  24. #include "third_party/abseil-cpp/absl/functional/function_ref.h"
  25. #if BUILDFLAG(IS_APPLE) && !HAS_FEATURE(objc_arc)
  26. #include "base/mac/scoped_block.h"
  27. #endif
  28. // See base/callback.h for user documentation.
  29. //
  30. //
  31. // CONCEPTS:
  32. // Functor -- A movable type representing something that should be called.
  33. // All function pointers and Callback<> are functors even if the
  34. // invocation syntax differs.
  35. // RunType -- A function type (as opposed to function _pointer_ type) for
  36. // a Callback<>::Run(). Usually just a convenience typedef.
  37. // (Bound)Args -- A set of types that stores the arguments.
  38. //
  39. // Types:
  40. // ForceVoidReturn<> -- Helper class for translating function signatures to
  41. // equivalent forms with a "void" return type.
  42. // FunctorTraits<> -- Type traits used to determine the correct RunType and
  43. // invocation manner for a Functor. This is where function
  44. // signature adapters are applied.
  45. // StorageTraits<> -- Type traits that determine how a bound argument is
  46. // stored in BindState.
  47. // InvokeHelper<> -- Take a Functor + arguments and actually invokes it.
  48. // Handle the differing syntaxes needed for WeakPtr<>
  49. // support. This is separate from Invoker to avoid creating
  50. // multiple version of Invoker<>.
  51. // Invoker<> -- Unwraps the curried parameters and executes the Functor.
  52. // BindState<> -- Stores the curried parameters, and is the main entry point
  53. // into the Bind() system.
  54. #if BUILDFLAG(IS_WIN)
  55. namespace Microsoft {
  56. namespace WRL {
  57. template <typename>
  58. class ComPtr;
  59. } // namespace WRL
  60. } // namespace Microsoft
  61. #endif
  62. namespace base {
  63. template <typename T>
  64. struct IsWeakReceiver;
  65. template <typename>
  66. struct BindUnwrapTraits;
  67. template <typename Functor, typename BoundArgsTuple, typename SFINAE = void>
  68. struct CallbackCancellationTraits;
  69. template <typename Signature>
  70. class FunctionRef;
  71. namespace internal {
  72. template <typename Functor, typename SFINAE = void>
  73. struct FunctorTraits;
  74. template <typename T>
  75. class UnretainedWrapper {
  76. public:
  77. explicit UnretainedWrapper(T* o) : ptr_(o) {}
  78. // Trick to only instantiate these constructors if they are used. Otherwise,
  79. // instantiating UnretainedWrapper with a T that is not supported by
  80. // raw_ptr would trigger raw_ptr<T>'s static_assert.
  81. template <typename U = T, typename I>
  82. // Avoids having a raw_ptr<T> -> T* -> raw_ptr<T> round trip, which
  83. // would trigger the raw_ptr error detector if T* was dangling.
  84. explicit UnretainedWrapper(const raw_ptr<U, I>& o) : ptr_(o) {}
  85. template <typename U = T, typename I>
  86. explicit UnretainedWrapper(raw_ptr<U, I>&& o) : ptr_(std::move(o)) {}
  87. T* get() const { return ptr_; }
  88. private:
  89. #if defined(PA_USE_MTE_CHECKED_PTR_WITH_64_BITS_POINTERS)
  90. // When `MTECheckedPtr` is enabled as the backing implementation of
  91. // `raw_ptr`, there are too many different types that immediately
  92. // cause Chrome to crash. Some of these are inutterable as forward
  93. // declarations in `raw_ptr.h` (necessary to mark it as not
  94. // `IsSupportedType`) - in particular, nested classes
  95. // (`Foo::UnsupportedFoo`) cannot be marked as unsupported.
  96. //
  97. // As a compromise, we decay the wrapper to use `T*` only (rather
  98. // than `raw_ptr`) when `raw_ptr` is `MTECheckedPtr`.
  99. using ImplType = T*;
  100. #else
  101. using ImplType = std::conditional_t<raw_ptr_traits::IsSupportedType<T>::value,
  102. raw_ptr<T, DanglingUntriaged>,
  103. T*>;
  104. #endif // defined(PA_USE_MTE_CHECKED_PTR_WITH_64_BITS_POINTERS)
  105. ImplType ptr_;
  106. };
  107. // Storage type for std::reference_wrapper so `BindState` can internally store
  108. // unprotected references using raw_ptr.
  109. //
  110. // std::reference_wrapper<T> and T& do not work, since the reference lifetime is
  111. // not safely protected by MiraclePtr.
  112. //
  113. // UnretainedWrapper<T> and raw_ptr<T> do not work, since BindUnwrapTraits would
  114. // try to pass by T* rather than T&.
  115. //
  116. // raw_ref<T> is not used to differentiate between storing a `raw_ref<T>`
  117. // explicitly versus storing a `T&` or `std::ref()`.
  118. template <typename T, bool = raw_ptr_traits::IsSupportedType<T>::value>
  119. class UnretainedRefWrapper {
  120. public:
  121. explicit UnretainedRefWrapper(T& o) : ref_(o) {}
  122. T& get() const { return ref_; }
  123. private:
  124. T& ref_;
  125. };
  126. #if !defined(PA_USE_MTE_CHECKED_PTR_WITH_64_BITS_POINTERS)
  127. // Implementation of UnretainedRefWrapper for `T` where raw_ref<T> is supported.
  128. template <typename T>
  129. class UnretainedRefWrapper<T, true> {
  130. public:
  131. explicit UnretainedRefWrapper(T& o) : ref_(o) {}
  132. T& get() const { return *ref_; }
  133. private:
  134. const raw_ref<T, DanglingUntriaged> ref_;
  135. };
  136. // Implementation of UnretainedRefWrapper for `raw_ref<T>`.
  137. template <typename T, typename I, bool b>
  138. class UnretainedRefWrapper<raw_ref<T, I>, b> {
  139. public:
  140. explicit UnretainedRefWrapper(const raw_ref<T, I>& ref) : ref_(ref) {}
  141. explicit UnretainedRefWrapper(raw_ref<T, I>&& ref) : ref_(std::move(ref)) {}
  142. T& get() const { return *ref_; }
  143. private:
  144. const raw_ref<T, I> ref_;
  145. };
  146. #endif
  147. template <typename T>
  148. class RetainedRefWrapper {
  149. public:
  150. explicit RetainedRefWrapper(T* o) : ptr_(o) {}
  151. explicit RetainedRefWrapper(scoped_refptr<T> o) : ptr_(std::move(o)) {}
  152. T* get() const { return ptr_.get(); }
  153. private:
  154. scoped_refptr<T> ptr_;
  155. };
  156. template <typename T>
  157. struct IgnoreResultHelper {
  158. explicit IgnoreResultHelper(T functor) : functor_(std::move(functor)) {}
  159. explicit operator bool() const { return !!functor_; }
  160. T functor_;
  161. };
  162. template <typename T, typename Deleter = std::default_delete<T>>
  163. class OwnedWrapper {
  164. public:
  165. explicit OwnedWrapper(T* o) : ptr_(o) {}
  166. explicit OwnedWrapper(std::unique_ptr<T, Deleter>&& ptr)
  167. : ptr_(std::move(ptr)) {}
  168. T* get() const { return ptr_.get(); }
  169. private:
  170. std::unique_ptr<T, Deleter> ptr_;
  171. };
  172. template <typename T>
  173. class OwnedRefWrapper {
  174. public:
  175. explicit OwnedRefWrapper(const T& t) : t_(t) {}
  176. explicit OwnedRefWrapper(T&& t) : t_(std::move(t)) {}
  177. T& get() const { return t_; }
  178. private:
  179. mutable T t_;
  180. };
  181. // PassedWrapper is a copyable adapter for a scoper that ignores const.
  182. //
  183. // It is needed to get around the fact that Bind() takes a const reference to
  184. // all its arguments. Because Bind() takes a const reference to avoid
  185. // unnecessary copies, it is incompatible with movable-but-not-copyable
  186. // types; doing a destructive "move" of the type into Bind() would violate
  187. // the const correctness.
  188. //
  189. // This conundrum cannot be solved without either C++11 rvalue references or
  190. // a O(2^n) blowup of Bind() templates to handle each combination of regular
  191. // types and movable-but-not-copyable types. Thus we introduce a wrapper type
  192. // that is copyable to transmit the correct type information down into
  193. // BindState<>. Ignoring const in this type makes sense because it is only
  194. // created when we are explicitly trying to do a destructive move.
  195. //
  196. // Two notes:
  197. // 1) PassedWrapper supports any type that has a move constructor, however
  198. // the type will need to be specifically allowed in order for it to be
  199. // bound to a Callback. We guard this explicitly at the call of Passed()
  200. // to make for clear errors. Things not given to Passed() will be forwarded
  201. // and stored by value which will not work for general move-only types.
  202. // 2) is_valid_ is distinct from NULL because it is valid to bind a "NULL"
  203. // scoper to a Callback and allow the Callback to execute once.
  204. template <typename T>
  205. class PassedWrapper {
  206. public:
  207. explicit PassedWrapper(T&& scoper) : scoper_(std::move(scoper)) {}
  208. PassedWrapper(PassedWrapper&& other)
  209. : is_valid_(other.is_valid_), scoper_(std::move(other.scoper_)) {}
  210. T Take() const {
  211. CHECK(is_valid_);
  212. is_valid_ = false;
  213. return std::move(scoper_);
  214. }
  215. private:
  216. mutable bool is_valid_ = true;
  217. mutable T scoper_;
  218. };
  219. template <typename T>
  220. using Unwrapper = BindUnwrapTraits<std::decay_t<T>>;
  221. template <typename T>
  222. decltype(auto) Unwrap(T&& o) {
  223. return Unwrapper<T>::Unwrap(std::forward<T>(o));
  224. }
  225. // IsWeakMethod is a helper that determine if we are binding a WeakPtr<> to a
  226. // method. It is used internally by Bind() to select the correct
  227. // InvokeHelper that will no-op itself in the event the WeakPtr<> for
  228. // the target object is invalidated.
  229. //
  230. // The first argument should be the type of the object that will be received by
  231. // the method.
  232. template <bool is_method, typename... Args>
  233. struct IsWeakMethod : std::false_type {};
  234. template <typename T, typename... Args>
  235. struct IsWeakMethod<true, T, Args...> : IsWeakReceiver<T> {};
  236. // Packs a list of types to hold them in a single type.
  237. template <typename... Types>
  238. struct TypeList {};
  239. // Used for DropTypeListItem implementation.
  240. template <size_t n, typename List>
  241. struct DropTypeListItemImpl;
  242. // Do not use enable_if and SFINAE here to avoid MSVC2013 compile failure.
  243. template <size_t n, typename T, typename... List>
  244. struct DropTypeListItemImpl<n, TypeList<T, List...>>
  245. : DropTypeListItemImpl<n - 1, TypeList<List...>> {};
  246. template <typename T, typename... List>
  247. struct DropTypeListItemImpl<0, TypeList<T, List...>> {
  248. using Type = TypeList<T, List...>;
  249. };
  250. template <>
  251. struct DropTypeListItemImpl<0, TypeList<>> {
  252. using Type = TypeList<>;
  253. };
  254. // A type-level function that drops |n| list item from given TypeList.
  255. template <size_t n, typename List>
  256. using DropTypeListItem = typename DropTypeListItemImpl<n, List>::Type;
  257. // Used for TakeTypeListItem implementation.
  258. template <size_t n, typename List, typename... Accum>
  259. struct TakeTypeListItemImpl;
  260. // Do not use enable_if and SFINAE here to avoid MSVC2013 compile failure.
  261. template <size_t n, typename T, typename... List, typename... Accum>
  262. struct TakeTypeListItemImpl<n, TypeList<T, List...>, Accum...>
  263. : TakeTypeListItemImpl<n - 1, TypeList<List...>, Accum..., T> {};
  264. template <typename T, typename... List, typename... Accum>
  265. struct TakeTypeListItemImpl<0, TypeList<T, List...>, Accum...> {
  266. using Type = TypeList<Accum...>;
  267. };
  268. template <typename... Accum>
  269. struct TakeTypeListItemImpl<0, TypeList<>, Accum...> {
  270. using Type = TypeList<Accum...>;
  271. };
  272. // A type-level function that takes first |n| list item from given TypeList.
  273. // E.g. TakeTypeListItem<3, TypeList<A, B, C, D>> is evaluated to
  274. // TypeList<A, B, C>.
  275. template <size_t n, typename List>
  276. using TakeTypeListItem = typename TakeTypeListItemImpl<n, List>::Type;
  277. // Used for ConcatTypeLists implementation.
  278. template <typename List1, typename List2>
  279. struct ConcatTypeListsImpl;
  280. template <typename... Types1, typename... Types2>
  281. struct ConcatTypeListsImpl<TypeList<Types1...>, TypeList<Types2...>> {
  282. using Type = TypeList<Types1..., Types2...>;
  283. };
  284. // A type-level function that concats two TypeLists.
  285. template <typename List1, typename List2>
  286. using ConcatTypeLists = typename ConcatTypeListsImpl<List1, List2>::Type;
  287. // Used for MakeFunctionType implementation.
  288. template <typename R, typename ArgList>
  289. struct MakeFunctionTypeImpl;
  290. template <typename R, typename... Args>
  291. struct MakeFunctionTypeImpl<R, TypeList<Args...>> {
  292. // MSVC 2013 doesn't support Type Alias of function types.
  293. // Revisit this after we update it to newer version.
  294. typedef R Type(Args...);
  295. };
  296. // A type-level function that constructs a function type that has |R| as its
  297. // return type and has TypeLists items as its arguments.
  298. template <typename R, typename ArgList>
  299. using MakeFunctionType = typename MakeFunctionTypeImpl<R, ArgList>::Type;
  300. // Used for ExtractArgs and ExtractReturnType.
  301. template <typename Signature>
  302. struct ExtractArgsImpl;
  303. template <typename R, typename... Args>
  304. struct ExtractArgsImpl<R(Args...)> {
  305. using ReturnType = R;
  306. using ArgsList = TypeList<Args...>;
  307. };
  308. // A type-level function that extracts function arguments into a TypeList.
  309. // E.g. ExtractArgs<R(A, B, C)> is evaluated to TypeList<A, B, C>.
  310. template <typename Signature>
  311. using ExtractArgs = typename ExtractArgsImpl<Signature>::ArgsList;
  312. // A type-level function that extracts the return type of a function.
  313. // E.g. ExtractReturnType<R(A, B, C)> is evaluated to R.
  314. template <typename Signature>
  315. using ExtractReturnType = typename ExtractArgsImpl<Signature>::ReturnType;
  316. template <typename Callable,
  317. typename Signature = decltype(&Callable::operator())>
  318. struct ExtractCallableRunTypeImpl;
  319. template <typename Callable, typename R, typename... Args>
  320. struct ExtractCallableRunTypeImpl<Callable, R (Callable::*)(Args...)> {
  321. using Type = R(Args...);
  322. };
  323. template <typename Callable, typename R, typename... Args>
  324. struct ExtractCallableRunTypeImpl<Callable, R (Callable::*)(Args...) const> {
  325. using Type = R(Args...);
  326. };
  327. template <typename Callable, typename R, typename... Args>
  328. struct ExtractCallableRunTypeImpl<Callable, R (Callable::*)(Args...) noexcept> {
  329. using Type = R(Args...);
  330. };
  331. template <typename Callable, typename R, typename... Args>
  332. struct ExtractCallableRunTypeImpl<Callable,
  333. R (Callable::*)(Args...) const noexcept> {
  334. using Type = R(Args...);
  335. };
  336. // Evaluated to RunType of the given callable type.
  337. // Example:
  338. // auto f = [](int, char*) { return 0.1; };
  339. // ExtractCallableRunType<decltype(f)>
  340. // is evaluated to
  341. // double(int, char*);
  342. template <typename Callable>
  343. using ExtractCallableRunType =
  344. typename ExtractCallableRunTypeImpl<Callable>::Type;
  345. // IsCallableObject<Functor> is std::true_type if |Functor| has operator().
  346. // Otherwise, it's std::false_type.
  347. // Example:
  348. // IsCallableObject<void(*)()>::value is false.
  349. //
  350. // struct Foo {};
  351. // IsCallableObject<void(Foo::*)()>::value is false.
  352. //
  353. // int i = 0;
  354. // auto f = [i]() {};
  355. // IsCallableObject<decltype(f)>::value is false.
  356. template <typename Functor, typename SFINAE = void>
  357. struct IsCallableObject : std::false_type {};
  358. template <typename Callable>
  359. struct IsCallableObject<Callable, std::void_t<decltype(&Callable::operator())>>
  360. : std::true_type {};
  361. // HasRefCountedTypeAsRawPtr inherits from true_type when any of the |Args| is a
  362. // raw pointer to a RefCounted type.
  363. template <typename... Ts>
  364. struct HasRefCountedTypeAsRawPtr
  365. : std::disjunction<NeedsScopedRefptrButGetsRawPtr<Ts>...> {};
  366. // ForceVoidReturn<>
  367. //
  368. // Set of templates that support forcing the function return type to void.
  369. template <typename Sig>
  370. struct ForceVoidReturn;
  371. template <typename R, typename... Args>
  372. struct ForceVoidReturn<R(Args...)> {
  373. using RunType = void(Args...);
  374. };
  375. // FunctorTraits<>
  376. //
  377. // See description at top of file.
  378. template <typename Functor, typename SFINAE>
  379. struct FunctorTraits;
  380. // For callable types.
  381. // This specialization handles lambdas (captureless and capturing) and functors
  382. // with a call operator. Capturing lambdas and stateful functors are explicitly
  383. // disallowed by BindImpl().
  384. //
  385. // Example:
  386. //
  387. // // Captureless lambdas are allowed.
  388. // []() {return 42;};
  389. //
  390. // // Capturing lambdas are *not* allowed.
  391. // int x;
  392. // [x]() {return x;};
  393. //
  394. // // Any empty class with operator() is allowed.
  395. // struct Foo {
  396. // void operator()() const {}
  397. // // No non-static member variable and no virtual functions.
  398. // };
  399. template <typename Functor>
  400. struct FunctorTraits<Functor,
  401. std::enable_if_t<IsCallableObject<Functor>::value>> {
  402. using RunType = ExtractCallableRunType<Functor>;
  403. static constexpr bool is_method = false;
  404. static constexpr bool is_nullable = false;
  405. static constexpr bool is_callback = false;
  406. static constexpr bool is_stateless = std::is_empty_v<Functor>;
  407. template <typename RunFunctor, typename... RunArgs>
  408. static ExtractReturnType<RunType> Invoke(RunFunctor&& functor,
  409. RunArgs&&... args) {
  410. return std::forward<RunFunctor>(functor)(std::forward<RunArgs>(args)...);
  411. }
  412. };
  413. // For functions.
  414. template <typename R, typename... Args>
  415. struct FunctorTraits<R (*)(Args...)> {
  416. using RunType = R(Args...);
  417. static constexpr bool is_method = false;
  418. static constexpr bool is_nullable = true;
  419. static constexpr bool is_callback = false;
  420. static constexpr bool is_stateless = true;
  421. template <typename Function, typename... RunArgs>
  422. static R Invoke(Function&& function, RunArgs&&... args) {
  423. return std::forward<Function>(function)(std::forward<RunArgs>(args)...);
  424. }
  425. };
  426. #if BUILDFLAG(IS_WIN) && !defined(ARCH_CPU_64_BITS)
  427. // For functions.
  428. template <typename R, typename... Args>
  429. struct FunctorTraits<R(__stdcall*)(Args...)> {
  430. using RunType = R(Args...);
  431. static constexpr bool is_method = false;
  432. static constexpr bool is_nullable = true;
  433. static constexpr bool is_callback = false;
  434. static constexpr bool is_stateless = true;
  435. template <typename... RunArgs>
  436. static R Invoke(R(__stdcall* function)(Args...), RunArgs&&... args) {
  437. return function(std::forward<RunArgs>(args)...);
  438. }
  439. };
  440. // For functions.
  441. template <typename R, typename... Args>
  442. struct FunctorTraits<R(__fastcall*)(Args...)> {
  443. using RunType = R(Args...);
  444. static constexpr bool is_method = false;
  445. static constexpr bool is_nullable = true;
  446. static constexpr bool is_callback = false;
  447. static constexpr bool is_stateless = true;
  448. template <typename... RunArgs>
  449. static R Invoke(R(__fastcall* function)(Args...), RunArgs&&... args) {
  450. return function(std::forward<RunArgs>(args)...);
  451. }
  452. };
  453. #endif // BUILDFLAG(IS_WIN) && !defined(ARCH_CPU_64_BITS)
  454. #if BUILDFLAG(IS_APPLE)
  455. // Support for Objective-C blocks. There are two implementation depending
  456. // on whether Automated Reference Counting (ARC) is enabled. When ARC is
  457. // enabled, then the block itself can be bound as the compiler will ensure
  458. // its lifetime will be correctly managed. Otherwise, require the block to
  459. // be wrapped in a base::mac::ScopedBlock (via base::RetainBlock) that will
  460. // correctly manage the block lifetime.
  461. //
  462. // The two implementation ensure that the One Definition Rule (ODR) is not
  463. // broken (it is not possible to write a template base::RetainBlock that would
  464. // work correctly both with ARC enabled and disabled).
  465. #if HAS_FEATURE(objc_arc)
  466. template <typename R, typename... Args>
  467. struct FunctorTraits<R (^)(Args...)> {
  468. using RunType = R(Args...);
  469. static constexpr bool is_method = false;
  470. static constexpr bool is_nullable = true;
  471. static constexpr bool is_callback = false;
  472. static constexpr bool is_stateless = true;
  473. template <typename BlockType, typename... RunArgs>
  474. static R Invoke(BlockType&& block, RunArgs&&... args) {
  475. // According to LLVM documentation (§ 6.3), "local variables of automatic
  476. // storage duration do not have precise lifetime." Use objc_precise_lifetime
  477. // to ensure that the Objective-C block is not deallocated until it has
  478. // finished executing even if the Callback<> is destroyed during the block
  479. // execution.
  480. // https://clang.llvm.org/docs/AutomaticReferenceCounting.html#precise-lifetime-semantics
  481. __attribute__((objc_precise_lifetime)) R (^scoped_block)(Args...) = block;
  482. return scoped_block(std::forward<RunArgs>(args)...);
  483. }
  484. };
  485. #else // HAS_FEATURE(objc_arc)
  486. template <typename R, typename... Args>
  487. struct FunctorTraits<base::mac::ScopedBlock<R (^)(Args...)>> {
  488. using RunType = R(Args...);
  489. static constexpr bool is_method = false;
  490. static constexpr bool is_nullable = true;
  491. static constexpr bool is_callback = false;
  492. static constexpr bool is_stateless = true;
  493. template <typename BlockType, typename... RunArgs>
  494. static R Invoke(BlockType&& block, RunArgs&&... args) {
  495. // Copy the block to ensure that the Objective-C block is not deallocated
  496. // until it has finished executing even if the Callback<> is destroyed
  497. // during the block execution.
  498. base::mac::ScopedBlock<R (^)(Args...)> scoped_block(block);
  499. return scoped_block.get()(std::forward<RunArgs>(args)...);
  500. }
  501. };
  502. #endif // HAS_FEATURE(objc_arc)
  503. #endif // BUILDFLAG(IS_APPLE)
  504. // For methods.
  505. template <typename R, typename Receiver, typename... Args>
  506. struct FunctorTraits<R (Receiver::*)(Args...)> {
  507. using RunType = R(Receiver*, Args...);
  508. static constexpr bool is_method = true;
  509. static constexpr bool is_nullable = true;
  510. static constexpr bool is_callback = false;
  511. static constexpr bool is_stateless = true;
  512. template <typename Method, typename ReceiverPtr, typename... RunArgs>
  513. static R Invoke(Method method,
  514. ReceiverPtr&& receiver_ptr,
  515. RunArgs&&... args) {
  516. return ((*receiver_ptr).*method)(std::forward<RunArgs>(args)...);
  517. }
  518. };
  519. // For const methods.
  520. template <typename R, typename Receiver, typename... Args>
  521. struct FunctorTraits<R (Receiver::*)(Args...) const> {
  522. using RunType = R(const Receiver*, Args...);
  523. static constexpr bool is_method = true;
  524. static constexpr bool is_nullable = true;
  525. static constexpr bool is_callback = false;
  526. static constexpr bool is_stateless = true;
  527. template <typename Method, typename ReceiverPtr, typename... RunArgs>
  528. static R Invoke(Method method,
  529. ReceiverPtr&& receiver_ptr,
  530. RunArgs&&... args) {
  531. return ((*receiver_ptr).*method)(std::forward<RunArgs>(args)...);
  532. }
  533. };
  534. #if BUILDFLAG(IS_WIN) && !defined(ARCH_CPU_64_BITS)
  535. // For __stdcall methods.
  536. template <typename R, typename Receiver, typename... Args>
  537. struct FunctorTraits<R (__stdcall Receiver::*)(Args...)> {
  538. using RunType = R(Receiver*, Args...);
  539. static constexpr bool is_method = true;
  540. static constexpr bool is_nullable = true;
  541. static constexpr bool is_callback = false;
  542. static constexpr bool is_stateless = true;
  543. template <typename Method, typename ReceiverPtr, typename... RunArgs>
  544. static R Invoke(Method method,
  545. ReceiverPtr&& receiver_ptr,
  546. RunArgs&&... args) {
  547. return ((*receiver_ptr).*method)(std::forward<RunArgs>(args)...);
  548. }
  549. };
  550. // For __stdcall const methods.
  551. template <typename R, typename Receiver, typename... Args>
  552. struct FunctorTraits<R (__stdcall Receiver::*)(Args...) const> {
  553. using RunType = R(const Receiver*, Args...);
  554. static constexpr bool is_method = true;
  555. static constexpr bool is_nullable = true;
  556. static constexpr bool is_callback = false;
  557. static constexpr bool is_stateless = true;
  558. template <typename Method, typename ReceiverPtr, typename... RunArgs>
  559. static R Invoke(Method method,
  560. ReceiverPtr&& receiver_ptr,
  561. RunArgs&&... args) {
  562. return ((*receiver_ptr).*method)(std::forward<RunArgs>(args)...);
  563. }
  564. };
  565. #endif // BUILDFLAG(IS_WIN) && !defined(ARCH_CPU_64_BITS)
  566. #ifdef __cpp_noexcept_function_type
  567. // noexcept makes a distinct function type in C++17.
  568. // I.e. `void(*)()` and `void(*)() noexcept` are same in pre-C++17, and
  569. // different in C++17.
  570. template <typename R, typename... Args>
  571. struct FunctorTraits<R (*)(Args...) noexcept> : FunctorTraits<R (*)(Args...)> {
  572. };
  573. template <typename R, typename Receiver, typename... Args>
  574. struct FunctorTraits<R (Receiver::*)(Args...) noexcept>
  575. : FunctorTraits<R (Receiver::*)(Args...)> {};
  576. template <typename R, typename Receiver, typename... Args>
  577. struct FunctorTraits<R (Receiver::*)(Args...) const noexcept>
  578. : FunctorTraits<R (Receiver::*)(Args...) const> {};
  579. #endif
  580. // For IgnoreResults.
  581. template <typename T>
  582. struct FunctorTraits<IgnoreResultHelper<T>> : FunctorTraits<T> {
  583. using RunType =
  584. typename ForceVoidReturn<typename FunctorTraits<T>::RunType>::RunType;
  585. template <typename IgnoreResultType, typename... RunArgs>
  586. static void Invoke(IgnoreResultType&& ignore_result_helper,
  587. RunArgs&&... args) {
  588. FunctorTraits<T>::Invoke(
  589. std::forward<IgnoreResultType>(ignore_result_helper).functor_,
  590. std::forward<RunArgs>(args)...);
  591. }
  592. };
  593. // For OnceCallbacks.
  594. template <typename R, typename... Args>
  595. struct FunctorTraits<OnceCallback<R(Args...)>> {
  596. using RunType = R(Args...);
  597. static constexpr bool is_method = false;
  598. static constexpr bool is_nullable = true;
  599. static constexpr bool is_callback = true;
  600. static constexpr bool is_stateless = true;
  601. template <typename CallbackType, typename... RunArgs>
  602. static R Invoke(CallbackType&& callback, RunArgs&&... args) {
  603. DCHECK(!callback.is_null());
  604. return std::forward<CallbackType>(callback).Run(
  605. std::forward<RunArgs>(args)...);
  606. }
  607. };
  608. // For RepeatingCallbacks.
  609. template <typename R, typename... Args>
  610. struct FunctorTraits<RepeatingCallback<R(Args...)>> {
  611. using RunType = R(Args...);
  612. static constexpr bool is_method = false;
  613. static constexpr bool is_nullable = true;
  614. static constexpr bool is_callback = true;
  615. static constexpr bool is_stateless = true;
  616. template <typename CallbackType, typename... RunArgs>
  617. static R Invoke(CallbackType&& callback, RunArgs&&... args) {
  618. DCHECK(!callback.is_null());
  619. return std::forward<CallbackType>(callback).Run(
  620. std::forward<RunArgs>(args)...);
  621. }
  622. };
  623. template <typename Functor>
  624. using MakeFunctorTraits = FunctorTraits<std::decay_t<Functor>>;
  625. // StorageTraits<>
  626. //
  627. // See description at top of file.
  628. template <typename T>
  629. struct StorageTraits {
  630. using Type = T;
  631. };
  632. // For T*, store as UnretainedWrapper<T> for safety, as it internally uses
  633. // raw_ptr<T> (when possible).
  634. template <typename T>
  635. struct StorageTraits<T*> {
  636. using Type = UnretainedWrapper<T>;
  637. };
  638. // Unwrap std::reference_wrapper and store it in a custom wrapper so that
  639. // references are also protected with raw_ptr<T>.
  640. template <typename T>
  641. struct StorageTraits<std::reference_wrapper<T>> {
  642. using Type = UnretainedRefWrapper<T>;
  643. };
  644. template <typename T>
  645. using MakeStorageType = typename StorageTraits<std::decay_t<T>>::Type;
  646. // InvokeHelper<>
  647. //
  648. // There are 2 logical InvokeHelper<> specializations: normal, WeakCalls.
  649. //
  650. // The normal type just calls the underlying runnable.
  651. //
  652. // WeakCalls need special syntax that is applied to the first argument to check
  653. // if they should no-op themselves.
  654. template <bool is_weak_call, typename ReturnType>
  655. struct InvokeHelper;
  656. template <typename ReturnType>
  657. struct InvokeHelper<false, ReturnType> {
  658. template <typename Functor, typename... RunArgs>
  659. static inline ReturnType MakeItSo(Functor&& functor, RunArgs&&... args) {
  660. using Traits = MakeFunctorTraits<Functor>;
  661. return Traits::Invoke(std::forward<Functor>(functor),
  662. std::forward<RunArgs>(args)...);
  663. }
  664. };
  665. template <typename ReturnType>
  666. struct InvokeHelper<true, ReturnType> {
  667. // WeakCalls are only supported for functions with a void return type.
  668. // Otherwise, the function result would be undefined if the WeakPtr<>
  669. // is invalidated.
  670. static_assert(std::is_void_v<ReturnType>,
  671. "weak_ptrs can only bind to methods without return values");
  672. template <typename Functor, typename BoundWeakPtr, typename... RunArgs>
  673. static inline void MakeItSo(Functor&& functor,
  674. BoundWeakPtr&& weak_ptr,
  675. RunArgs&&... args) {
  676. if (!weak_ptr)
  677. return;
  678. using Traits = MakeFunctorTraits<Functor>;
  679. Traits::Invoke(std::forward<Functor>(functor),
  680. std::forward<BoundWeakPtr>(weak_ptr),
  681. std::forward<RunArgs>(args)...);
  682. }
  683. };
  684. // Invoker<>
  685. //
  686. // See description at the top of the file.
  687. template <typename StorageType, typename UnboundRunType>
  688. struct Invoker;
  689. template <typename StorageType, typename R, typename... UnboundArgs>
  690. struct Invoker<StorageType, R(UnboundArgs...)> {
  691. static R RunOnce(BindStateBase* base,
  692. PassingType<UnboundArgs>... unbound_args) {
  693. // Local references to make debugger stepping easier. If in a debugger,
  694. // you really want to warp ahead and step through the
  695. // InvokeHelper<>::MakeItSo() call below.
  696. StorageType* storage = static_cast<StorageType*>(base);
  697. static constexpr size_t num_bound_args =
  698. std::tuple_size_v<decltype(storage->bound_args_)>;
  699. return RunImpl(std::move(storage->functor_),
  700. std::move(storage->bound_args_),
  701. std::make_index_sequence<num_bound_args>(),
  702. std::forward<UnboundArgs>(unbound_args)...);
  703. }
  704. static R Run(BindStateBase* base, PassingType<UnboundArgs>... unbound_args) {
  705. // Local references to make debugger stepping easier. If in a debugger,
  706. // you really want to warp ahead and step through the
  707. // InvokeHelper<>::MakeItSo() call below.
  708. const StorageType* storage = static_cast<StorageType*>(base);
  709. static constexpr size_t num_bound_args =
  710. std::tuple_size_v<decltype(storage->bound_args_)>;
  711. return RunImpl(storage->functor_, storage->bound_args_,
  712. std::make_index_sequence<num_bound_args>(),
  713. std::forward<UnboundArgs>(unbound_args)...);
  714. }
  715. private:
  716. template <typename Functor, typename BoundArgsTuple, size_t... indices>
  717. static inline R RunImpl(Functor&& functor,
  718. BoundArgsTuple&& bound,
  719. std::index_sequence<indices...>,
  720. UnboundArgs&&... unbound_args) {
  721. static constexpr bool is_method = MakeFunctorTraits<Functor>::is_method;
  722. using DecayedArgsTuple = std::decay_t<BoundArgsTuple>;
  723. static constexpr bool is_weak_call =
  724. IsWeakMethod<is_method,
  725. std::tuple_element_t<indices, DecayedArgsTuple>...>();
  726. return InvokeHelper<is_weak_call, R>::MakeItSo(
  727. std::forward<Functor>(functor),
  728. Unwrap(std::get<indices>(std::forward<BoundArgsTuple>(bound)))...,
  729. std::forward<UnboundArgs>(unbound_args)...);
  730. }
  731. };
  732. // Extracts necessary type info from Functor and BoundArgs.
  733. // Used to implement MakeUnboundRunType, BindOnce and BindRepeating.
  734. template <typename Functor, typename... BoundArgs>
  735. struct BindTypeHelper {
  736. static constexpr size_t num_bounds = sizeof...(BoundArgs);
  737. using FunctorTraits = MakeFunctorTraits<Functor>;
  738. // Example:
  739. // When Functor is `double (Foo::*)(int, const std::string&)`, and BoundArgs
  740. // is a template pack of `Foo*` and `int16_t`:
  741. // - RunType is `double(Foo*, int, const std::string&)`,
  742. // - ReturnType is `double`,
  743. // - RunParamsList is `TypeList<Foo*, int, const std::string&>`,
  744. // - BoundParamsList is `TypeList<Foo*, int>`,
  745. // - UnboundParamsList is `TypeList<const std::string&>`,
  746. // - BoundArgsList is `TypeList<Foo*, int16_t>`,
  747. // - UnboundRunType is `double(const std::string&)`.
  748. using RunType = typename FunctorTraits::RunType;
  749. using ReturnType = ExtractReturnType<RunType>;
  750. using RunParamsList = ExtractArgs<RunType>;
  751. using BoundParamsList = TakeTypeListItem<num_bounds, RunParamsList>;
  752. using UnboundParamsList = DropTypeListItem<num_bounds, RunParamsList>;
  753. using BoundArgsList = TypeList<BoundArgs...>;
  754. using UnboundRunType = MakeFunctionType<ReturnType, UnboundParamsList>;
  755. };
  756. template <typename Functor>
  757. std::enable_if_t<FunctorTraits<Functor>::is_nullable, bool> IsNull(
  758. const Functor& functor) {
  759. return !functor;
  760. }
  761. template <typename Functor>
  762. std::enable_if_t<!FunctorTraits<Functor>::is_nullable, bool> IsNull(
  763. const Functor&) {
  764. return false;
  765. }
  766. // Used by QueryCancellationTraits below.
  767. template <typename Functor, typename BoundArgsTuple, size_t... indices>
  768. bool QueryCancellationTraitsImpl(BindStateBase::CancellationQueryMode mode,
  769. const Functor& functor,
  770. const BoundArgsTuple& bound_args,
  771. std::index_sequence<indices...>) {
  772. switch (mode) {
  773. case BindStateBase::IS_CANCELLED:
  774. return CallbackCancellationTraits<Functor, BoundArgsTuple>::IsCancelled(
  775. functor, std::get<indices>(bound_args)...);
  776. case BindStateBase::MAYBE_VALID:
  777. return CallbackCancellationTraits<Functor, BoundArgsTuple>::MaybeValid(
  778. functor, std::get<indices>(bound_args)...);
  779. }
  780. NOTREACHED();
  781. return false;
  782. }
  783. // Relays |base| to corresponding CallbackCancellationTraits<>::Run(). Returns
  784. // true if the callback |base| represents is canceled.
  785. template <typename BindStateType>
  786. bool QueryCancellationTraits(const BindStateBase* base,
  787. BindStateBase::CancellationQueryMode mode) {
  788. const BindStateType* storage = static_cast<const BindStateType*>(base);
  789. static constexpr size_t num_bound_args =
  790. std::tuple_size_v<decltype(storage->bound_args_)>;
  791. return QueryCancellationTraitsImpl(
  792. mode, storage->functor_, storage->bound_args_,
  793. std::make_index_sequence<num_bound_args>());
  794. }
  795. // The base case of BanUnconstructedRefCountedReceiver that checks nothing.
  796. template <typename Functor, typename Receiver, typename... Unused>
  797. std::enable_if_t<
  798. !(MakeFunctorTraits<Functor>::is_method &&
  799. IsPointerV<std::decay_t<Receiver>> &&
  800. IsRefCountedType<RemovePointerT<std::decay_t<Receiver>>>::value)>
  801. BanUnconstructedRefCountedReceiver(const Receiver& receiver, Unused&&...) {}
  802. template <typename Functor>
  803. void BanUnconstructedRefCountedReceiver() {}
  804. // Asserts that Callback is not the first owner of a ref-counted receiver.
  805. template <typename Functor, typename Receiver, typename... Unused>
  806. std::enable_if_t<
  807. MakeFunctorTraits<Functor>::is_method &&
  808. IsPointerV<std::decay_t<Receiver>> &&
  809. IsRefCountedType<RemovePointerT<std::decay_t<Receiver>>>::value>
  810. BanUnconstructedRefCountedReceiver(const Receiver& receiver, Unused&&...) {
  811. DCHECK(receiver);
  812. // It's error prone to make the implicit first reference to ref-counted types.
  813. // In the example below, base::BindOnce() would make the implicit first
  814. // reference to the ref-counted Foo. If PostTask() failed or the posted task
  815. // ran fast enough, the newly created instance could be destroyed before `oo`
  816. // makes another reference.
  817. // Foo::Foo() {
  818. // base::ThreadPool::PostTask(FROM_HERE, base::BindOnce(&Foo::Bar, this));
  819. // }
  820. //
  821. // scoped_refptr<Foo> oo = new Foo();
  822. //
  823. // Hence, base::Bind{Once,Repeating}() refuses to create the first reference
  824. // to ref-counted objects, and DCHECK()s otherwise. As above, that typically
  825. // happens around PostTask() in their constructor, and such objects can be
  826. // destroyed before `new` returns if the task resolves fast enough.
  827. //
  828. // Instead of doing the above, please consider adding a static constructor,
  829. // and keep the first reference alive explicitly.
  830. // // static
  831. // scoped_refptr<Foo> Foo::Create() {
  832. // auto foo = base::WrapRefCounted(new Foo());
  833. // base::ThreadPool::PostTask(FROM_HERE, base::BindOnce(&Foo::Bar, foo));
  834. // return foo;
  835. // }
  836. //
  837. // Foo::Foo() {}
  838. //
  839. // scoped_refptr<Foo> oo = Foo::Create();
  840. //
  841. DCHECK(receiver->HasAtLeastOneRef());
  842. }
  843. // BindState<>
  844. //
  845. // This stores all the state passed into Bind().
  846. template <typename Functor, typename... BoundArgs>
  847. struct BindState final : BindStateBase {
  848. using IsCancellable = std::bool_constant<
  849. CallbackCancellationTraits<Functor,
  850. std::tuple<BoundArgs...>>::is_cancellable>;
  851. template <typename ForwardFunctor, typename... ForwardBoundArgs>
  852. static BindState* Create(BindStateBase::InvokeFuncStorage invoke_func,
  853. ForwardFunctor&& functor,
  854. ForwardBoundArgs&&... bound_args) {
  855. // Ban ref counted receivers that were not yet fully constructed to avoid
  856. // a common pattern of racy situation.
  857. BanUnconstructedRefCountedReceiver<ForwardFunctor>(bound_args...);
  858. // IsCancellable is std::false_type if
  859. // CallbackCancellationTraits<>::IsCancelled returns always false.
  860. // Otherwise, it's std::true_type.
  861. return new BindState(IsCancellable{}, invoke_func,
  862. std::forward<ForwardFunctor>(functor),
  863. std::forward<ForwardBoundArgs>(bound_args)...);
  864. }
  865. Functor functor_;
  866. std::tuple<BoundArgs...> bound_args_;
  867. private:
  868. static constexpr bool is_nested_callback =
  869. MakeFunctorTraits<Functor>::is_callback;
  870. template <typename ForwardFunctor, typename... ForwardBoundArgs>
  871. explicit BindState(std::true_type,
  872. BindStateBase::InvokeFuncStorage invoke_func,
  873. ForwardFunctor&& functor,
  874. ForwardBoundArgs&&... bound_args)
  875. : BindStateBase(invoke_func,
  876. &Destroy,
  877. &QueryCancellationTraits<BindState>),
  878. functor_(std::forward<ForwardFunctor>(functor)),
  879. bound_args_(std::forward<ForwardBoundArgs>(bound_args)...) {
  880. // We check the validity of nested callbacks (e.g., Bind(callback, ...)) in
  881. // release builds to avoid null pointers from ending up in posted tasks,
  882. // causing hard-to-diagnose crashes. Ideally we'd do this for all functors
  883. // here, but that would have a large binary size impact.
  884. if (is_nested_callback) {
  885. CHECK(!IsNull(functor_));
  886. } else {
  887. DCHECK(!IsNull(functor_));
  888. }
  889. }
  890. template <typename ForwardFunctor, typename... ForwardBoundArgs>
  891. explicit BindState(std::false_type,
  892. BindStateBase::InvokeFuncStorage invoke_func,
  893. ForwardFunctor&& functor,
  894. ForwardBoundArgs&&... bound_args)
  895. : BindStateBase(invoke_func, &Destroy),
  896. functor_(std::forward<ForwardFunctor>(functor)),
  897. bound_args_(std::forward<ForwardBoundArgs>(bound_args)...) {
  898. // See above for CHECK/DCHECK rationale.
  899. if (is_nested_callback) {
  900. CHECK(!IsNull(functor_));
  901. } else {
  902. DCHECK(!IsNull(functor_));
  903. }
  904. }
  905. ~BindState() = default;
  906. static void Destroy(const BindStateBase* self) {
  907. delete static_cast<const BindState*>(self);
  908. }
  909. };
  910. // Used to implement MakeBindStateType.
  911. template <bool is_method, typename Functor, typename... BoundArgs>
  912. struct MakeBindStateTypeImpl;
  913. template <typename Functor, typename... BoundArgs>
  914. struct MakeBindStateTypeImpl<false, Functor, BoundArgs...> {
  915. static_assert(!HasRefCountedTypeAsRawPtr<std::decay_t<BoundArgs>...>::value,
  916. "A parameter is a refcounted type and needs scoped_refptr.");
  917. using Type = BindState<std::decay_t<Functor>, MakeStorageType<BoundArgs>...>;
  918. };
  919. template <typename Functor>
  920. struct MakeBindStateTypeImpl<true, Functor> {
  921. using Type = BindState<std::decay_t<Functor>>;
  922. };
  923. template <typename Functor, typename Receiver, typename... BoundArgs>
  924. struct MakeBindStateTypeImpl<true, Functor, Receiver, BoundArgs...> {
  925. private:
  926. using DecayedReceiver = std::decay_t<Receiver>;
  927. static_assert(!std::is_array_v<std::remove_reference_t<Receiver>>,
  928. "First bound argument to a method cannot be an array.");
  929. static_assert(
  930. !IsRawRefV<DecayedReceiver>,
  931. "Receivers may not be raw_ref<T>. If using a raw_ref<T> here is safe"
  932. " and has no lifetime concerns, use base::Unretained() and document why"
  933. " it's safe.");
  934. static_assert(
  935. !IsPointerV<DecayedReceiver> ||
  936. IsRefCountedType<RemovePointerT<DecayedReceiver>>::value,
  937. "Receivers may not be raw pointers. If using a raw pointer here is safe"
  938. " and has no lifetime concerns, use base::Unretained() and document why"
  939. " it's safe.");
  940. static_assert(!HasRefCountedTypeAsRawPtr<std::decay_t<BoundArgs>...>::value,
  941. "A parameter is a refcounted type and needs scoped_refptr.");
  942. public:
  943. using Type = BindState<
  944. std::decay_t<Functor>,
  945. std::conditional_t<IsPointerV<DecayedReceiver>,
  946. scoped_refptr<RemovePointerT<DecayedReceiver>>,
  947. DecayedReceiver>,
  948. MakeStorageType<BoundArgs>...>;
  949. };
  950. template <typename Functor, typename... BoundArgs>
  951. using MakeBindStateType =
  952. typename MakeBindStateTypeImpl<MakeFunctorTraits<Functor>::is_method,
  953. Functor,
  954. BoundArgs...>::Type;
  955. // Returns a RunType of bound functor.
  956. // E.g. MakeUnboundRunType<R(A, B, C), A, B> is evaluated to R(C).
  957. template <typename Functor, typename... BoundArgs>
  958. using MakeUnboundRunType =
  959. typename BindTypeHelper<Functor, BoundArgs...>::UnboundRunType;
  960. // The implementation of TransformToUnwrappedType below.
  961. template <bool is_once, typename T>
  962. struct TransformToUnwrappedTypeImpl;
  963. template <typename T>
  964. struct TransformToUnwrappedTypeImpl<true, T> {
  965. using StoredType = std::decay_t<T>;
  966. using ForwardType = StoredType&&;
  967. using Unwrapped = decltype(Unwrap(std::declval<ForwardType>()));
  968. };
  969. template <typename T>
  970. struct TransformToUnwrappedTypeImpl<false, T> {
  971. using StoredType = std::decay_t<T>;
  972. using ForwardType = const StoredType&;
  973. using Unwrapped = decltype(Unwrap(std::declval<ForwardType>()));
  974. };
  975. // Transform |T| into `Unwrapped` type, which is passed to the target function.
  976. // Example:
  977. // In is_once == true case,
  978. // `int&&` -> `int&&`,
  979. // `const int&` -> `int&&`,
  980. // `OwnedWrapper<int>&` -> `int*&&`.
  981. // In is_once == false case,
  982. // `int&&` -> `const int&`,
  983. // `const int&` -> `const int&`,
  984. // `OwnedWrapper<int>&` -> `int* const &`.
  985. template <bool is_once, typename T>
  986. using TransformToUnwrappedType =
  987. typename TransformToUnwrappedTypeImpl<is_once, T>::Unwrapped;
  988. // Transforms |Args| into `Unwrapped` types, and packs them into a TypeList.
  989. // If |is_method| is true, tries to dereference the first argument to support
  990. // smart pointers.
  991. template <bool is_once, bool is_method, typename... Args>
  992. struct MakeUnwrappedTypeListImpl {
  993. using Type = TypeList<TransformToUnwrappedType<is_once, Args>...>;
  994. };
  995. // Performs special handling for this pointers.
  996. // Example:
  997. // int* -> int*,
  998. // std::unique_ptr<int> -> int*.
  999. template <bool is_once, typename Receiver, typename... Args>
  1000. struct MakeUnwrappedTypeListImpl<is_once, true, Receiver, Args...> {
  1001. using UnwrappedReceiver = TransformToUnwrappedType<is_once, Receiver>;
  1002. using Type = TypeList<decltype(&*std::declval<UnwrappedReceiver>()),
  1003. TransformToUnwrappedType<is_once, Args>...>;
  1004. };
  1005. template <bool is_once, bool is_method, typename... Args>
  1006. using MakeUnwrappedTypeList =
  1007. typename MakeUnwrappedTypeListImpl<is_once, is_method, Args...>::Type;
  1008. // IsOnceCallback<T> is a std::true_type if |T| is a OnceCallback.
  1009. template <typename T>
  1010. struct IsOnceCallback : std::false_type {};
  1011. template <typename Signature>
  1012. struct IsOnceCallback<OnceCallback<Signature>> : std::true_type {};
  1013. // Helpers to make error messages slightly more readable.
  1014. template <int i>
  1015. struct BindArgument {
  1016. template <typename ForwardingType>
  1017. struct ForwardedAs {
  1018. template <typename FunctorParamType>
  1019. struct ToParamWithType {
  1020. static constexpr bool kCanBeForwardedToBoundFunctor =
  1021. std::is_constructible_v<FunctorParamType, ForwardingType>;
  1022. // If the bound type can't be forwarded then test if `FunctorParamType` is
  1023. // a non-const lvalue reference and a reference to the unwrapped type
  1024. // *could* have been successfully forwarded.
  1025. static constexpr bool kNonConstRefParamMustBeWrapped =
  1026. kCanBeForwardedToBoundFunctor ||
  1027. !(std::is_lvalue_reference_v<FunctorParamType> &&
  1028. !std::is_const_v<std::remove_reference_t<FunctorParamType>> &&
  1029. std::is_convertible_v<std::decay_t<ForwardingType>&,
  1030. FunctorParamType>);
  1031. // Note that this intentionally drops the const qualifier from
  1032. // `ForwardingType`, to test if it *could* have been successfully
  1033. // forwarded if `Passed()` had been used.
  1034. static constexpr bool kMoveOnlyTypeMustUseBasePassed =
  1035. kCanBeForwardedToBoundFunctor ||
  1036. !std::is_constructible_v<FunctorParamType,
  1037. std::decay_t<ForwardingType>&&>;
  1038. };
  1039. };
  1040. template <typename BoundAsType>
  1041. struct BoundAs {
  1042. template <typename StorageType>
  1043. struct StoredAs {
  1044. static constexpr bool kBindArgumentCanBeCaptured =
  1045. std::is_constructible_v<StorageType, BoundAsType>;
  1046. // Note that this intentionally drops the const qualifier from
  1047. // `BoundAsType`, to test if it *could* have been successfully bound if
  1048. // `std::move()` had been used.
  1049. static constexpr bool kMoveOnlyTypeMustUseStdMove =
  1050. kBindArgumentCanBeCaptured ||
  1051. !std::is_constructible_v<StorageType, std::decay_t<BoundAsType>&&>;
  1052. };
  1053. };
  1054. };
  1055. // Helper to assert that parameter |i| of type |Arg| can be bound, which means:
  1056. // - |Arg| can be retained internally as |Storage|.
  1057. // - |Arg| can be forwarded as |Unwrapped| to |Param|.
  1058. template <int i,
  1059. typename Arg,
  1060. typename Storage,
  1061. typename Unwrapped,
  1062. typename Param>
  1063. struct AssertConstructible {
  1064. private:
  1065. // With `BindRepeating`, there are two decision points for how to handle a
  1066. // move-only type:
  1067. //
  1068. // 1. Whether the move-only argument should be moved into the internal
  1069. // `BindState`. Either `std::move()` or `Passed` is sufficient to trigger
  1070. // move-only semantics.
  1071. // 2. Whether or not the bound, move-only argument should be moved to the
  1072. // bound functor when invoked. When the argument is bound with `Passed`,
  1073. // invoking the callback will destructively move the bound, move-only
  1074. // argument to the bound functor. In contrast, if the argument is bound
  1075. // with `std::move()`, `RepeatingCallback` will attempt to call the bound
  1076. // functor with a constant reference to the bound, move-only argument. This
  1077. // will fail if the bound functor accepts that argument by value, since the
  1078. // argument cannot be copied. It is this latter case that this
  1079. // static_assert aims to catch.
  1080. //
  1081. // In contrast, `BindOnce()` only has one decision point. Once a move-only
  1082. // type is captured by value into the internal `BindState`, the bound,
  1083. // move-only argument will always be moved to the functor when invoked.
  1084. // Failure to use std::move will simply fail the `kMoveOnlyTypeMustUseStdMove`
  1085. // assert below instead.
  1086. //
  1087. // Note: `Passed()` is a legacy of supporting move-only types when repeating
  1088. // callbacks were the only callback type. A `RepeatingCallback` with a
  1089. // `Passed()` argument is really a `OnceCallback` and should eventually be
  1090. // migrated.
  1091. static_assert(
  1092. BindArgument<i>::template ForwardedAs<Unwrapped>::
  1093. template ToParamWithType<Param>::kMoveOnlyTypeMustUseBasePassed,
  1094. "base::BindRepeating() argument is a move-only type. Use base::Passed() "
  1095. "instead of std::move() to transfer ownership from the callback to the "
  1096. "bound functor.");
  1097. static_assert(
  1098. BindArgument<i>::template ForwardedAs<Unwrapped>::
  1099. template ToParamWithType<Param>::kNonConstRefParamMustBeWrapped,
  1100. "Bound argument for non-const reference parameter must be wrapped in "
  1101. "std::ref() or base::OwnedRef().");
  1102. static_assert(
  1103. BindArgument<i>::template ForwardedAs<Unwrapped>::
  1104. template ToParamWithType<Param>::kCanBeForwardedToBoundFunctor,
  1105. "Type mismatch between bound argument and bound functor's parameter.");
  1106. static_assert(BindArgument<i>::template BoundAs<Arg>::template StoredAs<
  1107. Storage>::kMoveOnlyTypeMustUseStdMove,
  1108. "Attempting to bind a move-only type. Use std::move() to "
  1109. "transfer ownership to the created callback.");
  1110. // In practice, this static_assert should be quite rare as the storage type
  1111. // is deduced from the arguments passed to `BindOnce()`/`BindRepeating()`.
  1112. static_assert(
  1113. BindArgument<i>::template BoundAs<Arg>::template StoredAs<
  1114. Storage>::kBindArgumentCanBeCaptured,
  1115. "Cannot capture argument: is the argument copyable or movable?");
  1116. };
  1117. // Takes three same-length TypeLists, and applies AssertConstructible for each
  1118. // triples.
  1119. template <typename Index,
  1120. typename Args,
  1121. typename UnwrappedTypeList,
  1122. typename ParamsList>
  1123. struct AssertBindArgsValidity;
  1124. template <size_t... Ns,
  1125. typename... Args,
  1126. typename... Unwrapped,
  1127. typename... Params>
  1128. struct AssertBindArgsValidity<std::index_sequence<Ns...>,
  1129. TypeList<Args...>,
  1130. TypeList<Unwrapped...>,
  1131. TypeList<Params...>>
  1132. : AssertConstructible<Ns, Args, std::decay_t<Args>, Unwrapped, Params>... {
  1133. static constexpr bool ok = true;
  1134. };
  1135. template <typename T>
  1136. struct AssertBindArgIsNotBasePassed : public std::true_type {};
  1137. template <typename T>
  1138. struct AssertBindArgIsNotBasePassed<PassedWrapper<T>> : public std::false_type {
  1139. };
  1140. template <template <typename> class CallbackT,
  1141. typename Functor,
  1142. typename... Args>
  1143. decltype(auto) BindImpl(Functor&& functor, Args&&... args) {
  1144. // This block checks if each |args| matches to the corresponding params of the
  1145. // target function. This check does not affect the behavior of Bind, but its
  1146. // error message should be more readable.
  1147. static constexpr bool kIsOnce = IsOnceCallback<CallbackT<void()>>::value;
  1148. using Helper = BindTypeHelper<Functor, Args...>;
  1149. using FunctorTraits = typename Helper::FunctorTraits;
  1150. using BoundArgsList = typename Helper::BoundArgsList;
  1151. using UnwrappedArgsList =
  1152. MakeUnwrappedTypeList<kIsOnce, FunctorTraits::is_method, Args&&...>;
  1153. using BoundParamsList = typename Helper::BoundParamsList;
  1154. static_assert(
  1155. MakeFunctorTraits<Functor>::is_stateless,
  1156. "Capturing lambdas and stateful lambdas are intentionally not supported. "
  1157. "Please use base::Bind{Once,Repeating} directly to bind arguments.");
  1158. static_assert(
  1159. AssertBindArgsValidity<std::make_index_sequence<Helper::num_bounds>,
  1160. BoundArgsList, UnwrappedArgsList,
  1161. BoundParamsList>::ok,
  1162. "The bound args need to be convertible to the target params.");
  1163. using BindState = MakeBindStateType<Functor, Args...>;
  1164. using UnboundRunType = MakeUnboundRunType<Functor, Args...>;
  1165. using Invoker = Invoker<BindState, UnboundRunType>;
  1166. using CallbackType = CallbackT<UnboundRunType>;
  1167. // Store the invoke func into PolymorphicInvoke before casting it to
  1168. // InvokeFuncStorage, so that we can ensure its type matches to
  1169. // PolymorphicInvoke, to which CallbackType will cast back.
  1170. using PolymorphicInvoke = typename CallbackType::PolymorphicInvoke;
  1171. PolymorphicInvoke invoke_func;
  1172. if constexpr (kIsOnce) {
  1173. invoke_func = Invoker::RunOnce;
  1174. } else {
  1175. invoke_func = Invoker::Run;
  1176. }
  1177. using InvokeFuncStorage = BindStateBase::InvokeFuncStorage;
  1178. return CallbackType(BindState::Create(
  1179. reinterpret_cast<InvokeFuncStorage>(invoke_func),
  1180. std::forward<Functor>(functor), std::forward<Args>(args)...));
  1181. }
  1182. // Special cases for binding to a base::{Once, Repeating}Callback without extra
  1183. // bound arguments. We CHECK() the validity of callback to guard against null
  1184. // pointers accidentally ending up in posted tasks, causing hard-to-debug
  1185. // crashes.
  1186. template <template <typename> class CallbackT,
  1187. typename Signature,
  1188. std::enable_if_t<std::is_same_v<CallbackT<Signature>,
  1189. OnceCallback<Signature>>>* = nullptr>
  1190. OnceCallback<Signature> BindImpl(OnceCallback<Signature> callback) {
  1191. CHECK(callback);
  1192. return callback;
  1193. }
  1194. template <template <typename> class CallbackT,
  1195. typename Signature,
  1196. std::enable_if_t<std::is_same_v<CallbackT<Signature>,
  1197. OnceCallback<Signature>>>* = nullptr>
  1198. OnceCallback<Signature> BindImpl(RepeatingCallback<Signature> callback) {
  1199. CHECK(callback);
  1200. return callback;
  1201. }
  1202. template <template <typename> class CallbackT,
  1203. typename Signature,
  1204. std::enable_if_t<std::is_same_v<CallbackT<Signature>,
  1205. RepeatingCallback<Signature>>>* =
  1206. nullptr>
  1207. RepeatingCallback<Signature> BindImpl(RepeatingCallback<Signature> callback) {
  1208. CHECK(callback);
  1209. return callback;
  1210. }
  1211. template <template <typename> class CallbackT, typename Signature>
  1212. auto BindImpl(absl::FunctionRef<Signature>, ...) {
  1213. static_assert(
  1214. AlwaysFalse<Signature>,
  1215. "base::Bind{Once,Repeating} require strong ownership: non-owning "
  1216. "function references may not bound as the functor due to potential "
  1217. "lifetime issues.");
  1218. return nullptr;
  1219. }
  1220. template <template <typename> class CallbackT, typename Signature>
  1221. auto BindImpl(FunctionRef<Signature>, ...) {
  1222. static_assert(
  1223. AlwaysFalse<Signature>,
  1224. "base::Bind{Once,Repeating} require strong ownership: non-owning "
  1225. "function references may not bound as the functor due to potential "
  1226. "lifetime issues.");
  1227. return nullptr;
  1228. }
  1229. } // namespace internal
  1230. // An injection point to control |this| pointer behavior on a method invocation.
  1231. // If IsWeakReceiver<> is true_type for |T| and |T| is used for a receiver of a
  1232. // method, base::Bind cancels the method invocation if the receiver is tested as
  1233. // false.
  1234. // E.g. Foo::bar() is not called:
  1235. // struct Foo : base::SupportsWeakPtr<Foo> {
  1236. // void bar() {}
  1237. // };
  1238. //
  1239. // WeakPtr<Foo> oo = nullptr;
  1240. // base::BindOnce(&Foo::bar, oo).Run();
  1241. template <typename T>
  1242. struct IsWeakReceiver : std::false_type {};
  1243. template <typename T>
  1244. struct IsWeakReceiver<std::reference_wrapper<T>> : IsWeakReceiver<T> {};
  1245. template <typename T>
  1246. struct IsWeakReceiver<WeakPtr<T>> : std::true_type {};
  1247. // An injection point to control how objects are checked for maybe validity,
  1248. // which is an optimistic thread-safe check for full validity.
  1249. template <typename>
  1250. struct MaybeValidTraits {
  1251. template <typename T>
  1252. static bool MaybeValid(const T& o) {
  1253. return o.MaybeValid();
  1254. }
  1255. };
  1256. // An injection point to control how bound objects passed to the target
  1257. // function. BindUnwrapTraits<>::Unwrap() is called for each bound objects right
  1258. // before the target function is invoked.
  1259. template <typename>
  1260. struct BindUnwrapTraits {
  1261. template <typename T>
  1262. static T&& Unwrap(T&& o) {
  1263. return std::forward<T>(o);
  1264. }
  1265. };
  1266. template <typename T>
  1267. struct BindUnwrapTraits<internal::UnretainedWrapper<T>> {
  1268. static T* Unwrap(const internal::UnretainedWrapper<T>& o) { return o.get(); }
  1269. };
  1270. template <typename T>
  1271. struct BindUnwrapTraits<internal::UnretainedRefWrapper<T>> {
  1272. static T& Unwrap(const internal::UnretainedRefWrapper<T>& o) {
  1273. return o.get();
  1274. }
  1275. };
  1276. template <typename T>
  1277. struct BindUnwrapTraits<internal::RetainedRefWrapper<T>> {
  1278. static T* Unwrap(const internal::RetainedRefWrapper<T>& o) { return o.get(); }
  1279. };
  1280. template <typename T, typename Deleter>
  1281. struct BindUnwrapTraits<internal::OwnedWrapper<T, Deleter>> {
  1282. static T* Unwrap(const internal::OwnedWrapper<T, Deleter>& o) {
  1283. return o.get();
  1284. }
  1285. };
  1286. template <typename T>
  1287. struct BindUnwrapTraits<internal::OwnedRefWrapper<T>> {
  1288. static T& Unwrap(const internal::OwnedRefWrapper<T>& o) { return o.get(); }
  1289. };
  1290. template <typename T>
  1291. struct BindUnwrapTraits<internal::PassedWrapper<T>> {
  1292. static T Unwrap(const internal::PassedWrapper<T>& o) { return o.Take(); }
  1293. };
  1294. #if BUILDFLAG(IS_WIN)
  1295. template <typename T>
  1296. struct BindUnwrapTraits<Microsoft::WRL::ComPtr<T>> {
  1297. static T* Unwrap(const Microsoft::WRL::ComPtr<T>& ptr) { return ptr.Get(); }
  1298. };
  1299. #endif
  1300. // CallbackCancellationTraits allows customization of Callback's cancellation
  1301. // semantics. By default, callbacks are not cancellable. A specialization should
  1302. // set is_cancellable = true and implement an IsCancelled() that returns if the
  1303. // callback should be cancelled.
  1304. template <typename Functor, typename BoundArgsTuple, typename SFINAE>
  1305. struct CallbackCancellationTraits {
  1306. static constexpr bool is_cancellable = false;
  1307. };
  1308. // Specialization for method bound to weak pointer receiver.
  1309. template <typename Functor, typename... BoundArgs>
  1310. struct CallbackCancellationTraits<
  1311. Functor,
  1312. std::tuple<BoundArgs...>,
  1313. std::enable_if_t<
  1314. internal::IsWeakMethod<internal::FunctorTraits<Functor>::is_method,
  1315. BoundArgs...>::value>> {
  1316. static constexpr bool is_cancellable = true;
  1317. template <typename Receiver, typename... Args>
  1318. static bool IsCancelled(const Functor&,
  1319. const Receiver& receiver,
  1320. const Args&...) {
  1321. return !receiver;
  1322. }
  1323. template <typename Receiver, typename... Args>
  1324. static bool MaybeValid(const Functor&,
  1325. const Receiver& receiver,
  1326. const Args&...) {
  1327. return MaybeValidTraits<Receiver>::MaybeValid(receiver);
  1328. }
  1329. };
  1330. // Specialization for a nested bind.
  1331. template <typename Signature, typename... BoundArgs>
  1332. struct CallbackCancellationTraits<OnceCallback<Signature>,
  1333. std::tuple<BoundArgs...>> {
  1334. static constexpr bool is_cancellable = true;
  1335. template <typename Functor>
  1336. static bool IsCancelled(const Functor& functor, const BoundArgs&...) {
  1337. return functor.IsCancelled();
  1338. }
  1339. template <typename Functor>
  1340. static bool MaybeValid(const Functor& functor, const BoundArgs&...) {
  1341. return MaybeValidTraits<Functor>::MaybeValid(functor);
  1342. }
  1343. };
  1344. template <typename Signature, typename... BoundArgs>
  1345. struct CallbackCancellationTraits<RepeatingCallback<Signature>,
  1346. std::tuple<BoundArgs...>> {
  1347. static constexpr bool is_cancellable = true;
  1348. template <typename Functor>
  1349. static bool IsCancelled(const Functor& functor, const BoundArgs&...) {
  1350. return functor.IsCancelled();
  1351. }
  1352. template <typename Functor>
  1353. static bool MaybeValid(const Functor& functor, const BoundArgs&...) {
  1354. return MaybeValidTraits<Functor>::MaybeValid(functor);
  1355. }
  1356. };
  1357. } // namespace base
  1358. #endif // BASE_BIND_INTERNAL_H_