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