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