v8  3.11.10 (node 0.8.28)
V8 is Google's open source JavaScript engine
v8.h
Go to the documentation of this file.
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // 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 "v8stdint.h"
42 
43 #ifdef _WIN32
44 
45 // Setup for Windows DLL export/import. When building the V8 DLL the
46 // BUILDING_V8_SHARED needs to be defined. When building a program which uses
47 // the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8
48 // static library or building a program which uses the V8 static library neither
49 // BUILDING_V8_SHARED nor USING_V8_SHARED should be defined.
50 #if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED)
51 #error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the
52  build configuration to ensure that at most one of these is set
53 #endif
54 
55 #ifdef BUILDING_V8_SHARED
56 #define V8EXPORT __declspec(dllexport)
57 #elif USING_V8_SHARED
58 #define V8EXPORT __declspec(dllimport)
59 #else
60 #define V8EXPORT
61 #endif // BUILDING_V8_SHARED
62 
63 #else // _WIN32
64 
65 // Setup for Linux shared library export.
66 #if defined(__GNUC__) && (__GNUC__ >= 4) && defined(V8_SHARED)
67 #ifdef BUILDING_V8_SHARED
68 #define V8EXPORT __attribute__ ((visibility("default")))
69 #else
70 #define V8EXPORT
71 #endif
72 #else // defined(__GNUC__) && (__GNUC__ >= 4)
73 #define V8EXPORT
74 #endif // defined(__GNUC__) && (__GNUC__ >= 4)
75 
76 #endif // _WIN32
77 
78 /**
79  * The v8 JavaScript engine.
80  */
81 namespace v8 {
82 
83 class Context;
84 class String;
85 class StringObject;
86 class Value;
87 class Utils;
88 class Number;
89 class NumberObject;
90 class Object;
91 class Array;
92 class Int32;
93 class Uint32;
94 class External;
95 class Primitive;
96 class Boolean;
97 class BooleanObject;
98 class Integer;
99 class Function;
100 class Date;
101 class ImplementationUtilities;
102 class Signature;
103 class AccessorSignature;
104 template <class T> class Handle;
105 template <class T> class Local;
106 template <class T> class Persistent;
107 class FunctionTemplate;
108 class ObjectTemplate;
109 class Data;
110 class AccessorInfo;
111 class StackTrace;
112 class StackFrame;
113 class Isolate;
114 
115 namespace internal {
116 
117 class Arguments;
118 class Object;
119 class Heap;
120 class HeapObject;
121 class Isolate;
122 }
123 
124 
125 // --- Weak Handles ---
126 
127 
128 /**
129  * A weak reference callback function.
130  *
131  * This callback should either explicitly invoke Dispose on |object| if
132  * V8 wrapper is not needed anymore, or 'revive' it by invocation of MakeWeak.
133  *
134  * \param object the weak global object to be reclaimed by the garbage collector
135  * \param parameter the value passed in when making the weak global object
136  */
137 typedef void (*WeakReferenceCallback)(Persistent<Value> object,
138  void* parameter);
139 
140 
141 // --- Handles ---
142 
143 #define TYPE_CHECK(T, S)
144  while (false) {
145  *(static_cast<T* volatile*>(0)) = static_cast<S*>(0);
146  }
147 
148 /**
149  * An object reference managed by the v8 garbage collector.
150  *
151  * All objects returned from v8 have to be tracked by the garbage
152  * collector so that it knows that the objects are still alive. Also,
153  * because the garbage collector may move objects, it is unsafe to
154  * point directly to an object. Instead, all objects are stored in
155  * handles which are known by the garbage collector and updated
156  * whenever an object moves. Handles should always be passed by value
157  * (except in cases like out-parameters) and they should never be
158  * allocated on the heap.
159  *
160  * There are two types of handles: local and persistent handles.
161  * Local handles are light-weight and transient and typically used in
162  * local operations. They are managed by HandleScopes. Persistent
163  * handles can be used when storing objects across several independent
164  * operations and have to be explicitly deallocated when they're no
165  * longer used.
166  *
167  * It is safe to extract the object stored in the handle by
168  * dereferencing the handle (for instance, to extract the Object* from
169  * a Handle<Object>); the value will still be governed by a handle
170  * behind the scenes and the same rules apply to these values as to
171  * their handles.
172  */
173 template <class T> class Handle {
174  public:
175  /**
176  * Creates an empty handle.
177  */
178  inline Handle() : val_(0) {}
179 
180  /**
181  * Creates a new handle for the specified value.
182  */
183  inline explicit Handle(T* val) : val_(val) {}
184 
185  /**
186  * Creates a handle for the contents of the specified handle. This
187  * constructor allows you to pass handles as arguments by value and
188  * to assign between handles. However, if you try to assign between
189  * incompatible handles, for instance from a Handle<String> to a
190  * Handle<Number> it will cause a compile-time error. Assigning
191  * between compatible handles, for instance assigning a
192  * Handle<String> to a variable declared as Handle<Value>, is legal
193  * because String is a subclass of Value.
194  */
195  template <class S> inline Handle(Handle<S> that)
196  : val_(reinterpret_cast<T*>(*that)) {
197  /**
198  * This check fails when trying to convert between incompatible
199  * handles. For example, converting from a Handle<String> to a
200  * Handle<Number>.
201  */
202  TYPE_CHECK(T, S);
203  }
204 
205  /**
206  * Returns true if the handle is empty.
207  */
208  inline bool IsEmpty() const { return val_ == 0; }
209 
210  /**
211  * Sets the handle to be empty. IsEmpty() will then return true.
212  */
213  inline void Clear() { val_ = 0; }
214 
215  inline T* operator->() const { return val_; }
216 
217  inline T* operator*() const { return val_; }
218 
219  /**
220  * Checks whether two handles are the same.
221  * Returns true if both are empty, or if the objects
222  * to which they refer are identical.
223  * The handles' references are not checked.
224  */
225  template <class S> inline bool operator==(Handle<S> that) const {
226  internal::Object** a = reinterpret_cast<internal::Object**>(**this);
227  internal::Object** b = reinterpret_cast<internal::Object**>(*that);
228  if (a == 0) return b == 0;
229  if (b == 0) return false;
230  return *a == *b;
231  }
232 
233  /**
234  * Checks whether two handles are different.
235  * Returns true if only one of the handles is empty, or if
236  * the objects to which they refer are different.
237  * The handles' references are not checked.
238  */
239  template <class S> inline bool operator!=(Handle<S> that) const {
240  return !operator==(that);
241  }
242 
243  template <class S> static inline Handle<T> Cast(Handle<S> that) {
244 #ifdef V8_ENABLE_CHECKS
245  // If we're going to perform the type check then we have to check
246  // that the handle isn't empty before doing the checked cast.
247  if (that.IsEmpty()) return Handle<T>();
248 #endif
249  return Handle<T>(T::Cast(*that));
250  }
251 
252  template <class S> inline Handle<S> As() {
253  return Handle<S>::Cast(*this);
254  }
255 
256  private:
257  T* val_;
258 };
259 
260 
261 /**
262  * A light-weight stack-allocated object handle. All operations
263  * that return objects from within v8 return them in local handles. They
264  * are created within HandleScopes, and all local handles allocated within a
265  * handle scope are destroyed when the handle scope is destroyed. Hence it
266  * is not necessary to explicitly deallocate local handles.
267  */
268 template <class T> class Local : public Handle<T> {
269  public:
270  inline Local();
271  template <class S> inline Local(Local<S> that)
272  : Handle<T>(reinterpret_cast<T*>(*that)) {
273  /**
274  * This check fails when trying to convert between incompatible
275  * handles. For example, converting from a Handle<String> to a
276  * Handle<Number>.
277  */
278  TYPE_CHECK(T, S);
279  }
280  template <class S> inline Local(S* that) : Handle<T>(that) { }
281  template <class S> static inline Local<T> Cast(Local<S> that) {
282 #ifdef V8_ENABLE_CHECKS
283  // If we're going to perform the type check then we have to check
284  // that the handle isn't empty before doing the checked cast.
285  if (that.IsEmpty()) return Local<T>();
286 #endif
287  return Local<T>(T::Cast(*that));
288  }
289 
290  template <class S> inline Local<S> As() {
291  return Local<S>::Cast(*this);
292  }
293 
294  /** Create a local handle for the content of another handle.
295  * The referee is kept alive by the local handle even when
296  * the original handle is destroyed/disposed.
297  */
298  inline static Local<T> New(Handle<T> that);
299 };
300 
301 
302 /**
303  * An object reference that is independent of any handle scope. Where
304  * a Local handle only lives as long as the HandleScope in which it was
305  * allocated, a Persistent handle remains valid until it is explicitly
306  * disposed.
307  *
308  * A persistent handle contains a reference to a storage cell within
309  * the v8 engine which holds an object value and which is updated by
310  * the garbage collector whenever the object is moved. A new storage
311  * cell can be created using Persistent::New and existing handles can
312  * be disposed using Persistent::Dispose. Since persistent handles
313  * are passed by value you may have many persistent handle objects
314  * that point to the same storage cell. For instance, if you pass a
315  * persistent handle as an argument to a function you will not get two
316  * different storage cells but rather two references to the same
317  * storage cell.
318  */
319 template <class T> class Persistent : public Handle<T> {
320  public:
321  /**
322  * Creates an empty persistent handle that doesn't point to any
323  * storage cell.
324  */
325  inline Persistent();
326 
327  /**
328  * Creates a persistent handle for the same storage cell as the
329  * specified handle. This constructor allows you to pass persistent
330  * handles as arguments by value and to assign between persistent
331  * handles. However, attempting to assign between incompatible
332  * persistent handles, for instance from a Persistent<String> to a
333  * Persistent<Number> will cause a compile-time error. Assigning
334  * between compatible persistent handles, for instance assigning a
335  * Persistent<String> to a variable declared as Persistent<Value>,
336  * is allowed as String is a subclass of Value.
337  */
338  template <class S> inline Persistent(Persistent<S> that)
339  : Handle<T>(reinterpret_cast<T*>(*that)) {
340  /**
341  * This check fails when trying to convert between incompatible
342  * handles. For example, converting from a Handle<String> to a
343  * Handle<Number>.
344  */
345  TYPE_CHECK(T, S);
346  }
347 
348  template <class S> inline Persistent(S* that) : Handle<T>(that) { }
349 
350  /**
351  * "Casts" a plain handle which is known to be a persistent handle
352  * to a persistent handle.
353  */
354  template <class S> explicit inline Persistent(Handle<S> that)
355  : Handle<T>(*that) { }
356 
357  template <class S> static inline Persistent<T> Cast(Persistent<S> that) {
358 #ifdef V8_ENABLE_CHECKS
359  // If we're going to perform the type check then we have to check
360  // that the handle isn't empty before doing the checked cast.
361  if (that.IsEmpty()) return Persistent<T>();
362 #endif
363  return Persistent<T>(T::Cast(*that));
364  }
365 
366  template <class S> inline Persistent<S> As() {
367  return Persistent<S>::Cast(*this);
368  }
369 
370  /**
371  * Creates a new persistent handle for an existing local or
372  * persistent handle.
373  */
374  inline static Persistent<T> New(Handle<T> that);
375 
376  /**
377  * Releases the storage cell referenced by this persistent handle.
378  * Does not remove the reference to the cell from any handles.
379  * This handle's reference, and any other references to the storage
380  * cell remain and IsEmpty will still return false.
381  */
382  inline void Dispose();
383 
384  /**
385  * Make the reference to this object weak. When only weak handles
386  * refer to the object, the garbage collector will perform a
387  * callback to the given V8::WeakReferenceCallback function, passing
388  * it the object reference and the given parameters.
389  */
390  inline void MakeWeak(void* parameters, WeakReferenceCallback callback);
391 
392  /** Clears the weak reference to this object.*/
393  inline void ClearWeak();
394 
395  /**
396  * Marks the reference to this object independent. Garbage collector
397  * is free to ignore any object groups containing this object.
398  * Weak callback for an independent handle should not
399  * assume that it will be preceded by a global GC prologue callback
400  * or followed by a global GC epilogue callback.
401  */
402  inline void MarkIndependent();
403 
404  /**
405  *Checks if the handle holds the only reference to an object.
406  */
407  inline bool IsNearDeath() const;
408 
409  /**
410  * Returns true if the handle's reference is weak.
411  */
412  inline bool IsWeak() const;
413 
414  /**
415  * Assigns a wrapper class ID to the handle. See RetainedObjectInfo
416  * interface description in v8-profiler.h for details.
417  */
418  inline void SetWrapperClassId(uint16_t class_id);
419 
420  private:
421  friend class ImplementationUtilities;
422  friend class ObjectTemplate;
423 };
424 
425 
426  /**
427  * A stack-allocated class that governs a number of local handles.
428  * After a handle scope has been created, all local handles will be
429  * allocated within that handle scope until either the handle scope is
430  * deleted or another handle scope is created. If there is already a
431  * handle scope and a new one is created, all allocations will take
432  * place in the new handle scope until it is deleted. After that,
433  * new handles will again be allocated in the original handle scope.
434  *
435  * After the handle scope of a local handle has been deleted the
436  * garbage collector will no longer track the object stored in the
437  * handle and may deallocate it. The behavior of accessing a handle
438  * for which the handle scope has been deleted is undefined.
439  */
441  public:
443 
445 
446  /**
447  * Closes the handle scope and returns the value as a handle in the
448  * previous scope, which is the new current scope after the call.
449  */
450  template <class T> Local<T> Close(Handle<T> value);
451 
452  /**
453  * Counts the number of allocated handles.
454  */
455  static int NumberOfHandles();
456 
457  /**
458  * Creates a new handle with the given value.
459  */
460  static internal::Object** CreateHandle(internal::Object* value);
461  // Faster version, uses HeapObject to obtain the current Isolate.
462  static internal::Object** CreateHandle(internal::HeapObject* value);
463 
464  private:
465  // Make it impossible to create heap-allocated or illegal handle
466  // scopes by disallowing certain operations.
467  HandleScope(const HandleScope&);
468  void operator=(const HandleScope&);
469  void* operator new(size_t size);
470  void operator delete(void*, size_t);
471 
472  // This Data class is accessible internally as HandleScopeData through a
473  // typedef in the ImplementationUtilities class.
474  class V8EXPORT Data {
475  public:
476  internal::Object** next;
477  internal::Object** limit;
478  int level;
479  inline void Initialize() {
480  next = limit = NULL;
481  level = 0;
482  }
483  };
484 
485  void Leave();
486 
487  internal::Isolate* isolate_;
488  internal::Object** prev_next_;
489  internal::Object** prev_limit_;
490 
491  // Allow for the active closing of HandleScopes which allows to pass a handle
492  // from the HandleScope being closed to the next top most HandleScope.
493  bool is_closed_;
494  internal::Object** RawClose(internal::Object** value);
495 
496  friend class ImplementationUtilities;
497 };
498 
499 
500 // --- Special objects ---
501 
502 
503 /**
504  * The superclass of values and API object templates.
505  */
506 class V8EXPORT Data {
507  private:
508  Data();
509 };
510 
511 
512 /**
513  * Pre-compilation data that can be associated with a script. This
514  * data can be calculated for a script in advance of actually
515  * compiling it, and can be stored between compilations. When script
516  * data is given to the compile method compilation will be faster.
517  */
518 class V8EXPORT ScriptData { // NOLINT
519  public:
520  virtual ~ScriptData() { }
521 
522  /**
523  * Pre-compiles the specified script (context-independent).
524  *
525  * \param input Pointer to UTF-8 script source code.
526  * \param length Length of UTF-8 script source code.
527  */
528  static ScriptData* PreCompile(const char* input, int length);
529 
530  /**
531  * Pre-compiles the specified script (context-independent).
532  *
533  * NOTE: Pre-compilation using this method cannot happen on another thread
534  * without using Lockers.
535  *
536  * \param source Script source code.
537  */
538  static ScriptData* PreCompile(Handle<String> source);
539 
540  /**
541  * Load previous pre-compilation data.
542  *
543  * \param data Pointer to data returned by a call to Data() of a previous
544  * ScriptData. Ownership is not transferred.
545  * \param length Length of data.
546  */
547  static ScriptData* New(const char* data, int length);
548 
549  /**
550  * Returns the length of Data().
551  */
552  virtual int Length() = 0;
553 
554  /**
555  * Returns a serialized representation of this ScriptData that can later be
556  * passed to New(). NOTE: Serialized data is platform-dependent.
557  */
558  virtual const char* Data() = 0;
559 
560  /**
561  * Returns true if the source code could not be parsed.
562  */
563  virtual bool HasError() = 0;
564 };
565 
566 
567 /**
568  * The origin, within a file, of a script.
569  */
571  public:
572  inline ScriptOrigin(
573  Handle<Value> resource_name,
574  Handle<Integer> resource_line_offset = Handle<Integer>(),
575  Handle<Integer> resource_column_offset = Handle<Integer>())
576  : resource_name_(resource_name),
577  resource_line_offset_(resource_line_offset),
578  resource_column_offset_(resource_column_offset) { }
579  inline Handle<Value> ResourceName() const;
580  inline Handle<Integer> ResourceLineOffset() const;
581  inline Handle<Integer> ResourceColumnOffset() const;
582  private:
583  Handle<Value> resource_name_;
584  Handle<Integer> resource_line_offset_;
585  Handle<Integer> resource_column_offset_;
586 };
587 
588 
589 /**
590  * A compiled JavaScript script.
591  */
593  public:
594  /**
595  * Compiles the specified script (context-independent).
596  *
597  * \param source Script source code.
598  * \param origin Script origin, owned by caller, no references are kept
599  * when New() returns
600  * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
601  * using pre_data speeds compilation if it's done multiple times.
602  * Owned by caller, no references are kept when New() returns.
603  * \param script_data Arbitrary data associated with script. Using
604  * this has same effect as calling SetData(), but allows data to be
605  * available to compile event handlers.
606  * \return Compiled script object (context independent; when run it
607  * will use the currently entered context).
608  */
609  static Local<Script> New(Handle<String> source,
610  ScriptOrigin* origin = NULL,
611  ScriptData* pre_data = NULL,
612  Handle<String> script_data = Handle<String>());
613 
614  /**
615  * Compiles the specified script using the specified file name
616  * object (typically a string) as the script's origin.
617  *
618  * \param source Script source code.
619  * \param file_name file name object (typically a string) to be used
620  * as the script's origin.
621  * \return Compiled script object (context independent; when run it
622  * will use the currently entered context).
623  */
624  static Local<Script> New(Handle<String> source,
625  Handle<Value> file_name);
626 
627  /**
628  * Compiles the specified script (bound to current context).
629  *
630  * \param source Script source code.
631  * \param origin Script origin, owned by caller, no references are kept
632  * when Compile() returns
633  * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
634  * using pre_data speeds compilation if it's done multiple times.
635  * Owned by caller, no references are kept when Compile() returns.
636  * \param script_data Arbitrary data associated with script. Using
637  * this has same effect as calling SetData(), but makes data available
638  * earlier (i.e. to compile event handlers).
639  * \return Compiled script object, bound to the context that was active
640  * when this function was called. When run it will always use this
641  * context.
642  */
643  static Local<Script> Compile(Handle<String> source,
644  ScriptOrigin* origin = NULL,
645  ScriptData* pre_data = NULL,
646  Handle<String> script_data = Handle<String>());
647 
648  /**
649  * Compiles the specified script using the specified file name
650  * object (typically a string) as the script's origin.
651  *
652  * \param source Script source code.
653  * \param file_name File name to use as script's origin
654  * \param script_data Arbitrary data associated with script. Using
655  * this has same effect as calling SetData(), but makes data available
656  * earlier (i.e. to compile event handlers).
657  * \return Compiled script object, bound to the context that was active
658  * when this function was called. When run it will always use this
659  * context.
660  */
661  static Local<Script> Compile(Handle<String> source,
662  Handle<Value> file_name,
663  Handle<String> script_data = Handle<String>());
664 
665  /**
666  * Runs the script returning the resulting value. If the script is
667  * context independent (created using ::New) it will be run in the
668  * currently entered context. If it is context specific (created
669  * using ::Compile) it will be run in the context in which it was
670  * compiled.
671  */
673 
674  /**
675  * Returns the script id value.
676  */
678 
679  /**
680  * Associate an additional data object with the script. This is mainly used
681  * with the debugger as this data object is only available through the
682  * debugger API.
683  */
684  void SetData(Handle<String> data);
685 };
686 
687 
688 /**
689  * An error message.
690  */
692  public:
693  Local<String> Get() const;
695 
696  /**
697  * Returns the resource name for the script from where the function causing
698  * the error originates.
699  */
701 
702  /**
703  * Returns the resource data for the script from where the function causing
704  * the error originates.
705  */
707 
708  /**
709  * Exception stack trace. By default stack traces are not captured for
710  * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
711  * to change this option.
712  */
714 
715  /**
716  * Returns the number, 1-based, of the line where the error occurred.
717  */
718  int GetLineNumber() const;
719 
720  /**
721  * Returns the index within the script of the first character where
722  * the error occurred.
723  */
724  int GetStartPosition() const;
725 
726  /**
727  * Returns the index within the script of the last character where
728  * the error occurred.
729  */
730  int GetEndPosition() const;
731 
732  /**
733  * Returns the index within the line of the first character where
734  * the error occurred.
735  */
736  int GetStartColumn() const;
737 
738  /**
739  * Returns the index within the line of the last character where
740  * the error occurred.
741  */
742  int GetEndColumn() const;
743 
744  // TODO(1245381): Print to a string instead of on a FILE.
745  static void PrintCurrentStackTrace(FILE* out);
746 
747  static const int kNoLineNumberInfo = 0;
748  static const int kNoColumnInfo = 0;
749 };
750 
751 
752 /**
753  * Representation of a JavaScript stack trace. The information collected is a
754  * snapshot of the execution stack and the information remains valid after
755  * execution continues.
756  */
758  public:
759  /**
760  * Flags that determine what information is placed captured for each
761  * StackFrame when grabbing the current stack trace.
762  */
766  kScriptName = 1 << 2,
767  kFunctionName = 1 << 3,
768  kIsEval = 1 << 4,
769  kIsConstructor = 1 << 5,
773  };
774 
775  /**
776  * Returns a StackFrame at a particular index.
777  */
778  Local<StackFrame> GetFrame(uint32_t index) const;
779 
780  /**
781  * Returns the number of StackFrames.
782  */
783  int GetFrameCount() const;
784 
785  /**
786  * Returns StackTrace as a v8::Array that contains StackFrame objects.
787  */
789 
790  /**
791  * Grab a snapshot of the current JavaScript execution stack.
792  *
793  * \param frame_limit The maximum number of stack frames we want to capture.
794  * \param options Enumerates the set of things we will capture for each
795  * StackFrame.
796  */
798  int frame_limit,
799  StackTraceOptions options = kOverview);
800 };
801 
802 
803 /**
804  * A single JavaScript stack frame.
805  */
807  public:
808  /**
809  * Returns the number, 1-based, of the line for the associate function call.
810  * This method will return Message::kNoLineNumberInfo if it is unable to
811  * retrieve the line number, or if kLineNumber was not passed as an option
812  * when capturing the StackTrace.
813  */
814  int GetLineNumber() const;
815 
816  /**
817  * Returns the 1-based column offset on the line for the associated function
818  * call.
819  * This method will return Message::kNoColumnInfo if it is unable to retrieve
820  * the column number, or if kColumnOffset was not passed as an option when
821  * capturing the StackTrace.
822  */
823  int GetColumn() const;
824 
825  /**
826  * Returns the name of the resource that contains the script for the
827  * function for this StackFrame.
828  */
830 
831  /**
832  * Returns the name of the resource that contains the script for the
833  * function for this StackFrame or sourceURL value if the script name
834  * is undefined and its source ends with //@ sourceURL=... string.
835  */
837 
838  /**
839  * Returns the name of the function associated with this stack frame.
840  */
842 
843  /**
844  * Returns whether or not the associated function is compiled via a call to
845  * eval().
846  */
847  bool IsEval() const;
848 
849  /**
850  * Returns whether or not the associated function is called as a
851  * constructor via "new".
852  */
853  bool IsConstructor() const;
854 };
855 
856 
857 // --- Value ---
858 
859 
860 /**
861  * The superclass of all JavaScript values and objects.
862  */
863 class Value : public Data {
864  public:
865  /**
866  * Returns true if this value is the undefined value. See ECMA-262
867  * 4.3.10.
868  */
869  inline bool IsUndefined() const;
870 
871  /**
872  * Returns true if this value is the null value. See ECMA-262
873  * 4.3.11.
874  */
875  inline bool IsNull() const;
876 
877  /**
878  * Returns true if this value is true.
879  */
880  V8EXPORT bool IsTrue() const;
881 
882  /**
883  * Returns true if this value is false.
884  */
885  V8EXPORT bool IsFalse() const;
886 
887  /**
888  * Returns true if this value is an instance of the String type.
889  * See ECMA-262 8.4.
890  */
891  inline bool IsString() const;
892 
893  /**
894  * Returns true if this value is a function.
895  */
896  V8EXPORT bool IsFunction() const;
897 
898  /**
899  * Returns true if this value is an array.
900  */
901  V8EXPORT bool IsArray() const;
902 
903  /**
904  * Returns true if this value is an object.
905  */
906  V8EXPORT bool IsObject() const;
907 
908  /**
909  * Returns true if this value is boolean.
910  */
911  V8EXPORT bool IsBoolean() const;
912 
913  /**
914  * Returns true if this value is a number.
915  */
916  V8EXPORT bool IsNumber() const;
917 
918  /**
919  * Returns true if this value is external.
920  */
921  V8EXPORT bool IsExternal() const;
922 
923  /**
924  * Returns true if this value is a 32-bit signed integer.
925  */
926  V8EXPORT bool IsInt32() const;
927 
928  /**
929  * Returns true if this value is a 32-bit unsigned integer.
930  */
931  V8EXPORT bool IsUint32() const;
932 
933  /**
934  * Returns true if this value is a Date.
935  */
936  V8EXPORT bool IsDate() const;
937 
938  /**
939  * Returns true if this value is a Boolean object.
940  */
941  V8EXPORT bool IsBooleanObject() const;
942 
943  /**
944  * Returns true if this value is a Number object.
945  */
946  V8EXPORT bool IsNumberObject() const;
947 
948  /**
949  * Returns true if this value is a String object.
950  */
951  V8EXPORT bool IsStringObject() const;
952 
953  /**
954  * Returns true if this value is a NativeError.
955  */
956  V8EXPORT bool IsNativeError() const;
957 
958  /**
959  * Returns true if this value is a RegExp.
960  */
961  V8EXPORT bool IsRegExp() const;
962 
971 
972  /**
973  * Attempts to convert a string to an array index.
974  * Returns an empty handle if the conversion fails.
975  */
977 
978  V8EXPORT bool BooleanValue() const;
979  V8EXPORT double NumberValue() const;
980  V8EXPORT int64_t IntegerValue() const;
981  V8EXPORT uint32_t Uint32Value() const;
982  V8EXPORT int32_t Int32Value() const;
983 
984  /** JS == */
985  V8EXPORT bool Equals(Handle<Value> that) const;
986  V8EXPORT bool StrictEquals(Handle<Value> that) const;
987 
988  private:
989  inline bool QuickIsUndefined() const;
990  inline bool QuickIsNull() const;
991  inline bool QuickIsString() const;
992  V8EXPORT bool FullIsUndefined() const;
993  V8EXPORT bool FullIsNull() const;
994  V8EXPORT bool FullIsString() const;
995 };
996 
997 
998 /**
999  * The superclass of primitive values. See ECMA-262 4.3.2.
1000  */
1001 class Primitive : public Value { };
1002 
1003 
1004 /**
1005  * A primitive boolean value (ECMA-262, 4.3.14). Either the true
1006  * or false value.
1007  */
1008 class Boolean : public Primitive {
1009  public:
1010  V8EXPORT bool Value() const;
1011  static inline Handle<Boolean> New(bool value);
1012 };
1013 
1014 
1015 /**
1016  * A JavaScript string value (ECMA-262, 4.3.17).
1017  */
1018 class String : public Primitive {
1019  public:
1020  /**
1021  * Returns the number of characters in this string.
1022  */
1023  V8EXPORT int Length() const;
1024 
1025  /**
1026  * Returns the number of bytes in the UTF-8 encoded
1027  * representation of this string.
1028  */
1029  V8EXPORT int Utf8Length() const;
1030 
1031  /**
1032  * A fast conservative check for non-ASCII characters. May
1033  * return true even for ASCII strings, but if it returns
1034  * false you can be sure that all characters are in the range
1035  * 0-127.
1036  */
1038 
1039  /**
1040  * Write the contents of the string to an external buffer.
1041  * If no arguments are given, expects the buffer to be large
1042  * enough to hold the entire string and NULL terminator. Copies
1043  * the contents of the string and the NULL terminator into the
1044  * buffer.
1045  *
1046  * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
1047  * before the end of the buffer.
1048  *
1049  * Copies up to length characters into the output buffer.
1050  * Only null-terminates if there is enough space in the buffer.
1051  *
1052  * \param buffer The buffer into which the string will be copied.
1053  * \param start The starting position within the string at which
1054  * copying begins.
1055  * \param length The number of characters to copy from the string. For
1056  * WriteUtf8 the number of bytes in the buffer.
1057  * \param nchars_ref The number of characters written, can be NULL.
1058  * \param options Various options that might affect performance of this or
1059  * subsequent operations.
1060  * \return The number of characters copied to the buffer excluding the null
1061  * terminator. For WriteUtf8: The number of bytes copied to the buffer
1062  * including the null terminator (if written).
1063  */
1068  };
1069 
1070  // 16-bit character codes.
1071  V8EXPORT int Write(uint16_t* buffer,
1072  int start = 0,
1073  int length = -1,
1074  int options = NO_OPTIONS) const;
1075  // ASCII characters.
1076  V8EXPORT int WriteAscii(char* buffer,
1077  int start = 0,
1078  int length = -1,
1079  int options = NO_OPTIONS) const;
1080  // UTF-8 encoded characters.
1081  V8EXPORT int WriteUtf8(char* buffer,
1082  int length = -1,
1083  int* nchars_ref = NULL,
1084  int options = NO_OPTIONS) const;
1085 
1086  /**
1087  * A zero length string.
1088  */
1090  inline static v8::Local<v8::String> Empty(Isolate* isolate);
1091 
1092  /**
1093  * Returns true if the string is external
1094  */
1095  V8EXPORT bool IsExternal() const;
1096 
1097  /**
1098  * Returns true if the string is both external and ASCII
1099  */
1101 
1103  public:
1105 
1106  protected:
1108 
1109  /**
1110  * Internally V8 will call this Dispose method when the external string
1111  * resource is no longer needed. The default implementation will use the
1112  * delete operator. This method can be overridden in subclasses to
1113  * control how allocated external string resources are disposed.
1114  */
1115  virtual void Dispose() { delete this; }
1116 
1117  private:
1118  // Disallow copying and assigning.
1119  ExternalStringResourceBase(const ExternalStringResourceBase&);
1120  void operator=(const ExternalStringResourceBase&);
1121 
1122  friend class v8::internal::Heap;
1123  };
1124 
1125  /**
1126  * An ExternalStringResource is a wrapper around a two-byte string
1127  * buffer that resides outside V8's heap. Implement an
1128  * ExternalStringResource to manage the life cycle of the underlying
1129  * buffer. Note that the string data must be immutable.
1130  */
1132  : public ExternalStringResourceBase {
1133  public:
1134  /**
1135  * Override the destructor to manage the life cycle of the underlying
1136  * buffer.
1137  */
1139 
1140  /**
1141  * The string data from the underlying buffer.
1142  */
1143  virtual const uint16_t* data() const = 0;
1144 
1145  /**
1146  * The length of the string. That is, the number of two-byte characters.
1147  */
1148  virtual size_t length() const = 0;
1149 
1150  protected:
1152  };
1153 
1154  /**
1155  * An ExternalAsciiStringResource is a wrapper around an ASCII
1156  * string buffer that resides outside V8's heap. Implement an
1157  * ExternalAsciiStringResource to manage the life cycle of the
1158  * underlying buffer. Note that the string data must be immutable
1159  * and that the data must be strict (7-bit) ASCII, not Latin-1 or
1160  * UTF-8, which would require special treatment internally in the
1161  * engine and, in the case of UTF-8, do not allow efficient indexing.
1162  * Use String::New or convert to 16 bit data for non-ASCII.
1163  */
1164 
1166  : public ExternalStringResourceBase {
1167  public:
1168  /**
1169  * Override the destructor to manage the life cycle of the underlying
1170  * buffer.
1171  */
1173  /** The string data from the underlying buffer.*/
1174  virtual const char* data() const = 0;
1175  /** The number of ASCII characters in the string.*/
1176  virtual size_t length() const = 0;
1177  protected:
1179  };
1180 
1181  /**
1182  * Get the ExternalStringResource for an external string. Returns
1183  * NULL if IsExternal() doesn't return true.
1184  */
1186 
1187  /**
1188  * Get the ExternalAsciiStringResource for an external ASCII string.
1189  * Returns NULL if IsExternalAscii() doesn't return true.
1190  */
1192  const;
1193 
1194  static inline String* Cast(v8::Value* obj);
1195 
1196  /**
1197  * Allocates a new string from either UTF-8 encoded or ASCII data.
1198  * The second parameter 'length' gives the buffer length.
1199  * If the data is UTF-8 encoded, the caller must
1200  * be careful to supply the length parameter.
1201  * If it is not given, the function calls
1202  * 'strlen' to determine the buffer length, it might be
1203  * wrong if 'data' contains a null character.
1204  */
1205  V8EXPORT static Local<String> New(const char* data, int length = -1);
1206 
1207  /** Allocates a new string from 16-bit character codes.*/
1208  V8EXPORT static Local<String> New(const uint16_t* data, int length = -1);
1209 
1210  /** Creates a symbol. Returns one if it exists already.*/
1211  V8EXPORT static Local<String> NewSymbol(const char* data, int length = -1);
1212 
1213  /**
1214  * Creates a new string by concatenating the left and the right strings
1215  * passed in as parameters.
1216  */
1218  Handle<String> right);
1219 
1220  /**
1221  * Creates a new external string using the data defined in the given
1222  * resource. When the external string is no longer live on V8's heap the
1223  * resource will be disposed by calling its Dispose method. The caller of
1224  * this function should not otherwise delete or modify the resource. Neither
1225  * should the underlying buffer be deallocated or modified except through the
1226  * destructor of the external string resource.
1227  */
1229 
1230  /**
1231  * Associate an external string resource with this string by transforming it
1232  * in place so that existing references to this string in the JavaScript heap
1233  * will use the external string resource. The external string resource's
1234  * character contents need to be equivalent to this string.
1235  * Returns true if the string has been changed to be an external string.
1236  * The string is not modified if the operation fails. See NewExternal for
1237  * information on the lifetime of the resource.
1238  */
1240 
1241  /**
1242  * Creates a new external string using the ASCII data defined in the given
1243  * resource. When the external string is no longer live on V8's heap the
1244  * resource will be disposed by calling its Dispose method. The caller of
1245  * this function should not otherwise delete or modify the resource. Neither
1246  * should the underlying buffer be deallocated or modified except through the
1247  * destructor of the external string resource.
1249  ExternalAsciiStringResource* resource);
1250 
1251  /**
1252  * Associate an external string resource with this string by transforming it
1253  * in place so that existing references to this string in the JavaScript heap
1254  * will use the external string resource. The external string resource's
1255  * character contents need to be equivalent to this string.
1256  * Returns true if the string has been changed to be an external string.
1257  * The string is not modified if the operation fails. See NewExternal for
1258  * information on the lifetime of the resource.
1259  */
1261 
1262  /**
1263  * Returns true if this string can be made external.
1264  */
1266 
1267  /** Creates an undetectable string from the supplied ASCII or UTF-8 data.*/
1268  V8EXPORT static Local<String> NewUndetectable(const char* data,
1269  int length = -1);
1270 
1271  /** Creates an undetectable string from the supplied 16-bit character codes.*/
1272  V8EXPORT static Local<String> NewUndetectable(const uint16_t* data,
1273  int length = -1);
1274 
1275  /**
1276  * Converts an object to a UTF-8-encoded character array. Useful if
1277  * you want to print the object. If conversion to a string fails
1278  * (e.g. due to an exception in the toString() method of the object)
1279  * then the length() method returns 0 and the * operator returns
1280  * NULL.
1281  */
1283  public:
1284  explicit Utf8Value(Handle<v8::Value> obj);
1286  char* operator*() { return str_; }
1287  const char* operator*() const { return str_; }
1288  int length() const { return length_; }
1289  private:
1290  char* str_;
1291  int length_;
1292 
1293  // Disallow copying and assigning.
1294  Utf8Value(const Utf8Value&);
1295  void operator=(const Utf8Value&);
1296  };
1297 
1298  /**
1299  * Converts an object to an ASCII string.
1300  * Useful if you want to print the object.
1301  * If conversion to a string fails (eg. due to an exception in the toString()
1302  * method of the object) then the length() method returns 0 and the * operator
1303  * returns NULL.
1304  */
1306  public:
1307  explicit AsciiValue(Handle<v8::Value> obj);
1309  char* operator*() { return str_; }
1310  const char* operator*() const { return str_; }
1311  int length() const { return length_; }
1312  private:
1313  char* str_;
1314  int length_;
1315 
1316  // Disallow copying and assigning.
1317  AsciiValue(const AsciiValue&);
1318  void operator=(const AsciiValue&);
1319  };
1320 
1321  /**
1322  * Converts an object to a two-byte string.
1323  * If conversion to a string fails (eg. due to an exception in the toString()
1324  * method of the object) then the length() method returns 0 and the * operator
1325  * returns NULL.
1326  */
1327  class V8EXPORT Value {
1328  public:
1329  explicit Value(Handle<v8::Value> obj);
1330  ~Value();
1331  uint16_t* operator*() { return str_; }
1332  const uint16_t* operator*() const { return str_; }
1333  int length() const { return length_; }
1334  private:
1335  uint16_t* str_;
1336  int length_;
1337 
1338  // Disallow copying and assigning.
1339  Value(const Value&);
1340  void operator=(const Value&);
1341  };
1342 
1343  private:
1344  V8EXPORT void VerifyExternalStringResource(ExternalStringResource* val) const;
1345  V8EXPORT static void CheckCast(v8::Value* obj);
1346 };
1347 
1348 
1349 /**
1350  * A JavaScript number value (ECMA-262, 4.3.20)
1351  */
1352 class Number : public Primitive {
1353  public:
1354  V8EXPORT double Value() const;
1355  V8EXPORT static Local<Number> New(double value);
1356  static inline Number* Cast(v8::Value* obj);
1357  private:
1358  V8EXPORT Number();
1359  V8EXPORT static void CheckCast(v8::Value* obj);
1360 };
1361 
1362 
1363 /**
1364  * A JavaScript value representing a signed integer.
1365  */
1366 class Integer : public Number {
1367  public:
1368  V8EXPORT static Local<Integer> New(int32_t value);
1369  V8EXPORT static Local<Integer> NewFromUnsigned(uint32_t value);
1370  V8EXPORT int64_t Value() const;
1371  static inline Integer* Cast(v8::Value* obj);
1372  private:
1373  V8EXPORT Integer();
1374  V8EXPORT static void CheckCast(v8::Value* obj);
1375 };
1376 
1377 
1378 /**
1379  * A JavaScript value representing a 32-bit signed integer.
1380  */
1381 class Int32 : public Integer {
1382  public:
1383  V8EXPORT int32_t Value() const;
1384  private:
1385  V8EXPORT Int32();
1386 };
1387 
1388 
1389 /**
1390  * A JavaScript value representing a 32-bit unsigned integer.
1391  */
1392 class Uint32 : public Integer {
1393  public:
1394  V8EXPORT uint32_t Value() const;
1395  private:
1396  V8EXPORT Uint32();
1397 };
1398 
1399 
1401  None = 0,
1402  ReadOnly = 1 << 0,
1403  DontEnum = 1 << 1,
1404  DontDelete = 1 << 2
1405 };
1406 
1417 };
1418 
1419 /**
1420  * Accessor[Getter|Setter] are used as callback functions when
1421  * setting|getting a particular property. See Object and ObjectTemplate's
1422  * method SetAccessor.
1423  */
1424 typedef Handle<Value> (*AccessorGetter)(Local<String> property,
1425  const AccessorInfo& info);
1426 
1427 
1428 typedef void (*AccessorSetter)(Local<String> property,
1429  Local<Value> value,
1430  const AccessorInfo& info);
1431 
1432 
1433 /**
1434  * Access control specifications.
1435  *
1436  * Some accessors should be accessible across contexts. These
1437  * accessors have an explicit access control parameter which specifies
1438  * the kind of cross-context access that should be allowed.
1439  *
1440  * Additionally, for security, accessors can prohibit overwriting by
1441  * accessors defined in JavaScript. For objects that have such
1442  * accessors either locally or in their prototype chain it is not
1443  * possible to overwrite the accessor by using __defineGetter__ or
1444  * __defineSetter__ from JavaScript code.
1445  */
1447  DEFAULT = 0,
1449  ALL_CAN_WRITE = 1 << 1,
1450  PROHIBITS_OVERWRITING = 1 << 2
1451 };
1452 
1453 
1454 /**
1455  * A JavaScript object (ECMA-262, 4.3.3)
1456  */
1457 class Object : public Value {
1458  public:
1460  Handle<Value> value,
1461  PropertyAttribute attribs = None);
1462 
1463  V8EXPORT bool Set(uint32_t index,
1464  Handle<Value> value);
1465 
1466  // Sets a local property on this object bypassing interceptors and
1467  // overriding accessors or read-only properties.
1468  //
1469  // Note that if the object has an interceptor the property will be set
1470  // locally, but since the interceptor takes precedence the local property
1471  // will only be returned if the interceptor doesn't return a value.
1472  //
1473  // Note also that this only works for named properties.
1475  Handle<Value> value,
1476  PropertyAttribute attribs = None);
1477 
1479 
1480  V8EXPORT Local<Value> Get(uint32_t index);
1481 
1482  /**
1483  * Gets the property attributes of a property which can be None or
1484  * any combination of ReadOnly, DontEnum and DontDelete. Returns
1485  * None when the property doesn't exist.
1486  */
1488 
1489  // TODO(1245389): Replace the type-specific versions of these
1490  // functions with generic ones that accept a Handle<Value> key.
1492 
1494 
1495  // Delete a property on this object bypassing interceptors and
1496  // ignoring dont-delete attributes.
1498 
1499  V8EXPORT bool Has(uint32_t index);
1500 
1501  V8EXPORT bool Delete(uint32_t index);
1502 
1504  AccessorGetter getter,
1505  AccessorSetter setter = 0,
1506  Handle<Value> data = Handle<Value>(),
1507  AccessControl settings = DEFAULT,
1508  PropertyAttribute attribute = None);
1509 
1510  /**
1511  * Returns an array containing the names of the enumerable properties
1512  * of this object, including properties from prototype objects. The
1513  * array returned by this method contains the same values as would
1514  * be enumerated by a for-in statement over this object.
1515  */
1517 
1518  /**
1519  * This function has the same functionality as GetPropertyNames but
1520  * the returned array doesn't contain the names of properties from
1521  * prototype objects.
1522  */
1524 
1525  /**
1526  * Get the prototype object. This does not skip objects marked to
1527  * be skipped by __proto__ and it does not consult the security
1528  * handler.
1529  */
1531 
1532  /**
1533  * Set the prototype object. This does not skip objects marked to
1534  * be skipped by __proto__ and it does not consult the security
1535  * handler.
1536  */
1537  V8EXPORT bool SetPrototype(Handle<Value> prototype);
1538 
1539  /**
1540  * Finds an instance of the given function template in the prototype
1541  * chain.
1542  */
1544  Handle<FunctionTemplate> tmpl);
1545 
1546  /**
1547  * Call builtin Object.prototype.toString on this object.
1548  * This is different from Value::ToString() that may call
1549  * user-defined toString function. This one does not.
1550  */
1552 
1553  /**
1554  * Returns the name of the function invoked as a constructor for this object.
1555  */
1557 
1558  /** Gets the number of internal fields for this Object. */
1560  /** Gets the value in an internal field. */
1561  inline Local<Value> GetInternalField(int index);
1562  /** Sets the value in an internal field. */
1563  V8EXPORT void SetInternalField(int index, Handle<Value> value);
1564 
1565  /** Gets a native pointer from an internal field. */
1566  inline void* GetPointerFromInternalField(int index);
1567 
1568  /** Sets a native pointer in an internal field. */
1569  V8EXPORT void SetPointerInInternalField(int index, void* value);
1570 
1571  // Testers for local properties.
1574  V8EXPORT bool HasRealIndexedProperty(uint32_t index);
1576 
1577  /**
1578  * If result.IsEmpty() no real property was located in the prototype chain.
1579  * This means interceptors in the prototype chain are not called.
1580  */
1582  Handle<String> key);
1583 
1584  /**
1585  * If result.IsEmpty() no real property was located on the object or
1586  * in the prototype chain.
1587  * This means interceptors in the prototype chain are not called.
1588  */
1590 
1591  /** Tests for a named lookup interceptor.*/
1593 
1594  /** Tests for an index lookup interceptor.*/
1596 
1597  /**
1598  * Turns on access check on the object if the object is an instance of
1599  * a template that has access check callbacks. If an object has no
1600  * access check info, the object cannot be accessed by anyone.
1601  */
1603 
1604  /**
1605  * Returns the identity hash for this object. The current implementation
1606  * uses a hidden property on the object to store the identity hash.
1607  *
1608  * The return value will never be 0. Also, it is not guaranteed to be
1609  * unique.
1610  */
1612 
1613  /**
1614  * Access hidden properties on JavaScript objects. These properties are
1615  * hidden from the executing JavaScript and only accessible through the V8
1616  * C++ API. Hidden properties introduced by V8 internally (for example the
1617  * identity hash) are prefixed with "v8::".
1618  */
1622 
1623  /**
1624  * Returns true if this is an instance of an api function (one
1625  * created from a function created from a function template) and has
1626  * been modified since it was created. Note that this method is
1627  * conservative and may return true for objects that haven't actually
1628  * been modified.
1629  */
1631 
1632  /**
1633  * Clone this object with a fast but shallow copy. Values will point
1634  * to the same values as the original object.
1635  */
1637 
1638  /**
1639  * Returns the context in which the object was created.
1640  */
1642 
1643  /**
1644  * Set the backing store of the indexed properties to be managed by the
1645  * embedding layer. Access to the indexed properties will follow the rules
1646  * spelled out in CanvasPixelArray.
1647  * Note: The embedding program still owns the data and needs to ensure that
1648  * the backing store is preserved while V8 has a reference.
1649  */
1650  V8EXPORT void SetIndexedPropertiesToPixelData(uint8_t* data, int length);
1654 
1655  /**
1656  * Set the backing store of the indexed properties to be managed by the
1657  * embedding layer. Access to the indexed properties will follow the rules
1658  * spelled out for the CanvasArray subtypes in the WebGL specification.
1659  * Note: The embedding program still owns the data and needs to ensure that
1660  * the backing store is preserved while V8 has a reference.
1661  */
1663  void* data,
1664  ExternalArrayType array_type,
1665  int number_of_elements);
1670 
1671  /**
1672  * Checks whether a callback is set by the
1673  * ObjectTemplate::SetCallAsFunctionHandler method.
1674  * When an Object is callable this method returns true.
1675  */
1677 
1678  /**
1679  * Call an Object as a function if a callback is set by the
1680  * ObjectTemplate::SetCallAsFunctionHandler method.
1681  */
1683  int argc,
1684  Handle<Value> argv[]);
1685 
1686  /**
1687  * Call an Object as a constructor if a callback is set by the
1688  * ObjectTemplate::SetCallAsFunctionHandler method.
1689  * Note: This method behaves like the Function::NewInstance method.
1690  */
1692  Handle<Value> argv[]);
1693 
1695  static inline Object* Cast(Value* obj);
1696 
1697  private:
1698  V8EXPORT Object();
1699  V8EXPORT static void CheckCast(Value* obj);
1700  V8EXPORT Local<Value> CheckedGetInternalField(int index);
1701  V8EXPORT void* SlowGetPointerFromInternalField(int index);
1702 
1703  /**
1704  * If quick access to the internal field is possible this method
1705  * returns the value. Otherwise an empty handle is returned.
1706  */
1707  inline Local<Value> UncheckedGetInternalField(int index);
1708 };
1709 
1710 
1711 /**
1712  * An instance of the built-in array constructor (ECMA-262, 15.4.2).
1713  */
1714 class Array : public Object {
1715  public:
1716  V8EXPORT uint32_t Length() const;
1717 
1718  /**
1719  * Clones an element at index |index|. Returns an empty
1720  * handle if cloning fails (for any reason).
1721  */
1723 
1724  /**
1725  * Creates a JavaScript array with the given length. If the length
1726  * is negative the returned array will have length 0.
1727  */
1728  V8EXPORT static Local<Array> New(int length = 0);
1729 
1730  static inline Array* Cast(Value* obj);
1731  private:
1732  V8EXPORT Array();
1733  V8EXPORT static void CheckCast(Value* obj);
1734 };
1735 
1736 
1737 /**
1738  * A JavaScript function object (ECMA-262, 15.3).
1739  */
1740 class Function : public Object {
1741  public:
1743  V8EXPORT Local<Object> NewInstance(int argc, Handle<Value> argv[]) const;
1745  int argc,
1746  Handle<Value> argv[]);
1749 
1750  /**
1751  * Name inferred from variable or property assignment of this function.
1752  * Used to facilitate debugging and profiling of JavaScript code written
1753  * in an OO style, where many functions are anonymous but are assigned
1754  * to object properties.
1755  */
1757 
1758  /**
1759  * Returns zero based line number of function body and
1760  * kLineOffsetNotFound if no information available.
1761  */
1763  /**
1764  * Returns zero based column number of function body and
1765  * kLineOffsetNotFound if no information available.
1766  */
1770  static inline Function* Cast(Value* obj);
1771  V8EXPORT static const int kLineOffsetNotFound;
1772 
1773  private:
1774  V8EXPORT Function();
1775  V8EXPORT static void CheckCast(Value* obj);
1776 };
1777 
1778 
1779 /**
1780  * An instance of the built-in Date constructor (ECMA-262, 15.9).
1781  */
1782 class Date : public Object {
1783  public:
1784  V8EXPORT static Local<Value> New(double time);
1785 
1786  /**
1787  * A specialization of Value::NumberValue that is more efficient
1788  * because we know the structure of this object.
1789  */
1790  V8EXPORT double NumberValue() const;
1791 
1792  static inline Date* Cast(v8::Value* obj);
1793 
1794  /**
1795  * Notification that the embedder has changed the time zone,
1796  * daylight savings time, or other date / time configuration
1797  * parameters. V8 keeps a cache of various values used for
1798  * date / time computation. This notification will reset
1799  * those cached values for the current context so that date /
1800  * time configuration changes would be reflected in the Date
1801  * object.
1802  *
1803  * This API should not be called more than needed as it will
1804  * negatively impact the performance of date operations.
1805  */
1807 
1808  private:
1809  V8EXPORT static void CheckCast(v8::Value* obj);
1810 };
1811 
1812 
1813 /**
1814  * A Number object (ECMA-262, 4.3.21).
1815  */
1816 class NumberObject : public Object {
1817  public:
1818  V8EXPORT static Local<Value> New(double value);
1819 
1820  /**
1821  * Returns the Number held by the object.
1822  */
1823  V8EXPORT double NumberValue() const;
1824 
1825  static inline NumberObject* Cast(v8::Value* obj);
1826 
1827  private:
1828  V8EXPORT static void CheckCast(v8::Value* obj);
1829 };
1830 
1831 
1832 /**
1833  * A Boolean object (ECMA-262, 4.3.15).
1834  */
1835 class BooleanObject : public Object {
1836  public:
1837  V8EXPORT static Local<Value> New(bool value);
1838 
1839  /**
1840  * Returns the Boolean held by the object.
1841  */
1842  V8EXPORT bool BooleanValue() const;
1843 
1844  static inline BooleanObject* Cast(v8::Value* obj);
1845 
1846  private:
1847  V8EXPORT static void CheckCast(v8::Value* obj);
1848 };
1849 
1850 
1851 /**
1852  * A String object (ECMA-262, 4.3.18).
1853  */
1854 class StringObject : public Object {
1855  public:
1857 
1858  /**
1859  * Returns the String held by the object.
1860  */
1862 
1863  static inline StringObject* Cast(v8::Value* obj);
1864 
1865  private:
1866  V8EXPORT static void CheckCast(v8::Value* obj);
1867 };
1868 
1869 
1870 /**
1871  * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
1872  */
1873 class RegExp : public Object {
1874  public:
1875  /**
1876  * Regular expression flag bits. They can be or'ed to enable a set
1877  * of flags.
1878  */
1879  enum Flags {
1880  kNone = 0,
1881  kGlobal = 1,
1883  kMultiline = 4
1884  };
1885 
1886  /**
1887  * Creates a regular expression from the given pattern string and
1888  * the flags bit field. May throw a JavaScript exception as
1889  * described in ECMA-262, 15.10.4.1.
1890  *
1891  * For example,
1892  * RegExp::New(v8::String::New("foo"),
1893  * static_cast<RegExp::Flags>(kGlobal | kMultiline))
1894  * is equivalent to evaluating "/foo/gm".
1895  */
1896  V8EXPORT static Local<RegExp> New(Handle<String> pattern,
1897  Flags flags);
1898 
1899  /**
1900  * Returns the value of the source property: a string representing
1901  * the regular expression.
1902  */
1904 
1905  /**
1906  * Returns the flags bit field.
1907  */
1909 
1910  static inline RegExp* Cast(v8::Value* obj);
1911 
1912  private:
1913  V8EXPORT static void CheckCast(v8::Value* obj);
1914 };
1915 
1916 
1917 /**
1918  * A JavaScript value that wraps a C++ void*. This type of value is
1919  * mainly used to associate C++ data structures with JavaScript
1920  * objects.
1921  *
1922  * The Wrap function V8 will return the most optimal Value object wrapping the
1923  * C++ void*. The type of the value is not guaranteed to be an External object
1924  * and no assumptions about its type should be made. To access the wrapped
1925  * value Unwrap should be used, all other operations on that object will lead
1926  * to unpredictable results.
1927  */
1928 class External : public Value {
1929  public:
1930  V8EXPORT static Local<Value> Wrap(void* data);
1931  static inline void* Unwrap(Handle<Value> obj);
1932 
1933  V8EXPORT static Local<External> New(void* value);
1934  static inline External* Cast(Value* obj);
1935  V8EXPORT void* Value() const;
1936  private:
1937  V8EXPORT External();
1938  V8EXPORT static void CheckCast(v8::Value* obj);
1939  static inline void* QuickUnwrap(Handle<v8::Value> obj);
1940  V8EXPORT static void* FullUnwrap(Handle<v8::Value> obj);
1941 };
1942 
1943 
1944 // --- Templates ---
1945 
1946 
1947 /**
1948  * The superclass of object and function templates.
1949  */
1950 class V8EXPORT Template : public Data {
1951  public:
1952  /** Adds a property to each instance created by this template.*/
1953  void Set(Handle<String> name, Handle<Data> value,
1954  PropertyAttribute attributes = None);
1955  inline void Set(const char* name, Handle<Data> value);
1956  private:
1957  Template();
1958 
1959  friend class ObjectTemplate;
1960  friend class FunctionTemplate;
1961 };
1962 
1963 
1964 /**
1965  * The argument information given to function call callbacks. This
1966  * class provides access to information about the context of the call,
1967  * including the receiver, the number and values of arguments, and
1968  * the holder of the function.
1969  */
1970 class Arguments {
1971  public:
1972  inline int Length() const;
1973  inline Local<Value> operator[](int i) const;
1974  inline Local<Function> Callee() const;
1975  inline Local<Object> This() const;
1976  inline Local<Object> Holder() const;
1977  inline bool IsConstructCall() const;
1978  inline Local<Value> Data() const;
1979  inline Isolate* GetIsolate() const;
1980 
1981  private:
1982  static const int kIsolateIndex = 0;
1983  static const int kDataIndex = -1;
1984  static const int kCalleeIndex = -2;
1985  static const int kHolderIndex = -3;
1986 
1987  friend class ImplementationUtilities;
1988  inline Arguments(internal::Object** implicit_args,
1989  internal::Object** values,
1990  int length,
1991  bool is_construct_call);
1992  internal::Object** implicit_args_;
1993  internal::Object** values_;
1994  int length_;
1995  bool is_construct_call_;
1996 };
1997 
1998 
1999 /**
2000  * The information passed to an accessor callback about the context
2001  * of the property access.
2002  */
2004  public:
2005  inline AccessorInfo(internal::Object** args)
2006  : args_(args) { }
2007  inline Isolate* GetIsolate() const;
2008  inline Local<Value> Data() const;
2009  inline Local<Object> This() const;
2010  inline Local<Object> Holder() const;
2011 
2012  private:
2013  internal::Object** args_;
2014 };
2015 
2016 
2017 typedef Handle<Value> (*InvocationCallback)(const Arguments& args);
2018 
2019 /**
2020  * NamedProperty[Getter|Setter] are used as interceptors on object.
2021  * See ObjectTemplate::SetNamedPropertyHandler.
2022  */
2024  const AccessorInfo& info);
2025 
2026 
2027 /**
2028  * Returns the value if the setter intercepts the request.
2029  * Otherwise, returns an empty handle.
2030  */
2032  Local<Value> value,
2033  const AccessorInfo& info);
2034 
2035 /**
2036  * Returns a non-empty handle if the interceptor intercepts the request.
2037  * The result is an integer encoding property attributes (like v8::None,
2038  * v8::DontEnum, etc.)
2039  */
2041  const AccessorInfo& info);
2042 
2043 
2044 /**
2045  * Returns a non-empty handle if the deleter intercepts the request.
2046  * The return value is true if the property could be deleted and false
2047  * otherwise.
2048  */
2050  const AccessorInfo& info);
2051 
2052 /**
2053  * Returns an array containing the names of the properties the named
2054  * property getter intercepts.
2055  */
2057 
2058 
2059 /**
2060  * Returns the value of the property if the getter intercepts the
2061  * request. Otherwise, returns an empty handle.
2062  */
2063 typedef Handle<Value> (*IndexedPropertyGetter)(uint32_t index,
2064  const AccessorInfo& info);
2065 
2066 
2067 /**
2068  * Returns the value if the setter intercepts the request.
2069  * Otherwise, returns an empty handle.
2070  */
2071 typedef Handle<Value> (*IndexedPropertySetter)(uint32_t index,
2072  Local<Value> value,
2073  const AccessorInfo& info);
2074 
2075 
2076 /**
2077  * Returns a non-empty handle if the interceptor intercepts the request.
2078  * The result is an integer encoding property attributes.
2079  */
2080 typedef Handle<Integer> (*IndexedPropertyQuery)(uint32_t index,
2081  const AccessorInfo& info);
2082 
2083 /**
2084  * Returns a non-empty handle if the deleter intercepts the request.
2085  * The return value is true if the property could be deleted and false
2086  * otherwise.
2087  */
2088 typedef Handle<Boolean> (*IndexedPropertyDeleter)(uint32_t index,
2089  const AccessorInfo& info);
2090 
2091 /**
2092  * Returns an array containing the indices of the properties the
2093  * indexed property getter intercepts.
2094  */
2096 
2097 
2098 /**
2099  * Access type specification.
2100  */
2106  ACCESS_KEYS
2107 };
2108 
2109 
2110 /**
2111  * Returns true if cross-context access should be allowed to the named
2112  * property with the given key on the host object.
2113  */
2114 typedef bool (*NamedSecurityCallback)(Local<Object> host,
2115  Local<Value> key,
2116  AccessType type,
2117  Local<Value> data);
2118 
2119 
2120 /**
2121  * Returns true if cross-context access should be allowed to the indexed
2122  * property with the given index on the host object.
2123  */
2124 typedef bool (*IndexedSecurityCallback)(Local<Object> host,
2125  uint32_t index,
2126  AccessType type,
2127  Local<Value> data);
2128 
2129 
2130 /**
2131  * A FunctionTemplate is used to create functions at runtime. There
2132  * can only be one function created from a FunctionTemplate in a
2133  * context. The lifetime of the created function is equal to the
2134  * lifetime of the context. So in case the embedder needs to create
2135  * temporary functions that can be collected using Scripts is
2136  * preferred.
2137  *
2138  * A FunctionTemplate can have properties, these properties are added to the
2139  * function object when it is created.
2140  *
2141  * A FunctionTemplate has a corresponding instance template which is
2142  * used to create object instances when the function is used as a
2143  * constructor. Properties added to the instance template are added to
2144  * each object instance.
2145  *
2146  * A FunctionTemplate can have a prototype template. The prototype template
2147  * is used to create the prototype object of the function.
2148  *
2149  * The following example shows how to use a FunctionTemplate:
2150  *
2151  * \code
2152  * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
2153  * t->Set("func_property", v8::Number::New(1));
2154  *
2155  * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
2156  * proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
2157  * proto_t->Set("proto_const", v8::Number::New(2));
2158  *
2159  * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
2160  * instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
2161  * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
2162  * instance_t->Set("instance_property", Number::New(3));
2163  *
2164  * v8::Local<v8::Function> function = t->GetFunction();
2165  * v8::Local<v8::Object> instance = function->NewInstance();
2166  * \endcode
2167  *
2168  * Let's use "function" as the JS variable name of the function object
2169  * and "instance" for the instance object created above. The function
2170  * and the instance will have the following properties:
2171  *
2172  * \code
2173  * func_property in function == true;
2174  * function.func_property == 1;
2175  *
2176  * function.prototype.proto_method() invokes 'InvokeCallback'
2177  * function.prototype.proto_const == 2;
2178  *
2179  * instance instanceof function == true;
2180  * instance.instance_accessor calls 'InstanceAccessorCallback'
2181  * instance.instance_property == 3;
2182  * \endcode
2183  *
2184  * A FunctionTemplate can inherit from another one by calling the
2185  * FunctionTemplate::Inherit method. The following graph illustrates
2186  * the semantics of inheritance:
2187  *
2188  * \code
2189  * FunctionTemplate Parent -> Parent() . prototype -> { }
2190  * ^ ^
2191  * | Inherit(Parent) | .__proto__
2192  * | |
2193  * FunctionTemplate Child -> Child() . prototype -> { }
2194  * \endcode
2195  *
2196  * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
2197  * object of the Child() function has __proto__ pointing to the
2198  * Parent() function's prototype object. An instance of the Child
2199  * function has all properties on Parent's instance templates.
2200  *
2201  * Let Parent be the FunctionTemplate initialized in the previous
2202  * section and create a Child FunctionTemplate by:
2203  *
2204  * \code
2205  * Local<FunctionTemplate> parent = t;
2206  * Local<FunctionTemplate> child = FunctionTemplate::New();
2207  * child->Inherit(parent);
2208  *
2209  * Local<Function> child_function = child->GetFunction();
2210  * Local<Object> child_instance = child_function->NewInstance();
2211  * \endcode
2212  *
2213  * The Child function and Child instance will have the following
2214  * properties:
2215  *
2216  * \code
2217  * child_func.prototype.__proto__ == function.prototype;
2218  * child_instance.instance_accessor calls 'InstanceAccessorCallback'
2219  * child_instance.instance_property == 3;
2220  * \endcode
2221  */
2223  public:
2224  /** Creates a function template.*/
2226  InvocationCallback callback = 0,
2227  Handle<Value> data = Handle<Value>(),
2228  Handle<Signature> signature = Handle<Signature>());
2229  /** Returns the unique function instance in the current execution context.*/
2231 
2232  /**
2233  * Set the call-handler callback for a FunctionTemplate. This
2234  * callback is called whenever the function created from this
2235  * FunctionTemplate is called.
2236  */
2238  Handle<Value> data = Handle<Value>());
2239 
2240  /** Get the InstanceTemplate. */
2242 
2243  /** Causes the function template to inherit from a parent function template.*/
2245 
2246  /**
2247  * A PrototypeTemplate is the template used to create the prototype object
2248  * of the function created by this template.
2249  */
2251 
2252 
2253  /**
2254  * Set the class name of the FunctionTemplate. This is used for
2255  * printing objects created with the function created from the
2256  * FunctionTemplate as its constructor.
2257  */
2259 
2260  /**
2261  * Determines whether the __proto__ accessor ignores instances of
2262  * the function template. If instances of the function template are
2263  * ignored, __proto__ skips all instances and instead returns the
2264  * next object in the prototype chain.
2265  *
2266  * Call with a value of true to make the __proto__ accessor ignore
2267  * instances of the function template. Call with a value of false
2268  * to make the __proto__ accessor not ignore instances of the
2269  * function template. By default, instances of a function template
2270  * are not ignored.
2271  */
2272  void SetHiddenPrototype(bool value);
2273 
2274  /**
2275  * Sets the ReadOnly flag in the attributes of the 'prototype' property
2276  * of functions created from this FunctionTemplate to true.
2277  */
2279 
2280  /**
2281  * Returns true if the given object is an instance of this function
2282  * template.
2283  */
2284  bool HasInstance(Handle<Value> object);
2285 
2286  private:
2287  FunctionTemplate();
2288  void AddInstancePropertyAccessor(Handle<String> name,
2289  AccessorGetter getter,
2290  AccessorSetter setter,
2291  Handle<Value> data,
2292  AccessControl settings,
2293  PropertyAttribute attributes,
2294  Handle<AccessorSignature> signature);
2295  void SetNamedInstancePropertyHandler(NamedPropertyGetter getter,
2296  NamedPropertySetter setter,
2297  NamedPropertyQuery query,
2298  NamedPropertyDeleter remover,
2299  NamedPropertyEnumerator enumerator,
2300  Handle<Value> data);
2301  void SetIndexedInstancePropertyHandler(IndexedPropertyGetter getter,
2302  IndexedPropertySetter setter,
2303  IndexedPropertyQuery query,
2304  IndexedPropertyDeleter remover,
2305  IndexedPropertyEnumerator enumerator,
2306  Handle<Value> data);
2307  void SetInstanceCallAsFunctionHandler(InvocationCallback callback,
2308  Handle<Value> data);
2309 
2310  friend class Context;
2311  friend class ObjectTemplate;
2312 };
2313 
2314 
2315 /**
2316  * An ObjectTemplate is used to create objects at runtime.
2317  *
2318  * Properties added to an ObjectTemplate are added to each object
2319  * created from the ObjectTemplate.
2320  */
2322  public:
2323  /** Creates an ObjectTemplate. */
2325 
2326  /** Creates a new instance of this template.*/
2328 
2329  /**
2330  * Sets an accessor on the object template.
2331  *
2332  * Whenever the property with the given name is accessed on objects
2333  * created from this ObjectTemplate the getter and setter callbacks
2334  * are called instead of getting and setting the property directly
2335  * on the JavaScript object.
2336  *
2337  * \param name The name of the property for which an accessor is added.
2338  * \param getter The callback to invoke when getting the property.
2339  * \param setter The callback to invoke when setting the property.
2340  * \param data A piece of data that will be passed to the getter and setter
2341  * callbacks whenever they are invoked.
2342  * \param settings Access control settings for the accessor. This is a bit
2343  * field consisting of one of more of
2344  * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
2345  * The default is to not allow cross-context access.
2346  * ALL_CAN_READ means that all cross-context reads are allowed.
2347  * ALL_CAN_WRITE means that all cross-context writes are allowed.
2348  * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
2349  * cross-context access.
2350  * \param attribute The attributes of the property for which an accessor
2351  * is added.
2352  * \param signature The signature describes valid receivers for the accessor
2353  * and is used to perform implicit instance checks against them. If the
2354  * receiver is incompatible (i.e. is not an instance of the constructor as
2355  * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
2356  * thrown and no callback is invoked.
2357  */
2359  AccessorGetter getter,
2360  AccessorSetter setter = 0,
2361  Handle<Value> data = Handle<Value>(),
2362  AccessControl settings = DEFAULT,
2363  PropertyAttribute attribute = None,
2364  Handle<AccessorSignature> signature =
2366 
2367  /**
2368  * Sets a named property handler on the object template.
2369  *
2370  * Whenever a named property is accessed on objects created from
2371  * this object template, the provided callback is invoked instead of
2372  * accessing the property directly on the JavaScript object.
2373  *
2374  * \param getter The callback to invoke when getting a property.
2375  * \param setter The callback to invoke when setting a property.
2376  * \param query The callback to invoke to check if a property is present,
2377  * and if present, get its attributes.
2378  * \param deleter The callback to invoke when deleting a property.
2379  * \param enumerator The callback to invoke to enumerate all the named
2380  * properties of an object.
2381  * \param data A piece of data that will be passed to the callbacks
2382  * whenever they are invoked.
2383  */
2385  NamedPropertySetter setter = 0,
2386  NamedPropertyQuery query = 0,
2387  NamedPropertyDeleter deleter = 0,
2388  NamedPropertyEnumerator enumerator = 0,
2389  Handle<Value> data = Handle<Value>());
2390 
2391  /**
2392  * Sets an indexed property handler on the object template.
2393  *
2394  * Whenever an indexed property is accessed on objects created from
2395  * this object template, the provided callback is invoked instead of
2396  * accessing the property directly on the JavaScript object.
2397  *
2398  * \param getter The callback to invoke when getting a property.
2399  * \param setter The callback to invoke when setting a property.
2400  * \param query The callback to invoke to check if an object has a property.
2401  * \param deleter The callback to invoke when deleting a property.
2402  * \param enumerator The callback to invoke to enumerate all the indexed
2403  * properties of an object.
2404  * \param data A piece of data that will be passed to the callbacks
2405  * whenever they are invoked.
2406  */
2408  IndexedPropertySetter setter = 0,
2409  IndexedPropertyQuery query = 0,
2410  IndexedPropertyDeleter deleter = 0,
2411  IndexedPropertyEnumerator enumerator = 0,
2412  Handle<Value> data = Handle<Value>());
2413 
2414  /**
2415  * Sets the callback to be used when calling instances created from
2416  * this template as a function. If no callback is set, instances
2417  * behave like normal JavaScript objects that cannot be called as a
2418  * function.
2419  */
2421  Handle<Value> data = Handle<Value>());
2422 
2423  /**
2424  * Mark object instances of the template as undetectable.
2425  *
2426  * In many ways, undetectable objects behave as though they are not
2427  * there. They behave like 'undefined' in conditionals and when
2428  * printed. However, properties can be accessed and called as on
2429  * normal objects.
2430  */
2432 
2433  /**
2434  * Sets access check callbacks on the object template.
2435  *
2436  * When accessing properties on instances of this object template,
2437  * the access check callback will be called to determine whether or
2438  * not to allow cross-context access to the properties.
2439  * The last parameter specifies whether access checks are turned
2440  * on by default on instances. If access checks are off by default,
2441  * they can be turned on on individual instances by calling
2442  * Object::TurnOnAccessCheck().
2443  */
2445  IndexedSecurityCallback indexed_handler,
2446  Handle<Value> data = Handle<Value>(),
2447  bool turned_on_by_default = true);
2448 
2449  /**
2450  * Gets the number of internal fields for objects generated from
2451  * this template.
2452  */
2454 
2455  /**
2456  * Sets the number of internal fields for objects generated from
2457  * this template.
2458  */
2459  void SetInternalFieldCount(int value);
2460 
2461  private:
2462  ObjectTemplate();
2463  static Local<ObjectTemplate> New(Handle<FunctionTemplate> constructor);
2464  friend class FunctionTemplate;
2465 };
2466 
2467 
2468 /**
2469  * A Signature specifies which receivers and arguments are valid
2470  * parameters to a function.
2471  */
2472 class V8EXPORT Signature : public Data {
2473  public:
2476  int argc = 0,
2477  Handle<FunctionTemplate> argv[] = 0);
2478  private:
2479  Signature();
2480 };
2481 
2482 
2483 /**
2484  * An AccessorSignature specifies which receivers are valid parameters
2485  * to an accessor callback.
2486  */
2488  public:
2491  private:
2492  AccessorSignature();
2493 };
2494 
2495 
2496 /**
2497  * A utility for determining the type of objects based on the template
2498  * they were constructed from.
2499  */
2500 class V8EXPORT TypeSwitch : public Data {
2501  public:
2503  static Local<TypeSwitch> New(int argc, Handle<FunctionTemplate> types[]);
2504  int match(Handle<Value> value);
2505  private:
2506  TypeSwitch();
2507 };
2508 
2509 
2510 // --- Extensions ---
2511 
2514  public:
2515  ExternalAsciiStringResourceImpl() : data_(0), length_(0) {}
2516  ExternalAsciiStringResourceImpl(const char* data, size_t length)
2517  : data_(data), length_(length) {}
2518  const char* data() const { return data_; }
2519  size_t length() const { return length_; }
2520 
2521  private:
2522  const char* data_;
2523  size_t length_;
2524 };
2525 
2526 /**
2527  * Ignore
2528  */
2529 class V8EXPORT Extension { // NOLINT
2530  public:
2531  // Note that the strings passed into this constructor must live as long
2532  // as the Extension itself.
2533  Extension(const char* name,
2534  const char* source = 0,
2535  int dep_count = 0,
2536  const char** deps = 0,
2537  int source_length = -1);
2538  virtual ~Extension() { }
2539  virtual v8::Handle<v8::FunctionTemplate>
2542  }
2543 
2544  const char* name() const { return name_; }
2545  size_t source_length() const { return source_length_; }
2547  return &source_; }
2548  int dependency_count() { return dep_count_; }
2549  const char** dependencies() { return deps_; }
2550  void set_auto_enable(bool value) { auto_enable_ = value; }
2551  bool auto_enable() { return auto_enable_; }
2552 
2553  private:
2554  const char* name_;
2555  size_t source_length_; // expected to initialize before source_
2557  int dep_count_;
2558  const char** deps_;
2559  bool auto_enable_;
2560 
2561  // Disallow copying and assigning.
2562  Extension(const Extension&);
2563  void operator=(const Extension&);
2564 };
2565 
2566 
2568 
2569 
2570 /**
2571  * Ignore
2572  */
2574  public:
2575  inline DeclareExtension(Extension* extension) {
2576  RegisterExtension(extension);
2577  }
2578 };
2579 
2580 
2581 // --- Statics ---
2582 
2583 
2588 
2589 inline Handle<Primitive> Undefined(Isolate* isolate);
2590 inline Handle<Primitive> Null(Isolate* isolate);
2591 inline Handle<Boolean> True(Isolate* isolate);
2592 inline Handle<Boolean> False(Isolate* isolate);
2593 
2594 
2595 /**
2596  * A set of constraints that specifies the limits of the runtime's memory use.
2597  * You must set the heap size before initializing the VM - the size cannot be
2598  * adjusted after the VM is initialized.
2599  *
2600  * If you are using threads then you should hold the V8::Locker lock while
2601  * setting the stack limit and you must set a non-default stack limit separately
2602  * for each thread.
2603  */
2605  public:
2607  int max_young_space_size() const { return max_young_space_size_; }
2608  void set_max_young_space_size(int value) { max_young_space_size_ = value; }
2609  int max_old_space_size() const { return max_old_space_size_; }
2610  void set_max_old_space_size(int value) { max_old_space_size_ = value; }
2611  int max_executable_size() { return max_executable_size_; }
2612  void set_max_executable_size(int value) { max_executable_size_ = value; }
2613  uint32_t* stack_limit() const { return stack_limit_; }
2614  // Sets an address beyond which the VM's stack may not grow.
2615  void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
2616  private:
2617  int max_young_space_size_;
2618  int max_old_space_size_;
2619  int max_executable_size_;
2620  uint32_t* stack_limit_;
2621 };
2622 
2623 
2625 
2626 
2627 // --- Exceptions ---
2628 
2629 
2630 typedef void (*FatalErrorCallback)(const char* location, const char* message);
2631 
2632 
2633 typedef void (*MessageCallback)(Handle<Message> message, Handle<Value> data);
2634 
2635 
2636 /**
2637  * Schedules an exception to be thrown when returning to JavaScript. When an
2638  * exception has been scheduled it is illegal to invoke any JavaScript
2639  * operation; the caller must return immediately and only after the exception
2640  * has been handled does it become legal to invoke JavaScript operations.
2641  */
2643 
2644 /**
2645  * Create new error objects by calling the corresponding error object
2646  * constructor with the message.
2647  */
2649  public:
2650  static Local<Value> RangeError(Handle<String> message);
2652  static Local<Value> SyntaxError(Handle<String> message);
2653  static Local<Value> TypeError(Handle<String> message);
2654  static Local<Value> Error(Handle<String> message);
2655 };
2656 
2657 
2658 // --- Counters Callbacks ---
2659 
2660 typedef int* (*CounterLookupCallback)(const char* name);
2661 
2662 typedef void* (*CreateHistogramCallback)(const char* name,
2663  int min,
2664  int max,
2665  size_t buckets);
2666 
2667 typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
2668 
2669 // --- Memory Allocation Callback ---
2677 
2681  };
2682 
2687  };
2688 
2690  AllocationAction action,
2691  int size);
2692 
2693 // --- Leave Script Callback ---
2694 typedef void (*CallCompletedCallback)();
2695 
2696 // --- Failed Access Check Callback ---
2697 typedef void (*FailedAccessCheckCallback)(Local<Object> target,
2698  AccessType type,
2699  Local<Value> data);
2700 
2701 // --- AllowCodeGenerationFromStrings callbacks ---
2702 
2703 /**
2704  * Callback to check if code generation from strings is allowed. See
2705  * Context::AllowCodeGenerationFromStrings.
2706  */
2708 
2709 // --- Garbage Collection Callbacks ---
2710 
2711 /**
2712  * Applications can register callback functions which will be called
2713  * before and after a garbage collection. Allocations are not
2714  * allowed in the callback functions, you therefore cannot manipulate
2715  * objects (set or delete properties for example) since it is possible
2716  * such operations will result in the allocation of objects.
2717  */
2718 enum GCType {
2722 };
2723 
2726  kGCCallbackFlagCompacted = 1 << 0
2727 };
2728 
2729 typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
2730 typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
2731 
2732 typedef void (*GCCallback)();
2733 
2734 
2735 /**
2736  * Collection of V8 heap information.
2737  *
2738  * Instances of this class can be passed to v8::V8::HeapStatistics to
2739  * get heap statistics from V8.
2740  */
2742  public:
2744  size_t total_heap_size() { return total_heap_size_; }
2745  size_t total_heap_size_executable() { return total_heap_size_executable_; }
2746  size_t used_heap_size() { return used_heap_size_; }
2747  size_t heap_size_limit() { return heap_size_limit_; }
2748 
2749  private:
2750  void set_total_heap_size(size_t size) { total_heap_size_ = size; }
2751  void set_total_heap_size_executable(size_t size) {
2752  total_heap_size_executable_ = size;
2753  }
2754  void set_used_heap_size(size_t size) { used_heap_size_ = size; }
2755  void set_heap_size_limit(size_t size) { heap_size_limit_ = size; }
2756 
2757  size_t total_heap_size_;
2758  size_t total_heap_size_executable_;
2759  size_t used_heap_size_;
2760  size_t heap_size_limit_;
2761 
2762  friend class V8;
2763 };
2764 
2765 
2766 class RetainedObjectInfo;
2767 
2768 /**
2769  * Isolate represents an isolated instance of the V8 engine. V8
2770  * isolates have completely separate states. Objects from one isolate
2771  * must not be used in other isolates. When V8 is initialized a
2772  * default isolate is implicitly created and entered. The embedder
2773  * can create additional isolates and use them in parallel in multiple
2774  * threads. An isolate can be entered by at most one thread at any
2775  * given time. The Locker/Unlocker API must be used to synchronize.
2776  */
2778  public:
2779  /**
2780  * Stack-allocated class which sets the isolate for all operations
2781  * executed within a local scope.
2782  */
2783  class V8EXPORT Scope {
2784  public:
2785  explicit Scope(Isolate* isolate) : isolate_(isolate) {
2786  isolate->Enter();
2787  }
2788 
2789  ~Scope() { isolate_->Exit(); }
2790 
2791  private:
2792  Isolate* const isolate_;
2793 
2794  // Prevent copying of Scope objects.
2795  Scope(const Scope&);
2796  Scope& operator=(const Scope&);
2797  };
2798 
2799  /**
2800  * Creates a new isolate. Does not change the currently entered
2801  * isolate.
2802  *
2803  * When an isolate is no longer used its resources should be freed
2804  * by calling Dispose(). Using the delete operator is not allowed.
2805  */
2806  static Isolate* New();
2807 
2808  /**
2809  * Returns the entered isolate for the current thread or NULL in
2810  * case there is no current isolate.
2811  */
2812  static Isolate* GetCurrent();
2813 
2814  /**
2815  * Methods below this point require holding a lock (using Locker) in
2816  * a multi-threaded environment.
2817  */
2818 
2819  /**
2820  * Sets this isolate as the entered one for the current thread.
2821  * Saves the previously entered one (if any), so that it can be
2822  * restored when exiting. Re-entering an isolate is allowed.
2823  */
2824  void Enter();
2825 
2826  /**
2827  * Exits this isolate by restoring the previously entered one in the
2828  * current thread. The isolate may still stay the same, if it was
2829  * entered more than once.
2830  *
2831  * Requires: this == Isolate::GetCurrent().
2832  */
2833  void Exit();
2834 
2835  /**
2836  * Disposes the isolate. The isolate must not be entered by any
2837  * thread to be disposable.
2838  */
2839  void Dispose();
2840 
2841  /**
2842  * Associate embedder-specific data with the isolate
2843  */
2844  inline void SetData(void* data);
2845 
2846  /**
2847  * Retrieve embedder-specific data from the isolate.
2848  * Returns NULL if SetData has never been called.
2849  */
2850  inline void* GetData();
2851 
2852  private:
2853  Isolate();
2854  Isolate(const Isolate&);
2855  ~Isolate();
2856  Isolate& operator=(const Isolate&);
2857  void* operator new(size_t size);
2858  void operator delete(void*, size_t);
2859 };
2860 
2861 
2863  public:
2866  kBZip2
2867  };
2868 
2869  const char* data;
2872 };
2873 
2874 
2875 /**
2876  * A helper class for driving V8 startup data decompression. It is based on
2877  * "CompressedStartupData" API functions from the V8 class. It isn't mandatory
2878  * for an embedder to use this class, instead, API functions can be used
2879  * directly.
2880  *
2881  * For an example of the class usage, see the "shell.cc" sample application.
2882  */
2884  public:
2887  int Decompress();
2888 
2889  protected:
2890  virtual int DecompressData(char* raw_data,
2891  int* raw_data_size,
2892  const char* compressed_data,
2893  int compressed_data_size) = 0;
2894 
2895  private:
2896  char** raw_data;
2897 };
2898 
2899 
2900 /**
2901  * EntropySource is used as a callback function when v8 needs a source
2902  * of entropy.
2903  */
2904 typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
2905 
2906 
2907 /**
2908  * ReturnAddressLocationResolver is used as a callback function when v8 is
2909  * resolving the location of a return address on the stack. Profilers that
2910  * change the return address on the stack can use this to resolve the stack
2911  * location to whereever the profiler stashed the original return address.
2912  * When invoked, return_addr_location will point to a location on stack where
2913  * a machine return address resides, this function should return either the
2914  * same pointer, or a pointer to the profiler's copy of the original return
2915  * address.
2916  */
2917 typedef uintptr_t (*ReturnAddressLocationResolver)(
2918  uintptr_t return_addr_location);
2919 
2920 
2921 /**
2922  * Interface for iterating though all external resources in the heap.
2923  */
2925  public:
2927  virtual void VisitExternalString(Handle<String> string) {}
2928 };
2929 
2930 
2931 /**
2932  * Container class for static utility functions.
2933  */
2934 class V8EXPORT V8 {
2935  public:
2936  /** Set the callback to invoke in case of fatal errors. */
2938 
2939  /**
2940  * Set the callback to invoke to check if code generation from
2941  * strings should be allowed.
2942  */
2945 
2946  /**
2947  * Ignore out-of-memory exceptions.
2948  *
2949  * V8 running out of memory is treated as a fatal error by default.
2950  * This means that the fatal error handler is called and that V8 is
2951  * terminated.
2952  *
2953  * IgnoreOutOfMemoryException can be used to not treat an
2954  * out-of-memory situation as a fatal error. This way, the contexts
2955  * that did not cause the out of memory problem might be able to
2956  * continue execution.
2957  */
2959 
2960  /**
2961  * Check if V8 is dead and therefore unusable. This is the case after
2962  * fatal errors such as out-of-memory situations.
2963  */
2964  static bool IsDead();
2965 
2966  /**
2967  * The following 4 functions are to be used when V8 is built with
2968  * the 'compress_startup_data' flag enabled. In this case, the
2969  * embedder must decompress startup data prior to initializing V8.
2970  *
2971  * This is how interaction with V8 should look like:
2972  * int compressed_data_count = v8::V8::GetCompressedStartupDataCount();
2973  * v8::StartupData* compressed_data =
2974  * new v8::StartupData[compressed_data_count];
2975  * v8::V8::GetCompressedStartupData(compressed_data);
2976  * ... decompress data (compressed_data can be updated in-place) ...
2977  * v8::V8::SetDecompressedStartupData(compressed_data);
2978  * ... now V8 can be initialized
2979  * ... make sure the decompressed data stays valid until V8 shutdown
2980  *
2981  * A helper class StartupDataDecompressor is provided. It implements
2982  * the protocol of the interaction described above, and can be used in
2983  * most cases instead of calling these API functions directly.
2984  */
2987  static void GetCompressedStartupData(StartupData* compressed_data);
2988  static void SetDecompressedStartupData(StartupData* decompressed_data);
2989 
2990  /**
2991  * Adds a message listener.
2992  *
2993  * The same message listener can be added more than once and in that
2994  * case it will be called more than once for each message.
2995  */
2997  Handle<Value> data = Handle<Value>());
2998 
2999  /**
3000  * Remove all message listeners from the specified callback function.
3001  */
3003 
3004  /**
3005  * Tells V8 to capture current stack trace when uncaught exception occurs
3006  * and report it to the message listeners. The option is off by default.
3007  */
3009  bool capture,
3010  int frame_limit = 10,
3012 
3013  /**
3014  * Sets V8 flags from a string.
3015  */
3016  static void SetFlagsFromString(const char* str, int length);
3017 
3018  /**
3019  * Sets V8 flags from the command line.
3020  */
3021  static void SetFlagsFromCommandLine(int* argc,
3022  char** argv,
3023  bool remove_flags);
3024 
3025  /** Get the version string. */
3026  static const char* GetVersion();
3027 
3028  /**
3029  * Enables the host application to provide a mechanism for recording
3030  * statistics counters.
3031  */
3033 
3034  /**
3035  * Enables the host application to provide a mechanism for recording
3036  * histograms. The CreateHistogram function returns a
3037  * histogram which will later be passed to the AddHistogramSample
3038  * function.
3039  */
3042 
3043  /**
3044  * Enables the computation of a sliding window of states. The sliding
3045  * window information is recorded in statistics counters.
3046  */
3048 
3049  /** Callback function for reporting failed access checks.*/
3051 
3052  /**
3053  * Enables the host application to receive a notification before a
3054  * garbage collection. Allocations are not allowed in the
3055  * callback function, you therefore cannot manipulate objects (set
3056  * or delete properties for example) since it is possible such
3057  * operations will result in the allocation of objects. It is possible
3058  * to specify the GCType filter for your callback. But it is not possible to
3059  * register the same callback function two times with different
3060  * GCType filters.
3061  */
3063  GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
3064 
3065  /**
3066  * This function removes callback which was installed by
3067  * AddGCPrologueCallback function.
3068  */
3070 
3071  /**
3072  * The function is deprecated. Please use AddGCPrologueCallback instead.
3073  * Enables the host application to receive a notification before a
3074  * garbage collection. Allocations are not allowed in the
3075  * callback function, you therefore cannot manipulate objects (set
3076  * or delete properties for example) since it is possible such
3077  * operations will result in the allocation of objects.
3078  */
3080 
3081  /**
3082  * Enables the host application to receive a notification after a
3083  * garbage collection. Allocations are not allowed in the
3084  * callback function, you therefore cannot manipulate objects (set
3085  * or delete properties for example) since it is possible such
3086  * operations will result in the allocation of objects. It is possible
3087  * to specify the GCType filter for your callback. But it is not possible to
3088  * register the same callback function two times with different
3089  * GCType filters.
3090  */
3092  GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
3093 
3094  /**
3095  * This function removes callback which was installed by
3096  * AddGCEpilogueCallback function.
3097  */
3099 
3100  /**
3101  * The function is deprecated. Please use AddGCEpilogueCallback instead.
3102  * Enables the host application to receive a notification after a
3103  * major garbage collection. Allocations are not allowed in the
3104  * callback function, you therefore cannot manipulate objects (set
3105  * or delete properties for example) since it is possible such
3106  * operations will result in the allocation of objects.
3107  */
3109 
3110  /**
3111  * Enables the host application to provide a mechanism to be notified
3112  * and perform custom logging when V8 Allocates Executable Memory.
3113  */
3115  ObjectSpace space,
3116  AllocationAction action);
3117 
3118  /**
3119  * Removes callback that was installed by AddMemoryAllocationCallback.
3120  */
3122 
3123  /**
3124  * Adds a callback to notify the host application when a script finished
3125  * running. If a script re-enters the runtime during executing, the
3126  * CallCompletedCallback is only invoked when the outer-most script
3127  * execution ends. Executing scripts inside the callback do not trigger
3128  * further callbacks.
3129  */
3131 
3132  /**
3133  * Removes callback that was installed by AddCallCompletedCallback.
3134  */
3136 
3137  /**
3138  * Allows the host application to group objects together. If one
3139  * object in the group is alive, all objects in the group are alive.
3140  * After each garbage collection, object groups are removed. It is
3141  * intended to be used in the before-garbage-collection callback
3142  * function, for instance to simulate DOM tree connections among JS
3143  * wrapper objects.
3144  * See v8-profiler.h for RetainedObjectInfo interface description.
3145  */
3146  static void AddObjectGroup(Persistent<Value>* objects,
3147  size_t length,
3148  RetainedObjectInfo* info = NULL);
3149 
3150  /**
3151  * Allows the host application to declare implicit references between
3152  * the objects: if |parent| is alive, all |children| are alive too.
3153  * After each garbage collection, all implicit references
3154  * are removed. It is intended to be used in the before-garbage-collection
3155  * callback function.
3156  */
3158  Persistent<Value>* children,
3159  size_t length);
3160 
3161  /**
3162  * Initializes from snapshot if possible. Otherwise, attempts to
3163  * initialize from scratch. This function is called implicitly if
3164  * you use the API without calling it first.
3165  */
3166  static bool Initialize();
3167 
3168  /**
3169  * Allows the host application to provide a callback which can be used
3170  * as a source of entropy for random number generators.
3171  */
3172  static void SetEntropySource(EntropySource source);
3173 
3174  /**
3175  * Allows the host application to provide a callback that allows v8 to
3176  * cooperate with a profiler that rewrites return addresses on stack.
3177  */
3179  ReturnAddressLocationResolver return_address_resolver);
3180 
3181  /**
3182  * Adjusts the amount of registered external memory. Used to give
3183  * V8 an indication of the amount of externally allocated memory
3184  * that is kept alive by JavaScript objects. V8 uses this to decide
3185  * when to perform global garbage collections. Registering
3186  * externally allocated memory will trigger global garbage
3187  * collections more often than otherwise in an attempt to garbage
3188  * collect the JavaScript objects keeping the externally allocated
3189  * memory alive.
3190  *
3191  * \param change_in_bytes the change in externally allocated memory
3192  * that is kept alive by JavaScript objects.
3193  * \returns the adjusted value.
3194  */
3196  intptr_t change_in_bytes);
3197 
3198  /**
3199  * Suspends recording of tick samples in the profiler.
3200  * When the V8 profiling mode is enabled (usually via command line
3201  * switches) this function suspends recording of tick samples.
3202  * Profiling ticks are discarded until ResumeProfiler() is called.
3203  *
3204  * See also the --prof and --prof_auto command line switches to
3205  * enable V8 profiling.
3206  */
3207  static void PauseProfiler();
3208 
3209  /**
3210  * Resumes recording of tick samples in the profiler.
3211  * See also PauseProfiler().
3212  */
3213  static void ResumeProfiler();
3214 
3215  /**
3216  * Return whether profiler is currently paused.
3217  */
3218  static bool IsProfilerPaused();
3219 
3220  /**
3221  * Retrieve the V8 thread id of the calling thread.
3222  *
3223  * The thread id for a thread should only be retrieved after the V8
3224  * lock has been acquired with a Locker object with that thread.
3225  */
3226  static int GetCurrentThreadId();
3227 
3228  /**
3229  * Forcefully terminate execution of a JavaScript thread. This can
3230  * be used to terminate long-running scripts.
3231  *
3232  * TerminateExecution should only be called when then V8 lock has
3233  * been acquired with a Locker object. Therefore, in order to be
3234  * able to terminate long-running threads, preemption must be
3235  * enabled to allow the user of TerminateExecution to acquire the
3236  * lock.
3237  *
3238  * The termination is achieved by throwing an exception that is
3239  * uncatchable by JavaScript exception handlers. Termination
3240  * exceptions act as if they were caught by a C++ TryCatch exception
3241  * handler. If forceful termination is used, any C++ TryCatch
3242  * exception handler that catches an exception should check if that
3243  * exception is a termination exception and immediately return if
3244  * that is the case. Returning immediately in that case will
3245  * continue the propagation of the termination exception if needed.
3246  *
3247  * The thread id passed to TerminateExecution must have been
3248  * obtained by calling GetCurrentThreadId on the thread in question.
3249  *
3250  * \param thread_id The thread id of the thread to terminate.
3251  */
3252  static void TerminateExecution(int thread_id);
3253 
3254  /**
3255  * Forcefully terminate the current thread of JavaScript execution
3256  * in the given isolate. If no isolate is provided, the default
3257  * isolate is used.
3258  *
3259  * This method can be used by any thread even if that thread has not
3260  * acquired the V8 lock with a Locker object.
3261  *
3262  * \param isolate The isolate in which to terminate the current JS execution.
3263  */
3264  static void TerminateExecution(Isolate* isolate = NULL);
3265 
3266  /**
3267  * Is V8 terminating JavaScript execution.
3268  *
3269  * Returns true if JavaScript execution is currently terminating
3270  * because of a call to TerminateExecution. In that case there are
3271  * still JavaScript frames on the stack and the termination
3272  * exception is still active.
3273  *
3274  * \param isolate The isolate in which to check.
3275  */
3276  static bool IsExecutionTerminating(Isolate* isolate = NULL);
3277 
3278  /**
3279  * Releases any resources used by v8 and stops any utility threads
3280  * that may be running. Note that disposing v8 is permanent, it
3281  * cannot be reinitialized.
3282  *
3283  * It should generally not be necessary to dispose v8 before exiting
3284  * a process, this should happen automatically. It is only necessary
3285  * to use if the process needs the resources taken up by v8.
3286  */
3287  static bool Dispose();
3288 
3289  /**
3290  * Get statistics about the heap memory usage.
3291  */
3292  static void GetHeapStatistics(HeapStatistics* heap_statistics);
3293 
3294  /**
3295  * Iterates through all external resources referenced from current isolate
3296  * heap. This method is not expected to be used except for debugging purposes
3297  * and may be quite slow.
3298  */
3300 
3301  /**
3302  * Optional notification that the embedder is idle.
3303  * V8 uses the notification to reduce memory footprint.
3304  * This call can be used repeatedly if the embedder remains idle.
3305  * Returns true if the embedder should stop calling IdleNotification
3306  * until real work has been done. This indicates that V8 has done
3307  * as much cleanup as it will be able to do.
3308  *
3309  * The hint argument specifies the amount of work to be done in the function
3310  * on scale from 1 to 1000. There is no guarantee that the actual work will
3311  * match the hint.
3312  */
3313  static bool IdleNotification(int hint = 1000);
3314 
3315  /**
3316  * Optional notification that the system is running low on memory.
3317  * V8 uses these notifications to attempt to free memory.
3318  */
3319  static void LowMemoryNotification();
3320 
3321  /**
3322  * Optional notification that a context has been disposed. V8 uses
3323  * these notifications to guide the GC heuristic. Returns the number
3324  * of context disposals - including this one - since the last time
3325  * V8 had a chance to clean up.
3326  */
3328 
3329  private:
3330  V8();
3331 
3332  static internal::Object** GlobalizeReference(internal::Object** handle);
3333  static void DisposeGlobal(internal::Object** global_handle);
3334  static void MakeWeak(internal::Object** global_handle,
3335  void* data,
3337  static void ClearWeak(internal::Object** global_handle);
3338  static void MarkIndependent(internal::Object** global_handle);
3339  static bool IsGlobalNearDeath(internal::Object** global_handle);
3340  static bool IsGlobalWeak(internal::Object** global_handle);
3341  static void SetWrapperClassId(internal::Object** global_handle,
3342  uint16_t class_id);
3343 
3344  template <class T> friend class Handle;
3345  template <class T> friend class Local;
3346  template <class T> friend class Persistent;
3347  friend class Context;
3348 };
3349 
3350 
3351 /**
3352  * An external exception handler.
3353  */
3355  public:
3356  /**
3357  * Creates a new try/catch block and registers it with v8.
3358  */
3360 
3361  /**
3362  * Unregisters and deletes this try/catch block.
3363  */
3365 
3366  /**
3367  * Returns true if an exception has been caught by this try/catch block.
3368  */
3369  bool HasCaught() const;
3370 
3371  /**
3372  * For certain types of exceptions, it makes no sense to continue
3373  * execution.
3374  *
3375  * Currently, the only type of exception that can be caught by a
3376  * TryCatch handler and for which it does not make sense to continue
3377  * is termination exception. Such exceptions are thrown when the
3378  * TerminateExecution methods are called to terminate a long-running
3379  * script.
3380  *
3381  * If CanContinue returns false, the correct action is to perform
3382  * any C++ cleanup needed and then return.
3383  */
3384  bool CanContinue() const;
3385 
3386  /**
3387  * Throws the exception caught by this TryCatch in a way that avoids
3388  * it being caught again by this same TryCatch. As with ThrowException
3389  * it is illegal to execute any JavaScript operations after calling
3390  * ReThrow; the caller must return immediately to where the exception
3391  * is caught.
3392  */
3394 
3395  /**
3396  * Returns the exception caught by this try/catch block. If no exception has
3397  * been caught an empty handle is returned.
3398  *
3399  * The returned handle is valid until this TryCatch block has been destroyed.
3400  */
3402 
3403  /**
3404  * Returns the .stack property of the thrown object. If no .stack
3405  * property is present an empty handle is returned.
3406  */
3408 
3409  /**
3410  * Returns the message associated with this exception. If there is
3411  * no message associated an empty handle is returned.
3412  *
3413  * The returned handle is valid until this TryCatch block has been
3414  * destroyed.
3415  */
3416  Local<v8::Message> Message() const;
3417 
3418  /**
3419  * Clears any exceptions that may have been caught by this try/catch block.
3420  * After this method has been called, HasCaught() will return false.
3421  *
3422  * It is not necessary to clear a try/catch block before using it again; if
3423  * another exception is thrown the previously caught exception will just be
3424  * overwritten. However, it is often a good idea since it makes it easier
3425  * to determine which operation threw a given exception.
3426  */
3427  void Reset();
3428 
3429  /**
3430  * Set verbosity of the external exception handler.
3431  *
3432  * By default, exceptions that are caught by an external exception
3433  * handler are not reported. Call SetVerbose with true on an
3434  * external exception handler to have exceptions caught by the
3435  * handler reported as if they were not caught.
3436  */
3437  void SetVerbose(bool value);
3438 
3439  /**
3440  * Set whether or not this TryCatch should capture a Message object
3441  * which holds source information about where the exception
3442  * occurred. True by default.
3443  */
3444  void SetCaptureMessage(bool value);
3445 
3446  private:
3447  v8::internal::Isolate* isolate_;
3448  void* next_;
3449  void* exception_;
3450  void* message_;
3451  bool is_verbose_ : 1;
3452  bool can_continue_ : 1;
3453  bool capture_message_ : 1;
3454  bool rethrow_ : 1;
3455 
3456  friend class v8::internal::Isolate;
3457 };
3458 
3459 
3460 // --- Context ---
3461 
3462 
3463 /**
3464  * Ignore
3465  */
3467  public:
3468  ExtensionConfiguration(int name_count, const char* names[])
3469  : name_count_(name_count), names_(names) { }
3470  private:
3471  friend class ImplementationUtilities;
3472  int name_count_;
3473  const char** names_;
3474 };
3475 
3476 
3477 /**
3478  * A sandboxed execution context with its own set of built-in objects
3479  * and functions.
3480  */
3482  public:
3483  /**
3484  * Returns the global proxy object or global object itself for
3485  * detached contexts.
3486  *
3487  * Global proxy object is a thin wrapper whose prototype points to
3488  * actual context's global object with the properties like Object, etc.
3489  * This is done that way for security reasons (for more details see
3490  * https://wiki.mozilla.org/Gecko:SplitWindow).
3491  *
3492  * Please note that changes to global proxy object prototype most probably
3493  * would break VM---v8 expects only global object as a prototype of
3494  * global proxy object.
3495  *
3496  * If DetachGlobal() has been invoked, Global() would return actual global
3497  * object until global is reattached with ReattachGlobal().
3498  */
3500 
3501  /**
3502  * Detaches the global object from its context before
3503  * the global object can be reused to create a new context.
3504  */
3506 
3507  /**
3508  * Reattaches a global object to a context. This can be used to
3509  * restore the connection between a global object and a context
3510  * after DetachGlobal has been called.
3511  *
3512  * \param global_object The global object to reattach to the
3513  * context. For this to work, the global object must be the global
3514  * object that was associated with this context before a call to
3515  * DetachGlobal.
3516  */
3517  void ReattachGlobal(Handle<Object> global_object);
3518 
3519  /** Creates a new context.
3520  *
3521  * Returns a persistent handle to the newly allocated context. This
3522  * persistent handle has to be disposed when the context is no
3523  * longer used so the context can be garbage collected.
3524  *
3525  * \param extensions An optional extension configuration containing
3526  * the extensions to be installed in the newly created context.
3527  *
3528  * \param global_template An optional object template from which the
3529  * global object for the newly created context will be created.
3530  *
3531  * \param global_object An optional global object to be reused for
3532  * the newly created context. This global object must have been
3533  * created by a previous call to Context::New with the same global
3534  * template. The state of the global object will be completely reset
3535  * and only object identify will remain.
3536  */
3538  ExtensionConfiguration* extensions = NULL,
3539  Handle<ObjectTemplate> global_template = Handle<ObjectTemplate>(),
3540  Handle<Value> global_object = Handle<Value>());
3541 
3542  /** Returns the last entered context. */
3544 
3545  /** Returns the context that is on the top of the stack. */
3547 
3548  /**
3549  * Returns the context of the calling JavaScript code. That is the
3550  * context of the top-most JavaScript frame. If there are no
3551  * JavaScript frames an empty handle is returned.
3552  */
3554 
3555  /**
3556  * Sets the security token for the context. To access an object in
3557  * another context, the security tokens must match.
3558  */
3560 
3561  /** Restores the security token to the default value. */
3563 
3564  /** Returns the security token of this context.*/
3566 
3567  /**
3568  * Enter this context. After entering a context, all code compiled
3569  * and run is compiled and run in this context. If another context
3570  * is already entered, this old context is saved so it can be
3571  * restored when the new context is exited.
3572  */
3573  void Enter();
3574 
3575  /**
3576  * Exit this context. Exiting the current context restores the
3577  * context that was in place when entering the current context.
3578  */
3579  void Exit();
3580 
3581  /** Returns true if the context has experienced an out of memory situation. */
3583 
3584  /** Returns true if V8 has a current context. */
3585  static bool InContext();
3586 
3587  /**
3588  * Associate an additional data object with the context. This is mainly used
3589  * with the debugger to provide additional information on the context through
3590  * the debugger API.
3591  */
3592  void SetData(Handle<String> data);
3594 
3595  /**
3596  * Control whether code generation from strings is allowed. Calling
3597  * this method with false will disable 'eval' and the 'Function'
3598  * constructor for code running in this context. If 'eval' or the
3599  * 'Function' constructor are used an exception will be thrown.
3600  *
3601  * If code generation from strings is not allowed the
3602  * V8::AllowCodeGenerationFromStrings callback will be invoked if
3603  * set before blocking the call to 'eval' or the 'Function'
3604  * constructor. If that callback returns true, the call will be
3605  * allowed, otherwise an exception will be thrown. If no callback is
3606  * set an exception will be thrown.
3607  */
3609 
3610  /**
3611  * Returns true if code generation from strings is allowed for the context.
3612  * For more details see AllowCodeGenerationFromStrings(bool) documentation.
3613  */
3615 
3616  /**
3617  * Stack-allocated class which sets the execution context for all
3618  * operations executed within a local scope.
3619  */
3620  class Scope {
3621  public:
3622  explicit inline Scope(Handle<Context> context) : context_(context) {
3623  context_->Enter();
3624  }
3625  inline ~Scope() { context_->Exit(); }
3626  private:
3627  Handle<Context> context_;
3628  };
3629 
3630  private:
3631  friend class Value;
3632  friend class Script;
3633  friend class Object;
3634  friend class Function;
3635 };
3636 
3637 
3638 /**
3639  * Multiple threads in V8 are allowed, but only one thread at a time
3640  * is allowed to use any given V8 isolate. See Isolate class
3641  * comments. The definition of 'using V8 isolate' includes
3642  * accessing handles or holding onto object pointers obtained
3643  * from V8 handles while in the particular V8 isolate. It is up
3644  * to the user of V8 to ensure (perhaps with locking) that this
3645  * constraint is not violated. In addition to any other synchronization
3646  * mechanism that may be used, the v8::Locker and v8::Unlocker classes
3647  * must be used to signal thead switches to V8.
3648  *
3649  * v8::Locker is a scoped lock object. While it's
3650  * active (i.e. between its construction and destruction) the current thread is
3651  * allowed to use the locked isolate. V8 guarantees that an isolate can be
3652  * locked by at most one thread at any time. In other words, the scope of a
3653  * v8::Locker is a critical section.
3654  *
3655  * Sample usage:
3656 * \code
3657  * ...
3658  * {
3659  * v8::Locker locker(isolate);
3660  * v8::Isolate::Scope isolate_scope(isolate);
3661  * ...
3662  * // Code using V8 and isolate goes here.
3663  * ...
3664  * } // Destructor called here
3665  * \endcode
3666  *
3667  * If you wish to stop using V8 in a thread A you can do this either
3668  * by destroying the v8::Locker object as above or by constructing a
3669  * v8::Unlocker object:
3670  *
3671  * \code
3672  * {
3673  * isolate->Exit();
3674  * v8::Unlocker unlocker(isolate);
3675  * ...
3676  * // Code not using V8 goes here while V8 can run in another thread.
3677  * ...
3678  * } // Destructor called here.
3679  * isolate->Enter();
3680  * \endcode
3681  *
3682  * The Unlocker object is intended for use in a long-running callback
3683  * from V8, where you want to release the V8 lock for other threads to
3684  * use.
3685  *
3686  * The v8::Locker is a recursive lock. That is, you can lock more than
3687  * once in a given thread. This can be useful if you have code that can
3688  * be called either from code that holds the lock or from code that does
3689  * not. The Unlocker is not recursive so you can not have several
3690  * Unlockers on the stack at once, and you can not use an Unlocker in a
3691  * thread that is not inside a Locker's scope.
3692  *
3693  * An unlocker will unlock several lockers if it has to and reinstate
3694  * the correct depth of locking on its destruction. eg.:
3695  *
3696  * \code
3697  * // V8 not locked.
3698  * {
3699  * v8::Locker locker(isolate);
3700  * Isolate::Scope isolate_scope(isolate);
3701  * // V8 locked.
3702  * {
3703  * v8::Locker another_locker(isolate);
3704  * // V8 still locked (2 levels).
3705  * {
3706  * isolate->Exit();
3707  * v8::Unlocker unlocker(isolate);
3708  * // V8 not locked.
3709  * }
3710  * isolate->Enter();
3711  * // V8 locked again (2 levels).
3712  * }
3713  * // V8 still locked (1 level).
3714  * }
3715  * // V8 Now no longer locked.
3716  * \endcode
3717  *
3718  *
3719  */
3721  public:
3722  /**
3723  * Initialize Unlocker for a given Isolate. NULL means default isolate.
3724  */
3725  explicit Unlocker(Isolate* isolate = NULL);
3727  private:
3728  internal::Isolate* isolate_;
3729 };
3730 
3731 
3733  public:
3734  /**
3735  * Initialize Locker for a given Isolate. NULL means default isolate.
3736  */
3737  explicit Locker(Isolate* isolate = NULL);
3739 
3740  /**
3741  * Start preemption.
3742  *
3743  * When preemption is started, a timer is fired every n milliseconds
3744  * that will switch between multiple threads that are in contention
3745  * for the V8 lock.
3746  */
3747  static void StartPreemption(int every_n_ms);
3748 
3749  /**
3750  * Stop preemption.
3751  */
3752  static void StopPreemption();
3753 
3754  /**
3755  * Returns whether or not the locker for a given isolate, or default isolate
3756  * if NULL is given, is locked by the current thread.
3757  */
3758  static bool IsLocked(Isolate* isolate = NULL);
3759 
3760  /**
3761  * Returns whether v8::Locker is being used by this V8 instance.
3762  */
3763  static bool IsActive();
3764 
3765  private:
3766  bool has_lock_;
3767  bool top_level_;
3768  internal::Isolate* isolate_;
3769 
3770  static bool active_;
3771 
3772  // Disallow copying and assigning.
3773  Locker(const Locker&);
3774  void operator=(const Locker&);
3775 };
3776 
3777 
3778 /**
3779  * A struct for exporting HeapStats data from V8, using "push" model.
3780  */
3781 struct HeapStatsUpdate;
3782 
3783 
3784 /**
3785  * An interface for exporting data from V8, using "push" model.
3786  */
3787 class V8EXPORT OutputStream { // NOLINT
3788  public:
3790  kAscii = 0 // 7-bit ASCII.
3791  };
3794  kAbort = 1
3795  };
3796  virtual ~OutputStream() {}
3797  /** Notify about the end of stream. */
3798  virtual void EndOfStream() = 0;
3799  /** Get preferred output chunk size. Called only once. */
3800  virtual int GetChunkSize() { return 1024; }
3801  /** Get preferred output encoding. Called only once. */
3803  /**
3804  * Writes the next chunk of snapshot data into the stream. Writing
3805  * can be stopped by returning kAbort as function result. EndOfStream
3806  * will not be called in case writing was aborted.
3807  */
3808  virtual WriteResult WriteAsciiChunk(char* data, int size) = 0;
3809  /**
3810  * Writes the next chunk of heap stats data into the stream. Writing
3811  * can be stopped by returning kAbort as function result. EndOfStream
3812  * will not be called in case writing was aborted.
3813  */
3815  return kAbort;
3816  };
3817 };
3818 
3819 
3820 /**
3821  * An interface for reporting progress and controlling long-running
3822  * activities.
3823  */
3824 class V8EXPORT ActivityControl { // NOLINT
3825  public:
3828  kAbort = 1
3829  };
3830  virtual ~ActivityControl() {}
3831  /**
3832  * Notify about current progress. The activity can be stopped by
3833  * returning kAbort as the callback result.
3834  */
3835  virtual ControlOption ReportProgressValue(int done, int total) = 0;
3836 };
3837 
3838 
3839 // --- Implementation ---
3840 
3841 
3842 namespace internal {
3843 
3844 const int kApiPointerSize = sizeof(void*); // NOLINT
3845 const int kApiIntSize = sizeof(int); // NOLINT
3846 
3847 // Tag information for HeapObject.
3848 const int kHeapObjectTag = 1;
3849 const int kHeapObjectTagSize = 2;
3850 const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
3851 
3852 // Tag information for Smi.
3853 const int kSmiTag = 0;
3854 const int kSmiTagSize = 1;
3855 const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
3856 
3857 template <size_t ptr_size> struct SmiTagging;
3858 
3859 // Smi constants for 32-bit systems.
3860 template <> struct SmiTagging<4> {
3861  static const int kSmiShiftSize = 0;
3862  static const int kSmiValueSize = 31;
3863  static inline int SmiToInt(internal::Object* value) {
3864  int shift_bits = kSmiTagSize + kSmiShiftSize;
3865  // Throw away top 32 bits and shift down (requires >> to be sign extending).
3866  return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
3867  }
3868 
3869  // For 32-bit systems any 2 bytes aligned pointer can be encoded as smi
3870  // with a plain reinterpret_cast.
3871  static const uintptr_t kEncodablePointerMask = 0x1;
3872  static const int kPointerToSmiShift = 0;
3873 };
3874 
3875 // Smi constants for 64-bit systems.
3876 template <> struct SmiTagging<8> {
3877  static const int kSmiShiftSize = 31;
3878  static const int kSmiValueSize = 32;
3879  static inline int SmiToInt(internal::Object* value) {
3880  int shift_bits = kSmiTagSize + kSmiShiftSize;
3881  // Shift down and throw away top 32 bits.
3882  return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
3883  }
3884 
3885  // To maximize the range of pointers that can be encoded
3886  // in the available 32 bits, we require them to be 8 bytes aligned.
3887  // This gives 2 ^ (32 + 3) = 32G address space covered.
3888  // It might be not enough to cover stack allocated objects on some platforms.
3889  static const int kPointerAlignment = 3;
3890 
3891  static const uintptr_t kEncodablePointerMask =
3892  ~(uintptr_t(0xffffffff) << kPointerAlignment);
3893 
3894  static const int kPointerToSmiShift =
3896 };
3897 
3901 const uintptr_t kEncodablePointerMask =
3904 
3905 /**
3906  * This class exports constants and functionality from within v8 that
3907  * is necessary to implement inline functions in the v8 api. Don't
3908  * depend on functions and constants defined here.
3909  */
3910 class Internals {
3911  public:
3912  // These values match non-compiler-dependent values defined within
3913  // the implementation of v8.
3914  static const int kHeapObjectMapOffset = 0;
3916  static const int kStringResourceOffset = 3 * kApiPointerSize;
3917 
3918  static const int kOddballKindOffset = 3 * kApiPointerSize;
3920  static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
3921  static const int kFullStringRepresentationMask = 0x07;
3922  static const int kExternalTwoByteRepresentationTag = 0x02;
3923 
3924  static const int kIsolateStateOffset = 0;
3926  static const int kIsolateRootsOffset = 3 * kApiPointerSize;
3927  static const int kUndefinedValueRootIndex = 5;
3928  static const int kNullValueRootIndex = 7;
3929  static const int kTrueValueRootIndex = 8;
3930  static const int kFalseValueRootIndex = 9;
3931  static const int kEmptySymbolRootIndex = 128;
3932 
3933  static const int kJSObjectType = 0xaa;
3934  static const int kFirstNonstringType = 0x80;
3935  static const int kOddballType = 0x82;
3936  static const int kForeignType = 0x85;
3937 
3938  static const int kUndefinedOddballKind = 5;
3939  static const int kNullOddballKind = 3;
3940 
3941  static inline bool HasHeapObjectTag(internal::Object* value) {
3942  return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
3943  kHeapObjectTag);
3944  }
3945 
3946  static inline bool HasSmiTag(internal::Object* value) {
3947  return ((reinterpret_cast<intptr_t>(value) & kSmiTagMask) == kSmiTag);
3948  }
3949 
3950  static inline int SmiValue(internal::Object* value) {
3951  return PlatformSmiTagging::SmiToInt(value);
3952  }
3953 
3954  static inline int GetInstanceType(internal::Object* obj) {
3955  typedef internal::Object O;
3957  return ReadField<uint8_t>(map, kMapInstanceTypeOffset);
3958  }
3959 
3960  static inline int GetOddballKind(internal::Object* obj) {
3961  typedef internal::Object O;
3963  }
3964 
3965  static inline void* GetExternalPointerFromSmi(internal::Object* value) {
3966  const uintptr_t address = reinterpret_cast<uintptr_t>(value);
3967  return reinterpret_cast<void*>(address >> kPointerToSmiShift);
3968  }
3969 
3970  static inline void* GetExternalPointer(internal::Object* obj) {
3971  if (HasSmiTag(obj)) {
3972  return GetExternalPointerFromSmi(obj);
3973  } else if (GetInstanceType(obj) == kForeignType) {
3974  return ReadField<void*>(obj, kForeignAddressOffset);
3975  } else {
3976  return NULL;
3977  }
3978  }
3979 
3980  static inline bool IsExternalTwoByteString(int instance_type) {
3981  int representation = (instance_type & kFullStringRepresentationMask);
3982  return representation == kExternalTwoByteRepresentationTag;
3983  }
3984 
3985  static inline bool IsInitialized(v8::Isolate* isolate) {
3986  uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) + kIsolateStateOffset;
3987  return *reinterpret_cast<int*>(addr) == 1;
3988  }
3989 
3990  static inline void SetEmbedderData(v8::Isolate* isolate, void* data) {
3991  uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) +
3993  *reinterpret_cast<void**>(addr) = data;
3994  }
3995 
3996  static inline void* GetEmbedderData(v8::Isolate* isolate) {
3997  uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) +
3999  return *reinterpret_cast<void**>(addr);
4000  }
4001 
4002  static inline internal::Object** GetRoot(v8::Isolate* isolate, int index) {
4003  uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) + kIsolateRootsOffset;
4004  return reinterpret_cast<internal::Object**>(addr + index * kApiPointerSize);
4005  }
4006 
4007  template <typename T>
4008  static inline T ReadField(Object* ptr, int offset) {
4009  uint8_t* addr = reinterpret_cast<uint8_t*>(ptr) + offset - kHeapObjectTag;
4010  return *reinterpret_cast<T*>(addr);
4011  }
4012 
4013  static inline bool CanCastToHeapObject(void* o) { return false; }
4014  static inline bool CanCastToHeapObject(Context* o) { return true; }
4015  static inline bool CanCastToHeapObject(String* o) { return true; }
4016  static inline bool CanCastToHeapObject(Object* o) { return true; }
4017  static inline bool CanCastToHeapObject(Message* o) { return true; }
4018  static inline bool CanCastToHeapObject(StackTrace* o) { return true; }
4019  static inline bool CanCastToHeapObject(StackFrame* o) { return true; }
4020 };
4021 
4022 } // namespace internal
4023 
4024 
4025 template <class T>
4026 Local<T>::Local() : Handle<T>() { }
4027 
4028 
4029 template <class T>
4030 Local<T> Local<T>::New(Handle<T> that) {
4031  if (that.IsEmpty()) return Local<T>();
4032  T* that_ptr = *that;
4033  internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
4034  if (internal::Internals::CanCastToHeapObject(that_ptr)) {
4035  return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
4036  reinterpret_cast<internal::HeapObject*>(*p))));
4037  }
4038  return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(*p)));
4039 }
4040 
4041 
4042 template <class T>
4043 Persistent<T> Persistent<T>::New(Handle<T> that) {
4044  if (that.IsEmpty()) return Persistent<T>();
4045  internal::Object** p = reinterpret_cast<internal::Object**>(*that);
4046  return Persistent<T>(reinterpret_cast<T*>(V8::GlobalizeReference(p)));
4047 }
4048 
4049 
4050 template <class T>
4051 bool Persistent<T>::IsNearDeath() const {
4052  if (this->IsEmpty()) return false;
4053  return V8::IsGlobalNearDeath(reinterpret_cast<internal::Object**>(**this));
4054 }
4055 
4056 
4057 template <class T>
4058 bool Persistent<T>::IsWeak() const {
4059  if (this->IsEmpty()) return false;
4060  return V8::IsGlobalWeak(reinterpret_cast<internal::Object**>(**this));
4061 }
4062 
4063 
4064 template <class T>
4065 void Persistent<T>::Dispose() {
4066  if (this->IsEmpty()) return;
4067  V8::DisposeGlobal(reinterpret_cast<internal::Object**>(**this));
4068 }
4069 
4070 
4071 template <class T>
4072 Persistent<T>::Persistent() : Handle<T>() { }
4073 
4074 template <class T>
4075 void Persistent<T>::MakeWeak(void* parameters, WeakReferenceCallback callback) {
4076  V8::MakeWeak(reinterpret_cast<internal::Object**>(**this),
4077  parameters,
4078  callback);
4079 }
4080 
4081 template <class T>
4082 void Persistent<T>::ClearWeak() {
4083  V8::ClearWeak(reinterpret_cast<internal::Object**>(**this));
4084 }
4085 
4086 template <class T>
4088  V8::MarkIndependent(reinterpret_cast<internal::Object**>(**this));
4089 }
4090 
4091 template <class T>
4092 void Persistent<T>::SetWrapperClassId(uint16_t class_id) {
4093  V8::SetWrapperClassId(reinterpret_cast<internal::Object**>(**this), class_id);
4094 }
4095 
4096 Arguments::Arguments(internal::Object** implicit_args,
4097  internal::Object** values, int length,
4098  bool is_construct_call)
4099  : implicit_args_(implicit_args),
4100  values_(values),
4101  length_(length),
4102  is_construct_call_(is_construct_call) { }
4103 
4104 
4105 Local<Value> Arguments::operator[](int i) const {
4106  if (i < 0 || length_ <= i) return Local<Value>(*Undefined());
4107  return Local<Value>(reinterpret_cast<Value*>(values_ - i));
4108 }
4109 
4110 
4112  return Local<Function>(reinterpret_cast<Function*>(
4113  &implicit_args_[kCalleeIndex]));
4114 }
4115 
4116 
4118  return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
4119 }
4120 
4121 
4123  return Local<Object>(reinterpret_cast<Object*>(
4124  &implicit_args_[kHolderIndex]));
4125 }
4126 
4127 
4129  return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
4130 }
4131 
4132 
4134  return *reinterpret_cast<Isolate**>(&implicit_args_[kIsolateIndex]);
4135 }
4136 
4137 
4139  return is_construct_call_;
4140 }
4141 
4142 
4143 int Arguments::Length() const {
4144  return length_;
4145 }
4146 
4147 
4148 template <class T>
4150  internal::Object** before = reinterpret_cast<internal::Object**>(*value);
4151  internal::Object** after = RawClose(before);
4152  return Local<T>(reinterpret_cast<T*>(after));
4153 }
4154 
4156  return resource_name_;
4157 }
4158 
4159 
4161  return resource_line_offset_;
4162 }
4163 
4164 
4166  return resource_column_offset_;
4167 }
4168 
4169 
4170 Handle<Boolean> Boolean::New(bool value) {
4171  return value ? True() : False();
4172 }
4173 
4174 
4175 void Template::Set(const char* name, v8::Handle<Data> value) {
4176  Set(v8::String::New(name), value);
4177 }
4178 
4179 
4181 #ifndef V8_ENABLE_CHECKS
4182  Local<Value> quick_result = UncheckedGetInternalField(index);
4183  if (!quick_result.IsEmpty()) return quick_result;
4184 #endif
4185  return CheckedGetInternalField(index);
4186 }
4187 
4188 
4189 Local<Value> Object::UncheckedGetInternalField(int index) {
4190  typedef internal::Object O;
4191  typedef internal::Internals I;
4192  O* obj = *reinterpret_cast<O**>(this);
4193  if (I::GetInstanceType(obj) == I::kJSObjectType) {
4194  // If the object is a plain JSObject, which is the common case,
4195  // we know where to find the internal fields and can return the
4196  // value directly.
4197  int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
4198  O* value = I::ReadField<O*>(obj, offset);
4199  O** result = HandleScope::CreateHandle(value);
4200  return Local<Value>(reinterpret_cast<Value*>(result));
4201  } else {
4202  return Local<Value>();
4203  }
4204 }
4205 
4206 
4207 void* External::Unwrap(Handle<v8::Value> obj) {
4208 #ifdef V8_ENABLE_CHECKS
4209  return FullUnwrap(obj);
4210 #else
4211  return QuickUnwrap(obj);
4212 #endif
4213 }
4214 
4215 
4216 void* External::QuickUnwrap(Handle<v8::Value> wrapper) {
4217  typedef internal::Object O;
4218  O* obj = *reinterpret_cast<O**>(const_cast<v8::Value*>(*wrapper));
4220 }
4221 
4222 
4224  typedef internal::Object O;
4225  typedef internal::Internals I;
4226 
4227  O* obj = *reinterpret_cast<O**>(this);
4228 
4229  if (I::GetInstanceType(obj) == I::kJSObjectType) {
4230  // If the object is a plain JSObject, which is the common case,
4231  // we know where to find the internal fields and can return the
4232  // value directly.
4233  int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
4234  O* value = I::ReadField<O*>(obj, offset);
4235  return I::GetExternalPointer(value);
4236  }
4237 
4238  return SlowGetPointerFromInternalField(index);
4239 }
4240 
4241 
4242 String* String::Cast(v8::Value* value) {
4243 #ifdef V8_ENABLE_CHECKS
4244  CheckCast(value);
4245 #endif
4246  return static_cast<String*>(value);
4247 }
4248 
4249 
4251  typedef internal::Object* S;
4252  typedef internal::Internals I;
4253  if (!I::IsInitialized(isolate)) return Empty();
4254  S* slot = I::GetRoot(isolate, I::kEmptySymbolRootIndex);
4255  return Local<String>(reinterpret_cast<String*>(slot));
4256 }
4257 
4258 
4260  typedef internal::Object O;
4261  typedef internal::Internals I;
4262  O* obj = *reinterpret_cast<O**>(const_cast<String*>(this));
4263  String::ExternalStringResource* result;
4265  void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
4266  result = reinterpret_cast<String::ExternalStringResource*>(value);
4267  } else {
4268  result = NULL;
4269  }
4270 #ifdef V8_ENABLE_CHECKS
4271  VerifyExternalStringResource(result);
4272 #endif
4273  return result;
4274 }
4275 
4276 
4277 bool Value::IsUndefined() const {
4278 #ifdef V8_ENABLE_CHECKS
4279  return FullIsUndefined();
4280 #else
4281  return QuickIsUndefined();
4282 #endif
4283 }
4284 
4285 bool Value::QuickIsUndefined() const {
4286  typedef internal::Object O;
4287  typedef internal::Internals I;
4288  O* obj = *reinterpret_cast<O**>(const_cast<Value*>(this));
4289  if (!I::HasHeapObjectTag(obj)) return false;
4290  if (I::GetInstanceType(obj) != I::kOddballType) return false;
4292 }
4293 
4294 
4295 bool Value::IsNull() const {
4296 #ifdef V8_ENABLE_CHECKS
4297  return FullIsNull();
4298 #else
4299  return QuickIsNull();
4300 #endif
4301 }
4302 
4303 bool Value::QuickIsNull() const {
4304  typedef internal::Object O;
4305  typedef internal::Internals I;
4306  O* obj = *reinterpret_cast<O**>(const_cast<Value*>(this));
4307  if (!I::HasHeapObjectTag(obj)) return false;
4308  if (I::GetInstanceType(obj) != I::kOddballType) return false;
4309  return (I::GetOddballKind(obj) == I::kNullOddballKind);
4310 }
4311 
4312 
4313 bool Value::IsString() const {
4314 #ifdef V8_ENABLE_CHECKS
4315  return FullIsString();
4316 #else
4317  return QuickIsString();
4318 #endif
4319 }
4320 
4321 bool Value::QuickIsString() const {
4322  typedef internal::Object O;
4323  typedef internal::Internals I;
4324  O* obj = *reinterpret_cast<O**>(const_cast<Value*>(this));
4325  if (!I::HasHeapObjectTag(obj)) return false;
4327 }
4328 
4329 
4330 Number* Number::Cast(v8::Value* value) {
4331 #ifdef V8_ENABLE_CHECKS
4332  CheckCast(value);
4333 #endif
4334  return static_cast<Number*>(value);
4335 }
4336 
4337 
4339 #ifdef V8_ENABLE_CHECKS
4340  CheckCast(value);
4341 #endif
4342  return static_cast<Integer*>(value);
4343 }
4344 
4345 
4346 Date* Date::Cast(v8::Value* value) {
4347 #ifdef V8_ENABLE_CHECKS
4348  CheckCast(value);
4349 #endif
4350  return static_cast<Date*>(value);
4351 }
4352 
4353 
4355 #ifdef V8_ENABLE_CHECKS
4356  CheckCast(value);
4357 #endif
4358  return static_cast<StringObject*>(value);
4359 }
4360 
4361 
4363 #ifdef V8_ENABLE_CHECKS
4364  CheckCast(value);
4365 #endif
4366  return static_cast<NumberObject*>(value);
4367 }
4368 
4369 
4371 #ifdef V8_ENABLE_CHECKS
4372  CheckCast(value);
4373 #endif
4374  return static_cast<BooleanObject*>(value);
4375 }
4376 
4377 
4378 RegExp* RegExp::Cast(v8::Value* value) {
4379 #ifdef V8_ENABLE_CHECKS
4380  CheckCast(value);
4381 #endif
4382  return static_cast<RegExp*>(value);
4383 }
4384 
4385 
4386 Object* Object::Cast(v8::Value* value) {
4387 #ifdef V8_ENABLE_CHECKS
4388  CheckCast(value);
4389 #endif
4390  return static_cast<Object*>(value);
4391 }
4392 
4393 
4394 Array* Array::Cast(v8::Value* value) {
4395 #ifdef V8_ENABLE_CHECKS
4396  CheckCast(value);
4397 #endif
4398  return static_cast<Array*>(value);
4399 }
4400 
4401 
4403 #ifdef V8_ENABLE_CHECKS
4404  CheckCast(value);
4405 #endif
4406  return static_cast<Function*>(value);
4407 }
4408 
4409 
4411 #ifdef V8_ENABLE_CHECKS
4412  CheckCast(value);
4413 #endif
4414  return static_cast<External*>(value);
4415 }
4416 
4417 
4419  return *reinterpret_cast<Isolate**>(&args_[-3]);
4420 }
4421 
4422 
4424  return Local<Value>(reinterpret_cast<Value*>(&args_[-2]));
4425 }
4426 
4427 
4429  return Local<Object>(reinterpret_cast<Object*>(&args_[0]));
4430 }
4431 
4432 
4434  return Local<Object>(reinterpret_cast<Object*>(&args_[-1]));
4435 }
4436 
4437 
4439  typedef internal::Object* S;
4440  typedef internal::Internals I;
4441  if (!I::IsInitialized(isolate)) return Undefined();
4442  S* slot = I::GetRoot(isolate, I::kUndefinedValueRootIndex);
4443  return Handle<Primitive>(reinterpret_cast<Primitive*>(slot));
4444 }
4445 
4446 
4448  typedef internal::Object* S;
4449  typedef internal::Internals I;
4450  if (!I::IsInitialized(isolate)) return Null();
4451  S* slot = I::GetRoot(isolate, I::kNullValueRootIndex);
4452  return Handle<Primitive>(reinterpret_cast<Primitive*>(slot));
4453 }
4454 
4455 
4457  typedef internal::Object* S;
4458  typedef internal::Internals I;
4459  if (!I::IsInitialized(isolate)) return True();
4460  S* slot = I::GetRoot(isolate, I::kTrueValueRootIndex);
4461  return Handle<Boolean>(reinterpret_cast<Boolean*>(slot));
4462 }
4463 
4464 
4466  typedef internal::Object* S;
4467  typedef internal::Internals I;
4468  if (!I::IsInitialized(isolate)) return False();
4469  S* slot = I::GetRoot(isolate, I::kFalseValueRootIndex);
4470  return Handle<Boolean>(reinterpret_cast<Boolean*>(slot));
4471 }
4472 
4473 
4474 void Isolate::SetData(void* data) {
4475  typedef internal::Internals I;
4476  I::SetEmbedderData(this, data);
4477 }
4478 
4479 
4480 void* Isolate::GetData() {
4481  typedef internal::Internals I;
4482  return I::GetEmbedderData(this);
4483 }
4484 
4485 
4486 /**
4487  * \example shell.cc
4488  * A simple shell that takes a list of expressions on the
4489  * command-line and executes them.
4490  */
4491 
4492 
4493 /**
4494  * \example process.cc
4495  */
4496 
4497 
4498 } // namespace v8
4499 
4500 
4501 #undef V8EXPORT
4502 #undef TYPE_CHECK
4503 
4504 
4505 #endif // V8_H_