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