// Copyright (c) 2025 Marshall A. Greenblatt. Portions copyright (c) 2011 // Google Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the name Chromium Embedded // Framework nor the names of its contributors may be used to endorse // or promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Do not include this header file directly. Use base/cef_bind.h instead. #ifndef CEF_INCLUDE_BASE_INTERNAL_CEF_BIND_INTERNAL_H_ #define CEF_INCLUDE_BASE_INTERNAL_CEF_BIND_INTERNAL_H_ #pragma once #if defined(USING_CHROMIUM_INCLUDES) // When building CEF include the Chromium header directly. #include "base/functional/bind_internal.h" #else // !USING_CHROMIUM_INCLUDES // The following is substantially similar to the Chromium implementation. // If the Chromium implementation diverges the below implementation should be // updated to match. #include #include #include #include #include #include #include #include "include/base/cef_build.h" #include "include/base/cef_is_complete.h" #include "include/base/cef_is_instantiation.h" #include "include/base/cef_logging.h" #include "include/base/cef_to_address.h" #include "include/base/cef_weak_ptr.h" #include "include/base/internal/cef_always_false.h" #include "include/base/internal/cef_callback_internal.h" // CEF does not use these Chromium features: // - base/functional/unretained_traits.h (SupportsUnretained) // - base/memory/raw_ptr.h, base/memory/raw_ref.h (MiraclePtr) // - third_party/abseil-cpp/absl/functional/function_ref.h // - PA_BUILDFLAG(USE_ASAN_BACKUP_REF_PTR) // See docs/callback.md for user documentation. // // Concepts: // Functor -- A movable type representing something that should be called. // All function pointers and `Callback<>` are functors even if the // invocation syntax differs. // RunType -- A function type (as opposed to function _pointer_ type) for // a `Callback<>::Run()`. Usually just a convenience typedef. // (Bound)Args -- A set of types that stores the arguments. // // Types: // `ForceVoidReturn<>` -- Helper class for translating function signatures to // equivalent forms with a `void` return type. // `FunctorTraits<>` -- Type traits used to determine the correct RunType and // invocation manner for a Functor. This is where // function signature adapters are applied. // `StorageTraits<>` -- Type traits that determine how a bound argument is // stored in `BindState<>`. // `InvokeHelper<>` -- Takes a Functor + arguments and actually invokes it. // Handles the differing syntaxes needed for `WeakPtr<>` // support. This is separate from `Invoker<>` to avoid // creating multiple versions of `Invoker<>`. // `Invoker<>` -- Unwraps the curried parameters and executes the Functor. // `BindState<>` -- Stores the curried parameters, and is the main entry point // into the `Bind()` system. #if defined(OS_WIN) namespace Microsoft { namespace WRL { template class ComPtr; } // namespace WRL } // namespace Microsoft #endif namespace base { template struct IsWeakReceiver; template struct BindUnwrapTraits; template struct CallbackCancellationTraits; // A tag type to return when `Bind()` calls fail. In this case we intentionally // don't return `void`, since that would produce spurious errors like "variable // has incomplete type 'void'" when assigning the result of // `Bind{Once,Repeating}()` to an `auto`. struct BindFailedCheckPreviousErrors {}; namespace cef_internal { // CEF simplified version: UnretainedWrapper just stores a raw pointer. // CEF does not use raw_ptr/MiraclePtr dangling pointer detection. template class UnretainedWrapper { public: explicit UnretainedWrapper(T* o) : ptr_(o) {} T* get() const { return ptr_; } // Always valid in CEF (no SupportsUnretained check). static constexpr bool value = true; private: T* ptr_; }; // UnretainedRefWrapper wraps a reference (via std::reference_wrapper). // Unlike UnretainedWrapper which returns a pointer, this returns a reference. template class UnretainedRefWrapper { public: explicit UnretainedRefWrapper(std::reference_wrapper ref) : ptr_(std::addressof(ref.get())) {} T& get() const { return *ptr_; } // Always valid in CEF (no SupportsUnretained check). static constexpr bool value = true; private: T* ptr_; }; // `MethodReceiverStorage` converts the current receiver type to its stored // type. For instance, it converts pointers to `scoped_refptr`. // CEF simplified version: no raw_ptr/raw_ref support. template struct MethodReceiverStorage { using Type = std::conditional_t, scoped_refptr>, T>; }; template class RetainedRefWrapper { public: explicit RetainedRefWrapper(T* o) : ptr_(o) {} explicit RetainedRefWrapper(scoped_refptr o) : ptr_(std::move(o)) {} T* get() const { return ptr_.get(); } private: scoped_refptr ptr_; }; template struct IgnoreResultHelper { explicit IgnoreResultHelper(T functor) : functor_(std::move(functor)) {} explicit operator bool() const { return !!functor_; } T functor_; }; template > class OwnedWrapper { public: explicit OwnedWrapper(T* o) : ptr_(o) {} explicit OwnedWrapper(std::unique_ptr&& ptr) : ptr_(std::move(ptr)) {} T* get() const { return ptr_.get(); } private: std::unique_ptr ptr_; }; template class OwnedRefWrapper { public: explicit OwnedRefWrapper(const T& t) : t_(t) {} explicit OwnedRefWrapper(T&& t) : t_(std::move(t)) {} T& get() const { return t_; } private: mutable T t_; }; // `PassedWrapper` is a copyable adapter for a scoper that ignores `const`. // // It is needed to get around the fact that `Bind()` takes a const reference to // all its arguments. Because `Bind()` takes a const reference to avoid // unnecessary copies, it is incompatible with movable-but-not-copyable // types; doing a destructive "move" of the type into `Bind()` would violate // the const correctness. // // This conundrum cannot be solved without either rvalue references or an O(2^n) // blowup of `Bind()` templates to handle each combination of regular types and // movable-but-not-copyable types. Thus we introduce a wrapper type that is // copyable to transmit the correct type information down into `BindState<>`. // Ignoring `const` in this type makes sense because it is only created when we // are explicitly trying to do a destructive move. // // Two notes: // 1) `PassedWrapper` supports any type that has a move constructor, however // the type will need to be specifically allowed in order for it to be // bound to a `Callback`. We guard this explicitly at the call of `Passed()` // to make for clear errors. Things not given to `Passed()` will be // forwarded and stored by value which will not work for general move-only // types. // 2) `is_valid_` is distinct from `nullptr` because it is valid to bind a null // scoper to a `Callback` and allow the `Callback` to execute once. // // TODO(crbug.com/40840557): We have rvalue references and such now. Remove. template class PassedWrapper { public: explicit PassedWrapper(T&& scoper) : scoper_(std::move(scoper)) {} PassedWrapper(PassedWrapper&& other) : is_valid_(other.is_valid_), scoper_(std::move(other.scoper_)) {} T Take() const { CHECK(is_valid_); is_valid_ = false; return std::move(scoper_); } private: mutable bool is_valid_ = true; mutable T scoper_; }; template using Unwrapper = BindUnwrapTraits>; template decltype(auto) Unwrap(T&& o) { return Unwrapper::Unwrap(std::forward(o)); } // `kIsWeakMethod` is a helper that determines if we are binding a `WeakPtr<>` // to a method. It is used internally by `Bind()` to select the correct // `InvokeHelper` that will no-op itself in the event the `WeakPtr<>` for the // target object is invalidated. // // The first argument should be the type of the object that will be received by // the method. template inline constexpr bool kIsWeakMethod = false; template inline constexpr bool kIsWeakMethod = IsWeakReceiver::value; // Packs a list of types to hold them in a single type. template struct TypeList {}; // Implements `DropTypeListItem`. template requires is_instantiation struct DropTypeListItemImpl { using Type = List; }; template requires(n > 0) struct DropTypeListItemImpl> : DropTypeListItemImpl> {}; // A type-level function that drops `n` list items from a given `TypeList`. template using DropTypeListItem = typename DropTypeListItemImpl::Type; // Implements `TakeTypeListItem`. template requires is_instantiation struct TakeTypeListItemImpl { using Type = TypeList; }; template requires(n > 0) struct TakeTypeListItemImpl, Accum...> : TakeTypeListItemImpl, Accum..., T> {}; // A type-level function that takes the first `n` items from a given `TypeList`; // e.g. `TakeTypeListItem<3, TypeList>` -> `TypeList`. template using TakeTypeListItem = typename TakeTypeListItemImpl::Type; // Implements `MakeFunctionType`. template struct MakeFunctionTypeImpl; template struct MakeFunctionTypeImpl> { using Type = R(Args...); }; // A type-level function that constructs a function type that has `R` as its // return type and has a `TypeList`'s items as its arguments. template using MakeFunctionType = typename MakeFunctionTypeImpl::Type; // Implements `ExtractArgs` and `ExtractReturnType`. template struct ExtractArgsImpl; template struct ExtractArgsImpl { using ReturnType = R; using ArgsList = TypeList; }; // A type-level function that extracts function arguments into a `TypeList`; // e.g. `ExtractArgs` -> `TypeList`. template using ExtractArgs = typename ExtractArgsImpl::ArgsList; // A type-level function that extracts the return type of a function. // e.g. `ExtractReturnType` -> `R`. template using ExtractReturnType = typename ExtractArgsImpl::ReturnType; template struct ExtractCallableRunTypeImpl; #define BIND_INTERNAL_EXTRACT_CALLABLE_RUN_TYPE_WITH_QUALS(quals) \ template \ struct ExtractCallableRunTypeImpl { \ using Type = R(Args...); \ } // MSVC warns about calling a macro with empty arguments (C4003). This is valid // C++11 and later, but we suppress the warning to avoid treating it as an // error. #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable : 4003) #endif BIND_INTERNAL_EXTRACT_CALLABLE_RUN_TYPE_WITH_QUALS(); BIND_INTERNAL_EXTRACT_CALLABLE_RUN_TYPE_WITH_QUALS(const); BIND_INTERNAL_EXTRACT_CALLABLE_RUN_TYPE_WITH_QUALS(noexcept); BIND_INTERNAL_EXTRACT_CALLABLE_RUN_TYPE_WITH_QUALS(const noexcept); #if defined(_MSC_VER) #pragma warning(pop) #endif #undef BIND_INTERNAL_EXTRACT_CALLABLE_RUN_TYPE_WITH_QUALS // Evaluated to the RunType of the given callable type; e.g. // `ExtractCallableRunType` -> // `double(int, char*)`. template using ExtractCallableRunType = typename ExtractCallableRunTypeImpl::Type; // True when `Functor` has a non-overloaded `operator()()`, e.g.: // struct S1 { // int operator()(int); // }; // static_assert(HasNonOverloadedCallOp); // // int i = 0; // auto f = [i] {}; // static_assert(HasNonOverloadedCallOp); // // struct S2 { // int operator()(int); // std::string operator()(std::string); // }; // static_assert(!HasNonOverloadedCallOp); // // static_assert(!HasNonOverloadedCallOp); // // struct S3 {}; // static_assert(!HasNonOverloadedCallOp); // ``` template concept HasNonOverloadedCallOp = requires { &Functor::operator(); }; template inline constexpr bool IsObjCArcBlockPointer = false; #if __OBJC__ && HAS_FEATURE(objc_arc) template inline constexpr bool IsObjCArcBlockPointer = true; #endif // Helper concept to check if Functor is invocable with BoundArgs. // Extracted from HasOverloadedCallOp to avoid nested `requires requires` // which triggers an internal compiler error in GCC 10. template concept IsInvocableWithBoundArgs = requires(Functor&& f, BoundArgs&&... args) { std::forward(f)(std::forward(args)...); }; // True when `Functor` has an overloaded `operator()()` that can be invoked with // the provided `BoundArgs`. // // Do not decay `Functor` before testing this, lest it give an incorrect result // for overloads with different ref-qualifiers. template concept HasOverloadedCallOp = requires { // The functor must be invocable with the bound args. requires IsInvocableWithBoundArgs; // Now exclude invocables that are not cases of overloaded `operator()()`s: // * `operator()()` exists, but isn't overloaded requires !HasNonOverloadedCallOp>; // * Function pointer (doesn't have `operator()()`) requires !std::is_pointer_v>; // * Block pointer (doesn't have `operator()()`) requires !IsObjCArcBlockPointer>; }; // `ForceVoidReturn<>` converts a signature to have a `void` return type. template struct ForceVoidReturn; template struct ForceVoidReturn { using RunType = void(Args...); }; // `FunctorTraits<>` // // See description at top of file. This must be declared here so it can be // referenced in `DecayedFunctorTraits`. template struct FunctorTraits; // Provides functor traits for pre-decayed functor types. template struct DecayedFunctorTraits; // Callable types. // This specialization handles lambdas (captureless and capturing) and functors // with a call operator. Capturing lambdas and stateful functors are explicitly // disallowed by `BindHelper<>::Bind()`; e.g.: // ``` // // Captureless lambda: Allowed // [] { return 42; }; // // // Capturing lambda: Disallowed // int x; // [x] { return x; }; // // // Empty class with `operator()()`: Allowed // struct Foo { // void operator()() const {} // // No non-`static` member variables and no virtual functions. // }; // ``` template requires HasNonOverloadedCallOp struct DecayedFunctorTraits { using RunType = ExtractCallableRunType; static constexpr bool is_method = false; static constexpr bool is_nullable = false; static constexpr bool is_callback = false; static constexpr bool is_stateless = std::is_empty_v; template static ExtractReturnType Invoke(RunFunctor&& functor, RunArgs&&... args) { return std::forward(functor)(std::forward(args)...); } }; // Functions. template struct DecayedFunctorTraits { using RunType = R(Args...); static constexpr bool is_method = false; static constexpr bool is_nullable = true; static constexpr bool is_callback = false; static constexpr bool is_stateless = true; template static R Invoke(Function&& function, RunArgs&&... args) { return std::forward(function)(std::forward(args)...); } }; template struct DecayedFunctorTraits : DecayedFunctorTraits {}; #if defined(OS_WIN) && !defined(ARCH_CPU_64_BITS) // `__stdcall` and `__fastcall` functions. #define BIND_INTERNAL_DECAYED_FUNCTOR_TRAITS_WITH_CONV_AND_QUALS(conv, quals) \ template \ struct DecayedFunctorTraits \ : DecayedFunctorTraits {} BIND_INTERNAL_DECAYED_FUNCTOR_TRAITS_WITH_CONV_AND_QUALS(__stdcall, ); BIND_INTERNAL_DECAYED_FUNCTOR_TRAITS_WITH_CONV_AND_QUALS(__stdcall, noexcept); BIND_INTERNAL_DECAYED_FUNCTOR_TRAITS_WITH_CONV_AND_QUALS(__fastcall, ); BIND_INTERNAL_DECAYED_FUNCTOR_TRAITS_WITH_CONV_AND_QUALS(__fastcall, noexcept); #undef BIND_INTERNAL_DECAYED_FUNCTOR_TRAITS_WITH_CONV_AND_QUALS #endif // defined(OS_WIN) && !defined(ARCH_CPU_64_BITS) #if __OBJC__ && HAS_FEATURE(objc_arc) // Objective-C blocks. Blocks can be bound as the compiler will ensure their // lifetimes will be correctly managed. template struct DecayedFunctorTraits { using RunType = R(Args...); static constexpr bool is_method = false; static constexpr bool is_nullable = true; static constexpr bool is_callback = false; static constexpr bool is_stateless = true; template static R Invoke(BlockType&& block, RunArgs&&... args) { // According to LLVM documentation (ยง 6.3), "local variables of automatic // storage duration do not have precise lifetime." Use // `objc_precise_lifetime` to ensure that the Objective-C block is not // deallocated until it has finished executing even if the `Callback<>` is // destroyed during the block execution. // https://clang.llvm.org/docs/AutomaticReferenceCounting.html#precise-lifetime-semantics __attribute__((objc_precise_lifetime)) R (^scoped_block)(Args...) = block; return scoped_block(std::forward(args)...); } }; #endif // __OBJC__ && HAS_FEATURE(objc_arc) // Methods. template struct DecayedFunctorTraits { using RunType = R(Receiver*, Args...); static constexpr bool is_method = true; static constexpr bool is_nullable = true; static constexpr bool is_callback = false; static constexpr bool is_stateless = true; template static R Invoke(Method method, ReceiverPtr&& receiver_ptr, RunArgs&&... args) { return ((*receiver_ptr).*method)(std::forward(args)...); } }; template struct DecayedFunctorTraits : DecayedFunctorTraits { using RunType = R(const Receiver*, Args...); }; #define BIND_INTERNAL_DECAYED_FUNCTOR_TRAITS_WITH_CONST_AND_QUALS(constqual, \ quals) \ template \ struct DecayedFunctorTraits \ : DecayedFunctorTraits {} BIND_INTERNAL_DECAYED_FUNCTOR_TRAITS_WITH_CONST_AND_QUALS(, noexcept); BIND_INTERNAL_DECAYED_FUNCTOR_TRAITS_WITH_CONST_AND_QUALS(const, noexcept); #undef BIND_INTERNAL_DECAYED_FUNCTOR_TRAITS_WITH_CONST_AND_QUALS #if defined(OS_WIN) && !defined(ARCH_CPU_64_BITS) // `__stdcall` methods. #define BIND_INTERNAL_DECAYED_FUNCTOR_TRAITS_STDCALL_WITH_QUALS(quals) \ template \ struct DecayedFunctorTraits \ : public DecayedFunctorTraits {} // MSVC warns about calling a macro with empty arguments (C4003). This is valid // C++11 and later, but we suppress the warning to avoid treating it as an // error. #pragma warning(push) #pragma warning(disable : 4003) BIND_INTERNAL_DECAYED_FUNCTOR_TRAITS_STDCALL_WITH_QUALS(); BIND_INTERNAL_DECAYED_FUNCTOR_TRAITS_STDCALL_WITH_QUALS(const); BIND_INTERNAL_DECAYED_FUNCTOR_TRAITS_STDCALL_WITH_QUALS(noexcept); BIND_INTERNAL_DECAYED_FUNCTOR_TRAITS_STDCALL_WITH_QUALS(const noexcept); #pragma warning(pop) #undef BIND_INTERNAL_DECAYED_FUNCTOR_TRAITS_STDCALL_WITH_QUALS #endif // defined(OS_WIN) && !defined(ARCH_CPU_64_BITS) // `IgnoreResult`s. template struct DecayedFunctorTraits, BoundArgs...> : FunctorTraits { using RunType = typename ForceVoidReturn< typename FunctorTraits::RunType>::RunType; template static void Invoke(IgnoreResultType&& ignore_result_helper, RunArgs&&... args) { FunctorTraits::Invoke( std::forward(ignore_result_helper).functor_, std::forward(args)...); } }; // `OnceCallback`s. template struct DecayedFunctorTraits, BoundArgs...> { using RunType = R(Args...); static constexpr bool is_method = false; static constexpr bool is_nullable = true; static constexpr bool is_callback = true; static constexpr bool is_stateless = true; template static R Invoke(CallbackType&& callback, RunArgs&&... args) { DCHECK(!callback.is_null()); return std::forward(callback).Run( std::forward(args)...); } }; // `RepeatingCallback`s. template struct DecayedFunctorTraits, BoundArgs...> { using RunType = R(Args...); static constexpr bool is_method = false; static constexpr bool is_nullable = true; static constexpr bool is_callback = true; static constexpr bool is_stateless = true; template static R Invoke(CallbackType&& callback, RunArgs&&... args) { DCHECK(!callback.is_null()); return std::forward(callback).Run( std::forward(args)...); } }; // For most functors, the traits should not depend on how the functor is passed, // so decay the functor. template // This requirement avoids "implicit instantiation of undefined template" errors // when the underlying `DecayedFunctorTraits<>` cannot be instantiated. Instead, // this template will also not be instantiated, and the caller can detect and // handle that. requires IsComplete, BoundArgs...>> struct FunctorTraits : DecayedFunctorTraits, BoundArgs...> {}; // For `overloaded operator()()`s, it's possible the ref qualifiers of the // functor matter, so be careful to use the undecayed type. template requires HasOverloadedCallOp struct FunctorTraits { // For an overloaded operator()(), it is not possible to resolve the // actual declared type. Since it is invocable with the bound args, make up a // signature based on their types. using RunType = decltype(std::declval()( std::declval()...))(std::decay_t...); static constexpr bool is_method = false; static constexpr bool is_nullable = false; static constexpr bool is_callback = false; static constexpr bool is_stateless = std::is_empty_v>; template static ExtractReturnType Invoke(RunFunctor&& functor, RunArgs&&... args) { return std::forward(functor)(std::forward(args)...); } }; // `StorageTraits<>` // // See description at top of file. // CEF simplified version: no raw_ptr/raw_ref support. template struct StorageTraits { // The type to use for storing the bound arg inside `BindState`. using Type = T; // True iff all compile-time preconditions for using this specialization are // satisfied. Specializations that set this to `false` should ensure a // `static_assert()` explains why. static constexpr bool value = true; }; // For `T*`, store as `UnretainedWrapper`. template struct StorageTraits { using Type = UnretainedWrapper; static constexpr bool value = Type::value; }; // Unwrap `std::reference_wrapper` and store as `UnretainedRefWrapper`. template struct StorageTraits> { using Type = UnretainedRefWrapper; static constexpr bool value = Type::value; }; template using ValidateStorageTraits = StorageTraits>; // `InvokeHelper<>` // // There are 2 logical `InvokeHelper<>` specializations: normal, weak. // // The normal type just calls the underlying runnable. // // Weak calls need special syntax that is applied to the first argument to check // if they should no-op themselves. template struct InvokeHelper; template struct InvokeHelper { template static inline ReturnType MakeItSo(Functor&& functor, BoundArgsTuple&& bound, RunArgs&&... args) { return Traits::Invoke( Unwrap(std::forward(functor)), Unwrap(std::get(std::forward(bound)))..., std::forward(args)...); } }; template struct InvokeHelper { template static inline void MakeItSo(Functor&& functor, BoundArgsTuple&& bound, RunArgs&&... args) { static_assert(index_target == 0); // Note the validity of the weak pointer should be tested _after_ it is // unwrapped, otherwise it creates a race for weak pointer implementations // that allow cross-thread usage and perform `Lock()` in `Unwrap()` traits. const auto& target = Unwrap(std::get<0>(bound)); if (!target) { return; } Traits::Invoke( Unwrap(std::forward(functor)), target, Unwrap(std::get(std::forward(bound)))..., std::forward(args)...); } }; // `Invoker<>` // // See description at the top of the file. template struct Invoker; template struct Invoker { private: using Indices = std::make_index_sequence< std::tuple_size_v>; public: static R RunOnce(BindStateBase* base, PassingType... unbound_args) { auto* const storage = static_cast(base); return RunImpl(std::move(storage->functor_), std::move(storage->bound_args_), Indices(), std::forward(unbound_args)...); } static R Run(BindStateBase* base, PassingType... unbound_args) { auto* const storage = static_cast(base); return RunImpl(storage->functor_, storage->bound_args_, Indices(), std::forward(unbound_args)...); } private: // The "templated struct with a lambda that asserts" pattern below is used // repeatedly in Bind/Callback code to verify compile-time preconditions. The // goal is to print only the root cause failure when users violate a // precondition, and not also a host of resulting compile errors. // // There are three key aspects: // 1. By placing the assertion inside a lambda that initializes a variable, // the assertion will not be verified until the compiler tries to read // the value of that variable. This allows the containing types to be // complete. As a result, code that needs to know if the assertion failed // can read the variable's value and get the right answer. (If we instead // placed the assertion at struct scope, the resulting type would be // incomplete when the assertion failed; in practice, reading a // `constexpr` member of an incomplete type seems to return the default // value regardless of what the code tried to set the value to, which // makes it impossible for other code to check whether the assertion // failed.) // 2. Code that will not successfully compile unless the assertion holds is // guarded by a constexpr if that checks the variable. // 3. By placing the variable inside an independent, templated struct and // naming it `value`, we allow checking multiple conditions via // `std::conjunction_v<>`. This short-circuits type instantiation, so // that when one condition fails, the others are never examined and thus // never assert. As a result, we can verify dependent conditions without // worrying that "if one fails, we'll get errors from several others". // (This would not be true if we simply checked all the values with `&&`, // which would instantiate all the types before evaluating the // expression.) // // For caller convenience and to avoid potential repetition, the actual // condition to be checked is always used as the default value of a template // argument, so callers can simply instantiate the struct with no template // params to verify the condition. // Weak calls are only supported for functions with a `void` return type. // Otherwise, the desired function result would be unclear if the `WeakPtr<>` // is invalidated. In theory, we could support default-constructible return // types (and return the default value) or allow callers to specify a default // return value via a template arg. It's not clear these are necessary. template > struct WeakCallReturnsVoid { static constexpr bool value = [] { static_assert(v, "WeakPtrs can only bind to methods without return values."); return v; }(); }; template static inline R RunImpl(Functor&& functor, BoundArgsTuple&& bound, std::index_sequence, UnboundArgs&&... unbound_args) { using DecayedArgsTuple = std::decay_t; static constexpr bool kIsWeakCall = kIsWeakMethod...>; if constexpr (WeakCallReturnsVoid::value) { // Do not `Unwrap()` here, as that immediately triggers dangling pointer // detection. Dangling pointer detection should only be triggered if the // callback is not cancelled, but cancellation status is not determined // until later inside the `InvokeHelper::MakeItSo()` specialization for // weak calls. // // Dangling pointers when invoking a cancelled callback are not considered // a memory safety error because protecting raw pointers usage with weak // receivers (where the weak receiver usually own the pointed objects) is // a common and broadly used pattern in the codebase. return InvokeHelper::MakeItSo( std::forward(functor), std::forward(bound), std::forward(unbound_args)...); } } }; // Allow binding a method call with no receiver. // TODO(crbug.com/41484339): Remove or make safe. template void VerifyMethodReceiver(Unused&&...) {} template void VerifyMethodReceiver(Receiver&& receiver, Unused&&...) { // Asserts that a callback is not the first owner of a ref-counted receiver. // CEF simplified: no raw_ptr, just check std::is_pointer_v. if constexpr (std::is_pointer_v> && IsRefCountedType< std::remove_pointer_t>>) { DCHECK(receiver); // It's error prone to make the implicit first reference to ref-counted // types. In the example below, `BindOnce()` would make the implicit first // reference to the ref-counted `Foo`. If `PostTask()` failed or the posted // task ran fast enough, the newly created instance could be destroyed // before `oo` makes another reference. // ``` // Foo::Foo() { // ThreadPool::PostTask(FROM_HERE, BindOnce(&Foo::Bar, this)); // } // // scoped_refptr oo = new Foo(); // ``` // // Hence, `Bind()` refuses to create the first reference to ref-counted // objects, and `DCHECK()`s otherwise. As above, that typically happens // around `PostTask()` in their constructors, and such objects can be // destroyed before `new` returns if the tasks resolve fast enough. // // Instead, consider adding a static factory, and keeping the first // reference alive explicitly. // ``` // // static // scoped_refptr Foo::Create() { // auto foo = base::WrapRefCounted(new Foo()); // ThreadPool::PostTask(FROM_HERE, BindOnce(&Foo::Bar, foo)); // return foo; // } // // scoped_refptr oo = Foo::Create(); // ``` DCHECK(receiver->HasAtLeastOneRef()); } } // `BindState<>` // // This stores all the state passed into `Bind()`. template struct BindState final : BindStateBase { private: using BoundArgsTuple = std::tuple; public: template static BindState* Create(BindStateBase::InvokeFuncStorage invoke_func, ForwardFunctor&& functor, ForwardBoundArgs&&... bound_args) { if constexpr (is_method) { VerifyMethodReceiver(bound_args...); } return new BindState(invoke_func, std::forward(functor), std::forward(bound_args)...); } Functor functor_; BoundArgsTuple bound_args_; private: using CancellationTraits = CallbackCancellationTraits; template requires CancellationTraits::is_cancellable BindState(BindStateBase::InvokeFuncStorage invoke_func, ForwardFunctor&& functor, ForwardBoundArgs&&... bound_args) : BindStateBase(invoke_func, &Destroy, &QueryCancellationTraits), functor_(std::forward(functor)), bound_args_(std::forward(bound_args)...) { CheckFunctorIsNonNull(); } template requires(!CancellationTraits::is_cancellable) BindState(BindStateBase::InvokeFuncStorage invoke_func, ForwardFunctor&& functor, ForwardBoundArgs&&... bound_args) : BindStateBase(invoke_func, &Destroy), functor_(std::forward(functor)), bound_args_(std::forward(bound_args)...) { CheckFunctorIsNonNull(); } ~BindState() = default; static bool QueryCancellationTraits( const BindStateBase* base, BindStateBase::CancellationQueryMode mode) { auto* const storage = static_cast(base); static constexpr std::make_index_sequence kIndices; return (mode == BindStateBase::CancellationQueryMode::kIsCancelled) ? storage->IsCancelled(kIndices) : storage->MaybeValid(kIndices); } static void Destroy(const BindStateBase* self) { delete static_cast(self); } // Helpers to do arg tuple expansion. template bool IsCancelled(std::index_sequence) const { return CancellationTraits::IsCancelled(functor_, std::get(bound_args_)...); } template bool MaybeValid(std::index_sequence) const { return CancellationTraits::MaybeValid(functor_, std::get(bound_args_)...); } void CheckFunctorIsNonNull() const { if constexpr (is_nullable) { // Check the validity of `functor_` to avoid hard-to-diagnose crashes. // Ideally we'd do this unconditionally, but release builds limit this to // the case of nested callbacks (e.g. `Bind(callback, ...)`) to limit // binary size impact. if constexpr (is_callback) { CHECK(!!functor_); } else { DCHECK(!!functor_); } } } }; template struct ValidateBindStateTypeCommonChecks { private: // Refcounted parameters must be passed as `scoped_refptr` instead of raw // pointers, to ensure they are not deleted before use. // CEF simplified: no raw_ptr/raw_ref. template && IsRefCountedType>> struct RefCountedTypeNotPassedByRawPointer { static constexpr bool value = [] { static_assert( !v, "A parameter is a refcounted type and needs scoped_refptr."); return !v; }(); }; public: using CommonCheckResult = std::conjunction< RefCountedTypeNotPassedByRawPointer>..., ValidateStorageTraits...>; }; // Used to determine and validate the appropriate `BindState`. The // specializations below cover all cases. The members are similar in intent to // those in `StorageTraits`; see comments there. template struct ValidateBindStateType; template struct ValidateBindStateType { using Type = BindState, typename ValidateStorageTraits::Type...>; static constexpr bool value = ValidateBindStateTypeCommonChecks::CommonCheckResult::value; }; template struct ValidateBindStateType { using Type = BindState>; static constexpr bool value = true; }; template struct ValidateBindStateType { private: using DecayedReceiver = std::decay_t; using ReceiverStorageType = typename MethodReceiverStorage::Type; template >> struct FirstBoundArgIsNotArray { static constexpr bool value = [] { static_assert(v, "First bound argument to a method cannot be an array."); return v; }(); }; // CEF simplified: no raw_ref check, simplified raw pointer check. template || IsRefCountedType>> struct ReceiverIsNotRawPtr { static constexpr bool value = [] { static_assert(v, "Receivers may not be raw pointers. If using a raw pointer " "here is safe and has no lifetime concerns, use " "base::Unretained() and document why it's safe."); return v; }(); }; public: using Type = BindState, ReceiverStorageType, typename ValidateStorageTraits::Type...>; static constexpr bool value = std::conjunction_v, ReceiverIsNotRawPtr<>, typename ValidateBindStateTypeCommonChecks< BoundArgs...>::CommonCheckResult>; }; // Transforms `T` into an unwrapped type, which is passed to the target // function; e.g.: // * `is_once` cases: // ** `TransformToUnwrappedType` -> `int&&` // ** `TransformToUnwrappedType` -> `int&&` // ** `TransformToUnwrappedType&>` -> `int*&&` // * `!is_once` cases: // ** `TransformToUnwrappedType` -> `const int&` // ** `TransformToUnwrappedType` -> `const int&` // ** `TransformToUnwrappedType&>` -> `int* const &` template , typename ForwardedType = std::conditional_t> using TransformToUnwrappedType = decltype(Unwrap(std::declval())); // Used to convert `this` arguments to underlying pointer types; e.g.: // `int*` -> `int*` // `std::unique_ptr` -> `int*` // `int` -> (assertion failure; `this` must be a pointer-like object) template struct ValidateReceiverType { private: // Pointer-like receivers use a different specialization, so this never // succeeds. template > struct ReceiverMustBePointerLike { static constexpr bool value = [] { static_assert(v, "Cannot convert `this` argument to address. Method calls " "must be bound using a pointer-like `this` argument."); return v; }(); }; public: // These members are similar in intent to those in `StorageTraits`; see // comments there. using Type = T; static constexpr bool value = ReceiverMustBePointerLike<>::value; }; template requires requires(T&& t) { base::to_address(t); } struct ValidateReceiverType { using Type = decltype(base::to_address(std::declval())); static constexpr bool value = true; }; // Transforms `Args` into unwrapped types, and packs them into a `TypeList`. If // `is_method` is true, tries to dereference the first argument to support smart // pointers. template struct ValidateUnwrappedTypeList { // These members are similar in intent to those in `StorageTraits`; see // comments there. using Type = TypeList...>; static constexpr bool value = true; }; template struct ValidateUnwrappedTypeList { private: using ReceiverStorageType = typename MethodReceiverStorage>::Type; using UnwrappedReceiver = TransformToUnwrappedType; using ValidatedReceiver = ValidateReceiverType; public: using Type = TypeList...>; static constexpr bool value = ValidatedReceiver::value; }; // CEF simplified: no raw_ptr/MayDangle support. // Helpers to make error messages slightly more readable. template struct BindArgument { template struct ForwardedAs { template struct ToParamWithType { static constexpr bool kCanBeForwardedToBoundFunctor = std::is_convertible_v; // If the bound type can't be forwarded, then test if `FunctorParamType` // is a non-const lvalue reference and a reference to the unwrapped type // could have been successfully forwarded. static constexpr bool kIsUnwrappedForwardableNonConstReference = std::is_lvalue_reference_v && !std::is_const_v> && std::is_convertible_v&, FunctorParamType>; // Also intentionally drop the `const` qualifier from `ForwardingType`, to // test if it could have been successfully forwarded if `Passed()` had // been used. static constexpr bool kWouldBeForwardableWithPassed = std::is_convertible_v&&, FunctorParamType>; }; }; template struct BoundAs { template struct StoredAs { static constexpr bool kBindArgumentCanBeCaptured = std::constructible_from; // If the argument can't be captured, intentionally drop the `const` // qualifier from `BoundAsType`, to test if it could have been // successfully captured if `std::move()` had been used. static constexpr bool kWouldBeCapturableWithStdMove = std::constructible_from&&>; }; }; }; // Helper to assert that parameter `i` of type `Arg` can be bound, which means: // * `Arg` can be retained internally as `Storage` // * `Arg` can be forwarded as `Unwrapped` to `Param` // CEF simplified: no raw_ptr/MayDangle checks. template struct ParamCanBeBound { private: using UnwrappedParam = BindArgument::template ForwardedAs< Unwrapped>::template ToParamWithType; using BoundStorage = BindArgument::template BoundAs::template StoredAs; // With `BindRepeating()`, there are two decision points for how to handle a // move-only type: // // 1. Whether the move-only argument should be moved into the internal // `BindState`. Either `std::move()` or `Passed()` is sufficient to trigger // move-only semantics. // 2. Whether or not the bound, move-only argument should be moved to the // bound functor when invoked. When the argument is bound with `Passed()`, // invoking the callback will destructively move the bound, move-only // argument to the bound functor. In contrast, if the argument is bound // with `std::move()`, `RepeatingCallback` will attempt to call the bound // functor with a constant reference to the bound, move-only argument. This // will fail if the bound functor accepts that argument by value, since the // argument cannot be copied. It is this latter case that this // assertion aims to catch. // // In contrast, `BindOnce()` only has one decision point. Once a move-only // type is captured by value into the internal `BindState`, the bound, // move-only argument will always be moved to the functor when invoked. // Failure to use `std::move()` will simply fail the // `MoveOnlyTypeMustUseStdMove` assertion below instead. // // Note: `Passed()` is a legacy of supporting move-only types when repeating // callbacks were the only callback type. A `RepeatingCallback` with a // `Passed()` argument is really a `OnceCallback` and should eventually be // migrated. template struct MoveOnlyTypeMustUseBasePassed { static constexpr bool value = [] { static_assert(v, "base::BindRepeating() argument is a move-only type. Use " "base::Passed() instead of std::move() to transfer " "ownership from the callback to the bound functor."); return v; }(); }; template struct NonConstRefParamMustBeWrapped { static constexpr bool value = [] { static_assert(v, "Bound argument for non-const reference parameter must be " "wrapped in std::ref() or base::OwnedRef()."); return v; }(); }; // Generic failed-to-forward message for cases that didn't match one of the // two assertions above. template struct CanBeForwardedToBoundFunctor { static constexpr bool value = [] { static_assert(v, "Type mismatch between bound argument and bound functor's " "parameter."); return v; }(); }; // The most common reason for failing to capture a parameter is attempting to // pass a move-only type as an lvalue. template struct MoveOnlyTypeMustUseStdMove { static constexpr bool value = [] { static_assert(v, "Attempting to bind a move-only type. Use std::move() to " "transfer ownership to the created callback."); return v; }(); }; // Any other reason the parameter could not be captured. template struct BindArgumentCanBeCaptured { static constexpr bool value = [] { // In practice, failing this precondition should be rare, as the storage // type is deduced from the arguments passed to `Bind()`. static_assert( v, "Cannot capture argument: is the argument copyable or movable?"); return v; }(); }; public: // CEF simplified: no raw_ptr/MayDangle checks. static constexpr bool value = std::conjunction_v, NonConstRefParamMustBeWrapped<>, CanBeForwardedToBoundFunctor<>, MoveOnlyTypeMustUseStdMove<>, BindArgumentCanBeCaptured<>>; }; // Takes three same-length `TypeList`s, and checks `ParamCanBeBound` for each // triple. template struct ParamsCanBeBound { static constexpr bool value = false; }; template struct ParamsCanBeBound, TypeList, TypeList, TypeList> { static constexpr bool value = std::conjunction_v, UnwrappedTypes, Params>...>; }; // Core implementation of `Bind()`, which checks common preconditions before // returning an appropriate callback. template