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