v8  8.1.307(node14.1.0)
V8 is Google's open source JavaScript engine
v8.h
Go to the documentation of this file.
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 /** \mainpage V8 API Reference Guide
6  *
7  * V8 is Google's open source JavaScript engine.
8  *
9  * This set of documents provides reference material generated from the
10  * V8 header file, include/v8.h.
11  *
12  * For other documentation see https://v8.dev/.
13  */
14 
15 #ifndef INCLUDE_V8_H_
16 #define INCLUDE_V8_H_
17 
18 #include <stddef.h>
19 #include <stdint.h>
20 #include <stdio.h>
21 #include <memory>
22 #include <string>
23 #include <type_traits>
24 #include <utility>
25 #include <vector>
26 
27 #include "v8-internal.h" // NOLINT(build/include)
28 #include "v8-version.h" // NOLINT(build/include)
29 #include "v8config.h" // NOLINT(build/include)
30 
31 // We reserve the V8_* prefix for macros defined in V8 public API and
32 // assume there are no name conflicts with the embedder's code.
33 
34 /**
35  * The v8 JavaScript engine.
36  */
37 namespace v8 {
38 
39 class AccessorSignature;
40 class Array;
41 class ArrayBuffer;
42 class BigInt;
43 class BigIntObject;
44 class Boolean;
45 class BooleanObject;
46 class Context;
47 class Data;
48 class Date;
49 class External;
50 class Function;
51 class FunctionTemplate;
52 class HeapProfiler;
53 class ImplementationUtilities;
54 class Int32;
55 class Integer;
56 class Isolate;
57 template <class T>
58 class Maybe;
59 class MicrotaskQueue;
60 class Name;
61 class Number;
62 class NumberObject;
63 class Object;
64 class ObjectOperationDescriptor;
65 class ObjectTemplate;
66 class Platform;
67 class Primitive;
68 class Promise;
69 class PropertyDescriptor;
70 class Proxy;
71 class RawOperationDescriptor;
72 class Script;
73 class SharedArrayBuffer;
74 class Signature;
75 class StartupData;
76 class StackFrame;
77 class StackTrace;
78 class String;
79 class StringObject;
80 class Symbol;
81 class SymbolObject;
82 class PrimitiveArray;
83 class Private;
84 class Uint32;
85 class Utils;
86 class Value;
87 class WasmModuleObject;
88 template <class T> class Local;
89 template <class T>
90 class MaybeLocal;
91 template <class T> class Eternal;
92 template<class T> class NonCopyablePersistentTraits;
93 template<class T> class PersistentBase;
94 template <class T, class M = NonCopyablePersistentTraits<T> >
95 class Persistent;
96 template <class T>
97 class Global;
98 template <class T>
100 template <class T>
102 template <class T>
104 template<class K, class V, class T> class PersistentValueMap;
105 template <class K, class V, class T>
107 template <class K, class V, class T>
108 class GlobalValueMap;
109 template<class V, class T> class PersistentValueVector;
110 template<class T, class P> class WeakCallbackObject;
111 class FunctionTemplate;
112 class ObjectTemplate;
113 template<typename T> class FunctionCallbackInfo;
114 template<typename T> class PropertyCallbackInfo;
115 class StackTrace;
116 class StackFrame;
117 class Isolate;
118 class CallHandlerHelper;
120 template<typename T> class ReturnValue;
121 
122 namespace internal {
123 class Arguments;
124 class DeferredHandles;
125 class Heap;
126 class HeapObject;
127 class ExternalString;
128 class Isolate;
129 class LocalEmbedderHeapTracer;
130 class MicrotaskQueue;
131 struct ScriptStreamingData;
132 template<typename T> class CustomArguments;
133 class PropertyCallbackArguments;
134 class FunctionCallbackArguments;
135 class GlobalHandles;
136 class ScopedExternalStringLock;
137 class ThreadLocalTop;
138 
139 namespace wasm {
140 class NativeModule;
141 class StreamingDecoder;
142 } // namespace wasm
143 
144 } // namespace internal
145 
146 namespace debug {
147 class ConsoleCallArguments;
148 } // namespace debug
149 
150 // --- Handles ---
151 
152 #define TYPE_CHECK(T, S)
153  while (false) {
154  *(static_cast<T* volatile*>(0)) = static_cast<S*>(0);
155  }
156 
157 /**
158  * An object reference managed by the v8 garbage collector.
159  *
160  * All objects returned from v8 have to be tracked by the garbage
161  * collector so that it knows that the objects are still alive. Also,
162  * because the garbage collector may move objects, it is unsafe to
163  * point directly to an object. Instead, all objects are stored in
164  * handles which are known by the garbage collector and updated
165  * whenever an object moves. Handles should always be passed by value
166  * (except in cases like out-parameters) and they should never be
167  * allocated on the heap.
168  *
169  * There are two types of handles: local and persistent handles.
170  *
171  * Local handles are light-weight and transient and typically used in
172  * local operations. They are managed by HandleScopes. That means that a
173  * HandleScope must exist on the stack when they are created and that they are
174  * only valid inside of the HandleScope active during their creation.
175  * For passing a local handle to an outer HandleScope, an EscapableHandleScope
176  * and its Escape() method must be used.
177  *
178  * Persistent handles can be used when storing objects across several
179  * independent operations and have to be explicitly deallocated when they're no
180  * longer used.
181  *
182  * It is safe to extract the object stored in the handle by
183  * dereferencing the handle (for instance, to extract the Object* from
184  * a Local<Object>); the value will still be governed by a handle
185  * behind the scenes and the same rules apply to these values as to
186  * their handles.
187  */
188 template <class T>
189 class Local {
190  public:
191  V8_INLINE Local() : val_(nullptr) {}
192  template <class S>
194  : val_(reinterpret_cast<T*>(*that)) {
195  /**
196  * This check fails when trying to convert between incompatible
197  * handles. For example, converting from a Local<String> to a
198  * Local<Number>.
199  */
200  TYPE_CHECK(T, S);
201  }
202 
203  /**
204  * Returns true if the handle is empty.
205  */
206  V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
207 
208  /**
209  * Sets the handle to be empty. IsEmpty() will then return true.
210  */
211  V8_INLINE void Clear() { val_ = nullptr; }
212 
213  V8_INLINE T* operator->() const { return val_; }
214 
215  V8_INLINE T* operator*() const { return val_; }
216 
217  /**
218  * Checks whether two handles are the same.
219  * Returns true if both are empty, or if the objects to which they refer
220  * are identical.
221  *
222  * If both handles refer to JS objects, this is the same as strict equality.
223  * For primitives, such as numbers or strings, a `false` return value does not
224  * indicate that the values aren't equal in the JavaScript sense.
225  * Use `Value::StrictEquals()` to check primitives for equality.
226  */
227  template <class S>
228  V8_INLINE bool operator==(const Local<S>& that) const {
229  internal::Address* a = reinterpret_cast<internal::Address*>(this->val_);
230  internal::Address* b = reinterpret_cast<internal::Address*>(that.val_);
231  if (a == nullptr) return b == nullptr;
232  if (b == nullptr) return false;
233  return *a == *b;
234  }
235 
236  template <class S> V8_INLINE bool operator==(
237  const PersistentBase<S>& that) const {
238  internal::Address* a = reinterpret_cast<internal::Address*>(this->val_);
239  internal::Address* b = reinterpret_cast<internal::Address*>(that.val_);
240  if (a == nullptr) return b == nullptr;
241  if (b == nullptr) return false;
242  return *a == *b;
243  }
244 
245  /**
246  * Checks whether two handles are different.
247  * Returns true if only one of the handles is empty, or if
248  * the objects to which they refer are different.
249  *
250  * If both handles refer to JS objects, this is the same as strict
251  * non-equality. For primitives, such as numbers or strings, a `true` return
252  * value does not indicate that the values aren't equal in the JavaScript
253  * sense. Use `Value::StrictEquals()` to check primitives for equality.
254  */
255  template <class S>
256  V8_INLINE bool operator!=(const Local<S>& that) const {
257  return !operator==(that);
258  }
259 
260  template <class S> V8_INLINE bool operator!=(
261  const Persistent<S>& that) const {
262  return !operator==(that);
263  }
264 
265  /**
266  * Cast a handle to a subclass, e.g. Local<Value> to Local<Object>.
267  * This is only valid if the handle actually refers to a value of the
268  * target type.
269  */
270  template <class S> V8_INLINE static Local<T> Cast(Local<S> that) {
271 #ifdef V8_ENABLE_CHECKS
272  // If we're going to perform the type check then we have to check
273  // that the handle isn't empty before doing the checked cast.
274  if (that.IsEmpty()) return Local<T>();
275 #endif
276  return Local<T>(T::Cast(*that));
277  }
278 
279  /**
280  * Calling this is equivalent to Local<S>::Cast().
281  * In particular, this is only valid if the handle actually refers to a value
282  * of the target type.
283  */
284  template <class S>
285  V8_INLINE Local<S> As() const {
286  return Local<S>::Cast(*this);
287  }
288 
289  /**
290  * Create a local handle for the content of another handle.
291  * The referee is kept alive by the local handle even when
292  * the original handle is destroyed/disposed.
293  */
294  V8_INLINE static Local<T> New(Isolate* isolate, Local<T> that);
295  V8_INLINE static Local<T> New(Isolate* isolate,
296  const PersistentBase<T>& that);
297  V8_INLINE static Local<T> New(Isolate* isolate,
298  const TracedReferenceBase<T>& that);
299 
300  private:
301  friend class Utils;
302  template<class F> friend class Eternal;
303  template<class F> friend class PersistentBase;
304  template<class F, class M> friend class Persistent;
305  template<class F> friend class Local;
306  template <class F>
307  friend class MaybeLocal;
308  template<class F> friend class FunctionCallbackInfo;
309  template<class F> friend class PropertyCallbackInfo;
310  friend class String;
311  friend class Object;
312  friend class Context;
313  friend class Isolate;
314  friend class Private;
315  template<class F> friend class internal::CustomArguments;
316  friend Local<Primitive> Undefined(Isolate* isolate);
317  friend Local<Primitive> Null(Isolate* isolate);
318  friend Local<Boolean> True(Isolate* isolate);
319  friend Local<Boolean> False(Isolate* isolate);
320  friend class HandleScope;
321  friend class EscapableHandleScope;
322  template <class F1, class F2, class F3>
324  template<class F1, class F2> friend class PersistentValueVector;
325  template <class F>
326  friend class ReturnValue;
327  template <class F>
328  friend class Traced;
329  template <class F>
330  friend class TracedGlobal;
331  template <class F>
332  friend class TracedReferenceBase;
333  template <class F>
334  friend class TracedReference;
335 
336  explicit V8_INLINE Local(T* that) : val_(that) {}
337  V8_INLINE static Local<T> New(Isolate* isolate, T* that);
338  T* val_;
339 };
340 
341 
342 #if !defined(V8_IMMINENT_DEPRECATION_WARNINGS)
343 // Handle is an alias for Local for historical reasons.
344 template <class T>
345 using Handle = Local<T>;
346 #endif
347 
348 
349 /**
350  * A MaybeLocal<> is a wrapper around Local<> that enforces a check whether
351  * the Local<> is empty before it can be used.
352  *
353  * If an API method returns a MaybeLocal<>, the API method can potentially fail
354  * either because an exception is thrown, or because an exception is pending,
355  * e.g. because a previous API call threw an exception that hasn't been caught
356  * yet, or because a TerminateExecution exception was thrown. In that case, an
357  * empty MaybeLocal is returned.
358  */
359 template <class T>
360 class MaybeLocal {
361  public:
362  V8_INLINE MaybeLocal() : val_(nullptr) {}
363  template <class S>
365  : val_(reinterpret_cast<T*>(*that)) {
366  TYPE_CHECK(T, S);
367  }
368 
369  V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
370 
371  /**
372  * Converts this MaybeLocal<> to a Local<>. If this MaybeLocal<> is empty,
373  * |false| is returned and |out| is left untouched.
374  */
375  template <class S>
377  out->val_ = IsEmpty() ? nullptr : this->val_;
378  return !IsEmpty();
379  }
380 
381  /**
382  * Converts this MaybeLocal<> to a Local<>. If this MaybeLocal<> is empty,
383  * V8 will crash the process.
384  */
386 
387  /**
388  * Converts this MaybeLocal<> to a Local<>, using a default value if this
389  * MaybeLocal<> is empty.
390  */
391  template <class S>
392  V8_INLINE Local<S> FromMaybe(Local<S> default_value) const {
393  return IsEmpty() ? default_value : Local<S>(val_);
394  }
395 
396  private:
397  T* val_;
398 };
399 
400 /**
401  * Eternal handles are set-once handles that live for the lifetime of the
402  * isolate.
403  */
404 template <class T> class Eternal {
405  public:
406  V8_INLINE Eternal() : val_(nullptr) {}
407  template <class S>
408  V8_INLINE Eternal(Isolate* isolate, Local<S> handle) : val_(nullptr) {
409  Set(isolate, handle);
410  }
411  // Can only be safely called if already set.
412  V8_INLINE Local<T> Get(Isolate* isolate) const;
413  V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
414  template<class S> V8_INLINE void Set(Isolate* isolate, Local<S> handle);
415 
416  private:
417  T* val_;
418 };
419 
420 
421 static const int kInternalFieldsInWeakCallback = 2;
422 static const int kEmbedderFieldsInWeakCallback = 2;
423 
424 template <typename T>
426  public:
427  typedef void (*Callback)(const WeakCallbackInfo<T>& data);
428 
429  WeakCallbackInfo(Isolate* isolate, T* parameter,
430  void* embedder_fields[kEmbedderFieldsInWeakCallback],
431  Callback* callback)
432  : isolate_(isolate), parameter_(parameter), callback_(callback) {
433  for (int i = 0; i < kEmbedderFieldsInWeakCallback; ++i) {
434  embedder_fields_[i] = embedder_fields[i];
435  }
436  }
437 
438  V8_INLINE Isolate* GetIsolate() const { return isolate_; }
439  V8_INLINE T* GetParameter() const { return parameter_; }
440  V8_INLINE void* GetInternalField(int index) const;
441 
442  // When first called, the embedder MUST Reset() the Global which triggered the
443  // callback. The Global itself is unusable for anything else. No v8 other api
444  // calls may be called in the first callback. Should additional work be
445  // required, the embedder must set a second pass callback, which will be
446  // called after all the initial callbacks are processed.
447  // Calling SetSecondPassCallback on the second pass will immediately crash.
448  void SetSecondPassCallback(Callback callback) const { *callback_ = callback; }
449 
450  private:
451  Isolate* isolate_;
452  T* parameter_;
453  Callback* callback_;
454  void* embedder_fields_[kEmbedderFieldsInWeakCallback];
455 };
456 
457 
458 // kParameter will pass a void* parameter back to the callback, kInternalFields
459 // will pass the first two internal fields back to the callback, kFinalizer
460 // will pass a void* parameter back, but is invoked before the object is
461 // actually collected, so it can be resurrected. In the last case, it is not
462 // possible to request a second pass callback.
464 
465 /**
466  * An object reference that is independent of any handle scope. Where
467  * a Local handle only lives as long as the HandleScope in which it was
468  * allocated, a PersistentBase handle remains valid until it is explicitly
469  * disposed using Reset().
470  *
471  * A persistent handle contains a reference to a storage cell within
472  * the V8 engine which holds an object value and which is updated by
473  * the garbage collector whenever the object is moved. A new storage
474  * cell can be created using the constructor or PersistentBase::Reset and
475  * existing handles can be disposed using PersistentBase::Reset.
476  *
477  */
478 template <class T> class PersistentBase {
479  public:
480  /**
481  * If non-empty, destroy the underlying storage cell
482  * IsEmpty() will return true after this call.
483  */
484  V8_INLINE void Reset();
485  /**
486  * If non-empty, destroy the underlying storage cell
487  * and create a new one with the contents of other if other is non empty
488  */
489  template <class S>
490  V8_INLINE void Reset(Isolate* isolate, const Local<S>& other);
491 
492  /**
493  * If non-empty, destroy the underlying storage cell
494  * and create a new one with the contents of other if other is non empty
495  */
496  template <class S>
497  V8_INLINE void Reset(Isolate* isolate, const PersistentBase<S>& other);
498 
499  V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
500  V8_INLINE void Empty() { val_ = 0; }
501 
502  V8_INLINE Local<T> Get(Isolate* isolate) const {
503  return Local<T>::New(isolate, *this);
504  }
505 
506  template <class S>
507  V8_INLINE bool operator==(const PersistentBase<S>& that) const {
508  internal::Address* a = reinterpret_cast<internal::Address*>(this->val_);
509  internal::Address* b = reinterpret_cast<internal::Address*>(that.val_);
510  if (a == nullptr) return b == nullptr;
511  if (b == nullptr) return false;
512  return *a == *b;
513  }
514 
515  template <class S>
516  V8_INLINE bool operator==(const Local<S>& that) const {
517  internal::Address* a = reinterpret_cast<internal::Address*>(this->val_);
518  internal::Address* b = reinterpret_cast<internal::Address*>(that.val_);
519  if (a == nullptr) return b == nullptr;
520  if (b == nullptr) return false;
521  return *a == *b;
522  }
523 
524  template <class S>
525  V8_INLINE bool operator!=(const PersistentBase<S>& that) const {
526  return !operator==(that);
527  }
528 
529  template <class S>
530  V8_INLINE bool operator!=(const Local<S>& that) const {
531  return !operator==(that);
532  }
533 
534  /**
535  * Install a finalization callback on this object.
536  * NOTE: There is no guarantee as to *when* or even *if* the callback is
537  * invoked. The invocation is performed solely on a best effort basis.
538  * As always, GC-based finalization should *not* be relied upon for any
539  * critical form of resource management!
540  */
541  template <typename P>
542  V8_INLINE void SetWeak(P* parameter,
543  typename WeakCallbackInfo<P>::Callback callback,
544  WeakCallbackType type);
545 
546  /**
547  * Turns this handle into a weak phantom handle without finalization callback.
548  * The handle will be reset automatically when the garbage collector detects
549  * that the object is no longer reachable.
550  * A related function Isolate::NumberOfPhantomHandleResetsSinceLastCall
551  * returns how many phantom handles were reset by the garbage collector.
552  */
553  V8_INLINE void SetWeak();
554 
555  template<typename P>
556  V8_INLINE P* ClearWeak();
557 
558  // TODO(dcarney): remove this.
559  V8_INLINE void ClearWeak() { ClearWeak<void>(); }
560 
561  /**
562  * Annotates the strong handle with the given label, which is then used by the
563  * heap snapshot generator as a name of the edge from the root to the handle.
564  * The function does not take ownership of the label and assumes that the
565  * label is valid as long as the handle is valid.
566  */
567  V8_INLINE void AnnotateStrongRetainer(const char* label);
568 
569  /** Returns true if the handle's reference is weak. */
570  V8_INLINE bool IsWeak() const;
571 
572  /**
573  * Assigns a wrapper class ID to the handle.
574  */
575  V8_INLINE void SetWrapperClassId(uint16_t class_id);
576 
577  /**
578  * Returns the class ID previously assigned to this handle or 0 if no class ID
579  * was previously assigned.
580  */
581  V8_INLINE uint16_t WrapperClassId() const;
582 
583  PersistentBase(const PersistentBase& other) = delete; // NOLINT
584  void operator=(const PersistentBase&) = delete;
585 
586  private:
587  friend class Isolate;
588  friend class Utils;
589  template<class F> friend class Local;
590  template<class F1, class F2> friend class Persistent;
591  template <class F>
592  friend class Global;
593  template<class F> friend class PersistentBase;
594  template<class F> friend class ReturnValue;
595  template <class F1, class F2, class F3>
597  template<class F1, class F2> friend class PersistentValueVector;
598  friend class Object;
599 
600  explicit V8_INLINE PersistentBase(T* val) : val_(val) {}
601  V8_INLINE static T* New(Isolate* isolate, T* that);
602 
603  T* val_;
604 };
605 
606 
607 /**
608  * Default traits for Persistent. This class does not allow
609  * use of the copy constructor or assignment operator.
610  * At present kResetInDestructor is not set, but that will change in a future
611  * version.
612  */
613 template<class T>
614 class NonCopyablePersistentTraits {
615  public:
616  typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
617  static const bool kResetInDestructor = false;
618  template<class S, class M>
619  V8_INLINE static void Copy(const Persistent<S, M>& source,
620  NonCopyablePersistent* dest) {
621  Uncompilable<Object>();
622  }
623  // TODO(dcarney): come up with a good compile error here.
624  template<class O> V8_INLINE static void Uncompilable() {
625  TYPE_CHECK(O, Primitive);
626  }
627 };
628 
629 
630 /**
631  * Helper class traits to allow copying and assignment of Persistent.
632  * This will clone the contents of storage cell, but not any of the flags, etc.
633  */
634 template<class T>
637  static const bool kResetInDestructor = true;
638  template<class S, class M>
639  static V8_INLINE void Copy(const Persistent<S, M>& source,
640  CopyablePersistent* dest) {
641  // do nothing, just allow copy
642  }
643 };
644 
645 
646 /**
647  * A PersistentBase which allows copy and assignment.
648  *
649  * Copy, assignment and destructor behavior is controlled by the traits
650  * class M.
651  *
652  * Note: Persistent class hierarchy is subject to future changes.
653  */
654 template <class T, class M> class Persistent : public PersistentBase<T> {
655  public:
656  /**
657  * A Persistent with no storage cell.
658  */
660  /**
661  * Construct a Persistent from a Local.
662  * When the Local is non-empty, a new storage cell is created
663  * pointing to the same object, and no flags are set.
664  */
665  template <class S>
666  V8_INLINE Persistent(Isolate* isolate, Local<S> that)
667  : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
668  TYPE_CHECK(T, S);
669  }
670  /**
671  * Construct a Persistent from a Persistent.
672  * When the Persistent is non-empty, a new storage cell is created
673  * pointing to the same object, and no flags are set.
674  */
675  template <class S, class M2>
676  V8_INLINE Persistent(Isolate* isolate, const Persistent<S, M2>& that)
677  : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
678  TYPE_CHECK(T, S);
679  }
680  /**
681  * The copy constructors and assignment operator create a Persistent
682  * exactly as the Persistent constructor, but the Copy function from the
683  * traits class is called, allowing the setting of flags based on the
684  * copied Persistent.
685  */
686  V8_INLINE Persistent(const Persistent& that) : PersistentBase<T>(nullptr) {
687  Copy(that);
688  }
689  template <class S, class M2>
690  V8_INLINE Persistent(const Persistent<S, M2>& that) : PersistentBase<T>(0) {
691  Copy(that);
692  }
694  Copy(that);
695  return *this;
696  }
697  template <class S, class M2>
698  V8_INLINE Persistent& operator=(const Persistent<S, M2>& that) { // NOLINT
699  Copy(that);
700  return *this;
701  }
702  /**
703  * The destructor will dispose the Persistent based on the
704  * kResetInDestructor flags in the traits class. Since not calling dispose
705  * can result in a memory leak, it is recommended to always set this flag.
706  */
708  if (M::kResetInDestructor) this->Reset();
709  }
710 
711  // TODO(dcarney): this is pretty useless, fix or remove
712  template <class S>
713  V8_INLINE static Persistent<T>& Cast(const Persistent<S>& that) { // NOLINT
714 #ifdef V8_ENABLE_CHECKS
715  // If we're going to perform the type check then we have to check
716  // that the handle isn't empty before doing the checked cast.
717  if (!that.IsEmpty()) T::Cast(*that);
718 #endif
719  return reinterpret_cast<Persistent<T>&>(const_cast<Persistent<S>&>(that));
720  }
721 
722  // TODO(dcarney): this is pretty useless, fix or remove
723  template <class S>
724  V8_INLINE Persistent<S>& As() const { // NOLINT
725  return Persistent<S>::Cast(*this);
726  }
727 
728  private:
729  friend class Isolate;
730  friend class Utils;
731  template<class F> friend class Local;
732  template<class F1, class F2> friend class Persistent;
733  template<class F> friend class ReturnValue;
734 
735  explicit V8_INLINE Persistent(T* that) : PersistentBase<T>(that) {}
736  V8_INLINE T* operator*() const { return this->val_; }
737  template<class S, class M2>
738  V8_INLINE void Copy(const Persistent<S, M2>& that);
739 };
740 
741 
742 /**
743  * A PersistentBase which has move semantics.
744  *
745  * Note: Persistent class hierarchy is subject to future changes.
746  */
747 template <class T>
748 class Global : public PersistentBase<T> {
749  public:
750  /**
751  * A Global with no storage cell.
752  */
753  V8_INLINE Global() : PersistentBase<T>(nullptr) {}
754 
755  /**
756  * Construct a Global from a Local.
757  * When the Local is non-empty, a new storage cell is created
758  * pointing to the same object, and no flags are set.
759  */
760  template <class S>
761  V8_INLINE Global(Isolate* isolate, Local<S> that)
762  : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
763  TYPE_CHECK(T, S);
764  }
765 
766  /**
767  * Construct a Global from a PersistentBase.
768  * When the Persistent is non-empty, a new storage cell is created
769  * pointing to the same object, and no flags are set.
770  */
771  template <class S>
772  V8_INLINE Global(Isolate* isolate, const PersistentBase<S>& that)
773  : PersistentBase<T>(PersistentBase<T>::New(isolate, that.val_)) {
774  TYPE_CHECK(T, S);
775  }
776 
777  /**
778  * Move constructor.
779  */
780  V8_INLINE Global(Global&& other);
781 
782  V8_INLINE ~Global() { this->Reset(); }
783 
784  /**
785  * Move via assignment.
786  */
787  template <class S>
788  V8_INLINE Global& operator=(Global<S>&& rhs);
789 
790  /**
791  * Pass allows returning uniques from functions, etc.
792  */
793  Global Pass() { return static_cast<Global&&>(*this); } // NOLINT
794 
795  /*
796  * For compatibility with Chromium's base::Bind (base::Passed).
797  */
798  typedef void MoveOnlyTypeForCPP03;
799 
800  Global(const Global&) = delete;
801  void operator=(const Global&) = delete;
802 
803  private:
804  template <class F>
805  friend class ReturnValue;
806  V8_INLINE T* operator*() const { return this->val_; }
807 };
808 
809 
810 // UniquePersistent is an alias for Global for historical reason.
811 template <class T>
812 using UniquePersistent = Global<T>;
813 
814 /**
815  * Deprecated. Use |TracedReference<T>| instead.
816  */
817 template <typename T>
819 
820 /**
821  * A traced handle with copy and move semantics. The handle is to be used
822  * together with |v8::EmbedderHeapTracer| and specifies edges from the embedder
823  * into V8's heap.
824  *
825  * The exact semantics are:
826  * - Tracing garbage collections use |v8::EmbedderHeapTracer|.
827  * - Non-tracing garbage collections refer to
828  * |v8::EmbedderHeapTracer::IsRootForNonTracingGC()| whether the handle should
829  * be treated as root or not.
830  *
831  * Note that the base class cannot be instantiated itself. Choose from
832  * - TracedGlobal
833  * - TracedReference
834  */
835 template <typename T>
836 class TracedReferenceBase {
837  public:
838  /**
839  * Returns true if this TracedReferenceBase is empty, i.e., has not been
840  * assigned an object.
841  */
842  bool IsEmpty() const { return val_ == nullptr; }
843 
844  /**
845  * If non-empty, destroy the underlying storage cell. |IsEmpty| will return
846  * true after this call.
847  */
848  V8_INLINE void Reset();
849 
850  /**
851  * Construct a Local<T> from this handle.
852  */
853  Local<T> Get(Isolate* isolate) const { return Local<T>::New(isolate, *this); }
854 
855  template <class S>
856  V8_INLINE bool operator==(const TracedReferenceBase<S>& that) const {
857  internal::Address* a = reinterpret_cast<internal::Address*>(val_);
858  internal::Address* b = reinterpret_cast<internal::Address*>(that.val_);
859  if (a == nullptr) return b == nullptr;
860  if (b == nullptr) return false;
861  return *a == *b;
862  }
863 
864  template <class S>
865  V8_INLINE bool operator==(const Local<S>& that) const {
866  internal::Address* a = reinterpret_cast<internal::Address*>(val_);
867  internal::Address* b = reinterpret_cast<internal::Address*>(that.val_);
868  if (a == nullptr) return b == nullptr;
869  if (b == nullptr) return false;
870  return *a == *b;
871  }
872 
873  template <class S>
874  V8_INLINE bool operator!=(const TracedReferenceBase<S>& that) const {
875  return !operator==(that);
876  }
877 
878  template <class S>
879  V8_INLINE bool operator!=(const Local<S>& that) const {
880  return !operator==(that);
881  }
882 
883  /**
884  * Assigns a wrapper class ID to the handle.
885  */
886  V8_INLINE void SetWrapperClassId(uint16_t class_id);
887 
888  /**
889  * Returns the class ID previously assigned to this handle or 0 if no class ID
890  * was previously assigned.
891  */
892  V8_INLINE uint16_t WrapperClassId() const;
893 
894  template <class S>
896  return reinterpret_cast<TracedReferenceBase<S>&>(
897  const_cast<TracedReferenceBase<T>&>(*this));
898  }
899 
900  private:
901  enum DestructionMode { kWithDestructor, kWithoutDestructor };
902 
903  /**
904  * An empty TracedReferenceBase without storage cell.
905  */
906  TracedReferenceBase() = default;
907 
908  V8_INLINE static T* New(Isolate* isolate, T* that, void* slot,
909  DestructionMode destruction_mode);
910 
911  T* val_ = nullptr;
912 
913  friend class EmbedderHeapTracer;
914  template <typename F>
915  friend class Local;
916  friend class Object;
917  template <typename F>
918  friend class TracedGlobal;
919  template <typename F>
920  friend class TracedReference;
921  template <typename F>
922  friend class ReturnValue;
923 };
924 
925 /**
926  * A traced handle with destructor that clears the handle. For more details see
927  * TracedReferenceBase.
928  */
929 template <typename T>
930 class TracedGlobal : public TracedReferenceBase<T> {
931  public:
932  using TracedReferenceBase<T>::Reset;
933 
934  /**
935  * Destructor resetting the handle.
936  */
937  ~TracedGlobal() { this->Reset(); }
938 
939  /**
940  * An empty TracedGlobal without storage cell.
941  */
943 
944  /**
945  * Construct a TracedGlobal from a Local.
946  *
947  * When the Local is non-empty, a new storage cell is created
948  * pointing to the same object.
949  */
950  template <class S>
951  TracedGlobal(Isolate* isolate, Local<S> that) : TracedReferenceBase<T>() {
952  this->val_ = this->New(isolate, that.val_, &this->val_,
953  TracedReferenceBase<T>::kWithDestructor);
954  TYPE_CHECK(T, S);
955  }
956 
957  /**
958  * Move constructor initializing TracedGlobal from an existing one.
959  */
961  // Forward to operator=.
962  *this = std::move(other);
963  }
964 
965  /**
966  * Move constructor initializing TracedGlobal from an existing one.
967  */
968  template <typename S>
970  // Forward to operator=.
971  *this = std::move(other);
972  }
973 
974  /**
975  * Copy constructor initializing TracedGlobal from an existing one.
976  */
978  // Forward to operator=;
979  *this = other;
980  }
981 
982  /**
983  * Copy constructor initializing TracedGlobal from an existing one.
984  */
985  template <typename S>
987  // Forward to operator=;
988  *this = other;
989  }
990 
991  /**
992  * Move assignment operator initializing TracedGlobal from an existing one.
993  */
995 
996  /**
997  * Move assignment operator initializing TracedGlobal from an existing one.
998  */
999  template <class S>
1001 
1002  /**
1003  * Copy assignment operator initializing TracedGlobal from an existing one.
1004  *
1005  * Note: Prohibited when |other| has a finalization callback set through
1006  * |SetFinalizationCallback|.
1007  */
1009 
1010  /**
1011  * Copy assignment operator initializing TracedGlobal from an existing one.
1012  *
1013  * Note: Prohibited when |other| has a finalization callback set through
1014  * |SetFinalizationCallback|.
1015  */
1016  template <class S>
1017  V8_INLINE TracedGlobal& operator=(const TracedGlobal<S>& rhs);
1018 
1019  /**
1020  * If non-empty, destroy the underlying storage cell and create a new one with
1021  * the contents of other if other is non empty
1022  */
1023  template <class S>
1024  V8_INLINE void Reset(Isolate* isolate, const Local<S>& other);
1025 
1026  template <class S>
1027  V8_INLINE TracedGlobal<S>& As() const {
1028  return reinterpret_cast<TracedGlobal<S>&>(
1029  const_cast<TracedGlobal<T>&>(*this));
1030  }
1031 
1032  /**
1033  * Adds a finalization callback to the handle. The type of this callback is
1034  * similar to WeakCallbackType::kInternalFields, i.e., it will pass the
1035  * parameter and the first two internal fields of the object.
1036  *
1037  * The callback is then supposed to reset the handle in the callback. No
1038  * further V8 API may be called in this callback. In case additional work
1039  * involving V8 needs to be done, a second callback can be scheduled using
1040  * WeakCallbackInfo<void>::SetSecondPassCallback.
1041  */
1043  void* parameter, WeakCallbackInfo<void>::Callback callback);
1044 };
1045 
1046 /**
1047  * A traced handle without destructor that clears the handle. The embedder needs
1048  * to ensure that the handle is not accessed once the V8 object has been
1049  * reclaimed. This can happen when the handle is not passed through the
1050  * EmbedderHeapTracer. For more details see TracedReferenceBase.
1051  *
1052  * The reference assumes the embedder has precise knowledge about references at
1053  * all times. In case V8 needs to separately handle on-stack references, the
1054  * embedder is required to set the stack start through
1055  * |EmbedderHeapTracer::SetStackStart|.
1056  */
1057 template <typename T>
1058 class TracedReference : public TracedReferenceBase<T> {
1059  public:
1060  using TracedReferenceBase<T>::Reset;
1061 
1062  /**
1063  * An empty TracedReference without storage cell.
1064  */
1066 
1067  /**
1068  * Construct a TracedReference from a Local.
1069  *
1070  * When the Local is non-empty, a new storage cell is created
1071  * pointing to the same object.
1072  */
1073  template <class S>
1074  TracedReference(Isolate* isolate, Local<S> that) : TracedReferenceBase<T>() {
1075  this->val_ = this->New(isolate, that.val_, &this->val_,
1076  TracedReferenceBase<T>::kWithoutDestructor);
1077  TYPE_CHECK(T, S);
1078  }
1079 
1080  /**
1081  * Move constructor initializing TracedReference from an
1082  * existing one.
1083  */
1085  // Forward to operator=.
1086  *this = std::move(other);
1087  }
1088 
1089  /**
1090  * Move constructor initializing TracedReference from an
1091  * existing one.
1092  */
1093  template <typename S>
1095  // Forward to operator=.
1096  *this = std::move(other);
1097  }
1098 
1099  /**
1100  * Copy constructor initializing TracedReference from an
1101  * existing one.
1102  */
1104  // Forward to operator=;
1105  *this = other;
1106  }
1107 
1108  /**
1109  * Copy constructor initializing TracedReference from an
1110  * existing one.
1111  */
1112  template <typename S>
1114  // Forward to operator=;
1115  *this = other;
1116  }
1117 
1118  /**
1119  * Move assignment operator initializing TracedGlobal from an existing one.
1120  */
1122 
1123  /**
1124  * Move assignment operator initializing TracedGlobal from an existing one.
1125  */
1126  template <class S>
1128 
1129  /**
1130  * Copy assignment operator initializing TracedGlobal from an existing one.
1131  *
1132  * Note: Prohibited when |other| has a finalization callback set through
1133  * |SetFinalizationCallback|.
1134  */
1136 
1137  /**
1138  * Copy assignment operator initializing TracedGlobal from an existing one.
1139  *
1140  * Note: Prohibited when |other| has a finalization callback set through
1141  * |SetFinalizationCallback|.
1142  */
1143  template <class S>
1145 
1146  /**
1147  * If non-empty, destroy the underlying storage cell and create a new one with
1148  * the contents of other if other is non empty
1149  */
1150  template <class S>
1151  V8_INLINE void Reset(Isolate* isolate, const Local<S>& other);
1152 
1153  template <class S>
1155  return reinterpret_cast<TracedReference<S>&>(
1156  const_cast<TracedReference<T>&>(*this));
1157  }
1158 
1159  /**
1160  * Adds a finalization callback to the handle. The type of this callback is
1161  * similar to WeakCallbackType::kInternalFields, i.e., it will pass the
1162  * parameter and the first two internal fields of the object.
1163  *
1164  * The callback is then supposed to reset the handle in the callback. No
1165  * further V8 API may be called in this callback. In case additional work
1166  * involving V8 needs to be done, a second callback can be scheduled using
1167  * WeakCallbackInfo<void>::SetSecondPassCallback.
1168  */
1169  V8_DEPRECATED("Use TracedGlobal<> if callbacks are required.")
1171  void* parameter, WeakCallbackInfo<void>::Callback callback);
1172 };
1173 
1174  /**
1175  * A stack-allocated class that governs a number of local handles.
1176  * After a handle scope has been created, all local handles will be
1177  * allocated within that handle scope until either the handle scope is
1178  * deleted or another handle scope is created. If there is already a
1179  * handle scope and a new one is created, all allocations will take
1180  * place in the new handle scope until it is deleted. After that,
1181  * new handles will again be allocated in the original handle scope.
1182  *
1183  * After the handle scope of a local handle has been deleted the
1184  * garbage collector will no longer track the object stored in the
1185  * handle and may deallocate it. The behavior of accessing a handle
1186  * for which the handle scope has been deleted is undefined.
1187  */
1189  public:
1190  explicit HandleScope(Isolate* isolate);
1191 
1192  ~HandleScope();
1193 
1194  /**
1195  * Counts the number of allocated handles.
1196  */
1197  static int NumberOfHandles(Isolate* isolate);
1198 
1200  return reinterpret_cast<Isolate*>(isolate_);
1201  }
1202 
1203  HandleScope(const HandleScope&) = delete;
1204  void operator=(const HandleScope&) = delete;
1205 
1206  protected:
1207  V8_INLINE HandleScope() = default;
1208 
1209  void Initialize(Isolate* isolate);
1210 
1211  static internal::Address* CreateHandle(internal::Isolate* isolate,
1212  internal::Address value);
1213 
1214  private:
1215  // Declaring operator new and delete as deleted is not spec compliant.
1216  // Therefore declare them private instead to disable dynamic alloc
1217  void* operator new(size_t size);
1218  void* operator new[](size_t size);
1219  void operator delete(void*, size_t);
1220  void operator delete[](void*, size_t);
1221 
1222  internal::Isolate* isolate_;
1223  internal::Address* prev_next_;
1224  internal::Address* prev_limit_;
1225 
1226  // Local::New uses CreateHandle with an Isolate* parameter.
1227  template<class F> friend class Local;
1228 
1229  // Object::GetInternalField and Context::GetEmbedderData use CreateHandle with
1230  // a HeapObject in their shortcuts.
1231  friend class Object;
1232  friend class Context;
1233 };
1234 
1235 
1236 /**
1237  * A HandleScope which first allocates a handle in the current scope
1238  * which will be later filled with the escape value.
1239  */
1241  public:
1242  explicit EscapableHandleScope(Isolate* isolate);
1243  V8_INLINE ~EscapableHandleScope() = default;
1244 
1245  /**
1246  * Pushes the value into the previous scope and returns a handle to it.
1247  * Cannot be called twice.
1248  */
1249  template <class T>
1250  V8_INLINE Local<T> Escape(Local<T> value) {
1251  internal::Address* slot =
1252  Escape(reinterpret_cast<internal::Address*>(*value));
1253  return Local<T>(reinterpret_cast<T*>(slot));
1254  }
1255 
1256  template <class T>
1258  return Escape(value.FromMaybe(Local<T>()));
1259  }
1260 
1261  EscapableHandleScope(const EscapableHandleScope&) = delete;
1262  void operator=(const EscapableHandleScope&) = delete;
1263 
1264  private:
1265  // Declaring operator new and delete as deleted is not spec compliant.
1266  // Therefore declare them private instead to disable dynamic alloc
1267  void* operator new(size_t size);
1268  void* operator new[](size_t size);
1269  void operator delete(void*, size_t);
1270  void operator delete[](void*, size_t);
1271 
1272  internal::Address* Escape(internal::Address* escape_value);
1273  internal::Address* escape_slot_;
1274 };
1275 
1276 /**
1277  * A SealHandleScope acts like a handle scope in which no handle allocations
1278  * are allowed. It can be useful for debugging handle leaks.
1279  * Handles can be allocated within inner normal HandleScopes.
1280  */
1282  public:
1283  explicit SealHandleScope(Isolate* isolate);
1284  ~SealHandleScope();
1285 
1286  SealHandleScope(const SealHandleScope&) = delete;
1287  void operator=(const SealHandleScope&) = delete;
1288 
1289  private:
1290  // Declaring operator new and delete as deleted is not spec compliant.
1291  // Therefore declare them private instead to disable dynamic alloc
1292  void* operator new(size_t size);
1293  void* operator new[](size_t size);
1294  void operator delete(void*, size_t);
1295  void operator delete[](void*, size_t);
1296 
1297  internal::Isolate* const isolate_;
1298  internal::Address* prev_limit_;
1299  int prev_sealed_level_;
1300 };
1301 
1302 
1303 // --- Special objects ---
1304 
1305 /**
1306  * The superclass of objects that can reside on V8's heap.
1307  */
1309  private:
1310  Data();
1311 };
1312 
1313 /**
1314  * A container type that holds relevant metadata for module loading.
1315  *
1316  * This is passed back to the embedder as part of
1317  * HostImportModuleDynamicallyCallback for module loading.
1318  */
1320  public:
1321  /**
1322  * The name that was passed by the embedder as ResourceName to the
1323  * ScriptOrigin. This can be either a v8::String or v8::Undefined.
1324  */
1326 
1327  /**
1328  * The options that were passed by the embedder as HostDefinedOptions to
1329  * the ScriptOrigin.
1330  */
1332 };
1333 
1334 /**
1335  * An array to hold Primitive values. This is used by the embedder to
1336  * pass host defined options to the ScriptOptions during compilation.
1337  *
1338  * This is passed back to the embedder as part of
1339  * HostImportModuleDynamicallyCallback for module loading.
1340  *
1341  */
1343  public:
1344  static Local<PrimitiveArray> New(Isolate* isolate, int length);
1345  int Length() const;
1346  void Set(Isolate* isolate, int index, Local<Primitive> item);
1347  Local<Primitive> Get(Isolate* isolate, int index);
1348 };
1349 
1350 /**
1351  * The optional attributes of ScriptOrigin.
1352  */
1354  public:
1355  V8_INLINE ScriptOriginOptions(bool is_shared_cross_origin = false,
1356  bool is_opaque = false, bool is_wasm = false,
1357  bool is_module = false)
1358  : flags_((is_shared_cross_origin ? kIsSharedCrossOrigin : 0) |
1359  (is_wasm ? kIsWasm : 0) | (is_opaque ? kIsOpaque : 0) |
1360  (is_module ? kIsModule : 0)) {}
1362  : flags_(flags &
1363  (kIsSharedCrossOrigin | kIsOpaque | kIsWasm | kIsModule)) {}
1364 
1365  bool IsSharedCrossOrigin() const {
1366  return (flags_ & kIsSharedCrossOrigin) != 0;
1367  }
1368  bool IsOpaque() const { return (flags_ & kIsOpaque) != 0; }
1369  bool IsWasm() const { return (flags_ & kIsWasm) != 0; }
1370  bool IsModule() const { return (flags_ & kIsModule) != 0; }
1371 
1372  int Flags() const { return flags_; }
1373 
1374  private:
1375  enum {
1376  kIsSharedCrossOrigin = 1,
1377  kIsOpaque = 1 << 1,
1378  kIsWasm = 1 << 2,
1379  kIsModule = 1 << 3
1380  };
1381  const int flags_;
1382 };
1383 
1384 /**
1385  * The origin, within a file, of a script.
1386  */
1388  public:
1390  Local<Value> resource_name,
1391  Local<Integer> resource_line_offset = Local<Integer>(),
1392  Local<Integer> resource_column_offset = Local<Integer>(),
1393  Local<Boolean> resource_is_shared_cross_origin = Local<Boolean>(),
1394  Local<Integer> script_id = Local<Integer>(),
1395  Local<Value> source_map_url = Local<Value>(),
1396  Local<Boolean> resource_is_opaque = Local<Boolean>(),
1397  Local<Boolean> is_wasm = Local<Boolean>(),
1398  Local<Boolean> is_module = Local<Boolean>(),
1399  Local<PrimitiveArray> host_defined_options = Local<PrimitiveArray>());
1400 
1401  V8_INLINE Local<Value> ResourceName() const;
1404  V8_INLINE Local<Integer> ScriptID() const;
1405  V8_INLINE Local<Value> SourceMapUrl() const;
1407  V8_INLINE ScriptOriginOptions Options() const { return options_; }
1408 
1409  private:
1410  Local<Value> resource_name_;
1411  Local<Integer> resource_line_offset_;
1412  Local<Integer> resource_column_offset_;
1413  ScriptOriginOptions options_;
1414  Local<Integer> script_id_;
1415  Local<Value> source_map_url_;
1416  Local<PrimitiveArray> host_defined_options_;
1417 };
1418 
1419 /**
1420  * A compiled JavaScript script, not yet tied to a Context.
1421  */
1423  public:
1424  /**
1425  * Binds the script to the currently entered context.
1426  */
1428 
1429  int GetId();
1431 
1432  /**
1433  * Data read from magic sourceURL comments.
1434  */
1436  /**
1437  * Data read from magic sourceMappingURL comments.
1438  */
1440 
1441  /**
1442  * Returns zero based line number of the code_pos location in the script.
1443  * -1 will be returned if no information available.
1444  */
1445  int GetLineNumber(int code_pos);
1446 
1447  static const int kNoScriptId = 0;
1448 };
1449 
1450 /**
1451  * A compiled JavaScript module, not yet tied to a Context.
1452  */
1454  // Only used as a container for code caching.
1455 };
1456 
1457 /**
1458  * A location in JavaScript source.
1459  */
1461  public:
1462  int GetLineNumber() { return line_number_; }
1463  int GetColumnNumber() { return column_number_; }
1464 
1465  Location(int line_number, int column_number)
1466  : line_number_(line_number), column_number_(column_number) {}
1467 
1468  private:
1469  int line_number_;
1470  int column_number_;
1471 };
1472 
1473 /**
1474  * A compiled JavaScript module.
1475  */
1476 class V8_EXPORT Module : public Data {
1477  public:
1478  /**
1479  * The different states a module can be in.
1480  *
1481  * This corresponds to the states used in ECMAScript except that "evaluated"
1482  * is split into kEvaluated and kErrored, indicating success and failure,
1483  * respectively.
1484  */
1485  enum Status {
1492  };
1493 
1494  /**
1495  * Returns the module's current status.
1496  */
1497  Status GetStatus() const;
1498 
1499  /**
1500  * For a module in kErrored status, this returns the corresponding exception.
1501  */
1502  Local<Value> GetException() const;
1503 
1504  /**
1505  * Returns the number of modules requested by this module.
1506  */
1507  int GetModuleRequestsLength() const;
1508 
1509  /**
1510  * Returns the ith module specifier in this module.
1511  * i must be < GetModuleRequestsLength() and >= 0.
1512  */
1513  Local<String> GetModuleRequest(int i) const;
1514 
1515  /**
1516  * Returns the source location (line number and column number) of the ith
1517  * module specifier's first occurrence in this module.
1518  */
1519  Location GetModuleRequestLocation(int i) const;
1520 
1521  /**
1522  * Returns the identity hash for this object.
1523  */
1524  int GetIdentityHash() const;
1525 
1527  Local<String> specifier,
1528  Local<Module> referrer);
1529 
1530  /**
1531  * Instantiates the module and its dependencies.
1532  *
1533  * Returns an empty Maybe<bool> if an exception occurred during
1534  * instantiation. (In the case where the callback throws an exception, that
1535  * exception is propagated.)
1536  */
1538  ResolveCallback callback);
1539 
1540  /**
1541  * Evaluates the module and its dependencies.
1542  *
1543  * If status is kInstantiated, run the module's code. On success, set status
1544  * to kEvaluated and return the completion value; on failure, set status to
1545  * kErrored and propagate the thrown exception (which is then also available
1546  * via |GetException|).
1547  */
1549 
1550  /**
1551  * Returns the namespace object of this module.
1552  *
1553  * The module's status must be at least kInstantiated.
1554  */
1556 
1557  /**
1558  * Returns the corresponding context-unbound module script.
1559  *
1560  * The module must be unevaluated, i.e. its status must not be kEvaluating,
1561  * kEvaluated or kErrored.
1562  */
1564 
1565  /*
1566  * Callback defined in the embedder. This is responsible for setting
1567  * the module's exported values with calls to SetSyntheticModuleExport().
1568  * The callback must return a Value to indicate success (where no
1569  * exception was thrown) and return an empy MaybeLocal to indicate falure
1570  * (where an exception was thrown).
1571  */
1573  Local<Context> context, Local<Module> module);
1574 
1575  /**
1576  * Creates a new SyntheticModule with the specified export names, where
1577  * evaluation_steps will be executed upon module evaluation.
1578  * export_names must not contain duplicates.
1579  * module_name is used solely for logging/debugging and doesn't affect module
1580  * behavior.
1581  */
1583  Isolate* isolate, Local<String> module_name,
1584  const std::vector<Local<String>>& export_names,
1585  SyntheticModuleEvaluationSteps evaluation_steps);
1586 
1587  /**
1588  * Set this module's exported value for the name export_name to the specified
1589  * export_value. This method must be called only on Modules created via
1590  * CreateSyntheticModule. An error will be thrown if export_name is not one
1591  * of the export_names that were passed in that CreateSyntheticModule call.
1592  * Returns Just(true) on success, Nothing<bool>() if an error was thrown.
1593  */
1595  Isolate* isolate, Local<String> export_name, Local<Value> export_value);
1597  "Use the preceding SetSyntheticModuleExport with an Isolate parameter, "
1598  "instead of the one that follows. The former will throw a runtime "
1599  "error if called for an export that doesn't exist (as per spec); "
1600  "the latter will crash with a failed CHECK().")
1601  void SetSyntheticModuleExport(Local<String> export_name,
1603 };
1604 
1605 /**
1606  * A compiled JavaScript script, tied to a Context which was active when the
1607  * script was compiled.
1608  */
1610  public:
1611  /**
1612  * A shorthand for ScriptCompiler::Compile().
1613  */
1615  Local<Context> context, Local<String> source,
1616  ScriptOrigin* origin = nullptr);
1617 
1618  /**
1619  * Runs the script returning the resulting value. It will be run in the
1620  * context in which it was created (ScriptCompiler::CompileBound or
1621  * UnboundScript::BindToCurrentContext()).
1622  */
1624 
1625  /**
1626  * Returns the corresponding context-unbound script.
1627  */
1629 };
1630 
1631 
1632 /**
1633  * For compiling scripts.
1634  */
1636  public:
1637  /**
1638  * Compilation data that the embedder can cache and pass back to speed up
1639  * future compilations. The data is produced if the CompilerOptions passed to
1640  * the compilation functions in ScriptCompiler contains produce_data_to_cache
1641  * = true. The data to cache can then can be retrieved from
1642  * UnboundScript.
1643  */
1648  };
1649 
1651  : data(nullptr),
1652  length(0),
1653  rejected(false),
1655 
1656  // If buffer_policy is BufferNotOwned, the caller keeps the ownership of
1657  // data and guarantees that it stays alive until the CachedData object is
1658  // destroyed. If the policy is BufferOwned, the given data will be deleted
1659  // (with delete[]) when the CachedData object is destroyed.
1660  CachedData(const uint8_t* data, int length,
1661  BufferPolicy buffer_policy = BufferNotOwned);
1662  ~CachedData();
1663  // TODO(marja): Async compilation; add constructors which take a callback
1664  // which will be called when V8 no longer needs the data.
1665  const uint8_t* data;
1666  int length;
1667  bool rejected;
1669 
1670  // Prevent copying.
1671  CachedData(const CachedData&) = delete;
1672  CachedData& operator=(const CachedData&) = delete;
1673  };
1674 
1675  /**
1676  * Source code which can be then compiled to a UnboundScript or Script.
1677  */
1678  class Source {
1679  public:
1680  // Source takes ownership of CachedData.
1681  V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
1682  CachedData* cached_data = nullptr);
1683  V8_INLINE Source(Local<String> source_string,
1684  CachedData* cached_data = nullptr);
1685  V8_INLINE ~Source();
1686 
1687  // Ownership of the CachedData or its buffers is *not* transferred to the
1688  // caller. The CachedData object is alive as long as the Source object is
1689  // alive.
1690  V8_INLINE const CachedData* GetCachedData() const;
1691 
1693 
1694  // Prevent copying.
1695  Source(const Source&) = delete;
1696  Source& operator=(const Source&) = delete;
1697 
1698  private:
1699  friend class ScriptCompiler;
1700 
1701  Local<String> source_string;
1702 
1703  // Origin information
1704  Local<Value> resource_name;
1705  Local<Integer> resource_line_offset;
1706  Local<Integer> resource_column_offset;
1707  ScriptOriginOptions resource_options;
1708  Local<Value> source_map_url;
1709  Local<PrimitiveArray> host_defined_options;
1710 
1711  // Cached data from previous compilation (if a kConsume*Cache flag is
1712  // set), or hold newly generated cache data (kProduce*Cache flags) are
1713  // set when calling a compile method.
1714  CachedData* cached_data;
1715  };
1716 
1717  /**
1718  * For streaming incomplete script data to V8. The embedder should implement a
1719  * subclass of this class.
1720  */
1722  public:
1723  virtual ~ExternalSourceStream() = default;
1724 
1725  /**
1726  * V8 calls this to request the next chunk of data from the embedder. This
1727  * function will be called on a background thread, so it's OK to block and
1728  * wait for the data, if the embedder doesn't have data yet. Returns the
1729  * length of the data returned. When the data ends, GetMoreData should
1730  * return 0. Caller takes ownership of the data.
1731  *
1732  * When streaming UTF-8 data, V8 handles multi-byte characters split between
1733  * two data chunks, but doesn't handle multi-byte characters split between
1734  * more than two data chunks. The embedder can avoid this problem by always
1735  * returning at least 2 bytes of data.
1736  *
1737  * When streaming UTF-16 data, V8 does not handle characters split between
1738  * two data chunks. The embedder has to make sure that chunks have an even
1739  * length.
1740  *
1741  * If the embedder wants to cancel the streaming, they should make the next
1742  * GetMoreData call return 0. V8 will interpret it as end of data (and most
1743  * probably, parsing will fail). The streaming task will return as soon as
1744  * V8 has parsed the data it received so far.
1745  */
1746  virtual size_t GetMoreData(const uint8_t** src) = 0;
1747 
1748  /**
1749  * V8 calls this method to set a 'bookmark' at the current position in
1750  * the source stream, for the purpose of (maybe) later calling
1751  * ResetToBookmark. If ResetToBookmark is called later, then subsequent
1752  * calls to GetMoreData should return the same data as they did when
1753  * SetBookmark was called earlier.
1754  *
1755  * The embedder may return 'false' to indicate it cannot provide this
1756  * functionality.
1757  */
1758  virtual bool SetBookmark();
1759 
1760  /**
1761  * V8 calls this to return to a previously set bookmark.
1762  */
1763  virtual void ResetToBookmark();
1764  };
1765 
1766  /**
1767  * Source code which can be streamed into V8 in pieces. It will be parsed
1768  * while streaming and compiled after parsing has completed. StreamedSource
1769  * must be kept alive while the streaming task is run (see ScriptStreamingTask
1770  * below).
1771  */
1773  public:
1775 
1777  "This class takes ownership of source_stream, so use the constructor "
1778  "taking a unique_ptr to make these semantics clearer")
1779  StreamedSource(ExternalSourceStream* source_stream, Encoding encoding);
1780  StreamedSource(std::unique_ptr<ExternalSourceStream> source_stream,
1781  Encoding encoding);
1782  ~StreamedSource();
1783 
1784  internal::ScriptStreamingData* impl() const { return impl_.get(); }
1785 
1786  // Prevent copying.
1787  StreamedSource(const StreamedSource&) = delete;
1788  StreamedSource& operator=(const StreamedSource&) = delete;
1789 
1790  private:
1791  std::unique_ptr<internal::ScriptStreamingData> impl_;
1792  };
1793 
1794  /**
1795  * A streaming task which the embedder must run on a background thread to
1796  * stream scripts into V8. Returned by ScriptCompiler::StartStreamingScript.
1797  */
1798  class V8_EXPORT ScriptStreamingTask final {
1799  public:
1800  void Run();
1801 
1802  private:
1803  friend class ScriptCompiler;
1804 
1805  explicit ScriptStreamingTask(internal::ScriptStreamingData* data)
1806  : data_(data) {}
1807 
1808  internal::ScriptStreamingData* data_;
1809  };
1810 
1815  };
1816 
1817  /**
1818  * The reason for which we are not requesting or providing a code cache.
1819  */
1836  };
1837 
1838  /**
1839  * Compiles the specified script (context-independent).
1840  * Cached data as part of the source object can be optionally produced to be
1841  * consumed later to speed up compilation of identical source scripts.
1842  *
1843  * Note that when producing cached data, the source must point to NULL for
1844  * cached data. When consuming cached data, the cached data must have been
1845  * produced by the same version of V8.
1846  *
1847  * \param source Script source code.
1848  * \return Compiled script object (context independent; for running it must be
1849  * bound to a context).
1850  */
1852  Isolate* isolate, Source* source,
1854  NoCacheReason no_cache_reason = kNoCacheNoReason);
1855 
1856  /**
1857  * Compiles the specified script (bound to current context).
1858  *
1859  * \param source Script source code.
1860  * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
1861  * using pre_data speeds compilation if it's done multiple times.
1862  * Owned by caller, no references are kept when this function returns.
1863  * \return Compiled script object, bound to the context that was active
1864  * when this function was called. When run it will always use this
1865  * context.
1866  */
1868  Local<Context> context, Source* source,
1870  NoCacheReason no_cache_reason = kNoCacheNoReason);
1871 
1872  /**
1873  * Returns a task which streams script data into V8, or NULL if the script
1874  * cannot be streamed. The user is responsible for running the task on a
1875  * background thread and deleting it. When ran, the task starts parsing the
1876  * script, and it will request data from the StreamedSource as needed. When
1877  * ScriptStreamingTask::Run exits, all data has been streamed and the script
1878  * can be compiled (see Compile below).
1879  *
1880  * This API allows to start the streaming with as little data as possible, and
1881  * the remaining data (for example, the ScriptOrigin) is passed to Compile.
1882  */
1883  static ScriptStreamingTask* StartStreamingScript(
1884  Isolate* isolate, StreamedSource* source,
1885  CompileOptions options = kNoCompileOptions);
1886 
1887  /**
1888  * Compiles a streamed script (bound to current context).
1889  *
1890  * This can only be called after the streaming has finished
1891  * (ScriptStreamingTask has been run). V8 doesn't construct the source string
1892  * during streaming, so the embedder needs to pass the full source here.
1893  */
1895  Local<Context> context, StreamedSource* source,
1896  Local<String> full_source_string, const ScriptOrigin& origin);
1897 
1898  /**
1899  * Return a version tag for CachedData for the current V8 version & flags.
1900  *
1901  * This value is meant only for determining whether a previously generated
1902  * CachedData instance is still valid; the tag has no other meaing.
1903  *
1904  * Background: The data carried by CachedData may depend on the exact
1905  * V8 version number or current compiler flags. This means that when
1906  * persisting CachedData, the embedder must take care to not pass in
1907  * data from another V8 version, or the same version with different
1908  * features enabled.
1909  *
1910  * The easiest way to do so is to clear the embedder's cache on any
1911  * such change.
1912  *
1913  * Alternatively, this tag can be stored alongside the cached data and
1914  * compared when it is being used.
1915  */
1916  static uint32_t CachedDataVersionTag();
1917 
1918  /**
1919  * Compile an ES module, returning a Module that encapsulates
1920  * the compiled code.
1921  *
1922  * Corresponds to the ParseModule abstract operation in the
1923  * ECMAScript specification.
1924  */
1926  Isolate* isolate, Source* source,
1928  NoCacheReason no_cache_reason = kNoCacheNoReason);
1929 
1930  /**
1931  * Compile a function for a given context. This is equivalent to running
1932  *
1933  * with (obj) {
1934  * return function(args) { ... }
1935  * }
1936  *
1937  * It is possible to specify multiple context extensions (obj in the above
1938  * example).
1939  */
1941  Local<Context> context, Source* source, size_t arguments_count,
1942  Local<String> arguments[], size_t context_extension_count,
1943  Local<Object> context_extensions[],
1945  NoCacheReason no_cache_reason = kNoCacheNoReason,
1946  Local<ScriptOrModule>* script_or_module_out = nullptr);
1947 
1948  /**
1949  * Creates and returns code cache for the specified unbound_script.
1950  * This will return nullptr if the script cannot be serialized. The
1951  * CachedData returned by this function should be owned by the caller.
1952  */
1953  static CachedData* CreateCodeCache(Local<UnboundScript> unbound_script);
1954 
1955  /**
1956  * Creates and returns code cache for the specified unbound_module_script.
1957  * This will return nullptr if the script cannot be serialized. The
1958  * CachedData returned by this function should be owned by the caller.
1959  */
1960  static CachedData* CreateCodeCache(
1961  Local<UnboundModuleScript> unbound_module_script);
1962 
1963  /**
1964  * Creates and returns code cache for the specified function that was
1965  * previously produced by CompileFunctionInContext.
1966  * This will return nullptr if the script cannot be serialized. The
1967  * CachedData returned by this function should be owned by the caller.
1968  */
1970 
1971  private:
1972  static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundInternal(
1973  Isolate* isolate, Source* source, CompileOptions options,
1974  NoCacheReason no_cache_reason);
1975 };
1976 
1977 
1978 /**
1979  * An error message.
1980  */
1982  public:
1983  Local<String> Get() const;
1984 
1985  /**
1986  * Return the isolate to which the Message belongs.
1987  */
1988  Isolate* GetIsolate() const;
1989 
1991  Local<Context> context) const;
1992 
1993  /**
1994  * Returns the origin for the script from where the function causing the
1995  * error originates.
1996  */
1997  ScriptOrigin GetScriptOrigin() const;
1998 
1999  /**
2000  * Returns the resource name for the script from where the function causing
2001  * the error originates.
2002  */
2004 
2005  /**
2006  * Exception stack trace. By default stack traces are not captured for
2007  * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
2008  * to change this option.
2009  */
2010  Local<StackTrace> GetStackTrace() const;
2011 
2012  /**
2013  * Returns the number, 1-based, of the line where the error occurred.
2014  */
2015  V8_WARN_UNUSED_RESULT Maybe<int> GetLineNumber(Local<Context> context) const;
2016 
2017  /**
2018  * Returns the index within the script of the first character where
2019  * the error occurred.
2020  */
2021  int GetStartPosition() const;
2022 
2023  /**
2024  * Returns the index within the script of the last character where
2025  * the error occurred.
2026  */
2027  int GetEndPosition() const;
2028 
2029  /**
2030  * Returns the Wasm function index where the error occurred. Returns -1 if
2031  * message is not from a Wasm script.
2032  */
2033  int GetWasmFunctionIndex() const;
2034 
2035  /**
2036  * Returns the error level of the message.
2037  */
2038  int ErrorLevel() const;
2039 
2040  /**
2041  * Returns the index within the line of the first character where
2042  * the error occurred.
2043  */
2044  int GetStartColumn() const;
2046 
2047  /**
2048  * Returns the index within the line of the last character where
2049  * the error occurred.
2050  */
2051  int GetEndColumn() const;
2052  V8_WARN_UNUSED_RESULT Maybe<int> GetEndColumn(Local<Context> context) const;
2053 
2054  /**
2055  * Passes on the value set by the embedder when it fed the script from which
2056  * this Message was generated to V8.
2057  */
2058  bool IsSharedCrossOrigin() const;
2059  bool IsOpaque() const;
2060 
2061  // TODO(1245381): Print to a string instead of on a FILE.
2062  static void PrintCurrentStackTrace(Isolate* isolate, FILE* out);
2063 
2064  static const int kNoLineNumberInfo = 0;
2065  static const int kNoColumnInfo = 0;
2066  static const int kNoScriptIdInfo = 0;
2067  static const int kNoWasmFunctionIndexInfo = -1;
2068 };
2069 
2070 
2071 /**
2072  * Representation of a JavaScript stack trace. The information collected is a
2073  * snapshot of the execution stack and the information remains valid after
2074  * execution continues.
2075  */
2077  public:
2078  /**
2079  * Flags that determine what information is placed captured for each
2080  * StackFrame when grabbing the current stack trace.
2081  * Note: these options are deprecated and we always collect all available
2082  * information (kDetailed).
2083  */
2087  kScriptName = 1 << 2,
2088  kFunctionName = 1 << 3,
2089  kIsEval = 1 << 4,
2090  kIsConstructor = 1 << 5,
2092  kScriptId = 1 << 7,
2096  };
2097 
2098  /**
2099  * Returns a StackFrame at a particular index.
2100  */
2101  Local<StackFrame> GetFrame(Isolate* isolate, uint32_t index) const;
2102 
2103  /**
2104  * Returns the number of StackFrames.
2105  */
2106  int GetFrameCount() const;
2107 
2108  /**
2109  * Grab a snapshot of the current JavaScript execution stack.
2110  *
2111  * \param frame_limit The maximum number of stack frames we want to capture.
2112  * \param options Enumerates the set of things we will capture for each
2113  * StackFrame.
2114  */
2116  Isolate* isolate, int frame_limit, StackTraceOptions options = kDetailed);
2117 };
2118 
2119 
2120 /**
2121  * A single JavaScript stack frame.
2122  */
2124  public:
2125  /**
2126  * Returns the number, 1-based, of the line for the associate function call.
2127  * This method will return Message::kNoLineNumberInfo if it is unable to
2128  * retrieve the line number, or if kLineNumber was not passed as an option
2129  * when capturing the StackTrace.
2130  */
2131  int GetLineNumber() const;
2132 
2133  /**
2134  * Returns the 1-based column offset on the line for the associated function
2135  * call.
2136  * This method will return Message::kNoColumnInfo if it is unable to retrieve
2137  * the column number, or if kColumnOffset was not passed as an option when
2138  * capturing the StackTrace.
2139  */
2140  int GetColumn() const;
2141 
2142  /**
2143  * Returns the id of the script for the function for this StackFrame.
2144  * This method will return Message::kNoScriptIdInfo if it is unable to
2145  * retrieve the script id, or if kScriptId was not passed as an option when
2146  * capturing the StackTrace.
2147  */
2148  int GetScriptId() const;
2149 
2150  /**
2151  * Returns the name of the resource that contains the script for the
2152  * function for this StackFrame.
2153  */
2154  Local<String> GetScriptName() const;
2155 
2156  /**
2157  * Returns the name of the resource that contains the script for the
2158  * function for this StackFrame or sourceURL value if the script name
2159  * is undefined and its source ends with //# sourceURL=... string or
2160  * deprecated //@ sourceURL=... string.
2161  */
2163 
2164  /**
2165  * Returns the name of the function associated with this stack frame.
2166  */
2167  Local<String> GetFunctionName() const;
2168 
2169  /**
2170  * Returns whether or not the associated function is compiled via a call to
2171  * eval().
2172  */
2173  bool IsEval() const;
2174 
2175  /**
2176  * Returns whether or not the associated function is called as a
2177  * constructor via "new".
2178  */
2179  bool IsConstructor() const;
2180 
2181  /**
2182  * Returns whether or not the associated functions is defined in wasm.
2183  */
2184  bool IsWasm() const;
2185 
2186  /**
2187  * Returns whether or not the associated function is defined by the user.
2188  */
2189  bool IsUserJavaScript() const;
2190 };
2191 
2192 
2193 // A StateTag represents a possible state of the VM.
2194 enum StateTag {
2203 };
2204 
2205 // A RegisterState represents the current state of registers used
2206 // by the sampling profiler API.
2208  RegisterState() : pc(nullptr), sp(nullptr), fp(nullptr), lr(nullptr) {}
2209  void* pc; // Instruction pointer.
2210  void* sp; // Stack pointer.
2211  void* fp; // Frame pointer.
2212  void* lr; // Link register (or nullptr on platforms without a link register).
2213 };
2214 
2215 // The output structure filled up by GetStackSample API function.
2216 struct SampleInfo {
2217  size_t frames_count; // Number of frames collected.
2218  StateTag vm_state; // Current VM state.
2219  void* external_callback_entry; // External callback address if VM is
2220  // executing an external callback.
2221  void* top_context; // Incumbent native context address.
2222 };
2223 
2224 struct MemoryRange {
2225  const void* start = nullptr;
2226  size_t length_in_bytes = 0;
2227 };
2228 
2229 struct JSEntryStub {
2231 };
2232 
2233 struct UnwindState {
2239 };
2240 
2245 };
2246 
2247 /**
2248  * A JSON Parser and Stringifier.
2249  */
2251  public:
2252  /**
2253  * Tries to parse the string |json_string| and returns it as value if
2254  * successful.
2255  *
2256  * \param the context in which to parse and create the value.
2257  * \param json_string The string to parse.
2258  * \return The corresponding value if successfully parsed.
2259  */
2261  Local<Context> context, Local<String> json_string);
2262 
2263  /**
2264  * Tries to stringify the JSON-serializable object |json_object| and returns
2265  * it as string if successful.
2266  *
2267  * \param json_object The JSON-serializable object to stringify.
2268  * \return The corresponding string if successfully stringified.
2269  */
2271  Local<Context> context, Local<Value> json_object,
2272  Local<String> gap = Local<String>());
2273 };
2274 
2275 /**
2276  * Value serialization compatible with the HTML structured clone algorithm.
2277  * The format is backward-compatible (i.e. safe to store to disk).
2278  */
2280  public:
2282  public:
2283  virtual ~Delegate() = default;
2284 
2285  /**
2286  * Handles the case where a DataCloneError would be thrown in the structured
2287  * clone spec. Other V8 embedders may throw some other appropriate exception
2288  * type.
2289  */
2290  virtual void ThrowDataCloneError(Local<String> message) = 0;
2291 
2292  /**
2293  * The embedder overrides this method to write some kind of host object, if
2294  * possible. If not, a suitable exception should be thrown and
2295  * Nothing<bool>() returned.
2296  */
2297  virtual Maybe<bool> WriteHostObject(Isolate* isolate, Local<Object> object);
2298 
2299  /**
2300  * Called when the ValueSerializer is going to serialize a
2301  * SharedArrayBuffer object. The embedder must return an ID for the
2302  * object, using the same ID if this SharedArrayBuffer has already been
2303  * serialized in this buffer. When deserializing, this ID will be passed to
2304  * ValueDeserializer::GetSharedArrayBufferFromId as |clone_id|.
2305  *
2306  * If the object cannot be serialized, an
2307  * exception should be thrown and Nothing<uint32_t>() returned.
2308  */
2309  virtual Maybe<uint32_t> GetSharedArrayBufferId(
2310  Isolate* isolate, Local<SharedArrayBuffer> shared_array_buffer);
2311 
2312  virtual Maybe<uint32_t> GetWasmModuleTransferId(
2313  Isolate* isolate, Local<WasmModuleObject> module);
2314  /**
2315  * Allocates memory for the buffer of at least the size provided. The actual
2316  * size (which may be greater or equal) is written to |actual_size|. If no
2317  * buffer has been allocated yet, nullptr will be provided.
2318  *
2319  * If the memory cannot be allocated, nullptr should be returned.
2320  * |actual_size| will be ignored. It is assumed that |old_buffer| is still
2321  * valid in this case and has not been modified.
2322  *
2323  * The default implementation uses the stdlib's `realloc()` function.
2324  */
2325  virtual void* ReallocateBufferMemory(void* old_buffer, size_t size,
2326  size_t* actual_size);
2327 
2328  /**
2329  * Frees a buffer allocated with |ReallocateBufferMemory|.
2330  *
2331  * The default implementation uses the stdlib's `free()` function.
2332  */
2333  virtual void FreeBufferMemory(void* buffer);
2334  };
2335 
2336  explicit ValueSerializer(Isolate* isolate);
2337  ValueSerializer(Isolate* isolate, Delegate* delegate);
2338  ~ValueSerializer();
2339 
2340  /**
2341  * Writes out a header, which includes the format version.
2342  */
2343  void WriteHeader();
2344 
2345  /**
2346  * Serializes a JavaScript value into the buffer.
2347  */
2349  Local<Value> value);
2350 
2351  /**
2352  * Returns the stored data (allocated using the delegate's
2353  * ReallocateBufferMemory) and its size. This serializer should not be used
2354  * once the buffer is released. The contents are undefined if a previous write
2355  * has failed. Ownership of the buffer is transferred to the caller.
2356  */
2357  V8_WARN_UNUSED_RESULT std::pair<uint8_t*, size_t> Release();
2358 
2359  /**
2360  * Marks an ArrayBuffer as havings its contents transferred out of band.
2361  * Pass the corresponding ArrayBuffer in the deserializing context to
2362  * ValueDeserializer::TransferArrayBuffer.
2363  */
2364  void TransferArrayBuffer(uint32_t transfer_id,
2365  Local<ArrayBuffer> array_buffer);
2366 
2367 
2368  /**
2369  * Indicate whether to treat ArrayBufferView objects as host objects,
2370  * i.e. pass them to Delegate::WriteHostObject. This should not be
2371  * called when no Delegate was passed.
2372  *
2373  * The default is not to treat ArrayBufferViews as host objects.
2374  */
2375  void SetTreatArrayBufferViewsAsHostObjects(bool mode);
2376 
2377  /**
2378  * Write raw data in various common formats to the buffer.
2379  * Note that integer types are written in base-128 varint format, not with a
2380  * binary copy. For use during an override of Delegate::WriteHostObject.
2381  */
2382  void WriteUint32(uint32_t value);
2383  void WriteUint64(uint64_t value);
2384  void WriteDouble(double value);
2385  void WriteRawBytes(const void* source, size_t length);
2386 
2387  ValueSerializer(const ValueSerializer&) = delete;
2388  void operator=(const ValueSerializer&) = delete;
2389 
2390  private:
2391  struct PrivateData;
2392  PrivateData* private_;
2393 };
2394 
2395 /**
2396  * Deserializes values from data written with ValueSerializer, or a compatible
2397  * implementation.
2398  */
2400  public:
2402  public:
2403  virtual ~Delegate() = default;
2404 
2405  /**
2406  * The embedder overrides this method to read some kind of host object, if
2407  * possible. If not, a suitable exception should be thrown and
2408  * MaybeLocal<Object>() returned.
2409  */
2410  virtual MaybeLocal<Object> ReadHostObject(Isolate* isolate);
2411 
2412  /**
2413  * Get a WasmModuleObject given a transfer_id previously provided
2414  * by ValueSerializer::GetWasmModuleTransferId
2415  */
2417  Isolate* isolate, uint32_t transfer_id);
2418 
2419  /**
2420  * Get a SharedArrayBuffer given a clone_id previously provided
2421  * by ValueSerializer::GetSharedArrayBufferId
2422  */
2424  Isolate* isolate, uint32_t clone_id);
2425  };
2426 
2427  ValueDeserializer(Isolate* isolate, const uint8_t* data, size_t size);
2428  ValueDeserializer(Isolate* isolate, const uint8_t* data, size_t size,
2429  Delegate* delegate);
2430  ~ValueDeserializer();
2431 
2432  /**
2433  * Reads and validates a header (including the format version).
2434  * May, for example, reject an invalid or unsupported wire format.
2435  */
2437 
2438  /**
2439  * Deserializes a JavaScript value from the buffer.
2440  */
2442 
2443  /**
2444  * Accepts the array buffer corresponding to the one passed previously to
2445  * ValueSerializer::TransferArrayBuffer.
2446  */
2447  void TransferArrayBuffer(uint32_t transfer_id,
2448  Local<ArrayBuffer> array_buffer);
2449 
2450  /**
2451  * Similar to TransferArrayBuffer, but for SharedArrayBuffer.
2452  * The id is not necessarily in the same namespace as unshared ArrayBuffer
2453  * objects.
2454  */
2455  void TransferSharedArrayBuffer(uint32_t id,
2456  Local<SharedArrayBuffer> shared_array_buffer);
2457 
2458  /**
2459  * Must be called before ReadHeader to enable support for reading the legacy
2460  * wire format (i.e., which predates this being shipped).
2461  *
2462  * Don't use this unless you need to read data written by previous versions of
2463  * blink::ScriptValueSerializer.
2464  */
2465  void SetSupportsLegacyWireFormat(bool supports_legacy_wire_format);
2466 
2467  /**
2468  * Expect inline wasm in the data stream (rather than in-memory transfer)
2469  */
2471  "Wasm module serialization is only supported via explicit methods, e.g. "
2472  "CompiledWasmModule::Serialize()")
2473  void SetExpectInlineWasm(bool allow_inline_wasm) {}
2474 
2475  /**
2476  * Reads the underlying wire format version. Likely mostly to be useful to
2477  * legacy code reading old wire format versions. Must be called after
2478  * ReadHeader.
2479  */
2480  uint32_t GetWireFormatVersion() const;
2481 
2482  /**
2483  * Reads raw data in various common formats to the buffer.
2484  * Note that integer types are read in base-128 varint format, not with a
2485  * binary copy. For use during an override of Delegate::ReadHostObject.
2486  */
2487  V8_WARN_UNUSED_RESULT bool ReadUint32(uint32_t* value);
2488  V8_WARN_UNUSED_RESULT bool ReadUint64(uint64_t* value);
2489  V8_WARN_UNUSED_RESULT bool ReadDouble(double* value);
2490  V8_WARN_UNUSED_RESULT bool ReadRawBytes(size_t length, const void** data);
2491 
2492  ValueDeserializer(const ValueDeserializer&) = delete;
2493  void operator=(const ValueDeserializer&) = delete;
2494 
2495  private:
2496  struct PrivateData;
2497  PrivateData* private_;
2498 };
2499 
2500 
2501 // --- Value ---
2502 
2503 
2504 /**
2505  * The superclass of all JavaScript values and objects.
2506  */
2507 class V8_EXPORT Value : public Data {
2508  public:
2509  /**
2510  * Returns true if this value is the undefined value. See ECMA-262
2511  * 4.3.10.
2512  *
2513  * This is equivalent to `value === undefined` in JS.
2514  */
2515  V8_INLINE bool IsUndefined() const;
2516 
2517  /**
2518  * Returns true if this value is the null value. See ECMA-262
2519  * 4.3.11.
2520  *
2521  * This is equivalent to `value === null` in JS.
2522  */
2523  V8_INLINE bool IsNull() const;
2524 
2525  /**
2526  * Returns true if this value is either the null or the undefined value.
2527  * See ECMA-262
2528  * 4.3.11. and 4.3.12
2529  *
2530  * This is equivalent to `value == null` in JS.
2531  */
2532  V8_INLINE bool IsNullOrUndefined() const;
2533 
2534  /**
2535  * Returns true if this value is true.
2536  *
2537  * This is not the same as `BooleanValue()`. The latter performs a
2538  * conversion to boolean, i.e. the result of `Boolean(value)` in JS, whereas
2539  * this checks `value === true`.
2540  */
2541  bool IsTrue() const;
2542 
2543  /**
2544  * Returns true if this value is false.
2545  *
2546  * This is not the same as `!BooleanValue()`. The latter performs a
2547  * conversion to boolean, i.e. the result of `!Boolean(value)` in JS, whereas
2548  * this checks `value === false`.
2549  */
2550  bool IsFalse() const;
2551 
2552  /**
2553  * Returns true if this value is a symbol or a string.
2554  *
2555  * This is equivalent to
2556  * `typeof value === 'string' || typeof value === 'symbol'` in JS.
2557  */
2558  bool IsName() const;
2559 
2560  /**
2561  * Returns true if this value is an instance of the String type.
2562  * See ECMA-262 8.4.
2563  *
2564  * This is equivalent to `typeof value === 'string'` in JS.
2565  */
2566  V8_INLINE bool IsString() const;
2567 
2568  /**
2569  * Returns true if this value is a symbol.
2570  *
2571  * This is equivalent to `typeof value === 'symbol'` in JS.
2572  */
2573  bool IsSymbol() const;
2574 
2575  /**
2576  * Returns true if this value is a function.
2577  *
2578  * This is equivalent to `typeof value === 'function'` in JS.
2579  */
2580  bool IsFunction() const;
2581 
2582  /**
2583  * Returns true if this value is an array. Note that it will return false for
2584  * an Proxy for an array.
2585  */
2586  bool IsArray() const;
2587 
2588  /**
2589  * Returns true if this value is an object.
2590  */
2591  bool IsObject() const;
2592 
2593  /**
2594  * Returns true if this value is a bigint.
2595  *
2596  * This is equivalent to `typeof value === 'bigint'` in JS.
2597  */
2598  bool IsBigInt() const;
2599 
2600  /**
2601  * Returns true if this value is boolean.
2602  *
2603  * This is equivalent to `typeof value === 'boolean'` in JS.
2604  */
2605  bool IsBoolean() const;
2606 
2607  /**
2608  * Returns true if this value is a number.
2609  *
2610  * This is equivalent to `typeof value === 'number'` in JS.
2611  */
2612  bool IsNumber() const;
2613 
2614  /**
2615  * Returns true if this value is an `External` object.
2616  */
2617  bool IsExternal() const;
2618 
2619  /**
2620  * Returns true if this value is a 32-bit signed integer.
2621  */
2622  bool IsInt32() const;
2623 
2624  /**
2625  * Returns true if this value is a 32-bit unsigned integer.
2626  */
2627  bool IsUint32() const;
2628 
2629  /**
2630  * Returns true if this value is a Date.
2631  */
2632  bool IsDate() const;
2633 
2634  /**
2635  * Returns true if this value is an Arguments object.
2636  */
2637  bool IsArgumentsObject() const;
2638 
2639  /**
2640  * Returns true if this value is a BigInt object.
2641  */
2642  bool IsBigIntObject() const;
2643 
2644  /**
2645  * Returns true if this value is a Boolean object.
2646  */
2647  bool IsBooleanObject() const;
2648 
2649  /**
2650  * Returns true if this value is a Number object.
2651  */
2652  bool IsNumberObject() const;
2653 
2654  /**
2655  * Returns true if this value is a String object.
2656  */
2657  bool IsStringObject() const;
2658 
2659  /**
2660  * Returns true if this value is a Symbol object.
2661  */
2662  bool IsSymbolObject() const;
2663 
2664  /**
2665  * Returns true if this value is a NativeError.
2666  */
2667  bool IsNativeError() const;
2668 
2669  /**
2670  * Returns true if this value is a RegExp.
2671  */
2672  bool IsRegExp() const;
2673 
2674  /**
2675  * Returns true if this value is an async function.
2676  */
2677  bool IsAsyncFunction() const;
2678 
2679  /**
2680  * Returns true if this value is a Generator function.
2681  */
2682  bool IsGeneratorFunction() const;
2683 
2684  /**
2685  * Returns true if this value is a Generator object (iterator).
2686  */
2687  bool IsGeneratorObject() const;
2688 
2689  /**
2690  * Returns true if this value is a Promise.
2691  */
2692  bool IsPromise() const;
2693 
2694  /**
2695  * Returns true if this value is a Map.
2696  */
2697  bool IsMap() const;
2698 
2699  /**
2700  * Returns true if this value is a Set.
2701  */
2702  bool IsSet() const;
2703 
2704  /**
2705  * Returns true if this value is a Map Iterator.
2706  */
2707  bool IsMapIterator() const;
2708 
2709  /**
2710  * Returns true if this value is a Set Iterator.
2711  */
2712  bool IsSetIterator() const;
2713 
2714  /**
2715  * Returns true if this value is a WeakMap.
2716  */
2717  bool IsWeakMap() const;
2718 
2719  /**
2720  * Returns true if this value is a WeakSet.
2721  */
2722  bool IsWeakSet() const;
2723 
2724  /**
2725  * Returns true if this value is an ArrayBuffer.
2726  */
2727  bool IsArrayBuffer() const;
2728 
2729  /**
2730  * Returns true if this value is an ArrayBufferView.
2731  */
2732  bool IsArrayBufferView() const;
2733 
2734  /**
2735  * Returns true if this value is one of TypedArrays.
2736  */
2737  bool IsTypedArray() const;
2738 
2739  /**
2740  * Returns true if this value is an Uint8Array.
2741  */
2742  bool IsUint8Array() const;
2743 
2744  /**
2745  * Returns true if this value is an Uint8ClampedArray.
2746  */
2747  bool IsUint8ClampedArray() const;
2748 
2749  /**
2750  * Returns true if this value is an Int8Array.
2751  */
2752  bool IsInt8Array() const;
2753 
2754  /**
2755  * Returns true if this value is an Uint16Array.
2756  */
2757  bool IsUint16Array() const;
2758 
2759  /**
2760  * Returns true if this value is an Int16Array.
2761  */
2762  bool IsInt16Array() const;
2763 
2764  /**
2765  * Returns true if this value is an Uint32Array.
2766  */
2767  bool IsUint32Array() const;
2768 
2769  /**
2770  * Returns true if this value is an Int32Array.
2771  */
2772  bool IsInt32Array() const;
2773 
2774  /**
2775  * Returns true if this value is a Float32Array.
2776  */
2777  bool IsFloat32Array() const;
2778 
2779  /**
2780  * Returns true if this value is a Float64Array.
2781  */
2782  bool IsFloat64Array() const;
2783 
2784  /**
2785  * Returns true if this value is a BigInt64Array.
2786  */
2787  bool IsBigInt64Array() const;
2788 
2789  /**
2790  * Returns true if this value is a BigUint64Array.
2791  */
2792  bool IsBigUint64Array() const;
2793 
2794  /**
2795  * Returns true if this value is a DataView.
2796  */
2797  bool IsDataView() const;
2798 
2799  /**
2800  * Returns true if this value is a SharedArrayBuffer.
2801  */
2802  bool IsSharedArrayBuffer() const;
2803 
2804  /**
2805  * Returns true if this value is a JavaScript Proxy.
2806  */
2807  bool IsProxy() const;
2808 
2809  /**
2810  * Returns true if this value is a WasmModuleObject.
2811  */
2812  bool IsWasmModuleObject() const;
2813 
2814  V8_DEPRECATED("Use IsWasmModuleObject")
2815  bool IsWebAssemblyCompiledModule() const;
2816 
2817  /**
2818  * Returns true if the value is a Module Namespace Object.
2819  */
2820  bool IsModuleNamespaceObject() const;
2821 
2822  /**
2823  * Perform the equivalent of `BigInt(value)` in JS.
2824  */
2826  Local<Context> context) const;
2827  /**
2828  * Perform the equivalent of `Number(value)` in JS.
2829  */
2831  Local<Context> context) const;
2832  /**
2833  * Perform the equivalent of `String(value)` in JS.
2834  */
2836  Local<Context> context) const;
2837  /**
2838  * Provide a string representation of this value usable for debugging.
2839  * This operation has no observable side effects and will succeed
2840  * unless e.g. execution is being terminated.
2841  */
2843  Local<Context> context) const;
2844  /**
2845  * Perform the equivalent of `Object(value)` in JS.
2846  */
2848  Local<Context> context) const;
2849  /**
2850  * Perform the equivalent of `Number(value)` in JS and convert the result
2851  * to an integer. Negative values are rounded up, positive values are rounded
2852  * down. NaN is converted to 0. Infinite values yield undefined results.
2853  */
2855  Local<Context> context) const;
2856  /**
2857  * Perform the equivalent of `Number(value)` in JS and convert the result
2858  * to an unsigned 32-bit integer by performing the steps in
2859  * https://tc39.es/ecma262/#sec-touint32.
2860  */
2862  Local<Context> context) const;
2863  /**
2864  * Perform the equivalent of `Number(value)` in JS and convert the result
2865  * to a signed 32-bit integer by performing the steps in
2866  * https://tc39.es/ecma262/#sec-toint32.
2867  */
2869 
2870  /**
2871  * Perform the equivalent of `Boolean(value)` in JS. This can never fail.
2872  */
2873  Local<Boolean> ToBoolean(Isolate* isolate) const;
2874 
2875  /**
2876  * Attempts to convert a string to an array index.
2877  * Returns an empty handle if the conversion fails.
2878  */
2880  Local<Context> context) const;
2881 
2882  /** Returns the equivalent of `ToBoolean()->Value()`. */
2883  bool BooleanValue(Isolate* isolate) const;
2884 
2885  /** Returns the equivalent of `ToNumber()->Value()`. */
2886  V8_WARN_UNUSED_RESULT Maybe<double> NumberValue(Local<Context> context) const;
2887  /** Returns the equivalent of `ToInteger()->Value()`. */
2889  Local<Context> context) const;
2890  /** Returns the equivalent of `ToUint32()->Value()`. */
2892  Local<Context> context) const;
2893  /** Returns the equivalent of `ToInt32()->Value()`. */
2894  V8_WARN_UNUSED_RESULT Maybe<int32_t> Int32Value(Local<Context> context) const;
2895 
2896  /** JS == */
2898  Local<Value> that) const;
2899  bool StrictEquals(Local<Value> that) const;
2900  bool SameValue(Local<Value> that) const;
2901 
2902  template <class T> V8_INLINE static Value* Cast(T* value);
2903 
2905 
2906  Maybe<bool> InstanceOf(Local<Context> context, Local<Object> object);
2907 
2908  private:
2909  V8_INLINE bool QuickIsUndefined() const;
2910  V8_INLINE bool QuickIsNull() const;
2911  V8_INLINE bool QuickIsNullOrUndefined() const;
2912  V8_INLINE bool QuickIsString() const;
2913  bool FullIsUndefined() const;
2914  bool FullIsNull() const;
2915  bool FullIsString() const;
2916 };
2917 
2918 
2919 /**
2920  * The superclass of primitive values. See ECMA-262 4.3.2.
2921  */
2922 class V8_EXPORT Primitive : public Value { };
2923 
2924 
2925 /**
2926  * A primitive boolean value (ECMA-262, 4.3.14). Either the true
2927  * or false value.
2928  */
2929 class V8_EXPORT Boolean : public Primitive {
2930  public:
2931  bool Value() const;
2932  V8_INLINE static Boolean* Cast(v8::Value* obj);
2933  V8_INLINE static Local<Boolean> New(Isolate* isolate, bool value);
2934 
2935  private:
2936  static void CheckCast(v8::Value* obj);
2937 };
2938 
2939 
2940 /**
2941  * A superclass for symbols and strings.
2942  */
2943 class V8_EXPORT Name : public Primitive {
2944  public:
2945  /**
2946  * Returns the identity hash for this object. The current implementation
2947  * uses an inline property on the object to store the identity hash.
2948  *
2949  * The return value will never be 0. Also, it is not guaranteed to be
2950  * unique.
2951  */
2952  int GetIdentityHash();
2953 
2954  V8_INLINE static Name* Cast(Value* obj);
2955 
2956  private:
2957  static void CheckCast(Value* obj);
2958 };
2959 
2960 /**
2961  * A flag describing different modes of string creation.
2962  *
2963  * Aside from performance implications there are no differences between the two
2964  * creation modes.
2965  */
2966 enum class NewStringType {
2967  /**
2968  * Create a new string, always allocating new storage memory.
2969  */
2970  kNormal,
2971 
2972  /**
2973  * Acts as a hint that the string should be created in the
2974  * old generation heap space and be deduplicated if an identical string
2975  * already exists.
2976  */
2978 };
2979 
2980 /**
2981  * A JavaScript string value (ECMA-262, 4.3.17).
2982  */
2983 class V8_EXPORT String : public Name {
2984  public:
2985  static constexpr int kMaxLength = internal::kApiTaggedSize == 4
2986  ? (1 << 28) - 16
2987  : internal::kSmiMaxValue / 2 - 24;
2988 
2989  enum Encoding {
2993  };
2994  /**
2995  * Returns the number of characters (UTF-16 code units) in this string.
2996  */
2997  int Length() const;
2998 
2999  /**
3000  * Returns the number of bytes in the UTF-8 encoded
3001  * representation of this string.
3002  */
3003  int Utf8Length(Isolate* isolate) const;
3004 
3005  /**
3006  * Returns whether this string is known to contain only one byte data,
3007  * i.e. ISO-8859-1 code points.
3008  * Does not read the string.
3009  * False negatives are possible.
3010  */
3011  bool IsOneByte() const;
3012 
3013  /**
3014  * Returns whether this string contain only one byte data,
3015  * i.e. ISO-8859-1 code points.
3016  * Will read the entire string in some cases.
3017  */
3018  bool ContainsOnlyOneByte() const;
3019 
3020  /**
3021  * Write the contents of the string to an external buffer.
3022  * If no arguments are given, expects the buffer to be large
3023  * enough to hold the entire string and NULL terminator. Copies
3024  * the contents of the string and the NULL terminator into the
3025  * buffer.
3026  *
3027  * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
3028  * before the end of the buffer.
3029  *
3030  * Copies up to length characters into the output buffer.
3031  * Only null-terminates if there is enough space in the buffer.
3032  *
3033  * \param buffer The buffer into which the string will be copied.
3034  * \param start The starting position within the string at which
3035  * copying begins.
3036  * \param length The number of characters to copy from the string. For
3037  * WriteUtf8 the number of bytes in the buffer.
3038  * \param nchars_ref The number of characters written, can be NULL.
3039  * \param options Various options that might affect performance of this or
3040  * subsequent operations.
3041  * \return The number of characters copied to the buffer excluding the null
3042  * terminator. For WriteUtf8: The number of bytes copied to the buffer
3043  * including the null terminator (if written).
3044  */
3050  // Used by WriteUtf8 to replace orphan surrogate code units with the
3051  // unicode replacement character. Needs to be set to guarantee valid UTF-8
3052  // output.
3054  };
3055 
3056  // 16-bit character codes.
3057  int Write(Isolate* isolate, uint16_t* buffer, int start = 0, int length = -1,
3058  int options = NO_OPTIONS) const;
3059  // One byte characters.
3060  int WriteOneByte(Isolate* isolate, uint8_t* buffer, int start = 0,
3061  int length = -1, int options = NO_OPTIONS) const;
3062  // UTF-8 encoded characters.
3063  int WriteUtf8(Isolate* isolate, char* buffer, int length = -1,
3064  int* nchars_ref = nullptr, int options = NO_OPTIONS) const;
3065 
3066  /**
3067  * A zero length string.
3068  */
3069  V8_INLINE static Local<String> Empty(Isolate* isolate);
3070 
3071  /**
3072  * Returns true if the string is external
3073  */
3074  bool IsExternal() const;
3075 
3076  /**
3077  * Returns true if the string is both external and one-byte.
3078  */
3079  bool IsExternalOneByte() const;
3080 
3082  public:
3083  virtual ~ExternalStringResourceBase() = default;
3084 
3085  /**
3086  * If a string is cacheable, the value returned by
3087  * ExternalStringResource::data() may be cached, otherwise it is not
3088  * expected to be stable beyond the current top-level task.
3089  */
3090  virtual bool IsCacheable() const { return true; }
3091 
3092  // Disallow copying and assigning.
3094  void operator=(const ExternalStringResourceBase&) = delete;
3095 
3096  protected:
3097  ExternalStringResourceBase() = default;
3098 
3099  /**
3100  * Internally V8 will call this Dispose method when the external string
3101  * resource is no longer needed. The default implementation will use the
3102  * delete operator. This method can be overridden in subclasses to
3103  * control how allocated external string resources are disposed.
3104  */
3105  virtual void Dispose() { delete this; }
3106 
3107  /**
3108  * For a non-cacheable string, the value returned by
3109  * |ExternalStringResource::data()| has to be stable between |Lock()| and
3110  * |Unlock()|, that is the string must behave as is |IsCacheable()| returned
3111  * true.
3112  *
3113  * These two functions must be thread-safe, and can be called from anywhere.
3114  * They also must handle lock depth, in the sense that each can be called
3115  * several times, from different threads, and unlocking should only happen
3116  * when the balance of Lock() and Unlock() calls is 0.
3117  */
3118  virtual void Lock() const {}
3119 
3120  /**
3121  * Unlocks the string.
3122  */
3123  virtual void Unlock() const {}
3124 
3125  private:
3126  friend class internal::ExternalString;
3127  friend class v8::String;
3128  friend class internal::ScopedExternalStringLock;
3129  };
3130 
3131  /**
3132  * An ExternalStringResource is a wrapper around a two-byte string
3133  * buffer that resides outside V8's heap. Implement an
3134  * ExternalStringResource to manage the life cycle of the underlying
3135  * buffer. Note that the string data must be immutable.
3136  */
3138  : public ExternalStringResourceBase {
3139  public:
3140  /**
3141  * Override the destructor to manage the life cycle of the underlying
3142  * buffer.
3143  */
3144  ~ExternalStringResource() override = default;
3145 
3146  /**
3147  * The string data from the underlying buffer.
3148  */
3149  virtual const uint16_t* data() const = 0;
3150 
3151  /**
3152  * The length of the string. That is, the number of two-byte characters.
3153  */
3154  virtual size_t length() const = 0;
3155 
3156  protected:
3157  ExternalStringResource() = default;
3158  };
3159 
3160  /**
3161  * An ExternalOneByteStringResource is a wrapper around an one-byte
3162  * string buffer that resides outside V8's heap. Implement an
3163  * ExternalOneByteStringResource to manage the life cycle of the
3164  * underlying buffer. Note that the string data must be immutable
3165  * and that the data must be Latin-1 and not UTF-8, which would require
3166  * special treatment internally in the engine and do not allow efficient
3167  * indexing. Use String::New or convert to 16 bit data for non-Latin1.
3168  */
3169 
3171  : public ExternalStringResourceBase {
3172  public:
3173  /**
3174  * Override the destructor to manage the life cycle of the underlying
3175  * buffer.
3176  */
3177  ~ExternalOneByteStringResource() override = default;
3178  /** The string data from the underlying buffer.*/
3179  virtual const char* data() const = 0;
3180  /** The number of Latin-1 characters in the string.*/
3181  virtual size_t length() const = 0;
3182  protected:
3183  ExternalOneByteStringResource() = default;
3184  };
3185 
3186  /**
3187  * If the string is an external string, return the ExternalStringResourceBase
3188  * regardless of the encoding, otherwise return NULL. The encoding of the
3189  * string is returned in encoding_out.
3190  */
3192  Encoding* encoding_out) const;
3193 
3194  /**
3195  * Get the ExternalStringResource for an external string. Returns
3196  * NULL if IsExternal() doesn't return true.
3197  */
3199 
3200  /**
3201  * Get the ExternalOneByteStringResource for an external one-byte string.
3202  * Returns NULL if IsExternalOneByte() doesn't return true.
3203  */
3205 
3206  V8_INLINE static String* Cast(v8::Value* obj);
3207 
3208  /** Allocates a new string from UTF-8 data. Only returns an empty value when
3209  * length > kMaxLength. **/
3211  Isolate* isolate, const char* data,
3212  NewStringType type = NewStringType::kNormal, int length = -1);
3213 
3214  /** Allocates a new string from Latin-1 data. Only returns an empty value
3215  * when length > kMaxLength. **/
3217  Isolate* isolate, const uint8_t* data,
3218  NewStringType type = NewStringType::kNormal, int length = -1);
3219 
3220  /** Allocates a new string from UTF-16 data. Only returns an empty value when
3221  * length > kMaxLength. **/
3223  Isolate* isolate, const uint16_t* data,
3224  NewStringType type = NewStringType::kNormal, int length = -1);
3225 
3226  /**
3227  * Creates a new string by concatenating the left and the right strings
3228  * passed in as parameters.
3229  */
3230  static Local<String> Concat(Isolate* isolate, Local<String> left,
3231  Local<String> right);
3232 
3233  /**
3234  * Creates a new external string using the data defined in the given
3235  * resource. When the external string is no longer live on V8's heap the
3236  * resource will be disposed by calling its Dispose method. The caller of
3237  * this function should not otherwise delete or modify the resource. Neither
3238  * should the underlying buffer be deallocated or modified except through the
3239  * destructor of the external string resource.
3240  */
3242  Isolate* isolate, ExternalStringResource* resource);
3243 
3244  /**
3245  * Associate an external string resource with this string by transforming it
3246  * in place so that existing references to this string in the JavaScript heap
3247  * will use the external string resource. The external string resource's
3248  * character contents need to be equivalent to this string.
3249  * Returns true if the string has been changed to be an external string.
3250  * The string is not modified if the operation fails. See NewExternal for
3251  * information on the lifetime of the resource.
3252  */
3253  bool MakeExternal(ExternalStringResource* resource);
3254 
3255  /**
3256  * Creates a new external string using the one-byte data defined in the given
3257  * resource. When the external string is no longer live on V8's heap the
3258  * resource will be disposed by calling its Dispose method. The caller of
3259  * this function should not otherwise delete or modify the resource. Neither
3260  * should the underlying buffer be deallocated or modified except through the
3261  * destructor of the external string resource.
3262  */
3264  Isolate* isolate, ExternalOneByteStringResource* resource);
3265 
3266  /**
3267  * Associate an external string resource with this string by transforming it
3268  * in place so that existing references to this string in the JavaScript heap
3269  * will use the external string resource. The external string resource's
3270  * character contents need to be equivalent to this string.
3271  * Returns true if the string has been changed to be an external string.
3272  * The string is not modified if the operation fails. See NewExternal for
3273  * information on the lifetime of the resource.
3274  */
3276 
3277  /**
3278  * Returns true if this string can be made external.
3279  */
3280  bool CanMakeExternal();
3281 
3282  /**
3283  * Returns true if the strings values are equal. Same as JS ==/===.
3284  */
3285  bool StringEquals(Local<String> str);
3286 
3287  /**
3288  * Converts an object to a UTF-8-encoded character array. Useful if
3289  * you want to print the object. If conversion to a string fails
3290  * (e.g. due to an exception in the toString() method of the object)
3291  * then the length() method returns 0 and the * operator returns
3292  * NULL.
3293  */
3295  public:
3296  Utf8Value(Isolate* isolate, Local<v8::Value> obj);
3297  ~Utf8Value();
3298  char* operator*() { return str_; }
3299  const char* operator*() const { return str_; }
3300  int length() const { return length_; }
3301 
3302  // Disallow copying and assigning.
3303  Utf8Value(const Utf8Value&) = delete;
3304  void operator=(const Utf8Value&) = delete;
3305 
3306  private:
3307  char* str_;
3308  int length_;
3309  };
3310 
3311  /**
3312  * Converts an object to a two-byte (UTF-16-encoded) string.
3313  * If conversion to a string fails (eg. due to an exception in the toString()
3314  * method of the object) then the length() method returns 0 and the * operator
3315  * returns NULL.
3316  */
3318  public:
3319  Value(Isolate* isolate, Local<v8::Value> obj);
3320  ~Value();
3321  uint16_t* operator*() { return str_; }
3322  const uint16_t* operator*() const { return str_; }
3323  int length() const { return length_; }
3324 
3325  // Disallow copying and assigning.
3326  Value(const Value&) = delete;
3327  void operator=(const Value&) = delete;
3328 
3329  private:
3330  uint16_t* str_;
3331  int length_;
3332  };
3333 
3334  private:
3335  void VerifyExternalStringResourceBase(ExternalStringResourceBase* v,
3336  Encoding encoding) const;
3337  void VerifyExternalStringResource(ExternalStringResource* val) const;
3338  ExternalStringResource* GetExternalStringResourceSlow() const;
3339  ExternalStringResourceBase* GetExternalStringResourceBaseSlow(
3340  String::Encoding* encoding_out) const;
3341 
3342  static void CheckCast(v8::Value* obj);
3343 };
3344 
3345 
3346 /**
3347  * A JavaScript symbol (ECMA-262 edition 6)
3348  */
3349 class V8_EXPORT Symbol : public Name {
3350  public:
3351  /**
3352  * Returns the description string of the symbol, or undefined if none.
3353  */
3354  Local<Value> Description() const;
3355 
3356  V8_DEPRECATE_SOON("Use Symbol::Description()")
3357  Local<Value> Name() const { return Description(); }
3358 
3359  /**
3360  * Create a symbol. If description is not empty, it will be used as the
3361  * description.
3362  */
3363  static Local<Symbol> New(Isolate* isolate,
3364  Local<String> description = Local<String>());
3365 
3366  /**
3367  * Access global symbol registry.
3368  * Note that symbols created this way are never collected, so
3369  * they should only be used for statically fixed properties.
3370  * Also, there is only one global name space for the descriptions used as
3371  * keys.
3372  * To minimize the potential for clashes, use qualified names as keys.
3373  */
3374  static Local<Symbol> For(Isolate* isolate, Local<String> description);
3375 
3376  /**
3377  * Retrieve a global symbol. Similar to |For|, but using a separate
3378  * registry that is not accessible by (and cannot clash with) JavaScript code.
3379  */
3380  static Local<Symbol> ForApi(Isolate* isolate, Local<String> description);
3381 
3382  // Well-known symbols
3383  static Local<Symbol> GetAsyncIterator(Isolate* isolate);
3384  static Local<Symbol> GetHasInstance(Isolate* isolate);
3385  static Local<Symbol> GetIsConcatSpreadable(Isolate* isolate);
3386  static Local<Symbol> GetIterator(Isolate* isolate);
3387  static Local<Symbol> GetMatch(Isolate* isolate);
3388  static Local<Symbol> GetReplace(Isolate* isolate);
3389  static Local<Symbol> GetSearch(Isolate* isolate);
3390  static Local<Symbol> GetSplit(Isolate* isolate);
3391  static Local<Symbol> GetToPrimitive(Isolate* isolate);
3392  static Local<Symbol> GetToStringTag(Isolate* isolate);
3393  static Local<Symbol> GetUnscopables(Isolate* isolate);
3394 
3395  V8_INLINE static Symbol* Cast(Value* obj);
3396 
3397  private:
3398  Symbol();
3399  static void CheckCast(Value* obj);
3400 };
3401 
3402 
3403 /**
3404  * A private symbol
3405  *
3406  * This is an experimental feature. Use at your own risk.
3407  */
3408 class V8_EXPORT Private : public Data {
3409  public:
3410  /**
3411  * Returns the print name string of the private symbol, or undefined if none.
3412  */
3413  Local<Value> Name() const;
3414 
3415  /**
3416  * Create a private symbol. If name is not empty, it will be the description.
3417  */
3418  static Local<Private> New(Isolate* isolate,
3419  Local<String> name = Local<String>());
3420 
3421  /**
3422  * Retrieve a global private symbol. If a symbol with this name has not
3423  * been retrieved in the same isolate before, it is created.
3424  * Note that private symbols created this way are never collected, so
3425  * they should only be used for statically fixed properties.
3426  * Also, there is only one global name space for the names used as keys.
3427  * To minimize the potential for clashes, use qualified names as keys,
3428  * e.g., "Class#property".
3429  */
3430  static Local<Private> ForApi(Isolate* isolate, Local<String> name);
3431 
3432  V8_INLINE static Private* Cast(Data* data);
3433 
3434  private:
3435  Private();
3436 
3437  static void CheckCast(Data* that);
3438 };
3439 
3440 
3441 /**
3442  * A JavaScript number value (ECMA-262, 4.3.20)
3443  */
3444 class V8_EXPORT Number : public Primitive {
3445  public:
3446  double Value() const;
3447  static Local<Number> New(Isolate* isolate, double value);
3448  V8_INLINE static Number* Cast(v8::Value* obj);
3449  private:
3450  Number();
3451  static void CheckCast(v8::Value* obj);
3452 };
3453 
3454 
3455 /**
3456  * A JavaScript value representing a signed integer.
3457  */
3458 class V8_EXPORT Integer : public Number {
3459  public:
3460  static Local<Integer> New(Isolate* isolate, int32_t value);
3461  static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value);
3462  int64_t Value() const;
3463  V8_INLINE static Integer* Cast(v8::Value* obj);
3464  private:
3465  Integer();
3466  static void CheckCast(v8::Value* obj);
3467 };
3468 
3469 
3470 /**
3471  * A JavaScript value representing a 32-bit signed integer.
3472  */
3473 class V8_EXPORT Int32 : public Integer {
3474  public:
3475  int32_t Value() const;
3476  V8_INLINE static Int32* Cast(v8::Value* obj);
3477 
3478  private:
3479  Int32();
3480  static void CheckCast(v8::Value* obj);
3481 };
3482 
3483 
3484 /**
3485  * A JavaScript value representing a 32-bit unsigned integer.
3486  */
3487 class V8_EXPORT Uint32 : public Integer {
3488  public:
3489  uint32_t Value() const;
3490  V8_INLINE static Uint32* Cast(v8::Value* obj);
3491 
3492  private:
3493  Uint32();
3494  static void CheckCast(v8::Value* obj);
3495 };
3496 
3497 /**
3498  * A JavaScript BigInt value (https://tc39.github.io/proposal-bigint)
3499  */
3500 class V8_EXPORT BigInt : public Primitive {
3501  public:
3502  static Local<BigInt> New(Isolate* isolate, int64_t value);
3503  static Local<BigInt> NewFromUnsigned(Isolate* isolate, uint64_t value);
3504  /**
3505  * Creates a new BigInt object using a specified sign bit and a
3506  * specified list of digits/words.
3507  * The resulting number is calculated as:
3508  *
3509  * (-1)^sign_bit * (words[0] * (2^64)^0 + words[1] * (2^64)^1 + ...)
3510  */
3511  static MaybeLocal<BigInt> NewFromWords(Local<Context> context, int sign_bit,
3512  int word_count, const uint64_t* words);
3513 
3514  /**
3515  * Returns the value of this BigInt as an unsigned 64-bit integer.
3516  * If `lossless` is provided, it will reflect whether the return value was
3517  * truncated or wrapped around. In particular, it is set to `false` if this
3518  * BigInt is negative.
3519  */
3520  uint64_t Uint64Value(bool* lossless = nullptr) const;
3521 
3522  /**
3523  * Returns the value of this BigInt as a signed 64-bit integer.
3524  * If `lossless` is provided, it will reflect whether this BigInt was
3525  * truncated or not.
3526  */
3527  int64_t Int64Value(bool* lossless = nullptr) const;
3528 
3529  /**
3530  * Returns the number of 64-bit words needed to store the result of
3531  * ToWordsArray().
3532  */
3533  int WordCount() const;
3534 
3535  /**
3536  * Writes the contents of this BigInt to a specified memory location.
3537  * `sign_bit` must be provided and will be set to 1 if this BigInt is
3538  * negative.
3539  * `*word_count` has to be initialized to the length of the `words` array.
3540  * Upon return, it will be set to the actual number of words that would
3541  * be needed to store this BigInt (i.e. the return value of `WordCount()`).
3542  */
3543  void ToWordsArray(int* sign_bit, int* word_count, uint64_t* words) const;
3544 
3545  V8_INLINE static BigInt* Cast(v8::Value* obj);
3546 
3547  private:
3548  BigInt();
3549  static void CheckCast(v8::Value* obj);
3550 };
3551 
3552 /**
3553  * PropertyAttribute.
3554  */
3556  /** None. **/
3557  None = 0,
3558  /** ReadOnly, i.e., not writable. **/
3559  ReadOnly = 1 << 0,
3560  /** DontEnum, i.e., not enumerable. **/
3561  DontEnum = 1 << 1,
3562  /** DontDelete, i.e., not configurable. **/
3563  DontDelete = 1 << 2
3564 };
3565 
3566 /**
3567  * Accessor[Getter|Setter] are used as callback functions when
3568  * setting|getting a particular property. See Object and ObjectTemplate's
3569  * method SetAccessor.
3570  */
3571 typedef void (*AccessorGetterCallback)(
3572  Local<String> property,
3573  const PropertyCallbackInfo<Value>& info);
3575  Local<Name> property,
3576  const PropertyCallbackInfo<Value>& info);
3577 
3578 
3579 typedef void (*AccessorSetterCallback)(
3580  Local<String> property,
3581  Local<Value> value,
3582  const PropertyCallbackInfo<void>& info);
3584  Local<Name> property,
3585  Local<Value> value,
3586  const PropertyCallbackInfo<void>& info);
3587 
3588 
3589 /**
3590  * Access control specifications.
3591  *
3592  * Some accessors should be accessible across contexts. These
3593  * accessors have an explicit access control parameter which specifies
3594  * the kind of cross-context access that should be allowed.
3595  *
3596  * TODO(dcarney): Remove PROHIBITS_OVERWRITING as it is now unused.
3597  */
3599  DEFAULT = 0,
3601  ALL_CAN_WRITE = 1 << 1,
3603 };
3604 
3605 /**
3606  * Property filter bits. They can be or'ed to build a composite filter.
3607  */
3615 };
3616 
3617 /**
3618  * Options for marking whether callbacks may trigger JS-observable side effects.
3619  * Side-effect-free callbacks are whitelisted during debug evaluation with
3620  * throwOnSideEffect. It applies when calling a Function, FunctionTemplate,
3621  * or an Accessor callback. For Interceptors, please see
3622  * PropertyHandlerFlags's kHasNoSideEffect.
3623  * Callbacks that only cause side effects to the receiver are whitelisted if
3624  * invoked on receiver objects that are created within the same debug-evaluate
3625  * call, as these objects are temporary and the side effect does not escape.
3626  */
3627 enum class SideEffectType {
3631 };
3632 
3633 /**
3634  * Keys/Properties filter enums:
3635  *
3636  * KeyCollectionMode limits the range of collected properties. kOwnOnly limits
3637  * the collected properties to the given Object only. kIncludesPrototypes will
3638  * include all keys of the objects's prototype chain as well.
3639  */
3641 
3642 /**
3643  * kIncludesIndices allows for integer indices to be collected, while
3644  * kSkipIndices will exclude integer indices from being collected.
3645  */
3647 
3648 /**
3649  * kConvertToString will convert integer indices to strings.
3650  * kKeepNumbers will return numbers for integer indices.
3651  */
3653 
3654 /**
3655  * Integrity level for objects.
3656  */
3658 
3659 /**
3660  * A JavaScript object (ECMA-262, 4.3.3)
3661  */
3662 class V8_EXPORT Object : public Value {
3663  public:
3664  /**
3665  * Set only return Just(true) or Empty(), so if it should never fail, use
3666  * result.Check().
3667  */
3668  V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context,
3669  Local<Value> key, Local<Value> value);
3670 
3671  V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context, uint32_t index,
3672  Local<Value> value);
3673 
3674  // Implements CreateDataProperty (ECMA-262, 7.3.4).
3675  //
3676  // Defines a configurable, writable, enumerable property with the given value
3677  // on the object unless the property already exists and is not configurable
3678  // or the object is not extensible.
3679  //
3680  // Returns true on success.
3682  Local<Name> key,
3683  Local<Value> value);
3685  uint32_t index,
3686  Local<Value> value);
3687 
3688  // Implements DefineOwnProperty.
3689  //
3690  // In general, CreateDataProperty will be faster, however, does not allow
3691  // for specifying attributes.
3692  //
3693  // Returns true on success.
3695  Local<Context> context, Local<Name> key, Local<Value> value,
3696  PropertyAttribute attributes = None);
3697 
3698  // Implements Object.DefineProperty(O, P, Attributes), see Ecma-262 19.1.2.4.
3699  //
3700  // The defineProperty function is used to add an own property or
3701  // update the attributes of an existing own property of an object.
3702  //
3703  // Both data and accessor descriptors can be used.
3704  //
3705  // In general, CreateDataProperty is faster, however, does not allow
3706  // for specifying attributes or an accessor descriptor.
3707  //
3708  // The PropertyDescriptor can change when redefining a property.
3709  //
3710  // Returns true on success.
3712  Local<Context> context, Local<Name> key,
3713  PropertyDescriptor& descriptor); // NOLINT(runtime/references)
3714 
3716  Local<Value> key);
3717 
3719  uint32_t index);
3720 
3721  /**
3722  * Gets the property attributes of a property which can be None or
3723  * any combination of ReadOnly, DontEnum and DontDelete. Returns
3724  * None when the property doesn't exist.
3725  */
3727  Local<Context> context, Local<Value> key);
3728 
3729  /**
3730  * Returns Object.getOwnPropertyDescriptor as per ES2016 section 19.1.2.6.
3731  */
3733  Local<Context> context, Local<Name> key);
3734 
3735  /**
3736  * Object::Has() calls the abstract operation HasProperty(O, P) described
3737  * in ECMA-262, 7.3.10. Has() returns
3738  * true, if the object has the property, either own or on the prototype chain.
3739  * Interceptors, i.e., PropertyQueryCallbacks, are called if present.
3740  *
3741  * Has() has the same side effects as JavaScript's `variable in object`.
3742  * For example, calling Has() on a revoked proxy will throw an exception.
3743  *
3744  * \note Has() converts the key to a name, which possibly calls back into
3745  * JavaScript.
3746  *
3747  * See also v8::Object::HasOwnProperty() and
3748  * v8::Object::HasRealNamedProperty().
3749  */
3750  V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
3751  Local<Value> key);
3752 
3754  Local<Value> key);
3755 
3756  V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context, uint32_t index);
3757 
3759  uint32_t index);
3760 
3761  /**
3762  * Note: SideEffectType affects the getter only, not the setter.
3763  */
3765  Local<Context> context, Local<Name> name,
3767  AccessorNameSetterCallback setter = nullptr,
3769  AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
3770  SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
3771  SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
3772 
3773  void SetAccessorProperty(Local<Name> name, Local<Function> getter,
3774  Local<Function> setter = Local<Function>(),
3775  PropertyAttribute attribute = None,
3776  AccessControl settings = DEFAULT);
3777 
3778  /**
3779  * Sets a native data property like Template::SetNativeDataProperty, but
3780  * this method sets on this object directly.
3781  */
3783  Local<Context> context, Local<Name> name,
3785  AccessorNameSetterCallback setter = nullptr,
3786  Local<Value> data = Local<Value>(), PropertyAttribute attributes = None,
3787  SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
3788  SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
3789 
3790  /**
3791  * Attempts to create a property with the given name which behaves like a data
3792  * property, except that the provided getter is invoked (and provided with the
3793  * data value) to supply its value the first time it is read. After the
3794  * property is accessed once, it is replaced with an ordinary data property.
3795  *
3796  * Analogous to Template::SetLazyDataProperty.
3797  */
3799  Local<Context> context, Local<Name> name,
3801  PropertyAttribute attributes = None,
3802  SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
3803  SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
3804 
3805  /**
3806  * Functionality for private properties.
3807  * This is an experimental feature, use at your own risk.
3808  * Note: Private properties are not inherited. Do not rely on this, since it
3809  * may change.
3810  */
3811  Maybe<bool> HasPrivate(Local<Context> context, Local<Private> key);
3812  Maybe<bool> SetPrivate(Local<Context> context, Local<Private> key,
3813  Local<Value> value);
3814  Maybe<bool> DeletePrivate(Local<Context> context, Local<Private> key);
3816 
3817  /**
3818  * Returns an array containing the names of the enumerable properties
3819  * of this object, including properties from prototype objects. The
3820  * array returned by this method contains the same values as would
3821  * be enumerated by a for-in statement over this object.
3822  */
3824  Local<Context> context);
3826  Local<Context> context, KeyCollectionMode mode,
3827  PropertyFilter property_filter, IndexFilter index_filter,
3829 
3830  /**
3831  * This function has the same functionality as GetPropertyNames but
3832  * the returned array doesn't contain the names of properties from
3833  * prototype objects.
3834  */
3836  Local<Context> context);
3837 
3838  /**
3839  * Returns an array containing the names of the filtered properties
3840  * of this object, including properties from prototype objects. The
3841  * array returned by this method contains the same values as would
3842  * be enumerated by a for-in statement over this object.
3843  */
3845  Local<Context> context, PropertyFilter filter,
3847 
3848  /**
3849  * Get the prototype object. This does not skip objects marked to
3850  * be skipped by __proto__ and it does not consult the security
3851  * handler.
3852  */
3854 
3855  /**
3856  * Set the prototype object. This does not skip objects marked to
3857  * be skipped by __proto__ and it does not consult the security
3858  * handler.
3859  */
3861  Local<Value> prototype);
3862 
3863  /**
3864  * Finds an instance of the given function template in the prototype
3865  * chain.
3866  */
3868 
3869  /**
3870  * Call builtin Object.prototype.toString on this object.
3871  * This is different from Value::ToString() that may call
3872  * user-defined toString function. This one does not.
3873  */
3875  Local<Context> context);
3876 
3877  /**
3878  * Returns the name of the function invoked as a constructor for this object.
3879  */
3881 
3882  /**
3883  * Sets the integrity level of the object.
3884  */
3885  Maybe<bool> SetIntegrityLevel(Local<Context> context, IntegrityLevel level);
3886 
3887  /** Gets the number of internal fields for this Object. */
3888  int InternalFieldCount();
3889 
3890  /** Same as above, but works for PersistentBase. */
3892  const PersistentBase<Object>& object) {
3893  return object.val_->InternalFieldCount();
3894  }
3895 
3896  /** Same as above, but works for TracedReferenceBase. */
3898  const TracedReferenceBase<Object>& object) {
3899  return object.val_->InternalFieldCount();
3900  }
3901 
3902  /** Gets the value from an internal field. */
3903  V8_INLINE Local<Value> GetInternalField(int index);
3904 
3905  /** Sets the value in an internal field. */
3906  void SetInternalField(int index, Local<Value> value);
3907 
3908  /**
3909  * Gets a 2-byte-aligned native pointer from an internal field. This field
3910  * must have been set by SetAlignedPointerInInternalField, everything else
3911  * leads to undefined behavior.
3912  */
3914 
3915  /** Same as above, but works for PersistentBase. */
3917  const PersistentBase<Object>& object, int index) {
3918  return object.val_->GetAlignedPointerFromInternalField(index);
3919  }
3920 
3921  /** Same as above, but works for TracedGlobal. */
3923  const TracedReferenceBase<Object>& object, int index) {
3924  return object.val_->GetAlignedPointerFromInternalField(index);
3925  }
3926 
3927  /**
3928  * Sets a 2-byte-aligned native pointer in an internal field. To retrieve such
3929  * a field, GetAlignedPointerFromInternalField must be used, everything else
3930  * leads to undefined behavior.
3931  */
3932  void SetAlignedPointerInInternalField(int index, void* value);
3933  void SetAlignedPointerInInternalFields(int argc, int indices[],
3934  void* values[]);
3935 
3936  /**
3937  * HasOwnProperty() is like JavaScript's Object.prototype.hasOwnProperty().
3938  *
3939  * See also v8::Object::Has() and v8::Object::HasRealNamedProperty().
3940  */
3942  Local<Name> key);
3944  uint32_t index);
3945  /**
3946  * Use HasRealNamedProperty() if you want to check if an object has an own
3947  * property without causing side effects, i.e., without calling interceptors.
3948  *
3949  * This function is similar to v8::Object::HasOwnProperty(), but it does not
3950  * call interceptors.
3951  *
3952  * \note Consider using non-masking interceptors, i.e., the interceptors are
3953  * not called if the receiver has the real named property. See
3954  * `v8::PropertyHandlerFlags::kNonMasking`.
3955  *
3956  * See also v8::Object::Has().
3957  */
3959  Local<Name> key);
3961  Local<Context> context, uint32_t index);
3963  Local<Context> context, Local<Name> key);
3964 
3965  /**
3966  * If result.IsEmpty() no real property was located in the prototype chain.
3967  * This means interceptors in the prototype chain are not called.
3968  */
3970  Local<Context> context, Local<Name> key);
3971 
3972  /**
3973  * Gets the property attributes of a real property in the prototype chain,
3974  * which can be None or any combination of ReadOnly, DontEnum and DontDelete.
3975  * Interceptors in the prototype chain are not called.
3976  */
3979  Local<Name> key);
3980 
3981  /**
3982  * If result.IsEmpty() no real property was located on the object or
3983  * in the prototype chain.
3984  * This means interceptors in the prototype chain are not called.
3985  */
3987  Local<Context> context, Local<Name> key);
3988 
3989  /**
3990  * Gets the property attributes of a real property which can be
3991  * None or any combination of ReadOnly, DontEnum and DontDelete.
3992  * Interceptors in the prototype chain are not called.
3993  */
3995  Local<Context> context, Local<Name> key);
3996 
3997  /** Tests for a named lookup interceptor.*/
3999 
4000  /** Tests for an index lookup interceptor.*/
4002 
4003  /**
4004  * Returns the identity hash for this object. The current implementation
4005  * uses a hidden property on the object to store the identity hash.
4006  *
4007  * The return value will never be 0. Also, it is not guaranteed to be
4008  * unique.
4009  */
4010  int GetIdentityHash();
4011 
4012  /**
4013  * Clone this object with a fast but shallow copy. Values will point
4014  * to the same values as the original object.
4015  */
4016  // TODO(dcarney): take an isolate and optionally bail out?
4017  Local<Object> Clone();
4018 
4019  /**
4020  * Returns the context in which the object was created.
4021  */
4023 
4024  /** Same as above, but works for Persistents */
4026  const PersistentBase<Object>& object) {
4027  return object.val_->CreationContext();
4028  }
4029 
4030  /**
4031  * Checks whether a callback is set by the
4032  * ObjectTemplate::SetCallAsFunctionHandler method.
4033  * When an Object is callable this method returns true.
4034  */
4035  bool IsCallable();
4036 
4037  /**
4038  * True if this object is a constructor.
4039  */
4040  bool IsConstructor();
4041 
4042  /**
4043  * True if this object can carry information relevant to the embedder in its
4044  * embedder fields, false otherwise. This is generally true for objects
4045  * constructed through function templates but also holds for other types where
4046  * V8 automatically adds internal fields at compile time, such as e.g.
4047  * v8::ArrayBuffer.
4048  */
4049  bool IsApiWrapper();
4050 
4051  /**
4052  * Call an Object as a function if a callback is set by the
4053  * ObjectTemplate::SetCallAsFunctionHandler method.
4054  */
4056  Local<Value> recv,
4057  int argc,
4058  Local<Value> argv[]);
4059 
4060  /**
4061  * Call an Object as a constructor if a callback is set by the
4062  * ObjectTemplate::SetCallAsFunctionHandler method.
4063  * Note: This method behaves like the Function::NewInstance method.
4064  */
4066  Local<Context> context, int argc, Local<Value> argv[]);
4067 
4068  /**
4069  * Return the isolate to which the Object belongs to.
4070  */
4071  Isolate* GetIsolate();
4072 
4073  /**
4074  * If this object is a Set, Map, WeakSet or WeakMap, this returns a
4075  * representation of the elements of this object as an array.
4076  * If this object is a SetIterator or MapIterator, this returns all
4077  * elements of the underlying collection, starting at the iterator's current
4078  * position.
4079  * For other types, this will return an empty MaybeLocal<Array> (without
4080  * scheduling an exception).
4081  */
4082  MaybeLocal<Array> PreviewEntries(bool* is_key_value);
4083 
4084  static Local<Object> New(Isolate* isolate);
4085 
4086  /**
4087  * Creates a JavaScript object with the given properties, and
4088  * a the given prototype_or_null (which can be any JavaScript
4089  * value, and if it's null, the newly created object won't have
4090  * a prototype at all). This is similar to Object.create().
4091  * All properties will be created as enumerable, configurable
4092  * and writable properties.
4093  */
4094  static Local<Object> New(Isolate* isolate, Local<Value> prototype_or_null,
4095  Local<Name>* names, Local<Value>* values,
4096  size_t length);
4097 
4098  V8_INLINE static Object* Cast(Value* obj);
4099 
4100  private:
4101  Object();
4102  static void CheckCast(Value* obj);
4103  Local<Value> SlowGetInternalField(int index);
4104  void* SlowGetAlignedPointerFromInternalField(int index);
4105 };
4106 
4107 
4108 /**
4109  * An instance of the built-in array constructor (ECMA-262, 15.4.2).
4110  */
4111 class V8_EXPORT Array : public Object {
4112  public:
4113  uint32_t Length() const;
4114 
4115  /**
4116  * Creates a JavaScript array with the given length. If the length
4117  * is negative the returned array will have length 0.
4118  */
4119  static Local<Array> New(Isolate* isolate, int length = 0);
4120 
4121  /**
4122  * Creates a JavaScript array out of a Local<Value> array in C++
4123  * with a known length.
4124  */
4125  static Local<Array> New(Isolate* isolate, Local<Value>* elements,
4126  size_t length);
4127  V8_INLINE static Array* Cast(Value* obj);
4128  private:
4129  Array();
4130  static void CheckCast(Value* obj);
4131 };
4132 
4133 
4134 /**
4135  * An instance of the built-in Map constructor (ECMA-262, 6th Edition, 23.1.1).
4136  */
4137 class V8_EXPORT Map : public Object {
4138  public:
4139  size_t Size() const;
4140  void Clear();
4142  Local<Value> key);
4144  Local<Value> key,
4145  Local<Value> value);
4146  V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
4147  Local<Value> key);
4149  Local<Value> key);
4150 
4151  /**
4152  * Returns an array of length Size() * 2, where index N is the Nth key and
4153  * index N + 1 is the Nth value.
4154  */
4155  Local<Array> AsArray() const;
4156 
4157  /**
4158  * Creates a new empty Map.
4159  */
4160  static Local<Map> New(Isolate* isolate);
4161 
4162  V8_INLINE static Map* Cast(Value* obj);
4163 
4164  private:
4165  Map();
4166  static void CheckCast(Value* obj);
4167 };
4168 
4169 
4170 /**
4171  * An instance of the built-in Set constructor (ECMA-262, 6th Edition, 23.2.1).
4172  */
4173 class V8_EXPORT Set : public Object {
4174  public:
4175  size_t Size() const;
4176  void Clear();
4178  Local<Value> key);
4179  V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
4180  Local<Value> key);
4182  Local<Value> key);
4183 
4184  /**
4185  * Returns an array of the keys in this Set.
4186  */
4187  Local<Array> AsArray() const;
4188 
4189  /**
4190  * Creates a new empty Set.
4191  */
4192  static Local<Set> New(Isolate* isolate);
4193 
4194  V8_INLINE static Set* Cast(Value* obj);
4195 
4196  private:
4197  Set();
4198  static void CheckCast(Value* obj);
4199 };
4200 
4201 
4202 template<typename T>
4203 class ReturnValue {
4204  public:
4205  template <class S> V8_INLINE ReturnValue(const ReturnValue<S>& that)
4206  : value_(that.value_) {
4207  TYPE_CHECK(T, S);
4208  }
4209  // Local setters
4210  template <typename S>
4211  V8_INLINE void Set(const Global<S>& handle);
4212  template <typename S>
4213  V8_INLINE void Set(const TracedReferenceBase<S>& handle);
4214  template <typename S>
4215  V8_INLINE void Set(const Local<S> handle);
4216  // Fast primitive setters
4217  V8_INLINE void Set(bool value);
4218  V8_INLINE void Set(double i);
4219  V8_INLINE void Set(int32_t i);
4220  V8_INLINE void Set(uint32_t i);
4221  // Fast JS primitive setters
4222  V8_INLINE void SetNull();
4223  V8_INLINE void SetUndefined();
4224  V8_INLINE void SetEmptyString();
4225  // Convenience getter for Isolate
4226  V8_INLINE Isolate* GetIsolate() const;
4227 
4228  // Pointer setter: Uncompilable to prevent inadvertent misuse.
4229  template <typename S>
4230  V8_INLINE void Set(S* whatever);
4231 
4232  // Getter. Creates a new Local<> so it comes with a certain performance
4233  // hit. If the ReturnValue was not yet set, this will return the undefined
4234  // value.
4235  V8_INLINE Local<Value> Get() const;
4236 
4237  private:
4238  template<class F> friend class ReturnValue;
4239  template<class F> friend class FunctionCallbackInfo;
4240  template<class F> friend class PropertyCallbackInfo;
4241  template <class F, class G, class H>
4243  V8_INLINE void SetInternal(internal::Address value) { *value_ = value; }
4244  V8_INLINE internal::Address GetDefaultValue();
4245  V8_INLINE explicit ReturnValue(internal::Address* slot);
4246  internal::Address* value_;
4247 };
4248 
4249 
4250 /**
4251  * The argument information given to function call callbacks. This
4252  * class provides access to information about the context of the call,
4253  * including the receiver, the number and values of arguments, and
4254  * the holder of the function.
4255  */
4256 template<typename T>
4257 class FunctionCallbackInfo {
4258  public:
4259  /** The number of available arguments. */
4260  V8_INLINE int Length() const;
4261  /**
4262  * Accessor for the available arguments. Returns `undefined` if the index
4263  * is out of bounds.
4264  */
4265  V8_INLINE Local<Value> operator[](int i) const;
4266  /** Returns the receiver. This corresponds to the "this" value. */
4267  V8_INLINE Local<Object> This() const;
4268  /**
4269  * If the callback was created without a Signature, this is the same
4270  * value as This(). If there is a signature, and the signature didn't match
4271  * This() but one of its hidden prototypes, this will be the respective
4272  * hidden prototype.
4273  *
4274  * Note that this is not the prototype of This() on which the accessor
4275  * referencing this callback was found (which in V8 internally is often
4276  * referred to as holder [sic]).
4277  */
4278  V8_INLINE Local<Object> Holder() const;
4279  /** For construct calls, this returns the "new.target" value. */
4280  V8_INLINE Local<Value> NewTarget() const;
4281  /** Indicates whether this is a regular call or a construct call. */
4282  V8_INLINE bool IsConstructCall() const;
4283  /** The data argument specified when creating the callback. */
4284  V8_INLINE Local<Value> Data() const;
4285  /** The current Isolate. */
4286  V8_INLINE Isolate* GetIsolate() const;
4287  /** The ReturnValue for the call. */
4289  // This shouldn't be public, but the arm compiler needs it.
4290  static const int kArgsLength = 6;
4291 
4292  protected:
4293  friend class internal::FunctionCallbackArguments;
4295  friend class debug::ConsoleCallArguments;
4296  static const int kHolderIndex = 0;
4297  static const int kIsolateIndex = 1;
4298  static const int kReturnValueDefaultValueIndex = 2;
4299  static const int kReturnValueIndex = 3;
4300  static const int kDataIndex = 4;
4301  static const int kNewTargetIndex = 5;
4302 
4304  internal::Address* values, int length);
4307  int length_;
4308 };
4309 
4310 
4311 /**
4312  * The information passed to a property callback about the context
4313  * of the property access.
4314  */
4315 template<typename T>
4316 class PropertyCallbackInfo {
4317  public:
4318  /**
4319  * \return The isolate of the property access.
4320  */
4321  V8_INLINE Isolate* GetIsolate() const;
4322 
4323  /**
4324  * \return The data set in the configuration, i.e., in
4325  * `NamedPropertyHandlerConfiguration` or
4326  * `IndexedPropertyHandlerConfiguration.`
4327  */
4328  V8_INLINE Local<Value> Data() const;
4329 
4330  /**
4331  * \return The receiver. In many cases, this is the object on which the
4332  * property access was intercepted. When using
4333  * `Reflect.get`, `Function.prototype.call`, or similar functions, it is the
4334  * object passed in as receiver or thisArg.
4335  *
4336  * \code
4337  * void GetterCallback(Local<Name> name,
4338  * const v8::PropertyCallbackInfo<v8::Value>& info) {
4339  * auto context = info.GetIsolate()->GetCurrentContext();
4340  *
4341  * v8::Local<v8::Value> a_this =
4342  * info.This()
4343  * ->GetRealNamedProperty(context, v8_str("a"))
4344  * .ToLocalChecked();
4345  * v8::Local<v8::Value> a_holder =
4346  * info.Holder()
4347  * ->GetRealNamedProperty(context, v8_str("a"))
4348  * .ToLocalChecked();
4349  *
4350  * CHECK(v8_str("r")->Equals(context, a_this).FromJust());
4351  * CHECK(v8_str("obj")->Equals(context, a_holder).FromJust());
4352  *
4353  * info.GetReturnValue().Set(name);
4354  * }
4355  *
4356  * v8::Local<v8::FunctionTemplate> templ =
4357  * v8::FunctionTemplate::New(isolate);
4358  * templ->InstanceTemplate()->SetHandler(
4359  * v8::NamedPropertyHandlerConfiguration(GetterCallback));
4360  * LocalContext env;
4361  * env->Global()
4362  * ->Set(env.local(), v8_str("obj"), templ->GetFunction(env.local())
4363  * .ToLocalChecked()
4364  * ->NewInstance(env.local())
4365  * .ToLocalChecked())
4366  * .FromJust();
4367  *
4368  * CompileRun("obj.a = 'obj'; var r = {a: 'r'}; Reflect.get(obj, 'x', r)");
4369  * \endcode
4370  */
4371  V8_INLINE Local<Object> This() const;
4372 
4373  /**
4374  * \return The object in the prototype chain of the receiver that has the
4375  * interceptor. Suppose you have `x` and its prototype is `y`, and `y`
4376  * has an interceptor. Then `info.This()` is `x` and `info.Holder()` is `y`.
4377  * The Holder() could be a hidden object (the global object, rather
4378  * than the global proxy).
4379  *
4380  * \note For security reasons, do not pass the object back into the runtime.
4381  */
4382  V8_INLINE Local<Object> Holder() const;
4383 
4384  /**
4385  * \return The return value of the callback.
4386  * Can be changed by calling Set().
4387  * \code
4388  * info.GetReturnValue().Set(...)
4389  * \endcode
4390  *
4391  */
4393 
4394  /**
4395  * \return True if the intercepted function should throw if an error occurs.
4396  * Usually, `true` corresponds to `'use strict'`.
4397  *
4398  * \note Always `false` when intercepting `Reflect.set()`
4399  * independent of the language mode.
4400  */
4401  V8_INLINE bool ShouldThrowOnError() const;
4402 
4403  // This shouldn't be public, but the arm compiler needs it.
4404  static const int kArgsLength = 7;
4405 
4406  protected:
4407  friend class MacroAssembler;
4408  friend class internal::PropertyCallbackArguments;
4410  static const int kShouldThrowOnErrorIndex = 0;
4411  static const int kHolderIndex = 1;
4412  static const int kIsolateIndex = 2;
4413  static const int kReturnValueDefaultValueIndex = 3;
4414  static const int kReturnValueIndex = 4;
4415  static const int kDataIndex = 5;
4416  static const int kThisIndex = 6;
4417 
4420 };
4421 
4422 
4423 typedef void (*FunctionCallback)(const FunctionCallbackInfo<Value>& info);
4424 
4426 
4427 /**
4428  * A JavaScript function object (ECMA-262, 15.3).
4429  */
4430 class V8_EXPORT Function : public Object {
4431  public:
4432  /**
4433  * Create a function in the current execution context
4434  * for a given FunctionCallback.
4435  */
4436  static MaybeLocal<Function> New(
4437  Local<Context> context, FunctionCallback callback,
4438  Local<Value> data = Local<Value>(), int length = 0,
4440  SideEffectType side_effect_type = SideEffectType::kHasSideEffect);
4441 
4443  Local<Context> context, int argc, Local<Value> argv[]) const;
4444 
4446  Local<Context> context) const {
4447  return NewInstance(context, 0, nullptr);
4448  }
4449 
4450  /**
4451  * When side effect checks are enabled, passing kHasNoSideEffect allows the
4452  * constructor to be invoked without throwing. Calls made within the
4453  * constructor are still checked.
4454  */
4456  Local<Context> context, int argc, Local<Value> argv[],
4457  SideEffectType side_effect_type = SideEffectType::kHasSideEffect) const;
4458 
4460  Local<Value> recv, int argc,
4461  Local<Value> argv[]);
4462 
4463  void SetName(Local<String> name);
4464  Local<Value> GetName() const;
4465 
4466  /**
4467  * Name inferred from variable or property assignment of this function.
4468  * Used to facilitate debugging and profiling of JavaScript code written
4469  * in an OO style, where many functions are anonymous but are assigned
4470  * to object properties.
4471  */
4472  Local<Value> GetInferredName() const;
4473 
4474  /**
4475  * displayName if it is set, otherwise name if it is configured, otherwise
4476  * function name, otherwise inferred name.
4477  */
4478  Local<Value> GetDebugName() const;
4479 
4480  /**
4481  * User-defined name assigned to the "displayName" property of this function.
4482  * Used to facilitate debugging and profiling of JavaScript code.
4483  */
4484  Local<Value> GetDisplayName() const;
4485 
4486  /**
4487  * Returns zero based line number of function body and
4488  * kLineOffsetNotFound if no information available.
4489  */
4490  int GetScriptLineNumber() const;
4491  /**
4492  * Returns zero based column number of function body and
4493  * kLineOffsetNotFound if no information available.
4494  */
4495  int GetScriptColumnNumber() const;
4496 
4497  /**
4498  * Returns scriptId.
4499  */
4500  int ScriptId() const;
4501 
4502  /**
4503  * Returns the original function if this function is bound, else returns
4504  * v8::Undefined.
4505  */
4506  Local<Value> GetBoundFunction() const;
4507 
4508  ScriptOrigin GetScriptOrigin() const;
4509  V8_INLINE static Function* Cast(Value* obj);
4510  static const int kLineOffsetNotFound;
4511 
4512  private:
4513  Function();
4514  static void CheckCast(Value* obj);
4515 };
4516 
4517 #ifndef V8_PROMISE_INTERNAL_FIELD_COUNT
4518 // The number of required internal fields can be defined by embedder.
4519 #define V8_PROMISE_INTERNAL_FIELD_COUNT 0
4520 #endif
4521 
4522 /**
4523  * An instance of the built-in Promise constructor (ES6 draft).
4524  */
4525 class V8_EXPORT Promise : public Object {
4526  public:
4527  /**
4528  * State of the promise. Each value corresponds to one of the possible values
4529  * of the [[PromiseState]] field.
4530  */
4532 
4533  class V8_EXPORT Resolver : public Object {
4534  public:
4535  /**
4536  * Create a new resolver, along with an associated promise in pending state.
4537  */
4539  Local<Context> context);
4540 
4541  /**
4542  * Extract the associated promise.
4543  */
4545 
4546  /**
4547  * Resolve/reject the associated promise with a given value.
4548  * Ignored if the promise is no longer pending.
4549  */
4551  Local<Value> value);
4552 
4554  Local<Value> value);
4555 
4556  V8_INLINE static Resolver* Cast(Value* obj);
4557 
4558  private:
4559  Resolver();
4560  static void CheckCast(Value* obj);
4561  };
4562 
4563  /**
4564  * Register a resolution/rejection handler with a promise.
4565  * The handler is given the respective resolution/rejection value as
4566  * an argument. If the promise is already resolved/rejected, the handler is
4567  * invoked at the end of turn.
4568  */
4570  Local<Function> handler);
4571 
4573  Local<Function> handler);
4574 
4576  Local<Function> on_fulfilled,
4577  Local<Function> on_rejected);
4578 
4579  /**
4580  * Returns true if the promise has at least one derived promise, and
4581  * therefore resolve/reject handlers (including default handler).
4582  */
4583  bool HasHandler();
4584 
4585  /**
4586  * Returns the content of the [[PromiseResult]] field. The Promise must not
4587  * be pending.
4588  */
4589  Local<Value> Result();
4590 
4591  /**
4592  * Returns the value of the [[PromiseState]] field.
4593  */
4594  PromiseState State();
4595 
4596  /**
4597  * Marks this promise as handled to avoid reporting unhandled rejections.
4598  */
4599  void MarkAsHandled();
4600 
4601  V8_INLINE static Promise* Cast(Value* obj);
4602 
4604 
4605  private:
4606  Promise();
4607  static void CheckCast(Value* obj);
4608 };
4609 
4610 /**
4611  * An instance of a Property Descriptor, see Ecma-262 6.2.4.
4612  *
4613  * Properties in a descriptor are present or absent. If you do not set
4614  * `enumerable`, `configurable`, and `writable`, they are absent. If `value`,
4615  * `get`, or `set` are absent, but you must specify them in the constructor, use
4616  * empty handles.
4617  *
4618  * Accessors `get` and `set` must be callable or undefined if they are present.
4619  *
4620  * \note Only query properties if they are present, i.e., call `x()` only if
4621  * `has_x()` returns true.
4622  *
4623  * \code
4624  * // var desc = {writable: false}
4625  * v8::PropertyDescriptor d(Local<Value>()), false);
4626  * d.value(); // error, value not set
4627  * if (d.has_writable()) {
4628  * d.writable(); // false
4629  * }
4630  *
4631  * // var desc = {value: undefined}
4632  * v8::PropertyDescriptor d(v8::Undefined(isolate));
4633  *
4634  * // var desc = {get: undefined}
4635  * v8::PropertyDescriptor d(v8::Undefined(isolate), Local<Value>()));
4636  * \endcode
4637  */
4639  public:
4640  // GenericDescriptor
4642 
4643  // DataDescriptor
4644  explicit PropertyDescriptor(Local<Value> value);
4645 
4646  // DataDescriptor with writable property
4647  PropertyDescriptor(Local<Value> value, bool writable);
4648 
4649  // AccessorDescriptor
4651 
4652  ~PropertyDescriptor();
4653 
4654  Local<Value> value() const;
4655  bool has_value() const;
4656 
4657  Local<Value> get() const;
4658  bool has_get() const;
4659  Local<Value> set() const;
4660  bool has_set() const;
4661 
4662  void set_enumerable(bool enumerable);
4663  bool enumerable() const;
4664  bool has_enumerable() const;
4665 
4666  void set_configurable(bool configurable);
4667  bool configurable() const;
4668  bool has_configurable() const;
4669 
4670  bool writable() const;
4671  bool has_writable() const;
4672 
4673  struct PrivateData;
4674  PrivateData* get_private() const { return private_; }
4675 
4676  PropertyDescriptor(const PropertyDescriptor&) = delete;
4677  void operator=(const PropertyDescriptor&) = delete;
4678 
4679  private:
4680  PrivateData* private_;
4681 };
4682 
4683 /**
4684  * An instance of the built-in Proxy constructor (ECMA-262, 6th Edition,
4685  * 26.2.1).
4686  */
4687 class V8_EXPORT Proxy : public Object {
4688  public:
4689  Local<Value> GetTarget();
4690  Local<Value> GetHandler();
4691  bool IsRevoked();
4692  void Revoke();
4693 
4694  /**
4695  * Creates a new Proxy for the target object.
4696  */
4697  static MaybeLocal<Proxy> New(Local<Context> context,
4698  Local<Object> local_target,
4699  Local<Object> local_handler);
4700 
4701  V8_INLINE static Proxy* Cast(Value* obj);
4702 
4703  private:
4704  Proxy();
4705  static void CheckCast(Value* obj);
4706 };
4707 
4708 /**
4709  * Points to an unowned continous buffer holding a known number of elements.
4710  *
4711  * This is similar to std::span (under consideration for C++20), but does not
4712  * require advanced C++ support. In the (far) future, this may be replaced with
4713  * or aliased to std::span.
4714  *
4715  * To facilitate future migration, this class exposes a subset of the interface
4716  * implemented by std::span.
4717  */
4718 template <typename T>
4720  public:
4721  /** The default constructor creates an empty span. */
4722  constexpr MemorySpan() = default;
4723 
4724  constexpr MemorySpan(T* data, size_t size) : data_(data), size_(size) {}
4725 
4726  /** Returns a pointer to the beginning of the buffer. */
4727  constexpr T* data() const { return data_; }
4728  /** Returns the number of elements that the buffer holds. */
4729  constexpr size_t size() const { return size_; }
4730 
4731  private:
4732  T* data_ = nullptr;
4733  size_t size_ = 0;
4734 };
4735 
4736 /**
4737  * An owned byte buffer with associated size.
4738  */
4739 struct OwnedBuffer {
4740  std::unique_ptr<const uint8_t[]> buffer;
4741  size_t size = 0;
4742  OwnedBuffer(std::unique_ptr<const uint8_t[]> buffer, size_t size)
4743  : buffer(std::move(buffer)), size(size) {}
4744  OwnedBuffer() = default;
4745 };
4746 
4747 // Wrapper around a compiled WebAssembly module, which is potentially shared by
4748 // different WasmModuleObjects.
4750  public:
4751  /**
4752  * Serialize the compiled module. The serialized data does not include the
4753  * wire bytes.
4754  */
4756 
4757  /**
4758  * Get the (wasm-encoded) wire bytes that were used to compile this module.
4759  */
4760  MemorySpan<const uint8_t> GetWireBytesRef();
4761 
4762  private:
4763  explicit CompiledWasmModule(std::shared_ptr<internal::wasm::NativeModule>);
4764  friend class Utils;
4765 
4766  const std::shared_ptr<internal::wasm::NativeModule> native_module_;
4767 };
4768 
4769 // An instance of WebAssembly.Module.
4771  public:
4772  WasmModuleObject() = delete;
4773 
4774  /**
4775  * Efficiently re-create a WasmModuleObject, without recompiling, from
4776  * a CompiledWasmModule.
4777  */
4779  Isolate* isolate, const CompiledWasmModule&);
4780 
4781  /**
4782  * Get the compiled module for this module object. The compiled module can be
4783  * shared by several module objects.
4784  */
4786 
4787  /**
4788  * If possible, deserialize the module, otherwise compile it from the provided
4789  * uncompiled bytes.
4790  */
4791  V8_DEPRECATED(
4792  "Use WasmStreaming for deserialization from cache or the "
4793  "CompiledWasmModule to transfer between isolates")
4794  static MaybeLocal<WasmModuleObject> DeserializeOrCompile(
4795  Isolate* isolate, MemorySpan<const uint8_t> serialized_module,
4796  MemorySpan<const uint8_t> wire_bytes);
4797 
4798  V8_INLINE static WasmModuleObject* Cast(Value* obj);
4799 
4800  private:
4801  static MaybeLocal<WasmModuleObject> Deserialize(
4802  Isolate* isolate, MemorySpan<const uint8_t> serialized_module,
4803  MemorySpan<const uint8_t> wire_bytes);
4804  static MaybeLocal<WasmModuleObject> Compile(Isolate* isolate,
4805  const uint8_t* start,
4806  size_t length);
4807 
4808  static void CheckCast(Value* obj);
4809 };
4810 
4811 /**
4812  * The V8 interface for WebAssembly streaming compilation. When streaming
4813  * compilation is initiated, V8 passes a {WasmStreaming} object to the embedder
4814  * such that the embedder can pass the input bytes for streaming compilation to
4815  * V8.
4816  */
4817 class V8_EXPORT WasmStreaming final {
4818  public:
4819  class WasmStreamingImpl;
4820 
4821  /**
4822  * Client to receive streaming event notifications.
4823  */
4824  class Client {
4825  public:
4826  virtual ~Client() = default;
4827  /**
4828  * Passes the fully compiled module to the client. This can be used to
4829  * implement code caching.
4830  */
4831  virtual void OnModuleCompiled(CompiledWasmModule compiled_module) = 0;
4832  };
4833 
4834  explicit WasmStreaming(std::unique_ptr<WasmStreamingImpl> impl);
4835 
4836  ~WasmStreaming();
4837 
4838  /**
4839  * Pass a new chunk of bytes to WebAssembly streaming compilation.
4840  * The buffer passed into {OnBytesReceived} is owned by the caller.
4841  */
4842  void OnBytesReceived(const uint8_t* bytes, size_t size);
4843 
4844  /**
4845  * {Finish} should be called after all received bytes where passed to
4846  * {OnBytesReceived} to tell V8 that there will be no more bytes. {Finish}
4847  * does not have to be called after {Abort} has been called already.
4848  */
4849  void Finish();
4850 
4851  /**
4852  * Abort streaming compilation. If {exception} has a value, then the promise
4853  * associated with streaming compilation is rejected with that value. If
4854  * {exception} does not have value, the promise does not get rejected.
4855  */
4856  void Abort(MaybeLocal<Value> exception);
4857 
4858  /**
4859  * Passes previously compiled module bytes. This must be called before
4860  * {OnBytesReceived}, {Finish}, or {Abort}. Returns true if the module bytes
4861  * can be used, false otherwise. The buffer passed via {bytes} and {size}
4862  * is owned by the caller. If {SetCompiledModuleBytes} returns true, the
4863  * buffer must remain valid until either {Finish} or {Abort} completes.
4864  */
4865  bool SetCompiledModuleBytes(const uint8_t* bytes, size_t size);
4866 
4867  /**
4868  * Sets the client object that will receive streaming event notifications.
4869  * This must be called before {OnBytesReceived}, {Finish}, or {Abort}.
4870  */
4871  void SetClient(std::shared_ptr<Client> client);
4872 
4873  /*
4874  * Sets the UTF-8 encoded source URL for the {Script} object. This must be
4875  * called before {Finish}.
4876  */
4877  void SetUrl(const char* url, size_t length);
4878 
4879  /**
4880  * Unpacks a {WasmStreaming} object wrapped in a {Managed} for the embedder.
4881  * Since the embedder is on the other side of the API, it cannot unpack the
4882  * {Managed} itself.
4883  */
4884  static std::shared_ptr<WasmStreaming> Unpack(Isolate* isolate,
4885  Local<Value> value);
4886 
4887  private:
4888  std::unique_ptr<WasmStreamingImpl> impl_;
4889 };
4890 
4891 // TODO(mtrofin): when streaming compilation is done, we can rename this
4892 // to simply WasmModuleObjectBuilder
4893 class V8_EXPORT WasmModuleObjectBuilderStreaming final {
4894  public:
4895  explicit WasmModuleObjectBuilderStreaming(Isolate* isolate);
4896  /**
4897  * The buffer passed into OnBytesReceived is owned by the caller.
4898  */
4899  void OnBytesReceived(const uint8_t*, size_t size);
4900  void Finish();
4901  /**
4902  * Abort streaming compilation. If {exception} has a value, then the promise
4903  * associated with streaming compilation is rejected with that value. If
4904  * {exception} does not have value, the promise does not get rejected.
4905  */
4906  void Abort(MaybeLocal<Value> exception);
4908 
4909  ~WasmModuleObjectBuilderStreaming() = default;
4910 
4911  private:
4912  WasmModuleObjectBuilderStreaming(const WasmModuleObjectBuilderStreaming&) =
4913  delete;
4914  WasmModuleObjectBuilderStreaming(WasmModuleObjectBuilderStreaming&&) =
4915  default;
4916  WasmModuleObjectBuilderStreaming& operator=(
4917  const WasmModuleObjectBuilderStreaming&) = delete;
4918  WasmModuleObjectBuilderStreaming& operator=(
4919  WasmModuleObjectBuilderStreaming&&) = default;
4920  Isolate* isolate_ = nullptr;
4921 
4922 #if V8_CC_MSVC
4923  /**
4924  * We don't need the static Copy API, so the default
4925  * NonCopyablePersistentTraits would be sufficient, however,
4926  * MSVC eagerly instantiates the Copy.
4927  * We ensure we don't use Copy, however, by compiling with the
4928  * defaults everywhere else.
4929  */
4930  Persistent<Promise, CopyablePersistentTraits<Promise>> promise_;
4931 #else
4932  Persistent<Promise> promise_;
4933 #endif
4934  std::shared_ptr<internal::wasm::StreamingDecoder> streaming_decoder_;
4935 };
4936 
4937 #ifndef V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT
4938 // The number of required internal fields can be defined by embedder.
4939 #define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 2
4940 #endif
4941 
4942 
4944 
4945 /**
4946  * A wrapper around the backing store (i.e. the raw memory) of an array buffer.
4947  * See a document linked in http://crbug.com/v8/9908 for more information.
4948  *
4949  * The allocation and destruction of backing stores is generally managed by
4950  * V8. Clients should always use standard C++ memory ownership types (i.e.
4951  * std::unique_ptr and std::shared_ptr) to manage lifetimes of backing stores
4952  * properly, since V8 internal objects may alias backing stores.
4953  *
4954  * This object does not keep the underlying |ArrayBuffer::Allocator| alive by
4955  * default. Use Isolate::CreateParams::array_buffer_allocator_shared when
4956  * creating the Isolate to make it hold a reference to the allocator itself.
4957  */
4959  public:
4960  ~BackingStore();
4961 
4962  /**
4963  * Return a pointer to the beginning of the memory block for this backing
4964  * store. The pointer is only valid as long as this backing store object
4965  * lives.
4966  */
4967  void* Data() const;
4968 
4969  /**
4970  * The length (in bytes) of this backing store.
4971  */
4972  size_t ByteLength() const;
4973 
4974  /**
4975  * Indicates whether the backing store was created for an ArrayBuffer or
4976  * a SharedArrayBuffer.
4977  */
4978  bool IsShared() const;
4979 
4980  private:
4981  /**
4982  * See [Shared]ArrayBuffer::GetBackingStore and
4983  * [Shared]ArrayBuffer::NewBackingStore.
4984  */
4985  BackingStore();
4986 };
4987 
4988 /**
4989  * This callback is used only if the memory block for this backing store cannot
4990  * be allocated with an ArrayBuffer::Allocator. In such cases the destructor
4991  * of this backing store object invokes the callback to free the memory block.
4992  */
4993 using BackingStoreDeleterCallback = void (*)(void* data, size_t length,
4994  void* deleter_data);
4995 
4996 /**
4997  * An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5).
4998  */
4999 class V8_EXPORT ArrayBuffer : public Object {
5000  public:
5001  /**
5002  * A thread-safe allocator that V8 uses to allocate |ArrayBuffer|'s memory.
5003  * The allocator is a global V8 setting. It has to be set via
5004  * Isolate::CreateParams.
5005  *
5006  * Memory allocated through this allocator by V8 is accounted for as external
5007  * memory by V8. Note that V8 keeps track of the memory for all internalized
5008  * |ArrayBuffer|s. Responsibility for tracking external memory (using
5009  * Isolate::AdjustAmountOfExternalAllocatedMemory) is handed over to the
5010  * embedder upon externalization and taken over upon internalization (creating
5011  * an internalized buffer from an existing buffer).
5012  *
5013  * Note that it is unsafe to call back into V8 from any of the allocator
5014  * functions.
5015  */
5016  class V8_EXPORT Allocator { // NOLINT
5017  public:
5018  virtual ~Allocator() = default;
5019 
5020  /**
5021  * Allocate |length| bytes. Return NULL if allocation is not successful.
5022  * Memory should be initialized to zeroes.
5023  */
5024  virtual void* Allocate(size_t length) = 0;
5025 
5026  /**
5027  * Allocate |length| bytes. Return NULL if allocation is not successful.
5028  * Memory does not have to be initialized.
5029  */
5030  virtual void* AllocateUninitialized(size_t length) = 0;
5031 
5032  /**
5033  * Free the memory block of size |length|, pointed to by |data|.
5034  * That memory is guaranteed to be previously allocated by |Allocate|.
5035  */
5036  virtual void Free(void* data, size_t length) = 0;
5037 
5038  /**
5039  * ArrayBuffer allocation mode. kNormal is a malloc/free style allocation,
5040  * while kReservation is for larger allocations with the ability to set
5041  * access permissions.
5042  */
5044 
5045  /**
5046  * malloc/free based convenience allocator.
5047  *
5048  * Caller takes ownership, i.e. the returned object needs to be freed using
5049  * |delete allocator| once it is no longer in use.
5050  */
5051  static Allocator* NewDefaultAllocator();
5052  };
5053 
5054  /**
5055  * The contents of an |ArrayBuffer|. Externalization of |ArrayBuffer|
5056  * returns an instance of this class, populated, with a pointer to data
5057  * and byte length.
5058  *
5059  * The Data pointer of ArrayBuffer::Contents must be freed using the provided
5060  * deleter, which will call ArrayBuffer::Allocator::Free if the buffer
5061  * was allocated with ArraryBuffer::Allocator::Allocate.
5062  */
5063  class V8_EXPORT Contents { // NOLINT
5064  public:
5065  using DeleterCallback = void (*)(void* buffer, size_t length, void* info);
5066 
5068  : data_(nullptr),
5069  byte_length_(0),
5070  allocation_base_(nullptr),
5071  allocation_length_(0),
5072  allocation_mode_(Allocator::AllocationMode::kNormal),
5073  deleter_(nullptr),
5074  deleter_data_(nullptr) {}
5075 
5076  void* AllocationBase() const { return allocation_base_; }
5077  size_t AllocationLength() const { return allocation_length_; }
5078  Allocator::AllocationMode AllocationMode() const {
5079  return allocation_mode_;
5080  }
5081 
5082  void* Data() const { return data_; }
5083  size_t ByteLength() const { return byte_length_; }
5084  DeleterCallback Deleter() const { return deleter_; }
5085  void* DeleterData() const { return deleter_data_; }
5086 
5087  private:
5088  Contents(void* data, size_t byte_length, void* allocation_base,
5089  size_t allocation_length,
5090  Allocator::AllocationMode allocation_mode, DeleterCallback deleter,
5091  void* deleter_data);
5092 
5093  void* data_;
5094  size_t byte_length_;
5095  void* allocation_base_;
5096  size_t allocation_length_;
5097  Allocator::AllocationMode allocation_mode_;
5098  DeleterCallback deleter_;
5099  void* deleter_data_;
5100 
5101  friend class ArrayBuffer;
5102  };
5103 
5104 
5105  /**
5106  * Data length in bytes.
5107  */
5108  size_t ByteLength() const;
5109 
5110  /**
5111  * Create a new ArrayBuffer. Allocate |byte_length| bytes.
5112  * Allocated memory will be owned by a created ArrayBuffer and
5113  * will be deallocated when it is garbage-collected,
5114  * unless the object is externalized.
5115  */
5116  static Local<ArrayBuffer> New(Isolate* isolate, size_t byte_length);
5117 
5118  /**
5119  * Create a new ArrayBuffer over an existing memory block.
5120  * The created array buffer is by default immediately in externalized state.
5121  * In externalized state, the memory block will not be reclaimed when a
5122  * created ArrayBuffer is garbage-collected.
5123  * In internalized state, the memory block will be released using
5124  * |Allocator::Free| once all ArrayBuffers referencing it are collected by
5125  * the garbage collector.
5126  */
5128  "Use the version that takes a BackingStore. "
5129  "See http://crbug.com/v8/9908.")
5130  static Local<ArrayBuffer> New(
5131  Isolate* isolate, void* data, size_t byte_length,
5133 
5134  /**
5135  * Create a new ArrayBuffer with an existing backing store.
5136  * The created array keeps a reference to the backing store until the array
5137  * is garbage collected. Note that the IsExternal bit does not affect this
5138  * reference from the array to the backing store.
5139  *
5140  * In future IsExternal bit will be removed. Until then the bit is set as
5141  * follows. If the backing store does not own the underlying buffer, then
5142  * the array is created in externalized state. Otherwise, the array is created
5143  * in internalized state. In the latter case the array can be transitioned
5144  * to the externalized state using Externalize(backing_store).
5145  */
5146  static Local<ArrayBuffer> New(Isolate* isolate,
5147  std::shared_ptr<BackingStore> backing_store);
5148 
5149  /**
5150  * Returns a new standalone BackingStore that is allocated using the array
5151  * buffer allocator of the isolate. The result can be later passed to
5152  * ArrayBuffer::New.
5153  *
5154  * If the allocator returns nullptr, then the function may cause GCs in the
5155  * given isolate and re-try the allocation. If GCs do not help, then the
5156  * function will crash with an out-of-memory error.
5157  */
5158  static std::unique_ptr<BackingStore> NewBackingStore(Isolate* isolate,
5159  size_t byte_length);
5160  /**
5161  * Returns a new standalone BackingStore that takes over the ownership of
5162  * the given buffer. The destructor of the BackingStore invokes the given
5163  * deleter callback.
5164  *
5165  * The result can be later passed to ArrayBuffer::New. The raw pointer
5166  * to the buffer must not be passed again to any V8 API function.
5167  */
5168  static std::unique_ptr<BackingStore> NewBackingStore(
5169  void* data, size_t byte_length, BackingStoreDeleterCallback deleter,
5170  void* deleter_data);
5171 
5172  /**
5173  * Returns true if ArrayBuffer is externalized, that is, does not
5174  * own its memory block.
5175  */
5177  "With v8::BackingStore externalized ArrayBuffers are "
5178  "the same as ordinary ArrayBuffers. See http://crbug.com/v8/9908.")
5179  bool IsExternal() const;
5180 
5181  /**
5182  * Returns true if this ArrayBuffer may be detached.
5183  */
5184  bool IsDetachable() const;
5185 
5186  /**
5187  * Detaches this ArrayBuffer and all its views (typed arrays).
5188  * Detaching sets the byte length of the buffer and all typed arrays to zero,
5189  * preventing JavaScript from ever accessing underlying backing store.
5190  * ArrayBuffer should have been externalized and must be detachable.
5191  */
5192  void Detach();
5193 
5194  /**
5195  * Make this ArrayBuffer external. The pointer to underlying memory block
5196  * and byte length are returned as |Contents| structure. After ArrayBuffer
5197  * had been externalized, it does no longer own the memory block. The caller
5198  * should take steps to free memory when it is no longer needed.
5199  *
5200  * The Data pointer of ArrayBuffer::Contents must be freed using the provided
5201  * deleter, which will call ArrayBuffer::Allocator::Free if the buffer
5202  * was allocated with ArrayBuffer::Allocator::Allocate.
5203  */
5205  "Use GetBackingStore or Detach. See http://crbug.com/v8/9908.")
5206  Contents Externalize();
5207 
5208  /**
5209  * Marks this ArrayBuffer external given a witness that the embedder
5210  * has fetched the backing store using the new GetBackingStore() function.
5211  *
5212  * With the new lifetime management of backing stores there is no need for
5213  * externalizing, so this function exists only to make the transition easier.
5214  */
5215  V8_DEPRECATE_SOON("This will be removed together with IsExternal.")
5216  void Externalize(const std::shared_ptr<BackingStore>& backing_store);
5217 
5218  /**
5219  * Get a pointer to the ArrayBuffer's underlying memory block without
5220  * externalizing it. If the ArrayBuffer is not externalized, this pointer
5221  * will become invalid as soon as the ArrayBuffer gets garbage collected.
5222  *
5223  * The embedder should make sure to hold a strong reference to the
5224  * ArrayBuffer while accessing this pointer.
5225  */
5226  V8_DEPRECATE_SOON("Use GetBackingStore. See http://crbug.com/v8/9908.")
5228 
5229  /**
5230  * Get a shared pointer to the backing store of this array buffer. This
5231  * pointer coordinates the lifetime management of the internal storage
5232  * with any live ArrayBuffers on the heap, even across isolates. The embedder
5233  * should not attempt to manage lifetime of the storage through other means.
5234  *
5235  * This function replaces both Externalize() and GetContents().
5236  */
5237  std::shared_ptr<BackingStore> GetBackingStore();
5238 
5239  V8_INLINE static ArrayBuffer* Cast(Value* obj);
5240 
5243 
5244  private:
5245  ArrayBuffer();
5246  static void CheckCast(Value* obj);
5247  Contents GetContents(bool externalize);
5248 };
5249 
5250 
5251 #ifndef V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT
5252 // The number of required internal fields can be defined by embedder.
5253 #define V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT 2
5254 #endif
5255 
5256 
5257 /**
5258  * A base class for an instance of one of "views" over ArrayBuffer,
5259  * including TypedArrays and DataView (ES6 draft 15.13).
5260  */
5262  public:
5263  /**
5264  * Returns underlying ArrayBuffer.
5265  */
5267  /**
5268  * Byte offset in |Buffer|.
5269  */
5270  size_t ByteOffset();
5271  /**
5272  * Size of a view in bytes.
5273  */
5274  size_t ByteLength();
5275 
5276  /**
5277  * Copy the contents of the ArrayBufferView's buffer to an embedder defined
5278  * memory without additional overhead that calling ArrayBufferView::Buffer
5279  * might incur.
5280  *
5281  * Will write at most min(|byte_length|, ByteLength) bytes starting at
5282  * ByteOffset of the underlying buffer to the memory starting at |dest|.
5283  * Returns the number of bytes actually written.
5284  */
5285  size_t CopyContents(void* dest, size_t byte_length);
5286 
5287  /**
5288  * Returns true if ArrayBufferView's backing ArrayBuffer has already been
5289  * allocated.
5290  */
5291  bool HasBuffer() const;
5292 
5293  V8_INLINE static ArrayBufferView* Cast(Value* obj);
5294 
5295  static const int kInternalFieldCount =
5297  static const int kEmbedderFieldCount =
5299 
5300  private:
5301  ArrayBufferView();
5302  static void CheckCast(Value* obj);
5303 };
5304 
5305 
5306 /**
5307  * A base class for an instance of TypedArray series of constructors
5308  * (ES6 draft 15.13.6).
5309  */
5311  public:
5312  /*
5313  * The largest typed array size that can be constructed using New.
5314  */
5315  static constexpr size_t kMaxLength = internal::kApiSystemPointerSize == 4
5317  : 0xFFFFFFFF;
5318 
5319  /**
5320  * Number of elements in this typed array
5321  * (e.g. for Int16Array, |ByteLength|/2).
5322  */
5323  size_t Length();
5324 
5325  V8_INLINE static TypedArray* Cast(Value* obj);
5326 
5327  private:
5328  TypedArray();
5329  static void CheckCast(Value* obj);
5330 };
5331 
5332 
5333 /**
5334  * An instance of Uint8Array constructor (ES6 draft 15.13.6).
5335  */
5337  public:
5338  static Local<Uint8Array> New(Local<ArrayBuffer> array_buffer,
5339  size_t byte_offset, size_t length);
5340  static Local<Uint8Array> New(Local<SharedArrayBuffer> shared_array_buffer,
5341  size_t byte_offset, size_t length);
5342  V8_INLINE static Uint8Array* Cast(Value* obj);
5343 
5344  private:
5345  Uint8Array();
5346  static void CheckCast(Value* obj);
5347 };
5348 
5349 
5350 /**
5351  * An instance of Uint8ClampedArray constructor (ES6 draft 15.13.6).
5352  */
5354  public:
5355  static Local<Uint8ClampedArray> New(Local<ArrayBuffer> array_buffer,
5356  size_t byte_offset, size_t length);
5357  static Local<Uint8ClampedArray> New(
5358  Local<SharedArrayBuffer> shared_array_buffer, size_t byte_offset,
5359  size_t length);
5360  V8_INLINE static Uint8ClampedArray* Cast(Value* obj);
5361 
5362  private:
5363  Uint8ClampedArray();
5364  static void CheckCast(Value* obj);
5365 };
5366 
5367 /**
5368  * An instance of Int8Array constructor (ES6 draft 15.13.6).
5369  */
5371  public:
5372  static Local<Int8Array> New(Local<ArrayBuffer> array_buffer,
5373  size_t byte_offset, size_t length);
5374  static Local<Int8Array> New(Local<SharedArrayBuffer> shared_array_buffer,
5375  size_t byte_offset, size_t length);
5376  V8_INLINE static Int8Array* Cast(Value* obj);
5377 
5378  private:
5379  Int8Array();
5380  static void CheckCast(Value* obj);
5381 };
5382 
5383 
5384 /**
5385  * An instance of Uint16Array constructor (ES6 draft 15.13.6).
5386  */
5388  public:
5389  static Local<Uint16Array> New(Local<ArrayBuffer> array_buffer,
5390  size_t byte_offset, size_t length);
5391  static Local<Uint16Array> New(Local<SharedArrayBuffer> shared_array_buffer,
5392  size_t byte_offset, size_t length);
5393  V8_INLINE static Uint16Array* Cast(Value* obj);
5394 
5395  private:
5396  Uint16Array();
5397  static void CheckCast(Value* obj);
5398 };
5399 
5400 
5401 /**
5402  * An instance of Int16Array constructor (ES6 draft 15.13.6).
5403  */
5405  public:
5406  static Local<Int16Array> New(Local<ArrayBuffer> array_buffer,
5407  size_t byte_offset, size_t length);
5408  static Local<Int16Array> New(Local<SharedArrayBuffer> shared_array_buffer,
5409  size_t byte_offset, size_t length);
5410  V8_INLINE static Int16Array* Cast(Value* obj);
5411 
5412  private:
5413  Int16Array();
5414  static void CheckCast(Value* obj);
5415 };
5416 
5417 
5418 /**
5419  * An instance of Uint32Array constructor (ES6 draft 15.13.6).
5420  */
5422  public:
5423  static Local<Uint32Array> New(Local<ArrayBuffer> array_buffer,
5424  size_t byte_offset, size_t length);
5425  static Local<Uint32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
5426  size_t byte_offset, size_t length);
5427  V8_INLINE static Uint32Array* Cast(Value* obj);
5428 
5429  private:
5430  Uint32Array();
5431  static void CheckCast(Value* obj);
5432 };
5433 
5434 
5435 /**
5436  * An instance of Int32Array constructor (ES6 draft 15.13.6).
5437  */
5439  public:
5440  static Local<Int32Array> New(Local<ArrayBuffer> array_buffer,
5441  size_t byte_offset, size_t length);
5442  static Local<Int32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
5443  size_t byte_offset, size_t length);
5444  V8_INLINE static Int32Array* Cast(Value* obj);
5445 
5446  private:
5447  Int32Array();
5448  static void CheckCast(Value* obj);
5449 };
5450 
5451 
5452 /**
5453  * An instance of Float32Array constructor (ES6 draft 15.13.6).
5454  */
5456  public:
5457  static Local<Float32Array> New(Local<ArrayBuffer> array_buffer,
5458  size_t byte_offset, size_t length);
5459  static Local<Float32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
5460  size_t byte_offset, size_t length);
5461  V8_INLINE static Float32Array* Cast(Value* obj);
5462 
5463  private:
5464  Float32Array();
5465  static void CheckCast(Value* obj);
5466 };
5467 
5468 
5469 /**
5470  * An instance of Float64Array constructor (ES6 draft 15.13.6).
5471  */
5473  public:
5474  static Local<Float64Array> New(Local<ArrayBuffer> array_buffer,
5475  size_t byte_offset, size_t length);
5476  static Local<Float64Array> New(Local<SharedArrayBuffer> shared_array_buffer,
5477  size_t byte_offset, size_t length);
5478  V8_INLINE static Float64Array* Cast(Value* obj);
5479 
5480  private:
5481  Float64Array();
5482  static void CheckCast(Value* obj);
5483 };
5484 
5485 /**
5486  * An instance of BigInt64Array constructor.
5487  */
5489  public:
5490  static Local<BigInt64Array> New(Local<ArrayBuffer> array_buffer,
5491  size_t byte_offset, size_t length);
5492  static Local<BigInt64Array> New(Local<SharedArrayBuffer> shared_array_buffer,
5493  size_t byte_offset, size_t length);
5494  V8_INLINE static BigInt64Array* Cast(Value* obj);
5495 
5496  private:
5497  BigInt64Array();
5498  static void CheckCast(Value* obj);
5499 };
5500 
5501 /**
5502  * An instance of BigUint64Array constructor.
5503  */
5505  public:
5506  static Local<BigUint64Array> New(Local<ArrayBuffer> array_buffer,
5507  size_t byte_offset, size_t length);
5508  static Local<BigUint64Array> New(Local<SharedArrayBuffer> shared_array_buffer,
5509  size_t byte_offset, size_t length);
5510  V8_INLINE static BigUint64Array* Cast(Value* obj);
5511 
5512  private:
5513  BigUint64Array();
5514  static void CheckCast(Value* obj);
5515 };
5516 
5517 /**
5518  * An instance of DataView constructor (ES6 draft 15.13.7).
5519  */
5521  public:
5522  static Local<DataView> New(Local<ArrayBuffer> array_buffer,
5523  size_t byte_offset, size_t length);
5524  static Local<DataView> New(Local<SharedArrayBuffer> shared_array_buffer,
5525  size_t byte_offset, size_t length);
5526  V8_INLINE static DataView* Cast(Value* obj);
5527 
5528  private:
5529  DataView();
5530  static void CheckCast(Value* obj);
5531 };
5532 
5533 
5534 /**
5535  * An instance of the built-in SharedArrayBuffer constructor.
5536  */
5538  public:
5539  /**
5540  * The contents of an |SharedArrayBuffer|. Externalization of
5541  * |SharedArrayBuffer| returns an instance of this class, populated, with a
5542  * pointer to data and byte length.
5543  *
5544  * The Data pointer of ArrayBuffer::Contents must be freed using the provided
5545  * deleter, which will call ArrayBuffer::Allocator::Free if the buffer
5546  * was allocated with ArraryBuffer::Allocator::Allocate.
5547  */
5548  class V8_EXPORT Contents { // NOLINT
5549  public:
5550  using Allocator = v8::ArrayBuffer::Allocator;
5551  using DeleterCallback = void (*)(void* buffer, size_t length, void* info);
5552 
5554  : data_(nullptr),
5555  byte_length_(0),
5556  allocation_base_(nullptr),
5557  allocation_length_(0),
5558  allocation_mode_(Allocator::AllocationMode::kNormal),
5559  deleter_(nullptr),
5560  deleter_data_(nullptr) {}
5561 
5562  void* AllocationBase() const { return allocation_base_; }
5563  size_t AllocationLength() const { return allocation_length_; }
5564  Allocator::AllocationMode AllocationMode() const {
5565  return allocation_mode_;
5566  }
5567 
5568  void* Data() const { return data_; }
5569  size_t ByteLength() const { return byte_length_; }
5570  DeleterCallback Deleter() const { return deleter_; }
5571  void* DeleterData() const { return deleter_data_; }
5572 
5573  private:
5574  Contents(void* data, size_t byte_length, void* allocation_base,
5575  size_t allocation_length,
5576  Allocator::AllocationMode allocation_mode, DeleterCallback deleter,
5577  void* deleter_data);
5578 
5579  void* data_;
5580  size_t byte_length_;
5581  void* allocation_base_;
5582  size_t allocation_length_;
5583  Allocator::AllocationMode allocation_mode_;
5584  DeleterCallback deleter_;
5585  void* deleter_data_;
5586 
5587  friend class SharedArrayBuffer;
5588  };
5589 
5590  /**
5591  * Data length in bytes.
5592  */
5593  size_t ByteLength() const;
5594 
5595  /**
5596  * Create a new SharedArrayBuffer. Allocate |byte_length| bytes.
5597  * Allocated memory will be owned by a created SharedArrayBuffer and
5598  * will be deallocated when it is garbage-collected,
5599  * unless the object is externalized.
5600  */
5601  static Local<SharedArrayBuffer> New(Isolate* isolate, size_t byte_length);
5602 
5603  /**
5604  * Create a new SharedArrayBuffer over an existing memory block. The created
5605  * array buffer is immediately in externalized state unless otherwise
5606  * specified. The memory block will not be reclaimed when a created
5607  * SharedArrayBuffer is garbage-collected.
5608  */
5610  "Use the version that takes a BackingStore. "
5611  "See http://crbug.com/v8/9908.")
5612  static Local<SharedArrayBuffer> New(
5613  Isolate* isolate, void* data, size_t byte_length,
5615 
5616  /**
5617  * Create a new SharedArrayBuffer with an existing backing store.
5618  * The created array keeps a reference to the backing store until the array
5619  * is garbage collected. Note that the IsExternal bit does not affect this
5620  * reference from the array to the backing store.
5621  *
5622  * In future IsExternal bit will be removed. Until then the bit is set as
5623  * follows. If the backing store does not own the underlying buffer, then
5624  * the array is created in externalized state. Otherwise, the array is created
5625  * in internalized state. In the latter case the array can be transitioned
5626  * to the externalized state using Externalize(backing_store).
5627  */
5628  static Local<SharedArrayBuffer> New(
5629  Isolate* isolate, std::shared_ptr<BackingStore> backing_store);
5630 
5631  /**
5632  * Returns a new standalone BackingStore that is allocated using the array
5633  * buffer allocator of the isolate. The result can be later passed to
5634  * SharedArrayBuffer::New.
5635  *
5636  * If the allocator returns nullptr, then the function may cause GCs in the
5637  * given isolate and re-try the allocation. If GCs do not help, then the
5638  * function will crash with an out-of-memory error.
5639  */
5640  static std::unique_ptr<BackingStore> NewBackingStore(Isolate* isolate,
5641  size_t byte_length);
5642  /**
5643  * Returns a new standalone BackingStore that takes over the ownership of
5644  * the given buffer. The destructor of the BackingStore invokes the given
5645  * deleter callback.
5646  *
5647  * The result can be later passed to SharedArrayBuffer::New. The raw pointer
5648  * to the buffer must not be passed again to any V8 functions.
5649  */
5650  static std::unique_ptr<BackingStore> NewBackingStore(
5651  void* data, size_t byte_length, BackingStoreDeleterCallback deleter,
5652  void* deleter_data);
5653 
5654  /**
5655  * Create a new SharedArrayBuffer over an existing memory block. Propagate
5656  * flags to indicate whether the underlying buffer can be grown.
5657  */
5658  V8_DEPRECATED(
5659  "Use the version that takes a BackingStore. "
5660  "See http://crbug.com/v8/9908.")
5661  static Local<SharedArrayBuffer> New(
5662  Isolate* isolate, const SharedArrayBuffer::Contents&,
5664 
5665  /**
5666  * Returns true if SharedArrayBuffer is externalized, that is, does not
5667  * own its memory block.
5668  */
5670  "With v8::BackingStore externalized SharedArrayBuffers are the same "
5671  "as ordinary SharedArrayBuffers. See http://crbug.com/v8/9908.")
5672  bool IsExternal() const;
5673 
5674  /**
5675  * Make this SharedArrayBuffer external. The pointer to underlying memory
5676  * block and byte length are returned as |Contents| structure. After
5677  * SharedArrayBuffer had been externalized, it does no longer own the memory
5678  * block. The caller should take steps to free memory when it is no longer
5679  * needed.
5680  *
5681  * The memory block is guaranteed to be allocated with |Allocator::Allocate|
5682  * by the allocator specified in
5683  * v8::Isolate::CreateParams::array_buffer_allocator.
5684  *
5685  */
5687  "Use GetBackingStore or Detach. See http://crbug.com/v8/9908.")
5688  Contents Externalize();
5689 
5690  /**
5691  * Marks this SharedArrayBuffer external given a witness that the embedder
5692  * has fetched the backing store using the new GetBackingStore() function.
5693  *
5694  * With the new lifetime management of backing stores there is no need for
5695  * externalizing, so this function exists only to make the transition easier.
5696  */
5697  V8_DEPRECATE_SOON("This will be removed together with IsExternal.")
5698  void Externalize(const std::shared_ptr<BackingStore>& backing_store);
5699 
5700  /**
5701  * Get a pointer to the ArrayBuffer's underlying memory block without
5702  * externalizing it. If the ArrayBuffer is not externalized, this pointer
5703  * will become invalid as soon as the ArrayBuffer became garbage collected.
5704  *
5705  * The embedder should make sure to hold a strong reference to the
5706  * ArrayBuffer while accessing this pointer.
5707  *
5708  * The memory block is guaranteed to be allocated with |Allocator::Allocate|
5709  * by the allocator specified in
5710  * v8::Isolate::CreateParams::array_buffer_allocator.
5711  */
5712  V8_DEPRECATE_SOON("Use GetBackingStore. See http://crbug.com/v8/9908.")
5714 
5715  /**
5716  * Get a shared pointer to the backing store of this array buffer. This
5717  * pointer coordinates the lifetime management of the internal storage
5718  * with any live ArrayBuffers on the heap, even across isolates. The embedder
5719  * should not attempt to manage lifetime of the storage through other means.
5720  *
5721  * This function replaces both Externalize() and GetContents().
5722  */
5723  std::shared_ptr<BackingStore> GetBackingStore();
5724 
5725  V8_INLINE static SharedArrayBuffer* Cast(Value* obj);
5726 
5728 
5729  private:
5730  SharedArrayBuffer();
5731  static void CheckCast(Value* obj);
5732  Contents GetContents(bool externalize);
5733 };
5734 
5735 
5736 /**
5737  * An instance of the built-in Date constructor (ECMA-262, 15.9).
5738  */
5739 class V8_EXPORT Date : public Object {
5740  public:
5742  double time);
5743 
5744  /**
5745  * A specialization of Value::NumberValue that is more efficient
5746  * because we know the structure of this object.
5747  */
5748  double ValueOf() const;
5749 
5750  V8_INLINE static Date* Cast(Value* obj);
5751 
5752  private:
5753  static void CheckCast(Value* obj);
5754 };
5755 
5756 
5757 /**
5758  * A Number object (ECMA-262, 4.3.21).
5759  */
5761  public:
5762  static Local<Value> New(Isolate* isolate, double value);
5763 
5764  double ValueOf() const;
5765 
5766  V8_INLINE static NumberObject* Cast(Value* obj);
5767 
5768  private:
5769  static void CheckCast(Value* obj);
5770 };
5771 
5772 /**
5773  * A BigInt object (https://tc39.github.io/proposal-bigint)
5774  */
5776  public:
5777  static Local<Value> New(Isolate* isolate, int64_t value);
5778 
5779  Local<BigInt> ValueOf() const;
5780 
5781  V8_INLINE static BigIntObject* Cast(Value* obj);
5782 
5783  private:
5784  static void CheckCast(Value* obj);
5785 };
5786 
5787 /**
5788  * A Boolean object (ECMA-262, 4.3.15).
5789  */
5791  public:
5792  static Local<Value> New(Isolate* isolate, bool value);
5793 
5794  bool ValueOf() const;
5795 
5796  V8_INLINE static BooleanObject* Cast(Value* obj);
5797 
5798  private:
5799  static void CheckCast(Value* obj);
5800 };
5801 
5802 
5803 /**
5804  * A String object (ECMA-262, 4.3.18).
5805  */
5807  public:
5808  static Local<Value> New(Isolate* isolate, Local<String> value);
5809 
5810  Local<String> ValueOf() const;
5811 
5812  V8_INLINE static StringObject* Cast(Value* obj);
5813 
5814  private:
5815  static void CheckCast(Value* obj);
5816 };
5817 
5818 
5819 /**
5820  * A Symbol object (ECMA-262 edition 6).
5821  */
5823  public:
5824  static Local<Value> New(Isolate* isolate, Local<Symbol> value);
5825 
5826  Local<Symbol> ValueOf() const;
5827 
5828  V8_INLINE static SymbolObject* Cast(Value* obj);
5829 
5830  private:
5831  static void CheckCast(Value* obj);
5832 };
5833 
5834 
5835 /**
5836  * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
5837  */
5838 class V8_EXPORT RegExp : public Object {
5839  public:
5840  /**
5841  * Regular expression flag bits. They can be or'ed to enable a set
5842  * of flags.
5843  */
5844  enum Flags {
5845  kNone = 0,
5846  kGlobal = 1 << 0,
5847  kIgnoreCase = 1 << 1,
5848  kMultiline = 1 << 2,
5849  kSticky = 1 << 3,
5850  kUnicode = 1 << 4,
5851  kDotAll = 1 << 5,
5852  };
5853 
5854  static constexpr int kFlagCount = 6;
5855 
5856  /**
5857  * Creates a regular expression from the given pattern string and
5858  * the flags bit field. May throw a JavaScript exception as
5859  * described in ECMA-262, 15.10.4.1.
5860  *
5861  * For example,
5862  * RegExp::New(v8::String::New("foo"),
5863  * static_cast<RegExp::Flags>(kGlobal | kMultiline))
5864  * is equivalent to evaluating "/foo/gm".
5865  */
5867  Local<String> pattern,
5868  Flags flags);
5869 
5870  /**
5871  * Like New, but additionally specifies a backtrack limit. If the number of
5872  * backtracks done in one Exec call hits the limit, a match failure is
5873  * immediately returned.
5874  */
5876  Local<Context> context, Local<String> pattern, Flags flags,
5877  uint32_t backtrack_limit);
5878 
5879  /**
5880  * Executes the current RegExp instance on the given subject string.
5881  * Equivalent to RegExp.prototype.exec as described in
5882  *
5883  * https://tc39.es/ecma262/#sec-regexp.prototype.exec
5884  *
5885  * On success, an Array containing the matched strings is returned. On
5886  * failure, returns Null.
5887  *
5888  * Note: modifies global context state, accessible e.g. through RegExp.input.
5889  */
5891  Local<String> subject);
5892 
5893  /**
5894  * Returns the value of the source property: a string representing
5895  * the regular expression.
5896  */
5897  Local<String> GetSource() const;
5898 
5899  /**
5900  * Returns the flags bit field.
5901  */
5902  Flags GetFlags() const;
5903 
5904  V8_INLINE static RegExp* Cast(Value* obj);
5905 
5906  private:
5907  static void CheckCast(Value* obj);
5908 };
5909 
5910 /**
5911  * An instance of the built-in FinalizationGroup constructor.
5912  *
5913  * This API is experimental and may change significantly.
5914  */
5916  public:
5917  /**
5918  * Runs the cleanup callback of the given FinalizationGroup.
5919  *
5920  * V8 will inform the embedder that there are finalizer callbacks be
5921  * called through HostCleanupFinalizationGroupCallback.
5922  *
5923  * HostCleanupFinalizationGroupCallback should schedule a task to
5924  * call FinalizationGroup::Cleanup() at some point in the
5925  * future. It's the embedders responsiblity to make this call at a
5926  * time which does not interrupt synchronous ECMAScript code
5927  * execution.
5928  *
5929  * If the result is Nothing<bool> then an exception has
5930  * occurred. Otherwise the result is |true| if the cleanup callback
5931  * was called successfully. The result is never |false|.
5932  */
5933  static V8_WARN_UNUSED_RESULT Maybe<bool> Cleanup(
5934  Local<FinalizationGroup> finalization_group);
5935 };
5936 
5937 /**
5938  * A JavaScript value that wraps a C++ void*. This type of value is mainly used
5939  * to associate C++ data structures with JavaScript objects.
5940  */
5941 class V8_EXPORT External : public Value {
5942  public:
5943  static Local<External> New(Isolate* isolate, void* value);
5944  V8_INLINE static External* Cast(Value* obj);
5945  void* Value() const;
5946  private:
5947  static void CheckCast(v8::Value* obj);
5948 };
5949 
5950 #define V8_INTRINSICS_LIST(F)
5951  F(ArrayProto_entries, array_entries_iterator)
5952  F(ArrayProto_forEach, array_for_each_iterator)
5953  F(ArrayProto_keys, array_keys_iterator)
5954  F(ArrayProto_values, array_values_iterator)
5955  F(ErrorPrototype, initial_error_prototype)
5956  F(IteratorPrototype, initial_iterator_prototype)
5957 
5959 #define V8_DECL_INTRINSIC(name, iname) k##name,
5961 #undef V8_DECL_INTRINSIC
5962 };
5963 
5964 
5965 // --- Templates ---
5966 
5967 
5968 /**
5969  * The superclass of object and function templates.
5970  */
5971 class V8_EXPORT Template : public Data {
5972  public:
5973  /**
5974  * Adds a property to each instance created by this template.
5975  *
5976  * The property must be defined either as a primitive value, or a template.
5977  */
5978  void Set(Local<Name> name, Local<Data> value,
5979  PropertyAttribute attributes = None);
5980  void SetPrivate(Local<Private> name, Local<Data> value,
5981  PropertyAttribute attributes = None);
5982  V8_INLINE void Set(Isolate* isolate, const char* name, Local<Data> value);
5983 
5984  void SetAccessorProperty(
5985  Local<Name> name,
5988  PropertyAttribute attribute = None,
5989  AccessControl settings = DEFAULT);
5990 
5991  /**
5992  * Whenever the property with the given name is accessed on objects
5993  * created from this Template the getter and setter callbacks
5994  * are called instead of getting and setting the property directly
5995  * on the JavaScript object.
5996  *
5997  * \param name The name of the property for which an accessor is added.
5998  * \param getter The callback to invoke when getting the property.
5999  * \param setter The callback to invoke when setting the property.
6000  * \param data A piece of data that will be passed to the getter and setter
6001  * callbacks whenever they are invoked.
6002  * \param settings Access control settings for the accessor. This is a bit
6003  * field consisting of one of more of
6004  * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
6005  * The default is to not allow cross-context access.
6006  * ALL_CAN_READ means that all cross-context reads are allowed.
6007  * ALL_CAN_WRITE means that all cross-context writes are allowed.
6008  * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
6009  * cross-context access.
6010  * \param attribute The attributes of the property for which an accessor
6011  * is added.
6012  * \param signature The signature describes valid receivers for the accessor
6013  * and is used to perform implicit instance checks against them. If the
6014  * receiver is incompatible (i.e. is not an instance of the constructor as
6015  * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
6016  * thrown and no callback is invoked.
6017  */
6018  void SetNativeDataProperty(
6019  Local<String> name, AccessorGetterCallback getter,
6020  AccessorSetterCallback setter = nullptr,
6021  // TODO(dcarney): gcc can't handle Local below
6022  Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
6024  AccessControl settings = DEFAULT,
6025  SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
6026  SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
6027  void SetNativeDataProperty(
6028  Local<Name> name, AccessorNameGetterCallback getter,
6029  AccessorNameSetterCallback setter = nullptr,
6030  // TODO(dcarney): gcc can't handle Local below
6031  Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
6033  AccessControl settings = DEFAULT,
6034  SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
6035  SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
6036 
6037  /**
6038  * Like SetNativeDataProperty, but V8 will replace the native data property
6039  * with a real data property on first access.
6040  */
6041  void SetLazyDataProperty(
6042  Local<Name> name, AccessorNameGetterCallback getter,
6043  Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
6044  SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
6045  SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
6046 
6047  /**
6048  * During template instantiation, sets the value with the intrinsic property
6049  * from the correct context.
6050  */
6051  void SetIntrinsicDataProperty(Local<Name> name, Intrinsic intrinsic,
6052  PropertyAttribute attribute = None);
6053 
6054  private:
6055  Template();
6056 
6057  friend class ObjectTemplate;
6058  friend class FunctionTemplate;
6059 };
6060 
6061 // TODO(dcarney): Replace GenericNamedPropertyFooCallback with just
6062 // NamedPropertyFooCallback.
6063 
6064 /**
6065  * Interceptor for get requests on an object.
6066  *
6067  * Use `info.GetReturnValue().Set()` to set the return value of the
6068  * intercepted get request.
6069  *
6070  * \param property The name of the property for which the request was
6071  * intercepted.
6072  * \param info Information about the intercepted request, such as
6073  * isolate, receiver, return value, or whether running in `'use strict`' mode.
6074  * See `PropertyCallbackInfo`.
6075  *
6076  * \code
6077  * void GetterCallback(
6078  * Local<Name> name,
6079  * const v8::PropertyCallbackInfo<v8::Value>& info) {
6080  * info.GetReturnValue().Set(v8_num(42));
6081  * }
6082  *
6083  * v8::Local<v8::FunctionTemplate> templ =
6084  * v8::FunctionTemplate::New(isolate);
6085  * templ->InstanceTemplate()->SetHandler(
6086  * v8::NamedPropertyHandlerConfiguration(GetterCallback));
6087  * LocalContext env;
6088  * env->Global()
6089  * ->Set(env.local(), v8_str("obj"), templ->GetFunction(env.local())
6090  * .ToLocalChecked()
6091  * ->NewInstance(env.local())
6092  * .ToLocalChecked())
6093  * .FromJust();
6094  * v8::Local<v8::Value> result = CompileRun("obj.a = 17; obj.a");
6095  * CHECK(v8_num(42)->Equals(env.local(), result).FromJust());
6096  * \endcode
6097  *
6098  * See also `ObjectTemplate::SetHandler`.
6099  */
6101  Local<Name> property, const PropertyCallbackInfo<Value>& info);
6102 
6103 /**
6104  * Interceptor for set requests on an object.
6105  *
6106  * Use `info.GetReturnValue()` to indicate whether the request was intercepted
6107  * or not. If the setter successfully intercepts the request, i.e., if the
6108  * request should not be further executed, call
6109  * `info.GetReturnValue().Set(value)`. If the setter
6110  * did not intercept the request, i.e., if the request should be handled as
6111  * if no interceptor is present, do not not call `Set()`.
6112  *
6113  * \param property The name of the property for which the request was
6114  * intercepted.
6115  * \param value The value which the property will have if the request
6116  * is not intercepted.
6117  * \param info Information about the intercepted request, such as
6118  * isolate, receiver, return value, or whether running in `'use strict'` mode.
6119  * See `PropertyCallbackInfo`.
6120  *
6121  * See also
6122  * `ObjectTemplate::SetHandler.`
6123  */
6125  Local<Name> property, Local<Value> value,
6126  const PropertyCallbackInfo<Value>& info);
6127 
6128 /**
6129  * Intercepts all requests that query the attributes of the
6130  * property, e.g., getOwnPropertyDescriptor(), propertyIsEnumerable(), and
6131  * defineProperty().
6132  *
6133  * Use `info.GetReturnValue().Set(value)` to set the property attributes. The
6134  * value is an integer encoding a `v8::PropertyAttribute`.
6135  *
6136  * \param property The name of the property for which the request was
6137  * intercepted.
6138  * \param info Information about the intercepted request, such as
6139  * isolate, receiver, return value, or whether running in `'use strict'` mode.
6140  * See `PropertyCallbackInfo`.
6141  *
6142  * \note Some functions query the property attributes internally, even though
6143  * they do not return the attributes. For example, `hasOwnProperty()` can
6144  * trigger this interceptor depending on the state of the object.
6145  *
6146  * See also
6147  * `ObjectTemplate::SetHandler.`
6148  */
6150  Local<Name> property, const PropertyCallbackInfo<Integer>& info);
6151 
6152 /**
6153  * Interceptor for delete requests on an object.
6154  *
6155  * Use `info.GetReturnValue()` to indicate whether the request was intercepted
6156  * or not. If the deleter successfully intercepts the request, i.e., if the
6157  * request should not be further executed, call
6158  * `info.GetReturnValue().Set(value)` with a boolean `value`. The `value` is
6159  * used as the return value of `delete`.
6160  *
6161  * \param property The name of the property for which the request was
6162  * intercepted.
6163  * \param info Information about the intercepted request, such as
6164  * isolate, receiver, return value, or whether running in `'use strict'` mode.
6165  * See `PropertyCallbackInfo`.
6166  *
6167  * \note If you need to mimic the behavior of `delete`, i.e., throw in strict
6168  * mode instead of returning false, use `info.ShouldThrowOnError()` to determine
6169  * if you are in strict mode.
6170  *
6171  * See also `ObjectTemplate::SetHandler.`
6172  */
6174  Local<Name> property, const PropertyCallbackInfo<Boolean>& info);
6175 
6176 /**
6177  * Returns an array containing the names of the properties the named
6178  * property getter intercepts.
6179  *
6180  * Note: The values in the array must be of type v8::Name.
6181  */
6183  const PropertyCallbackInfo<Array>& info);
6184 
6185 /**
6186  * Interceptor for defineProperty requests on an object.
6187  *
6188  * Use `info.GetReturnValue()` to indicate whether the request was intercepted
6189  * or not. If the definer successfully intercepts the request, i.e., if the
6190  * request should not be further executed, call
6191  * `info.GetReturnValue().Set(value)`. If the definer
6192  * did not intercept the request, i.e., if the request should be handled as
6193  * if no interceptor is present, do not not call `Set()`.
6194  *
6195  * \param property The name of the property for which the request was
6196  * intercepted.
6197  * \param desc The property descriptor which is used to define the
6198  * property if the request is not intercepted.
6199  * \param info Information about the intercepted request, such as
6200  * isolate, receiver, return value, or whether running in `'use strict'` mode.
6201  * See `PropertyCallbackInfo`.
6202  *
6203  * See also `ObjectTemplate::SetHandler`.
6204  */
6206  Local<Name> property, const PropertyDescriptor& desc,
6207  const PropertyCallbackInfo<Value>& info);
6208 
6209 /**
6210  * Interceptor for getOwnPropertyDescriptor requests on an object.
6211  *
6212  * Use `info.GetReturnValue().Set()` to set the return value of the
6213  * intercepted request. The return value must be an object that
6214  * can be converted to a PropertyDescriptor, e.g., a `v8::value` returned from
6215  * `v8::Object::getOwnPropertyDescriptor`.
6216  *
6217  * \param property The name of the property for which the request was
6218  * intercepted.
6219  * \info Information about the intercepted request, such as
6220  * isolate, receiver, return value, or whether running in `'use strict'` mode.
6221  * See `PropertyCallbackInfo`.
6222  *
6223  * \note If GetOwnPropertyDescriptor is intercepted, it will
6224  * always return true, i.e., indicate that the property was found.
6225  *
6226  * See also `ObjectTemplate::SetHandler`.
6227  */
6229  Local<Name> property, const PropertyCallbackInfo<Value>& info);
6230 
6231 /**
6232  * See `v8::GenericNamedPropertyGetterCallback`.
6233  */
6235  uint32_t index,
6236  const PropertyCallbackInfo<Value>& info);
6237 
6238 /**
6239  * See `v8::GenericNamedPropertySetterCallback`.
6240  */
6242  uint32_t index,
6243  Local<Value> value,
6244  const PropertyCallbackInfo<Value>& info);
6245 
6246 /**
6247  * See `v8::GenericNamedPropertyQueryCallback`.
6248  */
6250  uint32_t index,
6251  const PropertyCallbackInfo<Integer>& info);
6252 
6253 /**
6254  * See `v8::GenericNamedPropertyDeleterCallback`.
6255  */
6257  uint32_t index,
6258  const PropertyCallbackInfo<Boolean>& info);
6259 
6260 /**
6261  * Returns an array containing the indices of the properties the indexed
6262  * property getter intercepts.
6263  *
6264  * Note: The values in the array must be uint32_t.
6265  */
6267  const PropertyCallbackInfo<Array>& info);
6268 
6269 /**
6270  * See `v8::GenericNamedPropertyDefinerCallback`.
6271  */
6273  uint32_t index, const PropertyDescriptor& desc,
6274  const PropertyCallbackInfo<Value>& info);
6275 
6276 /**
6277  * See `v8::GenericNamedPropertyDescriptorCallback`.
6278  */
6280  uint32_t index, const PropertyCallbackInfo<Value>& info);
6281 
6282 /**
6283  * Access type specification.
6284  */
6291 };
6292 
6293 
6294 /**
6295  * Returns true if the given context should be allowed to access the given
6296  * object.
6297  */
6298 typedef bool (*AccessCheckCallback)(Local<Context> accessing_context,
6299  Local<Object> accessed_object,
6300  Local<Value> data);
6301 
6302 /**
6303  * A FunctionTemplate is used to create functions at runtime. There
6304  * can only be one function created from a FunctionTemplate in a
6305  * context. The lifetime of the created function is equal to the
6306  * lifetime of the context. So in case the embedder needs to create
6307  * temporary functions that can be collected using Scripts is
6308  * preferred.
6309  *
6310  * Any modification of a FunctionTemplate after first instantiation will trigger
6311  * a crash.
6312  *
6313  * A FunctionTemplate can have properties, these properties are added to the
6314  * function object when it is created.
6315  *
6316  * A FunctionTemplate has a corresponding instance template which is
6317  * used to create object instances when the function is used as a
6318  * constructor. Properties added to the instance template are added to
6319  * each object instance.
6320  *
6321  * A FunctionTemplate can have a prototype template. The prototype template
6322  * is used to create the prototype object of the function.
6323  *
6324  * The following example shows how to use a FunctionTemplate:
6325  *
6326  * \code
6327  * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(isolate);
6328  * t->Set(isolate, "func_property", v8::Number::New(isolate, 1));
6329  *
6330  * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
6331  * proto_t->Set(isolate,
6332  * "proto_method",
6333  * v8::FunctionTemplate::New(isolate, InvokeCallback));
6334  * proto_t->Set(isolate, "proto_const", v8::Number::New(isolate, 2));
6335  *
6336  * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
6337  * instance_t->SetAccessor(String::NewFromUtf8(isolate, "instance_accessor"),
6338  * InstanceAccessorCallback);
6339  * instance_t->SetHandler(
6340  * NamedPropertyHandlerConfiguration(PropertyHandlerCallback));
6341  * instance_t->Set(String::NewFromUtf8(isolate, "instance_property"),
6342  * Number::New(isolate, 3));
6343  *
6344  * v8::Local<v8::Function> function = t->GetFunction();
6345  * v8::Local<v8::Object> instance = function->NewInstance();
6346  * \endcode
6347  *
6348  * Let's use "function" as the JS variable name of the function object
6349  * and "instance" for the instance object created above. The function
6350  * and the instance will have the following properties:
6351  *
6352  * \code
6353  * func_property in function == true;
6354  * function.func_property == 1;
6355  *
6356  * function.prototype.proto_method() invokes 'InvokeCallback'
6357  * function.prototype.proto_const == 2;
6358  *
6359  * instance instanceof function == true;
6360  * instance.instance_accessor calls 'InstanceAccessorCallback'
6361  * instance.instance_property == 3;
6362  * \endcode
6363  *
6364  * A FunctionTemplate can inherit from another one by calling the
6365  * FunctionTemplate::Inherit method. The following graph illustrates
6366  * the semantics of inheritance:
6367  *
6368  * \code
6369  * FunctionTemplate Parent -> Parent() . prototype -> { }
6370  * ^ ^
6371  * | Inherit(Parent) | .__proto__
6372  * | |
6373  * FunctionTemplate Child -> Child() . prototype -> { }
6374  * \endcode
6375  *
6376  * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
6377  * object of the Child() function has __proto__ pointing to the
6378  * Parent() function's prototype object. An instance of the Child
6379  * function has all properties on Parent's instance templates.
6380  *
6381  * Let Parent be the FunctionTemplate initialized in the previous
6382  * section and create a Child FunctionTemplate by:
6383  *
6384  * \code
6385  * Local<FunctionTemplate> parent = t;
6386  * Local<FunctionTemplate> child = FunctionTemplate::New();
6387  * child->Inherit(parent);
6388  *
6389  * Local<Function> child_function = child->GetFunction();
6390  * Local<Object> child_instance = child_function->NewInstance();
6391  * \endcode
6392  *
6393  * The Child function and Child instance will have the following
6394  * properties:
6395  *
6396  * \code
6397  * child_func.prototype.__proto__ == function.prototype;
6398  * child_instance.instance_accessor calls 'InstanceAccessorCallback'
6399  * child_instance.instance_property == 3;
6400  * \endcode
6401  */
6403  public:
6404  /** Creates a function template.*/
6405  static Local<FunctionTemplate> New(
6406  Isolate* isolate, FunctionCallback callback = nullptr,
6407  Local<Value> data = Local<Value>(),
6408  Local<Signature> signature = Local<Signature>(), int length = 0,
6410  SideEffectType side_effect_type = SideEffectType::kHasSideEffect);
6411 
6412  /** Get a template included in the snapshot by index. */
6413  V8_DEPRECATED("Use v8::Isolate::GetDataFromSnapshotOnce instead")
6415  size_t index);
6416 
6417  /**
6418  * Creates a function template backed/cached by a private property.
6419  */
6421  Isolate* isolate, FunctionCallback callback,
6422  Local<Private> cache_property, Local<Value> data = Local<Value>(),
6423  Local<Signature> signature = Local<Signature>(), int length = 0,
6424  SideEffectType side_effect_type = SideEffectType::kHasSideEffect);
6425 
6426  /** Returns the unique function instance in the current execution context.*/
6428  Local<Context> context);
6429 
6430  /**
6431  * Similar to Context::NewRemoteContext, this creates an instance that
6432  * isn't backed by an actual object.
6433  *
6434  * The InstanceTemplate of this FunctionTemplate must have access checks with
6435  * handlers installed.
6436  */
6438 
6439  /**
6440  * Set the call-handler callback for a FunctionTemplate. This
6441  * callback is called whenever the function created from this
6442  * FunctionTemplate is called.
6443  */
6444  void SetCallHandler(
6445  FunctionCallback callback, Local<Value> data = Local<Value>(),
6446  SideEffectType side_effect_type = SideEffectType::kHasSideEffect);
6447 
6448  /** Set the predefined length property for the FunctionTemplate. */
6449  void SetLength(int length);
6450 
6451  /** Get the InstanceTemplate. */
6453 
6454  /**
6455  * Causes the function template to inherit from a parent function template.
6456  * This means the function's prototype.__proto__ is set to the parent
6457  * function's prototype.
6458  **/
6459  void Inherit(Local<FunctionTemplate> parent);
6460 
6461  /**
6462  * A PrototypeTemplate is the template used to create the prototype object
6463  * of the function created by this template.
6464  */
6466 
6467  /**
6468  * A PrototypeProviderTemplate is another function template whose prototype
6469  * property is used for this template. This is mutually exclusive with setting
6470  * a prototype template indirectly by calling PrototypeTemplate() or using
6471  * Inherit().
6472  **/
6473  void SetPrototypeProviderTemplate(Local<FunctionTemplate> prototype_provider);
6474 
6475  /**
6476  * Set the class name of the FunctionTemplate. This is used for
6477  * printing objects created with the function created from the
6478  * FunctionTemplate as its constructor.
6479  */
6480  void SetClassName(Local<String> name);
6481 
6482 
6483  /**
6484  * When set to true, no access check will be performed on the receiver of a
6485  * function call. Currently defaults to true, but this is subject to change.
6486  */
6487  void SetAcceptAnyReceiver(bool value);
6488 
6489  /**
6490  * Sets the ReadOnly flag in the attributes of the 'prototype' property
6491  * of functions created from this FunctionTemplate to true.
6492  */
6493  void ReadOnlyPrototype();
6494 
6495  /**
6496  * Removes the prototype property from functions created from this
6497  * FunctionTemplate.
6498  */
6499  void RemovePrototype();
6500 
6501  /**
6502  * Returns true if the given object is an instance of this function
6503  * template.
6504  */
6505  bool HasInstance(Local<Value> object);
6506 
6507  V8_INLINE static FunctionTemplate* Cast(Data* data);
6508 
6509  private:
6510  FunctionTemplate();
6511 
6512  static void CheckCast(Data* that);
6513  friend class Context;
6514  friend class ObjectTemplate;
6515 };
6516 
6517 /**
6518  * Configuration flags for v8::NamedPropertyHandlerConfiguration or
6519  * v8::IndexedPropertyHandlerConfiguration.
6520  */
6522  /**
6523  * None.
6524  */
6525  kNone = 0,
6526 
6527  /**
6528  * See ALL_CAN_READ above.
6529  */
6530  kAllCanRead = 1,
6531 
6532  /** Will not call into interceptor for properties on the receiver or prototype
6533  * chain, i.e., only call into interceptor for properties that do not exist.
6534  * Currently only valid for named interceptors.
6535  */
6536  kNonMasking = 1 << 1,
6537 
6538  /**
6539  * Will not call into interceptor for symbol lookup. Only meaningful for
6540  * named interceptors.
6541  */
6542  kOnlyInterceptStrings = 1 << 2,
6543 
6544  /**
6545  * The getter, query, enumerator callbacks do not produce side effects.
6546  */
6547  kHasNoSideEffect = 1 << 3,
6548 };
6549 
6559  Local<Value> data = Local<Value>(),
6561  : getter(getter),
6562  setter(setter),
6563  query(query),
6564  deleter(deleter),
6565  enumerator(enumerator),
6566  definer(definer),
6567  descriptor(descriptor),
6568  data(data),
6569  flags(flags) {}
6570 
6572  /** Note: getter is required */
6573  GenericNamedPropertyGetterCallback getter = nullptr,
6574  GenericNamedPropertySetterCallback setter = nullptr,
6575  GenericNamedPropertyQueryCallback query = nullptr,
6576  GenericNamedPropertyDeleterCallback deleter = nullptr,
6577  GenericNamedPropertyEnumeratorCallback enumerator = nullptr,
6578  Local<Value> data = Local<Value>(),
6580  : getter(getter),
6581  setter(setter),
6582  query(query),
6583  deleter(deleter),
6584  enumerator(enumerator),
6585  definer(nullptr),
6586  descriptor(nullptr),
6587  data(data),
6588  flags(flags) {}
6589 
6597  Local<Value> data = Local<Value>(),
6599  : getter(getter),
6600  setter(setter),
6601  query(nullptr),
6602  deleter(deleter),
6603  enumerator(enumerator),
6604  definer(definer),
6605  descriptor(descriptor),
6606  data(data),
6607  flags(flags) {}
6608 
6618 };
6619 
6620 
6629  Local<Value> data = Local<Value>(),
6631  : getter(getter),
6632  setter(setter),
6633  query(query),
6634  deleter(deleter),
6635  enumerator(enumerator),
6636  definer(definer),
6637  descriptor(descriptor),
6638  data(data),
6639  flags(flags) {}
6640 
6642  /** Note: getter is required */
6643  IndexedPropertyGetterCallback getter = nullptr,
6644  IndexedPropertySetterCallback setter = nullptr,
6645  IndexedPropertyQueryCallback query = nullptr,
6646  IndexedPropertyDeleterCallback deleter = nullptr,
6647  IndexedPropertyEnumeratorCallback enumerator = nullptr,
6648  Local<Value> data = Local<Value>(),
6650  : getter(getter),
6651  setter(setter),
6652  query(query),
6653  deleter(deleter),
6654  enumerator(enumerator),
6655  definer(nullptr),
6656  descriptor(nullptr),
6657  data(data),
6658  flags(flags) {}
6659 
6667  Local<Value> data = Local<Value>(),
6669  : getter(getter),
6670  setter(setter),
6671  query(nullptr),
6672  deleter(deleter),
6673  enumerator(enumerator),
6674  definer(definer),
6675  descriptor(descriptor),
6676  data(data),
6677  flags(flags) {}
6678 
6688 };
6689 
6690 
6691 /**
6692  * An ObjectTemplate is used to create objects at runtime.
6693  *
6694  * Properties added to an ObjectTemplate are added to each object
6695  * created from the ObjectTemplate.
6696  */
6698  public:
6699  /** Creates an ObjectTemplate. */
6700  static Local<ObjectTemplate> New(
6701  Isolate* isolate,
6703 
6704  /** Get a template included in the snapshot by index. */
6705  V8_DEPRECATED("Use v8::Isolate::GetDataFromSnapshotOnce instead")
6706  static MaybeLocal<ObjectTemplate> FromSnapshot(Isolate* isolate,
6707  size_t index);
6708 
6709  /** Creates a new instance of this template.*/
6711 
6712  /**
6713  * Sets an accessor on the object template.
6714  *
6715  * Whenever the property with the given name is accessed on objects
6716  * created from this ObjectTemplate the getter and setter callbacks
6717  * are called instead of getting and setting the property directly
6718  * on the JavaScript object.
6719  *
6720  * \param name The name of the property for which an accessor is added.
6721  * \param getter The callback to invoke when getting the property.
6722  * \param setter The callback to invoke when setting the property.
6723  * \param data A piece of data that will be passed to the getter and setter
6724  * callbacks whenever they are invoked.
6725  * \param settings Access control settings for the accessor. This is a bit
6726  * field consisting of one of more of
6727  * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
6728  * The default is to not allow cross-context access.
6729  * ALL_CAN_READ means that all cross-context reads are allowed.
6730  * ALL_CAN_WRITE means that all cross-context writes are allowed.
6731  * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
6732  * cross-context access.
6733  * \param attribute The attributes of the property for which an accessor
6734  * is added.
6735  * \param signature The signature describes valid receivers for the accessor
6736  * and is used to perform implicit instance checks against them. If the
6737  * receiver is incompatible (i.e. is not an instance of the constructor as
6738  * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
6739  * thrown and no callback is invoked.
6740  */
6741  void SetAccessor(
6742  Local<String> name, AccessorGetterCallback getter,
6743  AccessorSetterCallback setter = nullptr,
6744  Local<Value> data = Local<Value>(), AccessControl settings = DEFAULT,
6745  PropertyAttribute attribute = None,
6747  SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
6748  SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
6749  void SetAccessor(
6750  Local<Name> name, AccessorNameGetterCallback getter,
6751  AccessorNameSetterCallback setter = nullptr,
6752  Local<Value> data = Local<Value>(), AccessControl settings = DEFAULT,
6753  PropertyAttribute attribute = None,
6755  SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
6756  SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
6757 
6758  /**
6759  * Sets a named property handler on the object template.
6760  *
6761  * Whenever a property whose name is a string or a symbol is accessed on
6762  * objects created from this object template, the provided callback is
6763  * invoked instead of accessing the property directly on the JavaScript
6764  * object.
6765  *
6766  * @param configuration The NamedPropertyHandlerConfiguration that defines the
6767  * callbacks to invoke when accessing a property.
6768  */
6769  void SetHandler(const NamedPropertyHandlerConfiguration& configuration);
6770 
6771  /**
6772  * Sets an indexed property handler on the object template.
6773  *
6774  * Whenever an indexed property is accessed on objects created from
6775  * this object template, the provided callback is invoked instead of
6776  * accessing the property directly on the JavaScript object.
6777  *
6778  * \param getter The callback to invoke when getting a property.
6779  * \param setter The callback to invoke when setting a property.
6780  * \param query The callback to invoke to check if an object has a property.
6781  * \param deleter The callback to invoke when deleting a property.
6782  * \param enumerator The callback to invoke to enumerate all the indexed
6783  * properties of an object.
6784  * \param data A piece of data that will be passed to the callbacks
6785  * whenever they are invoked.
6786  */
6787  // TODO(dcarney): deprecate
6790  IndexedPropertySetterCallback setter = nullptr,
6791  IndexedPropertyQueryCallback query = nullptr,
6792  IndexedPropertyDeleterCallback deleter = nullptr,
6793  IndexedPropertyEnumeratorCallback enumerator = nullptr,
6794  Local<Value> data = Local<Value>()) {
6796  deleter, enumerator, data));
6797  }
6798 
6799  /**
6800  * Sets an indexed property handler on the object template.
6801  *
6802  * Whenever an indexed property is accessed on objects created from
6803  * this object template, the provided callback is invoked instead of
6804  * accessing the property directly on the JavaScript object.
6805  *
6806  * @param configuration The IndexedPropertyHandlerConfiguration that defines
6807  * the callbacks to invoke when accessing a property.
6808  */
6809  void SetHandler(const IndexedPropertyHandlerConfiguration& configuration);
6810 
6811  /**
6812  * Sets the callback to be used when calling instances created from
6813  * this template as a function. If no callback is set, instances
6814  * behave like normal JavaScript objects that cannot be called as a
6815  * function.
6816  */
6818  Local<Value> data = Local<Value>());
6819 
6820  /**
6821  * Mark object instances of the template as undetectable.
6822  *
6823  * In many ways, undetectable objects behave as though they are not
6824  * there. They behave like 'undefined' in conditionals and when
6825  * printed. However, properties can be accessed and called as on
6826  * normal objects.
6827  */
6828  void MarkAsUndetectable();
6829 
6830  /**
6831  * Sets access check callback on the object template and enables access
6832  * checks.
6833  *
6834  * When accessing properties on instances of this object template,
6835  * the access check callback will be called to determine whether or
6836  * not to allow cross-context access to the properties.
6837  */
6839  Local<Value> data = Local<Value>());
6840 
6841  /**
6842  * Like SetAccessCheckCallback but invokes an interceptor on failed access
6843  * checks instead of looking up all-can-read properties. You can only use
6844  * either this method or SetAccessCheckCallback, but not both at the same
6845  * time.
6846  */
6848  AccessCheckCallback callback,
6849  const NamedPropertyHandlerConfiguration& named_handler,
6850  const IndexedPropertyHandlerConfiguration& indexed_handler,
6851  Local<Value> data = Local<Value>());
6852 
6853  /**
6854  * Gets the number of internal fields for objects generated from
6855  * this template.
6856  */
6857  int InternalFieldCount();
6858 
6859  /**
6860  * Sets the number of internal fields for objects generated from
6861  * this template.
6862  */
6863  void SetInternalFieldCount(int value);
6864 
6865  /**
6866  * Returns true if the object will be an immutable prototype exotic object.
6867  */
6868  bool IsImmutableProto();
6869 
6870  /**
6871  * Makes the ObjectTemplate for an immutable prototype exotic object, with an
6872  * immutable __proto__.
6873  */
6874  void SetImmutableProto();
6875 
6876  V8_INLINE static ObjectTemplate* Cast(Data* data);
6877 
6878  private:
6879  ObjectTemplate();
6880  static Local<ObjectTemplate> New(internal::Isolate* isolate,
6881  Local<FunctionTemplate> constructor);
6882  static void CheckCast(Data* that);
6883  friend class FunctionTemplate;
6884 };
6885 
6886 /**
6887  * A Signature specifies which receiver is valid for a function.
6888  *
6889  * A receiver matches a given signature if the receiver (or any of its
6890  * hidden prototypes) was created from the signature's FunctionTemplate, or
6891  * from a FunctionTemplate that inherits directly or indirectly from the
6892  * signature's FunctionTemplate.
6893  */
6894 class V8_EXPORT Signature : public Data {
6895  public:
6896  static Local<Signature> New(
6897  Isolate* isolate,
6899 
6900  V8_INLINE static Signature* Cast(Data* data);
6901 
6902  private:
6903  Signature();
6904 
6905  static void CheckCast(Data* that);
6906 };
6907 
6908 
6909 /**
6910  * An AccessorSignature specifies which receivers are valid parameters
6911  * to an accessor callback.
6912  */
6914  public:
6915  static Local<AccessorSignature> New(
6916  Isolate* isolate,
6918 
6919  V8_INLINE static AccessorSignature* Cast(Data* data);
6920 
6921  private:
6922  AccessorSignature();
6923 
6924  static void CheckCast(Data* that);
6925 };
6926 
6927 
6928 // --- Extensions ---
6929 
6930 /**
6931  * Ignore
6932  */
6933 class V8_EXPORT Extension { // NOLINT
6934  public:
6935  // Note that the strings passed into this constructor must live as long
6936  // as the Extension itself.
6937  Extension(const char* name, const char* source = nullptr, int dep_count = 0,
6938  const char** deps = nullptr, int source_length = -1);
6939  virtual ~Extension() { delete source_; }
6941  Isolate* isolate, Local<String> name) {
6943  }
6944 
6945  const char* name() const { return name_; }
6946  size_t source_length() const { return source_length_; }
6948  return source_;
6949  }
6950  int dependency_count() const { return dep_count_; }
6951  const char** dependencies() const { return deps_; }
6952  void set_auto_enable(bool value) { auto_enable_ = value; }
6953  bool auto_enable() { return auto_enable_; }
6954 
6955  // Disallow copying and assigning.
6956  Extension(const Extension&) = delete;
6957  void operator=(const Extension&) = delete;
6958 
6959  private:
6960  const char* name_;
6961  size_t source_length_; // expected to initialize before source_
6963  int dep_count_;
6964  const char** deps_;
6965  bool auto_enable_;
6966 };
6967 
6968 void V8_EXPORT RegisterExtension(std::unique_ptr<Extension>);
6969 
6970 // --- Statics ---
6971 
6973 V8_INLINE Local<Primitive> Null(Isolate* isolate);
6974 V8_INLINE Local<Boolean> True(Isolate* isolate);
6975 V8_INLINE Local<Boolean> False(Isolate* isolate);
6976 
6977 /**
6978  * A set of constraints that specifies the limits of the runtime's memory use.
6979  * You must set the heap size before initializing the VM - the size cannot be
6980  * adjusted after the VM is initialized.
6981  *
6982  * If you are using threads then you should hold the V8::Locker lock while
6983  * setting the stack limit and you must set a non-default stack limit separately
6984  * for each thread.
6985  *
6986  * The arguments for set_max_semi_space_size, set_max_old_space_size,
6987  * set_max_executable_size, set_code_range_size specify limits in MB.
6988  *
6989  * The argument for set_max_semi_space_size_in_kb is in KB.
6990  */
6992  public:
6993  /**
6994  * Configures the constraints with reasonable default values based on the
6995  * provided heap size limit. The heap size includes both the young and
6996  * the old generation.
6997  *
6998  * \param initial_heap_size_in_bytes The initial heap size or zero.
6999  * By default V8 starts with a small heap and dynamically grows it to
7000  * match the set of live objects. This may lead to ineffective
7001  * garbage collections at startup if the live set is large.
7002  * Setting the initial heap size avoids such garbage collections.
7003  * Note that this does not affect young generation garbage collections.
7004  *
7005  * \param maximum_heap_size_in_bytes The hard limit for the heap size.
7006  * When the heap size approaches this limit, V8 will perform series of
7007  * garbage collections and invoke the NearHeapLimitCallback. If the garbage
7008  * collections do not help and the callback does not increase the limit,
7009  * then V8 will crash with V8::FatalProcessOutOfMemory.
7010  */
7011  void ConfigureDefaultsFromHeapSize(size_t initial_heap_size_in_bytes,
7012  size_t maximum_heap_size_in_bytes);
7013 
7014  /**
7015  * Configures the constraints with reasonable default values based on the
7016  * capabilities of the current device the VM is running on.
7017  *
7018  * \param physical_memory The total amount of physical memory on the current
7019  * device, in bytes.
7020  * \param virtual_memory_limit The amount of virtual memory on the current
7021  * device, in bytes, or zero, if there is no limit.
7022  */
7023  void ConfigureDefaults(uint64_t physical_memory,
7024  uint64_t virtual_memory_limit);
7025 
7026  /**
7027  * The address beyond which the VM's stack may not grow.
7028  */
7029  uint32_t* stack_limit() const { return stack_limit_; }
7030  void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
7031 
7032  /**
7033  * The amount of virtual memory reserved for generated code. This is relevant
7034  * for 64-bit architectures that rely on code range for calls in code.
7035  */
7036  size_t code_range_size_in_bytes() const { return code_range_size_; }
7037  void set_code_range_size_in_bytes(size_t limit) { code_range_size_ = limit; }
7038 
7039  /**
7040  * The maximum size of the old generation.
7041  * When the old generation approaches this limit, V8 will perform series of
7042  * garbage collections and invoke the NearHeapLimitCallback.
7043  * If the garbage collections do not help and the callback does not
7044  * increase the limit, then V8 will crash with V8::FatalProcessOutOfMemory.
7045  */
7047  return max_old_generation_size_;
7048  }
7050  max_old_generation_size_ = limit;
7051  }
7052 
7053  /**
7054  * The maximum size of the young generation, which consists of two semi-spaces
7055  * and a large object space. This affects frequency of Scavenge garbage
7056  * collections and should be typically much smaller that the old generation.
7057  */
7059  return max_young_generation_size_;
7060  }
7062  max_young_generation_size_ = limit;
7063  }
7064 
7066  return initial_old_generation_size_;
7067  }
7068  void set_initial_old_generation_size_in_bytes(size_t initial_size) {
7069  initial_old_generation_size_ = initial_size;
7070  }
7071 
7073  return initial_young_generation_size_;
7074  }
7076  initial_young_generation_size_ = initial_size;
7077  }
7078 
7079  /**
7080  * Deprecated functions. Do not use in new code.
7081  */
7082  V8_DEPRECATE_SOON("Use code_range_size_in_bytes.")
7083  size_t code_range_size() const { return code_range_size_ / kMB; }
7084  V8_DEPRECATE_SOON("Use set_code_range_size_in_bytes.")
7085  void set_code_range_size(size_t limit_in_mb) {
7086  code_range_size_ = limit_in_mb * kMB;
7087  }
7088  V8_DEPRECATE_SOON("Use max_young_generation_size_in_bytes.")
7089  size_t max_semi_space_size_in_kb() const;
7090  V8_DEPRECATE_SOON("Use set_max_young_generation_size_in_bytes.")
7091  void set_max_semi_space_size_in_kb(size_t limit_in_kb);
7092  V8_DEPRECATE_SOON("Use max_old_generation_size_in_bytes.")
7093  size_t max_old_space_size() const { return max_old_generation_size_ / kMB; }
7094  V8_DEPRECATE_SOON("Use set_max_old_generation_size_in_bytes.")
7095  void set_max_old_space_size(size_t limit_in_mb) {
7096  max_old_generation_size_ = limit_in_mb * kMB;
7097  }
7098  V8_DEPRECATE_SOON("Zone does not pool memory any more.")
7099  size_t max_zone_pool_size() const { return max_zone_pool_size_; }
7100  V8_DEPRECATE_SOON("Zone does not pool memory any more.")
7101  void set_max_zone_pool_size(size_t bytes) { max_zone_pool_size_ = bytes; }
7102 
7103  private:
7104  static constexpr size_t kMB = 1048576u;
7105  size_t code_range_size_ = 0;
7106  size_t max_old_generation_size_ = 0;
7107  size_t max_young_generation_size_ = 0;
7108  size_t max_zone_pool_size_ = 0;
7109  size_t initial_old_generation_size_ = 0;
7110  size_t initial_young_generation_size_ = 0;
7111  uint32_t* stack_limit_ = nullptr;
7112 };
7113 
7114 
7115 // --- Exceptions ---
7116 
7117 
7118 typedef void (*FatalErrorCallback)(const char* location, const char* message);
7119 
7120 typedef void (*OOMErrorCallback)(const char* location, bool is_heap_oom);
7121 
7122 typedef void (*DcheckErrorCallback)(const char* file, int line,
7123  const char* message);
7124 
7125 typedef void (*MessageCallback)(Local<Message> message, Local<Value> data);
7126 
7127 // --- Tracing ---
7128 
7129 typedef void (*LogEventCallback)(const char* name, int event);
7130 
7131 /**
7132  * Create new error objects by calling the corresponding error object
7133  * constructor with the message.
7134  */
7136  public:
7137  static Local<Value> RangeError(Local<String> message);
7138  static Local<Value> ReferenceError(Local<String> message);
7139  static Local<Value> SyntaxError(Local<String> message);
7140  static Local<Value> TypeError(Local<String> message);
7141  static Local<Value> Error(Local<String> message);
7142 
7143  /**
7144  * Creates an error message for the given exception.
7145  * Will try to reconstruct the original stack trace from the exception value,
7146  * or capture the current stack trace if not available.
7147  */
7148  static Local<Message> CreateMessage(Isolate* isolate, Local<Value> exception);
7149 
7150  /**
7151  * Returns the original stack trace that was captured at the creation time
7152  * of a given exception, or an empty handle if not available.
7153  */
7154  static Local<StackTrace> GetStackTrace(Local<Value> exception);
7155 };
7156 
7157 
7158 // --- Counters Callbacks ---
7159 
7160 typedef int* (*CounterLookupCallback)(const char* name);
7161 
7162 typedef void* (*CreateHistogramCallback)(const char* name,
7163  int min,
7164  int max,
7165  size_t buckets);
7166 
7167 typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
7168 
7169 // --- Crashkeys Callback ---
7170 enum class CrashKeyId {
7175  kDumpType,
7176 };
7177 
7178 typedef void (*AddCrashKeyCallback)(CrashKeyId id, const std::string& value);
7179 
7180 // --- Enter/Leave Script Callback ---
7182 typedef void (*CallCompletedCallback)(Isolate*);
7183 
7184 /**
7185  * HostCleanupFinalizationGroupCallback is called when we require the
7186  * embedder to enqueue a task that would call
7187  * FinalizationGroup::Cleanup().
7188  *
7189  * The FinalizationGroup is the one for which the embedder needs to
7190  * call FinalizationGroup::Cleanup() on.
7191  *
7192  * The context provided is the one in which the FinalizationGroup was
7193  * created in.
7194  */
7196  Local<Context> context, Local<FinalizationGroup> fg);
7197 
7198 /**
7199  * HostImportModuleDynamicallyCallback is called when we require the
7200  * embedder to load a module. This is used as part of the dynamic
7201  * import syntax.
7202  *
7203  * The referrer contains metadata about the script/module that calls
7204  * import.
7205  *
7206  * The specifier is the name of the module that should be imported.
7207  *
7208  * The embedder must compile, instantiate, evaluate the Module, and
7209  * obtain it's namespace object.
7210  *
7211  * The Promise returned from this function is forwarded to userland
7212  * JavaScript. The embedder must resolve this promise with the module
7213  * namespace object. In case of an exception, the embedder must reject
7214  * this promise with the exception. If the promise creation itself
7215  * fails (e.g. due to stack overflow), the embedder must propagate
7216  * that exception by returning an empty MaybeLocal.
7217  */
7219  Local<Context> context, Local<ScriptOrModule> referrer,
7220  Local<String> specifier);
7221 
7222 /**
7223  * HostInitializeImportMetaObjectCallback is called the first time import.meta
7224  * is accessed for a module. Subsequent access will reuse the same value.
7225  *
7226  * The method combines two implementation-defined abstract operations into one:
7227  * HostGetImportMetaProperties and HostFinalizeImportMeta.
7228  *
7229  * The embedder should use v8::Object::CreateDataProperty to add properties on
7230  * the meta object.
7231  */
7233  Local<Module> module,
7234  Local<Object> meta);
7235 
7236 /**
7237  * PrepareStackTraceCallback is called when the stack property of an error is
7238  * first accessed. The return value will be used as the stack value. If this
7239  * callback is registed, the |Error.prepareStackTrace| API will be disabled.
7240  * |sites| is an array of call sites, specified in
7241  * https://v8.dev/docs/stack-trace-api
7242  */
7244  Local<Value> error,
7245  Local<Array> sites);
7246 
7247 /**
7248  * PromiseHook with type kInit is called when a new promise is
7249  * created. When a new promise is created as part of the chain in the
7250  * case of Promise.then or in the intermediate promises created by
7251  * Promise.{race, all}/AsyncFunctionAwait, we pass the parent promise
7252  * otherwise we pass undefined.
7253  *
7254  * PromiseHook with type kResolve is called at the beginning of
7255  * resolve or reject function defined by CreateResolvingFunctions.
7256  *
7257  * PromiseHook with type kBefore is called at the beginning of the
7258  * PromiseReactionJob.
7259  *
7260  * PromiseHook with type kAfter is called right at the end of the
7261  * PromiseReactionJob.
7262  */
7264 
7265 typedef void (*PromiseHook)(PromiseHookType type, Local<Promise> promise,
7266  Local<Value> parent);
7267 
7268 // --- Promise Reject Callback ---
7274 };
7275 
7277  public:
7279  Local<Value> value)
7280  : promise_(promise), event_(event), value_(value) {}
7281 
7282  V8_INLINE Local<Promise> GetPromise() const { return promise_; }
7283  V8_INLINE PromiseRejectEvent GetEvent() const { return event_; }
7284  V8_INLINE Local<Value> GetValue() const { return value_; }
7285 
7286  private:
7287  Local<Promise> promise_;
7288  PromiseRejectEvent event_;
7289  Local<Value> value_;
7290 };
7291 
7293 
7294 // --- Microtasks Callbacks ---
7295 V8_DEPRECATE_SOON("Use *WithData version.")
7298 typedef void (*MicrotaskCallback)(void* data);
7299 
7300 
7301 /**
7302  * Policy for running microtasks:
7303  * - explicit: microtasks are invoked with Isolate::RunMicrotasks() method;
7304  * - scoped: microtasks invocation is controlled by MicrotasksScope objects;
7305  * - auto: microtasks are invoked when the script call depth decrements
7306  * to zero.
7307  */
7309 
7310 /**
7311  * Represents the microtask queue, where microtasks are stored and processed.
7312  * https://html.spec.whatwg.org/multipage/webappapis.html#microtask-queue
7313  * https://html.spec.whatwg.org/multipage/webappapis.html#enqueuejob(queuename,-job,-arguments)
7314  * https://html.spec.whatwg.org/multipage/webappapis.html#perform-a-microtask-checkpoint
7315  *
7316  * A MicrotaskQueue instance may be associated to multiple Contexts by passing
7317  * it to Context::New(), and they can be detached by Context::DetachGlobal().
7318  * The embedder must keep the MicrotaskQueue instance alive until all associated
7319  * Contexts are gone or detached.
7320  *
7321  * Use the same instance of MicrotaskQueue for all Contexts that may access each
7322  * other synchronously. E.g. for Web embedding, use the same instance for all
7323  * origins that share the same URL scheme and eTLD+1.
7324  */
7326  public:
7327  /**
7328  * Creates an empty MicrotaskQueue instance.
7329  */
7330  static std::unique_ptr<MicrotaskQueue> New(
7331  Isolate* isolate, MicrotasksPolicy policy = MicrotasksPolicy::kAuto);
7332 
7333  virtual ~MicrotaskQueue() = default;
7334 
7335  /**
7336  * Enqueues the callback to the queue.
7337  */
7338  virtual void EnqueueMicrotask(Isolate* isolate,
7339  Local<Function> microtask) = 0;
7340 
7341  /**
7342  * Enqueues the callback to the queue.
7343  */
7344  virtual void EnqueueMicrotask(v8::Isolate* isolate,
7345  MicrotaskCallback callback,
7346  void* data = nullptr) = 0;
7347 
7348  /**
7349  * Adds a callback to notify the embedder after microtasks were run. The
7350  * callback is triggered by explicit RunMicrotasks call or automatic
7351  * microtasks execution (see Isolate::SetMicrotasksPolicy).
7352  *
7353  * Callback will trigger even if microtasks were attempted to run,
7354  * but the microtasks queue was empty and no single microtask was actually
7355  * executed.
7356  *
7357  * Executing scripts inside the callback will not re-trigger microtasks and
7358  * the callback.
7359  */
7360  virtual void AddMicrotasksCompletedCallback(
7361  MicrotasksCompletedCallbackWithData callback, void* data = nullptr) = 0;
7362 
7363  /**
7364  * Removes callback that was installed by AddMicrotasksCompletedCallback.
7365  */
7366  virtual void RemoveMicrotasksCompletedCallback(
7367  MicrotasksCompletedCallbackWithData callback, void* data = nullptr) = 0;
7368 
7369  /**
7370  * Runs microtasks if no microtask is running on this MicrotaskQueue instance.
7371  */
7372  virtual void PerformCheckpoint(Isolate* isolate) = 0;
7373 
7374  /**
7375  * Returns true if a microtask is running on this MicrotaskQueue instance.
7376  */
7377  virtual bool IsRunningMicrotasks() const = 0;
7378 
7379  /**
7380  * Returns the current depth of nested MicrotasksScope that has
7381  * kRunMicrotasks.
7382  */
7383  virtual int GetMicrotasksScopeDepth() const = 0;
7384 
7385  MicrotaskQueue(const MicrotaskQueue&) = delete;
7386  MicrotaskQueue& operator=(const MicrotaskQueue&) = delete;
7387 
7388  private:
7389  friend class internal::MicrotaskQueue;
7390  MicrotaskQueue() = default;
7391 };
7392 
7393 /**
7394  * This scope is used to control microtasks when kScopeMicrotasksInvocation
7395  * is used on Isolate. In this mode every non-primitive call to V8 should be
7396  * done inside some MicrotasksScope.
7397  * Microtasks are executed when topmost MicrotasksScope marked as kRunMicrotasks
7398  * exits.
7399  * kDoNotRunMicrotasks should be used to annotate calls not intended to trigger
7400  * microtasks.
7401  */
7403  public:
7405 
7406  MicrotasksScope(Isolate* isolate, Type type);
7407  MicrotasksScope(Isolate* isolate, MicrotaskQueue* microtask_queue, Type type);
7408  ~MicrotasksScope();
7409 
7410  /**
7411  * Runs microtasks if no kRunMicrotasks scope is currently active.
7412  */
7413  static void PerformCheckpoint(Isolate* isolate);
7414 
7415  /**
7416  * Returns current depth of nested kRunMicrotasks scopes.
7417  */
7418  static int GetCurrentDepth(Isolate* isolate);
7419 
7420  /**
7421  * Returns true while microtasks are being executed.
7422  */
7423  static bool IsRunningMicrotasks(Isolate* isolate);
7424 
7425  // Prevent copying.
7426  MicrotasksScope(const MicrotasksScope&) = delete;
7427  MicrotasksScope& operator=(const MicrotasksScope&) = delete;
7428 
7429  private:
7430  internal::Isolate* const isolate_;
7431  internal::MicrotaskQueue* const microtask_queue_;
7432  bool run_;
7433 };
7434 
7435 
7436 // --- Failed Access Check Callback ---
7437 typedef void (*FailedAccessCheckCallback)(Local<Object> target,
7438  AccessType type,
7439  Local<Value> data);
7440 
7441 // --- AllowCodeGenerationFromStrings callbacks ---
7442 
7443 /**
7444  * Callback to check if code generation from strings is allowed. See
7445  * Context::AllowCodeGenerationFromStrings.
7446  */
7448  Local<String> source);
7449 
7451  // If true, proceed with the codegen algorithm. Otherwise, block it.
7452  bool codegen_allowed = false;
7453  // Overwrite the original source with this string, if present.
7454  // Use the original source if empty.
7455  // This field is considered only if codegen_allowed is true.
7457 };
7458 
7459 /**
7460  * Callback to check if codegen is allowed from a source object, and convert
7461  * the source to string if necessary.See ModifyCodeGenerationFromStrings.
7462  */
7464  *ModifyCodeGenerationFromStringsCallback)(Local<Context> context,
7465  Local<Value> source);
7466 
7467 // --- WebAssembly compilation callbacks ---
7469 
7471  Local<String> source);
7472 
7473 // --- Callback for APIs defined on v8-supported objects, but implemented
7474 // by the embedder. Example: WebAssembly.{compile|instantiate}Streaming ---
7476 
7477 // --- Callback for WebAssembly.compileStreaming ---
7479 
7480 // --- Callback for checking if WebAssembly threads are enabled ---
7481 typedef bool (*WasmThreadsEnabledCallback)(Local<Context> context);
7482 
7483 // --- Callback for loading source map file for WASM profiling support
7485  const char* name);
7486 
7487 // --- Garbage Collection Callbacks ---
7488 
7489 /**
7490  * Applications can register callback functions which will be called before and
7491  * after certain garbage collection operations. Allocations are not allowed in
7492  * the callback functions, you therefore cannot manipulate objects (set or
7493  * delete properties for example) since it is possible such operations will
7494  * result in the allocation of objects.
7495  */
7496 enum GCType {
7503 };
7504 
7505 /**
7506  * GCCallbackFlags is used to notify additional information about the GC
7507  * callback.
7508  * - kGCCallbackFlagConstructRetainedObjectInfos: The GC callback is for
7509  * constructing retained object infos.
7510  * - kGCCallbackFlagForced: The GC callback is for a forced GC for testing.
7511  * - kGCCallbackFlagSynchronousPhantomCallbackProcessing: The GC callback
7512  * is called synchronously without getting posted to an idle task.
7513  * - kGCCallbackFlagCollectAllAvailableGarbage: The GC callback is called
7514  * in a phase where V8 is trying to collect all available garbage
7515  * (e.g., handling a low memory notification).
7516  * - kGCCallbackScheduleIdleGarbageCollection: The GC callback is called to
7517  * trigger an idle garbage collection.
7518  */
7527 };
7528 
7529 typedef void (*GCCallback)(GCType type, GCCallbackFlags flags);
7530 
7531 typedef void (*InterruptCallback)(Isolate* isolate, void* data);
7532 
7533 /**
7534  * This callback is invoked when the heap size is close to the heap limit and
7535  * V8 is likely to abort with out-of-memory error.
7536  * The callback can extend the heap limit by returning a value that is greater
7537  * than the current_heap_limit. The initial heap limit is the limit that was
7538  * set after heap setup.
7539  */
7540 typedef size_t (*NearHeapLimitCallback)(void* data, size_t current_heap_limit,
7541  size_t initial_heap_limit);
7542 
7543 /**
7544  * Collection of shared per-process V8 memory information.
7545  *
7546  * Instances of this class can be passed to
7547  * v8::V8::GetSharedMemoryStatistics to get shared memory statistics from V8.
7548  */
7550  public:
7552  size_t read_only_space_size() { return read_only_space_size_; }
7553  size_t read_only_space_used_size() { return read_only_space_used_size_; }
7555  return read_only_space_physical_size_;
7556  }
7557 
7558  private:
7559  size_t read_only_space_size_;
7560  size_t read_only_space_used_size_;
7561  size_t read_only_space_physical_size_;
7562 
7563  friend class V8;
7564 };
7565 
7566 /**
7567  * Collection of V8 heap information.
7568  *
7569  * Instances of this class can be passed to v8::Isolate::GetHeapStatistics to
7570  * get heap statistics from V8.
7571  */
7573  public:
7574  HeapStatistics();
7575  size_t total_heap_size() { return total_heap_size_; }
7576  size_t total_heap_size_executable() { return total_heap_size_executable_; }
7577  size_t total_physical_size() { return total_physical_size_; }
7578  size_t total_available_size() { return total_available_size_; }
7579  size_t used_heap_size() { return used_heap_size_; }
7580  size_t heap_size_limit() { return heap_size_limit_; }
7581  size_t malloced_memory() { return malloced_memory_; }
7582  size_t external_memory() { return external_memory_; }
7583  size_t peak_malloced_memory() { return peak_malloced_memory_; }
7584  size_t number_of_native_contexts() { return number_of_native_contexts_; }
7585  size_t number_of_detached_contexts() { return number_of_detached_contexts_; }
7586 
7587  /**
7588  * Returns a 0/1 boolean, which signifies whether the V8 overwrite heap
7589  * garbage with a bit pattern.
7590  */
7591  size_t does_zap_garbage() { return does_zap_garbage_; }
7592 
7593  private:
7594  size_t total_heap_size_;
7595  size_t total_heap_size_executable_;
7596  size_t total_physical_size_;
7597  size_t total_available_size_;
7598  size_t used_heap_size_;
7599  size_t heap_size_limit_;
7600  size_t malloced_memory_;
7601  size_t external_memory_;
7602  size_t peak_malloced_memory_;
7603  bool does_zap_garbage_;
7604  size_t number_of_native_contexts_;
7605  size_t number_of_detached_contexts_;
7606 
7607  friend class V8;
7608  friend class Isolate;
7609 };
7610 
7611 
7613  public:
7615  const char* space_name() { return space_name_; }
7616  size_t space_size() { return space_size_; }
7617  size_t space_used_size() { return space_used_size_; }
7618  size_t space_available_size() { return space_available_size_; }
7619  size_t physical_space_size() { return physical_space_size_; }
7620 
7621  private:
7622  const char* space_name_;
7623  size_t space_size_;
7624  size_t space_used_size_;
7625  size_t space_available_size_;
7626  size_t physical_space_size_;
7627 
7628  friend class Isolate;
7629 };
7630 
7631 
7633  public:
7635  const char* object_type() { return object_type_; }
7636  const char* object_sub_type() { return object_sub_type_; }
7637  size_t object_count() { return object_count_; }
7638  size_t object_size() { return object_size_; }
7639 
7640  private:
7641  const char* object_type_;
7642  const char* object_sub_type_;
7643  size_t object_count_;
7644  size_t object_size_;
7645 
7646  friend class Isolate;
7647 };
7648 
7650  public:
7652  size_t code_and_metadata_size() { return code_and_metadata_size_; }
7653  size_t bytecode_and_metadata_size() { return bytecode_and_metadata_size_; }
7654  size_t external_script_source_size() { return external_script_source_size_; }
7655 
7656  private:
7657  size_t code_and_metadata_size_;
7658  size_t bytecode_and_metadata_size_;
7659  size_t external_script_source_size_;
7660 
7661  friend class Isolate;
7662 };
7663 
7664 /**
7665  * A JIT code event is issued each time code is added, moved or removed.
7666  *
7667  * \note removal events are not currently issued.
7668  */
7670  enum EventType {
7677  };
7678  // Definition of the code position type. The "POSITION" type means the place
7679  // in the source code which are of interest when making stack traces to
7680  // pin-point the source location of a stack frame as close as possible.
7681  // The "STATEMENT_POSITION" means the place at the beginning of each
7682  // statement, and is used to indicate possible break locations.
7684 
7685  // There are two different kinds of JitCodeEvents, one for JIT code generated
7686  // by the optimizing compiler, and one for byte code generated for the
7687  // interpreter. For JIT_CODE events, the |code_start| member of the event
7688  // points to the beginning of jitted assembly code, while for BYTE_CODE
7689  // events, |code_start| points to the first bytecode of the interpreted
7690  // function.
7692 
7693  // Type of event.
7696  // Start of the instructions.
7697  void* code_start;
7698  // Size of the instructions.
7699  size_t code_len;
7700  // Script info for CODE_ADDED event.
7702  // User-defined data for *_LINE_INFO_* event. It's used to hold the source
7703  // code line information which is returned from the
7704  // CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent
7705  // CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events.
7706  void* user_data;
7707 
7708  struct name_t {
7709  // Name of the object associated with the code, note that the string is not
7710  // zero-terminated.
7711  const char* str;
7712  // Number of chars in str.
7713  size_t len;
7714  };
7715 
7716  struct line_info_t {
7717  // PC offset
7718  size_t offset;
7719  // Code position
7720  size_t pos;
7721  // The position type.
7723  };
7724 
7726  // Source file name.
7727  const char* filename;
7728  // Length of filename.
7730  // Line number table, which maps offsets of JITted code to line numbers of
7731  // source file.
7733  // Number of entries in the line number table.
7735  };
7736 
7738 
7739  union {
7740  // Only valid for CODE_ADDED.
7741  struct name_t name;
7742 
7743  // Only valid for CODE_ADD_LINE_POS_INFO
7744  struct line_info_t line_info;
7745 
7746  // New location of instructions. Only valid for CODE_MOVED.
7747  void* new_code_start;
7748  };
7749 
7751 };
7752 
7753 /**
7754  * Option flags passed to the SetRAILMode function.
7755  * See documentation https://developers.google.com/web/tools/chrome-devtools/
7756  * profile/evaluate-performance/rail
7757  */
7758 enum RAILMode : unsigned {
7759  // Response performance mode: In this mode very low virtual machine latency
7760  // is provided. V8 will try to avoid JavaScript execution interruptions.
7761  // Throughput may be throttled.
7763  // Animation performance mode: In this mode low virtual machine latency is
7764  // provided. V8 will try to avoid as many JavaScript execution interruptions
7765  // as possible. Throughput may be throttled. This is the default mode.
7767  // Idle performance mode: The embedder is idle. V8 can complete deferred work
7768  // in this mode.
7770  // Load performance mode: In this mode high throughput is provided. V8 may
7771  // turn off latency optimizations.
7773 };
7774 
7775 /**
7776  * Option flags passed to the SetJitCodeEventHandler function.
7777  */
7780  // Generate callbacks for already existent code.
7782 };
7783 
7784 
7785 /**
7786  * Callback function passed to SetJitCodeEventHandler.
7787  *
7788  * \param event code add, move or removal event.
7789  */
7790 typedef void (*JitCodeEventHandler)(const JitCodeEvent* event);
7791 
7792 /**
7793  * Callback function passed to SetUnhandledExceptionCallback.
7794  */
7795 #if defined(V8_OS_WIN)
7796 typedef int (*UnhandledExceptionCallback)(
7798 #endif
7799 
7800 /**
7801  * Interface for iterating through all external resources in the heap.
7802  */
7804  public:
7805  virtual ~ExternalResourceVisitor() = default;
7806  virtual void VisitExternalString(Local<String> string) {}
7807 };
7808 
7809 
7810 /**
7811  * Interface for iterating through all the persistent handles in the heap.
7812  */
7814  public:
7815  virtual ~PersistentHandleVisitor() = default;
7817  uint16_t class_id) {}
7818 };
7819 
7820 /**
7821  * Memory pressure level for the MemoryPressureNotification.
7822  * kNone hints V8 that there is no memory pressure.
7823  * kModerate hints V8 to speed up incremental garbage collection at the cost of
7824  * of higher latency due to garbage collection pauses.
7825  * kCritical hints V8 to free memory as soon as possible. Garbage collection
7826  * pauses at this level will be large.
7827  */
7829 
7830 /**
7831  * Interface for tracing through the embedder heap. During a V8 garbage
7832  * collection, V8 collects hidden fields of all potential wrappers, and at the
7833  * end of its marking phase iterates the collection and asks the embedder to
7834  * trace through its heap and use reporter to report each JavaScript object
7835  * reachable from any of the given wrappers.
7836  */
7838  public:
7841  kReduceMemory = 1 << 0,
7842  };
7843 
7844  // Indicator for the stack state of the embedder.
7849  };
7850 
7851  /**
7852  * Interface for iterating through TracedGlobal handles.
7853  */
7855  public:
7856  virtual ~TracedGlobalHandleVisitor() = default;
7857  virtual void VisitTracedGlobalHandle(const TracedGlobal<Value>& handle) {}
7858  virtual void VisitTracedReference(const TracedReference<Value>& handle) {}
7859  };
7860 
7861  /**
7862  * Summary of a garbage collection cycle. See |TraceEpilogue| on how the
7863  * summary is reported.
7864  */
7865  struct TraceSummary {
7866  /**
7867  * Time spent managing the retained memory in milliseconds. This can e.g.
7868  * include the time tracing through objects in the embedder.
7869  */
7870  double time = 0.0;
7871 
7872  /**
7873  * Memory retained by the embedder through the |EmbedderHeapTracer|
7874  * mechanism in bytes.
7875  */
7876  size_t allocated_size = 0;
7877  };
7878 
7879  virtual ~EmbedderHeapTracer() = default;
7880 
7881  /**
7882  * Iterates all TracedGlobal handles created for the v8::Isolate the tracer is
7883  * attached to.
7884  */
7886 
7887  /**
7888  * Called by the embedder to set the start of the stack which is e.g. used by
7889  * V8 to determine whether handles are used from stack or heap.
7890  */
7891  void SetStackStart(void* stack_start);
7892 
7893  /**
7894  * Called by the embedder to notify V8 of an empty execution stack.
7895  */
7896  void NotifyEmptyEmbedderStack();
7897 
7898  /**
7899  * Called by v8 to register internal fields of found wrappers.
7900  *
7901  * The embedder is expected to store them somewhere and trace reachable
7902  * wrappers from them when called through |AdvanceTracing|.
7903  */
7904  virtual void RegisterV8References(
7905  const std::vector<std::pair<void*, void*> >& embedder_fields) = 0;
7906 
7908 
7909  /**
7910  * Called at the beginning of a GC cycle.
7911  */
7912  virtual void TracePrologue(TraceFlags flags) {}
7913 
7914  /**
7915  * Called to advance tracing in the embedder.
7916  *
7917  * The embedder is expected to trace its heap starting from wrappers reported
7918  * by RegisterV8References method, and report back all reachable wrappers.
7919  * Furthermore, the embedder is expected to stop tracing by the given
7920  * deadline. A deadline of infinity means that tracing should be finished.
7921  *
7922  * Returns |true| if tracing is done, and false otherwise.
7923  */
7924  virtual bool AdvanceTracing(double deadline_in_ms) = 0;
7925 
7926  /*
7927  * Returns true if there no more tracing work to be done (see AdvanceTracing)
7928  * and false otherwise.
7929  */
7930  virtual bool IsTracingDone() = 0;
7931 
7932  /**
7933  * Called at the end of a GC cycle.
7934  *
7935  * Note that allocation is *not* allowed within |TraceEpilogue|. Can be
7936  * overriden to fill a |TraceSummary| that is used by V8 to schedule future
7937  * garbage collections.
7938  */
7939  virtual void TraceEpilogue(TraceSummary* trace_summary) {}
7940 
7941  /**
7942  * Called upon entering the final marking pause. No more incremental marking
7943  * steps will follow this call.
7944  */
7945  virtual void EnterFinalPause(EmbedderStackState stack_state) = 0;
7946 
7947  /*
7948  * Called by the embedder to request immediate finalization of the currently
7949  * running tracing phase that has been started with TracePrologue and not
7950  * yet finished with TraceEpilogue.
7951  *
7952  * Will be a noop when currently not in tracing.
7953  *
7954  * This is an experimental feature.
7955  */
7956  void FinalizeTracing();
7957 
7958  /**
7959  * Returns true if the TracedGlobal handle should be considered as root for
7960  * the currently running non-tracing garbage collection and false otherwise.
7961  * The default implementation will keep all TracedGlobal references as roots.
7962  *
7963  * If this returns false, then V8 may decide that the object referred to by
7964  * such a handle is reclaimed. In that case:
7965  * - No action is required if handles are used with destructors, i.e., by just
7966  * using |TracedGlobal|.
7967  * - When run without destructors, i.e., by using
7968  * |TracedReference|, V8 calls |ResetHandleInNonTracingGC|.
7969  *
7970  * Note that the |handle| is different from the handle that the embedder holds
7971  * for retaining the object. The embedder may use |WrapperClassId()| to
7972  * distinguish cases where it wants handles to be treated as roots from not
7973  * being treated as roots.
7974  */
7975  virtual bool IsRootForNonTracingGC(
7976  const v8::TracedReference<v8::Value>& handle);
7977  virtual bool IsRootForNonTracingGC(const v8::TracedGlobal<v8::Value>& handle);
7978 
7979  /**
7980  * Used in combination with |IsRootForNonTracingGC|. Called by V8 when an
7981  * object that is backed by a handle is reclaimed by a non-tracing garbage
7982  * collection. It is up to the embedder to reset the original handle.
7983  *
7984  * Note that the |handle| is different from the handle that the embedder holds
7985  * for retaining the object. It is up to the embedder to find the original
7986  * handle via the object or class id.
7987  */
7988  virtual void ResetHandleInNonTracingGC(
7989  const v8::TracedReference<v8::Value>& handle);
7990 
7991  /*
7992  * Called by the embedder to immediately perform a full garbage collection.
7993  *
7994  * Should only be used in testing code.
7995  */
7997 
7998  /*
7999  * Called by the embedder to signal newly allocated or freed memory. Not bound
8000  * to tracing phases. Embedders should trade off when increments are reported
8001  * as V8 may consult global heuristics on whether to trigger garbage
8002  * collection on this change.
8003  */
8004  void IncreaseAllocatedSize(size_t bytes);
8005  void DecreaseAllocatedSize(size_t bytes);
8006 
8007  /*
8008  * Returns the v8::Isolate this tracer is attached too and |nullptr| if it
8009  * is not attached to any v8::Isolate.
8010  */
8011  v8::Isolate* isolate() const { return isolate_; }
8012 
8013  protected:
8014  v8::Isolate* isolate_ = nullptr;
8015 
8016  friend class internal::LocalEmbedderHeapTracer;
8017 };
8018 
8019 /**
8020  * Callback and supporting data used in SnapshotCreator to implement embedder
8021  * logic to serialize internal fields.
8022  * Internal fields that directly reference V8 objects are serialized without
8023  * calling this callback. Internal fields that contain aligned pointers are
8024  * serialized by this callback if it returns non-zero result. Otherwise it is
8025  * serialized verbatim.
8026  */
8028  typedef StartupData (*CallbackFunction)(Local<Object> holder, int index,
8029  void* data);
8030  SerializeInternalFieldsCallback(CallbackFunction function = nullptr,
8031  void* data_arg = nullptr)
8032  : callback(function), data(data_arg) {}
8033  CallbackFunction callback;
8034  void* data;
8035 };
8036 // Note that these fields are called "internal fields" in the API and called
8037 // "embedder fields" within V8.
8039 
8040 /**
8041  * Callback and supporting data used to implement embedder logic to deserialize
8042  * internal fields.
8043  */
8045  typedef void (*CallbackFunction)(Local<Object> holder, int index,
8046  StartupData payload, void* data);
8048  void* data_arg = nullptr)
8049  : callback(function), data(data_arg) {}
8050  void (*callback)(Local<Object> holder, int index, StartupData payload,
8051  void* data);
8052  void* data;
8053 };
8055 
8056 /**
8057  * Controls how the default MeasureMemoryDelegate reports the result of
8058  * the memory measurement to JS. With kSummary only the total size is reported.
8059  * With kDetailed the result includes the size of each native context.
8060  */
8062 
8063 /**
8064  * Controls how promptly a memory measurement request is executed.
8065  * By default the measurement is folded with the next scheduled GC which may
8066  * happen after a while. The kEager starts increment GC right away and
8067  * is useful for testing.
8068  */
8070 
8071 /**
8072  * The delegate is used in Isolate::MeasureMemory API.
8073  *
8074  * It specifies the contexts that need to be measured and gets called when
8075  * the measurement is completed to report the results.
8076  */
8078  public:
8079  virtual ~MeasureMemoryDelegate() = default;
8080 
8081  /**
8082  * Returns true if the size of the given context needs to be measured.
8083  */
8084  virtual bool ShouldMeasure(Local<Context> context) = 0;
8085 
8086  /**
8087  * This function is called when memory measurement finishes.
8088  *
8089  * \param context_sizes_in_bytes a vector of (context, size) pairs that
8090  * includes each context for which ShouldMeasure returned true and that
8091  * was not garbage collected while the memory measurement was in progress.
8092  *
8093  * \param unattributed_size_in_bytes total size of objects that were not
8094  * attributed to any context (i.e. are likely shared objects).
8095  */
8096  virtual void MeasurementComplete(
8097  const std::vector<std::pair<Local<Context>, size_t>>&
8098  context_sizes_in_bytes,
8099  size_t unattributed_size_in_bytes) = 0;
8100 
8101  /**
8102  * Returns a default delegate that resolves the given promise when
8103  * the memory measurement completes.
8104  *
8105  * \param isolate the current isolate
8106  * \param context the current context
8107  * \param promise_resolver the promise resolver that is given the
8108  * result of the memory measurement.
8109  * \param mode the detail level of the result.
8110  */
8111  static std::unique_ptr<MeasureMemoryDelegate> Default(
8112  Isolate* isolate, Local<Context> context,
8113  Local<Promise::Resolver> promise_resolver, MeasureMemoryMode mode);
8114 };
8115 
8116 /**
8117  * Isolate represents an isolated instance of the V8 engine. V8 isolates have
8118  * completely separate states. Objects from one isolate must not be used in
8119  * other isolates. The embedder can create multiple isolates and use them in
8120  * parallel in multiple threads. An isolate can be entered by at most one
8121  * thread at any given time. The Locker/Unlocker API must be used to
8122  * synchronize.
8123  */
8125  public:
8126  /**
8127  * Initial configuration parameters for a new Isolate.
8128  */
8129  struct CreateParams {
8131  : code_event_handler(nullptr),
8132  snapshot_blob(nullptr),
8133  counter_lookup_callback(nullptr),
8134  create_histogram_callback(nullptr),
8136  array_buffer_allocator(nullptr),
8138  external_references(nullptr),
8139  allow_atomics_wait(true),
8141 
8142  /**
8143  * Allows the host application to provide the address of a function that is
8144  * notified each time code is added, moved or removed.
8145  */
8147 
8148  /**
8149  * ResourceConstraints to use for the new Isolate.
8150  */
8152 
8153  /**
8154  * Explicitly specify a startup snapshot blob. The embedder owns the blob.
8155  */
8157 
8158 
8159  /**
8160  * Enables the host application to provide a mechanism for recording
8161  * statistics counters.
8162  */
8164 
8165  /**
8166  * Enables the host application to provide a mechanism for recording
8167  * histograms. The CreateHistogram function returns a
8168  * histogram which will later be passed to the AddHistogramSample
8169  * function.
8170  */
8173 
8174  /**
8175  * The ArrayBuffer::Allocator to use for allocating and freeing the backing
8176  * store of ArrayBuffers.
8177  *
8178  * If the shared_ptr version is used, the Isolate instance and every
8179  * |BackingStore| allocated using this allocator hold a std::shared_ptr
8180  * to the allocator, in order to facilitate lifetime
8181  * management for the allocator instance.
8182  */
8185 
8186  /**
8187  * Specifies an optional nullptr-terminated array of raw addresses in the
8188  * embedder that V8 can match against during serialization and use for
8189  * deserialization. This array and its content must stay valid for the
8190  * entire lifetime of the isolate.
8191  */
8192  const intptr_t* external_references;
8193 
8194  /**
8195  * Whether calling Atomics.wait (a function that may block) is allowed in
8196  * this isolate. This can also be configured via SetAllowAtomicsWait.
8197  */
8199 
8200  /**
8201  * Termination is postponed when there is no active SafeForTerminationScope.
8202  */
8204  };
8205 
8206 
8207  /**
8208  * Stack-allocated class which sets the isolate for all operations
8209  * executed within a local scope.
8210  */
8212  public:
8213  explicit Scope(Isolate* isolate) : isolate_(isolate) {
8214  isolate->Enter();
8215  }
8216 
8217  ~Scope() { isolate_->Exit(); }
8218 
8219  // Prevent copying of Scope objects.
8220  Scope(const Scope&) = delete;
8221  Scope& operator=(const Scope&) = delete;
8222 
8223  private:
8224  Isolate* const isolate_;
8225  };
8226 
8227 
8228  /**
8229  * Assert that no Javascript code is invoked.
8230  */
8232  public:
8234 
8235  DisallowJavascriptExecutionScope(Isolate* isolate, OnFailure on_failure);
8237 
8238  // Prevent copying of Scope objects.
8240  delete;
8242  const DisallowJavascriptExecutionScope&) = delete;
8243 
8244  private:
8245  OnFailure on_failure_;
8246  void* internal_;
8247  };
8248 
8249 
8250  /**
8251  * Introduce exception to DisallowJavascriptExecutionScope.
8252  */
8254  public:
8255  explicit AllowJavascriptExecutionScope(Isolate* isolate);
8257 
8258  // Prevent copying of Scope objects.
8260  delete;
8262  const AllowJavascriptExecutionScope&) = delete;
8263 
8264  private:
8265  void* internal_throws_;
8266  void* internal_assert_;
8267  void* internal_dump_;
8268  };
8269 
8270  /**
8271  * Do not run microtasks while this scope is active, even if microtasks are
8272  * automatically executed otherwise.
8273  */
8275  public:
8277  Isolate* isolate, MicrotaskQueue* microtask_queue = nullptr);
8279 
8280  // Prevent copying of Scope objects.
8282  delete;
8284  const SuppressMicrotaskExecutionScope&) = delete;
8285 
8286  private:
8287  internal::Isolate* const isolate_;
8288  internal::MicrotaskQueue* const microtask_queue_;
8289  internal::Address previous_stack_height_;
8290 
8291  friend class internal::ThreadLocalTop;
8292  };
8293 
8294  /**
8295  * This scope allows terminations inside direct V8 API calls and forbid them
8296  * inside any recursice API calls without explicit SafeForTerminationScope.
8297  */
8299  public:
8300  explicit SafeForTerminationScope(v8::Isolate* isolate);
8302 
8303  // Prevent copying of Scope objects.
8306 
8307  private:
8308  internal::Isolate* isolate_;
8309  bool prev_value_;
8310  };
8311 
8312  /**
8313  * Types of garbage collections that can be requested via
8314  * RequestGarbageCollectionForTesting.
8315  */
8319  };
8320 
8321  /**
8322  * Features reported via the SetUseCounterCallback callback. Do not change
8323  * assigned numbers of existing items; add new features to the end of this
8324  * list.
8325  */
8327  kUseAsm = 0,
8386  kLocale = 59,
8410 
8411  // If you add new values here, you'll also need to update Chromium's:
8412  // web_feature.mojom, use_counter_callback.cc, and enums.xml. V8 changes to
8413  // this list need to be landed first, then changes on the Chromium side.
8414  kUseCounterFeatureCount // This enum value must be last.
8415  };
8416 
8418  kMessageLog = (1 << 0),
8419  kMessageDebug = (1 << 1),
8420  kMessageInfo = (1 << 2),
8421  kMessageError = (1 << 3),
8422  kMessageWarning = (1 << 4),
8425  };
8426 
8427  typedef void (*UseCounterCallback)(Isolate* isolate,
8428  UseCounterFeature feature);
8429 
8430  /**
8431  * Allocates a new isolate but does not initialize it. Does not change the
8432  * currently entered isolate.
8433  *
8434  * Only Isolate::GetData() and Isolate::SetData(), which access the
8435  * embedder-controlled parts of the isolate, are allowed to be called on the
8436  * uninitialized isolate. To initialize the isolate, call
8437  * Isolate::Initialize().
8438  *
8439  * When an isolate is no longer used its resources should be freed
8440  * by calling Dispose(). Using the delete operator is not allowed.
8441  *
8442  * V8::Initialize() must have run prior to this.
8443  */
8444  static Isolate* Allocate();
8445 
8446  /**
8447  * Initialize an Isolate previously allocated by Isolate::Allocate().
8448  */
8449  static void Initialize(Isolate* isolate, const CreateParams& params);
8450 
8451  /**
8452  * Creates a new isolate. Does not change the currently entered
8453  * isolate.
8454  *
8455  * When an isolate is no longer used its resources should be freed
8456  * by calling Dispose(). Using the delete operator is not allowed.
8457  *
8458  * V8::Initialize() must have run prior to this.
8459  */
8460  static Isolate* New(const CreateParams& params);
8461 
8462  /**
8463  * Returns the entered isolate for the current thread or NULL in
8464  * case there is no current isolate.
8465  *
8466  * This method must not be invoked before V8::Initialize() was invoked.
8467  */
8468  static Isolate* GetCurrent();
8469 
8470  /**
8471  * Clears the set of objects held strongly by the heap. This set of
8472  * objects are originally built when a WeakRef is created or
8473  * successfully dereferenced.
8474  *
8475  * The embedder is expected to call this when a synchronous sequence
8476  * of ECMAScript execution completes. It's the embedders
8477  * responsiblity to make this call at a time which does not
8478  * interrupt synchronous ECMAScript code execution.
8479  */
8480  void ClearKeptObjects();
8481 
8482  /**
8483  * Custom callback used by embedders to help V8 determine if it should abort
8484  * when it throws and no internal handler is predicted to catch the
8485  * exception. If --abort-on-uncaught-exception is used on the command line,
8486  * then V8 will abort if either:
8487  * - no custom callback is set.
8488  * - the custom callback set returns true.
8489  * Otherwise, the custom callback will not be called and V8 will not abort.
8490  */
8494 
8495  /**
8496  * This specifies the callback to be called when finalization groups
8497  * are ready to be cleaned up and require FinalizationGroup::Cleanup()
8498  * to be called in a future task.
8499  */
8502 
8503  /**
8504  * This specifies the callback called by the upcoming dynamic
8505  * import() language feature to load modules.
8506  */
8509 
8510  /**
8511  * This specifies the callback called by the upcoming importa.meta
8512  * language feature to retrieve host-defined meta data for a module.
8513  */
8516 
8517  /**
8518  * This specifies the callback called when the stack property of Error
8519  * is accessed.
8520  */
8522 
8523  /**
8524  * Optional notification that the system is running low on memory.
8525  * V8 uses these notifications to guide heuristics.
8526  * It is allowed to call this function from another thread while
8527  * the isolate is executing long running JavaScript code.
8528  */
8530 
8531  /**
8532  * Methods below this point require holding a lock (using Locker) in
8533  * a multi-threaded environment.
8534  */
8535 
8536  /**
8537  * Sets this isolate as the entered one for the current thread.
8538  * Saves the previously entered one (if any), so that it can be
8539  * restored when exiting. Re-entering an isolate is allowed.
8540  */
8541  void Enter();
8542 
8543  /**
8544  * Exits this isolate by restoring the previously entered one in the
8545  * current thread. The isolate may still stay the same, if it was
8546  * entered more than once.
8547  *
8548  * Requires: this == Isolate::GetCurrent().
8549  */
8550  void Exit();
8551 
8552  /**
8553  * Disposes the isolate. The isolate must not be entered by any
8554  * thread to be disposable.
8555  */
8556  void Dispose();
8557 
8558  /**
8559  * Dumps activated low-level V8 internal stats. This can be used instead
8560  * of performing a full isolate disposal.
8561  */
8562  void DumpAndResetStats();
8563 
8564  /**
8565  * Discards all V8 thread-specific data for the Isolate. Should be used
8566  * if a thread is terminating and it has used an Isolate that will outlive
8567  * the thread -- all thread-specific data for an Isolate is discarded when
8568  * an Isolate is disposed so this call is pointless if an Isolate is about
8569  * to be Disposed.
8570  */
8572 
8573  /**
8574  * Associate embedder-specific data with the isolate. |slot| has to be
8575  * between 0 and GetNumberOfDataSlots() - 1.
8576  */
8577  V8_INLINE void SetData(uint32_t slot, void* data);
8578 
8579  /**
8580  * Retrieve embedder-specific data from the isolate.
8581  * Returns NULL if SetData has never been called for the given |slot|.
8582  */
8583  V8_INLINE void* GetData(uint32_t slot);
8584 
8585  /**
8586  * Returns the maximum number of available embedder data slots. Valid slots
8587  * are in the range of 0 - GetNumberOfDataSlots() - 1.
8588  */
8589  V8_INLINE static uint32_t GetNumberOfDataSlots();
8590 
8591  /**
8592  * Return data that was previously attached to the isolate snapshot via
8593  * SnapshotCreator, and removes the reference to it.
8594  * Repeated call with the same index returns an empty MaybeLocal.
8595  */
8596  template <class T>
8597  V8_INLINE MaybeLocal<T> GetDataFromSnapshotOnce(size_t index);
8598 
8599  /**
8600  * Get statistics about the heap memory usage.
8601  */
8602  void GetHeapStatistics(HeapStatistics* heap_statistics);
8603 
8604  /**
8605  * Returns the number of spaces in the heap.
8606  */
8607  size_t NumberOfHeapSpaces();
8608 
8609  /**
8610  * Get the memory usage of a space in the heap.
8611  *
8612  * \param space_statistics The HeapSpaceStatistics object to fill in
8613  * statistics.
8614  * \param index The index of the space to get statistics from, which ranges
8615  * from 0 to NumberOfHeapSpaces() - 1.
8616  * \returns true on success.
8617  */
8618  bool GetHeapSpaceStatistics(HeapSpaceStatistics* space_statistics,
8619  size_t index);
8620 
8621  /**
8622  * Returns the number of types of objects tracked in the heap at GC.
8623  */
8625 
8626  /**
8627  * Get statistics about objects in the heap.
8628  *
8629  * \param object_statistics The HeapObjectStatistics object to fill in
8630  * statistics of objects of given type, which were live in the previous GC.
8631  * \param type_index The index of the type of object to fill details about,
8632  * which ranges from 0 to NumberOfTrackedHeapObjectTypes() - 1.
8633  * \returns true on success.
8634  */
8635  bool GetHeapObjectStatisticsAtLastGC(HeapObjectStatistics* object_statistics,
8636  size_t type_index);
8637 
8638  /**
8639  * Get statistics about code and its metadata in the heap.
8640  *
8641  * \param object_statistics The HeapCodeStatistics object to fill in
8642  * statistics of code, bytecode and their metadata.
8643  * \returns true on success.
8644  */
8645  bool GetHeapCodeAndMetadataStatistics(HeapCodeStatistics* object_statistics);
8646 
8647  /**
8648  * This API is experimental and may change significantly.
8649  *
8650  * Enqueues a memory measurement request and invokes the delegate with the
8651  * results.
8652  *
8653  * \param delegate the delegate that defines which contexts to measure and
8654  * reports the results.
8655  *
8656  * \param execution promptness executing the memory measurement.
8657  * The kEager value is expected to be used only in tests.
8658  */
8659  bool MeasureMemory(
8660  std::unique_ptr<MeasureMemoryDelegate> delegate,
8662 
8663  V8_DEPRECATE_SOON("Use the version with a delegate")
8665  MeasureMemoryMode mode);
8666 
8667  /**
8668  * Get a call stack sample from the isolate.
8669  * \param state Execution state.
8670  * \param frames Caller allocated buffer to store stack frames.
8671  * \param frames_limit Maximum number of frames to capture. The buffer must
8672  * be large enough to hold the number of frames.
8673  * \param sample_info The sample info is filled up by the function
8674  * provides number of actual captured stack frames and
8675  * the current VM state.
8676  * \note GetStackSample should only be called when the JS thread is paused or
8677  * interrupted. Otherwise the behavior is undefined.
8678  */
8679  void GetStackSample(const RegisterState& state, void** frames,
8680  size_t frames_limit, SampleInfo* sample_info);
8681 
8682  /**
8683  * Adjusts the amount of registered external memory. Used to give V8 an
8684  * indication of the amount of externally allocated memory that is kept alive
8685  * by JavaScript objects. V8 uses this to decide when to perform global
8686  * garbage collections. Registering externally allocated memory will trigger
8687  * global garbage collections more often than it would otherwise in an attempt
8688  * to garbage collect the JavaScript objects that keep the externally
8689  * allocated memory alive.
8690  *
8691  * \param change_in_bytes the change in externally allocated memory that is
8692  * kept alive by JavaScript objects.
8693  * \returns the adjusted value.
8694  */
8695  V8_INLINE int64_t
8696  AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes);
8697 
8698  /**
8699  * Returns the number of phantom handles without callbacks that were reset
8700  * by the garbage collector since the last call to this function.
8701  */
8703 
8704  /**
8705  * Returns heap profiler for this isolate. Will return NULL until the isolate
8706  * is initialized.
8707  */
8709 
8710  /**
8711  * Tells the VM whether the embedder is idle or not.
8712  */
8713  void SetIdle(bool is_idle);
8714 
8715  /** Returns the ArrayBuffer::Allocator used in this isolate. */
8717 
8718  /** Returns true if this isolate has a current context. */
8719  bool InContext();
8720 
8721  /**
8722  * Returns the context of the currently running JavaScript, or the context
8723  * on the top of the stack if no JavaScript is running.
8724  */
8726 
8727  /** Returns the last context entered through V8's C++ API. */
8728  V8_DEPRECATED("Use GetEnteredOrMicrotaskContext().")
8730 
8731  /**
8732  * Returns either the last context entered through V8's C++ API, or the
8733  * context of the currently running microtask while processing microtasks.
8734  * If a context is entered while executing a microtask, that context is
8735  * returned.
8736  */
8738 
8739  /**
8740  * Returns the Context that corresponds to the Incumbent realm in HTML spec.
8741  * https://html.spec.whatwg.org/multipage/webappapis.html#incumbent
8742  */
8744 
8745  /**
8746  * Schedules an exception to be thrown when returning to JavaScript. When an
8747  * exception has been scheduled it is illegal to invoke any JavaScript
8748  * operation; the caller must return immediately and only after the exception
8749  * has been handled does it become legal to invoke JavaScript operations.
8750  */
8751  Local<Value> ThrowException(Local<Value> exception);
8752 
8753  typedef void (*GCCallback)(Isolate* isolate, GCType type,
8754  GCCallbackFlags flags);
8755  typedef void (*GCCallbackWithData)(Isolate* isolate, GCType type,
8756  GCCallbackFlags flags, void* data);
8757 
8758  /**
8759  * Enables the host application to receive a notification before a
8760  * garbage collection. Allocations are allowed in the callback function,
8761  * but the callback is not re-entrant: if the allocation inside it will
8762  * trigger the garbage collection, the callback won't be called again.
8763  * It is possible to specify the GCType filter for your callback. But it is
8764  * not possible to register the same callback function two times with
8765  * different GCType filters.
8766  */
8767  void AddGCPrologueCallback(GCCallbackWithData callback, void* data = nullptr,
8768  GCType gc_type_filter = kGCTypeAll);
8769  void AddGCPrologueCallback(GCCallback callback,
8770  GCType gc_type_filter = kGCTypeAll);
8771 
8772  /**
8773  * This function removes callback which was installed by
8774  * AddGCPrologueCallback function.
8775  */
8776  void RemoveGCPrologueCallback(GCCallbackWithData, void* data = nullptr);
8777  void RemoveGCPrologueCallback(GCCallback callback);
8778 
8779  /**
8780  * Sets the embedder heap tracer for the isolate.
8781  */
8783 
8784  /*
8785  * Gets the currently active heap tracer for the isolate.
8786  */
8788 
8789  /**
8790  * Use for |AtomicsWaitCallback| to indicate the type of event it receives.
8791  */
8792  enum class AtomicsWaitEvent {
8793  /** Indicates that this call is happening before waiting. */
8794  kStartWait,
8795  /** `Atomics.wait()` finished because of an `Atomics.wake()` call. */
8796  kWokenUp,
8797  /** `Atomics.wait()` finished because it timed out. */
8798  kTimedOut,
8799  /** `Atomics.wait()` was interrupted through |TerminateExecution()|. */
8801  /** `Atomics.wait()` was stopped through |AtomicsWaitWakeHandle|. */
8802  kAPIStopped,
8803  /** `Atomics.wait()` did not wait, as the initial condition was not met. */
8804  kNotEqual
8805  };
8806 
8807  /**
8808  * Passed to |AtomicsWaitCallback| as a means of stopping an ongoing
8809  * `Atomics.wait` call.
8810  */
8812  public:
8813  /**
8814  * Stop this `Atomics.wait()` call and call the |AtomicsWaitCallback|
8815  * with |kAPIStopped|.
8816  *
8817  * This function may be called from another thread. The caller has to ensure
8818  * through proper synchronization that it is not called after
8819  * the finishing |AtomicsWaitCallback|.
8820  *
8821  * Note that the ECMAScript specification does not plan for the possibility
8822  * of wakeups that are neither coming from a timeout or an `Atomics.wake()`
8823  * call, so this may invalidate assumptions made by existing code.
8824  * The embedder may accordingly wish to schedule an exception in the
8825  * finishing |AtomicsWaitCallback|.
8826  */
8827  void Wake();
8828  };
8829 
8830  /**
8831  * Embedder callback for `Atomics.wait()` that can be added through
8832  * |SetAtomicsWaitCallback|.
8833  *
8834  * This will be called just before starting to wait with the |event| value
8835  * |kStartWait| and after finishing waiting with one of the other
8836  * values of |AtomicsWaitEvent| inside of an `Atomics.wait()` call.
8837  *
8838  * |array_buffer| will refer to the underlying SharedArrayBuffer,
8839  * |offset_in_bytes| to the location of the waited-on memory address inside
8840  * the SharedArrayBuffer.
8841  *
8842  * |value| and |timeout_in_ms| will be the values passed to
8843  * the `Atomics.wait()` call. If no timeout was used, |timeout_in_ms|
8844  * will be `INFINITY`.
8845  *
8846  * In the |kStartWait| callback, |stop_handle| will be an object that
8847  * is only valid until the corresponding finishing callback and that
8848  * can be used to stop the wait process while it is happening.
8849  *
8850  * This callback may schedule exceptions, *unless* |event| is equal to
8851  * |kTerminatedExecution|.
8852  */
8853  typedef void (*AtomicsWaitCallback)(AtomicsWaitEvent event,
8854  Local<SharedArrayBuffer> array_buffer,
8855  size_t offset_in_bytes, int64_t value,
8856  double timeout_in_ms,
8857  AtomicsWaitWakeHandle* stop_handle,
8858  void* data);
8859 
8860  /**
8861  * Set a new |AtomicsWaitCallback|. This overrides an earlier
8862  * |AtomicsWaitCallback|, if there was any. If |callback| is nullptr,
8863  * this unsets the callback. |data| will be passed to the callback
8864  * as its last parameter.
8865  */
8866  void SetAtomicsWaitCallback(AtomicsWaitCallback callback, void* data);
8867 
8868  /**
8869  * Enables the host application to receive a notification after a
8870  * garbage collection. Allocations are allowed in the callback function,
8871  * but the callback is not re-entrant: if the allocation inside it will
8872  * trigger the garbage collection, the callback won't be called again.
8873  * It is possible to specify the GCType filter for your callback. But it is
8874  * not possible to register the same callback function two times with
8875  * different GCType filters.
8876  */
8877  void AddGCEpilogueCallback(GCCallbackWithData callback, void* data = nullptr,
8878  GCType gc_type_filter = kGCTypeAll);
8879  void AddGCEpilogueCallback(GCCallback callback,
8880  GCType gc_type_filter = kGCTypeAll);
8881 
8882  /**
8883  * This function removes callback which was installed by
8884  * AddGCEpilogueCallback function.
8885  */
8887  void* data = nullptr);
8888  void RemoveGCEpilogueCallback(GCCallback callback);
8889 
8890  typedef size_t (*GetExternallyAllocatedMemoryInBytesCallback)();
8891 
8892  /**
8893  * Set the callback that tells V8 how much memory is currently allocated
8894  * externally of the V8 heap. Ideally this memory is somehow connected to V8
8895  * objects and may get freed-up when the corresponding V8 objects get
8896  * collected by a V8 garbage collection.
8897  */
8899  GetExternallyAllocatedMemoryInBytesCallback callback);
8900 
8901  /**
8902  * Forcefully terminate the current thread of JavaScript execution
8903  * in the given isolate.
8904  *
8905  * This method can be used by any thread even if that thread has not
8906  * acquired the V8 lock with a Locker object.
8907  */
8908  void TerminateExecution();
8909 
8910  /**
8911  * Is V8 terminating JavaScript execution.
8912  *
8913  * Returns true if JavaScript execution is currently terminating
8914  * because of a call to TerminateExecution. In that case there are
8915  * still JavaScript frames on the stack and the termination
8916  * exception is still active.
8917  */
8918  bool IsExecutionTerminating();
8919 
8920  /**
8921  * Resume execution capability in the given isolate, whose execution
8922  * was previously forcefully terminated using TerminateExecution().
8923  *
8924  * When execution is forcefully terminated using TerminateExecution(),
8925  * the isolate can not resume execution until all JavaScript frames
8926  * have propagated the uncatchable exception which is generated. This
8927  * method allows the program embedding the engine to handle the
8928  * termination event and resume execution capability, even if
8929  * JavaScript frames remain on the stack.
8930  *
8931  * This method can be used by any thread even if that thread has not
8932  * acquired the V8 lock with a Locker object.
8933  */
8934  void CancelTerminateExecution();
8935 
8936  /**
8937  * Request V8 to interrupt long running JavaScript code and invoke
8938  * the given |callback| passing the given |data| to it. After |callback|
8939  * returns control will be returned to the JavaScript code.
8940  * There may be a number of interrupt requests in flight.
8941  * Can be called from another thread without acquiring a |Locker|.
8942  * Registered |callback| must not reenter interrupted Isolate.
8943  */
8944  void RequestInterrupt(InterruptCallback callback, void* data);
8945 
8946  /**
8947  * Request garbage collection in this Isolate. It is only valid to call this
8948  * function if --expose_gc was specified.
8949  *
8950  * This should only be used for testing purposes and not to enforce a garbage
8951  * collection schedule. It has strong negative impact on the garbage
8952  * collection performance. Use IdleNotificationDeadline() or
8953  * LowMemoryNotification() instead to influence the garbage collection
8954  * schedule.
8955  */
8957 
8958  /**
8959  * Set the callback to invoke for logging event.
8960  */
8961  void SetEventLogger(LogEventCallback that);
8962 
8963  /**
8964  * Adds a callback to notify the host application right before a script
8965  * is about to run. If a script re-enters the runtime during executing, the
8966  * BeforeCallEnteredCallback is invoked for each re-entrance.
8967  * Executing scripts inside the callback will re-trigger the callback.
8968  */
8970 
8971  /**
8972  * Removes callback that was installed by AddBeforeCallEnteredCallback.
8973  */
8975 
8976  /**
8977  * Adds a callback to notify the host application when a script finished
8978  * running. If a script re-enters the runtime during executing, the
8979  * CallCompletedCallback is only invoked when the outer-most script
8980  * execution ends. Executing scripts inside the callback do not trigger
8981  * further callbacks.
8982  */
8984 
8985  /**
8986  * Removes callback that was installed by AddCallCompletedCallback.
8987  */
8989 
8990  /**
8991  * Set the PromiseHook callback for various promise lifecycle
8992  * events.
8993  */
8994  void SetPromiseHook(PromiseHook hook);
8995 
8996  /**
8997  * Set callback to notify about promise reject with no handler, or
8998  * revocation of such a previous notification once the handler is added.
8999  */
9001 
9002  /**
9003  * Runs the default MicrotaskQueue until it gets empty.
9004  * Any exceptions thrown by microtask callbacks are swallowed.
9005  */
9006  void RunMicrotasks();
9007 
9008  /**
9009  * Enqueues the callback to the default MicrotaskQueue
9010  */
9011  void EnqueueMicrotask(Local<Function> microtask);
9012 
9013  /**
9014  * Enqueues the callback to the default MicrotaskQueue
9015  */
9016  void EnqueueMicrotask(MicrotaskCallback callback, void* data = nullptr);
9017 
9018  /**
9019  * Controls how Microtasks are invoked. See MicrotasksPolicy for details.
9020  */
9022 
9023  /**
9024  * Returns the policy controlling how Microtasks are invoked.
9025  */
9027 
9028  /**
9029  * Adds a callback to notify the host application after
9030  * microtasks were run on the default MicrotaskQueue. The callback is
9031  * triggered by explicit RunMicrotasks call or automatic microtasks execution
9032  * (see SetMicrotaskPolicy).
9033  *
9034  * Callback will trigger even if microtasks were attempted to run,
9035  * but the microtasks queue was empty and no single microtask was actually
9036  * executed.
9037  *
9038  * Executing scripts inside the callback will not re-trigger microtasks and
9039  * the callback.
9040  */
9041  V8_DEPRECATE_SOON("Use *WithData version.")
9044  MicrotasksCompletedCallbackWithData callback, void* data = nullptr);
9045 
9046  /**
9047  * Removes callback that was installed by AddMicrotasksCompletedCallback.
9048  */
9049  V8_DEPRECATE_SOON("Use *WithData version.")
9052  MicrotasksCompletedCallbackWithData callback, void* data = nullptr);
9053 
9054  /**
9055  * Sets a callback for counting the number of times a feature of V8 is used.
9056  */
9058 
9059  /**
9060  * Enables the host application to provide a mechanism for recording
9061  * statistics counters.
9062  */
9064 
9065  /**
9066  * Enables the host application to provide a mechanism for recording
9067  * histograms. The CreateHistogram function returns a
9068  * histogram which will later be passed to the AddHistogramSample
9069  * function.
9070  */
9073 
9074  /**
9075  * Enables the host application to provide a mechanism for recording a
9076  * predefined set of data as crash keys to be used in postmortem debugging in
9077  * case of a crash.
9078  */
9080 
9081  /**
9082  * Optional notification that the embedder is idle.
9083  * V8 uses the notification to perform garbage collection.
9084  * This call can be used repeatedly if the embedder remains idle.
9085  * Returns true if the embedder should stop calling IdleNotificationDeadline
9086  * until real work has been done. This indicates that V8 has done
9087  * as much cleanup as it will be able to do.
9088  *
9089  * The deadline_in_seconds argument specifies the deadline V8 has to finish
9090  * garbage collection work. deadline_in_seconds is compared with
9091  * MonotonicallyIncreasingTime() and should be based on the same timebase as
9092  * that function. There is no guarantee that the actual work will be done
9093  * within the time limit.
9094  */
9095  bool IdleNotificationDeadline(double deadline_in_seconds);
9096 
9097  /**
9098  * Optional notification that the system is running low on memory.
9099  * V8 uses these notifications to attempt to free memory.
9100  */
9101  void LowMemoryNotification();
9102 
9103  /**
9104  * Optional notification that a context has been disposed. V8 uses
9105  * these notifications to guide the GC heuristic. Returns the number
9106  * of context disposals - including this one - since the last time
9107  * V8 had a chance to clean up.
9108  *
9109  * The optional parameter |dependant_context| specifies whether the disposed
9110  * context was depending on state from other contexts or not.
9111  */
9112  int ContextDisposedNotification(bool dependant_context = true);
9113 
9114  /**
9115  * Optional notification that the isolate switched to the foreground.
9116  * V8 uses these notifications to guide heuristics.
9117  */
9119 
9120  /**
9121  * Optional notification that the isolate switched to the background.
9122  * V8 uses these notifications to guide heuristics.
9123  */
9125 
9126  /**
9127  * Optional notification which will enable the memory savings mode.
9128  * V8 uses this notification to guide heuristics which may result in a
9129  * smaller memory footprint at the cost of reduced runtime performance.
9130  */
9131  void EnableMemorySavingsMode();
9132 
9133  /**
9134  * Optional notification which will disable the memory savings mode.
9135  */
9136  void DisableMemorySavingsMode();
9137 
9138  /**
9139  * Optional notification to tell V8 the current performance requirements
9140  * of the embedder based on RAIL.
9141  * V8 uses these notifications to guide heuristics.
9142  * This is an unfinished experimental feature. Semantics and implementation
9143  * may change frequently.
9144  */
9145  void SetRAILMode(RAILMode rail_mode);
9146 
9147  /**
9148  * Optional notification to tell V8 the current isolate is used for debugging
9149  * and requires higher heap limit.
9150  */
9152 
9153  /**
9154  * Restores the original heap limit after IncreaseHeapLimitForDebugging().
9155  */
9156  void RestoreOriginalHeapLimit();
9157 
9158  /**
9159  * Returns true if the heap limit was increased for debugging and the
9160  * original heap limit was not restored yet.
9161  */
9163 
9164  /**
9165  * Allows the host application to provide the address of a function that is
9166  * notified each time code is added, moved or removed.
9167  *
9168  * \param options options for the JIT code event handler.
9169  * \param event_handler the JIT code event handler, which will be invoked
9170  * each time code is added, moved or removed.
9171  * \note \p event_handler won't get notified of existent code.
9172  * \note since code removal notifications are not currently issued, the
9173  * \p event_handler may get notifications of code that overlaps earlier
9174  * code notifications. This happens when code areas are reused, and the
9175  * earlier overlapping code areas should therefore be discarded.
9176  * \note the events passed to \p event_handler and the strings they point to
9177  * are not guaranteed to live past each call. The \p event_handler must
9178  * copy strings and other parameters it needs to keep around.
9179  * \note the set of events declared in JitCodeEvent::EventType is expected to
9180  * grow over time, and the JitCodeEvent structure is expected to accrue
9181  * new members. The \p event_handler function must ignore event codes
9182  * it does not recognize to maintain future compatibility.
9183  * \note Use Isolate::CreateParams to get events for code executed during
9184  * Isolate setup.
9185  */
9187  JitCodeEventHandler event_handler);
9188 
9189  /**
9190  * Modifies the stack limit for this Isolate.
9191  *
9192  * \param stack_limit An address beyond which the Vm's stack may not grow.
9193  *
9194  * \note If you are using threads then you should hold the V8::Locker lock
9195  * while setting the stack limit and you must set a non-default stack
9196  * limit separately for each thread.
9197  */
9198  void SetStackLimit(uintptr_t stack_limit);
9199 
9200  /**
9201  * Returns a memory range that can potentially contain jitted code. Code for
9202  * V8's 'builtins' will not be in this range if embedded builtins is enabled.
9203  *
9204  * On Win64, embedders are advised to install function table callbacks for
9205  * these ranges, as default SEH won't be able to unwind through jitted code.
9206  * The first page of the code range is reserved for the embedder and is
9207  * committed, writable, and executable, to be used to store unwind data, as
9208  * documented in
9209  * https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64.
9210  *
9211  * Might be empty on other platforms.
9212  *
9213  * https://code.google.com/p/v8/issues/detail?id=3598
9214  */
9215  void GetCodeRange(void** start, size_t* length_in_bytes);
9216 
9217  /**
9218  * Returns the UnwindState necessary for use with the Unwinder API.
9219  */
9220  // TODO(petermarshall): Remove this API.
9221  V8_DEPRECATE_SOON("Use entry_stubs + code_pages version.")
9223 
9224  /**
9225  * Returns the JSEntryStubs necessary for use with the Unwinder API.
9226  */
9228 
9229  static constexpr size_t kMinCodePagesBufferSize = 32;
9230 
9231  /**
9232  * Copies the code heap pages currently in use by V8 into |code_pages_out|.
9233  * |code_pages_out| must have at least kMinCodePagesBufferSize capacity and
9234  * must be empty.
9235  *
9236  * Signal-safe, does not allocate, does not access the V8 heap.
9237  * No code on the stack can rely on pages that might be missing.
9238  *
9239  * Returns the number of pages available to be copied, which might be greater
9240  * than |capacity|. In this case, only |capacity| pages will be copied into
9241  * |code_pages_out|. The caller should provide a bigger buffer on the next
9242  * call in order to get all available code pages, but this is not required.
9243  */
9244  size_t CopyCodePages(size_t capacity, MemoryRange* code_pages_out);
9245 
9246  /** Set the callback to invoke in case of fatal errors. */
9248 
9249  /** Set the callback to invoke in case of OOM errors. */
9251 
9252  /**
9253  * Add a callback to invoke in case the heap size is close to the heap limit.
9254  * If multiple callbacks are added, only the most recently added callback is
9255  * invoked.
9256  */
9257  void AddNearHeapLimitCallback(NearHeapLimitCallback callback, void* data);
9258 
9259  /**
9260  * Remove the given callback and restore the heap limit to the
9261  * given limit. If the given limit is zero, then it is ignored.
9262  * If the current heap size is greater than the given limit,
9263  * then the heap limit is restored to the minimal limit that
9264  * is possible for the current heap size.
9265  */
9266  void RemoveNearHeapLimitCallback(NearHeapLimitCallback callback,
9267  size_t heap_limit);
9268 
9269  /**
9270  * If the heap limit was changed by the NearHeapLimitCallback, then the
9271  * initial heap limit will be restored once the heap size falls below the
9272  * given threshold percentage of the initial heap limit.
9273  * The threshold percentage is a number in (0.0, 1.0) range.
9274  */
9275  void AutomaticallyRestoreInitialHeapLimit(double threshold_percent = 0.5);
9276 
9277  /**
9278  * Set the callback to invoke to check if code generation from
9279  * strings should be allowed.
9280  */
9281  V8_DEPRECATED(
9282  "Use Isolate::SetModifyCodeGenerationFromStringsCallback instead. "
9283  "See http://crbug.com/v8/10096.")
9284  void SetAllowCodeGenerationFromStringsCallback(
9287  ModifyCodeGenerationFromStringsCallback callback);
9288 
9289  /**
9290  * Set the callback to invoke to check if wasm code generation should
9291  * be allowed.
9292  */
9295 
9296  /**
9297  * Embedder over{ride|load} injection points for wasm APIs. The expectation
9298  * is that the embedder sets them at most once.
9299  */
9302 
9304 
9306 
9308 
9309  /**
9310  * Check if V8 is dead and therefore unusable. This is the case after
9311  * fatal errors such as out-of-memory situations.
9312  */
9313  bool IsDead();
9314 
9315  /**
9316  * Adds a message listener (errors only).
9317  *
9318  * The same message listener can be added more than once and in that
9319  * case it will be called more than once for each message.
9320  *
9321  * If data is specified, it will be passed to the callback when it is called.
9322  * Otherwise, the exception object will be passed to the callback instead.
9323  */
9325  Local<Value> data = Local<Value>());
9326 
9327  /**
9328  * Adds a message listener.
9329  *
9330  * The same message listener can be added more than once and in that
9331  * case it will be called more than once for each message.
9332  *
9333  * If data is specified, it will be passed to the callback when it is called.
9334  * Otherwise, the exception object will be passed to the callback instead.
9335  *
9336  * A listener can listen for particular error levels by providing a mask.
9337  */
9339  int message_levels,
9340  Local<Value> data = Local<Value>());
9341 
9342  /**
9343  * Remove all message listeners from the specified callback function.
9344  */
9346 
9347  /** Callback function for reporting failed access checks.*/
9349 
9350  /**
9351  * Tells V8 to capture current stack trace when uncaught exception occurs
9352  * and report it to the message listeners. The option is off by default.
9353  */
9355  bool capture, int frame_limit = 10,
9357 
9358  /**
9359  * Iterates through all external resources referenced from current isolate
9360  * heap. GC is not invoked prior to iterating, therefore there is no
9361  * guarantee that visited objects are still alive.
9362  */
9364 
9365  /**
9366  * Iterates through all the persistent handles in the current isolate's heap
9367  * that have class_ids.
9368  */
9370 
9371  /**
9372  * Iterates through all the persistent handles in the current isolate's heap
9373  * that have class_ids and are weak to be marked as inactive if there is no
9374  * pending activity for the handle.
9375  */
9377 
9378  /**
9379  * Check if this isolate is in use.
9380  * True if at least one thread Enter'ed this isolate.
9381  */
9382  bool IsInUse();
9383 
9384  /**
9385  * Set whether calling Atomics.wait (a function that may block) is allowed in
9386  * this isolate. This can also be configured via
9387  * CreateParams::allow_atomics_wait.
9388  */
9389  void SetAllowAtomicsWait(bool allow);
9390 
9391  /**
9392  * Time zone redetection indicator for
9393  * DateTimeConfigurationChangeNotification.
9394  *
9395  * kSkip indicates V8 that the notification should not trigger redetecting
9396  * host time zone. kRedetect indicates V8 that host time zone should be
9397  * redetected, and used to set the default time zone.
9398  *
9399  * The host time zone detection may require file system access or similar
9400  * operations unlikely to be available inside a sandbox. If v8 is run inside a
9401  * sandbox, the host time zone has to be detected outside the sandbox before
9402  * calling DateTimeConfigurationChangeNotification function.
9403  */
9405 
9406  /**
9407  * Notification that the embedder has changed the time zone, daylight savings
9408  * time or other date / time configuration parameters. V8 keeps a cache of
9409  * various values used for date / time computation. This notification will
9410  * reset those cached values for the current context so that date / time
9411  * configuration changes would be reflected.
9412  *
9413  * This API should not be called more than needed as it will negatively impact
9414  * the performance of date operations.
9415  */
9417  TimeZoneDetection time_zone_detection = TimeZoneDetection::kSkip);
9418 
9419  /**
9420  * Notification that the embedder has changed the locale. V8 keeps a cache of
9421  * various values used for locale computation. This notification will reset
9422  * those cached values for the current context so that locale configuration
9423  * changes would be reflected.
9424  *
9425  * This API should not be called more than needed as it will negatively impact
9426  * the performance of locale operations.
9427  */
9429 
9430  Isolate() = delete;
9431  ~Isolate() = delete;
9432  Isolate(const Isolate&) = delete;
9433  Isolate& operator=(const Isolate&) = delete;
9434  // Deleting operator new and delete here is allowed as ctor and dtor is also
9435  // deleted.
9436  void* operator new(size_t size) = delete;
9437  void* operator new[](size_t size) = delete;
9438  void operator delete(void*, size_t) = delete;
9439  void operator delete[](void*, size_t) = delete;
9440 
9441  private:
9442  template <class K, class V, class Traits>
9444 
9445  internal::Address* GetDataFromSnapshotOnce(size_t index);
9446  void ReportExternalAllocationLimitReached();
9447  void CheckMemoryPressure();
9448 };
9449 
9451  public:
9452  /**
9453  * Whether the data created can be rehashed and and the hash seed can be
9454  * recomputed when deserialized.
9455  * Only valid for StartupData returned by SnapshotCreator::CreateBlob().
9456  */
9457  bool CanBeRehashed() const;
9458 
9459  const char* data;
9461 };
9462 
9463 
9464 /**
9465  * EntropySource is used as a callback function when v8 needs a source
9466  * of entropy.
9467  */
9468 typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
9469 
9470 /**
9471  * ReturnAddressLocationResolver is used as a callback function when v8 is
9472  * resolving the location of a return address on the stack. Profilers that
9473  * change the return address on the stack can use this to resolve the stack
9474  * location to wherever the profiler stashed the original return address.
9475  *
9476  * \param return_addr_location A location on stack where a machine
9477  * return address resides.
9478  * \returns Either return_addr_location, or else a pointer to the profiler's
9479  * copy of the original return address.
9480  *
9481  * \note The resolver function must not cause garbage collection.
9482  */
9483 typedef uintptr_t (*ReturnAddressLocationResolver)(
9484  uintptr_t return_addr_location);
9485 
9486 
9487 /**
9488  * Container class for static utility functions.
9489  */
9490 class V8_EXPORT V8 {
9491  public:
9492  /**
9493  * Hand startup data to V8, in case the embedder has chosen to build
9494  * V8 with external startup data.
9495  *
9496  * Note:
9497  * - By default the startup data is linked into the V8 library, in which
9498  * case this function is not meaningful.
9499  * - If this needs to be called, it needs to be called before V8
9500  * tries to make use of its built-ins.
9501  * - To avoid unnecessary copies of data, V8 will point directly into the
9502  * given data blob, so pretty please keep it around until V8 exit.
9503  * - Compression of the startup blob might be useful, but needs to
9504  * handled entirely on the embedders' side.
9505  * - The call will abort if the data is invalid.
9506  */
9507  static void SetSnapshotDataBlob(StartupData* startup_blob);
9508 
9509  /** Set the callback to invoke in case of Dcheck failures. */
9510  static void SetDcheckErrorHandler(DcheckErrorCallback that);
9511 
9512 
9513  /**
9514  * Sets V8 flags from a string.
9515  */
9516  static void SetFlagsFromString(const char* str);
9517  static void SetFlagsFromString(const char* str, size_t length);
9518 
9519  /**
9520  * Sets V8 flags from the command line.
9521  */
9522  static void SetFlagsFromCommandLine(int* argc,
9523  char** argv,
9524  bool remove_flags);
9525 
9526  /** Get the version string. */
9527  static const char* GetVersion();
9528 
9529  /**
9530  * Initializes V8. This function needs to be called before the first Isolate
9531  * is created. It always returns true.
9532  */
9533  static bool Initialize();
9534 
9535  /**
9536  * Allows the host application to provide a callback which can be used
9537  * as a source of entropy for random number generators.
9538  */
9539  static void SetEntropySource(EntropySource source);
9540 
9541  /**
9542  * Allows the host application to provide a callback that allows v8 to
9543  * cooperate with a profiler that rewrites return addresses on stack.
9544  */
9546  ReturnAddressLocationResolver return_address_resolver);
9547 
9548  /**
9549  * Releases any resources used by v8 and stops any utility threads
9550  * that may be running. Note that disposing v8 is permanent, it
9551  * cannot be reinitialized.
9552  *
9553  * It should generally not be necessary to dispose v8 before exiting
9554  * a process, this should happen automatically. It is only necessary
9555  * to use if the process needs the resources taken up by v8.
9556  */
9557  static bool Dispose();
9558 
9559  /**
9560  * Initialize the ICU library bundled with V8. The embedder should only
9561  * invoke this method when using the bundled ICU. Returns true on success.
9562  *
9563  * If V8 was compiled with the ICU data in an external file, the location
9564  * of the data file has to be provided.
9565  */
9566  static bool InitializeICU(const char* icu_data_file = nullptr);
9567 
9568  /**
9569  * Initialize the ICU library bundled with V8. The embedder should only
9570  * invoke this method when using the bundled ICU. If V8 was compiled with
9571  * the ICU data in an external file and when the default location of that
9572  * file should be used, a path to the executable must be provided.
9573  * Returns true on success.
9574  *
9575  * The default is a file called icudtl.dat side-by-side with the executable.
9576  *
9577  * Optionally, the location of the data file can be provided to override the
9578  * default.
9579  */
9580  static bool InitializeICUDefaultLocation(const char* exec_path,
9581  const char* icu_data_file = nullptr);
9582 
9583  /**
9584  * Initialize the external startup data. The embedder only needs to
9585  * invoke this method when external startup data was enabled in a build.
9586  *
9587  * If V8 was compiled with the startup data in an external file, then
9588  * V8 needs to be given those external files during startup. There are
9589  * three ways to do this:
9590  * - InitializeExternalStartupData(const char*)
9591  * This will look in the given directory for the file "snapshot_blob.bin".
9592  * - InitializeExternalStartupDataFromFile(const char*)
9593  * As above, but will directly use the given file name.
9594  * - Call SetSnapshotDataBlob.
9595  * This will read the blobs from the given data structure and will
9596  * not perform any file IO.
9597  */
9598  static void InitializeExternalStartupData(const char* directory_path);
9599  static void InitializeExternalStartupDataFromFile(const char* snapshot_blob);
9600 
9601  /**
9602  * Sets the v8::Platform to use. This should be invoked before V8 is
9603  * initialized.
9604  */
9605  static void InitializePlatform(Platform* platform);
9606 
9607  /**
9608  * Clears all references to the v8::Platform. This should be invoked after
9609  * V8 was disposed.
9610  */
9611  static void ShutdownPlatform();
9612 
9613 #if V8_OS_POSIX
9614  /**
9615  * Give the V8 signal handler a chance to handle a fault.
9616  *
9617  * This function determines whether a memory access violation can be recovered
9618  * by V8. If so, it will return true and modify context to return to a code
9619  * fragment that can recover from the fault. Otherwise, TryHandleSignal will
9620  * return false.
9621  *
9622  * The parameters to this function correspond to those passed to a Linux
9623  * signal handler.
9624  *
9625  * \param signal_number The signal number.
9626  *
9627  * \param info A pointer to the siginfo_t structure provided to the signal
9628  * handler.
9629  *
9630  * \param context The third argument passed to the Linux signal handler, which
9631  * points to a ucontext_t structure.
9632  */
9633  V8_DEPRECATE_SOON("Use TryHandleWebAssemblyTrapPosix")
9634  static bool TryHandleSignal(int signal_number, void* info, void* context);
9635 #endif // V8_OS_POSIX
9636 
9637  /**
9638  * Activate trap-based bounds checking for WebAssembly.
9639  *
9640  * \param use_v8_signal_handler Whether V8 should install its own signal
9641  * handler or rely on the embedder's.
9642  */
9643  static bool EnableWebAssemblyTrapHandler(bool use_v8_signal_handler);
9644 
9645 #if defined(V8_OS_WIN)
9646  /**
9647  * On Win64, by default V8 does not emit unwinding data for jitted code,
9648  * which means the OS cannot walk the stack frames and the system Structured
9649  * Exception Handling (SEH) cannot unwind through V8-generated code:
9650  * https://code.google.com/p/v8/issues/detail?id=3598.
9651  *
9652  * This function allows embedders to register a custom exception handler for
9653  * exceptions in V8-generated code.
9654  */
9655  static void SetUnhandledExceptionCallback(
9657 #endif
9658 
9659  /**
9660  * Get statistics about the shared memory usage.
9661  */
9662  static void GetSharedMemoryStatistics(SharedMemoryStatistics* statistics);
9663 
9664  private:
9665  V8();
9666 
9667  static internal::Address* GlobalizeReference(internal::Isolate* isolate,
9668  internal::Address* handle);
9669  static internal::Address* GlobalizeTracedReference(internal::Isolate* isolate,
9670  internal::Address* handle,
9671  internal::Address* slot,
9672  bool has_destructor);
9673  static void MoveGlobalReference(internal::Address** from,
9674  internal::Address** to);
9675  static void MoveTracedGlobalReference(internal::Address** from,
9676  internal::Address** to);
9677  static void CopyTracedGlobalReference(const internal::Address* const* from,
9678  internal::Address** to);
9679  static internal::Address* CopyGlobalReference(internal::Address* from);
9680  static void DisposeGlobal(internal::Address* global_handle);
9681  static void DisposeTracedGlobal(internal::Address* global_handle);
9682  static void MakeWeak(internal::Address* location, void* data,
9683  WeakCallbackInfo<void>::Callback weak_callback,
9684  WeakCallbackType type);
9685  static void MakeWeak(internal::Address** location_addr);
9686  static void* ClearWeak(internal::Address* location);
9687  static void SetFinalizationCallbackTraced(
9688  internal::Address* location, void* parameter,
9689  WeakCallbackInfo<void>::Callback callback);
9690  static void AnnotateStrongRetainer(internal::Address* location,
9691  const char* label);
9692  static Value* Eternalize(Isolate* isolate, Value* handle);
9693 
9694  template <class K, class V, class T>
9696 
9697  static void FromJustIsNothing();
9698  static void ToLocalEmpty();
9699  static void InternalFieldOutOfBounds(int index);
9700  template <class T>
9701  friend class Global;
9702  template <class T> friend class Local;
9703  template <class T>
9704  friend class MaybeLocal;
9705  template <class T>
9706  friend class Maybe;
9707  template <class T>
9708  friend class TracedReferenceBase;
9709  template <class T>
9710  friend class TracedGlobal;
9711  template <class T>
9712  friend class TracedReference;
9713  template <class T>
9714  friend class WeakCallbackInfo;
9715  template <class T> friend class Eternal;
9716  template <class T> friend class PersistentBase;
9717  template <class T, class M> friend class Persistent;
9718  friend class Context;
9719 };
9720 
9721 /**
9722  * Helper class to create a snapshot data blob.
9723  */
9725  public:
9727 
9728  /**
9729  * Initialize and enter an isolate, and set it up for serialization.
9730  * The isolate is either created from scratch or from an existing snapshot.
9731  * The caller keeps ownership of the argument snapshot.
9732  * \param existing_blob existing snapshot from which to create this one.
9733  * \param external_references a null-terminated array of external references
9734  * that must be equivalent to CreateParams::external_references.
9735  */
9736  SnapshotCreator(Isolate* isolate,
9737  const intptr_t* external_references = nullptr,
9738  StartupData* existing_blob = nullptr);
9739 
9740  /**
9741  * Create and enter an isolate, and set it up for serialization.
9742  * The isolate is either created from scratch or from an existing snapshot.
9743  * The caller keeps ownership of the argument snapshot.
9744  * \param existing_blob existing snapshot from which to create this one.
9745  * \param external_references a null-terminated array of external references
9746  * that must be equivalent to CreateParams::external_references.
9747  */
9748  SnapshotCreator(const intptr_t* external_references = nullptr,
9749  StartupData* existing_blob = nullptr);
9750 
9751  ~SnapshotCreator();
9752 
9753  /**
9754  * \returns the isolate prepared by the snapshot creator.
9755  */
9756  Isolate* GetIsolate();
9757 
9758  /**
9759  * Set the default context to be included in the snapshot blob.
9760  * The snapshot will not contain the global proxy, and we expect one or a
9761  * global object template to create one, to be provided upon deserialization.
9762  *
9763  * \param callback optional callback to serialize internal fields.
9764  */
9765  void SetDefaultContext(Local<Context> context,
9768 
9769  /**
9770  * Add additional context to be included in the snapshot blob.
9771  * The snapshot will include the global proxy.
9772  *
9773  * \param callback optional callback to serialize internal fields.
9774  *
9775  * \returns the index of the context in the snapshot blob.
9776  */
9777  size_t AddContext(Local<Context> context,
9780 
9781  /**
9782  * Add a template to be included in the snapshot blob.
9783  * \returns the index of the template in the snapshot blob.
9784  */
9785  V8_DEPRECATED("use AddData instead")
9786  size_t AddTemplate(Local<Template> template_obj);
9787 
9788  /**
9789  * Attach arbitrary V8::Data to the context snapshot, which can be retrieved
9790  * via Context::GetDataFromSnapshot after deserialization. This data does not
9791  * survive when a new snapshot is created from an existing snapshot.
9792  * \returns the index for retrieval.
9793  */
9794  template <class T>
9795  V8_INLINE size_t AddData(Local<Context> context, Local<T> object);
9796 
9797  /**
9798  * Attach arbitrary V8::Data to the isolate snapshot, which can be retrieved
9799  * via Isolate::GetDataFromSnapshot after deserialization. This data does not
9800  * survive when a new snapshot is created from an existing snapshot.
9801  * \returns the index for retrieval.
9802  */
9803  template <class T>
9804  V8_INLINE size_t AddData(Local<T> object);
9805 
9806  /**
9807  * Created a snapshot data blob.
9808  * This must not be called from within a handle scope.
9809  * \param function_code_handling whether to include compiled function code
9810  * in the snapshot.
9811  * \returns { nullptr, 0 } on failure, and a startup snapshot on success. The
9812  * caller acquires ownership of the data array in the return value.
9813  */
9814  StartupData CreateBlob(FunctionCodeHandling function_code_handling);
9815 
9816  // Disallow copying and assigning.
9817  SnapshotCreator(const SnapshotCreator&) = delete;
9818  void operator=(const SnapshotCreator&) = delete;
9819 
9820  private:
9821  size_t AddData(Local<Context> context, internal::Address object);
9822  size_t AddData(internal::Address object);
9823 
9824  void* data_;
9825 };
9826 
9827 /**
9828  * A simple Maybe type, representing an object which may or may not have a
9829  * value, see https://hackage.haskell.org/package/base/docs/Data-Maybe.html.
9830  *
9831  * If an API method returns a Maybe<>, the API method can potentially fail
9832  * either because an exception is thrown, or because an exception is pending,
9833  * e.g. because a previous API call threw an exception that hasn't been caught
9834  * yet, or because a TerminateExecution exception was thrown. In that case, a
9835  * "Nothing" value is returned.
9836  */
9837 template <class T>
9838 class Maybe {
9839  public:
9840  V8_INLINE bool IsNothing() const { return !has_value_; }
9841  V8_INLINE bool IsJust() const { return has_value_; }
9842 
9843  /**
9844  * An alias for |FromJust|. Will crash if the Maybe<> is nothing.
9845  */
9846  V8_INLINE T ToChecked() const { return FromJust(); }
9847 
9848  /**
9849  * Short-hand for ToChecked(), which doesn't return a value. To be used, where
9850  * the actual value of the Maybe is not needed like Object::Set.
9851  */
9852  V8_INLINE void Check() const {
9853  if (V8_UNLIKELY(!IsJust())) V8::FromJustIsNothing();
9854  }
9855 
9856  /**
9857  * Converts this Maybe<> to a value of type T. If this Maybe<> is
9858  * nothing (empty), |false| is returned and |out| is left untouched.
9859  */
9860  V8_WARN_UNUSED_RESULT V8_INLINE bool To(T* out) const {
9861  if (V8_LIKELY(IsJust())) *out = value_;
9862  return IsJust();
9863  }
9864 
9865  /**
9866  * Converts this Maybe<> to a value of type T. If this Maybe<> is
9867  * nothing (empty), V8 will crash the process.
9868  */
9869  V8_INLINE T FromJust() const {
9870  if (V8_UNLIKELY(!IsJust())) V8::FromJustIsNothing();
9871  return value_;
9872  }
9873 
9874  /**
9875  * Converts this Maybe<> to a value of type T, using a default value if this
9876  * Maybe<> is nothing (empty).
9877  */
9878  V8_INLINE T FromMaybe(const T& default_value) const {
9879  return has_value_ ? value_ : default_value;
9880  }
9881 
9882  V8_INLINE bool operator==(const Maybe& other) const {
9883  return (IsJust() == other.IsJust()) &&
9884  (!IsJust() || FromJust() == other.FromJust());
9885  }
9886 
9887  V8_INLINE bool operator!=(const Maybe& other) const {
9888  return !operator==(other);
9889  }
9890 
9891  private:
9892  Maybe() : has_value_(false) {}
9893  explicit Maybe(const T& t) : has_value_(true), value_(t) {}
9894 
9895  bool has_value_;
9896  T value_;
9897 
9898  template <class U>
9899  friend Maybe<U> Nothing();
9900  template <class U>
9901  friend Maybe<U> Just(const U& u);
9902 };
9903 
9904 template <class T>
9905 inline Maybe<T> Nothing() {
9906  return Maybe<T>();
9907 }
9908 
9909 template <class T>
9910 inline Maybe<T> Just(const T& t) {
9911  return Maybe<T>(t);
9912 }
9913 
9914 // A template specialization of Maybe<T> for the case of T = void.
9915 template <>
9916 class Maybe<void> {
9917  public:
9918  V8_INLINE bool IsNothing() const { return !is_valid_; }
9919  V8_INLINE bool IsJust() const { return is_valid_; }
9920 
9921  V8_INLINE bool operator==(const Maybe& other) const {
9922  return IsJust() == other.IsJust();
9923  }
9924 
9925  V8_INLINE bool operator!=(const Maybe& other) const {
9926  return !operator==(other);
9927  }
9928 
9929  private:
9930  struct JustTag {};
9931 
9932  Maybe() : is_valid_(false) {}
9933  explicit Maybe(JustTag) : is_valid_(true) {}
9934 
9935  bool is_valid_;
9936 
9937  template <class U>
9938  friend Maybe<U> Nothing();
9939  friend Maybe<void> JustVoid();
9940 };
9941 
9942 inline Maybe<void> JustVoid() { return Maybe<void>(Maybe<void>::JustTag()); }
9943 
9944 /**
9945  * An external exception handler.
9946  */
9948  public:
9949  /**
9950  * Creates a new try/catch block and registers it with v8. Note that
9951  * all TryCatch blocks should be stack allocated because the memory
9952  * location itself is compared against JavaScript try/catch blocks.
9953  */
9954  explicit TryCatch(Isolate* isolate);
9955 
9956  /**
9957  * Unregisters and deletes this try/catch block.
9958  */
9959  ~TryCatch();
9960 
9961  /**
9962  * Returns true if an exception has been caught by this try/catch block.
9963  */
9964  bool HasCaught() const;
9965 
9966  /**
9967  * For certain types of exceptions, it makes no sense to continue execution.
9968  *
9969  * If CanContinue returns false, the correct action is to perform any C++
9970  * cleanup needed and then return. If CanContinue returns false and
9971  * HasTerminated returns true, it is possible to call
9972  * CancelTerminateExecution in order to continue calling into the engine.
9973  */
9974  bool CanContinue() const;
9975 
9976  /**
9977  * Returns true if an exception has been caught due to script execution
9978  * being terminated.
9979  *
9980  * There is no JavaScript representation of an execution termination
9981  * exception. Such exceptions are thrown when the TerminateExecution
9982  * methods are called to terminate a long-running script.
9983  *
9984  * If such an exception has been thrown, HasTerminated will return true,
9985  * indicating that it is possible to call CancelTerminateExecution in order
9986  * to continue calling into the engine.
9987  */
9988  bool HasTerminated() const;
9989 
9990  /**
9991  * Throws the exception caught by this TryCatch in a way that avoids
9992  * it being caught again by this same TryCatch. As with ThrowException
9993  * it is illegal to execute any JavaScript operations after calling
9994  * ReThrow; the caller must return immediately to where the exception
9995  * is caught.
9996  */
9997  Local<Value> ReThrow();
9998 
9999  /**
10000  * Returns the exception caught by this try/catch block. If no exception has
10001  * been caught an empty handle is returned.
10002  *
10003  * The returned handle is valid until this TryCatch block has been destroyed.
10004  */
10005  Local<Value> Exception() const;
10006 
10007  /**
10008  * Returns the .stack property of an object. If no .stack
10009  * property is present an empty handle is returned.
10010  */
10012  Local<Context> context, Local<Value> exception);
10013 
10014  /**
10015  * Returns the .stack property of the thrown object. If no .stack property is
10016  * present or if this try/catch block has not caught an exception, an empty
10017  * handle is returned.
10018  */
10020  Local<Context> context) const;
10021 
10022  /**
10023  * Returns the message associated with this exception. If there is
10024  * no message associated an empty handle is returned.
10025  *
10026  * The returned handle is valid until this TryCatch block has been
10027  * destroyed.
10028  */
10029  Local<v8::Message> Message() const;
10030 
10031  /**
10032  * Clears any exceptions that may have been caught by this try/catch block.
10033  * After this method has been called, HasCaught() will return false. Cancels
10034  * the scheduled exception if it is caught and ReThrow() is not called before.
10035  *
10036  * It is not necessary to clear a try/catch block before using it again; if
10037  * another exception is thrown the previously caught exception will just be
10038  * overwritten. However, it is often a good idea since it makes it easier
10039  * to determine which operation threw a given exception.
10040  */
10041  void Reset();
10042 
10043  /**
10044  * Set verbosity of the external exception handler.
10045  *
10046  * By default, exceptions that are caught by an external exception
10047  * handler are not reported. Call SetVerbose with true on an
10048  * external exception handler to have exceptions caught by the
10049  * handler reported as if they were not caught.
10050  */
10051  void SetVerbose(bool value);
10052 
10053  /**
10054  * Returns true if verbosity is enabled.
10055  */
10056  bool IsVerbose() const;
10057 
10058  /**
10059  * Set whether or not this TryCatch should capture a Message object
10060  * which holds source information about where the exception
10061  * occurred. True by default.
10062  */
10063  void SetCaptureMessage(bool value);
10064 
10065  /**
10066  * There are cases when the raw address of C++ TryCatch object cannot be
10067  * used for comparisons with addresses into the JS stack. The cases are:
10068  * 1) ARM, ARM64 and MIPS simulators which have separate JS stack.
10069  * 2) Address sanitizer allocates local C++ object in the heap when
10070  * UseAfterReturn mode is enabled.
10071  * This method returns address that can be used for comparisons with
10072  * addresses into the JS stack. When neither simulator nor ASAN's
10073  * UseAfterReturn is enabled, then the address returned will be the address
10074  * of the C++ try catch handler itself.
10075  */
10076  static void* JSStackComparableAddress(TryCatch* handler) {
10077  if (handler == nullptr) return nullptr;
10078  return handler->js_stack_comparable_address_;
10079  }
10080 
10081  TryCatch(const TryCatch&) = delete;
10082  void operator=(const TryCatch&) = delete;
10083 
10084  private:
10085  // Declaring operator new and delete as deleted is not spec compliant.
10086  // Therefore declare them private instead to disable dynamic alloc
10087  void* operator new(size_t size);
10088  void* operator new[](size_t size);
10089  void operator delete(void*, size_t);
10090  void operator delete[](void*, size_t);
10091 
10092  void ResetInternal();
10093 
10094  internal::Isolate* isolate_;
10095  TryCatch* next_;
10096  void* exception_;
10097  void* message_obj_;
10098  void* js_stack_comparable_address_;
10099  bool is_verbose_ : 1;
10100  bool can_continue_ : 1;
10101  bool capture_message_ : 1;
10102  bool rethrow_ : 1;
10103  bool has_terminated_ : 1;
10104 
10105  friend class internal::Isolate;
10106 };
10107 
10108 
10109 // --- Context ---
10110 
10111 
10112 /**
10113  * A container for extension names.
10114  */
10116  public:
10117  ExtensionConfiguration() : name_count_(0), names_(nullptr) {}
10118  ExtensionConfiguration(int name_count, const char* names[])
10119  : name_count_(name_count), names_(names) { }
10120 
10121  const char** begin() const { return &names_[0]; }
10122  const char** end() const { return &names_[name_count_]; }
10123 
10124  private:
10125  const int name_count_;
10126  const char** names_;
10127 };
10128 
10129 /**
10130  * A sandboxed execution context with its own set of built-in objects
10131  * and functions.
10132  */
10134  public:
10135  /**
10136  * Returns the global proxy object.
10137  *
10138  * Global proxy object is a thin wrapper whose prototype points to actual
10139  * context's global object with the properties like Object, etc. This is done
10140  * that way for security reasons (for more details see
10141  * https://wiki.mozilla.org/Gecko:SplitWindow).
10142  *
10143  * Please note that changes to global proxy object prototype most probably
10144  * would break VM---v8 expects only global object as a prototype of global
10145  * proxy object.
10146  */
10147  Local<Object> Global();
10148 
10149  /**
10150  * Detaches the global object from its context before
10151  * the global object can be reused to create a new context.
10152  */
10153  void DetachGlobal();
10154 
10155  /**
10156  * Creates a new context and returns a handle to the newly allocated
10157  * context.
10158  *
10159  * \param isolate The isolate in which to create the context.
10160  *
10161  * \param extensions An optional extension configuration containing
10162  * the extensions to be installed in the newly created context.
10163  *
10164  * \param global_template An optional object template from which the
10165  * global object for the newly created context will be created.
10166  *
10167  * \param global_object An optional global object to be reused for
10168  * the newly created context. This global object must have been
10169  * created by a previous call to Context::New with the same global
10170  * template. The state of the global object will be completely reset
10171  * and only object identify will remain.
10172  */
10173  static Local<Context> New(
10174  Isolate* isolate, ExtensionConfiguration* extensions = nullptr,
10176  MaybeLocal<Value> global_object = MaybeLocal<Value>(),
10177  DeserializeInternalFieldsCallback internal_fields_deserializer =
10179  MicrotaskQueue* microtask_queue = nullptr);
10180 
10181  /**
10182  * Create a new context from a (non-default) context snapshot. There
10183  * is no way to provide a global object template since we do not create
10184  * a new global object from template, but we can reuse a global object.
10185  *
10186  * \param isolate See v8::Context::New.
10187  *
10188  * \param context_snapshot_index The index of the context snapshot to
10189  * deserialize from. Use v8::Context::New for the default snapshot.
10190  *
10191  * \param embedder_fields_deserializer Optional callback to deserialize
10192  * internal fields. It should match the SerializeInternalFieldCallback used
10193  * to serialize.
10194  *
10195  * \param extensions See v8::Context::New.
10196  *
10197  * \param global_object See v8::Context::New.
10198  */
10200  Isolate* isolate, size_t context_snapshot_index,
10201  DeserializeInternalFieldsCallback embedder_fields_deserializer =
10203  ExtensionConfiguration* extensions = nullptr,
10204  MaybeLocal<Value> global_object = MaybeLocal<Value>(),
10205  MicrotaskQueue* microtask_queue = nullptr);
10206 
10207  /**
10208  * Returns an global object that isn't backed by an actual context.
10209  *
10210  * The global template needs to have access checks with handlers installed.
10211  * If an existing global object is passed in, the global object is detached
10212  * from its context.
10213  *
10214  * Note that this is different from a detached context where all accesses to
10215  * the global proxy will fail. Instead, the access check handlers are invoked.
10216  *
10217  * It is also not possible to detach an object returned by this method.
10218  * Instead, the access check handlers need to return nothing to achieve the
10219  * same effect.
10220  *
10221  * It is possible, however, to create a new context from the global object
10222  * returned by this method.
10223  */
10225  Isolate* isolate, Local<ObjectTemplate> global_template,
10226  MaybeLocal<Value> global_object = MaybeLocal<Value>());
10227 
10228  /**
10229  * Sets the security token for the context. To access an object in
10230  * another context, the security tokens must match.
10231  */
10232  void SetSecurityToken(Local<Value> token);
10233 
10234  /** Restores the security token to the default value. */
10235  void UseDefaultSecurityToken();
10236 
10237  /** Returns the security token of this context.*/
10239 
10240  /**
10241  * Enter this context. After entering a context, all code compiled
10242  * and run is compiled and run in this context. If another context
10243  * is already entered, this old context is saved so it can be
10244  * restored when the new context is exited.
10245  */
10246  void Enter();
10247 
10248  /**
10249  * Exit this context. Exiting the current context restores the
10250  * context that was in place when entering the current context.
10251  */
10252  void Exit();
10253 
10254  /** Returns an isolate associated with a current context. */
10255  Isolate* GetIsolate();
10256 
10257  /**
10258  * The field at kDebugIdIndex used to be reserved for the inspector.
10259  * It now serves no purpose.
10260  */
10262 
10263  /**
10264  * Return the number of fields allocated for embedder data.
10265  */
10266  uint32_t GetNumberOfEmbedderDataFields();
10267 
10268  /**
10269  * Gets the embedder data with the given index, which must have been set by a
10270  * previous call to SetEmbedderData with the same index.
10271  */
10272  V8_INLINE Local<Value> GetEmbedderData(int index);
10273 
10274  /**
10275  * Gets the binding object used by V8 extras. Extra natives get a reference
10276  * to this object and can use it to "export" functionality by adding
10277  * properties. Extra natives can also "import" functionality by accessing
10278  * properties added by the embedder using the V8 API.
10279  */
10281 
10282  /**
10283  * Sets the embedder data with the given index, growing the data as
10284  * needed. Note that index 0 currently has a special meaning for Chrome's
10285  * debugger.
10286  */
10287  void SetEmbedderData(int index, Local<Value> value);
10288 
10289  /**
10290  * Gets a 2-byte-aligned native pointer from the embedder data with the given
10291  * index, which must have been set by a previous call to
10292  * SetAlignedPointerInEmbedderData with the same index. Note that index 0
10293  * currently has a special meaning for Chrome's debugger.
10294  */
10296 
10297  /**
10298  * Sets a 2-byte-aligned native pointer in the embedder data with the given
10299  * index, growing the data as needed. Note that index 0 currently has a
10300  * special meaning for Chrome's debugger.
10301  */
10302  void SetAlignedPointerInEmbedderData(int index, void* value);
10303 
10304  /**
10305  * Control whether code generation from strings is allowed. Calling
10306  * this method with false will disable 'eval' and the 'Function'
10307  * constructor for code running in this context. If 'eval' or the
10308  * 'Function' constructor are used an exception will be thrown.
10309  *
10310  * If code generation from strings is not allowed the
10311  * V8::AllowCodeGenerationFromStrings callback will be invoked if
10312  * set before blocking the call to 'eval' or the 'Function'
10313  * constructor. If that callback returns true, the call will be
10314  * allowed, otherwise an exception will be thrown. If no callback is
10315  * set an exception will be thrown.
10316  */
10317  void AllowCodeGenerationFromStrings(bool allow);
10318 
10319  /**
10320  * Returns true if code generation from strings is allowed for the context.
10321  * For more details see AllowCodeGenerationFromStrings(bool) documentation.
10322  */
10324 
10325  /**
10326  * Sets the error description for the exception that is thrown when
10327  * code generation from strings is not allowed and 'eval' or the 'Function'
10328  * constructor are called.
10329  */
10331 
10332  /**
10333  * Return data that was previously attached to the context snapshot via
10334  * SnapshotCreator, and removes the reference to it.
10335  * Repeated call with the same index returns an empty MaybeLocal.
10336  */
10337  template <class T>
10338  V8_INLINE MaybeLocal<T> GetDataFromSnapshotOnce(size_t index);
10339 
10340  /**
10341  * If callback is set, abort any attempt to execute JavaScript in this
10342  * context, call the specified callback, and throw an exception.
10343  * To unset abort, pass nullptr as callback.
10344  */
10345  typedef void (*AbortScriptExecutionCallback)(Isolate* isolate,
10346  Local<Context> context);
10348 
10349  /**
10350  * Stack-allocated class which sets the execution context for all
10351  * operations executed within a local scope.
10352  */
10353  class Scope {
10354  public:
10355  explicit V8_INLINE Scope(Local<Context> context) : context_(context) {
10356  context_->Enter();
10357  }
10358  V8_INLINE ~Scope() { context_->Exit(); }
10359 
10360  private:
10361  Local<Context> context_;
10362  };
10363 
10364  /**
10365  * Stack-allocated class to support the backup incumbent settings object
10366  * stack.
10367  * https://html.spec.whatwg.org/multipage/webappapis.html#backup-incumbent-settings-object-stack
10368  */
10369  class V8_EXPORT BackupIncumbentScope final {
10370  public:
10371  /**
10372  * |backup_incumbent_context| is pushed onto the backup incumbent settings
10373  * object stack.
10374  */
10375  explicit BackupIncumbentScope(Local<Context> backup_incumbent_context);
10377 
10378  /**
10379  * Returns address that is comparable with JS stack address. Note that JS
10380  * stack may be allocated separately from the native stack. See also
10381  * |TryCatch::JSStackComparableAddress| for details.
10382  */
10383  uintptr_t JSStackComparableAddress() const {
10384  return js_stack_comparable_address_;
10385  }
10386 
10387  private:
10388  friend class internal::Isolate;
10389 
10390  Local<Context> backup_incumbent_context_;
10391  uintptr_t js_stack_comparable_address_ = 0;
10392  const BackupIncumbentScope* prev_ = nullptr;
10393  };
10394 
10395  private:
10396  friend class Value;
10397  friend class Script;
10398  friend class Object;
10399  friend class Function;
10400 
10401  internal::Address* GetDataFromSnapshotOnce(size_t index);
10402  Local<Value> SlowGetEmbedderData(int index);
10403  void* SlowGetAlignedPointerFromEmbedderData(int index);
10404 };
10405 
10406 
10407 /**
10408  * Multiple threads in V8 are allowed, but only one thread at a time is allowed
10409  * to use any given V8 isolate, see the comments in the Isolate class. The
10410  * definition of 'using a V8 isolate' includes accessing handles or holding onto
10411  * object pointers obtained from V8 handles while in the particular V8 isolate.
10412  * It is up to the user of V8 to ensure, perhaps with locking, that this
10413  * constraint is not violated. In addition to any other synchronization
10414  * mechanism that may be used, the v8::Locker and v8::Unlocker classes must be
10415  * used to signal thread switches to V8.
10416  *
10417  * v8::Locker is a scoped lock object. While it's active, i.e. between its
10418  * construction and destruction, the current thread is allowed to use the locked
10419  * isolate. V8 guarantees that an isolate can be locked by at most one thread at
10420  * any time. In other words, the scope of a v8::Locker is a critical section.
10421  *
10422  * Sample usage:
10423 * \code
10424  * ...
10425  * {
10426  * v8::Locker locker(isolate);
10427  * v8::Isolate::Scope isolate_scope(isolate);
10428  * ...
10429  * // Code using V8 and isolate goes here.
10430  * ...
10431  * } // Destructor called here
10432  * \endcode
10433  *
10434  * If you wish to stop using V8 in a thread A you can do this either by
10435  * destroying the v8::Locker object as above or by constructing a v8::Unlocker
10436  * object:
10437  *
10438  * \code
10439  * {
10440  * isolate->Exit();
10441  * v8::Unlocker unlocker(isolate);
10442  * ...
10443  * // Code not using V8 goes here while V8 can run in another thread.
10444  * ...
10445  * } // Destructor called here.
10446  * isolate->Enter();
10447  * \endcode
10448  *
10449  * The Unlocker object is intended for use in a long-running callback from V8,
10450  * where you want to release the V8 lock for other threads to use.
10451  *
10452  * The v8::Locker is a recursive lock, i.e. you can lock more than once in a
10453  * given thread. This can be useful if you have code that can be called either
10454  * from code that holds the lock or from code that does not. The Unlocker is
10455  * not recursive so you can not have several Unlockers on the stack at once, and
10456  * you can not use an Unlocker in a thread that is not inside a Locker's scope.
10457  *
10458  * An unlocker will unlock several lockers if it has to and reinstate the
10459  * correct depth of locking on its destruction, e.g.:
10460  *
10461  * \code
10462  * // V8 not locked.
10463  * {
10464  * v8::Locker locker(isolate);
10465  * Isolate::Scope isolate_scope(isolate);
10466  * // V8 locked.
10467  * {
10468  * v8::Locker another_locker(isolate);
10469  * // V8 still locked (2 levels).
10470  * {
10471  * isolate->Exit();
10472  * v8::Unlocker unlocker(isolate);
10473  * // V8 not locked.
10474  * }
10475  * isolate->Enter();
10476  * // V8 locked again (2 levels).
10477  * }
10478  * // V8 still locked (1 level).
10479  * }
10480  * // V8 Now no longer locked.
10481  * \endcode
10482  */
10484  public:
10485  /**
10486  * Initialize Unlocker for a given Isolate.
10487  */
10488  V8_INLINE explicit Unlocker(Isolate* isolate) { Initialize(isolate); }
10489 
10490  ~Unlocker();
10491  private:
10492  void Initialize(Isolate* isolate);
10493 
10494  internal::Isolate* isolate_;
10495 };
10496 
10497 
10499  public:
10500  /**
10501  * Initialize Locker for a given Isolate.
10502  */
10503  V8_INLINE explicit Locker(Isolate* isolate) { Initialize(isolate); }
10504 
10505  ~Locker();
10506 
10507  /**
10508  * Returns whether or not the locker for a given isolate, is locked by the
10509  * current thread.
10510  */
10511  static bool IsLocked(Isolate* isolate);
10512 
10513  /**
10514  * Returns whether v8::Locker is being used by this V8 instance.
10515  */
10516  static bool IsActive();
10517 
10518  // Disallow copying and assigning.
10519  Locker(const Locker&) = delete;
10520  void operator=(const Locker&) = delete;
10521 
10522  private:
10523  void Initialize(Isolate* isolate);
10524 
10525  bool has_lock_;
10526  bool top_level_;
10527  internal::Isolate* isolate_;
10528 };
10529 
10530 /**
10531  * Various helpers for skipping over V8 frames in a given stack.
10532  *
10533  * The unwinder API is only supported on the x64, ARM64 and ARM32 architectures.
10534  */
10536  public:
10537  /**
10538  * Attempt to unwind the stack to the most recent C++ frame. This function is
10539  * signal-safe and does not access any V8 state and thus doesn't require an
10540  * Isolate.
10541  *
10542  * The unwinder needs to know the location of the JS Entry Stub (a piece of
10543  * code that is run when C++ code calls into generated JS code). This is used
10544  * for edge cases where the current frame is being constructed or torn down
10545  * when the stack sample occurs.
10546  *
10547  * The unwinder also needs the virtual memory range of all possible V8 code
10548  * objects. There are two ranges required - the heap code range and the range
10549  * for code embedded in the binary. The V8 API provides all required inputs
10550  * via an UnwindState object through the Isolate::GetUnwindState() API. These
10551  * values will not change after Isolate initialization, so the same
10552  * |unwind_state| can be used for multiple calls.
10553  *
10554  * \param unwind_state Input state for the Isolate that the stack comes from.
10555  * \param register_state The current registers. This is an in-out param that
10556  * will be overwritten with the register values after unwinding, on success.
10557  * \param stack_base The resulting stack pointer and frame pointer values are
10558  * bounds-checked against the stack_base and the original stack pointer value
10559  * to ensure that they are valid locations in the given stack. If these values
10560  * or any intermediate frame pointer values used during unwinding are ever out
10561  * of these bounds, unwinding will fail.
10562  *
10563  * \return True on success.
10564  */
10565  // TODO(petermarshall): Remove this API
10566  V8_DEPRECATE_SOON("Use entry_stubs + code_pages version.")
10567  static bool TryUnwindV8Frames(const UnwindState& unwind_state,
10568  RegisterState* register_state,
10569  const void* stack_base);
10570 
10571  /**
10572  * The same as above, but is available on x64, ARM64 and ARM32.
10573  *
10574  * \param code_pages A list of all of the ranges in which V8 has allocated
10575  * executable code. The caller should obtain this list by calling
10576  * Isolate::CopyCodePages() during the same interrupt/thread suspension that
10577  * captures the stack.
10578  */
10579  static bool TryUnwindV8Frames(const JSEntryStubs& entry_stubs,
10580  size_t code_pages_length,
10581  const MemoryRange* code_pages,
10582  RegisterState* register_state,
10583  const void* stack_base);
10584 
10585  /**
10586  * Whether the PC is within the V8 code range represented by code_range or
10587  * embedded_code_range in |unwind_state|.
10588  *
10589  * If this returns false, then calling UnwindV8Frames() with the same PC
10590  * and unwind_state will always fail. If it returns true, then unwinding may
10591  * (but not necessarily) be successful.
10592  */
10593  // TODO(petermarshall): Remove this API
10594  V8_DEPRECATE_SOON("Use code_pages version.")
10595  static bool PCIsInV8(const UnwindState& unwind_state, void* pc);
10596 
10597  /**
10598  * The same as above, but is available on x64, ARM64 and ARM32. See the
10599  * comment on TryUnwindV8Frames.
10600  */
10601  static bool PCIsInV8(size_t code_pages_length, const MemoryRange* code_pages,
10602  void* pc);
10603 };
10604 
10605 // --- Implementation ---
10606 
10607 template <class T>
10608 Local<T> Local<T>::New(Isolate* isolate, Local<T> that) {
10609  return New(isolate, that.val_);
10610 }
10611 
10612 template <class T>
10613 Local<T> Local<T>::New(Isolate* isolate, const PersistentBase<T>& that) {
10614  return New(isolate, that.val_);
10615 }
10616 
10617 template <class T>
10618 Local<T> Local<T>::New(Isolate* isolate, const TracedReferenceBase<T>& that) {
10619  return New(isolate, that.val_);
10620 }
10621 
10622 template <class T>
10623 Local<T> Local<T>::New(Isolate* isolate, T* that) {
10624  if (that == nullptr) return Local<T>();
10625  T* that_ptr = that;
10626  internal::Address* p = reinterpret_cast<internal::Address*>(that_ptr);
10627  return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
10628  reinterpret_cast<internal::Isolate*>(isolate), *p)));
10629 }
10630 
10631 
10632 template<class T>
10633 template<class S>
10634 void Eternal<T>::Set(Isolate* isolate, Local<S> handle) {
10635  TYPE_CHECK(T, S);
10636  val_ = reinterpret_cast<T*>(
10637  V8::Eternalize(isolate, reinterpret_cast<Value*>(*handle)));
10638 }
10639 
10640 template <class T>
10641 Local<T> Eternal<T>::Get(Isolate* isolate) const {
10642  // The eternal handle will never go away, so as with the roots, we don't even
10643  // need to open a handle.
10644  return Local<T>(val_);
10645 }
10646 
10647 
10648 template <class T>
10650  if (V8_UNLIKELY(val_ == nullptr)) V8::ToLocalEmpty();
10651  return Local<T>(val_);
10652 }
10653 
10654 
10655 template <class T>
10656 void* WeakCallbackInfo<T>::GetInternalField(int index) const {
10657 #ifdef V8_ENABLE_CHECKS
10658  if (index < 0 || index >= kEmbedderFieldsInWeakCallback) {
10659  V8::InternalFieldOutOfBounds(index);
10660  }
10661 #endif
10662  return embedder_fields_[index];
10663 }
10664 
10665 
10666 template <class T>
10667 T* PersistentBase<T>::New(Isolate* isolate, T* that) {
10668  if (that == nullptr) return nullptr;
10669  internal::Address* p = reinterpret_cast<internal::Address*>(that);
10670  return reinterpret_cast<T*>(
10671  V8::GlobalizeReference(reinterpret_cast<internal::Isolate*>(isolate),
10672  p));
10673 }
10674 
10675 
10676 template <class T, class M>
10677 template <class S, class M2>
10678 void Persistent<T, M>::Copy(const Persistent<S, M2>& that) {
10679  TYPE_CHECK(T, S);
10680  this->Reset();
10681  if (that.IsEmpty()) return;
10682  internal::Address* p = reinterpret_cast<internal::Address*>(that.val_);
10683  this->val_ = reinterpret_cast<T*>(V8::CopyGlobalReference(p));
10684  M::Copy(that, this);
10685 }
10686 
10687 template <class T>
10688 bool PersistentBase<T>::IsWeak() const {
10689  typedef internal::Internals I;
10690  if (this->IsEmpty()) return false;
10691  return I::GetNodeState(reinterpret_cast<internal::Address*>(this->val_)) ==
10693 }
10694 
10695 
10696 template <class T>
10697 void PersistentBase<T>::Reset() {
10698  if (this->IsEmpty()) return;
10699  V8::DisposeGlobal(reinterpret_cast<internal::Address*>(this->val_));
10700  val_ = nullptr;
10701 }
10702 
10703 
10704 template <class T>
10705 template <class S>
10706 void PersistentBase<T>::Reset(Isolate* isolate, const Local<S>& other) {
10707  TYPE_CHECK(T, S);
10708  Reset();
10709  if (other.IsEmpty()) return;
10710  this->val_ = New(isolate, other.val_);
10711 }
10712 
10713 
10714 template <class T>
10715 template <class S>
10716 void PersistentBase<T>::Reset(Isolate* isolate,
10717  const PersistentBase<S>& other) {
10718  TYPE_CHECK(T, S);
10719  Reset();
10720  if (other.IsEmpty()) return;
10721  this->val_ = New(isolate, other.val_);
10722 }
10723 
10724 
10725 template <class T>
10726 template <typename P>
10728  P* parameter, typename WeakCallbackInfo<P>::Callback callback,
10729  WeakCallbackType type) {
10730  typedef typename WeakCallbackInfo<void>::Callback Callback;
10731  V8::MakeWeak(reinterpret_cast<internal::Address*>(this->val_), parameter,
10732  reinterpret_cast<Callback>(callback), type);
10733 }
10734 
10735 template <class T>
10737  V8::MakeWeak(reinterpret_cast<internal::Address**>(&this->val_));
10738 }
10739 
10740 template <class T>
10741 template <typename P>
10742 P* PersistentBase<T>::ClearWeak() {
10743  return reinterpret_cast<P*>(
10744  V8::ClearWeak(reinterpret_cast<internal::Address*>(this->val_)));
10745 }
10746 
10747 template <class T>
10748 void PersistentBase<T>::AnnotateStrongRetainer(const char* label) {
10749  V8::AnnotateStrongRetainer(reinterpret_cast<internal::Address*>(this->val_),
10750  label);
10751 }
10752 
10753 template <class T>
10754 void PersistentBase<T>::SetWrapperClassId(uint16_t class_id) {
10755  typedef internal::Internals I;
10756  if (this->IsEmpty()) return;
10757  internal::Address* obj = reinterpret_cast<internal::Address*>(this->val_);
10758  uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
10759  *reinterpret_cast<uint16_t*>(addr) = class_id;
10760 }
10761 
10762 
10763 template <class T>
10764 uint16_t PersistentBase<T>::WrapperClassId() const {
10765  typedef internal::Internals I;
10766  if (this->IsEmpty()) return 0;
10767  internal::Address* obj = reinterpret_cast<internal::Address*>(this->val_);
10768  uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
10769  return *reinterpret_cast<uint16_t*>(addr);
10770 }
10771 
10772 template <class T>
10773 Global<T>::Global(Global&& other) : PersistentBase<T>(other.val_) {
10774  if (other.val_ != nullptr) {
10775  V8::MoveGlobalReference(reinterpret_cast<internal::Address**>(&other.val_),
10776  reinterpret_cast<internal::Address**>(&this->val_));
10777  other.val_ = nullptr;
10778  }
10779 }
10780 
10781 template <class T>
10782 template <class S>
10783 Global<T>& Global<T>::operator=(Global<S>&& rhs) {
10784  TYPE_CHECK(T, S);
10785  if (this != &rhs) {
10786  this->Reset();
10787  if (rhs.val_ != nullptr) {
10788  this->val_ = rhs.val_;
10789  V8::MoveGlobalReference(
10790  reinterpret_cast<internal::Address**>(&rhs.val_),
10791  reinterpret_cast<internal::Address**>(&this->val_));
10792  rhs.val_ = nullptr;
10793  }
10794  }
10795  return *this;
10796 }
10797 
10798 template <class T>
10799 T* TracedReferenceBase<T>::New(Isolate* isolate, T* that, void* slot,
10800  DestructionMode destruction_mode) {
10801  if (that == nullptr) return nullptr;
10802  internal::Address* p = reinterpret_cast<internal::Address*>(that);
10803  return reinterpret_cast<T*>(V8::GlobalizeTracedReference(
10804  reinterpret_cast<internal::Isolate*>(isolate), p,
10805  reinterpret_cast<internal::Address*>(slot),
10806  destruction_mode == kWithDestructor));
10807 }
10808 
10809 template <class T>
10811  if (IsEmpty()) return;
10812  V8::DisposeTracedGlobal(reinterpret_cast<internal::Address*>(val_));
10813  val_ = nullptr;
10814 }
10815 
10816 template <class T>
10817 template <class S>
10818 void TracedGlobal<T>::Reset(Isolate* isolate, const Local<S>& other) {
10819  TYPE_CHECK(T, S);
10820  Reset();
10821  if (other.IsEmpty()) return;
10822  this->val_ = this->New(isolate, other.val_, &this->val_,
10823  TracedReferenceBase<T>::kWithDestructor);
10824 }
10825 
10826 template <class T>
10827 template <class S>
10829  TYPE_CHECK(T, S);
10830  *this = std::move(rhs.template As<T>());
10831  return *this;
10832 }
10833 
10834 template <class T>
10835 template <class S>
10837  TYPE_CHECK(T, S);
10838  *this = rhs.template As<T>();
10839  return *this;
10840 }
10841 
10842 template <class T>
10844  if (this != &rhs) {
10845  V8::MoveTracedGlobalReference(
10846  reinterpret_cast<internal::Address**>(&rhs.val_),
10847  reinterpret_cast<internal::Address**>(&this->val_));
10848  }
10849  return *this;
10850 }
10851 
10852 template <class T>
10854  if (this != &rhs) {
10855  this->Reset();
10856  if (rhs.val_ != nullptr) {
10857  V8::CopyTracedGlobalReference(
10858  reinterpret_cast<const internal::Address* const*>(&rhs.val_),
10859  reinterpret_cast<internal::Address**>(&this->val_));
10860  }
10861  }
10862  return *this;
10863 }
10864 
10865 template <class T>
10866 template <class S>
10867 void TracedReference<T>::Reset(Isolate* isolate, const Local<S>& other) {
10868  TYPE_CHECK(T, S);
10869  Reset();
10870  if (other.IsEmpty()) return;
10871  this->val_ = this->New(isolate, other.val_, &this->val_,
10872  TracedReferenceBase<T>::kWithoutDestructor);
10873 }
10874 
10875 template <class T>
10876 template <class S>
10878  TYPE_CHECK(T, S);
10879  *this = std::move(rhs.template As<T>());
10880  return *this;
10881 }
10882 
10883 template <class T>
10884 template <class S>
10886  const TracedReference<S>& rhs) {
10887  TYPE_CHECK(T, S);
10888  *this = rhs.template As<T>();
10889  return *this;
10890 }
10891 
10892 template <class T>
10894  if (this != &rhs) {
10895  V8::MoveTracedGlobalReference(
10896  reinterpret_cast<internal::Address**>(&rhs.val_),
10897  reinterpret_cast<internal::Address**>(&this->val_));
10898  }
10899  return *this;
10900 }
10901 
10902 template <class T>
10904  if (this != &rhs) {
10905  this->Reset();
10906  if (rhs.val_ != nullptr) {
10907  V8::CopyTracedGlobalReference(
10908  reinterpret_cast<const internal::Address* const*>(&rhs.val_),
10909  reinterpret_cast<internal::Address**>(&this->val_));
10910  }
10911  }
10912  return *this;
10913 }
10914 
10915 template <class T>
10916 void TracedReferenceBase<T>::SetWrapperClassId(uint16_t class_id) {
10917  typedef internal::Internals I;
10918  if (IsEmpty()) return;
10919  internal::Address* obj = reinterpret_cast<internal::Address*>(val_);
10920  uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
10921  *reinterpret_cast<uint16_t*>(addr) = class_id;
10922 }
10923 
10924 template <class T>
10925 uint16_t TracedReferenceBase<T>::WrapperClassId() const {
10926  typedef internal::Internals I;
10927  if (IsEmpty()) return 0;
10928  internal::Address* obj = reinterpret_cast<internal::Address*>(val_);
10929  uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
10930  return *reinterpret_cast<uint16_t*>(addr);
10931 }
10932 
10933 template <class T>
10935  void* parameter, typename WeakCallbackInfo<void>::Callback callback) {
10936  V8::SetFinalizationCallbackTraced(
10937  reinterpret_cast<internal::Address*>(this->val_), parameter, callback);
10938 }
10939 
10940 template <class T>
10942  void* parameter, typename WeakCallbackInfo<void>::Callback callback) {
10943  V8::SetFinalizationCallbackTraced(
10944  reinterpret_cast<internal::Address*>(this->val_), parameter, callback);
10945 }
10946 
10947 template <typename T>
10948 ReturnValue<T>::ReturnValue(internal::Address* slot) : value_(slot) {}
10949 
10950 template <typename T>
10951 template <typename S>
10952 void ReturnValue<T>::Set(const Global<S>& handle) {
10953  TYPE_CHECK(T, S);
10954  if (V8_UNLIKELY(handle.IsEmpty())) {
10955  *value_ = GetDefaultValue();
10956  } else {
10957  *value_ = *reinterpret_cast<internal::Address*>(*handle);
10958  }
10959 }
10960 
10961 template <typename T>
10962 template <typename S>
10963 void ReturnValue<T>::Set(const TracedReferenceBase<S>& handle) {
10964  TYPE_CHECK(T, S);
10965  if (V8_UNLIKELY(handle.IsEmpty())) {
10966  *value_ = GetDefaultValue();
10967  } else {
10968  *value_ = *reinterpret_cast<internal::Address*>(handle.val_);
10969  }
10970 }
10971 
10972 template <typename T>
10973 template <typename S>
10974 void ReturnValue<T>::Set(const Local<S> handle) {
10975  TYPE_CHECK(T, S);
10976  if (V8_UNLIKELY(handle.IsEmpty())) {
10977  *value_ = GetDefaultValue();
10978  } else {
10979  *value_ = *reinterpret_cast<internal::Address*>(*handle);
10980  }
10981 }
10982 
10983 template<typename T>
10984 void ReturnValue<T>::Set(double i) {
10985  TYPE_CHECK(T, Number);
10987 }
10988 
10989 template<typename T>
10990 void ReturnValue<T>::Set(int32_t i) {
10991  TYPE_CHECK(T, Integer);
10992  typedef internal::Internals I;
10993  if (V8_LIKELY(I::IsValidSmi(i))) {
10994  *value_ = I::IntToSmi(i);
10995  return;
10996  }
10998 }
10999 
11000 template<typename T>
11001 void ReturnValue<T>::Set(uint32_t i) {
11002  TYPE_CHECK(T, Integer);
11003  // Can't simply use INT32_MAX here for whatever reason.
11004  bool fits_into_int32_t = (i & (1U << 31)) == 0;
11005  if (V8_LIKELY(fits_into_int32_t)) {
11006  Set(static_cast<int32_t>(i));
11007  return;
11008  }
11010 }
11011 
11012 template<typename T>
11013 void ReturnValue<T>::Set(bool value) {
11014  TYPE_CHECK(T, Boolean);
11015  typedef internal::Internals I;
11016  int root_index;
11017  if (value) {
11018  root_index = I::kTrueValueRootIndex;
11019  } else {
11020  root_index = I::kFalseValueRootIndex;
11021  }
11022  *value_ = *I::GetRoot(GetIsolate(), root_index);
11023 }
11024 
11025 template<typename T>
11026 void ReturnValue<T>::SetNull() {
11027  TYPE_CHECK(T, Primitive);
11028  typedef internal::Internals I;
11030 }
11031 
11032 template<typename T>
11034  TYPE_CHECK(T, Primitive);
11035  typedef internal::Internals I;
11037 }
11038 
11039 template<typename T>
11041  TYPE_CHECK(T, String);
11042  typedef internal::Internals I;
11044 }
11045 
11046 template <typename T>
11048  // Isolate is always the pointer below the default value on the stack.
11049  return *reinterpret_cast<Isolate**>(&value_[-2]);
11050 }
11051 
11052 template <typename T>
11053 Local<Value> ReturnValue<T>::Get() const {
11054  typedef internal::Internals I;
11056  return Local<Value>(*Undefined(GetIsolate()));
11057  return Local<Value>::New(GetIsolate(), reinterpret_cast<Value*>(value_));
11058 }
11059 
11060 template <typename T>
11061 template <typename S>
11062 void ReturnValue<T>::Set(S* whatever) {
11063  // Uncompilable to prevent inadvertent misuse.
11064  TYPE_CHECK(S*, Primitive);
11065 }
11066 
11067 template <typename T>
11068 internal::Address ReturnValue<T>::GetDefaultValue() {
11069  // Default value is always the pointer below value_ on the stack.
11070  return value_[-1];
11071 }
11072 
11073 template <typename T>
11075  internal::Address* values,
11076  int length)
11077  : implicit_args_(implicit_args), values_(values), length_(length) {}
11078 
11079 template<typename T>
11081  if (i < 0 || length_ <= i) return Local<Value>(*Undefined(GetIsolate()));
11082  return Local<Value>(reinterpret_cast<Value*>(values_ - i));
11083 }
11084 
11085 
11086 template<typename T>
11088  return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
11089 }
11090 
11091 
11092 template<typename T>
11094  return Local<Object>(reinterpret_cast<Object*>(
11096 }
11097 
11098 template <typename T>
11100  return Local<Value>(
11101  reinterpret_cast<Value*>(&implicit_args_[kNewTargetIndex]));
11102 }
11103 
11104 template <typename T>
11106  return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
11107 }
11108 
11109 
11110 template<typename T>
11112  return *reinterpret_cast<Isolate**>(&implicit_args_[kIsolateIndex]);
11113 }
11114 
11115 
11116 template<typename T>
11119 }
11120 
11121 
11122 template<typename T>
11124  return !NewTarget()->IsUndefined();
11125 }
11126 
11127 
11128 template<typename T>
11129 int FunctionCallbackInfo<T>::Length() const {
11130  return length_;
11131 }
11132 
11134  Local<Integer> resource_line_offset,
11135  Local<Integer> resource_column_offset,
11136  Local<Boolean> resource_is_shared_cross_origin,
11137  Local<Integer> script_id,
11138  Local<Value> source_map_url,
11139  Local<Boolean> resource_is_opaque,
11140  Local<Boolean> is_wasm, Local<Boolean> is_module,
11141  Local<PrimitiveArray> host_defined_options)
11142  : resource_name_(resource_name),
11143  resource_line_offset_(resource_line_offset),
11144  resource_column_offset_(resource_column_offset),
11145  options_(!resource_is_shared_cross_origin.IsEmpty() &&
11146  resource_is_shared_cross_origin->IsTrue(),
11147  !resource_is_opaque.IsEmpty() && resource_is_opaque->IsTrue(),
11148  !is_wasm.IsEmpty() && is_wasm->IsTrue(),
11149  !is_module.IsEmpty() && is_module->IsTrue()),
11150  script_id_(script_id),
11151  source_map_url_(source_map_url),
11152  host_defined_options_(host_defined_options) {}
11153 
11154 Local<Value> ScriptOrigin::ResourceName() const { return resource_name_; }
11155 
11157  return host_defined_options_;
11158 }
11159 
11161  return resource_line_offset_;
11162 }
11163 
11164 
11166  return resource_column_offset_;
11167 }
11168 
11169 
11170 Local<Integer> ScriptOrigin::ScriptID() const { return script_id_; }
11171 
11172 
11173 Local<Value> ScriptOrigin::SourceMapUrl() const { return source_map_url_; }
11174 
11176  CachedData* data)
11177  : source_string(string),
11178  resource_name(origin.ResourceName()),
11179  resource_line_offset(origin.ResourceLineOffset()),
11180  resource_column_offset(origin.ResourceColumnOffset()),
11181  resource_options(origin.Options()),
11182  source_map_url(origin.SourceMapUrl()),
11183  host_defined_options(origin.HostDefinedOptions()),
11184  cached_data(data) {}
11185 
11187  CachedData* data)
11188  : source_string(string), cached_data(data) {}
11189 
11190 
11192  delete cached_data;
11193 }
11194 
11195 
11197  const {
11198  return cached_data;
11199 }
11200 
11202  return resource_options;
11203 }
11204 
11205 Local<Boolean> Boolean::New(Isolate* isolate, bool value) {
11206  return value ? True(isolate) : False(isolate);
11207 }
11208 
11209 void Template::Set(Isolate* isolate, const char* name, Local<Data> value) {
11212  value);
11213 }
11214 
11216 #ifdef V8_ENABLE_CHECKS
11217  CheckCast(data);
11218 #endif
11219  return reinterpret_cast<FunctionTemplate*>(data);
11220 }
11221 
11223 #ifdef V8_ENABLE_CHECKS
11224  CheckCast(data);
11225 #endif
11226  return reinterpret_cast<ObjectTemplate*>(data);
11227 }
11228 
11230 #ifdef V8_ENABLE_CHECKS
11231  CheckCast(data);
11232 #endif
11233  return reinterpret_cast<Signature*>(data);
11234 }
11235 
11237 #ifdef V8_ENABLE_CHECKS
11238  CheckCast(data);
11239 #endif
11240  return reinterpret_cast<AccessorSignature*>(data);
11241 }
11242 
11244 #ifndef V8_ENABLE_CHECKS
11245  typedef internal::Address A;
11246  typedef internal::Internals I;
11247  A obj = *reinterpret_cast<A*>(this);
11248  // Fast path: If the object is a plain JSObject, which is the common case, we
11249  // know where to find the internal fields and can return the value directly.
11250  auto instance_type = I::GetInstanceType(obj);
11251  if (instance_type == I::kJSObjectType ||
11252  instance_type == I::kJSApiObjectType ||
11253  instance_type == I::kJSSpecialApiObjectType) {
11254  int offset = I::kJSObjectHeaderSize + (I::kEmbedderDataSlotSize * index);
11255  A value = I::ReadRawField<A>(obj, offset);
11256 #ifdef V8_COMPRESS_POINTERS
11257  // We read the full pointer value and then decompress it in order to avoid
11258  // dealing with potential endiannes issues.
11259  value = I::DecompressTaggedAnyField(obj, static_cast<int32_t>(value));
11260 #endif
11261  internal::Isolate* isolate =
11263  A* result = HandleScope::CreateHandle(isolate, value);
11264  return Local<Value>(reinterpret_cast<Value*>(result));
11265  }
11266 #endif
11267  return SlowGetInternalField(index);
11268 }
11269 
11270 
11272 #ifndef V8_ENABLE_CHECKS
11273  typedef internal::Address A;
11274  typedef internal::Internals I;
11275  A obj = *reinterpret_cast<A*>(this);
11276  // Fast path: If the object is a plain JSObject, which is the common case, we
11277  // know where to find the internal fields and can return the value directly.
11278  auto instance_type = I::GetInstanceType(obj);
11279  if (V8_LIKELY(instance_type == I::kJSObjectType ||
11280  instance_type == I::kJSApiObjectType ||
11281  instance_type == I::kJSSpecialApiObjectType)) {
11282  int offset = I::kJSObjectHeaderSize + (I::kEmbedderDataSlotSize * index);
11283  return I::ReadRawField<void*>(obj, offset);
11284  }
11285 #endif
11286  return SlowGetAlignedPointerFromInternalField(index);
11287 }
11288 
11289 String* String::Cast(v8::Value* value) {
11290 #ifdef V8_ENABLE_CHECKS
11291  CheckCast(value);
11292 #endif
11293  return static_cast<String*>(value);
11294 }
11295 
11296 
11298  typedef internal::Address S;
11299  typedef internal::Internals I;
11300  I::CheckInitialized(isolate);
11301  S* slot = I::GetRoot(isolate, I::kEmptyStringRootIndex);
11302  return Local<String>(reinterpret_cast<String*>(slot));
11303 }
11304 
11305 
11307  typedef internal::Address A;
11308  typedef internal::Internals I;
11309  A obj = *reinterpret_cast<const A*>(this);
11310 
11311  ExternalStringResource* result;
11313  void* value = I::ReadRawField<void*>(obj, I::kStringResourceOffset);
11314  result = reinterpret_cast<String::ExternalStringResource*>(value);
11315  } else {
11316  result = GetExternalStringResourceSlow();
11317  }
11318 #ifdef V8_ENABLE_CHECKS
11319  VerifyExternalStringResource(result);
11320 #endif
11321  return result;
11322 }
11323 
11324 
11326  String::Encoding* encoding_out) const {
11327  typedef internal::Address A;
11328  typedef internal::Internals I;
11329  A obj = *reinterpret_cast<const A*>(this);
11331  *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
11332  ExternalStringResourceBase* resource;
11333  if (type == I::kExternalOneByteRepresentationTag ||
11335  void* value = I::ReadRawField<void*>(obj, I::kStringResourceOffset);
11336  resource = static_cast<ExternalStringResourceBase*>(value);
11337  } else {
11338  resource = GetExternalStringResourceBaseSlow(encoding_out);
11339  }
11340 #ifdef V8_ENABLE_CHECKS
11341  VerifyExternalStringResourceBase(resource, *encoding_out);
11342 #endif
11343  return resource;
11344 }
11345 
11346 
11347 bool Value::IsUndefined() const {
11348 #ifdef V8_ENABLE_CHECKS
11349  return FullIsUndefined();
11350 #else
11351  return QuickIsUndefined();
11352 #endif
11353 }
11354 
11355 bool Value::QuickIsUndefined() const {
11356  typedef internal::Address A;
11357  typedef internal::Internals I;
11358  A obj = *reinterpret_cast<const A*>(this);
11359  if (!I::HasHeapObjectTag(obj)) return false;
11360  if (I::GetInstanceType(obj) != I::kOddballType) return false;
11362 }
11363 
11364 
11365 bool Value::IsNull() const {
11366 #ifdef V8_ENABLE_CHECKS
11367  return FullIsNull();
11368 #else
11369  return QuickIsNull();
11370 #endif
11371 }
11372 
11373 bool Value::QuickIsNull() const {
11374  typedef internal::Address A;
11375  typedef internal::Internals I;
11376  A obj = *reinterpret_cast<const A*>(this);
11377  if (!I::HasHeapObjectTag(obj)) return false;
11378  if (I::GetInstanceType(obj) != I::kOddballType) return false;
11379  return (I::GetOddballKind(obj) == I::kNullOddballKind);
11380 }
11381 
11382 bool Value::IsNullOrUndefined() const {
11383 #ifdef V8_ENABLE_CHECKS
11384  return FullIsNull() || FullIsUndefined();
11385 #else
11386  return QuickIsNullOrUndefined();
11387 #endif
11388 }
11389 
11390 bool Value::QuickIsNullOrUndefined() const {
11391  typedef internal::Address A;
11392  typedef internal::Internals I;
11393  A obj = *reinterpret_cast<const A*>(this);
11394  if (!I::HasHeapObjectTag(obj)) return false;
11395  if (I::GetInstanceType(obj) != I::kOddballType) return false;
11396  int kind = I::GetOddballKind(obj);
11397  return kind == I::kNullOddballKind || kind == I::kUndefinedOddballKind;
11398 }
11399 
11400 bool Value::IsString() const {
11401 #ifdef V8_ENABLE_CHECKS
11402  return FullIsString();
11403 #else
11404  return QuickIsString();
11405 #endif
11406 }
11407 
11408 bool Value::QuickIsString() const {
11409  typedef internal::Address A;
11410  typedef internal::Internals I;
11411  A obj = *reinterpret_cast<const A*>(this);
11412  if (!I::HasHeapObjectTag(obj)) return false;
11414 }
11415 
11416 
11417 template <class T> Value* Value::Cast(T* value) {
11418  return static_cast<Value*>(value);
11419 }
11420 
11421 
11423 #ifdef V8_ENABLE_CHECKS
11424  CheckCast(value);
11425 #endif
11426  return static_cast<Boolean*>(value);
11427 }
11428 
11429 
11430 Name* Name::Cast(v8::Value* value) {
11431 #ifdef V8_ENABLE_CHECKS
11432  CheckCast(value);
11433 #endif
11434  return static_cast<Name*>(value);
11435 }
11436 
11437 
11438 Symbol* Symbol::Cast(v8::Value* value) {
11439 #ifdef V8_ENABLE_CHECKS
11440  CheckCast(value);
11441 #endif
11442  return static_cast<Symbol*>(value);
11443 }
11444 
11445 
11447 #ifdef V8_ENABLE_CHECKS
11448  CheckCast(data);
11449 #endif
11450  return reinterpret_cast<Private*>(data);
11451 }
11452 
11453 
11454 Number* Number::Cast(v8::Value* value) {
11455 #ifdef V8_ENABLE_CHECKS
11456  CheckCast(value);
11457 #endif
11458  return static_cast<Number*>(value);
11459 }
11460 
11461 
11463 #ifdef V8_ENABLE_CHECKS
11464  CheckCast(value);
11465 #endif
11466  return static_cast<Integer*>(value);
11467 }
11468 
11469 
11470 Int32* Int32::Cast(v8::Value* value) {
11471 #ifdef V8_ENABLE_CHECKS
11472  CheckCast(value);
11473 #endif
11474  return static_cast<Int32*>(value);
11475 }
11476 
11477 
11478 Uint32* Uint32::Cast(v8::Value* value) {
11479 #ifdef V8_ENABLE_CHECKS
11480  CheckCast(value);
11481 #endif
11482  return static_cast<Uint32*>(value);
11483 }
11484 
11485 BigInt* BigInt::Cast(v8::Value* value) {
11486 #ifdef V8_ENABLE_CHECKS
11487  CheckCast(value);
11488 #endif
11489  return static_cast<BigInt*>(value);
11490 }
11491 
11492 Date* Date::Cast(v8::Value* value) {
11493 #ifdef V8_ENABLE_CHECKS
11494  CheckCast(value);
11495 #endif
11496  return static_cast<Date*>(value);
11497 }
11498 
11499 
11501 #ifdef V8_ENABLE_CHECKS
11502  CheckCast(value);
11503 #endif
11504  return static_cast<StringObject*>(value);
11505 }
11506 
11507 
11509 #ifdef V8_ENABLE_CHECKS
11510  CheckCast(value);
11511 #endif
11512  return static_cast<SymbolObject*>(value);
11513 }
11514 
11515 
11517 #ifdef V8_ENABLE_CHECKS
11518  CheckCast(value);
11519 #endif
11520  return static_cast<NumberObject*>(value);
11521 }
11522 
11524 #ifdef V8_ENABLE_CHECKS
11525  CheckCast(value);
11526 #endif
11527  return static_cast<BigIntObject*>(value);
11528 }
11529 
11531 #ifdef V8_ENABLE_CHECKS
11532  CheckCast(value);
11533 #endif
11534  return static_cast<BooleanObject*>(value);
11535 }
11536 
11537 
11538 RegExp* RegExp::Cast(v8::Value* value) {
11539 #ifdef V8_ENABLE_CHECKS
11540  CheckCast(value);
11541 #endif
11542  return static_cast<RegExp*>(value);
11543 }
11544 
11545 
11546 Object* Object::Cast(v8::Value* value) {
11547 #ifdef V8_ENABLE_CHECKS
11548  CheckCast(value);
11549 #endif
11550  return static_cast<Object*>(value);
11551 }
11552 
11553 
11554 Array* Array::Cast(v8::Value* value) {
11555 #ifdef V8_ENABLE_CHECKS
11556  CheckCast(value);
11557 #endif
11558  return static_cast<Array*>(value);
11559 }
11560 
11561 
11562 Map* Map::Cast(v8::Value* value) {
11563 #ifdef V8_ENABLE_CHECKS
11564  CheckCast(value);
11565 #endif
11566  return static_cast<Map*>(value);
11567 }
11568 
11569 
11570 Set* Set::Cast(v8::Value* value) {
11571 #ifdef V8_ENABLE_CHECKS
11572  CheckCast(value);
11573 #endif
11574  return static_cast<Set*>(value);
11575 }
11576 
11577 
11579 #ifdef V8_ENABLE_CHECKS
11580  CheckCast(value);
11581 #endif
11582  return static_cast<Promise*>(value);
11583 }
11584 
11585 
11586 Proxy* Proxy::Cast(v8::Value* value) {
11587 #ifdef V8_ENABLE_CHECKS
11588  CheckCast(value);
11589 #endif
11590  return static_cast<Proxy*>(value);
11591 }
11592 
11594 #ifdef V8_ENABLE_CHECKS
11595  CheckCast(value);
11596 #endif
11597  return static_cast<WasmModuleObject*>(value);
11598 }
11599 
11601 #ifdef V8_ENABLE_CHECKS
11602  CheckCast(value);
11603 #endif
11604  return static_cast<Promise::Resolver*>(value);
11605 }
11606 
11607 
11609 #ifdef V8_ENABLE_CHECKS
11610  CheckCast(value);
11611 #endif
11612  return static_cast<ArrayBuffer*>(value);
11613 }
11614 
11615 
11617 #ifdef V8_ENABLE_CHECKS
11618  CheckCast(value);
11619 #endif
11620  return static_cast<ArrayBufferView*>(value);
11621 }
11622 
11623 
11625 #ifdef V8_ENABLE_CHECKS
11626  CheckCast(value);
11627 #endif
11628  return static_cast<TypedArray*>(value);
11629 }
11630 
11631 
11633 #ifdef V8_ENABLE_CHECKS
11634  CheckCast(value);
11635 #endif
11636  return static_cast<Uint8Array*>(value);
11637 }
11638 
11639 
11641 #ifdef V8_ENABLE_CHECKS
11642  CheckCast(value);
11643 #endif
11644  return static_cast<Int8Array*>(value);
11645 }
11646 
11647 
11649 #ifdef V8_ENABLE_CHECKS
11650  CheckCast(value);
11651 #endif
11652  return static_cast<Uint16Array*>(value);
11653 }
11654 
11655 
11657 #ifdef V8_ENABLE_CHECKS
11658  CheckCast(value);
11659 #endif
11660  return static_cast<Int16Array*>(value);
11661 }
11662 
11663 
11665 #ifdef V8_ENABLE_CHECKS
11666  CheckCast(value);
11667 #endif
11668  return static_cast<Uint32Array*>(value);
11669 }
11670 
11671 
11673 #ifdef V8_ENABLE_CHECKS
11674  CheckCast(value);
11675 #endif
11676  return static_cast<Int32Array*>(value);
11677 }
11678 
11679 
11681 #ifdef V8_ENABLE_CHECKS
11682  CheckCast(value);
11683 #endif
11684  return static_cast<Float32Array*>(value);
11685 }
11686 
11687 
11689 #ifdef V8_ENABLE_CHECKS
11690  CheckCast(value);
11691 #endif
11692  return static_cast<Float64Array*>(value);
11693 }
11694 
11696 #ifdef V8_ENABLE_CHECKS
11697  CheckCast(value);
11698 #endif
11699  return static_cast<BigInt64Array*>(value);
11700 }
11701 
11703 #ifdef V8_ENABLE_CHECKS
11704  CheckCast(value);
11705 #endif
11706  return static_cast<BigUint64Array*>(value);
11707 }
11708 
11710 #ifdef V8_ENABLE_CHECKS
11711  CheckCast(value);
11712 #endif
11713  return static_cast<Uint8ClampedArray*>(value);
11714 }
11715 
11716 
11718 #ifdef V8_ENABLE_CHECKS
11719  CheckCast(value);
11720 #endif
11721  return static_cast<DataView*>(value);
11722 }
11723 
11724 
11726 #ifdef V8_ENABLE_CHECKS
11727  CheckCast(value);
11728 #endif
11729  return static_cast<SharedArrayBuffer*>(value);
11730 }
11731 
11732 
11734 #ifdef V8_ENABLE_CHECKS
11735  CheckCast(value);
11736 #endif
11737  return static_cast<Function*>(value);
11738 }
11739 
11740 
11742 #ifdef V8_ENABLE_CHECKS
11743  CheckCast(value);
11744 #endif
11745  return static_cast<External*>(value);
11746 }
11747 
11748 
11749 template<typename T>
11751  return *reinterpret_cast<Isolate**>(&args_[kIsolateIndex]);
11752 }
11753 
11754 
11755 template<typename T>
11757  return Local<Value>(reinterpret_cast<Value*>(&args_[kDataIndex]));
11758 }
11759 
11760 
11761 template<typename T>
11763  return Local<Object>(reinterpret_cast<Object*>(&args_[kThisIndex]));
11764 }
11765 
11766 
11767 template<typename T>
11769  return Local<Object>(reinterpret_cast<Object*>(&args_[kHolderIndex]));
11770 }
11771 
11772 
11773 template<typename T>
11775  return ReturnValue<T>(&args_[kReturnValueIndex]);
11776 }
11777 
11778 template <typename T>
11780  typedef internal::Internals I;
11784  }
11786  reinterpret_cast<v8::internal::Isolate*>(GetIsolate()));
11787 }
11788 
11790  typedef internal::Address S;
11791  typedef internal::Internals I;
11792  I::CheckInitialized(isolate);
11793  S* slot = I::GetRoot(isolate, I::kUndefinedValueRootIndex);
11794  return Local<Primitive>(reinterpret_cast<Primitive*>(slot));
11795 }
11796 
11797 
11799  typedef internal::Address S;
11800  typedef internal::Internals I;
11801  I::CheckInitialized(isolate);
11802  S* slot = I::GetRoot(isolate, I::kNullValueRootIndex);
11803  return Local<Primitive>(reinterpret_cast<Primitive*>(slot));
11804 }
11805 
11806 
11808  typedef internal::Address S;
11809  typedef internal::Internals I;
11810  I::CheckInitialized(isolate);
11811  S* slot = I::GetRoot(isolate, I::kTrueValueRootIndex);
11812  return Local<Boolean>(reinterpret_cast<Boolean*>(slot));
11813 }
11814 
11815 
11817  typedef internal::Address S;
11818  typedef internal::Internals I;
11819  I::CheckInitialized(isolate);
11820  S* slot = I::GetRoot(isolate, I::kFalseValueRootIndex);
11821  return Local<Boolean>(reinterpret_cast<Boolean*>(slot));
11822 }
11823 
11824 
11825 void Isolate::SetData(uint32_t slot, void* data) {
11826  typedef internal::Internals I;
11827  I::SetEmbedderData(this, slot, data);
11828 }
11829 
11830 
11831 void* Isolate::GetData(uint32_t slot) {
11832  typedef internal::Internals I;
11833  return I::GetEmbedderData(this, slot);
11834 }
11835 
11836 
11838  typedef internal::Internals I;
11839  return I::kNumIsolateDataSlots;
11840 }
11841 
11842 template <class T>
11844  T* data = reinterpret_cast<T*>(GetDataFromSnapshotOnce(index));
11845  if (data) internal::PerformCastCheck(data);
11846  return Local<T>(data);
11847 }
11848 
11850  int64_t change_in_bytes) {
11851  typedef internal::Internals I;
11852  constexpr int64_t kMemoryReducerActivationLimit = 32 * 1024 * 1024;
11853  int64_t* external_memory = reinterpret_cast<int64_t*>(
11854  reinterpret_cast<uint8_t*>(this) + I::kExternalMemoryOffset);
11855  int64_t* external_memory_limit = reinterpret_cast<int64_t*>(
11856  reinterpret_cast<uint8_t*>(this) + I::kExternalMemoryLimitOffset);
11857  int64_t* external_memory_at_last_mc =
11858  reinterpret_cast<int64_t*>(reinterpret_cast<uint8_t*>(this) +
11860 
11861  // Embedders are weird: we see both over- and underflows here. Perform the
11862  // addition with unsigned types to avoid undefined behavior.
11863  const int64_t amount =
11864  static_cast<int64_t>(static_cast<uint64_t>(change_in_bytes) +
11865  static_cast<uint64_t>(*external_memory));
11866  *external_memory = amount;
11867 
11868  int64_t allocation_diff_since_last_mc =
11869  static_cast<int64_t>(static_cast<uint64_t>(*external_memory) -
11870  static_cast<uint64_t>(*external_memory_at_last_mc));
11871  // Only check memory pressure and potentially trigger GC if the amount of
11872  // external memory increased.
11873  if (allocation_diff_since_last_mc > kMemoryReducerActivationLimit) {
11874  CheckMemoryPressure();
11875  }
11876 
11877  if (change_in_bytes < 0) {
11878  const int64_t lower_limit =
11879  static_cast<int64_t>(static_cast<uint64_t>(*external_memory_limit) +
11880  static_cast<uint64_t>(change_in_bytes));
11881  if (lower_limit > I::kExternalAllocationSoftLimit) {
11882  *external_memory_limit = lower_limit;
11883  }
11884  } else if (change_in_bytes > 0 && amount > *external_memory_limit) {
11885  ReportExternalAllocationLimitReached();
11886  }
11887  return *external_memory;
11888 }
11889 
11891 #ifndef V8_ENABLE_CHECKS
11892  typedef internal::Address A;
11893  typedef internal::Internals I;
11894  A ctx = *reinterpret_cast<const A*>(this);
11895  A embedder_data =
11897  int value_offset =
11899  A value = I::ReadRawField<A>(embedder_data, value_offset);
11900 #ifdef V8_COMPRESS_POINTERS
11901  // We read the full pointer value and then decompress it in order to avoid
11902  // dealing with potential endiannes issues.
11903  value =
11904  I::DecompressTaggedAnyField(embedder_data, static_cast<int32_t>(value));
11905 #endif
11907  *reinterpret_cast<A*>(this));
11908  A* result = HandleScope::CreateHandle(isolate, value);
11909  return Local<Value>(reinterpret_cast<Value*>(result));
11910 #else
11911  return SlowGetEmbedderData(index);
11912 #endif
11913 }
11914 
11915 
11917 #ifndef V8_ENABLE_CHECKS
11918  typedef internal::Address A;
11919  typedef internal::Internals I;
11920  A ctx = *reinterpret_cast<const A*>(this);
11921  A embedder_data =
11923  int value_offset =
11925  return I::ReadRawField<void*>(embedder_data, value_offset);
11926 #else
11927  return SlowGetAlignedPointerFromEmbedderData(index);
11928 #endif
11929 }
11930 
11931 template <class T>
11933  T* data = reinterpret_cast<T*>(GetDataFromSnapshotOnce(index));
11934  if (data) internal::PerformCastCheck(data);
11935  return Local<T>(data);
11936 }
11937 
11938 template <class T>
11939 size_t SnapshotCreator::AddData(Local<Context> context, Local<T> object) {
11940  T* object_ptr = *object;
11941  internal::Address* p = reinterpret_cast<internal::Address*>(object_ptr);
11942  return AddData(context, *p);
11943 }
11944 
11945 template <class T>
11946 size_t SnapshotCreator::AddData(Local<T> object) {
11947  T* object_ptr = *object;
11948  internal::Address* p = reinterpret_cast<internal::Address*>(object_ptr);
11949  return AddData(*p);
11950 }
11951 
11952 /**
11953  * \example shell.cc
11954  * A simple shell that takes a list of expressions on the
11955  * command-line and executes them.
11956  */
11957 
11958 
11959 /**
11960  * \example process.cc
11961  */
11962 
11963 
11964 } // namespace v8
11965 
11966 
11967 #undef TYPE_CHECK
11968 
11969 
11970 #endif // INCLUDE_V8_H_
GenericNamedPropertyDefinerCallback definer
Definition: v8.h:6614
void Enter()
bool CanBeRehashed() const
bool IsConstructor() const
Scope(const Scope &)=delete
Local< StackTrace > GetStackTrace() const
static const int kJSApiObjectType
Definition: v8-internal.h:191
int GetLineNumber()
Definition: v8.h:1462
V8_INLINE TracedReference(const TracedReference &other)
Definition: v8.h:1103
static V8_INLINE StringObject * Cast(Value *obj)
Definition: v8.h:11500
TracedGlobal(Isolate *isolate, Local< S > that)
Definition: v8.h:951
friend class Traced
Definition: v8.h:328
void RequestInterrupt(InterruptCallback callback, void *data)
Location(int line_number, int column_number)
Definition: v8.h:1465
Definition: v8.h:2229
void(* GCCallback)(GCType type, GCCallbackFlags flags)
Definition: v8.h:7529
void SetLength(int length)
static Local< BigInt64Array > New(Local< ArrayBuffer > array_buffer, size_t byte_offset, size_t length)
V8_INLINE Local< Boolean > True(Isolate *isolate)
Definition: v8.h:11807
V8_WARN_UNUSED_RESULT MaybeLocal< Uint32 > ToArrayIndex(Local< Context > context) const
void SetWasmStreamingCallback(WasmStreamingCallback callback)
size_t space_available_size()
Definition: v8.h:7618
TracedReference< T > & operator=(TracedReference< S > &&rhs)
Definition: v8.h:10877
V8_INLINE Local< Value > GetEmbedderData(int index)
Definition: v8.h:11890
V8_INLINE void Set(Isolate *isolate, const char *name, Local< Data > value)
Definition: v8.h:11209
Local< Value > GetSourceMappingURL()
V8_INLINE Local< Value > GetValue() const
Definition: v8.h:7284
V8_WARN_UNUSED_RESULT MaybeLocal< Array > GetOwnPropertyNames(Local< Context > context)
bool IsPromise() const
V8_WARN_UNUSED_RESULT MaybeLocal< Value > ReadValue(Local< Context > context)
friend Maybe< U > Just(const U &u)
GarbageCollectionType
Definition: v8.h:8316
static V8_INLINE BigInt64Array * Cast(Value *obj)
Definition: v8.h:11695
double Value() const
void LocaleConfigurationChangeNotification()
static V8_INLINE Object * Cast(Value *obj)
Definition: v8.h:11546
Definition: v8.h:4137
void(* FatalErrorCallback)(const char *location, const char *message)
Definition: v8.h:7118
bool IsDataView() const
void RunMicrotasks()
OwnedBuffer(std::unique_ptr< const uint8_t[]> buffer, size_t size)
Definition: v8.h:4742
void(* BeforeCallEnteredCallback)(Isolate *)
Definition: v8.h:7181
static V8_INLINE Uint8ClampedArray * Cast(Value *obj)
Definition: v8.h:11709
void V8_EXPORT RegisterExtension(std::unique_ptr< Extension >)
AtomicsWaitEvent
Definition: v8.h:8792
Persistent< T, CopyablePersistentTraits< T > > CopyablePersistent
Definition: v8.h:636
V8_INLINE void SetWrapperClassId(uint16_t class_id)
Definition: v8.h:10754
V8_INLINE uint16_t WrapperClassId() const
Definition: v8.h:10764
KeyConversionMode
Definition: v8.h:3652
static V8_INLINE void Uncompilable()
Definition: v8.h:624
virtual bool IsRootForNonTracingGC(const v8::TracedGlobal< v8::Value > &handle)
void WriteUint32(uint32_t value)
size_t number_of_native_contexts()
Definition: v8.h:7584
friend class Global
Definition: v8.h:9701
void * lr
Definition: v8.h:2212
friend class MaybeLocal
Definition: v8.h:9704
SerializeInternalFieldsCallback SerializeEmbedderFieldsCallback
Definition: v8.h:8038
V8_WARN_UNUSED_RESULT Maybe< bool > SetSyntheticModuleExport(Isolate *isolate, Local< String > export_name, Local< Value > export_value)
bool IsVerbose() const
int64_t Int64Value(bool *lossless=nullptr) const
SafeForTerminationScope(const SafeForTerminationScope &)=delete
uint32_t Length() const
void AddCallCompletedCallback(CallCompletedCallback callback)
Local< Value > GetTarget()
virtual ~MicrotaskQueue()=default
void(* WasmStreamingCallback)(const FunctionCallbackInfo< Value > &)
Definition: v8.h:7478
static Local< Symbol > GetReplace(Isolate *isolate)
ScriptOrigin GetScriptOrigin() const
V8_INLINE bool operator==(const Local< S > &that) const
Definition: v8.h:228
void operator=(const Extension &)=delete
Source(const Source &)=delete
const char * data
Definition: v8.h:9459
static Local< ObjectTemplate > New(Isolate *isolate, Local< FunctionTemplate > constructor=Local< FunctionTemplate >())
BackupIncumbentScope(Local< Context > backup_incumbent_context)
V8_WARN_UNUSED_RESULT MaybeLocal< String > GetSourceLine(Local< Context > context) const
static V8_INLINE internal::Address ReadTaggedPointerField(internal::Address heap_object_ptr, int offset)
Definition: v8-internal.h:308
friend class internal::CustomArguments
Definition: v8.h:315
size_t AddContext(Local< Context > context, SerializeInternalFieldsCallback callback=SerializeInternalFieldsCallback())
virtual MaybeLocal< WasmModuleObject > GetWasmModuleFromId(Isolate *isolate, uint32_t transfer_id)
static Local< FunctionTemplate > New(Isolate *isolate, FunctionCallback callback=nullptr, Local< Value > data=Local< Value >(), Local< Signature > signature=Local< Signature >(), int length=0, ConstructorBehavior behavior=ConstructorBehavior::kAllow, SideEffectType side_effect_type=SideEffectType::kHasSideEffect)
bool IsUint8ClampedArray() const
V8_WARN_UNUSED_RESULT MaybeLocal< Value > Get(Local< Context > context, Local< Value > key)
char * operator*()
Definition: v8.h:3298
const char * space_name()
Definition: v8.h:7615
friend Maybe< U > Nothing()
Definition: v8.h:9905
bool IsFalse() const
IntegrityLevel
Definition: v8.h:3657
void(* ApiImplementationCallback)(const FunctionCallbackInfo< Value > &)
Definition: v8.h:7475
static void Initialize(Isolate *isolate, const CreateParams &params)
void Reset(Isolate *isolate, const Local< S > &other)
Definition: v8.h:10818
V8_WARN_UNUSED_RESULT MaybeLocal< String > ObjectProtoToString(Local< Context > context)
static V8_INLINE Int8Array * Cast(Value *obj)
Definition: v8.h:11640
bool IsExternal() const
const int kSmiMaxValue
Definition: v8-internal.h:120
void Dispose()
Definition: v8.h:2250
DisallowJavascriptExecutionScope(const DisallowJavascriptExecutionScope &)=delete
void SetEventLogger(LogEventCallback that)
const ExternalOneByteStringResource * GetExternalOneByteStringResource() const
static V8_INLINE uint8_t GetNodeState(internal::Address *obj)
Definition: v8-internal.h:257
Location GetModuleRequestLocation(int i) const
EscapableHandleScope(const EscapableHandleScope &)=delete
StateTag vm_state
Definition: v8.h:2218
void set_enumerable(bool enumerable)
static Local< Float32Array > New(Local< ArrayBuffer > array_buffer, size_t byte_offset, size_t length)
#define V8_EXPORT
Definition: v8config.h:458
static void PrintCurrentStackTrace(Isolate *isolate, FILE *out)
Local< Value > Name() const
Definition: v8.h:3357
void operator delete(void *, size_t)=delete
static Local< Value > New(Isolate *isolate, Local< Symbol > value)
V8_WARN_UNUSED_RESULT Maybe< bool > DefineProperty(Local< Context > context, Local< Name > key, PropertyDescriptor &descriptor)
Local< Value > GetPrototype()
V8_INLINE Persistent & operator=(const Persistent< S, M2 > &that)
Definition: v8.h:698
PromiseRejectEvent
Definition: v8.h:7269
bool IsRegExp() const
static V8_INLINE ArrayBufferView * Cast(Value *obj)
Definition: v8.h:11616
Definition: v8.h:146
static Local< Set > New(Isolate *isolate)
void(* GCCallback)(Isolate *isolate, GCType type, GCCallbackFlags flags)
Definition: v8.h:8753
void operator=(const PropertyDescriptor &)=delete
size_t read_only_space_physical_size()
Definition: v8.h:7554
size_t code_and_metadata_size()
Definition: v8.h:7652
Local< String > Get() const
Local< String > GetFunctionName() const
int GetLineNumber() const
V8_INLINE Eternal(Isolate *isolate, Local< S > handle)
Definition: v8.h:408
static MaybeLocal< Proxy > New(Local< Context > context, Local< Object > local_target, Local< Object > local_handler)
static Local< Uint16Array > New(Local< SharedArrayBuffer > shared_array_buffer, size_t byte_offset, size_t length)
V8_WARN_UNUSED_RESULT Maybe< bool > SetNativeDataProperty(Local< Context > context, Local< Name > name, AccessorNameGetterCallback getter, AccessorNameSetterCallback setter=nullptr, Local< Value > data=Local< Value >(), PropertyAttribute attributes=None, SideEffectType getter_side_effect_type=SideEffectType::kHasSideEffect, SideEffectType setter_side_effect_type=SideEffectType::kHasSideEffect)
bool IsBooleanObject() const
MaybeLocal< Promise >(* HostImportModuleDynamicallyCallback)(Local< Context > context, Local< ScriptOrModule > referrer, Local< String > specifier)
Definition: v8.h:7218
friend class ReturnValue
Definition: v8.h:4238
static V8_INLINE SharedArrayBuffer * Cast(Value *obj)
Definition: v8.h:11725
void * Data() const
PropertyHandlerFlags flags
Definition: v8.h:6617
V8_WARN_UNUSED_RESULT Maybe< bool > Reject(Local< Context > context, Local< Value > value)
uintptr_t Address
Definition: v8-internal.h:24
void AddGCPrologueCallback(GCCallbackWithData callback, void *data=nullptr, GCType gc_type_filter=kGCTypeAll)
V8_INLINE void SetUndefined()
Definition: v8.h:11033
void Reset(Isolate *isolate, const PersistentBase< S > &other)
Definition: v8.h:10716
PropertyHandlerFlags
Definition: v8.h:6521
static V8_INLINE Float32Array * Cast(Value *obj)
Definition: v8.h:11680
static V8_INLINE Map * Cast(Value *obj)
Definition: v8.h:11562
Maybe< T > Just(const T &t)
Definition: v8.h:9910
int GetStartPosition() const
V8_INLINE bool IsNothing() const
Definition: v8.h:9840
void SetEmbedderHeapTracer(EmbedderHeapTracer *tracer)
void RemoveMicrotasksCompletedCallback(MicrotasksCompletedCallback callback)
JSEntryStub js_entry_stub
Definition: v8.h:2242
void SetUseCounterCallback(UseCounterCallback callback)
V8_INLINE T * operator*() const
Definition: v8.h:215
v8::Isolate * isolate() const
Definition: v8.h:8011
static Local< DataView > New(Local< ArrayBuffer > array_buffer, size_t byte_offset, size_t length)
void RestoreOriginalHeapLimit()
size_t NumberOfPhantomHandleResetsSinceLastCall()
int32_t Value() const
Local< Value > GetSourceURL()
void SetHandler(const NamedPropertyHandlerConfiguration &configuration)
bool IsExternalOneByte() const
V8_WARN_UNUSED_RESULT MaybeLocal< Promise > Then(Local< Context > context, Local< Function > on_fulfilled, Local< Function > on_rejected)
V8_WARN_UNUSED_RESULT Maybe< bool > Equals(Local< Context > context, Local< Value > that) const
Definition: v8.h:9490
Local< ObjectTemplate > PrototypeTemplate()
bool IsBigInt64Array() const
#define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT
Definition: v8.h:4939
void ConfigureDefaultsFromHeapSize(size_t initial_heap_size_in_bytes, size_t maximum_heap_size_in_bytes)
V8_INLINE PropertyCallbackInfo(internal::Address *args)
Definition: v8.h:4418
Definition: v8.h:2507
static Local< Symbol > GetMatch(Isolate *isolate)
void * user_data
Definition: v8.h:7706
virtual int GetMicrotasksScopeDepth() const =0
void(* AbortScriptExecutionCallback)(Isolate *isolate, Local< Context > context)
Definition: v8.h:10345
void operator=(const TryCatch &)=delete
static V8_WARN_UNUSED_RESULT MaybeLocal< String > Stringify(Local< Context > context, Local< Value > json_object, Local< String > gap=Local< String >())
void Set(const Local< S > handle)
Definition: v8.h:10974
IndexedPropertyDefinerCallback definer
Definition: v8.h:6684
Utf8Value(const Utf8Value &)=delete
static V8_INLINE Proxy * Cast(Value *obj)
Definition: v8.h:11586
bool IsFloat32Array() const
size_t peak_malloced_memory()
Definition: v8.h:7583
V8_INLINE void * GetAlignedPointerFromInternalField(int index)
Definition: v8.h:11271
static Local< Symbol > GetIsConcatSpreadable(Isolate *isolate)
Local< Value > value() const
bool has_writable() const
bool IsBigIntObject() const
V8_INLINE Local< T > Get(Isolate *isolate) const
Definition: v8.h:502
static Isolate * Allocate()
V8_INLINE bool IsJust() const
Definition: v8.h:9841
virtual ~PersistentHandleVisitor()=default
V8_INLINE bool operator!=(const Persistent< S > &that) const
Definition: v8.h:260
static V8_INLINE Uint32Array * Cast(Value *obj)
Definition: v8.h:11664
const char * object_type()
Definition: v8.h:7635
bool IsExecutionTerminating()
void set_code_range_size(size_t limit_in_mb)
Definition: v8.h:7085
size_t frames_count
Definition: v8.h:2217
void CancelTerminateExecution()
static V8_INLINE AccessorSignature * Cast(Data *data)
Definition: v8.h:11236
virtual void Lock() const
Definition: v8.h:3118
void(* InterruptCallback)(Isolate *isolate, void *data)
Definition: v8.h:7531
CreateHistogramCallback create_histogram_callback
Definition: v8.h:8171
V8_INLINE bool operator!=(const Local< S > &that) const
Definition: v8.h:530
bool IsConstructor()
Local< Value > export_value
Definition: v8.h:1602
bool SetCompiledModuleBytes(const uint8_t *bytes, size_t size)
Definition: v8.h:4173
static V8_INLINE int GetOddballKind(const internal::Address obj)
Definition: v8-internal.h:236
friend class TracedReference
Definition: v8.h:9712
bool IsEval() const
size_t read_only_space_size()
Definition: v8.h:7552
StateTag
Definition: v8.h:2194
static Local< PrimitiveArray > New(Isolate *isolate, int length)
V8_INLINE T FromJust() const
Definition: v8.h:9869
bool IsWasm() const
Definition: v8.h:1369
void SetStackLimit(uintptr_t stack_limit)
static const int kEmbedderDataSlotSize
Definition: v8-internal.h:148
V8_INLINE T * GetParameter() const
Definition: v8.h:439
void SetCaptureMessage(bool value)
static Local< Private > ForApi(Isolate *isolate, Local< String > name)
size_t space_used_size()
Definition: v8.h:7617
void SetName(Local< String > name)
int GetIdentityHash()
static constexpr int kExternalAllocationSoftLimit
Definition: v8-internal.h:205
StackTraceOptions
Definition: v8.h:2084
void SetPromiseRejectCallback(PromiseRejectCallback callback)
size_t does_zap_garbage()
Definition: v8.h:7591
void(* AddHistogramSampleCallback)(void *histogram, int sample)
Definition: v8.h:7167
Definition: v8.h:2200
V8_INLINE Local< Value > SourceMapUrl() const
Definition: v8.h:11173
Local< Value > GetException() const
size_t code_range_size() const
Definition: v8.h:7083
V8_WARN_UNUSED_RESULT MaybeLocal< Value > Get(Local< Context > context, uint32_t index)
V8_WARN_UNUSED_RESULT MaybeLocal< Uint32 > ToUint32(Local< Context > context) const
bool IsStringObject() const
virtual void * AllocateUninitialized(size_t length)=0
void DisableMemorySavingsMode()
static void SetFlagsFromString(const char *str)
bool StrictEquals(Local< Value > that) const
bool IsModule() const
Definition: v8.h:1370
bool IsArrayBufferView() const
int Length() const
int dependency_count() const
Definition: v8.h:6950
V8_INLINE const CachedData * GetCachedData() const
Definition: v8.h:11196
static const int kArgsLength
Definition: v8.h:4290
bool IsObject() const
Scope & operator=(const Scope &)=delete
void DumpAndResetStats()
bool auto_enable()
Definition: v8.h:6953
static const int kFirstNonstringType
Definition: v8-internal.h:187
IndexedPropertyDeleterCallback deleter
Definition: v8.h:6682
static const int kNullValueRootIndex
Definition: v8-internal.h:176
static const uint32_t kNumIsolateDataSlots
Definition: v8-internal.h:155
SuppressMicrotaskExecutionScope & operator=(const SuppressMicrotaskExecutionScope &)=delete
static V8_INLINE Uint32 * Cast(v8::Value *obj)
Definition: v8.h:11478
Definition: v8.h:2943
V8_WARN_UNUSED_RESULT Maybe< bool > CreateDataProperty(Local< Context > context, uint32_t index, Local< Value > value)
static Local< BigInt64Array > New(Local< SharedArrayBuffer > shared_array_buffer, size_t byte_offset, size_t length)
virtual Maybe< uint32_t > GetSharedArrayBufferId(Isolate *isolate, Local< SharedArrayBuffer > shared_array_buffer)
V8_INLINE ReturnValue< T > GetReturnValue() const
Definition: v8.h:11117
MaybeLocal< T > GetDataFromSnapshotOnce(size_t index)
Definition: v8.h:11932
size_t length_in_bytes
Definition: v8.h:2226
static V8_INLINE Array * Cast(Value *obj)
Definition: v8.h:11554
V8_WARN_UNUSED_RESULT MaybeLocal< Value > CallAsFunction(Local< Context > context, Local< Value > recv, int argc, Local< Value > argv[])
void AllowCodeGenerationFromStrings(bool allow)
size_t AllocationLength() const
Definition: v8.h:5077
void GetStackSample(const RegisterState &state, void **frames, size_t frames_limit, SampleInfo *sample_info)
void(* IndexedPropertyEnumeratorCallback)(const PropertyCallbackInfo< Array > &info)
Definition: v8.h:6266
static const int kHolderIndex
Definition: v8.h:4296
void RemoveCallCompletedCallback(CallCompletedCallback callback)
V8_INLINE Persistent & operator=(const Persistent &that)
Definition: v8.h:693
size_t size
Definition: v8.h:4741
void(* MicrotasksCompletedCallback)(Isolate *)
Definition: v8.h:7296
V8_INLINE void * GetAlignedPointerFromEmbedderData(int index)
Definition: v8.h:11916
void RemoveGCPrologueCallback(GCCallback callback)
V8_WARN_UNUSED_RESULT MaybeLocal< Map > Set(Local< Context > context, Local< Value > key, Local< Value > value)
EmbedderDataFields
Definition: v8.h:10261
static Local< DataView > New(Local< SharedArrayBuffer > shared_array_buffer, size_t byte_offset, size_t length)
void(* IndexedPropertyDeleterCallback)(uint32_t index, const PropertyCallbackInfo< Boolean > &info)
Definition: v8.h:6256
void Initialize(Isolate *isolate)
V8_WARN_UNUSED_RESULT Maybe< int > GetEndColumn(Local< Context > context) const
virtual bool IsTracingDone()=0
void SetCallAsFunctionHandler(FunctionCallback callback, Local< Value > data=Local< Value >())
V8_INLINE bool IsString() const
Definition: v8.h:11400
void SetNativeDataProperty(Local< String > name, AccessorGetterCallback getter, AccessorSetterCallback setter=nullptr, Local< Value > data=Local< Value >(), PropertyAttribute attribute=None, Local< AccessorSignature > signature=Local< AccessorSignature >(), AccessControl settings=DEFAULT, SideEffectType getter_side_effect_type=SideEffectType::kHasSideEffect, SideEffectType setter_side_effect_type=SideEffectType::kHasSideEffect)
static Local< Value > New(Isolate *isolate, double value)
void ToWordsArray(int *sign_bit, int *word_count, uint64_t *words) const
bool IsDead()
static V8_INLINE void * GetEmbedderData(const v8::Isolate *isolate, uint32_t slot)
Definition: v8-internal.h:275
size_t used_heap_size()
Definition: v8.h:7579
V8_INLINE bool IsNothing() const
Definition: v8.h:9918
CrashKeyId
Definition: v8.h:7170
void * fp
Definition: v8.h:2211
constexpr MemorySpan()=default
SnapshotCreator(const intptr_t *external_references=nullptr, StartupData *existing_blob=nullptr)
static V8_INLINE Float64Array * Cast(Value *obj)
Definition: v8.h:11688
static const bool kResetInDestructor
Definition: v8.h:617
const char * name() const
Definition: v8.h:6945
Definition: v8.h:1308
Isolate(const Isolate &)=delete
V8_WARN_UNUSED_RESULT Maybe< PropertyAttribute > GetRealNamedPropertyAttributesInPrototypeChain(Local< Context > context, Local< Name > key)
void * operator new(size_t size)=delete
Status
Definition: v8.h:1485
void ClearKeptObjects()
void LowMemoryNotification()
WriteOptions
Definition: v8.h:3045
Local< StackFrame > GetFrame(Isolate *isolate, uint32_t index) const
Encoding
Definition: v8.h:2989
virtual void ResetHandleInNonTracingGC(const v8::TracedReference< v8::Value > &handle)
bool IsInUse()
void size_t byte_length
Definition: v8.h:5131
bool IsBigInt() const
V8_WARN_UNUSED_RESULT Maybe< bool > InstantiateModule(Local< Context > context, ResolveCallback callback)
static Local< Symbol > GetAsyncIterator(Isolate *isolate)
V8_WARN_UNUSED_RESULT Maybe< bool > WriteValue(Local< Context > context, Local< Value > value)
V8_INLINE Eternal()
Definition: v8.h:406
static V8_INLINE uint32_t GetNumberOfDataSlots()
Definition: v8.h:11837
bool(* ExtensionCallback)(const FunctionCallbackInfo< Value > &)
Definition: v8.h:7468
void EnableMemorySavingsMode()
Local< Value > ThrowException(Local< Value > exception)
static Local< Array > New(Isolate *isolate, Local< Value > *elements, size_t length)
void SetIntrinsicDataProperty(Local< Name > name, Intrinsic intrinsic, PropertyAttribute attribute=None)
constexpr MemorySpan(T *data, size_t size)
Definition: v8.h:4724
void Set(const TracedReferenceBase< S > &handle)
Definition: v8.h:10963
static Local< Signature > New(Isolate *isolate, Local< FunctionTemplate > receiver=Local< FunctionTemplate >())
bool MeasureMemory(std::unique_ptr< MeasureMemoryDelegate > delegate, MeasureMemoryExecution execution=MeasureMemoryExecution::kDefault)
static V8_WARN_UNUSED_RESULT MaybeLocal< UnboundScript > CompileUnboundScript(Isolate *isolate, Source *source, CompileOptions options=kNoCompileOptions, NoCacheReason no_cache_reason=kNoCacheNoReason)
V8_INLINE Local< S > As() const
Definition: v8.h:285
static Local< Uint32Array > New(Local< SharedArrayBuffer > shared_array_buffer, size_t byte_offset, size_t length)
static Local< BigInt > NewFromUnsigned(Isolate *isolate, uint64_t value)
V8_WARN_UNUSED_RESULT Maybe< int > GetLineNumber(Local< Context > context) const
void SetAccessCheckCallback(AccessCheckCallback callback, Local< Value > data=Local< Value >())
bool GetHeapCodeAndMetadataStatistics(HeapCodeStatistics *object_statistics)
OwnedBuffer Serialize()
static const int kNoColumnInfo
Definition: v8.h:2065
V8_WARN_UNUSED_RESULT Maybe< bool > Has(Local< Context > context, Local< Value > key)
int GetColumn() const
static int NumberOfHandles(Isolate *isolate)
bool IsShared() const
bool IsEmpty() const
Definition: v8.h:842
static const int kExternalMemoryLimitOffset
Definition: v8-internal.h:161
void(* CallCompletedCallback)(Isolate *)
Definition: v8.h:7182
V8_INLINE Local< Value > ResourceName() const
Definition: v8.h:11154
static const int kExternalMemoryAtLastMarkCompactOffset
Definition: v8-internal.h:163
V8_INLINE TracedGlobal(const TracedGlobal &other)
Definition: v8.h:977
V8_INLINE Local< T > Escape(Local< T > value)
Definition: v8.h:1250
V8_INLINE bool IsEmpty() const
Definition: v8.h:369
bool GetHeapSpaceStatistics(HeapSpaceStatistics *space_statistics, size_t index)
Local< ArrayBuffer > Buffer()
CachedData(const uint8_t *data, int length, BufferPolicy buffer_policy=BufferNotOwned)
void(* IndexedPropertyGetterCallback)(uint32_t index, const PropertyCallbackInfo< Value > &info)
Definition: v8.h:6234
void DiscardThreadSpecificMetadata()
static const int kNewTargetIndex
Definition: v8.h:4301
V8_INLINE void Set(int32_t i)
Definition: v8.h:10990
GenericNamedPropertyEnumeratorCallback enumerator
Definition: v8.h:6613
AddHistogramSampleCallback add_histogram_sample_callback
Definition: v8.h:8172
void(* LogEventCallback)(const char *name, int event)
Definition: v8.h:7129
V8_WARN_UNUSED_RESULT Maybe< bool > Delete(Local< Context > context, Local< Value > key)
Local< Value > GetDisplayName() const
size_t external_memory()
Definition: v8.h:7582
virtual void TracePrologue(TraceFlags flags)
Definition: v8.h:7912
Local< Object > FindInstanceInPrototypeChain(Local< FunctionTemplate > tmpl)
static const int kLineOffsetNotFound
Definition: v8.h:4510
static std::unique_ptr< BackingStore > NewBackingStore(Isolate *isolate, size_t byte_length)
V8_WARN_UNUSED_RESULT MaybeLocal< Object > NewInstance(Local< Context > context)
static V8_WARN_UNUSED_RESULT MaybeLocal< String > NewExternalTwoByte(Isolate *isolate, ExternalStringResource *resource)
bool SameValue(Local< Value > that) const
V8_INLINE ExternalStringResource * GetExternalStringResource() const
Definition: v8.h:11306
V8_INLINE Persistent(const Persistent< S, M2 > &that)
Definition: v8.h:690
void UseDefaultSecurityToken()
static V8_INLINE ObjectTemplate * Cast(Data *data)
Definition: v8.h:11222
static V8_INLINE Resolver * Cast(Value *obj)
Definition: v8.h:11600
void RemoveGCEpilogueCallback(GCCallback callback)
DeleterCallback Deleter() const
Definition: v8.h:5570
virtual void * Allocate(size_t length)=0
static Local< Symbol > GetUnscopables(Isolate *isolate)
static Local< Int32Array > New(Local< ArrayBuffer > array_buffer, size_t byte_offset, size_t length)
void set_code_range_size_in_bytes(size_t limit)
Definition: v8.h:7037
V8_INLINE T FromMaybe(const T &default_value) const
Definition: v8.h:9878
static V8_INLINE Boolean * Cast(v8::Value *obj)
Definition: v8.h:11422
static void SetEntropySource(EntropySource source)
DisallowJavascriptExecutionScope(Isolate *isolate, OnFailure on_failure)
PromiseHookType
Definition: v8.h:7263
Persistent< T, NonCopyablePersistentTraits< T > > NonCopyablePersistent
Definition: v8.h:616
static Local< Symbol > GetToPrimitive(Isolate *isolate)
friend class FunctionCallbackInfo
Definition: v8.h:4239
V8_INLINE ScriptOrigin(Local< Value > resource_name, Local< Integer > resource_line_offset=Local< Integer >(), Local< Integer > resource_column_offset=Local< Integer >(), Local< Boolean > resource_is_shared_cross_origin=Local< Boolean >(), Local< Integer > script_id=Local< Integer >(), Local< Value > source_map_url=Local< Value >(), Local< Boolean > resource_is_opaque=Local< Boolean >(), Local< Boolean > is_wasm=Local< Boolean >(), Local< Boolean > is_module=Local< Boolean >(), Local< PrimitiveArray > host_defined_options=Local< PrimitiveArray >())
Definition: v8.h:11133
const char * object_sub_type()
Definition: v8.h:7636
V8_INLINE ~Persistent()
Definition: v8.h:707
static const bool kResetInDestructor
Definition: v8.h:637
bool IdleNotificationDeadline(double deadline_in_seconds)
BufferPolicy buffer_policy
Definition: v8.h:1668
const void * start
Definition: v8.h:2225
static Local< Symbol > GetSearch(Isolate *isolate)
static Local< Float32Array > New(Local< SharedArrayBuffer > shared_array_buffer, size_t byte_offset, size_t length)
static V8_INLINE BigUint64Array * Cast(Value *obj)
Definition: v8.h:11702
V8_INLINE bool IsUndefined() const
Definition: v8.h:11347
void operator=(const Locker &)=delete
bool IsGeneratorFunction() const
MaybeLocal< Value >(* PrepareStackTraceCallback)(Local< Context > context, Local< Value > error, Local< Array > sites)
Definition: v8.h:7243
void Externalize(const std::shared_ptr< BackingStore > &backing_store)
static Local< ArrayBuffer > New(Isolate *isolate, size_t byte_length)
Value * Cast(T *value)
Definition: v8.h:11417
friend class Maybe
Definition: v8.h:9706
V8_INLINE Local< T > Get(Isolate *isolate) const
Definition: v8.h:10641
Local< String > GetSource() const
size_t heap_size_limit()
Definition: v8.h:7580
bool IsCallable()
friend class WeakCallbackInfo
Definition: v8.h:9714
void MemoryPressureNotification(MemoryPressureLevel level)
static Local< BigUint64Array > New(Local< SharedArrayBuffer > shared_array_buffer, size_t byte_offset, size_t length)
void AddMicrotasksCompletedCallback(MicrotasksCompletedCallback callback)
Local< UnboundModuleScript > GetUnboundModuleScript()
static void ShutdownPlatform()
MemoryPressureLevel
Definition: v8.h:7828
V8_INLINE Local< Value > GetInternalField(int index)
Definition: v8.h:11243
Local< Value > Result()
DeleterCallback Deleter() const
Definition: v8.h:5084
static Local< Value > New(Isolate *isolate, int64_t value)
void AddGCEpilogueCallback(GCCallback callback, GCType gc_type_filter=kGCTypeAll)
void(* GenericNamedPropertyQueryCallback)(Local< Name > property, const PropertyCallbackInfo< Integer > &info)
Definition: v8.h:6149
V8_WARN_UNUSED_RESULT MaybeLocal< String > ToString(Local< Context > context) const
void size_t byte_length
Definition: v8.h:5613
Local< Object > Clone()
static const int kNoLineNumberInfo
Definition: v8.h:2064
V8_INLINE bool IsNullOrUndefined() const
Definition: v8.h:11382
V8_INLINE Local< Value > Data() const
Definition: v8.h:11756
void(* GenericNamedPropertyEnumeratorCallback)(const PropertyCallbackInfo< Array > &info)
Definition: v8.h:6182
V8_INLINE bool operator==(const PersistentBase< S > &that) const
Definition: v8.h:236
void(* PromiseRejectCallback)(PromiseRejectMessage message)
Definition: v8.h:7292
internal::ScriptStreamingData * impl() const
Definition: v8.h:1784
void IterateTracedGlobalHandles(TracedGlobalHandleVisitor *visitor)
static Local< String > Concat(Isolate *isolate, Local< String > left, Local< String > right)
void SetNativeDataProperty(Local< Name > name, AccessorNameGetterCallback getter, AccessorNameSetterCallback setter=nullptr, Local< Value > data=Local< Value >(), PropertyAttribute attribute=None, Local< AccessorSignature > signature=Local< AccessorSignature >(), AccessControl settings=DEFAULT, SideEffectType getter_side_effect_type=SideEffectType::kHasSideEffect, SideEffectType setter_side_effect_type=SideEffectType::kHasSideEffect)
GenericNamedPropertyDescriptorCallback descriptor
Definition: v8.h:6615
void SetGetExternallyAllocatedMemoryInBytesCallback(GetExternallyAllocatedMemoryInBytesCallback callback)
void(* GenericNamedPropertyDeleterCallback)(Local< Name > property, const PropertyCallbackInfo< Boolean > &info)
Definition: v8.h:6173
bool(* AbortOnUncaughtExceptionCallback)(Isolate *)
Definition: v8.h:8491
static const int kStringResourceOffset
Definition: v8-internal.h:140
PropertyDescriptor(Local< Value > value)
V8_INLINE Global(Isolate *isolate, const PersistentBase< S > &that)
Definition: v8.h:772
void SetEmbedderData(int index, Local< Value > value)
int GetLineNumber(int code_pos)
int GetModuleRequestsLength() const
void(* Callback)(const WeakCallbackInfo< T > &data)
Definition: v8.h:427
static const int kNoScriptIdInfo
Definition: v8.h:2066
void(* IndexedPropertyDescriptorCallback)(uint32_t index, const PropertyCallbackInfo< Value > &info)
Definition: v8.h:6279
bool AddMessageListener(MessageCallback that, Local< Value > data=Local< Value >())
void * DeleterData() const
Definition: v8.h:5085
V8_INLINE ExternalStringResourceBase * GetExternalStringResourceBase(Encoding *encoding_out) const
Definition: v8.h:11325
V8_INLINE Isolate * GetIsolate() const
Definition: v8.h:11047
V8_INLINE Global()
Definition: v8.h:753
static Local< Value > RangeError(Local< String > message)
void SetIndexedPropertyHandler(IndexedPropertyGetterCallback getter, IndexedPropertySetterCallback setter=nullptr, IndexedPropertyQueryCallback query=nullptr, IndexedPropertyDeleterCallback deleter=nullptr, IndexedPropertyEnumeratorCallback enumerator=nullptr, Local< Value > data=Local< Value >())
Definition: v8.h:6788
bool IsOpaque() const
JSEntryStubs GetJSEntryStubs()
MemoryRange code
Definition: v8.h:2230
void SetVerbose(bool value)
static V8_INLINE void Copy(const Persistent< S, M > &source, CopyablePersistent *dest)
Definition: v8.h:639
void SetInternalField(int index, Local< Value > value)
void SetAccessorProperty(Local< Name > name, Local< Function > getter, Local< Function > setter=Local< Function >(), PropertyAttribute attribute=None, AccessControl settings=DEFAULT)
virtual MaybeLocal< SharedArrayBuffer > GetSharedArrayBufferFromId(Isolate *isolate, uint32_t clone_id)
UseCounterFeature
Definition: v8.h:8326
MaybeLocal< Value > GetPrivate(Local< Context > context, Local< Private > key)
bool CanMakeExternal()
void * AllocationBase() const
Definition: v8.h:5076
PropertyDescriptor(Local< Value > get, Local< Value > set)
virtual void MeasurementComplete(const std::vector< std::pair< Local< Context >, size_t >> &context_sizes_in_bytes, size_t unattributed_size_in_bytes)=0
bool IsProxy() const
TryCatch(const TryCatch &)=delete
V8_INLINE TracedGlobal< S > & As() const
Definition: v8.h:1027
static MaybeLocal< Object > NewRemoteContext(Isolate *isolate, Local< ObjectTemplate > global_template, MaybeLocal< Value > global_object=MaybeLocal< Value >())
V8_WARN_UNUSED_RESULT Maybe< bool > Delete(Local< Context > context, uint32_t index)
void GarbageCollectionForTesting(EmbedderStackState stack_state)
static Local< Message > CreateMessage(Isolate *isolate, Local< Value > exception)
static V8_INLINE int InternalFieldCount(const TracedReferenceBase< Object > &object)
Definition: v8.h:3897
bool MakeExternal(ExternalOneByteStringResource *resource)
static const int kJSObjectHeaderSize
Definition: v8-internal.h:145
Local< Context > GetIncumbentContext()
static V8_INLINE Function * Cast(Value *obj)
Definition: v8.h:11733
void(* AtomicsWaitCallback)(AtomicsWaitEvent event, Local< SharedArrayBuffer > array_buffer, size_t offset_in_bytes, int64_t value, double timeout_in_ms, AtomicsWaitWakeHandle *stop_handle, void *data)
Definition: v8.h:8853
static Local< Float64Array > New(Local< ArrayBuffer > array_buffer, size_t byte_offset, size_t length)
int64_t Value() const
bool IsInt32Array() const
V8_INLINE Persistent(Isolate *isolate, const Persistent< S, M2 > &that)
Definition: v8.h:676
V8_WARN_UNUSED_RESULT bool ReadUint32(uint32_t *value)
static void PerformCheckpoint(Isolate *isolate)
V8_WARN_UNUSED_RESULT Maybe< bool > CreateDataProperty(Local< Context > context, Local< Name > key, Local< Value > value)
V8_INLINE uint16_t WrapperClassId() const
Definition: v8.h:10925
bool IsInt32() const
static const int kInternalFieldCount
Definition: v8.h:5241
bool IsUint8Array() const
static std::shared_ptr< WasmStreaming > Unpack(Isolate *isolate, Local< Value > value)
static Local< Int8Array > New(Local< ArrayBuffer > array_buffer, size_t byte_offset, size_t length)
V8_INLINE int Length() const
Definition: v8.h:11129
size_t physical_space_size()
Definition: v8.h:7619
static Local< Uint8ClampedArray > New(Local< SharedArrayBuffer > shared_array_buffer, size_t byte_offset, size_t length)
static const int kArgsLength
Definition: v8.h:4404
bool IsSetIterator() const
static V8_INLINE Date * Cast(Value *obj)
Definition: v8.h:11492
void SetStackStart(void *stack_start)
V8_INLINE Local< Object > This() const
Definition: v8.h:11087
static Local< BigInt > New(Isolate *isolate, int64_t value)
static Local< Int8Array > New(Local< SharedArrayBuffer > shared_array_buffer, size_t byte_offset, size_t length)
virtual void AddMicrotasksCompletedCallback(MicrotasksCompletedCallbackWithData callback, void *data=nullptr)=0
virtual const uint16_t * data() const =0
V8_WARN_UNUSED_RESULT Maybe< bool > Delete(Local< Context > context, Local< Value > key)
int length() const
Definition: v8.h:3300
Local< String > ValueOf() const
int GetStartColumn() const
MicrotasksScope(Isolate *isolate, MicrotaskQueue *microtask_queue, Type type)
static bool IsLocked(Isolate *isolate)
friend class PersistentValueVector
Definition: v8.h:597
V8_INLINE P * ClearWeak()
static V8_INLINE Number * Cast(v8::Value *obj)
Definition: v8.h:11454
V8_WARN_UNUSED_RESULT Maybe< uint32_t > Uint32Value(Local< Context > context) const
size_t Size() const
static V8_INLINE WasmModuleObject * Cast(Value *obj)
Definition: v8.h:11593
CachedData & operator=(const CachedData &)=delete
static V8_WARN_UNUSED_RESULT MaybeLocal< Function > CompileFunctionInContext(Local< Context > context, Source *source, size_t arguments_count, Local< String > arguments[], size_t context_extension_count, Local< Object > context_extensions[], CompileOptions options=kNoCompileOptions, NoCacheReason no_cache_reason=kNoCacheNoReason, Local< ScriptOrModule > *script_or_module_out=nullptr)
MessageErrorLevel
Definition: v8.h:8417
Extension(const char *name, const char *source=nullptr, int dep_count=0, const char **deps=nullptr, int source_length=-1)
static bool InitializeICUDefaultLocation(const char *exec_path, const char *icu_data_file=nullptr)
size_t AddData(Local< Context > context, Local< T > object)
Definition: v8.h:11939
IndexedPropertySetterCallback setter
Definition: v8.h:6680
static Local< Value > New(Isolate *isolate, Local< String > value)
bool IsArgumentsObject() const
V8_INLINE TracedGlobal(TracedGlobal< S > &&other)
Definition: v8.h:969
virtual bool IsRunningMicrotasks() const =0
IndexedPropertyGetterCallback getter
Definition: v8.h:6679
static Local< AccessorSignature > New(Isolate *isolate, Local< FunctionTemplate > receiver=Local< FunctionTemplate >())
void(* MessageCallback)(Local< Message > message, Local< Value > data)
Definition: v8.h:7125
void VisitHandlesWithClassIds(PersistentHandleVisitor *visitor)
V8_WARN_UNUSED_RESULT Maybe< bool > SetPrototype(Local< Context > context, Local< Value > prototype)
size_t max_old_space_size() const
Definition: v8.h:7093
bool IsMapIterator() const
ExtensionConfiguration(int name_count, const char *names[])
Definition: v8.h:10118
bool IsWeakSet() const
IndexedPropertyHandlerConfiguration(IndexedPropertyGetterCallback getter, IndexedPropertySetterCallback setter, IndexedPropertyDescriptorCallback descriptor, IndexedPropertyDeleterCallback deleter, IndexedPropertyEnumeratorCallback enumerator, IndexedPropertyDefinerCallback definer, Local< Value > data=Local< Value >(), PropertyHandlerFlags flags=PropertyHandlerFlags::kNone)
Definition: v8.h:6660
size_t ByteLength() const
bool IsSharedCrossOrigin() const
Definition: v8.h:1365
V8_WARN_UNUSED_RESULT Maybe< PropertyAttribute > GetPropertyAttributes(Local< Context > context, Local< Value > key)
V8_WARN_UNUSED_RESULT MaybeLocal< Int32 > ToInt32(Local< Context > context) const
NamedPropertyHandlerConfiguration(GenericNamedPropertyGetterCallback getter, GenericNamedPropertySetterCallback setter, GenericNamedPropertyQueryCallback query, GenericNamedPropertyDeleterCallback deleter, GenericNamedPropertyEnumeratorCallback enumerator, GenericNamedPropertyDefinerCallback definer, GenericNamedPropertyDescriptorCallback descriptor, Local< Value > data=Local< Value >(), PropertyHandlerFlags flags=PropertyHandlerFlags::kNone)
Definition: v8.h:6551
friend class Persistent
Definition: v8.h:9717
static ScriptStreamingTask * StartStreamingScript(Isolate *isolate, StreamedSource *source, CompileOptions options=kNoCompileOptions)
bool Value() const
void GetHeapStatistics(HeapStatistics *heap_statistics)
Local< Value > GetResourceName()
static Local< Symbol > GetIterator(Isolate *isolate)
V8_INLINE Local< PrimitiveArray > HostDefinedOptions() const
Definition: v8.h:11156
static V8_WARN_UNUSED_RESULT MaybeLocal< RegExp > NewWithBacktrackLimit(Local< Context > context, Local< String > pattern, Flags flags, uint32_t backtrack_limit)
virtual const char * data() const =0
Local< String >(* WasmLoadSourceMapCallback)(Isolate *isolate, const char *name)
Definition: v8.h:7484
static Local< StackTrace > GetStackTrace(Local< Value > exception)
void SetAlignedPointerInInternalField(int index, void *value)
bool IsWasmModuleObject() const
SuppressMicrotaskExecutionScope(Isolate *isolate, MicrotaskQueue *microtask_queue=nullptr)
V8_INLINE void Set(uint32_t i)
Definition: v8.h:11001
void SetAddHistogramSampleFunction(AddHistogramSampleCallback)
V8_INLINE Isolate * GetIsolate() const
Definition: v8.h:11750
static Local< Symbol > New(Isolate *isolate, Local< String > description=Local< String >())
size_t total_physical_size()
Definition: v8.h:7577
V8_INLINE TracedReference< S > & As() const
Definition: v8.h:1154
bool BooleanValue(Isolate *isolate) const
bool IsApiWrapper()
size_t malloced_memory()
Definition: v8.h:7581
virtual void OnModuleCompiled(CompiledWasmModule compiled_module)=0
V8_INLINE void SetWeak(P *parameter, typename WeakCallbackInfo< P >::Callback callback, WeakCallbackType type)
Definition: v8.h:10727
void Set(S *whatever)
Definition: v8.h:11062
void SetJitCodeEventHandler(JitCodeEventOptions options, JitCodeEventHandler event_handler)
ResourceConstraints constraints
Definition: v8.h:8151
void MoveOnlyTypeForCPP03
Definition: v8.h:798
Local< Array > AsArray() const
size_t ByteLength() const
Definition: v8.h:5083
int GetScriptLineNumber() const
void operator=(const SealHandleScope &)=delete
V8_INLINE bool IsEmpty() const
Definition: v8.h:499
static const int kInternalFieldCount
Definition: v8.h:5295
V8_INLINE void AnnotateStrongRetainer(const char *label)
Definition: v8.h:10748
static V8_INLINE Int32Array * Cast(Value *obj)
Definition: v8.h:11672
void SetRAILMode(RAILMode rail_mode)
bool IsDetachable() const
static Local< Int16Array > New(Local< ArrayBuffer > array_buffer, size_t byte_offset, size_t length)
Isolate * GetIsolate()
virtual ~ExternalResourceVisitor()=default
static Local< Context > New(Isolate *isolate, ExtensionConfiguration *extensions=nullptr, MaybeLocal< ObjectTemplate > global_template=MaybeLocal< ObjectTemplate >(), MaybeLocal< Value > global_object=MaybeLocal< Value >(), DeserializeInternalFieldsCallback internal_fields_deserializer=DeserializeInternalFieldsCallback(), MicrotaskQueue *microtask_queue=nullptr)
static Local< Object > New(Isolate *isolate, Local< Value > prototype_or_null, Local< Name > *names, Local< Value > *values, size_t length)
size_t code_range_size_in_bytes() const
Definition: v8.h:7036
void MarkAsHandled()
size_t external_script_source_size()
Definition: v8.h:7654
static const int kDataIndex
Definition: v8.h:4300
void SetTreatArrayBufferViewsAsHostObjects(bool mode)
virtual void EnqueueMicrotask(Isolate *isolate, Local< Function > microtask)=0
Local< Value > ReThrow()
JSEntryStub js_run_microtasks_entry_stub
Definition: v8.h:2244
int GetColumnNumber()
Definition: v8.h:1463
bool has_value() const
Isolate & operator=(const Isolate &)=delete
size_t max_zone_pool_size() const
Definition: v8.h:7099
void Clear()
static V8_INLINE Set * Cast(Value *obj)
Definition: v8.h:11570
void DecreaseAllocatedSize(size_t bytes)
V8_EXPORT bool ShouldThrowOnError(v8::internal::Isolate *isolate)
bool MakeExternal(ExternalStringResource *resource)
V8_INLINE ~Source()
Definition: v8.h:11191
bool IsUint32() const
static Local< Array > New(Isolate *isolate, int length=0)
IndexFilter
Definition: v8.h:3646
V8_INLINE Local< Primitive > Undefined(Isolate *isolate)
Definition: v8.h:11789
const line_info_t * line_number_table
Definition: v8.h:7732
static V8_WARN_UNUSED_RESULT MaybeLocal< Module > CompileModule(Isolate *isolate, Source *source, CompileOptions options=kNoCompileOptions, NoCacheReason no_cache_reason=kNoCacheNoReason)
size_t max_old_generation_size_in_bytes() const
Definition: v8.h:7046
static V8_INLINE Int32 * Cast(v8::Value *obj)
Definition: v8.h:11470
MicrotasksScope(const MicrotasksScope &)=delete
internal::Address * implicit_args_
Definition: v8.h:4305
bool IsArrayBuffer() const
static Local< Uint8Array > New(Local< ArrayBuffer > array_buffer, size_t byte_offset, size_t length)
static bool PCIsInV8(size_t code_pages_length, const MemoryRange *code_pages, void *pc)
v8::Isolate * isolate_
Definition: v8.h:8014
bool(* WasmThreadsEnabledCallback)(Local< Context > context)
Definition: v8.h:7481
V8_INLINE bool ShouldThrowOnError() const
Definition: v8.h:11779
~ExternalStringResource() override=default
static void SetReturnAddressLocationResolver(ReturnAddressLocationResolver return_address_resolver)
int GetFrameCount() const
void operator=(const ValueSerializer &)=delete
virtual void FreeBufferMemory(void *buffer)
friend class PersistentValueMapBase
Definition: v8.h:9695
MicrotaskQueue & operator=(const MicrotaskQueue &)=delete
V8_WARN_UNUSED_RESULT Maybe< bool > SetLazyDataProperty(Local< Context > context, Local< Name > name, AccessorNameGetterCallback getter, Local< Value > data=Local< Value >(), PropertyAttribute attributes=None, SideEffectType getter_side_effect_type=SideEffectType::kHasSideEffect, SideEffectType setter_side_effect_type=SideEffectType::kHasSideEffect)
int InternalFieldCount()
static void InitializePlatform(Platform *platform)
PersistentBase(const PersistentBase &other)=delete
V8_INLINE Local< Integer > ResourceColumnOffset() const
Definition: v8.h:11165
bool IsWebAssemblyCompiledModule() const
V8_INLINE ReturnValue< T > GetReturnValue() const
Definition: v8.h:11774
uint32_t GetWireFormatVersion() const
KeyCollectionMode
Definition: v8.h:3640
virtual size_t length() const =0
static V8_INLINE Local< Context > CreationContext(const PersistentBase< Object > &object)
Definition: v8.h:4025
virtual void VisitExternalString(Local< String > string)
Definition: v8.h:7806
static constexpr size_t kMaxLength
Definition: v8.h:5315
void(* AccessorGetterCallback)(Local< String > property, const PropertyCallbackInfo< Value > &info)
Definition: v8.h:3571
static std::unique_ptr< BackingStore > NewBackingStore(void *data, size_t byte_length, BackingStoreDeleterCallback deleter, void *deleter_data)
bool(* AllowCodeGenerationFromStringsCallback)(Local< Context > context, Local< String > source)
Definition: v8.h:7447
size_t ByteLength() const
Value(const Value &)=delete
static Local< SharedArrayBuffer > New(Isolate *isolate, std::shared_ptr< BackingStore > backing_store)
static V8_INLINE void * GetAlignedPointerFromInternalField(const PersistentBase< Object > &object, int index)
Definition: v8.h:3916
~TracedGlobal()
Definition: v8.h:937
V8_INLINE Persistent()
Definition: v8.h:659
bool enumerable() const
static const int kTheHoleValueRootIndex
Definition: v8-internal.h:175
static V8_INLINE void * GetAlignedPointerFromInternalField(const TracedReferenceBase< Object > &object, int index)
Definition: v8.h:3922
V8_INLINE PromiseRejectEvent GetEvent() const
Definition: v8.h:7283
void SetClient(std::shared_ptr< Client > client)
double ValueOf() const
V8_INLINE ReturnValue(const ReturnValue< S > &that)
Definition: v8.h:4205
void WriteRawBytes(const void *source, size_t length)
V8_WARN_UNUSED_RESULT bool ReadUint64(uint64_t *value)
void SetAcceptAnyReceiver(bool value)
static Local< Float64Array > New(Local< SharedArrayBuffer > shared_array_buffer, size_t byte_offset, size_t length)
size_t initial_old_generation_size_in_bytes() const
Definition: v8.h:7065
static MaybeLocal< BigInt > NewFromWords(Local< Context > context, int sign_bit, int word_count, const uint64_t *words)
V8_INLINE void SetNull()
Definition: v8.h:11026
static constexpr int kFlagCount
Definition: v8.h:5854
static MaybeLocal< FunctionTemplate > FromSnapshot(Isolate *isolate, size_t index)
void operator=(const PersistentBase &)=delete
PrivateData * get_private() const
Definition: v8.h:4674
static const int kReturnValueDefaultValueIndex
Definition: v8.h:4298
bool(* AccessCheckCallback)(Local< Context > accessing_context, Local< Object > accessed_object, Local< Value > data)
Definition: v8.h:6298
void set_max_young_generation_size_in_bytes(size_t limit)
Definition: v8.h:7061
V8_WARN_UNUSED_RESULT MaybeLocal< Value > Get(Local< Context > context, Local< Value > key)
static Local< Private > New(Isolate *isolate, Local< String > name=Local< String >())
V8_INLINE Local< Integer > ScriptID() const
Definition: v8.h:11170
void DetachGlobal()
void IncreaseHeapLimitForDebugging()
StartupData * snapshot_blob
Definition: v8.h:8156
MaybeLocal< Module >(* ResolveCallback)(Local< Context > context, Local< String > specifier, Local< Module > referrer)
Definition: v8.h:1526
void size_t ArrayBufferCreationMode mode
Definition: v8.h:5132
static const int kNodeStateIsWeakValue
Definition: v8-internal.h:184
Local< Symbol > ValueOf() const
void set_max_zone_pool_size(size_t bytes)
Definition: v8.h:7101
void TransferArrayBuffer(uint32_t transfer_id, Local< ArrayBuffer > array_buffer)
static bool Initialize()
static V8_INLINE bool IsExternalTwoByteString(int instance_type)
Definition: v8-internal.h:240
static Local< Int32Array > New(Local< SharedArrayBuffer > shared_array_buffer, size_t byte_offset, size_t length)
Local< Boolean > ToBoolean(Isolate *isolate) const
SnapshotCreator(Isolate *isolate, const intptr_t *external_references=nullptr, StartupData *existing_blob=nullptr)
TracedReference< T > & operator=(const TracedReference< S > &rhs)
Definition: v8.h:10885
void * top_context
Definition: v8.h:2221
const int kApiSystemPointerSize
Definition: v8-internal.h:32
static bool EnableWebAssemblyTrapHandler(bool use_v8_signal_handler)
void Revoke()
void set_initial_old_generation_size_in_bytes(size_t initial_size)
Definition: v8.h:7068
V8_INLINE void SetFinalizationCallback(void *parameter, WeakCallbackInfo< void >::Callback callback)
Definition: v8.h:10941
V8_INLINE ~Scope()
Definition: v8.h:10358
V8_INLINE Local< Primitive > Null(Isolate *isolate)
Definition: v8.h:11798
V8_INLINE Source(Local< String > source_string, CachedData *cached_data=nullptr)
Definition: v8.h:11186
V8_INLINE bool operator==(const PersistentBase< S > &that) const
Definition: v8.h:507
friend class PersistentBase
Definition: v8.h:9716
virtual void Free(void *data, size_t length)=0
static const int kReturnValueIndex
Definition: v8.h:4414
static void SetFlagsFromCommandLine(int *argc, char **argv, bool remove_flags)
V8_INLINE bool operator!=(const Maybe &other) const
Definition: v8.h:9887
bool has_configurable() const
ArrayBuffer::Allocator * GetArrayBufferAllocator()
static Local< Symbol > For(Isolate *isolate, Local< String > description)
Local< String > GetScriptNameOrSourceURL() const
Definition: libplatform.h:15
int GetWasmFunctionIndex() const
bool HasInstance(Local< Value > object)
MemoryRange embedded_code_range
Definition: v8.h:2235
size_t number_of_detached_contexts()
Definition: v8.h:7585
static Local< Map > New(Isolate *isolate)
Global< T > & operator=(Global< S > &&rhs)
Definition: v8.h:10783
void(* IndexedPropertyQueryCallback)(uint32_t index, const PropertyCallbackInfo< Integer > &info)
Definition: v8.h:6249
Local< Context > GetCurrentContext()
MemorySpan< const uint8_t > serialized_module
Definition: v8.h:4795
virtual void EnqueueMicrotask(v8::Isolate *isolate, MicrotaskCallback callback, void *data=nullptr)=0
void * Data() const
Definition: v8.h:5082
void(* GenericNamedPropertyGetterCallback)(Local< Name > property, const PropertyCallbackInfo< Value > &info)
Definition: v8.h:6100
Local< Value > GetHandler()
static V8_INLINE bool HasHeapObjectTag(const internal::Address value)
Definition: v8-internal.h:214
EventType type
Definition: v8.h:7694
void RemoveNearHeapLimitCallback(NearHeapLimitCallback callback, size_t heap_limit)
static bool PCIsInV8(const UnwindState &unwind_state, void *pc)
#define V8_PROMISE_INTERNAL_FIELD_COUNT
Definition: v8.h:4519
Local< Value > get() const
V8_WARN_UNUSED_RESULT V8_INLINE bool ToLocal(Local< S > *out) const
Definition: v8.h:376
static V8_INLINE SymbolObject * Cast(Value *obj)
Definition: v8.h:11508
static const int kNativeContextEmbedderDataOffset
Definition: v8-internal.h:149
bool IsGeneratorObject() const
static const int kInferShouldThrowMode
Definition: v8-internal.h:201
V8_INLINE bool operator!=(const Maybe &other) const
Definition: v8.h:9925
V8_INLINE Local< Object > This() const
Definition: v8.h:11762
void SetAccessorProperty(Local< Name > name, Local< FunctionTemplate > getter=Local< FunctionTemplate >(), Local< FunctionTemplate > setter=Local< FunctionTemplate >(), PropertyAttribute attribute=None, AccessControl settings=DEFAULT)
V8_WARN_UNUSED_RESULT MaybeLocal< Value > StackTrace(Local< Context > context) const
ValueSerializer(const ValueSerializer &)=delete
EscapableHandleScope(Isolate *isolate)
void(* callback)(Local< Object > holder, int index, StartupData payload, void *data)
Definition: v8.h:8050
MeasureMemoryExecution
Definition: v8.h:8069
Maybe< bool > HasPrivate(Local< Context > context, Local< Private > key)
static V8_INLINE int GetInstanceType(const internal::Address obj)
Definition: v8-internal.h:230
static V8_WARN_UNUSED_RESULT MaybeLocal< RegExp > New(Local< Context > context, Local< String > pattern, Flags flags)
V8_WARN_UNUSED_RESULT V8_INLINE bool To(T *out) const
Definition: v8.h:9860
bool has_enumerable() const
friend class Local
Definition: v8.h:9702
V8_INLINE bool operator==(const Maybe &other) const
Definition: v8.h:9882
static V8_INLINE void CheckInitialized(v8::Isolate *isolate)
Definition: v8-internal.h:208
Local< Value > Name() const
void WriteUint64(uint64_t value)
V8_INLINE Local()
Definition: v8.h:191
MaybeLocal< Array > PreviewEntries(bool *is_key_value)
static V8_INLINE NumberObject * Cast(Value *obj)
Definition: v8.h:11516
V8_WARN_UNUSED_RESULT Maybe< bool > SetAccessor(Local< Context > context, Local< Name > name, AccessorNameGetterCallback getter, AccessorNameSetterCallback setter=nullptr, MaybeLocal< Value > data=MaybeLocal< Value >(), AccessControl settings=DEFAULT, PropertyAttribute attribute=None, SideEffectType getter_side_effect_type=SideEffectType::kHasSideEffect, SideEffectType setter_side_effect_type=SideEffectType::kHasSideEffect)
void SetInternalFieldCount(int value)
Maybe< bool > SetPrivate(Local< Context > context, Local< Private > key, Local< Value > value)
HandleScope(Isolate *isolate)
static V8_INLINE constexpr internal::Address IntToSmi(int value)
Definition: v8-internal.h:222
void SetPromiseHook(PromiseHook hook)
static bool TryUnwindV8Frames(const UnwindState &unwind_state, RegisterState *register_state, const void *stack_base)
void IsolateInForegroundNotification()
static Local< ArrayBuffer > New(Isolate *isolate, std::shared_ptr< BackingStore > backing_store)
CallbackFunction callback
Definition: v8.h:8033
MicrotasksScope(Isolate *isolate, Type type)
void * sp
Definition: v8.h:2210
Maybe< bool > InstanceOf(Local< Context > context, Local< Object > object)
void SetAtomicsWaitCallback(AtomicsWaitCallback callback, void *data)
int ScriptId() const
V8_WARN_UNUSED_RESULT Maybe< bool > DefineOwnProperty(Local< Context > context, Local< Name > key, Local< Value > value, PropertyAttribute attributes=None)
Local< Value > GetSecurityToken()
V8_INLINE TracedReferenceBase< S > & As() const
Definition: v8.h:895
bool HasIndexedLookupInterceptor()
V8_INLINE bool IsJust() const
Definition: v8.h:9919
V8_INLINE Isolate * GetIsolate() const
Definition: v8.h:438
Isolate * GetIsolate() const
bool(* EntropySource)(unsigned char *buffer, size_t length)
Definition: v8.h:9468
V8_WARN_UNUSED_RESULT MaybeLocal< Object > NewInstanceWithSideEffectType(Local< Context > context, int argc, Local< Value > argv[], SideEffectType side_effect_type=SideEffectType::kHasSideEffect) const
MeasureMemoryMode
Definition: v8.h:8061
void RemoveMessageListeners(MessageCallback that)
void SetAccessor(Local< String > name, AccessorGetterCallback getter, AccessorSetterCallback setter=nullptr, Local< Value > data=Local< Value >(), AccessControl settings=DEFAULT, PropertyAttribute attribute=None, Local< AccessorSignature > signature=Local< AccessorSignature >(), SideEffectType getter_side_effect_type=SideEffectType::kHasSideEffect, SideEffectType setter_side_effect_type=SideEffectType::kHasSideEffect)
V8_WARN_UNUSED_RESULT MaybeLocal< Array > GetPropertyNames(Local< Context > context, KeyCollectionMode mode, PropertyFilter property_filter, IndexFilter index_filter, KeyConversionMode key_conversion=KeyConversionMode::kKeepNumbers)
size_t NumberOfHeapSpaces()
V8_INLINE TracedGlobal & operator=(const TracedGlobal &rhs)
Definition: v8.h:10853
V8_INLINE ~Global()
Definition: v8.h:782
const char * operator*() const
Definition: v8.h:3299
V8_INLINE void SetData(uint32_t slot, void *data)
Definition: v8.h:11825
DeserializeInternalFieldsCallback DeserializeEmbedderFieldsCallback
Definition: v8.h:8054
int GetEndPosition() const
Isolate()=delete
void ConfigureDefaults(uint64_t physical_memory, uint64_t virtual_memory_limit)
Maybe< void > JustVoid()
Definition: v8.h:9942
static V8_INLINE Symbol * Cast(Value *obj)
Definition: v8.h:11438
static std::unique_ptr< BackingStore > NewBackingStore(Isolate *isolate, size_t byte_length)
static Local< Integer > NewFromUnsigned(Isolate *isolate, uint32_t value)
static Local< Uint32Array > New(Local< ArrayBuffer > array_buffer, size_t byte_offset, size_t length)
TryCatch(Isolate *isolate)
UnwindState GetUnwindState()
V8_INLINE bool IsNull() const
Definition: v8.h:11365
MaybeLocal< T > GetDataFromSnapshotOnce(size_t index)
Definition: v8.h:11843
const uint16_t * operator*() const
Definition: v8.h:3322
ValueSerializer(Isolate *isolate, Delegate *delegate)
virtual void TraceEpilogue(TraceSummary *trace_summary)
Definition: v8.h:7939
uint32_t Value() const
Local< Object > Global()
int raw_size
Definition: v8.h:9460
V8_INLINE MaybeLocal< T > EscapeMaybe(MaybeLocal< T > value)
Definition: v8.h:1257
const char ** begin() const
Definition: v8.h:10121
size_t AllocationLength() const
Definition: v8.h:5563
V8_WARN_UNUSED_RESULT MaybeLocal< Value > GetOwnPropertyDescriptor(Local< Context > context, Local< Name > key)
Value(Isolate *isolate, Local< v8::Value > obj)
void operator=(const ExternalStringResourceBase &)=delete
void SetHostInitializeImportMetaObjectCallback(HostInitializeImportMetaObjectCallback callback)
V8_INLINE Unlocker(Isolate *isolate)
Definition: v8.h:10488
bool IsBoolean() const
bool ContainsOnlyOneByte() const
static bool Dispose()
static Local< Module > CreateSyntheticModule(Isolate *isolate, Local< String > module_name, const std::vector< Local< String >> &export_names, SyntheticModuleEvaluationSteps evaluation_steps)
void(* AccessorNameSetterCallback)(Local< Name > property, Local< Value > value, const PropertyCallbackInfo< void > &info)
Definition: v8.h:3583
V8_WARN_UNUSED_RESULT MaybeLocal< BigInt > ToBigInt(Local< Context > context) const
void SetWasmInstanceCallback(ExtensionCallback callback)
Local< Array > AsArray() const
bool InContext()
virtual void Unlock() const
Definition: v8.h:3123
static CachedData * CreateCodeCacheForFunction(Local< Function > function)
V8_INLINE TracedGlobal(TracedGlobal &&other)
Definition: v8.h:960
void(* MicrotasksCompletedCallbackWithData)(Isolate *, void *)
Definition: v8.h:7297
bool IsSymbolObject() const
void * Value() const
~ExternalOneByteStringResource() override=default
V8_INLINE TracedReference & operator=(const TracedReference &rhs)
Definition: v8.h:10903
bool IsOpaque() const
Definition: v8.h:1368
void Abort(MaybeLocal< Value > exception)
static Local< Number > New(Isolate *isolate, double value)
V8_INLINE Local< Object > Holder() const
Definition: v8.h:11768
void SetAddCrashKeyCallback(AddCrashKeyCallback)
void Enter()
static V8_INLINE T ReadRawField(internal::Address heap_object_ptr, int offset)
Definition: v8-internal.h:291
virtual bool ShouldMeasure(Local< Context > context)=0
static const int kReturnValueDefaultValueIndex
Definition: v8.h:4413
V8_WARN_UNUSED_RESULT Maybe< bool > Has(Local< Context > context, Local< Value > key)
MaybeLocal< Promise > MeasureMemory(Local< Context > context, MeasureMemoryMode mode)
GCType
Definition: v8.h:7496
int WriteOneByte(Isolate *isolate, uint8_t *buffer, int start=0, int length=-1, int options=NO_OPTIONS) const
Local< Context > GetEnteredOrMicrotaskContext()
#define V8_UNLIKELY(condition)
Definition: v8config.h:413
static const int kEmbedderDataArrayHeaderSize
Definition: v8-internal.h:147
V8_INLINE bool operator==(const Local< S > &that) const
Definition: v8.h:516
V8_WARN_UNUSED_RESULT Maybe< bool > HasRealNamedCallbackProperty(Local< Context > context, Local< Name > key)
static V8_WARN_UNUSED_RESULT MaybeLocal< String > NewFromOneByte(Isolate *isolate, const uint8_t *data, NewStringType type=NewStringType::kNormal, int length=-1)
V8_INLINE TracedGlobal & operator=(TracedGlobal &&rhs)
Definition: v8.h:10843
static Local< Value > New(Isolate *isolate, bool value)
Contents GetContents()
RAILMode
Definition: v8.h:7758
uint32_t GetNumberOfEmbedderDataFields()
void set_stack_limit(uint32_t *value)
Definition: v8.h:7030
V8_WARN_UNUSED_RESULT Maybe< bool > ReadHeader(Local< Context > context)
int length() const
Definition: v8.h:3323
V8_INLINE void Empty()
Definition: v8.h:500
const intptr_t * external_references
Definition: v8.h:8192
JSEntryStub js_construct_entry_stub
Definition: v8.h:2243
virtual ~MeasureMemoryDelegate()=default
V8_INLINE Local< T > ToLocalChecked()
Definition: v8.h:10649
void SetAlignedPointerInEmbedderData(int index, void *value)
static const int kDontThrow
Definition: v8-internal.h:200
void SetErrorMessageForCodeGenerationFromStrings(Local< String > message)
static void InitializeExternalStartupData(const char *directory_path)
void SetWasmLoadSourceMapCallback(WasmLoadSourceMapCallback callback)
static Local< Symbol > GetSplit(Isolate *isolate)
static const int kUndefinedValueRootIndex
Definition: v8-internal.h:174
V8_WARN_UNUSED_RESULT MaybeLocal< Value > GetRealNamedPropertyInPrototypeChain(Local< Context > context, Local< Name > key)
AccessType
Definition: v8.h:6285
static V8_INLINE void SetEmbedderData(v8::Isolate *isolate, uint32_t slot, void *data)
Definition: v8-internal.h:267
size_t NumberOfTrackedHeapObjectTypes()
void operator=(const SnapshotCreator &)=delete
void Set(Local< Name > name, Local< Data > value, PropertyAttribute attributes=None)
V8_INLINE bool operator!=(const Local< S > &that) const
Definition: v8.h:879
static const int kOddballType
Definition: v8-internal.h:188
double ValueOf() const
static const int kInternalFieldCount
Definition: v8.h:5727
void(* JitCodeEventHandler)(const JitCodeEvent *event)
Definition: v8.h:7790
static V8_INLINE String * Cast(v8::Value *obj)
Definition: v8.h:11289
bool HasNamedLookupInterceptor()
void(* GenericNamedPropertyDescriptorCallback)(Local< Name > property, const PropertyCallbackInfo< Value > &info)
Definition: v8.h:6228
int Length() const
V8_INLINE FunctionCallbackInfo(internal::Address *implicit_args, internal::Address *values, int length)
Definition: v8.h:11074
static V8_INLINE External * Cast(Value *obj)
Definition: v8.h:11741
static MaybeLocal< Function > New(Local< Context > context, FunctionCallback callback, Local< Value > data=Local< Value >(), int length=0, ConstructorBehavior behavior=ConstructorBehavior::kAllow, SideEffectType side_effect_type=SideEffectType::kHasSideEffect)
void VisitExternalResources(ExternalResourceVisitor *visitor)
Global Pass()
Definition: v8.h:793
static MaybeLocal< WasmModuleObject > FromCompiledModule(Isolate *isolate, const CompiledWasmModule &)
V8_INLINE bool IsWeak() const
Definition: v8.h:10688
void(* PromiseHook)(PromiseHookType type, Local< Promise > promise, Local< Value > parent)
Definition: v8.h:7265
static constexpr size_t kMinCodePagesBufferSize
Definition: v8.h:9229
static void SetFlagsFromString(const char *str, size_t length)
virtual bool IsRootForNonTracingGC(const v8::TracedReference< v8::Value > &handle)
SealHandleScope(const SealHandleScope &)=delete
void SetCounterFunction(CounterLookupCallback)
virtual Local< FunctionTemplate > GetNativeFunctionTemplate(Isolate *isolate, Local< String > name)
Definition: v8.h:6940
void SetClassName(Local< String > name)
Local< Value > GetName() const
bool IsUint16Array() const
void OnBytesReceived(const uint8_t *, size_t size)
static V8_INLINE Integer * Cast(v8::Value *obj)
Definition: v8.h:11462
friend class PropertyCallbackInfo
Definition: v8.h:4240
bool IsModuleNamespaceObject() const
void AddNearHeapLimitCallback(NearHeapLimitCallback callback, void *data)
Intrinsic
Definition: v8.h:5958
TracedGlobal< T > & operator=(const TracedGlobal< S > &rhs)
Definition: v8.h:10836
Local< BigInt > ValueOf() const
virtual size_t GetMoreData(const uint8_t **src)=0
MaybeLocal< Value >(* SyntheticModuleEvaluationSteps)(Local< Context > context, Local< Module > module)
Definition: v8.h:1572
MicrotasksPolicy
Definition: v8.h:7308
MaybeLocal< String > modified_source
Definition: v8.h:7456
static const int kFalseValueRootIndex
Definition: v8-internal.h:178
void set_configurable(bool configurable)
void RemoveBeforeCallEnteredCallback(BeforeCallEnteredCallback callback)
bool StringEquals(Local< String > str)
virtual bool AdvanceTracing(double deadline_in_ms)=0
void Externalize(const std::shared_ptr< BackingStore > &backing_store)
bool IsUint32Array() const
OwnedBuffer()=default
friend Maybe< U > Nothing()
Definition: v8.h:9905
void EnqueueMicrotask(Local< Function > microtask)
static V8_INLINE ArrayBuffer * Cast(Value *obj)
Definition: v8.h:11608
static V8_INLINE Local< T > Cast(Local< S > that)
Definition: v8.h:270
void TransferArrayBuffer(uint32_t transfer_id, Local< ArrayBuffer > array_buffer)
V8_INLINE bool operator==(const Maybe &other) const
Definition: v8.h:9921
void Set(Isolate *isolate, Local< S > handle)
Definition: v8.h:10634
V8_INLINE Global(Global &&other)
Definition: v8.h:10773
void Clear()
TracedReference(Isolate *isolate, Local< S > that)
Definition: v8.h:1074
V8_WARN_UNUSED_RESULT MaybeLocal< Object > NewRemoteInstance()
void Set(Isolate *isolate, int index, Local< Primitive > item)
#define V8_DEPRECATED(message)
Definition: v8config.h:396
std::shared_ptr< BackingStore > GetBackingStore()
Local< T > Get(Isolate *isolate) const
Definition: v8.h:853
static const int kShouldThrowOnErrorIndex
Definition: v8.h:4410
int WordCount() const
static V8_INLINE Local< T > New(Isolate *isolate, const TracedReferenceBase< T > &that)
Definition: v8.h:10618
Local< Value > GetModuleNamespace()
Extension(const Extension &)=delete
size_t ByteLength() const
Definition: v8.h:5569
JitCodeEventHandler code_event_handler
Definition: v8.h:8146
ConstructorBehavior
Definition: v8.h:4425
size_t CopyContents(void *dest, size_t byte_length)
V8_WARN_UNUSED_RESULT Maybe< bool > Set(Local< Context > context, uint32_t index, Local< Value > value)
V8_INLINE Local(Local< S > that)
Definition: v8.h:193
V8_INLINE bool IsEmpty() const
Definition: v8.h:206
TracedGlobal()
Definition: v8.h:942
V8_INLINE bool operator==(const Local< S > &that) const
Definition: v8.h:865
void SetCreateHistogramFunction(CreateHistogramCallback)
V8_INLINE void SetFinalizationCallback(void *parameter, WeakCallbackInfo< void >::Callback callback)
Definition: v8.h:10934
Definition: v8.h:2195
Definition: v8.h:4111
bool HasTerminated() const
static V8_INLINE BooleanObject * Cast(Value *obj)
Definition: v8.h:11530
void(* FunctionCallback)(const FunctionCallbackInfo< Value > &info)
Definition: v8.h:4423
bool HasCaught() const
IndexedPropertyHandlerConfiguration(IndexedPropertyGetterCallback getter=nullptr, IndexedPropertySetterCallback setter=nullptr, IndexedPropertyQueryCallback query=nullptr, IndexedPropertyDeleterCallback deleter=nullptr, IndexedPropertyEnumeratorCallback enumerator=nullptr, Local< Value > data=Local< Value >(), PropertyHandlerFlags flags=PropertyHandlerFlags::kNone)
Definition: v8.h:6641
IndexedPropertyQueryCallback query
Definition: v8.h:6681
bool IsOneByte() const
ArrayBuffer::Allocator * array_buffer_allocator
Definition: v8.h:8183
static const int kEmptyStringRootIndex
Definition: v8-internal.h:179
NamedPropertyHandlerConfiguration(GenericNamedPropertyGetterCallback getter=nullptr, GenericNamedPropertySetterCallback setter=nullptr, GenericNamedPropertyQueryCallback query=nullptr, GenericNamedPropertyDeleterCallback deleter=nullptr, GenericNamedPropertyEnumeratorCallback enumerator=nullptr, Local< Value > data=Local< Value >(), PropertyHandlerFlags flags=PropertyHandlerFlags::kNone)
Definition: v8.h:6571
Source & operator=(const Source &)=delete
static MaybeLocal< Context > FromSnapshot(Isolate *isolate, size_t context_snapshot_index, DeserializeInternalFieldsCallback embedder_fields_deserializer=DeserializeInternalFieldsCallback(), ExtensionConfiguration *extensions=nullptr, MaybeLocal< Value > global_object=MaybeLocal< Value >(), MicrotaskQueue *microtask_queue=nullptr)
void TerminateExecution()
Definition: v8.h:2196
static V8_INLINE BigIntObject * Cast(Value *obj)
Definition: v8.h:11523
static Local< External > New(Isolate *isolate, void *value)
const String::ExternalOneByteStringResource * source() const
Definition: v8.h:6947
MicrotaskQueue(const MicrotaskQueue &)=delete
static Local< SharedArrayBuffer > New(Isolate *isolate, size_t byte_length)
void AutomaticallyRestoreInitialHeapLimit(double threshold_percent=0.5)
static V8_INLINE Name * Cast(Value *obj)
Definition: v8.h:11430
SafeForTerminationScope(v8::Isolate *isolate)
int Write(Isolate *isolate, uint16_t *buffer, int start=0, int length=-1, int options=NO_OPTIONS) const
bool IsName() const
void SetLazyDataProperty(Local< Name > name, AccessorNameGetterCallback getter, Local< Value > data=Local< Value >(), PropertyAttribute attribute=None, SideEffectType getter_side_effect_type=SideEffectType::kHasSideEffect, SideEffectType setter_side_effect_type=SideEffectType::kHasSideEffect)
Locker(const Locker &)=delete
Definition: v8.h:3557
bool IsCodeGenerationFromStringsAllowed()
V8_INLINE MaybeLocal()
Definition: v8.h:362
bool IsNativeError() const
virtual ~Allocator()=default
size_t Length()
Local< Promise > GetPromise()
V8_INLINE Local< Object > Holder() const
Definition: v8.h:11093
V8_INLINE ~EscapableHandleScope()=default
bool HasBuffer() const
bool AddMessageListenerWithErrorLevel(MessageCallback that, int message_levels, Local< Value > data=Local< Value >())
Local< Value > GetScriptResourceName() const
void AddGCPrologueCallback(GCCallback callback, GCType gc_type_filter=kGCTypeAll)
static Local< Symbol > GetHasInstance(Isolate *isolate)
static V8_INLINE void Copy(const Persistent< S, M > &source, NonCopyablePersistent *dest)
Definition: v8.h:619
V8_WARN_UNUSED_RESULT MaybeLocal< Array > GetPropertyNames(Local< Context > context)
V8_WARN_UNUSED_RESULT MaybeLocal< String > ToDetailString(Local< Context > context) const
SideEffectType
Definition: v8.h:3627
static V8_WARN_UNUSED_RESULT Maybe< bool > Cleanup(Local< FinalizationGroup > finalization_group)
V8_INLINE Isolate * GetIsolate() const
Definition: v8.h:11111
V8_INLINE bool operator==(const TracedReferenceBase< S > &that) const
Definition: v8.h:856
ValueDeserializer(Isolate *isolate, const uint8_t *data, size_t size, Delegate *delegate)
void * AllocationBase() const
Definition: v8.h:5562
static const int kIsolateIndex
Definition: v8.h:4297
virtual void PerformCheckpoint(Isolate *isolate)=0
static bool IsRunningMicrotasks(Isolate *isolate)
void set_initial_young_generation_size_in_bytes(size_t initial_size)
Definition: v8.h:7075
static Local< StackTrace > CurrentStackTrace(Isolate *isolate, int frame_limit, StackTraceOptions options=kDetailed)
internal::Address * args_
Definition: v8.h:4419
static V8_WARN_UNUSED_RESULT MaybeLocal< String > NewFromUtf8(Isolate *isolate, const char *data, NewStringType type=NewStringType::kNormal, int length=-1)
Local< ObjectTemplate > InstanceTemplate()
static bool IsActive()
MemoryRange code_range
Definition: v8.h:2234
static V8_WARN_UNUSED_RESULT MaybeLocal< Value > New(Local< Context > context, double time)
bool configurable() const
V8_EXPORT internal::Isolate * IsolateFromNeverReadOnlySpaceObject(Address obj)
void(* AddCrashKeyCallback)(CrashKeyId id, const std::string &value)
Definition: v8.h:7178
ScriptOrigin GetScriptOrigin() const
void SetAbortScriptExecution(AbortScriptExecutionCallback callback)
PropertyDescriptor(const PropertyDescriptor &)=delete
DisallowJavascriptExecutionScope & operator=(const DisallowJavascriptExecutionScope &)=delete
void EnqueueMicrotask(MicrotaskCallback callback, void *data=nullptr)
void AddGCEpilogueCallback(GCCallbackWithData callback, void *data=nullptr, GCType gc_type_filter=kGCTypeAll)
int GetIdentityHash() const
V8_INLINE Local< Boolean > False(Isolate *isolate)
Definition: v8.h:11816
virtual ~Client()=default
void SetPrototypeProviderTemplate(Local< FunctionTemplate > prototype_provider)
PromiseState
Definition: v8.h:4531
void SetSecurityToken(Local< Value > token)
int Flags() const
Definition: v8.h:1372
StreamedSource(const StreamedSource &)=delete
bool IsNumber() const
virtual ~Extension()
Definition: v8.h:6939
V8_INLINE ScriptOriginOptions(int flags)
Definition: v8.h:1361
friend class TracedGlobal
Definition: v8.h:9710
Definition: v8.h:4687
static const int kEmbedderFieldCount
Definition: v8.h:5297
bool IsNumberObject() const
void TransferSharedArrayBuffer(uint32_t id, Local< SharedArrayBuffer > shared_array_buffer)
Status GetStatus() const
uint16_t * operator*()
Definition: v8.h:3321
int Utf8Length(Isolate *isolate) const
size_t source_length() const
Definition: v8.h:6946
bool IsWeakMap() const
int GetEndColumn() const
int ErrorLevel() const
EmbedderHeapTracer * GetEmbedderHeapTracer()
static void SetDcheckErrorHandler(DcheckErrorCallback that)
V8_WARN_UNUSED_RESULT Maybe< bool > HasRealIndexedProperty(Local< Context > context, uint32_t index)
Local< UnboundScript > GetUnboundScript()
static Allocator * NewDefaultAllocator()
static V8_WARN_UNUSED_RESULT MaybeLocal< Value > StackTrace(Local< Context > context, Local< Value > exception)
static Isolate * GetCurrent()
V8_WARN_UNUSED_RESULT MaybeLocal< Function > GetFunction(Local< Context > context)
virtual void VisitTracedGlobalHandle(const TracedGlobal< Value > &handle)
Definition: v8.h:7857
JSEntryStub js_construct_entry_stub
Definition: v8.h:2237
Local< String > GetScriptName() const
AllowJavascriptExecutionScope & operator=(const AllowJavascriptExecutionScope &)=delete
V8_INLINE void ClearWeak()
Definition: v8.h:559
void GetCodeRange(void **start, size_t *length_in_bytes)
V8_INLINE ScriptOriginOptions(bool is_shared_cross_origin=false, bool is_opaque=false, bool is_wasm=false, bool is_module=false)
Definition: v8.h:1355
V8_INLINE T ToChecked() const
Definition: v8.h:9846
static Local< Integer > New(Isolate *isolate, int32_t value)
V8_WARN_UNUSED_RESULT MaybeLocal< Value > Evaluate(Local< Context > context)
void SetOOMErrorHandler(OOMErrorCallback that)
V8_INLINE bool IsEmpty() const
Definition: v8.h:413
JSEntryStub js_entry_stub
Definition: v8.h:2236
V8_WARN_UNUSED_RESULT Maybe< double > NumberValue(Local< Context > context) const
void SetPrepareStackTraceCallback(PrepareStackTraceCallback callback)
static internal::Address * CreateHandle(internal::Isolate *isolate, internal::Address value)
Local< Script > BindToCurrentContext()
V8_WARN_UNUSED_RESULT MaybeLocal< Integer > ToInteger(Local< Context > context) const
void operator=(const EscapableHandleScope &)=delete
static Local< Value > SyntaxError(Local< String > message)
void IsolateInBackgroundNotification()
IndexedPropertyEnumeratorCallback enumerator
Definition: v8.h:6683
V8_INLINE void Set(bool value)
Definition: v8.h:11013
void SetHostCleanupFinalizationGroupCallback(HostCleanupFinalizationGroupCallback callback)
V8_INLINE ScriptOriginOptions Options() const
Definition: v8.h:1407
void SetAllowWasmCodeGenerationCallback(AllowWasmCodeGenerationCallback callback)
void SetWasmModuleCallback(ExtensionCallback callback)
void SetHandler(const IndexedPropertyHandlerConfiguration &configuration)
SerializeInternalFieldsCallback(CallbackFunction function=nullptr, void *data_arg=nullptr)
Definition: v8.h:8030
V8_WARN_UNUSED_RESULT MaybeLocal< Object > Exec(Local< Context > context, Local< String > subject)
void RegisterEmbedderReference(const TracedReferenceBase< v8::Data > &ref)
void SetSecondPassCallback(Callback callback) const
Definition: v8.h:448
void set_max_old_space_size(size_t limit_in_mb)
Definition: v8.h:7095
static V8_INLINE constexpr bool IsValidSmi(intptr_t value)
Definition: v8-internal.h:226
static V8_INLINE DataView * Cast(Value *obj)
Definition: v8.h:11717
int WriteUtf8(Isolate *isolate, char *buffer, int length=-1, int *nchars_ref=nullptr, int options=NO_OPTIONS) const
V8_INLINE Isolate * GetIsolate() const
Definition: v8.h:1199
V8_INLINE void Check() const
Definition: v8.h:9852
void RemoveMicrotasksCompletedCallback(MicrotasksCompletedCallbackWithData callback, void *data=nullptr)
Local< Value > set() const
WasmModuleObjectBuilderStreaming(Isolate *isolate)
PropertyDescriptor(Local< Value > value, bool writable)
bool IsDate() const
static V8_INLINE Promise * Cast(Value *obj)
Definition: v8.h:11578
Local< Primitive > Get(Isolate *isolate, int index)
Maybe< bool > SetIntegrityLevel(Local< Context > context, IntegrityLevel level)
size_t space_size()
Definition: v8.h:7616
void operator=(const ValueDeserializer &)=delete
V8_WARN_UNUSED_RESULT bool ReadDouble(double *value)
void(* UseCounterCallback)(Isolate *isolate, UseCounterFeature feature)
Definition: v8.h:8427
V8_INLINE bool operator!=(const Local< S > &that) const
Definition: v8.h:256
#define V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT
Definition: v8.h:5253
bool IsFloat64Array() const
V8_INLINE void * GetInternalField(int index) const
Definition: v8.h:10656
static const int kIsolateIndex
Definition: v8.h:4412
#define V8_WARN_UNUSED_RESULT
Definition: v8config.h:424
Local< String > GetConstructorName()
#define V8_INTRINSICS_LIST(F)
Definition: v8.h:5950
static const int kEmbedderFieldCount
Definition: v8.h:5242
virtual void RegisterV8References(const std::vector< std::pair< void *, void *> > &embedder_fields)=0
V8_INLINE TracedReference(const TracedReference< S > &other)
Definition: v8.h:1113
static V8_INLINE internal::Address * GetRoot(v8::Isolate *isolate, int index)
Definition: v8-internal.h:283
MemorySpan< const uint8_t > MemorySpan< const uint8_t > wire_bytes
Definition: v8.h:4795
V8_WARN_UNUSED_RESULT MaybeLocal< Value > Call(Local< Context > context, Local< Value > recv, int argc, Local< Value > argv[])
V8_INLINE void Reset()
Definition: v8.h:10697
size_t bytecode_and_metadata_size()
Definition: v8.h:7653
V8_WARN_UNUSED_RESULT std::pair< uint8_t *, size_t > Release()
GenericNamedPropertyDeleterCallback deleter
Definition: v8.h:6612
void SetWasmThreadsEnabledCallback(WasmThreadsEnabledCallback callback)
bool IsMap() const
IndexedPropertyDescriptorCallback descriptor
Definition: v8.h:6685
V8_INLINE Local< Value > Get() const
Definition: v8.h:11053
void AddBeforeCallEnteredCallback(BeforeCallEnteredCallback callback)
constexpr size_t size() const
Definition: v8.h:4729
V8_INLINE void * GetData(uint32_t slot)
Definition: v8.h:11831
static const int kFullStringRepresentationMask
Definition: v8-internal.h:150
static std::unique_ptr< MeasureMemoryDelegate > Default(Isolate *isolate, Local< Context > context, Local< Promise::Resolver > promise_resolver, MeasureMemoryMode mode)
void * operator new[](size_t size)=delete
void *(* CreateHistogramCallback)(const char *name, int min, int max, size_t buckets)
Definition: v8.h:7162
ValueDeserializer(const ValueDeserializer &)=delete
static void SetSnapshotDataBlob(StartupData *startup_blob)
void RemoveGCPrologueCallback(GCCallbackWithData, void *data=nullptr)
void WriteDouble(double value)
uintptr_t JSStackComparableAddress() const
Definition: v8.h:10383
#define V8_DEPRECATE_SOON(message)
Definition: v8config.h:404
static Local< Uint16Array > New(Local< ArrayBuffer > array_buffer, size_t byte_offset, size_t length)
static Local< Symbol > ForApi(Isolate *isolate, Local< String > description)
const uint8_t * data
Definition: v8.h:1665
V8_WARN_UNUSED_RESULT Maybe< bool > Resolve(Local< Context > context, Local< Value > value)
Definition: v8.h:2202
const char ** dependencies() const
Definition: v8.h:6951
void(* GenericNamedPropertyDefinerCallback)(Local< Name > property, const PropertyDescriptor &desc, const PropertyCallbackInfo< Value > &info)
Definition: v8.h:6205
Local< Value > GetBoundFunction() const
static Local< Uint8Array > New(Local< SharedArrayBuffer > shared_array_buffer, size_t byte_offset, size_t length)
static V8_INLINE Signature * Cast(Data *data)
Definition: v8.h:11229
ExternalStringResourceBase(const ExternalStringResourceBase &)=delete
V8_WARN_UNUSED_RESULT bool ReadRawBytes(size_t length, const void **data)
void set_max_semi_space_size_in_kb(size_t limit_in_kb)
static V8_WARN_UNUSED_RESULT MaybeLocal< Script > Compile(Local< Context > context, Source *source, CompileOptions options=kNoCompileOptions, NoCacheReason no_cache_reason=kNoCacheNoReason)
static MaybeLocal< ObjectTemplate > FromSnapshot(Isolate *isolate, size_t index)
~Isolate()=delete
Local< Value > GetInferredName() const
void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback)
ValueSerializer(Isolate *isolate)
bool IsAsyncFunction() const
bool IsWasm() const
virtual ~ExternalStringResourceBase()=default
Definition: v8.h:5739
static void * JSStackComparableAddress(TryCatch *handler)
Definition: v8.h:10076
uint64_t Uint64Value(bool *lossless=nullptr) const
GenericNamedPropertySetterCallback setter
Definition: v8.h:6610
V8_WARN_UNUSED_RESULT MaybeLocal< Number > ToNumber(Local< Context > context) const
void set_auto_enable(bool value)
Definition: v8.h:6952
Flags GetFlags() const
virtual void VisitPersistentHandle(Persistent< Value > *value, uint16_t class_id)
Definition: v8.h:7816
MemorySpan< const uint8_t > GetWireBytesRef()
Global(const Global &)=delete
static const int kThisIndex
Definition: v8.h:4416
SealHandleScope(Isolate *isolate)
V8_WARN_UNUSED_RESULT Maybe< bool > HasRealNamedProperty(Local< Context > context, Local< Name > key)
bool IsTrue() const
void SetAbortOnUncaughtExceptionCallback(AbortOnUncaughtExceptionCallback callback)
virtual void * ReallocateBufferMemory(void *old_buffer, size_t size, size_t *actual_size)
void SetMicrotasksPolicy(MicrotasksPolicy policy)
size_t total_available_size()
Definition: v8.h:7578
static const int kUndefinedOddballKind
Definition: v8-internal.h:194
bool IsTypedArray() const
SafeForTerminationScope & operator=(const SafeForTerminationScope &)=delete
static V8_INLINE Private * Cast(Data *data)
Definition: v8.h:11446
static V8_INLINE Local< T > New(Isolate *isolate, Local< T > that)
Definition: v8.h:10608
static CachedData * CreateCodeCache(Local< UnboundScript > unbound_script)
virtual void EnterFinalPause(EmbedderStackState stack_state)=0
V8_WARN_UNUSED_RESULT Maybe< bool > Has(Local< Context > context, uint32_t index)
bool(* AllowWasmCodeGenerationCallback)(Local< Context > context, Local< String > source)
Definition: v8.h:7470
DeserializeInternalFieldsCallback(CallbackFunction function=nullptr, void *data_arg=nullptr)
Definition: v8.h:8047
const int kApiTaggedSize
Definition: v8-internal.h:106
void SetPrivate(Local< Private > name, Local< Data > value, PropertyAttribute attributes=None)
void RemoveGCEpilogueCallback(GCCallbackWithData callback, void *data=nullptr)
void * pc
Definition: v8.h:2209
bool ValueOf() const
size_t AddData(Local< T > object)
Definition: v8.h:11946
WasmStreaming(std::unique_ptr< WasmStreamingImpl > impl)
Local< String > GetModuleRequest(int i) const
Local< Value > GetDebugName() const
V8_INLINE Persistent(Isolate *isolate, Local< S > that)
Definition: v8.h:666
TracedGlobal< T > & operator=(TracedGlobal< S > &&rhs)
Definition: v8.h:10828
WeakCallbackInfo(Isolate *isolate, T *parameter, void *embedder_fields[kEmbedderFieldsInWeakCallback], Callback *callback)
Definition: v8.h:429
size_t AddTemplate(Local< Template > template_obj)
void Copy(const Persistent< S, M2 > &that)
Definition: v8.h:10678
static V8_INLINE FunctionTemplate * Cast(Data *data)
Definition: v8.h:11215
ArrayBufferCreationMode
Definition: v8.h:4943
void(* IndexedPropertyDefinerCallback)(uint32_t index, const PropertyDescriptor &desc, const PropertyCallbackInfo< Value > &info)
Definition: v8.h:6272
void Reset(Isolate *isolate, const Local< S > &other)
Definition: v8.h:10706
V8_INLINE bool IsConstructCall() const
Definition: v8.h:11123
#define TYPE_CHECK(T, S)
Definition: v8.h:152
bool IsInt16Array() const
int *(* CounterLookupCallback)(const char *name)
Definition: v8.h:7160
void(* AccessorNameGetterCallback)(Local< Name > property, const PropertyCallbackInfo< Value > &info)
Definition: v8.h:3574
static const int kStringEncodingMask
Definition: v8-internal.h:151
Definition: v8.h:3473
V8_INLINE void SetEmptyString()
Definition: v8.h:11040
V8_WARN_UNUSED_RESULT Maybe< bool > Set(Local< Context > context, Local< Value > key, Local< Value > value)
static const int kHolderIndex
Definition: v8.h:4411
V8_WARN_UNUSED_RESULT Maybe< int32_t > Int32Value(Local< Context > context) const
void Inherit(Local< FunctionTemplate > parent)
GCCallbackFlags
Definition: v8.h:7519
void * data
Definition: v8.h:5131
bool IsHeapLimitIncreasedForDebugging()
AllowJavascriptExecutionScope(const AllowJavascriptExecutionScope &)=delete
static V8_INLINE RegExp * Cast(Value *obj)
Definition: v8.h:11538
static V8_INLINE Uint16Array * Cast(Value *obj)
Definition: v8.h:11648
std::unique_ptr< const uint8_t[]> buffer
Definition: v8.h:4740
void SetHostImportModuleDynamicallyCallback(HostImportModuleDynamicallyCallback callback)
static V8_WARN_UNUSED_RESULT MaybeLocal< Script > Compile(Local< Context > context, Local< String > source, ScriptOrigin *origin=nullptr)
CompiledWasmModule GetCompiledModule()
V8_INLINE HandleScope()=default
size_t object_count()
Definition: v8.h:7637
void SetSupportsLegacyWireFormat(bool supports_legacy_wire_format)
V8_INLINE int64_t AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes)
Definition: v8.h:11849
void Abort(MaybeLocal< Value > exception)
V8_WARN_UNUSED_RESULT MaybeLocal< Set > Add(Local< Context > context, Local< Value > key)
Local< UnboundScript > script
Definition: v8.h:7701
virtual Maybe< uint32_t > GetWasmModuleTransferId(Isolate *isolate, Local< WasmModuleObject > module)
SnapshotCreator(const SnapshotCreator &)=delete
size_t initial_young_generation_size_in_bytes() const
Definition: v8.h:7072
V8_INLINE void Clear()
Definition: v8.h:211
StreamedSource(std::unique_ptr< ExternalSourceStream > source_stream, Encoding encoding)
PropertyHandlerFlags flags
Definition: v8.h:6687
GenericNamedPropertyQueryCallback query
Definition: v8.h:6611
static Local< Object > New(Isolate *isolate)
void(* GCCallbackWithData)(Isolate *isolate, GCType type, GCCallbackFlags flags, void *data)
Definition: v8.h:8755
static V8_WARN_UNUSED_RESULT MaybeLocal< Resolver > New(Local< Context > context)
void(* IndexedPropertySetterCallback)(uint32_t index, Local< Value > value, const PropertyCallbackInfo< Value > &info)
Definition: v8.h:6241
V8_INLINE Persistent(const Persistent &that)
Definition: v8.h:686
V8_INLINE Persistent< S > & As() const
Definition: v8.h:724
V8_INLINE Source(Local< String > source_string, const ScriptOrigin &origin, CachedData *cached_data=nullptr)
Definition: v8.h:11175
static void GetSharedMemoryStatistics(SharedMemoryStatistics *statistics)
constexpr T * data() const
Definition: v8.h:4727
void set_max_old_generation_size_in_bytes(size_t limit)
Definition: v8.h:7049
static const int kExternalTwoByteRepresentationTag
Definition: v8-internal.h:152
size_t max_young_generation_size_in_bytes() const
Definition: v8.h:7058
StreamedSource & operator=(const StreamedSource &)=delete
static const int kTrueValueRootIndex
Definition: v8-internal.h:177
const char ** end() const
Definition: v8.h:10122
static std::unique_ptr< BackingStore > NewBackingStore(void *data, size_t byte_length, BackingStoreDeleterCallback deleter, void *deleter_data)
void OnBytesReceived(const uint8_t *bytes, size_t size)
static uint32_t CachedDataVersionTag()
V8_WARN_UNUSED_RESULT Maybe< bool > HasOwnProperty(Local< Context > context, Local< Name > key)
static void InitializeExternalStartupDataFromFile(const char *snapshot_blob)
static Local< Uint8ClampedArray > New(Local< ArrayBuffer > array_buffer, size_t byte_offset, size_t length)
V8_INLINE void SetWeak()
Definition: v8.h:10736
static const int kJSSpecialApiObjectType
Definition: v8-internal.h:190
bool IsSharedCrossOrigin() const
StartupData CreateBlob(FunctionCodeHandling function_code_handling)
NewStringType
Definition: v8.h:2966
static V8_INLINE Uint8Array * Cast(Value *obj)
Definition: v8.h:11632
void DateTimeConfigurationChangeNotification(TimeZoneDetection time_zone_detection=TimeZoneDetection::kSkip)
Local< Context > GetEnteredContext()
V8_WARN_UNUSED_RESULT MaybeLocal< Value > Run(Local< Context > context)
void SetAccessCheckCallbackAndHandler(AccessCheckCallback callback, const NamedPropertyHandlerConfiguration &named_handler, const IndexedPropertyHandlerConfiguration &indexed_handler, Local< Value > data=Local< Value >())
NamedPropertyHandlerConfiguration(GenericNamedPropertyGetterCallback getter, GenericNamedPropertySetterCallback setter, GenericNamedPropertyDescriptorCallback descriptor, GenericNamedPropertyDeleterCallback deleter, GenericNamedPropertyEnumeratorCallback enumerator, GenericNamedPropertyDefinerCallback definer, Local< Value > data=Local< Value >(), PropertyHandlerFlags flags=PropertyHandlerFlags::kNone)
Definition: v8.h:6590
CounterLookupCallback counter_lookup_callback
Definition: v8.h:8163
size_t Size() const
bool IsRevoked()
TimeZoneDetection
Definition: v8.h:9404
void SetCaptureStackTraceForUncaughtExceptions(bool capture, int frame_limit=10, StackTrace::StackTraceOptions options=StackTrace::kOverview)
Scope(Isolate *isolate)
Definition: v8.h:8213
V8_WARN_UNUSED_RESULT Maybe< PropertyAttribute > GetRealNamedPropertyAttributes(Local< Context > context, Local< Name > key)
internal::Address * values_
Definition: v8.h:4306
V8_INLINE void Set(double i)
Definition: v8.h:10984
bool IsArray() const
size_t total_heap_size()
Definition: v8.h:7575
V8_WARN_UNUSED_RESULT MaybeLocal< Value > CallAsConstructor(Local< Context > context, int argc, Local< Value > argv[])
static Isolate * New(const CreateParams &params)
static V8_INLINE TypedArray * Cast(Value *obj)
Definition: v8.h:11624
void(* DcheckErrorCallback)(const char *file, int line, const char *message)
Definition: v8.h:7122
bool IsSet() const
virtual void ThrowDataCloneError(Local< String > message)=0
CachedData(const CachedData &)=delete
Local< String > TypeOf(Isolate *)
uint32_t * stack_limit() const
Definition: v8.h:7029
static constexpr int kMaxLength
Definition: v8.h:2985
size_t max_semi_space_size_in_kb() const
V8_WARN_UNUSED_RESULT MaybeLocal< Promise > Catch(Local< Context > context, Local< Function > handler)
Definition: v8.h:2241
V8_INLINE bool operator!=(const PersistentBase< S > &that) const
Definition: v8.h:525
Local< Context > CreationContext()
void(* CallbackFunction)(Local< Object > holder, int index, StartupData payload, void *data)
Definition: v8.h:8045
static const int kNoScriptId
Definition: v8.h:1447
static V8_WARN_UNUSED_RESULT MaybeLocal< String > NewFromTwoByte(Isolate *isolate, const uint16_t *data, NewStringType type=NewStringType::kNormal, int length=-1)
bool CanContinue() const
void SetIdle(bool is_idle)
static Local< FunctionTemplate > NewWithCache(Isolate *isolate, FunctionCallback callback, Local< Private > cache_property, Local< Value > data=Local< Value >(), Local< Signature > signature=Local< Signature >(), int length=0, SideEffectType side_effect_type=SideEffectType::kHasSideEffect)
size_t ByteLength() const
bool IsInt8Array() const
void VisitWeakHandles(PersistentHandleVisitor *visitor)
V8_INLINE Local< S > FromMaybe(Local< S > default_value) const
Definition: v8.h:392
static Local< Value > TypeError(Local< String > message)
size_t object_size()
Definition: v8.h:7638
void(* FailedAccessCheckCallback)(Local< Object > target, AccessType type, Local< Value > data)
Definition: v8.h:7437
CodeType code_type
Definition: v8.h:7695
void IncreaseAllocatedSize(size_t bytes)
void * DeleterData() const
Definition: v8.h:5571
static V8_INLINE int InternalFieldCount(const PersistentBase< Object > &object)
Definition: v8.h:3891
static Local< Value > ReferenceError(Local< String > message)
void operator=(const Value &)=delete
virtual ~EmbedderHeapTracer()=default
Isolate * GetIsolate()
int ContextDisposedNotification(bool dependant_context=true)
const SharedArrayBuffer::Contents ArrayBufferCreationMode mode
Definition: v8.h:5663
static const int kReturnValueIndex
Definition: v8.h:4299
void * code_start
Definition: v8.h:7697
void RequestGarbageCollectionForTesting(GarbageCollectionType type)
V8_WARN_UNUSED_RESULT Maybe< bool > Delete(Local< Context > context, Local< Value > key)
void SetModifyCodeGenerationFromStringsCallback(ModifyCodeGenerationFromStringsCallback callback)
V8_WARN_UNUSED_RESULT MaybeLocal< Value > GetRealNamedProperty(Local< Context > context, Local< Name > key)
bool GetHeapObjectStatisticsAtLastGC(HeapObjectStatistics *object_statistics, size_t type_index)
V8_WARN_UNUSED_RESULT Maybe< int > GetStartColumn(Local< Context > context) const
void operator=(const Utf8Value &)=delete
void * external_callback_entry
Definition: v8.h:2219
static const int kNoWasmFunctionIndexInfo
Definition: v8.h:2067
void SetAllowAtomicsWait(bool allow)
static const int kNullOddballKind
Definition: v8-internal.h:195
Local< PrimitiveArray > GetHostDefinedOptions()
static int GetCurrentDepth(Isolate *isolate)
const char * str
Definition: v8.h:7711
virtual ~Delegate()=default
static Local< Value > Error(Local< String > message)
void * Data() const
Definition: v8.h:5568
static const int kEmbedderFieldCount
Definition: v8.h:4603
V8_WARN_UNUSED_RESULT MaybeLocal< Object > NewInstance(Local< Context > context) const
Definition: v8.h:4445
V8_WARN_UNUSED_RESULT Maybe< int64_t > IntegerValue(Local< Context > context) const
bool only_terminate_in_safe_scope
Definition: v8.h:8203
virtual Maybe< bool > WriteHostObject(Isolate *isolate, Local< Object > object)
V8_INLINE Locker(Isolate *isolate)
Definition: v8.h:10503
bool IsExternal() const
static std::unique_ptr< MicrotaskQueue > New(Isolate *isolate, MicrotasksPolicy policy=MicrotasksPolicy::kAuto)
void SetFatalErrorHandler(FatalErrorCallback that)
Local< Value > GetScriptName()
#define V8_INLINE
Definition: v8config.h:359
static V8_INLINE Local< String > Empty(Isolate *isolate)
Definition: v8.h:11297
static bool TryUnwindV8Frames(const JSEntryStubs &entry_stubs, size_t code_pages_length, const MemoryRange *code_pages, RegisterState *register_state, const void *stack_base)
virtual void VisitTracedReference(const TracedReference< Value > &handle)
Definition: v8.h:7858
int GetScriptColumnNumber() const
V8_WARN_UNUSED_RESULT MaybeLocal< Object > NewInstance(Local< Context > context, int argc, Local< Value > argv[]) const
void(* MicrotaskCallback)(void *data)
Definition: v8.h:7298
WeakCallbackType
Definition: v8.h:463
V8_INLINE Scope(Local< Context > context)
Definition: v8.h:10355
void(* GenericNamedPropertySetterCallback)(Local< Name > property, Local< Value > value, const PropertyCallbackInfo< Value > &info)
Definition: v8.h:6124
static CachedData * CreateCodeCache(Local< UnboundModuleScript > unbound_module_script)
PromiseRejectMessage(Local< Promise > promise, PromiseRejectEvent event, Local< Value > value)
Definition: v8.h:7278
static V8_INLINE Int16Array * Cast(Value *obj)
Definition: v8.h:11656
HeapProfiler * GetHeapProfiler()
IndexedPropertyHandlerConfiguration(IndexedPropertyGetterCallback getter, IndexedPropertySetterCallback setter, IndexedPropertyQueryCallback query, IndexedPropertyDeleterCallback deleter, IndexedPropertyEnumeratorCallback enumerator, IndexedPropertyDefinerCallback definer, IndexedPropertyDescriptorCallback descriptor, Local< Value > data=Local< Value >(), PropertyHandlerFlags flags=PropertyHandlerFlags::kNone)
Definition: v8.h:6622
static V8_WARN_UNUSED_RESULT MaybeLocal< String > NewExternalOneByte(Isolate *isolate, ExternalOneByteStringResource *resource)
V8_INLINE TracedReference(TracedReference &&other)
Definition: v8.h:1084
void(* OOMErrorCallback)(const char *location, bool is_heap_oom)
Definition: v8.h:7120
AccessControl
Definition: v8.h:3598
V8_INLINE Local< Value > NewTarget() const
Definition: v8.h:11099
PropertyAttribute
Definition: v8.h:3555
JSEntryStub js_run_microtasks_entry_stub
Definition: v8.h:2238
#define V8_LIKELY(condition)
Definition: v8config.h:414
HandleScope(const HandleScope &)=delete
bool IsBigUint64Array() const
bool IsUserJavaScript() const
V8_WARN_UNUSED_RESULT MaybeLocal< Object > ToObject(Local< Context > context) const
wasm_source_info_t * wasm_source_info
Definition: v8.h:7737
void size_t ArrayBufferCreationMode mode
Definition: v8.h:5614
size_t read_only_space_used_size()
Definition: v8.h:7553
void operator=(const HandleScope &)=delete
bool HasHandler()
MicrotasksPolicy GetMicrotasksPolicy() const
void operator delete[](void *, size_t)=delete
V8_INLINE void Reset()
Definition: v8.h:10810
PromiseState State()
static const int kDataIndex
Definition: v8.h:4415
ValueDeserializer(Isolate *isolate, const uint8_t *data, size_t size)
Maybe< bool > DeletePrivate(Local< Context > context, Local< Private > key)
bool IsSymbol() const
static const int kExternalOneByteRepresentationTag
Definition: v8-internal.h:153
size_t code_len
Definition: v8.h:7699
void Reset(Isolate *isolate, const Local< S > &other)
Definition: v8.h:10867
static V8_WARN_UNUSED_RESULT MaybeLocal< Value > Parse(Local< Context > context, Local< String > json_string)
V8_INLINE Global(Isolate *isolate, Local< S > that)
Definition: v8.h:761
V8_WARN_UNUSED_RESULT MaybeLocal< Promise > Then(Local< Context > context, Local< Function > handler)
size_t total_heap_size_executable()
Definition: v8.h:7576
static const char * GetVersion()
Local< Value > Exception() const
static Local< BigUint64Array > New(Local< ArrayBuffer > array_buffer, size_t byte_offset, size_t length)
V8_INLINE Local< Promise > GetPromise() const
Definition: v8.h:7282
V8_INLINE bool operator!=(const TracedReferenceBase< S > &that) const
Definition: v8.h:874
V8_INLINE T * operator->() const
Definition: v8.h:213
GenericNamedPropertyGetterCallback getter
Definition: v8.h:6609
int GetScriptId() const
V8_INLINE MaybeLocal(Local< S > that)
Definition: v8.h:364
void SetAccessor(Local< Name > name, AccessorNameGetterCallback getter, AccessorNameSetterCallback setter=nullptr, Local< Value > data=Local< Value >(), AccessControl settings=DEFAULT, PropertyAttribute attribute=None, Local< AccessorSignature > signature=Local< AccessorSignature >(), SideEffectType getter_side_effect_type=SideEffectType::kHasSideEffect, SideEffectType setter_side_effect_type=SideEffectType::kHasSideEffect)
virtual void RemoveMicrotasksCompletedCallback(MicrotasksCompletedCallbackWithData callback, void *data=nullptr)=0
std::shared_ptr< ArrayBuffer::Allocator > array_buffer_allocator_shared
Definition: v8.h:8184
void(* AccessorSetterCallback)(Local< String > property, Local< Value > value, const PropertyCallbackInfo< void > &info)
Definition: v8.h:3579
void SetDefaultContext(Local< Context > context, SerializeInternalFieldsCallback callback=SerializeInternalFieldsCallback())
static const int kExternalMemoryOffset
Definition: v8-internal.h:159
static const int kNodeClassIdOffset
Definition: v8-internal.h:181
Isolate * GetIsolate()
void SetAlignedPointerInInternalFields(int argc, int indices[], void *values[])
int GetIdentityHash()
void SetUrl(const char *url, size_t length)
void operator=(const Global &)=delete
static V8_INLINE Local< T > New(Isolate *isolate, const PersistentBase< T > &that)
Definition: v8.h:10613
V8_INLINE Local< Value > Data() const
Definition: v8.h:11105
std::shared_ptr< BackingStore > GetBackingStore()
V8_WARN_UNUSED_RESULT Maybe< bool > HasOwnProperty(Local< Context > context, uint32_t index)
static V8_INLINE Local< Boolean > New(Isolate *isolate, bool value)
Definition: v8.h:11205
static V8_INLINE BigInt * Cast(v8::Value *obj)
Definition: v8.h:11485
static Local< Int16Array > New(Local< SharedArrayBuffer > shared_array_buffer, size_t byte_offset, size_t length)
static bool InitializeICU(const char *icu_data_file=nullptr)
SuppressMicrotaskExecutionScope(const SuppressMicrotaskExecutionScope &)=delete
Isolate * isolate
Definition: v8.h:7750
static const int kJSObjectType
Definition: v8-internal.h:192
V8_INLINE TracedReference & operator=(TracedReference &&rhs)
Definition: v8.h:10893
void SetCallHandler(FunctionCallback callback, Local< Value > data=Local< Value >(), SideEffectType side_effect_type=SideEffectType::kHasSideEffect)
void(* HostCleanupFinalizationGroupCallback)(Local< Context > context, Local< FinalizationGroup > fg)
Definition: v8.h:7195
JitCodeEventOptions
Definition: v8.h:7778
static V8_INLINE Persistent< T > & Cast(const Persistent< S > &that)
Definition: v8.h:713
void Set(const Global< S > &handle)
Definition: v8.h:10952
Local< Object > GetExtrasBindingObject()
Utf8Value(Isolate *isolate, Local< v8::Value > obj)
MicrotasksScope & operator=(const MicrotasksScope &)=delete
virtual MaybeLocal< Object > ReadHostObject(Isolate *isolate)
static Local< Symbol > GetToStringTag(Isolate *isolate)
bool IsSharedArrayBuffer() const
V8_WARN_UNUSED_RESULT MaybeLocal< Array > GetOwnPropertyNames(Local< Context > context, PropertyFilter filter, KeyConversionMode key_conversion=KeyConversionMode::kKeepNumbers)
V8_INLINE Local< Integer > ResourceLineOffset() const
Definition: v8.h:11160
void(* HostInitializeImportMetaObjectCallback)(Local< Context > context, Local< Module > module, Local< Object > meta)
Definition: v8.h:7232
void AddMicrotasksCompletedCallback(MicrotasksCompletedCallbackWithData callback, void *data=nullptr)
V8_INLINE void SetWrapperClassId(uint16_t class_id)
Definition: v8.h:10916
friend class TracedReferenceBase
Definition: v8.h:9708
friend class Eternal
Definition: v8.h:9715
virtual bool IsCacheable() const
Definition: v8.h:3090
bool IsFunction() const
V8_INLINE TracedReference(TracedReference< S > &&other)
Definition: v8.h:1094
V8_WARN_UNUSED_RESULT Maybe< bool > Has(Local< Context > context, Local< Value > key)
PropertyFilter
Definition: v8.h:3608
size_t CopyCodePages(size_t capacity, MemoryRange *code_pages_out)
V8_INLINE const ScriptOriginOptions & GetResourceOptions() const
Definition: v8.h:11201
V8_INLINE TracedGlobal(const TracedGlobal< S > &other)
Definition: v8.h:986
static V8_WARN_UNUSED_RESULT MaybeLocal< Script > Compile(Local< Context > context, StreamedSource *source, Local< String > full_source_string, const ScriptOrigin &origin)
PositionType position_type
Definition: v8.h:7722
V8_INLINE Local< Value > operator[](int i) const
Definition: v8.h:11080
Local< Value > Description() const