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