blob: cc6b966485958edd5d7f3f003332eee8fc702c6a [file] [log] [blame]
Avi Drissman468e51b62022-09-13 20:47:011// Copyright 2014 The Chromium Authors
kolczyk735c49b62014-10-24 13:06:042// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
aa@chromium.org37dacfa2013-11-26 03:31:044
aa@chromium.orgb520e132013-11-29 03:21:485#ifndef GIN_FUNCTION_TEMPLATE_H_
6#define GIN_FUNCTION_TEMPLATE_H_
7
avi90e658dd2015-12-21 07:16:198#include <stddef.h>
Nikolaos Papaspyrou5ce2a2f2023-10-19 09:09:009#include <type_traits>
Jeremy Roman6a1242b2019-02-04 17:51:5710#include <utility>
avi90e658dd2015-12-21 07:16:1911
Hans Wennborgc8b134b2020-06-19 21:15:3912#include "base/check.h"
Avi Drissman93a273dd2023-01-11 00:38:2713#include "base/functional/callback.h"
Keishi Hattori0e45c022021-11-27 09:25:5214#include "base/memory/raw_ptr.h"
Ashley Newsondeda1812024-01-09 12:04:1815#include "base/observer_list.h"
Devlin Cronine9db9842018-04-09 17:51:0516#include "base/strings/strcat.h"
aa@chromium.org314cde12013-11-23 20:26:5117#include "gin/arguments.h"
18#include "gin/converter.h"
jochen@chromium.org48c21632013-12-12 21:32:3419#include "gin/gin_export.h"
Ashley Newsondeda1812024-01-09 12:04:1820#include "gin/per_isolate_data.h"
Dan Elphick05acd602021-08-30 15:22:0721#include "v8/include/v8-external.h"
22#include "v8/include/v8-forward.h"
23#include "v8/include/v8-persistent-handle.h"
24#include "v8/include/v8-template.h"
aa@chromium.org314cde12013-11-23 20:26:5125
26namespace gin {
27
Devlin Cronine9db9842018-04-09 17:51:0528struct InvokerOptions {
29 bool holder_is_first_argument = false;
30 const char* holder_type = nullptr; // Null if unknown or not applicable.
aa@chromium.orgbf3dd3c2013-12-06 06:55:2531};
32
aa@chromium.org37dacfa2013-11-26 03:31:0433namespace internal {
34
aa@chromium.org314cde12013-11-23 20:26:5135template<typename T>
aa@chromium.orgbf3dd3c2013-12-06 06:55:2536struct CallbackParamTraits {
37 typedef T LocalType;
aa@chromium.org314cde12013-11-23 20:26:5138};
39template<typename T>
aa@chromium.orgbf3dd3c2013-12-06 06:55:2540struct CallbackParamTraits<const T&> {
41 typedef T LocalType;
42};
43template<typename T>
44struct CallbackParamTraits<const T*> {
45 typedef T* LocalType;
aa@chromium.org314cde12013-11-23 20:26:5146};
47
Colin Blundellea615d422021-05-12 09:35:4148// CallbackHolder and CallbackHolderBase are used to pass a
49// base::RepeatingCallback from CreateFunctionTemplate through v8 (via
50// v8::FunctionTemplate) to DispatchToCallback, where it is invoked.
aa@chromium.org6fe56102013-12-08 07:10:5851
Ashley Newsondeda1812024-01-09 12:04:1852// CallbackHolder will clean up the callback in two different scenarios:
53// - If the garbage collector finds that it's garbage and collects it. (But note
54// that even _if_ we become garbage, we might never get collected!)
55// - If the isolate gets disposed.
56//
57// TODO(crbug.com/1285119): When gin::Wrappable gets migrated over to using
58// cppgc, this class should also be considered for migration.
59
aa@chromium.org6fe56102013-12-08 07:10:5860// This simple base class is used so that we can share a single object template
61// among every CallbackHolder instance.
jochen@chromium.orgbf0142902014-02-11 15:06:1262class GIN_EXPORT CallbackHolderBase {
jochen@chromium.orgb4acaf82013-12-12 09:40:5063 public:
Daniel Hosseinian68c0798d2021-04-16 08:16:0764 CallbackHolderBase(const CallbackHolderBase&) = delete;
65 CallbackHolderBase& operator=(const CallbackHolderBase&) = delete;
66
deepak.sfaaa1b62015-04-30 07:30:4867 v8::Local<v8::External> GetHandle(v8::Isolate* isolate);
jochen@chromium.orgbf0142902014-02-11 15:06:1268
aa@chromium.org314cde12013-11-23 20:26:5169 protected:
jochen@chromium.orgbf0142902014-02-11 15:06:1270 explicit CallbackHolderBase(v8::Isolate* isolate);
71 virtual ~CallbackHolderBase();
72
73 private:
Ashley Newsondeda1812024-01-09 12:04:1874 class DisposeObserver : gin::PerIsolateData::DisposeObserver {
75 public:
76 DisposeObserver(gin::PerIsolateData* per_isolate_data,
77 CallbackHolderBase* holder);
78 ~DisposeObserver() override;
79 void OnBeforeDispose(v8::Isolate* isolate) override;
80 void OnDisposed() override;
81
82 private:
83 const raw_ref<gin::PerIsolateData> per_isolate_data_;
84 const raw_ref<CallbackHolderBase> holder_;
85 };
86
dcarney99ade9082015-04-22 09:55:4287 static void FirstWeakCallback(
88 const v8::WeakCallbackInfo<CallbackHolderBase>& data);
89 static void SecondWeakCallback(
90 const v8::WeakCallbackInfo<CallbackHolderBase>& data);
jochen@chromium.orgbf0142902014-02-11 15:06:1291
dcarney99ade9082015-04-22 09:55:4292 v8::Global<v8::External> v8_ref_;
Ashley Newsondeda1812024-01-09 12:04:1893 DisposeObserver dispose_observer_;
aa@chromium.org314cde12013-11-23 20:26:5194};
95
aa@chromium.org314cde12013-11-23 20:26:5196template<typename Sig>
97class CallbackHolder : public CallbackHolderBase {
98 public:
jochen@chromium.orgbf0142902014-02-11 15:06:1299 CallbackHolder(v8::Isolate* isolate,
tzikc21a0dc2017-11-14 08:23:44100 base::RepeatingCallback<Sig> callback,
Devlin Cronine9db9842018-04-09 17:51:05101 InvokerOptions invoker_options)
tzikc21a0dc2017-11-14 08:23:44102 : CallbackHolderBase(isolate),
103 callback(std::move(callback)),
Devlin Cronine9db9842018-04-09 17:51:05104 invoker_options(std::move(invoker_options)) {}
Daniel Hosseinian68c0798d2021-04-16 08:16:07105 CallbackHolder(const CallbackHolder&) = delete;
106 CallbackHolder& operator=(const CallbackHolder&) = delete;
Devlin Cronine9db9842018-04-09 17:51:05107
tzikc21a0dc2017-11-14 08:23:44108 base::RepeatingCallback<Sig> callback;
Devlin Cronine9db9842018-04-09 17:51:05109 InvokerOptions invoker_options;
110
aa@chromium.org314cde12013-11-23 20:26:51111 private:
Daniel Hosseinian68c0798d2021-04-16 08:16:07112 ~CallbackHolder() override = default;
aa@chromium.org314cde12013-11-23 20:26:51113};
114
Devlin Cronine9db9842018-04-09 17:51:05115template <typename T>
116bool GetNextArgument(Arguments* args,
117 const InvokerOptions& invoker_options,
118 bool is_first,
aa@chromium.orgbf3dd3c2013-12-06 06:55:25119 T* result) {
Devlin Cronine9db9842018-04-09 17:51:05120 if (is_first && invoker_options.holder_is_first_argument) {
aa@chromium.orgbf3dd3c2013-12-06 06:55:25121 return args->GetHolder(result);
122 } else {
123 return args->GetNext(result);
124 }
125}
126
127// For advanced use cases, we allow callers to request the unparsed Arguments
128// object and poke around in it directly.
Devlin Cronine9db9842018-04-09 17:51:05129inline bool GetNextArgument(Arguments* args,
130 const InvokerOptions& invoker_options,
131 bool is_first,
aa@chromium.orgbf3dd3c2013-12-06 06:55:25132 Arguments* result) {
133 *result = *args;
134 return true;
135}
Devlin Cronine9db9842018-04-09 17:51:05136inline bool GetNextArgument(Arguments* args,
137 const InvokerOptions& invoker_options,
138 bool is_first,
aa@chromium.org5b971af2014-01-06 22:20:54139 Arguments** result) {
140 *result = args;
141 return true;
142}
aa@chromium.orgbf3dd3c2013-12-06 06:55:25143
aa@chromium.org2491f142013-12-21 17:54:37144// It's common for clients to just need the isolate, so we make that easy.
Devlin Cronine9db9842018-04-09 17:51:05145inline bool GetNextArgument(Arguments* args,
146 const InvokerOptions& invoker_options,
147 bool is_first,
148 v8::Isolate** result) {
aa@chromium.org2491f142013-12-21 17:54:37149 *result = args->isolate();
150 return true;
151}
152
Devlin Cronine9db9842018-04-09 17:51:05153// Throws an error indicating conversion failure.
154GIN_EXPORT void ThrowConversionError(Arguments* args,
155 const InvokerOptions& invoker_options,
156 size_t index);
157
kolczyk735c49b62014-10-24 13:06:04158// Class template for extracting and storing single argument for callback
159// at position |index|.
Nikolaos Papaspyrou5ce2a2f2023-10-19 09:09:00160template <size_t index, typename ArgType, typename = void>
kolczyk735c49b62014-10-24 13:06:04161struct ArgumentHolder {
162 using ArgLocalType = typename CallbackParamTraits<ArgType>::LocalType;
163
164 ArgLocalType value;
165 bool ok;
166
Devlin Cronine9db9842018-04-09 17:51:05167 ArgumentHolder(Arguments* args, const InvokerOptions& invoker_options)
168 : ok(GetNextArgument(args, invoker_options, index == 0, &value)) {
169 if (!ok)
170 ThrowConversionError(args, invoker_options, index);
kolczyk735c49b62014-10-24 13:06:04171 }
172};
173
Nikolaos Papaspyrou5ce2a2f2023-10-19 09:09:00174// This is required for types such as v8::LocalVector<T>, which don't have
175// a default constructor. To create an element of such a type, the isolate
176// has to be provided.
177template <size_t index, typename ArgType>
178struct ArgumentHolder<
179 index,
180 ArgType,
181 std::enable_if_t<!std::is_default_constructible_v<
182 typename CallbackParamTraits<ArgType>::LocalType> &&
183 std::is_constructible_v<
184 typename CallbackParamTraits<ArgType>::LocalType,
185 v8::Isolate*>>> {
186 using ArgLocalType = typename CallbackParamTraits<ArgType>::LocalType;
187
188 ArgLocalType value;
189 bool ok;
190
191 ArgumentHolder(Arguments* args, const InvokerOptions& invoker_options)
192 : value(args->isolate()),
193 ok(GetNextArgument(args, invoker_options, index == 0, &value)) {
194 if (!ok) {
195 ThrowConversionError(args, invoker_options, index);
196 }
197 }
198};
199
kolczyk735c49b62014-10-24 13:06:04200// Class template for converting arguments from JavaScript to C++ and running
201// the callback with them.
202template <typename IndicesType, typename... ArgTypes>
tzikc21a0dc2017-11-14 08:23:44203class Invoker;
kolczyk735c49b62014-10-24 13:06:04204
205template <size_t... indices, typename... ArgTypes>
tzikc21a0dc2017-11-14 08:23:44206class Invoker<std::index_sequence<indices...>, ArgTypes...>
kolczyk735c49b62014-10-24 13:06:04207 : public ArgumentHolder<indices, ArgTypes>... {
208 public:
209 // Invoker<> inherits from ArgumentHolder<> for each argument.
210 // C++ has always been strict about the class initialization order,
211 // so it is guaranteed ArgumentHolders will be initialized (and thus, will
212 // extract arguments from Arguments) in the right order.
Devlin Cronine9db9842018-04-09 17:51:05213 Invoker(Arguments* args, const InvokerOptions& invoker_options)
214 : ArgumentHolder<indices, ArgTypes>(args, invoker_options)...,
215 args_(args) {}
kolczyk735c49b62014-10-24 13:06:04216
217 bool IsOK() {
218 return And(ArgumentHolder<indices, ArgTypes>::ok...);
219 }
220
221 template <typename ReturnType>
tzikc21a0dc2017-11-14 08:23:44222 void DispatchToCallback(
223 base::RepeatingCallback<ReturnType(ArgTypes...)> callback) {
Jeremy Apthorp789ac3b2020-04-01 01:06:45224 args_->Return(
225 callback.Run(std::move(ArgumentHolder<indices, ArgTypes>::value)...));
kolczyk735c49b62014-10-24 13:06:04226 }
227
228 // In C++, you can declare the function foo(void), but you can't pass a void
229 // expression to foo. As a result, we must specialize the case of Callbacks
230 // that have the void return type.
tzikc21a0dc2017-11-14 08:23:44231 void DispatchToCallback(base::RepeatingCallback<void(ArgTypes...)> callback) {
Jeremy Apthorp789ac3b2020-04-01 01:06:45232 callback.Run(std::move(ArgumentHolder<indices, ArgTypes>::value)...);
kolczyk735c49b62014-10-24 13:06:04233 }
234
235 private:
236 static bool And() { return true; }
237 template <typename... T>
238 static bool And(bool arg1, T... args) {
239 return arg1 && And(args...);
240 }
241
Keishi Hattori0e45c022021-11-27 09:25:52242 raw_ptr<Arguments> args_;
kolczyk735c49b62014-10-24 13:06:04243};
aa@chromium.orgbf3dd3c2013-12-06 06:55:25244
aa@chromium.org81f8b91b2013-11-26 21:02:51245// DispatchToCallback converts all the JavaScript arguments to C++ types and
Colin Blundellea615d422021-05-12 09:35:41246// invokes the base::RepeatingCallback.
kolczyk735c49b62014-10-24 13:06:04247template <typename Sig>
248struct Dispatcher {};
aa@chromium.orgbf3dd3c2013-12-06 06:55:25249
kolczyk735c49b62014-10-24 13:06:04250template <typename ReturnType, typename... ArgTypes>
251struct Dispatcher<ReturnType(ArgTypes...)> {
Jeremy Roman6a1242b2019-02-04 17:51:57252 static void DispatchToCallbackImpl(Arguments* args) {
deepak.sfaaa1b62015-04-30 07:30:48253 v8::Local<v8::External> v8_holder;
Jeremy Roman6a1242b2019-02-04 17:51:57254 CHECK(args->GetData(&v8_holder));
jochen@chromium.orgbf0142902014-02-11 15:06:12255 CallbackHolderBase* holder_base = reinterpret_cast<CallbackHolderBase*>(
256 v8_holder->Value());
aa@chromium.org314cde12013-11-23 20:26:51257
kolczyk735c49b62014-10-24 13:06:04258 typedef CallbackHolder<ReturnType(ArgTypes...)> HolderT;
aa@chromium.orgbf3dd3c2013-12-06 06:55:25259 HolderT* holder = static_cast<HolderT*>(holder_base);
aa@chromium.org37dacfa2013-11-26 03:31:04260
tzikc21a0dc2017-11-14 08:23:44261 using Indices = std::index_sequence_for<ArgTypes...>;
Jeremy Roman6a1242b2019-02-04 17:51:57262 Invoker<Indices, ArgTypes...> invoker(args, holder->invoker_options);
kolczyk735c49b62014-10-24 13:06:04263 if (invoker.IsOK())
264 invoker.DispatchToCallback(holder->callback);
aa@chromium.orgd73341d12013-12-21 00:48:46265 }
Jeremy Roman6a1242b2019-02-04 17:51:57266
267 static void DispatchToCallback(
268 const v8::FunctionCallbackInfo<v8::Value>& info) {
269 Arguments args(info);
270 DispatchToCallbackImpl(&args);
271 }
272
273 static void DispatchToCallbackForProperty(
274 v8::Local<v8::Name>,
275 const v8::PropertyCallbackInfo<v8::Value>& info) {
276 Arguments args(info);
277 DispatchToCallbackImpl(&args);
278 }
aa@chromium.orgd73341d12013-12-21 00:48:46279};
280
aa@chromium.org81f8b91b2013-11-26 21:02:51281} // namespace internal
282
aa@chromium.orgbf3dd3c2013-12-06 06:55:25283// CreateFunctionTemplate creates a v8::FunctionTemplate that will create
Colin Blundellea615d422021-05-12 09:35:41284// JavaScript functions that execute a provided C++ function or
285// base::RepeatingCallback. JavaScript arguments are automatically converted via
286// gin::Converter, as is the return value of the C++ function, if any.
287// |invoker_options| contains additional parameters. If it contains a
288// holder_type, it will be used to provide a useful conversion error if the
289// holder is the first argument. If not provided, a generic invocation error
290// will be used.
mnaganov098ba6f2015-03-03 16:34:48291//
292// NOTE: V8 caches FunctionTemplates for a lifetime of a web page for its own
293// internal reasons, thus it is generally a good idea to cache the template
294// returned by this function. Otherwise, repeated method invocations from JS
295// will create substantial memory leaks. See http://crbug.com/463487.
Ashley Newsondeda1812024-01-09 12:04:18296//
297// The callback will be destroyed if either the function template gets garbage
298// collected or _after_ the isolate is disposed. Garbage collection can never be
299// relied upon. As such, any destructors for objects bound to the callback must
300// not depend on the isolate being alive at the point they are called. The order
301// in which callbacks are destroyed is not guaranteed.
tzikc21a0dc2017-11-14 08:23:44302template <typename Sig>
aa@chromium.org81f8b91b2013-11-26 21:02:51303v8::Local<v8::FunctionTemplate> CreateFunctionTemplate(
tzikc21a0dc2017-11-14 08:23:44304 v8::Isolate* isolate,
305 base::RepeatingCallback<Sig> callback,
Devlin Cronine9db9842018-04-09 17:51:05306 InvokerOptions invoker_options = {}) {
aa@chromium.orgbf3dd3c2013-12-06 06:55:25307 typedef internal::CallbackHolder<Sig> HolderT;
Devlin Cronine9db9842018-04-09 17:51:05308 HolderT* holder =
309 new HolderT(isolate, std::move(callback), std::move(invoker_options));
jochen@chromium.orgbf0142902014-02-11 15:06:12310
jochen596fd5e2016-07-06 12:29:50311 v8::Local<v8::FunctionTemplate> tmpl = v8::FunctionTemplate::New(
312 isolate, &internal::Dispatcher<Sig>::DispatchToCallback,
Sathya Gunasekaran77d2ce82021-01-08 16:41:13313 ConvertToV8<v8::Local<v8::External>>(isolate, holder->GetHandle(isolate)),
314 v8::Local<v8::Signature>(), 0, v8::ConstructorBehavior::kThrow);
jochen596fd5e2016-07-06 12:29:50315 return tmpl;
aa@chromium.org7618ebbb2013-11-27 03:38:26316}
317
Jeremy Roman6a1242b2019-02-04 17:51:57318// CreateDataPropertyCallback creates a v8::AccessorNameGetterCallback and
319// corresponding data value that will hold and execute the provided
320// base::RepeatingCallback, using automatic conversions similar to
321// |CreateFunctionTemplate|.
322//
323// It is expected that these will be passed to v8::Template::SetLazyDataProperty
324// or another similar function.
325template <typename Sig>
326std::pair<v8::AccessorNameGetterCallback, v8::Local<v8::Value>>
327CreateDataPropertyCallback(v8::Isolate* isolate,
328 base::RepeatingCallback<Sig> callback,
329 InvokerOptions invoker_options = {}) {
330 typedef internal::CallbackHolder<Sig> HolderT;
331 HolderT* holder =
332 new HolderT(isolate, std::move(callback), std::move(invoker_options));
333 return {&internal::Dispatcher<Sig>::DispatchToCallbackForProperty,
334 ConvertToV8<v8::Local<v8::External>>(isolate,
335 holder->GetHandle(isolate))};
336}
337
aa@chromium.org314cde12013-11-23 20:26:51338} // namespace gin
aa@chromium.orgb520e132013-11-29 03:21:48339
340#endif // GIN_FUNCTION_TEMPLATE_H_