v8  8.1.307(node14.1.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 #include <memory>
22 #include <string>
23 #include <type_traits>
24 #include <utility>
25 #include <vector>
26 
27 #include "v8-internal.h" // NOLINT(build/include)
28 #include "v8-version.h" // NOLINT(build/include)
29 #include "v8config.h" // NOLINT(build/include)
30 
31 // We reserve the V8_* prefix for macros defined in V8 public API and
32 // assume there are no name conflicts with the embedder's code.
33 
34 /**
35  * The v8 JavaScript engine.
36  */
37 namespace v8 {
38 
39 class AccessorSignature;
40 class Array;
41 class ArrayBuffer;
42 class BigInt;
43 class BigIntObject;
44 class Boolean;
45 class BooleanObject;
46 class Context;
47 class Data;
48 class Date;
49 class External;
50 class Function;
51 class FunctionTemplate;
52 class HeapProfiler;
53 class ImplementationUtilities;
54 class Int32;
55 class Integer;
56 class Isolate;
57 template <class T>
58 class Maybe;
59 class MicrotaskQueue;
60 class Name;
61 class Number;
62 class NumberObject;
63 class Object;
64 class ObjectOperationDescriptor;
65 class ObjectTemplate;
66 class Platform;
67 class Primitive;
68 class Promise;
69 class PropertyDescriptor;
70 class Proxy;
71 class RawOperationDescriptor;
72 class Script;
73 class SharedArrayBuffer;
74 class Signature;
75 class StartupData;
76 class StackFrame;
77 class StackTrace;
78 class String;
79 class StringObject;
80 class Symbol;
81 class SymbolObject;
82 class PrimitiveArray;
83 class Private;
84 class Uint32;
85 class Utils;
86 class Value;
87 class WasmModuleObject;
88 template <class T> class Local;
89 template <class T>
90 class MaybeLocal;
91 template <class T> class Eternal;
92 template<class T> class NonCopyablePersistentTraits;
93 template<class T> class PersistentBase;
94 template <class T, class M = NonCopyablePersistentTraits<T> >
95 class Persistent;
96 template <class T>
97 class Global;
98 template <class T>
100 template <class T>
102 template <class T>
104 template<class K, class V, class T> class PersistentValueMap;
105 template <class K, class V, class T>
107 template <class K, class V, class T>
108 class GlobalValueMap;
109 template<class V, class T> class PersistentValueVector;
110 template<class T, class P> class WeakCallbackObject;
111 class FunctionTemplate;
112 class ObjectTemplate;
113 template<typename T> class FunctionCallbackInfo;
114 template<typename T> class PropertyCallbackInfo;
115 class StackTrace;
116 class StackFrame;
117 class Isolate;
118 class CallHandlerHelper;
120 template<typename T> class ReturnValue;
121 
122 namespace internal {
123 class Arguments;
124 class DeferredHandles;
125 class Heap;
126 class HeapObject;
127 class ExternalString;
128 class Isolate;
129 class LocalEmbedderHeapTracer;
130 class MicrotaskQueue;
131 struct ScriptStreamingData;
132 template<typename T> class CustomArguments;
133 class PropertyCallbackArguments;
134 class FunctionCallbackArguments;
135 class GlobalHandles;
136 class ScopedExternalStringLock;
137 class ThreadLocalTop;
138 
139 namespace wasm {
140 class NativeModule;
141 class StreamingDecoder;
142 } // namespace wasm
143 
144 } // namespace internal
145 
146 namespace debug {
147 class ConsoleCallArguments;
148 } // namespace debug
149 
150 // --- Handles ---
151 
152 #define TYPE_CHECK(T, S)
153  while (false) {
154  *(static_cast<T* volatile*>(0)) = static_cast<S*>(0);
155  }
156 
157 /**
158  * An object reference managed by the v8 garbage collector.
159  *
160  * All objects returned from v8 have to be tracked by the garbage
161  * collector so that it knows that the objects are still alive. Also,
162  * because the garbage collector may move objects, it is unsafe to
163  * point directly to an object. Instead, all objects are stored in
164  * handles which are known by the garbage collector and updated
165  * whenever an object moves. Handles should always be passed by value
166  * (except in cases like out-parameters) and they should never be
167  * allocated on the heap.
168  *
169  * There are two types of handles: local and persistent handles.
170  *
171  * Local handles are light-weight and transient and typically used in
172  * local operations. They are managed by HandleScopes. That means that a
173  * HandleScope must exist on the stack when they are created and that they are
174  * only valid inside of the HandleScope active during their creation.
175  * For passing a local handle to an outer HandleScope, an EscapableHandleScope
176  * and its Escape() method must be used.
177  *
178  * Persistent handles can be used when storing objects across several
179  * independent operations and have to be explicitly deallocated when they're no
180  * longer used.
181  *
182  * It is safe to extract the object stored in the handle by
183  * dereferencing the handle (for instance, to extract the Object* from
184  * a Local<Object>); the value will still be governed by a handle
185  * behind the scenes and the same rules apply to these values as to
186  * their handles.
187  */
188 template <class T>
189 class Local {
190  public:
191  V8_INLINE Local() : val_(nullptr) {}
192  template <class S>
194  : val_(reinterpret_cast<T*>(*that)) {
195  /**
196  * This check fails when trying to convert between incompatible
197  * handles. For example, converting from a Local<String> to a
198  * Local<Number>.
199  */
200  TYPE_CHECK(T, S);
201  }
202 
203  /**
204  * Returns true if the handle is empty.
205  */
206  V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
207 
208  /**
209  * Sets the handle to be empty. IsEmpty() will then return true.
210  */
211  V8_INLINE void Clear() { val_ = nullptr; }
212 
213  V8_INLINE T* operator->() const { return val_; }
214 
215  V8_INLINE T* operator*() const { return val_; }
216 
217  /**
218  * Checks whether two handles are the same.
219  * Returns true if both are empty, or if the objects to which they refer
220  * are identical.
221  *
222  * If both handles refer to JS objects, this is the same as strict equality.
223  * For primitives, such as numbers or strings, a `false` return value does not
224  * indicate that the values aren't equal in the JavaScript sense.
225  * Use `Value::StrictEquals()` to check primitives for equality.
226  */
227  template <class S>
228  V8_INLINE bool operator==(const Local<S>& that) const {
229  internal::Address* a = reinterpret_cast<internal::Address*>(this->val_);
230  internal::Address* b = reinterpret_cast<internal::Address*>(that.val_);
231  if (a == nullptr) return b == nullptr;
232  if (b == nullptr) return false;
233  return *a == *b;
234  }
235 
236  template <class S> V8_INLINE bool operator==(
237  const PersistentBase<S>& that) const {
238  internal::Address* a = reinterpret_cast<internal::Address*>(this->val_);
239  internal::Address* b = reinterpret_cast<internal::Address*>(that.val_);
240  if (a == nullptr) return b == nullptr;
241  if (b == nullptr) return false;
242  return *a == *b;
243  }
244 
245  /**
246  * Checks whether two handles are different.
247  * Returns true if only one of the handles is empty, or if
248  * the objects to which they refer are different.
249  *
250  * If both handles refer to JS objects, this is the same as strict
251  * non-equality. For primitives, such as numbers or strings, a `true` return
252  * value does not indicate that the values aren't equal in the JavaScript
253  * sense. Use `Value::StrictEquals()` to check primitives for equality.
254  */
255  template <class S>
256  V8_INLINE bool operator!=(const Local<S>& that) const {
257  return !operator==(that);
258  }
259 
260  template <class S> V8_INLINE bool operator!=(
261  const Persistent<S>& that) const {
262  return !operator==(that);
263  }
264 
265  /**
266  * Cast a handle to a subclass, e.g. Local<Value> to Local<Object>.
267  * This is only valid if the handle actually refers to a value of the
268  * target type.
269  */
270  template <class S> V8_INLINE static Local<T> Cast(Local<S> that) {
271 #ifdef V8_ENABLE_CHECKS
272  // If we're going to perform the type check then we have to check
273  // that the handle isn't empty before doing the checked cast.
274  if (that.IsEmpty()) return Local<T>();
275 #endif
276  return Local<T>(T::Cast(*that));
277  }
278 
279  /**
280  * Calling this is equivalent to Local<S>::Cast().
281  * In particular, this is only valid if the handle actually refers to a value
282  * of the target type.
283  */
284  template <class S>
285  V8_INLINE Local<S> As() const {
286  return Local<S>::Cast(*this);
287  }
288 
289  /**
290  * Create a local handle for the content of another handle.
291  * The referee is kept alive by the local handle even when
292  * the original handle is destroyed/disposed.
293  */
294  V8_INLINE static Local<T> New(Isolate* isolate, Local<T> that);
295  V8_INLINE static Local<T> New(Isolate* isolate,
296  const PersistentBase<T>& that);
297  V8_INLINE static Local<T> New(Isolate* isolate,
298  const TracedReferenceBase<T>& that);
299 
300  private:
301  friend class Utils;
302  template<class F> friend class Eternal;
303  template<class F> friend class PersistentBase;
304  template<class F, class M> friend class Persistent;
305  template<class F> friend class Local;
306  template <class F>
307  friend class MaybeLocal;
308  template<class F> friend class FunctionCallbackInfo;
309  template<class F> friend class PropertyCallbackInfo;
310  friend class String;
311  friend class Object;
312  friend class Context;
313  friend class Isolate;
314  friend class Private;
315  template<class F> friend class internal::CustomArguments;
316  friend Local<Primitive> Undefined(Isolate* isolate);
317  friend Local<Primitive> Null(Isolate* isolate);
318  friend Local<Boolean> True(Isolate* isolate);
319  friend Local<Boolean> False(Isolate* isolate);
320  friend class HandleScope;
321  friend class EscapableHandleScope;
322  template <class F1, class F2, class F3>
324  template<class F1, class F2> friend class PersistentValueVector;
325  template <class F>
326  friend class ReturnValue;
327  template <class F>
328  friend class Traced;
329  template <class F>
330  friend class TracedGlobal;
331  template <class F>
332  friend class TracedReferenceBase;
333  template <class F>
334  friend class TracedReference;
335 
336  explicit V8_INLINE Local(T* that) : val_(that) {}
337  V8_INLINE static Local<T> New(Isolate* isolate, T* that);
338  T* val_;
339 };
340 
341 
342 #if !defined(V8_IMMINENT_DEPRECATION_WARNINGS)
343 // Handle is an alias for Local for historical reasons.
344 template <class T>
345 using Handle = Local<T>;
346 #endif
347 
348 
349 /**
350  * A MaybeLocal<> is a wrapper around Local<> that enforces a check whether
351  * the Local<> is empty before it can be used.
352  *
353  * If an API method returns a MaybeLocal<>, the API method can potentially fail
354  * either because an exception is thrown, or because an exception is pending,
355  * e.g. because a previous API call threw an exception that hasn't been caught
356  * yet, or because a TerminateExecution exception was thrown. In that case, an
357  * empty MaybeLocal is returned.
358  */
359 template <class T>
360 class MaybeLocal {
361  public:
362  V8_INLINE MaybeLocal() : val_(nullptr) {}
363  template <class S>
365  : val_(reinterpret_cast<T*>(*that)) {
366  TYPE_CHECK(T, S);
367  }
368 
369  V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
370 
371  /**
372  * Converts this MaybeLocal<> to a Local<>. If this MaybeLocal<> is empty,
373  * |false| is returned and |out| is left untouched.
374  */
375  template <class S>
377  out->val_ = IsEmpty() ? nullptr : this->val_;
378  return !IsEmpty();
379  }
380 
381  /**
382  * Converts this MaybeLocal<> to a Local<>. If this MaybeLocal<> is empty,
383  * V8 will crash the process.
384  */
386 
387  /**
388  * Converts this MaybeLocal<> to a Local<>, using a default value if this
389  * MaybeLocal<> is empty.
390  */
391  template <class S>
392  V8_INLINE Local<S> FromMaybe(Local<S> default_value) const {
393  return IsEmpty() ? default_value : Local<S>(val_);
394  }
395 
396  private:
397  T* val_;
398 };
399 
400 /**
401  * Eternal handles are set-once handles that live for the lifetime of the
402  * isolate.
403  */
404 template <class T> class Eternal {
405  public:
406  V8_INLINE Eternal() : val_(nullptr) {}
407  template <class S>
408  V8_INLINE Eternal(Isolate* isolate, Local<S> handle) : val_(nullptr) {
409  Set(isolate, handle);
410  }
411  // Can only be safely called if already set.
412  V8_INLINE Local<T> Get(Isolate* isolate) const;
413  V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
414  template<class S> V8_INLINE void Set(Isolate* isolate, Local<S> handle);
415 
416  private:
417  T* val_;
418 };
419 
420 
421 static const int kInternalFieldsInWeakCallback = 2;
422 static const int kEmbedderFieldsInWeakCallback = 2;
423 
424 template <typename T>
426  public:
427  typedef void (*Callback)(const WeakCallbackInfo<T>& data);
428 
429  WeakCallbackInfo(Isolate* isolate, T* parameter,
430  void* embedder_fields[kEmbedderFieldsInWeakCallback],
431  Callback* callback)
432  : isolate_(isolate), parameter_(parameter), callback_(callback) {
433  for (int i = 0; i < kEmbedderFieldsInWeakCallback; ++i) {
434  embedder_fields_[i] = embedder_fields[i];
435  }
436  }
437 
438  V8_INLINE Isolate* GetIsolate() const { return isolate_; }
439  V8_INLINE T* GetParameter() const { return parameter_; }
440  V8_INLINE void* GetInternalField(int index) const;
441 
442  // When first called, the embedder MUST Reset() the Global which triggered the
443  // callback. The Global itself is unusable for anything else. No v8 other api
444  // calls may be called in the first callback. Should additional work be
445  // required, the embedder must set a second pass callback, which will be
446  // called after all the initial callbacks are processed.
447  // Calling SetSecondPassCallback on the second pass will immediately crash.
448  void SetSecondPassCallback(Callback callback) const { *callback_ = callback; }
449 
450  private:
451  Isolate* isolate_;
452  T* parameter_;
453  Callback* callback_;
454  void* embedder_fields_[kEmbedderFieldsInWeakCallback];
455 };
456 
457 
458 // kParameter will pass a void* parameter back to the callback, kInternalFields
459 // will pass the first two internal fields back to the callback, kFinalizer
460 // will pass a void* parameter back, but is invoked before the object is
461 // actually collected, so it can be resurrected. In the last case, it is not
462 // possible to request a second pass callback.
464 
465 /**
466  * An object reference that is independent of any handle scope. Where
467  * a Local handle only lives as long as the HandleScope in which it was
468  * allocated, a PersistentBase handle remains valid until it is explicitly
469  * disposed using Reset().
470  *
471  * A persistent handle contains a reference to a storage cell within
472  * the V8 engine which holds an object value and which is updated by
473  * the garbage collector whenever the object is moved. A new storage
474  * cell can be created using the constructor or PersistentBase::Reset and
475  * existing handles can be disposed using PersistentBase::Reset.
476  *
477  */
478 template <class T> class PersistentBase {
479  public:
480  /**
481  * If non-empty, destroy the underlying storage cell
482  * IsEmpty() will return true after this call.
483  */
484  V8_INLINE void Reset();
485  /**
486  * If non-empty, destroy the underlying storage cell
487  * and create a new one with the contents of other if other is non empty
488  */
489  template <class S>
490  V8_INLINE void Reset(Isolate* isolate, const Local<S>& other);
491 
492  /**
493  * If non-empty, destroy the underlying storage cell
494  * and create a new one with the contents of other if other is non empty
495  */
496  template <class S>
497  V8_INLINE void Reset(Isolate* isolate, const PersistentBase<S>& other);
498 
499  V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
500  V8_INLINE void Empty() { val_ = 0; }
501 
502  V8_INLINE Local<T> Get(Isolate* isolate) const {
503  return Local<T>::New(isolate, *this);
504  }
505 
506  template <class S>
507  V8_INLINE bool operator==(const PersistentBase<S>& that) const {
508  internal::Address* a = reinterpret_cast<internal::Address*>(this->val_);
509  internal::Address* b = reinterpret_cast<internal::Address*>(that.val_);
510  if (a == nullptr) return b == nullptr;
511  if (b == nullptr) return false;
512  return *a == *b;
513  }
514 
515  template <class S>
516  V8_INLINE bool operator==(const Local<S>& that) const {
517  internal::Address* a = reinterpret_cast<internal::Address*>(this->val_);
518  internal::Address* b = reinterpret_cast<internal::Address*>(that.val_);
519  if (a == nullptr) return b == nullptr;
520  if (b == nullptr) return false;
521  return *a == *b;
522  }
523 
524  template <class S>
525  V8_INLINE bool operator!=(const PersistentBase<S>& that) const {
526  return !operator==(that);
527  }
528 
529  template <class S>
530  V8_INLINE bool operator!=(const Local<S>& that) const {
531  return !operator==(that);
532  }
533 
534  /**
535  * Install a finalization callback on this object.
536  * NOTE: There is no guarantee as to *when* or even *if* the callback is
537  * invoked. The invocation is performed solely on a best effort basis.
538  * As always, GC-based finalization should *not* be relied upon for any
539  * critical form of resource management!
540  */
541  template <typename P>
542  V8_INLINE void SetWeak(P* parameter,
543  typename WeakCallbackInfo<P>::Callback callback,
544  WeakCallbackType type);
545 
546  /**
547  * Turns this handle into a weak phantom handle without finalization callback.
548  * The handle will be reset automatically when the garbage collector detects
549  * that the object is no longer reachable.
550  * A related function Isolate::NumberOfPhantomHandleResetsSinceLastCall
551  * returns how many phantom handles were reset by the garbage collector.
552  */
553  V8_INLINE void SetWeak();
554 
555  template<typename P>
556  V8_INLINE P* ClearWeak();
557 
558  // TODO(dcarney): remove this.
559  V8_INLINE void ClearWeak() { ClearWeak<void>(); }
560 
561  /**
562  * Annotates the strong handle with the given label, which is then used by the
563  * heap snapshot generator as a name of the edge from the root to the handle.
564  * The function does not take ownership of the label and assumes that the
565  * label is valid as long as the handle is valid.
566  */
567  V8_INLINE void AnnotateStrongRetainer(const char* label);
568 
569  /** Returns true if the handle's reference is weak. */
570  V8_INLINE bool IsWeak() const;
571 
572  /**
573  * Assigns a wrapper class ID to the handle.
574  */
575  V8_INLINE void SetWrapperClassId(uint16_t class_id);
576 
577  /**
578  * Returns the class ID previously assigned to this handle or 0 if no class ID
579  * was previously assigned.
580  */
581  V8_INLINE uint16_t WrapperClassId() const;
582 
583  PersistentBase(const PersistentBase& other) = delete; // NOLINT
584  void operator=(const PersistentBase&) = delete;
585 
586  private:
587  friend class Isolate;
588  friend class Utils;
589  template<class F> friend class Local;
590  template<class F1, class F2> friend class Persistent;
591  template <class F>
592  friend class Global;
593  template<class F> friend class PersistentBase;
594  template<class F> friend class ReturnValue;
595  template <class F1, class F2, class F3>
597  template<class F1, class F2> friend class PersistentValueVector;
598  friend class Object;
599 
600  explicit V8_INLINE PersistentBase(T* val) : val_(val) {}
601  V8_INLINE static T* New(Isolate* isolate, T* that);
602 
603  T* val_;
604 };
605 
606 
607 /**
608  * Default traits for Persistent. This class does not allow
609  * use of the copy constructor or assignment operator.
610  * At present kResetInDestructor is not set, but that will change in a future
611  * version.
612  */
613 template<class T>
614 class NonCopyablePersistentTraits {
615  public:
616  typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
617  static const bool kResetInDestructor = false;
618  template<class S, class M>
619  V8_INLINE static void Copy(const Persistent<S, M>& source,
620  NonCopyablePersistent* dest) {
621  Uncompilable<Object>();
622  }
623  // TODO(dcarney): come up with a good compile error here.
624  template<class O> V8_INLINE static void Uncompilable() {
625  TYPE_CHECK(O, Primitive);
626  }
627 };
628 
629 
630 /**
631  * Helper class traits to allow copying and assignment of Persistent.
632  * This will clone the contents of storage cell, but not any of the flags, etc.
633  */
634 template<class T>
637  static const bool kResetInDestructor = true;
638  template<class S, class M>
639  static V8_INLINE void Copy(const Persistent<S, M>& source,
640  CopyablePersistent* dest) {
641  // do nothing, just allow copy
642  }
643 };
644 
645 
646 /**
647  * A PersistentBase which allows copy and assignment.
648  *
649  * Copy, assignment and destructor behavior is controlled by the traits
650  * class M.
651  *
652  * Note: Persistent class hierarchy is subject to future changes.
653  */
654 template <class T, class M> class Persistent : public PersistentBase<T> {
655  public:
656  /**
657  * A Persistent with no storage cell.
658  */
660  /**
661  * Construct a Persistent from a Local.
662  * When the Local is non-empty, a new storage cell is created
663  * pointing to the same object, and no flags are set.
664  */
665  template <class S>
666  V8_INLINE Persistent(Isolate* isolate, Local<S> that)
667  : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
668  TYPE_CHECK(T, S);
669  }
670  /**
671  * Construct a Persistent from a Persistent.
672  * When the Persistent is non-empty, a new storage cell is created
673  * pointing to the same object, and no flags are set.
674  */
675  template <class S, class M2>
676  V8_INLINE Persistent(Isolate* isolate, const Persistent<S, M2>& that)
677  : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
678  TYPE_CHECK(T, S);
679  }
680  /**
681  * The copy constructors and assignment operator create a Persistent
682  * exactly as the Persistent constructor, but the Copy function from the
683  * traits class is called, allowing the setting of flags based on the
684  * copied Persistent.
685  */
686  V8_INLINE Persistent(const Persistent& that) : PersistentBase<T>(nullptr) {
687  Copy(that);
688  }
689  template <class S, class M2>
690  V8_INLINE Persistent(const Persistent<S, M2>& that) : PersistentBase<T>(0) {
691  Copy(that);
692  }
694  Copy(that);
695  return *this;
696  }
697  template <class S, class M2>
698  V8_INLINE Persistent& operator=(const Persistent<S, M2>& that) { // NOLINT
699  Copy(that);
700  return *this;
701  }
702  /**
703  * The destructor will dispose the Persistent based on the
704  * kResetInDestructor flags in the traits class. Since not calling dispose
705  * can result in a memory leak, it is recommended to always set this flag.
706  */
708  if (M::kResetInDestructor) this->Reset();
709  }
710 
711  // TODO(dcarney): this is pretty useless, fix or remove
712  template <class S>
713  V8_INLINE static Persistent<T>& Cast(const Persistent<S>& that) { // NOLINT
714 #ifdef V8_ENABLE_CHECKS
715  // If we're going to perform the type check then we have to check
716  // that the handle isn't empty before doing the checked cast.
717  if (!that.IsEmpty()) T::Cast(*that);
718 #endif
719  return reinterpret_cast<Persistent<T>&>(const_cast<Persistent<S>&>(that));
720  }
721 
722  // TODO(dcarney): this is pretty useless, fix or remove
723  template <class S>
724  V8_INLINE Persistent<S>& As() const { // NOLINT
725  return Persistent<S>::Cast(*this);
726  }
727 
728  private:
729  friend class Isolate;
730  friend class Utils;
731  template<class F> friend class Local;
732  template<class F1, class F2> friend class Persistent;
733  template<class F> friend class ReturnValue;
734 
735  explicit V8_INLINE Persistent(T* that) : PersistentBase<T>(that) {}
736  V8_INLINE T* operator*() const { return this->val_; }
737  template<class S, class M2>
738  V8_INLINE void Copy(const Persistent<S, M2>& that);
739 };
740 
741 
742 /**
743  * A PersistentBase which has move semantics.
744  *
745  * Note: Persistent class hierarchy is subject to future changes.
746  */
747 template <class T>
748 class Global : public PersistentBase<T> {
749  public:
750  /**
751  * A Global with no storage cell.
752  */
753  V8_INLINE Global() : PersistentBase<T>(nullptr) {}
754 
755  /**
756  * Construct a Global from a Local.
757  * When the Local is non-empty, a new storage cell is created
758  * pointing to the same object, and no flags are set.
759  */
760  template <class S>
761  V8_INLINE Global(Isolate* isolate, Local<S> that)
762  : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
763  TYPE_CHECK(T, S);
764  }
765 
766  /**
767  * Construct a Global from a PersistentBase.
768  * When the Persistent is non-empty, a new storage cell is created
769  * pointing to the same object, and no flags are set.
770  */
771  template <class S>
772  V8_INLINE Global(Isolate* isolate, const PersistentBase<S>& that)
773  : PersistentBase<T>(PersistentBase<T>::New(isolate, that.val_)) {
774  TYPE_CHECK(T, S);
775  }
776 
777  /**
778  * Move constructor.
779  */
780  V8_INLINE Global(Global&& other);
781 
782  V8_INLINE ~Global() { this->Reset(); }
783 
784  /**
785  * Move via assignment.
786  */
787  template <class S>
788  V8_INLINE Global& operator=(Global<S>&& rhs);
789 
790  /**
791  * Pass allows returning uniques from functions, etc.
792  */
793  Global Pass() { return static_cast<Global&&>(*this); } // NOLINT
794 
795  /*
796  * For compatibility with Chromium's base::Bind (base::Passed).
797  */
798  typedef void MoveOnlyTypeForCPP03;
799 
800  Global(const Global&) = delete;
801  void operator=(const Global&) = delete;
802 
803  private:
804  template <class F>
805  friend class ReturnValue;
806  V8_INLINE T* operator*() const { return this->val_; }
807 };
808 
809 
810 // UniquePersistent is an alias for Global for historical reason.
811 template <class T>
812 using UniquePersistent = Global<T>;
813 
814 /**
815  * Deprecated. Use |TracedReference<T>| instead.
816  */
817 template <typename T>
819 
820 /**
821  * A traced handle with copy and move semantics. The handle is to be used
822  * together with |v8::EmbedderHeapTracer| and specifies edges from the embedder
823  * into V8's heap.
824  *
825  * The exact semantics are:
826  * - Tracing garbage collections use |v8::EmbedderHeapTracer|.
827  * - Non-tracing garbage collections refer to
828  * |v8::EmbedderHeapTracer::IsRootForNonTracingGC()| whether the handle should
829  * be treated as root or not.
830  *
831  * Note that the base class cannot be instantiated itself. Choose from
832  * - TracedGlobal
833  * - TracedReference
834  */
835 template <typename T>
836 class TracedReferenceBase {
837  public:
838  /**
839  * Returns true if this TracedReferenceBase is empty, i.e., has not been
840  * assigned an object.
841  */
842  bool IsEmpty() const { return val_ == nullptr; }
843 
844  /**
845  * If non-empty, destroy the underlying storage cell. |IsEmpty| will return
846  * true after this call.
847  */
848  V8_INLINE void Reset();
849 
850  /**
851  * Construct a Local<T> from this handle.
852  */
853  Local<T> Get(Isolate* isolate) const { return Local<T>::New(isolate, *this); }
854 
855  template <class S>
856  V8_INLINE bool operator==(const TracedReferenceBase<S>& that) const {
857  internal::Address* a = reinterpret_cast<internal::Address*>(val_);
858  internal::Address* b = reinterpret_cast<internal::Address*>(that.val_);
859  if (a == nullptr) return b == nullptr;
860  if (b == nullptr) return false;
861  return *a == *b;
862  }
863 
864  template <class S>
865  V8_INLINE bool operator==(const Local<S>& that) const {
866  internal::Address* a = reinterpret_cast<internal::Address*>(val_);
867  internal::Address* b = reinterpret_cast<internal::Address*>(that.val_);
868  if (a == nullptr) return b == nullptr;
869  if (b == nullptr) return false;
870  return *a == *b;
871  }
872 
873  template <class S>
874  V8_INLINE bool operator!=(const TracedReferenceBase<S>& that) const {
875  return !operator==(that);
876  }
877 
878  template <class S>
879  V8_INLINE bool operator!=(const Local<S>& that) const {
880  return !operator==(that);
881  }
882 
883  /**
884  * Assigns a wrapper class ID to the handle.
885  */
886  V8_INLINE void SetWrapperClassId(uint16_t class_id);
887 
888  /**
889  * Returns the class ID previously assigned to this handle or 0 if no class ID
890  * was previously assigned.
891  */
892  V8_INLINE uint16_t WrapperClassId() const;
893 
894  template <class S>
896  return reinterpret_cast<TracedReferenceBase<S>&>(
897  const_cast<TracedReferenceBase<T>&>(*this));
898  }
899 
900  private:
901  enum DestructionMode { kWithDestructor, kWithoutDestructor };
902 
903  /**
904  * An empty TracedReferenceBase without storage cell.
905  */
906  TracedReferenceBase() = default;
907 
908  V8_INLINE static T* New(Isolate* isolate, T* that, void* slot,
909  DestructionMode destruction_mode);
910 
911  T* val_ = nullptr;
912 
913  friend class EmbedderHeapTracer;
914  template <typename F>
915  friend class Local;
916  friend class Object;
917  template <typename F>
918  friend class TracedGlobal;
919  template <typename F>
920  friend class TracedReference;
921  template <typename F>
922  friend class ReturnValue;
923 };
924 
925 /**
926  * A traced handle with destructor that clears the handle. For more details see
927  * TracedReferenceBase.
928  */
929 template <typename T>
930 class TracedGlobal : public TracedReferenceBase<T> {
931  public:
932  using TracedReferenceBase<T>::Reset;
933 
934  /**
935  * Destructor resetting the handle.
936  */
937  ~TracedGlobal() { this->Reset(); }
938 
939  /**
940  * An empty TracedGlobal without storage cell.
941  */
943 
944  /**
945  * Construct a TracedGlobal from a Local.
946  *
947  * When the Local is non-empty, a new storage cell is created
948  * pointing to the same object.
949  */
950  template <class S>
951  TracedGlobal(Isolate* isolate, Local<S> that) : TracedReferenceBase<T>() {
952  this->val_ = this->New(isolate, that.val_, &this->val_,
953  TracedReferenceBase<T>::kWithDestructor);
954  TYPE_CHECK(T, S);
955  }
956 
957  /**
958  * Move constructor initializing TracedGlobal from an existing one.
959  */
961  // Forward to operator=.
962  *this = std::move(other);
963  }
964 
965  /**
966  * Move constructor initializing TracedGlobal from an existing one.
967  */
968  template <typename S>
970  // Forward to operator=.
971  *this = std::move(other);
972  }
973 
974  /**
975  * Copy constructor initializing TracedGlobal from an existing one.
976  */
978  // Forward to operator=;
979  *this = other;
980  }
981 
982  /**
983  * Copy constructor initializing TracedGlobal from an existing one.
984  */
985  template <typename S>
987  // Forward to operator=;
988  *this = other;
989  }
990 
991  /**
992  * Move assignment operator initializing TracedGlobal from an existing one.
993  */
995 
996  /**
997  * Move assignment operator initializing TracedGlobal from an existing one.
998  */
999  template <class S>
1001 
1002  /**
1003  * Copy assignment operator initializing TracedGlobal from an existing one.
1004  *
1005  * Note: Prohibited when |other| has a finalization callback set through
1006  * |SetFinalizationCallback|.
1007  */
1009 
1010  /**
1011  * Copy assignment operator initializing TracedGlobal from an existing one.
1012  *
1013  * Note: Prohibited when |other| has a finalization callback set through
1014  * |SetFinalizationCallback|.
1015  */
1016  template <class S>
1017  V8_INLINE TracedGlobal& operator=(const TracedGlobal<S>& rhs);
1018 
1019  /**
1020  * If non-empty, destroy the underlying storage cell and create a new one with
1021  * the contents of other if other is non empty
1022  */
1023  template <class S>
1024  V8_INLINE void Reset(Isolate* isolate, const Local<S>& other);
1025 
1026  template <class S>
1027  V8_INLINE TracedGlobal<S>& As() const {
1028  return reinterpret_cast<TracedGlobal<S>&>(
1029  const_cast<TracedGlobal<T>&>(*this));
1030  }
1031 
1032  /**
1033  * Adds a finalization callback to the handle. The type of this callback is
1034  * similar to WeakCallbackType::kInternalFields, i.e., it will pass the
1035  * parameter and the first two internal fields of the object.
1036  *
1037  * The callback is then supposed to reset the handle in the callback. No
1038  * further V8 API may be called in this callback. In case additional work
1039  * involving V8 needs to be done, a second callback can be scheduled using
1040  * WeakCallbackInfo<void>::SetSecondPassCallback.
1041  */
1043  void* parameter, WeakCallbackInfo<void>::Callback callback);
1044 };
1045 
1046 /**
1047  * A traced handle without destructor that clears the handle. The embedder needs
1048  * to ensure that the handle is not accessed once the V8 object has been
1049  * reclaimed. This can happen when the handle is not passed through the
1050  * EmbedderHeapTracer. For more details see TracedReferenceBase.
1051  *
1052  * The reference assumes the embedder has precise knowledge about references at
1053  * all times. In case V8 needs to separately handle on-stack references, the
1054  * embedder is required to set the stack start through
1055  * |EmbedderHeapTracer::SetStackStart|.
1056  */
1057 template <typename T>
1058 class TracedReference : public TracedReferenceBase<T> {
1059  public:
1060  using TracedReferenceBase<T>::Reset;
1061 
1062  /**
1063  * An empty TracedReference without storage cell.
1064  */
1066 
1067  /**
1068  * Construct a TracedReference from a Local.
1069  *
1070  * When the Local is non-empty, a new storage cell is created
1071  * pointing to the same object.
1072  */
1073  template <class S>
1074  TracedReference(Isolate* isolate, Local<S> that) : TracedReferenceBase<T>() {
1075  this->val_ = this->New(isolate, that.val_, &this->val_,
1076  TracedReferenceBase<T>::kWithoutDestructor);
1077  TYPE_CHECK(T, S);
1078  }
1079 
1080  /**
1081  * Move constructor initializing TracedReference from an
1082  * existing one.
1083  */
1085  // Forward to operator=.
1086  *this = std::move(other);
1087  }
1088 
1089  /**
1090  * Move constructor initializing TracedReference from an
1091  * existing one.
1092  */
1093  template <typename S>
1095  // Forward to operator=.
1096  *this = std::move(other);
1097  }
1098 
1099  /**
1100  * Copy constructor initializing TracedReference from an
1101  * existing one.
1102  */
1104  // Forward to operator=;
1105  *this = other;
1106  }
1107 
1108  /**
1109  * Copy constructor initializing TracedReference from an
1110  * existing one.
1111  */
1112  template <typename S>
1114  // Forward to operator=;
1115  *this = other;
1116  }
1117 
1118  /**
1119  * Move assignment operator initializing TracedGlobal from an existing one.
1120  */
1122 
1123  /**
1124  * Move assignment operator initializing TracedGlobal from an existing one.
1125  */
1126  template <class S>
1128 
1129  /**
1130  * Copy assignment operator initializing TracedGlobal from an existing one.
1131  *
1132  * Note: Prohibited when |other| has a finalization callback set through
1133  * |SetFinalizationCallback|.
1134  */
1136 
1137  /**
1138  * Copy assignment operator initializing TracedGlobal from an existing one.
1139  *
1140  * Note: Prohibited when |other| has a finalization callback set through
1141  * |SetFinalizationCallback|.
1142  */
1143  template <class S>
1145 
1146  /**
1147  * If non-empty, destroy the underlying storage cell and create a new one with
1148  * the contents of other if other is non empty
1149  */
1150  template <class S>
1151  V8_INLINE void Reset(Isolate* isolate, const Local<S>& other);
1152 
1153  template <class S>
1155  return reinterpret_cast<TracedReference<S>&>(
1156  const_cast<TracedReference<T>&>(*this));
1157  }
1158 
1159  /**
1160  * Adds a finalization callback to the handle. The type of this callback is
1161  * similar to WeakCallbackType::kInternalFields, i.e., it will pass the
1162  * parameter and the first two internal fields of the object.
1163  *
1164  * The callback is then supposed to reset the handle in the callback. No
1165  * further V8 API may be called in this callback. In case additional work
1166  * involving V8 needs to be done, a second callback can be scheduled using
1167  * WeakCallbackInfo<void>::SetSecondPassCallback.
1168  */
1169  V8_DEPRECATED("Use TracedGlobal<> if callbacks are required.")
1171  void* parameter, WeakCallbackInfo<void>::Callback callback);
1172 };
1173 
1174  /**
1175  * A stack-allocated class that governs a number of local handles.
1176  * After a handle scope has been created, all local handles will be
1177  * allocated within that handle scope until either the handle scope is
1178  * deleted or another handle scope is created. If there is already a
1179  * handle scope and a new one is created, all allocations will take
1180  * place in the new handle scope until it is deleted. After that,
1181  * new handles will again be allocated in the original handle scope.
1182  *
1183  * After the handle scope of a local handle has been deleted the
1184  * garbage collector will no longer track the object stored in the
1185  * handle and may deallocate it. The behavior of accessing a handle
1186  * for which the handle scope has been deleted is undefined.
1187  */
1189  public:
1190  explicit HandleScope(Isolate* isolate);
1191 
1192  ~HandleScope();
1193 
1194  /**
1195  * Counts the number of allocated handles.
1196  */
1197  static int NumberOfHandles(Isolate* isolate);
1198 
1200  return reinterpret_cast<Isolate*>(isolate_);
1201  }
1202 
1203  HandleScope(const HandleScope&) = delete;
1204  void operator=(const HandleScope&) = delete;
1205 
1206  protected:
1207  V8_INLINE HandleScope() = default;
1208 
1209  void Initialize(Isolate* isolate);
1210 
1211  static internal::Address* CreateHandle(internal::Isolate* isolate,
1212  internal::Address value);
1213 
1214  private:
1215  // Declaring operator new and delete as deleted is not spec compliant.
1216  // Therefore declare them private instead to disable dynamic alloc
1217  void* operator new(size_t size);
1218  void* operator new[](size_t size);
1219  void operator delete(void*, size_t);
1220  void operator delete[](void*, size_t);
1221 
1222  internal::Isolate* isolate_;
1223  internal::Address* prev_next_;
1224  internal::Address* prev_limit_;
1225 
1226  // Local::New uses CreateHandle with an Isolate* parameter.
1227  template<class F> friend class Local;
1228 
1229  // Object::GetInternalField and Context::GetEmbedderData use CreateHandle with
1230  // a HeapObject in their shortcuts.
1231  friend class Object;
1232  friend class Context;
1233 };
1234 
1235 
1236 /**
1237  * A HandleScope which first allocates a handle in the current scope
1238  * which will be later filled with the escape value.
1239  */
1241  public:
1242  explicit EscapableHandleScope(Isolate* isolate);
1243  V8_INLINE ~EscapableHandleScope() = default;
1244 
1245  /**
1246  * Pushes the value into the previous scope and returns a handle to it.
1247  * Cannot be called twice.
1248  */
1249  template <class T>
1250  V8_INLINE Local<T> Escape(Local<T> value) {
1251  internal::Address* slot =
1252  Escape(reinterpret_cast<internal::Address*>(*value));
1253  return Local<T>(reinterpret_cast<T*>(slot));
1254  }
1255 
1256  template <class T>
1258  return Escape(value.FromMaybe(Local<T>()));
1259  }
1260 
1261  EscapableHandleScope(const EscapableHandleScope&) = delete;
1262  void operator=(const EscapableHandleScope&) = delete;
1263 
1264  private:
1265  // Declaring operator new and delete as deleted is not spec compliant.
1266  // Therefore declare them private instead to disable dynamic alloc
1267  void* operator new(size_t size);
1268  void* operator new[](size_t size);
1269  void operator delete(void*, size_t);
1270  void operator delete[](void*, size_t);
1271 
1272  internal::Address* Escape(internal::Address* escape_value);
1273  internal::Address* escape_slot_;
1274 };
1275 
1276 /**
1277  * A SealHandleScope acts like a handle scope in which no handle allocations
1278  * are allowed. It can be useful for debugging handle leaks.
1279  * Handles can be allocated within inner normal HandleScopes.
1280  */
1282  public:
1283  explicit SealHandleScope(Isolate* isolate);
1284  ~SealHandleScope();
1285 
1286  SealHandleScope(const SealHandleScope&) = delete;
1287  void operator=(const SealHandleScope&) = delete;
1288 
1289  private:
1290  // Declaring operator new and delete as deleted is not spec compliant.
1291  // Therefore declare them private instead to disable dynamic alloc
1292  void* operator new(size_t size);
1293  void* operator new[](size_t size);
1294  void operator delete(void*, size_t);
1295  void operator delete[](void*, size_t);
1296 
1297  internal::Isolate* const isolate_;
1298  internal::Address* prev_limit_;
1299  int prev_sealed_level_;
1300 };
1301 
1302 
1303 // --- Special objects ---
1304 
1305 /**
1306  * The superclass of objects that can reside on V8's heap.
1307  */
1309  private:
1310  Data();
1311 };
1312 
1313 /**
1314  * A container type that holds relevant metadata for module loading.
1315  *
1316  * This is passed back to the embedder as part of
1317  * HostImportModuleDynamicallyCallback for module loading.
1318  */
1320  public:
1321  /**
1322  * The name that was passed by the embedder as ResourceName to the
1323  * ScriptOrigin. This can be either a v8::String or v8::Undefined.
1324  */
1326 
1327  /**
1328  * The options that were passed by the embedder as HostDefinedOptions to
1329  * the ScriptOrigin.
1330  */
1332 };
1333 
1334 /**
1335  * An array to hold Primitive values. This is used by the embedder to
1336  * pass host defined options to the ScriptOptions during compilation.
1337  *
1338  * This is passed back to the embedder as part of
1339  * HostImportModuleDynamicallyCallback for module loading.
1340  *
1341  */
1343  public:
1344  static Local<PrimitiveArray> New(Isolate* isolate, int length);
1345  int Length() const;
1346  void Set(Isolate* isolate, int index, Local<Primitive> item);
1347  Local<Primitive> Get(Isolate* isolate, int index);
1348 };
1349 
1350 /**
1351  * The optional attributes of ScriptOrigin.
1352  */
1354  public:
1355  V8_INLINE ScriptOriginOptions(bool is_shared_cross_origin = false,
1356  bool is_opaque = false, bool is_wasm = false,
1357  bool is_module = false)
1358  : flags_((is_shared_cross_origin ? kIsSharedCrossOrigin : 0) |
1359  (is_wasm ? kIsWasm : 0) | (is_opaque ? kIsOpaque : 0) |
1360  (is_module ? kIsModule : 0)) {}
1362  : flags_(flags &
1363  (kIsSharedCrossOrigin | kIsOpaque | kIsWasm | kIsModule)) {}
1364 
1365  bool IsSharedCrossOrigin() const {
1366  return (flags_ & kIsSharedCrossOrigin) != 0;
1367  }
1368  bool IsOpaque() const { return (flags_ & kIsOpaque) != 0; }
1369  bool IsWasm() const { return (flags_ & kIsWasm) != 0; }
1370  bool IsModule() const { return (flags_ & kIsModule) != 0; }
1371 
1372  int Flags() const { return flags_; }
1373 
1374  private:
1375  enum {
1376  kIsSharedCrossOrigin = 1,
1377  kIsOpaque = 1 << 1,
1378  kIsWasm = 1 << 2,
1379  kIsModule = 1 << 3
1380  };
1381  const int flags_;
1382 };
1383 
1384 /**
1385  * The origin, within a file, of a script.
1386  */
1388  public:
1390  Local<Value> resource_name,
1391  Local<Integer> resource_line_offset = Local<Integer>(),
1392  Local<Integer> resource_column_offset = Local<Integer>(),
1393  Local<Boolean> resource_is_shared_cross_origin = Local<Boolean>(),
1394  Local<Integer> script_id = Local<Integer>(),
1395  Local<Value> source_map_url = Local<Value>(),
1396  Local<Boolean> resource_is_opaque = Local<Boolean>(),
1397  Local<Boolean> is_wasm = Local<Boolean>(),
1398  Local<Boolean> is_module = Local<Boolean>(),
1399  Local<PrimitiveArray> host_defined_options = Local<PrimitiveArray>());
1400 
1401  V8_INLINE Local<Value> ResourceName() const;
1404  V8_INLINE Local<Integer> ScriptID() const;
1405  V8_INLINE Local<Value> SourceMapUrl() const;
1407  V8_INLINE ScriptOriginOptions Options() const { return options_; }
1408 
1409  private:
1410  Local<Value> resource_name_;
1411  Local<Integer> resource_line_offset_;
1412  Local<Integer> resource_column_offset_;
1413  ScriptOriginOptions options_;
1414  Local<Integer> script_id_;
1415  Local<Value> source_map_url_;
1416  Local<PrimitiveArray> host_defined_options_;
1417 };
1418 
1419 /**
1420  * A compiled JavaScript script, not yet tied to a Context.
1421  */
1423  public:
1424  /**
1425  * Binds the script to the currently entered context.
1426  */
1428 
1429  int GetId();
1431 
1432  /**
1433  * Data read from magic sourceURL comments.
1434  */
1436  /**
1437  * Data read from magic sourceMappingURL comments.
1438  */
1440 
1441  /**
1442  * Returns zero based line number of the code_pos location in the script.
1443  * -1 will be returned if no information available.
1444  */
1445  int GetLineNumber(int code_pos);
1446 
1447  static const int kNoScriptId = 0;
1448 };
1449 
1450 /**
1451  * A compiled JavaScript module, not yet tied to a Context.
1452  */
1454  // Only used as a container for code caching.
1455 };
1456 
1457 /**
1458  * A location in JavaScript source.
1459  */
1461  public:
1462  int GetLineNumber() { return line_number_; }
1463  int GetColumnNumber() { return column_number_; }
1464 
1465  Location(int line_number, int column_number)
1466  : line_number_(line_number), column_number_(column_number) {}
1467 
1468  private:
1469  int line_number_;
1470  int column_number_;
1471 };
1472 
1473 /**
1474  * A compiled JavaScript module.
1475  */
1476 class V8_EXPORT Module : public Data {
1477  public:
1478  /**
1479  * The different states a module can be in.
1480  *
1481  * This corresponds to the states used in ECMAScript except that "evaluated"
1482  * is split into kEvaluated and kErrored, indicating success and failure,
1483  * respectively.
1484  */
1485  enum Status {
1492  };
1493 
1494  /**
1495  * Returns the module's current status.
1496  */
1497  Status GetStatus() const;
1498 
1499  /**
1500  * For a module in kErrored status, this returns the corresponding exception.
1501  */
1502  Local<Value> GetException() const;
1503 
1504  /**
1505  * Returns the number of modules requested by this module.
1506  */
1507  int GetModuleRequestsLength() const;
1508 
1509  /**
1510  * Returns the ith module specifier in this module.
1511  * i must be < GetModuleRequestsLength() and >= 0.
1512  */
1513  Local<String> GetModuleRequest(int i) const;
1514 
1515  /**
1516  * Returns the source location (line number and column number) of the ith
1517  * module specifier's first occurrence in this module.
1518  */
1519  Location GetModuleRequestLocation(int i) const;
1520 
1521  /**
1522  * Returns the identity hash for this object.
1523  */
1524  int GetIdentityHash() const;
1525 
1527  Local<String> specifier,
1528  Local<Module> referrer);
1529 
1530  /**
1531  * Instantiates the module and its dependencies.
1532  *
1533  * Returns an empty Maybe<bool> if an exception occurred during
1534  * instantiation. (In the case where the callback throws an exception, that
1535  * exception is propagated.)
1536  */
1538  ResolveCallback callback);
1539 
1540  /**
1541  * Evaluates the module and its dependencies.
1542  *
1543  * If status is kInstantiated, run the module's code. On success, set status
1544  * to kEvaluated and return the completion value; on failure, set status to
1545  * kErrored and propagate the thrown exception (which is then also available
1546  * via |GetException|).
1547  */
1549 
1550  /**
1551  * Returns the namespace object of this module.
1552  *
1553  * The module's status must be at least kInstantiated.
1554  */
1556 
1557  /**
1558  * Returns the corresponding context-unbound module script.
1559  *
1560  * The module must be unevaluated, i.e. its status must not be kEvaluating,
1561  * kEvaluated or kErrored.
1562  */
1564 
1565  /*
1566  * Callback defined in the embedder. This is responsible for setting
1567  * the module's exported values with calls to SetSyntheticModuleExport().
1568  * The callback must return a Value to indicate success (where no
1569  * exception was thrown) and return an empy MaybeLocal to indicate falure
1570  * (where an exception was thrown).
1571  */
1573  Local<Context> context, Local<Module> module);
1574 
1575  /**
1576  * Creates a new SyntheticModule with the specified export names, where
1577  * evaluation_steps will be executed upon module evaluation.
1578  * export_names must not contain duplicates.
1579  * module_name is used solely for logging/debugging and doesn't affect module
1580  * behavior.
1581  */
1583  Isolate* isolate, Local<String> module_name,
1584  const std::vector<Local<String>>& export_names,
1585  SyntheticModuleEvaluationSteps evaluation_steps);
1586 
1587  /**
1588  * Set this module's exported value for the name export_name to the specified
1589  * export_value. This method must be called only on Modules created via
1590  * CreateSyntheticModule. An error will be thrown if export_name is not one
1591  * of the export_names that were passed in that CreateSyntheticModule call.
1592  * Returns Just(true) on success, Nothing<bool>() if an error was thrown.
1593  */
1595  Isolate* isolate, Local<String> export_name, Local<Value> export_value);
1597  "Use the preceding SetSyntheticModuleExport with an Isolate parameter, "
1598  "instead of the one that follows. The former will throw a runtime "
1599  "error if called for an export that doesn't exist (as per spec); "
1600  "the latter will crash with a failed CHECK().")
1601  void SetSyntheticModuleExport(Local<String> export_name,
1603 };
1604 
1605 /**
1606  * A compiled JavaScript script, tied to a Context which was active when the
1607  * script was compiled.
1608  */
1610  public:
1611  /**
1612  * A shorthand for ScriptCompiler::Compile().
1613  */
1615  Local<Context> context, Local<String> source,
1616  ScriptOrigin* origin = nullptr);
1617 
1618  /**
1619  * Runs the script returning the resulting value. It will be run in the
1620  * context in which it was created (ScriptCompiler::CompileBound or
1621  * UnboundScript::BindToCurrentContext()).
1622  */
1624 
1625  /**
1626  * Returns the corresponding context-unbound script.
1627  */
1629 };
1630 
1631 
1632 /**
1633  * For compiling scripts.
1634  */
1636  public:
1637  /**
1638  * Compilation data that the embedder can cache and pass back to speed up
1639  * future compilations. The data is produced if the CompilerOptions passed to
1640  * the compilation functions in ScriptCompiler contains produce_data_to_cache
1641  * = true. The data to cache can then can be retrieved from
1642  * UnboundScript.
1643  */
1648  };
1649 
1651  : data(nullptr),
1652  length(0),
1653  rejected(false),
1655 
1656  // If buffer_policy is BufferNotOwned, the caller keeps the ownership of
1657  // data and guarantees that it stays alive until the CachedData object is
1658  // destroyed. If the policy is BufferOwned, the given data will be deleted
1659  // (with delete[]) when the CachedData object is destroyed.
1660  CachedData(const uint8_t* data, int length,
1661  BufferPolicy buffer_policy = BufferNotOwned);
1662  ~CachedData();
1663  // TODO(marja): Async compilation; add constructors which take a callback
1664  // which will be called when V8 no longer needs the data.
1665  const uint8_t* data;
1666  int length;
1667  bool rejected;
1669 
1670  // Prevent copying.
1671  CachedData(const CachedData&) = delete;
1672  CachedData& operator=(const CachedData&) = delete;
1673  };
1674 
1675  /**
1676  * Source code which can be then compiled to a UnboundScript or Script.
1677  */
1678  class Source {
1679  public:
1680  // Source takes ownership of CachedData.
1681  V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
1682  CachedData* cached_data = nullptr);
1683  V8_INLINE Source(Local<String> source_string,
1684  CachedData* cached_data = nullptr);
1685  V8_INLINE ~Source();
1686 
1687  // Ownership of the CachedData or its buffers is *not* transferred to the
1688  // caller. The CachedData object is alive as long as the Source object is
1689  // alive.
1690  V8_INLINE const CachedData* GetCachedData() const;
1691 
1693 
1694  // Prevent copying.
1695  Source(const Source&) = delete;
1696  Source& operator=(const Source&) = delete;
1697 
1698  private:
1699  friend class ScriptCompiler;
1700 
1701  Local<String> source_string;
1702 
1703  // Origin information
1704  Local<Value> resource_name;
1705  Local<Integer> resource_line_offset;
1706  Local<Integer> resource_column_offset;
1707  ScriptOriginOptions resource_options;
1708  Local<Value> source_map_url;
1709  Local<PrimitiveArray> host_defined_options;
1710 
1711  // Cached data from previous compilation (if a kConsume*Cache flag is
1712  // set), or hold newly generated cache data (kProduce*Cache flags) are
1713  // set when calling a compile method.
1714  CachedData* cached_data;
1715  };
1716 
1717  /**
1718  * For streaming incomplete script data to V8. The embedder should implement a
1719  * subclass of this class.
1720  */
1722  public:
1723  virtual ~ExternalSourceStream() = default;
1724 
1725  /**
1726  * V8 calls this to request the next chunk of data from the embedder. This
1727  * function will be called on a background thread, so it's OK to block and
1728  * wait for the data, if the embedder doesn't have data yet. Returns the
1729  * length of the data returned. When the data ends, GetMoreData should
1730  * return 0. Caller takes ownership of the data.
1731  *
1732  * When streaming UTF-8 data, V8 handles multi-byte characters split between
1733  * two data chunks, but doesn't handle multi-byte characters split between
1734  * more than two data chunks. The embedder can avoid this problem by always
1735  * returning at least 2 bytes of data.
1736  *
1737  * When streaming UTF-16 data, V8 does not handle characters split between
1738  * two data chunks. The embedder has to make sure that chunks have an even
1739  * length.
1740  *
1741  * If the embedder wants to cancel the streaming, they should make the next
1742  * GetMoreData call return 0. V8 will interpret it as end of data (and most
1743  * probably, parsing will fail). The streaming task will return as soon as
1744  * V8 has parsed the data it received so far.
1745  */
1746  virtual size_t GetMoreData(const uint8_t** src) = 0;
1747 
1748  /**
1749  * V8 calls this method to set a 'bookmark' at the current position in
1750  * the source stream, for the purpose of (maybe) later calling
1751  * ResetToBookmark. If ResetToBookmark is called later, then subsequent
1752  * calls to GetMoreData should return the same data as they did when
1753  * SetBookmark was called earlier.
1754  *
1755  * The embedder may return 'false' to indicate it cannot provide this
1756  * functionality.
1757  */
1758  virtual bool SetBookmark();
1759 
1760  /**
1761  * V8 calls this to return to a previously set bookmark.
1762  */
1763  virtual void ResetToBookmark();
1764  };
1765 
1766  /**
1767  * Source code which can be streamed into V8 in pieces. It will be parsed
1768  * while streaming and compiled after parsing has completed. StreamedSource
1769  * must be kept alive while the streaming task is run (see ScriptStreamingTask
1770  * below).
1771  */
1773  public:
1775 
1777  "This class takes ownership of source_stream, so use the constructor "
1778  "taking a unique_ptr to make these semantics clearer")
1779  StreamedSource(ExternalSourceStream* source_stream, Encoding encoding);
1780  StreamedSource(std::unique_ptr<ExternalSourceStream> source_stream,
1781  Encoding encoding);
1782  ~StreamedSource();
1783 
1784  internal::ScriptStreamingData* impl() const { return impl_.get(); }
1785 
1786  // Prevent copying.
1787  StreamedSource(const StreamedSource&) = delete;
1788  StreamedSource& operator=(const StreamedSource&) = delete;
1789 
1790  private:
1791  std::unique_ptr<internal::ScriptStreamingData> impl_;
1792  };
1793 
1794  /**
1795  * A streaming task which the embedder must run on a background thread to
1796  * stream scripts into V8. Returned by ScriptCompiler::StartStreamingScript.
1797  */
1798  class V8_EXPORT ScriptStreamingTask final {
1799  public:
1800  void Run();
1801 
1802  private:
1803  friend class ScriptCompiler;
1804 
1805  explicit ScriptStreamingTask(internal::ScriptStreamingData* data)
1806  : data_(data) {}
1807 
1808  internal::ScriptStreamingData* data_;
1809  };
1810 
1815  };
1816 
1817  /**
1818  * The reason for which we are not requesting or providing a code cache.
1819  */
1836  };
1837 
1838  /**
1839  * Compiles the specified script (context-independent).
1840  * Cached data as part of the source object can be optionally produced to be
1841  * consumed later to speed up compilation of identical source scripts.
1842  *
1843  * Note that when producing cached data, the source must point to NULL for
1844  * cached data. When consuming cached data, the cached data must have been
1845  * produced by the same version of V8.
1846  *
1847  * \param source Script source code.
1848  * \return Compiled script object (context independent; for running it must be
1849  * bound to a context).
1850  */
1852  Isolate* isolate, Source* source,
1854  NoCacheReason no_cache_reason = kNoCacheNoReason);
1855 
1856  /**
1857  * Compiles the specified script (bound to current context).
1858  *
1859  * \param source Script source code.
1860  * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
1861  * using pre_data speeds compilation if it's done multiple times.
1862  * Owned by caller, no references are kept when this function returns.
1863  * \return Compiled script object, bound to the context that was active
1864  * when this function was called. When run it will always use this
1865  * context.
1866  */
1868  Local<Context> context, Source* source,
1870  NoCacheReason no_cache_reason = kNoCacheNoReason);
1871 
1872  /**
1873  * Returns a task which streams script data into V8, or NULL if the script
1874  * cannot be streamed. The user is responsible for running the task on a
1875  * background thread and deleting it. When ran, the task starts parsing the
1876  * script, and it will request data from the StreamedSource as needed. When
1877  * ScriptStreamingTask::Run exits, all data has been streamed and the script
1878  * can be compiled (see Compile below).
1879  *
1880  * This API allows to start the streaming with as little data as possible, and
1881  * the remaining data (for example, the ScriptOrigin) is passed to Compile.
1882  */
1883  static ScriptStreamingTask* StartStreamingScript(
1884  Isolate* isolate, StreamedSource* source,
1885  CompileOptions options = kNoCompileOptions);
1886 
1887  /**
1888  * Compiles a streamed script (bound to current context).
1889  *
1890  * This can only be called after the streaming has finished
1891  * (ScriptStreamingTask has been run). V8 doesn't construct the source string
1892  * during streaming, so the embedder needs to pass the full source here.
1893  */
1895  Local<Context> context, StreamedSource* source,
1896  Local<String> full_source_string, const ScriptOrigin& origin);
1897 
1898  /**
1899  * Return a version tag for CachedData for the current V8 version & flags.
1900  *
1901  * This value is meant only for determining whether a previously generated
1902  * CachedData instance is still valid; the tag has no other meaing.
1903  *
1904  * Background: The data carried by CachedData may depend on the exact
1905  * V8 version number or current compiler flags. This means that when
1906  * persisting CachedData, the embedder must take care to not pass in
1907  * data from another V8 version, or the same version with different
1908  * features enabled.
1909  *
1910  * The easiest way to do so is to clear the embedder's cache on any
1911  * such change.
1912  *
1913  * Alternatively, this tag can be stored alongside the cached data and
1914  * compared when it is being used.
1915  */
1916  static uint32_t CachedDataVersionTag();
1917 
1918  /**
1919  * Compile an ES module, returning a Module that encapsulates
1920  * the compiled code.
1921  *
1922  * Corresponds to the ParseModule abstract operation in the
1923  * ECMAScript specification.
1924  */
1926  Isolate* isolate, Source* source,
1928  NoCacheReason no_cache_reason = kNoCacheNoReason);
1929 
1930  /**
1931  * Compile a function for a given context. This is equivalent to running
1932  *
1933  * with (obj) {
1934  * return function(args) { ... }
1935  * }
1936  *
1937  * It is possible to specify multiple context extensions (obj in the above
1938  * example).
1939  */
1941  Local<Context> context, Source* source, size_t arguments_count,
1942  Local<String> arguments[], size_t context_extension_count,
1943  Local<Object> context_extensions[],
1945  NoCacheReason no_cache_reason = kNoCacheNoReason,
1946  Local<ScriptOrModule>* script_or_module_out = nullptr);
1947 
1948  /**
1949  * Creates and returns code cache for the specified unbound_script.
1950  * This will return nullptr if the script cannot be serialized. The
1951  * CachedData returned by this function should be owned by the caller.
1952  */
1953  static CachedData* CreateCodeCache(Local<UnboundScript> unbound_script);
1954 
1955  /**
1956  * Creates and returns code cache for the specified unbound_module_script.
1957  * This will return nullptr if the script cannot be serialized. The
1958  * CachedData returned by this function should be owned by the caller.
1959  */
1960  static CachedData* CreateCodeCache(
1961  Local<UnboundModuleScript> unbound_module_script);
1962 
1963  /**
1964  * Creates and returns code cache for the specified function that was
1965  * previously produced by CompileFunctionInContext.
1966  * This will return nullptr if the script cannot be serialized. The
1967  * CachedData returned by this function should be owned by the caller.
1968  */
1970 
1971  private:
1972  static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundInternal(
1973  Isolate* isolate, Source* source, CompileOptions options,
1974  NoCacheReason no_cache_reason);
1975 };
1976 
1977 
1978 /**
1979  * An error message.
1980  */
1982  public:
1983  Local<String> Get() const;
1984 
1985  /**
1986  * Return the isolate to which the Message belongs.
1987  */
1988  Isolate* GetIsolate() const;
1989 
1991  Local<Context> context) const;
1992 
1993  /**
1994  * Returns the origin for the script from where the function causing the
1995  * error originates.
1996  */
1997  ScriptOrigin GetScriptOrigin() const;
1998 
1999  /**
2000  * Returns the resource name for the script from where the function causing
2001  * the error originates.
2002  */
2004 
2005  /**
2006  * Exception stack trace. By default stack traces are not captured for
2007  * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
2008  * to change this option.
2009  */
2010  Local<StackTrace> GetStackTrace() const;
2011 
2012  /**
2013  * Returns the number, 1-based, of the line where the error occurred.
2014  */
2015  V8_WARN_UNUSED_RESULT Maybe<int> GetLineNumber(Local<Context> context) const;
2016 
2017  /**
2018  * Returns the index within the script of the first character where
2019  * the error occurred.
2020  */
2021  int GetStartPosition() const;
2022 
2023  /**
2024  * Returns the index within the script of the last character where
2025  * the error occurred.
2026  */
2027  int GetEndPosition() const;
2028 
2029  /**
2030  * Returns the Wasm function index where the error occurred. Returns -1 if
2031  * message is not from a Wasm script.
2032  */
2033  int GetWasmFunctionIndex() const;
2034 
2035  /**
2036  * Returns the error level of the message.
2037  */
2038  int ErrorLevel() const;
2039 
2040  /**
2041  * Returns the index within the line of the first character where
2042  * the error occurred.
2043  */
2044  int GetStartColumn() const;
2046 
2047  /**
2048  * Returns the index within the line of the last character where
2049  * the error occurred.
2050  */
2051  int GetEndColumn() const;
2052  V8_WARN_UNUSED_RESULT Maybe<int> GetEndColumn(Local<Context> context) const;
2053 
2054  /**
2055  * Passes on the value set by the embedder when it fed the script from which
2056  * this Message was generated to V8.
2057  */
2058  bool IsSharedCrossOrigin() const;
2059  bool IsOpaque() const;
2060 
2061  // TODO(1245381): Print to a string instead of on a FILE.
2062  static void PrintCurrentStackTrace(Isolate* isolate, FILE* out);
2063 
2064  static const int kNoLineNumberInfo = 0;
2065  static const int kNoColumnInfo = 0;
2066  static const int kNoScriptIdInfo = 0;
2067  static const int kNoWasmFunctionIndexInfo = -1;
2068 };
2069 
2070 
2071 /**
2072  * Representation of a JavaScript stack trace. The information collected is a
2073  * snapshot of the execution stack and the information remains valid after
2074  * execution continues.
2075  */
2077  public:
2078  /**
2079  * Flags that determine what information is placed captured for each
2080  * StackFrame when grabbing the current stack trace.
2081  * Note: these options are deprecated and we always collect all available
2082  * information (kDetailed).
2083  */
2087  kScriptName = 1 << 2,
2088  kFunctionName = 1 << 3,
2089  kIsEval = 1 << 4,
2090  kIsConstructor = 1 << 5,
2092  kScriptId = 1 << 7,
2096  };
2097 
2098  /**
2099  * Returns a StackFrame at a particular index.
2100  */
2101  Local<StackFrame> GetFrame(Isolate* isolate, uint32_t index) const;
2102 
2103  /**
2104  * Returns the number of StackFrames.
2105  */
2106  int GetFrameCount() const;
2107 
2108  /**
2109  * Grab a snapshot of the current JavaScript execution stack.
2110  *
2111  * \param frame_limit The maximum number of stack frames we want to capture.
2112  * \param options Enumerates the set of things we will capture for each
2113  * StackFrame.
2114  */
2116  Isolate* isolate, int frame_limit, StackTraceOptions options = kDetailed);
2117 };
2118 
2119 
2120 /**
2121  * A single JavaScript stack frame.
2122  */
2124  public:
2125  /**
2126  * Returns the number, 1-based, of the line for the associate function call.
2127  * This method will return Message::kNoLineNumberInfo if it is unable to
2128  * retrieve the line number, or if kLineNumber was not passed as an option
2129  * when capturing the StackTrace.
2130  */
2131  int GetLineNumber() const;
2132 
2133  /**
2134  * Returns the 1-based column offset on the line for the associated function
2135  * call.
2136  * This method will return Message::kNoColumnInfo if it is unable to retrieve
2137  * the column number, or if kColumnOffset was not passed as an option when
2138  * capturing the StackTrace.
2139  */
2140  int GetColumn() const;
2141 
2142  /**
2143  * Returns the id of the script for the function for this StackFrame.
2144  * This method will return Message::kNoScriptIdInfo if it is unable to
2145  * retrieve the script id, or if kScriptId was not passed as an option when
2146  * capturing the StackTrace.
2147  */
2148  int GetScriptId() const;
2149 
2150  /**
2151  * Returns the name of the resource that contains the script for the
2152  * function for this StackFrame.
2153  */
2154  Local<String> GetScriptName() const;
2155 
2156  /**
2157  * Returns the name of the resource that contains the script for the
2158  * function for this StackFrame or sourceURL value if the script name
2159  * is undefined and its source ends with //# sourceURL=... string or
2160  * deprecated //@ sourceURL=... string.
2161  */
2163 
2164  /**
2165  * Returns the name of the function associated with this stack frame.
2166  */
2167  Local<String> GetFunctionName() const;
2168 
2169  /**
2170  * Returns whether or not the associated function is compiled via a call to
2171  * eval().
2172  */
2173  bool IsEval() const;
2174 
2175  /**
2176  * Returns whether or not the associated function is called as a
2177  * constructor via "new".
2178  */
2179  bool IsConstructor() const;
2180 
2181  /**
2182  * Returns whether or not the associated functions is defined in wasm.
2183  */
2184  bool IsWasm() const;
2185 
2186  /**
2187  * Returns whether or not the associated function is defined by the user.
2188  */
2189  bool IsUserJavaScript() const;
2190 };
2191 
2192 
2193 // A StateTag represents a possible state of the VM.
2194 enum StateTag {
2203 };
2204 
2205 // A RegisterState represents the current state of registers used
2206 // by the sampling profiler API.
2208  RegisterState() : pc(nullptr), sp(nullptr), fp(nullptr), lr(nullptr) {}
2209  void* pc; // Instruction pointer.
2210  void* sp; // Stack pointer.
2211  void* fp; // Frame pointer.
2212  void* lr; // Link register (or nullptr on platforms without a link register).
2213 };
2214 
2215 // The output structure filled up by GetStackSample API function.
2216 struct SampleInfo {
2217  size_t frames_count; // Number of frames collected.
2218  StateTag vm_state; // Current VM state.
2219  void* external_callback_entry; // External callback address if VM is
2220  // executing an external callback.
2221  void* top_context; // Incumbent native context address.
2222 };
2223 
2224 struct MemoryRange {
2225  const void* start = nullptr;
2226  size_t length_in_bytes = 0;
2227 };
2228 
2229 struct JSEntryStub {
2231 };
2232 
2233 struct UnwindState {
2239 };
2240 
2245 };
2246 
2247 /**
2248  * A JSON Parser and Stringifier.
2249  */
2251  public:
2252  /**
2253  * Tries to parse the string |json_string| and returns it as value if
2254  * successful.
2255  *
2256  * \param the context in which to parse and create the value.
2257  * \param json_string The string to parse.
2258  * \return The corresponding value if successfully parsed.
2259  */
2261  Local<Context> context, Local<String> json_string);
2262 
2263  /**
2264  * Tries to stringify the JSON-serializable object |json_object| and returns
2265  * it as string if successful.
2266  *
2267  * \param json_object The JSON-serializable object to stringify.
2268  * \return The corresponding string if successfully stringified.
2269  */
2271  Local<Context> context, Local<Value> json_object,
2272  Local<String> gap = Local<String>());
2273 };
2274 
2275 /**
2276  * Value serialization compatible with the HTML structured clone algorithm.
2277  * The format is backward-compatible (i.e. safe to store to disk).
2278  */
2280  public:
2282  public:
2283  virtual ~Delegate() = default;
2284 
2285  /**
2286  * Handles the case where a DataCloneError would be thrown in the structured
2287  * clone spec. Other V8 embedders may throw some other appropriate exception
2288  * type.
2289  */
2290  virtual void ThrowDataCloneError(Local<String> message) = 0;
2291 
2292  /**
2293  * The embedder overrides this method to write some kind of host object, if
2294  * possible. If not, a suitable exception should be thrown and
2295  * Nothing<bool>() returned.
2296  */
2297  virtual Maybe<bool> WriteHostObject(Isolate* isolate, Local<Object> object);
2298 
2299  /**
2300  * Called when the ValueSerializer is going to serialize a
2301  * SharedArrayBuffer object. The embedder must return an ID for the
2302  * object, using the same ID if this SharedArrayBuffer has already been
2303  * serialized in this buffer. When deserializing, this ID will be passed to
2304  * ValueDeserializer::GetSharedArrayBufferFromId as |clone_id|.
2305  *
2306  * If the object cannot be serialized, an
2307  * exception should be thrown and Nothing<uint32_t>() returned.
2308  */
2309  virtual Maybe<uint32_t> GetSharedArrayBufferId(
2310  Isolate* isolate, Local<SharedArrayBuffer> shared_array_buffer);
2311 
2312  virtual Maybe<uint32_t> GetWasmModuleTransferId(
2313  Isolate* isolate, Local<WasmModuleObject> module);
2314  /**
2315  * Allocates memory for the buffer of at least the size provided. The actual
2316  * size (which may be greater or equal) is written to |actual_size|. If no
2317  * buffer has been allocated yet, nullptr will be provided.
2318  *
2319  * If the memory cannot be allocated, nullptr should be returned.
2320  * |actual_size| will be ignored. It is assumed that |old_buffer| is still
2321  * valid in this case and has not been modified.
2322  *
2323  * The default implementation uses the stdlib's `realloc()` function.
2324  */
2325  virtual void* ReallocateBufferMemory(void* old_buffer, size_t size,
2326  size_t* actual_size);
2327 
2328  /**
2329  * Frees a buffer allocated with |ReallocateBufferMemory|.
2330  *
2331  * The default implementation uses the stdlib's `free()` function.
2332  */
2333  virtual void FreeBufferMemory(void* buffer);
2334  };
2335 
2336  explicit ValueSerializer(Isolate* isolate);
2337  ValueSerializer(Isolate* isolate, Delegate* delegate);
2338  ~ValueSerializer();
2339 
2340  /**
2341  * Writes out a header, which includes the format version.
2342  */
2343  void WriteHeader();
2344 
2345  /**
2346  * Serializes a JavaScript value into the buffer.
2347  */
2349  Local<Value> value);
2350 
2351  /**
2352  * Returns the stored data (allocated using the delegate's
2353  * ReallocateBufferMemory) and its size. This serializer should not be used
2354  * once the buffer is released. The contents are undefined if a previous write
2355  * has failed. Ownership of the buffer is transferred to the caller.
2356  */
2357  V8_WARN_UNUSED_RESULT std::pair<uint8_t*, size_t> Release();
2358 
2359  /**
2360  * Marks an ArrayBuffer as havings its contents transferred out of band.
2361  * Pass the corresponding ArrayBuffer in the deserializing context to
2362  * ValueDeserializer::TransferArrayBuffer.
2363  */
2364  void TransferArrayBuffer(uint32_t transfer_id,
2365  Local<ArrayBuffer> array_buffer);
2366 
2367 
2368  /**
2369  * Indicate whether to treat ArrayBufferView objects as host objects,
2370  * i.e. pass them to Delegate::WriteHostObject. This should not be
2371  * called when no Delegate was passed.
2372  *
2373  * The default is not to treat ArrayBufferViews as host objects.
2374  */
2375  void SetTreatArrayBufferViewsAsHostObjects(bool mode);
2376 
2377  /**
2378  * Write raw data in various common formats to the buffer.
2379  * Note that integer types are written in base-128 varint format, not with a
2380  * binary copy. For use during an override of Delegate::WriteHostObject.
2381  */
2382  void WriteUint32(uint32_t value);
2383  void WriteUint64(uint64_t value);
2384  void WriteDouble(double value);
2385  void WriteRawBytes(const void* source, size_t length);
2386 
2387  ValueSerializer(const ValueSerializer&) = delete;
2388  void operator=(const ValueSerializer&) = delete;
2389 
2390  private:
2391  struct PrivateData;
2392  PrivateData* private_;
2393 };
2394 
2395 /**
2396  * Deserializes values from data written with ValueSerializer, or a compatible
2397  * implementation.
2398  */
2400  public:
2402  public:
2403  virtual ~Delegate() = default;
2404 
2405  /**
2406  * The embedder overrides this method to read some kind of host object, if
2407  * possible. If not, a suitable exception should be thrown and
2408  * MaybeLocal<Object>() returned.
2409  */
2410  virtual MaybeLocal<Object> ReadHostObject(Isolate* isolate);
2411 
2412  /**
2413  * Get a WasmModuleObject given a transfer_id previously provided
2414  * by ValueSerializer::GetWasmModuleTransferId
2415  */
2417  Isolate* isolate, uint32_t transfer_id);
2418 
2419  /**
2420  * Get a SharedArrayBuffer given a clone_id previously provided
2421  * by ValueSerializer::GetSharedArrayBufferId
2422  */
2424  Isolate* isolate, uint32_t clone_id);
2425  };
2426 
2427  ValueDeserializer(Isolate* isolate, const uint8_t* data, size_t size);
2428  ValueDeserializer(Isolate* isolate, const uint8_t* data, size_t size,
2429  Delegate* delegate);
2430  ~ValueDeserializer();
2431 
2432  /**
2433  * Reads and validates a header (including the format version).
2434  * May, for example, reject an invalid or unsupported wire format.
2435  */
2437 
2438  /**
2439  * Deserializes a JavaScript value from the buffer.
2440  */
2442 
2443  /**
2444  * Accepts the array buffer corresponding to the one passed previously to
2445  * ValueSerializer::TransferArrayBuffer.
2446  */
2447  void TransferArrayBuffer(uint32_t transfer_id,
2448  Local<ArrayBuffer> array_buffer);
2449 
2450  /**
2451  * Similar to TransferArrayBuffer, but for SharedArrayBuffer.
2452  * The id is not necessarily in the same namespace as unshared ArrayBuffer
2453  * objects.
2454  */
2455  void TransferSharedArrayBuffer(uint32_t id,
2456  Local<SharedArrayBuffer> shared_array_buffer);
2457 
2458  /**
2459  * Must be called before ReadHeader to enable support for reading the legacy
2460  * wire format (i.e., which predates this being shipped).
2461  *
2462  * Don't use this unless you need to read data written by previous versions of
2463  * blink::ScriptValueSerializer.
2464  */
2465  void SetSupportsLegacyWireFormat(bool supports_legacy_wire_format);
2466 
2467  /**
2468  * Expect inline wasm in the data stream (rather than in-memory transfer)
2469  */
2471  "Wasm module serialization is only supported via explicit methods, e.g. "
2472  "CompiledWasmModule::Serialize()")
2473  void SetExpectInlineWasm(bool allow_inline_wasm) {}
2474 
2475  /**
2476  * Reads the underlying wire format version. Likely mostly to be useful to
2477  * legacy code reading old wire format versions. Must be called after
2478  * ReadHeader.
2479  */
2480  uint32_t GetWireFormatVersion() const;
2481 
2482  /**
2483  * Reads raw data in various common formats to the buffer.
2484  * Note that integer types are read in base-128 varint format, not with a
2485  * binary copy. For use during an override of Delegate::ReadHostObject.
2486  */
2487  V8_WARN_UNUSED_RESULT bool ReadUint32(uint32_t* value);
2488  V8_WARN_UNUSED_RESULT bool ReadUint64(uint64_t* value);
2489  V8_WARN_UNUSED_RESULT bool ReadDouble(double* value);
2490  V8_WARN_UNUSED_RESULT bool ReadRawBytes(size_t length, const void** data);
2491 
2492  ValueDeserializer(const ValueDeserializer&) = delete;
2493  void operator=(const ValueDeserializer&) = delete;
2494 
2495  private:
2496  struct PrivateData;
2497  PrivateData* private_;
2498 };
2499 
2500 
2501 // --- Value ---
2502 
2503 
2504 /**
2505  * The superclass of all JavaScript values and objects.
2506  */
2507 class V8_EXPORT Value : public Data {
2508  public:
2509  /**
2510  * Returns true if this value is the undefined value. See ECMA-262
2511  * 4.3.10.
2512  *
2513  * This is equivalent to `value === undefined` in JS.
2514  */
2515  V8_INLINE bool IsUndefined() const;
2516 
2517  /**
2518  * Returns true if this value is the null value. See ECMA-262
2519  * 4.3.11.
2520  *
2521  * This is equivalent to `value === null` in JS.
2522  */
2523  V8_INLINE bool IsNull() const;
2524 
2525  /**
2526  * Returns true if this value is either the null or the undefined value.
2527  * See ECMA-262
2528  * 4.3.11. and 4.3.12
2529  *
2530  * This is equivalent to `value == null` in JS.
2531  */
2532  V8_INLINE bool IsNullOrUndefined() const;
2533 
2534  /**
2535  * Returns true if this value is true.
2536  *
2537  * This is not the same as `BooleanValue()`. The latter performs a
2538  * conversion to boolean, i.e. the result of `Boolean(value)` in JS, whereas
2539  * this checks `value === true`.
2540  */
2541  bool IsTrue() const;
2542 
2543  /**
2544  * Returns true if this value is false.
2545  *
2546  * This is not the same as `!BooleanValue()`. The latter performs a
2547  * conversion to boolean, i.e. the result of `!Boolean(value)` in JS, whereas
2548  * this checks `value === false`.
2549  */
2550  bool IsFalse() const;
2551 
2552  /**
2553  * Returns true if this value is a symbol or a string.
2554  *
2555  * This is equivalent to
2556  * `typeof value === 'string' || typeof value === 'symbol'` in JS.
2557  */
2558  bool IsName() const;
2559 
2560  /**
2561  * Returns true if this value is an instance of the String type.
2562  * See ECMA-262 8.4.
2563  *
2564  * This is equivalent to `typeof value === 'string'` in JS.
2565  */
2566  V8_INLINE bool IsString() const;
2567 
2568  /**
2569  * Returns true if this value is a symbol.
2570  *
2571  * This is equivalent to `typeof value === 'symbol'` in JS.
2572  */
2573  bool IsSymbol() const;
2574 
2575  /**
2576  * Returns true if this value is a function.
2577  *
2578  * This is equivalent to `typeof value === 'function'` in JS.
2579  */
2580  bool IsFunction() const;
2581 
2582  /**
2583  * Returns true if this value is an array. Note that it will return false for
2584  * an Proxy for an array.
2585  */
2586  bool IsArray() const;
2587 
2588  /**
2589  * Returns true if this value is an object.
2590  */
2591  bool IsObject() const;
2592 
2593  /**
2594  * Returns true if this value is a bigint.
2595  *
2596  * This is equivalent to `typeof value === 'bigint'` in JS.
2597  */
2598  bool IsBigInt() const;
2599 
2600  /**
2601  * Returns true if this value is boolean.
2602  *
2603  * This is equivalent to `typeof value === 'boolean'` in JS.
2604  */
2605  bool IsBoolean() const;
2606 
2607  /**
2608  * Returns true if this value is a number.
2609  *
2610  * This is equivalent to `typeof value === 'number'` in JS.
2611  */
2612  bool IsNumber() const;
2613 
2614  /**
2615  * Returns true if this value is an `External` object.
2616  */
2617  bool IsExternal() const;
2618 
2619  /**
2620  * Returns true if this value is a 32-bit signed integer.
2621  */
2622  bool IsInt32() const;
2623 
2624  /**
2625  * Returns true if this value is a 32-bit unsigned integer.
2626  */
2627  bool IsUint32() const;
2628 
2629  /**
2630  * Returns true if this value is a Date.
2631  */
2632  bool IsDate() const;
2633 
2634  /**
2635  * Returns true if this value is an Arguments object.
2636  */
2637  bool IsArgumentsObject() const;
2638 
2639  /**
2640  * Returns true if this value is a BigInt object.
2641  */
2642  bool IsBigIntObject() const;
2643 
2644  /**
2645  * Returns true if this value is a Boolean object.
2646  */
2647  bool IsBooleanObject() const;
2648 
2649  /**
2650  * Returns true if this value is a Number object.
2651  */
2652  bool IsNumberObject() const;
2653 
2654  /**
2655  * Returns true if this value is a String object.
2656  */
2657  bool IsStringObject() const;
2658 
2659  /**
2660  * Returns true if this value is a Symbol object.
2661  */
2662  bool IsSymbolObject() const;
2663 
2664  /**
2665  * Returns true if this value is a NativeError.
2666  */
2667  bool IsNativeError() const;
2668 
2669  /**
2670  * Returns true if this value is a RegExp.
2671  */
2672  bool IsRegExp() const;
2673 
2674  /**
2675  * Returns true if this value is an async function.
2676  */
2677  bool IsAsyncFunction() const;
2678 
2679  /**
2680  * Returns true if this value is a Generator function.
2681  */
2682  bool IsGeneratorFunction() const;
2683 
2684  /**
2685  * Returns true if this value is a Generator object (iterator).
2686  */
2687  bool IsGeneratorObject() const;
2688 
2689  /**
2690  * Returns true if this value is a Promise.
2691  */
2692  bool IsPromise() const;
2693 
2694  /**
2695  * Returns true if this value is a Map.
2696  */
2697  bool IsMap() const;
2698 
2699  /**
2700  * Returns true if this value is a Set.
2701  */
2702  bool IsSet() const;
2703 
2704  /**
2705  * Returns true if this value is a Map Iterator.
2706  */
2707  bool IsMapIterator() const;
2708 
2709  /**
2710  * Returns true if this value is a Set Iterator.
2711  */
2712  bool IsSetIterator() const;
2713 
2714  /**
2715  * Returns true if this value is a WeakMap.
2716  */
2717  bool IsWeakMap() const;
2718 
2719  /**
2720  * Returns true if this value is a WeakSet.
2721  */
2722  bool IsWeakSet() const;
2723 
2724  /**
2725  * Returns true if this value is an ArrayBuffer.
2726  */
2727  bool IsArrayBuffer() const;
2728 
2729  /**
2730  * Returns true if this value is an ArrayBufferView.
2731  */
2732  bool IsArrayBufferView() const;
2733 
2734  /**
2735  * Returns true if this value is one of TypedArrays.
2736  */
2737  bool IsTypedArray() const;
2738 
2739  /**
2740  * Returns true if this value is an Uint8Array.
2741  */
2742  bool IsUint8Array() const;
2743 
2744  /**
2745  * Returns true if this value is an Uint8ClampedArray.
2746  */
2747  bool IsUint8ClampedArray() const;
2748 
2749  /**
2750  * Returns true if this value is an Int8Array.
2751  */
2752  bool IsInt8Array() const;
2753 
2754  /**
2755  * Returns true if this value is an Uint16Array.
2756  */
2757  bool IsUint16Array() const;
2758 
2759  /**
2760  * Returns true if this value is an Int16Array.
2761  */
2762  bool IsInt16Array() const;
2763 
2764  /**
2765  * Returns true if this value is an Uint32Array.
2766  */
2767  bool IsUint32Array() const;
2768 
2769  /**
2770  * Returns true if this value is an Int32Array.
2771  */
2772  bool IsInt32Array() const;
2773 
2774  /**
2775  * Returns true if this value is a Float32Array.
2776  */
2777  bool IsFloat32Array() const;
2778 
2779  /**
2780  * Returns true if this value is a Float64Array.
2781  */
2782  bool IsFloat64Array() const;
2783 
2784  /**
2785  * Returns true if this value is a BigInt64Array.
2786  */
2787  bool IsBigInt64Array() const;
2788 
2789  /**
2790  * Returns true if this value is a BigUint64Array.
2791  */
2792  bool IsBigUint64Array() const;
2793 
2794  /**
2795  * Returns true if this value is a DataView.
2796  */
2797  bool IsDataView() const;
2798 
2799  /**
2800  * Returns true if this value is a SharedArrayBuffer.
2801  */
2802  bool IsSharedArrayBuffer() const;
2803 
2804  /**
2805  * Returns true if this value is a JavaScript Proxy.
2806  */
2807  bool IsProxy() const;
2808 
2809  /**
2810  * Returns true if this value is a WasmModuleObject.
2811  */
2812  bool IsWasmModuleObject() const;
2813 
2814  V8_DEPRECATED("Use IsWasmModuleObject")
2815  bool IsWebAssemblyCompiledModule() const;
2816 
2817  /**
2818  * Returns true if the value is a Module Namespace Object.
2819  */
2820  bool IsModuleNamespaceObject() const;
2821 
2822  /**
2823  * Perform the equivalent of `BigInt(value)` in JS.
2824  */
2826  Local<Context> context) const;
2827  /**
2828  * Perform the equivalent of `Number(value)` in JS.
2829  */
2831  Local<Context> context) const;
2832  /**
2833  * Perform the equivalent of `String(value)` in JS.
2834  */
2836  Local<Context> context) const;
2837  /**
2838  * Provide a string representation of this value usable for debugging.
2839  * This operation has no observable side effects and will succeed
2840  * unless e.g. execution is being terminated.
2841  */
2843  Local<Context> context) const;
2844  /**
2845  * Perform the equivalent of `Object(value)` in JS.
2846  */
2848  Local<Context> context) const;
2849  /**
2850  * Perform the equivalent of `Number(value)` in JS and convert the result
2851  * to an integer. Negative values are rounded up, positive values are rounded
2852  * down. NaN is converted to 0. Infinite values yield undefined results.
2853  */
2855  Local<Context> context) const;
2856  /**
2857  * Perform the equivalent of `Number(value)` in JS and convert the result
2858  * to an unsigned 32-bit integer by performing the steps in
2859  * https://tc39.es/ecma262/#sec-touint32.
2860  */
2862  Local<Context> context) const;
2863  /**
2864  * Perform the equivalent of `Number(value)` in JS and convert the result
2865  * to a signed 32-bit integer by performing the steps in
2866  * https://tc39.es/ecma262/#sec-toint32.
2867  */
2869 
2870  /**
2871  * Perform the equivalent of `Boolean(value)` in JS. This can never fail.
2872  */
2873  Local<Boolean> ToBoolean(Isolate* isolate) const;
2874 
2875  /**
2876  * Attempts to convert a string to an array index.
2877  * Returns an empty handle if the conversion fails.
2878  */
2880  Local<Context> context) const;
2881 
2882  /** Returns the equivalent of `ToBoolean()->Value()`. */
2883  bool BooleanValue(Isolate* isolate) const;
2884 
2885  /** Returns the equivalent of `ToNumber()->Value()`. */
2886  V8_WARN_UNUSED_RESULT Maybe<double> NumberValue(Local<Context> context) const;
2887  /** Returns the equivalent of `ToInteger()->Value()`. */
2889  Local<Context> context) const;
2890  /** Returns the equivalent of `ToUint32()->Value()`. */
2892  Local<Context> context) const;
2893  /** Returns the equivalent of `ToInt32()->Value()`. */
2894  V8_WARN_UNUSED_RESULT Maybe<int32_t> Int32Value(Local<Context> context) const;
2895 
2896  /** JS == */
2898  Local<Value> that) const;
2899  bool StrictEquals(Local<Value> that) const;
2900  bool SameValue(Local<Value> that) const;
2901 
2902  template <class T> V8_INLINE static Value* Cast(T* value);
2903 
2905 
2906  Maybe<bool> InstanceOf(Local<Context> context, Local<Object> object);
2907 
2908  private:
2909  V8_INLINE bool QuickIsUndefined() const;
2910  V8_INLINE bool QuickIsNull() const;
2911  V8_INLINE bool QuickIsNullOrUndefined() const;
2912  V8_INLINE bool QuickIsString() const;
2913  bool FullIsUndefined() const;
2914  bool FullIsNull() const;
2915  bool FullIsString() const;
2916 };
2917 
2918 
2919 /**
2920  * The superclass of primitive values. See ECMA-262 4.3.2.
2921  */
2922 class V8_EXPORT Primitive : public Value { };
2923 
2924 
2925 /**
2926  * A primitive boolean value (ECMA-262, 4.3.14). Either the true
2927  * or false value.
2928  */
2929 class V8_EXPORT Boolean : public Primitive {
2930  public:
2931  bool Value() const;
2932  V8_INLINE static Boolean* Cast(v8::Value* obj);
2933  V8_INLINE static Local<Boolean> New(Isolate* isolate, bool value);
2934 
2935  private:
2936  static void CheckCast(v8::Value* obj);
2937 };
2938 
2939 
2940 /**
2941  * A superclass for symbols and strings.
2942  */
2943 class V8_EXPORT Name : public Primitive {
2944  public:
2945  /**
2946  * Returns the identity hash for this object. The current implementation
2947  * uses an inline property on the object to store the identity hash.
2948  *
2949  * The return value will never be 0. Also, it is not guaranteed to be
2950  * unique.
2951  */
2952  int GetIdentityHash();
2953 
2954  V8_INLINE static Name* Cast(Value* obj);
2955 
2956  private:
2957  static void CheckCast(Value* obj);
2958 };
2959 
2960 /**
2961  * A flag describing different modes of string creation.
2962  *
2963  * Aside from performance implications there are no differences between the two
2964  * creation modes.
2965  */
2966 enum class NewStringType {
2967  /**
2968  * Create a new string, always allocating new storage memory.
2969  */
2970  kNormal,
2971 
2972  /**
2973  * Acts as a hint that the string should be created in the
2974  * old generation heap space and be deduplicated if an identical string
2975  * already exists.
2976  */
2978 };
2979 
2980 /**
2981  * A JavaScript string value (ECMA-262, 4.3.17).
2982  */
2983 class V8_EXPORT String : public Name {
2984  public:
2985  static constexpr int kMaxLength = internal::kApiTaggedSize == 4
2986  ? (1 << 28) - 16
2987  : internal::kSmiMaxValue / 2 - 24;
2988 
2989  enum Encoding {
2993  };
2994  /**
2995  * Returns the number of characters (UTF-16 code units) in this string.
2996  */
2997  int Length() const;
2998 
2999  /**
3000  * Returns the number of bytes in the UTF-8 encoded
3001  * representation of this string.
3002  */
3003  int Utf8Length(Isolate* isolate) const;
3004 
3005  /**
3006  * Returns whether this string is known to contain only one byte data,
3007  * i.e. ISO-8859-1 code points.
3008  * Does not read the string.
3009  * False negatives are possible.
3010  */
3011  bool IsOneByte() const;
3012 
3013  /**
3014  * Returns whether this string contain only one byte data,
3015  * i.e. ISO-8859-1 code points.
3016  * Will read the entire string in some cases.
3017  */
3018  bool ContainsOnlyOneByte() const;
3019 
3020  /**
3021  * Write the contents of the string to an external buffer.
3022  * If no arguments are given, expects the buffer to be large
3023  * enough to hold the entire string and NULL terminator. Copies
3024  * the contents of the string and the NULL terminator into the
3025  * buffer.
3026  *
3027  * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
3028  * before the end of the buffer.
3029  *
3030  * Copies up to length characters into the output buffer.
3031  * Only null-terminates if there is enough space in the buffer.
3032  *
3033  * \param buffer The buffer into which the string will be copied.
3034  * \param start The starting position within the string at which
3035  * copying begins.
3036  * \param length The number of characters to copy from the string. For
3037  * WriteUtf8 the number of bytes in the buffer.
3038  * \param nchars_ref The number of characters written, can be NULL.
3039  * \param options Various options that might affect performance of this or
3040  * subsequent operations.
3041  * \return The number of characters copied to the buffer excluding the null
3042  * terminator. For WriteUtf8: The number of bytes copied to the buffer
3043  * including the null terminator (if written).
3044  */
3050  // Used by WriteUtf8 to replace orphan surrogate code units with the
3051  // unicode replacement character. Needs to be set to guarantee valid UTF-8
3052  // output.
3054  };
3055 
3056  // 16-bit character codes.
3057  int Write(Isolate* isolate, uint16_t* buffer, int start = 0, int length = -1,
3058  int options = NO_OPTIONS) const;
3059  // One byte characters.
3060  int WriteOneByte(Isolate* isolate, uint8_t* buffer, int start = 0,
3061  int length = -1, int options = NO_OPTIONS) const;
3062  // UTF-8 encoded characters.
3063  int WriteUtf8(Isolate* isolate, char* buffer, int length = -1,
3064  int* nchars_ref = nullptr, int options = NO_OPTIONS) const;
3065 
3066  /**
3067  * A zero length string.
3068  */
3069  V8_INLINE static Local<String> Empty(Isolate* isolate);
3070 
3071  /**
3072  * Returns true if the string is external
3073  */
3074  bool IsExternal() const;
3075 
3076  /**
3077  * Returns true if the string is both external and one-byte.
3078  */
3079  bool IsExternalOneByte() const;
3080 
3082  public:
3083  virtual ~ExternalStringResourceBase() = default;
3084 
3085  /**
3086  * If a string is cacheable, the value returned by
3087  * ExternalStringResource::data() may be cached, otherwise it is not
3088  * expected to be stable beyond the current top-level task.
3089  */
3090  virtual bool IsCacheable() const { return true; }
3091 
3092  // Disallow copying and assigning.
3094  void operator=(const ExternalStringResourceBase&) = delete;
3095 
3096  protected:
3097  ExternalStringResourceBase() = default;
3098 
3099  /**
3100  * Internally V8 will call this Dispose method when the external string
3101  * resource is no longer needed. The default implementation will use the
3102  * delete operator. This method can be overridden in subclasses to
3103  * control how allocated external string resources are disposed.
3104  */
3105  virtual void Dispose() { delete this; }
3106 
3107  /**
3108  * For a non-cacheable string, the value returned by
3109  * |ExternalStringResource::data()| has to be stable between |Lock()| and
3110  * |Unlock()|, that is the string must behave as is |IsCacheable()| returned
3111  * true.
3112  *
3113  * These two functions must be thread-safe, and can be called from anywhere.
3114  * They also must handle lock depth, in the sense that each can be called
3115  * several times, from different threads, and unlocking should only happen
3116  * when the balance of Lock() and Unlock() calls is 0.
3117  */
3118  virtual void Lock() const {}
3119 
3120  /**
3121  * Unlocks the string.
3122  */
3123  virtual void Unlock() const {}
3124 
3125  private:
3126  friend class internal::ExternalString;
3127  friend class v8::String;
3128  friend class internal::ScopedExternalStringLock;
3129  };
3130 
3131  /**
3132  * An ExternalStringResource is a wrapper around a two-byte string
3133  * buffer that resides outside V8's heap. Implement an
3134  * ExternalStringResource to manage the life cycle of the underlying
3135  * buffer. Note that the string data must be immutable.
3136  */
3138  : public ExternalStringResourceBase {
3139  public:
3140  /**
3141  * Override the destructor to manage the life cycle of the underlying
3142  * buffer.
3143  */
3144  ~ExternalStringResource() override = default;
3145 
3146  /**
3147  * The string data from the underlying buffer.
3148  */
3149  virtual const uint16_t* data() const = 0;
3150 
3151  /**
3152  * The length of the string. That is, the number of two-byte characters.
3153  */
3154  virtual size_t length() const = 0;
3155 
3156  protected:
3157  ExternalStringResource() = default;
3158  };
3159 
3160  /**
3161  * An ExternalOneByteStringResource is a wrapper around an one-byte
3162  * string buffer that resides outside V8's heap. Implement an
3163  * ExternalOneByteStringResource to manage the life cycle of the
3164  * underlying buffer. Note that the string data must be immutable
3165  * and that the data must be Latin-1 and not UTF-8, which would require
3166  * special treatment internally in the engine and do not allow efficient
3167  * indexing. Use String::New or convert to 16 bit data for non-Latin1.
3168  */
3169 
3171  : public ExternalStringResourceBase {
3172  public:
3173  /**
3174  * Override the destructor to manage the life cycle of the underlying
3175  * buffer.
3176  */
3177  ~ExternalOneByteStringResource() override = default;
3178  /** The string data from the underlying buffer.*/
3179  virtual const char* data() const = 0;
3180  /** The number of Latin-1 characters in the string.*/
3181  virtual size_t length() const = 0;
3182  protected:
3183  ExternalOneByteStringResource() = default;
3184  };
3185 
3186  /**
3187  * If the string is an external string, return the ExternalStringResourceBase
3188  * regardless of the encoding, otherwise return NULL. The encoding of the
3189  * string is returned in encoding_out.
3190  */
3192  Encoding* encoding_out) const;
3193 
3194  /**
3195  * Get the ExternalStringResource for an external string. Returns
3196  * NULL if IsExternal() doesn't return true.
3197  */
3199 
3200  /**
3201  * Get the ExternalOneByteStringResource for an external one-byte string.
3202  * Returns NULL if IsExternalOneByte() doesn't return true.
3203  */
3205 
3206  V8_INLINE static String* Cast(v8::Value* obj);
3207 
3208  /** Allocates a new string from UTF-8 data. Only returns an empty value when
3209  * length > kMaxLength. **/
3211  Isolate* isolate, const char* data,
3212  NewStringType type = NewStringType::kNormal, int length = -1);
3213 
3214  /** Allocates a new string from Latin-1 data. Only returns an empty value
3215  * when length > kMaxLength. **/
3217  Isolate* isolate, const uint8_t* data,
3218  NewStringType type = NewStringType::kNormal, int length = -1);
3219 
3220  /** Allocates a new string from UTF-16 data. Only returns an empty value when
3221  * length > kMaxLength. **/
3223  Isolate* isolate, const uint16_t* data,
3224  NewStringType type = NewStringType::kNormal, int length = -1);
3225 
3226  /**
3227  * Creates a new string by concatenating the left and the right strings
3228  * passed in as parameters.
3229  */
3230  static Local<String> Concat(Isolate* isolate, Local<String> left,
3231  Local<String> right);
3232 
3233  /**
3234  * Creates a new external string using the data defined in the given
3235  * resource. When the external string is no longer live on V8's heap the
3236  * resource will be disposed by calling its Dispose method. The caller of
3237  * this function should not otherwise delete or modify the resource. Neither
3238  * should the underlying buffer be deallocated or modified except through the
3239  * destructor of the external string resource.
3240  */
3242  Isolate* isolate, ExternalStringResource* resource);
3243 
3244  /**
3245  * Associate an external string resource with this string by transforming it
3246  * in place so that existing references to this string in the JavaScript heap
3247  * will use the external string resource. The external string resource's
3248  * character contents need to be equivalent to this string.
3249  * Returns true if the string has been changed to be an external string.
3250  * The string is not modified if the operation fails. See NewExternal for
3251  * information on the lifetime of the resource.
3252  */
3253  bool MakeExternal(ExternalStringResource* resource);
3254 
3255  /**
3256  * Creates a new external string using the one-byte data defined in the given
3257  * resource. When the external string is no longer live on V8's heap the
3258  * resource will be disposed by calling its Dispose method. The caller of
3259  * this function should not otherwise delete or modify the resource. Neither
3260  * should the underlying buffer be deallocated or modified except through the
3261  * destructor of the external string resource.
3262  */
3264  Isolate* isolate, ExternalOneByteStringResource* resource);
3265 
3266  /**
3267  * Associate an external string resource with this string by transforming it
3268  * in place so that existing references to this string in the JavaScript heap
3269  * will use the external string resource. The external string resource's
3270  * character contents need to be equivalent to this string.
3271  * Returns true if the string has been changed to be an external string.
3272  * The string is not modified if the operation fails. See NewExternal for
3273  * information on the lifetime of the resource.
3274  */
3276 
3277  /**
3278  * Returns true if this string can be made external.
3279  */
3280  bool CanMakeExternal();
3281 
3282  /**
3283  * Returns true if the strings values are equal. Same as JS ==/===.
3284  */
3285  bool StringEquals(Local<String> str);
3286 
3287  /**
3288  * Converts an object to a UTF-8-encoded character array. Useful if
3289  * you want to print the object. If conversion to a string fails
3290  * (e.g. due to an exception in the toString() method of the object)
3291  * then the length() method returns 0 and the * operator returns
3292  * NULL.
3293  */
3295  public:
3296  Utf8Value(Isolate* isolate, Local<v8::Value> obj);
3297  ~Utf8Value();
3298  char* operator*() { return str_; }
3299  const char* operator*() const { return str_; }
3300  int length() const { return length_; }
3301 
3302  // Disallow copying and assigning.
3303  Utf8Value(const Utf8Value&) = delete;
3304  void operator=(const Utf8Value&) = delete;
3305 
3306  private:
3307  char* str_;
3308  int length_;
3309  };
3310 
3311  /**
3312  * Converts an object to a two-byte (UTF-16-encoded) string.
3313  * If conversion to a string fails (eg. due to an exception in the toString()
3314  * method of the object) then the length() method returns 0 and the * operator
3315  * returns NULL.
3316  */
3318  public:
3319  Value(Isolate* isolate, Local<v8::Value> obj);
3320  ~Value();
3321  uint16_t* operator*() { return str_; }
3322  const uint16_t* operator*() const { return str_; }
3323  int length() const { return length_; }
3324 
3325  // Disallow copying and assigning.
3326  Value(const Value&) = delete;
3327  void operator=(const Value&) = delete;
3328 
3329  private:
3330  uint16_t* str_;
3331  int length_;
3332  };
3333 
3334  private:
3335  void VerifyExternalStringResourceBase(ExternalStringResourceBase* v,
3336  Encoding encoding) const;
3337  void VerifyExternalStringResource(ExternalStringResource* val) const;
3338  ExternalStringResource* GetExternalStringResourceSlow() const;
3339  ExternalStringResourceBase* GetExternalStringResourceBaseSlow(
3340  String::Encoding* encoding_out) const;
3341 
3342  static void CheckCast(v8::Value* obj);
3343 };
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  * Call an Object as a function if a callback is set by the
4053  * ObjectTemplate::SetCallAsFunctionHandler method.
4054  */
4056  Local<Value> recv,
4057  int argc,
4058  Local<Value> argv[]);
4059 
4060  /**
4061  * Call an Object as a constructor if a callback is set by the
4062  * ObjectTemplate::SetCallAsFunctionHandler method.
4063  * Note: This method behaves like the Function::NewInstance method.
4064  */
4066  Local<Context> context, int argc, Local<Value> argv[]);
4067 
4068  /**
4069  * Return the isolate to which the Object belongs to.
4070  */
4071  Isolate* GetIsolate();
4072 
4073  /**
4074  * If this object is a Set, Map, WeakSet or WeakMap, this returns a
4075  * representation of the elements of this object as an array.
4076  * If this object is a SetIterator or MapIterator, this returns all
4077  * elements of the underlying collection, starting at the iterator's current
4078  * position.
4079  * For other types, this will return an empty MaybeLocal<Array> (without
4080  * scheduling an exception).
4081  */
4082  MaybeLocal<Array> PreviewEntries(bool* is_key_value);
4083 
4084  static Local<Object> New(Isolate* isolate);
4085 
4086  /**
4087  * Creates a JavaScript object with the given properties, and
4088  * a the given prototype_or_null (which can be any JavaScript
4089  * value, and if it's null, the newly created object won't have
4090  * a prototype at all). This is similar to Object.create().
4091  * All properties will be created as enumerable, configurable
4092  * and writable properties.
4093  */
4094  static Local<Object> New(Isolate* isolate, Local<Value> prototype_or_null,
4095  Local<Name>* names, Local<Value>* values,
4096  size_t length);
4097 
4098  V8_INLINE static Object* Cast(Value* obj);
4099 
4100  private:
4101  Object();
4102  static void CheckCast(Value* obj);
4103  Local<Value> SlowGetInternalField(int index);
4104  void* SlowGetAlignedPointerFromInternalField(int index);
4105 };
4106 
4107 
4108 /**
4109  * An instance of the built-in array constructor (ECMA-262, 15.4.2).
4110  */
4111 class V8_EXPORT Array : public Object {
4112  public:
4113  uint32_t Length() const;
4114 
4115  /**
4116  * Creates a JavaScript array with the given length. If the length
4117  * is negative the returned array will have length 0.
4118  */
4119  static Local<Array> New(Isolate* isolate, int length = 0);
4120 
4121  /**
4122  * Creates a JavaScript array out of a Local<Value> array in C++
4123  * with a known length.
4124  */
4125  static Local<Array> New(Isolate* isolate, Local<Value>* elements,
4126  size_t length);
4127  V8_INLINE static Array* Cast(Value* obj);
4128  private:
4129  Array();
4130  static void CheckCast(Value* obj);
4131 };
4132 
4133 
4134 /**
4135  * An instance of the built-in Map constructor (ECMA-262, 6th Edition, 23.1.1).
4136  */
4137 class V8_EXPORT Map : public Object {
4138  public:
4139  size_t Size() const;
4140  void Clear();
4142  Local<Value> key);
4144  Local<Value> key,
4145  Local<Value> value);
4146  V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
4147  Local<Value> key);
4149  Local<Value> key);
4150 
4151  /**
4152  * Returns an array of length Size() * 2, where index N is the Nth key and
4153  * index N + 1 is the Nth value.
4154  */
4155  Local<Array> AsArray() const;
4156 
4157  /**
4158  * Creates a new empty Map.
4159  */
4160  static Local<Map> New(Isolate* isolate);
4161 
4162  V8_INLINE static Map* Cast(Value* obj);
4163 
4164  private:
4165  Map();
4166  static void CheckCast(Value* obj);
4167 };
4168 
4169 
4170 /**
4171  * An instance of the built-in Set constructor (ECMA-262, 6th Edition, 23.2.1).
4172  */
4173 class V8_EXPORT Set : public Object {
4174  public:
4175  size_t Size() const;
4176  void Clear();
4178  Local<Value> key);
4179  V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
4180  Local<Value> key);
4182  Local<Value> key);
4183 
4184  /**
4185  * Returns an array of the keys in this Set.
4186  */
4187  Local<Array> AsArray() const;
4188 
4189  /**
4190  * Creates a new empty Set.
4191  */
4192  static Local<Set> New(Isolate* isolate);
4193 
4194  V8_INLINE static Set* Cast(Value* obj);
4195 
4196  private:
4197  Set();
4198  static void CheckCast(Value* obj);
4199 };
4200 
4201 
4202 template<typename T>
4203 class ReturnValue {
4204  public:
4205  template <class S> V8_INLINE ReturnValue(const ReturnValue<S>& that)
4206  : value_(that.value_) {
4207  TYPE_CHECK(T, S);
4208  }
4209  // Local setters
4210  template <typename S>
4211  V8_INLINE void Set(const Global<S>& handle);
4212  template <typename S>
4213  V8_INLINE void Set(const TracedReferenceBase<S>& handle);
4214  template <typename S>
4215  V8_INLINE void Set(const Local<S> handle);
4216  // Fast primitive setters
4217  V8_INLINE void Set(bool value);
4218  V8_INLINE void Set(double i);
4219  V8_INLINE void Set(int32_t i);
4220  V8_INLINE void Set(uint32_t i);
4221  // Fast JS primitive setters
4222  V8_INLINE void SetNull();
4223  V8_INLINE void SetUndefined();
4224  V8_INLINE void SetEmptyString();
4225  // Convenience getter for Isolate
4226  V8_INLINE Isolate* GetIsolate() const;
4227 
4228  // Pointer setter: Uncompilable to prevent inadvertent misuse.
4229  template <typename S>
4230  V8_INLINE void Set(S* whatever);
4231 
4232  // Getter. Creates a new Local<> so it comes with a certain performance
4233  // hit. If the ReturnValue was not yet set, this will return the undefined
4234  // value.
4235  V8_INLINE Local<Value> Get() const;
4236 
4237  private:
4238  template<class F> friend class ReturnValue;
4239  template<class F> friend class FunctionCallbackInfo;
4240  template<class F> friend class PropertyCallbackInfo;
4241  template <class F, class G, class H>
4243  V8_INLINE void SetInternal(internal::Address value) { *value_ = value; }
4244  V8_INLINE internal::Address GetDefaultValue();
4245  V8_INLINE explicit ReturnValue(internal::Address* slot);
4246  internal::Address* value_;
4247 };
4248 
4249 
4250 /**
4251  * The argument information given to function call callbacks. This
4252  * class provides access to information about the context of the call,
4253  * including the receiver, the number and values of arguments, and
4254  * the holder of the function.
4255  */
4256 template<typename T>
4257 class FunctionCallbackInfo {
4258  public:
4259  /** The number of available arguments. */
4260  V8_INLINE int Length() const;
4261  /**
4262  * Accessor for the available arguments. Returns `undefined` if the index
4263  * is out of bounds.
4264  */
4265  V8_INLINE Local<Value> operator[](int i) const;
4266  /** Returns the receiver. This corresponds to the "this" value. */
4267  V8_INLINE Local<Object> This() const;
4268  /**
4269  * If the callback was created without a Signature, this is the same
4270  * value as This(). If there is a signature, and the signature didn't match
4271  * This() but one of its hidden prototypes, this will be the respective
4272  * hidden prototype.
4273  *
4274  * Note that this is not the prototype of This() on which the accessor
4275  * referencing this callback was found (which in V8 internally is often
4276  * referred to as holder [sic]).
4277  */
4278  V8_INLINE Local<Object> Holder() const;
4279  /** For construct calls, this returns the "new.target" value. */
4280  V8_INLINE Local<Value> NewTarget() const;
4281  /** Indicates whether this is a regular call or a construct call. */
4282  V8_INLINE bool IsConstructCall() const;
4283  /** The data argument specified when creating the callback. */
4284  V8_INLINE Local<Value> Data() const;
4285  /** The current Isolate. */
4286  V8_INLINE Isolate* GetIsolate() const;
4287  /** The ReturnValue for the call. */
4289  // This shouldn't be public, but the arm compiler needs it.
4290  static const int kArgsLength = 6;
4291 
4292  protected:
4293  friend class internal::FunctionCallbackArguments;
4295  friend class debug::ConsoleCallArguments;
4296  static const int kHolderIndex = 0;
4297  static const int kIsolateIndex = 1;
4298  static const int kReturnValueDefaultValueIndex = 2;
4299  static const int kReturnValueIndex = 3;
4300  static const int kDataIndex = 4;
4301  static const int kNewTargetIndex = 5;
4302 
4304  internal::Address* values, int length);
4307  int length_;
4308 };
4309 
4310 
4311 /**
4312  * The information passed to a property callback about the context
4313  * of the property access.
4314  */
4315 template<typename T>
4316 class PropertyCallbackInfo {
4317  public:
4318  /**
4319  * \return The isolate of the property access.
4320  */
4321  V8_INLINE Isolate* GetIsolate() const;
4322 
4323  /**
4324  * \return The data set in the configuration, i.e., in
4325  * `NamedPropertyHandlerConfiguration` or
4326  * `IndexedPropertyHandlerConfiguration.`
4327  */
4328  V8_INLINE Local<Value> Data() const;
4329 
4330  /**
4331  * \return The receiver. In many cases, this is the object on which the
4332  * property access was intercepted. When using
4333  * `Reflect.get`, `Function.prototype.call`, or similar functions, it is the
4334  * object passed in as receiver or thisArg.
4335  *
4336  * \code
4337  * void GetterCallback(Local<Name> name,
4338  * const v8::PropertyCallbackInfo<v8::Value>& info) {
4339  * auto context = info.GetIsolate()->GetCurrentContext();
4340  *
4341  * v8::Local<v8::Value> a_this =
4342  * info.This()
4343  * ->GetRealNamedProperty(context, v8_str("a"))
4344  * .ToLocalChecked();
4345  * v8::Local<v8::Value> a_holder =
4346  * info.Holder()
4347  * ->GetRealNamedProperty(context, v8_str("a"))
4348  * .ToLocalChecked();
4349  *
4350  * CHECK(v8_str("r")->Equals(context, a_this).FromJust());
4351  * CHECK(v8_str("obj")->Equals(context, a_holder).FromJust());
4352  *
4353  * info.GetReturnValue().Set(name);
4354  * }
4355  *
4356  * v8::Local<v8::FunctionTemplate> templ =
4357  * v8::FunctionTemplate::New(isolate);
4358  * templ->InstanceTemplate()->SetHandler(
4359  * v8::NamedPropertyHandlerConfiguration(GetterCallback));
4360  * LocalContext env;
4361  * env->Global()
4362  * ->Set(env.local(), v8_str("obj"), templ->GetFunction(env.local())
4363  * .ToLocalChecked()
4364  * ->NewInstance(env.local())
4365  * .ToLocalChecked())
4366  * .FromJust();
4367  *
4368  * CompileRun("obj.a = 'obj'; var r = {a: 'r'}; Reflect.get(obj, 'x', r)");
4369  * \endcode
4370  */
4371  V8_INLINE Local<Object> This() const;
4372 
4373  /**
4374  * \return The object in the prototype chain of the receiver that has the
4375  * interceptor. Suppose you have `x` and its prototype is `y`, and `y`
4376  * has an interceptor. Then `info.This()` is `x` and `info.Holder()` is `y`.
4377  * The Holder() could be a hidden object (the global object, rather
4378  * than the global proxy).
4379  *
4380  * \note For security reasons, do not pass the object back into the runtime.
4381  */
4382  V8_INLINE Local<Object> Holder() const;
4383 
4384  /**
4385  * \return The return value of the callback.
4386  * Can be changed by calling Set().
4387  * \code
4388  * info.GetReturnValue().Set(...)
4389  * \endcode
4390  *
4391  */
4393 
4394  /**
4395  * \return True if the intercepted function should throw if an error occurs.
4396  * Usually, `true` corresponds to `'use strict'`.
4397  *
4398  * \note Always `false` when intercepting `Reflect.set()`
4399  * independent of the language mode.
4400  */
4401  V8_INLINE bool ShouldThrowOnError() const;
4402 
4403  // This shouldn't be public, but the arm compiler needs it.
4404  static const int kArgsLength = 7;
4405 
4406  protected:
4407  friend class MacroAssembler;
4408  friend class internal::PropertyCallbackArguments;
4410  static const int kShouldThrowOnErrorIndex = 0;
4411  static const int kHolderIndex = 1;
4412  static const int kIsolateIndex = 2;
4413  static const int kReturnValueDefaultValueIndex = 3;
4414  static const int kReturnValueIndex = 4;
4415  static const int kDataIndex = 5;
4416  static const int kThisIndex = 6;
4417 
4420 };
4421 
4422 
4423 typedef void (*FunctionCallback)(const FunctionCallbackInfo<Value>& info);
4424 
4426 
4427 /**
4428  * A JavaScript function object (ECMA-262, 15.3).
4429  */
4430 class V8_EXPORT Function : public Object {
4431  public:
4432  /**
4433  * Create a function in the current execution context
4434  * for a given FunctionCallback.
4435  */
4436  static MaybeLocal<Function> New(
4437  Local<Context> context, FunctionCallback callback,
4438  Local<Value> data = Local<Value>(), int length = 0,
4440  SideEffectType side_effect_type = SideEffectType::kHasSideEffect);
4441 
4443  Local<Context> context, int argc, Local<Value> argv[]) const;
4444 
4446  Local<Context> context) const {
4447  return NewInstance(context, 0, nullptr);
4448  }
4449 
4450  /**
4451  * When side effect checks are enabled, passing kHasNoSideEffect allows the
4452  * constructor to be invoked without throwing. Calls made within the
4453  * constructor are still checked.
4454  */
4456  Local<Context> context, int argc, Local<Value> argv[],
4457  SideEffectType side_effect_type = SideEffectType::kHasSideEffect) const;
4458 
4460  Local<Value> recv, int argc,
4461  Local<Value> argv[]);
4462 
4463  void SetName(Local<String> name);
4464  Local<Value> GetName() const;
4465 
4466  /**
4467  * Name inferred from variable or property assignment of this function.
4468  * Used to facilitate debugging and profiling of JavaScript code written
4469  * in an OO style, where many functions are anonymous but are assigned
4470  * to object properties.
4471  */
4472  Local<Value> GetInferredName() const;
4473 
4474  /**
4475  * displayName if it is set, otherwise name if it is configured, otherwise
4476  * function name, otherwise inferred name.
4477  */
4478  Local<Value> GetDebugName() const;
4479 
4480  /**
4481  * User-defined name assigned to the "displayName" property of this function.
4482  * Used to facilitate debugging and profiling of JavaScript code.
4483  */
4484  Local<Value> GetDisplayName() const;
4485 
4486  /**
4487  * Returns zero based line number of function body and
4488  * kLineOffsetNotFound if no information available.
4489  */
4490  int GetScriptLineNumber() const;
4491  /**
4492  * Returns zero based column number of function body and
4493  * kLineOffsetNotFound if no information available.
4494  */
4495  int GetScriptColumnNumber() const;
4496 
4497  /**
4498  * Returns scriptId.
4499  */
4500  int ScriptId() const;
4501 
4502  /**
4503  * Returns the original function if this function is bound, else returns
4504  * v8::Undefined.
4505  */
4506  Local<Value> GetBoundFunction() const;
4507 
4508  ScriptOrigin GetScriptOrigin() const;
4509  V8_INLINE static Function* Cast(Value* obj);
4510  static const int kLineOffsetNotFound;
4511 
4512  private:
4513  Function();
4514  static void CheckCast(Value* obj);
4515 };
4516 
4517 #ifndef V8_PROMISE_INTERNAL_FIELD_COUNT
4518 // The number of required internal fields can be defined by embedder.
4519 #define V8_PROMISE_INTERNAL_FIELD_COUNT 0
4520 #endif
4521 
4522 /**
4523  * An instance of the built-in Promise constructor (ES6 draft).
4524  */
4525 class V8_EXPORT Promise : public Object {
4526  public:
4527  /**
4528  * State of the promise. Each value corresponds to one of the possible values
4529  * of the [[PromiseState]] field.
4530  */
4532 
4533  class V8_EXPORT Resolver : public Object {
4534  public:
4535  /**
4536  * Create a new resolver, along with an associated promise in pending state.
4537  */
4539  Local<Context> context);
4540 
4541  /**
4542  * Extract the associated promise.
4543  */
4545 
4546  /**
4547  * Resolve/reject the associated promise with a given value.
4548  * Ignored if the promise is no longer pending.
4549  */
4551  Local<Value> value);
4552 
4554  Local<Value> value);
4555 
4556  V8_INLINE static Resolver* Cast(Value* obj);
4557 
4558  private:
4559  Resolver();
4560  static void CheckCast(Value* obj);
4561  };
4562 
4563  /**
4564  * Register a resolution/rejection handler with a promise.
4565  * The handler is given the respective resolution/rejection value as
4566  * an argument. If the promise is already resolved/rejected, the handler is
4567  * invoked at the end of turn.
4568  */
4570  Local<Function> handler);
4571 
4573  Local<Function> handler);
4574 
4576  Local<Function> on_fulfilled,
4577  Local<Function> on_rejected);
4578 
4579  /**
4580  * Returns true if the promise has at least one derived promise, and
4581  * therefore resolve/reject handlers (including default handler).
4582  */
4583  bool HasHandler();
4584 
4585  /**
4586  * Returns the content of the [[PromiseResult]] field. The Promise must not
4587  * be pending.
4588  */
4589  Local<Value> Result();
4590 
4591  /**
4592  * Returns the value of the [[PromiseState]] field.
4593  */
4594  PromiseState State();
4595 
4596  /**
4597  * Marks this promise as handled to avoid reporting unhandled rejections.
4598  */
4599  void MarkAsHandled();
4600 
4601  V8_INLINE static Promise* Cast(Value* obj);
4602 
4604 
4605  private:
4606  Promise();
4607  static void CheckCast(Value* obj);
4608 };
4609 
4610 /**
4611  * An instance of a Property Descriptor, see Ecma-262 6.2.4.
4612  *
4613  * Properties in a descriptor are present or absent. If you do not set
4614  * `enumerable`, `configurable`, and `writable`, they are absent. If `value`,
4615  * `get`, or `set` are absent, but you must specify them in the constructor, use
4616  * empty handles.
4617  *
4618  * Accessors `get` and `set` must be callable or undefined if they are present.
4619  *
4620  * \note Only query properties if they are present, i.e., call `x()` only if
4621  * `has_x()` returns true.
4622  *
4623  * \code
4624  * // var desc = {writable: false}
4625  * v8::PropertyDescriptor d(Local<Value>()), false);
4626  * d.value(); // error, value not set
4627  * if (d.has_writable()) {
4628  * d.writable(); // false
4629  * }
4630  *
4631  * // var desc = {value: undefined}
4632  * v8::PropertyDescriptor d(v8::Undefined(isolate));
4633  *
4634  * // var desc = {get: undefined}
4635  * v8::PropertyDescriptor d(v8::Undefined(isolate), Local<Value>()));
4636  * \endcode
4637  */
4639  public:
4640  // GenericDescriptor
4642 
4643  // DataDescriptor
4644  explicit PropertyDescriptor(Local<Value> value);
4645 
4646  // DataDescriptor with writable property
4647  PropertyDescriptor(Local<Value> value, bool writable);
4648 
4649  // AccessorDescriptor
4651 
4652  ~PropertyDescriptor();
4653 
4654  Local<Value> value() const;
4655  bool has_value() const;
4656 
4657  Local<Value> get() const;
4658  bool has_get() const;
4659  Local<Value> set() const;
4660  bool has_set() const;
4661 
4662  void set_enumerable(bool enumerable);
4663  bool enumerable() const;
4664  bool has_enumerable() const;
4665 
4666  void set_configurable(bool configurable);
4667  bool configurable() const;
4668  bool has_configurable() const;
4669 
4670  bool writable() const;
4671  bool has_writable() const;
4672 
4673  struct PrivateData;
4674  PrivateData* get_private() const { return private_; }
4675 
4676  PropertyDescriptor(const PropertyDescriptor&) = delete;
4677  void operator=(const PropertyDescriptor&) = delete;
4678 
4679  private:
4680  PrivateData* private_;
4681 };
4682 
4683 /**
4684  * An instance of the built-in Proxy constructor (ECMA-262, 6th Edition,
4685  * 26.2.1).
4686  */
4687 class V8_EXPORT Proxy : public Object {
4688  public:
4689  Local<Value> GetTarget();
4690  Local<Value> GetHandler();
4691  bool IsRevoked();
4692  void Revoke();
4693 
4694  /**
4695  * Creates a new Proxy for the target object.
4696  */
4697  static MaybeLocal<Proxy> New(Local<Context> context,
4698  Local<Object> local_target,
4699  Local<Object> local_handler);
4700 
4701  V8_INLINE static Proxy* Cast(Value* obj);
4702 
4703  private:
4704  Proxy();
4705  static void CheckCast(Value* obj);
4706 };
4707 
4708 /**
4709  * Points to an unowned continous buffer holding a known number of elements.
4710  *
4711  * This is similar to std::span (under consideration for C++20), but does not
4712  * require advanced C++ support. In the (far) future, this may be replaced with
4713  * or aliased to std::span.
4714  *
4715  * To facilitate future migration, this class exposes a subset of the interface
4716  * implemented by std::span.
4717  */
4718 template <typename T>
4720  public:
4721  /** The default constructor creates an empty span. */
4722  constexpr MemorySpan() = default;
4723 
4724  constexpr MemorySpan(T* data, size_t size) : data_(data), size_(size) {}
4725 
4726  /** Returns a pointer to the beginning of the buffer. */
4727  constexpr T* data() const { return data_; }
4728  /** Returns the number of elements that the buffer holds. */
4729  constexpr size_t size() const { return size_; }
4730 
4731  private:
4732  T* data_ = nullptr;
4733  size_t size_ = 0;
4734 };
4735 
4736 /**
4737  * An owned byte buffer with associated size.
4738  */
4739 struct OwnedBuffer {
4740  std::unique_ptr<const uint8_t[]> buffer;
4741  size_t size = 0;
4742  OwnedBuffer(std::unique_ptr<const uint8_t[]> buffer, size_t size)
4743  : buffer(std::move(buffer)), size(size) {}
4744  OwnedBuffer() = default;
4745 };
4746 
4747 // Wrapper around a compiled WebAssembly module, which is potentially shared by
4748 // different WasmModuleObjects.
4750  public:
4751  /**
4752  * Serialize the compiled module. The serialized data does not include the
4753  * wire bytes.
4754  */
4756 
4757  /**
4758  * Get the (wasm-encoded) wire bytes that were used to compile this module.
4759  */
4760  MemorySpan<const uint8_t> GetWireBytesRef();
4761 
4762  private:
4763  explicit CompiledWasmModule(std::shared_ptr<internal::wasm::NativeModule>);
4764  friend class Utils;
4765 
4766  const std::shared_ptr<internal::wasm::NativeModule> native_module_;
4767 };
4768 
4769 // An instance of WebAssembly.Module.
4771  public:
4772  WasmModuleObject() = delete;
4773 
4774  /**
4775  * Efficiently re-create a WasmModuleObject, without recompiling, from
4776  * a CompiledWasmModule.
4777  */
4779  Isolate* isolate, const CompiledWasmModule&);
4780 
4781  /**
4782  * Get the compiled module for this module object. The compiled module can be
4783  * shared by several module objects.
4784  */
4786 
4787  /**
4788  * If possible, deserialize the module, otherwise compile it from the provided
4789  * uncompiled bytes.
4790  */
4791  V8_DEPRECATED(
4792  "Use WasmStreaming for deserialization from cache or the "
4793  "CompiledWasmModule to transfer between isolates")
4794  static MaybeLocal<WasmModuleObject> DeserializeOrCompile(
4795  Isolate* isolate, MemorySpan<const uint8_t> serialized_module,
4796  MemorySpan<const uint8_t> wire_bytes);
4797 
4798  V8_INLINE static WasmModuleObject* Cast(Value* obj);
4799 
4800  private:
4801  static MaybeLocal<WasmModuleObject> Deserialize(
4802  Isolate* isolate, MemorySpan<const uint8_t> serialized_module,
4803  MemorySpan<const uint8_t> wire_bytes);
4804  static MaybeLocal<WasmModuleObject> Compile(Isolate* isolate,
4805  const uint8_t* start,
4806  size_t length);
4807 
4808  static void CheckCast(Value* obj);
4809 };
4810 
4811 /**
4812  * The V8 interface for WebAssembly streaming compilation. When streaming
4813  * compilation is initiated, V8 passes a {WasmStreaming} object to the embedder
4814  * such that the embedder can pass the input bytes for streaming compilation to
4815  * V8.
4816  */
4817 class V8_EXPORT WasmStreaming final {
4818  public:
4819  class WasmStreamingImpl;
4820 
4821  /**
4822  * Client to receive streaming event notifications.
4823  */
4824  class Client {
4825  public:
4826  virtual ~Client() = default;
4827  /**
4828  * Passes the fully compiled module to the client. This can be used to
4829  * implement code caching.
4830  */
4831  virtual void OnModuleCompiled(CompiledWasmModule compiled_module) = 0;
4832  };
4833 
4834  explicit WasmStreaming(std::unique_ptr<WasmStreamingImpl> impl);
4835 
4836  ~WasmStreaming();
4837 
4838  /**
4839  * Pass a new chunk of bytes to WebAssembly streaming compilation.
4840  * The buffer passed into {OnBytesReceived} is owned by the caller.
4841  */
4842  void OnBytesReceived(const uint8_t* bytes, size_t size);
4843 
4844  /**
4845  * {Finish} should be called after all received bytes where passed to
4846  * {OnBytesReceived} to tell V8 that there will be no more bytes. {Finish}
4847  * does not have to be called after {Abort} has been called already.
4848  */
4849  void Finish();
4850 
4851  /**
4852  * Abort streaming compilation. If {exception} has a value, then the promise
4853  * associated with streaming compilation is rejected with that value. If
4854  * {exception} does not have value, the promise does not get rejected.
4855  */
4856  void Abort(MaybeLocal<Value> exception);
4857 
4858  /**
4859  * Passes previously compiled module bytes. This must be called before
4860  * {OnBytesReceived}, {Finish}, or {Abort}. Returns true if the module bytes
4861  * can be used, false otherwise. The buffer passed via {bytes} and {size}
4862  * is owned by the caller. If {SetCompiledModuleBytes} returns true, the
4863  * buffer must remain valid until either {Finish} or {Abort} completes.
4864  */
4865  bool SetCompiledModuleBytes(const uint8_t* bytes, size_t size);
4866 
4867  /**
4868  * Sets the client object that will receive streaming event notifications.
4869  * This must be called before {OnBytesReceived}, {Finish}, or {Abort}.
4870  */
4871  void SetClient(std::shared_ptr<Client> client);
4872 
4873  /*
4874  * Sets the UTF-8 encoded source URL for the {Script} object. This must be
4875  * called before {Finish}.
4876  */
4877  void SetUrl(const char* url, size_t length);
4878 
4879  /**
4880  * Unpacks a {WasmStreaming} object wrapped in a {Managed} for the embedder.
4881  * Since the embedder is on the other side of the API, it cannot unpack the
4882  * {Managed} itself.
4883  */
4884  static std::shared_ptr<WasmStreaming> Unpack(Isolate* isolate,
4885  Local<Value> value);
4886 
4887  private:
4888  std::unique_ptr<WasmStreamingImpl> impl_;
4889 };
4890 
4891 // TODO(mtrofin): when streaming compilation is done, we can rename this
4892 // to simply WasmModuleObjectBuilder
4893 class V8_EXPORT WasmModuleObjectBuilderStreaming final {
4894  public:
4895  explicit WasmModuleObjectBuilderStreaming(Isolate* isolate);
4896  /**
4897  * The buffer passed into OnBytesReceived is owned by the caller.
4898  */
4899  void OnBytesReceived(const uint8_t*, size_t size);
4900  void Finish();
4901  /**
4902  * Abort streaming compilation. If {exception} has a value, then the promise
4903  * associated with streaming compilation is rejected with that value. If
4904  * {exception} does not have value, the promise does not get rejected.
4905  */
4906  void Abort(MaybeLocal<Value> exception);
4908 
4909  ~WasmModuleObjectBuilderStreaming() = default;
4910 
4911  private:
4912  WasmModuleObjectBuilderStreaming(const WasmModuleObjectBuilderStreaming&) =
4913  delete;
4914  WasmModuleObjectBuilderStreaming(WasmModuleObjectBuilderStreaming&&) =
4915  default;
4916  WasmModuleObjectBuilderStreaming& operator=(
4917  const WasmModuleObjectBuilderStreaming&) = delete;
4918  WasmModuleObjectBuilderStreaming& operator=(
4919  WasmModuleObjectBuilderStreaming&&) = default;
4920  Isolate* isolate_ = nullptr;
4921 
4922 #if V8_CC_MSVC
4923  /**
4924  * We don't need the static Copy API, so the default
4925  * NonCopyablePersistentTraits would be sufficient, however,
4926  * MSVC eagerly instantiates the Copy.
4927  * We ensure we don't use Copy, however, by compiling with the
4928  * defaults everywhere else.
4929  */
4930  Persistent<Promise, CopyablePersistentTraits<Promise>> promise_;
4931 #else
4932  Persistent<Promise> promise_;
4933 #endif
4934  std::shared_ptr<internal::wasm::StreamingDecoder> streaming_decoder_;
4935 };
4936 
4937 #ifndef V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT
4938 // The number of required internal fields can be defined by embedder.
4939 #define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 2
4940 #endif
4941 
4942 
4944 
4945 /**
4946  * A wrapper around the backing store (i.e. the raw memory) of an array buffer.
4947  * See a document linked in http://crbug.com/v8/9908 for more information.
4948  *
4949  * The allocation and destruction of backing stores is generally managed by
4950  * V8. Clients should always use standard C++ memory ownership types (i.e.
4951  * std::unique_ptr and std::shared_ptr) to manage lifetimes of backing stores
4952  * properly, since V8 internal objects may alias backing stores.
4953  *
4954  * This object does not keep the underlying |ArrayBuffer::Allocator| alive by
4955  * default. Use Isolate::CreateParams::array_buffer_allocator_shared when
4956  * creating the Isolate to make it hold a reference to the allocator itself.
4957  */
4958 class