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