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