1 // Copyright (c) 2012 Google Inc. All rights reserved.
2 //
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are
5 // met:
6 //
7 // * Redistributions of source code must retain the above copyright
8 // notice, this list of conditions and the following disclaimer.
9 // * Redistributions in binary form must reproduce the above
10 // copyright notice, this list of conditions and the following disclaimer
11 // in the documentation and/or other materials provided with the
12 // distribution.
13 // * Neither the name of Google Inc. nor the name Chromium Embedded
14 // Framework nor the names of its contributors may be used to endorse
15 // or promote products derived from this software without specific prior
16 // written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30 // Do not include this header file directly. Use base/cef_bind.h or
31 // base/cef_callback.h instead.
32
33 // This file contains utility functions and classes that help the
34 // implementation, and management of the Callback objects.
35
36 #ifndef CEF_INCLUDE_BASE_INTERNAL_CEF_CALLBACK_INTERNAL_H_
37 #define CEF_INCLUDE_BASE_INTERNAL_CEF_CALLBACK_INTERNAL_H_
38
39 #include "include/base/cef_callback_forward.h"
40 #include "include/base/cef_ref_counted.h"
41
42 namespace base {
43
44 struct FakeBindState;
45
46 namespace internal {
47
48 class BindStateBase;
49 class FinallyExecutorCommon;
50 class ThenAndCatchExecutorCommon;
51
52 template <typename ReturnType>
53 class PostTaskExecutor;
54
55 template <typename Functor, typename... BoundArgs>
56 struct BindState;
57
58 class CallbackBase;
59 class CallbackBaseCopyable;
60
61 struct BindStateBaseRefCountTraits {
62 static void Destruct(const BindStateBase*);
63 };
64
65 template <typename T>
66 using PassingType = std::conditional_t<std::is_scalar<T>::value, T, T&&>;
67
68 // BindStateBase is used to provide an opaque handle that the Callback
69 // class can use to represent a function object with bound arguments. It
70 // behaves as an existential type that is used by a corresponding
71 // DoInvoke function to perform the function execution. This allows
72 // us to shield the Callback class from the types of the bound argument via
73 // "type erasure."
74 // At the base level, the only task is to add reference counting data. Avoid
75 // using or inheriting any virtual functions. Creating a vtable for every
76 // BindState template instantiation results in a lot of bloat. Its only task is
77 // to call the destructor which can be done with a function pointer.
78 class BindStateBase
79 : public RefCountedThreadSafe<BindStateBase, BindStateBaseRefCountTraits> {
80 public:
81 REQUIRE_ADOPTION_FOR_REFCOUNTED_TYPE();
82
83 enum CancellationQueryMode {
84 IS_CANCELLED,
85 MAYBE_VALID,
86 };
87
88 using InvokeFuncStorage = void (*)();
89
90 BindStateBase(const BindStateBase&) = delete;
91 BindStateBase& operator=(const BindStateBase&) = delete;
92
93 private:
94 BindStateBase(InvokeFuncStorage polymorphic_invoke,
95 void (*destructor)(const BindStateBase*));
96 BindStateBase(InvokeFuncStorage polymorphic_invoke,
97 void (*destructor)(const BindStateBase*),
98 bool (*query_cancellation_traits)(const BindStateBase*,
99 CancellationQueryMode mode));
100
101 ~BindStateBase() = default;
102
103 friend struct BindStateBaseRefCountTraits;
104 friend class RefCountedThreadSafe<BindStateBase, BindStateBaseRefCountTraits>;
105
106 friend class CallbackBase;
107 friend class CallbackBaseCopyable;
108
109 // Allowlist subclasses that access the destructor of BindStateBase.
110 template <typename Functor, typename... BoundArgs>
111 friend struct BindState;
112 friend struct ::base::FakeBindState;
113
IsCancelled()114 bool IsCancelled() const {
115 return query_cancellation_traits_(this, IS_CANCELLED);
116 }
117
MaybeValid()118 bool MaybeValid() const {
119 return query_cancellation_traits_(this, MAYBE_VALID);
120 }
121
122 // In C++, it is safe to cast function pointers to function pointers of
123 // another type. It is not okay to use void*. We create a InvokeFuncStorage
124 // that that can store our function pointer, and then cast it back to
125 // the original type on usage.
126 InvokeFuncStorage polymorphic_invoke_;
127
128 // Pointer to a function that will properly destroy |this|.
129 void (*destructor_)(const BindStateBase*);
130 bool (*query_cancellation_traits_)(const BindStateBase*,
131 CancellationQueryMode mode);
132 };
133
134 // Holds the Callback methods that don't require specialization to reduce
135 // template bloat.
136 // CallbackBase<MoveOnly> is a direct base class of MoveOnly callbacks, and
137 // CallbackBase<Copyable> uses CallbackBase<MoveOnly> for its implementation.
138 class CallbackBase {
139 public:
140 inline CallbackBase(CallbackBase&& c) noexcept;
141 CallbackBase& operator=(CallbackBase&& c) noexcept;
142
143 explicit CallbackBase(const CallbackBaseCopyable& c);
144 CallbackBase& operator=(const CallbackBaseCopyable& c);
145
146 explicit CallbackBase(CallbackBaseCopyable&& c) noexcept;
147 CallbackBase& operator=(CallbackBaseCopyable&& c) noexcept;
148
149 // Returns true if Callback is null (doesn't refer to anything).
is_null()150 bool is_null() const { return !bind_state_; }
151 explicit operator bool() const { return !is_null(); }
152
153 // Returns true if the callback invocation will be nop due to an cancellation.
154 // It's invalid to call this on uninitialized callback.
155 //
156 // Must be called on the Callback's destination sequence.
157 bool IsCancelled() const;
158
159 // If this returns false, the callback invocation will be a nop due to a
160 // cancellation. This may(!) still return true, even on a cancelled callback.
161 //
162 // This function is thread-safe.
163 bool MaybeValid() const;
164
165 // Returns the Callback into an uninitialized state.
166 void Reset();
167
168 protected:
169 friend class FinallyExecutorCommon;
170 friend class ThenAndCatchExecutorCommon;
171
172 template <typename ReturnType>
173 friend class PostTaskExecutor;
174
175 using InvokeFuncStorage = BindStateBase::InvokeFuncStorage;
176
177 // Returns true if this callback equals |other|. |other| may be null.
178 bool EqualsInternal(const CallbackBase& other) const;
179
180 constexpr inline CallbackBase();
181
182 // Allow initializing of |bind_state_| via the constructor to avoid default
183 // initialization of the scoped_refptr.
184 explicit inline CallbackBase(BindStateBase* bind_state);
185
polymorphic_invoke()186 InvokeFuncStorage polymorphic_invoke() const {
187 return bind_state_->polymorphic_invoke_;
188 }
189
190 // Force the destructor to be instantiated inside this translation unit so
191 // that our subclasses will not get inlined versions. Avoids more template
192 // bloat.
193 ~CallbackBase();
194
195 scoped_refptr<BindStateBase> bind_state_;
196 };
197
198 constexpr CallbackBase::CallbackBase() = default;
199 CallbackBase::CallbackBase(CallbackBase&&) noexcept = default;
CallbackBase(BindStateBase * bind_state)200 CallbackBase::CallbackBase(BindStateBase* bind_state)
201 : bind_state_(AdoptRef(bind_state)) {}
202
203 // CallbackBase<Copyable> is a direct base class of Copyable Callbacks.
204 class CallbackBaseCopyable : public CallbackBase {
205 public:
206 CallbackBaseCopyable(const CallbackBaseCopyable& c);
207 CallbackBaseCopyable(CallbackBaseCopyable&& c) noexcept = default;
208 CallbackBaseCopyable& operator=(const CallbackBaseCopyable& c);
209 CallbackBaseCopyable& operator=(CallbackBaseCopyable&& c) noexcept;
210
211 protected:
212 constexpr CallbackBaseCopyable() = default;
CallbackBaseCopyable(BindStateBase * bind_state)213 explicit CallbackBaseCopyable(BindStateBase* bind_state)
214 : CallbackBase(bind_state) {}
215 ~CallbackBaseCopyable() = default;
216 };
217
218 // Helpers for the `Then()` implementation.
219 template <typename OriginalCallback, typename ThenCallback>
220 struct ThenHelper;
221
222 // Specialization when original callback returns `void`.
223 template <template <typename> class OriginalCallback,
224 template <typename>
225 class ThenCallback,
226 typename... OriginalArgs,
227 typename ThenR,
228 typename... ThenArgs>
229 struct ThenHelper<OriginalCallback<void(OriginalArgs...)>,
230 ThenCallback<ThenR(ThenArgs...)>> {
231 static_assert(sizeof...(ThenArgs) == 0,
232 "|then| callback cannot accept parameters if |this| has a "
233 "void return type.");
234
235 static auto CreateTrampoline() {
236 return [](OriginalCallback<void(OriginalArgs...)> c1,
237 ThenCallback<ThenR(ThenArgs...)> c2, OriginalArgs... c1_args) {
238 std::move(c1).Run(std::forward<OriginalArgs>(c1_args)...);
239 return std::move(c2).Run();
240 };
241 }
242 };
243
244 // Specialization when original callback returns a non-void type.
245 template <template <typename> class OriginalCallback,
246 template <typename>
247 class ThenCallback,
248 typename OriginalR,
249 typename... OriginalArgs,
250 typename ThenR,
251 typename... ThenArgs>
252 struct ThenHelper<OriginalCallback<OriginalR(OriginalArgs...)>,
253 ThenCallback<ThenR(ThenArgs...)>> {
254 static_assert(sizeof...(ThenArgs) == 1,
255 "|then| callback must accept exactly one parameter if |this| "
256 "has a non-void return type.");
257 // TODO(dcheng): This should probably check is_convertible as well (same with
258 // `AssertBindArgsValidity`).
259 static_assert(std::is_constructible<ThenArgs..., OriginalR&&>::value,
260 "|then| callback's parameter must be constructible from "
261 "return type of |this|.");
262
263 static auto CreateTrampoline() {
264 return [](OriginalCallback<OriginalR(OriginalArgs...)> c1,
265 ThenCallback<ThenR(ThenArgs...)> c2, OriginalArgs... c1_args) {
266 return std::move(c2).Run(
267 std::move(c1).Run(std::forward<OriginalArgs>(c1_args)...));
268 };
269 }
270 };
271
272 } // namespace internal
273 } // namespace base
274
275 #endif // CEF_INCLUDE_BASE_INTERNAL_CEF_CALLBACK_INTERNAL_H_
276