v8  9.4.146 (node 16.15.0)
V8 is Google's open source JavaScript engine
v8.h
Go to the documentation of this file.
1 // Copyright 2012 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 /** \mainpage V8 API Reference Guide
6  *
7  * V8 is Google's open source JavaScript engine.
8  *
9  * This set of documents provides reference material generated from the
10  * V8 header file, include/v8.h.
11  *
12  * For other documentation see https://v8.dev/.
13  */
14 
15 #ifndef INCLUDE_V8_H_
16 #define INCLUDE_V8_H_
17 
18 #include <stddef.h>
19 #include <stdint.h>
20 #include <stdio.h>
21 
22 #include <atomic>
23 #include <memory>
24 #include <string>
25 #include <type_traits>
26 #include <utility>
27 #include <vector>
28 
29 #include "cppgc/common.h"
30 #include "v8-internal.h" // NOLINT(build/include_directory)
31 #include "v8-version.h" // NOLINT(build/include_directory)
32 #include "v8config.h" // NOLINT(build/include_directory)
33 
34 // We reserve the V8_* prefix for macros defined in V8 public API and
35 // assume there are no name conflicts with the embedder's code.
36 
37 /**
38  * The v8 JavaScript engine.
39  */
40 namespace v8 {
41 
42 class AccessorSignature;
43 class Array;
44 class ArrayBuffer;
45 class BigInt;
46 class BigIntObject;
47 class Boolean;
48 class BooleanObject;
49 class CFunction;
50 class CallHandlerHelper;
51 class Context;
52 class CppHeap;
53 class CTypeInfo;
54 class Data;
55 class Date;
57 class External;
58 class Function;
59 class FunctionTemplate;
60 class HeapProfiler;
61 class ImplementationUtilities;
62 class Int32;
63 class Integer;
64 class Isolate;
65 class Isolate;
66 class MicrotaskQueue;
67 class Name;
68 class Number;
69 class NumberObject;
70 class Object;
71 class ObjectOperationDescriptor;
72 class ObjectTemplate;
73 class Platform;
74 class Primitive;
75 class PrimitiveArray;
76 class Private;
77 class Promise;
78 class PropertyDescriptor;
79 class Proxy;
80 class RawOperationDescriptor;
81 class Script;
82 class SharedArrayBuffer;
83 class Signature;
84 class StackFrame;
85 class StackTrace;
86 class StartupData;
87 class String;
88 class StringObject;
89 class Symbol;
90 class SymbolObject;
92 class Uint32;
93 class Utils;
94 class Value;
95 class WasmMemoryObject;
96 class WasmModuleObject;
97 template <class K, class V, class T>
98 class GlobalValueMap;
99 template <class K, class V, class T>
101 template<class T> class NonCopyablePersistentTraits;
102 template <class T, class M = NonCopyablePersistentTraits<T>>
103 class Persistent;
104 template <class T>
106 template <class T>
107 class Eternal;
108 template <class T>
109 class Global;
110 template <class T>
111 class Local;
112 template <class T>
113 class Maybe;
114 template <class T>
115 class MaybeLocal;
116 template <class T>
117 class TracedGlobal;
118 template <class T>
119 class TracedReference;
120 template<class K, class V, class T> class PersistentValueMap;
121 template<class T, class P> class WeakCallbackObject;
122 template <class T>
123 class PersistentBase;
124 template <class V, class T>
126 template<typename T> class FunctionCallbackInfo;
127 template<typename T> class PropertyCallbackInfo;
128 template<typename T> class ReturnValue;
129 
130 namespace internal {
131 class BackgroundDeserializeTask;
132 class BasicTracedReferenceExtractor;
133 class ExternalString;
134 class FunctionCallbackArguments;
135 class GlobalHandles;
136 class Heap;
137 class HeapObject;
138 class Isolate;
139 class LocalEmbedderHeapTracer;
140 class MicrotaskQueue;
141 class PropertyCallbackArguments;
142 class ReadOnlyHeap;
143 class ScopedExternalStringLock;
144 class ThreadLocalTop;
145 struct ScriptStreamingData;
146 enum class ArgumentsType;
147 template <ArgumentsType>
148 class Arguments;
149 template <typename T>
151 
152 namespace wasm {
153 class NativeModule;
154 class StreamingDecoder;
155 } // namespace wasm
156 
157 } // namespace internal
158 
159 namespace metrics {
160 class Recorder;
161 } // namespace metrics
162 
163 namespace debug {
164 class ConsoleCallArguments;
165 } // namespace debug
166 
167 // --- Handles ---
168 
169 /**
170  * An object reference managed by the v8 garbage collector.
171  *
172  * All objects returned from v8 have to be tracked by the garbage
173  * collector so that it knows that the objects are still alive. Also,
174  * because the garbage collector may move objects, it is unsafe to
175  * point directly to an object. Instead, all objects are stored in
176  * handles which are known by the garbage collector and updated
177  * whenever an object moves. Handles should always be passed by value
178  * (except in cases like out-parameters) and they should never be
179  * allocated on the heap.
180  *
181  * There are two types of handles: local and persistent handles.
182  *
183  * Local handles are light-weight and transient and typically used in
184  * local operations. They are managed by HandleScopes. That means that a
185  * HandleScope must exist on the stack when they are created and that they are
186  * only valid inside of the HandleScope active during their creation.
187  * For passing a local handle to an outer HandleScope, an EscapableHandleScope
188  * and its Escape() method must be used.
189  *
190  * Persistent handles can be used when storing objects across several
191  * independent operations and have to be explicitly deallocated when they're no
192  * longer used.
193  *
194  * It is safe to extract the object stored in the handle by
195  * dereferencing the handle (for instance, to extract the Object* from
196  * a Local<Object>); the value will still be governed by a handle
197  * behind the scenes and the same rules apply to these values as to
198  * their handles.
199  */
200 template <class T>
201 class Local {
202  public:
203  V8_INLINE Local() : val_(nullptr) {}
204  template <class S>
206  : val_(reinterpret_cast<T*>(*that)) {
207  /**
208  * This check fails when trying to convert between incompatible
209  * handles. For example, converting from a Local<String> to a
210  * Local<Number>.
211  */
212  static_assert(std::is_base_of<T, S>::value, "type check");
213  }
214 
215  /**
216  * Returns true if the handle is empty.
217  */
218  V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
219 
220  /**
221  * Sets the handle to be empty. IsEmpty() will then return true.
222  */
223  V8_INLINE void Clear() { val_ = nullptr; }
224 
225  V8_INLINE T* operator->() const { return val_; }
226 
227  V8_INLINE T* operator*() const { return val_; }
228 
229  /**
230  * Checks whether two handles are the same.
231  * Returns true if both are empty, or if the objects to which they refer
232  * are identical.
233  *
234  * If both handles refer to JS objects, this is the same as strict equality.
235  * For primitives, such as numbers or strings, a `false` return value does not
236  * indicate that the values aren't equal in the JavaScript sense.
237  * Use `Value::StrictEquals()` to check primitives for equality.
238  */
239  template <class S>
240  V8_INLINE bool operator==(const Local<S>& that) const {
241  internal::Address* a = reinterpret_cast<internal::Address*>(this->val_);
242  internal::Address* b = reinterpret_cast<internal::Address*>(that.val_);
243  if (a == nullptr) return b == nullptr;
244  if (b == nullptr) return false;
245  return *a == *b;
246  }
247 
248  template <class S> V8_INLINE bool operator==(
249  const PersistentBase<S>& that) const {
250  internal::Address* a = reinterpret_cast<internal::Address*>(this->val_);
251  internal::Address* b = reinterpret_cast<internal::Address*>(that.val_);
252  if (a == nullptr) return b == nullptr;
253  if (b == nullptr) return false;
254  return *a == *b;
255  }
256 
257  /**
258  * Checks whether two handles are different.
259  * Returns true if only one of the handles is empty, or if
260  * the objects to which they refer are different.
261  *
262  * If both handles refer to JS objects, this is the same as strict
263  * non-equality. For primitives, such as numbers or strings, a `true` return
264  * value does not indicate that the values aren't equal in the JavaScript
265  * sense. Use `Value::StrictEquals()` to check primitives for equality.
266  */
267  template <class S>
268  V8_INLINE bool operator!=(const Local<S>& that) const {
269  return !operator==(that);
270  }
271 
272  template <class S> V8_INLINE bool operator!=(
273  const Persistent<S>& that) const {
274  return !operator==(that);
275  }
276 
277  /**
278  * Cast a handle to a subclass, e.g. Local<Value> to Local<Object>.
279  * This is only valid if the handle actually refers to a value of the
280  * target type.
281  */
282  template <class S> V8_INLINE static Local<T> Cast(Local<S> that) {
283 #ifdef V8_ENABLE_CHECKS
284  // If we're going to perform the type check then we have to check
285  // that the handle isn't empty before doing the checked cast.
286  if (that.IsEmpty()) return Local<T>();
287 #endif
288  return Local<T>(T::Cast(*that));
289  }
290 
291  /**
292  * Calling this is equivalent to Local<S>::Cast().
293  * In particular, this is only valid if the handle actually refers to a value
294  * of the target type.
295  */
296  template <class S>
297  V8_INLINE Local<S> As() const {
298  return Local<S>::Cast(*this);
299  }
300 
301  /**
302  * Create a local handle for the content of another handle.
303  * The referee is kept alive by the local handle even when
304  * the original handle is destroyed/disposed.
305  */
306  V8_INLINE static Local<T> New(Isolate* isolate, Local<T> that);
307  V8_INLINE static Local<T> New(Isolate* isolate,
308  const PersistentBase<T>& that);
309  V8_INLINE static Local<T> New(Isolate* isolate,
310  const BasicTracedReference<T>& that);
311 
312  private:
313  friend class TracedReferenceBase;
314  friend class Utils;
315  template<class F> friend class Eternal;
316  template<class F> friend class PersistentBase;
317  template<class F, class M> friend class Persistent;
318  template<class F> friend class Local;
319  template <class F>
320  friend class MaybeLocal;
321  template<class F> friend class FunctionCallbackInfo;
322  template<class F> friend class PropertyCallbackInfo;
323  friend class String;
324  friend class Object;
325  friend class Context;
326  friend class Isolate;
327  friend class Private;
328  template<class F> friend class internal::CustomArguments;
329  friend Local<Primitive> Undefined(Isolate* isolate);
330  friend Local<Primitive> Null(Isolate* isolate);
331  friend Local<Boolean> True(Isolate* isolate);
332  friend Local<Boolean> False(Isolate* isolate);
333  friend class HandleScope;
334  friend class EscapableHandleScope;
335  template <class F1, class F2, class F3>
337  template<class F1, class F2> friend class PersistentValueVector;
338  template <class F>
339  friend class ReturnValue;
340  template <class F>
341  friend class Traced;
342  template <class F>
343  friend class TracedGlobal;
344  template <class F>
345  friend class BasicTracedReference;
346  template <class F>
347  friend class TracedReference;
348 
349  explicit V8_INLINE Local(T* that) : val_(that) {}
350  V8_INLINE static Local<T> New(Isolate* isolate, T* that);
351  T* val_;
352 };
353 
354 
355 #if !defined(V8_IMMINENT_DEPRECATION_WARNINGS)
356 // Handle is an alias for Local for historical reasons.
357 template <class T>
358 using Handle = Local<T>;
359 #endif
360 
361 
362 /**
363  * A MaybeLocal<> is a wrapper around Local<> that enforces a check whether
364  * the Local<> is empty before it can be used.
365  *
366  * If an API method returns a MaybeLocal<>, the API method can potentially fail
367  * either because an exception is thrown, or because an exception is pending,
368  * e.g. because a previous API call threw an exception that hasn't been caught
369  * yet, or because a TerminateExecution exception was thrown. In that case, an
370  * empty MaybeLocal is returned.
371  */
372 template <class T>
373 class MaybeLocal {
374  public:
375  V8_INLINE MaybeLocal() : val_(nullptr) {}
376  template <class S>
378  : val_(reinterpret_cast<T*>(*that)) {
379  static_assert(std::is_base_of<T, S>::value, "type check");
380  }
381 
382  V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
383 
384  /**
385  * Converts this MaybeLocal<> to a Local<>. If this MaybeLocal<> is empty,
386  * |false| is returned and |out| is left untouched.
387  */
388  template <class S>
390  out->val_ = IsEmpty() ? nullptr : this->val_;
391  return !IsEmpty();
392  }
393 
394  /**
395  * Converts this MaybeLocal<> to a Local<>. If this MaybeLocal<> is empty,
396  * V8 will crash the process.
397  */
399 
400  /**
401  * Converts this MaybeLocal<> to a Local<>, using a default value if this
402  * MaybeLocal<> is empty.
403  */
404  template <class S>
405  V8_INLINE Local<S> FromMaybe(Local<S> default_value) const {
406  return IsEmpty() ? default_value : Local<S>(val_);
407  }
408 
409  private:
410  T* val_;
411 };
412 
413 /**
414  * Eternal handles are set-once handles that live for the lifetime of the
415  * isolate.
416  */
417 template <class T> class Eternal {
418  public:
419  V8_INLINE Eternal() : val_(nullptr) {}
420  template <class S>
421  V8_INLINE Eternal(Isolate* isolate, Local<S> handle) : val_(nullptr) {
422  Set(isolate, handle);
423  }
424  // Can only be safely called if already set.
425  V8_INLINE Local<T> Get(Isolate* isolate) const;
426  V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
427  template<class S> V8_INLINE void Set(Isolate* isolate, Local<S> handle);
428 
429  private:
430  T* val_;
431 };
432 
433 
434 static const int kInternalFieldsInWeakCallback = 2;
435 static const int kEmbedderFieldsInWeakCallback = 2;
436 
437 template <typename T>
439  public:
440  using Callback = void (*)(const WeakCallbackInfo<T>& data);
441 
442  WeakCallbackInfo(Isolate* isolate, T* parameter,
443  void* embedder_fields[kEmbedderFieldsInWeakCallback],
444  Callback* callback)
445  : isolate_(isolate), parameter_(parameter), callback_(callback) {
446  for (int i = 0; i < kEmbedderFieldsInWeakCallback; ++i) {
447  embedder_fields_[i] = embedder_fields[i];
448  }
449  }
450 
451  V8_INLINE Isolate* GetIsolate() const { return isolate_; }
452  V8_INLINE T* GetParameter() const { return parameter_; }
453  V8_INLINE void* GetInternalField(int index) const;
454 
455  // When first called, the embedder MUST Reset() the Global which triggered the
456  // callback. The Global itself is unusable for anything else. No v8 other api
457  // calls may be called in the first callback. Should additional work be
458  // required, the embedder must set a second pass callback, which will be
459  // called after all the initial callbacks are processed.
460  // Calling SetSecondPassCallback on the second pass will immediately crash.
461  void SetSecondPassCallback(Callback callback) const { *callback_ = callback; }
462 
463  private:
464  Isolate* isolate_;
465  T* parameter_;
466  Callback* callback_;
467  void* embedder_fields_[kEmbedderFieldsInWeakCallback];
468 };
469 
470 
471 // kParameter will pass a void* parameter back to the callback, kInternalFields
472 // will pass the first two internal fields back to the callback, kFinalizer
473 // will pass a void* parameter back, but is invoked before the object is
474 // actually collected, so it can be resurrected. In the last case, it is not
475 // possible to request a second pass callback.
477 
478 /**
479  * An object reference that is independent of any handle scope. Where
480  * a Local handle only lives as long as the HandleScope in which it was
481  * allocated, a PersistentBase handle remains valid until it is explicitly
482  * disposed using Reset().
483  *
484  * A persistent handle contains a reference to a storage cell within
485  * the V8 engine which holds an object value and which is updated by
486  * the garbage collector whenever the object is moved. A new storage
487  * cell can be created using the constructor or PersistentBase::Reset and
488  * existing handles can be disposed using PersistentBase::Reset.
489  *
490  */
491 template <class T> class PersistentBase {
492  public:
493  /**
494  * If non-empty, destroy the underlying storage cell
495  * IsEmpty() will return true after this call.
496  */
497  V8_INLINE void Reset();
498  /**
499  * If non-empty, destroy the underlying storage cell
500  * and create a new one with the contents of other if other is non empty
501  */
502  template <class S>
503  V8_INLINE void Reset(Isolate* isolate, const Local<S>& other);
504 
505  /**
506  * If non-empty, destroy the underlying storage cell
507  * and create a new one with the contents of other if other is non empty
508  */
509  template <class S>
510  V8_INLINE void Reset(Isolate* isolate, const PersistentBase<S>& other);
511 
512  V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
513  V8_INLINE void Empty() { val_ = 0; }
514 
515  V8_INLINE Local<T> Get(Isolate* isolate) const {
516  return Local<T>::New(isolate, *this);
517  }
518 
519  template <class S>
520  V8_INLINE bool operator==(const PersistentBase<S>& that) const {
521  internal::Address* a = reinterpret_cast<internal::Address*>(this->val_);
522  internal::Address* b = reinterpret_cast<internal::Address*>(that.val_);
523  if (a == nullptr) return b == nullptr;
524  if (b == nullptr) return false;
525  return *a == *b;
526  }
527 
528  template <class S>
529  V8_INLINE bool operator==(const Local<S>& that) const {
530  internal::Address* a = reinterpret_cast<internal::Address*>(this->val_);
531  internal::Address* b = reinterpret_cast<internal::Address*>(that.val_);
532  if (a == nullptr) return b == nullptr;
533  if (b == nullptr) return false;
534  return *a == *b;
535  }
536 
537  template <class S>
538  V8_INLINE bool operator!=(const PersistentBase<S>& that) const {
539  return !operator==(that);
540  }
541 
542  template <class S>
543  V8_INLINE bool operator!=(const Local<S>& that) const {
544  return !operator==(that);
545  }
546 
547  /**
548  * Install a finalization callback on this object.
549  * NOTE: There is no guarantee as to *when* or even *if* the callback is
550  * invoked. The invocation is performed solely on a best effort basis.
551  * As always, GC-based finalization should *not* be relied upon for any
552  * critical form of resource management!
553  *
554  * The callback is supposed to reset the handle. No further V8 API may be
555  * called in this callback. In case additional work involving V8 needs to be
556  * done, a second callback can be scheduled using
557  * WeakCallbackInfo<void>::SetSecondPassCallback.
558  */
559  template <typename P>
560  V8_INLINE void SetWeak(P* parameter,
561  typename WeakCallbackInfo<P>::Callback callback,
562  WeakCallbackType type);
563 
564  /**
565  * Turns this handle into a weak phantom handle without finalization callback.
566  * The handle will be reset automatically when the garbage collector detects
567  * that the object is no longer reachable.
568  * A related function Isolate::NumberOfPhantomHandleResetsSinceLastCall
569  * returns how many phantom handles were reset by the garbage collector.
570  */
571  V8_INLINE void SetWeak();
572 
573  template<typename P>
575 
576  // TODO(dcarney): remove this.
577  V8_INLINE void ClearWeak() { ClearWeak<void>(); }
578 
579  /**
580  * Annotates the strong handle with the given label, which is then used by the
581  * heap snapshot generator as a name of the edge from the root to the handle.
582  * The function does not take ownership of the label and assumes that the
583  * label is valid as long as the handle is valid.
584  */
585  V8_INLINE void AnnotateStrongRetainer(const char* label);
586 
587  /** Returns true if the handle's reference is weak. */
588  V8_INLINE bool IsWeak() const;
589 
590  /**
591  * Assigns a wrapper class ID to the handle.
592  */
593  V8_INLINE void SetWrapperClassId(uint16_t class_id);
594 
595  /**
596  * Returns the class ID previously assigned to this handle or 0 if no class ID
597  * was previously assigned.
598  */
599  V8_INLINE uint16_t WrapperClassId() const;
600 
601  PersistentBase(const PersistentBase& other) = delete;
602  void operator=(const PersistentBase&) = delete;
603 
604  private:
605  friend class Isolate;
606  friend class Utils;
607  template<class F> friend class Local;
608  template<class F1, class F2> friend class Persistent;
609  template <class F>
610  friend class Global;
611  template<class F> friend class PersistentBase;
612  template<class F> friend class ReturnValue;
613  template <class F1, class F2, class F3>
615  template<class F1, class F2> friend class PersistentValueVector;
616  friend class Object;
617 
618  explicit V8_INLINE PersistentBase(T* val) : val_(val) {}
619  V8_INLINE static T* New(Isolate* isolate, T* that);
620 
621  T* val_;
622 };
623 
624 
625 /**
626  * Default traits for Persistent. This class does not allow
627  * use of the copy constructor or assignment operator.
628  * At present kResetInDestructor is not set, but that will change in a future
629  * version.
630  */
631 template<class T>
632 class NonCopyablePersistentTraits {
633  public:
634  using NonCopyablePersistent = Persistent<T, NonCopyablePersistentTraits<T>>;
635  static const bool kResetInDestructor = false;
636  template<class S, class M>
637  V8_INLINE static void Copy(const Persistent<S, M>& source,
638  NonCopyablePersistent* dest) {
639  static_assert(sizeof(S) < 0,
640  "NonCopyablePersistentTraits::Copy is not instantiable");
641  }
642 };
643 
644 
645 /**
646  * Helper class traits to allow copying and assignment of Persistent.
647  * This will clone the contents of storage cell, but not any of the flags, etc.
648  */
649 template<class T>
651  using CopyablePersistent = Persistent<T, CopyablePersistentTraits<T>>;
652  static const bool kResetInDestructor = true;
653  template<class S, class M>
654  static V8_INLINE void Copy(const Persistent<S, M>& source,
655  CopyablePersistent* dest) {
656  // do nothing, just allow copy
657  }
658 };
659 
660 
661 /**
662  * A PersistentBase which allows copy and assignment.
663  *
664  * Copy, assignment and destructor behavior is controlled by the traits
665  * class M.
666  *
667  * Note: Persistent class hierarchy is subject to future changes.
668  */
669 template <class T, class M> class Persistent : public PersistentBase<T> {
670  public:
671  /**
672  * A Persistent with no storage cell.
673  */
675  /**
676  * Construct a Persistent from a Local.
677  * When the Local is non-empty, a new storage cell is created
678  * pointing to the same object, and no flags are set.
679  */
680  template <class S>
681  V8_INLINE Persistent(Isolate* isolate, Local<S> that)
682  : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
683  static_assert(std::is_base_of<T, S>::value, "type check");
684  }
685  /**
686  * Construct a Persistent from a Persistent.
687  * When the Persistent is non-empty, a new storage cell is created
688  * pointing to the same object, and no flags are set.
689  */
690  template <class S, class M2>
691  V8_INLINE Persistent(Isolate* isolate, const Persistent<S, M2>& that)
692  : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
693  static_assert(std::is_base_of<T, S>::value, "type check");
694  }
695  /**
696  * The copy constructors and assignment operator create a Persistent
697  * exactly as the Persistent constructor, but the Copy function from the
698  * traits class is called, allowing the setting of flags based on the
699  * copied Persistent.
700  */
701  V8_INLINE Persistent(const Persistent& that) : PersistentBase<T>(nullptr) {
702  Copy(that);
703  }
704  template <class S, class M2>
705  V8_INLINE Persistent(const Persistent<S, M2>& that) : PersistentBase<T>(0) {
706  Copy(that);
707  }
709  Copy(that);
710  return *this;
711  }
712  template <class S, class M2>
713  V8_INLINE Persistent& operator=(const Persistent<S, M2>& that) {
714  Copy(that);
715  return *this;
716  }
717  /**
718  * The destructor will dispose the Persistent based on the
719  * kResetInDestructor flags in the traits class. Since not calling dispose
720  * can result in a memory leak, it is recommended to always set this flag.
721  */
723  if (M::kResetInDestructor) this->Reset();
724  }
725 
726  // TODO(dcarney): this is pretty useless, fix or remove
727  template <class S>
728  V8_INLINE static Persistent<T>& Cast(const Persistent<S>& that) {
729 #ifdef V8_ENABLE_CHECKS
730  // If we're going to perform the type check then we have to check
731  // that the handle isn't empty before doing the checked cast.
732  if (!that.IsEmpty()) T::Cast(*that);
733 #endif
734  return reinterpret_cast<Persistent<T>&>(const_cast<Persistent<S>&>(that));
735  }
736 
737  // TODO(dcarney): this is pretty useless, fix or remove
738  template <class S>
739  V8_INLINE Persistent<S>& As() const {
740  return Persistent<S>::Cast(*this);
741  }
742 
743  private:
744  friend class Isolate;
745  friend class Utils;
746  template<class F> friend class Local;
747  template<class F1, class F2> friend class Persistent;
748  template<class F> friend class ReturnValue;
749 
750  explicit V8_INLINE Persistent(T* that) : PersistentBase<T>(that) {}
751  V8_INLINE T* operator*() const { return this->val_; }
752  template<class S, class M2>
753  V8_INLINE void Copy(const Persistent<S, M2>& that);
754 };
755 
756 
757 /**
758  * A PersistentBase which has move semantics.
759  *
760  * Note: Persistent class hierarchy is subject to future changes.
761  */
762 template <class T>
763 class Global : public PersistentBase<T> {
764  public:
765  /**
766  * A Global with no storage cell.
767  */
768  V8_INLINE Global() : PersistentBase<T>(nullptr) {}
769 
770  /**
771  * Construct a Global from a Local.
772  * When the Local is non-empty, a new storage cell is created
773  * pointing to the same object, and no flags are set.
774  */
775  template <class S>
776  V8_INLINE Global(Isolate* isolate, Local<S> that)
777  : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
778  static_assert(std::is_base_of<T, S>::value, "type check");
779  }
780 
781  /**
782  * Construct a Global from a PersistentBase.
783  * When the Persistent is non-empty, a new storage cell is created
784  * pointing to the same object, and no flags are set.
785  */
786  template <class S>
787  V8_INLINE Global(Isolate* isolate, const PersistentBase<S>& that)
788  : PersistentBase<T>(PersistentBase<T>::New(isolate, that.val_)) {
789  static_assert(std::is_base_of<T, S>::value, "type check");
790  }
791 
792  /**
793  * Move constructor.
794  */
795  V8_INLINE Global(Global&& other);
796 
797  V8_INLINE ~Global() { this->Reset(); }
798 
799  /**
800  * Move via assignment.
801  */
802  template <class S>
804 
805  /**
806  * Pass allows returning uniques from functions, etc.
807  */
808  Global Pass() { return static_cast<Global&&>(*this); }
809 
810  /*
811  * For compatibility with Chromium's base::Bind (base::Passed).
812  */
813  using MoveOnlyTypeForCPP03 = void;
814 
815  Global(const Global&) = delete;
816  void operator=(const Global&) = delete;
817 
818  private:
819  template <class F>
820  friend class ReturnValue;
821  V8_INLINE T* operator*() const { return this->val_; }
822 };
823 
824 
825 // UniquePersistent is an alias for Global for historical reason.
826 template <class T>
827 using UniquePersistent = Global<T>;
828 
829 /**
830  * Deprecated. Use |TracedReference<T>| instead.
831  */
832 template <typename T>
834 
836  public:
837  /**
838  * Returns true if the reference is empty, i.e., has not been assigned
839  * object.
840  */
841  bool IsEmpty() const { return val_ == nullptr; }
842 
843  /**
844  * If non-empty, destroy the underlying storage cell. |IsEmpty| will return
845  * true after this call.
846  */
847  V8_INLINE void Reset();
848 
849  /**
850  * Construct a Local<Value> from this handle.
851  */
852  V8_INLINE v8::Local<v8::Value> Get(v8::Isolate* isolate) const;
853 
854  /**
855  * Returns true if this TracedReference is empty, i.e., has not been
856  * assigned an object. This version of IsEmpty is thread-safe.
857  */
858  bool IsEmptyThreadSafe() const {
859  return this->GetSlotThreadSafe() == nullptr;
860  }
861 
862  /**
863  * Assigns a wrapper class ID to the handle.
864  */
865  V8_INLINE void SetWrapperClassId(uint16_t class_id);
866 
867  /**
868  * Returns the class ID previously assigned to this handle or 0 if no class ID
869  * was previously assigned.
870  */
871  V8_INLINE uint16_t WrapperClassId() const;
872 
873  protected:
874  /**
875  * Update this reference in a thread-safe way.
876  */
877  void SetSlotThreadSafe(void* new_val) {
878  reinterpret_cast<std::atomic<void*>*>(&val_)->store(
879  new_val, std::memory_order_relaxed);
880  }
881 
882  /**
883  * Get this reference in a thread-safe way
884  */
885  const void* GetSlotThreadSafe() const {
886  return reinterpret_cast<std::atomic<const void*> const*>(&val_)->load(
887  std::memory_order_relaxed);
888  }
889 
890  V8_EXPORT void CheckValue() const;
891 
892  // val_ points to a GlobalHandles node.
893  internal::Address* val_ = nullptr;
894 
895  friend class internal::BasicTracedReferenceExtractor;
896  template <typename F>
897  friend class Local;
898  template <typename U>
899  friend bool operator==(const TracedReferenceBase&, const Local<U>&);
900  friend bool operator==(const TracedReferenceBase&,
901  const TracedReferenceBase&);
902 };
903 
904 /**
905  * A traced handle with copy and move semantics. The handle is to be used
906  * together with |v8::EmbedderHeapTracer| or as part of GarbageCollected objects
907  * (see v8-cppgc.h) and specifies edges from C++ objects to JavaScript.
908  *
909  * The exact semantics are:
910  * - Tracing garbage collections use |v8::EmbedderHeapTracer| or cppgc.
911  * - Non-tracing garbage collections refer to
912  * |v8::EmbedderRootsHandler::IsRoot()| whether the handle should
913  * be treated as root or not.
914  *
915  * Note that the base class cannot be instantiated itself. Choose from
916  * - TracedGlobal
917  * - TracedReference
918  */
919 template <typename T>
921  public:
922  /**
923  * Construct a Local<T> from this handle.
924  */
925  Local<T> Get(Isolate* isolate) const { return Local<T>::New(isolate, *this); }
926 
927  template <class S>
929  return reinterpret_cast<BasicTracedReference<S>&>(
930  const_cast<BasicTracedReference<T>&>(*this));
931  }
932 
933  T* operator->() const {
934 #ifdef V8_ENABLE_CHECKS
935  CheckValue();
936 #endif // V8_ENABLE_CHECKS
937  return reinterpret_cast<T*>(val_);
938  }
939  T* operator*() const {
940 #ifdef V8_ENABLE_CHECKS
941  CheckValue();
942 #endif // V8_ENABLE_CHECKS
943  return reinterpret_cast<T*>(val_);
944  }
945 
946  private:
947  enum DestructionMode { kWithDestructor, kWithoutDestructor };
948 
949  /**
950  * An empty BasicTracedReference without storage cell.
951  */
952  BasicTracedReference() = default;
953 
954  V8_INLINE static internal::Address* New(Isolate* isolate, T* that, void* slot,
955  DestructionMode destruction_mode);
956 
957  friend class EmbedderHeapTracer;
958  template <typename F>
959  friend class Local;
960  friend class Object;
961  template <typename F>
962  friend class TracedGlobal;
963  template <typename F>
964  friend class TracedReference;
965  template <typename F>
966  friend class BasicTracedReference;
967  template <typename F>
968  friend class ReturnValue;
969 };
970 
971 /**
972  * A traced handle with destructor that clears the handle. For more details see
973  * BasicTracedReference.
974  */
975 template <typename T>
977  public:
978  using BasicTracedReference<T>::Reset;
979 
980  /**
981  * Destructor resetting the handle.Is
982  */
983  ~TracedGlobal() { this->Reset(); }
984 
985  /**
986  * An empty TracedGlobal without storage cell.
987  */
989 
990  /**
991  * Construct a TracedGlobal from a Local.
992  *
993  * When the Local is non-empty, a new storage cell is created
994  * pointing to the same object.
995  */
996  template <class S>
997  TracedGlobal(Isolate* isolate, Local<S> that) : BasicTracedReference<T>() {
998  this->val_ = this->New(isolate, that.val_, &this->val_,
999  BasicTracedReference<T>::kWithDestructor);
1000  static_assert(std::is_base_of<T, S>::value, "type check");
1001  }
1002 
1003  /**
1004  * Move constructor initializing TracedGlobal from an existing one.
1005  */
1007  // Forward to operator=.
1008  *this = std::move(other);
1009  }
1010 
1011  /**
1012  * Move constructor initializing TracedGlobal from an existing one.
1013  */
1014  template <typename S>
1016  // Forward to operator=.
1017  *this = std::move(other);
1018  }
1019 
1020  /**
1021  * Copy constructor initializing TracedGlobal from an existing one.
1022  */
1024  // Forward to operator=;
1025  *this = other;
1026  }
1027 
1028  /**
1029  * Copy constructor initializing TracedGlobal from an existing one.
1030  */
1031  template <typename S>
1033  // Forward to operator=;
1034  *this = other;
1035  }
1036 
1037  /**
1038  * Move assignment operator initializing TracedGlobal from an existing one.
1039  */
1041 
1042  /**
1043  * Move assignment operator initializing TracedGlobal from an existing one.
1044  */
1045  template <class S>
1047 
1048  /**
1049  * Copy assignment operator initializing TracedGlobal from an existing one.
1050  *
1051  * Note: Prohibited when |other| has a finalization callback set through
1052  * |SetFinalizationCallback|.
1053  */
1055 
1056  /**
1057  * Copy assignment operator initializing TracedGlobal from an existing one.
1058  *
1059  * Note: Prohibited when |other| has a finalization callback set through
1060  * |SetFinalizationCallback|.
1061  */
1062  template <class S>
1064 
1065  /**
1066  * If non-empty, destroy the underlying storage cell and create a new one with
1067  * the contents of other if other is non empty
1068  */
1069  template <class S>
1070  V8_INLINE void Reset(Isolate* isolate, const Local<S>& other);
1071 
1072  template <class S>
1073  V8_INLINE TracedGlobal<S>& As() const {
1074  return reinterpret_cast<TracedGlobal<S>&>(
1075  const_cast<TracedGlobal<T>&>(*this));
1076  }
1077 
1078  /**
1079  * Adds a finalization callback to the handle. The type of this callback is
1080  * similar to WeakCallbackType::kInternalFields, i.e., it will pass the
1081  * parameter and the first two internal fields of the object.
1082  *
1083  * The callback is then supposed to reset the handle in the callback. No
1084  * further V8 API may be called in this callback. In case additional work
1085  * involving V8 needs to be done, a second callback can be scheduled using
1086  * WeakCallbackInfo<void>::SetSecondPassCallback.
1087  */
1089  void* parameter, WeakCallbackInfo<void>::Callback callback);
1090 };
1091 
1092 /**
1093  * A traced handle without destructor that clears the handle. The embedder needs
1094  * to ensure that the handle is not accessed once the V8 object has been
1095  * reclaimed. This can happen when the handle is not passed through the
1096  * EmbedderHeapTracer. For more details see BasicTracedReference.
1097  *
1098  * The reference assumes the embedder has precise knowledge about references at
1099  * all times. In case V8 needs to separately handle on-stack references, the
1100  * embedder is required to set the stack start through
1101  * |EmbedderHeapTracer::SetStackStart|.
1102  */
1103 template <typename T>
1105  public:
1106  using BasicTracedReference<T>::Reset;
1107 
1108  /**
1109  * An empty TracedReference without storage cell.
1110  */
1112 
1113  /**
1114  * Construct a TracedReference from a Local.
1115  *
1116  * When the Local is non-empty, a new storage cell is created
1117  * pointing to the same object.
1118  */
1119  template <class S>
1121  this->val_ = this->New(isolate, that.val_, &this->val_,
1122  BasicTracedReference<T>::kWithoutDestructor);
1123  static_assert(std::is_base_of<T, S>::value, "type check");
1124  }
1125 
1126  /**
1127  * Move constructor initializing TracedReference from an
1128  * existing one.
1129  */
1131  // Forward to operator=.
1132  *this = std::move(other);
1133  }
1134 
1135  /**
1136  * Move constructor initializing TracedReference from an
1137  * existing one.
1138  */
1139  template <typename S>
1141  // Forward to operator=.
1142  *this = std::move(other);
1143  }
1144 
1145  /**
1146  * Copy constructor initializing TracedReference from an
1147  * existing one.
1148  */
1150  // Forward to operator=;
1151  *this = other;
1152  }
1153 
1154  /**
1155  * Copy constructor initializing TracedReference from an
1156  * existing one.
1157  */
1158  template <typename S>
1160  // Forward to operator=;
1161  *this = other;
1162  }
1163 
1164  /**
1165  * Move assignment operator initializing TracedGlobal from an existing one.
1166  */
1168 
1169  /**
1170  * Move assignment operator initializing TracedGlobal from an existing one.
1171  */
1172  template <class S>
1174 
1175  /**
1176  * Copy assignment operator initializing TracedGlobal from an existing one.
1177  */
1179 
1180  /**
1181  * Copy assignment operator initializing TracedGlobal from an existing one.
1182  */
1183  template <class S>
1185 
1186  /**
1187  * If non-empty, destroy the underlying storage cell and create a new one with
1188  * the contents of other if other is non empty
1189  */
1190  template <class S>
1191  V8_INLINE void Reset(Isolate* isolate, const Local<S>& other);
1192 
1193  template <class S>
1195  return reinterpret_cast<TracedReference<S>&>(
1196  const_cast<TracedReference<T>&>(*this));
1197  }
1198 };
1199 
1200  /**
1201  * A stack-allocated class that governs a number of local handles.
1202  * After a handle scope has been created, all local handles will be
1203  * allocated within that handle scope until either the handle scope is
1204  * deleted or another handle scope is created. If there is already a
1205  * handle scope and a new one is created, all allocations will take
1206  * place in the new handle scope until it is deleted. After that,
1207  * new handles will again be allocated in the original handle scope.
1208  *
1209  * After the handle scope of a local handle has been deleted the
1210  * garbage collector will no longer track the object stored in the
1211  * handle and may deallocate it. The behavior of accessing a handle
1212  * for which the handle scope has been deleted is undefined.
1213  */
1215  public:
1216  explicit HandleScope(Isolate* isolate);
1217 
1219 
1220  /**
1221  * Counts the number of allocated handles.
1222  */
1223  static int NumberOfHandles(Isolate* isolate);
1224 
1226  return reinterpret_cast<Isolate*>(isolate_);
1227  }
1228 
1229  HandleScope(const HandleScope&) = delete;
1230  void operator=(const HandleScope&) = delete;
1231 
1232  protected:
1233  V8_INLINE HandleScope() = default;
1234 
1235  void Initialize(Isolate* isolate);
1236 
1237  static internal::Address* CreateHandle(internal::Isolate* isolate,
1238  internal::Address value);
1239 
1240  private:
1241  // Declaring operator new and delete as deleted is not spec compliant.
1242  // Therefore declare them private instead to disable dynamic alloc
1243  void* operator new(size_t size);
1244  void* operator new[](size_t size);
1245  void operator delete(void*, size_t);
1246  void operator delete[](void*, size_t);
1247 
1248  internal::Isolate* isolate_;
1249  internal::Address* prev_next_;
1250  internal::Address* prev_limit_;
1251 
1252  // Local::New uses CreateHandle with an Isolate* parameter.
1253  template<class F> friend class Local;
1254 
1255  // Object::GetInternalField and Context::GetEmbedderData use CreateHandle with
1256  // a HeapObject in their shortcuts.
1257  friend class Object;
1258  friend class Context;
1259 };
1260 
1261 /**
1262  * A HandleScope which first allocates a handle in the current scope
1263  * which will be later filled with the escape value.
1264  */
1266  public:
1267  explicit EscapableHandleScope(Isolate* isolate);
1269 
1270  /**
1271  * Pushes the value into the previous scope and returns a handle to it.
1272  * Cannot be called twice.
1273  */
1274  template <class T>
1275  V8_INLINE Local<T> Escape(Local<T> value) {
1276  internal::Address* slot =
1277  Escape(reinterpret_cast<internal::Address*>(*value));
1278  return Local<T>(reinterpret_cast<T*>(slot));
1279  }
1280 
1281  template <class T>
1283  return Escape(value.FromMaybe(Local<T>()));
1284  }
1285 
1287  void operator=(const EscapableHandleScope&) = delete;
1288 
1289  private:
1290  // Declaring operator new and delete as deleted is not spec compliant.
1291  // Therefore declare them private instead to disable dynamic alloc
1292  void* operator new(size_t size);
1293  void* operator new[](size_t size);
1294  void operator delete(void*, size_t);
1295  void operator delete[](void*, size_t);
1296 
1297  internal::Address* Escape(internal::Address* escape_value);
1298  internal::Address* escape_slot_;
1299 };
1300 
1301 /**
1302  * A SealHandleScope acts like a handle scope in which no handle allocations
1303  * are allowed. It can be useful for debugging handle leaks.
1304  * Handles can be allocated within inner normal HandleScopes.
1305  */
1307  public:
1308  explicit SealHandleScope(Isolate* isolate);
1310 
1312  void operator=(const SealHandleScope&) = delete;
1313 
1314  private:
1315  // Declaring operator new and delete as deleted is not spec compliant.
1316  // Therefore declare them private instead to disable dynamic alloc
1317  void* operator new(size_t size);
1318  void* operator new[](size_t size);
1319  void operator delete(void*, size_t);
1320  void operator delete[](void*, size_t);
1321 
1322  internal::Isolate* const isolate_;
1323  internal::Address* prev_limit_;
1324  int prev_sealed_level_;
1325 };
1326 
1327 // --- Special objects ---
1328 
1329 /**
1330  * The superclass of objects that can reside on V8's heap.
1331  */
1333  public:
1334  /**
1335  * Returns true if this data is a |v8::Value|.
1336  */
1337  bool IsValue() const;
1338 
1339  /**
1340  * Returns true if this data is a |v8::Module|.
1341  */
1342  bool IsModule() const;
1343 
1344  /**
1345  * Returns true if this data is a |v8::Private|.
1346  */
1347  bool IsPrivate() const;
1348 
1349  /**
1350  * Returns true if this data is a |v8::ObjectTemplate|.
1351  */
1352  bool IsObjectTemplate() const;
1353 
1354  /**
1355  * Returns true if this data is a |v8::FunctionTemplate|.
1356  */
1357  bool IsFunctionTemplate() const;
1358 
1359  /**
1360  * Returns true if this data is a |v8::Context|.
1361  */
1362  bool IsContext() const;
1363 
1364  private:
1365  Data();
1366 };
1367 
1368 /**
1369  * A container type that holds relevant metadata for module loading.
1370  *
1371  * This is passed back to the embedder as part of
1372  * HostImportModuleDynamicallyCallback for module loading.
1373  */
1375  public:
1376  /**
1377  * The name that was passed by the embedder as ResourceName to the
1378  * ScriptOrigin. This can be either a v8::String or v8::Undefined.
1379  */
1381 
1382  /**
1383  * The options that were passed by the embedder as HostDefinedOptions to
1384  * the ScriptOrigin.
1385  */
1387 };
1388 
1389 /**
1390  * An array to hold Primitive values. This is used by the embedder to
1391  * pass host defined options to the ScriptOptions during compilation.
1392  *
1393  * This is passed back to the embedder as part of
1394  * HostImportModuleDynamicallyCallback for module loading.
1395  *
1396  */
1398  public:
1399  static Local<PrimitiveArray> New(Isolate* isolate, int length);
1400  int Length() const;
1401  void Set(Isolate* isolate, int index, Local<Primitive> item);
1402  Local<Primitive> Get(Isolate* isolate, int index);
1403 };
1404 
1405 /**
1406  * The optional attributes of ScriptOrigin.
1407  */
1409  public:
1410  V8_INLINE ScriptOriginOptions(bool is_shared_cross_origin = false,
1411  bool is_opaque = false, bool is_wasm = false,
1412  bool is_module = false)
1413  : flags_((is_shared_cross_origin ? kIsSharedCrossOrigin : 0) |
1414  (is_wasm ? kIsWasm : 0) | (is_opaque ? kIsOpaque : 0) |
1415  (is_module ? kIsModule : 0)) {}
1417  : flags_(flags &
1418  (kIsSharedCrossOrigin | kIsOpaque | kIsWasm | kIsModule)) {}
1419 
1420  bool IsSharedCrossOrigin() const {
1421  return (flags_ & kIsSharedCrossOrigin) != 0;
1422  }
1423  bool IsOpaque() const { return (flags_ & kIsOpaque) != 0; }
1424  bool IsWasm() const { return (flags_ & kIsWasm) != 0; }
1425  bool IsModule() const { return (flags_ & kIsModule) != 0; }
1426 
1427  int Flags() const { return flags_; }
1428 
1429  private:
1430  enum {
1431  kIsSharedCrossOrigin = 1,
1432  kIsOpaque = 1 << 1,
1433  kIsWasm = 1 << 2,
1434  kIsModule = 1 << 3
1435  };
1436  const int flags_;
1437 };
1438 
1439 /**
1440  * The origin, within a file, of a script.
1441  */
1443  public:
1444  V8_DEPRECATED("Use constructor with primitive C++ types")
1445  V8_INLINE explicit ScriptOrigin(
1446  Local<Value> resource_name, Local<Integer> resource_line_offset,
1447  Local<Integer> resource_column_offset,
1448  Local<Boolean> resource_is_shared_cross_origin = Local<Boolean>(),
1449  Local<Integer> script_id = Local<Integer>(),
1450  Local<Value> source_map_url = Local<Value>(),
1451  Local<Boolean> resource_is_opaque = Local<Boolean>(),
1452  Local<Boolean> is_wasm = Local<Boolean>(),
1453  Local<Boolean> is_module = Local<Boolean>(),
1454  Local<PrimitiveArray> host_defined_options = Local<PrimitiveArray>());
1455  V8_DEPRECATED("Use constructor that takes an isolate")
1456  V8_INLINE explicit ScriptOrigin(
1457  Local<Value> resource_name, int resource_line_offset = 0,
1458  int resource_column_offset = 0,
1459  bool resource_is_shared_cross_origin = false, int script_id = -1,
1460  Local<Value> source_map_url = Local<Value>(),
1461  bool resource_is_opaque = false, bool is_wasm = false,
1462  bool is_module = false,
1463  Local<PrimitiveArray> host_defined_options = Local<PrimitiveArray>());
1464  V8_INLINE explicit ScriptOrigin(
1465  Isolate* isolate, Local<Value> resource_name,
1466  int resource_line_offset = 0, int resource_column_offset = 0,
1467  bool resource_is_shared_cross_origin = false, int script_id = -1,
1468  Local<Value> source_map_url = Local<Value>(),
1469  bool resource_is_opaque = false, bool is_wasm = false,
1470  bool is_module = false,
1471  Local<PrimitiveArray> host_defined_options = Local<PrimitiveArray>());
1472 
1473  V8_INLINE Local<Value> ResourceName() const;
1474  V8_DEPRECATED("Use getter with primitvie C++ types.")
1476  V8_DEPRECATED("Use getter with primitvie C++ types.")
1478  V8_DEPRECATED("Use getter with primitvie C++ types.")
1479  V8_INLINE Local<Integer> ScriptID() const;
1480  V8_INLINE int LineOffset() const;
1481  V8_INLINE int ColumnOffset() const;
1482  V8_INLINE int ScriptId() const;
1483  V8_INLINE Local<Value> SourceMapUrl() const;
1485  V8_INLINE ScriptOriginOptions Options() const { return options_; }
1486 
1487  private:
1488  Isolate* isolate_;
1489  Local<Value> resource_name_;
1490  int resource_line_offset_;
1491  int resource_column_offset_;
1492  ScriptOriginOptions options_;
1493  int script_id_;
1494  Local<Value> source_map_url_;
1495  Local<PrimitiveArray> host_defined_options_;
1496 };
1497 
1498 /**
1499  * A compiled JavaScript script, not yet tied to a Context.
1500  */
1502  public:
1503  /**
1504  * Binds the script to the currently entered context.
1505  */
1507 
1508  int GetId() const;
1510 
1511  /**
1512  * Data read from magic sourceURL comments.
1513  */
1515  /**
1516  * Data read from magic sourceMappingURL comments.
1517  */
1519 
1520  /**
1521  * Returns zero based line number of the code_pos location in the script.
1522  * -1 will be returned if no information available.
1523  */
1524  int GetLineNumber(int code_pos);
1525 
1526  static const int kNoScriptId = 0;
1527 };
1528 
1529 /**
1530  * A compiled JavaScript module, not yet tied to a Context.
1531  */
1533  // Only used as a container for code caching.
1534 };
1535 
1536 /**
1537  * A location in JavaScript source.
1538  */
1540  public:
1541  int GetLineNumber() { return line_number_; }
1542  int GetColumnNumber() { return column_number_; }
1543 
1544  Location(int line_number, int column_number)
1545  : line_number_(line_number), column_number_(column_number) {}
1546 
1547  private:
1548  int line_number_;
1549  int column_number_;
1550 };
1551 
1552 /**
1553  * A fixed-sized array with elements of type Data.
1554  */
1555 class V8_EXPORT FixedArray : public Data {
1556  public:
1557  int Length() const;
1558  Local<Data> Get(Local<Context> context, int i) const;
1559 };
1560 
1561 class V8_EXPORT ModuleRequest : public Data {
1562  public:
1563  /**
1564  * Returns the module specifier for this ModuleRequest.
1565  */
1567 
1568  /**
1569  * Returns the source code offset of this module request.
1570  * Use Module::SourceOffsetToLocation to convert this to line/column numbers.
1571  */
1572  int GetSourceOffset() const;
1573 
1574  /**
1575  * Contains the import assertions for this request in the form:
1576  * [key1, value1, source_offset1, key2, value2, source_offset2, ...].
1577  * The keys and values are of type v8::String, and the source offsets are of
1578  * type Int32. Use Module::SourceOffsetToLocation to convert the source
1579  * offsets to Locations with line/column numbers.
1580  *
1581  * All assertions present in the module request will be supplied in this
1582  * list, regardless of whether they are supported by the host. Per
1583  * https://tc39.es/proposal-import-assertions/#sec-hostgetsupportedimportassertions,
1584  * hosts are expected to ignore assertions that they do not support (as
1585  * opposed to, for example, triggering an error if an unsupported assertion is
1586  * present).
1587  */
1589 
1590  V8_INLINE static ModuleRequest* Cast(Data* data);
1591 
1592  private:
1593  static void CheckCast(Data* obj);
1594 };
1595 
1596 /**
1597  * A compiled JavaScript module.
1598  */
1599 class V8_EXPORT Module : public Data {
1600  public:
1601  /**
1602  * The different states a module can be in.
1603  *
1604  * This corresponds to the states used in ECMAScript except that "evaluated"
1605  * is split into kEvaluated and kErrored, indicating success and failure,
1606  * respectively.
1607  */
1608  enum Status {
1614  kErrored
1615  };
1616 
1617  /**
1618  * Returns the module's current status.
1619  */
1621 
1622  /**
1623  * For a module in kErrored status, this returns the corresponding exception.
1624  */
1626 
1627  /**
1628  * Returns the number of modules requested by this module.
1629  */
1630  V8_DEPRECATED("Use Module::GetModuleRequests() and FixedArray::Length().")
1631  int GetModuleRequestsLength() const;
1632 
1633  /**
1634  * Returns the ith module specifier in this module.
1635  * i must be < GetModuleRequestsLength() and >= 0.
1636  */
1638  "Use Module::GetModuleRequests() and ModuleRequest::GetSpecifier().")
1639  Local<String> GetModuleRequest(int i) const;
1640 
1641  /**
1642  * Returns the source location (line number and column number) of the ith
1643  * module specifier's first occurrence in this module.
1644  */
1646  "Use Module::GetModuleRequests(), ModuleRequest::GetSourceOffset(), and "
1647  "Module::SourceOffsetToLocation().")
1648  Location GetModuleRequestLocation(int i) const;
1649 
1650  /**
1651  * Returns the ModuleRequests for this module.
1652  */
1654 
1655  /**
1656  * For the given source text offset in this module, returns the corresponding
1657  * Location with line and column numbers.
1658  */
1660 
1661  /**
1662  * Returns the identity hash for this object.
1663  */
1664  int GetIdentityHash() const;
1665 
1666  using ResolveCallback V8_DEPRECATED("Use ResolveModuleCallback") =
1667  MaybeLocal<Module> (*)(Local<Context> context, Local<String> specifier,
1668  Local<Module> referrer);
1669  using ResolveModuleCallback = MaybeLocal<Module> (*)(
1670  Local<Context> context, Local<String> specifier,
1671  Local<FixedArray> import_assertions, Local<Module> referrer);
1672 
1673  /**
1674  * Instantiates the module and its dependencies.
1675  *
1676  * Returns an empty Maybe<bool> if an exception occurred during
1677  * instantiation. (In the case where the callback throws an exception, that
1678  * exception is propagated.)
1679  */
1681  "Use the version of InstantiateModule that takes a ResolveModuleCallback "
1682  "parameter")
1683  V8_WARN_UNUSED_RESULT Maybe<bool> InstantiateModule(Local<Context> context,
1684  ResolveCallback callback);
1686  Local<Context> context, ResolveModuleCallback callback);
1687 
1688  /**
1689  * Evaluates the module and its dependencies.
1690  *
1691  * If status is kInstantiated, run the module's code and return a Promise
1692  * object. On success, set status to kEvaluated and resolve the Promise with
1693  * the completion value; on failure, set status to kErrored and reject the
1694  * Promise with the error.
1695  *
1696  * If IsGraphAsync() is false, the returned Promise is settled.
1697  */
1699 
1700  /**
1701  * Returns the namespace object of this module.
1702  *
1703  * The module's status must be at least kInstantiated.
1704  */
1706 
1707  /**
1708  * Returns the corresponding context-unbound module script.
1709  *
1710  * The module must be unevaluated, i.e. its status must not be kEvaluating,
1711  * kEvaluated or kErrored.
1712  */
1714 
1715  /**
1716  * Returns the underlying script's id.
1717  *
1718  * The module must be a SourceTextModule and must not have a kErrored status.
1719  */
1720  int ScriptId() const;
1721 
1722  /**
1723  * Returns whether this module or any of its requested modules is async,
1724  * i.e. contains top-level await.
1725  *
1726  * The module's status must be at least kInstantiated.
1727  */
1728  bool IsGraphAsync() const;
1729 
1730  /**
1731  * Returns whether the module is a SourceTextModule.
1732  */
1733  bool IsSourceTextModule() const;
1734 
1735  /**
1736  * Returns whether the module is a SyntheticModule.
1737  */
1738  bool IsSyntheticModule() const;
1739 
1740  /*
1741  * Callback defined in the embedder. This is responsible for setting
1742  * the module's exported values with calls to SetSyntheticModuleExport().
1743  * The callback must return a resolved Promise to indicate success (where no
1744  * exception was thrown) and return an empy MaybeLocal to indicate falure
1745  * (where an exception was thrown).
1746  */
1747  using SyntheticModuleEvaluationSteps =
1748  MaybeLocal<Value> (*)(Local<Context> context, Local<Module> module);
1749 
1750  /**
1751  * Creates a new SyntheticModule with the specified export names, where
1752  * evaluation_steps will be executed upon module evaluation.
1753  * export_names must not contain duplicates.
1754  * module_name is used solely for logging/debugging and doesn't affect module
1755  * behavior.
1756  */
1758  Isolate* isolate, Local<String> module_name,
1759  const std::vector<Local<String>>& export_names,
1760  SyntheticModuleEvaluationSteps evaluation_steps);
1761 
1762  /**
1763  * Set this module's exported value for the name export_name to the specified
1764  * export_value. This method must be called only on Modules created via
1765  * CreateSyntheticModule. An error will be thrown if export_name is not one
1766  * of the export_names that were passed in that CreateSyntheticModule call.
1767  * Returns Just(true) on success, Nothing<bool>() if an error was thrown.
1768  */
1770  Isolate* isolate, Local<String> export_name, Local<Value> export_value);
1771 
1772  V8_INLINE static Module* Cast(Data* data);
1773 
1774  private:
1775  static void CheckCast(Data* obj);
1776 };
1777 
1778 /**
1779  * A compiled JavaScript script, tied to a Context which was active when the
1780  * script was compiled.
1781  */
1783  public:
1784  /**
1785  * A shorthand for ScriptCompiler::Compile().
1786  */
1788  Local<Context> context, Local<String> source,
1789  ScriptOrigin* origin = nullptr);
1790 
1791  /**
1792  * Runs the script returning the resulting value. It will be run in the
1793  * context in which it was created (ScriptCompiler::CompileBound or
1794  * UnboundScript::BindToCurrentContext()).
1795  */
1797 
1798  /**
1799  * Returns the corresponding context-unbound script.
1800  */
1802 };
1803 
1804 enum class ScriptType { kClassic, kModule };
1805 
1806 /**
1807  * For compiling scripts.
1808  */
1810  public:
1811  class ConsumeCodeCacheTask;
1812 
1813  /**
1814  * Compilation data that the embedder can cache and pass back to speed up
1815  * future compilations. The data is produced if the CompilerOptions passed to
1816  * the compilation functions in ScriptCompiler contains produce_data_to_cache
1817  * = true. The data to cache can then can be retrieved from
1818  * UnboundScript.
1819  */
1823  BufferOwned
1824  };
1825 
1827  : data(nullptr),
1828  length(0),
1829  rejected(false),
1831 
1832  // If buffer_policy is BufferNotOwned, the caller keeps the ownership of
1833  // data and guarantees that it stays alive until the CachedData object is
1834  // destroyed. If the policy is BufferOwned, the given data will be deleted
1835  // (with delete[]) when the CachedData object is destroyed.
1836  CachedData(const uint8_t* data, int length,
1837  BufferPolicy buffer_policy = BufferNotOwned);
1839  // TODO(marja): Async compilation; add constructors which take a callback
1840  // which will be called when V8 no longer needs the data.
1841  const uint8_t* data;
1842  int length;
1843  bool rejected;
1845 
1846  // Prevent copying.
1847  CachedData(const CachedData&) = delete;
1848  CachedData& operator=(const CachedData&) = delete;
1849  };
1850 
1851  /**
1852  * Source code which can be then compiled to a UnboundScript or Script.
1853  */
1854  class Source {
1855  public:
1856  // Source takes ownership of both CachedData and CodeCacheConsumeTask.
1857  V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
1858  CachedData* cached_data = nullptr,
1859  ConsumeCodeCacheTask* consume_cache_task = nullptr);
1860  // Source takes ownership of both CachedData and CodeCacheConsumeTask.
1861  V8_INLINE explicit Source(
1862  Local<String> source_string, CachedData* cached_data = nullptr,
1863  ConsumeCodeCacheTask* consume_cache_task = nullptr);
1864  V8_INLINE ~Source() = default;
1865 
1866  // Ownership of the CachedData or its buffers is *not* transferred to the
1867  // caller. The CachedData object is alive as long as the Source object is
1868  // alive.
1869  V8_INLINE const CachedData* GetCachedData() const;
1870 
1872 
1873  private:
1874  friend class ScriptCompiler;
1875 
1876  Local<String> source_string;
1877 
1878  // Origin information
1879  Local<Value> resource_name;
1880  int resource_line_offset;
1881  int resource_column_offset;
1882  ScriptOriginOptions resource_options;
1883  Local<Value> source_map_url;
1884  Local<PrimitiveArray> host_defined_options;
1885 
1886  // Cached data from previous compilation (if a kConsume*Cache flag is
1887  // set), or hold newly generated cache data (kProduce*Cache flags) are
1888  // set when calling a compile method.
1889  std::unique_ptr<CachedData> cached_data;
1890  std::unique_ptr<ConsumeCodeCacheTask> consume_cache_task;
1891  };
1892 
1893  /**
1894  * For streaming incomplete script data to V8. The embedder should implement a
1895  * subclass of this class.
1896  */
1898  public:
1899  virtual ~ExternalSourceStream() = default;
1900 
1901  /**
1902  * V8 calls this to request the next chunk of data from the embedder. This
1903  * function will be called on a background thread, so it's OK to block and
1904  * wait for the data, if the embedder doesn't have data yet. Returns the
1905  * length of the data returned. When the data ends, GetMoreData should
1906  * return 0. Caller takes ownership of the data.
1907  *
1908  * When streaming UTF-8 data, V8 handles multi-byte characters split between
1909  * two data chunks, but doesn't handle multi-byte characters split between
1910  * more than two data chunks. The embedder can avoid this problem by always
1911  * returning at least 2 bytes of data.
1912  *
1913  * When streaming UTF-16 data, V8 does not handle characters split between
1914  * two data chunks. The embedder has to make sure that chunks have an even
1915  * length.
1916  *
1917  * If the embedder wants to cancel the streaming, they should make the next
1918  * GetMoreData call return 0. V8 will interpret it as end of data (and most
1919  * probably, parsing will fail). The streaming task will return as soon as
1920  * V8 has parsed the data it received so far.
1921  */
1922  virtual size_t GetMoreData(const uint8_t** src) = 0;
1923 
1924  /**
1925  * V8 calls this method to set a 'bookmark' at the current position in
1926  * the source stream, for the purpose of (maybe) later calling
1927  * ResetToBookmark. If ResetToBookmark is called later, then subsequent
1928  * calls to GetMoreData should return the same data as they did when
1929  * SetBookmark was called earlier.
1930  *
1931  * The embedder may return 'false' to indicate it cannot provide this
1932  * functionality.
1933  */
1934  virtual bool SetBookmark();
1935 
1936  /**
1937  * V8 calls this to return to a previously set bookmark.
1938  */
1939  virtual void ResetToBookmark();
1940  };
1941 
1942  /**
1943  * Source code which can be streamed into V8 in pieces. It will be parsed
1944  * while streaming and compiled after parsing has completed. StreamedSource
1945  * must be kept alive while the streaming task is run (see ScriptStreamingTask
1946  * below).
1947  */
1949  public:
1951 
1952  StreamedSource(std::unique_ptr<ExternalSourceStream> source_stream,
1953  Encoding encoding);
1955 
1956  internal::ScriptStreamingData* impl() const { return impl_.get(); }
1957 
1958  // Prevent copying.
1959  StreamedSource(const StreamedSource&) = delete;
1961 
1962  private:
1963  std::unique_ptr<internal::ScriptStreamingData> impl_;
1964  };
1965 
1966  /**
1967  * A streaming task which the embedder must run on a background thread to
1968  * stream scripts into V8. Returned by ScriptCompiler::StartStreaming.
1969  */
1970  class V8_EXPORT ScriptStreamingTask final {
1971  public:
1972  void Run();
1973 
1974  private:
1975  friend class ScriptCompiler;
1976 
1977  explicit ScriptStreamingTask(internal::ScriptStreamingData* data)
1978  : data_(data) {}
1979 
1980  internal::ScriptStreamingData* data_;
1981  };
1982 
1983  /**
1984  * A task which the embedder must run on a background thread to
1985  * consume a V8 code cache. Returned by
1986  * ScriptCompiler::StarConsumingCodeCache.
1987  */
1988  class V8_EXPORT ConsumeCodeCacheTask final {
1989  public:
1991 
1992  void Run();
1993 
1994  private:
1995  friend class ScriptCompiler;
1996 
1997  explicit ConsumeCodeCacheTask(
1998  std::unique_ptr<internal::BackgroundDeserializeTask> impl);
1999 
2000  std::unique_ptr<internal::BackgroundDeserializeTask> impl_;
2001  };
2002 
2007  };
2008 
2009  /**
2010  * The reason for which we are not requesting or providing a code cache.
2011  */
2028  };
2029 
2030  /**
2031  * Compiles the specified script (context-independent).
2032  * Cached data as part of the source object can be optionally produced to be
2033  * consumed later to speed up compilation of identical source scripts.
2034  *
2035  * Note that when producing cached data, the source must point to NULL for
2036  * cached data. When consuming cached data, the cached data must have been
2037  * produced by the same version of V8, and the embedder needs to ensure the
2038  * cached data is the correct one for the given script.
2039  *
2040  * \param source Script source code.
2041  * \return Compiled script object (context independent; for running it must be
2042  * bound to a context).
2043  */
2045  Isolate* isolate, Source* source,
2047  NoCacheReason no_cache_reason = kNoCacheNoReason);
2048 
2049  /**
2050  * Compiles the specified script (bound to current context).
2051  *
2052  * \param source Script source code.
2053  * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
2054  * using pre_data speeds compilation if it's done multiple times.
2055  * Owned by caller, no references are kept when this function returns.
2056  * \return Compiled script object, bound to the context that was active
2057  * when this function was called. When run it will always use this
2058  * context.
2059  */
2061  Local<Context> context, Source* source,
2063  NoCacheReason no_cache_reason = kNoCacheNoReason);
2064 
2065  /**
2066  * Returns a task which streams script data into V8, or NULL if the script
2067  * cannot be streamed. The user is responsible for running the task on a
2068  * background thread and deleting it. When ran, the task starts parsing the
2069  * script, and it will request data from the StreamedSource as needed. When
2070  * ScriptStreamingTask::Run exits, all data has been streamed and the script
2071  * can be compiled (see Compile below).
2072  *
2073  * This API allows to start the streaming with as little data as possible, and
2074  * the remaining data (for example, the ScriptOrigin) is passed to Compile.
2075  */
2076  static ScriptStreamingTask* StartStreaming(
2077  Isolate* isolate, StreamedSource* source,
2079 
2080  static ConsumeCodeCacheTask* StartConsumingCodeCache(
2081  Isolate* isolate, std::unique_ptr<CachedData> source);
2082 
2083  /**
2084  * Compiles a streamed script (bound to current context).
2085  *
2086  * This can only be called after the streaming has finished
2087  * (ScriptStreamingTask has been run). V8 doesn't construct the source string
2088  * during streaming, so the embedder needs to pass the full source here.
2089  */
2091  Local<Context> context, StreamedSource* source,
2092  Local<String> full_source_string, const ScriptOrigin& origin);
2093 
2094  /**
2095  * Return a version tag for CachedData for the current V8 version & flags.
2096  *
2097  * This value is meant only for determining whether a previously generated
2098  * CachedData instance is still valid; the tag has no other meaing.
2099  *
2100  * Background: The data carried by CachedData may depend on the exact
2101  * V8 version number or current compiler flags. This means that when
2102  * persisting CachedData, the embedder must take care to not pass in
2103  * data from another V8 version, or the same version with different
2104  * features enabled.
2105  *
2106  * The easiest way to do so is to clear the embedder's cache on any
2107  * such change.
2108  *
2109  * Alternatively, this tag can be stored alongside the cached data and
2110  * compared when it is being used.
2111  */
2112  static uint32_t CachedDataVersionTag();
2113 
2114  /**
2115  * Compile an ES module, returning a Module that encapsulates
2116  * the compiled code.
2117  *
2118  * Corresponds to the ParseModule abstract operation in the
2119  * ECMAScript specification.
2120  */
2122  Isolate* isolate, Source* source,
2124  NoCacheReason no_cache_reason = kNoCacheNoReason);
2125 
2126  /**
2127  * Compiles a streamed module script.
2128  *
2129  * This can only be called after the streaming has finished
2130  * (ScriptStreamingTask has been run). V8 doesn't construct the source string
2131  * during streaming, so the embedder needs to pass the full source here.
2132  */
2134  Local<Context> context, StreamedSource* v8_source,
2135  Local<String> full_source_string, const ScriptOrigin& origin);
2136 
2137  /**
2138  * Compile a function for a given context. This is equivalent to running
2139  *
2140  * with (obj) {
2141  * return function(args) { ... }
2142  * }
2143  *
2144  * It is possible to specify multiple context extensions (obj in the above
2145  * example).
2146  */
2148  Local<Context> context, Source* source, size_t arguments_count,
2149  Local<String> arguments[], size_t context_extension_count,
2150  Local<Object> context_extensions[],
2152  NoCacheReason no_cache_reason = kNoCacheNoReason,
2153  Local<ScriptOrModule>* script_or_module_out = nullptr);
2154 
2155  /**
2156  * Creates and returns code cache for the specified unbound_script.
2157  * This will return nullptr if the script cannot be serialized. The
2158  * CachedData returned by this function should be owned by the caller.
2159  */
2160  static CachedData* CreateCodeCache(Local<UnboundScript> unbound_script);
2161 
2162  /**
2163  * Creates and returns code cache for the specified unbound_module_script.
2164  * This will return nullptr if the script cannot be serialized. The
2165  * CachedData returned by this function should be owned by the caller.
2166  */
2168  Local<UnboundModuleScript> unbound_module_script);
2169 
2170  /**
2171  * Creates and returns code cache for the specified function that was
2172  * previously produced by CompileFunctionInContext.
2173  * This will return nullptr if the script cannot be serialized. The
2174  * CachedData returned by this function should be owned by the caller.
2175  */
2177 
2178  private:
2179  static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundInternal(
2180  Isolate* isolate, Source* source, CompileOptions options,
2181  NoCacheReason no_cache_reason);
2182 };
2183 
2184 
2185 /**
2186  * An error message.
2187  */
2189  public:
2190  Local<String> Get() const;
2191 
2192  /**
2193  * Return the isolate to which the Message belongs.
2194  */
2196 
2198  Local<Context> context) const;
2200  Local<Context> context) const;
2201 
2202  /**
2203  * Returns the origin for the script from where the function causing the
2204  * error originates.
2205  */
2207 
2208  /**
2209  * Returns the resource name for the script from where the function causing
2210  * the error originates.
2211  */
2213 
2214  /**
2215  * Exception stack trace. By default stack traces are not captured for
2216  * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
2217  * to change this option.
2218  */
2220 
2221  /**
2222  * Returns the number, 1-based, of the line where the error occurred.
2223  */
2225 
2226  /**
2227  * Returns the index within the script of the first character where
2228  * the error occurred.
2229  */
2230  int GetStartPosition() const;
2231 
2232  /**
2233  * Returns the index within the script of the last character where
2234  * the error occurred.
2235  */
2236  int GetEndPosition() const;
2237 
2238  /**
2239  * Returns the Wasm function index where the error occurred. Returns -1 if
2240  * message is not from a Wasm script.
2241  */
2243 
2244  /**
2245  * Returns the error level of the message.
2246  */
2247  int ErrorLevel() const;
2248 
2249  /**
2250  * Returns the index within the line of the first character where
2251  * the error occurred.
2252  */
2253  int GetStartColumn() const;
2255 
2256  /**
2257  * Returns the index within the line of the last character where
2258  * the error occurred.
2259  */
2260  int GetEndColumn() const;
2262 
2263  /**
2264  * Passes on the value set by the embedder when it fed the script from which
2265  * this Message was generated to V8.
2266  */
2267  bool IsSharedCrossOrigin() const;
2268  bool IsOpaque() const;
2269 
2270  // TODO(1245381): Print to a string instead of on a FILE.
2271  static void PrintCurrentStackTrace(Isolate* isolate, FILE* out);
2272 
2273  static const int kNoLineNumberInfo = 0;
2274  static const int kNoColumnInfo = 0;
2275  static const int kNoScriptIdInfo = 0;
2276  static const int kNoWasmFunctionIndexInfo = -1;
2277 };
2278 
2279 
2280 /**
2281  * Representation of a JavaScript stack trace. The information collected is a
2282  * snapshot of the execution stack and the information remains valid after
2283  * execution continues.
2284  */
2286  public:
2287  /**
2288  * Flags that determine what information is placed captured for each
2289  * StackFrame when grabbing the current stack trace.
2290  * Note: these options are deprecated and we always collect all available
2291  * information (kDetailed).
2292  */
2296  kScriptName = 1 << 2,
2297  kFunctionName = 1 << 3,
2298  kIsEval = 1 << 4,
2299  kIsConstructor = 1 << 5,
2301  kScriptId = 1 << 7,
2305  };
2306 
2307  /**
2308  * Returns a StackFrame at a particular index.
2309  */
2310  Local<StackFrame> GetFrame(Isolate* isolate, uint32_t index) const;
2311 
2312  /**
2313  * Returns the number of StackFrames.
2314  */
2315  int GetFrameCount() const;
2316 
2317  /**
2318  * Grab a snapshot of the current JavaScript execution stack.
2319  *
2320  * \param frame_limit The maximum number of stack frames we want to capture.
2321  * \param options Enumerates the set of things we will capture for each
2322  * StackFrame.
2323  */
2325  Isolate* isolate, int frame_limit, StackTraceOptions options = kDetailed);
2326 };
2327 
2328 
2329 /**
2330  * A single JavaScript stack frame.
2331  */
2333  public:
2334  /**
2335  * Returns the number, 1-based, of the line for the associate function call.
2336  * This method will return Message::kNoLineNumberInfo if it is unable to
2337  * retrieve the line number, or if kLineNumber was not passed as an option
2338  * when capturing the StackTrace.
2339  */
2340  int GetLineNumber() const;
2341 
2342  /**
2343  * Returns the 1-based column offset on the line for the associated function
2344  * call.
2345  * This method will return Message::kNoColumnInfo if it is unable to retrieve
2346  * the column number, or if kColumnOffset was not passed as an option when
2347  * capturing the StackTrace.
2348  */
2349  int GetColumn() const;
2350 
2351  /**
2352  * Returns the id of the script for the function for this StackFrame.
2353  * This method will return Message::kNoScriptIdInfo if it is unable to
2354  * retrieve the script id, or if kScriptId was not passed as an option when
2355  * capturing the StackTrace.
2356  */
2357  int GetScriptId() const;
2358 
2359  /**
2360  * Returns the name of the resource that contains the script for the
2361  * function for this StackFrame.
2362  */
2364 
2365  /**
2366  * Returns the name of the resource that contains the script for the
2367  * function for this StackFrame or sourceURL value if the script name
2368  * is undefined and its source ends with //# sourceURL=... string or
2369  * deprecated //@ sourceURL=... string.
2370  */
2372 
2373  /**
2374  * Returns the source of the script for the function for this StackFrame.
2375  */
2377 
2378  /**
2379  * Returns the source mapping URL (if one is present) of the script for
2380  * the function for this StackFrame.
2381  */
2383 
2384  /**
2385  * Returns the name of the function associated with this stack frame.
2386  */
2388 
2389  /**
2390  * Returns whether or not the associated function is compiled via a call to
2391  * eval().
2392  */
2393  bool IsEval() const;
2394 
2395  /**
2396  * Returns whether or not the associated function is called as a
2397  * constructor via "new".
2398  */
2399  bool IsConstructor() const;
2400 
2401  /**
2402  * Returns whether or not the associated functions is defined in wasm.
2403  */
2404  bool IsWasm() const;
2405 
2406  /**
2407  * Returns whether or not the associated function is defined by the user.
2408  */
2409  bool IsUserJavaScript() const;
2410 };
2411 
2412 
2413 // A StateTag represents a possible state of the VM.
2414 enum StateTag {
2423  IDLE
2424 };
2425 
2426 // Holds the callee saved registers needed for the stack unwinder. It is the
2427 // empty struct if no registers are required. Implemented in
2428 // include/v8-unwinder-state.h.
2429 struct CalleeSavedRegisters;
2430 
2431 // A RegisterState represents the current state of registers used
2432 // by the sampling profiler API.
2438 
2439  void* pc; // Instruction pointer.
2440  void* sp; // Stack pointer.
2441  void* fp; // Frame pointer.
2442  void* lr; // Link register (or nullptr on platforms without a link register).
2443  // Callee saved registers (or null if no callee saved registers were stored)
2444  std::unique_ptr<CalleeSavedRegisters> callee_saved;
2445 };
2446 
2447 // The output structure filled up by GetStackSample API function.
2448 struct SampleInfo {
2449  size_t frames_count; // Number of frames collected.
2450  StateTag vm_state; // Current VM state.
2451  void* external_callback_entry; // External callback address if VM is
2452  // executing an external callback.
2453  void* context; // Incumbent native context address.
2454 };
2455 
2456 struct MemoryRange {
2457  const void* start = nullptr;
2458  size_t length_in_bytes = 0;
2459 };
2460 
2461 struct JSEntryStub {
2463 };
2464 
2469 };
2470 
2471 /**
2472  * A JSON Parser and Stringifier.
2473  */
2475  public:
2476  /**
2477  * Tries to parse the string |json_string| and returns it as value if
2478  * successful.
2479  *
2480  * \param the context in which to parse and create the value.
2481  * \param json_string The string to parse.
2482  * \return The corresponding value if successfully parsed.
2483  */
2485  Local<Context> context, Local<String> json_string);
2486 
2487  /**
2488  * Tries to stringify the JSON-serializable object |json_object| and returns
2489  * it as string if successful.
2490  *
2491  * \param json_object The JSON-serializable object to stringify.
2492  * \return The corresponding string if successfully stringified.
2493  */
2495  Local<Context> context, Local<Value> json_object,
2496  Local<String> gap = Local<String>());
2497 };
2498 
2499 /**
2500  * Value serialization compatible with the HTML structured clone algorithm.
2501  * The format is backward-compatible (i.e. safe to store to disk).
2502  */
2504  public:
2506  public:
2507  virtual ~Delegate() = default;
2508 
2509  /**
2510  * Handles the case where a DataCloneError would be thrown in the structured
2511  * clone spec. Other V8 embedders may throw some other appropriate exception
2512  * type.
2513  */
2514  virtual void ThrowDataCloneError(Local<String> message) = 0;
2515 
2516  /**
2517  * The embedder overrides this method to write some kind of host object, if
2518  * possible. If not, a suitable exception should be thrown and
2519  * Nothing<bool>() returned.
2520  */
2521  virtual Maybe<bool> WriteHostObject(Isolate* isolate, Local<Object> object);
2522 
2523  /**
2524  * Called when the ValueSerializer is going to serialize a
2525  * SharedArrayBuffer object. The embedder must return an ID for the
2526  * object, using the same ID if this SharedArrayBuffer has already been
2527  * serialized in this buffer. When deserializing, this ID will be passed to
2528  * ValueDeserializer::GetSharedArrayBufferFromId as |clone_id|.
2529  *
2530  * If the object cannot be serialized, an
2531  * exception should be thrown and Nothing<uint32_t>() returned.
2532  */
2533  virtual Maybe<uint32_t> GetSharedArrayBufferId(
2534  Isolate* isolate, Local<SharedArrayBuffer> shared_array_buffer);
2535 
2536  virtual Maybe<uint32_t> GetWasmModuleTransferId(
2537  Isolate* isolate, Local<WasmModuleObject> module);
2538  /**
2539  * Allocates memory for the buffer of at least the size provided. The actual
2540  * size (which may be greater or equal) is written to |actual_size|. If no
2541  * buffer has been allocated yet, nullptr will be provided.
2542  *
2543  * If the memory cannot be allocated, nullptr should be returned.
2544  * |actual_size| will be ignored. It is assumed that |old_buffer| is still
2545  * valid in this case and has not been modified.
2546  *
2547  * The default implementation uses the stdlib's `realloc()` function.
2548  */
2549  virtual void* ReallocateBufferMemory(void* old_buffer, size_t size,
2550  size_t* actual_size);
2551 
2552  /**
2553  * Frees a buffer allocated with |ReallocateBufferMemory|.
2554  *
2555  * The default implementation uses the stdlib's `free()` function.
2556  */
2557  virtual void FreeBufferMemory(void* buffer);
2558  };
2559 
2560  explicit ValueSerializer(Isolate* isolate);
2561  ValueSerializer(Isolate* isolate, Delegate* delegate);
2563 
2564  /**
2565  * Writes out a header, which includes the format version.
2566  */
2567  void WriteHeader();
2568 
2569  /**
2570  * Serializes a JavaScript value into the buffer.
2571  */
2573  Local<Value> value);
2574 
2575  /**
2576  * Returns the stored data (allocated using the delegate's
2577  * ReallocateBufferMemory) and its size. This serializer should not be used
2578  * once the buffer is released. The contents are undefined if a previous write
2579  * has failed. Ownership of the buffer is transferred to the caller.
2580  */
2581  V8_WARN_UNUSED_RESULT std::pair<uint8_t*, size_t> Release();
2582 
2583  /**
2584  * Marks an ArrayBuffer as havings its contents transferred out of band.
2585  * Pass the corresponding ArrayBuffer in the deserializing context to
2586  * ValueDeserializer::TransferArrayBuffer.
2587  */
2588  void TransferArrayBuffer(uint32_t transfer_id,
2589  Local<ArrayBuffer> array_buffer);
2590 
2591 
2592  /**
2593  * Indicate whether to treat ArrayBufferView objects as host objects,
2594  * i.e. pass them to Delegate::WriteHostObject. This should not be
2595  * called when no Delegate was passed.
2596  *
2597  * The default is not to treat ArrayBufferViews as host objects.
2598  */
2600 
2601  /**
2602  * Write raw data in various common formats to the buffer.
2603  * Note that integer types are written in base-128 varint format, not with a
2604  * binary copy. For use during an override of Delegate::WriteHostObject.
2605  */
2606  void WriteUint32(uint32_t value);
2607  void WriteUint64(uint64_t value);
2608  void WriteDouble(double value);
2609  void WriteRawBytes(const void* source, size_t length);
2610 
2612  void operator=(const ValueSerializer&) = delete;
2613 
2614  private:
2615  struct PrivateData;
2616  PrivateData* private_;
2617 };
2618 
2619 /**
2620  * Deserializes values from data written with ValueSerializer, or a compatible
2621  * implementation.
2622  */
2624  public:
2626  public:
2627  virtual ~Delegate() = default;
2628 
2629  /**
2630  * The embedder overrides this method to read some kind of host object, if
2631  * possible. If not, a suitable exception should be thrown and
2632  * MaybeLocal<Object>() returned.
2633  */
2635 
2636  /**
2637  * Get a WasmModuleObject given a transfer_id previously provided
2638  * by ValueSerializer::GetWasmModuleTransferId
2639  */
2641  Isolate* isolate, uint32_t transfer_id);
2642 
2643  /**
2644  * Get a SharedArrayBuffer given a clone_id previously provided
2645  * by ValueSerializer::GetSharedArrayBufferId
2646  */
2648  Isolate* isolate, uint32_t clone_id);
2649  };
2650 
2651  ValueDeserializer(Isolate* isolate, const uint8_t* data, size_t size);
2652  ValueDeserializer(Isolate* isolate, const uint8_t* data, size_t size,
2653  Delegate* delegate);
2655 
2656  /**
2657  * Reads and validates a header (including the format version).
2658  * May, for example, reject an invalid or unsupported wire format.
2659  */
2661 
2662  /**
2663  * Deserializes a JavaScript value from the buffer.
2664  */
2666 
2667  /**
2668  * Accepts the array buffer corresponding to the one passed previously to
2669  * ValueSerializer::TransferArrayBuffer.
2670  */
2671  void TransferArrayBuffer(uint32_t transfer_id,
2672  Local<ArrayBuffer> array_buffer);
2673 
2674  /**
2675  * Similar to TransferArrayBuffer, but for SharedArrayBuffer.
2676  * The id is not necessarily in the same namespace as unshared ArrayBuffer
2677  * objects.
2678  */
2679  void TransferSharedArrayBuffer(uint32_t id,
2680  Local<SharedArrayBuffer> shared_array_buffer);
2681 
2682  /**
2683  * Must be called before ReadHeader to enable support for reading the legacy
2684  * wire format (i.e., which predates this being shipped).
2685  *
2686  * Don't use this unless you need to read data written by previous versions of
2687  * blink::ScriptValueSerializer.
2688  */
2689  void SetSupportsLegacyWireFormat(bool supports_legacy_wire_format);
2690 
2691  /**
2692  * Reads the underlying wire format version. Likely mostly to be useful to
2693  * legacy code reading old wire format versions. Must be called after
2694  * ReadHeader.
2695  */
2696  uint32_t GetWireFormatVersion() const;
2697 
2698  /**
2699  * Reads raw data in various common formats to the buffer.
2700  * Note that integer types are read in base-128 varint format, not with a
2701  * binary copy. For use during an override of Delegate::ReadHostObject.
2702  */
2703  V8_WARN_UNUSED_RESULT bool ReadUint32(uint32_t* value);
2704  V8_WARN_UNUSED_RESULT bool ReadUint64(uint64_t* value);
2705  V8_WARN_UNUSED_RESULT bool ReadDouble(double* value);
2706  V8_WARN_UNUSED_RESULT bool ReadRawBytes(size_t length, const void** data);
2707 
2709  void operator=(const ValueDeserializer&) = delete;
2710 
2711  private:
2712  struct PrivateData;
2713  PrivateData* private_;
2714 };
2715 
2716 
2717 // --- Value ---
2718 
2719 
2720 /**
2721  * The superclass of all JavaScript values and objects.
2722  */
2723 class V8_EXPORT Value : public Data {
2724  public:
2725  /**
2726  * Returns true if this value is the undefined value. See ECMA-262
2727  * 4.3.10.
2728  *
2729  * This is equivalent to `value === undefined` in JS.
2730  */
2731  V8_INLINE bool IsUndefined() const;
2732 
2733  /**
2734  * Returns true if this value is the null value. See ECMA-262
2735  * 4.3.11.
2736  *
2737  * This is equivalent to `value === null` in JS.
2738  */
2739  V8_INLINE bool IsNull() const;
2740 
2741  /**
2742  * Returns true if this value is either the null or the undefined value.
2743  * See ECMA-262
2744  * 4.3.11. and 4.3.12
2745  *
2746  * This is equivalent to `value == null` in JS.
2747  */
2748  V8_INLINE bool IsNullOrUndefined() const;
2749 
2750  /**
2751  * Returns true if this value is true.
2752  *
2753  * This is not the same as `BooleanValue()`. The latter performs a
2754  * conversion to boolean, i.e. the result of `Boolean(value)` in JS, whereas
2755  * this checks `value === true`.
2756  */
2757  bool IsTrue() const;
2758 
2759  /**
2760  * Returns true if this value is false.
2761  *
2762  * This is not the same as `!BooleanValue()`. The latter performs a
2763  * conversion to boolean, i.e. the result of `!Boolean(value)` in JS, whereas
2764  * this checks `value === false`.
2765  */
2766  bool IsFalse() const;
2767 
2768  /**
2769  * Returns true if this value is a symbol or a string.
2770  *
2771  * This is equivalent to
2772  * `typeof value === 'string' || typeof value === 'symbol'` in JS.
2773  */
2774  bool IsName() const;
2775 
2776  /**
2777  * Returns true if this value is an instance of the String type.
2778  * See ECMA-262 8.4.
2779  *
2780  * This is equivalent to `typeof value === 'string'` in JS.
2781  */
2782  V8_INLINE bool IsString() const;
2783 
2784  /**
2785  * Returns true if this value is a symbol.
2786  *
2787  * This is equivalent to `typeof value === 'symbol'` in JS.
2788  */
2789  bool IsSymbol() const;
2790 
2791  /**
2792  * Returns true if this value is a function.
2793  *
2794  * This is equivalent to `typeof value === 'function'` in JS.
2795  */
2796  bool IsFunction() const;
2797 
2798  /**
2799  * Returns true if this value is an array. Note that it will return false for
2800  * an Proxy for an array.
2801  */
2802  bool IsArray() const;
2803 
2804  /**
2805  * Returns true if this value is an object.
2806  */
2807  bool IsObject() const;
2808 
2809  /**
2810  * Returns true if this value is a bigint.
2811  *
2812  * This is equivalent to `typeof value === 'bigint'` in JS.
2813  */
2814  bool IsBigInt() const;
2815 
2816  /**
2817  * Returns true if this value is boolean.
2818  *
2819  * This is equivalent to `typeof value === 'boolean'` in JS.
2820  */
2821  bool IsBoolean() const;
2822 
2823  /**
2824  * Returns true if this value is a number.
2825  *
2826  * This is equivalent to `typeof value === 'number'` in JS.
2827  */
2828  bool IsNumber() const;
2829 
2830  /**
2831  * Returns true if this value is an `External` object.
2832  */
2833  bool IsExternal() const;
2834 
2835  /**
2836  * Returns true if this value is a 32-bit signed integer.
2837  */
2838  bool IsInt32() const;
2839 
2840  /**
2841  * Returns true if this value is a 32-bit unsigned integer.
2842  */
2843  bool IsUint32() const;
2844 
2845  /**
2846  * Returns true if this value is a Date.
2847  */
2848  bool IsDate() const;
2849 
2850  /**
2851  * Returns true if this value is an Arguments object.
2852  */
2853  bool IsArgumentsObject() const;
2854 
2855  /**
2856  * Returns true if this value is a BigInt object.
2857  */
2858  bool IsBigIntObject() const;
2859 
2860  /**
2861  * Returns true if this value is a Boolean object.
2862  */
2863  bool IsBooleanObject() const;
2864 
2865  /**
2866  * Returns true if this value is a Number object.
2867  */
2868  bool IsNumberObject() const;
2869 
2870  /**
2871  * Returns true if this value is a String object.
2872  */
2873  bool IsStringObject() const;
2874 
2875  /**
2876  * Returns true if this value is a Symbol object.
2877  */
2878  bool IsSymbolObject() const;
2879 
2880  /**
2881  * Returns true if this value is a NativeError.
2882  */
2883  bool IsNativeError() const;
2884 
2885  /**
2886  * Returns true if this value is a RegExp.
2887  */
2888  bool IsRegExp() const;
2889 
2890  /**
2891  * Returns true if this value is an async function.
2892  */
2893  bool IsAsyncFunction() const;
2894 
2895  /**
2896  * Returns true if this value is a Generator function.
2897  */
2898  bool IsGeneratorFunction() const;
2899 
2900  /**
2901  * Returns true if this value is a Generator object (iterator).
2902  */
2903  bool IsGeneratorObject() const;
2904 
2905  /**
2906  * Returns true if this value is a Promise.
2907  */
2908  bool IsPromise() const;
2909 
2910  /**
2911  * Returns true if this value is a Map.
2912  */
2913  bool IsMap() const;
2914 
2915  /**
2916  * Returns true if this value is a Set.
2917  */
2918  bool IsSet() const;
2919 
2920  /**
2921  * Returns true if this value is a Map Iterator.
2922  */
2923  bool IsMapIterator() const;
2924 
2925  /**
2926  * Returns true if this value is a Set Iterator.
2927  */
2928  bool IsSetIterator() const;
2929 
2930  /**
2931  * Returns true if this value is a WeakMap.
2932  */
2933  bool IsWeakMap() const;
2934 
2935  /**
2936  * Returns true if this value is a WeakSet.
2937  */
2938  bool IsWeakSet() const;
2939 
2940  /**
2941  * Returns true if this value is an ArrayBuffer.
2942  */
2943  bool IsArrayBuffer() const;
2944 
2945  /**
2946  * Returns true if this value is an ArrayBufferView.
2947  */
2948  bool IsArrayBufferView() const;
2949 
2950  /**
2951  * Returns true if this value is one of TypedArrays.
2952  */
2953  bool IsTypedArray() const;
2954 
2955  /**
2956  * Returns true if this value is an Uint8Array.
2957  */
2958  bool IsUint8Array() const;
2959 
2960  /**
2961  * Returns true if this value is an Uint8ClampedArray.
2962  */
2963  bool IsUint8ClampedArray() const;
2964 
2965  /**
2966  * Returns true if this value is an Int8Array.
2967  */
2968  bool IsInt8Array() const;
2969 
2970  /**
2971  * Returns true if this value is an Uint16Array.
2972  */
2973  bool IsUint16Array() const;
2974 
2975  /**
2976  * Returns true if this value is an Int16Array.
2977  */
2978  bool IsInt16Array() const;
2979 
2980  /**
2981  * Returns true if this value is an Uint32Array.
2982  */
2983  bool IsUint32Array() const;
2984 
2985  /**
2986  * Returns true if this value is an Int32Array.
2987  */
2988  bool IsInt32Array() const;
2989 
2990  /**
2991  * Returns true if this value is a Float32Array.
2992  */
2993  bool IsFloat32Array() const;
2994 
2995  /**
2996  * Returns true if this value is a Float64Array.
2997  */
2998  bool IsFloat64Array() const;
2999 
3000  /**
3001  * Returns true if this value is a BigInt64Array.
3002  */
3003  bool IsBigInt64Array() const;
3004 
3005  /**
3006  * Returns true if this value is a BigUint64Array.
3007  */
3008  bool IsBigUint64Array() const;
3009 
3010  /**
3011  * Returns true if this value is a DataView.
3012  */
3013  bool IsDataView() const;
3014 
3015  /**
3016  * Returns true if this value is a SharedArrayBuffer.
3017  */
3018  bool IsSharedArrayBuffer() const;
3019 
3020  /**
3021  * Returns true if this value is a JavaScript Proxy.
3022  */
3023  bool IsProxy() const;
3024 
3025  /**
3026  * Returns true if this value is a WasmMemoryObject.
3027  */
3028  bool IsWasmMemoryObject() const;
3029 
3030  /**
3031  * Returns true if this value is a WasmModuleObject.
3032  */
3033  bool IsWasmModuleObject() const;
3034 
3035  /**
3036  * Returns true if the value is a Module Namespace Object.
3037  */
3039 
3040  /**
3041  * Perform the equivalent of `BigInt(value)` in JS.
3042  */
3044  Local<Context> context) const;
3045  /**
3046  * Perform the equivalent of `Number(value)` in JS.
3047  */
3049  Local<Context> context) const;
3050  /**
3051  * Perform the equivalent of `String(value)` in JS.
3052  */
3054  Local<Context> context) const;
3055  /**
3056  * Provide a string representation of this value usable for debugging.
3057  * This operation has no observable side effects and will succeed
3058  * unless e.g. execution is being terminated.
3059  */
3061  Local<Context> context) const;
3062  /**
3063  * Perform the equivalent of `Object(value)` in JS.
3064  */
3066  Local<Context> context) const;
3067  /**
3068  * Perform the equivalent of `Number(value)` in JS and convert the result
3069  * to an integer. Negative values are rounded up, positive values are rounded
3070  * down. NaN is converted to 0. Infinite values yield undefined results.
3071  */
3073  Local<Context> context) const;
3074  /**
3075  * Perform the equivalent of `Number(value)` in JS and convert the result
3076  * to an unsigned 32-bit integer by performing the steps in
3077  * https://tc39.es/ecma262/#sec-touint32.
3078  */
3080  Local<Context> context) const;
3081  /**
3082  * Perform the equivalent of `Number(value)` in JS and convert the result
3083  * to a signed 32-bit integer by performing the steps in
3084  * https://tc39.es/ecma262/#sec-toint32.
3085  */
3087 
3088  /**
3089  * Perform the equivalent of `Boolean(value)` in JS. This can never fail.
3090  */
3091  Local<Boolean> ToBoolean(Isolate* isolate) const;
3092 
3093  /**
3094  * Attempts to convert a string to an array index.
3095  * Returns an empty handle if the conversion fails.
3096  */
3098  Local<Context> context) const;
3099 
3100  /** Returns the equivalent of `ToBoolean()->Value()`. */
3101  bool BooleanValue(Isolate* isolate) const;
3102 
3103  /** Returns the equivalent of `ToNumber()->Value()`. */
3105  /** Returns the equivalent of `ToInteger()->Value()`. */
3107  Local<Context> context) const;
3108  /** Returns the equivalent of `ToUint32()->Value()`. */
3110  Local<Context> context) const;
3111  /** Returns the equivalent of `ToInt32()->Value()`. */
3113 
3114  /** JS == */
3116  Local<Value> that) const;
3117  bool StrictEquals(Local<Value> that) const;
3118  bool SameValue(Local<Value> that) const;
3119 
3120  template <class T> V8_INLINE static Value* Cast(T* value);
3121 
3123 
3124  Maybe<bool> InstanceOf(Local<Context> context, Local<Object> object);
3125 
3126  private:
3127  V8_INLINE bool QuickIsUndefined() const;
3128  V8_INLINE bool QuickIsNull() const;
3129  V8_INLINE bool QuickIsNullOrUndefined() const;
3130  V8_INLINE bool QuickIsString() const;
3131  bool FullIsUndefined() const;
3132  bool FullIsNull() const;
3133  bool FullIsString() const;
3134 
3135  static void CheckCast(Data* that);
3136 };
3137 
3138 
3139 /**
3140  * The superclass of primitive values. See ECMA-262 4.3.2.
3141  */
3142 class V8_EXPORT Primitive : public Value { };
3143 
3144 
3145 /**
3146  * A primitive boolean value (ECMA-262, 4.3.14). Either the true
3147  * or false value.
3148  */
3149 class V8_EXPORT Boolean : public Primitive {
3150  public:
3151  bool Value() const;
3152  V8_INLINE static Boolean* Cast(v8::Data* data);
3153  V8_INLINE static Local<Boolean> New(Isolate* isolate, bool value);
3154 
3155  private:
3156  static void CheckCast(v8::Data* that);
3157 };
3158 
3159 
3160 /**
3161  * A superclass for symbols and strings.
3162  */
3163 class V8_EXPORT Name : public Primitive {
3164  public:
3165  /**
3166  * Returns the identity hash for this object. The current implementation
3167  * uses an inline property on the object to store the identity hash.
3168  *
3169  * The return value will never be 0. Also, it is not guaranteed to be
3170  * unique.
3171  */
3173 
3174  V8_INLINE static Name* Cast(Data* data);
3175 
3176  private:
3177  static void CheckCast(Data* that);
3178 };
3179 
3180 /**
3181  * A flag describing different modes of string creation.
3182  *
3183  * Aside from performance implications there are no differences between the two
3184  * creation modes.
3185  */
3186 enum class NewStringType {
3187  /**
3188  * Create a new string, always allocating new storage memory.
3189  */
3190  kNormal,
3191 
3192  /**
3193  * Acts as a hint that the string should be created in the
3194  * old generation heap space and be deduplicated if an identical string
3195  * already exists.
3196  */
3198 };
3199 
3200 /**
3201  * A JavaScript string value (ECMA-262, 4.3.17).
3202  */
3203 class V8_EXPORT String : public Name {
3204  public:
3205  static constexpr int kMaxLength =
3206  internal::kApiSystemPointerSize == 4 ? (1 << 28) - 16 : (1 << 29) - 24;
3207 
3208  enum Encoding {
3211  ONE_BYTE_ENCODING = 0x8
3212  };
3213  /**
3214  * Returns the number of characters (UTF-16 code units) in this string.
3215  */
3216  int Length() const;
3217 
3218  /**
3219  * Returns the number of bytes in the UTF-8 encoded
3220  * representation of this string.
3221  */
3222  int Utf8Length(Isolate* isolate) const;
3223 
3224  /**
3225  * Returns whether this string is known to contain only one byte data,
3226  * i.e. ISO-8859-1 code points.
3227  * Does not read the string.
3228  * False negatives are possible.
3229  */
3230  bool IsOneByte() const;
3231 
3232  /**
3233  * Returns whether this string contain only one byte data,
3234  * i.e. ISO-8859-1 code points.
3235  * Will read the entire string in some cases.
3236  */
3237  bool ContainsOnlyOneByte() const;
3238 
3239  /**
3240  * Write the contents of the string to an external buffer.
3241  * If no arguments are given, expects the buffer to be large
3242  * enough to hold the entire string and NULL terminator. Copies
3243  * the contents of the string and the NULL terminator into the
3244  * buffer.
3245  *
3246  * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
3247  * before the end of the buffer.
3248  *
3249  * Copies up to length characters into the output buffer.
3250  * Only null-terminates if there is enough space in the buffer.
3251  *
3252  * \param buffer The buffer into which the string will be copied.
3253  * \param start The starting position within the string at which
3254  * copying begins.
3255  * \param length The number of characters to copy from the string. For
3256  * WriteUtf8 the number of bytes in the buffer.
3257  * \param nchars_ref The number of characters written, can be NULL.
3258  * \param options Various options that might affect performance of this or
3259  * subsequent operations.
3260  * \return The number of characters copied to the buffer excluding the null
3261  * terminator. For WriteUtf8: The number of bytes copied to the buffer
3262  * including the null terminator (if written).
3263  */
3269  // Used by WriteUtf8 to replace orphan surrogate code units with the
3270  // unicode replacement character. Needs to be set to guarantee valid UTF-8
3271  // output.
3273  };
3274 
3275  // 16-bit character codes.
3276  int Write(Isolate* isolate, uint16_t* buffer, int start = 0, int length = -1,
3277  int options = NO_OPTIONS) const;
3278  // One byte characters.
3279  int WriteOneByte(Isolate* isolate, uint8_t* buffer, int start = 0,
3280  int length = -1, int options = NO_OPTIONS) const;
3281  // UTF-8 encoded characters.
3282  int WriteUtf8(Isolate* isolate, char* buffer, int length = -1,
3283  int* nchars_ref = nullptr, int options = NO_OPTIONS) const;
3284 
3285  /**
3286  * A zero length string.
3287  */
3288  V8_INLINE static Local<String> Empty(Isolate* isolate);
3289 
3290  /**
3291  * Returns true if the string is external.
3292  */
3293  bool IsExternal() const;
3294 
3295  /**
3296  * Returns true if the string is both external and two-byte.
3297  */
3298  bool IsExternalTwoByte() const;
3299 
3300  /**
3301  * Returns true if the string is both external and one-byte.
3302  */
3303  bool IsExternalOneByte() const;
3304 
3306  public:
3307  virtual ~ExternalStringResourceBase() = default;
3308 
3309  /**
3310  * If a string is cacheable, the value returned by
3311  * ExternalStringResource::data() may be cached, otherwise it is not
3312  * expected to be stable beyond the current top-level task.
3313  */
3314  virtual bool IsCacheable() const { return true; }
3315 
3316  // Disallow copying and assigning.
3318  void operator=(const ExternalStringResourceBase&) = delete;
3319 
3320  protected:
3322 
3323  /**
3324  * Internally V8 will call this Dispose method when the external string
3325  * resource is no longer needed. The default implementation will use the
3326  * delete operator. This method can be overridden in subclasses to
3327  * control how allocated external string resources are disposed.
3328  */
3329  virtual void Dispose() { delete this; }
3330 
3331  /**
3332  * For a non-cacheable string, the value returned by
3333  * |ExternalStringResource::data()| has to be stable between |Lock()| and
3334  * |Unlock()|, that is the string must behave as is |IsCacheable()| returned
3335  * true.
3336  *
3337  * These two functions must be thread-safe, and can be called from anywhere.
3338  * They also must handle lock depth, in the sense that each can be called
3339  * several times, from different threads, and unlocking should only happen
3340  * when the balance of Lock() and Unlock() calls is 0.
3341  */
3342  virtual void Lock() const {}
3343 
3344  /**
3345  * Unlocks the string.
3346  */
3347  virtual void Unlock() const {}
3348 
3349  private:
3350  friend class internal::ExternalString;
3351  friend class v8::String;
3352  friend class internal::ScopedExternalStringLock;
3353  };
3354 
3355  /**
3356  * An ExternalStringResource is a wrapper around a two-byte string
3357  * buffer that resides outside V8's heap. Implement an
3358  * ExternalStringResource to manage the life cycle of the underlying
3359  * buffer. Note that the string data must be immutable.
3360  */
3362  : public ExternalStringResourceBase {
3363  public:
3364  /**
3365  * Override the destructor to manage the life cycle of the underlying
3366  * buffer.
3367  */
3368  ~ExternalStringResource() override = default;
3369 
3370  /**
3371  * The string data from the underlying buffer. If the resource is cacheable
3372  * then data() must return the same value for all invocations.
3373  */
3374  virtual const uint16_t* data() const = 0;
3375 
3376  /**
3377  * The length of the string. That is, the number of two-byte characters.
3378  */
3379  virtual size_t length() const = 0;
3380 
3381  /**
3382  * Returns the cached data from the underlying buffer. This method can be
3383  * called only for cacheable resources (i.e. IsCacheable() == true) and only
3384  * after UpdateDataCache() was called.
3385  */
3386  const uint16_t* cached_data() const {
3387  CheckCachedDataInvariants();
3388  return cached_data_;
3389  }
3390 
3391  /**
3392  * Update {cached_data_} with the data from the underlying buffer. This can
3393  * be called only for cacheable resources.
3394  */
3396 
3397  protected:
3399 
3400  private:
3401  void CheckCachedDataInvariants() const;
3402 
3403  const uint16_t* cached_data_ = nullptr;
3404  };
3405 
3406  /**
3407  * An ExternalOneByteStringResource is a wrapper around an one-byte
3408  * string buffer that resides outside V8's heap. Implement an
3409  * ExternalOneByteStringResource to manage the life cycle of the
3410  * underlying buffer. Note that the string data must be immutable
3411  * and that the data must be Latin-1 and not UTF-8, which would require
3412  * special treatment internally in the engine and do not allow efficient
3413  * indexing. Use String::New or convert to 16 bit data for non-Latin1.
3414  */
3415 
3417  : public ExternalStringResourceBase {
3418  public:
3419  /**
3420  * Override the destructor to manage the life cycle of the underlying
3421  * buffer.
3422  */
3423  ~ExternalOneByteStringResource() override = default;
3424 
3425  /**
3426  * The string data from the underlying buffer. If the resource is cacheable
3427  * then data() must return the same value for all invocations.
3428  */
3429  virtual const char* data() const = 0;
3430 
3431  /** The number of Latin-1 characters in the string.*/
3432  virtual size_t length() const = 0;
3433 
3434  /**
3435  * Returns the cached data from the underlying buffer. If the resource is
3436  * uncacheable or if UpdateDataCache() was not called before, it has
3437  * undefined behaviour.
3438  */
3439  const char* cached_data() const {
3440  CheckCachedDataInvariants();
3441  return cached_data_;
3442  }
3443 
3444  /**
3445  * Update {cached_data_} with the data from the underlying buffer. This can
3446  * be called only for cacheable resources.
3447  */
3449 
3450  protected:
3452 
3453  private:
3454  void CheckCachedDataInvariants() const;
3455 
3456  const char* cached_data_ = nullptr;
3457  };
3458 
3459  /**
3460  * If the string is an external string, return the ExternalStringResourceBase
3461  * regardless of the encoding, otherwise return NULL. The encoding of the
3462  * string is returned in encoding_out.
3463  */
3465  Encoding* encoding_out) const;
3466 
3467  /**
3468  * Get the ExternalStringResource for an external string. Returns
3469  * NULL if IsExternal() doesn't return true.
3470  */
3472 
3473  /**
3474  * Get the ExternalOneByteStringResource for an external one-byte string.
3475  * Returns NULL if IsExternalOneByte() doesn't return true.
3476  */
3478 
3479  V8_INLINE static String* Cast(v8::Data* data);
3480 
3481  /**
3482  * Allocates a new string from a UTF-8 literal. This is equivalent to calling
3483  * String::NewFromUtf(isolate, "...").ToLocalChecked(), but without the check
3484  * overhead.
3485  *
3486  * When called on a string literal containing '\0', the inferred length is the
3487  * length of the input array minus 1 (for the final '\0') and not the value
3488  * returned by strlen.
3489  **/
3490  template <int N>
3492  Isolate* isolate, const char (&literal)[N],
3494  static_assert(N <= kMaxLength, "String is too long");
3495  return NewFromUtf8Literal(isolate, literal, type, N - 1);
3496  }
3497 
3498  /** Allocates a new string from UTF-8 data. Only returns an empty value when
3499  * length > kMaxLength. **/
3501  Isolate* isolate, const char* data,
3502  NewStringType type = NewStringType::kNormal, int length = -1);
3503 
3504  /** Allocates a new string from Latin-1 data. Only returns an empty value
3505  * when length > kMaxLength. **/
3507  Isolate* isolate, const uint8_t* data,
3508  NewStringType type = NewStringType::kNormal, int length = -1);
3509 
3510  /** Allocates a new string from UTF-16 data. Only returns an empty value when
3511  * length > kMaxLength. **/
3513  Isolate* isolate, const uint16_t* data,
3514  NewStringType type = NewStringType::kNormal, int length = -1);
3515 
3516  /**
3517  * Creates a new string by concatenating the left and the right strings
3518  * passed in as parameters.
3519  */
3520  static Local<String> Concat(Isolate* isolate, Local<String> left,
3521  Local<String> right);
3522 
3523  /**
3524  * Creates a new external string using the data defined in the given
3525  * resource. When the external string is no longer live on V8's heap the
3526  * resource will be disposed by calling its Dispose method. The caller of
3527  * this function should not otherwise delete or modify the resource. Neither
3528  * should the underlying buffer be deallocated or modified except through the
3529  * destructor of the external string resource.
3530  */
3532  Isolate* isolate, ExternalStringResource* resource);
3533 
3534  /**
3535  * Associate an external string resource with this string by transforming it
3536  * in place so that existing references to this string in the JavaScript heap
3537  * will use the external string resource. The external string resource's
3538  * character contents need to be equivalent to this string.
3539  * Returns true if the string has been changed to be an external string.
3540  * The string is not modified if the operation fails. See NewExternal for
3541  * information on the lifetime of the resource.
3542  */
3544 
3545  /**
3546  * Creates a new external string using the one-byte data defined in the given
3547  * resource. When the external string is no longer live on V8's heap the
3548  * resource will be disposed by calling its Dispose method. The caller of
3549  * this function should not otherwise delete or modify the resource. Neither
3550  * should the underlying buffer be deallocated or modified except through the
3551  * destructor of the external string resource.
3552  */
3554  Isolate* isolate, ExternalOneByteStringResource* resource);
3555 
3556  /**
3557  * Associate an external string resource with this string by transforming it
3558  * in place so that existing references to this string in the JavaScript heap
3559  * will use the external string resource. The external string resource's
3560  * character contents need to be equivalent to this string.
3561  * Returns true if the string has been changed to be an external string.
3562  * The string is not modified if the operation fails. See NewExternal for
3563  * information on the lifetime of the resource.
3564  */
3566 
3567  /**
3568  * Returns true if this string can be made external.
3569  */
3570  bool CanMakeExternal() const;
3571 
3572  /**
3573  * Returns true if the strings values are equal. Same as JS ==/===.
3574  */
3575  bool StringEquals(Local<String> str) const;
3576 
3577  /**
3578  * Converts an object to a UTF-8-encoded character array. Useful if
3579  * you want to print the object. If conversion to a string fails
3580  * (e.g. due to an exception in the toString() method of the object)
3581  * then the length() method returns 0 and the * operator returns
3582  * NULL.
3583  */
3585  public:
3586  Utf8Value(Isolate* isolate, Local<v8::Value> obj);
3588  char* operator*() { return str_; }
3589  const char* operator*() const { return str_; }
3590  int length() const { return length_; }
3591 
3592  // Disallow copying and assigning.
3593  Utf8Value(const Utf8Value&) = delete;
3594  void operator=(const Utf8Value&) = delete;
3595 
3596  private:
3597  char* str_;
3598  int length_;
3599  };
3600 
3601  /**
3602  * Converts an object to a two-byte (UTF-16-encoded) string.
3603  * If conversion to a string fails (eg. due to an exception in the toString()
3604  * method of the object) then the length() method returns 0 and the * operator
3605  * returns NULL.
3606  */
3608  public:
3609  Value(Isolate* isolate, Local<v8::Value> obj);
3610  ~Value();
3611  uint16_t* operator*() { return str_; }
3612  const uint16_t* operator*() const { return str_; }
3613  int length() const { return length_; }
3614 
3615  // Disallow copying and assigning.
3616  Value(const Value&) = delete;
3617  void operator=(const Value&) = delete;
3618 
3619  private:
3620  uint16_t* str_;
3621  int length_;
3622  };
3623 
3624  private:
3625  void VerifyExternalStringResourceBase(ExternalStringResourceBase* v,
3626  Encoding encoding) const;
3627  void VerifyExternalStringResource(ExternalStringResource* val) const;
3628  ExternalStringResource* GetExternalStringResourceSlow() const;
3629  ExternalStringResourceBase* GetExternalStringResourceBaseSlow(
3630  String::Encoding* encoding_out) const;
3631 
3632  static Local<v8::String> NewFromUtf8Literal(Isolate* isolate,
3633  const char* literal,
3634  NewStringType type, int length);
3635 
3636  static void CheckCast(v8::Data* that);
3637 };
3638 
3639 // Zero-length string specialization (templated string size includes
3640 // terminator).
3641 template <>
3643  Isolate* isolate, const char (&literal)[1], NewStringType type) {
3644  return String::Empty(isolate);
3645 }
3646 
3647 /**
3648  * A JavaScript symbol (ECMA-262 edition 6)
3649  */
3650 class V8_EXPORT Symbol : public Name {
3651  public:
3652  /**
3653  * Returns the description string of the symbol, or undefined if none.
3654  */
3655  V8_DEPRECATE_SOON("Use Symbol::Description(isolate)")
3657  Local<Value> Description(Isolate* isolate) const;
3658 
3659  /**
3660  * Create a symbol. If description is not empty, it will be used as the
3661  * description.
3662  */
3663  static Local<Symbol> New(Isolate* isolate,
3664  Local<String> description = Local<String>());
3665 
3666  /**
3667  * Access global symbol registry.
3668  * Note that symbols created this way are never collected, so
3669  * they should only be used for statically fixed properties.
3670  * Also, there is only one global name space for the descriptions used as
3671  * keys.
3672  * To minimize the potential for clashes, use qualified names as keys.
3673  */
3674  static Local<Symbol> For(Isolate* isolate, Local<String> description);
3675 
3676  /**
3677  * Retrieve a global symbol. Similar to |For|, but using a separate
3678  * registry that is not accessible by (and cannot clash with) JavaScript code.
3679  */
3680  static Local<Symbol> ForApi(Isolate* isolate, Local<String> description);
3681 
3682  // Well-known symbols
3684  static Local<Symbol> GetHasInstance(Isolate* isolate);
3686  static Local<Symbol> GetIterator(Isolate* isolate);
3687  static Local<Symbol> GetMatch(Isolate* isolate);
3688  static Local<Symbol> GetReplace(Isolate* isolate);
3689  static Local<Symbol> GetSearch(Isolate* isolate);
3690  static Local<Symbol> GetSplit(Isolate* isolate);
3691  static Local<Symbol> GetToPrimitive(Isolate* isolate);
3692  static Local<Symbol> GetToStringTag(Isolate* isolate);
3693  static Local<Symbol> GetUnscopables(Isolate* isolate);
3694 
3695  V8_INLINE static Symbol* Cast(Data* data);
3696 
3697  private:
3698  Symbol();
3699  static void CheckCast(Data* that);
3700 };
3701 
3702 
3703 /**
3704  * A private symbol
3705  *
3706  * This is an experimental feature. Use at your own risk.
3707  */
3708 class V8_EXPORT Private : public Data {
3709  public:
3710  /**
3711  * Returns the print name string of the private symbol, or undefined if none.
3712  */
3713  Local<Value> Name() const;
3714 
3715  /**
3716  * Create a private symbol. If name is not empty, it will be the description.
3717  */
3718  static Local<Private> New(Isolate* isolate,
3719  Local<String> name = Local<String>());
3720 
3721  /**
3722  * Retrieve a global private symbol. If a symbol with this name has not
3723  * been retrieved in the same isolate before, it is created.
3724  * Note that private symbols created this way are never collected, so
3725  * they should only be used for statically fixed properties.
3726  * Also, there is only one global name space for the names used as keys.
3727  * To minimize the potential for clashes, use qualified names as keys,
3728  * e.g., "Class#property".
3729  */
3730  static Local<Private> ForApi(Isolate* isolate, Local<String> name);
3731 
3732  V8_INLINE static Private* Cast(Data* data);
3733 
3734  private:
3735  Private();
3736 
3737  static void CheckCast(Data* that);
3738 };
3739 
3740 
3741 /**
3742  * A JavaScript number value (ECMA-262, 4.3.20)
3743  */
3744 class V8_EXPORT Number : public Primitive {
3745  public:
3746  double Value() const;
3747  static Local<Number> New(Isolate* isolate, double value);
3748  V8_INLINE static Number* Cast(v8::Data* data);
3749 
3750  private:
3751  Number();
3752  static void CheckCast(v8::Data* that);
3753 };
3754 
3755 
3756 /**
3757  * A JavaScript value representing a signed integer.
3758  */
3759 class V8_EXPORT Integer : public Number {
3760  public:
3761  static Local<Integer> New(Isolate* isolate, int32_t value);
3762  static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value);
3763  int64_t Value() const;
3764  V8_INLINE static Integer* Cast(v8::Data* data);
3765 
3766  private:
3767  Integer();
3768  static void CheckCast(v8::Data* that);
3769 };
3770 
3771 
3772 /**
3773  * A JavaScript value representing a 32-bit signed integer.
3774  */
3775 class V8_EXPORT Int32 : public Integer {
3776  public:
3777  int32_t Value() const;
3778  V8_INLINE static Int32* Cast(v8::Data* data);
3779 
3780  private:
3781  Int32();
3782  static void CheckCast(v8::Data* that);
3783 };
3784 
3785 
3786 /**
3787  * A JavaScript value representing a 32-bit unsigned integer.
3788  */
3789 class V8_EXPORT Uint32 : public Integer {
3790  public:
3791  uint32_t Value() const;
3792  V8_INLINE static Uint32* Cast(v8::Data* data);
3793 
3794  private:
3795  Uint32();
3796  static void CheckCast(v8::Data* that);
3797 };
3798 
3799 /**
3800  * A JavaScript BigInt value (https://tc39.github.io/proposal-bigint)
3801  */
3802 class V8_EXPORT BigInt : public Primitive {
3803  public:
3804  static Local<BigInt> New(Isolate* isolate, int64_t value);
3805  static Local<BigInt> NewFromUnsigned(Isolate* isolate, uint64_t value);
3806  /**
3807  * Creates a new BigInt object using a specified sign bit and a
3808  * specified list of digits/words.
3809  * The resulting number is calculated as:
3810  *
3811  * (-1)^sign_bit * (words[0] * (2^64)^0 + words[1] * (2^64)^1 + ...)
3812  */
3813  static MaybeLocal<BigInt> NewFromWords(Local<Context> context, int sign_bit,
3814  int word_count, const uint64_t* words);
3815 
3816  /**
3817  * Returns the value of this BigInt as an unsigned 64-bit integer.
3818  * If `lossless` is provided, it will reflect whether the return value was
3819  * truncated or wrapped around. In particular, it is set to `false` if this
3820  * BigInt is negative.
3821  */
3822  uint64_t Uint64Value(bool* lossless = nullptr) const;
3823 
3824  /**
3825  * Returns the value of this BigInt as a signed 64-bit integer.
3826  * If `lossless` is provided, it will reflect whether this BigInt was
3827  * truncated or not.
3828  */
3829  int64_t Int64Value(bool* lossless = nullptr) const;
3830 
3831  /**
3832  * Returns the number of 64-bit words needed to store the result of
3833  * ToWordsArray().
3834  */
3835  int WordCount() const;
3836 
3837  /**
3838  * Writes the contents of this BigInt to a specified memory location.
3839  * `sign_bit` must be provided and will be set to 1 if this BigInt is
3840  * negative.
3841  * `*word_count` has to be initialized to the length of the `words` array.
3842  * Upon return, it will be set to the actual number of words that would
3843  * be needed to store this BigInt (i.e. the return value of `WordCount()`).
3844  */
3845  void ToWordsArray(int* sign_bit, int* word_count, uint64_t* words) const;
3846 
3847  V8_INLINE static BigInt* Cast(v8::Data* data);
3848 
3849  private:
3850  BigInt();
3851  static void CheckCast(v8::Data* that);
3852 };
3853 
3854 /**
3855  * PropertyAttribute.
3856  */
3858  /** None. **/
3859  None = 0,
3860  /** ReadOnly, i.e., not writable. **/
3861  ReadOnly = 1 << 0,
3862  /** DontEnum, i.e., not enumerable. **/
3863  DontEnum = 1 << 1,
3864  /** DontDelete, i.e., not configurable. **/
3865  DontDelete = 1 << 2
3866 };
3867 
3868 /**
3869  * Accessor[Getter|Setter] are used as callback functions when
3870  * setting|getting a particular property. See Object and ObjectTemplate's
3871  * method SetAccessor.
3872  */
3873 using AccessorGetterCallback =
3874  void (*)(Local<String> property, const PropertyCallbackInfo<Value>& info);
3875 using AccessorNameGetterCallback =
3876  void (*)(Local<Name> property, const PropertyCallbackInfo<Value>& info);
3877 
3878 using AccessorSetterCallback = void (*)(Local<String> property,
3879  Local<Value> value,
3880  const PropertyCallbackInfo<void>& info);
3881 using AccessorNameSetterCallback =
3882  void (*)(Local<Name> property, Local<Value> value,
3883  const PropertyCallbackInfo<void>& info);
3884 
3885 /**
3886  * Access control specifications.
3887  *
3888  * Some accessors should be accessible across contexts. These
3889  * accessors have an explicit access control parameter which specifies
3890  * the kind of cross-context access that should be allowed.
3891  *
3892  * TODO(dcarney): Remove PROHIBITS_OVERWRITING as it is now unused.
3893  */
3895  DEFAULT = 0,
3897  ALL_CAN_WRITE = 1 << 1,
3898  PROHIBITS_OVERWRITING = 1 << 2
3899 };
3900 
3901 /**
3902  * Property filter bits. They can be or'ed to build a composite filter.
3903  */
3910  SKIP_SYMBOLS = 16
3911 };
3912 
3913 /**
3914  * Options for marking whether callbacks may trigger JS-observable side effects.
3915  * Side-effect-free callbacks are allowlisted during debug evaluation with
3916  * throwOnSideEffect. It applies when calling a Function, FunctionTemplate,
3917  * or an Accessor callback. For Interceptors, please see
3918  * PropertyHandlerFlags's kHasNoSideEffect.
3919  * Callbacks that only cause side effects to the receiver are allowlisted if
3920  * invoked on receiver objects that are created within the same debug-evaluate
3921  * call, as these objects are temporary and the side effect does not escape.
3922  */
3923 enum class SideEffectType {
3927 };
3928 
3929 /**
3930  * Keys/Properties filter enums:
3931  *
3932  * KeyCollectionMode limits the range of collected properties. kOwnOnly limits
3933  * the collected properties to the given Object only. kIncludesPrototypes will
3934  * include all keys of the objects's prototype chain as well.
3935  */
3937 
3938 /**
3939  * kIncludesIndices allows for integer indices to be collected, while
3940  * kSkipIndices will exclude integer indices from being collected.
3941  */
3943 
3944 /**
3945  * kConvertToString will convert integer indices to strings.
3946  * kKeepNumbers will return numbers for integer indices.
3947  */
3949 
3950 /**
3951  * Integrity level for objects.
3952  */
3954 
3955 /**
3956  * A JavaScript object (ECMA-262, 4.3.3)
3957  */
3958 class V8_EXPORT Object : public Value {
3959  public:
3960  /**
3961  * Set only return Just(true) or Empty(), so if it should never fail, use
3962  * result.Check().
3963  */
3965  Local<Value> key, Local<Value> value);
3966 
3967  V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context, uint32_t index,
3968  Local<Value> value);
3969 
3970  // Implements CreateDataProperty (ECMA-262, 7.3.4).
3971  //
3972  // Defines a configurable, writable, enumerable property with the given value
3973  // on the object unless the property already exists and is not configurable
3974  // or the object is not extensible.
3975  //
3976  // Returns true on success.
3978  Local<Name> key,
3979  Local<Value> value);
3981  uint32_t index,
3982  Local<Value> value);
3983 
3984  // Implements DefineOwnProperty.
3985  //
3986  // In general, CreateDataProperty will be faster, however, does not allow
3987  // for specifying attributes.
3988  //
3989  // Returns true on success.
3991  Local<Context> context, Local<Name> key, Local<Value> value,
3992  PropertyAttribute attributes = None);
3993 
3994  // Implements Object.DefineProperty(O, P, Attributes), see Ecma-262 19.1.2.4.
3995  //
3996  // The defineProperty function is used to add an own property or
3997  // update the attributes of an existing own property of an object.
3998  //
3999  // Both data and accessor descriptors can be used.
4000  //
4001  // In general, CreateDataProperty is faster, however, does not allow
4002  // for specifying attributes or an accessor descriptor.
4003  //
4004  // The PropertyDescriptor can change when redefining a property.
4005  //
4006  // Returns true on success.
4008  Local<Context> context, Local<Name> key, PropertyDescriptor& descriptor);
4009 
4011  Local<Value> key);
4012 
4014  uint32_t index);
4015 
4016  /**
4017  * Gets the property attributes of a property which can be None or
4018  * any combination of ReadOnly, DontEnum and DontDelete. Returns
4019  * None when the property doesn't exist.
4020  */
4022  Local<Context> context, Local<Value> key);
4023 
4024  /**
4025  * Returns Object.getOwnPropertyDescriptor as per ES2016 section 19.1.2.6.
4026  */
4028  Local<Context> context, Local<Name> key);
4029 
4030  /**
4031  * Object::Has() calls the abstract operation HasProperty(O, P) described
4032  * in ECMA-262, 7.3.10. Has() returns
4033  * true, if the object has the property, either own or on the prototype chain.
4034  * Interceptors, i.e., PropertyQueryCallbacks, are called if present.
4035  *
4036  * Has() has the same side effects as JavaScript's `variable in object`.
4037  * For example, calling Has() on a revoked proxy will throw an exception.
4038  *
4039  * \note Has() converts the key to a name, which possibly calls back into
4040  * JavaScript.
4041  *
4042  * See also v8::Object::HasOwnProperty() and
4043  * v8::Object::HasRealNamedProperty().
4044  */
4046  Local<Value> key);
4047 
4049  Local<Value> key);
4050 
4051  V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context, uint32_t index);
4052 
4054  uint32_t index);
4055 
4056  /**
4057  * Note: SideEffectType affects the getter only, not the setter.
4058  */
4060  Local<Context> context, Local<Name> name,
4061  AccessorNameGetterCallback getter,
4062  AccessorNameSetterCallback setter = nullptr,
4064  AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
4065  SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
4066  SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
4067 
4069  Local<Function> setter = Local<Function>(),
4070  PropertyAttribute attribute = None,
4071  AccessControl settings = DEFAULT);
4072 
4073  /**
4074  * Sets a native data property like Template::SetNativeDataProperty, but
4075  * this method sets on this object directly.
4076  */
4078  Local<Context> context, Local<Name> name,
4079  AccessorNameGetterCallback getter,
4080  AccessorNameSetterCallback setter = nullptr,
4081  Local<Value> data = Local<Value>(), PropertyAttribute attributes = None,
4082  SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
4083  SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
4084 
4085  /**
4086  * Attempts to create a property with the given name which behaves like a data
4087  * property, except that the provided getter is invoked (and provided with the
4088  * data value) to supply its value the first time it is read. After the
4089  * property is accessed once, it is replaced with an ordinary data property.
4090  *
4091  * Analogous to Template::SetLazyDataProperty.
4092  */
4094  Local<Context> context, Local<Name> name,
4095  AccessorNameGetterCallback getter, Local<Value> data = Local<Value>(),
4096  PropertyAttribute attributes = None,
4097  SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
4098  SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
4099 
4100  /**
4101  * Functionality for private properties.
4102  * This is an experimental feature, use at your own risk.
4103  * Note: Private properties are not inherited. Do not rely on this, since it
4104  * may change.
4105  */
4106  Maybe<bool> HasPrivate(Local<Context> context, Local<Private> key);
4107  Maybe<bool> SetPrivate(Local<Context> context, Local<Private> key,
4108  Local<Value> value);
4111 
4112  /**
4113  * Returns an array containing the names of the enumerable properties
4114  * of this object, including properties from prototype objects. The
4115  * array returned by this method contains the same values as would
4116  * be enumerated by a for-in statement over this object.
4117  */
4119  Local<Context> context);
4121  Local<Context> context, KeyCollectionMode mode,
4122  PropertyFilter property_filter, IndexFilter index_filter,
4124 
4125  /**
4126  * This function has the same functionality as GetPropertyNames but
4127  * the returned array doesn't contain the names of properties from
4128  * prototype objects.
4129  */
4131  Local<Context> context);
4132 
4133  /**
4134  * Returns an array containing the names of the filtered properties
4135  * of this object, including properties from prototype objects. The
4136  * array returned by this method contains the same values as would
4137  * be enumerated by a for-in statement over this object.
4138  */
4140  Local<Context> context, PropertyFilter filter,
4142 
4143  /**
4144  * Get the prototype object. This does not skip objects marked to
4145  * be skipped by __proto__ and it does not consult the security
4146  * handler.
4147  */
4149 
4150  /**
4151  * Set the prototype object. This does not skip objects marked to
4152  * be skipped by __proto__ and it does not consult the security
4153  * handler.
4154  */
4156  Local<Value> prototype);
4157 
4158  /**
4159  * Finds an instance of the given function template in the prototype
4160  * chain.
4161  */
4163 
4164  /**
4165  * Call builtin Object.prototype.toString on this object.
4166  * This is different from Value::ToString() that may call
4167  * user-defined toString function. This one does not.
4168  */
4170  Local<Context> context);
4171 
4172  /**
4173  * Returns the name of the function invoked as a constructor for this object.
4174  */
4176 
4177  /**
4178  * Sets the integrity level of the object.
4179  */
4181 
4182  /** Gets the number of internal fields for this Object. */
4183  int InternalFieldCount() const;
4184 
4185  /** Same as above, but works for PersistentBase. */
4187  const PersistentBase<Object>& object) {
4188  return object.val_->InternalFieldCount();
4189  }
4190 
4191  /** Same as above, but works for BasicTracedReference. */
4193  const BasicTracedReference<Object>& object) {
4194  return object->InternalFieldCount();
4195  }
4196 
4197  /** Gets the value from an internal field. */
4198  V8_INLINE Local<Value> GetInternalField(int index);
4199 
4200  /** Sets the value in an internal field. */
4201  void SetInternalField(int index, Local<Value> value);
4202 
4203  /**
4204  * Gets a 2-byte-aligned native pointer from an internal field. This field
4205  * must have been set by SetAlignedPointerInInternalField, everything else
4206  * leads to undefined behavior.
4207  */
4209 
4210  /** Same as above, but works for PersistentBase. */
4212  const PersistentBase<Object>& object, int index) {
4213  return object.val_->GetAlignedPointerFromInternalField(index);
4214  }
4215 
4216  /** Same as above, but works for TracedGlobal. */
4218  const BasicTracedReference<Object>& object, int index) {
4219  return object->GetAlignedPointerFromInternalField(index);
4220  }
4221 
4222  /**
4223  * Sets a 2-byte-aligned native pointer in an internal field. To retrieve such
4224  * a field, GetAlignedPointerFromInternalField must be used, everything else
4225  * leads to undefined behavior.
4226  */
4227  void SetAlignedPointerInInternalField(int index, void* value);
4228  void SetAlignedPointerInInternalFields(int argc, int indices[],
4229  void* values[]);
4230 
4231  /**
4232  * HasOwnProperty() is like JavaScript's Object.prototype.hasOwnProperty().
4233  *
4234  * See also v8::Object::Has() and v8::Object::HasRealNamedProperty().
4235  */
4237  Local<Name> key);
4239  uint32_t index);
4240  /**
4241  * Use HasRealNamedProperty() if you want to check if an object has an own
4242  * property without causing side effects, i.e., without calling interceptors.
4243  *
4244  * This function is similar to v8::Object::HasOwnProperty(), but it does not
4245  * call interceptors.
4246  *
4247  * \note Consider using non-masking interceptors, i.e., the interceptors are
4248  * not called if the receiver has the real named property. See
4249  * `v8::PropertyHandlerFlags::kNonMasking`.
4250  *
4251  * See also v8::Object::Has().
4252  */
4254  Local<Name> key);
4256  Local<Context> context, uint32_t index);
4258  Local<Context> context, Local<Name> key);
4259 
4260  /**
4261  * If result.IsEmpty() no real property was located in the prototype chain.
4262  * This means interceptors in the prototype chain are not called.
4263  */
4265  Local<Context> context, Local<Name> key);
4266 
4267  /**
4268  * Gets the property attributes of a real property in the prototype chain,
4269  * which can be None or any combination of ReadOnly, DontEnum and DontDelete.
4270  * Interceptors in the prototype chain are not called.
4271  */
4274  Local<Name> key);
4275 
4276  /**
4277  * If result.IsEmpty() no real property was located on the object or
4278  * in the prototype chain.
4279  * This means interceptors in the prototype chain are not called.
4280  */
4282  Local<Context> context, Local<Name> key);
4283 
4284  /**
4285  * Gets the property attributes of a real property which can be
4286  * None or any combination of ReadOnly, DontEnum and DontDelete.
4287  * Interceptors in the prototype chain are not called.
4288  */
4290  Local<Context> context, Local<Name> key);
4291 
4292  /** Tests for a named lookup interceptor.*/
4294 
4295  /** Tests for an index lookup interceptor.*/
4297 
4298  /**
4299  * Returns the identity hash for this object. The current implementation
4300  * uses a hidden property on the object to store the identity hash.
4301  *
4302  * The return value will never be 0. Also, it is not guaranteed to be
4303  * unique.
4304  */
4306 
4307  /**
4308  * Clone this object with a fast but shallow copy. Values will point
4309  * to the same values as the original object.
4310  */
4311  // TODO(dcarney): take an isolate and optionally bail out?
4313 
4314  /**
4315  * Returns the context in which the object was created.
4316  */
4317  // TODO(chromium:1166077): Mark as deprecate once users are updated.
4318  V8_DEPRECATE_SOON("Use MaybeLocal<Context> GetCreationContext()")
4321 
4322  /** Same as above, but works for Persistents */
4323  // TODO(chromium:1166077): Mark as deprecate once users are updated.
4325  "Use MaybeLocal<Context> GetCreationContext(const "
4326  "PersistentBase<Object>& object)")
4327  static Local<Context> CreationContext(const PersistentBase<Object>& object);
4329  const PersistentBase<Object>& object) {
4330  return object.val_->GetCreationContext();
4331  }
4332 
4333  /**
4334  * Checks whether a callback is set by the
4335  * ObjectTemplate::SetCallAsFunctionHandler method.
4336  * When an Object is callable this method returns true.
4337  */
4338  bool IsCallable() const;
4339 
4340  /**
4341  * True if this object is a constructor.
4342  */
4343  bool IsConstructor() const;
4344 
4345  /**
4346  * True if this object can carry information relevant to the embedder in its
4347  * embedder fields, false otherwise. This is generally true for objects
4348  * constructed through function templates but also holds for other types where
4349  * V8 automatically adds internal fields at compile time, such as e.g.
4350  * v8::ArrayBuffer.
4351  */
4352  bool IsApiWrapper() const;
4353 
4354  /**
4355  * True if this object was created from an object template which was marked
4356  * as undetectable. See v8::ObjectTemplate::MarkAsUndetectable for more
4357  * information.
4358  */
4359  bool IsUndetectable() const;
4360 
4361  /**
4362  * Call an Object as a function if a callback is set by the
4363  * ObjectTemplate::SetCallAsFunctionHandler method.
4364  */
4366  Local<Value> recv,
4367  int argc,
4368  Local<Value> argv[]);
4369 
4370  /**
4371  * Call an Object as a constructor if a callback is set by the
4372  * ObjectTemplate::SetCallAsFunctionHandler method.
4373  * Note: This method behaves like the Function::NewInstance method.
4374  */
4376  Local<Context> context, int argc, Local<Value> argv[]);
4377 
4378  /**
4379  * Return the isolate to which the Object belongs to.
4380  */
4382 
4383  /**
4384  * If this object is a Set, Map, WeakSet or WeakMap, this returns a
4385  * representation of the elements of this object as an array.
4386  * If this object is a SetIterator or MapIterator, this returns all
4387  * elements of the underlying collection, starting at the iterator's current
4388  * position.
4389  * For other types, this will return an empty MaybeLocal<Array> (without
4390  * scheduling an exception).
4391  */
4392  MaybeLocal<Array> PreviewEntries(bool* is_key_value);
4393 
4394  static Local<Object> New(Isolate* isolate);
4395 
4396  /**
4397  * Creates a JavaScript object with the given properties, and
4398  * a the given prototype_or_null (which can be any JavaScript
4399  * value, and if it's null, the newly created object won't have
4400  * a prototype at all). This is similar to Object.create().
4401  * All properties will be created as enumerable, configurable
4402  * and writable properties.
4403  */
4404  static Local<Object> New(Isolate* isolate, Local<Value> prototype_or_null,
4405  Local<Name>* names, Local<Value>* values,
4406  size_t length);
4407 
4408  V8_INLINE static Object* Cast(Value* obj);
4409 
4410  /**
4411  * Support for TC39 "dynamic code brand checks" proposal.
4412  *
4413  * This API allows to query whether an object was constructed from a
4414  * "code like" ObjectTemplate.
4415  *
4416  * See also: v8::ObjectTemplate::SetCodeLike
4417  */
4418  bool IsCodeLike(Isolate* isolate) const;
4419 
4420  private:
4421  Object();
4422  static void CheckCast(Value* obj);
4423  Local<Value> SlowGetInternalField(int index);
4424  void* SlowGetAlignedPointerFromInternalField(int index);
4425 };
4426 
4427 
4428 /**
4429  * An instance of the built-in array constructor (ECMA-262, 15.4.2).
4430  */
4431 class V8_EXPORT Array : public Object {
4432  public:
4433  uint32_t Length() const;
4434 
4435  /**
4436  * Creates a JavaScript array with the given length. If the length
4437  * is negative the returned array will have length 0.
4438  */
4439  static Local<Array> New(Isolate* isolate, int length = 0);
4440 
4441  /**
4442  * Creates a JavaScript array out of a Local<Value> array in C++
4443  * with a known length.
4444  */
4445  static Local<Array> New(Isolate* isolate, Local<Value>* elements,
4446  size_t length);
4447  V8_INLINE static Array* Cast(Value* obj);
4448 
4449  private:
4450  Array();
4451  static void CheckCast(Value* obj);
4452 };
4453 
4454 
4455 /**
4456  * An instance of the built-in Map constructor (ECMA-262, 6th Edition, 23.1.1).
4457  */
4458 class V8_EXPORT Map : public Object {
4459  public:
4460  size_t Size() const;
4461  void Clear();
4463  Local<Value> key);
4465  Local<Value> key,
4466  Local<Value> value);
4468  Local<Value> key);
4470  Local<Value> key);
4471 
4472  /**
4473  * Returns an array of length Size() * 2, where index N is the Nth key and
4474  * index N + 1 is the Nth value.
4475  */
4476  Local<Array> AsArray() const;
4477 
4478  /**
4479  * Creates a new empty Map.
4480  */
4481  static Local<Map> New(Isolate* isolate);
4482 
4483  V8_INLINE static Map* Cast(Value* obj);
4484 
4485  private:
4486  Map();
4487  static void CheckCast(Value* obj);
4488 };
4489 
4490 
4491 /**
4492  * An instance of the built-in Set constructor (ECMA-262, 6th Edition, 23.2.1).
4493  */
4494 class V8_EXPORT Set : public Object {
4495  public:
4496  size_t Size() const;
4497  void Clear();
4499  Local<Value> key);
4501  Local<Value> key);
4503  Local<Value> key);
4504 
4505  /**
4506  * Returns an array of the keys in this Set.
4507  */
4508  Local<Array> AsArray() const;
4509 
4510  /**
4511  * Creates a new empty Set.
4512  */
4513  static Local<Set> New(Isolate* isolate);
4514 
4515  V8_INLINE static Set* Cast(Value* obj);
4516 
4517  private:
4518  Set();
4519  static void CheckCast(Value* obj);
4520 };
4521 
4522 
4523 template<typename T>
4525  public:
4526  template <class S> V8_INLINE ReturnValue(const ReturnValue<S>& that)
4527  : value_(that.value_) {
4528  static_assert(std::is_base_of<T, S>::value, "type check");
4529  }
4530  // Local setters
4531  template <typename S>
4532  V8_INLINE void Set(const Global<S>& handle);
4533  template <typename S>
4534  V8_INLINE void Set(const BasicTracedReference<S>& handle);
4535  template <typename S>
4536  V8_INLINE void Set(const Local<S> handle);
4537  // Fast primitive setters
4538  V8_INLINE void Set(bool value);
4539  V8_INLINE void Set(double i);
4540  V8_INLINE void Set(int32_t i);
4541  V8_INLINE void Set(uint32_t i);
4542  // Fast JS primitive setters
4543  V8_INLINE void SetNull();
4544  V8_INLINE void SetUndefined();
4545  V8_INLINE void SetEmptyString();
4546  // Convenience getter for Isolate
4547  V8_INLINE Isolate* GetIsolate() const;
4548 
4549  // Pointer setter: Uncompilable to prevent inadvertent misuse.
4550  template <typename S>
4551  V8_INLINE void Set(S* whatever);
4552 
4553  // Getter. Creates a new Local<> so it comes with a certain performance
4554  // hit. If the ReturnValue was not yet set, this will return the undefined
4555  // value.
4556  V8_INLINE Local<Value> Get() const;
4557 
4558  private:
4559  template<class F> friend class ReturnValue;
4560  template<class F> friend class FunctionCallbackInfo;
4561  template<class F> friend class PropertyCallbackInfo;
4562  template <class F, class G, class H>
4564  V8_INLINE void SetInternal(internal::Address value) { *value_ = value; }
4565  V8_INLINE internal::Address GetDefaultValue();
4566  V8_INLINE explicit ReturnValue(internal::Address* slot);
4567  internal::Address* value_;
4568 };
4569 
4570 
4571 /**
4572  * The argument information given to function call callbacks. This
4573  * class provides access to information about the context of the call,
4574  * including the receiver, the number and values of arguments, and
4575  * the holder of the function.
4576  */
4577 template<typename T>
4579  public:
4580  /** The number of available arguments. */
4581  V8_INLINE int Length() const;
4582  /**
4583  * Accessor for the available arguments. Returns `undefined` if the index
4584  * is out of bounds.
4585  */
4586  V8_INLINE Local<Value> operator[](int i) const;
4587  /** Returns the receiver. This corresponds to the "this" value. */
4588  V8_INLINE Local<Object> This() const;
4589  /**
4590  * If the callback was created without a Signature, this is the same
4591  * value as This(). If there is a signature, and the signature didn't match
4592  * This() but one of its hidden prototypes, this will be the respective
4593  * hidden prototype.
4594  *
4595  * Note that this is not the prototype of This() on which the accessor
4596  * referencing this callback was found (which in V8 internally is often
4597  * referred to as holder [sic]).
4598  */
4599  V8_INLINE Local<Object> Holder() const;
4600  /** For construct calls, this returns the "new.target" value. */
4601  V8_INLINE Local<Value> NewTarget() const;
4602  /** Indicates whether this is a regular call or a construct call. */
4603  V8_INLINE bool IsConstructCall() const;
4604  /** The data argument specified when creating the callback. */
4605  V8_INLINE Local<Value> Data() const;
4606  /** The current Isolate. */
4607  V8_INLINE Isolate* GetIsolate() const;
4608  /** The ReturnValue for the call. */
4610  // This shouldn't be public, but the arm compiler needs it.
4611  static const int kArgsLength = 6;
4612 
4613  protected:
4614  friend class internal::FunctionCallbackArguments;
4616  friend class debug::ConsoleCallArguments;
4617  static const int kHolderIndex = 0;
4618  static const int kIsolateIndex = 1;
4619  static const int kReturnValueDefaultValueIndex = 2;
4620  static const int kReturnValueIndex = 3;
4621  static const int kDataIndex = 4;
4622  static const int kNewTargetIndex = 5;
4623 
4625  internal::Address* values, int length);
4628  int length_;
4629 };
4630 
4631 
4632 /**
4633  * The information passed to a property callback about the context
4634  * of the property access.
4635  */
4636 template<typename T>
4638  public:
4639  /**
4640  * \return The isolate of the property access.
4641  */
4643 
4644  /**
4645  * \return The data set in the configuration, i.e., in
4646  * `NamedPropertyHandlerConfiguration` or
4647  * `IndexedPropertyHandlerConfiguration.`
4648  */
4650 
4651  /**
4652  * \return The receiver. In many cases, this is the object on which the
4653  * property access was intercepted. When using
4654  * `Reflect.get`, `Function.prototype.call`, or similar functions, it is the
4655  * object passed in as receiver or thisArg.
4656  *
4657  * \code
4658  * void GetterCallback(Local<Name> name,
4659  * const v8::PropertyCallbackInfo<v8::Value>& info) {
4660  * auto context = info.GetIsolate()->GetCurrentContext();
4661  *
4662  * v8::Local<v8::Value> a_this =
4663  * info.This()
4664  * ->GetRealNamedProperty(context, v8_str("a"))
4665  * .ToLocalChecked();
4666  * v8::Local<v8::Value> a_holder =
4667  * info.Holder()
4668  * ->GetRealNamedProperty(context, v8_str("a"))
4669  * .ToLocalChecked();
4670  *
4671  * CHECK(v8_str("r")->Equals(context, a_this).FromJust());
4672  * CHECK(v8_str("obj")->Equals(context, a_holder).FromJust());
4673  *
4674  * info.GetReturnValue().Set(name);
4675  * }
4676  *
4677  * v8::Local<v8::FunctionTemplate> templ =
4678  * v8::FunctionTemplate::New(isolate);
4679  * templ->InstanceTemplate()->SetHandler(
4680  * v8::NamedPropertyHandlerConfiguration(GetterCallback));
4681  * LocalContext env;
4682  * env->Global()
4683  * ->Set(env.local(), v8_str("obj"), templ->GetFunction(env.local())
4684  * .ToLocalChecked()
4685  * ->NewInstance(env.local())
4686  * .ToLocalChecked())
4687  * .FromJust();
4688  *
4689  * CompileRun("obj.a = 'obj'; var r = {a: 'r'}; Reflect.get(obj, 'x', r)");
4690  * \endcode
4691  */
4693 
4694  /**
4695  * \return The object in the prototype chain of the receiver that has the
4696  * interceptor. Suppose you have `x` and its prototype is `y`, and `y`
4697  * has an interceptor. Then `info.This()` is `x` and `info.Holder()` is `y`.
4698  * The Holder() could be a hidden object (the global object, rather
4699  * than the global proxy).
4700  *
4701  * \note For security reasons, do not pass the object back into the runtime.
4702  */
4704 
4705  /**
4706  * \return The return value of the callback.
4707  * Can be changed by calling Set().
4708  * \code
4709  * info.GetReturnValue().Set(...)
4710  * \endcode
4711  *
4712  */
4714 
4715  /**
4716  * \return True if the intercepted function should throw if an error occurs.
4717  * Usually, `true` corresponds to `'use strict'`.
4718  *
4719  * \note Always `false` when intercepting `Reflect.set()`
4720  * independent of the language mode.
4721  */
4723 
4724  // This shouldn't be public, but the arm compiler needs it.
4725  static const int kArgsLength = 7;
4726 
4727  protected:
4728  friend class MacroAssembler;
4729  friend class internal::PropertyCallbackArguments;
4731  static const int kShouldThrowOnErrorIndex = 0;
4732  static const int kHolderIndex = 1;
4733  static const int kIsolateIndex = 2;
4734  static const int kReturnValueDefaultValueIndex = 3;
4735  static const int kReturnValueIndex = 4;
4736  static const int kDataIndex = 5;
4737  static const int kThisIndex = 6;
4738 
4741 };
4742 
4743 using FunctionCallback = void (*)(const FunctionCallbackInfo<Value>& info);
4744 
4746 
4747 /**
4748  * A JavaScript function object (ECMA-262, 15.3).
4749  */
4750 class V8_EXPORT Function : public Object {
4751  public:
4752  /**
4753  * Create a function in the current execution context
4754  * for a given FunctionCallback.
4755  */
4757  Local<Context> context, FunctionCallback callback,
4758  Local<Value> data = Local<Value>(), int length = 0,
4760  SideEffectType side_effect_type = SideEffectType::kHasSideEffect);
4761 
4763  Local<Context> context, int argc, Local<Value> argv[]) const;
4764 
4766  Local<Context> context) const {
4767  return NewInstance(context, 0, nullptr);
4768  }
4769 
4770  /**
4771  * When side effect checks are enabled, passing kHasNoSideEffect allows the
4772  * constructor to be invoked without throwing. Calls made within the
4773  * constructor are still checked.
4774  */
4776  Local<Context> context, int argc, Local<Value> argv[],
4777  SideEffectType side_effect_type = SideEffectType::kHasSideEffect) const;
4778 
4780  Local<Value> recv, int argc,
4781  Local<Value> argv[]);
4782 
4783  void SetName(Local<String> name);
4784  Local<Value> GetName() const;
4785 
4786  /**
4787  * Name inferred from variable or property assignment of this function.
4788  * Used to facilitate debugging and profiling of JavaScript code written
4789  * in an OO style, where many functions are anonymous but are assigned
4790  * to object properties.
4791  */
4793 
4794  /**
4795  * displayName if it is set, otherwise name if it is configured, otherwise
4796  * function name, otherwise inferred name.
4797  */
4799 
4800  /**
4801  * Returns zero based line number of function body and
4802  * kLineOffsetNotFound if no information available.
4803  */
4804  int GetScriptLineNumber() const;
4805  /**
4806  * Returns zero based column number of function body and
4807  * kLineOffsetNotFound if no information available.
4808  */
4810 
4811  /**
4812  * Returns scriptId.
4813  */
4814  int ScriptId() const;
4815 
4816  /**
4817  * Returns the original function if this function is bound, else returns
4818  * v8::Undefined.
4819  */
4821 
4822  /**
4823  * Calls builtin Function.prototype.toString on this function.
4824  * This is different from Value::ToString() that may call a user-defined
4825  * toString() function, and different than Object::ObjectProtoToString() which
4826  * always serializes "[object Function]".
4827  */
4829  Local<Context> context);
4830 
4832  V8_INLINE static Function* Cast(Value* obj);
4833  static const int kLineOffsetNotFound;
4834 
4835  private:
4836  Function();
4837  static void CheckCast(Value* obj);
4838 };
4839 
4840 #ifndef V8_PROMISE_INTERNAL_FIELD_COUNT
4841 // The number of required internal fields can be defined by embedder.
4842 #define V8_PROMISE_INTERNAL_FIELD_COUNT 0
4843 #endif
4844 
4845 /**
4846  * An instance of the built-in Promise constructor (ES6 draft).
4847  */
4848 class V8_EXPORT Promise : public Object {
4849  public:
4850  /**
4851  * State of the promise. Each value corresponds to one of the possible values
4852  * of the [[PromiseState]] field.
4853  */
4855 
4856  class V8_EXPORT Resolver : public Object {
4857  public:
4858  /**
4859  * Create a new resolver, along with an associated promise in pending state.
4860  */
4862  Local<Context> context);
4863 
4864  /**
4865  * Extract the associated promise.
4866  */
4868 
4869  /**
4870  * Resolve/reject the associated promise with a given value.
4871  * Ignored if the promise is no longer pending.
4872  */
4874  Local<Value> value);
4875 
4877  Local<Value> value);
4878 
4879  V8_INLINE static Resolver* Cast(Value* obj);
4880 
4881  private:
4882  Resolver();
4883  static void CheckCast(Value* obj);
4884  };
4885 
4886  /**
4887  * Register a resolution/rejection handler with a promise.
4888  * The handler is given the respective resolution/rejection value as
4889  * an argument. If the promise is already resolved/rejected, the handler is
4890  * invoked at the end of turn.
4891  */
4893  Local<Function> handler);
4894 
4896  Local<Function> handler);
4897 
4899  Local<Function> on_fulfilled,
4900  Local<Function> on_rejected);
4901 
4902  /**
4903  * Returns true if the promise has at least one derived promise, and
4904  * therefore resolve/reject handlers (including default handler).
4905  */
4906  bool HasHandler() const;
4907 
4908  /**
4909  * Returns the content of the [[PromiseResult]] field. The Promise must not
4910  * be pending.
4911  */
4913 
4914  /**
4915  * Returns the value of the [[PromiseState]] field.
4916  */
4918 
4919  /**
4920  * Marks this promise as handled to avoid reporting unhandled rejections.
4921  */
4923 
4924  /**
4925  * Marks this promise as silent to prevent pausing the debugger when the
4926  * promise is rejected.
4927  */
4929 
4930  V8_INLINE static Promise* Cast(Value* obj);
4931 
4933 
4934  private:
4935  Promise();
4936  static void CheckCast(Value* obj);
4937 };
4938 
4939 /**
4940  * An instance of a Property Descriptor, see Ecma-262 6.2.4.
4941  *
4942  * Properties in a descriptor are present or absent. If you do not set
4943  * `enumerable`, `configurable`, and `writable`, they are absent. If `value`,
4944  * `get`, or `set` are absent, but you must specify them in the constructor, use
4945  * empty handles.
4946  *
4947  * Accessors `get` and `set` must be callable or undefined if they are present.
4948  *
4949  * \note Only query properties if they are present, i.e., call `x()` only if
4950  * `has_x()` returns true.
4951  *
4952  * \code
4953  * // var desc = {writable: false}
4954  * v8::PropertyDescriptor d(Local<Value>()), false);
4955  * d.value(); // error, value not set
4956  * if (d.has_writable()) {
4957  * d.writable(); // false
4958  * }
4959  *
4960  * // var desc = {value: undefined}
4961  * v8::PropertyDescriptor d(v8::Undefined(isolate));
4962  *
4963  * // var desc = {get: undefined}
4964  * v8::PropertyDescriptor d(v8::Undefined(isolate), Local<Value>()));
4965  * \endcode
4966  */
4968  public:
4969  // GenericDescriptor
4971 
4972  // DataDescriptor
4973  explicit PropertyDescriptor(Local<Value> value);
4974 
4975  // DataDescriptor with writable property
4976  PropertyDescriptor(Local<Value> value, bool writable);
4977 
4978  // AccessorDescriptor
4980 
4982 
4983  Local<Value> value() const;
4984  bool has_value() const;
4985 
4986  Local<Value> get() const;
4987  bool has_get() const;
4988  Local<Value> set() const;
4989  bool has_set() const;
4990 
4991  void set_enumerable(bool enumerable);
4992  bool enumerable() const;
4993  bool has_enumerable() const;
4994 
4995  void set_configurable(bool configurable);
4996  bool configurable() const;
4997  bool has_configurable() const;
4998 
4999  bool writable() const;
5000  bool has_writable() const;
5001 
5002  struct PrivateData;
5003  PrivateData* get_private() const { return private_; }
5004 
5006  void operator=(const PropertyDescriptor&) = delete;
5007 
5008  private:
5009  PrivateData* private_;
5010 };
5011 
5012 /**
5013  * An instance of the built-in Proxy constructor (ECMA-262, 6th Edition,
5014  * 26.2.1).
5015  */
5016 class V8_EXPORT Proxy : public Object {
5017  public:
5020  bool IsRevoked() const;
5021  void Revoke();
5022 
5023  /**
5024  * Creates a new Proxy for the target object.
5025  */
5026  static MaybeLocal<Proxy> New(Local<Context> context,
5027  Local<Object> local_target,
5028  Local<Object> local_handler);
5029 
5030  V8_INLINE static Proxy* Cast(Value* obj);
5031 
5032  private:
5033  Proxy();
5034  static void CheckCast(Value* obj);
5035 };
5036 
5037 /**
5038  * Points to an unowned continous buffer holding a known number of elements.
5039  *
5040  * This is similar to std::span (under consideration for C++20), but does not
5041  * require advanced C++ support. In the (far) future, this may be replaced with
5042  * or aliased to std::span.
5043  *
5044  * To facilitate future migration, this class exposes a subset of the interface
5045  * implemented by std::span.
5046  */
5047 template <typename T>
5049  public:
5050  /** The default constructor creates an empty span. */
5051  constexpr MemorySpan() = default;
5052 
5053  constexpr MemorySpan(T* data, size_t size) : data_(data), size_(size) {}
5054 
5055  /** Returns a pointer to the beginning of the buffer. */
5056  constexpr T* data() const { return data_; }
5057  /** Returns the number of elements that the buffer holds. */
5058  constexpr size_t size() const { return size_; }
5059 
5060  private:
5061  T* data_ = nullptr;
5062  size_t size_ = 0;
5063 };
5064 
5065 /**
5066  * An owned byte buffer with associated size.
5067  */
5068 struct OwnedBuffer {
5069  std::unique_ptr<const uint8_t[]> buffer;
5070  size_t size = 0;
5071  OwnedBuffer(std::unique_ptr<const uint8_t[]> buffer, size_t size)
5072  : buffer(std::move(buffer)), size(size) {}
5073  OwnedBuffer() = default;
5074 };
5075 
5076 // Wrapper around a compiled WebAssembly module, which is potentially shared by
5077 // different WasmModuleObjects.
5079  public:
5080  /**
5081  * Serialize the compiled module. The serialized data does not include the
5082  * wire bytes.
5083  */
5085 
5086  /**
5087  * Get the (wasm-encoded) wire bytes that were used to compile this module.
5088  */
5089  MemorySpan<const uint8_t> GetWireBytesRef();
5090 
5091  const std::string& source_url() const { return source_url_; }
5092 
5093  private:
5094  friend class WasmModuleObject;
5095  friend class WasmStreaming;
5096 
5097  explicit CompiledWasmModule(std::shared_ptr<internal::wasm::NativeModule>,
5098  const char* source_url, size_t url_length);
5099 
5100  const std::shared_ptr<internal::wasm::NativeModule> native_module_;
5101  const std::string source_url_;
5102 };
5103 
5104 // An instance of WebAssembly.Memory.
5106  public:
5107  WasmMemoryObject() = delete;
5108 
5109  /**
5110  * Returns underlying ArrayBuffer.
5111  */
5113 
5114  V8_INLINE static WasmMemoryObject* Cast(Value* obj);
5115 
5116  private:
5117  static void CheckCast(Value* object);
5118 };
5119 
5120 // An instance of WebAssembly.Module.
5122  public:
5123  WasmModuleObject() = delete;
5124 
5125  /**
5126  * Efficiently re-create a WasmModuleObject, without recompiling, from
5127  * a CompiledWasmModule.
5128  */
5130  Isolate* isolate, const CompiledWasmModule&);
5131 
5132  /**
5133  * Get the compiled module for this module object. The compiled module can be
5134  * shared by several module objects.
5135  */
5137 
5138  V8_INLINE static WasmModuleObject* Cast(Value* obj);
5139 
5140  private:
5141  static void CheckCast(Value* obj);
5142 };
5143 
5144 /**
5145  * The V8 interface for WebAssembly streaming compilation. When streaming
5146  * compilation is initiated, V8 passes a {WasmStreaming} object to the embedder
5147  * such that the embedder can pass the input bytes for streaming compilation to
5148  * V8.
5149  */
5150 class V8_EXPORT WasmStreaming final {
5151  public:
5152  class WasmStreamingImpl;
5153 
5154  /**
5155  * Client to receive streaming event notifications.
5156  */
5157  class Client {
5158  public:
5159  virtual ~Client() = default;
5160  /**
5161  * Passes the fully compiled module to the client. This can be used to
5162  * implement code caching.
5163  */
5164  virtual void OnModuleCompiled(CompiledWasmModule compiled_module) = 0;
5165  };
5166 
5167  explicit WasmStreaming(std::unique_ptr<WasmStreamingImpl> impl);
5168 
5170 
5171  /**
5172  * Pass a new chunk of bytes to WebAssembly streaming compilation.
5173  * The buffer passed into {OnBytesReceived} is owned by the caller.
5174  */
5175  void OnBytesReceived(const uint8_t* bytes, size_t size);
5176 
5177  /**
5178  * {Finish} should be called after all received bytes where passed to
5179  * {OnBytesReceived} to tell V8 that there will be no more bytes. {Finish}
5180  * does not have to be called after {Abort} has been called already.
5181  */
5182  void Finish();
5183 
5184  /**
5185  * Abort streaming compilation. If {exception} has a value, then the promise
5186  * associated with streaming compilation is rejected with that value. If
5187  * {exception} does not have value, the promise does not get rejected.
5188  */
5189  void Abort(MaybeLocal<Value> exception);
5190 
5191  /**
5192  * Passes previously compiled module bytes. This must be called before
5193  * {OnBytesReceived}, {Finish}, or {Abort}. Returns true if the module bytes
5194  * can be used, false otherwise. The buffer passed via {bytes} and {size}
5195  * is owned by the caller. If {SetCompiledModuleBytes} returns true, the
5196  * buffer must remain valid until either {Finish} or {Abort} completes.
5197  */
5198  bool SetCompiledModuleBytes(const uint8_t* bytes, size_t size);
5199 
5200  /**
5201  * Sets the client object that will receive streaming event notifications.
5202  * This must be called before {OnBytesReceived}, {Finish}, or {Abort}.
5203  */
5204  void SetClient(std::shared_ptr<Client> client);
5205 
5206  /*
5207  * Sets the UTF-8 encoded source URL for the {Script} object. This must be
5208  * called before {Finish}.
5209  */
5210  void SetUrl(const char* url, size_t length);
5211 
5212  /**
5213  * Unpacks a {WasmStreaming} object wrapped in a {Managed} for the embedder.
5214  * Since the embedder is on the other side of the API, it cannot unpack the
5215  * {Managed} itself.
5216  */
5217  static std::shared_ptr<WasmStreaming> Unpack(Isolate* isolate,
5218  Local<Value> value);
5219 
5220  private:
5221  std::unique_ptr<WasmStreamingImpl> impl_;
5222 };
5223 
5224 // TODO(mtrofin): when streaming compilation is done, we can rename this
5225 // to simply WasmModuleObjectBuilder
5226 class V8_EXPORT WasmModuleObjectBuilderStreaming final {
5227  public:
5229  /**
5230  * The buffer passed into OnBytesReceived is owned by the caller.
5231  */
5232  void OnBytesReceived(const uint8_t*, size_t size);
5233  void Finish();
5234  /**
5235  * Abort streaming compilation. If {exception} has a value, then the promise
5236  * associated with streaming compilation is rejected with that value. If
5237  * {exception} does not have value, the promise does not get rejected.
5238  */
5239  void Abort(MaybeLocal<Value> exception);
5241 
5243 
5244  private:
5245  WasmModuleObjectBuilderStreaming(const WasmModuleObjectBuilderStreaming&) =
5246  delete;
5247  WasmModuleObjectBuilderStreaming(WasmModuleObjectBuilderStreaming&&) =
5248  default;
5249  WasmModuleObjectBuilderStreaming& operator=(
5250  const WasmModuleObjectBuilderStreaming&) = delete;
5251  WasmModuleObjectBuilderStreaming& operator=(
5252  WasmModuleObjectBuilderStreaming&&) = default;
5253  Isolate* isolate_ = nullptr;
5254 
5255 #if V8_CC_MSVC
5256  /**
5257  * We don't need the static Copy API, so the default
5258  * NonCopyablePersistentTraits would be sufficient, however,
5259  * MSVC eagerly instantiates the Copy.
5260  * We ensure we don't use Copy, however, by compiling with the
5261  * defaults everywhere else.
5262  */
5263  Persistent<Promise, CopyablePersistentTraits<Promise>> promise_;
5264 #else
5265  Persistent<Promise> promise_;
5266 #endif
5267  std::shared_ptr<internal::wasm::StreamingDecoder> streaming_decoder_;
5268 };
5269 
5270 #ifndef V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT
5271 // The number of required internal fields can be defined by embedder.
5272 #define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 2
5273 #endif
5274 
5275 
5277 
5278 /**
5279  * A wrapper around the backing store (i.e. the raw memory) of an array buffer.
5280  * See a document linked in http://crbug.com/v8/9908 for more information.
5281  *
5282  * The allocation and destruction of backing stores is generally managed by
5283  * V8. Clients should always use standard C++ memory ownership types (i.e.
5284  * std::unique_ptr and std::shared_ptr) to manage lifetimes of backing stores
5285  * properly, since V8 internal objects may alias backing stores.
5286  *
5287  * This object does not keep the underlying |ArrayBuffer::Allocator| alive by
5288  * default. Use Isolate::CreateParams::array_buffer_allocator_shared when
5289  * creating the Isolate to make it hold a reference to the allocator itself.
5290  */
5292  public:
5294 
5295  /**
5296  * Return a pointer to the beginning of the memory block for this backing
5297  * store. The pointer is only valid as long as this backing store object
5298  * lives.
5299  */
5300  void* Data() const;
5301 
5302  /**
5303  * The length (in bytes) of this backing store.
5304  */
5305  size_t ByteLength() const;
5306 
5307  /**
5308  * Indicates whether the backing store was created for an ArrayBuffer or
5309  * a SharedArrayBuffer.
5310  */
5311  bool IsShared() const;
5312 
5313  /**
5314  * Prevent implicit instantiation of operator delete with size_t argument.
5315  * The size_t argument would be incorrect because ptr points to the
5316  * internal BackingStore object.
5317  */
5318  void operator delete(void* ptr) { ::operator delete(ptr); }
5319 
5320  /**
5321  * Wrapper around ArrayBuffer::Allocator::Reallocate that preserves IsShared.
5322  * Assumes that the backing_store was allocated by the ArrayBuffer allocator
5323  * of the given isolate.
5324  */
5325  static std::unique_ptr<BackingStore> Reallocate(
5326  v8::Isolate* isolate, std::unique_ptr<BackingStore> backing_store,
5327  size_t byte_length);
5328 
5329  /**
5330  * This callback is used only if the memory block for a BackingStore cannot be
5331  * allocated with an ArrayBuffer::Allocator. In such cases the destructor of
5332  * the BackingStore invokes the callback to free the memory block.
5333  */
5334  using DeleterCallback = void (*)(void* data, size_t length,
5335  void* deleter_data);
5336 
5337  /**
5338  * If the memory block of a BackingStore is static or is managed manually,
5339  * then this empty deleter along with nullptr deleter_data can be passed to
5340  * ArrayBuffer::NewBackingStore to indicate that.
5341  *
5342  * The manually managed case should be used with caution and only when it
5343  * is guaranteed that the memory block freeing happens after detaching its
5344  * ArrayBuffer.
5345  */
5346  static void EmptyDeleter(void* data, size_t length, void* deleter_data);
5347 
5348  private:
5349  /**
5350  * See [Shared]ArrayBuffer::GetBackingStore and
5351  * [Shared]ArrayBuffer::NewBackingStore.
5352  */
5353  BackingStore();
5354 };
5355 
5356 #if !defined(V8_IMMINENT_DEPRECATION_WARNINGS)
5357 // Use v8::BackingStore::DeleterCallback instead.
5358 using BackingStoreDeleterCallback = void (*)(void* data, size_t length,
5359  void* deleter_data);
5360 
5361 #endif
5362 
5363 /**
5364  * An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5).
5365  */
5366 class V8_EXPORT ArrayBuffer : public Object {
5367  public:
5368  /**
5369  * A thread-safe allocator that V8 uses to allocate |ArrayBuffer|'s memory.
5370  * The allocator is a global V8 setting. It has to be set via
5371  * Isolate::CreateParams.
5372  *
5373  * Memory allocated through this allocator by V8 is accounted for as external
5374  * memory by V8. Note that V8 keeps track of the memory for all internalized
5375  * |ArrayBuffer|s. Responsibility for tracking external memory (using
5376  * Isolate::AdjustAmountOfExternalAllocatedMemory) is handed over to the
5377  * embedder upon externalization and taken over upon internalization (creating
5378  * an internalized buffer from an existing buffer).
5379  *
5380  * Note that it is unsafe to call back into V8 from any of the allocator
5381  * functions.
5382  */
5384  public:
5385  virtual ~Allocator() = default;
5386 
5387  /**
5388  * Allocate |length| bytes. Return nullptr if allocation is not successful.
5389  * Memory should be initialized to zeroes.
5390  */
5391  virtual void* Allocate(size_t length) = 0;
5392 
5393  /**
5394  * Allocate |length| bytes. Return nullptr if allocation is not successful.
5395  * Memory does not have to be initialized.
5396  */
5397  virtual void* AllocateUninitialized(size_t length) = 0;
5398 
5399  /**
5400  * Free the memory block of size |length|, pointed to by |data|.
5401  * That memory is guaranteed to be previously allocated by |Allocate|.
5402  */
5403  virtual void Free(void* data, size_t length) = 0;
5404 
5405  /**
5406  * Reallocate the memory block of size |old_length| to a memory block of
5407  * size |new_length| by expanding, contracting, or copying the existing
5408  * memory block. If |new_length| > |old_length|, then the new part of
5409  * the memory must be initialized to zeros. Return nullptr if reallocation
5410  * is not successful.
5411  *
5412  * The caller guarantees that the memory block was previously allocated
5413  * using Allocate or AllocateUninitialized.
5414  *
5415  * The default implementation allocates a new block and copies data.
5416  */
5417  virtual void* Reallocate(void* data, size_t old_length, size_t new_length);
5418 
5419  /**
5420  * ArrayBuffer allocation mode. kNormal is a malloc/free style allocation,
5421  * while kReservation is for larger allocations with the ability to set
5422  * access permissions.
5423  */
5425 
5426  /**
5427  * malloc/free based convenience allocator.
5428  *
5429  * Caller takes ownership, i.e. the returned object needs to be freed using
5430  * |delete allocator| once it is no longer in use.
5431  */
5433  };
5434 
5435  /**
5436  * Data length in bytes.
5437  */
5438  size_t ByteLength() const;
5439 
5440  /**
5441  * Create a new ArrayBuffer. Allocate |byte_length| bytes.
5442  * Allocated memory will be owned by a created ArrayBuffer and
5443  * will be deallocated when it is garbage-collected,
5444  * unless the object is externalized.
5445  */
5446  static Local<ArrayBuffer> New(Isolate* isolate, size_t byte_length);
5447 
5448  /**
5449  * Create a new ArrayBuffer with an existing backing store.
5450  * The created array keeps a reference to the backing store until the array
5451  * is garbage collected. Note that the IsExternal bit does not affect this
5452  * reference from the array to the backing store.
5453  *
5454  * In future IsExternal bit will be removed. Until then the bit is set as
5455  * follows. If the backing store does not own the underlying buffer, then
5456  * the array is created in externalized state. Otherwise, the array is created
5457  * in internalized state. In the latter case the array can be transitioned
5458  * to the externalized state using Externalize(backing_store).
5459  */
5460  static Local<ArrayBuffer> New(Isolate* isolate,
5461  std::shared_ptr<BackingStore> backing_store);
5462 
5463  /**
5464  * Returns a new standalone BackingStore that is allocated using the array
5465  * buffer allocator of the isolate. The result can be later passed to
5466  * ArrayBuffer::New.
5467  *
5468  * If the allocator returns nullptr, then the function may cause GCs in the
5469  * given isolate and re-try the allocation. If GCs do not help, then the
5470  * function will crash with an out-of-memory error.
5471  */
5472  static std::unique_ptr<BackingStore> NewBackingStore(Isolate* isolate,
5473  size_t byte_length);
5474  /**
5475  * Returns a new standalone BackingStore that takes over the ownership of
5476  * the given buffer. The destructor of the BackingStore invokes the given
5477  * deleter callback.
5478  *
5479  * The result can be later passed to ArrayBuffer::New. The raw pointer
5480  * to the buffer must not be passed again to any V8 API function.
5481  */
5482  static std::unique_ptr<BackingStore> NewBackingStore(
5483  void* data, size_t byte_length, v8::BackingStore::DeleterCallback deleter,
5484  void* deleter_data);
5485 
5486  /**
5487  * Returns true if this ArrayBuffer may be detached.
5488  */
5489  bool IsDetachable() const;
5490 
5491  /**
5492  * Detaches this ArrayBuffer and all its views (typed arrays).
5493  * Detaching sets the byte length of the buffer and all typed arrays to zero,
5494  * preventing JavaScript from ever accessing underlying backing store.
5495  * ArrayBuffer should have been externalized and must be detachable.
5496  */
5497  void Detach();
5498 
5499  /**
5500  * Get a shared pointer to the backing store of this array buffer. This
5501  * pointer coordinates the lifetime management of the internal storage
5502  * with any live ArrayBuffers on the heap, even across isolates. The embedder
5503  * should not attempt to manage lifetime of the storage through other means.
5504  */
5505  std::shared_ptr<BackingStore> GetBackingStore();
5506 
5507  V8_INLINE static ArrayBuffer* Cast(Value* obj);
5508 
5511 
5512  private:
5513  ArrayBuffer();
5514  static void CheckCast(Value* obj);
5515 };
5516 
5517 
5518 #ifndef V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT
5519 // The number of required internal fields can be defined by embedder.
5520 #define V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT 2
5521 #endif
5522 
5523 
5524 /**
5525  * A base class for an instance of one of "views" over ArrayBuffer,
5526  * including TypedArrays and DataView (ES6 draft 15.13).
5527  */
5529  public:
5530  /**
5531  * Returns underlying ArrayBuffer.
5532  */
5534  /**
5535  * Byte offset in |Buffer|.
5536  */
5537  size_t ByteOffset();
5538  /**
5539  * Size of a view in bytes.
5540  */
5541  size_t ByteLength();
5542 
5543  /**
5544  * Copy the contents of the ArrayBufferView's buffer to an embedder defined
5545  * memory without additional overhead that calling ArrayBufferView::Buffer
5546  * might incur.
5547  *
5548  * Will write at most min(|byte_length|, ByteLength) bytes starting at
5549  * ByteOffset of the underlying buffer to the memory starting at |dest|.
5550  * Returns the number of bytes actually written.
5551  */
5552  size_t CopyContents(void* dest, size_t byte_length);
5553 
5554  /**
5555  * Returns true if ArrayBufferView's backing ArrayBuffer has already been
5556  * allocated.
5557  */
5558  bool HasBuffer() const;
5559 
5560  V8_INLINE static ArrayBufferView* Cast(Value* obj);
5561 
5562  static const int kInternalFieldCount =
5564  static const int kEmbedderFieldCount =
5566 
5567  private:
5568  ArrayBufferView();
5569  static void CheckCast(Value* obj);
5570 };
5571 
5572 
5573 /**
5574  * A base class for an instance of TypedArray series of constructors
5575  * (ES6 draft 15.13.6).
5576  */
5578  public:
5579  /*
5580  * The largest typed array size that can be constructed using New.
5581  */
5582  static constexpr size_t kMaxLength =
5585  : static_cast<size_t>(uint64_t{1} << 32);
5586 
5587  /**
5588  * Number of elements in this typed array
5589  * (e.g. for Int16Array, |ByteLength|/2).
5590  */
5591  size_t Length();
5592 
5593  V8_INLINE static TypedArray* Cast(Value* obj);
5594 
5595  private:
5596  TypedArray();
5597  static void CheckCast(Value* obj);
5598 };
5599 
5600 
5601 /**
5602  * An instance of Uint8Array constructor (ES6 draft 15.13.6).
5603  */
5605  public:
5606  static Local<Uint8Array> New(Local<ArrayBuffer> array_buffer,
5607  size_t byte_offset, size_t length);
5608  static Local<Uint8Array> New(Local<SharedArrayBuffer> shared_array_buffer,
5609  size_t byte_offset, size_t length);
5610  V8_INLINE static Uint8Array* Cast(Value* obj);
5611 
5612  private:
5613  Uint8Array();
5614  static void CheckCast(Value* obj);
5615 };
5616 
5617 
5618 /**
5619  * An instance of Uint8ClampedArray constructor (ES6 draft 15.13.6).
5620  */
5622  public:
5624  size_t byte_offset, size_t length);
5626  Local<SharedArrayBuffer> shared_array_buffer, size_t byte_offset,
5627  size_t length);
5628  V8_INLINE static Uint8ClampedArray* Cast(Value* obj);
5629 
5630  private:
5631  Uint8ClampedArray();
5632  static void CheckCast(Value* obj);
5633 };
5634 
5635 /**
5636  * An instance of Int8Array constructor (ES6 draft 15.13.6).
5637  */
5639  public:
5640  static Local<Int8Array> New(Local<ArrayBuffer> array_buffer,
5641  size_t byte_offset, size_t length);
5642  static Local<Int8Array> New(Local<SharedArrayBuffer> shared_array_buffer,
5643  size_t byte_offset, size_t length);
5644  V8_INLINE static Int8Array* Cast(Value* obj);
5645 
5646  private:
5647  Int8Array();
5648  static void CheckCast(Value* obj);
5649 };
5650 
5651 
5652 /**
5653  * An instance of Uint16Array constructor (ES6 draft 15.13.6).
5654  */
5656  public:
5657  static Local<Uint16Array> New(Local<ArrayBuffer> array_buffer,
5658  size_t byte_offset, size_t length);
5659  static Local<Uint16Array> New(Local<SharedArrayBuffer> shared_array_buffer,
5660  size_t byte_offset, size_t length);
5661  V8_INLINE static Uint16Array* Cast(Value* obj);
5662 
5663  private:
5664  Uint16Array();
5665  static void CheckCast(Value* obj);
5666 };
5667 
5668 
5669 /**
5670  * An instance of Int16Array constructor (ES6 draft 15.13.6).
5671  */
5673  public:
5674  static Local<Int16Array> New(Local<ArrayBuffer> array_buffer,
5675  size_t byte_offset, size_t length);
5676  static Local<Int16Array> New(Local<SharedArrayBuffer> shared_array_buffer,
5677  size_t byte_offset, size_t length);
5678  V8_INLINE static Int16Array* Cast(Value* obj);
5679 
5680  private:
5681  Int16Array();
5682  static void CheckCast(Value* obj);
5683 };
5684 
5685 
5686 /**
5687  * An instance of Uint32Array constructor (ES6 draft 15.13.6).
5688  */
5690  public:
5691  static Local<Uint32Array> New(Local<ArrayBuffer> array_buffer,
5692  size_t byte_offset, size_t length);
5693  static Local<Uint32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
5694  size_t byte_offset, size_t length);
5695  V8_INLINE static Uint32Array* Cast(Value* obj);
5696 
5697  private:
5698  Uint32Array();
5699  static void CheckCast(Value* obj);
5700 };
5701 
5702 
5703 /**
5704  * An instance of Int32Array constructor (ES6 draft 15.13.6).
5705  */
5707  public:
5708  static Local<Int32Array> New(Local<ArrayBuffer> array_buffer,
5709  size_t byte_offset, size_t length);
5710  static Local<Int32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
5711  size_t byte_offset, size_t length);
5712  V8_INLINE static Int32Array* Cast(Value* obj);
5713 
5714  private:
5715  Int32Array();
5716  static void CheckCast(Value* obj);
5717 };
5718 
5719 
5720 /**
5721  * An instance of Float32Array constructor (ES6 draft 15.13.6).
5722  */
5724  public:
5725  static Local<Float32Array> New(Local<ArrayBuffer> array_buffer,
5726  size_t byte_offset, size_t length);
5727  static Local<Float32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
5728  size_t byte_offset, size_t length);
5729  V8_INLINE static Float32Array* Cast(Value* obj);
5730 
5731  private:
5732  Float32Array();
5733  static void CheckCast(Value* obj);
5734 };
5735 
5736 
5737 /**
5738  * An instance of Float64Array constructor (ES6 draft 15.13.6).
5739  */
5741  public:
5742  static Local<Float64Array> New(Local<ArrayBuffer> array_buffer,
5743  size_t byte_offset, size_t length);
5744  static Local<Float64Array> New(Local<SharedArrayBuffer> shared_array_buffer,
5745  size_t byte_offset, size_t length);
5746  V8_INLINE static Float64Array* Cast(Value* obj);
5747 
5748  private:
5749  Float64Array();
5750  static void CheckCast(Value* obj);
5751 };
5752 
5753 /**
5754  * An instance of BigInt64Array constructor.
5755  */
5757  public:
5758  static Local<BigInt64Array> New(Local<ArrayBuffer> array_buffer,
5759  size_t byte_offset, size_t length);
5760  static Local<BigInt64Array> New(Local<SharedArrayBuffer> shared_array_buffer,
5761  size_t byte_offset, size_t length);
5762  V8_INLINE static BigInt64Array* Cast(Value* obj);
5763 
5764  private:
5765  BigInt64Array();
5766  static void CheckCast(Value* obj);
5767 };
5768 
5769 /**
5770  * An instance of BigUint64Array constructor.
5771  */
5773  public:
5774  static Local<BigUint64Array> New(Local<ArrayBuffer> array_buffer,
5775  size_t byte_offset, size_t length);
5776  static Local<BigUint64Array> New(Local<SharedArrayBuffer> shared_array_buffer,
5777  size_t byte_offset, size_t length);
5778  V8_INLINE static BigUint64Array* Cast(Value* obj);
5779 
5780  private:
5781  BigUint64Array();
5782  static void CheckCast(Value* obj);
5783 };
5784 
5785 /**
5786  * An instance of DataView constructor (ES6 draft 15.13.7).
5787  */
5789  public:
5790  static Local<DataView> New(Local<ArrayBuffer> array_buffer,
5791  size_t byte_offset, size_t length);
5792  static Local<DataView> New(Local<SharedArrayBuffer> shared_array_buffer,
5793  size_t byte_offset, size_t length);
5794  V8_INLINE static DataView* Cast(Value* obj);
5795 
5796  private:
5797  DataView();
5798  static void CheckCast(Value* obj);
5799 };
5800 
5801 
5802 /**
5803  * An instance of the built-in SharedArrayBuffer constructor.
5804  */
5806  public:
5807  /**
5808  * Data length in bytes.
5809  */
5810  size_t ByteLength() const;
5811 
5812  /**
5813  * Create a new SharedArrayBuffer. Allocate |byte_length| bytes.
5814  * Allocated memory will be owned by a created SharedArrayBuffer and
5815  * will be deallocated when it is garbage-collected,
5816  * unless the object is externalized.
5817  */
5818  static Local<SharedArrayBuffer> New(Isolate* isolate, size_t byte_length);
5819 
5820  /**
5821  * Create a new SharedArrayBuffer with an existing backing store.
5822  * The created array keeps a reference to the backing store until the array
5823  * is garbage collected. Note that the IsExternal bit does not affect this
5824  * reference from the array to the backing store.
5825  *
5826  * In future IsExternal bit will be removed. Until then the bit is set as
5827  * follows. If the backing store does not own the underlying buffer, then
5828  * the array is created in externalized state. Otherwise, the array is created
5829  * in internalized state. In the latter case the array can be transitioned
5830  * to the externalized state using Externalize(backing_store).
5831  */
5833  Isolate* isolate, std::shared_ptr<BackingStore> backing_store);
5834 
5835  /**
5836  * Returns a new standalone BackingStore that is allocated using the array
5837  * buffer allocator of the isolate. The result can be later passed to
5838  * SharedArrayBuffer::New.
5839  *
5840  * If the allocator returns nullptr, then the function may cause GCs in the
5841  * given isolate and re-try the allocation. If GCs do not help, then the
5842  * function will crash with an out-of-memory error.
5843  */
5844  static std::unique_ptr<BackingStore> NewBackingStore(Isolate* isolate,
5845  size_t byte_length);
5846  /**
5847  * Returns a new standalone BackingStore that takes over the ownership of
5848  * the given buffer. The destructor of the BackingStore invokes the given
5849  * deleter callback.
5850  *
5851  * The result can be later passed to SharedArrayBuffer::New. The raw pointer
5852  * to the buffer must not be passed again to any V8 functions.
5853  */
5854  static std::unique_ptr<BackingStore> NewBackingStore(
5855  void* data, size_t byte_length, v8::BackingStore::DeleterCallback deleter,
5856  void* deleter_data);
5857 
5858  /**
5859  * Get a shared pointer to the backing store of this array buffer. This
5860  * pointer coordinates the lifetime management of the internal storage
5861  * with any live ArrayBuffers on the heap, even across isolates. The embedder
5862  * should not attempt to manage lifetime of the storage through other means.
5863  */
5864  std::shared_ptr<BackingStore> GetBackingStore();
5865 
5866  V8_INLINE static SharedArrayBuffer* Cast(Value* obj);
5867 
5869 
5870  private:
5871  SharedArrayBuffer();
5872  static void CheckCast(Value* obj);
5873 };
5874 
5875 
5876 /**
5877  * An instance of the built-in Date constructor (ECMA-262, 15.9).
5878  */
5879 class V8_EXPORT Date : public Object {
5880  public:
5882  double time);
5883 
5884  /**
5885  * A specialization of Value::NumberValue that is more efficient
5886  * because we know the structure of this object.
5887  */
5888  double ValueOf() const;
5889 
5890  V8_INLINE static Date* Cast(Value* obj);
5891 
5892  private:
5893  static void CheckCast(Value* obj);
5894 };
5895 
5896 
5897 /**
5898  * A Number object (ECMA-262, 4.3.21).
5899  */
5901  public:
5902  static Local<Value> New(Isolate* isolate, double value);
5903 
5904  double ValueOf() const;
5905 
5906  V8_INLINE static NumberObject* Cast(Value* obj);
5907 
5908  private:
5909  static void CheckCast(Value* obj);
5910 };
5911 
5912 /**
5913  * A BigInt object (https://tc39.github.io/proposal-bigint)
5914  */
5916  public:
5917  static Local<Value> New(Isolate* isolate, int64_t value);
5918 
5920 
5921  V8_INLINE static BigIntObject* Cast(Value* obj);
5922 
5923  private:
5924  static void CheckCast(Value* obj);
5925 };
5926 
5927 /**
5928  * A Boolean object (ECMA-262, 4.3.15).
5929  */
5931  public:
5932  static Local<Value> New(Isolate* isolate, bool value);
5933 
5934  bool ValueOf() const;
5935 
5936  V8_INLINE static BooleanObject* Cast(Value* obj);
5937 
5938  private:
5939  static void CheckCast(Value* obj);
5940 };
5941 
5942 
5943 /**
5944  * A String object (ECMA-262, 4.3.18).
5945  */
5947  public:
5948  static Local<Value> New(Isolate* isolate, Local<String> value);
5949 
5951 
5952  V8_INLINE static StringObject* Cast(Value* obj);
5953 
5954  private:
5955  static void CheckCast(Value* obj);
5956 };
5957 
5958 
5959 /**
5960  * A Symbol object (ECMA-262 edition 6).
5961  */
5963  public:
5964  static Local<Value> New(Isolate* isolate, Local<Symbol> value);
5965 
5967 
5968  V8_INLINE static SymbolObject* Cast(Value* obj);
5969 
5970  private:
5971  static void CheckCast(Value* obj);
5972 };
5973 
5974 
5975 /**
5976  * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
5977  */
5978 class V8_EXPORT RegExp : public Object {
5979  public:
5980  /**
5981  * Regular expression flag bits. They can be or'ed to enable a set
5982  * of flags.
5983  * The kLinear value ('l') is experimental and can only be used with
5984  * --enable-experimental-regexp-engine. RegExps with kLinear flag are
5985  * guaranteed to be executed in asymptotic linear time wrt. the length of
5986  * the subject string.
5987  */
5988  enum Flags {
5989  kNone = 0,
5990  kGlobal = 1 << 0,
5991  kIgnoreCase = 1 << 1,
5992  kMultiline = 1 << 2,
5993  kSticky = 1 << 3,
5994  kUnicode = 1 << 4,
5995  kDotAll = 1 << 5,
5996  kLinear = 1 << 6,
5997  kHasIndices = 1 << 7,
5998  };
5999 
6000  static constexpr int kFlagCount = 8;
6001 
6002  /**
6003  * Creates a regular expression from the given pattern string and
6004  * the flags bit field. May throw a JavaScript exception as
6005  * described in ECMA-262, 15.10.4.1.
6006  *
6007  * For example,
6008  * RegExp::New(v8::String::New("foo"),
6009  * static_cast<RegExp::Flags>(kGlobal | kMultiline))
6010  * is equivalent to evaluating "/foo/gm".
6011  */
6013  Local<String> pattern,
6014  Flags flags);
6015 
6016  /**
6017  * Like New, but additionally specifies a backtrack limit. If the number of
6018  * backtracks done in one Exec call hits the limit, a match failure is
6019  * immediately returned.
6020  */
6022  Local<Context> context, Local<String> pattern, Flags flags,
6023  uint32_t backtrack_limit);
6024 
6025  /**
6026  * Executes the current RegExp instance on the given subject string.
6027  * Equivalent to RegExp.prototype.exec as described in
6028  *
6029  * https://tc39.es/ecma262/#sec-regexp.prototype.exec
6030  *
6031  * On success, an Array containing the matched strings is returned. On
6032  * failure, returns Null.
6033  *
6034  * Note: modifies global context state, accessible e.g. through RegExp.input.
6035  */
6037  Local<String> subject);
6038 
6039  /**
6040  * Returns the value of the source property: a string representing
6041  * the regular expression.
6042  */
6044 
6045  /**
6046  * Returns the flags bit field.
6047  */
6048  Flags GetFlags() const;
6049 
6050  V8_INLINE static RegExp* Cast(Value* obj);
6051 
6052  private:
6053  static void CheckCast(Value* obj);
6054 };
6055 
6056 /**
6057  * A JavaScript value that wraps a C++ void*. This type of value is mainly used
6058  * to associate C++ data structures with JavaScript objects.
6059  */
6060 class V8_EXPORT External : public Value {
6061  public:
6062  static Local<External> New(Isolate* isolate, void* value);
6063  V8_INLINE static External* Cast(Value* obj);
6064  void* Value() const;
6065  private:
6066  static void CheckCast(v8::Value* obj);
6067 };
6068 
6069 #define V8_INTRINSICS_LIST(F)
6070  F(ArrayProto_entries, array_entries_iterator)
6071  F(ArrayProto_forEach, array_for_each_iterator)
6072  F(ArrayProto_keys, array_keys_iterator)
6073  F(ArrayProto_values, array_values_iterator)
6074  F(AsyncIteratorPrototype, initial_async_iterator_prototype)
6075  F(ErrorPrototype, initial_error_prototype)
6076  F(IteratorPrototype, initial_iterator_prototype)
6077  F(ObjProto_valueOf, object_value_of_function)
6078 
6080 #define V8_DECL_INTRINSIC(name, iname) k##name,
6082 #undef V8_DECL_INTRINSIC
6083 };
6084 
6085 
6086 // --- Templates ---
6087 
6088 
6089 /**
6090  * The superclass of object and function templates.
6091  */
6092 class V8_EXPORT Template : public Data {
6093  public:
6094  /**
6095  * Adds a property to each instance created by this template.
6096  *
6097  * The property must be defined either as a primitive value, or a template.
6098  */
6099  void Set(Local<Name> name, Local<Data> value,
6100  PropertyAttribute attributes = None);
6101  void SetPrivate(Local<Private> name, Local<Data> value,
6102  PropertyAttribute attributes = None);
6103  V8_INLINE void Set(Isolate* isolate, const char* name, Local<Data> value,
6104  PropertyAttribute attributes = None);
6105 
6107  Local<Name> name,
6110  PropertyAttribute attribute = None,
6111  AccessControl settings = DEFAULT);
6112 
6113  /**
6114  * Whenever the property with the given name is accessed on objects
6115  * created from this Template the getter and setter callbacks
6116  * are called instead of getting and setting the property directly
6117  * on the JavaScript object.
6118  *
6119  * \param name The name of the property for which an accessor is added.
6120  * \param getter The callback to invoke when getting the property.
6121  * \param setter The callback to invoke when setting the property.
6122  * \param data A piece of data that will be passed to the getter and setter
6123  * callbacks whenever they are invoked.
6124  * \param settings Access control settings for the accessor. This is a bit
6125  * field consisting of one of more of
6126  * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
6127  * The default is to not allow cross-context access.
6128  * ALL_CAN_READ means that all cross-context reads are allowed.
6129  * ALL_CAN_WRITE means that all cross-context writes are allowed.
6130  * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
6131  * cross-context access.
6132  * \param attribute The attributes of the property for which an accessor
6133  * is added.
6134  * \param signature The signature describes valid receivers for the accessor
6135  * and is used to perform implicit instance checks against them. If the
6136  * receiver is incompatible (i.e. is not an instance of the constructor as
6137  * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
6138  * thrown and no callback is invoked.
6139  */
6141  Local<String> name, AccessorGetterCallback getter,
6142  AccessorSetterCallback setter = nullptr,
6143  Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
6145  AccessControl settings = DEFAULT,
6146  SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
6147  SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
6149  Local<Name> name, AccessorNameGetterCallback getter,
6150  AccessorNameSetterCallback setter = nullptr,
6151  Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
6153  AccessControl settings = DEFAULT,
6154  SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
6155  SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
6156 
6157  /**
6158  * Like SetNativeDataProperty, but V8 will replace the native data property
6159  * with a real data property on first access.
6160  */
6162  Local<Name> name, AccessorNameGetterCallback getter,
6163  Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
6164  SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
6165  SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
6166 
6167  /**
6168  * During template instantiation, sets the value with the intrinsic property
6169  * from the correct context.
6170  */
6172  PropertyAttribute attribute = None);
6173 
6174  private:
6175  Template();
6176 
6177  friend class ObjectTemplate;
6178  friend class FunctionTemplate;
6179 };
6180 
6181 // TODO(dcarney): Replace GenericNamedPropertyFooCallback with just
6182 // NamedPropertyFooCallback.
6183 
6184 /**
6185  * Interceptor for get requests on an object.
6186  *
6187  * Use `info.GetReturnValue().Set()` to set the return value of the
6188  * intercepted get request.
6189  *
6190  * \param property The name of the property for which the request was
6191  * intercepted.
6192  * \param info Information about the intercepted request, such as
6193  * isolate, receiver, return value, or whether running in `'use strict`' mode.
6194  * See `PropertyCallbackInfo`.
6195  *
6196  * \code
6197  * void GetterCallback(
6198  * Local<Name> name,
6199  * const v8::PropertyCallbackInfo<v8::Value>& info) {
6200  * info.GetReturnValue().Set(v8_num(42));
6201  * }
6202  *
6203  * v8::Local<v8::FunctionTemplate> templ =
6204  * v8::FunctionTemplate::New(isolate);
6205  * templ->InstanceTemplate()->SetHandler(
6206  * v8::NamedPropertyHandlerConfiguration(GetterCallback));
6207  * LocalContext env;
6208  * env->Global()
6209  * ->Set(env.local(), v8_str("obj"), templ->GetFunction(env.local())
6210  * .ToLocalChecked()
6211  * ->NewInstance(env.local())
6212  * .ToLocalChecked())
6213  * .FromJust();
6214  * v8::Local<v8::Value> result = CompileRun("obj.a = 17; obj.a");
6215  * CHECK(v8_num(42)->Equals(env.local(), result).FromJust());
6216  * \endcode
6217  *
6218  * See also `ObjectTemplate::SetHandler`.
6219  */
6220 using GenericNamedPropertyGetterCallback =
6221  void (*)(Local<Name> property, const PropertyCallbackInfo<Value>& info);
6222 
6223 /**
6224  * Interceptor for set requests on an object.
6225  *
6226  * Use `info.GetReturnValue()` to indicate whether the request was intercepted
6227  * or not. If the setter successfully intercepts the request, i.e., if the
6228  * request should not be further executed, call
6229  * `info.GetReturnValue().Set(value)`. If the setter
6230  * did not intercept the request, i.e., if the request should be handled as
6231  * if no interceptor is present, do not not call `Set()`.
6232  *
6233  * \param property The name of the property for which the request was
6234  * intercepted.
6235  * \param value The value which the property will have if the request
6236  * is not intercepted.
6237  * \param info Information about the intercepted request, such as
6238  * isolate, receiver, return value, or whether running in `'use strict'` mode.
6239  * See `PropertyCallbackInfo`.
6240  *
6241  * See also
6242  * `ObjectTemplate::SetHandler.`
6243  */
6244 using GenericNamedPropertySetterCallback =
6245  void (*)(Local<Name> property, Local<Value> value,
6246  const PropertyCallbackInfo<Value>& info);
6247 
6248 /**
6249  * Intercepts all requests that query the attributes of the
6250  * property, e.g., getOwnPropertyDescriptor(), propertyIsEnumerable(), and
6251  * defineProperty().
6252  *
6253  * Use `info.GetReturnValue().Set(value)` to set the property attributes. The
6254  * value is an integer encoding a `v8::PropertyAttribute`.
6255  *
6256  * \param property The name of the property for which the request was
6257  * intercepted.
6258  * \param info Information about the intercepted request, such as
6259  * isolate, receiver, return value, or whether running in `'use strict'` mode.
6260  * See `PropertyCallbackInfo`.
6261  *
6262  * \note Some functions query the property attributes internally, even though
6263  * they do not return the attributes. For example, `hasOwnProperty()` can
6264  * trigger this interceptor depending on the state of the object.
6265  *
6266  * See also
6267  * `ObjectTemplate::SetHandler.`
6268  */
6269 using GenericNamedPropertyQueryCallback =
6270  void (*)(Local<Name> property, const PropertyCallbackInfo<Integer>& info);
6271 
6272 /**
6273  * Interceptor for delete requests on an object.
6274  *
6275  * Use `info.GetReturnValue()` to indicate whether the request was intercepted
6276  * or not. If the deleter successfully intercepts the request, i.e., if the
6277  * request should not be further executed, call
6278  * `info.GetReturnValue().Set(value)` with a boolean `value`. The `value` is
6279  * used as the return value of `delete`.
6280  *
6281  * \param property The name of the property for which the request was
6282  * intercepted.
6283  * \param info Information about the intercepted request, such as
6284  * isolate, receiver, return value, or whether running in `'use strict'` mode.
6285  * See `PropertyCallbackInfo`.
6286  *
6287  * \note If you need to mimic the behavior of `delete`, i.e., throw in strict
6288  * mode instead of returning false, use `info.ShouldThrowOnError()` to determine
6289  * if you are in strict mode.
6290  *
6291  * See also `ObjectTemplate::SetHandler.`
6292  */
6293 using GenericNamedPropertyDeleterCallback =
6294  void (*)(Local<Name> property, const PropertyCallbackInfo<Boolean>& info);
6295 
6296 /**
6297  * Returns an array containing the names of the properties the named
6298  * property getter intercepts.
6299  *
6300  * Note: The values in the array must be of type v8::Name.
6301  */
6302 using GenericNamedPropertyEnumeratorCallback =
6303  void (*)(const PropertyCallbackInfo<Array>& info);
6304 
6305 /**
6306  * Interceptor for defineProperty requests on an object.
6307  *
6308  * Use `info.GetReturnValue()` to indicate whether the request was intercepted
6309  * or not. If the definer successfully intercepts the request, i.e., if the
6310  * request should not be further executed, call
6311  * `info.GetReturnValue().Set(value)`. If the definer
6312  * did not intercept the request, i.e., if the request should be handled as
6313  * if no interceptor is present, do not not call `Set()`.
6314  *
6315  * \param property The name of the property for which the request was
6316  * intercepted.
6317  * \param desc The property descriptor which is used to define the
6318  * property if the request is not intercepted.
6319  * \param info Information about the intercepted request, such as
6320  * isolate, receiver, return value, or whether running in `'use strict'` mode.
6321  * See `PropertyCallbackInfo`.
6322  *
6323  * See also `ObjectTemplate::SetHandler`.
6324  */
6325 using GenericNamedPropertyDefinerCallback =
6326  void (*)(Local<Name> property, const PropertyDescriptor& desc,
6327  const PropertyCallbackInfo<Value>& info);
6328 
6329 /**
6330  * Interceptor for getOwnPropertyDescriptor requests on an object.
6331  *
6332  * Use `info.GetReturnValue().Set()` to set the return value of the
6333  * intercepted request. The return value must be an object that
6334  * can be converted to a PropertyDescriptor, e.g., a `v8::value` returned from
6335  * `v8::Object::getOwnPropertyDescriptor`.
6336  *
6337  * \param property The name of the property for which the request was
6338  * intercepted.
6339  * \info Information about the intercepted request, such as
6340  * isolate, receiver, return value, or whether running in `'use strict'` mode.
6341  * See `PropertyCallbackInfo`.
6342  *
6343  * \note If GetOwnPropertyDescriptor is intercepted, it will
6344  * always return true, i.e., indicate that the property was found.
6345  *
6346  * See also `ObjectTemplate::SetHandler`.
6347  */
6348 using GenericNamedPropertyDescriptorCallback =
6349  void (*)(Local<Name> property, const PropertyCallbackInfo<Value>& info);
6350 
6351 /**
6352  * See `v8::GenericNamedPropertyGetterCallback`.
6353  */
6354 using IndexedPropertyGetterCallback =
6355  void (*)(uint32_t index, const PropertyCallbackInfo<Value>& info);
6356 
6357 /**
6358  * See `v8::GenericNamedPropertySetterCallback`.
6359  */
6360 using IndexedPropertySetterCallback =
6361  void (*)(uint32_t index, Local<Value> value,
6362  const PropertyCallbackInfo<Value>& info);
6363 
6364 /**
6365  * See `v8::GenericNamedPropertyQueryCallback`.
6366  */
6367 using IndexedPropertyQueryCallback =
6368  void (*)(uint32_t index, const PropertyCallbackInfo<Integer>& info);
6369 
6370 /**
6371  * See `v8::GenericNamedPropertyDeleterCallback`.
6372  */
6373 using IndexedPropertyDeleterCallback =
6374  void (*)(uint32_t index, const PropertyCallbackInfo<Boolean>& info);
6375 
6376 /**
6377  * Returns an array containing the indices of the properties the indexed
6378  * property getter intercepts.
6379  *
6380  * Note: The values in the array must be uint32_t.
6381  */
6382 using IndexedPropertyEnumeratorCallback =
6383  void (*)(const PropertyCallbackInfo<Array>& info);
6384 
6385 /**
6386  * See `v8::GenericNamedPropertyDefinerCallback`.
6387  */
6388 using IndexedPropertyDefinerCallback =
6389  void (*)(uint32_t index, const PropertyDescriptor& desc,
6390  const PropertyCallbackInfo<Value>& info);
6391 
6392 /**
6393  * See `v8::GenericNamedPropertyDescriptorCallback`.
6394  */
6395 using IndexedPropertyDescriptorCallback =
6396  void (*)(uint32_t index, const PropertyCallbackInfo<Value>& info);
6397 
6398 /**
6399  * Access type specification.
6400  */
6406  ACCESS_KEYS
6407 };
6408 
6409 
6410 /**
6411  * Returns true if the given context should be allowed to access the given
6412  * object.
6413  */
6414 using AccessCheckCallback = bool (*)(Local<Context> accessing_context,
6415  Local<Object> accessed_object,
6416  Local<Value> data);
6417 
6418 /**
6419  * A FunctionTemplate is used to create functions at runtime. There
6420  * can only be one function created from a FunctionTemplate in a
6421  * context. The lifetime of the created function is equal to the
6422  * lifetime of the context. So in case the embedder needs to create
6423  * temporary functions that can be collected using Scripts is
6424  * preferred.
6425  *
6426  * Any modification of a FunctionTemplate after first instantiation will trigger
6427  * a crash.
6428  *
6429  * A FunctionTemplate can have properties, these properties are added to the
6430  * function object when it is created.
6431  *
6432  * A FunctionTemplate has a corresponding instance template which is
6433  * used to create object instances when the function is used as a
6434  * constructor. Properties added to the instance template are added to
6435  * each object instance.
6436  *
6437  * A FunctionTemplate can have a prototype template. The prototype template
6438  * is used to create the prototype object of the function.
6439  *
6440  * The following example shows how to use a FunctionTemplate:
6441  *
6442  * \code
6443  * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(isolate);
6444  * t->Set(isolate, "func_property", v8::Number::New(isolate, 1));
6445  *
6446  * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
6447  * proto_t->Set(isolate,
6448  * "proto_method",
6449  * v8::FunctionTemplate::New(isolate, InvokeCallback));
6450  * proto_t->Set(isolate, "proto_const", v8::Number::New(isolate, 2));
6451  *
6452  * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
6453  * instance_t->SetAccessor(
6454  String::NewFromUtf8Literal(isolate, "instance_accessor"),
6455  * InstanceAccessorCallback);
6456  * instance_t->SetHandler(
6457  * NamedPropertyHandlerConfiguration(PropertyHandlerCallback));
6458  * instance_t->Set(String::NewFromUtf8Literal(isolate, "instance_property"),
6459  * Number::New(isolate, 3));
6460  *
6461  * v8::Local<v8::Function> function = t->GetFunction();
6462  * v8::Local<v8::Object> instance = function->NewInstance();
6463  * \endcode
6464  *
6465  * Let's use "function" as the JS variable name of the function object
6466  * and "instance" for the instance object created above. The function
6467  * and the instance will have the following properties:
6468  *
6469  * \code
6470  * func_property in function == true;
6471  * function.func_property == 1;
6472  *
6473  * function.prototype.proto_method() invokes 'InvokeCallback'
6474  * function.prototype.proto_const == 2;
6475  *
6476  * instance instanceof function == true;
6477  * instance.instance_accessor calls 'InstanceAccessorCallback'
6478  * instance.instance_property == 3;
6479  * \endcode
6480  *
6481  * A FunctionTemplate can inherit from another one by calling the
6482  * FunctionTemplate::Inherit method. The following graph illustrates
6483  * the semantics of inheritance:
6484  *
6485  * \code
6486  * FunctionTemplate Parent -> Parent() . prototype -> { }
6487  * ^ ^
6488  * | Inherit(Parent) | .__proto__
6489  * | |
6490  * FunctionTemplate Child -> Child() . prototype -> { }
6491  * \endcode
6492  *
6493  * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
6494  * object of the Child() function has __proto__ pointing to the
6495  * Parent() function's prototype object. An instance of the Child
6496  * function has all properties on Parent's instance templates.
6497  *
6498  * Let Parent be the FunctionTemplate initialized in the previous
6499  * section and create a Child FunctionTemplate by:
6500  *
6501  * \code
6502  * Local<FunctionTemplate> parent = t;
6503  * Local<FunctionTemplate> child = FunctionTemplate::New();
6504  * child->Inherit(parent);
6505  *
6506  * Local<Function> child_function = child->GetFunction();
6507  * Local<Object> child_instance = child_function->NewInstance();
6508  * \endcode
6509  *
6510  * The Child function and Child instance will have the following
6511  * properties:
6512  *
6513  * \code
6514  * child_func.prototype.__proto__ == function.prototype;
6515  * child_instance.instance_accessor calls 'InstanceAccessorCallback'
6516  * child_instance.instance_property == 3;
6517  * \endcode
6518  *
6519  * The additional 'c_function' parameter refers to a fast API call, which
6520  * must not trigger GC or JavaScript execution, or call into V8 in other
6521  * ways. For more information how to define them, see
6522  * include/v8-fast-api-calls.h. Please note that this feature is still
6523  * experimental.
6524  */
6526  public:
6527  /** Creates a function template.*/
6529  Isolate* isolate, FunctionCallback callback = nullptr,
6530  Local<Value> data = Local<Value>(),
6531  Local<Signature> signature = Local<Signature>(), int length = 0,
6534  const CFunction* c_function = nullptr, uint16_t instance_type = 0,
6535  uint16_t allowed_receiver_instance_type_range_start = 0,
6536  uint16_t allowed_receiver_instance_type_range_end = 0);
6537 
6538  /** Creates a function template for multiple overloaded fast API calls.*/
6540  Isolate* isolate, FunctionCallback callback = nullptr,
6541  Local<Value> data = Local<Value>(),
6542  Local<Signature> signature = Local<Signature>(), int length = 0,
6545  const MemorySpan<const CFunction>& c_function_overloads = {});
6546 
6547  /**
6548  * Creates a function template backed/cached by a private property.
6549  */
6551  Isolate* isolate, FunctionCallback callback,
6552  Local<Private> cache_property, Local<Value> data = Local<Value>(),
6553  Local<Signature> signature = Local<Signature>(), int length = 0,
6554  SideEffectType side_effect_type = SideEffectType::kHasSideEffect);
6555 
6556  /** Returns the unique function instance in the current execution context.*/
6558  Local<Context> context);
6559 
6560  /**
6561  * Similar to Context::NewRemoteContext, this creates an instance that
6562  * isn't backed by an actual object.
6563  *
6564  * The InstanceTemplate of this FunctionTemplate must have access checks with
6565  * handlers installed.
6566  */
6568 
6569  /**
6570  * Set the call-handler callback for a FunctionTemplate. This
6571  * callback is called whenever the function created from this
6572  * FunctionTemplate is called. The 'c_function' represents a fast
6573  * API call, see the comment above the class declaration.
6574  */
6576  FunctionCallback callback, Local<Value> data = Local<Value>(),
6578  const MemorySpan<const CFunction>& c_function_overloads = {});
6579 
6580  /** Set the predefined length property for the FunctionTemplate. */
6581  void SetLength(int length);
6582 
6583  /** Get the InstanceTemplate. */
6585 
6586  /**
6587  * Causes the function template to inherit from a parent function template.
6588  * This means the function's prototype.__proto__ is set to the parent
6589  * function's prototype.
6590  **/
6592 
6593  /**
6594  * A PrototypeTemplate is the template used to create the prototype object
6595  * of the function created by this template.
6596  */
6598 
6599  /**
6600  * A PrototypeProviderTemplate is another function template whose prototype
6601  * property is used for this template. This is mutually exclusive with setting
6602  * a prototype template indirectly by calling PrototypeTemplate() or using
6603  * Inherit().
6604  **/
6606 
6607  /**
6608  * Set the class name of the FunctionTemplate. This is used for
6609  * printing objects created with the function created from the
6610  * FunctionTemplate as its constructor.
6611  */
6613 
6614 
6615  /**
6616  * When set to true, no access check will be performed on the receiver of a
6617  * function call. Currently defaults to true, but this is subject to change.
6618  */
6619  void SetAcceptAnyReceiver(bool value);
6620 
6621  /**
6622  * Sets the ReadOnly flag in the attributes of the 'prototype' property
6623  * of functions created from this FunctionTemplate to true.
6624  */
6626 
6627  /**
6628  * Removes the prototype property from functions created from this
6629  * FunctionTemplate.
6630  */
6632 
6633  /**
6634  * Returns true if the given object is an instance of this function
6635  * template.
6636  */
6637  bool HasInstance(Local<Value> object);
6638 
6639  /**
6640  * Returns true if the given value is an API object that was constructed by an
6641  * instance of this function template (without checking for inheriting
6642  * function templates).
6643  *
6644  * This is an experimental feature and may still change significantly.
6645  */
6647 
6648  V8_INLINE static FunctionTemplate* Cast(Data* data);
6649 
6650  private:
6651  FunctionTemplate();
6652 
6653  static void CheckCast(Data* that);
6654  friend class Context;
6655  friend class ObjectTemplate;
6656 };
6657 
6658 /**
6659  * Configuration flags for v8::NamedPropertyHandlerConfiguration or
6660  * v8::IndexedPropertyHandlerConfiguration.
6661  */
6663  /**
6664  * None.
6665  */
6666  kNone = 0,
6667 
6668  /**
6669  * See ALL_CAN_READ above.
6670  */
6671  kAllCanRead = 1,
6672 
6673  /** Will not call into interceptor for properties on the receiver or prototype
6674  * chain, i.e., only call into interceptor for properties that do not exist.
6675  * Currently only valid for named interceptors.
6676  */
6677  kNonMasking = 1 << 1,
6678 
6679  /**
6680  * Will not call into interceptor for symbol lookup. Only meaningful for
6681  * named interceptors.
6682  */
6683  kOnlyInterceptStrings = 1 << 2,
6684 
6685  /**
6686  * The getter, query, enumerator callbacks do not produce side effects.
6687  */
6688  kHasNoSideEffect = 1 << 3,
6689 };
6690 
6693  GenericNamedPropertyGetterCallback getter,
6694  GenericNamedPropertySetterCallback setter,
6695  GenericNamedPropertyQueryCallback query,
6696  GenericNamedPropertyDeleterCallback deleter,
6697  GenericNamedPropertyEnumeratorCallback enumerator,
6698  GenericNamedPropertyDefinerCallback definer,
6699  GenericNamedPropertyDescriptorCallback descriptor,
6700  Local<Value> data = Local<Value>(),
6702  : getter(getter),
6703  setter(setter),
6704  query(query),
6705  deleter(deleter),
6706  enumerator(enumerator),
6707  definer(definer),
6708  descriptor(descriptor),
6709  data(data),
6710  flags(flags) {}
6711 
6713  /** Note: getter is required */
6714  GenericNamedPropertyGetterCallback getter = nullptr,
6715  GenericNamedPropertySetterCallback setter = nullptr,
6716  GenericNamedPropertyQueryCallback query = nullptr,
6717  GenericNamedPropertyDeleterCallback deleter = nullptr,
6718  GenericNamedPropertyEnumeratorCallback enumerator = nullptr,
6719  Local<Value> data = Local<Value>(),
6721  : getter(getter),
6722  setter(setter),
6723  query(query),
6724  deleter(deleter),
6725  enumerator(enumerator),
6726  definer(nullptr),
6727  descriptor(nullptr),
6728  data(data),
6729  flags(flags) {}
6730 
6732  GenericNamedPropertyGetterCallback getter,
6733  GenericNamedPropertySetterCallback setter,
6734  GenericNamedPropertyDescriptorCallback descriptor,
6735  GenericNamedPropertyDeleterCallback deleter,
6736  GenericNamedPropertyEnumeratorCallback enumerator,
6737  GenericNamedPropertyDefinerCallback definer,
6738  Local<Value> data = Local<Value>(),
6740  : getter(getter),
6741  setter(setter),
6742  query(nullptr),
6743  deleter(deleter),
6744  enumerator(enumerator),
6745  definer(definer),
6746  descriptor(descriptor),
6747  data(data),
6748  flags(flags) {}
6749 
6750  GenericNamedPropertyGetterCallback getter;
6751  GenericNamedPropertySetterCallback setter;
6752  GenericNamedPropertyQueryCallback query;
6753  GenericNamedPropertyDeleterCallback deleter;
6754  GenericNamedPropertyEnumeratorCallback enumerator;
6755  GenericNamedPropertyDefinerCallback definer;
6756  GenericNamedPropertyDescriptorCallback descriptor;
6759 };
6760 
6761 
6764  IndexedPropertyGetterCallback getter,
6765  IndexedPropertySetterCallback setter, IndexedPropertyQueryCallback query,
6766  IndexedPropertyDeleterCallback deleter,
6767  IndexedPropertyEnumeratorCallback enumerator,
6768  IndexedPropertyDefinerCallback definer,
6769  IndexedPropertyDescriptorCallback descriptor,
6770  Local<Value> data = Local<Value>(),
6772  : getter(getter),
6773  setter(setter),
6774  query(query),
6775  deleter(deleter),
6776  enumerator(enumerator),
6777  definer(definer),
6778  descriptor(descriptor),
6779  data(data),
6780  flags(flags) {}
6781 
6783  /** Note: getter is required */
6784  IndexedPropertyGetterCallback getter = nullptr,
6785  IndexedPropertySetterCallback setter = nullptr,
6786  IndexedPropertyQueryCallback query = nullptr,
6787  IndexedPropertyDeleterCallback deleter = nullptr,
6788  IndexedPropertyEnumeratorCallback enumerator = nullptr,
6789  Local<Value> data = Local<Value>(),
6791  : getter(getter),
6792  setter(setter),
6793  query(query),
6794  deleter(deleter),
6795  enumerator(enumerator),
6796  definer(nullptr),
6797  descriptor(nullptr),
6798  data(data),
6799  flags(flags) {}
6800 
6802  IndexedPropertyGetterCallback getter,
6803  IndexedPropertySetterCallback setter,
6804  IndexedPropertyDescriptorCallback descriptor,
6805  IndexedPropertyDeleterCallback deleter,
6806  IndexedPropertyEnumeratorCallback enumerator,
6807  IndexedPropertyDefinerCallback definer,
6808  Local<Value> data = Local<Value>(),
6810  : getter(getter),
6811  setter(setter),
6812  query(nullptr),
6813  deleter(deleter),
6814  enumerator(enumerator),
6815  definer(definer),
6816  descriptor(descriptor),
6817  data(data),
6818  flags(flags) {}
6819 
6820  IndexedPropertyGetterCallback getter;
6821  IndexedPropertySetterCallback setter;
6822  IndexedPropertyQueryCallback query;
6823  IndexedPropertyDeleterCallback deleter;
6824  IndexedPropertyEnumeratorCallback enumerator;
6825  IndexedPropertyDefinerCallback definer;
6826  IndexedPropertyDescriptorCallback descriptor;
6829 };
6830 
6831 
6832 /**
6833  * An ObjectTemplate is used to create objects at runtime.
6834  *
6835  * Properties added to an ObjectTemplate are added to each object
6836  * created from the ObjectTemplate.
6837  */
6839  public:
6840  /** Creates an ObjectTemplate. */
6842  Isolate* isolate,
6844 
6845  /** Creates a new instance of this template.*/
6847 
6848  /**
6849  * Sets an accessor on the object template.
6850  *
6851  * Whenever the property with the given name is accessed on objects
6852  * created from this ObjectTemplate the getter and setter callbacks
6853  * are called instead of getting and setting the property directly
6854  * on the JavaScript object.
6855  *
6856  * \param name The name of the property for which an accessor is added.
6857  * \param getter The callback to invoke when getting the property.
6858  * \param setter The callback to invoke when setting the property.
6859  * \param data A piece of data that will be passed to the getter and setter
6860  * callbacks whenever they are invoked.
6861  * \param settings Access control settings for the accessor. This is a bit
6862  * field consisting of one of more of
6863  * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
6864  * The default is to not allow cross-context access.
6865  * ALL_CAN_READ means that all cross-context reads are allowed.
6866  * ALL_CAN_WRITE means that all cross-context writes are allowed.
6867  * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
6868  * cross-context access.
6869  * \param attribute The attributes of the property for which an accessor
6870  * is added.
6871  * \param signature The signature describes valid receivers for the accessor
6872  * and is used to perform implicit instance checks against them. If the
6873  * receiver is incompatible (i.e. is not an instance of the constructor as
6874  * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
6875  * thrown and no callback is invoked.
6876  */
6878  Local<String> name, AccessorGetterCallback getter,
6879  AccessorSetterCallback setter = nullptr,
6880  Local<Value> data = Local<Value>(), AccessControl settings = DEFAULT,
6881  PropertyAttribute attribute = None,
6883  SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
6884  SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
6886  Local<Name> name, AccessorNameGetterCallback getter,
6887  AccessorNameSetterCallback setter = nullptr,
6888  Local<Value> data = Local<Value>(), AccessControl settings = DEFAULT,
6889  PropertyAttribute attribute = None,
6891  SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
6892  SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
6893 
6894  /**
6895  * Sets a named property handler on the object template.
6896  *
6897  * Whenever a property whose name is a string or a symbol is accessed on
6898  * objects created from this object template, the provided callback is
6899  * invoked instead of accessing the property directly on the JavaScript
6900  * object.
6901  *
6902  * @param configuration The NamedPropertyHandlerConfiguration that defines the
6903  * callbacks to invoke when accessing a property.
6904  */
6905  void SetHandler(const NamedPropertyHandlerConfiguration& configuration);
6906 
6907  /**
6908  * Sets an indexed property handler on the object template.
6909  *
6910  * Whenever an indexed property is accessed on objects created from
6911  * this object template, the provided callback is invoked instead of
6912  * accessing the property directly on the JavaScript object.
6913  *
6914  * \param getter The callback to invoke when getting a property.
6915  * \param setter The callback to invoke when setting a property.
6916  * \param query The callback to invoke to check if an object has a property.
6917  * \param deleter The callback to invoke when deleting a property.
6918  * \param enumerator The callback to invoke to enumerate all the indexed
6919  * properties of an object.
6920  * \param data A piece of data that will be passed to the callbacks
6921  * whenever they are invoked.
6922  */
6923  // TODO(dcarney): deprecate
6925  IndexedPropertyGetterCallback getter,
6926  IndexedPropertySetterCallback setter = nullptr,
6927  IndexedPropertyQueryCallback query = nullptr,
6928  IndexedPropertyDeleterCallback deleter = nullptr,
6929  IndexedPropertyEnumeratorCallback enumerator = nullptr,
6930  Local<Value> data = Local<Value>()) {
6932  deleter, enumerator, data));
6933  }
6934 
6935  /**
6936  * Sets an indexed property handler on the object template.
6937  *
6938  * Whenever an indexed property is accessed on objects created from
6939  * this object template, the provided callback is invoked instead of
6940  * accessing the property directly on the JavaScript object.
6941  *
6942  * @param configuration The IndexedPropertyHandlerConfiguration that defines
6943  * the callbacks to invoke when accessing a property.
6944  */
6946 
6947  /**
6948  * Sets the callback to be used when calling instances created from
6949  * this template as a function. If no callback is set, instances
6950  * behave like normal JavaScript objects that cannot be called as a
6951  * function.
6952  */
6953  void SetCallAsFunctionHandler(FunctionCallback callback,
6954  Local<Value> data = Local<Value>());
6955 
6956  /**
6957  * Mark object instances of the template as undetectable.
6958  *
6959  * In many ways, undetectable objects behave as though they are not
6960  * there. They behave like 'undefined' in conditionals and when
6961  * printed. However, properties can be accessed and called as on
6962  * normal objects.
6963  */
6965 
6966  /**
6967  * Sets access check callback on the object template and enables access
6968  * checks.
6969  *
6970  * When accessing properties on instances of this object template,
6971  * the access check callback will be called to determine whether or
6972  * not to allow cross-context access to the properties.
6973  */
6974  void SetAccessCheckCallback(AccessCheckCallback callback,
6975  Local<Value> data = Local<Value>());
6976 
6977  /**
6978  * Like SetAccessCheckCallback but invokes an interceptor on failed access
6979  * checks instead of looking up all-can-read properties. You can only use
6980  * either this method or SetAccessCheckCallback, but not both at the same
6981  * time.
6982  */
6984  AccessCheckCallback callback,
6985  const NamedPropertyHandlerConfiguration& named_handler,
6986  const IndexedPropertyHandlerConfiguration& indexed_handler,
6987  Local<Value> data = Local<Value>());
6988 
6989  /**
6990  * Gets the number of internal fields for objects generated from
6991  * this template.
6992  */
6993  int InternalFieldCount() const;
6994 
6995  /**
6996  * Sets the number of internal fields for objects generated from
6997  * this template.
6998  */
6999  void SetInternalFieldCount(int value);
7000 
7001  /**
7002  * Returns true if the object will be an immutable prototype exotic object.
7003  */
7004  bool IsImmutableProto() const;
7005 
7006  /**
7007  * Makes the ObjectTemplate for an immutable prototype exotic object, with an
7008  * immutable __proto__.
7009  */
7011 
7012  /**
7013  * Support for TC39 "dynamic code brand checks" proposal.
7014  *
7015  * This API allows to mark (& query) objects as "code like", which causes
7016  * them to be treated like Strings in the context of eval and function
7017  * constructor.
7018  *
7019  * Reference: https://github.com/tc39/proposal-dynamic-code-brand-checks
7020  */
7021  void SetCodeLike();
7022  bool IsCodeLike() const;
7023 
7024  V8_INLINE static ObjectTemplate* Cast(Data* data);
7025 
7026  private:
7027  ObjectTemplate();
7028  static Local<ObjectTemplate> New(internal::Isolate* isolate,
7029  Local<FunctionTemplate> constructor);
7030  static void CheckCast(Data* that);
7031  friend class FunctionTemplate;
7032 };
7033 
7034 /**
7035  * A Signature specifies which receiver is valid for a function.
7036  *
7037  * A receiver matches a given signature if the receiver (or any of its
7038  * hidden prototypes) was created from the signature's FunctionTemplate, or
7039  * from a FunctionTemplate that inherits directly or indirectly from the
7040  * signature's FunctionTemplate.
7041  */
7042 class V8_EXPORT Signature : public Data {
7043  public:
7045  Isolate* isolate,
7047 
7048  V8_INLINE static Signature* Cast(Data* data);
7049 
7050  private:
7051  Signature();
7052 
7053  static void CheckCast(Data* that);
7054 };
7055 
7056 
7057 /**
7058  * An AccessorSignature specifies which receivers are valid parameters
7059  * to an accessor callback.
7060  */
7062  public:
7064  Isolate* isolate,
7066 
7067  V8_INLINE static AccessorSignature* Cast(Data* data);
7068 
7069  private:
7070  AccessorSignature();
7071 
7072  static void CheckCast(Data* that);
7073 };
7074 
7075 
7076 // --- Extensions ---
7077 
7078 /**
7079  * Ignore
7080  */
7082  public:
7083  // Note that the strings passed into this constructor must live as long
7084  // as the Extension itself.
7085  Extension(const char* name, const char* source = nullptr, int dep_count = 0,
7086  const char** deps = nullptr, int source_length = -1);
7087  virtual ~Extension() { delete source_; }
7089  Isolate* isolate, Local<String> name) {
7091  }
7092 
7093  const char* name() const { return name_; }
7094  size_t source_length() const { return source_length_; }
7096  return source_;
7097  }
7098  int dependency_count() const { return dep_count_; }
7099  const char** dependencies() const { return deps_; }
7100  void set_auto_enable(bool value) { auto_enable_ = value; }
7101  bool auto_enable() { return auto_enable_; }
7102 
7103  // Disallow copying and assigning.
7104  Extension(const Extension&) = delete;
7105  void operator=(const Extension&) = delete;
7106 
7107  private:
7108  const char* name_;
7109  size_t source_length_; // expected to initialize before source_
7111  int dep_count_;
7112  const char** deps_;
7113  bool auto_enable_;
7114 };
7115 
7116 void V8_EXPORT RegisterExtension(std::unique_ptr<Extension>);
7117 
7118 // --- Statics ---
7119 
7121 V8_INLINE Local<Primitive> Null(Isolate* isolate);
7122 V8_INLINE Local<Boolean> True(Isolate* isolate);
7123 V8_INLINE Local<Boolean> False(Isolate* isolate);
7124 
7125 /**
7126  * A set of constraints that specifies the limits of the runtime's memory use.
7127  * You must set the heap size before initializing the VM - the size cannot be
7128  * adjusted after the VM is initialized.
7129  *
7130  * If you are using threads then you should hold the V8::Locker lock while
7131  * setting the stack limit and you must set a non-default stack limit separately
7132  * for each thread.
7133  *
7134  * The arguments for set_max_semi_space_size, set_max_old_space_size,
7135  * set_max_executable_size, set_code_range_size specify limits in MB.
7136  *
7137  * The argument for set_max_semi_space_size_in_kb is in KB.
7138  */
7140  public:
7141  /**
7142  * Configures the constraints with reasonable default values based on the
7143  * provided heap size limit. The heap size includes both the young and
7144  * the old generation.
7145  *
7146  * \param initial_heap_size_in_bytes The initial heap size or zero.
7147  * By default V8 starts with a small heap and dynamically grows it to
7148  * match the set of live objects. This may lead to ineffective
7149  * garbage collections at startup if the live set is large.
7150  * Setting the initial heap size avoids such garbage collections.
7151  * Note that this does not affect young generation garbage collections.
7152  *
7153  * \param maximum_heap_size_in_bytes The hard limit for the heap size.
7154  * When the heap size approaches this limit, V8 will perform series of
7155  * garbage collections and invoke the NearHeapLimitCallback. If the garbage
7156  * collections do not help and the callback does not increase the limit,
7157  * then V8 will crash with V8::FatalProcessOutOfMemory.
7158  */
7159  void ConfigureDefaultsFromHeapSize(size_t initial_heap_size_in_bytes,
7160  size_t maximum_heap_size_in_bytes);
7161 
7162  /**
7163  * Configures the constraints with reasonable default values based on the
7164  * capabilities of the current device the VM is running on.
7165  *
7166  * \param physical_memory The total amount of physical memory on the current
7167  * device, in bytes.
7168  * \param virtual_memory_limit The amount of virtual memory on the current
7169  * device, in bytes, or zero, if there is no limit.
7170  */
7171  void ConfigureDefaults(uint64_t physical_memory,
7172  uint64_t virtual_memory_limit);
7173 
7174  /**
7175  * The address beyond which the VM's stack may not grow.
7176  */
7177  uint32_t* stack_limit() const { return stack_limit_; }
7178  void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
7179 
7180  /**
7181  * The amount of virtual memory reserved for generated code. This is relevant
7182  * for 64-bit architectures that rely on code range for calls in code.
7183  *
7184  * When V8_COMPRESS_POINTERS_IN_SHARED_CAGE is defined, there is a shared
7185  * process-wide code range that is lazily initialized. This value is used to
7186  * configure that shared code range when the first Isolate is
7187  * created. Subsequent Isolates ignore this value.
7188  */
7189  size_t code_range_size_in_bytes() const { return code_range_size_; }
7190  void set_code_range_size_in_bytes(size_t limit) { code_range_size_ = limit; }
7191 
7192  /**
7193  * The maximum size of the old generation.
7194  * When the old generation approaches this limit, V8 will perform series of
7195  * garbage collections and invoke the NearHeapLimitCallback.
7196  * If the garbage collections do not help and the callback does not
7197  * increase the limit, then V8 will crash with V8::FatalProcessOutOfMemory.
7198  */
7200  return max_old_generation_size_;
7201  }
7203  max_old_generation_size_ = limit;
7204  }
7205 
7206  /**
7207  * The maximum size of the young generation, which consists of two semi-spaces
7208  * and a large object space. This affects frequency of Scavenge garbage
7209  * collections and should be typically much smaller that the old generation.
7210  */
7212  return max_young_generation_size_;
7213  }
7215  max_young_generation_size_ = limit;
7216  }
7217 
7219  return initial_old_generation_size_;
7220  }
7221  void set_initial_old_generation_size_in_bytes(size_t initial_size) {
7222  initial_old_generation_size_ = initial_size;
7223  }
7224 
7226  return initial_young_generation_size_;
7227  }
7229  initial_young_generation_size_ = initial_size;
7230  }
7231 
7232  private:
7233  static constexpr size_t kMB = 1048576u;
7234  size_t code_range_size_ = 0;
7235  size_t max_old_generation_size_ = 0;
7236  size_t max_young_generation_size_ = 0;
7237  size_t initial_old_generation_size_ = 0;
7238  size_t initial_young_generation_size_ = 0;
7239  uint32_t* stack_limit_ = nullptr;
7240 };
7241 
7242 
7243 // --- Exceptions ---
7244 
7245 using FatalErrorCallback = void (*)(const char* location, const char* message);
7246 
7247 using OOMErrorCallback = void (*)(const char* location, bool is_heap_oom);
7248 
7249 using DcheckErrorCallback = void (*)(const char* file, int line,
7250  const char* message);
7251 
7252 using MessageCallback = void (*)(Local<Message> message, Local<Value> data);
7253 
7254 // --- Tracing ---
7255 
7256 enum LogEventStatus : int { kStart = 0, kEnd = 1, kStamp = 2 };
7257 using LogEventCallback = void (*)(const char* name,
7258  int /* LogEventStatus */ status);
7259 
7260 /**
7261  * Create new error objects by calling the corresponding error object
7262  * constructor with the message.
7263  */
7265  public:
7266  static Local<Value> RangeError(Local<String> message);
7268  static Local<Value> SyntaxError(Local<String> message);
7269  static Local<Value> TypeError(Local<String> message);
7271  static Local<Value> WasmLinkError(Local<String> message);
7273  static Local<Value> Error(Local<String> message);
7274 
7275  /**
7276  * Creates an error message for the given exception.
7277  * Will try to reconstruct the original stack trace from the exception value,
7278  * or capture the current stack trace if not available.
7279  */
7280  static Local<Message> CreateMessage(Isolate* isolate, Local<Value> exception);
7281 
7282  /**
7283  * Returns the original stack trace that was captured at the creation time
7284  * of a given exception, or an empty handle if not available.
7285  */
7287 };
7288 
7289 
7290 // --- Counters Callbacks ---
7291 
7292 using CounterLookupCallback = int* (*)(const char* name);
7293 
7294 using CreateHistogramCallback = void* (*)(const char* name, int min, int max,
7295  size_t buckets);
7296 
7297 using AddHistogramSampleCallback = void (*)(void* histogram, int sample);
7298 
7299 // --- Crashkeys Callback ---
7300 enum class CrashKeyId {
7305  kDumpType,
7306 };
7307 
7308 using AddCrashKeyCallback = void (*)(CrashKeyId id, const std::string& value);
7309 
7310 // --- Enter/Leave Script Callback ---
7311 using BeforeCallEnteredCallback = void (*)(Isolate*);
7312 using CallCompletedCallback = void (*)(Isolate*);
7313 
7314 /**
7315  * HostImportModuleDynamicallyCallback is called when we require the
7316  * embedder to load a module. This is used as part of the dynamic
7317  * import syntax.
7318  *
7319  * The referrer contains metadata about the script/module that calls
7320  * import.
7321  *
7322  * The specifier is the name of the module that should be imported.
7323  *
7324  * The embedder must compile, instantiate, evaluate the Module, and
7325  * obtain its namespace object.
7326  *
7327  * The Promise returned from this function is forwarded to userland
7328  * JavaScript. The embedder must resolve this promise with the module
7329  * namespace object. In case of an exception, the embedder must reject
7330  * this promise with the exception. If the promise creation itself
7331  * fails (e.g. due to stack overflow), the embedder must propagate
7332  * that exception by returning an empty MaybeLocal.
7333  */
7334 using HostImportModuleDynamicallyCallback V8_DEPRECATED(
7335  "Use HostImportModuleDynamicallyWithImportAssertionsCallback instead") =
7336  MaybeLocal<Promise> (*)(Local<Context> context,
7337  Local<ScriptOrModule> referrer,
7338  Local<String> specifier);
7339 
7340 /**
7341  * HostImportModuleDynamicallyWithImportAssertionsCallback is called when we
7342  * require the embedder to load a module. This is used as part of the dynamic
7343  * import syntax.
7344  *
7345  * The referrer contains metadata about the script/module that calls
7346  * import.
7347  *
7348  * The specifier is the name of the module that should be imported.
7349  *
7350  * The import_assertions are import assertions for this request in the form:
7351  * [key1, value1, key2, value2, ...] where the keys and values are of type
7352  * v8::String. Note, unlike the FixedArray passed to ResolveModuleCallback and
7353  * returned from ModuleRequest::GetImportAssertions(), this array does not
7354  * contain the source Locations of the assertions.
7355  *
7356  * The embedder must compile, instantiate, evaluate the Module, and
7357  * obtain its namespace object.
7358  *
7359  * The Promise returned from this function is forwarded to userland
7360  * JavaScript. The embedder must resolve this promise with the module
7361  * namespace object. In case of an exception, the embedder must reject
7362  * this promise with the exception. If the promise creation itself
7363  * fails (e.g. due to stack overflow), the embedder must propagate
7364  * that exception by returning an empty MaybeLocal.
7365  */
7366 using HostImportModuleDynamicallyWithImportAssertionsCallback =
7367  MaybeLocal<Promise> (*)(Local<Context> context,
7368  Local<ScriptOrModule> referrer,
7369  Local<String> specifier,
7370  Local<FixedArray> import_assertions);
7371 
7372 /**
7373  * HostInitializeImportMetaObjectCallback is called the first time import.meta
7374  * is accessed for a module. Subsequent access will reuse the same value.
7375  *
7376  * The method combines two implementation-defined abstract operations into one:
7377  * HostGetImportMetaProperties and HostFinalizeImportMeta.
7378  *
7379  * The embedder should use v8::Object::CreateDataProperty to add properties on
7380  * the meta object.
7381  */
7382 using HostInitializeImportMetaObjectCallback = void (*)(Local<Context> context,
7383  Local<Module> module,
7384  Local<Object> meta);
7385 
7386 /**
7387  * PrepareStackTraceCallback is called when the stack property of an error is
7388  * first accessed. The return value will be used as the stack value. If this
7389  * callback is registed, the |Error.prepareStackTrace| API will be disabled.
7390  * |sites| is an array of call sites, specified in
7391  * https://v8.dev/docs/stack-trace-api
7392  */
7393 using PrepareStackTraceCallback = MaybeLocal<Value> (*)(Local<Context> context,
7394  Local<Value> error,
7395  Local<Array> sites);
7396 
7397 /**
7398  * PromiseHook with type kInit is called when a new promise is
7399  * created. When a new promise is created as part of the chain in the
7400  * case of Promise.then or in the intermediate promises created by
7401  * Promise.{race, all}/AsyncFunctionAwait, we pass the parent promise
7402  * otherwise we pass undefined.
7403  *
7404  * PromiseHook with type kResolve is called at the beginning of
7405  * resolve or reject function defined by CreateResolvingFunctions.
7406  *
7407  * PromiseHook with type kBefore is called at the beginning of the
7408  * PromiseReactionJob.
7409  *
7410  * PromiseHook with type kAfter is called right at the end of the
7411  * PromiseReactionJob.
7412  */
7414 
7415 using PromiseHook = void (*)(PromiseHookType type, Local<Promise> promise,
7416  Local<Value> parent);
7417 
7418 // --- Promise Reject Callback ---
7424 };
7425 
7427  public:
7429  Local<Value> value)
7430  : promise_(promise), event_(event), value_(value) {}
7431 
7432  V8_INLINE Local<Promise> GetPromise() const { return promise_; }
7433  V8_INLINE PromiseRejectEvent GetEvent() const { return event_; }
7434  V8_INLINE Local<Value> GetValue() const { return value_; }
7435 
7436  private:
7437  Local<Promise> promise_;
7438  PromiseRejectEvent event_;
7439  Local<Value> value_;
7440 };
7441 
7442 using PromiseRejectCallback = void (*)(PromiseRejectMessage message);
7443 
7444 // --- Microtasks Callbacks ---
7445 using MicrotasksCompletedCallbackWithData = void (*)(Isolate*, void*);
7446 using MicrotaskCallback = void (*)(void* data);
7447 
7448 /**
7449  * Policy for running microtasks:
7450  * - explicit: microtasks are invoked with the
7451  * Isolate::PerformMicrotaskCheckpoint() method;
7452  * - scoped: microtasks invocation is controlled by MicrotasksScope objects;
7453  * - auto: microtasks are invoked when the script call depth decrements
7454  * to zero.
7455  */
7457 
7458 /**
7459  * Represents the microtask queue, where microtasks are stored and processed.
7460  * https://html.spec.whatwg.org/multipage/webappapis.html#microtask-queue
7461  * https://html.spec.whatwg.org/multipage/webappapis.html#enqueuejob(queuename,-job,-arguments)
7462  * https://html.spec.whatwg.org/multipage/webappapis.html#perform-a-microtask-checkpoint
7463  *
7464  * A MicrotaskQueue instance may be associated to multiple Contexts by passing
7465  * it to Context::New(), and they can be detached by Context::DetachGlobal().
7466  * The embedder must keep the MicrotaskQueue instance alive until all associated
7467  * Contexts are gone or detached.
7468  *
7469  * Use the same instance of MicrotaskQueue for all Contexts that may access each
7470  * other synchronously. E.g. for Web embedding, use the same instance for all
7471  * origins that share the same URL scheme and eTLD+1.
7472  */
7474  public:
7475  /**
7476  * Creates an empty MicrotaskQueue instance.
7477  */
7478  static std::unique_ptr<MicrotaskQueue> New(
7479  Isolate* isolate, MicrotasksPolicy policy = MicrotasksPolicy::kAuto);
7480 
7481  virtual ~MicrotaskQueue() = default;
7482 
7483  /**
7484  * Enqueues the callback to the queue.
7485  */
7486  virtual void EnqueueMicrotask(Isolate* isolate,
7487  Local<Function> microtask) = 0;
7488 
7489  /**
7490  * Enqueues the callback to the queue.
7491  */
7492  virtual void EnqueueMicrotask(v8::Isolate* isolate,
7493  MicrotaskCallback callback,
7494  void* data = nullptr) = 0;
7495 
7496  /**
7497  * Adds a callback to notify the embedder after microtasks were run. The
7498  * callback is triggered by explicit RunMicrotasks call or automatic
7499  * microtasks execution (see Isolate::SetMicrotasksPolicy).
7500  *
7501  * Callback will trigger even if microtasks were attempted to run,
7502  * but the microtasks queue was empty and no single microtask was actually
7503  * executed.
7504  *
7505  * Executing scripts inside the callback will not re-trigger microtasks and
7506  * the callback.
7507  */
7509  MicrotasksCompletedCallbackWithData callback, void* data = nullptr) = 0;
7510 
7511  /**
7512  * Removes callback that was installed by AddMicrotasksCompletedCallback.
7513  */
7515  MicrotasksCompletedCallbackWithData callback, void* data = nullptr) = 0;
7516 
7517  /**
7518  * Runs microtasks if no microtask is running on this MicrotaskQueue instance.
7519  */
7520  virtual void PerformCheckpoint(Isolate* isolate) = 0;
7521 
7522  /**
7523  * Returns true if a microtask is running on this MicrotaskQueue instance.
7524  */
7525  virtual bool IsRunningMicrotasks() const = 0;
7526 
7527  /**
7528  * Returns the current depth of nested MicrotasksScope that has
7529  * kRunMicrotasks.
7530  */
7531  virtual int GetMicrotasksScopeDepth() const = 0;
7532 
7533  MicrotaskQueue(const MicrotaskQueue&) = delete;
7535 
7536  private:
7537  friend class internal::MicrotaskQueue;
7538  MicrotaskQueue() = default;
7539 };
7540 
7541 /**
7542  * This scope is used to control microtasks when MicrotasksPolicy::kScoped
7543  * is used on Isolate. In this mode every non-primitive call to V8 should be
7544  * done inside some MicrotasksScope.
7545  * Microtasks are executed when topmost MicrotasksScope marked as kRunMicrotasks
7546  * exits.
7547  * kDoNotRunMicrotasks should be used to annotate calls not intended to trigger
7548  * microtasks.
7549  */
7551  public:
7553 
7554  MicrotasksScope(Isolate* isolate, Type type);
7555  MicrotasksScope(Isolate* isolate, MicrotaskQueue* microtask_queue, Type type);
7557 
7558  /**
7559  * Runs microtasks if no kRunMicrotasks scope is currently active.
7560  */
7561  static void PerformCheckpoint(Isolate* isolate);
7562 
7563  /**
7564  * Returns current depth of nested kRunMicrotasks scopes.
7565  */
7566  static int GetCurrentDepth(Isolate* isolate);
7567 
7568  /**
7569  * Returns true while microtasks are being executed.
7570  */
7571  static bool IsRunningMicrotasks(Isolate* isolate);
7572 
7573  // Prevent copying.
7576 
7577  private:
7578  internal::Isolate* const isolate_;
7579  internal::MicrotaskQueue* const microtask_queue_;
7580  bool run_;
7581 };
7582 
7583 // --- Failed Access Check Callback ---
7584 using FailedAccessCheckCallback = void (*)(Local<Object> target,
7585  AccessType type, Local<Value> data);
7586 
7587 // --- AllowCodeGenerationFromStrings callbacks ---
7588 
7589 /**
7590  * Callback to check if code generation from strings is allowed. See
7591  * Context::AllowCodeGenerationFromStrings.
7592  */
7593 using AllowCodeGenerationFromStringsCallback = bool (*)(Local<Context> context,
7594  Local<String> source);
7595 
7597  // If true, proceed with the codegen algorithm. Otherwise, block it.
7598  bool codegen_allowed = false;
7599  // Overwrite the original source with this string, if present.
7600  // Use the original source if empty.
7601  // This field is considered only if codegen_allowed is true.
7603 };
7604 
7605 /**
7606  * Callback to check if codegen is allowed from a source object, and convert
7607  * the source to string if necessary. See: ModifyCodeGenerationFromStrings.
7608  */
7609 using ModifyCodeGenerationFromStringsCallback =
7611  Local<Value> source);
7612 using ModifyCodeGenerationFromStringsCallback2 =
7614  Local<Value> source,
7615  bool is_code_like);
7616 
7617 // --- WebAssembly compilation callbacks ---
7618 using ExtensionCallback = bool (*)(const FunctionCallbackInfo<Value>&);
7619 
7620 using AllowWasmCodeGenerationCallback = bool (*)(Local<Context> context,
7621  Local<String> source);
7622 
7623 // --- Callback for APIs defined on v8-supported objects, but implemented
7624 // by the embedder. Example: WebAssembly.{compile|instantiate}Streaming ---
7625 using ApiImplementationCallback = void (*)(const FunctionCallbackInfo<Value>&);
7626 
7627 // --- Callback for WebAssembly.compileStreaming ---
7628 using WasmStreamingCallback = void (*)(const FunctionCallbackInfo<Value>&);
7629 
7630 // --- Callback for loading source map file for Wasm profiling support
7631 using WasmLoadSourceMapCallback = Local<String> (*)(Isolate* isolate,
7632  const char* name);
7633 
7634 // --- Callback for checking if WebAssembly Simd is enabled ---
7635 using WasmSimdEnabledCallback = bool (*)(Local<Context> context);
7636 
7637 // --- Callback for checking if WebAssembly exceptions are enabled ---
7638 using WasmExceptionsEnabledCallback = bool (*)(Local<Context> context);
7639 
7640 // --- Callback for checking if the SharedArrayBuffer constructor is enabled ---
7641 using SharedArrayBufferConstructorEnabledCallback =
7642  bool (*)(Local<Context> context);
7643 
7644 // --- Garbage Collection Callbacks ---
7645 
7646 /**
7647  * Applications can register callback functions which will be called before and
7648  * after certain garbage collection operations. Allocations are not allowed in
7649  * the callback functions, you therefore cannot manipulate objects (set or
7650  * delete properties for example) since it is possible such operations will
7651  * result in the allocation of objects.
7652  */
7653 enum GCType {
7660 };
7661 
7662 /**
7663  * GCCallbackFlags is used to notify additional information about the GC
7664  * callback.
7665  * - kGCCallbackFlagConstructRetainedObjectInfos: The GC callback is for
7666  * constructing retained object infos.
7667  * - kGCCallbackFlagForced: The GC callback is for a forced GC for testing.
7668  * - kGCCallbackFlagSynchronousPhantomCallbackProcessing: The GC callback
7669  * is called synchronously without getting posted to an idle task.
7670  * - kGCCallbackFlagCollectAllAvailableGarbage: The GC callback is called
7671  * in a phase where V8 is trying to collect all available garbage
7672  * (e.g., handling a low memory notification).
7673  * - kGCCallbackScheduleIdleGarbageCollection: The GC callback is called to
7674  * trigger an idle garbage collection.
7675  */
7684 };
7685 
7686 using GCCallback = void (*)(GCType type, GCCallbackFlags flags);
7687 
7688 using InterruptCallback = void (*)(Isolate* isolate, void* data);
7689 
7690 /**
7691  * This callback is invoked when the heap size is close to the heap limit and
7692  * V8 is likely to abort with out-of-memory error.
7693  * The callback can extend the heap limit by returning a value that is greater
7694  * than the current_heap_limit. The initial heap limit is the limit that was
7695  * set after heap setup.
7696  */
7697 using NearHeapLimitCallback = size_t (*)(void* data, size_t current_heap_limit,
7698  size_t initial_heap_limit);
7699 
7700 /**
7701  * Collection of shared per-process V8 memory information.
7702  *
7703  * Instances of this class can be passed to
7704  * v8::V8::GetSharedMemoryStatistics to get shared memory statistics from V8.
7705  */
7707  public:
7709  size_t read_only_space_size() { return read_only_space_size_; }
7710  size_t read_only_space_used_size() { return read_only_space_used_size_; }
7712  return read_only_space_physical_size_;
7713  }
7714 
7715  private:
7716  size_t read_only_space_size_;
7717  size_t read_only_space_used_size_;
7718  size_t read_only_space_physical_size_;
7719 
7720  friend class V8;
7721  friend class internal::ReadOnlyHeap;
7722 };
7723 
7724 /**
7725  * Collection of V8 heap information.
7726  *
7727  * Instances of this class can be passed to v8::Isolate::GetHeapStatistics to
7728  * get heap statistics from V8.
7729  */
7731  public:
7733  size_t total_heap_size() { return total_heap_size_; }
7734  size_t total_heap_size_executable() { return total_heap_size_executable_; }
7735  size_t total_physical_size() { return total_physical_size_; }
7736  size_t total_available_size() { return total_available_size_; }
7737  size_t total_global_handles_size() { return total_global_handles_size_; }
7738  size_t used_global_handles_size() { return used_global_handles_size_; }
7739  size_t used_heap_size() { return used_heap_size_; }
7740  size_t heap_size_limit() { return heap_size_limit_; }
7741  size_t malloced_memory() { return malloced_memory_; }
7742  size_t external_memory() { return external_memory_; }
7743  size_t peak_malloced_memory() { return peak_malloced_memory_; }
7744  size_t number_of_native_contexts() { return number_of_native_contexts_; }
7745  size_t number_of_detached_contexts() { return number_of_detached_contexts_; }
7746 
7747  /**
7748  * Returns a 0/1 boolean, which signifies whether the V8 overwrite heap
7749  * garbage with a bit pattern.
7750  */
7751  size_t does_zap_garbage() { return does_zap_garbage_; }
7752 
7753  private:
7754  size_t total_heap_size_;
7755  size_t total_heap_size_executable_;
7756  size_t total_physical_size_;
7757  size_t total_available_size_;
7758  size_t used_heap_size_;
7759  size_t heap_size_limit_;
7760  size_t malloced_memory_;
7761  size_t external_memory_;
7762  size_t peak_malloced_memory_;
7763  bool does_zap_garbage_;
7764  size_t number_of_native_contexts_;
7765  size_t number_of_detached_contexts_;
7766  size_t total_global_handles_size_;
7767  size_t used_global_handles_size_;
7768 
7769  friend class V8;
7770  friend class Isolate;
7771 };
7772 
7773 
7775  public:
7777  const char* space_name() { return space_name_; }
7778  size_t space_size() { return space_size_; }
7779  size_t space_used_size() { return space_used_size_; }
7780  size_t space_available_size() { return space_available_size_; }
7781  size_t physical_space_size() { return physical_space_size_; }
7782 
7783  private:
7784  const char* space_name_;
7785  size_t space_size_;
7786  size_t space_used_size_;
7787  size_t space_available_size_;
7788  size_t physical_space_size_;
7789 
7790  friend class Isolate;
7791 };
7792 
7793 
7795  public:
7797  const char* object_type() { return object_type_; }
7798  const char* object_sub_type() { return object_sub_type_; }
7799  size_t object_count() { return object_count_; }
7800  size_t object_size() { return object_size_; }
7801 
7802  private:
7803  const char* object_type_;
7804  const char* object_sub_type_;
7805  size_t object_count_;
7806  size_t object_size_;
7807 
7808  friend class Isolate;
7809 };
7810 
7812  public:
7814  size_t code_and_metadata_size() { return code_and_metadata_size_; }
7815  size_t bytecode_and_metadata_size() { return bytecode_and_metadata_size_; }
7816  size_t external_script_source_size() { return external_script_source_size_; }
7817 
7818  private:
7819  size_t code_and_metadata_size_;
7820  size_t bytecode_and_metadata_size_;
7821  size_t external_script_source_size_;
7822 
7823  friend class Isolate;
7824 };
7825 
7826 /**
7827  * A JIT code event is issued each time code is added, moved or removed.
7828  *
7829  * \note removal events are not currently issued.
7830  */
7832  enum EventType {
7839  };
7840  // Definition of the code position type. The "POSITION" type means the place
7841  // in the source code which are of interest when making stack traces to
7842  // pin-point the source location of a stack frame as close as possible.
7843  // The "STATEMENT_POSITION" means the place at the beginning of each
7844  // statement, and is used to indicate possible break locations.
7846 
7847  // There are two different kinds of JitCodeEvents, one for JIT code generated
7848  // by the optimizing compiler, and one for byte code generated for the
7849  // interpreter. For JIT_CODE events, the |code_start| member of the event
7850  // points to the beginning of jitted assembly code, while for BYTE_CODE
7851  // events, |code_start| points to the first bytecode of the interpreted
7852  // function.
7854 
7855  // Type of event.
7858  // Start of the instructions.
7859  void* code_start;
7860  // Size of the instructions.
7861  size_t code_len;
7862  // Script info for CODE_ADDED event.
7864  // User-defined data for *_LINE_INFO_* event. It's used to hold the source
7865  // code line information which is returned from the
7866  // CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent
7867  // CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events.
7868  void* user_data;
7869 
7870  struct name_t {
7871  // Name of the object associated with the code, note that the string is not
7872  // zero-terminated.
7873  const char* str;
7874  // Number of chars in str.
7875  size_t len;
7876  };
7877 
7878  struct line_info_t {
7879  // PC offset
7880  size_t offset;
7881  // Code position
7882  size_t pos;
7883  // The position type.
7885  };
7886 
7888  // Source file name.
7889  const char* filename;
7890  // Length of filename.
7892  // Line number table, which maps offsets of JITted code to line numbers of
7893  // source file.
7895  // Number of entries in the line number table.
7897  };
7898 
7900 
7901  union {
7902  // Only valid for CODE_ADDED.
7903  struct name_t name;
7904 
7905  // Only valid for CODE_ADD_LINE_POS_INFO
7906  struct line_info_t line_info;
7907 
7908  // New location of instructions. Only valid for CODE_MOVED.
7910  };
7911 
7913 };
7914 
7915 /**
7916  * Option flags passed to the SetRAILMode function.
7917  * See documentation https://developers.google.com/web/tools/chrome-devtools/
7918  * profile/evaluate-performance/rail
7919  */
7920 enum RAILMode : unsigned {
7921  // Response performance mode: In this mode very low virtual machine latency
7922  // is provided. V8 will try to avoid JavaScript execution interruptions.
7923  // Throughput may be throttled.
7925  // Animation performance mode: In this mode low virtual machine latency is
7926  // provided. V8 will try to avoid as many JavaScript execution interruptions
7927  // as possible. Throughput may be throttled. This is the default mode.
7929  // Idle performance mode: The embedder is idle. V8 can complete deferred work
7930  // in this mode.
7932  // Load performance mode: In this mode high throughput is provided. V8 may
7933  // turn off latency optimizations.
7935 };
7936 
7937 /**
7938  * Option flags passed to the SetJitCodeEventHandler function.
7939  */
7942  // Generate callbacks for already existent code.
7944 };
7945 
7946 
7947 /**
7948  * Callback function passed to SetJitCodeEventHandler.
7949  *
7950  * \param event code add, move or removal event.
7951  */
7952 using JitCodeEventHandler = void (*)(const JitCodeEvent* event);
7953 
7954 /**
7955  * Callback function passed to SetUnhandledExceptionCallback.
7956  */
7957 #if defined(V8_OS_WIN)
7960 #endif
7961 
7962 /**
7963  * Interface for iterating through all external resources in the heap.
7964  */
7966  public:
7967  virtual ~ExternalResourceVisitor() = default;
7968  virtual void VisitExternalString(Local<String> string) {}
7969 };
7970 
7971 /**
7972  * Interface for iterating through all the persistent handles in the heap.
7973  */
7975  public:
7976  virtual ~PersistentHandleVisitor() = default;
7978  uint16_t class_id) {}
7979 };
7980 
7981 /**
7982  * Memory pressure level for the MemoryPressureNotification.
7983  * kNone hints V8 that there is no memory pressure.
7984  * kModerate hints V8 to speed up incremental garbage collection at the cost of
7985  * of higher latency due to garbage collection pauses.
7986  * kCritical hints V8 to free memory as soon as possible. Garbage collection
7987  * pauses at this level will be large.
7988  */
7990 
7991 /**
7992  * Handler for embedder roots on non-unified heap garbage collections.
7993  */
7995  public:
7996  virtual ~EmbedderRootsHandler() = default;
7997 
7998  /**
7999  * Returns true if the TracedGlobal handle should be considered as root for
8000  * the currently running non-tracing garbage collection and false otherwise.
8001  * The default implementation will keep all TracedGlobal references as roots.
8002  *
8003  * If this returns false, then V8 may decide that the object referred to by
8004  * such a handle is reclaimed. In that case:
8005  * - No action is required if handles are used with destructors, i.e., by just
8006  * using |TracedGlobal|.
8007  * - When run without destructors, i.e., by using |TracedReference|, V8 calls
8008  * |ResetRoot|.
8009  *
8010  * Note that the |handle| is different from the handle that the embedder holds
8011  * for retaining the object. The embedder may use |WrapperClassId()| to
8012  * distinguish cases where it wants handles to be treated as roots from not
8013  * being treated as roots.
8014  */
8015  virtual bool IsRoot(const v8::TracedReference<v8::Value>& handle) = 0;
8016  virtual bool IsRoot(const v8::TracedGlobal<v8::Value>& handle) = 0;
8017 
8018  /**
8019  * Used in combination with |IsRoot|. Called by V8 when an
8020  * object that is backed by a handle is reclaimed by a non-tracing garbage
8021  * collection. It is up to the embedder to reset the original handle.
8022  *
8023  * Note that the |handle| is different from the handle that the embedder holds
8024  * for retaining the object. It is up to the embedder to find the original
8025  * handle via the object or class id.
8026  */
8027  virtual void ResetRoot(const v8::TracedReference<v8::Value>& handle) = 0;
8028 };
8029 
8030 /**
8031  * Interface for tracing through the embedder heap. During a V8 garbage
8032  * collection, V8 collects hidden fields of all potential wrappers, and at the
8033  * end of its marking phase iterates the collection and asks the embedder to
8034  * trace through its heap and use reporter to report each JavaScript object
8035  * reachable from any of the given wrappers.
8036  */
8038  public:
8039  using EmbedderStackState = cppgc::EmbedderStackState;
8040 
8043  kReduceMemory = 1 << 0,
8044  kForced = 1 << 2,
8045  };
8046 
8047  /**
8048  * Interface for iterating through TracedGlobal handles.
8049  */
8051  public:
8052  virtual ~TracedGlobalHandleVisitor() = default;
8053  virtual void VisitTracedGlobalHandle(const TracedGlobal<Value>& handle) {}
8054  virtual void VisitTracedReference(const TracedReference<Value>& handle) {}
8055  };
8056 
8057  /**
8058  * Summary of a garbage collection cycle. See |TraceEpilogue| on how the
8059  * summary is reported.
8060  */
8061  struct TraceSummary {
8062  /**
8063  * Time spent managing the retained memory in milliseconds. This can e.g.
8064  * include the time tracing through objects in the embedder.
8065  */
8066  double time = 0.0;
8067 
8068  /**
8069  * Memory retained by the embedder through the |EmbedderHeapTracer|
8070  * mechanism in bytes.
8071  */
8072  size_t allocated_size = 0;
8073  };
8074 
8075  virtual ~EmbedderHeapTracer() = default;
8076 
8077  /**
8078  * Iterates all TracedGlobal handles created for the v8::Isolate the tracer is
8079  * attached to.
8080  */
8082 
8083  /**
8084  * Called by the embedder to set the start of the stack which is e.g. used by
8085  * V8 to determine whether handles are used from stack or heap.
8086  */
8087  void SetStackStart(void* stack_start);
8088 
8089  /**
8090  * Called by the embedder to notify V8 of an empty execution stack.
8091  */
8093  "This call only optimized internal caches which V8 is able to figure out "
8094  "on its own now.")
8095  void NotifyEmptyEmbedderStack();
8096 
8097  /**
8098  * Called by v8 to register internal fields of found wrappers.
8099  *
8100  * The embedder is expected to store them somewhere and trace reachable
8101  * wrappers from them when called through |AdvanceTracing|.
8102  */
8103  virtual void RegisterV8References(
8104  const std::vector<std::pair<void*, void*> >& embedder_fields) = 0;
8105 
8107 
8108  /**
8109  * Called at the beginning of a GC cycle.
8110  */
8111  virtual void TracePrologue(TraceFlags flags) {}
8112 
8113  /**
8114  * Called to advance tracing in the embedder.
8115  *
8116  * The embedder is expected to trace its heap starting from wrappers reported
8117  * by RegisterV8References method, and report back all reachable wrappers.
8118  * Furthermore, the embedder is expected to stop tracing by the given
8119  * deadline. A deadline of infinity means that tracing should be finished.
8120  *
8121  * Returns |true| if tracing is done, and false otherwise.
8122  */
8123  virtual bool AdvanceTracing(double deadline_in_ms) = 0;
8124 
8125  /*
8126  * Returns true if there no more tracing work to be done (see AdvanceTracing)
8127  * and false otherwise.
8128  */
8129  virtual bool IsTracingDone() = 0;
8130 
8131  /**
8132  * Called at the end of a GC cycle.
8133  *
8134  * Note that allocation is *not* allowed within |TraceEpilogue|. Can be
8135  * overriden to fill a |TraceSummary| that is used by V8 to schedule future
8136  * garbage collections.
8137  */
8138  virtual void TraceEpilogue(TraceSummary* trace_summary) {}
8139 
8140  /**
8141  * Called upon entering the final marking pause. No more incremental marking
8142  * steps will follow this call.
8143  */
8144  virtual void EnterFinalPause(EmbedderStackState stack_state) = 0;
8145 
8146  /*
8147  * Called by the embedder to request immediate finalization of the currently
8148  * running tracing phase that has been started with TracePrologue and not
8149  * yet finished with TraceEpilogue.
8150  *
8151  * Will be a noop when currently not in tracing.
8152  *
8153  * This is an experimental feature.
8154  */
8156 
8157  /**
8158  * See documentation on EmbedderRootsHandler.
8159  */
8161  const v8::TracedReference<v8::Value>& handle);
8162  virtual bool IsRootForNonTracingGC(const v8::TracedGlobal<v8::Value>& handle);
8163 
8164  /**
8165  * See documentation on EmbedderRootsHandler.
8166  */
8168  const v8::TracedReference<v8::Value>& handle);
8169 
8170  /*
8171  * Called by the embedder to immediately perform a full garbage collection.
8172  *
8173  * Should only be used in testing code.
8174  */
8175  void GarbageCollectionForTesting(EmbedderStackState stack_state);
8176 
8177  /*
8178  * Called by the embedder to signal newly allocated or freed memory. Not bound
8179  * to tracing phases. Embedders should trade off when increments are reported
8180  * as V8 may consult global heuristics on whether to trigger garbage
8181  * collection on this change.
8182  */
8183  void IncreaseAllocatedSize(size_t bytes);
8184  void DecreaseAllocatedSize(size_t bytes);
8185 
8186  /*
8187  * Returns the v8::Isolate this tracer is attached too and |nullptr| if it
8188  * is not attached to any v8::Isolate.
8189  */
8190  v8::Isolate* isolate() const { return isolate_; }
8191 
8192  protected:
8193  v8::Isolate* isolate_ = nullptr;
8194 
8195  friend class internal::LocalEmbedderHeapTracer;
8196 };
8197 
8198 /**
8199  * Callback and supporting data used in SnapshotCreator to implement embedder
8200  * logic to serialize internal fields.
8201  * Internal fields that directly reference V8 objects are serialized without
8202  * calling this callback. Internal fields that contain aligned pointers are
8203  * serialized by this callback if it returns non-zero result. Otherwise it is
8204  * serialized verbatim.
8205  */
8207  using CallbackFunction = StartupData (*)(Local<Object> holder, int index,
8208  void* data);
8209  SerializeInternalFieldsCallback(CallbackFunction function = nullptr,
8210  void* data_arg = nullptr)
8211  : callback(function), data(data_arg) {}
8212  CallbackFunction callback;
8213  void* data;
8214 };
8215 // Note that these fields are called "internal fields" in the API and called
8216 // "embedder fields" within V8.
8217 using SerializeEmbedderFieldsCallback = SerializeInternalFieldsCallback;
8218 
8219 /**
8220  * Callback and supporting data used to implement embedder logic to deserialize
8221  * internal fields.
8222  */
8224  using CallbackFunction = void (*)(Local<Object> holder, int index,
8225  StartupData payload, void* data);
8226  DeserializeInternalFieldsCallback(CallbackFunction function = nullptr,
8227  void* data_arg = nullptr)
8228  : callback(function), data(data_arg) {}
8229  void (*callback)(Local<Object> holder, int index, StartupData payload,
8230  void* data);
8231  void* data;
8232 };
8233 using DeserializeEmbedderFieldsCallback = DeserializeInternalFieldsCallback;
8234 
8235 /**
8236  * Controls how the default MeasureMemoryDelegate reports the result of
8237  * the memory measurement to JS. With kSummary only the total size is reported.
8238  * With kDetailed the result includes the size of each native context.
8239  */
8241 
8242 /**
8243  * Controls how promptly a memory measurement request is executed.
8244  * By default the measurement is folded with the next scheduled GC which may
8245  * happen after a while and is forced after some timeout.
8246  * The kEager mode starts incremental GC right away and is useful for testing.
8247  * The kLazy mode does not force GC.
8248  */
8250 
8251 /**
8252  * The delegate is used in Isolate::MeasureMemory API.
8253  *
8254  * It specifies the contexts that need to be measured and gets called when
8255  * the measurement is completed to report the results.
8256  */
8258  public:
8259  virtual ~MeasureMemoryDelegate() = default;
8260 
8261  /**
8262  * Returns true if the size of the given context needs to be measured.
8263  */
8264  virtual bool ShouldMeasure(Local<Context> context) = 0;
8265 
8266  /**
8267  * This function is called when memory measurement finishes.
8268  *
8269  * \param context_sizes_in_bytes a vector of (context, size) pairs that
8270  * includes each context for which ShouldMeasure returned true and that
8271  * was not garbage collected while the memory measurement was in progress.
8272  *
8273  * \param unattributed_size_in_bytes total size of objects that were not
8274  * attributed to any context (i.e. are likely shared objects).
8275  */
8276  virtual void MeasurementComplete(
8277  const std::vector<std::pair<Local<Context>, size_t>>&
8278  context_sizes_in_bytes,
8279  size_t unattributed_size_in_bytes) = 0;
8280 
8281  /**
8282  * Returns a default delegate that resolves the given promise when
8283  * the memory measurement completes.
8284  *
8285  * \param isolate the current isolate
8286  * \param context the current context
8287  * \param promise_resolver the promise resolver that is given the
8288  * result of the memory measurement.
8289  * \param mode the detail level of the result.
8290  */
8291  static std::unique_ptr<MeasureMemoryDelegate> Default(
8292  Isolate* isolate, Local<Context> context,
8293  Local<Promise::Resolver> promise_resolver, MeasureMemoryMode mode);
8294 };
8295 
8296 /**
8297  * Isolate represents an isolated instance of the V8 engine. V8 isolates have
8298  * completely separate states. Objects from one isolate must not be used in
8299  * other isolates. The embedder can create multiple isolates and use them in
8300  * parallel in multiple threads. An isolate can be entered by at most one
8301  * thread at any given time. The Locker/Unlocker API must be used to
8302  * synchronize.
8303  */
8305  public:
8306  /**
8307  * Initial configuration parameters for a new Isolate.
8308  */
8312 
8313  /**
8314  * Allows the host application to provide the address of a function that is
8315  * notified each time code is added, moved or removed.
8316  */
8317  JitCodeEventHandler code_event_handler = nullptr;
8318 
8319  /**
8320  * ResourceConstraints to use for the new Isolate.
8321  */
8323 
8324  /**
8325  * Explicitly specify a startup snapshot blob. The embedder owns the blob.
8326  */
8328 
8329  /**
8330  * Enables the host application to provide a mechanism for recording
8331  * statistics counters.
8332  */
8333  CounterLookupCallback counter_lookup_callback = nullptr;
8334 
8335  /**
8336  * Enables the host application to provide a mechanism for recording
8337  * histograms. The CreateHistogram function returns a
8338  * histogram which will later be passed to the AddHistogramSample
8339  * function.
8340  */
8341  CreateHistogramCallback create_histogram_callback = nullptr;
8342  AddHistogramSampleCallback add_histogram_sample_callback = nullptr;
8343 
8344  /**
8345  * The ArrayBuffer::Allocator to use for allocating and freeing the backing
8346  * store of ArrayBuffers.
8347  *
8348  * If the shared_ptr version is used, the Isolate instance and every
8349  * |BackingStore| allocated using this allocator hold a std::shared_ptr
8350  * to the allocator, in order to facilitate lifetime
8351  * management for the allocator instance.
8352  */
8355 
8356  /**
8357  * Specifies an optional nullptr-terminated array of raw addresses in the
8358  * embedder that V8 can match against during serialization and use for
8359  * deserialization. This array and its content must stay valid for the
8360  * entire lifetime of the isolate.
8361  */
8362  const intptr_t* external_references = nullptr;
8363 
8364  /**
8365  * Whether calling Atomics.wait (a function that may block) is allowed in
8366  * this isolate. This can also be configured via SetAllowAtomicsWait.
8367  */
8368  bool allow_atomics_wait = true;
8369 
8370  /**
8371  * Termination is postponed when there is no active SafeForTerminationScope.
8372  */
8374 
8375  /**
8376  * The following parameters describe the offsets for addressing type info
8377  * for wrapped API objects and are used by the fast C API
8378  * (for details see v8-fast-api-calls.h).
8379  */
8382  };
8383 
8384  /**
8385  * Stack-allocated class which sets the isolate for all operations
8386  * executed within a local scope.
8387  */
8389  public:
8390  explicit Scope(Isolate* isolate) : isolate_(isolate) {
8391  isolate->Enter();
8392  }
8393 
8394  ~Scope() { isolate_->Exit(); }
8395 
8396  // Prevent copying of Scope objects.
8397  Scope(const Scope&) = delete;
8398  Scope& operator=(const Scope&) = delete;
8399 
8400  private:
8401  Isolate* const isolate_;
8402  };
8403 
8404  /**
8405  * Assert that no Javascript code is invoked.
8406  */
8408  public:
8410 
8413 
8414  // Prevent copying of Scope objects.
8416  delete;
8418  const DisallowJavascriptExecutionScope&) = delete;
8419 
8420  private:
8421  OnFailure on_failure_;
8422  Isolate* isolate_;
8423 
8424  bool was_execution_allowed_assert_;
8425  bool was_execution_allowed_throws_;
8426  bool was_execution_allowed_dump_;
8427  };
8428 
8429  /**
8430  * Introduce exception to DisallowJavascriptExecutionScope.
8431  */
8433  public:
8436 
8437  // Prevent copying of Scope objects.
8439  delete;
8441  const AllowJavascriptExecutionScope&) = delete;
8442 
8443  private:
8444  Isolate* isolate_;
8445  bool was_execution_allowed_assert_;
8446  bool was_execution_allowed_throws_;
8447  bool was_execution_allowed_dump_;
8448  };
8449 
8450  /**
8451  * Do not run microtasks while this scope is active, even if microtasks are
8452  * automatically executed otherwise.
8453  */
8455  public:
8457  Isolate* isolate, MicrotaskQueue* microtask_queue = nullptr);
8459 
8460  // Prevent copying of Scope objects.
8462  delete;
8464  const SuppressMicrotaskExecutionScope&) = delete;
8465 
8466  private:
8467  internal::Isolate* const isolate_;
8468  internal::MicrotaskQueue* const microtask_queue_;
8469  internal::Address previous_stack_height_;
8470 
8471  friend class internal::ThreadLocalTop;
8472  };
8473 
8474  /**
8475  * This scope allows terminations inside direct V8 API calls and forbid them
8476  * inside any recursive API calls without explicit SafeForTerminationScope.
8477  */
8479  public:
8480  explicit SafeForTerminationScope(v8::Isolate* isolate);
8482 
8483  // Prevent copying of Scope objects.
8486 
8487  private:
8488  internal::Isolate* isolate_;
8489  bool prev_value_;
8490  };
8491 
8492  /**
8493  * Types of garbage collections that can be requested via
8494  * RequestGarbageCollectionForTesting.
8495  */
8499  };
8500 
8501  /**
8502  * Features reported via the SetUseCounterCallback callback. Do not change
8503  * assigned numbers of existing items; add new features to the end of this
8504  * list.
8505  */
8507  kUseAsm = 0,
8559  kAtomicsNotify = 52, // Unused.
8560  kAtomicsWake = 53, // Unused.
8566  kLocale = 59,
8581  kDateGetTimezoneOffset = 74, // Unused.
8616  kWasmBulkMemory = 109, // Unused.
8620 
8621  // If you add new values here, you'll also need to update Chromium's:
8622  // web_feature.mojom, use_counter_callback.cc, and enums.xml. V8 changes to
8623  // this list need to be landed first, then changes on the Chromium side.
8624  kUseCounterFeatureCount // This enum value must be last.
8625  };
8626 
8628  kMessageLog = (1 << 0),
8629  kMessageDebug = (1 << 1),
8630  kMessageInfo = (1 << 2),
8631  kMessageError = (1 << 3),
8632  kMessageWarning = (1 << 4),
8635  };
8636 
8637  using UseCounterCallback = void (*)(Isolate* isolate,
8638  UseCounterFeature feature);
8639 
8640  /**
8641  * Allocates a new isolate but does not initialize it. Does not change the
8642  * currently entered isolate.
8643  *
8644  * Only Isolate::GetData() and Isolate::SetData(), which access the
8645  * embedder-controlled parts of the isolate, are allowed to be called on the
8646  * uninitialized isolate. To initialize the isolate, call
8647  * Isolate::Initialize().
8648  *
8649  * When an isolate is no longer used its resources should be freed
8650  * by calling Dispose(). Using the delete operator is not allowed.
8651  *
8652  * V8::Initialize() must have run prior to this.
8653  */
8654  static Isolate* Allocate();
8655 
8656  /**
8657  * Initialize an Isolate previously allocated by Isolate::Allocate().
8658  */
8659  static void Initialize(Isolate* isolate, const CreateParams& params);
8660 
8661  /**
8662  * Creates a new isolate. Does not change the currently entered
8663  * isolate.
8664  *
8665  * When an isolate is no longer used its resources should be freed
8666  * by calling Dispose(). Using the delete operator is not allowed.
8667  *
8668  * V8::Initialize() must have run prior to this.
8669  */
8670  static Isolate* New(const CreateParams& params);
8671 
8672  /**
8673  * Returns the entered isolate for the current thread or NULL in
8674  * case there is no current isolate.
8675  *
8676  * This method must not be invoked before V8::Initialize() was invoked.
8677  */
8678  static Isolate* GetCurrent();
8679 
8680  /**
8681  * Returns the entered isolate for the current thread or NULL in
8682  * case there is no current isolate.
8683  *
8684  * No checks are performed by this method.
8685  */
8687 
8688  /**
8689  * Clears the set of objects held strongly by the heap. This set of
8690  * objects are originally built when a WeakRef is created or
8691  * successfully dereferenced.
8692  *
8693  * This is invoked automatically after microtasks are run. See
8694  * MicrotasksPolicy for when microtasks are run.
8695  *
8696  * This needs to be manually invoked only if the embedder is manually running
8697  * microtasks via a custom MicrotaskQueue class's PerformCheckpoint. In that
8698  * case, it is the embedder's responsibility to make this call at a time which
8699  * does not interrupt synchronous ECMAScript code execution.
8700  */
8702 
8703  /**
8704  * Custom callback used by embedders to help V8 determine if it should abort
8705  * when it throws and no internal handler is predicted to catch the
8706  * exception. If --abort-on-uncaught-exception is used on the command line,
8707  * then V8 will abort if either:
8708  * - no custom callback is set.
8709  * - the custom callback set returns true.
8710  * Otherwise, the custom callback will not be called and V8 will not abort.
8711  */
8712  using AbortOnUncaughtExceptionCallback = bool (*)(Isolate*);
8714  AbortOnUncaughtExceptionCallback callback);
8715 
8716  /**
8717  * This specifies the callback called by the upcoming dynamic
8718  * import() language feature to load modules.
8719  */
8721  "Use the version of SetHostImportModuleDynamicallyCallback that takes a "
8722  "HostImportModuleDynamicallyWithImportAssertionsCallback instead")
8723  void SetHostImportModuleDynamicallyCallback(
8724  HostImportModuleDynamicallyCallback callback);
8725 
8726  /**
8727  * This specifies the callback called by the upcoming dynamic
8728  * import() language feature to load modules.
8729  */
8731  HostImportModuleDynamicallyWithImportAssertionsCallback callback);
8732 
8733  /**
8734  * This specifies the callback called by the upcoming import.meta
8735  * language feature to retrieve host-defined meta data for a module.
8736  */
8738  HostInitializeImportMetaObjectCallback callback);
8739 
8740  /**
8741  * This specifies the callback called when the stack property of Error
8742  * is accessed.
8743  */
8744  void SetPrepareStackTraceCallback(PrepareStackTraceCallback callback);
8745 
8746  /**
8747  * Optional notification that the system is running low on memory.
8748  * V8 uses these notifications to guide heuristics.
8749  * It is allowed to call this function from another thread while
8750  * the isolate is executing long running JavaScript code.
8751  */
8753 
8754  /**
8755  * Drop non-essential caches. Should only be called from testing code.
8756  * The method can potentially block for a long time and does not necessarily
8757  * trigger GC.
8758  */
8760 
8761  /**
8762  * Methods below this point require holding a lock (using Locker) in
8763  * a multi-threaded environment.
8764  */
8765 
8766  /**
8767  * Sets this isolate as the entered one for the current thread.
8768  * Saves the previously entered one (if any), so that it can be
8769  * restored when exiting. Re-entering an isolate is allowed.
8770  */
8771  void Enter();
8772 
8773  /**
8774  * Exits this isolate by restoring the previously entered one in the
8775  * current thread. The isolate may still stay the same, if it was
8776  * entered more than once.
8777  *
8778  * Requires: this == Isolate::GetCurrent().
8779  */
8780  void Exit();
8781 
8782  /**
8783  * Disposes the isolate. The isolate must not be entered by any
8784  * thread to be disposable.
8785  */
8786  void Dispose();
8787 
8788  /**
8789  * Dumps activated low-level V8 internal stats. This can be used instead
8790  * of performing a full isolate disposal.
8791  */
8793 
8794  /**
8795  * Discards all V8 thread-specific data for the Isolate. Should be used
8796  * if a thread is terminating and it has used an Isolate that will outlive
8797  * the thread -- all thread-specific data for an Isolate is discarded when
8798  * an Isolate is disposed so this call is pointless if an Isolate is about
8799  * to be Disposed.
8800  */
8802 
8803  /**
8804  * Associate embedder-specific data with the isolate. |slot| has to be
8805  * between 0 and GetNumberOfDataSlots() - 1.
8806  */
8807  V8_INLINE void SetData(uint32_t slot, void* data);
8808 
8809  /**
8810  * Retrieve embedder-specific data from the isolate.
8811  * Returns NULL if SetData has never been called for the given |slot|.
8812  */
8813  V8_INLINE void* GetData(uint32_t slot);
8814 
8815  /**
8816  * Returns the maximum number of available embedder data slots. Valid slots
8817  * are in the range of 0 - GetNumberOfDataSlots() - 1.
8818  */
8819  V8_INLINE static uint32_t GetNumberOfDataSlots();
8820 
8821  /**
8822  * Return data that was previously attached to the isolate snapshot via
8823  * SnapshotCreator, and removes the reference to it.
8824  * Repeated call with the same index returns an empty MaybeLocal.
8825  */
8826  template <class T>
8828 
8829  /**
8830  * Get statistics about the heap memory usage.
8831  */
8832  void GetHeapStatistics(HeapStatistics* heap_statistics);
8833 
8834  /**
8835  * Returns the number of spaces in the heap.
8836  */
8838 
8839  /**
8840  * Get the memory usage of a space in the heap.
8841  *
8842  * \param space_statistics The HeapSpaceStatistics object to fill in
8843  * statistics.
8844  * \param index The index of the space to get statistics from, which ranges
8845  * from 0 to NumberOfHeapSpaces() - 1.
8846  * \returns true on success.
8847  */
8849  size_t index);
8850 
8851  /**
8852  * Returns the number of types of objects tracked in the heap at GC.
8853  */
8855 
8856  /**
8857  * Get statistics about objects in the heap.
8858  *
8859  * \param object_statistics The HeapObjectStatistics object to fill in
8860  * statistics of objects of given type, which were live in the previous GC.
8861  * \param type_index The index of the type of object to fill details about,
8862  * which ranges from 0 to NumberOfTrackedHeapObjectTypes() - 1.
8863  * \returns true on success.
8864  */
8866  size_t type_index);
8867 
8868  /**
8869  * Get statistics about code and its metadata in the heap.
8870  *
8871  * \param object_statistics The HeapCodeStatistics object to fill in
8872  * statistics of code, bytecode and their metadata.
8873  * \returns true on success.
8874  */
8876 
8877  /**
8878  * This API is experimental and may change significantly.
8879  *
8880  * Enqueues a memory measurement request and invokes the delegate with the
8881  * results.
8882  *
8883  * \param delegate the delegate that defines which contexts to measure and
8884  * reports the results.
8885  *
8886  * \param execution promptness executing the memory measurement.
8887  * The kEager value is expected to be used only in tests.
8888  */
8890  std::unique_ptr<MeasureMemoryDelegate> delegate,
8892 
8893  /**
8894  * Get a call stack sample from the isolate.
8895  * \param state Execution state.
8896  * \param frames Caller allocated buffer to store stack frames.
8897  * \param frames_limit Maximum number of frames to capture. The buffer must
8898  * be large enough to hold the number of frames.
8899  * \param sample_info The sample info is filled up by the function
8900  * provides number of actual captured stack frames and
8901  * the current VM state.
8902  * \note GetStackSample should only be called when the JS thread is paused or
8903  * interrupted. Otherwise the behavior is undefined.
8904  */
8905  void GetStackSample(const RegisterState& state, void** frames,
8906  size_t frames_limit, SampleInfo* sample_info);
8907 
8908  /**
8909  * Adjusts the amount of registered external memory. Used to give V8 an
8910  * indication of the amount of externally allocated memory that is kept alive
8911  * by JavaScript objects. V8 uses this to decide when to perform global
8912  * garbage collections. Registering externally allocated memory will trigger
8913  * global garbage collections more often than it would otherwise in an attempt
8914  * to garbage collect the JavaScript objects that keep the externally
8915  * allocated memory alive.
8916  *
8917  * \param change_in_bytes the change in externally allocated memory that is
8918  * kept alive by JavaScript objects.
8919  * \returns the adjusted value.
8920  */
8921  int64_t AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes);
8922 
8923  /**
8924  * Returns the number of phantom handles without callbacks that were reset
8925  * by the garbage collector since the last call to this function.
8926  */
8928 
8929  /**
8930  * Returns heap profiler for this isolate. Will return NULL until the isolate
8931  * is initialized.
8932  */
8934 
8935  /**
8936  * Tells the VM whether the embedder is idle or not.
8937  */
8938  void SetIdle(bool is_idle);
8939 
8940  /** Returns the ArrayBuffer::Allocator used in this isolate. */
8942 
8943  /** Returns true if this isolate has a current context. */
8944  bool InContext();
8945 
8946  /**
8947  * Returns the context of the currently running JavaScript, or the context
8948  * on the top of the stack if no JavaScript is running.
8949  */
8951 
8952  /**
8953  * Returns either the last context entered through V8's C++ API, or the
8954  * context of the currently running microtask while processing microtasks.
8955  * If a context is entered while executing a microtask, that context is
8956  * returned.
8957  */
8959 
8960  /**
8961  * Returns the Context that corresponds to the Incumbent realm in HTML spec.
8962  * https://html.spec.whatwg.org/multipage/webappapis.html#incumbent
8963  */
8965 
8966  /**
8967  * Schedules a v8::Exception::Error with the given message.
8968  * See ThrowException for more details. Templatized to provide compile-time
8969  * errors in case of too long strings (see v8::String::NewFromUtf8Literal).
8970  */
8971  template <int N>
8972  Local<Value> ThrowError(const char (&message)[N]) {
8973  return ThrowError(String::NewFromUtf8Literal(this, message));
8974  }
8976 
8977  /**
8978  * Schedules an exception to be thrown when returning to JavaScript. When an
8979  * exception has been scheduled it is illegal to invoke any JavaScript
8980  * operation; the caller must return immediately and only after the exception
8981  * has been handled does it become legal to invoke JavaScript operations.
8982  */
8984 
8985  using GCCallback = void (*)(Isolate* isolate, GCType type,
8986  GCCallbackFlags flags);
8987  using GCCallbackWithData = void (*)(Isolate* isolate, GCType type,
8988  GCCallbackFlags flags, void* data);
8989 
8990  /**
8991  * Enables the host application to receive a notification before a
8992  * garbage collection. Allocations are allowed in the callback function,
8993  * but the callback is not re-entrant: if the allocation inside it will
8994  * trigger the garbage collection, the callback won't be called again.
8995  * It is possible to specify the GCType filter for your callback. But it is
8996  * not possible to register the same callback function two times with
8997  * different GCType filters.
8998  */
8999  void AddGCPrologueCallback(GCCallbackWithData callback, void* data = nullptr,
9000  GCType gc_type_filter = kGCTypeAll);
9001  void AddGCPrologueCallback(GCCallback callback,
9002  GCType gc_type_filter = kGCTypeAll);
9003 
9004  /**
9005  * This function removes callback which was installed by
9006  * AddGCPrologueCallback function.
9007  */
9008  void RemoveGCPrologueCallback(GCCallbackWithData, void* data = nullptr);
9009  void RemoveGCPrologueCallback(GCCallback callback);
9010 
9011  /**
9012  * Sets the embedder heap tracer for the isolate.
9013  */
9015 
9016  /*
9017  * Gets the currently active heap tracer for the isolate.
9018  */
9020 
9021  /**
9022  * Sets an embedder roots handle that V8 should consider when performing
9023  * non-unified heap garbage collections.
9024  *
9025  * Using only EmbedderHeapTracer automatically sets up a default handler.
9026  * The intended use case is for setting a custom handler after invoking
9027  * `AttachCppHeap()`.
9028  *
9029  * V8 does not take ownership of the handler.
9030  */
9032 
9033  /**
9034  * Attaches a managed C++ heap as an extension to the JavaScript heap. The
9035  * embedder maintains ownership of the CppHeap. At most one C++ heap can be
9036  * attached to V8.
9037  *
9038  * This is an experimental feature and may still change significantly.
9039  */
9041 
9042  /**
9043  * Detaches a managed C++ heap if one was attached using `AttachCppHeap()`.
9044  *
9045  * This is an experimental feature and may still change significantly.
9046  */
9048 
9049  /**
9050  * This is an experimental feature and may still change significantly.
9051 
9052  * \returns the C++ heap managed by V8. Only available if such a heap has been
9053  * attached using `AttachCppHeap()`.
9054  */
9056 
9057  /**
9058  * Use for |AtomicsWaitCallback| to indicate the type of event it receives.
9059  */
9060  enum class AtomicsWaitEvent {
9061  /** Indicates that this call is happening before waiting. */
9062  kStartWait,
9063  /** `Atomics.wait()` finished because of an `Atomics.wake()` call. */
9064  kWokenUp,
9065  /** `Atomics.wait()` finished because it timed out. */
9066  kTimedOut,
9067  /** `Atomics.wait()` was interrupted through |TerminateExecution()|. */
9069  /** `Atomics.wait()` was stopped through |AtomicsWaitWakeHandle|. */
9070  kAPIStopped,
9071  /** `Atomics.wait()` did not wait, as the initial condition was not met. */
9072  kNotEqual
9073  };
9074 
9075  /**
9076  * Passed to |AtomicsWaitCallback| as a means of stopping an ongoing
9077  * `Atomics.wait` call.
9078  */
9080  public:
9081  /**
9082  * Stop this `Atomics.wait()` call and call the |AtomicsWaitCallback|
9083  * with |kAPIStopped|.
9084  *
9085  * This function may be called from another thread. The caller has to ensure
9086  * through proper synchronization that it is not called after
9087  * the finishing |AtomicsWaitCallback|.
9088  *
9089  * Note that the ECMAScript specification does not plan for the possibility
9090  * of wakeups that are neither coming from a timeout or an `Atomics.wake()`
9091  * call, so this may invalidate assumptions made by existing code.
9092  * The embedder may accordingly wish to schedule an exception in the
9093  * finishing |AtomicsWaitCallback|.
9094  */
9095  void Wake();
9096  };
9097 
9098  /**
9099  * Embedder callback for `Atomics.wait()` that can be added through
9100  * |SetAtomicsWaitCallback|.
9101  *
9102  * This will be called just before starting to wait with the |event| value
9103  * |kStartWait| and after finishing waiting with one of the other
9104  * values of |AtomicsWaitEvent| inside of an `Atomics.wait()` call.
9105  *
9106  * |array_buffer| will refer to the underlying SharedArrayBuffer,
9107  * |offset_in_bytes| to the location of the waited-on memory address inside
9108  * the SharedArrayBuffer.
9109  *
9110  * |value| and |timeout_in_ms| will be the values passed to
9111  * the `Atomics.wait()` call. If no timeout was used, |timeout_in_ms|
9112  * will be `INFINITY`.
9113  *
9114  * In the |kStartWait| callback, |stop_handle| will be an object that
9115  * is only valid until the corresponding finishing callback and that
9116  * can be used to stop the wait process while it is happening.
9117  *
9118  * This callback may schedule exceptions, *unless* |event| is equal to
9119  * |kTerminatedExecution|.
9120  */
9121  using AtomicsWaitCallback = void (*)(AtomicsWaitEvent event,
9122  Local<SharedArrayBuffer> array_buffer,
9123  size_t offset_in_bytes, int64_t value,
9124  double timeout_in_ms,
9125  AtomicsWaitWakeHandle* stop_handle,
9126  void* data);
9127 
9128  /**
9129  * Set a new |AtomicsWaitCallback|. This overrides an earlier
9130  * |AtomicsWaitCallback|, if there was any. If |callback| is nullptr,
9131  * this unsets the callback. |data| will be passed to the callback
9132  * as its last parameter.
9133  */
9134  void SetAtomicsWaitCallback(AtomicsWaitCallback callback, void* data);
9135 
9136  /**
9137  * Enables the host application to receive a notification after a
9138  * garbage collection. Allocations are allowed in the callback function,
9139  * but the callback is not re-entrant: if the allocation inside it will
9140  * trigger the garbage collection, the callback won't be called again.
9141  * It is possible to specify the GCType filter for your callback. But it is
9142  * not possible to register the same callback function two times with
9143  * different GCType filters.
9144  */
9145  void AddGCEpilogueCallback(GCCallbackWithData callback, void* data = nullptr,
9146  GCType gc_type_filter = kGCTypeAll);
9147  void AddGCEpilogueCallback(GCCallback callback,
9148  GCType gc_type_filter = kGCTypeAll);
9149 
9150  /**
9151  * This function removes callback which was installed by
9152  * AddGCEpilogueCallback function.
9153  */
9154  void RemoveGCEpilogueCallback(GCCallbackWithData callback,
9155  void* data = nullptr);
9156  void RemoveGCEpilogueCallback(GCCallback callback);
9157 
9158  using GetExternallyAllocatedMemoryInBytesCallback = size_t (*)();
9159 
9160  /**
9161  * Set the callback that tells V8 how much memory is currently allocated
9162  * externally of the V8 heap. Ideally this memory is somehow connected to V8
9163  * objects and may get freed-up when the corresponding V8 objects get
9164  * collected by a V8 garbage collection.
9165  */
9167  GetExternallyAllocatedMemoryInBytesCallback callback);
9168 
9169  /**
9170  * Forcefully terminate the current thread of JavaScript execution
9171  * in the given isolate.
9172  *
9173  * This method can be used by any thread even if that thread has not
9174  * acquired the V8 lock with a Locker object.
9175  */
9177 
9178  /**
9179  * Is V8 terminating JavaScript execution.
9180  *
9181  * Returns true if JavaScript execution is currently terminating
9182  * because of a call to TerminateExecution. In that case there are
9183  * still JavaScript frames on the stack and the termination
9184  * exception is still active.
9185  */
9187 
9188  /**
9189  * Resume execution capability in the given isolate, whose execution
9190  * was previously forcefully terminated using TerminateExecution().
9191  *
9192  * When execution is forcefully terminated using TerminateExecution(),
9193  * the isolate can not resume execution until all JavaScript frames
9194  * have propagated the uncatchable exception which is generated. This
9195  * method allows the program embedding the engine to handle the
9196  * termination event and resume execution capability, even if
9197  * JavaScript frames remain on the stack.
9198  *
9199  * This method can be used by any thread even if that thread has not
9200  * acquired the V8 lock with a Locker object.
9201  */
9203 
9204  /**
9205  * Request V8 to interrupt long running JavaScript code and invoke
9206  * the given |callback| passing the given |data| to it. After |callback|
9207  * returns control will be returned to the JavaScript code.
9208  * There may be a number of interrupt requests in flight.
9209  * Can be called from another thread without acquiring a |Locker|.
9210  * Registered |callback| must not reenter interrupted Isolate.
9211  */
9212  void RequestInterrupt(InterruptCallback callback, void* data);
9213 
9214  /**
9215  * Returns true if there is ongoing background work within V8 that will
9216  * eventually post a foreground task, like asynchronous WebAssembly
9217  * compilation.
9218  */
9220 
9221  /**
9222  * Request garbage collection in this Isolate. It is only valid to call this
9223  * function if --expose_gc was specified.
9224  *
9225  * This should only be used for testing purposes and not to enforce a garbage
9226  * collection schedule. It has strong negative impact on the garbage
9227  * collection performance. Use IdleNotificationDeadline() or
9228  * LowMemoryNotification() instead to influence the garbage collection
9229  * schedule.
9230  */
9232 
9233  /**
9234  * Set the callback to invoke for logging event.
9235  */
9236  void SetEventLogger(LogEventCallback that);
9237 
9238  /**
9239  * Adds a callback to notify the host application right before a script
9240  * is about to run. If a script re-enters the runtime during executing, the
9241  * BeforeCallEnteredCallback is invoked for each re-entrance.
9242  * Executing scripts inside the callback will re-trigger the callback.
9243  */
9244  void AddBeforeCallEnteredCallback(BeforeCallEnteredCallback callback);
9245 
9246  /**
9247  * Removes callback that was installed by AddBeforeCallEnteredCallback.
9248  */
9249  void RemoveBeforeCallEnteredCallback(BeforeCallEnteredCallback callback);
9250 
9251  /**
9252  * Adds a callback to notify the host application when a script finished
9253  * running. If a script re-enters the runtime during executing, the
9254  * CallCompletedCallback is only invoked when the outer-most script
9255  * execution ends. Executing scripts inside the callback do not trigger
9256  * further callbacks.
9257  */
9258  void AddCallCompletedCallback(CallCompletedCallback callback);
9259 
9260  /**
9261  * Removes callback that was installed by AddCallCompletedCallback.
9262  */
9263  void RemoveCallCompletedCallback(CallCompletedCallback callback);
9264 
9265  /**
9266  * Set the PromiseHook callback for various promise lifecycle
9267  * events.
9268  */
9269  void SetPromiseHook(PromiseHook hook);
9270 
9271  /**
9272  * Set callback to notify about promise reject with no handler, or
9273  * revocation of such a previous notification once the handler is added.
9274  */
9275  void SetPromiseRejectCallback(PromiseRejectCallback callback);
9276 
9277  /**
9278  * Runs the default MicrotaskQueue until it gets empty and perform other
9279  * microtask checkpoint steps, such as calling ClearKeptObjects. Asserts that
9280  * the MicrotasksPolicy is not kScoped. Any exceptions thrown by microtask
9281  * callbacks are swallowed.
9282  */
9284 
9285  /**
9286  * Enqueues the callback to the default MicrotaskQueue
9287  */
9288  void EnqueueMicrotask(Local<Function> microtask);
9289 
9290  /**
9291  * Enqueues the callback to the default MicrotaskQueue
9292  */
9293  void EnqueueMicrotask(MicrotaskCallback callback, void* data = nullptr);
9294 
9295  /**
9296  * Controls how Microtasks are invoked. See MicrotasksPolicy for details.
9297  */
9299 
9300  /**
9301  * Returns the policy controlling how Microtasks are invoked.
9302  */
9304 
9305  /**
9306  * Adds a callback to notify the host application after
9307  * microtasks were run on the default MicrotaskQueue. The callback is
9308  * triggered by explicit RunMicrotasks call or automatic microtasks execution
9309  * (see SetMicrotaskPolicy).
9310  *
9311  * Callback will trigger even if microtasks were attempted to run,
9312  * but the microtasks queue was empty and no single microtask was actually
9313  * executed.
9314  *
9315  * Executing scripts inside the callback will not re-trigger microtasks and
9316  * the callback.
9317  */
9319  MicrotasksCompletedCallbackWithData callback, void* data = nullptr);
9320 
9321  /**
9322  * Removes callback that was installed by AddMicrotasksCompletedCallback.
9323  */
9325  MicrotasksCompletedCallbackWithData callback, void* data = nullptr);
9326 
9327  /**
9328  * Sets a callback for counting the number of times a feature of V8 is used.
9329  */
9330  void SetUseCounterCallback(UseCounterCallback callback);
9331 
9332  /**
9333  * Enables the host application to provide a mechanism for recording
9334  * statistics counters.
9335  */
9336  void SetCounterFunction(CounterLookupCallback);
9337 
9338  /**
9339  * Enables the host application to provide a mechanism for recording
9340  * histograms. The CreateHistogram function returns a
9341  * histogram which will later be passed to the AddHistogramSample
9342  * function.
9343  */
9344  void SetCreateHistogramFunction(CreateHistogramCallback);
9345  void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
9346 
9347  /**
9348  * Enables the host application to provide a mechanism for recording
9349  * event based metrics. In order to use this interface
9350  * include/v8-metrics.h
9351  * needs to be included and the recorder needs to be derived from the
9352  * Recorder base class defined there.
9353  * This method can only be called once per isolate and must happen during
9354  * isolate initialization before background threads are spawned.
9355  */
9357  const std::shared_ptr<metrics::Recorder>& metrics_recorder);
9358 
9359  /**
9360  * Enables the host application to provide a mechanism for recording a
9361  * predefined set of data as crash keys to be used in postmortem debugging in
9362  * case of a crash.
9363  */
9364  void SetAddCrashKeyCallback(AddCrashKeyCallback);
9365 
9366  /**
9367  * Optional notification that the embedder is idle.
9368  * V8 uses the notification to perform garbage collection.
9369  * This call can be used repeatedly if the embedder remains idle.
9370  * Returns true if the embedder should stop calling IdleNotificationDeadline
9371  * until real work has been done. This indicates that V8 has done
9372  * as much cleanup as it will be able to do.
9373  *
9374  * The deadline_in_seconds argument specifies the deadline V8 has to finish
9375  * garbage collection work. deadline_in_seconds is compared with
9376  * MonotonicallyIncreasingTime() and should be based on the same timebase as
9377  * that function. There is no guarantee that the actual work will be done
9378  * within the time limit.
9379  */
9380  bool IdleNotificationDeadline(double deadline_in_seconds);
9381 
9382  /**
9383  * Optional notification that the system is running low on memory.
9384  * V8 uses these notifications to attempt to free memory.
9385  */
9387 
9388  /**
9389  * Optional notification that a context has been disposed. V8 uses these
9390  * notifications to guide the GC heuristic and cancel FinalizationRegistry
9391  * cleanup tasks. Returns the number of context disposals - including this one
9392  * - since the last time V8 had a chance to clean up.
9393  *
9394  * The optional parameter |dependant_context| specifies whether the disposed
9395  * context was depending on state from other contexts or not.
9396  */
9397  int ContextDisposedNotification(bool dependant_context = true);
9398 
9399  /**
9400  * Optional notification that the isolate switched to the foreground.
9401  * V8 uses these notifications to guide heuristics.
9402  */
9404 
9405  /**
9406  * Optional notification that the isolate switched to the background.
9407  * V8 uses these notifications to guide heuristics.
9408  */
9410 
9411  /**
9412  * Optional notification which will enable the memory savings mode.
9413  * V8 uses this notification to guide heuristics which may result in a
9414  * smaller memory footprint at the cost of reduced runtime performance.
9415  */
9417 
9418  /**
9419  * Optional notification which will disable the memory savings mode.
9420  */
9422 
9423  /**
9424  * Optional notification to tell V8 the current performance requirements
9425  * of the embedder based on RAIL.
9426  * V8 uses these notifications to guide heuristics.
9427  * This is an unfinished experimental feature. Semantics and implementation
9428  * may change frequently.
9429  */
9430  void SetRAILMode(RAILMode rail_mode);
9431 
9432  /**
9433  * Update load start time of the RAIL mode
9434  */
9436 
9437  /**
9438  * Optional notification to tell V8 the current isolate is used for debugging
9439  * and requires higher heap limit.
9440  */
9442 
9443  /**
9444  * Restores the original heap limit after IncreaseHeapLimitForDebugging().
9445  */
9447 
9448  /**
9449  * Returns true if the heap limit was increased for debugging and the
9450  * original heap limit was not restored yet.
9451  */
9453 
9454  /**
9455  * Allows the host application to provide the address of a function that is
9456  * notified each time code is added, moved or removed.
9457  *
9458  * \param options options for the JIT code event handler.
9459  * \param event_handler the JIT code event handler, which will be invoked
9460  * each time code is added, moved or removed.
9461  * \note \p event_handler won't get notified of existent code.
9462  * \note since code removal notifications are not currently issued, the
9463  * \p event_handler may get notifications of code that overlaps earlier
9464  * code notifications. This happens when code areas are reused, and the
9465  * earlier overlapping code areas should therefore be discarded.
9466  * \note the events passed to \p event_handler and the strings they point to
9467  * are not guaranteed to live past each call. The \p event_handler must
9468  * copy strings and other parameters it needs to keep around.
9469  * \note the set of events declared in JitCodeEvent::EventType is expected to
9470  * grow over time, and the JitCodeEvent structure is expected to accrue
9471  * new members. The \p event_handler function must ignore event codes
9472  * it does not recognize to maintain future compatibility.
9473  * \note Use Isolate::CreateParams to get events for code executed during
9474  * Isolate setup.
9475  */
9477  JitCodeEventHandler event_handler);
9478 
9479  /**
9480  * Modifies the stack limit for this Isolate.
9481  *
9482  * \param stack_limit An address beyond which the Vm's stack may not grow.
9483  *
9484  * \note If you are using threads then you should hold the V8::Locker lock
9485  * while setting the stack limit and you must set a non-default stack
9486  * limit separately for each thread.
9487  */
9488  void SetStackLimit(uintptr_t stack_limit);
9489 
9490  /**
9491  * Returns a memory range that can potentially contain jitted code. Code for
9492  * V8's 'builtins' will not be in this range if embedded builtins is enabled.
9493  *
9494  * On Win64, embedders are advised to install function table callbacks for
9495  * these ranges, as default SEH won't be able to unwind through jitted code.
9496  * The first page of the code range is reserved for the embedder and is
9497  * committed, writable, and executable, to be used to store unwind data, as
9498  * documented in
9499  * https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64.
9500  *
9501  * Might be empty on other platforms.
9502  *
9503  * https://code.google.com/p/v8/issues/detail?id=3598
9504  */
9505  void GetCodeRange(void** start, size_t* length_in_bytes);
9506 
9507  /**
9508  * As GetCodeRange, but for embedded builtins (these live in a distinct
9509  * memory region from other V8 Code objects).
9510  */
9511  void GetEmbeddedCodeRange(const void** start, size_t* length_in_bytes);
9512 
9513  /**
9514  * Returns the JSEntryStubs necessary for use with the Unwinder API.
9515  */
9517 
9518  static constexpr size_t kMinCodePagesBufferSize = 32;
9519 
9520  /**
9521  * Copies the code heap pages currently in use by V8 into |code_pages_out|.
9522  * |code_pages_out| must have at least kMinCodePagesBufferSize capacity and
9523  * must be empty.
9524  *
9525  * Signal-safe, does not allocate, does not access the V8 heap.
9526  * No code on the stack can rely on pages that might be missing.
9527  *
9528  * Returns the number of pages available to be copied, which might be greater
9529  * than |capacity|. In this case, only |capacity| pages will be copied into
9530  * |code_pages_out|. The caller should provide a bigger buffer on the next
9531  * call in order to get all available code pages, but this is not required.
9532  */
9533  size_t CopyCodePages(size_t capacity, MemoryRange* code_pages_out);
9534 
9535  /** Set the callback to invoke in case of fatal errors. */
9536  void SetFatalErrorHandler(FatalErrorCallback that);
9537 
9538  /** Set the callback to invoke in case of OOM errors. */
9539  void SetOOMErrorHandler(OOMErrorCallback that);
9540 
9541  /**
9542  * Add a callback to invoke in case the heap size is close to the heap limit.
9543  * If multiple callbacks are added, only the most recently added callback is
9544  * invoked.
9545  */
9546  void AddNearHeapLimitCallback(NearHeapLimitCallback callback, void* data);
9547 
9548  /**
9549  * Remove the given callback and restore the heap limit to the
9550  * given limit. If the given limit is zero, then it is ignored.
9551  * If the current heap size is greater than the given limit,
9552  * then the heap limit is restored to the minimal limit that
9553  * is possible for the current heap size.
9554  */
9555  void RemoveNearHeapLimitCallback(NearHeapLimitCallback callback,
9556  size_t heap_limit);
9557 
9558  /**
9559  * If the heap limit was changed by the NearHeapLimitCallback, then the
9560  * initial heap limit will be restored once the heap size falls below the
9561  * given threshold percentage of the initial heap limit.
9562  * The threshold percentage is a number in (0.0, 1.0) range.
9563  */
9564  void AutomaticallyRestoreInitialHeapLimit(double threshold_percent = 0.5);
9565 
9566  /**
9567  * Set the callback to invoke to check if code generation from
9568  * strings should be allowed.
9569  */
9571  ModifyCodeGenerationFromStringsCallback2 callback);
9572 
9573  /**
9574  * Set the callback to invoke to check if wasm code generation should
9575  * be allowed.
9576  */
9578  AllowWasmCodeGenerationCallback callback);
9579 
9580  /**
9581  * Embedder over{ride|load} injection points for wasm APIs. The expectation
9582  * is that the embedder sets them at most once.
9583  */
9584  void SetWasmModuleCallback(ExtensionCallback callback);
9585  void SetWasmInstanceCallback(ExtensionCallback callback);
9586 
9587  void SetWasmStreamingCallback(WasmStreamingCallback callback);
9588 
9589  void SetWasmLoadSourceMapCallback(WasmLoadSourceMapCallback callback);
9590 
9591  void SetWasmSimdEnabledCallback(WasmSimdEnabledCallback callback);
9592 
9593  void SetWasmExceptionsEnabledCallback(WasmExceptionsEnabledCallback callback);
9594 
9596  SharedArrayBufferConstructorEnabledCallback callback);
9597 
9598  /**
9599  * This function can be called by the embedder to signal V8 that the dynamic
9600  * enabling of features has finished. V8 can now set up dynamically added
9601  * features.
9602  */
9604 
9605  /**
9606  * Check if V8 is dead and therefore unusable. This is the case after
9607  * fatal errors such as out-of-memory situations.
9608  */
9609  bool IsDead();
9610 
9611  /**
9612  * Adds a message listener (errors only).
9613  *
9614  * The same message listener can be added more than once and in that
9615  * case it will be called more than once for each message.
9616  *
9617  * If data is specified, it will be passed to the callback when it is called.
9618  * Otherwise, the exception object will be passed to the callback instead.
9619  */
9620  bool AddMessageListener(MessageCallback that,
9621  Local<Value> data = Local<Value>());
9622 
9623  /**
9624  * Adds a message listener.
9625  *
9626  * The same message listener can be added more than once and in that
9627  * case it will be called more than once for each message.
9628  *
9629  * If data is specified, it will be passed to the callback when it is called.
9630  * Otherwise, the exception object will be passed to the callback instead.
9631  *
9632  * A listener can listen for particular error levels by providing a mask.
9633  */
9634  bool AddMessageListenerWithErrorLevel(MessageCallback that,
9635  int message_levels,
9636  Local<Value> data = Local<Value>());
9637 
9638  /**
9639  * Remove all message listeners from the specified callback function.
9640  */
9641  void RemoveMessageListeners(MessageCallback that);
9642 
9643  /** Callback function for reporting failed access checks.*/
9644  void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
9645 
9646  /**
9647  * Tells V8 to capture current stack trace when uncaught exception occurs
9648  * and report it to the message listeners. The option is off by default.
9649  */
9651  bool capture, int frame_limit = 10,
9653 
9654  /**
9655  * Iterates through all external resources referenced from current isolate
9656  * heap. GC is not invoked prior to iterating, therefore there is no
9657  * guarantee that visited objects are still alive.
9658  */
9660 
9661  /**
9662  * Iterates through all the persistent handles in the current isolate's heap
9663  * that have class_ids.
9664  */
9666 
9667  /**
9668  * Iterates through all the persistent handles in the current isolate's heap
9669  * that have class_ids and are weak to be marked as inactive if there is no
9670  * pending activity for the handle.
9671  */
9673 
9674  /**
9675  * Check if this isolate is in use.
9676  * True if at least one thread Enter'ed this isolate.
9677  */
9678  bool IsInUse();
9679 
9680  /**
9681  * Set whether calling Atomics.wait (a function that may block) is allowed in
9682  * this isolate. This can also be configured via
9683  * CreateParams::allow_atomics_wait.
9684  */
9685  void SetAllowAtomicsWait(bool allow);
9686 
9687  /**
9688  * Time zone redetection indicator for
9689  * DateTimeConfigurationChangeNotification.
9690  *
9691  * kSkip indicates V8 that the notification should not trigger redetecting
9692  * host time zone. kRedetect indicates V8 that host time zone should be
9693  * redetected, and used to set the default time zone.
9694  *
9695  * The host time zone detection may require file system access or similar
9696  * operations unlikely to be available inside a sandbox. If v8 is run inside a
9697  * sandbox, the host time zone has to be detected outside the sandbox before
9698  * calling DateTimeConfigurationChangeNotification function.
9699  */
9701 
9702  /**
9703  * Notification that the embedder has changed the time zone, daylight savings
9704  * time or other date / time configuration parameters. V8 keeps a cache of
9705  * various values used for date / time computation. This notification will
9706  * reset those cached values for the current context so that date / time
9707  * configuration changes would be reflected.
9708  *
9709  * This API should not be called more than needed as it will negatively impact
9710  * the performance of date operations.
9711  */
9713  TimeZoneDetection time_zone_detection = TimeZoneDetection::kSkip);
9714 
9715  /**
9716  * Notification that the embedder has changed the locale. V8 keeps a cache of
9717  * various values used for locale computation. This notification will reset
9718  * those cached values for the current context so that locale configuration
9719  * changes would be reflected.
9720  *
9721  * This API should not be called more than needed as it will negatively impact
9722  * the performance of locale operations.
9723  */
9725 
9726  Isolate() = delete;
9727  ~Isolate() = delete;
9728  Isolate(const Isolate&) = delete;
9729  Isolate& operator=(const Isolate&) = delete;
9730  // Deleting operator new and delete here is allowed as ctor and dtor is also
9731  // deleted.
9732  void* operator new(size_t size) = delete;
9733  void* operator new[](size_t size) = delete;
9734  void operator delete(void*, size_t) = delete;
9735  void operator delete[](void*, size_t) = delete;
9736 
9737  private:
9738  template <class K, class V, class Traits>
9740 
9741  internal::Address* GetDataFromSnapshotOnce(size_t index);
9742  void ReportExternalAllocationLimitReached();
9743 };
9744 
9746  public:
9747  /**
9748  * Whether the data created can be rehashed and and the hash seed can be
9749  * recomputed when deserialized.
9750  * Only valid for StartupData returned by SnapshotCreator::CreateBlob().
9751  */
9752  bool CanBeRehashed() const;
9753  /**
9754  * Allows embedders to verify whether the data is valid for the current
9755  * V8 instance.
9756  */
9757  bool IsValid() const;
9758 
9759  const char* data;
9761 };
9762 
9763 /**
9764  * EntropySource is used as a callback function when v8 needs a source
9765  * of entropy.
9766  */
9767 using EntropySource = bool (*)(unsigned char* buffer, size_t length);
9768 
9769 /**
9770  * ReturnAddressLocationResolver is used as a callback function when v8 is
9771  * resolving the location of a return address on the stack. Profilers that
9772  * change the return address on the stack can use this to resolve the stack
9773  * location to wherever the profiler stashed the original return address.
9774  *
9775  * \param return_addr_location A location on stack where a machine
9776  * return address resides.
9777  * \returns Either return_addr_location, or else a pointer to the profiler's
9778  * copy of the original return address.
9779  *
9780  * \note The resolver function must not cause garbage collection.
9781  */
9782 using ReturnAddressLocationResolver =
9783  uintptr_t (*)(uintptr_t return_addr_location);
9784 
9785 /**
9786  * Container class for static utility functions.
9787  */
9788 class V8_EXPORT V8 {
9789  public:
9790  /**
9791  * Hand startup data to V8, in case the embedder has chosen to build
9792  * V8 with external startup data.
9793  *
9794  * Note:
9795  * - By default the startup data is linked into the V8 library, in which
9796  * case this function is not meaningful.
9797  * - If this needs to be called, it needs to be called before V8
9798  * tries to make use of its built-ins.
9799  * - To avoid unnecessary copies of data, V8 will point directly into the
9800  * given data blob, so pretty please keep it around until V8 exit.
9801  * - Compression of the startup blob might be useful, but needs to
9802  * handled entirely on the embedders' side.
9803  * - The call will abort if the data is invalid.
9804  */
9805  static void SetSnapshotDataBlob(StartupData* startup_blob);
9806 
9807  /** Set the callback to invoke in case of Dcheck failures. */
9808  static void SetDcheckErrorHandler(DcheckErrorCallback that);
9809 
9810 
9811  /**
9812  * Sets V8 flags from a string.
9813  */
9814  static void SetFlagsFromString(const char* str);
9815  static void SetFlagsFromString(const char* str, size_t length);
9816 
9817  /**
9818  * Sets V8 flags from the command line.
9819  */
9820  static void SetFlagsFromCommandLine(int* argc,
9821  char** argv,
9822  bool remove_flags);
9823 
9824  /** Get the version string. */
9825  static const char* GetVersion();
9826 
9827  /**
9828  * Initializes V8. This function needs to be called before the first Isolate
9829  * is created. It always returns true.
9830  */
9831  V8_INLINE static bool Initialize() {
9832  const int kBuildConfiguration =
9833  (internal::PointerCompressionIsEnabled() ? kPointerCompression : 0) |
9834  (internal::SmiValuesAre31Bits() ? k31BitSmis : 0) |
9835  (internal::HeapSandboxIsEnabled() ? kHeapSandbox : 0);
9836  return Initialize(kBuildConfiguration);
9837  }
9838 
9839  /**
9840  * Allows the host application to provide a callback which can be used
9841  * as a source of entropy for random number generators.
9842  */
9843  static void SetEntropySource(EntropySource source);
9844 
9845  /**
9846  * Allows the host application to provide a callback that allows v8 to
9847  * cooperate with a profiler that rewrites return addresses on stack.
9848  */
9850  ReturnAddressLocationResolver return_address_resolver);
9851 
9852  /**
9853  * Releases any resources used by v8 and stops any utility threads
9854  * that may be running. Note that disposing v8 is permanent, it
9855  * cannot be reinitialized.
9856  *
9857  * It should generally not be necessary to dispose v8 before exiting
9858  * a process, this should happen automatically. It is only necessary
9859  * to use if the process needs the resources taken up by v8.
9860  */
9861  static bool Dispose();
9862 
9863  /**
9864  * Initialize the ICU library bundled with V8. The embedder should only
9865  * invoke this method when using the bundled ICU. Returns true on success.
9866  *
9867  * If V8 was compiled with the ICU data in an external file, the location
9868  * of the data file has to be provided.
9869  */
9870  static bool InitializeICU(const char* icu_data_file = nullptr);
9871 
9872  /**
9873  * Initialize the ICU library bundled with V8. The embedder should only
9874  * invoke this method when using the bundled ICU. If V8 was compiled with
9875  * the ICU data in an external file and when the default location of that
9876  * file should be used, a path to the executable must be provided.
9877  * Returns true on success.
9878  *
9879  * The default is a file called icudtl.dat side-by-side with the executable.
9880  *
9881  * Optionally, the location of the data file can be provided to override the
9882  * default.
9883  */
9884  static bool InitializeICUDefaultLocation(const char* exec_path,
9885  const char* icu_data_file = nullptr);
9886 
9887  /**
9888  * Initialize the external startup data. The embedder only needs to
9889  * invoke this method when external startup data was enabled in a build.
9890  *
9891  * If V8 was compiled with the startup data in an external file, then
9892  * V8 needs to be given those external files during startup. There are
9893  * three ways to do this:
9894  * - InitializeExternalStartupData(const char*)
9895  * This will look in the given directory for the file "snapshot_blob.bin".
9896  * - InitializeExternalStartupDataFromFile(const char*)
9897  * As above, but will directly use the given file name.
9898  * - Call SetSnapshotDataBlob.
9899  * This will read the blobs from the given data structure and will
9900  * not perform any file IO.
9901  */
9902  static void InitializeExternalStartupData(const char* directory_path);
9903  static void InitializeExternalStartupDataFromFile(const char* snapshot_blob);
9904 
9905  /**
9906  * Sets the v8::Platform to use. This should be invoked before V8 is
9907  * initialized.
9908  */
9909  static void InitializePlatform(Platform* platform);
9910 
9911  /**
9912  * Clears all references to the v8::Platform. This should be invoked after
9913  * V8 was disposed.
9914  */
9915  static void ShutdownPlatform();
9916 
9917  /**
9918  * Activate trap-based bounds checking for WebAssembly.
9919  *
9920  * \param use_v8_signal_handler Whether V8 should install its own signal
9921  * handler or rely on the embedder's.
9922  */
9923  static bool EnableWebAssemblyTrapHandler(bool use_v8_signal_handler);
9924 
9925 #if defined(V8_OS_WIN)
9926  /**
9927  * On Win64, by default V8 does not emit unwinding data for jitted code,
9928  * which means the OS cannot walk the stack frames and the system Structured
9929  * Exception Handling (SEH) cannot unwind through V8-generated code:
9930  * https://code.google.com/p/v8/issues/detail?id=3598.
9931  *
9932  * This function allows embedders to register a custom exception handler for
9933  * exceptions in V8-generated code.
9934  */
9935  static void SetUnhandledExceptionCallback(
9937 #endif
9938 
9939  /**
9940  * Get statistics about the shared memory usage.
9941  */
9943 
9944  private:
9945  V8();
9946 
9947  enum BuildConfigurationFeatures {
9948  kPointerCompression = 1 << 0,
9949  k31BitSmis = 1 << 1,
9950  kHeapSandbox = 1 << 2,
9951  };
9952 
9953  /**
9954  * Checks that the embedder build configuration is compatible with
9955  * the V8 binary and if so initializes V8.
9956  */
9957  static bool Initialize(int build_config);
9958 
9959  static internal::Address* GlobalizeReference(internal::Isolate* isolate,
9960  internal::Address* handle);
9961  static internal::Address* GlobalizeTracedReference(internal::Isolate* isolate,
9962  internal::Address* handle,
9963  internal::Address* slot,
9964  bool has_destructor);
9965  static void MoveGlobalReference(internal::Address** from,
9966  internal::Address** to);
9967  static void MoveTracedGlobalReference(internal::Address** from,
9968  internal::Address** to);
9969  static void CopyTracedGlobalReference(const internal::Address* const* from,
9970  internal::Address** to);
9971  static internal::Address* CopyGlobalReference(internal::Address* from);
9972  static void DisposeGlobal(internal::Address* global_handle);
9973  static void DisposeTracedGlobal(internal::Address* global_handle);
9974  static void MakeWeak(internal::Address* location, void* data,
9975  WeakCallbackInfo<void>::Callback weak_callback,
9976  WeakCallbackType type);
9977  static void MakeWeak(internal::Address** location_addr);
9978  static void* ClearWeak(internal::Address* location);
9979  static void SetFinalizationCallbackTraced(
9980  internal::Address* location, void* parameter,
9981  WeakCallbackInfo<void>::Callback callback);
9982  static void AnnotateStrongRetainer(internal::Address* location,
9983  const char* label);
9984  static Value* Eternalize(Isolate* isolate, Value* handle);
9985 
9986  template <class K, class V, class T>
9988 
9989  static void FromJustIsNothing();
9990  static void ToLocalEmpty();
9991  static void InternalFieldOutOfBounds(int index);
9992  template <class T>
9993  friend class BasicTracedReference;
9994  template <class T>
9995  friend class Global;
9996  template <class T> friend class Local;
9997  template <class T>
9998  friend class MaybeLocal;
9999  template <class T>
10000  friend class Maybe;
10001  template <class T>
10002  friend class TracedGlobal;
10003  friend class TracedReferenceBase;
10004  template <class T>
10005  friend class TracedReference;
10006  template <class T>
10007  friend class WeakCallbackInfo;
10008  template <class T> friend class Eternal;
10009  template <class T> friend class PersistentBase;
10010  template <class T, class M> friend class Persistent;
10011  friend class Context;
10012 };
10013 
10014 /**
10015  * Helper class to create a snapshot data blob.
10016  *
10017  * The Isolate used by a SnapshotCreator is owned by it, and will be entered
10018  * and exited by the constructor and destructor, respectively; The destructor
10019  * will also destroy the Isolate. Experimental language features, including
10020  * those available by default, are not available while creating a snapshot.
10021  */
10023  public:
10025 
10026  /**
10027  * Initialize and enter an isolate, and set it up for serialization.
10028  * The isolate is either created from scratch or from an existing snapshot.
10029  * The caller keeps ownership of the argument snapshot.
10030  * \param existing_blob existing snapshot from which to create this one.
10031  * \param external_references a null-terminated array of external references
10032  * that must be equivalent to CreateParams::external_references.
10033  */
10035  const intptr_t* external_references = nullptr,
10036  StartupData* existing_blob = nullptr);
10037 
10038  /**
10039  * Create and enter an isolate, and set it up for serialization.
10040  * The isolate is either created from scratch or from an existing snapshot.
10041  * The caller keeps ownership of the argument snapshot.
10042  * \param existing_blob existing snapshot from which to create this one.
10043  * \param external_references a null-terminated array of external references
10044  * that must be equivalent to CreateParams::external_references.
10045  */
10046  SnapshotCreator(const intptr_t* external_references = nullptr,
10047  StartupData* existing_blob = nullptr);
10048 
10049  /**
10050  * Destroy the snapshot creator, and exit and dispose of the Isolate
10051  * associated with it.
10052  */
10054 
10055  /**
10056  * \returns the isolate prepared by the snapshot creator.
10057  */
10059 
10060  /**
10061  * Set the default context to be included in the snapshot blob.
10062  * The snapshot will not contain the global proxy, and we expect one or a
10063  * global object template to create one, to be provided upon deserialization.
10064  *
10065  * \param callback optional callback to serialize internal fields.
10066  */
10070 
10071  /**
10072  * Add additional context to be included in the snapshot blob.
10073  * The snapshot will include the global proxy.
10074  *
10075  * \param callback optional callback to serialize internal fields.
10076  *
10077  * \returns the index of the context in the snapshot blob.
10078  */
10079  size_t AddContext(Local<Context> context,
10082 
10083  /**
10084  * Attach arbitrary V8::Data to the context snapshot, which can be retrieved
10085  * via Context::GetDataFromSnapshot after deserialization. This data does not
10086  * survive when a new snapshot is created from an existing snapshot.
10087  * \returns the index for retrieval.
10088  */
10089  template <class T>
10090  V8_INLINE size_t AddData(Local<Context> context, Local<T> object);
10091 
10092  /**
10093  * Attach arbitrary V8::Data to the isolate snapshot, which can be retrieved
10094  * via Isolate::GetDataFromSnapshot after deserialization. This data does not
10095  * survive when a new snapshot is created from an existing snapshot.
10096  * \returns the index for retrieval.
10097  */
10098  template <class T>
10099  V8_INLINE size_t AddData(Local<T> object);
10100 
10101  /**
10102  * Created a snapshot data blob.
10103  * This must not be called from within a handle scope.
10104  * \param function_code_handling whether to include compiled function code
10105  * in the snapshot.
10106  * \returns { nullptr, 0 } on failure, and a startup snapshot on success. The
10107  * caller acquires ownership of the data array in the return value.
10108  */
10110 
10111  // Disallow copying and assigning.
10113  void operator=(const SnapshotCreator&) = delete;
10114 
10115  private:
10116  size_t AddData(Local<Context> context, internal::Address object);
10117  size_t AddData(internal::Address object);
10118 
10119  void* data_;
10120 };
10121 
10122 /**
10123  * A simple Maybe type, representing an object which may or may not have a
10124  * value, see https://hackage.haskell.org/package/base/docs/Data-Maybe.html.
10125  *
10126  * If an API method returns a Maybe<>, the API method can potentially fail
10127  * either because an exception is thrown, or because an exception is pending,
10128  * e.g. because a previous API call threw an exception that hasn't been caught
10129  * yet, or because a TerminateExecution exception was thrown. In that case, a
10130  * "Nothing" value is returned.
10131  */
10132 template <class T>
10133 class Maybe {
10134  public:
10135  V8_INLINE bool IsNothing() const { return !has_value_; }
10136  V8_INLINE bool IsJust() const { return has_value_; }
10137 
10138  /**
10139  * An alias for |FromJust|. Will crash if the Maybe<> is nothing.
10140  */
10141  V8_INLINE T ToChecked() const { return FromJust(); }
10142 
10143  /**
10144  * Short-hand for ToChecked(), which doesn't return a value. To be used, where
10145  * the actual value of the Maybe is not needed like Object::Set.
10146  */
10147  V8_INLINE void Check() const {
10148  if (V8_UNLIKELY(!IsJust())) V8::FromJustIsNothing();
10149  }
10150 
10151  /**
10152  * Converts this Maybe<> to a value of type T. If this Maybe<> is
10153  * nothing (empty), |false| is returned and |out| is left untouched.
10154  */
10155  V8_WARN_UNUSED_RESULT V8_INLINE bool To(T* out) const {
10156  if (V8_LIKELY(IsJust())) *out = value_;
10157  return IsJust();
10158  }
10159 
10160  /**
10161  * Converts this Maybe<> to a value of type T. If this Maybe<> is
10162  * nothing (empty), V8 will crash the process.
10163  */
10164  V8_INLINE T FromJust() const {
10165  if (V8_UNLIKELY(!IsJust())) V8::FromJustIsNothing();
10166  return value_;
10167  }
10168 
10169  /**
10170  * Converts this Maybe<> to a value of type T, using a default value if this
10171  * Maybe<> is nothing (empty).
10172  */
10173  V8_INLINE T FromMaybe(const T& default_value) const {
10174  return has_value_ ? value_ : default_value;
10175  }
10176 
10177  V8_INLINE bool operator==(const Maybe& other) const {
10178  return (IsJust() == other.IsJust()) &&
10179  (!IsJust() || FromJust() == other.FromJust());
10180  }
10181 
10182  V8_INLINE bool operator!=(const Maybe& other) const {
10183  return !operator==(other);
10184  }
10185 
10186  private:
10187  Maybe() : has_value_(false) {}
10188  explicit Maybe(const T& t) : has_value_(true), value_(t) {}
10189 
10190  bool has_value_;
10191  T value_;
10192 
10193  template <class U>
10194  friend Maybe<U> Nothing();
10195  template <class U>
10196  friend Maybe<U> Just(const U& u);
10197 };
10198 
10199 template <class T>
10200 inline Maybe<T> Nothing() {
10201  return Maybe<T>();
10202 }
10203 
10204 template <class T>
10205 inline Maybe<T> Just(const T& t) {
10206  return Maybe<T>(t);
10207 }
10208 
10209 // A template specialization of Maybe<T> for the case of T = void.
10210 template <>
10211 class Maybe<void> {
10212  public:
10213  V8_INLINE bool IsNothing() const { return !is_valid_; }
10214  V8_INLINE bool IsJust() const { return is_valid_; }
10215 
10216  V8_INLINE bool operator==(const Maybe& other) const {
10217  return IsJust() == other.IsJust();
10218  }
10219 
10220  V8_INLINE bool operator!=(const Maybe& other) const {
10221  return !operator==(other);
10222  }
10223 
10224  private:
10225  struct JustTag {};
10226 
10227  Maybe() : is_valid_(false) {}
10228  explicit Maybe(JustTag) : is_valid_(true) {}
10229 
10230  bool is_valid_;
10231 
10232  template <class U>
10233  friend Maybe<U> Nothing();
10234  friend Maybe<void> JustVoid();
10235 };
10236 
10237 inline Maybe<void> JustVoid() { return Maybe<void>(Maybe<void>::JustTag()); }
10238 
10239 /**
10240  * An external exception handler.
10241  */
10243  public:
10244  /**
10245  * Creates a new try/catch block and registers it with v8. Note that
10246  * all TryCatch blocks should be stack allocated because the memory
10247  * location itself is compared against JavaScript try/catch blocks.
10248  */
10249  explicit TryCatch(Isolate* isolate);
10250 
10251  /**
10252  * Unregisters and deletes this try/catch block.
10253  */
10255 
10256  /**
10257  * Returns true if an exception has been caught by this try/catch block.
10258  */
10259  bool HasCaught() const;
10260 
10261  /**
10262  * For certain types of exceptions, it makes no sense to continue execution.
10263  *
10264  * If CanContinue returns false, the correct action is to perform any C++
10265  * cleanup needed and then return. If CanContinue returns false and
10266  * HasTerminated returns true, it is possible to call
10267  * CancelTerminateExecution in order to continue calling into the engine.
10268  */
10269  bool CanContinue() const;
10270 
10271  /**
10272  * Returns true if an exception has been caught due to script execution
10273  * being terminated.
10274  *
10275  * There is no JavaScript representation of an execution termination
10276  * exception. Such exceptions are thrown when the TerminateExecution
10277  * methods are called to terminate a long-running script.
10278  *
10279  * If such an exception has been thrown, HasTerminated will return true,
10280  * indicating that it is possible to call CancelTerminateExecution in order
10281  * to continue calling into the engine.
10282  */
10283  bool HasTerminated() const;
10284 
10285  /**
10286  * Throws the exception caught by this TryCatch in a way that avoids
10287  * it being caught again by this same TryCatch. As with ThrowException
10288  * it is illegal to execute any JavaScript operations after calling
10289  * ReThrow; the caller must return immediately to where the exception
10290  * is caught.
10291  */
10293 
10294  /**
10295  * Returns the exception caught by this try/catch block. If no exception has
10296  * been caught an empty handle is returned.
10297  */
10299 
10300  /**
10301  * Returns the .stack property of an object. If no .stack
10302  * property is present an empty handle is returned.
10303  */
10305  Local<Context> context, Local<Value> exception);
10306 
10307  /**
10308  * Returns the .stack property of the thrown object. If no .stack property is
10309  * present or if this try/catch block has not caught an exception, an empty
10310  * handle is returned.
10311  */
10313  Local<Context> context) const;
10314 
10315  /**
10316  * Returns the message associated with this exception. If there is
10317  * no message associated an empty handle is returned.
10318  */
10319  Local<v8::Message> Message() const;
10320 
10321  /**
10322  * Clears any exceptions that may have been caught by this try/catch block.
10323  * After this method has been called, HasCaught() will return false. Cancels
10324  * the scheduled exception if it is caught and ReThrow() is not called before.
10325  *
10326  * It is not necessary to clear a try/catch block before using it again; if
10327  * another exception is thrown the previously caught exception will just be
10328  * overwritten. However, it is often a good idea since it makes it easier
10329  * to determine which operation threw a given exception.
10330  */
10331  void Reset();
10332 
10333  /**
10334  * Set verbosity of the external exception handler.
10335  *
10336  * By default, exceptions that are caught by an external exception
10337  * handler are not reported. Call SetVerbose with true on an
10338  * external exception handler to have exceptions caught by the
10339  * handler reported as if they were not caught.
10340  */
10341  void SetVerbose(bool value);
10342 
10343  /**
10344  * Returns true if verbosity is enabled.
10345  */
10346  bool IsVerbose() const;
10347 
10348  /**
10349  * Set whether or not this TryCatch should capture a Message object
10350  * which holds source information about where the exception
10351  * occurred. True by default.
10352  */
10353  void SetCaptureMessage(bool value);
10354 
10355  /**
10356  * There are cases when the raw address of C++ TryCatch object cannot be
10357  * used for comparisons with addresses into the JS stack. The cases are:
10358  * 1) ARM, ARM64 and MIPS simulators which have separate JS stack.
10359  * 2) Address sanitizer allocates local C++ object in the heap when
10360  * UseAfterReturn mode is enabled.
10361  * This method returns address that can be used for comparisons with
10362  * addresses into the JS stack. When neither simulator nor ASAN's
10363  * UseAfterReturn is enabled, then the address returned will be the address
10364  * of the C++ try catch handler itself.
10365  */
10366  static void* JSStackComparableAddress(TryCatch* handler) {
10367  if (handler == nullptr) return nullptr;
10368  return handler->js_stack_comparable_address_;
10369  }
10370 
10371  TryCatch(const TryCatch&) = delete;
10372  void operator=(const TryCatch&) = delete;
10373 
10374  private:
10375  // Declaring operator new and delete as deleted is not spec compliant.
10376  // Therefore declare them private instead to disable dynamic alloc
10377  void* operator new(size_t size);
10378  void* operator new[](size_t size);
10379  void operator delete(void*, size_t);
10380  void operator delete[](void*, size_t);
10381 
10382  void ResetInternal();
10383 
10384  internal::Isolate* isolate_;
10385  TryCatch* next_;
10386  void* exception_;
10387  void* message_obj_;
10388  void* js_stack_comparable_address_;
10389  bool is_verbose_ : 1;
10390  bool can_continue_ : 1;
10391  bool capture_message_ : 1;
10392  bool rethrow_ : 1;
10393  bool has_terminated_ : 1;
10394 
10395  friend class internal::Isolate;
10396 };
10397 
10398 
10399 // --- Context ---
10400 
10401 
10402 /**
10403  * A container for extension names.
10404  */
10406  public:
10407  ExtensionConfiguration() : name_count_(0), names_(nullptr) {}
10408  ExtensionConfiguration(int name_count, const char* names[])
10409  : name_count_(name_count), names_(names) { }
10410 
10411  const char** begin() const { return &names_[0]; }
10412  const char** end() const { return &names_[name_count_]; }
10413 
10414  private:
10415  const int name_count_;
10416  const char** names_;
10417 };
10418 
10419 /**
10420  * A sandboxed execution context with its own set of built-in objects
10421  * and functions.
10422  */
10423 class V8_EXPORT Context : public Data {
10424  public:
10425  /**
10426  * Returns the global proxy object.
10427  *
10428  * Global proxy object is a thin wrapper whose prototype points to actual
10429  * context's global object with the properties like Object, etc. This is done
10430  * that way for security reasons (for more details see
10431  * https://wiki.mozilla.org/Gecko:SplitWindow).
10432  *
10433  * Please note that changes to global proxy object prototype most probably
10434  * would break VM---v8 expects only global object as a prototype of global
10435  * proxy object.
10436  */
10438 
10439  /**
10440  * Detaches the global object from its context before
10441  * the global object can be reused to create a new context.
10442  */
10444 
10445  /**
10446  * Creates a new context and returns a handle to the newly allocated
10447  * context.
10448  *
10449  * \param isolate The isolate in which to create the context.
10450  *
10451  * \param extensions An optional extension configuration containing
10452  * the extensions to be installed in the newly created context.
10453  *
10454  * \param global_template An optional object template from which the
10455  * global object for the newly created context will be created.
10456  *
10457  * \param global_object An optional global object to be reused for
10458  * the newly created context. This global object must have been
10459  * created by a previous call to Context::New with the same global
10460  * template. The state of the global object will be completely reset
10461  * and only object identify will remain.
10462  */
10463  static Local<Context> New(
10464  Isolate* isolate, ExtensionConfiguration* extensions = nullptr,
10466  MaybeLocal<Value> global_object = MaybeLocal<Value>(),
10467  DeserializeInternalFieldsCallback internal_fields_deserializer =
10469  MicrotaskQueue* microtask_queue = nullptr);
10470 
10471  /**
10472  * Create a new context from a (non-default) context snapshot. There
10473  * is no way to provide a global object template since we do not create
10474  * a new global object from template, but we can reuse a global object.
10475  *
10476  * \param isolate See v8::Context::New.
10477  *
10478  * \param context_snapshot_index The index of the context snapshot to
10479  * deserialize from. Use v8::Context::New for the default snapshot.
10480  *
10481  * \param embedder_fields_deserializer Optional callback to deserialize
10482  * internal fields. It should match the SerializeInternalFieldCallback used
10483  * to serialize.
10484  *
10485  * \param extensions See v8::Context::New.
10486  *
10487  * \param global_object See v8::Context::New.
10488  */
10490  Isolate* isolate, size_t context_snapshot_index,
10491  DeserializeInternalFieldsCallback embedder_fields_deserializer =
10493  ExtensionConfiguration* extensions = nullptr,
10494  MaybeLocal<Value> global_object = MaybeLocal<Value>(),
10495  MicrotaskQueue* microtask_queue = nullptr);
10496 
10497  /**
10498  * Returns an global object that isn't backed by an actual context.
10499  *
10500  * The global template needs to have access checks with handlers installed.
10501  * If an existing global object is passed in, the global object is detached
10502  * from its context.
10503  *
10504  * Note that this is different from a detached context where all accesses to
10505  * the global proxy will fail. Instead, the access check handlers are invoked.
10506  *
10507  * It is also not possible to detach an object returned by this method.
10508  * Instead, the access check handlers need to return nothing to achieve the
10509  * same effect.
10510  *
10511  * It is possible, however, to create a new context from the global object
10512  * returned by this method.
10513  */
10515  Isolate* isolate, Local<ObjectTemplate> global_template,
10516  MaybeLocal<Value> global_object = MaybeLocal<Value>());
10517 
10518  /**
10519  * Sets the security token for the context. To access an object in
10520  * another context, the security tokens must match.
10521  */
10523 
10524  /** Restores the security token to the default value. */
10526 
10527  /** Returns the security token of this context.*/
10529 
10530  /**
10531  * Enter this context. After entering a context, all code compiled
10532  * and run is compiled and run in this context. If another context
10533  * is already entered, this old context is saved so it can be
10534  * restored when the new context is exited.
10535  */
10536  void Enter();
10537 
10538  /**
10539  * Exit this context. Exiting the current context restores the
10540  * context that was in place when entering the current context.
10541  */
10542  void Exit();
10543 
10544  /** Returns the isolate associated with a current context. */
10546 
10547  /** Returns the microtask queue associated with a current context. */
10549 
10550  /**
10551  * The field at kDebugIdIndex used to be reserved for the inspector.
10552  * It now serves no purpose.
10553  */
10555 
10556  /**
10557  * Return the number of fields allocated for embedder data.
10558  */
10560 
10561  /**
10562  * Gets the embedder data with the given index, which must have been set by a
10563  * previous call to SetEmbedderData with the same index.
10564  */
10565  V8_INLINE Local<Value> GetEmbedderData(int index);
10566 
10567  /**
10568  * Gets the binding object used by V8 extras. Extra natives get a reference
10569  * to this object and can use it to "export" functionality by adding
10570  * properties. Extra natives can also "import" functionality by accessing
10571  * properties added by the embedder using the V8 API.
10572  */
10574 
10575  /**
10576  * Sets the embedder data with the given index, growing the data as
10577  * needed. Note that index 0 currently has a special meaning for Chrome's
10578  * debugger.
10579  */
10580  void SetEmbedderData(int index, Local<Value> value);
10581 
10582  /**
10583  * Gets a 2-byte-aligned native pointer from the embedder data with the given
10584  * index, which must have been set by a previous call to
10585  * SetAlignedPointerInEmbedderData with the same index. Note that index 0
10586  * currently has a special meaning for Chrome's debugger.
10587  */
10589 
10590  /**
10591  * Sets a 2-byte-aligned native pointer in the embedder data with the given
10592  * index, growing the data as needed. Note that index 0 currently has a
10593  * special meaning for Chrome's debugger.
10594  */
10595  void SetAlignedPointerInEmbedderData(int index, void* value);
10596 
10597  /**
10598  * Control whether code generation from strings is allowed. Calling
10599  * this method with false will disable 'eval' and the 'Function'
10600  * constructor for code running in this context. If 'eval' or the
10601  * 'Function' constructor are used an exception will be thrown.
10602  *
10603  * If code generation from strings is not allowed the
10604  * V8::AllowCodeGenerationFromStrings callback will be invoked if
10605  * set before blocking the call to 'eval' or the 'Function'
10606  * constructor. If that callback returns true, the call will be
10607  * allowed, otherwise an exception will be thrown. If no callback is
10608  * set an exception will be thrown.
10609  */
10611 
10612  /**
10613  * Returns true if code generation from strings is allowed for the context.
10614  * For more details see AllowCodeGenerationFromStrings(bool) documentation.
10615  */
10617 
10618  /**
10619  * Sets the error description for the exception that is thrown when
10620  * code generation from strings is not allowed and 'eval' or the 'Function'
10621  * constructor are called.
10622  */
10624 
10625  /**
10626  * Return data that was previously attached to the context snapshot via
10627  * SnapshotCreator, and removes the reference to it.
10628  * Repeated call with the same index returns an empty MaybeLocal.
10629  */
10630  template <class T>
10632 
10633  /**
10634  * If callback is set, abort any attempt to execute JavaScript in this
10635  * context, call the specified callback, and throw an exception.
10636  * To unset abort, pass nullptr as callback.
10637  */
10638  using AbortScriptExecutionCallback = void (*)(Isolate* isolate,
10639  Local<Context> context);
10640  void SetAbortScriptExecution(AbortScriptExecutionCallback callback);
10641 
10642  /**
10643  * Returns the value that was set or restored by
10644  * SetContinuationPreservedEmbedderData(), if any.
10645  */
10647 
10648  /**
10649  * Sets a value that will be stored on continuations and reset while the
10650  * continuation runs.
10651  */
10653 
10654  /**
10655  * Set or clear hooks to be invoked for promise lifecycle operations.
10656  * To clear a hook, set it to an empty v8::Function. Each function will
10657  * receive the observed promise as the first argument. If a chaining
10658  * operation is used on a promise, the init will additionally receive
10659  * the parent promise as the second argument.
10660  */
10661  void SetPromiseHooks(Local<Function> init_hook,
10662  Local<Function> before_hook,
10663  Local<Function> after_hook,
10664  Local<Function> resolve_hook);
10665 
10666  /**
10667  * Stack-allocated class which sets the execution context for all
10668  * operations executed within a local scope.
10669  */
10671  public:
10672  explicit V8_INLINE Scope(Local<Context> context) : context_(context) {
10673  context_->Enter();
10674  }
10675  V8_INLINE ~Scope() { context_->Exit(); }
10676 
10677  private:
10678  Local<Context> context_;
10679  };
10680 
10681  /**
10682  * Stack-allocated class to support the backup incumbent settings object
10683  * stack.
10684  * https://html.spec.whatwg.org/multipage/webappapis.html#backup-incumbent-settings-object-stack
10685  */
10686  class V8_EXPORT V8_NODISCARD BackupIncumbentScope final {
10687  public:
10688  /**
10689  * |backup_incumbent_context| is pushed onto the backup incumbent settings
10690  * object stack.
10691  */
10692  explicit BackupIncumbentScope(Local<Context> backup_incumbent_context);
10694 
10695  /**
10696  * Returns address that is comparable with JS stack address. Note that JS
10697  * stack may be allocated separately from the native stack. See also
10698  * |TryCatch::JSStackComparableAddress| for details.
10699  */
10700  uintptr_t JSStackComparableAddress() const {
10701  return js_stack_comparable_address_;
10702  }
10703 
10704  private:
10705  friend class internal::Isolate;
10706 
10707  Local<Context> backup_incumbent_context_;
10708  uintptr_t js_stack_comparable_address_ = 0;
10709  const BackupIncumbentScope* prev_ = nullptr;
10710  };
10711 
10712  V8_INLINE static Context* Cast(Data* data);
10713 
10714  private:
10715  friend class Value;
10716  friend class Script;
10717  friend class Object;
10718  friend class Function;
10719 
10720  static void CheckCast(Data* obj);
10721 
10722  internal::Address* GetDataFromSnapshotOnce(size_t index);
10723  Local<Value> SlowGetEmbedderData(int index);
10724  void* SlowGetAlignedPointerFromEmbedderData(int index);
10725 };
10726 
10727 /**
10728  * Multiple threads in V8 are allowed, but only one thread at a time is allowed
10729  * to use any given V8 isolate, see the comments in the Isolate class. The
10730  * definition of 'using a V8 isolate' includes accessing handles or holding onto
10731  * object pointers obtained from V8 handles while in the particular V8 isolate.
10732  * It is up to the user of V8 to ensure, perhaps with locking, that this
10733  * constraint is not violated. In addition to any other synchronization
10734  * mechanism that may be used, the v8::Locker and v8::Unlocker classes must be
10735  * used to signal thread switches to V8.
10736  *
10737  * v8::Locker is a scoped lock object. While it's active, i.e. between its
10738  * construction and destruction, the current thread is allowed to use the locked
10739  * isolate. V8 guarantees that an isolate can be locked by at most one thread at
10740  * any time. In other words, the scope of a v8::Locker is a critical section.
10741  *
10742  * Sample usage:
10743 * \code
10744  * ...
10745  * {
10746  * v8::Locker locker(isolate);
10747  * v8::Isolate::Scope isolate_scope(isolate);
10748  * ...
10749  * // Code using V8 and isolate goes here.
10750  * ...
10751  * } // Destructor called here
10752  * \endcode
10753  *
10754  * If you wish to stop using V8 in a thread A you can do this either by
10755  * destroying the v8::Locker object as above or by constructing a v8::Unlocker
10756  * object:
10757  *
10758  * \code
10759  * {
10760  * isolate->Exit();
10761  * v8::Unlocker unlocker(isolate);
10762  * ...
10763  * // Code not using V8 goes here while V8 can run in another thread.
10764  * ...
10765  * } // Destructor called here.
10766  * isolate->Enter();
10767  * \endcode
10768  *
10769  * The Unlocker object is intended for use in a long-running callback from V8,
10770  * where you want to release the V8 lock for other threads to use.
10771  *
10772  * The v8::Locker is a recursive lock, i.e. you can lock more than once in a
10773  * given thread. This can be useful if you have code that can be called either
10774  * from code that holds the lock or from code that does not. The Unlocker is
10775  * not recursive so you can not have several Unlockers on the stack at once, and
10776  * you can not use an Unlocker in a thread that is not inside a Locker's scope.
10777  *
10778  * An unlocker will unlock several lockers if it has to and reinstate the
10779  * correct depth of locking on its destruction, e.g.:
10780  *
10781  * \code
10782  * // V8 not locked.
10783  * {
10784  * v8::Locker locker(isolate);
10785  * Isolate::Scope isolate_scope(isolate);
10786  * // V8 locked.
10787  * {
10788  * v8::Locker another_locker(isolate);
10789  * // V8 still locked (2 levels).
10790  * {
10791  * isolate->Exit();
10792  * v8::Unlocker unlocker(isolate);
10793  * // V8 not locked.
10794  * }
10795  * isolate->Enter();
10796  * // V8 locked again (2 levels).
10797  * }
10798  * // V8 still locked (1 level).
10799  * }
10800  * // V8 Now no longer locked.
10801  * \endcode
10802  */
10804  public:
10805  /**
10806  * Initialize Unlocker for a given Isolate.
10807  */
10808  V8_INLINE explicit Unlocker(Isolate* isolate) { Initialize(isolate); }
10809 
10811  private:
10812  void Initialize(Isolate* isolate);
10813 
10814  internal::Isolate* isolate_;
10815 };
10816 
10817 
10819  public:
10820  /**
10821  * Initialize Locker for a given Isolate.
10822  */
10823  V8_INLINE explicit Locker(Isolate* isolate) { Initialize(isolate); }
10824 
10826 
10827  /**
10828  * Returns whether or not the locker for a given isolate, is locked by the
10829  * current thread.
10830  */
10831  static bool IsLocked(Isolate* isolate);
10832 
10833  /**
10834  * Returns whether v8::Locker is being used by this V8 instance.
10835  */
10836  static bool IsActive();
10837 
10838  // Disallow copying and assigning.
10839  Locker(const Locker&) = delete;
10840  void operator=(const Locker&) = delete;
10841 
10842  private:
10843  void Initialize(Isolate* isolate);
10844 
10845  bool has_lock_;
10846  bool top_level_;
10847  internal::Isolate* isolate_;
10848 };
10849 
10850 /**
10851  * Various helpers for skipping over V8 frames in a given stack.
10852  *
10853  * The unwinder API is only supported on the x64, ARM64 and ARM32 architectures.
10854  */
10856  public:
10857  /**
10858  * Attempt to unwind the stack to the most recent C++ frame. This function is
10859  * signal-safe and does not access any V8 state and thus doesn't require an
10860  * Isolate.
10861  *
10862  * The unwinder needs to know the location of the JS Entry Stub (a piece of
10863  * code that is run when C++ code calls into generated JS code). This is used
10864  * for edge cases where the current frame is being constructed or torn down
10865  * when the stack sample occurs.
10866  *
10867  * The unwinder also needs the virtual memory range of all possible V8 code
10868  * objects. There are two ranges required - the heap code range and the range
10869  * for code embedded in the binary.
10870  *
10871  * Available on x64, ARM64 and ARM32.
10872  *
10873  * \param code_pages A list of all of the ranges in which V8 has allocated
10874  * executable code. The caller should obtain this list by calling
10875  * Isolate::CopyCodePages() during the same interrupt/thread suspension that
10876  * captures the stack.
10877  * \param register_state The current registers. This is an in-out param that
10878  * will be overwritten with the register values after unwinding, on success.
10879  * \param stack_base The resulting stack pointer and frame pointer values are
10880  * bounds-checked against the stack_base and the original stack pointer value
10881  * to ensure that they are valid locations in the given stack. If these values
10882  * or any intermediate frame pointer values used during unwinding are ever out
10883  * of these bounds, unwinding will fail.
10884  *
10885  * \return True on success.
10886  */
10887  static bool TryUnwindV8Frames(const JSEntryStubs& entry_stubs,
10888  size_t code_pages_length,
10889  const MemoryRange* code_pages,
10890  RegisterState* register_state,
10891  const void* stack_base);
10892 
10893  /**
10894  * Whether the PC is within the V8 code range represented by code_pages.
10895  *
10896  * If this returns false, then calling UnwindV8Frames() with the same PC
10897  * and unwind_state will always fail. If it returns true, then unwinding may
10898  * (but not necessarily) be successful.
10899  *
10900  * Available on x64, ARM64 and ARM32
10901  */
10902  static bool PCIsInV8(size_t code_pages_length, const MemoryRange* code_pages,
10903  void* pc);
10904 };
10905 
10906 // --- Implementation ---
10907 
10908 template <class T>
10909 Local<T> Local<T>::New(Isolate* isolate, Local<T> that) {
10910  return New(isolate, that.val_);
10911 }
10912 
10913 template <class T>
10914 Local<T> Local<T>::New(Isolate* isolate, const PersistentBase<T>& that) {
10915  return New(isolate, that.val_);
10916 }
10917 
10918 template <class T>
10919 Local<T> Local<T>::New(Isolate* isolate, const BasicTracedReference<T>& that) {
10920  return New(isolate, *that);
10921 }
10922 
10923 template <class T>
10924 Local<T> Local<T>::New(Isolate* isolate, T* that) {
10925  if (that == nullptr) return Local<T>();
10926  T* that_ptr = that;
10927  internal::Address* p = reinterpret_cast<internal::Address*>(that_ptr);
10928  return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
10929  reinterpret_cast<internal::Isolate*>(isolate), *p)));
10930 }
10931 
10932 
10933 template<class T>
10934 template<class S>
10935 void Eternal<T>::Set(Isolate* isolate, Local<S> handle) {
10936  static_assert(std::is_base_of<T, S>::value, "type check");
10937  val_ = reinterpret_cast<T*>(
10938  V8::Eternalize(isolate, reinterpret_cast<Value*>(*handle)));
10939 }
10940 
10941 template <class T>
10942 Local<T> Eternal<T>::Get(Isolate* isolate) const {
10943  // The eternal handle will never go away, so as with the roots, we don't even
10944  // need to open a handle.
10945  return Local<T>(val_);
10946 }
10947 
10948 
10949 template <class T>
10951  if (V8_UNLIKELY(val_ == nullptr)) V8::ToLocalEmpty();
10952  return Local<T>(val_);
10953 }
10954 
10955 
10956 template <class T>
10957 void* WeakCallbackInfo<T>::GetInternalField(int index) const {
10958 #ifdef V8_ENABLE_CHECKS
10959  if (index < 0 || index >= kEmbedderFieldsInWeakCallback) {
10960  V8::InternalFieldOutOfBounds(index);
10961  }
10962 #endif
10963  return embedder_fields_[index];
10964 }
10965 
10966 
10967 template <class T>
10968 T* PersistentBase<T>::New(Isolate* isolate, T* that) {
10969  if (that == nullptr) return nullptr;
10970  internal::Address* p = reinterpret_cast<internal::Address*>(that);
10971  return reinterpret_cast<T*>(
10972  V8::GlobalizeReference(reinterpret_cast<internal::Isolate*>(isolate),
10973  p));
10974 }
10975 
10976 
10977 template <class T, class M>
10978 template <class S, class M2>
10979 void Persistent<T, M>::Copy(const Persistent<S, M2>& that) {
10980  static_assert(std::is_base_of<T, S>::value, "type check");
10981  this->Reset();
10982  if (that.IsEmpty()) return;
10983  internal::Address* p = reinterpret_cast<internal::Address*>(that.val_);
10984  this->val_ = reinterpret_cast<T*>(V8::CopyGlobalReference(p));
10985  M::Copy(that, this);
10986 }
10987 
10988 template <class T>
10989 bool PersistentBase<T>::IsWeak() const {
10990  using I = internal::Internals;
10991  if (this->IsEmpty()) return false;
10992  return I::GetNodeState(reinterpret_cast<internal::Address*>(this->val_)) ==
10994 }
10995 
10996 
10997 template <class T>
10998 void PersistentBase<T>::Reset() {
10999  if (this->IsEmpty()) return;
11000  V8::DisposeGlobal(reinterpret_cast<internal::Address*>(this->val_));
11001  val_ = nullptr;
11002 }
11003 
11004 
11005 template <class T>
11006 template <class S>
11007 void PersistentBase<T>::Reset(Isolate* isolate, const Local<S>& other) {
11008  static_assert(std::is_base_of<T, S>::value, "type check");
11009  Reset();
11010  if (other.IsEmpty()) return;
11011  this->val_ = New(isolate, other.val_);
11012 }
11013 
11014 
11015 template <class T>
11016 template <class S>
11017 void PersistentBase<T>::Reset(Isolate* isolate,
11018  const PersistentBase<S>& other) {
11019  static_assert(std::is_base_of<T, S>::value, "type check");
11020  Reset();
11021  if (other.IsEmpty()) return;
11022  this->val_ = New(isolate, other.val_);
11023 }
11024 
11025 
11026 template <class T>
11027 template <typename P>
11029  P* parameter, typename WeakCallbackInfo<P>::Callback callback,
11030  WeakCallbackType type) {
11031  using Callback = WeakCallbackInfo<void>::Callback;
11032 #if (__GNUC__ >= 8) && !defined(__clang__)
11033 #pragma GCC diagnostic push
11034 #pragma GCC diagnostic ignored "-Wcast-function-type"
11035 #endif
11036  V8::MakeWeak(reinterpret_cast<internal::Address*>(this->val_), parameter,
11037  reinterpret_cast<Callback>(callback), type);
11038 #if (__GNUC__ >= 8) && !defined(__clang__)
11039 #pragma GCC diagnostic pop
11040 #endif
11041 }
11042 
11043 template <class T>
11045  V8::MakeWeak(reinterpret_cast<internal::Address**>(&this->val_));
11046 }
11047 
11048 template <class T>
11049 template <typename P>
11050 P* PersistentBase<T>::ClearWeak() {
11051  return reinterpret_cast<P*>(
11052  V8::ClearWeak(reinterpret_cast<internal::Address*>(this->val_)));
11053 }
11054 
11055 template <class T>
11056 void PersistentBase<T>::AnnotateStrongRetainer(const char* label) {
11057  V8::AnnotateStrongRetainer(reinterpret_cast<internal::Address*>(this->val_),
11058  label);
11059 }
11060 
11061 template <class T>
11062 void PersistentBase<T>::SetWrapperClassId(uint16_t class_id) {
11063  using I = internal::Internals;
11064  if (this->IsEmpty()) return;
11065  internal::Address* obj = reinterpret_cast<internal::Address*>(this->val_);
11066  uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
11067  *reinterpret_cast<uint16_t*>(addr) = class_id;
11068 }
11069 
11070 
11071 template <class T>
11072 uint16_t PersistentBase<T>::WrapperClassId() const {
11073  using I = internal::Internals;
11074  if (this->IsEmpty()) return 0;
11075  internal::Address* obj = reinterpret_cast<internal::Address*>(this->val_);
11076  uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
11077  return *reinterpret_cast<uint16_t*>(addr);
11078 }
11079 
11080 template <class T>
11081 Global<T>::Global(Global&& other) : PersistentBase<T>(other.val_) {
11082  if (other.val_ != nullptr) {
11083  V8::MoveGlobalReference(reinterpret_cast<internal::Address**>(&other.val_),
11084  reinterpret_cast<internal::Address**>(&this->val_));
11085  other.val_ = nullptr;
11086  }
11087 }
11088 
11089 template <class T>
11090 template <class S>
11091 Global<T>& Global<T>::operator=(Global<S>&& rhs) {
11092  static_assert(std::is_base_of<T, S>::value, "type check");
11093  if (this != &rhs) {
11094  this->Reset();
11095  if (rhs.val_ != nullptr) {
11096  this->val_ = rhs.val_;
11097  V8::MoveGlobalReference(
11098  reinterpret_cast<internal::Address**>(&rhs.val_),
11099  reinterpret_cast<internal::Address**>(&this->val_));
11100  rhs.val_ = nullptr;
11101  }
11102  }
11103  return *this;
11104 }
11105 
11106 template <class T>
11108  Isolate* isolate, T* that, void* slot, DestructionMode destruction_mode) {
11109  if (that == nullptr) return nullptr;
11110  internal::Address* p = reinterpret_cast<internal::Address*>(that);
11111  return V8::GlobalizeTracedReference(
11112  reinterpret_cast<internal::Isolate*>(isolate), p,
11113  reinterpret_cast<internal::Address*>(slot),
11114  destruction_mode == kWithDestructor);
11115 }
11116 
11118  if (IsEmpty()) return;
11119  V8::DisposeTracedGlobal(reinterpret_cast<internal::Address*>(val_));
11120  SetSlotThreadSafe(nullptr);
11121 }
11122 
11124  if (IsEmpty()) return Local<Value>();
11125  return Local<Value>::New(isolate, reinterpret_cast<Value*>(val_));
11126 }
11127 
11129  const TracedReferenceBase& rhs) {
11130  v8::internal::Address* a = reinterpret_cast<v8::internal::Address*>(lhs.val_);
11131  v8::internal::Address* b = reinterpret_cast<v8::internal::Address*>(rhs.val_);
11132  if (a == nullptr) return b == nullptr;
11133  if (b == nullptr) return false;
11134  return *a == *b;
11135 }
11136 
11137 template <typename U>
11139  const v8::Local<U>& rhs) {
11140  v8::internal::Address* a = reinterpret_cast<v8::internal::Address*>(lhs.val_);
11141  v8::internal::Address* b = reinterpret_cast<v8::internal::Address*>(*rhs);
11142  if (a == nullptr) return b == nullptr;
11143  if (b == nullptr) return false;
11144  return *a == *b;
11145 }
11146 
11147 template <typename U>
11148 V8_INLINE bool operator==(const v8::Local<U>& lhs,
11149  const TracedReferenceBase& rhs) {
11150  return rhs == lhs;
11151 }
11152 
11154  const TracedReferenceBase& rhs) {
11155  return !(lhs == rhs);
11156 }
11157 
11158 template <typename U>
11160  const v8::Local<U>& rhs) {
11161  return !(lhs == rhs);
11162 }
11163 
11164 template <typename U>
11165 V8_INLINE bool operator!=(const v8::Local<U>& lhs,
11166  const TracedReferenceBase& rhs) {
11167  return !(rhs == lhs);
11168 }
11169 
11170 template <class T>
11171 template <class S>
11172 void TracedGlobal<T>::Reset(Isolate* isolate, const Local<S>& other) {
11173  static_assert(std::is_base_of<T, S>::value, "type check");
11174  Reset();
11175  if (other.IsEmpty()) return;
11176  this->val_ = this->New(isolate, other.val_, &this->val_,
11177  BasicTracedReference<T>::kWithDestructor);
11178 }
11179 
11180 template <class T>
11181 template <class S>
11183  static_assert(std::is_base_of<T, S>::value, "type check");
11184  *this = std::move(rhs.template As<T>());
11185  return *this;
11186 }
11187 
11188 template <class T>
11189 template <class S>
11191  static_assert(std::is_base_of<T, S>::value, "type check");
11192  *this = rhs.template As<T>();
11193  return *this;
11194 }
11195 
11196 template <class T>
11198  if (this != &rhs) {
11199  V8::MoveTracedGlobalReference(
11200  reinterpret_cast<internal::Address**>(&rhs.val_),
11201  reinterpret_cast<internal::Address**>(&this->val_));
11202  }
11203  return *this;
11204 }
11205 
11206 template <class T>
11208  if (this != &rhs) {
11209  this->Reset();
11210  if (rhs.val_ != nullptr) {
11211  V8::CopyTracedGlobalReference(
11212  reinterpret_cast<const internal::Address* const*>(&rhs.val_),
11213  reinterpret_cast<internal::Address**>(&this->val_));
11214  }
11215  }
11216  return *this;
11217 }
11218 
11219 template <class T>
11220 template <class S>
11221 void TracedReference<T>::Reset(Isolate* isolate, const Local<S>& other) {
11222  static_assert(std::is_base_of<T, S>::value, "type check");
11223  this->Reset();
11224  if (other.IsEmpty()) return;
11225  this->SetSlotThreadSafe(
11226  this->New(isolate, other.val_, &this->val_,
11227  BasicTracedReference<T>::kWithoutDestructor));
11228 }
11229 
11230 template <class T>
11231 template <class S>
11233  static_assert(std::is_base_of<T, S>::value, "type check");
11234  *this = std::move(rhs.template As<T>());
11235  return *this;
11236 }
11237 
11238 template <class T>
11239 template <class S>
11241  const TracedReference<S>& rhs) {
11242  static_assert(std::is_base_of<T, S>::value, "type check");
11243  *this = rhs.template As<T>();
11244  return *this;
11245 }
11246 
11247 template <class T>
11249  if (this != &rhs) {
11250  V8::MoveTracedGlobalReference(
11251  reinterpret_cast<internal::Address**>(&rhs.val_),
11252  reinterpret_cast<internal::Address**>(&this->val_));
11253  }
11254  return *this;
11255 }
11256 
11257 template <class T>
11259  if (this != &rhs) {
11260  this->Reset();
11261  if (rhs.val_ != nullptr) {
11262  V8::CopyTracedGlobalReference(
11263  reinterpret_cast<const internal::Address* const*>(&rhs.val_),
11264  reinterpret_cast<internal::Address**>(&this->val_));
11265  }
11266  }
11267  return *this;
11268 }
11269 
11270 void TracedReferenceBase::SetWrapperClassId(uint16_t class_id) {
11271  using I = internal::Internals;
11272  if (IsEmpty()) return;
11273  internal::Address* obj = reinterpret_cast<internal::Address*>(val_);
11274  uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
11275  *reinterpret_cast<uint16_t*>(addr) = class_id;
11276 }
11277 
11279  using I = internal::Internals;
11280  if (IsEmpty()) return 0;
11281  internal::Address* obj = reinterpret_cast<internal::Address*>(val_);
11282  uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
11283  return *reinterpret_cast<uint16_t*>(addr);
11284 }
11285 
11286 template <class T>
11288  void* parameter, typename WeakCallbackInfo<void>::Callback callback) {
11289  V8::SetFinalizationCallbackTraced(
11290  reinterpret_cast<internal::Address*>(this->val_), parameter, callback);
11291 }
11292 
11293 template <typename T>
11294 ReturnValue<T>::ReturnValue(internal::Address* slot) : value_(slot) {}
11295 
11296 template <typename T>
11297 template <typename S>
11298 void ReturnValue<T>::Set(const Global<S>& handle) {
11299  static_assert(std::is_base_of<T, S>::value, "type check");
11300  if (V8_UNLIKELY(handle.IsEmpty())) {
11301  *value_ = GetDefaultValue();
11302  } else {
11303  *value_ = *reinterpret_cast<internal::Address*>(*handle);
11304  }
11305 }
11306 
11307 template <typename T>
11308 template <typename S>
11309 void ReturnValue<T>::Set(const BasicTracedReference<S>& handle) {
11310  static_assert(std::is_base_of<T, S>::value, "type check");
11311  if (V8_UNLIKELY(handle.IsEmpty())) {
11312  *value_ = GetDefaultValue();
11313  } else {
11314  *value_ = *reinterpret_cast<internal::Address*>(handle.val_);
11315  }
11316 }
11317 
11318 template <typename T>
11319 template <typename S>
11320 void ReturnValue<T>::Set(const Local<S> handle) {
11321  static_assert(std::is_void<T>::value || std::is_base_of<T, S>::value,
11322  "type check");
11323  if (V8_UNLIKELY(handle.IsEmpty())) {
11324  *value_ = GetDefaultValue();
11325  } else {
11326  *value_ = *reinterpret_cast<internal::Address*>(*handle);
11327  }
11328 }
11329 
11330 template<typename T>
11331 void ReturnValue<T>::Set(double i) {
11332  static_assert(std::is_base_of<T, Number>::value, "type check");
11334 }
11335 
11336 template<typename T>
11337 void ReturnValue<T>::Set(int32_t i) {
11338  static_assert(std::is_base_of<T, Integer>::value, "type check");
11339  using I = internal::Internals;
11340  if (V8_LIKELY(I::IsValidSmi(i))) {
11341  *value_ = I::IntToSmi(i);
11342  return;
11343  }
11345 }
11346 
11347 template<typename T>
11348 void ReturnValue<T>::Set(uint32_t i) {
11349  static_assert(std::is_base_of<T, Integer>::value, "type check");
11350  // Can't simply use INT32_MAX here for whatever reason.
11351  bool fits_into_int32_t = (i & (1U << 31)) == 0;
11352  if (V8_LIKELY(fits_into_int32_t)) {
11353  Set(static_cast<int32_t>(i));
11354  return;
11355  }
11357 }
11358 
11359 template<typename T>
11360 void ReturnValue<T>::Set(bool value) {
11361  static_assert(std::is_base_of<T, Boolean>::value, "type check");
11362  using I = internal::Internals;
11363  int root_index;
11364  if (value) {
11365  root_index = I::kTrueValueRootIndex;
11366  } else {
11367  root_index = I::kFalseValueRootIndex;
11368  }
11369  *value_ = *I::GetRoot(GetIsolate(), root_index);
11370 }
11371 
11372 template<typename T>
11373 void ReturnValue<T>::SetNull() {
11374  static_assert(std::is_base_of<T, Primitive>::value, "type check");
11375  using I = internal::Internals;
11377 }
11378 
11379 template<typename T>
11381  static_assert(std::is_base_of<T, Primitive>::value, "type check");
11382  using I = internal::Internals;
11384 }
11385 
11386 template<typename T>
11388  static_assert(std::is_base_of<T, String>::value, "type check");
11389  using I = internal::Internals;
11391 }
11392 
11393 template <typename T>
11395  // Isolate is always the pointer below the default value on the stack.
11396  return *reinterpret_cast<Isolate**>(&value_[-2]);
11397 }
11398 
11399 template <typename T>
11400 Local<Value> ReturnValue<T>::Get() const {
11401  using I = internal::Internals;
11403  return Local<Value>(*Undefined(GetIsolate()));
11404  return Local<Value>::New(GetIsolate(), reinterpret_cast<Value*>(value_));
11405 }
11406 
11407 template <typename T>
11408 template <typename S>
11409 void ReturnValue<T>::Set(S* whatever) {
11410  static_assert(sizeof(S) < 0, "incompilable to prevent inadvertent misuse");
11411 }
11412 
11413 template <typename T>
11414 internal::Address ReturnValue<T>::GetDefaultValue() {
11415  // Default value is always the pointer below value_ on the stack.
11416  return value_[-1];
11417 }
11418 
11419 template <typename T>
11421  internal::Address* values,
11422  int length)
11423  : implicit_args_(implicit_args), values_(values), length_(length) {}
11424 
11425 template<typename T>
11427  // values_ points to the first argument (not the receiver).
11428  if (i < 0 || length_ <= i) return Local<Value>(*Undefined(GetIsolate()));
11429  return Local<Value>(reinterpret_cast<Value*>(values_ + i));
11430 }
11431 
11432 
11433 template<typename T>
11435  // values_ points to the first argument (not the receiver).
11436  return Local<Object>(reinterpret_cast<Object*>(values_ - 1));
11437 }
11438 
11439 
11440 template<typename T>
11442  return Local<Object>(reinterpret_cast<Object*>(
11444 }
11445 
11446 template <typename T>
11448  return Local<Value>(
11449  reinterpret_cast<Value*>(&implicit_args_[kNewTargetIndex]));
11450 }
11451 
11452 template <typename T>
11454  return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
11455 }
11456 
11457 
11458 template<typename T>
11460  return *reinterpret_cast<Isolate**>(&implicit_args_[kIsolateIndex]);
11461 }
11462 
11463 
11464 template<typename T>
11467 }
11468 
11469 
11470 template<typename T>
11472  return !NewTarget()->IsUndefined();
11473 }
11474 
11475 
11476 template<typename T>
11477 int FunctionCallbackInfo<T>::Length() const {
11478  return length_;
11479 }
11480 
11482  Local<Value> resource_name, Local<Integer> line_offset,
11483  Local<Integer> column_offset, Local<Boolean> is_shared_cross_origin,
11484  Local<Integer> script_id, Local<Value> source_map_url,
11485  Local<Boolean> is_opaque, Local<Boolean> is_wasm, Local<Boolean> is_module,
11486  Local<PrimitiveArray> host_defined_options)
11487  : ScriptOrigin(
11488  Isolate::GetCurrent(), resource_name,
11489  line_offset.IsEmpty() ? 0 : static_cast<int>(line_offset->Value()),
11490  column_offset.IsEmpty() ? 0
11491  : static_cast<int>(column_offset->Value()),
11492  !is_shared_cross_origin.IsEmpty() && is_shared_cross_origin->IsTrue(),
11493  static_cast<int>(script_id.IsEmpty() ? -1 : script_id->Value()),
11494  source_map_url, !is_opaque.IsEmpty() && is_opaque->IsTrue(),
11495  !is_wasm.IsEmpty() && is_wasm->IsTrue(),
11496  !is_module.IsEmpty() && is_module->IsTrue(), host_defined_options) {}
11497 
11498 ScriptOrigin::ScriptOrigin(Local<Value> resource_name, int line_offset,
11499  int column_offset, bool is_shared_cross_origin,
11500  int script_id, Local<Value> source_map_url,
11501  bool is_opaque, bool is_wasm, bool is_module,
11502  Local<PrimitiveArray> host_defined_options)
11503  : isolate_(Isolate::GetCurrent()),
11504  resource_name_(resource_name),
11505  resource_line_offset_(line_offset),
11506  resource_column_offset_(column_offset),
11507  options_(is_shared_cross_origin, is_opaque, is_wasm, is_module),
11508  script_id_(script_id),
11509  source_map_url_(source_map_url),
11510  host_defined_options_(host_defined_options) {}
11511 
11512 ScriptOrigin::ScriptOrigin(Isolate* isolate, Local<Value> resource_name,
11513  int line_offset, int column_offset,
11514  bool is_shared_cross_origin, int script_id,
11515  Local<Value> source_map_url, bool is_opaque,
11516  bool is_wasm, bool is_module,
11517  Local<PrimitiveArray> host_defined_options)
11518  : isolate_(isolate),
11519  resource_name_(resource_name),
11520  resource_line_offset_(line_offset),
11521  resource_column_offset_(column_offset),
11522  options_(is_shared_cross_origin, is_opaque, is_wasm, is_module),
11523  script_id_(script_id),
11524  source_map_url_(source_map_url),
11525  host_defined_options_(host_defined_options) {}
11526 
11527 Local<Value> ScriptOrigin::ResourceName() const { return resource_name_; }
11528 
11530  return host_defined_options_;
11531 }
11532 
11534  return v8::Integer::New(isolate_, resource_line_offset_);
11535 }
11536 
11538  return v8::Integer::New(isolate_, resource_column_offset_);
11539 }
11540 
11542  return v8::Integer::New(isolate_, script_id_);
11543 }
11544 
11545 int ScriptOrigin::LineOffset() const { return resource_line_offset_; }
11546 
11547 int ScriptOrigin::ColumnOffset() const { return resource_column_offset_; }
11548 
11549 int ScriptOrigin::ScriptId() const { return script_id_; }
11550 
11551 Local<Value> ScriptOrigin::SourceMapUrl() const { return source_map_url_; }
11552 
11554  CachedData* data,
11555  ConsumeCodeCacheTask* consume_cache_task)
11556  : source_string(string),
11557  resource_name(origin.ResourceName()),
11558  resource_line_offset(origin.LineOffset()),
11559  resource_column_offset(origin.ColumnOffset()),
11560  resource_options(origin.Options()),
11561  source_map_url(origin.SourceMapUrl()),
11562  host_defined_options(origin.HostDefinedOptions()),
11563  cached_data(data),
11564  consume_cache_task(consume_cache_task) {}
11565 
11567  ConsumeCodeCacheTask* consume_cache_task)
11568  : source_string(string),
11569  cached_data(data),
11570  consume_cache_task(consume_cache_task) {}
11571 
11573  const {
11574  return cached_data.get();
11575 }
11576 
11578  return resource_options;
11579 }
11580 
11581 Local<Boolean> Boolean::New(Isolate* isolate, bool value) {
11582  return value ? True(isolate) : False(isolate);
11583 }
11584 
11585 void Template::Set(Isolate* isolate, const char* name, Local<Data> value,
11586  PropertyAttribute attributes) {
11589  value, attributes);
11590 }
11591 
11593 #ifdef V8_ENABLE_CHECKS
11594  CheckCast(data);
11595 #endif
11596  return reinterpret_cast<FunctionTemplate*>(data);
11597 }
11598 
11600 #ifdef V8_ENABLE_CHECKS
11601  CheckCast(data);
11602 #endif
11603  return reinterpret_cast<ObjectTemplate*>(data);
11604 }
11605 
11607 #ifdef V8_ENABLE_CHECKS
11608  CheckCast(data);
11609 #endif
11610  return reinterpret_cast<Signature*>(data);
11611 }
11612 
11614 #ifdef V8_ENABLE_CHECKS
11615  CheckCast(data);
11616 #endif
11617  return reinterpret_cast<AccessorSignature*>(data);
11618 }
11619 
11621 #ifndef V8_ENABLE_CHECKS
11622  using A = internal::Address;
11623  using I = internal::Internals;
11624  A obj = *reinterpret_cast<A*>(this);
11625  // Fast path: If the object is a plain JSObject, which is the common case, we
11626  // know where to find the internal fields and can return the value directly.
11627  int instance_type = I::GetInstanceType(obj);
11628  if (v8::internal::CanHaveInternalField(instance_type)) {
11629  int offset = I::kJSObjectHeaderSize + (I::kEmbedderDataSlotSize * index);
11630  A value = I::ReadRawField<A>(obj, offset);
11631 #ifdef V8_COMPRESS_POINTERS
11632  // We read the full pointer value and then decompress it in order to avoid
11633  // dealing with potential endiannes issues.
11634  value = I::DecompressTaggedAnyField(obj, static_cast<uint32_t>(value));
11635 #endif
11636  internal::Isolate* isolate =
11638  A* result = HandleScope::CreateHandle(isolate, value);
11639  return Local<Value>(reinterpret_cast<Value*>(result));
11640  }
11641 #endif
11642  return SlowGetInternalField(index);
11643 }
11644 
11645 
11647 #ifndef V8_ENABLE_CHECKS
11648  using A = internal::Address;
11649  using I = internal::Internals;
11650  A obj = *reinterpret_cast<A*>(this);
11651  // Fast path: If the object is a plain JSObject, which is the common case, we
11652  // know where to find the internal fields and can return the value directly.
11653  auto instance_type = I::GetInstanceType(obj);
11654  if (v8::internal::CanHaveInternalField(instance_type)) {
11655  int offset = I::kJSObjectHeaderSize + (I::kEmbedderDataSlotSize * index);
11656 #ifdef V8_HEAP_SANDBOX
11657  offset += I::kEmbedderDataSlotRawPayloadOffset;
11658 #endif
11659  internal::Isolate* isolate = I::GetIsolateForHeapSandbox(obj);
11660  A value = I::ReadExternalPointerField(
11661  isolate, obj, offset, internal::kEmbedderDataSlotPayloadTag);
11662  return reinterpret_cast<void*>(value);
11663  }
11664 #endif
11665  return SlowGetAlignedPointerFromInternalField(index);
11666 }
11667 
11668 String* String::Cast(v8::Data* data) {
11669 #ifdef V8_ENABLE_CHECKS
11670  CheckCast(data);
11671 #endif
11672  return static_cast<String*>(data);
11673 }
11674 
11676  using S = internal::Address;
11677  using I = internal::Internals;
11678  I::CheckInitialized(isolate);
11679  S* slot = I::GetRoot(isolate, I::kEmptyStringRootIndex);
11680  return Local<String>(reinterpret_cast<String*>(slot));
11681 }
11682 
11683 
11685  using A = internal::Address;
11686  using I = internal::Internals;
11687  A obj = *reinterpret_cast<const A*>(this);
11688 
11689  ExternalStringResource* result;
11691  internal::Isolate* isolate = I::GetIsolateForHeapSandbox(obj);
11692  A value =
11695  result = reinterpret_cast<String::ExternalStringResource*>(value);
11696  } else {
11697  result = GetExternalStringResourceSlow();
11698  }
11699 #ifdef V8_ENABLE_CHECKS
11700  VerifyExternalStringResource(result);
11701 #endif
11702  return result;
11703 }
11704 
11705 
11707  String::Encoding* encoding_out) const {
11708  using A = internal::Address;
11709  using I = internal::Internals;
11710  A obj = *reinterpret_cast<const A*>(this);
11712  *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
11713  ExternalStringResourceBase* resource;
11714  if (type == I::kExternalOneByteRepresentationTag ||
11716  internal::Isolate* isolate = I::GetIsolateForHeapSandbox(obj);
11717  A value =
11720  resource = reinterpret_cast<ExternalStringResourceBase*>(value);
11721  } else {
11722  resource = GetExternalStringResourceBaseSlow(encoding_out);
11723  }
11724 #ifdef V8_ENABLE_CHECKS
11725  VerifyExternalStringResourceBase(resource, *encoding_out);
11726 #endif
11727  return resource;
11728 }
11729 
11730 
11731 bool Value::IsUndefined() const {
11732 #ifdef V8_ENABLE_CHECKS
11733  return FullIsUndefined();
11734 #else
11735  return QuickIsUndefined();
11736 #endif
11737 }
11738 
11739 bool Value::QuickIsUndefined() const {
11740  using A = internal::Address;
11741  using I = internal::Internals;
11742  A obj = *reinterpret_cast<const A*>(this);
11743  if (!I::HasHeapObjectTag(obj)) return false;
11744  if (I::GetInstanceType(obj) != I::kOddballType) return false;
11746 }
11747 
11748 
11749 bool Value::IsNull() const {
11750 #ifdef V8_ENABLE_CHECKS
11751  return FullIsNull();
11752 #else
11753  return QuickIsNull();
11754 #endif
11755 }
11756 
11757 bool Value::QuickIsNull() const {
11758  using A = internal::Address;
11759  using I = internal::Internals;
11760  A obj = *reinterpret_cast<const A*>(this);
11761  if (!I::HasHeapObjectTag(obj)) return false;
11762  if (I::GetInstanceType(obj) != I::kOddballType) return false;
11763  return (I::GetOddballKind(obj) == I::kNullOddballKind);
11764 }
11765 
11766 bool Value::IsNullOrUndefined() const {
11767 #ifdef V8_ENABLE_CHECKS
11768  return FullIsNull() || FullIsUndefined();
11769 #else
11770  return QuickIsNullOrUndefined();
11771 #endif
11772 }
11773 
11774 bool Value::QuickIsNullOrUndefined() const {
11775  using A = internal::Address;
11776  using I = internal::Internals;
11777  A obj = *reinterpret_cast<const A*>(this);
11778  if (!I::HasHeapObjectTag(obj)) return false;
11779  if (I::GetInstanceType(obj) != I::kOddballType) return false;
11780  int kind = I::GetOddballKind(obj);
11781  return kind == I::kNullOddballKind || kind == I::kUndefinedOddballKind;
11782 }
11783 
11784 bool Value::IsString() const {
11785 #ifdef V8_ENABLE_CHECKS
11786  return FullIsString();
11787 #else
11788  return QuickIsString();
11789 #endif
11790 }
11791 
11792 bool Value::QuickIsString() const {
11793  using A = internal::Address;
11794  using I = internal::Internals;
11795  A obj = *reinterpret_cast<const A*>(this);
11796  if (!I::HasHeapObjectTag(obj)) return false;
11798 }
11799 
11800 
11801 template <class T> Value* Value::Cast(T* value) {
11802  return static_cast<Value*>(value);
11803 }
11804 
11805 template <>
11807 #ifdef V8_ENABLE_CHECKS
11808  CheckCast(value);
11809 #endif
11810  return static_cast<Value*>(value);
11811 }
11812 
11814 #ifdef V8_ENABLE_CHECKS
11815  CheckCast(data);
11816 #endif
11817  return static_cast<Boolean*>(data);
11818 }
11819 
11820 Name* Name::Cast(v8::Data* data) {
11821 #ifdef V8_ENABLE_CHECKS
11822  CheckCast(data);
11823 #endif
11824  return static_cast<Name*>(data);
11825 }
11826 
11827 Symbol* Symbol::Cast(v8::Data* data) {
11828 #ifdef V8_ENABLE_CHECKS
11829  CheckCast(data);
11830 #endif
11831  return static_cast<Symbol*>(data);
11832 }
11833 
11835 #ifdef V8_ENABLE_CHECKS
11836  CheckCast(data);
11837 #endif
11838  return reinterpret_cast<Private*>(data);
11839 }
11840 
11842 #ifdef V8_ENABLE_CHECKS
11843  CheckCast(data);
11844 #endif
11845  return reinterpret_cast<ModuleRequest*>(data);
11846 }
11847 
11849 #ifdef V8_ENABLE_CHECKS
11850  CheckCast(data);
11851 #endif
11852  return reinterpret_cast<Module*>(data);
11853 }
11854 
11855 Number* Number::Cast(v8::Data* data) {
11856 #ifdef V8_ENABLE_CHECKS
11857  CheckCast(data);
11858 #endif
11859  return static_cast<Number*>(data);
11860 }
11861 
11863 #ifdef V8_ENABLE_CHECKS
11864  CheckCast(data);
11865 #endif
11866  return static_cast<Integer*>(data);
11867 }
11868 
11869 Int32* Int32::Cast(v8::Data* data) {
11870 #ifdef V8_ENABLE_CHECKS
11871  CheckCast(data);
11872 #endif
11873  return static_cast<Int32*>(data);
11874 }
11875 
11876 Uint32* Uint32::Cast(v8::Data* data) {
11877 #ifdef V8_ENABLE_CHECKS
11878  CheckCast(data);
11879 #endif
11880  return static_cast<Uint32*>(data);
11881 }
11882 
11883 BigInt* BigInt::Cast(v8::Data* data) {
11884 #ifdef V8_ENABLE_CHECKS
11885  CheckCast(data);
11886 #endif
11887  return static_cast<BigInt*>(data);
11888 }
11889 
11891 #ifdef V8_ENABLE_CHECKS
11892  CheckCast(data);
11893 #endif
11894  return static_cast<Context*>(data);
11895 }
11896 
11897 Date* Date::Cast(v8::Value* value) {
11898 #ifdef V8_ENABLE_CHECKS
11899  CheckCast(value);
11900 #endif
11901  return static_cast<Date*>(value);
11902 }
11903 
11904 
11906 #ifdef V8_ENABLE_CHECKS
11907  CheckCast(value);
11908 #endif
11909  return static_cast<StringObject*>(value);
11910 }
11911 
11912 
11914 #ifdef V8_ENABLE_CHECKS
11915  CheckCast(value);
11916 #endif
11917  return static_cast<SymbolObject*>(value);
11918 }
11919 
11920 
11922 #ifdef V8_ENABLE_CHECKS
11923  CheckCast(value);
11924 #endif
11925  return static_cast<NumberObject*>(value);
11926 }
11927 
11929 #ifdef V8_ENABLE_CHECKS
11930  CheckCast(value);
11931 #endif
11932  return static_cast<BigIntObject*>(value);
11933 }
11934 
11936 #ifdef V8_ENABLE_CHECKS
11937  CheckCast(value);
11938 #endif
11939  return static_cast<BooleanObject*>(value);
11940 }
11941 
11942 
11943 RegExp* RegExp::Cast(v8::Value* value) {
11944 #ifdef V8_ENABLE_CHECKS
11945  CheckCast(value);
11946 #endif
11947  return static_cast<RegExp*>(value);
11948 }
11949 
11950 
11951 Object* Object::Cast(v8::Value* value) {
11952 #ifdef V8_ENABLE_CHECKS
11953  CheckCast(value);
11954 #endif
11955  return static_cast<Object*>(value);
11956 }
11957 
11958 
11959 Array* Array::Cast(v8::Value* value) {
11960 #ifdef V8_ENABLE_CHECKS
11961  CheckCast(value);
11962 #endif
11963  return static_cast<Array*>(value);
11964 }
11965 
11966 
11967 Map* Map::Cast(v8::Value* value) {
11968 #ifdef V8_ENABLE_CHECKS
11969  CheckCast(value);
11970 #endif
11971  return static_cast<Map*>(value);
11972 }
11973 
11974 
11975 Set* Set::Cast(v8::Value* value) {
11976 #ifdef V8_ENABLE_CHECKS
11977  CheckCast(value);
11978 #endif
11979  return static_cast<Set*>(value);
11980 }
11981 
11982 
11984 #ifdef V8_ENABLE_CHECKS
11985  CheckCast(value);
11986 #endif
11987  return static_cast<Promise*>(value);
11988 }
11989 
11990 
11991 Proxy* Proxy::Cast(v8::Value* value) {
11992 #ifdef V8_ENABLE_CHECKS
11993  CheckCast(value);
11994 #endif
11995  return static_cast<Proxy*>(value);
11996 }
11997 
11999 #ifdef V8_ENABLE_CHECKS
12000  CheckCast(value);
12001 #endif
12002  return static_cast<WasmMemoryObject*>(value);
12003 }
12004 
12006 #ifdef V8_ENABLE_CHECKS
12007  CheckCast(value);
12008 #endif
12009  return static_cast<WasmModuleObject*>(value);
12010 }
12011 
12013 #ifdef V8_ENABLE_CHECKS
12014  CheckCast(value);
12015 #endif
12016  return static_cast<Promise::Resolver*>(value);
12017 }
12018 
12019 
12021 #ifdef V8_ENABLE_CHECKS
12022  CheckCast(value);
12023 #endif
12024  return static_cast<ArrayBuffer*>(value);
12025 }
12026 
12027 
12029 #ifdef V8_ENABLE_CHECKS
12030  CheckCast(value);
12031 #endif
12032  return static_cast<ArrayBufferView*>(value);
12033 }
12034 
12035 
12037 #ifdef V8_ENABLE_CHECKS
12038  CheckCast(value);
12039 #endif
12040  return static_cast<TypedArray*>(value);
12041 }
12042 
12043 
12045 #ifdef V8_ENABLE_CHECKS
12046  CheckCast(value);
12047 #endif
12048  return static_cast<Uint8Array*>(value);
12049 }
12050 
12051 
12053 #ifdef V8_ENABLE_CHECKS
12054  CheckCast(value);
12055 #endif
12056  return static_cast<Int8Array*>(value);
12057 }
12058 
12059 
12061 #ifdef V8_ENABLE_CHECKS
12062  CheckCast(value);
12063 #endif
12064  return static_cast<Uint16Array*>(value);
12065 }
12066 
12067 
12069 #ifdef V8_ENABLE_CHECKS
12070  CheckCast(value);
12071 #endif
12072  return static_cast<Int16Array*>(value);
12073 }
12074 
12075 
12077 #ifdef V8_ENABLE_CHECKS
12078  CheckCast(value);
12079 #endif
12080  return static_cast<Uint32Array*>(value);
12081 }
12082 
12083 
12085 #ifdef V8_ENABLE_CHECKS
12086  CheckCast(value);
12087 #endif
12088  return static_cast<Int32Array*>(value);
12089 }
12090 
12091 
12093 #ifdef V8_ENABLE_CHECKS
12094  CheckCast(value);
12095 #endif
12096  return static_cast<Float32Array*>(value);
12097 }
12098 
12099 
12101 #ifdef V8_ENABLE_CHECKS
12102  CheckCast(value);
12103 #endif
12104  return static_cast<Float64Array*>(value);
12105 }
12106 
12108 #ifdef V8_ENABLE_CHECKS
12109  CheckCast(value);
12110 #endif
12111  return static_cast<BigInt64Array*>(value);
12112 }
12113 
12115 #ifdef V8_ENABLE_CHECKS
12116  CheckCast(value);
12117 #endif
12118  return static_cast<BigUint64Array*>(value);
12119 }
12120 
12122 #ifdef V8_ENABLE_CHECKS
12123  CheckCast(value);
12124 #endif
12125  return static_cast<Uint8ClampedArray*>(value);
12126 }
12127 
12128 
12130 #ifdef V8_ENABLE_CHECKS
12131  CheckCast(value);
12132 #endif
12133  return static_cast<DataView*>(value);
12134 }
12135 
12136 
12138 #ifdef V8_ENABLE_CHECKS
12139  CheckCast(value);
12140 #endif
12141  return static_cast<SharedArrayBuffer*>(value);
12142 }
12143 
12144 
12146 #ifdef V8_ENABLE_CHECKS
12147  CheckCast(value);
12148 #endif
12149  return static_cast<Function*>(value);
12150 }
12151 
12152 
12154 #ifdef V8_ENABLE_CHECKS
12155  CheckCast(value);
12156 #endif
12157  return static_cast<External*>(value);
12158 }
12159 
12160 
12161 template<typename T>
12163  return *reinterpret_cast<Isolate**>(&args_[kIsolateIndex]);
12164 }
12165 
12166 
12167 template<typename T>
12169  return Local<Value>(reinterpret_cast<Value*>(&args_[kDataIndex]));
12170 }
12171 
12172 
12173 template<typename T>
12175  return Local<Object>(reinterpret_cast<Object*>(&args_[kThisIndex]));
12176 }
12177 
12178 
12179 template<typename T>
12181  return Local<Object>(reinterpret_cast<Object*>(&args_[kHolderIndex]));
12182 }
12183 
12184 
12185 template<typename T>
12187  return ReturnValue<T>(&args_[kReturnValueIndex]);
12188 }
12189 
12190 template <typename T>
12192  using I = internal::Internals;
12196  }
12198  reinterpret_cast<v8::internal::Isolate*>(GetIsolate()));
12199 }
12200 
12202  using S = internal::Address;
12203  using I = internal::Internals;
12204  I::CheckInitialized(isolate);
12205  S* slot = I::GetRoot(isolate, I::kUndefinedValueRootIndex);
12206  return Local<Primitive>(reinterpret_cast<Primitive*>(slot));
12207 }
12208 
12209 
12211  using S = internal::Address;
12212  using I = internal::Internals;
12213  I::CheckInitialized(isolate);
12214  S* slot = I::GetRoot(isolate, I::kNullValueRootIndex);
12215  return Local<Primitive>(reinterpret_cast<Primitive*>(slot));
12216 }
12217 
12218 
12220  using S = internal::Address;
12221  using I = internal::Internals;
12222  I::CheckInitialized(isolate);
12223  S* slot = I::GetRoot(isolate, I::kTrueValueRootIndex);
12224  return Local<Boolean>(reinterpret_cast<Boolean*>(slot));
12225 }
12226 
12227 
12229  using S = internal::Address;
12230  using I = internal::Internals;
12231  I::CheckInitialized(isolate);
12232  S* slot = I::GetRoot(isolate, I::kFalseValueRootIndex);
12233  return Local<Boolean>(reinterpret_cast<Boolean*>(slot));
12234 }
12235 
12236 
12237 void Isolate::SetData(uint32_t slot, void* data) {
12238  using I = internal::Internals;
12239  I::SetEmbedderData(this, slot, data);
12240 }
12241 
12242 
12243 void* Isolate::GetData(uint32_t slot) {
12244  using I = internal::Internals;
12245  return I::GetEmbedderData(this, slot);
12246 }
12247 
12248 
12250  using I = internal::Internals;
12251  return I::kNumIsolateDataSlots;
12252 }
12253 
12254 template <class T>
12256  T* data = reinterpret_cast<T*>(GetDataFromSnapshotOnce(index));
12257  if (data) internal::PerformCastCheck(data);
12258  return Local<T>(data);
12259 }
12260 
12262 #ifndef V8_ENABLE_CHECKS
12263  using A = internal::Address;
12264  using I = internal::Internals;
12265  A ctx = *reinterpret_cast<const A*>(this);
12266  A embedder_data =
12268  int value_offset =
12270  A value = I::ReadRawField<A>(embedder_data, value_offset);
12271 #ifdef V8_COMPRESS_POINTERS
12272  // We read the full pointer value and then decompress it in order to avoid
12273  // dealing with potential endiannes issues.
12274  value =
12275  I::DecompressTaggedAnyField(embedder_data, static_cast<uint32_t>(value));
12276 #endif
12278  *reinterpret_cast<A*>(this));
12279  A* result = HandleScope::CreateHandle(isolate, value);
12280  return Local<Value>(reinterpret_cast<Value*>(result));
12281 #else
12282  return SlowGetEmbedderData(index);
12283 #endif
12284 }
12285 
12286 
12288 #ifndef V8_ENABLE_CHECKS
12289  using A = internal::Address;
12290  using I = internal::Internals;
12291  A ctx = *reinterpret_cast<const A*>(this);
12292  A embedder_data =
12294  int value_offset =
12296 #ifdef V8_HEAP_SANDBOX
12297  value_offset += I::kEmbedderDataSlotRawPayloadOffset;
12298 #endif
12299  internal::Isolate* isolate = I::GetIsolateForHeapSandbox(ctx);
12300  return reinterpret_cast<void*>(
12301  I::ReadExternalPointerField(isolate, embedder_data, value_offset,
12303 #else
12304  return SlowGetAlignedPointerFromEmbedderData(index);
12305 #endif
12306 }
12307 
12308 template <class T>
12310  T* data = reinterpret_cast<T*>(GetDataFromSnapshotOnce(index));
12311  if (data) internal::PerformCastCheck(data);
12312  return Local<T>(data);
12313 }
12314 
12315 template <class T>
12316 size_t SnapshotCreator::AddData(Local<Context> context, Local<T> object) {
12317  T* object_ptr = *object;
12318  internal::Address* p = reinterpret_cast<internal::Address*>(object_ptr);
12319  return AddData(context, *p);
12320 }
12321 
12322 template <class T>
12323 size_t SnapshotCreator::AddData(Local<T> object) {
12324  T* object_ptr = *object;
12325  internal::Address* p = reinterpret_cast<internal::Address*>(object_ptr);
12326  return AddData(*p);
12327 }
12328 
12329 /**
12330  * \example shell.cc
12331  * A simple shell that takes a list of expressions on the
12332  * command-line and executes them.
12333  */
12334 
12335 
12336 /**
12337  * \example process.cc
12338  */
12339 
12340 
12341 } // namespace v8
12342 
12343 #endif // INCLUDE_V8_H_