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  */