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