• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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;
71 class DeclaredAccessorDescriptor;
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 Name;
81 class Number;
82 class NumberObject;
83 class Object;
84 class ObjectOperationDescriptor;
85 class ObjectTemplate;
86 class Platform;
87 class Primitive;
88 class RawOperationDescriptor;
89 class Script;
90 class Signature;
91 class StackFrame;
92 class StackTrace;
93 class String;
94 class StringObject;
95 class Symbol;
96 class SymbolObject;
97 class Private;
98 class Uint32;
99 class Utils;
100 class Value;
101 template <class T> class Handle;
102 template <class T> class Local;
103 template <class T> class Eternal;
104 template<class T> class NonCopyablePersistentTraits;
105 template<class T> class PersistentBase;
106 template<class T,
107          class M = NonCopyablePersistentTraits<T> > class Persistent;
108 template<class T> class UniquePersistent;
109 template<class K, class V, class T> class PersistentValueMap;
110 template<class V, class T> class PersistentValueVector;
111 template<class T, class P> class WeakCallbackObject;
112 class FunctionTemplate;
113 class ObjectTemplate;
114 class Data;
115 template<typename T> class FunctionCallbackInfo;
116 template<typename T> class PropertyCallbackInfo;
117 class StackTrace;
118 class StackFrame;
119 class Isolate;
120 class DeclaredAccessorDescriptor;
121 class ObjectOperationDescriptor;
122 class RawOperationDescriptor;
123 class CallHandlerHelper;
124 class EscapableHandleScope;
125 template<typename T> class ReturnValue;
126 
127 namespace internal {
128 class Arguments;
129 class Heap;
130 class HeapObject;
131 class Isolate;
132 class Object;
133 struct StreamedSource;
134 template<typename T> class CustomArguments;
135 class PropertyCallbackArguments;
136 class FunctionCallbackArguments;
137 class GlobalHandles;
138 }
139 
140 
141 /**
142  * General purpose unique identifier.
143  */
144 class UniqueId {
145  public:
UniqueId(intptr_t data)146   explicit UniqueId(intptr_t data)
147       : data_(data) {}
148 
149   bool operator==(const UniqueId& other) const {
150     return data_ == other.data_;
151   }
152 
153   bool operator!=(const UniqueId& other) const {
154     return data_ != other.data_;
155   }
156 
157   bool operator<(const UniqueId& other) const {
158     return data_ < other.data_;
159   }
160 
161  private:
162   intptr_t data_;
163 };
164 
165 // --- Handles ---
166 
167 #define TYPE_CHECK(T, S)                                       \
168   while (false) {                                              \
169     *(static_cast<T* volatile*>(0)) = static_cast<S*>(0);      \
170   }
171 
172 
173 /**
174  * An object reference managed by the v8 garbage collector.
175  *
176  * All objects returned from v8 have to be tracked by the garbage
177  * collector so that it knows that the objects are still alive.  Also,
178  * because the garbage collector may move objects, it is unsafe to
179  * point directly to an object.  Instead, all objects are stored in
180  * handles which are known by the garbage collector and updated
181  * whenever an object moves.  Handles should always be passed by value
182  * (except in cases like out-parameters) and they should never be
183  * allocated on the heap.
184  *
185  * There are two types of handles: local and persistent handles.
186  * Local handles are light-weight and transient and typically used in
187  * local operations.  They are managed by HandleScopes.  Persistent
188  * handles can be used when storing objects across several independent
189  * operations and have to be explicitly deallocated when they're no
190  * longer used.
191  *
192  * It is safe to extract the object stored in the handle by
193  * dereferencing the handle (for instance, to extract the Object* from
194  * a Handle<Object>); the value will still be governed by a handle
195  * behind the scenes and the same rules apply to these values as to
196  * their handles.
197  */
198 template <class T> class Handle {
199  public:
200   /**
201    * Creates an empty handle.
202    */
Handle()203   V8_INLINE Handle() : val_(0) {}
204 
205   /**
206    * Creates a handle for the contents of the specified handle.  This
207    * constructor allows you to pass handles as arguments by value and
208    * to assign between handles.  However, if you try to assign between
209    * incompatible handles, for instance from a Handle<String> to a
210    * Handle<Number> it will cause a compile-time error.  Assigning
211    * between compatible handles, for instance assigning a
212    * Handle<String> to a variable declared as Handle<Value>, is legal
213    * because String is a subclass of Value.
214    */
Handle(Handle<S> that)215   template <class S> V8_INLINE Handle(Handle<S> that)
216       : val_(reinterpret_cast<T*>(*that)) {
217     /**
218      * This check fails when trying to convert between incompatible
219      * handles. For example, converting from a Handle<String> to a
220      * Handle<Number>.
221      */
222     TYPE_CHECK(T, S);
223   }
224 
225   /**
226    * Returns true if the handle is empty.
227    */
IsEmpty()228   V8_INLINE bool IsEmpty() const { return val_ == 0; }
229 
230   /**
231    * Sets the handle to be empty. IsEmpty() will then return true.
232    */
Clear()233   V8_INLINE void Clear() { val_ = 0; }
234 
235   V8_INLINE T* operator->() const { return val_; }
236 
237   V8_INLINE T* operator*() const { return val_; }
238 
239   /**
240    * Checks whether two handles are the same.
241    * Returns true if both are empty, or if the objects
242    * to which they refer are identical.
243    * The handles' references are not checked.
244    */
245   template <class S> V8_INLINE bool operator==(const Handle<S>& that) const {
246     internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
247     internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
248     if (a == 0) return b == 0;
249     if (b == 0) return false;
250     return *a == *b;
251   }
252 
253   template <class S> V8_INLINE bool operator==(
254       const PersistentBase<S>& that) const {
255     internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
256     internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
257     if (a == 0) return b == 0;
258     if (b == 0) return false;
259     return *a == *b;
260   }
261 
262   /**
263    * Checks whether two handles are different.
264    * Returns true if only one of the handles is empty, or if
265    * the objects to which they refer are different.
266    * The handles' references are not checked.
267    */
268   template <class S> V8_INLINE bool operator!=(const Handle<S>& that) const {
269     return !operator==(that);
270   }
271 
272   template <class S> V8_INLINE bool operator!=(
273       const Persistent<S>& that) const {
274     return !operator==(that);
275   }
276 
Cast(Handle<S> that)277   template <class S> V8_INLINE static Handle<T> Cast(Handle<S> that) {
278 #ifdef V8_ENABLE_CHECKS
279     // If we're going to perform the type check then we have to check
280     // that the handle isn't empty before doing the checked cast.
281     if (that.IsEmpty()) return Handle<T>();
282 #endif
283     return Handle<T>(T::Cast(*that));
284   }
285 
As()286   template <class S> V8_INLINE Handle<S> As() {
287     return Handle<S>::Cast(*this);
288   }
289 
New(Isolate * isolate,Handle<T> that)290   V8_INLINE static Handle<T> New(Isolate* isolate, Handle<T> that) {
291     return New(isolate, that.val_);
292   }
New(Isolate * isolate,const PersistentBase<T> & that)293   V8_INLINE static Handle<T> New(Isolate* isolate,
294                                  const PersistentBase<T>& that) {
295     return New(isolate, that.val_);
296   }
297 
298  private:
299   friend class Utils;
300   template<class F, class M> friend class Persistent;
301   template<class F> friend class PersistentBase;
302   template<class F> friend class Handle;
303   template<class F> friend class Local;
304   template<class F> friend class FunctionCallbackInfo;
305   template<class F> friend class PropertyCallbackInfo;
306   template<class F> friend class internal::CustomArguments;
307   friend Handle<Primitive> Undefined(Isolate* isolate);
308   friend Handle<Primitive> Null(Isolate* isolate);
309   friend Handle<Boolean> True(Isolate* isolate);
310   friend Handle<Boolean> False(Isolate* isolate);
311   friend class Context;
312   friend class HandleScope;
313   friend class Object;
314   friend class Private;
315 
316   /**
317    * Creates a new handle for the specified value.
318    */
Handle(T * val)319   V8_INLINE explicit Handle(T* val) : val_(val) {}
320 
321   V8_INLINE static Handle<T> New(Isolate* isolate, T* that);
322 
323   T* val_;
324 };
325 
326 
327 /**
328  * A light-weight stack-allocated object handle.  All operations
329  * that return objects from within v8 return them in local handles.  They
330  * are created within HandleScopes, and all local handles allocated within a
331  * handle scope are destroyed when the handle scope is destroyed.  Hence it
332  * is not necessary to explicitly deallocate local handles.
333  */
334 template <class T> class Local : public Handle<T> {
335  public:
336   V8_INLINE Local();
Local(Local<S> that)337   template <class S> V8_INLINE Local(Local<S> that)
338       : Handle<T>(reinterpret_cast<T*>(*that)) {
339     /**
340      * This check fails when trying to convert between incompatible
341      * handles. For example, converting from a Handle<String> to a
342      * Handle<Number>.
343      */
344     TYPE_CHECK(T, S);
345   }
346 
347 
Cast(Local<S> that)348   template <class S> V8_INLINE static Local<T> Cast(Local<S> that) {
349 #ifdef V8_ENABLE_CHECKS
350     // If we're going to perform the type check then we have to check
351     // that the handle isn't empty before doing the checked cast.
352     if (that.IsEmpty()) return Local<T>();
353 #endif
354     return Local<T>(T::Cast(*that));
355   }
Local(Handle<S> that)356   template <class S> V8_INLINE Local(Handle<S> that)
357       : Handle<T>(reinterpret_cast<T*>(*that)) {
358     TYPE_CHECK(T, S);
359   }
360 
As()361   template <class S> V8_INLINE Local<S> As() {
362     return Local<S>::Cast(*this);
363   }
364 
365   /**
366    * Create a local handle for the content of another handle.
367    * The referee is kept alive by the local handle even when
368    * the original handle is destroyed/disposed.
369    */
370   V8_INLINE static Local<T> New(Isolate* isolate, Handle<T> that);
371   V8_INLINE static Local<T> New(Isolate* isolate,
372                                 const PersistentBase<T>& that);
373 
374  private:
375   friend class Utils;
376   template<class F> friend class Eternal;
377   template<class F> friend class PersistentBase;
378   template<class F, class M> friend class Persistent;
379   template<class F> friend class Handle;
380   template<class F> friend class Local;
381   template<class F> friend class FunctionCallbackInfo;
382   template<class F> friend class PropertyCallbackInfo;
383   friend class String;
384   friend class Object;
385   friend class Context;
386   template<class F> friend class internal::CustomArguments;
387   friend class HandleScope;
388   friend class EscapableHandleScope;
389   template<class F1, class F2, class F3> friend class PersistentValueMap;
390   template<class F1, class F2> friend class PersistentValueVector;
391 
Local(S * that)392   template <class S> V8_INLINE Local(S* that) : Handle<T>(that) { }
393   V8_INLINE static Local<T> New(Isolate* isolate, T* that);
394 };
395 
396 
397 // Eternal handles are set-once handles that live for the life of the isolate.
398 template <class T> class Eternal {
399  public:
Eternal()400   V8_INLINE Eternal() : index_(kInitialValue) { }
401   template<class S>
Eternal(Isolate * isolate,Local<S> handle)402   V8_INLINE Eternal(Isolate* isolate, Local<S> handle) : index_(kInitialValue) {
403     Set(isolate, handle);
404   }
405   // Can only be safely called if already set.
406   V8_INLINE Local<T> Get(Isolate* isolate);
IsEmpty()407   V8_INLINE bool IsEmpty() { return index_ == kInitialValue; }
408   template<class S> V8_INLINE void Set(Isolate* isolate, Local<S> handle);
409 
410  private:
411   static const int kInitialValue = -1;
412   int index_;
413 };
414 
415 
416 template<class T, class P>
417 class WeakCallbackData {
418  public:
419   typedef void (*Callback)(const WeakCallbackData<T, P>& data);
420 
GetIsolate()421   V8_INLINE Isolate* GetIsolate() const { return isolate_; }
GetValue()422   V8_INLINE Local<T> GetValue() const { return handle_; }
GetParameter()423   V8_INLINE P* GetParameter() const { return parameter_; }
424 
425  private:
426   friend class internal::GlobalHandles;
WeakCallbackData(Isolate * isolate,Local<T> handle,P * parameter)427   WeakCallbackData(Isolate* isolate, Local<T> handle, P* parameter)
428     : isolate_(isolate), handle_(handle), parameter_(parameter) { }
429   Isolate* isolate_;
430   Local<T> handle_;
431   P* parameter_;
432 };
433 
434 
435 /**
436  * An object reference that is independent of any handle scope.  Where
437  * a Local handle only lives as long as the HandleScope in which it was
438  * allocated, a PersistentBase handle remains valid until it is explicitly
439  * disposed.
440  *
441  * A persistent handle contains a reference to a storage cell within
442  * the v8 engine which holds an object value and which is updated by
443  * the garbage collector whenever the object is moved.  A new storage
444  * cell can be created using the constructor or PersistentBase::Reset and
445  * existing handles can be disposed using PersistentBase::Reset.
446  *
447  */
448 template <class T> class PersistentBase {
449  public:
450   /**
451    * If non-empty, destroy the underlying storage cell
452    * IsEmpty() will return true after this call.
453    */
454   V8_INLINE void Reset();
455   /**
456    * If non-empty, destroy the underlying storage cell
457    * and create a new one with the contents of other if other is non empty
458    */
459   template <class S>
460   V8_INLINE void Reset(Isolate* isolate, const Handle<S>& other);
461 
462   /**
463    * If non-empty, destroy the underlying storage cell
464    * and create a new one with the contents of other if other is non empty
465    */
466   template <class S>
467   V8_INLINE void Reset(Isolate* isolate, const PersistentBase<S>& other);
468 
IsEmpty()469   V8_INLINE bool IsEmpty() const { return val_ == 0; }
470 
471   template <class S>
472   V8_INLINE bool operator==(const PersistentBase<S>& that) const {
473     internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
474     internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
475     if (a == 0) return b == 0;
476     if (b == 0) return false;
477     return *a == *b;
478   }
479 
480   template <class S> V8_INLINE bool operator==(const Handle<S>& that) const {
481     internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
482     internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
483     if (a == 0) return b == 0;
484     if (b == 0) return false;
485     return *a == *b;
486   }
487 
488   template <class S>
489   V8_INLINE bool operator!=(const PersistentBase<S>& that) const {
490     return !operator==(that);
491   }
492 
493   template <class S> V8_INLINE bool operator!=(const Handle<S>& that) const {
494     return !operator==(that);
495   }
496 
497   /**
498    *  Install a finalization callback on this object.
499    *  NOTE: There is no guarantee as to *when* or even *if* the callback is
500    *  invoked. The invocation is performed solely on a best effort basis.
501    *  As always, GC-based finalization should *not* be relied upon for any
502    *  critical form of resource management!
503    */
504   template<typename P>
505   V8_INLINE void SetWeak(
506       P* parameter,
507       typename WeakCallbackData<T, P>::Callback callback);
508 
509   template<typename S, typename P>
510   V8_INLINE void SetWeak(
511       P* parameter,
512       typename WeakCallbackData<S, P>::Callback callback);
513 
514   template<typename P>
515   V8_INLINE P* ClearWeak();
516 
517   // TODO(dcarney): remove this.
ClearWeak()518   V8_INLINE void ClearWeak() { ClearWeak<void>(); }
519 
520   /**
521    * Marks the reference to this object independent. Garbage collector is free
522    * to ignore any object groups containing this object. Weak callback for an
523    * independent handle should not assume that it will be preceded by a global
524    * GC prologue callback or followed by a global GC epilogue callback.
525    */
526   V8_INLINE void MarkIndependent();
527 
528   /**
529    * Marks the reference to this object partially dependent. Partially dependent
530    * handles only depend on other partially dependent handles and these
531    * dependencies are provided through object groups. It provides a way to build
532    * smaller object groups for young objects that represent only a subset of all
533    * external dependencies. This mark is automatically cleared after each
534    * garbage collection.
535    */
536   V8_INLINE void MarkPartiallyDependent();
537 
538   V8_INLINE bool IsIndependent() const;
539 
540   /** Checks if the handle holds the only reference to an object. */
541   V8_INLINE bool IsNearDeath() const;
542 
543   /** Returns true if the handle's reference is weak.  */
544   V8_INLINE bool IsWeak() const;
545 
546   /**
547    * Assigns a wrapper class ID to the handle. See RetainedObjectInfo interface
548    * description in v8-profiler.h for details.
549    */
550   V8_INLINE void SetWrapperClassId(uint16_t class_id);
551 
552   /**
553    * Returns the class ID previously assigned to this handle or 0 if no class ID
554    * was previously assigned.
555    */
556   V8_INLINE uint16_t WrapperClassId() const;
557 
558  private:
559   friend class Isolate;
560   friend class Utils;
561   template<class F> friend class Handle;
562   template<class F> friend class Local;
563   template<class F1, class F2> friend class Persistent;
564   template<class F> friend class UniquePersistent;
565   template<class F> friend class PersistentBase;
566   template<class F> friend class ReturnValue;
567   template<class F1, class F2, class F3> friend class PersistentValueMap;
568   template<class F1, class F2> friend class PersistentValueVector;
569   friend class Object;
570 
PersistentBase(T * val)571   explicit V8_INLINE PersistentBase(T* val) : val_(val) {}
572   PersistentBase(PersistentBase& other); // NOLINT
573   void operator=(PersistentBase&);
574   V8_INLINE static T* New(Isolate* isolate, T* that);
575 
576   T* val_;
577 };
578 
579 
580 /**
581  * Default traits for Persistent. This class does not allow
582  * use of the copy constructor or assignment operator.
583  * At present kResetInDestructor is not set, but that will change in a future
584  * version.
585  */
586 template<class T>
587 class NonCopyablePersistentTraits {
588  public:
589   typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
590   static const bool kResetInDestructor = false;
591   template<class S, class M>
Copy(const Persistent<S,M> & source,NonCopyablePersistent * dest)592   V8_INLINE static void Copy(const Persistent<S, M>& source,
593                              NonCopyablePersistent* dest) {
594     Uncompilable<Object>();
595   }
596   // TODO(dcarney): come up with a good compile error here.
Uncompilable()597   template<class O> V8_INLINE static void Uncompilable() {
598     TYPE_CHECK(O, Primitive);
599   }
600 };
601 
602 
603 /**
604  * Helper class traits to allow copying and assignment of Persistent.
605  * This will clone the contents of storage cell, but not any of the flags, etc.
606  */
607 template<class T>
608 struct CopyablePersistentTraits {
609   typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
610   static const bool kResetInDestructor = true;
611   template<class S, class M>
CopyCopyablePersistentTraits612   static V8_INLINE void Copy(const Persistent<S, M>& source,
613                              CopyablePersistent* dest) {
614     // do nothing, just allow copy
615   }
616 };
617 
618 
619 /**
620  * A PersistentBase which allows copy and assignment.
621  *
622  * Copy, assignment and destructor bevavior is controlled by the traits
623  * class M.
624  *
625  * Note: Persistent class hierarchy is subject to future changes.
626  */
627 template <class T, class M> class Persistent : public PersistentBase<T> {
628  public:
629   /**
630    * A Persistent with no storage cell.
631    */
Persistent()632   V8_INLINE Persistent() : PersistentBase<T>(0) { }
633   /**
634    * Construct a Persistent from a Handle.
635    * When the Handle is non-empty, a new storage cell is created
636    * pointing to the same object, and no flags are set.
637    */
Persistent(Isolate * isolate,Handle<S> that)638   template <class S> V8_INLINE Persistent(Isolate* isolate, Handle<S> that)
639       : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
640     TYPE_CHECK(T, S);
641   }
642   /**
643    * Construct a Persistent from a Persistent.
644    * When the Persistent is non-empty, a new storage cell is created
645    * pointing to the same object, and no flags are set.
646    */
647   template <class S, class M2>
Persistent(Isolate * isolate,const Persistent<S,M2> & that)648   V8_INLINE Persistent(Isolate* isolate, const Persistent<S, M2>& that)
649     : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
650     TYPE_CHECK(T, S);
651   }
652   /**
653    * The copy constructors and assignment operator create a Persistent
654    * exactly as the Persistent constructor, but the Copy function from the
655    * traits class is called, allowing the setting of flags based on the
656    * copied Persistent.
657    */
Persistent(const Persistent & that)658   V8_INLINE Persistent(const Persistent& that) : PersistentBase<T>(0) {
659     Copy(that);
660   }
661   template <class S, class M2>
Persistent(const Persistent<S,M2> & that)662   V8_INLINE Persistent(const Persistent<S, M2>& that) : PersistentBase<T>(0) {
663     Copy(that);
664   }
665   V8_INLINE Persistent& operator=(const Persistent& that) { // NOLINT
666     Copy(that);
667     return *this;
668   }
669   template <class S, class M2>
670   V8_INLINE Persistent& operator=(const Persistent<S, M2>& that) { // NOLINT
671     Copy(that);
672     return *this;
673   }
674   /**
675    * The destructor will dispose the Persistent based on the
676    * kResetInDestructor flags in the traits class.  Since not calling dispose
677    * can result in a memory leak, it is recommended to always set this flag.
678    */
~Persistent()679   V8_INLINE ~Persistent() {
680     if (M::kResetInDestructor) this->Reset();
681   }
682 
683   // TODO(dcarney): this is pretty useless, fix or remove
684   template <class S>
Cast(Persistent<S> & that)685   V8_INLINE static Persistent<T>& Cast(Persistent<S>& that) { // NOLINT
686 #ifdef V8_ENABLE_CHECKS
687     // If we're going to perform the type check then we have to check
688     // that the handle isn't empty before doing the checked cast.
689     if (!that.IsEmpty()) T::Cast(*that);
690 #endif
691     return reinterpret_cast<Persistent<T>&>(that);
692   }
693 
694   // TODO(dcarney): this is pretty useless, fix or remove
As()695   template <class S> V8_INLINE Persistent<S>& As() { // NOLINT
696     return Persistent<S>::Cast(*this);
697   }
698 
699   // This will be removed.
700   V8_INLINE T* ClearAndLeak();
701 
702  private:
703   friend class Isolate;
704   friend class Utils;
705   template<class F> friend class Handle;
706   template<class F> friend class Local;
707   template<class F1, class F2> friend class Persistent;
708   template<class F> friend class ReturnValue;
709 
Persistent(S * that)710   template <class S> V8_INLINE Persistent(S* that) : PersistentBase<T>(that) { }
711   V8_INLINE T* operator*() const { return this->val_; }
712   template<class S, class M2>
713   V8_INLINE void Copy(const Persistent<S, M2>& that);
714 };
715 
716 
717 /**
718  * A PersistentBase which has move semantics.
719  *
720  * Note: Persistent class hierarchy is subject to future changes.
721  */
722 template<class T>
723 class UniquePersistent : public PersistentBase<T> {
724   struct RValue {
RValueRValue725     V8_INLINE explicit RValue(UniquePersistent* obj) : object(obj) {}
726     UniquePersistent* object;
727   };
728 
729  public:
730   /**
731    * A UniquePersistent with no storage cell.
732    */
UniquePersistent()733   V8_INLINE UniquePersistent() : PersistentBase<T>(0) { }
734   /**
735    * Construct a UniquePersistent from a Handle.
736    * When the Handle is non-empty, a new storage cell is created
737    * pointing to the same object, and no flags are set.
738    */
739   template <class S>
UniquePersistent(Isolate * isolate,Handle<S> that)740   V8_INLINE UniquePersistent(Isolate* isolate, Handle<S> that)
741       : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
742     TYPE_CHECK(T, S);
743   }
744   /**
745    * Construct a UniquePersistent from a PersistentBase.
746    * When the Persistent is non-empty, a new storage cell is created
747    * pointing to the same object, and no flags are set.
748    */
749   template <class S>
UniquePersistent(Isolate * isolate,const PersistentBase<S> & that)750   V8_INLINE UniquePersistent(Isolate* isolate, const PersistentBase<S>& that)
751     : PersistentBase<T>(PersistentBase<T>::New(isolate, that.val_)) {
752     TYPE_CHECK(T, S);
753   }
754   /**
755    * Move constructor.
756    */
UniquePersistent(RValue rvalue)757   V8_INLINE UniquePersistent(RValue rvalue)
758     : PersistentBase<T>(rvalue.object->val_) {
759     rvalue.object->val_ = 0;
760   }
~UniquePersistent()761   V8_INLINE ~UniquePersistent() { this->Reset(); }
762   /**
763    * Move via assignment.
764    */
765   template<class S>
766   V8_INLINE UniquePersistent& operator=(UniquePersistent<S> rhs) {
767     TYPE_CHECK(T, S);
768     this->Reset();
769     this->val_ = rhs.val_;
770     rhs.val_ = 0;
771     return *this;
772   }
773   /**
774    * Cast operator for moves.
775    */
RValue()776   V8_INLINE operator RValue() { return RValue(this); }
777   /**
778    * Pass allows returning uniques from functions, etc.
779    */
Pass()780   UniquePersistent Pass() { return UniquePersistent(RValue(this)); }
781 
782  private:
783   UniquePersistent(UniquePersistent&);
784   void operator=(UniquePersistent&);
785 };
786 
787 
788  /**
789  * A stack-allocated class that governs a number of local handles.
790  * After a handle scope has been created, all local handles will be
791  * allocated within that handle scope until either the handle scope is
792  * deleted or another handle scope is created.  If there is already a
793  * handle scope and a new one is created, all allocations will take
794  * place in the new handle scope until it is deleted.  After that,
795  * new handles will again be allocated in the original handle scope.
796  *
797  * After the handle scope of a local handle has been deleted the
798  * garbage collector will no longer track the object stored in the
799  * handle and may deallocate it.  The behavior of accessing a handle
800  * for which the handle scope has been deleted is undefined.
801  */
802 class V8_EXPORT HandleScope {
803  public:
804   HandleScope(Isolate* isolate);
805 
806   ~HandleScope();
807 
808   /**
809    * Counts the number of allocated handles.
810    */
811   static int NumberOfHandles(Isolate* isolate);
812 
GetIsolate()813   V8_INLINE Isolate* GetIsolate() const {
814     return reinterpret_cast<Isolate*>(isolate_);
815   }
816 
817  protected:
HandleScope()818   V8_INLINE HandleScope() {}
819 
820   void Initialize(Isolate* isolate);
821 
822   static internal::Object** CreateHandle(internal::Isolate* isolate,
823                                          internal::Object* value);
824 
825  private:
826   // Uses heap_object to obtain the current Isolate.
827   static internal::Object** CreateHandle(internal::HeapObject* heap_object,
828                                          internal::Object* value);
829 
830   // Make it hard to create heap-allocated or illegal handle scopes by
831   // disallowing certain operations.
832   HandleScope(const HandleScope&);
833   void operator=(const HandleScope&);
834   void* operator new(size_t size);
835   void operator delete(void*, size_t);
836 
837   internal::Isolate* isolate_;
838   internal::Object** prev_next_;
839   internal::Object** prev_limit_;
840 
841   // Local::New uses CreateHandle with an Isolate* parameter.
842   template<class F> friend class Local;
843 
844   // Object::GetInternalField and Context::GetEmbedderData use CreateHandle with
845   // a HeapObject* in their shortcuts.
846   friend class Object;
847   friend class Context;
848 };
849 
850 
851 /**
852  * A HandleScope which first allocates a handle in the current scope
853  * which will be later filled with the escape value.
854  */
855 class V8_EXPORT EscapableHandleScope : public HandleScope {
856  public:
857   EscapableHandleScope(Isolate* isolate);
~EscapableHandleScope()858   V8_INLINE ~EscapableHandleScope() {}
859 
860   /**
861    * Pushes the value into the previous scope and returns a handle to it.
862    * Cannot be called twice.
863    */
864   template <class T>
Escape(Local<T> value)865   V8_INLINE Local<T> Escape(Local<T> value) {
866     internal::Object** slot =
867         Escape(reinterpret_cast<internal::Object**>(*value));
868     return Local<T>(reinterpret_cast<T*>(slot));
869   }
870 
871  private:
872   internal::Object** Escape(internal::Object** escape_value);
873 
874   // Make it hard to create heap-allocated or illegal handle scopes by
875   // disallowing certain operations.
876   EscapableHandleScope(const EscapableHandleScope&);
877   void operator=(const EscapableHandleScope&);
878   void* operator new(size_t size);
879   void operator delete(void*, size_t);
880 
881   internal::Object** escape_slot_;
882 };
883 
884 
885 /**
886  * A simple Maybe type, representing an object which may or may not have a
887  * value.
888  */
889 template<class T>
890 struct Maybe {
MaybeMaybe891   Maybe() : has_value(false) {}
MaybeMaybe892   explicit Maybe(T t) : has_value(true), value(t) {}
MaybeMaybe893   Maybe(bool has, T t) : has_value(has), value(t) {}
894 
895   bool has_value;
896   T value;
897 };
898 
899 
900 // Convenience wrapper.
901 template <class T>
maybe(T t)902 inline Maybe<T> maybe(T t) {
903   return Maybe<T>(t);
904 }
905 
906 
907 // --- Special objects ---
908 
909 
910 /**
911  * The superclass of values and API object templates.
912  */
913 class V8_EXPORT Data {
914  private:
915   Data();
916 };
917 
918 
919 /**
920  * The origin, within a file, of a script.
921  */
922 class ScriptOrigin {
923  public:
924   V8_INLINE ScriptOrigin(
925       Handle<Value> resource_name,
926       Handle<Integer> resource_line_offset = Handle<Integer>(),
927       Handle<Integer> resource_column_offset = Handle<Integer>(),
928       Handle<Boolean> resource_is_shared_cross_origin = Handle<Boolean>(),
929       Handle<Integer> script_id = Handle<Integer>())
resource_name_(resource_name)930       : resource_name_(resource_name),
931         resource_line_offset_(resource_line_offset),
932         resource_column_offset_(resource_column_offset),
933         resource_is_shared_cross_origin_(resource_is_shared_cross_origin),
934         script_id_(script_id) { }
935   V8_INLINE Handle<Value> ResourceName() const;
936   V8_INLINE Handle<Integer> ResourceLineOffset() const;
937   V8_INLINE Handle<Integer> ResourceColumnOffset() const;
938   V8_INLINE Handle<Boolean> ResourceIsSharedCrossOrigin() const;
939   V8_INLINE Handle<Integer> ScriptID() const;
940  private:
941   Handle<Value> resource_name_;
942   Handle<Integer> resource_line_offset_;
943   Handle<Integer> resource_column_offset_;
944   Handle<Boolean> resource_is_shared_cross_origin_;
945   Handle<Integer> script_id_;
946 };
947 
948 
949 /**
950  * A compiled JavaScript script, not yet tied to a Context.
951  */
952 class V8_EXPORT UnboundScript {
953  public:
954   /**
955    * Binds the script to the currently entered context.
956    */
957   Local<Script> BindToCurrentContext();
958 
959   int GetId();
960   Handle<Value> GetScriptName();
961 
962   /**
963    * Data read from magic sourceURL comments.
964    */
965   Handle<Value> GetSourceURL();
966   /**
967    * Data read from magic sourceMappingURL comments.
968    */
969   Handle<Value> GetSourceMappingURL();
970 
971   /**
972    * Returns zero based line number of the code_pos location in the script.
973    * -1 will be returned if no information available.
974    */
975   int GetLineNumber(int code_pos);
976 
977   static const int kNoScriptId = 0;
978 };
979 
980 
981 /**
982  * A compiled JavaScript script, tied to a Context which was active when the
983  * script was compiled.
984  */
985 class V8_EXPORT Script {
986  public:
987   /**
988    * A shorthand for ScriptCompiler::Compile().
989    */
990   static Local<Script> Compile(Handle<String> source,
991                                ScriptOrigin* origin = NULL);
992 
993   // To be decprecated, use the Compile above.
994   static Local<Script> Compile(Handle<String> source,
995                                Handle<String> file_name);
996 
997   /**
998    * Runs the script returning the resulting value. It will be run in the
999    * context in which it was created (ScriptCompiler::CompileBound or
1000    * UnboundScript::BindToGlobalContext()).
1001    */
1002   Local<Value> Run();
1003 
1004   /**
1005    * Returns the corresponding context-unbound script.
1006    */
1007   Local<UnboundScript> GetUnboundScript();
1008 
1009   V8_DEPRECATED("Use GetUnboundScript()->GetId()",
GetId()1010                 int GetId()) {
1011     return GetUnboundScript()->GetId();
1012   }
1013 };
1014 
1015 
1016 /**
1017  * For compiling scripts.
1018  */
1019 class V8_EXPORT ScriptCompiler {
1020  public:
1021   /**
1022    * Compilation data that the embedder can cache and pass back to speed up
1023    * future compilations. The data is produced if the CompilerOptions passed to
1024    * the compilation functions in ScriptCompiler contains produce_data_to_cache
1025    * = true. The data to cache can then can be retrieved from
1026    * UnboundScript.
1027    */
1028   struct V8_EXPORT CachedData {
1029     enum BufferPolicy {
1030       BufferNotOwned,
1031       BufferOwned
1032     };
1033 
CachedDataCachedData1034     CachedData() : data(NULL), length(0), buffer_policy(BufferNotOwned) {}
1035 
1036     // If buffer_policy is BufferNotOwned, the caller keeps the ownership of
1037     // data and guarantees that it stays alive until the CachedData object is
1038     // destroyed. If the policy is BufferOwned, the given data will be deleted
1039     // (with delete[]) when the CachedData object is destroyed.
1040     CachedData(const uint8_t* data, int length,
1041                BufferPolicy buffer_policy = BufferNotOwned);
1042     ~CachedData();
1043     // TODO(marja): Async compilation; add constructors which take a callback
1044     // which will be called when V8 no longer needs the data.
1045     const uint8_t* data;
1046     int length;
1047     BufferPolicy buffer_policy;
1048 
1049    private:
1050     // Prevent copying. Not implemented.
1051     CachedData(const CachedData&);
1052     CachedData& operator=(const CachedData&);
1053   };
1054 
1055   /**
1056    * Source code which can be then compiled to a UnboundScript or Script.
1057    */
1058   class Source {
1059    public:
1060     // Source takes ownership of CachedData.
1061     V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
1062            CachedData* cached_data = NULL);
1063     V8_INLINE Source(Local<String> source_string,
1064                      CachedData* cached_data = NULL);
1065     V8_INLINE ~Source();
1066 
1067     // Ownership of the CachedData or its buffers is *not* transferred to the
1068     // caller. The CachedData object is alive as long as the Source object is
1069     // alive.
1070     V8_INLINE const CachedData* GetCachedData() const;
1071 
1072    private:
1073     friend class ScriptCompiler;
1074     // Prevent copying. Not implemented.
1075     Source(const Source&);
1076     Source& operator=(const Source&);
1077 
1078     Local<String> source_string;
1079 
1080     // Origin information
1081     Handle<Value> resource_name;
1082     Handle<Integer> resource_line_offset;
1083     Handle<Integer> resource_column_offset;
1084     Handle<Boolean> resource_is_shared_cross_origin;
1085 
1086     // Cached data from previous compilation (if a kConsume*Cache flag is
1087     // set), or hold newly generated cache data (kProduce*Cache flags) are
1088     // set when calling a compile method.
1089     CachedData* cached_data;
1090   };
1091 
1092   /**
1093    * For streaming incomplete script data to V8. The embedder should implement a
1094    * subclass of this class.
1095    */
1096   class ExternalSourceStream {
1097    public:
~ExternalSourceStream()1098     virtual ~ExternalSourceStream() {}
1099 
1100     /**
1101      * V8 calls this to request the next chunk of data from the embedder. This
1102      * function will be called on a background thread, so it's OK to block and
1103      * wait for the data, if the embedder doesn't have data yet. Returns the
1104      * length of the data returned. When the data ends, GetMoreData should
1105      * return 0. Caller takes ownership of the data.
1106      *
1107      * When streaming UTF-8 data, V8 handles multi-byte characters split between
1108      * two data chunks, but doesn't handle multi-byte characters split between
1109      * more than two data chunks. The embedder can avoid this problem by always
1110      * returning at least 2 bytes of data.
1111      *
1112      * If the embedder wants to cancel the streaming, they should make the next
1113      * GetMoreData call return 0. V8 will interpret it as end of data (and most
1114      * probably, parsing will fail). The streaming task will return as soon as
1115      * V8 has parsed the data it received so far.
1116      */
1117     virtual size_t GetMoreData(const uint8_t** src) = 0;
1118   };
1119 
1120 
1121   /**
1122    * Source code which can be streamed into V8 in pieces. It will be parsed
1123    * while streaming. It can be compiled after the streaming is complete.
1124    * StreamedSource must be kept alive while the streaming task is ran (see
1125    * ScriptStreamingTask below).
1126    */
1127   class V8_EXPORT StreamedSource {
1128    public:
1129     enum Encoding { ONE_BYTE, TWO_BYTE, UTF8 };
1130 
1131     StreamedSource(ExternalSourceStream* source_stream, Encoding encoding);
1132     ~StreamedSource();
1133 
1134     // Ownership of the CachedData or its buffers is *not* transferred to the
1135     // caller. The CachedData object is alive as long as the StreamedSource
1136     // object is alive.
1137     const CachedData* GetCachedData() const;
1138 
impl()1139     internal::StreamedSource* impl() const { return impl_; }
1140 
1141    private:
1142     // Prevent copying. Not implemented.
1143     StreamedSource(const StreamedSource&);
1144     StreamedSource& operator=(const StreamedSource&);
1145 
1146     internal::StreamedSource* impl_;
1147   };
1148 
1149   /**
1150    * A streaming task which the embedder must run on a background thread to
1151    * stream scripts into V8. Returned by ScriptCompiler::StartStreamingScript.
1152    */
1153   class ScriptStreamingTask {
1154    public:
~ScriptStreamingTask()1155     virtual ~ScriptStreamingTask() {}
1156     virtual void Run() = 0;
1157   };
1158 
1159   enum CompileOptions {
1160     kNoCompileOptions = 0,
1161     kProduceParserCache,
1162     kConsumeParserCache,
1163     kProduceCodeCache,
1164     kConsumeCodeCache,
1165 
1166     // Support the previous API for a transition period.
1167     kProduceDataToCache
1168   };
1169 
1170   /**
1171    * Compiles the specified script (context-independent).
1172    * Cached data as part of the source object can be optionally produced to be
1173    * consumed later to speed up compilation of identical source scripts.
1174    *
1175    * Note that when producing cached data, the source must point to NULL for
1176    * cached data. When consuming cached data, the cached data must have been
1177    * produced by the same version of V8.
1178    *
1179    * \param source Script source code.
1180    * \return Compiled script object (context independent; for running it must be
1181    *   bound to a context).
1182    */
1183   static Local<UnboundScript> CompileUnbound(
1184       Isolate* isolate, Source* source,
1185       CompileOptions options = kNoCompileOptions);
1186 
1187   /**
1188    * Compiles the specified script (bound to current context).
1189    *
1190    * \param source Script source code.
1191    * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
1192    *   using pre_data speeds compilation if it's done multiple times.
1193    *   Owned by caller, no references are kept when this function returns.
1194    * \return Compiled script object, bound to the context that was active
1195    *   when this function was called. When run it will always use this
1196    *   context.
1197    */
1198   static Local<Script> Compile(
1199       Isolate* isolate, Source* source,
1200       CompileOptions options = kNoCompileOptions);
1201 
1202   /**
1203    * Returns a task which streams script data into V8, or NULL if the script
1204    * cannot be streamed. The user is responsible for running the task on a
1205    * background thread and deleting it. When ran, the task starts parsing the
1206    * script, and it will request data from the StreamedSource as needed. When
1207    * ScriptStreamingTask::Run exits, all data has been streamed and the script
1208    * can be compiled (see Compile below).
1209    *
1210    * This API allows to start the streaming with as little data as possible, and
1211    * the remaining data (for example, the ScriptOrigin) is passed to Compile.
1212    */
1213   static ScriptStreamingTask* StartStreamingScript(
1214       Isolate* isolate, StreamedSource* source,
1215       CompileOptions options = kNoCompileOptions);
1216 
1217   /**
1218    * Compiles a streamed script (bound to current context).
1219    *
1220    * This can only be called after the streaming has finished
1221    * (ScriptStreamingTask has been run). V8 doesn't construct the source string
1222    * during streaming, so the embedder needs to pass the full source here.
1223    */
1224   static Local<Script> Compile(Isolate* isolate, StreamedSource* source,
1225                                Handle<String> full_source_string,
1226                                const ScriptOrigin& origin);
1227 };
1228 
1229 
1230 /**
1231  * An error message.
1232  */
1233 class V8_EXPORT Message {
1234  public:
1235   Local<String> Get() const;
1236   Local<String> GetSourceLine() const;
1237 
1238   /**
1239    * Returns the origin for the script from where the function causing the
1240    * error originates.
1241    */
1242   ScriptOrigin GetScriptOrigin() const;
1243 
1244   /**
1245    * Returns the resource name for the script from where the function causing
1246    * the error originates.
1247    */
1248   Handle<Value> GetScriptResourceName() const;
1249 
1250   /**
1251    * Exception stack trace. By default stack traces are not captured for
1252    * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
1253    * to change this option.
1254    */
1255   Handle<StackTrace> GetStackTrace() const;
1256 
1257   /**
1258    * Returns the number, 1-based, of the line where the error occurred.
1259    */
1260   int GetLineNumber() const;
1261 
1262   /**
1263    * Returns the index within the script of the first character where
1264    * the error occurred.
1265    */
1266   int GetStartPosition() const;
1267 
1268   /**
1269    * Returns the index within the script of the last character where
1270    * the error occurred.
1271    */
1272   int GetEndPosition() const;
1273 
1274   /**
1275    * Returns the index within the line of the first character where
1276    * the error occurred.
1277    */
1278   int GetStartColumn() const;
1279 
1280   /**
1281    * Returns the index within the line of the last character where
1282    * the error occurred.
1283    */
1284   int GetEndColumn() const;
1285 
1286   /**
1287    * Passes on the value set by the embedder when it fed the script from which
1288    * this Message was generated to V8.
1289    */
1290   bool IsSharedCrossOrigin() const;
1291 
1292   // TODO(1245381): Print to a string instead of on a FILE.
1293   static void PrintCurrentStackTrace(Isolate* isolate, FILE* out);
1294 
1295   static const int kNoLineNumberInfo = 0;
1296   static const int kNoColumnInfo = 0;
1297   static const int kNoScriptIdInfo = 0;
1298 };
1299 
1300 
1301 /**
1302  * Representation of a JavaScript stack trace. The information collected is a
1303  * snapshot of the execution stack and the information remains valid after
1304  * execution continues.
1305  */
1306 class V8_EXPORT StackTrace {
1307  public:
1308   /**
1309    * Flags that determine what information is placed captured for each
1310    * StackFrame when grabbing the current stack trace.
1311    */
1312   enum StackTraceOptions {
1313     kLineNumber = 1,
1314     kColumnOffset = 1 << 1 | kLineNumber,
1315     kScriptName = 1 << 2,
1316     kFunctionName = 1 << 3,
1317     kIsEval = 1 << 4,
1318     kIsConstructor = 1 << 5,
1319     kScriptNameOrSourceURL = 1 << 6,
1320     kScriptId = 1 << 7,
1321     kExposeFramesAcrossSecurityOrigins = 1 << 8,
1322     kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
1323     kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL
1324   };
1325 
1326   /**
1327    * Returns a StackFrame at a particular index.
1328    */
1329   Local<StackFrame> GetFrame(uint32_t index) const;
1330 
1331   /**
1332    * Returns the number of StackFrames.
1333    */
1334   int GetFrameCount() const;
1335 
1336   /**
1337    * Returns StackTrace as a v8::Array that contains StackFrame objects.
1338    */
1339   Local<Array> AsArray();
1340 
1341   /**
1342    * Grab a snapshot of the current JavaScript execution stack.
1343    *
1344    * \param frame_limit The maximum number of stack frames we want to capture.
1345    * \param options Enumerates the set of things we will capture for each
1346    *   StackFrame.
1347    */
1348   static Local<StackTrace> CurrentStackTrace(
1349       Isolate* isolate,
1350       int frame_limit,
1351       StackTraceOptions options = kOverview);
1352 };
1353 
1354 
1355 /**
1356  * A single JavaScript stack frame.
1357  */
1358 class V8_EXPORT StackFrame {
1359  public:
1360   /**
1361    * Returns the number, 1-based, of the line for the associate function call.
1362    * This method will return Message::kNoLineNumberInfo if it is unable to
1363    * retrieve the line number, or if kLineNumber was not passed as an option
1364    * when capturing the StackTrace.
1365    */
1366   int GetLineNumber() const;
1367 
1368   /**
1369    * Returns the 1-based column offset on the line for the associated function
1370    * call.
1371    * This method will return Message::kNoColumnInfo if it is unable to retrieve
1372    * the column number, or if kColumnOffset was not passed as an option when
1373    * capturing the StackTrace.
1374    */
1375   int GetColumn() const;
1376 
1377   /**
1378    * Returns the id of the script for the function for this StackFrame.
1379    * This method will return Message::kNoScriptIdInfo if it is unable to
1380    * retrieve the script id, or if kScriptId was not passed as an option when
1381    * capturing the StackTrace.
1382    */
1383   int GetScriptId() const;
1384 
1385   /**
1386    * Returns the name of the resource that contains the script for the
1387    * function for this StackFrame.
1388    */
1389   Local<String> GetScriptName() const;
1390 
1391   /**
1392    * Returns the name of the resource that contains the script for the
1393    * function for this StackFrame or sourceURL value if the script name
1394    * is undefined and its source ends with //# sourceURL=... string or
1395    * deprecated //@ sourceURL=... string.
1396    */
1397   Local<String> GetScriptNameOrSourceURL() const;
1398 
1399   /**
1400    * Returns the name of the function associated with this stack frame.
1401    */
1402   Local<String> GetFunctionName() const;
1403 
1404   /**
1405    * Returns whether or not the associated function is compiled via a call to
1406    * eval().
1407    */
1408   bool IsEval() const;
1409 
1410   /**
1411    * Returns whether or not the associated function is called as a
1412    * constructor via "new".
1413    */
1414   bool IsConstructor() const;
1415 };
1416 
1417 
1418 /**
1419  * A JSON Parser.
1420  */
1421 class V8_EXPORT JSON {
1422  public:
1423   /**
1424    * Tries to parse the string |json_string| and returns it as value if
1425    * successful.
1426    *
1427    * \param json_string The string to parse.
1428    * \return The corresponding value if successfully parsed.
1429    */
1430   static Local<Value> Parse(Local<String> json_string);
1431 };
1432 
1433 
1434 // --- Value ---
1435 
1436 
1437 /**
1438  * The superclass of all JavaScript values and objects.
1439  */
1440 class V8_EXPORT Value : public Data {
1441  public:
1442   /**
1443    * Returns true if this value is the undefined value.  See ECMA-262
1444    * 4.3.10.
1445    */
1446   V8_INLINE bool IsUndefined() const;
1447 
1448   /**
1449    * Returns true if this value is the null value.  See ECMA-262
1450    * 4.3.11.
1451    */
1452   V8_INLINE bool IsNull() const;
1453 
1454    /**
1455    * Returns true if this value is true.
1456    */
1457   bool IsTrue() const;
1458 
1459   /**
1460    * Returns true if this value is false.
1461    */
1462   bool IsFalse() const;
1463 
1464   /**
1465    * Returns true if this value is a symbol or a string.
1466    * This is an experimental feature.
1467    */
1468   bool IsName() const;
1469 
1470   /**
1471    * Returns true if this value is an instance of the String type.
1472    * See ECMA-262 8.4.
1473    */
1474   V8_INLINE bool IsString() const;
1475 
1476   /**
1477    * Returns true if this value is a symbol.
1478    * This is an experimental feature.
1479    */
1480   bool IsSymbol() const;
1481 
1482   /**
1483    * Returns true if this value is a function.
1484    */
1485   bool IsFunction() const;
1486 
1487   /**
1488    * Returns true if this value is an array.
1489    */
1490   bool IsArray() const;
1491 
1492   /**
1493    * Returns true if this value is an object.
1494    */
1495   bool IsObject() const;
1496 
1497   /**
1498    * Returns true if this value is boolean.
1499    */
1500   bool IsBoolean() const;
1501 
1502   /**
1503    * Returns true if this value is a number.
1504    */
1505   bool IsNumber() const;
1506 
1507   /**
1508    * Returns true if this value is external.
1509    */
1510   bool IsExternal() const;
1511 
1512   /**
1513    * Returns true if this value is a 32-bit signed integer.
1514    */
1515   bool IsInt32() const;
1516 
1517   /**
1518    * Returns true if this value is a 32-bit unsigned integer.
1519    */
1520   bool IsUint32() const;
1521 
1522   /**
1523    * Returns true if this value is a Date.
1524    */
1525   bool IsDate() const;
1526 
1527   /**
1528    * Returns true if this value is an Arguments object.
1529    */
1530   bool IsArgumentsObject() const;
1531 
1532   /**
1533    * Returns true if this value is a Boolean object.
1534    */
1535   bool IsBooleanObject() const;
1536 
1537   /**
1538    * Returns true if this value is a Number object.
1539    */
1540   bool IsNumberObject() const;
1541 
1542   /**
1543    * Returns true if this value is a String object.
1544    */
1545   bool IsStringObject() const;
1546 
1547   /**
1548    * Returns true if this value is a Symbol object.
1549    * This is an experimental feature.
1550    */
1551   bool IsSymbolObject() const;
1552 
1553   /**
1554    * Returns true if this value is a NativeError.
1555    */
1556   bool IsNativeError() const;
1557 
1558   /**
1559    * Returns true if this value is a RegExp.
1560    */
1561   bool IsRegExp() const;
1562 
1563   /**
1564    * Returns true if this value is a Promise.
1565    * This is an experimental feature.
1566    */
1567   bool IsPromise() const;
1568 
1569   /**
1570    * Returns true if this value is a Map.
1571    * This is an experimental feature.
1572    */
1573   bool IsMap() const;
1574 
1575   /**
1576    * Returns true if this value is a Set.
1577    * This is an experimental feature.
1578    */
1579   bool IsSet() const;
1580 
1581   /**
1582    * Returns true if this value is a WeakMap.
1583    * This is an experimental feature.
1584    */
1585   bool IsWeakMap() const;
1586 
1587   /**
1588    * Returns true if this value is a WeakSet.
1589    * This is an experimental feature.
1590    */
1591   bool IsWeakSet() const;
1592 
1593   /**
1594    * Returns true if this value is an ArrayBuffer.
1595    * This is an experimental feature.
1596    */
1597   bool IsArrayBuffer() const;
1598 
1599   /**
1600    * Returns true if this value is an ArrayBufferView.
1601    * This is an experimental feature.
1602    */
1603   bool IsArrayBufferView() const;
1604 
1605   /**
1606    * Returns true if this value is one of TypedArrays.
1607    * This is an experimental feature.
1608    */
1609   bool IsTypedArray() const;
1610 
1611   /**
1612    * Returns true if this value is an Uint8Array.
1613    * This is an experimental feature.
1614    */
1615   bool IsUint8Array() const;
1616 
1617   /**
1618    * Returns true if this value is an Uint8ClampedArray.
1619    * This is an experimental feature.
1620    */
1621   bool IsUint8ClampedArray() const;
1622 
1623   /**
1624    * Returns true if this value is an Int8Array.
1625    * This is an experimental feature.
1626    */
1627   bool IsInt8Array() const;
1628 
1629   /**
1630    * Returns true if this value is an Uint16Array.
1631    * This is an experimental feature.
1632    */
1633   bool IsUint16Array() const;
1634 
1635   /**
1636    * Returns true if this value is an Int16Array.
1637    * This is an experimental feature.
1638    */
1639   bool IsInt16Array() const;
1640 
1641   /**
1642    * Returns true if this value is an Uint32Array.
1643    * This is an experimental feature.
1644    */
1645   bool IsUint32Array() const;
1646 
1647   /**
1648    * Returns true if this value is an Int32Array.
1649    * This is an experimental feature.
1650    */
1651   bool IsInt32Array() const;
1652 
1653   /**
1654    * Returns true if this value is a Float32Array.
1655    * This is an experimental feature.
1656    */
1657   bool IsFloat32Array() const;
1658 
1659   /**
1660    * Returns true if this value is a Float64Array.
1661    * This is an experimental feature.
1662    */
1663   bool IsFloat64Array() const;
1664 
1665   /**
1666    * Returns true if this value is a DataView.
1667    * This is an experimental feature.
1668    */
1669   bool IsDataView() const;
1670 
1671   Local<Boolean> ToBoolean() const;
1672   Local<Number> ToNumber() const;
1673   Local<String> ToString() const;
1674   Local<String> ToDetailString() const;
1675   Local<Object> ToObject() const;
1676   Local<Integer> ToInteger() const;
1677   Local<Uint32> ToUint32() const;
1678   Local<Int32> ToInt32() const;
1679 
1680   /**
1681    * Attempts to convert a string to an array index.
1682    * Returns an empty handle if the conversion fails.
1683    */
1684   Local<Uint32> ToArrayIndex() const;
1685 
1686   bool BooleanValue() const;
1687   double NumberValue() const;
1688   int64_t IntegerValue() const;
1689   uint32_t Uint32Value() const;
1690   int32_t Int32Value() const;
1691 
1692   /** JS == */
1693   bool Equals(Handle<Value> that) const;
1694   bool StrictEquals(Handle<Value> that) const;
1695   bool SameValue(Handle<Value> that) const;
1696 
1697   template <class T> V8_INLINE static Value* Cast(T* value);
1698 
1699  private:
1700   V8_INLINE bool QuickIsUndefined() const;
1701   V8_INLINE bool QuickIsNull() const;
1702   V8_INLINE bool QuickIsString() const;
1703   bool FullIsUndefined() const;
1704   bool FullIsNull() const;
1705   bool FullIsString() const;
1706 };
1707 
1708 
1709 /**
1710  * The superclass of primitive values.  See ECMA-262 4.3.2.
1711  */
1712 class V8_EXPORT Primitive : public Value { };
1713 
1714 
1715 /**
1716  * A primitive boolean value (ECMA-262, 4.3.14).  Either the true
1717  * or false value.
1718  */
1719 class V8_EXPORT Boolean : public Primitive {
1720  public:
1721   bool Value() const;
1722   V8_INLINE static Handle<Boolean> New(Isolate* isolate, bool value);
1723 };
1724 
1725 
1726 /**
1727  * A superclass for symbols and strings.
1728  */
1729 class V8_EXPORT Name : public Primitive {
1730  public:
1731   V8_INLINE static Name* Cast(v8::Value* obj);
1732  private:
1733   static void CheckCast(v8::Value* obj);
1734 };
1735 
1736 
1737 /**
1738  * A JavaScript string value (ECMA-262, 4.3.17).
1739  */
1740 class V8_EXPORT String : public Name {
1741  public:
1742   enum Encoding {
1743     UNKNOWN_ENCODING = 0x1,
1744     TWO_BYTE_ENCODING = 0x0,
1745     ASCII_ENCODING = 0x4,  // TODO(yangguo): deprecate this.
1746     ONE_BYTE_ENCODING = 0x4
1747   };
1748   /**
1749    * Returns the number of characters in this string.
1750    */
1751   int Length() const;
1752 
1753   /**
1754    * Returns the number of bytes in the UTF-8 encoded
1755    * representation of this string.
1756    */
1757   int Utf8Length() const;
1758 
1759   /**
1760    * Returns whether this string is known to contain only one byte data.
1761    * Does not read the string.
1762    * False negatives are possible.
1763    */
1764   bool IsOneByte() const;
1765 
1766   /**
1767    * Returns whether this string contain only one byte data.
1768    * Will read the entire string in some cases.
1769    */
1770   bool ContainsOnlyOneByte() const;
1771 
1772   /**
1773    * Write the contents of the string to an external buffer.
1774    * If no arguments are given, expects the buffer to be large
1775    * enough to hold the entire string and NULL terminator. Copies
1776    * the contents of the string and the NULL terminator into the
1777    * buffer.
1778    *
1779    * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
1780    * before the end of the buffer.
1781    *
1782    * Copies up to length characters into the output buffer.
1783    * Only null-terminates if there is enough space in the buffer.
1784    *
1785    * \param buffer The buffer into which the string will be copied.
1786    * \param start The starting position within the string at which
1787    * copying begins.
1788    * \param length The number of characters to copy from the string.  For
1789    *    WriteUtf8 the number of bytes in the buffer.
1790    * \param nchars_ref The number of characters written, can be NULL.
1791    * \param options Various options that might affect performance of this or
1792    *    subsequent operations.
1793    * \return The number of characters copied to the buffer excluding the null
1794    *    terminator.  For WriteUtf8: The number of bytes copied to the buffer
1795    *    including the null terminator (if written).
1796    */
1797   enum WriteOptions {
1798     NO_OPTIONS = 0,
1799     HINT_MANY_WRITES_EXPECTED = 1,
1800     NO_NULL_TERMINATION = 2,
1801     PRESERVE_ASCII_NULL = 4,  // TODO(yangguo): deprecate this.
1802     PRESERVE_ONE_BYTE_NULL = 4,
1803     // Used by WriteUtf8 to replace orphan surrogate code units with the
1804     // unicode replacement character. Needs to be set to guarantee valid UTF-8
1805     // output.
1806     REPLACE_INVALID_UTF8 = 8
1807   };
1808 
1809   // 16-bit character codes.
1810   int Write(uint16_t* buffer,
1811             int start = 0,
1812             int length = -1,
1813             int options = NO_OPTIONS) const;
1814   // One byte characters.
1815   int WriteOneByte(uint8_t* buffer,
1816                    int start = 0,
1817                    int length = -1,
1818                    int options = NO_OPTIONS) const;
1819   // UTF-8 encoded characters.
1820   int WriteUtf8(char* buffer,
1821                 int length = -1,
1822                 int* nchars_ref = NULL,
1823                 int options = NO_OPTIONS) const;
1824 
1825   /**
1826    * A zero length string.
1827    */
1828   V8_INLINE static v8::Local<v8::String> Empty(Isolate* isolate);
1829 
1830   /**
1831    * Returns true if the string is external
1832    */
1833   bool IsExternal() const;
1834 
1835   /**
1836    * Returns true if the string is both external and one-byte.
1837    */
1838   bool IsExternalOneByte() const;
1839 
1840   // TODO(yangguo): deprecate this.
IsExternalAscii()1841   bool IsExternalAscii() const { return IsExternalOneByte(); }
1842 
1843   class V8_EXPORT ExternalStringResourceBase {  // NOLINT
1844    public:
~ExternalStringResourceBase()1845     virtual ~ExternalStringResourceBase() {}
1846 
1847    protected:
ExternalStringResourceBase()1848     ExternalStringResourceBase() {}
1849 
1850     /**
1851      * Internally V8 will call this Dispose method when the external string
1852      * resource is no longer needed. The default implementation will use the
1853      * delete operator. This method can be overridden in subclasses to
1854      * control how allocated external string resources are disposed.
1855      */
Dispose()1856     virtual void Dispose() { delete this; }
1857 
1858    private:
1859     // Disallow copying and assigning.
1860     ExternalStringResourceBase(const ExternalStringResourceBase&);
1861     void operator=(const ExternalStringResourceBase&);
1862 
1863     friend class v8::internal::Heap;
1864   };
1865 
1866   /**
1867    * An ExternalStringResource is a wrapper around a two-byte string
1868    * buffer that resides outside V8's heap. Implement an
1869    * ExternalStringResource to manage the life cycle of the underlying
1870    * buffer.  Note that the string data must be immutable.
1871    */
1872   class V8_EXPORT ExternalStringResource
1873       : public ExternalStringResourceBase {
1874    public:
1875     /**
1876      * Override the destructor to manage the life cycle of the underlying
1877      * buffer.
1878      */
~ExternalStringResource()1879     virtual ~ExternalStringResource() {}
1880 
1881     /**
1882      * The string data from the underlying buffer.
1883      */
1884     virtual const uint16_t* data() const = 0;
1885 
1886     /**
1887      * The length of the string. That is, the number of two-byte characters.
1888      */
1889     virtual size_t length() const = 0;
1890 
1891    protected:
ExternalStringResource()1892     ExternalStringResource() {}
1893   };
1894 
1895   /**
1896    * An ExternalOneByteStringResource is a wrapper around an one-byte
1897    * string buffer that resides outside V8's heap. Implement an
1898    * ExternalOneByteStringResource to manage the life cycle of the
1899    * underlying buffer.  Note that the string data must be immutable
1900    * and that the data must be Latin-1 and not UTF-8, which would require
1901    * special treatment internally in the engine and do not allow efficient
1902    * indexing.  Use String::New or convert to 16 bit data for non-Latin1.
1903    */
1904 
1905   class V8_EXPORT ExternalOneByteStringResource
1906       : public ExternalStringResourceBase {
1907    public:
1908     /**
1909      * Override the destructor to manage the life cycle of the underlying
1910      * buffer.
1911      */
~ExternalOneByteStringResource()1912     virtual ~ExternalOneByteStringResource() {}
1913     /** The string data from the underlying buffer.*/
1914     virtual const char* data() const = 0;
1915     /** The number of Latin-1 characters in the string.*/
1916     virtual size_t length() const = 0;
1917    protected:
ExternalOneByteStringResource()1918     ExternalOneByteStringResource() {}
1919   };
1920 
1921   typedef ExternalOneByteStringResource ExternalAsciiStringResource;
1922 
1923   /**
1924    * If the string is an external string, return the ExternalStringResourceBase
1925    * regardless of the encoding, otherwise return NULL.  The encoding of the
1926    * string is returned in encoding_out.
1927    */
1928   V8_INLINE ExternalStringResourceBase* GetExternalStringResourceBase(
1929       Encoding* encoding_out) const;
1930 
1931   /**
1932    * Get the ExternalStringResource for an external string.  Returns
1933    * NULL if IsExternal() doesn't return true.
1934    */
1935   V8_INLINE ExternalStringResource* GetExternalStringResource() const;
1936 
1937   /**
1938    * Get the ExternalOneByteStringResource for an external one-byte string.
1939    * Returns NULL if IsExternalOneByte() doesn't return true.
1940    */
1941   const ExternalOneByteStringResource* GetExternalOneByteStringResource() const;
1942 
1943   // TODO(yangguo): deprecate this.
GetExternalAsciiStringResource()1944   const ExternalAsciiStringResource* GetExternalAsciiStringResource() const {
1945     return GetExternalOneByteStringResource();
1946   }
1947 
1948   V8_INLINE static String* Cast(v8::Value* obj);
1949 
1950   enum NewStringType {
1951     kNormalString, kInternalizedString, kUndetectableString
1952   };
1953 
1954   /** Allocates a new string from UTF-8 data.*/
1955   static Local<String> NewFromUtf8(Isolate* isolate,
1956                                   const char* data,
1957                                   NewStringType type = kNormalString,
1958                                   int length = -1);
1959 
1960   /** Allocates a new string from Latin-1 data.*/
1961   static Local<String> NewFromOneByte(
1962       Isolate* isolate,
1963       const uint8_t* data,
1964       NewStringType type = kNormalString,
1965       int length = -1);
1966 
1967   /** Allocates a new string from UTF-16 data.*/
1968   static Local<String> NewFromTwoByte(
1969       Isolate* isolate,
1970       const uint16_t* data,
1971       NewStringType type = kNormalString,
1972       int length = -1);
1973 
1974   /**
1975    * Creates a new string by concatenating the left and the right strings
1976    * passed in as parameters.
1977    */
1978   static Local<String> Concat(Handle<String> left, Handle<String> right);
1979 
1980   /**
1981    * Creates a new external string using the data defined in the given
1982    * resource. When the external string is no longer live on V8's heap the
1983    * resource will be disposed by calling its Dispose method. The caller of
1984    * this function should not otherwise delete or modify the resource. Neither
1985    * should the underlying buffer be deallocated or modified except through the
1986    * destructor of the external string resource.
1987    */
1988   static Local<String> NewExternal(Isolate* isolate,
1989                                    ExternalStringResource* resource);
1990 
1991   /**
1992    * Associate an external string resource with this string by transforming it
1993    * in place so that existing references to this string in the JavaScript heap
1994    * will use the external string resource. The external string resource's
1995    * character contents need to be equivalent to this string.
1996    * Returns true if the string has been changed to be an external string.
1997    * The string is not modified if the operation fails. See NewExternal for
1998    * information on the lifetime of the resource.
1999    */
2000   bool MakeExternal(ExternalStringResource* resource);
2001 
2002   /**
2003    * Creates a new external string using the one-byte data defined in the given
2004    * resource. When the external string is no longer live on V8's heap the
2005    * resource will be disposed by calling its Dispose method. The caller of
2006    * this function should not otherwise delete or modify the resource. Neither
2007    * should the underlying buffer be deallocated or modified except through the
2008    * destructor of the external string resource.
2009    */
2010   static Local<String> NewExternal(Isolate* isolate,
2011                                    ExternalOneByteStringResource* resource);
2012 
2013   /**
2014    * Associate an external string resource with this string by transforming it
2015    * in place so that existing references to this string in the JavaScript heap
2016    * will use the external string resource. The external string resource's
2017    * character contents need to be equivalent to this string.
2018    * Returns true if the string has been changed to be an external string.
2019    * The string is not modified if the operation fails. See NewExternal for
2020    * information on the lifetime of the resource.
2021    */
2022   bool MakeExternal(ExternalOneByteStringResource* resource);
2023 
2024   /**
2025    * Returns true if this string can be made external.
2026    */
2027   bool CanMakeExternal();
2028 
2029   /**
2030    * Converts an object to a UTF-8-encoded character array.  Useful if
2031    * you want to print the object.  If conversion to a string fails
2032    * (e.g. due to an exception in the toString() method of the object)
2033    * then the length() method returns 0 and the * operator returns
2034    * NULL.
2035    */
2036   class V8_EXPORT Utf8Value {
2037    public:
2038     explicit Utf8Value(Handle<v8::Value> obj);
2039     ~Utf8Value();
2040     char* operator*() { return str_; }
2041     const char* operator*() const { return str_; }
length()2042     int length() const { return length_; }
2043    private:
2044     char* str_;
2045     int length_;
2046 
2047     // Disallow copying and assigning.
2048     Utf8Value(const Utf8Value&);
2049     void operator=(const Utf8Value&);
2050   };
2051 
2052   /**
2053    * Converts an object to a two-byte string.
2054    * If conversion to a string fails (eg. due to an exception in the toString()
2055    * method of the object) then the length() method returns 0 and the * operator
2056    * returns NULL.
2057    */
2058   class V8_EXPORT Value {
2059    public:
2060     explicit Value(Handle<v8::Value> obj);
2061     ~Value();
2062     uint16_t* operator*() { return str_; }
2063     const uint16_t* operator*() const { return str_; }
length()2064     int length() const { return length_; }
2065    private:
2066     uint16_t* str_;
2067     int length_;
2068 
2069     // Disallow copying and assigning.
2070     Value(const Value&);
2071     void operator=(const Value&);
2072   };
2073 
2074  private:
2075   void VerifyExternalStringResourceBase(ExternalStringResourceBase* v,
2076                                         Encoding encoding) const;
2077   void VerifyExternalStringResource(ExternalStringResource* val) const;
2078   static void CheckCast(v8::Value* obj);
2079 };
2080 
2081 
2082 /**
2083  * A JavaScript symbol (ECMA-262 edition 6)
2084  *
2085  * This is an experimental feature. Use at your own risk.
2086  */
2087 class V8_EXPORT Symbol : public Name {
2088  public:
2089   // Returns the print name string of the symbol, or undefined if none.
2090   Local<Value> Name() const;
2091 
2092   // Create a symbol. If name is not empty, it will be used as the description.
2093   static Local<Symbol> New(
2094       Isolate *isolate, Local<String> name = Local<String>());
2095 
2096   // Access global symbol registry.
2097   // Note that symbols created this way are never collected, so
2098   // they should only be used for statically fixed properties.
2099   // Also, there is only one global name space for the names used as keys.
2100   // To minimize the potential for clashes, use qualified names as keys.
2101   static Local<Symbol> For(Isolate *isolate, Local<String> name);
2102 
2103   // Retrieve a global symbol. Similar to |For|, but using a separate
2104   // registry that is not accessible by (and cannot clash with) JavaScript code.
2105   static Local<Symbol> ForApi(Isolate *isolate, Local<String> name);
2106 
2107   // Well-known symbols
2108   static Local<Symbol> GetIterator(Isolate* isolate);
2109   static Local<Symbol> GetUnscopables(Isolate* isolate);
2110 
2111   V8_INLINE static Symbol* Cast(v8::Value* obj);
2112 
2113  private:
2114   Symbol();
2115   static void CheckCast(v8::Value* obj);
2116 };
2117 
2118 
2119 /**
2120  * A private symbol
2121  *
2122  * This is an experimental feature. Use at your own risk.
2123  */
2124 class V8_EXPORT Private : public Data {
2125  public:
2126   // Returns the print name string of the private symbol, or undefined if none.
2127   Local<Value> Name() const;
2128 
2129   // Create a private symbol. If name is not empty, it will be the description.
2130   static Local<Private> New(
2131       Isolate *isolate, Local<String> name = Local<String>());
2132 
2133   // Retrieve a global private symbol. If a symbol with this name has not
2134   // been retrieved in the same isolate before, it is created.
2135   // Note that private symbols created this way are never collected, so
2136   // they should only be used for statically fixed properties.
2137   // Also, there is only one global name space for the names used as keys.
2138   // To minimize the potential for clashes, use qualified names as keys,
2139   // e.g., "Class#property".
2140   static Local<Private> ForApi(Isolate *isolate, Local<String> name);
2141 
2142  private:
2143   Private();
2144 };
2145 
2146 
2147 /**
2148  * A JavaScript number value (ECMA-262, 4.3.20)
2149  */
2150 class V8_EXPORT Number : public Primitive {
2151  public:
2152   double Value() const;
2153   static Local<Number> New(Isolate* isolate, double value);
2154   V8_INLINE static Number* Cast(v8::Value* obj);
2155  private:
2156   Number();
2157   static void CheckCast(v8::Value* obj);
2158 };
2159 
2160 
2161 /**
2162  * A JavaScript value representing a signed integer.
2163  */
2164 class V8_EXPORT Integer : public Number {
2165  public:
2166   static Local<Integer> New(Isolate* isolate, int32_t value);
2167   static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value);
2168   int64_t Value() const;
2169   V8_INLINE static Integer* Cast(v8::Value* obj);
2170  private:
2171   Integer();
2172   static void CheckCast(v8::Value* obj);
2173 };
2174 
2175 
2176 /**
2177  * A JavaScript value representing a 32-bit signed integer.
2178  */
2179 class V8_EXPORT Int32 : public Integer {
2180  public:
2181   int32_t Value() const;
2182  private:
2183   Int32();
2184 };
2185 
2186 
2187 /**
2188  * A JavaScript value representing a 32-bit unsigned integer.
2189  */
2190 class V8_EXPORT Uint32 : public Integer {
2191  public:
2192   uint32_t Value() const;
2193  private:
2194   Uint32();
2195 };
2196 
2197 
2198 enum PropertyAttribute {
2199   None       = 0,
2200   ReadOnly   = 1 << 0,
2201   DontEnum   = 1 << 1,
2202   DontDelete = 1 << 2
2203 };
2204 
2205 enum ExternalArrayType {
2206   kExternalInt8Array = 1,
2207   kExternalUint8Array,
2208   kExternalInt16Array,
2209   kExternalUint16Array,
2210   kExternalInt32Array,
2211   kExternalUint32Array,
2212   kExternalFloat32Array,
2213   kExternalFloat64Array,
2214   kExternalUint8ClampedArray,
2215 
2216   // Legacy constant names
2217   kExternalByteArray = kExternalInt8Array,
2218   kExternalUnsignedByteArray = kExternalUint8Array,
2219   kExternalShortArray = kExternalInt16Array,
2220   kExternalUnsignedShortArray = kExternalUint16Array,
2221   kExternalIntArray = kExternalInt32Array,
2222   kExternalUnsignedIntArray = kExternalUint32Array,
2223   kExternalFloatArray = kExternalFloat32Array,
2224   kExternalDoubleArray = kExternalFloat64Array,
2225   kExternalPixelArray = kExternalUint8ClampedArray
2226 };
2227 
2228 /**
2229  * Accessor[Getter|Setter] are used as callback functions when
2230  * setting|getting a particular property. See Object and ObjectTemplate's
2231  * method SetAccessor.
2232  */
2233 typedef void (*AccessorGetterCallback)(
2234     Local<String> property,
2235     const PropertyCallbackInfo<Value>& info);
2236 typedef void (*AccessorNameGetterCallback)(
2237     Local<Name> property,
2238     const PropertyCallbackInfo<Value>& info);
2239 
2240 
2241 typedef void (*AccessorSetterCallback)(
2242     Local<String> property,
2243     Local<Value> value,
2244     const PropertyCallbackInfo<void>& info);
2245 typedef void (*AccessorNameSetterCallback)(
2246     Local<Name> property,
2247     Local<Value> value,
2248     const PropertyCallbackInfo<void>& info);
2249 
2250 
2251 /**
2252  * Access control specifications.
2253  *
2254  * Some accessors should be accessible across contexts.  These
2255  * accessors have an explicit access control parameter which specifies
2256  * the kind of cross-context access that should be allowed.
2257  *
2258  * TODO(dcarney): Remove PROHIBITS_OVERWRITING as it is now unused.
2259  */
2260 enum AccessControl {
2261   DEFAULT               = 0,
2262   ALL_CAN_READ          = 1,
2263   ALL_CAN_WRITE         = 1 << 1,
2264   PROHIBITS_OVERWRITING = 1 << 2
2265 };
2266 
2267 
2268 /**
2269  * A JavaScript object (ECMA-262, 4.3.3)
2270  */
2271 class V8_EXPORT Object : public Value {
2272  public:
2273   bool Set(Handle<Value> key, Handle<Value> value);
2274 
2275   bool Set(uint32_t index, Handle<Value> value);
2276 
2277   // Sets an own property on this object bypassing interceptors and
2278   // overriding accessors or read-only properties.
2279   //
2280   // Note that if the object has an interceptor the property will be set
2281   // locally, but since the interceptor takes precedence the local property
2282   // will only be returned if the interceptor doesn't return a value.
2283   //
2284   // Note also that this only works for named properties.
2285   bool ForceSet(Handle<Value> key,
2286                 Handle<Value> value,
2287                 PropertyAttribute attribs = None);
2288 
2289   Local<Value> Get(Handle<Value> key);
2290 
2291   Local<Value> Get(uint32_t index);
2292 
2293   /**
2294    * Gets the property attributes of a property which can be None or
2295    * any combination of ReadOnly, DontEnum and DontDelete. Returns
2296    * None when the property doesn't exist.
2297    */
2298   PropertyAttribute GetPropertyAttributes(Handle<Value> key);
2299 
2300   /**
2301    * Returns Object.getOwnPropertyDescriptor as per ES5 section 15.2.3.3.
2302    */
2303   Local<Value> GetOwnPropertyDescriptor(Local<String> key);
2304 
2305   bool Has(Handle<Value> key);
2306 
2307   bool Delete(Handle<Value> key);
2308 
2309   // Delete a property on this object bypassing interceptors and
2310   // ignoring dont-delete attributes.
2311   bool ForceDelete(Handle<Value> key);
2312 
2313   bool Has(uint32_t index);
2314 
2315   bool Delete(uint32_t index);
2316 
2317   bool SetAccessor(Handle<String> name,
2318                    AccessorGetterCallback getter,
2319                    AccessorSetterCallback setter = 0,
2320                    Handle<Value> data = Handle<Value>(),
2321                    AccessControl settings = DEFAULT,
2322                    PropertyAttribute attribute = None);
2323   bool SetAccessor(Handle<Name> name,
2324                    AccessorNameGetterCallback getter,
2325                    AccessorNameSetterCallback setter = 0,
2326                    Handle<Value> data = Handle<Value>(),
2327                    AccessControl settings = DEFAULT,
2328                    PropertyAttribute attribute = None);
2329 
2330   // This function is not yet stable and should not be used at this time.
2331   bool SetDeclaredAccessor(Local<Name> name,
2332                            Local<DeclaredAccessorDescriptor> descriptor,
2333                            PropertyAttribute attribute = None,
2334                            AccessControl settings = DEFAULT);
2335 
2336   void SetAccessorProperty(Local<Name> name,
2337                            Local<Function> getter,
2338                            Handle<Function> setter = Handle<Function>(),
2339                            PropertyAttribute attribute = None,
2340                            AccessControl settings = DEFAULT);
2341 
2342   /**
2343    * Functionality for private properties.
2344    * This is an experimental feature, use at your own risk.
2345    * Note: Private properties are inherited. Do not rely on this, since it may
2346    * change.
2347    */
2348   bool HasPrivate(Handle<Private> key);
2349   bool SetPrivate(Handle<Private> key, Handle<Value> value);
2350   bool DeletePrivate(Handle<Private> key);
2351   Local<Value> GetPrivate(Handle<Private> key);
2352 
2353   /**
2354    * Returns an array containing the names of the enumerable properties
2355    * of this object, including properties from prototype objects.  The
2356    * array returned by this method contains the same values as would
2357    * be enumerated by a for-in statement over this object.
2358    */
2359   Local<Array> GetPropertyNames();
2360 
2361   /**
2362    * This function has the same functionality as GetPropertyNames but
2363    * the returned array doesn't contain the names of properties from
2364    * prototype objects.
2365    */
2366   Local<Array> GetOwnPropertyNames();
2367 
2368   /**
2369    * Get the prototype object.  This does not skip objects marked to
2370    * be skipped by __proto__ and it does not consult the security
2371    * handler.
2372    */
2373   Local<Value> GetPrototype();
2374 
2375   /**
2376    * Set the prototype object.  This does not skip objects marked to
2377    * be skipped by __proto__ and it does not consult the security
2378    * handler.
2379    */
2380   bool SetPrototype(Handle<Value> prototype);
2381 
2382   /**
2383    * Finds an instance of the given function template in the prototype
2384    * chain.
2385    */
2386   Local<Object> FindInstanceInPrototypeChain(Handle<FunctionTemplate> tmpl);
2387 
2388   /**
2389    * Call builtin Object.prototype.toString on this object.
2390    * This is different from Value::ToString() that may call
2391    * user-defined toString function. This one does not.
2392    */
2393   Local<String> ObjectProtoToString();
2394 
2395   /**
2396    * Returns the name of the function invoked as a constructor for this object.
2397    */
2398   Local<String> GetConstructorName();
2399 
2400   /** Gets the number of internal fields for this Object. */
2401   int InternalFieldCount();
2402 
2403   /** Same as above, but works for Persistents */
InternalFieldCount(const PersistentBase<Object> & object)2404   V8_INLINE static int InternalFieldCount(
2405       const PersistentBase<Object>& object) {
2406     return object.val_->InternalFieldCount();
2407   }
2408 
2409   /** Gets the value from an internal field. */
2410   V8_INLINE Local<Value> GetInternalField(int index);
2411 
2412   /** Sets the value in an internal field. */
2413   void SetInternalField(int index, Handle<Value> value);
2414 
2415   /**
2416    * Gets a 2-byte-aligned native pointer from an internal field. This field
2417    * must have been set by SetAlignedPointerInInternalField, everything else
2418    * leads to undefined behavior.
2419    */
2420   V8_INLINE void* GetAlignedPointerFromInternalField(int index);
2421 
2422   /** Same as above, but works for Persistents */
GetAlignedPointerFromInternalField(const PersistentBase<Object> & object,int index)2423   V8_INLINE static void* GetAlignedPointerFromInternalField(
2424       const PersistentBase<Object>& object, int index) {
2425     return object.val_->GetAlignedPointerFromInternalField(index);
2426   }
2427 
2428   /**
2429    * Sets a 2-byte-aligned native pointer in an internal field. To retrieve such
2430    * a field, GetAlignedPointerFromInternalField must be used, everything else
2431    * leads to undefined behavior.
2432    */
2433   void SetAlignedPointerInInternalField(int index, void* value);
2434 
2435   // Testers for local properties.
2436   bool HasOwnProperty(Handle<String> key);
2437   bool HasRealNamedProperty(Handle<String> key);
2438   bool HasRealIndexedProperty(uint32_t index);
2439   bool HasRealNamedCallbackProperty(Handle<String> key);
2440 
2441   /**
2442    * If result.IsEmpty() no real property was located in the prototype chain.
2443    * This means interceptors in the prototype chain are not called.
2444    */
2445   Local<Value> GetRealNamedPropertyInPrototypeChain(Handle<String> key);
2446 
2447   /**
2448    * If result.IsEmpty() no real property was located on the object or
2449    * in the prototype chain.
2450    * This means interceptors in the prototype chain are not called.
2451    */
2452   Local<Value> GetRealNamedProperty(Handle<String> key);
2453 
2454   /** Tests for a named lookup interceptor.*/
2455   bool HasNamedLookupInterceptor();
2456 
2457   /** Tests for an index lookup interceptor.*/
2458   bool HasIndexedLookupInterceptor();
2459 
2460   /**
2461    * Turns on access check on the object if the object is an instance of
2462    * a template that has access check callbacks. If an object has no
2463    * access check info, the object cannot be accessed by anyone.
2464    */
2465   void TurnOnAccessCheck();
2466 
2467   /**
2468    * Returns the identity hash for this object. The current implementation
2469    * uses a hidden property on the object to store the identity hash.
2470    *
2471    * The return value will never be 0. Also, it is not guaranteed to be
2472    * unique.
2473    */
2474   int GetIdentityHash();
2475 
2476   /**
2477    * Access hidden properties on JavaScript objects. These properties are
2478    * hidden from the executing JavaScript and only accessible through the V8
2479    * C++ API. Hidden properties introduced by V8 internally (for example the
2480    * identity hash) are prefixed with "v8::".
2481    */
2482   bool SetHiddenValue(Handle<String> key, Handle<Value> value);
2483   Local<Value> GetHiddenValue(Handle<String> key);
2484   bool DeleteHiddenValue(Handle<String> key);
2485 
2486   /**
2487    * Returns true if this is an instance of an api function (one
2488    * created from a function created from a function template) and has
2489    * been modified since it was created.  Note that this method is
2490    * conservative and may return true for objects that haven't actually
2491    * been modified.
2492    */
2493   bool IsDirty();
2494 
2495   /**
2496    * Clone this object with a fast but shallow copy.  Values will point
2497    * to the same values as the original object.
2498    */
2499   Local<Object> Clone();
2500 
2501   /**
2502    * Returns the context in which the object was created.
2503    */
2504   Local<Context> CreationContext();
2505 
2506   /**
2507    * Set the backing store of the indexed properties to be managed by the
2508    * embedding layer. Access to the indexed properties will follow the rules
2509    * spelled out in CanvasPixelArray.
2510    * Note: The embedding program still owns the data and needs to ensure that
2511    *       the backing store is preserved while V8 has a reference.
2512    */
2513   void SetIndexedPropertiesToPixelData(uint8_t* data, int length);
2514   bool HasIndexedPropertiesInPixelData();
2515   uint8_t* GetIndexedPropertiesPixelData();
2516   int GetIndexedPropertiesPixelDataLength();
2517 
2518   /**
2519    * Set the backing store of the indexed properties to be managed by the
2520    * embedding layer. Access to the indexed properties will follow the rules
2521    * spelled out for the CanvasArray subtypes in the WebGL specification.
2522    * Note: The embedding program still owns the data and needs to ensure that
2523    *       the backing store is preserved while V8 has a reference.
2524    */
2525   void SetIndexedPropertiesToExternalArrayData(void* data,
2526                                                ExternalArrayType array_type,
2527                                                int number_of_elements);
2528   bool HasIndexedPropertiesInExternalArrayData();
2529   void* GetIndexedPropertiesExternalArrayData();
2530   ExternalArrayType GetIndexedPropertiesExternalArrayDataType();
2531   int GetIndexedPropertiesExternalArrayDataLength();
2532 
2533   /**
2534    * Checks whether a callback is set by the
2535    * ObjectTemplate::SetCallAsFunctionHandler method.
2536    * When an Object is callable this method returns true.
2537    */
2538   bool IsCallable();
2539 
2540   /**
2541    * Call an Object as a function if a callback is set by the
2542    * ObjectTemplate::SetCallAsFunctionHandler method.
2543    */
2544   Local<Value> CallAsFunction(Handle<Value> recv,
2545                               int argc,
2546                               Handle<Value> argv[]);
2547 
2548   /**
2549    * Call an Object as a constructor if a callback is set by the
2550    * ObjectTemplate::SetCallAsFunctionHandler method.
2551    * Note: This method behaves like the Function::NewInstance method.
2552    */
2553   Local<Value> CallAsConstructor(int argc, Handle<Value> argv[]);
2554 
2555   static Local<Object> New(Isolate* isolate);
2556 
2557   V8_INLINE static Object* Cast(Value* obj);
2558 
2559  private:
2560   Object();
2561   static void CheckCast(Value* obj);
2562   Local<Value> SlowGetInternalField(int index);
2563   void* SlowGetAlignedPointerFromInternalField(int index);
2564 };
2565 
2566 
2567 /**
2568  * An instance of the built-in array constructor (ECMA-262, 15.4.2).
2569  */
2570 class V8_EXPORT Array : public Object {
2571  public:
2572   uint32_t Length() const;
2573 
2574   /**
2575    * Clones an element at index |index|.  Returns an empty
2576    * handle if cloning fails (for any reason).
2577    */
2578   Local<Object> CloneElementAt(uint32_t index);
2579 
2580   /**
2581    * Creates a JavaScript array with the given length. If the length
2582    * is negative the returned array will have length 0.
2583    */
2584   static Local<Array> New(Isolate* isolate, int length = 0);
2585 
2586   V8_INLINE static Array* Cast(Value* obj);
2587  private:
2588   Array();
2589   static void CheckCast(Value* obj);
2590 };
2591 
2592 
2593 template<typename T>
2594 class ReturnValue {
2595  public:
ReturnValue(const ReturnValue<S> & that)2596   template <class S> V8_INLINE ReturnValue(const ReturnValue<S>& that)
2597       : value_(that.value_) {
2598     TYPE_CHECK(T, S);
2599   }
2600   // Handle setters
2601   template <typename S> V8_INLINE void Set(const Persistent<S>& handle);
2602   template <typename S> V8_INLINE void Set(const Handle<S> handle);
2603   // Fast primitive setters
2604   V8_INLINE void Set(bool value);
2605   V8_INLINE void Set(double i);
2606   V8_INLINE void Set(int32_t i);
2607   V8_INLINE void Set(uint32_t i);
2608   // Fast JS primitive setters
2609   V8_INLINE void SetNull();
2610   V8_INLINE void SetUndefined();
2611   V8_INLINE void SetEmptyString();
2612   // Convenience getter for Isolate
2613   V8_INLINE Isolate* GetIsolate();
2614 
2615   // Pointer setter: Uncompilable to prevent inadvertent misuse.
2616   template <typename S>
2617   V8_INLINE void Set(S* whatever);
2618 
2619  private:
2620   template<class F> friend class ReturnValue;
2621   template<class F> friend class FunctionCallbackInfo;
2622   template<class F> friend class PropertyCallbackInfo;
2623   template<class F, class G, class H> friend class PersistentValueMap;
SetInternal(internal::Object * value)2624   V8_INLINE void SetInternal(internal::Object* value) { *value_ = value; }
2625   V8_INLINE internal::Object* GetDefaultValue();
2626   V8_INLINE explicit ReturnValue(internal::Object** slot);
2627   internal::Object** value_;
2628 };
2629 
2630 
2631 /**
2632  * The argument information given to function call callbacks.  This
2633  * class provides access to information about the context of the call,
2634  * including the receiver, the number and values of arguments, and
2635  * the holder of the function.
2636  */
2637 template<typename T>
2638 class FunctionCallbackInfo {
2639  public:
2640   V8_INLINE int Length() const;
2641   V8_INLINE Local<Value> operator[](int i) const;
2642   V8_INLINE Local<Function> Callee() const;
2643   V8_INLINE Local<Object> This() const;
2644   V8_INLINE Local<Object> Holder() const;
2645   V8_INLINE bool IsConstructCall() const;
2646   V8_INLINE Local<Value> Data() const;
2647   V8_INLINE Isolate* GetIsolate() const;
2648   V8_INLINE ReturnValue<T> GetReturnValue() const;
2649   // This shouldn't be public, but the arm compiler needs it.
2650   static const int kArgsLength = 7;
2651 
2652  protected:
2653   friend class internal::FunctionCallbackArguments;
2654   friend class internal::CustomArguments<FunctionCallbackInfo>;
2655   static const int kHolderIndex = 0;
2656   static const int kIsolateIndex = 1;
2657   static const int kReturnValueDefaultValueIndex = 2;
2658   static const int kReturnValueIndex = 3;
2659   static const int kDataIndex = 4;
2660   static const int kCalleeIndex = 5;
2661   static const int kContextSaveIndex = 6;
2662 
2663   V8_INLINE FunctionCallbackInfo(internal::Object** implicit_args,
2664                    internal::Object** values,
2665                    int length,
2666                    bool is_construct_call);
2667   internal::Object** implicit_args_;
2668   internal::Object** values_;
2669   int length_;
2670   bool is_construct_call_;
2671 };
2672 
2673 
2674 /**
2675  * The information passed to a property callback about the context
2676  * of the property access.
2677  */
2678 template<typename T>
2679 class PropertyCallbackInfo {
2680  public:
2681   V8_INLINE Isolate* GetIsolate() const;
2682   V8_INLINE Local<Value> Data() const;
2683   V8_INLINE Local<Object> This() const;
2684   V8_INLINE Local<Object> Holder() const;
2685   V8_INLINE ReturnValue<T> GetReturnValue() const;
2686   // This shouldn't be public, but the arm compiler needs it.
2687   static const int kArgsLength = 6;
2688 
2689  protected:
2690   friend class MacroAssembler;
2691   friend class internal::PropertyCallbackArguments;
2692   friend class internal::CustomArguments<PropertyCallbackInfo>;
2693   static const int kHolderIndex = 0;
2694   static const int kIsolateIndex = 1;
2695   static const int kReturnValueDefaultValueIndex = 2;
2696   static const int kReturnValueIndex = 3;
2697   static const int kDataIndex = 4;
2698   static const int kThisIndex = 5;
2699 
PropertyCallbackInfo(internal::Object ** args)2700   V8_INLINE PropertyCallbackInfo(internal::Object** args) : args_(args) {}
2701   internal::Object** args_;
2702 };
2703 
2704 
2705 typedef void (*FunctionCallback)(const FunctionCallbackInfo<Value>& info);
2706 
2707 
2708 /**
2709  * A JavaScript function object (ECMA-262, 15.3).
2710  */
2711 class V8_EXPORT Function : public Object {
2712  public:
2713   /**
2714    * Create a function in the current execution context
2715    * for a given FunctionCallback.
2716    */
2717   static Local<Function> New(Isolate* isolate,
2718                              FunctionCallback callback,
2719                              Local<Value> data = Local<Value>(),
2720                              int length = 0);
2721 
2722   Local<Object> NewInstance() const;
2723   Local<Object> NewInstance(int argc, Handle<Value> argv[]) const;
2724   Local<Value> Call(Handle<Value> recv, int argc, Handle<Value> argv[]);
2725   void SetName(Handle<String> name);
2726   Handle<Value> GetName() const;
2727 
2728   /**
2729    * Name inferred from variable or property assignment of this function.
2730    * Used to facilitate debugging and profiling of JavaScript code written
2731    * in an OO style, where many functions are anonymous but are assigned
2732    * to object properties.
2733    */
2734   Handle<Value> GetInferredName() const;
2735 
2736   /**
2737    * User-defined name assigned to the "displayName" property of this function.
2738    * Used to facilitate debugging and profiling of JavaScript code.
2739    */
2740   Handle<Value> GetDisplayName() const;
2741 
2742   /**
2743    * Returns zero based line number of function body and
2744    * kLineOffsetNotFound if no information available.
2745    */
2746   int GetScriptLineNumber() const;
2747   /**
2748    * Returns zero based column number of function body and
2749    * kLineOffsetNotFound if no information available.
2750    */
2751   int GetScriptColumnNumber() const;
2752 
2753   /**
2754    * Tells whether this function is builtin.
2755    */
2756   bool IsBuiltin() const;
2757 
2758   /**
2759    * Returns scriptId.
2760    */
2761   int ScriptId() const;
2762 
2763   /**
2764    * Returns the original function if this function is bound, else returns
2765    * v8::Undefined.
2766    */
2767   Local<Value> GetBoundFunction() const;
2768 
2769   ScriptOrigin GetScriptOrigin() const;
2770   V8_INLINE static Function* Cast(Value* obj);
2771   static const int kLineOffsetNotFound;
2772 
2773  private:
2774   Function();
2775   static void CheckCast(Value* obj);
2776 };
2777 
2778 
2779 /**
2780  * An instance of the built-in Promise constructor (ES6 draft).
2781  * This API is experimental. Only works with --harmony flag.
2782  */
2783 class V8_EXPORT Promise : public Object {
2784  public:
2785   class V8_EXPORT Resolver : public Object {
2786    public:
2787     /**
2788      * Create a new resolver, along with an associated promise in pending state.
2789      */
2790     static Local<Resolver> New(Isolate* isolate);
2791 
2792     /**
2793      * Extract the associated promise.
2794      */
2795     Local<Promise> GetPromise();
2796 
2797     /**
2798      * Resolve/reject the associated promise with a given value.
2799      * Ignored if the promise is no longer pending.
2800      */
2801     void Resolve(Handle<Value> value);
2802     void Reject(Handle<Value> value);
2803 
2804     V8_INLINE static Resolver* Cast(Value* obj);
2805 
2806    private:
2807     Resolver();
2808     static void CheckCast(Value* obj);
2809   };
2810 
2811   /**
2812    * Register a resolution/rejection handler with a promise.
2813    * The handler is given the respective resolution/rejection value as
2814    * an argument. If the promise is already resolved/rejected, the handler is
2815    * invoked at the end of turn.
2816    */
2817   Local<Promise> Chain(Handle<Function> handler);
2818   Local<Promise> Catch(Handle<Function> handler);
2819   Local<Promise> Then(Handle<Function> handler);
2820 
2821   V8_INLINE static Promise* Cast(Value* obj);
2822 
2823  private:
2824   Promise();
2825   static void CheckCast(Value* obj);
2826 };
2827 
2828 
2829 #ifndef V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT
2830 // The number of required internal fields can be defined by embedder.
2831 #define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 2
2832 #endif
2833 
2834 /**
2835  * An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5).
2836  * This API is experimental and may change significantly.
2837  */
2838 class V8_EXPORT ArrayBuffer : public Object {
2839  public:
2840   /**
2841    * Allocator that V8 uses to allocate |ArrayBuffer|'s memory.
2842    * The allocator is a global V8 setting. It should be set with
2843    * V8::SetArrayBufferAllocator prior to creation of a first ArrayBuffer.
2844    *
2845    * This API is experimental and may change significantly.
2846    */
2847   class V8_EXPORT Allocator { // NOLINT
2848    public:
~Allocator()2849     virtual ~Allocator() {}
2850 
2851     /**
2852      * Allocate |length| bytes. Return NULL if allocation is not successful.
2853      * Memory should be initialized to zeroes.
2854      */
2855     virtual void* Allocate(size_t length) = 0;
2856 
2857     /**
2858      * Allocate |length| bytes. Return NULL if allocation is not successful.
2859      * Memory does not have to be initialized.
2860      */
2861     virtual void* AllocateUninitialized(size_t length) = 0;
2862     /**
2863      * Free the memory block of size |length|, pointed to by |data|.
2864      * That memory is guaranteed to be previously allocated by |Allocate|.
2865      */
2866     virtual void Free(void* data, size_t length) = 0;
2867   };
2868 
2869   /**
2870    * The contents of an |ArrayBuffer|. Externalization of |ArrayBuffer|
2871    * returns an instance of this class, populated, with a pointer to data
2872    * and byte length.
2873    *
2874    * The Data pointer of ArrayBuffer::Contents is always allocated with
2875    * Allocator::Allocate that is set with V8::SetArrayBufferAllocator.
2876    *
2877    * This API is experimental and may change significantly.
2878    */
2879   class V8_EXPORT Contents { // NOLINT
2880    public:
Contents()2881     Contents() : data_(NULL), byte_length_(0) {}
2882 
Data()2883     void* Data() const { return data_; }
ByteLength()2884     size_t ByteLength() const { return byte_length_; }
2885 
2886    private:
2887     void* data_;
2888     size_t byte_length_;
2889 
2890     friend class ArrayBuffer;
2891   };
2892 
2893 
2894   /**
2895    * Data length in bytes.
2896    */
2897   size_t ByteLength() const;
2898 
2899   /**
2900    * Create a new ArrayBuffer. Allocate |byte_length| bytes.
2901    * Allocated memory will be owned by a created ArrayBuffer and
2902    * will be deallocated when it is garbage-collected,
2903    * unless the object is externalized.
2904    */
2905   static Local<ArrayBuffer> New(Isolate* isolate, size_t byte_length);
2906 
2907   /**
2908    * Create a new ArrayBuffer over an existing memory block.
2909    * The created array buffer is immediately in externalized state.
2910    * The memory block will not be reclaimed when a created ArrayBuffer
2911    * is garbage-collected.
2912    */
2913   static Local<ArrayBuffer> New(Isolate* isolate, void* data,
2914                                 size_t byte_length);
2915 
2916   /**
2917    * Returns true if ArrayBuffer is extrenalized, that is, does not
2918    * own its memory block.
2919    */
2920   bool IsExternal() const;
2921 
2922   /**
2923    * Neuters this ArrayBuffer and all its views (typed arrays).
2924    * Neutering sets the byte length of the buffer and all typed arrays to zero,
2925    * preventing JavaScript from ever accessing underlying backing store.
2926    * ArrayBuffer should have been externalized.
2927    */
2928   void Neuter();
2929 
2930   /**
2931    * Make this ArrayBuffer external. The pointer to underlying memory block
2932    * and byte length are returned as |Contents| structure. After ArrayBuffer
2933    * had been etxrenalized, it does no longer owns the memory block. The caller
2934    * should take steps to free memory when it is no longer needed.
2935    *
2936    * The memory block is guaranteed to be allocated with |Allocator::Allocate|
2937    * that has been set with V8::SetArrayBufferAllocator.
2938    */
2939   Contents Externalize();
2940 
2941   V8_INLINE static ArrayBuffer* Cast(Value* obj);
2942 
2943   static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
2944 
2945  private:
2946   ArrayBuffer();
2947   static void CheckCast(Value* obj);
2948 };
2949 
2950 
2951 #ifndef V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT
2952 // The number of required internal fields can be defined by embedder.
2953 #define V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT 2
2954 #endif
2955 
2956 
2957 /**
2958  * A base class for an instance of one of "views" over ArrayBuffer,
2959  * including TypedArrays and DataView (ES6 draft 15.13).
2960  *
2961  * This API is experimental and may change significantly.
2962  */
2963 class V8_EXPORT ArrayBufferView : public Object {
2964  public:
2965   /**
2966    * Returns underlying ArrayBuffer.
2967    */
2968   Local<ArrayBuffer> Buffer();
2969   /**
2970    * Byte offset in |Buffer|.
2971    */
2972   size_t ByteOffset();
2973   /**
2974    * Size of a view in bytes.
2975    */
2976   size_t ByteLength();
2977 
2978   V8_INLINE static ArrayBufferView* Cast(Value* obj);
2979 
2980   static const int kInternalFieldCount =
2981       V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT;
2982 
2983  private:
2984   ArrayBufferView();
2985   static void CheckCast(Value* obj);
2986 };
2987 
2988 
2989 /**
2990  * A base class for an instance of TypedArray series of constructors
2991  * (ES6 draft 15.13.6).
2992  * This API is experimental and may change significantly.
2993  */
2994 class V8_EXPORT TypedArray : public ArrayBufferView {
2995  public:
2996   /**
2997    * Number of elements in this typed array
2998    * (e.g. for Int16Array, |ByteLength|/2).
2999    */
3000   size_t Length();
3001 
3002   V8_INLINE static TypedArray* Cast(Value* obj);
3003 
3004  private:
3005   TypedArray();
3006   static void CheckCast(Value* obj);
3007 };
3008 
3009 
3010 /**
3011  * An instance of Uint8Array constructor (ES6 draft 15.13.6).
3012  * This API is experimental and may change significantly.
3013  */
3014 class V8_EXPORT Uint8Array : public TypedArray {
3015  public:
3016   static Local<Uint8Array> New(Handle<ArrayBuffer> array_buffer,
3017                                size_t byte_offset, size_t length);
3018   V8_INLINE static Uint8Array* Cast(Value* obj);
3019 
3020  private:
3021   Uint8Array();
3022   static void CheckCast(Value* obj);
3023 };
3024 
3025 
3026 /**
3027  * An instance of Uint8ClampedArray constructor (ES6 draft 15.13.6).
3028  * This API is experimental and may change significantly.
3029  */
3030 class V8_EXPORT Uint8ClampedArray : public TypedArray {
3031  public:
3032   static Local<Uint8ClampedArray> New(Handle<ArrayBuffer> array_buffer,
3033                                size_t byte_offset, size_t length);
3034   V8_INLINE static Uint8ClampedArray* Cast(Value* obj);
3035 
3036  private:
3037   Uint8ClampedArray();
3038   static void CheckCast(Value* obj);
3039 };
3040 
3041 /**
3042  * An instance of Int8Array constructor (ES6 draft 15.13.6).
3043  * This API is experimental and may change significantly.
3044  */
3045 class V8_EXPORT Int8Array : public TypedArray {
3046  public:
3047   static Local<Int8Array> New(Handle<ArrayBuffer> array_buffer,
3048                                size_t byte_offset, size_t length);
3049   V8_INLINE static Int8Array* Cast(Value* obj);
3050 
3051  private:
3052   Int8Array();
3053   static void CheckCast(Value* obj);
3054 };
3055 
3056 
3057 /**
3058  * An instance of Uint16Array constructor (ES6 draft 15.13.6).
3059  * This API is experimental and may change significantly.
3060  */
3061 class V8_EXPORT Uint16Array : public TypedArray {
3062  public:
3063   static Local<Uint16Array> New(Handle<ArrayBuffer> array_buffer,
3064                                size_t byte_offset, size_t length);
3065   V8_INLINE static Uint16Array* Cast(Value* obj);
3066 
3067  private:
3068   Uint16Array();
3069   static void CheckCast(Value* obj);
3070 };
3071 
3072 
3073 /**
3074  * An instance of Int16Array constructor (ES6 draft 15.13.6).
3075  * This API is experimental and may change significantly.
3076  */
3077 class V8_EXPORT Int16Array : public TypedArray {
3078  public:
3079   static Local<Int16Array> New(Handle<ArrayBuffer> array_buffer,
3080                                size_t byte_offset, size_t length);
3081   V8_INLINE static Int16Array* Cast(Value* obj);
3082 
3083  private:
3084   Int16Array();
3085   static void CheckCast(Value* obj);
3086 };
3087 
3088 
3089 /**
3090  * An instance of Uint32Array constructor (ES6 draft 15.13.6).
3091  * This API is experimental and may change significantly.
3092  */
3093 class V8_EXPORT Uint32Array : public TypedArray {
3094  public:
3095   static Local<Uint32Array> New(Handle<ArrayBuffer> array_buffer,
3096                                size_t byte_offset, size_t length);
3097   V8_INLINE static Uint32Array* Cast(Value* obj);
3098 
3099  private:
3100   Uint32Array();
3101   static void CheckCast(Value* obj);
3102 };
3103 
3104 
3105 /**
3106  * An instance of Int32Array constructor (ES6 draft 15.13.6).
3107  * This API is experimental and may change significantly.
3108  */
3109 class V8_EXPORT Int32Array : public TypedArray {
3110  public:
3111   static Local<Int32Array> New(Handle<ArrayBuffer> array_buffer,
3112                                size_t byte_offset, size_t length);
3113   V8_INLINE static Int32Array* Cast(Value* obj);
3114 
3115  private:
3116   Int32Array();
3117   static void CheckCast(Value* obj);
3118 };
3119 
3120 
3121 /**
3122  * An instance of Float32Array constructor (ES6 draft 15.13.6).
3123  * This API is experimental and may change significantly.
3124  */
3125 class V8_EXPORT Float32Array : public TypedArray {
3126  public:
3127   static Local<Float32Array> New(Handle<ArrayBuffer> array_buffer,
3128                                size_t byte_offset, size_t length);
3129   V8_INLINE static Float32Array* Cast(Value* obj);
3130 
3131  private:
3132   Float32Array();
3133   static void CheckCast(Value* obj);
3134 };
3135 
3136 
3137 /**
3138  * An instance of Float64Array constructor (ES6 draft 15.13.6).
3139  * This API is experimental and may change significantly.
3140  */
3141 class V8_EXPORT Float64Array : public TypedArray {
3142  public:
3143   static Local<Float64Array> New(Handle<ArrayBuffer> array_buffer,
3144                                size_t byte_offset, size_t length);
3145   V8_INLINE static Float64Array* Cast(Value* obj);
3146 
3147  private:
3148   Float64Array();
3149   static void CheckCast(Value* obj);
3150 };
3151 
3152 
3153 /**
3154  * An instance of DataView constructor (ES6 draft 15.13.7).
3155  * This API is experimental and may change significantly.
3156  */
3157 class V8_EXPORT DataView : public ArrayBufferView {
3158  public:
3159   static Local<DataView> New(Handle<ArrayBuffer> array_buffer,
3160                              size_t byte_offset, size_t length);
3161   V8_INLINE static DataView* Cast(Value* obj);
3162 
3163  private:
3164   DataView();
3165   static void CheckCast(Value* obj);
3166 };
3167 
3168 
3169 /**
3170  * An instance of the built-in Date constructor (ECMA-262, 15.9).
3171  */
3172 class V8_EXPORT Date : public Object {
3173  public:
3174   static Local<Value> New(Isolate* isolate, double time);
3175 
3176   /**
3177    * A specialization of Value::NumberValue that is more efficient
3178    * because we know the structure of this object.
3179    */
3180   double ValueOf() const;
3181 
3182   V8_INLINE static Date* Cast(v8::Value* obj);
3183 
3184   /**
3185    * Notification that the embedder has changed the time zone,
3186    * daylight savings time, or other date / time configuration
3187    * parameters.  V8 keeps a cache of various values used for
3188    * date / time computation.  This notification will reset
3189    * those cached values for the current context so that date /
3190    * time configuration changes would be reflected in the Date
3191    * object.
3192    *
3193    * This API should not be called more than needed as it will
3194    * negatively impact the performance of date operations.
3195    */
3196   static void DateTimeConfigurationChangeNotification(Isolate* isolate);
3197 
3198  private:
3199   static void CheckCast(v8::Value* obj);
3200 };
3201 
3202 
3203 /**
3204  * A Number object (ECMA-262, 4.3.21).
3205  */
3206 class V8_EXPORT NumberObject : public Object {
3207  public:
3208   static Local<Value> New(Isolate* isolate, double value);
3209 
3210   double ValueOf() const;
3211 
3212   V8_INLINE static NumberObject* Cast(v8::Value* obj);
3213 
3214  private:
3215   static void CheckCast(v8::Value* obj);
3216 };
3217 
3218 
3219 /**
3220  * A Boolean object (ECMA-262, 4.3.15).
3221  */
3222 class V8_EXPORT BooleanObject : public Object {
3223  public:
3224   static Local<Value> New(bool value);
3225 
3226   bool ValueOf() const;
3227 
3228   V8_INLINE static BooleanObject* Cast(v8::Value* obj);
3229 
3230  private:
3231   static void CheckCast(v8::Value* obj);
3232 };
3233 
3234 
3235 /**
3236  * A String object (ECMA-262, 4.3.18).
3237  */
3238 class V8_EXPORT StringObject : public Object {
3239  public:
3240   static Local<Value> New(Handle<String> value);
3241 
3242   Local<String> ValueOf() const;
3243 
3244   V8_INLINE static StringObject* Cast(v8::Value* obj);
3245 
3246  private:
3247   static void CheckCast(v8::Value* obj);
3248 };
3249 
3250 
3251 /**
3252  * A Symbol object (ECMA-262 edition 6).
3253  *
3254  * This is an experimental feature. Use at your own risk.
3255  */
3256 class V8_EXPORT SymbolObject : public Object {
3257  public:
3258   static Local<Value> New(Isolate* isolate, Handle<Symbol> value);
3259 
3260   Local<Symbol> ValueOf() const;
3261 
3262   V8_INLINE static SymbolObject* Cast(v8::Value* obj);
3263 
3264  private:
3265   static void CheckCast(v8::Value* obj);
3266 };
3267 
3268 
3269 /**
3270  * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
3271  */
3272 class V8_EXPORT RegExp : public Object {
3273  public:
3274   /**
3275    * Regular expression flag bits. They can be or'ed to enable a set
3276    * of flags.
3277    */
3278   enum Flags {
3279     kNone = 0,
3280     kGlobal = 1,
3281     kIgnoreCase = 2,
3282     kMultiline = 4
3283   };
3284 
3285   /**
3286    * Creates a regular expression from the given pattern string and
3287    * the flags bit field. May throw a JavaScript exception as
3288    * described in ECMA-262, 15.10.4.1.
3289    *
3290    * For example,
3291    *   RegExp::New(v8::String::New("foo"),
3292    *               static_cast<RegExp::Flags>(kGlobal | kMultiline))
3293    * is equivalent to evaluating "/foo/gm".
3294    */
3295   static Local<RegExp> New(Handle<String> pattern, Flags flags);
3296 
3297   /**
3298    * Returns the value of the source property: a string representing
3299    * the regular expression.
3300    */
3301   Local<String> GetSource() const;
3302 
3303   /**
3304    * Returns the flags bit field.
3305    */
3306   Flags GetFlags() const;
3307 
3308   V8_INLINE static RegExp* Cast(v8::Value* obj);
3309 
3310  private:
3311   static void CheckCast(v8::Value* obj);
3312 };
3313 
3314 
3315 /**
3316  * A JavaScript value that wraps a C++ void*. This type of value is mainly used
3317  * to associate C++ data structures with JavaScript objects.
3318  */
3319 class V8_EXPORT External : public Value {
3320  public:
3321   static Local<External> New(Isolate* isolate, void* value);
3322   V8_INLINE static External* Cast(Value* obj);
3323   void* Value() const;
3324  private:
3325   static void CheckCast(v8::Value* obj);
3326 };
3327 
3328 
3329 // --- Templates ---
3330 
3331 
3332 /**
3333  * The superclass of object and function templates.
3334  */
3335 class V8_EXPORT Template : public Data {
3336  public:
3337   /** Adds a property to each instance created by this template.*/
3338   void Set(Handle<Name> name, Handle<Data> value,
3339            PropertyAttribute attributes = None);
3340   V8_INLINE void Set(Isolate* isolate, const char* name, Handle<Data> value);
3341 
3342   void SetAccessorProperty(
3343      Local<Name> name,
3344      Local<FunctionTemplate> getter = Local<FunctionTemplate>(),
3345      Local<FunctionTemplate> setter = Local<FunctionTemplate>(),
3346      PropertyAttribute attribute = None,
3347      AccessControl settings = DEFAULT);
3348 
3349   /**
3350    * Whenever the property with the given name is accessed on objects
3351    * created from this Template the getter and setter callbacks
3352    * are called instead of getting and setting the property directly
3353    * on the JavaScript object.
3354    *
3355    * \param name The name of the property for which an accessor is added.
3356    * \param getter The callback to invoke when getting the property.
3357    * \param setter The callback to invoke when setting the property.
3358    * \param data A piece of data that will be passed to the getter and setter
3359    *   callbacks whenever they are invoked.
3360    * \param settings Access control settings for the accessor. This is a bit
3361    *   field consisting of one of more of
3362    *   DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
3363    *   The default is to not allow cross-context access.
3364    *   ALL_CAN_READ means that all cross-context reads are allowed.
3365    *   ALL_CAN_WRITE means that all cross-context writes are allowed.
3366    *   The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
3367    *   cross-context access.
3368    * \param attribute The attributes of the property for which an accessor
3369    *   is added.
3370    * \param signature The signature describes valid receivers for the accessor
3371    *   and is used to perform implicit instance checks against them. If the
3372    *   receiver is incompatible (i.e. is not an instance of the constructor as
3373    *   defined by FunctionTemplate::HasInstance()), an implicit TypeError is
3374    *   thrown and no callback is invoked.
3375    */
3376   void SetNativeDataProperty(Local<String> name,
3377                              AccessorGetterCallback getter,
3378                              AccessorSetterCallback setter = 0,
3379                              // TODO(dcarney): gcc can't handle Local below
3380                              Handle<Value> data = Handle<Value>(),
3381                              PropertyAttribute attribute = None,
3382                              Local<AccessorSignature> signature =
3383                                  Local<AccessorSignature>(),
3384                              AccessControl settings = DEFAULT);
3385   void SetNativeDataProperty(Local<Name> name,
3386                              AccessorNameGetterCallback getter,
3387                              AccessorNameSetterCallback setter = 0,
3388                              // TODO(dcarney): gcc can't handle Local below
3389                              Handle<Value> data = Handle<Value>(),
3390                              PropertyAttribute attribute = None,
3391                              Local<AccessorSignature> signature =
3392                                  Local<AccessorSignature>(),
3393                              AccessControl settings = DEFAULT);
3394 
3395   // This function is not yet stable and should not be used at this time.
3396   bool SetDeclaredAccessor(Local<Name> name,
3397                            Local<DeclaredAccessorDescriptor> descriptor,
3398                            PropertyAttribute attribute = None,
3399                            Local<AccessorSignature> signature =
3400                                Local<AccessorSignature>(),
3401                            AccessControl settings = DEFAULT);
3402 
3403  private:
3404   Template();
3405 
3406   friend class ObjectTemplate;
3407   friend class FunctionTemplate;
3408 };
3409 
3410 
3411 /**
3412  * NamedProperty[Getter|Setter] are used as interceptors on object.
3413  * See ObjectTemplate::SetNamedPropertyHandler.
3414  */
3415 typedef void (*NamedPropertyGetterCallback)(
3416     Local<String> property,
3417     const PropertyCallbackInfo<Value>& info);
3418 
3419 
3420 /**
3421  * Returns the value if the setter intercepts the request.
3422  * Otherwise, returns an empty handle.
3423  */
3424 typedef void (*NamedPropertySetterCallback)(
3425     Local<String> property,
3426     Local<Value> value,
3427     const PropertyCallbackInfo<Value>& info);
3428 
3429 
3430 /**
3431  * Returns a non-empty handle if the interceptor intercepts the request.
3432  * The result is an integer encoding property attributes (like v8::None,
3433  * v8::DontEnum, etc.)
3434  */
3435 typedef void (*NamedPropertyQueryCallback)(
3436     Local<String> property,
3437     const PropertyCallbackInfo<Integer>& info);
3438 
3439 
3440 /**
3441  * Returns a non-empty handle if the deleter intercepts the request.
3442  * The return value is true if the property could be deleted and false
3443  * otherwise.
3444  */
3445 typedef void (*NamedPropertyDeleterCallback)(
3446     Local<String> property,
3447     const PropertyCallbackInfo<Boolean>& info);
3448 
3449 
3450 /**
3451  * Returns an array containing the names of the properties the named
3452  * property getter intercepts.
3453  */
3454 typedef void (*NamedPropertyEnumeratorCallback)(
3455     const PropertyCallbackInfo<Array>& info);
3456 
3457 
3458 /**
3459  * Returns the value of the property if the getter intercepts the
3460  * request.  Otherwise, returns an empty handle.
3461  */
3462 typedef void (*IndexedPropertyGetterCallback)(
3463     uint32_t index,
3464     const PropertyCallbackInfo<Value>& info);
3465 
3466 
3467 /**
3468  * Returns the value if the setter intercepts the request.
3469  * Otherwise, returns an empty handle.
3470  */
3471 typedef void (*IndexedPropertySetterCallback)(
3472     uint32_t index,
3473     Local<Value> value,
3474     const PropertyCallbackInfo<Value>& info);
3475 
3476 
3477 /**
3478  * Returns a non-empty handle if the interceptor intercepts the request.
3479  * The result is an integer encoding property attributes.
3480  */
3481 typedef void (*IndexedPropertyQueryCallback)(
3482     uint32_t index,
3483     const PropertyCallbackInfo<Integer>& info);
3484 
3485 
3486 /**
3487  * Returns a non-empty handle if the deleter intercepts the request.
3488  * The return value is true if the property could be deleted and false
3489  * otherwise.
3490  */
3491 typedef void (*IndexedPropertyDeleterCallback)(
3492     uint32_t index,
3493     const PropertyCallbackInfo<Boolean>& info);
3494 
3495 
3496 /**
3497  * Returns an array containing the indices of the properties the
3498  * indexed property getter intercepts.
3499  */
3500 typedef void (*IndexedPropertyEnumeratorCallback)(
3501     const PropertyCallbackInfo<Array>& info);
3502 
3503 
3504 /**
3505  * Access type specification.
3506  */
3507 enum AccessType {
3508   ACCESS_GET,
3509   ACCESS_SET,
3510   ACCESS_HAS,
3511   ACCESS_DELETE,
3512   ACCESS_KEYS
3513 };
3514 
3515 
3516 /**
3517  * Returns true if cross-context access should be allowed to the named
3518  * property with the given key on the host object.
3519  */
3520 typedef bool (*NamedSecurityCallback)(Local<Object> host,
3521                                       Local<Value> key,
3522                                       AccessType type,
3523                                       Local<Value> data);
3524 
3525 
3526 /**
3527  * Returns true if cross-context access should be allowed to the indexed
3528  * property with the given index on the host object.
3529  */
3530 typedef bool (*IndexedSecurityCallback)(Local<Object> host,
3531                                         uint32_t index,
3532                                         AccessType type,
3533                                         Local<Value> data);
3534 
3535 
3536 /**
3537  * A FunctionTemplate is used to create functions at runtime. There
3538  * can only be one function created from a FunctionTemplate in a
3539  * context.  The lifetime of the created function is equal to the
3540  * lifetime of the context.  So in case the embedder needs to create
3541  * temporary functions that can be collected using Scripts is
3542  * preferred.
3543  *
3544  * A FunctionTemplate can have properties, these properties are added to the
3545  * function object when it is created.
3546  *
3547  * A FunctionTemplate has a corresponding instance template which is
3548  * used to create object instances when the function is used as a
3549  * constructor. Properties added to the instance template are added to
3550  * each object instance.
3551  *
3552  * A FunctionTemplate can have a prototype template. The prototype template
3553  * is used to create the prototype object of the function.
3554  *
3555  * The following example shows how to use a FunctionTemplate:
3556  *
3557  * \code
3558  *    v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
3559  *    t->Set("func_property", v8::Number::New(1));
3560  *
3561  *    v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
3562  *    proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
3563  *    proto_t->Set("proto_const", v8::Number::New(2));
3564  *
3565  *    v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
3566  *    instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
3567  *    instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
3568  *    instance_t->Set("instance_property", Number::New(3));
3569  *
3570  *    v8::Local<v8::Function> function = t->GetFunction();
3571  *    v8::Local<v8::Object> instance = function->NewInstance();
3572  * \endcode
3573  *
3574  * Let's use "function" as the JS variable name of the function object
3575  * and "instance" for the instance object created above.  The function
3576  * and the instance will have the following properties:
3577  *
3578  * \code
3579  *   func_property in function == true;
3580  *   function.func_property == 1;
3581  *
3582  *   function.prototype.proto_method() invokes 'InvokeCallback'
3583  *   function.prototype.proto_const == 2;
3584  *
3585  *   instance instanceof function == true;
3586  *   instance.instance_accessor calls 'InstanceAccessorCallback'
3587  *   instance.instance_property == 3;
3588  * \endcode
3589  *
3590  * A FunctionTemplate can inherit from another one by calling the
3591  * FunctionTemplate::Inherit method.  The following graph illustrates
3592  * the semantics of inheritance:
3593  *
3594  * \code
3595  *   FunctionTemplate Parent  -> Parent() . prototype -> { }
3596  *     ^                                                  ^
3597  *     | Inherit(Parent)                                  | .__proto__
3598  *     |                                                  |
3599  *   FunctionTemplate Child   -> Child()  . prototype -> { }
3600  * \endcode
3601  *
3602  * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
3603  * object of the Child() function has __proto__ pointing to the
3604  * Parent() function's prototype object. An instance of the Child
3605  * function has all properties on Parent's instance templates.
3606  *
3607  * Let Parent be the FunctionTemplate initialized in the previous
3608  * section and create a Child FunctionTemplate by:
3609  *
3610  * \code
3611  *   Local<FunctionTemplate> parent = t;
3612  *   Local<FunctionTemplate> child = FunctionTemplate::New();
3613  *   child->Inherit(parent);
3614  *
3615  *   Local<Function> child_function = child->GetFunction();
3616  *   Local<Object> child_instance = child_function->NewInstance();
3617  * \endcode
3618  *
3619  * The Child function and Child instance will have the following
3620  * properties:
3621  *
3622  * \code
3623  *   child_func.prototype.__proto__ == function.prototype;
3624  *   child_instance.instance_accessor calls 'InstanceAccessorCallback'
3625  *   child_instance.instance_property == 3;
3626  * \endcode
3627  */
3628 class V8_EXPORT FunctionTemplate : public Template {
3629  public:
3630   /** Creates a function template.*/
3631   static Local<FunctionTemplate> New(
3632       Isolate* isolate,
3633       FunctionCallback callback = 0,
3634       Handle<Value> data = Handle<Value>(),
3635       Handle<Signature> signature = Handle<Signature>(),
3636       int length = 0);
3637 
3638   /** Returns the unique function instance in the current execution context.*/
3639   Local<Function> GetFunction();
3640 
3641   /**
3642    * Set the call-handler callback for a FunctionTemplate.  This
3643    * callback is called whenever the function created from this
3644    * FunctionTemplate is called.
3645    */
3646   void SetCallHandler(FunctionCallback callback,
3647                       Handle<Value> data = Handle<Value>());
3648 
3649   /** Set the predefined length property for the FunctionTemplate. */
3650   void SetLength(int length);
3651 
3652   /** Get the InstanceTemplate. */
3653   Local<ObjectTemplate> InstanceTemplate();
3654 
3655   /** Causes the function template to inherit from a parent function template.*/
3656   void Inherit(Handle<FunctionTemplate> parent);
3657 
3658   /**
3659    * A PrototypeTemplate is the template used to create the prototype object
3660    * of the function created by this template.
3661    */
3662   Local<ObjectTemplate> PrototypeTemplate();
3663 
3664   /**
3665    * Set the class name of the FunctionTemplate.  This is used for
3666    * printing objects created with the function created from the
3667    * FunctionTemplate as its constructor.
3668    */
3669   void SetClassName(Handle<String> name);
3670 
3671   /**
3672    * Determines whether the __proto__ accessor ignores instances of
3673    * the function template.  If instances of the function template are
3674    * ignored, __proto__ skips all instances and instead returns the
3675    * next object in the prototype chain.
3676    *
3677    * Call with a value of true to make the __proto__ accessor ignore
3678    * instances of the function template.  Call with a value of false
3679    * to make the __proto__ accessor not ignore instances of the
3680    * function template.  By default, instances of a function template
3681    * are not ignored.
3682    */
3683   void SetHiddenPrototype(bool value);
3684 
3685   /**
3686    * Sets the ReadOnly flag in the attributes of the 'prototype' property
3687    * of functions created from this FunctionTemplate to true.
3688    */
3689   void ReadOnlyPrototype();
3690 
3691   /**
3692    * Removes the prototype property from functions created from this
3693    * FunctionTemplate.
3694    */
3695   void RemovePrototype();
3696 
3697   /**
3698    * Returns true if the given object is an instance of this function
3699    * template.
3700    */
3701   bool HasInstance(Handle<Value> object);
3702 
3703  private:
3704   FunctionTemplate();
3705   friend class Context;
3706   friend class ObjectTemplate;
3707 };
3708 
3709 
3710 /**
3711  * An ObjectTemplate is used to create objects at runtime.
3712  *
3713  * Properties added to an ObjectTemplate are added to each object
3714  * created from the ObjectTemplate.
3715  */
3716 class V8_EXPORT ObjectTemplate : public Template {
3717  public:
3718   /** Creates an ObjectTemplate. */
3719   static Local<ObjectTemplate> New(Isolate* isolate);
3720   // Will be deprecated soon.
3721   static Local<ObjectTemplate> New();
3722 
3723   /** Creates a new instance of this template.*/
3724   Local<Object> NewInstance();
3725 
3726   /**
3727    * Sets an accessor on the object template.
3728    *
3729    * Whenever the property with the given name is accessed on objects
3730    * created from this ObjectTemplate the getter and setter callbacks
3731    * are called instead of getting and setting the property directly
3732    * on the JavaScript object.
3733    *
3734    * \param name The name of the property for which an accessor is added.
3735    * \param getter The callback to invoke when getting the property.
3736    * \param setter The callback to invoke when setting the property.
3737    * \param data A piece of data that will be passed to the getter and setter
3738    *   callbacks whenever they are invoked.
3739    * \param settings Access control settings for the accessor. This is a bit
3740    *   field consisting of one of more of
3741    *   DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
3742    *   The default is to not allow cross-context access.
3743    *   ALL_CAN_READ means that all cross-context reads are allowed.
3744    *   ALL_CAN_WRITE means that all cross-context writes are allowed.
3745    *   The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
3746    *   cross-context access.
3747    * \param attribute The attributes of the property for which an accessor
3748    *   is added.
3749    * \param signature The signature describes valid receivers for the accessor
3750    *   and is used to perform implicit instance checks against them. If the
3751    *   receiver is incompatible (i.e. is not an instance of the constructor as
3752    *   defined by FunctionTemplate::HasInstance()), an implicit TypeError is
3753    *   thrown and no callback is invoked.
3754    */
3755   void SetAccessor(Handle<String> name,
3756                    AccessorGetterCallback getter,
3757                    AccessorSetterCallback setter = 0,
3758                    Handle<Value> data = Handle<Value>(),
3759                    AccessControl settings = DEFAULT,
3760                    PropertyAttribute attribute = None,
3761                    Handle<AccessorSignature> signature =
3762                        Handle<AccessorSignature>());
3763   void SetAccessor(Handle<Name> name,
3764                    AccessorNameGetterCallback getter,
3765                    AccessorNameSetterCallback setter = 0,
3766                    Handle<Value> data = Handle<Value>(),
3767                    AccessControl settings = DEFAULT,
3768                    PropertyAttribute attribute = None,
3769                    Handle<AccessorSignature> signature =
3770                        Handle<AccessorSignature>());
3771 
3772   /**
3773    * Sets a named property handler on the object template.
3774    *
3775    * Whenever a property whose name is a string is accessed on objects created
3776    * from this object template, the provided callback is invoked instead of
3777    * accessing the property directly on the JavaScript object.
3778    *
3779    * \param getter The callback to invoke when getting a property.
3780    * \param setter The callback to invoke when setting a property.
3781    * \param query The callback to invoke to check if a property is present,
3782    *   and if present, get its attributes.
3783    * \param deleter The callback to invoke when deleting a property.
3784    * \param enumerator The callback to invoke to enumerate all the named
3785    *   properties of an object.
3786    * \param data A piece of data that will be passed to the callbacks
3787    *   whenever they are invoked.
3788    */
3789   void SetNamedPropertyHandler(
3790       NamedPropertyGetterCallback getter,
3791       NamedPropertySetterCallback setter = 0,
3792       NamedPropertyQueryCallback query = 0,
3793       NamedPropertyDeleterCallback deleter = 0,
3794       NamedPropertyEnumeratorCallback enumerator = 0,
3795       Handle<Value> data = Handle<Value>());
3796 
3797   /**
3798    * Sets an indexed property handler on the object template.
3799    *
3800    * Whenever an indexed property is accessed on objects created from
3801    * this object template, the provided callback is invoked instead of
3802    * accessing the property directly on the JavaScript object.
3803    *
3804    * \param getter The callback to invoke when getting a property.
3805    * \param setter The callback to invoke when setting a property.
3806    * \param query The callback to invoke to check if an object has a property.
3807    * \param deleter The callback to invoke when deleting a property.
3808    * \param enumerator The callback to invoke to enumerate all the indexed
3809    *   properties of an object.
3810    * \param data A piece of data that will be passed to the callbacks
3811    *   whenever they are invoked.
3812    */
3813   void SetIndexedPropertyHandler(
3814       IndexedPropertyGetterCallback getter,
3815       IndexedPropertySetterCallback setter = 0,
3816       IndexedPropertyQueryCallback query = 0,
3817       IndexedPropertyDeleterCallback deleter = 0,
3818       IndexedPropertyEnumeratorCallback enumerator = 0,
3819       Handle<Value> data = Handle<Value>());
3820 
3821   /**
3822    * Sets the callback to be used when calling instances created from
3823    * this template as a function.  If no callback is set, instances
3824    * behave like normal JavaScript objects that cannot be called as a
3825    * function.
3826    */
3827   void SetCallAsFunctionHandler(FunctionCallback callback,
3828                                 Handle<Value> data = Handle<Value>());
3829 
3830   /**
3831    * Mark object instances of the template as undetectable.
3832    *
3833    * In many ways, undetectable objects behave as though they are not
3834    * there.  They behave like 'undefined' in conditionals and when
3835    * printed.  However, properties can be accessed and called as on
3836    * normal objects.
3837    */
3838   void MarkAsUndetectable();
3839 
3840   /**
3841    * Sets access check callbacks on the object template.
3842    *
3843    * When accessing properties on instances of this object template,
3844    * the access check callback will be called to determine whether or
3845    * not to allow cross-context access to the properties.
3846    * The last parameter specifies whether access checks are turned
3847    * on by default on instances. If access checks are off by default,
3848    * they can be turned on on individual instances by calling
3849    * Object::TurnOnAccessCheck().
3850    */
3851   void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
3852                                IndexedSecurityCallback indexed_handler,
3853                                Handle<Value> data = Handle<Value>(),
3854                                bool turned_on_by_default = true);
3855 
3856   /**
3857    * Gets the number of internal fields for objects generated from
3858    * this template.
3859    */
3860   int InternalFieldCount();
3861 
3862   /**
3863    * Sets the number of internal fields for objects generated from
3864    * this template.
3865    */
3866   void SetInternalFieldCount(int value);
3867 
3868  private:
3869   ObjectTemplate();
3870   static Local<ObjectTemplate> New(internal::Isolate* isolate,
3871                                    Handle<FunctionTemplate> constructor);
3872   friend class FunctionTemplate;
3873 };
3874 
3875 
3876 /**
3877  * A Signature specifies which receivers and arguments are valid
3878  * parameters to a function.
3879  */
3880 class V8_EXPORT Signature : public Data {
3881  public:
3882   static Local<Signature> New(Isolate* isolate,
3883                               Handle<FunctionTemplate> receiver =
3884                                   Handle<FunctionTemplate>(),
3885                               int argc = 0,
3886                               Handle<FunctionTemplate> argv[] = 0);
3887 
3888  private:
3889   Signature();
3890 };
3891 
3892 
3893 /**
3894  * An AccessorSignature specifies which receivers are valid parameters
3895  * to an accessor callback.
3896  */
3897 class V8_EXPORT AccessorSignature : public Data {
3898  public:
3899   static Local<AccessorSignature> New(Isolate* isolate,
3900                                       Handle<FunctionTemplate> receiver =
3901                                           Handle<FunctionTemplate>());
3902 
3903  private:
3904   AccessorSignature();
3905 };
3906 
3907 
3908 class V8_EXPORT DeclaredAccessorDescriptor : public Data {
3909  private:
3910   DeclaredAccessorDescriptor();
3911 };
3912 
3913 
3914 class V8_EXPORT ObjectOperationDescriptor : public Data {
3915  public:
3916   // This function is not yet stable and should not be used at this time.
3917   static Local<RawOperationDescriptor> NewInternalFieldDereference(
3918       Isolate* isolate,
3919       int internal_field);
3920  private:
3921   ObjectOperationDescriptor();
3922 };
3923 
3924 
3925 enum DeclaredAccessorDescriptorDataType {
3926     kDescriptorBoolType,
3927     kDescriptorInt8Type, kDescriptorUint8Type,
3928     kDescriptorInt16Type, kDescriptorUint16Type,
3929     kDescriptorInt32Type, kDescriptorUint32Type,
3930     kDescriptorFloatType, kDescriptorDoubleType
3931 };
3932 
3933 
3934 class V8_EXPORT RawOperationDescriptor : public Data {
3935  public:
3936   Local<DeclaredAccessorDescriptor> NewHandleDereference(Isolate* isolate);
3937   Local<RawOperationDescriptor> NewRawDereference(Isolate* isolate);
3938   Local<RawOperationDescriptor> NewRawShift(Isolate* isolate,
3939                                             int16_t byte_offset);
3940   Local<DeclaredAccessorDescriptor> NewPointerCompare(Isolate* isolate,
3941                                                       void* compare_value);
3942   Local<DeclaredAccessorDescriptor> NewPrimitiveValue(
3943       Isolate* isolate,
3944       DeclaredAccessorDescriptorDataType data_type,
3945       uint8_t bool_offset = 0);
3946   Local<DeclaredAccessorDescriptor> NewBitmaskCompare8(Isolate* isolate,
3947                                                        uint8_t bitmask,
3948                                                        uint8_t compare_value);
3949   Local<DeclaredAccessorDescriptor> NewBitmaskCompare16(
3950       Isolate* isolate,
3951       uint16_t bitmask,
3952       uint16_t compare_value);
3953   Local<DeclaredAccessorDescriptor> NewBitmaskCompare32(
3954       Isolate* isolate,
3955       uint32_t bitmask,
3956       uint32_t compare_value);
3957 
3958  private:
3959   RawOperationDescriptor();
3960 };
3961 
3962 
3963 /**
3964  * A utility for determining the type of objects based on the template
3965  * they were constructed from.
3966  */
3967 class V8_EXPORT TypeSwitch : public Data {
3968  public:
3969   static Local<TypeSwitch> New(Handle<FunctionTemplate> type);
3970   static Local<TypeSwitch> New(int argc, Handle<FunctionTemplate> types[]);
3971   int match(Handle<Value> value);
3972  private:
3973   TypeSwitch();
3974 };
3975 
3976 
3977 // --- Extensions ---
3978 
3979 class V8_EXPORT ExternalOneByteStringResourceImpl
3980     : public String::ExternalOneByteStringResource {
3981  public:
ExternalOneByteStringResourceImpl()3982   ExternalOneByteStringResourceImpl() : data_(0), length_(0) {}
ExternalOneByteStringResourceImpl(const char * data,size_t length)3983   ExternalOneByteStringResourceImpl(const char* data, size_t length)
3984       : data_(data), length_(length) {}
data()3985   const char* data() const { return data_; }
length()3986   size_t length() const { return length_; }
3987 
3988  private:
3989   const char* data_;
3990   size_t length_;
3991 };
3992 
3993 /**
3994  * Ignore
3995  */
3996 class V8_EXPORT Extension {  // NOLINT
3997  public:
3998   // Note that the strings passed into this constructor must live as long
3999   // as the Extension itself.
4000   Extension(const char* name,
4001             const char* source = 0,
4002             int dep_count = 0,
4003             const char** deps = 0,
4004             int source_length = -1);
~Extension()4005   virtual ~Extension() { }
GetNativeFunctionTemplate(v8::Isolate * isolate,v8::Handle<v8::String> name)4006   virtual v8::Handle<v8::FunctionTemplate> GetNativeFunctionTemplate(
4007       v8::Isolate* isolate, v8::Handle<v8::String> name) {
4008     return v8::Handle<v8::FunctionTemplate>();
4009   }
4010 
name()4011   const char* name() const { return name_; }
source_length()4012   size_t source_length() const { return source_length_; }
source()4013   const String::ExternalOneByteStringResource* source() const {
4014     return &source_; }
dependency_count()4015   int dependency_count() { return dep_count_; }
dependencies()4016   const char** dependencies() { return deps_; }
set_auto_enable(bool value)4017   void set_auto_enable(bool value) { auto_enable_ = value; }
auto_enable()4018   bool auto_enable() { return auto_enable_; }
4019 
4020  private:
4021   const char* name_;
4022   size_t source_length_;  // expected to initialize before source_
4023   ExternalOneByteStringResourceImpl source_;
4024   int dep_count_;
4025   const char** deps_;
4026   bool auto_enable_;
4027 
4028   // Disallow copying and assigning.
4029   Extension(const Extension&);
4030   void operator=(const Extension&);
4031 };
4032 
4033 
4034 void V8_EXPORT RegisterExtension(Extension* extension);
4035 
4036 
4037 // --- Statics ---
4038 
4039 V8_INLINE Handle<Primitive> Undefined(Isolate* isolate);
4040 V8_INLINE Handle<Primitive> Null(Isolate* isolate);
4041 V8_INLINE Handle<Boolean> True(Isolate* isolate);
4042 V8_INLINE Handle<Boolean> False(Isolate* isolate);
4043 
4044 
4045 /**
4046  * A set of constraints that specifies the limits of the runtime's memory use.
4047  * You must set the heap size before initializing the VM - the size cannot be
4048  * adjusted after the VM is initialized.
4049  *
4050  * If you are using threads then you should hold the V8::Locker lock while
4051  * setting the stack limit and you must set a non-default stack limit separately
4052  * for each thread.
4053  */
4054 class V8_EXPORT ResourceConstraints {
4055  public:
4056   ResourceConstraints();
4057 
4058   /**
4059    * Configures the constraints with reasonable default values based on the
4060    * capabilities of the current device the VM is running on.
4061    *
4062    * \param physical_memory The total amount of physical memory on the current
4063    *   device, in bytes.
4064    * \param virtual_memory_limit The amount of virtual memory on the current
4065    *   device, in bytes, or zero, if there is no limit.
4066    * \param number_of_processors The number of CPUs available on the current
4067    *   device.
4068    */
4069   void ConfigureDefaults(uint64_t physical_memory,
4070                          uint64_t virtual_memory_limit,
4071                          uint32_t number_of_processors);
4072 
max_semi_space_size()4073   int max_semi_space_size() const { return max_semi_space_size_; }
set_max_semi_space_size(int value)4074   void set_max_semi_space_size(int value) { max_semi_space_size_ = value; }
max_old_space_size()4075   int max_old_space_size() const { return max_old_space_size_; }
set_max_old_space_size(int value)4076   void set_max_old_space_size(int value) { max_old_space_size_ = value; }
max_executable_size()4077   int max_executable_size() const { return max_executable_size_; }
set_max_executable_size(int value)4078   void set_max_executable_size(int value) { max_executable_size_ = value; }
stack_limit()4079   uint32_t* stack_limit() const { return stack_limit_; }
4080   // Sets an address beyond which the VM's stack may not grow.
set_stack_limit(uint32_t * value)4081   void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
max_available_threads()4082   int max_available_threads() const { return max_available_threads_; }
4083   // Set the number of threads available to V8, assuming at least 1.
set_max_available_threads(int value)4084   void set_max_available_threads(int value) {
4085     max_available_threads_ = value;
4086   }
code_range_size()4087   size_t code_range_size() const { return code_range_size_; }
set_code_range_size(size_t value)4088   void set_code_range_size(size_t value) {
4089     code_range_size_ = value;
4090   }
4091 
4092  private:
4093   int max_semi_space_size_;
4094   int max_old_space_size_;
4095   int max_executable_size_;
4096   uint32_t* stack_limit_;
4097   int max_available_threads_;
4098   size_t code_range_size_;
4099 };
4100 
4101 
4102 // --- Exceptions ---
4103 
4104 
4105 typedef void (*FatalErrorCallback)(const char* location, const char* message);
4106 
4107 
4108 typedef void (*MessageCallback)(Handle<Message> message, Handle<Value> error);
4109 
4110 // --- Tracing ---
4111 
4112 typedef void (*LogEventCallback)(const char* name, int event);
4113 
4114 /**
4115  * Create new error objects by calling the corresponding error object
4116  * constructor with the message.
4117  */
4118 class V8_EXPORT Exception {
4119  public:
4120   static Local<Value> RangeError(Handle<String> message);
4121   static Local<Value> ReferenceError(Handle<String> message);
4122   static Local<Value> SyntaxError(Handle<String> message);
4123   static Local<Value> TypeError(Handle<String> message);
4124   static Local<Value> Error(Handle<String> message);
4125 };
4126 
4127 
4128 // --- Counters Callbacks ---
4129 
4130 typedef int* (*CounterLookupCallback)(const char* name);
4131 
4132 typedef void* (*CreateHistogramCallback)(const char* name,
4133                                          int min,
4134                                          int max,
4135                                          size_t buckets);
4136 
4137 typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
4138 
4139 // --- Memory Allocation Callback ---
4140   enum ObjectSpace {
4141     kObjectSpaceNewSpace = 1 << 0,
4142     kObjectSpaceOldPointerSpace = 1 << 1,
4143     kObjectSpaceOldDataSpace = 1 << 2,
4144     kObjectSpaceCodeSpace = 1 << 3,
4145     kObjectSpaceMapSpace = 1 << 4,
4146     kObjectSpaceLoSpace = 1 << 5,
4147 
4148     kObjectSpaceAll = kObjectSpaceNewSpace | kObjectSpaceOldPointerSpace |
4149       kObjectSpaceOldDataSpace | kObjectSpaceCodeSpace | kObjectSpaceMapSpace |
4150       kObjectSpaceLoSpace
4151   };
4152 
4153   enum AllocationAction {
4154     kAllocationActionAllocate = 1 << 0,
4155     kAllocationActionFree = 1 << 1,
4156     kAllocationActionAll = kAllocationActionAllocate | kAllocationActionFree
4157   };
4158 
4159 typedef void (*MemoryAllocationCallback)(ObjectSpace space,
4160                                          AllocationAction action,
4161                                          int size);
4162 
4163 // --- Leave Script Callback ---
4164 typedef void (*CallCompletedCallback)();
4165 
4166 // --- Microtask Callback ---
4167 typedef void (*MicrotaskCallback)(void* data);
4168 
4169 // --- Failed Access Check Callback ---
4170 typedef void (*FailedAccessCheckCallback)(Local<Object> target,
4171                                           AccessType type,
4172                                           Local<Value> data);
4173 
4174 // --- AllowCodeGenerationFromStrings callbacks ---
4175 
4176 /**
4177  * Callback to check if code generation from strings is allowed. See
4178  * Context::AllowCodeGenerationFromStrings.
4179  */
4180 typedef bool (*AllowCodeGenerationFromStringsCallback)(Local<Context> context);
4181 
4182 // --- Garbage Collection Callbacks ---
4183 
4184 /**
4185  * Applications can register callback functions which will be called
4186  * before and after a garbage collection.  Allocations are not
4187  * allowed in the callback functions, you therefore cannot manipulate
4188  * objects (set or delete properties for example) since it is possible
4189  * such operations will result in the allocation of objects.
4190  */
4191 enum GCType {
4192   kGCTypeScavenge = 1 << 0,
4193   kGCTypeMarkSweepCompact = 1 << 1,
4194   kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact
4195 };
4196 
4197 enum GCCallbackFlags {
4198   kNoGCCallbackFlags = 0,
4199   kGCCallbackFlagCompacted = 1 << 0,
4200   kGCCallbackFlagConstructRetainedObjectInfos = 1 << 1,
4201   kGCCallbackFlagForced = 1 << 2
4202 };
4203 
4204 typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
4205 typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
4206 
4207 typedef void (*InterruptCallback)(Isolate* isolate, void* data);
4208 
4209 
4210 /**
4211  * Collection of V8 heap information.
4212  *
4213  * Instances of this class can be passed to v8::V8::HeapStatistics to
4214  * get heap statistics from V8.
4215  */
4216 class V8_EXPORT HeapStatistics {
4217  public:
4218   HeapStatistics();
total_heap_size()4219   size_t total_heap_size() { return total_heap_size_; }
total_heap_size_executable()4220   size_t total_heap_size_executable() { return total_heap_size_executable_; }
total_physical_size()4221   size_t total_physical_size() { return total_physical_size_; }
used_heap_size()4222   size_t used_heap_size() { return used_heap_size_; }
heap_size_limit()4223   size_t heap_size_limit() { return heap_size_limit_; }
4224 
4225  private:
4226   size_t total_heap_size_;
4227   size_t total_heap_size_executable_;
4228   size_t total_physical_size_;
4229   size_t used_heap_size_;
4230   size_t heap_size_limit_;
4231 
4232   friend class V8;
4233   friend class Isolate;
4234 };
4235 
4236 
4237 class RetainedObjectInfo;
4238 
4239 
4240 /**
4241  * FunctionEntryHook is the type of the profile entry hook called at entry to
4242  * any generated function when function-level profiling is enabled.
4243  *
4244  * \param function the address of the function that's being entered.
4245  * \param return_addr_location points to a location on stack where the machine
4246  *    return address resides. This can be used to identify the caller of
4247  *    \p function, and/or modified to divert execution when \p function exits.
4248  *
4249  * \note the entry hook must not cause garbage collection.
4250  */
4251 typedef void (*FunctionEntryHook)(uintptr_t function,
4252                                   uintptr_t return_addr_location);
4253 
4254 /**
4255  * A JIT code event is issued each time code is added, moved or removed.
4256  *
4257  * \note removal events are not currently issued.
4258  */
4259 struct JitCodeEvent {
4260   enum EventType {
4261     CODE_ADDED,
4262     CODE_MOVED,
4263     CODE_REMOVED,
4264     CODE_ADD_LINE_POS_INFO,
4265     CODE_START_LINE_INFO_RECORDING,
4266     CODE_END_LINE_INFO_RECORDING
4267   };
4268   // Definition of the code position type. The "POSITION" type means the place
4269   // in the source code which are of interest when making stack traces to
4270   // pin-point the source location of a stack frame as close as possible.
4271   // The "STATEMENT_POSITION" means the place at the beginning of each
4272   // statement, and is used to indicate possible break locations.
4273   enum PositionType { POSITION, STATEMENT_POSITION };
4274 
4275   // Type of event.
4276   EventType type;
4277   // Start of the instructions.
4278   void* code_start;
4279   // Size of the instructions.
4280   size_t code_len;
4281   // Script info for CODE_ADDED event.
4282   Handle<UnboundScript> script;
4283   // User-defined data for *_LINE_INFO_* event. It's used to hold the source
4284   // code line information which is returned from the
4285   // CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent
4286   // CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events.
4287   void* user_data;
4288 
4289   struct name_t {
4290     // Name of the object associated with the code, note that the string is not
4291     // zero-terminated.
4292     const char* str;
4293     // Number of chars in str.
4294     size_t len;
4295   };
4296 
4297   struct line_info_t {
4298     // PC offset
4299     size_t offset;
4300     // Code postion
4301     size_t pos;
4302     // The position type.
4303     PositionType position_type;
4304   };
4305 
4306   union {
4307     // Only valid for CODE_ADDED.
4308     struct name_t name;
4309 
4310     // Only valid for CODE_ADD_LINE_POS_INFO
4311     struct line_info_t line_info;
4312 
4313     // New location of instructions. Only valid for CODE_MOVED.
4314     void* new_code_start;
4315   };
4316 };
4317 
4318 /**
4319  * Option flags passed to the SetJitCodeEventHandler function.
4320  */
4321 enum JitCodeEventOptions {
4322   kJitCodeEventDefault = 0,
4323   // Generate callbacks for already existent code.
4324   kJitCodeEventEnumExisting = 1
4325 };
4326 
4327 
4328 /**
4329  * Callback function passed to SetJitCodeEventHandler.
4330  *
4331  * \param event code add, move or removal event.
4332  */
4333 typedef void (*JitCodeEventHandler)(const JitCodeEvent* event);
4334 
4335 
4336 /**
4337  * Isolate represents an isolated instance of the V8 engine.  V8 isolates have
4338  * completely separate states.  Objects from one isolate must not be used in
4339  * other isolates.  The embedder can create multiple isolates and use them in
4340  * parallel in multiple threads.  An isolate can be entered by at most one
4341  * thread at any given time.  The Locker/Unlocker API must be used to
4342  * synchronize.
4343  */
4344 class V8_EXPORT Isolate {
4345  public:
4346   /**
4347    * Initial configuration parameters for a new Isolate.
4348    */
4349   struct CreateParams {
CreateParamsCreateParams4350     CreateParams()
4351         : entry_hook(NULL),
4352           code_event_handler(NULL),
4353           enable_serializer(false) {}
4354 
4355     /**
4356      * The optional entry_hook allows the host application to provide the
4357      * address of a function that's invoked on entry to every V8-generated
4358      * function.  Note that entry_hook is invoked at the very start of each
4359      * generated function. Furthermore, if an  entry_hook is given, V8 will
4360      * always run without a context snapshot.
4361      */
4362     FunctionEntryHook entry_hook;
4363 
4364     /**
4365      * Allows the host application to provide the address of a function that is
4366      * notified each time code is added, moved or removed.
4367      */
4368     JitCodeEventHandler code_event_handler;
4369 
4370     /**
4371      * ResourceConstraints to use for the new Isolate.
4372      */
4373     ResourceConstraints constraints;
4374 
4375     /**
4376      * This flag currently renders the Isolate unusable.
4377      */
4378     bool enable_serializer;
4379   };
4380 
4381 
4382   /**
4383    * Stack-allocated class which sets the isolate for all operations
4384    * executed within a local scope.
4385    */
4386   class V8_EXPORT Scope {
4387    public:
Scope(Isolate * isolate)4388     explicit Scope(Isolate* isolate) : isolate_(isolate) {
4389       isolate->Enter();
4390     }
4391 
~Scope()4392     ~Scope() { isolate_->Exit(); }
4393 
4394    private:
4395     Isolate* const isolate_;
4396 
4397     // Prevent copying of Scope objects.
4398     Scope(const Scope&);
4399     Scope& operator=(const Scope&);
4400   };
4401 
4402 
4403   /**
4404    * Assert that no Javascript code is invoked.
4405    */
4406   class V8_EXPORT DisallowJavascriptExecutionScope {
4407    public:
4408     enum OnFailure { CRASH_ON_FAILURE, THROW_ON_FAILURE };
4409 
4410     DisallowJavascriptExecutionScope(Isolate* isolate, OnFailure on_failure);
4411     ~DisallowJavascriptExecutionScope();
4412 
4413    private:
4414     bool on_failure_;
4415     void* internal_;
4416 
4417     // Prevent copying of Scope objects.
4418     DisallowJavascriptExecutionScope(const DisallowJavascriptExecutionScope&);
4419     DisallowJavascriptExecutionScope& operator=(
4420         const DisallowJavascriptExecutionScope&);
4421   };
4422 
4423 
4424   /**
4425    * Introduce exception to DisallowJavascriptExecutionScope.
4426    */
4427   class V8_EXPORT AllowJavascriptExecutionScope {
4428    public:
4429     explicit AllowJavascriptExecutionScope(Isolate* isolate);
4430     ~AllowJavascriptExecutionScope();
4431 
4432    private:
4433     void* internal_throws_;
4434     void* internal_assert_;
4435 
4436     // Prevent copying of Scope objects.
4437     AllowJavascriptExecutionScope(const AllowJavascriptExecutionScope&);
4438     AllowJavascriptExecutionScope& operator=(
4439         const AllowJavascriptExecutionScope&);
4440   };
4441 
4442   /**
4443    * Do not run microtasks while this scope is active, even if microtasks are
4444    * automatically executed otherwise.
4445    */
4446   class V8_EXPORT SuppressMicrotaskExecutionScope {
4447    public:
4448     explicit SuppressMicrotaskExecutionScope(Isolate* isolate);
4449     ~SuppressMicrotaskExecutionScope();
4450 
4451    private:
4452     internal::Isolate* isolate_;
4453 
4454     // Prevent copying of Scope objects.
4455     SuppressMicrotaskExecutionScope(const SuppressMicrotaskExecutionScope&);
4456     SuppressMicrotaskExecutionScope& operator=(
4457         const SuppressMicrotaskExecutionScope&);
4458   };
4459 
4460   /**
4461    * Types of garbage collections that can be requested via
4462    * RequestGarbageCollectionForTesting.
4463    */
4464   enum GarbageCollectionType {
4465     kFullGarbageCollection,
4466     kMinorGarbageCollection
4467   };
4468 
4469   /**
4470    * Features reported via the SetUseCounterCallback callback. Do not chang
4471    * assigned numbers of existing items; add new features to the end of this
4472    * list.
4473    */
4474   enum UseCounterFeature {
4475     kUseAsm = 0,
4476     kUseCounterFeatureCount  // This enum value must be last.
4477   };
4478 
4479   typedef void (*UseCounterCallback)(Isolate* isolate,
4480                                      UseCounterFeature feature);
4481 
4482 
4483   /**
4484    * Creates a new isolate.  Does not change the currently entered
4485    * isolate.
4486    *
4487    * When an isolate is no longer used its resources should be freed
4488    * by calling Dispose().  Using the delete operator is not allowed.
4489    *
4490    * V8::Initialize() must have run prior to this.
4491    */
4492   static Isolate* New(const CreateParams& params = CreateParams());
4493 
4494   /**
4495    * Returns the entered isolate for the current thread or NULL in
4496    * case there is no current isolate.
4497    */
4498   static Isolate* GetCurrent();
4499 
4500   /**
4501    * Methods below this point require holding a lock (using Locker) in
4502    * a multi-threaded environment.
4503    */
4504 
4505   /**
4506    * Sets this isolate as the entered one for the current thread.
4507    * Saves the previously entered one (if any), so that it can be
4508    * restored when exiting.  Re-entering an isolate is allowed.
4509    */
4510   void Enter();
4511 
4512   /**
4513    * Exits this isolate by restoring the previously entered one in the
4514    * current thread.  The isolate may still stay the same, if it was
4515    * entered more than once.
4516    *
4517    * Requires: this == Isolate::GetCurrent().
4518    */
4519   void Exit();
4520 
4521   /**
4522    * Disposes the isolate.  The isolate must not be entered by any
4523    * thread to be disposable.
4524    */
4525   void Dispose();
4526 
4527   /**
4528    * Associate embedder-specific data with the isolate. |slot| has to be
4529    * between 0 and GetNumberOfDataSlots() - 1.
4530    */
4531   V8_INLINE void SetData(uint32_t slot, void* data);
4532 
4533   /**
4534    * Retrieve embedder-specific data from the isolate.
4535    * Returns NULL if SetData has never been called for the given |slot|.
4536    */
4537   V8_INLINE void* GetData(uint32_t slot);
4538 
4539   /**
4540    * Returns the maximum number of available embedder data slots. Valid slots
4541    * are in the range of 0 - GetNumberOfDataSlots() - 1.
4542    */
4543   V8_INLINE static uint32_t GetNumberOfDataSlots();
4544 
4545   /**
4546    * Get statistics about the heap memory usage.
4547    */
4548   void GetHeapStatistics(HeapStatistics* heap_statistics);
4549 
4550   /**
4551    * Adjusts the amount of registered external memory. Used to give V8 an
4552    * indication of the amount of externally allocated memory that is kept alive
4553    * by JavaScript objects. V8 uses this to decide when to perform global
4554    * garbage collections. Registering externally allocated memory will trigger
4555    * global garbage collections more often than it would otherwise in an attempt
4556    * to garbage collect the JavaScript objects that keep the externally
4557    * allocated memory alive.
4558    *
4559    * \param change_in_bytes the change in externally allocated memory that is
4560    *   kept alive by JavaScript objects.
4561    * \returns the adjusted value.
4562    */
4563   V8_INLINE int64_t
4564       AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes);
4565 
4566   /**
4567    * Returns heap profiler for this isolate. Will return NULL until the isolate
4568    * is initialized.
4569    */
4570   HeapProfiler* GetHeapProfiler();
4571 
4572   /**
4573    * Returns CPU profiler for this isolate. Will return NULL unless the isolate
4574    * is initialized. It is the embedder's responsibility to stop all CPU
4575    * profiling activities if it has started any.
4576    */
4577   CpuProfiler* GetCpuProfiler();
4578 
4579   /** Returns true if this isolate has a current context. */
4580   bool InContext();
4581 
4582   /** Returns the context that is on the top of the stack. */
4583   Local<Context> GetCurrentContext();
4584 
4585   /**
4586    * Returns the context of the calling JavaScript code.  That is the
4587    * context of the top-most JavaScript frame.  If there are no
4588    * JavaScript frames an empty handle is returned.
4589    */
4590   Local<Context> GetCallingContext();
4591 
4592   /** Returns the last entered context. */
4593   Local<Context> GetEnteredContext();
4594 
4595   /**
4596    * Schedules an exception to be thrown when returning to JavaScript.  When an
4597    * exception has been scheduled it is illegal to invoke any JavaScript
4598    * operation; the caller must return immediately and only after the exception
4599    * has been handled does it become legal to invoke JavaScript operations.
4600    */
4601   Local<Value> ThrowException(Local<Value> exception);
4602 
4603   /**
4604    * Allows the host application to group objects together. If one
4605    * object in the group is alive, all objects in the group are alive.
4606    * After each garbage collection, object groups are removed. It is
4607    * intended to be used in the before-garbage-collection callback
4608    * function, for instance to simulate DOM tree connections among JS
4609    * wrapper objects. Object groups for all dependent handles need to
4610    * be provided for kGCTypeMarkSweepCompact collections, for all other
4611    * garbage collection types it is sufficient to provide object groups
4612    * for partially dependent handles only.
4613    */
4614   template<typename T> void SetObjectGroupId(const Persistent<T>& object,
4615                                              UniqueId id);
4616 
4617   /**
4618    * Allows the host application to declare implicit references from an object
4619    * group to an object. If the objects of the object group are alive, the child
4620    * object is alive too. After each garbage collection, all implicit references
4621    * are removed. It is intended to be used in the before-garbage-collection
4622    * callback function.
4623    */
4624   template<typename T> void SetReferenceFromGroup(UniqueId id,
4625                                                   const Persistent<T>& child);
4626 
4627   /**
4628    * Allows the host application to declare implicit references from an object
4629    * to another object. If the parent object is alive, the child object is alive
4630    * too. After each garbage collection, all implicit references are removed. It
4631    * is intended to be used in the before-garbage-collection callback function.
4632    */
4633   template<typename T, typename S>
4634   void SetReference(const Persistent<T>& parent, const Persistent<S>& child);
4635 
4636   typedef void (*GCPrologueCallback)(Isolate* isolate,
4637                                      GCType type,
4638                                      GCCallbackFlags flags);
4639   typedef void (*GCEpilogueCallback)(Isolate* isolate,
4640                                      GCType type,
4641                                      GCCallbackFlags flags);
4642 
4643   /**
4644    * Enables the host application to receive a notification before a
4645    * garbage collection. Allocations are allowed in the callback function,
4646    * but the callback is not re-entrant: if the allocation inside it will
4647    * trigger the garbage collection, the callback won't be called again.
4648    * It is possible to specify the GCType filter for your callback. But it is
4649    * not possible to register the same callback function two times with
4650    * different GCType filters.
4651    */
4652   void AddGCPrologueCallback(
4653       GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
4654 
4655   /**
4656    * This function removes callback which was installed by
4657    * AddGCPrologueCallback function.
4658    */
4659   void RemoveGCPrologueCallback(GCPrologueCallback callback);
4660 
4661   /**
4662    * Enables the host application to receive a notification after a
4663    * garbage collection. Allocations are allowed in the callback function,
4664    * but the callback is not re-entrant: if the allocation inside it will
4665    * trigger the garbage collection, the callback won't be called again.
4666    * It is possible to specify the GCType filter for your callback. But it is
4667    * not possible to register the same callback function two times with
4668    * different GCType filters.
4669    */
4670   void AddGCEpilogueCallback(
4671       GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
4672 
4673   /**
4674    * This function removes callback which was installed by
4675    * AddGCEpilogueCallback function.
4676    */
4677   void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
4678 
4679   /**
4680    * Request V8 to interrupt long running JavaScript code and invoke
4681    * the given |callback| passing the given |data| to it. After |callback|
4682    * returns control will be returned to the JavaScript code.
4683    * At any given moment V8 can remember only a single callback for the very
4684    * last interrupt request.
4685    * Can be called from another thread without acquiring a |Locker|.
4686    * Registered |callback| must not reenter interrupted Isolate.
4687    */
4688   void RequestInterrupt(InterruptCallback callback, void* data);
4689 
4690   /**
4691    * Clear interrupt request created by |RequestInterrupt|.
4692    * Can be called from another thread without acquiring a |Locker|.
4693    */
4694   void ClearInterrupt();
4695 
4696   /**
4697    * Request garbage collection in this Isolate. It is only valid to call this
4698    * function if --expose_gc was specified.
4699    *
4700    * This should only be used for testing purposes and not to enforce a garbage
4701    * collection schedule. It has strong negative impact on the garbage
4702    * collection performance. Use IdleNotification() or LowMemoryNotification()
4703    * instead to influence the garbage collection schedule.
4704    */
4705   void RequestGarbageCollectionForTesting(GarbageCollectionType type);
4706 
4707   /**
4708    * Set the callback to invoke for logging event.
4709    */
4710   void SetEventLogger(LogEventCallback that);
4711 
4712   /**
4713    * Adds a callback to notify the host application when a script finished
4714    * running.  If a script re-enters the runtime during executing, the
4715    * CallCompletedCallback is only invoked when the outer-most script
4716    * execution ends.  Executing scripts inside the callback do not trigger
4717    * further callbacks.
4718    */
4719   void AddCallCompletedCallback(CallCompletedCallback callback);
4720 
4721   /**
4722    * Removes callback that was installed by AddCallCompletedCallback.
4723    */
4724   void RemoveCallCompletedCallback(CallCompletedCallback callback);
4725 
4726   /**
4727    * Experimental: Runs the Microtask Work Queue until empty
4728    * Any exceptions thrown by microtask callbacks are swallowed.
4729    */
4730   void RunMicrotasks();
4731 
4732   /**
4733    * Experimental: Enqueues the callback to the Microtask Work Queue
4734    */
4735   void EnqueueMicrotask(Handle<Function> microtask);
4736 
4737   /**
4738    * Experimental: Enqueues the callback to the Microtask Work Queue
4739    */
4740   void EnqueueMicrotask(MicrotaskCallback microtask, void* data = NULL);
4741 
4742    /**
4743    * Experimental: Controls whether the Microtask Work Queue is automatically
4744    * run when the script call depth decrements to zero.
4745    */
4746   void SetAutorunMicrotasks(bool autorun);
4747 
4748   /**
4749    * Experimental: Returns whether the Microtask Work Queue is automatically
4750    * run when the script call depth decrements to zero.
4751    */
4752   bool WillAutorunMicrotasks() const;
4753 
4754   /**
4755    * Sets a callback for counting the number of times a feature of V8 is used.
4756    */
4757   void SetUseCounterCallback(UseCounterCallback callback);
4758 
4759   /**
4760    * Enables the host application to provide a mechanism for recording
4761    * statistics counters.
4762    */
4763   void SetCounterFunction(CounterLookupCallback);
4764 
4765   /**
4766    * Enables the host application to provide a mechanism for recording
4767    * histograms. The CreateHistogram function returns a
4768    * histogram which will later be passed to the AddHistogramSample
4769    * function.
4770    */
4771   void SetCreateHistogramFunction(CreateHistogramCallback);
4772   void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
4773 
4774   /**
4775    * Optional notification that the embedder is idle.
4776    * V8 uses the notification to reduce memory footprint.
4777    * This call can be used repeatedly if the embedder remains idle.
4778    * Returns true if the embedder should stop calling IdleNotification
4779    * until real work has been done.  This indicates that V8 has done
4780    * as much cleanup as it will be able to do.
4781    *
4782    * The idle_time_in_ms argument specifies the time V8 has to do reduce
4783    * the memory footprint. There is no guarantee that the actual work will be
4784    * done within the time limit.
4785    */
4786   bool IdleNotification(int idle_time_in_ms);
4787 
4788   /**
4789    * Optional notification that the system is running low on memory.
4790    * V8 uses these notifications to attempt to free memory.
4791    */
4792   void LowMemoryNotification();
4793 
4794   /**
4795    * Optional notification that a context has been disposed. V8 uses
4796    * these notifications to guide the GC heuristic. Returns the number
4797    * of context disposals - including this one - since the last time
4798    * V8 had a chance to clean up.
4799    */
4800   int ContextDisposedNotification();
4801 
4802   /**
4803    * Allows the host application to provide the address of a function that is
4804    * notified each time code is added, moved or removed.
4805    *
4806    * \param options options for the JIT code event handler.
4807    * \param event_handler the JIT code event handler, which will be invoked
4808    *     each time code is added, moved or removed.
4809    * \note \p event_handler won't get notified of existent code.
4810    * \note since code removal notifications are not currently issued, the
4811    *     \p event_handler may get notifications of code that overlaps earlier
4812    *     code notifications. This happens when code areas are reused, and the
4813    *     earlier overlapping code areas should therefore be discarded.
4814    * \note the events passed to \p event_handler and the strings they point to
4815    *     are not guaranteed to live past each call. The \p event_handler must
4816    *     copy strings and other parameters it needs to keep around.
4817    * \note the set of events declared in JitCodeEvent::EventType is expected to
4818    *     grow over time, and the JitCodeEvent structure is expected to accrue
4819    *     new members. The \p event_handler function must ignore event codes
4820    *     it does not recognize to maintain future compatibility.
4821    * \note Use Isolate::CreateParams to get events for code executed during
4822    *     Isolate setup.
4823    */
4824   void SetJitCodeEventHandler(JitCodeEventOptions options,
4825                               JitCodeEventHandler event_handler);
4826 
4827   /**
4828    * Modifies the stack limit for this Isolate.
4829    *
4830    * \param stack_limit An address beyond which the Vm's stack may not grow.
4831    *
4832    * \note  If you are using threads then you should hold the V8::Locker lock
4833    *     while setting the stack limit and you must set a non-default stack
4834    *     limit separately for each thread.
4835    */
4836   void SetStackLimit(uintptr_t stack_limit);
4837 
4838  private:
4839   template<class K, class V, class Traits> friend class PersistentValueMap;
4840 
4841   Isolate();
4842   Isolate(const Isolate&);
4843   ~Isolate();
4844   Isolate& operator=(const Isolate&);
4845   void* operator new(size_t size);
4846   void operator delete(void*, size_t);
4847 
4848   void SetObjectGroupId(internal::Object** object, UniqueId id);
4849   void SetReferenceFromGroup(UniqueId id, internal::Object** object);
4850   void SetReference(internal::Object** parent, internal::Object** child);
4851   void CollectAllGarbage(const char* gc_reason);
4852 };
4853 
4854 class V8_EXPORT StartupData {
4855  public:
4856   enum CompressionAlgorithm {
4857     kUncompressed,
4858     kBZip2
4859   };
4860 
4861   const char* data;
4862   int compressed_size;
4863   int raw_size;
4864 };
4865 
4866 
4867 /**
4868  * A helper class for driving V8 startup data decompression.  It is based on
4869  * "CompressedStartupData" API functions from the V8 class.  It isn't mandatory
4870  * for an embedder to use this class, instead, API functions can be used
4871  * directly.
4872  *
4873  * For an example of the class usage, see the "shell.cc" sample application.
4874  */
4875 class V8_EXPORT StartupDataDecompressor {  // NOLINT
4876  public:
4877   StartupDataDecompressor();
4878   virtual ~StartupDataDecompressor();
4879   int Decompress();
4880 
4881  protected:
4882   virtual int DecompressData(char* raw_data,
4883                              int* raw_data_size,
4884                              const char* compressed_data,
4885                              int compressed_data_size) = 0;
4886 
4887  private:
4888   char** raw_data;
4889 };
4890 
4891 
4892 /**
4893  * EntropySource is used as a callback function when v8 needs a source
4894  * of entropy.
4895  */
4896 typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
4897 
4898 
4899 /**
4900  * ReturnAddressLocationResolver is used as a callback function when v8 is
4901  * resolving the location of a return address on the stack. Profilers that
4902  * change the return address on the stack can use this to resolve the stack
4903  * location to whereever the profiler stashed the original return address.
4904  *
4905  * \param return_addr_location points to a location on stack where a machine
4906  *    return address resides.
4907  * \returns either return_addr_location, or else a pointer to the profiler's
4908  *    copy of the original return address.
4909  *
4910  * \note the resolver function must not cause garbage collection.
4911  */
4912 typedef uintptr_t (*ReturnAddressLocationResolver)(
4913     uintptr_t return_addr_location);
4914 
4915 
4916 /**
4917  * Interface for iterating through all external resources in the heap.
4918  */
4919 class V8_EXPORT ExternalResourceVisitor {  // NOLINT
4920  public:
~ExternalResourceVisitor()4921   virtual ~ExternalResourceVisitor() {}
VisitExternalString(Handle<String> string)4922   virtual void VisitExternalString(Handle<String> string) {}
4923 };
4924 
4925 
4926 /**
4927  * Interface for iterating through all the persistent handles in the heap.
4928  */
4929 class V8_EXPORT PersistentHandleVisitor {  // NOLINT
4930  public:
~PersistentHandleVisitor()4931   virtual ~PersistentHandleVisitor() {}
VisitPersistentHandle(Persistent<Value> * value,uint16_t class_id)4932   virtual void VisitPersistentHandle(Persistent<Value>* value,
4933                                      uint16_t class_id) {}
4934 };
4935 
4936 
4937 /**
4938  * Container class for static utility functions.
4939  */
4940 class V8_EXPORT V8 {
4941  public:
4942   /** Set the callback to invoke in case of fatal errors. */
4943   static void SetFatalErrorHandler(FatalErrorCallback that);
4944 
4945   /**
4946    * Set the callback to invoke to check if code generation from
4947    * strings should be allowed.
4948    */
4949   static void SetAllowCodeGenerationFromStringsCallback(
4950       AllowCodeGenerationFromStringsCallback that);
4951 
4952   /**
4953    * Set allocator to use for ArrayBuffer memory.
4954    * The allocator should be set only once. The allocator should be set
4955    * before any code tha uses ArrayBuffers is executed.
4956    * This allocator is used in all isolates.
4957    */
4958   static void SetArrayBufferAllocator(ArrayBuffer::Allocator* allocator);
4959 
4960   /**
4961    * Check if V8 is dead and therefore unusable.  This is the case after
4962    * fatal errors such as out-of-memory situations.
4963    */
4964   static bool IsDead();
4965 
4966   /**
4967    * The following 4 functions are to be used when V8 is built with
4968    * the 'compress_startup_data' flag enabled. In this case, the
4969    * embedder must decompress startup data prior to initializing V8.
4970    *
4971    * This is how interaction with V8 should look like:
4972    *   int compressed_data_count = v8::V8::GetCompressedStartupDataCount();
4973    *   v8::StartupData* compressed_data =
4974    *     new v8::StartupData[compressed_data_count];
4975    *   v8::V8::GetCompressedStartupData(compressed_data);
4976    *   ... decompress data (compressed_data can be updated in-place) ...
4977    *   v8::V8::SetDecompressedStartupData(compressed_data);
4978    *   ... now V8 can be initialized
4979    *   ... make sure the decompressed data stays valid until V8 shutdown
4980    *
4981    * A helper class StartupDataDecompressor is provided. It implements
4982    * the protocol of the interaction described above, and can be used in
4983    * most cases instead of calling these API functions directly.
4984    */
4985   static StartupData::CompressionAlgorithm GetCompressedStartupDataAlgorithm();
4986   static int GetCompressedStartupDataCount();
4987   static void GetCompressedStartupData(StartupData* compressed_data);
4988   static void SetDecompressedStartupData(StartupData* decompressed_data);
4989 
4990   /**
4991    * Hand startup data to V8, in case the embedder has chosen to build
4992    * V8 with external startup data.
4993    *
4994    * Note:
4995    * - By default the startup data is linked into the V8 library, in which
4996    *   case this function is not meaningful.
4997    * - If this needs to be called, it needs to be called before V8
4998    *   tries to make use of its built-ins.
4999    * - To avoid unnecessary copies of data, V8 will point directly into the
5000    *   given data blob, so pretty please keep it around until V8 exit.
5001    * - Compression of the startup blob might be useful, but needs to
5002    *   handled entirely on the embedders' side.
5003    * - The call will abort if the data is invalid.
5004    */
5005   static void SetNativesDataBlob(StartupData* startup_blob);
5006   static void SetSnapshotDataBlob(StartupData* startup_blob);
5007 
5008   /**
5009    * Adds a message listener.
5010    *
5011    * The same message listener can be added more than once and in that
5012    * case it will be called more than once for each message.
5013    *
5014    * If data is specified, it will be passed to the callback when it is called.
5015    * Otherwise, the exception object will be passed to the callback instead.
5016    */
5017   static bool AddMessageListener(MessageCallback that,
5018                                  Handle<Value> data = Handle<Value>());
5019 
5020   /**
5021    * Remove all message listeners from the specified callback function.
5022    */
5023   static void RemoveMessageListeners(MessageCallback that);
5024 
5025   /**
5026    * Tells V8 to capture current stack trace when uncaught exception occurs
5027    * and report it to the message listeners. The option is off by default.
5028    */
5029   static void SetCaptureStackTraceForUncaughtExceptions(
5030       bool capture,
5031       int frame_limit = 10,
5032       StackTrace::StackTraceOptions options = StackTrace::kOverview);
5033 
5034   /**
5035    * Sets V8 flags from a string.
5036    */
5037   static void SetFlagsFromString(const char* str, int length);
5038 
5039   /**
5040    * Sets V8 flags from the command line.
5041    */
5042   static void SetFlagsFromCommandLine(int* argc,
5043                                       char** argv,
5044                                       bool remove_flags);
5045 
5046   /** Get the version string. */
5047   static const char* GetVersion();
5048 
5049   /** Callback function for reporting failed access checks.*/
5050   static void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
5051 
5052   /**
5053    * Enables the host application to receive a notification before a
5054    * garbage collection.  Allocations are not allowed in the
5055    * callback function, you therefore cannot manipulate objects (set
5056    * or delete properties for example) since it is possible such
5057    * operations will result in the allocation of objects. It is possible
5058    * to specify the GCType filter for your callback. But it is not possible to
5059    * register the same callback function two times with different
5060    * GCType filters.
5061    */
5062   static void AddGCPrologueCallback(
5063       GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
5064 
5065   /**
5066    * This function removes callback which was installed by
5067    * AddGCPrologueCallback function.
5068    */
5069   static void RemoveGCPrologueCallback(GCPrologueCallback callback);
5070 
5071   /**
5072    * Enables the host application to receive a notification after a
5073    * garbage collection.  Allocations are not allowed in the
5074    * callback function, you therefore cannot manipulate objects (set
5075    * or delete properties for example) since it is possible such
5076    * operations will result in the allocation of objects. It is possible
5077    * to specify the GCType filter for your callback. But it is not possible to
5078    * register the same callback function two times with different
5079    * GCType filters.
5080    */
5081   static void AddGCEpilogueCallback(
5082       GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
5083 
5084   /**
5085    * This function removes callback which was installed by
5086    * AddGCEpilogueCallback function.
5087    */
5088   static void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
5089 
5090   /**
5091    * Enables the host application to provide a mechanism to be notified
5092    * and perform custom logging when V8 Allocates Executable Memory.
5093    */
5094   static void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
5095                                           ObjectSpace space,
5096                                           AllocationAction action);
5097 
5098   /**
5099    * Removes callback that was installed by AddMemoryAllocationCallback.
5100    */
5101   static void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
5102 
5103   /**
5104    * Initializes V8. This function needs to be called before the first Isolate
5105    * is created. It always returns true.
5106    */
5107   static bool Initialize();
5108 
5109   /**
5110    * Allows the host application to provide a callback which can be used
5111    * as a source of entropy for random number generators.
5112    */
5113   static void SetEntropySource(EntropySource source);
5114 
5115   /**
5116    * Allows the host application to provide a callback that allows v8 to
5117    * cooperate with a profiler that rewrites return addresses on stack.
5118    */
5119   static void SetReturnAddressLocationResolver(
5120       ReturnAddressLocationResolver return_address_resolver);
5121 
5122   /**
5123    * Forcefully terminate the current thread of JavaScript execution
5124    * in the given isolate.
5125    *
5126    * This method can be used by any thread even if that thread has not
5127    * acquired the V8 lock with a Locker object.
5128    *
5129    * \param isolate The isolate in which to terminate the current JS execution.
5130    */
5131   static void TerminateExecution(Isolate* isolate);
5132 
5133   /**
5134    * Is V8 terminating JavaScript execution.
5135    *
5136    * Returns true if JavaScript execution is currently terminating
5137    * because of a call to TerminateExecution.  In that case there are
5138    * still JavaScript frames on the stack and the termination
5139    * exception is still active.
5140    *
5141    * \param isolate The isolate in which to check.
5142    */
5143   static bool IsExecutionTerminating(Isolate* isolate = NULL);
5144 
5145   /**
5146    * Resume execution capability in the given isolate, whose execution
5147    * was previously forcefully terminated using TerminateExecution().
5148    *
5149    * When execution is forcefully terminated using TerminateExecution(),
5150    * the isolate can not resume execution until all JavaScript frames
5151    * have propagated the uncatchable exception which is generated.  This
5152    * method allows the program embedding the engine to handle the
5153    * termination event and resume execution capability, even if
5154    * JavaScript frames remain on the stack.
5155    *
5156    * This method can be used by any thread even if that thread has not
5157    * acquired the V8 lock with a Locker object.
5158    *
5159    * \param isolate The isolate in which to resume execution capability.
5160    */
5161   static void CancelTerminateExecution(Isolate* isolate);
5162 
5163   /**
5164    * Releases any resources used by v8 and stops any utility threads
5165    * that may be running.  Note that disposing v8 is permanent, it
5166    * cannot be reinitialized.
5167    *
5168    * It should generally not be necessary to dispose v8 before exiting
5169    * a process, this should happen automatically.  It is only necessary
5170    * to use if the process needs the resources taken up by v8.
5171    */
5172   static bool Dispose();
5173 
5174   /**
5175    * Iterates through all external resources referenced from current isolate
5176    * heap.  GC is not invoked prior to iterating, therefore there is no
5177    * guarantee that visited objects are still alive.
5178    */
5179   static void VisitExternalResources(ExternalResourceVisitor* visitor);
5180 
5181   /**
5182    * Iterates through all the persistent handles in the current isolate's heap
5183    * that have class_ids.
5184    */
5185   static void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor);
5186 
5187   /**
5188    * Iterates through all the persistent handles in the current isolate's heap
5189    * that have class_ids and are candidates to be marked as partially dependent
5190    * handles. This will visit handles to young objects created since the last
5191    * garbage collection but is free to visit an arbitrary superset of these
5192    * objects.
5193    */
5194   static void VisitHandlesForPartialDependence(
5195       Isolate* isolate, PersistentHandleVisitor* visitor);
5196 
5197   /**
5198    * Initialize the ICU library bundled with V8. The embedder should only
5199    * invoke this method when using the bundled ICU. Returns true on success.
5200    *
5201    * If V8 was compiled with the ICU data in an external file, the location
5202    * of the data file has to be provided.
5203    */
5204   static bool InitializeICU(const char* icu_data_file = NULL);
5205 
5206   /**
5207    * Sets the v8::Platform to use. This should be invoked before V8 is
5208    * initialized.
5209    */
5210   static void InitializePlatform(Platform* platform);
5211 
5212   /**
5213    * Clears all references to the v8::Platform. This should be invoked after
5214    * V8 was disposed.
5215    */
5216   static void ShutdownPlatform();
5217 
5218  private:
5219   V8();
5220 
5221   static internal::Object** GlobalizeReference(internal::Isolate* isolate,
5222                                                internal::Object** handle);
5223   static internal::Object** CopyPersistent(internal::Object** handle);
5224   static void DisposeGlobal(internal::Object** global_handle);
5225   typedef WeakCallbackData<Value, void>::Callback WeakCallback;
5226   static void MakeWeak(internal::Object** global_handle,
5227                        void* data,
5228                        WeakCallback weak_callback);
5229   static void* ClearWeak(internal::Object** global_handle);
5230   static void Eternalize(Isolate* isolate,
5231                          Value* handle,
5232                          int* index);
5233   static Local<Value> GetEternal(Isolate* isolate, int index);
5234 
5235   template <class T> friend class Handle;
5236   template <class T> friend class Local;
5237   template <class T> friend class Eternal;
5238   template <class T> friend class PersistentBase;
5239   template <class T, class M> friend class Persistent;
5240   friend class Context;
5241 };
5242 
5243 
5244 /**
5245  * An external exception handler.
5246  */
5247 class V8_EXPORT TryCatch {
5248  public:
5249   /**
5250    * Creates a new try/catch block and registers it with v8.  Note that
5251    * all TryCatch blocks should be stack allocated because the memory
5252    * location itself is compared against JavaScript try/catch blocks.
5253    */
5254   TryCatch();
5255 
5256   /**
5257    * Unregisters and deletes this try/catch block.
5258    */
5259   ~TryCatch();
5260 
5261   /**
5262    * Returns true if an exception has been caught by this try/catch block.
5263    */
5264   bool HasCaught() const;
5265 
5266   /**
5267    * For certain types of exceptions, it makes no sense to continue execution.
5268    *
5269    * If CanContinue returns false, the correct action is to perform any C++
5270    * cleanup needed and then return.  If CanContinue returns false and
5271    * HasTerminated returns true, it is possible to call
5272    * CancelTerminateExecution in order to continue calling into the engine.
5273    */
5274   bool CanContinue() const;
5275 
5276   /**
5277    * Returns true if an exception has been caught due to script execution
5278    * being terminated.
5279    *
5280    * There is no JavaScript representation of an execution termination
5281    * exception.  Such exceptions are thrown when the TerminateExecution
5282    * methods are called to terminate a long-running script.
5283    *
5284    * If such an exception has been thrown, HasTerminated will return true,
5285    * indicating that it is possible to call CancelTerminateExecution in order
5286    * to continue calling into the engine.
5287    */
5288   bool HasTerminated() const;
5289 
5290   /**
5291    * Throws the exception caught by this TryCatch in a way that avoids
5292    * it being caught again by this same TryCatch.  As with ThrowException
5293    * it is illegal to execute any JavaScript operations after calling
5294    * ReThrow; the caller must return immediately to where the exception
5295    * is caught.
5296    */
5297   Handle<Value> ReThrow();
5298 
5299   /**
5300    * Returns the exception caught by this try/catch block.  If no exception has
5301    * been caught an empty handle is returned.
5302    *
5303    * The returned handle is valid until this TryCatch block has been destroyed.
5304    */
5305   Local<Value> Exception() const;
5306 
5307   /**
5308    * Returns the .stack property of the thrown object.  If no .stack
5309    * property is present an empty handle is returned.
5310    */
5311   Local<Value> StackTrace() const;
5312 
5313   /**
5314    * Returns the message associated with this exception.  If there is
5315    * no message associated an empty handle is returned.
5316    *
5317    * The returned handle is valid until this TryCatch block has been
5318    * destroyed.
5319    */
5320   Local<v8::Message> Message() const;
5321 
5322   /**
5323    * Clears any exceptions that may have been caught by this try/catch block.
5324    * After this method has been called, HasCaught() will return false. Cancels
5325    * the scheduled exception if it is caught and ReThrow() is not called before.
5326    *
5327    * It is not necessary to clear a try/catch block before using it again; if
5328    * another exception is thrown the previously caught exception will just be
5329    * overwritten.  However, it is often a good idea since it makes it easier
5330    * to determine which operation threw a given exception.
5331    */
5332   void Reset();
5333 
5334   /**
5335    * Set verbosity of the external exception handler.
5336    *
5337    * By default, exceptions that are caught by an external exception
5338    * handler are not reported.  Call SetVerbose with true on an
5339    * external exception handler to have exceptions caught by the
5340    * handler reported as if they were not caught.
5341    */
5342   void SetVerbose(bool value);
5343 
5344   /**
5345    * Set whether or not this TryCatch should capture a Message object
5346    * which holds source information about where the exception
5347    * occurred.  True by default.
5348    */
5349   void SetCaptureMessage(bool value);
5350 
5351   /**
5352    * There are cases when the raw address of C++ TryCatch object cannot be
5353    * used for comparisons with addresses into the JS stack. The cases are:
5354    * 1) ARM, ARM64 and MIPS simulators which have separate JS stack.
5355    * 2) Address sanitizer allocates local C++ object in the heap when
5356    *    UseAfterReturn mode is enabled.
5357    * This method returns address that can be used for comparisons with
5358    * addresses into the JS stack. When neither simulator nor ASAN's
5359    * UseAfterReturn is enabled, then the address returned will be the address
5360    * of the C++ try catch handler itself.
5361    */
JSStackComparableAddress(v8::TryCatch * handler)5362   static void* JSStackComparableAddress(v8::TryCatch* handler) {
5363     if (handler == NULL) return NULL;
5364     return handler->js_stack_comparable_address_;
5365   }
5366 
5367  private:
5368   void ResetInternal();
5369 
5370   // Make it hard to create heap-allocated TryCatch blocks.
5371   TryCatch(const TryCatch&);
5372   void operator=(const TryCatch&);
5373   void* operator new(size_t size);
5374   void operator delete(void*, size_t);
5375 
5376   v8::internal::Isolate* isolate_;
5377   v8::TryCatch* next_;
5378   void* exception_;
5379   void* message_obj_;
5380   void* message_script_;
5381   void* js_stack_comparable_address_;
5382   int message_start_pos_;
5383   int message_end_pos_;
5384   bool is_verbose_ : 1;
5385   bool can_continue_ : 1;
5386   bool capture_message_ : 1;
5387   bool rethrow_ : 1;
5388   bool has_terminated_ : 1;
5389 
5390   friend class v8::internal::Isolate;
5391 };
5392 
5393 
5394 // --- Context ---
5395 
5396 
5397 /**
5398  * A container for extension names.
5399  */
5400 class V8_EXPORT ExtensionConfiguration {
5401  public:
ExtensionConfiguration()5402   ExtensionConfiguration() : name_count_(0), names_(NULL) { }
ExtensionConfiguration(int name_count,const char * names[])5403   ExtensionConfiguration(int name_count, const char* names[])
5404       : name_count_(name_count), names_(names) { }
5405 
begin()5406   const char** begin() const { return &names_[0]; }
end()5407   const char** end()  const { return &names_[name_count_]; }
5408 
5409  private:
5410   const int name_count_;
5411   const char** names_;
5412 };
5413 
5414 
5415 /**
5416  * A sandboxed execution context with its own set of built-in objects
5417  * and functions.
5418  */
5419 class V8_EXPORT Context {
5420  public:
5421   /**
5422    * Returns the global proxy object.
5423    *
5424    * Global proxy object is a thin wrapper whose prototype points to actual
5425    * context's global object with the properties like Object, etc. This is done
5426    * that way for security reasons (for more details see
5427    * https://wiki.mozilla.org/Gecko:SplitWindow).
5428    *
5429    * Please note that changes to global proxy object prototype most probably
5430    * would break VM---v8 expects only global object as a prototype of global
5431    * proxy object.
5432    */
5433   Local<Object> Global();
5434 
5435   /**
5436    * Detaches the global object from its context before
5437    * the global object can be reused to create a new context.
5438    */
5439   void DetachGlobal();
5440 
5441   /**
5442    * Creates a new context and returns a handle to the newly allocated
5443    * context.
5444    *
5445    * \param isolate The isolate in which to create the context.
5446    *
5447    * \param extensions An optional extension configuration containing
5448    * the extensions to be installed in the newly created context.
5449    *
5450    * \param global_template An optional object template from which the
5451    * global object for the newly created context will be created.
5452    *
5453    * \param global_object An optional global object to be reused for
5454    * the newly created context. This global object must have been
5455    * created by a previous call to Context::New with the same global
5456    * template. The state of the global object will be completely reset
5457    * and only object identify will remain.
5458    */
5459   static Local<Context> New(
5460       Isolate* isolate,
5461       ExtensionConfiguration* extensions = NULL,
5462       Handle<ObjectTemplate> global_template = Handle<ObjectTemplate>(),
5463       Handle<Value> global_object = Handle<Value>());
5464 
5465   /**
5466    * Sets the security token for the context.  To access an object in
5467    * another context, the security tokens must match.
5468    */
5469   void SetSecurityToken(Handle<Value> token);
5470 
5471   /** Restores the security token to the default value. */
5472   void UseDefaultSecurityToken();
5473 
5474   /** Returns the security token of this context.*/
5475   Handle<Value> GetSecurityToken();
5476 
5477   /**
5478    * Enter this context.  After entering a context, all code compiled
5479    * and run is compiled and run in this context.  If another context
5480    * is already entered, this old context is saved so it can be
5481    * restored when the new context is exited.
5482    */
5483   void Enter();
5484 
5485   /**
5486    * Exit this context.  Exiting the current context restores the
5487    * context that was in place when entering the current context.
5488    */
5489   void Exit();
5490 
5491   /** Returns an isolate associated with a current context. */
5492   v8::Isolate* GetIsolate();
5493 
5494   /**
5495    * Gets the embedder data with the given index, which must have been set by a
5496    * previous call to SetEmbedderData with the same index. Note that index 0
5497    * currently has a special meaning for Chrome's debugger.
5498    */
5499   V8_INLINE Local<Value> GetEmbedderData(int index);
5500 
5501   /**
5502    * Sets the embedder data with the given index, growing the data as
5503    * needed. Note that index 0 currently has a special meaning for Chrome's
5504    * debugger.
5505    */
5506   void SetEmbedderData(int index, Handle<Value> value);
5507 
5508   /**
5509    * Gets a 2-byte-aligned native pointer from the embedder data with the given
5510    * index, which must have bees set by a previous call to
5511    * SetAlignedPointerInEmbedderData with the same index. Note that index 0
5512    * currently has a special meaning for Chrome's debugger.
5513    */
5514   V8_INLINE void* GetAlignedPointerFromEmbedderData(int index);
5515 
5516   /**
5517    * Sets a 2-byte-aligned native pointer in the embedder data with the given
5518    * index, growing the data as needed. Note that index 0 currently has a
5519    * special meaning for Chrome's debugger.
5520    */
5521   void SetAlignedPointerInEmbedderData(int index, void* value);
5522 
5523   /**
5524    * Control whether code generation from strings is allowed. Calling
5525    * this method with false will disable 'eval' and the 'Function'
5526    * constructor for code running in this context. If 'eval' or the
5527    * 'Function' constructor are used an exception will be thrown.
5528    *
5529    * If code generation from strings is not allowed the
5530    * V8::AllowCodeGenerationFromStrings callback will be invoked if
5531    * set before blocking the call to 'eval' or the 'Function'
5532    * constructor. If that callback returns true, the call will be
5533    * allowed, otherwise an exception will be thrown. If no callback is
5534    * set an exception will be thrown.
5535    */
5536   void AllowCodeGenerationFromStrings(bool allow);
5537 
5538   /**
5539    * Returns true if code generation from strings is allowed for the context.
5540    * For more details see AllowCodeGenerationFromStrings(bool) documentation.
5541    */
5542   bool IsCodeGenerationFromStringsAllowed();
5543 
5544   /**
5545    * Sets the error description for the exception that is thrown when
5546    * code generation from strings is not allowed and 'eval' or the 'Function'
5547    * constructor are called.
5548    */
5549   void SetErrorMessageForCodeGenerationFromStrings(Handle<String> message);
5550 
5551   /**
5552    * Stack-allocated class which sets the execution context for all
5553    * operations executed within a local scope.
5554    */
5555   class Scope {
5556    public:
Scope(Handle<Context> context)5557     explicit V8_INLINE Scope(Handle<Context> context) : context_(context) {
5558       context_->Enter();
5559     }
~Scope()5560     V8_INLINE ~Scope() { context_->Exit(); }
5561 
5562    private:
5563     Handle<Context> context_;
5564   };
5565 
5566  private:
5567   friend class Value;
5568   friend class Script;
5569   friend class Object;
5570   friend class Function;
5571 
5572   Local<Value> SlowGetEmbedderData(int index);
5573   void* SlowGetAlignedPointerFromEmbedderData(int index);
5574 };
5575 
5576 
5577 /**
5578  * Multiple threads in V8 are allowed, but only one thread at a time is allowed
5579  * to use any given V8 isolate, see the comments in the Isolate class. The
5580  * definition of 'using a V8 isolate' includes accessing handles or holding onto
5581  * object pointers obtained from V8 handles while in the particular V8 isolate.
5582  * It is up to the user of V8 to ensure, perhaps with locking, that this
5583  * constraint is not violated. In addition to any other synchronization
5584  * mechanism that may be used, the v8::Locker and v8::Unlocker classes must be
5585  * used to signal thead switches to V8.
5586  *
5587  * v8::Locker is a scoped lock object. While it's active, i.e. between its
5588  * construction and destruction, the current thread is allowed to use the locked
5589  * isolate. V8 guarantees that an isolate can be locked by at most one thread at
5590  * any time. In other words, the scope of a v8::Locker is a critical section.
5591  *
5592  * Sample usage:
5593 * \code
5594  * ...
5595  * {
5596  *   v8::Locker locker(isolate);
5597  *   v8::Isolate::Scope isolate_scope(isolate);
5598  *   ...
5599  *   // Code using V8 and isolate goes here.
5600  *   ...
5601  * } // Destructor called here
5602  * \endcode
5603  *
5604  * If you wish to stop using V8 in a thread A you can do this either by
5605  * destroying the v8::Locker object as above or by constructing a v8::Unlocker
5606  * object:
5607  *
5608  * \code
5609  * {
5610  *   isolate->Exit();
5611  *   v8::Unlocker unlocker(isolate);
5612  *   ...
5613  *   // Code not using V8 goes here while V8 can run in another thread.
5614  *   ...
5615  * } // Destructor called here.
5616  * isolate->Enter();
5617  * \endcode
5618  *
5619  * The Unlocker object is intended for use in a long-running callback from V8,
5620  * where you want to release the V8 lock for other threads to use.
5621  *
5622  * The v8::Locker is a recursive lock, i.e. you can lock more than once in a
5623  * given thread. This can be useful if you have code that can be called either
5624  * from code that holds the lock or from code that does not. The Unlocker is
5625  * not recursive so you can not have several Unlockers on the stack at once, and
5626  * you can not use an Unlocker in a thread that is not inside a Locker's scope.
5627  *
5628  * An unlocker will unlock several lockers if it has to and reinstate the
5629  * correct depth of locking on its destruction, e.g.:
5630  *
5631  * \code
5632  * // V8 not locked.
5633  * {
5634  *   v8::Locker locker(isolate);
5635  *   Isolate::Scope isolate_scope(isolate);
5636  *   // V8 locked.
5637  *   {
5638  *     v8::Locker another_locker(isolate);
5639  *     // V8 still locked (2 levels).
5640  *     {
5641  *       isolate->Exit();
5642  *       v8::Unlocker unlocker(isolate);
5643  *       // V8 not locked.
5644  *     }
5645  *     isolate->Enter();
5646  *     // V8 locked again (2 levels).
5647  *   }
5648  *   // V8 still locked (1 level).
5649  * }
5650  * // V8 Now no longer locked.
5651  * \endcode
5652  */
5653 class V8_EXPORT Unlocker {
5654  public:
5655   /**
5656    * Initialize Unlocker for a given Isolate.
5657    */
Unlocker(Isolate * isolate)5658   V8_INLINE explicit Unlocker(Isolate* isolate) { Initialize(isolate); }
5659 
5660   ~Unlocker();
5661  private:
5662   void Initialize(Isolate* isolate);
5663 
5664   internal::Isolate* isolate_;
5665 };
5666 
5667 
5668 class V8_EXPORT Locker {
5669  public:
5670   /**
5671    * Initialize Locker for a given Isolate.
5672    */
Locker(Isolate * isolate)5673   V8_INLINE explicit Locker(Isolate* isolate) { Initialize(isolate); }
5674 
5675   ~Locker();
5676 
5677   /**
5678    * Returns whether or not the locker for a given isolate, is locked by the
5679    * current thread.
5680    */
5681   static bool IsLocked(Isolate* isolate);
5682 
5683   /**
5684    * Returns whether v8::Locker is being used by this V8 instance.
5685    */
5686   static bool IsActive();
5687 
5688  private:
5689   void Initialize(Isolate* isolate);
5690 
5691   bool has_lock_;
5692   bool top_level_;
5693   internal::Isolate* isolate_;
5694 
5695   static bool active_;
5696 
5697   // Disallow copying and assigning.
5698   Locker(const Locker&);
5699   void operator=(const Locker&);
5700 };
5701 
5702 
5703 // --- Implementation ---
5704 
5705 
5706 namespace internal {
5707 
5708 const int kApiPointerSize = sizeof(void*);  // NOLINT
5709 const int kApiIntSize = sizeof(int);  // NOLINT
5710 const int kApiInt64Size = sizeof(int64_t);  // NOLINT
5711 
5712 // Tag information for HeapObject.
5713 const int kHeapObjectTag = 1;
5714 const int kHeapObjectTagSize = 2;
5715 const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
5716 
5717 // Tag information for Smi.
5718 const int kSmiTag = 0;
5719 const int kSmiTagSize = 1;
5720 const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
5721 
5722 template <size_t ptr_size> struct SmiTagging;
5723 
5724 template<int kSmiShiftSize>
IntToSmi(int value)5725 V8_INLINE internal::Object* IntToSmi(int value) {
5726   int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
5727   uintptr_t tagged_value =
5728       (static_cast<uintptr_t>(value) << smi_shift_bits) | kSmiTag;
5729   return reinterpret_cast<internal::Object*>(tagged_value);
5730 }
5731 
5732 // Smi constants for 32-bit systems.
5733 template <> struct SmiTagging<4> {
5734   enum { kSmiShiftSize = 0, kSmiValueSize = 31 };
5735   static int SmiShiftSize() { return kSmiShiftSize; }
5736   static int SmiValueSize() { return kSmiValueSize; }
5737   V8_INLINE static int SmiToInt(const internal::Object* value) {
5738     int shift_bits = kSmiTagSize + kSmiShiftSize;
5739     // Throw away top 32 bits and shift down (requires >> to be sign extending).
5740     return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
5741   }
5742   V8_INLINE static internal::Object* IntToSmi(int value) {
5743     return internal::IntToSmi<kSmiShiftSize>(value);
5744   }
5745   V8_INLINE static bool IsValidSmi(intptr_t value) {
5746     // To be representable as an tagged small integer, the two
5747     // most-significant bits of 'value' must be either 00 or 11 due to
5748     // sign-extension. To check this we add 01 to the two
5749     // most-significant bits, and check if the most-significant bit is 0
5750     //
5751     // CAUTION: The original code below:
5752     // bool result = ((value + 0x40000000) & 0x80000000) == 0;
5753     // may lead to incorrect results according to the C language spec, and
5754     // in fact doesn't work correctly with gcc4.1.1 in some cases: The
5755     // compiler may produce undefined results in case of signed integer
5756     // overflow. The computation must be done w/ unsigned ints.
5757     return static_cast<uintptr_t>(value + 0x40000000U) < 0x80000000U;
5758   }
5759 };
5760 
5761 // Smi constants for 64-bit systems.
5762 template <> struct SmiTagging<8> {
5763   enum { kSmiShiftSize = 31, kSmiValueSize = 32 };
5764   static int SmiShiftSize() { return kSmiShiftSize; }
5765   static int SmiValueSize() { return kSmiValueSize; }
5766   V8_INLINE static int SmiToInt(const internal::Object* value) {
5767     int shift_bits = kSmiTagSize + kSmiShiftSize;
5768     // Shift down and throw away top 32 bits.
5769     return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
5770   }
5771   V8_INLINE static internal::Object* IntToSmi(int value) {
5772     return internal::IntToSmi<kSmiShiftSize>(value);
5773   }
5774   V8_INLINE static bool IsValidSmi(intptr_t value) {
5775     // To be representable as a long smi, the value must be a 32-bit integer.
5776     return (value == static_cast<int32_t>(value));
5777   }
5778 };
5779 
5780 typedef SmiTagging<kApiPointerSize> PlatformSmiTagging;
5781 const int kSmiShiftSize = PlatformSmiTagging::kSmiShiftSize;
5782 const int kSmiValueSize = PlatformSmiTagging::kSmiValueSize;
5783 V8_INLINE static bool SmiValuesAre31Bits() { return kSmiValueSize == 31; }
5784 V8_INLINE static bool SmiValuesAre32Bits() { return kSmiValueSize == 32; }
5785 
5786 /**
5787  * This class exports constants and functionality from within v8 that
5788  * is necessary to implement inline functions in the v8 api.  Don't
5789  * depend on functions and constants defined here.
5790  */
5791 class Internals {
5792  public:
5793   // These values match non-compiler-dependent values defined within
5794   // the implementation of v8.
5795   static const int kHeapObjectMapOffset = 0;
5796   static const int kMapInstanceTypeAndBitFieldOffset =
5797       1 * kApiPointerSize + kApiIntSize;
5798   static const int kStringResourceOffset = 3 * kApiPointerSize;
5799 
5800   static const int kOddballKindOffset = 3 * kApiPointerSize;
5801   static const int kForeignAddressOffset = kApiPointerSize;
5802   static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
5803   static const int kFixedArrayHeaderSize = 2 * kApiPointerSize;
5804   static const int kContextHeaderSize = 2 * kApiPointerSize;
5805   static const int kContextEmbedderDataIndex = 95;
5806   static const int kFullStringRepresentationMask = 0x07;
5807   static const int kStringEncodingMask = 0x4;
5808   static const int kExternalTwoByteRepresentationTag = 0x02;
5809   static const int kExternalOneByteRepresentationTag = 0x06;
5810 
5811   static const int kIsolateEmbedderDataOffset = 0 * kApiPointerSize;
5812   static const int kAmountOfExternalAllocatedMemoryOffset =
5813       4 * kApiPointerSize;
5814   static const int kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset =
5815       kAmountOfExternalAllocatedMemoryOffset + kApiInt64Size;
5816   static const int kIsolateRootsOffset =
5817       kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset + kApiInt64Size +
5818       kApiPointerSize;
5819   static const int kUndefinedValueRootIndex = 5;
5820   static const int kNullValueRootIndex = 7;
5821   static const int kTrueValueRootIndex = 8;
5822   static const int kFalseValueRootIndex = 9;
5823   static const int kEmptyStringRootIndex = 164;
5824 
5825   // The external allocation limit should be below 256 MB on all architectures
5826   // to avoid that resource-constrained embedders run low on memory.
5827   static const int kExternalAllocationLimit = 192 * 1024 * 1024;
5828 
5829   static const int kNodeClassIdOffset = 1 * kApiPointerSize;
5830   static const int kNodeFlagsOffset = 1 * kApiPointerSize + 3;
5831   static const int kNodeStateMask = 0xf;
5832   static const int kNodeStateIsWeakValue = 2;
5833   static const int kNodeStateIsPendingValue = 3;
5834   static const int kNodeStateIsNearDeathValue = 4;
5835   static const int kNodeIsIndependentShift = 4;
5836   static const int kNodeIsPartiallyDependentShift = 5;
5837 
5838   static const int kJSObjectType = 0xbc;
5839   static const int kFirstNonstringType = 0x80;
5840   static const int kOddballType = 0x83;
5841   static const int kForeignType = 0x88;
5842 
5843   static const int kUndefinedOddballKind = 5;
5844   static const int kNullOddballKind = 3;
5845 
5846   static const uint32_t kNumIsolateDataSlots = 4;
5847 
5848   V8_EXPORT static void CheckInitializedImpl(v8::Isolate* isolate);
5849   V8_INLINE static void CheckInitialized(v8::Isolate* isolate) {
5850 #ifdef V8_ENABLE_CHECKS
5851     CheckInitializedImpl(isolate);
5852 #endif
5853   }
5854 
5855   V8_INLINE static bool HasHeapObjectTag(const internal::Object* value) {
5856     return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
5857             kHeapObjectTag);
5858   }
5859 
5860   V8_INLINE static int SmiValue(const internal::Object* value) {
5861     return PlatformSmiTagging::SmiToInt(value);
5862   }
5863 
5864   V8_INLINE static internal::Object* IntToSmi(int value) {
5865     return PlatformSmiTagging::IntToSmi(value);
5866   }
5867 
5868   V8_INLINE static bool IsValidSmi(intptr_t value) {
5869     return PlatformSmiTagging::IsValidSmi(value);
5870   }
5871 
5872   V8_INLINE static int GetInstanceType(const internal::Object* obj) {
5873     typedef internal::Object O;
5874     O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
5875     // Map::InstanceType is defined so that it will always be loaded into
5876     // the LS 8 bits of one 16-bit word, regardless of endianess.
5877     return ReadField<uint16_t>(map, kMapInstanceTypeAndBitFieldOffset) & 0xff;
5878   }
5879 
5880   V8_INLINE static int GetOddballKind(const internal::Object* obj) {
5881     typedef internal::Object O;
5882     return SmiValue(ReadField<O*>(obj, kOddballKindOffset));
5883   }
5884 
5885   V8_INLINE static bool IsExternalTwoByteString(int instance_type) {
5886     int representation = (instance_type & kFullStringRepresentationMask);
5887     return representation == kExternalTwoByteRepresentationTag;
5888   }
5889 
5890   V8_INLINE static uint8_t GetNodeFlag(internal::Object** obj, int shift) {
5891       uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
5892       return *addr & static_cast<uint8_t>(1U << shift);
5893   }
5894 
5895   V8_INLINE static void UpdateNodeFlag(internal::Object** obj,
5896                                        bool value, int shift) {
5897       uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
5898       uint8_t mask = static_cast<uint8_t>(1U << shift);
5899       *addr = static_cast<uint8_t>((*addr & ~mask) | (value << shift));
5900   }
5901 
5902   V8_INLINE static uint8_t GetNodeState(internal::Object** obj) {
5903     uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
5904     return *addr & kNodeStateMask;
5905   }
5906 
5907   V8_INLINE static void UpdateNodeState(internal::Object** obj,
5908                                         uint8_t value) {
5909     uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
5910     *addr = static_cast<uint8_t>((*addr & ~kNodeStateMask) | value);
5911   }
5912 
5913   V8_INLINE static void SetEmbedderData(v8::Isolate* isolate,
5914                                         uint32_t slot,
5915                                         void* data) {
5916     uint8_t *addr = reinterpret_cast<uint8_t *>(isolate) +
5917                     kIsolateEmbedderDataOffset + slot * kApiPointerSize;
5918     *reinterpret_cast<void**>(addr) = data;
5919   }
5920 
5921   V8_INLINE static void* GetEmbedderData(const v8::Isolate* isolate,
5922                                          uint32_t slot) {
5923     const uint8_t* addr = reinterpret_cast<const uint8_t*>(isolate) +
5924         kIsolateEmbedderDataOffset + slot * kApiPointerSize;
5925     return *reinterpret_cast<void* const*>(addr);
5926   }
5927 
5928   V8_INLINE static internal::Object** GetRoot(v8::Isolate* isolate,
5929                                               int index) {
5930     uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) + kIsolateRootsOffset;
5931     return reinterpret_cast<internal::Object**>(addr + index * kApiPointerSize);
5932   }
5933 
5934   template <typename T>
5935   V8_INLINE static T ReadField(const internal::Object* ptr, int offset) {
5936     const uint8_t* addr =
5937         reinterpret_cast<const uint8_t*>(ptr) + offset - kHeapObjectTag;
5938     return *reinterpret_cast<const T*>(addr);
5939   }
5940 
5941   template <typename T>
5942   V8_INLINE static T ReadEmbedderData(const v8::Context* context, int index) {
5943     typedef internal::Object O;
5944     typedef internal::Internals I;
5945     O* ctx = *reinterpret_cast<O* const*>(context);
5946     int embedder_data_offset = I::kContextHeaderSize +
5947         (internal::kApiPointerSize * I::kContextEmbedderDataIndex);
5948     O* embedder_data = I::ReadField<O*>(ctx, embedder_data_offset);
5949     int value_offset =
5950         I::kFixedArrayHeaderSize + (internal::kApiPointerSize * index);
5951     return I::ReadField<T>(embedder_data, value_offset);
5952   }
5953 };
5954 
5955 }  // namespace internal
5956 
5957 
5958 template <class T>
5959 Local<T>::Local() : Handle<T>() { }
5960 
5961 
5962 template <class T>
5963 Local<T> Local<T>::New(Isolate* isolate, Handle<T> that) {
5964   return New(isolate, that.val_);
5965 }
5966 
5967 template <class T>
5968 Local<T> Local<T>::New(Isolate* isolate, const PersistentBase<T>& that) {
5969   return New(isolate, that.val_);
5970 }
5971 
5972 template <class T>
5973 Handle<T> Handle<T>::New(Isolate* isolate, T* that) {
5974   if (that == NULL) return Handle<T>();
5975   T* that_ptr = that;
5976   internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
5977   return Handle<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
5978       reinterpret_cast<internal::Isolate*>(isolate), *p)));
5979 }
5980 
5981 
5982 template <class T>
5983 Local<T> Local<T>::New(Isolate* isolate, T* that) {
5984   if (that == NULL) return Local<T>();
5985   T* that_ptr = that;
5986   internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
5987   return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
5988       reinterpret_cast<internal::Isolate*>(isolate), *p)));
5989 }
5990 
5991 
5992 template<class T>
5993 template<class S>
5994 void Eternal<T>::Set(Isolate* isolate, Local<S> handle) {
5995   TYPE_CHECK(T, S);
5996   V8::Eternalize(isolate, reinterpret_cast<Value*>(*handle), &this->index_);
5997 }
5998 
5999 
6000 template<class T>
6001 Local<T> Eternal<T>::Get(Isolate* isolate) {
6002   return Local<T>(reinterpret_cast<T*>(*V8::GetEternal(isolate, index_)));
6003 }
6004 
6005 
6006 template <class T>
6007 T* PersistentBase<T>::New(Isolate* isolate, T* that) {
6008   if (that == NULL) return NULL;
6009   internal::Object** p = reinterpret_cast<internal::Object**>(that);
6010   return reinterpret_cast<T*>(
6011       V8::GlobalizeReference(reinterpret_cast<internal::Isolate*>(isolate),
6012                              p));
6013 }
6014 
6015 
6016 template <class T, class M>
6017 template <class S, class M2>
6018 void Persistent<T, M>::Copy(const Persistent<S, M2>& that) {
6019   TYPE_CHECK(T, S);
6020   this->Reset();
6021   if (that.IsEmpty()) return;
6022   internal::Object** p = reinterpret_cast<internal::Object**>(that.val_);
6023   this->val_ = reinterpret_cast<T*>(V8::CopyPersistent(p));
6024   M::Copy(that, this);
6025 }
6026 
6027 
6028 template <class T>
6029 bool PersistentBase<T>::IsIndependent() const {
6030   typedef internal::Internals I;
6031   if (this->IsEmpty()) return false;
6032   return I::GetNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
6033                         I::kNodeIsIndependentShift);
6034 }
6035 
6036 
6037 template <class T>
6038 bool PersistentBase<T>::IsNearDeath() const {
6039   typedef internal::Internals I;
6040   if (this->IsEmpty()) return false;
6041   uint8_t node_state =
6042       I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_));
6043   return node_state == I::kNodeStateIsNearDeathValue ||
6044       node_state == I::kNodeStateIsPendingValue;
6045 }
6046 
6047 
6048 template <class T>
6049 bool PersistentBase<T>::IsWeak() const {
6050   typedef internal::Internals I;
6051   if (this->IsEmpty()) return false;
6052   return I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_)) ==
6053       I::kNodeStateIsWeakValue;
6054 }
6055 
6056 
6057 template <class T>
6058 void PersistentBase<T>::Reset() {
6059   if (this->IsEmpty()) return;
6060   V8::DisposeGlobal(reinterpret_cast<internal::Object**>(this->val_));
6061   val_ = 0;
6062 }
6063 
6064 
6065 template <class T>
6066 template <class S>
6067 void PersistentBase<T>::Reset(Isolate* isolate, const Handle<S>& other) {
6068   TYPE_CHECK(T, S);
6069   Reset();
6070   if (other.IsEmpty()) return;
6071   this->val_ = New(isolate, other.val_);
6072 }
6073 
6074 
6075 template <class T>
6076 template <class S>
6077 void PersistentBase<T>::Reset(Isolate* isolate,
6078                               const PersistentBase<S>& other) {
6079   TYPE_CHECK(T, S);
6080   Reset();
6081   if (other.IsEmpty()) return;
6082   this->val_ = New(isolate, other.val_);
6083 }
6084 
6085 
6086 template <class T>
6087 template <typename S, typename P>
6088 void PersistentBase<T>::SetWeak(
6089     P* parameter,
6090     typename WeakCallbackData<S, P>::Callback callback) {
6091   TYPE_CHECK(S, T);
6092   typedef typename WeakCallbackData<Value, void>::Callback Callback;
6093   V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_),
6094                parameter,
6095                reinterpret_cast<Callback>(callback));
6096 }
6097 
6098 
6099 template <class T>
6100 template <typename P>
6101 void PersistentBase<T>::SetWeak(
6102     P* parameter,
6103     typename WeakCallbackData<T, P>::Callback callback) {
6104   SetWeak<T, P>(parameter, callback);
6105 }
6106 
6107 
6108 template <class T>
6109 template<typename P>
6110 P* PersistentBase<T>::ClearWeak() {
6111   return reinterpret_cast<P*>(
6112     V8::ClearWeak(reinterpret_cast<internal::Object**>(this->val_)));
6113 }
6114 
6115 
6116 template <class T>
6117 void PersistentBase<T>::MarkIndependent() {
6118   typedef internal::Internals I;
6119   if (this->IsEmpty()) return;
6120   I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
6121                     true,
6122                     I::kNodeIsIndependentShift);
6123 }
6124 
6125 
6126 template <class T>
6127 void PersistentBase<T>::MarkPartiallyDependent() {
6128   typedef internal::Internals I;
6129   if (this->IsEmpty()) return;
6130   I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
6131                     true,
6132                     I::kNodeIsPartiallyDependentShift);
6133 }
6134 
6135 
6136 template <class T, class M>
6137 T* Persistent<T, M>::ClearAndLeak() {
6138   T* old;
6139   old = this->val_;
6140   this->val_ = NULL;
6141   return old;
6142 }
6143 
6144 
6145 template <class T>
6146 void PersistentBase<T>::SetWrapperClassId(uint16_t class_id) {
6147   typedef internal::Internals I;
6148   if (this->IsEmpty()) return;
6149   internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
6150   uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
6151   *reinterpret_cast<uint16_t*>(addr) = class_id;
6152 }
6153 
6154 
6155 template <class T>
6156 uint16_t PersistentBase<T>::WrapperClassId() const {
6157   typedef internal::Internals I;
6158   if (this->IsEmpty()) return 0;
6159   internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
6160   uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
6161   return *reinterpret_cast<uint16_t*>(addr);
6162 }
6163 
6164 
6165 template<typename T>
6166 ReturnValue<T>::ReturnValue(internal::Object** slot) : value_(slot) {}
6167 
6168 template<typename T>
6169 template<typename S>
6170 void ReturnValue<T>::Set(const Persistent<S>& handle) {
6171   TYPE_CHECK(T, S);
6172   if (V8_UNLIKELY(handle.IsEmpty())) {
6173     *value_ = GetDefaultValue();
6174   } else {
6175     *value_ = *reinterpret_cast<internal::Object**>(*handle);
6176   }
6177 }
6178 
6179 template<typename T>
6180 template<typename S>
6181 void ReturnValue<T>::Set(const Handle<S> handle) {
6182   TYPE_CHECK(T, S);
6183   if (V8_UNLIKELY(handle.IsEmpty())) {
6184     *value_ = GetDefaultValue();
6185   } else {
6186     *value_ = *reinterpret_cast<internal::Object**>(*handle);
6187   }
6188 }
6189 
6190 template<typename T>
6191 void ReturnValue<T>::Set(double i) {
6192   TYPE_CHECK(T, Number);
6193   Set(Number::New(GetIsolate(), i));
6194 }
6195 
6196 template<typename T>
6197 void ReturnValue<T>::Set(int32_t i) {
6198   TYPE_CHECK(T, Integer);
6199   typedef internal::Internals I;
6200   if (V8_LIKELY(I::IsValidSmi(i))) {
6201     *value_ = I::IntToSmi(i);
6202     return;
6203   }
6204   Set(Integer::New(GetIsolate(), i));
6205 }
6206 
6207 template<typename T>
6208 void ReturnValue<T>::Set(uint32_t i) {
6209   TYPE_CHECK(T, Integer);
6210   // Can't simply use INT32_MAX here for whatever reason.
6211   bool fits_into_int32_t = (i & (1U << 31)) == 0;
6212   if (V8_LIKELY(fits_into_int32_t)) {
6213     Set(static_cast<int32_t>(i));
6214     return;
6215   }
6216   Set(Integer::NewFromUnsigned(GetIsolate(), i));
6217 }
6218 
6219 template<typename T>
6220 void ReturnValue<T>::Set(bool value) {
6221   TYPE_CHECK(T, Boolean);
6222   typedef internal::Internals I;
6223   int root_index;
6224   if (value) {
6225     root_index = I::kTrueValueRootIndex;
6226   } else {
6227     root_index = I::kFalseValueRootIndex;
6228   }
6229   *value_ = *I::GetRoot(GetIsolate(), root_index);
6230 }
6231 
6232 template<typename T>
6233 void ReturnValue<T>::SetNull() {
6234   TYPE_CHECK(T, Primitive);
6235   typedef internal::Internals I;
6236   *value_ = *I::GetRoot(GetIsolate(), I::kNullValueRootIndex);
6237 }
6238 
6239 template<typename T>
6240 void ReturnValue<T>::SetUndefined() {
6241   TYPE_CHECK(T, Primitive);
6242   typedef internal::Internals I;
6243   *value_ = *I::GetRoot(GetIsolate(), I::kUndefinedValueRootIndex);
6244 }
6245 
6246 template<typename T>
6247 void ReturnValue<T>::SetEmptyString() {
6248   TYPE_CHECK(T, String);
6249   typedef internal::Internals I;
6250   *value_ = *I::GetRoot(GetIsolate(), I::kEmptyStringRootIndex);
6251 }
6252 
6253 template<typename T>
6254 Isolate* ReturnValue<T>::GetIsolate() {
6255   // Isolate is always the pointer below the default value on the stack.
6256   return *reinterpret_cast<Isolate**>(&value_[-2]);
6257 }
6258 
6259 template<typename T>
6260 template<typename S>
6261 void ReturnValue<T>::Set(S* whatever) {
6262   // Uncompilable to prevent inadvertent misuse.
6263   TYPE_CHECK(S*, Primitive);
6264 }
6265 
6266 template<typename T>
6267 internal::Object* ReturnValue<T>::GetDefaultValue() {
6268   // Default value is always the pointer below value_ on the stack.
6269   return value_[-1];
6270 }
6271 
6272 
6273 template<typename T>
6274 FunctionCallbackInfo<T>::FunctionCallbackInfo(internal::Object** implicit_args,
6275                                               internal::Object** values,
6276                                               int length,
6277                                               bool is_construct_call)
6278     : implicit_args_(implicit_args),
6279       values_(values),
6280       length_(length),
6281       is_construct_call_(is_construct_call) { }
6282 
6283 
6284 template<typename T>
6285 Local<Value> FunctionCallbackInfo<T>::operator[](int i) const {
6286   if (i < 0 || length_ <= i) return Local<Value>(*Undefined(GetIsolate()));
6287   return Local<Value>(reinterpret_cast<Value*>(values_ - i));
6288 }
6289 
6290 
6291 template<typename T>
6292 Local<Function> FunctionCallbackInfo<T>::Callee() const {
6293   return Local<Function>(reinterpret_cast<Function*>(
6294       &implicit_args_[kCalleeIndex]));
6295 }
6296 
6297 
6298 template<typename T>
6299 Local<Object> FunctionCallbackInfo<T>::This() const {
6300   return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
6301 }
6302 
6303 
6304 template<typename T>
6305 Local<Object> FunctionCallbackInfo<T>::Holder() const {
6306   return Local<Object>(reinterpret_cast<Object*>(
6307       &implicit_args_[kHolderIndex]));
6308 }
6309 
6310 
6311 template<typename T>
6312 Local<Value> FunctionCallbackInfo<T>::Data() const {
6313   return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
6314 }
6315 
6316 
6317 template<typename T>
6318 Isolate* FunctionCallbackInfo<T>::GetIsolate() const {
6319   return *reinterpret_cast<Isolate**>(&implicit_args_[kIsolateIndex]);
6320 }
6321 
6322 
6323 template<typename T>
6324 ReturnValue<T> FunctionCallbackInfo<T>::GetReturnValue() const {
6325   return ReturnValue<T>(&implicit_args_[kReturnValueIndex]);
6326 }
6327 
6328 
6329 template<typename T>
6330 bool FunctionCallbackInfo<T>::IsConstructCall() const {
6331   return is_construct_call_;
6332 }
6333 
6334 
6335 template<typename T>
6336 int FunctionCallbackInfo<T>::Length() const {
6337   return length_;
6338 }
6339 
6340 
6341 Handle<Value> ScriptOrigin::ResourceName() const {
6342   return resource_name_;
6343 }
6344 
6345 
6346 Handle<Integer> ScriptOrigin::ResourceLineOffset() const {
6347   return resource_line_offset_;
6348 }
6349 
6350 
6351 Handle<Integer> ScriptOrigin::ResourceColumnOffset() const {
6352   return resource_column_offset_;
6353 }
6354 
6355 
6356 Handle<Boolean> ScriptOrigin::ResourceIsSharedCrossOrigin() const {
6357   return resource_is_shared_cross_origin_;
6358 }
6359 
6360 
6361 Handle<Integer> ScriptOrigin::ScriptID() const {
6362   return script_id_;
6363 }
6364 
6365 
6366 ScriptCompiler::Source::Source(Local<String> string, const ScriptOrigin& origin,
6367                                CachedData* data)
6368     : source_string(string),
6369       resource_name(origin.ResourceName()),
6370       resource_line_offset(origin.ResourceLineOffset()),
6371       resource_column_offset(origin.ResourceColumnOffset()),
6372       resource_is_shared_cross_origin(origin.ResourceIsSharedCrossOrigin()),
6373       cached_data(data) {}
6374 
6375 
6376 ScriptCompiler::Source::Source(Local<String> string,
6377                                CachedData* data)
6378     : source_string(string), cached_data(data) {}
6379 
6380 
6381 ScriptCompiler::Source::~Source() {
6382   delete cached_data;
6383 }
6384 
6385 
6386 const ScriptCompiler::CachedData* ScriptCompiler::Source::GetCachedData()
6387     const {
6388   return cached_data;
6389 }
6390 
6391 
6392 Handle<Boolean> Boolean::New(Isolate* isolate, bool value) {
6393   return value ? True(isolate) : False(isolate);
6394 }
6395 
6396 
6397 void Template::Set(Isolate* isolate, const char* name, v8::Handle<Data> value) {
6398   Set(v8::String::NewFromUtf8(isolate, name), value);
6399 }
6400 
6401 
6402 Local<Value> Object::GetInternalField(int index) {
6403 #ifndef V8_ENABLE_CHECKS
6404   typedef internal::Object O;
6405   typedef internal::HeapObject HO;
6406   typedef internal::Internals I;
6407   O* obj = *reinterpret_cast<O**>(this);
6408   // Fast path: If the object is a plain JSObject, which is the common case, we
6409   // know where to find the internal fields and can return the value directly.
6410   if (I::GetInstanceType(obj) == I::kJSObjectType) {
6411     int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
6412     O* value = I::ReadField<O*>(obj, offset);
6413     O** result = HandleScope::CreateHandle(reinterpret_cast<HO*>(obj), value);
6414     return Local<Value>(reinterpret_cast<Value*>(result));
6415   }
6416 #endif
6417   return SlowGetInternalField(index);
6418 }
6419 
6420 
6421 void* Object::GetAlignedPointerFromInternalField(int index) {
6422 #ifndef V8_ENABLE_CHECKS
6423   typedef internal::Object O;
6424   typedef internal::Internals I;
6425   O* obj = *reinterpret_cast<O**>(this);
6426   // Fast path: If the object is a plain JSObject, which is the common case, we
6427   // know where to find the internal fields and can return the value directly.
6428   if (V8_LIKELY(I::GetInstanceType(obj) == I::kJSObjectType)) {
6429     int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
6430     return I::ReadField<void*>(obj, offset);
6431   }
6432 #endif
6433   return SlowGetAlignedPointerFromInternalField(index);
6434 }
6435 
6436 
6437 String* String::Cast(v8::Value* value) {
6438 #ifdef V8_ENABLE_CHECKS
6439   CheckCast(value);
6440 #endif
6441   return static_cast<String*>(value);
6442 }
6443 
6444 
6445 Local<String> String::Empty(Isolate* isolate) {
6446   typedef internal::Object* S;
6447   typedef internal::Internals I;
6448   I::CheckInitialized(isolate);
6449   S* slot = I::GetRoot(isolate, I::kEmptyStringRootIndex);
6450   return Local<String>(reinterpret_cast<String*>(slot));
6451 }
6452 
6453 
6454 String::ExternalStringResource* String::GetExternalStringResource() const {
6455   typedef internal::Object O;
6456   typedef internal::Internals I;
6457   O* obj = *reinterpret_cast<O* const*>(this);
6458   String::ExternalStringResource* result;
6459   if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
6460     void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
6461     result = reinterpret_cast<String::ExternalStringResource*>(value);
6462   } else {
6463     result = NULL;
6464   }
6465 #ifdef V8_ENABLE_CHECKS
6466   VerifyExternalStringResource(result);
6467 #endif
6468   return result;
6469 }
6470 
6471 
6472 String::ExternalStringResourceBase* String::GetExternalStringResourceBase(
6473     String::Encoding* encoding_out) const {
6474   typedef internal::Object O;
6475   typedef internal::Internals I;
6476   O* obj = *reinterpret_cast<O* const*>(this);
6477   int type = I::GetInstanceType(obj) & I::kFullStringRepresentationMask;
6478   *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
6479   ExternalStringResourceBase* resource = NULL;
6480   if (type == I::kExternalOneByteRepresentationTag ||
6481       type == I::kExternalTwoByteRepresentationTag) {
6482     void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
6483     resource = static_cast<ExternalStringResourceBase*>(value);
6484   }
6485 #ifdef V8_ENABLE_CHECKS
6486     VerifyExternalStringResourceBase(resource, *encoding_out);
6487 #endif
6488   return resource;
6489 }
6490 
6491 
6492 bool Value::IsUndefined() const {
6493 #ifdef V8_ENABLE_CHECKS
6494   return FullIsUndefined();
6495 #else
6496   return QuickIsUndefined();
6497 #endif
6498 }
6499 
6500 bool Value::QuickIsUndefined() const {
6501   typedef internal::Object O;
6502   typedef internal::Internals I;
6503   O* obj = *reinterpret_cast<O* const*>(this);
6504   if (!I::HasHeapObjectTag(obj)) return false;
6505   if (I::GetInstanceType(obj) != I::kOddballType) return false;
6506   return (I::GetOddballKind(obj) == I::kUndefinedOddballKind);
6507 }
6508 
6509 
6510 bool Value::IsNull() const {
6511 #ifdef V8_ENABLE_CHECKS
6512   return FullIsNull();
6513 #else
6514   return QuickIsNull();
6515 #endif
6516 }
6517 
6518 bool Value::QuickIsNull() const {
6519   typedef internal::Object O;
6520   typedef internal::Internals I;
6521   O* obj = *reinterpret_cast<O* const*>(this);
6522   if (!I::HasHeapObjectTag(obj)) return false;
6523   if (I::GetInstanceType(obj) != I::kOddballType) return false;
6524   return (I::GetOddballKind(obj) == I::kNullOddballKind);
6525 }
6526 
6527 
6528 bool Value::IsString() const {
6529 #ifdef V8_ENABLE_CHECKS
6530   return FullIsString();
6531 #else
6532   return QuickIsString();
6533 #endif
6534 }
6535 
6536 bool Value::QuickIsString() const {
6537   typedef internal::Object O;
6538   typedef internal::Internals I;
6539   O* obj = *reinterpret_cast<O* const*>(this);
6540   if (!I::HasHeapObjectTag(obj)) return false;
6541   return (I::GetInstanceType(obj) < I::kFirstNonstringType);
6542 }
6543 
6544 
6545 template <class T> Value* Value::Cast(T* value) {
6546   return static_cast<Value*>(value);
6547 }
6548 
6549 
6550 Name* Name::Cast(v8::Value* value) {
6551 #ifdef V8_ENABLE_CHECKS
6552   CheckCast(value);
6553 #endif
6554   return static_cast<Name*>(value);
6555 }
6556 
6557 
6558 Symbol* Symbol::Cast(v8::Value* value) {
6559 #ifdef V8_ENABLE_CHECKS
6560   CheckCast(value);
6561 #endif
6562   return static_cast<Symbol*>(value);
6563 }
6564 
6565 
6566 Number* Number::Cast(v8::Value* value) {
6567 #ifdef V8_ENABLE_CHECKS
6568   CheckCast(value);
6569 #endif
6570   return static_cast<Number*>(value);
6571 }
6572 
6573 
6574 Integer* Integer::Cast(v8::Value* value) {
6575 #ifdef V8_ENABLE_CHECKS
6576   CheckCast(value);
6577 #endif
6578   return static_cast<Integer*>(value);
6579 }
6580 
6581 
6582 Date* Date::Cast(v8::Value* value) {
6583 #ifdef V8_ENABLE_CHECKS
6584   CheckCast(value);
6585 #endif
6586   return static_cast<Date*>(value);
6587 }
6588 
6589 
6590 StringObject* StringObject::Cast(v8::Value* value) {
6591 #ifdef V8_ENABLE_CHECKS
6592   CheckCast(value);
6593 #endif
6594   return static_cast<StringObject*>(value);
6595 }
6596 
6597 
6598 SymbolObject* SymbolObject::Cast(v8::Value* value) {
6599 #ifdef V8_ENABLE_CHECKS
6600   CheckCast(value);
6601 #endif
6602   return static_cast<SymbolObject*>(value);
6603 }
6604 
6605 
6606 NumberObject* NumberObject::Cast(v8::Value* value) {
6607 #ifdef V8_ENABLE_CHECKS
6608   CheckCast(value);
6609 #endif
6610   return static_cast<NumberObject*>(value);
6611 }
6612 
6613 
6614 BooleanObject* BooleanObject::Cast(v8::Value* value) {
6615 #ifdef V8_ENABLE_CHECKS
6616   CheckCast(value);
6617 #endif
6618   return static_cast<BooleanObject*>(value);
6619 }
6620 
6621 
6622 RegExp* RegExp::Cast(v8::Value* value) {
6623 #ifdef V8_ENABLE_CHECKS
6624   CheckCast(value);
6625 #endif
6626   return static_cast<RegExp*>(value);
6627 }
6628 
6629 
6630 Object* Object::Cast(v8::Value* value) {
6631 #ifdef V8_ENABLE_CHECKS
6632   CheckCast(value);
6633 #endif
6634   return static_cast<Object*>(value);
6635 }
6636 
6637 
6638 Array* Array::Cast(v8::Value* value) {
6639 #ifdef V8_ENABLE_CHECKS
6640   CheckCast(value);
6641 #endif
6642   return static_cast<Array*>(value);
6643 }
6644 
6645 
6646 Promise* Promise::Cast(v8::Value* value) {
6647 #ifdef V8_ENABLE_CHECKS
6648   CheckCast(value);
6649 #endif
6650   return static_cast<Promise*>(value);
6651 }
6652 
6653 
6654 Promise::Resolver* Promise::Resolver::Cast(v8::Value* value) {
6655 #ifdef V8_ENABLE_CHECKS
6656   CheckCast(value);
6657 #endif
6658   return static_cast<Promise::Resolver*>(value);
6659 }
6660 
6661 
6662 ArrayBuffer* ArrayBuffer::Cast(v8::Value* value) {
6663 #ifdef V8_ENABLE_CHECKS
6664   CheckCast(value);
6665 #endif
6666   return static_cast<ArrayBuffer*>(value);
6667 }
6668 
6669 
6670 ArrayBufferView* ArrayBufferView::Cast(v8::Value* value) {
6671 #ifdef V8_ENABLE_CHECKS
6672   CheckCast(value);
6673 #endif
6674   return static_cast<ArrayBufferView*>(value);
6675 }
6676 
6677 
6678 TypedArray* TypedArray::Cast(v8::Value* value) {
6679 #ifdef V8_ENABLE_CHECKS
6680   CheckCast(value);
6681 #endif
6682   return static_cast<TypedArray*>(value);
6683 }
6684 
6685 
6686 Uint8Array* Uint8Array::Cast(v8::Value* value) {
6687 #ifdef V8_ENABLE_CHECKS
6688   CheckCast(value);
6689 #endif
6690   return static_cast<Uint8Array*>(value);
6691 }
6692 
6693 
6694 Int8Array* Int8Array::Cast(v8::Value* value) {
6695 #ifdef V8_ENABLE_CHECKS
6696   CheckCast(value);
6697 #endif
6698   return static_cast<Int8Array*>(value);
6699 }
6700 
6701 
6702 Uint16Array* Uint16Array::Cast(v8::Value* value) {
6703 #ifdef V8_ENABLE_CHECKS
6704   CheckCast(value);
6705 #endif
6706   return static_cast<Uint16Array*>(value);
6707 }
6708 
6709 
6710 Int16Array* Int16Array::Cast(v8::Value* value) {
6711 #ifdef V8_ENABLE_CHECKS
6712   CheckCast(value);
6713 #endif
6714   return static_cast<Int16Array*>(value);
6715 }
6716 
6717 
6718 Uint32Array* Uint32Array::Cast(v8::Value* value) {
6719 #ifdef V8_ENABLE_CHECKS
6720   CheckCast(value);
6721 #endif
6722   return static_cast<Uint32Array*>(value);
6723 }
6724 
6725 
6726 Int32Array* Int32Array::Cast(v8::Value* value) {
6727 #ifdef V8_ENABLE_CHECKS
6728   CheckCast(value);
6729 #endif
6730   return static_cast<Int32Array*>(value);
6731 }
6732 
6733 
6734 Float32Array* Float32Array::Cast(v8::Value* value) {
6735 #ifdef V8_ENABLE_CHECKS
6736   CheckCast(value);
6737 #endif
6738   return static_cast<Float32Array*>(value);
6739 }
6740 
6741 
6742 Float64Array* Float64Array::Cast(v8::Value* value) {
6743 #ifdef V8_ENABLE_CHECKS
6744   CheckCast(value);
6745 #endif
6746   return static_cast<Float64Array*>(value);
6747 }
6748 
6749 
6750 Uint8ClampedArray* Uint8ClampedArray::Cast(v8::Value* value) {
6751 #ifdef V8_ENABLE_CHECKS
6752   CheckCast(value);
6753 #endif
6754   return static_cast<Uint8ClampedArray*>(value);
6755 }
6756 
6757 
6758 DataView* DataView::Cast(v8::Value* value) {
6759 #ifdef V8_ENABLE_CHECKS
6760   CheckCast(value);
6761 #endif
6762   return static_cast<DataView*>(value);
6763 }
6764 
6765 
6766 Function* Function::Cast(v8::Value* value) {
6767 #ifdef V8_ENABLE_CHECKS
6768   CheckCast(value);
6769 #endif
6770   return static_cast<Function*>(value);
6771 }
6772 
6773 
6774 External* External::Cast(v8::Value* value) {
6775 #ifdef V8_ENABLE_CHECKS
6776   CheckCast(value);
6777 #endif
6778   return static_cast<External*>(value);
6779 }
6780 
6781 
6782 template<typename T>
6783 Isolate* PropertyCallbackInfo<T>::GetIsolate() const {
6784   return *reinterpret_cast<Isolate**>(&args_[kIsolateIndex]);
6785 }
6786 
6787 
6788 template<typename T>
6789 Local<Value> PropertyCallbackInfo<T>::Data() const {
6790   return Local<Value>(reinterpret_cast<Value*>(&args_[kDataIndex]));
6791 }
6792 
6793 
6794 template<typename T>
6795 Local<Object> PropertyCallbackInfo<T>::This() const {
6796   return Local<Object>(reinterpret_cast<Object*>(&args_[kThisIndex]));
6797 }
6798 
6799 
6800 template<typename T>
6801 Local<Object> PropertyCallbackInfo<T>::Holder() const {
6802   return Local<Object>(reinterpret_cast<Object*>(&args_[kHolderIndex]));
6803 }
6804 
6805 
6806 template<typename T>
6807 ReturnValue<T> PropertyCallbackInfo<T>::GetReturnValue() const {
6808   return ReturnValue<T>(&args_[kReturnValueIndex]);
6809 }
6810 
6811 
6812 Handle<Primitive> Undefined(Isolate* isolate) {
6813   typedef internal::Object* S;
6814   typedef internal::Internals I;
6815   I::CheckInitialized(isolate);
6816   S* slot = I::GetRoot(isolate, I::kUndefinedValueRootIndex);
6817   return Handle<Primitive>(reinterpret_cast<Primitive*>(slot));
6818 }
6819 
6820 
6821 Handle<Primitive> Null(Isolate* isolate) {
6822   typedef internal::Object* S;
6823   typedef internal::Internals I;
6824   I::CheckInitialized(isolate);
6825   S* slot = I::GetRoot(isolate, I::kNullValueRootIndex);
6826   return Handle<Primitive>(reinterpret_cast<Primitive*>(slot));
6827 }
6828 
6829 
6830 Handle<Boolean> True(Isolate* isolate) {
6831   typedef internal::Object* S;
6832   typedef internal::Internals I;
6833   I::CheckInitialized(isolate);
6834   S* slot = I::GetRoot(isolate, I::kTrueValueRootIndex);
6835   return Handle<Boolean>(reinterpret_cast<Boolean*>(slot));
6836 }
6837 
6838 
6839 Handle<Boolean> False(Isolate* isolate) {
6840   typedef internal::Object* S;
6841   typedef internal::Internals I;
6842   I::CheckInitialized(isolate);
6843   S* slot = I::GetRoot(isolate, I::kFalseValueRootIndex);
6844   return Handle<Boolean>(reinterpret_cast<Boolean*>(slot));
6845 }
6846 
6847 
6848 void Isolate::SetData(uint32_t slot, void* data) {
6849   typedef internal::Internals I;
6850   I::SetEmbedderData(this, slot, data);
6851 }
6852 
6853 
6854 void* Isolate::GetData(uint32_t slot) {
6855   typedef internal::Internals I;
6856   return I::GetEmbedderData(this, slot);
6857 }
6858 
6859 
6860 uint32_t Isolate::GetNumberOfDataSlots() {
6861   typedef internal::Internals I;
6862   return I::kNumIsolateDataSlots;
6863 }
6864 
6865 
6866 int64_t Isolate::AdjustAmountOfExternalAllocatedMemory(
6867     int64_t change_in_bytes) {
6868   typedef internal::Internals I;
6869   int64_t* amount_of_external_allocated_memory =
6870       reinterpret_cast<int64_t*>(reinterpret_cast<uint8_t*>(this) +
6871                                  I::kAmountOfExternalAllocatedMemoryOffset);
6872   int64_t* amount_of_external_allocated_memory_at_last_global_gc =
6873       reinterpret_cast<int64_t*>(
6874           reinterpret_cast<uint8_t*>(this) +
6875           I::kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset);
6876   int64_t amount = *amount_of_external_allocated_memory + change_in_bytes;
6877   if (change_in_bytes > 0 &&
6878       amount - *amount_of_external_allocated_memory_at_last_global_gc >
6879           I::kExternalAllocationLimit) {
6880     CollectAllGarbage("external memory allocation limit reached.");
6881   } else {
6882     *amount_of_external_allocated_memory = amount;
6883   }
6884   return *amount_of_external_allocated_memory;
6885 }
6886 
6887 
6888 template<typename T>
6889 void Isolate::SetObjectGroupId(const Persistent<T>& object,
6890                                UniqueId id) {
6891   TYPE_CHECK(Value, T);
6892   SetObjectGroupId(reinterpret_cast<v8::internal::Object**>(object.val_), id);
6893 }
6894 
6895 
6896 template<typename T>
6897 void Isolate::SetReferenceFromGroup(UniqueId id,
6898                                     const Persistent<T>& object) {
6899   TYPE_CHECK(Value, T);
6900   SetReferenceFromGroup(id,
6901                         reinterpret_cast<v8::internal::Object**>(object.val_));
6902 }
6903 
6904 
6905 template<typename T, typename S>
6906 void Isolate::SetReference(const Persistent<T>& parent,
6907                            const Persistent<S>& child) {
6908   TYPE_CHECK(Object, T);
6909   TYPE_CHECK(Value, S);
6910   SetReference(reinterpret_cast<v8::internal::Object**>(parent.val_),
6911                reinterpret_cast<v8::internal::Object**>(child.val_));
6912 }
6913 
6914 
6915 Local<Value> Context::GetEmbedderData(int index) {
6916 #ifndef V8_ENABLE_CHECKS
6917   typedef internal::Object O;
6918   typedef internal::HeapObject HO;
6919   typedef internal::Internals I;
6920   HO* context = *reinterpret_cast<HO**>(this);
6921   O** result =
6922       HandleScope::CreateHandle(context, I::ReadEmbedderData<O*>(this, index));
6923   return Local<Value>(reinterpret_cast<Value*>(result));
6924 #else
6925   return SlowGetEmbedderData(index);
6926 #endif
6927 }
6928 
6929 
6930 void* Context::GetAlignedPointerFromEmbedderData(int index) {
6931 #ifndef V8_ENABLE_CHECKS
6932   typedef internal::Internals I;
6933   return I::ReadEmbedderData<void*>(this, index);
6934 #else
6935   return SlowGetAlignedPointerFromEmbedderData(index);
6936 #endif
6937 }
6938 
6939 
6940 /**
6941  * \example shell.cc
6942  * A simple shell that takes a list of expressions on the
6943  * command-line and executes them.
6944  */
6945 
6946 
6947 /**
6948  * \example process.cc
6949  */
6950 
6951 
6952 }  // namespace v8
6953 
6954 
6955 #undef TYPE_CHECK
6956 
6957 
6958 #endif  // V8_H_
6959