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