v8  6.7.288(node10.6.0)
V8 is Google's open source JavaScript engine
v8.h
Go to the documentation of this file.
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 /** \mainpage V8 API Reference Guide
6  *
7  * V8 is Google's open source JavaScript engine.
8  *
9  * This set of documents provides reference material generated from the
10  * V8 header file, include/v8.h.
11  *
12  * For other documentation see http://code.google.com/apis/v8/
13  */
14 
15 #ifndef INCLUDE_V8_H_
16 #define INCLUDE_V8_H_
17 
18 #include <stddef.h>
19 #include <stdint.h>
20 #include <stdio.h>
21 #include <memory>
22 #include <utility>
23 #include <vector>
24 
25 #include "v8-version.h" // NOLINT(build/include)
26 #include "v8config.h" // NOLINT(build/include)
27 
28 // We reserve the V8_* prefix for macros defined in V8 public API and
29 // assume there are no name conflicts with the embedder's code.
30 
31 #ifdef V8_OS_WIN
32 
33 // Setup for Windows DLL export/import. When building the V8 DLL the
34 // BUILDING_V8_SHARED needs to be defined. When building a program which uses
35 // the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8
36 // static library or building a program which uses the V8 static library neither
37 // BUILDING_V8_SHARED nor USING_V8_SHARED should be defined.
38 #ifdef BUILDING_V8_SHARED
39 # define V8_EXPORT __declspec(dllexport)
40 #elif USING_V8_SHARED
41 # define V8_EXPORT __declspec(dllimport)
42 #else
43 # define V8_EXPORT
44 #endif // BUILDING_V8_SHARED
45 
46 #else // V8_OS_WIN
47 
48 // Setup for Linux shared library export.
49 #if V8_HAS_ATTRIBUTE_VISIBILITY
50 # ifdef BUILDING_V8_SHARED
51 # define V8_EXPORT __attribute__ ((visibility("default")))
52 # else
53 # define V8_EXPORT
54 # endif
55 #else
56 # define V8_EXPORT
57 #endif
58 
59 #endif // V8_OS_WIN
60 
61 /**
62  * The v8 JavaScript engine.
63  */
64 namespace v8 {
65 
66 class AccessorSignature;
67 class Array;
68 class ArrayBuffer;
69 class BigInt;
70 class BigIntObject;
71 class Boolean;
72 class BooleanObject;
73 class Context;
74 class 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 } // namespace internal
160 
161 namespace debug {
162 class ConsoleCallArguments;
163 } // namespace debug
164 
165 // --- Handles ---
166 
167 #define TYPE_CHECK(T, S)
168  while (false) {
169  *(static_cast<T* volatile*>(0)) = static_cast<S*>(0);
170  }
171 
172 /**
173  * An object reference managed by the v8 garbage collector.
174  *
175  * All objects returned from v8 have to be tracked by the garbage
176  * collector so that it knows that the objects are still alive. Also,
177  * because the garbage collector may move objects, it is unsafe to
178  * point directly to an object. Instead, all objects are stored in
179  * handles which are known by the garbage collector and updated
180  * whenever an object moves. Handles should always be passed by value
181  * (except in cases like out-parameters) and they should never be
182  * allocated on the heap.
183  *
184  * There are two types of handles: local and persistent handles.
185  *
186  * Local handles are light-weight and transient and typically used in
187  * local operations. They are managed by HandleScopes. That means that a
188  * HandleScope must exist on the stack when they are created and that they are
189  * only valid inside of the HandleScope active during their creation.
190  * For passing a local handle to an outer HandleScope, an EscapableHandleScope
191  * and its Escape() method must be used.
192  *
193  * Persistent handles can be used when storing objects across several
194  * independent operations and have to be explicitly deallocated when they're no
195  * longer used.
196  *
197  * It is safe to extract the object stored in the handle by
198  * dereferencing the handle (for instance, to extract the Object* from
199  * a Local<Object>); the value will still be governed by a handle
200  * behind the scenes and the same rules apply to these values as to
201  * their handles.
202  */
203 template <class T>
204 class Local {
205  public:
206  V8_INLINE Local() : val_(0) {}
207  template <class S>
208  V8_INLINE Local(Local<S> that)
209  : val_(reinterpret_cast<T*>(*that)) {
210  /**
211  * This check fails when trying to convert between incompatible
212  * handles. For example, converting from a Local<String> to a
213  * Local<Number>.
214  */
215  TYPE_CHECK(T, S);
216  }
217 
218  /**
219  * Returns true if the handle is empty.
220  */
221  V8_INLINE bool IsEmpty() const { return val_ == 0; }
222 
223  /**
224  * Sets the handle to be empty. IsEmpty() will then return true.
225  */
226  V8_INLINE void Clear() { val_ = 0; }
227 
228  V8_INLINE T* operator->() const { return val_; }
229 
230  V8_INLINE T* operator*() const { return val_; }
231 
232  /**
233  * Checks whether two handles are the same.
234  * Returns true if both are empty, or if the objects
235  * to which they refer are identical.
236  * The handles' references are not checked.
237  */
238  template <class S>
239  V8_INLINE bool operator==(const Local<S>& that) const {
240  internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
241  internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
242  if (a == 0) return b == 0;
243  if (b == 0) return false;
244  return *a == *b;
245  }
246 
247  template <class S> V8_INLINE bool operator==(
248  const PersistentBase<S>& that) const {
249  internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
250  internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
251  if (a == 0) return b == 0;
252  if (b == 0) return false;
253  return *a == *b;
254  }
255 
256  /**
257  * Checks whether two handles are different.
258  * Returns true if only one of the handles is empty, or if
259  * the objects to which they refer are different.
260  * The handles' references are not checked.
261  */
262  template <class S>
263  V8_INLINE bool operator!=(const Local<S>& that) const {
264  return !operator==(that);
265  }
266 
267  template <class S> V8_INLINE bool operator!=(
268  const Persistent<S>& that) const {
269  return !operator==(that);
270  }
271 
272  /**
273  * Cast a handle to a subclass, e.g. Local<Value> to Local<Object>.
274  * This is only valid if the handle actually refers to a value of the
275  * target type.
276  */
277  template <class S> V8_INLINE static Local<T> Cast(Local<S> that) {
278 #ifdef V8_ENABLE_CHECKS
279  // If we're going to perform the type check then we have to check
280  // that the handle isn't empty before doing the checked cast.
281  if (that.IsEmpty()) return Local<T>();
282 #endif
283  return Local<T>(T::Cast(*that));
284  }
285 
286  /**
287  * Calling this is equivalent to Local<S>::Cast().
288  * In particular, this is only valid if the handle actually refers to a value
289  * of the target type.
290  */
291  template <class S>
292  V8_INLINE Local<S> As() const {
293  return Local<S>::Cast(*this);
294  }
295 
296  /**
297  * Create a local handle for the content of another handle.
298  * The referee is kept alive by the local handle even when
299  * the original handle is destroyed/disposed.
300  */
301  V8_INLINE static Local<T> New(Isolate* isolate, Local<T> that);
302  V8_INLINE static Local<T> New(Isolate* isolate,
303  const PersistentBase<T>& that);
304 
305  private:
306  friend class Utils;
307  template<class F> friend class Eternal;
308  template<class F> friend class PersistentBase;
309  template<class F, class M> friend class Persistent;
310  template<class F> friend class Local;
311  template <class F>
312  friend class MaybeLocal;
313  template<class F> friend class FunctionCallbackInfo;
314  template<class F> friend class PropertyCallbackInfo;
315  friend class String;
316  friend class Object;
317  friend class Context;
318  friend class Isolate;
319  friend class Private;
320  template<class F> friend class internal::CustomArguments;
322  friend Local<Primitive> Null(Isolate* isolate);
323  friend Local<Boolean> True(Isolate* isolate);
324  friend Local<Boolean> False(Isolate* isolate);
325  friend class HandleScope;
326  friend class EscapableHandleScope;
327  template <class F1, class F2, class F3>
329  template<class F1, class F2> friend class PersistentValueVector;
330  template <class F>
331  friend class ReturnValue;
332 
333  explicit V8_INLINE Local(T* that) : val_(that) {}
334  V8_INLINE static Local<T> New(Isolate* isolate, T* that);
335  T* val_;
336 };
337 
338 
339 #if !defined(V8_IMMINENT_DEPRECATION_WARNINGS)
340 // Handle is an alias for Local for historical reasons.
341 template <class T>
342 using Handle = Local<T>;
343 #endif
344 
345 
346 /**
347  * A MaybeLocal<> is a wrapper around Local<> that enforces a check whether
348  * the Local<> is empty before it can be used.
349  *
350  * If an API method returns a MaybeLocal<>, the API method can potentially fail
351  * either because an exception is thrown, or because an exception is pending,
352  * e.g. because a previous API call threw an exception that hasn't been caught
353  * yet, or because a TerminateExecution exception was thrown. In that case, an
354  * empty MaybeLocal is returned.
355  */
356 template <class T>
357 class MaybeLocal {
358  public:
360  template <class S>
361  V8_INLINE MaybeLocal(Local<S> that)
362  : val_(reinterpret_cast<T*>(*that)) {
363  TYPE_CHECK(T, S);
364  }
365 
366  V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
367 
368  /**
369  * Converts this MaybeLocal<> to a Local<>. If this MaybeLocal<> is empty,
370  * |false| is returned and |out| is left untouched.
371  */
372  template <class S>
373  V8_WARN_UNUSED_RESULT V8_INLINE bool ToLocal(Local<S>* out) const {
374  out->val_ = IsEmpty() ? nullptr : this->val_;
375  return !IsEmpty();
376  }
377 
378  /**
379  * Converts this MaybeLocal<> to a Local<>. If this MaybeLocal<> is empty,
380  * V8 will crash the process.
381  */
382  V8_INLINE Local<T> ToLocalChecked();
383 
384  /**
385  * Converts this MaybeLocal<> to a Local<>, using a default value if this
386  * MaybeLocal<> is empty.
387  */
388  template <class S>
389  V8_INLINE Local<S> FromMaybe(Local<S> default_value) const {
390  return IsEmpty() ? default_value : Local<S>(val_);
391  }
392 
393  private:
394  T* val_;
395 };
396 
397 /**
398  * Eternal handles are set-once handles that live for the lifetime of the
399  * isolate.
400  */
401 template <class T> class Eternal {
402  public:
404  template <class S>
405  V8_INLINE Eternal(Isolate* isolate, Local<S> handle) : val_(nullptr) {
406  Set(isolate, handle);
407  }
408  // Can only be safely called if already set.
409  V8_INLINE Local<T> Get(Isolate* isolate) const;
410  V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
411  template<class S> V8_INLINE void Set(Isolate* isolate, Local<S> handle);
412 
413  private:
414  T* val_;
415 };
416 
417 
418 static const int kInternalFieldsInWeakCallback = 2;
419 static const int kEmbedderFieldsInWeakCallback = 2;
420 
421 template <typename T>
423  public:
424  typedef void (*Callback)(const WeakCallbackInfo<T>& data);
425 
426  WeakCallbackInfo(Isolate* isolate, T* parameter,
427  void* embedder_fields[kEmbedderFieldsInWeakCallback],
428  Callback* callback)
429  : isolate_(isolate), parameter_(parameter), callback_(callback) {
430  for (int i = 0; i < kEmbedderFieldsInWeakCallback; ++i) {
431  embedder_fields_[i] = embedder_fields[i];
432  }
433  }
434 
435  V8_INLINE Isolate* GetIsolate() const { return isolate_; }
436  V8_INLINE T* GetParameter() const { return parameter_; }
437  V8_INLINE void* GetInternalField(int index) const;
438 
439  // When first called, the embedder MUST Reset() the Global which triggered the
440  // callback. The Global itself is unusable for anything else. No v8 other api
441  // calls may be called in the first callback. Should additional work be
442  // required, the embedder must set a second pass callback, which will be
443  // called after all the initial callbacks are processed.
444  // Calling SetSecondPassCallback on the second pass will immediately crash.
445  void SetSecondPassCallback(Callback callback) const { *callback_ = callback; }
446 
447  private:
448  Isolate* isolate_;
449  T* parameter_;
450  Callback* callback_;
451  void* embedder_fields_[kEmbedderFieldsInWeakCallback];
452 };
453 
454 
455 // kParameter will pass a void* parameter back to the callback, kInternalFields
456 // will pass the first two internal fields back to the callback, kFinalizer
457 // will pass a void* parameter back, but is invoked before the object is
458 // actually collected, so it can be resurrected. In the last case, it is not
459 // possible to request a second pass callback.
461 
462 /**
463  * An object reference that is independent of any handle scope. Where
464  * a Local handle only lives as long as the HandleScope in which it was
465  * allocated, a PersistentBase handle remains valid until it is explicitly
466  * disposed using Reset().
467  *
468  * A persistent handle contains a reference to a storage cell within
469  * the V8 engine which holds an object value and which is updated by
470  * the garbage collector whenever the object is moved. A new storage
471  * cell can be created using the constructor or PersistentBase::Reset and
472  * existing handles can be disposed using PersistentBase::Reset.
473  *
474  */
475 template <class T> class PersistentBase {
476  public:
477  /**
478  * If non-empty, destroy the underlying storage cell
479  * IsEmpty() will return true after this call.
480  */
481  V8_INLINE void Reset();
482  /**
483  * If non-empty, destroy the underlying storage cell
484  * and create a new one with the contents of other if other is non empty
485  */
486  template <class S>
487  V8_INLINE void Reset(Isolate* isolate, const Local<S>& other);
488 
489  /**
490  * If non-empty, destroy the underlying storage cell
491  * and create a new one with the contents of other if other is non empty
492  */
493  template <class S>
494  V8_INLINE void Reset(Isolate* isolate, const PersistentBase<S>& other);
495 
496  V8_INLINE bool IsEmpty() const { return val_ == NULL; }
497  V8_INLINE void Empty() { val_ = 0; }
498 
499  V8_INLINE Local<T> Get(Isolate* isolate) const {
500  return Local<T>::New(isolate, *this);
501  }
502 
503  template <class S>
504  V8_INLINE bool operator==(const PersistentBase<S>& that) const {
505  internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
506  internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
507  if (a == NULL) return b == NULL;
508  if (b == NULL) return false;
509  return *a == *b;
510  }
511 
512  template <class S>
513  V8_INLINE bool operator==(const Local<S>& that) const {
514  internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
515  internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
516  if (a == NULL) return b == NULL;
517  if (b == NULL) return false;
518  return *a == *b;
519  }
520 
521  template <class S>
522  V8_INLINE bool operator!=(const PersistentBase<S>& that) const {
523  return !operator==(that);
524  }
525 
526  template <class S>
527  V8_INLINE bool operator!=(const Local<S>& that) const {
528  return !operator==(that);
529  }
530 
531  /**
532  * Install a finalization callback on this object.
533  * NOTE: There is no guarantee as to *when* or even *if* the callback is
534  * invoked. The invocation is performed solely on a best effort basis.
535  * As always, GC-based finalization should *not* be relied upon for any
536  * critical form of resource management!
537  */
538  template <typename P>
539  V8_INLINE void SetWeak(P* parameter,
540  typename WeakCallbackInfo<P>::Callback callback,
541  WeakCallbackType type);
542 
543  /**
544  * Turns this handle into a weak phantom handle without finalization callback.
545  * The handle will be reset automatically when the garbage collector detects
546  * that the object is no longer reachable.
547  * A related function Isolate::NumberOfPhantomHandleResetsSinceLastCall
548  * returns how many phantom handles were reset by the garbage collector.
549  */
550  V8_INLINE void SetWeak();
551 
552  template<typename P>
553  V8_INLINE P* ClearWeak();
554 
555  // TODO(dcarney): remove this.
556  V8_INLINE void ClearWeak() { ClearWeak<void>(); }
557 
558  /**
559  * Annotates the strong handle with the given label, which is then used by the
560  * heap snapshot generator as a name of the edge from the root to the handle.
561  * The function does not take ownership of the label and assumes that the
562  * label is valid as long as the handle is valid.
563  */
564  V8_INLINE void AnnotateStrongRetainer(const char* label);
565 
566  /**
567  * Allows the embedder to tell the v8 garbage collector that a certain object
568  * is alive. Only allowed when the embedder is asked to trace its heap by
569  * EmbedderHeapTracer.
570  */
571  V8_INLINE void RegisterExternalReference(Isolate* isolate) const;
572 
573  /**
574  * Marks the reference to this object independent. Garbage collector is free
575  * to ignore any object groups containing this object. Weak callback for an
576  * independent handle should not assume that it will be preceded by a global
577  * GC prologue callback or followed by a global GC epilogue callback.
578  */
580  "Objects are always considered independent. "
581  "Use MarkActive to avoid collecting otherwise dead weak handles.",
582  V8_INLINE void MarkIndependent());
583 
584  /**
585  * Marks the reference to this object as active. The scavenge garbage
586  * collection should not reclaim the objects marked as active, even if the
587  * object held by the handle is otherwise unreachable.
588  *
589  * This bit is cleared after the each garbage collection pass.
590  */
591  V8_INLINE void MarkActive();
592 
593  V8_DEPRECATE_SOON("See MarkIndependent.",
594  V8_INLINE bool IsIndependent() const);
595 
596  /** Checks if the handle holds the only reference to an object. */
597  V8_INLINE bool IsNearDeath() const;
598 
599  /** Returns true if the handle's reference is weak. */
600  V8_INLINE bool IsWeak() const;
601 
602  /**
603  * Assigns a wrapper class ID to the handle. See RetainedObjectInfo interface
604  * description in v8-profiler.h for details.
605  */
606  V8_INLINE void SetWrapperClassId(uint16_t class_id);
607 
608  /**
609  * Returns the class ID previously assigned to this handle or 0 if no class ID
610  * was previously assigned.
611  */
612  V8_INLINE uint16_t WrapperClassId() const;
613 
614  PersistentBase(const PersistentBase& other) = delete; // NOLINT
615  void operator=(const PersistentBase&) = delete;
616 
617  private:
618  friend class Isolate;
619  friend class Utils;
620  template<class F> friend class Local;
621  template<class F1, class F2> friend class Persistent;
622  template <class F>
623  friend class Global;
624  template<class F> friend class PersistentBase;
625  template<class F> friend class ReturnValue;
626  template <class F1, class F2, class F3>
628  template<class F1, class F2> friend class PersistentValueVector;
629  friend class Object;
630 
631  explicit V8_INLINE PersistentBase(T* val) : val_(val) {}
632  V8_INLINE static T* New(Isolate* isolate, T* that);
633 
634  T* val_;
635 };
636 
637 
638 /**
639  * Default traits for Persistent. This class does not allow
640  * use of the copy constructor or assignment operator.
641  * At present kResetInDestructor is not set, but that will change in a future
642  * version.
643  */
644 template<class T>
645 class NonCopyablePersistentTraits {
646  public:
647  typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
648  static const bool kResetInDestructor = false;
649  template<class S, class M>
650  V8_INLINE static void Copy(const Persistent<S, M>& source,
651  NonCopyablePersistent* dest) {
652  Uncompilable<Object>();
653  }
654  // TODO(dcarney): come up with a good compile error here.
655  template<class O> V8_INLINE static void Uncompilable() {
656  TYPE_CHECK(O, Primitive);
657  }
658 };
659 
660 
661 /**
662  * Helper class traits to allow copying and assignment of Persistent.
663  * This will clone the contents of storage cell, but not any of the flags, etc.
664  */
665 template<class T>
667  typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
668  static const bool kResetInDestructor = true;
669  template<class S, class M>
670  static V8_INLINE void Copy(const Persistent<S, M>& source,
671  CopyablePersistent* dest) {
672  // do nothing, just allow copy
673  }
674 };
675 
676 
677 /**
678  * A PersistentBase which allows copy and assignment.
679  *
680  * Copy, assignment and destructor behavior is controlled by the traits
681  * class M.
682  *
683  * Note: Persistent class hierarchy is subject to future changes.
684  */
685 template <class T, class M> class Persistent : public PersistentBase<T> {
686  public:
687  /**
688  * A Persistent with no storage cell.
689  */
690  V8_INLINE Persistent() : PersistentBase<T>(0) { }
691  /**
692  * Construct a Persistent from a Local.
693  * When the Local is non-empty, a new storage cell is created
694  * pointing to the same object, and no flags are set.
695  */
696  template <class S>
697  V8_INLINE Persistent(Isolate* isolate, Local<S> that)
698  : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
699  TYPE_CHECK(T, S);
700  }
701  /**
702  * Construct a Persistent from a Persistent.
703  * When the Persistent is non-empty, a new storage cell is created
704  * pointing to the same object, and no flags are set.
705  */
706  template <class S, class M2>
707  V8_INLINE Persistent(Isolate* isolate, const Persistent<S, M2>& that)
708  : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
709  TYPE_CHECK(T, S);
710  }
711  /**
712  * The copy constructors and assignment operator create a Persistent
713  * exactly as the Persistent constructor, but the Copy function from the
714  * traits class is called, allowing the setting of flags based on the
715  * copied Persistent.
716  */
717  V8_INLINE Persistent(const Persistent& that) : PersistentBase<T>(0) {
718  Copy(that);
719  }
720  template <class S, class M2>
721  V8_INLINE Persistent(const Persistent<S, M2>& that) : PersistentBase<T>(0) {
722  Copy(that);
723  }
724  V8_INLINE Persistent& operator=(const Persistent& that) { // NOLINT
725  Copy(that);
726  return *this;
727  }
728  template <class S, class M2>
729  V8_INLINE Persistent& operator=(const Persistent<S, M2>& that) { // NOLINT
730  Copy(that);
731  return *this;
732  }
733  /**
734  * The destructor will dispose the Persistent based on the
735  * kResetInDestructor flags in the traits class. Since not calling dispose
736  * can result in a memory leak, it is recommended to always set this flag.
737  */
739  if (M::kResetInDestructor) this->Reset();
740  }
741 
742  // TODO(dcarney): this is pretty useless, fix or remove
743  template <class S>
744  V8_INLINE static Persistent<T>& Cast(const Persistent<S>& that) { // NOLINT
745 #ifdef V8_ENABLE_CHECKS
746  // If we're going to perform the type check then we have to check
747  // that the handle isn't empty before doing the checked cast.
748  if (!that.IsEmpty()) T::Cast(*that);
749 #endif
750  return reinterpret_cast<Persistent<T>&>(const_cast<Persistent<S>&>(that));
751  }
752 
753  // TODO(dcarney): this is pretty useless, fix or remove
754  template <class S>
755  V8_INLINE Persistent<S>& As() const { // NOLINT
756  return Persistent<S>::Cast(*this);
757  }
758 
759  private:
760  friend class Isolate;
761  friend class Utils;
762  template<class F> friend class Local;
763  template<class F1, class F2> friend class Persistent;
764  template<class F> friend class ReturnValue;
765 
766  explicit V8_INLINE Persistent(T* that) : PersistentBase<T>(that) {}
767  V8_INLINE T* operator*() const { return this->val_; }
768  template<class S, class M2>
769  V8_INLINE void Copy(const Persistent<S, M2>& that);
770 };
771 
772 
773 /**
774  * A PersistentBase which has move semantics.
775  *
776  * Note: Persistent class hierarchy is subject to future changes.
777  */
778 template <class T>
779 class Global : public PersistentBase<T> {
780  public:
781  /**
782  * A Global with no storage cell.
783  */
785  /**
786  * Construct a Global from a Local.
787  * When the Local is non-empty, a new storage cell is created
788  * pointing to the same object, and no flags are set.
789  */
790  template <class S>
791  V8_INLINE Global(Isolate* isolate, Local<S> that)
792  : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
793  TYPE_CHECK(T, S);
794  }
795  /**
796  * Construct a Global from a PersistentBase.
797  * When the Persistent is non-empty, a new storage cell is created
798  * pointing to the same object, and no flags are set.
799  */
800  template <class S>
801  V8_INLINE Global(Isolate* isolate, const PersistentBase<S>& that)
802  : PersistentBase<T>(PersistentBase<T>::New(isolate, that.val_)) {
803  TYPE_CHECK(T, S);
804  }
805  /**
806  * Move constructor.
807  */
808  V8_INLINE Global(Global&& other) : PersistentBase<T>(other.val_) { // NOLINT
809  other.val_ = nullptr;
810  }
811  V8_INLINE ~Global() { this->Reset(); }
812  /**
813  * Move via assignment.
814  */
815  template <class S>
816  V8_INLINE Global& operator=(Global<S>&& rhs) { // NOLINT
817  TYPE_CHECK(T, S);
818  if (this != &rhs) {
819  this->Reset();
820  this->val_ = rhs.val_;
821  rhs.val_ = nullptr;
822  }
823  return *this;
824  }
825  /**
826  * Pass allows returning uniques from functions, etc.
827  */
828  Global Pass() { return static_cast<Global&&>(*this); } // NOLINT
829 
830  /*
831  * For compatibility with Chromium's base::Bind (base::Passed).
832  */
833  typedef void MoveOnlyTypeForCPP03;
834 
835  Global(const Global&) = delete;
836  void operator=(const Global&) = delete;
837 
838  private:
839  template <class F>
840  friend class ReturnValue;
841  V8_INLINE T* operator*() const { return this->val_; }
842 };
843 
844 
845 // UniquePersistent is an alias for Global for historical reason.
846 template <class T>
847 using UniquePersistent = Global<T>;
848 
849 
850  /**
851  * A stack-allocated class that governs a number of local handles.
852  * After a handle scope has been created, all local handles will be
853  * allocated within that handle scope until either the handle scope is
854  * deleted or another handle scope is created. If there is already a
855  * handle scope and a new one is created, all allocations will take
856  * place in the new handle scope until it is deleted. After that,
857  * new handles will again be allocated in the original handle scope.
858  *
859  * After the handle scope of a local handle has been deleted the
860  * garbage collector will no longer track the object stored in the
861  * handle and may deallocate it. The behavior of accessing a handle
862  * for which the handle scope has been deleted is undefined.
863  */
865  public:
866  explicit HandleScope(Isolate* isolate);
867 
868  ~HandleScope();
869 
870  /**
871  * Counts the number of allocated handles.
872  */
873  static int NumberOfHandles(Isolate* isolate);
874 
876  return reinterpret_cast<Isolate*>(isolate_);
877  }
878 
879  HandleScope(const HandleScope&) = delete;
880  void operator=(const HandleScope&) = delete;
881 
882  protected:
884 
885  void Initialize(Isolate* isolate);
886 
887  static internal::Object** CreateHandle(internal::Isolate* isolate,
888  internal::Object* value);
889 
890  private:
891  // Declaring operator new and delete as deleted is not spec compliant.
892  // Therefore declare them private instead to disable dynamic alloc
893  void* operator new(size_t size);
894  void* operator new[](size_t size);
895  void operator delete(void*, size_t);
896  void operator delete[](void*, size_t);
897 
898  // Uses heap_object to obtain the current Isolate.
899  static internal::Object** CreateHandle(internal::HeapObject* heap_object,
900  internal::Object* value);
901 
902  internal::Isolate* isolate_;
903  internal::Object** prev_next_;
904  internal::Object** prev_limit_;
905 
906  // Local::New uses CreateHandle with an Isolate* parameter.
907  template<class F> friend class Local;
908 
909  // Object::GetInternalField and Context::GetEmbedderData use CreateHandle with
910  // a HeapObject* in their shortcuts.
911  friend class Object;
912  friend class Context;
913 };
914 
915 
916 /**
917  * A HandleScope which first allocates a handle in the current scope
918  * which will be later filled with the escape value.
919  */
921  public:
922  explicit EscapableHandleScope(Isolate* isolate);
924 
925  /**
926  * Pushes the value into the previous scope and returns a handle to it.
927  * Cannot be called twice.
928  */
929  template <class T>
930  V8_INLINE Local<T> Escape(Local<T> value) {
931  internal::Object** slot =
932  Escape(reinterpret_cast<internal::Object**>(*value));
933  return Local<T>(reinterpret_cast<T*>(slot));
934  }
935 
937  void operator=(const EscapableHandleScope&) = delete;
938 
939  private:
940  // Declaring operator new and delete as deleted is not spec compliant.
941  // Therefore declare them private instead to disable dynamic alloc
942  void* operator new(size_t size);
943  void* operator new[](size_t size);
944  void operator delete(void*, size_t);
945  void operator delete[](void*, size_t);
946 
947  internal::Object** Escape(internal::Object** escape_value);
948  internal::Object** escape_slot_;
949 };
950 
951 /**
952  * A SealHandleScope acts like a handle scope in which no handle allocations
953  * are allowed. It can be useful for debugging handle leaks.
954  * Handles can be allocated within inner normal HandleScopes.
955  */
957  public:
958  explicit SealHandleScope(Isolate* isolate);
959  ~SealHandleScope();
960 
961  SealHandleScope(const SealHandleScope&) = delete;
962  void operator=(const SealHandleScope&) = delete;
963 
964  private:
965  // Declaring operator new and delete as deleted is not spec compliant.
966  // Therefore declare them private instead to disable dynamic alloc
967  void* operator new(size_t size);
968  void* operator new[](size_t size);
969  void operator delete(void*, size_t);
970  void operator delete[](void*, size_t);
971 
972  internal::Isolate* const isolate_;
973  internal::Object** prev_limit_;
974  int prev_sealed_level_;
975 };
976 
977 
978 // --- Special objects ---
979 
980 
981 /**
982  * The superclass of values and API object templates.
983  */
985  private:
986  Data();
987 };
988 
989 /**
990  * A container type that holds relevant metadata for module loading.
991  *
992  * This is passed back to the embedder as part of
993  * HostImportModuleDynamicallyCallback for module loading.
994  */
996  public:
997  /**
998  * The name that was passed by the embedder as ResourceName to the
999  * ScriptOrigin. This can be either a v8::String or v8::Undefined.
1000  */
1001  Local<Value> GetResourceName();
1002 
1003  /**
1004  * The options that were passed by the embedder as HostDefinedOptions to
1005  * the ScriptOrigin.
1006  */
1008 };
1009 
1010 /**
1011  * An array to hold Primitive values. This is used by the embedder to
1012  * pass host defined options to the ScriptOptions during compilation.
1013  *
1014  * This is passed back to the embedder as part of
1015  * HostImportModuleDynamicallyCallback for module loading.
1016  *
1017  */
1019  public:
1020  static Local<PrimitiveArray> New(Isolate* isolate, int length);
1021  int Length() const;
1022  void Set(int index, Local<Primitive> item);
1023  Local<Primitive> Get(int index);
1024 };
1025 
1026 /**
1027  * The optional attributes of ScriptOrigin.
1028  */
1030  public:
1031  V8_INLINE ScriptOriginOptions(bool is_shared_cross_origin = false,
1032  bool is_opaque = false, bool is_wasm = false,
1033  bool is_module = false)
1034  : flags_((is_shared_cross_origin ? kIsSharedCrossOrigin : 0) |
1035  (is_wasm ? kIsWasm : 0) | (is_opaque ? kIsOpaque : 0) |
1036  (is_module ? kIsModule : 0)) {}
1038  : flags_(flags &
1039  (kIsSharedCrossOrigin | kIsOpaque | kIsWasm | kIsModule)) {}
1040 
1041  bool IsSharedCrossOrigin() const {
1042  return (flags_ & kIsSharedCrossOrigin) != 0;
1043  }
1044  bool IsOpaque() const { return (flags_ & kIsOpaque) != 0; }
1045  bool IsWasm() const { return (flags_ & kIsWasm) != 0; }
1046  bool IsModule() const { return (flags_ & kIsModule) != 0; }
1047 
1048  int Flags() const { return flags_; }
1049 
1050  private:
1051  enum {
1052  kIsSharedCrossOrigin = 1,
1053  kIsOpaque = 1 << 1,
1054  kIsWasm = 1 << 2,
1055  kIsModule = 1 << 3
1056  };
1057  const int flags_;
1058 };
1059 
1060 /**
1061  * The origin, within a file, of a script.
1062  */
1064  public:
1066  Local<Value> resource_name,
1067  Local<Integer> resource_line_offset = Local<Integer>(),
1068  Local<Integer> resource_column_offset = Local<Integer>(),
1069  Local<Boolean> resource_is_shared_cross_origin = Local<Boolean>(),
1070  Local<Integer> script_id = Local<Integer>(),
1071  Local<Value> source_map_url = Local<Value>(),
1072  Local<Boolean> resource_is_opaque = Local<Boolean>(),
1073  Local<Boolean> is_wasm = Local<Boolean>(),
1074  Local<Boolean> is_module = Local<Boolean>(),
1075  Local<PrimitiveArray> host_defined_options = Local<PrimitiveArray>());
1076 
1077  V8_INLINE Local<Value> ResourceName() const;
1078  V8_INLINE Local<Integer> ResourceLineOffset() const;
1079  V8_INLINE Local<Integer> ResourceColumnOffset() const;
1080  V8_INLINE Local<Integer> ScriptID() const;
1081  V8_INLINE Local<Value> SourceMapUrl() const;
1083  V8_INLINE ScriptOriginOptions Options() const { return options_; }
1084 
1085  private:
1086  Local<Value> resource_name_;
1087  Local<Integer> resource_line_offset_;
1088  Local<Integer> resource_column_offset_;
1089  ScriptOriginOptions options_;
1090  Local<Integer> script_id_;
1091  Local<Value> source_map_url_;
1092  Local<PrimitiveArray> host_defined_options_;
1093 };
1094 
1095 /**
1096  * A compiled JavaScript script, not yet tied to a Context.
1097  */
1099  public:
1100  /**
1101  * Binds the script to the currently entered context.
1102  */
1103  Local<Script> BindToCurrentContext();
1104 
1105  int GetId();
1106  Local<Value> GetScriptName();
1107 
1108  /**
1109  * Data read from magic sourceURL comments.
1110  */
1111  Local<Value> GetSourceURL();
1112  /**
1113  * Data read from magic sourceMappingURL comments.
1114  */
1115  Local<Value> GetSourceMappingURL();
1116 
1117  /**
1118  * Returns zero based line number of the code_pos location in the script.
1119  * -1 will be returned if no information available.
1120  */
1121  int GetLineNumber(int code_pos);
1122 
1123  static const int kNoScriptId = 0;
1124 };
1125 
1126 /**
1127  * A location in JavaScript source.
1128  */
1130  public:
1131  int GetLineNumber() { return line_number_; }
1132  int GetColumnNumber() { return column_number_; }
1133 
1134  Location(int line_number, int column_number)
1135  : line_number_(line_number), column_number_(column_number) {}
1136 
1137  private:
1138  int line_number_;
1139  int column_number_;
1140 };
1141 
1142 /**
1143  * A compiled JavaScript module.
1144  */
1146  public:
1147  /**
1148  * The different states a module can be in.
1149  *
1150  * This corresponds to the states used in ECMAScript except that "evaluated"
1151  * is split into kEvaluated and kErrored, indicating success and failure,
1152  * respectively.
1153  */
1154  enum Status {
1161  };
1162 
1163  /**
1164  * Returns the module's current status.
1165  */
1166  Status GetStatus() const;
1167 
1168  /**
1169  * For a module in kErrored status, this returns the corresponding exception.
1170  */
1171  Local<Value> GetException() const;
1172 
1173  /**
1174  * Returns the number of modules requested by this module.
1175  */
1176  int GetModuleRequestsLength() const;
1177 
1178  /**
1179  * Returns the ith module specifier in this module.
1180  * i must be < GetModuleRequestsLength() and >= 0.
1181  */
1182  Local<String> GetModuleRequest(int i) const;
1183 
1184  /**
1185  * Returns the source location (line number and column number) of the ith
1186  * module specifier's first occurrence in this module.
1187  */
1188  Location GetModuleRequestLocation(int i) const;
1189 
1190  /**
1191  * Returns the identity hash for this object.
1192  */
1193  int GetIdentityHash() const;
1194 
1195  typedef MaybeLocal<Module> (*ResolveCallback)(Local<Context> context,
1196  Local<String> specifier,
1197  Local<Module> referrer);
1198 
1199  /**
1200  * Instantiates the module and its dependencies.
1201  *
1202  * Returns an empty Maybe<bool> if an exception occurred during
1203  * instantiation. (In the case where the callback throws an exception, that
1204  * exception is propagated.)
1205  */
1206  V8_WARN_UNUSED_RESULT Maybe<bool> InstantiateModule(Local<Context> context,
1207  ResolveCallback callback);
1208 
1209  /**
1210  * Evaluates the module and its dependencies.
1211  *
1212  * If status is kInstantiated, run the module's code. On success, set status
1213  * to kEvaluated and return the completion value; on failure, set status to
1214  * kErrored and propagate the thrown exception (which is then also available
1215  * via |GetException|).
1216  */
1217  V8_WARN_UNUSED_RESULT MaybeLocal<Value> Evaluate(Local<Context> context);
1218 
1219  /**
1220  * Returns the namespace object of this module.
1221  *
1222  * The module's status must be at least kInstantiated.
1223  */
1224  Local<Value> GetModuleNamespace();
1225 };
1226 
1227 /**
1228  * A compiled JavaScript script, tied to a Context which was active when the
1229  * script was compiled.
1230  */
1232  public:
1233  /**
1234  * A shorthand for ScriptCompiler::Compile().
1235  */
1236  static V8_DEPRECATED("Use maybe version",
1237  Local<Script> Compile(Local<String> source,
1238  ScriptOrigin* origin = nullptr));
1239  static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile(
1240  Local<Context> context, Local<String> source,
1241  ScriptOrigin* origin = nullptr);
1242 
1243  static Local<Script> V8_DEPRECATED("Use maybe version",
1244  Compile(Local<String> source,
1245  Local<String> file_name));
1246 
1247  /**
1248  * Runs the script returning the resulting value. It will be run in the
1249  * context in which it was created (ScriptCompiler::CompileBound or
1250  * UnboundScript::BindToCurrentContext()).
1251  */
1252  V8_DEPRECATED("Use maybe version", Local<Value> Run());
1253  V8_WARN_UNUSED_RESULT MaybeLocal<Value> Run(Local<Context> context);
1254 
1255  /**
1256  * Returns the corresponding context-unbound script.
1257  */
1259 };
1260 
1261 
1262 /**
1263  * For compiling scripts.
1264  */
1266  public:
1267  /**
1268  * Compilation data that the embedder can cache and pass back to speed up
1269  * future compilations. The data is produced if the CompilerOptions passed to
1270  * the compilation functions in ScriptCompiler contains produce_data_to_cache
1271  * = true. The data to cache can then can be retrieved from
1272  * UnboundScript.
1273  */
1278  };
1279 
1281  : data(NULL),
1282  length(0),
1283  rejected(false),
1285 
1286  // If buffer_policy is BufferNotOwned, the caller keeps the ownership of
1287  // data and guarantees that it stays alive until the CachedData object is
1288  // destroyed. If the policy is BufferOwned, the given data will be deleted
1289  // (with delete[]) when the CachedData object is destroyed.
1290  CachedData(const uint8_t* data, int length,
1291  BufferPolicy buffer_policy = BufferNotOwned);
1292  ~CachedData();
1293  // TODO(marja): Async compilation; add constructors which take a callback
1294  // which will be called when V8 no longer needs the data.
1295  const uint8_t* data;
1296  int length;
1297  bool rejected;
1299 
1300  // Prevent copying.
1301  CachedData(const CachedData&) = delete;
1302  CachedData& operator=(const CachedData&) = delete;
1303  };
1304 
1305  /**
1306  * Source code which can be then compiled to a UnboundScript or Script.
1307  */
1308  class Source {
1309  public:
1310  // Source takes ownership of CachedData.
1311  V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
1312  CachedData* cached_data = NULL);
1313  V8_INLINE Source(Local<String> source_string,
1314  CachedData* cached_data = NULL);
1315  V8_INLINE ~Source();
1316 
1317  // Ownership of the CachedData or its buffers is *not* transferred to the
1318  // caller. The CachedData object is alive as long as the Source object is
1319  // alive.
1320  V8_INLINE const CachedData* GetCachedData() const;
1321 
1323 
1324  // Prevent copying.
1325  Source(const Source&) = delete;
1326  Source& operator=(const Source&) = delete;
1327 
1328  private:
1329  friend class ScriptCompiler;
1330 
1331  Local<String> source_string;
1332 
1333  // Origin information
1334  Local<Value> resource_name;
1335  Local<Integer> resource_line_offset;
1336  Local<Integer> resource_column_offset;
1337  ScriptOriginOptions resource_options;
1338  Local<Value> source_map_url;
1339  Local<PrimitiveArray> host_defined_options;
1340 
1341  // Cached data from previous compilation (if a kConsume*Cache flag is
1342  // set), or hold newly generated cache data (kProduce*Cache flags) are
1343  // set when calling a compile method.
1344  CachedData* cached_data;
1345  };
1346 
1347  /**
1348  * For streaming incomplete script data to V8. The embedder should implement a
1349  * subclass of this class.
1350  */
1352  public:
1353  virtual ~ExternalSourceStream() {}
1354 
1355  /**
1356  * V8 calls this to request the next chunk of data from the embedder. This
1357  * function will be called on a background thread, so it's OK to block and
1358  * wait for the data, if the embedder doesn't have data yet. Returns the
1359  * length of the data returned. When the data ends, GetMoreData should
1360  * return 0. Caller takes ownership of the data.
1361  *
1362  * When streaming UTF-8 data, V8 handles multi-byte characters split between
1363  * two data chunks, but doesn't handle multi-byte characters split between
1364  * more than two data chunks. The embedder can avoid this problem by always
1365  * returning at least 2 bytes of data.
1366  *
1367  * If the embedder wants to cancel the streaming, they should make the next
1368  * GetMoreData call return 0. V8 will interpret it as end of data (and most
1369  * probably, parsing will fail). The streaming task will return as soon as
1370  * V8 has parsed the data it received so far.
1371  */
1372  virtual size_t GetMoreData(const uint8_t** src) = 0;
1373 
1374  /**
1375  * V8 calls this method to set a 'bookmark' at the current position in
1376  * the source stream, for the purpose of (maybe) later calling
1377  * ResetToBookmark. If ResetToBookmark is called later, then subsequent
1378  * calls to GetMoreData should return the same data as they did when
1379  * SetBookmark was called earlier.
1380  *
1381  * The embedder may return 'false' to indicate it cannot provide this
1382  * functionality.
1383  */
1384  virtual bool SetBookmark();
1385 
1386  /**
1387  * V8 calls this to return to a previously set bookmark.
1388  */
1389  virtual void ResetToBookmark();
1390  };
1391 
1392 
1393  /**
1394  * Source code which can be streamed into V8 in pieces. It will be parsed
1395  * while streaming. It can be compiled after the streaming is complete.
1396  * StreamedSource must be kept alive while the streaming task is ran (see
1397  * ScriptStreamingTask below).
1398  */
1400  public:
1402 
1403  StreamedSource(ExternalSourceStream* source_stream, Encoding encoding);
1404  ~StreamedSource();
1405 
1406  // Ownership of the CachedData or its buffers is *not* transferred to the
1407  // caller. The CachedData object is alive as long as the StreamedSource
1408  // object is alive.
1409  const CachedData* GetCachedData() const;
1410 
1411  internal::ScriptStreamingData* impl() const { return impl_; }
1412 
1413  // Prevent copying.
1414  StreamedSource(const StreamedSource&) = delete;
1415  StreamedSource& operator=(const StreamedSource&) = delete;
1416 
1417  private:
1418  internal::ScriptStreamingData* impl_;
1419  };
1420 
1421  /**
1422  * A streaming task which the embedder must run on a background thread to
1423  * stream scripts into V8. Returned by ScriptCompiler::StartStreamingScript.
1424  */
1426  public:
1427  virtual ~ScriptStreamingTask() {}
1428  virtual void Run() = 0;
1429  };
1430 
1439  };
1440 
1441  /**
1442  * The reason for which we are not requesting or providing a code cache.
1443  */
1460  };
1461 
1462  /**
1463  * Compiles the specified script (context-independent).
1464  * Cached data as part of the source object can be optionally produced to be
1465  * consumed later to speed up compilation of identical source scripts.
1466  *
1467  * Note that when producing cached data, the source must point to NULL for
1468  * cached data. When consuming cached data, the cached data must have been
1469  * produced by the same version of V8.
1470  *
1471  * \param source Script source code.
1472  * \return Compiled script object (context independent; for running it must be
1473  * bound to a context).
1474  */
1476  Isolate* isolate, Source* source,
1478  NoCacheReason no_cache_reason = kNoCacheNoReason);
1479 
1480  /**
1481  * Compiles the specified script (bound to current context).
1482  *
1483  * \param source Script source code.
1484  * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
1485  * using pre_data speeds compilation if it's done multiple times.
1486  * Owned by caller, no references are kept when this function returns.
1487  * \return Compiled script object, bound to the context that was active
1488  * when this function was called. When run it will always use this
1489  * context.
1490  */
1491  static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile(
1492  Local<Context> context, Source* source,
1494  NoCacheReason no_cache_reason = kNoCacheNoReason);
1495 
1496  /**
1497  * Returns a task which streams script data into V8, or NULL if the script
1498  * cannot be streamed. The user is responsible for running the task on a
1499  * background thread and deleting it. When ran, the task starts parsing the
1500  * script, and it will request data from the StreamedSource as needed. When
1501  * ScriptStreamingTask::Run exits, all data has been streamed and the script
1502  * can be compiled (see Compile below).
1503  *
1504  * This API allows to start the streaming with as little data as possible, and
1505  * the remaining data (for example, the ScriptOrigin) is passed to Compile.
1506  */
1508  Isolate* isolate, StreamedSource* source,
1509  CompileOptions options = kNoCompileOptions);
1510 
1511  /**
1512  * Compiles a streamed script (bound to current context).
1513  *
1514  * This can only be called after the streaming has finished
1515  * (ScriptStreamingTask has been run). V8 doesn't construct the source string
1516  * during streaming, so the embedder needs to pass the full source here.
1517  */
1518  static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile(
1519  Local<Context> context, StreamedSource* source,
1520  Local<String> full_source_string, const ScriptOrigin& origin);
1521 
1522  /**
1523  * Return a version tag for CachedData for the current V8 version & flags.
1524  *
1525  * This value is meant only for determining whether a previously generated
1526  * CachedData instance is still valid; the tag has no other meaing.
1527  *
1528  * Background: The data carried by CachedData may depend on the exact
1529  * V8 version number or current compiler flags. This means that when
1530  * persisting CachedData, the embedder must take care to not pass in
1531  * data from another V8 version, or the same version with different
1532  * features enabled.
1533  *
1534  * The easiest way to do so is to clear the embedder's cache on any
1535  * such change.
1536  *
1537  * Alternatively, this tag can be stored alongside the cached data and
1538  * compared when it is being used.
1539  */
1540  static uint32_t CachedDataVersionTag();
1541 
1542  /**
1543  * Compile an ES module, returning a Module that encapsulates
1544  * the compiled code.
1545  *
1546  * Corresponds to the ParseModule abstract operation in the
1547  * ECMAScript specification.
1548  */
1549  static V8_WARN_UNUSED_RESULT MaybeLocal<Module> CompileModule(
1550  Isolate* isolate, Source* source);
1551 
1552  /**
1553  * Compile a function for a given context. This is equivalent to running
1554  *
1555  * with (obj) {
1556  * return function(args) { ... }
1557  * }
1558  *
1559  * It is possible to specify multiple context extensions (obj in the above
1560  * example).
1561  */
1562  static V8_DEPRECATED("Use maybe version",
1563  Local<Function> CompileFunctionInContext(
1564  Isolate* isolate, Source* source,
1565  Local<Context> context, size_t arguments_count,
1566  Local<String> arguments[],
1567  size_t context_extension_count,
1568  Local<Object> context_extensions[]));
1570  Local<Context> context, Source* source, size_t arguments_count,
1571  Local<String> arguments[], size_t context_extension_count,
1572  Local<Object> context_extensions[],
1574  NoCacheReason no_cache_reason = kNoCacheNoReason);
1575 
1576  /**
1577  * Creates and returns code cache for the specified unbound_script.
1578  * This will return nullptr if the script cannot be serialized. The
1579  * CachedData returned by this function should be owned by the caller.
1580  */
1581  static CachedData* CreateCodeCache(Local<UnboundScript> unbound_script,
1582  Local<String> source);
1583 
1584  /**
1585  * Creates and returns code cache for the specified function that was
1586  * previously produced by CompileFunctionInContext.
1587  * This will return nullptr if the script cannot be serialized. The
1588  * CachedData returned by this function should be owned by the caller.
1589  */
1590  static CachedData* CreateCodeCacheForFunction(Local<Function> function,
1591  Local<String> source);
1592 
1593  private:
1594  static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundInternal(
1595  Isolate* isolate, Source* source, CompileOptions options,
1596  NoCacheReason no_cache_reason);
1597 };
1598 
1599 
1600 /**
1601  * An error message.
1602  */
1604  public:
1605  Local<String> Get() const;
1606 
1607  V8_DEPRECATED("Use maybe version", Local<String> GetSourceLine() const);
1609  Local<Context> context) const;
1610 
1611  /**
1612  * Returns the origin for the script from where the function causing the
1613  * error originates.
1614  */
1615  ScriptOrigin GetScriptOrigin() const;
1616 
1617  /**
1618  * Returns the resource name for the script from where the function causing
1619  * the error originates.
1620  */
1621  Local<Value> GetScriptResourceName() const;
1622 
1623  /**
1624  * Exception stack trace. By default stack traces are not captured for
1625  * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
1626  * to change this option.
1627  */
1628  Local<StackTrace> GetStackTrace() const;
1629 
1630  /**
1631  * Returns the number, 1-based, of the line where the error occurred.
1632  */
1633  V8_DEPRECATED("Use maybe version", int GetLineNumber() const);
1634  V8_WARN_UNUSED_RESULT Maybe<int> GetLineNumber(Local<Context> context) const;
1635 
1636  /**
1637  * Returns the index within the script of the first character where
1638  * the error occurred.
1639  */
1640  int GetStartPosition() const;
1641 
1642  /**
1643  * Returns the index within the script of the last character where
1644  * the error occurred.
1645  */
1646  int GetEndPosition() const;
1647 
1648  /**
1649  * Returns the error level of the message.
1650  */
1651  int ErrorLevel() const;
1652 
1653  /**
1654  * Returns the index within the line of the first character where
1655  * the error occurred.
1656  */
1657  int GetStartColumn() const;
1658  V8_WARN_UNUSED_RESULT Maybe<int> GetStartColumn(Local<Context> context) const;
1659 
1660  /**
1661  * Returns the index within the line of the last character where
1662  * the error occurred.
1663  */
1664  int GetEndColumn() const;
1665  V8_WARN_UNUSED_RESULT Maybe<int> GetEndColumn(Local<Context> context) const;
1666 
1667  /**
1668  * Passes on the value set by the embedder when it fed the script from which
1669  * this Message was generated to V8.
1670  */
1671  bool IsSharedCrossOrigin() const;
1672  bool IsOpaque() const;
1673 
1674  // TODO(1245381): Print to a string instead of on a FILE.
1675  static void PrintCurrentStackTrace(Isolate* isolate, FILE* out);
1676 
1677  static const int kNoLineNumberInfo = 0;
1678  static const int kNoColumnInfo = 0;
1679  static const int kNoScriptIdInfo = 0;
1680 };
1681 
1682 
1683 /**
1684  * Representation of a JavaScript stack trace. The information collected is a
1685  * snapshot of the execution stack and the information remains valid after
1686  * execution continues.
1687  */
1689  public:
1690  /**
1691  * Flags that determine what information is placed captured for each
1692  * StackFrame when grabbing the current stack trace.
1693  * Note: these options are deprecated and we always collect all available
1694  * information (kDetailed).
1695  */
1699  kScriptName = 1 << 2,
1700  kFunctionName = 1 << 3,
1701  kIsEval = 1 << 4,
1702  kIsConstructor = 1 << 5,
1704  kScriptId = 1 << 7,
1708  };
1709 
1710  /**
1711  * Returns a StackFrame at a particular index.
1712  */
1713  Local<StackFrame> GetFrame(uint32_t index) const;
1714 
1715  /**
1716  * Returns the number of StackFrames.
1717  */
1718  int GetFrameCount() const;
1719 
1720  /**
1721  * Grab a snapshot of the current JavaScript execution stack.
1722  *
1723  * \param frame_limit The maximum number of stack frames we want to capture.
1724  * \param options Enumerates the set of things we will capture for each
1725  * StackFrame.
1726  */
1727  static Local<StackTrace> CurrentStackTrace(
1728  Isolate* isolate, int frame_limit, StackTraceOptions options = kDetailed);
1729 };
1730 
1731 
1732 /**
1733  * A single JavaScript stack frame.
1734  */
1736  public:
1737  /**
1738  * Returns the number, 1-based, of the line for the associate function call.
1739  * This method will return Message::kNoLineNumberInfo if it is unable to
1740  * retrieve the line number, or if kLineNumber was not passed as an option
1741  * when capturing the StackTrace.
1742  */
1743  int GetLineNumber() const;
1744 
1745  /**
1746  * Returns the 1-based column offset on the line for the associated function
1747  * call.
1748  * This method will return Message::kNoColumnInfo if it is unable to retrieve
1749  * the column number, or if kColumnOffset was not passed as an option when
1750  * capturing the StackTrace.
1751  */
1752  int GetColumn() const;
1753 
1754  /**
1755  * Returns the id of the script for the function for this StackFrame.
1756  * This method will return Message::kNoScriptIdInfo if it is unable to
1757  * retrieve the script id, or if kScriptId was not passed as an option when
1758  * capturing the StackTrace.
1759  */
1760  int GetScriptId() const;
1761 
1762  /**
1763  * Returns the name of the resource that contains the script for the
1764  * function for this StackFrame.
1765  */
1766  Local<String> GetScriptName() const;
1767 
1768  /**
1769  * Returns the name of the resource that contains the script for the
1770  * function for this StackFrame or sourceURL value if the script name
1771  * is undefined and its source ends with //# sourceURL=... string or
1772  * deprecated //@ sourceURL=... string.
1773  */
1774  Local<String> GetScriptNameOrSourceURL() const;
1775 
1776  /**
1777  * Returns the name of the function associated with this stack frame.
1778  */
1779  Local<String> GetFunctionName() const;
1780 
1781  /**
1782  * Returns whether or not the associated function is compiled via a call to
1783  * eval().
1784  */
1785  bool IsEval() const;
1786 
1787  /**
1788  * Returns whether or not the associated function is called as a
1789  * constructor via "new".
1790  */
1791  bool IsConstructor() const;
1792 
1793  /**
1794  * Returns whether or not the associated functions is defined in wasm.
1795  */
1796  bool IsWasm() const;
1797 };
1798 
1799 
1800 // A StateTag represents a possible state of the VM.
1801 enum StateTag {
1810 };
1811 
1812 // A RegisterState represents the current state of registers used
1813 // by the sampling profiler API.
1816  void* pc; // Instruction pointer.
1817  void* sp; // Stack pointer.
1818  void* fp; // Frame pointer.
1819 };
1820 
1821 // The output structure filled up by GetStackSample API function.
1822 struct SampleInfo {
1823  size_t frames_count; // Number of frames collected.
1824  StateTag vm_state; // Current VM state.
1825  void* external_callback_entry; // External callback address if VM is
1826  // executing an external callback.
1827 };
1828 
1829 /**
1830  * A JSON Parser and Stringifier.
1831  */
1833  public:
1834  /**
1835  * Tries to parse the string |json_string| and returns it as value if
1836  * successful.
1837  *
1838  * \param json_string The string to parse.
1839  * \return The corresponding value if successfully parsed.
1840  */
1841  static V8_DEPRECATE_SOON("Use the maybe version taking context",
1842  MaybeLocal<Value> Parse(Isolate* isolate,
1843  Local<String> json_string));
1844  static V8_WARN_UNUSED_RESULT MaybeLocal<Value> Parse(
1845  Local<Context> context, Local<String> json_string);
1846 
1847  /**
1848  * Tries to stringify the JSON-serializable object |json_object| and returns
1849  * it as string if successful.
1850  *
1851  * \param json_object The JSON-serializable object to stringify.
1852  * \return The corresponding string if successfully stringified.
1853  */
1854  static V8_WARN_UNUSED_RESULT MaybeLocal<String> Stringify(
1855  Local<Context> context, Local<Value> json_object,
1856  Local<String> gap = Local<String>());
1857 };
1858 
1859 /**
1860  * Value serialization compatible with the HTML structured clone algorithm.
1861  * The format is backward-compatible (i.e. safe to store to disk).
1862  *
1863  * WARNING: This API is under development, and changes (including incompatible
1864  * changes to the API or wire format) may occur without notice until this
1865  * warning is removed.
1866  */
1868  public:
1870  public:
1871  virtual ~Delegate() {}
1872 
1873  /**
1874  * Handles the case where a DataCloneError would be thrown in the structured
1875  * clone spec. Other V8 embedders may throw some other appropriate exception
1876  * type.
1877  */
1878  virtual void ThrowDataCloneError(Local<String> message) = 0;
1879 
1880  /**
1881  * The embedder overrides this method to write some kind of host object, if
1882  * possible. If not, a suitable exception should be thrown and
1883  * Nothing<bool>() returned.
1884  */
1885  virtual Maybe<bool> WriteHostObject(Isolate* isolate, Local<Object> object);
1886 
1887  /**
1888  * Called when the ValueSerializer is going to serialize a
1889  * SharedArrayBuffer object. The embedder must return an ID for the
1890  * object, using the same ID if this SharedArrayBuffer has already been
1891  * serialized in this buffer. When deserializing, this ID will be passed to
1892  * ValueDeserializer::GetSharedArrayBufferFromId as |clone_id|.
1893  *
1894  * If the object cannot be serialized, an
1895  * exception should be thrown and Nothing<uint32_t>() returned.
1896  */
1897  virtual Maybe<uint32_t> GetSharedArrayBufferId(
1898  Isolate* isolate, Local<SharedArrayBuffer> shared_array_buffer);
1899 
1900  virtual Maybe<uint32_t> GetWasmModuleTransferId(
1901  Isolate* isolate, Local<WasmCompiledModule> module);
1902  /**
1903  * Allocates memory for the buffer of at least the size provided. The actual
1904  * size (which may be greater or equal) is written to |actual_size|. If no
1905  * buffer has been allocated yet, nullptr will be provided.
1906  *
1907  * If the memory cannot be allocated, nullptr should be returned.
1908  * |actual_size| will be ignored. It is assumed that |old_buffer| is still
1909  * valid in this case and has not been modified.
1910  */
1911  virtual void* ReallocateBufferMemory(void* old_buffer, size_t size,
1912  size_t* actual_size);
1913 
1914  /**
1915  * Frees a buffer allocated with |ReallocateBufferMemory|.
1916  */
1917  virtual void FreeBufferMemory(void* buffer);
1918  };
1919 
1920  explicit ValueSerializer(Isolate* isolate);
1921  ValueSerializer(Isolate* isolate, Delegate* delegate);
1922  ~ValueSerializer();
1923 
1924  /**
1925  * Writes out a header, which includes the format version.
1926  */
1927  void WriteHeader();
1928 
1929  /**
1930  * Serializes a JavaScript value into the buffer.
1931  */
1932  V8_WARN_UNUSED_RESULT Maybe<bool> WriteValue(Local<Context> context,
1933  Local<Value> value);
1934 
1935  /**
1936  * Returns the stored data. This serializer should not be used once the buffer
1937  * is released. The contents are undefined if a previous write has failed.
1938  */
1939  V8_DEPRECATE_SOON("Use Release()", std::vector<uint8_t> ReleaseBuffer());
1940 
1941  /**
1942  * Returns the stored data (allocated using the delegate's
1943  * AllocateBufferMemory) and its size. This serializer should not be used once
1944  * the buffer is released. The contents are undefined if a previous write has
1945  * failed.
1946  */
1948 
1949  /**
1950  * Marks an ArrayBuffer as havings its contents transferred out of band.
1951  * Pass the corresponding ArrayBuffer in the deserializing context to
1952  * ValueDeserializer::TransferArrayBuffer.
1953  */
1954  void TransferArrayBuffer(uint32_t transfer_id,
1955  Local<ArrayBuffer> array_buffer);
1956 
1957  /**
1958  * Similar to TransferArrayBuffer, but for SharedArrayBuffer.
1959  */
1960  V8_DEPRECATE_SOON("Use Delegate::GetSharedArrayBufferId",
1961  void TransferSharedArrayBuffer(
1962  uint32_t transfer_id,
1963  Local<SharedArrayBuffer> shared_array_buffer));
1964 
1965  /**
1966  * Indicate whether to treat ArrayBufferView objects as host objects,
1967  * i.e. pass them to Delegate::WriteHostObject. This should not be
1968  * called when no Delegate was passed.
1969  *
1970  * The default is not to treat ArrayBufferViews as host objects.
1971  */
1972  void SetTreatArrayBufferViewsAsHostObjects(bool mode);
1973 
1974  /**
1975  * Write raw data in various common formats to the buffer.
1976  * Note that integer types are written in base-128 varint format, not with a
1977  * binary copy. For use during an override of Delegate::WriteHostObject.
1978  */
1979  void WriteUint32(uint32_t value);
1980  void WriteUint64(uint64_t value);
1981  void WriteDouble(double value);
1982  void WriteRawBytes(const void* source, size_t length);
1983 
1984  private:
1985  ValueSerializer(const ValueSerializer&) = delete;
1986  void operator=(const ValueSerializer&) = delete;
1987 
1988  struct PrivateData;
1989  PrivateData* private_;
1990 };
1991 
1992 /**
1993  * Deserializes values from data written with ValueSerializer, or a compatible
1994  * implementation.
1995  *
1996  * WARNING: This API is under development, and changes (including incompatible
1997  * changes to the API or wire format) may occur without notice until this
1998  * warning is removed.
1999  */
2001  public:
2003  public:
2004  virtual ~Delegate() {}
2005 
2006  /**
2007  * The embedder overrides this method to read some kind of host object, if
2008  * possible. If not, a suitable exception should be thrown and
2009  * MaybeLocal<Object>() returned.
2010  */
2011  virtual MaybeLocal<Object> ReadHostObject(Isolate* isolate);
2012 
2013  /**
2014  * Get a WasmCompiledModule given a transfer_id previously provided
2015  * by ValueSerializer::GetWasmModuleTransferId
2016  */
2017  virtual MaybeLocal<WasmCompiledModule> GetWasmModuleFromId(
2018  Isolate* isolate, uint32_t transfer_id);
2019 
2020  /**
2021  * Get a SharedArrayBuffer given a clone_id previously provided
2022  * by ValueSerializer::GetSharedArrayBufferId
2023  */
2024  virtual MaybeLocal<SharedArrayBuffer> GetSharedArrayBufferFromId(
2025  Isolate* isolate, uint32_t clone_id);
2026  };
2027 
2028  ValueDeserializer(Isolate* isolate, const uint8_t* data, size_t size);
2029  ValueDeserializer(Isolate* isolate, const uint8_t* data, size_t size,
2030  Delegate* delegate);
2031  ~ValueDeserializer();
2032 
2033  /**
2034  * Reads and validates a header (including the format version).
2035  * May, for example, reject an invalid or unsupported wire format.
2036  */
2037  V8_WARN_UNUSED_RESULT Maybe<bool> ReadHeader(Local<Context> context);
2038 
2039  /**
2040  * Deserializes a JavaScript value from the buffer.
2041  */
2042  V8_WARN_UNUSED_RESULT MaybeLocal<Value> ReadValue(Local<Context> context);
2043 
2044  /**
2045  * Accepts the array buffer corresponding to the one passed previously to
2046  * ValueSerializer::TransferArrayBuffer.
2047  */
2048  void TransferArrayBuffer(uint32_t transfer_id,
2049  Local<ArrayBuffer> array_buffer);
2050 
2051  /**
2052  * Similar to TransferArrayBuffer, but for SharedArrayBuffer.
2053  * The id is not necessarily in the same namespace as unshared ArrayBuffer
2054  * objects.
2055  */
2056  void TransferSharedArrayBuffer(uint32_t id,
2057  Local<SharedArrayBuffer> shared_array_buffer);
2058 
2059  /**
2060  * Must be called before ReadHeader to enable support for reading the legacy
2061  * wire format (i.e., which predates this being shipped).
2062  *
2063  * Don't use this unless you need to read data written by previous versions of
2064  * blink::ScriptValueSerializer.
2065  */
2066  void SetSupportsLegacyWireFormat(bool supports_legacy_wire_format);
2067 
2068  /**
2069  * Expect inline wasm in the data stream (rather than in-memory transfer)
2070  */
2071  void SetExpectInlineWasm(bool allow_inline_wasm);
2072 
2073  /**
2074  * Reads the underlying wire format version. Likely mostly to be useful to
2075  * legacy code reading old wire format versions. Must be called after
2076  * ReadHeader.
2077  */
2078  uint32_t GetWireFormatVersion() const;
2079 
2080  /**
2081  * Reads raw data in various common formats to the buffer.
2082  * Note that integer types are read in base-128 varint format, not with a
2083  * binary copy. For use during an override of Delegate::ReadHostObject.
2084  */
2085  V8_WARN_UNUSED_RESULT bool ReadUint32(uint32_t* value);
2086  V8_WARN_UNUSED_RESULT bool ReadUint64(uint64_t* value);
2087  V8_WARN_UNUSED_RESULT bool ReadDouble(double* value);
2088  V8_WARN_UNUSED_RESULT bool ReadRawBytes(size_t length, const void** data);
2089 
2090  private:
2091  ValueDeserializer(const ValueDeserializer&) = delete;
2092  void operator=(const ValueDeserializer&) = delete;
2093 
2094  struct PrivateData;
2095  PrivateData* private_;
2096 };
2097 
2098 
2099 // --- Value ---
2100 
2101 
2102 /**
2103  * The superclass of all JavaScript values and objects.
2104  */
2105 class V8_EXPORT Value : public Data {
2106  public:
2107  /**
2108  * Returns true if this value is the undefined value. See ECMA-262
2109  * 4.3.10.
2110  */
2111  V8_INLINE bool IsUndefined() const;
2112 
2113  /**
2114  * Returns true if this value is the null value. See ECMA-262
2115  * 4.3.11.
2116  */
2117  V8_INLINE bool IsNull() const;
2118 
2119  /**
2120  * Returns true if this value is either the null or the undefined value.
2121  * See ECMA-262
2122  * 4.3.11. and 4.3.12
2123  */
2124  V8_INLINE bool IsNullOrUndefined() const;
2125 
2126  /**
2127  * Returns true if this value is true.
2128  */
2129  bool IsTrue() const;
2130 
2131  /**
2132  * Returns true if this value is false.
2133  */
2134  bool IsFalse() const;
2135 
2136  /**
2137  * Returns true if this value is a symbol or a string.
2138  */
2139  bool IsName() const;
2140 
2141  /**
2142  * Returns true if this value is an instance of the String type.
2143  * See ECMA-262 8.4.
2144  */
2145  V8_INLINE bool IsString() const;
2146 
2147  /**
2148  * Returns true if this value is a symbol.
2149  */
2150  bool IsSymbol() const;
2151 
2152  /**
2153  * Returns true if this value is a function.
2154  */
2155  bool IsFunction() const;
2156 
2157  /**
2158  * Returns true if this value is an array. Note that it will return false for
2159  * an Proxy for an array.
2160  */
2161  bool IsArray() const;
2162 
2163  /**
2164  * Returns true if this value is an object.
2165  */
2166  bool IsObject() const;
2167 
2168  /**
2169  * Returns true if this value is a bigint.
2170  */
2171  bool IsBigInt() const;
2172 
2173  /**
2174  * Returns true if this value is boolean.
2175  */
2176  bool IsBoolean() const;
2177 
2178  /**
2179  * Returns true if this value is a number.
2180  */
2181  bool IsNumber() const;
2182 
2183  /**
2184  * Returns true if this value is external.
2185  */
2186  bool IsExternal() const;
2187 
2188  /**
2189  * Returns true if this value is a 32-bit signed integer.
2190  */
2191  bool IsInt32() const;
2192 
2193  /**
2194  * Returns true if this value is a 32-bit unsigned integer.
2195  */
2196  bool IsUint32() const;
2197 
2198  /**
2199  * Returns true if this value is a Date.
2200  */
2201  bool IsDate() const;
2202 
2203  /**
2204  * Returns true if this value is an Arguments object.
2205  */
2206  bool IsArgumentsObject() const;
2207 
2208  /**
2209  * Returns true if this value is a BigInt object.
2210  */
2211  bool IsBigIntObject() const;
2212 
2213  /**
2214  * Returns true if this value is a Boolean object.
2215  */
2216  bool IsBooleanObject() const;
2217 
2218  /**
2219  * Returns true if this value is a Number object.
2220  */
2221  bool IsNumberObject() const;
2222 
2223  /**
2224  * Returns true if this value is a String object.
2225  */
2226  bool IsStringObject() const;
2227 
2228  /**
2229  * Returns true if this value is a Symbol object.
2230  */
2231  bool IsSymbolObject() const;
2232 
2233  /**
2234  * Returns true if this value is a NativeError.
2235  */
2236  bool IsNativeError() const;
2237 
2238  /**
2239  * Returns true if this value is a RegExp.
2240  */
2241  bool IsRegExp() const;
2242 
2243  /**
2244  * Returns true if this value is an async function.
2245  */
2246  bool IsAsyncFunction() const;
2247 
2248  /**
2249  * Returns true if this value is a Generator function.
2250  */
2251  bool IsGeneratorFunction() const;
2252 
2253  /**
2254  * Returns true if this value is a Generator object (iterator).
2255  */
2256  bool IsGeneratorObject() const;
2257 
2258  /**
2259  * Returns true if this value is a Promise.
2260  */
2261  bool IsPromise() const;
2262 
2263  /**
2264  * Returns true if this value is a Map.
2265  */
2266  bool IsMap() const;
2267 
2268  /**
2269  * Returns true if this value is a Set.
2270  */
2271  bool IsSet() const;
2272 
2273  /**
2274  * Returns true if this value is a Map Iterator.
2275  */
2276  bool IsMapIterator() const;
2277 
2278  /**
2279  * Returns true if this value is a Set Iterator.
2280  */
2281  bool IsSetIterator() const;
2282 
2283  /**
2284  * Returns true if this value is a WeakMap.
2285  */
2286  bool IsWeakMap() const;
2287 
2288  /**
2289  * Returns true if this value is a WeakSet.
2290  */
2291  bool IsWeakSet() const;
2292 
2293  /**
2294  * Returns true if this value is an ArrayBuffer.
2295  */
2296  bool IsArrayBuffer() const;
2297 
2298  /**
2299  * Returns true if this value is an ArrayBufferView.
2300  */
2301  bool IsArrayBufferView() const;
2302 
2303  /**
2304  * Returns true if this value is one of TypedArrays.
2305  */
2306  bool IsTypedArray() const;
2307 
2308  /**
2309  * Returns true if this value is an Uint8Array.
2310  */
2311  bool IsUint8Array() const;
2312 
2313  /**
2314  * Returns true if this value is an Uint8ClampedArray.
2315  */
2316  bool IsUint8ClampedArray() const;
2317 
2318  /**
2319  * Returns true if this value is an Int8Array.
2320  */
2321  bool IsInt8Array() const;
2322 
2323  /**
2324  * Returns true if this value is an Uint16Array.
2325  */
2326  bool IsUint16Array() const;
2327 
2328  /**
2329  * Returns true if this value is an Int16Array.
2330  */
2331  bool IsInt16Array() const;
2332 
2333  /**
2334  * Returns true if this value is an Uint32Array.
2335  */
2336  bool IsUint32Array() const;
2337 
2338  /**
2339  * Returns true if this value is an Int32Array.
2340  */
2341  bool IsInt32Array() const;
2342 
2343  /**
2344  * Returns true if this value is a Float32Array.
2345  */
2346  bool IsFloat32Array() const;
2347 
2348  /**
2349  * Returns true if this value is a Float64Array.
2350  */
2351  bool IsFloat64Array() const;
2352 
2353  /**
2354  * Returns true if this value is a BigInt64Array.
2355  */
2356  bool IsBigInt64Array() const;
2357 
2358  /**
2359  * Returns true if this value is a BigUint64Array.
2360  */
2361  bool IsBigUint64Array() const;
2362 
2363  /**
2364  * Returns true if this value is a DataView.
2365  */
2366  bool IsDataView() const;
2367 
2368  /**
2369  * Returns true if this value is a SharedArrayBuffer.
2370  * This is an experimental feature.
2371  */
2372  bool IsSharedArrayBuffer() const;
2373 
2374  /**
2375  * Returns true if this value is a JavaScript Proxy.
2376  */
2377  bool IsProxy() const;
2378 
2379  bool IsWebAssemblyCompiledModule() const;
2380 
2382  Local<Context> context) const;
2384  Local<Context> context) const;
2386  Local<Context> context) const;
2388  Local<Context> context) const;
2390  Local<Context> context) const;
2392  Local<Context> context) const;
2394  Local<Context> context) const;
2396  Local<Context> context) const;
2397  V8_WARN_UNUSED_RESULT MaybeLocal<Int32> ToInt32(Local<Context> context) const;
2398 
2399  V8_DEPRECATE_SOON("Use maybe version",
2400  Local<Boolean> ToBoolean(Isolate* isolate) const);
2401  V8_DEPRECATE_SOON("Use maybe version",
2402  Local<Number> ToNumber(Isolate* isolate) const);
2403  V8_DEPRECATE_SOON("Use maybe version",
2404  Local<String> ToString(Isolate* isolate) const);
2405  V8_DEPRECATE_SOON("Use maybe version",
2406  Local<Object> ToObject(Isolate* isolate) const);
2407  V8_DEPRECATE_SOON("Use maybe version",
2408  Local<Integer> ToInteger(Isolate* isolate) const);
2409  V8_DEPRECATE_SOON("Use maybe version",
2410  Local<Int32> ToInt32(Isolate* isolate) const);
2411 
2412  inline V8_DEPRECATE_SOON("Use maybe version",
2413  Local<Boolean> ToBoolean() const);
2414  inline V8_DEPRECATE_SOON("Use maybe version", Local<String> ToString() const);
2415  inline V8_DEPRECATE_SOON("Use maybe version", Local<Object> ToObject() const);
2416  inline V8_DEPRECATE_SOON("Use maybe version",
2417  Local<Integer> ToInteger() const);
2418 
2419  /**
2420  * Attempts to convert a string to an array index.
2421  * Returns an empty handle if the conversion fails.
2422  */
2424  Local<Context> context) const;
2425 
2426  V8_WARN_UNUSED_RESULT Maybe<bool> BooleanValue(Local<Context> context) const;
2427  V8_WARN_UNUSED_RESULT Maybe<double> NumberValue(Local<Context> context) const;
2428  V8_WARN_UNUSED_RESULT Maybe<int64_t> IntegerValue(
2429  Local<Context> context) const;
2430  V8_WARN_UNUSED_RESULT Maybe<uint32_t> Uint32Value(
2431  Local<Context> context) const;
2432  V8_WARN_UNUSED_RESULT Maybe<int32_t> Int32Value(Local<Context> context) const;
2433 
2434  V8_DEPRECATE_SOON("Use maybe version", bool BooleanValue() const);
2435  V8_DEPRECATE_SOON("Use maybe version", double NumberValue() const);
2436  V8_DEPRECATE_SOON("Use maybe version", int64_t IntegerValue() const);
2437  V8_DEPRECATE_SOON("Use maybe version", uint32_t Uint32Value() const);
2438  V8_DEPRECATE_SOON("Use maybe version", int32_t Int32Value() const);
2439 
2440  /** JS == */
2441  V8_DEPRECATE_SOON("Use maybe version", bool Equals(Local<Value> that) const);
2442  V8_WARN_UNUSED_RESULT Maybe<bool> Equals(Local<Context> context,
2443  Local<Value> that) const;
2444  bool StrictEquals(Local<Value> that) const;
2445  bool SameValue(Local<Value> that) const;
2446 
2447  template <class T> V8_INLINE static Value* Cast(T* value);
2448 
2449  Local<String> TypeOf(Isolate*);
2450 
2451  Maybe<bool> InstanceOf(Local<Context> context, Local<Object> object);
2452 
2453  private:
2454  V8_INLINE bool QuickIsUndefined() const;
2455  V8_INLINE bool QuickIsNull() const;
2456  V8_INLINE bool QuickIsNullOrUndefined() const;
2457  V8_INLINE bool QuickIsString() const;
2458  bool FullIsUndefined() const;
2459  bool FullIsNull() const;
2460  bool FullIsString() const;
2461 };
2462 
2463 
2464 /**
2465  * The superclass of primitive values. See ECMA-262 4.3.2.
2466  */
2467 class V8_EXPORT Primitive : public Value { };
2468 
2469 
2470 /**
2471  * A primitive boolean value (ECMA-262, 4.3.14). Either the true
2472  * or false value.
2473  */
2474 class V8_EXPORT Boolean : public Primitive {
2475  public:
2476  bool Value() const;
2477  V8_INLINE static Boolean* Cast(v8::Value* obj);
2478  V8_INLINE static Local<Boolean> New(Isolate* isolate, bool value);
2479 
2480  private:
2481  static void CheckCast(v8::Value* obj);
2482 };
2483 
2484 
2485 /**
2486  * A superclass for symbols and strings.
2487  */
2488 class V8_EXPORT Name : public Primitive {
2489  public:
2490  /**
2491  * Returns the identity hash for this object. The current implementation
2492  * uses an inline property on the object to store the identity hash.
2493  *
2494  * The return value will never be 0. Also, it is not guaranteed to be
2495  * unique.
2496  */
2497  int GetIdentityHash();
2498 
2499  V8_INLINE static Name* Cast(Value* obj);
2500 
2501  private:
2502  static void CheckCast(Value* obj);
2503 };
2504 
2505 /**
2506  * A flag describing different modes of string creation.
2507  *
2508  * Aside from performance implications there are no differences between the two
2509  * creation modes.
2510  */
2511 enum class NewStringType {
2512  /**
2513  * Create a new string, always allocating new storage memory.
2514  */
2515  kNormal,
2516 
2517  /**
2518  * Acts as a hint that the string should be created in the
2519  * old generation heap space and be deduplicated if an identical string
2520  * already exists.
2521  */
2523 };
2524 
2525 /**
2526  * A JavaScript string value (ECMA-262, 4.3.17).
2527  */
2528 class V8_EXPORT String : public Name {
2529  public:
2530  static constexpr int kMaxLength =
2531  sizeof(void*) == 4 ? (1 << 28) - 16 : (1 << 30) - 1 - 24;
2532 
2533  enum Encoding {
2537  };
2538  /**
2539  * Returns the number of characters (UTF-16 code units) in this string.
2540  */
2541  int Length() const;
2542 
2543  /**
2544  * Returns the number of bytes in the UTF-8 encoded
2545  * representation of this string.
2546  */
2547  int Utf8Length() const;
2548 
2549  /**
2550  * Returns whether this string is known to contain only one byte data,
2551  * i.e. ISO-8859-1 code points.
2552  * Does not read the string.
2553  * False negatives are possible.
2554  */
2555  bool IsOneByte() const;
2556 
2557  /**
2558  * Returns whether this string contain only one byte data,
2559  * i.e. ISO-8859-1 code points.
2560  * Will read the entire string in some cases.
2561  */
2562  bool ContainsOnlyOneByte() const;
2563 
2564  /**
2565  * Write the contents of the string to an external buffer.
2566  * If no arguments are given, expects the buffer to be large
2567  * enough to hold the entire string and NULL terminator. Copies
2568  * the contents of the string and the NULL terminator into the
2569  * buffer.
2570  *
2571  * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
2572  * before the end of the buffer.
2573  *
2574  * Copies up to length characters into the output buffer.
2575  * Only null-terminates if there is enough space in the buffer.
2576  *
2577  * \param buffer The buffer into which the string will be copied.
2578  * \param start The starting position within the string at which
2579  * copying begins.
2580  * \param length The number of characters to copy from the string. For
2581  * WriteUtf8 the number of bytes in the buffer.
2582  * \param nchars_ref The number of characters written, can be NULL.
2583  * \param options Various options that might affect performance of this or
2584  * subsequent operations.
2585  * \return The number of characters copied to the buffer excluding the null
2586  * terminator. For WriteUtf8: The number of bytes copied to the buffer
2587  * including the null terminator (if written).
2588  */
2594  // Used by WriteUtf8 to replace orphan surrogate code units with the
2595  // unicode replacement character. Needs to be set to guarantee valid UTF-8
2596  // output.
2598  };
2599 
2600  // 16-bit character codes.
2601  int Write(uint16_t* buffer,
2602  int start = 0,
2603  int length = -1,
2604  int options = NO_OPTIONS) const;
2605  // One byte characters.
2606  int WriteOneByte(uint8_t* buffer,
2607  int start = 0,
2608  int length = -1,
2609  int options = NO_OPTIONS) const;
2610  // UTF-8 encoded characters.
2611  int WriteUtf8(char* buffer,
2612  int length = -1,
2613  int* nchars_ref = NULL,
2614  int options = NO_OPTIONS) const;
2615 
2616  /**
2617  * A zero length string.
2618  */
2619  V8_INLINE static Local<String> Empty(Isolate* isolate);
2620 
2621  /**
2622  * Returns true if the string is external
2623  */
2624  bool IsExternal() const;
2625 
2626  /**
2627  * Returns true if the string is both external and one-byte.
2628  */
2629  bool IsExternalOneByte() const;
2630 
2632  public:
2634 
2635  virtual bool IsCompressible() const { return false; }
2636 
2637  protected:
2639 
2640  /**
2641  * Internally V8 will call this Dispose method when the external string
2642  * resource is no longer needed. The default implementation will use the
2643  * delete operator. This method can be overridden in subclasses to
2644  * control how allocated external string resources are disposed.
2645  */
2646  virtual void Dispose() { delete this; }
2647 
2648  // Disallow copying and assigning.
2650  void operator=(const ExternalStringResourceBase&) = delete;
2651 
2652  private:
2653  friend class internal::Heap;
2654  friend class v8::String;
2655  };
2656 
2657  /**
2658  * An ExternalStringResource is a wrapper around a two-byte string
2659  * buffer that resides outside V8's heap. Implement an
2660  * ExternalStringResource to manage the life cycle of the underlying
2661  * buffer. Note that the string data must be immutable.
2662  */
2664  : public ExternalStringResourceBase {
2665  public:
2666  /**
2667  * Override the destructor to manage the life cycle of the underlying
2668  * buffer.
2669  */
2671 
2672  /**
2673  * The string data from the underlying buffer.
2674  */
2675  virtual const uint16_t* data() const = 0;
2676 
2677  /**
2678  * The length of the string. That is, the number of two-byte characters.
2679  */
2680  virtual size_t length() const = 0;
2681 
2682  protected:
2684  };
2685 
2686  /**
2687  * An ExternalOneByteStringResource is a wrapper around an one-byte
2688  * string buffer that resides outside V8's heap. Implement an
2689  * ExternalOneByteStringResource to manage the life cycle of the
2690  * underlying buffer. Note that the string data must be immutable
2691  * and that the data must be Latin-1 and not UTF-8, which would require
2692  * special treatment internally in the engine and do not allow efficient
2693  * indexing. Use String::New or convert to 16 bit data for non-Latin1.
2694  */
2695 
2697  : public ExternalStringResourceBase {
2698  public:
2699  /**
2700  * Override the destructor to manage the life cycle of the underlying
2701  * buffer.
2702  */
2704  /** The string data from the underlying buffer.*/
2705  virtual const char* data() const = 0;
2706  /** The number of Latin-1 characters in the string.*/
2707  virtual size_t length() const = 0;
2708  protected:
2710  };
2711 
2712  /**
2713  * If the string is an external string, return the ExternalStringResourceBase
2714  * regardless of the encoding, otherwise return NULL. The encoding of the
2715  * string is returned in encoding_out.
2716  */
2718  Encoding* encoding_out) const;
2719 
2720  /**
2721  * Get the ExternalStringResource for an external string. Returns
2722  * NULL if IsExternal() doesn't return true.
2723  */
2725 
2726  /**
2727  * Get the ExternalOneByteStringResource for an external one-byte string.
2728  * Returns NULL if IsExternalOneByte() doesn't return true.
2729  */
2731 
2732  V8_INLINE static String* Cast(v8::Value* obj);
2733 
2734  // TODO(dcarney): remove with deprecation of New functions.
2736  kNormalString = static_cast<int>(v8::NewStringType::kNormal),
2738  };
2739 
2740  /** Allocates a new string from UTF-8 data.*/
2741  static V8_DEPRECATE_SOON(
2742  "Use maybe version",
2743  Local<String> NewFromUtf8(Isolate* isolate, const char* data,
2745  int length = -1));
2746 
2747  /** Allocates a new string from UTF-8 data. Only returns an empty value when
2748  * length > kMaxLength. **/
2749  static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromUtf8(
2750  Isolate* isolate, const char* data, v8::NewStringType type,
2751  int length = -1);
2752 
2753  /** Allocates a new string from Latin-1 data. Only returns an empty value
2754  * when length > kMaxLength. **/
2755  static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromOneByte(
2756  Isolate* isolate, const uint8_t* data, v8::NewStringType type,
2757  int length = -1);
2758 
2759  /** Allocates a new string from UTF-16 data.*/
2760  static V8_DEPRECATE_SOON(
2761  "Use maybe version",
2762  Local<String> NewFromTwoByte(Isolate* isolate, const uint16_t* data,
2764  int length = -1));
2765 
2766  /** Allocates a new string from UTF-16 data. Only returns an empty value when
2767  * length > kMaxLength. **/
2768  static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromTwoByte(
2769  Isolate* isolate, const uint16_t* data, v8::NewStringType type,
2770  int length = -1);
2771 
2772  /**
2773  * Creates a new string by concatenating the left and the right strings
2774  * passed in as parameters.
2775  */
2776  static Local<String> Concat(Local<String> left, Local<String> right);
2777 
2778  /**
2779  * Creates a new external string using the data defined in the given
2780  * resource. When the external string is no longer live on V8's heap the
2781  * resource will be disposed by calling its Dispose method. The caller of
2782  * this function should not otherwise delete or modify the resource. Neither
2783  * should the underlying buffer be deallocated or modified except through the
2784  * destructor of the external string resource.
2785  */
2786  static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewExternalTwoByte(
2787  Isolate* isolate, ExternalStringResource* resource);
2788 
2789  /**
2790  * Associate an external string resource with this string by transforming it
2791  * in place so that existing references to this string in the JavaScript heap
2792  * will use the external string resource. The external string resource's
2793  * character contents need to be equivalent to this string.
2794  * Returns true if the string has been changed to be an external string.
2795  * The string is not modified if the operation fails. See NewExternal for
2796  * information on the lifetime of the resource.
2797  */
2798  bool MakeExternal(ExternalStringResource* resource);
2799 
2800  /**
2801  * Creates a new external string using the one-byte data defined in the given
2802  * resource. When the external string is no longer live on V8's heap the
2803  * resource will be disposed by calling its Dispose method. The caller of
2804  * this function should not otherwise delete or modify the resource. Neither
2805  * should the underlying buffer be deallocated or modified except through the
2806  * destructor of the external string resource.
2807  */
2808  static V8_DEPRECATE_SOON(
2809  "Use maybe version",
2810  Local<String> NewExternal(Isolate* isolate,
2811  ExternalOneByteStringResource* resource));
2812  static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewExternalOneByte(
2813  Isolate* isolate, ExternalOneByteStringResource* resource);
2814 
2815  /**
2816  * Associate an external string resource with this string by transforming it
2817  * in place so that existing references to this string in the JavaScript heap
2818  * will use the external string resource. The external string resource's
2819  * character contents need to be equivalent to this string.
2820  * Returns true if the string has been changed to be an external string.
2821  * The string is not modified if the operation fails. See NewExternal for
2822  * information on the lifetime of the resource.
2823  */
2825 
2826  /**
2827  * Returns true if this string can be made external.
2828  */
2829  bool CanMakeExternal();
2830 
2831  /**
2832  * Converts an object to a UTF-8-encoded character array. Useful if
2833  * you want to print the object. If conversion to a string fails
2834  * (e.g. due to an exception in the toString() method of the object)
2835  * then the length() method returns 0 and the * operator returns
2836  * NULL.
2837  */
2839  public:
2840  V8_DEPRECATED("Use Isolate version",
2841  explicit Utf8Value(Local<v8::Value> obj));
2842  Utf8Value(Isolate* isolate, Local<v8::Value> obj);
2843  ~Utf8Value();
2844  char* operator*() { return str_; }
2845  const char* operator*() const { return str_; }
2846  int length() const { return length_; }
2847 
2848  // Disallow copying and assigning.
2849  Utf8Value(const Utf8Value&) = delete;
2850  void operator=(const Utf8Value&) = delete;
2851 
2852  private:
2853  char* str_;
2854  int length_;
2855  };
2856 
2857  /**
2858  * Converts an object to a two-byte (UTF-16-encoded) string.
2859  * If conversion to a string fails (eg. due to an exception in the toString()
2860  * method of the object) then the length() method returns 0 and the * operator
2861  * returns NULL.
2862  */
2864  public:
2865  V8_DEPRECATED("Use Isolate version", explicit Value(Local<v8::Value> obj));
2866  Value(Isolate* isolate, Local<v8::Value> obj);
2867  ~Value();
2868  uint16_t* operator*() { return str_; }
2869  const uint16_t* operator*() const { return str_; }
2870  int length() const { return length_; }
2871 
2872  // Disallow copying and assigning.
2873  Value(const Value&) = delete;
2874  void operator=(const Value&) = delete;
2875 
2876  private:
2877  uint16_t* str_;
2878  int length_;
2879  };
2880 
2881  private:
2882  void VerifyExternalStringResourceBase(ExternalStringResourceBase* v,
2883  Encoding encoding) const;
2884  void VerifyExternalStringResource(ExternalStringResource* val) const;
2885  static void CheckCast(v8::Value* obj);
2886 };
2887 
2888 
2889 /**
2890  * A JavaScript symbol (ECMA-262 edition 6)
2891  */
2892 class V8_EXPORT Symbol : public Name {
2893  public:
2894  /**
2895  * Returns the print name string of the symbol, or undefined if none.
2896  */
2897  Local<Value> Name() const;
2898 
2899  /**
2900  * Create a symbol. If name is not empty, it will be used as the description.
2901  */
2902  static Local<Symbol> New(Isolate* isolate,
2903  Local<String> name = Local<String>());
2904 
2905  /**
2906  * Access global symbol registry.
2907  * Note that symbols created this way are never collected, so
2908  * they should only be used for statically fixed properties.
2909  * Also, there is only one global name space for the names used as keys.
2910  * To minimize the potential for clashes, use qualified names as keys.
2911  */
2912  static Local<Symbol> For(Isolate *isolate, Local<String> name);
2913 
2914  /**
2915  * Retrieve a global symbol. Similar to |For|, but using a separate
2916  * registry that is not accessible by (and cannot clash with) JavaScript code.
2917  */
2918  static Local<Symbol> ForApi(Isolate *isolate, Local<String> name);
2919 
2920  // Well-known symbols
2921  static Local<Symbol> GetHasInstance(Isolate* isolate);
2922  static Local<Symbol> GetIsConcatSpreadable(Isolate* isolate);
2923  static Local<Symbol> GetIterator(Isolate* isolate);
2924  static Local<Symbol> GetMatch(Isolate* isolate);
2925  static Local<Symbol> GetReplace(Isolate* isolate);
2926  static Local<Symbol> GetSearch(Isolate* isolate);
2927  static Local<Symbol> GetSplit(Isolate* isolate);
2928  static Local<Symbol> GetToPrimitive(Isolate* isolate);
2929  static Local<Symbol> GetToStringTag(Isolate* isolate);
2930  static Local<Symbol> GetUnscopables(Isolate* isolate);
2931 
2932  V8_INLINE static Symbol* Cast(Value* obj);
2933 
2934  private:
2935  Symbol();
2936  static void CheckCast(Value* obj);
2937 };
2938 
2939 
2940 /**
2941  * A private symbol
2942  *
2943  * This is an experimental feature. Use at your own risk.
2944  */
2945 class V8_EXPORT Private : public Data {
2946  public:
2947  /**
2948  * Returns the print name string of the private symbol, or undefined if none.
2949  */
2950  Local<Value> Name() const;
2951 
2952  /**
2953  * Create a private symbol. If name is not empty, it will be the description.
2954  */
2955  static Local<Private> New(Isolate* isolate,
2956  Local<String> name = Local<String>());
2957 
2958  /**
2959  * Retrieve a global private symbol. If a symbol with this name has not
2960  * been retrieved in the same isolate before, it is created.
2961  * Note that private symbols created this way are never collected, so
2962  * they should only be used for statically fixed properties.
2963  * Also, there is only one global name space for the names used as keys.
2964  * To minimize the potential for clashes, use qualified names as keys,
2965  * e.g., "Class#property".
2966  */
2967  static Local<Private> ForApi(Isolate* isolate, Local<String> name);
2968 
2969  V8_INLINE static Private* Cast(Data* data);
2970 
2971  private:
2972  Private();
2973 
2974  static void CheckCast(Data* that);
2975 };
2976 
2977 
2978 /**
2979  * A JavaScript number value (ECMA-262, 4.3.20)
2980  */
2981 class V8_EXPORT Number : public Primitive {
2982  public:
2983  double Value() const;
2984  static Local<Number> New(Isolate* isolate, double value);
2985  V8_INLINE static Number* Cast(v8::Value* obj);
2986  private:
2987  Number();
2988  static void CheckCast(v8::Value* obj);
2989 };
2990 
2991 
2992 /**
2993  * A JavaScript value representing a signed integer.
2994  */
2995 class V8_EXPORT Integer : public Number {
2996  public:
2997  static Local<Integer> New(Isolate* isolate, int32_t value);
2998  static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value);
2999  int64_t Value() const;
3000  V8_INLINE static Integer* Cast(v8::Value* obj);
3001  private:
3002  Integer();
3003  static void CheckCast(v8::Value* obj);
3004 };
3005 
3006 
3007 /**
3008  * A JavaScript value representing a 32-bit signed integer.
3009  */
3010 class V8_EXPORT Int32 : public Integer {
3011  public:
3012  int32_t Value() const;
3013  V8_INLINE static Int32* Cast(v8::Value* obj);
3014 
3015  private:
3016  Int32();
3017  static void CheckCast(v8::Value* obj);
3018 };
3019 
3020 
3021 /**
3022  * A JavaScript value representing a 32-bit unsigned integer.
3023  */
3024 class V8_EXPORT Uint32 : public Integer {
3025  public:
3026  uint32_t Value() const;
3027  V8_INLINE static Uint32* Cast(v8::Value* obj);
3028 
3029  private:
3030  Uint32();
3031  static void CheckCast(v8::Value* obj);
3032 };
3033 
3034 /**
3035  * A JavaScript BigInt value (https://tc39.github.io/proposal-bigint)
3036  */
3037 class V8_EXPORT BigInt : public Primitive {
3038  public:
3039  static Local<BigInt> New(Isolate* isolate, int64_t value);
3040  V8_INLINE static BigInt* Cast(v8::Value* obj);
3041 
3042  private:
3043  BigInt();
3044  static void CheckCast(v8::Value* obj);
3045 };
3046 
3047 /**
3048  * PropertyAttribute.
3049  */
3051  /** None. **/
3052  None = 0,
3053  /** ReadOnly, i.e., not writable. **/
3054  ReadOnly = 1 << 0,
3055  /** DontEnum, i.e., not enumerable. **/
3056  DontEnum = 1 << 1,
3057  /** DontDelete, i.e., not configurable. **/
3058  DontDelete = 1 << 2
3059 };
3060 
3061 /**
3062  * Accessor[Getter|Setter] are used as callback functions when
3063  * setting|getting a particular property. See Object and ObjectTemplate's
3064  * method SetAccessor.
3065  */
3066 typedef void (*AccessorGetterCallback)(
3067  Local<String> property,
3068  const PropertyCallbackInfo<Value>& info);
3070  Local<Name> property,
3071  const PropertyCallbackInfo<Value>& info);
3072 
3073 
3074 typedef void (*AccessorSetterCallback)(
3075  Local<String> property,
3076  Local<Value> value,
3077  const PropertyCallbackInfo<void>& info);
3079  Local<Name> property,
3080  Local<Value> value,
3081  const PropertyCallbackInfo<void>& info);
3082 
3083 
3084 /**
3085  * Access control specifications.
3086  *
3087  * Some accessors should be accessible across contexts. These
3088  * accessors have an explicit access control parameter which specifies
3089  * the kind of cross-context access that should be allowed.
3090  *
3091  * TODO(dcarney): Remove PROHIBITS_OVERWRITING as it is now unused.
3092  */
3094  DEFAULT = 0,
3096  ALL_CAN_WRITE = 1 << 1,
3098 };
3099 
3100 /**
3101  * Property filter bits. They can be or'ed to build a composite filter.
3102  */
3110 };
3111 
3112 /**
3113  * Options for marking whether callbacks may trigger JS-observable side effects.
3114  * Side-effect-free callbacks are whitelisted during debug evaluation with
3115  * throwOnSideEffect. It applies when calling a Function, FunctionTemplate,
3116  * or an Accessor's getter callback. For Interceptors, please see
3117  * PropertyHandlerFlags's kHasNoSideEffect.
3118  */
3120 
3121 /**
3122  * Keys/Properties filter enums:
3123  *
3124  * KeyCollectionMode limits the range of collected properties. kOwnOnly limits
3125  * the collected properties to the given Object only. kIncludesPrototypes will
3126  * include all keys of the objects's prototype chain as well.
3127  */
3129 
3130 /**
3131  * kIncludesIndices allows for integer indices to be collected, while
3132  * kSkipIndices will exclude integer indices from being collected.
3133  */
3135 
3136 /**
3137  * kConvertToString will convert integer indices to strings.
3138  * kKeepNumbers will return numbers for integer indices.
3139  */
3141 
3142 /**
3143  * Integrity level for objects.
3144  */
3146 
3147 /**
3148  * A JavaScript object (ECMA-262, 4.3.3)
3149  */
3150 class V8_EXPORT Object : public Value {
3151  public:
3152  V8_DEPRECATE_SOON("Use maybe version",
3153  bool Set(Local<Value> key, Local<Value> value));
3154  V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context,
3155  Local<Value> key, Local<Value> value);
3156 
3157  V8_DEPRECATE_SOON("Use maybe version",
3158  bool Set(uint32_t index, Local<Value> value));
3159  V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context, uint32_t index,
3160  Local<Value> value);
3161 
3162  // Implements CreateDataProperty (ECMA-262, 7.3.4).
3163  //
3164  // Defines a configurable, writable, enumerable property with the given value
3165  // on the object unless the property already exists and is not configurable
3166  // or the object is not extensible.
3167  //
3168  // Returns true on success.
3169  V8_WARN_UNUSED_RESULT Maybe<bool> CreateDataProperty(Local<Context> context,
3170  Local<Name> key,
3171  Local<Value> value);
3172  V8_WARN_UNUSED_RESULT Maybe<bool> CreateDataProperty(Local<Context> context,
3173  uint32_t index,
3174  Local<Value> value);
3175 
3176  // Implements DefineOwnProperty.
3177  //
3178  // In general, CreateDataProperty will be faster, however, does not allow
3179  // for specifying attributes.
3180  //
3181  // Returns true on success.
3183  Local<Context> context, Local<Name> key, Local<Value> value,
3184  PropertyAttribute attributes = None);
3185 
3186  // Implements Object.DefineProperty(O, P, Attributes), see Ecma-262 19.1.2.4.
3187  //
3188  // The defineProperty function is used to add an own property or
3189  // update the attributes of an existing own property of an object.
3190  //
3191  // Both data and accessor descriptors can be used.
3192  //
3193  // In general, CreateDataProperty is faster, however, does not allow
3194  // for specifying attributes or an accessor descriptor.
3195  //
3196  // The PropertyDescriptor can change when redefining a property.
3197  //
3198  // Returns true on success.
3200  Local<Context> context, Local<Name> key, PropertyDescriptor& descriptor);
3201 
3202  V8_DEPRECATE_SOON("Use maybe version", Local<Value> Get(Local<Value> key));
3203  V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
3204  Local<Value> key);
3205 
3206  V8_DEPRECATE_SOON("Use maybe version", Local<Value> Get(uint32_t index));
3207  V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
3208  uint32_t index);
3209 
3210  /**
3211  * Gets the property attributes of a property which can be None or
3212  * any combination of ReadOnly, DontEnum and DontDelete. Returns
3213  * None when the property doesn't exist.
3214  */
3216  Local<Context> context, Local<Value> key);
3217 
3218  /**
3219  * Returns Object.getOwnPropertyDescriptor as per ES2016 section 19.1.2.6.
3220  */
3222  Local<Context> context, Local<Name> key);
3223 
3224  V8_DEPRECATE_SOON("Use maybe version", bool Has(Local<Value> key));
3225  /**
3226  * Object::Has() calls the abstract operation HasProperty(O, P) described
3227  * in ECMA-262, 7.3.10. Has() returns
3228  * true, if the object has the property, either own or on the prototype chain.
3229  * Interceptors, i.e., PropertyQueryCallbacks, are called if present.
3230  *
3231  * Has() has the same side effects as JavaScript's `variable in object`.
3232  * For example, calling Has() on a revoked proxy will throw an exception.
3233  *
3234  * \note Has() converts the key to a name, which possibly calls back into
3235  * JavaScript.
3236  *
3237  * See also v8::Object::HasOwnProperty() and
3238  * v8::Object::HasRealNamedProperty().
3239  */
3240  V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
3241  Local<Value> key);
3242 
3243  V8_DEPRECATE_SOON("Use maybe version", bool Delete(Local<Value> key));
3244  V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
3245  Local<Value> key);
3246 
3247  V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context, uint32_t index);
3248 
3249  V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
3250  uint32_t index);
3251 
3252  /**
3253  * Note: SideEffectType affects the getter only, not the setter.
3254  */
3255  V8_WARN_UNUSED_RESULT Maybe<bool> SetAccessor(
3256  Local<Context> context, Local<Name> name,
3258  MaybeLocal<Value> data = MaybeLocal<Value>(),
3259  AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
3260  SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect);
3261 
3262  void SetAccessorProperty(Local<Name> name, Local<Function> getter,
3263  Local<Function> setter = Local<Function>(),
3264  PropertyAttribute attribute = None,
3265  AccessControl settings = DEFAULT);
3266 
3267  /**
3268  * Sets a native data property like Template::SetNativeDataProperty, but
3269  * this method sets on this object directly.
3270  */
3272  Local<Context> context, Local<Name> name,
3275  Local<Value> data = Local<Value>(), PropertyAttribute attributes = None,
3276  SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect);
3277 
3278  /**
3279  * Attempts to create a property with the given name which behaves like a data
3280  * property, except that the provided getter is invoked (and provided with the
3281  * data value) to supply its value the first time it is read. After the
3282  * property is accessed once, it is replaced with an ordinary data property.
3283  *
3284  * Analogous to Template::SetLazyDataProperty.
3285  */
3287  Local<Context> context, Local<Name> name,
3288  AccessorNameGetterCallback getter, Local<Value> data = Local<Value>(),
3289  PropertyAttribute attributes = None,
3290  SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect);
3291 
3292  /**
3293  * Functionality for private properties.
3294  * This is an experimental feature, use at your own risk.
3295  * Note: Private properties are not inherited. Do not rely on this, since it
3296  * may change.
3297  */
3298  Maybe<bool> HasPrivate(Local<Context> context, Local<Private> key);
3299  Maybe<bool> SetPrivate(Local<Context> context, Local<Private> key,
3300  Local<Value> value);
3301  Maybe<bool> DeletePrivate(Local<Context> context, Local<Private> key);
3302  MaybeLocal<Value> GetPrivate(Local<Context> context, Local<Private> key);
3303 
3304  /**
3305  * Returns an array containing the names of the enumerable properties
3306  * of this object, including properties from prototype objects. The
3307  * array returned by this method contains the same values as would
3308  * be enumerated by a for-in statement over this object.
3309  */
3310  V8_DEPRECATE_SOON("Use maybe version", Local<Array> GetPropertyNames());
3312  Local<Context> context);
3314  Local<Context> context, KeyCollectionMode mode,
3315  PropertyFilter property_filter, IndexFilter index_filter,
3317 
3318  /**
3319  * This function has the same functionality as GetPropertyNames but
3320  * the returned array doesn't contain the names of properties from
3321  * prototype objects.
3322  */
3323  V8_DEPRECATE_SOON("Use maybe version", Local<Array> GetOwnPropertyNames());
3325  Local<Context> context);
3326 
3327  /**
3328  * Returns an array containing the names of the filtered properties
3329  * of this object, including properties from prototype objects. The
3330  * array returned by this method contains the same values as would
3331  * be enumerated by a for-in statement over this object.
3332  */
3334  Local<Context> context, PropertyFilter filter,
3336 
3337  /**
3338  * Get the prototype object. This does not skip objects marked to
3339  * be skipped by __proto__ and it does not consult the security
3340  * handler.
3341  */
3342  Local<Value> GetPrototype();
3343 
3344  /**
3345  * Set the prototype object. This does not skip objects marked to
3346  * be skipped by __proto__ and it does not consult the security
3347  * handler.
3348  */
3349  V8_WARN_UNUSED_RESULT Maybe<bool> SetPrototype(Local<Context> context,
3350  Local<Value> prototype);
3351 
3352  /**
3353  * Finds an instance of the given function template in the prototype
3354  * chain.
3355  */
3357 
3358  /**
3359  * Call builtin Object.prototype.toString on this object.
3360  * This is different from Value::ToString() that may call
3361  * user-defined toString function. This one does not.
3362  */
3364  Local<Context> context);
3365 
3366  /**
3367  * Returns the name of the function invoked as a constructor for this object.
3368  */
3369  Local<String> GetConstructorName();
3370 
3371  /**
3372  * Sets the integrity level of the object.
3373  */
3374  Maybe<bool> SetIntegrityLevel(Local<Context> context, IntegrityLevel level);
3375 
3376  /** Gets the number of internal fields for this Object. */
3377  int InternalFieldCount();
3378 
3379  /** Same as above, but works for Persistents */
3381  const PersistentBase<Object>& object) {
3382  return object.val_->InternalFieldCount();
3383  }
3384 
3385  /** Gets the value from an internal field. */
3386  V8_INLINE Local<Value> GetInternalField(int index);
3387 
3388  /** Sets the value in an internal field. */
3389  void SetInternalField(int index, Local<Value> value);
3390 
3391  /**
3392  * Gets a 2-byte-aligned native pointer from an internal field. This field
3393  * must have been set by SetAlignedPointerInInternalField, everything else
3394  * leads to undefined behavior.
3395  */
3397 
3398  /** Same as above, but works for Persistents */
3400  const PersistentBase<Object>& object, int index) {
3401  return object.val_->GetAlignedPointerFromInternalField(index);
3402  }
3403 
3404  /**
3405  * Sets a 2-byte-aligned native pointer in an internal field. To retrieve such
3406  * a field, GetAlignedPointerFromInternalField must be used, everything else
3407  * leads to undefined behavior.
3408  */
3409  void SetAlignedPointerInInternalField(int index, void* value);
3410  void SetAlignedPointerInInternalFields(int argc, int indices[],
3411  void* values[]);
3412 
3413  /**
3414  * HasOwnProperty() is like JavaScript's Object.prototype.hasOwnProperty().
3415  *
3416  * See also v8::Object::Has() and v8::Object::HasRealNamedProperty().
3417  */
3418  V8_WARN_UNUSED_RESULT Maybe<bool> HasOwnProperty(Local<Context> context,
3419  Local<Name> key);
3420  V8_WARN_UNUSED_RESULT Maybe<bool> HasOwnProperty(Local<Context> context,
3421  uint32_t index);
3422  V8_DEPRECATE_SOON("Use maybe version",
3423  bool HasRealNamedProperty(Local<String> key));
3424  /**
3425  * Use HasRealNamedProperty() if you want to check if an object has an own
3426  * property without causing side effects, i.e., without calling interceptors.
3427  *
3428  * This function is similar to v8::Object::HasOwnProperty(), but it does not
3429  * call interceptors.
3430  *
3431  * \note Consider using non-masking interceptors, i.e., the interceptors are
3432  * not called if the receiver has the real named property. See
3433  * `v8::PropertyHandlerFlags::kNonMasking`.
3434  *
3435  * See also v8::Object::Has().
3436  */
3437  V8_WARN_UNUSED_RESULT Maybe<bool> HasRealNamedProperty(Local<Context> context,
3438  Local<Name> key);
3439  V8_DEPRECATE_SOON("Use maybe version",
3440  bool HasRealIndexedProperty(uint32_t index));
3442  Local<Context> context, uint32_t index);
3443  V8_DEPRECATE_SOON("Use maybe version",
3444  bool HasRealNamedCallbackProperty(Local<String> key));
3446  Local<Context> context, Local<Name> key);
3447 
3448  /**
3449  * If result.IsEmpty() no real property was located in the prototype chain.
3450  * This means interceptors in the prototype chain are not called.
3451  */
3453  Local<Context> context, Local<Name> key);
3454 
3455  /**
3456  * Gets the property attributes of a real property in the prototype chain,
3457  * which can be None or any combination of ReadOnly, DontEnum and DontDelete.
3458  * Interceptors in the prototype chain are not called.
3459  */
3462  Local<Name> key);
3463 
3464  /**
3465  * If result.IsEmpty() no real property was located on the object or
3466  * in the prototype chain.
3467  * This means interceptors in the prototype chain are not called.
3468  */
3470  Local<Context> context, Local<Name> key);
3471 
3472  /**
3473  * Gets the property attributes of a real property which can be
3474  * None or any combination of ReadOnly, DontEnum and DontDelete.
3475  * Interceptors in the prototype chain are not called.
3476  */
3478  Local<Context> context, Local<Name> key);
3479 
3480  /** Tests for a named lookup interceptor.*/
3482 
3483  /** Tests for an index lookup interceptor.*/
3485 
3486  /**
3487  * Returns the identity hash for this object. The current implementation
3488  * uses a hidden property on the object to store the identity hash.
3489  *
3490  * The return value will never be 0. Also, it is not guaranteed to be
3491  * unique.
3492  */
3493  int GetIdentityHash();
3494 
3495  /**
3496  * Clone this object with a fast but shallow copy. Values will point
3497  * to the same values as the original object.
3498  */
3499  // TODO(dcarney): take an isolate and optionally bail out?
3500  Local<Object> Clone();
3501 
3502  /**
3503  * Returns the context in which the object was created.
3504  */
3505  Local<Context> CreationContext();
3506 
3507  /** Same as above, but works for Persistents */
3509  const PersistentBase<Object>& object) {
3510  return object.val_->CreationContext();
3511  }
3512 
3513  /**
3514  * Checks whether a callback is set by the
3515  * ObjectTemplate::SetCallAsFunctionHandler method.
3516  * When an Object is callable this method returns true.
3517  */
3518  bool IsCallable();
3519 
3520  /**
3521  * True if this object is a constructor.
3522  */
3523  bool IsConstructor();
3524 
3525  /**
3526  * Call an Object as a function if a callback is set by the
3527  * ObjectTemplate::SetCallAsFunctionHandler method.
3528  */
3529  V8_WARN_UNUSED_RESULT MaybeLocal<Value> CallAsFunction(Local<Context> context,
3530  Local<Value> recv,
3531  int argc,
3532  Local<Value> argv[]);
3533 
3534  /**
3535  * Call an Object as a constructor if a callback is set by the
3536  * ObjectTemplate::SetCallAsFunctionHandler method.
3537  * Note: This method behaves like the Function::NewInstance method.
3538  */
3540  Local<Context> context, int argc, Local<Value> argv[]);
3541 
3542  /**
3543  * Return the isolate to which the Object belongs to.
3544  */
3545  Isolate* GetIsolate();
3546 
3547  static Local<Object> New(Isolate* isolate);
3548 
3549  V8_INLINE static Object* Cast(Value* obj);
3550 
3551  private:
3552  Object();
3553  static void CheckCast(Value* obj);
3554  Local<Value> SlowGetInternalField(int index);
3555  void* SlowGetAlignedPointerFromInternalField(int index);
3556 };
3557 
3558 
3559 /**
3560  * An instance of the built-in array constructor (ECMA-262, 15.4.2).
3561  */
3562 class V8_EXPORT Array : public Object {
3563  public:
3564  uint32_t Length() const;
3565 
3566  /**
3567  * Creates a JavaScript array with the given length. If the length
3568  * is negative the returned array will have length 0.
3569  */
3570  static Local<Array> New(Isolate* isolate, int length = 0);
3571 
3572  V8_INLINE static Array* Cast(Value* obj);
3573  private:
3574  Array();
3575  static void CheckCast(Value* obj);
3576 };
3577 
3578 
3579 /**
3580  * An instance of the built-in Map constructor (ECMA-262, 6th Edition, 23.1.1).
3581  */
3582 class V8_EXPORT Map : public Object {
3583  public:
3584  size_t Size() const;
3585  void Clear();
3586  V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
3587  Local<Value> key);
3588  V8_WARN_UNUSED_RESULT MaybeLocal<Map> Set(Local<Context> context,
3589  Local<Value> key,
3590  Local<Value> value);
3591  V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
3592  Local<Value> key);
3593  V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
3594  Local<Value> key);
3595 
3596  /**
3597  * Returns an array of length Size() * 2, where index N is the Nth key and
3598  * index N + 1 is the Nth value.
3599  */
3600  Local<Array> AsArray() const;
3601 
3602  /**
3603  * Creates a new empty Map.
3604  */
3605  static Local<Map> New(Isolate* isolate);
3606 
3607  V8_INLINE static Map* Cast(Value* obj);
3608 
3609  private:
3610  Map();
3611  static void CheckCast(Value* obj);
3612 };
3613 
3614 
3615 /**
3616  * An instance of the built-in Set constructor (ECMA-262, 6th Edition, 23.2.1).
3617  */
3618 class V8_EXPORT Set : public Object {
3619  public:
3620  size_t Size() const;
3621  void Clear();
3622  V8_WARN_UNUSED_RESULT MaybeLocal<Set> Add(Local<Context> context,
3623  Local<Value> key);
3624  V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
3625  Local<Value> key);
3626  V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
3627  Local<Value> key);
3628 
3629  /**
3630  * Returns an array of the keys in this Set.
3631  */
3632  Local<Array> AsArray() const;
3633 
3634  /**
3635  * Creates a new empty Set.
3636  */
3637  static Local<Set> New(Isolate* isolate);
3638 
3639  V8_INLINE static Set* Cast(Value* obj);
3640 
3641  private:
3642  Set();
3643  static void CheckCast(Value* obj);
3644 };
3645 
3646 
3647 template<typename T>
3648 class ReturnValue {
3649  public:
3650  template <class S> V8_INLINE ReturnValue(const ReturnValue<S>& that)
3651  : value_(that.value_) {
3652  TYPE_CHECK(T, S);
3653  }
3654  // Local setters
3655  template <typename S>
3656  V8_INLINE V8_DEPRECATE_SOON("Use Global<> instead",
3657  void Set(const Persistent<S>& handle));
3658  template <typename S>
3659  V8_INLINE void Set(const Global<S>& handle);
3660  template <typename S>
3661  V8_INLINE void Set(const Local<S> handle);
3662  // Fast primitive setters
3663  V8_INLINE void Set(bool value);
3664  V8_INLINE void Set(double i);
3665  V8_INLINE void Set(int32_t i);
3666  V8_INLINE void Set(uint32_t i);
3667  // Fast JS primitive setters
3668  V8_INLINE void SetNull();
3669  V8_INLINE void SetUndefined();
3670  V8_INLINE void SetEmptyString();
3671  // Convenience getter for Isolate
3672  V8_INLINE Isolate* GetIsolate() const;
3673 
3674  // Pointer setter: Uncompilable to prevent inadvertent misuse.
3675  template <typename S>
3676  V8_INLINE void Set(S* whatever);
3677 
3678  // Getter. Creates a new Local<> so it comes with a certain performance
3679  // hit. If the ReturnValue was not yet set, this will return the undefined
3680  // value.
3681  V8_INLINE Local<Value> Get() const;
3682 
3683  private:
3684  template<class F> friend class ReturnValue;
3685  template<class F> friend class FunctionCallbackInfo;
3686  template<class F> friend class PropertyCallbackInfo;
3687  template <class F, class G, class H>
3689  V8_INLINE void SetInternal(internal::Object* value) { *value_ = value; }
3690  V8_INLINE internal::Object* GetDefaultValue();
3691  V8_INLINE explicit ReturnValue(internal::Object** slot);
3692  internal::Object** value_;
3693 };
3694 
3695 
3696 /**
3697  * The argument information given to function call callbacks. This
3698  * class provides access to information about the context of the call,
3699  * including the receiver, the number and values of arguments, and
3700  * the holder of the function.
3701  */
3702 template<typename T>
3703 class FunctionCallbackInfo {
3704  public:
3705  /** The number of available arguments. */
3706  V8_INLINE int Length() const;
3707  /** Accessor for the available arguments. */
3708  V8_INLINE Local<Value> operator[](int i) const;
3709  /** Returns the receiver. This corresponds to the "this" value. */
3710  V8_INLINE Local<Object> This() const;
3711  /**
3712  * If the callback was created without a Signature, this is the same
3713  * value as This(). If there is a signature, and the signature didn't match
3714  * This() but one of its hidden prototypes, this will be the respective
3715  * hidden prototype.
3716  *
3717  * Note that this is not the prototype of This() on which the accessor
3718  * referencing this callback was found (which in V8 internally is often
3719  * referred to as holder [sic]).
3720  */
3721  V8_INLINE Local<Object> Holder() const;
3722  /** For construct calls, this returns the "new.target" value. */
3723  V8_INLINE Local<Value> NewTarget() const;
3724  /** Indicates whether this is a regular call or a construct call. */
3725  V8_INLINE bool IsConstructCall() const;
3726  /** The data argument specified when creating the callback. */
3727  V8_INLINE Local<Value> Data() const;
3728  /** The current Isolate. */
3729  V8_INLINE Isolate* GetIsolate() const;
3730  /** The ReturnValue for the call. */
3731  V8_INLINE ReturnValue<T> GetReturnValue() const;
3732  // This shouldn't be public, but the arm compiler needs it.
3733  static const int kArgsLength = 6;
3734 
3735  protected:
3739  static const int kHolderIndex = 0;
3740  static const int kIsolateIndex = 1;
3741  static const int kReturnValueDefaultValueIndex = 2;
3742  static const int kReturnValueIndex = 3;
3743  static const int kDataIndex = 4;
3744  static const int kNewTargetIndex = 5;
3745 
3746  V8_INLINE FunctionCallbackInfo(internal::Object** implicit_args,
3747  internal::Object** values, int length);
3749  internal::Object** values_;
3750  int length_;
3751 };
3752 
3753 
3754 /**
3755  * The information passed to a property callback about the context
3756  * of the property access.
3757  */
3758 template<typename T>
3759 class PropertyCallbackInfo {
3760  public:
3761  /**
3762  * \return The isolate of the property access.
3763  */
3764  V8_INLINE Isolate* GetIsolate() const;
3765 
3766  /**
3767  * \return The data set in the configuration, i.e., in
3768  * `NamedPropertyHandlerConfiguration` or
3769  * `IndexedPropertyHandlerConfiguration.`
3770  */
3771  V8_INLINE Local<Value> Data() const;
3772 
3773  /**
3774  * \return The receiver. In many cases, this is the object on which the
3775  * property access was intercepted. When using
3776  * `Reflect.get`, `Function.prototype.call`, or similar functions, it is the
3777  * object passed in as receiver or thisArg.
3778  *
3779  * \code
3780  * void GetterCallback(Local<Name> name,
3781  * const v8::PropertyCallbackInfo<v8::Value>& info) {
3782  * auto context = info.GetIsolate()->GetCurrentContext();
3783  *
3784  * v8::Local<v8::Value> a_this =
3785  * info.This()
3786  * ->GetRealNamedProperty(context, v8_str("a"))
3787  * .ToLocalChecked();
3788  * v8::Local<v8::Value> a_holder =
3789  * info.Holder()
3790  * ->GetRealNamedProperty(context, v8_str("a"))
3791  * .ToLocalChecked();
3792  *
3793  * CHECK(v8_str("r")->Equals(context, a_this).FromJust());
3794  * CHECK(v8_str("obj")->Equals(context, a_holder).FromJust());
3795  *
3796  * info.GetReturnValue().Set(name);
3797  * }
3798  *
3799  * v8::Local<v8::FunctionTemplate> templ =
3800  * v8::FunctionTemplate::New(isolate);
3801  * templ->InstanceTemplate()->SetHandler(
3802  * v8::NamedPropertyHandlerConfiguration(GetterCallback));
3803  * LocalContext env;
3804  * env->Global()
3805  * ->Set(env.local(), v8_str("obj"), templ->GetFunction(env.local())
3806  * .ToLocalChecked()
3807  * ->NewInstance(env.local())
3808  * .ToLocalChecked())
3809  * .FromJust();
3810  *
3811  * CompileRun("obj.a = 'obj'; var r = {a: 'r'}; Reflect.get(obj, 'x', r)");
3812  * \endcode
3813  */
3814  V8_INLINE Local<Object> This() const;
3815 
3816  /**
3817  * \return The object in the prototype chain of the receiver that has the
3818  * interceptor. Suppose you have `x` and its prototype is `y`, and `y`
3819  * has an interceptor. Then `info.This()` is `x` and `info.Holder()` is `y`.
3820  * The Holder() could be a hidden object (the global object, rather
3821  * than the global proxy).
3822  *
3823  * \note For security reasons, do not pass the object back into the runtime.
3824  */
3825  V8_INLINE Local<Object> Holder() const;
3826 
3827  /**
3828  * \return The return value of the callback.
3829  * Can be changed by calling Set().
3830  * \code
3831  * info.GetReturnValue().Set(...)
3832  * \endcode
3833  *
3834  */
3835  V8_INLINE ReturnValue<T> GetReturnValue() const;
3836 
3837  /**
3838  * \return True if the intercepted function should throw if an error occurs.
3839  * Usually, `true` corresponds to `'use strict'`.
3840  *
3841  * \note Always `false` when intercepting `Reflect.set()`
3842  * independent of the language mode.
3843  */
3844  V8_INLINE bool ShouldThrowOnError() const;
3845 
3846  // This shouldn't be public, but the arm compiler needs it.
3847  static const int kArgsLength = 7;
3848 
3849  protected:
3850  friend class MacroAssembler;
3853  static const int kShouldThrowOnErrorIndex = 0;
3854  static const int kHolderIndex = 1;
3855  static const int kIsolateIndex = 2;
3856  static const int kReturnValueDefaultValueIndex = 3;
3857  static const int kReturnValueIndex = 4;
3858  static const int kDataIndex = 5;
3859  static const int kThisIndex = 6;
3860 
3861  V8_INLINE PropertyCallbackInfo(internal::Object** args) : args_(args) {}
3862  internal::Object** args_;
3863 };
3864 
3865 
3866 typedef void (*FunctionCallback)(const FunctionCallbackInfo<Value>& info);
3867 
3869 
3870 /**
3871  * A JavaScript function object (ECMA-262, 15.3).
3872  */
3873 class V8_EXPORT Function : public Object {
3874  public:
3875  /**
3876  * Create a function in the current execution context
3877  * for a given FunctionCallback.
3878  */
3879  static MaybeLocal<Function> New(
3880  Local<Context> context, FunctionCallback callback,
3881  Local<Value> data = Local<Value>(), int length = 0,
3883  SideEffectType side_effect_type = SideEffectType::kHasSideEffect);
3884  static V8_DEPRECATE_SOON(
3885  "Use maybe version",
3886  Local<Function> New(Isolate* isolate, FunctionCallback callback,
3887  Local<Value> data = Local<Value>(), int length = 0));
3888 
3890  Local<Context> context, int argc, Local<Value> argv[]) const;
3891 
3893  Local<Context> context) const {
3894  return NewInstance(context, 0, nullptr);
3895  }
3896 
3897  V8_DEPRECATE_SOON("Use maybe version",
3898  Local<Value> Call(Local<Value> recv, int argc,
3899  Local<Value> argv[]));
3900  V8_WARN_UNUSED_RESULT MaybeLocal<Value> Call(Local<Context> context,
3901  Local<Value> recv, int argc,
3902  Local<Value> argv[]);
3903 
3904  void SetName(Local<String> name);
3905  Local<Value> GetName() const;
3906 
3907  /**
3908  * Name inferred from variable or property assignment of this function.
3909  * Used to facilitate debugging and profiling of JavaScript code written
3910  * in an OO style, where many functions are anonymous but are assigned
3911  * to object properties.
3912  */
3913  Local<Value> GetInferredName() const;
3914 
3915  /**
3916  * displayName if it is set, otherwise name if it is configured, otherwise
3917  * function name, otherwise inferred name.
3918  */
3919  Local<Value> GetDebugName() const;
3920 
3921  /**
3922  * User-defined name assigned to the "displayName" property of this function.
3923  * Used to facilitate debugging and profiling of JavaScript code.
3924  */
3925  Local<Value> GetDisplayName() const;
3926 
3927  /**
3928  * Returns zero based line number of function body and
3929  * kLineOffsetNotFound if no information available.
3930  */
3931  int GetScriptLineNumber() const;
3932  /**
3933  * Returns zero based column number of function body and
3934  * kLineOffsetNotFound if no information available.
3935  */
3936  int GetScriptColumnNumber() const;
3937 
3938  /**
3939  * Returns scriptId.
3940  */
3941  int ScriptId() const;
3942 
3943  /**
3944  * Returns the original function if this function is bound, else returns
3945  * v8::Undefined.
3946  */
3947  Local<Value> GetBoundFunction() const;
3948 
3949  ScriptOrigin GetScriptOrigin() const;
3950  V8_INLINE static Function* Cast(Value* obj);
3951  static const int kLineOffsetNotFound;
3952 
3953  private:
3954  Function();
3955  static void CheckCast(Value* obj);
3956 };
3957 
3958 #ifndef V8_PROMISE_INTERNAL_FIELD_COUNT
3959 // The number of required internal fields can be defined by embedder.
3960 #define V8_PROMISE_INTERNAL_FIELD_COUNT 0
3961 #endif
3962 
3963 /**
3964  * An instance of the built-in Promise constructor (ES6 draft).
3965  */
3966 class V8_EXPORT Promise : public Object {
3967  public:
3968  /**
3969  * State of the promise. Each value corresponds to one of the possible values
3970  * of the [[PromiseState]] field.
3971  */
3973 
3974  class V8_EXPORT Resolver : public Object {
3975  public:
3976  /**
3977  * Create a new resolver, along with an associated promise in pending state.
3978  */
3979  static V8_DEPRECATED("Use maybe version",
3980  Local<Resolver> New(Isolate* isolate));
3981  static V8_WARN_UNUSED_RESULT MaybeLocal<Resolver> New(
3982  Local<Context> context);
3983 
3984  /**
3985  * Extract the associated promise.
3986  */
3987  Local<Promise> GetPromise();
3988 
3989  /**
3990  * Resolve/reject the associated promise with a given value.
3991  * Ignored if the promise is no longer pending.
3992  */
3993  V8_DEPRECATED("Use maybe version", void Resolve(Local<Value> value));
3994  V8_WARN_UNUSED_RESULT Maybe<bool> Resolve(Local<Context> context,
3995  Local<Value> value);
3996 
3997  V8_DEPRECATED("Use maybe version", void Reject(Local<Value> value));
3998  V8_WARN_UNUSED_RESULT Maybe<bool> Reject(Local<Context> context,
3999  Local<Value> value);
4000 
4001  V8_INLINE static Resolver* Cast(Value* obj);
4002 
4003  private:
4004  Resolver();
4005  static void CheckCast(Value* obj);
4006  };
4007 
4008  /**
4009  * Register a resolution/rejection handler with a promise.
4010  * The handler is given the respective resolution/rejection value as
4011  * an argument. If the promise is already resolved/rejected, the handler is
4012  * invoked at the end of turn.
4013  */
4014  V8_WARN_UNUSED_RESULT MaybeLocal<Promise> Catch(Local<Context> context,
4015  Local<Function> handler);
4016 
4017  V8_WARN_UNUSED_RESULT MaybeLocal<Promise> Then(Local<Context> context,
4018  Local<Function> handler);
4019 
4020  /**
4021  * Returns true if the promise has at least one derived promise, and
4022  * therefore resolve/reject handlers (including default handler).
4023  */
4024  bool HasHandler();
4025 
4026  /**
4027  * Returns the content of the [[PromiseResult]] field. The Promise must not
4028  * be pending.
4029  */
4030  Local<Value> Result();
4031 
4032  /**
4033  * Returns the value of the [[PromiseState]] field.
4034  */
4035  PromiseState State();
4036 
4037  V8_INLINE static Promise* Cast(Value* obj);
4038 
4040 
4041  private:
4042  Promise();
4043  static void CheckCast(Value* obj);
4044 };
4045 
4046 /**
4047  * An instance of a Property Descriptor, see Ecma-262 6.2.4.
4048  *
4049  * Properties in a descriptor are present or absent. If you do not set
4050  * `enumerable`, `configurable`, and `writable`, they are absent. If `value`,
4051  * `get`, or `set` are absent, but you must specify them in the constructor, use
4052  * empty handles.
4053  *
4054  * Accessors `get` and `set` must be callable or undefined if they are present.
4055  *
4056  * \note Only query properties if they are present, i.e., call `x()` only if
4057  * `has_x()` returns true.
4058  *
4059  * \code
4060  * // var desc = {writable: false}
4061  * v8::PropertyDescriptor d(Local<Value>()), false);
4062  * d.value(); // error, value not set
4063  * if (d.has_writable()) {
4064  * d.writable(); // false
4065  * }
4066  *
4067  * // var desc = {value: undefined}
4068  * v8::PropertyDescriptor d(v8::Undefined(isolate));
4069  *
4070  * // var desc = {get: undefined}
4071  * v8::PropertyDescriptor d(v8::Undefined(isolate), Local<Value>()));
4072  * \endcode
4073  */
4075  public:
4076  // GenericDescriptor
4078 
4079  // DataDescriptor
4080  PropertyDescriptor(Local<Value> value);
4081 
4082  // DataDescriptor with writable property
4083  PropertyDescriptor(Local<Value> value, bool writable);
4084 
4085  // AccessorDescriptor
4086  PropertyDescriptor(Local<Value> get, Local<Value> set);
4087 
4088  ~PropertyDescriptor();
4089 
4090  Local<Value> value() const;
4091  bool has_value() const;
4092 
4093  Local<Value> get() const;
4094  bool has_get() const;
4095  Local<Value> set() const;
4096  bool has_set() const;
4097 
4098  void set_enumerable(bool enumerable);
4099  bool enumerable() const;
4100  bool has_enumerable() const;
4101 
4102  void set_configurable(bool configurable);
4103  bool configurable() const;
4104  bool has_configurable() const;
4105 
4106  bool writable() const;
4107  bool has_writable() const;
4108 
4109  struct PrivateData;
4110  PrivateData* get_private() const { return private_; }
4111 
4112  PropertyDescriptor(const PropertyDescriptor&) = delete;
4113  void operator=(const PropertyDescriptor&) = delete;
4114 
4115  private:
4116  PrivateData* private_;
4117 };
4118 
4119 /**
4120  * An instance of the built-in Proxy constructor (ECMA-262, 6th Edition,
4121  * 26.2.1).
4122  */
4123 class V8_EXPORT Proxy : public Object {
4124  public:
4125  Local<Value> GetTarget();
4126  Local<Value> GetHandler();
4127  bool IsRevoked();
4128  void Revoke();
4129 
4130  /**
4131  * Creates a new Proxy for the target object.
4132  */
4133  static MaybeLocal<Proxy> New(Local<Context> context,
4134  Local<Object> local_target,
4135  Local<Object> local_handler);
4136 
4137  V8_INLINE static Proxy* Cast(Value* obj);
4138 
4139  private:
4140  Proxy();
4141  static void CheckCast(Value* obj);
4142 };
4143 
4144 // TODO(mtrofin): rename WasmCompiledModule to WasmModuleObject, for
4145 // consistency with internal APIs.
4147  public:
4149  /**
4150  * A buffer that is owned by the caller.
4151  */
4153 
4154  /**
4155  * An opaque, native heap object for transferring wasm modules. It
4156  * supports move semantics, and does not support copy semantics.
4157  */
4158  class TransferrableModule final {
4159  public:
4160  TransferrableModule(TransferrableModule&& src) = default;
4161  TransferrableModule(const TransferrableModule& src) = delete;
4162 
4163  TransferrableModule& operator=(TransferrableModule&& src) = default;
4164  TransferrableModule& operator=(const TransferrableModule& src) = delete;
4165 
4166  private:
4167  typedef std::pair<std::unique_ptr<const uint8_t[]>, size_t> OwnedBuffer;
4168  friend class WasmCompiledModule;
4169  TransferrableModule(OwnedBuffer&& code, OwnedBuffer&& bytes)
4170  : compiled_code(std::move(code)), wire_bytes(std::move(bytes)) {}
4171 
4172  OwnedBuffer compiled_code = {nullptr, 0};
4173  OwnedBuffer wire_bytes = {nullptr, 0};
4174  };
4175 
4176  /**
4177  * Get an in-memory, non-persistable, and context-independent (meaning,
4178  * suitable for transfer to another Isolate and Context) representation
4179  * of this wasm compiled module.
4180  */
4181  TransferrableModule GetTransferrableModule();
4182 
4183  /**
4184  * Efficiently re-create a WasmCompiledModule, without recompiling, from
4185  * a TransferrableModule.
4186  */
4187  static MaybeLocal<WasmCompiledModule> FromTransferrableModule(
4188  Isolate* isolate, const TransferrableModule&);
4189 
4190  /**
4191  * Get the wasm-encoded bytes that were used to compile this module.
4192  */
4193  Local<String> GetWasmWireBytes();
4194 
4195  /**
4196  * Serialize the compiled module. The serialized data does not include the
4197  * uncompiled bytes.
4198  */
4200 
4201  /**
4202  * If possible, deserialize the module, otherwise compile it from the provided
4203  * uncompiled bytes.
4204  */
4205  static MaybeLocal<WasmCompiledModule> DeserializeOrCompile(
4206  Isolate* isolate, const CallerOwnedBuffer& serialized_module,
4207  const CallerOwnedBuffer& wire_bytes);
4208  V8_INLINE static WasmCompiledModule* Cast(Value* obj);
4209 
4210  private:
4211  static MaybeLocal<WasmCompiledModule> Deserialize(
4212  Isolate* isolate, const CallerOwnedBuffer& serialized_module,
4213  const CallerOwnedBuffer& wire_bytes);
4214  static MaybeLocal<WasmCompiledModule> Compile(Isolate* isolate,
4215  const uint8_t* start,
4216  size_t length);
4217  static CallerOwnedBuffer AsCallerOwned(
4218  const TransferrableModule::OwnedBuffer& buff) {
4219  return {buff.first.get(), buff.second};
4220  }
4221 
4222  WasmCompiledModule();
4223  static void CheckCast(Value* obj);
4224 };
4225 
4226 // TODO(mtrofin): when streaming compilation is done, we can rename this
4227 // to simply WasmModuleObjectBuilder
4228 class V8_EXPORT WasmModuleObjectBuilderStreaming final {
4229  public:
4230  explicit WasmModuleObjectBuilderStreaming(Isolate* isolate);
4231  /**
4232  * The buffer passed into OnBytesReceived is owned by the caller.
4233  */
4234  void OnBytesReceived(const uint8_t*, size_t size);
4235  void Finish();
4236  /**
4237  * Abort streaming compilation. If {exception} has a value, then the promise
4238  * associated with streaming compilation is rejected with that value. If
4239  * {exception} does not have value, the promise does not get rejected.
4240  */
4241  void Abort(MaybeLocal<Value> exception);
4242  Local<Promise> GetPromise();
4243 
4245 
4246  private:
4247  typedef std::pair<std::unique_ptr<const uint8_t[]>, size_t> Buffer;
4248 
4249  WasmModuleObjectBuilderStreaming(const WasmModuleObjectBuilderStreaming&) =
4250  delete;
4251  WasmModuleObjectBuilderStreaming(WasmModuleObjectBuilderStreaming&&) =
4252  default;
4253  WasmModuleObjectBuilderStreaming& operator=(
4254  const WasmModuleObjectBuilderStreaming&) = delete;
4255  WasmModuleObjectBuilderStreaming& operator=(
4256  WasmModuleObjectBuilderStreaming&&) = default;
4257  Isolate* isolate_ = nullptr;
4258 
4259 #if V8_CC_MSVC
4260  /**
4261  * We don't need the static Copy API, so the default
4262  * NonCopyablePersistentTraits would be sufficient, however,
4263  * MSVC eagerly instantiates the Copy.
4264  * We ensure we don't use Copy, however, by compiling with the
4265  * defaults everywhere else.
4266  */
4267  Persistent<Promise, CopyablePersistentTraits<Promise>> promise_;
4268 #else
4269  Persistent<Promise> promise_;
4270 #endif
4271  std::vector<Buffer> received_buffers_;
4272  size_t total_size_ = 0;
4273  std::shared_ptr<internal::wasm::StreamingDecoder> streaming_decoder_;
4274 };
4275 
4276 #ifndef V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT
4277 // The number of required internal fields can be defined by embedder.
4278 #define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 2
4279 #endif
4280 
4281 
4283 
4284 
4285 /**
4286  * An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5).
4287  */
4288 class V8_EXPORT ArrayBuffer : public Object {
4289  public:
4290  /**
4291  * A thread-safe allocator that V8 uses to allocate |ArrayBuffer|'s memory.
4292  * The allocator is a global V8 setting. It has to be set via
4293  * Isolate::CreateParams.
4294  *
4295  * Memory allocated through this allocator by V8 is accounted for as external
4296  * memory by V8. Note that V8 keeps track of the memory for all internalized
4297  * |ArrayBuffer|s. Responsibility for tracking external memory (using
4298  * Isolate::AdjustAmountOfExternalAllocatedMemory) is handed over to the
4299  * embedder upon externalization and taken over upon internalization (creating
4300  * an internalized buffer from an existing buffer).
4301  *
4302  * Note that it is unsafe to call back into V8 from any of the allocator
4303  * functions.
4304  */
4305  class V8_EXPORT Allocator { // NOLINT
4306  public:
4307  virtual ~Allocator() {}
4308 
4309  /**
4310  * Allocate |length| bytes. Return NULL if allocation is not successful.
4311  * Memory should be initialized to zeroes.
4312  */
4313  virtual void* Allocate(size_t length) = 0;
4314 
4315  /**
4316  * Allocate |length| bytes. Return NULL if allocation is not successful.
4317  * Memory does not have to be initialized.
4318  */
4319  virtual void* AllocateUninitialized(size_t length) = 0;
4320 
4321  /**
4322  * Free the memory block of size |length|, pointed to by |data|.
4323  * That memory is guaranteed to be previously allocated by |Allocate|.
4324  */
4325  virtual void Free(void* data, size_t length) = 0;
4326 
4327  /**
4328  * ArrayBuffer allocation mode. kNormal is a malloc/free style allocation,
4329  * while kReservation is for larger allocations with the ability to set
4330  * access permissions.
4331  */
4333 
4334  /**
4335  * malloc/free based convenience allocator.
4336  *
4337  * Caller takes ownership, i.e. the returned object needs to be freed using
4338  * |delete allocator| once it is no longer in use.
4339  */
4340  static Allocator* NewDefaultAllocator();
4341  };
4342 
4343  /**
4344  * The contents of an |ArrayBuffer|. Externalization of |ArrayBuffer|
4345  * returns an instance of this class, populated, with a pointer to data
4346  * and byte length.
4347  *
4348  * The Data pointer of ArrayBuffer::Contents is always allocated with
4349  * Allocator::Allocate that is set via Isolate::CreateParams.
4350  */
4351  class V8_EXPORT Contents { // NOLINT
4352  public:
4354  : data_(nullptr),
4355  byte_length_(0),
4357  allocation_length_(0),
4359 
4360  void* AllocationBase() const { return allocation_base_; }
4361  size_t AllocationLength() const { return allocation_length_; }
4362  Allocator::AllocationMode AllocationMode() const {
4363  return allocation_mode_;
4364  }
4365 
4366  void* Data() const { return data_; }
4367  size_t ByteLength() const { return byte_length_; }
4368 
4369  private:
4370  void* data_;
4371  size_t byte_length_;
4372  void* allocation_base_;
4373  size_t allocation_length_;
4374  Allocator::AllocationMode allocation_mode_;
4375 
4376  friend class ArrayBuffer;
4377  };
4378 
4379 
4380  /**
4381  * Data length in bytes.
4382  */
4383  size_t ByteLength() const;
4384 
4385  /**
4386  * Create a new ArrayBuffer. Allocate |byte_length| bytes.
4387  * Allocated memory will be owned by a created ArrayBuffer and
4388  * will be deallocated when it is garbage-collected,
4389  * unless the object is externalized.
4390  */
4391  static Local<ArrayBuffer> New(Isolate* isolate, size_t byte_length);
4392 
4393  /**
4394  * Create a new ArrayBuffer over an existing memory block.
4395  * The created array buffer is by default immediately in externalized state.
4396  * In externalized state, the memory block will not be reclaimed when a
4397  * created ArrayBuffer is garbage-collected.
4398  * In internalized state, the memory block will be released using
4399  * |Allocator::Free| once all ArrayBuffers referencing it are collected by
4400  * the garbage collector.
4401  */
4402  static Local<ArrayBuffer> New(
4403  Isolate* isolate, void* data, size_t byte_length,
4405 
4406  /**
4407  * Returns true if ArrayBuffer is externalized, that is, does not
4408  * own its memory block.
4409  */
4410  bool IsExternal() const;
4411 
4412  /**
4413  * Returns true if this ArrayBuffer may be neutered.
4414  */
4415  bool IsNeuterable() const;
4416 
4417  /**
4418  * Neuters this ArrayBuffer and all its views (typed arrays).
4419  * Neutering sets the byte length of the buffer and all typed arrays to zero,
4420  * preventing JavaScript from ever accessing underlying backing store.
4421  * ArrayBuffer should have been externalized and must be neuterable.
4422  */
4423  void Neuter();
4424 
4425  /**
4426  * Make this ArrayBuffer external. The pointer to underlying memory block
4427  * and byte length are returned as |Contents| structure. After ArrayBuffer
4428  * had been externalized, it does no longer own the memory block. The caller
4429  * should take steps to free memory when it is no longer needed.
4430  *
4431  * The memory block is guaranteed to be allocated with |Allocator::Allocate|
4432  * that has been set via Isolate::CreateParams.
4433  */
4435 
4436  /**
4437  * Get a pointer to the ArrayBuffer's underlying memory block without
4438  * externalizing it. If the ArrayBuffer is not externalized, this pointer
4439  * will become invalid as soon as the ArrayBuffer gets garbage collected.
4440  *
4441  * The embedder should make sure to hold a strong reference to the
4442  * ArrayBuffer while accessing this pointer.
4443  *
4444  * The memory block is guaranteed to be allocated with |Allocator::Allocate|.
4445  */
4447 
4448  V8_INLINE static ArrayBuffer* Cast(Value* obj);
4449 
4452 
4453  private:
4454  ArrayBuffer();
4455  static void CheckCast(Value* obj);
4456 };
4457 
4458 
4459 #ifndef V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT
4460 // The number of required internal fields can be defined by embedder.
4461 #define V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT 2
4462 #endif
4463 
4464 
4465 /**
4466  * A base class for an instance of one of "views" over ArrayBuffer,
4467  * including TypedArrays and DataView (ES6 draft 15.13).
4468  */
4470  public:
4471  /**
4472  * Returns underlying ArrayBuffer.
4473  */
4474  Local<ArrayBuffer> Buffer();
4475  /**
4476  * Byte offset in |Buffer|.
4477  */
4478  size_t ByteOffset();
4479  /**
4480  * Size of a view in bytes.
4481  */
4482  size_t ByteLength();
4483 
4484  /**
4485  * Copy the contents of the ArrayBufferView's buffer to an embedder defined
4486  * memory without additional overhead that calling ArrayBufferView::Buffer
4487  * might incur.
4488  *
4489  * Will write at most min(|byte_length|, ByteLength) bytes starting at
4490  * ByteOffset of the underlying buffer to the memory starting at |dest|.
4491  * Returns the number of bytes actually written.
4492  */
4494 
4495  /**
4496  * Returns true if ArrayBufferView's backing ArrayBuffer has already been
4497  * allocated.
4498  */
4499  bool HasBuffer() const;
4500 
4501  V8_INLINE static ArrayBufferView* Cast(Value* obj);
4502 
4503  static const int kInternalFieldCount =
4505  static const int kEmbedderFieldCount =
4507 
4508  private:
4509  ArrayBufferView();
4510  static void CheckCast(Value* obj);
4511 };
4512 
4513 
4514 /**
4515  * A base class for an instance of TypedArray series of constructors
4516  * (ES6 draft 15.13.6).
4517  */
4519  public:
4520  /*
4521  * The largest typed array size that can be constructed using New.
4522  */
4523  static constexpr size_t kMaxLength =
4524  sizeof(void*) == 4 ? (1u << 30) - 1 : (1u << 31) - 1;
4525 
4526  /**
4527  * Number of elements in this typed array
4528  * (e.g. for Int16Array, |ByteLength|/2).
4529  */
4530  size_t Length();
4531 
4532  V8_INLINE static TypedArray* Cast(Value* obj);
4533 
4534  private:
4535  TypedArray();
4536  static void CheckCast(Value* obj);
4537 };
4538 
4539 
4540 /**
4541  * An instance of Uint8Array constructor (ES6 draft 15.13.6).
4542  */
4544  public:
4545  static Local<Uint8Array> New(Local<ArrayBuffer> array_buffer,
4546  size_t byte_offset, size_t length);
4547  static Local<Uint8Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4548  size_t byte_offset, size_t length);
4549  V8_INLINE static Uint8Array* Cast(Value* obj);
4550 
4551  private:
4552  Uint8Array();
4553  static void CheckCast(Value* obj);
4554 };
4555 
4556 
4557 /**
4558  * An instance of Uint8ClampedArray constructor (ES6 draft 15.13.6).
4559  */
4561  public:
4562  static Local<Uint8ClampedArray> New(Local<ArrayBuffer> array_buffer,
4563  size_t byte_offset, size_t length);
4564  static Local<Uint8ClampedArray> New(
4565  Local<SharedArrayBuffer> shared_array_buffer, size_t byte_offset,
4566  size_t length);
4567  V8_INLINE static Uint8ClampedArray* Cast(Value* obj);
4568 
4569  private:
4570  Uint8ClampedArray();
4571  static void CheckCast(Value* obj);
4572 };
4573 
4574 /**
4575  * An instance of Int8Array constructor (ES6 draft 15.13.6).
4576  */
4578  public:
4579  static Local<Int8Array> New(Local<ArrayBuffer> array_buffer,
4580  size_t byte_offset, size_t length);
4581  static Local<Int8Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4582  size_t byte_offset, size_t length);
4583  V8_INLINE static Int8Array* Cast(Value* obj);
4584 
4585  private:
4586  Int8Array();
4587  static void CheckCast(Value* obj);
4588 };
4589 
4590 
4591 /**
4592  * An instance of Uint16Array constructor (ES6 draft 15.13.6).
4593  */
4595  public:
4596  static Local<Uint16Array> New(Local<ArrayBuffer> array_buffer,
4597  size_t byte_offset, size_t length);
4598  static Local<Uint16Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4599  size_t byte_offset, size_t length);
4600  V8_INLINE static Uint16Array* Cast(Value* obj);
4601 
4602  private:
4603  Uint16Array();
4604  static void CheckCast(Value* obj);
4605 };
4606 
4607 
4608 /**
4609  * An instance of Int16Array constructor (ES6 draft 15.13.6).
4610  */
4612  public:
4613  static Local<Int16Array> New(Local<ArrayBuffer> array_buffer,
4614  size_t byte_offset, size_t length);
4615  static Local<Int16Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4616  size_t byte_offset, size_t length);
4617  V8_INLINE static Int16Array* Cast(Value* obj);
4618 
4619  private:
4620  Int16Array();
4621  static void CheckCast(Value* obj);
4622 };
4623 
4624 
4625 /**
4626  * An instance of Uint32Array constructor (ES6 draft 15.13.6).
4627  */
4629  public:
4630  static Local<Uint32Array> New(Local<ArrayBuffer> array_buffer,
4631  size_t byte_offset, size_t length);
4632  static Local<Uint32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4633  size_t byte_offset, size_t length);
4634  V8_INLINE static Uint32Array* Cast(Value* obj);
4635 
4636  private:
4637  Uint32Array();
4638  static void CheckCast(Value* obj);
4639 };
4640 
4641 
4642 /**
4643  * An instance of Int32Array constructor (ES6 draft 15.13.6).
4644  */
4646  public:
4647  static Local<Int32Array> New(Local<ArrayBuffer> array_buffer,
4648  size_t byte_offset, size_t length);
4649  static Local<Int32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4650  size_t byte_offset, size_t length);
4651  V8_INLINE static Int32Array* Cast(Value* obj);
4652 
4653  private:
4654  Int32Array();
4655  static void CheckCast(Value* obj);
4656 };
4657 
4658 
4659 /**
4660  * An instance of Float32Array constructor (ES6 draft 15.13.6).
4661  */
4663  public:
4664  static Local<Float32Array> New(Local<ArrayBuffer> array_buffer,
4665  size_t byte_offset, size_t length);
4666  static Local<Float32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4667  size_t byte_offset, size_t length);
4668  V8_INLINE static Float32Array* Cast(Value* obj);
4669 
4670  private:
4671  Float32Array();
4672  static void CheckCast(Value* obj);
4673 };
4674 
4675 
4676 /**
4677  * An instance of Float64Array constructor (ES6 draft 15.13.6).
4678  */
4680  public:
4681  static Local<Float64Array> New(Local<ArrayBuffer> array_buffer,
4682  size_t byte_offset, size_t length);
4683  static Local<Float64Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4684  size_t byte_offset, size_t length);
4685  V8_INLINE static Float64Array* Cast(Value* obj);
4686 
4687  private:
4688  Float64Array();
4689  static void CheckCast(Value* obj);
4690 };
4691 
4692 /**
4693  * An instance of BigInt64Array constructor.
4694  */
4696  public:
4697  static Local<BigInt64Array> New(Local<ArrayBuffer> array_buffer,
4698  size_t byte_offset, size_t length);
4699  static Local<BigInt64Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4700  size_t byte_offset, size_t length);
4701  V8_INLINE static BigInt64Array* Cast(Value* obj);
4702 
4703  private:
4704  BigInt64Array();
4705  static void CheckCast(Value* obj);
4706 };
4707 
4708 /**
4709  * An instance of BigUint64Array constructor.
4710  */
4712  public:
4713  static Local<BigUint64Array> New(Local<ArrayBuffer> array_buffer,
4714  size_t byte_offset, size_t length);
4715  static Local<BigUint64Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4716  size_t byte_offset, size_t length);
4717  V8_INLINE static BigUint64Array* Cast(Value* obj);
4718 
4719  private:
4720  BigUint64Array();
4721  static void CheckCast(Value* obj);
4722 };
4723 
4724 /**
4725  * An instance of DataView constructor (ES6 draft 15.13.7).
4726  */
4728  public:
4729  static Local<DataView> New(Local<ArrayBuffer> array_buffer,
4730  size_t byte_offset, size_t length);
4731  static Local<DataView> New(Local<SharedArrayBuffer> shared_array_buffer,
4732  size_t byte_offset, size_t length);
4733  V8_INLINE static DataView* Cast(Value* obj);
4734 
4735  private:
4736  DataView();
4737  static void CheckCast(Value* obj);
4738 };
4739 
4740 
4741 /**
4742  * An instance of the built-in SharedArrayBuffer constructor.
4743  * This API is experimental and may change significantly.
4744  */
4746  public:
4747  /**
4748  * The contents of an |SharedArrayBuffer|. Externalization of
4749  * |SharedArrayBuffer| returns an instance of this class, populated, with a
4750  * pointer to data and byte length.
4751  *
4752  * The Data pointer of SharedArrayBuffer::Contents is always allocated with
4753  * |ArrayBuffer::Allocator::Allocate| by the allocator specified in
4754  * v8::Isolate::CreateParams::array_buffer_allocator.
4755  *
4756  * This API is experimental and may change significantly.
4757  */
4758  class V8_EXPORT Contents { // NOLINT
4759  public:
4761  : data_(nullptr),
4762  byte_length_(0),
4764  allocation_length_(0),
4766 
4767  void* AllocationBase() const { return allocation_base_; }
4768  size_t AllocationLength() const { return allocation_length_; }
4769  ArrayBuffer::Allocator::AllocationMode AllocationMode() const {
4770  return allocation_mode_;
4771  }
4772 
4773  void* Data() const { return data_; }
4774  size_t ByteLength() const { return byte_length_; }
4775 
4776  private:
4777  void* data_;
4778  size_t byte_length_;
4779  void* allocation_base_;
4780  size_t allocation_length_;
4781  ArrayBuffer::Allocator::AllocationMode allocation_mode_;
4782 
4783  friend class SharedArrayBuffer;
4784  };
4785 
4786 
4787  /**
4788  * Data length in bytes.
4789  */
4790  size_t ByteLength() const;
4791 
4792  /**
4793  * Create a new SharedArrayBuffer. Allocate |byte_length| bytes.
4794  * Allocated memory will be owned by a created SharedArrayBuffer and
4795  * will be deallocated when it is garbage-collected,
4796  * unless the object is externalized.
4797  */
4798  static Local<SharedArrayBuffer> New(Isolate* isolate, size_t byte_length);
4799 
4800  /**
4801  * Create a new SharedArrayBuffer over an existing memory block. The created
4802  * array buffer is immediately in externalized state unless otherwise
4803  * specified. The memory block will not be reclaimed when a created
4804  * SharedArrayBuffer is garbage-collected.
4805  */
4806  static Local<SharedArrayBuffer> New(
4807  Isolate* isolate, void* data, size_t byte_length,
4809 
4810  /**
4811  * Returns true if SharedArrayBuffer is externalized, that is, does not
4812  * own its memory block.
4813  */
4814  bool IsExternal() const;
4815 
4816  /**
4817  * Make this SharedArrayBuffer external. The pointer to underlying memory
4818  * block and byte length are returned as |Contents| structure. After
4819  * SharedArrayBuffer had been externalized, it does no longer own the memory
4820  * block. The caller should take steps to free memory when it is no longer
4821  * needed.
4822  *
4823  * The memory block is guaranteed to be allocated with |Allocator::Allocate|
4824  * by the allocator specified in
4825  * v8::Isolate::CreateParams::array_buffer_allocator.
4826  *
4827  */
4829 
4830  /**
4831  * Get a pointer to the ArrayBuffer's underlying memory block without
4832  * externalizing it. If the ArrayBuffer is not externalized, this pointer
4833  * will become invalid as soon as the ArrayBuffer became garbage collected.
4834  *
4835  * The embedder should make sure to hold a strong reference to the
4836  * ArrayBuffer while accessing this pointer.
4837  *
4838  * The memory block is guaranteed to be allocated with |Allocator::Allocate|
4839  * by the allocator specified in
4840  * v8::Isolate::CreateParams::array_buffer_allocator.
4841  */
4843 
4844  V8_INLINE static SharedArrayBuffer* Cast(Value* obj);
4845 
4847 
4848  private:
4849  SharedArrayBuffer();
4850  static void CheckCast(Value* obj);
4851 };
4852 
4853 
4854 /**
4855  * An instance of the built-in Date constructor (ECMA-262, 15.9).
4856  */
4857 class V8_EXPORT Date : public Object {
4858  public:
4859  static V8_DEPRECATE_SOON("Use maybe version.",
4860  Local<Value> New(Isolate* isolate, double time));
4861  static V8_WARN_UNUSED_RESULT MaybeLocal<Value> New(Local<Context> context,
4862  double time);
4863 
4864  /**
4865  * A specialization of Value::NumberValue that is more efficient
4866  * because we know the structure of this object.
4867  */
4868  double ValueOf() const;
4869 
4870  V8_INLINE static Date* Cast(Value* obj);
4871 
4872  /**
4873  * Notification that the embedder has changed the time zone,
4874  * daylight savings time, or other date / time configuration
4875  * parameters. V8 keeps a cache of various values used for
4876  * date / time computation. This notification will reset
4877  * those cached values for the current context so that date /
4878  * time configuration changes would be reflected in the Date
4879  * object.
4880  *
4881  * This API should not be called more than needed as it will
4882  * negatively impact the performance of date operations.
4883  */
4884  static void DateTimeConfigurationChangeNotification(Isolate* isolate);
4885 
4886  private:
4887  static void CheckCast(Value* obj);
4888 };
4889 
4890 
4891 /**
4892  * A Number object (ECMA-262, 4.3.21).
4893  */
4895  public:
4896  static Local<Value> New(Isolate* isolate, double value);
4897 
4898  double ValueOf() const;
4899 
4900  V8_INLINE static NumberObject* Cast(Value* obj);
4901 
4902  private:
4903  static void CheckCast(Value* obj);
4904 };
4905 
4906 /**
4907  * A BigInt object (https://tc39.github.io/proposal-bigint)
4908  */
4910  public:
4911  static Local<Value> New(Isolate* isolate, int64_t value);
4912 
4913  Local<BigInt> ValueOf() const;
4914 
4915  V8_INLINE static BigIntObject* Cast(Value* obj);
4916 
4917  private:
4918  static void CheckCast(Value* obj);
4919 };
4920 
4921 /**
4922  * A Boolean object (ECMA-262, 4.3.15).
4923  */
4925  public:
4926  static Local<Value> New(Isolate* isolate, bool value);
4927 
4928  bool ValueOf() const;
4929 
4930  V8_INLINE static BooleanObject* Cast(Value* obj);
4931 
4932  private:
4933  static void CheckCast(Value* obj);
4934 };
4935 
4936 
4937 /**
4938  * A String object (ECMA-262, 4.3.18).
4939  */
4941  public:
4942  static Local<Value> New(Local<String> value);
4943 
4944  Local<String> ValueOf() const;
4945 
4946  V8_INLINE static StringObject* Cast(Value* obj);
4947 
4948  private:
4949  static void CheckCast(Value* obj);
4950 };
4951 
4952 
4953 /**
4954  * A Symbol object (ECMA-262 edition 6).
4955  */
4957  public:
4958  static Local<Value> New(Isolate* isolate, Local<Symbol> value);
4959 
4960  Local<Symbol> ValueOf() const;
4961 
4962  V8_INLINE static SymbolObject* Cast(Value* obj);
4963 
4964  private:
4965  static void CheckCast(Value* obj);
4966 };
4967 
4968 
4969 /**
4970  * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
4971  */
4972 class V8_EXPORT RegExp : public Object {
4973  public:
4974  /**
4975  * Regular expression flag bits. They can be or'ed to enable a set
4976  * of flags.
4977  */
4978  enum Flags {
4979  kNone = 0,
4980  kGlobal = 1 << 0,
4981  kIgnoreCase = 1 << 1,
4982  kMultiline = 1 << 2,
4983  kSticky = 1 << 3,
4984  kUnicode = 1 << 4,
4985  kDotAll = 1 << 5,
4986  };
4987 
4988  /**
4989  * Creates a regular expression from the given pattern string and
4990  * the flags bit field. May throw a JavaScript exception as
4991  * described in ECMA-262, 15.10.4.1.
4992  *
4993  * For example,
4994  * RegExp::New(v8::String::New("foo"),
4995  * static_cast<RegExp::Flags>(kGlobal | kMultiline))
4996  * is equivalent to evaluating "/foo/gm".
4997  */
4998  static V8_DEPRECATED("Use maybe version",
4999  Local<RegExp> New(Local<String> pattern, Flags flags));
5000  static V8_WARN_UNUSED_RESULT MaybeLocal<RegExp> New(Local<Context> context,
5001  Local<String> pattern,
5002  Flags flags);
5003 
5004  /**
5005  * Returns the value of the source property: a string representing
5006  * the regular expression.
5007  */
5008  Local<String> GetSource() const;
5009 
5010  /**
5011  * Returns the flags bit field.
5012  */
5013  Flags GetFlags() const;
5014 
5015  V8_INLINE static RegExp* Cast(Value* obj);
5016 
5017  private:
5018  static void CheckCast(Value* obj);
5019 };
5020 
5021 
5022 /**
5023  * A JavaScript value that wraps a C++ void*. This type of value is mainly used
5024  * to associate C++ data structures with JavaScript objects.
5025  */
5026 class V8_EXPORT External : public Value {
5027  public:
5028  static Local<External> New(Isolate* isolate, void* value);
5029  V8_INLINE static External* Cast(Value* obj);
5030  void* Value() const;
5031  private:
5032  static void CheckCast(v8::Value* obj);
5033 };
5034 
5035 #define V8_INTRINSICS_LIST(F)
5036  F(ArrayProto_entries, array_entries_iterator)
5037  F(ArrayProto_forEach, array_for_each_iterator)
5038  F(ArrayProto_keys, array_keys_iterator)
5039  F(ArrayProto_values, array_values_iterator)
5040  F(ErrorPrototype, initial_error_prototype)
5041  F(IteratorPrototype, initial_iterator_prototype)
5042 
5044 #define V8_DECL_INTRINSIC(name, iname) k##name,
5046 #undef V8_DECL_INTRINSIC
5047 };
5048 
5049 
5050 // --- Templates ---
5051 
5052 
5053 /**
5054  * The superclass of object and function templates.
5055  */
5056 class V8_EXPORT Template : public Data {
5057  public:
5058  /**
5059  * Adds a property to each instance created by this template.
5060  *
5061  * The property must be defined either as a primitive value, or a template.
5062  */
5063  void Set(Local<Name> name, Local<Data> value,
5064  PropertyAttribute attributes = None);
5065  void SetPrivate(Local<Private> name, Local<Data> value,
5066  PropertyAttribute attributes = None);
5067  V8_INLINE void Set(Isolate* isolate, const char* name, Local<Data> value);
5068 
5069  void SetAccessorProperty(
5070  Local<Name> name,
5071  Local<FunctionTemplate> getter = Local<FunctionTemplate>(),
5072  Local<FunctionTemplate> setter = Local<FunctionTemplate>(),
5073  PropertyAttribute attribute = None,
5074  AccessControl settings = DEFAULT);
5075 
5076  /**
5077  * Whenever the property with the given name is accessed on objects
5078  * created from this Template the getter and setter callbacks
5079  * are called instead of getting and setting the property directly
5080  * on the JavaScript object.
5081  *
5082  * \param name The name of the property for which an accessor is added.
5083  * \param getter The callback to invoke when getting the property.
5084  * \param setter The callback to invoke when setting the property.
5085  * \param data A piece of data that will be passed to the getter and setter
5086  * callbacks whenever they are invoked.
5087  * \param settings Access control settings for the accessor. This is a bit
5088  * field consisting of one of more of
5089  * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
5090  * The default is to not allow cross-context access.
5091  * ALL_CAN_READ means that all cross-context reads are allowed.
5092  * ALL_CAN_WRITE means that all cross-context writes are allowed.
5093  * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
5094  * cross-context access.
5095  * \param attribute The attributes of the property for which an accessor
5096  * is added.
5097  * \param signature The signature describes valid receivers for the accessor
5098  * and is used to perform implicit instance checks against them. If the
5099  * receiver is incompatible (i.e. is not an instance of the constructor as
5100  * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
5101  * thrown and no callback is invoked.
5102  */
5103  void SetNativeDataProperty(
5104  Local<String> name,