v8  7.0.276 (node 11.14.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 http://code.google.com/apis/v8/
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 #include <memory>
22 #include <utility>
23 #include <vector>
24 
25 #include "v8-version.h" // NOLINT(build/include)
26 #include "v8config.h" // NOLINT(build/include)
27 
28 // We reserve the V8_* prefix for macros defined in V8 public API and
29 // assume there are no name conflicts with the embedder's code.
30 
31 #ifdef V8_OS_WIN
32 
33 // Setup for Windows DLL export/import. When building the V8 DLL the
34 // BUILDING_V8_SHARED needs to be defined. When building a program which uses
35 // the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8
36 // static library or building a program which uses the V8 static library neither
37 // BUILDING_V8_SHARED nor USING_V8_SHARED should be defined.
38 #ifdef BUILDING_V8_SHARED
39 # define V8_EXPORT __declspec(dllexport)
40 #elif USING_V8_SHARED
41 # define V8_EXPORT __declspec(dllimport)
42 #else
43 # define V8_EXPORT
44 #endif // BUILDING_V8_SHARED
45 
46 #else // V8_OS_WIN
47 
48 // Setup for Linux shared library export.
49 #if V8_HAS_ATTRIBUTE_VISIBILITY
50 # ifdef BUILDING_V8_SHARED
51 # define V8_EXPORT __attribute__ ((visibility("default")))
52 # else
53 # define V8_EXPORT
54 # endif
55 #else
56 # define V8_EXPORT
57 #endif
58 
59 #endif // V8_OS_WIN
60 
61 /**
62  * The v8 JavaScript engine.
63  */
64 namespace v8 {
65 
66 class AccessorSignature;
67 class Array;
68 class ArrayBuffer;
69 class BigInt;
70 class BigIntObject;
71 class Boolean;
72 class BooleanObject;
73 class Context;
74 class Data;
75 class Date;
76 class External;
77 class Function;
78 class FunctionTemplate;
79 class HeapProfiler;
80 class ImplementationUtilities;
81 class Int32;
82 class Integer;
83 class Isolate;
84 template <class T>
85 class Maybe;
86 class Name;
87 class Number;
88 class NumberObject;
89 class Object;
90 class ObjectOperationDescriptor;
91 class ObjectTemplate;
92 class Platform;
93 class Primitive;
94 class Promise;
95 class PropertyDescriptor;
96 class Proxy;
97 class RawOperationDescriptor;
98 class Script;
99 class SharedArrayBuffer;
100 class Signature;
101 class StartupData;
102 class StackFrame;
103 class StackTrace;
104 class String;
105 class StringObject;
106 class Symbol;
107 class SymbolObject;
108 class PrimitiveArray;
109 class Private;
110 class Uint32;
111 class Utils;
112 class Value;
113 class WasmCompiledModule;
114 template <class T> class Local;
115 template <class T>
116 class MaybeLocal;
117 template <class T> class Eternal;
118 template<class T> class NonCopyablePersistentTraits;
119 template<class T> class PersistentBase;
120 template <class T, class M = NonCopyablePersistentTraits<T> >
121 class Persistent;
122 template <class T>
123 class Global;
124 template<class K, class V, class T> class PersistentValueMap;
125 template <class K, class V, class T>
127 template <class K, class V, class T>
128 class GlobalValueMap;
129 template<class V, class T> class PersistentValueVector;
130 template<class T, class P> class WeakCallbackObject;
131 class FunctionTemplate;
132 class ObjectTemplate;
133 template<typename T> class FunctionCallbackInfo;
134 template<typename T> class PropertyCallbackInfo;
135 class StackTrace;
136 class StackFrame;
137 class Isolate;
138 class CallHandlerHelper;
140 template<typename T> class ReturnValue;
141 
142 namespace internal {
143 class Arguments;
144 class DeferredHandles;
145 class Heap;
146 class HeapObject;
147 class Isolate;
148 class LocalEmbedderHeapTracer;
149 class NeverReadOnlySpaceObject;
150 class Object;
151 struct ScriptStreamingData;
152 template<typename T> class CustomArguments;
153 class PropertyCallbackArguments;
154 class FunctionCallbackArguments;
155 class GlobalHandles;
156 
157 namespace wasm {
158 class NativeModule;
159 class StreamingDecoder;
160 } // namespace wasm
161 
162 /**
163  * Configuration of tagging scheme.
164  */
165 const int kApiPointerSize = sizeof(void*); // NOLINT
166 const int kApiDoubleSize = sizeof(double); // NOLINT
167 const int kApiIntSize = sizeof(int); // NOLINT
168 const int kApiInt64Size = sizeof(int64_t); // NOLINT
169 
170 // Tag information for HeapObject.
171 const int kHeapObjectTag = 1;
172 const int kWeakHeapObjectTag = 3;
173 const int kHeapObjectTagSize = 2;
174 const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
175 
176 // Tag information for Smi.
177 const int kSmiTag = 0;
178 const int kSmiTagSize = 1;
179 const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
180 
181 template <size_t tagged_ptr_size>
182 struct SmiTagging;
183 
184 template <int kSmiShiftSize>
185 V8_INLINE internal::Object* IntToSmi(int value) {
186  int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
187  intptr_t tagged_value =
188  (static_cast<intptr_t>(value) << smi_shift_bits) | kSmiTag;
189  return reinterpret_cast<internal::Object*>(tagged_value);
190 }
191 
192 // Smi constants for systems where tagged pointer is a 32-bit value.
193 template <>
194 struct SmiTagging<4> {
195  enum { kSmiShiftSize = 0, kSmiValueSize = 31 };
196  static int SmiShiftSize() { return kSmiShiftSize; }
197  static int SmiValueSize() { return kSmiValueSize; }
198  V8_INLINE static int SmiToInt(const internal::Object* value) {
199  int shift_bits = kSmiTagSize + kSmiShiftSize;
200  // Throw away top 32 bits and shift down (requires >> to be sign extending).
201  return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
202  }
203  V8_INLINE static internal::Object* IntToSmi(int value) {
205  }
206  V8_INLINE static constexpr bool IsValidSmi(intptr_t value) {
207  // To be representable as an tagged small integer, the two
208  // most-significant bits of 'value' must be either 00 or 11 due to
209  // sign-extension. To check this we add 01 to the two
210  // most-significant bits, and check if the most-significant bit is 0
211  //
212  // CAUTION: The original code below:
213  // bool result = ((value + 0x40000000) & 0x80000000) == 0;
214  // may lead to incorrect results according to the C language spec, and
215  // in fact doesn't work correctly with gcc4.1.1 in some cases: The
216  // compiler may produce undefined results in case of signed integer
217  // overflow. The computation must be done w/ unsigned ints.
218  return static_cast<uintptr_t>(value) + 0x40000000U < 0x80000000U;
219  }
220 };
221 
222 // Smi constants for systems where tagged pointer is a 64-bit value.
223 template <>
224 struct SmiTagging<8> {
225  enum { kSmiShiftSize = 31, kSmiValueSize = 32 };
226  static int SmiShiftSize() { return kSmiShiftSize; }
227  static int SmiValueSize() { return kSmiValueSize; }
228  V8_INLINE static int SmiToInt(const internal::Object* value) {
229  int shift_bits = kSmiTagSize + kSmiShiftSize;
230  // Shift down and throw away top 32 bits.
231  return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
232  }
233  V8_INLINE static internal::Object* IntToSmi(int value) {
235  }
236  V8_INLINE static constexpr bool IsValidSmi(intptr_t value) {
237  // To be representable as a long smi, the value must be a 32-bit integer.
238  return (value == static_cast<int32_t>(value));
239  }
240 };
241 
242 #if V8_COMPRESS_POINTERS
243 static_assert(
245  "Pointer compression can be enabled only for 64-bit architectures");
246 typedef SmiTagging<4> PlatformSmiTagging;
247 #else
249 #endif
250 
253 const int kSmiMinValue = (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
254 const int kSmiMaxValue = -(kSmiMinValue + 1);
255 constexpr bool SmiValuesAre31Bits() { return kSmiValueSize == 31; }
256 constexpr bool SmiValuesAre32Bits() { return kSmiValueSize == 32; }
257 
258 } // namespace internal
259 
260 namespace debug {
261 class ConsoleCallArguments;
262 } // namespace debug
263 
264 // --- Handles ---
265 
266 #define TYPE_CHECK(T, S)
267  while (false) {
268  *(static_cast<T* volatile*>(0)) = static_cast<S*>(0);
269  }
270 
271 /**
272  * An object reference managed by the v8 garbage collector.
273  *
274  * All objects returned from v8 have to be tracked by the garbage
275  * collector so that it knows that the objects are still alive. Also,
276  * because the garbage collector may move objects, it is unsafe to
277  * point directly to an object. Instead, all objects are stored in
278  * handles which are known by the garbage collector and updated
279  * whenever an object moves. Handles should always be passed by value
280  * (except in cases like out-parameters) and they should never be
281  * allocated on the heap.
282  *
283  * There are two types of handles: local and persistent handles.
284  *
285  * Local handles are light-weight and transient and typically used in
286  * local operations. They are managed by HandleScopes. That means that a
287  * HandleScope must exist on the stack when they are created and that they are
288  * only valid inside of the HandleScope active during their creation.
289  * For passing a local handle to an outer HandleScope, an EscapableHandleScope
290  * and its Escape() method must be used.
291  *
292  * Persistent handles can be used when storing objects across several
293  * independent operations and have to be explicitly deallocated when they're no
294  * longer used.
295  *
296  * It is safe to extract the object stored in the handle by
297  * dereferencing the handle (for instance, to extract the Object* from
298  * a Local<Object>); the value will still be governed by a handle
299  * behind the scenes and the same rules apply to these values as to
300  * their handles.
301  */
302 template <class T>
303 class Local {
304  public:
305  V8_INLINE Local() : val_(0) {}
306  template <class S>
308  : val_(reinterpret_cast<T*>(*that)) {
309  /**
310  * This check fails when trying to convert between incompatible
311  * handles. For example, converting from a Local<String> to a
312  * Local<Number>.
313  */
314  TYPE_CHECK(T, S);
315  }
316 
317  /**
318  * Returns true if the handle is empty.
319  */
320  V8_INLINE bool IsEmpty() const { return val_ == 0; }
321 
322  /**
323  * Sets the handle to be empty. IsEmpty() will then return true.
324  */
325  V8_INLINE void Clear() { val_ = 0; }
326 
327  V8_INLINE T* operator->() const { return val_; }
328 
329  V8_INLINE T* operator*() const { return val_; }
330 
331  /**
332  * Checks whether two handles are the same.
333  * Returns true if both are empty, or if the objects
334  * to which they refer are identical.
335  * The handles' references are not checked.
336  */
337  template <class S>
338  V8_INLINE bool operator==(const Local<S>& that) const {
339  internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
340  internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
341  if (a == 0) return b == 0;
342  if (b == 0) return false;
343  return *a == *b;
344  }
345 
346  template <class S> V8_INLINE bool operator==(
347  const PersistentBase<S>& that) const {
348  internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
349  internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
350  if (a == 0) return b == 0;
351  if (b == 0) return false;
352  return *a == *b;
353  }
354 
355  /**
356  * Checks whether two handles are different.
357  * Returns true if only one of the handles is empty, or if
358  * the objects to which they refer are different.
359  * The handles' references are not checked.
360  */
361  template <class S>
362  V8_INLINE bool operator!=(const Local<S>& that) const {
363  return !operator==(that);
364  }
365 
366  template <class S> V8_INLINE bool operator!=(
367  const Persistent<S>& that) const {
368  return !operator==(that);
369  }
370 
371  /**
372  * Cast a handle to a subclass, e.g. Local<Value> to Local<Object>.
373  * This is only valid if the handle actually refers to a value of the
374  * target type.
375  */
376  template <class S> V8_INLINE static Local<T> Cast(Local<S> that) {
377 #ifdef V8_ENABLE_CHECKS
378  // If we're going to perform the type check then we have to check
379  // that the handle isn't empty before doing the checked cast.
380  if (that.IsEmpty()) return Local<T>();
381 #endif
382  return Local<T>(T::Cast(*that));
383  }
384 
385  /**
386  * Calling this is equivalent to Local<S>::Cast().
387  * In particular, this is only valid if the handle actually refers to a value
388  * of the target type.
389  */
390  template <class S>
391  V8_INLINE Local<S> As() const {
392  return Local<S>::Cast(*this);
393  }
394 
395  /**
396  * Create a local handle for the content of another handle.
397  * The referee is kept alive by the local handle even when
398  * the original handle is destroyed/disposed.
399  */
400  V8_INLINE static Local<T> New(Isolate* isolate, Local<T> that);
401  V8_INLINE static Local<T> New(Isolate* isolate,
402  const PersistentBase<T>& that);
403 
404  private:
405  friend class Utils;
406  template<class F> friend class Eternal;
407  template<class F> friend class PersistentBase;
408  template<class F, class M> friend class Persistent;
409  template<class F> friend class Local;
410  template <class F>
411  friend class MaybeLocal;
412  template<class F> friend class FunctionCallbackInfo;
413  template<class F> friend class PropertyCallbackInfo;
414  friend class String;
415  friend class Object;
416  friend class Context;
417  friend class Isolate;
418  friend class Private;
419  template<class F> friend class internal::CustomArguments;
420  friend Local<Primitive> Undefined(Isolate* isolate);
421  friend Local<Primitive> Null(Isolate* isolate);
422  friend Local<Boolean> True(Isolate* isolate);
423  friend Local<Boolean> False(Isolate* isolate);
424  friend class HandleScope;
425  friend class EscapableHandleScope;
426  template <class F1, class F2, class F3>
428  template<class F1, class F2> friend class PersistentValueVector;
429  template <class F>
430  friend class ReturnValue;
431 
432  explicit V8_INLINE Local(T* that) : val_(that) {}
433  V8_INLINE static Local<T> New(Isolate* isolate, T* that);
434  T* val_;
435 };
436 
437 
438 #if !defined(V8_IMMINENT_DEPRECATION_WARNINGS)
439 // Handle is an alias for Local for historical reasons.
440 template <class T>
441 using Handle = Local<T>;
442 #endif
443 
444 
445 /**
446  * A MaybeLocal<> is a wrapper around Local<> that enforces a check whether
447  * the Local<> is empty before it can be used.
448  *
449  * If an API method returns a MaybeLocal<>, the API method can potentially fail
450  * either because an exception is thrown, or because an exception is pending,
451  * e.g. because a previous API call threw an exception that hasn't been caught
452  * yet, or because a TerminateExecution exception was thrown. In that case, an
453  * empty MaybeLocal is returned.
454  */
455 template <class T>
456 class MaybeLocal {
457  public:
458  V8_INLINE MaybeLocal() : val_(nullptr) {}
459  template <class S>
461  : val_(reinterpret_cast<T*>(*that)) {
462  TYPE_CHECK(T, S);
463  }
464 
465  V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
466 
467  /**
468  * Converts this MaybeLocal<> to a Local<>. If this MaybeLocal<> is empty,
469  * |false| is returned and |out| is left untouched.
470  */
471  template <class S>
473  out->val_ = IsEmpty() ? nullptr : this->val_;
474  return !IsEmpty();
475  }
476 
477  /**
478  * Converts this MaybeLocal<> to a Local<>. If this MaybeLocal<> is empty,
479  * V8 will crash the process.
480  */
482 
483  /**
484  * Converts this MaybeLocal<> to a Local<>, using a default value if this
485  * MaybeLocal<> is empty.
486  */
487  template <class S>
488  V8_INLINE Local<S> FromMaybe(Local<S> default_value) const {
489  return IsEmpty() ? default_value : Local<S>(val_);
490  }
491 
492  private:
493  T* val_;
494 };
495 
496 /**
497  * Eternal handles are set-once handles that live for the lifetime of the
498  * isolate.
499  */
500 template <class T> class Eternal {
501  public:
502  V8_INLINE Eternal() : val_(nullptr) {}
503  template <class S>
504  V8_INLINE Eternal(Isolate* isolate, Local<S> handle) : val_(nullptr) {
505  Set(isolate, handle);
506  }
507  // Can only be safely called if already set.
508  V8_INLINE Local<T> Get(Isolate* isolate) const;
509  V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
510  template<class S> V8_INLINE void Set(Isolate* isolate, Local<S> handle);
511 
512  private:
513  T* val_;
514 };
515 
516 
517 static const int kInternalFieldsInWeakCallback = 2;
518 static const int kEmbedderFieldsInWeakCallback = 2;
519 
520 template <typename T>
522  public:
523  typedef void (*Callback)(const WeakCallbackInfo<T>& data);
524 
525  WeakCallbackInfo(Isolate* isolate, T* parameter,
526  void* embedder_fields[kEmbedderFieldsInWeakCallback],
527  Callback* callback)
528  : isolate_(isolate), parameter_(parameter), callback_(callback) {
529  for (int i = 0; i < kEmbedderFieldsInWeakCallback; ++i) {
530  embedder_fields_[i] = embedder_fields[i];
531  }
532  }
533 
534  V8_INLINE Isolate* GetIsolate() const { return isolate_; }
535  V8_INLINE T* GetParameter() const { return parameter_; }
536  V8_INLINE void* GetInternalField(int index) const;
537 
538  // When first called, the embedder MUST Reset() the Global which triggered the
539  // callback. The Global itself is unusable for anything else. No v8 other api
540  // calls may be called in the first callback. Should additional work be
541  // required, the embedder must set a second pass callback, which will be
542  // called after all the initial callbacks are processed.
543  // Calling SetSecondPassCallback on the second pass will immediately crash.
544  void SetSecondPassCallback(Callback callback) const { *callback_ = callback; }
545 
546  private:
547  Isolate* isolate_;
548  T* parameter_;
549  Callback* callback_;
550  void* embedder_fields_[kEmbedderFieldsInWeakCallback];
551 };
552 
553 
554 // kParameter will pass a void* parameter back to the callback, kInternalFields
555 // will pass the first two internal fields back to the callback, kFinalizer
556 // will pass a void* parameter back, but is invoked before the object is
557 // actually collected, so it can be resurrected. In the last case, it is not
558 // possible to request a second pass callback.
560 
561 /**
562  * An object reference that is independent of any handle scope. Where
563  * a Local handle only lives as long as the HandleScope in which it was
564  * allocated, a PersistentBase handle remains valid until it is explicitly
565  * disposed using Reset().
566  *
567  * A persistent handle contains a reference to a storage cell within
568  * the V8 engine which holds an object value and which is updated by
569  * the garbage collector whenever the object is moved. A new storage
570  * cell can be created using the constructor or PersistentBase::Reset and
571  * existing handles can be disposed using PersistentBase::Reset.
572  *
573  */
574 template <class T> class PersistentBase {
575  public:
576  /**
577  * If non-empty, destroy the underlying storage cell
578  * IsEmpty() will return true after this call.
579  */
580  V8_INLINE void Reset();
581  /**
582  * If non-empty, destroy the underlying storage cell
583  * and create a new one with the contents of other if other is non empty
584  */
585  template <class S>
586  V8_INLINE void Reset(Isolate* isolate, const Local<S>& other);
587 
588  /**
589  * If non-empty, destroy the underlying storage cell
590  * and create a new one with the contents of other if other is non empty
591  */
592  template <class S>
593  V8_INLINE void Reset(Isolate* isolate, const PersistentBase<S>& other);
594 
595  V8_INLINE bool IsEmpty() const { return val_ == NULL; }
596  V8_INLINE void Empty() { val_ = 0; }
597 
598  V8_INLINE Local<T> Get(Isolate* isolate) const {
599  return Local<T>::New(isolate, *this);
600  }
601 
602  template <class S>
603  V8_INLINE bool operator==(const PersistentBase<S>& that) const {
604  internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
605  internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
606  if (a == NULL) return b == NULL;
607  if (b == NULL) return false;
608  return *a == *b;
609  }
610 
611  template <class S>
612  V8_INLINE bool operator==(const Local<S>& that) const {
613  internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
614  internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
615  if (a == NULL) return b == NULL;
616  if (b == NULL) return false;
617  return *a == *b;
618  }
619 
620  template <class S>
621  V8_INLINE bool operator!=(const PersistentBase<S>& that) const {
622  return !operator==(that);
623  }
624 
625  template <class S>
626  V8_INLINE bool operator!=(const Local<S>& that) const {
627  return !operator==(that);
628  }
629 
630  /**
631  * Install a finalization callback on this object.
632  * NOTE: There is no guarantee as to *when* or even *if* the callback is
633  * invoked. The invocation is performed solely on a best effort basis.
634  * As always, GC-based finalization should *not* be relied upon for any
635  * critical form of resource management!
636  */
637  template <typename P>
638  V8_INLINE void SetWeak(P* parameter,
639  typename WeakCallbackInfo<P>::Callback callback,
640  WeakCallbackType type);
641 
642  /**
643  * Turns this handle into a weak phantom handle without finalization callback.
644  * The handle will be reset automatically when the garbage collector detects
645  * that the object is no longer reachable.
646  * A related function Isolate::NumberOfPhantomHandleResetsSinceLastCall
647  * returns how many phantom handles were reset by the garbage collector.
648  */
649  V8_INLINE void SetWeak();
650 
651  template<typename P>
653 
654  // TODO(dcarney): remove this.
655  V8_INLINE void ClearWeak() { ClearWeak<void>(); }
656 
657  /**
658  * Annotates the strong handle with the given label, which is then used by the
659  * heap snapshot generator as a name of the edge from the root to the handle.
660  * The function does not take ownership of the label and assumes that the
661  * label is valid as long as the handle is valid.
662  */
663  V8_INLINE void AnnotateStrongRetainer(const char* label);
664 
665  /**
666  * Allows the embedder to tell the v8 garbage collector that a certain object
667  * is alive. Only allowed when the embedder is asked to trace its heap by
668  * EmbedderHeapTracer.
669  */
670  V8_INLINE void RegisterExternalReference(Isolate* isolate) const;
671 
672  /**
673  * Marks the reference to this object independent. Garbage collector is free
674  * to ignore any object groups containing this object. Weak callback for an
675  * independent handle should not assume that it will be preceded by a global
676  * GC prologue callback or followed by a global GC epilogue callback.
677  */
679  "Objects are always considered independent. "
680  "Use MarkActive to avoid collecting otherwise dead weak handles.",
681  V8_INLINE void MarkIndependent());
682 
683  /**
684  * Marks the reference to this object as active. The scavenge garbage
685  * collection should not reclaim the objects marked as active, even if the
686  * object held by the handle is otherwise unreachable.
687  *
688  * This bit is cleared after the each garbage collection pass.
689  */
690  V8_INLINE void MarkActive();
691 
692  V8_DEPRECATE_SOON("See MarkIndependent.",
693  V8_INLINE bool IsIndependent() const);
694 
695  /** Checks if the handle holds the only reference to an object. */
696  V8_INLINE bool IsNearDeath() const;
697 
698  /** Returns true if the handle's reference is weak. */
699  V8_INLINE bool IsWeak() const;
700 
701  /**
702  * Assigns a wrapper class ID to the handle. See RetainedObjectInfo interface
703  * description in v8-profiler.h for details.
704  */
705  V8_INLINE void SetWrapperClassId(uint16_t class_id);
706 
707  /**
708  * Returns the class ID previously assigned to this handle or 0 if no class ID
709  * was previously assigned.
710  */
711  V8_INLINE uint16_t WrapperClassId() const;
712 
713  PersistentBase(const PersistentBase& other) = delete; // NOLINT
714  void operator=(const PersistentBase&) = delete;
715 
716  private:
717  friend class Isolate;
718  friend class Utils;
719  template<class F> friend class Local;
720  template<class F1, class F2> friend class Persistent;
721  template <class F>
722  friend class Global;
723  template<class F> friend class PersistentBase;
724  template<class F> friend class ReturnValue;
725  template <class F1, class F2, class F3>
727  template<class F1, class F2> friend class PersistentValueVector;
728  friend class Object;
729 
730  explicit V8_INLINE PersistentBase(T* val) : val_(val) {}
731  V8_INLINE static T* New(Isolate* isolate, T* that);
732 
733  T* val_;
734 };
735 
736 
737 /**
738  * Default traits for Persistent. This class does not allow
739  * use of the copy constructor or assignment operator.
740  * At present kResetInDestructor is not set, but that will change in a future
741  * version.
742  */
743 template<class T>
744 class NonCopyablePersistentTraits {
745  public:
746  typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
747  static const bool kResetInDestructor = false;
748  template<class S, class M>
749  V8_INLINE static void Copy(const Persistent<S, M>& source,
750  NonCopyablePersistent* dest) {
751  Uncompilable<Object>();
752  }
753  // TODO(dcarney): come up with a good compile error here.
754  template<class O> V8_INLINE static void Uncompilable() {
755  TYPE_CHECK(O, Primitive);
756  }
757 };
758 
759 
760 /**
761  * Helper class traits to allow copying and assignment of Persistent.
762  * This will clone the contents of storage cell, but not any of the flags, etc.
763  */
764 template<class T>
767  static const bool kResetInDestructor = true;
768  template<class S, class M>
769  static V8_INLINE void Copy(const Persistent<S, M>& source,
770  CopyablePersistent* dest) {
771  // do nothing, just allow copy
772  }
773 };
774 
775 
776 /**
777  * A PersistentBase which allows copy and assignment.
778  *
779  * Copy, assignment and destructor behavior is controlled by the traits
780  * class M.
781  *
782  * Note: Persistent class hierarchy is subject to future changes.
783  */
784 template <class T, class M> class Persistent : public PersistentBase<T> {
785  public:
786  /**
787  * A Persistent with no storage cell.
788  */
790  /**
791  * Construct a Persistent from a Local.
792  * When the Local is non-empty, a new storage cell is created
793  * pointing to the same object, and no flags are set.
794  */
795  template <class S>
796  V8_INLINE Persistent(Isolate* isolate, Local<S> that)
797  : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
798  TYPE_CHECK(T, S);
799  }
800  /**
801  * Construct a Persistent from a Persistent.
802  * When the Persistent is non-empty, a new storage cell is created
803  * pointing to the same object, and no flags are set.
804  */
805  template <class S, class M2>
806  V8_INLINE Persistent(Isolate* isolate, const Persistent<S, M2>& that)
807  : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
808  TYPE_CHECK(T, S);
809  }
810  /**
811  * The copy constructors and assignment operator create a Persistent
812  * exactly as the Persistent constructor, but the Copy function from the
813  * traits class is called, allowing the setting of flags based on the
814  * copied Persistent.
815  */
817  Copy(that);
818  }
819  template <class S, class M2>
820  V8_INLINE Persistent(const Persistent<S, M2>& that) : PersistentBase<T>(0) {
821  Copy(that);
822  }
823  V8_INLINE Persistent& operator=(const Persistent& that) { // NOLINT
824  Copy(that);
825  return *this;
826  }
827  template <class S, class M2>
828  V8_INLINE Persistent& operator=(const Persistent<S, M2>& that) { // NOLINT
829  Copy(that);
830  return *this;
831  }
832  /**
833  * The destructor will dispose the Persistent based on the
834  * kResetInDestructor flags in the traits class. Since not calling dispose
835  * can result in a memory leak, it is recommended to always set this flag.
836  */
838  if (M::kResetInDestructor) this->Reset();
839  }
840 
841  // TODO(dcarney): this is pretty useless, fix or remove
842  template <class S>
843  V8_INLINE static Persistent<T>& Cast(const Persistent<S>& that) { // NOLINT
844 #ifdef V8_ENABLE_CHECKS
845  // If we're going to perform the type check then we have to check
846  // that the handle isn't empty before doing the checked cast.
847  if (!that.IsEmpty()) T::Cast(*that);
848 #endif
849  return reinterpret_cast<Persistent<T>&>(const_cast<Persistent<S>&>(that));
850  }
851 
852  // TODO(dcarney): this is pretty useless, fix or remove
853  template <class S>
854  V8_INLINE Persistent<S>& As() const { // NOLINT
855  return Persistent<S>::Cast(*this);
856  }
857 
858  private:
859  friend class Isolate;
860  friend class Utils;
861  template<class F> friend class Local;
862  template<class F1, class F2> friend class Persistent;
863  template<class F> friend class ReturnValue;
864 
865  explicit V8_INLINE Persistent(T* that) : PersistentBase<T>(that) {}
866  V8_INLINE T* operator*() const { return this->val_; }
867  template<class S, class M2>
868  V8_INLINE void Copy(const Persistent<S, M2>& that);
869 };
870 
871 
872 /**
873  * A PersistentBase which has move semantics.
874  *
875  * Note: Persistent class hierarchy is subject to future changes.
876  */
877 template <class T>
878 class Global : public PersistentBase<T> {
879  public:
880  /**
881  * A Global with no storage cell.
882  */
883  V8_INLINE Global() : PersistentBase<T>(nullptr) {}
884  /**
885  * Construct a Global from a Local.
886  * When the Local is non-empty, a new storage cell is created
887  * pointing to the same object, and no flags are set.
888  */
889  template <class S>
890  V8_INLINE Global(Isolate* isolate, Local<S> that)
891  : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
892  TYPE_CHECK(T, S);
893  }
894  /**
895  * Construct a Global from a PersistentBase.
896  * When the Persistent is non-empty, a new storage cell is created
897  * pointing to the same object, and no flags are set.
898  */
899  template <class S>
900  V8_INLINE Global(Isolate* isolate, const PersistentBase<S>& that)
901  : PersistentBase<T>(PersistentBase<T>::New(isolate, that.val_)) {
902  TYPE_CHECK(T, S);
903  }
904  /**
905  * Move constructor.
906  */
907  V8_INLINE Global(Global&& other) : PersistentBase<T>(other.val_) { // NOLINT
908  other.val_ = nullptr;
909  }
910  V8_INLINE ~Global() { this->Reset(); }
911  /**
912  * Move via assignment.
913  */
914  template <class S>
915  V8_INLINE Global& operator=(Global<S>&& rhs) { // NOLINT
916  TYPE_CHECK(T, S);
917  if (this != &rhs) {
918  this->Reset();
919  this->val_ = rhs.val_;
920  rhs.val_ = nullptr;
921  }
922  return *this;
923  }
924  /**
925  * Pass allows returning uniques from functions, etc.
926  */
927  Global Pass() { return static_cast<Global&&>(*this); } // NOLINT
928 
929  /*
930  * For compatibility with Chromium's base::Bind (base::Passed).
931  */
932  typedef void MoveOnlyTypeForCPP03;
933 
934  Global(const Global&) = delete;
935  void operator=(const Global&) = delete;
936 
937  private:
938  template <class F>
939  friend class ReturnValue;
940  V8_INLINE T* operator*() const { return this->val_; }
941 };
942 
943 
944 // UniquePersistent is an alias for Global for historical reason.
945 template <class T>
946 using UniquePersistent = Global<T>;
947 
948 
949  /**
950  * A stack-allocated class that governs a number of local handles.
951  * After a handle scope has been created, all local handles will be
952  * allocated within that handle scope until either the handle scope is
953  * deleted or another handle scope is created. If there is already a
954  * handle scope and a new one is created, all allocations will take
955  * place in the new handle scope until it is deleted. After that,
956  * new handles will again be allocated in the original handle scope.
957  *
958  * After the handle scope of a local handle has been deleted the
959  * garbage collector will no longer track the object stored in the
960  * handle and may deallocate it. The behavior of accessing a handle
961  * for which the handle scope has been deleted is undefined.
962  */
964  public:
965  explicit HandleScope(Isolate* isolate);
966 
968 
969  /**
970  * Counts the number of allocated handles.
971  */
972  static int NumberOfHandles(Isolate* isolate);
973 
974  V8_INLINE Isolate* GetIsolate() const {
975  return reinterpret_cast<Isolate*>(isolate_);
976  }
977 
978  HandleScope(const HandleScope&) = delete;
979  void operator=(const HandleScope&) = delete;
980 
981  protected:
983 
984  void Initialize(Isolate* isolate);
985 
986  static internal::Object** CreateHandle(internal::Isolate* isolate,
987  internal::Object* value);
988 
989  private:
990  // Declaring operator new and delete as deleted is not spec compliant.
991  // Therefore declare them private instead to disable dynamic alloc
992  void* operator new(size_t size);
993  void* operator new[](size_t size);
994  void operator delete(void*, size_t);
995  void operator delete[](void*, size_t);
996 
997  // Uses heap_object to obtain the current Isolate.
998  static internal::Object** CreateHandle(
999  internal::NeverReadOnlySpaceObject* heap_object, internal::Object* value);
1000 
1001  internal::Isolate* isolate_;
1002  internal::Object** prev_next_;
1003  internal::Object** prev_limit_;
1004 
1005  // Local::New uses CreateHandle with an Isolate* parameter.
1006  template<class F> friend class Local;
1007 
1008  // Object::GetInternalField and Context::GetEmbedderData use CreateHandle with
1009  // a HeapObject* in their shortcuts.
1010  friend class Object;
1011  friend class Context;
1012 };
1013 
1014 
1015 /**
1016  * A HandleScope which first allocates a handle in the current scope
1017  * which will be later filled with the escape value.
1018  */
1020  public:
1021  explicit EscapableHandleScope(Isolate* isolate);
1023 
1024  /**
1025  * Pushes the value into the previous scope and returns a handle to it.
1026  * Cannot be called twice.
1027  */
1028  template <class T>
1029  V8_INLINE Local<T> Escape(Local<T> value) {
1030  internal::Object** slot =
1031  Escape(reinterpret_cast<internal::Object**>(*value));
1032  return Local<T>(reinterpret_cast<T*>(slot));
1033  }
1034 
1035  template <class T>
1037  return Escape(value.FromMaybe(Local<T>()));
1038  }
1039 
1041  void operator=(const EscapableHandleScope&) = delete;
1042 
1043  private:
1044  // Declaring operator new and delete as deleted is not spec compliant.
1045  // Therefore declare them private instead to disable dynamic alloc
1046  void* operator new(size_t size);
1047  void* operator new[](size_t size);
1048  void operator delete(void*, size_t);
1049  void operator delete[](void*, size_t);
1050 
1051  internal::Object** Escape(internal::Object** escape_value);
1052  internal::Object** escape_slot_;
1053 };
1054 
1055 /**
1056  * A SealHandleScope acts like a handle scope in which no handle allocations
1057  * are allowed. It can be useful for debugging handle leaks.
1058  * Handles can be allocated within inner normal HandleScopes.
1059  */
1061  public:
1062  explicit SealHandleScope(Isolate* isolate);
1064 
1066  void operator=(const SealHandleScope&) = delete;
1067 
1068  private:
1069  // Declaring operator new and delete as deleted is not spec compliant.
1070  // Therefore declare them private instead to disable dynamic alloc
1071  void* operator new(size_t size);
1072  void* operator new[](size_t size);
1073  void operator delete(void*, size_t);
1074  void operator delete[](void*, size_t);
1075 
1076  internal::Isolate* const isolate_;
1077  internal::Object** prev_limit_;
1078  int prev_sealed_level_;
1079 };
1080 
1081 
1082 // --- Special objects ---
1083 
1084 
1085 /**
1086  * The superclass of values and API object templates.
1087  */
1089  private:
1090  Data();
1091 };
1092 
1093 /**
1094  * A container type that holds relevant metadata for module loading.
1095  *
1096  * This is passed back to the embedder as part of
1097  * HostImportModuleDynamicallyCallback for module loading.
1098  */
1100  public:
1101  /**
1102  * The name that was passed by the embedder as ResourceName to the
1103  * ScriptOrigin. This can be either a v8::String or v8::Undefined.
1104  */
1106 
1107  /**
1108  * The options that were passed by the embedder as HostDefinedOptions to
1109  * the ScriptOrigin.
1110  */
1112 };
1113 
1114 /**
1115  * An array to hold Primitive values. This is used by the embedder to
1116  * pass host defined options to the ScriptOptions during compilation.
1117  *
1118  * This is passed back to the embedder as part of
1119  * HostImportModuleDynamicallyCallback for module loading.
1120  *
1121  */
1123  public:
1124  static Local<PrimitiveArray> New(Isolate* isolate, int length);
1125  int Length() const;
1126  void Set(Isolate* isolate, int index, Local<Primitive> item);
1127  Local<Primitive> Get(Isolate* isolate, int index);
1128 };
1129 
1130 /**
1131  * The optional attributes of ScriptOrigin.
1132  */
1134  public:
1135  V8_INLINE ScriptOriginOptions(bool is_shared_cross_origin = false,
1136  bool is_opaque = false, bool is_wasm = false,
1137  bool is_module = false)
1138  : flags_((is_shared_cross_origin ? kIsSharedCrossOrigin : 0) |
1139  (is_wasm ? kIsWasm : 0) | (is_opaque ? kIsOpaque : 0) |
1140  (is_module ? kIsModule : 0)) {}
1142  : flags_(flags &
1143  (kIsSharedCrossOrigin | kIsOpaque | kIsWasm | kIsModule)) {}
1144 
1145  bool IsSharedCrossOrigin() const {
1146  return (flags_ & kIsSharedCrossOrigin) != 0;
1147  }
1148  bool IsOpaque() const { return (flags_ & kIsOpaque) != 0; }
1149  bool IsWasm() const { return (flags_ & kIsWasm) != 0; }
1150  bool IsModule() const { return (flags_ & kIsModule) != 0; }
1151 
1152  int Flags() const { return flags_; }
1153 
1154  private:
1155  enum {
1156  kIsSharedCrossOrigin = 1,
1157  kIsOpaque = 1 << 1,
1158  kIsWasm = 1 << 2,
1159  kIsModule = 1 << 3
1160  };
1161  const int flags_;
1162 };
1163 
1164 /**
1165  * The origin, within a file, of a script.
1166  */
1168  public:
1170  Local<Value> resource_name,
1171  Local<Integer> resource_line_offset = Local<Integer>(),
1172  Local<Integer> resource_column_offset = Local<Integer>(),
1173  Local<Boolean> resource_is_shared_cross_origin = Local<Boolean>(),
1174  Local<Integer> script_id = Local<Integer>(),
1175  Local<Value> source_map_url = Local<Value>(),
1176  Local<Boolean> resource_is_opaque = Local<Boolean>(),
1177  Local<Boolean> is_wasm = Local<Boolean>(),
1178  Local<Boolean> is_module = Local<Boolean>(),
1179  Local<PrimitiveArray> host_defined_options = Local<PrimitiveArray>());
1180 
1181  V8_INLINE Local<Value> ResourceName() const;
1184  V8_INLINE Local<Integer> ScriptID() const;
1185  V8_INLINE Local<Value> SourceMapUrl() const;
1187  V8_INLINE ScriptOriginOptions Options() const { return options_; }
1188 
1189  private:
1190  Local<Value> resource_name_;
1191  Local<Integer> resource_line_offset_;
1192  Local<Integer> resource_column_offset_;
1193  ScriptOriginOptions options_;
1194  Local<Integer> script_id_;
1195  Local<Value> source_map_url_;
1196  Local<PrimitiveArray> host_defined_options_;
1197 };
1198 
1199 /**
1200  * A compiled JavaScript script, not yet tied to a Context.
1201  */
1203  public:
1204  /**
1205  * Binds the script to the currently entered context.
1206  */
1208 
1209  int GetId();
1211 
1212  /**
1213  * Data read from magic sourceURL comments.
1214  */
1216  /**
1217  * Data read from magic sourceMappingURL comments.
1218  */
1220 
1221  /**
1222  * Returns zero based line number of the code_pos location in the script.
1223  * -1 will be returned if no information available.
1224  */
1225  int GetLineNumber(int code_pos);
1226 
1227  static const int kNoScriptId = 0;
1228 };
1229 
1230 /**
1231  * A compiled JavaScript module, not yet tied to a Context.
1232  */
1234  // Only used as a container for code caching.
1235 };
1236 
1237 /**
1238  * A location in JavaScript source.
1239  */
1241  public:
1242  int GetLineNumber() { return line_number_; }
1243  int GetColumnNumber() { return column_number_; }
1244 
1245  Location(int line_number, int column_number)
1246  : line_number_(line_number), column_number_(column_number) {}
1247 
1248  private:
1249  int line_number_;
1250  int column_number_;
1251 };
1252 
1253 /**
1254  * A compiled JavaScript module.
1255  */
1257  public:
1258  /**
1259  * The different states a module can be in.
1260  *
1261  * This corresponds to the states used in ECMAScript except that "evaluated"
1262  * is split into kEvaluated and kErrored, indicating success and failure,
1263  * respectively.
1264  */
1265  enum Status {
1271  kErrored
1272  };
1273 
1274  /**
1275  * Returns the module's current status.
1276  */
1278 
1279  /**
1280  * For a module in kErrored status, this returns the corresponding exception.
1281  */
1283 
1284  /**
1285  * Returns the number of modules requested by this module.
1286  */
1288 
1289  /**
1290  * Returns the ith module specifier in this module.
1291  * i must be < GetModuleRequestsLength() and >= 0.
1292  */
1294 
1295  /**
1296  * Returns the source location (line number and column number) of the ith
1297  * module specifier's first occurrence in this module.
1298  */
1300 
1301  /**
1302  * Returns the identity hash for this object.
1303  */
1304  int GetIdentityHash() const;
1305 
1306  typedef MaybeLocal<Module> (*ResolveCallback)(Local<Context> context,
1307  Local<String> specifier,
1308  Local<Module> referrer);
1309 
1310  /**
1311  * Instantiates the module and its dependencies.
1312  *
1313  * Returns an empty Maybe<bool> if an exception occurred during
1314  * instantiation. (In the case where the callback throws an exception, that
1315  * exception is propagated.)
1316  */
1317  V8_WARN_UNUSED_RESULT Maybe<bool> InstantiateModule(Local<Context> context,
1318  ResolveCallback callback);
1319 
1320  /**
1321  * Evaluates the module and its dependencies.
1322  *
1323  * If status is kInstantiated, run the module's code. On success, set status
1324  * to kEvaluated and return the completion value; on failure, set status to
1325  * kErrored and propagate the thrown exception (which is then also available
1326  * via |GetException|).
1327  */
1329 
1330  /**
1331  * Returns the namespace object of this module.
1332  *
1333  * The module's status must be at least kInstantiated.
1334  */
1336 
1337  /**
1338  * Returns the corresponding context-unbound module script.
1339  *
1340  * The module must be unevaluated, i.e. its status must not be kEvaluating,
1341  * kEvaluated or kErrored.
1342  */
1344 };
1345 
1346 /**
1347  * A compiled JavaScript script, tied to a Context which was active when the
1348  * script was compiled.
1349  */
1351  public:
1352  /**
1353  * A shorthand for ScriptCompiler::Compile().
1354  */
1356  Local<Context> context, Local<String> source,
1357  ScriptOrigin* origin = nullptr);
1358 
1359  /**
1360  * Runs the script returning the resulting value. It will be run in the
1361  * context in which it was created (ScriptCompiler::CompileBound or
1362  * UnboundScript::BindToCurrentContext()).
1363  */
1365 
1366  /**
1367  * Returns the corresponding context-unbound script.
1368  */
1370 };
1371 
1372 
1373 /**
1374  * For compiling scripts.
1375  */
1377  public:
1378  /**
1379  * Compilation data that the embedder can cache and pass back to speed up
1380  * future compilations. The data is produced if the CompilerOptions passed to
1381  * the compilation functions in ScriptCompiler contains produce_data_to_cache
1382  * = true. The data to cache can then can be retrieved from
1383  * UnboundScript.
1384  */
1388  BufferOwned
1389  };
1390 
1392  : data(NULL),
1393  length(0),
1394  rejected(false),
1396 
1397  // If buffer_policy is BufferNotOwned, the caller keeps the ownership of
1398  // data and guarantees that it stays alive until the CachedData object is
1399  // destroyed. If the policy is BufferOwned, the given data will be deleted
1400  // (with delete[]) when the CachedData object is destroyed.
1401  CachedData(const uint8_t* data, int length,
1402  BufferPolicy buffer_policy = BufferNotOwned);
1404  // TODO(marja): Async compilation; add constructors which take a callback
1405  // which will be called when V8 no longer needs the data.
1406  const uint8_t* data;
1407  int length;
1408  bool rejected;
1410 
1411  // Prevent copying.
1412  CachedData(const CachedData&) = delete;
1413  CachedData& operator=(const CachedData&) = delete;
1414  };
1415 
1416  /**
1417  * Source code which can be then compiled to a UnboundScript or Script.
1418  */
1419  class Source {
1420  public:
1421  // Source takes ownership of CachedData.
1422  V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
1423  CachedData* cached_data = NULL);
1424  V8_INLINE Source(Local<String> source_string,
1425  CachedData* cached_data = NULL);
1426  V8_INLINE ~Source();
1427 
1428  // Ownership of the CachedData or its buffers is *not* transferred to the
1429  // caller. The CachedData object is alive as long as the Source object is
1430  // alive.
1431  V8_INLINE const CachedData* GetCachedData() const;
1432 
1434 
1435  // Prevent copying.
1436  Source(const Source&) = delete;
1437  Source& operator=(const Source&) = delete;
1438 
1439  private:
1440  friend class ScriptCompiler;
1441 
1442  Local<String> source_string;
1443 
1444  // Origin information
1445  Local<Value> resource_name;
1446  Local<Integer> resource_line_offset;
1447  Local<Integer> resource_column_offset;
1448  ScriptOriginOptions resource_options;
1449  Local<Value> source_map_url;
1450  Local<PrimitiveArray> host_defined_options;
1451 
1452  // Cached data from previous compilation (if a kConsume*Cache flag is
1453  // set), or hold newly generated cache data (kProduce*Cache flags) are
1454  // set when calling a compile method.
1455  CachedData* cached_data;
1456  };
1457 
1458  /**
1459  * For streaming incomplete script data to V8. The embedder should implement a
1460  * subclass of this class.
1461  */
1463  public:
1464  virtual ~ExternalSourceStream() {}
1465 
1466  /**
1467  * V8 calls this to request the next chunk of data from the embedder. This
1468  * function will be called on a background thread, so it's OK to block and
1469  * wait for the data, if the embedder doesn't have data yet. Returns the
1470  * length of the data returned. When the data ends, GetMoreData should
1471  * return 0. Caller takes ownership of the data.
1472  *
1473  * When streaming UTF-8 data, V8 handles multi-byte characters split between
1474  * two data chunks, but doesn't handle multi-byte characters split between
1475  * more than two data chunks. The embedder can avoid this problem by always
1476  * returning at least 2 bytes of data.
1477  *
1478  * When streaming UTF-16 data, V8 does not handle characters split between
1479  * two data chunks. The embedder has to make sure that chunks have an even
1480  * length.
1481  *
1482  * If the embedder wants to cancel the streaming, they should make the next
1483  * GetMoreData call return 0. V8 will interpret it as end of data (and most
1484  * probably, parsing will fail). The streaming task will return as soon as
1485  * V8 has parsed the data it received so far.
1486  */
1487  virtual size_t GetMoreData(const uint8_t** src) = 0;
1488 
1489  /**
1490  * V8 calls this method to set a 'bookmark' at the current position in
1491  * the source stream, for the purpose of (maybe) later calling
1492  * ResetToBookmark. If ResetToBookmark is called later, then subsequent
1493  * calls to GetMoreData should return the same data as they did when
1494  * SetBookmark was called earlier.
1495  *
1496  * The embedder may return 'false' to indicate it cannot provide this
1497  * functionality.
1498  */
1499  virtual bool SetBookmark();
1500 
1501  /**
1502  * V8 calls this to return to a previously set bookmark.
1503  */
1504  virtual void ResetToBookmark();
1505  };
1506 
1507 
1508  /**
1509  * Source code which can be streamed into V8 in pieces. It will be parsed
1510  * while streaming. It can be compiled after the streaming is complete.
1511  * StreamedSource must be kept alive while the streaming task is ran (see
1512  * ScriptStreamingTask below).
1513  */
1515  public:
1517 
1518  StreamedSource(ExternalSourceStream* source_stream, Encoding encoding);
1520 
1521  // Ownership of the CachedData or its buffers is *not* transferred to the
1522  // caller. The CachedData object is alive as long as the StreamedSource
1523  // object is alive.
1524  const CachedData* GetCachedData() const;
1525 
1526  internal::ScriptStreamingData* impl() const { return impl_; }
1527 
1528  // Prevent copying.
1529  StreamedSource(const StreamedSource&) = delete;
1531 
1532  private:
1533  internal::ScriptStreamingData* impl_;
1534  };
1535 
1536  /**
1537  * A streaming task which the embedder must run on a background thread to
1538  * stream scripts into V8. Returned by ScriptCompiler::StartStreamingScript.
1539  */
1541  public:
1542  virtual ~ScriptStreamingTask() {}
1543  virtual void Run() = 0;
1544  };
1545 
1554  };
1555 
1556  /**
1557  * The reason for which we are not requesting or providing a code cache.
1558  */
1575  };
1576 
1577  /**
1578  * Compiles the specified script (context-independent).
1579  * Cached data as part of the source object can be optionally produced to be
1580  * consumed later to speed up compilation of identical source scripts.
1581  *
1582  * Note that when producing cached data, the source must point to NULL for
1583  * cached data. When consuming cached data, the cached data must have been
1584  * produced by the same version of V8.
1585  *
1586  * \param source Script source code.
1587  * \return Compiled script object (context independent; for running it must be
1588  * bound to a context).
1589  */
1591  Isolate* isolate, Source* source,
1593  NoCacheReason no_cache_reason = kNoCacheNoReason);
1594 
1595  /**
1596  * Compiles the specified script (bound to current context).
1597  *
1598  * \param source Script source code.
1599  * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
1600  * using pre_data speeds compilation if it's done multiple times.
1601  * Owned by caller, no references are kept when this function returns.
1602  * \return Compiled script object, bound to the context that was active
1603  * when this function was called. When run it will always use this
1604  * context.
1605  */
1607  Local<Context> context, Source* source,
1609  NoCacheReason no_cache_reason = kNoCacheNoReason);
1610 
1611  /**
1612  * Returns a task which streams script data into V8, or NULL if the script
1613  * cannot be streamed. The user is responsible for running the task on a
1614  * background thread and deleting it. When ran, the task starts parsing the
1615  * script, and it will request data from the StreamedSource as needed. When
1616  * ScriptStreamingTask::Run exits, all data has been streamed and the script
1617  * can be compiled (see Compile below).
1618  *
1619  * This API allows to start the streaming with as little data as possible, and
1620  * the remaining data (for example, the ScriptOrigin) is passed to Compile.
1621  */
1623  Isolate* isolate, StreamedSource* source,
1624  CompileOptions options = kNoCompileOptions);
1625 
1626  /**
1627  * Compiles a streamed script (bound to current context).
1628  *
1629  * This can only be called after the streaming has finished
1630  * (ScriptStreamingTask has been run). V8 doesn't construct the source string
1631  * during streaming, so the embedder needs to pass the full source here.
1632  */
1634  Local<Context> context, StreamedSource* source,
1635  Local<String> full_source_string, const ScriptOrigin& origin);
1636 
1637  /**
1638  * Return a version tag for CachedData for the current V8 version & flags.
1639  *
1640  * This value is meant only for determining whether a previously generated
1641  * CachedData instance is still valid; the tag has no other meaing.
1642  *
1643  * Background: The data carried by CachedData may depend on the exact
1644  * V8 version number or current compiler flags. This means that when
1645  * persisting CachedData, the embedder must take care to not pass in
1646  * data from another V8 version, or the same version with different
1647  * features enabled.
1648  *
1649  * The easiest way to do so is to clear the embedder's cache on any
1650  * such change.
1651  *
1652  * Alternatively, this tag can be stored alongside the cached data and
1653  * compared when it is being used.
1654  */
1655  static uint32_t CachedDataVersionTag();
1656 
1657  /**
1658  * Compile an ES module, returning a Module that encapsulates
1659  * the compiled code.
1660  *
1661  * Corresponds to the ParseModule abstract operation in the
1662  * ECMAScript specification.
1663  */
1665  Isolate* isolate, Source* source,
1667  NoCacheReason no_cache_reason = kNoCacheNoReason);
1668 
1669  /**
1670  * Compile a function for a given context. This is equivalent to running
1671  *
1672  * with (obj) {
1673  * return function(args) { ... }
1674  * }
1675  *
1676  * It is possible to specify multiple context extensions (obj in the above
1677  * example).
1678  */
1680  Local<Context> context, Source* source, size_t arguments_count,
1681  Local<String> arguments[], size_t context_extension_count,
1682  Local<Object> context_extensions[],
1684  NoCacheReason no_cache_reason = kNoCacheNoReason);
1685 
1686  /**
1687  * Creates and returns code cache for the specified unbound_script.
1688  * This will return nullptr if the script cannot be serialized. The
1689  * CachedData returned by this function should be owned by the caller.
1690  */
1691  static CachedData* CreateCodeCache(Local<UnboundScript> unbound_script);
1692 
1693  /**
1694  * Creates and returns code cache for the specified unbound_module_script.
1695  * This will return nullptr if the script cannot be serialized. The
1696  * CachedData returned by this function should be owned by the caller.
1697  */
1699  Local<UnboundModuleScript> unbound_module_script);
1700 
1701  /**
1702  * Creates and returns code cache for the specified function that was
1703  * previously produced by CompileFunctionInContext.
1704  * This will return nullptr if the script cannot be serialized. The
1705  * CachedData returned by this function should be owned by the caller.
1706  */
1708 
1709  private:
1710  static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundInternal(
1711  Isolate* isolate, Source* source, CompileOptions options,
1712  NoCacheReason no_cache_reason);
1713 };
1714 
1715 
1716 /**
1717  * An error message.
1718  */
1720  public:
1721  Local<String> Get() const;
1722 
1723  /**
1724  * Return the isolate to which the Message belongs.
1725  */
1726  Isolate* GetIsolate() const;
1727 
1729  Local<Context> context) const;
1730 
1731  /**
1732  * Returns the origin for the script from where the function causing the
1733  * error originates.
1734  */
1736 
1737  /**
1738  * Returns the resource name for the script from where the function causing
1739  * the error originates.
1740  */
1742 
1743  /**
1744  * Exception stack trace. By default stack traces are not captured for
1745  * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
1746  * to change this option.
1747  */
1749 
1750  /**
1751  * Returns the number, 1-based, of the line where the error occurred.
1752  */
1753  V8_WARN_UNUSED_RESULT Maybe<int> GetLineNumber(Local<Context> context) const;
1754 
1755  /**
1756  * Returns the index within the script of the first character where
1757  * the error occurred.
1758  */
1759  int GetStartPosition() const;
1760 
1761  /**
1762  * Returns the index within the script of the last character where
1763  * the error occurred.
1764  */
1765  int GetEndPosition() const;
1766 
1767  /**
1768  * Returns the error level of the message.
1769  */
1770  int ErrorLevel() const;
1771 
1772  /**
1773  * Returns the index within the line of the first character where
1774  * the error occurred.
1775  */
1776  int GetStartColumn() const;
1777  V8_WARN_UNUSED_RESULT Maybe<int> GetStartColumn(Local<Context> context) const;
1778 
1779  /**
1780  * Returns the index within the line of the last character where
1781  * the error occurred.
1782  */
1783  int GetEndColumn() const;
1784  V8_WARN_UNUSED_RESULT Maybe<int> GetEndColumn(Local<Context> context) const;
1785 
1786  /**
1787  * Passes on the value set by the embedder when it fed the script from which
1788  * this Message was generated to V8.
1789  */
1790  bool IsSharedCrossOrigin() const;
1791  bool IsOpaque() const;
1792 
1793  // TODO(1245381): Print to a string instead of on a FILE.
1794  static void PrintCurrentStackTrace(Isolate* isolate, FILE* out);
1795 
1796  static const int kNoLineNumberInfo = 0;
1797  static const int kNoColumnInfo = 0;
1798  static const int kNoScriptIdInfo = 0;
1799 };
1800 
1801 
1802 /**
1803  * Representation of a JavaScript stack trace. The information collected is a
1804  * snapshot of the execution stack and the information remains valid after
1805  * execution continues.
1806  */
1808  public:
1809  /**
1810  * Flags that determine what information is placed captured for each
1811  * StackFrame when grabbing the current stack trace.
1812  * Note: these options are deprecated and we always collect all available
1813  * information (kDetailed).
1814  */
1818  kScriptName = 1 << 2,
1819  kFunctionName = 1 << 3,
1820  kIsEval = 1 << 4,
1821  kIsConstructor = 1 << 5,
1823  kScriptId = 1 << 7,
1827  };
1828 
1829  /**
1830  * Returns a StackFrame at a particular index.
1831  */
1832  Local<StackFrame> GetFrame(Isolate* isolate, uint32_t index) const;
1833 
1834  /**
1835  * Returns the number of StackFrames.
1836  */
1837  int GetFrameCount() const;
1838 
1839  /**
1840  * Grab a snapshot of the current JavaScript execution stack.
1841  *
1842  * \param frame_limit The maximum number of stack frames we want to capture.
1843  * \param options Enumerates the set of things we will capture for each
1844  * StackFrame.
1845  */
1847  Isolate* isolate, int frame_limit, StackTraceOptions options = kDetailed);
1848 };
1849 
1850 
1851 /**
1852  * A single JavaScript stack frame.
1853  */
1855  public:
1856  /**
1857  * Returns the number, 1-based, of the line for the associate function call.
1858  * This method will return Message::kNoLineNumberInfo if it is unable to
1859  * retrieve the line number, or if kLineNumber was not passed as an option
1860  * when capturing the StackTrace.
1861  */
1862  int GetLineNumber() const;
1863 
1864  /**
1865  * Returns the 1-based column offset on the line for the associated function
1866  * call.
1867  * This method will return Message::kNoColumnInfo if it is unable to retrieve
1868  * the column number, or if kColumnOffset was not passed as an option when
1869  * capturing the StackTrace.
1870  */
1871  int GetColumn() const;
1872 
1873  /**
1874  * Returns the id of the script for the function for this StackFrame.
1875  * This method will return Message::kNoScriptIdInfo if it is unable to
1876  * retrieve the script id, or if kScriptId was not passed as an option when
1877  * capturing the StackTrace.
1878  */
1879  int GetScriptId() const;
1880 
1881  /**
1882  * Returns the name of the resource that contains the script for the
1883  * function for this StackFrame.
1884  */
1886 
1887  /**
1888  * Returns the name of the resource that contains the script for the
1889  * function for this StackFrame or sourceURL value if the script name
1890  * is undefined and its source ends with //# sourceURL=... string or
1891  * deprecated //@ sourceURL=... string.
1892  */
1894 
1895  /**
1896  * Returns the name of the function associated with this stack frame.
1897  */
1899 
1900  /**
1901  * Returns whether or not the associated function is compiled via a call to
1902  * eval().
1903  */
1904  bool IsEval() const;
1905 
1906  /**
1907  * Returns whether or not the associated function is called as a
1908  * constructor via "new".
1909  */
1910  bool IsConstructor() const;
1911 
1912  /**
1913  * Returns whether or not the associated functions is defined in wasm.
1914  */
1915  bool IsWasm() const;
1916 };
1917 
1918 
1919 // A StateTag represents a possible state of the VM.
1920 enum StateTag {
1928  IDLE
1929 };
1930 
1931 // A RegisterState represents the current state of registers used
1932 // by the sampling profiler API.
1934  RegisterState() : pc(nullptr), sp(nullptr), fp(nullptr) {}
1935  void* pc; // Instruction pointer.
1936  void* sp; // Stack pointer.
1937  void* fp; // Frame pointer.
1938 };
1939 
1940 // The output structure filled up by GetStackSample API function.
1941 struct SampleInfo {
1942  size_t frames_count; // Number of frames collected.
1943  StateTag vm_state; // Current VM state.
1944  void* external_callback_entry; // External callback address if VM is
1945  // executing an external callback.
1946 };
1947 
1948 /**
1949  * A JSON Parser and Stringifier.
1950  */
1952  public:
1953  /**
1954  * Tries to parse the string |json_string| and returns it as value if
1955  * successful.
1956  *
1957  * \param json_string The string to parse.
1958  * \return The corresponding value if successfully parsed.
1959  */
1960  static V8_DEPRECATE_SOON("Use the maybe version taking context",
1961  MaybeLocal<Value> Parse(Isolate* isolate,
1962  Local<String> json_string));
1964  Local<Context> context, Local<String> json_string);
1965 
1966  /**
1967  * Tries to stringify the JSON-serializable object |json_object| and returns
1968  * it as string if successful.
1969  *
1970  * \param json_object The JSON-serializable object to stringify.
1971  * \return The corresponding string if successfully stringified.
1972  */
1974  Local<Context> context, Local<Value> json_object,
1975  Local<String> gap = Local<String>());
1976 };
1977 
1978 /**
1979  * Value serialization compatible with the HTML structured clone algorithm.
1980  * The format is backward-compatible (i.e. safe to store to disk).
1981  *
1982  * WARNING: This API is under development, and changes (including incompatible
1983  * changes to the API or wire format) may occur without notice until this
1984  * warning is removed.
1985  */
1987  public:
1989  public:
1990  virtual ~Delegate() {}
1991 
1992  /**
1993  * Handles the case where a DataCloneError would be thrown in the structured
1994  * clone spec. Other V8 embedders may throw some other appropriate exception
1995  * type.
1996  */
1997  virtual void ThrowDataCloneError(Local<String> message) = 0;
1998 
1999  /**
2000  * The embedder overrides this method to write some kind of host object, if
2001  * possible. If not, a suitable exception should be thrown and
2002  * Nothing<bool>() returned.
2003  */
2004  virtual Maybe<bool> WriteHostObject(Isolate* isolate, Local<Object> object);
2005 
2006  /**
2007  * Called when the ValueSerializer is going to serialize a
2008  * SharedArrayBuffer object. The embedder must return an ID for the
2009  * object, using the same ID if this SharedArrayBuffer has already been
2010  * serialized in this buffer. When deserializing, this ID will be passed to
2011  * ValueDeserializer::GetSharedArrayBufferFromId as |clone_id|.
2012  *
2013  * If the object cannot be serialized, an
2014  * exception should be thrown and Nothing<uint32_t>() returned.
2015  */
2016  virtual Maybe<uint32_t> GetSharedArrayBufferId(
2017  Isolate* isolate, Local<SharedArrayBuffer> shared_array_buffer);
2018 
2019  virtual Maybe<uint32_t> GetWasmModuleTransferId(
2020  Isolate* isolate, Local<WasmCompiledModule> module);
2021  /**
2022  * Allocates memory for the buffer of at least the size provided. The actual
2023  * size (which may be greater or equal) is written to |actual_size|. If no
2024  * buffer has been allocated yet, nullptr will be provided.
2025  *
2026  * If the memory cannot be allocated, nullptr should be returned.
2027  * |actual_size| will be ignored. It is assumed that |old_buffer| is still
2028  * valid in this case and has not been modified.
2029  *
2030  * The default implementation uses the stdlib's `realloc()` function.
2031  */
2032  virtual void* ReallocateBufferMemory(void* old_buffer, size_t size,
2033  size_t* actual_size);
2034 
2035  /**
2036  * Frees a buffer allocated with |ReallocateBufferMemory|.
2037  *
2038  * The default implementation uses the stdlib's `free()` function.
2039  */
2040  virtual void FreeBufferMemory(void* buffer);
2041  };
2042 
2043  explicit ValueSerializer(Isolate* isolate);
2044  ValueSerializer(Isolate* isolate, Delegate* delegate);
2046 
2047  /**
2048  * Writes out a header, which includes the format version.
2049  */
2050  void WriteHeader();
2051 
2052  /**
2053  * Serializes a JavaScript value into the buffer.
2054  */
2055  V8_WARN_UNUSED_RESULT Maybe<bool> WriteValue(Local<Context> context,
2056  Local<Value> value);
2057 
2058  /**
2059  * Returns the stored data. This serializer should not be used once the buffer
2060  * is released. The contents are undefined if a previous write has failed.
2061  */
2062  V8_DEPRECATE_SOON("Use Release()", std::vector<uint8_t> ReleaseBuffer());
2063 
2064  /**
2065  * Returns the stored data (allocated using the delegate's
2066  * ReallocateBufferMemory) and its size. This serializer should not be used
2067  * once the buffer is released. The contents are undefined if a previous write
2068  * has failed. Ownership of the buffer is transferred to the caller.
2069  */
2070  V8_WARN_UNUSED_RESULT std::pair<uint8_t*, size_t> Release();
2071 
2072  /**
2073  * Marks an ArrayBuffer as havings its contents transferred out of band.
2074  * Pass the corresponding ArrayBuffer in the deserializing context to
2075  * ValueDeserializer::TransferArrayBuffer.
2076  */
2077  void TransferArrayBuffer(uint32_t transfer_id,
2078  Local<ArrayBuffer> array_buffer);
2079 
2080  /**
2081  * Similar to TransferArrayBuffer, but for SharedArrayBuffer.
2082  */
2083  V8_DEPRECATE_SOON("Use Delegate::GetSharedArrayBufferId",
2084  void TransferSharedArrayBuffer(
2085  uint32_t transfer_id,
2086  Local<SharedArrayBuffer> shared_array_buffer));
2087 
2088  /**
2089  * Indicate whether to treat ArrayBufferView objects as host objects,
2090  * i.e. pass them to Delegate::WriteHostObject. This should not be
2091  * called when no Delegate was passed.
2092  *
2093  * The default is not to treat ArrayBufferViews as host objects.
2094  */
2096 
2097  /**
2098  * Write raw data in various common formats to the buffer.
2099  * Note that integer types are written in base-128 varint format, not with a
2100  * binary copy. For use during an override of Delegate::WriteHostObject.
2101  */
2102  void WriteUint32(uint32_t value);
2103  void WriteUint64(uint64_t value);
2104  void WriteDouble(double value);
2105  void WriteRawBytes(const void* source, size_t length);
2106 
2107  private:
2108  ValueSerializer(const ValueSerializer&) = delete;
2109  void operator=(const ValueSerializer&) = delete;
2110 
2111  struct PrivateData;
2112  PrivateData* private_;
2113 };
2114 
2115 /**
2116  * Deserializes values from data written with ValueSerializer, or a compatible
2117  * implementation.
2118  *
2119  * WARNING: This API is under development, and changes (including incompatible
2120  * changes to the API or wire format) may occur without notice until this
2121  * warning is removed.
2122  */
2124  public:
2126  public:
2127  virtual ~Delegate() {}
2128 
2129  /**
2130  * The embedder overrides this method to read some kind of host object, if
2131  * possible. If not, a suitable exception should be thrown and
2132  * MaybeLocal<Object>() returned.
2133  */
2134  virtual MaybeLocal<Object> ReadHostObject(Isolate* isolate);
2135 
2136  /**
2137  * Get a WasmCompiledModule given a transfer_id previously provided
2138  * by ValueSerializer::GetWasmModuleTransferId
2139  */
2141  Isolate* isolate, uint32_t transfer_id);
2142 
2143  /**
2144  * Get a SharedArrayBuffer given a clone_id previously provided
2145  * by ValueSerializer::GetSharedArrayBufferId
2146  */
2148  Isolate* isolate, uint32_t clone_id);
2149  };
2150 
2151  ValueDeserializer(Isolate* isolate, const uint8_t* data, size_t size);
2152  ValueDeserializer(Isolate* isolate, const uint8_t* data, size_t size,
2153  Delegate* delegate);
2155 
2156  /**
2157  * Reads and validates a header (including the format version).
2158  * May, for example, reject an invalid or unsupported wire format.
2159  */
2160  V8_WARN_UNUSED_RESULT Maybe<bool> ReadHeader(Local<Context> context);
2161 
2162  /**
2163  * Deserializes a JavaScript value from the buffer.
2164  */
2166 
2167  /**
2168  * Accepts the array buffer corresponding to the one passed previously to
2169  * ValueSerializer::TransferArrayBuffer.
2170  */
2171  void TransferArrayBuffer(uint32_t transfer_id,
2172  Local<ArrayBuffer> array_buffer);
2173 
2174  /**
2175  * Similar to TransferArrayBuffer, but for SharedArrayBuffer.
2176  * The id is not necessarily in the same namespace as unshared ArrayBuffer
2177  * objects.
2178  */
2179  void TransferSharedArrayBuffer(uint32_t id,
2180  Local<SharedArrayBuffer> shared_array_buffer);
2181 
2182  /**
2183  * Must be called before ReadHeader to enable support for reading the legacy
2184  * wire format (i.e., which predates this being shipped).
2185  *
2186  * Don't use this unless you need to read data written by previous versions of
2187  * blink::ScriptValueSerializer.
2188  */
2189  void SetSupportsLegacyWireFormat(bool supports_legacy_wire_format);
2190 
2191  /**
2192  * Expect inline wasm in the data stream (rather than in-memory transfer)
2193  */
2194  void SetExpectInlineWasm(bool allow_inline_wasm);
2195 
2196  /**
2197  * Reads the underlying wire format version. Likely mostly to be useful to
2198  * legacy code reading old wire format versions. Must be called after
2199  * ReadHeader.
2200  */
2201  uint32_t GetWireFormatVersion() const;
2202 
2203  /**
2204  * Reads raw data in various common formats to the buffer.
2205  * Note that integer types are read in base-128 varint format, not with a
2206  * binary copy. For use during an override of Delegate::ReadHostObject.
2207  */
2208  V8_WARN_UNUSED_RESULT bool ReadUint32(uint32_t* value);
2209  V8_WARN_UNUSED_RESULT bool ReadUint64(uint64_t* value);
2210  V8_WARN_UNUSED_RESULT bool ReadDouble(double* value);
2211  V8_WARN_UNUSED_RESULT bool ReadRawBytes(size_t length, const void** data);
2212 
2213  private:
2214  ValueDeserializer(const ValueDeserializer&) = delete;
2215  void operator=(const ValueDeserializer&) = delete;
2216 
2217  struct PrivateData;
2218  PrivateData* private_;
2219 };
2220 
2221 
2222 // --- Value ---
2223 
2224 
2225 /**
2226  * The superclass of all JavaScript values and objects.
2227  */
2228 class V8_EXPORT Value : public Data {
2229  public:
2230  /**
2231  * Returns true if this value is the undefined value. See ECMA-262
2232  * 4.3.10.
2233  */
2234  V8_INLINE bool IsUndefined() const;
2235 
2236  /**
2237  * Returns true if this value is the null value. See ECMA-262
2238  * 4.3.11.
2239  */
2240  V8_INLINE bool IsNull() const;
2241 
2242  /**
2243  * Returns true if this value is either the null or the undefined value.
2244  * See ECMA-262
2245  * 4.3.11. and 4.3.12
2246  */
2247  V8_INLINE bool IsNullOrUndefined() const;
2248 
2249  /**
2250  * Returns true if this value is true.
2251  */
2252  bool IsTrue() const;
2253 
2254  /**
2255  * Returns true if this value is false.
2256  */
2257  bool IsFalse() const;
2258 
2259  /**
2260  * Returns true if this value is a symbol or a string.
2261  */
2262  bool IsName() const;
2263 
2264  /**
2265  * Returns true if this value is an instance of the String type.
2266  * See ECMA-262 8.4.
2267  */
2268  V8_INLINE bool IsString() const;
2269 
2270  /**
2271  * Returns true if this value is a symbol.
2272  */
2273  bool IsSymbol() const;
2274 
2275  /**
2276  * Returns true if this value is a function.
2277  */
2278  bool IsFunction() const;
2279 
2280  /**
2281  * Returns true if this value is an array. Note that it will return false for
2282  * an Proxy for an array.
2283  */
2284  bool IsArray() const;
2285 
2286  /**
2287  * Returns true if this value is an object.
2288  */
2289  bool IsObject() const;
2290 
2291  /**
2292  * Returns true if this value is a bigint.
2293  */
2294  bool IsBigInt() const;
2295 
2296  /**
2297  * Returns true if this value is boolean.
2298  */
2299  bool IsBoolean() const;
2300 
2301  /**
2302  * Returns true if this value is a number.
2303  */
2304  bool IsNumber() const;
2305 
2306  /**
2307  * Returns true if this value is external.
2308  */
2309  bool IsExternal() const;
2310 
2311  /**
2312  * Returns true if this value is a 32-bit signed integer.
2313  */
2314  bool IsInt32() const;
2315 
2316  /**
2317  * Returns true if this value is a 32-bit unsigned integer.
2318  */
2319  bool IsUint32() const;
2320 
2321  /**
2322  * Returns true if this value is a Date.
2323  */
2324  bool IsDate() const;
2325 
2326  /**
2327  * Returns true if this value is an Arguments object.
2328  */
2329  bool IsArgumentsObject() const;
2330 
2331  /**
2332  * Returns true if this value is a BigInt object.
2333  */
2334  bool IsBigIntObject() const;
2335 
2336  /**
2337  * Returns true if this value is a Boolean object.
2338  */
2339  bool IsBooleanObject() const;
2340 
2341  /**
2342  * Returns true if this value is a Number object.
2343  */
2344  bool IsNumberObject() const;
2345 
2346  /**
2347  * Returns true if this value is a String object.
2348  */
2349  bool IsStringObject() const;
2350 
2351  /**
2352  * Returns true if this value is a Symbol object.
2353  */
2354  bool IsSymbolObject() const;
2355 
2356  /**
2357  * Returns true if this value is a NativeError.
2358  */
2359  bool IsNativeError() const;
2360 
2361  /**
2362  * Returns true if this value is a RegExp.
2363  */
2364  bool IsRegExp() const;
2365 
2366  /**
2367  * Returns true if this value is an async function.
2368  */
2369  bool IsAsyncFunction() const;
2370 
2371  /**
2372  * Returns true if this value is a Generator function.
2373  */
2374  bool IsGeneratorFunction() const;
2375 
2376  /**
2377  * Returns true if this value is a Generator object (iterator).
2378  */
2379  bool IsGeneratorObject() const;
2380 
2381  /**
2382  * Returns true if this value is a Promise.
2383  */
2384  bool IsPromise() const;
2385 
2386  /**
2387  * Returns true if this value is a Map.
2388  */
2389  bool IsMap() const;
2390 
2391  /**
2392  * Returns true if this value is a Set.
2393  */
2394  bool IsSet() const;
2395 
2396  /**
2397  * Returns true if this value is a Map Iterator.
2398  */
2399  bool IsMapIterator() const;
2400 
2401  /**
2402  * Returns true if this value is a Set Iterator.
2403  */
2404  bool IsSetIterator() const;
2405 
2406  /**
2407  * Returns true if this value is a WeakMap.
2408  */
2409  bool IsWeakMap() const;
2410 
2411  /**
2412  * Returns true if this value is a WeakSet.
2413  */
2414  bool IsWeakSet() const;
2415 
2416  /**
2417  * Returns true if this value is an ArrayBuffer.
2418  */
2419  bool IsArrayBuffer() const;
2420 
2421  /**
2422  * Returns true if this value is an ArrayBufferView.
2423  */
2424  bool IsArrayBufferView() const;
2425 
2426  /**
2427  * Returns true if this value is one of TypedArrays.
2428  */
2429  bool IsTypedArray() const;
2430 
2431  /**
2432  * Returns true if this value is an Uint8Array.
2433  */
2434  bool IsUint8Array() const;
2435 
2436  /**
2437  * Returns true if this value is an Uint8ClampedArray.
2438  */
2439  bool IsUint8ClampedArray() const;
2440 
2441  /**
2442  * Returns true if this value is an Int8Array.
2443  */
2444  bool IsInt8Array() const;
2445 
2446  /**
2447  * Returns true if this value is an Uint16Array.
2448  */
2449  bool IsUint16Array() const;
2450 
2451  /**
2452  * Returns true if this value is an Int16Array.
2453  */
2454  bool IsInt16Array() const;
2455 
2456  /**
2457  * Returns true if this value is an Uint32Array.
2458  */
2459  bool IsUint32Array() const;
2460 
2461  /**
2462  * Returns true if this value is an Int32Array.
2463  */
2464  bool IsInt32Array() const;
2465 
2466  /**
2467  * Returns true if this value is a Float32Array.
2468  */
2469  bool IsFloat32Array() const;
2470 
2471  /**
2472  * Returns true if this value is a Float64Array.
2473  */
2474  bool IsFloat64Array() const;
2475 
2476  /**
2477  * Returns true if this value is a BigInt64Array.
2478  */
2479  bool IsBigInt64Array() const;
2480 
2481  /**
2482  * Returns true if this value is a BigUint64Array.
2483  */
2484  bool IsBigUint64Array() const;
2485 
2486  /**
2487  * Returns true if this value is a DataView.
2488  */
2489  bool IsDataView() const;
2490 
2491  /**
2492  * Returns true if this value is a SharedArrayBuffer.
2493  * This is an experimental feature.
2494  */
2495  bool IsSharedArrayBuffer() const;
2496 
2497  /**
2498  * Returns true if this value is a JavaScript Proxy.
2499  */
2500  bool IsProxy() const;
2501 
2503 
2504  /**
2505  * Returns true if the value is a Module Namespace Object.
2506  */
2508 
2510  Local<Context> context) const;
2512  Local<Context> context) const;
2514  Local<Context> context) const;
2516  Local<Context> context) const;
2518  Local<Context> context) const;
2520  Local<Context> context) const;
2522  Local<Context> context) const;
2524  Local<Context> context) const;
2526 
2527  V8_DEPRECATE_SOON("Use maybe version",
2528  Local<Boolean> ToBoolean(Isolate* isolate) const);
2529  V8_DEPRECATE_SOON("Use maybe version",
2530  Local<Number> ToNumber(Isolate* isolate) const);
2531  V8_DEPRECATE_SOON("Use maybe version",
2532  Local<String> ToString(Isolate* isolate) const);
2533  V8_DEPRECATE_SOON("Use maybe version",
2534  Local<Object> ToObject(Isolate* isolate) const);
2535  V8_DEPRECATE_SOON("Use maybe version",
2536  Local<Integer> ToInteger(Isolate* isolate) const);
2537  V8_DEPRECATE_SOON("Use maybe version",
2538  Local<Int32> ToInt32(Isolate* isolate) const);
2539 
2540  /**
2541  * Attempts to convert a string to an array index.
2542  * Returns an empty handle if the conversion fails.
2543  */
2545  Local<Context> context) const;
2546 
2547  V8_WARN_UNUSED_RESULT Maybe<bool> BooleanValue(Local<Context> context) const;
2548  V8_WARN_UNUSED_RESULT Maybe<double> NumberValue(Local<Context> context) const;
2550  Local<Context> context) const;
2552  Local<Context> context) const;
2553  V8_WARN_UNUSED_RESULT Maybe<int32_t> Int32Value(Local<Context> context) const;
2554 
2555  /** JS == */
2556  V8_WARN_UNUSED_RESULT Maybe<bool> Equals(Local<Context> context,
2557  Local<Value> that) const;
2558  bool StrictEquals(Local<Value> that) const;
2559  bool SameValue(Local<Value> that) const;
2560 
2561  template <class T> V8_INLINE static Value* Cast(T* value);
2562 
2563  Local<String> TypeOf(Isolate*);
2564 
2565  Maybe<bool> InstanceOf(Local<Context> context, Local<Object> object);
2566 
2567  private:
2568  V8_INLINE bool QuickIsUndefined() const;
2569  V8_INLINE bool QuickIsNull() const;
2570  V8_INLINE bool QuickIsNullOrUndefined() const;
2571  V8_INLINE bool QuickIsString() const;
2572  bool FullIsUndefined() const;
2573  bool FullIsNull() const;
2574  bool FullIsString() const;
2575 };
2576 
2577 
2578 /**
2579  * The superclass of primitive values. See ECMA-262 4.3.2.
2580  */
2581 class V8_EXPORT Primitive : public Value { };
2582 
2583 
2584 /**
2585  * A primitive boolean value (ECMA-262, 4.3.14). Either the true
2586  * or false value.
2587  */
2588 class V8_EXPORT Boolean : public Primitive {
2589  public:
2590  bool Value() const;
2591  V8_INLINE static Boolean* Cast(v8::Value* obj);
2592  V8_INLINE static Local<Boolean> New(Isolate* isolate, bool value);
2593 
2594  private:
2595  static void CheckCast(v8::Value* obj);
2596 };
2597 
2598 
2599 /**
2600  * A superclass for symbols and strings.
2601  */
2602 class V8_EXPORT Name : public Primitive {
2603  public:
2604  /**
2605  * Returns the identity hash for this object. The current implementation
2606  * uses an inline property on the object to store the identity hash.
2607  *
2608  * The return value will never be 0. Also, it is not guaranteed to be
2609  * unique.
2610  */
2612 
2613  V8_INLINE static Name* Cast(Value* obj);
2614 
2615  private:
2616  static void CheckCast(Value* obj);
2617 };
2618 
2619 /**
2620  * A flag describing different modes of string creation.
2621  *
2622  * Aside from performance implications there are no differences between the two
2623  * creation modes.
2624  */
2625 enum class NewStringType {
2626  /**
2627  * Create a new string, always allocating new storage memory.
2628  */
2629  kNormal,
2630 
2631  /**
2632  * Acts as a hint that the string should be created in the
2633  * old generation heap space and be deduplicated if an identical string
2634  * already exists.
2635  */
2637 };
2638 
2639 /**
2640  * A JavaScript string value (ECMA-262, 4.3.17).
2641  */
2642 class V8_EXPORT String : public Name {
2643  public:
2644  static constexpr int kMaxLength = internal::kApiPointerSize == 4
2645  ? (1 << 28) - 16
2646  : internal::kSmiMaxValue / 2 - 24;
2647 
2648  enum Encoding {
2651  ONE_BYTE_ENCODING = 0x8
2652  };
2653  /**
2654  * Returns the number of characters (UTF-16 code units) in this string.
2655  */
2656  int Length() const;
2657 
2658  /**
2659  * Returns the number of bytes in the UTF-8 encoded
2660  * representation of this string.
2661  */
2662  int Utf8Length(Isolate* isolate) const;
2663 
2664  /**
2665  * Returns whether this string is known to contain only one byte data,
2666  * i.e. ISO-8859-1 code points.
2667  * Does not read the string.
2668  * False negatives are possible.
2669  */
2670  bool IsOneByte() const;
2671 
2672  /**
2673  * Returns whether this string contain only one byte data,
2674  * i.e. ISO-8859-1 code points.
2675  * Will read the entire string in some cases.
2676  */
2677  bool ContainsOnlyOneByte() const;
2678 
2679  /**
2680  * Write the contents of the string to an external buffer.
2681  * If no arguments are given, expects the buffer to be large
2682  * enough to hold the entire string and NULL terminator. Copies
2683  * the contents of the string and the NULL terminator into the
2684  * buffer.
2685  *
2686  * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
2687  * before the end of the buffer.
2688  *
2689  * Copies up to length characters into the output buffer.
2690  * Only null-terminates if there is enough space in the buffer.
2691  *
2692  * \param buffer The buffer into which the string will be copied.
2693  * \param start The starting position within the string at which
2694  * copying begins.
2695  * \param length The number of characters to copy from the string. For
2696  * WriteUtf8 the number of bytes in the buffer.
2697  * \param nchars_ref The number of characters written, can be NULL.
2698  * \param options Various options that might affect performance of this or
2699  * subsequent operations.
2700  * \return The number of characters copied to the buffer excluding the null
2701  * terminator. For WriteUtf8: The number of bytes copied to the buffer
2702  * including the null terminator (if written).
2703  */
2709  // Used by WriteUtf8 to replace orphan surrogate code units with the
2710  // unicode replacement character. Needs to be set to guarantee valid UTF-8
2711  // output.
2713  };
2714 
2715  // 16-bit character codes.
2716  int Write(Isolate* isolate, uint16_t* buffer, int start = 0, int length = -1,
2717  int options = NO_OPTIONS) const;
2718  // One byte characters.
2719  int WriteOneByte(Isolate* isolate, uint8_t* buffer, int start = 0,
2720  int length = -1, int options = NO_OPTIONS) const;
2721  // UTF-8 encoded characters.
2722  int WriteUtf8(Isolate* isolate, char* buffer, int length = -1,
2723  int* nchars_ref = NULL, int options = NO_OPTIONS) const;
2724 
2725  /**
2726  * A zero length string.
2727  */
2728  V8_INLINE static Local<String> Empty(Isolate* isolate);
2729 
2730  /**
2731  * Returns true if the string is external
2732  */
2733  bool IsExternal() const;
2734 
2735  /**
2736  * Returns true if the string is both external and one-byte.
2737  */
2738  bool IsExternalOneByte() const;
2739 
2741  public:
2743 
2744  virtual bool IsCompressible() const { return false; }
2745 
2746  protected:
2748 
2749  /**
2750  * Internally V8 will call this Dispose method when the external string
2751  * resource is no longer needed. The default implementation will use the
2752  * delete operator. This method can be overridden in subclasses to
2753  * control how allocated external string resources are disposed.
2754  */
2755  virtual void Dispose() { delete this; }
2756 
2757  // Disallow copying and assigning.
2759  void operator=(const ExternalStringResourceBase&) = delete;
2760 
2761  private:
2762  friend class internal::Heap;
2763  friend class v8::String;
2764  };
2765 
2766  /**
2767  * An ExternalStringResource is a wrapper around a two-byte string
2768  * buffer that resides outside V8's heap. Implement an
2769  * ExternalStringResource to manage the life cycle of the underlying
2770  * buffer. Note that the string data must be immutable.
2771  */
2773  : public ExternalStringResourceBase {
2774  public:
2775  /**
2776  * Override the destructor to manage the life cycle of the underlying
2777  * buffer.
2778  */
2780 
2781  /**
2782  * The string data from the underlying buffer.
2783  */
2784  virtual const uint16_t* data() const = 0;
2785 
2786  /**
2787  * The length of the string. That is, the number of two-byte characters.
2788  */
2789  virtual size_t length() const = 0;
2790 
2791  protected:
2793  };
2794 
2795  /**
2796  * An ExternalOneByteStringResource is a wrapper around an one-byte
2797  * string buffer that resides outside V8's heap. Implement an
2798  * ExternalOneByteStringResource to manage the life cycle of the
2799  * underlying buffer. Note that the string data must be immutable
2800  * and that the data must be Latin-1 and not UTF-8, which would require
2801  * special treatment internally in the engine and do not allow efficient
2802  * indexing. Use String::New or convert to 16 bit data for non-Latin1.
2803  */
2804 
2806  : public ExternalStringResourceBase {
2807  public:
2808  /**
2809  * Override the destructor to manage the life cycle of the underlying
2810  * buffer.
2811  */
2813  /** The string data from the underlying buffer.*/
2814  virtual const char* data() const = 0;
2815  /** The number of Latin-1 characters in the string.*/
2816  virtual size_t length() const = 0;
2817  protected:
2819  };
2820 
2821  /**
2822  * If the string is an external string, return the ExternalStringResourceBase
2823  * regardless of the encoding, otherwise return NULL. The encoding of the
2824  * string is returned in encoding_out.
2825  */
2827  Encoding* encoding_out) const;
2828 
2829  /**
2830  * Get the ExternalStringResource for an external string. Returns
2831  * NULL if IsExternal() doesn't return true.
2832  */
2834 
2835  /**
2836  * Get the ExternalOneByteStringResource for an external one-byte string.
2837  * Returns NULL if IsExternalOneByte() doesn't return true.
2838  */
2840 
2841  V8_INLINE static String* Cast(v8::Value* obj);
2842 
2843  // TODO(dcarney): remove with deprecation of New functions.
2847  };
2848 
2849  /** Allocates a new string from UTF-8 data.*/
2851  "Use maybe version",
2852  Local<String> NewFromUtf8(Isolate* isolate, const char* data,
2854  int length = -1));
2855 
2856  /** Allocates a new string from UTF-8 data. Only returns an empty value when
2857  * length > kMaxLength. **/
2859  Isolate* isolate, const char* data, v8::NewStringType type,
2860  int length = -1);
2861 
2862  /** Allocates a new string from Latin-1 data. Only returns an empty value
2863  * when length > kMaxLength. **/
2865  Isolate* isolate, const uint8_t* data, v8::NewStringType type,
2866  int length = -1);
2867 
2868  /** Allocates a new string from UTF-16 data.*/
2870  "Use maybe version",
2871  Local<String> NewFromTwoByte(Isolate* isolate, const uint16_t* data,
2873  int length = -1));
2874 
2875  /** Allocates a new string from UTF-16 data. Only returns an empty value when
2876  * length > kMaxLength. **/
2878  Isolate* isolate, const uint16_t* data, v8::NewStringType type,
2879  int length = -1);
2880 
2881  /**
2882  * Creates a new string by concatenating the left and the right strings
2883  * passed in as parameters.
2884  */
2885  static Local<String> Concat(Isolate* isolate, Local<String> left,
2886  Local<String> right);
2887 
2888  /**
2889  * Creates a new external string using the data defined in the given
2890  * resource. When the external string is no longer live on V8's heap the
2891  * resource will be disposed by calling its Dispose method. The caller of
2892  * this function should not otherwise delete or modify the resource. Neither
2893  * should the underlying buffer be deallocated or modified except through the
2894  * destructor of the external string resource.
2895  */
2897  Isolate* isolate, ExternalStringResource* resource);
2898 
2899  /**
2900  * Associate an external string resource with this string by transforming it
2901  * in place so that existing references to this string in the JavaScript heap
2902  * will use the external string resource. The external string resource's
2903  * character contents need to be equivalent to this string.
2904  * Returns true if the string has been changed to be an external string.
2905  * The string is not modified if the operation fails. See NewExternal for
2906  * information on the lifetime of the resource.
2907  */
2909 
2910  /**
2911  * Creates a new external string using the one-byte data defined in the given
2912  * resource. When the external string is no longer live on V8's heap the
2913  * resource will be disposed by calling its Dispose method. The caller of
2914  * this function should not otherwise delete or modify the resource. Neither
2915  * should the underlying buffer be deallocated or modified except through the
2916  * destructor of the external string resource.
2917  */
2919  "Use maybe version",
2920  Local<String> NewExternal(Isolate* isolate,
2921  ExternalOneByteStringResource* resource));
2923  Isolate* isolate, ExternalOneByteStringResource* resource);
2924 
2925  /**
2926  * Associate an external string resource with this string by transforming it
2927  * in place so that existing references to this string in the JavaScript heap
2928  * will use the external string resource. The external string resource's
2929  * character contents need to be equivalent to this string.
2930  * Returns true if the string has been changed to be an external string.
2931  * The string is not modified if the operation fails. See NewExternal for
2932  * information on the lifetime of the resource.
2933  */
2935 
2936  /**
2937  * Returns true if this string can be made external.
2938  */
2940 
2941  /**
2942  * Returns true if the strings values are equal. Same as JS ==/===.
2943  */
2945 
2946  /**
2947  * Converts an object to a UTF-8-encoded character array. Useful if
2948  * you want to print the object. If conversion to a string fails
2949  * (e.g. due to an exception in the toString() method of the object)
2950  * then the length() method returns 0 and the * operator returns
2951  * NULL.
2952  */
2954  public:
2955  Utf8Value(Isolate* isolate, Local<v8::Value> obj);
2957  char* operator*() { return str_; }
2958  const char* operator*() const { return str_; }
2959  int length() const { return length_; }
2960 
2961  // Disallow copying and assigning.
2962  Utf8Value(const Utf8Value&) = delete;
2963  void operator=(const Utf8Value&) = delete;
2964 
2965  private:
2966  char* str_;
2967  int length_;
2968  };
2969 
2970  /**
2971  * Converts an object to a two-byte (UTF-16-encoded) string.
2972  * If conversion to a string fails (eg. due to an exception in the toString()
2973  * method of the object) then the length() method returns 0 and the * operator
2974  * returns NULL.
2975  */
2977  public:
2978  Value(Isolate* isolate, Local<v8::Value> obj);
2979  ~Value();
2980  uint16_t* operator*() { return str_; }
2981  const uint16_t* operator*() const { return str_; }
2982  int length() const { return length_; }
2983 
2984  // Disallow copying and assigning.
2985  Value(const Value&) = delete;
2986  void operator=(const Value&) = delete;
2987 
2988  private:
2989  uint16_t* str_;
2990  int length_;
2991  };
2992 
2993  private:
2994  void VerifyExternalStringResourceBase(ExternalStringResourceBase* v,
2995  Encoding encoding) const;
2996  void VerifyExternalStringResource(ExternalStringResource* val) const;
2997  ExternalStringResource* GetExternalStringResourceSlow() const;
2998  ExternalStringResourceBase* GetExternalStringResourceBaseSlow(
2999  String::Encoding* encoding_out) const;
3000  const ExternalOneByteStringResource* GetExternalOneByteStringResourceSlow()
3001  const;
3002 
3003  static void CheckCast(v8::Value* obj);
3004 };
3005 
3006 
3007 /**
3008  * A JavaScript symbol (ECMA-262 edition 6)
3009  */
3010 class V8_EXPORT Symbol : public Name {
3011  public:
3012  /**
3013  * Returns the print name string of the symbol, or undefined if none.
3014  */
3015  Local<Value> Name() const;
3016 
3017  /**
3018  * Create a symbol. If name is not empty, it will be used as the description.
3019  */
3020  static Local<Symbol> New(Isolate* isolate,
3021  Local<String> name = Local<String>());
3022 
3023  /**
3024  * Access global symbol registry.
3025  * Note that symbols created this way are never collected, so
3026  * they should only be used for statically fixed properties.
3027  * Also, there is only one global name space for the names used as keys.
3028  * To minimize the potential for clashes, use qualified names as keys.
3029  */
3030  static Local<Symbol> For(Isolate *isolate, Local<String> name);
3031 
3032  /**
3033  * Retrieve a global symbol. Similar to |For|, but using a separate
3034  * registry that is not accessible by (and cannot clash with) JavaScript code.
3035  */
3036  static Local<Symbol> ForApi(Isolate *isolate, Local<String> name);
3037 
3038  // Well-known symbols
3039  static Local<Symbol> GetHasInstance(Isolate* isolate);
3040  static Local<Symbol> GetIsConcatSpreadable(Isolate* isolate);
3041  static Local<Symbol> GetIterator(Isolate* isolate);
3042  static Local<Symbol> GetMatch(Isolate* isolate);
3043  static Local<Symbol> GetReplace(Isolate* isolate);
3044  static Local<Symbol> GetSearch(Isolate* isolate);
3045  static Local<Symbol> GetSplit(Isolate* isolate);
3046  static Local<Symbol> GetToPrimitive(Isolate* isolate);
3047  static Local<Symbol> GetToStringTag(Isolate* isolate);
3048  static Local<Symbol> GetUnscopables(Isolate* isolate);
3049 
3050  V8_INLINE static Symbol* Cast(Value* obj);
3051 
3052  private:
3053  Symbol();
3054  static void CheckCast(Value* obj);
3055 };
3056 
3057 
3058 /**
3059  * A private symbol
3060  *
3061  * This is an experimental feature. Use at your own risk.
3062  */
3063 class V8_EXPORT Private : public Data {
3064  public:
3065  /**
3066  * Returns the print name string of the private symbol, or undefined if none.
3067  */
3068  Local<Value> Name() const;
3069 
3070  /**
3071  * Create a private symbol. If name is not empty, it will be the description.
3072  */
3073  static Local<Private> New(Isolate* isolate,
3074  Local<String> name = Local<String>());
3075 
3076  /**
3077  * Retrieve a global private symbol. If a symbol with this name has not
3078  * been retrieved in the same isolate before, it is created.
3079  * Note that private symbols created this way are never collected, so
3080  * they should only be used for statically fixed properties.
3081  * Also, there is only one global name space for the names used as keys.
3082  * To minimize the potential for clashes, use qualified names as keys,
3083  * e.g., "Class#property".
3084  */
3085  static Local<Private> ForApi(Isolate* isolate, Local<String> name);
3086 
3087  V8_INLINE static Private* Cast(Data* data);
3088 
3089  private:
3090  Private();
3091 
3092  static void CheckCast(Data* that);
3093 };
3094 
3095 
3096 /**
3097  * A JavaScript number value (ECMA-262, 4.3.20)
3098  */
3099 class V8_EXPORT Number : public Primitive {
3100  public:
3101  double Value() const;
3102  static Local<Number> New(Isolate* isolate, double value);
3103  V8_INLINE static Number* Cast(v8::Value* obj);
3104  private:
3105  Number();
3106  static void CheckCast(v8::Value* obj);
3107 };
3108 
3109 
3110 /**
3111  * A JavaScript value representing a signed integer.
3112  */
3113 class V8_EXPORT Integer : public Number {
3114  public:
3115  static Local<Integer> New(Isolate* isolate, int32_t value);
3116  static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value);
3117  int64_t Value() const;
3118  V8_INLINE static Integer* Cast(v8::Value* obj);
3119  private:
3120  Integer();
3121  static void CheckCast(v8::Value* obj);
3122 };
3123 
3124 
3125 /**
3126  * A JavaScript value representing a 32-bit signed integer.
3127  */
3128 class V8_EXPORT Int32 : public Integer {
3129  public:
3130  int32_t Value() const;
3131  V8_INLINE static Int32* Cast(v8::Value* obj);
3132 
3133  private:
3134  Int32();
3135  static void CheckCast(v8::Value* obj);
3136 };
3137 
3138 
3139 /**
3140  * A JavaScript value representing a 32-bit unsigned integer.
3141  */
3142 class V8_EXPORT Uint32 : public Integer {
3143  public:
3144  uint32_t Value() const;
3145  V8_INLINE static Uint32* Cast(v8::Value* obj);
3146 
3147  private:
3148  Uint32();
3149  static void CheckCast(v8::Value* obj);
3150 };
3151 
3152 /**
3153  * A JavaScript BigInt value (https://tc39.github.io/proposal-bigint)
3154  */
3155 class V8_EXPORT BigInt : public Primitive {
3156  public:
3157  static Local<BigInt> New(Isolate* isolate, int64_t value);
3158  static Local<BigInt> NewFromUnsigned(Isolate* isolate, uint64_t value);
3159  /**
3160  * Creates a new BigInt object using a specified sign bit and a
3161  * specified list of digits/words.
3162  * The resulting number is calculated as:
3163  *
3164  * (-1)^sign_bit * (words[0] * (2^64)^0 + words[1] * (2^64)^1 + ...)
3165  */
3166  static MaybeLocal<BigInt> NewFromWords(Local<Context> context, int sign_bit,
3167  int word_count, const uint64_t* words);
3168 
3169  /**
3170  * Returns the value of this BigInt as an unsigned 64-bit integer.
3171  * If `lossless` is provided, it will reflect whether the return value was
3172  * truncated or wrapped around. In particular, it is set to `false` if this
3173  * BigInt is negative.
3174  */
3175  uint64_t Uint64Value(bool* lossless = nullptr) const;
3176 
3177  /**
3178  * Returns the value of this BigInt as a signed 64-bit integer.
3179  * If `lossless` is provided, it will reflect whether this BigInt was
3180  * truncated or not.
3181  */
3182  int64_t Int64Value(bool* lossless = nullptr) const;
3183 
3184  /**
3185  * Returns the number of 64-bit words needed to store the result of
3186  * ToWordsArray().
3187  */
3188  int WordCount() const;
3189 
3190  /**
3191  * Writes the contents of this BigInt to a specified memory location.
3192  * `sign_bit` must be provided and will be set to 1 if this BigInt is
3193  * negative.
3194  * `*word_count` has to be initialized to the length of the `words` array.
3195  * Upon return, it will be set to the actual number of words that would
3196  * be needed to store this BigInt (i.e. the return value of `WordCount()`).
3197  */
3198  void ToWordsArray(int* sign_bit, int* word_count, uint64_t* words) const;
3199 
3200  V8_INLINE static BigInt* Cast(v8::Value* obj);
3201 
3202  private:
3203  BigInt();
3204  static void CheckCast(v8::Value* obj);
3205 };
3206 
3207 /**
3208  * PropertyAttribute.
3209  */
3211  /** None. **/
3212  None = 0,
3213  /** ReadOnly, i.e., not writable. **/
3214  ReadOnly = 1 << 0,
3215  /** DontEnum, i.e., not enumerable. **/
3216  DontEnum = 1 << 1,
3217  /** DontDelete, i.e., not configurable. **/
3218  DontDelete = 1 << 2
3219 };
3220 
3221 /**
3222  * Accessor[Getter|Setter] are used as callback functions when
3223  * setting|getting a particular property. See Object and ObjectTemplate's
3224  * method SetAccessor.
3225  */
3226 typedef void (*AccessorGetterCallback)(
3227  Local<String> property,
3228  const PropertyCallbackInfo<Value>& info);
3230  Local<Name> property,
3231  const PropertyCallbackInfo<Value>& info);
3232 
3233 
3234 typedef void (*AccessorSetterCallback)(
3235  Local<String> property,
3236  Local<Value> value,
3237  const PropertyCallbackInfo<void>& info);
3239  Local<Name> property,
3240  Local<Value> value,
3241  const PropertyCallbackInfo<void>& info);
3242 
3243 
3244 /**
3245  * Access control specifications.
3246  *
3247  * Some accessors should be accessible across contexts. These
3248  * accessors have an explicit access control parameter which specifies
3249  * the kind of cross-context access that should be allowed.
3250  *
3251  * TODO(dcarney): Remove PROHIBITS_OVERWRITING as it is now unused.
3252  */
3254  DEFAULT = 0,
3256  ALL_CAN_WRITE = 1 << 1,
3257  PROHIBITS_OVERWRITING = 1 << 2
3258 };
3259 
3260 /**
3261  * Property filter bits. They can be or'ed to build a composite filter.
3262  */
3269  SKIP_SYMBOLS = 16
3270 };
3271 
3272 /**
3273  * Options for marking whether callbacks may trigger JS-observable side effects.
3274  * Side-effect-free callbacks are whitelisted during debug evaluation with
3275  * throwOnSideEffect. It applies when calling a Function, FunctionTemplate,
3276  * or an Accessor's getter callback. For Interceptors, please see
3277  * PropertyHandlerFlags's kHasNoSideEffect.
3278  */
3280 
3281 /**
3282  * Keys/Properties filter enums:
3283  *
3284  * KeyCollectionMode limits the range of collected properties. kOwnOnly limits
3285  * the collected properties to the given Object only. kIncludesPrototypes will
3286  * include all keys of the objects's prototype chain as well.
3287  */
3289 
3290 /**
3291  * kIncludesIndices allows for integer indices to be collected, while
3292  * kSkipIndices will exclude integer indices from being collected.
3293  */
3295 
3296 /**
3297  * kConvertToString will convert integer indices to strings.
3298  * kKeepNumbers will return numbers for integer indices.
3299  */
3301 
3302 /**
3303  * Integrity level for objects.
3304  */
3306 
3307 /**
3308  * A JavaScript object (ECMA-262, 4.3.3)
3309  */
3310 class V8_EXPORT Object : public Value {
3311  public:
3312  V8_DEPRECATE_SOON("Use maybe version",
3313  bool Set(Local<Value> key, Local<Value> value));
3314  V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context,
3315  Local<Value> key, Local<Value> value);
3316 
3317  V8_DEPRECATE_SOON("Use maybe version",
3318  bool Set(uint32_t index, Local<Value> value));
3319  V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context, uint32_t index,
3320  Local<Value> value);
3321 
3322  // Implements CreateDataProperty (ECMA-262, 7.3.4).
3323  //
3324  // Defines a configurable, writable, enumerable property with the given value
3325  // on the object unless the property already exists and is not configurable
3326  // or the object is not extensible.
3327  //
3328  // Returns true on success.
3329  V8_WARN_UNUSED_RESULT Maybe<bool> CreateDataProperty(Local<Context> context,
3330  Local<Name> key,
3331  Local<Value> value);
3332  V8_WARN_UNUSED_RESULT Maybe<bool> CreateDataProperty(Local<Context> context,
3333  uint32_t index,
3334  Local<Value> value);
3335 
3336  // Implements DefineOwnProperty.
3337  //
3338  // In general, CreateDataProperty will be faster, however, does not allow
3339  // for specifying attributes.
3340  //
3341  // Returns true on success.
3343  Local<Context> context, Local<Name> key, Local<Value> value,
3344  PropertyAttribute attributes = None);
3345 
3346  // Implements Object.DefineProperty(O, P, Attributes), see Ecma-262 19.1.2.4.
3347  //
3348  // The defineProperty function is used to add an own property or
3349  // update the attributes of an existing own property of an object.
3350  //
3351  // Both data and accessor descriptors can be used.
3352  //
3353  // In general, CreateDataProperty is faster, however, does not allow
3354  // for specifying attributes or an accessor descriptor.
3355  //
3356  // The PropertyDescriptor can change when redefining a property.
3357  //
3358  // Returns true on success.
3360  Local<Context> context, Local<Name> key, PropertyDescriptor& descriptor);
3361 
3362  V8_DEPRECATE_SOON("Use maybe version", Local<Value> Get(Local<Value> key));
3364  Local<Value> key);
3365 
3366  V8_DEPRECATE_SOON("Use maybe version", Local<Value> Get(uint32_t index));
3368  uint32_t index);
3369 
3370  /**
3371  * Gets the property attributes of a property which can be None or
3372  * any combination of ReadOnly, DontEnum and DontDelete. Returns
3373  * None when the property doesn't exist.
3374  */
3376  Local<Context> context, Local<Value> key);
3377 
3378  /**
3379  * Returns Object.getOwnPropertyDescriptor as per ES2016 section 19.1.2.6.
3380  */
3382  Local<Context> context, Local<Name> key);
3383 
3384  V8_DEPRECATE_SOON("Use maybe version", bool Has(Local<Value> key));
3385  /**
3386  * Object::Has() calls the abstract operation HasProperty(O, P) described
3387  * in ECMA-262, 7.3.10. Has() returns
3388  * true, if the object has the property, either own or on the prototype chain.
3389  * Interceptors, i.e., PropertyQueryCallbacks, are called if present.
3390  *
3391  * Has() has the same side effects as JavaScript's `variable in object`.
3392  * For example, calling Has() on a revoked proxy will throw an exception.
3393  *
3394  * \note Has() converts the key to a name, which possibly calls back into
3395  * JavaScript.
3396  *
3397  * See also v8::Object::HasOwnProperty() and
3398  * v8::Object::HasRealNamedProperty().
3399  */
3400  V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
3401  Local<Value> key);
3402 
3403  V8_DEPRECATE_SOON("Use maybe version", bool Delete(Local<Value> key));
3404  V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
3405  Local<Value> key);
3406 
3407  V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context, uint32_t index);
3408 
3409  V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
3410  uint32_t index);
3411 
3412  /**
3413  * Note: SideEffectType affects the getter only, not the setter.
3414  */
3416  Local<Context> context, Local<Name> name,
3419  AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
3420  SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect);
3421 
3423  Local<Function> setter = Local<Function>(),
3424  PropertyAttribute attribute = None,
3425  AccessControl settings = DEFAULT);
3426 
3427  /**
3428  * Sets a native data property like Template::SetNativeDataProperty, but
3429  * this method sets on this object directly.
3430  */
3432  Local<Context> context, Local<Name> name,
3434  AccessorNameSetterCallback setter = nullptr,
3435  Local<Value> data = Local<Value>(), PropertyAttribute attributes = None,
3436  SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect);
3437 
3438  /**
3439  * Attempts to create a property with the given name which behaves like a data
3440  * property, except that the provided getter is invoked (and provided with the
3441  * data value) to supply its value the first time it is read. After the
3442  * property is accessed once, it is replaced with an ordinary data property.
3443  *
3444  * Analogous to Template::SetLazyDataProperty.
3445  */
3447  Local<Context> context, Local<Name> name,
3449  PropertyAttribute attributes = None,
3450  SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect);
3451 
3452  /**
3453  * Functionality for private properties.
3454  * This is an experimental feature, use at your own risk.
3455  * Note: Private properties are not inherited. Do not rely on this, since it
3456  * may change.
3457  */
3458  Maybe<bool> HasPrivate(Local<Context> context, Local<Private> key);
3459  Maybe<bool> SetPrivate(Local<Context> context, Local<Private> key,
3460  Local<Value> value);
3461  Maybe<bool> DeletePrivate(Local<Context> context, Local<Private> key);
3462  MaybeLocal<Value> GetPrivate(Local<Context> context, Local<Private> key);
3463 
3464  /**
3465  * Returns an array containing the names of the enumerable properties
3466  * of this object, including properties from prototype objects. The
3467  * array returned by this method contains the same values as would
3468  * be enumerated by a for-in statement over this object.
3469  */
3470  V8_DEPRECATE_SOON("Use maybe version", Local<Array> GetPropertyNames());
3472  Local<Context> context);
3474  Local<Context> context, KeyCollectionMode mode,
3475  PropertyFilter property_filter, IndexFilter index_filter,
3477 
3478  /**
3479  * This function has the same functionality as GetPropertyNames but
3480  * the returned array doesn't contain the names of properties from
3481  * prototype objects.
3482  */
3483  V8_DEPRECATE_SOON("Use maybe version", Local<Array> GetOwnPropertyNames());
3485  Local<Context> context);
3486 
3487  /**
3488  * Returns an array containing the names of the filtered properties
3489  * of this object, including properties from prototype objects. The
3490  * array returned by this method contains the same values as would
3491  * be enumerated by a for-in statement over this object.
3492  */
3494  Local<Context> context, PropertyFilter filter,
3496 
3497  /**
3498  * Get the prototype object. This does not skip objects marked to
3499  * be skipped by __proto__ and it does not consult the security
3500  * handler.
3501  */
3503 
3504  /**
3505  * Set the prototype object. This does not skip objects marked to
3506  * be skipped by __proto__ and it does not consult the security
3507  * handler.
3508  */
3509  V8_WARN_UNUSED_RESULT Maybe<bool> SetPrototype(Local<Context> context,
3510  Local<Value> prototype);
3511 
3512  /**
3513  * Finds an instance of the given function template in the prototype
3514  * chain.
3515  */
3517 
3518  /**
3519  * Call builtin Object.prototype.toString on this object.
3520  * This is different from Value::ToString() that may call
3521  * user-defined toString function. This one does not.
3522  */
3524  Local<Context> context);
3525 
3526  /**
3527  * Returns the name of the function invoked as a constructor for this object.
3528  */
3530 
3531  /**
3532  * Sets the integrity level of the object.
3533  */
3534  Maybe<bool> SetIntegrityLevel(Local<Context> context, IntegrityLevel level);
3535 
3536  /** Gets the number of internal fields for this Object. */
3538 
3539  /** Same as above, but works for Persistents */
3541  const PersistentBase<Object>& object) {
3542  return object.val_->InternalFieldCount();
3543  }
3544 
3545  /** Gets the value from an internal field. */
3546  V8_INLINE Local<Value> GetInternalField(int index);
3547 
3548  /** Sets the value in an internal field. */
3549  void SetInternalField(int index, Local<Value> value);
3550 
3551  /**
3552  * Gets a 2-byte-aligned native pointer from an internal field. This field
3553  * must have been set by SetAlignedPointerInInternalField, everything else
3554  * leads to undefined behavior.
3555  */
3557 
3558  /** Same as above, but works for Persistents */
3560  const PersistentBase<Object>& object, int index) {
3561  return object.val_->GetAlignedPointerFromInternalField(index);
3562  }
3563 
3564  /**
3565  * Sets a 2-byte-aligned native pointer in an internal field. To retrieve such
3566  * a field, GetAlignedPointerFromInternalField must be used, everything else
3567  * leads to undefined behavior.
3568  */
3569  void SetAlignedPointerInInternalField(int index, void* value);
3570  void SetAlignedPointerInInternalFields(int argc, int indices[],
3571  void* values[]);
3572 
3573  /**
3574  * HasOwnProperty() is like JavaScript's Object.prototype.hasOwnProperty().
3575  *
3576  * See also v8::Object::Has() and v8::Object::HasRealNamedProperty().
3577  */
3578  V8_WARN_UNUSED_RESULT Maybe<bool> HasOwnProperty(Local<Context> context,
3579  Local<Name> key);
3580  V8_WARN_UNUSED_RESULT Maybe<bool> HasOwnProperty(Local<Context> context,
3581  uint32_t index);
3582  V8_DEPRECATE_SOON("Use maybe version",
3583  bool HasRealNamedProperty(Local<String> key));
3584  /**
3585  * Use HasRealNamedProperty() if you want to check if an object has an own
3586  * property without causing side effects, i.e., without calling interceptors.
3587  *
3588  * This function is similar to v8::Object::HasOwnProperty(), but it does not
3589  * call interceptors.
3590  *
3591  * \note Consider using non-masking interceptors, i.e., the interceptors are
3592  * not called if the receiver has the real named property. See
3593  * `v8::PropertyHandlerFlags::kNonMasking`.
3594  *
3595  * See also v8::Object::Has().
3596  */
3597  V8_WARN_UNUSED_RESULT Maybe<bool> HasRealNamedProperty(Local<Context> context,
3598  Local<Name> key);
3599  V8_DEPRECATE_SOON("Use maybe version",
3600  bool HasRealIndexedProperty(uint32_t index));
3602  Local<Context> context, uint32_t index);
3603  V8_DEPRECATE_SOON("Use maybe version",
3604  bool HasRealNamedCallbackProperty(Local<String> key));
3606  Local<Context> context, Local<Name> key);
3607 
3608  /**
3609  * If result.IsEmpty() no real property was located in the prototype chain.
3610  * This means interceptors in the prototype chain are not called.
3611  */
3613  Local<Context> context, Local<Name> key);
3614 
3615  /**
3616  * Gets the property attributes of a real property in the prototype chain,
3617  * which can be None or any combination of ReadOnly, DontEnum and DontDelete.
3618  * Interceptors in the prototype chain are not called.
3619  */
3622  Local<Name> key);
3623 
3624  /**
3625  * If result.IsEmpty() no real property was located on the object or
3626  * in the prototype chain.
3627  * This means interceptors in the prototype chain are not called.
3628  */
3630  Local<Context> context, Local<Name> key);
3631 
3632  /**
3633  * Gets the property attributes of a real property which can be
3634  * None or any combination of ReadOnly, DontEnum and DontDelete.
3635  * Interceptors in the prototype chain are not called.
3636  */
3638  Local<Context> context, Local<Name> key);
3639 
3640  /** Tests for a named lookup interceptor.*/
3642 
3643  /** Tests for an index lookup interceptor.*/
3645 
3646  /**
3647  * Returns the identity hash for this object. The current implementation
3648  * uses a hidden property on the object to store the identity hash.
3649  *
3650  * The return value will never be 0. Also, it is not guaranteed to be
3651  * unique.
3652  */
3654 
3655  /**
3656  * Clone this object with a fast but shallow copy. Values will point
3657  * to the same values as the original object.
3658  */
3659  // TODO(dcarney): take an isolate and optionally bail out?
3661 
3662  /**
3663  * Returns the context in which the object was created.
3664  */
3666 
3667  /** Same as above, but works for Persistents */
3669  const PersistentBase<Object>& object) {
3670  return object.val_->CreationContext();
3671  }
3672 
3673  /**
3674  * Checks whether a callback is set by the
3675  * ObjectTemplate::SetCallAsFunctionHandler method.
3676  * When an Object is callable this method returns true.
3677  */
3678  bool IsCallable();
3679 
3680  /**
3681  * True if this object is a constructor.
3682  */
3684 
3685  /**
3686  * Call an Object as a function if a callback is set by the
3687  * ObjectTemplate::SetCallAsFunctionHandler method.
3688  */
3690  Local<Value> recv,
3691  int argc,
3692  Local<Value> argv[]);
3693 
3694  /**
3695  * Call an Object as a constructor if a callback is set by the
3696  * ObjectTemplate::SetCallAsFunctionHandler method.
3697  * Note: This method behaves like the Function::NewInstance method.
3698  */
3700  Local<Context> context, int argc, Local<Value> argv[]);
3701 
3702  /**
3703  * Return the isolate to which the Object belongs to.
3704  */
3705  Isolate* GetIsolate();
3706 
3707  /**
3708  * If this object is a Set, Map, WeakSet or WeakMap, this returns a
3709  * representation of the elements of this object as an array.
3710  * If this object is a SetIterator or MapIterator, this returns all
3711  * elements of the underlying collection, starting at the iterator's current
3712  * position.
3713  * For other types, this will return an empty MaybeLocal<Array> (without
3714  * scheduling an exception).
3715  */
3716  MaybeLocal<Array> PreviewEntries(bool* is_key_value);
3717 
3718  static Local<Object> New(Isolate* isolate);
3719 
3720  V8_INLINE static Object* Cast(Value* obj);
3721 
3722  private:
3723  Object();
3724  static void CheckCast(Value* obj);
3725  Local<Value> SlowGetInternalField(int index);
3726  void* SlowGetAlignedPointerFromInternalField(int index);
3727 };
3728 
3729 
3730 /**
3731  * An instance of the built-in array constructor (ECMA-262, 15.4.2).
3732  */
3733 class V8_EXPORT Array : public Object {
3734  public:
3735  uint32_t Length() const;
3736 
3737  /**
3738  * Creates a JavaScript array with the given length. If the length
3739  * is negative the returned array will have length 0.
3740  */
3741  static Local<Array> New(Isolate* isolate, int length = 0);
3742 
3743  V8_INLINE static Array* Cast(Value* obj);
3744  private:
3745  Array();
3746  static void CheckCast(Value* obj);
3747 };
3748 
3749 
3750 /**
3751  * An instance of the built-in Map constructor (ECMA-262, 6th Edition, 23.1.1).
3752  */
3753 class V8_EXPORT Map : public Object {
3754  public:
3755  size_t Size() const;
3756  void Clear();
3758  Local<Value> key);
3760  Local<Value> key,
3761  Local<Value> value);
3762  V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
3763  Local<Value> key);
3764  V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
3765  Local<Value> key);
3766 
3767  /**
3768  * Returns an array of length Size() * 2, where index N is the Nth key and
3769  * index N + 1 is the Nth value.
3770  */
3771  Local<Array> AsArray() const;
3772 
3773  /**
3774  * Creates a new empty Map.
3775  */
3776  static Local<Map> New(Isolate* isolate);
3777 
3778  V8_INLINE static Map* Cast(Value* obj);
3779 
3780  private:
3781  Map();
3782  static void CheckCast(Value* obj);
3783 };
3784 
3785 
3786 /**
3787  * An instance of the built-in Set constructor (ECMA-262, 6th Edition, 23.2.1).
3788  */
3789 class V8_EXPORT Set : public Object {
3790  public:
3791  size_t Size() const;
3792  void Clear();
3794  Local<Value> key);
3795  V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
3796  Local<Value> key);
3797  V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
3798  Local<Value> key);
3799 
3800  /**
3801  * Returns an array of the keys in this Set.
3802  */
3803  Local<Array> AsArray() const;
3804 
3805  /**
3806  * Creates a new empty Set.
3807  */
3808  static Local<Set> New(Isolate* isolate);
3809 
3810  V8_INLINE static Set* Cast(Value* obj);
3811 
3812  private:
3813  Set();
3814  static void CheckCast(Value* obj);
3815 };
3816 
3817 
3818 template<typename T>
3820  public:
3821  template <class S> V8_INLINE ReturnValue(const ReturnValue<S>& that)
3822  : value_(that.value_) {
3823  TYPE_CHECK(T, S);
3824  }
3825  // Local setters
3826  template <typename S>
3827  V8_INLINE V8_DEPRECATE_SOON("Use Global<> instead",
3828  void Set(const Persistent<S>& handle));
3829  template <typename S>
3830  V8_INLINE void Set(const Global<S>& handle);
3831  template <typename S>
3832  V8_INLINE void Set(const Local<S> handle);
3833  // Fast primitive setters
3834  V8_INLINE void Set(bool value);
3835  V8_INLINE void Set(double i);
3836  V8_INLINE void Set(int32_t i);
3837  V8_INLINE void Set(uint32_t i);
3838  // Fast JS primitive setters
3839  V8_INLINE void SetNull();
3840  V8_INLINE void SetUndefined();
3841  V8_INLINE void SetEmptyString();
3842  // Convenience getter for Isolate
3843  V8_INLINE Isolate* GetIsolate() const;
3844 
3845  // Pointer setter: Uncompilable to prevent inadvertent misuse.
3846  template <typename S>
3847  V8_INLINE void Set(S* whatever);
3848 
3849  // Getter. Creates a new Local<> so it comes with a certain performance
3850  // hit. If the ReturnValue was not yet set, this will return the undefined
3851  // value.
3852  V8_INLINE Local<Value> Get() const;
3853 
3854  private:
3855  template<class F> friend class ReturnValue;
3856  template<class F> friend class FunctionCallbackInfo;
3857  template<class F> friend class PropertyCallbackInfo;
3858  template <class F, class G, class H>
3860  V8_INLINE void SetInternal(internal::Object* value) { *value_ = value; }
3861  V8_INLINE internal::Object* GetDefaultValue();
3862  V8_INLINE explicit ReturnValue(internal::Object** slot);
3863  internal::Object** value_;
3864 };
3865 
3866 
3867 /**
3868  * The argument information given to function call callbacks. This
3869  * class provides access to information about the context of the call,
3870  * including the receiver, the number and values of arguments, and
3871  * the holder of the function.
3872  */
3873 template<typename T>
3875  public:
3876  /** The number of available arguments. */
3877  V8_INLINE int Length() const;
3878  /** Accessor for the available arguments. */
3879  V8_INLINE Local<Value> operator[](int i) const;
3880  /** Returns the receiver. This corresponds to the "this" value. */
3881  V8_INLINE Local<Object> This() const;
3882  /**
3883  * If the callback was created without a Signature, this is the same
3884  * value as This(). If there is a signature, and the signature didn't match
3885  * This() but one of its hidden prototypes, this will be the respective
3886  * hidden prototype.
3887  *
3888  * Note that this is not the prototype of This() on which the accessor
3889  * referencing this callback was found (which in V8 internally is often
3890  * referred to as holder [sic]).
3891  */
3892  V8_INLINE Local<Object> Holder() const;
3893  /** For construct calls, this returns the "new.target" value. */
3894  V8_INLINE Local<Value> NewTarget() const;
3895  /** Indicates whether this is a regular call or a construct call. */
3896  V8_INLINE bool IsConstructCall() const;
3897  /** The data argument specified when creating the callback. */
3898  V8_INLINE Local<Value> Data() const;
3899  /** The current Isolate. */
3900  V8_INLINE Isolate* GetIsolate() const;
3901  /** The ReturnValue for the call. */
3903  // This shouldn't be public, but the arm compiler needs it.
3904  static const int kArgsLength = 6;
3905 
3906  protected:
3907  friend class internal::FunctionCallbackArguments;
3909  friend class debug::ConsoleCallArguments;
3910  static const int kHolderIndex = 0;
3911  static const int kIsolateIndex = 1;
3912  static const int kReturnValueDefaultValueIndex = 2;
3913  static const int kReturnValueIndex = 3;
3914  static const int kDataIndex = 4;
3915  static const int kNewTargetIndex = 5;
3916 
3917  V8_INLINE FunctionCallbackInfo(internal::Object** implicit_args,
3918  internal::Object** values, int length);
3920  internal::Object** values_;
3921  int length_;
3922 };
3923 
3924 
3925 /**
3926  * The information passed to a property callback about the context
3927  * of the property access.
3928  */
3929 template<typename T>
3931  public:
3932  /**
3933  * \return The isolate of the property access.
3934  */
3935  V8_INLINE Isolate* GetIsolate() const;
3936 
3937  /**
3938  * \return The data set in the configuration, i.e., in
3939  * `NamedPropertyHandlerConfiguration` or
3940  * `IndexedPropertyHandlerConfiguration.`
3941  */
3943 
3944  /**
3945  * \return The receiver. In many cases, this is the object on which the
3946  * property access was intercepted. When using
3947  * `Reflect.get`, `Function.prototype.call`, or similar functions, it is the
3948  * object passed in as receiver or thisArg.
3949  *
3950  * \code
3951  * void GetterCallback(Local<Name> name,
3952  * const v8::PropertyCallbackInfo<v8::Value>& info) {
3953  * auto context = info.GetIsolate()->GetCurrentContext();
3954  *
3955  * v8::Local<v8::Value> a_this =
3956  * info.This()
3957  * ->GetRealNamedProperty(context, v8_str("a"))
3958  * .ToLocalChecked();
3959  * v8::Local<v8::Value> a_holder =
3960  * info.Holder()
3961  * ->GetRealNamedProperty(context, v8_str("a"))
3962  * .ToLocalChecked();
3963  *
3964  * CHECK(v8_str("r")->Equals(context, a_this).FromJust());
3965  * CHECK(v8_str("obj")->Equals(context, a_holder).FromJust());
3966  *
3967  * info.GetReturnValue().Set(name);
3968  * }
3969  *
3970  * v8::Local<v8::FunctionTemplate> templ =
3971  * v8::FunctionTemplate::New(isolate);
3972  * templ->InstanceTemplate()->SetHandler(
3973  * v8::NamedPropertyHandlerConfiguration(GetterCallback));
3974  * LocalContext env;
3975  * env->Global()
3976  * ->Set(env.local(), v8_str("obj"), templ->GetFunction(env.local())
3977  * .ToLocalChecked()
3978  * ->NewInstance(env.local())
3979  * .ToLocalChecked())
3980  * .FromJust();
3981  *
3982  * CompileRun("obj.a = 'obj'; var r = {a: 'r'}; Reflect.get(obj, 'x', r)");
3983  * \endcode
3984  */
3986 
3987  /**
3988  * \return The object in the prototype chain of the receiver that has the
3989  * interceptor. Suppose you have `x` and its prototype is `y`, and `y`
3990  * has an interceptor. Then `info.This()` is `x` and `info.Holder()` is `y`.
3991  * The Holder() could be a hidden object (the global object, rather
3992  * than the global proxy).
3993  *
3994  * \note For security reasons, do not pass the object back into the runtime.
3995  */
3997 
3998  /**
3999  * \return The return value of the callback.
4000  * Can be changed by calling Set().
4001  * \code
4002  * info.GetReturnValue().Set(...)
4003  * \endcode
4004  *
4005  */
4007 
4008  /**
4009  * \return True if the intercepted function should throw if an error occurs.
4010  * Usually, `true` corresponds to `'use strict'`.
4011  *
4012  * \note Always `false` when intercepting `Reflect.set()`
4013  * independent of the language mode.
4014  */
4016 
4017  // This shouldn't be public, but the arm compiler needs it.
4018  static const int kArgsLength = 7;
4019 
4020  protected:
4021  friend class MacroAssembler;
4022  friend class internal::PropertyCallbackArguments;
4024  static const int kShouldThrowOnErrorIndex = 0;
4025  static const int kHolderIndex = 1;
4026  static const int kIsolateIndex = 2;
4027  static const int kReturnValueDefaultValueIndex = 3;
4028  static const int kReturnValueIndex = 4;
4029  static const int kDataIndex = 5;
4030  static const int kThisIndex = 6;
4031 
4032  V8_INLINE PropertyCallbackInfo(internal::Object** args) : args_(args) {}
4033  internal::Object** args_;
4034 };
4035 
4036 
4037 typedef void (*FunctionCallback)(const FunctionCallbackInfo<Value>& info);
4038 
4040 
4041 /**
4042  * A JavaScript function object (ECMA-262, 15.3).
4043  */
4044 class V8_EXPORT Function : public Object {
4045  public:
4046  /**
4047  * Create a function in the current execution context
4048  * for a given FunctionCallback.
4049  */
4051  Local<Context> context, FunctionCallback callback,
4052  Local<Value> data = Local<Value>(), int length = 0,
4054  SideEffectType side_effect_type = SideEffectType::kHasSideEffect);
4056  "Use maybe version",
4057  Local<Function> New(Isolate* isolate, FunctionCallback callback,
4058  Local<Value> data = Local<Value>(), int length = 0));
4059 
4061  Local<Context> context, int argc, Local<Value> argv[]) const;
4062 
4064  Local<Context> context) const {
4065  return NewInstance(context, 0, nullptr);
4066  }
4067 
4068  /**
4069  * When side effect checks are enabled, passing kHasNoSideEffect allows the
4070  * constructor to be invoked without throwing. Calls made within the
4071  * constructor are still checked.
4072  */
4074  Local<Context> context, int argc, Local<Value> argv[],
4075  SideEffectType side_effect_type = SideEffectType::kHasSideEffect) const;
4076 
4077  V8_DEPRECATE_SOON("Use maybe version",
4078  Local<Value> Call(Local<Value> recv, int argc,
4079  Local<Value> argv[]));
4081  Local<Value> recv, int argc,
4082  Local<Value> argv[]);
4083 
4084  void SetName(Local<String> name);
4085  Local<Value> GetName() const;
4086 
4087  /**
4088  * Name inferred from variable or property assignment of this function.
4089  * Used to facilitate debugging and profiling of JavaScript code written
4090  * in an OO style, where many functions are anonymous but are assigned
4091  * to object properties.
4092  */
4094 
4095  /**
4096  * displayName if it is set, otherwise name if it is configured, otherwise
4097  * function name, otherwise inferred name.
4098  */
4100 
4101  /**
4102  * User-defined name assigned to the "displayName" property of this function.
4103  * Used to facilitate debugging and profiling of JavaScript code.
4104  */
4106 
4107  /**
4108  * Returns zero based line number of function body and
4109  * kLineOffsetNotFound if no information available.
4110  */
4111  int GetScriptLineNumber() const;
4112  /**
4113  * Returns zero based column number of function body and
4114  * kLineOffsetNotFound if no information available.
4115  */
4117 
4118  /**
4119  * Returns scriptId.
4120  */
4121  int ScriptId() const;
4122 
4123  /**
4124  * Returns the original function if this function is bound, else returns
4125  * v8::Undefined.
4126  */
4128 
4130  V8_INLINE static Function* Cast(Value* obj);
4131  static const int kLineOffsetNotFound;
4132 
4133  private:
4134  Function();
4135  static void CheckCast(Value* obj);
4136 };
4137 
4138 #ifndef V8_PROMISE_INTERNAL_FIELD_COUNT
4139 // The number of required internal fields can be defined by embedder.
4140 #define V8_PROMISE_INTERNAL_FIELD_COUNT 0
4141 #endif
4142 
4143 /**
4144  * An instance of the built-in Promise constructor (ES6 draft).
4145  */
4146 class V8_EXPORT Promise : public Object {
4147  public:
4148  /**
4149  * State of the promise. Each value corresponds to one of the possible values
4150  * of the [[PromiseState]] field.
4151  */
4153 
4154  class V8_EXPORT Resolver : public Object {
4155  public:
4156  /**
4157  * Create a new resolver, along with an associated promise in pending state.
4158  */
4160  Local<Context> context);
4161 
4162  /**
4163  * Extract the associated promise.
4164  */
4166 
4167  /**
4168  * Resolve/reject the associated promise with a given value.
4169  * Ignored if the promise is no longer pending.
4170  */
4171  V8_WARN_UNUSED_RESULT Maybe<bool> Resolve(Local<Context> context,
4172  Local<Value> value);
4173 
4174  V8_WARN_UNUSED_RESULT Maybe<bool> Reject(Local<Context> context,
4175  Local<Value> value);
4176 
4177  V8_INLINE static Resolver* Cast(Value* obj);
4178 
4179  private:
4180  Resolver();
4181  static void CheckCast(Value* obj);
4182  };
4183 
4184  /**
4185  * Register a resolution/rejection handler with a promise.
4186  * The handler is given the respective resolution/rejection value as
4187  * an argument. If the promise is already resolved/rejected, the handler is
4188  * invoked at the end of turn.
4189  */
4191  Local<Function> handler);
4192 
4194  Local<Function> handler);
4195 
4196  /**
4197  * Returns true if the promise has at least one derived promise, and
4198  * therefore resolve/reject handlers (including default handler).
4199  */
4200  bool HasHandler();
4201 
4202  /**
4203  * Returns the content of the [[PromiseResult]] field. The Promise must not
4204  * be pending.
4205  */
4207 
4208  /**
4209  * Returns the value of the [[PromiseState]] field.
4210  */
4212 
4213  V8_INLINE static Promise* Cast(Value* obj);
4214 
4216 
4217  private:
4218  Promise();
4219  static void CheckCast(Value* obj);
4220 };
4221 
4222 /**
4223  * An instance of a Property Descriptor, see Ecma-262 6.2.4.
4224  *
4225  * Properties in a descriptor are present or absent. If you do not set
4226  * `enumerable`, `configurable`, and `writable`, they are absent. If `value`,
4227  * `get`, or `set` are absent, but you must specify them in the constructor, use
4228  * empty handles.
4229  *
4230  * Accessors `get` and `set` must be callable or undefined if they are present.
4231  *
4232  * \note Only query properties if they are present, i.e., call `x()` only if
4233  * `has_x()` returns true.
4234  *
4235  * \code
4236  * // var desc = {writable: false}
4237  * v8::PropertyDescriptor d(Local<Value>()), false);
4238  * d.value(); // error, value not set
4239  * if (d.has_writable()) {
4240  * d.writable(); // false
4241  * }
4242  *
4243  * // var desc = {value: undefined}
4244  * v8::PropertyDescriptor d(v8::Undefined(isolate));
4245  *
4246  * // var desc = {get: undefined}
4247  * v8::PropertyDescriptor d(v8::Undefined(isolate), Local<Value>()));
4248  * \endcode
4249  */
4251  public:
4252  // GenericDescriptor
4254 
4255  // DataDescriptor
4257 
4258  // DataDescriptor with writable property
4259  PropertyDescriptor(Local<Value> value, bool writable);
4260 
4261  // AccessorDescriptor
4263 
4265 
4266  Local<Value> value() const;
4267  bool has_value() const;
4268 
4269  Local<Value> get() const;
4270  bool has_get() const;
4271  Local<Value> set() const;
4272  bool has_set() const;
4273 
4274  void set_enumerable(bool enumerable);
4275  bool enumerable() const;
4276  bool has_enumerable() const;
4277 
4278  void set_configurable(bool configurable);
4279  bool configurable() const;
4280  bool has_configurable() const;
4281 
4282  bool writable() const;
4283  bool has_writable() const;
4284 
4285  struct PrivateData;
4286  PrivateData* get_private() const { return private_; }
4287 
4289  void operator=(const PropertyDescriptor&) = delete;
4290 
4291  private:
4292  PrivateData* private_;
4293 };
4294 
4295 /**
4296  * An instance of the built-in Proxy constructor (ECMA-262, 6th Edition,
4297  * 26.2.1).
4298  */
4299 class V8_EXPORT Proxy : public Object {
4300  public:
4303  bool IsRevoked();
4304  void Revoke();
4305 
4306  /**
4307  * Creates a new Proxy for the target object.
4308  */
4309  static MaybeLocal<Proxy> New(Local<Context> context,
4310  Local<Object> local_target,
4311  Local<Object> local_handler);
4312 
4313  V8_INLINE static Proxy* Cast(Value* obj);
4314 
4315  private:
4316  Proxy();
4317  static void CheckCast(Value* obj);
4318 };
4319 
4320 // TODO(mtrofin): rename WasmCompiledModule to WasmModuleObject, for
4321 // consistency with internal APIs.
4323  public:
4324  typedef std::pair<std::unique_ptr<const uint8_t[]>, size_t> SerializedModule;
4325 
4326 // The COMMA macro allows us to use ',' inside of the V8_DEPRECATED macro.
4327 #define COMMA ,
4329  "Use BufferReference.",
4330  typedef std::pair<const uint8_t * COMMA size_t> CallerOwnedBuffer);
4331 #undef COMMA
4332 
4333  /**
4334  * A unowned reference to a byte buffer.
4335  */
4337  const uint8_t* start;
4338  size_t size;
4339  BufferReference(const uint8_t* start, size_t size)
4340  : start(start), size(size) {}
4341  // Temporarily allow conversion to and from CallerOwnedBuffer.
4343  "Use BufferReference directly.",
4344  inline BufferReference(CallerOwnedBuffer)); // NOLINT(runtime/explicit)
4345  V8_DEPRECATED("Use BufferReference directly.",
4346  inline operator CallerOwnedBuffer());
4347  };
4348 
4349  /**
4350  * An opaque, native heap object for transferring wasm modules. It
4351  * supports move semantics, and does not support copy semantics.
4352  */
4353  class TransferrableModule final {
4354  public:
4355  TransferrableModule(TransferrableModule&& src) = default;
4356  TransferrableModule(const TransferrableModule& src) = delete;
4357 
4358  TransferrableModule& operator=(TransferrableModule&& src) = default;
4359  TransferrableModule& operator=(const TransferrableModule& src) = delete;
4360 
4361  private:
4362  typedef std::shared_ptr<internal::wasm::NativeModule> SharedModule;
4363  typedef std::pair<std::unique_ptr<const uint8_t[]>, size_t> OwnedBuffer;
4364  friend class WasmCompiledModule;
4365  explicit TransferrableModule(SharedModule shared_module)
4366  : shared_module_(std::move(shared_module)) {}
4367  TransferrableModule(OwnedBuffer serialized, OwnedBuffer bytes)
4368  : serialized_(std::move(serialized)), wire_bytes_(std::move(bytes)) {}
4369 
4370  SharedModule shared_module_;
4371  OwnedBuffer serialized_ = {nullptr, 0};
4372  OwnedBuffer wire_bytes_ = {nullptr, 0};
4373  };
4374 
4375  /**
4376  * Get an in-memory, non-persistable, and context-independent (meaning,
4377  * suitable for transfer to another Isolate and Context) representation
4378  * of this wasm compiled module.
4379  */
4380  TransferrableModule GetTransferrableModule();
4381 
4382  /**
4383  * Efficiently re-create a WasmCompiledModule, without recompiling, from
4384  * a TransferrableModule.
4385  */
4387  Isolate* isolate, const TransferrableModule&);
4388 
4389  /**
4390  * Get the wasm-encoded bytes that were used to compile this module.
4391  */
4393  V8_DEPRECATED("Use GetWasmWireBytesRef version.",
4394  Local<String> GetWasmWireBytes());
4395 
4396  /**
4397  * Serialize the compiled module. The serialized data does not include the
4398  * uncompiled bytes.
4399  */
4401 
4402  /**
4403  * If possible, deserialize the module, otherwise compile it from the provided
4404  * uncompiled bytes.
4405  */
4407  Isolate* isolate, BufferReference serialized_module,
4408  BufferReference wire_bytes);
4409  V8_INLINE static WasmCompiledModule* Cast(Value* obj);
4410 
4411  private:
4412  static MaybeLocal<WasmCompiledModule> Deserialize(
4413  Isolate* isolate, BufferReference serialized_module,
4414  BufferReference wire_bytes);
4415  static MaybeLocal<WasmCompiledModule> Compile(Isolate* isolate,
4416  const uint8_t* start,
4417  size_t length);
4418  static BufferReference AsReference(
4419  const TransferrableModule::OwnedBuffer& buff) {
4420  return {buff.first.get(), buff.second};
4421  }
4422 
4423  WasmCompiledModule();
4424  static void CheckCast(Value* obj);
4425 };
4426 
4427 // TODO(clemensh): Remove after M70 branch.
4428 WasmCompiledModule::BufferReference::BufferReference(
4429  WasmCompiledModule::CallerOwnedBuffer buf)
4430  : BufferReference(buf.first, buf.second) {}
4432 operator WasmCompiledModule::CallerOwnedBuffer() {
4433  return {start, size};
4434 }
4435 
4436 /**
4437  * The V8 interface for WebAssembly streaming compilation. When streaming
4438  * compilation is initiated, V8 passes a {WasmStreaming} object to the embedder
4439  * such that the embedder can pass the input butes for streaming compilation to
4440  * V8.
4441  */
4442 class V8_EXPORT WasmStreaming final {
4443  public:
4444  class WasmStreamingImpl;
4445 
4446  WasmStreaming(std::unique_ptr<WasmStreamingImpl> impl);
4447 
4449 
4450  /**
4451  * Pass a new chunck of bytes to WebAssembly streaming compilation.
4452  * The buffer passed into {OnBytesReceived} is owned by the caller.
4453  */
4454  void OnBytesReceived(const uint8_t* bytes, size_t size);
4455 
4456  /**
4457  * {Finish} should be called after all received bytes where passed to
4458  * {OnBytesReceived} to tell V8 that there will be no more bytes. {Finish}
4459  * does not have to be called after {Abort} has been called already.
4460  */
4461  void Finish();
4462 
4463  /**
4464  * Abort streaming compilation. If {exception} has a value, then the promise
4465  * associated with streaming compilation is rejected with that value. If
4466  * {exception} does not have value, the promise does not get rejected.
4467  */
4468  void Abort(MaybeLocal<Value> exception);
4469 
4470  /**
4471  * Unpacks a {WasmStreaming} object wrapped in a {Managed} for the embedder.
4472  * Since the embedder is on the other side of the API, it cannot unpack the
4473  * {Managed} itself.
4474  */
4475  static std::shared_ptr<WasmStreaming> Unpack(Isolate* isolate,
4476  Local<Value> value);
4477 
4478  private:
4479  std::unique_ptr<WasmStreamingImpl> impl_;
4480 };
4481 
4482 // TODO(mtrofin): when streaming compilation is done, we can rename this
4483 // to simply WasmModuleObjectBuilder
4484 class V8_EXPORT WasmModuleObjectBuilderStreaming final {
4485  public:
4486  explicit WasmModuleObjectBuilderStreaming(Isolate* isolate);
4487  /**
4488  * The buffer passed into OnBytesReceived is owned by the caller.
4489  */
4490  void OnBytesReceived(const uint8_t*, size_t size);
4491  void Finish();
4492  /**
4493  * Abort streaming compilation. If {exception} has a value, then the promise
4494  * associated with streaming compilation is rejected with that value. If
4495  * {exception} does not have value, the promise does not get rejected.
4496  */
4497  void Abort(MaybeLocal<Value> exception);
4499 
4501 
4502  private:
4503  WasmModuleObjectBuilderStreaming(const WasmModuleObjectBuilderStreaming&) =
4504  delete;
4505  WasmModuleObjectBuilderStreaming(WasmModuleObjectBuilderStreaming&&) =
4506  default;
4507  WasmModuleObjectBuilderStreaming& operator=(
4508  const WasmModuleObjectBuilderStreaming&) = delete;
4509  WasmModuleObjectBuilderStreaming& operator=(
4510  WasmModuleObjectBuilderStreaming&&) = default;
4511  Isolate* isolate_ = nullptr;
4512 
4513 #if V8_CC_MSVC
4514  /**
4515  * We don't need the static Copy API, so the default
4516  * NonCopyablePersistentTraits would be sufficient, however,
4517  * MSVC eagerly instantiates the Copy.
4518  * We ensure we don't use Copy, however, by compiling with the
4519  * defaults everywhere else.
4520  */
4521  Persistent<Promise, CopyablePersistentTraits<Promise>> promise_;
4522 #else
4523  Persistent<Promise> promise_;
4524 #endif
4525  std::shared_ptr<internal::wasm::StreamingDecoder> streaming_decoder_;
4526 };
4527 
4528 #ifndef V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT
4529 // The number of required internal fields can be defined by embedder.
4530 #define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 2
4531 #endif
4532 
4533 
4535 
4536 
4537 /**
4538  * An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5).
4539  */
4540 class V8_EXPORT ArrayBuffer : public Object {
4541  public:
4542  /**
4543  * A thread-safe allocator that V8 uses to allocate |ArrayBuffer|'s memory.
4544  * The allocator is a global V8 setting. It has to be set via
4545  * Isolate::CreateParams.
4546  *
4547  * Memory allocated through this allocator by V8 is accounted for as external
4548  * memory by V8. Note that V8 keeps track of the memory for all internalized
4549  * |ArrayBuffer|s. Responsibility for tracking external memory (using
4550  * Isolate::AdjustAmountOfExternalAllocatedMemory) is handed over to the
4551  * embedder upon externalization and taken over upon internalization (creating
4552  * an internalized buffer from an existing buffer).
4553  *
4554  * Note that it is unsafe to call back into V8 from any of the allocator
4555  * functions.
4556  */
4557  class V8_EXPORT Allocator { // NOLINT
4558  public:
4559  virtual ~Allocator() {}
4560 
4561  /**
4562  * Allocate |length| bytes. Return NULL if allocation is not successful.
4563  * Memory should be initialized to zeroes.
4564  */
4565  virtual void* Allocate(size_t length) = 0;
4566 
4567  /**
4568  * Allocate |length| bytes. Return NULL if allocation is not successful.
4569  * Memory does not have to be initialized.
4570  */
4571  virtual void* AllocateUninitialized(size_t length) = 0;
4572 
4573  /**
4574  * Free the memory block of size |length|, pointed to by |data|.
4575  * That memory is guaranteed to be previously allocated by |Allocate|.
4576  */
4577  virtual void Free(void* data, size_t length) = 0;
4578 
4579  /**
4580  * ArrayBuffer allocation mode. kNormal is a malloc/free style allocation,
4581  * while kReservation is for larger allocations with the ability to set
4582  * access permissions.
4583  */
4585 
4586  /**
4587  * malloc/free based convenience allocator.
4588  *
4589  * Caller takes ownership, i.e. the returned object needs to be freed using
4590  * |delete allocator| once it is no longer in use.
4591  */
4593  };
4594 
4595  /**
4596  * The contents of an |ArrayBuffer|. Externalization of |ArrayBuffer|
4597  * returns an instance of this class, populated, with a pointer to data
4598  * and byte length.
4599  *
4600  * The Data pointer of ArrayBuffer::Contents must be freed using the provided
4601  * deleter, which will call ArrayBuffer::Allocator::Free if the buffer
4602  * was allocated with ArraryBuffer::Allocator::Allocate.
4603  */
4604  class V8_EXPORT Contents { // NOLINT
4605  public:
4606  using DeleterCallback = void (*)(void* buffer, size_t length, void* info);
4607 
4609  : data_(nullptr),
4610  byte_length_(0),
4611  allocation_base_(nullptr),
4612  allocation_length_(0),
4613  allocation_mode_(Allocator::AllocationMode::kNormal),
4614  deleter_(nullptr),
4615  deleter_data_(nullptr) {}
4616 
4617  void* AllocationBase() const { return allocation_base_; }
4618  size_t AllocationLength() const { return allocation_length_; }
4619  Allocator::AllocationMode AllocationMode() const {
4620  return allocation_mode_;
4621  }
4622 
4623  void* Data() const { return data_; }
4624  size_t ByteLength() const { return byte_length_; }
4625  DeleterCallback Deleter() const { return deleter_; }
4626  void* DeleterData() const { return deleter_data_; }
4627 
4628  private:
4629  Contents(void* data, size_t byte_length, void* allocation_base,
4630  size_t allocation_length,
4631  Allocator::AllocationMode allocation_mode, DeleterCallback deleter,
4632  void* deleter_data);
4633 
4634  void* data_;
4635  size_t byte_length_;
4636  void* allocation_base_;
4637  size_t allocation_length_;
4638  Allocator::AllocationMode allocation_mode_;
4639  DeleterCallback deleter_;
4640  void* deleter_data_;
4641 
4642  friend class ArrayBuffer;
4643  };
4644 
4645 
4646  /**
4647  * Data length in bytes.
4648  */
4649  size_t ByteLength() const;
4650 
4651  /**
4652  * Create a new ArrayBuffer. Allocate |byte_length| bytes.
4653  * Allocated memory will be owned by a created ArrayBuffer and
4654  * will be deallocated when it is garbage-collected,
4655  * unless the object is externalized.
4656  */
4657  static Local<ArrayBuffer> New(Isolate* isolate, size_t byte_length);
4658 
4659  /**
4660  * Create a new ArrayBuffer over an existing memory block.
4661  * The created array buffer is by default immediately in externalized state.
4662  * In externalized state, the memory block will not be reclaimed when a
4663  * created ArrayBuffer is garbage-collected.
4664  * In internalized state, the memory block will be released using
4665  * |Allocator::Free| once all ArrayBuffers referencing it are collected by
4666  * the garbage collector.
4667  */
4669  Isolate* isolate, void* data, size_t byte_length,
4671 
4672  /**
4673  * Returns true if ArrayBuffer is externalized, that is, does not
4674  * own its memory block.
4675  */
4676  bool IsExternal() const;
4677 
4678  /**
4679  * Returns true if this ArrayBuffer may be neutered.
4680  */
4681  bool IsNeuterable() const;
4682 
4683  /**
4684  * Neuters this ArrayBuffer and all its views (typed arrays).
4685  * Neutering sets the byte length of the buffer and all typed arrays to zero,
4686  * preventing JavaScript from ever accessing underlying backing store.
4687  * ArrayBuffer should have been externalized and must be neuterable.
4688  */
4689  void Neuter();
4690 
4691  /**
4692  * Make this ArrayBuffer external. The pointer to underlying memory block
4693  * and byte length are returned as |Contents| structure. After ArrayBuffer
4694  * had been externalized, it does no longer own the memory block. The caller
4695  * should take steps to free memory when it is no longer needed.
4696  *
4697  * The Data pointer of ArrayBuffer::Contents must be freed using the provided
4698  * deleter, which will call ArrayBuffer::Allocator::Free if the buffer
4699  * was allocated with ArraryBuffer::Allocator::Allocate.
4700  */
4702 
4703  /**
4704  * Get a pointer to the ArrayBuffer's underlying memory block without
4705  * externalizing it. If the ArrayBuffer is not externalized, this pointer
4706  * will become invalid as soon as the ArrayBuffer gets garbage collected.
4707  *
4708  * The embedder should make sure to hold a strong reference to the
4709  * ArrayBuffer while accessing this pointer.
4710  */
4712 
4713  V8_INLINE static ArrayBuffer* Cast(Value* obj);
4714 
4717 
4718  private:
4719  ArrayBuffer();
4720  static void CheckCast(Value* obj);
4721 };
4722 
4723 
4724 #ifndef V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT
4725 // The number of required internal fields can be defined by embedder.
4726 #define V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT 2
4727 #endif
4728 
4729 
4730 /**
4731  * A base class for an instance of one of "views" over ArrayBuffer,
4732  * including TypedArrays and DataView (ES6 draft 15.13).
4733  */
4735  public:
4736  /**
4737  * Returns underlying ArrayBuffer.
4738  */
4740  /**
4741  * Byte offset in |Buffer|.
4742  */
4743  size_t ByteOffset();
4744  /**
4745  * Size of a view in bytes.
4746  */
4747  size_t ByteLength();
4748 
4749  /**
4750  * Copy the contents of the ArrayBufferView's buffer to an embedder defined
4751  * memory without additional overhead that calling ArrayBufferView::Buffer
4752  * might incur.
4753  *
4754  * Will write at most min(|byte_length|, ByteLength) bytes starting at
4755  * ByteOffset of the underlying buffer to the memory starting at |dest|.
4756  * Returns the number of bytes actually written.
4757  */
4758  size_t CopyContents(void* dest, size_t byte_length);
4759 
4760  /**
4761  * Returns true if ArrayBufferView's backing ArrayBuffer has already been
4762  * allocated.
4763  */
4764  bool HasBuffer() const;
4765 
4766  V8_INLINE static ArrayBufferView* Cast(Value* obj);
4767 
4768  static const int kInternalFieldCount =
4770  static const int kEmbedderFieldCount =
4772 
4773  private:
4774  ArrayBufferView();
4775  static void CheckCast(Value* obj);
4776 };
4777 
4778 
4779 /**
4780  * A base class for an instance of TypedArray series of constructors
4781  * (ES6 draft 15.13.6).
4782  */
4784  public:
4785  /*
4786  * The largest typed array size that can be constructed using New.
4787  */
4788  static constexpr size_t kMaxLength = internal::kSmiMaxValue;
4789 
4790  /**
4791  * Number of elements in this typed array
4792  * (e.g. for Int16Array, |ByteLength|/2).
4793  */
4794  size_t Length();
4795 
4796  V8_INLINE static TypedArray* Cast(Value* obj);
4797 
4798  private:
4799  TypedArray();
4800  static void CheckCast(Value* obj);
4801 };
4802 
4803 
4804 /**
4805  * An instance of Uint8Array constructor (ES6 draft 15.13.6).
4806  */
4808  public:
4809  static Local<Uint8Array> New(Local<ArrayBuffer> array_buffer,
4810  size_t byte_offset, size_t length);
4811  static Local<Uint8Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4812  size_t byte_offset, size_t length);
4813  V8_INLINE static Uint8Array* Cast(Value* obj);
4814 
4815  private:
4816  Uint8Array();
4817  static void CheckCast(Value* obj);
4818 };
4819 
4820 
4821 /**
4822  * An instance of Uint8ClampedArray constructor (ES6 draft 15.13.6).
4823  */
4825  public:
4827  size_t byte_offset, size_t length);
4829  Local<SharedArrayBuffer> shared_array_buffer, size_t byte_offset,
4830  size_t length);
4831  V8_INLINE static Uint8ClampedArray* Cast(Value* obj);
4832 
4833  private:
4834  Uint8ClampedArray();
4835  static void CheckCast(Value* obj);
4836 };
4837 
4838 /**
4839  * An instance of Int8Array constructor (ES6 draft 15.13.6).
4840  */
4842  public:
4843  static Local<Int8Array> New(Local<ArrayBuffer> array_buffer,
4844  size_t byte_offset, size_t length);
4845  static Local<Int8Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4846  size_t byte_offset, size_t length);
4847  V8_INLINE static Int8Array* Cast(Value* obj);
4848 
4849  private:
4850  Int8Array();
4851  static void CheckCast(Value* obj);
4852 };
4853 
4854 
4855 /**
4856  * An instance of Uint16Array constructor (ES6 draft 15.13.6).
4857  */
4859  public:
4860  static Local<Uint16Array> New(Local<ArrayBuffer> array_buffer,
4861  size_t byte_offset, size_t length);
4862  static Local<Uint16Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4863  size_t byte_offset, size_t length);
4864  V8_INLINE static Uint16Array* Cast(Value* obj);
4865 
4866  private:
4867  Uint16Array();
4868  static void CheckCast(Value* obj);
4869 };
4870 
4871 
4872 /**
4873  * An instance of Int16Array constructor (ES6 draft 15.13.6).
4874  */
4876  public:
4877  static Local<Int16Array> New(Local<ArrayBuffer> array_buffer,
4878  size_t byte_offset, size_t length);
4879  static Local<Int16Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4880  size_t byte_offset, size_t length);
4881  V8_INLINE static Int16Array* Cast(Value* obj);
4882 
4883  private:
4884  Int16Array();
4885  static void CheckCast(Value* obj);
4886 };
4887 
4888 
4889 /**
4890  * An instance of Uint32Array constructor (ES6 draft 15.13.6).
4891  */
4893  public:
4894  static Local<Uint32Array> New(Local<ArrayBuffer> array_buffer,
4895  size_t byte_offset, size_t length);
4896  static Local<Uint32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4897  size_t byte_offset, size_t length);
4898  V8_INLINE static Uint32Array* Cast(Value* obj);
4899 
4900  private:
4901  Uint32Array();
4902  static void CheckCast(Value* obj);
4903 };
4904 
4905 
4906 /**
4907  * An instance of Int32Array constructor (ES6 draft 15.13.6).
4908  */
4910  public:
4911  static Local<Int32Array> New(Local<ArrayBuffer> array_buffer,
4912  size_t byte_offset, size_t length);
4913  static Local<Int32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4914  size_t byte_offset, size_t length);
4915  V8_INLINE static Int32Array* Cast(Value* obj);
4916 
4917  private:
4918  Int32Array();
4919  static void CheckCast(Value* obj);
4920 };
4921 
4922 
4923 /**
4924  * An instance of Float32Array constructor (ES6 draft 15.13.6).
4925  */
4927  public:
4928  static Local<Float32Array> New(Local<ArrayBuffer> array_buffer,
4929  size_t byte_offset, size_t length);
4930  static Local<Float32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4931  size_t byte_offset, size_t length);
4932  V8_INLINE static Float32Array* Cast(Value* obj);
4933 
4934  private:
4935  Float32Array();
4936  static void CheckCast(Value* obj);
4937 };
4938 
4939 
4940 /**
4941  * An instance of Float64Array constructor (ES6 draft 15.13.6).
4942  */
4944  public:
4945  static Local<Float64Array> New(Local<ArrayBuffer> array_buffer,
4946  size_t byte_offset, size_t length);
4947  static Local<Float64Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4948  size_t byte_offset, size_t length);
4949  V8_INLINE static Float64Array* Cast(Value* obj);
4950 
4951  private:
4952  Float64Array();
4953  static void CheckCast(Value* obj);
4954 };
4955 
4956 /**
4957  * An instance of BigInt64Array constructor.
4958  */
4960  public:
4961  static Local<BigInt64Array> New(Local<ArrayBuffer> array_buffer,
4962  size_t byte_offset, size_t length);
4963  static Local<BigInt64Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4964  size_t byte_offset, size_t length);
4965  V8_INLINE static BigInt64Array* Cast(Value* obj);
4966 
4967  private:
4968  BigInt64Array();
4969  static void CheckCast(Value* obj);
4970 };
4971 
4972 /**
4973  * An instance of BigUint64Array constructor.
4974  */
4976  public:
4977  static Local<BigUint64Array> New(Local<ArrayBuffer> array_buffer,
4978  size_t byte_offset, size_t length);
4979  static Local<BigUint64Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4980  size_t byte_offset, size_t length);
4981  V8_INLINE static BigUint64Array* Cast(Value* obj);
4982 
4983  private:
4984  BigUint64Array();
4985  static void CheckCast(Value* obj);
4986 };
4987 
4988 /**
4989  * An instance of DataView constructor (ES6 draft 15.13.7).
4990  */
4992  public:
4993  static Local<DataView> New(Local<ArrayBuffer> array_buffer,
4994  size_t byte_offset, size_t length);
4995  static Local<DataView> New(Local<SharedArrayBuffer> shared_array_buffer,
4996  size_t byte_offset, size_t length);
4997  V8_INLINE static DataView* Cast(Value* obj);
4998 
4999  private:
5000  DataView();
5001  static void CheckCast(Value* obj);
5002 };
5003 
5004 
5005 /**
5006  * An instance of the built-in SharedArrayBuffer constructor.
5007  * This API is experimental and may change significantly.
5008  */
5010  public:
5011  /**
5012  * The contents of an |SharedArrayBuffer|. Externalization of
5013  * |SharedArrayBuffer| returns an instance of this class, populated, with a
5014  * pointer to data and byte length.
5015  *
5016  * The Data pointer of ArrayBuffer::Contents must be freed using the provided
5017  * deleter, which will call ArrayBuffer::Allocator::Free if the buffer
5018  * was allocated with ArraryBuffer::Allocator::Allocate.
5019  *
5020  * This API is experimental and may change significantly.
5021  */
5022  class V8_EXPORT Contents { // NOLINT
5023  public:
5024  using Allocator = v8::ArrayBuffer::Allocator;
5025  using DeleterCallback = void (*)(void* buffer, size_t length, void* info);
5026 
5028  : data_(nullptr),
5029  byte_length_(0),
5030  allocation_base_(nullptr),
5031  allocation_length_(0),
5032  allocation_mode_(Allocator::AllocationMode::kNormal),
5033  deleter_(nullptr),
5034  deleter_data_(nullptr) {}
5035 
5036  void* AllocationBase() const { return allocation_base_; }
5037  size_t AllocationLength() const { return allocation_length_; }
5038  Allocator::AllocationMode AllocationMode() const {
5039  return allocation_mode_;
5040  }
5041 
5042  void* Data() const { return data_; }
5043  size_t ByteLength() const { return byte_length_; }
5044  DeleterCallback Deleter() const { return deleter_; }
5045  void* DeleterData() const { return deleter_data_; }
5046 
5047  private:
5048  Contents(void* data, size_t byte_length, void* allocation_base,
5049  size_t allocation_length,
5050  Allocator::AllocationMode allocation_mode, DeleterCallback deleter,
5051  void* deleter_data);
5052 
5053  void* data_;
5054  size_t byte_length_;
5055  void* allocation_base_;
5056  size_t allocation_length_;
5057  Allocator::AllocationMode allocation_mode_;
5058  DeleterCallback deleter_;
5059  void* deleter_data_;
5060 
5061  friend class SharedArrayBuffer;
5062  };
5063 
5064  /**
5065  * Data length in bytes.
5066  */
5067  size_t ByteLength() const;
5068 
5069  /**
5070  * Create a new SharedArrayBuffer. Allocate |byte_length| bytes.
5071  * Allocated memory will be owned by a created SharedArrayBuffer and
5072  * will be deallocated when it is garbage-collected,
5073  * unless the object is externalized.
5074  */
5075  static Local<SharedArrayBuffer> New(Isolate* isolate, size_t byte_length);
5076 
5077  /**
5078  * Create a new SharedArrayBuffer over an existing memory block. The created
5079  * array buffer is immediately in externalized state unless otherwise
5080  * specified. The memory block will not be reclaimed when a created
5081  * SharedArrayBuffer is garbage-collected.
5082  */
5084  Isolate* isolate, void* data, size_t byte_length,
5086 
5087  /**
5088  * Returns true if SharedArrayBuffer is externalized, that is, does not
5089  * own its memory block.
5090  */
5091  bool IsExternal() const;
5092 
5093  /**
5094  * Make this SharedArrayBuffer external. The pointer to underlying memory
5095  * block and byte length are returned as |Contents| structure. After
5096  * SharedArrayBuffer had been externalized, it does no longer own the memory
5097  * block. The caller should take steps to free memory when it is no longer
5098  * needed.
5099  *
5100  * The memory block is guaranteed to be allocated with |Allocator::Allocate|
5101  * by the allocator specified in
5102  * v8::Isolate::CreateParams::array_buffer_allocator.
5103  *
5104  */
5106 
5107  /**
5108  * Get a pointer to the ArrayBuffer's underlying memory block without
5109  * externalizing it. If the ArrayBuffer is not externalized, this pointer
5110  * will become invalid as soon as the ArrayBuffer became garbage collected.
5111  *
5112  * The embedder should make sure to hold a strong reference to the
5113  * ArrayBuffer while accessing this pointer.
5114  *
5115  * The memory block is guaranteed to be allocated with |Allocator::Allocate|
5116  * by the allocator specified in
5117  * v8::Isolate::CreateParams::array_buffer_allocator.
5118  */
5120 
5121  V8_INLINE static SharedArrayBuffer* Cast(Value* obj);
5122 
5124 
5125  private:
5126  SharedArrayBuffer();
5127  static void CheckCast(Value* obj);
5128 };
5129 
5130 
5131 /**
5132  * An instance of the built-in Date constructor (ECMA-262, 15.9).
5133  */
5134 class V8_EXPORT Date : public Object {
5135  public:
5136  static V8_DEPRECATE_SOON("Use maybe version.",
5137  Local<Value> New(Isolate* isolate, double time));
5138  static V8_WARN_UNUSED_RESULT MaybeLocal<Value> New(Local<Context> context,
5139  double time);
5140 
5141  /**
5142  * A specialization of Value::NumberValue that is more efficient
5143  * because we know the structure of this object.
5144  */
5145  double ValueOf() const;
5146 
5147  V8_INLINE static Date* Cast(Value* obj);
5148 
5149  /**
5150  * Notification that the embedder has changed the time zone,
5151  * daylight savings time, or other date / time configuration
5152  * parameters. V8 keeps a cache of various values used for
5153  * date / time computation. This notification will reset
5154  * those cached values for the current context so that date /
5155  * time configuration changes would be reflected in the Date
5156  * object.
5157  *
5158  * This API should not be called more than needed as it will
5159  * negatively impact the performance of date operations.
5160  */
5161  static void DateTimeConfigurationChangeNotification(Isolate* isolate);
5162 
5163  private:
5164  static void CheckCast(Value* obj);
5165 };
5166 
5167 
5168 /**
5169  * A Number object (ECMA-262, 4.3.21).
5170  */
5172  public:
5173  static Local<Value> New(Isolate* isolate, double value);
5174 
5175  double ValueOf() const;
5176 
5177  V8_INLINE static NumberObject* Cast(Value* obj);
5178 
5179  private:
5180  static void CheckCast(Value* obj);
5181 };
5182 
5183 /**
5184  * A BigInt object (https://tc39.github.io/proposal-bigint)
5185  */
5187  public:
5188  static Local<Value> New(Isolate* isolate, int64_t value);
5189 
5191 
5192  V8_INLINE static BigIntObject* Cast(Value* obj);
5193 
5194  private:
5195  static void CheckCast(Value* obj);
5196 };
5197 
5198 /**
5199  * A Boolean object (ECMA-262, 4.3.15).
5200  */
5202  public:
5203  static Local<Value> New(Isolate* isolate, bool value);
5204 
5205  bool ValueOf() const;
5206 
5207  V8_INLINE static BooleanObject* Cast(Value* obj);
5208 
5209  private:
5210  static void CheckCast(Value* obj);
5211 };
5212 
5213 
5214 /**
5215  * A String object (ECMA-262, 4.3.18).
5216  */
5218  public:
5219  static Local<Value> New(Isolate* isolate, Local<String> value);
5220 
5222 
5223  V8_INLINE static StringObject* Cast(Value* obj);
5224 
5225  private:
5226  static void CheckCast(Value* obj);
5227 };
5228 
5229 
5230 /**
5231  * A Symbol object (ECMA-262 edition 6).
5232  */
5234  public:
5235  static Local<Value> New(Isolate* isolate, Local<Symbol> value);
5236 
5238 
5239  V8_INLINE static SymbolObject* Cast(Value* obj);
5240 
5241  private:
5242  static void CheckCast(Value* obj);
5243 };
5244 
5245 
5246 /**
5247  * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
5248  */
5249 class V8_EXPORT RegExp : public Object {
5250  public:
5251  /**
5252  * Regular expression flag bits. They can be or'ed to enable a set
5253  * of flags.
5254  */
5255  enum Flags {
5256  kNone = 0,
5257  kGlobal = 1 << 0,
5258  kIgnoreCase = 1 << 1,
5259  kMultiline = 1 << 2,
5260  kSticky = 1 << 3,
5261  kUnicode = 1 << 4,
5262  kDotAll = 1 << 5,
5263  };
5264 
5265  /**
5266  * Creates a regular expression from the given pattern string and
5267  * the flags bit field. May throw a JavaScript exception as
5268  * described in ECMA-262, 15.10.4.1.
5269  *
5270  * For example,
5271  * RegExp::New(v8::String::New("foo"),
5272  * static_cast<RegExp::Flags>(kGlobal | kMultiline))
5273  * is equivalent to evaluating "/foo/gm".
5274  */
5276  Local<String> pattern,
5277  Flags flags);
5278 
5279  /**
5280  * Returns the value of the source property: a string representing
5281  * the regular expression.
5282  */
5284 
5285  /**
5286  * Returns the flags bit field.
5287  */
5288  Flags GetFlags() const;
5289 
5290  V8_INLINE static RegExp* Cast(Value* obj);
5291 
5292  private:
5293  static void CheckCast(Value* obj);
5294 };
5295 
5296 
5297 /**
5298  * A JavaScript value that wraps a C++ void*. This type of value is mainly used
5299  * to associate C++ data structures with JavaScript objects.
5300  */
5301 class V8_EXPORT External : public Value {
5302  public:
5303  static Local<External> New(Isolate* isolate, void* value);
5304  V8_INLINE static External* Cast(Value* obj);
5305  void* Value() const;
5306  private:
5307  static void CheckCast(v8::Value* obj);
5308 };
5309 
5310 #define V8_INTRINSICS_LIST(F)
5311  F(ArrayProto_entries, array_entries_iterator)
5312  F(ArrayProto_forEach, array_for_each_iterator)
5313  F(ArrayProto_keys, array_keys_iterator)
5314  F(ArrayProto_values, array_values_iterator)
5315  F(ErrorPrototype, initial_error_prototype)
5316  F(IteratorPrototype, initial_iterator_prototype)
5317 
5319 #define V8_DECL_INTRINSIC(name, iname) k##name,
5321 #undef V8_DECL_INTRINSIC
5322 };
5323 
5324 
5325 // --- Templates ---
5326 
5327 
5328 /**
5329  * The superclass of object and function templates.
5330  */
5331 class V8_EXPORT Template : public Data {
5332  public:
5333  /**
5334  * Adds a property to each instance created by this template.
5335  *
5336  * The property must be defined either as a primitive value, or a template.
5337  */
5338  void Set(Local<Name> name, Local<Data> value,
5339  PropertyAttribute attributes = None);
5340  void SetPrivate(Local<Private> name, Local<Data> value,
5341  PropertyAttribute attributes = None);
5342  V8_INLINE void Set(Isolate* isolate, const char* name, Local<Data> value);
5343 
5345  Local<Name> name,
5348  PropertyAttribute attribute = None,
5349  AccessControl settings = DEFAULT);
5350 
5351  /**
5352  * Whenever the property with the given name is accessed on objects
5353  * created from this Template the getter and setter callbacks
5354  * are called instead of getting and setting the property directly
5355  * on the JavaScript object.
5356  *
5357  * \param name The name of the property for which an accessor is added.
5358  * \param getter The callback to invoke when getting the property.
5359  * \param setter The callback to invoke when setting the property.
5360  * \param data A piece of data that will be passed to the getter and setter
5361  * callbacks whenever they are invoked.
5362  * \param settings Access control settings for the accessor. This is a bit
5363  * field consisting of one of more of
5364  * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
5365  * The default is to not allow cross-context access.
5366  * ALL_CAN_READ means that all cross-context reads are allowed.
5367  * ALL_CAN_WRITE means that all cross-context writes are allowed.
5368  * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
5369  * cross-context access.
5370  * \param attribute The attributes of the property for which an accessor
5371  * is added.
5372  * \param signature The signature describes valid receivers for the accessor
5373  * and is used to perform implicit instance checks against them. If the
5374  * receiver is incompatible (i.e. is not an instance of the constructor as
5375  * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
5376  * thrown and no callback is invoked.
5377  */
5379  Local<String> name, AccessorGetterCallback getter,
5380  AccessorSetterCallback setter = 0,
5381  // TODO(dcarney): gcc can't handle Local below
5382  Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
5384  AccessControl settings = DEFAULT,
5385  SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect);
5387  Local<Name> name, AccessorNameGetterCallback getter,
5388  AccessorNameSetterCallback setter = 0,
5389  // TODO(dcarney): gcc can't handle Local below
5390  Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
5392  AccessControl settings = DEFAULT,
5393  SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect);
5394 
5395  /**
5396  * Like SetNativeDataProperty, but V8 will replace the native data property
5397  * with a real data property on first access.
5398  */
5400  Local<Name> name, AccessorNameGetterCallback getter,
5401  Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
5402  SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect);
5403 
5404  /**
5405  * During template instantiation, sets the value with the intrinsic property
5406  * from the correct context.
5407  */
5409  PropertyAttribute attribute = None);
5410 
5411  private:
5412  Template();
5413 
5414  friend class ObjectTemplate;
5415  friend class FunctionTemplate;
5416 };
5417 
5418 // TODO(dcarney): Replace GenericNamedPropertyFooCallback with just
5419 // NamedPropertyFooCallback.
5420 
5421 /**
5422  * Interceptor for get requests on an object.
5423  *
5424  * Use `info.GetReturnValue().Set()` to set the return value of the
5425  * intercepted get request.
5426  *
5427  * \param property The name of the property for which the request was
5428  * intercepted.
5429  * \param info Information about the intercepted request, such as
5430  * isolate, receiver, return value, or whether running in `'use strict`' mode.
5431  * See `PropertyCallbackInfo`.
5432  *
5433  * \code
5434  * void GetterCallback(
5435  * Local<Name> name,
5436  * const v8::PropertyCallbackInfo<v8::Value>& info) {
5437  * info.GetReturnValue().Set(v8_num(42));
5438  * }
5439  *
5440  * v8::Local<v8::FunctionTemplate> templ =
5441  * v8::FunctionTemplate::New(isolate);
5442  * templ->InstanceTemplate()->SetHandler(
5443  * v8::NamedPropertyHandlerConfiguration(GetterCallback));
5444  * LocalContext env;
5445  * env->Global()
5446  * ->Set(env.local(), v8_str("obj"), templ->GetFunction(env.local())
5447  * .ToLocalChecked()
5448  * ->NewInstance(env.local())
5449  * .ToLocalChecked())
5450  * .FromJust();
5451  * v8::Local<v8::Value> result = CompileRun("obj.a = 17; obj.a");
5452  * CHECK(v8_num(42)->Equals(env.local(), result).FromJust());
5453  * \endcode
5454  *
5455  * See also `ObjectTemplate::SetHandler`.
5456  */
5458  Local<Name> property, const PropertyCallbackInfo<Value>& info);
5459 
5460 /**
5461  * Interceptor for set requests on an object.
5462  *
5463  * Use `info.GetReturnValue()` to indicate whether the request was intercepted
5464  * or not. If the setter successfully intercepts the request, i.e., if the
5465  * request should not be further executed, call
5466  * `info.GetReturnValue().Set(value)`. If the setter
5467  * did not intercept the request, i.e., if the request should be handled as
5468  * if no interceptor is present, do not not call `Set()`.
5469  *
5470  * \param property The name of the property for which the request was
5471  * intercepted.
5472  * \param value The value which the property will have if the request
5473  * is not intercepted.
5474  * \param info Information about the intercepted request, such as
5475  * isolate, receiver, return value, or whether running in `'use strict'` mode.
5476  * See `PropertyCallbackInfo`.
5477  *
5478  * See also
5479  * `ObjectTemplate::SetHandler.`
5480  */
5482  Local<Name> property, Local<Value> value,
5483  const PropertyCallbackInfo<Value>& info);
5484 
5485 /**
5486  * Intercepts all requests that query the attributes of the
5487  * property, e.g., getOwnPropertyDescriptor(), propertyIsEnumerable(), and
5488  * defineProperty().
5489  *
5490  * Use `info.GetReturnValue().Set(value)` to set the property attributes. The
5491  * value is an integer encoding a `v8::PropertyAttribute`.
5492  *
5493  * \param property The name of the property for which the request was
5494  * intercepted.
5495  * \param info Information about the intercepted request, such as
5496  * isolate, receiver, return value, or whether running in `'use strict'` mode.
5497  * See `PropertyCallbackInfo`.
5498  *
5499  * \note Some functions query the property attributes internally, even though
5500  * they do not return the attributes. For example, `hasOwnProperty()` can
5501  * trigger this interceptor depending on the state of the object.
5502  *
5503  * See also
5504  * `ObjectTemplate::SetHandler.`
5505  */
5507  Local<Name> property, const PropertyCallbackInfo<Integer>& info);
5508 
5509 /**
5510  * Interceptor for delete requests on an object.
5511  *
5512  * Use `info.GetReturnValue()` to indicate whether the request was intercepted
5513  * or not. If the deleter successfully intercepts the request, i.e., if the
5514  * request should not be further executed, call
5515  * `info.GetReturnValue().Set(value)` with a boolean `value`. The `value` is
5516  * used as the return value of `delete`.
5517  *
5518  * \param property The name of the property for which the request was
5519  * intercepted.
5520  * \param info Information about the intercepted request, such as
5521  * isolate, receiver, return value, or whether running in `'use strict'` mode.
5522  * See `PropertyCallbackInfo`.
5523  *
5524  * \note If you need to mimic the behavior of `delete`, i.e., throw in strict
5525  * mode instead of returning false, use `info.ShouldThrowOnError()` to determine
5526  * if you are in strict mode.
5527  *
5528  * See also `ObjectTemplate::SetHandler.`
5529  */
5531  Local<Name> property, const PropertyCallbackInfo<Boolean>& info);
5532 
5533 /**
5534  * Returns an array containing the names of the properties the named
5535  * property getter intercepts.
5536  *
5537  * Note: The values in the array must be of type v8::Name.
5538  */
5540  const PropertyCallbackInfo<Array>& info);
5541 
5542 /**
5543  * Interceptor for defineProperty requests on an object.
5544  *
5545  * Use `info.GetReturnValue()` to indicate whether the request was intercepted
5546  * or not. If the definer successfully intercepts the request, i.e., if the
5547  * request should not be further executed, call
5548  * `info.GetReturnValue().Set(value)`. If the definer
5549  * did not intercept the request, i.e., if the request should be handled as
5550  * if no interceptor is present, do not not call `Set()`.
5551  *
5552  * \param property The name of the property for which the request was
5553  * intercepted.
5554  * \param desc The property descriptor which is used to define the
5555  * property if the request is not intercepted.
5556  * \param info Information about the intercepted request, such as
5557  * isolate, receiver, return value, or whether running in `'use strict'` mode.
5558  * See `PropertyCallbackInfo`.
5559  *
5560  * See also `ObjectTemplate::SetHandler`.
5561  */
5563  Local<Name> property, const PropertyDescriptor& desc,
5564  const PropertyCallbackInfo<Value>& info);
5565 
5566 /**
5567  * Interceptor for getOwnPropertyDescriptor requests on an object.
5568  *
5569  * Use `info.GetReturnValue().Set()` to set the return value of the
5570  * intercepted request. The return value must be an object that
5571  * can be converted to a PropertyDescriptor, e.g., a `v8::value` returned from
5572  * `v8::Object::getOwnPropertyDescriptor`.
5573  *
5574  * \param property The name of the property for which the request was
5575  * intercepted.
5576  * \info Information about the intercepted request, such as
5577  * isolate, receiver, return value, or whether running in `'use strict'` mode.
5578  * See `PropertyCallbackInfo`.
5579  *
5580  * \note If GetOwnPropertyDescriptor is intercepted, it will
5581  * always return true, i.e., indicate that the property was found.
5582  *
5583  * See also `ObjectTemplate::SetHandler`.
5584  */
5586  Local<Name> property, const PropertyCallbackInfo<Value>& info);
5587 
5588 /**
5589  * See `v8::GenericNamedPropertyGetterCallback`.
5590  */
5592  uint32_t index,
5593  const PropertyCallbackInfo<Value>& info);
5594 
5595 /**
5596  * See `v8::GenericNamedPropertySetterCallback`.
5597  */
5599  uint32_t index,
5600  Local<Value> value,
5601  const PropertyCallbackInfo<Value>& info);
5602 
5603 /**
5604  * See `v8::GenericNamedPropertyQueryCallback`.
5605  */
5607  uint32_t index,
5608  const PropertyCallbackInfo<Integer>& info);
5609 
5610 /**
5611  * See `v8::GenericNamedPropertyDeleterCallback`.
5612  */
5614  uint32_t index,
5615  const PropertyCallbackInfo<Boolean>& info);
5616 
5617 /**
5618  * Returns an array containing the indices of the properties the indexed
5619  * property getter intercepts.
5620  *
5621  * Note: The values in the array must be uint32_t.
5622  */
5624  const PropertyCallbackInfo<Array>& info);
5625 
5626 /**
5627  * See `v8::GenericNamedPropertyDefinerCallback`.
5628  */
5630  uint32_t index, const PropertyDescriptor& desc,
5631  const PropertyCallbackInfo<Value>& info);
5632 
5633 /**
5634  * See `v8::GenericNamedPropertyDescriptorCallback`.
5635  */
5637  uint32_t index, const PropertyCallbackInfo<Value>& info);
5638 
5639 /**
5640  * Access type specification.
5641  */
5647  ACCESS_KEYS
5648 };
5649 
5650 
5651 /**
5652  * Returns true if the given context should be allowed to access the given
5653  * object.
5654  */
5655 typedef bool (*AccessCheckCallback)(Local<Context> accessing_context,
5656  Local<Object> accessed_object,
5657  Local<Value> data);
5658 
5659 /**
5660  * A FunctionTemplate is used to create functions at runtime. There
5661  * can only be one function created from a FunctionTemplate in a
5662  * context. The lifetime of the created function is equal to the
5663  * lifetime of the context. So in case the embedder needs to create
5664  * temporary functions that can be collected using Scripts is
5665  * preferred.
5666  *
5667  * Any modification of a FunctionTemplate after first instantiation will trigger
5668  * a crash.
5669  *
5670  * A FunctionTemplate can have properties, these properties are added to the
5671  * function object when it is created.
5672  *
5673  * A FunctionTemplate has a corresponding instance template which is
5674  * used to create object instances when the function is used as a
5675  * constructor. Properties added to the instance template are added to
5676  * each object instance.
5677  *
5678  * A FunctionTemplate can have a prototype template. The prototype template
5679  * is used to create the prototype object of the function.
5680  *
5681  * The following example shows how to use a FunctionTemplate:
5682  *
5683  * \code
5684  * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(isolate);
5685  * t->Set(isolate, "func_property", v8::Number::New(isolate, 1));
5686  *
5687  * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
5688  * proto_t->Set(isolate,
5689  * "proto_method",
5690  * v8::FunctionTemplate::New(isolate, InvokeCallback));
5691  * proto_t->Set(isolate, "proto_const", v8::Number::New(isolate, 2));
5692  *
5693  * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
5694  * instance_t->SetAccessor(String::NewFromUtf8(isolate, "instance_accessor"),
5695  * InstanceAccessorCallback);
5696  * instance_t->SetHandler(
5697  * NamedPropertyHandlerConfiguration(PropertyHandlerCallback));
5698  * instance_t->Set(String::NewFromUtf8(isolate, "instance_property"),
5699  * Number::New(isolate, 3));
5700  *
5701  * v8::Local<v8::Function> function = t->GetFunction();
5702  * v8::Local<v8::Object> instance = function->NewInstance();
5703  * \endcode
5704  *
5705  * Let's use "function" as the JS variable name of the function object
5706  * and "instance" for the instance object created above. The function
5707  * and the instance will have the following properties:
5708  *
5709  * \code
5710  * func_property in function == true;
5711  * function.func_property == 1;
5712  *
5713  * function.prototype.proto_method() invokes 'InvokeCallback'
5714  * function.prototype.proto_const == 2;
5715  *
5716  * instance instanceof function == true;
5717  * instance.instance_accessor calls 'InstanceAccessorCallback'
5718  * instance.instance_property == 3;
5719  * \endcode
5720  *
5721  * A FunctionTemplate can inherit from another one by calling the
5722  * FunctionTemplate::Inherit method. The following graph illustrates
5723  * the semantics of inheritance:
5724  *
5725  * \code
5726  * FunctionTemplate Parent -> Parent() . prototype -> { }
5727  * ^ ^
5728  * | Inherit(Parent) | .__proto__
5729  * | |
5730  * FunctionTemplate Child -> Child() . prototype -> { }
5731  * \endcode
5732  *
5733  * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
5734  * object of the Child() function has __proto__ pointing to the
5735  * Parent() function's prototype object. An instance of the Child
5736  * function has all properties on Parent's instance templates.
5737  *
5738  * Let Parent be the FunctionTemplate initialized in the previous
5739  * section and create a Child FunctionTemplate by:
5740  *
5741  * \code
5742  * Local<FunctionTemplate> parent = t;
5743  * Local<FunctionTemplate> child = FunctionTemplate::New();
5744  * child->Inherit(parent);
5745  *
5746  * Local<Function> child_function = child->GetFunction();
5747  * Local<Object> child_instance = child_function->NewInstance();
5748  * \endcode
5749  *
5750  * The Child function and Child instance will have the following
5751  * properties:
5752  *
5753  * \code
5754  * child_func.prototype.__proto__ == function.prototype;
5755  * child_instance.instance_accessor calls 'InstanceAccessorCallback'
5756  * child_instance.instance_property == 3;
5757  * \endcode
5758  */
5760  public:
5761  /** Creates a function template.*/
5763  Isolate* isolate, FunctionCallback callback = 0,
5764  Local<Value> data = Local<Value>(),
5765  Local<Signature> signature = Local<Signature>(), int length = 0,
5767  SideEffectType side_effect_type = SideEffectType::kHasSideEffect);
5768 
5769  /** Get a template included in the snapshot by index. */
5770  static MaybeLocal<FunctionTemplate> FromSnapshot(Isolate* isolate,
5771  size_t index);
5772 
5773  /**
5774  * Creates a function template backed/cached by a private property.
5775  */
5777  Isolate* isolate, FunctionCallback callback,
5778  Local<Private> cache_property, Local<Value> data = Local<Value>(),
5779  Local<Signature> signature = Local<Signature>(), int length = 0,
5780  SideEffectType side_effect_type = SideEffectType::kHasSideEffect);
5781 
5782  /** Returns the unique function instance in the current execution context.*/
5783  V8_DEPRECATE_SOON("Use maybe version", Local<Function> GetFunction());
5785  Local<Context> context);
5786 
5787  /**
5788  * Similar to Context::NewRemoteContext, this creates an instance that
5789  * isn't backed by an actual object.
5790  *
5791  * The InstanceTemplate of this FunctionTemplate must have access checks with
5792  * handlers installed.
5793  */
5795 
5796  /**
5797  * Set the call-handler callback for a FunctionTemplate. This
5798  * callback is called whenever the function created from this
5799  * FunctionTemplate is called.
5800  */
5802  FunctionCallback callback, Local<Value> data = Local<Value>(),
5803  SideEffectType side_effect_type = SideEffectType::kHasSideEffect);
5804 
5805  /** Set the predefined length property for the FunctionTemplate. */
5806  void SetLength(int length);
5807 
5808  /** Get the InstanceTemplate. */
5810 
5811  /**
5812  * Causes the function template to inherit from a parent function template.
5813  * This means the function's prototype.__proto__ is set to the parent
5814  * function's prototype.
5815  **/
5817 
5818  /**
5819  * A PrototypeTemplate is the template used to create the prototype object
5820  * of the function created by this template.
5821  */
5823 
5824  /**
5825  * A PrototypeProviderTemplate is another function template whose prototype
5826  * property is used for this template. This is mutually exclusive with setting
5827  * a prototype template indirectly by calling PrototypeTemplate() or using
5828  * Inherit().
5829  **/
5831 
5832  /**
5833  * Set the class name of the FunctionTemplate. This is used for
5834  * printing objects created with the function created from the
5835  * FunctionTemplate as its constructor.
5836  */
5838 
5839 
5840  /**
5841  * When set to true, no access check will be performed on the receiver of a
5842  * function call. Currently defaults to true, but this is subject to change.
5843  */
5844  void SetAcceptAnyReceiver(bool value);
5845 
5846  /**
5847  * Determines whether the __proto__ accessor ignores instances of
5848  * the function template. If instances of the function template are
5849  * ignored, __proto__ skips all instances and instead returns the
5850  * next object in the prototype chain.
5851  *
5852  * Call with a value of true to make the __proto__ accessor ignore
5853  * instances of the function template. Call with a value of false
5854  * to make the __proto__ accessor not ignore instances of the
5855  * function template. By default, instances of a function template
5856  * are not ignored.
5857  */
5858  void SetHiddenPrototype(bool value);
5859 
5860  /**
5861  * Sets the ReadOnly flag in the attributes of the 'prototype' property
5862  * of functions created from this FunctionTemplate to true.
5863  */
5865 
5866  /**
5867  * Removes the prototype property from functions created from this
5868  * FunctionTemplate.
5869  */
5871 
5872  /**
5873  * Returns true if the given object is an instance of this function
5874  * template.
5875  */
5876  bool HasInstance(Local<Value> object);
5877 
5878  V8_INLINE static FunctionTemplate* Cast(Data* data);
5879 
5880  private:
5881  FunctionTemplate();
5882 
5883  static void CheckCast(Data* that);
5884  friend class Context;
5885  friend class ObjectTemplate;
5886 };
5887 
5888 /**
5889  * Configuration flags for v8::NamedPropertyHandlerConfiguration or
5890  * v8::IndexedPropertyHandlerConfiguration.
5891  */
5893  /**
5894  * None.
5895  */
5896  kNone = 0,
5897 
5898  /**
5899  * See ALL_CAN_READ above.
5900  */
5901  kAllCanRead = 1,
5902 
5903  /** Will not call into interceptor for properties on the receiver or prototype
5904  * chain, i.e., only call into interceptor for properties that do not exist.
5905  * Currently only valid for named interceptors.
5906  */
5907  kNonMasking = 1 << 1,
5908 
5909  /**
5910  * Will not call into interceptor for symbol lookup. Only meaningful for
5911  * named interceptors.
5912  */
5913  kOnlyInterceptStrings = 1 << 2,
5914 
5915  /**
5916  * The getter, query, enumerator callbacks do not produce side effects.
5917  */
5918  kHasNoSideEffect = 1 << 3,
5919 };
5920 
5930  Local<Value> data = Local<Value>(),
5932  : getter(getter),
5933  setter(setter),
5934  query(query),
5935  deleter(deleter),
5936  enumerator(enumerator),
5937  definer(definer),
5938  descriptor(descriptor),
5939  data(data),
5940  flags(flags) {}
5941 
5943  /** Note: getter is required */
5949  Local<Value> data = Local<Value>(),
5951  : getter(getter),
5952  setter(setter),
5953  query(query),
5954  deleter(deleter),
5955  enumerator(enumerator),
5956  definer(0),
5957  descriptor(0),
5958  data(data),
5959  flags(flags) {}
5960 
5968  Local<Value> data = Local<Value>(),
5970  : getter(getter),
5971  setter(setter),
5972  query(0),
5973  deleter(deleter),
5974  enumerator(enumerator),
5975  definer(definer),
5976  descriptor(descriptor),
5977  data(data),
5978  flags(flags) {}
5979 
5989 };
5990 
5991 
6000  Local<Value> data = Local<Value>(),
6002  : getter(getter),
6003  setter(setter),
6004  query(query),
6005  deleter(deleter),
6006  enumerator(enumerator),
6007  definer(definer),
6008  descriptor(descriptor),
6009  data(data),
6010  flags(flags) {}
6011 
6013  /** Note: getter is required */
6014  IndexedPropertyGetterCallback getter = 0,
6015  IndexedPropertySetterCallback setter = 0,
6016  IndexedPropertyQueryCallback query = 0,
6017  IndexedPropertyDeleterCallback deleter = 0,
6018  IndexedPropertyEnumeratorCallback enumerator = 0,
6019  Local<Value> data = Local<Value>(),
6021  : getter(getter),
6022  setter(setter),
6023  query(query),
6024  deleter(deleter),
6025  enumerator(enumerator),
6026  definer(0),
6027  descriptor(0),
6028  data(data),
6029  flags(flags) {}
6030 
6038  Local<Value> data = Local<Value>(),
6040  : getter(getter),
6041  setter(setter),
6042  query(0),
6043  deleter(deleter),
6044  enumerator(enumerator),
6045  definer(definer),
6046  descriptor(descriptor),
6047  data(data),
6048  flags(flags) {}
6049 
6059 };
6060 
6061 
6062 /**
6063  * An ObjectTemplate is used to create objects at runtime.
6064  *
6065  * Properties added to an ObjectTemplate are added to each object
6066  * created from the ObjectTemplate.
6067  */
6069  public:
6070  /** Creates an ObjectTemplate. */
6072  Isolate* isolate,
6074 
6075  /** Get a template included in the snapshot by index. */
6076  static MaybeLocal<ObjectTemplate> FromSnapshot(Isolate* isolate,
6077  size_t index);
6078 
6079  /** Creates a new instance of this template.*/
6080  V8_DEPRECATE_SOON("Use maybe version", Local<Object> NewInstance());
6082 
6083  /**
6084  * Sets an accessor on the object template.
6085  *
6086  * Whenever the property with the given name is accessed on objects
6087  * created from this ObjectTemplate the getter and setter callbacks
6088  * are called instead of getting and setting the property directly
6089  * on the JavaScript object.
6090  *
6091  * \param name The name of the property for which an accessor is added.
6092  * \param getter The callback to invoke when getting the property.
6093  * \param setter The callback to invoke when setting the property.
6094  * \param data A piece of data that will be passed to the getter and setter
6095  * callbacks whenever they are invoked.
6096  * \param settings Access control settings for the accessor. This is a bit
6097  * field consisting of one of more of
6098  * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
6099  * The default is to not allow cross-context access.
6100  * ALL_CAN_READ means that all cross-context reads are allowed.
6101  * ALL_CAN_WRITE means that all cross-context writes are allowed.
6102  * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
6103  * cross-context access.
6104  * \param attribute The attributes of the property for which an accessor
6105  * is added.
6106  * \param signature The signature describes valid receivers for the accessor
6107  * and is used to perform implicit instance checks against them. If the
6108  * receiver is incompatible (i.e. is not an instance of the constructor as
6109  * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
6110  * thrown and no callback is invoked.
6111  */
6113  Local<String> name, AccessorGetterCallback getter,
6114  AccessorSetterCallback setter = 0, Local<Value> data = Local<Value>(),
6115  AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
6117  SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect);
6119  Local<Name> name, AccessorNameGetterCallback getter,
6121  AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
6123  SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect);
6124 
6125  /**
6126  * Sets a named property handler on the object template.
6127  *
6128  * Whenever a property whose name is a string or a symbol is accessed on
6129  * objects created from this object template, the provided callback is
6130  * invoked instead of accessing the property directly on the JavaScript
6131  * object.
6132  *
6133  * @param configuration The NamedPropertyHandlerConfiguration that defines the
6134  * callbacks to invoke when accessing a property.
6135  */
6136  void SetHandler(const NamedPropertyHandlerConfiguration& configuration);
6137 
6138  /**
6139  * Sets an indexed property handler on the object template.
6140  *
6141  * Whenever an indexed property is accessed on objects created from
6142  * this object template, the provided callback is invoked instead of
6143  * accessing the property directly on the JavaScript object.
6144  *
6145  * \param getter The callback to invoke when getting a property.
6146  * \param setter The callback to invoke when setting a property.
6147  * \param query The callback to invoke to check if an object has a property.
6148  * \param deleter The callback to invoke when deleting a property.
6149  * \param enumerator The callback to invoke to enumerate all the indexed
6150  * properties of an object.
6151  * \param data A piece of data that will be passed to the callbacks
6152  * whenever they are invoked.
6153  */
6154  // TODO(dcarney): deprecate
6157  IndexedPropertySetterCallback setter = 0,
6158  IndexedPropertyQueryCallback query = 0,
6159  IndexedPropertyDeleterCallback deleter = 0,
6160  IndexedPropertyEnumeratorCallback enumerator = 0,
6161  Local<Value> data = Local<Value>()) {
6163  deleter, enumerator, data));
6164  }
6165 
6166  /**
6167  * Sets an indexed property handler on the object template.
6168  *
6169  * Whenever an indexed property is accessed on objects created from
6170  * this object template, the provided callback is invoked instead of
6171  * accessing the property directly on the JavaScript object.
6172  *
6173  * @param configuration The IndexedPropertyHandlerConfiguration that defines
6174  * the callbacks to invoke when accessing a property.
6175  */
6177 
6178  /**
6179  * Sets the callback to be used when calling instances created from
6180  * this template as a function. If no callback is set, instances
6181  * behave like normal JavaScript objects that cannot be called as a
6182  * function.
6183  */
6185  Local<Value> data = Local<Value>());
6186 
6187  /**
6188  * Mark object instances of the template as undetectable.
6189  *
6190  * In many ways, undetectable objects behave as though they are not
6191  * there. They behave like 'undefined' in conditionals and when
6192  * printed. However, properties can be accessed and called as on
6193  * normal objects.
6194  */
6196 
6197  /**
6198  * Sets access check callback on the object template and enables access
6199  * checks.
6200  *
6201  * When accessing properties on instances of this object template,
6202  * the access check callback will be called to determine whether or
6203  * not to allow cross-context access to the properties.
6204  */
6206  Local<Value> data = Local<Value>());
6207 
6208  /**
6209  * Like SetAccessCheckCallback but invokes an interceptor on failed access
6210  * checks instead of looking up all-can-read properties. You can only use
6211  * either this method or SetAccessCheckCallback, but not both at the same
6212  * time.
6213  */
6215  AccessCheckCallback callback,
6216  const NamedPropertyHandlerConfiguration& named_handler,
6217  const IndexedPropertyHandlerConfiguration& indexed_handler,
6218  Local<Value> data = Local<Value>());
6219 
6220  /**
6221  * Gets the number of internal fields for objects generated from
6222  * this template.
6223  */
6225 
6226  /**
6227  * Sets the number of internal fields for objects generated from
6228  * this template.
6229  */
6230  void SetInternalFieldCount(int value);
6231 
6232  /**
6233  * Returns true if the object will be an immutable prototype exotic object.
6234  */
6236 
6237  /**
6238  * Makes the ObjectTemplate for an immutable prototype exotic object, with an
6239  * immutable __proto__.
6240  */
6242 
6243  V8_INLINE static ObjectTemplate* Cast(Data* data);
6244 
6245  private:
6246  ObjectTemplate();
6247  static Local<ObjectTemplate> New(internal::Isolate* isolate,
6248  Local<FunctionTemplate> constructor);
6249  static void CheckCast(Data* that);
6250  friend class FunctionTemplate;
6251 };
6252 
6253 /**
6254  * A Signature specifies which receiver is valid for a function.
6255  *
6256  * A receiver matches a given signature if the receiver (or any of its
6257  * hidden prototypes) was created from the signature's FunctionTemplate, or
6258  * from a FunctionTemplate that inherits directly or indirectly from the
6259  * signature's FunctionTemplate.
6260  */
6261 class V8_EXPORT Signature : public Data {
6262  public:
6264  Isolate* isolate,
6266 
6267  V8_INLINE static Signature* Cast(Data* data);
6268 
6269  private:
6270  Signature();
6271 
6272  static void CheckCast(Data* that);
6273 };
6274 
6275 
6276 /**
6277  * An AccessorSignature specifies which receivers are valid parameters
6278  * to an accessor callback.
6279  */
6281  public:
6283  Isolate* isolate,
6285 
6286  V8_INLINE static AccessorSignature* Cast(Data* data);
6287 
6288  private:
6289  AccessorSignature();
6290 
6291  static void CheckCast(Data* that);
6292 };
6293 
6294 
6295 // --- Extensions ---
6296 V8_DEPRECATE_SOON("Implementation detail", class)
6299  public:
6300  ExternalOneByteStringResourceImpl() : data_(0), length_(0) {}
6301  ExternalOneByteStringResourceImpl(const char* data, size_t length)
6302  : data_(data), length_(length) {}
6303  const char* data() const { return data_; }
6304  size_t length() const { return length_; }
6305 
6306  private:
6307  const char* data_;
6308  size_t length_;
6309 };
6310 
6311 /**
6312  * Ignore
6313  */
6314 class V8_EXPORT Extension { // NOLINT
6315  public:
6316  // Note that the strings passed into this constructor must live as long
6317  // as the Extension itself.
6318  Extension(const char* name,
6319  const char* source = 0,
6320  int dep_count = 0,
6321  const char** deps = 0,
6322  int source_length = -1);
6323  virtual ~Extension() { delete source_; }
6324  virtual Local<FunctionTemplate> GetNativeFunctionTemplate(
6325  Isolate* isolate, Local<String> name) {
6327  }
6328 
6329  const char* name() const { return name_; }
6330  size_t source_length() const { return source_length_; }
6331  const String::ExternalOneByteStringResource* source() const {
6332  return source_;
6333  }
6334  int dependency_count() { return dep_count_; }
6335  const char** dependencies() { return deps_; }
6336  void set_auto_enable(bool value) { auto_enable_ = value; }
6337  bool auto_enable() { return auto_enable_; }
6338 
6339  // Disallow copying and assigning.
6340  Extension(const Extension&) = delete;
6341  void operator=(const Extension&) = delete;
6342 
6343  private:
6344  const char* name_;
6345  size_t source_length_; // expected to initialize before source_
6347  int dep_count_;
6348  const char** deps_;
6349  bool auto_enable_;
6350 };
6351 
6352 
6353 void V8_EXPORT RegisterExtension(Extension* extension);
6354 
6355 
6356 // --- Statics ---
6357 
6358 V8_INLINE Local<Primitive> Undefined(Isolate* isolate);
6359 V8_INLINE Local<Primitive> Null(Isolate* isolate);
6360 V8_INLINE Local<Boolean> True(Isolate* isolate);
6361 V8_INLINE Local<Boolean> False(Isolate* isolate);
6362 
6363 /**
6364  * A set of constraints that specifies the limits of the runtime's memory use.
6365  * You must set the heap size before initializing the VM - the size cannot be
6366  * adjusted after the VM is initialized.
6367  *
6368  * If you are using threads then you should hold the V8::Locker lock while
6369  * setting the stack limit and you must set a non-default stack limit separately
6370  * for each thread.
6371  *
6372  * The arguments for set_max_semi_space_size, set_max_old_space_size,
6373  * set_max_executable_size, set_code_range_size specify limits in MB.
6374  *
6375  * The argument for set_max_semi_space_size_in_kb is in KB.
6376  */
6377 class V8_EXPORT ResourceConstraints {
6378  public:
6379  ResourceConstraints();
6380 
6381  /**
6382  * Configures the constraints with reasonable default values based on the
6383  * capabilities of the current device the VM is running on.
6384  *
6385  * \param physical_memory The total amount of physical memory on the current
6386  * device, in bytes.
6387  * \param virtual_memory_limit The amount of virtual memory on the current
6388  * device, in bytes, or zero, if there is no limit.
6389  */
6390  void ConfigureDefaults(uint64_t physical_memory,
6391  uint64_t virtual_memory_limit);
6392 
6393  // Returns the max semi-space size in MB.
6394  V8_DEPRECATE_SOON("Use max_semi_space_size_in_kb()",
6395  size_t max_semi_space_size()) {
6396  return max_semi_space_size_in_kb_ / 1024;
6397  }
6398 
6399  // Sets the max semi-space size in MB.
6400  V8_DEPRECATE_SOON("Use set_max_semi_space_size_in_kb(size_t limit_in_kb)",
6401  void set_max_semi_space_size(size_t limit_in_mb)) {
6402  max_semi_space_size_in_kb_ = limit_in_mb * 1024;
6403  }
6404 
6405  // Returns the max semi-space size in KB.
6406  size_t max_semi_space_size_in_kb() const {
6407  return max_semi_space_size_in_kb_;
6408  }
6409 
6410  // Sets the max semi-space size in KB.
6411  void set_max_semi_space_size_in_kb(size_t limit_in_kb) {
6412  max_semi_space_size_in_kb_ = limit_in_kb;
6413  }
6414 
6415  size_t max_old_space_size() const { return max_old_space_size_; }
6416  void set_max_old_space_size(size_t limit_in_mb) {
6417  max_old_space_size_ = limit_in_mb;
6418  }
6419  V8_DEPRECATE_SOON("max_executable_size_ is subsumed by max_old_space_size_",
6420  size_t max_executable_size() const) {
6421  return max_executable_size_;
6422  }
6423  V8_DEPRECATE_SOON("max_executable_size_ is subsumed by max_old_space_size_",
6424  void set_max_executable_size(size_t limit_in_mb)) {
6425  max_executable_size_ = limit_in_mb;
6426  }
6427  uint32_t* stack_limit() const { return stack_limit_; }
6428  // Sets an address beyond which the VM's stack may not grow.
6429  void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
6430  size_t code_range_size() const { return code_range_size_; }
6431  void set_code_range_size(size_t limit_in_mb) {
6432  code_range_size_ = limit_in_mb;
6433  }
6434  size_t max_zone_pool_size() const { return max_zone_pool_size_; }
6435  void set_max_zone_pool_size(size_t bytes) { max_zone_pool_size_ = bytes; }
6436 
6437  private:
6438  // max_semi_space_size_ is in KB
6439  size_t max_semi_space_size_in_kb_;
6440 
6441  // The remaining limits are in MB
6442  size_t max_old_space_size_;
6443  size_t max_executable_size_;
6444  uint32_t* stack_limit_;
6445  size_t code_range_size_;
6446  size_t max_zone_pool_size_;
6447 };
6448 
6449 
6450 // --- Exceptions ---
6451 
6452 
6453 typedef void (*FatalErrorCallback)(const char* location, const char* message);
6454 
6455 typedef void (*OOMErrorCallback)(const char* location, bool is_heap_oom);
6456 
6457 typedef void (*DcheckErrorCallback)(const char* file, int line,
6458  const char* message);
6459 
6460 typedef void (*MessageCallback)(Local<Message> message, Local<Value> data);
6461 
6462 // --- Tracing ---
6463 
6464 typedef void (*LogEventCallback)(const char* name, int event);
6465 
6466 /**
6467  * Create new error objects by calling the corresponding error object
6468  * constructor with the message.
6469  */
6470 class V8_EXPORT Exception {
6471  public:
6472  static Local<Value> RangeError(Local<String> message);
6473  static Local<Value> ReferenceError(Local<String> message);
6474  static Local<Value> SyntaxError(Local<String> message);
6475  static Local<Value> TypeError(Local<String> message);
6476  static Local<Value> Error(Local<String> message);
6477 
6478  /**
6479  * Creates an error message for the given exception.
6480  * Will try to reconstruct the original stack trace from the exception value,
6481  * or capture the current stack trace if not available.
6482  */
6483  static Local<Message> CreateMessage(Isolate* isolate, Local<Value> exception);
6484 
6485  /**
6486  * Returns the original stack trace that was captured at the creation time
6487  * of a given exception, or an empty handle if not available.
6488  */
6489  static Local<StackTrace> GetStackTrace(Local<Value> exception);
6490 };
6491 
6492 
6493 // --- Counters Callbacks ---
6494 
6495 typedef int* (*CounterLookupCallback)(const char* name);
6496 
6497 typedef void* (*CreateHistogramCallback)(const char* name,
6498  int min,
6499  int max,
6500  size_t buckets);
6501 
6502 typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
6503 
6504 // --- Enter/Leave Script Callback ---
6505 typedef void (*BeforeCallEnteredCallback)(Isolate*);
6506 typedef void (*CallCompletedCallback)(Isolate*);
6507 
6508 /**
6509  * HostImportModuleDynamicallyCallback is called when we require the
6510  * embedder to load a module. This is used as part of the dynamic
6511  * import syntax.
6512  *
6513  * The referrer contains metadata about the script/module that calls
6514  * import.
6515  *
6516  * The specifier is the name of the module that should be imported.
6517  *
6518  * The embedder must compile, instantiate, evaluate the Module, and
6519  * obtain it's namespace object.
6520  *
6521  * The Promise returned from this function is forwarded to userland
6522  * JavaScript. The embedder must resolve this promise with the module
6523  * namespace object. In case of an exception, the embedder must reject
6524  * this promise with the exception. If the promise creation itself
6525  * fails (e.g. due to stack overflow), the embedder must propagate
6526  * that exception by returning an empty MaybeLocal.
6527  */
6528 typedef MaybeLocal<Promise> (*HostImportModuleDynamicallyCallback)(
6529  Local<Context> context, Local<ScriptOrModule> referrer,
6530  Local<String> specifier);
6531 
6532 /**
6533  * HostInitializeImportMetaObjectCallback is called the first time import.meta
6534  * is accessed for a module. Subsequent access will reuse the same value.
6535  *
6536  * The method combines two implementation-defined abstract operations into one:
6537  * HostGetImportMetaProperties and HostFinalizeImportMeta.
6538  *
6539  * The embedder should use v8::Object::CreateDataProperty to add properties on
6540  * the meta object.
6541  */
6542 typedef void (*HostInitializeImportMetaObjectCallback)(Local<Context> context,
6543  Local<Module> module,
6544  Local<Object> meta);
6545 
6546 /**
6547  * PromiseHook with type kInit is called when a new promise is
6548  * created. When a new promise is created as part of the chain in the
6549  * case of Promise.then or in the intermediate promises created by
6550  * Promise.{race, all}/AsyncFunctionAwait, we pass the parent promise
6551  * otherwise we pass undefined.
6552  *
6553  * PromiseHook with type kResolve is called at the beginning of
6554  * resolve or reject function defined by CreateResolvingFunctions.
6555  *
6556  * PromiseHook with type kBefore is called at the beginning of the
6557  * PromiseReactionJob.
6558  *
6559  * PromiseHook with type kAfter is called right at the end of the
6560  * PromiseReactionJob.
6561  */
6562 enum class PromiseHookType { kInit, kResolve, kBefore, kAfter };
6563 
6564 typedef void (*PromiseHook)(PromiseHookType type, Local<Promise> promise,
6565  Local<Value> parent);
6566 
6567 // --- Promise Reject Callback ---
6568 enum PromiseRejectEvent {
6569  kPromiseRejectWithNoHandler = 0,
6570  kPromiseHandlerAddedAfterReject = 1,
6571  kPromiseRejectAfterResolved = 2,
6572  kPromiseResolveAfterResolved = 3,
6573 };
6574 
6575 class PromiseRejectMessage {
6576  public:
6577  PromiseRejectMessage(Local<Promise> promise, PromiseRejectEvent event,
6578  Local<Value> value, Local<StackTrace> stack_trace)
6579  : promise_(promise),
6580  event_(event),
6581  value_(value),
6582  stack_trace_(stack_trace) {}
6583 
6584  V8_INLINE Local<Promise> GetPromise() const { return promise_; }
6585  V8_INLINE PromiseRejectEvent GetEvent() const { return event_; }
6586  V8_INLINE Local<Value> GetValue() const { return value_; }
6587 
6588  private:
6589  Local<Promise> promise_;
6590  PromiseRejectEvent event_;
6591  Local<Value> value_;
6592  Local<StackTrace> stack_trace_;
6593 };
6594 
6595 typedef void (*PromiseRejectCallback)(PromiseRejectMessage message);
6596 
6597 // --- Microtasks Callbacks ---
6598 typedef void (*MicrotasksCompletedCallback)(Isolate*);
6599 typedef void (*MicrotaskCallback)(void* data);
6600 
6601 
6602 /**
6603  * Policy for running microtasks:
6604  * - explicit: microtasks are invoked with Isolate::RunMicrotasks() method;
6605  * - scoped: microtasks invocation is controlled by MicrotasksScope objects;
6606  * - auto: microtasks are invoked when the script call depth decrements
6607  * to zero.
6608  */
6609 enum class MicrotasksPolicy { kExplicit, kScoped, kAuto };
6610 
6611 
6612 /**
6613  * This scope is used to control microtasks when kScopeMicrotasksInvocation
6614  * is used on Isolate. In this mode every non-primitive call to V8 should be
6615  * done inside some MicrotasksScope.
6616  * Microtasks are executed when topmost MicrotasksScope marked as kRunMicrotasks
6617  * exits.
6618  * kDoNotRunMicrotasks should be used to annotate calls not intended to trigger
6619  * microtasks.
6620  */
6621 class V8_EXPORT MicrotasksScope {
6622  public:
6623  enum Type { kRunMicrotasks, kDoNotRunMicrotasks };
6624 
6625  MicrotasksScope(Isolate* isolate, Type type);
6626  ~MicrotasksScope();
6627 
6628  /**
6629  * Runs microtasks if no kRunMicrotasks scope is currently active.
6630  */
6631  static void PerformCheckpoint(Isolate* isolate);
6632 
6633  /**
6634  * Returns current depth of nested kRunMicrotasks scopes.
6635  */
6636  static int GetCurrentDepth(Isolate* isolate);
6637 
6638  /**
6639  * Returns true while microtasks are being executed.
6640  */
6641  static bool IsRunningMicrotasks(Isolate* isolate);
6642 
6643  // Prevent copying.
6644  MicrotasksScope(const MicrotasksScope&) = delete;
6645  MicrotasksScope& operator=(const MicrotasksScope&) = delete;
6646 
6647  private:
6648  internal::Isolate* const isolate_;
6649  bool run_;
6650 };
6651 
6652 
6653 // --- Failed Access Check Callback ---
6654 typedef void (*FailedAccessCheckCallback)(Local<Object> target,
6655  AccessType type,
6656  Local<Value> data);
6657 
6658 // --- AllowCodeGenerationFromStrings callbacks ---
6659 
6660 /**
6661  * Callback to check if code generation from strings is allowed. See
6662  * Context::AllowCodeGenerationFromStrings.
6663  */
6664 typedef bool (*AllowCodeGenerationFromStringsCallback)(Local<Context> context,
6665  Local<String> source);
6666 
6667 // --- WebAssembly compilation callbacks ---
6668 typedef bool (*ExtensionCallback)(const FunctionCallbackInfo<Value>&);
6669 
6670 typedef bool (*AllowWasmCodeGenerationCallback)(Local<Context> context,
6671  Local<String> source);
6672 
6673 // --- Callback for APIs defined on v8-supported objects, but implemented
6674 // by the embedder. Example: WebAssembly.{compile|instantiate}Streaming ---
6675 typedef void (*ApiImplementationCallback)(const FunctionCallbackInfo<Value>&);
6676 
6677 // --- Callback for WebAssembly.compileStreaming ---
6678 typedef void (*WasmStreamingCallback)(const FunctionCallbackInfo<Value>&);
6679 
6680 // --- Callback for checking if WebAssembly threads are enabled ---
6681 typedef bool (*WasmThreadsEnabledCallback)(Local<Context> context);
6682 
6683 // --- Garbage Collection Callbacks ---
6684 
6685 /**
6686  * Applications can register callback functions which will be called before and
6687  * after certain garbage collection operations. Allocations are not allowed in
6688  * the callback functions, you therefore cannot manipulate objects (set or
6689  * delete properties for example) since it is possible such operations will
6690  * result in the allocation of objects.
6691  */
6692 enum GCType {
6693  kGCTypeScavenge = 1 << 0,
6694  kGCTypeMarkSweepCompact = 1 << 1,
6695  kGCTypeIncrementalMarking = 1 << 2,
6696  kGCTypeProcessWeakCallbacks = 1 << 3,
6697  kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact |
6698  kGCTypeIncrementalMarking | kGCTypeProcessWeakCallbacks
6699 };
6700 
6701 /**
6702  * GCCallbackFlags is used to notify additional information about the GC
6703  * callback.
6704  * - kGCCallbackFlagConstructRetainedObjectInfos: The GC callback is for
6705  * constructing retained object infos.
6706  * - kGCCallbackFlagForced: The GC callback is for a forced GC for testing.
6707  * - kGCCallbackFlagSynchronousPhantomCallbackProcessing: The GC callback
6708  * is called synchronously without getting posted to an idle task.
6709  * - kGCCallbackFlagCollectAllAvailableGarbage: The GC callback is called
6710  * in a phase where V8 is trying to collect all available garbage
6711  * (e.g., handling a low memory notification).
6712  * - kGCCallbackScheduleIdleGarbageCollection: The GC callback is called to
6713  * trigger an idle garbage collection.
6714  */
6715 enum GCCallbackFlags {
6716  kNoGCCallbackFlags = 0,
6717  kGCCallbackFlagConstructRetainedObjectInfos = 1 << 1,
6718  kGCCallbackFlagForced = 1 << 2,
6719  kGCCallbackFlagSynchronousPhantomCallbackProcessing = 1 << 3,
6720  kGCCallbackFlagCollectAllAvailableGarbage = 1 << 4,
6721  kGCCallbackFlagCollectAllExternalMemory = 1 << 5,
6722  kGCCallbackScheduleIdleGarbageCollection = 1 << 6,
6723 };
6724 
6725 typedef void (*GCCallback)(GCType type, GCCallbackFlags flags);
6726 
6727 typedef void (*InterruptCallback)(Isolate* isolate, void* data);
6728 
6729 /**
6730  * This callback is invoked when the heap size is close to the heap limit and
6731  * V8 is likely to abort with out-of-memory error.
6732  * The callback can extend the heap limit by returning a value that is greater
6733  * than the current_heap_limit. The initial heap limit is the limit that was
6734  * set after heap setup.
6735  */
6736 typedef size_t (*NearHeapLimitCallback)(void* data, size_t current_heap_limit,
6737  size_t initial_heap_limit);
6738 
6739 /**
6740  * Collection of V8 heap information.
6741  *
6742  * Instances of this class can be passed to v8::V8::HeapStatistics to
6743  * get heap statistics from V8.
6744  */
6745 class V8_EXPORT HeapStatistics {
6746  public:
6747  HeapStatistics();
6748  size_t total_heap_size() { return total_heap_size_; }
6749  size_t total_heap_size_executable() { return total_heap_size_executable_; }
6750  size_t total_physical_size() { return total_physical_size_; }
6751  size_t total_available_size() { return total_available_size_; }
6752  size_t used_heap_size() { return used_heap_size_; }
6753  size_t heap_size_limit() { return heap_size_limit_; }
6754  size_t malloced_memory() { return malloced_memory_; }
6755  size_t external_memory() { return external_memory_; }
6756  size_t peak_malloced_memory() { return peak_malloced_memory_; }
6757  size_t number_of_native_contexts() { return number_of_native_contexts_; }
6758  size_t number_of_detached_contexts() { return number_of_detached_contexts_; }
6759 
6760  /**
6761  * Returns a 0/1 boolean, which signifies whether the V8 overwrite heap
6762  * garbage with a bit pattern.
6763  */
6764  size_t does_zap_garbage() { return does_zap_garbage_; }
6765 
6766  private:
6767  size_t total_heap_size_;
6768  size_t total_heap_size_executable_;
6769  size_t total_physical_size_;
6770  size_t total_available_size_;
6771  size_t used_heap_size_;
6772  size_t heap_size_limit_;
6773  size_t malloced_memory_;
6774  size_t external_memory_;
6775  size_t peak_malloced_memory_;
6776  bool does_zap_garbage_;
6777  size_t number_of_native_contexts_;
6778  size_t number_of_detached_contexts_;
6779 
6780  friend class V8;
6781  friend class Isolate;
6782 };
6783 
6784 
6785 class V8_EXPORT HeapSpaceStatistics {
6786  public:
6787  HeapSpaceStatistics();
6788  const char* space_name() { return space_name_; }
6789  size_t space_size() { return space_size_; }
6790  size_t space_used_size() { return space_used_size_; }
6791  size_t space_available_size() { return space_available_size_; }
6792  size_t physical_space_size() { return physical_space_size_; }
6793 
6794  private:
6795  const char* space_name_;
6796  size_t space_size_;
6797  size_t space_used_size_;
6798  size_t space_available_size_;
6799  size_t physical_space_size_;
6800 
6801  friend class Isolate;
6802 };
6803 
6804 
6805 class V8_EXPORT HeapObjectStatistics {
6806  public:
6807  HeapObjectStatistics();
6808  const char* object_type() { return object_type_; }
6809  const char* object_sub_type() { return object_sub_type_; }
6810  size_t object_count() { return object_count_; }
6811  size_t object_size() { return object_size_; }
6812 
6813  private:
6814  const char* object_type_;
6815  const char* object_sub_type_;
6816  size_t object_count_;
6817  size_t object_size_;
6818 
6819  friend class Isolate;
6820 };
6821 
6822 class V8_EXPORT HeapCodeStatistics {
6823  public:
6824  HeapCodeStatistics();
6825  size_t code_and_metadata_size() { return code_and_metadata_size_; }
6826  size_t bytecode_and_metadata_size() { return bytecode_and_metadata_size_; }
6827  size_t external_script_source_size() { return external_script_source_size_; }
6828 
6829  private:
6830  size_t code_and_metadata_size_;
6831  size_t bytecode_and_metadata_size_;
6832  size_t external_script_source_size_;
6833 
6834  friend class Isolate;
6835 };
6836 
6837 class RetainedObjectInfo;
6838 
6839 
6840 /**
6841  * FunctionEntryHook is the type of the profile entry hook called at entry to
6842  * any generated function when function-level profiling is enabled.
6843  *
6844  * \param function the address of the function that's being entered.
6845  * \param return_addr_location points to a location on stack where the machine
6846  * return address resides. This can be used to identify the caller of
6847  * \p function, and/or modified to divert execution when \p function exits.
6848  *
6849  * \note the entry hook must not cause garbage collection.
6850  */
6851 typedef void (*FunctionEntryHook)(uintptr_t function,
6852  uintptr_t return_addr_location);
6853 
6854 /**
6855  * A JIT code event is issued each time code is added, moved or removed.
6856  *
6857  * \note removal events are not currently issued.
6858  */
6859 struct JitCodeEvent {
6860  enum EventType {
6861  CODE_ADDED,
6862  CODE_MOVED,
6863  CODE_REMOVED,
6864  CODE_ADD_LINE_POS_INFO,
6865  CODE_START_LINE_INFO_RECORDING,
6866  CODE_END_LINE_INFO_RECORDING
6867  };
6868  // Definition of the code position type. The "POSITION" type means the place
6869  // in the source code which are of interest when making stack traces to
6870  // pin-point the source location of a stack frame as close as possible.
6871  // The "STATEMENT_POSITION" means the place at the beginning of each
6872  // statement, and is used to indicate possible break locations.
6873  enum PositionType { POSITION, STATEMENT_POSITION };
6874 
6875  // There are two different kinds of JitCodeEvents, one for JIT code generated
6876  // by the optimizing compiler, and one for byte code generated for the
6877  // interpreter. For JIT_CODE events, the |code_start| member of the event
6878  // points to the beginning of jitted assembly code, while for BYTE_CODE
6879  // events, |code_start| points to the first bytecode of the interpreted
6880  // function.
6881  enum CodeType { BYTE_CODE, JIT_CODE };
6882 
6883  // Type of event.
6884  EventType type;
6885  CodeType code_type;
6886  // Start of the instructions.
6887  void* code_start;
6888  // Size of the instructions.
6889  size_t code_len;
6890  // Script info for CODE_ADDED event.
6891  Local<UnboundScript> script;
6892  // User-defined data for *_LINE_INFO_* event. It's used to hold the source
6893  // code line information which is returned from the
6894  // CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent
6895  // CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events.
6896  void* user_data;
6897 
6898  struct name_t {
6899  // Name of the object associated with the code, note that the string is not
6900  // zero-terminated.
6901  const char* str;
6902  // Number of chars in str.
6903  size_t len;
6904  };
6905 
6906  struct line_info_t {
6907  // PC offset
6908  size_t offset;
6909  // Code position
6910  size_t pos;
6911  // The position type.
6912  PositionType position_type;
6913  };
6914 
6915  union {
6916  // Only valid for CODE_ADDED.
6917  struct name_t name;
6918 
6919  // Only valid for CODE_ADD_LINE_POS_INFO
6920  struct line_info_t line_info;
6921 
6922  // New location of instructions. Only valid for CODE_MOVED.
6923  void* new_code_start;
6924  };
6925 
6926  Isolate* isolate;
6927 };
6928 
6929 /**
6930  * Option flags passed to the SetRAILMode function.
6931  * See documentation https://developers.google.com/web/tools/chrome-devtools/
6932  * profile/evaluate-performance/rail
6933  */
6934 enum RAILMode {
6935  // Response performance mode: In this mode very low virtual machine latency
6936  // is provided. V8 will try to avoid JavaScript execution interruptions.
6937  // Throughput may be throttled.
6938  PERFORMANCE_RESPONSE,
6939  // Animation performance mode: In this mode low virtual machine latency is
6940  // provided. V8 will try to avoid as many JavaScript execution interruptions
6941  // as possible. Throughput may be throttled. This is the default mode.
6942  PERFORMANCE_ANIMATION,
6943  // Idle performance mode: The embedder is idle. V8 can complete deferred work
6944  // in this mode.
6945  PERFORMANCE_IDLE,
6946  // Load performance mode: In this mode high throughput is provided. V8 may
6947  // turn off latency optimizations.
6948  PERFORMANCE_LOAD
6949 };
6950 
6951 /**
6952  * Option flags passed to the SetJitCodeEventHandler function.
6953  */
6954 enum JitCodeEventOptions {
6955  kJitCodeEventDefault = 0,
6956  // Generate callbacks for already existent code.
6957  kJitCodeEventEnumExisting = 1
6958 };
6959 
6960 
6961 /**
6962  * Callback function passed to SetJitCodeEventHandler.
6963  *
6964  * \param event code add, move or removal event.
6965  */
6966 typedef void (*JitCodeEventHandler)(const JitCodeEvent* event);
6967 
6968 
6969 /**
6970  * Interface for iterating through all external resources in the heap.
6971  */
6972 class V8_EXPORT ExternalResourceVisitor { // NOLINT
6973  public:
6974  virtual ~ExternalResourceVisitor() {}
6975  virtual void VisitExternalString(Local<String> string) {}
6976 };
6977 
6978 
6979 /**
6980  * Interface for iterating through all the persistent handles in the heap.
6981  */
6982 class V8_EXPORT PersistentHandleVisitor { // NOLINT
6983  public:
6984  virtual ~PersistentHandleVisitor() {}
6985  virtual void VisitPersistentHandle(Persistent<Value>* value,
6986  uint16_t class_id) {}
6987 };
6988 
6989 /**
6990  * Memory pressure level for the MemoryPressureNotification.
6991  * kNone hints V8 that there is no memory pressure.
6992  * kModerate hints V8 to speed up incremental garbage collection at the cost of
6993  * of higher latency due to garbage collection pauses.
6994  * kCritical hints V8 to free memory as soon as possible. Garbage collection
6995  * pauses at this level will be large.
6996  */
6997 enum class MemoryPressureLevel { kNone, kModerate, kCritical };
6998 
6999 /**
7000  * Interface for tracing through the embedder heap. During a V8 garbage
7001  * collection, V8 collects hidden fields of all potential wrappers, and at the
7002  * end of its marking phase iterates the collection and asks the embedder to
7003  * trace through its heap and use reporter to report each JavaScript object
7004  * reachable from any of the given wrappers.
7005  */
7006 class V8_EXPORT EmbedderHeapTracer {
7007  public:
7008  // Indicator for the stack state of the embedder.
7009  enum EmbedderStackState {
7010  kUnknown,
7011  kNonEmpty,
7012  kEmpty,
7013  };
7014 
7015  enum ForceCompletionAction { FORCE_COMPLETION, DO_NOT_FORCE_COMPLETION };
7016 
7018  explicit AdvanceTracingActions(ForceCompletionAction force_completion_)
7019  : force_completion(force_completion_) {}
7020 
7021  ForceCompletionAction force_completion;
7022  };
7023 
7024  virtual ~EmbedderHeapTracer() = default;
7025 
7026  /**
7027  * Called by v8 to register internal fields of found wrappers.
7028  *
7029  * The embedder is expected to store them somewhere and trace reachable
7030  * wrappers from them when called through |AdvanceTracing|.
7031  */
7032  virtual void RegisterV8References(
7033  const std::vector<std::pair<void*, void*> >& embedder_fields) = 0;
7034 
7035  /**
7036  * Called at the beginning of a GC cycle.
7037  */
7038  virtual void TracePrologue() = 0;
7039 
7040  /**
7041  * Called to make a tracing step in the embedder.
7042  *
7043  * The embedder is expected to trace its heap starting from wrappers reported
7044  * by RegisterV8References method, and report back all reachable wrappers.
7045  * Furthermore, the embedder is expected to stop tracing by the given
7046  * deadline.
7047  *
7048  * Returns true if there is still work to do.
7049  *
7050  * Note: Only one of the AdvanceTracing methods needs to be overriden by the
7051  * embedder.
7052  */
7053  V8_DEPRECATE_SOON("Use void AdvanceTracing(deadline_in_ms)",
7054  virtual bool AdvanceTracing(
7055  double deadline_in_ms, AdvanceTracingActions actions)) {
7056  return false;
7057  }
7058 
7059  /**
7060  * Called to advance tracing in the embedder.
7061  *
7062  * The embedder is expected to trace its heap starting from wrappers reported
7063  * by RegisterV8References method, and report back all reachable wrappers.
7064  * Furthermore, the embedder is expected to stop tracing by the given
7065  * deadline. A deadline of infinity means that tracing should be finished.
7066  *
7067  * Returns |true| if tracing is done, and false otherwise.
7068  *
7069  * Note: Only one of the AdvanceTracing methods needs to be overriden by the
7070  * embedder.
7071  */
7072  virtual bool AdvanceTracing(double deadline_in_ms);
7073 
7074  /*
7075  * Returns true if there no more tracing work to be done (see AdvanceTracing)
7076  * and false otherwise.
7077  */
7078  virtual bool IsTracingDone();
7079 
7080  /**
7081  * Called at the end of a GC cycle.
7082  *
7083  * Note that allocation is *not* allowed within |TraceEpilogue|.
7084  */
7085  virtual void TraceEpilogue() = 0;
7086 
7087  /**
7088  * Called upon entering the final marking pause. No more incremental marking
7089  * steps will follow this call.
7090  *
7091  * Note: Only one of the EnterFinalPause methods needs to be overriden by the
7092  * embedder.
7093  */
7094  V8_DEPRECATE_SOON("Use void EnterFinalPause(EmbedderStackState)",
7095  virtual void EnterFinalPause()) {}
7096  virtual void EnterFinalPause(EmbedderStackState stack_state);
7097 
7098  /**
7099  * Called when tracing is aborted.
7100  *
7101  * The embedder is expected to throw away all intermediate data and reset to
7102  * the initial state.
7103  */
7104  virtual void AbortTracing() = 0;
7105 
7106  /*
7107  * Called by the embedder to request immediate finalization of the currently
7108  * running tracing phase that has been started with TracePrologue and not
7109  * yet finished with TraceEpilogue.
7110  *
7111  * Will be a noop when currently not in tracing.
7112  *
7113  * This is an experimental feature.
7114  */
7115  void FinalizeTracing();
7116 
7117  /*
7118  * Called by the embedder to immediately perform a full garbage collection.
7119  *
7120  * Should only be used in testing code.
7121  */
7122  void GarbageCollectionForTesting(EmbedderStackState stack_state);
7123 
7124  /*
7125  * Returns the v8::Isolate this tracer is attached too and |nullptr| if it
7126  * is not attached to any v8::Isolate.
7127  */
7128  v8::Isolate* isolate() const { return isolate_; }
7129 
7130  /**
7131  * Returns the number of wrappers that are still to be traced by the embedder.
7132  */
7133  V8_DEPRECATE_SOON("Use IsTracingDone",
7134  virtual size_t NumberOfWrappersToTrace()) {
7135  return 0;
7136  }
7137 
7138  protected:
7139  v8::Isolate* isolate_ = nullptr;
7140 
7141  friend class internal::LocalEmbedderHeapTracer;
7142 };
7143 
7144 /**
7145  * Callback and supporting data used in SnapshotCreator to implement embedder
7146  * logic to serialize internal fields.
7147  */
7148 struct SerializeInternalFieldsCallback {
7149  typedef StartupData (*CallbackFunction)(Local<Object> holder, int index,
7150  void* data);
7151  SerializeInternalFieldsCallback(CallbackFunction function = nullptr,
7152  void* data_arg = nullptr)
7153  : callback(function), data(data_arg) {}
7154  CallbackFunction callback;
7155  void* data;
7156 };
7157 // Note that these fields are called "internal fields" in the API and called
7158 // "embedder fields" within V8.
7159 typedef SerializeInternalFieldsCallback SerializeEmbedderFieldsCallback;
7160 
7161 /**
7162  * Callback and supporting data used to implement embedder logic to deserialize
7163  * internal fields.
7164  */
7165 struct DeserializeInternalFieldsCallback {
7166  typedef void (*CallbackFunction)(Local<Object> holder, int index,
7167  StartupData payload, void* data);
7168  DeserializeInternalFieldsCallback(CallbackFunction function = nullptr,
7169  void* data_arg = nullptr)
7170  : callback(function), data(data_arg) {}
7171  void (*callback)(Local<Object> holder, int index, StartupData payload,
7172  void* data);
7173  void* data;
7174 };
7175 typedef DeserializeInternalFieldsCallback DeserializeEmbedderFieldsCallback;
7176 
7177 /**
7178  * Isolate represents an isolated instance of the V8 engine. V8 isolates have
7179  * completely separate states. Objects from one isolate must not be used in
7180  * other isolates. The embedder can create multiple isolates and use them in
7181  * parallel in multiple threads. An isolate can be entered by at most one
7182  * thread at any given time. The Locker/Unlocker API must be used to
7183  * synchronize.
7184  */
7185 class V8_EXPORT Isolate {
7186  public:
7187  /**
7188  * Initial configuration parameters for a new Isolate.
7189  */
7190  struct CreateParams {
7192  : entry_hook(nullptr),
7193  code_event_handler(nullptr),
7194  snapshot_blob(nullptr),
7195  counter_lookup_callback(nullptr),
7196  create_histogram_callback(nullptr),
7198  array_buffer_allocator(nullptr),
7199  external_references(nullptr),
7200  allow_atomics_wait(true),
7202 
7203  /**
7204  * The optional entry_hook allows the host application to provide the
7205  * address of a function that's invoked on entry to every V8-generated
7206  * function. Note that entry_hook is invoked at the very start of each
7207  * generated function.
7208  * An entry_hook can only be provided in no-snapshot builds; in snapshot
7209  * builds it must be nullptr.
7210  */
7211  FunctionEntryHook entry_hook;
7212 
7213  /**
7214  * Allows the host application to provide the address of a function that is
7215  * notified each time code is added, moved or removed.
7216  */
7217  JitCodeEventHandler code_event_handler;
7218 
7219  /**
7220  * ResourceConstraints to use for the new Isolate.
7221  */
7222  ResourceConstraints constraints;
7223 
7224  /**
7225  * Explicitly specify a startup snapshot blob. The embedder owns the blob.
7226  */
7227  StartupData* snapshot_blob;
7228 
7229 
7230  /**
7231  * Enables the host application to provide a mechanism for recording
7232  * statistics counters.
7233  */
7234  CounterLookupCallback counter_lookup_callback;
7235 
7236  /**
7237  * Enables the host application to provide a mechanism for recording
7238  * histograms. The CreateHistogram function returns a
7239  * histogram which will later be passed to the AddHistogramSample
7240  * function.
7241  */
7242  CreateHistogramCallback create_histogram_callback;
7243  AddHistogramSampleCallback add_histogram_sample_callback;
7244 
7245  /**
7246  * The ArrayBuffer::Allocator to use for allocating and freeing the backing
7247  * store of ArrayBuffers.
7248  */
7250 
7251  /**
7252  * Specifies an optional nullptr-terminated array of raw addresses in the
7253  * embedder that V8 can match against during serialization and use for
7254  * deserialization. This array and its content must stay valid for the
7255  * entire lifetime of the isolate.
7256  */
7257  const intptr_t* external_references;
7258 
7259  /**
7260  * Whether calling Atomics.wait (a function that may block) is allowed in
7261  * this isolate. This can also be configured via SetAllowAtomicsWait.
7262  */
7264 
7265  /**
7266  * Termination is postponed when there is no active SafeForTerminationScope.
7267  */
7269  };
7270 
7271 
7272  /**
7273  * Stack-allocated class which sets the isolate for all operations
7274  * executed within a local scope.
7275  */
7277  public:
7278  explicit Scope(Isolate* isolate) : isolate_(isolate) {
7279  isolate->Enter();
7280  }
7281 
7282  ~Scope() { isolate_->Exit(); }
7283 
7284  // Prevent copying of Scope objects.
7285  Scope(const Scope&) = delete;
7286  Scope& operator=(const Scope&) = delete;
7287 
7288  private:
7289  Isolate* const isolate_;
7290  };
7291 
7292 
7293  /**
7294  * Assert that no Javascript code is invoked.
7295  */
7297  public:
7299 
7300  DisallowJavascriptExecutionScope(Isolate* isolate, OnFailure on_failure);
7302 
7303  // Prevent copying of Scope objects.
7305  delete;
7307  const DisallowJavascriptExecutionScope&) = delete;
7308 
7309  private:
7310  bool on_failure_;
7311  void* internal_;
7312  };
7313 
7314 
7315  /**
7316  * Introduce exception to DisallowJavascriptExecutionScope.
7317  */
7319  public:
7320  explicit AllowJavascriptExecutionScope(Isolate* isolate);
7322 
7323  // Prevent copying of Scope objects.
7325  delete;
7327  const AllowJavascriptExecutionScope&) = delete;
7328 
7329  private:
7330  void* internal_throws_;
7331  void* internal_assert_;
7332  };
7333 
7334  /**
7335  * Do not run microtasks while this scope is active, even if microtasks are
7336  * automatically executed otherwise.
7337  */
7339  public:
7340  explicit SuppressMicrotaskExecutionScope(Isolate* isolate);
7342 
7343  // Prevent copying of Scope objects.
7345  delete;
7347  const SuppressMicrotaskExecutionScope&) = delete;
7348 
7349  private:
7350  internal::Isolate* const isolate_;
7351  };
7352 
7353  /**
7354  * This scope allows terminations inside direct V8 API calls and forbid them
7355  * inside any recursice API calls without explicit SafeForTerminationScope.
7356  */
7358  public:
7359  explicit SafeForTerminationScope(v8::Isolate* isolate);
7361 
7362  // Prevent copying of Scope objects.
7365 
7366  private:
7367  internal::Isolate* isolate_;
7368  bool prev_value_;
7369  };
7370 
7371  /**
7372  * Types of garbage collections that can be requested via
7373  * RequestGarbageCollectionForTesting.
7374  */
7375  enum GarbageCollectionType {
7376  kFullGarbageCollection,
7377  kMinorGarbageCollection
7378  };
7379 
7380  /**
7381  * Features reported via the SetUseCounterCallback callback. Do not change
7382  * assigned numbers of existing items; add new features to the end of this
7383  * list.
7384  */
7385  enum UseCounterFeature {
7386  kUseAsm = 0,
7387  kBreakIterator = 1,
7388  kLegacyConst = 2,
7389  kMarkDequeOverflow = 3,
7390  kStoreBufferOverflow = 4,
7391  kSlotsBufferOverflow = 5,
7392  kObjectObserve = 6,
7393  kForcedGC = 7,
7394  kSloppyMode = 8,
7395  kStrictMode = 9,
7396  kStrongMode = 10,
7397  kRegExpPrototypeStickyGetter = 11,
7398  kRegExpPrototypeToString = 12,
7399  kRegExpPrototypeUnicodeGetter = 13,
7400  kIntlV8Parse = 14,
7401  kIntlPattern = 15,
7402  kIntlResolved = 16,
7403  kPromiseChain = 17,
7404  kPromiseAccept = 18,
7405  kPromiseDefer = 19,
7406  kHtmlCommentInExternalScript = 20,
7407  kHtmlComment = 21,
7408  kSloppyModeBlockScopedFunctionRedefinition = 22,
7409  kForInInitializer = 23,
7410  kArrayProtectorDirtied = 24,
7411  kArraySpeciesModified = 25,
7412  kArrayPrototypeConstructorModified = 26,
7413  kArrayInstanceProtoModified = 27,
7414  kArrayInstanceConstructorModified = 28,
7415  kLegacyFunctionDeclaration = 29,
7416  kRegExpPrototypeSourceGetter = 30,
7417  kRegExpPrototypeOldFlagGetter = 31,
7418  kDecimalWithLeadingZeroInStrictMode = 32,
7419  kLegacyDateParser = 33,
7420  kDefineGetterOrSetterWouldThrow = 34,
7421  kFunctionConstructorReturnedUndefined = 35,
7422  kAssigmentExpressionLHSIsCallInSloppy = 36,
7423  kAssigmentExpressionLHSIsCallInStrict = 37,
7424  kPromiseConstructorReturnedUndefined = 38,
7425  kConstructorNonUndefinedPrimitiveReturn = 39,
7426  kLabeledExpressionStatement = 40,
7427  kLineOrParagraphSeparatorAsLineTerminator = 41,
7428  kIndexAccessor = 42,
7429  kErrorCaptureStackTrace = 43,
7430  kErrorPrepareStackTrace = 44,
7431  kErrorStackTraceLimit = 45,
7432  kWebAssemblyInstantiation = 46,
7433  kDeoptimizerDisableSpeculation = 47,
7434  kArrayPrototypeSortJSArrayModifiedPrototype = 48,
7435  kFunctionTokenOffsetTooLongForToString = 49,
7436  kWasmSharedMemory = 50,
7437  kWasmThreadOpcodes = 51,
7438 
7439  // If you add new values here, you'll also need to update Chromium's:
7440  // web_feature.mojom, UseCounterCallback.cpp, and enums.xml. V8 changes to
7441  // this list need to be landed first, then changes on the Chromium side.
7442  kUseCounterFeatureCount // This enum value must be last.
7443  };
7444 
7445  enum MessageErrorLevel {
7446  kMessageLog = (1 << 0),
7447  kMessageDebug = (1 << 1),
7448  kMessageInfo = (1 << 2),
7449  kMessageError = (1 << 3),
7450  kMessageWarning = (1 << 4),
7451  kMessageAll = kMessageLog | kMessageDebug | kMessageInfo | kMessageError |
7452  kMessageWarning,
7453  };
7454 
7455  typedef void (*UseCounterCallback)(Isolate* isolate,
7456  UseCounterFeature feature);
7457 
7458  /**
7459  * Allocates a new isolate but does not initialize it. Does not change the
7460  * currently entered isolate.
7461  *
7462  * Only Isolate::GetData() and Isolate::SetData(), which access the
7463  * embedder-controlled parts of the isolate, are allowed to be called on the
7464  * uninitialized isolate. To initialize the isolate, call
7465  * Isolate::Initialize().
7466  *
7467  * When an isolate is no longer used its resources should be freed
7468  * by calling Dispose(). Using the delete operator is not allowed.
7469  *
7470  * V8::Initialize() must have run prior to this.
7471  */
7472  static Isolate* Allocate();
7473 
7474  /**
7475  * Initialize an Isolate previously allocated by Isolate::Allocate().
7476  */
7477  static void Initialize(Isolate* isolate, const CreateParams& params);
7478 
7479  /**
7480  * Creates a new isolate. Does not change the currently entered
7481  * isolate.
7482  *
7483  * When an isolate is no longer used its resources should be freed
7484  * by calling Dispose(). Using the delete operator is not allowed.
7485  *
7486  * V8::Initialize() must have run prior to this.
7487  */
7488  static Isolate* New(const CreateParams& params);
7489 
7490  /**
7491  * Returns the entered isolate for the current thread or NULL in
7492  * case there is no current isolate.
7493  *
7494  * This method must not be invoked before V8::Initialize() was invoked.
7495  */
7496  static Isolate* GetCurrent();
7497 
7498  /**
7499  * Custom callback used by embedders to help V8 determine if it should abort
7500  * when it throws and no internal handler is predicted to catch the
7501  * exception. If --abort-on-uncaught-exception is used on the command line,
7502  * then V8 will abort if either:
7503  * - no custom callback is set.
7504  * - the custom callback set returns true.
7505  * Otherwise, the custom callback will not be called and V8 will not abort.
7506  */
7507  typedef bool (*AbortOnUncaughtExceptionCallback)(Isolate*);
7508  void SetAbortOnUncaughtExceptionCallback(
7509  AbortOnUncaughtExceptionCallback callback);
7510 
7511  /**
7512  * This specifies the callback called by the upcoming dynamic
7513  * import() language feature to load modules.
7514  */
7515  void SetHostImportModuleDynamicallyCallback(
7516  HostImportModuleDynamicallyCallback callback);
7517 
7518  /**
7519  * This specifies the callback called by the upcoming importa.meta
7520  * language feature to retrieve host-defined meta data for a module.
7521  */
7522  void SetHostInitializeImportMetaObjectCallback(
7523  HostInitializeImportMetaObjectCallback callback);
7524 
7525  /**
7526  * Optional notification that the system is running low on memory.
7527  * V8 uses these notifications to guide heuristics.
7528  * It is allowed to call this function from another thread while
7529  * the isolate is executing long running JavaScript code.
7530  */
7531  void MemoryPressureNotification(MemoryPressureLevel level);
7532 
7533  /**
7534  * Methods below this point require holding a lock (using Locker) in
7535  * a multi-threaded environment.
7536  */
7537 
7538  /**
7539  * Sets this isolate as the entered one for the current thread.
7540  * Saves the previously entered one (if any), so that it can be
7541  * restored when exiting. Re-entering an isolate is allowed.
7542  */
7543  void Enter();
7544 
7545  /**
7546  * Exits this isolate by restoring the previously entered one in the
7547  * current thread. The isolate may still stay the same, if it was
7548  * entered more than once.
7549  *
7550  * Requires: this == Isolate::GetCurrent().
7551  */
7552  void Exit();
7553 
7554  /**
7555  * Disposes the isolate. The isolate must not be entered by any
7556  * thread to be disposable.
7557  */
7558  void Dispose();
7559 
7560  /**
7561  * Dumps activated low-level V8 internal stats. This can be used instead
7562  * of performing a full isolate disposal.
7563  */
7564  void DumpAndResetStats();
7565 
7566  /**
7567  * Discards all V8 thread-specific data for the Isolate. Should be used
7568  * if a thread is terminating and it has used an Isolate that will outlive
7569  * the thread -- all thread-specific data for an Isolate is discarded when
7570  * an Isolate is disposed so this call is pointless if an Isolate is about
7571  * to be Disposed.
7572  */
7573  void DiscardThreadSpecificMetadata();
7574 
7575  /**
7576  * Associate embedder-specific data with the isolate. |slot| has to be
7577  * between 0 and GetNumberOfDataSlots() - 1.
7578  */
7579  V8_INLINE void SetData(uint32_t slot, void* data);
7580 
7581  /**
7582  * Retrieve embedder-specific data from the isolate.
7583  * Returns NULL if SetData has never been called for the given |slot|.
7584  */
7585  V8_INLINE void* GetData(uint32_t slot);
7586 
7587  /**
7588  * Returns the maximum number of available embedder data slots. Valid slots
7589  * are in the range of 0 - GetNumberOfDataSlots() - 1.
7590  */
7591  V8_INLINE static uint32_t GetNumberOfDataSlots();
7592 
7593  /**
7594  * Return data that was previously attached to the isolate snapshot via
7595  * SnapshotCreator, and removes the reference to it.
7596  * Repeated call with the same index returns an empty MaybeLocal.
7597  */
7598  template <class T>
7599  V8_INLINE MaybeLocal<T> GetDataFromSnapshotOnce(size_t index);
7600 
7601  /**
7602  * Get statistics about the heap memory usage.
7603  */
7604  void GetHeapStatistics(HeapStatistics* heap_statistics);
7605 
7606  /**
7607  * Returns the number of spaces in the heap.
7608  */
7609  size_t NumberOfHeapSpaces();
7610 
7611  /**
7612  * Get the memory usage of a space in the heap.
7613  *
7614  * \param space_statistics The HeapSpaceStatistics object to fill in
7615  * statistics.
7616  * \param index The index of the space to get statistics from, which ranges
7617  * from 0 to NumberOfHeapSpaces() - 1.
7618  * \returns true on success.
7619  */
7620  bool GetHeapSpaceStatistics(HeapSpaceStatistics* space_statistics,
7621  size_t index);
7622 
7623  /**
7624  * Returns the number of types of objects tracked in the heap at GC.
7625  */
7626  size_t NumberOfTrackedHeapObjectTypes();
7627 
7628  /**
7629  * Get statistics about objects in the heap.
7630  *
7631  * \param object_statistics The HeapObjectStatistics object to fill in
7632  * statistics of objects of given type, which were live in the previous GC.
7633  * \param type_index The index of the type of object to fill details about,
7634  * which ranges from 0 to NumberOfTrackedHeapObjectTypes() - 1.
7635  * \returns true on success.
7636  */
7637  bool GetHeapObjectStatisticsAtLastGC(HeapObjectStatistics* object_statistics,
7638  size_t type_index);
7639 
7640  /**
7641  * Get statistics about code and its metadata in the heap.
7642  *
7643  * \param object_statistics The HeapCodeStatistics object to fill in
7644  * statistics of code, bytecode and their metadata.
7645  * \returns true on success.
7646  */
7647  bool GetHeapCodeAndMetadataStatistics(HeapCodeStatistics* object_statistics);
7648 
7649  /**
7650  * Get a call stack sample from the isolate.
7651  * \param state Execution state.
7652  * \param frames Caller allocated buffer to store stack frames.
7653  * \param frames_limit Maximum number of frames to capture. The buffer must
7654  * be large enough to hold the number of frames.
7655  * \param sample_info The sample info is filled up by the function
7656  * provides number of actual captured stack frames and
7657  * the current VM state.
7658  * \note GetStackSample should only be called when the JS thread is paused or
7659  * interrupted. Otherwise the behavior is undefined.
7660  */
7661  void GetStackSample(const RegisterState& state, void** frames,
7662  size_t frames_limit, SampleInfo* sample_info);
7663 
7664  /**
7665  * Adjusts the amount of registered external memory. Used to give V8 an
7666  * indication of the amount of externally allocated memory that is kept alive
7667  * by JavaScript objects. V8 uses this to decide when to perform global
7668  * garbage collections. Registering externally allocated memory will trigger
7669  * global garbage collections more often than it would otherwise in an attempt
7670  * to garbage collect the JavaScript objects that keep the externally
7671  * allocated memory alive.
7672  *
7673  * \param change_in_bytes the change in externally allocated memory that is
7674  * kept alive by JavaScript objects.
7675  * \returns the adjusted value.
7676  */
7677  V8_INLINE int64_t
7678  AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes);
7679 
7680  /**
7681  * Returns the number of phantom handles without callbacks that were reset
7682  * by the garbage collector since the last call to this function.
7683  */
7684  size_t NumberOfPhantomHandleResetsSinceLastCall();
7685 
7686  /**
7687  * Returns heap profiler for this isolate. Will return NULL until the isolate
7688  * is initialized.
7689  */
7690  HeapProfiler* GetHeapProfiler();
7691 
7692  /**
7693  * Tells the VM whether the embedder is idle or not.
7694  */
7695  void SetIdle(bool is_idle);
7696 
7697  /** Returns true if this isolate has a current context. */
7698  bool InContext();
7699 
7700  /**
7701  * Returns the context of the currently running JavaScript, or the context
7702  * on the top of the stack if no JavaScript is running.
7703  */
7704  Local<Context> GetCurrentContext();
7705 
7706  /** Returns the last context entered through V8's C++ API. */
7707  Local<Context> GetEnteredContext();
7708 
7709  /**
7710  * Returns either the last context entered through V8's C++ API, or the
7711  * context of the currently running microtask while processing microtasks.
7712  * If a context is entered while executing a microtask, that context is
7713  * returned.
7714  */
7715  Local<Context> GetEnteredOrMicrotaskContext();
7716 
7717  /**
7718  * Returns the Context that corresponds to the Incumbent realm in HTML spec.
7719  * https://html.spec.whatwg.org/multipage/webappapis.html#incumbent
7720  */
7721  Local<Context> GetIncumbentContext();
7722 
7723  /**
7724  * Schedules an exception to be thrown when returning to JavaScript. When an
7725  * exception has been scheduled it is illegal to invoke any JavaScript
7726  * operation; the caller must return immediately and only after the exception
7727  * has been handled does it become legal to invoke JavaScript operations.
7728  */
7729  Local<Value> ThrowException(Local<Value> exception);
7730 
7731  typedef void (*GCCallback)(Isolate* isolate, GCType type,
7732  GCCallbackFlags flags);
7733  typedef void (*GCCallbackWithData)(Isolate* isolate, GCType type,
7734  GCCallbackFlags flags, void* data);
7735 
7736  /**
7737  * Enables the host application to receive a notification before a
7738  * garbage collection. Allocations are allowed in the callback function,
7739  * but the callback is not re-entrant: if the allocation inside it will
7740  * trigger the garbage collection, the callback won't be called again.
7741  * It is possible to specify the GCType filter for your callback. But it is
7742  * not possible to register the same callback function two times with
7743  * different GCType filters.
7744  */
7745  void AddGCPrologueCallback(GCCallbackWithData callback, void* data = nullptr,
7746  GCType gc_type_filter = kGCTypeAll);
7747  void AddGCPrologueCallback(GCCallback callback,
7748  GCType gc_type_filter = kGCTypeAll);
7749 
7750  /**
7751  * This function removes callback which was installed by
7752  * AddGCPrologueCallback function.
7753  */
7754  void RemoveGCPrologueCallback(GCCallbackWithData, void* data = nullptr);
7755  void RemoveGCPrologueCallback(GCCallback callback);
7756 
7757  /**
7758  * Sets the embedder heap tracer for the isolate.
7759  */
7760  void SetEmbedderHeapTracer(EmbedderHeapTracer* tracer);
7761 
7762  /**
7763  * Use for |AtomicsWaitCallback| to indicate the type of event it receives.
7764  */
7765  enum class AtomicsWaitEvent {
7766  /** Indicates that this call is happening before waiting. */
7767  kStartWait,
7768  /** `Atomics.wait()` finished because of an `Atomics.wake()` call. */
7769  kWokenUp,
7770  /** `Atomics.wait()` finished because it timed out. */
7771  kTimedOut,
7772  /** `Atomics.wait()` was interrupted through |TerminateExecution()|. */
7773  kTerminatedExecution,
7774  /** `Atomics.wait()` was stopped through |AtomicsWaitWakeHandle|. */
7775  kAPIStopped,
7776  /** `Atomics.wait()` did not wait, as the initial condition was not met. */
7777  kNotEqual
7778  };
7779 
7780  /**
7781  * Passed to |AtomicsWaitCallback| as a means of stopping an ongoing
7782  * `Atomics.wait` call.
7783  */
7785  public:
7786  /**
7787  * Stop this `Atomics.wait()` call and call the |AtomicsWaitCallback|
7788  * with |kAPIStopped|.
7789  *
7790  * This function may be called from another thread. The caller has to ensure
7791  * through proper synchronization that it is not called after
7792  * the finishing |AtomicsWaitCallback|.
7793  *
7794  * Note that the ECMAScript specification does not plan for the possibility
7795  * of wakeups that are neither coming from a timeout or an `Atomics.wake()`
7796  * call, so this may invalidate assumptions made by existing code.
7797  * The embedder may accordingly wish to schedule an exception in the
7798  * finishing |AtomicsWaitCallback|.
7799  */
7800  void Wake();
7801  };
7802 
7803  /**
7804  * Embedder callback for `Atomics.wait()` that can be added through
7805  * |SetAtomicsWaitCallback|.
7806  *
7807  * This will be called just before starting to wait with the |event| value
7808  * |kStartWait| and after finishing waiting with one of the other
7809  * values of |AtomicsWaitEvent| inside of an `Atomics.wait()` call.
7810  *
7811  * |array_buffer| will refer to the underlying SharedArrayBuffer,
7812  * |offset_in_bytes| to the location of the waited-on memory address inside
7813  * the SharedArrayBuffer.
7814  *
7815  * |value| and |timeout_in_ms| will be the values passed to
7816  * the `Atomics.wait()` call. If no timeout was used, |timeout_in_ms|
7817  * will be `INFINITY`.
7818  *
7819  * In the |kStartWait| callback, |stop_handle| will be an object that
7820  * is only valid until the corresponding finishing callback and that
7821  * can be used to stop the wait process while it is happening.
7822  *
7823  * This callback may schedule exceptions, *unless* |event| is equal to
7824  * |kTerminatedExecution|.
7825  */
7826  typedef void (*AtomicsWaitCallback)(AtomicsWaitEvent event,
7827  Local<SharedArrayBuffer> array_buffer,
7828  size_t offset_in_bytes, int32_t value,
7829  double timeout_in_ms,
7830  AtomicsWaitWakeHandle* stop_handle,
7831  void* data);
7832 
7833  /**
7834  * Set a new |AtomicsWaitCallback|. This overrides an earlier
7835  * |AtomicsWaitCallback|, if there was any. If |callback| is nullptr,
7836  * this unsets the callback. |data| will be passed to the callback
7837  * as its last parameter.
7838  */
7839  void SetAtomicsWaitCallback(AtomicsWaitCallback callback, void* data);
7840 
7841  /**
7842  * Enables the host application to receive a notification after a
7843  * garbage collection. Allocations are allowed in the callback function,
7844  * but the callback is not re-entrant: if the allocation inside it will
7845  * trigger the garbage collection, the callback won't be called again.
7846  * It is possible to specify the GCType filter for your callback. But it is
7847  * not possible to register the same callback function two times with
7848  * different GCType filters.
7849  */
7850  void AddGCEpilogueCallback(GCCallbackWithData callback, void* data = nullptr,
7851  GCType gc_type_filter = kGCTypeAll);
7852  void AddGCEpilogueCallback(GCCallback callback,
7853  GCType gc_type_filter = kGCTypeAll);
7854 
7855  /**
7856  * This function removes callback which was installed by
7857  * AddGCEpilogueCallback function.
7858  */
7859  void RemoveGCEpilogueCallback(GCCallbackWithData callback,
7860  void* data = nullptr);
7861  void RemoveGCEpilogueCallback(GCCallback callback);
7862 
7863  typedef size_t (*GetExternallyAllocatedMemoryInBytesCallback)();
7864 
7865  /**
7866  * Set the callback that tells V8 how much memory is currently allocated
7867  * externally of the V8 heap. Ideally this memory is somehow connected to V8
7868  * objects and may get freed-up when the corresponding V8 objects get
7869  * collected by a V8 garbage collection.
7870  */
7871  void SetGetExternallyAllocatedMemoryInBytesCallback(
7872  GetExternallyAllocatedMemoryInBytesCallback callback);
7873 
7874  /**
7875  * Forcefully terminate the current thread of JavaScript execution
7876  * in the given isolate.
7877  *
7878  * This method can be used by any thread even if that thread has not
7879  * acquired the V8 lock with a Locker object.
7880  */
7881  void TerminateExecution();
7882 
7883  /**
7884  * Is V8 terminating JavaScript execution.
7885  *
7886  * Returns true if JavaScript execution is currently terminating
7887  * because of a call to TerminateExecution. In that case there are
7888  * still JavaScript frames on the stack and the termination
7889  * exception is still active.
7890  */
7891  bool IsExecutionTerminating();
7892 
7893  /**
7894  * Resume execution capability in the given isolate, whose execution
7895  * was previously forcefully terminated using TerminateExecution().
7896  *
7897  * When execution is forcefully terminated using TerminateExecution(),
7898  * the isolate can not resume execution until all JavaScript frames
7899  * have propagated the uncatchable exception which is generated. This
7900  * method allows the program embedding the engine to handle the
7901  * termination event and resume execution capability, even if
7902  * JavaScript frames remain on the stack.
7903  *
7904  * This method can be used by any thread even if that thread has not
7905  * acquired the V8 lock with a Locker object.
7906  */
7907  void CancelTerminateExecution();
7908 
7909  /**
7910  * Request V8 to interrupt long running JavaScript code and invoke
7911  * the given |callback| passing the given |data| to it. After |callback|
7912  * returns control will be returned to the JavaScript code.
7913  * There may be a number of interrupt requests in flight.
7914  * Can be called from another thread without acquiring a |Locker|.
7915  * Registered |callback| must not reenter interrupted Isolate.
7916  */
7917  void RequestInterrupt(InterruptCallback callback, void* data);
7918 
7919  /**
7920  * Request garbage collection in this Isolate. It is only valid to call this
7921  * function if --expose_gc was specified.
7922  *
7923  * This should only be used for testing purposes and not to enforce a garbage
7924  * collection schedule. It has strong negative impact on the garbage
7925  * collection performance. Use IdleNotificationDeadline() or
7926  * LowMemoryNotification() instead to influence the garbage collection
7927  * schedule.
7928  */
7929  void RequestGarbageCollectionForTesting(GarbageCollectionType type);
7930 
7931  /**
7932  * Set the callback to invoke for logging event.
7933  */
7934  void SetEventLogger(LogEventCallback that);
7935 
7936  /**
7937  * Adds a callback to notify the host application right before a script
7938  * is about to run. If a script re-enters the runtime during executing, the
7939  * BeforeCallEnteredCallback is invoked for each re-entrance.
7940  * Executing scripts inside the callback will re-trigger the callback.
7941  */
7942  void AddBeforeCallEnteredCallback(BeforeCallEnteredCallback callback);
7943 
7944  /**
7945  * Removes callback that was installed by AddBeforeCallEnteredCallback.
7946  */
7947  void RemoveBeforeCallEnteredCallback(BeforeCallEnteredCallback callback);
7948 
7949  /**
7950  * Adds a callback to notify the host application when a script finished
7951  * running. If a script re-enters the runtime during executing, the
7952  * CallCompletedCallback is only invoked when the outer-most script
7953  * execution ends. Executing scripts inside the callback do not trigger
7954  * further callbacks.
7955  */
7956  void AddCallCompletedCallback(CallCompletedCallback callback);
7957 
7958  /**
7959  * Removes callback that was installed by AddCallCompletedCallback.
7960  */
7961  void RemoveCallCompletedCallback(CallCompletedCallback callback);
7962 
7963  /**
7964  * Set the PromiseHook callback for various promise lifecycle
7965  * events.
7966  */
7967  void SetPromiseHook(PromiseHook hook);
7968 
7969  /**
7970  * Set callback to notify about promise reject with no handler, or
7971  * revocation of such a previous notification once the handler is added.
7972  */
7973  void SetPromiseRejectCallback(PromiseRejectCallback callback);
7974 
7975  /**
7976  * Runs the Microtask Work Queue until empty
7977  * Any exceptions thrown by microtask callbacks are swallowed.
7978  */
7979  void RunMicrotasks();
7980 
7981  /**
7982  * Enqueues the callback to the Microtask Work Queue
7983  */
7984  void EnqueueMicrotask(Local<Function> microtask);
7985 
7986  /**
7987  * Enqueues the callback to the Microtask Work Queue
7988  */
7989  void EnqueueMicrotask(MicrotaskCallback callback, void* data = nullptr);
7990 
7991  /**
7992  * Controls how Microtasks are invoked. See MicrotasksPolicy for details.
7993  */
7994  void SetMicrotasksPolicy(MicrotasksPolicy policy);
7995 
7996  /**
7997  * Returns the policy controlling how Microtasks are invoked.
7998  */
7999  MicrotasksPolicy GetMicrotasksPolicy() const;
8000 
8001  /**
8002  * Adds a callback to notify the host application after
8003  * microtasks were run. The callback is triggered by explicit RunMicrotasks
8004  * call or automatic microtasks execution (see SetAutorunMicrotasks).
8005  *
8006  * Callback will trigger even if microtasks were attempted to run,
8007  * but the microtasks queue was empty and no single microtask was actually
8008  * executed.
8009  *
8010  * Executing scriptsinside the callback will not re-trigger microtasks and
8011  * the callback.
8012  */
8013  void AddMicrotasksCompletedCallback(MicrotasksCompletedCallback callback);
8014 
8015  /**
8016  * Removes callback that was installed by AddMicrotasksCompletedCallback.
8017  */
8018  void RemoveMicrotasksCompletedCallback(MicrotasksCompletedCallback callback);
8019 
8020  /**
8021  * Sets a callback for counting the number of times a feature of V8 is used.
8022  */
8023  void SetUseCounterCallback(UseCounterCallback callback);
8024 
8025  /**
8026  * Enables the host application to provide a mechanism for recording
8027  * statistics counters.
8028  */
8029  void SetCounterFunction(CounterLookupCallback);
8030 
8031  /**
8032  * Enables the host application to provide a mechanism for recording
8033  * histograms. The CreateHistogram function returns a
8034  * histogram which will later be passed to the AddHistogramSample
8035  * function.
8036  */
8037  void SetCreateHistogramFunction(CreateHistogramCallback);
8038  void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
8039 
8040  /**
8041  * Optional notification that the embedder is idle.
8042  * V8 uses the notification to perform garbage collection.
8043  * This call can be used repeatedly if the embedder remains idle.
8044  * Returns true if the embedder should stop calling IdleNotificationDeadline
8045  * until real work has been done. This indicates that V8 has done
8046  * as much cleanup as it will be able to do.
8047  *
8048  * The deadline_in_seconds argument specifies the deadline V8 has to finish
8049  * garbage collection work. deadline_in_seconds is compared with
8050  * MonotonicallyIncreasingTime() and should be based on the same timebase as
8051  * that function. There is no guarantee that the actual work will be done
8052  * within the time limit.
8053  */
8054  bool IdleNotificationDeadline(double deadline_in_seconds);
8055 
8056  /**
8057  * Optional notification that the system is running low on memory.
8058  * V8 uses these notifications to attempt to free memory.
8059  */
8060  void LowMemoryNotification();
8061 
8062  /**
8063  * Optional notification that a context has been disposed. V8 uses
8064  * these notifications to guide the GC heuristic. Returns the number
8065  * of context disposals - including this one - since the last time
8066  * V8 had a chance to clean up.
8067  *
8068  * The optional parameter |dependant_context| specifies whether the disposed
8069  * context was depending on state from other contexts or not.
8070  */
8071  int ContextDisposedNotification(bool dependant_context = true);
8072 
8073  /**
8074  * Optional notification that the isolate switched to the foreground.
8075  * V8 uses these notifications to guide heuristics.
8076  */
8077  void IsolateInForegroundNotification();
8078 
8079  /**
8080  * Optional notification that the isolate switched to the background.
8081  * V8 uses these notifications to guide heuristics.
8082  */
8083  void IsolateInBackgroundNotification();
8084 
8085  /**
8086  * Optional notification which will enable the memory savings mode.
8087  * V8 uses this notification to guide heuristics which may result in a
8088  * smaller memory footprint at the cost of reduced runtime performance.
8089  */
8090  void EnableMemorySavingsMode();
8091 
8092  /**
8093  * Optional notification which will disable the memory savings mode.
8094  */
8095  void DisableMemorySavingsMode();
8096 
8097  /**
8098  * Optional notification to tell V8 the current performance requirements
8099  * of the embedder based on RAIL.
8100  * V8 uses these notifications to guide heuristics.
8101  * This is an unfinished experimental feature. Semantics and implementation
8102  * may change frequently.
8103  */
8104  void SetRAILMode(RAILMode rail_mode);
8105 
8106  /**
8107  * Optional notification to tell V8 the current isolate is used for debugging
8108  * and requires higher heap limit.
8109  */
8110  void IncreaseHeapLimitForDebugging();
8111 
8112  /**
8113  * Restores the original heap limit after IncreaseHeapLimitForDebugging().
8114  */
8115  void RestoreOriginalHeapLimit();
8116 
8117  /**
8118  * Returns true if the heap limit was increased for debugging and the
8119  * original heap limit was not restored yet.
8120  */
8121  bool IsHeapLimitIncreasedForDebugging();
8122 
8123  /**
8124  * Allows the host application to provide the address of a function that is
8125  * notified each time code is added, moved or removed.
8126  *
8127  * \param options options for the JIT code event handler.
8128  * \param event_handler the JIT code event handler, which will be invoked
8129  * each time code is added, moved or removed.
8130  * \note \p event_handler won't get notified of existent code.
8131  * \note since code removal notifications are not currently issued, the
8132  * \p event_handler may get notifications of code that overlaps earlier
8133  * code notifications. This happens when code areas are reused, and the
8134  * earlier overlapping code areas should therefore be discarded.
8135  * \note the events passed to \p event_handler and the strings they point to
8136  * are not guaranteed to live past each call. The \p event_handler must
8137  * copy strings and other parameters it needs to keep around.
8138  * \note the set of events declared in JitCodeEvent::EventType is expected to
8139  * grow over time, and the JitCodeEvent structure is expected to accrue
8140  * new members. The \p event_handler function must ignore event codes
8141  * it does not recognize to maintain future compatibility.
8142  * \note Use Isolate::CreateParams to get events for code executed during
8143  * Isolate setup.
8144  */
8145  void SetJitCodeEventHandler(JitCodeEventOptions options,
8146  JitCodeEventHandler event_handler);
8147 
8148  /**
8149  * Modifies the stack limit for this Isolate.
8150  *
8151  * \param stack_limit An address beyond which the Vm's stack may not grow.
8152  *
8153  * \note If you are using threads then you should hold the V8::Locker lock
8154  * while setting the stack limit and you must set a non-default stack
8155  * limit separately for each thread.
8156  */
8157  void SetStackLimit(uintptr_t stack_limit);
8158 
8159  /**
8160  * Returns a memory range that can potentially contain jitted code.
8161  *
8162  * On Win64, embedders are advised to install function table callbacks for
8163  * these ranges, as default SEH won't be able to unwind through jitted code.
8164  *
8165  * The first page of the code range is reserved for the embedder and is
8166  * committed, writable, and executable.
8167  *
8168  * Might be empty on other platforms.
8169  *
8170  * https://code.google.com/p/v8/issues/detail?id=3598
8171  */
8172  void GetCodeRange(void** start, size_t* length_in_bytes);
8173 
8174  /** Set the callback to invoke in case of fatal errors. */
8175  void SetFatalErrorHandler(FatalErrorCallback that);
8176 
8177  /** Set the callback to invoke in case of OOM errors. */
8178  void SetOOMErrorHandler(OOMErrorCallback that);
8179 
8180  /**
8181  * Add a callback to invoke in case the heap size is close to the heap limit.
8182  * If multiple callbacks are added, only the most recently added callback is
8183  * invoked.
8184  */
8185  void AddNearHeapLimitCallback(NearHeapLimitCallback callback, void* data);
8186 
8187  /**
8188  * Remove the given callback and restore the heap limit to the
8189  * given limit. If the given limit is zero, then it is ignored.
8190  * If the current heap size is greater than the given limit,
8191  * then the heap limit is restored to the minimal limit that
8192  * is possible for the current heap size.
8193  */
8194  void RemoveNearHeapLimitCallback(NearHeapLimitCallback callback,
8195  size_t heap_limit);
8196 
8197  /**
8198  * Set the callback to invoke to check if code generation from
8199  * strings should be allowed.
8200  */
8201  void SetAllowCodeGenerationFromStringsCallback(
8202  AllowCodeGenerationFromStringsCallback callback);
8203 
8204  /**
8205  * Set the callback to invoke to check if wasm code generation should
8206  * be allowed.
8207  */
8208  void SetAllowWasmCodeGenerationCallback(
8209  AllowWasmCodeGenerationCallback callback);
8210 
8211  /**
8212  * Embedder over{ride|load} injection points for wasm APIs. The expectation
8213  * is that the embedder sets them at most once.
8214  */
8215  void SetWasmModuleCallback(ExtensionCallback callback);
8216  void SetWasmInstanceCallback(ExtensionCallback callback);
8217 
8218  void SetWasmCompileStreamingCallback(ApiImplementationCallback callback);
8219 
8220  void SetWasmStreamingCallback(WasmStreamingCallback callback);
8221 
8222  void SetWasmThreadsEnabledCallback(WasmThreadsEnabledCallback callback);
8223 
8224  /**
8225  * Check if V8 is dead and therefore unusable. This is the case after
8226  * fatal errors such as out-of-memory situations.
8227  */
8228  bool IsDead();
8229 
8230  /**
8231  * Adds a message listener (errors only).
8232  *
8233  * The same message listener can be added more than once and in that
8234  * case it will be called more than once for each message.
8235  *
8236  * If data is specified, it will be passed to the callback when it is called.
8237  * Otherwise, the exception object will be passed to the callback instead.
8238  */
8239  bool AddMessageListener(MessageCallback that,
8240  Local<Value> data = Local<Value>());
8241 
8242  /**
8243  * Adds a message listener.
8244  *
8245  * The same message listener can be added more than once and in that
8246  * case it will be called more than once for each message.
8247  *
8248  * If data is specified, it will be passed to the callback when it is called.
8249  * Otherwise, the exception object will be passed to the callback instead.
8250  *
8251  * A listener can listen for particular error levels by providing a mask.
8252  */
8253  bool AddMessageListenerWithErrorLevel(MessageCallback that,
8254  int message_levels,
8255  Local<Value> data = Local<Value>());
8256 
8257  /**
8258  * Remove all message listeners from the specified callback function.
8259  */
8260  void RemoveMessageListeners(MessageCallback that);
8261 
8262  /** Callback function for reporting failed access checks.*/
8263  void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
8264 
8265  /**
8266  * Tells V8 to capture current stack trace when uncaught exception occurs
8267  * and report it to the message listeners. The option is off by default.
8268  */
8269  void SetCaptureStackTraceForUncaughtExceptions(
8270  bool capture, int frame_limit = 10,
8272 
8273  /**
8274  * Iterates through all external resources referenced from current isolate
8275  * heap. GC is not invoked prior to iterating, therefore there is no
8276  * guarantee that visited objects are still alive.
8277  */
8278  void VisitExternalResources(ExternalResourceVisitor* visitor);
8279 
8280  /**
8281  * Iterates through all the persistent handles in the current isolate's heap
8282  * that have class_ids.
8283  */
8284  void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor);
8285 
8286  /**
8287  * Iterates through all the persistent handles in the current isolate's heap
8288  * that have class_ids and are candidates to be marked as partially dependent
8289  * handles. This will visit handles to young objects created since the last
8290  * garbage collection but is free to visit an arbitrary superset of these
8291  * objects.
8292  */
8293  void VisitHandlesForPartialDependence(PersistentHandleVisitor* visitor);
8294 
8295  /**
8296  * Iterates through all the persistent handles in the current isolate's heap
8297  * that have class_ids and are weak to be marked as inactive if there is no
8298  * pending activity for the handle.
8299  */
8300  void VisitWeakHandles(PersistentHandleVisitor* visitor);
8301 
8302  /**
8303  * Check if this isolate is in use.
8304  * True if at least one thread Enter'ed this isolate.
8305  */
8306  bool IsInUse();
8307 
8308  /**
8309  * Set whether calling Atomics.wait (a function that may block) is allowed in
8310  * this isolate. This can also be configured via
8311  * CreateParams::allow_atomics_wait.
8312  */
8313  void SetAllowAtomicsWait(bool allow);
8314 
8315  Isolate() = delete;
8316  ~Isolate() = delete;
8317  Isolate(const Isolate&) = delete;
8318  Isolate& operator=(const Isolate&) = delete;
8319  // Deleting operator new and delete here is allowed as ctor and dtor is also
8320  // deleted.
8321  void* operator new(size_t size) = delete;
8322  void* operator new[](size_t size) = delete;
8323  void operator delete(void*, size_t) = delete;
8324  void operator delete[](void*, size_t) = delete;
8325 
8326  private:
8327  template <class K, class V, class Traits>
8328  friend class PersistentValueMapBase;
8329 
8330  internal::Object** GetDataFromSnapshotOnce(size_t index);
8331  void ReportExternalAllocationLimitReached();
8332  void CheckMemoryPressure();
8333 };
8334 
8335 class V8_EXPORT StartupData {
8336  public:
8337  const char* data;
8338  int raw_size;
8339 };
8340 
8341 
8342 /**
8343  * EntropySource is used as a callback function when v8 needs a source
8344  * of entropy.
8345  */
8346 typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
8347 
8348 /**
8349  * ReturnAddressLocationResolver is used as a callback function when v8 is
8350  * resolving the location of a return address on the stack. Profilers that
8351  * change the return address on the stack can use this to resolve the stack
8352  * location to wherever the profiler stashed the original return address.
8353  *
8354  * \param return_addr_location A location on stack where a machine
8355  * return address resides.
8356  * \returns Either return_addr_location, or else a pointer to the profiler's
8357  * copy of the original return address.
8358  *
8359  * \note The resolver function must not cause garbage collection.
8360  */
8361 typedef uintptr_t (*ReturnAddressLocationResolver)(
8362  uintptr_t return_addr_location);
8363 
8364 
8365 /**
8366  * Container class for static utility functions.
8367  */
8368 class V8_EXPORT V8 {
8369  public:
8370  /**
8371  * Hand startup data to V8, in case the embedder has chosen to build
8372  * V8 with external startup data.
8373  *
8374  * Note:
8375  * - By default the startup data is linked into the V8 library, in which
8376  * case this function is not meaningful.
8377  * - If this needs to be called, it needs to be called before V8
8378  * tries to make use of its built-ins.
8379  * - To avoid unnecessary copies of data, V8 will point directly into the
8380  * given data blob, so pretty please keep it around until V8 exit.
8381  * - Compression of the startup blob might be useful, but needs to
8382  * handled entirely on the embedders' side.
8383  * - The call will abort if the data is invalid.
8384  */
8385  static void SetNativesDataBlob(StartupData* startup_blob);
8386  static void SetSnapshotDataBlob(StartupData* startup_blob);
8387 
8388  /** Set the callback to invoke in case of Dcheck failures. */
8389  static void SetDcheckErrorHandler(DcheckErrorCallback that);
8390 
8391 
8392  /**
8393  * Sets V8 flags from a string.
8394  */
8395  static void SetFlagsFromString(const char* str, int length);
8396 
8397  /**
8398  * Sets V8 flags from the command line.
8399  */
8400  static void SetFlagsFromCommandLine(int* argc,
8401  char** argv,
8402  bool remove_flags);
8403 
8404  /** Get the version string. */
8405  static const char* GetVersion();
8406 
8407  /**
8408  * Initializes V8. This function needs to be called before the first Isolate
8409  * is created. It always returns true.
8410  */
8411  static bool Initialize();
8412 
8413  /**
8414  * Allows the host application to provide a callback which can be used
8415  * as a source of entropy for random number generators.
8416  */
8417  static void SetEntropySource(EntropySource source);
8418 
8419  /**
8420  * Allows the host application to provide a callback that allows v8 to
8421  * cooperate with a profiler that rewrites return addresses on stack.
8422  */
8423  static void SetReturnAddressLocationResolver(
8424  ReturnAddressLocationResolver return_address_resolver);
8425 
8426  /**
8427  * Releases any resources used by v8 and stops any utility threads
8428  * that may be running. Note that disposing v8 is permanent, it
8429  * cannot be reinitialized.
8430  *
8431  * It should generally not be necessary to dispose v8 before exiting
8432  * a process, this should happen automatically. It is only necessary
8433  * to use if the process needs the resources taken up by v8.
8434  */
8435  static bool Dispose();
8436 
8437  /**
8438  * Initialize the ICU library bundled with V8. The embedder should only
8439  * invoke this method when using the bundled ICU. Returns true on success.
8440  *
8441  * If V8 was compiled with the ICU data in an external file, the location
8442  * of the data file has to be provided.
8443  */
8444  static bool InitializeICU(const char* icu_data_file = nullptr);
8445 
8446  /**
8447  * Initialize the ICU library bundled with V8. The embedder should only
8448  * invoke this method when using the bundled ICU. If V8 was compiled with
8449  * the ICU data in an external file and when the default location of that
8450  * file should be used, a path to the executable must be provided.
8451  * Returns true on success.
8452  *
8453  * The default is a file called icudtl.dat side-by-side with the executable.
8454  *
8455  * Optionally, the location of the data file can be provided to override the
8456  * default.
8457  */
8458  static bool InitializeICUDefaultLocation(const char* exec_path,
8459  const char* icu_data_file = nullptr);
8460 
8461  /**
8462  * Initialize the external startup data. The embedder only needs to
8463  * invoke this method when external startup data was enabled in a build.
8464  *
8465  * If V8 was compiled with the startup data in an external file, then
8466  * V8 needs to be given those external files during startup. There are
8467  * three ways to do this:
8468  * - InitializeExternalStartupData(const char*)
8469  * This will look in the given directory for files "natives_blob.bin"
8470  * and "snapshot_blob.bin" - which is what the default build calls them.
8471  * - InitializeExternalStartupData(const char*, const char*)
8472  * As above, but will directly use the two given file names.
8473  * - Call SetNativesDataBlob, SetNativesDataBlob.
8474  * This will read the blobs from the given data structures and will
8475  * not perform any file IO.
8476  */
8477  static void InitializeExternalStartupData(const char* directory_path);
8478  static void InitializeExternalStartupData(const char* natives_blob,
8479  const char* snapshot_blob);
8480  /**
8481  * Sets the v8::Platform to use. This should be invoked before V8 is
8482  * initialized.
8483  */
8484  static void InitializePlatform(Platform* platform);
8485 
8486  /**
8487  * Clears all references to the v8::Platform. This should be invoked after
8488  * V8 was disposed.
8489  */
8490  static void ShutdownPlatform();
8491 
8492 #if V8_OS_POSIX
8493  /**
8494  * Give the V8 signal handler a chance to handle a fault.
8495  *
8496  * This function determines whether a memory access violation can be recovered
8497  * by V8. If so, it will return true and modify context to return to a code
8498  * fragment that can recover from the fault. Otherwise, TryHandleSignal will
8499  * return false.
8500  *
8501  * The parameters to this function correspond to those passed to a Linux
8502  * signal handler.
8503  *
8504  * \param signal_number The signal number.
8505  *
8506  * \param info A pointer to the siginfo_t structure provided to the signal
8507  * handler.
8508  *
8509  * \param context The third argument passed to the Linux signal handler, which
8510  * points to a ucontext_t structure.
8511  */
8512  static bool TryHandleSignal(int signal_number, void* info, void* context);
8513 #endif // V8_OS_POSIX
8514 
8515  /**
8516  * Enable the default signal handler rather than using one provided by the
8517  * embedder.
8518  */
8519  V8_DEPRECATE_SOON("Use EnableWebAssemblyTrapHandler",
8520  static bool RegisterDefaultSignalHandler());
8521 
8522  /**
8523  * Activate trap-based bounds checking for WebAssembly.
8524  *
8525  * \param use_v8_signal_handler Whether V8 should install its own signal
8526  * handler or rely on the embedder's.
8527  */
8528  static bool EnableWebAssemblyTrapHandler(bool use_v8_signal_handler);
8529 
8530  private:
8531  V8();
8532 
8533  static internal::Object** GlobalizeReference(internal::Isolate* isolate,
8534  internal::Object** handle);
8535  static internal::Object** CopyPersistent(internal::Object** handle);
8536  static void DisposeGlobal(internal::Object** global_handle);
8537  static void MakeWeak(internal::Object** location, void* data,
8538  WeakCallbackInfo<void>::Callback weak_callback,
8539  WeakCallbackType type);
8540  static void MakeWeak(internal::Object** location, void* data,
8541  // Must be 0 or -1.
8542  int internal_field_index1,
8543  // Must be 1 or -1.
8544  int internal_field_index2,
8545  WeakCallbackInfo<void>::Callback weak_callback);
8546  static void MakeWeak(internal::Object*** location_addr);
8547  static void* ClearWeak(internal::Object** location);
8548  static void AnnotateStrongRetainer(internal::Object** location,
8549  const char* label);
8550  static Value* Eternalize(Isolate* isolate, Value* handle);
8551 
8552  static void RegisterExternallyReferencedObject(internal::Object** object,
8553  internal::Isolate* isolate);
8554 
8555  template <class K, class V, class T>
8556  friend class PersistentValueMapBase;
8557 
8558  static void FromJustIsNothing();
8559  static void ToLocalEmpty();
8560  static void InternalFieldOutOfBounds(int index);
8561  template <class T> friend class Local;
8562  template <class T>
8563  friend class MaybeLocal;
8564  template <class T>
8565  friend class Maybe;
8566  template <class T>
8567  friend class WeakCallbackInfo;
8568  template <class T> friend class Eternal;
8569  template <class T> friend class PersistentBase;
8570  template <class T, class M> friend class Persistent;
8571  friend class Context;
8572 };
8573 
8574 /**
8575  * Helper class to create a snapshot data blob.
8576  */
8577 class V8_EXPORT SnapshotCreator {
8578  public:
8579  enum class FunctionCodeHandling { kClear, kKeep };
8580 
8581  /**
8582  * Initialize and enter an isolate, and set it up for serialization.
8583  * The isolate is either created from scratch or from an existing snapshot.
8584  * The caller keeps ownership of the argument snapshot.
8585  * \param existing_blob existing snapshot from which to create this one.
8586  * \param external_references a null-terminated array of external references
8587  * that must be equivalent to CreateParams::external_references.
8588  */
8589  SnapshotCreator(Isolate* isolate,
8590  const intptr_t* external_references = nullptr,
8591  StartupData* existing_blob = nullptr);
8592 
8593  /**
8594  * Create and enter an isolate, and set it up for serialization.
8595  * The isolate is either created from scratch or from an existing snapshot.
8596  * The caller keeps ownership of the argument snapshot.
8597  * \param existing_blob existing snapshot from which to create this one.
8598  * \param external_references a null-terminated array of external references
8599  * that must be equivalent to CreateParams::external_references.
8600  */
8601  SnapshotCreator(const intptr_t* external_references = nullptr,
8602  StartupData* existing_blob = nullptr);
8603 
8604  ~SnapshotCreator();
8605 
8606  /**
8607  * \returns the isolate prepared by the snapshot creator.
8608  */
8609  Isolate* GetIsolate();
8610 
8611  /**
8612  * Set the default context to be included in the snapshot blob.
8613  * The snapshot will not contain the global proxy, and we expect one or a
8614  * global object template to create one, to be provided upon deserialization.
8615  *
8616  * \param callback optional callback to serialize internal fields.
8617  */
8618  void SetDefaultContext(Local<Context> context,
8619  SerializeInternalFieldsCallback callback =
8620  SerializeInternalFieldsCallback());
8621 
8622  /**
8623  * Add additional context to be included in the snapshot blob.
8624  * The snapshot will include the global proxy.
8625  *
8626  * \param callback optional callback to serialize internal fields.
8627  *
8628  * \returns the index of the context in the snapshot blob.
8629  */
8630  size_t AddContext(Local<Context> context,
8631  SerializeInternalFieldsCallback callback =
8632  SerializeInternalFieldsCallback());
8633 
8634  /**
8635  * Add a template to be included in the snapshot blob.
8636  * \returns the index of the template in the snapshot blob.
8637  */
8638  size_t AddTemplate(Local<Template> template_obj);
8639 
8640  /**
8641  * Attach arbitrary V8::Data to the context snapshot, which can be retrieved
8642  * via Context::GetDataFromSnapshot after deserialization. This data does not
8643  * survive when a new snapshot is created from an existing snapshot.
8644  * \returns the index for retrieval.
8645  */
8646  template <class T>
8647  V8_INLINE size_t AddData(Local<Context> context, Local<T> object);
8648 
8649  /**
8650  * Attach arbitrary V8::Data to the isolate snapshot, which can be retrieved
8651  * via Isolate::GetDataFromSnapshot after deserialization. This data does not
8652  * survive when a new snapshot is created from an existing snapshot.
8653  * \returns the index for retrieval.
8654  */
8655  template <class T>
8656  V8_INLINE size_t AddData(Local<T> object);
8657 
8658  /**
8659  * Created a snapshot data blob.
8660  * This must not be called from within a handle scope.
8661  * \param function_code_handling whether to include compiled function code
8662  * in the snapshot.
8663  * \returns { nullptr, 0 } on failure, and a startup snapshot on success. The
8664  * caller acquires ownership of the data array in the return value.
8665  */
8666  StartupData CreateBlob(FunctionCodeHandling function_code_handling);
8667 
8668  // Disallow copying and assigning.
8669  SnapshotCreator(const SnapshotCreator&) = delete;
8670  void operator=(const SnapshotCreator&) = delete;
8671 
8672  private:
8673  size_t AddData(Local<Context> context, internal::Object* object);
8674  size_t AddData(internal::Object* object);
8675 
8676  void* data_;
8677 };
8678 
8679 /**
8680  * A simple Maybe type, representing an object which may or may not have a
8681  * value, see https://hackage.haskell.org/package/base/docs/Data-Maybe.html.
8682  *
8683  * If an API method returns a Maybe<>, the API method can potentially fail
8684  * either because an exception is thrown, or because an exception is pending,
8685  * e.g. because a previous API call threw an exception that hasn't been caught
8686  * yet, or because a TerminateExecution exception was thrown. In that case, a
8687  * "Nothing" value is returned.
8688  */
8689 template <class T>
8690 class Maybe {
8691  public:
8692  V8_INLINE bool IsNothing() const { return !has_value_; }
8693  V8_INLINE bool IsJust() const { return has_value_; }
8694 
8695  /**
8696  * An alias for |FromJust|. Will crash if the Maybe<> is nothing.
8697  */
8698  V8_INLINE T ToChecked() const { return FromJust(); }
8699 
8700  /**
8701  * Converts this Maybe<> to a value of type T. If this Maybe<> is
8702  * nothing (empty), |false| is returned and |out| is left untouched.
8703  */
8704  V8_WARN_UNUSED_RESULT V8_INLINE bool To(T* out) const {
8705  if (V8_LIKELY(IsJust())) *out = value_;
8706  return IsJust();
8707  }
8708 
8709  /**
8710  * Converts this Maybe<> to a value of type T. If this Maybe<> is
8711  * nothing (empty), V8 will crash the process.
8712  */
8713  V8_INLINE T FromJust() const {
8714  if (V8_UNLIKELY(!IsJust())) V8::FromJustIsNothing();
8715  return value_;
8716  }
8717 
8718  /**
8719  * Converts this Maybe<> to a value of type T, using a default value if this
8720  * Maybe<> is nothing (empty).
8721  */
8722  V8_INLINE T FromMaybe(const T& default_value) const {
8723  return has_value_ ? value_ : default_value;
8724  }
8725 
8726  V8_INLINE bool operator==(const Maybe& other) const {
8727  return (IsJust() == other.IsJust()) &&
8728  (!IsJust() || FromJust() == other.FromJust());
8729  }
8730 
8731  V8_INLINE bool operator!=(const Maybe& other) const {
8732  return !operator==(other);
8733  }
8734 
8735  private:
8736  Maybe() : has_value_(false) {}
8737  explicit Maybe(const T& t) : has_value_(true), value_(t) {}
8738 
8739  bool has_value_;
8740  T value_;
8741 
8742  template <class U>
8743  friend Maybe<U> Nothing();
8744  template <class U>
8745  friend Maybe<U> Just(const U& u);
8746 };
8747 
8748 template <class T>
8749 inline Maybe<T> Nothing() {
8750  return Maybe<T>();
8751 }
8752 
8753 template <class T>
8754 inline Maybe<T> Just(const T& t) {
8755  return Maybe<T>(t);
8756 }
8757 
8758 // A template specialization of Maybe<T> for the case of T = void.
8759 template <>
8760 class Maybe<void> {
8761  public:
8762  V8_INLINE bool IsNothing() const { return !is_valid_; }
8763  V8_INLINE bool IsJust() const { return is_valid_; }
8764 
8765  V8_INLINE bool operator==(const Maybe& other) const {
8766  return IsJust() == other.IsJust();
8767  }
8768 
8769  V8_INLINE bool operator!=(const Maybe& other) const {
8770  return !operator==(other);
8771  }
8772 
8773  private:
8774  struct JustTag {};
8775 
8776  Maybe() : is_valid_(false) {}
8777  explicit Maybe(JustTag) : is_valid_(true) {}
8778 
8779  bool is_valid_;
8780 
8781  template <class U>
8782  friend Maybe<U> Nothing();
8783  friend Maybe<void> JustVoid();
8784 };
8785 
8786 inline Maybe<void> JustVoid() { return Maybe<void>(Maybe<void>::JustTag()); }
8787 
8788 /**
8789  * An external exception handler.
8790  */
8791 class V8_EXPORT TryCatch {
8792  public:
8793  /**
8794  * Creates a new try/catch block and registers it with v8. Note that
8795  * all TryCatch blocks should be stack allocated because the memory
8796  * location itself is compared against JavaScript try/catch blocks.
8797  */
8798  explicit TryCatch(Isolate* isolate);
8799 
8800  /**
8801  * Unregisters and deletes this try/catch block.
8802  */
8803  ~TryCatch();
8804 
8805  /**
8806  * Returns true if an exception has been caught by this try/catch block.
8807  */
8808  bool HasCaught() const;
8809 
8810  /**
8811  * For certain types of exceptions, it makes no sense to continue execution.
8812  *
8813  * If CanContinue returns false, the correct action is to perform any C++
8814  * cleanup needed and then return. If CanContinue returns false and
8815  * HasTerminated returns true, it is possible to call
8816  * CancelTerminateExecution in order to continue calling into the engine.
8817  */
8818  bool CanContinue() const;
8819 
8820  /**
8821  * Returns true if an exception has been caught due to script execution
8822  * being terminated.
8823  *
8824  * There is no JavaScript representation of an execution termination
8825  * exception. Such exceptions are thrown when the TerminateExecution
8826  * methods are called to terminate a long-running script.
8827  *
8828  * If such an exception has been thrown, HasTerminated will return true,
8829  * indicating that it is possible to call CancelTerminateExecution in order
8830  * to continue calling into the engine.
8831  */
8832  bool HasTerminated() const;
8833 
8834  /**
8835  * Throws the exception caught by this TryCatch in a way that avoids
8836  * it being caught again by this same TryCatch. As with ThrowException
8837  * it is illegal to execute any JavaScript operations after calling
8838  * ReThrow; the caller must return immediately to where the exception
8839  * is caught.
8840  */
8841  Local<Value> ReThrow();
8842 
8843  /**
8844  * Returns the exception caught by this try/catch block. If no exception has
8845  * been caught an empty handle is returned.
8846  *
8847  * The returned handle is valid until this TryCatch block has been destroyed.
8848  */
8849  Local<Value> Exception() const;
8850 
8851  /**
8852  * Returns the .stack property of the thrown object. If no .stack
8853  * property is present an empty handle is returned.
8854  */
8856  Local<Context> context) const;
8857 
8858  /**
8859  * Returns the message associated with this exception. If there is
8860  * no message associated an empty handle is returned.
8861  *
8862  * The returned handle is valid until this TryCatch block has been
8863  * destroyed.
8864  */
8865  Local<v8::Message> Message() const;
8866 
8867  /**
8868  * Clears any exceptions that may have been caught by this try/catch block.
8869  * After this method has been called, HasCaught() will return false. Cancels
8870  * the scheduled exception if it is caught and ReThrow() is not called before.
8871  *
8872  * It is not necessary to clear a try/catch block before using it again; if
8873  * another exception is thrown the previously caught exception will just be
8874  * overwritten. However, it is often a good idea since it makes it easier
8875  * to determine which operation threw a given exception.
8876  */
8877  void Reset();
8878 
8879  /**
8880  * Set verbosity of the external exception handler.
8881  *
8882  * By default, exceptions that are caught by an external exception
8883  * handler are not reported. Call SetVerbose with true on an
8884  * external exception handler to have exceptions caught by the
8885  * handler reported as if they were not caught.
8886  */
8887  void SetVerbose(bool value);
8888 
8889  /**
8890  * Returns true if verbosity is enabled.
8891  */
8892  bool IsVerbose() const;
8893 
8894  /**
8895  * Set whether or not this TryCatch should capture a Message object
8896  * which holds source information about where the exception
8897  * occurred. True by default.
8898  */
8899  void SetCaptureMessage(bool value);
8900 
8901  /**
8902  * There are cases when the raw address of C++ TryCatch object cannot be
8903  * used for comparisons with addresses into the JS stack. The cases are:
8904  * 1) ARM, ARM64 and MIPS simulators which have separate JS stack.
8905  * 2) Address sanitizer allocates local C++ object in the heap when
8906  * UseAfterReturn mode is enabled.
8907  * This method returns address that can be used for comparisons with
8908  * addresses into the JS stack. When neither simulator nor ASAN's
8909  * UseAfterReturn is enabled, then the address returned will be the address
8910  * of the C++ try catch handler itself.
8911  */
8912  static void* JSStackComparableAddress(TryCatch* handler) {
8913  if (handler == NULL) return NULL;
8914  return handler->js_stack_comparable_address_;
8915  }
8916 
8917  TryCatch(const TryCatch&) = delete;
8918  void operator=(const TryCatch&) = delete;
8919 
8920  private:
8921  // Declaring operator new and delete as deleted is not spec compliant.
8922  // Therefore declare them private instead to disable dynamic alloc
8923  void* operator new(size_t size);
8924  void* operator new[](size_t size);
8925  void operator delete(void*, size_t);
8926  void operator delete[](void*, size_t);
8927 
8928  void ResetInternal();
8929 
8930  internal::Isolate* isolate_;
8931  TryCatch* next_;
8932  void* exception_;
8933  void* message_obj_;
8934  void* js_stack_comparable_address_;
8935  bool is_verbose_ : 1;
8936  bool can_continue_ : 1;
8937  bool capture_message_ : 1;
8938  bool rethrow_ : 1;
8939  bool has_terminated_ : 1;
8940 
8941  friend class internal::Isolate;
8942 };
8943 
8944 
8945 // --- Context ---
8946 
8947 
8948 /**
8949  * A container for extension names.
8950  */
8951 class V8_EXPORT ExtensionConfiguration {
8952  public:
8953  ExtensionConfiguration() : name_count_(0), names_(NULL) { }
8954  ExtensionConfiguration(int name_count, const char* names[])
8955  : name_count_(name_count), names_(names) { }
8956 
8957  const char** begin() const { return &names_[0]; }
8958  const char** end() const { return &names_[name_count_]; }
8959 
8960  private:
8961  const int name_count_;
8962  const char** names_;
8963 };
8964 
8965 /**
8966  * A sandboxed execution context with its own set of built-in objects
8967  * and functions.
8968  */
8969 class V8_EXPORT Context {
8970  public:
8971  /**
8972  * Returns the global proxy object.
8973  *
8974  * Global proxy object is a thin wrapper whose prototype points to actual
8975  * context's global object with the properties like Object, etc. This is done
8976  * that way for security reasons (for more details see
8977  * https://wiki.mozilla.org/Gecko:SplitWindow).
8978  *
8979  * Please note that changes to global proxy object prototype most probably
8980  * would break VM---v8 expects only global object as a prototype of global
8981  * proxy object.
8982  */
8983  Local<Object> Global();
8984 
8985  /**
8986  * Detaches the global object from its context before
8987  * the global object can be reused to create a new context.
8988  */
8989  void DetachGlobal();
8990 
8991  /**
8992  * Creates a new context and returns a handle to the newly allocated
8993  * context.
8994  *
8995  * \param isolate The isolate in which to create the context.
8996  *
8997  * \param extensions An optional extension configuration containing
8998  * the extensions to be installed in the newly created context.
8999  *
9000  * \param global_template An optional object template from which the
9001  * global object for the newly created context will be created.
9002  *
9003  * \param global_object An optional global object to be reused for
9004  * the newly created context. This global object must have been
9005  * created by a previous call to Context::New with the same global
9006  * template. The state of the global object will be completely reset
9007  * and only object identify will remain.
9008  */
9009  static Local<Context> New(
9010  Isolate* isolate, ExtensionConfiguration* extensions = NULL,
9012  MaybeLocal<Value> global_object = MaybeLocal<Value>(),
9013  DeserializeInternalFieldsCallback internal_fields_deserializer =
9014  DeserializeInternalFieldsCallback());
9015 
9016  /**
9017  * Create a new context from a (non-default) context snapshot. There
9018  * is no way to provide a global object template since we do not create
9019  * a new global object from template, but we can reuse a global object.
9020  *
9021  * \param isolate See v8::Context::New.
9022  *
9023  * \param context_snapshot_index The index of the context snapshot to
9024  * deserialize from. Use v8::Context::New for the default snapshot.
9025  *
9026  * \param embedder_fields_deserializer Optional callback to deserialize
9027  * internal fields. It should match the SerializeInternalFieldCallback used
9028  * to serialize.
9029  *
9030  * \param extensions See v8::Context::New.
9031  *
9032  * \param global_object See v8::Context::New.
9033  */
9034 
9035  static MaybeLocal<Context> FromSnapshot(
9036  Isolate* isolate, size_t context_snapshot_index,
9037  DeserializeInternalFieldsCallback embedder_fields_deserializer =
9038  DeserializeInternalFieldsCallback(),
9039  ExtensionConfiguration* extensions = nullptr,
9040  MaybeLocal<Value> global_object = MaybeLocal<Value>());
9041 
9042  /**
9043  * Returns an global object that isn't backed by an actual context.
9044  *
9045  * The global template needs to have access checks with handlers installed.
9046  * If an existing global object is passed in, the global object is detached
9047  * from its context.
9048  *
9049  * Note that this is different from a detached context where all accesses to
9050  * the global proxy will fail. Instead, the access check handlers are invoked.
9051  *
9052  * It is also not possible to detach an object returned by this method.
9053  * Instead, the access check handlers need to return nothing to achieve the
9054  * same effect.
9055  *
9056  * It is possible, however, to create a new context from the global object
9057  * returned by this method.
9058  */
9059  static MaybeLocal<Object> NewRemoteContext(
9060  Isolate* isolate, Local<ObjectTemplate> global_template,
9061  MaybeLocal<Value> global_object = MaybeLocal<Value>());
9062 
9063  /**
9064  * Sets the security token for the context. To access an object in
9065  * another context, the security tokens must match.
9066  */
9067  void SetSecurityToken(Local<Value> token);
9068 
9069  /** Restores the security token to the default value. */
9070  void UseDefaultSecurityToken();
9071 
9072  /** Returns the security token of this context.*/
9073  Local<Value> GetSecurityToken();
9074 
9075  /**
9076  * Enter this context. After entering a context, all code compiled
9077  * and run is compiled and run in this context. If another context
9078  * is already entered, this old context is saved so it can be
9079  * restored when the new context is exited.
9080  */
9081  void Enter();
9082 
9083  /**
9084  * Exit this context. Exiting the current context restores the
9085  * context that was in place when entering the current context.
9086  */
9087  void Exit();
9088 
9089  /** Returns an isolate associated with a current context. */
9090  Isolate* GetIsolate();
9091 
9092  /**
9093  * The field at kDebugIdIndex used to be reserved for the inspector.
9094  * It now serves no purpose.
9095  */
9096  enum EmbedderDataFields { kDebugIdIndex = 0 };
9097 
9098  /**
9099  * Return the number of fields allocated for embedder data.
9100  */
9101  uint32_t GetNumberOfEmbedderDataFields();
9102 
9103  /**
9104  * Gets the embedder data with the given index, which must have been set by a
9105  * previous call to SetEmbedderData with the same index.
9106  */
9107  V8_INLINE Local<Value> GetEmbedderData(int index);
9108 
9109  /**
9110  * Gets the binding object used by V8 extras. Extra natives get a reference
9111  * to this object and can use it to "export" functionality by adding
9112  * properties. Extra natives can also "import" functionality by accessing
9113  * properties added by the embedder using the V8 API.
9114  */
9115  Local<Object> GetExtrasBindingObject();
9116 
9117  /**
9118  * Sets the embedder data with the given index, growing the data as
9119  * needed. Note that index 0 currently has a special meaning for Chrome's
9120  * debugger.
9121  */
9122  void SetEmbedderData(int index, Local<Value> value);
9123 
9124  /**
9125  * Gets a 2-byte-aligned native pointer from the embedder data with the given
9126  * index, which must have been set by a previous call to
9127  * SetAlignedPointerInEmbedderData with the same index. Note that index 0
9128  * currently has a special meaning for Chrome's debugger.
9129  */
9130  V8_INLINE void* GetAlignedPointerFromEmbedderData(int index);
9131 
9132  /**
9133  * Sets a 2-byte-aligned native pointer in the embedder data with the given
9134  * index, growing the data as needed. Note that index 0 currently has a
9135  * special meaning for Chrome's debugger.
9136  */
9137  void SetAlignedPointerInEmbedderData(int index, void* value);
9138 
9139  /**
9140  * Control whether code generation from strings is allowed. Calling
9141  * this method with false will disable 'eval' and the 'Function'
9142  * constructor for code running in this context. If 'eval' or the
9143  * 'Function' constructor are used an exception will be thrown.
9144  *
9145  * If code generation from strings is not allowed the
9146  * V8::AllowCodeGenerationFromStrings callback will be invoked if
9147  * set before blocking the call to 'eval' or the 'Function'
9148  * constructor. If that callback returns true, the call will be
9149  * allowed, otherwise an exception will be thrown. If no callback is
9150  * set an exception will be thrown.
9151  */
9152  void AllowCodeGenerationFromStrings(bool allow);
9153 
9154  /**
9155  * Returns true if code generation from strings is allowed for the context.
9156  * For more details see AllowCodeGenerationFromStrings(bool) documentation.
9157  */
9158  bool IsCodeGenerationFromStringsAllowed();
9159 
9160  /**
9161  * Sets the error description for the exception that is thrown when
9162  * code generation from strings is not allowed and 'eval' or the 'Function'
9163  * constructor are called.
9164  */
9165  void SetErrorMessageForCodeGenerationFromStrings(Local<String> message);
9166 
9167  /**
9168  * Return data that was previously attached to the context snapshot via
9169  * SnapshotCreator, and removes the reference to it.
9170  * Repeated call with the same index returns an empty MaybeLocal.
9171  */
9172  template <class T>
9173  V8_INLINE MaybeLocal<T> GetDataFromSnapshotOnce(size_t index);
9174 
9175  /**
9176  * Stack-allocated class which sets the execution context for all
9177  * operations executed within a local scope.
9178  */
9179  class Scope {
9180  public:
9181  explicit V8_INLINE Scope(Local<Context> context) : context_(context) {
9182  context_->Enter();
9183  }
9184  V8_INLINE ~Scope() { context_->Exit(); }
9185 
9186  private:
9187  Local<Context> context_;
9188  };
9189 
9190  /**
9191  * Stack-allocated class to support the backup incumbent settings object
9192  * stack.
9193  * https://html.spec.whatwg.org/multipage/webappapis.html#backup-incumbent-settings-object-stack
9194  */
9196  public:
9197  /**
9198  * |backup_incumbent_context| is pushed onto the backup incumbent settings
9199  * object stack.
9200  */
9201  explicit BackupIncumbentScope(Local<Context> backup_incumbent_context);
9203 
9204  private:
9205  friend class internal::Isolate;
9206 
9207  Local<Context> backup_incumbent_context_;
9208  const BackupIncumbentScope* prev_ = nullptr;
9209  };
9210 
9211  private:
9212  friend class Value;
9213  friend class Script;
9214  friend class Object;
9215  friend class Function;
9216 
9217  internal::Object** GetDataFromSnapshotOnce(size_t index);
9218  Local<Value> SlowGetEmbedderData(int index);
9219  void* SlowGetAlignedPointerFromEmbedderData(int index);
9220 };
9221 
9222 
9223 /**
9224  * Multiple threads in V8 are allowed, but only one thread at a time is allowed
9225  * to use any given V8 isolate, see the comments in the Isolate class. The
9226  * definition of 'using a V8 isolate' includes accessing handles or holding onto
9227  * object pointers obtained from V8 handles while in the particular V8 isolate.
9228  * It is up to the user of V8 to ensure, perhaps with locking, that this
9229  * constraint is not violated. In addition to any other synchronization
9230  * mechanism that may be used, the v8::Locker and v8::Unlocker classes must be
9231  * used to signal thread switches to V8.
9232  *
9233  * v8::Locker is a scoped lock object. While it's active, i.e. between its
9234  * construction and destruction, the current thread is allowed to use the locked
9235  * isolate. V8 guarantees that an isolate can be locked by at most one thread at
9236  * any time. In other words, the scope of a v8::Locker is a critical section.
9237  *
9238  * Sample usage:
9239 * \code
9240  * ...
9241  * {
9242  * v8::Locker locker(isolate);
9243  * v8::Isolate::Scope isolate_scope(isolate);
9244  * ...
9245  * // Code using V8 and isolate goes here.
9246  * ...
9247  * } // Destructor called here
9248  * \endcode
9249  *
9250  * If you wish to stop using V8 in a thread A you can do this either by
9251  * destroying the v8::Locker object as above or by constructing a v8::Unlocker
9252  * object:
9253  *
9254  * \code
9255  * {
9256  * isolate->Exit();
9257  * v8::Unlocker unlocker(isolate);
9258  * ...
9259  * // Code not using V8 goes here while V8 can run in another thread.
9260  * ...
9261  * } // Destructor called here.
9262  * isolate->Enter();
9263  * \endcode
9264  *
9265  * The Unlocker object is intended for use in a long-running callback from V8,
9266  * where you want to release the V8 lock for other threads to use.
9267  *
9268  * The v8::Locker is a recursive lock, i.e. you can lock more than once in a
9269  * given thread. This can be useful if you have code that can be called either
9270  * from code that holds the lock or from code that does not. The Unlocker is
9271  * not recursive so you can not have several Unlockers on the stack at once, and
9272  * you can not use an Unlocker in a thread that is not inside a Locker's scope.
9273  *
9274  * An unlocker will unlock several lockers if it has to and reinstate the
9275  * correct depth of locking on its destruction, e.g.:
9276  *
9277  * \code
9278  * // V8 not locked.
9279  * {
9280  * v8::Locker locker(isolate);
9281  * Isolate::Scope isolate_scope(isolate);
9282  * // V8 locked.
9283  * {
9284  * v8::Locker another_locker(isolate);
9285  * // V8 still locked (2 levels).
9286  * {
9287  * isolate->Exit();
9288  * v8::Unlocker unlocker(isolate);
9289  * // V8 not locked.
9290  * }
9291  * isolate->Enter();
9292  * // V8 locked again (2 levels).
9293  * }
9294  * // V8 still locked (1 level).
9295  * }
9296  * // V8 Now no longer locked.
9297  * \endcode
9298  */
9299 class V8_EXPORT Unlocker {
9300  public:
9301  /**
9302  * Initialize Unlocker for a given Isolate.
9303  */
9304  V8_INLINE explicit Unlocker(Isolate* isolate) { Initialize(isolate); }
9305 
9306  ~Unlocker();
9307  private:
9308  void Initialize(Isolate* isolate);
9309 
9310  internal::Isolate* isolate_;
9311 };
9312 
9313 
9314 class V8_EXPORT Locker {
9315  public:
9316  /**
9317  * Initialize Locker for a given Isolate.
9318  */
9319  V8_INLINE explicit Locker(Isolate* isolate) { Initialize(isolate); }
9320 
9321  ~Locker();
9322 
9323  /**
9324  * Returns whether or not the locker for a given isolate, is locked by the
9325  * current thread.
9326  */
9327  static bool IsLocked(Isolate* isolate);
9328 
9329  /**
9330  * Returns whether v8::Locker is being used by this V8 instance.
9331  */
9332  static bool IsActive();
9333 
9334  // Disallow copying and assigning.
9335  Locker(const Locker&) = delete;
9336  void operator=(const Locker&) = delete;
9337 
9338  private:
9339  void Initialize(Isolate* isolate);
9340 
9341  bool has_lock_;
9342  bool top_level_;
9343  internal::Isolate* isolate_;
9344 };
9345 
9346 
9347 // --- Implementation ---
9348 
9349 
9350 namespace internal {
9351 
9352 /**
9353  * This class exports constants and functionality from within v8 that
9354  * is necessary to implement inline functions in the v8 api. Don't
9355  * depend on functions and constants defined here.
9356  */
9357 class Internals {
9358  public:
9359  // These values match non-compiler-dependent values defined within
9360  // the implementation of v8.
9361  static const int kHeapObjectMapOffset = 0;
9363  static const int kStringResourceOffset = 3 * kApiPointerSize;
9364 
9367  static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
9368  static const int kFixedArrayHeaderSize = 2 * kApiPointerSize;
9369  static const int kContextHeaderSize = 2 * kApiPointerSize;
9370  static const int kContextEmbedderDataIndex = 5;
9371  static const int kFullStringRepresentationMask = 0x0f;
9372  static const int kStringEncodingMask = 0x8;
9373  static const int kExternalTwoByteRepresentationTag = 0x02;
9374  static const int kExternalOneByteRepresentationTag = 0x0a;
9375 
9377  static const int kExternalMemoryOffset = 4 * kApiPointerSize;
9378  static const int kExternalMemoryLimitOffset =
9385  static const int kUndefinedValueRootIndex = 4;
9386  static const int kTheHoleValueRootIndex = 5;
9387  static const int kNullValueRootIndex = 6;
9388  static const int kTrueValueRootIndex = 7;
9389  static const int kFalseValueRootIndex = 8;
9390  static const int kEmptyStringRootIndex = 9;
9391 
9392  static const int kNodeClassIdOffset = 1 * kApiPointerSize;
9393  static const int kNodeFlagsOffset = 1 * kApiPointerSize + 3;
9394  static const int kNodeStateMask = 0x7;
9395  static const int kNodeStateIsWeakValue = 2;
9396  static const int kNodeStateIsPendingValue = 3;
9397  static const int kNodeStateIsNearDeathValue = 4;
9398  static const int kNodeIsIndependentShift = 3;
9399  static const int kNodeIsActiveShift = 4;
9400 
9401  static const int kFirstNonstringType = 0x80;
9402  static const int kOddballType = 0x83;
9403  static const int kForeignType = 0x87;
9404  static const int kJSSpecialApiObjectType = 0x410;
9405  static const int kJSApiObjectType = 0x420;
9406  static const int kJSObjectType = 0x421;
9407 
9408  static const int kUndefinedOddballKind = 5;
9409  static const int kNullOddballKind = 3;
9410 
9411  static const uint32_t kNumIsolateDataSlots = 4;
9412 
9413  V8_EXPORT static void CheckInitializedImpl(v8::Isolate* isolate);
9414  V8_INLINE static void CheckInitialized(v8::Isolate* isolate) {
9415 #ifdef V8_ENABLE_CHECKS
9416  CheckInitializedImpl(isolate);
9417 #endif
9418  }
9419 
9420  V8_INLINE static bool HasHeapObjectTag(const internal::Object* value) {
9421  return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
9422  kHeapObjectTag);
9423  }
9424 
9425  V8_INLINE static int SmiValue(const internal::Object* value) {
9426  return PlatformSmiTagging::SmiToInt(value);
9427  }
9428 
9429  V8_INLINE static internal::Object* IntToSmi(int value) {
9430  return PlatformSmiTagging::IntToSmi(value);
9431  }
9432 
9433  V8_INLINE static constexpr bool IsValidSmi(intptr_t value) {
9435  }
9436 
9437  V8_INLINE static int GetInstanceType(const internal::Object* obj) {
9438  typedef internal::Object O;
9440  return ReadField<uint16_t>(map, kMapInstanceTypeOffset);
9441  }
9442 
9443  V8_INLINE static int GetOddballKind(const internal::Object* obj) {
9444  typedef internal::Object O;
9446  }
9447 
9448  V8_INLINE static bool IsExternalTwoByteString(int instance_type) {
9449  int representation = (instance_type & kFullStringRepresentationMask);
9450  return representation == kExternalTwoByteRepresentationTag;
9451  }
9452 
9453  V8_INLINE static uint8_t GetNodeFlag(internal::Object** obj, int shift) {
9454  uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
9455  return *addr & static_cast<uint8_t>(1U << shift);
9456  }
9457 
9458  V8_INLINE static void UpdateNodeFlag(internal::Object** obj,
9459  bool value, int shift) {
9460  uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
9461  uint8_t mask = static_cast<uint8_t>(1U << shift);
9462  *addr = static_cast<uint8_t>((*addr & ~mask) | (value << shift));
9463  }
9464 
9465  V8_INLINE static uint8_t GetNodeState(internal::Object** obj) {
9466  uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
9467  return *addr & kNodeStateMask;
9468  }
9469 
9470  V8_INLINE static void UpdateNodeState(internal::Object** obj,
9471  uint8_t value) {
9472  uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
9473  *addr = static_cast<uint8_t>((*addr & ~kNodeStateMask) | value);
9474  }
9475 
9476  V8_INLINE static void SetEmbedderData(v8::Isolate* isolate,
9477  uint32_t slot,
9478  void* data) {
9479  uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) +
9481  *reinterpret_cast<void**>(addr) = data;
9482  }
9483 
9484  V8_INLINE static void* GetEmbedderData(const v8::Isolate* isolate,
9485  uint32_t slot) {
9486  const uint8_t* addr = reinterpret_cast<const uint8_t*>(isolate) +
9488  return *reinterpret_cast<void* const*>(addr);
9489  }
9490 
9491  V8_INLINE static internal::Object** GetRoot(v8::Isolate* isolate,
9492  int index) {
9493  uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) + kIsolateRootsOffset;
9494  return reinterpret_cast<internal::Object**>(addr + index * kApiPointerSize);
9495  }
9496 
9497  template <typename T>
9498  V8_INLINE static T ReadField(const internal::Object* ptr, int offset) {
9499  const uint8_t* addr =
9500  reinterpret_cast<const uint8_t*>(ptr) + offset - kHeapObjectTag;
9501  return *reinterpret_cast<const T*>(addr);
9502  }
9503 
9504  template <typename T>
9505  V8_INLINE static T ReadEmbedderData(const v8::Context* context, int index) {
9506  typedef internal::Object O;
9507  typedef internal::Internals I;
9508  O* ctx = *reinterpret_cast<O* const*>(context);
9509  int embedder_data_offset = I::kContextHeaderSize +
9511  O* embedder_data = I::ReadField<O*>(ctx, embedder_data_offset);
9512  int value_offset =
9514  return I::ReadField<T>(embedder_data, value_offset);
9515  }
9516 };
9517 
9518 // Only perform cast check for types derived from v8::Data since
9519 // other types do not implement the Cast method.
9520 template <bool PerformCheck>
9521 struct CastCheck {
9522  template <class T>
9523  static void Perform(T* data);
9524 };
9525 
9526 template <>
9527 template <class T>
9528 void CastCheck<true>::Perform(T* data) {
9529  T::Cast(data);
9530 }
9531 
9532 template <>
9533 template <class T>
9534 void CastCheck<false>::Perform(T* data) {}
9535 
9536 template <class T>
9538  CastCheck<std::is_base_of<Data, T>::value>::Perform(data);
9539 }
9540 
9541 } // namespace internal
9542 
9543 
9544 template <class T>
9545 Local<T> Local<T>::New(Isolate* isolate, Local<T> that) {
9546  return New(isolate, that.val_);
9547 }
9548 
9549 template <class T>
9550 Local<T> Local<T>::New(Isolate* isolate, const PersistentBase<T>& that) {
9551  return New(isolate, that.val_);
9552 }
9553 
9554 
9555 template <class T>
9556 Local<T> Local<T>::New(Isolate* isolate, T* that) {
9557  if (that == NULL) return Local<T>();
9558  T* that_ptr = that;
9559  internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
9560  return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
9561  reinterpret_cast<internal::Isolate*>(isolate), *p)));
9562 }
9563 
9564 
9565 template<class T>
9566 template<class S>
9567 void Eternal<T>::Set(Isolate* isolate, Local<S> handle) {
9568  TYPE_CHECK(T, S);
9569  val_ = reinterpret_cast<T*>(
9570  V8::Eternalize(isolate, reinterpret_cast<Value*>(*handle)));
9571 }
9572 
9573 template <class T>
9574 Local<T> Eternal<T>::Get(Isolate* isolate) const {
9575  // The eternal handle will never go away, so as with the roots, we don't even
9576  // need to open a handle.
9577  return Local<T>(val_);
9578 }
9579 
9580 
9581 template <class T>
9583  if (V8_UNLIKELY(val_ == nullptr)) V8::ToLocalEmpty();
9584  return Local<T>(val_);
9585 }
9586 
9587 
9588 template <class T>
9589 void* WeakCallbackInfo<T>::GetInternalField(int index) const {
9590 #ifdef V8_ENABLE_CHECKS
9591  if (index < 0 || index >= kEmbedderFieldsInWeakCallback) {
9592  V8::InternalFieldOutOfBounds(index);
9593  }
9594 #endif
9595  return embedder_fields_[index];
9596 }
9597 
9598 
9599 template <class T>
9600 T* PersistentBase<T>::New(Isolate* isolate, T* that) {
9601  if (that == NULL) return NULL;
9602  internal::Object** p = reinterpret_cast<internal::Object**>(that);
9603  return reinterpret_cast<T*>(
9604  V8::GlobalizeReference(reinterpret_cast<internal::Isolate*>(isolate),
9605  p));
9606 }
9607 
9608 
9609 template <class T, class M>
9610 template <class S, class M2>
9611 void Persistent<T, M>::Copy(const Persistent<S, M2>& that) {
9612  TYPE_CHECK(T, S);
9613  this->Reset();
9614  if (that.IsEmpty()) return;
9615  internal::Object** p = reinterpret_cast<internal::Object**>(that.val_);
9616  this->val_ = reinterpret_cast<T*>(V8::CopyPersistent(p));
9617  M::Copy(that, this);
9618 }
9619 
9620 template <class T>
9621 bool PersistentBase<T>::IsIndependent() const {
9622  typedef internal::Internals I;
9623  if (this->IsEmpty()) return false;
9624  return I::GetNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
9626 }
9627 
9628 template <class T>
9629 bool PersistentBase<T>::IsNearDeath() const {
9630  typedef internal::Internals I;
9631  if (this->IsEmpty()) return false;
9632  uint8_t node_state =
9633  I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_));
9634  return node_state == I::kNodeStateIsNearDeathValue ||
9635  node_state == I::kNodeStateIsPendingValue;
9636 }
9637 
9638 
9639 template <class T>
9640 bool PersistentBase<T>::IsWeak() const {
9641  typedef internal::Internals I;
9642  if (this->IsEmpty()) return false;
9643  return I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_)) ==
9645 }
9646 
9647 
9648 template <class T>
9649 void PersistentBase<T>::Reset() {
9650  if (this->IsEmpty()) return;
9651  V8::DisposeGlobal(reinterpret_cast<internal::Object**>(this->val_));
9652  val_ = 0;
9653 }
9654 
9655 
9656 template <class T>
9657 template <class S>
9658 void PersistentBase<T>::Reset(Isolate* isolate, const Local<S>& other) {
9659  TYPE_CHECK(T, S);
9660  Reset();
9661  if (other.IsEmpty()) return;
9662  this->val_ = New(isolate, other.val_);
9663 }
9664 
9665 
9666 template <class T>
9667 template <class S>
9668 void PersistentBase<T>::Reset(Isolate* isolate,
9669  const PersistentBase<S>& other) {
9670  TYPE_CHECK(T, S);
9671  Reset();
9672  if (other.IsEmpty()) return;
9673  this->val_ = New(isolate, other.val_);
9674 }
9675 
9676 
9677 template <class T>
9678 template <typename P>
9680  P* parameter, typename WeakCallbackInfo<P>::Callback callback,
9681  WeakCallbackType type) {
9682  typedef typename WeakCallbackInfo<void>::Callback Callback;
9683  V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter,
9684  reinterpret_cast<Callback>(callback), type);
9685 }
9686 
9687 template <class T>
9689  V8::MakeWeak(reinterpret_cast<internal::Object***>(&this->val_));
9690 }
9691 
9692 template <class T>
9693 template <typename P>
9694 P* PersistentBase<T>::ClearWeak() {
9695  return reinterpret_cast<P*>(
9696  V8::ClearWeak(reinterpret_cast<internal::Object**>(this->val_)));
9697 }
9698 
9699 template <class T>
9700 void PersistentBase<T>::AnnotateStrongRetainer(const char* label) {
9701  V8::AnnotateStrongRetainer(reinterpret_cast<internal::Object**>(this->val_),
9702  label);
9703 }
9704 
9705 template <class T>
9706 void PersistentBase<T>::RegisterExternalReference(Isolate* isolate) const {
9707  if (IsEmpty()) return;
9708  V8::RegisterExternallyReferencedObject(
9709  reinterpret_cast<internal::Object**>(this->val_),
9710  reinterpret_cast<internal::Isolate*>(isolate));
9711 }
9712 
9713 template <class T>
9714 void PersistentBase<T>::MarkIndependent() {
9715  typedef internal::Internals I;
9716  if (this->IsEmpty()) return;
9717  I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_), true,
9719 }
9720 
9721 template <class T>
9723  typedef internal::Internals I;
9724  if (this->IsEmpty()) return;
9725  I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_), true,
9727 }
9728 
9729 
9730 template <class T>
9731 void PersistentBase<T>::SetWrapperClassId(uint16_t class_id) {
9732  typedef internal::Internals I;
9733  if (this->IsEmpty()) return;
9734  internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
9735  uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
9736  *reinterpret_cast<uint16_t*>(addr) = class_id;
9737 }
9738 
9739 
9740 template <class T>
9741 uint16_t PersistentBase<T>::WrapperClassId() const {
9742  typedef internal::Internals I;
9743  if (this->IsEmpty()) return 0;
9744  internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
9745  uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
9746  return *reinterpret_cast<uint16_t*>(addr);
9747 }
9748 
9749 
9750 template<typename T>
9751 ReturnValue<T>::ReturnValue(internal::Object** slot) : value_(slot) {}
9752 
9753 template<typename T>
9754 template<typename S>
9755 void ReturnValue<T>::Set(const Persistent<S>& handle) {
9756  TYPE_CHECK(T, S);
9757  if (V8_UNLIKELY(handle.IsEmpty())) {
9758  *value_ = GetDefaultValue();
9759  } else {
9760  *value_ = *reinterpret_cast<internal::Object**>(*handle);
9761  }
9762 }
9763 
9764 template <typename T>
9765 template <typename S>
9766 void ReturnValue<T>::Set(const Global<S>& handle) {
9767  TYPE_CHECK(T, S);
9768  if (V8_UNLIKELY(handle.IsEmpty())) {
9769  *value_ = GetDefaultValue();
9770  } else {
9771  *value_ = *reinterpret_cast<internal::Object**>(*handle);
9772  }
9773 }
9774 
9775 template <typename T>
9776 template <typename S>
9777 void ReturnValue<T>::Set(const Local<S> handle) {
9778  TYPE_CHECK(T, S);
9779  if (V8_UNLIKELY(handle.IsEmpty())) {
9780  *value_ = GetDefaultValue();
9781  } else {
9782  *value_ = *reinterpret_cast<internal::Object**>(*handle);
9783  }
9784 }
9785 
9786 template<typename T>
9787 void ReturnValue<T>::Set(double i) {
9788  TYPE_CHECK(T, Number);
9790 }
9791 
9792 template<typename T>
9793 void ReturnValue<T>::Set(int32_t i) {
9794  TYPE_CHECK(T, Integer);
9795  typedef internal::Internals I;
9796  if (V8_LIKELY(I::IsValidSmi(i))) {
9797  *value_ = I::IntToSmi(i);
9798  return;
9799  }
9801 }
9802 
9803 template<typename T>
9804 void ReturnValue<T>::Set(uint32_t i) {
9805  TYPE_CHECK(T, Integer);
9806  // Can't simply use INT32_MAX here for whatever reason.
9807  bool fits_into_int32_t = (i & (1U << 31)) == 0;
9808  if (V8_LIKELY(fits_into_int32_t)) {
9809  Set(static_cast<int32_t>(i));
9810  return;
9811  }
9813 }
9814 
9815 template<typename T>
9816 void ReturnValue<T>::Set(bool value) {
9817  TYPE_CHECK(T, Boolean);
9818  typedef internal::Internals I;
9819  int root_index;
9820  if (value) {
9821  root_index = I::kTrueValueRootIndex;
9822  } else {
9823  root_index = I::kFalseValueRootIndex;
9824  }
9825  *value_ = *I::GetRoot(GetIsolate(), root_index);
9826 }
9827 
9828 template<typename T>
9829 void ReturnValue<T>::SetNull() {
9830  TYPE_CHECK(T, Primitive);
9831  typedef internal::Internals I;
9833 }
9834 
9835 template<typename T>
9837  TYPE_CHECK(T, Primitive);
9838  typedef internal::Internals I;
9840 }
9841 
9842 template<typename T>
9844  TYPE_CHECK(T, String);
9845  typedef internal::Internals I;
9847 }
9848 
9849 template <typename T>
9850 Isolate* ReturnValue<T>::GetIsolate() const {
9851  // Isolate is always the pointer below the default value on the stack.
9852  return *reinterpret_cast<Isolate**>(&value_[-2]);
9853 }
9854 
9855 template <typename T>
9856 Local<Value> ReturnValue<T>::Get() const {
9857  typedef internal::Internals I;
9859  return Local<Value>(*Undefined(GetIsolate()));
9860  return Local<Value>::New(GetIsolate(), reinterpret_cast<Value*>(value_));
9861 }
9862 
9863 template <typename T>
9864 template <typename S>
9865 void ReturnValue<T>::Set(S* whatever) {
9866  // Uncompilable to prevent inadvertent misuse.
9867  TYPE_CHECK(S*, Primitive);
9868 }
9869 
9870 template<typename T>
9871 internal::Object* ReturnValue<T>::GetDefaultValue() {
9872  // Default value is always the pointer below value_ on the stack.
9873  return value_[-1];
9874 }
9875 
9876 template <typename T>
9878  internal::Object** values,
9879  int length)
9880  : implicit_args_(implicit_args), values_(values), length_(length) {}
9881 
9882 template<typename T>
9884  if (i < 0 || length_ <= i) return Local<Value>(*Undefined(GetIsolate()));
9885  return Local<Value>(reinterpret_cast<Value*>(values_ - i));
9886 }
9887 
9888 
9889 template<typename T>
9891  return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
9892 }
9893 
9894 
9895 template<typename T>
9897  return Local<Object>(reinterpret_cast<Object*>(
9899 }
9900 
9901 template <typename T>
9903  return Local<Value>(
9904  reinterpret_cast<Value*>(&implicit_args_[kNewTargetIndex]));
9905 }
9906 
9907 template <typename T>
9909  return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
9910 }
9911 
9912 
9913 template<typename T>
9914 Isolate* FunctionCallbackInfo<T>::GetIsolate() const {
9915  return *reinterpret_cast<Isolate**>(&implicit_args_[kIsolateIndex]);
9916 }
9917 
9918 
9919 template<typename T>
9922 }
9923 
9924 
9925 template<typename T>
9927  return !NewTarget()->IsUndefined();
9928 }
9929 
9930 
9931 template<typename T>
9932 int FunctionCallbackInfo<T>::Length() const {
9933  return length_;
9934 }
9935 
9937  Local<Integer> resource_line_offset,
9938  Local<Integer> resource_column_offset,
9939  Local<Boolean> resource_is_shared_cross_origin,
9940  Local<Integer> script_id,
9941  Local<Value> source_map_url,
9942  Local<Boolean> resource_is_opaque,
9943  Local<Boolean> is_wasm, Local<Boolean> is_module,
9944  Local<PrimitiveArray> host_defined_options)
9945  : resource_name_(resource_name),
9946  resource_line_offset_(resource_line_offset),
9947  resource_column_offset_(resource_column_offset),
9948  options_(!resource_is_shared_cross_origin.IsEmpty() &&
9949  resource_is_shared_cross_origin->IsTrue(),
9950  !resource_is_opaque.IsEmpty() && resource_is_opaque->IsTrue(),
9951  !is_wasm.IsEmpty() && is_wasm->IsTrue(),
9952  !is_module.IsEmpty() && is_module->IsTrue()),
9953  script_id_(script_id),
9954  source_map_url_(source_map_url),
9955  host_defined_options_(host_defined_options) {}
9956 
9957 Local<Value> ScriptOrigin::ResourceName() const { return resource_name_; }
9958 
9960  return host_defined_options_;
9961 }
9962 
9964  return resource_line_offset_;
9965 }
9966 
9967 
9969  return resource_column_offset_;
9970 }
9971 
9972 
9973 Local<Integer> ScriptOrigin::ScriptID() const { return script_id_; }
9974 
9975 
9976 Local<Value> ScriptOrigin::SourceMapUrl() const { return source_map_url_; }
9977 
9979  CachedData* data)
9980  : source_string(string),
9981  resource_name(origin.ResourceName()),
9982  resource_line_offset(origin.ResourceLineOffset()),
9983  resource_column_offset(origin.ResourceColumnOffset()),
9984  resource_options(origin.Options()),
9985  source_map_url(origin.SourceMapUrl()),
9986  host_defined_options(origin.HostDefinedOptions()),
9987  cached_data(data) {}
9988 
9990  CachedData* data)
9991  : source_string(string), cached_data(data) {}
9992 
9993 
9995  delete cached_data;
9996 }
9997 
9998 
10000  const {
10001  return cached_data;
10002 }
10003 
10005  return resource_options;
10006 }
10007 
10008 Local<Boolean> Boolean::New(Isolate* isolate, bool value) {
10009  return value ? True(isolate) : False(isolate);
10010 }
10011 
10012 void Template::Set(Isolate* isolate, const char* name, Local<Data> value) {
10015  value);
10016 }
10017 
10019 #ifdef V8_ENABLE_CHECKS
10020  CheckCast(data);
10021 #endif
10022  return reinterpret_cast<FunctionTemplate*>(data);
10023 }
10024 
10026 #ifdef V8_ENABLE_CHECKS
10027  CheckCast(data);
10028 #endif
10029  return reinterpret_cast<ObjectTemplate*>(data);
10030 }
10031 
10033 #ifdef V8_ENABLE_CHECKS
10034  CheckCast(data);
10035 #endif
10036  return reinterpret_cast<Signature*>(data);
10037 }
10038 
10040 #ifdef V8_ENABLE_CHECKS
10041  CheckCast(data);
10042 #endif
10043  return reinterpret_cast<AccessorSignature*>(data);
10044 }
10045 
10047 #ifndef V8_ENABLE_CHECKS
10048  typedef internal::Object O;
10049  typedef internal::Internals I;
10050  O* obj = *reinterpret_cast<O**>(this);
10051  // Fast path: If the object is a plain JSObject, which is the common case, we
10052  // know where to find the internal fields and can return the value directly.
10053  auto instance_type = I::GetInstanceType(obj);
10054  if (instance_type == I::kJSObjectType ||
10055  instance_type == I::kJSApiObjectType ||
10056  instance_type == I::kJSSpecialApiObjectType) {
10057  int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
10058  O* value = I::ReadField<O*>(obj, offset);
10059  O** result = HandleScope::CreateHandle(
10060  reinterpret_cast<internal::NeverReadOnlySpaceObject*>(obj), value);
10061  return Local<Value>(reinterpret_cast<Value*>(result));
10062  }
10063 #endif
10064  return SlowGetInternalField(index);
10065 }
10066 
10067 
10069 #ifndef V8_ENABLE_CHECKS
10070  typedef internal::Object O;
10071  typedef internal::Internals I;
10072  O* obj = *reinterpret_cast<O**>(this);
10073  // Fast path: If the object is a plain JSObject, which is the common case, we
10074  // know where to find the internal fields and can return the value directly.
10075  auto instance_type = I::GetInstanceType(obj);
10076  if (V8_LIKELY(instance_type == I::kJSObjectType ||
10077  instance_type == I::kJSApiObjectType ||
10078  instance_type == I::kJSSpecialApiObjectType)) {
10079  int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
10080  return I::ReadField<void*>(obj, offset);
10081  }
10082 #endif
10083  return SlowGetAlignedPointerFromInternalField(index);
10084 }
10085 
10086 String* String::Cast(v8::Value* value) {
10087 #ifdef V8_ENABLE_CHECKS
10088  CheckCast(value);
10089 #endif
10090  return static_cast<String*>(value);
10091 }
10092 
10093 
10094 Local<String> String::Empty(Isolate* isolate) {
10095  typedef internal::Object* S;
10096  typedef internal::Internals I;
10097  I::CheckInitialized(isolate);
10098  S* slot = I::GetRoot(isolate, I::kEmptyStringRootIndex);
10099  return Local<String>(reinterpret_cast<String*>(slot));
10100 }
10101 
10102 
10104  typedef internal::Object O;
10105  typedef internal::Internals I;
10106  O* obj = *reinterpret_cast<O* const*>(this);
10107 
10108  ExternalStringResource* result;
10110  void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
10111  result = reinterpret_cast<String::ExternalStringResource*>(value);
10112  } else {
10113  result = GetExternalStringResourceSlow();
10114  }
10115 #ifdef V8_ENABLE_CHECKS
10116  VerifyExternalStringResource(result);
10117 #endif
10118  return result;
10119 }
10120 
10121 
10123  String::Encoding* encoding_out) const {
10124  typedef internal::Object O;
10125  typedef internal::Internals I;
10126  O* obj = *reinterpret_cast<O* const*>(this);
10128  *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
10129  ExternalStringResourceBase* resource;
10130  if (type == I::kExternalOneByteRepresentationTag ||
10132  void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
10133  resource = static_cast<ExternalStringResourceBase*>(value);
10134  } else {
10135  resource = GetExternalStringResourceBaseSlow(encoding_out);
10136  }
10137 #ifdef V8_ENABLE_CHECKS
10138  VerifyExternalStringResourceBase(resource, *encoding_out);
10139 #endif
10140  return resource;
10141 }
10142 
10143 
10144 bool Value::IsUndefined() const {
10145 #ifdef V8_ENABLE_CHECKS
10146  return FullIsUndefined();
10147 #else
10148  return QuickIsUndefined();
10149 #endif
10150 }
10151 
10152 bool Value::QuickIsUndefined() const {
10153  typedef internal::Object O;
10154  typedef internal::Internals I;
10155  O* obj = *reinterpret_cast<O* const*>(this);
10156  if (!I::HasHeapObjectTag(obj)) return false;
10157  if (I::GetInstanceType(obj) != I::kOddballType) return false;
10159 }
10160 
10161 
10162 bool Value::IsNull() const {
10163 #ifdef V8_ENABLE_CHECKS
10164  return FullIsNull();
10165 #else
10166  return QuickIsNull();
10167 #endif
10168 }
10169 
10170 bool Value::QuickIsNull() const {
10171  typedef internal::Object O;
10172  typedef internal::Internals I;
10173  O* obj = *reinterpret_cast<O* const*>(this);
10174  if (!I::HasHeapObjectTag(obj)) return false;
10175  if (I::GetInstanceType(obj) != I::kOddballType) return false;
10176  return (I::GetOddballKind(obj) == I::kNullOddballKind);
10177 }
10178 
10179 bool Value::IsNullOrUndefined() const {
10180 #ifdef V8_ENABLE_CHECKS
10181  return FullIsNull() || FullIsUndefined();
10182 #else
10183  return QuickIsNullOrUndefined();
10184 #endif
10185 }
10186 
10187 bool Value::QuickIsNullOrUndefined() const {
10188  typedef internal::Object O;
10189  typedef internal::Internals I;
10190  O* obj = *reinterpret_cast<O* const*>(this);
10191  if (!I::HasHeapObjectTag(obj)) return false;
10192  if (I::GetInstanceType(obj) != I::kOddballType) return false;
10193  int kind = I::GetOddballKind(obj);
10194  return kind == I::kNullOddballKind || kind == I::kUndefinedOddballKind;
10195 }
10196 
10197 bool Value::IsString() const {
10198 #ifdef V8_ENABLE_CHECKS
10199  return FullIsString();
10200 #else
10201  return QuickIsString();
10202 #endif
10203 }
10204 
10205 bool Value::QuickIsString() const {
10206  typedef internal::Object O;
10207  typedef internal::Internals I;
10208  O* obj = *reinterpret_cast<O* const*>(this);
10209  if (!I::HasHeapObjectTag(obj)) return false;
10211 }
10212 
10213 
10214 template <class T> Value* Value::Cast(T* value) {
10215  return static_cast<Value*>(value);
10216 }
10217 
10218 
10220 #ifdef V8_ENABLE_CHECKS
10221  CheckCast(value);
10222 #endif
10223  return static_cast<Boolean*>(value);
10224 }
10225 
10226 
10227 Name* Name::Cast(v8::Value* value) {
10228 #ifdef V8_ENABLE_CHECKS
10229  CheckCast(value);
10230 #endif
10231  return static_cast<Name*>(value);
10232 }
10233 
10234 
10235 Symbol* Symbol::Cast(v8::Value* value) {
10236 #ifdef V8_ENABLE_CHECKS
10237  CheckCast(value);
10238 #endif
10239  return static_cast<Symbol*>(value);
10240 }
10241 
10242 
10244 #ifdef V8_ENABLE_CHECKS
10245  CheckCast(data);
10246 #endif
10247  return reinterpret_cast<Private*>(data);
10248 }
10249 
10250 
10251 Number* Number::Cast(v8::Value* value) {
10252 #ifdef V8_ENABLE_CHECKS
10253  CheckCast(value);
10254 #endif
10255  return static_cast<Number*>(value);
10256 }
10257 
10258 
10260 #ifdef V8_ENABLE_CHECKS
10261  CheckCast(value);
10262 #endif
10263  return static_cast<Integer*>(value);
10264 }
10265 
10266 
10267 Int32* Int32::Cast(v8::Value* value) {
10268 #ifdef V8_ENABLE_CHECKS
10269  CheckCast(value);
10270 #endif
10271  return static_cast<Int32*>(value);
10272 }
10273 
10274 
10275 Uint32* Uint32::Cast(v8::Value* value) {
10276 #ifdef V8_ENABLE_CHECKS
10277  CheckCast(value);
10278 #endif
10279  return static_cast<Uint32*>(value);
10280 }
10281 
10282 BigInt* BigInt::Cast(v8::Value* value) {
10283 #ifdef V8_ENABLE_CHECKS
10284  CheckCast(value);
10285 #endif
10286  return static_cast<BigInt*>(value);
10287 }
10288 
10289 Date* Date::Cast(v8::Value* value) {
10290 #ifdef V8_ENABLE_CHECKS
10291  CheckCast(value);
10292 #endif
10293  return static_cast<Date*>(value);
10294 }
10295 
10296 
10298 #ifdef V8_ENABLE_CHECKS
10299  CheckCast(value);
10300 #endif
10301  return static_cast<StringObject*>(value);
10302 }
10303 
10304 
10306 #ifdef V8_ENABLE_CHECKS
10307  CheckCast(value);
10308 #endif
10309  return static_cast<SymbolObject*>(value);
10310 }
10311 
10312 
10314 #ifdef V8_ENABLE_CHECKS
10315  CheckCast(value);
10316 #endif
10317  return static_cast<NumberObject*>(value);
10318 }
10319 
10321 #ifdef V8_ENABLE_CHECKS
10322  CheckCast(value);
10323 #endif
10324  return static_cast<BigIntObject*>(value);
10325 }
10326 
10328 #ifdef V8_ENABLE_CHECKS
10329  CheckCast(value);
10330 #endif
10331  return static_cast<BooleanObject*>(value);
10332 }
10333 
10334 
10335 RegExp* RegExp::Cast(v8::Value* value) {
10336 #ifdef V8_ENABLE_CHECKS
10337  CheckCast(value);
10338 #endif
10339  return static_cast<RegExp*>(value);
10340 }
10341 
10342 
10343 Object* Object::Cast(v8::Value* value) {
10344 #ifdef V8_ENABLE_CHECKS
10345  CheckCast(value);
10346 #endif
10347  return static_cast<Object*>(value);
10348 }
10349 
10350 
10351 Array* Array::Cast(v8::Value* value) {
10352 #ifdef V8_ENABLE_CHECKS
10353  CheckCast(value);
10354 #endif
10355  return static_cast<Array*>(value);
10356 }
10357 
10358 
10359 Map* Map::Cast(v8::Value* value) {
10360 #ifdef V8_ENABLE_CHECKS
10361  CheckCast(value);
10362 #endif
10363  return static_cast<Map*>(value);
10364 }
10365 
10366 
10367 Set* Set::Cast(v8::Value* value) {
10368 #ifdef V8_ENABLE_CHECKS
10369  CheckCast(value);
10370 #endif
10371  return static_cast<Set*>(value);
10372 }
10373 
10374 
10376 #ifdef V8_ENABLE_CHECKS
10377  CheckCast(value);
10378 #endif
10379  return static_cast<Promise*>(value);
10380 }
10381 
10382 
10383 Proxy* Proxy::Cast(v8::Value* value) {
10384 #ifdef V8_ENABLE_CHECKS
10385  CheckCast(value);
10386 #endif
10387  return static_cast<Proxy*>(value);
10388 }
10389 
10391 #ifdef V8_ENABLE_CHECKS
10392  CheckCast(value);
10393 #endif
10394  return static_cast<WasmCompiledModule*>(value);
10395 }
10396 
10398 #ifdef V8_ENABLE_CHECKS
10399  CheckCast(value);
10400 #endif
10401  return static_cast<Promise::Resolver*>(value);
10402 }
10403 
10404 
10406 #ifdef V8_ENABLE_CHECKS
10407  CheckCast(value);
10408 #endif
10409  return static_cast<ArrayBuffer*>(value);
10410 }
10411 
10412 
10414 #ifdef V8_ENABLE_CHECKS
10415  CheckCast(value);
10416 #endif
10417  return static_cast<ArrayBufferView*>(value);
10418 }
10419 
10420 
10422 #ifdef V8_ENABLE_CHECKS
10423  CheckCast(value);
10424 #endif
10425  return static_cast<TypedArray*>(value);
10426 }
10427 
10428 
10430 #ifdef V8_ENABLE_CHECKS
10431  CheckCast(value);
10432 #endif
10433  return static_cast<Uint8Array*>(value);
10434 }
10435 
10436 
10438 #ifdef V8_ENABLE_CHECKS
10439  CheckCast(value);
10440 #endif
10441  return static_cast<Int8Array*>(value);
10442 }
10443 
10444 
10446 #ifdef V8_ENABLE_CHECKS
10447  CheckCast(value);
10448 #endif
10449  return static_cast<Uint16Array*>(value);
10450 }
10451 
10452 
10454 #ifdef V8_ENABLE_CHECKS
10455  CheckCast(value);
10456 #endif
10457  return static_cast<Int16Array*>(value);
10458 }
10459 
10460 
10462 #ifdef V8_ENABLE_CHECKS
10463  CheckCast(value);
10464 #endif
10465  return static_cast<Uint32Array*>(value);
10466 }
10467 
10468 
10470 #ifdef V8_ENABLE_CHECKS
10471  CheckCast(value);
10472 #endif
10473  return static_cast<Int32Array*>(value);
10474 }
10475 
10476 
10478 #ifdef V8_ENABLE_CHECKS
10479  CheckCast(value);
10480 #endif
10481  return static_cast<Float32Array*>(value);
10482 }
10483 
10484 
10486 #ifdef V8_ENABLE_CHECKS
10487  CheckCast(value);
10488 #endif
10489  return static_cast<Float64Array*>(value);
10490 }
10491 
10493 #ifdef V8_ENABLE_CHECKS
10494  CheckCast(value);
10495 #endif
10496  return static_cast<BigInt64Array*>(value);
10497 }
10498 
10500 #ifdef V8_ENABLE_CHECKS
10501  CheckCast(value);
10502 #endif
10503  return static_cast<BigUint64Array*>(value);
10504 }
10505 
10507 #ifdef V8_ENABLE_CHECKS
10508  CheckCast(value);
10509 #endif
10510  return static_cast<Uint8ClampedArray*>(value);
10511 }
10512 
10513 
10515 #ifdef V8_ENABLE_CHECKS
10516  CheckCast(value);
10517 #endif
10518  return static_cast<DataView*>(value);
10519 }
10520 
10521 
10523 #ifdef V8_ENABLE_CHECKS
10524  CheckCast(value);
10525 #endif
10526  return static_cast<SharedArrayBuffer*>(value);
10527 }
10528 
10529 
10531 #ifdef V8_ENABLE_CHECKS
10532  CheckCast(value);
10533 #endif
10534  return static_cast<Function*>(value);
10535 }
10536 
10537 
10539 #ifdef V8_ENABLE_CHECKS
10540  CheckCast(value);
10541 #endif
10542  return static_cast<External*>(value);
10543 }
10544 
10545 
10546 template<typename T>
10547 Isolate* PropertyCallbackInfo<T>::GetIsolate() const {
10548  return *reinterpret_cast<Isolate**>(&args_[kIsolateIndex]);
10549 }
10550 
10551 
10552 template<typename T>
10554  return Local<Value>(reinterpret_cast<Value*>(&args_[kDataIndex]));
10555 }
10556 
10557 
10558 template<typename T>
10560  return Local<Object>(reinterpret_cast<Object*>(&args_[kThisIndex]));
10561 }
10562 
10563 
10564 template<typename T>
10566  return Local<Object>(reinterpret_cast<Object*>(&args_[kHolderIndex]));
10567 }
10568 
10569 
10570 template<typename T>
10572  return ReturnValue<T>(&args_[kReturnValueIndex]);
10573 }
10574 
10575 template <typename T>
10577  typedef internal::Internals I;
10579 }
10580 
10581 
10582 Local<Primitive> Undefined(Isolate* isolate) {
10583  typedef internal::Object* S;
10584  typedef internal::Internals I;
10585  I::CheckInitialized(isolate);
10586  S* slot = I::GetRoot(isolate, I::kUndefinedValueRootIndex);
10587  return Local<Primitive>(reinterpret_cast<Primitive*>(slot));
10588 }
10589 
10590 
10591 Local<Primitive> Null(Isolate* isolate) {
10592  typedef internal::Object* S;
10593  typedef internal::Internals I;
10594  I::CheckInitialized(isolate);
10595  S* slot = I::GetRoot(isolate, I::kNullValueRootIndex);
10596  return Local<Primitive>(reinterpret_cast<Primitive*>(slot));
10597 }
10598 
10599 
10600 Local<Boolean> True(Isolate* isolate) {
10601  typedef internal::Object* S;
10602  typedef internal::Internals I;
10603  I::CheckInitialized(isolate);
10604  S* slot = I::GetRoot(isolate, I::kTrueValueRootIndex);
10605  return Local<Boolean>(reinterpret_cast<Boolean*>(slot));
10606 }
10607 
10608 
10609 Local<Boolean> False(Isolate* isolate) {
10610  typedef internal::Object* S;
10611  typedef internal::Internals I;
10612  I::CheckInitialized(isolate);
10613  S* slot = I::GetRoot(isolate, I::kFalseValueRootIndex);
10614  return Local<Boolean>(reinterpret_cast<Boolean*>(slot));
10615 }
10616 
10617 
10618 void Isolate::SetData(uint32_t slot, void* data) {
10619  typedef internal::Internals I;
10620  I::SetEmbedderData(this, slot, data);
10621 }
10622 
10623 
10624 void* Isolate::GetData(uint32_t slot) {
10625  typedef internal::Internals I;
10626  return I::GetEmbedderData(this, slot);
10627 }
10628 
10629 
10630 uint32_t Isolate::GetNumberOfDataSlots() {
10631  typedef internal::Internals I;
10632  return I::kNumIsolateDataSlots;
10633 }
10634 
10635 template <class T>
10636 MaybeLocal<T> Isolate::GetDataFromSnapshotOnce(size_t index) {
10637  T* data = reinterpret_cast<T*>(GetDataFromSnapshotOnce(index));
10638  if (data) internal::PerformCastCheck(data);
10639  return Local<T>(data);
10640 }
10641 
10642 int64_t Isolate::AdjustAmountOfExternalAllocatedMemory(
10643  int64_t change_in_bytes) {
10644  typedef internal::Internals I;
10645  const int64_t kMemoryReducerActivationLimit = 32 * 1024 * 1024;
10646  int64_t* external_memory = reinterpret_cast<int64_t*>(
10647  reinterpret_cast<uint8_t*>(this) + I::kExternalMemoryOffset);
10648  int64_t* external_memory_limit = reinterpret_cast<int64_t*>(
10649  reinterpret_cast<uint8_t*>(this) + I::kExternalMemoryLimitOffset);
10650  int64_t* external_memory_at_last_mc =
10651  reinterpret_cast<int64_t*>(reinterpret_cast<uint8_t*>(this) +
10653  const int64_t amount = *external_memory + change_in_bytes;
10654 
10655  *external_memory = amount;
10656 
10657  int64_t allocation_diff_since_last_mc =
10658  *external_memory_at_last_mc - *external_memory;
10659  allocation_diff_since_last_mc = allocation_diff_since_last_mc < 0
10660  ? -allocation_diff_since_last_mc
10661  : allocation_diff_since_last_mc;
10662  if (allocation_diff_since_last_mc > kMemoryReducerActivationLimit) {
10663  CheckMemoryPressure();
10664  }
10665 
10666  if (change_in_bytes < 0) {
10667  *external_memory_limit += change_in_bytes;
10668  }
10669 
10670  if (change_in_bytes > 0 && amount > *external_memory_limit) {
10671  ReportExternalAllocationLimitReached();
10672  }
10673  return *external_memory;
10674 }
10675 
10676 Local<Value> Context::GetEmbedderData(int index) {
10677 #ifndef V8_ENABLE_CHECKS
10678  typedef internal::Object O;
10679  typedef internal::Internals I;
10680  auto* context = *reinterpret_cast<internal::NeverReadOnlySpaceObject**>(this);
10681  O** result =
10682  HandleScope::CreateHandle(context, I::ReadEmbedderData<O*>(this, index));
10683  return Local<Value>(reinterpret_cast<Value*>(result));
10684 #else
10685  return SlowGetEmbedderData(index);
10686 #endif
10687 }
10688 
10689 
10690 void* Context::GetAlignedPointerFromEmbedderData(int index) {
10691 #ifndef V8_ENABLE_CHECKS
10692  typedef internal::Internals I;
10693  return I::ReadEmbedderData<void*>(this, index);
10694 #else
10695  return SlowGetAlignedPointerFromEmbedderData(index);
10696 #endif
10697 }
10698 
10699 template <class T>
10700 MaybeLocal<T> Context::GetDataFromSnapshotOnce(size_t index) {
10701  T* data = reinterpret_cast<T*>(GetDataFromSnapshotOnce(index));
10702  if (data) internal::PerformCastCheck(data);
10703  return Local<T>(data);
10704 }
10705 
10706 template <class T>
10707 size_t SnapshotCreator::AddData(Local<Context> context, Local<T> object) {
10708  T* object_ptr = *object;
10709  internal::Object** p = reinterpret_cast<internal::Object**>(object_ptr);
10710  return AddData(context, *p);
10711 }
10712 
10713 template <class T>
10714 size_t SnapshotCreator::AddData(Local<T> object) {
10715  T* object_ptr = *object;
10716  internal::Object** p = reinterpret_cast<internal::Object**>(object_ptr);
10717  return AddData(*p);
10718 }
10719 
10720 /**
10721  * \example shell.cc
10722  * A simple shell that takes a list of expressions on the
10723  * command-line and executes them.
10724  */
10725 
10726 
10727 /**
10728  * \example process.cc
10729  */
10730 
10731 
10732 } // namespace v8
10733 
10734 
10735 #undef TYPE_CHECK
10736 
10737 
10738 #endif // INCLUDE_V8_H_