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