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