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
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.
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.
28 /** \mainpage V8 API Reference Guide
30 * V8 is Google's open source JavaScript engine.
32 * This set of documents provides reference material generated from the
33 * V8 header file, include/v8.h.
35 * For other documentation see http://code.google.com/apis/v8/
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
55 #ifdef BUILDING_V8_SHARED
56 #define V8EXPORT __declspec(dllexport)
58 #define V8EXPORT __declspec(dllimport)
61 #endif // BUILDING_V8_SHARED
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)
72 #endif // defined(__GNUC__) && (__GNUC__ >= 4)
77 * The v8 JavaScript engine.
99 class ImplementationUtilities;
101 template <class T> class Handle;
102 template <class T> class Local;
103 template <class T> class Persistent;
104 class FunctionTemplate;
105 class ObjectTemplate;
121 // --- Weak Handles ---
125 * A weak reference callback function.
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.
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
133 typedef void (*WeakReferenceCallback)(Persistent<Value> object,
139 #define TYPE_CHECK(T, S) \
141 *(static_cast<T* volatile*>(0)) = static_cast<S*>(0); \
145 * An object reference managed by the v8 garbage collector.
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.
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
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
169 template <class T> class Handle {
172 * Creates an empty handle.
174 inline Handle() : val_(0) {}
177 * Creates a new handle for the specified value.
179 inline explicit Handle(T* val) : val_(val) {}
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.
191 template <class S> inline Handle(Handle<S> that)
192 : val_(reinterpret_cast<T*>(*that)) {
194 * This check fails when trying to convert between incompatible
195 * handles. For example, converting from a Handle<String> to a
202 * Returns true if the handle is empty.
204 inline bool IsEmpty() const { return val_ == 0; }
207 * Sets the handle to be empty. IsEmpty() will then return true.
209 inline void Clear() { val_ = 0; }
211 inline T* operator->() const { return val_; }
213 inline T* operator*() const { return val_; }
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.
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;
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.
235 template <class S> inline bool operator!=(Handle<S> that) const {
236 return !operator==(that);
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>();
245 return Handle<T>(T::Cast(*that));
248 template <class S> inline Handle<S> As() {
249 return Handle<S>::Cast(*this);
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.
264 template <class T> class Local : public Handle<T> {
267 template <class S> inline Local(Local<S> that)
268 : Handle<T>(reinterpret_cast<T*>(*that)) {
270 * This check fails when trying to convert between incompatible
271 * handles. For example, converting from a Handle<String> to a
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>();
283 return Local<T>(T::Cast(*that));
286 template <class S> inline Local<S> As() {
287 return Local<S>::Cast(*this);
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.
294 inline static Local<T> New(Handle<T> that);
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
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
315 template <class T> class Persistent : public Handle<T> {
318 * Creates an empty persistent handle that doesn't point to any
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.
334 template <class S> inline Persistent(Persistent<S> that)
335 : Handle<T>(reinterpret_cast<T*>(*that)) {
337 * This check fails when trying to convert between incompatible
338 * handles. For example, converting from a Handle<String> to a
344 template <class S> inline Persistent(S* that) : Handle<T>(that) { }
347 * "Casts" a plain handle which is known to be a persistent handle
348 * to a persistent handle.
350 template <class S> explicit inline Persistent(Handle<S> that)
351 : Handle<T>(*that) { }
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>();
359 return Persistent<T>(T::Cast(*that));
362 template <class S> inline Persistent<S> As() {
363 return Persistent<S>::Cast(*this);
367 * Creates a new persistent handle for an existing local or
370 inline static Persistent<T> New(Handle<T> that);
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.
378 inline void Dispose();
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.
386 inline void MakeWeak(void* parameters, WeakReferenceCallback callback);
388 /** Clears the weak reference to this object.*/
389 inline void ClearWeak();
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.
398 inline void MarkIndependent();
401 *Checks if the handle holds the only reference to an object.
403 inline bool IsNearDeath() const;
406 * Returns true if the handle's reference is weak.
408 inline bool IsWeak() const;
411 * Assigns a wrapper class ID to the handle. See RetainedObjectInfo
412 * interface description in v8-profiler.h for details.
414 inline void SetWrapperClassId(uint16_t class_id);
417 friend class ImplementationUtilities;
418 friend class ObjectTemplate;
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.
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.
436 class V8EXPORT HandleScope {
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.
446 template <class T> Local<T> Close(Handle<T> value);
449 * Counts the number of allocated handles.
451 static int NumberOfHandles();
454 * Creates a new handle with the given value.
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);
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);
468 // This Data class is accessible internally as HandleScopeData through a
469 // typedef in the ImplementationUtilities class.
470 class V8EXPORT Data {
472 internal::Object** next;
473 internal::Object** limit;
475 inline void Initialize() {
483 internal::Isolate* isolate_;
484 internal::Object** prev_next_;
485 internal::Object** prev_limit_;
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.
490 internal::Object** RawClose(internal::Object** value);
492 friend class ImplementationUtilities;
496 // --- Special objects ---
500 * The superclass of values and API object templates.
502 class V8EXPORT Data {
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.
514 class V8EXPORT ScriptData { // NOLINT
516 virtual ~ScriptData() { }
519 * Pre-compiles the specified script (context-independent).
521 * \param input Pointer to UTF-8 script source code.
522 * \param length Length of UTF-8 script source code.
524 static ScriptData* PreCompile(const char* input, int length);
527 * Pre-compiles the specified script (context-independent).
529 * NOTE: Pre-compilation using this method cannot happen on another thread
530 * without using Lockers.
532 * \param source Script source code.
534 static ScriptData* PreCompile(Handle<String> source);
537 * Load previous pre-compilation data.
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.
543 static ScriptData* New(const char* data, int length);
546 * Returns the length of Data().
548 virtual int Length() = 0;
551 * Returns a serialized representation of this ScriptData that can later be
552 * passed to New(). NOTE: Serialized data is platform-dependent.
554 virtual const char* Data() = 0;
557 * Returns true if the source code could not be parsed.
559 virtual bool HasError() = 0;
564 * The origin, within a file, of a script.
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;
579 Handle<Value> resource_name_;
580 Handle<Integer> resource_line_offset_;
581 Handle<Integer> resource_column_offset_;
586 * A compiled JavaScript script.
588 class V8EXPORT Script {
597 * Compiles the specified script (context-independent).
599 * \param source Script source code.
600 * \param origin Script origin, owned by caller, no references are kept
602 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
603 * using pre_data speeds compilation if it's done multiple times.
604 * Owned by caller, no references are kept when New() returns.
605 * \param script_data Arbitrary data associated with script. Using
606 * this has same effect as calling SetData(), but allows data to be
607 * available to compile event handlers.
608 * \return Compiled script object (context independent; when run it
609 * will use the currently entered context).
611 static Local<Script> New(Handle<String> source,
612 ScriptOrigin* origin = NULL,
613 ScriptData* pre_data = NULL,
614 Handle<String> script_data = Handle<String>(),
615 CompileFlags = Default);
618 * Compiles the specified script using the specified file name
619 * object (typically a string) as the script's origin.
621 * \param source Script source code.
622 * \param file_name file name object (typically a string) to be used
623 * as the script's origin.
624 * \return Compiled script object (context independent; when run it
625 * will use the currently entered context).
627 static Local<Script> New(Handle<String> source,
628 Handle<Value> file_name,
629 CompileFlags = Default);
632 * Compiles the specified script (bound to current context).
634 * \param source Script source code.
635 * \param origin Script origin, owned by caller, no references are kept
636 * when Compile() returns
637 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
638 * using pre_data speeds compilation if it's done multiple times.
639 * Owned by caller, no references are kept when Compile() returns.
640 * \param script_data Arbitrary data associated with script. Using
641 * this has same effect as calling SetData(), but makes data available
642 * earlier (i.e. to compile event handlers).
643 * \return Compiled script object, bound to the context that was active
644 * when this function was called. When run it will always use this
647 static Local<Script> Compile(Handle<String> source,
648 ScriptOrigin* origin = NULL,
649 ScriptData* pre_data = NULL,
650 Handle<String> script_data = Handle<String>(),
651 CompileFlags = Default);
654 * Compiles the specified script using the specified file name
655 * object (typically a string) as the script's origin.
657 * \param source Script source code.
658 * \param file_name File name to use as script's origin
659 * \param script_data Arbitrary data associated with script. Using
660 * this has same effect as calling SetData(), but makes data available
661 * earlier (i.e. to compile event handlers).
662 * \return Compiled script object, bound to the context that was active
663 * when this function was called. When run it will always use this
666 static Local<Script> Compile(Handle<String> source,
667 Handle<Value> file_name,
668 Handle<String> script_data = Handle<String>(),
669 CompileFlags = Default);
672 * Runs the script returning the resulting value. If the script is
673 * context independent (created using ::New) it will be run in the
674 * currently entered context. If it is context specific (created
675 * using ::Compile) it will be run in the context in which it was
679 Local<Value> Run(Handle<Object> qml);
682 * Returns the script id value.
687 * Associate an additional data object with the script. This is mainly used
688 * with the debugger as this data object is only available through the
691 void SetData(Handle<String> data);
698 class V8EXPORT Message {
700 Local<String> Get() const;
701 Local<String> GetSourceLine() const;
704 * Returns the resource name for the script from where the function causing
705 * the error originates.
707 Handle<Value> GetScriptResourceName() const;
710 * Returns the resource data for the script from where the function causing
711 * the error originates.
713 Handle<Value> GetScriptData() const;
716 * Exception stack trace. By default stack traces are not captured for
717 * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
718 * to change this option.
720 Handle<StackTrace> GetStackTrace() const;
723 * Returns the number, 1-based, of the line where the error occurred.
725 int GetLineNumber() const;
728 * Returns the index within the script of the first character where
729 * the error occurred.
731 int GetStartPosition() const;
734 * Returns the index within the script of the last character where
735 * the error occurred.
737 int GetEndPosition() const;
740 * Returns the index within the line of the first character where
741 * the error occurred.
743 int GetStartColumn() const;
746 * Returns the index within the line of the last character where
747 * the error occurred.
749 int GetEndColumn() const;
751 // TODO(1245381): Print to a string instead of on a FILE.
752 static void PrintCurrentStackTrace(FILE* out);
754 static const int kNoLineNumberInfo = 0;
755 static const int kNoColumnInfo = 0;
760 * Representation of a JavaScript stack trace. The information collected is a
761 * snapshot of the execution stack and the information remains valid after
762 * execution continues.
764 class V8EXPORT StackTrace {
767 * Flags that determine what information is placed captured for each
768 * StackFrame when grabbing the current stack trace.
770 enum StackTraceOptions {
772 kColumnOffset = 1 << 1 | kLineNumber,
773 kScriptName = 1 << 2,
774 kFunctionName = 1 << 3,
776 kIsConstructor = 1 << 5,
777 kScriptNameOrSourceURL = 1 << 6,
778 kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
779 kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL
783 * Returns a StackFrame at a particular index.
785 Local<StackFrame> GetFrame(uint32_t index) const;
788 * Returns the number of StackFrames.
790 int GetFrameCount() const;
793 * Returns StackTrace as a v8::Array that contains StackFrame objects.
795 Local<Array> AsArray();
798 * Grab a snapshot of the current JavaScript execution stack.
800 * \param frame_limit The maximum number of stack frames we want to capture.
801 * \param options Enumerates the set of things we will capture for each
804 static Local<StackTrace> CurrentStackTrace(
806 StackTraceOptions options = kOverview);
811 * A single JavaScript stack frame.
813 class V8EXPORT StackFrame {
816 * Returns the number, 1-based, of the line for the associate function call.
817 * This method will return Message::kNoLineNumberInfo if it is unable to
818 * retrieve the line number, or if kLineNumber was not passed as an option
819 * when capturing the StackTrace.
821 int GetLineNumber() const;
824 * Returns the 1-based column offset on the line for the associated function
826 * This method will return Message::kNoColumnInfo if it is unable to retrieve
827 * the column number, or if kColumnOffset was not passed as an option when
828 * capturing the StackTrace.
830 int GetColumn() const;
833 * Returns the name of the resource that contains the script for the
834 * function for this StackFrame.
836 Local<String> GetScriptName() const;
839 * Returns the name of the resource that contains the script for the
840 * function for this StackFrame or sourceURL value if the script name
841 * is undefined and its source ends with //@ sourceURL=... string.
843 Local<String> GetScriptNameOrSourceURL() const;
846 * Returns the name of the function associated with this stack frame.
848 Local<String> GetFunctionName() const;
851 * Returns whether or not the associated function is compiled via a call to
857 * Returns whether or not the associated function is called as a
858 * constructor via "new".
860 bool IsConstructor() const;
868 * The superclass of all JavaScript values and objects.
870 class Value : public Data {
873 * Returns true if this value is the undefined value. See ECMA-262
876 V8EXPORT bool IsUndefined() const;
879 * Returns true if this value is the null value. See ECMA-262
882 V8EXPORT bool IsNull() const;
885 * Returns true if this value is true.
887 V8EXPORT bool IsTrue() const;
890 * Returns true if this value is false.
892 V8EXPORT bool IsFalse() const;
895 * Returns true if this value is an instance of the String type.
898 inline bool IsString() const;
901 * Returns true if this value is a function.
903 V8EXPORT bool IsFunction() const;
906 * Returns true if this value is an array.
908 V8EXPORT bool IsArray() const;
911 * Returns true if this value is an object.
913 V8EXPORT bool IsObject() const;
916 * Returns true if this value is boolean.
918 V8EXPORT bool IsBoolean() const;
921 * Returns true if this value is a number.
923 V8EXPORT bool IsNumber() const;
926 * Returns true if this value is external.
928 V8EXPORT bool IsExternal() const;
931 * Returns true if this value is a 32-bit signed integer.
933 V8EXPORT bool IsInt32() const;
936 * Returns true if this value is a 32-bit unsigned integer.
938 V8EXPORT bool IsUint32() const;
941 * Returns true if this value is a Date.
943 V8EXPORT bool IsDate() const;
946 * Returns true if this value is a Boolean object.
948 V8EXPORT bool IsBooleanObject() const;
951 * Returns true if this value is a Number object.
953 V8EXPORT bool IsNumberObject() const;
956 * Returns true if this value is a String object.
958 V8EXPORT bool IsStringObject() const;
961 * Returns true if this value is a NativeError.
963 V8EXPORT bool IsNativeError() const;
966 * Returns true if this value is a RegExp.
968 V8EXPORT bool IsRegExp() const;
971 * Returns true if this value is an Error.
973 V8EXPORT bool IsError() const;
975 V8EXPORT Local<Boolean> ToBoolean() const;
976 V8EXPORT Local<Number> ToNumber() const;
977 V8EXPORT Local<String> ToString() const;
978 V8EXPORT Local<String> ToDetailString() const;
979 V8EXPORT Local<Object> ToObject() const;
980 V8EXPORT Local<Integer> ToInteger() const;
981 V8EXPORT Local<Uint32> ToUint32() const;
982 V8EXPORT Local<Int32> ToInt32() const;
985 * Attempts to convert a string to an array index.
986 * Returns an empty handle if the conversion fails.
988 V8EXPORT Local<Uint32> ToArrayIndex() const;
990 V8EXPORT bool BooleanValue() const;
991 V8EXPORT double NumberValue() const;
992 V8EXPORT int64_t IntegerValue() const;
993 V8EXPORT uint32_t Uint32Value() const;
994 V8EXPORT int32_t Int32Value() const;
997 V8EXPORT bool Equals(Handle<Value> that) const;
998 V8EXPORT bool StrictEquals(Handle<Value> that) const;
1001 inline bool QuickIsString() const;
1002 V8EXPORT bool FullIsString() const;
1007 * The superclass of primitive values. See ECMA-262 4.3.2.
1009 class Primitive : public Value { };
1013 * A primitive boolean value (ECMA-262, 4.3.14). Either the true
1016 class Boolean : public Primitive {
1018 V8EXPORT bool Value() const;
1019 static inline Handle<Boolean> New(bool value);
1024 * A JavaScript string value (ECMA-262, 4.3.17).
1026 class String : public Primitive {
1029 * Returns the number of characters in this string.
1031 V8EXPORT int Length() const;
1034 * Returns the number of bytes in the UTF-8 encoded
1035 * representation of this string.
1037 V8EXPORT int Utf8Length() const;
1040 * Returns the hash of this string.
1042 V8EXPORT uint32_t Hash() const;
1044 struct CompleteHashData {
1045 CompleteHashData() : length(0), hash(0), symbol_id(0) {}
1052 * Returns the "complete" hash of the string. This is
1053 * all the information about the string needed to implement
1054 * a very efficient hash keyed on the string.
1056 * The members of CompleteHashData are:
1057 * length: The length of the string. Equivalent to Length()
1058 * hash: The hash of the string. Equivalent to Hash()
1059 * symbol_id: If the string is a sequential symbol, the symbol
1060 * id, otherwise 0. If the symbol ids of two strings are
1061 * the same (and non-zero) the two strings are identical.
1062 * If the symbol ids are different the strings may still be
1063 * identical, but an Equals() check must be performed.
1065 V8EXPORT CompleteHashData CompleteHash() const;
1068 * Compute a hash value for the passed UTF16 string
1071 V8EXPORT static uint32_t ComputeHash(uint16_t *string, int length);
1072 V8EXPORT static uint32_t ComputeHash(char *string, int length);
1075 * Returns true if this string is equal to the external
1076 * string data provided.
1078 V8EXPORT bool Equals(uint16_t *string, int length);
1079 V8EXPORT bool Equals(char *string, int length);
1080 inline bool Equals(Handle<Value> that) const { return v8::Value::Equals(that); }
1083 * Write the contents of the string to an external buffer.
1084 * If no arguments are given, expects the buffer to be large
1085 * enough to hold the entire string and NULL terminator. Copies
1086 * the contents of the string and the NULL terminator into the
1089 * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
1090 * before the end of the buffer.
1092 * Copies up to length characters into the output buffer.
1093 * Only null-terminates if there is enough space in the buffer.
1095 * \param buffer The buffer into which the string will be copied.
1096 * \param start The starting position within the string at which
1098 * \param length The number of characters to copy from the string. For
1099 * WriteUtf8 the number of bytes in the buffer.
1100 * \param nchars_ref The number of characters written, can be NULL.
1101 * \param options Various options that might affect performance of this or
1102 * subsequent operations.
1103 * \return The number of characters copied to the buffer excluding the null
1104 * terminator. For WriteUtf8: The number of bytes copied to the buffer
1105 * including the null terminator (if written).
1109 HINT_MANY_WRITES_EXPECTED = 1,
1110 NO_NULL_TERMINATION = 2
1113 V8EXPORT uint16_t GetCharacter(int index);
1115 // 16-bit character codes.
1116 V8EXPORT int Write(uint16_t* buffer,
1119 int options = NO_OPTIONS) const;
1120 // ASCII characters.
1121 V8EXPORT int WriteAscii(char* buffer,
1124 int options = NO_OPTIONS) const;
1125 // UTF-8 encoded characters.
1126 V8EXPORT int WriteUtf8(char* buffer,
1128 int* nchars_ref = NULL,
1129 int options = NO_OPTIONS) const;
1132 * A zero length string.
1134 V8EXPORT static v8::Local<v8::String> Empty();
1137 * Returns true if the string is external
1139 V8EXPORT bool IsExternal() const;
1142 * Returns true if the string is both external and ASCII
1144 V8EXPORT bool IsExternalAscii() const;
1146 class V8EXPORT ExternalStringResourceBase { // NOLINT
1148 virtual ~ExternalStringResourceBase() {}
1151 ExternalStringResourceBase() {}
1154 * Internally V8 will call this Dispose method when the external string
1155 * resource is no longer needed. The default implementation will use the
1156 * delete operator. This method can be overridden in subclasses to
1157 * control how allocated external string resources are disposed.
1159 virtual void Dispose() { delete this; }
1162 // Disallow copying and assigning.
1163 ExternalStringResourceBase(const ExternalStringResourceBase&);
1164 void operator=(const ExternalStringResourceBase&);
1166 friend class v8::internal::Heap;
1170 * An ExternalStringResource is a wrapper around a two-byte string
1171 * buffer that resides outside V8's heap. Implement an
1172 * ExternalStringResource to manage the life cycle of the underlying
1173 * buffer. Note that the string data must be immutable.
1175 class V8EXPORT ExternalStringResource
1176 : public ExternalStringResourceBase {
1179 * Override the destructor to manage the life cycle of the underlying
1182 virtual ~ExternalStringResource() {}
1185 * The string data from the underlying buffer.
1187 virtual const uint16_t* data() const = 0;
1190 * The length of the string. That is, the number of two-byte characters.
1192 virtual size_t length() const = 0;
1195 ExternalStringResource() {}
1199 * An ExternalAsciiStringResource is a wrapper around an ASCII
1200 * string buffer that resides outside V8's heap. Implement an
1201 * ExternalAsciiStringResource to manage the life cycle of the
1202 * underlying buffer. Note that the string data must be immutable
1203 * and that the data must be strict (7-bit) ASCII, not Latin-1 or
1204 * UTF-8, which would require special treatment internally in the
1205 * engine and, in the case of UTF-8, do not allow efficient indexing.
1206 * Use String::New or convert to 16 bit data for non-ASCII.
1209 class V8EXPORT ExternalAsciiStringResource
1210 : public ExternalStringResourceBase {
1213 * Override the destructor to manage the life cycle of the underlying
1216 virtual ~ExternalAsciiStringResource() {}
1217 /** The string data from the underlying buffer.*/
1218 virtual const char* data() const = 0;
1219 /** The number of ASCII characters in the string.*/
1220 virtual size_t length() const = 0;
1222 ExternalAsciiStringResource() {}
1226 * Get the ExternalStringResource for an external string. Returns
1227 * NULL if IsExternal() doesn't return true.
1229 inline ExternalStringResource* GetExternalStringResource() const;
1232 * Get the ExternalAsciiStringResource for an external ASCII string.
1233 * Returns NULL if IsExternalAscii() doesn't return true.
1235 V8EXPORT const ExternalAsciiStringResource* GetExternalAsciiStringResource()
1238 static inline String* Cast(v8::Value* obj);
1241 * Allocates a new string from either UTF-8 encoded or ASCII data.
1242 * The second parameter 'length' gives the buffer length.
1243 * If the data is UTF-8 encoded, the caller must
1244 * be careful to supply the length parameter.
1245 * If it is not given, the function calls
1246 * 'strlen' to determine the buffer length, it might be
1247 * wrong if 'data' contains a null character.
1249 V8EXPORT static Local<String> New(const char* data, int length = -1);
1251 /** Allocates a new string from 16-bit character codes.*/
1252 V8EXPORT static Local<String> New(const uint16_t* data, int length = -1);
1254 /** Creates a symbol. Returns one if it exists already.*/
1255 V8EXPORT static Local<String> NewSymbol(const char* data, int length = -1);
1258 * Creates a new string by concatenating the left and the right strings
1259 * passed in as parameters.
1261 V8EXPORT static Local<String> Concat(Handle<String> left,
1262 Handle<String>right);
1265 * Creates a new external string using the data defined in the given
1266 * resource. When the external string is no longer live on V8's heap the
1267 * resource will be disposed by calling its Dispose method. The caller of
1268 * this function should not otherwise delete or modify the resource. Neither
1269 * should the underlying buffer be deallocated or modified except through the
1270 * destructor of the external string resource.
1272 V8EXPORT static Local<String> NewExternal(ExternalStringResource* resource);
1275 * Associate an external string resource with this string by transforming it
1276 * in place so that existing references to this string in the JavaScript heap
1277 * will use the external string resource. The external string resource's
1278 * character contents need to be equivalent to this string.
1279 * Returns true if the string has been changed to be an external string.
1280 * The string is not modified if the operation fails. See NewExternal for
1281 * information on the lifetime of the resource.
1283 V8EXPORT bool MakeExternal(ExternalStringResource* resource);
1286 * Creates a new external string using the ASCII data defined in the given
1287 * resource. When the external string is no longer live on V8's heap the
1288 * resource will be disposed by calling its Dispose method. The caller of
1289 * this function should not otherwise delete or modify the resource. Neither
1290 * should the underlying buffer be deallocated or modified except through the
1291 * destructor of the external string resource.
1293 V8EXPORT static Local<String> NewExternal(
1294 ExternalAsciiStringResource* resource);
1297 * Associate an external string resource with this string by transforming it
1298 * in place so that existing references to this string in the JavaScript heap
1299 * will use the external string resource. The external string resource's
1300 * character contents need to be equivalent to this string.
1301 * Returns true if the string has been changed to be an external string.
1302 * The string is not modified if the operation fails. See NewExternal for
1303 * information on the lifetime of the resource.
1305 V8EXPORT bool MakeExternal(ExternalAsciiStringResource* resource);
1308 * Returns true if this string can be made external.
1310 V8EXPORT bool CanMakeExternal();
1312 /** Creates an undetectable string from the supplied ASCII or UTF-8 data.*/
1313 V8EXPORT static Local<String> NewUndetectable(const char* data,
1316 /** Creates an undetectable string from the supplied 16-bit character codes.*/
1317 V8EXPORT static Local<String> NewUndetectable(const uint16_t* data,
1321 * Converts an object to a UTF-8-encoded character array. Useful if
1322 * you want to print the object. If conversion to a string fails
1323 * (e.g. due to an exception in the toString() method of the object)
1324 * then the length() method returns 0 and the * operator returns
1327 class V8EXPORT Utf8Value {
1329 explicit Utf8Value(Handle<v8::Value> obj);
1331 char* operator*() { return str_; }
1332 const char* operator*() const { return str_; }
1333 int length() const { return length_; }
1338 // Disallow copying and assigning.
1339 Utf8Value(const Utf8Value&);
1340 void operator=(const Utf8Value&);
1344 * Converts an object to an ASCII string.
1345 * Useful if you want to print the object.
1346 * If conversion to a string fails (eg. due to an exception in the toString()
1347 * method of the object) then the length() method returns 0 and the * operator
1350 class V8EXPORT AsciiValue {
1352 explicit AsciiValue(Handle<v8::Value> obj);
1354 char* operator*() { return str_; }
1355 const char* operator*() const { return str_; }
1356 int length() const { return length_; }
1361 // Disallow copying and assigning.
1362 AsciiValue(const AsciiValue&);
1363 void operator=(const AsciiValue&);
1367 * Converts an object to a two-byte string.
1368 * If conversion to a string fails (eg. due to an exception in the toString()
1369 * method of the object) then the length() method returns 0 and the * operator
1372 class V8EXPORT Value {
1374 explicit Value(Handle<v8::Value> obj);
1376 uint16_t* operator*() { return str_; }
1377 const uint16_t* operator*() const { return str_; }
1378 int length() const { return length_; }
1383 // Disallow copying and assigning.
1384 Value(const Value&);
1385 void operator=(const Value&);
1389 V8EXPORT void VerifyExternalStringResource(ExternalStringResource* val) const;
1390 V8EXPORT static void CheckCast(v8::Value* obj);
1395 * A JavaScript number value (ECMA-262, 4.3.20)
1397 class Number : public Primitive {
1399 V8EXPORT double Value() const;
1400 V8EXPORT static Local<Number> New(double value);
1401 static inline Number* Cast(v8::Value* obj);
1404 V8EXPORT static void CheckCast(v8::Value* obj);
1409 * A JavaScript value representing a signed integer.
1411 class Integer : public Number {
1413 V8EXPORT static Local<Integer> New(int32_t value);
1414 V8EXPORT static Local<Integer> NewFromUnsigned(uint32_t value);
1415 V8EXPORT int64_t Value() const;
1416 static inline Integer* Cast(v8::Value* obj);
1419 V8EXPORT static void CheckCast(v8::Value* obj);
1424 * A JavaScript value representing a 32-bit signed integer.
1426 class Int32 : public Integer {
1428 V8EXPORT int32_t Value() const;
1435 * A JavaScript value representing a 32-bit unsigned integer.
1437 class Uint32 : public Integer {
1439 V8EXPORT uint32_t Value() const;
1445 enum PropertyAttribute {
1452 enum ExternalArrayType {
1453 kExternalByteArray = 1,
1454 kExternalUnsignedByteArray,
1455 kExternalShortArray,
1456 kExternalUnsignedShortArray,
1458 kExternalUnsignedIntArray,
1459 kExternalFloatArray,
1460 kExternalDoubleArray,
1465 * Accessor[Getter|Setter] are used as callback functions when
1466 * setting|getting a particular property. See Object and ObjectTemplate's
1467 * method SetAccessor.
1469 typedef Handle<Value> (*AccessorGetter)(Local<String> property,
1470 const AccessorInfo& info);
1473 typedef void (*AccessorSetter)(Local<String> property,
1475 const AccessorInfo& info);
1479 * Access control specifications.
1481 * Some accessors should be accessible across contexts. These
1482 * accessors have an explicit access control parameter which specifies
1483 * the kind of cross-context access that should be allowed.
1485 * Additionally, for security, accessors can prohibit overwriting by
1486 * accessors defined in JavaScript. For objects that have such
1487 * accessors either locally or in their prototype chain it is not
1488 * possible to overwrite the accessor by using __defineGetter__ or
1489 * __defineSetter__ from JavaScript code.
1491 enum AccessControl {
1494 ALL_CAN_WRITE = 1 << 1,
1495 PROHIBITS_OVERWRITING = 1 << 2
1500 * A JavaScript object (ECMA-262, 4.3.3)
1502 class Object : public Value {
1504 V8EXPORT bool Set(Handle<Value> key,
1505 Handle<Value> value,
1506 PropertyAttribute attribs = None);
1508 V8EXPORT bool Set(uint32_t index,
1509 Handle<Value> value);
1511 // Sets a local property on this object bypassing interceptors and
1512 // overriding accessors or read-only properties.
1514 // Note that if the object has an interceptor the property will be set
1515 // locally, but since the interceptor takes precedence the local property
1516 // will only be returned if the interceptor doesn't return a value.
1518 // Note also that this only works for named properties.
1519 V8EXPORT bool ForceSet(Handle<Value> key,
1520 Handle<Value> value,
1521 PropertyAttribute attribs = None);
1523 V8EXPORT Local<Value> Get(Handle<Value> key);
1525 V8EXPORT Local<Value> Get(uint32_t index);
1528 * Gets the property attributes of a property which can be None or
1529 * any combination of ReadOnly, DontEnum and DontDelete. Returns
1530 * None when the property doesn't exist.
1532 V8EXPORT PropertyAttribute GetPropertyAttributes(Handle<Value> key);
1534 // TODO(1245389): Replace the type-specific versions of these
1535 // functions with generic ones that accept a Handle<Value> key.
1536 V8EXPORT bool Has(Handle<String> key);
1538 V8EXPORT bool Delete(Handle<String> key);
1540 // Delete a property on this object bypassing interceptors and
1541 // ignoring dont-delete attributes.
1542 V8EXPORT bool ForceDelete(Handle<Value> key);
1544 V8EXPORT bool Has(uint32_t index);
1546 V8EXPORT bool Delete(uint32_t index);
1548 V8EXPORT bool SetAccessor(Handle<String> name,
1549 AccessorGetter getter,
1550 AccessorSetter setter = 0,
1551 Handle<Value> data = Handle<Value>(),
1552 AccessControl settings = DEFAULT,
1553 PropertyAttribute attribute = None);
1556 * Returns an array containing the names of the enumerable properties
1557 * of this object, including properties from prototype objects. The
1558 * array returned by this method contains the same values as would
1559 * be enumerated by a for-in statement over this object.
1561 V8EXPORT Local<Array> GetPropertyNames();
1564 * This function has the same functionality as GetPropertyNames but
1565 * the returned array doesn't contain the names of properties from
1566 * prototype objects.
1568 V8EXPORT Local<Array> GetOwnPropertyNames();
1571 * Get the prototype object. This does not skip objects marked to
1572 * be skipped by __proto__ and it does not consult the security
1575 V8EXPORT Local<Value> GetPrototype();
1578 * Set the prototype object. This does not skip objects marked to
1579 * be skipped by __proto__ and it does not consult the security
1582 V8EXPORT bool SetPrototype(Handle<Value> prototype);
1585 * Finds an instance of the given function template in the prototype
1588 V8EXPORT Local<Object> FindInstanceInPrototypeChain(
1589 Handle<FunctionTemplate> tmpl);
1592 * Call builtin Object.prototype.toString on this object.
1593 * This is different from Value::ToString() that may call
1594 * user-defined toString function. This one does not.
1596 V8EXPORT Local<String> ObjectProtoToString();
1599 * Returns the name of the function invoked as a constructor for this object.
1601 V8EXPORT Local<String> GetConstructorName();
1603 /** Gets the number of internal fields for this Object. */
1604 V8EXPORT int InternalFieldCount();
1605 /** Gets the value in an internal field. */
1606 inline Local<Value> GetInternalField(int index);
1607 /** Sets the value in an internal field. */
1608 V8EXPORT void SetInternalField(int index, Handle<Value> value);
1610 /** Gets a native pointer from an internal field. */
1611 inline void* GetPointerFromInternalField(int index);
1613 /** Sets a native pointer in an internal field. */
1614 V8EXPORT void SetPointerInInternalField(int index, void* value);
1616 class V8EXPORT ExternalResource { // NOLINT
1618 ExternalResource() {}
1619 virtual ~ExternalResource() {}
1622 virtual void Dispose() { delete this; }
1625 // Disallow copying and assigning.
1626 ExternalResource(const ExternalResource&);
1627 void operator=(const ExternalResource&);
1629 friend class v8::internal::Heap;
1632 V8EXPORT void SetExternalResource(ExternalResource *);
1633 V8EXPORT ExternalResource *GetExternalResource();
1635 // Testers for local properties.
1636 V8EXPORT bool HasOwnProperty(Handle<String> key);
1637 V8EXPORT bool HasRealNamedProperty(Handle<String> key);
1638 V8EXPORT bool HasRealIndexedProperty(uint32_t index);
1639 V8EXPORT bool HasRealNamedCallbackProperty(Handle<String> key);
1642 * If result.IsEmpty() no real property was located in the prototype chain.
1643 * This means interceptors in the prototype chain are not called.
1645 V8EXPORT Local<Value> GetRealNamedPropertyInPrototypeChain(
1646 Handle<String> key);
1649 * If result.IsEmpty() no real property was located on the object or
1650 * in the prototype chain.
1651 * This means interceptors in the prototype chain are not called.
1653 V8EXPORT Local<Value> GetRealNamedProperty(Handle<String> key);
1655 /** Tests for a named lookup interceptor.*/
1656 V8EXPORT bool HasNamedLookupInterceptor();
1658 /** Tests for an index lookup interceptor.*/
1659 V8EXPORT bool HasIndexedLookupInterceptor();
1662 * Turns on access check on the object if the object is an instance of
1663 * a template that has access check callbacks. If an object has no
1664 * access check info, the object cannot be accessed by anyone.
1666 V8EXPORT void TurnOnAccessCheck();
1669 * Returns the identity hash for this object. The current implementation
1670 * uses a hidden property on the object to store the identity hash.
1672 * The return value will never be 0. Also, it is not guaranteed to be
1675 V8EXPORT int GetIdentityHash();
1678 * Access hidden properties on JavaScript objects. These properties are
1679 * hidden from the executing JavaScript and only accessible through the V8
1680 * C++ API. Hidden properties introduced by V8 internally (for example the
1681 * identity hash) are prefixed with "v8::".
1683 V8EXPORT bool SetHiddenValue(Handle<String> key, Handle<Value> value);
1684 V8EXPORT Local<Value> GetHiddenValue(Handle<String> key);
1685 V8EXPORT bool DeleteHiddenValue(Handle<String> key);
1688 * Returns true if this is an instance of an api function (one
1689 * created from a function created from a function template) and has
1690 * been modified since it was created. Note that this method is
1691 * conservative and may return true for objects that haven't actually
1694 V8EXPORT bool IsDirty();
1697 * Clone this object with a fast but shallow copy. Values will point
1698 * to the same values as the original object.
1700 V8EXPORT Local<Object> Clone();
1703 * Returns the context in which the object was created.
1705 V8EXPORT Local<Context> CreationContext();
1708 * Set the backing store of the indexed properties to be managed by the
1709 * embedding layer. Access to the indexed properties will follow the rules
1710 * spelled out in CanvasPixelArray.
1711 * Note: The embedding program still owns the data and needs to ensure that
1712 * the backing store is preserved while V8 has a reference.
1714 V8EXPORT void SetIndexedPropertiesToPixelData(uint8_t* data, int length);
1715 V8EXPORT bool HasIndexedPropertiesInPixelData();
1716 V8EXPORT uint8_t* GetIndexedPropertiesPixelData();
1717 V8EXPORT int GetIndexedPropertiesPixelDataLength();
1720 * Set the backing store of the indexed properties to be managed by the
1721 * embedding layer. Access to the indexed properties will follow the rules
1722 * spelled out for the CanvasArray subtypes in the WebGL specification.
1723 * Note: The embedding program still owns the data and needs to ensure that
1724 * the backing store is preserved while V8 has a reference.
1726 V8EXPORT void SetIndexedPropertiesToExternalArrayData(
1728 ExternalArrayType array_type,
1729 int number_of_elements);
1730 V8EXPORT bool HasIndexedPropertiesInExternalArrayData();
1731 V8EXPORT void* GetIndexedPropertiesExternalArrayData();
1732 V8EXPORT ExternalArrayType GetIndexedPropertiesExternalArrayDataType();
1733 V8EXPORT int GetIndexedPropertiesExternalArrayDataLength();
1736 * Checks whether a callback is set by the
1737 * ObjectTemplate::SetCallAsFunctionHandler method.
1738 * When an Object is callable this method returns true.
1740 V8EXPORT bool IsCallable();
1743 * Call an Object as a function if a callback is set by the
1744 * ObjectTemplate::SetCallAsFunctionHandler method.
1746 V8EXPORT Local<Value> CallAsFunction(Handle<Object> recv,
1748 Handle<Value> argv[]);
1751 * Call an Object as a constructor if a callback is set by the
1752 * ObjectTemplate::SetCallAsFunctionHandler method.
1753 * Note: This method behaves like the Function::NewInstance method.
1755 V8EXPORT Local<Value> CallAsConstructor(int argc,
1756 Handle<Value> argv[]);
1758 V8EXPORT static Local<Object> New();
1759 static inline Object* Cast(Value* obj);
1763 V8EXPORT static void CheckCast(Value* obj);
1764 V8EXPORT Local<Value> CheckedGetInternalField(int index);
1765 V8EXPORT void* SlowGetPointerFromInternalField(int index);
1768 * If quick access to the internal field is possible this method
1769 * returns the value. Otherwise an empty handle is returned.
1771 inline Local<Value> UncheckedGetInternalField(int index);
1776 * An instance of the built-in array constructor (ECMA-262, 15.4.2).
1778 class Array : public Object {
1780 V8EXPORT uint32_t Length() const;
1783 * Clones an element at index |index|. Returns an empty
1784 * handle if cloning fails (for any reason).
1786 V8EXPORT Local<Object> CloneElementAt(uint32_t index);
1789 * Creates a JavaScript array with the given length. If the length
1790 * is negative the returned array will have length 0.
1792 V8EXPORT static Local<Array> New(int length = 0);
1794 static inline Array* Cast(Value* obj);
1797 V8EXPORT static void CheckCast(Value* obj);
1802 * A JavaScript function object (ECMA-262, 15.3).
1804 class Function : public Object {
1806 V8EXPORT Local<Object> NewInstance() const;
1807 V8EXPORT Local<Object> NewInstance(int argc, Handle<Value> argv[]) const;
1808 V8EXPORT Local<Value> Call(Handle<Object> recv,
1810 Handle<Value> argv[]);
1811 V8EXPORT void SetName(Handle<String> name);
1812 V8EXPORT Handle<Value> GetName() const;
1815 * Returns zero based line number of function body and
1816 * kLineOffsetNotFound if no information available.
1818 V8EXPORT int GetScriptLineNumber() const;
1819 V8EXPORT ScriptOrigin GetScriptOrigin() const;
1820 static inline Function* Cast(Value* obj);
1821 V8EXPORT static const int kLineOffsetNotFound;
1823 V8EXPORT Function();
1824 V8EXPORT static void CheckCast(Value* obj);
1829 * An instance of the built-in Date constructor (ECMA-262, 15.9).
1831 class Date : public Object {
1833 V8EXPORT static Local<Value> New(double time);
1836 * A specialization of Value::NumberValue that is more efficient
1837 * because we know the structure of this object.
1839 V8EXPORT double NumberValue() const;
1841 static inline Date* Cast(v8::Value* obj);
1844 * Notification that the embedder has changed the time zone,
1845 * daylight savings time, or other date / time configuration
1846 * parameters. V8 keeps a cache of various values used for
1847 * date / time computation. This notification will reset
1848 * those cached values for the current context so that date /
1849 * time configuration changes would be reflected in the Date
1852 * This API should not be called more than needed as it will
1853 * negatively impact the performance of date operations.
1855 V8EXPORT static void DateTimeConfigurationChangeNotification();
1858 V8EXPORT static void CheckCast(v8::Value* obj);
1863 * A Number object (ECMA-262, 4.3.21).
1865 class NumberObject : public Object {
1867 V8EXPORT static Local<Value> New(double value);
1870 * Returns the Number held by the object.
1872 V8EXPORT double NumberValue() const;
1874 static inline NumberObject* Cast(v8::Value* obj);
1877 V8EXPORT static void CheckCast(v8::Value* obj);
1882 * A Boolean object (ECMA-262, 4.3.15).
1884 class BooleanObject : public Object {
1886 V8EXPORT static Local<Value> New(bool value);
1889 * Returns the Boolean held by the object.
1891 V8EXPORT bool BooleanValue() const;
1893 static inline BooleanObject* Cast(v8::Value* obj);
1896 V8EXPORT static void CheckCast(v8::Value* obj);
1901 * A String object (ECMA-262, 4.3.18).
1903 class StringObject : public Object {
1905 V8EXPORT static Local<Value> New(Handle<String> value);
1908 * Returns the String held by the object.
1910 V8EXPORT Local<String> StringValue() const;
1912 static inline StringObject* Cast(v8::Value* obj);
1915 V8EXPORT static void CheckCast(v8::Value* obj);
1920 * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
1922 class RegExp : public Object {
1925 * Regular expression flag bits. They can be or'ed to enable a set
1936 * Creates a regular expression from the given pattern string and
1937 * the flags bit field. May throw a JavaScript exception as
1938 * described in ECMA-262, 15.10.4.1.
1941 * RegExp::New(v8::String::New("foo"),
1942 * static_cast<RegExp::Flags>(kGlobal | kMultiline))
1943 * is equivalent to evaluating "/foo/gm".
1945 V8EXPORT static Local<RegExp> New(Handle<String> pattern,
1949 * Returns the value of the source property: a string representing
1950 * the regular expression.
1952 V8EXPORT Local<String> GetSource() const;
1955 * Returns the flags bit field.
1957 V8EXPORT Flags GetFlags() const;
1959 static inline RegExp* Cast(v8::Value* obj);
1962 V8EXPORT static void CheckCast(v8::Value* obj);
1967 * A JavaScript value that wraps a C++ void*. This type of value is
1968 * mainly used to associate C++ data structures with JavaScript
1971 * The Wrap function V8 will return the most optimal Value object wrapping the
1972 * C++ void*. The type of the value is not guaranteed to be an External object
1973 * and no assumptions about its type should be made. To access the wrapped
1974 * value Unwrap should be used, all other operations on that object will lead
1975 * to unpredictable results.
1977 class External : public Value {
1979 V8EXPORT static Local<Value> Wrap(void* data);
1980 static inline void* Unwrap(Handle<Value> obj);
1982 V8EXPORT static Local<External> New(void* value);
1983 static inline External* Cast(Value* obj);
1984 V8EXPORT void* Value() const;
1986 V8EXPORT External();
1987 V8EXPORT static void CheckCast(v8::Value* obj);
1988 static inline void* QuickUnwrap(Handle<v8::Value> obj);
1989 V8EXPORT static void* FullUnwrap(Handle<v8::Value> obj);
1993 // --- Templates ---
1997 * The superclass of object and function templates.
1999 class V8EXPORT Template : public Data {
2001 /** Adds a property to each instance created by this template.*/
2002 void Set(Handle<String> name, Handle<Data> value,
2003 PropertyAttribute attributes = None);
2004 inline void Set(const char* name, Handle<Data> value);
2008 friend class ObjectTemplate;
2009 friend class FunctionTemplate;
2014 * The argument information given to function call callbacks. This
2015 * class provides access to information about the context of the call,
2016 * including the receiver, the number and values of arguments, and
2017 * the holder of the function.
2021 inline int Length() const;
2022 inline Local<Value> operator[](int i) const;
2023 inline Local<Function> Callee() const;
2024 inline Local<Object> This() const;
2025 inline Local<Object> Holder() const;
2026 inline bool IsConstructCall() const;
2027 inline Local<Value> Data() const;
2029 static const int kDataIndex = 0;
2030 static const int kCalleeIndex = -1;
2031 static const int kHolderIndex = -2;
2033 friend class ImplementationUtilities;
2034 inline Arguments(internal::Object** implicit_args,
2035 internal::Object** values,
2037 bool is_construct_call);
2038 internal::Object** implicit_args_;
2039 internal::Object** values_;
2041 bool is_construct_call_;
2046 * The information passed to an accessor callback about the context
2047 * of the property access.
2049 class V8EXPORT AccessorInfo {
2051 inline AccessorInfo(internal::Object** args)
2053 inline Local<Value> Data() const;
2054 inline Local<Object> This() const;
2055 inline Local<Object> Holder() const;
2057 internal::Object** args_;
2061 typedef Handle<Value> (*InvocationCallback)(const Arguments& args);
2064 * NamedProperty[Getter|Setter] are used as interceptors on object.
2065 * See ObjectTemplate::SetNamedPropertyHandler.
2067 typedef Handle<Value> (*NamedPropertyGetter)(Local<String> property,
2068 const AccessorInfo& info);
2072 * Returns the value if the setter intercepts the request.
2073 * Otherwise, returns an empty handle.
2075 typedef Handle<Value> (*NamedPropertySetter)(Local<String> property,
2077 const AccessorInfo& info);
2080 * Returns a non-empty handle if the interceptor intercepts the request.
2081 * The result is an integer encoding property attributes (like v8::None,
2082 * v8::DontEnum, etc.)
2084 typedef Handle<Integer> (*NamedPropertyQuery)(Local<String> property,
2085 const AccessorInfo& info);
2089 * Returns a non-empty handle if the deleter intercepts the request.
2090 * The return value is true if the property could be deleted and false
2093 typedef Handle<Boolean> (*NamedPropertyDeleter)(Local<String> property,
2094 const AccessorInfo& info);
2097 * Returns an array containing the names of the properties the named
2098 * property getter intercepts.
2100 typedef Handle<Array> (*NamedPropertyEnumerator)(const AccessorInfo& info);
2104 * Returns the value of the property if the getter intercepts the
2105 * request. Otherwise, returns an empty handle.
2107 typedef Handle<Value> (*IndexedPropertyGetter)(uint32_t index,
2108 const AccessorInfo& info);
2112 * Returns the value if the setter intercepts the request.
2113 * Otherwise, returns an empty handle.
2115 typedef Handle<Value> (*IndexedPropertySetter)(uint32_t index,
2117 const AccessorInfo& info);
2121 * Returns a non-empty handle if the interceptor intercepts the request.
2122 * The result is an integer encoding property attributes.
2124 typedef Handle<Integer> (*IndexedPropertyQuery)(uint32_t index,
2125 const AccessorInfo& info);
2128 * Returns a non-empty handle if the deleter intercepts the request.
2129 * The return value is true if the property could be deleted and false
2132 typedef Handle<Boolean> (*IndexedPropertyDeleter)(uint32_t index,
2133 const AccessorInfo& info);
2136 * Returns an array containing the indices of the properties the
2137 * indexed property getter intercepts.
2139 typedef Handle<Array> (*IndexedPropertyEnumerator)(const AccessorInfo& info);
2143 * Access type specification.
2155 * Returns true if cross-context access should be allowed to the named
2156 * property with the given key on the host object.
2158 typedef bool (*NamedSecurityCallback)(Local<Object> host,
2165 * Returns true if cross-context access should be allowed to the indexed
2166 * property with the given index on the host object.
2168 typedef bool (*IndexedSecurityCallback)(Local<Object> host,
2175 * A FunctionTemplate is used to create functions at runtime. There
2176 * can only be one function created from a FunctionTemplate in a
2177 * context. The lifetime of the created function is equal to the
2178 * lifetime of the context. So in case the embedder needs to create
2179 * temporary functions that can be collected using Scripts is
2182 * A FunctionTemplate can have properties, these properties are added to the
2183 * function object when it is created.
2185 * A FunctionTemplate has a corresponding instance template which is
2186 * used to create object instances when the function is used as a
2187 * constructor. Properties added to the instance template are added to
2188 * each object instance.
2190 * A FunctionTemplate can have a prototype template. The prototype template
2191 * is used to create the prototype object of the function.
2193 * The following example shows how to use a FunctionTemplate:
2196 * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
2197 * t->Set("func_property", v8::Number::New(1));
2199 * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
2200 * proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
2201 * proto_t->Set("proto_const", v8::Number::New(2));
2203 * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
2204 * instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
2205 * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
2206 * instance_t->Set("instance_property", Number::New(3));
2208 * v8::Local<v8::Function> function = t->GetFunction();
2209 * v8::Local<v8::Object> instance = function->NewInstance();
2212 * Let's use "function" as the JS variable name of the function object
2213 * and "instance" for the instance object created above. The function
2214 * and the instance will have the following properties:
2217 * func_property in function == true;
2218 * function.func_property == 1;
2220 * function.prototype.proto_method() invokes 'InvokeCallback'
2221 * function.prototype.proto_const == 2;
2223 * instance instanceof function == true;
2224 * instance.instance_accessor calls 'InstanceAccessorCallback'
2225 * instance.instance_property == 3;
2228 * A FunctionTemplate can inherit from another one by calling the
2229 * FunctionTemplate::Inherit method. The following graph illustrates
2230 * the semantics of inheritance:
2233 * FunctionTemplate Parent -> Parent() . prototype -> { }
2235 * | Inherit(Parent) | .__proto__
2237 * FunctionTemplate Child -> Child() . prototype -> { }
2240 * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
2241 * object of the Child() function has __proto__ pointing to the
2242 * Parent() function's prototype object. An instance of the Child
2243 * function has all properties on Parent's instance templates.
2245 * Let Parent be the FunctionTemplate initialized in the previous
2246 * section and create a Child FunctionTemplate by:
2249 * Local<FunctionTemplate> parent = t;
2250 * Local<FunctionTemplate> child = FunctionTemplate::New();
2251 * child->Inherit(parent);
2253 * Local<Function> child_function = child->GetFunction();
2254 * Local<Object> child_instance = child_function->NewInstance();
2257 * The Child function and Child instance will have the following
2261 * child_func.prototype.__proto__ == function.prototype;
2262 * child_instance.instance_accessor calls 'InstanceAccessorCallback'
2263 * child_instance.instance_property == 3;
2266 class V8EXPORT FunctionTemplate : public Template {
2268 /** Creates a function template.*/
2269 static Local<FunctionTemplate> New(
2270 InvocationCallback callback = 0,
2271 Handle<Value> data = Handle<Value>(),
2272 Handle<Signature> signature = Handle<Signature>());
2273 /** Returns the unique function instance in the current execution context.*/
2274 Local<Function> GetFunction();
2277 * Set the call-handler callback for a FunctionTemplate. This
2278 * callback is called whenever the function created from this
2279 * FunctionTemplate is called.
2281 void SetCallHandler(InvocationCallback callback,
2282 Handle<Value> data = Handle<Value>());
2284 /** Get the InstanceTemplate. */
2285 Local<ObjectTemplate> InstanceTemplate();
2287 /** Causes the function template to inherit from a parent function template.*/
2288 void Inherit(Handle<FunctionTemplate> parent);
2291 * A PrototypeTemplate is the template used to create the prototype object
2292 * of the function created by this template.
2294 Local<ObjectTemplate> PrototypeTemplate();
2298 * Set the class name of the FunctionTemplate. This is used for
2299 * printing objects created with the function created from the
2300 * FunctionTemplate as its constructor.
2302 void SetClassName(Handle<String> name);
2305 * Determines whether the __proto__ accessor ignores instances of
2306 * the function template. If instances of the function template are
2307 * ignored, __proto__ skips all instances and instead returns the
2308 * next object in the prototype chain.
2310 * Call with a value of true to make the __proto__ accessor ignore
2311 * instances of the function template. Call with a value of false
2312 * to make the __proto__ accessor not ignore instances of the
2313 * function template. By default, instances of a function template
2316 void SetHiddenPrototype(bool value);
2319 * Sets the ReadOnly flag in the attributes of the 'prototype' property
2320 * of functions created from this FunctionTemplate to true.
2322 void ReadOnlyPrototype();
2325 * Returns true if the given object is an instance of this function
2328 bool HasInstance(Handle<Value> object);
2332 void AddInstancePropertyAccessor(Handle<String> name,
2333 AccessorGetter getter,
2334 AccessorSetter setter,
2336 AccessControl settings,
2337 PropertyAttribute attributes);
2338 void SetNamedInstancePropertyHandler(NamedPropertyGetter getter,
2339 NamedPropertySetter setter,
2340 NamedPropertyQuery query,
2341 NamedPropertyDeleter remover,
2342 NamedPropertyEnumerator enumerator,
2344 Handle<Value> data);
2345 void SetIndexedInstancePropertyHandler(IndexedPropertyGetter getter,
2346 IndexedPropertySetter setter,
2347 IndexedPropertyQuery query,
2348 IndexedPropertyDeleter remover,
2349 IndexedPropertyEnumerator enumerator,
2350 Handle<Value> data);
2351 void SetInstanceCallAsFunctionHandler(InvocationCallback callback,
2352 Handle<Value> data);
2354 friend class Context;
2355 friend class ObjectTemplate;
2360 * An ObjectTemplate is used to create objects at runtime.
2362 * Properties added to an ObjectTemplate are added to each object
2363 * created from the ObjectTemplate.
2365 class V8EXPORT ObjectTemplate : public Template {
2367 /** Creates an ObjectTemplate. */
2368 static Local<ObjectTemplate> New();
2370 /** Creates a new instance of this template.*/
2371 Local<Object> NewInstance();
2374 * Sets an accessor on the object template.
2376 * Whenever the property with the given name is accessed on objects
2377 * created from this ObjectTemplate the getter and setter callbacks
2378 * are called instead of getting and setting the property directly
2379 * on the JavaScript object.
2381 * \param name The name of the property for which an accessor is added.
2382 * \param getter The callback to invoke when getting the property.
2383 * \param setter The callback to invoke when setting the property.
2384 * \param data A piece of data that will be passed to the getter and setter
2385 * callbacks whenever they are invoked.
2386 * \param settings Access control settings for the accessor. This is a bit
2387 * field consisting of one of more of
2388 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
2389 * The default is to not allow cross-context access.
2390 * ALL_CAN_READ means that all cross-context reads are allowed.
2391 * ALL_CAN_WRITE means that all cross-context writes are allowed.
2392 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
2393 * cross-context access.
2394 * \param attribute The attributes of the property for which an accessor
2397 void SetAccessor(Handle<String> name,
2398 AccessorGetter getter,
2399 AccessorSetter setter = 0,
2400 Handle<Value> data = Handle<Value>(),
2401 AccessControl settings = DEFAULT,
2402 PropertyAttribute attribute = None);
2405 * Sets a named property handler on the object template.
2407 * Whenever a named property is accessed on objects created from
2408 * this object template, the provided callback is invoked instead of
2409 * accessing the property directly on the JavaScript object.
2411 * \param getter The callback to invoke when getting a property.
2412 * \param setter The callback to invoke when setting a property.
2413 * \param query The callback to invoke to check if a property is present,
2414 * and if present, get its attributes.
2415 * \param deleter The callback to invoke when deleting a property.
2416 * \param enumerator The callback to invoke to enumerate all the named
2417 * properties of an object.
2418 * \param data A piece of data that will be passed to the callbacks
2419 * whenever they are invoked.
2421 void SetNamedPropertyHandler(NamedPropertyGetter getter,
2422 NamedPropertySetter setter = 0,
2423 NamedPropertyQuery query = 0,
2424 NamedPropertyDeleter deleter = 0,
2425 NamedPropertyEnumerator enumerator = 0,
2426 Handle<Value> data = Handle<Value>());
2427 void SetFallbackPropertyHandler(NamedPropertyGetter getter,
2428 NamedPropertySetter setter = 0,
2429 NamedPropertyQuery query = 0,
2430 NamedPropertyDeleter deleter = 0,
2431 NamedPropertyEnumerator enumerator = 0,
2432 Handle<Value> data = Handle<Value>());
2435 * Sets an indexed property handler on the object template.
2437 * Whenever an indexed property is accessed on objects created from
2438 * this object template, the provided callback is invoked instead of
2439 * accessing the property directly on the JavaScript object.
2441 * \param getter The callback to invoke when getting a property.
2442 * \param setter The callback to invoke when setting a property.
2443 * \param query The callback to invoke to check if an object has a property.
2444 * \param deleter The callback to invoke when deleting a property.
2445 * \param enumerator The callback to invoke to enumerate all the indexed
2446 * properties of an object.
2447 * \param data A piece of data that will be passed to the callbacks
2448 * whenever they are invoked.
2450 void SetIndexedPropertyHandler(IndexedPropertyGetter getter,
2451 IndexedPropertySetter setter = 0,
2452 IndexedPropertyQuery query = 0,
2453 IndexedPropertyDeleter deleter = 0,
2454 IndexedPropertyEnumerator enumerator = 0,
2455 Handle<Value> data = Handle<Value>());
2458 * Sets the callback to be used when calling instances created from
2459 * this template as a function. If no callback is set, instances
2460 * behave like normal JavaScript objects that cannot be called as a
2463 void SetCallAsFunctionHandler(InvocationCallback callback,
2464 Handle<Value> data = Handle<Value>());
2467 * Mark object instances of the template as undetectable.
2469 * In many ways, undetectable objects behave as though they are not
2470 * there. They behave like 'undefined' in conditionals and when
2471 * printed. However, properties can be accessed and called as on
2474 void MarkAsUndetectable();
2477 * Sets access check callbacks on the object template.
2479 * When accessing properties on instances of this object template,
2480 * the access check callback will be called to determine whether or
2481 * not to allow cross-context access to the properties.
2482 * The last parameter specifies whether access checks are turned
2483 * on by default on instances. If access checks are off by default,
2484 * they can be turned on on individual instances by calling
2485 * Object::TurnOnAccessCheck().
2487 void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
2488 IndexedSecurityCallback indexed_handler,
2489 Handle<Value> data = Handle<Value>(),
2490 bool turned_on_by_default = true);
2493 * Gets the number of internal fields for objects generated from
2496 int InternalFieldCount();
2499 * Sets the number of internal fields for objects generated from
2502 void SetInternalFieldCount(int value);
2505 * Sets whether the object can store an "external resource" object.
2507 bool HasExternalResource();
2508 void SetHasExternalResource(bool value);
2511 * Mark object instances of the template as using the user object
2512 * comparison callback.
2514 void MarkAsUseUserObjectComparison();
2518 static Local<ObjectTemplate> New(Handle<FunctionTemplate> constructor);
2519 friend class FunctionTemplate;
2524 * A Signature specifies which receivers and arguments a function can
2525 * legally be called with.
2527 class V8EXPORT Signature : public Data {
2529 static Local<Signature> New(Handle<FunctionTemplate> receiver =
2530 Handle<FunctionTemplate>(),
2532 Handle<FunctionTemplate> argv[] = 0);
2539 * A utility for determining the type of objects based on the template
2540 * they were constructed from.
2542 class V8EXPORT TypeSwitch : public Data {
2544 static Local<TypeSwitch> New(Handle<FunctionTemplate> type);
2545 static Local<TypeSwitch> New(int argc, Handle<FunctionTemplate> types[]);
2546 int match(Handle<Value> value);
2552 // --- Extensions ---
2554 class V8EXPORT ExternalAsciiStringResourceImpl
2555 : public String::ExternalAsciiStringResource {
2557 ExternalAsciiStringResourceImpl() : data_(0), length_(0) {}
2558 ExternalAsciiStringResourceImpl(const char* data, size_t length)
2559 : data_(data), length_(length) {}
2560 const char* data() const { return data_; }
2561 size_t length() const { return length_; }
2571 class V8EXPORT Extension { // NOLINT
2573 // Note that the strings passed into this constructor must live as long
2574 // as the Extension itself.
2575 Extension(const char* name,
2576 const char* source = 0,
2578 const char** deps = 0,
2579 int source_length = -1);
2580 virtual ~Extension() { }
2581 virtual v8::Handle<v8::FunctionTemplate>
2582 GetNativeFunction(v8::Handle<v8::String>) {
2583 return v8::Handle<v8::FunctionTemplate>();
2586 const char* name() const { return name_; }
2587 size_t source_length() const { return source_length_; }
2588 const String::ExternalAsciiStringResource* source() const {
2590 int dependency_count() { return dep_count_; }
2591 const char** dependencies() { return deps_; }
2592 void set_auto_enable(bool value) { auto_enable_ = value; }
2593 bool auto_enable() { return auto_enable_; }
2597 size_t source_length_; // expected to initialize before source_
2598 ExternalAsciiStringResourceImpl source_;
2603 // Disallow copying and assigning.
2604 Extension(const Extension&);
2605 void operator=(const Extension&);
2609 void V8EXPORT RegisterExtension(Extension* extension);
2615 class V8EXPORT DeclareExtension {
2617 inline DeclareExtension(Extension* extension) {
2618 RegisterExtension(extension);
2626 Handle<Primitive> V8EXPORT Undefined();
2627 Handle<Primitive> V8EXPORT Null();
2628 Handle<Boolean> V8EXPORT True();
2629 Handle<Boolean> V8EXPORT False();
2633 * A set of constraints that specifies the limits of the runtime's memory use.
2634 * You must set the heap size before initializing the VM - the size cannot be
2635 * adjusted after the VM is initialized.
2637 * If you are using threads then you should hold the V8::Locker lock while
2638 * setting the stack limit and you must set a non-default stack limit separately
2641 class V8EXPORT ResourceConstraints {
2643 ResourceConstraints();
2644 int max_young_space_size() const { return max_young_space_size_; }
2645 void set_max_young_space_size(int value) { max_young_space_size_ = value; }
2646 int max_old_space_size() const { return max_old_space_size_; }
2647 void set_max_old_space_size(int value) { max_old_space_size_ = value; }
2648 int max_executable_size() { return max_executable_size_; }
2649 void set_max_executable_size(int value) { max_executable_size_ = value; }
2650 uint32_t* stack_limit() const { return stack_limit_; }
2651 // Sets an address beyond which the VM's stack may not grow.
2652 void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
2654 int max_young_space_size_;
2655 int max_old_space_size_;
2656 int max_executable_size_;
2657 uint32_t* stack_limit_;
2661 bool V8EXPORT SetResourceConstraints(ResourceConstraints* constraints);
2664 // --- Exceptions ---
2667 typedef void (*FatalErrorCallback)(const char* location, const char* message);
2670 typedef void (*MessageCallback)(Handle<Message> message, Handle<Value> data);
2674 * Schedules an exception to be thrown when returning to JavaScript. When an
2675 * exception has been scheduled it is illegal to invoke any JavaScript
2676 * operation; the caller must return immediately and only after the exception
2677 * has been handled does it become legal to invoke JavaScript operations.
2679 Handle<Value> V8EXPORT ThrowException(Handle<Value> exception);
2682 * Create new error objects by calling the corresponding error object
2683 * constructor with the message.
2685 class V8EXPORT Exception {
2687 static Local<Value> RangeError(Handle<String> message);
2688 static Local<Value> ReferenceError(Handle<String> message);
2689 static Local<Value> SyntaxError(Handle<String> message);
2690 static Local<Value> TypeError(Handle<String> message);
2691 static Local<Value> Error(Handle<String> message);
2695 // --- Counters Callbacks ---
2697 typedef int* (*CounterLookupCallback)(const char* name);
2699 typedef void* (*CreateHistogramCallback)(const char* name,
2704 typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
2706 // --- Memory Allocation Callback ---
2708 kObjectSpaceNewSpace = 1 << 0,
2709 kObjectSpaceOldPointerSpace = 1 << 1,
2710 kObjectSpaceOldDataSpace = 1 << 2,
2711 kObjectSpaceCodeSpace = 1 << 3,
2712 kObjectSpaceMapSpace = 1 << 4,
2713 kObjectSpaceLoSpace = 1 << 5,
2715 kObjectSpaceAll = kObjectSpaceNewSpace | kObjectSpaceOldPointerSpace |
2716 kObjectSpaceOldDataSpace | kObjectSpaceCodeSpace | kObjectSpaceMapSpace |
2720 enum AllocationAction {
2721 kAllocationActionAllocate = 1 << 0,
2722 kAllocationActionFree = 1 << 1,
2723 kAllocationActionAll = kAllocationActionAllocate | kAllocationActionFree
2726 typedef void (*MemoryAllocationCallback)(ObjectSpace space,
2727 AllocationAction action,
2730 // --- Failed Access Check Callback ---
2731 typedef void (*FailedAccessCheckCallback)(Local<Object> target,
2735 // --- User Object Comparisoa nCallback ---
2736 typedef bool (*UserObjectComparisonCallback)(Local<Object> lhs,
2739 // --- AllowCodeGenerationFromStrings callbacks ---
2742 * Callback to check if code generation from strings is allowed. See
2743 * Context::AllowCodeGenerationFromStrings.
2745 typedef bool (*AllowCodeGenerationFromStringsCallback)(Local<Context> context);
2747 // --- Garbage Collection Callbacks ---
2750 * Applications can register callback functions which will be called
2751 * before and after a garbage collection. Allocations are not
2752 * allowed in the callback functions, you therefore cannot manipulate
2753 * objects (set or delete properties for example) since it is possible
2754 * such operations will result in the allocation of objects.
2757 kGCTypeScavenge = 1 << 0,
2758 kGCTypeMarkSweepCompact = 1 << 1,
2759 kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact
2762 enum GCCallbackFlags {
2763 kNoGCCallbackFlags = 0,
2764 kGCCallbackFlagCompacted = 1 << 0
2767 typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
2768 typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
2770 typedef void (*GCCallback)();
2774 * Collection of V8 heap information.
2776 * Instances of this class can be passed to v8::V8::HeapStatistics to
2777 * get heap statistics from V8.
2779 class V8EXPORT HeapStatistics {
2782 size_t total_heap_size() { return total_heap_size_; }
2783 size_t total_heap_size_executable() { return total_heap_size_executable_; }
2784 size_t used_heap_size() { return used_heap_size_; }
2785 size_t heap_size_limit() { return heap_size_limit_; }
2788 void set_total_heap_size(size_t size) { total_heap_size_ = size; }
2789 void set_total_heap_size_executable(size_t size) {
2790 total_heap_size_executable_ = size;
2792 void set_used_heap_size(size_t size) { used_heap_size_ = size; }
2793 void set_heap_size_limit(size_t size) { heap_size_limit_ = size; }
2795 size_t total_heap_size_;
2796 size_t total_heap_size_executable_;
2797 size_t used_heap_size_;
2798 size_t heap_size_limit_;
2804 class RetainedObjectInfo;
2807 * Isolate represents an isolated instance of the V8 engine. V8
2808 * isolates have completely separate states. Objects from one isolate
2809 * must not be used in other isolates. When V8 is initialized a
2810 * default isolate is implicitly created and entered. The embedder
2811 * can create additional isolates and use them in parallel in multiple
2812 * threads. An isolate can be entered by at most one thread at any
2813 * given time. The Locker/Unlocker API can be used to synchronize.
2815 class V8EXPORT Isolate {
2818 * Stack-allocated class which sets the isolate for all operations
2819 * executed within a local scope.
2821 class V8EXPORT Scope {
2823 explicit Scope(Isolate* isolate) : isolate_(isolate) {
2827 ~Scope() { isolate_->Exit(); }
2830 Isolate* const isolate_;
2832 // Prevent copying of Scope objects.
2833 Scope(const Scope&);
2834 Scope& operator=(const Scope&);
2838 * Creates a new isolate. Does not change the currently entered
2841 * When an isolate is no longer used its resources should be freed
2842 * by calling Dispose(). Using the delete operator is not allowed.
2844 static Isolate* New();
2847 * Returns the entered isolate for the current thread or NULL in
2848 * case there is no current isolate.
2850 static Isolate* GetCurrent();
2853 * Methods below this point require holding a lock (using Locker) in
2854 * a multi-threaded environment.
2858 * Sets this isolate as the entered one for the current thread.
2859 * Saves the previously entered one (if any), so that it can be
2860 * restored when exiting. Re-entering an isolate is allowed.
2865 * Exits this isolate by restoring the previously entered one in the
2866 * current thread. The isolate may still stay the same, if it was
2867 * entered more than once.
2869 * Requires: this == Isolate::GetCurrent().
2874 * Disposes the isolate. The isolate must not be entered by any
2875 * thread to be disposable.
2880 * Associate embedder-specific data with the isolate
2882 void SetData(void* data);
2885 * Retrive embedder-specific data from the isolate.
2886 * Returns NULL if SetData has never been called.
2892 Isolate(const Isolate&);
2894 Isolate& operator=(const Isolate&);
2895 void* operator new(size_t size);
2896 void operator delete(void*, size_t);
2902 enum CompressionAlgorithm {
2908 int compressed_size;
2914 * A helper class for driving V8 startup data decompression. It is based on
2915 * "CompressedStartupData" API functions from the V8 class. It isn't mandatory
2916 * for an embedder to use this class, instead, API functions can be used
2919 * For an example of the class usage, see the "shell.cc" sample application.
2921 class V8EXPORT StartupDataDecompressor { // NOLINT
2923 StartupDataDecompressor();
2924 virtual ~StartupDataDecompressor();
2928 virtual int DecompressData(char* raw_data,
2930 const char* compressed_data,
2931 int compressed_data_size) = 0;
2939 * EntropySource is used as a callback function when v8 needs a source
2942 typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
2945 * Container class for static utility functions.
2949 /** Set the callback to invoke in case of fatal errors. */
2950 static void SetFatalErrorHandler(FatalErrorCallback that);
2953 * Set the callback to invoke to check if code generation from
2954 * strings should be allowed.
2956 static void SetAllowCodeGenerationFromStringsCallback(
2957 AllowCodeGenerationFromStringsCallback that);
2960 * Ignore out-of-memory exceptions.
2962 * V8 running out of memory is treated as a fatal error by default.
2963 * This means that the fatal error handler is called and that V8 is
2966 * IgnoreOutOfMemoryException can be used to not treat an
2967 * out-of-memory situation as a fatal error. This way, the contexts
2968 * that did not cause the out of memory problem might be able to
2969 * continue execution.
2971 static void IgnoreOutOfMemoryException();
2974 * Check if V8 is dead and therefore unusable. This is the case after
2975 * fatal errors such as out-of-memory situations.
2977 static bool IsDead();
2980 * The following 4 functions are to be used when V8 is built with
2981 * the 'compress_startup_data' flag enabled. In this case, the
2982 * embedder must decompress startup data prior to initializing V8.
2984 * This is how interaction with V8 should look like:
2985 * int compressed_data_count = v8::V8::GetCompressedStartupDataCount();
2986 * v8::StartupData* compressed_data =
2987 * new v8::StartupData[compressed_data_count];
2988 * v8::V8::GetCompressedStartupData(compressed_data);
2989 * ... decompress data (compressed_data can be updated in-place) ...
2990 * v8::V8::SetDecompressedStartupData(compressed_data);
2991 * ... now V8 can be initialized
2992 * ... make sure the decompressed data stays valid until V8 shutdown
2994 * A helper class StartupDataDecompressor is provided. It implements
2995 * the protocol of the interaction described above, and can be used in
2996 * most cases instead of calling these API functions directly.
2998 static StartupData::CompressionAlgorithm GetCompressedStartupDataAlgorithm();
2999 static int GetCompressedStartupDataCount();
3000 static void GetCompressedStartupData(StartupData* compressed_data);
3001 static void SetDecompressedStartupData(StartupData* decompressed_data);
3004 * Adds a message listener.
3006 * The same message listener can be added more than once and in that
3007 * case it will be called more than once for each message.
3009 static bool AddMessageListener(MessageCallback that,
3010 Handle<Value> data = Handle<Value>());
3013 * Remove all message listeners from the specified callback function.
3015 static void RemoveMessageListeners(MessageCallback that);
3018 * Tells V8 to capture current stack trace when uncaught exception occurs
3019 * and report it to the message listeners. The option is off by default.
3021 static void SetCaptureStackTraceForUncaughtExceptions(
3023 int frame_limit = 10,
3024 StackTrace::StackTraceOptions options = StackTrace::kOverview);
3027 * Sets V8 flags from a string.
3029 static void SetFlagsFromString(const char* str, int length);
3032 * Sets V8 flags from the command line.
3034 static void SetFlagsFromCommandLine(int* argc,
3038 /** Get the version string. */
3039 static const char* GetVersion();
3042 * Enables the host application to provide a mechanism for recording
3043 * statistics counters.
3045 static void SetCounterFunction(CounterLookupCallback);
3048 * Enables the host application to provide a mechanism for recording
3049 * histograms. The CreateHistogram function returns a
3050 * histogram which will later be passed to the AddHistogramSample
3053 static void SetCreateHistogramFunction(CreateHistogramCallback);
3054 static void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
3057 * Enables the computation of a sliding window of states. The sliding
3058 * window information is recorded in statistics counters.
3060 static void EnableSlidingStateWindow();
3062 /** Callback function for reporting failed access checks.*/
3063 static void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
3065 /** Callback for user object comparisons */
3066 static void SetUserObjectComparisonCallbackFunction(UserObjectComparisonCallback);
3069 * Enables the host application to receive a notification before a
3070 * garbage collection. Allocations are not allowed in the
3071 * callback function, you therefore cannot manipulate objects (set
3072 * or delete properties for example) since it is possible such
3073 * operations will result in the allocation of objects. It is possible
3074 * to specify the GCType filter for your callback. But it is not possible to
3075 * register the same callback function two times with different
3078 static void AddGCPrologueCallback(
3079 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
3082 * This function removes callback which was installed by
3083 * AddGCPrologueCallback function.
3085 static void RemoveGCPrologueCallback(GCPrologueCallback callback);
3088 * The function is deprecated. Please use AddGCPrologueCallback instead.
3089 * Enables the host application to receive a notification before a
3090 * garbage collection. Allocations are not allowed in the
3091 * callback function, you therefore cannot manipulate objects (set
3092 * or delete properties for example) since it is possible such
3093 * operations will result in the allocation of objects.
3095 static void SetGlobalGCPrologueCallback(GCCallback);
3098 * Enables the host application to receive a notification after a
3099 * garbage collection. Allocations are not allowed in the
3100 * callback function, you therefore cannot manipulate objects (set
3101 * or delete properties for example) since it is possible such
3102 * operations will result in the allocation of objects. It is possible
3103 * to specify the GCType filter for your callback. But it is not possible to
3104 * register the same callback function two times with different
3107 static void AddGCEpilogueCallback(
3108 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
3111 * This function removes callback which was installed by
3112 * AddGCEpilogueCallback function.
3114 static void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
3117 * The function is deprecated. Please use AddGCEpilogueCallback instead.
3118 * Enables the host application to receive a notification after a
3119 * major garbage collection. Allocations are not allowed in the
3120 * callback function, you therefore cannot manipulate objects (set
3121 * or delete properties for example) since it is possible such
3122 * operations will result in the allocation of objects.
3124 static void SetGlobalGCEpilogueCallback(GCCallback);
3127 * Enables the host application to provide a mechanism to be notified
3128 * and perform custom logging when V8 Allocates Executable Memory.
3130 static void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
3132 AllocationAction action);
3135 * This function removes callback which was installed by
3136 * AddMemoryAllocationCallback function.
3138 static void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
3141 * Allows the host application to group objects together. If one
3142 * object in the group is alive, all objects in the group are alive.
3143 * After each garbage collection, object groups are removed. It is
3144 * intended to be used in the before-garbage-collection callback
3145 * function, for instance to simulate DOM tree connections among JS
3147 * See v8-profiler.h for RetainedObjectInfo interface description.
3149 static void AddObjectGroup(Persistent<Value>* objects,
3151 RetainedObjectInfo* info = NULL);
3154 * Allows the host application to declare implicit references between
3155 * the objects: if |parent| is alive, all |children| are alive too.
3156 * After each garbage collection, all implicit references
3157 * are removed. It is intended to be used in the before-garbage-collection
3158 * callback function.
3160 static void AddImplicitReferences(Persistent<Object> parent,
3161 Persistent<Value>* children,
3165 * Initializes from snapshot if possible. Otherwise, attempts to
3166 * initialize from scratch. This function is called implicitly if
3167 * you use the API without calling it first.
3169 static bool Initialize();
3172 * Allows the host application to provide a callback which can be used
3173 * as a source of entropy for random number generators.
3175 static void SetEntropySource(EntropySource source);
3178 * Adjusts the amount of registered external memory. Used to give
3179 * V8 an indication of the amount of externally allocated memory
3180 * that is kept alive by JavaScript objects. V8 uses this to decide
3181 * when to perform global garbage collections. Registering
3182 * externally allocated memory will trigger global garbage
3183 * collections more often than otherwise in an attempt to garbage
3184 * collect the JavaScript objects keeping the externally allocated
3187 * \param change_in_bytes the change in externally allocated memory
3188 * that is kept alive by JavaScript objects.
3189 * \returns the adjusted value.
3191 static int AdjustAmountOfExternalAllocatedMemory(int change_in_bytes);
3194 * Suspends recording of tick samples in the profiler.
3195 * When the V8 profiling mode is enabled (usually via command line
3196 * switches) this function suspends recording of tick samples.
3197 * Profiling ticks are discarded until ResumeProfiler() is called.
3199 * See also the --prof and --prof_auto command line switches to
3200 * enable V8 profiling.
3202 static void PauseProfiler();
3205 * Resumes recording of tick samples in the profiler.
3206 * See also PauseProfiler().
3208 static void ResumeProfiler();
3211 * Return whether profiler is currently paused.
3213 static bool IsProfilerPaused();
3216 * Retrieve the V8 thread id of the calling thread.
3218 * The thread id for a thread should only be retrieved after the V8
3219 * lock has been acquired with a Locker object with that thread.
3221 static int GetCurrentThreadId();
3224 * Forcefully terminate execution of a JavaScript thread. This can
3225 * be used to terminate long-running scripts.
3227 * TerminateExecution should only be called when then V8 lock has
3228 * been acquired with a Locker object. Therefore, in order to be
3229 * able to terminate long-running threads, preemption must be
3230 * enabled to allow the user of TerminateExecution to acquire the
3233 * The termination is achieved by throwing an exception that is
3234 * uncatchable by JavaScript exception handlers. Termination
3235 * exceptions act as if they were caught by a C++ TryCatch exception
3236 * handler. If forceful termination is used, any C++ TryCatch
3237 * exception handler that catches an exception should check if that
3238 * exception is a termination exception and immediately return if
3239 * that is the case. Returning immediately in that case will
3240 * continue the propagation of the termination exception if needed.
3242 * The thread id passed to TerminateExecution must have been
3243 * obtained by calling GetCurrentThreadId on the thread in question.
3245 * \param thread_id The thread id of the thread to terminate.
3247 static void TerminateExecution(int thread_id);
3250 * Forcefully terminate the current thread of JavaScript execution
3251 * in the given isolate. If no isolate is provided, the default
3254 * This method can be used by any thread even if that thread has not
3255 * acquired the V8 lock with a Locker object.
3257 * \param isolate The isolate in which to terminate the current JS execution.
3259 static void TerminateExecution(Isolate* isolate = NULL);
3262 * Is V8 terminating JavaScript execution.
3264 * Returns true if JavaScript execution is currently terminating
3265 * because of a call to TerminateExecution. In that case there are
3266 * still JavaScript frames on the stack and the termination
3267 * exception is still active.
3269 * \param isolate The isolate in which to check.
3271 static bool IsExecutionTerminating(Isolate* isolate = NULL);
3274 * Releases any resources used by v8 and stops any utility threads
3275 * that may be running. Note that disposing v8 is permanent, it
3276 * cannot be reinitialized.
3278 * It should generally not be necessary to dispose v8 before exiting
3279 * a process, this should happen automatically. It is only necessary
3280 * to use if the process needs the resources taken up by v8.
3282 static bool Dispose();
3285 * Get statistics about the heap memory usage.
3287 static void GetHeapStatistics(HeapStatistics* heap_statistics);
3290 * Optional notification that the embedder is idle.
3291 * V8 uses the notification to reduce memory footprint.
3292 * This call can be used repeatedly if the embedder remains idle.
3293 * Returns true if the embedder should stop calling IdleNotification
3294 * until real work has been done. This indicates that V8 has done
3295 * as much cleanup as it will be able to do.
3297 static bool IdleNotification();
3300 * Optional notification that the system is running low on memory.
3301 * V8 uses these notifications to attempt to free memory.
3303 static void LowMemoryNotification();
3306 * Optional notification that a context has been disposed. V8 uses
3307 * these notifications to guide the GC heuristic. Returns the number
3308 * of context disposals - including this one - since the last time
3309 * V8 had a chance to clean up.
3311 static int ContextDisposedNotification();
3316 static internal::Object** GlobalizeReference(internal::Object** handle);
3317 static void DisposeGlobal(internal::Object** global_handle);
3318 static void MakeWeak(internal::Object** global_handle,
3320 WeakReferenceCallback);
3321 static void ClearWeak(internal::Object** global_handle);
3322 static void MarkIndependent(internal::Object** global_handle);
3323 static bool IsGlobalNearDeath(internal::Object** global_handle);
3324 static bool IsGlobalWeak(internal::Object** global_handle);
3325 static void SetWrapperClassId(internal::Object** global_handle,
3328 template <class T> friend class Handle;
3329 template <class T> friend class Local;
3330 template <class T> friend class Persistent;
3331 friend class Context;
3336 * An external exception handler.
3338 class V8EXPORT TryCatch {
3341 * Creates a new try/catch block and registers it with v8.
3346 * Unregisters and deletes this try/catch block.
3351 * Returns true if an exception has been caught by this try/catch block.
3353 bool HasCaught() const;
3356 * For certain types of exceptions, it makes no sense to continue
3359 * Currently, the only type of exception that can be caught by a
3360 * TryCatch handler and for which it does not make sense to continue
3361 * is termination exception. Such exceptions are thrown when the
3362 * TerminateExecution methods are called to terminate a long-running
3365 * If CanContinue returns false, the correct action is to perform
3366 * any C++ cleanup needed and then return.
3368 bool CanContinue() const;
3371 * Throws the exception caught by this TryCatch in a way that avoids
3372 * it being caught again by this same TryCatch. As with ThrowException
3373 * it is illegal to execute any JavaScript operations after calling
3374 * ReThrow; the caller must return immediately to where the exception
3377 Handle<Value> ReThrow();
3380 * Returns the exception caught by this try/catch block. If no exception has
3381 * been caught an empty handle is returned.
3383 * The returned handle is valid until this TryCatch block has been destroyed.
3385 Local<Value> Exception() const;
3388 * Returns the .stack property of the thrown object. If no .stack
3389 * property is present an empty handle is returned.
3391 Local<Value> StackTrace() const;
3394 * Returns the message associated with this exception. If there is
3395 * no message associated an empty handle is returned.
3397 * The returned handle is valid until this TryCatch block has been
3400 Local<v8::Message> Message() const;
3403 * Clears any exceptions that may have been caught by this try/catch block.
3404 * After this method has been called, HasCaught() will return false.
3406 * It is not necessary to clear a try/catch block before using it again; if
3407 * another exception is thrown the previously caught exception will just be
3408 * overwritten. However, it is often a good idea since it makes it easier
3409 * to determine which operation threw a given exception.
3414 * Set verbosity of the external exception handler.
3416 * By default, exceptions that are caught by an external exception
3417 * handler are not reported. Call SetVerbose with true on an
3418 * external exception handler to have exceptions caught by the
3419 * handler reported as if they were not caught.
3421 void SetVerbose(bool value);
3424 * Set whether or not this TryCatch should capture a Message object
3425 * which holds source information about where the exception
3426 * occurred. True by default.
3428 void SetCaptureMessage(bool value);
3431 v8::internal::Isolate* isolate_;
3435 bool is_verbose_ : 1;
3436 bool can_continue_ : 1;
3437 bool capture_message_ : 1;
3440 friend class v8::internal::Isolate;
3450 class V8EXPORT ExtensionConfiguration {
3452 ExtensionConfiguration(int name_count, const char* names[])
3453 : name_count_(name_count), names_(names) { }
3455 friend class ImplementationUtilities;
3457 const char** names_;
3462 * A sandboxed execution context with its own set of built-in objects
3465 class V8EXPORT Context {
3468 * Returns the global proxy object or global object itself for
3469 * detached contexts.
3471 * Global proxy object is a thin wrapper whose prototype points to
3472 * actual context's global object with the properties like Object, etc.
3473 * This is done that way for security reasons (for more details see
3474 * https://wiki.mozilla.org/Gecko:SplitWindow).
3476 * Please note that changes to global proxy object prototype most probably
3477 * would break VM---v8 expects only global object as a prototype of
3478 * global proxy object.
3480 * If DetachGlobal() has been invoked, Global() would return actual global
3481 * object until global is reattached with ReattachGlobal().
3483 Local<Object> Global();
3486 * Detaches the global object from its context before
3487 * the global object can be reused to create a new context.
3489 void DetachGlobal();
3492 * Reattaches a global object to a context. This can be used to
3493 * restore the connection between a global object and a context
3494 * after DetachGlobal has been called.
3496 * \param global_object The global object to reattach to the
3497 * context. For this to work, the global object must be the global
3498 * object that was associated with this context before a call to
3501 void ReattachGlobal(Handle<Object> global_object);
3503 /** Creates a new context.
3505 * Returns a persistent handle to the newly allocated context. This
3506 * persistent handle has to be disposed when the context is no
3507 * longer used so the context can be garbage collected.
3509 * \param extensions An optional extension configuration containing
3510 * the extensions to be installed in the newly created context.
3512 * \param global_template An optional object template from which the
3513 * global object for the newly created context will be created.
3515 * \param global_object An optional global object to be reused for
3516 * the newly created context. This global object must have been
3517 * created by a previous call to Context::New with the same global
3518 * template. The state of the global object will be completely reset
3519 * and only object identify will remain.
3521 static Persistent<Context> New(
3522 ExtensionConfiguration* extensions = NULL,
3523 Handle<ObjectTemplate> global_template = Handle<ObjectTemplate>(),
3524 Handle<Value> global_object = Handle<Value>());
3526 /** Returns the last entered context. */
3527 static Local<Context> GetEntered();
3529 /** Returns the context that is on the top of the stack. */
3530 static Local<Context> GetCurrent();
3533 * Returns the context of the calling JavaScript code. That is the
3534 * context of the top-most JavaScript frame. If there are no
3535 * JavaScript frames an empty handle is returned.
3537 static Local<Context> GetCalling();
3538 static Local<Object> GetCallingQmlGlobal();
3539 static Local<Value> GetCallingScriptData();
3542 * Sets the security token for the context. To access an object in
3543 * another context, the security tokens must match.
3545 void SetSecurityToken(Handle<Value> token);
3547 /** Restores the security token to the default value. */
3548 void UseDefaultSecurityToken();
3550 /** Returns the security token of this context.*/
3551 Handle<Value> GetSecurityToken();
3554 * Enter this context. After entering a context, all code compiled
3555 * and run is compiled and run in this context. If another context
3556 * is already entered, this old context is saved so it can be
3557 * restored when the new context is exited.
3562 * Exit this context. Exiting the current context restores the
3563 * context that was in place when entering the current context.
3567 /** Returns true if the context has experienced an out of memory situation. */
3568 bool HasOutOfMemoryException();
3570 /** Returns true if V8 has a current context. */
3571 static bool InContext();
3574 * Associate an additional data object with the context. This is mainly used
3575 * with the debugger to provide additional information on the context through
3578 void SetData(Handle<String> data);
3579 Local<Value> GetData();
3582 * Control whether code generation from strings is allowed. Calling
3583 * this method with false will disable 'eval' and the 'Function'
3584 * constructor for code running in this context. If 'eval' or the
3585 * 'Function' constructor are used an exception will be thrown.
3587 * If code generation from strings is not allowed the
3588 * V8::AllowCodeGenerationFromStrings callback will be invoked if
3589 * set before blocking the call to 'eval' or the 'Function'
3590 * constructor. If that callback returns true, the call will be
3591 * allowed, otherwise an exception will be thrown. If no callback is
3592 * set an exception will be thrown.
3594 void AllowCodeGenerationFromStrings(bool allow);
3597 * Stack-allocated class which sets the execution context for all
3598 * operations executed within a local scope.
3602 explicit inline Scope(Handle<Context> context) : context_(context) {
3605 inline ~Scope() { context_->Exit(); }
3607 Handle<Context> context_;
3612 friend class Script;
3613 friend class Object;
3614 friend class Function;
3619 * Multiple threads in V8 are allowed, but only one thread at a time
3620 * is allowed to use any given V8 isolate. See Isolate class
3621 * comments. The definition of 'using V8 isolate' includes
3622 * accessing handles or holding onto object pointers obtained
3623 * from V8 handles while in the particular V8 isolate. It is up
3624 * to the user of V8 to ensure (perhaps with locking) that this
3625 * constraint is not violated.
3627 * v8::Locker is a scoped lock object. While it's
3628 * active (i.e. between its construction and destruction) the current thread is
3629 * allowed to use the locked isolate. V8 guarantees that an isolate can be
3630 * locked by at most one thread at any time. In other words, the scope of a
3631 * v8::Locker is a critical section.
3637 * v8::Locker locker(isolate);
3638 * v8::Isolate::Scope isolate_scope(isolate);
3640 * // Code using V8 and isolate goes here.
3642 * } // Destructor called here
3645 * If you wish to stop using V8 in a thread A you can do this either
3646 * by destroying the v8::Locker object as above or by constructing a
3647 * v8::Unlocker object:
3652 * v8::Unlocker unlocker(isolate);
3654 * // Code not using V8 goes here while V8 can run in another thread.
3656 * } // Destructor called here.
3660 * The Unlocker object is intended for use in a long-running callback
3661 * from V8, where you want to release the V8 lock for other threads to
3664 * The v8::Locker is a recursive lock. That is, you can lock more than
3665 * once in a given thread. This can be useful if you have code that can
3666 * be called either from code that holds the lock or from code that does
3667 * not. The Unlocker is not recursive so you can not have several
3668 * Unlockers on the stack at once, and you can not use an Unlocker in a
3669 * thread that is not inside a Locker's scope.
3671 * An unlocker will unlock several lockers if it has to and reinstate
3672 * the correct depth of locking on its destruction. eg.:
3677 * v8::Locker locker(isolate);
3678 * Isolate::Scope isolate_scope(isolate);
3681 * v8::Locker another_locker(isolate);
3682 * // V8 still locked (2 levels).
3685 * v8::Unlocker unlocker(isolate);
3689 * // V8 locked again (2 levels).
3691 * // V8 still locked (1 level).
3693 * // V8 Now no longer locked.
3698 class V8EXPORT Unlocker {
3701 * Initialize Unlocker for a given Isolate. NULL means default isolate.
3703 explicit Unlocker(Isolate* isolate = NULL);
3706 internal::Isolate* isolate_;
3710 class V8EXPORT Locker {
3713 * Initialize Locker for a given Isolate. NULL means default isolate.
3715 explicit Locker(Isolate* isolate = NULL);
3721 * When preemption is started, a timer is fired every n milliseconds
3722 * that will switch between multiple threads that are in contention
3725 static void StartPreemption(int every_n_ms);
3730 static void StopPreemption();
3733 * Returns whether or not the locker for a given isolate, or default isolate
3734 * if NULL is given, is locked by the current thread.
3736 static bool IsLocked(Isolate* isolate = NULL);
3739 * Returns whether v8::Locker is being used by this V8 instance.
3741 static bool IsActive();
3746 internal::Isolate* isolate_;
3748 static bool active_;
3750 // Disallow copying and assigning.
3751 Locker(const Locker&);
3752 void operator=(const Locker&);
3757 * An interface for exporting data from V8, using "push" model.
3759 class V8EXPORT OutputStream { // NOLINT
3761 enum OutputEncoding {
3762 kAscii = 0 // 7-bit ASCII.
3768 virtual ~OutputStream() {}
3769 /** Notify about the end of stream. */
3770 virtual void EndOfStream() = 0;
3771 /** Get preferred output chunk size. Called only once. */
3772 virtual int GetChunkSize() { return 1024; }
3773 /** Get preferred output encoding. Called only once. */
3774 virtual OutputEncoding GetOutputEncoding() { return kAscii; }
3776 * Writes the next chunk of snapshot data into the stream. Writing
3777 * can be stopped by returning kAbort as function result. EndOfStream
3778 * will not be called in case writing was aborted.
3780 virtual WriteResult WriteAsciiChunk(char* data, int size) = 0;
3785 * An interface for reporting progress and controlling long-running
3788 class V8EXPORT ActivityControl { // NOLINT
3790 enum ControlOption {
3794 virtual ~ActivityControl() {}
3796 * Notify about current progress. The activity can be stopped by
3797 * returning kAbort as the callback result.
3799 virtual ControlOption ReportProgressValue(int done, int total) = 0;
3803 // --- Implementation ---
3806 namespace internal {
3808 static const int kApiPointerSize = sizeof(void*); // NOLINT
3809 static const int kApiIntSize = sizeof(int); // NOLINT
3811 // Tag information for HeapObject.
3812 const int kHeapObjectTag = 1;
3813 const int kHeapObjectTagSize = 2;
3814 const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
3816 // Tag information for Smi.
3817 const int kSmiTag = 0;
3818 const int kSmiTagSize = 1;
3819 const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
3821 template <size_t ptr_size> struct SmiTagging;
3823 // Smi constants for 32-bit systems.
3824 template <> struct SmiTagging<4> {
3825 static const int kSmiShiftSize = 0;
3826 static const int kSmiValueSize = 31;
3827 static inline int SmiToInt(internal::Object* value) {
3828 int shift_bits = kSmiTagSize + kSmiShiftSize;
3829 // Throw away top 32 bits and shift down (requires >> to be sign extending).
3830 return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
3833 // For 32-bit systems any 2 bytes aligned pointer can be encoded as smi
3834 // with a plain reinterpret_cast.
3835 static const uintptr_t kEncodablePointerMask = 0x1;
3836 static const int kPointerToSmiShift = 0;
3839 // Smi constants for 64-bit systems.
3840 template <> struct SmiTagging<8> {
3841 static const int kSmiShiftSize = 31;
3842 static const int kSmiValueSize = 32;
3843 static inline int SmiToInt(internal::Object* value) {
3844 int shift_bits = kSmiTagSize + kSmiShiftSize;
3845 // Shift down and throw away top 32 bits.
3846 return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
3849 // To maximize the range of pointers that can be encoded
3850 // in the available 32 bits, we require them to be 8 bytes aligned.
3851 // This gives 2 ^ (32 + 3) = 32G address space covered.
3852 // It might be not enough to cover stack allocated objects on some platforms.
3853 static const int kPointerAlignment = 3;
3855 static const uintptr_t kEncodablePointerMask =
3856 ~(uintptr_t(0xffffffff) << kPointerAlignment);
3858 static const int kPointerToSmiShift =
3859 kSmiTagSize + kSmiShiftSize - kPointerAlignment;
3862 typedef SmiTagging<kApiPointerSize> PlatformSmiTagging;
3863 const int kSmiShiftSize = PlatformSmiTagging::kSmiShiftSize;
3864 const int kSmiValueSize = PlatformSmiTagging::kSmiValueSize;
3865 const uintptr_t kEncodablePointerMask =
3866 PlatformSmiTagging::kEncodablePointerMask;
3867 const int kPointerToSmiShift = PlatformSmiTagging::kPointerToSmiShift;
3869 template <size_t ptr_size> struct InternalConstants;
3871 // Internal constants for 32-bit systems.
3872 template <> struct InternalConstants<4> {
3873 static const int kStringResourceOffset = 3 * kApiPointerSize;
3876 // Internal constants for 64-bit systems.
3877 template <> struct InternalConstants<8> {
3878 static const int kStringResourceOffset = 3 * kApiPointerSize;
3882 * This class exports constants and functionality from within v8 that
3883 * is necessary to implement inline functions in the v8 api. Don't
3884 * depend on functions and constants defined here.
3888 // These values match non-compiler-dependent values defined within
3889 // the implementation of v8.
3890 static const int kHeapObjectMapOffset = 0;
3891 static const int kMapInstanceTypeOffset = 1 * kApiPointerSize + kApiIntSize;
3892 static const int kStringResourceOffset =
3893 InternalConstants<kApiPointerSize>::kStringResourceOffset;
3895 static const int kForeignAddressOffset = kApiPointerSize;
3896 static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
3897 static const int kFullStringRepresentationMask = 0x07;
3898 static const int kExternalTwoByteRepresentationTag = 0x02;
3900 static const int kJSObjectType = 0xa6;
3901 static const int kFirstNonstringType = 0x80;
3902 static const int kForeignType = 0x85;
3904 static inline bool HasHeapObjectTag(internal::Object* value) {
3905 return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
3909 static inline bool HasSmiTag(internal::Object* value) {
3910 return ((reinterpret_cast<intptr_t>(value) & kSmiTagMask) == kSmiTag);
3913 static inline int SmiValue(internal::Object* value) {
3914 return PlatformSmiTagging::SmiToInt(value);
3917 static inline int GetInstanceType(internal::Object* obj) {
3918 typedef internal::Object O;
3919 O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
3920 return ReadField<uint8_t>(map, kMapInstanceTypeOffset);
3923 static inline void* GetExternalPointerFromSmi(internal::Object* value) {
3924 const uintptr_t address = reinterpret_cast<uintptr_t>(value);
3925 return reinterpret_cast<void*>(address >> kPointerToSmiShift);
3928 static inline void* GetExternalPointer(internal::Object* obj) {
3929 if (HasSmiTag(obj)) {
3930 return GetExternalPointerFromSmi(obj);
3931 } else if (GetInstanceType(obj) == kForeignType) {
3932 return ReadField<void*>(obj, kForeignAddressOffset);
3938 static inline bool IsExternalTwoByteString(int instance_type) {
3939 int representation = (instance_type & kFullStringRepresentationMask);
3940 return representation == kExternalTwoByteRepresentationTag;
3943 template <typename T>
3944 static inline T ReadField(Object* ptr, int offset) {
3945 uint8_t* addr = reinterpret_cast<uint8_t*>(ptr) + offset - kHeapObjectTag;
3946 return *reinterpret_cast<T*>(addr);
3949 static inline bool CanCastToHeapObject(void*) { return false; }
3950 static inline bool CanCastToHeapObject(Context*) { return true; }
3951 static inline bool CanCastToHeapObject(String*) { return true; }
3952 static inline bool CanCastToHeapObject(Object*) { return true; }
3953 static inline bool CanCastToHeapObject(Message*) { return true; }
3954 static inline bool CanCastToHeapObject(StackTrace*) { return true; }
3955 static inline bool CanCastToHeapObject(StackFrame*) { return true; }
3958 } // namespace internal
3962 Local<T>::Local() : Handle<T>() { }
3966 Local<T> Local<T>::New(Handle<T> that) {
3967 if (that.IsEmpty()) return Local<T>();
3968 T* that_ptr = *that;
3969 internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
3970 if (internal::Internals::CanCastToHeapObject(that_ptr)) {
3971 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
3972 reinterpret_cast<internal::HeapObject*>(*p))));
3974 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(*p)));
3979 Persistent<T> Persistent<T>::New(Handle<T> that) {
3980 if (that.IsEmpty()) return Persistent<T>();
3981 internal::Object** p = reinterpret_cast<internal::Object**>(*that);
3982 return Persistent<T>(reinterpret_cast<T*>(V8::GlobalizeReference(p)));
3987 bool Persistent<T>::IsNearDeath() const {
3988 if (this->IsEmpty()) return false;
3989 return V8::IsGlobalNearDeath(reinterpret_cast<internal::Object**>(**this));
3994 bool Persistent<T>::IsWeak() const {
3995 if (this->IsEmpty()) return false;
3996 return V8::IsGlobalWeak(reinterpret_cast<internal::Object**>(**this));
4001 void Persistent<T>::Dispose() {
4002 if (this->IsEmpty()) return;
4003 V8::DisposeGlobal(reinterpret_cast<internal::Object**>(**this));
4008 Persistent<T>::Persistent() : Handle<T>() { }
4011 void Persistent<T>::MakeWeak(void* parameters, WeakReferenceCallback callback) {
4012 V8::MakeWeak(reinterpret_cast<internal::Object**>(**this),
4018 void Persistent<T>::ClearWeak() {
4019 V8::ClearWeak(reinterpret_cast<internal::Object**>(**this));
4023 void Persistent<T>::MarkIndependent() {
4024 V8::MarkIndependent(reinterpret_cast<internal::Object**>(**this));
4028 void Persistent<T>::SetWrapperClassId(uint16_t class_id) {
4029 V8::SetWrapperClassId(reinterpret_cast<internal::Object**>(**this), class_id);
4032 Arguments::Arguments(internal::Object** implicit_args,
4033 internal::Object** values, int length,
4034 bool is_construct_call)
4035 : implicit_args_(implicit_args),
4038 is_construct_call_(is_construct_call) { }
4041 Local<Value> Arguments::operator[](int i) const {
4042 if (i < 0 || length_ <= i) return Local<Value>(*Undefined());
4043 return Local<Value>(reinterpret_cast<Value*>(values_ - i));
4047 Local<Function> Arguments::Callee() const {
4048 return Local<Function>(reinterpret_cast<Function*>(
4049 &implicit_args_[kCalleeIndex]));
4053 Local<Object> Arguments::This() const {
4054 return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
4058 Local<Object> Arguments::Holder() const {
4059 return Local<Object>(reinterpret_cast<Object*>(
4060 &implicit_args_[kHolderIndex]));
4064 Local<Value> Arguments::Data() const {
4065 return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
4069 bool Arguments::IsConstructCall() const {
4070 return is_construct_call_;
4074 int Arguments::Length() const {
4080 Local<T> HandleScope::Close(Handle<T> value) {
4081 internal::Object** before = reinterpret_cast<internal::Object**>(*value);
4082 internal::Object** after = RawClose(before);
4083 return Local<T>(reinterpret_cast<T*>(after));
4086 Handle<Value> ScriptOrigin::ResourceName() const {
4087 return resource_name_;
4091 Handle<Integer> ScriptOrigin::ResourceLineOffset() const {
4092 return resource_line_offset_;
4096 Handle<Integer> ScriptOrigin::ResourceColumnOffset() const {
4097 return resource_column_offset_;
4101 Handle<Boolean> Boolean::New(bool value) {
4102 return value ? True() : False();
4106 void Template::Set(const char* name, v8::Handle<Data> value) {
4107 Set(v8::String::New(name), value);
4111 Local<Value> Object::GetInternalField(int index) {
4112 #ifndef V8_ENABLE_CHECKS
4113 Local<Value> quick_result = UncheckedGetInternalField(index);
4114 if (!quick_result.IsEmpty()) return quick_result;
4116 return CheckedGetInternalField(index);
4120 Local<Value> Object::UncheckedGetInternalField(int index) {
4121 typedef internal::Object O;
4122 typedef internal::Internals I;
4123 O* obj = *reinterpret_cast<O**>(this);
4124 if (I::GetInstanceType(obj) == I::kJSObjectType) {
4125 // If the object is a plain JSObject, which is the common case,
4126 // we know where to find the internal fields and can return the
4128 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
4129 O* value = I::ReadField<O*>(obj, offset);
4130 O** result = HandleScope::CreateHandle(value);
4131 return Local<Value>(reinterpret_cast<Value*>(result));
4133 return Local<Value>();
4138 void* External::Unwrap(Handle<v8::Value> obj) {
4139 #ifdef V8_ENABLE_CHECKS
4140 return FullUnwrap(obj);
4142 return QuickUnwrap(obj);
4147 void* External::QuickUnwrap(Handle<v8::Value> wrapper) {
4148 typedef internal::Object O;
4149 O* obj = *reinterpret_cast<O**>(const_cast<v8::Value*>(*wrapper));
4150 return internal::Internals::GetExternalPointer(obj);
4154 void* Object::GetPointerFromInternalField(int index) {
4155 typedef internal::Object O;
4156 typedef internal::Internals I;
4158 O* obj = *reinterpret_cast<O**>(this);
4160 if (I::GetInstanceType(obj) == I::kJSObjectType) {
4161 // If the object is a plain JSObject, which is the common case,
4162 // we know where to find the internal fields and can return the
4164 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
4165 O* value = I::ReadField<O*>(obj, offset);
4166 return I::GetExternalPointer(value);
4169 return SlowGetPointerFromInternalField(index);
4173 String* String::Cast(v8::Value* value) {
4174 #ifdef V8_ENABLE_CHECKS
4177 return static_cast<String*>(value);
4181 String::ExternalStringResource* String::GetExternalStringResource() const {
4182 typedef internal::Object O;
4183 typedef internal::Internals I;
4184 O* obj = *reinterpret_cast<O**>(const_cast<String*>(this));
4185 String::ExternalStringResource* result;
4186 if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
4187 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
4188 result = reinterpret_cast<String::ExternalStringResource*>(value);
4192 #ifdef V8_ENABLE_CHECKS
4193 VerifyExternalStringResource(result);
4199 bool Value::IsString() const {
4200 #ifdef V8_ENABLE_CHECKS
4201 return FullIsString();
4203 return QuickIsString();
4207 bool Value::QuickIsString() const {
4208 typedef internal::Object O;
4209 typedef internal::Internals I;
4210 O* obj = *reinterpret_cast<O**>(const_cast<Value*>(this));
4211 if (!I::HasHeapObjectTag(obj)) return false;
4212 return (I::GetInstanceType(obj) < I::kFirstNonstringType);
4216 Number* Number::Cast(v8::Value* value) {
4217 #ifdef V8_ENABLE_CHECKS
4220 return static_cast<Number*>(value);
4224 Integer* Integer::Cast(v8::Value* value) {
4225 #ifdef V8_ENABLE_CHECKS
4228 return static_cast<Integer*>(value);
4232 Date* Date::Cast(v8::Value* value) {
4233 #ifdef V8_ENABLE_CHECKS
4236 return static_cast<Date*>(value);
4240 StringObject* StringObject::Cast(v8::Value* value) {
4241 #ifdef V8_ENABLE_CHECKS
4244 return static_cast<StringObject*>(value);
4248 NumberObject* NumberObject::Cast(v8::Value* value) {
4249 #ifdef V8_ENABLE_CHECKS
4252 return static_cast<NumberObject*>(value);
4256 BooleanObject* BooleanObject::Cast(v8::Value* value) {
4257 #ifdef V8_ENABLE_CHECKS
4260 return static_cast<BooleanObject*>(value);
4264 RegExp* RegExp::Cast(v8::Value* value) {
4265 #ifdef V8_ENABLE_CHECKS
4268 return static_cast<RegExp*>(value);
4272 Object* Object::Cast(v8::Value* value) {
4273 #ifdef V8_ENABLE_CHECKS
4276 return static_cast<Object*>(value);
4280 Array* Array::Cast(v8::Value* value) {
4281 #ifdef V8_ENABLE_CHECKS
4284 return static_cast<Array*>(value);
4288 Function* Function::Cast(v8::Value* value) {
4289 #ifdef V8_ENABLE_CHECKS
4292 return static_cast<Function*>(value);
4296 External* External::Cast(v8::Value* value) {
4297 #ifdef V8_ENABLE_CHECKS
4300 return static_cast<External*>(value);
4304 Local<Value> AccessorInfo::Data() const {
4305 return Local<Value>(reinterpret_cast<Value*>(&args_[-2]));
4309 Local<Object> AccessorInfo::This() const {
4310 return Local<Object>(reinterpret_cast<Object*>(&args_[0]));
4314 Local<Object> AccessorInfo::Holder() const {
4315 return Local<Object>(reinterpret_cast<Object*>(&args_[-1]));
4321 * A simple shell that takes a list of expressions on the
4322 * command-line and executes them.
4327 * \example process.cc