• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2007-2009 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
4 // met:
5 //
6 //     * Redistributions of source code must retain the above copyright
7 //       notice, this list of conditions and the following disclaimer.
8 //     * Redistributions in binary form must reproduce the above
9 //       copyright notice, this list of conditions and the following
10 //       disclaimer in the documentation and/or other materials provided
11 //       with the distribution.
12 //     * Neither the name of Google Inc. nor the names of its
13 //       contributors may be used to endorse or promote products derived
14 //       from this software without specific prior written permission.
15 //
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 
28 /** \mainpage V8 API Reference Guide
29  *
30  * V8 is Google's open source JavaScript engine.
31  *
32  * This set of documents provides reference material generated from the
33  * V8 header file, include/v8.h.
34  *
35  * For other documentation see http://code.google.com/apis/v8/
36  */
37 
38 #ifndef V8_H_
39 #define V8_H_
40 
41 #include <stdio.h>
42 
43 #ifdef _WIN32
44 // When compiling on MinGW stdint.h is available.
45 #ifdef __MINGW32__
46 #include <stdint.h>
47 #else  // __MINGW32__
48 typedef signed char int8_t;
49 typedef unsigned char uint8_t;
50 typedef short int16_t;  // NOLINT
51 typedef unsigned short uint16_t;  // NOLINT
52 typedef int int32_t;
53 typedef unsigned int uint32_t;
54 typedef __int64 int64_t;
55 typedef unsigned __int64 uint64_t;
56 // intptr_t and friends are defined in crtdefs.h through stdio.h.
57 #endif  // __MINGW32__
58 
59 // Setup for Windows DLL export/import. When building the V8 DLL the
60 // BUILDING_V8_SHARED needs to be defined. When building a program which uses
61 // the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8
62 // static library or building a program which uses the V8 static library neither
63 // BUILDING_V8_SHARED nor USING_V8_SHARED should be defined.
64 // The reason for having both V8EXPORT and V8EXPORT_INLINE is that classes which
65 // have their code inside this header file need to have __declspec(dllexport)
66 // when building the DLL but cannot have __declspec(dllimport) when building
67 // a program which uses the DLL.
68 #if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED)
69 #error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the\
70   build configuration to ensure that at most one of these is set
71 #endif
72 
73 #ifdef BUILDING_V8_SHARED
74 #define V8EXPORT __declspec(dllexport)
75 #define V8EXPORT_INLINE __declspec(dllexport)
76 #elif USING_V8_SHARED
77 #define V8EXPORT __declspec(dllimport)
78 #define V8EXPORT_INLINE
79 #else
80 #define V8EXPORT
81 #define V8EXPORT_INLINE
82 #endif  // BUILDING_V8_SHARED
83 
84 #else  // _WIN32
85 
86 #include <stdint.h>
87 
88 // Setup for Linux shared library export. There is no need to distinguish
89 // between building or using the V8 shared library, but we should not
90 // export symbols when we are building a static library.
91 #if defined(__GNUC__) && (__GNUC__ >= 4) && defined(V8_SHARED)
92 #define V8EXPORT __attribute__ ((visibility("default")))
93 #define V8EXPORT_INLINE __attribute__ ((visibility("default")))
94 #else  // defined(__GNUC__) && (__GNUC__ >= 4)
95 #define V8EXPORT
96 #define V8EXPORT_INLINE
97 #endif  // defined(__GNUC__) && (__GNUC__ >= 4)
98 
99 #endif  // _WIN32
100 
101 /**
102  * The v8 JavaScript engine.
103  */
104 namespace v8 {
105 
106 class Context;
107 class String;
108 class Value;
109 class Utils;
110 class Number;
111 class Object;
112 class Array;
113 class Int32;
114 class Uint32;
115 class External;
116 class Primitive;
117 class Boolean;
118 class Integer;
119 class Function;
120 class Date;
121 class ImplementationUtilities;
122 class Signature;
123 template <class T> class Handle;
124 template <class T> class Local;
125 template <class T> class Persistent;
126 class FunctionTemplate;
127 class ObjectTemplate;
128 class Data;
129 
130 namespace internal {
131 
132 class Arguments;
133 class Object;
134 class Top;
135 
136 }
137 
138 
139 // --- W e a k  H a n d l e s
140 
141 
142 /**
143  * A weak reference callback function.
144  *
145  * \param object the weak global object to be reclaimed by the garbage collector
146  * \param parameter the value passed in when making the weak global object
147  */
148 typedef void (*WeakReferenceCallback)(Persistent<Value> object,
149                                       void* parameter);
150 
151 
152 // --- H a n d l e s ---
153 
154 #define TYPE_CHECK(T, S)                              \
155   while (false) {                                     \
156     *(static_cast<T**>(0)) = static_cast<S*>(0);      \
157   }
158 
159 /**
160  * An object reference managed by the v8 garbage collector.
161  *
162  * All objects returned from v8 have to be tracked by the garbage
163  * collector so that it knows that the objects are still alive.  Also,
164  * because the garbage collector may move objects, it is unsafe to
165  * point directly to an object.  Instead, all objects are stored in
166  * handles which are known by the garbage collector and updated
167  * whenever an object moves.  Handles should always be passed by value
168  * (except in cases like out-parameters) and they should never be
169  * allocated on the heap.
170  *
171  * There are two types of handles: local and persistent handles.
172  * Local handles are light-weight and transient and typically used in
173  * local operations.  They are managed by HandleScopes.  Persistent
174  * handles can be used when storing objects across several independent
175  * operations and have to be explicitly deallocated when they're no
176  * longer used.
177  *
178  * It is safe to extract the object stored in the handle by
179  * dereferencing the handle (for instance, to extract the Object* from
180  * an Handle<Object>); the value will still be governed by a handle
181  * behind the scenes and the same rules apply to these values as to
182  * their handles.
183  */
184 template <class T> class V8EXPORT_INLINE Handle {
185  public:
186 
187   /**
188    * Creates an empty handle.
189    */
190   inline Handle();
191 
192   /**
193    * Creates a new handle for the specified value.
194    */
Handle(T * val)195   explicit Handle(T* val) : val_(val) { }
196 
197   /**
198    * Creates a handle for the contents of the specified handle.  This
199    * constructor allows you to pass handles as arguments by value and
200    * to assign between handles.  However, if you try to assign between
201    * incompatible handles, for instance from a Handle<String> to a
202    * Handle<Number> it will cause a compiletime error.  Assigning
203    * between compatible handles, for instance assigning a
204    * Handle<String> to a variable declared as Handle<Value>, is legal
205    * because String is a subclass of Value.
206    */
Handle(Handle<S> that)207   template <class S> inline Handle(Handle<S> that)
208       : val_(reinterpret_cast<T*>(*that)) {
209     /**
210      * This check fails when trying to convert between incompatible
211      * handles. For example, converting from a Handle<String> to a
212      * Handle<Number>.
213      */
214     TYPE_CHECK(T, S);
215   }
216 
217   /**
218    * Returns true if the handle is empty.
219    */
IsEmpty()220   bool IsEmpty() const { return val_ == 0; }
221 
222   T* operator->() const { return val_; }
223 
224   T* operator*() const { return val_; }
225 
226   /**
227    * Sets the handle to be empty. IsEmpty() will then return true.
228    */
Clear()229   void Clear() { this->val_ = 0; }
230 
231   /**
232    * Checks whether two handles are the same.
233    * Returns true if both are empty, or if the objects
234    * to which they refer are identical.
235    * The handles' references are not checked.
236    */
237   template <class S> bool operator==(Handle<S> that) const {
238     internal::Object** a = reinterpret_cast<internal::Object**>(**this);
239     internal::Object** b = reinterpret_cast<internal::Object**>(*that);
240     if (a == 0) return b == 0;
241     if (b == 0) return false;
242     return *a == *b;
243   }
244 
245   /**
246    * Checks whether two handles are different.
247    * Returns true if only one of the handles is empty, or if
248    * the objects to which they refer are different.
249    * The handles' references are not checked.
250    */
251   template <class S> bool operator!=(Handle<S> that) const {
252     return !operator==(that);
253   }
254 
Cast(Handle<S> that)255   template <class S> static inline Handle<T> Cast(Handle<S> that) {
256 #ifdef V8_ENABLE_CHECKS
257     // If we're going to perform the type check then we have to check
258     // that the handle isn't empty before doing the checked cast.
259     if (that.IsEmpty()) return Handle<T>();
260 #endif
261     return Handle<T>(T::Cast(*that));
262   }
263 
264  private:
265   T* val_;
266 };
267 
268 
269 /**
270  * A light-weight stack-allocated object handle.  All operations
271  * that return objects from within v8 return them in local handles.  They
272  * are created within HandleScopes, and all local handles allocated within a
273  * handle scope are destroyed when the handle scope is destroyed.  Hence it
274  * is not necessary to explicitly deallocate local handles.
275  */
276 template <class T> class V8EXPORT_INLINE Local : public Handle<T> {
277  public:
278   inline Local();
Local(Local<S> that)279   template <class S> inline Local(Local<S> that)
280       : Handle<T>(reinterpret_cast<T*>(*that)) {
281     /**
282      * This check fails when trying to convert between incompatible
283      * handles. For example, converting from a Handle<String> to a
284      * Handle<Number>.
285      */
286     TYPE_CHECK(T, S);
287   }
Local(S * that)288   template <class S> inline Local(S* that) : Handle<T>(that) { }
Cast(Local<S> that)289   template <class S> static inline Local<T> Cast(Local<S> that) {
290 #ifdef V8_ENABLE_CHECKS
291     // If we're going to perform the type check then we have to check
292     // that the handle isn't empty before doing the checked cast.
293     if (that.IsEmpty()) return Local<T>();
294 #endif
295     return Local<T>(T::Cast(*that));
296   }
297 
298   /** Create a local handle for the content of another handle.
299    *  The referee is kept alive by the local handle even when
300    *  the original handle is destroyed/disposed.
301    */
302   inline static Local<T> New(Handle<T> that);
303 };
304 
305 
306 /**
307  * An object reference that is independent of any handle scope.  Where
308  * a Local handle only lives as long as the HandleScope in which it was
309  * allocated, a Persistent handle remains valid until it is explicitly
310  * disposed.
311  *
312  * A persistent handle contains a reference to a storage cell within
313  * the v8 engine which holds an object value and which is updated by
314  * the garbage collector whenever the object is moved.  A new storage
315  * cell can be created using Persistent::New and existing handles can
316  * be disposed using Persistent::Dispose.  Since persistent handles
317  * are passed by value you may have many persistent handle objects
318  * that point to the same storage cell.  For instance, if you pass a
319  * persistent handle as an argument to a function you will not get two
320  * different storage cells but rather two references to the same
321  * storage cell.
322  */
323 template <class T> class V8EXPORT_INLINE Persistent : public Handle<T> {
324  public:
325 
326   /**
327    * Creates an empty persistent handle that doesn't point to any
328    * storage cell.
329    */
330   inline Persistent();
331 
332   /**
333    * Creates a persistent handle for the same storage cell as the
334    * specified handle.  This constructor allows you to pass persistent
335    * handles as arguments by value and to assign between persistent
336    * handles.  However, attempting to assign between incompatible
337    * persistent handles, for instance from a Persistent<String> to a
338    * Persistent<Number> will cause a compiletime error.  Assigning
339    * between compatible persistent handles, for instance assigning a
340    * Persistent<String> to a variable declared as Persistent<Value>,
341    * is allowed as String is a subclass of Value.
342    */
Persistent(Persistent<S> that)343   template <class S> inline Persistent(Persistent<S> that)
344       : Handle<T>(reinterpret_cast<T*>(*that)) {
345     /**
346      * This check fails when trying to convert between incompatible
347      * handles. For example, converting from a Handle<String> to a
348      * Handle<Number>.
349      */
350     TYPE_CHECK(T, S);
351   }
352 
Persistent(S * that)353   template <class S> inline Persistent(S* that) : Handle<T>(that) { }
354 
355   /**
356    * "Casts" a plain handle which is known to be a persistent handle
357    * to a persistent handle.
358    */
Persistent(Handle<S> that)359   template <class S> explicit inline Persistent(Handle<S> that)
360       : Handle<T>(*that) { }
361 
Cast(Persistent<S> that)362   template <class S> static inline Persistent<T> Cast(Persistent<S> that) {
363 #ifdef V8_ENABLE_CHECKS
364     // If we're going to perform the type check then we have to check
365     // that the handle isn't empty before doing the checked cast.
366     if (that.IsEmpty()) return Persistent<T>();
367 #endif
368     return Persistent<T>(T::Cast(*that));
369   }
370 
371   /**
372    * Creates a new persistent handle for an existing local or
373    * persistent handle.
374    */
375   inline static Persistent<T> New(Handle<T> that);
376 
377   /**
378    * Releases the storage cell referenced by this persistent handle.
379    * Does not remove the reference to the cell from any handles.
380    * This handle's reference, and any any other references to the storage
381    * cell remain and IsEmpty will still return false.
382    */
383   inline void Dispose();
384 
385   /**
386    * Make the reference to this object weak.  When only weak handles
387    * refer to the object, the garbage collector will perform a
388    * callback to the given V8::WeakReferenceCallback function, passing
389    * it the object reference and the given parameters.
390    */
391   inline void MakeWeak(void* parameters, WeakReferenceCallback callback);
392 
393   /** Clears the weak reference to this object.*/
394   inline void ClearWeak();
395 
396   /**
397    *Checks if the handle holds the only reference to an object.
398    */
399   inline bool IsNearDeath() const;
400 
401   /**
402    * Returns true if the handle's reference is weak.
403    */
404   inline bool IsWeak() const;
405 
406  private:
407   friend class ImplementationUtilities;
408   friend class ObjectTemplate;
409 };
410 
411 
412  /**
413  * A stack-allocated class that governs a number of local handles.
414  * After a handle scope has been created, all local handles will be
415  * allocated within that handle scope until either the handle scope is
416  * deleted or another handle scope is created.  If there is already a
417  * handle scope and a new one is created, all allocations will take
418  * place in the new handle scope until it is deleted.  After that,
419  * new handles will again be allocated in the original handle scope.
420  *
421  * After the handle scope of a local handle has been deleted the
422  * garbage collector will no longer track the object stored in the
423  * handle and may deallocate it.  The behavior of accessing a handle
424  * for which the handle scope has been deleted is undefined.
425  */
426 class V8EXPORT HandleScope {
427  public:
428   HandleScope();
429 
430   ~HandleScope();
431 
432   /**
433    * Closes the handle scope and returns the value as a handle in the
434    * previous scope, which is the new current scope after the call.
435    */
436   template <class T> Local<T> Close(Handle<T> value);
437 
438   /**
439    * Counts the number of allocated handles.
440    */
441   static int NumberOfHandles();
442 
443   /**
444    * Creates a new handle with the given value.
445    */
446   static internal::Object** CreateHandle(internal::Object* value);
447 
448  private:
449   // Make it impossible to create heap-allocated or illegal handle
450   // scopes by disallowing certain operations.
451   HandleScope(const HandleScope&);
452   void operator=(const HandleScope&);
453   void* operator new(size_t size);
454   void operator delete(void*, size_t);
455 
456   // This Data class is accessible internally as HandleScopeData through a
457   // typedef in the ImplementationUtilities class.
458   class V8EXPORT Data {
459    public:
460     int extensions;
461     internal::Object** next;
462     internal::Object** limit;
Initialize()463     inline void Initialize() {
464       extensions = -1;
465       next = limit = NULL;
466     }
467   };
468 
469   Data previous_;
470 
471   // Allow for the active closing of HandleScopes which allows to pass a handle
472   // from the HandleScope being closed to the next top most HandleScope.
473   bool is_closed_;
474   internal::Object** RawClose(internal::Object** value);
475 
476   friend class ImplementationUtilities;
477 };
478 
479 
480 // --- S p e c i a l   o b j e c t s ---
481 
482 
483 /**
484  * The superclass of values and API object templates.
485  */
486 class V8EXPORT Data {
487  private:
488   Data();
489 };
490 
491 
492 /**
493  * Pre-compilation data that can be associated with a script.  This
494  * data can be calculated for a script in advance of actually
495  * compiling it, and can be stored between compilations.  When script
496  * data is given to the compile method compilation will be faster.
497  */
498 class V8EXPORT ScriptData {  // NOLINT
499  public:
~ScriptData()500   virtual ~ScriptData() { }
501   static ScriptData* PreCompile(const char* input, int length);
502   static ScriptData* New(unsigned* data, int length);
503 
504   virtual int Length() = 0;
505   virtual unsigned* Data() = 0;
506   virtual bool HasError() = 0;
507 };
508 
509 
510 /**
511  * The origin, within a file, of a script.
512  */
513 class V8EXPORT ScriptOrigin {
514  public:
515   ScriptOrigin(Handle<Value> resource_name,
516                Handle<Integer> resource_line_offset = Handle<Integer>(),
517                Handle<Integer> resource_column_offset = Handle<Integer>())
resource_name_(resource_name)518       : resource_name_(resource_name),
519         resource_line_offset_(resource_line_offset),
520         resource_column_offset_(resource_column_offset) { }
521   inline Handle<Value> ResourceName() const;
522   inline Handle<Integer> ResourceLineOffset() const;
523   inline Handle<Integer> ResourceColumnOffset() const;
524  private:
525   Handle<Value> resource_name_;
526   Handle<Integer> resource_line_offset_;
527   Handle<Integer> resource_column_offset_;
528 };
529 
530 
531 /**
532  * A compiled JavaScript script.
533  */
534 class V8EXPORT Script {
535  public:
536 
537   /**
538    * Compiles the specified script (context-independent).
539    *
540    * \param source Script source code.
541    * \param origin Script origin, owned by caller, no references are kept
542    *   when New() returns
543    * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
544    *   using pre_data speeds compilation if it's done multiple times.
545    *   Owned by caller, no references are kept when New() returns.
546    * \param script_data Arbitrary data associated with script. Using
547    *   this has same effect as calling SetData(), but allows data to be
548    *   available to compile event handlers.
549    * \return Compiled script object (context independent; when run it
550    *   will use the currently entered context).
551    */
552   static Local<Script> New(Handle<String> source,
553                            ScriptOrigin* origin = NULL,
554                            ScriptData* pre_data = NULL,
555                            Handle<String> script_data = Handle<String>());
556 
557   /**
558    * Compiles the specified script using the specified file name
559    * object (typically a string) as the script's origin.
560    *
561    * \param source Script source code.
562    * \patam file_name file name object (typically a string) to be used
563    *   as the script's origin.
564    * \return Compiled script object (context independent; when run it
565    *   will use the currently entered context).
566    */
567   static Local<Script> New(Handle<String> source,
568                            Handle<Value> file_name);
569 
570   /**
571    * Compiles the specified script (bound to current context).
572    *
573    * \param source Script source code.
574    * \param origin Script origin, owned by caller, no references are kept
575    *   when Compile() returns
576    * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
577    *   using pre_data speeds compilation if it's done multiple times.
578    *   Owned by caller, no references are kept when Compile() returns.
579    * \param script_data Arbitrary data associated with script. Using
580    *   this has same effect as calling SetData(), but makes data available
581    *   earlier (i.e. to compile event handlers).
582    * \return Compiled script object, bound to the context that was active
583    *   when this function was called.  When run it will always use this
584    *   context.
585    */
586   static Local<Script> Compile(Handle<String> source,
587                                ScriptOrigin* origin = NULL,
588                                ScriptData* pre_data = NULL,
589                                Handle<String> script_data = Handle<String>());
590 
591   /**
592    * Compiles the specified script using the specified file name
593    * object (typically a string) as the script's origin.
594    *
595    * \param source Script source code.
596    * \param file_name File name to use as script's origin
597    * \param script_data Arbitrary data associated with script. Using
598    *   this has same effect as calling SetData(), but makes data available
599    *   earlier (i.e. to compile event handlers).
600    * \return Compiled script object, bound to the context that was active
601    *   when this function was called.  When run it will always use this
602    *   context.
603    */
604   static Local<Script> Compile(Handle<String> source,
605                                Handle<Value> file_name,
606                                Handle<String> script_data = Handle<String>());
607 
608   /**
609    * Runs the script returning the resulting value.  If the script is
610    * context independent (created using ::New) it will be run in the
611    * currently entered context.  If it is context specific (created
612    * using ::Compile) it will be run in the context in which it was
613    * compiled.
614    */
615   Local<Value> Run();
616 
617   /**
618    * Returns the script id value.
619    */
620   Local<Value> Id();
621 
622   /**
623    * Associate an additional data object with the script. This is mainly used
624    * with the debugger as this data object is only available through the
625    * debugger API.
626    */
627   void SetData(Handle<String> data);
628 };
629 
630 
631 /**
632  * An error message.
633  */
634 class V8EXPORT Message {
635  public:
636   Local<String> Get() const;
637   Local<String> GetSourceLine() const;
638 
639   /**
640    * Returns the resource name for the script from where the function causing
641    * the error originates.
642    */
643   Handle<Value> GetScriptResourceName() const;
644 
645   /**
646    * Returns the resource data for the script from where the function causing
647    * the error originates.
648    */
649   Handle<Value> GetScriptData() const;
650 
651   /**
652    * Returns the number, 1-based, of the line where the error occurred.
653    */
654   int GetLineNumber() const;
655 
656   /**
657    * Returns the index within the script of the first character where
658    * the error occurred.
659    */
660   int GetStartPosition() const;
661 
662   /**
663    * Returns the index within the script of the last character where
664    * the error occurred.
665    */
666   int GetEndPosition() const;
667 
668   /**
669    * Returns the index within the line of the first character where
670    * the error occurred.
671    */
672   int GetStartColumn() const;
673 
674   /**
675    * Returns the index within the line of the last character where
676    * the error occurred.
677    */
678   int GetEndColumn() const;
679 
680   // TODO(1245381): Print to a string instead of on a FILE.
681   static void PrintCurrentStackTrace(FILE* out);
682 };
683 
684 
685 // --- V a l u e ---
686 
687 
688 /**
689  * The superclass of all JavaScript values and objects.
690  */
691 class V8EXPORT Value : public Data {
692  public:
693 
694   /**
695    * Returns true if this value is the undefined value.  See ECMA-262
696    * 4.3.10.
697    */
698   bool IsUndefined() const;
699 
700   /**
701    * Returns true if this value is the null value.  See ECMA-262
702    * 4.3.11.
703    */
704   bool IsNull() const;
705 
706    /**
707    * Returns true if this value is true.
708    */
709   bool IsTrue() const;
710 
711   /**
712    * Returns true if this value is false.
713    */
714   bool IsFalse() const;
715 
716   /**
717    * Returns true if this value is an instance of the String type.
718    * See ECMA-262 8.4.
719    */
720   inline bool IsString() const;
721 
722   /**
723    * Returns true if this value is a function.
724    */
725   bool IsFunction() const;
726 
727   /**
728    * Returns true if this value is an array.
729    */
730   bool IsArray() const;
731 
732   /**
733    * Returns true if this value is an object.
734    */
735   bool IsObject() const;
736 
737   /**
738    * Returns true if this value is boolean.
739    */
740   bool IsBoolean() const;
741 
742   /**
743    * Returns true if this value is a number.
744    */
745   bool IsNumber() const;
746 
747   /**
748    * Returns true if this value is external.
749    */
750   bool IsExternal() const;
751 
752   /**
753    * Returns true if this value is a 32-bit signed integer.
754    */
755   bool IsInt32() const;
756 
757   /**
758    * Returns true if this value is a Date.
759    */
760   bool IsDate() const;
761 
762   Local<Boolean> ToBoolean() const;
763   Local<Number> ToNumber() const;
764   Local<String> ToString() const;
765   Local<String> ToDetailString() const;
766   Local<Object> ToObject() const;
767   Local<Integer> ToInteger() const;
768   Local<Uint32> ToUint32() const;
769   Local<Int32> ToInt32() const;
770 
771   /**
772    * Attempts to convert a string to an array index.
773    * Returns an empty handle if the conversion fails.
774    */
775   Local<Uint32> ToArrayIndex() const;
776 
777   bool BooleanValue() const;
778   double NumberValue() const;
779   int64_t IntegerValue() const;
780   uint32_t Uint32Value() const;
781   int32_t Int32Value() const;
782 
783   /** JS == */
784   bool Equals(Handle<Value> that) const;
785   bool StrictEquals(Handle<Value> that) const;
786 
787  private:
788   inline bool QuickIsString() const;
789   bool FullIsString() const;
790 };
791 
792 
793 /**
794  * The superclass of primitive values.  See ECMA-262 4.3.2.
795  */
796 class V8EXPORT Primitive : public Value { };
797 
798 
799 /**
800  * A primitive boolean value (ECMA-262, 4.3.14).  Either the true
801  * or false value.
802  */
803 class V8EXPORT Boolean : public Primitive {
804  public:
805   bool Value() const;
806   static inline Handle<Boolean> New(bool value);
807 };
808 
809 
810 /**
811  * A JavaScript string value (ECMA-262, 4.3.17).
812  */
813 class V8EXPORT String : public Primitive {
814  public:
815 
816   /**
817    * Returns the number of characters in this string.
818    */
819   int Length() const;
820 
821   /**
822    * Returns the number of bytes in the UTF-8 encoded
823    * representation of this string.
824    */
825   int Utf8Length() const;
826 
827   /**
828    * Write the contents of the string to an external buffer.
829    * If no arguments are given, expects the buffer to be large
830    * enough to hold the entire string and NULL terminator. Copies
831    * the contents of the string and the NULL terminator into the
832    * buffer.
833    *
834    * Copies up to length characters into the output buffer.
835    * Only null-terminates if there is enough space in the buffer.
836    *
837    * \param buffer The buffer into which the string will be copied.
838    * \param start The starting position within the string at which
839    * copying begins.
840    * \param length The number of bytes to copy from the string.
841    * \return The number of characters copied to the buffer
842    * excluding the NULL terminator.
843    */
844   int Write(uint16_t* buffer, int start = 0, int length = -1) const;  // UTF-16
845   int WriteAscii(char* buffer, int start = 0, int length = -1) const;  // ASCII
846   int WriteUtf8(char* buffer, int length = -1) const; // UTF-8
847 
848   /**
849    * A zero length string.
850    */
851   static v8::Local<v8::String> Empty();
852 
853   /**
854    * Returns true if the string is external
855    */
856   bool IsExternal() const;
857 
858   /**
859    * Returns true if the string is both external and ascii
860    */
861   bool IsExternalAscii() const;
862 
863   class V8EXPORT ExternalStringResourceBase {
864    public:
~ExternalStringResourceBase()865     virtual ~ExternalStringResourceBase() {}
866    protected:
ExternalStringResourceBase()867     ExternalStringResourceBase() {}
868    private:
869     // Disallow copying and assigning.
870     ExternalStringResourceBase(const ExternalStringResourceBase&);
871     void operator=(const ExternalStringResourceBase&);
872   };
873 
874   /**
875    * An ExternalStringResource is a wrapper around a two-byte string
876    * buffer that resides outside V8's heap. Implement an
877    * ExternalStringResource to manage the life cycle of the underlying
878    * buffer.  Note that the string data must be immutable.
879    */
880   class V8EXPORT ExternalStringResource
881       : public ExternalStringResourceBase {
882    public:
883     /**
884      * Override the destructor to manage the life cycle of the underlying
885      * buffer.
886      */
~ExternalStringResource()887     virtual ~ExternalStringResource() {}
888     /** The string data from the underlying buffer.*/
889     virtual const uint16_t* data() const = 0;
890     /** The length of the string. That is, the number of two-byte characters.*/
891     virtual size_t length() const = 0;
892    protected:
ExternalStringResource()893     ExternalStringResource() {}
894   };
895 
896   /**
897    * An ExternalAsciiStringResource is a wrapper around an ascii
898    * string buffer that resides outside V8's heap. Implement an
899    * ExternalAsciiStringResource to manage the life cycle of the
900    * underlying buffer.  Note that the string data must be immutable
901    * and that the data must be strict 7-bit ASCII, not Latin1 or
902    * UTF-8, which would require special treatment internally in the
903    * engine and, in the case of UTF-8, do not allow efficient indexing.
904    * Use String::New or convert to 16 bit data for non-ASCII.
905    */
906 
907   class V8EXPORT ExternalAsciiStringResource
908       : public ExternalStringResourceBase {
909    public:
910     /**
911      * Override the destructor to manage the life cycle of the underlying
912      * buffer.
913      */
~ExternalAsciiStringResource()914     virtual ~ExternalAsciiStringResource() {}
915     /** The string data from the underlying buffer.*/
916     virtual const char* data() const = 0;
917     /** The number of ascii characters in the string.*/
918     virtual size_t length() const = 0;
919    protected:
ExternalAsciiStringResource()920     ExternalAsciiStringResource() {}
921   };
922 
923   /**
924    * Get the ExternalStringResource for an external string.  Returns
925    * NULL if IsExternal() doesn't return true.
926    */
927   inline ExternalStringResource* GetExternalStringResource() const;
928 
929   /**
930    * Get the ExternalAsciiStringResource for an external ascii string.
931    * Returns NULL if IsExternalAscii() doesn't return true.
932    */
933   ExternalAsciiStringResource* GetExternalAsciiStringResource() const;
934 
935   static inline String* Cast(v8::Value* obj);
936 
937   /**
938    * Allocates a new string from either utf-8 encoded or ascii data.
939    * The second parameter 'length' gives the buffer length.
940    * If the data is utf-8 encoded, the caller must
941    * be careful to supply the length parameter.
942    * If it is not given, the function calls
943    * 'strlen' to determine the buffer length, it might be
944    * wrong if 'data' contains a null character.
945    */
946   static Local<String> New(const char* data, int length = -1);
947 
948   /** Allocates a new string from utf16 data.*/
949   static Local<String> New(const uint16_t* data, int length = -1);
950 
951   /** Creates a symbol. Returns one if it exists already.*/
952   static Local<String> NewSymbol(const char* data, int length = -1);
953 
954   /**
955    * Creates a new string by concatenating the left and the right strings
956    * passed in as parameters.
957    */
958   static Local<String> Concat(Handle<String> left, Handle<String>right);
959 
960   /**
961    * Creates a new external string using the data defined in the given
962    * resource. The resource is deleted when the external string is no
963    * longer live on V8's heap. The caller of this function should not
964    * delete or modify the resource. Neither should the underlying buffer be
965    * deallocated or modified except through the destructor of the
966    * external string resource.
967    */
968   static Local<String> NewExternal(ExternalStringResource* resource);
969 
970   /**
971    * Associate an external string resource with this string by transforming it
972    * in place so that existing references to this string in the JavaScript heap
973    * will use the external string resource. The external string resource's
974    * character contents needs to be equivalent to this string.
975    * Returns true if the string has been changed to be an external string.
976    * The string is not modified if the operation fails.
977    */
978   bool MakeExternal(ExternalStringResource* resource);
979 
980   /**
981    * Creates a new external string using the ascii data defined in the given
982    * resource. The resource is deleted when the external string is no
983    * longer live on V8's heap. The caller of this function should not
984    * delete or modify the resource. Neither should the underlying buffer be
985    * deallocated or modified except through the destructor of the
986    * external string resource.
987    */
988   static Local<String> NewExternal(ExternalAsciiStringResource* resource);
989 
990   /**
991    * Associate an external string resource with this string by transforming it
992    * in place so that existing references to this string in the JavaScript heap
993    * will use the external string resource. The external string resource's
994    * character contents needs to be equivalent to this string.
995    * Returns true if the string has been changed to be an external string.
996    * The string is not modified if the operation fails.
997    */
998   bool MakeExternal(ExternalAsciiStringResource* resource);
999 
1000   /**
1001    * Returns true if this string can be made external.
1002    */
1003   bool CanMakeExternal();
1004 
1005   /** Creates an undetectable string from the supplied ascii or utf-8 data.*/
1006   static Local<String> NewUndetectable(const char* data, int length = -1);
1007 
1008   /** Creates an undetectable string from the supplied utf-16 data.*/
1009   static Local<String> NewUndetectable(const uint16_t* data, int length = -1);
1010 
1011   /**
1012    * Converts an object to a utf8-encoded character array.  Useful if
1013    * you want to print the object.  If conversion to a string fails
1014    * (eg. due to an exception in the toString() method of the object)
1015    * then the length() method returns 0 and the * operator returns
1016    * NULL.
1017    */
1018   class V8EXPORT Utf8Value {
1019    public:
1020     explicit Utf8Value(Handle<v8::Value> obj);
1021     ~Utf8Value();
1022     char* operator*() { return str_; }
1023     const char* operator*() const { return str_; }
length()1024     int length() const { return length_; }
1025    private:
1026     char* str_;
1027     int length_;
1028 
1029     // Disallow copying and assigning.
1030     Utf8Value(const Utf8Value&);
1031     void operator=(const Utf8Value&);
1032   };
1033 
1034   /**
1035    * Converts an object to an ascii string.
1036    * Useful if you want to print the object.
1037    * If conversion to a string fails (eg. due to an exception in the toString()
1038    * method of the object) then the length() method returns 0 and the * operator
1039    * returns NULL.
1040    */
1041   class V8EXPORT AsciiValue {
1042    public:
1043     explicit AsciiValue(Handle<v8::Value> obj);
1044     ~AsciiValue();
1045     char* operator*() { return str_; }
1046     const char* operator*() const { return str_; }
length()1047     int length() const { return length_; }
1048    private:
1049     char* str_;
1050     int length_;
1051 
1052     // Disallow copying and assigning.
1053     AsciiValue(const AsciiValue&);
1054     void operator=(const AsciiValue&);
1055   };
1056 
1057   /**
1058    * Converts an object to a two-byte string.
1059    * If conversion to a string fails (eg. due to an exception in the toString()
1060    * method of the object) then the length() method returns 0 and the * operator
1061    * returns NULL.
1062    */
1063   class V8EXPORT Value {
1064    public:
1065     explicit Value(Handle<v8::Value> obj);
1066     ~Value();
1067     uint16_t* operator*() { return str_; }
1068     const uint16_t* operator*() const { return str_; }
length()1069     int length() const { return length_; }
1070    private:
1071     uint16_t* str_;
1072     int length_;
1073 
1074     // Disallow copying and assigning.
1075     Value(const Value&);
1076     void operator=(const Value&);
1077   };
1078 
1079  private:
1080   void VerifyExternalStringResource(ExternalStringResource* val) const;
1081   static void CheckCast(v8::Value* obj);
1082 };
1083 
1084 
1085 /**
1086  * A JavaScript number value (ECMA-262, 4.3.20)
1087  */
1088 class V8EXPORT Number : public Primitive {
1089  public:
1090   double Value() const;
1091   static Local<Number> New(double value);
1092   static inline Number* Cast(v8::Value* obj);
1093  private:
1094   Number();
1095   static void CheckCast(v8::Value* obj);
1096 };
1097 
1098 
1099 /**
1100  * A JavaScript value representing a signed integer.
1101  */
1102 class V8EXPORT Integer : public Number {
1103  public:
1104   static Local<Integer> New(int32_t value);
1105   static Local<Integer> NewFromUnsigned(uint32_t value);
1106   int64_t Value() const;
1107   static inline Integer* Cast(v8::Value* obj);
1108  private:
1109   Integer();
1110   static void CheckCast(v8::Value* obj);
1111 };
1112 
1113 
1114 /**
1115  * A JavaScript value representing a 32-bit signed integer.
1116  */
1117 class V8EXPORT Int32 : public Integer {
1118  public:
1119   int32_t Value() const;
1120  private:
1121   Int32();
1122 };
1123 
1124 
1125 /**
1126  * A JavaScript value representing a 32-bit unsigned integer.
1127  */
1128 class V8EXPORT Uint32 : public Integer {
1129  public:
1130   uint32_t Value() const;
1131  private:
1132   Uint32();
1133 };
1134 
1135 
1136 /**
1137  * An instance of the built-in Date constructor (ECMA-262, 15.9).
1138  */
1139 class V8EXPORT Date : public Value {
1140  public:
1141   static Local<Value> New(double time);
1142 
1143   /**
1144    * A specialization of Value::NumberValue that is more efficient
1145    * because we know the structure of this object.
1146    */
1147   double NumberValue() const;
1148 
1149   static inline Date* Cast(v8::Value* obj);
1150  private:
1151   static void CheckCast(v8::Value* obj);
1152 };
1153 
1154 
1155 enum PropertyAttribute {
1156   None       = 0,
1157   ReadOnly   = 1 << 0,
1158   DontEnum   = 1 << 1,
1159   DontDelete = 1 << 2
1160 };
1161 
1162 enum ExternalArrayType {
1163   kExternalByteArray = 1,
1164   kExternalUnsignedByteArray,
1165   kExternalShortArray,
1166   kExternalUnsignedShortArray,
1167   kExternalIntArray,
1168   kExternalUnsignedIntArray,
1169   kExternalFloatArray
1170 };
1171 
1172 /**
1173  * A JavaScript object (ECMA-262, 4.3.3)
1174  */
1175 class V8EXPORT Object : public Value {
1176  public:
1177   bool Set(Handle<Value> key,
1178            Handle<Value> value,
1179            PropertyAttribute attribs = None);
1180 
1181   // Sets a local property on this object bypassing interceptors and
1182   // overriding accessors or read-only properties.
1183   //
1184   // Note that if the object has an interceptor the property will be set
1185   // locally, but since the interceptor takes precedence the local property
1186   // will only be returned if the interceptor doesn't return a value.
1187   //
1188   // Note also that this only works for named properties.
1189   bool ForceSet(Handle<Value> key,
1190                 Handle<Value> value,
1191                 PropertyAttribute attribs = None);
1192 
1193   Local<Value> Get(Handle<Value> key);
1194 
1195   // TODO(1245389): Replace the type-specific versions of these
1196   // functions with generic ones that accept a Handle<Value> key.
1197   bool Has(Handle<String> key);
1198 
1199   bool Delete(Handle<String> key);
1200 
1201   // Delete a property on this object bypassing interceptors and
1202   // ignoring dont-delete attributes.
1203   bool ForceDelete(Handle<Value> key);
1204 
1205   bool Has(uint32_t index);
1206 
1207   bool Delete(uint32_t index);
1208 
1209   /**
1210    * Returns an array containing the names of the enumerable properties
1211    * of this object, including properties from prototype objects.  The
1212    * array returned by this method contains the same values as would
1213    * be enumerated by a for-in statement over this object.
1214    */
1215   Local<Array> GetPropertyNames();
1216 
1217   /**
1218    * Get the prototype object.  This does not skip objects marked to
1219    * be skipped by __proto__ and it does not consult the security
1220    * handler.
1221    */
1222   Local<Value> GetPrototype();
1223 
1224   /**
1225    * Set the prototype object.  This does not skip objects marked to
1226    * be skipped by __proto__ and it does not consult the security
1227    * handler.
1228    */
1229   bool SetPrototype(Handle<Value> prototype);
1230 
1231   /**
1232    * Finds an instance of the given function template in the prototype
1233    * chain.
1234    */
1235   Local<Object> FindInstanceInPrototypeChain(Handle<FunctionTemplate> tmpl);
1236 
1237   /**
1238    * Call builtin Object.prototype.toString on this object.
1239    * This is different from Value::ToString() that may call
1240    * user-defined toString function. This one does not.
1241    */
1242   Local<String> ObjectProtoToString();
1243 
1244   /** Gets the number of internal fields for this Object. */
1245   int InternalFieldCount();
1246   /** Gets the value in an internal field. */
1247   inline Local<Value> GetInternalField(int index);
1248   /** Sets the value in an internal field. */
1249   void SetInternalField(int index, Handle<Value> value);
1250 
1251   /** Gets a native pointer from an internal field. */
1252   inline void* GetPointerFromInternalField(int index);
1253 
1254   /** Sets a native pointer in an internal field. */
1255   void SetPointerInInternalField(int index, void* value);
1256 
1257   // Testers for local properties.
1258   bool HasRealNamedProperty(Handle<String> key);
1259   bool HasRealIndexedProperty(uint32_t index);
1260   bool HasRealNamedCallbackProperty(Handle<String> key);
1261 
1262   /**
1263    * If result.IsEmpty() no real property was located in the prototype chain.
1264    * This means interceptors in the prototype chain are not called.
1265    */
1266   Local<Value> GetRealNamedPropertyInPrototypeChain(Handle<String> key);
1267 
1268   /**
1269    * If result.IsEmpty() no real property was located on the object or
1270    * in the prototype chain.
1271    * This means interceptors in the prototype chain are not called.
1272    */
1273   Local<Value> GetRealNamedProperty(Handle<String> key);
1274 
1275   /** Tests for a named lookup interceptor.*/
1276   bool HasNamedLookupInterceptor();
1277 
1278   /** Tests for an index lookup interceptor.*/
1279   bool HasIndexedLookupInterceptor();
1280 
1281   /**
1282    * Turns on access check on the object if the object is an instance of
1283    * a template that has access check callbacks. If an object has no
1284    * access check info, the object cannot be accessed by anyone.
1285    */
1286   void TurnOnAccessCheck();
1287 
1288   /**
1289    * Returns the identity hash for this object. The current implemenation uses
1290    * a hidden property on the object to store the identity hash.
1291    *
1292    * The return value will never be 0. Also, it is not guaranteed to be
1293    * unique.
1294    */
1295   int GetIdentityHash();
1296 
1297   /**
1298    * Access hidden properties on JavaScript objects. These properties are
1299    * hidden from the executing JavaScript and only accessible through the V8
1300    * C++ API. Hidden properties introduced by V8 internally (for example the
1301    * identity hash) are prefixed with "v8::".
1302    */
1303   bool SetHiddenValue(Handle<String> key, Handle<Value> value);
1304   Local<Value> GetHiddenValue(Handle<String> key);
1305   bool DeleteHiddenValue(Handle<String> key);
1306 
1307   /**
1308    * Returns true if this is an instance of an api function (one
1309    * created from a function created from a function template) and has
1310    * been modified since it was created.  Note that this method is
1311    * conservative and may return true for objects that haven't actually
1312    * been modified.
1313    */
1314   bool IsDirty();
1315 
1316   /**
1317    * Clone this object with a fast but shallow copy.  Values will point
1318    * to the same values as the original object.
1319    */
1320   Local<Object> Clone();
1321 
1322   /**
1323    * Set the backing store of the indexed properties to be managed by the
1324    * embedding layer. Access to the indexed properties will follow the rules
1325    * spelled out in CanvasPixelArray.
1326    * Note: The embedding program still owns the data and needs to ensure that
1327    *       the backing store is preserved while V8 has a reference.
1328    */
1329   void SetIndexedPropertiesToPixelData(uint8_t* data, int length);
1330 
1331   /**
1332    * Set the backing store of the indexed properties to be managed by the
1333    * embedding layer. Access to the indexed properties will follow the rules
1334    * spelled out for the CanvasArray subtypes in the WebGL specification.
1335    * Note: The embedding program still owns the data and needs to ensure that
1336    *       the backing store is preserved while V8 has a reference.
1337    */
1338   void SetIndexedPropertiesToExternalArrayData(void* data,
1339                                                ExternalArrayType array_type,
1340                                                int number_of_elements);
1341 
1342   static Local<Object> New();
1343   static inline Object* Cast(Value* obj);
1344  private:
1345   Object();
1346   static void CheckCast(Value* obj);
1347   Local<Value> CheckedGetInternalField(int index);
1348   void* SlowGetPointerFromInternalField(int index);
1349 
1350   /**
1351    * If quick access to the internal field is possible this method
1352    * returns the value.  Otherwise an empty handle is returned.
1353    */
1354   inline Local<Value> UncheckedGetInternalField(int index);
1355 };
1356 
1357 
1358 /**
1359  * An instance of the built-in array constructor (ECMA-262, 15.4.2).
1360  */
1361 class V8EXPORT Array : public Object {
1362  public:
1363   uint32_t Length() const;
1364 
1365   /**
1366    * Clones an element at index |index|.  Returns an empty
1367    * handle if cloning fails (for any reason).
1368    */
1369   Local<Object> CloneElementAt(uint32_t index);
1370 
1371   static Local<Array> New(int length = 0);
1372   static inline Array* Cast(Value* obj);
1373  private:
1374   Array();
1375   static void CheckCast(Value* obj);
1376 };
1377 
1378 
1379 /**
1380  * A JavaScript function object (ECMA-262, 15.3).
1381  */
1382 class V8EXPORT Function : public Object {
1383  public:
1384   Local<Object> NewInstance() const;
1385   Local<Object> NewInstance(int argc, Handle<Value> argv[]) const;
1386   Local<Value> Call(Handle<Object> recv, int argc, Handle<Value> argv[]);
1387   void SetName(Handle<String> name);
1388   Handle<Value> GetName() const;
1389 
1390   /**
1391    * Returns zero based line number of function body and
1392    * kLineOffsetNotFound if no information available.
1393    */
1394   int GetScriptLineNumber() const;
1395   ScriptOrigin GetScriptOrigin() const;
1396   static inline Function* Cast(Value* obj);
1397   static const int kLineOffsetNotFound;
1398  private:
1399   Function();
1400   static void CheckCast(Value* obj);
1401 };
1402 
1403 
1404 /**
1405  * A JavaScript value that wraps a C++ void*.  This type of value is
1406  * mainly used to associate C++ data structures with JavaScript
1407  * objects.
1408  *
1409  * The Wrap function V8 will return the most optimal Value object wrapping the
1410  * C++ void*. The type of the value is not guaranteed to be an External object
1411  * and no assumptions about its type should be made. To access the wrapped
1412  * value Unwrap should be used, all other operations on that object will lead
1413  * to unpredictable results.
1414  */
1415 class V8EXPORT External : public Value {
1416  public:
1417   static Local<Value> Wrap(void* data);
1418   static inline void* Unwrap(Handle<Value> obj);
1419 
1420   static Local<External> New(void* value);
1421   static inline External* Cast(Value* obj);
1422   void* Value() const;
1423  private:
1424   External();
1425   static void CheckCast(v8::Value* obj);
1426   static inline void* QuickUnwrap(Handle<v8::Value> obj);
1427   static void* FullUnwrap(Handle<v8::Value> obj);
1428 };
1429 
1430 
1431 // --- T e m p l a t e s ---
1432 
1433 
1434 /**
1435  * The superclass of object and function templates.
1436  */
1437 class V8EXPORT Template : public Data {
1438  public:
1439   /** Adds a property to each instance created by this template.*/
1440   void Set(Handle<String> name, Handle<Data> value,
1441            PropertyAttribute attributes = None);
1442   inline void Set(const char* name, Handle<Data> value);
1443  private:
1444   Template();
1445 
1446   friend class ObjectTemplate;
1447   friend class FunctionTemplate;
1448 };
1449 
1450 
1451 /**
1452  * The argument information given to function call callbacks.  This
1453  * class provides access to information about the context of the call,
1454  * including the receiver, the number and values of arguments, and
1455  * the holder of the function.
1456  */
1457 class V8EXPORT Arguments {
1458  public:
1459   inline int Length() const;
1460   inline Local<Value> operator[](int i) const;
1461   inline Local<Function> Callee() const;
1462   inline Local<Object> This() const;
1463   inline Local<Object> Holder() const;
1464   inline bool IsConstructCall() const;
1465   inline Local<Value> Data() const;
1466  private:
1467   Arguments();
1468   friend class ImplementationUtilities;
1469   inline Arguments(Local<Value> data,
1470                    Local<Object> holder,
1471                    Local<Function> callee,
1472                    bool is_construct_call,
1473                    void** values, int length);
1474   Local<Value> data_;
1475   Local<Object> holder_;
1476   Local<Function> callee_;
1477   bool is_construct_call_;
1478   void** values_;
1479   int length_;
1480 };
1481 
1482 
1483 /**
1484  * The information passed to an accessor callback about the context
1485  * of the property access.
1486  */
1487 class V8EXPORT AccessorInfo {
1488  public:
AccessorInfo(internal::Object ** args)1489   inline AccessorInfo(internal::Object** args)
1490       : args_(args) { }
1491   inline Local<Value> Data() const;
1492   inline Local<Object> This() const;
1493   inline Local<Object> Holder() const;
1494  private:
1495   internal::Object** args_;
1496 };
1497 
1498 
1499 typedef Handle<Value> (*InvocationCallback)(const Arguments& args);
1500 
1501 typedef int (*LookupCallback)(Local<Object> self, Local<String> name);
1502 
1503 /**
1504  * Accessor[Getter|Setter] are used as callback functions when
1505  * setting|getting a particular property. See objectTemplate::SetAccessor.
1506  */
1507 typedef Handle<Value> (*AccessorGetter)(Local<String> property,
1508                                         const AccessorInfo& info);
1509 
1510 
1511 typedef void (*AccessorSetter)(Local<String> property,
1512                                Local<Value> value,
1513                                const AccessorInfo& info);
1514 
1515 
1516 /**
1517  * NamedProperty[Getter|Setter] are used as interceptors on object.
1518  * See ObjectTemplate::SetNamedPropertyHandler.
1519  */
1520 typedef Handle<Value> (*NamedPropertyGetter)(Local<String> property,
1521                                              const AccessorInfo& info);
1522 
1523 
1524 /**
1525  * Returns the value if the setter intercepts the request.
1526  * Otherwise, returns an empty handle.
1527  */
1528 typedef Handle<Value> (*NamedPropertySetter)(Local<String> property,
1529                                              Local<Value> value,
1530                                              const AccessorInfo& info);
1531 
1532 
1533 /**
1534  * Returns a non-empty handle if the interceptor intercepts the request.
1535  * The result is true if the property exists and false otherwise.
1536  */
1537 typedef Handle<Boolean> (*NamedPropertyQuery)(Local<String> property,
1538                                               const AccessorInfo& info);
1539 
1540 
1541 /**
1542  * Returns a non-empty handle if the deleter intercepts the request.
1543  * The return value is true if the property could be deleted and false
1544  * otherwise.
1545  */
1546 typedef Handle<Boolean> (*NamedPropertyDeleter)(Local<String> property,
1547                                                 const AccessorInfo& info);
1548 
1549 /**
1550  * Returns an array containing the names of the properties the named
1551  * property getter intercepts.
1552  */
1553 typedef Handle<Array> (*NamedPropertyEnumerator)(const AccessorInfo& info);
1554 
1555 
1556 /**
1557  * Returns the value of the property if the getter intercepts the
1558  * request.  Otherwise, returns an empty handle.
1559  */
1560 typedef Handle<Value> (*IndexedPropertyGetter)(uint32_t index,
1561                                                const AccessorInfo& info);
1562 
1563 
1564 /**
1565  * Returns the value if the setter intercepts the request.
1566  * Otherwise, returns an empty handle.
1567  */
1568 typedef Handle<Value> (*IndexedPropertySetter)(uint32_t index,
1569                                                Local<Value> value,
1570                                                const AccessorInfo& info);
1571 
1572 
1573 /**
1574  * Returns a non-empty handle if the interceptor intercepts the request.
1575  * The result is true if the property exists and false otherwise.
1576  */
1577 typedef Handle<Boolean> (*IndexedPropertyQuery)(uint32_t index,
1578                                                 const AccessorInfo& info);
1579 
1580 /**
1581  * Returns a non-empty handle if the deleter intercepts the request.
1582  * The return value is true if the property could be deleted and false
1583  * otherwise.
1584  */
1585 typedef Handle<Boolean> (*IndexedPropertyDeleter)(uint32_t index,
1586                                                   const AccessorInfo& info);
1587 
1588 /**
1589  * Returns an array containing the indices of the properties the
1590  * indexed property getter intercepts.
1591  */
1592 typedef Handle<Array> (*IndexedPropertyEnumerator)(const AccessorInfo& info);
1593 
1594 
1595 /**
1596  * Access control specifications.
1597  *
1598  * Some accessors should be accessible across contexts.  These
1599  * accessors have an explicit access control parameter which specifies
1600  * the kind of cross-context access that should be allowed.
1601  *
1602  * Additionally, for security, accessors can prohibit overwriting by
1603  * accessors defined in JavaScript.  For objects that have such
1604  * accessors either locally or in their prototype chain it is not
1605  * possible to overwrite the accessor by using __defineGetter__ or
1606  * __defineSetter__ from JavaScript code.
1607  */
1608 enum AccessControl {
1609   DEFAULT               = 0,
1610   ALL_CAN_READ          = 1,
1611   ALL_CAN_WRITE         = 1 << 1,
1612   PROHIBITS_OVERWRITING = 1 << 2
1613 };
1614 
1615 
1616 /**
1617  * Access type specification.
1618  */
1619 enum AccessType {
1620   ACCESS_GET,
1621   ACCESS_SET,
1622   ACCESS_HAS,
1623   ACCESS_DELETE,
1624   ACCESS_KEYS
1625 };
1626 
1627 
1628 /**
1629  * Returns true if cross-context access should be allowed to the named
1630  * property with the given key on the host object.
1631  */
1632 typedef bool (*NamedSecurityCallback)(Local<Object> host,
1633                                       Local<Value> key,
1634                                       AccessType type,
1635                                       Local<Value> data);
1636 
1637 
1638 /**
1639  * Returns true if cross-context access should be allowed to the indexed
1640  * property with the given index on the host object.
1641  */
1642 typedef bool (*IndexedSecurityCallback)(Local<Object> host,
1643                                         uint32_t index,
1644                                         AccessType type,
1645                                         Local<Value> data);
1646 
1647 
1648 /**
1649  * A FunctionTemplate is used to create functions at runtime. There
1650  * can only be one function created from a FunctionTemplate in a
1651  * context.  The lifetime of the created function is equal to the
1652  * lifetime of the context.  So in case the embedder needs to create
1653  * temporary functions that can be collected using Scripts is
1654  * preferred.
1655  *
1656  * A FunctionTemplate can have properties, these properties are added to the
1657  * function object when it is created.
1658  *
1659  * A FunctionTemplate has a corresponding instance template which is
1660  * used to create object instances when the function is used as a
1661  * constructor. Properties added to the instance template are added to
1662  * each object instance.
1663  *
1664  * A FunctionTemplate can have a prototype template. The prototype template
1665  * is used to create the prototype object of the function.
1666  *
1667  * The following example shows how to use a FunctionTemplate:
1668  *
1669  * \code
1670  *    v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
1671  *    t->Set("func_property", v8::Number::New(1));
1672  *
1673  *    v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
1674  *    proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
1675  *    proto_t->Set("proto_const", v8::Number::New(2));
1676  *
1677  *    v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
1678  *    instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
1679  *    instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
1680  *    instance_t->Set("instance_property", Number::New(3));
1681  *
1682  *    v8::Local<v8::Function> function = t->GetFunction();
1683  *    v8::Local<v8::Object> instance = function->NewInstance();
1684  * \endcode
1685  *
1686  * Let's use "function" as the JS variable name of the function object
1687  * and "instance" for the instance object created above.  The function
1688  * and the instance will have the following properties:
1689  *
1690  * \code
1691  *   func_property in function == true;
1692  *   function.func_property == 1;
1693  *
1694  *   function.prototype.proto_method() invokes 'InvokeCallback'
1695  *   function.prototype.proto_const == 2;
1696  *
1697  *   instance instanceof function == true;
1698  *   instance.instance_accessor calls 'InstanceAccessorCallback'
1699  *   instance.instance_property == 3;
1700  * \endcode
1701  *
1702  * A FunctionTemplate can inherit from another one by calling the
1703  * FunctionTemplate::Inherit method.  The following graph illustrates
1704  * the semantics of inheritance:
1705  *
1706  * \code
1707  *   FunctionTemplate Parent  -> Parent() . prototype -> { }
1708  *     ^                                                  ^
1709  *     | Inherit(Parent)                                  | .__proto__
1710  *     |                                                  |
1711  *   FunctionTemplate Child   -> Child()  . prototype -> { }
1712  * \endcode
1713  *
1714  * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
1715  * object of the Child() function has __proto__ pointing to the
1716  * Parent() function's prototype object. An instance of the Child
1717  * function has all properties on Parent's instance templates.
1718  *
1719  * Let Parent be the FunctionTemplate initialized in the previous
1720  * section and create a Child FunctionTemplate by:
1721  *
1722  * \code
1723  *   Local<FunctionTemplate> parent = t;
1724  *   Local<FunctionTemplate> child = FunctionTemplate::New();
1725  *   child->Inherit(parent);
1726  *
1727  *   Local<Function> child_function = child->GetFunction();
1728  *   Local<Object> child_instance = child_function->NewInstance();
1729  * \endcode
1730  *
1731  * The Child function and Child instance will have the following
1732  * properties:
1733  *
1734  * \code
1735  *   child_func.prototype.__proto__ == function.prototype;
1736  *   child_instance.instance_accessor calls 'InstanceAccessorCallback'
1737  *   child_instance.instance_property == 3;
1738  * \endcode
1739  */
1740 class V8EXPORT FunctionTemplate : public Template {
1741  public:
1742   /** Creates a function template.*/
1743   static Local<FunctionTemplate> New(
1744       InvocationCallback callback = 0,
1745       Handle<Value> data = Handle<Value>(),
1746       Handle<Signature> signature = Handle<Signature>());
1747   /** Returns the unique function instance in the current execution context.*/
1748   Local<Function> GetFunction();
1749 
1750   /**
1751    * Set the call-handler callback for a FunctionTemplate.  This
1752    * callback is called whenever the function created from this
1753    * FunctionTemplate is called.
1754    */
1755   void SetCallHandler(InvocationCallback callback,
1756                       Handle<Value> data = Handle<Value>());
1757 
1758   /** Get the InstanceTemplate. */
1759   Local<ObjectTemplate> InstanceTemplate();
1760 
1761   /** Causes the function template to inherit from a parent function template.*/
1762   void Inherit(Handle<FunctionTemplate> parent);
1763 
1764   /**
1765    * A PrototypeTemplate is the template used to create the prototype object
1766    * of the function created by this template.
1767    */
1768   Local<ObjectTemplate> PrototypeTemplate();
1769 
1770 
1771   /**
1772    * Set the class name of the FunctionTemplate.  This is used for
1773    * printing objects created with the function created from the
1774    * FunctionTemplate as its constructor.
1775    */
1776   void SetClassName(Handle<String> name);
1777 
1778   /**
1779    * Determines whether the __proto__ accessor ignores instances of
1780    * the function template.  If instances of the function template are
1781    * ignored, __proto__ skips all instances and instead returns the
1782    * next object in the prototype chain.
1783    *
1784    * Call with a value of true to make the __proto__ accessor ignore
1785    * instances of the function template.  Call with a value of false
1786    * to make the __proto__ accessor not ignore instances of the
1787    * function template.  By default, instances of a function template
1788    * are not ignored.
1789    */
1790   void SetHiddenPrototype(bool value);
1791 
1792   /**
1793    * Returns true if the given object is an instance of this function
1794    * template.
1795    */
1796   bool HasInstance(Handle<Value> object);
1797 
1798  private:
1799   FunctionTemplate();
1800   void AddInstancePropertyAccessor(Handle<String> name,
1801                                    AccessorGetter getter,
1802                                    AccessorSetter setter,
1803                                    Handle<Value> data,
1804                                    AccessControl settings,
1805                                    PropertyAttribute attributes);
1806   void SetNamedInstancePropertyHandler(NamedPropertyGetter getter,
1807                                        NamedPropertySetter setter,
1808                                        NamedPropertyQuery query,
1809                                        NamedPropertyDeleter remover,
1810                                        NamedPropertyEnumerator enumerator,
1811                                        Handle<Value> data);
1812   void SetIndexedInstancePropertyHandler(IndexedPropertyGetter getter,
1813                                          IndexedPropertySetter setter,
1814                                          IndexedPropertyQuery query,
1815                                          IndexedPropertyDeleter remover,
1816                                          IndexedPropertyEnumerator enumerator,
1817                                          Handle<Value> data);
1818   void SetInstanceCallAsFunctionHandler(InvocationCallback callback,
1819                                         Handle<Value> data);
1820 
1821   friend class Context;
1822   friend class ObjectTemplate;
1823 };
1824 
1825 
1826 /**
1827  * An ObjectTemplate is used to create objects at runtime.
1828  *
1829  * Properties added to an ObjectTemplate are added to each object
1830  * created from the ObjectTemplate.
1831  */
1832 class V8EXPORT ObjectTemplate : public Template {
1833  public:
1834   /** Creates an ObjectTemplate. */
1835   static Local<ObjectTemplate> New();
1836 
1837   /** Creates a new instance of this template.*/
1838   Local<Object> NewInstance();
1839 
1840   /**
1841    * Sets an accessor on the object template.
1842    *
1843    * Whenever the property with the given name is accessed on objects
1844    * created from this ObjectTemplate the getter and setter callbacks
1845    * are called instead of getting and setting the property directly
1846    * on the JavaScript object.
1847    *
1848    * \param name The name of the property for which an accessor is added.
1849    * \param getter The callback to invoke when getting the property.
1850    * \param setter The callback to invoke when setting the property.
1851    * \param data A piece of data that will be passed to the getter and setter
1852    *   callbacks whenever they are invoked.
1853    * \param settings Access control settings for the accessor. This is a bit
1854    *   field consisting of one of more of
1855    *   DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
1856    *   The default is to not allow cross-context access.
1857    *   ALL_CAN_READ means that all cross-context reads are allowed.
1858    *   ALL_CAN_WRITE means that all cross-context writes are allowed.
1859    *   The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
1860    *   cross-context access.
1861    * \param attribute The attributes of the property for which an accessor
1862    *   is added.
1863    */
1864   void SetAccessor(Handle<String> name,
1865                    AccessorGetter getter,
1866                    AccessorSetter setter = 0,
1867                    Handle<Value> data = Handle<Value>(),
1868                    AccessControl settings = DEFAULT,
1869                    PropertyAttribute attribute = None);
1870 
1871   /**
1872    * Sets a named property handler on the object template.
1873    *
1874    * Whenever a named property is accessed on objects created from
1875    * this object template, the provided callback is invoked instead of
1876    * accessing the property directly on the JavaScript object.
1877    *
1878    * \param getter The callback to invoke when getting a property.
1879    * \param setter The callback to invoke when setting a property.
1880    * \param query The callback to invoke to check is an object has a property.
1881    * \param deleter The callback to invoke when deleting a property.
1882    * \param enumerator The callback to invoke to enumerate all the named
1883    *   properties of an object.
1884    * \param data A piece of data that will be passed to the callbacks
1885    *   whenever they are invoked.
1886    */
1887   void SetNamedPropertyHandler(NamedPropertyGetter getter,
1888                                NamedPropertySetter setter = 0,
1889                                NamedPropertyQuery query = 0,
1890                                NamedPropertyDeleter deleter = 0,
1891                                NamedPropertyEnumerator enumerator = 0,
1892                                Handle<Value> data = Handle<Value>());
1893 
1894   /**
1895    * Sets an indexed property handler on the object template.
1896    *
1897    * Whenever an indexed property is accessed on objects created from
1898    * this object template, the provided callback is invoked instead of
1899    * accessing the property directly on the JavaScript object.
1900    *
1901    * \param getter The callback to invoke when getting a property.
1902    * \param setter The callback to invoke when setting a property.
1903    * \param query The callback to invoke to check is an object has a property.
1904    * \param deleter The callback to invoke when deleting a property.
1905    * \param enumerator The callback to invoke to enumerate all the indexed
1906    *   properties of an object.
1907    * \param data A piece of data that will be passed to the callbacks
1908    *   whenever they are invoked.
1909    */
1910   void SetIndexedPropertyHandler(IndexedPropertyGetter getter,
1911                                  IndexedPropertySetter setter = 0,
1912                                  IndexedPropertyQuery query = 0,
1913                                  IndexedPropertyDeleter deleter = 0,
1914                                  IndexedPropertyEnumerator enumerator = 0,
1915                                  Handle<Value> data = Handle<Value>());
1916   /**
1917    * Sets the callback to be used when calling instances created from
1918    * this template as a function.  If no callback is set, instances
1919    * behave like normal JavaScript objects that cannot be called as a
1920    * function.
1921    */
1922   void SetCallAsFunctionHandler(InvocationCallback callback,
1923                                 Handle<Value> data = Handle<Value>());
1924 
1925   /**
1926    * Mark object instances of the template as undetectable.
1927    *
1928    * In many ways, undetectable objects behave as though they are not
1929    * there.  They behave like 'undefined' in conditionals and when
1930    * printed.  However, properties can be accessed and called as on
1931    * normal objects.
1932    */
1933   void MarkAsUndetectable();
1934 
1935   /**
1936    * Sets access check callbacks on the object template.
1937    *
1938    * When accessing properties on instances of this object template,
1939    * the access check callback will be called to determine whether or
1940    * not to allow cross-context access to the properties.
1941    * The last parameter specifies whether access checks are turned
1942    * on by default on instances. If access checks are off by default,
1943    * they can be turned on on individual instances by calling
1944    * Object::TurnOnAccessCheck().
1945    */
1946   void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
1947                                IndexedSecurityCallback indexed_handler,
1948                                Handle<Value> data = Handle<Value>(),
1949                                bool turned_on_by_default = true);
1950 
1951   /**
1952    * Gets the number of internal fields for objects generated from
1953    * this template.
1954    */
1955   int InternalFieldCount();
1956 
1957   /**
1958    * Sets the number of internal fields for objects generated from
1959    * this template.
1960    */
1961   void SetInternalFieldCount(int value);
1962 
1963  private:
1964   ObjectTemplate();
1965   static Local<ObjectTemplate> New(Handle<FunctionTemplate> constructor);
1966   friend class FunctionTemplate;
1967 };
1968 
1969 
1970 /**
1971  * A Signature specifies which receivers and arguments a function can
1972  * legally be called with.
1973  */
1974 class V8EXPORT Signature : public Data {
1975  public:
1976   static Local<Signature> New(Handle<FunctionTemplate> receiver =
1977                                   Handle<FunctionTemplate>(),
1978                               int argc = 0,
1979                               Handle<FunctionTemplate> argv[] = 0);
1980  private:
1981   Signature();
1982 };
1983 
1984 
1985 /**
1986  * A utility for determining the type of objects based on the template
1987  * they were constructed from.
1988  */
1989 class V8EXPORT TypeSwitch : public Data {
1990  public:
1991   static Local<TypeSwitch> New(Handle<FunctionTemplate> type);
1992   static Local<TypeSwitch> New(int argc, Handle<FunctionTemplate> types[]);
1993   int match(Handle<Value> value);
1994  private:
1995   TypeSwitch();
1996 };
1997 
1998 
1999 // --- E x t e n s i o n s ---
2000 
2001 
2002 /**
2003  * Ignore
2004  */
2005 class V8EXPORT Extension {  // NOLINT
2006  public:
2007   Extension(const char* name,
2008             const char* source = 0,
2009             int dep_count = 0,
2010             const char** deps = 0);
~Extension()2011   virtual ~Extension() { }
2012   virtual v8::Handle<v8::FunctionTemplate>
GetNativeFunction(v8::Handle<v8::String> name)2013       GetNativeFunction(v8::Handle<v8::String> name) {
2014     return v8::Handle<v8::FunctionTemplate>();
2015   }
2016 
name()2017   const char* name() { return name_; }
source()2018   const char* source() { return source_; }
dependency_count()2019   int dependency_count() { return dep_count_; }
dependencies()2020   const char** dependencies() { return deps_; }
set_auto_enable(bool value)2021   void set_auto_enable(bool value) { auto_enable_ = value; }
auto_enable()2022   bool auto_enable() { return auto_enable_; }
2023 
2024  private:
2025   const char* name_;
2026   const char* source_;
2027   int dep_count_;
2028   const char** deps_;
2029   bool auto_enable_;
2030 
2031   // Disallow copying and assigning.
2032   Extension(const Extension&);
2033   void operator=(const Extension&);
2034 };
2035 
2036 
2037 void V8EXPORT RegisterExtension(Extension* extension);
2038 
2039 
2040 /**
2041  * Ignore
2042  */
2043 class V8EXPORT DeclareExtension {
2044  public:
DeclareExtension(Extension * extension)2045   inline DeclareExtension(Extension* extension) {
2046     RegisterExtension(extension);
2047   }
2048 };
2049 
2050 
2051 // --- S t a t i c s ---
2052 
2053 
2054 Handle<Primitive> V8EXPORT Undefined();
2055 Handle<Primitive> V8EXPORT Null();
2056 Handle<Boolean> V8EXPORT True();
2057 Handle<Boolean> V8EXPORT False();
2058 
2059 
2060 /**
2061  * A set of constraints that specifies the limits of the runtime's memory use.
2062  * You must set the heap size before initializing the VM - the size cannot be
2063  * adjusted after the VM is initialized.
2064  *
2065  * If you are using threads then you should hold the V8::Locker lock while
2066  * setting the stack limit and you must set a non-default stack limit separately
2067  * for each thread.
2068  */
2069 class V8EXPORT ResourceConstraints {
2070  public:
2071   ResourceConstraints();
max_young_space_size()2072   int max_young_space_size() const { return max_young_space_size_; }
set_max_young_space_size(int value)2073   void set_max_young_space_size(int value) { max_young_space_size_ = value; }
max_old_space_size()2074   int max_old_space_size() const { return max_old_space_size_; }
set_max_old_space_size(int value)2075   void set_max_old_space_size(int value) { max_old_space_size_ = value; }
stack_limit()2076   uint32_t* stack_limit() const { return stack_limit_; }
2077   // Sets an address beyond which the VM's stack may not grow.
set_stack_limit(uint32_t * value)2078   void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
2079  private:
2080   int max_young_space_size_;
2081   int max_old_space_size_;
2082   uint32_t* stack_limit_;
2083 };
2084 
2085 
2086 bool SetResourceConstraints(ResourceConstraints* constraints);
2087 
2088 
2089 // --- E x c e p t i o n s ---
2090 
2091 
2092 typedef void (*FatalErrorCallback)(const char* location, const char* message);
2093 
2094 
2095 typedef void (*MessageCallback)(Handle<Message> message, Handle<Value> data);
2096 
2097 
2098 /**
2099  * Schedules an exception to be thrown when returning to JavaScript.  When an
2100  * exception has been scheduled it is illegal to invoke any JavaScript
2101  * operation; the caller must return immediately and only after the exception
2102  * has been handled does it become legal to invoke JavaScript operations.
2103  */
2104 Handle<Value> V8EXPORT ThrowException(Handle<Value> exception);
2105 
2106 /**
2107  * Create new error objects by calling the corresponding error object
2108  * constructor with the message.
2109  */
2110 class V8EXPORT Exception {
2111  public:
2112   static Local<Value> RangeError(Handle<String> message);
2113   static Local<Value> ReferenceError(Handle<String> message);
2114   static Local<Value> SyntaxError(Handle<String> message);
2115   static Local<Value> TypeError(Handle<String> message);
2116   static Local<Value> Error(Handle<String> message);
2117 };
2118 
2119 
2120 // --- C o u n t e r s  C a l l b a c k s ---
2121 
2122 typedef int* (*CounterLookupCallback)(const char* name);
2123 
2124 typedef void* (*CreateHistogramCallback)(const char* name,
2125                                          int min,
2126                                          int max,
2127                                          size_t buckets);
2128 
2129 typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
2130 
2131 // --- F a i l e d A c c e s s C h e c k C a l l b a c k ---
2132 typedef void (*FailedAccessCheckCallback)(Local<Object> target,
2133                                           AccessType type,
2134                                           Local<Value> data);
2135 
2136 // --- G a r b a g e C o l l e c t i o n  C a l l b a c k s
2137 
2138 /**
2139  * Applications can register a callback function which is called
2140  * before and after a major garbage collection.  Allocations are not
2141  * allowed in the callback function, you therefore cannot manipulate
2142  * objects (set or delete properties for example) since it is possible
2143  * such operations will result in the allocation of objects.
2144  */
2145 typedef void (*GCCallback)();
2146 
2147 
2148 // --- C o n t e x t  G e n e r a t o r ---
2149 
2150 /**
2151  * Applications must provide a callback function which is called to generate
2152  * a context if a context was not deserialized from the snapshot.
2153  */
2154 typedef Persistent<Context> (*ContextGenerator)();
2155 
2156 
2157 /**
2158  * Profiler modules.
2159  *
2160  * In V8, profiler consists of several modules: CPU profiler, and different
2161  * kinds of heap profiling. Each can be turned on / off independently.
2162  * When PROFILER_MODULE_HEAP_SNAPSHOT flag is passed to ResumeProfilerEx,
2163  * modules are enabled only temporarily for making a snapshot of the heap.
2164  */
2165 enum ProfilerModules {
2166   PROFILER_MODULE_NONE            = 0,
2167   PROFILER_MODULE_CPU             = 1,
2168   PROFILER_MODULE_HEAP_STATS      = 1 << 1,
2169   PROFILER_MODULE_JS_CONSTRUCTORS = 1 << 2,
2170   PROFILER_MODULE_HEAP_SNAPSHOT   = 1 << 16
2171 };
2172 
2173 
2174 /**
2175  * Collection of V8 heap information.
2176  *
2177  * Instances of this class can be passed to v8::V8::HeapStatistics to
2178  * get heap statistics from V8.
2179  */
2180 class V8EXPORT HeapStatistics {
2181  public:
2182   HeapStatistics();
total_heap_size()2183   size_t total_heap_size() { return total_heap_size_; }
used_heap_size()2184   size_t used_heap_size() { return used_heap_size_; }
2185 
2186  private:
set_total_heap_size(size_t size)2187   void set_total_heap_size(size_t size) { total_heap_size_ = size; }
set_used_heap_size(size_t size)2188   void set_used_heap_size(size_t size) { used_heap_size_ = size; }
2189 
2190   size_t total_heap_size_;
2191   size_t used_heap_size_;
2192 
2193   friend class V8;
2194 };
2195 
2196 
2197 /**
2198  * Container class for static utility functions.
2199  */
2200 class V8EXPORT V8 {
2201  public:
2202   /** Set the callback to invoke in case of fatal errors. */
2203   static void SetFatalErrorHandler(FatalErrorCallback that);
2204 
2205   /**
2206    * Ignore out-of-memory exceptions.
2207    *
2208    * V8 running out of memory is treated as a fatal error by default.
2209    * This means that the fatal error handler is called and that V8 is
2210    * terminated.
2211    *
2212    * IgnoreOutOfMemoryException can be used to not treat a
2213    * out-of-memory situation as a fatal error.  This way, the contexts
2214    * that did not cause the out of memory problem might be able to
2215    * continue execution.
2216    */
2217   static void IgnoreOutOfMemoryException();
2218 
2219   /**
2220    * Check if V8 is dead and therefore unusable.  This is the case after
2221    * fatal errors such as out-of-memory situations.
2222    */
2223   static bool IsDead();
2224 
2225   /**
2226    * Adds a message listener.
2227    *
2228    * The same message listener can be added more than once and it that
2229    * case it will be called more than once for each message.
2230    */
2231   static bool AddMessageListener(MessageCallback that,
2232                                  Handle<Value> data = Handle<Value>());
2233 
2234   /**
2235    * Remove all message listeners from the specified callback function.
2236    */
2237   static void RemoveMessageListeners(MessageCallback that);
2238 
2239   /**
2240    * Sets V8 flags from a string.
2241    */
2242   static void SetFlagsFromString(const char* str, int length);
2243 
2244   /**
2245    * Sets V8 flags from the command line.
2246    */
2247   static void SetFlagsFromCommandLine(int* argc,
2248                                       char** argv,
2249                                       bool remove_flags);
2250 
2251   /** Get the version string. */
2252   static const char* GetVersion();
2253 
2254   /**
2255    * Enables the host application to provide a mechanism for recording
2256    * statistics counters.
2257    */
2258   static void SetCounterFunction(CounterLookupCallback);
2259 
2260   /**
2261    * Enables the host application to provide a mechanism for recording
2262    * histograms. The CreateHistogram function returns a
2263    * histogram which will later be passed to the AddHistogramSample
2264    * function.
2265    */
2266   static void SetCreateHistogramFunction(CreateHistogramCallback);
2267   static void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
2268 
2269   /**
2270    * Enables the computation of a sliding window of states. The sliding
2271    * window information is recorded in statistics counters.
2272    */
2273   static void EnableSlidingStateWindow();
2274 
2275   /** Callback function for reporting failed access checks.*/
2276   static void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
2277 
2278   /**
2279    * Enables the host application to receive a notification before a
2280    * major garbage colletion.  Allocations are not allowed in the
2281    * callback function, you therefore cannot manipulate objects (set
2282    * or delete properties for example) since it is possible such
2283    * operations will result in the allocation of objects.
2284    */
2285   static void SetGlobalGCPrologueCallback(GCCallback);
2286 
2287   /**
2288    * Enables the host application to receive a notification after a
2289    * major garbage collection.  Allocations are not allowed in the
2290    * callback function, you therefore cannot manipulate objects (set
2291    * or delete properties for example) since it is possible such
2292    * operations will result in the allocation of objects.
2293    */
2294   static void SetGlobalGCEpilogueCallback(GCCallback);
2295 
2296   /**
2297    * Allows the host application to group objects together. If one
2298    * object in the group is alive, all objects in the group are alive.
2299    * After each garbage collection, object groups are removed. It is
2300    * intended to be used in the before-garbage-collection callback
2301    * function, for instance to simulate DOM tree connections among JS
2302    * wrapper objects.
2303    */
2304   static void AddObjectGroup(Persistent<Value>* objects, size_t length);
2305 
2306   /**
2307    * Initializes from snapshot if possible. Otherwise, attempts to
2308    * initialize from scratch.  This function is called implicitly if
2309    * you use the API without calling it first.
2310    */
2311   static bool Initialize();
2312 
2313   /**
2314    * Adjusts the amount of registered external memory.  Used to give
2315    * V8 an indication of the amount of externally allocated memory
2316    * that is kept alive by JavaScript objects.  V8 uses this to decide
2317    * when to perform global garbage collections.  Registering
2318    * externally allocated memory will trigger global garbage
2319    * collections more often than otherwise in an attempt to garbage
2320    * collect the JavaScript objects keeping the externally allocated
2321    * memory alive.
2322    *
2323    * \param change_in_bytes the change in externally allocated memory
2324    *   that is kept alive by JavaScript objects.
2325    * \returns the adjusted value.
2326    */
2327   static int AdjustAmountOfExternalAllocatedMemory(int change_in_bytes);
2328 
2329   /**
2330    * Suspends recording of tick samples in the profiler.
2331    * When the V8 profiling mode is enabled (usually via command line
2332    * switches) this function suspends recording of tick samples.
2333    * Profiling ticks are discarded until ResumeProfiler() is called.
2334    *
2335    * See also the --prof and --prof_auto command line switches to
2336    * enable V8 profiling.
2337    */
2338   static void PauseProfiler();
2339 
2340   /**
2341    * Resumes recording of tick samples in the profiler.
2342    * See also PauseProfiler().
2343    */
2344   static void ResumeProfiler();
2345 
2346   /**
2347    * Return whether profiler is currently paused.
2348    */
2349   static bool IsProfilerPaused();
2350 
2351   /**
2352    * Resumes specified profiler modules. Can be called several times to
2353    * mark the opening of a profiler events block with the given tag.
2354    *
2355    * "ResumeProfiler" is equivalent to "ResumeProfilerEx(PROFILER_MODULE_CPU)".
2356    * See ProfilerModules enum.
2357    *
2358    * \param flags Flags specifying profiler modules.
2359    * \param tag Profile tag.
2360    */
2361   static void ResumeProfilerEx(int flags, int tag = 0);
2362 
2363   /**
2364    * Pauses specified profiler modules. Each call to "PauseProfilerEx" closes
2365    * a block of profiler events opened by a call to "ResumeProfilerEx" with the
2366    * same tag value. There is no need for blocks to be properly nested.
2367    * The profiler is paused when the last opened block is closed.
2368    *
2369    * "PauseProfiler" is equivalent to "PauseProfilerEx(PROFILER_MODULE_CPU)".
2370    * See ProfilerModules enum.
2371    *
2372    * \param flags Flags specifying profiler modules.
2373    * \param tag Profile tag.
2374    */
2375   static void PauseProfilerEx(int flags, int tag = 0);
2376 
2377   /**
2378    * Returns active (resumed) profiler modules.
2379    * See ProfilerModules enum.
2380    *
2381    * \returns active profiler modules.
2382    */
2383   static int GetActiveProfilerModules();
2384 
2385   /**
2386    * If logging is performed into a memory buffer (via --logfile=*), allows to
2387    * retrieve previously written messages. This can be used for retrieving
2388    * profiler log data in the application. This function is thread-safe.
2389    *
2390    * Caller provides a destination buffer that must exist during GetLogLines
2391    * call. Only whole log lines are copied into the buffer.
2392    *
2393    * \param from_pos specified a point in a buffer to read from, 0 is the
2394    *   beginning of a buffer. It is assumed that caller updates its current
2395    *   position using returned size value from the previous call.
2396    * \param dest_buf destination buffer for log data.
2397    * \param max_size size of the destination buffer.
2398    * \returns actual size of log data copied into buffer.
2399    */
2400   static int GetLogLines(int from_pos, char* dest_buf, int max_size);
2401 
2402   /**
2403    * Retrieve the V8 thread id of the calling thread.
2404    *
2405    * The thread id for a thread should only be retrieved after the V8
2406    * lock has been acquired with a Locker object with that thread.
2407    */
2408   static int GetCurrentThreadId();
2409 
2410   /**
2411    * Forcefully terminate execution of a JavaScript thread.  This can
2412    * be used to terminate long-running scripts.
2413    *
2414    * TerminateExecution should only be called when then V8 lock has
2415    * been acquired with a Locker object.  Therefore, in order to be
2416    * able to terminate long-running threads, preemption must be
2417    * enabled to allow the user of TerminateExecution to acquire the
2418    * lock.
2419    *
2420    * The termination is achieved by throwing an exception that is
2421    * uncatchable by JavaScript exception handlers.  Termination
2422    * exceptions act as if they were caught by a C++ TryCatch exception
2423    * handlers.  If forceful termination is used, any C++ TryCatch
2424    * exception handler that catches an exception should check if that
2425    * exception is a termination exception and immediately return if
2426    * that is the case.  Returning immediately in that case will
2427    * continue the propagation of the termination exception if needed.
2428    *
2429    * The thread id passed to TerminateExecution must have been
2430    * obtained by calling GetCurrentThreadId on the thread in question.
2431    *
2432    * \param thread_id The thread id of the thread to terminate.
2433    */
2434   static void TerminateExecution(int thread_id);
2435 
2436   /**
2437    * Forcefully terminate the current thread of JavaScript execution.
2438    *
2439    * This method can be used by any thread even if that thread has not
2440    * acquired the V8 lock with a Locker object.
2441    */
2442   static void TerminateExecution();
2443 
2444   /**
2445    * Releases any resources used by v8 and stops any utility threads
2446    * that may be running.  Note that disposing v8 is permanent, it
2447    * cannot be reinitialized.
2448    *
2449    * It should generally not be necessary to dispose v8 before exiting
2450    * a process, this should happen automatically.  It is only necessary
2451    * to use if the process needs the resources taken up by v8.
2452    */
2453   static bool Dispose();
2454 
2455   /**
2456    * Get statistics about the heap memory usage.
2457    */
2458   static void GetHeapStatistics(HeapStatistics* heap_statistics);
2459 
2460   /**
2461    * Optional notification that the embedder is idle.
2462    * V8 uses the notification to reduce memory footprint.
2463    * This call can be used repeatedly if the embedder remains idle.
2464    * Returns true if the embedder should stop calling IdleNotification
2465    * until real work has been done.  This indicates that V8 has done
2466    * as much cleanup as it will be able to do.
2467    */
2468   static bool IdleNotification();
2469 
2470   /**
2471    * Optional notification that the system is running low on memory.
2472    * V8 uses these notifications to attempt to free memory.
2473    */
2474   static void LowMemoryNotification();
2475 
2476  private:
2477   V8();
2478 
2479   static internal::Object** GlobalizeReference(internal::Object** handle);
2480   static void DisposeGlobal(internal::Object** global_handle);
2481   static void MakeWeak(internal::Object** global_handle,
2482                        void* data,
2483                        WeakReferenceCallback);
2484   static void ClearWeak(internal::Object** global_handle);
2485   static bool IsGlobalNearDeath(internal::Object** global_handle);
2486   static bool IsGlobalWeak(internal::Object** global_handle);
2487 
2488   template <class T> friend class Handle;
2489   template <class T> friend class Local;
2490   template <class T> friend class Persistent;
2491   friend class Context;
2492 };
2493 
2494 
2495 /**
2496  * An external exception handler.
2497  */
2498 class V8EXPORT TryCatch {
2499  public:
2500 
2501   /**
2502    * Creates a new try/catch block and registers it with v8.
2503    */
2504   TryCatch();
2505 
2506   /**
2507    * Unregisters and deletes this try/catch block.
2508    */
2509   ~TryCatch();
2510 
2511   /**
2512    * Returns true if an exception has been caught by this try/catch block.
2513    */
2514   bool HasCaught() const;
2515 
2516   /**
2517    * For certain types of exceptions, it makes no sense to continue
2518    * execution.
2519    *
2520    * Currently, the only type of exception that can be caught by a
2521    * TryCatch handler and for which it does not make sense to continue
2522    * is termination exception.  Such exceptions are thrown when the
2523    * TerminateExecution methods are called to terminate a long-running
2524    * script.
2525    *
2526    * If CanContinue returns false, the correct action is to perform
2527    * any C++ cleanup needed and then return.
2528    */
2529   bool CanContinue() const;
2530 
2531   /**
2532    * Throws the exception caught by this TryCatch in a way that avoids
2533    * it being caught again by this same TryCatch.  As with ThrowException
2534    * it is illegal to execute any JavaScript operations after calling
2535    * ReThrow; the caller must return immediately to where the exception
2536    * is caught.
2537    */
2538   Handle<Value> ReThrow();
2539 
2540   /**
2541    * Returns the exception caught by this try/catch block.  If no exception has
2542    * been caught an empty handle is returned.
2543    *
2544    * The returned handle is valid until this TryCatch block has been destroyed.
2545    */
2546   Local<Value> Exception() const;
2547 
2548   /**
2549    * Returns the .stack property of the thrown object.  If no .stack
2550    * property is present an empty handle is returned.
2551    */
2552   Local<Value> StackTrace() const;
2553 
2554   /**
2555    * Returns the message associated with this exception.  If there is
2556    * no message associated an empty handle is returned.
2557    *
2558    * The returned handle is valid until this TryCatch block has been
2559    * destroyed.
2560    */
2561   Local<v8::Message> Message() const;
2562 
2563   /**
2564    * Clears any exceptions that may have been caught by this try/catch block.
2565    * After this method has been called, HasCaught() will return false.
2566    *
2567    * It is not necessary to clear a try/catch block before using it again; if
2568    * another exception is thrown the previously caught exception will just be
2569    * overwritten.  However, it is often a good idea since it makes it easier
2570    * to determine which operation threw a given exception.
2571    */
2572   void Reset();
2573 
2574   /**
2575    * Set verbosity of the external exception handler.
2576    *
2577    * By default, exceptions that are caught by an external exception
2578    * handler are not reported.  Call SetVerbose with true on an
2579    * external exception handler to have exceptions caught by the
2580    * handler reported as if they were not caught.
2581    */
2582   void SetVerbose(bool value);
2583 
2584   /**
2585    * Set whether or not this TryCatch should capture a Message object
2586    * which holds source information about where the exception
2587    * occurred.  True by default.
2588    */
2589   void SetCaptureMessage(bool value);
2590 
2591  private:
2592   void* next_;
2593   void* exception_;
2594   void* message_;
2595   bool is_verbose_ : 1;
2596   bool can_continue_ : 1;
2597   bool capture_message_ : 1;
2598   bool rethrow_ : 1;
2599 
2600   friend class v8::internal::Top;
2601 };
2602 
2603 
2604 // --- C o n t e x t ---
2605 
2606 
2607 /**
2608  * Ignore
2609  */
2610 class V8EXPORT ExtensionConfiguration {
2611  public:
ExtensionConfiguration(int name_count,const char * names[])2612   ExtensionConfiguration(int name_count, const char* names[])
2613       : name_count_(name_count), names_(names) { }
2614  private:
2615   friend class ImplementationUtilities;
2616   int name_count_;
2617   const char** names_;
2618 };
2619 
2620 
2621 /**
2622  * A sandboxed execution context with its own set of built-in objects
2623  * and functions.
2624  */
2625 class V8EXPORT Context {
2626  public:
2627   /** Returns the global object of the context. */
2628   Local<Object> Global();
2629 
2630   /**
2631    * Detaches the global object from its context before
2632    * the global object can be reused to create a new context.
2633    */
2634   void DetachGlobal();
2635 
2636   /**
2637    * Reattaches a global object to a context.  This can be used to
2638    * restore the connection between a global object and a context
2639    * after DetachGlobal has been called.
2640    *
2641    * \param global_object The global object to reattach to the
2642    *   context.  For this to work, the global object must be the global
2643    *   object that was associated with this context before a call to
2644    *   DetachGlobal.
2645    */
2646   void ReattachGlobal(Handle<Object> global_object);
2647 
2648   /** Creates a new context. */
2649   static Persistent<Context> New(
2650       ExtensionConfiguration* extensions = NULL,
2651       Handle<ObjectTemplate> global_template = Handle<ObjectTemplate>(),
2652       Handle<Value> global_object = Handle<Value>());
2653 
2654   /** Returns the last entered context. */
2655   static Local<Context> GetEntered();
2656 
2657   /** Returns the context that is on the top of the stack. */
2658   static Local<Context> GetCurrent();
2659 
2660   /**
2661    * Returns the context of the calling JavaScript code.  That is the
2662    * context of the top-most JavaScript frame.  If there are no
2663    * JavaScript frames an empty handle is returned.
2664    */
2665   static Local<Context> GetCalling();
2666 
2667   /**
2668    * Sets the security token for the context.  To access an object in
2669    * another context, the security tokens must match.
2670    */
2671   void SetSecurityToken(Handle<Value> token);
2672 
2673   /** Restores the security token to the default value. */
2674   void UseDefaultSecurityToken();
2675 
2676   /** Returns the security token of this context.*/
2677   Handle<Value> GetSecurityToken();
2678 
2679   /**
2680    * Enter this context.  After entering a context, all code compiled
2681    * and run is compiled and run in this context.  If another context
2682    * is already entered, this old context is saved so it can be
2683    * restored when the new context is exited.
2684    */
2685   void Enter();
2686 
2687   /**
2688    * Exit this context.  Exiting the current context restores the
2689    * context that was in place when entering the current context.
2690    */
2691   void Exit();
2692 
2693   /** Returns true if the context has experienced an out of memory situation. */
2694   bool HasOutOfMemoryException();
2695 
2696   /** Returns true if V8 has a current context. */
2697   static bool InContext();
2698 
2699   /**
2700    * Associate an additional data object with the context. This is mainly used
2701    * with the debugger to provide additional information on the context through
2702    * the debugger API.
2703    */
2704   void SetData(Handle<String> data);
2705   Local<Value> GetData();
2706 
2707   /**
2708    * Stack-allocated class which sets the execution context for all
2709    * operations executed within a local scope.
2710    */
2711   class V8EXPORT Scope {
2712    public:
Scope(Handle<Context> context)2713     inline Scope(Handle<Context> context) : context_(context) {
2714       context_->Enter();
2715     }
~Scope()2716     inline ~Scope() { context_->Exit(); }
2717    private:
2718     Handle<Context> context_;
2719   };
2720 
2721  private:
2722   friend class Value;
2723   friend class Script;
2724   friend class Object;
2725   friend class Function;
2726 };
2727 
2728 
2729 /**
2730  * Multiple threads in V8 are allowed, but only one thread at a time
2731  * is allowed to use V8.  The definition of 'using V8' includes
2732  * accessing handles or holding onto object pointers obtained from V8
2733  * handles.  It is up to the user of V8 to ensure (perhaps with
2734  * locking) that this constraint is not violated.
2735  *
2736  * If you wish to start using V8 in a thread you can do this by constructing
2737  * a v8::Locker object.  After the code using V8 has completed for the
2738  * current thread you can call the destructor.  This can be combined
2739  * with C++ scope-based construction as follows:
2740  *
2741  * \code
2742  * ...
2743  * {
2744  *   v8::Locker locker;
2745  *   ...
2746  *   // Code using V8 goes here.
2747  *   ...
2748  * } // Destructor called here
2749  * \endcode
2750  *
2751  * If you wish to stop using V8 in a thread A you can do this by either
2752  * by destroying the v8::Locker object as above or by constructing a
2753  * v8::Unlocker object:
2754  *
2755  * \code
2756  * {
2757  *   v8::Unlocker unlocker;
2758  *   ...
2759  *   // Code not using V8 goes here while V8 can run in another thread.
2760  *   ...
2761  * } // Destructor called here.
2762  * \endcode
2763  *
2764  * The Unlocker object is intended for use in a long-running callback
2765  * from V8, where you want to release the V8 lock for other threads to
2766  * use.
2767  *
2768  * The v8::Locker is a recursive lock.  That is, you can lock more than
2769  * once in a given thread.  This can be useful if you have code that can
2770  * be called either from code that holds the lock or from code that does
2771  * not.  The Unlocker is not recursive so you can not have several
2772  * Unlockers on the stack at once, and you can not use an Unlocker in a
2773  * thread that is not inside a Locker's scope.
2774  *
2775  * An unlocker will unlock several lockers if it has to and reinstate
2776  * the correct depth of locking on its destruction. eg.:
2777  *
2778  * \code
2779  * // V8 not locked.
2780  * {
2781  *   v8::Locker locker;
2782  *   // V8 locked.
2783  *   {
2784  *     v8::Locker another_locker;
2785  *     // V8 still locked (2 levels).
2786  *     {
2787  *       v8::Unlocker unlocker;
2788  *       // V8 not locked.
2789  *     }
2790  *     // V8 locked again (2 levels).
2791  *   }
2792  *   // V8 still locked (1 level).
2793  * }
2794  * // V8 Now no longer locked.
2795  * \endcode
2796  */
2797 class V8EXPORT Unlocker {
2798  public:
2799   Unlocker();
2800   ~Unlocker();
2801 };
2802 
2803 
2804 class V8EXPORT Locker {
2805  public:
2806   Locker();
2807   ~Locker();
2808 
2809   /**
2810    * Start preemption.
2811    *
2812    * When preemption is started, a timer is fired every n milli seconds
2813    * that will switch between multiple threads that are in contention
2814    * for the V8 lock.
2815    */
2816   static void StartPreemption(int every_n_ms);
2817 
2818   /**
2819    * Stop preemption.
2820    */
2821   static void StopPreemption();
2822 
2823   /**
2824    * Returns whether or not the locker is locked by the current thread.
2825    */
2826   static bool IsLocked();
2827 
2828   /**
2829    * Returns whether v8::Locker is being used by this V8 instance.
2830    */
IsActive()2831   static bool IsActive() { return active_; }
2832 
2833  private:
2834   bool has_lock_;
2835   bool top_level_;
2836 
2837   static bool active_;
2838 
2839   // Disallow copying and assigning.
2840   Locker(const Locker&);
2841   void operator=(const Locker&);
2842 };
2843 
2844 
2845 
2846 // --- I m p l e m e n t a t i o n ---
2847 
2848 
2849 namespace internal {
2850 
2851 
2852 // Tag information for HeapObject.
2853 const int kHeapObjectTag = 1;
2854 const int kHeapObjectTagSize = 2;
2855 const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
2856 
2857 // Tag information for Smi.
2858 const int kSmiTag = 0;
2859 const int kSmiTagSize = 1;
2860 const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
2861 
2862 template <size_t ptr_size> struct SmiConstants;
2863 
2864 // Smi constants for 32-bit systems.
2865 template <> struct SmiConstants<4> {
2866   static const int kSmiShiftSize = 0;
2867   static const int kSmiValueSize = 31;
2868   static inline int SmiToInt(internal::Object* value) {
2869     int shift_bits = kSmiTagSize + kSmiShiftSize;
2870     // Throw away top 32 bits and shift down (requires >> to be sign extending).
2871     return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
2872   }
2873 };
2874 
2875 // Smi constants for 64-bit systems.
2876 template <> struct SmiConstants<8> {
2877   static const int kSmiShiftSize = 31;
2878   static const int kSmiValueSize = 32;
2879   static inline int SmiToInt(internal::Object* value) {
2880     int shift_bits = kSmiTagSize + kSmiShiftSize;
2881     // Shift down and throw away top 32 bits.
2882     return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
2883   }
2884 };
2885 
2886 const int kSmiShiftSize = SmiConstants<sizeof(void*)>::kSmiShiftSize;
2887 const int kSmiValueSize = SmiConstants<sizeof(void*)>::kSmiValueSize;
2888 
2889 template <size_t ptr_size> struct InternalConstants;
2890 
2891 // Internal constants for 32-bit systems.
2892 template <> struct InternalConstants<4> {
2893   static const int kStringResourceOffset = 3 * sizeof(void*);
2894 };
2895 
2896 // Internal constants for 64-bit systems.
2897 template <> struct InternalConstants<8> {
2898   static const int kStringResourceOffset = 2 * sizeof(void*);
2899 };
2900 
2901 /**
2902  * This class exports constants and functionality from within v8 that
2903  * is necessary to implement inline functions in the v8 api.  Don't
2904  * depend on functions and constants defined here.
2905  */
2906 class Internals {
2907  public:
2908 
2909   // These values match non-compiler-dependent values defined within
2910   // the implementation of v8.
2911   static const int kHeapObjectMapOffset = 0;
2912   static const int kMapInstanceTypeOffset = sizeof(void*) + sizeof(int);
2913   static const int kStringResourceOffset =
2914       InternalConstants<sizeof(void*)>::kStringResourceOffset;
2915 
2916   static const int kProxyProxyOffset = sizeof(void*);
2917   static const int kJSObjectHeaderSize = 3 * sizeof(void*);
2918   static const int kFullStringRepresentationMask = 0x07;
2919   static const int kExternalTwoByteRepresentationTag = 0x03;
2920 
2921   // These constants are compiler dependent so their values must be
2922   // defined within the implementation.
2923   V8EXPORT static int kJSObjectType;
2924   V8EXPORT static int kFirstNonstringType;
2925   V8EXPORT static int kProxyType;
2926 
2927   static inline bool HasHeapObjectTag(internal::Object* value) {
2928     return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
2929             kHeapObjectTag);
2930   }
2931 
2932   static inline bool HasSmiTag(internal::Object* value) {
2933     return ((reinterpret_cast<intptr_t>(value) & kSmiTagMask) == kSmiTag);
2934   }
2935 
2936   static inline int SmiValue(internal::Object* value) {
2937     return SmiConstants<sizeof(void*)>::SmiToInt(value);
2938   }
2939 
2940   static inline int GetInstanceType(internal::Object* obj) {
2941     typedef internal::Object O;
2942     O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
2943     return ReadField<uint8_t>(map, kMapInstanceTypeOffset);
2944   }
2945 
2946   static inline void* GetExternalPointer(internal::Object* obj) {
2947     if (HasSmiTag(obj)) {
2948       return obj;
2949     } else if (GetInstanceType(obj) == kProxyType) {
2950       return ReadField<void*>(obj, kProxyProxyOffset);
2951     } else {
2952       return NULL;
2953     }
2954   }
2955 
2956   static inline bool IsExternalTwoByteString(int instance_type) {
2957     int representation = (instance_type & kFullStringRepresentationMask);
2958     return representation == kExternalTwoByteRepresentationTag;
2959   }
2960 
2961   template <typename T>
2962   static inline T ReadField(Object* ptr, int offset) {
2963     uint8_t* addr = reinterpret_cast<uint8_t*>(ptr) + offset - kHeapObjectTag;
2964     return *reinterpret_cast<T*>(addr);
2965   }
2966 
2967 };
2968 
2969 }
2970 
2971 
2972 template <class T>
2973 Handle<T>::Handle() : val_(0) { }
2974 
2975 
2976 template <class T>
2977 Local<T>::Local() : Handle<T>() { }
2978 
2979 
2980 template <class T>
2981 Local<T> Local<T>::New(Handle<T> that) {
2982   if (that.IsEmpty()) return Local<T>();
2983   internal::Object** p = reinterpret_cast<internal::Object**>(*that);
2984   return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(*p)));
2985 }
2986 
2987 
2988 template <class T>
2989 Persistent<T> Persistent<T>::New(Handle<T> that) {
2990   if (that.IsEmpty()) return Persistent<T>();
2991   internal::Object** p = reinterpret_cast<internal::Object**>(*that);
2992   return Persistent<T>(reinterpret_cast<T*>(V8::GlobalizeReference(p)));
2993 }
2994 
2995 
2996 template <class T>
2997 bool Persistent<T>::IsNearDeath() const {
2998   if (this->IsEmpty()) return false;
2999   return V8::IsGlobalNearDeath(reinterpret_cast<internal::Object**>(**this));
3000 }
3001 
3002 
3003 template <class T>
3004 bool Persistent<T>::IsWeak() const {
3005   if (this->IsEmpty()) return false;
3006   return V8::IsGlobalWeak(reinterpret_cast<internal::Object**>(**this));
3007 }
3008 
3009 
3010 template <class T>
3011 void Persistent<T>::Dispose() {
3012   if (this->IsEmpty()) return;
3013   V8::DisposeGlobal(reinterpret_cast<internal::Object**>(**this));
3014 }
3015 
3016 
3017 template <class T>
3018 Persistent<T>::Persistent() : Handle<T>() { }
3019 
3020 template <class T>
3021 void Persistent<T>::MakeWeak(void* parameters, WeakReferenceCallback callback) {
3022   V8::MakeWeak(reinterpret_cast<internal::Object**>(**this),
3023                parameters,
3024                callback);
3025 }
3026 
3027 template <class T>
3028 void Persistent<T>::ClearWeak() {
3029   V8::ClearWeak(reinterpret_cast<internal::Object**>(**this));
3030 }
3031 
3032 Local<Value> Arguments::operator[](int i) const {
3033   if (i < 0 || length_ <= i) return Local<Value>(*Undefined());
3034   return Local<Value>(reinterpret_cast<Value*>(values_ - i));
3035 }
3036 
3037 
3038 Local<Function> Arguments::Callee() const {
3039   return callee_;
3040 }
3041 
3042 
3043 Local<Object> Arguments::This() const {
3044   return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
3045 }
3046 
3047 
3048 Local<Object> Arguments::Holder() const {
3049   return holder_;
3050 }
3051 
3052 
3053 Local<Value> Arguments::Data() const {
3054   return data_;
3055 }
3056 
3057 
3058 bool Arguments::IsConstructCall() const {
3059   return is_construct_call_;
3060 }
3061 
3062 
3063 int Arguments::Length() const {
3064   return length_;
3065 }
3066 
3067 
3068 template <class T>
3069 Local<T> HandleScope::Close(Handle<T> value) {
3070   internal::Object** before = reinterpret_cast<internal::Object**>(*value);
3071   internal::Object** after = RawClose(before);
3072   return Local<T>(reinterpret_cast<T*>(after));
3073 }
3074 
3075 Handle<Value> ScriptOrigin::ResourceName() const {
3076   return resource_name_;
3077 }
3078 
3079 
3080 Handle<Integer> ScriptOrigin::ResourceLineOffset() const {
3081   return resource_line_offset_;
3082 }
3083 
3084 
3085 Handle<Integer> ScriptOrigin::ResourceColumnOffset() const {
3086   return resource_column_offset_;
3087 }
3088 
3089 
3090 Handle<Boolean> Boolean::New(bool value) {
3091   return value ? True() : False();
3092 }
3093 
3094 
3095 void Template::Set(const char* name, v8::Handle<Data> value) {
3096   Set(v8::String::New(name), value);
3097 }
3098 
3099 
3100 Local<Value> Object::GetInternalField(int index) {
3101 #ifndef V8_ENABLE_CHECKS
3102   Local<Value> quick_result = UncheckedGetInternalField(index);
3103   if (!quick_result.IsEmpty()) return quick_result;
3104 #endif
3105   return CheckedGetInternalField(index);
3106 }
3107 
3108 
3109 Local<Value> Object::UncheckedGetInternalField(int index) {
3110   typedef internal::Object O;
3111   typedef internal::Internals I;
3112   O* obj = *reinterpret_cast<O**>(this);
3113   if (I::GetInstanceType(obj) == I::kJSObjectType) {
3114     // If the object is a plain JSObject, which is the common case,
3115     // we know where to find the internal fields and can return the
3116     // value directly.
3117     int offset = I::kJSObjectHeaderSize + (sizeof(void*) * index);
3118     O* value = I::ReadField<O*>(obj, offset);
3119     O** result = HandleScope::CreateHandle(value);
3120     return Local<Value>(reinterpret_cast<Value*>(result));
3121   } else {
3122     return Local<Value>();
3123   }
3124 }
3125 
3126 
3127 void* External::Unwrap(Handle<v8::Value> obj) {
3128 #ifdef V8_ENABLE_CHECKS
3129   return FullUnwrap(obj);
3130 #else
3131   return QuickUnwrap(obj);
3132 #endif
3133 }
3134 
3135 
3136 void* External::QuickUnwrap(Handle<v8::Value> wrapper) {
3137   typedef internal::Object O;
3138   O* obj = *reinterpret_cast<O**>(const_cast<v8::Value*>(*wrapper));
3139   return internal::Internals::GetExternalPointer(obj);
3140 }
3141 
3142 
3143 void* Object::GetPointerFromInternalField(int index) {
3144   typedef internal::Object O;
3145   typedef internal::Internals I;
3146 
3147   O* obj = *reinterpret_cast<O**>(this);
3148 
3149   if (I::GetInstanceType(obj) == I::kJSObjectType) {
3150     // If the object is a plain JSObject, which is the common case,
3151     // we know where to find the internal fields and can return the
3152     // value directly.
3153     int offset = I::kJSObjectHeaderSize + (sizeof(void*) * index);
3154     O* value = I::ReadField<O*>(obj, offset);
3155     return I::GetExternalPointer(value);
3156   }
3157 
3158   return SlowGetPointerFromInternalField(index);
3159 }
3160 
3161 
3162 String* String::Cast(v8::Value* value) {
3163 #ifdef V8_ENABLE_CHECKS
3164   CheckCast(value);
3165 #endif
3166   return static_cast<String*>(value);
3167 }
3168 
3169 
3170 String::ExternalStringResource* String::GetExternalStringResource() const {
3171   typedef internal::Object O;
3172   typedef internal::Internals I;
3173   O* obj = *reinterpret_cast<O**>(const_cast<String*>(this));
3174   String::ExternalStringResource* result;
3175   if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
3176     void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
3177     result = reinterpret_cast<String::ExternalStringResource*>(value);
3178   } else {
3179     result = NULL;
3180   }
3181 #ifdef V8_ENABLE_CHECKS
3182   VerifyExternalStringResource(result);
3183 #endif
3184   return result;
3185 }
3186 
3187 
3188 bool Value::IsString() const {
3189 #ifdef V8_ENABLE_CHECKS
3190   return FullIsString();
3191 #else
3192   return QuickIsString();
3193 #endif
3194 }
3195 
3196 bool Value::QuickIsString() const {
3197   typedef internal::Object O;
3198   typedef internal::Internals I;
3199   O* obj = *reinterpret_cast<O**>(const_cast<Value*>(this));
3200   if (!I::HasHeapObjectTag(obj)) return false;
3201   return (I::GetInstanceType(obj) < I::kFirstNonstringType);
3202 }
3203 
3204 
3205 Number* Number::Cast(v8::Value* value) {
3206 #ifdef V8_ENABLE_CHECKS
3207   CheckCast(value);
3208 #endif
3209   return static_cast<Number*>(value);
3210 }
3211 
3212 
3213 Integer* Integer::Cast(v8::Value* value) {
3214 #ifdef V8_ENABLE_CHECKS
3215   CheckCast(value);
3216 #endif
3217   return static_cast<Integer*>(value);
3218 }
3219 
3220 
3221 Date* Date::Cast(v8::Value* value) {
3222 #ifdef V8_ENABLE_CHECKS
3223   CheckCast(value);
3224 #endif
3225   return static_cast<Date*>(value);
3226 }
3227 
3228 
3229 Object* Object::Cast(v8::Value* value) {
3230 #ifdef V8_ENABLE_CHECKS
3231   CheckCast(value);
3232 #endif
3233   return static_cast<Object*>(value);
3234 }
3235 
3236 
3237 Array* Array::Cast(v8::Value* value) {
3238 #ifdef V8_ENABLE_CHECKS
3239   CheckCast(value);
3240 #endif
3241   return static_cast<Array*>(value);
3242 }
3243 
3244 
3245 Function* Function::Cast(v8::Value* value) {
3246 #ifdef V8_ENABLE_CHECKS
3247   CheckCast(value);
3248 #endif
3249   return static_cast<Function*>(value);
3250 }
3251 
3252 
3253 External* External::Cast(v8::Value* value) {
3254 #ifdef V8_ENABLE_CHECKS
3255   CheckCast(value);
3256 #endif
3257   return static_cast<External*>(value);
3258 }
3259 
3260 
3261 Local<Value> AccessorInfo::Data() const {
3262   return Local<Value>(reinterpret_cast<Value*>(&args_[-3]));
3263 }
3264 
3265 
3266 Local<Object> AccessorInfo::This() const {
3267   return Local<Object>(reinterpret_cast<Object*>(&args_[0]));
3268 }
3269 
3270 
3271 Local<Object> AccessorInfo::Holder() const {
3272   return Local<Object>(reinterpret_cast<Object*>(&args_[-1]));
3273 }
3274 
3275 
3276 /**
3277  * \example shell.cc
3278  * A simple shell that takes a list of expressions on the
3279  * command-line and executes them.
3280  */
3281 
3282 
3283 /**
3284  * \example process.cc
3285  */
3286 
3287 
3288 }  // namespace v8
3289 
3290 
3291 #undef V8EXPORT
3292 #undef V8EXPORT_INLINE
3293 #undef TYPE_CHECK
3294 
3295 
3296 #endif  // V8_H_
3297