v8  8.6.395 (node 15.0.1)
V8 is Google's open source JavaScript engine
v8-fast-api-calls.h
Go to the documentation of this file.
1 // Copyright 2020 the V8 project 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 
5 /**
6  * This file provides additional API on top of the default one for making
7  * API calls, which come from embedder C++ functions. The functions are being
8  * called directly from optimized code, doing all the necessary typechecks
9  * in the compiler itself, instead of on the embedder side. Hence the "fast"
10  * in the name. Example usage might look like:
11  *
12  * \code
13  * void FastMethod(int param, bool another_param);
14  *
15  * v8::FunctionTemplate::New(isolate, SlowCallback, data,
16  * signature, length, constructor_behavior
17  * side_effect_type,
18  * &v8::CFunction::Make(FastMethod));
19  * \endcode
20  *
21  * An example for custom embedder type support might employ a way to wrap/
22  * unwrap various C++ types in JSObject instances, e.g:
23  *
24  * \code
25  *
26  * // Helper method with a check for field count.
27  * template <typename T, int offset>
28  * inline T* GetInternalField(v8::Local<v8::Object> wrapper) {
29  * assert(offset < wrapper->InternalFieldCount());
30  * return reinterpret_cast<T*>(
31  * wrapper->GetAlignedPointerFromInternalField(offset));
32  * }
33  *
34  * class CustomEmbedderType {
35  * public:
36  * // Returns the raw C object from a wrapper JS object.
37  * static CustomEmbedderType* Unwrap(v8::Local<v8::Object> wrapper) {
38  * return GetInternalField<CustomEmbedderType,
39  * kV8EmbedderWrapperObjectIndex>(wrapper);
40  * }
41  * static void FastMethod(v8::ApiObject receiver_obj, int param) {
42  * v8::Object* v8_object = reinterpret_cast<v8::Object*>(&api_object);
43  * CustomEmbedderType* receiver = static_cast<CustomEmbedderType*>(
44  * receiver_obj->GetAlignedPointerFromInternalField(
45  * kV8EmbedderWrapperObjectIndex));
46  *
47  * // Type checks are already done by the optimized code.
48  * // Then call some performance-critical method like:
49  * // receiver->Method(param);
50  * }
51  *
52  * static void SlowMethod(
53  * const v8::FunctionCallbackInfo<v8::Value>& info) {
54  * v8::Local<v8::Object> instance =
55  * v8::Local<v8::Object>::Cast(info.Holder());
56  * CustomEmbedderType* receiver = Unwrap(instance);
57  * // TODO: Do type checks and extract {param}.
58  * receiver->Method(param);
59  * }
60  * };
61  *
62  * // TODO(mslekova): Clean-up these constants
63  * // The constants kV8EmbedderWrapperTypeIndex and
64  * // kV8EmbedderWrapperObjectIndex describe the offsets for the type info
65  * // struct and the native object, when expressed as internal field indices
66  * // within a JSObject. The existance of this helper function assumes that
67  * // all embedder objects have their JSObject-side type info at the same
68  * // offset, but this is not a limitation of the API itself. For a detailed
69  * // use case, see the third example.
70  * static constexpr int kV8EmbedderWrapperTypeIndex = 0;
71  * static constexpr int kV8EmbedderWrapperObjectIndex = 1;
72  *
73  * // The following setup function can be templatized based on
74  * // the {embedder_object} argument.
75  * void SetupCustomEmbedderObject(v8::Isolate* isolate,
76  * v8::Local<v8::Context> context,
77  * CustomEmbedderType* embedder_object) {
78  * isolate->set_embedder_wrapper_type_index(
79  * kV8EmbedderWrapperTypeIndex);
80  * isolate->set_embedder_wrapper_object_index(
81  * kV8EmbedderWrapperObjectIndex);
82  *
83  * v8::CFunction c_func =
84  * MakeV8CFunction(CustomEmbedderType::FastMethod);
85  *
86  * Local<v8::FunctionTemplate> method_template =
87  * v8::FunctionTemplate::New(
88  * isolate, CustomEmbedderType::SlowMethod, v8::Local<v8::Value>(),
89  * v8::Local<v8::Signature>(), 1, v8::ConstructorBehavior::kAllow,
90  * v8::SideEffectType::kHasSideEffect, &c_func);
91  *
92  * v8::Local<v8::ObjectTemplate> object_template =
93  * v8::ObjectTemplate::New(isolate);
94  * object_template->SetInternalFieldCount(
95  * kV8EmbedderWrapperObjectIndex + 1);
96  * object_template->Set(isolate, "method", method_template);
97  *
98  * // Instantiate the wrapper JS object.
99  * v8::Local<v8::Object> object =
100  * object_template->NewInstance(context).ToLocalChecked();
101  * object->SetAlignedPointerInInternalField(
102  * kV8EmbedderWrapperObjectIndex,
103  * reinterpret_cast<void*>(embedder_object));
104  *
105  * // TODO: Expose {object} where it's necessary.
106  * }
107  * \endcode
108  *
109  * For instance if {object} is exposed via a global "obj" variable,
110  * one could write in JS:
111  * function hot_func() {
112  * obj.method(42);
113  * }
114  * and once {hot_func} gets optimized, CustomEmbedderType::FastMethod
115  * will be called instead of the slow version, with the following arguments:
116  * receiver := the {embedder_object} from above
117  * param := 42
118  *
119  * Currently only void return types are supported.
120  * Currently supported argument types:
121  * - pointer to an embedder type
122  * - bool
123  * - int32_t
124  * - uint32_t
125  * - int64_t
126  * - uint64_t
127  * The 64-bit integer types currently have the IDL (unsigned) long long
128  * semantics: https://heycam.github.io/webidl/#abstract-opdef-converttoint
129  * In the future we'll extend the API to also provide conversions from/to
130  * BigInt to preserve full precision.
131  * To be supported types:
132  * - float32_t
133  * - float64_t
134  * - arrays of C types
135  * - arrays of embedder types
136  */
137 
138 #ifndef INCLUDE_V8_FAST_API_CALLS_H_
139 #define INCLUDE_V8_FAST_API_CALLS_H_
140 
141 #include <stddef.h>
142 #include <stdint.h>
143 
144 #include "v8config.h" // NOLINT(build/include_directory)
145 
146 namespace v8 {
147 
148 class CTypeInfo {
149  public:
150  enum class Type : char {
151  kVoid,
152  kBool,
153  kInt32,
154  kUint32,
155  kInt64,
156  kUint64,
157  kFloat32,
158  kFloat64,
159  kV8Value,
160  };
161 
162  enum class ArgFlags : uint8_t {
163  kNone = 0,
164  kIsArrayBit = 1 << 0, // This argument is first in an array of values.
165  };
166 
168  return CTypeInfo(static_cast<int>(flags) | kIsWrapperTypeBit);
169  }
170 
171  static constexpr CTypeInfo FromCType(Type ctype,
172  ArgFlags flags = ArgFlags::kNone) {
173  // TODO(mslekova): Refactor the manual bit manipulations to use
174  // PointerWithPayload instead.
175  // ctype cannot be Type::kV8Value.
176  return CTypeInfo(
177  ((static_cast<uintptr_t>(ctype) << kTypeOffset) & kTypeMask) |
178  static_cast<int>(flags));
179  }
180 
181  const void* GetWrapperInfo() const;
182 
183  constexpr Type GetType() const {
184  if (payload_ & kIsWrapperTypeBit) {
185  return Type::kV8Value;
186  }
187  return static_cast<Type>((payload_ & kTypeMask) >> kTypeOffset);
188  }
189 
190  constexpr bool IsArray() const {
191  return payload_ & static_cast<int>(ArgFlags::kIsArrayBit);
192  }
193 
194  static const CTypeInfo& Invalid() {
195  static CTypeInfo invalid = CTypeInfo(0);
196  return invalid;
197  }
198 
199  private:
200  explicit constexpr CTypeInfo(uintptr_t payload) : payload_(payload) {}
201 
202  // That must be the last bit after ArgFlags.
203  static constexpr uintptr_t kIsWrapperTypeBit = 1 << 1;
204  static constexpr uintptr_t kWrapperTypeInfoMask = static_cast<uintptr_t>(~0)
205  << 2;
206 
207  static constexpr unsigned int kTypeOffset = kIsWrapperTypeBit;
208  static constexpr unsigned int kTypeSize = 8 - kTypeOffset;
209  static constexpr uintptr_t kTypeMask =
210  (~(static_cast<uintptr_t>(~0) << kTypeSize)) << kTypeOffset;
211 
212  const uintptr_t payload_;
213 };
214 
216  public:
217  virtual const CTypeInfo& ReturnInfo() const = 0;
218  virtual unsigned int ArgumentCount() const = 0;
219  virtual const CTypeInfo& ArgumentInfo(unsigned int index) const = 0;
220 };
221 
222 struct ApiObject {
223  uintptr_t address;
224 };
225 
226 namespace internal {
227 
228 template <typename T>
229 struct GetCType {
230  static constexpr CTypeInfo Get() {
232  }
233 };
234 
235 #define SPECIALIZE_GET_C_TYPE_FOR(ctype, ctypeinfo)
236  template <>
237  struct GetCType<ctype> {
238  static constexpr CTypeInfo Get() {
239  return CTypeInfo::FromCType(CTypeInfo::Type::ctypeinfo);
240  }
241  };
242 
243 #define SUPPORTED_C_TYPES(V)
244  V(void, kVoid)
245  V(bool, kBool)
246  V(int32_t, kInt32)
247  V(uint32_t, kUint32)
248  V(int64_t, kInt64)
249  V(uint64_t, kUint64)
250  V(float, kFloat32)
251  V(double, kFloat64)
252  V(ApiObject, kV8Value)
253 
255 
256 // T* where T is a primitive (array of primitives).
257 template <typename T, typename = void>
259  static constexpr CTypeInfo Get() {
260  return CTypeInfo::FromCType(GetCType<T>::Get().GetType(),
262  }
263 };
264 
265 // T* where T is an API object.
266 template <typename T>
267 struct GetCTypePointerImpl<T, void> {
268  static constexpr CTypeInfo Get() { return CTypeInfo::FromWrapperType(); }
269 };
270 
271 // T** where T is a primitive. Not allowed.
272 template <typename T, typename = void>
274  static_assert(sizeof(T**) != sizeof(T**), "Unsupported type");
275 };
276 
277 // T** where T is an API object (array of API objects).
278 template <typename T>
279 struct GetCTypePointerPointerImpl<T, void> {
280  static constexpr CTypeInfo Get() {
282  }
283 };
284 
285 template <typename T>
286 struct GetCType<T**> : public GetCTypePointerPointerImpl<T> {};
287 
288 template <typename T>
289 struct GetCType<T*> : public GetCTypePointerImpl<T> {};
290 
291 template <typename R, bool RaisesException, typename... Args>
293  public:
294  static constexpr int kHasErrorArgCount = (RaisesException ? 1 : 0);
295  static constexpr int kReceiverCount = 1;
297  : return_info_(internal::GetCType<R>::Get()),
298  arg_count_(sizeof...(Args) - kHasErrorArgCount),
299  arg_info_{internal::GetCType<Args>::Get()...} {
300  static_assert(sizeof...(Args) >= kHasErrorArgCount + kReceiverCount,
301  "The receiver or the has_error argument is missing.");
302  static_assert(
303  internal::GetCType<R>::Get().GetType() == CTypeInfo::Type::kVoid,
304  "Only void return types are currently supported.");
305  }
306 
307  const CTypeInfo& ReturnInfo() const override { return return_info_; }
308  unsigned int ArgumentCount() const override { return arg_count_; }
309  const CTypeInfo& ArgumentInfo(unsigned int index) const override {
310  if (index >= ArgumentCount()) {
311  return CTypeInfo::Invalid();
312  }
313  return arg_info_[index];
314  }
315 
316  private:
317  const CTypeInfo return_info_;
318  const unsigned int arg_count_;
319  const CTypeInfo arg_info_[sizeof...(Args)];
320 };
321 
322 } // namespace internal
323 
325  public:
326  constexpr CFunction() : address_(nullptr), type_info_(nullptr) {}
327 
328  const CTypeInfo& ReturnInfo() const { return type_info_->ReturnInfo(); }
329 
330  const CTypeInfo& ArgumentInfo(unsigned int index) const {
331  return type_info_->ArgumentInfo(index);
332  }
333 
334  unsigned int ArgumentCount() const { return type_info_->ArgumentCount(); }
335 
336  const void* GetAddress() const { return address_; }
337  const CFunctionInfo* GetTypeInfo() const { return type_info_; }
338 
339  template <typename F>
340  static CFunction Make(F* func) {
341  return ArgUnwrap<F*>::Make(func);
342  }
343 
344  template <typename F>
345  static CFunction MakeWithErrorSupport(F* func) {
346  return ArgUnwrap<F*>::MakeWithErrorSupport(func);
347  }
348 
349  template <typename F>
350  static CFunction Make(F* func, const CFunctionInfo* type_info) {
351  return CFunction(reinterpret_cast<const void*>(func), type_info);
352  }
353 
354  private:
355  const void* address_;
356  const CFunctionInfo* type_info_;
357 
358  CFunction(const void* address, const CFunctionInfo* type_info);
359 
360  template <typename R, bool RaisesException, typename... Args>
361  static CFunctionInfo* GetCFunctionInfo() {
362  static internal::CFunctionInfoImpl<R, RaisesException, Args...> instance;
363  return &instance;
364  }
365 
366  template <typename F>
367  class ArgUnwrap {
368  static_assert(sizeof(F) != sizeof(F),
369  "CFunction must be created from a function pointer.");
370  };
371 
372  template <typename R, typename... Args>
373  class ArgUnwrap<R (*)(Args...)> {
374  public:
375  static CFunction Make(R (*func)(Args...)) {
376  return CFunction(reinterpret_cast<const void*>(func),
377  GetCFunctionInfo<R, false, Args...>());
378  }
379  static CFunction MakeWithErrorSupport(R (*func)(Args...)) {
380  return CFunction(reinterpret_cast<const void*>(func),
381  GetCFunctionInfo<R, true, Args...>());
382  }
383  };
384 };
385 
386 } // namespace v8
387 
388 #endif // INCLUDE_V8_FAST_API_CALLS_H_