v8  6.2.414 (node 8.16.2)
V8 is Google's open source JavaScript engine
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
v8.h
Go to the documentation of this file.
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 /** \mainpage V8 API Reference Guide
6  *
7  * V8 is Google's open source JavaScript engine.
8  *
9  * This set of documents provides reference material generated from the
10  * V8 header file, include/v8.h.
11  *
12  * For other documentation see http://code.google.com/apis/v8/
13  */
14 
15 #ifndef INCLUDE_V8_H_
16 #define INCLUDE_V8_H_
17 
18 #include <stddef.h>
19 #include <stdint.h>
20 #include <stdio.h>
21 #include <memory>
22 #include <utility>
23 #include <vector>
24 
25 #include "v8-version.h" // NOLINT(build/include)
26 #include "v8config.h" // NOLINT(build/include)
27 
28 // We reserve the V8_* prefix for macros defined in V8 public API and
29 // assume there are no name conflicts with the embedder's code.
30 
31 #ifdef V8_OS_WIN
32 
33 // Setup for Windows DLL export/import. When building the V8 DLL the
34 // BUILDING_V8_SHARED needs to be defined. When building a program which uses
35 // the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8
36 // static library or building a program which uses the V8 static library neither
37 // BUILDING_V8_SHARED nor USING_V8_SHARED should be defined.
38 #ifdef BUILDING_V8_SHARED
39 # define V8_EXPORT __declspec(dllexport)
40 #elif USING_V8_SHARED
41 # define V8_EXPORT __declspec(dllimport)
42 #else
43 # define V8_EXPORT
44 #endif // BUILDING_V8_SHARED
45 
46 #else // V8_OS_WIN
47 
48 // Setup for Linux shared library export.
49 #if V8_HAS_ATTRIBUTE_VISIBILITY
50 # ifdef BUILDING_V8_SHARED
51 # define V8_EXPORT __attribute__ ((visibility("default")))
52 # else
53 # define V8_EXPORT
54 # endif
55 #else
56 # define V8_EXPORT
57 #endif
58 
59 #endif // V8_OS_WIN
60 
61 /**
62  * The v8 JavaScript engine.
63  */
64 namespace v8 {
65 
66 class AccessorSignature;
67 class Array;
68 class ArrayBuffer;
69 class Boolean;
70 class BooleanObject;
71 class Context;
72 class CpuProfiler;
73 class Data;
74 class Date;
75 class External;
76 class Function;
77 class FunctionTemplate;
78 class HeapProfiler;
79 class ImplementationUtilities;
80 class Int32;
81 class Integer;
82 class Isolate;
83 template <class T>
84 class Maybe;
85 class Name;
86 class Number;
87 class NumberObject;
88 class Object;
89 class ObjectOperationDescriptor;
90 class ObjectTemplate;
91 class Platform;
92 class Primitive;
93 class Promise;
94 class PropertyDescriptor;
95 class Proxy;
96 class RawOperationDescriptor;
97 class Script;
98 class SharedArrayBuffer;
99 class Signature;
100 class StartupData;
101 class StackFrame;
102 class StackTrace;
103 class String;
104 class StringObject;
105 class Symbol;
106 class SymbolObject;
107 class Private;
108 class Uint32;
109 class Utils;
110 class Value;
111 class WasmCompiledModule;
112 template <class T> class Local;
113 template <class T>
114 class MaybeLocal;
115 template <class T> class Eternal;
116 template<class T> class NonCopyablePersistentTraits;
117 template<class T> class PersistentBase;
118 template <class T, class M = NonCopyablePersistentTraits<T> >
119 class Persistent;
120 template <class T>
121 class Global;
122 template<class K, class V, class T> class PersistentValueMap;
123 template <class K, class V, class T>
125 template <class K, class V, class T>
126 class GlobalValueMap;
127 template<class V, class T> class PersistentValueVector;
128 template<class T, class P> class WeakCallbackObject;
129 class FunctionTemplate;
130 class ObjectTemplate;
131 template<typename T> class FunctionCallbackInfo;
132 template<typename T> class PropertyCallbackInfo;
133 class StackTrace;
134 class StackFrame;
135 class Isolate;
136 class CallHandlerHelper;
138 template<typename T> class ReturnValue;
139 
140 namespace internal {
141 class Arguments;
142 class DeferredHandles;
143 class Heap;
144 class HeapObject;
145 class Isolate;
146 class Object;
147 struct StreamedSource;
148 template<typename T> class CustomArguments;
149 class PropertyCallbackArguments;
150 class FunctionCallbackArguments;
151 class GlobalHandles;
152 } // namespace internal
153 
154 namespace debug {
155 class ConsoleCallArguments;
156 } // namespace debug
157 
158 // --- Handles ---
159 
160 #define TYPE_CHECK(T, S)
161  while (false) {
162  *(static_cast<T* volatile*>(0)) = static_cast<S*>(0);
163  }
164 
165 /**
166  * An object reference managed by the v8 garbage collector.
167  *
168  * All objects returned from v8 have to be tracked by the garbage
169  * collector so that it knows that the objects are still alive. Also,
170  * because the garbage collector may move objects, it is unsafe to
171  * point directly to an object. Instead, all objects are stored in
172  * handles which are known by the garbage collector and updated
173  * whenever an object moves. Handles should always be passed by value
174  * (except in cases like out-parameters) and they should never be
175  * allocated on the heap.
176  *
177  * There are two types of handles: local and persistent handles.
178  *
179  * Local handles are light-weight and transient and typically used in
180  * local operations. They are managed by HandleScopes. That means that a
181  * HandleScope must exist on the stack when they are created and that they are
182  * only valid inside of the HandleScope active during their creation.
183  * For passing a local handle to an outer HandleScope, an EscapableHandleScope
184  * and its Escape() method must be used.
185  *
186  * Persistent handles can be used when storing objects across several
187  * independent operations and have to be explicitly deallocated when they're no
188  * longer used.
189  *
190  * It is safe to extract the object stored in the handle by
191  * dereferencing the handle (for instance, to extract the Object* from
192  * a Local<Object>); the value will still be governed by a handle
193  * behind the scenes and the same rules apply to these values as to
194  * their handles.
195  */
196 template <class T>
197 class Local {
198  public:
199  V8_INLINE Local() : val_(0) {}
200  template <class S>
202  : val_(reinterpret_cast<T*>(*that)) {
203  /**
204  * This check fails when trying to convert between incompatible
205  * handles. For example, converting from a Local<String> to a
206  * Local<Number>.
207  */
208  TYPE_CHECK(T, S);
209  }
210 
211  /**
212  * Returns true if the handle is empty.
213  */
214  V8_INLINE bool IsEmpty() const { return val_ == 0; }
215 
216  /**
217  * Sets the handle to be empty. IsEmpty() will then return true.
218  */
219  V8_INLINE void Clear() { val_ = 0; }
220 
221  V8_INLINE T* operator->() const { return val_; }
222 
223  V8_INLINE T* operator*() const { return val_; }
224 
225  /**
226  * Checks whether two handles are the same.
227  * Returns true if both are empty, or if the objects
228  * to which they refer are identical.
229  * The handles' references are not checked.
230  */
231  template <class S>
232  V8_INLINE bool operator==(const Local<S>& that) const {
233  internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
234  internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
235  if (a == 0) return b == 0;
236  if (b == 0) return false;
237  return *a == *b;
238  }
239 
240  template <class S> V8_INLINE bool operator==(
241  const PersistentBase<S>& that) const {
242  internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
243  internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
244  if (a == 0) return b == 0;
245  if (b == 0) return false;
246  return *a == *b;
247  }
248 
249  /**
250  * Checks whether two handles are different.
251  * Returns true if only one of the handles is empty, or if
252  * the objects to which they refer are different.
253  * The handles' references are not checked.
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 
298  private:
299  friend class Utils;
300  template<class F> friend class Eternal;
301  template<class F> friend class PersistentBase;
302  template<class F, class M> friend class Persistent;
303  template<class F> friend class Local;
304  template <class F>
305  friend class MaybeLocal;
306  template<class F> friend class FunctionCallbackInfo;
307  template<class F> friend class PropertyCallbackInfo;
308  friend class String;
309  friend class Object;
310  friend class Context;
311  friend class Private;
312  template<class F> friend class internal::CustomArguments;
313  friend Local<Primitive> Undefined(Isolate* isolate);
314  friend Local<Primitive> Null(Isolate* isolate);
315  friend Local<Boolean> True(Isolate* isolate);
316  friend Local<Boolean> False(Isolate* isolate);
317  friend class HandleScope;
318  friend class EscapableHandleScope;
319  template <class F1, class F2, class F3>
321  template<class F1, class F2> friend class PersistentValueVector;
322  template <class F>
323  friend class ReturnValue;
324 
325  explicit V8_INLINE Local(T* that) : val_(that) {}
326  V8_INLINE static Local<T> New(Isolate* isolate, T* that);
327  T* val_;
328 };
329 
330 
331 #if !defined(V8_IMMINENT_DEPRECATION_WARNINGS)
332 // Handle is an alias for Local for historical reasons.
333 template <class T>
334 using Handle = Local<T>;
335 #endif
336 
337 
338 /**
339  * A MaybeLocal<> is a wrapper around Local<> that enforces a check whether
340  * the Local<> is empty before it can be used.
341  *
342  * If an API method returns a MaybeLocal<>, the API method can potentially fail
343  * either because an exception is thrown, or because an exception is pending,
344  * e.g. because a previous API call threw an exception that hasn't been caught
345  * yet, or because a TerminateExecution exception was thrown. In that case, an
346  * empty MaybeLocal is returned.
347  */
348 template <class T>
349 class MaybeLocal {
350  public:
351  V8_INLINE MaybeLocal() : val_(nullptr) {}
352  template <class S>
354  : val_(reinterpret_cast<T*>(*that)) {
355  TYPE_CHECK(T, S);
356  }
357 
358  V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
359 
360  /**
361  * Converts this MaybeLocal<> to a Local<>. If this MaybeLocal<> is empty,
362  * |false| is returned and |out| is left untouched.
363  */
364  template <class S>
366  out->val_ = IsEmpty() ? nullptr : this->val_;
367  return !IsEmpty();
368  }
369 
370  /**
371  * Converts this MaybeLocal<> to a Local<>. If this MaybeLocal<> is empty,
372  * V8 will crash the process.
373  */
375 
376  /**
377  * Converts this MaybeLocal<> to a Local<>, using a default value if this
378  * MaybeLocal<> is empty.
379  */
380  template <class S>
381  V8_INLINE Local<S> FromMaybe(Local<S> default_value) const {
382  return IsEmpty() ? default_value : Local<S>(val_);
383  }
384 
385  private:
386  T* val_;
387 };
388 
389 /**
390  * Eternal handles are set-once handles that live for the lifetime of the
391  * isolate.
392  */
393 template <class T> class Eternal {
394  public:
395  V8_INLINE Eternal() : val_(nullptr) {}
396  template <class S>
397  V8_INLINE Eternal(Isolate* isolate, Local<S> handle) : val_(nullptr) {
398  Set(isolate, handle);
399  }
400  // Can only be safely called if already set.
401  V8_INLINE Local<T> Get(Isolate* isolate) const;
402  V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
403  template<class S> V8_INLINE void Set(Isolate* isolate, Local<S> handle);
404 
405  private:
406  T* val_;
407 };
408 
409 
410 static const int kInternalFieldsInWeakCallback = 2;
411 static const int kEmbedderFieldsInWeakCallback = 2;
412 
413 template <typename T>
415  public:
416  typedef void (*Callback)(const WeakCallbackInfo<T>& data);
417 
418  WeakCallbackInfo(Isolate* isolate, T* parameter,
419  void* embedder_fields[kEmbedderFieldsInWeakCallback],
420  Callback* callback)
421  : isolate_(isolate), parameter_(parameter), callback_(callback) {
422  for (int i = 0; i < kEmbedderFieldsInWeakCallback; ++i) {
423  embedder_fields_[i] = embedder_fields[i];
424  }
425  }
426 
427  V8_INLINE Isolate* GetIsolate() const { return isolate_; }
428  V8_INLINE T* GetParameter() const { return parameter_; }
429  V8_INLINE void* GetInternalField(int index) const;
430 
431  V8_INLINE V8_DEPRECATED("use indexed version",
432  void* GetInternalField1() const) {
433  return embedder_fields_[0];
434  }
435  V8_INLINE V8_DEPRECATED("use indexed version",
436  void* GetInternalField2() const) {
437  return embedder_fields_[1];
438  }
439 
440  V8_DEPRECATED("Not realiable once SetSecondPassCallback() was used.",
441  bool IsFirstPass() const) {
442  return callback_ != nullptr;
443  }
444 
445  // When first called, the embedder MUST Reset() the Global which triggered the
446  // callback. The Global itself is unusable for anything else. No v8 other api
447  // calls may be called in the first callback. Should additional work be
448  // required, the embedder must set a second pass callback, which will be
449  // called after all the initial callbacks are processed.
450  // Calling SetSecondPassCallback on the second pass will immediately crash.
451  void SetSecondPassCallback(Callback callback) const { *callback_ = callback; }
452 
453  private:
454  Isolate* isolate_;
455  T* parameter_;
456  Callback* callback_;
457  void* embedder_fields_[kEmbedderFieldsInWeakCallback];
458 };
459 
460 
461 // kParameter will pass a void* parameter back to the callback, kInternalFields
462 // will pass the first two internal fields back to the callback, kFinalizer
463 // will pass a void* parameter back, but is invoked before the object is
464 // actually collected, so it can be resurrected. In the last case, it is not
465 // possible to request a second pass callback.
467 
468 /**
469  * An object reference that is independent of any handle scope. Where
470  * a Local handle only lives as long as the HandleScope in which it was
471  * allocated, a PersistentBase handle remains valid until it is explicitly
472  * disposed using Reset().
473  *
474  * A persistent handle contains a reference to a storage cell within
475  * the V8 engine which holds an object value and which is updated by
476  * the garbage collector whenever the object is moved. A new storage
477  * cell can be created using the constructor or PersistentBase::Reset and
478  * existing handles can be disposed using PersistentBase::Reset.
479  *
480  */
481 template <class T> class PersistentBase {
482  public:
483  /**
484  * If non-empty, destroy the underlying storage cell
485  * IsEmpty() will return true after this call.
486  */
487  V8_INLINE void Reset();
488  /**
489  * If non-empty, destroy the underlying storage cell
490  * and create a new one with the contents of other if other is non empty
491  */
492  template <class S>
493  V8_INLINE void Reset(Isolate* isolate, const Local<S>& other);
494 
495  /**
496  * If non-empty, destroy the underlying storage cell
497  * and create a new one with the contents of other if other is non empty
498  */
499  template <class S>
500  V8_INLINE void Reset(Isolate* isolate, const PersistentBase<S>& other);
501 
502  V8_INLINE bool IsEmpty() const { return val_ == NULL; }
503  V8_INLINE void Empty() { val_ = 0; }
504 
505  V8_INLINE Local<T> Get(Isolate* isolate) const {
506  return Local<T>::New(isolate, *this);
507  }
508 
509  template <class S>
510  V8_INLINE bool operator==(const PersistentBase<S>& that) const {
511  internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
512  internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
513  if (a == NULL) return b == NULL;
514  if (b == NULL) return false;
515  return *a == *b;
516  }
517 
518  template <class S>
519  V8_INLINE bool operator==(const Local<S>& that) const {
520  internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
521  internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
522  if (a == NULL) return b == NULL;
523  if (b == NULL) return false;
524  return *a == *b;
525  }
526 
527  template <class S>
528  V8_INLINE bool operator!=(const PersistentBase<S>& that) const {
529  return !operator==(that);
530  }
531 
532  template <class S>
533  V8_INLINE bool operator!=(const Local<S>& that) const {
534  return !operator==(that);
535  }
536 
537  /**
538  * Install a finalization callback on this object.
539  * NOTE: There is no guarantee as to *when* or even *if* the callback is
540  * invoked. The invocation is performed solely on a best effort basis.
541  * As always, GC-based finalization should *not* be relied upon for any
542  * critical form of resource management!
543  */
544  template <typename P>
545  V8_INLINE void SetWeak(P* parameter,
546  typename WeakCallbackInfo<P>::Callback callback,
547  WeakCallbackType type);
548 
549  /**
550  * Turns this handle into a weak phantom handle without finalization callback.
551  * The handle will be reset automatically when the garbage collector detects
552  * that the object is no longer reachable.
553  * A related function Isolate::NumberOfPhantomHandleResetsSinceLastCall
554  * returns how many phantom handles were reset by the garbage collector.
555  */
556  V8_INLINE void SetWeak();
557 
558  template<typename P>
560 
561  // TODO(dcarney): remove this.
562  V8_INLINE void ClearWeak() { ClearWeak<void>(); }
563 
564  /**
565  * Allows the embedder to tell the v8 garbage collector that a certain object
566  * is alive. Only allowed when the embedder is asked to trace its heap by
567  * EmbedderHeapTracer.
568  */
569  V8_INLINE void RegisterExternalReference(Isolate* isolate) const;
570 
571  /**
572  * Marks the reference to this object independent. Garbage collector is free
573  * to ignore any object groups containing this object. Weak callback for an
574  * independent handle should not assume that it will be preceded by a global
575  * GC prologue callback or followed by a global GC epilogue callback.
576  */
577  V8_INLINE void MarkIndependent();
578 
579  /**
580  * Marks the reference to this object as active. The scavenge garbage
581  * collection should not reclaim the objects marked as active.
582  * This bit is cleared after the each garbage collection pass.
583  */
584  V8_INLINE void MarkActive();
585 
586  V8_INLINE bool IsIndependent() const;
587 
588  /** Checks if the handle holds the only reference to an object. */
589  V8_INLINE bool IsNearDeath() const;
590 
591  /** Returns true if the handle's reference is weak. */
592  V8_INLINE bool IsWeak() const;
593 
594  /**
595  * Assigns a wrapper class ID to the handle. See RetainedObjectInfo interface
596  * description in v8-profiler.h for details.
597  */
598  V8_INLINE void SetWrapperClassId(uint16_t class_id);
599 
600  /**
601  * Returns the class ID previously assigned to this handle or 0 if no class ID
602  * was previously assigned.
603  */
604  V8_INLINE uint16_t WrapperClassId() const;
605 
606  PersistentBase(const PersistentBase& other) = delete; // NOLINT
607  void operator=(const PersistentBase&) = delete;
608 
609  private:
610  friend class Isolate;
611  friend class Utils;
612  template<class F> friend class Local;
613  template<class F1, class F2> friend class Persistent;
614  template <class F>
615  friend class Global;
616  template<class F> friend class PersistentBase;
617  template<class F> friend class ReturnValue;
618  template <class F1, class F2, class F3>
620  template<class F1, class F2> friend class PersistentValueVector;
621  friend class Object;
622 
623  explicit V8_INLINE PersistentBase(T* val) : val_(val) {}
624  V8_INLINE static T* New(Isolate* isolate, T* that);
625 
626  T* val_;
627 };
628 
629 
630 /**
631  * Default traits for Persistent. This class does not allow
632  * use of the copy constructor or assignment operator.
633  * At present kResetInDestructor is not set, but that will change in a future
634  * version.
635  */
636 template<class T>
637 class NonCopyablePersistentTraits {
638  public:
639  typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
640  static const bool kResetInDestructor = false;
641  template<class S, class M>
642  V8_INLINE static void Copy(const Persistent<S, M>& source,
643  NonCopyablePersistent* dest) {
644  Uncompilable<Object>();
645  }
646  // TODO(dcarney): come up with a good compile error here.
647  template<class O> V8_INLINE static void Uncompilable() {
648  TYPE_CHECK(O, Primitive);
649  }
650 };
651 
652 
653 /**
654  * Helper class traits to allow copying and assignment of Persistent.
655  * This will clone the contents of storage cell, but not any of the flags, etc.
656  */
657 template<class T>
660  static const bool kResetInDestructor = true;
661  template<class S, class M>
662  static V8_INLINE void Copy(const Persistent<S, M>& source,
663  CopyablePersistent* dest) {
664  // do nothing, just allow copy
665  }
666 };
667 
668 
669 /**
670  * A PersistentBase which allows copy and assignment.
671  *
672  * Copy, assignment and destructor behavior is controlled by the traits
673  * class M.
674  *
675  * Note: Persistent class hierarchy is subject to future changes.
676  */
677 template <class T, class M> class Persistent : public PersistentBase<T> {
678  public:
679  /**
680  * A Persistent with no storage cell.
681  */
683  /**
684  * Construct a Persistent from a Local.
685  * When the Local is non-empty, a new storage cell is created
686  * pointing to the same object, and no flags are set.
687  */
688  template <class S>
689  V8_INLINE Persistent(Isolate* isolate, Local<S> that)
690  : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
691  TYPE_CHECK(T, S);
692  }
693  /**
694  * Construct a Persistent from a Persistent.
695  * When the Persistent is non-empty, a new storage cell is created
696  * pointing to the same object, and no flags are set.
697  */
698  template <class S, class M2>
699  V8_INLINE Persistent(Isolate* isolate, const Persistent<S, M2>& that)
700  : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
701  TYPE_CHECK(T, S);
702  }
703  /**
704  * The copy constructors and assignment operator create a Persistent
705  * exactly as the Persistent constructor, but the Copy function from the
706  * traits class is called, allowing the setting of flags based on the
707  * copied Persistent.
708  */
710  Copy(that);
711  }
712  template <class S, class M2>
713  V8_INLINE Persistent(const Persistent<S, M2>& that) : PersistentBase<T>(0) {
714  Copy(that);
715  }
716  V8_INLINE Persistent& operator=(const Persistent& that) { // NOLINT
717  Copy(that);
718  return *this;
719  }
720  template <class S, class M2>
721  V8_INLINE Persistent& operator=(const Persistent<S, M2>& that) { // NOLINT
722  Copy(that);
723  return *this;
724  }
725  /**
726  * The destructor will dispose the Persistent based on the
727  * kResetInDestructor flags in the traits class. Since not calling dispose
728  * can result in a memory leak, it is recommended to always set this flag.
729  */
731  if (M::kResetInDestructor) this->Reset();
732  }
733 
734  // TODO(dcarney): this is pretty useless, fix or remove
735  template <class S>
736  V8_INLINE static Persistent<T>& Cast(const Persistent<S>& that) { // NOLINT
737 #ifdef V8_ENABLE_CHECKS
738  // If we're going to perform the type check then we have to check
739  // that the handle isn't empty before doing the checked cast.
740  if (!that.IsEmpty()) T::Cast(*that);
741 #endif
742  return reinterpret_cast<Persistent<T>&>(const_cast<Persistent<S>&>(that));
743  }
744 
745  // TODO(dcarney): this is pretty useless, fix or remove
746  template <class S>
747  V8_INLINE Persistent<S>& As() const { // NOLINT
748  return Persistent<S>::Cast(*this);
749  }
750 
751  private:
752  friend class Isolate;
753  friend class Utils;
754  template<class F> friend class Local;
755  template<class F1, class F2> friend class Persistent;
756  template<class F> friend class ReturnValue;
757 
758  explicit V8_INLINE Persistent(T* that) : PersistentBase<T>(that) {}
759  V8_INLINE T* operator*() const { return this->val_; }
760  template<class S, class M2>
761  V8_INLINE void Copy(const Persistent<S, M2>& that);
762 };
763 
764 
765 /**
766  * A PersistentBase which has move semantics.
767  *
768  * Note: Persistent class hierarchy is subject to future changes.
769  */
770 template <class T>
771 class Global : public PersistentBase<T> {
772  public:
773  /**
774  * A Global with no storage cell.
775  */
776  V8_INLINE Global() : PersistentBase<T>(nullptr) {}
777  /**
778  * Construct a Global from a Local.
779  * When the Local is non-empty, a new storage cell is created
780  * pointing to the same object, and no flags are set.
781  */
782  template <class S>
783  V8_INLINE Global(Isolate* isolate, Local<S> that)
784  : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
785  TYPE_CHECK(T, S);
786  }
787  /**
788  * Construct a Global from a PersistentBase.
789  * When the Persistent is non-empty, a new storage cell is created
790  * pointing to the same object, and no flags are set.
791  */
792  template <class S>
793  V8_INLINE Global(Isolate* isolate, const PersistentBase<S>& that)
794  : PersistentBase<T>(PersistentBase<T>::New(isolate, that.val_)) {
795  TYPE_CHECK(T, S);
796  }
797  /**
798  * Move constructor.
799  */
800  V8_INLINE Global(Global&& other) : PersistentBase<T>(other.val_) { // NOLINT
801  other.val_ = nullptr;
802  }
803  V8_INLINE ~Global() { this->Reset(); }
804  /**
805  * Move via assignment.
806  */
807  template <class S>
808  V8_INLINE Global& operator=(Global<S>&& rhs) { // NOLINT
809  TYPE_CHECK(T, S);
810  if (this != &rhs) {
811  this->Reset();
812  this->val_ = rhs.val_;
813  rhs.val_ = nullptr;
814  }
815  return *this;
816  }
817  /**
818  * Pass allows returning uniques from functions, etc.
819  */
820  Global Pass() { return static_cast<Global&&>(*this); } // NOLINT
821 
822  /*
823  * For compatibility with Chromium's base::Bind (base::Passed).
824  */
825  typedef void MoveOnlyTypeForCPP03;
826 
827  Global(const Global&) = delete;
828  void operator=(const Global&) = delete;
829 
830  private:
831  template <class F>
832  friend class ReturnValue;
833  V8_INLINE T* operator*() const { return this->val_; }
834 };
835 
836 
837 // UniquePersistent is an alias for Global for historical reason.
838 template <class T>
839 using UniquePersistent = Global<T>;
840 
841 
842  /**
843  * A stack-allocated class that governs a number of local handles.
844  * After a handle scope has been created, all local handles will be
845  * allocated within that handle scope until either the handle scope is
846  * deleted or another handle scope is created. If there is already a
847  * handle scope and a new one is created, all allocations will take
848  * place in the new handle scope until it is deleted. After that,
849  * new handles will again be allocated in the original handle scope.
850  *
851  * After the handle scope of a local handle has been deleted the
852  * garbage collector will no longer track the object stored in the
853  * handle and may deallocate it. The behavior of accessing a handle
854  * for which the handle scope has been deleted is undefined.
855  */
857  public:
858  explicit HandleScope(Isolate* isolate);
859 
861 
862  /**
863  * Counts the number of allocated handles.
864  */
865  static int NumberOfHandles(Isolate* isolate);
866 
868  return reinterpret_cast<Isolate*>(isolate_);
869  }
870 
871  HandleScope(const HandleScope&) = delete;
872  void operator=(const HandleScope&) = delete;
873 
874  protected:
876 
877  void Initialize(Isolate* isolate);
878 
879  static internal::Object** CreateHandle(internal::Isolate* isolate,
880  internal::Object* value);
881 
882  private:
883  // Declaring operator new and delete as deleted is not spec compliant.
884  // Therefore declare them private instead to disable dynamic alloc
885  void* operator new(size_t size);
886  void* operator new[](size_t size);
887  void operator delete(void*, size_t);
888  void operator delete[](void*, size_t);
889 
890  // Uses heap_object to obtain the current Isolate.
891  static internal::Object** CreateHandle(internal::HeapObject* heap_object,
892  internal::Object* value);
893 
894  internal::Isolate* isolate_;
895  internal::Object** prev_next_;
896  internal::Object** prev_limit_;
897 
898  // Local::New uses CreateHandle with an Isolate* parameter.
899  template<class F> friend class Local;
900 
901  // Object::GetInternalField and Context::GetEmbedderData use CreateHandle with
902  // a HeapObject* in their shortcuts.
903  friend class Object;
904  friend class Context;
905 };
906 
907 
908 /**
909  * A HandleScope which first allocates a handle in the current scope
910  * which will be later filled with the escape value.
911  */
913  public:
914  explicit EscapableHandleScope(Isolate* isolate);
916 
917  /**
918  * Pushes the value into the previous scope and returns a handle to it.
919  * Cannot be called twice.
920  */
921  template <class T>
922  V8_INLINE Local<T> Escape(Local<T> value) {
923  internal::Object** slot =
924  Escape(reinterpret_cast<internal::Object**>(*value));
925  return Local<T>(reinterpret_cast<T*>(slot));
926  }
927 
929  void operator=(const EscapableHandleScope&) = delete;
930 
931  private:
932  // Declaring operator new and delete as deleted is not spec compliant.
933  // Therefore declare them private instead to disable dynamic alloc
934  void* operator new(size_t size);
935  void* operator new[](size_t size);
936  void operator delete(void*, size_t);
937  void operator delete[](void*, size_t);
938 
939  internal::Object** Escape(internal::Object** escape_value);
940  internal::Object** escape_slot_;
941 };
942 
943 /**
944  * A SealHandleScope acts like a handle scope in which no handle allocations
945  * are allowed. It can be useful for debugging handle leaks.
946  * Handles can be allocated within inner normal HandleScopes.
947  */
949  public:
952 
954  void operator=(const SealHandleScope&) = delete;
955 
956  private:
957  // Declaring operator new and delete as deleted is not spec compliant.
958  // Therefore declare them private instead to disable dynamic alloc
959  void* operator new(size_t size);
960  void* operator new[](size_t size);
961  void operator delete(void*, size_t);
962  void operator delete[](void*, size_t);
963 
964  internal::Isolate* const isolate_;
965  internal::Object** prev_limit_;
966  int prev_sealed_level_;
967 };
968 
969 
970 // --- Special objects ---
971 
972 
973 /**
974  * The superclass of values and API object templates.
975  */
977  private:
978  Data();
979 };
980 
981 
982 /**
983  * The optional attributes of ScriptOrigin.
984  */
986  public:
987  V8_INLINE ScriptOriginOptions(bool is_shared_cross_origin = false,
988  bool is_opaque = false, bool is_wasm = false,
989  bool is_module = false)
990  : flags_((is_shared_cross_origin ? kIsSharedCrossOrigin : 0) |
991  (is_wasm ? kIsWasm : 0) | (is_opaque ? kIsOpaque : 0) |
992  (is_module ? kIsModule : 0)) {}
994  : flags_(flags &
995  (kIsSharedCrossOrigin | kIsOpaque | kIsWasm | kIsModule)) {}
996 
997  bool IsSharedCrossOrigin() const {
998  return (flags_ & kIsSharedCrossOrigin) != 0;
999  }
1000  bool IsOpaque() const { return (flags_ & kIsOpaque) != 0; }
1001  bool IsWasm() const { return (flags_ & kIsWasm) != 0; }
1002  bool IsModule() const { return (flags_ & kIsModule) != 0; }
1003 
1004  int Flags() const { return flags_; }
1005 
1006  private:
1007  enum {
1008  kIsSharedCrossOrigin = 1,
1009  kIsOpaque = 1 << 1,
1010  kIsWasm = 1 << 2,
1011  kIsModule = 1 << 3
1012  };
1013  const int flags_;
1014 };
1015 
1016 /**
1017  * The origin, within a file, of a script.
1018  */
1020  public:
1022  Local<Value> resource_name,
1023  Local<Integer> resource_line_offset = Local<Integer>(),
1024  Local<Integer> resource_column_offset = Local<Integer>(),
1025  Local<Boolean> resource_is_shared_cross_origin = Local<Boolean>(),
1026  Local<Integer> script_id = Local<Integer>(),
1027  Local<Value> source_map_url = Local<Value>(),
1028  Local<Boolean> resource_is_opaque = Local<Boolean>(),
1029  Local<Boolean> is_wasm = Local<Boolean>(),
1030  Local<Boolean> is_module = Local<Boolean>());
1031 
1032  V8_INLINE Local<Value> ResourceName() const;
1035  V8_INLINE Local<Integer> ScriptID() const;
1036  V8_INLINE Local<Value> SourceMapUrl() const;
1037  V8_INLINE ScriptOriginOptions Options() const { return options_; }
1038 
1039  private:
1040  Local<Value> resource_name_;
1041  Local<Integer> resource_line_offset_;
1042  Local<Integer> resource_column_offset_;
1043  ScriptOriginOptions options_;
1044  Local<Integer> script_id_;
1045  Local<Value> source_map_url_;
1046 };
1047 
1048 /**
1049  * A compiled JavaScript script, not yet tied to a Context.
1050  */
1052  public:
1053  /**
1054  * Binds the script to the currently entered context.
1055  */
1057 
1058  int GetId();
1060 
1061  /**
1062  * Data read from magic sourceURL comments.
1063  */
1065  /**
1066  * Data read from magic sourceMappingURL comments.
1067  */
1069 
1070  /**
1071  * Returns zero based line number of the code_pos location in the script.
1072  * -1 will be returned if no information available.
1073  */
1074  int GetLineNumber(int code_pos);
1075 
1076  static const int kNoScriptId = 0;
1077 };
1078 
1079 /**
1080  * A location in JavaScript source.
1081  */
1083  public:
1084  int GetLineNumber() { return line_number_; }
1085  int GetColumnNumber() { return column_number_; }
1086 
1087  Location(int line_number, int column_number)
1088  : line_number_(line_number), column_number_(column_number) {}
1089 
1090  private:
1091  int line_number_;
1092  int column_number_;
1093 };
1094 
1095 /**
1096  * This is an unfinished experimental feature, and is only exposed
1097  * here for internal testing purposes. DO NOT USE.
1098  *
1099  * A compiled JavaScript module.
1100  */
1102  public:
1103  /**
1104  * The different states a module can be in.
1105  */
1106  enum Status {
1112  kErrored
1113  };
1114 
1115  /**
1116  * Returns the module's current status.
1117  */
1119 
1120  /**
1121  * For a module in kErrored status, this returns the corresponding exception.
1122  */
1124 
1125  /**
1126  * Returns the number of modules requested by this module.
1127  */
1129 
1130  /**
1131  * Returns the ith module specifier in this module.
1132  * i must be < GetModuleRequestsLength() and >= 0.
1133  */
1135 
1136  /**
1137  * Returns the source location (line number and column number) of the ith
1138  * module specifier's first occurrence in this module.
1139  */
1141 
1142  /**
1143  * Returns the identity hash for this object.
1144  */
1145  int GetIdentityHash() const;
1146 
1148  Local<String> specifier,
1149  Local<Module> referrer);
1150 
1151  /**
1152  * ModuleDeclarationInstantiation
1153  *
1154  * Returns an empty Maybe<bool> if an exception occurred during
1155  * instantiation. (In the case where the callback throws an exception, that
1156  * exception is propagated.)
1157  */
1158  V8_DEPRECATED("Use Maybe<bool> version",
1159  bool Instantiate(Local<Context> context,
1160  ResolveCallback callback));
1162  ResolveCallback callback);
1163 
1164  /**
1165  * ModuleEvaluation
1166  *
1167  * Returns the completion value.
1168  * TODO(neis): Be more precise or say nothing.
1169  */
1171 
1172  /**
1173  * Returns the namespace object of this module.
1174  * The module's status must be kEvaluated.
1175  */
1177 };
1178 
1179 /**
1180  * A compiled JavaScript script, tied to a Context which was active when the
1181  * script was compiled.
1182  */
1184  public:
1185  /**
1186  * A shorthand for ScriptCompiler::Compile().
1187  */
1189  "Use maybe version",
1190  Local<Script> Compile(Local<String> source,
1191  ScriptOrigin* origin = nullptr));
1193  Local<Context> context, Local<String> source,
1194  ScriptOrigin* origin = nullptr);
1195 
1196  static Local<Script> V8_DEPRECATE_SOON("Use maybe version",
1197  Compile(Local<String> source,
1198  Local<String> file_name));
1199 
1200  /**
1201  * Runs the script returning the resulting value. It will be run in the
1202  * context in which it was created (ScriptCompiler::CompileBound or
1203  * UnboundScript::BindToCurrentContext()).
1204  */
1205  V8_DEPRECATE_SOON("Use maybe version", Local<Value> Run());
1207 
1208  /**
1209  * Returns the corresponding context-unbound script.
1210  */
1212 };
1213 
1214 
1215 /**
1216  * For compiling scripts.
1217  */
1219  public:
1220  /**
1221  * Compilation data that the embedder can cache and pass back to speed up
1222  * future compilations. The data is produced if the CompilerOptions passed to
1223  * the compilation functions in ScriptCompiler contains produce_data_to_cache
1224  * = true. The data to cache can then can be retrieved from
1225  * UnboundScript.
1226  */
1230  BufferOwned
1231  };
1232 
1234  : data(NULL),
1235  length(0),
1236  rejected(false),
1238 
1239  // If buffer_policy is BufferNotOwned, the caller keeps the ownership of
1240  // data and guarantees that it stays alive until the CachedData object is
1241  // destroyed. If the policy is BufferOwned, the given data will be deleted
1242  // (with delete[]) when the CachedData object is destroyed.
1243  CachedData(const uint8_t* data, int length,
1244  BufferPolicy buffer_policy = BufferNotOwned);
1246  // TODO(marja): Async compilation; add constructors which take a callback
1247  // which will be called when V8 no longer needs the data.
1248  const uint8_t* data;
1249  int length;
1250  bool rejected;
1252 
1253  // Prevent copying.
1254  CachedData(const CachedData&) = delete;
1255  CachedData& operator=(const CachedData&) = delete;
1256  };
1257 
1258  /**
1259  * Source code which can be then compiled to a UnboundScript or Script.
1260  */
1261  class Source {
1262  public:
1263  // Source takes ownership of CachedData.
1264  V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
1265  CachedData* cached_data = NULL);
1266  V8_INLINE Source(Local<String> source_string,
1267  CachedData* cached_data = NULL);
1268  V8_INLINE ~Source();
1269 
1270  // Ownership of the CachedData or its buffers is *not* transferred to the
1271  // caller. The CachedData object is alive as long as the Source object is
1272  // alive.
1273  V8_INLINE const CachedData* GetCachedData() const;
1274 
1276 
1277  // Prevent copying.
1278  Source(const Source&) = delete;
1279  Source& operator=(const Source&) = delete;
1280 
1281  private:
1282  friend class ScriptCompiler;
1283 
1284  Local<String> source_string;
1285 
1286  // Origin information
1287  Local<Value> resource_name;
1288  Local<Integer> resource_line_offset;
1289  Local<Integer> resource_column_offset;
1290  ScriptOriginOptions resource_options;
1291  Local<Value> source_map_url;
1292 
1293  // Cached data from previous compilation (if a kConsume*Cache flag is
1294  // set), or hold newly generated cache data (kProduce*Cache flags) are
1295  // set when calling a compile method.
1296  CachedData* cached_data;
1297  };
1298 
1299  /**
1300  * For streaming incomplete script data to V8. The embedder should implement a
1301  * subclass of this class.
1302  */
1304  public:
1305  virtual ~ExternalSourceStream() {}
1306 
1307  /**
1308  * V8 calls this to request the next chunk of data from the embedder. This
1309  * function will be called on a background thread, so it's OK to block and
1310  * wait for the data, if the embedder doesn't have data yet. Returns the
1311  * length of the data returned. When the data ends, GetMoreData should
1312  * return 0. Caller takes ownership of the data.
1313  *
1314  * If the embedder wants to cancel the streaming, they should make the next
1315  * GetMoreData call return 0. V8 will interpret it as end of data (and most
1316  * probably, parsing will fail). The streaming task will return as soon as
1317  * V8 has parsed the data it received so far.
1318  */
1319  virtual size_t GetMoreData(const uint8_t** src) = 0;
1320 
1321  /**
1322  * V8 calls this method to set a 'bookmark' at the current position in
1323  * the source stream, for the purpose of (maybe) later calling
1324  * ResetToBookmark. If ResetToBookmark is called later, then subsequent
1325  * calls to GetMoreData should return the same data as they did when
1326  * SetBookmark was called earlier.
1327  *
1328  * The embedder may return 'false' to indicate it cannot provide this
1329  * functionality.
1330  */
1331  virtual bool SetBookmark();
1332 
1333  /**
1334  * V8 calls this to return to a previously set bookmark.
1335  */
1336  virtual void ResetToBookmark();
1337  };
1338 
1339 
1340  /**
1341  * Source code which can be streamed into V8 in pieces. It will be parsed
1342  * while streaming. It can be compiled after the streaming is complete.
1343  * StreamedSource must be kept alive while the streaming task is ran (see
1344  * ScriptStreamingTask below).
1345  */
1347  public:
1349 
1350  StreamedSource(ExternalSourceStream* source_stream, Encoding encoding);
1352 
1353  // Ownership of the CachedData or its buffers is *not* transferred to the
1354  // caller. The CachedData object is alive as long as the StreamedSource
1355  // object is alive.
1356  const CachedData* GetCachedData() const;
1357 
1358  internal::StreamedSource* impl() const { return impl_; }
1359 
1360  // Prevent copying.
1361  StreamedSource(const StreamedSource&) = delete;
1363 
1364  private:
1365  internal::StreamedSource* impl_;
1366  };
1367 
1368  /**
1369  * A streaming task which the embedder must run on a background thread to
1370  * stream scripts into V8. Returned by ScriptCompiler::StartStreamingScript.
1371  */
1373  public:
1374  virtual ~ScriptStreamingTask() {}
1375  virtual void Run() = 0;
1376  };
1377 
1384  };
1385 
1386  /**
1387  * Compiles the specified script (context-independent).
1388  * Cached data as part of the source object can be optionally produced to be
1389  * consumed later to speed up compilation of identical source scripts.
1390  *
1391  * Note that when producing cached data, the source must point to NULL for
1392  * cached data. When consuming cached data, the cached data must have been
1393  * produced by the same version of V8.
1394  *
1395  * \param source Script source code.
1396  * \return Compiled script object (context independent; for running it must be
1397  * bound to a context).
1398  */
1399  static V8_DEPRECATED("Use maybe version",
1400  Local<UnboundScript> CompileUnbound(
1401  Isolate* isolate, Source* source,
1402  CompileOptions options = kNoCompileOptions));
1404  Isolate* isolate, Source* source,
1405  CompileOptions options = kNoCompileOptions);
1406 
1407  /**
1408  * Compiles the specified script (bound to current context).
1409  *
1410  * \param source Script source code.
1411  * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
1412  * using pre_data speeds compilation if it's done multiple times.
1413  * Owned by caller, no references are kept when this function returns.
1414  * \return Compiled script object, bound to the context that was active
1415  * when this function was called. When run it will always use this
1416  * context.
1417  */
1419  "Use maybe version",
1420  Local<Script> Compile(Isolate* isolate, Source* source,
1421  CompileOptions options = kNoCompileOptions));
1423  Local<Context> context, Source* source,
1424  CompileOptions options = kNoCompileOptions);
1425 
1426  /**
1427  * Returns a task which streams script data into V8, or NULL if the script
1428  * cannot be streamed. The user is responsible for running the task on a
1429  * background thread and deleting it. When ran, the task starts parsing the
1430  * script, and it will request data from the StreamedSource as needed. When
1431  * ScriptStreamingTask::Run exits, all data has been streamed and the script
1432  * can be compiled (see Compile below).
1433  *
1434  * This API allows to start the streaming with as little data as possible, and
1435  * the remaining data (for example, the ScriptOrigin) is passed to Compile.
1436  */
1438  Isolate* isolate, StreamedSource* source,
1439  CompileOptions options = kNoCompileOptions);
1440 
1441  /**
1442  * Compiles a streamed script (bound to current context).
1443  *
1444  * This can only be called after the streaming has finished
1445  * (ScriptStreamingTask has been run). V8 doesn't construct the source string
1446  * during streaming, so the embedder needs to pass the full source here.
1447  */
1448  static V8_DEPRECATED("Use maybe version",
1449  Local<Script> Compile(Isolate* isolate,
1450  StreamedSource* source,
1451  Local<String> full_source_string,
1452  const ScriptOrigin& origin));
1454  Local<Context> context, StreamedSource* source,
1455  Local<String> full_source_string, const ScriptOrigin& origin);
1456 
1457  /**
1458  * Return a version tag for CachedData for the current V8 version & flags.
1459  *
1460  * This value is meant only for determining whether a previously generated
1461  * CachedData instance is still valid; the tag has no other meaing.
1462  *
1463  * Background: The data carried by CachedData may depend on the exact
1464  * V8 version number or current compiler flags. This means that when
1465  * persisting CachedData, the embedder must take care to not pass in
1466  * data from another V8 version, or the same version with different
1467  * features enabled.
1468  *
1469  * The easiest way to do so is to clear the embedder's cache on any
1470  * such change.
1471  *
1472  * Alternatively, this tag can be stored alongside the cached data and
1473  * compared when it is being used.
1474  */
1475  static uint32_t CachedDataVersionTag();
1476 
1477  /**
1478  * This is an unfinished experimental feature, and is only exposed
1479  * here for internal testing purposes. DO NOT USE.
1480  *
1481  * Compile an ES module, returning a Module that encapsulates
1482  * the compiled code.
1483  *
1484  * Corresponds to the ParseModule abstract operation in the
1485  * ECMAScript specification.
1486  */
1488  Isolate* isolate, Source* source);
1489 
1490  /**
1491  * Compile a function for a given context. This is equivalent to running
1492  *
1493  * with (obj) {
1494  * return function(args) { ... }
1495  * }
1496  *
1497  * It is possible to specify multiple context extensions (obj in the above
1498  * example).
1499  */
1500  static V8_DEPRECATE_SOON("Use maybe version",
1501  Local<Function> CompileFunctionInContext(
1502  Isolate* isolate, Source* source,
1503  Local<Context> context, size_t arguments_count,
1504  Local<String> arguments[],
1505  size_t context_extension_count,
1506  Local<Object> context_extensions[]));
1508  Local<Context> context, Source* source, size_t arguments_count,
1509  Local<String> arguments[], size_t context_extension_count,
1510  Local<Object> context_extensions[]);
1511 
1512  private:
1513  static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundInternal(
1514  Isolate* isolate, Source* source, CompileOptions options);
1515 };
1516 
1517 
1518 /**
1519  * An error message.
1520  */
1522  public:
1523  Local<String> Get() const;
1524 
1525  V8_DEPRECATE_SOON("Use maybe version", Local<String> GetSourceLine() const);
1527  Local<Context> context) const;
1528 
1529  /**
1530  * Returns the origin for the script from where the function causing the
1531  * error originates.
1532  */
1534 
1535  /**
1536  * Returns the resource name for the script from where the function causing
1537  * the error originates.
1538  */
1540 
1541  /**
1542  * Exception stack trace. By default stack traces are not captured for
1543  * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
1544  * to change this option.
1545  */
1547 
1548  /**
1549  * Returns the number, 1-based, of the line where the error occurred.
1550  */
1551  V8_DEPRECATE_SOON("Use maybe version", int GetLineNumber() const);
1553 
1554  /**
1555  * Returns the index within the script of the first character where
1556  * the error occurred.
1557  */
1558  int GetStartPosition() const;
1559 
1560  /**
1561  * Returns the index within the script of the last character where
1562  * the error occurred.
1563  */
1564  int GetEndPosition() const;
1565 
1566  /**
1567  * Returns the error level of the message.
1568  */
1569  int ErrorLevel() const;
1570 
1571  /**
1572  * Returns the index within the line of the first character where
1573  * the error occurred.
1574  */
1575  V8_DEPRECATE_SOON("Use maybe version", int GetStartColumn() const);
1577 
1578  /**
1579  * Returns the index within the line of the last character where
1580  * the error occurred.
1581  */
1582  V8_DEPRECATED("Use maybe version", int GetEndColumn() const);
1584 
1585  /**
1586  * Passes on the value set by the embedder when it fed the script from which
1587  * this Message was generated to V8.
1588  */
1589  bool IsSharedCrossOrigin() const;
1590  bool IsOpaque() const;
1591 
1592  // TODO(1245381): Print to a string instead of on a FILE.
1593  static void PrintCurrentStackTrace(Isolate* isolate, FILE* out);
1594 
1595  static const int kNoLineNumberInfo = 0;
1596  static const int kNoColumnInfo = 0;
1597  static const int kNoScriptIdInfo = 0;
1598 };
1599 
1600 
1601 /**
1602  * Representation of a JavaScript stack trace. The information collected is a
1603  * snapshot of the execution stack and the information remains valid after
1604  * execution continues.
1605  */
1607  public:
1608  /**
1609  * Flags that determine what information is placed captured for each
1610  * StackFrame when grabbing the current stack trace.
1611  * Note: these options are deprecated and we always collect all available
1612  * information (kDetailed).
1613  */
1617  kScriptName = 1 << 2,
1618  kFunctionName = 1 << 3,
1619  kIsEval = 1 << 4,
1620  kIsConstructor = 1 << 5,
1622  kScriptId = 1 << 7,
1626  };
1627 
1628  /**
1629  * Returns a StackFrame at a particular index.
1630  */
1631  Local<StackFrame> GetFrame(uint32_t index) const;
1632 
1633  /**
1634  * Returns the number of StackFrames.
1635  */
1636  int GetFrameCount() const;
1637 
1638  /**
1639  * Returns StackTrace as a v8::Array that contains StackFrame objects.
1640  */
1641  V8_DEPRECATED("Use native API instead", Local<Array> AsArray());
1642 
1643  /**
1644  * Grab a snapshot of the current JavaScript execution stack.
1645  *
1646  * \param frame_limit The maximum number of stack frames we want to capture.
1647  * \param options Enumerates the set of things we will capture for each
1648  * StackFrame.
1649  */
1651  Isolate* isolate, int frame_limit, StackTraceOptions options = kDetailed);
1652 };
1653 
1654 
1655 /**
1656  * A single JavaScript stack frame.
1657  */
1659  public:
1660  /**
1661  * Returns the number, 1-based, of the line for the associate function call.
1662  * This method will return Message::kNoLineNumberInfo if it is unable to
1663  * retrieve the line number, or if kLineNumber was not passed as an option
1664  * when capturing the StackTrace.
1665  */
1666  int GetLineNumber() const;
1667 
1668  /**
1669  * Returns the 1-based column offset on the line for the associated function
1670  * call.
1671  * This method will return Message::kNoColumnInfo if it is unable to retrieve
1672  * the column number, or if kColumnOffset was not passed as an option when
1673  * capturing the StackTrace.
1674  */
1675  int GetColumn() const;
1676 
1677  /**
1678  * Returns the id of the script for the function for this StackFrame.
1679  * This method will return Message::kNoScriptIdInfo if it is unable to
1680  * retrieve the script id, or if kScriptId was not passed as an option when
1681  * capturing the StackTrace.
1682  */
1683  int GetScriptId() const;
1684 
1685  /**
1686  * Returns the name of the resource that contains the script for the
1687  * function for this StackFrame.
1688  */
1690 
1691  /**
1692  * Returns the name of the resource that contains the script for the
1693  * function for this StackFrame or sourceURL value if the script name
1694  * is undefined and its source ends with //# sourceURL=... string or
1695  * deprecated //@ sourceURL=... string.
1696  */
1698 
1699  /**
1700  * Returns the name of the function associated with this stack frame.
1701  */
1703 
1704  /**
1705  * Returns whether or not the associated function is compiled via a call to
1706  * eval().
1707  */
1708  bool IsEval() const;
1709 
1710  /**
1711  * Returns whether or not the associated function is called as a
1712  * constructor via "new".
1713  */
1714  bool IsConstructor() const;
1715 
1716  /**
1717  * Returns whether or not the associated functions is defined in wasm.
1718  */
1719  bool IsWasm() const;
1720 };
1721 
1722 
1723 // A StateTag represents a possible state of the VM.
1724 enum StateTag {
1732  IDLE
1733 };
1734 
1735 // A RegisterState represents the current state of registers used
1736 // by the sampling profiler API.
1738  RegisterState() : pc(nullptr), sp(nullptr), fp(nullptr) {}
1739  void* pc; // Instruction pointer.
1740  void* sp; // Stack pointer.
1741  void* fp; // Frame pointer.
1742 };
1743 
1744 // The output structure filled up by GetStackSample API function.
1745 struct SampleInfo {
1746  size_t frames_count; // Number of frames collected.
1747  StateTag vm_state; // Current VM state.
1748  void* external_callback_entry; // External callback address if VM is
1749  // executing an external callback.
1750 };
1751 
1752 /**
1753  * A JSON Parser and Stringifier.
1754  */
1756  public:
1757  /**
1758  * Tries to parse the string |json_string| and returns it as value if
1759  * successful.
1760  *
1761  * \param json_string The string to parse.
1762  * \return The corresponding value if successfully parsed.
1763  */
1764  static V8_DEPRECATED("Use the maybe version taking context",
1765  Local<Value> Parse(Local<String> json_string));
1766  static V8_DEPRECATE_SOON("Use the maybe version taking context",
1767  MaybeLocal<Value> Parse(Isolate* isolate,
1768  Local<String> json_string));
1770  Local<Context> context, Local<String> json_string);
1771 
1772  /**
1773  * Tries to stringify the JSON-serializable object |json_object| and returns
1774  * it as string if successful.
1775  *
1776  * \param json_object The JSON-serializable object to stringify.
1777  * \return The corresponding string if successfully stringified.
1778  */
1780  Local<Context> context, Local<Object> json_object,
1781  Local<String> gap = Local<String>());
1782 };
1783 
1784 /**
1785  * Value serialization compatible with the HTML structured clone algorithm.
1786  * The format is backward-compatible (i.e. safe to store to disk).
1787  *
1788  * WARNING: This API is under development, and changes (including incompatible
1789  * changes to the API or wire format) may occur without notice until this
1790  * warning is removed.
1791  */
1793  public:
1795  public:
1796  virtual ~Delegate() {}
1797 
1798  /**
1799  * Handles the case where a DataCloneError would be thrown in the structured
1800  * clone spec. Other V8 embedders may throw some other appropriate exception
1801  * type.
1802  */
1803  virtual void ThrowDataCloneError(Local<String> message) = 0;
1804 
1805  /**
1806  * The embedder overrides this method to write some kind of host object, if
1807  * possible. If not, a suitable exception should be thrown and
1808  * Nothing<bool>() returned.
1809  */
1810  virtual Maybe<bool> WriteHostObject(Isolate* isolate, Local<Object> object);
1811 
1812  /**
1813  * Called when the ValueSerializer is going to serialize a
1814  * SharedArrayBuffer object. The embedder must return an ID for the
1815  * object, using the same ID if this SharedArrayBuffer has already been
1816  * serialized in this buffer. When deserializing, this ID will be passed to
1817  * ValueDeserializer::TransferSharedArrayBuffer as |transfer_id|.
1818  *
1819  * If the object cannot be serialized, an
1820  * exception should be thrown and Nothing<uint32_t>() returned.
1821  */
1822  virtual Maybe<uint32_t> GetSharedArrayBufferId(
1823  Isolate* isolate, Local<SharedArrayBuffer> shared_array_buffer);
1824 
1825  virtual Maybe<uint32_t> GetWasmModuleTransferId(
1826  Isolate* isolate, Local<WasmCompiledModule> module);
1827  /**
1828  * Allocates memory for the buffer of at least the size provided. The actual
1829  * size (which may be greater or equal) is written to |actual_size|. If no
1830  * buffer has been allocated yet, nullptr will be provided.
1831  *
1832  * If the memory cannot be allocated, nullptr should be returned.
1833  * |actual_size| will be ignored. It is assumed that |old_buffer| is still
1834  * valid in this case and has not been modified.
1835  */
1836  virtual void* ReallocateBufferMemory(void* old_buffer, size_t size,
1837  size_t* actual_size);
1838 
1839  /**
1840  * Frees a buffer allocated with |ReallocateBufferMemory|.
1841  */
1842  virtual void FreeBufferMemory(void* buffer);
1843  };
1844 
1845  explicit ValueSerializer(Isolate* isolate);
1846  ValueSerializer(Isolate* isolate, Delegate* delegate);
1848 
1849  /**
1850  * Writes out a header, which includes the format version.
1851  */
1852  void WriteHeader();
1853 
1854  /**
1855  * Serializes a JavaScript value into the buffer.
1856  */
1858  Local<Value> value);
1859 
1860  /**
1861  * Returns the stored data. This serializer should not be used once the buffer
1862  * is released. The contents are undefined if a previous write has failed.
1863  */
1864  V8_DEPRECATE_SOON("Use Release()", std::vector<uint8_t> ReleaseBuffer());
1865 
1866  /**
1867  * Returns the stored data (allocated using the delegate's
1868  * AllocateBufferMemory) and its size. This serializer should not be used once
1869  * the buffer is released. The contents are undefined if a previous write has
1870  * failed.
1871  */
1872  V8_WARN_UNUSED_RESULT std::pair<uint8_t*, size_t> Release();
1873 
1874  /**
1875  * Marks an ArrayBuffer as havings its contents transferred out of band.
1876  * Pass the corresponding ArrayBuffer in the deserializing context to
1877  * ValueDeserializer::TransferArrayBuffer.
1878  */
1879  void TransferArrayBuffer(uint32_t transfer_id,
1880  Local<ArrayBuffer> array_buffer);
1881 
1882  /**
1883  * Similar to TransferArrayBuffer, but for SharedArrayBuffer.
1884  */
1885  V8_DEPRECATE_SOON("Use Delegate::GetSharedArrayBufferId",
1886  void TransferSharedArrayBuffer(
1887  uint32_t transfer_id,
1888  Local<SharedArrayBuffer> shared_array_buffer));
1889 
1890  /**
1891  * Indicate whether to treat ArrayBufferView objects as host objects,
1892  * i.e. pass them to Delegate::WriteHostObject. This should not be
1893  * called when no Delegate was passed.
1894  *
1895  * The default is not to treat ArrayBufferViews as host objects.
1896  */
1898 
1899  /**
1900  * Write raw data in various common formats to the buffer.
1901  * Note that integer types are written in base-128 varint format, not with a
1902  * binary copy. For use during an override of Delegate::WriteHostObject.
1903  */
1904  void WriteUint32(uint32_t value);
1905  void WriteUint64(uint64_t value);
1906  void WriteDouble(double value);
1907  void WriteRawBytes(const void* source, size_t length);
1908 
1909  private:
1910  ValueSerializer(const ValueSerializer&) = delete;
1911  void operator=(const ValueSerializer&) = delete;
1912 
1913  struct PrivateData;
1914  PrivateData* private_;
1915 };
1916 
1917 /**
1918  * Deserializes values from data written with ValueSerializer, or a compatible
1919  * implementation.
1920  *
1921  * WARNING: This API is under development, and changes (including incompatible
1922  * changes to the API or wire format) may occur without notice until this
1923  * warning is removed.
1924  */
1926  public:
1928  public:
1929  virtual ~Delegate() {}
1930 
1931  /**
1932  * The embedder overrides this method to read some kind of host object, if
1933  * possible. If not, a suitable exception should be thrown and
1934  * MaybeLocal<Object>() returned.
1935  */
1937 
1938  /**
1939  * Get a WasmCompiledModule given a transfer_id previously provided
1940  * by ValueSerializer::GetWasmModuleTransferId
1941  */
1943  Isolate* isolate, uint32_t transfer_id);
1944  };
1945 
1946  ValueDeserializer(Isolate* isolate, const uint8_t* data, size_t size);
1947  ValueDeserializer(Isolate* isolate, const uint8_t* data, size_t size,
1948  Delegate* delegate);
1950 
1951  /**
1952  * Reads and validates a header (including the format version).
1953  * May, for example, reject an invalid or unsupported wire format.
1954  */
1956 
1957  /**
1958  * Deserializes a JavaScript value from the buffer.
1959  */
1961 
1962  /**
1963  * Accepts the array buffer corresponding to the one passed previously to
1964  * ValueSerializer::TransferArrayBuffer.
1965  */
1966  void TransferArrayBuffer(uint32_t transfer_id,
1967  Local<ArrayBuffer> array_buffer);
1968 
1969  /**
1970  * Similar to TransferArrayBuffer, but for SharedArrayBuffer.
1971  * The id is not necessarily in the same namespace as unshared ArrayBuffer
1972  * objects.
1973  */
1974  void TransferSharedArrayBuffer(uint32_t id,
1975  Local<SharedArrayBuffer> shared_array_buffer);
1976 
1977  /**
1978  * Must be called before ReadHeader to enable support for reading the legacy
1979  * wire format (i.e., which predates this being shipped).
1980  *
1981  * Don't use this unless you need to read data written by previous versions of
1982  * blink::ScriptValueSerializer.
1983  */
1984  void SetSupportsLegacyWireFormat(bool supports_legacy_wire_format);
1985 
1986  /**
1987  * Expect inline wasm in the data stream (rather than in-memory transfer)
1988  */
1989  void SetExpectInlineWasm(bool allow_inline_wasm);
1990 
1991  /**
1992  * Reads the underlying wire format version. Likely mostly to be useful to
1993  * legacy code reading old wire format versions. Must be called after
1994  * ReadHeader.
1995  */
1996  uint32_t GetWireFormatVersion() const;
1997 
1998  /**
1999  * Reads raw data in various common formats to the buffer.
2000  * Note that integer types are read in base-128 varint format, not with a
2001  * binary copy. For use during an override of Delegate::ReadHostObject.
2002  */
2003  V8_WARN_UNUSED_RESULT bool ReadUint32(uint32_t* value);
2004  V8_WARN_UNUSED_RESULT bool ReadUint64(uint64_t* value);
2005  V8_WARN_UNUSED_RESULT bool ReadDouble(double* value);
2006  V8_WARN_UNUSED_RESULT bool ReadRawBytes(size_t length, const void** data);
2007 
2008  private:
2009  ValueDeserializer(const ValueDeserializer&) = delete;
2010  void operator=(const ValueDeserializer&) = delete;
2011 
2012  struct PrivateData;
2013  PrivateData* private_;
2014 };
2015 
2016 /**
2017  * A map whose keys are referenced weakly. It is similar to JavaScript WeakMap
2018  * but can be created without entering a v8::Context and hence shouldn't
2019  * escape to JavaScript.
2020  */
2021 class V8_EXPORT NativeWeakMap : public Data {
2022  public:
2023  static Local<NativeWeakMap> New(Isolate* isolate);
2024  void Set(Local<Value> key, Local<Value> value);
2025  Local<Value> Get(Local<Value> key) const;
2026  bool Has(Local<Value> key);
2027  bool Delete(Local<Value> key);
2028 };
2029 
2030 
2031 // --- Value ---
2032 
2033 
2034 /**
2035  * The superclass of all JavaScript values and objects.
2036  */
2037 class V8_EXPORT Value : public Data {
2038  public:
2039  /**
2040  * Returns true if this value is the undefined value. See ECMA-262
2041  * 4.3.10.
2042  */
2043  V8_INLINE bool IsUndefined() const;
2044 
2045  /**
2046  * Returns true if this value is the null value. See ECMA-262
2047  * 4.3.11.
2048  */
2049  V8_INLINE bool IsNull() const;
2050 
2051  /**
2052  * Returns true if this value is either the null or the undefined value.
2053  * See ECMA-262
2054  * 4.3.11. and 4.3.12
2055  */
2056  V8_INLINE bool IsNullOrUndefined() const;
2057 
2058  /**
2059  * Returns true if this value is true.
2060  */
2061  bool IsTrue() const;
2062 
2063  /**
2064  * Returns true if this value is false.
2065  */
2066  bool IsFalse() const;
2067 
2068  /**
2069  * Returns true if this value is a symbol or a string.
2070  */
2071  bool IsName() const;
2072 
2073  /**
2074  * Returns true if this value is an instance of the String type.
2075  * See ECMA-262 8.4.
2076  */
2077  V8_INLINE bool IsString() const;
2078 
2079  /**
2080  * Returns true if this value is a symbol.
2081  */
2082  bool IsSymbol() const;
2083 
2084  /**
2085  * Returns true if this value is a function.
2086  */
2087  bool IsFunction() const;
2088 
2089  /**
2090  * Returns true if this value is an array. Note that it will return false for
2091  * an Proxy for an array.
2092  */
2093  bool IsArray() const;
2094 
2095  /**
2096  * Returns true if this value is an object.
2097  */
2098  bool IsObject() const;
2099 
2100  /**
2101  * Returns true if this value is boolean.
2102  */
2103  bool IsBoolean() const;
2104 
2105  /**
2106  * Returns true if this value is a number.
2107  */
2108  bool IsNumber() const;
2109 
2110  /**
2111  * Returns true if this value is external.
2112  */
2113  bool IsExternal() const;
2114 
2115  /**
2116  * Returns true if this value is a 32-bit signed integer.
2117  */
2118  bool IsInt32() const;
2119 
2120  /**
2121  * Returns true if this value is a 32-bit unsigned integer.
2122  */
2123  bool IsUint32() const;
2124 
2125  /**
2126  * Returns true if this value is a Date.
2127  */
2128  bool IsDate() const;
2129 
2130  /**
2131  * Returns true if this value is an Arguments object.
2132  */
2133  bool IsArgumentsObject() const;
2134 
2135  /**
2136  * Returns true if this value is a Boolean object.
2137  */
2138  bool IsBooleanObject() const;
2139 
2140  /**
2141  * Returns true if this value is a Number object.
2142  */
2143  bool IsNumberObject() const;
2144 
2145  /**
2146  * Returns true if this value is a String object.
2147  */
2148  bool IsStringObject() const;
2149 
2150  /**
2151  * Returns true if this value is a Symbol object.
2152  */
2153  bool IsSymbolObject() const;
2154 
2155  /**
2156  * Returns true if this value is a NativeError.
2157  */
2158  bool IsNativeError() const;
2159 
2160  /**
2161  * Returns true if this value is a RegExp.
2162  */
2163  bool IsRegExp() const;
2164 
2165  /**
2166  * Returns true if this value is an async function.
2167  */
2168  bool IsAsyncFunction() const;
2169 
2170  /**
2171  * Returns true if this value is a Generator function.
2172  */
2173  bool IsGeneratorFunction() const;
2174 
2175  /**
2176  * Returns true if this value is a Generator object (iterator).
2177  */
2178  bool IsGeneratorObject() const;
2179 
2180  /**
2181  * Returns true if this value is a Promise.
2182  */
2183  bool IsPromise() const;
2184 
2185  /**
2186  * Returns true if this value is a Map.
2187  */
2188  bool IsMap() const;
2189 
2190  /**
2191  * Returns true if this value is a Set.
2192  */
2193  bool IsSet() const;
2194 
2195  /**
2196  * Returns true if this value is a Map Iterator.
2197  */
2198  bool IsMapIterator() const;
2199 
2200  /**
2201  * Returns true if this value is a Set Iterator.
2202  */
2203  bool IsSetIterator() const;
2204 
2205  /**
2206  * Returns true if this value is a WeakMap.
2207  */
2208  bool IsWeakMap() const;
2209 
2210  /**
2211  * Returns true if this value is a WeakSet.
2212  */
2213  bool IsWeakSet() const;
2214 
2215  /**
2216  * Returns true if this value is an ArrayBuffer.
2217  */
2218  bool IsArrayBuffer() const;
2219 
2220  /**
2221  * Returns true if this value is an ArrayBufferView.
2222  */
2223  bool IsArrayBufferView() const;
2224 
2225  /**
2226  * Returns true if this value is one of TypedArrays.
2227  */
2228  bool IsTypedArray() const;
2229 
2230  /**
2231  * Returns true if this value is an Uint8Array.
2232  */
2233  bool IsUint8Array() const;
2234 
2235  /**
2236  * Returns true if this value is an Uint8ClampedArray.
2237  */
2238  bool IsUint8ClampedArray() const;
2239 
2240  /**
2241  * Returns true if this value is an Int8Array.
2242  */
2243  bool IsInt8Array() const;
2244 
2245  /**
2246  * Returns true if this value is an Uint16Array.
2247  */
2248  bool IsUint16Array() const;
2249 
2250  /**
2251  * Returns true if this value is an Int16Array.
2252  */
2253  bool IsInt16Array() const;
2254 
2255  /**
2256  * Returns true if this value is an Uint32Array.
2257  */
2258  bool IsUint32Array() const;
2259 
2260  /**
2261  * Returns true if this value is an Int32Array.
2262  */
2263  bool IsInt32Array() const;
2264 
2265  /**
2266  * Returns true if this value is a Float32Array.
2267  */
2268  bool IsFloat32Array() const;
2269 
2270  /**
2271  * Returns true if this value is a Float64Array.
2272  */
2273  bool IsFloat64Array() const;
2274 
2275  /**
2276  * Returns true if this value is a DataView.
2277  */
2278  bool IsDataView() const;
2279 
2280  /**
2281  * Returns true if this value is a SharedArrayBuffer.
2282  * This is an experimental feature.
2283  */
2284  bool IsSharedArrayBuffer() const;
2285 
2286  /**
2287  * Returns true if this value is a JavaScript Proxy.
2288  */
2289  bool IsProxy() const;
2290 
2292 
2294  Local<Context> context) const;
2296  Local<Context> context) const;
2298  Local<Context> context) const;
2300  Local<Context> context) const;
2302  Local<Context> context) const;
2304  Local<Context> context) const;
2306  Local<Context> context) const;
2308 
2309  V8_DEPRECATE_SOON("Use maybe version",
2310  Local<Boolean> ToBoolean(Isolate* isolate) const);
2311  V8_DEPRECATE_SOON("Use maybe version",
2312  Local<Number> ToNumber(Isolate* isolate) const);
2313  V8_DEPRECATE_SOON("Use maybe version",
2314  Local<String> ToString(Isolate* isolate) const);
2315  V8_DEPRECATED("Use maybe version",
2316  Local<String> ToDetailString(Isolate* isolate) const);
2317  V8_DEPRECATE_SOON("Use maybe version",
2318  Local<Object> ToObject(Isolate* isolate) const);
2319  V8_DEPRECATE_SOON("Use maybe version",
2320  Local<Integer> ToInteger(Isolate* isolate) const);
2321  V8_DEPRECATED("Use maybe version",
2322  Local<Uint32> ToUint32(Isolate* isolate) const);
2323  V8_DEPRECATE_SOON("Use maybe version",
2324  Local<Int32> ToInt32(Isolate* isolate) const);
2325 
2326  inline V8_DEPRECATE_SOON("Use maybe version",
2327  Local<Boolean> ToBoolean() const);
2328  inline V8_DEPRECATED("Use maybe version", Local<Number> ToNumber() const);
2329  inline V8_DEPRECATE_SOON("Use maybe version", Local<String> ToString() const);
2330  inline V8_DEPRECATED("Use maybe version",
2331  Local<String> ToDetailString() const);
2332  inline V8_DEPRECATE_SOON("Use maybe version", Local<Object> ToObject() const);
2333  inline V8_DEPRECATE_SOON("Use maybe version",
2334  Local<Integer> ToInteger() const);
2335  inline V8_DEPRECATED("Use maybe version", Local<Uint32> ToUint32() const);
2336  inline V8_DEPRECATED("Use maybe version", Local<Int32> ToInt32() const);
2337 
2338  /**
2339  * Attempts to convert a string to an array index.
2340  * Returns an empty handle if the conversion fails.
2341  */
2342  V8_DEPRECATED("Use maybe version", Local<Uint32> ToArrayIndex() const);
2344  Local<Context> context) const;
2345 
2349  Local<Context> context) const;
2351  Local<Context> context) const;
2353 
2354  V8_DEPRECATE_SOON("Use maybe version", bool BooleanValue() const);
2355  V8_DEPRECATE_SOON("Use maybe version", double NumberValue() const);
2356  V8_DEPRECATE_SOON("Use maybe version", int64_t IntegerValue() const);
2357  V8_DEPRECATE_SOON("Use maybe version", uint32_t Uint32Value() const);
2358  V8_DEPRECATE_SOON("Use maybe version", int32_t Int32Value() const);
2359 
2360  /** JS == */
2361  V8_DEPRECATE_SOON("Use maybe version", bool Equals(Local<Value> that) const);
2363  Local<Value> that) const;
2364  bool StrictEquals(Local<Value> that) const;
2365  bool SameValue(Local<Value> that) const;
2366 
2367  template <class T> V8_INLINE static Value* Cast(T* value);
2368 
2370 
2371  Maybe<bool> InstanceOf(Local<Context> context, Local<Object> object);
2372 
2373  private:
2374  V8_INLINE bool QuickIsUndefined() const;
2375  V8_INLINE bool QuickIsNull() const;
2376  V8_INLINE bool QuickIsNullOrUndefined() const;
2377  V8_INLINE bool QuickIsString() const;
2378  bool FullIsUndefined() const;
2379  bool FullIsNull() const;
2380  bool FullIsString() const;
2381 };
2382 
2383 
2384 /**
2385  * The superclass of primitive values. See ECMA-262 4.3.2.
2386  */
2387 class V8_EXPORT Primitive : public Value { };
2388 
2389 
2390 /**
2391  * A primitive boolean value (ECMA-262, 4.3.14). Either the true
2392  * or false value.
2393  */
2394 class V8_EXPORT Boolean : public Primitive {
2395  public:
2396  bool Value() const;
2397  V8_INLINE static Boolean* Cast(v8::Value* obj);
2398  V8_INLINE static Local<Boolean> New(Isolate* isolate, bool value);
2399 
2400  private:
2401  static void CheckCast(v8::Value* obj);
2402 };
2403 
2404 
2405 /**
2406  * A superclass for symbols and strings.
2407  */
2408 class V8_EXPORT Name : public Primitive {
2409  public:
2410  /**
2411  * Returns the identity hash for this object. The current implementation
2412  * uses an inline property on the object to store the identity hash.
2413  *
2414  * The return value will never be 0. Also, it is not guaranteed to be
2415  * unique.
2416  */
2418 
2419  V8_INLINE static Name* Cast(Value* obj);
2420 
2421  private:
2422  static void CheckCast(Value* obj);
2423 };
2424 
2425 /**
2426  * A flag describing different modes of string creation.
2427  *
2428  * Aside from performance implications there are no differences between the two
2429  * creation modes.
2430  */
2431 enum class NewStringType {
2432  /**
2433  * Create a new string, always allocating new storage memory.
2434  */
2435  kNormal,
2436 
2437  /**
2438  * Acts as a hint that the string should be created in the
2439  * old generation heap space and be deduplicated if an identical string
2440  * already exists.
2441  */
2443 };
2444 
2445 /**
2446  * A JavaScript string value (ECMA-262, 4.3.17).
2447  */
2448 class V8_EXPORT String : public Name {
2449  public:
2450  static constexpr int kMaxLength =
2451  sizeof(void*) == 4 ? (1 << 28) - 16 : (1 << 30) - 1 - 24;
2452 
2453  enum Encoding {
2456  ONE_BYTE_ENCODING = 0x8
2457  };
2458  /**
2459  * Returns the number of characters (UTF-16 code units) in this string.
2460  */
2461  int Length() const;
2462 
2463  /**
2464  * Returns the number of bytes in the UTF-8 encoded
2465  * representation of this string.
2466  */
2467  int Utf8Length() const;
2468 
2469  /**
2470  * Returns whether this string is known to contain only one byte data,
2471  * i.e. ISO-8859-1 code points.
2472  * Does not read the string.
2473  * False negatives are possible.
2474  */
2475  bool IsOneByte() const;
2476 
2477  /**
2478  * Returns whether this string contain only one byte data,
2479  * i.e. ISO-8859-1 code points.
2480  * Will read the entire string in some cases.
2481  */
2482  bool ContainsOnlyOneByte() const;
2483 
2484  /**
2485  * Write the contents of the string to an external buffer.
2486  * If no arguments are given, expects the buffer to be large
2487  * enough to hold the entire string and NULL terminator. Copies
2488  * the contents of the string and the NULL terminator into the
2489  * buffer.
2490  *
2491  * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
2492  * before the end of the buffer.
2493  *
2494  * Copies up to length characters into the output buffer.
2495  * Only null-terminates if there is enough space in the buffer.
2496  *
2497  * \param buffer The buffer into which the string will be copied.
2498  * \param start The starting position within the string at which
2499  * copying begins.
2500  * \param length The number of characters to copy from the string. For
2501  * WriteUtf8 the number of bytes in the buffer.
2502  * \param nchars_ref The number of characters written, can be NULL.
2503  * \param options Various options that might affect performance of this or
2504  * subsequent operations.
2505  * \return The number of characters copied to the buffer excluding the null
2506  * terminator. For WriteUtf8: The number of bytes copied to the buffer
2507  * including the null terminator (if written).
2508  */
2514  // Used by WriteUtf8 to replace orphan surrogate code units with the
2515  // unicode replacement character. Needs to be set to guarantee valid UTF-8
2516  // output.
2518  };
2519 
2520  // 16-bit character codes.
2521  int Write(uint16_t* buffer,
2522  int start = 0,
2523  int length = -1,
2524  int options = NO_OPTIONS) const;
2525  // One byte characters.
2526  int WriteOneByte(uint8_t* buffer,
2527  int start = 0,
2528  int length = -1,
2529  int options = NO_OPTIONS) const;
2530  // UTF-8 encoded characters.
2531  int WriteUtf8(char* buffer,
2532  int length = -1,
2533  int* nchars_ref = NULL,
2534  int options = NO_OPTIONS) const;
2535 
2536  /**
2537  * A zero length string.
2538  */
2539  V8_INLINE static Local<String> Empty(Isolate* isolate);
2540 
2541  /**
2542  * Returns true if the string is external
2543  */
2544  bool IsExternal() const;
2545 
2546  /**
2547  * Returns true if the string is both external and one-byte.
2548  */
2549  bool IsExternalOneByte() const;
2550 
2552  public:
2554 
2555  virtual bool IsCompressible() const { return false; }
2556 
2557  protected:
2559 
2560  /**
2561  * Internally V8 will call this Dispose method when the external string
2562  * resource is no longer needed. The default implementation will use the
2563  * delete operator. This method can be overridden in subclasses to
2564  * control how allocated external string resources are disposed.
2565  */
2566  virtual void Dispose() { delete this; }
2567 
2568  // Disallow copying and assigning.
2570  void operator=(const ExternalStringResourceBase&) = delete;
2571 
2572  private:
2573  friend class internal::Heap;
2574  friend class v8::String;
2575  };
2576 
2577  /**
2578  * An ExternalStringResource is a wrapper around a two-byte string
2579  * buffer that resides outside V8's heap. Implement an
2580  * ExternalStringResource to manage the life cycle of the underlying
2581  * buffer. Note that the string data must be immutable.
2582  */
2584  : public ExternalStringResourceBase {
2585  public:
2586  /**
2587  * Override the destructor to manage the life cycle of the underlying
2588  * buffer.
2589  */
2591 
2592  /**
2593  * The string data from the underlying buffer.
2594  */
2595  virtual const uint16_t* data() const = 0;
2596 
2597  /**
2598  * The length of the string. That is, the number of two-byte characters.
2599  */
2600  virtual size_t length() const = 0;
2601 
2602  protected:
2604  };
2605 
2606  /**
2607  * An ExternalOneByteStringResource is a wrapper around an one-byte
2608  * string buffer that resides outside V8's heap. Implement an
2609  * ExternalOneByteStringResource to manage the life cycle of the
2610  * underlying buffer. Note that the string data must be immutable
2611  * and that the data must be Latin-1 and not UTF-8, which would require
2612  * special treatment internally in the engine and do not allow efficient
2613  * indexing. Use String::New or convert to 16 bit data for non-Latin1.
2614  */
2615 
2617  : public ExternalStringResourceBase {
2618  public:
2619  /**
2620  * Override the destructor to manage the life cycle of the underlying
2621  * buffer.
2622  */
2624  /** The string data from the underlying buffer.*/
2625  virtual const char* data() const = 0;
2626  /** The number of Latin-1 characters in the string.*/
2627  virtual size_t length() const = 0;
2628  protected:
2630  };
2631 
2632  /**
2633  * If the string is an external string, return the ExternalStringResourceBase
2634  * regardless of the encoding, otherwise return NULL. The encoding of the
2635  * string is returned in encoding_out.
2636  */
2638  Encoding* encoding_out) const;
2639 
2640  /**
2641  * Get the ExternalStringResource for an external string. Returns
2642  * NULL if IsExternal() doesn't return true.
2643  */
2645 
2646  /**
2647  * Get the ExternalOneByteStringResource for an external one-byte string.
2648  * Returns NULL if IsExternalOneByte() doesn't return true.
2649  */
2651 
2652  V8_INLINE static String* Cast(v8::Value* obj);
2653 
2654  // TODO(dcarney): remove with deprecation of New functions.
2658  };
2659 
2660  /** Allocates a new string from UTF-8 data.*/
2662  "Use maybe version",
2663  Local<String> NewFromUtf8(Isolate* isolate, const char* data,
2665  int length = -1));
2666 
2667  /** Allocates a new string from UTF-8 data. Only returns an empty value when
2668  * length > kMaxLength. **/
2670  Isolate* isolate, const char* data, v8::NewStringType type,
2671  int length = -1);
2672 
2673  /** Allocates a new string from Latin-1 data.*/
2675  "Use maybe version",
2676  Local<String> NewFromOneByte(Isolate* isolate, const uint8_t* data,
2678  int length = -1));
2679 
2680  /** Allocates a new string from Latin-1 data. Only returns an empty value
2681  * when length > kMaxLength. **/
2683  Isolate* isolate, const uint8_t* data, v8::NewStringType type,
2684  int length = -1);
2685 
2686  /** Allocates a new string from UTF-16 data.*/
2688  "Use maybe version",
2689  Local<String> NewFromTwoByte(Isolate* isolate, const uint16_t* data,
2691  int length = -1));
2692 
2693  /** Allocates a new string from UTF-16 data. Only returns an empty value when
2694  * length > kMaxLength. **/
2696  Isolate* isolate, const uint16_t* data, v8::NewStringType type,
2697  int length = -1);
2698 
2699  /**
2700  * Creates a new string by concatenating the left and the right strings
2701  * passed in as parameters.
2702  */
2703  static Local<String> Concat(Local<String> left, Local<String> right);
2704 
2705  /**
2706  * Creates a new external string using the data defined in the given
2707  * resource. When the external string is no longer live on V8's heap the
2708  * resource will be disposed by calling its Dispose method. The caller of
2709  * this function should not otherwise delete or modify the resource. Neither
2710  * should the underlying buffer be deallocated or modified except through the
2711  * destructor of the external string resource.
2712  */
2713  static V8_DEPRECATED("Use maybe version",
2714  Local<String> NewExternal(
2715  Isolate* isolate, ExternalStringResource* resource));
2717  Isolate* isolate, ExternalStringResource* resource);
2718 
2719  /**
2720  * Associate an external string resource with this string by transforming it
2721  * in place so that existing references to this string in the JavaScript heap
2722  * will use the external string resource. The external string resource's
2723  * character contents need to be equivalent to this string.
2724  * Returns true if the string has been changed to be an external string.
2725  * The string is not modified if the operation fails. See NewExternal for
2726  * information on the lifetime of the resource.
2727  */
2729 
2730  /**
2731  * Creates a new external string using the one-byte data defined in the given
2732  * resource. When the external string is no longer live on V8's heap the
2733  * resource will be disposed by calling its Dispose method. The caller of
2734  * this function should not otherwise delete or modify the resource. Neither
2735  * should the underlying buffer be deallocated or modified except through the
2736  * destructor of the external string resource.
2737  */
2739  "Use maybe version",
2740  Local<String> NewExternal(Isolate* isolate,
2741  ExternalOneByteStringResource* resource));
2743  Isolate* isolate, ExternalOneByteStringResource* resource);
2744 
2745  /**
2746  * Associate an external string resource with this string by transforming it
2747  * in place so that existing references to this string in the JavaScript heap
2748  * will use the external string resource. The external string resource's
2749  * character contents need to be equivalent to this string.
2750  * Returns true if the string has been changed to be an external string.
2751  * The string is not modified if the operation fails. See NewExternal for
2752  * information on the lifetime of the resource.
2753  */
2755 
2756  /**
2757  * Returns true if this string can be made external.
2758  */
2760 
2761  /**
2762  * Converts an object to a UTF-8-encoded character array. Useful if
2763  * you want to print the object. If conversion to a string fails
2764  * (e.g. due to an exception in the toString() method of the object)
2765  * then the length() method returns 0 and the * operator returns
2766  * NULL.
2767  */
2769  public:
2770  V8_DEPRECATE_SOON("Use Isolate version",
2771  explicit Utf8Value(Local<v8::Value> obj));
2772  Utf8Value(Isolate* isolate, Local<v8::Value> obj);
2774  char* operator*() { return str_; }
2775  const char* operator*() const { return str_; }
2776  int length() const { return length_; }
2777 
2778  // Disallow copying and assigning.
2779  Utf8Value(const Utf8Value&) = delete;
2780  void operator=(const Utf8Value&) = delete;
2781 
2782  private:
2783  char* str_;
2784  int length_;
2785  };
2786 
2787  /**
2788  * Converts an object to a two-byte (UTF-16-encoded) string.
2789  * If conversion to a string fails (eg. due to an exception in the toString()
2790  * method of the object) then the length() method returns 0 and the * operator
2791  * returns NULL.
2792  */
2794  public:
2795  V8_DEPRECATE_SOON("Use Isolate version",
2796  explicit Value(Local<v8::Value> obj));
2797  Value(Isolate* isolate, Local<v8::Value> obj);
2798  ~Value();
2799  uint16_t* operator*() { return str_; }
2800  const uint16_t* operator*() const { return str_; }
2801  int length() const { return length_; }
2802 
2803  // Disallow copying and assigning.
2804  Value(const Value&) = delete;
2805  void operator=(const Value&) = delete;
2806 
2807  private:
2808  uint16_t* str_;
2809  int length_;
2810  };
2811 
2812  private:
2813  void VerifyExternalStringResourceBase(ExternalStringResourceBase* v,
2814  Encoding encoding) const;
2815  void VerifyExternalStringResource(ExternalStringResource* val) const;
2816  static void CheckCast(v8::Value* obj);
2817 };
2818 
2819 
2820 /**
2821  * A JavaScript symbol (ECMA-262 edition 6)
2822  */
2823 class V8_EXPORT Symbol : public Name {
2824  public:
2825  /**
2826  * Returns the print name string of the symbol, or undefined if none.
2827  */
2828  Local<Value> Name() const;
2829 
2830  /**
2831  * Create a symbol. If name is not empty, it will be used as the description.
2832  */
2833  static Local<Symbol> New(Isolate* isolate,
2834  Local<String> name = Local<String>());
2835 
2836  /**
2837  * Access global symbol registry.
2838  * Note that symbols created this way are never collected, so
2839  * they should only be used for statically fixed properties.
2840  * Also, there is only one global name space for the names used as keys.
2841  * To minimize the potential for clashes, use qualified names as keys.
2842  */
2843  static Local<Symbol> For(Isolate *isolate, Local<String> name);
2844 
2845  /**
2846  * Retrieve a global symbol. Similar to |For|, but using a separate
2847  * registry that is not accessible by (and cannot clash with) JavaScript code.
2848  */
2849  static Local<Symbol> ForApi(Isolate *isolate, Local<String> name);
2850 
2851  // Well-known symbols
2852  static Local<Symbol> GetHasInstance(Isolate* isolate);
2854  static Local<Symbol> GetIterator(Isolate* isolate);
2855  static Local<Symbol> GetMatch(Isolate* isolate);
2856  static Local<Symbol> GetReplace(Isolate* isolate);
2857  static Local<Symbol> GetSearch(Isolate* isolate);
2858  static Local<Symbol> GetSplit(Isolate* isolate);
2859  static Local<Symbol> GetToPrimitive(Isolate* isolate);
2860  static Local<Symbol> GetToStringTag(Isolate* isolate);
2861  static Local<Symbol> GetUnscopables(Isolate* isolate);
2862 
2863  V8_INLINE static Symbol* Cast(Value* obj);
2864 
2865  private:
2866  Symbol();
2867  static void CheckCast(Value* obj);
2868 };
2869 
2870 
2871 /**
2872  * A private symbol
2873  *
2874  * This is an experimental feature. Use at your own risk.
2875  */
2876 class V8_EXPORT Private : public Data {
2877  public:
2878  /**
2879  * Returns the print name string of the private symbol, or undefined if none.
2880  */
2881  Local<Value> Name() const;
2882 
2883  /**
2884  * Create a private symbol. If name is not empty, it will be the description.
2885  */
2886  static Local<Private> New(Isolate* isolate,
2887  Local<String> name = Local<String>());
2888 
2889  /**
2890  * Retrieve a global private symbol. If a symbol with this name has not
2891  * been retrieved in the same isolate before, it is created.
2892  * Note that private symbols created this way are never collected, so
2893  * they should only be used for statically fixed properties.
2894  * Also, there is only one global name space for the names used as keys.
2895  * To minimize the potential for clashes, use qualified names as keys,
2896  * e.g., "Class#property".
2897  */
2898  static Local<Private> ForApi(Isolate* isolate, Local<String> name);
2899 
2900  private:
2901  Private();
2902 };
2903 
2904 
2905 /**
2906  * A JavaScript number value (ECMA-262, 4.3.20)
2907  */
2908 class V8_EXPORT Number : public Primitive {
2909  public:
2910  double Value() const;
2911  static Local<Number> New(Isolate* isolate, double value);
2912  V8_INLINE static Number* Cast(v8::Value* obj);
2913  private:
2914  Number();
2915  static void CheckCast(v8::Value* obj);
2916 };
2917 
2918 
2919 /**
2920  * A JavaScript value representing a signed integer.
2921  */
2922 class V8_EXPORT Integer : public Number {
2923  public:
2924  static Local<Integer> New(Isolate* isolate, int32_t value);
2925  static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value);
2926  int64_t Value() const;
2927  V8_INLINE static Integer* Cast(v8::Value* obj);
2928  private:
2929  Integer();
2930  static void CheckCast(v8::Value* obj);
2931 };
2932 
2933 
2934 /**
2935  * A JavaScript value representing a 32-bit signed integer.
2936  */
2937 class V8_EXPORT Int32 : public Integer {
2938  public:
2939  int32_t Value() const;
2940  V8_INLINE static Int32* Cast(v8::Value* obj);
2941 
2942  private:
2943  Int32();
2944  static void CheckCast(v8::Value* obj);
2945 };
2946 
2947 
2948 /**
2949  * A JavaScript value representing a 32-bit unsigned integer.
2950  */
2951 class V8_EXPORT Uint32 : public Integer {
2952  public:
2953  uint32_t Value() const;
2954  V8_INLINE static Uint32* Cast(v8::Value* obj);
2955 
2956  private:
2957  Uint32();
2958  static void CheckCast(v8::Value* obj);
2959 };
2960 
2961 /**
2962  * PropertyAttribute.
2963  */
2965  /** None. **/
2966  None = 0,
2967  /** ReadOnly, i.e., not writable. **/
2968  ReadOnly = 1 << 0,
2969  /** DontEnum, i.e., not enumerable. **/
2970  DontEnum = 1 << 1,
2971  /** DontDelete, i.e., not configurable. **/
2972  DontDelete = 1 << 2
2973 };
2974 
2975 /**
2976  * Accessor[Getter|Setter] are used as callback functions when
2977  * setting|getting a particular property. See Object and ObjectTemplate's
2978  * method SetAccessor.
2979  */
2980 typedef void (*AccessorGetterCallback)(
2981  Local<String> property,
2982  const PropertyCallbackInfo<Value>& info);
2984  Local<Name> property,
2985  const PropertyCallbackInfo<Value>& info);
2986 
2987 
2988 typedef void (*AccessorSetterCallback)(
2989  Local<String> property,
2990  Local<Value> value,
2991  const PropertyCallbackInfo<void>& info);
2993  Local<Name> property,
2994  Local<Value> value,
2995  const PropertyCallbackInfo<void>& info);
2996 
2997 
2998 /**
2999  * Access control specifications.
3000  *
3001  * Some accessors should be accessible across contexts. These
3002  * accessors have an explicit access control parameter which specifies
3003  * the kind of cross-context access that should be allowed.
3004  *
3005  * TODO(dcarney): Remove PROHIBITS_OVERWRITING as it is now unused.
3006  */
3008  DEFAULT = 0,
3010  ALL_CAN_WRITE = 1 << 1,
3011  PROHIBITS_OVERWRITING = 1 << 2
3012 };
3013 
3014 /**
3015  * Property filter bits. They can be or'ed to build a composite filter.
3016  */
3023  SKIP_SYMBOLS = 16
3024 };
3025 
3026 /**
3027  * Keys/Properties filter enums:
3028  *
3029  * KeyCollectionMode limits the range of collected properties. kOwnOnly limits
3030  * the collected properties to the given Object only. kIncludesPrototypes will
3031  * include all keys of the objects's prototype chain as well.
3032  */
3034 
3035 /**
3036  * kIncludesIndices allows for integer indices to be collected, while
3037  * kSkipIndices will exclude integer indicies from being collected.
3038  */
3040 
3041 /**
3042  * Integrity level for objects.
3043  */
3045 
3046 /**
3047  * A JavaScript object (ECMA-262, 4.3.3)
3048  */
3049 class V8_EXPORT Object : public Value {
3050  public:
3051  V8_DEPRECATE_SOON("Use maybe version",
3052  bool Set(Local<Value> key, Local<Value> value));
3054  Local<Value> key, Local<Value> value);
3055 
3056  V8_DEPRECATE_SOON("Use maybe version",
3057  bool Set(uint32_t index, Local<Value> value));
3058  V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context, uint32_t index,
3059  Local<Value> value);
3060 
3061  // Implements CreateDataProperty (ECMA-262, 7.3.4).
3062  //
3063  // Defines a configurable, writable, enumerable property with the given value
3064  // on the object unless the property already exists and is not configurable
3065  // or the object is not extensible.
3066  //
3067  // Returns true on success.
3069  Local<Name> key,
3070  Local<Value> value);
3072  uint32_t index,
3073  Local<Value> value);
3074 
3075  // Implements DefineOwnProperty.
3076  //
3077  // In general, CreateDataProperty will be faster, however, does not allow
3078  // for specifying attributes.
3079  //
3080  // Returns true on success.
3082  Local<Context> context, Local<Name> key, Local<Value> value,
3083  PropertyAttribute attributes = None);
3084 
3085  // Implements Object.DefineProperty(O, P, Attributes), see Ecma-262 19.1.2.4.
3086  //
3087  // The defineProperty function is used to add an own property or
3088  // update the attributes of an existing own property of an object.
3089  //
3090  // Both data and accessor descriptors can be used.
3091  //
3092  // In general, CreateDataProperty is faster, however, does not allow
3093  // for specifying attributes or an accessor descriptor.
3094  //
3095  // The PropertyDescriptor can change when redefining a property.
3096  //
3097  // Returns true on success.
3099  Local<Context> context, Local<Name> key, PropertyDescriptor& descriptor);
3100 
3101  // Sets an own property on this object bypassing interceptors and
3102  // overriding accessors or read-only properties.
3103  //
3104  // Note that if the object has an interceptor the property will be set
3105  // locally, but since the interceptor takes precedence the local property
3106  // will only be returned if the interceptor doesn't return a value.
3107  //
3108  // Note also that this only works for named properties.
3109  V8_DEPRECATED("Use CreateDataProperty / DefineOwnProperty",
3110  Maybe<bool> ForceSet(Local<Context> context, Local<Value> key,
3111  Local<Value> value,
3112  PropertyAttribute attribs = None));
3113 
3114  V8_DEPRECATE_SOON("Use maybe version", Local<Value> Get(Local<Value> key));
3116  Local<Value> key);
3117 
3118  V8_DEPRECATE_SOON("Use maybe version", Local<Value> Get(uint32_t index));
3120  uint32_t index);
3121 
3122  /**
3123  * Gets the property attributes of a property which can be None or
3124  * any combination of ReadOnly, DontEnum and DontDelete. Returns
3125  * None when the property doesn't exist.
3126  */
3127  V8_DEPRECATED("Use maybe version",
3128  PropertyAttribute GetPropertyAttributes(Local<Value> key));
3130  Local<Context> context, Local<Value> key);
3131 
3132  /**
3133  * Returns Object.getOwnPropertyDescriptor as per ES2016 section 19.1.2.6.
3134  */
3135  V8_DEPRECATED("Use maybe version",
3136  Local<Value> GetOwnPropertyDescriptor(Local<Name> key));
3138  Local<Context> context, Local<Name> key);
3139 
3140  V8_DEPRECATE_SOON("Use maybe version", bool Has(Local<Value> key));
3141  /**
3142  * Object::Has() calls the abstract operation HasProperty(O, P) described
3143  * in ECMA-262, 7.3.10. Has() returns
3144  * true, if the object has the property, either own or on the prototype chain.
3145  * Interceptors, i.e., PropertyQueryCallbacks, are called if present.
3146  *
3147  * Has() has the same side effects as JavaScript's `variable in object`.
3148  * For example, calling Has() on a revoked proxy will throw an exception.
3149  *
3150  * \note Has() converts the key to a name, which possibly calls back into
3151  * JavaScript.
3152  *
3153  * See also v8::Object::HasOwnProperty() and
3154  * v8::Object::HasRealNamedProperty().
3155  */
3157  Local<Value> key);
3158 
3159  V8_DEPRECATE_SOON("Use maybe version", bool Delete(Local<Value> key));
3161  Local<Value> key);
3162 
3163  V8_DEPRECATED("Use maybe version", bool Has(uint32_t index));
3165  uint32_t index);
3166 
3167  V8_DEPRECATED("Use maybe version", bool Delete(uint32_t index));
3169  uint32_t index);
3170 
3171  V8_DEPRECATED("Use maybe version",
3172  bool SetAccessor(Local<String> name,
3173  AccessorGetterCallback getter,
3174  AccessorSetterCallback setter = 0,
3175  Local<Value> data = Local<Value>(),
3176  AccessControl settings = DEFAULT,
3177  PropertyAttribute attribute = None));
3178  V8_DEPRECATED("Use maybe version",
3179  bool SetAccessor(Local<Name> name,
3181  AccessorNameSetterCallback setter = 0,
3182  Local<Value> data = Local<Value>(),
3183  AccessControl settings = DEFAULT,
3184  PropertyAttribute attribute = None));
3186  Local<Name> name,
3188  AccessorNameSetterCallback setter = 0,
3190  AccessControl settings = DEFAULT,
3191  PropertyAttribute attribute = None);
3192 
3194  Local<Function> setter = Local<Function>(),
3195  PropertyAttribute attribute = None,
3196  AccessControl settings = DEFAULT);
3197 
3198  /**
3199  * Sets a native data property like Template::SetNativeDataProperty, but
3200  * this method sets on this object directly.
3201  */
3203  Local<Context> context, Local<Name> name,
3205  AccessorNameSetterCallback setter = nullptr,
3206  Local<Value> data = Local<Value>(), PropertyAttribute attributes = None);
3207 
3208  /**
3209  * Functionality for private properties.
3210  * This is an experimental feature, use at your own risk.
3211  * Note: Private properties are not inherited. Do not rely on this, since it
3212  * may change.
3213  */
3214  Maybe<bool> HasPrivate(Local<Context> context, Local<Private> key);
3215  Maybe<bool> SetPrivate(Local<Context> context, Local<Private> key,
3216  Local<Value> value);
3219 
3220  /**
3221  * Returns an array containing the names of the enumerable properties
3222  * of this object, including properties from prototype objects. The
3223  * array returned by this method contains the same values as would
3224  * be enumerated by a for-in statement over this object.
3225  */
3226  V8_DEPRECATE_SOON("Use maybe version", Local<Array> GetPropertyNames());
3228  Local<Context> context);
3230  Local<Context> context, KeyCollectionMode mode,
3231  PropertyFilter property_filter, IndexFilter index_filter);
3232 
3233  /**
3234  * This function has the same functionality as GetPropertyNames but
3235  * the returned array doesn't contain the names of properties from
3236  * prototype objects.
3237  */
3238  V8_DEPRECATE_SOON("Use maybe version", Local<Array> GetOwnPropertyNames());
3240  Local<Context> context);
3241 
3242  /**
3243  * Returns an array containing the names of the filtered properties
3244  * of this object, including properties from prototype objects. The
3245  * array returned by this method contains the same values as would
3246  * be enumerated by a for-in statement over this object.
3247  */
3249  Local<Context> context, PropertyFilter filter);
3250 
3251  /**
3252  * Get the prototype object. This does not skip objects marked to
3253  * be skipped by __proto__ and it does not consult the security
3254  * handler.
3255  */
3257 
3258  /**
3259  * Set the prototype object. This does not skip objects marked to
3260  * be skipped by __proto__ and it does not consult the security
3261  * handler.
3262  */
3263  V8_DEPRECATED("Use maybe version", bool SetPrototype(Local<Value> prototype));
3265  Local<Value> prototype);
3266 
3267  /**
3268  * Finds an instance of the given function template in the prototype
3269  * chain.
3270  */
3272 
3273  /**
3274  * Call builtin Object.prototype.toString on this object.
3275  * This is different from Value::ToString() that may call
3276  * user-defined toString function. This one does not.
3277  */
3278  V8_DEPRECATED("Use maybe version", Local<String> ObjectProtoToString());
3280  Local<Context> context);
3281 
3282  /**
3283  * Returns the name of the function invoked as a constructor for this object.
3284  */
3286 
3287  /**
3288  * Sets the integrity level of the object.
3289  */
3291 
3292  /** Gets the number of internal fields for this Object. */
3294 
3295  /** Same as above, but works for Persistents */
3297  const PersistentBase<Object>& object) {
3298  return object.val_->InternalFieldCount();
3299  }
3300 
3301  /** Gets the value from an internal field. */
3302  V8_INLINE Local<Value> GetInternalField(int index);
3303 
3304  /** Sets the value in an internal field. */
3305  void SetInternalField(int index, Local<Value> value);
3306 
3307  /**
3308  * Gets a 2-byte-aligned native pointer from an internal field. This field
3309  * must have been set by SetAlignedPointerInInternalField, everything else
3310  * leads to undefined behavior.
3311  */
3313 
3314  /** Same as above, but works for Persistents */
3316  const PersistentBase<Object>& object, int index) {
3317  return object.val_->GetAlignedPointerFromInternalField(index);
3318  }
3319 
3320  /**
3321  * Sets a 2-byte-aligned native pointer in an internal field. To retrieve such
3322  * a field, GetAlignedPointerFromInternalField must be used, everything else
3323  * leads to undefined behavior.
3324  */
3325  void SetAlignedPointerInInternalField(int index, void* value);
3326  void SetAlignedPointerInInternalFields(int argc, int indices[],
3327  void* values[]);
3328 
3329  // Testers for local properties.
3330  V8_DEPRECATED("Use maybe version", bool HasOwnProperty(Local<String> key));
3331 
3332  /**
3333  * HasOwnProperty() is like JavaScript's Object.prototype.hasOwnProperty().
3334  *
3335  * See also v8::Object::Has() and v8::Object::HasRealNamedProperty().
3336  */
3338  Local<Name> key);
3340  uint32_t index);
3341  V8_DEPRECATE_SOON("Use maybe version",
3342  bool HasRealNamedProperty(Local<String> key));
3343  /**
3344  * Use HasRealNamedProperty() if you want to check if an object has an own
3345  * property without causing side effects, i.e., without calling interceptors.
3346  *
3347  * This function is similar to v8::Object::HasOwnProperty(), but it does not
3348  * call interceptors.
3349  *
3350  * \note Consider using non-masking interceptors, i.e., the interceptors are
3351  * not called if the receiver has the real named property. See
3352  * `v8::PropertyHandlerFlags::kNonMasking`.
3353  *
3354  * See also v8::Object::Has().
3355  */
3357  Local<Name> key);
3358  V8_DEPRECATE_SOON("Use maybe version",
3359  bool HasRealIndexedProperty(uint32_t index));
3361  Local<Context> context, uint32_t index);
3362  V8_DEPRECATE_SOON("Use maybe version",
3363  bool HasRealNamedCallbackProperty(Local<String> key));
3365  Local<Context> context, Local<Name> key);
3366 
3367  /**
3368  * If result.IsEmpty() no real property was located in the prototype chain.
3369  * This means interceptors in the prototype chain are not called.
3370  */
3372  "Use maybe version",
3373  Local<Value> GetRealNamedPropertyInPrototypeChain(Local<String> key));
3375  Local<Context> context, Local<Name> key);
3376 
3377  /**
3378  * Gets the property attributes of a real property in the prototype chain,
3379  * which can be None or any combination of ReadOnly, DontEnum and DontDelete.
3380  * Interceptors in the prototype chain are not called.
3381  */
3383  "Use maybe version",
3384  Maybe<PropertyAttribute> GetRealNamedPropertyAttributesInPrototypeChain(
3385  Local<String> key));
3388  Local<Name> key);
3389 
3390  /**
3391  * If result.IsEmpty() no real property was located on the object or
3392  * in the prototype chain.
3393  * This means interceptors in the prototype chain are not called.
3394  */
3395  V8_DEPRECATED("Use maybe version",
3396  Local<Value> GetRealNamedProperty(Local<String> key));
3398  Local<Context> context, Local<Name> key);
3399 
3400  /**
3401  * Gets the property attributes of a real property which can be
3402  * None or any combination of ReadOnly, DontEnum and DontDelete.
3403  * Interceptors in the prototype chain are not called.
3404  */
3405  V8_DEPRECATED("Use maybe version",
3406  Maybe<PropertyAttribute> GetRealNamedPropertyAttributes(
3407  Local<String> key));
3409  Local<Context> context, Local<Name> key);
3410 
3411  /** Tests for a named lookup interceptor.*/
3413 
3414  /** Tests for an index lookup interceptor.*/
3416 
3417  /**
3418  * Returns the identity hash for this object. The current implementation
3419  * uses a hidden property on the object to store the identity hash.
3420  *
3421  * The return value will never be 0. Also, it is not guaranteed to be
3422  * unique.
3423  */
3425 
3426  /**
3427  * Clone this object with a fast but shallow copy. Values will point
3428  * to the same values as the original object.
3429  */
3430  // TODO(dcarney): take an isolate and optionally bail out?
3432 
3433  /**
3434  * Returns the context in which the object was created.
3435  */
3437 
3438  /** Same as above, but works for Persistents */
3440  const PersistentBase<Object>& object) {
3441  return object.val_->CreationContext();
3442  }
3443 
3444  /**
3445  * Checks whether a callback is set by the
3446  * ObjectTemplate::SetCallAsFunctionHandler method.
3447  * When an Object is callable this method returns true.
3448  */
3449  bool IsCallable();
3450 
3451  /**
3452  * True if this object is a constructor.
3453  */
3455 
3456  /**
3457  * Call an Object as a function if a callback is set by the
3458  * ObjectTemplate::SetCallAsFunctionHandler method.
3459  */
3460  V8_DEPRECATED("Use maybe version",
3461  Local<Value> CallAsFunction(Local<Value> recv, int argc,
3462  Local<Value> argv[]));
3464  Local<Value> recv,
3465  int argc,
3466  Local<Value> argv[]);
3467 
3468  /**
3469  * Call an Object as a constructor if a callback is set by the
3470  * ObjectTemplate::SetCallAsFunctionHandler method.
3471  * Note: This method behaves like the Function::NewInstance method.
3472  */
3473  V8_DEPRECATED("Use maybe version",
3474  Local<Value> CallAsConstructor(int argc, Local<Value> argv[]));
3476  Local<Context> context, int argc, Local<Value> argv[]);
3477 
3478  /**
3479  * Return the isolate to which the Object belongs to.
3480  */
3481  V8_DEPRECATE_SOON("Keep track of isolate correctly", Isolate* GetIsolate());
3482 
3483  static Local<Object> New(Isolate* isolate);
3484 
3485  V8_INLINE static Object* Cast(Value* obj);
3486 
3487  private:
3488  Object();
3489  static void CheckCast(Value* obj);
3490  Local<Value> SlowGetInternalField(int index);
3491  void* SlowGetAlignedPointerFromInternalField(int index);
3492 };
3493 
3494 
3495 /**
3496  * An instance of the built-in array constructor (ECMA-262, 15.4.2).
3497  */
3498 class V8_EXPORT Array : public Object {
3499  public:
3500  uint32_t Length() const;
3501 
3502  /**
3503  * Clones an element at index |index|. Returns an empty
3504  * handle if cloning fails (for any reason).
3505  */
3506  V8_DEPRECATED("Cloning is not supported.",
3507  Local<Object> CloneElementAt(uint32_t index));
3508  V8_DEPRECATED("Cloning is not supported.",
3509  MaybeLocal<Object> CloneElementAt(Local<Context> context,
3510  uint32_t index));
3511 
3512  /**
3513  * Creates a JavaScript array with the given length. If the length
3514  * is negative the returned array will have length 0.
3515  */
3516  static Local<Array> New(Isolate* isolate, int length = 0);
3517 
3518  V8_INLINE static Array* Cast(Value* obj);
3519  private:
3520  Array();
3521  static void CheckCast(Value* obj);
3522 };
3523 
3524 
3525 /**
3526  * An instance of the built-in Map constructor (ECMA-262, 6th Edition, 23.1.1).
3527  */
3528 class V8_EXPORT Map : public Object {
3529  public:
3530  size_t Size() const;
3531  void Clear();
3533  Local<Value> key);
3535  Local<Value> key,
3536  Local<Value> value);
3538  Local<Value> key);
3540  Local<Value> key);
3541 
3542  /**
3543  * Returns an array of length Size() * 2, where index N is the Nth key and
3544  * index N + 1 is the Nth value.
3545  */
3546  Local<Array> AsArray() const;
3547 
3548  /**
3549  * Creates a new empty Map.
3550  */
3551  static Local<Map> New(Isolate* isolate);
3552 
3553  V8_INLINE static Map* Cast(Value* obj);
3554 
3555  private:
3556  Map();
3557  static void CheckCast(Value* obj);
3558 };
3559 
3560 
3561 /**
3562  * An instance of the built-in Set constructor (ECMA-262, 6th Edition, 23.2.1).
3563  */
3564 class V8_EXPORT Set : public Object {
3565  public:
3566  size_t Size() const;
3567  void Clear();
3569  Local<Value> key);
3571  Local<Value> key);
3573  Local<Value> key);
3574 
3575  /**
3576  * Returns an array of the keys in this Set.
3577  */
3578  Local<Array> AsArray() const;
3579 
3580  /**
3581  * Creates a new empty Set.
3582  */
3583  static Local<Set> New(Isolate* isolate);
3584 
3585  V8_INLINE static Set* Cast(Value* obj);
3586 
3587  private:
3588  Set();
3589  static void CheckCast(Value* obj);
3590 };
3591 
3592 
3593 template<typename T>
3595  public:
3596  template <class S> V8_INLINE ReturnValue(const ReturnValue<S>& that)
3597  : value_(that.value_) {
3598  TYPE_CHECK(T, S);
3599  }
3600  // Local setters
3601  template <typename S>
3602  V8_INLINE V8_DEPRECATE_SOON("Use Global<> instead",
3603  void Set(const Persistent<S>& handle));
3604  template <typename S>
3605  V8_INLINE void Set(const Global<S>& handle);
3606  template <typename S>
3607  V8_INLINE void Set(const Local<S> handle);
3608  // Fast primitive setters
3609  V8_INLINE void Set(bool value);
3610  V8_INLINE void Set(double i);
3611  V8_INLINE void Set(int32_t i);
3612  V8_INLINE void Set(uint32_t i);
3613  // Fast JS primitive setters
3614  V8_INLINE void SetNull();
3615  V8_INLINE void SetUndefined();
3616  V8_INLINE void SetEmptyString();
3617  // Convenience getter for Isolate
3618  V8_INLINE Isolate* GetIsolate() const;
3619 
3620  // Pointer setter: Uncompilable to prevent inadvertent misuse.
3621  template <typename S>
3622  V8_INLINE void Set(S* whatever);
3623 
3624  // Getter. Creates a new Local<> so it comes with a certain performance
3625  // hit. If the ReturnValue was not yet set, this will return the undefined
3626  // value.
3627  V8_INLINE Local<Value> Get() const;
3628 
3629  private:
3630  template<class F> friend class ReturnValue;
3631  template<class F> friend class FunctionCallbackInfo;
3632  template<class F> friend class PropertyCallbackInfo;
3633  template <class F, class G, class H>
3635  V8_INLINE void SetInternal(internal::Object* value) { *value_ = value; }
3636  V8_INLINE internal::Object* GetDefaultValue();
3637  V8_INLINE explicit ReturnValue(internal::Object** slot);
3638  internal::Object** value_;
3639 };
3640 
3641 
3642 /**
3643  * The argument information given to function call callbacks. This
3644  * class provides access to information about the context of the call,
3645  * including the receiver, the number and values of arguments, and
3646  * the holder of the function.
3647  */
3648 template<typename T>
3650  public:
3651  /** The number of available arguments. */
3652  V8_INLINE int Length() const;
3653  /** Accessor for the available arguments. */
3654  V8_INLINE Local<Value> operator[](int i) const;
3655  V8_INLINE V8_DEPRECATED("Use Data() to explicitly pass Callee instead",
3656  Local<Function> Callee() const);
3657  /** Returns the receiver. This corresponds to the "this" value. */
3658  V8_INLINE Local<Object> This() const;
3659  /**
3660  * If the callback was created without a Signature, this is the same
3661  * value as This(). If there is a signature, and the signature didn't match
3662  * This() but one of its hidden prototypes, this will be the respective
3663  * hidden prototype.
3664  *
3665  * Note that this is not the prototype of This() on which the accessor
3666  * referencing this callback was found (which in V8 internally is often
3667  * referred to as holder [sic]).
3668  */
3669  V8_INLINE Local<Object> Holder() const;
3670  /** For construct calls, this returns the "new.target" value. */
3671  V8_INLINE Local<Value> NewTarget() const;
3672  /** Indicates whether this is a regular call or a construct call. */
3673  V8_INLINE bool IsConstructCall() const;
3674  /** The data argument specified when creating the callback. */
3675  V8_INLINE Local<Value> Data() const;
3676  /** The current Isolate. */
3677  V8_INLINE Isolate* GetIsolate() const;
3678  /** The ReturnValue for the call. */
3680  // This shouldn't be public, but the arm compiler needs it.
3681  static const int kArgsLength = 8;
3682 
3683  protected:
3684  friend class internal::FunctionCallbackArguments;
3686  friend class debug::ConsoleCallArguments;
3687  static const int kHolderIndex = 0;
3688  static const int kIsolateIndex = 1;
3689  static const int kReturnValueDefaultValueIndex = 2;
3690  static const int kReturnValueIndex = 3;
3691  static const int kDataIndex = 4;
3692  static const int kCalleeIndex = 5;
3693  static const int kContextSaveIndex = 6;
3694  static const int kNewTargetIndex = 7;
3695 
3696  V8_INLINE FunctionCallbackInfo(internal::Object** implicit_args,
3697  internal::Object** values, int length);
3699  internal::Object** values_;
3700  int length_;
3701 };
3702 
3703 
3704 /**
3705  * The information passed to a property callback about the context
3706  * of the property access.
3707  */
3708 template<typename T>
3710  public:
3711  /**
3712  * \return The isolate of the property access.
3713  */
3715 
3716  /**
3717  * \return The data set in the configuration, i.e., in
3718  * `NamedPropertyHandlerConfiguration` or
3719  * `IndexedPropertyHandlerConfiguration.`
3720  */
3722 
3723  /**
3724  * \return The receiver. In many cases, this is the object on which the
3725  * property access was intercepted. When using
3726  * `Reflect.get`, `Function.prototype.call`, or similar functions, it is the
3727  * object passed in as receiver or thisArg.
3728  *
3729  * \code
3730  * void GetterCallback(Local<Name> name,
3731  * const v8::PropertyCallbackInfo<v8::Value>& info) {
3732  * auto context = info.GetIsolate()->GetCurrentContext();
3733  *
3734  * v8::Local<v8::Value> a_this =
3735  * info.This()
3736  * ->GetRealNamedProperty(context, v8_str("a"))
3737  * .ToLocalChecked();
3738  * v8::Local<v8::Value> a_holder =
3739  * info.Holder()
3740  * ->GetRealNamedProperty(context, v8_str("a"))
3741  * .ToLocalChecked();
3742  *
3743  * CHECK(v8_str("r")->Equals(context, a_this).FromJust());
3744  * CHECK(v8_str("obj")->Equals(context, a_holder).FromJust());
3745  *
3746  * info.GetReturnValue().Set(name);
3747  * }
3748  *
3749  * v8::Local<v8::FunctionTemplate> templ =
3750  * v8::FunctionTemplate::New(isolate);
3751  * templ->InstanceTemplate()->SetHandler(
3752  * v8::NamedPropertyHandlerConfiguration(GetterCallback));
3753  * LocalContext env;
3754  * env->Global()
3755  * ->Set(env.local(), v8_str("obj"), templ->GetFunction(env.local())
3756  * .ToLocalChecked()
3757  * ->NewInstance(env.local())
3758  * .ToLocalChecked())
3759  * .FromJust();
3760  *
3761  * CompileRun("obj.a = 'obj'; var r = {a: 'r'}; Reflect.get(obj, 'x', r)");
3762  * \endcode
3763  */
3765 
3766  /**
3767  * \return The object in the prototype chain of the receiver that has the
3768  * interceptor. Suppose you have `x` and its prototype is `y`, and `y`
3769  * has an interceptor. Then `info.This()` is `x` and `info.Holder()` is `y`.
3770  * The Holder() could be a hidden object (the global object, rather
3771  * than the global proxy).
3772  *
3773  * \note For security reasons, do not pass the object back into the runtime.
3774  */
3776 
3777  /**
3778  * \return The return value of the callback.
3779  * Can be changed by calling Set().
3780  * \code
3781  * info.GetReturnValue().Set(...)
3782  * \endcode
3783  *
3784  */
3786 
3787  /**
3788  * \return True if the intercepted function should throw if an error occurs.
3789  * Usually, `true` corresponds to `'use strict'`.
3790  *
3791  * \note Always `false` when intercepting `Reflect.set()`
3792  * independent of the language mode.
3793  */
3795 
3796  // This shouldn't be public, but the arm compiler needs it.
3797  static const int kArgsLength = 7;
3798 
3799  protected:
3800  friend class MacroAssembler;
3801  friend class internal::PropertyCallbackArguments;
3803  static const int kShouldThrowOnErrorIndex = 0;
3804  static const int kHolderIndex = 1;
3805  static const int kIsolateIndex = 2;
3806  static const int kReturnValueDefaultValueIndex = 3;
3807  static const int kReturnValueIndex = 4;
3808  static const int kDataIndex = 5;
3809  static const int kThisIndex = 6;
3810 
3811  V8_INLINE PropertyCallbackInfo(internal::Object** args) : args_(args) {}
3812  internal::Object** args_;
3813 };
3814 
3815 
3816 typedef void (*FunctionCallback)(const FunctionCallbackInfo<Value>& info);
3817 
3819 
3820 /**
3821  * A JavaScript function object (ECMA-262, 15.3).
3822  */
3823 class V8_EXPORT Function : public Object {
3824  public:
3825  /**
3826  * Create a function in the current execution context
3827  * for a given FunctionCallback.
3828  */
3830  Local<Context> context, FunctionCallback callback,
3831  Local<Value> data = Local<Value>(), int length = 0,
3834  "Use maybe version",
3835  Local<Function> New(Isolate* isolate, FunctionCallback callback,
3836  Local<Value> data = Local<Value>(), int length = 0));
3837 
3838  V8_DEPRECATED("Use maybe version",
3839  Local<Object> NewInstance(int argc, Local<Value> argv[]) const);
3841  Local<Context> context, int argc, Local<Value> argv[]) const;
3842 
3843  V8_DEPRECATED("Use maybe version", Local<Object> NewInstance() const);
3845  Local<Context> context) const {
3846  return NewInstance(context, 0, nullptr);
3847  }
3848 
3849  V8_DEPRECATE_SOON("Use maybe version",
3850  Local<Value> Call(Local<Value> recv, int argc,
3851  Local<Value> argv[]));
3853  Local<Value> recv, int argc,
3854  Local<Value> argv[]);
3855 
3856  void SetName(Local<String> name);
3857  Local<Value> GetName() const;
3858 
3859  /**
3860  * Name inferred from variable or property assignment of this function.
3861  * Used to facilitate debugging and profiling of JavaScript code written
3862  * in an OO style, where many functions are anonymous but are assigned
3863  * to object properties.
3864  */
3866 
3867  /**
3868  * displayName if it is set, otherwise name if it is configured, otherwise
3869  * function name, otherwise inferred name.
3870  */
3872 
3873  /**
3874  * User-defined name assigned to the "displayName" property of this function.
3875  * Used to facilitate debugging and profiling of JavaScript code.
3876  */
3878 
3879  /**
3880  * Returns zero based line number of function body and
3881  * kLineOffsetNotFound if no information available.
3882  */
3883  int GetScriptLineNumber() const;
3884  /**
3885  * Returns zero based column number of function body and
3886  * kLineOffsetNotFound if no information available.
3887  */
3889 
3890  /**
3891  * Tells whether this function is builtin.
3892  */
3893  V8_DEPRECATED("this should no longer be used.", bool IsBuiltin() const);
3894 
3895  /**
3896  * Returns scriptId.
3897  */
3898  int ScriptId() const;
3899 
3900  /**
3901  * Returns the original function if this function is bound, else returns
3902  * v8::Undefined.
3903  */
3905 
3907  V8_INLINE static Function* Cast(Value* obj);
3908  static const int kLineOffsetNotFound;
3909 
3910  private:
3911  Function();
3912  static void CheckCast(Value* obj);
3913 };
3914 
3915 #ifndef V8_PROMISE_INTERNAL_FIELD_COUNT
3916 // The number of required internal fields can be defined by embedder.
3917 #define V8_PROMISE_INTERNAL_FIELD_COUNT 0
3918 #endif
3919 
3920 /**
3921  * An instance of the built-in Promise constructor (ES6 draft).
3922  */
3923 class V8_EXPORT Promise : public Object {
3924  public:
3925  /**
3926  * State of the promise. Each value corresponds to one of the possible values
3927  * of the [[PromiseState]] field.
3928  */
3930 
3931  class V8_EXPORT Resolver : public Object {
3932  public:
3933  /**
3934  * Create a new resolver, along with an associated promise in pending state.
3935  */
3936  static V8_DEPRECATE_SOON("Use maybe version",
3937  Local<Resolver> New(Isolate* isolate));
3939  Local<Context> context);
3940 
3941  /**
3942  * Extract the associated promise.
3943  */
3945 
3946  /**
3947  * Resolve/reject the associated promise with a given value.
3948  * Ignored if the promise is no longer pending.
3949  */
3950  V8_DEPRECATE_SOON("Use maybe version", void Resolve(Local<Value> value));
3952  Local<Value> value);
3953 
3954  V8_DEPRECATE_SOON("Use maybe version", void Reject(Local<Value> value));
3956  Local<Value> value);
3957 
3958  V8_INLINE static Resolver* Cast(Value* obj);
3959 
3960  private:
3961  Resolver();
3962  static void CheckCast(Value* obj);
3963  };
3964 
3965  /**
3966  * Register a resolution/rejection handler with a promise.
3967  * The handler is given the respective resolution/rejection value as
3968  * an argument. If the promise is already resolved/rejected, the handler is
3969  * invoked at the end of turn.
3970  */
3971  V8_DEPRECATED("Use maybe version",
3972  Local<Promise> Catch(Local<Function> handler));
3974  Local<Function> handler);
3975 
3976  V8_DEPRECATED("Use maybe version",
3977  Local<Promise> Then(Local<Function> handler));
3979  Local<Function> handler);
3980 
3981  /**
3982  * Returns true if the promise has at least one derived promise, and
3983  * therefore resolve/reject handlers (including default handler).
3984  */
3985  bool HasHandler();
3986 
3987  /**
3988  * Returns the content of the [[PromiseResult]] field. The Promise must not
3989  * be pending.
3990  */
3992 
3993  /**
3994  * Returns the value of the [[PromiseState]] field.
3995  */
3997 
3998  V8_INLINE static Promise* Cast(Value* obj);
3999 
4001 
4002  private:
4003  Promise();
4004  static void CheckCast(Value* obj);
4005 };
4006 
4007 /**
4008  * An instance of a Property Descriptor, see Ecma-262 6.2.4.
4009  *
4010  * Properties in a descriptor are present or absent. If you do not set
4011  * `enumerable`, `configurable`, and `writable`, they are absent. If `value`,
4012  * `get`, or `set` are absent, but you must specify them in the constructor, use
4013  * empty handles.
4014  *
4015  * Accessors `get` and `set` must be callable or undefined if they are present.
4016  *
4017  * \note Only query properties if they are present, i.e., call `x()` only if
4018  * `has_x()` returns true.
4019  *
4020  * \code
4021  * // var desc = {writable: false}
4022  * v8::PropertyDescriptor d(Local<Value>()), false);
4023  * d.value(); // error, value not set
4024  * if (d.has_writable()) {
4025  * d.writable(); // false
4026  * }
4027  *
4028  * // var desc = {value: undefined}
4029  * v8::PropertyDescriptor d(v8::Undefined(isolate));
4030  *
4031  * // var desc = {get: undefined}
4032  * v8::PropertyDescriptor d(v8::Undefined(isolate), Local<Value>()));
4033  * \endcode
4034  */
4036  public:
4037  // GenericDescriptor
4039 
4040  // DataDescriptor
4042 
4043  // DataDescriptor with writable property
4044  PropertyDescriptor(Local<Value> value, bool writable);
4045 
4046  // AccessorDescriptor
4048 
4050 
4051  Local<Value> value() const;
4052  bool has_value() const;
4053 
4054  Local<Value> get() const;
4055  bool has_get() const;
4056  Local<Value> set() const;
4057  bool has_set() const;
4058 
4059  void set_enumerable(bool enumerable);
4060  bool enumerable() const;
4061  bool has_enumerable() const;
4062 
4063  void set_configurable(bool configurable);
4064  bool configurable() const;
4065  bool has_configurable() const;
4066 
4067  bool writable() const;
4068  bool has_writable() const;
4069 
4070  struct PrivateData;
4071  PrivateData* get_private() const { return private_; }
4072 
4074  void operator=(const PropertyDescriptor&) = delete;
4075 
4076  private:
4077  PrivateData* private_;
4078 };
4079 
4080 /**
4081  * An instance of the built-in Proxy constructor (ECMA-262, 6th Edition,
4082  * 26.2.1).
4083  */
4084 class V8_EXPORT Proxy : public Object {
4085  public:
4088  bool IsRevoked();
4089  void Revoke();
4090 
4091  /**
4092  * Creates a new Proxy for the target object.
4093  */
4094  static MaybeLocal<Proxy> New(Local<Context> context,
4095  Local<Object> local_target,
4096  Local<Object> local_handler);
4097 
4098  V8_INLINE static Proxy* Cast(Value* obj);
4099 
4100  private:
4101  Proxy();
4102  static void CheckCast(Value* obj);
4103 };
4104 
4105 // TODO(mtrofin): rename WasmCompiledModule to WasmModuleObject, for
4106 // consistency with internal APIs.
4108  public:
4109  typedef std::pair<std::unique_ptr<const uint8_t[]>, size_t> SerializedModule;
4110  // A buffer that is owned by the caller.
4111  typedef std::pair<const uint8_t*, size_t> CallerOwnedBuffer;
4112 
4113  // An opaque, native heap object for transferring wasm modules. It
4114  // supports move semantics, and does not support copy semantics.
4115  class TransferrableModule final {
4116  public:
4117  TransferrableModule(TransferrableModule&& src) = default;
4118  TransferrableModule(const TransferrableModule& src) = delete;
4119 
4120  TransferrableModule& operator=(TransferrableModule&& src) = default;
4121  TransferrableModule& operator=(const TransferrableModule& src) = delete;
4122 
4123  private:
4124  typedef std::pair<std::unique_ptr<const uint8_t[]>, size_t> OwnedBuffer;
4125  friend class WasmCompiledModule;
4126  TransferrableModule(OwnedBuffer&& code, OwnedBuffer&& bytes)
4127  : compiled_code(std::move(code)), wire_bytes(std::move(bytes)) {}
4128 
4129  OwnedBuffer compiled_code = {nullptr, 0};
4130  OwnedBuffer wire_bytes = {nullptr, 0};
4131  };
4132 
4133  // Get an in-memory, non-persistable, and context-independent (meaning,
4134  // suitable for transfer to another Isolate and Context) representation
4135  // of this wasm compiled module.
4136  TransferrableModule GetTransferrableModule();
4137 
4138  // Efficiently re-create a WasmCompiledModule, without recompiling, from
4139  // a TransferrableModule.
4141  Isolate* isolate, const TransferrableModule&);
4142 
4143  // Get the wasm-encoded bytes that were used to compile this module.
4145 
4146  // Serialize the compiled module. The serialized data does not include the
4147  // uncompiled bytes.
4149 
4150  // If possible, deserialize the module, otherwise compile it from the provided
4151  // uncompiled bytes.
4153  Isolate* isolate, const CallerOwnedBuffer& serialized_module,
4154  const CallerOwnedBuffer& wire_bytes);
4155  V8_INLINE static WasmCompiledModule* Cast(Value* obj);
4156 
4157  private:
4158  // TODO(ahaas): please remove the friend once streamed compilation is
4159  // implemented
4160  friend class WasmModuleObjectBuilder;
4161 
4162  static MaybeLocal<WasmCompiledModule> Deserialize(
4163  Isolate* isolate, const CallerOwnedBuffer& serialized_module,
4164  const CallerOwnedBuffer& wire_bytes);
4165  static MaybeLocal<WasmCompiledModule> Compile(Isolate* isolate,
4166  const uint8_t* start,
4167  size_t length);
4168  static CallerOwnedBuffer AsCallerOwned(
4169  const TransferrableModule::OwnedBuffer& buff) {
4170  return {buff.first.get(), buff.second};
4171  }
4172 
4173  WasmCompiledModule();
4174  static void CheckCast(Value* obj);
4175 };
4176 
4177 // TODO(mtrofin): when streaming compilation is done, we can rename this
4178 // to simply WasmModuleObjectBuilder
4179 class V8_EXPORT WasmModuleObjectBuilderStreaming final {
4180  public:
4182  // The buffer passed into OnBytesReceived is owned by the caller.
4183  void OnBytesReceived(const uint8_t*, size_t size);
4184  void Finish();
4185  void Abort(Local<Value> exception);
4187 
4189 
4190  private:
4191  typedef std::pair<std::unique_ptr<const uint8_t[]>, size_t> Buffer;
4192 
4193  WasmModuleObjectBuilderStreaming(const WasmModuleObjectBuilderStreaming&) =
4194  delete;
4195  WasmModuleObjectBuilderStreaming(WasmModuleObjectBuilderStreaming&&) =
4196  default;
4197  WasmModuleObjectBuilderStreaming& operator=(
4198  const WasmModuleObjectBuilderStreaming&) = delete;
4199  WasmModuleObjectBuilderStreaming& operator=(
4200  WasmModuleObjectBuilderStreaming&&) = default;
4201  Isolate* isolate_ = nullptr;
4202 
4203 #if V8_CC_MSVC
4204  // We don't need the static Copy API, so the default
4205  // NonCopyablePersistentTraits would be sufficient, however,
4206  // MSVC eagerly instantiates the Copy.
4207  // We ensure we don't use Copy, however, by compiling with the
4208  // defaults everywhere else.
4209  Persistent<Promise, CopyablePersistentTraits<Promise>> promise_;
4210 #else
4211  Persistent<Promise> promise_;
4212 #endif
4213  std::vector<Buffer> received_buffers_;
4214  size_t total_size_ = 0;
4215 };
4216 
4217 class V8_EXPORT WasmModuleObjectBuilder final {
4218  public:
4219  WasmModuleObjectBuilder(Isolate* isolate) : isolate_(isolate) {}
4220  // The buffer passed into OnBytesReceived is owned by the caller.
4221  void OnBytesReceived(const uint8_t*, size_t size);
4223 
4224  private:
4225  Isolate* isolate_ = nullptr;
4226  // TODO(ahaas): We probably need none of this below here once streamed
4227  // compilation is implemented.
4228  typedef std::pair<std::unique_ptr<const uint8_t[]>, size_t> Buffer;
4229 
4230  // Disable copy semantics *in this implementation*. We can choose to
4231  // relax this, albeit it's not clear why.
4232  WasmModuleObjectBuilder(const WasmModuleObjectBuilder&) = delete;
4233  WasmModuleObjectBuilder(WasmModuleObjectBuilder&&) = default;
4234  WasmModuleObjectBuilder& operator=(const WasmModuleObjectBuilder&) = delete;
4235  WasmModuleObjectBuilder& operator=(WasmModuleObjectBuilder&&) = default;
4236 
4237  std::vector<Buffer> received_buffers_;
4238  size_t total_size_ = 0;
4239 };
4240 
4241 #ifndef V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT
4242 // The number of required internal fields can be defined by embedder.
4243 #define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 2
4244 #endif
4245 
4246 
4248 
4249 
4250 /**
4251  * An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5).
4252  */
4253 class V8_EXPORT ArrayBuffer : public Object {
4254  public:
4255  /**
4256  * A thread-safe allocator that V8 uses to allocate |ArrayBuffer|'s memory.
4257  * The allocator is a global V8 setting. It has to be set via
4258  * Isolate::CreateParams.
4259  *
4260  * Memory allocated through this allocator by V8 is accounted for as external
4261  * memory by V8. Note that V8 keeps track of the memory for all internalized
4262  * |ArrayBuffer|s. Responsibility for tracking external memory (using
4263  * Isolate::AdjustAmountOfExternalAllocatedMemory) is handed over to the
4264  * embedder upon externalization and taken over upon internalization (creating
4265  * an internalized buffer from an existing buffer).
4266  *
4267  * Note that it is unsafe to call back into V8 from any of the allocator
4268  * functions.
4269  */
4270  class V8_EXPORT Allocator { // NOLINT
4271  public:
4272  virtual ~Allocator() {}
4273 
4274  /**
4275  * Allocate |length| bytes. Return NULL if allocation is not successful.
4276  * Memory should be initialized to zeroes.
4277  */
4278  virtual void* Allocate(size_t length) = 0;
4279 
4280  /**
4281  * Allocate |length| bytes. Return NULL if allocation is not successful.
4282  * Memory does not have to be initialized.
4283  */
4284  virtual void* AllocateUninitialized(size_t length) = 0;
4285 
4286  /**
4287  * Reserved |length| bytes, but do not commit the memory. Must call
4288  * |SetProtection| to make memory accessible.
4289  */
4290  // TODO(eholk): make this pure virtual once blink implements this.
4291  virtual void* Reserve(size_t length);
4292 
4293  /**
4294  * Free the memory block of size |length|, pointed to by |data|.
4295  * That memory is guaranteed to be previously allocated by |Allocate|.
4296  */
4297  virtual void Free(void* data, size_t length) = 0;
4298 
4300 
4301  /**
4302  * Free the memory block of size |length|, pointed to by |data|.
4303  * That memory is guaranteed to be previously allocated by |Allocate| or
4304  * |Reserve|, depending on |mode|.
4305  */
4306  // TODO(eholk): make this pure virtual once blink implements this.
4307  virtual void Free(void* data, size_t length, AllocationMode mode);
4308 
4310 
4311  /**
4312  * Change the protection on a region of memory.
4313  *
4314  * On platforms that make a distinction between reserving and committing
4315  * memory, changing the protection to kReadWrite must also ensure the memory
4316  * is committed.
4317  */
4318  // TODO(eholk): make this pure virtual once blink implements this.
4319  virtual void SetProtection(void* data, size_t length,
4320  Protection protection);
4321 
4322  /**
4323  * malloc/free based convenience allocator.
4324  *
4325  * Caller takes ownership, i.e. the returned object needs to be freed using
4326  * |delete allocator| once it is no longer in use.
4327  */
4329  };
4330 
4331  /**
4332  * The contents of an |ArrayBuffer|. Externalization of |ArrayBuffer|
4333  * returns an instance of this class, populated, with a pointer to data
4334  * and byte length.
4335  *
4336  * The Data pointer of ArrayBuffer::Contents is always allocated with
4337  * Allocator::Allocate that is set via Isolate::CreateParams.
4338  */
4339  class V8_EXPORT Contents { // NOLINT
4340  public:
4342  : data_(nullptr),
4343  byte_length_(0),
4344  allocation_base_(nullptr),
4345  allocation_length_(0),
4346  allocation_mode_(Allocator::AllocationMode::kNormal) {}
4347 
4348  void* AllocationBase() const { return allocation_base_; }
4349  size_t AllocationLength() const { return allocation_length_; }
4350  Allocator::AllocationMode AllocationMode() const {
4351  return allocation_mode_;
4352  }
4353 
4354  void* Data() const { return data_; }
4355  size_t ByteLength() const { return byte_length_; }
4356 
4357  private:
4358  void* data_;
4359  size_t byte_length_;
4360  void* allocation_base_;
4361  size_t allocation_length_;
4362  Allocator::AllocationMode allocation_mode_;
4363 
4364  friend class ArrayBuffer;
4365  };
4366 
4367 
4368  /**
4369  * Data length in bytes.
4370  */
4371  size_t ByteLength() const;
4372 
4373  /**
4374  * Create a new ArrayBuffer. Allocate |byte_length| bytes.
4375  * Allocated memory will be owned by a created ArrayBuffer and
4376  * will be deallocated when it is garbage-collected,
4377  * unless the object is externalized.
4378  */
4379  static Local<ArrayBuffer> New(Isolate* isolate, size_t byte_length);
4380 
4381  /**
4382  * Create a new ArrayBuffer over an existing memory block.
4383  * The created array buffer is by default immediately in externalized state.
4384  * In externalized state, the memory block will not be reclaimed when a
4385  * created ArrayBuffer is garbage-collected.
4386  * In internalized state, the memory block will be released using
4387  * |Allocator::Free| once all ArrayBuffers referencing it are collected by
4388  * the garbage collector.
4389  */
4391  Isolate* isolate, void* data, size_t byte_length,
4393 
4394  /**
4395  * Returns true if ArrayBuffer is externalized, that is, does not
4396  * own its memory block.
4397  */
4398  bool IsExternal() const;
4399 
4400  /**
4401  * Returns true if this ArrayBuffer may be neutered.
4402  */
4403  bool IsNeuterable() const;
4404 
4405  /**
4406  * Neuters this ArrayBuffer and all its views (typed arrays).
4407  * Neutering sets the byte length of the buffer and all typed arrays to zero,
4408  * preventing JavaScript from ever accessing underlying backing store.
4409  * ArrayBuffer should have been externalized and must be neuterable.
4410  */
4411  void Neuter();
4412 
4413  /**
4414  * Make this ArrayBuffer external. The pointer to underlying memory block
4415  * and byte length are returned as |Contents| structure. After ArrayBuffer
4416  * had been externalized, it does no longer own the memory block. The caller
4417  * should take steps to free memory when it is no longer needed.
4418  *
4419  * The memory block is guaranteed to be allocated with |Allocator::Allocate|
4420  * that has been set via Isolate::CreateParams.
4421  */
4423 
4424  /**
4425  * Get a pointer to the ArrayBuffer's underlying memory block without
4426  * externalizing it. If the ArrayBuffer is not externalized, this pointer
4427  * will become invalid as soon as the ArrayBuffer gets garbage collected.
4428  *
4429  * The embedder should make sure to hold a strong reference to the
4430  * ArrayBuffer while accessing this pointer.
4431  *
4432  * The memory block is guaranteed to be allocated with |Allocator::Allocate|.
4433  */
4435 
4436  V8_INLINE static ArrayBuffer* Cast(Value* obj);
4437 
4440 
4441  private:
4442  ArrayBuffer();
4443  static void CheckCast(Value* obj);
4444 };
4445 
4446 
4447 #ifndef V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT
4448 // The number of required internal fields can be defined by embedder.
4449 #define V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT 2
4450 #endif
4451 
4452 
4453 /**
4454  * A base class for an instance of one of "views" over ArrayBuffer,
4455  * including TypedArrays and DataView (ES6 draft 15.13).
4456  */
4458  public:
4459  /**
4460  * Returns underlying ArrayBuffer.
4461  */
4463  /**
4464  * Byte offset in |Buffer|.
4465  */
4466  size_t ByteOffset();
4467  /**
4468  * Size of a view in bytes.
4469  */
4470  size_t ByteLength();
4471 
4472  /**
4473  * Copy the contents of the ArrayBufferView's buffer to an embedder defined
4474  * memory without additional overhead that calling ArrayBufferView::Buffer
4475  * might incur.
4476  *
4477  * Will write at most min(|byte_length|, ByteLength) bytes starting at
4478  * ByteOffset of the underlying buffer to the memory starting at |dest|.
4479  * Returns the number of bytes actually written.
4480  */
4481  size_t CopyContents(void* dest, size_t byte_length);
4482 
4483  /**
4484  * Returns true if ArrayBufferView's backing ArrayBuffer has already been
4485  * allocated.
4486  */
4487  bool HasBuffer() const;
4488 
4489  V8_INLINE static ArrayBufferView* Cast(Value* obj);
4490 
4491  static const int kInternalFieldCount =
4493  static const int kEmbedderFieldCount =
4495 
4496  private:
4497  ArrayBufferView();
4498  static void CheckCast(Value* obj);
4499 };
4500 
4501 
4502 /**
4503  * A base class for an instance of TypedArray series of constructors
4504  * (ES6 draft 15.13.6).
4505  */
4507  public:
4508  /*
4509  * The largest typed array size that can be constructed using New.
4510  */
4511  static constexpr size_t kMaxLength =
4512  sizeof(void*) == 4 ? (1u << 30) - 1 : (1u << 31) - 1;
4513 
4514  /**
4515  * Number of elements in this typed array
4516  * (e.g. for Int16Array, |ByteLength|/2).
4517  */
4518  size_t Length();
4519 
4520  V8_INLINE static TypedArray* Cast(Value* obj);
4521 
4522  private:
4523  TypedArray();
4524  static void CheckCast(Value* obj);
4525 };
4526 
4527 
4528 /**
4529  * An instance of Uint8Array constructor (ES6 draft 15.13.6).
4530  */
4532  public:
4533  static Local<Uint8Array> New(Local<ArrayBuffer> array_buffer,
4534  size_t byte_offset, size_t length);
4535  static Local<Uint8Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4536  size_t byte_offset, size_t length);
4537  V8_INLINE static Uint8Array* Cast(Value* obj);
4538 
4539  private:
4540  Uint8Array();
4541  static void CheckCast(Value* obj);
4542 };
4543 
4544 
4545 /**
4546  * An instance of Uint8ClampedArray constructor (ES6 draft 15.13.6).
4547  */
4549  public:
4551  size_t byte_offset, size_t length);
4553  Local<SharedArrayBuffer> shared_array_buffer, size_t byte_offset,
4554  size_t length);
4555  V8_INLINE static Uint8ClampedArray* Cast(Value* obj);
4556 
4557  private:
4558  Uint8ClampedArray();
4559  static void CheckCast(Value* obj);
4560 };
4561 
4562 /**
4563  * An instance of Int8Array constructor (ES6 draft 15.13.6).
4564  */
4566  public:
4567  static Local<Int8Array> New(Local<ArrayBuffer> array_buffer,
4568  size_t byte_offset, size_t length);
4569  static Local<Int8Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4570  size_t byte_offset, size_t length);
4571  V8_INLINE static Int8Array* Cast(Value* obj);
4572 
4573  private:
4574  Int8Array();
4575  static void CheckCast(Value* obj);
4576 };
4577 
4578 
4579 /**
4580  * An instance of Uint16Array constructor (ES6 draft 15.13.6).
4581  */
4583  public:
4584  static Local<Uint16Array> New(Local<ArrayBuffer> array_buffer,
4585  size_t byte_offset, size_t length);
4586  static Local<Uint16Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4587  size_t byte_offset, size_t length);
4588  V8_INLINE static Uint16Array* Cast(Value* obj);
4589 
4590  private:
4591  Uint16Array();
4592  static void CheckCast(Value* obj);
4593 };
4594 
4595 
4596 /**
4597  * An instance of Int16Array constructor (ES6 draft 15.13.6).
4598  */
4600  public:
4601  static Local<Int16Array> New(Local<ArrayBuffer> array_buffer,
4602  size_t byte_offset, size_t length);
4603  static Local<Int16Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4604  size_t byte_offset, size_t length);
4605  V8_INLINE static Int16Array* Cast(Value* obj);
4606 
4607  private:
4608  Int16Array();
4609  static void CheckCast(Value* obj);
4610 };
4611 
4612 
4613 /**
4614  * An instance of Uint32Array constructor (ES6 draft 15.13.6).
4615  */
4617  public:
4618  static Local<Uint32Array> New(Local<ArrayBuffer> array_buffer,
4619  size_t byte_offset, size_t length);
4620  static Local<Uint32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4621  size_t byte_offset, size_t length);
4622  V8_INLINE static Uint32Array* Cast(Value* obj);
4623 
4624  private:
4625  Uint32Array();
4626  static void CheckCast(Value* obj);
4627 };
4628 
4629 
4630 /**
4631  * An instance of Int32Array constructor (ES6 draft 15.13.6).
4632  */
4634  public:
4635  static Local<Int32Array> New(Local<ArrayBuffer> array_buffer,
4636  size_t byte_offset, size_t length);
4637  static Local<Int32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4638  size_t byte_offset, size_t length);
4639  V8_INLINE static Int32Array* Cast(Value* obj);
4640 
4641  private:
4642  Int32Array();
4643  static void CheckCast(Value* obj);
4644 };
4645 
4646 
4647 /**
4648  * An instance of Float32Array constructor (ES6 draft 15.13.6).
4649  */
4651  public:
4652  static Local<Float32Array> New(Local<ArrayBuffer> array_buffer,
4653  size_t byte_offset, size_t length);
4654  static Local<Float32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4655  size_t byte_offset, size_t length);
4656  V8_INLINE static Float32Array* Cast(Value* obj);
4657 
4658  private:
4659  Float32Array();
4660  static void CheckCast(Value* obj);
4661 };
4662 
4663 
4664 /**
4665  * An instance of Float64Array constructor (ES6 draft 15.13.6).
4666  */
4668  public:
4669  static Local<Float64Array> New(Local<ArrayBuffer> array_buffer,
4670  size_t byte_offset, size_t length);
4671  static Local<Float64Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4672  size_t byte_offset, size_t length);
4673  V8_INLINE static Float64Array* Cast(Value* obj);
4674 
4675  private:
4676  Float64Array();
4677  static void CheckCast(Value* obj);
4678 };
4679 
4680 
4681 /**
4682  * An instance of DataView constructor (ES6 draft 15.13.7).
4683  */
4685  public:
4686  static Local<DataView> New(Local<ArrayBuffer> array_buffer,
4687  size_t byte_offset, size_t length);
4688  static Local<DataView> New(Local<SharedArrayBuffer> shared_array_buffer,
4689  size_t byte_offset, size_t length);
4690  V8_INLINE static DataView* Cast(Value* obj);
4691 
4692  private:
4693  DataView();
4694  static void CheckCast(Value* obj);
4695 };
4696 
4697 
4698 /**
4699  * An instance of the built-in SharedArrayBuffer constructor.
4700  * This API is experimental and may change significantly.
4701  */
4703  public:
4704  /**
4705  * The contents of an |SharedArrayBuffer|. Externalization of
4706  * |SharedArrayBuffer| returns an instance of this class, populated, with a
4707  * pointer to data and byte length.
4708  *
4709  * The Data pointer of SharedArrayBuffer::Contents is always allocated with
4710  * |ArrayBuffer::Allocator::Allocate| by the allocator specified in
4711  * v8::Isolate::CreateParams::array_buffer_allocator.
4712  *
4713  * This API is experimental and may change significantly.
4714  */
4715  class V8_EXPORT Contents { // NOLINT
4716  public:
4718  : data_(nullptr),
4719  byte_length_(0),
4720  allocation_base_(nullptr),
4721  allocation_length_(0),
4723 
4724  void* AllocationBase() const { return allocation_base_; }
4725  size_t AllocationLength() const { return allocation_length_; }
4726  ArrayBuffer::Allocator::AllocationMode AllocationMode() const {
4727  return allocation_mode_;
4728  }
4729 
4730  void* Data() const { return data_; }
4731  size_t ByteLength() const { return byte_length_; }
4732 
4733  private:
4734  void* data_;
4735  size_t byte_length_;
4736  void* allocation_base_;
4737  size_t allocation_length_;
4738  ArrayBuffer::Allocator::AllocationMode allocation_mode_;
4739 
4740  friend class SharedArrayBuffer;
4741  };
4742 
4743 
4744  /**
4745  * Data length in bytes.
4746  */
4747  size_t ByteLength() const;
4748 
4749  /**
4750  * Create a new SharedArrayBuffer. Allocate |byte_length| bytes.
4751  * Allocated memory will be owned by a created SharedArrayBuffer and
4752  * will be deallocated when it is garbage-collected,
4753  * unless the object is externalized.
4754  */
4755  static Local<SharedArrayBuffer> New(Isolate* isolate, size_t byte_length);
4756 
4757  /**
4758  * Create a new SharedArrayBuffer over an existing memory block. The created
4759  * array buffer is immediately in externalized state unless otherwise
4760  * specified. The memory block will not be reclaimed when a created
4761  * SharedArrayBuffer is garbage-collected.
4762  */
4764  Isolate* isolate, void* data, size_t byte_length,
4766 
4767  /**
4768  * Returns true if SharedArrayBuffer is externalized, that is, does not
4769  * own its memory block.
4770  */
4771  bool IsExternal() const;
4772 
4773  /**
4774  * Make this SharedArrayBuffer external. The pointer to underlying memory
4775  * block and byte length are returned as |Contents| structure. After
4776  * SharedArrayBuffer had been externalized, it does no longer own the memory
4777  * block. The caller should take steps to free memory when it is no longer
4778  * needed.
4779  *
4780  * The memory block is guaranteed to be allocated with |Allocator::Allocate|
4781  * by the allocator specified in
4782  * v8::Isolate::CreateParams::array_buffer_allocator.
4783  *
4784  */
4786 
4787  /**
4788  * Get a pointer to the ArrayBuffer's underlying memory block without
4789  * externalizing it. If the ArrayBuffer is not externalized, this pointer
4790  * will become invalid as soon as the ArrayBuffer became garbage collected.
4791  *
4792  * The embedder should make sure to hold a strong reference to the
4793  * ArrayBuffer while accessing this pointer.
4794  *
4795  * The memory block is guaranteed to be allocated with |Allocator::Allocate|
4796  * by the allocator specified in
4797  * v8::Isolate::CreateParams::array_buffer_allocator.
4798  */
4800 
4801  V8_INLINE static SharedArrayBuffer* Cast(Value* obj);
4802 
4804 
4805  private:
4806  SharedArrayBuffer();
4807  static void CheckCast(Value* obj);
4808 };
4809 
4810 
4811 /**
4812  * An instance of the built-in Date constructor (ECMA-262, 15.9).
4813  */
4814 class V8_EXPORT Date : public Object {
4815  public:
4816  static V8_DEPRECATE_SOON("Use maybe version.",
4817  Local<Value> New(Isolate* isolate, double time));
4819  double time);
4820 
4821  /**
4822  * A specialization of Value::NumberValue that is more efficient
4823  * because we know the structure of this object.
4824  */
4825  double ValueOf() const;
4826 
4827  V8_INLINE static Date* Cast(Value* obj);
4828 
4829  /**
4830  * Notification that the embedder has changed the time zone,
4831  * daylight savings time, or other date / time configuration
4832  * parameters. V8 keeps a cache of various values used for
4833  * date / time computation. This notification will reset
4834  * those cached values for the current context so that date /
4835  * time configuration changes would be reflected in the Date
4836  * object.
4837  *
4838  * This API should not be called more than needed as it will
4839  * negatively impact the performance of date operations.
4840  */
4842 
4843  private:
4844  static void CheckCast(Value* obj);
4845 };
4846 
4847 
4848 /**
4849  * A Number object (ECMA-262, 4.3.21).
4850  */
4852  public:
4853  static Local<Value> New(Isolate* isolate, double value);
4854 
4855  double ValueOf() const;
4856 
4857  V8_INLINE static NumberObject* Cast(Value* obj);
4858 
4859  private:
4860  static void CheckCast(Value* obj);
4861 };
4862 
4863 
4864 /**
4865  * A Boolean object (ECMA-262, 4.3.15).
4866  */
4868  public:
4869  static Local<Value> New(Isolate* isolate, bool value);
4870  V8_DEPRECATED("Pass an isolate", static Local<Value> New(bool value));
4871 
4872  bool ValueOf() const;
4873 
4874  V8_INLINE static BooleanObject* Cast(Value* obj);
4875 
4876  private:
4877  static void CheckCast(Value* obj);
4878 };
4879 
4880 
4881 /**
4882  * A String object (ECMA-262, 4.3.18).
4883  */
4885  public:
4886  static Local<Value> New(Local<String> value);
4887 
4889 
4890  V8_INLINE static StringObject* Cast(Value* obj);
4891 
4892  private:
4893  static void CheckCast(Value* obj);
4894 };
4895 
4896 
4897 /**
4898  * A Symbol object (ECMA-262 edition 6).
4899  */
4901  public:
4902  static Local<Value> New(Isolate* isolate, Local<Symbol> value);
4903 
4905 
4906  V8_INLINE static SymbolObject* Cast(Value* obj);
4907 
4908  private:
4909  static void CheckCast(Value* obj);
4910 };
4911 
4912 
4913 /**
4914  * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
4915  */
4916 class V8_EXPORT RegExp : public Object {
4917  public:
4918  /**
4919  * Regular expression flag bits. They can be or'ed to enable a set
4920  * of flags.
4921  */
4922  enum Flags {
4923  kNone = 0,
4924  kGlobal = 1 << 0,
4925  kIgnoreCase = 1 << 1,
4926  kMultiline = 1 << 2,
4927  kSticky = 1 << 3,
4928  kUnicode = 1 << 4,
4929  kDotAll = 1 << 5,
4930  };
4931 
4932  /**
4933  * Creates a regular expression from the given pattern string and
4934  * the flags bit field. May throw a JavaScript exception as
4935  * described in ECMA-262, 15.10.4.1.
4936  *
4937  * For example,
4938  * RegExp::New(v8::String::New("foo"),
4939  * static_cast<RegExp::Flags>(kGlobal | kMultiline))
4940  * is equivalent to evaluating "/foo/gm".
4941  */
4942  static V8_DEPRECATE_SOON("Use maybe version",
4943  Local<RegExp> New(Local<String> pattern,
4944  Flags flags));
4946  Local<String> pattern,
4947  Flags flags);
4948 
4949  /**
4950  * Returns the value of the source property: a string representing
4951  * the regular expression.
4952  */
4954 
4955  /**
4956  * Returns the flags bit field.
4957  */
4958  Flags GetFlags() const;
4959 
4960  V8_INLINE static RegExp* Cast(Value* obj);
4961 
4962  private:
4963  static void CheckCast(Value* obj);
4964 };
4965 
4966 
4967 /**
4968  * A JavaScript value that wraps a C++ void*. This type of value is mainly used
4969  * to associate C++ data structures with JavaScript objects.
4970  */
4971 class V8_EXPORT External : public Value {
4972  public:
4973  static Local<External> New(Isolate* isolate, void* value);
4974  V8_INLINE static External* Cast(Value* obj);
4975  void* Value() const;
4976  private:
4977  static void CheckCast(v8::Value* obj);
4978 };
4979 
4980 #define V8_INTRINSICS_LIST(F)
4981  F(ArrayProto_entries, array_entries_iterator)
4982  F(ArrayProto_forEach, array_for_each_iterator)
4983  F(ArrayProto_keys, array_keys_iterator)
4984  F(ArrayProto_values, array_values_iterator)
4985  F(ErrorPrototype, initial_error_prototype)
4986  F(IteratorPrototype, initial_iterator_prototype)
4987 
4989 #define V8_DECL_INTRINSIC(name, iname) k##name,
4991 #undef V8_DECL_INTRINSIC
4992 };
4993 
4994 
4995 // --- Templates ---
4996 
4997 
4998 /**
4999  * The superclass of object and function templates.
5000  */
5001 class V8_EXPORT Template : public Data {
5002  public:
5003  /**
5004  * Adds a property to each instance created by this template.
5005  *
5006  * The property must be defined either as a primitive value, or a template.
5007  */
5008  void Set(Local<Name> name, Local<Data> value,
5009  PropertyAttribute attributes = None);
5010  void SetPrivate(Local<Private> name, Local<Data> value,
5011  PropertyAttribute attributes = None);
5012  V8_INLINE void Set(Isolate* isolate, const char* name, Local<Data> value);
5013 
5015  Local<Name> name,
5018  PropertyAttribute attribute = None,
5019  AccessControl settings = DEFAULT);
5020 
5021  /**
5022  * Whenever the property with the given name is accessed on objects
5023  * created from this Template the getter and setter callbacks
5024  * are called instead of getting and setting the property directly
5025  * on the JavaScript object.
5026  *
5027  * \param name The name of the property for which an accessor is added.
5028  * \param getter The callback to invoke when getting the property.
5029  * \param setter The callback to invoke when setting the property.
5030  * \param data A piece of data that will be passed to the getter and setter
5031  * callbacks whenever they are invoked.
5032  * \param settings Access control settings for the accessor. This is a bit
5033  * field consisting of one of more of
5034  * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
5035  * The default is to not allow cross-context access.
5036  * ALL_CAN_READ means that all cross-context reads are allowed.
5037  * ALL_CAN_WRITE means that all cross-context writes are allowed.
5038  * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
5039  * cross-context access.
5040  * \param attribute The attributes of the property for which an accessor
5041  * is added.
5042  * \param signature The signature describes valid receivers for the accessor
5043  * and is used to perform implicit instance checks against them. If the
5044  * receiver is incompatible (i.e. is not an instance of the constructor as
5045  * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
5046  * thrown and no callback is invoked.
5047  */
5049  Local<String> name, AccessorGetterCallback getter,
5050  AccessorSetterCallback setter = 0,
5051  // TODO(dcarney): gcc can't handle Local below
5052  Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
5054  AccessControl settings = DEFAULT);
5056  Local<Name> name, AccessorNameGetterCallback getter,
5057  AccessorNameSetterCallback setter = 0,
5058  // TODO(dcarney): gcc can't handle Local below
5059  Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
5061  AccessControl settings = DEFAULT);
5062 
5063  /**
5064  * Like SetNativeDataProperty, but V8 will replace the native data property
5065  * with a real data property on first access.
5066  */
5068  Local<Value> data = Local<Value>(),
5069  PropertyAttribute attribute = None);
5070 
5071  /**
5072  * During template instantiation, sets the value with the intrinsic property
5073  * from the correct context.
5074  */
5076  PropertyAttribute attribute = None);
5077 
5078  private:
5079  Template();
5080 
5081  friend class ObjectTemplate;
5082  friend class FunctionTemplate;
5083 };
5084 
5085 
5086 /**
5087  * NamedProperty[Getter|Setter] are used as interceptors on object.
5088  * See ObjectTemplate::SetNamedPropertyHandler.
5089  */
5091  Local<String> property,
5092  const PropertyCallbackInfo<Value>& info);
5093 
5094 
5095 /**
5096  * Returns the value if the setter intercepts the request.
5097  * Otherwise, returns an empty handle.
5098  */
5100  Local<String> property,
5101  Local<Value> value,
5102  const PropertyCallbackInfo<Value>& info);
5103 
5104 
5105 /**
5106  * Returns a non-empty handle if the interceptor intercepts the request.
5107  * The result is an integer encoding property attributes (like v8::None,
5108  * v8::DontEnum, etc.)
5109  */
5111  Local<String> property,
5112  const PropertyCallbackInfo<Integer>& info);
5113 
5114 
5115 /**
5116  * Returns a non-empty handle if the deleter intercepts the request.
5117  * The return value is true if the property could be deleted and false
5118  * otherwise.
5119  */
5121  Local<String> property,
5122  const PropertyCallbackInfo<Boolean>& info);
5123 
5124 /**
5125  * Returns an array containing the names of the properties the named
5126  * property getter intercepts.
5127  */
5129  const PropertyCallbackInfo<Array>& info);
5130 
5131 
5132 // TODO(dcarney): Deprecate and remove previous typedefs, and replace
5133 // GenericNamedPropertyFooCallback with just NamedPropertyFooCallback.
5134 
5135 /**
5136  * Interceptor for get requests on an object.
5137  *
5138  * Use `info.GetReturnValue().Set()` to set the return value of the
5139  * intercepted get request.
5140  *
5141  * \param property The name of the property for which the request was
5142  * intercepted.
5143  * \param info Information about the intercepted request, such as
5144  * isolate, receiver, return value, or whether running in `'use strict`' mode.
5145  * See `PropertyCallbackInfo`.
5146  *
5147  * \code
5148  * void GetterCallback(
5149  * Local<Name> name,
5150  * const v8::PropertyCallbackInfo<v8::Value>& info) {
5151  * info.GetReturnValue().Set(v8_num(42));
5152  * }
5153  *
5154  * v8::Local<v8::FunctionTemplate> templ =
5155  * v8::FunctionTemplate::New(isolate);
5156  * templ->InstanceTemplate()->SetHandler(
5157  * v8::NamedPropertyHandlerConfiguration(GetterCallback));
5158  * LocalContext env;
5159  * env->Global()
5160  * ->Set(env.local(), v8_str("obj"), templ->GetFunction(env.local())
5161  * .ToLocalChecked()
5162  * ->NewInstance(env.local())
5163  * .ToLocalChecked())
5164  * .FromJust();
5165  * v8::Local<v8::Value> result = CompileRun("obj.a = 17; obj.a");
5166  * CHECK(v8_num(42)->Equals(env.local(), result).FromJust());
5167  * \endcode
5168  *
5169  * See also `ObjectTemplate::SetHandler`.
5170  */
5172  Local<Name> property, const PropertyCallbackInfo<Value>& info);
5173 
5174 /**
5175  * Interceptor for set requests on an object.
5176  *
5177  * Use `info.GetReturnValue()` to indicate whether the request was intercepted
5178  * or not. If the setter successfully intercepts the request, i.e., if the
5179  * request should not be further executed, call
5180  * `info.GetReturnValue().Set(value)`. If the setter
5181  * did not intercept the request, i.e., if the request should be handled as
5182  * if no interceptor is present, do not not call `Set()`.
5183  *
5184  * \param property The name of the property for which the request was
5185  * intercepted.
5186  * \param value The value which the property will have if the request
5187  * is not intercepted.
5188  * \param info Information about the intercepted request, such as
5189  * isolate, receiver, return value, or whether running in `'use strict'` mode.
5190  * See `PropertyCallbackInfo`.
5191  *
5192  * See also
5193  * `ObjectTemplate::SetHandler.`
5194  */
5196  Local<Name> property, Local<Value> value,
5197  const PropertyCallbackInfo<Value>& info);
5198 
5199 /**
5200  * Intercepts all requests that query the attributes of the
5201  * property, e.g., getOwnPropertyDescriptor(), propertyIsEnumerable(), and
5202  * defineProperty().
5203  *
5204  * Use `info.GetReturnValue().Set(value)` to set the property attributes. The
5205  * value is an interger encoding a `v8::PropertyAttribute`.
5206  *
5207  * \param property The name of the property for which the request was
5208  * intercepted.
5209  * \param info Information about the intercepted request, such as
5210  * isolate, receiver, return value, or whether running in `'use strict'` mode.
5211  * See `PropertyCallbackInfo`.
5212  *
5213  * \note Some functions query the property attributes internally, even though
5214  * they do not return the attributes. For example, `hasOwnProperty()` can
5215  * trigger this interceptor depending on the state of the object.
5216  *
5217  * See also
5218  * `ObjectTemplate::SetHandler.`
5219  */
5221  Local<Name> property, const PropertyCallbackInfo<Integer>& info);
5222 
5223 /**
5224  * Interceptor for delete requests on an object.
5225  *
5226  * Use `info.GetReturnValue()` to indicate whether the request was intercepted
5227  * or not. If the deleter successfully intercepts the request, i.e., if the
5228  * request should not be further executed, call
5229  * `info.GetReturnValue().Set(value)` with a boolean `value`. The `value` is
5230  * used as the return value of `delete`.
5231  *
5232  * \param property The name of the property for which the request was
5233  * intercepted.
5234  * \param info Information about the intercepted request, such as
5235  * isolate, receiver, return value, or whether running in `'use strict'` mode.
5236  * See `PropertyCallbackInfo`.
5237  *
5238  * \note If you need to mimic the behavior of `delete`, i.e., throw in strict
5239  * mode instead of returning false, use `info.ShouldThrowOnError()` to determine
5240  * if you are in strict mode.
5241  *
5242  * See also `ObjectTemplate::SetHandler.`
5243  */
5245  Local<Name> property, const PropertyCallbackInfo<Boolean>& info);
5246 
5247 /**
5248  * Returns an array containing the names of the properties the named
5249  * property getter intercepts.
5250  */
5252  const PropertyCallbackInfo<Array>& info);
5253 
5254 /**
5255  * Interceptor for defineProperty requests on an object.
5256  *
5257  * Use `info.GetReturnValue()` to indicate whether the request was intercepted
5258  * or not. If the definer successfully intercepts the request, i.e., if the
5259  * request should not be further executed, call
5260  * `info.GetReturnValue().Set(value)`. If the definer
5261  * did not intercept the request, i.e., if the request should be handled as
5262  * if no interceptor is present, do not not call `Set()`.
5263  *
5264  * \param property The name of the property for which the request was
5265  * intercepted.
5266  * \param desc The property descriptor which is used to define the
5267  * property if the request is not intercepted.
5268  * \param info Information about the intercepted request, such as
5269  * isolate, receiver, return value, or whether running in `'use strict'` mode.
5270  * See `PropertyCallbackInfo`.
5271  *
5272  * See also `ObjectTemplate::SetHandler`.
5273  */
5275  Local<Name> property, const PropertyDescriptor& desc,
5276  const PropertyCallbackInfo<Value>& info);
5277 
5278 /**
5279  * Interceptor for getOwnPropertyDescriptor requests on an object.
5280  *
5281  * Use `info.GetReturnValue().Set()` to set the return value of the
5282  * intercepted request. The return value must be an object that
5283  * can be converted to a PropertyDescriptor, e.g., a `v8::value` returned from
5284  * `v8::Object::getOwnPropertyDescriptor`.
5285  *
5286  * \param property The name of the property for which the request was
5287  * intercepted.
5288  * \info Information about the intercepted request, such as
5289  * isolate, receiver, return value, or whether running in `'use strict'` mode.
5290  * See `PropertyCallbackInfo`.
5291  *
5292  * \note If GetOwnPropertyDescriptor is intercepted, it will
5293  * always return true, i.e., indicate that the property was found.
5294  *
5295  * See also `ObjectTemplate::SetHandler`.
5296  */
5298  Local<Name> property, const PropertyCallbackInfo<Value>& info);
5299 
5300 /**
5301  * See `v8::GenericNamedPropertyGetterCallback`.
5302  */
5304  uint32_t index,
5305  const PropertyCallbackInfo<Value>& info);
5306 
5307 /**
5308  * See `v8::GenericNamedPropertySetterCallback`.
5309  */
5311  uint32_t index,
5312  Local<Value> value,
5313  const PropertyCallbackInfo<Value>& info);
5314 
5315 /**
5316  * See `v8::GenericNamedPropertyQueryCallback`.
5317  */
5319  uint32_t index,
5320  const PropertyCallbackInfo<Integer>& info);
5321 
5322 /**
5323  * See `v8::GenericNamedPropertyDeleterCallback`.
5324  */
5326  uint32_t index,
5327  const PropertyCallbackInfo<Boolean>& info);
5328 
5329 /**
5330  * See `v8::GenericNamedPropertyEnumeratorCallback`.
5331  */
5333  const PropertyCallbackInfo<Array>& info);
5334 
5335 /**
5336  * See `v8::GenericNamedPropertyDefinerCallback`.
5337  */
5339  uint32_t index, const PropertyDescriptor& desc,
5340  const PropertyCallbackInfo<Value>& info);
5341 
5342 /**
5343  * See `v8::GenericNamedPropertyDescriptorCallback`.
5344  */
5346  uint32_t index, const PropertyCallbackInfo<Value>& info);
5347 
5348 /**
5349  * Access type specification.
5350  */
5356  ACCESS_KEYS
5357 };
5358 
5359 
5360 /**
5361  * Returns true if the given context should be allowed to access the given
5362  * object.
5363  */
5364 typedef bool (*AccessCheckCallback)(Local<Context> accessing_context,
5365  Local<Object> accessed_object,
5366  Local<Value> data);
5367 
5368 /**
5369  * A FunctionTemplate is used to create functions at runtime. There
5370  * can only be one function created from a FunctionTemplate in a
5371  * context. The lifetime of the created function is equal to the
5372  * lifetime of the context. So in case the embedder needs to create
5373  * temporary functions that can be collected using Scripts is
5374  * preferred.
5375  *
5376  * Any modification of a FunctionTemplate after first instantiation will trigger
5377  * a crash.
5378  *
5379  * A FunctionTemplate can have properties, these properties are added to the
5380  * function object when it is created.
5381  *
5382  * A FunctionTemplate has a corresponding instance template which is
5383  * used to create object instances when the function is used as a
5384  * constructor. Properties added to the instance template are added to
5385  * each object instance.
5386  *
5387  * A FunctionTemplate can have a prototype template. The prototype template
5388  * is used to create the prototype object of the function.
5389  *
5390  * The following example shows how to use a FunctionTemplate:
5391  *
5392  * \code
5393  * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(isolate);
5394  * t->Set(isolate, "func_property", v8::Number::New(isolate, 1));
5395  *
5396  * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
5397  * proto_t->Set(isolate,
5398  * "proto_method",
5399  * v8::FunctionTemplate::New(isolate, InvokeCallback));
5400  * proto_t->Set(isolate, "proto_const", v8::Number::New(isolate, 2));
5401  *
5402  * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
5403  * instance_t->SetAccessor(String::NewFromUtf8(isolate, "instance_accessor"),
5404  * InstanceAccessorCallback);
5405  * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback);
5406  * instance_t->Set(String::NewFromUtf8(isolate, "instance_property"),
5407  * Number::New(isolate, 3));
5408  *
5409  * v8::Local<v8::Function> function = t->GetFunction();
5410  * v8::Local<v8::Object> instance = function->NewInstance();
5411  * \endcode
5412  *
5413  * Let's use "function" as the JS variable name of the function object
5414  * and "instance" for the instance object created above. The function
5415  * and the instance will have the following properties:
5416  *
5417  * \code
5418  * func_property in function == true;
5419  * function.func_property == 1;
5420  *
5421  * function.prototype.proto_method() invokes 'InvokeCallback'
5422  * function.prototype.proto_const == 2;
5423  *
5424  * instance instanceof function == true;
5425  * instance.instance_accessor calls 'InstanceAccessorCallback'
5426  * instance.instance_property == 3;
5427  * \endcode
5428  *
5429  * A FunctionTemplate can inherit from another one by calling the
5430  * FunctionTemplate::Inherit method. The following graph illustrates
5431  * the semantics of inheritance:
5432  *
5433  * \code
5434  * FunctionTemplate Parent -> Parent() . prototype -> { }
5435  * ^ ^
5436  * | Inherit(Parent) | .__proto__
5437  * | |
5438  * FunctionTemplate Child -> Child() . prototype -> { }
5439  * \endcode
5440  *
5441  * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
5442  * object of the Child() function has __proto__ pointing to the
5443  * Parent() function's prototype object. An instance of the Child
5444  * function has all properties on Parent's instance templates.
5445  *
5446  * Let Parent be the FunctionTemplate initialized in the previous
5447  * section and create a Child FunctionTemplate by:
5448  *
5449  * \code
5450  * Local<FunctionTemplate> parent = t;
5451  * Local<FunctionTemplate> child = FunctionTemplate::New();
5452  * child->Inherit(parent);
5453  *
5454  * Local<Function> child_function = child->GetFunction();
5455  * Local<Object> child_instance = child_function->NewInstance();
5456  * \endcode
5457  *
5458  * The Child function and Child instance will have the following
5459  * properties:
5460  *
5461  * \code
5462  * child_func.prototype.__proto__ == function.prototype;
5463  * child_instance.instance_accessor calls 'InstanceAccessorCallback'
5464  * child_instance.instance_property == 3;
5465  * \endcode
5466  */
5468  public:
5469  /** Creates a function template.*/
5471  Isolate* isolate, FunctionCallback callback = 0,
5472  Local<Value> data = Local<Value>(),
5473  Local<Signature> signature = Local<Signature>(), int length = 0,
5475 
5476  /** Get a template included in the snapshot by index. */
5478  size_t index);
5479 
5480  /**
5481  * Creates a function template backed/cached by a private property.
5482  */
5484  Isolate* isolate, FunctionCallback callback,
5485  Local<Private> cache_property, Local<Value> data = Local<Value>(),
5486  Local<Signature> signature = Local<Signature>(), int length = 0);
5487 
5488  /** Returns the unique function instance in the current execution context.*/
5489  V8_DEPRECATE_SOON("Use maybe version", Local<Function> GetFunction());
5491  Local<Context> context);
5492 
5493  /**
5494  * Similar to Context::NewRemoteContext, this creates an instance that
5495  * isn't backed by an actual object.
5496  *
5497  * The InstanceTemplate of this FunctionTemplate must have access checks with
5498  * handlers installed.
5499  */
5501 
5502  /**
5503  * Set the call-handler callback for a FunctionTemplate. This
5504  * callback is called whenever the function created from this
5505  * FunctionTemplate is called.
5506  */
5508  Local<Value> data = Local<Value>());
5509 
5510  /** Set the predefined length property for the FunctionTemplate. */
5511  void SetLength(int length);
5512 
5513  /** Get the InstanceTemplate. */
5515 
5516  /**
5517  * Causes the function template to inherit from a parent function template.
5518  * This means the the function's prototype.__proto__ is set to the parent
5519  * function's prototype.
5520  **/
5522 
5523  /**
5524  * A PrototypeTemplate is the template used to create the prototype object
5525  * of the function created by this template.
5526  */
5528 
5529  /**
5530  * A PrototypeProviderTemplate is another function template whose prototype
5531  * property is used for this template. This is mutually exclusive with setting
5532  * a prototype template indirectly by calling PrototypeTemplate() or using
5533  * Inherit().
5534  **/
5536 
5537  /**
5538  * Set the class name of the FunctionTemplate. This is used for
5539  * printing objects created with the function created from the
5540  * FunctionTemplate as its constructor.
5541  */
5543 
5544 
5545  /**
5546  * When set to true, no access check will be performed on the receiver of a
5547  * function call. Currently defaults to true, but this is subject to change.
5548  */
5549  void SetAcceptAnyReceiver(bool value);
5550 
5551  /**
5552  * Determines whether the __proto__ accessor ignores instances of
5553  * the function template. If instances of the function template are
5554  * ignored, __proto__ skips all instances and instead returns the
5555  * next object in the prototype chain.
5556  *
5557  * Call with a value of true to make the __proto__ accessor ignore
5558  * instances of the function template. Call with a value of false
5559  * to make the __proto__ accessor not ignore instances of the
5560  * function template. By default, instances of a function template
5561  * are not ignored.
5562  */
5563  void SetHiddenPrototype(bool value);
5564 
5565  /**
5566  * Sets the ReadOnly flag in the attributes of the 'prototype' property
5567  * of functions created from this FunctionTemplate to true.
5568  */
5570 
5571  /**
5572  * Removes the prototype property from functions created from this
5573  * FunctionTemplate.
5574  */
5576 
5577  /**
5578  * Returns true if the given object is an instance of this function
5579  * template.
5580  */
5581  bool HasInstance(Local<Value> object);
5582 
5583  private:
5584  FunctionTemplate();
5585  friend class Context;
5586  friend class ObjectTemplate;
5587 };
5588 
5589 /**
5590  * Configuration flags for v8::NamedPropertyHandlerConfiguration or
5591  * v8::IndexedPropertyHandlerConfiguration.
5592  */
5594  /**
5595  * None.
5596  */
5597  kNone = 0,
5598 
5599  /**
5600  * See ALL_CAN_READ above.
5601  */
5602  kAllCanRead = 1,
5603 
5604  /** Will not call into interceptor for properties on the receiver or prototype
5605  * chain, i.e., only call into interceptor for properties that do not exist.
5606  * Currently only valid for named interceptors.
5607  */
5608  kNonMasking = 1 << 1,
5609 
5610  /**
5611  * Will not call into interceptor for symbol lookup. Only meaningful for
5612  * named interceptors.
5613  */
5614  kOnlyInterceptStrings = 1 << 2,
5615 };
5616 
5619  /** Note: getter is required */
5625  Local<Value> data = Local<Value>(),
5627  : getter(getter),
5628  setter(setter),
5629  query(query),
5630  deleter(deleter),
5631  enumerator(enumerator),
5632  definer(0),
5633  descriptor(0),
5634  data(data),
5635  flags(flags) {}
5636 
5644  Local<Value> data = Local<Value>(),
5646  : getter(getter),
5647  setter(setter),
5648  query(0),
5649  deleter(deleter),
5650  enumerator(enumerator),
5651  definer(definer),
5652  descriptor(descriptor),
5653  data(data),
5654  flags(flags) {}
5655 
5665 };
5666 
5667 
5670  /** Note: getter is required */
5671  IndexedPropertyGetterCallback getter = 0,
5672  IndexedPropertySetterCallback setter = 0,
5673  IndexedPropertyQueryCallback query = 0,
5674  IndexedPropertyDeleterCallback deleter = 0,
5675  IndexedPropertyEnumeratorCallback enumerator = 0,
5676  Local<Value> data = Local<Value>(),
5678  : getter(getter),
5679  setter(setter),
5680  query(query),
5681  deleter(deleter),
5682  enumerator(enumerator),
5683  definer(0),
5684  descriptor(0),
5685  data(data),
5686  flags(flags) {}
5687 
5695  Local<Value> data = Local<Value>(),
5697  : getter(getter),
5698  setter(setter),
5699  query(0),
5700  deleter(deleter),
5701  enumerator(enumerator),
5702  definer(definer),
5703  descriptor(descriptor),
5704  data(data),
5705  flags(flags) {}
5706 
5716 };
5717 
5718 
5719 /**
5720  * An ObjectTemplate is used to create objects at runtime.
5721  *
5722  * Properties added to an ObjectTemplate are added to each object
5723  * created from the ObjectTemplate.
5724  */
5726  public:
5727  /** Creates an ObjectTemplate. */
5729  Isolate* isolate,
5731  static V8_DEPRECATED("Use isolate version", Local<ObjectTemplate> New());
5732 
5733  /** Get a template included in the snapshot by index. */
5735  size_t index);
5736 
5737  /** Creates a new instance of this template.*/
5738  V8_DEPRECATE_SOON("Use maybe version", Local<Object> NewInstance());
5740 
5741  /**
5742  * Sets an accessor on the object template.
5743  *
5744  * Whenever the property with the given name is accessed on objects
5745  * created from this ObjectTemplate the getter and setter callbacks
5746  * are called instead of getting and setting the property directly
5747  * on the JavaScript object.
5748  *
5749  * \param name The name of the property for which an accessor is added.
5750  * \param getter The callback to invoke when getting the property.
5751  * \param setter The callback to invoke when setting the property.
5752  * \param data A piece of data that will be passed to the getter and setter
5753  * callbacks whenever they are invoked.
5754  * \param settings Access control settings for the accessor. This is a bit
5755  * field consisting of one of more of
5756  * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
5757  * The default is to not allow cross-context access.
5758  * ALL_CAN_READ means that all cross-context reads are allowed.
5759  * ALL_CAN_WRITE means that all cross-context writes are allowed.
5760  * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
5761  * cross-context access.
5762  * \param attribute The attributes of the property for which an accessor
5763  * is added.
5764  * \param signature The signature describes valid receivers for the accessor
5765  * and is used to perform implicit instance checks against them. If the
5766  * receiver is incompatible (i.e. is not an instance of the constructor as
5767  * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
5768  * thrown and no callback is invoked.
5769  */
5771  Local<String> name, AccessorGetterCallback getter,
5772  AccessorSetterCallback setter = 0, Local<Value> data = Local<Value>(),
5773  AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
5776  Local<Name> name, AccessorNameGetterCallback getter,
5778  AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
5780 
5781  /**
5782  * Sets a named property handler on the object template.
5783  *
5784  * Whenever a property whose name is a string is accessed on objects created
5785  * from this object template, the provided callback is invoked instead of
5786  * accessing the property directly on the JavaScript object.
5787  *
5788  * SetNamedPropertyHandler() is different from SetHandler(), in
5789  * that the latter can intercept symbol-named properties as well as
5790  * string-named properties when called with a
5791  * NamedPropertyHandlerConfiguration. New code should use SetHandler().
5792  *
5793  * \param getter The callback to invoke when getting a property.
5794  * \param setter The callback to invoke when setting a property.
5795  * \param query The callback to invoke to check if a property is present,
5796  * and if present, get its attributes.
5797  * \param deleter The callback to invoke when deleting a property.
5798  * \param enumerator The callback to invoke to enumerate all the named
5799  * properties of an object.
5800  * \param data A piece of data that will be passed to the callbacks
5801  * whenever they are invoked.
5802  */
5803  // TODO(dcarney): deprecate
5805  NamedPropertySetterCallback setter = 0,
5806  NamedPropertyQueryCallback query = 0,
5807  NamedPropertyDeleterCallback deleter = 0,
5808  NamedPropertyEnumeratorCallback enumerator = 0,
5809  Local<Value> data = Local<Value>());
5810 
5811  /**
5812  * Sets a named property handler on the object template.
5813  *
5814  * Whenever a property whose name is a string or a symbol is accessed on
5815  * objects created from this object template, the provided callback is
5816  * invoked instead of accessing the property directly on the JavaScript
5817  * object.
5818  *
5819  * @param configuration The NamedPropertyHandlerConfiguration that defines the
5820  * callbacks to invoke when accessing a property.
5821  */
5822  void SetHandler(const NamedPropertyHandlerConfiguration& configuration);
5823 
5824  /**
5825  * Sets an indexed property handler on the object template.
5826  *
5827  * Whenever an indexed property is accessed on objects created from
5828  * this object template, the provided callback is invoked instead of
5829  * accessing the property directly on the JavaScript object.
5830  *
5831  * \param getter The callback to invoke when getting a property.
5832  * \param setter The callback to invoke when setting a property.
5833  * \param query The callback to invoke to check if an object has a property.
5834  * \param deleter The callback to invoke when deleting a property.
5835  * \param enumerator The callback to invoke to enumerate all the indexed
5836  * properties of an object.
5837  * \param data A piece of data that will be passed to the callbacks
5838  * whenever they are invoked.
5839  */
5840  // TODO(dcarney): deprecate
5843  IndexedPropertySetterCallback setter = 0,
5844  IndexedPropertyQueryCallback query = 0,
5845  IndexedPropertyDeleterCallback deleter = 0,
5846  IndexedPropertyEnumeratorCallback enumerator = 0,
5847  Local<Value> data = Local<Value>()) {
5849  deleter, enumerator, data));
5850  }
5851 
5852  /**
5853  * Sets an indexed property handler on the object template.
5854  *
5855  * Whenever an indexed property is accessed on objects created from
5856  * this object template, the provided callback is invoked instead of
5857  * accessing the property directly on the JavaScript object.
5858  *
5859  * @param configuration The IndexedPropertyHandlerConfiguration that defines
5860  * the callbacks to invoke when accessing a property.
5861  */
5863 
5864  /**
5865  * Sets the callback to be used when calling instances created from
5866  * this template as a function. If no callback is set, instances
5867  * behave like normal JavaScript objects that cannot be called as a
5868  * function.
5869  */
5871  Local<Value> data = Local<Value>());
5872 
5873  /**
5874  * Mark object instances of the template as undetectable.
5875  *
5876  * In many ways, undetectable objects behave as though they are not
5877  * there. They behave like 'undefined' in conditionals and when
5878  * printed. However, properties can be accessed and called as on
5879  * normal objects.
5880  */
5882 
5883  /**
5884  * Sets access check callback on the object template and enables access
5885  * checks.
5886  *
5887  * When accessing properties on instances of this object template,
5888  * the access check callback will be called to determine whether or
5889  * not to allow cross-context access to the properties.
5890  */
5892  Local<Value> data = Local<Value>());
5893 
5894  /**
5895  * Like SetAccessCheckCallback but invokes an interceptor on failed access
5896  * checks instead of looking up all-can-read properties. You can only use
5897  * either this method or SetAccessCheckCallback, but not both at the same
5898  * time.
5899  */
5901  AccessCheckCallback callback,
5902  const NamedPropertyHandlerConfiguration& named_handler,
5903  const IndexedPropertyHandlerConfiguration& indexed_handler,
5904  Local<Value> data = Local<Value>());
5905 
5906  /**
5907  * Gets the number of internal fields for objects generated from
5908  * this template.
5909  */
5911 
5912  /**
5913  * Sets the number of internal fields for objects generated from
5914  * this template.
5915  */
5916  void SetInternalFieldCount(int value);
5917 
5918  /**
5919  * Returns true if the object will be an immutable prototype exotic object.
5920  */
5922 
5923  /**
5924  * Makes the ObjectTempate for an immutable prototype exotic object, with an
5925  * immutable __proto__.
5926  */
5928 
5929  private:
5930  ObjectTemplate();
5931  static Local<ObjectTemplate> New(internal::Isolate* isolate,
5932  Local<FunctionTemplate> constructor);
5933  friend class FunctionTemplate;
5934 };
5935 
5936 /**
5937  * A Signature specifies which receiver is valid for a function.
5938  *
5939  * A receiver matches a given signature if the receiver (or any of its
5940  * hidden prototypes) was created from the signature's FunctionTemplate, or
5941  * from a FunctionTemplate that inherits directly or indirectly from the
5942  * signature's FunctionTemplate.
5943  */
5944 class V8_EXPORT Signature : public Data {
5945  public:
5947  Isolate* isolate,
5949 
5950  private:
5951  Signature();
5952 };
5953 
5954 
5955 /**
5956  * An AccessorSignature specifies which receivers are valid parameters
5957  * to an accessor callback.
5958  */
5960  public:
5962  Isolate* isolate,
5964 
5965  private:
5966  AccessorSignature();
5967 };
5968 
5969 
5970 // --- Extensions ---
5971 
5974  public:
5975  ExternalOneByteStringResourceImpl() : data_(0), length_(0) {}
5976  ExternalOneByteStringResourceImpl(const char* data, size_t length)
5977  : data_(data), length_(length) {}
5978  const char* data() const { return data_; }
5979  size_t length() const { return length_; }
5980 
5981  private:
5982  const char* data_;
5983  size_t length_;
5984 };
5985 
5986 /**
5987  * Ignore
5988  */
5989 class V8_EXPORT Extension { // NOLINT
5990  public:
5991  // Note that the strings passed into this constructor must live as long
5992  // as the Extension itself.
5993  Extension(const char* name,
5994  const char* source = 0,
5995  int dep_count = 0,
5996  const char** deps = 0,
5997  int source_length = -1);
5998  virtual ~Extension() { }
6000  Isolate* isolate, Local<String> name) {
6002  }
6003 
6004  const char* name() const { return name_; }
6005  size_t source_length() const { return source_length_; }
6007  return &source_; }
6008  int dependency_count() { return dep_count_; }
6009  const char** dependencies() { return deps_; }
6010  void set_auto_enable(bool value) { auto_enable_ = value; }
6011  bool auto_enable() { return auto_enable_; }
6012 
6013  // Disallow copying and assigning.
6014  Extension(const Extension&) = delete;
6015  void operator=(const Extension&) = delete;
6016 
6017  private:
6018  const char* name_;
6019  size_t source_length_; // expected to initialize before source_
6021  int dep_count_;
6022  const char** deps_;
6023  bool auto_enable_;
6024 };
6025 
6026 
6028 
6029 
6030 // --- Statics ---
6031 
6033 V8_INLINE Local<Primitive> Null(Isolate* isolate);
6034 V8_INLINE Local<Boolean> True(Isolate* isolate);
6035 V8_INLINE Local<Boolean> False(Isolate* isolate);
6036 
6037 /**
6038  * A set of constraints that specifies the limits of the runtime's memory use.
6039  * You must set the heap size before initializing the VM - the size cannot be
6040  * adjusted after the VM is initialized.
6041  *
6042  * If you are using threads then you should hold the V8::Locker lock while
6043  * setting the stack limit and you must set a non-default stack limit separately
6044  * for each thread.
6045  *
6046  * The arguments for set_max_semi_space_size, set_max_old_space_size,
6047  * set_max_executable_size, set_code_range_size specify limits in MB.
6048  *
6049  * The argument for set_max_semi_space_size_in_kb is in KB.
6050  */
6052  public:
6054 
6055  /**
6056  * Configures the constraints with reasonable default values based on the
6057  * capabilities of the current device the VM is running on.
6058  *
6059  * \param physical_memory The total amount of physical memory on the current
6060  * device, in bytes.
6061  * \param virtual_memory_limit The amount of virtual memory on the current
6062  * device, in bytes, or zero, if there is no limit.
6063  */
6064  void ConfigureDefaults(uint64_t physical_memory,
6065  uint64_t virtual_memory_limit);
6066 
6067  // Returns the max semi-space size in MB.
6068  V8_DEPRECATE_SOON("Use max_semi_space_size_in_kb()",
6069  int max_semi_space_size()) {
6070  return static_cast<int>(max_semi_space_size_in_kb_ / 1024);
6071  }
6072 
6073  // Sets the max semi-space size in MB.
6074  V8_DEPRECATE_SOON("Use set_max_semi_space_size_in_kb(size_t limit_in_kb)",
6075  void set_max_semi_space_size(int limit_in_mb)) {
6076  max_semi_space_size_in_kb_ = limit_in_mb * 1024;
6077  }
6078 
6079  // Returns the max semi-space size in KB.
6080  size_t max_semi_space_size_in_kb() const {
6081  return max_semi_space_size_in_kb_;
6082  }
6083 
6084  // Sets the max semi-space size in KB.
6085  void set_max_semi_space_size_in_kb(size_t limit_in_kb) {
6086  max_semi_space_size_in_kb_ = limit_in_kb;
6087  }
6088 
6089  int max_old_space_size() const { return max_old_space_size_; }
6090  void set_max_old_space_size(int limit_in_mb) {
6091  max_old_space_size_ = limit_in_mb;
6092  }
6093  V8_DEPRECATE_SOON("max_executable_size_ is subsumed by max_old_space_size_",
6094  int max_executable_size() const) {
6095  return max_executable_size_;
6096  }
6097  V8_DEPRECATE_SOON("max_executable_size_ is subsumed by max_old_space_size_",
6098  void set_max_executable_size(int limit_in_mb)) {
6099  max_executable_size_ = limit_in_mb;
6100  }
6101  uint32_t* stack_limit() const { return stack_limit_; }
6102  // Sets an address beyond which the VM's stack may not grow.
6103  void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
6104  size_t code_range_size() const { return code_range_size_; }
6105  void set_code_range_size(size_t limit_in_mb) {
6106  code_range_size_ = limit_in_mb;
6107  }
6108  size_t max_zone_pool_size() const { return max_zone_pool_size_; }
6109  void set_max_zone_pool_size(const size_t bytes) {
6110  max_zone_pool_size_ = bytes;
6111  }
6112 
6113  private:
6114  // max_semi_space_size_ is in KB
6115  size_t max_semi_space_size_in_kb_;
6116 
6117  // The remaining limits are in MB
6118  int max_old_space_size_;
6119  int max_executable_size_;
6120  uint32_t* stack_limit_;
6121  size_t code_range_size_;
6122  size_t max_zone_pool_size_;
6123 };
6124 
6125 
6126 // --- Exceptions ---
6127 
6128 
6129 typedef void (*FatalErrorCallback)(const char* location, const char* message);
6130 
6131 typedef void (*OOMErrorCallback)(const char* location, bool is_heap_oom);
6132 
6133 typedef void (*MessageCallback)(Local<Message> message, Local<Value> data);
6134 
6135 // --- Tracing ---
6136 
6137 typedef void (*LogEventCallback)(const char* name, int event);
6138 
6139 /**
6140  * Create new error objects by calling the corresponding error object
6141  * constructor with the message.
6142  */
6144  public:
6145  static Local<Value> RangeError(Local<String> message);
6147  static Local<Value> SyntaxError(Local<String> message);
6148  static Local<Value> TypeError(Local<String> message);
6149  static Local<Value> Error(Local<String> message);
6150 
6151  /**
6152  * Creates an error message for the given exception.
6153  * Will try to reconstruct the original stack trace from the exception value,
6154  * or capture the current stack trace if not available.
6155  */
6156  static Local<Message> CreateMessage(Isolate* isolate, Local<Value> exception);
6157  V8_DEPRECATED("Use version with an Isolate*",
6158  static Local<Message> CreateMessage(Local<Value> exception));
6159 
6160  /**
6161  * Returns the original stack trace that was captured at the creation time
6162  * of a given exception, or an empty handle if not available.
6163  */
6165 };
6166 
6167 
6168 // --- Counters Callbacks ---
6169 
6170 typedef int* (*CounterLookupCallback)(const char* name);
6171 
6172 typedef void* (*CreateHistogramCallback)(const char* name,
6173  int min,
6174  int max,
6175  size_t buckets);
6176 
6177 typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
6178 
6179 // --- Memory Allocation Callback ---
6189 };
6190 
6195  };
6196 
6197 // --- Enter/Leave Script Callback ---
6199 typedef void (*CallCompletedCallback)(Isolate*);
6201 
6202 /**
6203  * HostImportDynamicallyCallback is called when we require the
6204  * embedder to load a module. This is used as part of the dynamic
6205  * import syntax.
6206  *
6207  * The referrer is the name of the file which calls the dynamic
6208  * import. The referrer can be used to resolve the module location.
6209  *
6210  * The specifier is the name of the module that should be imported.
6211  *
6212  * The embedder must compile, instantiate, evaluate the Module, and
6213  * obtain it's namespace object.
6214  *
6215  * The Promise returned from this function is forwarded to userland
6216  * JavaScript. The embedder must resolve this promise with the module
6217  * namespace object. In case of an exception, the embedder must reject
6218  * this promise with the exception. If the promise creation itself
6219  * fails (e.g. due to stack overflow), the embedder must propagate
6220  * that exception by returning an empty MaybeLocal.
6221  */
6223  Local<Context> context, Local<String> referrer, Local<String> specifier);
6224 
6225 /**
6226  * PromiseHook with type kInit is called when a new promise is
6227  * created. When a new promise is created as part of the chain in the
6228  * case of Promise.then or in the intermediate promises created by
6229  * Promise.{race, all}/AsyncFunctionAwait, we pass the parent promise
6230  * otherwise we pass undefined.
6231  *
6232  * PromiseHook with type kResolve is called at the beginning of
6233  * resolve or reject function defined by CreateResolvingFunctions.
6234  *
6235  * PromiseHook with type kBefore is called at the beginning of the
6236  * PromiseReactionJob.
6237  *
6238  * PromiseHook with type kAfter is called right at the end of the
6239  * PromiseReactionJob.
6240  */
6242 
6243 typedef void (*PromiseHook)(PromiseHookType type, Local<Promise> promise,
6244  Local<Value> parent);
6245 
6246 // --- Promise Reject Callback ---
6250 };
6251 
6253  public:
6255  Local<Value> value, Local<StackTrace> stack_trace)
6256  : promise_(promise),
6257  event_(event),
6258  value_(value),
6259  stack_trace_(stack_trace) {}
6260 
6261  V8_INLINE Local<Promise> GetPromise() const { return promise_; }
6262  V8_INLINE PromiseRejectEvent GetEvent() const { return event_; }
6263  V8_INLINE Local<Value> GetValue() const { return value_; }
6264 
6265  V8_DEPRECATED("Use v8::Exception::CreateMessage(GetValue())->GetStackTrace()",
6266  V8_INLINE Local<StackTrace> GetStackTrace() const) {
6267  return stack_trace_;
6268  }
6269 
6270  private:
6271  Local<Promise> promise_;
6272  PromiseRejectEvent event_;
6273  Local<Value> value_;
6274  Local<StackTrace> stack_trace_;
6275 };
6276 
6278 
6279 // --- Microtasks Callbacks ---
6281 typedef void (*MicrotaskCallback)(void* data);
6282 
6283 
6284 /**
6285  * Policy for running microtasks:
6286  * - explicit: microtasks are invoked with Isolate::RunMicrotasks() method;
6287  * - scoped: microtasks invocation is controlled by MicrotasksScope objects;
6288  * - auto: microtasks are invoked when the script call depth decrements
6289  * to zero.
6290  */
6292 
6293 
6294 /**
6295  * This scope is used to control microtasks when kScopeMicrotasksInvocation
6296  * is used on Isolate. In this mode every non-primitive call to V8 should be
6297  * done inside some MicrotasksScope.
6298  * Microtasks are executed when topmost MicrotasksScope marked as kRunMicrotasks
6299  * exits.
6300  * kDoNotRunMicrotasks should be used to annotate calls not intended to trigger
6301  * microtasks.
6302  */
6304  public:
6306 
6307  MicrotasksScope(Isolate* isolate, Type type);
6309 
6310  /**
6311  * Runs microtasks if no kRunMicrotasks scope is currently active.
6312  */
6313  static void PerformCheckpoint(Isolate* isolate);
6314 
6315  /**
6316  * Returns current depth of nested kRunMicrotasks scopes.
6317  */
6318  static int GetCurrentDepth(Isolate* isolate);
6319 
6320  /**
6321  * Returns true while microtasks are being executed.
6322  */
6323  static bool IsRunningMicrotasks(Isolate* isolate);
6324 
6325  // Prevent copying.
6328 
6329  private:
6330  internal::Isolate* const isolate_;
6331  bool run_;
6332 };
6333 
6334 
6335 // --- Failed Access Check Callback ---
6336 typedef void (*FailedAccessCheckCallback)(Local<Object> target,
6337  AccessType type,
6338  Local<Value> data);
6339 
6340 // --- AllowCodeGenerationFromStrings callbacks ---
6341 
6342 /**
6343  * Callback to check if code generation from strings is allowed. See
6344  * Context::AllowCodeGenerationFromStrings.
6345  */
6347  Local<String> source);
6348 
6349 // --- WebAssembly compilation callbacks ---
6351 
6352 // --- Callback for APIs defined on v8-supported objects, but implemented
6353 // by the embedder. Example: WebAssembly.{compile|instantiate}Streaming ---
6355 
6356 // --- Garbage Collection Callbacks ---
6357 
6358 /**
6359  * Applications can register callback functions which will be called before and
6360  * after certain garbage collection operations. Allocations are not allowed in
6361  * the callback functions, you therefore cannot manipulate objects (set or
6362  * delete properties for example) since it is possible such operations will
6363  * result in the allocation of objects.
6364  */
6365 enum GCType {
6372 };
6373 
6374 /**
6375  * GCCallbackFlags is used to notify additional information about the GC
6376  * callback.
6377  * - kGCCallbackFlagConstructRetainedObjectInfos: The GC callback is for
6378  * constructing retained object infos.
6379  * - kGCCallbackFlagForced: The GC callback is for a forced GC for testing.
6380  * - kGCCallbackFlagSynchronousPhantomCallbackProcessing: The GC callback
6381  * is called synchronously without getting posted to an idle task.
6382  * - kGCCallbackFlagCollectAllAvailableGarbage: The GC callback is called
6383  * in a phase where V8 is trying to collect all available garbage
6384  * (e.g., handling a low memory notification).
6385  * - kGCCallbackScheduleIdleGarbageCollection: The GC callback is called to
6386  * trigger an idle garbage collection.
6387  */
6396 };
6397 
6398 typedef void (*GCCallback)(GCType type, GCCallbackFlags flags);
6399 
6400 typedef void (*InterruptCallback)(Isolate* isolate, void* data);
6401 
6402 
6403 /**
6404  * Collection of V8 heap information.
6405  *
6406  * Instances of this class can be passed to v8::V8::HeapStatistics to
6407  * get heap statistics from V8.
6408  */
6410  public:
6412  size_t total_heap_size() { return total_heap_size_; }
6413  size_t total_heap_size_executable() { return total_heap_size_executable_; }
6414  size_t total_physical_size() { return total_physical_size_; }
6415  size_t total_available_size() { return total_available_size_; }
6416  size_t used_heap_size() { return used_heap_size_; }
6417  size_t heap_size_limit() { return heap_size_limit_; }
6418  size_t malloced_memory() { return malloced_memory_; }
6419  size_t peak_malloced_memory() { return peak_malloced_memory_; }
6420 
6421  /**
6422  * Returns a 0/1 boolean, which signifies whether the V8 overwrite heap
6423  * garbage with a bit pattern.
6424  */
6425  size_t does_zap_garbage() { return does_zap_garbage_; }
6426 
6427  private:
6428  size_t total_heap_size_;
6429  size_t total_heap_size_executable_;
6430  size_t total_physical_size_;
6431  size_t total_available_size_;
6432  size_t used_heap_size_;
6433  size_t heap_size_limit_;
6434  size_t malloced_memory_;
6435  size_t peak_malloced_memory_;
6436  bool does_zap_garbage_;
6437 
6438  friend class V8;
6439  friend class Isolate;
6440 };
6441 
6442 
6444  public:
6446  const char* space_name() { return space_name_; }
6447  size_t space_size() { return space_size_; }
6448  size_t space_used_size() { return space_used_size_; }
6449  size_t space_available_size() { return space_available_size_; }
6450  size_t physical_space_size() { return physical_space_size_; }
6451 
6452  private:
6453  const char* space_name_;
6454  size_t space_size_;
6455  size_t space_used_size_;
6456  size_t space_available_size_;
6457  size_t physical_space_size_;
6458 
6459  friend class Isolate;
6460 };
6461 
6462 
6464  public:
6466  const char* object_type() { return object_type_; }
6467  const char* object_sub_type() { return object_sub_type_; }
6468  size_t object_count() { return object_count_; }
6469  size_t object_size() { return object_size_; }
6470 
6471  private:
6472  const char* object_type_;
6473  const char* object_sub_type_;
6474  size_t object_count_;
6475  size_t object_size_;
6476 
6477  friend class Isolate;
6478 };
6479 
6481  public:
6483  size_t code_and_metadata_size() { return code_and_metadata_size_; }
6484  size_t bytecode_and_metadata_size() { return bytecode_and_metadata_size_; }
6485 
6486  private:
6487  size_t code_and_metadata_size_;
6488  size_t bytecode_and_metadata_size_;
6489 
6490  friend class Isolate;
6491 };
6492 
6493 class RetainedObjectInfo;
6494 
6495 
6496 /**
6497  * FunctionEntryHook is the type of the profile entry hook called at entry to
6498  * any generated function when function-level profiling is enabled.
6499  *
6500  * \param function the address of the function that's being entered.
6501  * \param return_addr_location points to a location on stack where the machine
6502  * return address resides. This can be used to identify the caller of
6503  * \p function, and/or modified to divert execution when \p function exits.
6504  *
6505  * \note the entry hook must not cause garbage collection.
6506  */
6507 typedef void (*FunctionEntryHook)(uintptr_t function,
6508  uintptr_t return_addr_location);
6509 
6510 /**
6511  * A JIT code event is issued each time code is added, moved or removed.
6512  *
6513  * \note removal events are not currently issued.
6514  */
6516  enum EventType {
6523  };
6524  // Definition of the code position type. The "POSITION" type means the place
6525  // in the source code which are of interest when making stack traces to
6526  // pin-point the source location of a stack frame as close as possible.
6527  // The "STATEMENT_POSITION" means the place at the beginning of each
6528  // statement, and is used to indicate possible break locations.
6530 
6531  // Type of event.
6533  // Start of the instructions.
6534  void* code_start;
6535  // Size of the instructions.
6536  size_t code_len;
6537  // Script info for CODE_ADDED event.
6539  // User-defined data for *_LINE_INFO_* event. It's used to hold the source
6540  // code line information which is returned from the
6541  // CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent
6542  // CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events.
6543  void* user_data;
6544 
6545  struct name_t {
6546  // Name of the object associated with the code, note that the string is not
6547  // zero-terminated.
6548  const char* str;
6549  // Number of chars in str.
6550  size_t len;
6551  };
6552 
6553  struct line_info_t {
6554  // PC offset
6555  size_t offset;
6556  // Code position
6557  size_t pos;
6558  // The position type.
6560  };
6561 
6562  union {
6563  // Only valid for CODE_ADDED.
6564  struct name_t name;
6565 
6566  // Only valid for CODE_ADD_LINE_POS_INFO
6567  struct line_info_t line_info;
6568 
6569  // New location of instructions. Only valid for CODE_MOVED.
6571  };
6572 };
6573 
6574 /**
6575  * Option flags passed to the SetRAILMode function.
6576  * See documentation https://developers.google.com/web/tools/chrome-devtools/
6577  * profile/evaluate-performance/rail
6578  */
6579 enum RAILMode {
6580  // Response performance mode: In this mode very low virtual machine latency
6581  // is provided. V8 will try to avoid JavaScript execution interruptions.
6582  // Throughput may be throttled.
6584  // Animation performance mode: In this mode low virtual machine latency is
6585  // provided. V8 will try to avoid as many JavaScript execution interruptions
6586  // as possible. Throughput may be throttled. This is the default mode.
6588  // Idle performance mode: The embedder is idle. V8 can complete deferred work
6589  // in this mode.
6591  // Load performance mode: In this mode high throughput is provided. V8 may
6592  // turn off latency optimizations.
6594 };
6595 
6596 /**
6597  * Option flags passed to the SetJitCodeEventHandler function.
6598  */
6601  // Generate callbacks for already existent code.
6603 };
6604 
6605 
6606 /**
6607  * Callback function passed to SetJitCodeEventHandler.
6608  *
6609  * \param event code add, move or removal event.
6610  */
6611 typedef void (*JitCodeEventHandler)(const JitCodeEvent* event);
6612 
6613 
6614 /**
6615  * Interface for iterating through all external resources in the heap.
6616  */
6618  public:
6620  virtual void VisitExternalString(Local<String> string) {}
6621 };
6622 
6623 
6624 /**
6625  * Interface for iterating through all the persistent handles in the heap.
6626  */
6628  public:
6631  uint16_t class_id) {}
6632 };
6633 
6634 /**
6635  * Memory pressure level for the MemoryPressureNotification.
6636  * kNone hints V8 that there is no memory pressure.
6637  * kModerate hints V8 to speed up incremental garbage collection at the cost of
6638  * of higher latency due to garbage collection pauses.
6639  * kCritical hints V8 to free memory as soon as possible. Garbage collection
6640  * pauses at this level will be large.
6641  */
6643 
6644 /**
6645  * Interface for tracing through the embedder heap. During a v8 garbage
6646  * collection, v8 collects hidden fields of all potential wrappers, and at the
6647  * end of its marking phase iterates the collection and asks the embedder to
6648  * trace through its heap and use reporter to report each JavaScript object
6649  * reachable from any of the given wrappers.
6650  *
6651  * Before the first call to the TraceWrappersFrom function TracePrologue will be
6652  * called. When the garbage collection cycle is finished, TraceEpilogue will be
6653  * called.
6654  */
6656  public:
6658 
6660  explicit AdvanceTracingActions(ForceCompletionAction force_completion_)
6661  : force_completion(force_completion_) {}
6662 
6664  };
6665 
6666  /**
6667  * Called by v8 to register internal fields of found wrappers.
6668  *
6669  * The embedder is expected to store them somewhere and trace reachable
6670  * wrappers from them when called through |AdvanceTracing|.
6671  */
6672  virtual void RegisterV8References(
6673  const std::vector<std::pair<void*, void*> >& embedder_fields) = 0;
6674 
6675  /**
6676  * Called at the beginning of a GC cycle.
6677  */
6678  virtual void TracePrologue() = 0;
6679 
6680  /**
6681  * Called to to make a tracing step in the embedder.
6682  *
6683  * The embedder is expected to trace its heap starting from wrappers reported
6684  * by RegisterV8References method, and report back all reachable wrappers.
6685  * Furthermore, the embedder is expected to stop tracing by the given
6686  * deadline.
6687  *
6688  * Returns true if there is still work to do.
6689  */
6690  virtual bool AdvanceTracing(double deadline_in_ms,
6691  AdvanceTracingActions actions) = 0;
6692 
6693  /**
6694  * Called at the end of a GC cycle.
6695  *
6696  * Note that allocation is *not* allowed within |TraceEpilogue|.
6697  */
6698  virtual void TraceEpilogue() = 0;
6699 
6700  /**
6701  * Called upon entering the final marking pause. No more incremental marking
6702  * steps will follow this call.
6703  */
6704  virtual void EnterFinalPause() = 0;
6705 
6706  /**
6707  * Called when tracing is aborted.
6708  *
6709  * The embedder is expected to throw away all intermediate data and reset to
6710  * the initial state.
6711  */
6712  virtual void AbortTracing() = 0;
6713 
6714  /**
6715  * Returns the number of wrappers that are still to be traced by the embedder.
6716  */
6717  virtual size_t NumberOfWrappersToTrace() { return 0; }
6718 
6719  protected:
6720  virtual ~EmbedderHeapTracer() = default;
6721 };
6722 
6723 /**
6724  * Callback and supporting data used in SnapshotCreator to implement embedder
6725  * logic to serialize internal fields.
6726  */
6728  typedef StartupData (*CallbackFunction)(Local<Object> holder, int index,
6729  void* data);
6730  SerializeInternalFieldsCallback(CallbackFunction function = nullptr,
6731  void* data_arg = nullptr)
6732  : callback(function), data(data_arg) {}
6733  CallbackFunction callback;
6734  void* data;
6735 };
6736 // Note that these fields are called "internal fields" in the API and called
6737 // "embedder fields" within V8.
6739 
6740 /**
6741  * Callback and supporting data used to implement embedder logic to deserialize
6742  * internal fields.
6743  */
6745  typedef void (*CallbackFunction)(Local<Object> holder, int index,
6746  StartupData payload, void* data);
6748  void* data_arg = nullptr)
6749  : callback(function), data(data_arg) {}
6750  void (*callback)(Local<Object> holder, int index, StartupData payload,
6751  void* data);
6752  void* data;
6753 };
6755 
6756 /**
6757  * Isolate represents an isolated instance of the V8 engine. V8 isolates have
6758  * completely separate states. Objects from one isolate must not be used in
6759  * other isolates. The embedder can create multiple isolates and use them in
6760  * parallel in multiple threads. An isolate can be entered by at most one
6761  * thread at any given time. The Locker/Unlocker API must be used to
6762  * synchronize.
6763  */
6765  public:
6766  /**
6767  * Initial configuration parameters for a new Isolate.
6768  */
6769  struct CreateParams {
6771  : entry_hook(nullptr),
6772  code_event_handler(nullptr),
6773  snapshot_blob(nullptr),
6774  counter_lookup_callback(nullptr),
6775  create_histogram_callback(nullptr),
6777  array_buffer_allocator(nullptr),
6778  external_references(nullptr),
6779  allow_atomics_wait(true) {}
6780 
6781  /**
6782  * The optional entry_hook allows the host application to provide the
6783  * address of a function that's invoked on entry to every V8-generated
6784  * function. Note that entry_hook is invoked at the very start of each
6785  * generated function.
6786  * An entry_hook can only be provided in no-snapshot builds; in snapshot
6787  * builds it must be nullptr.
6788  */
6790 
6791  /**
6792  * Allows the host application to provide the address of a function that is
6793  * notified each time code is added, moved or removed.
6794  */
6796 
6797  /**
6798  * ResourceConstraints to use for the new Isolate.
6799  */
6801 
6802  /**
6803  * Explicitly specify a startup snapshot blob. The embedder owns the blob.
6804  */
6806 
6807 
6808  /**
6809  * Enables the host application to provide a mechanism for recording
6810  * statistics counters.
6811  */
6813 
6814  /**
6815  * Enables the host application to provide a mechanism for recording
6816  * histograms. The CreateHistogram function returns a
6817  * histogram which will later be passed to the AddHistogramSample
6818  * function.
6819  */
6822 
6823  /**
6824  * The ArrayBuffer::Allocator to use for allocating and freeing the backing
6825  * store of ArrayBuffers.
6826  */
6828 
6829  /**
6830  * Specifies an optional nullptr-terminated array of raw addresses in the
6831  * embedder that V8 can match against during serialization and use for
6832  * deserialization. This array and its content must stay valid for the
6833  * entire lifetime of the isolate.
6834  */
6835  const intptr_t* external_references;
6836 
6837  /**
6838  * Whether calling Atomics.wait (a function that may block) is allowed in
6839  * this isolate. This can also be configured via SetAllowAtomicsWait.
6840  */
6842  };
6843 
6844 
6845  /**
6846  * Stack-allocated class which sets the isolate for all operations
6847  * executed within a local scope.
6848  */
6850  public:
6851  explicit Scope(Isolate* isolate) : isolate_(isolate) {
6852  isolate->Enter();
6853  }
6854 
6855  ~Scope() { isolate_->Exit(); }
6856 
6857  // Prevent copying of Scope objects.
6858  Scope(const Scope&) = delete;
6859  Scope& operator=(const Scope&) = delete;
6860 
6861  private:
6862  Isolate* const isolate_;
6863  };
6864 
6865 
6866  /**
6867  * Assert that no Javascript code is invoked.
6868  */
6870  public:
6872 
6875 
6876  // Prevent copying of Scope objects.
6878  delete;
6880  const DisallowJavascriptExecutionScope&) = delete;
6881 
6882  private:
6883  bool on_failure_;
6884  void* internal_;
6885  };
6886 
6887 
6888  /**
6889  * Introduce exception to DisallowJavascriptExecutionScope.
6890  */
6892  public:
6895 
6896  // Prevent copying of Scope objects.
6898  delete;
6900  const AllowJavascriptExecutionScope&) = delete;
6901 
6902  private:
6903  void* internal_throws_;
6904  void* internal_assert_;
6905  };
6906 
6907  /**
6908  * Do not run microtasks while this scope is active, even if microtasks are
6909  * automatically executed otherwise.
6910  */
6912  public:
6915 
6916  // Prevent copying of Scope objects.
6918  delete;
6920  const SuppressMicrotaskExecutionScope&) = delete;
6921 
6922  private:
6923  internal::Isolate* const isolate_;
6924  };
6925 
6926  /**
6927  * Types of garbage collections that can be requested via
6928  * RequestGarbageCollectionForTesting.
6929  */
6933  };
6934 
6935  /**
6936  * Features reported via the SetUseCounterCallback callback. Do not change
6937  * assigned numbers of existing items; add new features to the end of this
6938  * list.
6939  */
6941  kUseAsm = 0,
6982 
6983  // If you add new values here, you'll also need to update Chromium's:
6984  // UseCounter.h, V8PerIsolateData.cpp, histograms.xml
6985  kUseCounterFeatureCount // This enum value must be last.
6986  };
6987 
6989  kMessageLog = (1 << 0),
6990  kMessageDebug = (1 << 1),
6991  kMessageInfo = (1 << 2),
6992  kMessageError = (1 << 3),
6993  kMessageWarning = (1 << 4),
6996  };
6997 
6998  typedef void (*UseCounterCallback)(Isolate* isolate,
6999  UseCounterFeature feature);
7000 
7001 
7002  /**
7003  * Creates a new isolate. Does not change the currently entered
7004  * isolate.
7005  *
7006  * When an isolate is no longer used its resources should be freed
7007  * by calling Dispose(). Using the delete operator is not allowed.
7008  *
7009  * V8::Initialize() must have run prior to this.
7010  */
7011  static Isolate* New(const CreateParams& params);
7012 
7013  /**
7014  * Returns the entered isolate for the current thread or NULL in
7015  * case there is no current isolate.
7016  *
7017  * This method must not be invoked before V8::Initialize() was invoked.
7018  */
7019  static Isolate* GetCurrent();
7020 
7021  /**
7022  * Custom callback used by embedders to help V8 determine if it should abort
7023  * when it throws and no internal handler is predicted to catch the
7024  * exception. If --abort-on-uncaught-exception is used on the command line,
7025  * then V8 will abort if either:
7026  * - no custom callback is set.
7027  * - the custom callback set returns true.
7028  * Otherwise, the custom callback will not be called and V8 will not abort.
7029  */
7033 
7034  /**
7035  * This is an unfinished experimental feature, and is only exposed
7036  * here for internal testing purposes. DO NOT USE.
7037  *
7038  * This specifies the callback called by the upcoming dynamic
7039  * import() language feature to load modules.
7040  */
7043 
7044  /**
7045  * Optional notification that the system is running low on memory.
7046  * V8 uses these notifications to guide heuristics.
7047  * It is allowed to call this function from another thread while
7048  * the isolate is executing long running JavaScript code.
7049  */
7051 
7052  /**
7053  * Methods below this point require holding a lock (using Locker) in
7054  * a multi-threaded environment.
7055  */
7056 
7057  /**
7058  * Sets this isolate as the entered one for the current thread.
7059  * Saves the previously entered one (if any), so that it can be
7060  * restored when exiting. Re-entering an isolate is allowed.
7061  */
7062  void Enter();
7063 
7064  /**
7065  * Exits this isolate by restoring the previously entered one in the
7066  * current thread. The isolate may still stay the same, if it was
7067  * entered more than once.
7068  *
7069  * Requires: this == Isolate::GetCurrent().
7070  */
7071  void Exit();
7072 
7073  /**
7074  * Disposes the isolate. The isolate must not be entered by any
7075  * thread to be disposable.
7076  */
7077  void Dispose();
7078 
7079  /**
7080  * Dumps activated low-level V8 internal stats. This can be used instead
7081  * of performing a full isolate disposal.
7082  */
7084 
7085  /**
7086  * Discards all V8 thread-specific data for the Isolate. Should be used
7087  * if a thread is terminating and it has used an Isolate that will outlive
7088  * the thread -- all thread-specific data for an Isolate is discarded when
7089  * an Isolate is disposed so this call is pointless if an Isolate is about
7090  * to be Disposed.
7091  */
7093 
7094  /**
7095  * Associate embedder-specific data with the isolate. |slot| has to be
7096  * between 0 and GetNumberOfDataSlots() - 1.
7097  */
7098  V8_INLINE void SetData(uint32_t slot, void* data);
7099 
7100  /**
7101  * Retrieve embedder-specific data from the isolate.
7102  * Returns NULL if SetData has never been called for the given |slot|.
7103  */
7104  V8_INLINE void* GetData(uint32_t slot);
7105 
7106  /**
7107  * Returns the maximum number of available embedder data slots. Valid slots
7108  * are in the range of 0 - GetNumberOfDataSlots() - 1.
7109  */
7110  V8_INLINE static uint32_t GetNumberOfDataSlots();
7111 
7112  /**
7113  * Get statistics about the heap memory usage.
7114  */
7115  void GetHeapStatistics(HeapStatistics* heap_statistics);
7116 
7117  /**
7118  * Returns the number of spaces in the heap.
7119  */
7121 
7122  /**
7123  * Get the memory usage of a space in the heap.
7124  *
7125  * \param space_statistics The HeapSpaceStatistics object to fill in
7126  * statistics.
7127  * \param index The index of the space to get statistics from, which ranges
7128  * from 0 to NumberOfHeapSpaces() - 1.
7129  * \returns true on success.
7130  */
7132  size_t index);
7133 
7134  /**
7135  * Returns the number of types of objects tracked in the heap at GC.
7136  */
7138 
7139  /**
7140  * Get statistics about objects in the heap.
7141  *
7142  * \param object_statistics The HeapObjectStatistics object to fill in
7143  * statistics of objects of given type, which were live in the previous GC.
7144  * \param type_index The index of the type of object to fill details about,
7145  * which ranges from 0 to NumberOfTrackedHeapObjectTypes() - 1.
7146  * \returns true on success.
7147  */
7149  size_t type_index);
7150 
7151  /**
7152  * Get statistics about code and its metadata in the heap.
7153  *
7154  * \param object_statistics The HeapCodeStatistics object to fill in
7155  * statistics of code, bytecode and their metadata.
7156  * \returns true on success.
7157  */
7159 
7160  /**
7161  * Get a call stack sample from the isolate.
7162  * \param state Execution state.
7163  * \param frames Caller allocated buffer to store stack frames.
7164  * \param frames_limit Maximum number of frames to capture. The buffer must
7165  * be large enough to hold the number of frames.
7166  * \param sample_info The sample info is filled up by the function
7167  * provides number of actual captured stack frames and
7168  * the current VM state.
7169  * \note GetStackSample should only be called when the JS thread is paused or
7170  * interrupted. Otherwise the behavior is undefined.
7171  */
7172  void GetStackSample(const RegisterState& state, void** frames,
7173  size_t frames_limit, SampleInfo* sample_info);
7174 
7175  /**
7176  * Adjusts the amount of registered external memory. Used to give V8 an
7177  * indication of the amount of externally allocated memory that is kept alive
7178  * by JavaScript objects. V8 uses this to decide when to perform global
7179  * garbage collections. Registering externally allocated memory will trigger
7180  * global garbage collections more often than it would otherwise in an attempt
7181  * to garbage collect the JavaScript objects that keep the externally
7182  * allocated memory alive.
7183  *
7184  * \param change_in_bytes the change in externally allocated memory that is
7185  * kept alive by JavaScript objects.
7186  * \returns the adjusted value.
7187  */
7188  V8_INLINE int64_t
7189  AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes);
7190 
7191  /**
7192  * Returns the number of phantom handles without callbacks that were reset
7193  * by the garbage collector since the last call to this function.
7194  */
7196 
7197  /**
7198  * Returns heap profiler for this isolate. Will return NULL until the isolate
7199  * is initialized.
7200  */
7202 
7203  /**
7204  * Returns CPU profiler for this isolate. Will return NULL unless the isolate
7205  * is initialized. It is the embedder's responsibility to stop all CPU
7206  * profiling activities if it has started any.
7207  */
7208  V8_DEPRECATE_SOON("CpuProfiler should be created with CpuProfiler::New call.",
7209  CpuProfiler* GetCpuProfiler());
7210 
7211  /** Returns true if this isolate has a current context. */
7212  bool InContext();
7213 
7214  /**
7215  * Returns the context of the currently running JavaScript, or the context
7216  * on the top of the stack if no JavaScript is running.
7217  */
7219 
7220  /**
7221  * Returns the context of the calling JavaScript code. That is the
7222  * context of the top-most JavaScript frame. If there are no
7223  * JavaScript frames an empty handle is returned.
7224  */
7226  "Calling context concept is not compatible with tail calls, and will be "
7227  "removed.",
7228  Local<Context> GetCallingContext());
7229 
7230  /** Returns the last context entered through V8's C++ API. */
7232 
7233  /**
7234  * Returns either the last context entered through V8's C++ API, or the
7235  * context of the currently running microtask while processing microtasks.
7236  * If a context is entered while executing a microtask, that context is
7237  * returned.
7238  */
7240 
7241  /**
7242  * Returns the Context that corresponds to the Incumbent realm in HTML spec.
7243  * https://html.spec.whatwg.org/multipage/webappapis.html#incumbent
7244  */
7246 
7247  /**
7248  * Schedules an exception to be thrown when returning to JavaScript. When an
7249  * exception has been scheduled it is illegal to invoke any JavaScript
7250  * operation; the caller must return immediately and only after the exception
7251  * has been handled does it become legal to invoke JavaScript operations.
7252  */
7254 
7255  typedef void (*GCCallback)(Isolate* isolate, GCType type,
7256  GCCallbackFlags flags);
7257 
7258  /**
7259  * Enables the host application to receive a notification before a
7260  * garbage collection. Allocations are allowed in the callback function,
7261  * but the callback is not re-entrant: if the allocation inside it will
7262  * trigger the garbage collection, the callback won't be called again.
7263  * It is possible to specify the GCType filter for your callback. But it is
7264  * not possible to register the same callback function two times with
7265  * different GCType filters.
7266  */
7268  GCType gc_type_filter = kGCTypeAll);
7269 
7270  /**
7271  * This function removes callback which was installed by
7272  * AddGCPrologueCallback function.
7273  */
7275 
7276  /**
7277  * Sets the embedder heap tracer for the isolate.
7278  */
7280 
7281  /**
7282  * Enables the host application to receive a notification after a
7283  * garbage collection. Allocations are allowed in the callback function,
7284  * but the callback is not re-entrant: if the allocation inside it will
7285  * trigger the garbage collection, the callback won't be called again.
7286  * It is possible to specify the GCType filter for your callback. But it is
7287  * not possible to register the same callback function two times with
7288  * different GCType filters.
7289  */
7291  GCType gc_type_filter = kGCTypeAll);
7292 
7293  /**
7294  * This function removes callback which was installed by
7295  * AddGCEpilogueCallback function.
7296  */
7298 
7299  typedef size_t (*GetExternallyAllocatedMemoryInBytesCallback)();
7300 
7301  /**
7302  * Set the callback that tells V8 how much memory is currently allocated
7303  * externally of the V8 heap. Ideally this memory is somehow connected to V8
7304  * objects and may get freed-up when the corresponding V8 objects get
7305  * collected by a V8 garbage collection.
7306  */
7308  GetExternallyAllocatedMemoryInBytesCallback callback);
7309 
7310  /**
7311  * Forcefully terminate the current thread of JavaScript execution
7312  * in the given isolate.
7313  *
7314  * This method can be used by any thread even if that thread has not
7315  * acquired the V8 lock with a Locker object.
7316  */
7318 
7319  /**
7320  * Is V8 terminating JavaScript execution.
7321  *
7322  * Returns true if JavaScript execution is currently terminating
7323  * because of a call to TerminateExecution. In that case there are
7324  * still JavaScript frames on the stack and the termination
7325  * exception is still active.
7326  */
7328 
7329  /**
7330  * Resume execution capability in the given isolate, whose execution
7331  * was previously forcefully terminated using TerminateExecution().
7332  *
7333  * When execution is forcefully terminated using TerminateExecution(),
7334  * the isolate can not resume execution until all JavaScript frames
7335  * have propagated the uncatchable exception which is generated. This
7336  * method allows the program embedding the engine to handle the
7337  * termination event and resume execution capability, even if
7338  * JavaScript frames remain on the stack.
7339  *
7340  * This method can be used by any thread even if that thread has not
7341  * acquired the V8 lock with a Locker object.
7342  */
7344 
7345  /**
7346  * Request V8 to interrupt long running JavaScript code and invoke
7347  * the given |callback| passing the given |data| to it. After |callback|
7348  * returns control will be returned to the JavaScript code.
7349  * There may be a number of interrupt requests in flight.
7350  * Can be called from another thread without acquiring a |Locker|.
7351  * Registered |callback| must not reenter interrupted Isolate.
7352  */
7353  void RequestInterrupt(InterruptCallback callback, void* data);
7354 
7355  /**
7356  * Request garbage collection in this Isolate. It is only valid to call this
7357  * function if --expose_gc was specified.
7358  *
7359  * This should only be used for testing purposes and not to enforce a garbage
7360  * collection schedule. It has strong negative impact on the garbage
7361  * collection performance. Use IdleNotificationDeadline() or
7362  * LowMemoryNotification() instead to influence the garbage collection
7363  * schedule.
7364  */
7366 
7367  /**
7368  * Set the callback to invoke for logging event.
7369  */
7371 
7372  /**
7373  * Adds a callback to notify the host application right before a script
7374  * is about to run. If a script re-enters the runtime during executing, the
7375  * BeforeCallEnteredCallback is invoked for each re-entrance.
7376  * Executing scripts inside the callback will re-trigger the callback.
7377  */
7379 
7380  /**
7381  * Removes callback that was installed by AddBeforeCallEnteredCallback.
7382  */
7384 
7385  /**
7386  * Adds a callback to notify the host application when a script finished
7387  * running. If a script re-enters the runtime during executing, the
7388  * CallCompletedCallback is only invoked when the outer-most script
7389  * execution ends. Executing scripts inside the callback do not trigger
7390  * further callbacks.
7391  */
7394  "Use callback with parameter",
7395  void AddCallCompletedCallback(DeprecatedCallCompletedCallback callback));
7396 
7397  /**
7398  * Removes callback that was installed by AddCallCompletedCallback.
7399  */
7402  "Use callback with parameter",
7403  void RemoveCallCompletedCallback(
7405 
7406  /**
7407  * Set the PromiseHook callback for various promise lifecycle
7408  * events.
7409  */
7411 
7412  /**
7413  * Set callback to notify about promise reject with no handler, or
7414  * revocation of such a previous notification once the handler is added.
7415  */
7417 
7418  /**
7419  * Experimental: Runs the Microtask Work Queue until empty
7420  * Any exceptions thrown by microtask callbacks are swallowed.
7421  */
7423 
7424  /**
7425  * Experimental: Enqueues the callback to the Microtask Work Queue
7426  */
7427  void EnqueueMicrotask(Local<Function> microtask);
7428 
7429  /**
7430  * Experimental: Enqueues the callback to the Microtask Work Queue
7431  */
7432  void EnqueueMicrotask(MicrotaskCallback microtask, void* data = NULL);
7433 
7434  /**
7435  * Experimental: Controls how Microtasks are invoked. See MicrotasksPolicy
7436  * for details.
7437  */
7439  V8_DEPRECATE_SOON("Use SetMicrotasksPolicy",
7440  void SetAutorunMicrotasks(bool autorun));
7441 
7442  /**
7443  * Experimental: Returns the policy controlling how Microtasks are invoked.
7444  */
7446  V8_DEPRECATE_SOON("Use GetMicrotasksPolicy",
7447  bool WillAutorunMicrotasks() const);
7448 
7449  /**
7450  * Experimental: adds a callback to notify the host application after
7451  * microtasks were run. The callback is triggered by explicit RunMicrotasks
7452  * call or automatic microtasks execution (see SetAutorunMicrotasks).
7453  *
7454  * Callback will trigger even if microtasks were attempted to run,
7455  * but the microtasks queue was empty and no single microtask was actually
7456  * executed.
7457  *
7458  * Executing scriptsinside the callback will not re-trigger microtasks and
7459  * the callback.
7460  */
7462 
7463  /**
7464  * Removes callback that was installed by AddMicrotasksCompletedCallback.
7465  */
7467 
7468  /**
7469  * Sets a callback for counting the number of times a feature of V8 is used.
7470  */
7472 
7473  /**
7474  * Enables the host application to provide a mechanism for recording
7475  * statistics counters.
7476  */
7478 
7479  /**
7480  * Enables the host application to provide a mechanism for recording
7481  * histograms. The CreateHistogram function returns a
7482  * histogram which will later be passed to the AddHistogramSample
7483  * function.
7484  */
7487 
7488  /**
7489  * Optional notification that the embedder is idle.
7490  * V8 uses the notification to perform garbage collection.
7491  * This call can be used repeatedly if the embedder remains idle.
7492  * Returns true if the embedder should stop calling IdleNotificationDeadline
7493  * until real work has been done. This indicates that V8 has done
7494  * as much cleanup as it will be able to do.
7495  *
7496  * The deadline_in_seconds argument specifies the deadline V8 has to finish
7497  * garbage collection work. deadline_in_seconds is compared with
7498  * MonotonicallyIncreasingTime() and should be based on the same timebase as
7499  * that function. There is no guarantee that the actual work will be done
7500  * within the time limit.
7501  */
7502  bool IdleNotificationDeadline(double deadline_in_seconds);
7503 
7504  V8_DEPRECATED("use IdleNotificationDeadline()",
7505  bool IdleNotification(int idle_time_in_ms));
7506 
7507  /**
7508  * Optional notification that the system is running low on memory.
7509  * V8 uses these notifications to attempt to free memory.
7510  */
7512 
7513  /**
7514  * Optional notification that a context has been disposed. V8 uses
7515  * these notifications to guide the GC heuristic. Returns the number
7516  * of context disposals - including this one - since the last time
7517  * V8 had a chance to clean up.
7518  *
7519  * The optional parameter |dependant_context| specifies whether the disposed
7520  * context was depending on state from other contexts or not.
7521  */
7522  int ContextDisposedNotification(bool dependant_context = true);
7523 
7524  /**
7525  * Optional notification that the isolate switched to the foreground.
7526  * V8 uses these notifications to guide heuristics.
7527  */
7529 
7530  /**
7531  * Optional notification that the isolate switched to the background.
7532  * V8 uses these notifications to guide heuristics.
7533  */
7535 
7536  /**
7537  * Optional notification to tell V8 the current performance requirements
7538  * of the embedder based on RAIL.
7539  * V8 uses these notifications to guide heuristics.
7540  * This is an unfinished experimental feature. Semantics and implementation
7541  * may change frequently.
7542  */
7543  void SetRAILMode(RAILMode rail_mode);
7544 
7545  /**
7546  * Optional notification to tell V8 the current isolate is used for debugging
7547  * and requires higher heap limit.
7548  */
7550 
7551  /**
7552  * Restores the original heap limit after IncreaseHeapLimitForDebugging().
7553  */
7555 
7556  /**
7557  * Returns true if the heap limit was increased for debugging and the
7558  * original heap limit was not restored yet.
7559  */
7561 
7562  /**
7563  * Allows the host application to provide the address of a function that is
7564  * notified each time code is added, moved or removed.
7565  *
7566  * \param options options for the JIT code event handler.
7567  * \param event_handler the JIT code event handler, which will be invoked
7568  * each time code is added, moved or removed.
7569  * \note \p event_handler won't get notified of existent code.
7570  * \note since code removal notifications are not currently issued, the
7571  * \p event_handler may get notifications of code that overlaps earlier
7572  * code notifications. This happens when code areas are reused, and the
7573  * earlier overlapping code areas should therefore be discarded.
7574  * \note the events passed to \p event_handler and the strings they point to
7575  * are not guaranteed to live past each call. The \p event_handler must
7576  * copy strings and other parameters it needs to keep around.
7577  * \note the set of events declared in JitCodeEvent::EventType is expected to
7578  * grow over time, and the JitCodeEvent structure is expected to accrue
7579  * new members. The \p event_handler function must ignore event codes
7580  * it does not recognize to maintain future compatibility.
7581  * \note Use Isolate::CreateParams to get events for code executed during
7582  * Isolate setup.
7583  */
7585  JitCodeEventHandler event_handler);
7586 
7587  /**
7588  * Modifies the stack limit for this Isolate.
7589  *
7590  * \param stack_limit An address beyond which the Vm's stack may not grow.
7591  *
7592  * \note If you are using threads then you should hold the V8::Locker lock
7593  * while setting the stack limit and you must set a non-default stack
7594  * limit separately for each thread.
7595  */
7596  void SetStackLimit(uintptr_t stack_limit);
7597 
7598  /**
7599  * Returns a memory range that can potentially contain jitted code.
7600  *
7601  * On Win64, embedders are advised to install function table callbacks for
7602  * these ranges, as default SEH won't be able to unwind through jitted code.
7603  *
7604  * The first page of the code range is reserved for the embedder and is
7605  * committed, writable, and executable.
7606  *
7607  * Might be empty on other platforms.
7608  *
7609  * https://code.google.com/p/v8/issues/detail?id=3598
7610  */
7611  void GetCodeRange(void** start, size_t* length_in_bytes);
7612 
7613  /** Set the callback to invoke in case of fatal errors. */
7615 
7616  /** Set the callback to invoke in case of OOM errors. */
7618 
7619  /**
7620  * Set the callback to invoke to check if code generation from
7621  * strings should be allowed.
7622  */
7625 
7626  /**
7627  * Embedder over{ride|load} injection points for wasm APIs. The expectation
7628  * is that the embedder sets them at most once.
7629  */
7632 
7634 
7635  /**
7636  * Check if V8 is dead and therefore unusable. This is the case after
7637  * fatal errors such as out-of-memory situations.
7638  */
7639  bool IsDead();
7640 
7641  /**
7642  * Adds a message listener (errors only).
7643  *
7644  * The same message listener can be added more than once and in that
7645  * case it will be called more than once for each message.
7646  *
7647  * If data is specified, it will be passed to the callback when it is called.
7648  * Otherwise, the exception object will be passed to the callback instead.
7649  */
7651  Local<Value> data = Local<Value>());
7652 
7653  /**
7654  * Adds a message listener.
7655  *
7656  * The same message listener can be added more than once and in that
7657  * case it will be called more than once for each message.
7658  *
7659  * If data is specified, it will be passed to the callback when it is called.
7660  * Otherwise, the exception object will be passed to the callback instead.
7661  *
7662  * A listener can listen for particular error levels by providing a mask.
7663  */
7665  int message_levels,
7666  Local<Value> data = Local<Value>());
7667 
7668  /**
7669  * Remove all message listeners from the specified callback function.
7670  */
7672 
7673  /** Callback function for reporting failed access checks.*/
7675 
7676  /**
7677  * Tells V8 to capture current stack trace when uncaught exception occurs
7678  * and report it to the message listeners. The option is off by default.
7679  */
7681  bool capture, int frame_limit = 10,
7683 
7684  /**
7685  * Iterates through all external resources referenced from current isolate
7686  * heap. GC is not invoked prior to iterating, therefore there is no
7687  * guarantee that visited objects are still alive.
7688  */
7690 
7691  /**
7692  * Iterates through all the persistent handles in the current isolate's heap
7693  * that have class_ids.
7694  */
7696 
7697  /**
7698  * Iterates through all the persistent handles in the current isolate's heap
7699  * that have class_ids and are candidates to be marked as partially dependent
7700  * handles. This will visit handles to young objects created since the last
7701  * garbage collection but is free to visit an arbitrary superset of these
7702  * objects.
7703  */
7705 
7706  /**
7707  * Iterates through all the persistent handles in the current isolate's heap
7708  * that have class_ids and are weak to be marked as inactive if there is no
7709  * pending activity for the handle.
7710  */
7712 
7713  /**
7714  * Check if this isolate is in use.
7715  * True if at least one thread Enter'ed this isolate.
7716  */
7717  bool IsInUse();
7718 
7719  /**
7720  * Set whether calling Atomics.wait (a function that may block) is allowed in
7721  * this isolate. This can also be configured via
7722  * CreateParams::allow_atomics_wait.
7723  */
7724  void SetAllowAtomicsWait(bool allow);
7725 
7726  Isolate() = delete;
7727  ~Isolate() = delete;
7728  Isolate(const Isolate&) = delete;
7729  Isolate& operator=(const Isolate&) = delete;
7730  // Deleting operator new and delete here is allowed as ctor and dtor is also
7731  // deleted.
7732  void* operator new(size_t size) = delete;
7733  void* operator new[](size_t size) = delete;
7734  void operator delete(void*, size_t) = delete;
7735  void operator delete[](void*, size_t) = delete;
7736 
7737  private:
7738  template <class K, class V, class Traits>
7740 
7741  void ReportExternalAllocationLimitReached();
7742  void CheckMemoryPressure();
7743 };
7744 
7746  public:
7747  const char* data;
7749 };
7750 
7751 
7752 /**
7753  * EntropySource is used as a callback function when v8 needs a source
7754  * of entropy.
7755  */
7756 typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
7757 
7758 /**
7759  * ReturnAddressLocationResolver is used as a callback function when v8 is
7760  * resolving the location of a return address on the stack. Profilers that
7761  * change the return address on the stack can use this to resolve the stack
7762  * location to wherever the profiler stashed the original return address.
7763  *
7764  * \param return_addr_location A location on stack where a machine
7765  * return address resides.
7766  * \returns Either return_addr_location, or else a pointer to the profiler's
7767  * copy of the original return address.
7768  *
7769  * \note The resolver function must not cause garbage collection.
7770  */
7771 typedef uintptr_t (*ReturnAddressLocationResolver)(
7772  uintptr_t return_addr_location);
7773 
7774 
7775 /**
7776  * Container class for static utility functions.
7777  */
7778 class V8_EXPORT V8 {
7779  public:
7780  /** Set the callback to invoke in case of fatal errors. */
7782  "Use isolate version",
7783  void SetFatalErrorHandler(FatalErrorCallback that));
7784 
7785  /**
7786  * Check if V8 is dead and therefore unusable. This is the case after
7787  * fatal errors such as out-of-memory situations.
7788  */
7789  V8_INLINE static V8_DEPRECATED("Use isolate version", bool IsDead());
7790 
7791  /**
7792  * Hand startup data to V8, in case the embedder has chosen to build
7793  * V8 with external startup data.
7794  *
7795  * Note:
7796  * - By default the startup data is linked into the V8 library, in which
7797  * case this function is not meaningful.
7798  * - If this needs to be called, it needs to be called before V8
7799  * tries to make use of its built-ins.
7800  * - To avoid unnecessary copies of data, V8 will point directly into the
7801  * given data blob, so pretty please keep it around until V8 exit.
7802  * - Compression of the startup blob might be useful, but needs to
7803  * handled entirely on the embedders' side.
7804  * - The call will abort if the data is invalid.
7805  */
7806  static void SetNativesDataBlob(StartupData* startup_blob);
7807  static void SetSnapshotDataBlob(StartupData* startup_blob);
7808 
7809  /**
7810  * Bootstrap an isolate and a context from scratch to create a startup
7811  * snapshot. Include the side-effects of running the optional script.
7812  * Returns { NULL, 0 } on failure.
7813  * The caller acquires ownership of the data array in the return value.
7814  */
7815  static StartupData CreateSnapshotDataBlob(const char* embedded_source = NULL);
7816 
7817  /**
7818  * Bootstrap an isolate and a context from the cold startup blob, run the
7819  * warm-up script to trigger code compilation. The side effects are then
7820  * discarded. The resulting startup snapshot will include compiled code.
7821  * Returns { NULL, 0 } on failure.
7822  * The caller acquires ownership of the data array in the return value.
7823  * The argument startup blob is untouched.
7824  */
7826  const char* warmup_source);
7827 
7828  /**
7829  * Adds a message listener.
7830  *
7831  * The same message listener can be added more than once and in that
7832  * case it will be called more than once for each message.
7833  *
7834  * If data is specified, it will be passed to the callback when it is called.
7835  * Otherwise, the exception object will be passed to the callback instead.
7836  */
7838  "Use isolate version",
7839  bool AddMessageListener(MessageCallback that,
7840  Local<Value> data = Local<Value>()));
7841 
7842  /**
7843  * Remove all message listeners from the specified callback function.
7844  */
7846  "Use isolate version", void RemoveMessageListeners(MessageCallback that));
7847 
7848  /**
7849  * Tells V8 to capture current stack trace when uncaught exception occurs
7850  * and report it to the message listeners. The option is off by default.
7851  */
7853  "Use isolate version",
7854  void SetCaptureStackTraceForUncaughtExceptions(
7855  bool capture, int frame_limit = 10,
7857 
7858  /**
7859  * Sets V8 flags from a string.
7860  */
7861  static void SetFlagsFromString(const char* str, int length);
7862 
7863  /**
7864  * Sets V8 flags from the command line.
7865  */
7866  static void SetFlagsFromCommandLine(int* argc,
7867  char** argv,
7868  bool remove_flags);
7869 
7870  /** Get the version string. */
7871  static const char* GetVersion();
7872 
7873  /** Callback function for reporting failed access checks.*/
7875  "Use isolate version",
7876  void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback));
7877 
7878  /**
7879  * Enables the host application to receive a notification before a
7880  * garbage collection. Allocations are not allowed in the
7881  * callback function, you therefore cannot manipulate objects (set
7882  * or delete properties for example) since it is possible such
7883  * operations will result in the allocation of objects. It is possible
7884  * to specify the GCType filter for your callback. But it is not possible to
7885  * register the same callback function two times with different
7886  * GCType filters.
7887  */
7889  "Use isolate version",
7890  void AddGCPrologueCallback(GCCallback callback,
7891  GCType gc_type_filter = kGCTypeAll));
7892 
7893  /**
7894  * This function removes callback which was installed by
7895  * AddGCPrologueCallback function.
7896  */
7898  "Use isolate version",
7899  void RemoveGCPrologueCallback(GCCallback callback));
7900 
7901  /**
7902  * Enables the host application to receive a notification after a
7903  * garbage collection. Allocations are not allowed in the
7904  * callback function, you therefore cannot manipulate objects (set
7905  * or delete properties for example) since it is possible such
7906  * operations will result in the allocation of objects. It is possible
7907  * to specify the GCType filter for your callback. But it is not possible to
7908  * register the same callback function two times with different
7909  * GCType filters.
7910  */
7912  "Use isolate version",
7913  void AddGCEpilogueCallback(GCCallback callback,
7914  GCType gc_type_filter = kGCTypeAll));
7915 
7916  /**
7917  * This function removes callback which was installed by
7918  * AddGCEpilogueCallback function.
7919  */
7921  "Use isolate version",
7922  void RemoveGCEpilogueCallback(GCCallback callback));
7923 
7924  /**
7925  * Initializes V8. This function needs to be called before the first Isolate
7926  * is created. It always returns true.
7927  */
7928  static bool Initialize();
7929 
7930  /**
7931  * Allows the host application to provide a callback which can be used
7932  * as a source of entropy for random number generators.
7933  */
7934  static void SetEntropySource(EntropySource source);
7935 
7936  /**
7937  * Allows the host application to provide a callback that allows v8 to
7938  * cooperate with a profiler that rewrites return addresses on stack.
7939  */
7941  ReturnAddressLocationResolver return_address_resolver);
7942 
7943  /**
7944  * Forcefully terminate the current thread of JavaScript execution
7945  * in the given isolate.
7946  *
7947  * This method can be used by any thread even if that thread has not
7948  * acquired the V8 lock with a Locker object.
7949  *
7950  * \param isolate The isolate in which to terminate the current JS execution.
7951  */
7952  V8_INLINE static V8_DEPRECATED("Use isolate version",
7953  void TerminateExecution(Isolate* isolate));
7954 
7955  /**
7956  * Is V8 terminating JavaScript execution.
7957  *
7958  * Returns true if JavaScript execution is currently terminating
7959  * because of a call to TerminateExecution. In that case there are
7960  * still JavaScript frames on the stack and the termination
7961  * exception is still active.
7962  *
7963  * \param isolate The isolate in which to check.
7964  */
7966  "Use isolate version",
7967  bool IsExecutionTerminating(Isolate* isolate = NULL));
7968 
7969  /**
7970  * Resume execution capability in the given isolate, whose execution
7971  * was previously forcefully terminated using TerminateExecution().
7972  *
7973  * When execution is forcefully terminated using TerminateExecution(),
7974  * the isolate can not resume execution until all JavaScript frames
7975  * have propagated the uncatchable exception which is generated. This
7976  * method allows the program embedding the engine to handle the
7977  * termination event and resume execution capability, even if
7978  * JavaScript frames remain on the stack.
7979  *
7980  * This method can be used by any thread even if that thread has not
7981  * acquired the V8 lock with a Locker object.
7982  *
7983  * \param isolate The isolate in which to resume execution capability.
7984  */
7986  "Use isolate version", void CancelTerminateExecution(Isolate* isolate));
7987 
7988  /**
7989  * Releases any resources used by v8 and stops any utility threads
7990  * that may be running. Note that disposing v8 is permanent, it
7991  * cannot be reinitialized.
7992  *
7993  * It should generally not be necessary to dispose v8 before exiting
7994  * a process, this should happen automatically. It is only necessary
7995  * to use if the process needs the resources taken up by v8.
7996  */
7997  static bool Dispose();
7998 
7999  /**
8000  * Iterates through all external resources referenced from current isolate
8001  * heap. GC is not invoked prior to iterating, therefore there is no
8002  * guarantee that visited objects are still alive.
8003  */
8005  "Use isolate version",
8006  void VisitExternalResources(ExternalResourceVisitor* visitor));
8007 
8008  /**
8009  * Iterates through all the persistent handles in the current isolate's heap
8010  * that have class_ids.
8011  */
8013  "Use isolate version",
8014  void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor));
8015 
8016  /**
8017  * Iterates through all the persistent handles in isolate's heap that have
8018  * class_ids.
8019  */
8021  "Use isolate version",
8022  void VisitHandlesWithClassIds(Isolate* isolate,
8023  PersistentHandleVisitor* visitor));
8024 
8025  /**
8026  * Iterates through all the persistent handles in the current isolate's heap
8027  * that have class_ids and are candidates to be marked as partially dependent
8028  * handles. This will visit handles to young objects created since the last
8029  * garbage collection but is free to visit an arbitrary superset of these
8030  * objects.
8031  */
8033  "Use isolate version",
8034  void VisitHandlesForPartialDependence(Isolate* isolate,
8035  PersistentHandleVisitor* visitor));
8036 
8037  /**
8038  * Initialize the ICU library bundled with V8. The embedder should only
8039  * invoke this method when using the bundled ICU. Returns true on success.
8040  *
8041  * If V8 was compiled with the ICU data in an external file, the location
8042  * of the data file has to be provided.
8043  */
8045  "Use version with default location.",
8046  static bool InitializeICU(const char* icu_data_file = nullptr));
8047 
8048  /**
8049  * Initialize the ICU library bundled with V8. The embedder should only
8050  * invoke this method when using the bundled ICU. If V8 was compiled with
8051  * the ICU data in an external file and when the default location of that
8052  * file should be used, a path to the executable must be provided.
8053  * Returns true on success.
8054  *
8055  * The default is a file called icudtl.dat side-by-side with the executable.
8056  *
8057  * Optionally, the location of the data file can be provided to override the
8058  * default.
8059  */
8060  static bool InitializeICUDefaultLocation(const char* exec_path,
8061  const char* icu_data_file = nullptr);
8062 
8063  /**
8064  * Initialize the external startup data. The embedder only needs to
8065  * invoke this method when external startup data was enabled in a build.
8066  *
8067  * If V8 was compiled with the startup data in an external file, then
8068  * V8 needs to be given those external files during startup. There are
8069  * three ways to do this:
8070  * - InitializeExternalStartupData(const char*)
8071  * This will look in the given directory for files "natives_blob.bin"
8072  * and "snapshot_blob.bin" - which is what the default build calls them.
8073  * - InitializeExternalStartupData(const char*, const char*)
8074  * As above, but will directly use the two given file names.
8075  * - Call SetNativesDataBlob, SetNativesDataBlob.
8076  * This will read the blobs from the given data structures and will
8077  * not perform any file IO.
8078  */
8079  static void InitializeExternalStartupData(const char* directory_path);
8080  static void InitializeExternalStartupData(const char* natives_blob,
8081  const char* snapshot_blob);
8082  /**
8083  * Sets the v8::Platform to use. This should be invoked before V8 is
8084  * initialized.
8085  */
8086  static void InitializePlatform(Platform* platform);
8087 
8088  /**
8089  * Clears all references to the v8::Platform. This should be invoked after
8090  * V8 was disposed.
8091  */
8092  static void ShutdownPlatform();
8093 
8094 #if V8_OS_POSIX
8095  /**
8096  * Give the V8 signal handler a chance to handle a fault.
8097  *
8098  * This function determines whether a memory access violation can be recovered
8099  * by V8. If so, it will return true and modify context to return to a code
8100  * fragment that can recover from the fault. Otherwise, TryHandleSignal will
8101  * return false.
8102  *
8103  * The parameters to this function correspond to those passed to a Linux
8104  * signal handler.
8105  *
8106  * \param signal_number The signal number.
8107  *
8108  * \param info A pointer to the siginfo_t structure provided to the signal
8109  * handler.
8110  *
8111  * \param context The third argument passed to the Linux signal handler, which
8112  * points to a ucontext_t structure.
8113  */
8114  static bool TryHandleSignal(int signal_number, void* info, void* context);
8115 #endif // V8_OS_POSIX
8116 
8117  /**
8118  * Enable the default signal handler rather than using one provided by the
8119  * embedder.
8120  */
8122 
8123  private:
8124  V8();
8125 
8126  static internal::Object** GlobalizeReference(internal::Isolate* isolate,
8127  internal::Object** handle);
8128  static internal::Object** CopyPersistent(internal::Object** handle);
8129  static void DisposeGlobal(internal::Object** global_handle);
8130  static void MakeWeak(internal::Object** location, void* data,
8131  WeakCallbackInfo<void>::Callback weak_callback,
8132  WeakCallbackType type);
8133  static void MakeWeak(internal::Object** location, void* data,
8134  // Must be 0 or -1.
8135  int internal_field_index1,
8136  // Must be 1 or -1.
8137  int internal_field_index2,
8138  WeakCallbackInfo<void>::Callback weak_callback);
8139  static void MakeWeak(internal::Object*** location_addr);
8140  static void* ClearWeak(internal::Object** location);
8141  static Value* Eternalize(Isolate* isolate, Value* handle);
8142 
8143  static void RegisterExternallyReferencedObject(internal::Object** object,
8144  internal::Isolate* isolate);
8145 
8146  template <class K, class V, class T>
8148 
8149  static void FromJustIsNothing();
8150  static void ToLocalEmpty();
8151  static void InternalFieldOutOfBounds(int index);
8152  template <class T> friend class Local;
8153  template <class T>
8154  friend class MaybeLocal;
8155  template <class T>
8156  friend class Maybe;
8157  template <class T>
8158  friend class WeakCallbackInfo;
8159  template <class T> friend class Eternal;
8160  template <class T> friend class PersistentBase;
8161  template <class T, class M> friend class Persistent;
8162  friend class Context;
8163 };
8164 
8165 /**
8166  * Helper class to create a snapshot data blob.
8167  */
8169  public:
8171 
8172  /**
8173  * Create and enter an isolate, and set it up for serialization.
8174  * The isolate is either created from scratch or from an existing snapshot.
8175  * The caller keeps ownership of the argument snapshot.
8176  * \param existing_blob existing snapshot from which to create this one.
8177  * \param external_references a null-terminated array of external references
8178  * that must be equivalent to CreateParams::external_references.
8179  */
8180  SnapshotCreator(const intptr_t* external_references = nullptr,
8181  StartupData* existing_blob = nullptr);
8182 
8184 
8185  /**
8186  * \returns the isolate prepared by the snapshot creator.
8187  */
8189 
8190  /**
8191  * Set the default context to be included in the snapshot blob.
8192  * The snapshot will not contain the global proxy, and we expect one or a
8193  * global object template to create one, to be provided upon deserialization.
8194  *
8195  * \param callback optional callback to serialize internal fields.
8196  */
8200 
8201  /**
8202  * Add additional context to be included in the snapshot blob.
8203  * The snapshot will include the global proxy.
8204  *
8205  * \param callback optional callback to serialize internal fields.
8206  *
8207  * \returns the index of the context in the snapshot blob.
8208  */
8209  size_t AddContext(Local<Context> context,
8212 
8213  /**
8214  * Add a template to be included in the snapshot blob.
8215  * \returns the index of the template in the snapshot blob.
8216  */
8217  size_t AddTemplate(Local<Template> template_obj);
8218 
8219  /**
8220  * Created a snapshot data blob.
8221  * This must not be called from within a handle scope.
8222  * \param function_code_handling whether to include compiled function code
8223  * in the snapshot.
8224  * \returns { nullptr, 0 } on failure, and a startup snapshot on success. The
8225  * caller acquires ownership of the data array in the return value.
8226  */
8228 
8229  // Disallow copying and assigning.
8231  void operator=(const SnapshotCreator&) = delete;
8232 
8233  private:
8234  void* data_;
8235 };
8236 
8237 /**
8238  * A simple Maybe type, representing an object which may or may not have a
8239  * value, see https://hackage.haskell.org/package/base/docs/Data-Maybe.html.
8240  *
8241  * If an API method returns a Maybe<>, the API method can potentially fail
8242  * either because an exception is thrown, or because an exception is pending,
8243  * e.g. because a previous API call threw an exception that hasn't been caught
8244  * yet, or because a TerminateExecution exception was thrown. In that case, a
8245  * "Nothing" value is returned.
8246  */
8247 template <class T>
8248 class Maybe {
8249  public:
8250  V8_INLINE bool IsNothing() const { return !has_value_; }
8251  V8_INLINE bool IsJust() const { return has_value_; }
8252 
8253  /**
8254  * An alias for |FromJust|. Will crash if the Maybe<> is nothing.
8255  */
8256  V8_INLINE T ToChecked() const { return FromJust(); }
8257 
8258  /**
8259  * Converts this Maybe<> to a value of type T. If this Maybe<> is
8260  * nothing (empty), |false| is returned and |out| is left untouched.
8261  */
8262  V8_WARN_UNUSED_RESULT V8_INLINE bool To(T* out) const {
8263  if (V8_LIKELY(IsJust())) *out = value_;
8264  return IsJust();
8265  }
8266 
8267  /**
8268  * Converts this Maybe<> to a value of type T. If this Maybe<> is
8269  * nothing (empty), V8 will crash the process.
8270  */
8271  V8_INLINE T FromJust() const {
8272  if (V8_UNLIKELY(!IsJust())) V8::FromJustIsNothing();
8273  return value_;
8274  }
8275 
8276  /**
8277  * Converts this Maybe<> to a value of type T, using a default value if this
8278  * Maybe<> is nothing (empty).
8279  */
8280  V8_INLINE T FromMaybe(const T& default_value) const {
8281  return has_value_ ? value_ : default_value;
8282  }
8283 
8284  V8_INLINE bool operator==(const Maybe& other) const {
8285  return (IsJust() == other.IsJust()) &&
8286  (!IsJust() || FromJust() == other.FromJust());
8287  }
8288 
8289  V8_INLINE bool operator!=(const Maybe& other) const {
8290  return !operator==(other);
8291  }
8292 
8293  private:
8294  Maybe() : has_value_(false) {}
8295  explicit Maybe(const T& t) : has_value_(true), value_(t) {}
8296 
8297  bool has_value_;
8298  T value_;
8299 
8300  template <class U>
8301  friend Maybe<U> Nothing();
8302  template <class U>
8303  friend Maybe<U> Just(const U& u);
8304 };
8305 
8306 
8307 template <class T>
8308 inline Maybe<T> Nothing() {
8309  return Maybe<T>();
8310 }
8311 
8312 
8313 template <class T>
8314 inline Maybe<T> Just(const T& t) {
8315  return Maybe<T>(t);
8316 }
8317 
8318 
8319 /**
8320  * An external exception handler.
8321  */
8323  public:
8324  /**
8325  * Creates a new try/catch block and registers it with v8. Note that
8326  * all TryCatch blocks should be stack allocated because the memory
8327  * location itself is compared against JavaScript try/catch blocks.
8328  */
8329  V8_DEPRECATED("Use isolate version", TryCatch());
8330 
8331  /**
8332  * Creates a new try/catch block and registers it with v8. Note that
8333  * all TryCatch blocks should be stack allocated because the memory
8334  * location itself is compared against JavaScript try/catch blocks.
8335  */
8336  TryCatch(Isolate* isolate);
8337 
8338  /**
8339  * Unregisters and deletes this try/catch block.
8340  */
8342 
8343  /**
8344  * Returns true if an exception has been caught by this try/catch block.
8345  */
8346  bool HasCaught() const;
8347 
8348  /**
8349  * For certain types of exceptions, it makes no sense to continue execution.
8350  *
8351  * If CanContinue returns false, the correct action is to perform any C++
8352  * cleanup needed and then return. If CanContinue returns false and
8353  * HasTerminated returns true, it is possible to call
8354  * CancelTerminateExecution in order to continue calling into the engine.
8355  */
8356  bool CanContinue() const;
8357 
8358  /**
8359  * Returns true if an exception has been caught due to script execution
8360  * being terminated.
8361  *
8362  * There is no JavaScript representation of an execution termination
8363  * exception. Such exceptions are thrown when the TerminateExecution
8364  * methods are called to terminate a long-running script.
8365  *
8366  * If such an exception has been thrown, HasTerminated will return true,
8367  * indicating that it is possible to call CancelTerminateExecution in order
8368  * to continue calling into the engine.
8369  */
8370  bool HasTerminated() const;
8371 
8372  /**
8373  * Throws the exception caught by this TryCatch in a way that avoids
8374  * it being caught again by this same TryCatch. As with ThrowException
8375  * it is illegal to execute any JavaScript operations after calling
8376  * ReThrow; the caller must return immediately to where the exception
8377  * is caught.
8378  */
8380 
8381  /**
8382  * Returns the exception caught by this try/catch block. If no exception has
8383  * been caught an empty handle is returned.
8384  *
8385  * The returned handle is valid until this TryCatch block has been destroyed.
8386  */
8388 
8389  /**
8390  * Returns the .stack property of the thrown object. If no .stack
8391  * property is present an empty handle is returned.
8392  */
8393  V8_DEPRECATE_SOON("Use maybe version.", Local<Value> StackTrace() const);
8395  Local<Context> context) const;
8396 
8397  /**
8398  * Returns the message associated with this exception. If there is
8399  * no message associated an empty handle is returned.
8400  *
8401  * The returned handle is valid until this TryCatch block has been
8402  * destroyed.
8403  */
8404  Local<v8::Message> Message() const;
8405 
8406  /**
8407  * Clears any exceptions that may have been caught by this try/catch block.
8408  * After this method has been called, HasCaught() will return false. Cancels
8409  * the scheduled exception if it is caught and ReThrow() is not called before.
8410  *
8411  * It is not necessary to clear a try/catch block before using it again; if
8412  * another exception is thrown the previously caught exception will just be
8413  * overwritten. However, it is often a good idea since it makes it easier
8414  * to determine which operation threw a given exception.
8415  */
8416  void Reset();
8417 
8418  /**
8419  * Set verbosity of the external exception handler.
8420  *
8421  * By default, exceptions that are caught by an external exception
8422  * handler are not reported. Call SetVerbose with true on an
8423  * external exception handler to have exceptions caught by the
8424  * handler reported as if they were not caught.
8425  */
8426  void SetVerbose(bool value);
8427 
8428  /**
8429  * Returns true if verbosity is enabled.
8430  */
8431  bool IsVerbose() const;
8432 
8433  /**
8434  * Set whether or not this TryCatch should capture a Message object
8435  * which holds source information about where the exception
8436  * occurred. True by default.
8437  */
8438  void SetCaptureMessage(bool value);
8439 
8440  /**
8441  * There are cases when the raw address of C++ TryCatch object cannot be
8442  * used for comparisons with addresses into the JS stack. The cases are:
8443  * 1) ARM, ARM64 and MIPS simulators which have separate JS stack.
8444  * 2) Address sanitizer allocates local C++ object in the heap when
8445  * UseAfterReturn mode is enabled.
8446  * This method returns address that can be used for comparisons with
8447  * addresses into the JS stack. When neither simulator nor ASAN's
8448  * UseAfterReturn is enabled, then the address returned will be the address
8449  * of the C++ try catch handler itself.
8450  */
8451  static void* JSStackComparableAddress(TryCatch* handler) {
8452  if (handler == NULL) return NULL;
8453  return handler->js_stack_comparable_address_;
8454  }
8455 
8456  TryCatch(const TryCatch&) = delete;
8457  void operator=(const TryCatch&) = delete;
8458 
8459  private:
8460  // Declaring operator new and delete as deleted is not spec compliant.
8461  // Therefore declare them private instead to disable dynamic alloc
8462  void* operator new(size_t size);
8463  void* operator new[](size_t size);
8464  void operator delete(void*, size_t);
8465  void operator delete[](void*, size_t);
8466 
8467  void ResetInternal();
8468 
8469  internal::Isolate* isolate_;
8470  TryCatch* next_;
8471  void* exception_;
8472  void* message_obj_;
8473  void* js_stack_comparable_address_;
8474  bool is_verbose_ : 1;
8475  bool can_continue_ : 1;
8476  bool capture_message_ : 1;
8477  bool rethrow_ : 1;
8478  bool has_terminated_ : 1;
8479 
8480  friend class internal::Isolate;
8481 };
8482 
8483 
8484 // --- Context ---
8485 
8486 
8487 /**
8488  * A container for extension names.
8489  */
8491  public:
8492  ExtensionConfiguration() : name_count_(0), names_(NULL) { }
8493  ExtensionConfiguration(int name_count, const char* names[])
8494  : name_count_(name_count), names_(names) { }
8495 
8496  const char** begin() const { return &names_[0]; }
8497  const char** end() const { return &names_[name_count_]; }
8498 
8499  private:
8500  const int name_count_;
8501  const char** names_;
8502 };
8503 
8504 /**
8505  * A sandboxed execution context with its own set of built-in objects
8506  * and functions.
8507  */
8509  public:
8510  /**
8511  * Returns the global proxy object.
8512  *
8513  * Global proxy object is a thin wrapper whose prototype points to actual
8514  * context's global object with the properties like Object, etc. This is done
8515  * that way for security reasons (for more details see
8516  * https://wiki.mozilla.org/Gecko:SplitWindow).
8517  *
8518  * Please note that changes to global proxy object prototype most probably
8519  * would break VM---v8 expects only global object as a prototype of global
8520  * proxy object.
8521  */
8523 
8524  /**
8525  * Detaches the global object from its context before
8526  * the global object can be reused to create a new context.
8527  */
8529 
8530  /**
8531  * Creates a new context and returns a handle to the newly allocated
8532  * context.
8533  *
8534  * \param isolate The isolate in which to create the context.
8535  *
8536  * \param extensions An optional extension configuration containing
8537  * the extensions to be installed in the newly created context.
8538  *
8539  * \param global_template An optional object template from which the
8540  * global object for the newly created context will be created.
8541  *
8542  * \param global_object An optional global object to be reused for
8543  * the newly created context. This global object must have been
8544  * created by a previous call to Context::New with the same global
8545  * template. The state of the global object will be completely reset
8546  * and only object identify will remain.
8547  */
8548  static Local<Context> New(
8549  Isolate* isolate, ExtensionConfiguration* extensions = NULL,
8551  MaybeLocal<Value> global_object = MaybeLocal<Value>(),
8552  DeserializeInternalFieldsCallback internal_fields_deserializer =
8554 
8555  /**
8556  * Create a new context from a (non-default) context snapshot. There
8557  * is no way to provide a global object template since we do not create
8558  * a new global object from template, but we can reuse a global object.
8559  *
8560  * \param isolate See v8::Context::New.
8561  *
8562  * \param context_snapshot_index The index of the context snapshot to
8563  * deserialize from. Use v8::Context::New for the default snapshot.
8564  *
8565  * \param embedder_fields_deserializer Optional callback to deserialize
8566  * internal fields. It should match the SerializeInternalFieldCallback used
8567  * to serialize.
8568  *
8569  * \param extensions See v8::Context::New.
8570  *
8571  * \param global_object See v8::Context::New.
8572  */
8573 
8575  Isolate* isolate, size_t context_snapshot_index,
8576  DeserializeInternalFieldsCallback embedder_fields_deserializer =
8578  ExtensionConfiguration* extensions = nullptr,
8579  MaybeLocal<Value> global_object = MaybeLocal<Value>());
8580 
8581  /**
8582  * Returns an global object that isn't backed by an actual context.
8583  *
8584  * The global template needs to have access checks with handlers installed.
8585  * If an existing global object is passed in, the global object is detached
8586  * from its context.
8587  *
8588  * Note that this is different from a detached context where all accesses to
8589  * the global proxy will fail. Instead, the access check handlers are invoked.
8590  *
8591  * It is also not possible to detach an object returned by this method.
8592  * Instead, the access check handlers need to return nothing to achieve the
8593  * same effect.
8594  *
8595  * It is possible, however, to create a new context from the global object
8596  * returned by this method.
8597  */
8599  Isolate* isolate, Local<ObjectTemplate> global_template,
8600  MaybeLocal<Value> global_object = MaybeLocal<Value>());
8601 
8602  /**
8603  * Sets the security token for the context. To access an object in
8604  * another context, the security tokens must match.
8605  */
8607 
8608  /** Restores the security token to the default value. */
8610 
8611  /** Returns the security token of this context.*/
8613 
8614  /**
8615  * Enter this context. After entering a context, all code compiled
8616  * and run is compiled and run in this context. If another context
8617  * is already entered, this old context is saved so it can be
8618  * restored when the new context is exited.
8619  */
8620  void Enter();
8621 
8622  /**
8623  * Exit this context. Exiting the current context restores the
8624  * context that was in place when entering the current context.
8625  */
8626  void Exit();
8627 
8628  /** Returns an isolate associated with a current context. */
8630 
8631  /**
8632  * The field at kDebugIdIndex used to be reserved for the inspector.
8633  * It now serves no purpose.
8634  */
8636 
8637  /**
8638  * Gets the embedder data with the given index, which must have been set by a
8639  * previous call to SetEmbedderData with the same index.
8640  */
8641  V8_INLINE Local<Value> GetEmbedderData(int index);
8642 
8643  /**
8644  * Gets the binding object used by V8 extras. Extra natives get a reference
8645  * to this object and can use it to "export" functionality by adding
8646  * properties. Extra natives can also "import" functionality by accessing
8647  * properties added by the embedder using the V8 API.
8648  */
8650 
8651  /**
8652  * Sets the embedder data with the given index, growing the data as
8653  * needed. Note that index 0 currently has a special meaning for Chrome's
8654  * debugger.
8655  */
8656  void SetEmbedderData(int index, Local<Value> value);
8657 
8658  /**
8659  * Gets a 2-byte-aligned native pointer from the embedder data with the given
8660  * index, which must have been set by a previous call to
8661  * SetAlignedPointerInEmbedderData with the same index. Note that index 0
8662  * currently has a special meaning for Chrome's debugger.
8663  */
8665 
8666  /**
8667  * Sets a 2-byte-aligned native pointer in the embedder data with the given
8668  * index, growing the data as needed. Note that index 0 currently has a
8669  * special meaning for Chrome's debugger.
8670  */
8671  void SetAlignedPointerInEmbedderData(int index, void* value);
8672 
8673  /**
8674  * Control whether code generation from strings is allowed. Calling
8675  * this method with false will disable 'eval' and the 'Function'
8676  * constructor for code running in this context. If 'eval' or the
8677  * 'Function' constructor are used an exception will be thrown.
8678  *
8679  * If code generation from strings is not allowed the
8680  * V8::AllowCodeGenerationFromStrings callback will be invoked if
8681  * set before blocking the call to 'eval' or the 'Function'
8682  * constructor. If that callback returns true, the call will be
8683  * allowed, otherwise an exception will be thrown. If no callback is
8684  * set an exception will be thrown.
8685  */
8687 
8688  /**
8689  * Returns true if code generation from strings is allowed for the context.
8690  * For more details see AllowCodeGenerationFromStrings(bool) documentation.
8691  */
8693 
8694  /**
8695  * Sets the error description for the exception that is thrown when
8696  * code generation from strings is not allowed and 'eval' or the 'Function'
8697  * constructor are called.
8698  */
8700 
8701  /**
8702  * Estimate the memory in bytes retained by this context.
8703  */
8704  V8_DEPRECATED("no longer supported", size_t EstimatedSize());
8705 
8706  /**
8707  * Stack-allocated class which sets the execution context for all
8708  * operations executed within a local scope.
8709  */
8710  class Scope {
8711  public:
8712  explicit V8_INLINE Scope(Local<Context> context) : context_(context) {
8713  context_->Enter();
8714  }
8715  V8_INLINE ~Scope() { context_->Exit(); }
8716 
8717  private:
8718  Local<Context> context_;
8719  };
8720 
8721  /**
8722  * Stack-allocated class to support the backup incumbent settings object
8723  * stack.
8724  * https://html.spec.whatwg.org/multipage/webappapis.html#backup-incumbent-settings-object-stack
8725  */
8727  public:
8728  /**
8729  * |backup_incumbent_context| is pushed onto the backup incumbent settings
8730  * object stack.
8731  */
8732  explicit BackupIncumbentScope(Local<Context> backup_incumbent_context);
8734 
8735  private:
8736  friend class internal::Isolate;
8737 
8738  Local<Context> backup_incumbent_context_;
8739  const BackupIncumbentScope* prev_ = nullptr;
8740  };
8741 
8742  private:
8743  friend class Value;
8744  friend class Script;
8745  friend class Object;
8746  friend class Function;
8747 
8748  Local<Value> SlowGetEmbedderData(int index);
8749  void* SlowGetAlignedPointerFromEmbedderData(int index);
8750 };
8751 
8752 
8753 /**
8754  * Multiple threads in V8 are allowed, but only one thread at a time is allowed
8755  * to use any given V8 isolate, see the comments in the Isolate class. The
8756  * definition of 'using a V8 isolate' includes accessing handles or holding onto
8757  * object pointers obtained from V8 handles while in the particular V8 isolate.
8758  * It is up to the user of V8 to ensure, perhaps with locking, that this
8759  * constraint is not violated. In addition to any other synchronization
8760  * mechanism that may be used, the v8::Locker and v8::Unlocker classes must be
8761  * used to signal thread switches to V8.
8762  *
8763  * v8::Locker is a scoped lock object. While it's active, i.e. between its
8764  * construction and destruction, the current thread is allowed to use the locked
8765  * isolate. V8 guarantees that an isolate can be locked by at most one thread at
8766  * any time. In other words, the scope of a v8::Locker is a critical section.
8767  *
8768  * Sample usage:
8769 * \code
8770  * ...
8771  * {
8772  * v8::Locker locker(isolate);
8773  * v8::Isolate::Scope isolate_scope(isolate);
8774  * ...
8775  * // Code using V8 and isolate goes here.
8776  * ...
8777  * } // Destructor called here
8778  * \endcode
8779  *
8780  * If you wish to stop using V8 in a thread A you can do this either by
8781  * destroying the v8::Locker object as above or by constructing a v8::Unlocker
8782  * object:
8783  *
8784  * \code
8785  * {
8786  * isolate->Exit();
8787  * v8::Unlocker unlocker(isolate);
8788  * ...
8789  * // Code not using V8 goes here while V8 can run in another thread.
8790  * ...
8791  * } // Destructor called here.
8792  * isolate->Enter();
8793  * \endcode
8794  *
8795  * The Unlocker object is intended for use in a long-running callback from V8,
8796  * where you want to release the V8 lock for other threads to use.
8797  *
8798  * The v8::Locker is a recursive lock, i.e. you can lock more than once in a
8799  * given thread. This can be useful if you have code that can be called either
8800  * from code that holds the lock or from code that does not. The Unlocker is
8801  * not recursive so you can not have several Unlockers on the stack at once, and
8802  * you can not use an Unlocker in a thread that is not inside a Locker's scope.
8803  *
8804  * An unlocker will unlock several lockers if it has to and reinstate the
8805  * correct depth of locking on its destruction, e.g.:
8806  *
8807  * \code
8808  * // V8 not locked.
8809  * {
8810  * v8::Locker locker(isolate);
8811  * Isolate::Scope isolate_scope(isolate);
8812  * // V8 locked.
8813  * {
8814  * v8::Locker another_locker(isolate);
8815  * // V8 still locked (2 levels).
8816  * {
8817  * isolate->Exit();
8818  * v8::Unlocker unlocker(isolate);
8819  * // V8 not locked.
8820  * }
8821  * isolate->Enter();
8822  * // V8 locked again (2 levels).
8823  * }
8824  * // V8 still locked (1 level).
8825  * }
8826  * // V8 Now no longer locked.
8827  * \endcode
8828  */
8830  public:
8831  /**
8832  * Initialize Unlocker for a given Isolate.
8833  */
8834  V8_INLINE explicit Unlocker(Isolate* isolate) { Initialize(isolate); }
8835 
8837  private:
8838  void Initialize(Isolate* isolate);
8839 
8840  internal::Isolate* isolate_;
8841 };
8842 
8843 
8845  public:
8846  /**
8847  * Initialize Locker for a given Isolate.
8848  */
8849  V8_INLINE explicit Locker(Isolate* isolate) { Initialize(isolate); }
8850 
8852 
8853  /**
8854  * Returns whether or not the locker for a given isolate, is locked by the
8855  * current thread.
8856  */
8857  static bool IsLocked(Isolate* isolate);
8858 
8859  /**
8860  * Returns whether v8::Locker is being used by this V8 instance.
8861  */
8862  static bool IsActive();
8863 
8864  // Disallow copying and assigning.
8865  Locker(const Locker&) = delete;
8866  void operator=(const Locker&) = delete;
8867 
8868  private:
8869  void Initialize(Isolate* isolate);
8870 
8871  bool has_lock_;
8872  bool top_level_;
8873  internal::Isolate* isolate_;
8874 };
8875 
8876 
8877 // --- Implementation ---
8878 
8879 
8880 namespace internal {
8881 
8882 const int kApiPointerSize = sizeof(void*); // NOLINT
8883 const int kApiIntSize = sizeof(int); // NOLINT
8884 const int kApiInt64Size = sizeof(int64_t); // NOLINT
8885 
8886 // Tag information for HeapObject.
8887 const int kHeapObjectTag = 1;
8888 const int kHeapObjectTagSize = 2;
8889 const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
8890 
8891 // Tag information for Smi.
8892 const int kSmiTag = 0;
8893 const int kSmiTagSize = 1;
8894 const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
8895 
8896 template <size_t ptr_size> struct SmiTagging;
8897 
8898 template<int kSmiShiftSize>
8899 V8_INLINE internal::Object* IntToSmi(int value) {
8900  int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
8901  uintptr_t tagged_value =
8902  (static_cast<uintptr_t>(value) << smi_shift_bits) | kSmiTag;
8903  return reinterpret_cast<internal::Object*>(tagged_value);
8904 }
8905 
8906 // Smi constants for 32-bit systems.
8907 template <> struct SmiTagging<4> {
8908  enum { kSmiShiftSize = 0, kSmiValueSize = 31 };
8909  static int SmiShiftSize() { return kSmiShiftSize; }
8910  static int SmiValueSize() { return kSmiValueSize; }
8911  V8_INLINE static int SmiToInt(const internal::Object* value) {
8912  int shift_bits = kSmiTagSize + kSmiShiftSize;
8913  // Throw away top 32 bits and shift down (requires >> to be sign extending).
8914  return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
8915  }
8916  V8_INLINE static internal::Object* IntToSmi(int value) {
8918  }
8919  V8_INLINE static bool IsValidSmi(intptr_t value) {
8920  // To be representable as an tagged small integer, the two
8921  // most-significant bits of 'value' must be either 00 or 11 due to
8922  // sign-extension. To check this we add 01 to the two
8923  // most-significant bits, and check if the most-significant bit is 0
8924  //
8925  // CAUTION: The original code below:
8926  // bool result = ((value + 0x40000000) & 0x80000000) == 0;
8927  // may lead to incorrect results according to the C language spec, and
8928  // in fact doesn't work correctly with gcc4.1.1 in some cases: The
8929  // compiler may produce undefined results in case of signed integer
8930  // overflow. The computation must be done w/ unsigned ints.
8931  return static_cast<uintptr_t>(value + 0x40000000U) < 0x80000000U;
8932  }
8933 };
8934 
8935 // Smi constants for 64-bit systems.
8936 template <> struct SmiTagging<8> {
8937  enum { kSmiShiftSize = 31, kSmiValueSize = 32 };
8938  static int SmiShiftSize() { return kSmiShiftSize; }
8939  static int SmiValueSize() { return kSmiValueSize; }
8940  V8_INLINE static int SmiToInt(const internal::Object* value) {
8941  int shift_bits = kSmiTagSize + kSmiShiftSize;
8942  // Shift down and throw away top 32 bits.
8943  return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
8944  }
8945  V8_INLINE static internal::Object* IntToSmi(int value) {
8947  }
8948  V8_INLINE static bool IsValidSmi(intptr_t value) {
8949  // To be representable as a long smi, the value must be a 32-bit integer.
8950  return (value == static_cast<int32_t>(value));
8951  }
8952 };
8953 
8957 V8_INLINE static bool SmiValuesAre31Bits() { return kSmiValueSize == 31; }
8958 V8_INLINE static bool SmiValuesAre32Bits() { return kSmiValueSize == 32; }
8959 
8960 /**
8961  * This class exports constants and functionality from within v8 that
8962  * is necessary to implement inline functions in the v8 api. Don't
8963  * depend on functions and constants defined here.
8964  */
8965 class Internals {
8966  public:
8967  // These values match non-compiler-dependent values defined within
8968  // the implementation of v8.
8969  static const int kHeapObjectMapOffset = 0;
8972  static const int kStringResourceOffset = 3 * kApiPointerSize;
8973 
8974  static const int kOddballKindOffset = 4 * kApiPointerSize + sizeof(double);
8976  static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
8977  static const int kFixedArrayHeaderSize = 2 * kApiPointerSize;
8978  static const int kContextHeaderSize = 2 * kApiPointerSize;
8979  static const int kContextEmbedderDataIndex = 5;
8980  static const int kFullStringRepresentationMask = 0x0f;
8981  static const int kStringEncodingMask = 0x8;
8982  static const int kExternalTwoByteRepresentationTag = 0x02;
8983  static const int kExternalOneByteRepresentationTag = 0x0a;
8984 
8986  static const int kExternalMemoryOffset = 4 * kApiPointerSize;
8987  static const int kExternalMemoryLimitOffset =
8994  static const int kUndefinedValueRootIndex = 4;
8995  static const int kTheHoleValueRootIndex = 5;
8996  static const int kNullValueRootIndex = 6;
8997  static const int kTrueValueRootIndex = 7;
8998  static const int kFalseValueRootIndex = 8;
8999  static const int kEmptyStringRootIndex = 9;
9000 
9001  static const int kNodeClassIdOffset = 1 * kApiPointerSize;
9002  static const int kNodeFlagsOffset = 1 * kApiPointerSize + 3;
9003  static const int kNodeStateMask = 0x7;
9004  static const int kNodeStateIsWeakValue = 2;
9005  static const int kNodeStateIsPendingValue = 3;
9006  static const int kNodeStateIsNearDeathValue = 4;
9007  static const int kNodeIsIndependentShift = 3;
9008  static const int kNodeIsActiveShift = 4;
9009 
9010  static const int kJSApiObjectType = 0xbd;
9011  static const int kJSObjectType = 0xbe;
9012  static const int kFirstNonstringType = 0x80;
9013  static const int kOddballType = 0x82;
9014  static const int kForeignType = 0x86;
9015 
9016  static const int kUndefinedOddballKind = 5;
9017  static const int kNullOddballKind = 3;
9018 
9019  static const uint32_t kNumIsolateDataSlots = 4;
9020 
9021  V8_EXPORT static void CheckInitializedImpl(v8::Isolate* isolate);
9022  V8_INLINE static void CheckInitialized(v8::Isolate* isolate) {
9023 #ifdef V8_ENABLE_CHECKS
9024  CheckInitializedImpl(isolate);
9025 #endif
9026  }
9027 
9028  V8_INLINE static bool HasHeapObjectTag(const internal::Object* value) {
9029  return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
9030  kHeapObjectTag);
9031  }
9032 
9033  V8_INLINE static int SmiValue(const internal::Object* value) {
9034  return PlatformSmiTagging::SmiToInt(value);
9035  }
9036 
9037  V8_INLINE static internal::Object* IntToSmi(int value) {
9038  return PlatformSmiTagging::IntToSmi(value);
9039  }
9040 
9041  V8_INLINE static bool IsValidSmi(intptr_t value) {
9043  }
9044 
9045  V8_INLINE static int GetInstanceType(const internal::Object* obj) {
9046  typedef internal::Object O;
9048  // Map::InstanceType is defined so that it will always be loaded into
9049  // the LS 8 bits of one 16-bit word, regardless of endianess.
9050  return ReadField<uint16_t>(map, kMapInstanceTypeAndBitFieldOffset) & 0xff;
9051  }
9052 
9053  V8_INLINE static int GetOddballKind(const internal::Object* obj) {
9054  typedef internal::Object O;
9056  }
9057 
9058  V8_INLINE static bool IsExternalTwoByteString(int instance_type) {
9059  int representation = (instance_type & kFullStringRepresentationMask);
9060  return representation == kExternalTwoByteRepresentationTag;
9061  }
9062 
9063  V8_INLINE static uint8_t GetNodeFlag(internal::Object** obj, int shift) {
9064  uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
9065  return *addr & static_cast<uint8_t>(1U << shift);
9066  }
9067 
9068  V8_INLINE static void UpdateNodeFlag(internal::Object** obj,
9069  bool value, int shift) {
9070  uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
9071  uint8_t mask = static_cast<uint8_t>(1U << shift);
9072  *addr = static_cast<uint8_t>((*addr & ~mask) | (value << shift));
9073  }
9074 
9075  V8_INLINE static uint8_t GetNodeState(internal::Object** obj) {
9076  uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
9077  return *addr & kNodeStateMask;
9078  }
9079 
9080  V8_INLINE static void UpdateNodeState(internal::Object** obj,
9081  uint8_t value) {
9082  uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
9083  *addr = static_cast<uint8_t>((*addr & ~kNodeStateMask) | value);
9084  }
9085 
9086  V8_INLINE static void SetEmbedderData(v8::Isolate* isolate,
9087  uint32_t slot,
9088  void* data) {
9089  uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) +
9091  *reinterpret_cast<void**>(addr) = data;
9092  }
9093 
9094  V8_INLINE static void* GetEmbedderData(const v8::Isolate* isolate,
9095  uint32_t slot) {
9096  const uint8_t* addr = reinterpret_cast<const uint8_t*>(isolate) +
9098  return *reinterpret_cast<void* const*>(addr);
9099  }
9100 
9101  V8_INLINE static internal::Object** GetRoot(v8::Isolate* isolate,
9102  int index) {
9103  uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) + kIsolateRootsOffset;
9104  return reinterpret_cast<internal::Object**>(addr + index * kApiPointerSize);
9105  }
9106 
9107  template <typename T>
9108  V8_INLINE static T ReadField(const internal::Object* ptr, int offset) {
9109  const uint8_t* addr =
9110  reinterpret_cast<const uint8_t*>(ptr) + offset - kHeapObjectTag;
9111  return *reinterpret_cast<const T*>(addr);
9112  }
9113 
9114  template <typename T>
9115  V8_INLINE static T ReadEmbedderData(const v8::Context* context, int index) {
9116  typedef internal::Object O;
9117  typedef internal::Internals I;
9118  O* ctx = *reinterpret_cast<O* const*>(context);
9119  int embedder_data_offset = I::kContextHeaderSize +
9121  O* embedder_data = I::ReadField<O*>(ctx, embedder_data_offset);
9122  int value_offset =
9124  return I::ReadField<T>(embedder_data, value_offset);
9125  }
9126 };
9127 
9128 } // namespace internal
9129 
9130 
9131 template <class T>
9132 Local<T> Local<T>::New(Isolate* isolate, Local<T> that) {
9133  return New(isolate, that.val_);
9134 }
9135 
9136 template <class T>
9137 Local<T> Local<T>::New(Isolate* isolate, const PersistentBase<T>& that) {
9138  return New(isolate, that.val_);
9139 }
9140 
9141 
9142 template <class T>
9143 Local<T> Local<T>::New(Isolate* isolate, T* that) {
9144  if (that == NULL) return Local<T>();
9145  T* that_ptr = that;
9146  internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
9147  return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
9148  reinterpret_cast<internal::Isolate*>(isolate), *p)));
9149 }
9150 
9151 
9152 template<class T>
9153 template<class S>
9154 void Eternal<T>::Set(Isolate* isolate, Local<S> handle) {
9155  TYPE_CHECK(T, S);
9156  val_ = reinterpret_cast<T*>(
9157  V8::Eternalize(isolate, reinterpret_cast<Value*>(*handle)));
9158 }
9159 
9160 template <class T>
9161 Local<T> Eternal<T>::Get(Isolate* isolate) const {
9162  // The eternal handle will never go away, so as with the roots, we don't even
9163  // need to open a handle.
9164  return Local<T>(val_);
9165 }
9166 
9167 
9168 template <class T>
9170  if (V8_UNLIKELY(val_ == nullptr)) V8::ToLocalEmpty();
9171  return Local<T>(val_);
9172 }
9173 
9174 
9175 template <class T>
9176 void* WeakCallbackInfo<T>::GetInternalField(int index) const {
9177 #ifdef V8_ENABLE_CHECKS
9178  if (index < 0 || index >= kEmbedderFieldsInWeakCallback) {
9179  V8::InternalFieldOutOfBounds(index);
9180  }
9181 #endif
9182  return embedder_fields_[index];
9183 }
9184 
9185 
9186 template <class T>
9187 T* PersistentBase<T>::New(Isolate* isolate, T* that) {
9188  if (that == NULL) return NULL;
9189  internal::Object** p = reinterpret_cast<internal::Object**>(that);
9190  return reinterpret_cast<T*>(
9191  V8::GlobalizeReference(reinterpret_cast<internal::Isolate*>(isolate),
9192  p));
9193 }
9194 
9195 
9196 template <class T, class M>
9197 template <class S, class M2>
9198 void Persistent<T, M>::Copy(const Persistent<S, M2>& that) {
9199  TYPE_CHECK(T, S);
9200  this->Reset();
9201  if (that.IsEmpty()) return;
9202  internal::Object** p = reinterpret_cast<internal::Object**>(that.val_);
9203  this->val_ = reinterpret_cast<T*>(V8::CopyPersistent(p));
9204  M::Copy(that, this);
9205 }
9206 
9207 
9208 template <class T>
9209 bool PersistentBase<T>::IsIndependent() const {
9210  typedef internal::Internals I;
9211  if (this->IsEmpty()) return false;
9212  return I::GetNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
9214 }
9215 
9216 
9217 template <class T>
9218 bool PersistentBase<T>::IsNearDeath() const {
9219  typedef internal::Internals I;
9220  if (this->IsEmpty()) return false;
9221  uint8_t node_state =
9222  I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_));
9223  return node_state == I::kNodeStateIsNearDeathValue ||
9224  node_state == I::kNodeStateIsPendingValue;
9225 }
9226 
9227 
9228 template <class T>
9229 bool PersistentBase<T>::IsWeak() const {
9230  typedef internal::Internals I;
9231  if (this->IsEmpty()) return false;
9232  return I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_)) ==
9234 }
9235 
9236 
9237 template <class T>
9238 void PersistentBase<T>::Reset() {
9239  if (this->IsEmpty()) return;
9240  V8::DisposeGlobal(reinterpret_cast<internal::Object**>(this->val_));
9241  val_ = 0;
9242 }
9243 
9244 
9245 template <class T>
9246 template <class S>
9247 void PersistentBase<T>::Reset(Isolate* isolate, const Local<S>& other) {
9248  TYPE_CHECK(T, S);
9249  Reset();
9250  if (other.IsEmpty()) return;
9251  this->val_ = New(isolate, other.val_);
9252 }
9253 
9254 
9255 template <class T>
9256 template <class S>
9257 void PersistentBase<T>::Reset(Isolate* isolate,
9258  const PersistentBase<S>& other) {
9259  TYPE_CHECK(T, S);
9260  Reset();
9261  if (other.IsEmpty()) return;
9262  this->val_ = New(isolate, other.val_);
9263 }
9264 
9265 
9266 template <class T>
9267 template <typename P>
9269  P* parameter, typename WeakCallbackInfo<P>::Callback callback,
9270  WeakCallbackType type) {
9271  typedef typename WeakCallbackInfo<void>::Callback Callback;
9272  V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter,
9273  reinterpret_cast<Callback>(callback), type);
9274 }
9275 
9276 template <class T>
9278  V8::MakeWeak(reinterpret_cast<internal::Object***>(&this->val_));
9279 }
9280 
9281 template <class T>
9282 template <typename P>
9283 P* PersistentBase<T>::ClearWeak() {
9284  return reinterpret_cast<P*>(
9285  V8::ClearWeak(reinterpret_cast<internal::Object**>(this->val_)));
9286 }
9287 
9288 template <class T>
9290  if (IsEmpty()) return;
9291  V8::RegisterExternallyReferencedObject(
9292  reinterpret_cast<internal::Object**>(this->val_),
9293  reinterpret_cast<internal::Isolate*>(isolate));
9294 }
9295 
9296 template <class T>
9298  typedef internal::Internals I;
9299  if (this->IsEmpty()) return;
9300  I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
9301  true,
9303 }
9304 
9305 template <class T>
9307  typedef internal::Internals I;
9308  if (this->IsEmpty()) return;
9309  I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_), true,
9311 }
9312 
9313 
9314 template <class T>
9315 void PersistentBase<T>::SetWrapperClassId(uint16_t class_id) {
9316  typedef internal::Internals I;
9317  if (this->IsEmpty()) return;
9318  internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
9319  uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
9320  *reinterpret_cast<uint16_t*>(addr) = class_id;
9321 }
9322 
9323 
9324 template <class T>
9325 uint16_t PersistentBase<T>::WrapperClassId() const {
9326  typedef internal::Internals I;
9327  if (this->IsEmpty()) return 0;
9328  internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
9329  uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
9330  return *reinterpret_cast<uint16_t*>(addr);
9331 }
9332 
9333 
9334 template<typename T>
9335 ReturnValue<T>::ReturnValue(internal::Object** slot) : value_(slot) {}
9336 
9337 template<typename T>
9338 template<typename S>
9339 void ReturnValue<T>::Set(const Persistent<S>& handle) {
9340  TYPE_CHECK(T, S);
9341  if (V8_UNLIKELY(handle.IsEmpty())) {
9342  *value_ = GetDefaultValue();
9343  } else {
9344  *value_ = *reinterpret_cast<internal::Object**>(*handle);
9345  }
9346 }
9347 
9348 template <typename T>
9349 template <typename S>
9350 void ReturnValue<T>::Set(const Global<S>& handle) {
9351  TYPE_CHECK(T, S);
9352  if (V8_UNLIKELY(handle.IsEmpty())) {
9353  *value_ = GetDefaultValue();
9354  } else {
9355  *value_ = *reinterpret_cast<internal::Object**>(*handle);
9356  }
9357 }
9358 
9359 template <typename T>
9360 template <typename S>
9361 void ReturnValue<T>::Set(const Local<S> handle) {
9362  TYPE_CHECK(T, S);
9363  if (V8_UNLIKELY(handle.IsEmpty())) {
9364  *value_ = GetDefaultValue();
9365  } else {
9366  *value_ = *reinterpret_cast<internal::Object**>(*handle);
9367  }
9368 }
9369 
9370 template<typename T>
9371 void ReturnValue<T>::Set(double i) {
9372  TYPE_CHECK(T, Number);
9374 }
9375 
9376 template<typename T>
9377 void ReturnValue<T>::Set(int32_t i) {
9378  TYPE_CHECK(T, Integer);
9379  typedef internal::Internals I;
9380  if (V8_LIKELY(I::IsValidSmi(i))) {
9381  *value_ = I::IntToSmi(i);
9382  return;
9383  }
9385 }
9386 
9387 template<typename T>
9388 void ReturnValue<T>::Set(uint32_t i) {
9389  TYPE_CHECK(T, Integer);
9390  // Can't simply use INT32_MAX here for whatever reason.
9391  bool fits_into_int32_t = (i & (1U << 31)) == 0;
9392  if (V8_LIKELY(fits_into_int32_t)) {
9393  Set(static_cast<int32_t>(i));
9394  return;
9395  }
9397 }
9398 
9399 template<typename T>
9400 void ReturnValue<T>::Set(bool value) {
9401  TYPE_CHECK(T, Boolean);
9402  typedef internal::Internals I;
9403  int root_index;
9404  if (value) {
9405  root_index = I::kTrueValueRootIndex;
9406  } else {
9407  root_index = I::kFalseValueRootIndex;
9408  }
9409  *value_ = *I::GetRoot(GetIsolate(), root_index);
9410 }
9411 
9412 template<typename T>
9413 void ReturnValue<T>::SetNull() {
9414  TYPE_CHECK(T, Primitive);
9415  typedef internal::Internals I;
9417 }
9418 
9419 template<typename T>
9421  TYPE_CHECK(T, Primitive);
9422  typedef internal::Internals I;
9424 }
9425 
9426 template<typename T>
9428  TYPE_CHECK(T, String);
9429  typedef internal::Internals I;
9431 }
9432 
9433 template <typename T>
9435  // Isolate is always the pointer below the default value on the stack.
9436  return *reinterpret_cast<Isolate**>(&value_[-2]);
9437 }
9438 
9439 template <typename T>
9440 Local<Value> ReturnValue<T>::Get() const {
9441  typedef internal::Internals I;
9443  return Local<Value>(*Undefined(GetIsolate()));
9444  return Local<Value>::New(GetIsolate(), reinterpret_cast<Value*>(value_));
9445 }
9446 
9447 template <typename T>
9448 template <typename S>
9449 void ReturnValue<T>::Set(S* whatever) {
9450  // Uncompilable to prevent inadvertent misuse.
9451  TYPE_CHECK(S*, Primitive);
9452 }
9453 
9454 template<typename T>
9455 internal::Object* ReturnValue<T>::GetDefaultValue() {
9456  // Default value is always the pointer below value_ on the stack.
9457  return value_[-1];
9458 }
9459 
9460 template <typename T>
9462  internal::Object** values,
9463  int length)
9464  : implicit_args_(implicit_args), values_(values), length_(length) {}
9465 
9466 template<typename T>
9468  if (i < 0 || length_ <= i) return Local<Value>(*Undefined(GetIsolate()));
9469  return Local<Value>(reinterpret_cast<Value*>(values_ - i));
9470 }
9471 
9472 
9473 template<typename T>
9474 Local<Function> FunctionCallbackInfo<T>::Callee() const {
9475  return Local<Function>(reinterpret_cast<Function*>(
9477 }
9478 
9479 
9480 template<typename T>
9482  return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
9483 }
9484 
9485 
9486 template<typename T>
9488  return Local<Object>(reinterpret_cast<Object*>(
9490 }
9491 
9492 template <typename T>
9494  return Local<Value>(
9495  reinterpret_cast<Value*>(&implicit_args_[kNewTargetIndex]));
9496 }
9497 
9498 template <typename T>
9500  return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
9501 }
9502 
9503 
9504 template<typename T>
9506  return *reinterpret_cast<Isolate**>(&implicit_args_[kIsolateIndex]);
9507 }
9508 
9509 
9510 template<typename T>
9513 }
9514 
9515 
9516 template<typename T>
9518  return !NewTarget()->IsUndefined();
9519 }
9520 
9521 
9522 template<typename T>
9523 int FunctionCallbackInfo<T>::Length() const {
9524  return length_;
9525 }
9526 
9528  Local<Integer> resource_line_offset,
9529  Local<Integer> resource_column_offset,
9530  Local<Boolean> resource_is_shared_cross_origin,
9531  Local<Integer> script_id,
9532  Local<Value> source_map_url,
9533  Local<Boolean> resource_is_opaque,
9534  Local<Boolean> is_wasm, Local<Boolean> is_module)
9535  : resource_name_(resource_name),
9536  resource_line_offset_(resource_line_offset),
9537  resource_column_offset_(resource_column_offset),
9538  options_(!resource_is_shared_cross_origin.IsEmpty() &&
9539  resource_is_shared_cross_origin->IsTrue(),
9540  !resource_is_opaque.IsEmpty() && resource_is_opaque->IsTrue(),
9541  !is_wasm.IsEmpty() && is_wasm->IsTrue(),
9542  !is_module.IsEmpty() && is_module->IsTrue()),
9543  script_id_(script_id),
9544  source_map_url_(source_map_url) {}
9545 
9546 Local<Value> ScriptOrigin::ResourceName() const { return resource_name_; }
9547 
9548 
9550  return resource_line_offset_;
9551 }
9552 
9553 
9555  return resource_column_offset_;
9556 }
9557 
9558 
9559 Local<Integer> ScriptOrigin::ScriptID() const { return script_id_; }
9560 
9561 
9562 Local<Value> ScriptOrigin::SourceMapUrl() const { return source_map_url_; }
9563 
9564 
9566  CachedData* data)
9567  : source_string(string),
9568  resource_name(origin.ResourceName()),
9569  resource_line_offset(origin.ResourceLineOffset()),
9570  resource_column_offset(origin.ResourceColumnOffset()),
9571  resource_options(origin.Options()),
9572  source_map_url(origin.SourceMapUrl()),
9573  cached_data(data) {}
9574 
9575 
9577  CachedData* data)
9578  : source_string(string), cached_data(data) {}
9579 
9580 
9582  delete cached_data;
9583 }
9584 
9585 
9587  const {
9588  return cached_data;
9589 }
9590 
9592  return resource_options;
9593 }
9594 
9595 Local<Boolean> Boolean::New(Isolate* isolate, bool value) {
9596  return value ? True(isolate) : False(isolate);
9597 }
9598 
9599 void Template::Set(Isolate* isolate, const char* name, Local<Data> value) {
9602  value);
9603 }
9604 
9605 
9607 #ifndef V8_ENABLE_CHECKS
9608  typedef internal::Object O;
9609  typedef internal::HeapObject HO;
9610  typedef internal::Internals I;
9611  O* obj = *reinterpret_cast<O**>(this);
9612  // Fast path: If the object is a plain JSObject, which is the common case, we
9613  // know where to find the internal fields and can return the value directly.
9614  auto instance_type = I::GetInstanceType(obj);
9615  if (instance_type == I::kJSObjectType ||
9616  instance_type == I::kJSApiObjectType) {
9617  int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
9618  O* value = I::ReadField<O*>(obj, offset);
9619  O** result = HandleScope::CreateHandle(reinterpret_cast<HO*>(obj), value);
9620  return Local<Value>(reinterpret_cast<Value*>(result));
9621  }
9622 #endif
9623  return SlowGetInternalField(index);
9624 }
9625 
9626 
9628 #ifndef V8_ENABLE_CHECKS
9629  typedef internal::Object O;
9630  typedef internal::Internals I;
9631  O* obj = *reinterpret_cast<O**>(this);
9632  // Fast path: If the object is a plain JSObject, which is the common case, we
9633  // know where to find the internal fields and can return the value directly.
9634  auto instance_type = I::GetInstanceType(obj);
9635  if (V8_LIKELY(instance_type == I::kJSObjectType ||
9636  instance_type == I::kJSApiObjectType)) {
9637  int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
9638  return I::ReadField<void*>(obj, offset);
9639  }
9640 #endif
9641  return SlowGetAlignedPointerFromInternalField(index);
9642 }
9643 
9644 String* String::Cast(v8::Value* value) {
9645 #ifdef V8_ENABLE_CHECKS
9646  CheckCast(value);
9647 #endif
9648  return static_cast<String*>(value);
9649 }
9650 
9651 
9653  typedef internal::Object* S;
9654  typedef internal::Internals I;
9655  I::CheckInitialized(isolate);
9656  S* slot = I::GetRoot(isolate, I::kEmptyStringRootIndex);
9657  return Local<String>(reinterpret_cast<String*>(slot));
9658 }
9659 
9660 
9662  typedef internal::Object O;
9663  typedef internal::Internals I;
9664  O* obj = *reinterpret_cast<O* const*>(this);
9665  String::ExternalStringResource* result;
9667  void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
9668  result = reinterpret_cast<String::ExternalStringResource*>(value);
9669  } else {
9670  result = NULL;
9671  }
9672 #ifdef V8_ENABLE_CHECKS
9673  VerifyExternalStringResource(result);
9674 #endif
9675  return result;
9676 }
9677 
9678 
9680  String::Encoding* encoding_out) const {
9681  typedef internal::Object O;
9682  typedef internal::Internals I;
9683  O* obj = *reinterpret_cast<O* const*>(this);
9685  *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
9686  ExternalStringResourceBase* resource = NULL;
9687  if (type == I::kExternalOneByteRepresentationTag ||
9689  void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
9690  resource = static_cast<ExternalStringResourceBase*>(value);
9691  }
9692 #ifdef V8_ENABLE_CHECKS
9693  VerifyExternalStringResourceBase(resource, *encoding_out);
9694 #endif
9695  return resource;
9696 }
9697 
9698 
9699 bool Value::IsUndefined() const {
9700 #ifdef V8_ENABLE_CHECKS
9701  return FullIsUndefined();
9702 #else
9703  return QuickIsUndefined();
9704 #endif
9705 }
9706 
9707 bool Value::QuickIsUndefined() const {
9708  typedef internal::Object O;
9709  typedef internal::Internals I;
9710  O* obj = *reinterpret_cast<O* const*>(this);
9711  if (!I::HasHeapObjectTag(obj)) return false;
9712  if (I::GetInstanceType(obj) != I::kOddballType) return false;
9714 }
9715 
9716 
9717 bool Value::IsNull() const {
9718 #ifdef V8_ENABLE_CHECKS
9719  return FullIsNull();
9720 #else
9721  return QuickIsNull();
9722 #endif
9723 }
9724 
9725 bool Value::QuickIsNull() const {
9726  typedef internal::Object O;
9727  typedef internal::Internals I;
9728  O* obj = *reinterpret_cast<O* const*>(this);
9729  if (!I::HasHeapObjectTag(obj)) return false;
9730  if (I::GetInstanceType(obj) != I::kOddballType) return false;
9731  return (I::GetOddballKind(obj) == I::kNullOddballKind);
9732 }
9733 
9734 bool Value::IsNullOrUndefined() const {
9735 #ifdef V8_ENABLE_CHECKS
9736  return FullIsNull() || FullIsUndefined();
9737 #else
9738  return QuickIsNullOrUndefined();
9739 #endif
9740 }
9741 
9742 bool Value::QuickIsNullOrUndefined() const {
9743  typedef internal::Object O;
9744  typedef internal::Internals I;
9745  O* obj = *reinterpret_cast<O* const*>(this);
9746  if (!I::HasHeapObjectTag(obj)) return false;
9747  if (I::GetInstanceType(obj) != I::kOddballType) return false;
9748  int kind = I::GetOddballKind(obj);
9749  return kind == I::kNullOddballKind || kind == I::kUndefinedOddballKind;
9750 }
9751 
9752 bool Value::IsString() const {
9753 #ifdef V8_ENABLE_CHECKS
9754  return FullIsString();
9755 #else
9756  return QuickIsString();
9757 #endif
9758 }
9759 
9760 bool Value::QuickIsString() const {
9761  typedef internal::Object O;
9762  typedef internal::Internals I;
9763  O* obj = *reinterpret_cast<O* const*>(this);
9764  if (!I::HasHeapObjectTag(obj)) return false;
9766 }
9767 
9768 
9769 template <class T> Value* Value::Cast(T* value) {
9770  return static_cast<Value*>(value);
9771 }
9772 
9773 
9774 Local<Boolean> Value::ToBoolean() const {
9776  .FromMaybe(Local<Boolean>());
9777 }
9778 
9779 
9780 Local<Number> Value::ToNumber() const {
9782  .FromMaybe(Local<Number>());
9783 }
9784 
9785 
9786 Local<String> Value::ToString() const {
9788  .FromMaybe(Local<String>());
9789 }
9790 
9791 
9792 Local<String> Value::ToDetailString() const {
9794  .FromMaybe(Local<String>());
9795 }
9796 
9797 
9798 Local<Object> Value::ToObject() const {
9800  .FromMaybe(Local<Object>());
9801 }
9802 
9803 
9804 Local<Integer> Value::ToInteger() const {
9806  .FromMaybe(Local<Integer>());
9807 }
9808 
9809 
9810 Local<Uint32> Value::ToUint32() const {
9812  .FromMaybe(Local<Uint32>());
9813 }
9814 
9815 
9816 Local<Int32> Value::ToInt32() const {
9818  .FromMaybe(Local<Int32>());
9819 }
9820 
9821 
9823 #ifdef V8_ENABLE_CHECKS
9824  CheckCast(value);
9825 #endif
9826  return static_cast<Boolean*>(value);
9827 }
9828 
9829 
9830 Name* Name::Cast(v8::Value* value) {
9831 #ifdef V8_ENABLE_CHECKS
9832  CheckCast(value);
9833 #endif
9834  return static_cast<Name*>(value);
9835 }
9836 
9837 
9838 Symbol* Symbol::Cast(v8::Value* value) {
9839 #ifdef V8_ENABLE_CHECKS
9840  CheckCast(value);
9841 #endif
9842  return static_cast<Symbol*>(value);
9843 }
9844 
9845 
9846 Number* Number::Cast(v8::Value* value) {
9847 #ifdef V8_ENABLE_CHECKS
9848  CheckCast(value);
9849 #endif
9850  return static_cast<Number*>(value);
9851 }
9852 
9853 
9855 #ifdef V8_ENABLE_CHECKS
9856  CheckCast(value);
9857 #endif
9858  return static_cast<Integer*>(value);
9859 }
9860 
9861 
9862 Int32* Int32::Cast(v8::Value* value) {
9863 #ifdef V8_ENABLE_CHECKS
9864  CheckCast(value);
9865 #endif
9866  return static_cast<Int32*>(value);
9867 }
9868 
9869 
9870 Uint32* Uint32::Cast(v8::Value* value) {
9871 #ifdef V8_ENABLE_CHECKS
9872  CheckCast(value);
9873 #endif
9874  return static_cast<Uint32*>(value);
9875 }
9876 
9877 
9878 Date* Date::Cast(v8::Value* value) {
9879 #ifdef V8_ENABLE_CHECKS
9880  CheckCast(value);
9881 #endif
9882  return static_cast<Date*>(value);
9883 }
9884 
9885 
9887 #ifdef V8_ENABLE_CHECKS
9888  CheckCast(value);
9889 #endif
9890  return static_cast<StringObject*>(value);
9891 }
9892 
9893 
9895 #ifdef V8_ENABLE_CHECKS
9896  CheckCast(value);
9897 #endif
9898  return static_cast<SymbolObject*>(value);
9899 }
9900 
9901 
9903 #ifdef V8_ENABLE_CHECKS
9904  CheckCast(value);
9905 #endif
9906  return static_cast<NumberObject*>(value);
9907 }
9908 
9909 
9911 #ifdef V8_ENABLE_CHECKS
9912  CheckCast(value);
9913 #endif
9914  return static_cast<BooleanObject*>(value);
9915 }
9916 
9917 
9918 RegExp* RegExp::Cast(v8::Value* value) {
9919 #ifdef V8_ENABLE_CHECKS
9920  CheckCast(value);
9921 #endif
9922  return static_cast<RegExp*>(value);
9923 }
9924 
9925 
9926 Object* Object::Cast(v8::Value* value) {
9927 #ifdef V8_ENABLE_CHECKS
9928  CheckCast(value);
9929 #endif
9930  return static_cast<Object*>(value);
9931 }
9932 
9933 
9934 Array* Array::Cast(v8::Value* value) {
9935 #ifdef V8_ENABLE_CHECKS
9936  CheckCast(value);
9937 #endif
9938  return static_cast<Array*>(value);
9939 }
9940 
9941 
9942 Map* Map::Cast(v8::Value* value) {
9943 #ifdef V8_ENABLE_CHECKS
9944  CheckCast(value);
9945 #endif
9946  return static_cast<Map*>(value);
9947 }
9948 
9949 
9950 Set* Set::Cast(v8::Value* value) {
9951 #ifdef V8_ENABLE_CHECKS
9952  CheckCast(value);
9953 #endif
9954  return static_cast<Set*>(value);
9955 }
9956 
9957 
9959 #ifdef V8_ENABLE_CHECKS
9960  CheckCast(value);
9961 #endif
9962  return static_cast<Promise*>(value);
9963 }
9964 
9965 
9966 Proxy* Proxy::Cast(v8::Value* value) {
9967 #ifdef V8_ENABLE_CHECKS
9968  CheckCast(value);
9969 #endif
9970  return static_cast<Proxy*>(value);
9971 }
9972 
9974 #ifdef V8_ENABLE_CHECKS
9975  CheckCast(value);
9976 #endif
9977  return static_cast<WasmCompiledModule*>(value);
9978 }
9979 
9981 #ifdef V8_ENABLE_CHECKS
9982  CheckCast(value);
9983 #endif
9984  return static_cast<Promise::Resolver*>(value);
9985 }
9986 
9987 
9989 #ifdef V8_ENABLE_CHECKS
9990  CheckCast(value);
9991 #endif
9992  return static_cast<ArrayBuffer*>(value);
9993 }
9994 
9995 
9997 #ifdef V8_ENABLE_CHECKS
9998  CheckCast(value);
9999 #endif
10000  return static_cast<ArrayBufferView*>(value);
10001 }
10002 
10003 
10005 #ifdef V8_ENABLE_CHECKS
10006  CheckCast(value);
10007 #endif
10008  return static_cast<TypedArray*>(value);
10009 }
10010 
10011 
10013 #ifdef V8_ENABLE_CHECKS
10014  CheckCast(value);
10015 #endif
10016  return static_cast<Uint8Array*>(value);
10017 }
10018 
10019 
10021 #ifdef V8_ENABLE_CHECKS
10022  CheckCast(value);
10023 #endif
10024  return static_cast<Int8Array*>(value);
10025 }
10026 
10027 
10029 #ifdef V8_ENABLE_CHECKS
10030  CheckCast(value);
10031 #endif
10032  return static_cast<Uint16Array*>(value);
10033 }
10034 
10035 
10037 #ifdef V8_ENABLE_CHECKS
10038  CheckCast(value);
10039 #endif
10040  return static_cast<Int16Array*>(value);
10041 }
10042 
10043 
10045 #ifdef V8_ENABLE_CHECKS
10046  CheckCast(value);
10047 #endif
10048  return static_cast<Uint32Array*>(value);
10049 }
10050 
10051 
10053 #ifdef V8_ENABLE_CHECKS
10054  CheckCast(value);
10055 #endif
10056  return static_cast<Int32Array*>(value);
10057 }
10058 
10059 
10061 #ifdef V8_ENABLE_CHECKS
10062  CheckCast(value);
10063 #endif
10064  return static_cast<Float32Array*>(value);
10065 }
10066 
10067 
10069 #ifdef V8_ENABLE_CHECKS
10070  CheckCast(value);
10071 #endif
10072  return static_cast<Float64Array*>(value);
10073 }
10074 
10075 
10077 #ifdef V8_ENABLE_CHECKS
10078  CheckCast(value);
10079 #endif
10080  return static_cast<Uint8ClampedArray*>(value);
10081 }
10082 
10083 
10085 #ifdef V8_ENABLE_CHECKS
10086  CheckCast(value);
10087 #endif
10088  return static_cast<DataView*>(value);
10089 }
10090 
10091 
10093 #ifdef V8_ENABLE_CHECKS
10094  CheckCast(value);
10095 #endif
10096  return static_cast<SharedArrayBuffer*>(value);
10097 }
10098 
10099 
10101 #ifdef V8_ENABLE_CHECKS
10102  CheckCast(value);
10103 #endif
10104  return static_cast<Function*>(value);
10105 }
10106 
10107 
10109 #ifdef V8_ENABLE_CHECKS
10110  CheckCast(value);
10111 #endif
10112  return static_cast<External*>(value);
10113 }
10114 
10115 
10116 template<typename T>
10118  return *reinterpret_cast<Isolate**>(&args_[kIsolateIndex]);
10119 }
10120 
10121 
10122 template<typename T>
10124  return Local<Value>(reinterpret_cast<Value*>(&args_[kDataIndex]));
10125 }
10126 
10127 
10128 template<typename T>
10130  return Local<Object>(reinterpret_cast<Object*>(&args_[kThisIndex]));
10131 }
10132 
10133 
10134 template<typename T>
10136  return Local<Object>(reinterpret_cast<Object*>(&args_[kHolderIndex]));
10137 }
10138 
10139 
10140 template<typename T>
10142  return ReturnValue<T>(&args_[kReturnValueIndex]);
10143 }
10144 
10145 template <typename T>
10147  typedef internal::Internals I;
10149 }
10150 
10151 
10153  typedef internal::Object* S;
10154  typedef internal::Internals I;
10155  I::CheckInitialized(isolate);
10156  S* slot = I::GetRoot(isolate, I::kUndefinedValueRootIndex);
10157  return Local<Primitive>(reinterpret_cast<Primitive*>(slot));
10158 }
10159 
10160 
10162  typedef internal::Object* S;
10163  typedef internal::Internals I;
10164  I::CheckInitialized(isolate);
10165  S* slot = I::GetRoot(isolate, I::kNullValueRootIndex);
10166  return Local<Primitive>(reinterpret_cast<Primitive*>(slot));
10167 }
10168 
10169 
10171  typedef internal::Object* S;
10172  typedef internal::Internals I;
10173  I::CheckInitialized(isolate);
10174  S* slot = I::GetRoot(isolate, I::kTrueValueRootIndex);
10175  return Local<Boolean>(reinterpret_cast<Boolean*>(slot));
10176 }
10177 
10178 
10180  typedef internal::Object* S;
10181  typedef internal::Internals I;
10182  I::CheckInitialized(isolate);
10183  S* slot = I::GetRoot(isolate, I::kFalseValueRootIndex);
10184  return Local<Boolean>(reinterpret_cast<Boolean*>(slot));
10185 }
10186 
10187 
10188 void Isolate::SetData(uint32_t slot, void* data) {
10189  typedef internal::Internals I;
10190  I::SetEmbedderData(this, slot, data);
10191 }
10192 
10193 
10194 void* Isolate::GetData(uint32_t slot) {
10195  typedef internal::Internals I;
10196  return I::GetEmbedderData(this, slot);
10197 }
10198 
10199 
10201  typedef internal::Internals I;
10202  return I::kNumIsolateDataSlots;
10203 }
10204 
10205 
10207  int64_t change_in_bytes) {
10208  typedef internal::Internals I;
10209  const int64_t kMemoryReducerActivationLimit = 32 * 1024 * 1024;
10210  int64_t* external_memory = reinterpret_cast<int64_t*>(
10211  reinterpret_cast<uint8_t*>(this) + I::kExternalMemoryOffset);
10212  int64_t* external_memory_limit = reinterpret_cast<int64_t*>(
10213  reinterpret_cast<uint8_t*>(this) + I::kExternalMemoryLimitOffset);
10214  int64_t* external_memory_at_last_mc =
10215  reinterpret_cast<int64_t*>(reinterpret_cast<uint8_t*>(this) +
10217  const int64_t amount = *external_memory + change_in_bytes;
10218 
10219  *external_memory = amount;
10220 
10221  int64_t allocation_diff_since_last_mc =
10222  *external_memory_at_last_mc - *external_memory;
10223  allocation_diff_since_last_mc = allocation_diff_since_last_mc < 0
10224  ? -allocation_diff_since_last_mc
10225  : allocation_diff_since_last_mc;
10226  if (allocation_diff_since_last_mc > kMemoryReducerActivationLimit) {
10227  CheckMemoryPressure();
10228  }
10229 
10230  if (change_in_bytes < 0) {
10231  *external_memory_limit += change_in_bytes;
10232  }
10233 
10234  if (change_in_bytes > 0 && amount > *external_memory_limit) {
10235  ReportExternalAllocationLimitReached();
10236  }
10237  return *external_memory;
10238 }
10239 
10241 #ifndef V8_ENABLE_CHECKS
10242  typedef internal::Object O;
10243  typedef internal::HeapObject HO;
10244  typedef internal::Internals I;
10245  HO* context = *reinterpret_cast<HO**>(this);
10246  O** result =
10247  HandleScope::CreateHandle(context, I::ReadEmbedderData<O*>(this, index));
10248  return Local<Value>(reinterpret_cast<Value*>(result));
10249 #else
10250  return SlowGetEmbedderData(index);
10251 #endif
10252 }
10253 
10254 
10256 #ifndef V8_ENABLE_CHECKS
10257  typedef internal::Internals I;
10258  return I::ReadEmbedderData<void*>(this, index);
10259 #else
10260  return SlowGetAlignedPointerFromEmbedderData(index);
10261 #endif
10262 }
10263 
10264 bool V8::IsDead() {
10265  Isolate* isolate = Isolate::GetCurrent();
10266  return isolate->IsDead();
10267 }
10268 
10269 
10270 bool V8::AddMessageListener(MessageCallback that, Local<Value> data) {
10271  Isolate* isolate = Isolate::GetCurrent();
10272  return isolate->AddMessageListener(that, data);
10273 }
10274 
10275 
10276 void V8::RemoveMessageListeners(MessageCallback that) {
10277  Isolate* isolate = Isolate::GetCurrent();
10278  isolate->RemoveMessageListeners(that);
10279 }
10280 
10281 
10282 void V8::SetFailedAccessCheckCallbackFunction(
10283  FailedAccessCheckCallback callback) {
10284  Isolate* isolate = Isolate::GetCurrent();
10286 }
10287 
10288 
10289 void V8::SetCaptureStackTraceForUncaughtExceptions(
10290  bool capture, int frame_limit, StackTrace::StackTraceOptions options) {
10291  Isolate* isolate = Isolate::GetCurrent();
10292  isolate->SetCaptureStackTraceForUncaughtExceptions(capture, frame_limit,
10293  options);
10294 }
10295 
10296 
10297 void V8::SetFatalErrorHandler(FatalErrorCallback callback) {
10298  Isolate* isolate = Isolate::GetCurrent();
10299  isolate->SetFatalErrorHandler(callback);
10300 }
10301 
10302 void V8::RemoveGCPrologueCallback(GCCallback callback) {
10303  Isolate* isolate = Isolate::GetCurrent();
10305  reinterpret_cast<Isolate::GCCallback>(callback));
10306 }
10307 
10308 
10309 void V8::RemoveGCEpilogueCallback(GCCallback callback) {
10310  Isolate* isolate = Isolate::GetCurrent();
10312  reinterpret_cast<Isolate::GCCallback>(callback));
10313 }
10314 
10315 void V8::TerminateExecution(Isolate* isolate) { isolate->TerminateExecution(); }
10316 
10317 
10318 bool V8::IsExecutionTerminating(Isolate* isolate) {
10319  if (isolate == NULL) {
10320  isolate = Isolate::GetCurrent();
10321  }
10322  return isolate->IsExecutionTerminating();
10323 }
10324 
10325 
10326 void V8::CancelTerminateExecution(Isolate* isolate) {
10328 }
10329 
10330 
10331 void V8::VisitExternalResources(ExternalResourceVisitor* visitor) {
10332  Isolate* isolate = Isolate::GetCurrent();
10333  isolate->VisitExternalResources(visitor);
10334 }
10335 
10336 
10337 void V8::VisitHandlesWithClassIds(PersistentHandleVisitor* visitor) {
10338  Isolate* isolate = Isolate::GetCurrent();
10339  isolate->VisitHandlesWithClassIds(visitor);
10340 }
10341 
10342 
10343 void V8::VisitHandlesWithClassIds(Isolate* isolate,
10344  PersistentHandleVisitor* visitor) {
10345  isolate->VisitHandlesWithClassIds(visitor);
10346 }
10347 
10348 
10349 void V8::VisitHandlesForPartialDependence(Isolate* isolate,
10350  PersistentHandleVisitor* visitor) {
10352 }
10353 
10354 /**
10355  * \example shell.cc
10356  * A simple shell that takes a list of expressions on the
10357  * command-line and executes them.
10358  */
10359 
10360 
10361 /**
10362  * \example process.cc
10363  */
10364 
10365 
10366 } // namespace v8
10367 
10368 
10369 #undef TYPE_CHECK
10370 
10371 
10372 #endif // INCLUDE_V8_H_