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