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