v8  4.2.77(io.js2.5.0)
V8 is Google's open source JavaScript engine
v8.h
Go to the documentation of this file.
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 /** \mainpage V8 API Reference Guide
6  *
7  * V8 is Google's open source JavaScript engine.
8  *
9  * This set of documents provides reference material generated from the
10  * V8 header file, include/v8.h.
11  *
12  * For other documentation see http://code.google.com/apis/v8/
13  */
14 
15 #ifndef V8_H_
16 #define V8_H_
17 
18 #include <stddef.h>
19 #include <stdint.h>
20 #include <stdio.h>
21 
22 #include "v8config.h"
23 
24 // We reserve the V8_* prefix for macros defined in V8 public API and
25 // assume there are no name conflicts with the embedder's code.
26 
27 #ifdef V8_OS_WIN
28 
29 // Setup for Windows DLL export/import. When building the V8 DLL the
30 // BUILDING_V8_SHARED needs to be defined. When building a program which uses
31 // the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8
32 // static library or building a program which uses the V8 static library neither
33 // BUILDING_V8_SHARED nor USING_V8_SHARED should be defined.
34 #if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED)
35 #error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the
36  build configuration to ensure that at most one of these is set
37 #endif
38 
39 #ifdef BUILDING_V8_SHARED
40 # define V8_EXPORT __declspec(dllexport)
41 #elif USING_V8_SHARED
42 # define V8_EXPORT __declspec(dllimport)
43 #else
44 # define V8_EXPORT
45 #endif // BUILDING_V8_SHARED
46 
47 #else // V8_OS_WIN
48 
49 // Setup for Linux shared library export.
50 #if V8_HAS_ATTRIBUTE_VISIBILITY && defined(V8_SHARED)
51 # ifdef BUILDING_V8_SHARED
52 # define V8_EXPORT __attribute__ ((visibility("default")))
53 # else
54 # define V8_EXPORT
55 # endif
56 #else
57 # define V8_EXPORT
58 #endif
59 
60 #endif // V8_OS_WIN
61 
62 /**
63  * The v8 JavaScript engine.
64  */
65 namespace v8 {
66 
67 class AccessorSignature;
68 class Array;
69 class Boolean;
70 class BooleanObject;
71 class Context;
72 class CpuProfiler;
73 class Data;
74 class Date;
75 class External;
76 class Function;
77 class FunctionTemplate;
78 class HeapProfiler;
79 class ImplementationUtilities;
80 class Int32;
81 class Integer;
82 class Isolate;
83 class Name;
84 class Number;
85 class NumberObject;
86 class Object;
87 class ObjectOperationDescriptor;
88 class ObjectTemplate;
89 class Platform;
90 class Primitive;
91 class Promise;
92 class RawOperationDescriptor;
93 class Script;
94 class Signature;
95 class StackFrame;
96 class StackTrace;
97 class String;
98 class StringObject;
99 class Symbol;
100 class SymbolObject;
101 class Private;
102 class Uint32;
103 class Utils;
104 class Value;
105 template <class T> class Handle;
106 template <class T> class Local;
107 template <class T> class Eternal;
108 template<class T> class NonCopyablePersistentTraits;
109 template<class T> class PersistentBase;
110 template<class T,
111  class M = NonCopyablePersistentTraits<T> > class Persistent;
112 template<class T> class UniquePersistent;
113 template<class K, class V, class T> class PersistentValueMap;
114 template <class K, class V, class T>
116 template <class K, class V, class T>
118 template<class V, class T> class PersistentValueVector;
119 template<class T, class P> class WeakCallbackObject;
120 class FunctionTemplate;
121 class ObjectTemplate;
122 class Data;
123 template<typename T> class FunctionCallbackInfo;
124 template<typename T> class PropertyCallbackInfo;
125 class StackTrace;
126 class StackFrame;
127 class Isolate;
128 class CallHandlerHelper;
130 template<typename T> class ReturnValue;
131 
132 namespace internal {
133 class Arguments;
134 class Heap;
135 class HeapObject;
136 class Isolate;
137 class Object;
138 struct StreamedSource;
139 template<typename T> class CustomArguments;
140 class PropertyCallbackArguments;
141 class FunctionCallbackArguments;
142 class GlobalHandles;
143 
144 template <typename T>
146  public:
147  V8_INLINE v8::Isolate* GetIsolate() const { return isolate_; }
148 
149  explicit CallbackData(v8::Isolate* isolate, T* parameter)
150  : isolate_(isolate), parameter_(parameter) {}
151  V8_INLINE T* GetParameter() const { return parameter_; }
152 
153  private:
154  v8::Isolate* isolate_;
155  T* parameter_;
156 };
157 }
158 
159 
160 /**
161  * General purpose unique identifier.
162  */
163 class UniqueId {
164  public:
165  explicit UniqueId(intptr_t data)
166  : data_(data) {}
167 
168  bool operator==(const UniqueId& other) const {
169  return data_ == other.data_;
170  }
171 
172  bool operator!=(const UniqueId& other) const {
173  return data_ != other.data_;
174  }
175 
176  bool operator<(const UniqueId& other) const {
177  return data_ < other.data_;
178  }
179 
180  private:
181  intptr_t data_;
182 };
183 
184 // --- Handles ---
185 
186 #define TYPE_CHECK(T, S)
187  while (false) {
188  *(static_cast<T* volatile*>(0)) = static_cast<S*>(0);
189  }
190 
191 
192 /**
193  * An object reference managed by the v8 garbage collector.
194  *
195  * All objects returned from v8 have to be tracked by the garbage
196  * collector so that it knows that the objects are still alive. Also,
197  * because the garbage collector may move objects, it is unsafe to
198  * point directly to an object. Instead, all objects are stored in
199  * handles which are known by the garbage collector and updated
200  * whenever an object moves. Handles should always be passed by value
201  * (except in cases like out-parameters) and they should never be
202  * allocated on the heap.
203  *
204  * There are two types of handles: local and persistent handles.
205  * Local handles are light-weight and transient and typically used in
206  * local operations. They are managed by HandleScopes. Persistent
207  * handles can be used when storing objects across several independent
208  * operations and have to be explicitly deallocated when they're no
209  * longer used.
210  *
211  * It is safe to extract the object stored in the handle by
212  * dereferencing the handle (for instance, to extract the Object* from
213  * a Handle<Object>); the value will still be governed by a handle
214  * behind the scenes and the same rules apply to these values as to
215  * their handles.
216  */
217 template <class T> class Handle {
218  public:
219  /**
220  * Creates an empty handle.
221  */
222  V8_INLINE Handle() : val_(0) {}
223 
224  /**
225  * Creates a handle for the contents of the specified handle. This
226  * constructor allows you to pass handles as arguments by value and
227  * to assign between handles. However, if you try to assign between
228  * incompatible handles, for instance from a Handle<String> to a
229  * Handle<Number> it will cause a compile-time error. Assigning
230  * between compatible handles, for instance assigning a
231  * Handle<String> to a variable declared as Handle<Value>, is legal
232  * because String is a subclass of Value.
233  */
234  template <class S> V8_INLINE Handle(Handle<S> that)
235  : val_(reinterpret_cast<T*>(*that)) {
236  /**
237  * This check fails when trying to convert between incompatible
238  * handles. For example, converting from a Handle<String> to a
239  * Handle<Number>.
240  */
241  TYPE_CHECK(T, S);
242  }
243 
244  /**
245  * Returns true if the handle is empty.
246  */
247  V8_INLINE bool IsEmpty() const { return val_ == 0; }
248 
249  /**
250  * Sets the handle to be empty. IsEmpty() will then return true.
251  */
252  V8_INLINE void Clear() { val_ = 0; }
253 
254  V8_INLINE T* operator->() const { return val_; }
255 
256  V8_INLINE T* operator*() const { return val_; }
257 
258  /**
259  * Checks whether two handles are the same.
260  * Returns true if both are empty, or if the objects
261  * to which they refer are identical.
262  * The handles' references are not checked.
263  */
264  template <class S> V8_INLINE bool operator==(const Handle<S>& that) const {
265  internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
266  internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
267  if (a == 0) return b == 0;
268  if (b == 0) return false;
269  return *a == *b;
270  }
271 
272  template <class S> V8_INLINE bool operator==(
273  const PersistentBase<S>& that) const {
274  internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
275  internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
276  if (a == 0) return b == 0;
277  if (b == 0) return false;
278  return *a == *b;
279  }
280 
281  /**
282  * Checks whether two handles are different.
283  * Returns true if only one of the handles is empty, or if
284  * the objects to which they refer are different.
285  * The handles' references are not checked.
286  */
287  template <class S> V8_INLINE bool operator!=(const Handle<S>& that) const {
288  return !operator==(that);
289  }
290 
291  template <class S> V8_INLINE bool operator!=(
292  const Persistent<S>& that) const {
293  return !operator==(that);
294  }
295 
296  template <class S> V8_INLINE static Handle<T> Cast(Handle<S> that) {
297 #ifdef V8_ENABLE_CHECKS
298  // If we're going to perform the type check then we have to check
299  // that the handle isn't empty before doing the checked cast.
300  if (that.IsEmpty()) return Handle<T>();
301 #endif
302  return Handle<T>(T::Cast(*that));
303  }
304 
305  template <class S> V8_INLINE Handle<S> As() {
306  return Handle<S>::Cast(*this);
307  }
308 
309  V8_INLINE static Handle<T> New(Isolate* isolate, Handle<T> that) {
310  return New(isolate, that.val_);
311  }
312  V8_INLINE static Handle<T> New(Isolate* isolate,
313  const PersistentBase<T>& that) {
314  return New(isolate, that.val_);
315  }
316 
317  private:
318  friend class Utils;
319  template<class F, class M> friend class Persistent;
320  template<class F> friend class PersistentBase;
321  template<class F> friend class Handle;
322  template<class F> friend class Local;
323  template<class F> friend class FunctionCallbackInfo;
324  template<class F> friend class PropertyCallbackInfo;
325  template<class F> friend class internal::CustomArguments;
327  friend Handle<Primitive> Null(Isolate* isolate);
328  friend Handle<Boolean> True(Isolate* isolate);
329  friend Handle<Boolean> False(Isolate* isolate);
330  friend class Context;
331  friend class HandleScope;
332  friend class Object;
333  friend class Private;
334 
335  /**
336  * Creates a new handle for the specified value.
337  */
338  V8_INLINE explicit Handle(T* val) : val_(val) {}
339 
340  V8_INLINE static Handle<T> New(Isolate* isolate, T* that);
341 
342  T* val_;
343 };
344 
345 
346 /**
347  * A light-weight stack-allocated object handle. All operations
348  * that return objects from within v8 return them in local handles. They
349  * are created within HandleScopes, and all local handles allocated within a
350  * handle scope are destroyed when the handle scope is destroyed. Hence it
351  * is not necessary to explicitly deallocate local handles.
352  */
353 template <class T> class Local : public Handle<T> {
354  public:
355  V8_INLINE Local();
356  template <class S> V8_INLINE Local(Local<S> that)
357  : Handle<T>(reinterpret_cast<T*>(*that)) {
358  /**
359  * This check fails when trying to convert between incompatible
360  * handles. For example, converting from a Handle<String> to a
361  * Handle<Number>.
362  */
363  TYPE_CHECK(T, S);
364  }
365 
366 
367  template <class S> V8_INLINE static Local<T> Cast(Local<S> that) {
368 #ifdef V8_ENABLE_CHECKS
369  // If we're going to perform the type check then we have to check
370  // that the handle isn't empty before doing the checked cast.
371  if (that.IsEmpty()) return Local<T>();
372 #endif
373  return Local<T>(T::Cast(*that));
374  }
375  template <class S> V8_INLINE Local(Handle<S> that)
376  : Handle<T>(reinterpret_cast<T*>(*that)) {
377  TYPE_CHECK(T, S);
378  }
379 
380  template <class S> V8_INLINE Local<S> As() {
381  return Local<S>::Cast(*this);
382  }
383 
384  /**
385  * Create a local handle for the content of another handle.
386  * The referee is kept alive by the local handle even when
387  * the original handle is destroyed/disposed.
388  */
389  V8_INLINE static Local<T> New(Isolate* isolate, Handle<T> that);
390  V8_INLINE static Local<T> New(Isolate* isolate,
391  const PersistentBase<T>& that);
392 
393  private:
394  friend class Utils;
395  template<class F> friend class Eternal;
396  template<class F> friend class PersistentBase;
397  template<class F, class M> friend class Persistent;
398  template<class F> friend class Handle;
399  template<class F> friend class Local;
400  template<class F> friend class FunctionCallbackInfo;
401  template<class F> friend class PropertyCallbackInfo;
402  friend class String;
403  friend class Object;
404  friend class Context;
405  template<class F> friend class internal::CustomArguments;
406  friend class HandleScope;
407  friend class EscapableHandleScope;
408  template <class F1, class F2, class F3>
410  template<class F1, class F2> friend class PersistentValueVector;
411 
412  template <class S> V8_INLINE Local(S* that) : Handle<T>(that) { }
413  V8_INLINE static Local<T> New(Isolate* isolate, T* that);
414 };
415 
416 
417 // Eternal handles are set-once handles that live for the life of the isolate.
418 template <class T> class Eternal {
419  public:
420  V8_INLINE Eternal() : index_(kInitialValue) { }
421  template<class S>
422  V8_INLINE Eternal(Isolate* isolate, Local<S> handle) : index_(kInitialValue) {
423  Set(isolate, handle);
424  }
425  // Can only be safely called if already set.
426  V8_INLINE Local<T> Get(Isolate* isolate);
427  V8_INLINE bool IsEmpty() { return index_ == kInitialValue; }
428  template<class S> V8_INLINE void Set(Isolate* isolate, Local<S> handle);
429 
430  private:
431  static const int kInitialValue = -1;
432  int index_;
433 };
434 
435 
436 template <typename T>
438  public:
439  typedef void (*Callback)(const PhantomCallbackData<T>& data);
440 
441  V8_INLINE void* GetInternalField1() const { return internal_field1_; }
442  V8_INLINE void* GetInternalField2() const { return internal_field2_; }
443 
444  PhantomCallbackData(Isolate* isolate, T* parameter, void* internal_field1,
445  void* internal_field2)
446  : internal::CallbackData<T>(isolate, parameter),
447  internal_field1_(internal_field1),
448  internal_field2_(internal_field2) {}
449 
450  private:
451  void* internal_field1_;
452  void* internal_field2_;
453 };
454 
455 
456 template <class T, class P>
458  public:
459  typedef void (*Callback)(const WeakCallbackData<T, P>& data);
460 
461  V8_INLINE Local<T> GetValue() const { return handle_; }
462 
463  private:
464  friend class internal::GlobalHandles;
465  WeakCallbackData(Isolate* isolate, P* parameter, Local<T> handle)
466  : internal::CallbackData<P>(isolate, parameter), handle_(handle) {}
467  Local<T> handle_;
468 };
469 
470 
471 static const int kNoInternalFieldIndex = -1;
472 
473 
474 /**
475  * An object reference that is independent of any handle scope. Where
476  * a Local handle only lives as long as the HandleScope in which it was
477  * allocated, a PersistentBase handle remains valid until it is explicitly
478  * disposed.
479  *
480  * A persistent handle contains a reference to a storage cell within
481  * the v8 engine which holds an object value and which is updated by
482  * the garbage collector whenever the object is moved. A new storage
483  * cell can be created using the constructor or PersistentBase::Reset and
484  * existing handles can be disposed using PersistentBase::Reset.
485  *
486  */
487 template <class T> class PersistentBase {
488  public:
489  /**
490  * If non-empty, destroy the underlying storage cell
491  * IsEmpty() will return true after this call.
492  */
493  V8_INLINE void Reset();
494  /**
495  * If non-empty, destroy the underlying storage cell
496  * and create a new one with the contents of other if other is non empty
497  */
498  template <class S>
499  V8_INLINE void Reset(Isolate* isolate, const Handle<S>& other);
500 
501  /**
502  * If non-empty, destroy the underlying storage cell
503  * and create a new one with the contents of other if other is non empty
504  */
505  template <class S>
506  V8_INLINE void Reset(Isolate* isolate, const PersistentBase<S>& other);
507 
508  V8_INLINE bool IsEmpty() const { return val_ == NULL; }
509  V8_INLINE void Empty() { val_ = 0; }
510 
511  template <class S>
512  V8_INLINE bool operator==(const PersistentBase<S>& that) const {
513  internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
514  internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
515  if (a == NULL) return b == NULL;
516  if (b == NULL) return false;
517  return *a == *b;
518  }
519 
520  template <class S> V8_INLINE bool operator==(const Handle<S>& that) const {
521  internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
522  internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
523  if (a == NULL) return b == NULL;
524  if (b == NULL) return false;
525  return *a == *b;
526  }
527 
528  template <class S>
529  V8_INLINE bool operator!=(const PersistentBase<S>& that) const {
530  return !operator==(that);
531  }
532 
533  template <class S> V8_INLINE bool operator!=(const Handle<S>& that) const {
534  return !operator==(that);
535  }
536 
537  /**
538  * Install a finalization callback on this object.
539  * NOTE: There is no guarantee as to *when* or even *if* the callback is
540  * invoked. The invocation is performed solely on a best effort basis.
541  * As always, GC-based finalization should *not* be relied upon for any
542  * critical form of resource management!
543  */
544  template<typename P>
545  V8_INLINE void SetWeak(
546  P* parameter,
547  typename WeakCallbackData<T, P>::Callback callback);
548 
549  template<typename S, typename P>
550  V8_INLINE void SetWeak(
551  P* parameter,
552  typename WeakCallbackData<S, P>::Callback callback);
553 
554  // Phantom persistents work like weak persistents, except that the pointer to
555  // the object being collected is not available in the finalization callback.
556  // This enables the garbage collector to collect the object and any objects
557  // it references transitively in one GC cycle. At the moment you can either
558  // specify a parameter for the callback or the location of two internal
559  // fields in the dying object.
560  template <typename P>
561  V8_INLINE void SetPhantom(P* parameter,
562  typename PhantomCallbackData<P>::Callback callback,
563  int internal_field_index1 = kNoInternalFieldIndex,
564  int internal_field_index2 = kNoInternalFieldIndex);
565 
566  template<typename P>
567  V8_INLINE P* ClearWeak();
568 
569  // TODO(dcarney): remove this.
570  V8_INLINE void ClearWeak() { ClearWeak<void>(); }
571 
572  /**
573  * Marks the reference to this object independent. Garbage collector is free
574  * to ignore any object groups containing this object. Weak callback for an
575  * independent handle should not assume that it will be preceded by a global
576  * GC prologue callback or followed by a global GC epilogue callback.
577  */
578  V8_INLINE void MarkIndependent();
579 
580  /**
581  * Marks the reference to this object partially dependent. Partially dependent
582  * handles only depend on other partially dependent handles and these
583  * dependencies are provided through object groups. It provides a way to build
584  * smaller object groups for young objects that represent only a subset of all
585  * external dependencies. This mark is automatically cleared after each
586  * garbage collection.
587  */
589 
590  V8_INLINE bool IsIndependent() const;
591 
592  /** Checks if the handle holds the only reference to an object. */
593  V8_INLINE bool IsNearDeath() const;
594 
595  /** Returns true if the handle's reference is weak. */
596  V8_INLINE bool IsWeak() const;
597 
598  /**
599  * Assigns a wrapper class ID to the handle. See RetainedObjectInfo interface
600  * description in v8-profiler.h for details.
601  */
602  V8_INLINE void SetWrapperClassId(uint16_t class_id);
603 
604  /**
605  * Returns the class ID previously assigned to this handle or 0 if no class ID
606  * was previously assigned.
607  */
608  V8_INLINE uint16_t WrapperClassId() const;
609 
610  private:
611  friend class Isolate;
612  friend class Utils;
613  template<class F> friend class Handle;
614  template<class F> friend class Local;
615  template<class F1, class F2> friend class Persistent;
616  template<class F> friend class UniquePersistent;
617  template<class F> friend class PersistentBase;
618  template<class F> friend class ReturnValue;
619  template <class F1, class F2, class F3>
621  template<class F1, class F2> friend class PersistentValueVector;
622  friend class Object;
623 
624  explicit V8_INLINE PersistentBase(T* val) : val_(val) {}
625  PersistentBase(PersistentBase& other); // NOLINT
626  void operator=(PersistentBase&);
627  V8_INLINE static T* New(Isolate* isolate, T* that);
628 
629  T* val_;
630 };
631 
632 
633 /**
634  * Default traits for Persistent. This class does not allow
635  * use of the copy constructor or assignment operator.
636  * At present kResetInDestructor is not set, but that will change in a future
637  * version.
638  */
639 template<class T>
640 class NonCopyablePersistentTraits {
641  public:
642  typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
643  static const bool kResetInDestructor = false;
644  template<class S, class M>
645  V8_INLINE static void Copy(const Persistent<S, M>& source,
646  NonCopyablePersistent* dest) {
647  Uncompilable<Object>();
648  }
649  // TODO(dcarney): come up with a good compile error here.
650  template<class O> V8_INLINE static void Uncompilable() {
651  TYPE_CHECK(O, Primitive);
652  }
653 };
654 
655 
656 /**
657  * Helper class traits to allow copying and assignment of Persistent.
658  * This will clone the contents of storage cell, but not any of the flags, etc.
659  */
660 template<class T>
662  typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
663  static const bool kResetInDestructor = true;
664  template<class S, class M>
665  static V8_INLINE void Copy(const Persistent<S, M>& source,
666  CopyablePersistent* dest) {
667  // do nothing, just allow copy
668  }
669 };
670 
671 
672 /**
673  * A PersistentBase which allows copy and assignment.
674  *
675  * Copy, assignment and destructor bevavior is controlled by the traits
676  * class M.
677  *
678  * Note: Persistent class hierarchy is subject to future changes.
679  */
680 template <class T, class M> class Persistent : public PersistentBase<T> {
681  public:
682  /**
683  * A Persistent with no storage cell.
684  */
685  V8_INLINE Persistent() : PersistentBase<T>(0) { }
686  /**
687  * Construct a Persistent from a Handle.
688  * When the Handle is non-empty, a new storage cell is created
689  * pointing to the same object, and no flags are set.
690  */
691  template <class S> V8_INLINE Persistent(Isolate* isolate, Handle<S> that)
692  : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
693  TYPE_CHECK(T, S);
694  }
695  /**
696  * Construct a Persistent from a Persistent.
697  * When the Persistent is non-empty, a new storage cell is created
698  * pointing to the same object, and no flags are set.
699  */
700  template <class S, class M2>
701  V8_INLINE Persistent(Isolate* isolate, const Persistent<S, M2>& that)
702  : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
703  TYPE_CHECK(T, S);
704  }
705  /**
706  * The copy constructors and assignment operator create a Persistent
707  * exactly as the Persistent constructor, but the Copy function from the
708  * traits class is called, allowing the setting of flags based on the
709  * copied Persistent.
710  */
711  V8_INLINE Persistent(const Persistent& that) : PersistentBase<T>(0) {
712  Copy(that);
713  }
714  template <class S, class M2>
715  V8_INLINE Persistent(const Persistent<S, M2>& that) : PersistentBase<T>(0) {
716  Copy(that);
717  }
718  V8_INLINE Persistent& operator=(const Persistent& that) { // NOLINT
719  Copy(that);
720  return *this;
721  }
722  template <class S, class M2>
723  V8_INLINE Persistent& operator=(const Persistent<S, M2>& that) { // NOLINT
724  Copy(that);
725  return *this;
726  }
727  /**
728  * The destructor will dispose the Persistent based on the
729  * kResetInDestructor flags in the traits class. Since not calling dispose
730  * can result in a memory leak, it is recommended to always set this flag.
731  */
733  if (M::kResetInDestructor) this->Reset();
734  }
735 
736  // TODO(dcarney): this is pretty useless, fix or remove
737  template <class S>
738  V8_INLINE static Persistent<T>& Cast(Persistent<S>& that) { // NOLINT
739 #ifdef V8_ENABLE_CHECKS
740  // If we're going to perform the type check then we have to check
741  // that the handle isn't empty before doing the checked cast.
742  if (!that.IsEmpty()) T::Cast(*that);
743 #endif
744  return reinterpret_cast<Persistent<T>&>(that);
745  }
746 
747  // TODO(dcarney): this is pretty useless, fix or remove
748  template <class S> V8_INLINE Persistent<S>& As() { // NOLINT
749  return Persistent<S>::Cast(*this);
750  }
751 
752  private:
753  friend class Isolate;
754  friend class Utils;
755  template<class F> friend class Handle;
756  template<class F> friend class Local;
757  template<class F1, class F2> friend class Persistent;
758  template<class F> friend class ReturnValue;
759 
760  template <class S> V8_INLINE Persistent(S* that) : PersistentBase<T>(that) { }
761  V8_INLINE T* operator*() const { return this->val_; }
762  template<class S, class M2>
763  V8_INLINE void Copy(const Persistent<S, M2>& that);
764 };
765 
766 
767 /**
768  * A PersistentBase which has move semantics.
769  *
770  * Note: Persistent class hierarchy is subject to future changes.
771  */
772 template<class T>
773 class UniquePersistent : public PersistentBase<T> {
774  struct RValue {
775  V8_INLINE explicit RValue(UniquePersistent* obj) : object(obj) {}
776  UniquePersistent* object;
777  };
778 
779  public:
780  /**
781  * A UniquePersistent with no storage cell.
782  */
783  V8_INLINE UniquePersistent() : PersistentBase<T>(0) { }
784  /**
785  * Construct a UniquePersistent from a Handle.
786  * When the Handle is non-empty, a new storage cell is created
787  * pointing to the same object, and no flags are set.
788  */
789  template <class S>
790  V8_INLINE UniquePersistent(Isolate* isolate, Handle<S> that)
791  : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
792  TYPE_CHECK(T, S);
793  }
794  /**
795  * Construct a UniquePersistent from a PersistentBase.
796  * When the Persistent is non-empty, a new storage cell is created
797  * pointing to the same object, and no flags are set.
798  */
799  template <class S>
800  V8_INLINE UniquePersistent(Isolate* isolate, const PersistentBase<S>& that)
801  : PersistentBase<T>(PersistentBase<T>::New(isolate, that.val_)) {
802  TYPE_CHECK(T, S);
803  }
804  /**
805  * Move constructor.
806  */
808  : PersistentBase<T>(rvalue.object->val_) {
809  rvalue.object->val_ = 0;
810  }
811  V8_INLINE ~UniquePersistent() { this->Reset(); }
812  /**
813  * Move via assignment.
814  */
815  template<class S>
816  V8_INLINE UniquePersistent& operator=(UniquePersistent<S> rhs) {
817  TYPE_CHECK(T, S);
818  this->Reset();
819  this->val_ = rhs.val_;
820  rhs.val_ = 0;
821  return *this;
822  }
823  /**
824  * Cast operator for moves.
825  */
826  V8_INLINE operator RValue() { return RValue(this); }
827  /**
828  * Pass allows returning uniques from functions, etc.
829  */
830  UniquePersistent Pass() { return UniquePersistent(RValue(this)); }
831 
832  private:
833  UniquePersistent(UniquePersistent&);
834  void operator=(UniquePersistent&);
835 };
836 
837 
838  /**
839  * A stack-allocated class that governs a number of local handles.
840  * After a handle scope has been created, all local handles will be
841  * allocated within that handle scope until either the handle scope is
842  * deleted or another handle scope is created. If there is already a
843  * handle scope and a new one is created, all allocations will take
844  * place in the new handle scope until it is deleted. After that,
845  * new handles will again be allocated in the original handle scope.
846  *
847  * After the handle scope of a local handle has been deleted the
848  * garbage collector will no longer track the object stored in the
849  * handle and may deallocate it. The behavior of accessing a handle
850  * for which the handle scope has been deleted is undefined.
851  */
853  public:
854  HandleScope(Isolate* isolate);
855 
856  ~HandleScope();
857 
858  /**
859  * Counts the number of allocated handles.
860  */
861  static int NumberOfHandles(Isolate* isolate);
862 
864  return reinterpret_cast<Isolate*>(isolate_);
865  }
866 
867  protected:
869 
870  void Initialize(Isolate* isolate);
871 
872  static internal::Object** CreateHandle(internal::Isolate* isolate,
873  internal::Object* value);
874 
875  private:
876  // Uses heap_object to obtain the current Isolate.
877  static internal::Object** CreateHandle(internal::HeapObject* heap_object,
878  internal::Object* value);
879 
880  // Make it hard to create heap-allocated or illegal handle scopes by
881  // disallowing certain operations.
882  HandleScope(const HandleScope&);
883  void operator=(const HandleScope&);
884  void* operator new(size_t size);
885  void operator delete(void*, size_t);
886 
887  internal::Isolate* isolate_;
888  internal::Object** prev_next_;
889  internal::Object** prev_limit_;
890 
891  // Local::New uses CreateHandle with an Isolate* parameter.
892  template<class F> friend class Local;
893 
894  // Object::GetInternalField and Context::GetEmbedderData use CreateHandle with
895  // a HeapObject* in their shortcuts.
896  friend class Object;
897  friend class Context;
898 };
899 
900 
901 /**
902  * A HandleScope which first allocates a handle in the current scope
903  * which will be later filled with the escape value.
904  */
906  public:
907  EscapableHandleScope(Isolate* isolate);
909 
910  /**
911  * Pushes the value into the previous scope and returns a handle to it.
912  * Cannot be called twice.
913  */
914  template <class T>
915  V8_INLINE Local<T> Escape(Local<T> value) {
916  internal::Object** slot =
917  Escape(reinterpret_cast<internal::Object**>(*value));
918  return Local<T>(reinterpret_cast<T*>(slot));
919  }
920 
921  private:
922  internal::Object** Escape(internal::Object** escape_value);
923 
924  // Make it hard to create heap-allocated or illegal handle scopes by
925  // disallowing certain operations.
926  EscapableHandleScope(const EscapableHandleScope&);
927  void operator=(const EscapableHandleScope&);
928  void* operator new(size_t size);
929  void operator delete(void*, size_t);
930 
931  internal::Object** escape_slot_;
932 };
933 
934 
935 /**
936  * A simple Maybe type, representing an object which may or may not have a
937  * value.
938  */
939 template<class T>
940 struct Maybe {
941  Maybe() : has_value(false) {}
942  explicit Maybe(T t) : has_value(true), value(t) {}
943  Maybe(bool has, T t) : has_value(has), value(t) {}
944 
945  bool has_value;
946  T value;
947 };
948 
949 
950 // Convenience wrapper.
951 template <class T>
952 inline Maybe<T> maybe(T t) {
953  return Maybe<T>(t);
954 }
955 
956 
957 // --- Special objects ---
958 
959 
960 /**
961  * The superclass of values and API object templates.
962  */
964  private:
965  Data();
966 };
967 
968 
969 /**
970  * The origin, within a file, of a script.
971  */
973  public:
975  Handle<Value> resource_name,
976  Handle<Integer> resource_line_offset = Handle<Integer>(),
977  Handle<Integer> resource_column_offset = Handle<Integer>(),
978  Handle<Boolean> resource_is_shared_cross_origin = Handle<Boolean>(),
979  Handle<Integer> script_id = Handle<Integer>(),
980  Handle<Boolean> resource_is_embedder_debug_script = Handle<Boolean>())
981  : resource_name_(resource_name),
982  resource_line_offset_(resource_line_offset),
983  resource_column_offset_(resource_column_offset),
984  resource_is_embedder_debug_script_(resource_is_embedder_debug_script),
985  resource_is_shared_cross_origin_(resource_is_shared_cross_origin),
986  script_id_(script_id) {}
987  V8_INLINE Handle<Value> ResourceName() const;
988  V8_INLINE Handle<Integer> ResourceLineOffset() const;
989  V8_INLINE Handle<Integer> ResourceColumnOffset() const;
990  /**
991  * Returns true for embedder's debugger scripts
992  */
995  V8_INLINE Handle<Integer> ScriptID() const;
996 
997  private:
998  Handle<Value> resource_name_;
999  Handle<Integer> resource_line_offset_;
1000  Handle<Integer> resource_column_offset_;
1001  Handle<Boolean> resource_is_embedder_debug_script_;
1002  Handle<Boolean> resource_is_shared_cross_origin_;
1003  Handle<Integer> script_id_;
1004 };
1005 
1006 
1007 /**
1008  * A compiled JavaScript script, not yet tied to a Context.
1009  */
1011  public:
1012  /**
1013  * Binds the script to the currently entered context.
1014  */
1015  Local<Script> BindToCurrentContext();
1016 
1017  int GetId();
1018  Handle<Value> GetScriptName();
1019 
1020  /**
1021  * Data read from magic sourceURL comments.
1022  */
1023  Handle<Value> GetSourceURL();
1024  /**
1025  * Data read from magic sourceMappingURL comments.
1026  */
1027  Handle<Value> GetSourceMappingURL();
1028 
1029  /**
1030  * Returns zero based line number of the code_pos location in the script.
1031  * -1 will be returned if no information available.
1032  */
1033  int GetLineNumber(int code_pos);
1034 
1035  static const int kNoScriptId = 0;
1036 };
1037 
1038 
1039 /**
1040  * A compiled JavaScript script, tied to a Context which was active when the
1041  * script was compiled.
1042  */
1044  public:
1045  /**
1046  * A shorthand for ScriptCompiler::Compile().
1047  */
1048  static Local<Script> Compile(Handle<String> source,
1049  ScriptOrigin* origin = NULL);
1050 
1051  // To be decprecated, use the Compile above.
1052  static Local<Script> Compile(Handle<String> source,
1053  Handle<String> file_name);
1054 
1055  /**
1056  * Runs the script returning the resulting value. It will be run in the
1057  * context in which it was created (ScriptCompiler::CompileBound or
1058  * UnboundScript::BindToCurrentContext()).
1059  */
1060  Local<Value> Run();
1061 
1062  /**
1063  * Returns the corresponding context-unbound script.
1064  */
1066 
1067  V8_DEPRECATED("Use GetUnboundScript()->GetId()",
1068  int GetId()) {
1070  }
1071 };
1072 
1073 
1074 /**
1075  * For compiling scripts.
1076  */
1078  public:
1079  /**
1080  * Compilation data that the embedder can cache and pass back to speed up
1081  * future compilations. The data is produced if the CompilerOptions passed to
1082  * the compilation functions in ScriptCompiler contains produce_data_to_cache
1083  * = true. The data to cache can then can be retrieved from
1084  * UnboundScript.
1085  */
1090  };
1091 
1093  : data(NULL),
1094  length(0),
1095  rejected(false),
1097 
1098  // If buffer_policy is BufferNotOwned, the caller keeps the ownership of
1099  // data and guarantees that it stays alive until the CachedData object is
1100  // destroyed. If the policy is BufferOwned, the given data will be deleted
1101  // (with delete[]) when the CachedData object is destroyed.
1102  CachedData(const uint8_t* data, int length,
1103  BufferPolicy buffer_policy = BufferNotOwned);
1104  ~CachedData();
1105  // TODO(marja): Async compilation; add constructors which take a callback
1106  // which will be called when V8 no longer needs the data.
1107  const uint8_t* data;
1108  int length;
1109  bool rejected;
1111 
1112  private:
1113  // Prevent copying. Not implemented.
1114  CachedData(const CachedData&);
1115  CachedData& operator=(const CachedData&);
1116  };
1117 
1118  /**
1119  * Source code which can be then compiled to a UnboundScript or Script.
1120  */
1121  class Source {
1122  public:
1123  // Source takes ownership of CachedData.
1124  V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
1125  CachedData* cached_data = NULL);
1126  V8_INLINE Source(Local<String> source_string,
1127  CachedData* cached_data = NULL);
1128  V8_INLINE ~Source();
1129 
1130  // Ownership of the CachedData or its buffers is *not* transferred to the
1131  // caller. The CachedData object is alive as long as the Source object is
1132  // alive.
1133  V8_INLINE const CachedData* GetCachedData() const;
1134 
1135  private:
1136  friend class ScriptCompiler;
1137  // Prevent copying. Not implemented.
1138  Source(const Source&);
1139  Source& operator=(const Source&);
1140 
1141  Local<String> source_string;
1142 
1143  // Origin information
1144  Handle<Value> resource_name;
1145  Handle<Integer> resource_line_offset;
1146  Handle<Integer> resource_column_offset;
1147  Handle<Boolean> resource_is_embedder_debug_script;
1148  Handle<Boolean> resource_is_shared_cross_origin;
1149 
1150  // Cached data from previous compilation (if a kConsume*Cache flag is
1151  // set), or hold newly generated cache data (kProduce*Cache flags) are
1152  // set when calling a compile method.
1153  CachedData* cached_data;
1154  };
1155 
1156  /**
1157  * For streaming incomplete script data to V8. The embedder should implement a
1158  * subclass of this class.
1159  */
1161  public:
1162  virtual ~ExternalSourceStream() {}
1163 
1164  /**
1165  * V8 calls this to request the next chunk of data from the embedder. This
1166  * function will be called on a background thread, so it's OK to block and
1167  * wait for the data, if the embedder doesn't have data yet. Returns the
1168  * length of the data returned. When the data ends, GetMoreData should
1169  * return 0. Caller takes ownership of the data.
1170  *
1171  * When streaming UTF-8 data, V8 handles multi-byte characters split between
1172  * two data chunks, but doesn't handle multi-byte characters split between
1173  * more than two data chunks. The embedder can avoid this problem by always
1174  * returning at least 2 bytes of data.
1175  *
1176  * If the embedder wants to cancel the streaming, they should make the next
1177  * GetMoreData call return 0. V8 will interpret it as end of data (and most
1178  * probably, parsing will fail). The streaming task will return as soon as
1179  * V8 has parsed the data it received so far.
1180  */
1181  virtual size_t GetMoreData(const uint8_t** src) = 0;
1182  };
1183 
1184 
1185  /**
1186  * Source code which can be streamed into V8 in pieces. It will be parsed
1187  * while streaming. It can be compiled after the streaming is complete.
1188  * StreamedSource must be kept alive while the streaming task is ran (see
1189  * ScriptStreamingTask below).
1190  */
1192  public:
1194 
1195  StreamedSource(ExternalSourceStream* source_stream, Encoding encoding);
1196  ~StreamedSource();
1197 
1198  // Ownership of the CachedData or its buffers is *not* transferred to the
1199  // caller. The CachedData object is alive as long as the StreamedSource
1200  // object is alive.
1201  const CachedData* GetCachedData() const;
1202 
1203  internal::StreamedSource* impl() const { return impl_; }
1204 
1205  private:
1206  // Prevent copying. Not implemented.
1207  StreamedSource(const StreamedSource&);
1208  StreamedSource& operator=(const StreamedSource&);
1209 
1210  internal::StreamedSource* impl_;
1211  };
1212 
1213  /**
1214  * A streaming task which the embedder must run on a background thread to
1215  * stream scripts into V8. Returned by ScriptCompiler::StartStreamingScript.
1216  */
1218  public:
1219  virtual ~ScriptStreamingTask() {}
1220  virtual void Run() = 0;
1221  };
1222 
1229 
1230  // Support the previous API for a transition period.
1232  };
1233 
1234  /**
1235  * Compiles the specified script (context-independent).
1236  * Cached data as part of the source object can be optionally produced to be
1237  * consumed later to speed up compilation of identical source scripts.
1238  *
1239  * Note that when producing cached data, the source must point to NULL for
1240  * cached data. When consuming cached data, the cached data must have been
1241  * produced by the same version of V8.
1242  *
1243  * \param source Script source code.
1244  * \return Compiled script object (context independent; for running it must be
1245  * bound to a context).
1246  */
1247  static Local<UnboundScript> CompileUnbound(
1248  Isolate* isolate, Source* source,
1249  CompileOptions options = kNoCompileOptions);
1250 
1251  /**
1252  * Compiles the specified script (bound to current context).
1253  *
1254  * \param source Script source code.
1255  * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
1256  * using pre_data speeds compilation if it's done multiple times.
1257  * Owned by caller, no references are kept when this function returns.
1258  * \return Compiled script object, bound to the context that was active
1259  * when this function was called. When run it will always use this
1260  * context.
1261  */
1262  static Local<Script> Compile(
1263  Isolate* isolate, Source* source,
1264  CompileOptions options = kNoCompileOptions);
1265 
1266  /**
1267  * Returns a task which streams script data into V8, or NULL if the script
1268  * cannot be streamed. The user is responsible for running the task on a
1269  * background thread and deleting it. When ran, the task starts parsing the
1270  * script, and it will request data from the StreamedSource as needed. When
1271  * ScriptStreamingTask::Run exits, all data has been streamed and the script
1272  * can be compiled (see Compile below).
1273  *
1274  * This API allows to start the streaming with as little data as possible, and
1275  * the remaining data (for example, the ScriptOrigin) is passed to Compile.
1276  */
1278  Isolate* isolate, StreamedSource* source,
1279  CompileOptions options = kNoCompileOptions);
1280 
1281  /**
1282  * Compiles a streamed script (bound to current context).
1283  *
1284  * This can only be called after the streaming has finished
1285  * (ScriptStreamingTask has been run). V8 doesn't construct the source string
1286  * during streaming, so the embedder needs to pass the full source here.
1287  */
1288  static Local<Script> Compile(Isolate* isolate, StreamedSource* source,
1289  Handle<String> full_source_string,
1290  const ScriptOrigin& origin);
1291 
1292  /**
1293  * Return a version tag for CachedData for the current V8 version & flags.
1294  *
1295  * This value is meant only for determining whether a previously generated
1296  * CachedData instance is still valid; the tag has no other meaing.
1297  *
1298  * Background: The data carried by CachedData may depend on the exact
1299  * V8 version number or currently compiler flags. This means when
1300  * persisting CachedData, the embedder must take care to not pass in
1301  * data from another V8 version, or the same version with different
1302  * features enabled.
1303  *
1304  * The easiest way to do so is to clear the embedder's cache on any
1305  * such change.
1306  *
1307  * Alternatively, this tag can be stored alongside the cached data and
1308  * compared when it is being used.
1309  */
1310  static uint32_t CachedDataVersionTag();
1311 
1312  /**
1313  * Compile an ES6 module.
1314  *
1315  * This is an experimental feature.
1316  *
1317  * TODO(adamk): Script is likely the wrong return value for this;
1318  * should return some new Module type.
1319  */
1320  static Local<Script> CompileModule(
1321  Isolate* isolate, Source* source,
1322  CompileOptions options = kNoCompileOptions);
1323 
1324  /**
1325  * Compile a function for a given context. This is equivalent to running
1326  *
1327  * with (obj) {
1328  * return function(args) { ... }
1329  * }
1330  *
1331  * It is possible to specify multiple context extensions (obj in the above
1332  * example).
1333  */
1334  static Local<Function> CompileFunctionInContext(
1335  Isolate* isolate, Source* source, Local<Context> context,
1336  size_t arguments_count, Local<String> arguments[],
1337  size_t context_extension_count, Local<Object> context_extensions[]);
1338 
1339  private:
1340  static Local<UnboundScript> CompileUnboundInternal(Isolate* isolate,
1341  Source* source,
1342  CompileOptions options,
1343  bool is_module);
1344 };
1345 
1346 
1347 /**
1348  * An error message.
1349  */
1351  public:
1352  Local<String> Get() const;
1353  Local<String> GetSourceLine() const;
1354 
1355  /**
1356  * Returns the origin for the script from where the function causing the
1357  * error originates.
1358  */
1359  ScriptOrigin GetScriptOrigin() const;
1360 
1361  /**
1362  * Returns the resource name for the script from where the function causing
1363  * the error originates.
1364  */
1365  Handle<Value> GetScriptResourceName() const;
1366 
1367  /**
1368  * Exception stack trace. By default stack traces are not captured for
1369  * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
1370  * to change this option.
1371  */
1372  Handle<StackTrace> GetStackTrace() const;
1373 
1374  /**
1375  * Returns the number, 1-based, of the line where the error occurred.
1376  */
1377  int GetLineNumber() const;
1378 
1379  /**
1380  * Returns the index within the script of the first character where
1381  * the error occurred.
1382  */
1383  int GetStartPosition() const;
1384 
1385  /**
1386  * Returns the index within the script of the last character where
1387  * the error occurred.
1388  */
1389  int GetEndPosition() const;
1390 
1391  /**
1392  * Returns the index within the line of the first character where
1393  * the error occurred.
1394  */
1395  int GetStartColumn() const;
1396 
1397  /**
1398  * Returns the index within the line of the last character where
1399  * the error occurred.
1400  */
1401  int GetEndColumn() const;
1402 
1403  /**
1404  * Passes on the value set by the embedder when it fed the script from which
1405  * this Message was generated to V8.
1406  */
1407  bool IsSharedCrossOrigin() const;
1408 
1409  // TODO(1245381): Print to a string instead of on a FILE.
1410  static void PrintCurrentStackTrace(Isolate* isolate, FILE* out);
1411 
1412  static const int kNoLineNumberInfo = 0;
1413  static const int kNoColumnInfo = 0;
1414  static const int kNoScriptIdInfo = 0;
1415 };
1416 
1417 
1418 /**
1419  * Representation of a JavaScript stack trace. The information collected is a
1420  * snapshot of the execution stack and the information remains valid after
1421  * execution continues.
1422  */
1424  public:
1425  /**
1426  * Flags that determine what information is placed captured for each
1427  * StackFrame when grabbing the current stack trace.
1428  */
1432  kScriptName = 1 << 2,
1433  kFunctionName = 1 << 3,
1434  kIsEval = 1 << 4,
1435  kIsConstructor = 1 << 5,
1437  kScriptId = 1 << 7,
1441  };
1442 
1443  /**
1444  * Returns a StackFrame at a particular index.
1445  */
1446  Local<StackFrame> GetFrame(uint32_t index) const;
1447 
1448  /**
1449  * Returns the number of StackFrames.
1450  */
1451  int GetFrameCount() const;
1452 
1453  /**
1454  * Returns StackTrace as a v8::Array that contains StackFrame objects.
1455  */
1456  Local<Array> AsArray();
1457 
1458  /**
1459  * Grab a snapshot of the current JavaScript execution stack.
1460  *
1461  * \param frame_limit The maximum number of stack frames we want to capture.
1462  * \param options Enumerates the set of things we will capture for each
1463  * StackFrame.
1464  */
1465  static Local<StackTrace> CurrentStackTrace(
1466  Isolate* isolate,
1467  int frame_limit,
1468  StackTraceOptions options = kOverview);
1469 };
1470 
1471 
1472 /**
1473  * A single JavaScript stack frame.
1474  */
1476  public:
1477  /**
1478  * Returns the number, 1-based, of the line for the associate function call.
1479  * This method will return Message::kNoLineNumberInfo if it is unable to
1480  * retrieve the line number, or if kLineNumber was not passed as an option
1481  * when capturing the StackTrace.
1482  */
1483  int GetLineNumber() const;
1484 
1485  /**
1486  * Returns the 1-based column offset on the line for the associated function
1487  * call.
1488  * This method will return Message::kNoColumnInfo if it is unable to retrieve
1489  * the column number, or if kColumnOffset was not passed as an option when
1490  * capturing the StackTrace.
1491  */
1492  int GetColumn() const;
1493 
1494  /**
1495  * Returns the id of the script for the function for this StackFrame.
1496  * This method will return Message::kNoScriptIdInfo if it is unable to
1497  * retrieve the script id, or if kScriptId was not passed as an option when
1498  * capturing the StackTrace.
1499  */
1500  int GetScriptId() const;
1501 
1502  /**
1503  * Returns the name of the resource that contains the script for the
1504  * function for this StackFrame.
1505  */
1506  Local<String> GetScriptName() const;
1507 
1508  /**
1509  * Returns the name of the resource that contains the script for the
1510  * function for this StackFrame or sourceURL value if the script name
1511  * is undefined and its source ends with //# sourceURL=... string or
1512  * deprecated //@ sourceURL=... string.
1513  */
1514  Local<String> GetScriptNameOrSourceURL() const;
1515 
1516  /**
1517  * Returns the name of the function associated with this stack frame.
1518  */
1519  Local<String> GetFunctionName() const;
1520 
1521  /**
1522  * Returns whether or not the associated function is compiled via a call to
1523  * eval().
1524  */
1525  bool IsEval() const;
1526 
1527  /**
1528  * Returns whether or not the associated function is called as a
1529  * constructor via "new".
1530  */
1531  bool IsConstructor() const;
1532 };
1533 
1534 
1535 // A StateTag represents a possible state of the VM.
1537 
1538 
1539 // A RegisterState represents the current state of registers used
1540 // by the sampling profiler API.
1542  RegisterState() : pc(NULL), sp(NULL), fp(NULL) {}
1543  void* pc; // Instruction pointer.
1544  void* sp; // Stack pointer.
1545  void* fp; // Frame pointer.
1546 };
1547 
1548 
1549 // The output structure filled up by GetStackSample API function.
1550 struct SampleInfo {
1553 };
1554 
1555 
1556 /**
1557  * A JSON Parser.
1558  */
1560  public:
1561  /**
1562  * Tries to parse the string |json_string| and returns it as value if
1563  * successful.
1564  *
1565  * \param json_string The string to parse.
1566  * \return The corresponding value if successfully parsed.
1567  */
1568  static Local<Value> Parse(Local<String> json_string);
1569 };
1570 
1571 
1572 /**
1573  * A map whose keys are referenced weakly. It is similar to JavaScript WeakMap
1574  * but can be created without entering a v8::Context and hence shouldn't
1575  * escape to JavaScript.
1576  */
1577 class V8_EXPORT NativeWeakMap : public Data {
1578  public:
1579  static Local<NativeWeakMap> New(Isolate* isolate);
1580  void Set(Handle<Value> key, Handle<Value> value);
1581  Local<Value> Get(Handle<Value> key);
1582  bool Has(Handle<Value> key);
1583  bool Delete(Handle<Value> key);
1584 };
1585 
1586 
1587 // --- Value ---
1588 
1589 
1590 /**
1591  * The superclass of all JavaScript values and objects.
1592  */
1593 class V8_EXPORT Value : public Data {
1594  public:
1595  /**
1596  * Returns true if this value is the undefined value. See ECMA-262
1597  * 4.3.10.
1598  */
1599  V8_INLINE bool IsUndefined() const;
1600 
1601  /**
1602  * Returns true if this value is the null value. See ECMA-262
1603  * 4.3.11.
1604  */
1605  V8_INLINE bool IsNull() const;
1606 
1607  /**
1608  * Returns true if this value is true.
1609  */
1610  bool IsTrue() const;
1611 
1612  /**
1613  * Returns true if this value is false.
1614  */
1615  bool IsFalse() const;
1616 
1617  /**
1618  * Returns true if this value is a symbol or a string.
1619  * This is an experimental feature.
1620  */
1621  bool IsName() const;
1622 
1623  /**
1624  * Returns true if this value is an instance of the String type.
1625  * See ECMA-262 8.4.
1626  */
1627  V8_INLINE bool IsString() const;
1628 
1629  /**
1630  * Returns true if this value is a symbol.
1631  * This is an experimental feature.
1632  */
1633  bool IsSymbol() const;
1634 
1635  /**
1636  * Returns true if this value is a function.
1637  */
1638  bool IsFunction() const;
1639 
1640  /**
1641  * Returns true if this value is an array.
1642  */
1643  bool IsArray() const;
1644 
1645  /**
1646  * Returns true if this value is an object.
1647  */
1648  bool IsObject() const;
1649 
1650  /**
1651  * Returns true if this value is boolean.
1652  */
1653  bool IsBoolean() const;
1654 
1655  /**
1656  * Returns true if this value is a number.
1657  */
1658  bool IsNumber() const;
1659 
1660  /**
1661  * Returns true if this value is external.
1662  */
1663  bool IsExternal() const;
1664 
1665  /**
1666  * Returns true if this value is a 32-bit signed integer.
1667  */
1668  bool IsInt32() const;
1669 
1670  /**
1671  * Returns true if this value is a 32-bit unsigned integer.
1672  */
1673  bool IsUint32() const;
1674 
1675  /**
1676  * Returns true if this value is a Date.
1677  */
1678  bool IsDate() const;
1679 
1680  /**
1681  * Returns true if this value is an Arguments object.
1682  */
1683  bool IsArgumentsObject() const;
1684 
1685  /**
1686  * Returns true if this value is a Boolean object.
1687  */
1688  bool IsBooleanObject() const;
1689 
1690  /**
1691  * Returns true if this value is a Number object.
1692  */
1693  bool IsNumberObject() const;
1694 
1695  /**
1696  * Returns true if this value is a String object.
1697  */
1698  bool IsStringObject() const;
1699 
1700  /**
1701  * Returns true if this value is a Symbol object.
1702  * This is an experimental feature.
1703  */
1704  bool IsSymbolObject() const;
1705 
1706  /**
1707  * Returns true if this value is a NativeError.
1708  */
1709  bool IsNativeError() const;
1710 
1711  /**
1712  * Returns true if this value is a RegExp.
1713  */
1714  bool IsRegExp() const;
1715 
1716  /**
1717  * Returns true if this value is a Generator function.
1718  * This is an experimental feature.
1719  */
1720  bool IsGeneratorFunction() const;
1721 
1722  /**
1723  * Returns true if this value is a Generator object (iterator).
1724  * This is an experimental feature.
1725  */
1726  bool IsGeneratorObject() const;
1727 
1728  /**
1729  * Returns true if this value is a Promise.
1730  * This is an experimental feature.
1731  */
1732  bool IsPromise() const;
1733 
1734  /**
1735  * Returns true if this value is a Map.
1736  * This is an experimental feature.
1737  */
1738  bool IsMap() const;
1739 
1740  /**
1741  * Returns true if this value is a Set.
1742  * This is an experimental feature.
1743  */
1744  bool IsSet() const;
1745 
1746  /**
1747  * Returns true if this value is a Map Iterator.
1748  * This is an experimental feature.
1749  */
1750  bool IsMapIterator() const;
1751 
1752  /**
1753  * Returns true if this value is a Set Iterator.
1754  * This is an experimental feature.
1755  */
1756  bool IsSetIterator() const;
1757 
1758  /**
1759  * Returns true if this value is a WeakMap.
1760  * This is an experimental feature.
1761  */
1762  bool IsWeakMap() const;
1763 
1764  /**
1765  * Returns true if this value is a WeakSet.
1766  * This is an experimental feature.
1767  */
1768  bool IsWeakSet() const;
1769 
1770  /**
1771  * Returns true if this value is an ArrayBuffer.
1772  * This is an experimental feature.
1773  */
1774  bool IsArrayBuffer() const;
1775 
1776  /**
1777  * Returns true if this value is an ArrayBufferView.
1778  * This is an experimental feature.
1779  */
1780  bool IsArrayBufferView() const;
1781 
1782  /**
1783  * Returns true if this value is one of TypedArrays.
1784  * This is an experimental feature.
1785  */
1786  bool IsTypedArray() const;
1787 
1788  /**
1789  * Returns true if this value is an Uint8Array.
1790  * This is an experimental feature.
1791  */
1792  bool IsUint8Array() const;
1793 
1794  /**
1795  * Returns true if this value is an Uint8ClampedArray.
1796  * This is an experimental feature.
1797  */
1798  bool IsUint8ClampedArray() const;
1799 
1800  /**
1801  * Returns true if this value is an Int8Array.
1802  * This is an experimental feature.
1803  */
1804  bool IsInt8Array() const;
1805 
1806  /**
1807  * Returns true if this value is an Uint16Array.
1808  * This is an experimental feature.
1809  */
1810  bool IsUint16Array() const;
1811 
1812  /**
1813  * Returns true if this value is an Int16Array.
1814  * This is an experimental feature.
1815  */
1816  bool IsInt16Array() const;
1817 
1818  /**
1819  * Returns true if this value is an Uint32Array.
1820  * This is an experimental feature.
1821  */
1822  bool IsUint32Array() const;
1823 
1824  /**
1825  * Returns true if this value is an Int32Array.
1826  * This is an experimental feature.
1827  */
1828  bool IsInt32Array() const;
1829 
1830  /**
1831  * Returns true if this value is a Float32Array.
1832  * This is an experimental feature.
1833  */
1834  bool IsFloat32Array() const;
1835 
1836  /**
1837  * Returns true if this value is a Float64Array.
1838  * This is an experimental feature.
1839  */
1840  bool IsFloat64Array() const;
1841 
1842  /**
1843  * Returns true if this value is a DataView.
1844  * This is an experimental feature.
1845  */
1846  bool IsDataView() const;
1847 
1848  Local<Boolean> ToBoolean(Isolate* isolate) const;
1849  Local<Number> ToNumber(Isolate* isolate) const;
1850  Local<String> ToString(Isolate* isolate) const;
1851  Local<String> ToDetailString(Isolate* isolate) const;
1852  Local<Object> ToObject(Isolate* isolate) const;
1853  Local<Integer> ToInteger(Isolate* isolate) const;
1854  Local<Uint32> ToUint32(Isolate* isolate) const;
1855  Local<Int32> ToInt32(Isolate* isolate) const;
1856 
1857  // TODO(dcarney): deprecate all these.
1858  inline Local<Boolean> ToBoolean() const;
1859  inline Local<Number> ToNumber() const;
1860  inline Local<String> ToString() const;
1861  inline Local<String> ToDetailString() const;
1862  inline Local<Object> ToObject() const;
1863  inline Local<Integer> ToInteger() const;
1864  inline Local<Uint32> ToUint32() const;
1865  inline Local<Int32> ToInt32() const;
1866 
1867  /**
1868  * Attempts to convert a string to an array index.
1869  * Returns an empty handle if the conversion fails.
1870  */
1871  Local<Uint32> ToArrayIndex() const;
1872 
1873  bool BooleanValue() const;
1874  double NumberValue() const;
1875  int64_t IntegerValue() const;
1876  uint32_t Uint32Value() const;
1877  int32_t Int32Value() const;
1878 
1879  /** JS == */
1880  bool Equals(Handle<Value> that) const;
1881  bool StrictEquals(Handle<Value> that) const;
1882  bool SameValue(Handle<Value> that) const;
1883 
1884  template <class T> V8_INLINE static Value* Cast(T* value);
1885 
1886  private:
1887  V8_INLINE bool QuickIsUndefined() const;
1888  V8_INLINE bool QuickIsNull() const;
1889  V8_INLINE bool QuickIsString() const;
1890  bool FullIsUndefined() const;
1891  bool FullIsNull() const;
1892  bool FullIsString() const;
1893 };
1894 
1895 
1896 /**
1897  * The superclass of primitive values. See ECMA-262 4.3.2.
1898  */
1899 class V8_EXPORT Primitive : public Value { };
1900 
1901 
1902 /**
1903  * A primitive boolean value (ECMA-262, 4.3.14). Either the true
1904  * or false value.
1905  */
1906 class V8_EXPORT Boolean : public Primitive {
1907  public:
1908  bool Value() const;
1909  V8_INLINE static Handle<Boolean> New(Isolate* isolate, bool value);
1910 };
1911 
1912 
1913 /**
1914  * A superclass for symbols and strings.
1915  */
1916 class V8_EXPORT Name : public Primitive {
1917  public:
1918  /**
1919  * Returns the identity hash for this object. The current implementation
1920  * uses an inline property on the object to store the identity hash.
1921  *
1922  * The return value will never be 0. Also, it is not guaranteed to be
1923  * unique.
1924  */
1925  int GetIdentityHash();
1926 
1927  V8_INLINE static Name* Cast(v8::Value* obj);
1928  private:
1929  static void CheckCast(v8::Value* obj);
1930 };
1931 
1932 
1933 /**
1934  * A JavaScript string value (ECMA-262, 4.3.17).
1935  */
1936 class V8_EXPORT String : public Name {
1937  public:
1938  enum Encoding {
1942  };
1943  /**
1944  * Returns the number of characters in this string.
1945  */
1946  int Length() const;
1947 
1948  /**
1949  * Returns the number of bytes in the UTF-8 encoded
1950  * representation of this string.
1951  */
1952  int Utf8Length() const;
1953 
1954  /**
1955  * Returns whether this string is known to contain only one byte data.
1956  * Does not read the string.
1957  * False negatives are possible.
1958  */
1959  bool IsOneByte() const;
1960 
1961  /**
1962  * Returns whether this string contain only one byte data.
1963  * Will read the entire string in some cases.
1964  */
1965  bool ContainsOnlyOneByte() const;
1966 
1967  /**
1968  * Write the contents of the string to an external buffer.
1969  * If no arguments are given, expects the buffer to be large
1970  * enough to hold the entire string and NULL terminator. Copies
1971  * the contents of the string and the NULL terminator into the
1972  * buffer.
1973  *
1974  * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
1975  * before the end of the buffer.
1976  *
1977  * Copies up to length characters into the output buffer.
1978  * Only null-terminates if there is enough space in the buffer.
1979  *
1980  * \param buffer The buffer into which the string will be copied.
1981  * \param start The starting position within the string at which
1982  * copying begins.
1983  * \param length The number of characters to copy from the string. For
1984  * WriteUtf8 the number of bytes in the buffer.
1985  * \param nchars_ref The number of characters written, can be NULL.
1986  * \param options Various options that might affect performance of this or
1987  * subsequent operations.
1988  * \return The number of characters copied to the buffer excluding the null
1989  * terminator. For WriteUtf8: The number of bytes copied to the buffer
1990  * including the null terminator (if written).
1991  */
1997  // Used by WriteUtf8 to replace orphan surrogate code units with the
1998  // unicode replacement character. Needs to be set to guarantee valid UTF-8
1999  // output.
2001  };
2002 
2003  // 16-bit character codes.
2004  int Write(uint16_t* buffer,
2005  int start = 0,
2006  int length = -1,
2007  int options = NO_OPTIONS) const;
2008  // One byte characters.
2009  int WriteOneByte(uint8_t* buffer,
2010  int start = 0,
2011  int length = -1,
2012  int options = NO_OPTIONS) const;
2013  // UTF-8 encoded characters.
2014  int WriteUtf8(char* buffer,
2015  int length = -1,
2016  int* nchars_ref = NULL,
2017  int options = NO_OPTIONS) const;
2018 
2019  /**
2020  * A zero length string.
2021  */
2022  V8_INLINE static v8::Local<v8::String> Empty(Isolate* isolate);
2023 
2024  /**
2025  * Returns true if the string is external
2026  */
2027  bool IsExternal() const;
2028 
2029  /**
2030  * Returns true if the string is both external and one-byte.
2031  */
2032  bool IsExternalOneByte() const;
2033 
2035  public:
2037 
2038  protected:
2040 
2041  /**
2042  * Internally V8 will call this Dispose method when the external string
2043  * resource is no longer needed. The default implementation will use the
2044  * delete operator. This method can be overridden in subclasses to
2045  * control how allocated external string resources are disposed.
2046  */
2047  virtual void Dispose() { delete this; }
2048 
2049  private:
2050  // Disallow copying and assigning.
2051  ExternalStringResourceBase(const ExternalStringResourceBase&);
2052  void operator=(const ExternalStringResourceBase&);
2053 
2054  friend class v8::internal::Heap;
2055  };
2056 
2057  /**
2058  * An ExternalStringResource is a wrapper around a two-byte string
2059  * buffer that resides outside V8's heap. Implement an
2060  * ExternalStringResource to manage the life cycle of the underlying
2061  * buffer. Note that the string data must be immutable.
2062  */
2064  : public ExternalStringResourceBase {
2065  public:
2066  /**
2067  * Override the destructor to manage the life cycle of the underlying
2068  * buffer.
2069  */
2071 
2072  /**
2073  * The string data from the underlying buffer.
2074  */
2075  virtual const uint16_t* data() const = 0;
2076 
2077  /**
2078  * The length of the string. That is, the number of two-byte characters.
2079  */
2080  virtual size_t length() const = 0;
2081 
2082  protected:
2084  };
2085 
2086  /**
2087  * An ExternalOneByteStringResource is a wrapper around an one-byte
2088  * string buffer that resides outside V8's heap. Implement an
2089  * ExternalOneByteStringResource to manage the life cycle of the
2090  * underlying buffer. Note that the string data must be immutable
2091  * and that the data must be Latin-1 and not UTF-8, which would require
2092  * special treatment internally in the engine and do not allow efficient
2093  * indexing. Use String::New or convert to 16 bit data for non-Latin1.
2094  */
2095 
2097  : public ExternalStringResourceBase {
2098  public:
2099  /**
2100  * Override the destructor to manage the life cycle of the underlying
2101  * buffer.
2102  */
2104  /** The string data from the underlying buffer.*/
2105  virtual const char* data() const = 0;
2106  /** The number of Latin-1 characters in the string.*/
2107  virtual size_t length() const = 0;
2108  protected:
2110  };
2111 
2112  /**
2113  * If the string is an external string, return the ExternalStringResourceBase
2114  * regardless of the encoding, otherwise return NULL. The encoding of the
2115  * string is returned in encoding_out.
2116  */
2118  Encoding* encoding_out) const;
2119 
2120  /**
2121  * Get the ExternalStringResource for an external string. Returns
2122  * NULL if IsExternal() doesn't return true.
2123  */
2125 
2126  /**
2127  * Get the ExternalOneByteStringResource for an external one-byte string.
2128  * Returns NULL if IsExternalOneByte() doesn't return true.
2129  */
2131 
2132  V8_INLINE static String* Cast(v8::Value* obj);
2133 
2135 
2136  /** Allocates a new string from UTF-8 data.*/
2137  static Local<String> NewFromUtf8(Isolate* isolate, const char* data,
2139  int length = -1);
2140 
2141  /** Allocates a new string from Latin-1 data.*/
2142  static Local<String> NewFromOneByte(
2143  Isolate* isolate,
2144  const uint8_t* data,
2146  int length = -1);
2147 
2148  /** Allocates a new string from UTF-16 data.*/
2149  static Local<String> NewFromTwoByte(
2150  Isolate* isolate,
2151  const uint16_t* data,
2153  int length = -1);
2154 
2155  /**
2156  * Creates a new string by concatenating the left and the right strings
2157  * passed in as parameters.
2158  */
2159  static Local<String> Concat(Handle<String> left, Handle<String> right);
2160 
2161  /**
2162  * Creates a new external string using the data defined in the given
2163  * resource. When the external string is no longer live on V8's heap the
2164  * resource will be disposed by calling its Dispose method. The caller of
2165  * this function should not otherwise delete or modify the resource. Neither
2166  * should the underlying buffer be deallocated or modified except through the
2167  * destructor of the external string resource.
2168  */
2169  static Local<String> NewExternal(Isolate* isolate,
2170  ExternalStringResource* resource);
2171 
2172  /**
2173  * Associate an external string resource with this string by transforming it
2174  * in place so that existing references to this string in the JavaScript heap
2175  * will use the external string resource. The external string resource's
2176  * character contents need to be equivalent to this string.
2177  * Returns true if the string has been changed to be an external string.
2178  * The string is not modified if the operation fails. See NewExternal for
2179  * information on the lifetime of the resource.
2180  */
2181  bool MakeExternal(ExternalStringResource* resource);
2182 
2183  /**
2184  * Creates a new external string using the one-byte data defined in the given
2185  * resource. When the external string is no longer live on V8's heap the
2186  * resource will be disposed by calling its Dispose method. The caller of
2187  * this function should not otherwise delete or modify the resource. Neither
2188  * should the underlying buffer be deallocated or modified except through the
2189  * destructor of the external string resource.
2190  */
2191  static Local<String> NewExternal(Isolate* isolate,
2192  ExternalOneByteStringResource* resource);
2193 
2194  /**
2195  * Associate an external string resource with this string by transforming it
2196  * in place so that existing references to this string in the JavaScript heap
2197  * will use the external string resource. The external string resource's
2198  * character contents need to be equivalent to this string.
2199  * Returns true if the string has been changed to be an external string.
2200  * The string is not modified if the operation fails. See NewExternal for
2201  * information on the lifetime of the resource.
2202  */
2204 
2205  /**
2206  * Returns true if this string can be made external.
2207  */
2208  bool CanMakeExternal();
2209 
2210  /**
2211  * Converts an object to a UTF-8-encoded character array. Useful if
2212  * you want to print the object. If conversion to a string fails
2213  * (e.g. due to an exception in the toString() method of the object)
2214  * then the length() method returns 0 and the * operator returns
2215  * NULL.
2216  */
2218  public:
2219  explicit Utf8Value(Handle<v8::Value> obj);
2220  ~Utf8Value();
2221  char* operator*() { return str_; }
2222  const char* operator*() const { return str_; }
2223  int length() const { return length_; }
2224  private:
2225  char* str_;
2226  int length_;
2227 
2228  // Disallow copying and assigning.
2229  Utf8Value(const Utf8Value&);
2230  void operator=(const Utf8Value&);
2231  };
2232 
2233  /**
2234  * Converts an object to a two-byte string.
2235  * If conversion to a string fails (eg. due to an exception in the toString()
2236  * method of the object) then the length() method returns 0 and the * operator
2237  * returns NULL.
2238  */
2240  public:
2241  explicit Value(Handle<v8::Value> obj);
2242  ~Value();
2243  uint16_t* operator*() { return str_; }
2244  const uint16_t* operator*() const { return str_; }
2245  int length() const { return length_; }
2246  private:
2247  uint16_t* str_;
2248  int length_;
2249 
2250  // Disallow copying and assigning.
2251  Value(const Value&);
2252  void operator=(const Value&);
2253  };
2254 
2255  private:
2256  void VerifyExternalStringResourceBase(ExternalStringResourceBase* v,
2257  Encoding encoding) const;
2258  void VerifyExternalStringResource(ExternalStringResource* val) const;
2259  static void CheckCast(v8::Value* obj);
2260 };
2261 
2262 
2263 /**
2264  * A JavaScript symbol (ECMA-262 edition 6)
2265  *
2266  * This is an experimental feature. Use at your own risk.
2267  */
2268 class V8_EXPORT Symbol : public Name {
2269  public:
2270  // Returns the print name string of the symbol, or undefined if none.
2271  Local<Value> Name() const;
2272 
2273  // Create a symbol. If name is not empty, it will be used as the description.
2274  static Local<Symbol> New(
2275  Isolate *isolate, Local<String> name = Local<String>());
2276 
2277  // Access global symbol registry.
2278  // Note that symbols created this way are never collected, so
2279  // they should only be used for statically fixed properties.
2280  // Also, there is only one global name space for the names used as keys.
2281  // To minimize the potential for clashes, use qualified names as keys.
2282  static Local<Symbol> For(Isolate *isolate, Local<String> name);
2283 
2284  // Retrieve a global symbol. Similar to |For|, but using a separate
2285  // registry that is not accessible by (and cannot clash with) JavaScript code.
2286  static Local<Symbol> ForApi(Isolate *isolate, Local<String> name);
2287 
2288  // Well-known symbols
2289  static Local<Symbol> GetIterator(Isolate* isolate);
2290  static Local<Symbol> GetUnscopables(Isolate* isolate);
2291  static Local<Symbol> GetToStringTag(Isolate* isolate);
2292 
2293  V8_INLINE static Symbol* Cast(v8::Value* obj);
2294 
2295  private:
2296  Symbol();
2297  static void CheckCast(v8::Value* obj);
2298 };
2299 
2300 
2301 /**
2302  * A private symbol
2303  *
2304  * This is an experimental feature. Use at your own risk.
2305  */
2306 class V8_EXPORT Private : public Data {
2307  public:
2308  // Returns the print name string of the private symbol, or undefined if none.
2309  Local<Value> Name() const;
2310 
2311  // Create a private symbol. If name is not empty, it will be the description.
2312  static Local<Private> New(
2313  Isolate *isolate, Local<String> name = Local<String>());
2314 
2315  // Retrieve a global private symbol. If a symbol with this name has not
2316  // been retrieved in the same isolate before, it is created.
2317  // Note that private symbols created this way are never collected, so
2318  // they should only be used for statically fixed properties.
2319  // Also, there is only one global name space for the names used as keys.
2320  // To minimize the potential for clashes, use qualified names as keys,
2321  // e.g., "Class#property".
2322  static Local<Private> ForApi(Isolate *isolate, Local<String> name);
2323 
2324  private:
2325  Private();
2326 };
2327 
2328 
2329 /**
2330  * A JavaScript number value (ECMA-262, 4.3.20)
2331  */
2332 class V8_EXPORT Number : public Primitive {
2333  public:
2334  double Value() const;
2335  static Local<Number> New(Isolate* isolate, double value);
2336  V8_INLINE static Number* Cast(v8::Value* obj);
2337  private:
2338  Number();
2339  static void CheckCast(v8::Value* obj);
2340 };
2341 
2342 
2343 /**
2344  * A JavaScript value representing a signed integer.
2345  */
2346 class V8_EXPORT Integer : public Number {
2347  public:
2348  static Local<Integer> New(Isolate* isolate, int32_t value);
2349  static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value);
2350  int64_t Value() const;
2351  V8_INLINE static Integer* Cast(v8::Value* obj);
2352  private:
2353  Integer();
2354  static void CheckCast(v8::Value* obj);
2355 };
2356 
2357 
2358 /**
2359  * A JavaScript value representing a 32-bit signed integer.
2360  */
2361 class V8_EXPORT Int32 : public Integer {
2362  public:
2363  int32_t Value() const;
2364  private:
2365  Int32();
2366 };
2367 
2368 
2369 /**
2370  * A JavaScript value representing a 32-bit unsigned integer.
2371  */
2372 class V8_EXPORT Uint32 : public Integer {
2373  public:
2374  uint32_t Value() const;
2375  private:
2376  Uint32();
2377 };
2378 
2379 
2381  None = 0,
2382  ReadOnly = 1 << 0,
2383  DontEnum = 1 << 1,
2384  DontDelete = 1 << 2
2385 };
2386 
2397 
2398  // Legacy constant names
2408 };
2409 
2410 /**
2411  * Accessor[Getter|Setter] are used as callback functions when
2412  * setting|getting a particular property. See Object and ObjectTemplate's
2413  * method SetAccessor.
2414  */
2415 typedef void (*AccessorGetterCallback)(
2416  Local<String> property,
2417  const PropertyCallbackInfo<Value>& info);
2419  Local<Name> property,
2420  const PropertyCallbackInfo<Value>& info);
2421 
2422 
2423 typedef void (*AccessorSetterCallback)(
2424  Local<String> property,
2425  Local<Value> value,
2426  const PropertyCallbackInfo<void>& info);
2428  Local<Name> property,
2429  Local<Value> value,
2430  const PropertyCallbackInfo<void>& info);
2431 
2432 
2433 /**
2434  * Access control specifications.
2435  *
2436  * Some accessors should be accessible across contexts. These
2437  * accessors have an explicit access control parameter which specifies
2438  * the kind of cross-context access that should be allowed.
2439  *
2440  * TODO(dcarney): Remove PROHIBITS_OVERWRITING as it is now unused.
2441  */
2443  DEFAULT = 0,
2445  ALL_CAN_WRITE = 1 << 1,
2447 };
2448 
2449 
2450 /**
2451  * A JavaScript object (ECMA-262, 4.3.3)
2452  */
2453 class V8_EXPORT Object : public Value {
2454  public:
2455  bool Set(Handle<Value> key, Handle<Value> value);
2456 
2457  bool Set(uint32_t index, Handle<Value> value);
2458 
2459  // Sets an own property on this object bypassing interceptors and
2460  // overriding accessors or read-only properties.
2461  //
2462  // Note that if the object has an interceptor the property will be set
2463  // locally, but since the interceptor takes precedence the local property
2464  // will only be returned if the interceptor doesn't return a value.
2465  //
2466  // Note also that this only works for named properties.
2467  bool ForceSet(Handle<Value> key,
2468  Handle<Value> value,
2469  PropertyAttribute attribs = None);
2470 
2471  Local<Value> Get(Handle<Value> key);
2472 
2473  Local<Value> Get(uint32_t index);
2474 
2475  /**
2476  * Gets the property attributes of a property which can be None or
2477  * any combination of ReadOnly, DontEnum and DontDelete. Returns
2478  * None when the property doesn't exist.
2479  */
2481 
2482  /**
2483  * Returns Object.getOwnPropertyDescriptor as per ES5 section 15.2.3.3.
2484  */
2485  Local<Value> GetOwnPropertyDescriptor(Local<String> key);
2486 
2487  bool Has(Handle<Value> key);
2488 
2489  bool Delete(Handle<Value> key);
2490 
2491  bool Has(uint32_t index);
2492 
2493  bool Delete(uint32_t index);
2494 
2495  bool SetAccessor(Handle<String> name,
2496  AccessorGetterCallback getter,
2497  AccessorSetterCallback setter = 0,
2498  Handle<Value> data = Handle<Value>(),
2499  AccessControl settings = DEFAULT,
2500  PropertyAttribute attribute = None);
2501  bool SetAccessor(Handle<Name> name,
2503  AccessorNameSetterCallback setter = 0,
2504  Handle<Value> data = Handle<Value>(),
2505  AccessControl settings = DEFAULT,
2506  PropertyAttribute attribute = None);
2507 
2508  void SetAccessorProperty(Local<Name> name,
2509  Local<Function> getter,
2510  Handle<Function> setter = Handle<Function>(),
2511  PropertyAttribute attribute = None,
2512  AccessControl settings = DEFAULT);
2513 
2514  /**
2515  * Functionality for private properties.
2516  * This is an experimental feature, use at your own risk.
2517  * Note: Private properties are inherited. Do not rely on this, since it may
2518  * change.
2519  */
2520  bool HasPrivate(Handle<Private> key);
2521  bool SetPrivate(Handle<Private> key, Handle<Value> value);
2522  bool DeletePrivate(Handle<Private> key);
2523  Local<Value> GetPrivate(Handle<Private> key);
2524 
2525  /**
2526  * Returns an array containing the names of the enumerable properties
2527  * of this object, including properties from prototype objects. The
2528  * array returned by this method contains the same values as would
2529  * be enumerated by a for-in statement over this object.
2530  */
2531  Local<Array> GetPropertyNames();
2532 
2533  /**
2534  * This function has the same functionality as GetPropertyNames but
2535  * the returned array doesn't contain the names of properties from
2536  * prototype objects.
2537  */
2538  Local<Array> GetOwnPropertyNames();
2539 
2540  /**
2541  * Get the prototype object. This does not skip objects marked to
2542  * be skipped by __proto__ and it does not consult the security
2543  * handler.
2544  */
2545  Local<Value> GetPrototype();
2546 
2547  /**
2548  * Set the prototype object. This does not skip objects marked to
2549  * be skipped by __proto__ and it does not consult the security
2550  * handler.
2551  */
2552  bool SetPrototype(Handle<Value> prototype);
2553 
2554  /**
2555  * Finds an instance of the given function template in the prototype
2556  * chain.
2557  */
2559 
2560  /**
2561  * Call builtin Object.prototype.toString on this object.
2562  * This is different from Value::ToString() that may call
2563  * user-defined toString function. This one does not.
2564  */
2565  Local<String> ObjectProtoToString();
2566 
2567  /**
2568  * Returns the name of the function invoked as a constructor for this object.
2569  */
2570  Local<String> GetConstructorName();
2571 
2572  /** Gets the number of internal fields for this Object. */
2573  int InternalFieldCount();
2574 
2575  /** Same as above, but works for Persistents */
2577  const PersistentBase<Object>& object) {
2578  return object.val_->InternalFieldCount();
2579  }
2580 
2581  /** Gets the value from an internal field. */
2582  V8_INLINE Local<Value> GetInternalField(int index);
2583 
2584  /** Sets the value in an internal field. */
2585  void SetInternalField(int index, Handle<Value> value);
2586 
2587  /**
2588  * Gets a 2-byte-aligned native pointer from an internal field. This field
2589  * must have been set by SetAlignedPointerInInternalField, everything else
2590  * leads to undefined behavior.
2591  */
2593 
2594  /** Same as above, but works for Persistents */
2596  const PersistentBase<Object>& object, int index) {
2597  return object.val_->GetAlignedPointerFromInternalField(index);
2598  }
2599 
2600  /**
2601  * Sets a 2-byte-aligned native pointer in an internal field. To retrieve such
2602  * a field, GetAlignedPointerFromInternalField must be used, everything else
2603  * leads to undefined behavior.
2604  */
2605  void SetAlignedPointerInInternalField(int index, void* value);
2606 
2607  // Testers for local properties.
2608  bool HasOwnProperty(Handle<String> key);
2609  bool HasRealNamedProperty(Handle<String> key);
2610  bool HasRealIndexedProperty(uint32_t index);
2611  bool HasRealNamedCallbackProperty(Handle<String> key);
2612 
2613  /**
2614  * If result.IsEmpty() no real property was located in the prototype chain.
2615  * This means interceptors in the prototype chain are not called.
2616  */
2618 
2619  /**
2620  * If result.IsEmpty() no real property was located on the object or
2621  * in the prototype chain.
2622  * This means interceptors in the prototype chain are not called.
2623  */
2624  Local<Value> GetRealNamedProperty(Handle<String> key);
2625 
2626  /** Tests for a named lookup interceptor.*/
2628 
2629  /** Tests for an index lookup interceptor.*/
2631 
2632  /**
2633  * Turns on access check on the object if the object is an instance of
2634  * a template that has access check callbacks. If an object has no
2635  * access check info, the object cannot be accessed by anyone.
2636  */
2637  void TurnOnAccessCheck();
2638 
2639  /**
2640  * Returns the identity hash for this object. The current implementation
2641  * uses a hidden property on the object to store the identity hash.
2642  *
2643  * The return value will never be 0. Also, it is not guaranteed to be
2644  * unique.
2645  */
2646  int GetIdentityHash();
2647 
2648  /**
2649  * Access hidden properties on JavaScript objects. These properties are
2650  * hidden from the executing JavaScript and only accessible through the V8
2651  * C++ API. Hidden properties introduced by V8 internally (for example the
2652  * identity hash) are prefixed with "v8::".
2653  */
2654  bool SetHiddenValue(Handle<String> key, Handle<Value> value);
2655  Local<Value> GetHiddenValue(Handle<String> key);
2656  bool DeleteHiddenValue(Handle<String> key);
2657 
2658  /**
2659  * Clone this object with a fast but shallow copy. Values will point
2660  * to the same values as the original object.
2661  */
2662  Local<Object> Clone();
2663 
2664  /**
2665  * Returns the context in which the object was created.
2666  */
2667  Local<Context> CreationContext();
2668 
2669  /**
2670  * Set the backing store of the indexed properties to be managed by the
2671  * embedding layer. Access to the indexed properties will follow the rules
2672  * spelled out in CanvasPixelArray.
2673  * Note: The embedding program still owns the data and needs to ensure that
2674  * the backing store is preserved while V8 has a reference.
2675  */
2676  void SetIndexedPropertiesToPixelData(uint8_t* data, int length);
2678  uint8_t* GetIndexedPropertiesPixelData();
2680 
2681  /**
2682  * Set the backing store of the indexed properties to be managed by the
2683  * embedding layer. Access to the indexed properties will follow the rules
2684  * spelled out for the CanvasArray subtypes in the WebGL specification.
2685  * Note: The embedding program still owns the data and needs to ensure that
2686  * the backing store is preserved while V8 has a reference.
2687  */
2689  ExternalArrayType array_type,
2690  int number_of_elements);
2695 
2696  /**
2697  * Checks whether a callback is set by the
2698  * ObjectTemplate::SetCallAsFunctionHandler method.
2699  * When an Object is callable this method returns true.
2700  */
2701  bool IsCallable();
2702 
2703  /**
2704  * Call an Object as a function if a callback is set by the
2705  * ObjectTemplate::SetCallAsFunctionHandler method.
2706  */
2707  Local<Value> CallAsFunction(Handle<Value> recv,
2708  int argc,
2709  Handle<Value> argv[]);
2710 
2711  /**
2712  * Call an Object as a constructor if a callback is set by the
2713  * ObjectTemplate::SetCallAsFunctionHandler method.
2714  * Note: This method behaves like the Function::NewInstance method.
2715  */
2716  Local<Value> CallAsConstructor(int argc, Handle<Value> argv[]);
2717 
2718  /**
2719  * Return the isolate to which the Object belongs to.
2720  */
2721  Isolate* GetIsolate();
2722 
2723  static Local<Object> New(Isolate* isolate);
2724 
2725  V8_INLINE static Object* Cast(Value* obj);
2726 
2727  private:
2728  Object();
2729  static void CheckCast(Value* obj);
2730  Local<Value> SlowGetInternalField(int index);
2731  void* SlowGetAlignedPointerFromInternalField(int index);
2732 };
2733 
2734 
2735 /**
2736  * An instance of the built-in array constructor (ECMA-262, 15.4.2).
2737  */
2738 class V8_EXPORT Array : public Object {
2739  public:
2740  uint32_t Length() const;
2741 
2742  /**
2743  * Clones an element at index |index|. Returns an empty
2744  * handle if cloning fails (for any reason).
2745  */
2746  Local<Object> CloneElementAt(uint32_t index);
2747 
2748  /**
2749  * Creates a JavaScript array with the given length. If the length
2750  * is negative the returned array will have length 0.
2751  */
2752  static Local<Array> New(Isolate* isolate, int length = 0);
2753 
2754  V8_INLINE static Array* Cast(Value* obj);
2755  private:
2756  Array();
2757  static void CheckCast(Value* obj);
2758 };
2759 
2760 
2761 template<typename T>
2762 class ReturnValue {
2763  public:
2764  template <class S> V8_INLINE ReturnValue(const ReturnValue<S>& that)
2765  : value_(that.value_) {
2766  TYPE_CHECK(T, S);
2767  }
2768  // Handle setters
2769  template <typename S> V8_INLINE void Set(const Persistent<S>& handle);
2770  template <typename S> V8_INLINE void Set(const Handle<S> handle);
2771  // Fast primitive setters
2772  V8_INLINE void Set(bool value);
2773  V8_INLINE void Set(double i);
2774  V8_INLINE void Set(int32_t i);
2775  V8_INLINE void Set(uint32_t i);
2776  // Fast JS primitive setters
2777  V8_INLINE void SetNull();
2778  V8_INLINE void SetUndefined();
2779  V8_INLINE void SetEmptyString();
2780  // Convenience getter for Isolate
2782 
2783  // Pointer setter: Uncompilable to prevent inadvertent misuse.
2784  template <typename S>
2785  V8_INLINE void Set(S* whatever);
2786 
2787  private:
2788  template<class F> friend class ReturnValue;
2789  template<class F> friend class FunctionCallbackInfo;
2790  template<class F> friend class PropertyCallbackInfo;
2791  template <class F, class G, class H>
2793  V8_INLINE void SetInternal(internal::Object* value) { *value_ = value; }
2794  V8_INLINE internal::Object* GetDefaultValue();
2795  V8_INLINE explicit ReturnValue(internal::Object** slot);
2796  internal::Object** value_;
2797 };
2798 
2799 
2800 /**
2801  * The argument information given to function call callbacks. This
2802  * class provides access to information about the context of the call,
2803  * including the receiver, the number and values of arguments, and
2804  * the holder of the function.
2805  */
2806 template<typename T>
2807 class FunctionCallbackInfo {
2808  public:
2809  V8_INLINE int Length() const;
2810  V8_INLINE Local<Value> operator[](int i) const;
2811  V8_INLINE Local<Function> Callee() const;
2812  V8_INLINE Local<Object> This() const;
2813  V8_INLINE Local<Object> Holder() const;
2814  V8_INLINE bool IsConstructCall() const;
2815  V8_INLINE Local<Value> Data() const;
2816  V8_INLINE Isolate* GetIsolate() const;
2817  V8_INLINE ReturnValue<T> GetReturnValue() const;
2818  // This shouldn't be public, but the arm compiler needs it.
2819  static const int kArgsLength = 7;
2820 
2821  protected:
2824  static const int kHolderIndex = 0;
2825  static const int kIsolateIndex = 1;
2826  static const int kReturnValueDefaultValueIndex = 2;
2827  static const int kReturnValueIndex = 3;
2828  static const int kDataIndex = 4;
2829  static const int kCalleeIndex = 5;
2830  static const int kContextSaveIndex = 6;
2831 
2832  V8_INLINE FunctionCallbackInfo(internal::Object** implicit_args,
2833  internal::Object** values,
2834  int length,
2835  bool is_construct_call);
2837  internal::Object** values_;
2838  int length_;
2840 };
2841 
2842 
2843 /**
2844  * The information passed to a property callback about the context
2845  * of the property access.
2846  */
2847 template<typename T>
2848 class PropertyCallbackInfo {
2849  public:
2850  V8_INLINE Isolate* GetIsolate() const;
2851  V8_INLINE Local<Value> Data() const;
2852  V8_INLINE Local<Object> This() const;
2853  V8_INLINE Local<Object> Holder() const;
2854  V8_INLINE ReturnValue<T> GetReturnValue() const;
2855  // This shouldn't be public, but the arm compiler needs it.
2856  static const int kArgsLength = 6;
2857 
2858  protected:
2859  friend class MacroAssembler;
2862  static const int kHolderIndex = 0;
2863  static const int kIsolateIndex = 1;
2864  static const int kReturnValueDefaultValueIndex = 2;
2865  static const int kReturnValueIndex = 3;
2866  static const int kDataIndex = 4;
2867  static const int kThisIndex = 5;
2868 
2869  V8_INLINE PropertyCallbackInfo(internal::Object** args) : args_(args) {}
2870  internal::Object** args_;
2871 };
2872 
2873 
2874 typedef void (*FunctionCallback)(const FunctionCallbackInfo<Value>& info);
2875 
2876 
2877 /**
2878  * A JavaScript function object (ECMA-262, 15.3).
2879  */
2880 class V8_EXPORT Function : public Object {
2881  public:
2882  /**
2883  * Create a function in the current execution context
2884  * for a given FunctionCallback.
2885  */
2886  static Local<Function> New(Isolate* isolate,
2887  FunctionCallback callback,
2888  Local<Value> data = Local<Value>(),
2889  int length = 0);
2890 
2891  Local<Object> NewInstance() const;
2892  Local<Object> NewInstance(int argc, Handle<Value> argv[]) const;
2893  Local<Value> Call(Handle<Value> recv, int argc, Handle<Value> argv[]);
2894  void SetName(Handle<String> name);
2895  Handle<Value> GetName() const;
2896 
2897  /**
2898  * Name inferred from variable or property assignment of this function.
2899  * Used to facilitate debugging and profiling of JavaScript code written
2900  * in an OO style, where many functions are anonymous but are assigned
2901  * to object properties.
2902  */
2903  Handle<Value> GetInferredName() const;
2904 
2905  /**
2906  * User-defined name assigned to the "displayName" property of this function.
2907  * Used to facilitate debugging and profiling of JavaScript code.
2908  */
2909  Handle<Value> GetDisplayName() const;
2910 
2911  /**
2912  * Returns zero based line number of function body and
2913  * kLineOffsetNotFound if no information available.
2914  */
2915  int GetScriptLineNumber() const;
2916  /**
2917  * Returns zero based column number of function body and
2918  * kLineOffsetNotFound if no information available.
2919  */
2920  int GetScriptColumnNumber() const;
2921 
2922  /**
2923  * Tells whether this function is builtin.
2924  */
2925  bool IsBuiltin() const;
2926 
2927  /**
2928  * Returns scriptId.
2929  */
2930  int ScriptId() const;
2931 
2932  /**
2933  * Returns the original function if this function is bound, else returns
2934  * v8::Undefined.
2935  */
2936  Local<Value> GetBoundFunction() const;
2937 
2938  ScriptOrigin GetScriptOrigin() const;
2939  V8_INLINE static Function* Cast(Value* obj);
2940  static const int kLineOffsetNotFound;
2941 
2942  private:
2943  Function();
2944  static void CheckCast(Value* obj);
2945 };
2946 
2947 
2948 /**
2949  * An instance of the built-in Promise constructor (ES6 draft).
2950  * This API is experimental. Only works with --harmony flag.
2951  */
2952 class V8_EXPORT Promise : public Object {
2953  public:
2954  class V8_EXPORT Resolver : public Object {
2955  public:
2956  /**
2957  * Create a new resolver, along with an associated promise in pending state.
2958  */
2959  static Local<Resolver> New(Isolate* isolate);
2960 
2961  /**
2962  * Extract the associated promise.
2963  */
2964  Local<Promise> GetPromise();
2965 
2966  /**
2967  * Resolve/reject the associated promise with a given value.
2968  * Ignored if the promise is no longer pending.
2969  */
2970  void Resolve(Handle<Value> value);
2971  void Reject(Handle<Value> value);
2972 
2973  V8_INLINE static Resolver* Cast(Value* obj);
2974 
2975  private:
2976  Resolver();
2977  static void CheckCast(Value* obj);
2978  };
2979 
2980  /**
2981  * Register a resolution/rejection handler with a promise.
2982  * The handler is given the respective resolution/rejection value as
2983  * an argument. If the promise is already resolved/rejected, the handler is
2984  * invoked at the end of turn.
2985  */
2986  Local<Promise> Chain(Handle<Function> handler);
2987  Local<Promise> Catch(Handle<Function> handler);
2988  Local<Promise> Then(Handle<Function> handler);
2989 
2990  /**
2991  * Returns true if the promise has at least one derived promise, and
2992  * therefore resolve/reject handlers (including default handler).
2993  */
2994  bool HasHandler();
2995 
2996  V8_INLINE static Promise* Cast(Value* obj);
2997 
2998  private:
2999  Promise();
3000  static void CheckCast(Value* obj);
3001 };
3002 
3003 
3004 #ifndef V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT
3005 // The number of required internal fields can be defined by embedder.
3006 #define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 2
3007 #endif
3008 
3009 /**
3010  * An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5).
3011  * This API is experimental and may change significantly.
3012  */
3013 class V8_EXPORT ArrayBuffer : public Object {
3014  public:
3015  /**
3016  * Allocator that V8 uses to allocate |ArrayBuffer|'s memory.
3017  * The allocator is a global V8 setting. It should be set with
3018  * V8::SetArrayBufferAllocator prior to creation of a first ArrayBuffer.
3019  *
3020  * This API is experimental and may change significantly.
3021  */
3022  class V8_EXPORT Allocator { // NOLINT
3023  public:
3024  virtual ~Allocator() {}
3025 
3026  /**
3027  * Allocate |length| bytes. Return NULL if allocation is not successful.
3028  * Memory should be initialized to zeroes.
3029  */
3030  virtual void* Allocate(size_t length) = 0;
3031 
3032  /**
3033  * Allocate |length| bytes. Return NULL if allocation is not successful.
3034  * Memory does not have to be initialized.
3035  */
3036  virtual void* AllocateUninitialized(size_t length) = 0;
3037  /**
3038  * Free the memory block of size |length|, pointed to by |data|.
3039  * That memory is guaranteed to be previously allocated by |Allocate|.
3040  */
3041  virtual void Free(void* data, size_t length) = 0;
3042  };
3043 
3044  /**
3045  * The contents of an |ArrayBuffer|. Externalization of |ArrayBuffer|
3046  * returns an instance of this class, populated, with a pointer to data
3047  * and byte length.
3048  *
3049  * The Data pointer of ArrayBuffer::Contents is always allocated with
3050  * Allocator::Allocate that is set with V8::SetArrayBufferAllocator.
3051  *
3052  * This API is experimental and may change significantly.
3053  */
3054  class V8_EXPORT Contents { // NOLINT
3055  public:
3056  Contents() : data_(NULL), byte_length_(0) {}
3057 
3058  void* Data() const { return data_; }
3059  size_t ByteLength() const { return byte_length_; }
3060 
3061  private:
3062  void* data_;
3063  size_t byte_length_;
3064 
3065  friend class ArrayBuffer;
3066  };
3067 
3068 
3069  /**
3070  * Data length in bytes.
3071  */
3072  size_t ByteLength() const;
3073 
3074  /**
3075  * Create a new ArrayBuffer. Allocate |byte_length| bytes.
3076  * Allocated memory will be owned by a created ArrayBuffer and
3077  * will be deallocated when it is garbage-collected,
3078  * unless the object is externalized.
3079  */
3080  static Local<ArrayBuffer> New(Isolate* isolate, size_t byte_length);
3081 
3082  /**
3083  * Create a new ArrayBuffer over an existing memory block.
3084  * The created array buffer is immediately in externalized state.
3085  * The memory block will not be reclaimed when a created ArrayBuffer
3086  * is garbage-collected.
3087  */
3088  static Local<ArrayBuffer> New(Isolate* isolate, void* data,
3089  size_t byte_length);
3090 
3091  /**
3092  * Returns true if ArrayBuffer is extrenalized, that is, does not
3093  * own its memory block.
3094  */
3095  bool IsExternal() const;
3096 
3097  /**
3098  * Returns true if this ArrayBuffer may be neutered.
3099  */
3100  bool IsNeuterable() const;
3101 
3102  /**
3103  * Neuters this ArrayBuffer and all its views (typed arrays).
3104  * Neutering sets the byte length of the buffer and all typed arrays to zero,
3105  * preventing JavaScript from ever accessing underlying backing store.
3106  * ArrayBuffer should have been externalized and must be neuterable.
3107  */
3108  void Neuter();
3109 
3110  /**
3111  * Make this ArrayBuffer external. The pointer to underlying memory block
3112  * and byte length are returned as |Contents| structure. After ArrayBuffer
3113  * had been etxrenalized, it does no longer owns the memory block. The caller
3114  * should take steps to free memory when it is no longer needed.
3115  *
3116  * The memory block is guaranteed to be allocated with |Allocator::Allocate|
3117  * that has been set with V8::SetArrayBufferAllocator.
3118  */
3120 
3121  V8_INLINE static ArrayBuffer* Cast(Value* obj);
3122 
3124 
3125  private:
3126  ArrayBuffer();
3127  static void CheckCast(Value* obj);
3128 };
3129 
3130 
3131 #ifndef V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT
3132 // The number of required internal fields can be defined by embedder.
3133 #define V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT 2
3134 #endif
3135 
3136 
3137 /**
3138  * A base class for an instance of one of "views" over ArrayBuffer,
3139  * including TypedArrays and DataView (ES6 draft 15.13).
3140  *
3141  * This API is experimental and may change significantly.
3142  */
3144  public:
3145  /**
3146  * Returns underlying ArrayBuffer.
3147  */
3148  Local<ArrayBuffer> Buffer();
3149  /**
3150  * Byte offset in |Buffer|.
3151  */
3152  size_t ByteOffset();
3153  /**
3154  * Size of a view in bytes.
3155  */
3156  size_t ByteLength();
3157 
3158  V8_INLINE static ArrayBufferView* Cast(Value* obj);
3159 
3160  static const int kInternalFieldCount =
3162 
3163  private:
3164  ArrayBufferView();
3165  static void CheckCast(Value* obj);
3166 };
3167 
3168 
3169 /**
3170  * A base class for an instance of TypedArray series of constructors
3171  * (ES6 draft 15.13.6).
3172  * This API is experimental and may change significantly.
3173  */
3175  public:
3176  /**
3177  * Number of elements in this typed array
3178  * (e.g. for Int16Array, |ByteLength|/2).
3179  */
3180  size_t Length();
3181 
3182  V8_INLINE static TypedArray* Cast(Value* obj);
3183 
3184  private:
3185  TypedArray();
3186  static void CheckCast(Value* obj);
3187 };
3188 
3189 
3190 /**
3191  * An instance of Uint8Array constructor (ES6 draft 15.13.6).
3192  * This API is experimental and may change significantly.
3193  */
3195  public:
3196  static Local<Uint8Array> New(Handle<ArrayBuffer> array_buffer,
3197  size_t byte_offset, size_t length);
3198  V8_INLINE static Uint8Array* Cast(Value* obj);
3199 
3200  private:
3201  Uint8Array();
3202  static void CheckCast(Value* obj);
3203 };
3204 
3205 
3206 /**
3207  * An instance of Uint8ClampedArray constructor (ES6 draft 15.13.6).
3208  * This API is experimental and may change significantly.
3209  */
3211  public:
3212  static Local<Uint8ClampedArray> New(Handle<ArrayBuffer> array_buffer,
3213  size_t byte_offset, size_t length);
3214  V8_INLINE static Uint8ClampedArray* Cast(Value* obj);
3215 
3216  private:
3217  Uint8ClampedArray();
3218  static void CheckCast(Value* obj);
3219 };
3220 
3221 /**
3222  * An instance of Int8Array constructor (ES6 draft 15.13.6).
3223  * This API is experimental and may change significantly.
3224  */
3226  public:
3227  static Local<Int8Array> New(Handle<ArrayBuffer> array_buffer,
3228  size_t byte_offset, size_t length);
3229  V8_INLINE static Int8Array* Cast(Value* obj);
3230 
3231  private:
3232  Int8Array();
3233  static void CheckCast(Value* obj);
3234 };
3235 
3236 
3237 /**
3238  * An instance of Uint16Array constructor (ES6 draft 15.13.6).
3239  * This API is experimental and may change significantly.
3240  */
3242  public:
3243  static Local<Uint16Array> New(Handle<ArrayBuffer> array_buffer,
3244  size_t byte_offset, size_t length);
3245  V8_INLINE static Uint16Array* Cast(Value* obj);
3246 
3247  private:
3248  Uint16Array();
3249  static void CheckCast(Value* obj);
3250 };
3251 
3252 
3253 /**
3254  * An instance of Int16Array constructor (ES6 draft 15.13.6).
3255  * This API is experimental and may change significantly.
3256  */
3258  public:
3259  static Local<Int16Array> New(Handle<ArrayBuffer> array_buffer,
3260  size_t byte_offset, size_t length);
3261  V8_INLINE static Int16Array* Cast(Value* obj);
3262 
3263  private:
3264  Int16Array();
3265  static void CheckCast(Value* obj);
3266 };
3267 
3268 
3269 /**
3270  * An instance of Uint32Array constructor (ES6 draft 15.13.6).
3271  * This API is experimental and may change significantly.
3272  */
3274  public:
3275  static Local<Uint32Array> New(Handle<ArrayBuffer> array_buffer,
3276  size_t byte_offset, size_t length);
3277  V8_INLINE static Uint32Array* Cast(Value* obj);
3278 
3279  private:
3280  Uint32Array();
3281  static void CheckCast(Value* obj);
3282 };
3283 
3284 
3285 /**
3286  * An instance of Int32Array constructor (ES6 draft 15.13.6).
3287  * This API is experimental and may change significantly.
3288  */
3290  public:
3291  static Local<Int32Array> New(Handle<ArrayBuffer> array_buffer,
3292  size_t byte_offset, size_t length);
3293  V8_INLINE static Int32Array* Cast(Value* obj);
3294 
3295  private:
3296  Int32Array();
3297  static void CheckCast(Value* obj);
3298 };
3299 
3300 
3301 /**
3302  * An instance of Float32Array constructor (ES6 draft 15.13.6).
3303  * This API is experimental and may change significantly.
3304  */
3306  public:
3307  static Local<Float32Array> New(Handle<ArrayBuffer> array_buffer,
3308  size_t byte_offset, size_t length);
3309  V8_INLINE static Float32Array* Cast(Value* obj);
3310 
3311  private:
3312  Float32Array();
3313  static void CheckCast(Value* obj);
3314 };
3315 
3316 
3317 /**
3318  * An instance of Float64Array constructor (ES6 draft 15.13.6).
3319  * This API is experimental and may change significantly.
3320  */
3322  public:
3323  static Local<Float64Array> New(Handle<ArrayBuffer> array_buffer,
3324  size_t byte_offset, size_t length);
3325  V8_INLINE static Float64Array* Cast(Value* obj);
3326 
3327  private:
3328  Float64Array();
3329  static void CheckCast(Value* obj);
3330 };
3331 
3332 
3333 /**
3334  * An instance of DataView constructor (ES6 draft 15.13.7).
3335  * This API is experimental and may change significantly.
3336  */
3338  public:
3339  static Local<DataView> New(Handle<ArrayBuffer> array_buffer,
3340  size_t byte_offset, size_t length);
3341  V8_INLINE static DataView* Cast(Value* obj);
3342 
3343  private:
3344  DataView();
3345  static void CheckCast(Value* obj);
3346 };
3347 
3348 
3349 /**
3350  * An instance of the built-in Date constructor (ECMA-262, 15.9).
3351  */
3352 class V8_EXPORT Date : public Object {
3353  public:
3354  static Local<Value> New(Isolate* isolate, double time);
3355 
3356  /**
3357  * A specialization of Value::NumberValue that is more efficient
3358  * because we know the structure of this object.
3359  */
3360  double ValueOf() const;
3361 
3362  V8_INLINE static Date* Cast(v8::Value* obj);
3363 
3364  /**
3365  * Notification that the embedder has changed the time zone,
3366  * daylight savings time, or other date / time configuration
3367  * parameters. V8 keeps a cache of various values used for
3368  * date / time computation. This notification will reset
3369  * those cached values for the current context so that date /
3370  * time configuration changes would be reflected in the Date
3371  * object.
3372  *
3373  * This API should not be called more than needed as it will
3374  * negatively impact the performance of date operations.
3375  */
3376  static void DateTimeConfigurationChangeNotification(Isolate* isolate);
3377 
3378  private:
3379  static void CheckCast(v8::Value* obj);
3380 };
3381 
3382 
3383 /**
3384  * A Number object (ECMA-262, 4.3.21).
3385  */
3387  public:
3388  static Local<Value> New(Isolate* isolate, double value);
3389 
3390  double ValueOf() const;
3391 
3392  V8_INLINE static NumberObject* Cast(v8::Value* obj);
3393 
3394  private:
3395  static void CheckCast(v8::Value* obj);
3396 };
3397 
3398 
3399 /**
3400  * A Boolean object (ECMA-262, 4.3.15).
3401  */
3403  public:
3404  static Local<Value> New(bool value);
3405 
3406  bool ValueOf() const;
3407 
3408  V8_INLINE static BooleanObject* Cast(v8::Value* obj);
3409 
3410  private:
3411  static void CheckCast(v8::Value* obj);
3412 };
3413 
3414 
3415 /**
3416  * A String object (ECMA-262, 4.3.18).
3417  */
3419  public:
3420  static Local<Value> New(Handle<String> value);
3421 
3422  Local<String> ValueOf() const;
3423 
3424  V8_INLINE static StringObject* Cast(v8::Value* obj);
3425 
3426  private:
3427  static void CheckCast(v8::Value* obj);
3428 };
3429 
3430 
3431 /**
3432  * A Symbol object (ECMA-262 edition 6).
3433  *
3434  * This is an experimental feature. Use at your own risk.
3435  */
3437  public:
3438  static Local<Value> New(Isolate* isolate, Handle<Symbol> value);
3439 
3440  Local<Symbol> ValueOf() const;
3441 
3442  V8_INLINE static SymbolObject* Cast(v8::Value* obj);
3443 
3444  private:
3445  static void CheckCast(v8::Value* obj);
3446 };
3447 
3448 
3449 /**
3450  * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
3451  */
3452 class V8_EXPORT RegExp : public Object {
3453  public:
3454  /**
3455  * Regular expression flag bits. They can be or'ed to enable a set
3456  * of flags.
3457  */
3458  enum Flags {
3459  kNone = 0,
3460  kGlobal = 1,
3463  };
3464 
3465  /**
3466  * Creates a regular expression from the given pattern string and
3467  * the flags bit field. May throw a JavaScript exception as
3468  * described in ECMA-262, 15.10.4.1.
3469  *
3470  * For example,
3471  * RegExp::New(v8::String::New("foo"),
3472  * static_cast<RegExp::Flags>(kGlobal | kMultiline))
3473  * is equivalent to evaluating "/foo/gm".
3474  */
3475  static Local<RegExp> New(Handle<String> pattern, Flags flags);
3476 
3477  /**
3478  * Returns the value of the source property: a string representing
3479  * the regular expression.
3480  */
3481  Local<String> GetSource() const;
3482 
3483  /**
3484  * Returns the flags bit field.
3485  */
3486  Flags GetFlags() const;
3487 
3488  V8_INLINE static RegExp* Cast(v8::Value* obj);
3489 
3490  private:
3491  static void CheckCast(v8::Value* obj);
3492 };
3493 
3494 
3495 /**
3496  * A JavaScript value that wraps a C++ void*. This type of value is mainly used
3497  * to associate C++ data structures with JavaScript objects.
3498  */
3499 class V8_EXPORT External : public Value {
3500  public:
3501  static Local<External> New(Isolate* isolate, void* value);
3502  V8_INLINE static External* Cast(Value* obj);
3503  void* Value() const;
3504  private:
3505  static void CheckCast(v8::Value* obj);
3506 };
3507 
3508 
3509 // --- Templates ---
3510 
3511 
3512 /**
3513  * The superclass of object and function templates.
3514  */
3515 class V8_EXPORT Template : public Data {
3516  public:
3517  /** Adds a property to each instance created by this template.*/
3518  void Set(Handle<Name> name, Handle<Data> value,
3519  PropertyAttribute attributes = None);
3520  V8_INLINE void Set(Isolate* isolate, const char* name, Handle<Data> value);
3521 
3522  void SetAccessorProperty(
3523  Local<Name> name,
3524  Local<FunctionTemplate> getter = Local<FunctionTemplate>(),
3525  Local<FunctionTemplate> setter = Local<FunctionTemplate>(),
3526  PropertyAttribute attribute = None,
3527  AccessControl settings = DEFAULT);
3528 
3529  /**
3530  * Whenever the property with the given name is accessed on objects
3531  * created from this Template the getter and setter callbacks
3532  * are called instead of getting and setting the property directly
3533  * on the JavaScript object.
3534  *
3535  * \param name The name of the property for which an accessor is added.
3536  * \param getter The callback to invoke when getting the property.
3537  * \param setter The callback to invoke when setting the property.
3538  * \param data A piece of data that will be passed to the getter and setter
3539  * callbacks whenever they are invoked.
3540  * \param settings Access control settings for the accessor. This is a bit
3541  * field consisting of one of more of
3542  * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
3543  * The default is to not allow cross-context access.
3544  * ALL_CAN_READ means that all cross-context reads are allowed.
3545  * ALL_CAN_WRITE means that all cross-context writes are allowed.
3546  * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
3547  * cross-context access.
3548  * \param attribute The attributes of the property for which an accessor
3549  * is added.
3550  * \param signature The signature describes valid receivers for the accessor
3551  * and is used to perform implicit instance checks against them. If the
3552  * receiver is incompatible (i.e. is not an instance of the constructor as
3553  * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
3554  * thrown and no callback is invoked.
3555  */
3556  void SetNativeDataProperty(Local<String> name,
3557  AccessorGetterCallback getter,
3558  AccessorSetterCallback setter = 0,
3559  // TODO(dcarney): gcc can't handle Local below
3560  Handle<Value> data = Handle<Value>(),
3561  PropertyAttribute attribute = None,
3562  Local<AccessorSignature> signature =
3563  Local<AccessorSignature>(),
3564  AccessControl settings = DEFAULT);
3565  void SetNativeDataProperty(Local<Name> name,
3567  AccessorNameSetterCallback setter = 0,
3568  // TODO(dcarney): gcc can't handle Local below
3569  Handle<Value> data = Handle<Value>(),
3570  PropertyAttribute attribute = None,
3571  Local<AccessorSignature> signature =
3572  Local<AccessorSignature>(),
3573  AccessControl settings = DEFAULT);
3574 
3575  private:
3576  Template();
3577 
3578  friend class ObjectTemplate;
3579  friend class FunctionTemplate;
3580 };
3581 
3582 
3583 /**
3584  * NamedProperty[Getter|Setter] are used as interceptors on object.
3585  * See ObjectTemplate::SetNamedPropertyHandler.
3586  */
3588  Local<String> property,
3589  const PropertyCallbackInfo<Value>& info);
3590 
3591 
3592 /**
3593  * Returns the value if the setter intercepts the request.
3594  * Otherwise, returns an empty handle.
3595  */
3597  Local<String> property,
3598  Local<Value> value,
3599  const PropertyCallbackInfo<Value>& info);
3600 
3601 
3602 /**
3603  * Returns a non-empty handle if the interceptor intercepts the request.
3604  * The result is an integer encoding property attributes (like v8::None,
3605  * v8::DontEnum, etc.)
3606  */
3608  Local<String> property,
3609  const PropertyCallbackInfo<Integer>& info);
3610 
3611 
3612 /**
3613  * Returns a non-empty handle if the deleter intercepts the request.
3614  * The return value is true if the property could be deleted and false
3615  * otherwise.
3616  */
3618  Local<String> property,
3619  const PropertyCallbackInfo<Boolean>& info);
3620 
3621 
3622 /**
3623  * Returns an array containing the names of the properties the named
3624  * property getter intercepts.
3625  */
3627  const PropertyCallbackInfo<Array>& info);
3628 
3629 
3630 // TODO(dcarney): Deprecate and remove previous typedefs, and replace
3631 // GenericNamedPropertyFooCallback with just NamedPropertyFooCallback.
3632 /**
3633  * GenericNamedProperty[Getter|Setter] are used as interceptors on object.
3634  * See ObjectTemplate::SetNamedPropertyHandler.
3635  */
3637  Local<Name> property, const PropertyCallbackInfo<Value>& info);
3638 
3639 
3640 /**
3641  * Returns the value if the setter intercepts the request.
3642  * Otherwise, returns an empty handle.
3643  */
3645  Local<Name> property, Local<Value> value,
3646  const PropertyCallbackInfo<Value>& info);
3647 
3648 
3649 /**
3650  * Returns a non-empty handle if the interceptor intercepts the request.
3651  * The result is an integer encoding property attributes (like v8::None,
3652  * v8::DontEnum, etc.)
3653  */
3655  Local<Name> property, const PropertyCallbackInfo<Integer>& info);
3656 
3657 
3658 /**
3659  * Returns a non-empty handle if the deleter intercepts the request.
3660  * The return value is true if the property could be deleted and false
3661  * otherwise.
3662  */
3664  Local<Name> property, const PropertyCallbackInfo<Boolean>& info);
3665 
3666 
3667 /**
3668  * Returns an array containing the names of the properties the named
3669  * property getter intercepts.
3670  */
3672  const PropertyCallbackInfo<Array>& info);
3673 
3674 
3675 /**
3676  * Returns the value of the property if the getter intercepts the
3677  * request. Otherwise, returns an empty handle.
3678  */
3680  uint32_t index,
3681  const PropertyCallbackInfo<Value>& info);
3682 
3683 
3684 /**
3685  * Returns the value if the setter intercepts the request.
3686  * Otherwise, returns an empty handle.
3687  */
3689  uint32_t index,
3690  Local<Value> value,
3691  const PropertyCallbackInfo<Value>& info);
3692 
3693 
3694 /**
3695  * Returns a non-empty handle if the interceptor intercepts the request.
3696  * The result is an integer encoding property attributes.
3697  */
3699  uint32_t index,
3700  const PropertyCallbackInfo<Integer>& info);
3701 
3702 
3703 /**
3704  * Returns a non-empty handle if the deleter intercepts the request.
3705  * The return value is true if the property could be deleted and false
3706  * otherwise.
3707  */
3709  uint32_t index,
3710  const PropertyCallbackInfo<Boolean>& info);
3711 
3712 
3713 /**
3714  * Returns an array containing the indices of the properties the
3715  * indexed property getter intercepts.
3716  */
3718  const PropertyCallbackInfo<Array>& info);
3719 
3720 
3721 /**
3722  * Access type specification.
3723  */
3730 };
3731 
3732 
3733 /**
3734  * Returns true if cross-context access should be allowed to the named
3735  * property with the given key on the host object.
3736  */
3737 typedef bool (*NamedSecurityCallback)(Local<Object> host,
3738  Local<Value> key,
3739  AccessType type,
3740  Local<Value> data);
3741 
3742 
3743 /**
3744  * Returns true if cross-context access should be allowed to the indexed
3745  * property with the given index on the host object.
3746  */
3747 typedef bool (*IndexedSecurityCallback)(Local<Object> host,
3748  uint32_t index,
3749  AccessType type,
3750  Local<Value> data);
3751 
3752 
3753 /**
3754  * A FunctionTemplate is used to create functions at runtime. There
3755  * can only be one function created from a FunctionTemplate in a
3756  * context. The lifetime of the created function is equal to the
3757  * lifetime of the context. So in case the embedder needs to create
3758  * temporary functions that can be collected using Scripts is
3759  * preferred.
3760  *
3761  * Any modification of a FunctionTemplate after first instantiation will trigger
3762  *a crash.
3763  *
3764  * A FunctionTemplate can have properties, these properties are added to the
3765  * function object when it is created.
3766  *
3767  * A FunctionTemplate has a corresponding instance template which is
3768  * used to create object instances when the function is used as a
3769  * constructor. Properties added to the instance template are added to
3770  * each object instance.
3771  *
3772  * A FunctionTemplate can have a prototype template. The prototype template
3773  * is used to create the prototype object of the function.
3774  *
3775  * The following example shows how to use a FunctionTemplate:
3776  *
3777  * \code
3778  * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
3779  * t->Set("func_property", v8::Number::New(1));
3780  *
3781  * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
3782  * proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
3783  * proto_t->Set("proto_const", v8::Number::New(2));
3784  *
3785  * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
3786  * instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
3787  * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
3788  * instance_t->Set("instance_property", Number::New(3));
3789  *
3790  * v8::Local<v8::Function> function = t->GetFunction();
3791  * v8::Local<v8::Object> instance = function->NewInstance();
3792  * \endcode
3793  *
3794  * Let's use "function" as the JS variable name of the function object
3795  * and "instance" for the instance object created above. The function
3796  * and the instance will have the following properties:
3797  *
3798  * \code
3799  * func_property in function == true;
3800  * function.func_property == 1;
3801  *
3802  * function.prototype.proto_method() invokes 'InvokeCallback'
3803  * function.prototype.proto_const == 2;
3804  *
3805  * instance instanceof function == true;
3806  * instance.instance_accessor calls 'InstanceAccessorCallback'
3807  * instance.instance_property == 3;
3808  * \endcode
3809  *
3810  * A FunctionTemplate can inherit from another one by calling the
3811  * FunctionTemplate::Inherit method. The following graph illustrates
3812  * the semantics of inheritance:
3813  *
3814  * \code
3815  * FunctionTemplate Parent -> Parent() . prototype -> { }
3816  * ^ ^
3817  * | Inherit(Parent) | .__proto__
3818  * | |
3819  * FunctionTemplate Child -> Child() . prototype -> { }
3820  * \endcode
3821  *
3822  * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
3823  * object of the Child() function has __proto__ pointing to the
3824  * Parent() function's prototype object. An instance of the Child
3825  * function has all properties on Parent's instance templates.
3826  *
3827  * Let Parent be the FunctionTemplate initialized in the previous
3828  * section and create a Child FunctionTemplate by:
3829  *
3830  * \code
3831  * Local<FunctionTemplate> parent = t;
3832  * Local<FunctionTemplate> child = FunctionTemplate::New();
3833  * child->Inherit(parent);
3834  *
3835  * Local<Function> child_function = child->GetFunction();
3836  * Local<Object> child_instance = child_function->NewInstance();
3837  * \endcode
3838  *
3839  * The Child function and Child instance will have the following
3840  * properties:
3841  *
3842  * \code
3843  * child_func.prototype.__proto__ == function.prototype;
3844  * child_instance.instance_accessor calls 'InstanceAccessorCallback'
3845  * child_instance.instance_property == 3;
3846  * \endcode
3847  */
3849  public:
3850  /** Creates a function template.*/
3851  static Local<FunctionTemplate> New(
3852  Isolate* isolate,
3853  FunctionCallback callback = 0,
3854  Handle<Value> data = Handle<Value>(),
3855  Handle<Signature> signature = Handle<Signature>(),
3856  int length = 0);
3857 
3858  /** Returns the unique function instance in the current execution context.*/
3859  Local<Function> GetFunction();
3860 
3861  /**
3862  * Set the call-handler callback for a FunctionTemplate. This
3863  * callback is called whenever the function created from this
3864  * FunctionTemplate is called.
3865  */
3866  void SetCallHandler(FunctionCallback callback,
3867  Handle<Value> data = Handle<Value>());
3868 
3869  /** Set the predefined length property for the FunctionTemplate. */
3870  void SetLength(int length);
3871 
3872  /** Get the InstanceTemplate. */
3874 
3875  /** Causes the function template to inherit from a parent function template.*/
3876  void Inherit(Handle<FunctionTemplate> parent);
3877 
3878  /**
3879  * A PrototypeTemplate is the template used to create the prototype object
3880  * of the function created by this template.
3881  */
3883 
3884  /**
3885  * Set the class name of the FunctionTemplate. This is used for
3886  * printing objects created with the function created from the
3887  * FunctionTemplate as its constructor.
3888  */
3889  void SetClassName(Handle<String> name);
3890 
3891  /**
3892  * Determines whether the __proto__ accessor ignores instances of
3893  * the function template. If instances of the function template are
3894  * ignored, __proto__ skips all instances and instead returns the
3895  * next object in the prototype chain.
3896  *
3897  * Call with a value of true to make the __proto__ accessor ignore
3898  * instances of the function template. Call with a value of false
3899  * to make the __proto__ accessor not ignore instances of the
3900  * function template. By default, instances of a function template
3901  * are not ignored.
3902  */
3903  void SetHiddenPrototype(bool value);
3904 
3905  /**
3906  * Sets the ReadOnly flag in the attributes of the 'prototype' property
3907  * of functions created from this FunctionTemplate to true.
3908  */
3909  void ReadOnlyPrototype();
3910 
3911  /**
3912  * Removes the prototype property from functions created from this
3913  * FunctionTemplate.
3914  */
3915  void RemovePrototype();
3916 
3917  /**
3918  * Returns true if the given object is an instance of this function
3919  * template.
3920  */
3921  bool HasInstance(Handle<Value> object);
3922 
3923  private:
3924  FunctionTemplate();
3925  friend class Context;
3926  friend class ObjectTemplate;
3927 };
3928 
3929 
3930 enum class PropertyHandlerFlags { kNone = 0, kAllCanRead = 1 };
3931 
3932 
3935  /** Note: getter is required **/
3941  Handle<Value> data = Handle<Value>(),
3943  : getter(getter),
3944  setter(setter),
3945  query(query),
3946  deleter(deleter),
3947  enumerator(enumerator),
3948  data(data),
3949  flags(flags) {}
3950 
3956  Handle<Value> data;
3958 };
3959 
3960 
3963  /** Note: getter is required **/
3964  IndexedPropertyGetterCallback getter = 0,
3965  IndexedPropertySetterCallback setter = 0,
3966  IndexedPropertyQueryCallback query = 0,
3967  IndexedPropertyDeleterCallback deleter = 0,
3968  IndexedPropertyEnumeratorCallback enumerator = 0,
3969  Handle<Value> data = Handle<Value>(),
3971  : getter(getter),
3972  setter(setter),
3973  query(query),
3974  deleter(deleter),
3975  enumerator(enumerator),
3976  data(data),
3977  flags(flags) {}
3978 
3984  Handle<Value> data;
3986 };
3987 
3988 
3989 /**
3990  * An ObjectTemplate is used to create objects at runtime.
3991  *
3992  * Properties added to an ObjectTemplate are added to each object
3993  * created from the ObjectTemplate.
3994  */
3996  public:
3997  /** Creates an ObjectTemplate. */
3998  static Local<ObjectTemplate> New(Isolate* isolate);
3999  // Will be deprecated soon.
4000  static Local<ObjectTemplate> New();
4001 
4002  /** Creates a new instance of this template.*/
4003  Local<Object> NewInstance();
4004 
4005  /**
4006  * Sets an accessor on the object template.
4007  *
4008  * Whenever the property with the given name is accessed on objects
4009  * created from this ObjectTemplate the getter and setter callbacks
4010  * are called instead of getting and setting the property directly
4011  * on the JavaScript object.
4012  *
4013  * \param name The name of the property for which an accessor is added.
4014  * \param getter The callback to invoke when getting the property.
4015  * \param setter The callback to invoke when setting the property.
4016  * \param data A piece of data that will be passed to the getter and setter
4017  * callbacks whenever they are invoked.
4018  * \param settings Access control settings for the accessor. This is a bit
4019  * field consisting of one of more of
4020  * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
4021  * The default is to not allow cross-context access.
4022  * ALL_CAN_READ means that all cross-context reads are allowed.
4023  * ALL_CAN_WRITE means that all cross-context writes are allowed.
4024  * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
4025  * cross-context access.
4026  * \param attribute The attributes of the property for which an accessor
4027  * is added.
4028  * \param signature The signature describes valid receivers for the accessor
4029  * and is used to perform implicit instance checks against them. If the
4030  * receiver is incompatible (i.e. is not an instance of the constructor as
4031  * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
4032  * thrown and no callback is invoked.
4033  */
4034  void SetAccessor(Handle<String> name,
4035  AccessorGetterCallback getter,
4036  AccessorSetterCallback setter = 0,
4037  Handle<Value> data = Handle<Value>(),
4038  AccessControl settings = DEFAULT,
4039  PropertyAttribute attribute = None,
4040  Handle<AccessorSignature> signature =
4041  Handle<AccessorSignature>());
4042  void SetAccessor(Handle<Name> name,
4044  AccessorNameSetterCallback setter = 0,
4045  Handle<Value> data = Handle<Value>(),
4046  AccessControl settings = DEFAULT,
4047  PropertyAttribute attribute = None,
4048  Handle<AccessorSignature> signature =
4049  Handle<AccessorSignature>());
4050 
4051  /**
4052  * Sets a named property handler on the object template.
4053  *
4054  * Whenever a property whose name is a string is accessed on objects created
4055  * from this object template, the provided callback is invoked instead of
4056  * accessing the property directly on the JavaScript object.
4057  *
4058  * Note that new code should use the second version that can intercept
4059  * symbol-named properties as well as string-named properties.
4060  *
4061  * \param getter The callback to invoke when getting a property.
4062  * \param setter The callback to invoke when setting a property.
4063  * \param query The callback to invoke to check if a property is present,
4064  * and if present, get its attributes.
4065  * \param deleter The callback to invoke when deleting a property.
4066  * \param enumerator The callback to invoke to enumerate all the named
4067  * properties of an object.
4068  * \param data A piece of data that will be passed to the callbacks
4069  * whenever they are invoked.
4070  */
4071  // TODO(dcarney): deprecate
4074  NamedPropertySetterCallback setter = 0,
4075  NamedPropertyQueryCallback query = 0,
4076  NamedPropertyDeleterCallback deleter = 0,
4077  NamedPropertyEnumeratorCallback enumerator = 0,
4078  Handle<Value> data = Handle<Value>());
4079  void SetHandler(const NamedPropertyHandlerConfiguration& configuration);
4080 
4081  /**
4082  * Sets an indexed property handler on the object template.
4083  *
4084  * Whenever an indexed property is accessed on objects created from
4085  * this object template, the provided callback is invoked instead of
4086  * accessing the property directly on the JavaScript object.
4087  *
4088  * \param getter The callback to invoke when getting a property.
4089  * \param setter The callback to invoke when setting a property.
4090  * \param query The callback to invoke to check if an object has a property.
4091  * \param deleter The callback to invoke when deleting a property.
4092  * \param enumerator The callback to invoke to enumerate all the indexed
4093  * properties of an object.
4094  * \param data A piece of data that will be passed to the callbacks
4095  * whenever they are invoked.
4096  */
4097  void SetHandler(const IndexedPropertyHandlerConfiguration& configuration);
4098  // TODO(dcarney): deprecate
4101  IndexedPropertySetterCallback setter = 0,
4102  IndexedPropertyQueryCallback query = 0,
4103  IndexedPropertyDeleterCallback deleter = 0,
4104  IndexedPropertyEnumeratorCallback enumerator = 0,
4105  Handle<Value> data = Handle<Value>()) {
4107  deleter, enumerator, data));
4108  }
4109  /**
4110  * Sets the callback to be used when calling instances created from
4111  * this template as a function. If no callback is set, instances
4112  * behave like normal JavaScript objects that cannot be called as a
4113  * function.
4114  */
4116  Handle<Value> data = Handle<Value>());
4117 
4118  /**
4119  * Mark object instances of the template as undetectable.
4120  *
4121  * In many ways, undetectable objects behave as though they are not
4122  * there. They behave like 'undefined' in conditionals and when
4123  * printed. However, properties can be accessed and called as on
4124  * normal objects.
4125  */
4126  void MarkAsUndetectable();
4127 
4128  /**
4129  * Sets access check callbacks on the object template.
4130  *
4131  * When accessing properties on instances of this object template,
4132  * the access check callback will be called to determine whether or
4133  * not to allow cross-context access to the properties.
4134  * The last parameter specifies whether access checks are turned
4135  * on by default on instances. If access checks are off by default,
4136  * they can be turned on on individual instances by calling
4137  * Object::TurnOnAccessCheck().
4138  */
4140  IndexedSecurityCallback indexed_handler,
4141  Handle<Value> data = Handle<Value>(),
4142  bool turned_on_by_default = true);
4143 
4144  /**
4145  * Gets the number of internal fields for objects generated from
4146  * this template.
4147  */
4148  int InternalFieldCount();
4149 
4150  /**
4151  * Sets the number of internal fields for objects generated from
4152  * this template.
4153  */
4154  void SetInternalFieldCount(int value);
4155 
4156  private:
4157  ObjectTemplate();
4158  static Local<ObjectTemplate> New(internal::Isolate* isolate,
4159  Handle<FunctionTemplate> constructor);
4160  friend class FunctionTemplate;
4161 };
4162 
4163 
4164 /**
4165  * A Signature specifies which receiver is valid for a function.
4166  */
4167 class V8_EXPORT Signature : public Data {
4168  public:
4169  static Local<Signature> New(
4170  Isolate* isolate,
4171  Handle<FunctionTemplate> receiver = Handle<FunctionTemplate>());
4172 
4173  private:
4174  Signature();
4175 };
4176 
4177 
4178 /**
4179  * An AccessorSignature specifies which receivers are valid parameters
4180  * to an accessor callback.
4181  */
4183  public:
4184  static Local<AccessorSignature> New(Isolate* isolate,
4185  Handle<FunctionTemplate> receiver =
4186  Handle<FunctionTemplate>());
4187 
4188  private:
4189  AccessorSignature();
4190 };
4191 
4192 
4193 /**
4194  * A utility for determining the type of objects based on the template
4195  * they were constructed from.
4196  */
4197 class V8_EXPORT TypeSwitch : public Data {
4198  public:
4199  static Local<TypeSwitch> New(Handle<FunctionTemplate> type);
4200  static Local<TypeSwitch> New(int argc, Handle<FunctionTemplate> types[]);
4201  int match(Handle<Value> value);
4202  private:
4203  TypeSwitch();
4204 };
4205 
4206 
4207 // --- Extensions ---
4208 
4211  public:
4213  ExternalOneByteStringResourceImpl(const char* data, size_t length)
4214  : data_(data), length_(length) {}
4215  const char* data() const { return data_; }
4216  size_t length() const { return length_; }
4217 
4218  private:
4219  const char* data_;
4220  size_t length_;
4221 };
4222 
4223 /**
4224  * Ignore
4225  */
4226 class V8_EXPORT Extension { // NOLINT
4227  public:
4228  // Note that the strings passed into this constructor must live as long
4229  // as the Extension itself.
4230  Extension(const char* name,
4231  const char* source = 0,
4232  int dep_count = 0,
4233  const char** deps = 0,
4234  int source_length = -1);
4235  virtual ~Extension() { }
4237  v8::Isolate* isolate, v8::Handle<v8::String> name) {
4238  return v8::Handle<v8::FunctionTemplate>();
4239  }
4240 
4241  const char* name() const { return name_; }
4242  size_t source_length() const { return source_length_; }
4244  return &source_; }
4245  int dependency_count() { return dep_count_; }
4246  const char** dependencies() { return deps_; }
4247  void set_auto_enable(bool value) { auto_enable_ = value; }
4248  bool auto_enable() { return auto_enable_; }
4249 
4250  private:
4251  const char* name_;
4252  size_t source_length_; // expected to initialize before source_
4254  int dep_count_;
4255  const char** deps_;
4256  bool auto_enable_;
4257 
4258  // Disallow copying and assigning.
4259  Extension(const Extension&);
4260  void operator=(const Extension&);
4261 };
4262 
4263 
4264 void V8_EXPORT RegisterExtension(Extension* extension);
4265 
4266 
4267 // --- Statics ---
4268 
4269 V8_INLINE Handle<Primitive> Undefined(Isolate* isolate);
4270 V8_INLINE Handle<Primitive> Null(Isolate* isolate);
4271 V8_INLINE Handle<Boolean> True(Isolate* isolate);
4272 V8_INLINE Handle<Boolean> False(Isolate* isolate);
4273 
4274 
4275 /**
4276  * A set of constraints that specifies the limits of the runtime's memory use.
4277  * You must set the heap size before initializing the VM - the size cannot be
4278  * adjusted after the VM is initialized.
4279  *
4280  * If you are using threads then you should hold the V8::Locker lock while
4281  * setting the stack limit and you must set a non-default stack limit separately
4282  * for each thread.
4283  */
4285  public:
4287 
4288  /**
4289  * Configures the constraints with reasonable default values based on the
4290  * capabilities of the current device the VM is running on.
4291  *
4292  * \param physical_memory The total amount of physical memory on the current
4293  * device, in bytes.
4294  * \param virtual_memory_limit The amount of virtual memory on the current
4295  * device, in bytes, or zero, if there is no limit.
4296  * \param number_of_processors The number of CPUs available on the current
4297  * device.
4298  */
4299  void ConfigureDefaults(uint64_t physical_memory,
4300  uint64_t virtual_memory_limit,
4301  uint32_t number_of_processors);
4302 
4303  int max_semi_space_size() const { return max_semi_space_size_; }
4304  void set_max_semi_space_size(int value) { max_semi_space_size_ = value; }
4305  int max_old_space_size() const { return max_old_space_size_; }
4306  void set_max_old_space_size(int value) { max_old_space_size_ = value; }
4307  int max_executable_size() const { return max_executable_size_; }
4308  void set_max_executable_size(int value) { max_executable_size_ = value; }
4309  uint32_t* stack_limit() const { return stack_limit_; }
4310  // Sets an address beyond which the VM's stack may not grow.
4311  void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
4312  int max_available_threads() const { return max_available_threads_; }
4313  // Set the number of threads available to V8, assuming at least 1.
4314  void set_max_available_threads(int value) {
4315  max_available_threads_ = value;
4316  }
4317  size_t code_range_size() const { return code_range_size_; }
4318  void set_code_range_size(size_t value) {
4319  code_range_size_ = value;
4320  }
4321 
4322  private:
4323  int max_semi_space_size_;
4324  int max_old_space_size_;
4325  int max_executable_size_;
4326  uint32_t* stack_limit_;
4327  int max_available_threads_;
4328  size_t code_range_size_;
4329 };
4330 
4331 
4332 // --- Exceptions ---
4333 
4334 
4335 typedef void (*FatalErrorCallback)(const char* location, const char* message);
4336 
4337 
4338 typedef void (*MessageCallback)(Handle<Message> message, Handle<Value> error);
4339 
4340 // --- Tracing ---
4341 
4342 typedef void (*LogEventCallback)(const char* name, int event);
4343 
4344 /**
4345  * Create new error objects by calling the corresponding error object
4346  * constructor with the message.
4347  */
4349  public:
4350  static Local<Value> RangeError(Handle<String> message);
4351  static Local<Value> ReferenceError(Handle<String> message);
4352  static Local<Value> SyntaxError(Handle<String> message);
4353  static Local<Value> TypeError(Handle<String> message);
4354  static Local<Value> Error(Handle<String> message);
4355 
4356  /**
4357  * Creates an error message for the given exception.
4358  * Will try to reconstruct the original stack trace from the exception value,
4359  * or capture the current stack trace if not available.
4360  */
4361  static Local<Message> CreateMessage(Handle<Value> exception);
4362 
4363  /**
4364  * Returns the original stack trace that was captured at the creation time
4365  * of a given exception, or an empty handle if not available.
4366  */
4367  static Local<StackTrace> GetStackTrace(Handle<Value> exception);
4368 };
4369 
4370 
4371 // --- Counters Callbacks ---
4372 
4373 typedef int* (*CounterLookupCallback)(const char* name);
4374 
4375 typedef void* (*CreateHistogramCallback)(const char* name,
4376  int min,
4377  int max,
4378  size_t buckets);
4379 
4380 typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
4381 
4382 // --- Memory Allocation Callback ---
4395 };
4396 
4401  };
4402 
4404  AllocationAction action,
4405  int size);
4406 
4407 // --- Leave Script Callback ---
4408 typedef void (*CallCompletedCallback)();
4409 
4410 // --- Promise Reject Callback ---
4414 };
4415 
4417  public:
4419  Handle<Value> value, Handle<StackTrace> stack_trace)
4420  : promise_(promise),
4421  event_(event),
4422  value_(value),
4423  stack_trace_(stack_trace) {}
4424 
4425  V8_INLINE Handle<Promise> GetPromise() const { return promise_; }
4426  V8_INLINE PromiseRejectEvent GetEvent() const { return event_; }
4427  V8_INLINE Handle<Value> GetValue() const { return value_; }
4428 
4429  // DEPRECATED. Use v8::Exception::CreateMessage(GetValue())->GetStackTrace()
4430  V8_INLINE Handle<StackTrace> GetStackTrace() const { return stack_trace_; }
4431 
4432  private:
4433  Handle<Promise> promise_;
4434  PromiseRejectEvent event_;
4435  Handle<Value> value_;
4436  Handle<StackTrace> stack_trace_;
4437 };
4438 
4440 
4441 // --- Microtask Callback ---
4442 typedef void (*MicrotaskCallback)(void* data);
4443 
4444 // --- Failed Access Check Callback ---
4445 typedef void (*FailedAccessCheckCallback)(Local<Object> target,
4446  AccessType type,
4447  Local<Value> data);
4448 
4449 // --- AllowCodeGenerationFromStrings callbacks ---
4450 
4451 /**
4452  * Callback to check if code generation from strings is allowed. See
4453  * Context::AllowCodeGenerationFromStrings.
4454  */
4455 typedef bool (*AllowCodeGenerationFromStringsCallback)(Local<Context> context);
4456 
4457 // --- Garbage Collection Callbacks ---
4458 
4459 /**
4460  * Applications can register callback functions which will be called
4461  * before and after a garbage collection. Allocations are not
4462  * allowed in the callback functions, you therefore cannot manipulate
4463  * objects (set or delete properties for example) since it is possible
4464  * such operations will result in the allocation of objects.
4465  */
4466 enum GCType {
4470 };
4471 
4477 };
4478 
4479 typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
4480 typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
4481 
4482 typedef void (*InterruptCallback)(Isolate* isolate, void* data);
4483 
4484 
4485 /**
4486  * Collection of V8 heap information.
4487  *
4488  * Instances of this class can be passed to v8::V8::HeapStatistics to
4489  * get heap statistics from V8.
4490  */
4492  public:
4493  HeapStatistics();
4494  size_t total_heap_size() { return total_heap_size_; }
4495  size_t total_heap_size_executable() { return total_heap_size_executable_; }
4496  size_t total_physical_size() { return total_physical_size_; }
4497  size_t used_heap_size() { return used_heap_size_; }
4498  size_t heap_size_limit() { return heap_size_limit_; }
4499 
4500  private:
4501  size_t total_heap_size_;
4502  size_t total_heap_size_executable_;
4503  size_t total_physical_size_;
4504  size_t used_heap_size_;
4505  size_t heap_size_limit_;
4506 
4507  friend class V8;
4508  friend class Isolate;
4509 };
4510 
4511 
4512 class RetainedObjectInfo;
4513 
4514 
4515 /**
4516  * FunctionEntryHook is the type of the profile entry hook called at entry to
4517  * any generated function when function-level profiling is enabled.
4518  *
4519  * \param function the address of the function that's being entered.
4520  * \param return_addr_location points to a location on stack where the machine
4521  * return address resides. This can be used to identify the caller of
4522  * \p function, and/or modified to divert execution when \p function exits.
4523  *
4524  * \note the entry hook must not cause garbage collection.
4525  */
4526 typedef void (*FunctionEntryHook)(uintptr_t function,
4527  uintptr_t return_addr_location);
4528 
4529 /**
4530  * A JIT code event is issued each time code is added, moved or removed.
4531  *
4532  * \note removal events are not currently issued.
4533  */
4535  enum EventType {
4542  };
4543  // Definition of the code position type. The "POSITION" type means the place
4544  // in the source code which are of interest when making stack traces to
4545  // pin-point the source location of a stack frame as close as possible.
4546  // The "STATEMENT_POSITION" means the place at the beginning of each
4547  // statement, and is used to indicate possible break locations.
4549 
4550  // Type of event.
4552  // Start of the instructions.
4553  void* code_start;
4554  // Size of the instructions.
4556  // Script info for CODE_ADDED event.
4558  // User-defined data for *_LINE_INFO_* event. It's used to hold the source
4559  // code line information which is returned from the
4560  // CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent
4561  // CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events.
4562  void* user_data;
4563 
4564  struct name_t {
4565  // Name of the object associated with the code, note that the string is not
4566  // zero-terminated.
4567  const char* str;
4568  // Number of chars in str.
4570  };
4571 
4572  struct line_info_t {
4573  // PC offset
4575  // Code postion
4577  // The position type.
4579  };
4580 
4581  union {
4582  // Only valid for CODE_ADDED.
4583  struct name_t name;
4584 
4585  // Only valid for CODE_ADD_LINE_POS_INFO
4586  struct line_info_t line_info;
4587 
4588  // New location of instructions. Only valid for CODE_MOVED.
4589  void* new_code_start;
4590  };
4591 };
4592 
4593 /**
4594  * Option flags passed to the SetJitCodeEventHandler function.
4595  */
4598  // Generate callbacks for already existent code.
4600 };
4601 
4602 
4603 /**
4604  * Callback function passed to SetJitCodeEventHandler.
4605  *
4606  * \param event code add, move or removal event.
4607  */
4608 typedef void (*JitCodeEventHandler)(const JitCodeEvent* event);
4609 
4610 
4611 /**
4612  * Interface for iterating through all external resources in the heap.
4613  */
4615  public:
4617  virtual void VisitExternalString(Handle<String> string) {}
4618 };
4619 
4620 
4621 /**
4622  * Interface for iterating through all the persistent handles in the heap.
4623  */
4625  public:
4627  virtual void VisitPersistentHandle(Persistent<Value>* value,
4628  uint16_t class_id) {}
4629 };
4630 
4631 
4632 /**
4633  * Isolate represents an isolated instance of the V8 engine. V8 isolates have
4634  * completely separate states. Objects from one isolate must not be used in
4635  * other isolates. The embedder can create multiple isolates and use them in
4636  * parallel in multiple threads. An isolate can be entered by at most one
4637  * thread at any given time. The Locker/Unlocker API must be used to
4638  * synchronize.
4639  */
4641  public:
4642  /**
4643  * Initial configuration parameters for a new Isolate.
4644  */
4645  struct CreateParams {
4647  : entry_hook(NULL),
4648  code_event_handler(NULL),
4649  enable_serializer(false) {}
4650 
4651  /**
4652  * The optional entry_hook allows the host application to provide the
4653  * address of a function that's invoked on entry to every V8-generated
4654  * function. Note that entry_hook is invoked at the very start of each
4655  * generated function. Furthermore, if an entry_hook is given, V8 will
4656  * always run without a context snapshot.
4657  */
4659 
4660  /**
4661  * Allows the host application to provide the address of a function that is
4662  * notified each time code is added, moved or removed.
4663  */
4665 
4666  /**
4667  * ResourceConstraints to use for the new Isolate.
4668  */
4670 
4671  /**
4672  * This flag currently renders the Isolate unusable.
4673  */
4675  };
4676 
4677 
4678  /**
4679  * Stack-allocated class which sets the isolate for all operations
4680  * executed within a local scope.
4681  */
4683  public:
4684  explicit Scope(Isolate* isolate) : isolate_(isolate) {
4685  isolate->Enter();
4686  }
4687 
4688  ~Scope() { isolate_->Exit(); }
4689 
4690  private:
4691  Isolate* const isolate_;
4692 
4693  // Prevent copying of Scope objects.
4694  Scope(const Scope&);
4695  Scope& operator=(const Scope&);
4696  };
4697 
4698 
4699  /**
4700  * Assert that no Javascript code is invoked.
4701  */
4703  public:
4705 
4706  DisallowJavascriptExecutionScope(Isolate* isolate, OnFailure on_failure);
4708 
4709  private:
4710  bool on_failure_;
4711  void* internal_;
4712 
4713  // Prevent copying of Scope objects.
4714  DisallowJavascriptExecutionScope(const DisallowJavascriptExecutionScope&);
4717  };
4718 
4719 
4720  /**
4721  * Introduce exception to DisallowJavascriptExecutionScope.
4722  */
4724  public:
4725  explicit AllowJavascriptExecutionScope(Isolate* isolate);
4727 
4728  private:
4729  void* internal_throws_;
4730  void* internal_assert_;
4731 
4732  // Prevent copying of Scope objects.
4733  AllowJavascriptExecutionScope(const AllowJavascriptExecutionScope&);
4734  AllowJavascriptExecutionScope& operator=(
4736  };
4737 
4738  /**
4739  * Do not run microtasks while this scope is active, even if microtasks are
4740  * automatically executed otherwise.
4741  */
4743  public:
4744  explicit SuppressMicrotaskExecutionScope(Isolate* isolate);
4746 
4747  private:
4748  internal::Isolate* isolate_;
4749 
4750  // Prevent copying of Scope objects.
4751  SuppressMicrotaskExecutionScope(const SuppressMicrotaskExecutionScope&);
4754  };
4755 
4756  /**
4757  * Types of garbage collections that can be requested via
4758  * RequestGarbageCollectionForTesting.
4759  */
4763  };
4764 
4765  /**
4766  * Features reported via the SetUseCounterCallback callback. Do not chang
4767  * assigned numbers of existing items; add new features to the end of this
4768  * list.
4769  */
4771  kUseAsm = 0,
4773  kUseCounterFeatureCount // This enum value must be last.
4774  };
4775 
4776  typedef void (*UseCounterCallback)(Isolate* isolate,
4777  UseCounterFeature feature);
4778 
4779 
4780  /**
4781  * Creates a new isolate. Does not change the currently entered
4782  * isolate.
4783  *
4784  * When an isolate is no longer used its resources should be freed
4785  * by calling Dispose(). Using the delete operator is not allowed.
4786  *
4787  * V8::Initialize() must have run prior to this.
4788  */
4789  static Isolate* New(const CreateParams& params = CreateParams());
4790 
4791  /**
4792  * Returns the entered isolate for the current thread or NULL in
4793  * case there is no current isolate.
4794  *
4795  * This method must not be invoked before V8::Initialize() was invoked.
4796  */
4797  static Isolate* GetCurrent();
4798 
4799  /**
4800  * Methods below this point require holding a lock (using Locker) in
4801  * a multi-threaded environment.
4802  */
4803 
4804  /**
4805  * Sets this isolate as the entered one for the current thread.
4806  * Saves the previously entered one (if any), so that it can be
4807  * restored when exiting. Re-entering an isolate is allowed.
4808  */
4809  void Enter();
4810 
4811  /**
4812  * Exits this isolate by restoring the previously entered one in the
4813  * current thread. The isolate may still stay the same, if it was
4814  * entered more than once.
4815  *
4816  * Requires: this == Isolate::GetCurrent().
4817  */
4818  void Exit();
4819 
4820  /**
4821  * Disposes the isolate. The isolate must not be entered by any
4822  * thread to be disposable.
4823  */
4824  void Dispose();
4825 
4826  /**
4827  * Associate embedder-specific data with the isolate. |slot| has to be
4828  * between 0 and GetNumberOfDataSlots() - 1.
4829  */
4830  V8_INLINE void SetData(uint32_t slot, void* data);
4831 
4832  /**
4833  * Retrieve embedder-specific data from the isolate.
4834  * Returns NULL if SetData has never been called for the given |slot|.
4835  */
4836  V8_INLINE void* GetData(uint32_t slot);
4837 
4838  /**
4839  * Returns the maximum number of available embedder data slots. Valid slots
4840  * are in the range of 0 - GetNumberOfDataSlots() - 1.
4841  */
4842  V8_INLINE static uint32_t GetNumberOfDataSlots();
4843 
4844  /**
4845  * Get statistics about the heap memory usage.
4846  */
4847  void GetHeapStatistics(HeapStatistics* heap_statistics);
4848 
4849  /**
4850  * Get a call stack sample from the isolate.
4851  * \param state Execution state.
4852  * \param frames Caller allocated buffer to store stack frames.
4853  * \param frames_limit Maximum number of frames to capture. The buffer must
4854  * be large enough to hold the number of frames.
4855  * \param sample_info The sample info is filled up by the function
4856  * provides number of actual captured stack frames and
4857  * the current VM state.
4858  * \note GetStackSample should only be called when the JS thread is paused or
4859  * interrupted. Otherwise the behavior is undefined.
4860  */
4861  void GetStackSample(const RegisterState& state, void** frames,
4862  size_t frames_limit, SampleInfo* sample_info);
4863 
4864  /**
4865  * Adjusts the amount of registered external memory. Used to give V8 an
4866  * indication of the amount of externally allocated memory that is kept alive
4867  * by JavaScript objects. V8 uses this to decide when to perform global
4868  * garbage collections. Registering externally allocated memory will trigger
4869  * global garbage collections more often than it would otherwise in an attempt
4870  * to garbage collect the JavaScript objects that keep the externally
4871  * allocated memory alive.
4872  *
4873  * \param change_in_bytes the change in externally allocated memory that is
4874  * kept alive by JavaScript objects.
4875  * \returns the adjusted value.
4876  */
4877  V8_INLINE int64_t
4878  AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes);
4879 
4880  /**
4881  * Returns heap profiler for this isolate. Will return NULL until the isolate
4882  * is initialized.
4883  */
4885 
4886  /**
4887  * Returns CPU profiler for this isolate. Will return NULL unless the isolate
4888  * is initialized. It is the embedder's responsibility to stop all CPU
4889  * profiling activities if it has started any.
4890  */
4892 
4893  /** Returns true if this isolate has a current context. */
4894  bool InContext();
4895 
4896  /** Returns the context that is on the top of the stack. */
4897  Local<Context> GetCurrentContext();
4898 
4899  /**
4900  * Returns the context of the calling JavaScript code. That is the
4901  * context of the top-most JavaScript frame. If there are no
4902  * JavaScript frames an empty handle is returned.
4903  */
4904  Local<Context> GetCallingContext();
4905 
4906  /** Returns the last entered context. */
4907  Local<Context> GetEnteredContext();
4908 
4909  /**
4910  * Schedules an exception to be thrown when returning to JavaScript. When an
4911  * exception has been scheduled it is illegal to invoke any JavaScript
4912  * operation; the caller must return immediately and only after the exception
4913  * has been handled does it become legal to invoke JavaScript operations.
4914  */
4915  Local<Value> ThrowException(Local<Value> exception);
4916 
4917  /**
4918  * Allows the host application to group objects together. If one
4919  * object in the group is alive, all objects in the group are alive.
4920  * After each garbage collection, object groups are removed. It is
4921  * intended to be used in the before-garbage-collection callback
4922  * function, for instance to simulate DOM tree connections among JS
4923  * wrapper objects. Object groups for all dependent handles need to
4924  * be provided for kGCTypeMarkSweepCompact collections, for all other
4925  * garbage collection types it is sufficient to provide object groups
4926  * for partially dependent handles only.
4927  */
4928  template<typename T> void SetObjectGroupId(const Persistent<T>& object,
4929  UniqueId id);
4930 
4931  /**
4932  * Allows the host application to declare implicit references from an object
4933  * group to an object. If the objects of the object group are alive, the child
4934  * object is alive too. After each garbage collection, all implicit references
4935  * are removed. It is intended to be used in the before-garbage-collection
4936  * callback function.
4937  */
4938  template<typename T> void SetReferenceFromGroup(UniqueId id,
4939  const Persistent<T>& child);
4940 
4941  /**
4942  * Allows the host application to declare implicit references from an object
4943  * to another object. If the parent object is alive, the child object is alive
4944  * too. After each garbage collection, all implicit references are removed. It
4945  * is intended to be used in the before-garbage-collection callback function.
4946  */
4947  template<typename T, typename S>
4948  void SetReference(const Persistent<T>& parent, const Persistent<S>& child);
4949 
4950  typedef void (*GCPrologueCallback)(Isolate* isolate,
4951  GCType type,
4952  GCCallbackFlags flags);
4953  typedef void (*GCEpilogueCallback)(Isolate* isolate,
4954  GCType type,
4955  GCCallbackFlags flags);
4956 
4957  /**
4958  * Enables the host application to receive a notification before a
4959  * garbage collection. Allocations are allowed in the callback function,
4960  * but the callback is not re-entrant: if the allocation inside it will
4961  * trigger the garbage collection, the callback won't be called again.
4962  * It is possible to specify the GCType filter for your callback. But it is
4963  * not possible to register the same callback function two times with
4964  * different GCType filters.
4965  */
4966  void AddGCPrologueCallback(
4967  GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
4968 
4969  /**
4970  * This function removes callback which was installed by
4971  * AddGCPrologueCallback function.
4972  */
4974 
4975  /**
4976  * Enables the host application to receive a notification after a
4977  * garbage collection. Allocations are allowed in the callback function,
4978  * but the callback is not re-entrant: if the allocation inside it will
4979  * trigger the garbage collection, the callback won't be called again.
4980  * It is possible to specify the GCType filter for your callback. But it is
4981  * not possible to register the same callback function two times with
4982  * different GCType filters.
4983  */
4984  void AddGCEpilogueCallback(
4985  GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
4986 
4987  /**
4988  * This function removes callback which was installed by
4989  * AddGCEpilogueCallback function.
4990  */
4992 
4993 
4994  /**
4995  * Forcefully terminate the current thread of JavaScript execution
4996  * in the given isolate.
4997  *
4998  * This method can be used by any thread even if that thread has not
4999  * acquired the V8 lock with a Locker object.
5000  */
5001  void TerminateExecution();
5002 
5003  /**
5004  * Is V8 terminating JavaScript execution.
5005  *
5006  * Returns true if JavaScript execution is currently terminating
5007  * because of a call to TerminateExecution. In that case there are
5008  * still JavaScript frames on the stack and the termination
5009  * exception is still active.
5010  */
5011  bool IsExecutionTerminating();
5012 
5013  /**
5014  * Resume execution capability in the given isolate, whose execution
5015  * was previously forcefully terminated using TerminateExecution().
5016  *
5017  * When execution is forcefully terminated using TerminateExecution(),
5018  * the isolate can not resume execution until all JavaScript frames
5019  * have propagated the uncatchable exception which is generated. This
5020  * method allows the program embedding the engine to handle the
5021  * termination event and resume execution capability, even if
5022  * JavaScript frames remain on the stack.
5023  *
5024  * This method can be used by any thread even if that thread has not
5025  * acquired the V8 lock with a Locker object.
5026  */
5027  void CancelTerminateExecution();
5028 
5029  /**
5030  * Request V8 to interrupt long running JavaScript code and invoke
5031  * the given |callback| passing the given |data| to it. After |callback|
5032  * returns control will be returned to the JavaScript code.
5033  * There may be a number of interrupt requests in flight.
5034  * Can be called from another thread without acquiring a |Locker|.
5035  * Registered |callback| must not reenter interrupted Isolate.
5036  */
5037  void RequestInterrupt(InterruptCallback callback, void* data);
5038 
5039  /**
5040  * Clear interrupt request created by |RequestInterrupt|.
5041  * Can be called from another thread without acquiring a |Locker|.
5042  */
5043  V8_DEPRECATED("There's no way to clear interrupts in flight.",
5044  void ClearInterrupt());
5045 
5046  /**
5047  * Request garbage collection in this Isolate. It is only valid to call this
5048  * function if --expose_gc was specified.
5049  *
5050  * This should only be used for testing purposes and not to enforce a garbage
5051  * collection schedule. It has strong negative impact on the garbage
5052  * collection performance. Use IdleNotification() or LowMemoryNotification()
5053  * instead to influence the garbage collection schedule.
5054  */
5056 
5057  /**
5058  * Set the callback to invoke for logging event.
5059  */
5060  void SetEventLogger(LogEventCallback that);
5061 
5062  /**
5063  * Adds a callback to notify the host application when a script finished
5064  * running. If a script re-enters the runtime during executing, the
5065  * CallCompletedCallback is only invoked when the outer-most script
5066  * execution ends. Executing scripts inside the callback do not trigger
5067  * further callbacks.
5068  */
5070 
5071  /**
5072  * Removes callback that was installed by AddCallCompletedCallback.
5073  */
5075 
5076 
5077  /**
5078  * Set callback to notify about promise reject with no handler, or
5079  * revocation of such a previous notification once the handler is added.
5080  */
5082 
5083  /**
5084  * Experimental: Runs the Microtask Work Queue until empty
5085  * Any exceptions thrown by microtask callbacks are swallowed.
5086  */
5087  void RunMicrotasks();
5088 
5089  /**
5090  * Experimental: Enqueues the callback to the Microtask Work Queue
5091  */
5092  void EnqueueMicrotask(Handle<Function> microtask);
5093 
5094  /**
5095  * Experimental: Enqueues the callback to the Microtask Work Queue
5096  */
5097  void EnqueueMicrotask(MicrotaskCallback microtask, void* data = NULL);
5098 
5099  /**
5100  * Experimental: Controls whether the Microtask Work Queue is automatically
5101  * run when the script call depth decrements to zero.
5102  */
5103  void SetAutorunMicrotasks(bool autorun);
5104 
5105  /**
5106  * Experimental: Returns whether the Microtask Work Queue is automatically
5107  * run when the script call depth decrements to zero.
5108  */
5109  bool WillAutorunMicrotasks() const;
5110 
5111  /**
5112  * Sets a callback for counting the number of times a feature of V8 is used.
5113  */
5115 
5116  /**
5117  * Enables the host application to provide a mechanism for recording
5118  * statistics counters.
5119  */
5121 
5122  /**
5123  * Enables the host application to provide a mechanism for recording
5124  * histograms. The CreateHistogram function returns a
5125  * histogram which will later be passed to the AddHistogramSample
5126  * function.
5127  */
5130 
5131  /**
5132  * Optional notification that the embedder is idle.
5133  * V8 uses the notification to perform garbage collection.
5134  * This call can be used repeatedly if the embedder remains idle.
5135  * Returns true if the embedder should stop calling IdleNotification
5136  * until real work has been done. This indicates that V8 has done
5137  * as much cleanup as it will be able to do.
5138  *
5139  * The idle_time_in_ms argument specifies the time V8 has to perform
5140  * garbage collection. There is no guarantee that the actual work will be
5141  * done within the time limit.
5142  * The deadline_in_seconds argument specifies the deadline V8 has to finish
5143  * garbage collection work. deadline_in_seconds is compared with
5144  * MonotonicallyIncreasingTime() and should be based on the same timebase as
5145  * that function. There is no guarantee that the actual work will be done
5146  * within the time limit.
5147  */
5148  bool IdleNotification(int idle_time_in_ms);
5149  bool IdleNotificationDeadline(double deadline_in_seconds);
5150 
5151  /**
5152  * Optional notification that the system is running low on memory.
5153  * V8 uses these notifications to attempt to free memory.
5154  */
5155  void LowMemoryNotification();
5156 
5157  /**
5158  * Optional notification that a context has been disposed. V8 uses
5159  * these notifications to guide the GC heuristic. Returns the number
5160  * of context disposals - including this one - since the last time
5161  * V8 had a chance to clean up.
5162  *
5163  * The optional parameter |dependant_context| specifies whether the disposed
5164  * context was depending on state from other contexts or not.
5165  */
5166  int ContextDisposedNotification(bool dependant_context = true);
5167 
5168  /**
5169  * Allows the host application to provide the address of a function that is
5170  * notified each time code is added, moved or removed.
5171  *
5172  * \param options options for the JIT code event handler.
5173  * \param event_handler the JIT code event handler, which will be invoked
5174  * each time code is added, moved or removed.
5175  * \note \p event_handler won't get notified of existent code.
5176  * \note since code removal notifications are not currently issued, the
5177  * \p event_handler may get notifications of code that overlaps earlier
5178  * code notifications. This happens when code areas are reused, and the
5179  * earlier overlapping code areas should therefore be discarded.
5180  * \note the events passed to \p event_handler and the strings they point to
5181  * are not guaranteed to live past each call. The \p event_handler must
5182  * copy strings and other parameters it needs to keep around.
5183  * \note the set of events declared in JitCodeEvent::EventType is expected to
5184  * grow over time, and the JitCodeEvent structure is expected to accrue
5185  * new members. The \p event_handler function must ignore event codes
5186  * it does not recognize to maintain future compatibility.
5187  * \note Use Isolate::CreateParams to get events for code executed during
5188  * Isolate setup.
5189  */
5191  JitCodeEventHandler event_handler);
5192 
5193  /**
5194  * Modifies the stack limit for this Isolate.
5195  *
5196  * \param stack_limit An address beyond which the Vm's stack may not grow.
5197  *
5198  * \note If you are using threads then you should hold the V8::Locker lock
5199  * while setting the stack limit and you must set a non-default stack
5200  * limit separately for each thread.
5201  */
5202  void SetStackLimit(uintptr_t stack_limit);
5203 
5204  /**
5205  * Returns a memory range that can potentially contain jitted code.
5206  *
5207  * On Win64, embedders are advised to install function table callbacks for
5208  * these ranges, as default SEH won't be able to unwind through jitted code.
5209  *
5210  * The first page of the code range is reserved for the embedder and is
5211  * committed, writable, and executable.
5212  *
5213  * Might be empty on other platforms.
5214  *
5215  * https://code.google.com/p/v8/issues/detail?id=3598
5216  */
5217  void GetCodeRange(void** start, size_t* length_in_bytes);
5218 
5219  /** Set the callback to invoke in case of fatal errors. */
5221 
5222  /**
5223  * Set the callback to invoke to check if code generation from
5224  * strings should be allowed.
5225  */
5228 
5229  /**
5230  * Check if V8 is dead and therefore unusable. This is the case after
5231  * fatal errors such as out-of-memory situations.
5232  */
5233  bool IsDead();
5234 
5235  /**
5236  * Adds a message listener.
5237  *
5238  * The same message listener can be added more than once and in that
5239  * case it will be called more than once for each message.
5240  *
5241  * If data is specified, it will be passed to the callback when it is called.
5242  * Otherwise, the exception object will be passed to the callback instead.
5243  */
5245  Handle<Value> data = Handle<Value>());
5246 
5247  /**
5248  * Remove all message listeners from the specified callback function.
5249  */
5251 
5252  /** Callback function for reporting failed access checks.*/
5254 
5255  /**
5256  * Tells V8 to capture current stack trace when uncaught exception occurs
5257  * and report it to the message listeners. The option is off by default.
5258  */
5260  bool capture, int frame_limit = 10,
5262 
5263  /**
5264