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 {
596 * Compiles the specified script (context-independent).
598 * \param source Script source code.
599 * \param origin Script origin, owned by caller, no references are kept
601 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
602 * using pre_data speeds compilation if it's done multiple times.
603 * Owned by caller, no references are kept when New() returns.
604 * \param script_data Arbitrary data associated with script. Using
605 * this has same effect as calling SetData(), but allows data to be
606 * available to compile event handlers.
607 * \return Compiled script object (context independent; when run it
608 * will use the currently entered context).
610 static Local<Script> New(Handle<String> source,
611 ScriptOrigin* origin = NULL,
612 ScriptData* pre_data = NULL,
613 Handle<String> script_data = Handle<String>(),
614 CompileFlags = Default);
617 * Compiles the specified script using the specified file name
618 * object (typically a string) as the script's origin.
620 * \param source Script source code.
621 * \param file_name file name object (typically a string) to be used
622 * as the script's origin.
623 * \return Compiled script object (context independent; when run it
624 * will use the currently entered context).
626 static Local<Script> New(Handle<String> source,
627 Handle<Value> file_name,
628 CompileFlags = Default);
631 * Compiles the specified script (bound to current context).
633 * \param source Script source code.
634 * \param origin Script origin, owned by caller, no references are kept
635 * when Compile() returns
636 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
637 * using pre_data speeds compilation if it's done multiple times.
638 * Owned by caller, no references are kept when Compile() returns.
639 * \param script_data Arbitrary data associated with script. Using
640 * this has same effect as calling SetData(), but makes data available
641 * earlier (i.e. to compile event handlers).
642 * \return Compiled script object, bound to the context that was active
643 * when this function was called. When run it will always use this
646 static Local<Script> Compile(Handle<String> source,
647 ScriptOrigin* origin = NULL,
648 ScriptData* pre_data = NULL,
649 Handle<String> script_data = Handle<String>(),
650 CompileFlags = Default);
653 * Compiles the specified script using the specified file name
654 * object (typically a string) as the script's origin.
656 * \param source Script source code.
657 * \param file_name File name to use as script's origin
658 * \param script_data Arbitrary data associated with script. Using
659 * this has same effect as calling SetData(), but makes data available
660 * earlier (i.e. to compile event handlers).
661 * \return Compiled script object, bound to the context that was active
662 * when this function was called. When run it will always use this
665 static Local<Script> Compile(Handle<String> source,
666 Handle<Value> file_name,
667 Handle<String> script_data = Handle<String>(),
668 CompileFlags = Default);
671 * Runs the script returning the resulting value. If the script is
672 * context independent (created using ::New) it will be run in the
673 * currently entered context. If it is context specific (created
674 * using ::Compile) it will be run in the context in which it was
678 Local<Value> Run(Handle<Object> qml);
681 * Returns the script id value.
686 * Associate an additional data object with the script. This is mainly used
687 * with the debugger as this data object is only available through the
690 void SetData(Handle<String> data);
697 class V8EXPORT Message {
699 Local<String> Get() const;
700 Local<String> GetSourceLine() const;
703 * Returns the resource name for the script from where the function causing
704 * the error originates.
706 Handle<Value> GetScriptResourceName() const;
709 * Returns the resource data for the script from where the function causing
710 * the error originates.
712 Handle<Value> GetScriptData() const;
715 * Exception stack trace. By default stack traces are not captured for
716 * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
717 * to change this option.
719 Handle<StackTrace> GetStackTrace() const;
722 * Returns the number, 1-based, of the line where the error occurred.
724 int GetLineNumber() const;
727 * Returns the index within the script of the first character where
728 * the error occurred.
730 int GetStartPosition() const;
733 * Returns the index within the script of the last character where
734 * the error occurred.
736 int GetEndPosition() const;
739 * Returns the index within the line of the first character where
740 * the error occurred.
742 int GetStartColumn() const;
745 * Returns the index within the line of the last character where
746 * the error occurred.
748 int GetEndColumn() const;
750 // TODO(1245381): Print to a string instead of on a FILE.
751 static void PrintCurrentStackTrace(FILE* out);
753 static const int kNoLineNumberInfo = 0;
754 static const int kNoColumnInfo = 0;
759 * Representation of a JavaScript stack trace. The information collected is a
760 * snapshot of the execution stack and the information remains valid after
761 * execution continues.
763 class V8EXPORT StackTrace {
766 * Flags that determine what information is placed captured for each
767 * StackFrame when grabbing the current stack trace.
769 enum StackTraceOptions {
771 kColumnOffset = 1 << 1 | kLineNumber,
772 kScriptName = 1 << 2,
773 kFunctionName = 1 << 3,
775 kIsConstructor = 1 << 5,
776 kScriptNameOrSourceURL = 1 << 6,
777 kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
778 kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL
782 * Returns a StackFrame at a particular index.
784 Local<StackFrame> GetFrame(uint32_t index) const;
787 * Returns the number of StackFrames.
789 int GetFrameCount() const;
792 * Returns StackTrace as a v8::Array that contains StackFrame objects.
794 Local<Array> AsArray();
797 * Grab a snapshot of the current JavaScript execution stack.
799 * \param frame_limit The maximum number of stack frames we want to capture.
800 * \param options Enumerates the set of things we will capture for each
803 static Local<StackTrace> CurrentStackTrace(
805 StackTraceOptions options = kOverview);
810 * A single JavaScript stack frame.
812 class V8EXPORT StackFrame {
815 * Returns the number, 1-based, of the line for the associate function call.
816 * This method will return Message::kNoLineNumberInfo if it is unable to
817 * retrieve the line number, or if kLineNumber was not passed as an option
818 * when capturing the StackTrace.
820 int GetLineNumber() const;
823 * Returns the 1-based column offset on the line for the associated function
825 * This method will return Message::kNoColumnInfo if it is unable to retrieve
826 * the column number, or if kColumnOffset was not passed as an option when
827 * capturing the StackTrace.
829 int GetColumn() const;
832 * Returns the name of the resource that contains the script for the
833 * function for this StackFrame.
835 Local<String> GetScriptName() const;
838 * Returns the name of the resource that contains the script for the
839 * function for this StackFrame or sourceURL value if the script name
840 * is undefined and its source ends with //@ sourceURL=... string.
842 Local<String> GetScriptNameOrSourceURL() const;
845 * Returns the name of the function associated with this stack frame.
847 Local<String> GetFunctionName() const;
850 * Returns whether or not the associated function is compiled via a call to
856 * Returns whether or not the associated function is called as a
857 * constructor via "new".
859 bool IsConstructor() const;
867 * The superclass of all JavaScript values and objects.
869 class Value : public Data {
872 * Returns true if this value is the undefined value. See ECMA-262
875 V8EXPORT bool IsUndefined() const;
878 * Returns true if this value is the null value. See ECMA-262
881 V8EXPORT bool IsNull() const;
884 * Returns true if this value is true.
886 V8EXPORT bool IsTrue() const;
889 * Returns true if this value is false.
891 V8EXPORT bool IsFalse() const;
894 * Returns true if this value is an instance of the String type.
897 inline bool IsString() const;
900 * Returns true if this value is a function.
902 V8EXPORT bool IsFunction() const;
905 * Returns true if this value is an array.
907 V8EXPORT bool IsArray() const;
910 * Returns true if this value is an object.
912 V8EXPORT bool IsObject() const;
915 * Returns true if this value is boolean.
917 V8EXPORT bool IsBoolean() const;
920 * Returns true if this value is a number.
922 V8EXPORT bool IsNumber() const;
925 * Returns true if this value is external.
927 V8EXPORT bool IsExternal() const;
930 * Returns true if this value is a 32-bit signed integer.
932 V8EXPORT bool IsInt32() const;
935 * Returns true if this value is a 32-bit unsigned integer.
937 V8EXPORT bool IsUint32() const;
940 * Returns true if this value is a Date.
942 V8EXPORT bool IsDate() const;
945 * Returns true if this value is a Boolean object.
947 V8EXPORT bool IsBooleanObject() const;
950 * Returns true if this value is a Number object.
952 V8EXPORT bool IsNumberObject() const;
955 * Returns true if this value is a String object.
957 V8EXPORT bool IsStringObject() const;
960 * Returns true if this value is a NativeError.
962 V8EXPORT bool IsNativeError() const;
965 * Returns true if this value is a RegExp.
967 V8EXPORT bool IsRegExp() const;
969 V8EXPORT Local<Boolean> ToBoolean() const;
970 V8EXPORT Local<Number> ToNumber() const;
971 V8EXPORT Local<String> ToString() const;
972 V8EXPORT Local<String> ToDetailString() const;
973 V8EXPORT Local<Object> ToObject() const;
974 V8EXPORT Local<Integer> ToInteger() const;
975 V8EXPORT Local<Uint32> ToUint32() const;
976 V8EXPORT Local<Int32> ToInt32() const;
979 * Attempts to convert a string to an array index.
980 * Returns an empty handle if the conversion fails.
982 V8EXPORT Local<Uint32> ToArrayIndex() const;
984 V8EXPORT bool BooleanValue() const;
985 V8EXPORT double NumberValue() const;
986 V8EXPORT int64_t IntegerValue() const;
987 V8EXPORT uint32_t Uint32Value() const;
988 V8EXPORT int32_t Int32Value() const;
991 V8EXPORT bool Equals(Handle<Value> that) const;
992 V8EXPORT bool StrictEquals(Handle<Value> that) const;
995 inline bool QuickIsString() const;
996 V8EXPORT bool FullIsString() const;
1001 * The superclass of primitive values. See ECMA-262 4.3.2.
1003 class Primitive : public Value { };
1007 * A primitive boolean value (ECMA-262, 4.3.14). Either the true
1010 class Boolean : public Primitive {
1012 V8EXPORT bool Value() const;
1013 static inline Handle<Boolean> New(bool value);
1018 * A JavaScript string value (ECMA-262, 4.3.17).
1020 class String : public Primitive {
1023 * Returns the number of characters in this string.
1025 V8EXPORT int Length() const;
1028 * Returns the number of bytes in the UTF-8 encoded
1029 * representation of this string.
1031 V8EXPORT int Utf8Length() const;
1034 * Returns the hash of this string.
1036 V8EXPORT uint32_t Hash() const;
1038 struct CompleteHashData {
1039 CompleteHashData() : length(0), hash(0), symbol_id(0) {}
1046 * Returns the "complete" hash of the string. This is
1047 * all the information about the string needed to implement
1048 * a very efficient hash keyed on the string.
1050 * The members of CompleteHashData are:
1051 * length: The length of the string. Equivalent to Length()
1052 * hash: The hash of the string. Equivalent to Hash()
1053 * symbol_id: If the string is a sequential symbol, the symbol
1054 * id, otherwise 0. If the symbol ids of two strings are
1055 * the same (and non-zero) the two strings are identical.
1056 * If the symbol ids are different the strings may still be
1057 * identical, but an Equals() check must be performed.
1059 V8EXPORT CompleteHashData CompleteHash() const;
1062 * Compute a hash value for the passed UTF16 string
1065 V8EXPORT static uint32_t ComputeHash(uint16_t *string, int length);
1066 V8EXPORT static uint32_t ComputeHash(char *string, int length);
1069 * Returns true if this string is equal to the external
1070 * string data provided.
1072 V8EXPORT bool Equals(uint16_t *string, int length);
1073 V8EXPORT bool Equals(char *string, int length);
1074 inline bool Equals(Handle<Value> that) const { return v8::Value::Equals(that); }
1077 * Write the contents of the string to an external buffer.
1078 * If no arguments are given, expects the buffer to be large
1079 * enough to hold the entire string and NULL terminator. Copies
1080 * the contents of the string and the NULL terminator into the
1083 * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
1084 * before the end of the buffer.
1086 * Copies up to length characters into the output buffer.
1087 * Only null-terminates if there is enough space in the buffer.
1089 * \param buffer The buffer into which the string will be copied.
1090 * \param start The starting position within the string at which
1092 * \param length The number of characters to copy from the string. For
1093 * WriteUtf8 the number of bytes in the buffer.
1094 * \param nchars_ref The number of characters written, can be NULL.
1095 * \param options Various options that might affect performance of this or
1096 * subsequent operations.
1097 * \return The number of characters copied to the buffer excluding the null
1098 * terminator. For WriteUtf8: The number of bytes copied to the buffer
1099 * including the null terminator (if written).
1103 HINT_MANY_WRITES_EXPECTED = 1,
1104 NO_NULL_TERMINATION = 2
1107 V8EXPORT uint16_t GetCharacter(int index);
1109 // 16-bit character codes.
1110 V8EXPORT int Write(uint16_t* buffer,
1113 int options = NO_OPTIONS) const;
1114 // ASCII characters.
1115 V8EXPORT int WriteAscii(char* buffer,
1118 int options = NO_OPTIONS) const;
1119 // UTF-8 encoded characters.
1120 V8EXPORT int WriteUtf8(char* buffer,
1122 int* nchars_ref = NULL,
1123 int options = NO_OPTIONS) const;
1126 * A zero length string.
1128 V8EXPORT static v8::Local<v8::String> Empty();
1131 * Returns true if the string is external
1133 V8EXPORT bool IsExternal() const;
1136 * Returns true if the string is both external and ASCII
1138 V8EXPORT bool IsExternalAscii() const;
1140 class V8EXPORT ExternalStringResourceBase { // NOLINT
1142 virtual ~ExternalStringResourceBase() {}
1145 ExternalStringResourceBase() {}
1148 * Internally V8 will call this Dispose method when the external string
1149 * resource is no longer needed. The default implementation will use the
1150 * delete operator. This method can be overridden in subclasses to
1151 * control how allocated external string resources are disposed.
1153 virtual void Dispose() { delete this; }
1156 // Disallow copying and assigning.
1157 ExternalStringResourceBase(const ExternalStringResourceBase&);
1158 void operator=(const ExternalStringResourceBase&);
1160 friend class v8::internal::Heap;
1164 * An ExternalStringResource is a wrapper around a two-byte string
1165 * buffer that resides outside V8's heap. Implement an
1166 * ExternalStringResource to manage the life cycle of the underlying
1167 * buffer. Note that the string data must be immutable.
1169 class V8EXPORT ExternalStringResource
1170 : public ExternalStringResourceBase {
1173 * Override the destructor to manage the life cycle of the underlying
1176 virtual ~ExternalStringResource() {}
1179 * The string data from the underlying buffer.
1181 virtual const uint16_t* data() const = 0;
1184 * The length of the string. That is, the number of two-byte characters.
1186 virtual size_t length() const = 0;
1189 ExternalStringResource() {}
1193 * An ExternalAsciiStringResource is a wrapper around an ASCII
1194 * string buffer that resides outside V8's heap. Implement an
1195 * ExternalAsciiStringResource to manage the life cycle of the
1196 * underlying buffer. Note that the string data must be immutable
1197 * and that the data must be strict (7-bit) ASCII, not Latin-1 or
1198 * UTF-8, which would require special treatment internally in the
1199 * engine and, in the case of UTF-8, do not allow efficient indexing.
1200 * Use String::New or convert to 16 bit data for non-ASCII.
1203 class V8EXPORT ExternalAsciiStringResource
1204 : public ExternalStringResourceBase {
1207 * Override the destructor to manage the life cycle of the underlying
1210 virtual ~ExternalAsciiStringResource() {}
1211 /** The string data from the underlying buffer.*/
1212 virtual const char* data() const = 0;
1213 /** The number of ASCII characters in the string.*/
1214 virtual size_t length() const = 0;
1216 ExternalAsciiStringResource() {}
1220 * Get the ExternalStringResource for an external string. Returns
1221 * NULL if IsExternal() doesn't return true.
1223 inline ExternalStringResource* GetExternalStringResource() const;
1226 * Get the ExternalAsciiStringResource for an external ASCII string.
1227 * Returns NULL if IsExternalAscii() doesn't return true.
1229 V8EXPORT const ExternalAsciiStringResource* GetExternalAsciiStringResource()
1232 static inline String* Cast(v8::Value* obj);
1235 * Allocates a new string from either UTF-8 encoded or ASCII data.
1236 * The second parameter 'length' gives the buffer length.
1237 * If the data is UTF-8 encoded, the caller must
1238 * be careful to supply the length parameter.
1239 * If it is not given, the function calls
1240 * 'strlen' to determine the buffer length, it might be
1241 * wrong if 'data' contains a null character.
1243 V8EXPORT static Local<String> New(const char* data, int length = -1);
1245 /** Allocates a new string from 16-bit character codes.*/
1246 V8EXPORT static Local<String> New(const uint16_t* data, int length = -1);
1248 /** Creates a symbol. Returns one if it exists already.*/
1249 V8EXPORT static Local<String> NewSymbol(const char* data, int length = -1);
1252 * Creates a new string by concatenating the left and the right strings
1253 * passed in as parameters.
1255 V8EXPORT static Local<String> Concat(Handle<String> left,
1256 Handle<String>right);
1259 * Creates a new external string using the data defined in the given
1260 * resource. When the external string is no longer live on V8's heap the
1261 * resource will be disposed by calling its Dispose method. The caller of
1262 * this function should not otherwise delete or modify the resource. Neither
1263 * should the underlying buffer be deallocated or modified except through the
1264 * destructor of the external string resource.
1266 V8EXPORT static Local<String> NewExternal(ExternalStringResource* resource);
1269 * Associate an external string resource with this string by transforming it
1270 * in place so that existing references to this string in the JavaScript heap
1271 * will use the external string resource. The external string resource's
1272 * character contents need to be equivalent to this string.
1273 * Returns true if the string has been changed to be an external string.
1274 * The string is not modified if the operation fails. See NewExternal for
1275 * information on the lifetime of the resource.
1277 V8EXPORT bool MakeExternal(ExternalStringResource* resource);
1280 * Creates a new external string using the ASCII data defined in the given
1281 * resource. When the external string is no longer live on V8's heap the
1282 * resource will be disposed by calling its Dispose method. The caller of
1283 * this function should not otherwise delete or modify the resource. Neither
1284 * should the underlying buffer be deallocated or modified except through the
1285 * destructor of the external string resource.
1287 V8EXPORT static Local<String> NewExternal(
1288 ExternalAsciiStringResource* resource);
1291 * Associate an external string resource with this string by transforming it
1292 * in place so that existing references to this string in the JavaScript heap
1293 * will use the external string resource. The external string resource's
1294 * character contents need to be equivalent to this string.
1295 * Returns true if the string has been changed to be an external string.
1296 * The string is not modified if the operation fails. See NewExternal for
1297 * information on the lifetime of the resource.
1299 V8EXPORT bool MakeExternal(ExternalAsciiStringResource* resource);
1302 * Returns true if this string can be made external.
1304 V8EXPORT bool CanMakeExternal();
1306 /** Creates an undetectable string from the supplied ASCII or UTF-8 data.*/
1307 V8EXPORT static Local<String> NewUndetectable(const char* data,
1310 /** Creates an undetectable string from the supplied 16-bit character codes.*/
1311 V8EXPORT static Local<String> NewUndetectable(const uint16_t* data,
1315 * Converts an object to a UTF-8-encoded character array. Useful if
1316 * you want to print the object. If conversion to a string fails
1317 * (e.g. due to an exception in the toString() method of the object)
1318 * then the length() method returns 0 and the * operator returns
1321 class V8EXPORT Utf8Value {
1323 explicit Utf8Value(Handle<v8::Value> obj);
1325 char* operator*() { return str_; }
1326 const char* operator*() const { return str_; }
1327 int length() const { return length_; }
1332 // Disallow copying and assigning.
1333 Utf8Value(const Utf8Value&);
1334 void operator=(const Utf8Value&);
1338 * Converts an object to an ASCII string.
1339 * Useful if you want to print the object.
1340 * If conversion to a string fails (eg. due to an exception in the toString()
1341 * method of the object) then the length() method returns 0 and the * operator
1344 class V8EXPORT AsciiValue {
1346 explicit AsciiValue(Handle<v8::Value> obj);
1348 char* operator*() { return str_; }
1349 const char* operator*() const { return str_; }
1350 int length() const { return length_; }
1355 // Disallow copying and assigning.
1356 AsciiValue(const AsciiValue&);
1357 void operator=(const AsciiValue&);
1361 * Converts an object to a two-byte string.
1362 * If conversion to a string fails (eg. due to an exception in the toString()
1363 * method of the object) then the length() method returns 0 and the * operator
1366 class V8EXPORT Value {
1368 explicit Value(Handle<v8::Value> obj);
1370 uint16_t* operator*() { return str_; }
1371 const uint16_t* operator*() const { return str_; }
1372 int length() const { return length_; }
1377 // Disallow copying and assigning.
1378 Value(const Value&);
1379 void operator=(const Value&);
1383 V8EXPORT void VerifyExternalStringResource(ExternalStringResource* val) const;
1384 V8EXPORT static void CheckCast(v8::Value* obj);
1389 * A JavaScript number value (ECMA-262, 4.3.20)
1391 class Number : public Primitive {
1393 V8EXPORT double Value() const;
1394 V8EXPORT static Local<Number> New(double value);
1395 static inline Number* Cast(v8::Value* obj);
1398 V8EXPORT static void CheckCast(v8::Value* obj);
1403 * A JavaScript value representing a signed integer.
1405 class Integer : public Number {
1407 V8EXPORT static Local<Integer> New(int32_t value);
1408 V8EXPORT static Local<Integer> NewFromUnsigned(uint32_t value);
1409 V8EXPORT int64_t Value() const;
1410 static inline Integer* Cast(v8::Value* obj);
1413 V8EXPORT static void CheckCast(v8::Value* obj);
1418 * A JavaScript value representing a 32-bit signed integer.
1420 class Int32 : public Integer {
1422 V8EXPORT int32_t Value() const;
1429 * A JavaScript value representing a 32-bit unsigned integer.
1431 class Uint32 : public Integer {
1433 V8EXPORT uint32_t Value() const;
1439 enum PropertyAttribute {
1446 enum ExternalArrayType {
1447 kExternalByteArray = 1,
1448 kExternalUnsignedByteArray,
1449 kExternalShortArray,
1450 kExternalUnsignedShortArray,
1452 kExternalUnsignedIntArray,
1453 kExternalFloatArray,
1454 kExternalDoubleArray,
1459 * Accessor[Getter|Setter] are used as callback functions when
1460 * setting|getting a particular property. See Object and ObjectTemplate's
1461 * method SetAccessor.
1463 typedef Handle<Value> (*AccessorGetter)(Local<String> property,
1464 const AccessorInfo& info);
1467 typedef void (*AccessorSetter)(Local<String> property,
1469 const AccessorInfo& info);
1473 * Access control specifications.
1475 * Some accessors should be accessible across contexts. These
1476 * accessors have an explicit access control parameter which specifies
1477 * the kind of cross-context access that should be allowed.
1479 * Additionally, for security, accessors can prohibit overwriting by
1480 * accessors defined in JavaScript. For objects that have such
1481 * accessors either locally or in their prototype chain it is not
1482 * possible to overwrite the accessor by using __defineGetter__ or
1483 * __defineSetter__ from JavaScript code.
1485 enum AccessControl {
1488 ALL_CAN_WRITE = 1 << 1,
1489 PROHIBITS_OVERWRITING = 1 << 2
1494 * A JavaScript object (ECMA-262, 4.3.3)
1496 class Object : public Value {
1498 V8EXPORT bool Set(Handle<Value> key,
1499 Handle<Value> value,
1500 PropertyAttribute attribs = None);
1502 V8EXPORT bool Set(uint32_t index,
1503 Handle<Value> value);
1505 // Sets a local property on this object bypassing interceptors and
1506 // overriding accessors or read-only properties.
1508 // Note that if the object has an interceptor the property will be set
1509 // locally, but since the interceptor takes precedence the local property
1510 // will only be returned if the interceptor doesn't return a value.
1512 // Note also that this only works for named properties.
1513 V8EXPORT bool ForceSet(Handle<Value> key,
1514 Handle<Value> value,
1515 PropertyAttribute attribs = None);
1517 V8EXPORT Local<Value> Get(Handle<Value> key);
1519 V8EXPORT Local<Value> Get(uint32_t index);
1522 * Gets the property attributes of a property which can be None or
1523 * any combination of ReadOnly, DontEnum and DontDelete. Returns
1524 * None when the property doesn't exist.
1526 V8EXPORT PropertyAttribute GetPropertyAttributes(Handle<Value> key);
1528 // TODO(1245389): Replace the type-specific versions of these
1529 // functions with generic ones that accept a Handle<Value> key.
1530 V8EXPORT bool Has(Handle<String> key);
1532 V8EXPORT bool Delete(Handle<String> key);
1534 // Delete a property on this object bypassing interceptors and
1535 // ignoring dont-delete attributes.
1536 V8EXPORT bool ForceDelete(Handle<Value> key);
1538 V8EXPORT bool Has(uint32_t index);
1540 V8EXPORT bool Delete(uint32_t index);
1542 V8EXPORT bool SetAccessor(Handle<String> name,
1543 AccessorGetter getter,
1544 AccessorSetter setter = 0,
1545 Handle<Value> data = Handle<Value>(),
1546 AccessControl settings = DEFAULT,
1547 PropertyAttribute attribute = None);
1550 * Returns an array containing the names of the enumerable properties
1551 * of this object, including properties from prototype objects. The
1552 * array returned by this method contains the same values as would
1553 * be enumerated by a for-in statement over this object.
1555 V8EXPORT Local<Array> GetPropertyNames();
1558 * This function has the same functionality as GetPropertyNames but
1559 * the returned array doesn't contain the names of properties from
1560 * prototype objects.
1562 V8EXPORT Local<Array> GetOwnPropertyNames();
1565 * Get the prototype object. This does not skip objects marked to
1566 * be skipped by __proto__ and it does not consult the security
1569 V8EXPORT Local<Value> GetPrototype();
1572 * Set the prototype object. This does not skip objects marked to
1573 * be skipped by __proto__ and it does not consult the security
1576 V8EXPORT bool SetPrototype(Handle<Value> prototype);
1579 * Finds an instance of the given function template in the prototype
1582 V8EXPORT Local<Object> FindInstanceInPrototypeChain(
1583 Handle<FunctionTemplate> tmpl);
1586 * Call builtin Object.prototype.toString on this object.
1587 * This is different from Value::ToString() that may call
1588 * user-defined toString function. This one does not.
1590 V8EXPORT Local<String> ObjectProtoToString();
1593 * Returns the name of the function invoked as a constructor for this object.
1595 V8EXPORT Local<String> GetConstructorName();
1597 /** Gets the number of internal fields for this Object. */
1598 V8EXPORT int InternalFieldCount();
1599 /** Gets the value in an internal field. */
1600 inline Local<Value> GetInternalField(int index);
1601 /** Sets the value in an internal field. */
1602 V8EXPORT void SetInternalField(int index, Handle<Value> value);
1604 /** Gets a native pointer from an internal field. */
1605 inline void* GetPointerFromInternalField(int index);
1607 /** Sets a native pointer in an internal field. */
1608 V8EXPORT void SetPointerInInternalField(int index, void* value);
1610 class V8EXPORT ExternalResource { // NOLINT
1612 ExternalResource() {}
1613 virtual ~ExternalResource() {}
1616 virtual void Dispose() { delete this; }
1619 // Disallow copying and assigning.
1620 ExternalResource(const ExternalResource&);
1621 void operator=(const ExternalResource&);
1623 friend class v8::internal::Heap;
1626 V8EXPORT void SetExternalResource(ExternalResource *);
1627 V8EXPORT ExternalResource *GetExternalResource();
1629 // Testers for local properties.
1630 V8EXPORT bool HasOwnProperty(Handle<String> key);
1631 V8EXPORT bool HasRealNamedProperty(Handle<String> key);
1632 V8EXPORT bool HasRealIndexedProperty(uint32_t index);
1633 V8EXPORT bool HasRealNamedCallbackProperty(Handle<String> key);
1636 * If result.IsEmpty() no real property was located in the prototype chain.
1637 * This means interceptors in the prototype chain are not called.
1639 V8EXPORT Local<Value> GetRealNamedPropertyInPrototypeChain(
1640 Handle<String> key);
1643 * If result.IsEmpty() no real property was located on the object or
1644 * in the prototype chain.
1645 * This means interceptors in the prototype chain are not called.
1647 V8EXPORT Local<Value> GetRealNamedProperty(Handle<String> key);
1649 /** Tests for a named lookup interceptor.*/
1650 V8EXPORT bool HasNamedLookupInterceptor();
1652 /** Tests for an index lookup interceptor.*/
1653 V8EXPORT bool HasIndexedLookupInterceptor();
1656 * Turns on access check on the object if the object is an instance of
1657 * a template that has access check callbacks. If an object has no
1658 * access check info, the object cannot be accessed by anyone.
1660 V8EXPORT void TurnOnAccessCheck();
1663 * Returns the identity hash for this object. The current implementation
1664 * uses a hidden property on the object to store the identity hash.
1666 * The return value will never be 0. Also, it is not guaranteed to be
1669 V8EXPORT int GetIdentityHash();
1672 * Access hidden properties on JavaScript objects. These properties are
1673 * hidden from the executing JavaScript and only accessible through the V8
1674 * C++ API. Hidden properties introduced by V8 internally (for example the
1675 * identity hash) are prefixed with "v8::".
1677 V8EXPORT bool SetHiddenValue(Handle<String> key, Handle<Value> value);
1678 V8EXPORT Local<Value> GetHiddenValue(Handle<String> key);
1679 V8EXPORT bool DeleteHiddenValue(Handle<String> key);
1682 * Returns true if this is an instance of an api function (one
1683 * created from a function created from a function template) and has
1684 * been modified since it was created. Note that this method is
1685 * conservative and may return true for objects that haven't actually
1688 V8EXPORT bool IsDirty();
1691 * Clone this object with a fast but shallow copy. Values will point
1692 * to the same values as the original object.
1694 V8EXPORT Local<Object> Clone();
1697 * Returns the context in which the object was created.
1699 V8EXPORT Local<Context> CreationContext();
1702 * Set the backing store of the indexed properties to be managed by the
1703 * embedding layer. Access to the indexed properties will follow the rules
1704 * spelled out in CanvasPixelArray.
1705 * Note: The embedding program still owns the data and needs to ensure that
1706 * the backing store is preserved while V8 has a reference.
1708 V8EXPORT void SetIndexedPropertiesToPixelData(uint8_t* data, int length);
1709 V8EXPORT bool HasIndexedPropertiesInPixelData();
1710 V8EXPORT uint8_t* GetIndexedPropertiesPixelData();
1711 V8EXPORT int GetIndexedPropertiesPixelDataLength();
1714 * Set the backing store of the indexed properties to be managed by the
1715 * embedding layer. Access to the indexed properties will follow the rules
1716 * spelled out for the CanvasArray subtypes in the WebGL specification.
1717 * Note: The embedding program still owns the data and needs to ensure that
1718 * the backing store is preserved while V8 has a reference.
1720 V8EXPORT void SetIndexedPropertiesToExternalArrayData(
1722 ExternalArrayType array_type,
1723 int number_of_elements);
1724 V8EXPORT bool HasIndexedPropertiesInExternalArrayData();
1725 V8EXPORT void* GetIndexedPropertiesExternalArrayData();
1726 V8EXPORT ExternalArrayType GetIndexedPropertiesExternalArrayDataType();
1727 V8EXPORT int GetIndexedPropertiesExternalArrayDataLength();
1730 * Checks whether a callback is set by the
1731 * ObjectTemplate::SetCallAsFunctionHandler method.
1732 * When an Object is callable this method returns true.
1734 V8EXPORT bool IsCallable();
1737 * Call an Object as a function if a callback is set by the
1738 * ObjectTemplate::SetCallAsFunctionHandler method.
1740 V8EXPORT Local<Value> CallAsFunction(Handle<Object> recv,
1742 Handle<Value> argv[]);
1745 * Call an Object as a constructor if a callback is set by the
1746 * ObjectTemplate::SetCallAsFunctionHandler method.
1747 * Note: This method behaves like the Function::NewInstance method.
1749 V8EXPORT Local<Value> CallAsConstructor(int argc,
1750 Handle<Value> argv[]);
1752 V8EXPORT static Local<Object> New();
1753 static inline Object* Cast(Value* obj);
1757 V8EXPORT static void CheckCast(Value* obj);
1758 V8EXPORT Local<Value> CheckedGetInternalField(int index);
1759 V8EXPORT void* SlowGetPointerFromInternalField(int index);
1762 * If quick access to the internal field is possible this method
1763 * returns the value. Otherwise an empty handle is returned.
1765 inline Local<Value> UncheckedGetInternalField(int index);
1770 * An instance of the built-in array constructor (ECMA-262, 15.4.2).
1772 class Array : public Object {
1774 V8EXPORT uint32_t Length() const;
1777 * Clones an element at index |index|. Returns an empty
1778 * handle if cloning fails (for any reason).
1780 V8EXPORT Local<Object> CloneElementAt(uint32_t index);
1783 * Creates a JavaScript array with the given length. If the length
1784 * is negative the returned array will have length 0.
1786 V8EXPORT static Local<Array> New(int length = 0);
1788 static inline Array* Cast(Value* obj);
1791 V8EXPORT static void CheckCast(Value* obj);
1796 * A JavaScript function object (ECMA-262, 15.3).
1798 class Function : public Object {
1800 V8EXPORT Local<Object> NewInstance() const;
1801 V8EXPORT Local<Object> NewInstance(int argc, Handle<Value> argv[]) const;
1802 V8EXPORT Local<Value> Call(Handle<Object> recv,
1804 Handle<Value> argv[]);
1805 V8EXPORT void SetName(Handle<String> name);
1806 V8EXPORT Handle<Value> GetName() const;
1809 * Returns zero based line number of function body and
1810 * kLineOffsetNotFound if no information available.
1812 V8EXPORT int GetScriptLineNumber() const;
1813 V8EXPORT ScriptOrigin GetScriptOrigin() const;
1814 static inline Function* Cast(Value* obj);
1815 V8EXPORT static const int kLineOffsetNotFound;
1817 V8EXPORT Function();
1818 V8EXPORT static void CheckCast(Value* obj);
1823 * An instance of the built-in Date constructor (ECMA-262, 15.9).
1825 class Date : public Object {
1827 V8EXPORT static Local<Value> New(double time);
1830 * A specialization of Value::NumberValue that is more efficient
1831 * because we know the structure of this object.
1833 V8EXPORT double NumberValue() const;
1835 static inline Date* Cast(v8::Value* obj);
1838 * Notification that the embedder has changed the time zone,
1839 * daylight savings time, or other date / time configuration
1840 * parameters. V8 keeps a cache of various values used for
1841 * date / time computation. This notification will reset
1842 * those cached values for the current context so that date /
1843 * time configuration changes would be reflected in the Date
1846 * This API should not be called more than needed as it will
1847 * negatively impact the performance of date operations.
1849 V8EXPORT static void DateTimeConfigurationChangeNotification();
1852 V8EXPORT static void CheckCast(v8::Value* obj);
1857 * A Number object (ECMA-262, 4.3.21).
1859 class NumberObject : public Object {
1861 V8EXPORT static Local<Value> New(double value);
1864 * Returns the Number held by the object.
1866 V8EXPORT double NumberValue() const;
1868 static inline NumberObject* Cast(v8::Value* obj);
1871 V8EXPORT static void CheckCast(v8::Value* obj);
1876 * A Boolean object (ECMA-262, 4.3.15).
1878 class BooleanObject : public Object {
1880 V8EXPORT static Local<Value> New(bool value);
1883 * Returns the Boolean held by the object.
1885 V8EXPORT bool BooleanValue() const;
1887 static inline BooleanObject* Cast(v8::Value* obj);
1890 V8EXPORT static void CheckCast(v8::Value* obj);
1895 * A String object (ECMA-262, 4.3.18).
1897 class StringObject : public Object {
1899 V8EXPORT static Local<Value> New(Handle<String> value);
1902 * Returns the String held by the object.
1904 V8EXPORT Local<String> StringValue() const;
1906 static inline StringObject* Cast(v8::Value* obj);
1909 V8EXPORT static void CheckCast(v8::Value* obj);
1914 * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
1916 class RegExp : public Object {
1919 * Regular expression flag bits. They can be or'ed to enable a set
1930 * Creates a regular expression from the given pattern string and
1931 * the flags bit field. May throw a JavaScript exception as
1932 * described in ECMA-262, 15.10.4.1.
1935 * RegExp::New(v8::String::New("foo"),
1936 * static_cast<RegExp::Flags>(kGlobal | kMultiline))
1937 * is equivalent to evaluating "/foo/gm".
1939 V8EXPORT static Local<RegExp> New(Handle<String> pattern,
1943 * Returns the value of the source property: a string representing
1944 * the regular expression.
1946 V8EXPORT Local<String> GetSource() const;
1949 * Returns the flags bit field.
1951 V8EXPORT Flags GetFlags() const;
1953 static inline RegExp* Cast(v8::Value* obj);
1956 V8EXPORT static void CheckCast(v8::Value* obj);
1961 * A JavaScript value that wraps a C++ void*. This type of value is
1962 * mainly used to associate C++ data structures with JavaScript
1965 * The Wrap function V8 will return the most optimal Value object wrapping the
1966 * C++ void*. The type of the value is not guaranteed to be an External object
1967 * and no assumptions about its type should be made. To access the wrapped
1968 * value Unwrap should be used, all other operations on that object will lead
1969 * to unpredictable results.
1971 class External : public Value {
1973 V8EXPORT static Local<Value> Wrap(void* data);
1974 static inline void* Unwrap(Handle<Value> obj);
1976 V8EXPORT static Local<External> New(void* value);
1977 static inline External* Cast(Value* obj);
1978 V8EXPORT void* Value() const;
1980 V8EXPORT External();
1981 V8EXPORT static void CheckCast(v8::Value* obj);
1982 static inline void* QuickUnwrap(Handle<v8::Value> obj);
1983 V8EXPORT static void* FullUnwrap(Handle<v8::Value> obj);
1987 // --- Templates ---
1991 * The superclass of object and function templates.
1993 class V8EXPORT Template : public Data {
1995 /** Adds a property to each instance created by this template.*/
1996 void Set(Handle<String> name, Handle<Data> value,
1997 PropertyAttribute attributes = None);
1998 inline void Set(const char* name, Handle<Data> value);
2002 friend class ObjectTemplate;
2003 friend class FunctionTemplate;
2008 * The argument information given to function call callbacks. This
2009 * class provides access to information about the context of the call,
2010 * including the receiver, the number and values of arguments, and
2011 * the holder of the function.
2015 inline int Length() const;
2016 inline Local<Value> operator[](int i) const;
2017 inline Local<Function> Callee() const;
2018 inline Local<Object> This() const;
2019 inline Local<Object> Holder() const;
2020 inline bool IsConstructCall() const;
2021 inline Local<Value> Data() const;
2023 static const int kDataIndex = 0;
2024 static const int kCalleeIndex = -1;
2025 static const int kHolderIndex = -2;
2027 friend class ImplementationUtilities;
2028 inline Arguments(internal::Object** implicit_args,
2029 internal::Object** values,
2031 bool is_construct_call);
2032 internal::Object** implicit_args_;
2033 internal::Object** values_;
2035 bool is_construct_call_;
2040 * The information passed to an accessor callback about the context
2041 * of the property access.
2043 class V8EXPORT AccessorInfo {
2045 inline AccessorInfo(internal::Object** args)
2047 inline Local<Value> Data() const;
2048 inline Local<Object> This() const;
2049 inline Local<Object> Holder() const;
2051 internal::Object** args_;
2055 typedef Handle<Value> (*InvocationCallback)(const Arguments& args);
2058 * NamedProperty[Getter|Setter] are used as interceptors on object.
2059 * See ObjectTemplate::SetNamedPropertyHandler.
2061 typedef Handle<Value> (*NamedPropertyGetter)(Local<String> property,
2062 const AccessorInfo& info);
2066 * Returns the value if the setter intercepts the request.
2067 * Otherwise, returns an empty handle.
2069 typedef Handle<Value> (*NamedPropertySetter)(Local<String> property,
2071 const AccessorInfo& info);
2074 * Returns a non-empty handle if the interceptor intercepts the request.
2075 * The result is an integer encoding property attributes (like v8::None,
2076 * v8::DontEnum, etc.)
2078 typedef Handle<Integer> (*NamedPropertyQuery)(Local<String> property,
2079 const AccessorInfo& info);
2083 * Returns a non-empty handle if the deleter intercepts the request.
2084 * The return value is true if the property could be deleted and false
2087 typedef Handle<Boolean> (*NamedPropertyDeleter)(Local<String> property,
2088 const AccessorInfo& info);
2091 * Returns an array containing the names of the properties the named
2092 * property getter intercepts.
2094 typedef Handle<Array> (*NamedPropertyEnumerator)(const AccessorInfo& info);
2098 * Returns the value of the property if the getter intercepts the
2099 * request. Otherwise, returns an empty handle.
2101 typedef Handle<Value> (*IndexedPropertyGetter)(uint32_t index,
2102 const AccessorInfo& info);
2106 * Returns the value if the setter intercepts the request.
2107 * Otherwise, returns an empty handle.
2109 typedef Handle<Value> (*IndexedPropertySetter)(uint32_t index,
2111 const AccessorInfo& info);
2115 * Returns a non-empty handle if the interceptor intercepts the request.
2116 * The result is an integer encoding property attributes.
2118 typedef Handle<Integer> (*IndexedPropertyQuery)(uint32_t index,
2119 const AccessorInfo& info);
2122 * Returns a non-empty handle if the deleter intercepts the request.
2123 * The return value is true if the property could be deleted and false
2126 typedef Handle<Boolean> (*IndexedPropertyDeleter)(uint32_t index,
2127 const AccessorInfo& info);
2130 * Returns an array containing the indices of the properties the
2131 * indexed property getter intercepts.
2133 typedef Handle<Array> (*IndexedPropertyEnumerator)(const AccessorInfo& info);
2137 * Access type specification.
2149 * Returns true if cross-context access should be allowed to the named
2150 * property with the given key on the host object.
2152 typedef bool (*NamedSecurityCallback)(Local<Object> host,
2159 * Returns true if cross-context access should be allowed to the indexed
2160 * property with the given index on the host object.
2162 typedef bool (*IndexedSecurityCallback)(Local<Object> host,
2169 * A FunctionTemplate is used to create functions at runtime. There
2170 * can only be one function created from a FunctionTemplate in a
2171 * context. The lifetime of the created function is equal to the
2172 * lifetime of the context. So in case the embedder needs to create
2173 * temporary functions that can be collected using Scripts is
2176 * A FunctionTemplate can have properties, these properties are added to the
2177 * function object when it is created.
2179 * A FunctionTemplate has a corresponding instance template which is
2180 * used to create object instances when the function is used as a
2181 * constructor. Properties added to the instance template are added to
2182 * each object instance.
2184 * A FunctionTemplate can have a prototype template. The prototype template
2185 * is used to create the prototype object of the function.
2187 * The following example shows how to use a FunctionTemplate:
2190 * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
2191 * t->Set("func_property", v8::Number::New(1));
2193 * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
2194 * proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
2195 * proto_t->Set("proto_const", v8::Number::New(2));
2197 * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
2198 * instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
2199 * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
2200 * instance_t->Set("instance_property", Number::New(3));
2202 * v8::Local<v8::Function> function = t->GetFunction();
2203 * v8::Local<v8::Object> instance = function->NewInstance();
2206 * Let's use "function" as the JS variable name of the function object
2207 * and "instance" for the instance object created above. The function
2208 * and the instance will have the following properties:
2211 * func_property in function == true;
2212 * function.func_property == 1;
2214 * function.prototype.proto_method() invokes 'InvokeCallback'
2215 * function.prototype.proto_const == 2;
2217 * instance instanceof function == true;
2218 * instance.instance_accessor calls 'InstanceAccessorCallback'
2219 * instance.instance_property == 3;
2222 * A FunctionTemplate can inherit from another one by calling the
2223 * FunctionTemplate::Inherit method. The following graph illustrates
2224 * the semantics of inheritance:
2227 * FunctionTemplate Parent -> Parent() . prototype -> { }
2229 * | Inherit(Parent) | .__proto__
2231 * FunctionTemplate Child -> Child() . prototype -> { }
2234 * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
2235 * object of the Child() function has __proto__ pointing to the
2236 * Parent() function's prototype object. An instance of the Child
2237 * function has all properties on Parent's instance templates.
2239 * Let Parent be the FunctionTemplate initialized in the previous
2240 * section and create a Child FunctionTemplate by:
2243 * Local<FunctionTemplate> parent = t;
2244 * Local<FunctionTemplate> child = FunctionTemplate::New();
2245 * child->Inherit(parent);
2247 * Local<Function> child_function = child->GetFunction();
2248 * Local<Object> child_instance = child_function->NewInstance();
2251 * The Child function and Child instance will have the following
2255 * child_func.prototype.__proto__ == function.prototype;
2256 * child_instance.instance_accessor calls 'InstanceAccessorCallback'
2257 * child_instance.instance_property == 3;
2260 class V8EXPORT FunctionTemplate : public Template {
2262 /** Creates a function template.*/
2263 static Local<FunctionTemplate> New(
2264 InvocationCallback callback = 0,
2265 Handle<Value> data = Handle<Value>(),
2266 Handle<Signature> signature = Handle<Signature>());
2267 /** Returns the unique function instance in the current execution context.*/
2268 Local<Function> GetFunction();
2271 * Set the call-handler callback for a FunctionTemplate. This
2272 * callback is called whenever the function created from this
2273 * FunctionTemplate is called.
2275 void SetCallHandler(InvocationCallback callback,
2276 Handle<Value> data = Handle<Value>());
2278 /** Get the InstanceTemplate. */
2279 Local<ObjectTemplate> InstanceTemplate();
2281 /** Causes the function template to inherit from a parent function template.*/
2282 void Inherit(Handle<FunctionTemplate> parent);
2285 * A PrototypeTemplate is the template used to create the prototype object
2286 * of the function created by this template.
2288 Local<ObjectTemplate> PrototypeTemplate();
2292 * Set the class name of the FunctionTemplate. This is used for
2293 * printing objects created with the function created from the
2294 * FunctionTemplate as its constructor.
2296 void SetClassName(Handle<String> name);
2299 * Determines whether the __proto__ accessor ignores instances of
2300 * the function template. If instances of the function template are
2301 * ignored, __proto__ skips all instances and instead returns the
2302 * next object in the prototype chain.
2304 * Call with a value of true to make the __proto__ accessor ignore
2305 * instances of the function template. Call with a value of false
2306 * to make the __proto__ accessor not ignore instances of the
2307 * function template. By default, instances of a function template
2310 void SetHiddenPrototype(bool value);
2313 * Sets the ReadOnly flag in the attributes of the 'prototype' property
2314 * of functions created from this FunctionTemplate to true.
2316 void ReadOnlyPrototype();
2319 * Returns true if the given object is an instance of this function
2322 bool HasInstance(Handle<Value> object);
2326 void AddInstancePropertyAccessor(Handle<String> name,
2327 AccessorGetter getter,
2328 AccessorSetter setter,
2330 AccessControl settings,
2331 PropertyAttribute attributes);
2332 void SetNamedInstancePropertyHandler(NamedPropertyGetter getter,
2333 NamedPropertySetter setter,
2334 NamedPropertyQuery query,
2335 NamedPropertyDeleter remover,
2336 NamedPropertyEnumerator enumerator,
2338 Handle<Value> data);
2339 void SetIndexedInstancePropertyHandler(IndexedPropertyGetter getter,
2340 IndexedPropertySetter setter,
2341 IndexedPropertyQuery query,
2342 IndexedPropertyDeleter remover,
2343 IndexedPropertyEnumerator enumerator,
2344 Handle<Value> data);
2345 void SetInstanceCallAsFunctionHandler(InvocationCallback callback,
2346 Handle<Value> data);
2348 friend class Context;
2349 friend class ObjectTemplate;
2354 * An ObjectTemplate is used to create objects at runtime.
2356 * Properties added to an ObjectTemplate are added to each object
2357 * created from the ObjectTemplate.
2359 class V8EXPORT ObjectTemplate : public Template {
2361 /** Creates an ObjectTemplate. */
2362 static Local<ObjectTemplate> New();
2364 /** Creates a new instance of this template.*/
2365 Local<Object> NewInstance();
2368 * Sets an accessor on the object template.
2370 * Whenever the property with the given name is accessed on objects
2371 * created from this ObjectTemplate the getter and setter callbacks
2372 * are called instead of getting and setting the property directly
2373 * on the JavaScript object.
2375 * \param name The name of the property for which an accessor is added.
2376 * \param getter The callback to invoke when getting the property.
2377 * \param setter The callback to invoke when setting the property.
2378 * \param data A piece of data that will be passed to the getter and setter
2379 * callbacks whenever they are invoked.
2380 * \param settings Access control settings for the accessor. This is a bit
2381 * field consisting of one of more of
2382 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
2383 * The default is to not allow cross-context access.
2384 * ALL_CAN_READ means that all cross-context reads are allowed.
2385 * ALL_CAN_WRITE means that all cross-context writes are allowed.
2386 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
2387 * cross-context access.
2388 * \param attribute The attributes of the property for which an accessor
2391 void SetAccessor(Handle<String> name,
2392 AccessorGetter getter,
2393 AccessorSetter setter = 0,
2394 Handle<Value> data = Handle<Value>(),
2395 AccessControl settings = DEFAULT,
2396 PropertyAttribute attribute = None);
2399 * Sets a named property handler on the object template.
2401 * Whenever a named property is accessed on objects created from
2402 * this object template, the provided callback is invoked instead of
2403 * accessing the property directly on the JavaScript object.
2405 * \param getter The callback to invoke when getting a property.
2406 * \param setter The callback to invoke when setting a property.
2407 * \param query The callback to invoke to check if a property is present,
2408 * and if present, get its attributes.
2409 * \param deleter The callback to invoke when deleting a property.
2410 * \param enumerator The callback to invoke to enumerate all the named
2411 * properties of an object.
2412 * \param data A piece of data that will be passed to the callbacks
2413 * whenever they are invoked.
2415 void SetNamedPropertyHandler(NamedPropertyGetter getter,
2416 NamedPropertySetter setter = 0,
2417 NamedPropertyQuery query = 0,
2418 NamedPropertyDeleter deleter = 0,
2419 NamedPropertyEnumerator enumerator = 0,
2420 Handle<Value> data = Handle<Value>());
2421 void SetFallbackPropertyHandler(NamedPropertyGetter getter,
2422 NamedPropertySetter setter = 0,
2423 NamedPropertyQuery query = 0,
2424 NamedPropertyDeleter deleter = 0,
2425 NamedPropertyEnumerator enumerator = 0,
2426 Handle<Value> data = Handle<Value>());
2429 * Sets an indexed property handler on the object template.
2431 * Whenever an indexed property is accessed on objects created from
2432 * this object template, the provided callback is invoked instead of
2433 * accessing the property directly on the JavaScript object.
2435 * \param getter The callback to invoke when getting a property.
2436 * \param setter The callback to invoke when setting a property.
2437 * \param query The callback to invoke to check if an object has a property.
2438 * \param deleter The callback to invoke when deleting a property.
2439 * \param enumerator The callback to invoke to enumerate all the indexed
2440 * properties of an object.
2441 * \param data A piece of data that will be passed to the callbacks
2442 * whenever they are invoked.
2444 void SetIndexedPropertyHandler(IndexedPropertyGetter getter,
2445 IndexedPropertySetter setter = 0,
2446 IndexedPropertyQuery query = 0,
2447 IndexedPropertyDeleter deleter = 0,
2448 IndexedPropertyEnumerator enumerator = 0,
2449 Handle<Value> data = Handle<Value>());
2452 * Sets the callback to be used when calling instances created from
2453 * this template as a function. If no callback is set, instances
2454 * behave like normal JavaScript objects that cannot be called as a
2457 void SetCallAsFunctionHandler(InvocationCallback callback,
2458 Handle<Value> data = Handle<Value>());
2461 * Mark object instances of the template as undetectable.
2463 * In many ways, undetectable objects behave as though they are not
2464 * there. They behave like 'undefined' in conditionals and when
2465 * printed. However, properties can be accessed and called as on
2468 void MarkAsUndetectable();
2471 * Sets access check callbacks on the object template.
2473 * When accessing properties on instances of this object template,
2474 * the access check callback will be called to determine whether or
2475 * not to allow cross-context access to the properties.
2476 * The last parameter specifies whether access checks are turned
2477 * on by default on instances. If access checks are off by default,
2478 * they can be turned on on individual instances by calling
2479 * Object::TurnOnAccessCheck().
2481 void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
2482 IndexedSecurityCallback indexed_handler,
2483 Handle<Value> data = Handle<Value>(),
2484 bool turned_on_by_default = true);
2487 * Gets the number of internal fields for objects generated from
2490 int InternalFieldCount();
2493 * Sets the number of internal fields for objects generated from
2496 void SetInternalFieldCount(int value);
2499 * Sets whether the object can store an "external resource" object.
2501 bool HasExternalResource();
2502 void SetHasExternalResource(bool value);
2506 static Local<ObjectTemplate> New(Handle<FunctionTemplate> constructor);
2507 friend class FunctionTemplate;
2512 * A Signature specifies which receivers and arguments a function can
2513 * legally be called with.
2515 class V8EXPORT Signature : public Data {
2517 static Local<Signature> New(Handle<FunctionTemplate> receiver =
2518 Handle<FunctionTemplate>(),
2520 Handle<FunctionTemplate> argv[] = 0);
2527 * A utility for determining the type of objects based on the template
2528 * they were constructed from.
2530 class V8EXPORT TypeSwitch : public Data {
2532 static Local<TypeSwitch> New(Handle<FunctionTemplate> type);
2533 static Local<TypeSwitch> New(int argc, Handle<FunctionTemplate> types[]);
2534 int match(Handle<Value> value);
2540 // --- Extensions ---
2542 class V8EXPORT ExternalAsciiStringResourceImpl
2543 : public String::ExternalAsciiStringResource {
2545 ExternalAsciiStringResourceImpl() : data_(0), length_(0) {}
2546 ExternalAsciiStringResourceImpl(const char* data, size_t length)
2547 : data_(data), length_(length) {}
2548 const char* data() const { return data_; }
2549 size_t length() const { return length_; }
2559 class V8EXPORT Extension { // NOLINT
2561 // Note that the strings passed into this constructor must live as long
2562 // as the Extension itself.
2563 Extension(const char* name,
2564 const char* source = 0,
2566 const char** deps = 0,
2567 int source_length = -1);
2568 virtual ~Extension() { }
2569 virtual v8::Handle<v8::FunctionTemplate>
2570 GetNativeFunction(v8::Handle<v8::String> name) {
2571 return v8::Handle<v8::FunctionTemplate>();
2574 const char* name() const { return name_; }
2575 size_t source_length() const { return source_length_; }
2576 const String::ExternalAsciiStringResource* source() const {
2578 int dependency_count() { return dep_count_; }
2579 const char** dependencies() { return deps_; }
2580 void set_auto_enable(bool value) { auto_enable_ = value; }
2581 bool auto_enable() { return auto_enable_; }
2585 size_t source_length_; // expected to initialize before source_
2586 ExternalAsciiStringResourceImpl source_;
2591 // Disallow copying and assigning.
2592 Extension(const Extension&);
2593 void operator=(const Extension&);
2597 void V8EXPORT RegisterExtension(Extension* extension);
2603 class V8EXPORT DeclareExtension {
2605 inline DeclareExtension(Extension* extension) {
2606 RegisterExtension(extension);
2614 Handle<Primitive> V8EXPORT Undefined();
2615 Handle<Primitive> V8EXPORT Null();
2616 Handle<Boolean> V8EXPORT True();
2617 Handle<Boolean> V8EXPORT False();
2621 * A set of constraints that specifies the limits of the runtime's memory use.
2622 * You must set the heap size before initializing the VM - the size cannot be
2623 * adjusted after the VM is initialized.
2625 * If you are using threads then you should hold the V8::Locker lock while
2626 * setting the stack limit and you must set a non-default stack limit separately
2629 class V8EXPORT ResourceConstraints {
2631 ResourceConstraints();
2632 int max_young_space_size() const { return max_young_space_size_; }
2633 void set_max_young_space_size(int value) { max_young_space_size_ = value; }
2634 int max_old_space_size() const { return max_old_space_size_; }
2635 void set_max_old_space_size(int value) { max_old_space_size_ = value; }
2636 int max_executable_size() { return max_executable_size_; }
2637 void set_max_executable_size(int value) { max_executable_size_ = value; }
2638 uint32_t* stack_limit() const { return stack_limit_; }
2639 // Sets an address beyond which the VM's stack may not grow.
2640 void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
2642 int max_young_space_size_;
2643 int max_old_space_size_;
2644 int max_executable_size_;
2645 uint32_t* stack_limit_;
2649 bool V8EXPORT SetResourceConstraints(ResourceConstraints* constraints);
2652 // --- Exceptions ---
2655 typedef void (*FatalErrorCallback)(const char* location, const char* message);
2658 typedef void (*MessageCallback)(Handle<Message> message, Handle<Value> data);
2662 * Schedules an exception to be thrown when returning to JavaScript. When an
2663 * exception has been scheduled it is illegal to invoke any JavaScript
2664 * operation; the caller must return immediately and only after the exception
2665 * has been handled does it become legal to invoke JavaScript operations.
2667 Handle<Value> V8EXPORT ThrowException(Handle<Value> exception);
2670 * Create new error objects by calling the corresponding error object
2671 * constructor with the message.
2673 class V8EXPORT Exception {
2675 static Local<Value> RangeError(Handle<String> message);
2676 static Local<Value> ReferenceError(Handle<String> message);
2677 static Local<Value> SyntaxError(Handle<String> message);
2678 static Local<Value> TypeError(Handle<String> message);
2679 static Local<Value> Error(Handle<String> message);
2683 // --- Counters Callbacks ---
2685 typedef int* (*CounterLookupCallback)(const char* name);
2687 typedef void* (*CreateHistogramCallback)(const char* name,
2692 typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
2694 // --- Memory Allocation Callback ---
2696 kObjectSpaceNewSpace = 1 << 0,
2697 kObjectSpaceOldPointerSpace = 1 << 1,
2698 kObjectSpaceOldDataSpace = 1 << 2,
2699 kObjectSpaceCodeSpace = 1 << 3,
2700 kObjectSpaceMapSpace = 1 << 4,
2701 kObjectSpaceLoSpace = 1 << 5,
2703 kObjectSpaceAll = kObjectSpaceNewSpace | kObjectSpaceOldPointerSpace |
2704 kObjectSpaceOldDataSpace | kObjectSpaceCodeSpace | kObjectSpaceMapSpace |
2708 enum AllocationAction {
2709 kAllocationActionAllocate = 1 << 0,
2710 kAllocationActionFree = 1 << 1,
2711 kAllocationActionAll = kAllocationActionAllocate | kAllocationActionFree
2714 typedef void (*MemoryAllocationCallback)(ObjectSpace space,
2715 AllocationAction action,
2718 // --- Failed Access Check Callback ---
2719 typedef void (*FailedAccessCheckCallback)(Local<Object> target,
2723 // --- AllowCodeGenerationFromStrings callbacks ---
2726 * Callback to check if code generation from strings is allowed. See
2727 * Context::AllowCodeGenerationFromStrings.
2729 typedef bool (*AllowCodeGenerationFromStringsCallback)(Local<Context> context);
2731 // --- Garbage Collection Callbacks ---
2734 * Applications can register callback functions which will be called
2735 * before and after a garbage collection. Allocations are not
2736 * allowed in the callback functions, you therefore cannot manipulate
2737 * objects (set or delete properties for example) since it is possible
2738 * such operations will result in the allocation of objects.
2741 kGCTypeScavenge = 1 << 0,
2742 kGCTypeMarkSweepCompact = 1 << 1,
2743 kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact
2746 enum GCCallbackFlags {
2747 kNoGCCallbackFlags = 0,
2748 kGCCallbackFlagCompacted = 1 << 0
2751 typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
2752 typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
2754 typedef void (*GCCallback)();
2758 * Collection of V8 heap information.
2760 * Instances of this class can be passed to v8::V8::HeapStatistics to
2761 * get heap statistics from V8.
2763 class V8EXPORT HeapStatistics {
2766 size_t total_heap_size() { return total_heap_size_; }
2767 size_t total_heap_size_executable() { return total_heap_size_executable_; }
2768 size_t used_heap_size() { return used_heap_size_; }
2769 size_t heap_size_limit() { return heap_size_limit_; }
2772 void set_total_heap_size(size_t size) { total_heap_size_ = size; }
2773 void set_total_heap_size_executable(size_t size) {
2774 total_heap_size_executable_ = size;
2776 void set_used_heap_size(size_t size) { used_heap_size_ = size; }
2777 void set_heap_size_limit(size_t size) { heap_size_limit_ = size; }
2779 size_t total_heap_size_;
2780 size_t total_heap_size_executable_;
2781 size_t used_heap_size_;
2782 size_t heap_size_limit_;
2788 class RetainedObjectInfo;
2791 * Isolate represents an isolated instance of the V8 engine. V8
2792 * isolates have completely separate states. Objects from one isolate
2793 * must not be used in other isolates. When V8 is initialized a
2794 * default isolate is implicitly created and entered. The embedder
2795 * can create additional isolates and use them in parallel in multiple
2796 * threads. An isolate can be entered by at most one thread at any
2797 * given time. The Locker/Unlocker API can be used to synchronize.
2799 class V8EXPORT Isolate {
2802 * Stack-allocated class which sets the isolate for all operations
2803 * executed within a local scope.
2805 class V8EXPORT Scope {
2807 explicit Scope(Isolate* isolate) : isolate_(isolate) {
2811 ~Scope() { isolate_->Exit(); }
2814 Isolate* const isolate_;
2816 // Prevent copying of Scope objects.
2817 Scope(const Scope&);
2818 Scope& operator=(const Scope&);
2822 * Creates a new isolate. Does not change the currently entered
2825 * When an isolate is no longer used its resources should be freed
2826 * by calling Dispose(). Using the delete operator is not allowed.
2828 static Isolate* New();
2831 * Returns the entered isolate for the current thread or NULL in
2832 * case there is no current isolate.
2834 static Isolate* GetCurrent();
2837 * Methods below this point require holding a lock (using Locker) in
2838 * a multi-threaded environment.
2842 * Sets this isolate as the entered one for the current thread.
2843 * Saves the previously entered one (if any), so that it can be
2844 * restored when exiting. Re-entering an isolate is allowed.
2849 * Exits this isolate by restoring the previously entered one in the
2850 * current thread. The isolate may still stay the same, if it was
2851 * entered more than once.
2853 * Requires: this == Isolate::GetCurrent().
2858 * Disposes the isolate. The isolate must not be entered by any
2859 * thread to be disposable.
2864 * Associate embedder-specific data with the isolate
2866 void SetData(void* data);
2869 * Retrive embedder-specific data from the isolate.
2870 * Returns NULL if SetData has never been called.
2876 Isolate(const Isolate&);
2878 Isolate& operator=(const Isolate&);
2879 void* operator new(size_t size);
2880 void operator delete(void*, size_t);
2886 enum CompressionAlgorithm {
2892 int compressed_size;
2898 * A helper class for driving V8 startup data decompression. It is based on
2899 * "CompressedStartupData" API functions from the V8 class. It isn't mandatory
2900 * for an embedder to use this class, instead, API functions can be used
2903 * For an example of the class usage, see the "shell.cc" sample application.
2905 class V8EXPORT StartupDataDecompressor { // NOLINT
2907 StartupDataDecompressor();
2908 virtual ~StartupDataDecompressor();
2912 virtual int DecompressData(char* raw_data,
2914 const char* compressed_data,
2915 int compressed_data_size) = 0;
2923 * EntropySource is used as a callback function when v8 needs a source
2926 typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
2929 * Container class for static utility functions.
2933 /** Set the callback to invoke in case of fatal errors. */
2934 static void SetFatalErrorHandler(FatalErrorCallback that);
2937 * Set the callback to invoke to check if code generation from
2938 * strings should be allowed.
2940 static void SetAllowCodeGenerationFromStringsCallback(
2941 AllowCodeGenerationFromStringsCallback that);
2944 * Ignore out-of-memory exceptions.
2946 * V8 running out of memory is treated as a fatal error by default.
2947 * This means that the fatal error handler is called and that V8 is
2950 * IgnoreOutOfMemoryException can be used to not treat an
2951 * out-of-memory situation as a fatal error. This way, the contexts
2952 * that did not cause the out of memory problem might be able to
2953 * continue execution.
2955 static void IgnoreOutOfMemoryException();
2958 * Check if V8 is dead and therefore unusable. This is the case after
2959 * fatal errors such as out-of-memory situations.
2961 static bool IsDead();
2964 * The following 4 functions are to be used when V8 is built with
2965 * the 'compress_startup_data' flag enabled. In this case, the
2966 * embedder must decompress startup data prior to initializing V8.
2968 * This is how interaction with V8 should look like:
2969 * int compressed_data_count = v8::V8::GetCompressedStartupDataCount();
2970 * v8::StartupData* compressed_data =
2971 * new v8::StartupData[compressed_data_count];
2972 * v8::V8::GetCompressedStartupData(compressed_data);
2973 * ... decompress data (compressed_data can be updated in-place) ...
2974 * v8::V8::SetDecompressedStartupData(compressed_data);
2975 * ... now V8 can be initialized
2976 * ... make sure the decompressed data stays valid until V8 shutdown
2978 * A helper class StartupDataDecompressor is provided. It implements
2979 * the protocol of the interaction described above, and can be used in
2980 * most cases instead of calling these API functions directly.
2982 static StartupData::CompressionAlgorithm GetCompressedStartupDataAlgorithm();
2983 static int GetCompressedStartupDataCount();
2984 static void GetCompressedStartupData(StartupData* compressed_data);
2985 static void SetDecompressedStartupData(StartupData* decompressed_data);
2988 * Adds a message listener.
2990 * The same message listener can be added more than once and in that
2991 * case it will be called more than once for each message.
2993 static bool AddMessageListener(MessageCallback that,
2994 Handle<Value> data = Handle<Value>());
2997 * Remove all message listeners from the specified callback function.
2999 static void RemoveMessageListeners(MessageCallback that);
3002 * Tells V8 to capture current stack trace when uncaught exception occurs
3003 * and report it to the message listeners. The option is off by default.
3005 static void SetCaptureStackTraceForUncaughtExceptions(
3007 int frame_limit = 10,
3008 StackTrace::StackTraceOptions options = StackTrace::kOverview);
3011 * Sets V8 flags from a string.
3013 static void SetFlagsFromString(const char* str, int length);
3016 * Sets V8 flags from the command line.
3018 static void SetFlagsFromCommandLine(int* argc,
3022 /** Get the version string. */
3023 static const char* GetVersion();
3026 * Enables the host application to provide a mechanism for recording
3027 * statistics counters.
3029 static void SetCounterFunction(CounterLookupCallback);
3032 * Enables the host application to provide a mechanism for recording
3033 * histograms. The CreateHistogram function returns a
3034 * histogram which will later be passed to the AddHistogramSample
3037 static void SetCreateHistogramFunction(CreateHistogramCallback);
3038 static void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
3041 * Enables the computation of a sliding window of states. The sliding
3042 * window information is recorded in statistics counters.
3044 static void EnableSlidingStateWindow();
3046 /** Callback function for reporting failed access checks.*/
3047 static void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
3050 * Enables the host application to receive a notification before a
3051 * garbage collection. Allocations are not allowed in the
3052 * callback function, you therefore cannot manipulate objects (set
3053 * or delete properties for example) since it is possible such
3054 * operations will result in the allocation of objects. It is possible
3055 * to specify the GCType filter for your callback. But it is not possible to
3056 * register the same callback function two times with different
3059 static void AddGCPrologueCallback(
3060 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
3063 * This function removes callback which was installed by
3064 * AddGCPrologueCallback function.
3066 static void RemoveGCPrologueCallback(GCPrologueCallback callback);
3069 * The function is deprecated. Please use AddGCPrologueCallback instead.
3070 * Enables the host application to receive a notification before a
3071 * garbage collection. Allocations are not allowed in the
3072 * callback function, you therefore cannot manipulate objects (set
3073 * or delete properties for example) since it is possible such
3074 * operations will result in the allocation of objects.
3076 static void SetGlobalGCPrologueCallback(GCCallback);
3079 * Enables the host application to receive a notification after a
3080 * garbage collection. Allocations are not allowed in the
3081 * callback function, you therefore cannot manipulate objects (set
3082 * or delete properties for example) since it is possible such
3083 * operations will result in the allocation of objects. It is possible
3084 * to specify the GCType filter for your callback. But it is not possible to
3085 * register the same callback function two times with different
3088 static void AddGCEpilogueCallback(
3089 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
3092 * This function removes callback which was installed by
3093 * AddGCEpilogueCallback function.
3095 static void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
3098 * The function is deprecated. Please use AddGCEpilogueCallback instead.
3099 * Enables the host application to receive a notification after a
3100 * major garbage collection. Allocations are not allowed in the
3101 * callback function, you therefore cannot manipulate objects (set
3102 * or delete properties for example) since it is possible such
3103 * operations will result in the allocation of objects.
3105 static void SetGlobalGCEpilogueCallback(GCCallback);
3108 * Enables the host application to provide a mechanism to be notified
3109 * and perform custom logging when V8 Allocates Executable Memory.
3111 static void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
3113 AllocationAction action);
3116 * This function removes callback which was installed by
3117 * AddMemoryAllocationCallback function.
3119 static void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
3122 * Allows the host application to group objects together. If one
3123 * object in the group is alive, all objects in the group are alive.
3124 * After each garbage collection, object groups are removed. It is
3125 * intended to be used in the before-garbage-collection callback
3126 * function, for instance to simulate DOM tree connections among JS
3128 * See v8-profiler.h for RetainedObjectInfo interface description.
3130 static void AddObjectGroup(Persistent<Value>* objects,
3132 RetainedObjectInfo* info = NULL);
3135 * Allows the host application to declare implicit references between
3136 * the objects: if |parent| is alive, all |children| are alive too.
3137 * After each garbage collection, all implicit references
3138 * are removed. It is intended to be used in the before-garbage-collection
3139 * callback function.
3141 static void AddImplicitReferences(Persistent<Object> parent,
3142 Persistent<Value>* children,
3146 * Initializes from snapshot if possible. Otherwise, attempts to
3147 * initialize from scratch. This function is called implicitly if
3148 * you use the API without calling it first.
3150 static bool Initialize();
3153 * Allows the host application to provide a callback which can be used
3154 * as a source of entropy for random number generators.
3156 static void SetEntropySource(EntropySource source);
3159 * Adjusts the amount of registered external memory. Used to give
3160 * V8 an indication of the amount of externally allocated memory
3161 * that is kept alive by JavaScript objects. V8 uses this to decide
3162 * when to perform global garbage collections. Registering
3163 * externally allocated memory will trigger global garbage
3164 * collections more often than otherwise in an attempt to garbage
3165 * collect the JavaScript objects keeping the externally allocated
3168 * \param change_in_bytes the change in externally allocated memory
3169 * that is kept alive by JavaScript objects.
3170 * \returns the adjusted value.
3172 static int AdjustAmountOfExternalAllocatedMemory(int change_in_bytes);
3175 * Suspends recording of tick samples in the profiler.
3176 * When the V8 profiling mode is enabled (usually via command line
3177 * switches) this function suspends recording of tick samples.
3178 * Profiling ticks are discarded until ResumeProfiler() is called.
3180 * See also the --prof and --prof_auto command line switches to
3181 * enable V8 profiling.
3183 static void PauseProfiler();
3186 * Resumes recording of tick samples in the profiler.
3187 * See also PauseProfiler().
3189 static void ResumeProfiler();
3192 * Return whether profiler is currently paused.
3194 static bool IsProfilerPaused();
3197 * Retrieve the V8 thread id of the calling thread.
3199 * The thread id for a thread should only be retrieved after the V8
3200 * lock has been acquired with a Locker object with that thread.
3202 static int GetCurrentThreadId();
3205 * Forcefully terminate execution of a JavaScript thread. This can
3206 * be used to terminate long-running scripts.
3208 * TerminateExecution should only be called when then V8 lock has
3209 * been acquired with a Locker object. Therefore, in order to be
3210 * able to terminate long-running threads, preemption must be
3211 * enabled to allow the user of TerminateExecution to acquire the
3214 * The termination is achieved by throwing an exception that is
3215 * uncatchable by JavaScript exception handlers. Termination
3216 * exceptions act as if they were caught by a C++ TryCatch exception
3217 * handler. If forceful termination is used, any C++ TryCatch
3218 * exception handler that catches an exception should check if that
3219 * exception is a termination exception and immediately return if
3220 * that is the case. Returning immediately in that case will
3221 * continue the propagation of the termination exception if needed.
3223 * The thread id passed to TerminateExecution must have been
3224 * obtained by calling GetCurrentThreadId on the thread in question.
3226 * \param thread_id The thread id of the thread to terminate.
3228 static void TerminateExecution(int thread_id);
3231 * Forcefully terminate the current thread of JavaScript execution
3232 * in the given isolate. If no isolate is provided, the default
3235 * This method can be used by any thread even if that thread has not
3236 * acquired the V8 lock with a Locker object.
3238 * \param isolate The isolate in which to terminate the current JS execution.
3240 static void TerminateExecution(Isolate* isolate = NULL);
3243 * Is V8 terminating JavaScript execution.
3245 * Returns true if JavaScript execution is currently terminating
3246 * because of a call to TerminateExecution. In that case there are
3247 * still JavaScript frames on the stack and the termination
3248 * exception is still active.
3250 * \param isolate The isolate in which to check.
3252 static bool IsExecutionTerminating(Isolate* isolate = NULL);
3255 * Releases any resources used by v8 and stops any utility threads
3256 * that may be running. Note that disposing v8 is permanent, it
3257 * cannot be reinitialized.
3259 * It should generally not be necessary to dispose v8 before exiting
3260 * a process, this should happen automatically. It is only necessary
3261 * to use if the process needs the resources taken up by v8.
3263 static bool Dispose();
3266 * Get statistics about the heap memory usage.
3268 static void GetHeapStatistics(HeapStatistics* heap_statistics);
3271 * Optional notification that the embedder is idle.
3272 * V8 uses the notification to reduce memory footprint.
3273 * This call can be used repeatedly if the embedder remains idle.
3274 * Returns true if the embedder should stop calling IdleNotification
3275 * until real work has been done. This indicates that V8 has done
3276 * as much cleanup as it will be able to do.
3278 static bool IdleNotification();
3281 * Optional notification that the system is running low on memory.
3282 * V8 uses these notifications to attempt to free memory.
3284 static void LowMemoryNotification();
3287 * Optional notification that a context has been disposed. V8 uses
3288 * these notifications to guide the GC heuristic. Returns the number
3289 * of context disposals - including this one - since the last time
3290 * V8 had a chance to clean up.
3292 static int ContextDisposedNotification();
3297 static internal::Object** GlobalizeReference(internal::Object** handle);
3298 static void DisposeGlobal(internal::Object** global_handle);
3299 static void MakeWeak(internal::Object** global_handle,
3301 WeakReferenceCallback);
3302 static void ClearWeak(internal::Object** global_handle);
3303 static void MarkIndependent(internal::Object** global_handle);
3304 static bool IsGlobalNearDeath(internal::Object** global_handle);
3305 static bool IsGlobalWeak(internal::Object** global_handle);
3306 static void SetWrapperClassId(internal::Object** global_handle,
3309 template <class T> friend class Handle;
3310 template <class T> friend class Local;
3311 template <class T> friend class Persistent;
3312 friend class Context;
3317 * An external exception handler.
3319 class V8EXPORT TryCatch {
3322 * Creates a new try/catch block and registers it with v8.
3327 * Unregisters and deletes this try/catch block.
3332 * Returns true if an exception has been caught by this try/catch block.
3334 bool HasCaught() const;
3337 * For certain types of exceptions, it makes no sense to continue
3340 * Currently, the only type of exception that can be caught by a
3341 * TryCatch handler and for which it does not make sense to continue
3342 * is termination exception. Such exceptions are thrown when the
3343 * TerminateExecution methods are called to terminate a long-running
3346 * If CanContinue returns false, the correct action is to perform
3347 * any C++ cleanup needed and then return.
3349 bool CanContinue() const;
3352 * Throws the exception caught by this TryCatch in a way that avoids
3353 * it being caught again by this same TryCatch. As with ThrowException
3354 * it is illegal to execute any JavaScript operations after calling
3355 * ReThrow; the caller must return immediately to where the exception
3358 Handle<Value> ReThrow();
3361 * Returns the exception caught by this try/catch block. If no exception has
3362 * been caught an empty handle is returned.
3364 * The returned handle is valid until this TryCatch block has been destroyed.
3366 Local<Value> Exception() const;
3369 * Returns the .stack property of the thrown object. If no .stack
3370 * property is present an empty handle is returned.
3372 Local<Value> StackTrace() const;
3375 * Returns the message associated with this exception. If there is
3376 * no message associated an empty handle is returned.
3378 * The returned handle is valid until this TryCatch block has been
3381 Local<v8::Message> Message() const;
3384 * Clears any exceptions that may have been caught by this try/catch block.
3385 * After this method has been called, HasCaught() will return false.
3387 * It is not necessary to clear a try/catch block before using it again; if
3388 * another exception is thrown the previously caught exception will just be
3389 * overwritten. However, it is often a good idea since it makes it easier
3390 * to determine which operation threw a given exception.
3395 * Set verbosity of the external exception handler.
3397 * By default, exceptions that are caught by an external exception
3398 * handler are not reported. Call SetVerbose with true on an
3399 * external exception handler to have exceptions caught by the
3400 * handler reported as if they were not caught.
3402 void SetVerbose(bool value);
3405 * Set whether or not this TryCatch should capture a Message object
3406 * which holds source information about where the exception
3407 * occurred. True by default.
3409 void SetCaptureMessage(bool value);
3412 v8::internal::Isolate* isolate_;
3416 bool is_verbose_ : 1;
3417 bool can_continue_ : 1;
3418 bool capture_message_ : 1;
3421 friend class v8::internal::Isolate;
3431 class V8EXPORT ExtensionConfiguration {
3433 ExtensionConfiguration(int name_count, const char* names[])
3434 : name_count_(name_count), names_(names) { }
3436 friend class ImplementationUtilities;
3438 const char** names_;
3443 * A sandboxed execution context with its own set of built-in objects
3446 class V8EXPORT Context {
3449 * Returns the global proxy object or global object itself for
3450 * detached contexts.
3452 * Global proxy object is a thin wrapper whose prototype points to
3453 * actual context's global object with the properties like Object, etc.
3454 * This is done that way for security reasons (for more details see
3455 * https://wiki.mozilla.org/Gecko:SplitWindow).
3457 * Please note that changes to global proxy object prototype most probably
3458 * would break VM---v8 expects only global object as a prototype of
3459 * global proxy object.
3461 * If DetachGlobal() has been invoked, Global() would return actual global
3462 * object until global is reattached with ReattachGlobal().
3464 Local<Object> Global();
3467 * Detaches the global object from its context before
3468 * the global object can be reused to create a new context.
3470 void DetachGlobal();
3473 * Reattaches a global object to a context. This can be used to
3474 * restore the connection between a global object and a context
3475 * after DetachGlobal has been called.
3477 * \param global_object The global object to reattach to the
3478 * context. For this to work, the global object must be the global
3479 * object that was associated with this context before a call to
3482 void ReattachGlobal(Handle<Object> global_object);
3484 /** Creates a new context.
3486 * Returns a persistent handle to the newly allocated context. This
3487 * persistent handle has to be disposed when the context is no
3488 * longer used so the context can be garbage collected.
3490 * \param extensions An optional extension configuration containing
3491 * the extensions to be installed in the newly created context.
3493 * \param global_template An optional object template from which the
3494 * global object for the newly created context will be created.
3496 * \param global_object An optional global object to be reused for
3497 * the newly created context. This global object must have been
3498 * created by a previous call to Context::New with the same global
3499 * template. The state of the global object will be completely reset
3500 * and only object identify will remain.
3502 static Persistent<Context> New(
3503 ExtensionConfiguration* extensions = NULL,
3504 Handle<ObjectTemplate> global_template = Handle<ObjectTemplate>(),
3505 Handle<Value> global_object = Handle<Value>());
3507 /** Returns the last entered context. */
3508 static Local<Context> GetEntered();
3510 /** Returns the context that is on the top of the stack. */
3511 static Local<Context> GetCurrent();
3514 * Returns the context of the calling JavaScript code. That is the
3515 * context of the top-most JavaScript frame. If there are no
3516 * JavaScript frames an empty handle is returned.
3518 static Local<Context> GetCalling();
3519 static Local<Object> GetCallingQmlGlobal();
3520 static Local<Value> GetCallingScriptData();
3523 * Sets the security token for the context. To access an object in
3524 * another context, the security tokens must match.
3526 void SetSecurityToken(Handle<Value> token);
3528 /** Restores the security token to the default value. */
3529 void UseDefaultSecurityToken();
3531 /** Returns the security token of this context.*/
3532 Handle<Value> GetSecurityToken();
3535 * Enter this context. After entering a context, all code compiled
3536 * and run is compiled and run in this context. If another context
3537 * is already entered, this old context is saved so it can be
3538 * restored when the new context is exited.
3543 * Exit this context. Exiting the current context restores the
3544 * context that was in place when entering the current context.
3548 /** Returns true if the context has experienced an out of memory situation. */
3549 bool HasOutOfMemoryException();
3551 /** Returns true if V8 has a current context. */
3552 static bool InContext();
3555 * Associate an additional data object with the context. This is mainly used
3556 * with the debugger to provide additional information on the context through
3559 void SetData(Handle<String> data);
3560 Local<Value> GetData();
3563 * Control whether code generation from strings is allowed. Calling
3564 * this method with false will disable 'eval' and the 'Function'
3565 * constructor for code running in this context. If 'eval' or the
3566 * 'Function' constructor are used an exception will be thrown.
3568 * If code generation from strings is not allowed the
3569 * V8::AllowCodeGenerationFromStrings callback will be invoked if
3570 * set before blocking the call to 'eval' or the 'Function'
3571 * constructor. If that callback returns true, the call will be
3572 * allowed, otherwise an exception will be thrown. If no callback is
3573 * set an exception will be thrown.
3575 void AllowCodeGenerationFromStrings(bool allow);
3578 * Stack-allocated class which sets the execution context for all
3579 * operations executed within a local scope.
3583 explicit inline Scope(Handle<Context> context) : context_(context) {
3586 inline ~Scope() { context_->Exit(); }
3588 Handle<Context> context_;
3593 friend class Script;
3594 friend class Object;
3595 friend class Function;
3600 * Multiple threads in V8 are allowed, but only one thread at a time
3601 * is allowed to use any given V8 isolate. See Isolate class
3602 * comments. The definition of 'using V8 isolate' includes
3603 * accessing handles or holding onto object pointers obtained
3604 * from V8 handles while in the particular V8 isolate. It is up
3605 * to the user of V8 to ensure (perhaps with locking) that this
3606 * constraint is not violated.
3608 * v8::Locker is a scoped lock object. While it's
3609 * active (i.e. between its construction and destruction) the current thread is
3610 * allowed to use the locked isolate. V8 guarantees that an isolate can be
3611 * locked by at most one thread at any time. In other words, the scope of a
3612 * v8::Locker is a critical section.
3618 * v8::Locker locker(isolate);
3619 * v8::Isolate::Scope isolate_scope(isolate);
3621 * // Code using V8 and isolate goes here.
3623 * } // Destructor called here
3626 * If you wish to stop using V8 in a thread A you can do this either
3627 * by destroying the v8::Locker object as above or by constructing a
3628 * v8::Unlocker object:
3633 * v8::Unlocker unlocker(isolate);
3635 * // Code not using V8 goes here while V8 can run in another thread.
3637 * } // Destructor called here.
3641 * The Unlocker object is intended for use in a long-running callback
3642 * from V8, where you want to release the V8 lock for other threads to
3645 * The v8::Locker is a recursive lock. That is, you can lock more than
3646 * once in a given thread. This can be useful if you have code that can
3647 * be called either from code that holds the lock or from code that does
3648 * not. The Unlocker is not recursive so you can not have several
3649 * Unlockers on the stack at once, and you can not use an Unlocker in a
3650 * thread that is not inside a Locker's scope.
3652 * An unlocker will unlock several lockers if it has to and reinstate
3653 * the correct depth of locking on its destruction. eg.:
3658 * v8::Locker locker(isolate);
3659 * Isolate::Scope isolate_scope(isolate);
3662 * v8::Locker another_locker(isolate);
3663 * // V8 still locked (2 levels).
3666 * v8::Unlocker unlocker(isolate);
3670 * // V8 locked again (2 levels).
3672 * // V8 still locked (1 level).
3674 * // V8 Now no longer locked.
3679 class V8EXPORT Unlocker {
3682 * Initialize Unlocker for a given Isolate. NULL means default isolate.
3684 explicit Unlocker(Isolate* isolate = NULL);
3687 internal::Isolate* isolate_;
3691 class V8EXPORT Locker {
3694 * Initialize Locker for a given Isolate. NULL means default isolate.
3696 explicit Locker(Isolate* isolate = NULL);
3702 * When preemption is started, a timer is fired every n milliseconds
3703 * that will switch between multiple threads that are in contention
3706 static void StartPreemption(int every_n_ms);
3711 static void StopPreemption();
3714 * Returns whether or not the locker for a given isolate, or default isolate
3715 * if NULL is given, is locked by the current thread.
3717 static bool IsLocked(Isolate* isolate = NULL);
3720 * Returns whether v8::Locker is being used by this V8 instance.
3722 static bool IsActive();
3727 internal::Isolate* isolate_;
3729 static bool active_;
3731 // Disallow copying and assigning.
3732 Locker(const Locker&);
3733 void operator=(const Locker&);
3738 * An interface for exporting data from V8, using "push" model.
3740 class V8EXPORT OutputStream { // NOLINT
3742 enum OutputEncoding {
3743 kAscii = 0 // 7-bit ASCII.
3749 virtual ~OutputStream() {}
3750 /** Notify about the end of stream. */
3751 virtual void EndOfStream() = 0;
3752 /** Get preferred output chunk size. Called only once. */
3753 virtual int GetChunkSize() { return 1024; }
3754 /** Get preferred output encoding. Called only once. */
3755 virtual OutputEncoding GetOutputEncoding() { return kAscii; }
3757 * Writes the next chunk of snapshot data into the stream. Writing
3758 * can be stopped by returning kAbort as function result. EndOfStream
3759 * will not be called in case writing was aborted.
3761 virtual WriteResult WriteAsciiChunk(char* data, int size) = 0;
3766 * An interface for reporting progress and controlling long-running
3769 class V8EXPORT ActivityControl { // NOLINT
3771 enum ControlOption {
3775 virtual ~ActivityControl() {}
3777 * Notify about current progress. The activity can be stopped by
3778 * returning kAbort as the callback result.
3780 virtual ControlOption ReportProgressValue(int done, int total) = 0;
3784 // --- Implementation ---
3787 namespace internal {
3789 static const int kApiPointerSize = sizeof(void*); // NOLINT
3790 static const int kApiIntSize = sizeof(int); // NOLINT
3792 // Tag information for HeapObject.
3793 const int kHeapObjectTag = 1;
3794 const int kHeapObjectTagSize = 2;
3795 const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
3797 // Tag information for Smi.
3798 const int kSmiTag = 0;
3799 const int kSmiTagSize = 1;
3800 const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
3802 template <size_t ptr_size> struct SmiTagging;
3804 // Smi constants for 32-bit systems.
3805 template <> struct SmiTagging<4> {
3806 static const int kSmiShiftSize = 0;
3807 static const int kSmiValueSize = 31;
3808 static inline int SmiToInt(internal::Object* value) {
3809 int shift_bits = kSmiTagSize + kSmiShiftSize;
3810 // Throw away top 32 bits and shift down (requires >> to be sign extending).
3811 return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
3814 // For 32-bit systems any 2 bytes aligned pointer can be encoded as smi
3815 // with a plain reinterpret_cast.
3816 static const uintptr_t kEncodablePointerMask = 0x1;
3817 static const int kPointerToSmiShift = 0;
3820 // Smi constants for 64-bit systems.
3821 template <> struct SmiTagging<8> {
3822 static const int kSmiShiftSize = 31;
3823 static const int kSmiValueSize = 32;
3824 static inline int SmiToInt(internal::Object* value) {
3825 int shift_bits = kSmiTagSize + kSmiShiftSize;
3826 // Shift down and throw away top 32 bits.
3827 return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
3830 // To maximize the range of pointers that can be encoded
3831 // in the available 32 bits, we require them to be 8 bytes aligned.
3832 // This gives 2 ^ (32 + 3) = 32G address space covered.
3833 // It might be not enough to cover stack allocated objects on some platforms.
3834 static const int kPointerAlignment = 3;
3836 static const uintptr_t kEncodablePointerMask =
3837 ~(uintptr_t(0xffffffff) << kPointerAlignment);
3839 static const int kPointerToSmiShift =
3840 kSmiTagSize + kSmiShiftSize - kPointerAlignment;
3843 typedef SmiTagging<kApiPointerSize> PlatformSmiTagging;
3844 const int kSmiShiftSize = PlatformSmiTagging::kSmiShiftSize;
3845 const int kSmiValueSize = PlatformSmiTagging::kSmiValueSize;
3846 const uintptr_t kEncodablePointerMask =
3847 PlatformSmiTagging::kEncodablePointerMask;
3848 const int kPointerToSmiShift = PlatformSmiTagging::kPointerToSmiShift;
3850 template <size_t ptr_size> struct InternalConstants;
3852 // Internal constants for 32-bit systems.
3853 template <> struct InternalConstants<4> {
3854 static const int kStringResourceOffset = 3 * kApiPointerSize;
3857 // Internal constants for 64-bit systems.
3858 template <> struct InternalConstants<8> {
3859 static const int kStringResourceOffset = 3 * kApiPointerSize;
3863 * This class exports constants and functionality from within v8 that
3864 * is necessary to implement inline functions in the v8 api. Don't
3865 * depend on functions and constants defined here.
3869 // These values match non-compiler-dependent values defined within
3870 // the implementation of v8.
3871 static const int kHeapObjectMapOffset = 0;
3872 static const int kMapInstanceTypeOffset = 1 * kApiPointerSize + kApiIntSize;
3873 static const int kStringResourceOffset =
3874 InternalConstants<kApiPointerSize>::kStringResourceOffset;
3876 static const int kForeignAddressOffset = kApiPointerSize;
3877 static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
3878 static const int kFullStringRepresentationMask = 0x07;
3879 static const int kExternalTwoByteRepresentationTag = 0x02;
3881 static const int kJSObjectType = 0xa6;
3882 static const int kFirstNonstringType = 0x80;
3883 static const int kForeignType = 0x85;
3885 static inline bool HasHeapObjectTag(internal::Object* value) {
3886 return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
3890 static inline bool HasSmiTag(internal::Object* value) {
3891 return ((reinterpret_cast<intptr_t>(value) & kSmiTagMask) == kSmiTag);
3894 static inline int SmiValue(internal::Object* value) {
3895 return PlatformSmiTagging::SmiToInt(value);
3898 static inline int GetInstanceType(internal::Object* obj) {
3899 typedef internal::Object O;
3900 O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
3901 return ReadField<uint8_t>(map, kMapInstanceTypeOffset);
3904 static inline void* GetExternalPointerFromSmi(internal::Object* value) {
3905 const uintptr_t address = reinterpret_cast<uintptr_t>(value);
3906 return reinterpret_cast<void*>(address >> kPointerToSmiShift);
3909 static inline void* GetExternalPointer(internal::Object* obj) {
3910 if (HasSmiTag(obj)) {
3911 return GetExternalPointerFromSmi(obj);
3912 } else if (GetInstanceType(obj) == kForeignType) {
3913 return ReadField<void*>(obj, kForeignAddressOffset);
3919 static inline bool IsExternalTwoByteString(int instance_type) {
3920 int representation = (instance_type & kFullStringRepresentationMask);
3921 return representation == kExternalTwoByteRepresentationTag;
3924 template <typename T>
3925 static inline T ReadField(Object* ptr, int offset) {
3926 uint8_t* addr = reinterpret_cast<uint8_t*>(ptr) + offset - kHeapObjectTag;
3927 return *reinterpret_cast<T*>(addr);
3930 static inline bool CanCastToHeapObject(void* o) { return false; }
3931 static inline bool CanCastToHeapObject(Context* o) { return true; }
3932 static inline bool CanCastToHeapObject(String* o) { return true; }
3933 static inline bool CanCastToHeapObject(Object* o) { return true; }
3934 static inline bool CanCastToHeapObject(Message* o) { return true; }
3935 static inline bool CanCastToHeapObject(StackTrace* o) { return true; }
3936 static inline bool CanCastToHeapObject(StackFrame* o) { return true; }
3939 } // namespace internal
3943 Local<T>::Local() : Handle<T>() { }
3947 Local<T> Local<T>::New(Handle<T> that) {
3948 if (that.IsEmpty()) return Local<T>();
3949 T* that_ptr = *that;
3950 internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
3951 if (internal::Internals::CanCastToHeapObject(that_ptr)) {
3952 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
3953 reinterpret_cast<internal::HeapObject*>(*p))));
3955 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(*p)));
3960 Persistent<T> Persistent<T>::New(Handle<T> that) {
3961 if (that.IsEmpty()) return Persistent<T>();
3962 internal::Object** p = reinterpret_cast<internal::Object**>(*that);
3963 return Persistent<T>(reinterpret_cast<T*>(V8::GlobalizeReference(p)));
3968 bool Persistent<T>::IsNearDeath() const {
3969 if (this->IsEmpty()) return false;
3970 return V8::IsGlobalNearDeath(reinterpret_cast<internal::Object**>(**this));
3975 bool Persistent<T>::IsWeak() const {
3976 if (this->IsEmpty()) return false;
3977 return V8::IsGlobalWeak(reinterpret_cast<internal::Object**>(**this));
3982 void Persistent<T>::Dispose() {
3983 if (this->IsEmpty()) return;
3984 V8::DisposeGlobal(reinterpret_cast<internal::Object**>(**this));
3989 Persistent<T>::Persistent() : Handle<T>() { }
3992 void Persistent<T>::MakeWeak(void* parameters, WeakReferenceCallback callback) {
3993 V8::MakeWeak(reinterpret_cast<internal::Object**>(**this),
3999 void Persistent<T>::ClearWeak() {
4000 V8::ClearWeak(reinterpret_cast<internal::Object**>(**this));
4004 void Persistent<T>::MarkIndependent() {
4005 V8::MarkIndependent(reinterpret_cast<internal::Object**>(**this));
4009 void Persistent<T>::SetWrapperClassId(uint16_t class_id) {
4010 V8::SetWrapperClassId(reinterpret_cast<internal::Object**>(**this), class_id);
4013 Arguments::Arguments(internal::Object** implicit_args,
4014 internal::Object** values, int length,
4015 bool is_construct_call)
4016 : implicit_args_(implicit_args),
4019 is_construct_call_(is_construct_call) { }
4022 Local<Value> Arguments::operator[](int i) const {
4023 if (i < 0 || length_ <= i) return Local<Value>(*Undefined());
4024 return Local<Value>(reinterpret_cast<Value*>(values_ - i));
4028 Local<Function> Arguments::Callee() const {
4029 return Local<Function>(reinterpret_cast<Function*>(
4030 &implicit_args_[kCalleeIndex]));
4034 Local<Object> Arguments::This() const {
4035 return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
4039 Local<Object> Arguments::Holder() const {
4040 return Local<Object>(reinterpret_cast<Object*>(
4041 &implicit_args_[kHolderIndex]));
4045 Local<Value> Arguments::Data() const {
4046 return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
4050 bool Arguments::IsConstructCall() const {
4051 return is_construct_call_;
4055 int Arguments::Length() const {
4061 Local<T> HandleScope::Close(Handle<T> value) {
4062 internal::Object** before = reinterpret_cast<internal::Object**>(*value);
4063 internal::Object** after = RawClose(before);
4064 return Local<T>(reinterpret_cast<T*>(after));
4067 Handle<Value> ScriptOrigin::ResourceName() const {
4068 return resource_name_;
4072 Handle<Integer> ScriptOrigin::ResourceLineOffset() const {
4073 return resource_line_offset_;
4077 Handle<Integer> ScriptOrigin::ResourceColumnOffset() const {
4078 return resource_column_offset_;
4082 Handle<Boolean> Boolean::New(bool value) {
4083 return value ? True() : False();
4087 void Template::Set(const char* name, v8::Handle<Data> value) {
4088 Set(v8::String::New(name), value);
4092 Local<Value> Object::GetInternalField(int index) {
4093 #ifndef V8_ENABLE_CHECKS
4094 Local<Value> quick_result = UncheckedGetInternalField(index);
4095 if (!quick_result.IsEmpty()) return quick_result;
4097 return CheckedGetInternalField(index);
4101 Local<Value> Object::UncheckedGetInternalField(int index) {
4102 typedef internal::Object O;
4103 typedef internal::Internals I;
4104 O* obj = *reinterpret_cast<O**>(this);
4105 if (I::GetInstanceType(obj) == I::kJSObjectType) {
4106 // If the object is a plain JSObject, which is the common case,
4107 // we know where to find the internal fields and can return the
4109 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
4110 O* value = I::ReadField<O*>(obj, offset);
4111 O** result = HandleScope::CreateHandle(value);
4112 return Local<Value>(reinterpret_cast<Value*>(result));
4114 return Local<Value>();
4119 void* External::Unwrap(Handle<v8::Value> obj) {
4120 #ifdef V8_ENABLE_CHECKS
4121 return FullUnwrap(obj);
4123 return QuickUnwrap(obj);
4128 void* External::QuickUnwrap(Handle<v8::Value> wrapper) {
4129 typedef internal::Object O;
4130 O* obj = *reinterpret_cast<O**>(const_cast<v8::Value*>(*wrapper));
4131 return internal::Internals::GetExternalPointer(obj);
4135 void* Object::GetPointerFromInternalField(int index) {
4136 typedef internal::Object O;
4137 typedef internal::Internals I;
4139 O* obj = *reinterpret_cast<O**>(this);
4141 if (I::GetInstanceType(obj) == I::kJSObjectType) {
4142 // If the object is a plain JSObject, which is the common case,
4143 // we know where to find the internal fields and can return the
4145 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
4146 O* value = I::ReadField<O*>(obj, offset);
4147 return I::GetExternalPointer(value);
4150 return SlowGetPointerFromInternalField(index);
4154 String* String::Cast(v8::Value* value) {
4155 #ifdef V8_ENABLE_CHECKS
4158 return static_cast<String*>(value);
4162 String::ExternalStringResource* String::GetExternalStringResource() const {
4163 typedef internal::Object O;
4164 typedef internal::Internals I;
4165 O* obj = *reinterpret_cast<O**>(const_cast<String*>(this));
4166 String::ExternalStringResource* result;
4167 if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
4168 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
4169 result = reinterpret_cast<String::ExternalStringResource*>(value);
4173 #ifdef V8_ENABLE_CHECKS
4174 VerifyExternalStringResource(result);
4180 bool Value::IsString() const {
4181 #ifdef V8_ENABLE_CHECKS
4182 return FullIsString();
4184 return QuickIsString();
4188 bool Value::QuickIsString() const {
4189 typedef internal::Object O;
4190 typedef internal::Internals I;
4191 O* obj = *reinterpret_cast<O**>(const_cast<Value*>(this));
4192 if (!I::HasHeapObjectTag(obj)) return false;
4193 return (I::GetInstanceType(obj) < I::kFirstNonstringType);
4197 Number* Number::Cast(v8::Value* value) {
4198 #ifdef V8_ENABLE_CHECKS
4201 return static_cast<Number*>(value);
4205 Integer* Integer::Cast(v8::Value* value) {
4206 #ifdef V8_ENABLE_CHECKS
4209 return static_cast<Integer*>(value);
4213 Date* Date::Cast(v8::Value* value) {
4214 #ifdef V8_ENABLE_CHECKS
4217 return static_cast<Date*>(value);
4221 StringObject* StringObject::Cast(v8::Value* value) {
4222 #ifdef V8_ENABLE_CHECKS
4225 return static_cast<StringObject*>(value);
4229 NumberObject* NumberObject::Cast(v8::Value* value) {
4230 #ifdef V8_ENABLE_CHECKS
4233 return static_cast<NumberObject*>(value);
4237 BooleanObject* BooleanObject::Cast(v8::Value* value) {
4238 #ifdef V8_ENABLE_CHECKS
4241 return static_cast<BooleanObject*>(value);
4245 RegExp* RegExp::Cast(v8::Value* value) {
4246 #ifdef V8_ENABLE_CHECKS
4249 return static_cast<RegExp*>(value);
4253 Object* Object::Cast(v8::Value* value) {
4254 #ifdef V8_ENABLE_CHECKS
4257 return static_cast<Object*>(value);
4261 Array* Array::Cast(v8::Value* value) {
4262 #ifdef V8_ENABLE_CHECKS
4265 return static_cast<Array*>(value);
4269 Function* Function::Cast(v8::Value* value) {
4270 #ifdef V8_ENABLE_CHECKS
4273 return static_cast<Function*>(value);
4277 External* External::Cast(v8::Value* value) {
4278 #ifdef V8_ENABLE_CHECKS
4281 return static_cast<External*>(value);
4285 Local<Value> AccessorInfo::Data() const {
4286 return Local<Value>(reinterpret_cast<Value*>(&args_[-2]));
4290 Local<Object> AccessorInfo::This() const {
4291 return Local<Object>(reinterpret_cast<Object*>(&args_[0]));
4295 Local<Object> AccessorInfo::Holder() const {
4296 return Local<Object>(reinterpret_cast<Object*>(&args_[-1]));
4302 * A simple shell that takes a list of expressions on the
4303 * command-line and executes them.
4308 * \example process.cc