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