1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 /** \mainpage V8 API Reference Guide
7 * V8 is Google's open source JavaScript engine.
9 * This set of documents provides reference material generated from the
10 * V8 header file, include/v8.h.
12 * For other documentation see http://code.google.com/apis/v8/
20 // We reserve the V8_* prefix for macros defined in V8 public API and
21 // assume there are no name conflicts with the embedder's code.
25 // Setup for Windows DLL export/import. When building the V8 DLL the
26 // BUILDING_V8_SHARED needs to be defined. When building a program which uses
27 // the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8
28 // static library or building a program which uses the V8 static library neither
29 // BUILDING_V8_SHARED nor USING_V8_SHARED should be defined.
30 #if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED)
31 #error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the\
32 build configuration to ensure that at most one of these is set
35 #ifdef BUILDING_V8_SHARED
36 # define V8_EXPORT __declspec(dllexport)
38 # define V8_EXPORT __declspec(dllimport)
41 #endif // BUILDING_V8_SHARED
45 // Setup for Linux shared library export.
46 #if V8_HAS_ATTRIBUTE_VISIBILITY && defined(V8_SHARED)
47 # ifdef BUILDING_V8_SHARED
48 # define V8_EXPORT __attribute__ ((visibility("default")))
59 * The v8 JavaScript engine.
63 class AccessorSignature;
71 class DeclaredAccessorDescriptor;
74 class FunctionTemplate;
76 class ImplementationUtilities;
83 class ObjectOperationDescriptor;
87 class RawOperationDescriptor;
100 template <class T> class Handle;
101 template <class T> class Local;
102 template <class T> class Eternal;
103 template<class T> class NonCopyablePersistentTraits;
104 template<class T> class PersistentBase;
106 class M = NonCopyablePersistentTraits<T> > class Persistent;
107 template<class T> class UniquePersistent;
108 template<class K, class V, class T> class PersistentValueMap;
109 template<class V, class T> class PersistentValueVector;
110 template<class T, class P> class WeakCallbackObject;
111 class FunctionTemplate;
112 class ObjectTemplate;
114 template<typename T> class FunctionCallbackInfo;
115 template<typename T> class PropertyCallbackInfo;
119 class DeclaredAccessorDescriptor;
120 class ObjectOperationDescriptor;
121 class RawOperationDescriptor;
122 class CallHandlerHelper;
123 class EscapableHandleScope;
124 template<typename T> class ReturnValue;
132 template<typename T> class CustomArguments;
133 class PropertyCallbackArguments;
134 class FunctionCallbackArguments;
140 * General purpose unique identifier.
144 explicit UniqueId(intptr_t data)
147 bool operator==(const UniqueId& other) const {
148 return data_ == other.data_;
151 bool operator!=(const UniqueId& other) const {
152 return data_ != other.data_;
155 bool operator<(const UniqueId& other) const {
156 return data_ < other.data_;
165 #define TYPE_CHECK(T, S) \
167 *(static_cast<T* volatile*>(0)) = static_cast<S*>(0); \
172 * An object reference managed by the v8 garbage collector.
174 * All objects returned from v8 have to be tracked by the garbage
175 * collector so that it knows that the objects are still alive. Also,
176 * because the garbage collector may move objects, it is unsafe to
177 * point directly to an object. Instead, all objects are stored in
178 * handles which are known by the garbage collector and updated
179 * whenever an object moves. Handles should always be passed by value
180 * (except in cases like out-parameters) and they should never be
181 * allocated on the heap.
183 * There are two types of handles: local and persistent handles.
184 * Local handles are light-weight and transient and typically used in
185 * local operations. They are managed by HandleScopes. Persistent
186 * handles can be used when storing objects across several independent
187 * operations and have to be explicitly deallocated when they're no
190 * It is safe to extract the object stored in the handle by
191 * dereferencing the handle (for instance, to extract the Object* from
192 * a Handle<Object>); the value will still be governed by a handle
193 * behind the scenes and the same rules apply to these values as to
196 template <class T> class Handle {
199 * Creates an empty handle.
201 V8_INLINE Handle() : val_(0) {}
204 * Creates a handle for the contents of the specified handle. This
205 * constructor allows you to pass handles as arguments by value and
206 * to assign between handles. However, if you try to assign between
207 * incompatible handles, for instance from a Handle<String> to a
208 * Handle<Number> it will cause a compile-time error. Assigning
209 * between compatible handles, for instance assigning a
210 * Handle<String> to a variable declared as Handle<Value>, is legal
211 * because String is a subclass of Value.
213 template <class S> V8_INLINE Handle(Handle<S> that)
214 : val_(reinterpret_cast<T*>(*that)) {
216 * This check fails when trying to convert between incompatible
217 * handles. For example, converting from a Handle<String> to a
224 * Returns true if the handle is empty.
226 V8_INLINE bool IsEmpty() const { return val_ == 0; }
229 * Sets the handle to be empty. IsEmpty() will then return true.
231 V8_INLINE void Clear() { val_ = 0; }
233 V8_INLINE T* operator->() const { return val_; }
235 V8_INLINE T* operator*() const { return val_; }
238 * Checks whether two handles are the same.
239 * Returns true if both are empty, or if the objects
240 * to which they refer are identical.
241 * The handles' references are not checked.
243 template <class S> V8_INLINE bool operator==(const Handle<S>& that) const {
244 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
245 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
246 if (a == 0) return b == 0;
247 if (b == 0) return false;
251 template <class S> V8_INLINE bool operator==(
252 const PersistentBase<S>& that) const {
253 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
254 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
255 if (a == 0) return b == 0;
256 if (b == 0) return false;
261 * Checks whether two handles are different.
262 * Returns true if only one of the handles is empty, or if
263 * the objects to which they refer are different.
264 * The handles' references are not checked.
266 template <class S> V8_INLINE bool operator!=(const Handle<S>& that) const {
267 return !operator==(that);
270 template <class S> V8_INLINE bool operator!=(
271 const Persistent<S>& that) const {
272 return !operator==(that);
275 template <class S> V8_INLINE static Handle<T> Cast(Handle<S> that) {
276 #ifdef V8_ENABLE_CHECKS
277 // If we're going to perform the type check then we have to check
278 // that the handle isn't empty before doing the checked cast.
279 if (that.IsEmpty()) return Handle<T>();
281 return Handle<T>(T::Cast(*that));
284 template <class S> V8_INLINE Handle<S> As() {
285 return Handle<S>::Cast(*this);
288 V8_INLINE static Handle<T> New(Isolate* isolate, Handle<T> that) {
289 return New(isolate, that.val_);
291 V8_INLINE static Handle<T> New(Isolate* isolate,
292 const PersistentBase<T>& that) {
293 return New(isolate, that.val_);
298 template<class F, class M> friend class Persistent;
299 template<class F> friend class PersistentBase;
300 template<class F> friend class Handle;
301 template<class F> friend class Local;
302 template<class F> friend class FunctionCallbackInfo;
303 template<class F> friend class PropertyCallbackInfo;
304 template<class F> friend class internal::CustomArguments;
305 friend Handle<Primitive> Undefined(Isolate* isolate);
306 friend Handle<Primitive> Null(Isolate* isolate);
307 friend Handle<Boolean> True(Isolate* isolate);
308 friend Handle<Boolean> False(Isolate* isolate);
309 friend class Context;
310 friend class HandleScope;
312 friend class Private;
315 * Creates a new handle for the specified value.
317 V8_INLINE explicit Handle(T* val) : val_(val) {}
319 V8_INLINE static Handle<T> New(Isolate* isolate, T* that);
326 * A light-weight stack-allocated object handle. All operations
327 * that return objects from within v8 return them in local handles. They
328 * are created within HandleScopes, and all local handles allocated within a
329 * handle scope are destroyed when the handle scope is destroyed. Hence it
330 * is not necessary to explicitly deallocate local handles.
332 template <class T> class Local : public Handle<T> {
335 template <class S> V8_INLINE Local(Local<S> that)
336 : Handle<T>(reinterpret_cast<T*>(*that)) {
338 * This check fails when trying to convert between incompatible
339 * handles. For example, converting from a Handle<String> to a
346 template <class S> V8_INLINE static Local<T> Cast(Local<S> that) {
347 #ifdef V8_ENABLE_CHECKS
348 // If we're going to perform the type check then we have to check
349 // that the handle isn't empty before doing the checked cast.
350 if (that.IsEmpty()) return Local<T>();
352 return Local<T>(T::Cast(*that));
354 template <class S> V8_INLINE Local(Handle<S> that)
355 : Handle<T>(reinterpret_cast<T*>(*that)) {
359 template <class S> V8_INLINE Local<S> As() {
360 return Local<S>::Cast(*this);
364 * Create a local handle for the content of another handle.
365 * The referee is kept alive by the local handle even when
366 * the original handle is destroyed/disposed.
368 V8_INLINE static Local<T> New(Isolate* isolate, Handle<T> that);
369 V8_INLINE static Local<T> New(Isolate* isolate,
370 const PersistentBase<T>& that);
374 template<class F> friend class Eternal;
375 template<class F> friend class PersistentBase;
376 template<class F, class M> friend class Persistent;
377 template<class F> friend class Handle;
378 template<class F> friend class Local;
379 template<class F> friend class FunctionCallbackInfo;
380 template<class F> friend class PropertyCallbackInfo;
383 friend class Context;
384 template<class F> friend class internal::CustomArguments;
385 friend class HandleScope;
386 friend class EscapableHandleScope;
387 template<class F1, class F2, class F3> friend class PersistentValueMap;
388 template<class F1, class F2> friend class PersistentValueVector;
390 template <class S> V8_INLINE Local(S* that) : Handle<T>(that) { }
391 V8_INLINE static Local<T> New(Isolate* isolate, T* that);
395 // Eternal handles are set-once handles that live for the life of the isolate.
396 template <class T> class Eternal {
398 V8_INLINE Eternal() : index_(kInitialValue) { }
400 V8_INLINE Eternal(Isolate* isolate, Local<S> handle) : index_(kInitialValue) {
401 Set(isolate, handle);
403 // Can only be safely called if already set.
404 V8_INLINE Local<T> Get(Isolate* isolate);
405 V8_INLINE bool IsEmpty() { return index_ == kInitialValue; }
406 template<class S> V8_INLINE void Set(Isolate* isolate, Local<S> handle);
409 static const int kInitialValue = -1;
414 template<class T, class P>
415 class WeakCallbackData {
417 typedef void (*Callback)(const WeakCallbackData<T, P>& data);
419 V8_INLINE Isolate* GetIsolate() const { return isolate_; }
420 V8_INLINE Local<T> GetValue() const { return handle_; }
421 V8_INLINE P* GetParameter() const { return parameter_; }
424 friend class internal::GlobalHandles;
425 WeakCallbackData(Isolate* isolate, Local<T> handle, P* parameter)
426 : isolate_(isolate), handle_(handle), parameter_(parameter) { }
434 * An object reference that is independent of any handle scope. Where
435 * a Local handle only lives as long as the HandleScope in which it was
436 * allocated, a PersistentBase handle remains valid until it is explicitly
439 * A persistent handle contains a reference to a storage cell within
440 * the v8 engine which holds an object value and which is updated by
441 * the garbage collector whenever the object is moved. A new storage
442 * cell can be created using the constructor or PersistentBase::Reset and
443 * existing handles can be disposed using PersistentBase::Reset.
446 template <class T> class PersistentBase {
449 * If non-empty, destroy the underlying storage cell
450 * IsEmpty() will return true after this call.
452 V8_INLINE void Reset();
454 * If non-empty, destroy the underlying storage cell
455 * and create a new one with the contents of other if other is non empty
458 V8_INLINE void Reset(Isolate* isolate, const Handle<S>& other);
461 * If non-empty, destroy the underlying storage cell
462 * and create a new one with the contents of other if other is non empty
465 V8_INLINE void Reset(Isolate* isolate, const PersistentBase<S>& other);
467 V8_INLINE bool IsEmpty() const { return val_ == 0; }
470 V8_INLINE bool operator==(const PersistentBase<S>& that) const {
471 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
472 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
473 if (a == 0) return b == 0;
474 if (b == 0) return false;
478 template <class S> V8_INLINE bool operator==(const Handle<S>& that) const {
479 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
480 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
481 if (a == 0) return b == 0;
482 if (b == 0) return false;
487 V8_INLINE bool operator!=(const PersistentBase<S>& that) const {
488 return !operator==(that);
491 template <class S> V8_INLINE bool operator!=(const Handle<S>& that) const {
492 return !operator==(that);
496 * Install a finalization callback on this object.
497 * NOTE: There is no guarantee as to *when* or even *if* the callback is
498 * invoked. The invocation is performed solely on a best effort basis.
499 * As always, GC-based finalization should *not* be relied upon for any
500 * critical form of resource management!
503 V8_INLINE void SetWeak(
505 typename WeakCallbackData<T, P>::Callback callback);
507 template<typename S, typename P>
508 V8_INLINE void SetWeak(
510 typename WeakCallbackData<S, P>::Callback callback);
513 V8_INLINE P* ClearWeak();
515 // TODO(dcarney): remove this.
516 V8_INLINE void ClearWeak() { ClearWeak<void>(); }
519 * Marks the reference to this object independent. Garbage collector is free
520 * to ignore any object groups containing this object. Weak callback for an
521 * independent handle should not assume that it will be preceded by a global
522 * GC prologue callback or followed by a global GC epilogue callback.
524 V8_INLINE void MarkIndependent();
527 * Marks the reference to this object partially dependent. Partially dependent
528 * handles only depend on other partially dependent handles and these
529 * dependencies are provided through object groups. It provides a way to build
530 * smaller object groups for young objects that represent only a subset of all
531 * external dependencies. This mark is automatically cleared after each
532 * garbage collection.
534 V8_INLINE void MarkPartiallyDependent();
536 V8_INLINE bool IsIndependent() const;
538 /** Checks if the handle holds the only reference to an object. */
539 V8_INLINE bool IsNearDeath() const;
541 /** Returns true if the handle's reference is weak. */
542 V8_INLINE bool IsWeak() const;
545 * Assigns a wrapper class ID to the handle. See RetainedObjectInfo interface
546 * description in v8-profiler.h for details.
548 V8_INLINE void SetWrapperClassId(uint16_t class_id);
551 * Returns the class ID previously assigned to this handle or 0 if no class ID
552 * was previously assigned.
554 V8_INLINE uint16_t WrapperClassId() const;
557 friend class Isolate;
559 template<class F> friend class Handle;
560 template<class F> friend class Local;
561 template<class F1, class F2> friend class Persistent;
562 template<class F> friend class UniquePersistent;
563 template<class F> friend class PersistentBase;
564 template<class F> friend class ReturnValue;
565 template<class F1, class F2, class F3> friend class PersistentValueMap;
566 template<class F1, class F2> friend class PersistentValueVector;
569 explicit V8_INLINE PersistentBase(T* val) : val_(val) {}
570 PersistentBase(PersistentBase& other); // NOLINT
571 void operator=(PersistentBase&);
572 V8_INLINE static T* New(Isolate* isolate, T* that);
579 * Default traits for Persistent. This class does not allow
580 * use of the copy constructor or assignment operator.
581 * At present kResetInDestructor is not set, but that will change in a future
585 class NonCopyablePersistentTraits {
587 typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
588 static const bool kResetInDestructor = false;
589 template<class S, class M>
590 V8_INLINE static void Copy(const Persistent<S, M>& source,
591 NonCopyablePersistent* dest) {
592 Uncompilable<Object>();
594 // TODO(dcarney): come up with a good compile error here.
595 template<class O> V8_INLINE static void Uncompilable() {
596 TYPE_CHECK(O, Primitive);
602 * Helper class traits to allow copying and assignment of Persistent.
603 * This will clone the contents of storage cell, but not any of the flags, etc.
606 struct CopyablePersistentTraits {
607 typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
608 static const bool kResetInDestructor = true;
609 template<class S, class M>
610 static V8_INLINE void Copy(const Persistent<S, M>& source,
611 CopyablePersistent* dest) {
612 // do nothing, just allow copy
618 * A PersistentBase which allows copy and assignment.
620 * Copy, assignment and destructor bevavior is controlled by the traits
623 * Note: Persistent class hierarchy is subject to future changes.
625 template <class T, class M> class Persistent : public PersistentBase<T> {
628 * A Persistent with no storage cell.
630 V8_INLINE Persistent() : PersistentBase<T>(0) { }
632 * Construct a Persistent from a Handle.
633 * When the Handle is non-empty, a new storage cell is created
634 * pointing to the same object, and no flags are set.
636 template <class S> V8_INLINE Persistent(Isolate* isolate, Handle<S> that)
637 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
641 * Construct a Persistent from a Persistent.
642 * When the Persistent is non-empty, a new storage cell is created
643 * pointing to the same object, and no flags are set.
645 template <class S, class M2>
646 V8_INLINE Persistent(Isolate* isolate, const Persistent<S, M2>& that)
647 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
651 * The copy constructors and assignment operator create a Persistent
652 * exactly as the Persistent constructor, but the Copy function from the
653 * traits class is called, allowing the setting of flags based on the
656 V8_INLINE Persistent(const Persistent& that) : PersistentBase<T>(0) {
659 template <class S, class M2>
660 V8_INLINE Persistent(const Persistent<S, M2>& that) : PersistentBase<T>(0) {
663 V8_INLINE Persistent& operator=(const Persistent& that) { // NOLINT
667 template <class S, class M2>
668 V8_INLINE Persistent& operator=(const Persistent<S, M2>& that) { // NOLINT
673 * The destructor will dispose the Persistent based on the
674 * kResetInDestructor flags in the traits class. Since not calling dispose
675 * can result in a memory leak, it is recommended to always set this flag.
677 V8_INLINE ~Persistent() {
678 if (M::kResetInDestructor) this->Reset();
681 // TODO(dcarney): this is pretty useless, fix or remove
683 V8_INLINE static Persistent<T>& Cast(Persistent<S>& that) { // NOLINT
684 #ifdef V8_ENABLE_CHECKS
685 // If we're going to perform the type check then we have to check
686 // that the handle isn't empty before doing the checked cast.
687 if (!that.IsEmpty()) T::Cast(*that);
689 return reinterpret_cast<Persistent<T>&>(that);
692 // TODO(dcarney): this is pretty useless, fix or remove
693 template <class S> V8_INLINE Persistent<S>& As() { // NOLINT
694 return Persistent<S>::Cast(*this);
697 // This will be removed.
698 V8_INLINE T* ClearAndLeak();
701 friend class Isolate;
703 template<class F> friend class Handle;
704 template<class F> friend class Local;
705 template<class F1, class F2> friend class Persistent;
706 template<class F> friend class ReturnValue;
708 template <class S> V8_INLINE Persistent(S* that) : PersistentBase<T>(that) { }
709 V8_INLINE T* operator*() const { return this->val_; }
710 template<class S, class M2>
711 V8_INLINE void Copy(const Persistent<S, M2>& that);
716 * A PersistentBase which has move semantics.
718 * Note: Persistent class hierarchy is subject to future changes.
721 class UniquePersistent : public PersistentBase<T> {
723 V8_INLINE explicit RValue(UniquePersistent* obj) : object(obj) {}
724 UniquePersistent* object;
729 * A UniquePersistent with no storage cell.
731 V8_INLINE UniquePersistent() : PersistentBase<T>(0) { }
733 * Construct a UniquePersistent from a Handle.
734 * When the Handle is non-empty, a new storage cell is created
735 * pointing to the same object, and no flags are set.
738 V8_INLINE UniquePersistent(Isolate* isolate, Handle<S> that)
739 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
743 * Construct a UniquePersistent from a PersistentBase.
744 * When the Persistent is non-empty, a new storage cell is created
745 * pointing to the same object, and no flags are set.
748 V8_INLINE UniquePersistent(Isolate* isolate, const PersistentBase<S>& that)
749 : PersistentBase<T>(PersistentBase<T>::New(isolate, that.val_)) {
755 V8_INLINE UniquePersistent(RValue rvalue)
756 : PersistentBase<T>(rvalue.object->val_) {
757 rvalue.object->val_ = 0;
759 V8_INLINE ~UniquePersistent() { this->Reset(); }
761 * Move via assignment.
764 V8_INLINE UniquePersistent& operator=(UniquePersistent<S> rhs) {
767 this->val_ = rhs.val_;
772 * Cast operator for moves.
774 V8_INLINE operator RValue() { return RValue(this); }
776 * Pass allows returning uniques from functions, etc.
778 UniquePersistent Pass() { return UniquePersistent(RValue(this)); }
781 UniquePersistent(UniquePersistent&);
782 void operator=(UniquePersistent&);
787 * A stack-allocated class that governs a number of local handles.
788 * After a handle scope has been created, all local handles will be
789 * allocated within that handle scope until either the handle scope is
790 * deleted or another handle scope is created. If there is already a
791 * handle scope and a new one is created, all allocations will take
792 * place in the new handle scope until it is deleted. After that,
793 * new handles will again be allocated in the original handle scope.
795 * After the handle scope of a local handle has been deleted the
796 * garbage collector will no longer track the object stored in the
797 * handle and may deallocate it. The behavior of accessing a handle
798 * for which the handle scope has been deleted is undefined.
800 class V8_EXPORT HandleScope {
802 HandleScope(Isolate* isolate);
807 * Counts the number of allocated handles.
809 static int NumberOfHandles(Isolate* isolate);
811 V8_INLINE Isolate* GetIsolate() const {
812 return reinterpret_cast<Isolate*>(isolate_);
816 V8_INLINE HandleScope() {}
818 void Initialize(Isolate* isolate);
820 static internal::Object** CreateHandle(internal::Isolate* isolate,
821 internal::Object* value);
824 // Uses heap_object to obtain the current Isolate.
825 static internal::Object** CreateHandle(internal::HeapObject* heap_object,
826 internal::Object* value);
828 // Make it hard to create heap-allocated or illegal handle scopes by
829 // disallowing certain operations.
830 HandleScope(const HandleScope&);
831 void operator=(const HandleScope&);
832 void* operator new(size_t size);
833 void operator delete(void*, size_t);
835 internal::Isolate* isolate_;
836 internal::Object** prev_next_;
837 internal::Object** prev_limit_;
839 // Local::New uses CreateHandle with an Isolate* parameter.
840 template<class F> friend class Local;
842 // Object::GetInternalField and Context::GetEmbedderData use CreateHandle with
843 // a HeapObject* in their shortcuts.
845 friend class Context;
850 * A HandleScope which first allocates a handle in the current scope
851 * which will be later filled with the escape value.
853 class V8_EXPORT EscapableHandleScope : public HandleScope {
855 EscapableHandleScope(Isolate* isolate);
856 V8_INLINE ~EscapableHandleScope() {}
859 * Pushes the value into the previous scope and returns a handle to it.
860 * Cannot be called twice.
863 V8_INLINE Local<T> Escape(Local<T> value) {
864 internal::Object** slot =
865 Escape(reinterpret_cast<internal::Object**>(*value));
866 return Local<T>(reinterpret_cast<T*>(slot));
870 internal::Object** Escape(internal::Object** escape_value);
872 // Make it hard to create heap-allocated or illegal handle scopes by
873 // disallowing certain operations.
874 EscapableHandleScope(const EscapableHandleScope&);
875 void operator=(const EscapableHandleScope&);
876 void* operator new(size_t size);
877 void operator delete(void*, size_t);
879 internal::Object** escape_slot_;
884 * A simple Maybe type, representing an object which may or may not have a
889 Maybe() : has_value(false) {}
890 explicit Maybe(T t) : has_value(true), value(t) {}
891 Maybe(bool has, T t) : has_value(has), value(t) {}
898 // --- Special objects ---
902 * The superclass of values and API object templates.
904 class V8_EXPORT Data {
911 * The origin, within a file, of a script.
915 V8_INLINE ScriptOrigin(
916 Handle<Value> resource_name,
917 Handle<Integer> resource_line_offset = Handle<Integer>(),
918 Handle<Integer> resource_column_offset = Handle<Integer>(),
919 Handle<Boolean> resource_is_shared_cross_origin = Handle<Boolean>())
920 : resource_name_(resource_name),
921 resource_line_offset_(resource_line_offset),
922 resource_column_offset_(resource_column_offset),
923 resource_is_shared_cross_origin_(resource_is_shared_cross_origin) { }
924 V8_INLINE Handle<Value> ResourceName() const;
925 V8_INLINE Handle<Integer> ResourceLineOffset() const;
926 V8_INLINE Handle<Integer> ResourceColumnOffset() const;
927 V8_INLINE Handle<Boolean> ResourceIsSharedCrossOrigin() const;
929 Handle<Value> resource_name_;
930 Handle<Integer> resource_line_offset_;
931 Handle<Integer> resource_column_offset_;
932 Handle<Boolean> resource_is_shared_cross_origin_;
937 * A compiled JavaScript script, not yet tied to a Context.
939 class V8_EXPORT UnboundScript {
942 * Binds the script to the currently entered context.
944 Local<Script> BindToCurrentContext();
947 Handle<Value> GetScriptName();
950 * Returns zero based line number of the code_pos location in the script.
951 * -1 will be returned if no information available.
953 int GetLineNumber(int code_pos);
955 static const int kNoScriptId = 0;
960 * A compiled JavaScript script, tied to a Context which was active when the
961 * script was compiled.
963 class V8_EXPORT Script {
966 * A shorthand for ScriptCompiler::Compile().
968 static Local<Script> Compile(Handle<String> source,
969 ScriptOrigin* origin = NULL);
971 // To be decprecated, use the Compile above.
972 static Local<Script> Compile(Handle<String> source,
973 Handle<String> file_name);
976 * Runs the script returning the resulting value. It will be run in the
977 * context in which it was created (ScriptCompiler::CompileBound or
978 * UnboundScript::BindToGlobalContext()).
983 * Returns the corresponding context-unbound script.
985 Local<UnboundScript> GetUnboundScript();
987 // To be deprecated; use GetUnboundScript()->GetId();
989 return GetUnboundScript()->GetId();
992 // Use GetUnboundScript()->GetId();
993 V8_DEPRECATED("Use GetUnboundScript()->GetId()",
994 Handle<Value> GetScriptName()) {
995 return GetUnboundScript()->GetScriptName();
999 * Returns zero based line number of the code_pos location in the script.
1000 * -1 will be returned if no information available.
1002 V8_DEPRECATED("Use GetUnboundScript()->GetLineNumber()",
1003 int GetLineNumber(int code_pos)) {
1004 return GetUnboundScript()->GetLineNumber(code_pos);
1010 * For compiling scripts.
1012 class V8_EXPORT ScriptCompiler {
1015 * Compilation data that the embedder can cache and pass back to speed up
1016 * future compilations. The data is produced if the CompilerOptions passed to
1017 * the compilation functions in ScriptCompiler contains produce_data_to_cache
1018 * = true. The data to cache can then can be retrieved from
1021 struct V8_EXPORT CachedData {
1027 CachedData() : data(NULL), length(0), buffer_policy(BufferNotOwned) {}
1029 // If buffer_policy is BufferNotOwned, the caller keeps the ownership of
1030 // data and guarantees that it stays alive until the CachedData object is
1031 // destroyed. If the policy is BufferOwned, the given data will be deleted
1032 // (with delete[]) when the CachedData object is destroyed.
1033 CachedData(const uint8_t* data, int length,
1034 BufferPolicy buffer_policy = BufferNotOwned);
1036 // TODO(marja): Async compilation; add constructors which take a callback
1037 // which will be called when V8 no longer needs the data.
1038 const uint8_t* data;
1040 BufferPolicy buffer_policy;
1043 // Prevent copying. Not implemented.
1044 CachedData(const CachedData&);
1045 CachedData& operator=(const CachedData&);
1049 * Source code which can be then compiled to a UnboundScript or
1054 // Source takes ownership of CachedData.
1055 V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
1056 CachedData* cached_data = NULL);
1057 V8_INLINE Source(Local<String> source_string,
1058 CachedData* cached_data = NULL);
1059 V8_INLINE ~Source();
1061 // Ownership of the CachedData or its buffers is *not* transferred to the
1062 // caller. The CachedData object is alive as long as the Source object is
1064 V8_INLINE const CachedData* GetCachedData() const;
1067 friend class ScriptCompiler;
1068 // Prevent copying. Not implemented.
1069 Source(const Source&);
1070 Source& operator=(const Source&);
1072 Local<String> source_string;
1074 // Origin information
1075 Handle<Value> resource_name;
1076 Handle<Integer> resource_line_offset;
1077 Handle<Integer> resource_column_offset;
1078 Handle<Boolean> resource_is_shared_cross_origin;
1080 // Cached data from previous compilation (if any), or generated during
1081 // compilation (if the generate_cached_data flag is passed to
1083 CachedData* cached_data;
1086 enum CompileOptions {
1088 kProduceDataToCache = 1 << 0
1092 * Compiles the specified script (context-independent).
1094 * \param source Script source code.
1095 * \return Compiled script object (context independent; for running it must be
1096 * bound to a context).
1098 static Local<UnboundScript> CompileUnbound(
1099 Isolate* isolate, Source* source,
1100 CompileOptions options = kNoCompileOptions);
1103 * Compiles the specified script (bound to current context).
1105 * \param source Script source code.
1106 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
1107 * using pre_data speeds compilation if it's done multiple times.
1108 * Owned by caller, no references are kept when this function returns.
1109 * \return Compiled script object, bound to the context that was active
1110 * when this function was called. When run it will always use this
1113 static Local<Script> Compile(
1114 Isolate* isolate, Source* source,
1115 CompileOptions options = kNoCompileOptions);
1122 class V8_EXPORT Message {
1124 Local<String> Get() const;
1125 Local<String> GetSourceLine() const;
1128 * Returns the resource name for the script from where the function causing
1129 * the error originates.
1131 Handle<Value> GetScriptResourceName() const;
1134 * Exception stack trace. By default stack traces are not captured for
1135 * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
1136 * to change this option.
1138 Handle<StackTrace> GetStackTrace() const;
1141 * Returns the number, 1-based, of the line where the error occurred.
1143 int GetLineNumber() const;
1146 * Returns the index within the script of the first character where
1147 * the error occurred.
1149 int GetStartPosition() const;
1152 * Returns the index within the script of the last character where
1153 * the error occurred.
1155 int GetEndPosition() const;
1158 * Returns the index within the line of the first character where
1159 * the error occurred.
1161 int GetStartColumn() const;
1164 * Returns the index within the line of the last character where
1165 * the error occurred.
1167 int GetEndColumn() const;
1170 * Passes on the value set by the embedder when it fed the script from which
1171 * this Message was generated to V8.
1173 bool IsSharedCrossOrigin() const;
1175 // TODO(1245381): Print to a string instead of on a FILE.
1176 static void PrintCurrentStackTrace(Isolate* isolate, FILE* out);
1178 static const int kNoLineNumberInfo = 0;
1179 static const int kNoColumnInfo = 0;
1180 static const int kNoScriptIdInfo = 0;
1185 * Representation of a JavaScript stack trace. The information collected is a
1186 * snapshot of the execution stack and the information remains valid after
1187 * execution continues.
1189 class V8_EXPORT StackTrace {
1192 * Flags that determine what information is placed captured for each
1193 * StackFrame when grabbing the current stack trace.
1195 enum StackTraceOptions {
1197 kColumnOffset = 1 << 1 | kLineNumber,
1198 kScriptName = 1 << 2,
1199 kFunctionName = 1 << 3,
1201 kIsConstructor = 1 << 5,
1202 kScriptNameOrSourceURL = 1 << 6,
1204 kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
1205 kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL
1209 * Returns a StackFrame at a particular index.
1211 Local<StackFrame> GetFrame(uint32_t index) const;
1214 * Returns the number of StackFrames.
1216 int GetFrameCount() const;
1219 * Returns StackTrace as a v8::Array that contains StackFrame objects.
1221 Local<Array> AsArray();
1224 * Grab a snapshot of the current JavaScript execution stack.
1226 * \param frame_limit The maximum number of stack frames we want to capture.
1227 * \param options Enumerates the set of things we will capture for each
1230 static Local<StackTrace> CurrentStackTrace(
1233 StackTraceOptions options = kOverview);
1238 * A single JavaScript stack frame.
1240 class V8_EXPORT StackFrame {
1243 * Returns the number, 1-based, of the line for the associate function call.
1244 * This method will return Message::kNoLineNumberInfo if it is unable to
1245 * retrieve the line number, or if kLineNumber was not passed as an option
1246 * when capturing the StackTrace.
1248 int GetLineNumber() const;
1251 * Returns the 1-based column offset on the line for the associated function
1253 * This method will return Message::kNoColumnInfo if it is unable to retrieve
1254 * the column number, or if kColumnOffset was not passed as an option when
1255 * capturing the StackTrace.
1257 int GetColumn() const;
1260 * Returns the id of the script for the function for this StackFrame.
1261 * This method will return Message::kNoScriptIdInfo if it is unable to
1262 * retrieve the script id, or if kScriptId was not passed as an option when
1263 * capturing the StackTrace.
1265 int GetScriptId() const;
1268 * Returns the name of the resource that contains the script for the
1269 * function for this StackFrame.
1271 Local<String> GetScriptName() const;
1274 * Returns the name of the resource that contains the script for the
1275 * function for this StackFrame or sourceURL value if the script name
1276 * is undefined and its source ends with //# sourceURL=... string or
1277 * deprecated //@ sourceURL=... string.
1279 Local<String> GetScriptNameOrSourceURL() const;
1282 * Returns the name of the function associated with this stack frame.
1284 Local<String> GetFunctionName() const;
1287 * Returns whether or not the associated function is compiled via a call to
1290 bool IsEval() const;
1293 * Returns whether or not the associated function is called as a
1294 * constructor via "new".
1296 bool IsConstructor() const;
1303 class V8_EXPORT JSON {
1306 * Tries to parse the string |json_string| and returns it as value if
1309 * \param json_string The string to parse.
1310 * \return The corresponding value if successfully parsed.
1312 static Local<Value> Parse(Local<String> json_string);
1320 * The superclass of all JavaScript values and objects.
1322 class V8_EXPORT Value : public Data {
1325 * Returns true if this value is the undefined value. See ECMA-262
1328 V8_INLINE bool IsUndefined() const;
1331 * Returns true if this value is the null value. See ECMA-262
1334 V8_INLINE bool IsNull() const;
1337 * Returns true if this value is true.
1339 bool IsTrue() const;
1342 * Returns true if this value is false.
1344 bool IsFalse() const;
1347 * Returns true if this value is an instance of the String type.
1350 V8_INLINE bool IsString() const;
1353 * Returns true if this value is a symbol.
1354 * This is an experimental feature.
1356 bool IsSymbol() const;
1359 * Returns true if this value is a function.
1361 bool IsFunction() const;
1364 * Returns true if this value is an array.
1366 bool IsArray() const;
1369 * Returns true if this value is an object.
1371 bool IsObject() const;
1374 * Returns true if this value is boolean.
1376 bool IsBoolean() const;
1379 * Returns true if this value is a number.
1381 bool IsNumber() const;
1384 * Returns true if this value is external.
1386 bool IsExternal() const;
1389 * Returns true if this value is a 32-bit signed integer.
1391 bool IsInt32() const;
1394 * Returns true if this value is a 32-bit unsigned integer.
1396 bool IsUint32() const;
1399 * Returns true if this value is a Date.
1401 bool IsDate() const;
1404 * Returns true if this value is a Boolean object.
1406 bool IsBooleanObject() const;
1409 * Returns true if this value is a Number object.
1411 bool IsNumberObject() const;
1414 * Returns true if this value is a String object.
1416 bool IsStringObject() const;
1419 * Returns true if this value is a Symbol object.
1420 * This is an experimental feature.
1422 bool IsSymbolObject() const;
1425 * Returns true if this value is a NativeError.
1427 bool IsNativeError() const;
1430 * Returns true if this value is a RegExp.
1432 bool IsRegExp() const;
1435 * Returns true if this value is a Promise.
1436 * This is an experimental feature.
1438 bool IsPromise() const;
1441 * Returns true if this value is an ArrayBuffer.
1442 * This is an experimental feature.
1444 bool IsArrayBuffer() const;
1447 * Returns true if this value is an ArrayBufferView.
1448 * This is an experimental feature.
1450 bool IsArrayBufferView() const;
1453 * Returns true if this value is one of TypedArrays.
1454 * This is an experimental feature.
1456 bool IsTypedArray() const;
1459 * Returns true if this value is an Uint8Array.
1460 * This is an experimental feature.
1462 bool IsUint8Array() const;
1465 * Returns true if this value is an Uint8ClampedArray.
1466 * This is an experimental feature.
1468 bool IsUint8ClampedArray() const;
1471 * Returns true if this value is an Int8Array.
1472 * This is an experimental feature.
1474 bool IsInt8Array() const;
1477 * Returns true if this value is an Uint16Array.
1478 * This is an experimental feature.
1480 bool IsUint16Array() const;
1483 * Returns true if this value is an Int16Array.
1484 * This is an experimental feature.
1486 bool IsInt16Array() const;
1489 * Returns true if this value is an Uint32Array.
1490 * This is an experimental feature.
1492 bool IsUint32Array() const;
1495 * Returns true if this value is an Int32Array.
1496 * This is an experimental feature.
1498 bool IsInt32Array() const;
1501 * Returns true if this value is a Float32Array.
1502 * This is an experimental feature.
1504 bool IsFloat32Array() const;
1507 * Returns true if this value is a Float32x4Array.
1508 * This is an experimental feature.
1510 bool IsFloat32x4Array() const;
1513 * Returns true if this value is a Float64x2Array.
1514 * This is an experimental feature.
1516 bool IsFloat64x2Array() const;
1519 * Returns true if this value is a Int32x4Array.
1520 * This is an experimental feature.
1522 bool IsInt32x4Array() const;
1525 * Returns true if this value is a Float64Array.
1526 * This is an experimental feature.
1528 bool IsFloat64Array() const;
1531 * Returns true if this value is a DataView.
1532 * This is an experimental feature.
1534 bool IsDataView() const;
1536 Local<Boolean> ToBoolean() const;
1537 Local<Number> ToNumber() const;
1538 Local<String> ToString() const;
1539 Local<String> ToDetailString() const;
1540 Local<Object> ToObject() const;
1541 Local<Integer> ToInteger() const;
1542 Local<Uint32> ToUint32() const;
1543 Local<Int32> ToInt32() const;
1546 * Attempts to convert a string to an array index.
1547 * Returns an empty handle if the conversion fails.
1549 Local<Uint32> ToArrayIndex() const;
1551 bool BooleanValue() const;
1552 double NumberValue() const;
1553 int64_t IntegerValue() const;
1554 uint32_t Uint32Value() const;
1555 int32_t Int32Value() const;
1558 bool Equals(Handle<Value> that) const;
1559 bool StrictEquals(Handle<Value> that) const;
1560 bool SameValue(Handle<Value> that) const;
1562 template <class T> V8_INLINE static Value* Cast(T* value);
1565 V8_INLINE bool QuickIsUndefined() const;
1566 V8_INLINE bool QuickIsNull() const;
1567 V8_INLINE bool QuickIsString() const;
1568 bool FullIsUndefined() const;
1569 bool FullIsNull() const;
1570 bool FullIsString() const;
1575 * The superclass of primitive values. See ECMA-262 4.3.2.
1577 class V8_EXPORT Primitive : public Value { };
1581 * A primitive boolean value (ECMA-262, 4.3.14). Either the true
1584 class V8_EXPORT Boolean : public Primitive {
1587 V8_INLINE static Handle<Boolean> New(Isolate* isolate, bool value);
1592 * A JavaScript string value (ECMA-262, 4.3.17).
1594 class V8_EXPORT String : public Primitive {
1597 UNKNOWN_ENCODING = 0x1,
1598 TWO_BYTE_ENCODING = 0x0,
1599 ASCII_ENCODING = 0x4,
1600 ONE_BYTE_ENCODING = 0x4
1603 * Returns the number of characters in this string.
1608 * Returns the number of bytes in the UTF-8 encoded
1609 * representation of this string.
1611 int Utf8Length() const;
1614 * Returns whether this string is known to contain only one byte data.
1615 * Does not read the string.
1616 * False negatives are possible.
1618 bool IsOneByte() const;
1621 * Returns whether this string contain only one byte data.
1622 * Will read the entire string in some cases.
1624 bool ContainsOnlyOneByte() const;
1627 * Write the contents of the string to an external buffer.
1628 * If no arguments are given, expects the buffer to be large
1629 * enough to hold the entire string and NULL terminator. Copies
1630 * the contents of the string and the NULL terminator into the
1633 * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
1634 * before the end of the buffer.
1636 * Copies up to length characters into the output buffer.
1637 * Only null-terminates if there is enough space in the buffer.
1639 * \param buffer The buffer into which the string will be copied.
1640 * \param start The starting position within the string at which
1642 * \param length The number of characters to copy from the string. For
1643 * WriteUtf8 the number of bytes in the buffer.
1644 * \param nchars_ref The number of characters written, can be NULL.
1645 * \param options Various options that might affect performance of this or
1646 * subsequent operations.
1647 * \return The number of characters copied to the buffer excluding the null
1648 * terminator. For WriteUtf8: The number of bytes copied to the buffer
1649 * including the null terminator (if written).
1653 HINT_MANY_WRITES_EXPECTED = 1,
1654 NO_NULL_TERMINATION = 2,
1655 PRESERVE_ASCII_NULL = 4,
1656 // Used by WriteUtf8 to replace orphan surrogate code units with the
1657 // unicode replacement character. Needs to be set to guarantee valid UTF-8
1659 REPLACE_INVALID_UTF8 = 8
1662 // 16-bit character codes.
1663 int Write(uint16_t* buffer,
1666 int options = NO_OPTIONS) const;
1667 // One byte characters.
1668 int WriteOneByte(uint8_t* buffer,
1671 int options = NO_OPTIONS) const;
1672 // UTF-8 encoded characters.
1673 int WriteUtf8(char* buffer,
1675 int* nchars_ref = NULL,
1676 int options = NO_OPTIONS) const;
1679 * A zero length string.
1681 V8_INLINE static v8::Local<v8::String> Empty(Isolate* isolate);
1684 * Returns true if the string is external
1686 bool IsExternal() const;
1689 * Returns true if the string is both external and ASCII
1691 bool IsExternalAscii() const;
1693 class V8_EXPORT ExternalStringResourceBase { // NOLINT
1695 virtual ~ExternalStringResourceBase() {}
1698 ExternalStringResourceBase() {}
1701 * Internally V8 will call this Dispose method when the external string
1702 * resource is no longer needed. The default implementation will use the
1703 * delete operator. This method can be overridden in subclasses to
1704 * control how allocated external string resources are disposed.
1706 virtual void Dispose() { delete this; }
1709 // Disallow copying and assigning.
1710 ExternalStringResourceBase(const ExternalStringResourceBase&);
1711 void operator=(const ExternalStringResourceBase&);
1713 friend class v8::internal::Heap;
1717 * An ExternalStringResource is a wrapper around a two-byte string
1718 * buffer that resides outside V8's heap. Implement an
1719 * ExternalStringResource to manage the life cycle of the underlying
1720 * buffer. Note that the string data must be immutable.
1722 class V8_EXPORT ExternalStringResource
1723 : public ExternalStringResourceBase {
1726 * Override the destructor to manage the life cycle of the underlying
1729 virtual ~ExternalStringResource() {}
1732 * The string data from the underlying buffer.
1734 virtual const uint16_t* data() const = 0;
1737 * The length of the string. That is, the number of two-byte characters.
1739 virtual size_t length() const = 0;
1742 ExternalStringResource() {}
1746 * An ExternalAsciiStringResource is a wrapper around an ASCII
1747 * string buffer that resides outside V8's heap. Implement an
1748 * ExternalAsciiStringResource to manage the life cycle of the
1749 * underlying buffer. Note that the string data must be immutable
1750 * and that the data must be strict (7-bit) ASCII, not Latin-1 or
1751 * UTF-8, which would require special treatment internally in the
1752 * engine and, in the case of UTF-8, do not allow efficient indexing.
1753 * Use String::New or convert to 16 bit data for non-ASCII.
1756 class V8_EXPORT ExternalAsciiStringResource
1757 : public ExternalStringResourceBase {
1760 * Override the destructor to manage the life cycle of the underlying
1763 virtual ~ExternalAsciiStringResource() {}
1764 /** The string data from the underlying buffer.*/
1765 virtual const char* data() const = 0;
1766 /** The number of ASCII characters in the string.*/
1767 virtual size_t length() const = 0;
1769 ExternalAsciiStringResource() {}
1772 typedef ExternalAsciiStringResource ExternalOneByteStringResource;
1775 * If the string is an external string, return the ExternalStringResourceBase
1776 * regardless of the encoding, otherwise return NULL. The encoding of the
1777 * string is returned in encoding_out.
1779 V8_INLINE ExternalStringResourceBase* GetExternalStringResourceBase(
1780 Encoding* encoding_out) const;
1783 * Get the ExternalStringResource for an external string. Returns
1784 * NULL if IsExternal() doesn't return true.
1786 V8_INLINE ExternalStringResource* GetExternalStringResource() const;
1789 * Get the ExternalAsciiStringResource for an external ASCII string.
1790 * Returns NULL if IsExternalAscii() doesn't return true.
1792 const ExternalAsciiStringResource* GetExternalAsciiStringResource() const;
1794 V8_INLINE static String* Cast(v8::Value* obj);
1796 enum NewStringType {
1797 kNormalString, kInternalizedString, kUndetectableString
1800 /** Allocates a new string from UTF-8 data.*/
1801 static Local<String> NewFromUtf8(Isolate* isolate,
1803 NewStringType type = kNormalString,
1806 /** Allocates a new string from Latin-1 data.*/
1807 static Local<String> NewFromOneByte(
1809 const uint8_t* data,
1810 NewStringType type = kNormalString,
1813 /** Allocates a new string from UTF-16 data.*/
1814 static Local<String> NewFromTwoByte(
1816 const uint16_t* data,
1817 NewStringType type = kNormalString,
1821 * Creates a new string by concatenating the left and the right strings
1822 * passed in as parameters.
1824 static Local<String> Concat(Handle<String> left, Handle<String> right);
1827 * Creates a new external string using the data defined in the given
1828 * resource. When the external string is no longer live on V8's heap the
1829 * resource will be disposed by calling its Dispose method. The caller of
1830 * this function should not otherwise delete or modify the resource. Neither
1831 * should the underlying buffer be deallocated or modified except through the
1832 * destructor of the external string resource.
1834 static Local<String> NewExternal(Isolate* isolate,
1835 ExternalStringResource* resource);
1838 * Associate an external string resource with this string by transforming it
1839 * in place so that existing references to this string in the JavaScript heap
1840 * will use the external string resource. The external string resource's
1841 * character contents need to be equivalent to this string.
1842 * Returns true if the string has been changed to be an external string.
1843 * The string is not modified if the operation fails. See NewExternal for
1844 * information on the lifetime of the resource.
1846 bool MakeExternal(ExternalStringResource* resource);
1849 * Creates a new external string using the ASCII data defined in the given
1850 * resource. When the external string is no longer live on V8's heap the
1851 * resource will be disposed by calling its Dispose method. The caller of
1852 * this function should not otherwise delete or modify the resource. Neither
1853 * should the underlying buffer be deallocated or modified except through the
1854 * destructor of the external string resource.
1856 static Local<String> NewExternal(Isolate* isolate,
1857 ExternalAsciiStringResource* resource);
1860 * Associate an external string resource with this string by transforming it
1861 * in place so that existing references to this string in the JavaScript heap
1862 * will use the external string resource. The external string resource's
1863 * character contents need to be equivalent to this string.
1864 * Returns true if the string has been changed to be an external string.
1865 * The string is not modified if the operation fails. See NewExternal for
1866 * information on the lifetime of the resource.
1868 bool MakeExternal(ExternalAsciiStringResource* resource);
1871 * Returns true if this string can be made external.
1873 bool CanMakeExternal();
1876 * Converts an object to a UTF-8-encoded character array. Useful if
1877 * you want to print the object. If conversion to a string fails
1878 * (e.g. due to an exception in the toString() method of the object)
1879 * then the length() method returns 0 and the * operator returns
1882 class V8_EXPORT Utf8Value {
1884 explicit Utf8Value(Handle<v8::Value> obj);
1886 char* operator*() { return str_; }
1887 const char* operator*() const { return str_; }
1888 int length() const { return length_; }
1893 // Disallow copying and assigning.
1894 Utf8Value(const Utf8Value&);
1895 void operator=(const Utf8Value&);
1899 * Converts an object to a two-byte string.
1900 * If conversion to a string fails (eg. due to an exception in the toString()
1901 * method of the object) then the length() method returns 0 and the * operator
1904 class V8_EXPORT Value {
1906 explicit Value(Handle<v8::Value> obj);
1908 uint16_t* operator*() { return str_; }
1909 const uint16_t* operator*() const { return str_; }
1910 int length() const { return length_; }
1915 // Disallow copying and assigning.
1916 Value(const Value&);
1917 void operator=(const Value&);
1921 void VerifyExternalStringResourceBase(ExternalStringResourceBase* v,
1922 Encoding encoding) const;
1923 void VerifyExternalStringResource(ExternalStringResource* val) const;
1924 static void CheckCast(v8::Value* obj);
1929 * A JavaScript symbol (ECMA-262 edition 6)
1931 * This is an experimental feature. Use at your own risk.
1933 class V8_EXPORT Symbol : public Primitive {
1935 // Returns the print name string of the symbol, or undefined if none.
1936 Local<Value> Name() const;
1938 // Create a symbol. If name is not empty, it will be used as the description.
1939 static Local<Symbol> New(
1940 Isolate *isolate, Local<String> name = Local<String>());
1942 // Access global symbol registry.
1943 // Note that symbols created this way are never collected, so
1944 // they should only be used for statically fixed properties.
1945 // Also, there is only one global name space for the names used as keys.
1946 // To minimize the potential for clashes, use qualified names as keys.
1947 static Local<Symbol> For(Isolate *isolate, Local<String> name);
1949 // Retrieve a global symbol. Similar to |For|, but using a separate
1950 // registry that is not accessible by (and cannot clash with) JavaScript code.
1951 static Local<Symbol> ForApi(Isolate *isolate, Local<String> name);
1953 V8_INLINE static Symbol* Cast(v8::Value* obj);
1956 static void CheckCast(v8::Value* obj);
1963 * This is an experimental feature. Use at your own risk.
1965 class V8_EXPORT Private : public Data {
1967 // Returns the print name string of the private symbol, or undefined if none.
1968 Local<Value> Name() const;
1970 // Create a private symbol. If name is not empty, it will be the description.
1971 static Local<Private> New(
1972 Isolate *isolate, Local<String> name = Local<String>());
1974 // Retrieve a global private symbol. If a symbol with this name has not
1975 // been retrieved in the same isolate before, it is created.
1976 // Note that private symbols created this way are never collected, so
1977 // they should only be used for statically fixed properties.
1978 // Also, there is only one global name space for the names used as keys.
1979 // To minimize the potential for clashes, use qualified names as keys,
1980 // e.g., "Class#property".
1981 static Local<Private> ForApi(Isolate *isolate, Local<String> name);
1989 * A JavaScript number value (ECMA-262, 4.3.20)
1991 class V8_EXPORT Number : public Primitive {
1993 double Value() const;
1994 static Local<Number> New(Isolate* isolate, double value);
1995 V8_INLINE static Number* Cast(v8::Value* obj);
1998 static void CheckCast(v8::Value* obj);
2003 * A JavaScript value representing a signed integer.
2005 class V8_EXPORT Integer : public Number {
2007 static Local<Integer> New(Isolate* isolate, int32_t value);
2008 static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value);
2009 int64_t Value() const;
2010 V8_INLINE static Integer* Cast(v8::Value* obj);
2013 static void CheckCast(v8::Value* obj);
2018 * A JavaScript value representing a 32-bit signed integer.
2020 class V8_EXPORT Int32 : public Integer {
2022 int32_t Value() const;
2029 * A JavaScript value representing a 32-bit unsigned integer.
2031 class V8_EXPORT Uint32 : public Integer {
2033 uint32_t Value() const;
2039 enum PropertyAttribute {
2046 enum ExternalArrayType {
2047 kExternalInt8Array = 1,
2048 kExternalUint8Array,
2049 kExternalInt16Array,
2050 kExternalUint16Array,
2051 kExternalInt32Array,
2052 kExternalInt32x4Array,
2053 kExternalUint32Array,
2054 kExternalFloat32Array,
2055 kExternalFloat32x4Array,
2056 kExternalFloat64x2Array,
2057 kExternalFloat64Array,
2058 kExternalUint8ClampedArray,
2060 // Legacy constant names
2061 kExternalByteArray = kExternalInt8Array,
2062 kExternalUnsignedByteArray = kExternalUint8Array,
2063 kExternalShortArray = kExternalInt16Array,
2064 kExternalUnsignedShortArray = kExternalUint16Array,
2065 kExternalIntArray = kExternalInt32Array,
2066 kExternalUnsignedIntArray = kExternalUint32Array,
2067 kExternalFloatArray = kExternalFloat32Array,
2068 kExternalDoubleArray = kExternalFloat64Array,
2069 kExternalPixelArray = kExternalUint8ClampedArray
2073 * Accessor[Getter|Setter] are used as callback functions when
2074 * setting|getting a particular property. See Object and ObjectTemplate's
2075 * method SetAccessor.
2077 typedef void (*AccessorGetterCallback)(
2078 Local<String> property,
2079 const PropertyCallbackInfo<Value>& info);
2082 typedef void (*AccessorSetterCallback)(
2083 Local<String> property,
2085 const PropertyCallbackInfo<void>& info);
2089 * Access control specifications.
2091 * Some accessors should be accessible across contexts. These
2092 * accessors have an explicit access control parameter which specifies
2093 * the kind of cross-context access that should be allowed.
2095 * Additionally, for security, accessors can prohibit overwriting by
2096 * accessors defined in JavaScript. For objects that have such
2097 * accessors either locally or in their prototype chain it is not
2098 * possible to overwrite the accessor by using __defineGetter__ or
2099 * __defineSetter__ from JavaScript code.
2101 enum AccessControl {
2104 ALL_CAN_WRITE = 1 << 1,
2105 PROHIBITS_OVERWRITING = 1 << 2
2110 * A JavaScript object (ECMA-262, 4.3.3)
2112 class V8_EXPORT Object : public Value {
2114 bool Set(Handle<Value> key,
2115 Handle<Value> value,
2116 PropertyAttribute attribs = None);
2118 bool Set(uint32_t index, Handle<Value> value);
2120 // Sets a local property on this object bypassing interceptors and
2121 // overriding accessors or read-only properties.
2123 // Note that if the object has an interceptor the property will be set
2124 // locally, but since the interceptor takes precedence the local property
2125 // will only be returned if the interceptor doesn't return a value.
2127 // Note also that this only works for named properties.
2128 bool ForceSet(Handle<Value> key,
2129 Handle<Value> value,
2130 PropertyAttribute attribs = None);
2132 Local<Value> Get(Handle<Value> key);
2134 Local<Value> Get(uint32_t index);
2137 * Gets the property attributes of a property which can be None or
2138 * any combination of ReadOnly, DontEnum and DontDelete. Returns
2139 * None when the property doesn't exist.
2141 PropertyAttribute GetPropertyAttributes(Handle<Value> key);
2143 bool Has(Handle<Value> key);
2145 bool Delete(Handle<Value> key);
2147 // Delete a property on this object bypassing interceptors and
2148 // ignoring dont-delete attributes.
2149 bool ForceDelete(Handle<Value> key);
2151 bool Has(uint32_t index);
2153 bool Delete(uint32_t index);
2155 bool SetAccessor(Handle<String> name,
2156 AccessorGetterCallback getter,
2157 AccessorSetterCallback setter = 0,
2158 Handle<Value> data = Handle<Value>(),
2159 AccessControl settings = DEFAULT,
2160 PropertyAttribute attribute = None);
2162 // This function is not yet stable and should not be used at this time.
2163 bool SetDeclaredAccessor(Local<String> name,
2164 Local<DeclaredAccessorDescriptor> descriptor,
2165 PropertyAttribute attribute = None,
2166 AccessControl settings = DEFAULT);
2168 void SetAccessorProperty(Local<String> name,
2169 Local<Function> getter,
2170 Handle<Function> setter = Handle<Function>(),
2171 PropertyAttribute attribute = None,
2172 AccessControl settings = DEFAULT);
2175 * Functionality for private properties.
2176 * This is an experimental feature, use at your own risk.
2177 * Note: Private properties are inherited. Do not rely on this, since it may
2180 bool HasPrivate(Handle<Private> key);
2181 bool SetPrivate(Handle<Private> key, Handle<Value> value);
2182 bool DeletePrivate(Handle<Private> key);
2183 Local<Value> GetPrivate(Handle<Private> key);
2186 * Returns an array containing the names of the enumerable properties
2187 * of this object, including properties from prototype objects. The
2188 * array returned by this method contains the same values as would
2189 * be enumerated by a for-in statement over this object.
2191 Local<Array> GetPropertyNames();
2194 * This function has the same functionality as GetPropertyNames but
2195 * the returned array doesn't contain the names of properties from
2196 * prototype objects.
2198 Local<Array> GetOwnPropertyNames();
2201 * Get the prototype object. This does not skip objects marked to
2202 * be skipped by __proto__ and it does not consult the security
2205 Local<Value> GetPrototype();
2208 * Set the prototype object. This does not skip objects marked to
2209 * be skipped by __proto__ and it does not consult the security
2212 bool SetPrototype(Handle<Value> prototype);
2215 * Finds an instance of the given function template in the prototype
2218 Local<Object> FindInstanceInPrototypeChain(Handle<FunctionTemplate> tmpl);
2221 * Call builtin Object.prototype.toString on this object.
2222 * This is different from Value::ToString() that may call
2223 * user-defined toString function. This one does not.
2225 Local<String> ObjectProtoToString();
2228 * Returns the function invoked as a constructor for this object.
2229 * May be the null value.
2231 Local<Value> GetConstructor();
2234 * Returns the name of the function invoked as a constructor for this object.
2236 Local<String> GetConstructorName();
2238 /** Gets the number of internal fields for this Object. */
2239 int InternalFieldCount();
2241 /** Same as above, but works for Persistents */
2242 V8_INLINE static int InternalFieldCount(
2243 const PersistentBase<Object>& object) {
2244 return object.val_->InternalFieldCount();
2247 /** Gets the value from an internal field. */
2248 V8_INLINE Local<Value> GetInternalField(int index);
2250 /** Sets the value in an internal field. */
2251 void SetInternalField(int index, Handle<Value> value);
2254 * Gets a 2-byte-aligned native pointer from an internal field. This field
2255 * must have been set by SetAlignedPointerInInternalField, everything else
2256 * leads to undefined behavior.
2258 V8_INLINE void* GetAlignedPointerFromInternalField(int index);
2260 /** Same as above, but works for Persistents */
2261 V8_INLINE static void* GetAlignedPointerFromInternalField(
2262 const PersistentBase<Object>& object, int index) {
2263 return object.val_->GetAlignedPointerFromInternalField(index);
2267 * Sets a 2-byte-aligned native pointer in an internal field. To retrieve such
2268 * a field, GetAlignedPointerFromInternalField must be used, everything else
2269 * leads to undefined behavior.
2271 void SetAlignedPointerInInternalField(int index, void* value);
2273 // Testers for local properties.
2274 bool HasOwnProperty(Handle<String> key);
2275 bool HasRealNamedProperty(Handle<String> key);
2276 bool HasRealIndexedProperty(uint32_t index);
2277 bool HasRealNamedCallbackProperty(Handle<String> key);
2280 * If result.IsEmpty() no real property was located in the prototype chain.
2281 * This means interceptors in the prototype chain are not called.
2283 Local<Value> GetRealNamedPropertyInPrototypeChain(Handle<String> key);
2286 * If result.IsEmpty() no real property was located on the object or
2287 * in the prototype chain.
2288 * This means interceptors in the prototype chain are not called.
2290 Local<Value> GetRealNamedProperty(Handle<String> key);
2292 /** Tests for a named lookup interceptor.*/
2293 bool HasNamedLookupInterceptor();
2295 /** Tests for an index lookup interceptor.*/
2296 bool HasIndexedLookupInterceptor();
2299 * Turns on access check on the object if the object is an instance of
2300 * a template that has access check callbacks. If an object has no
2301 * access check info, the object cannot be accessed by anyone.
2303 void TurnOnAccessCheck();
2306 * Returns the identity hash for this object. The current implementation
2307 * uses a hidden property on the object to store the identity hash.
2309 * The return value will never be 0. Also, it is not guaranteed to be
2312 int GetIdentityHash();
2315 * Access hidden properties on JavaScript objects. These properties are
2316 * hidden from the executing JavaScript and only accessible through the V8
2317 * C++ API. Hidden properties introduced by V8 internally (for example the
2318 * identity hash) are prefixed with "v8::".
2320 bool SetHiddenValue(Handle<String> key, Handle<Value> value);
2321 Local<Value> GetHiddenValue(Handle<String> key);
2322 bool DeleteHiddenValue(Handle<String> key);
2325 * Returns true if this is an instance of an api function (one
2326 * created from a function created from a function template) and has
2327 * been modified since it was created. Note that this method is
2328 * conservative and may return true for objects that haven't actually
2334 * Clone this object with a fast but shallow copy. Values will point
2335 * to the same values as the original object.
2337 Local<Object> Clone();
2340 * Returns the context in which the object was created.
2342 Local<Context> CreationContext();
2345 * Set the backing store of the indexed properties to be managed by the
2346 * embedding layer. Access to the indexed properties will follow the rules
2347 * spelled out in CanvasPixelArray.
2348 * Note: The embedding program still owns the data and needs to ensure that
2349 * the backing store is preserved while V8 has a reference.
2351 void SetIndexedPropertiesToPixelData(uint8_t* data, int length);
2352 bool HasIndexedPropertiesInPixelData();
2353 uint8_t* GetIndexedPropertiesPixelData();
2354 int GetIndexedPropertiesPixelDataLength();
2357 * Set the backing store of the indexed properties to be managed by the
2358 * embedding layer. Access to the indexed properties will follow the rules
2359 * spelled out for the CanvasArray subtypes in the WebGL specification.
2360 * Note: The embedding program still owns the data and needs to ensure that
2361 * the backing store is preserved while V8 has a reference.
2363 void SetIndexedPropertiesToExternalArrayData(void* data,
2364 ExternalArrayType array_type,
2365 int number_of_elements);
2366 bool HasIndexedPropertiesInExternalArrayData();
2367 void* GetIndexedPropertiesExternalArrayData();
2368 ExternalArrayType GetIndexedPropertiesExternalArrayDataType();
2369 int GetIndexedPropertiesExternalArrayDataLength();
2372 * Checks whether a callback is set by the
2373 * ObjectTemplate::SetCallAsFunctionHandler method.
2374 * When an Object is callable this method returns true.
2379 * Call an Object as a function if a callback is set by the
2380 * ObjectTemplate::SetCallAsFunctionHandler method.
2382 Local<Value> CallAsFunction(Handle<Value> recv,
2384 Handle<Value> argv[]);
2387 * Call an Object as a constructor if a callback is set by the
2388 * ObjectTemplate::SetCallAsFunctionHandler method.
2389 * Note: This method behaves like the Function::NewInstance method.
2391 Local<Value> CallAsConstructor(int argc, Handle<Value> argv[]);
2393 static Local<Object> New(Isolate* isolate);
2395 V8_INLINE static Object* Cast(Value* obj);
2399 static void CheckCast(Value* obj);
2400 Local<Value> SlowGetInternalField(int index);
2401 void* SlowGetAlignedPointerFromInternalField(int index);
2406 * An instance of the built-in array constructor (ECMA-262, 15.4.2).
2408 class V8_EXPORT Array : public Object {
2410 uint32_t Length() const;
2413 * Clones an element at index |index|. Returns an empty
2414 * handle if cloning fails (for any reason).
2416 Local<Object> CloneElementAt(uint32_t index);
2419 * Creates a JavaScript array with the given length. If the length
2420 * is negative the returned array will have length 0.
2422 static Local<Array> New(Isolate* isolate, int length = 0);
2424 V8_INLINE static Array* Cast(Value* obj);
2427 static void CheckCast(Value* obj);
2431 template<typename T>
2434 template <class S> V8_INLINE ReturnValue(const ReturnValue<S>& that)
2435 : value_(that.value_) {
2439 template <typename S> V8_INLINE void Set(const Persistent<S>& handle);
2440 template <typename S> V8_INLINE void Set(const Handle<S> handle);
2441 // Fast primitive setters
2442 V8_INLINE void Set(bool value);
2443 V8_INLINE void Set(double i);
2444 V8_INLINE void Set(int32_t i);
2445 V8_INLINE void Set(uint32_t i);
2446 // Fast JS primitive setters
2447 V8_INLINE void SetNull();
2448 V8_INLINE void SetUndefined();
2449 V8_INLINE void SetEmptyString();
2450 // Convenience getter for Isolate
2451 V8_INLINE Isolate* GetIsolate();
2454 template<class F> friend class ReturnValue;
2455 template<class F> friend class FunctionCallbackInfo;
2456 template<class F> friend class PropertyCallbackInfo;
2457 template<class F, class G, class H> friend class PersistentValueMap;
2458 V8_INLINE void SetInternal(internal::Object* value) { *value_ = value; }
2459 V8_INLINE internal::Object* GetDefaultValue();
2460 V8_INLINE explicit ReturnValue(internal::Object** slot);
2461 internal::Object** value_;
2466 * The argument information given to function call callbacks. This
2467 * class provides access to information about the context of the call,
2468 * including the receiver, the number and values of arguments, and
2469 * the holder of the function.
2471 template<typename T>
2472 class FunctionCallbackInfo {
2474 V8_INLINE int Length() const;
2475 V8_INLINE Local<Value> operator[](int i) const;
2476 V8_INLINE Local<Function> Callee() const;
2477 V8_INLINE Local<Object> This() const;
2478 V8_INLINE Local<Object> Holder() const;
2479 V8_INLINE bool IsConstructCall() const;
2480 V8_INLINE Local<Value> Data() const;
2481 V8_INLINE Isolate* GetIsolate() const;
2482 V8_INLINE ReturnValue<T> GetReturnValue() const;
2483 // This shouldn't be public, but the arm compiler needs it.
2484 static const int kArgsLength = 7;
2487 friend class internal::FunctionCallbackArguments;
2488 friend class internal::CustomArguments<FunctionCallbackInfo>;
2489 static const int kHolderIndex = 0;
2490 static const int kIsolateIndex = 1;
2491 static const int kReturnValueDefaultValueIndex = 2;
2492 static const int kReturnValueIndex = 3;
2493 static const int kDataIndex = 4;
2494 static const int kCalleeIndex = 5;
2495 static const int kContextSaveIndex = 6;
2497 V8_INLINE FunctionCallbackInfo(internal::Object** implicit_args,
2498 internal::Object** values,
2500 bool is_construct_call);
2501 internal::Object** implicit_args_;
2502 internal::Object** values_;
2504 bool is_construct_call_;
2509 * The information passed to a property callback about the context
2510 * of the property access.
2512 template<typename T>
2513 class PropertyCallbackInfo {
2515 V8_INLINE Isolate* GetIsolate() const;
2516 V8_INLINE Local<Value> Data() const;
2517 V8_INLINE Local<Value> This() const;
2518 V8_INLINE Local<Object> Holder() const;
2519 V8_INLINE ReturnValue<T> GetReturnValue() const;
2520 // This shouldn't be public, but the arm compiler needs it.
2521 static const int kArgsLength = 6;
2524 friend class MacroAssembler;
2525 friend class internal::PropertyCallbackArguments;
2526 friend class internal::CustomArguments<PropertyCallbackInfo>;
2527 static const int kHolderIndex = 0;
2528 static const int kIsolateIndex = 1;
2529 static const int kReturnValueDefaultValueIndex = 2;
2530 static const int kReturnValueIndex = 3;
2531 static const int kDataIndex = 4;
2532 static const int kThisIndex = 5;
2534 V8_INLINE PropertyCallbackInfo(internal::Object** args) : args_(args) {}
2535 internal::Object** args_;
2539 typedef void (*FunctionCallback)(const FunctionCallbackInfo<Value>& info);
2543 * A JavaScript function object (ECMA-262, 15.3).
2545 class V8_EXPORT Function : public Object {
2548 * Create a function in the current execution context
2549 * for a given FunctionCallback.
2551 static Local<Function> New(Isolate* isolate,
2552 FunctionCallback callback,
2553 Local<Value> data = Local<Value>(),
2556 Local<Object> NewInstance() const;
2557 Local<Object> NewInstance(int argc, Handle<Value> argv[]) const;
2558 Local<Value> Call(Handle<Value> recv, int argc, Handle<Value> argv[]);
2559 void SetName(Handle<String> name);
2560 Handle<Value> GetName() const;
2563 * Name inferred from variable or property assignment of this function.
2564 * Used to facilitate debugging and profiling of JavaScript code written
2565 * in an OO style, where many functions are anonymous but are assigned
2566 * to object properties.
2568 Handle<Value> GetInferredName() const;
2571 * User-defined name assigned to the "displayName" property of this function.
2572 * Used to facilitate debugging and profiling of JavaScript code.
2574 Handle<Value> GetDisplayName() const;
2577 * Returns zero based line number of function body and
2578 * kLineOffsetNotFound if no information available.
2580 int GetScriptLineNumber() const;
2582 * Returns zero based column number of function body and
2583 * kLineOffsetNotFound if no information available.
2585 int GetScriptColumnNumber() const;
2588 * Tells whether this function is builtin.
2590 bool IsBuiltin() const;
2595 int ScriptId() const;
2598 * Returns the original function if this function is bound, else returns
2601 Local<Value> GetBoundFunction() const;
2603 ScriptOrigin GetScriptOrigin() const;
2604 V8_INLINE static Function* Cast(Value* obj);
2605 static const int kLineOffsetNotFound;
2609 static void CheckCast(Value* obj);
2614 * An instance of the built-in Promise constructor (ES6 draft).
2615 * This API is experimental. Only works with --harmony flag.
2617 class V8_EXPORT Promise : public Object {
2619 class V8_EXPORT Resolver : public Object {
2622 * Create a new resolver, along with an associated promise in pending state.
2624 static Local<Resolver> New(Isolate* isolate);
2627 * Extract the associated promise.
2629 Local<Promise> GetPromise();
2632 * Resolve/reject the associated promise with a given value.
2633 * Ignored if the promise is no longer pending.
2635 void Resolve(Handle<Value> value);
2636 void Reject(Handle<Value> value);
2638 V8_INLINE static Resolver* Cast(Value* obj);
2642 static void CheckCast(Value* obj);
2646 * Register a resolution/rejection handler with a promise.
2647 * The handler is given the respective resolution/rejection value as
2648 * an argument. If the promise is already resolved/rejected, the handler is
2649 * invoked at the end of turn.
2651 Local<Promise> Chain(Handle<Function> handler);
2652 Local<Promise> Catch(Handle<Function> handler);
2654 V8_INLINE static Promise* Cast(Value* obj);
2658 static void CheckCast(Value* obj);
2662 #ifndef V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT
2663 // The number of required internal fields can be defined by embedder.
2664 #define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 2
2668 * An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5).
2669 * This API is experimental and may change significantly.
2671 class V8_EXPORT ArrayBuffer : public Object {
2674 * Allocator that V8 uses to allocate |ArrayBuffer|'s memory.
2675 * The allocator is a global V8 setting. It should be set with
2676 * V8::SetArrayBufferAllocator prior to creation of a first ArrayBuffer.
2678 * This API is experimental and may change significantly.
2680 class V8_EXPORT Allocator { // NOLINT
2682 virtual ~Allocator() {}
2685 * Allocate |length| bytes. Return NULL if allocation is not successful.
2686 * Memory should be initialized to zeroes.
2688 virtual void* Allocate(size_t length) = 0;
2691 * Allocate |length| bytes. Return NULL if allocation is not successful.
2692 * Memory does not have to be initialized.
2694 virtual void* AllocateUninitialized(size_t length) = 0;
2696 * Free the memory block of size |length|, pointed to by |data|.
2697 * That memory is guaranteed to be previously allocated by |Allocate|.
2699 virtual void Free(void* data, size_t length) = 0;
2703 * The contents of an |ArrayBuffer|. Externalization of |ArrayBuffer|
2704 * returns an instance of this class, populated, with a pointer to data
2707 * The Data pointer of ArrayBuffer::Contents is always allocated with
2708 * Allocator::Allocate that is set with V8::SetArrayBufferAllocator.
2710 * This API is experimental and may change significantly.
2712 class V8_EXPORT Contents { // NOLINT
2714 Contents() : data_(NULL), byte_length_(0) {}
2716 void* Data() const { return data_; }
2717 size_t ByteLength() const { return byte_length_; }
2721 size_t byte_length_;
2723 friend class ArrayBuffer;
2728 * Data length in bytes.
2730 size_t ByteLength() const;
2733 * Create a new ArrayBuffer. Allocate |byte_length| bytes.
2734 * Allocated memory will be owned by a created ArrayBuffer and
2735 * will be deallocated when it is garbage-collected,
2736 * unless the object is externalized.
2738 static Local<ArrayBuffer> New(Isolate* isolate, size_t byte_length);
2741 * Create a new ArrayBuffer over an existing memory block.
2742 * The created array buffer is immediately in externalized state.
2743 * The memory block will not be reclaimed when a created ArrayBuffer
2744 * is garbage-collected.
2746 static Local<ArrayBuffer> New(Isolate* isolate, void* data,
2747 size_t byte_length);
2750 * Returns true if ArrayBuffer is extrenalized, that is, does not
2751 * own its memory block.
2753 bool IsExternal() const;
2756 * Neuters this ArrayBuffer and all its views (typed arrays).
2757 * Neutering sets the byte length of the buffer and all typed arrays to zero,
2758 * preventing JavaScript from ever accessing underlying backing store.
2759 * ArrayBuffer should have been externalized.
2764 * Make this ArrayBuffer external. The pointer to underlying memory block
2765 * and byte length are returned as |Contents| structure. After ArrayBuffer
2766 * had been etxrenalized, it does no longer owns the memory block. The caller
2767 * should take steps to free memory when it is no longer needed.
2769 * The memory block is guaranteed to be allocated with |Allocator::Allocate|
2770 * that has been set with V8::SetArrayBufferAllocator.
2772 Contents Externalize();
2774 V8_INLINE static ArrayBuffer* Cast(Value* obj);
2776 static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
2780 static void CheckCast(Value* obj);
2784 #ifndef V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT
2785 // The number of required internal fields can be defined by embedder.
2786 #define V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT 2
2791 * A base class for an instance of one of "views" over ArrayBuffer,
2792 * including TypedArrays and DataView (ES6 draft 15.13).
2794 * This API is experimental and may change significantly.
2796 class V8_EXPORT ArrayBufferView : public Object {
2799 * Returns underlying ArrayBuffer.
2801 Local<ArrayBuffer> Buffer();
2803 * Byte offset in |Buffer|.
2805 size_t ByteOffset();
2807 * Size of a view in bytes.
2809 size_t ByteLength();
2811 V8_INLINE static ArrayBufferView* Cast(Value* obj);
2813 static const int kInternalFieldCount =
2814 V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT;
2818 static void CheckCast(Value* obj);
2823 * A base class for an instance of TypedArray series of constructors
2824 * (ES6 draft 15.13.6).
2825 * This API is experimental and may change significantly.
2827 class V8_EXPORT TypedArray : public ArrayBufferView {
2830 * Number of elements in this typed array
2831 * (e.g. for Int16Array, |ByteLength|/2).
2835 V8_INLINE static TypedArray* Cast(Value* obj);
2839 static void CheckCast(Value* obj);
2844 * An instance of Uint8Array constructor (ES6 draft 15.13.6).
2845 * This API is experimental and may change significantly.
2847 class V8_EXPORT Uint8Array : public TypedArray {
2849 static Local<Uint8Array> New(Handle<ArrayBuffer> array_buffer,
2850 size_t byte_offset, size_t length);
2851 V8_INLINE static Uint8Array* Cast(Value* obj);
2855 static void CheckCast(Value* obj);
2860 * An instance of Uint8ClampedArray constructor (ES6 draft 15.13.6).
2861 * This API is experimental and may change significantly.
2863 class V8_EXPORT Uint8ClampedArray : public TypedArray {
2865 static Local<Uint8ClampedArray> New(Handle<ArrayBuffer> array_buffer,
2866 size_t byte_offset, size_t length);
2867 V8_INLINE static Uint8ClampedArray* Cast(Value* obj);
2870 Uint8ClampedArray();
2871 static void CheckCast(Value* obj);
2875 * An instance of Int8Array constructor (ES6 draft 15.13.6).
2876 * This API is experimental and may change significantly.
2878 class V8_EXPORT Int8Array : public TypedArray {
2880 static Local<Int8Array> New(Handle<ArrayBuffer> array_buffer,
2881 size_t byte_offset, size_t length);
2882 V8_INLINE static Int8Array* Cast(Value* obj);
2886 static void CheckCast(Value* obj);
2891 * An instance of Uint16Array constructor (ES6 draft 15.13.6).
2892 * This API is experimental and may change significantly.
2894 class V8_EXPORT Uint16Array : public TypedArray {
2896 static Local<Uint16Array> New(Handle<ArrayBuffer> array_buffer,
2897 size_t byte_offset, size_t length);
2898 V8_INLINE static Uint16Array* Cast(Value* obj);
2902 static void CheckCast(Value* obj);
2907 * An instance of Int16Array constructor (ES6 draft 15.13.6).
2908 * This API is experimental and may change significantly.
2910 class V8_EXPORT Int16Array : public TypedArray {
2912 static Local<Int16Array> New(Handle<ArrayBuffer> array_buffer,
2913 size_t byte_offset, size_t length);
2914 V8_INLINE static Int16Array* Cast(Value* obj);
2918 static void CheckCast(Value* obj);
2923 * An instance of Uint32Array constructor (ES6 draft 15.13.6).
2924 * This API is experimental and may change significantly.
2926 class V8_EXPORT Uint32Array : public TypedArray {
2928 static Local<Uint32Array> New(Handle<ArrayBuffer> array_buffer,
2929 size_t byte_offset, size_t length);
2930 V8_INLINE static Uint32Array* Cast(Value* obj);
2934 static void CheckCast(Value* obj);
2939 * An instance of Int32Array constructor (ES6 draft 15.13.6).
2940 * This API is experimental and may change significantly.
2942 class V8_EXPORT Int32Array : public TypedArray {
2944 static Local<Int32Array> New(Handle<ArrayBuffer> array_buffer,
2945 size_t byte_offset, size_t length);
2946 V8_INLINE static Int32Array* Cast(Value* obj);
2950 static void CheckCast(Value* obj);
2955 * An instance of Float32Array constructor (ES6 draft 15.13.6).
2956 * This API is experimental and may change significantly.
2958 class V8_EXPORT Float32Array : public TypedArray {
2960 static Local<Float32Array> New(Handle<ArrayBuffer> array_buffer,
2961 size_t byte_offset, size_t length);
2962 V8_INLINE static Float32Array* Cast(Value* obj);
2966 static void CheckCast(Value* obj);
2970 class V8_EXPORT Float32x4Array : public TypedArray {
2972 static Local<Float32x4Array> New(Handle<ArrayBuffer> array_buffer,
2973 size_t byte_offset, size_t length);
2974 V8_INLINE static Float32x4Array* Cast(Value* obj);
2978 static void CheckCast(Value* obj);
2982 class V8_EXPORT Float64x2Array : public TypedArray {
2984 static Local<Float64x2Array> New(Handle<ArrayBuffer> array_buffer,
2985 size_t byte_offset, size_t length);
2986 V8_INLINE static Float64x2Array* Cast(Value* obj);
2990 static void CheckCast(Value* obj);
2994 class V8_EXPORT Int32x4Array : public TypedArray {
2996 static Local<Int32x4Array> New(Handle<ArrayBuffer> array_buffer,
2997 size_t byte_offset, size_t length);
2998 V8_INLINE static Int32x4Array* Cast(Value* obj);
3002 static void CheckCast(Value* obj);
3007 * An instance of Float64Array constructor (ES6 draft 15.13.6).
3008 * This API is experimental and may change significantly.
3010 class V8_EXPORT Float64Array : public TypedArray {
3012 static Local<Float64Array> New(Handle<ArrayBuffer> array_buffer,
3013 size_t byte_offset, size_t length);
3014 V8_INLINE static Float64Array* Cast(Value* obj);
3018 static void CheckCast(Value* obj);
3023 * An instance of DataView constructor (ES6 draft 15.13.7).
3024 * This API is experimental and may change significantly.
3026 class V8_EXPORT DataView : public ArrayBufferView {
3028 static Local<DataView> New(Handle<ArrayBuffer> array_buffer,
3029 size_t byte_offset, size_t length);
3030 V8_INLINE static DataView* Cast(Value* obj);
3034 static void CheckCast(Value* obj);
3039 * An instance of the built-in Date constructor (ECMA-262, 15.9).
3041 class V8_EXPORT Date : public Object {
3043 static Local<Value> New(Isolate* isolate, double time);
3046 * A specialization of Value::NumberValue that is more efficient
3047 * because we know the structure of this object.
3049 double ValueOf() const;
3051 V8_INLINE static Date* Cast(v8::Value* obj);
3054 * Notification that the embedder has changed the time zone,
3055 * daylight savings time, or other date / time configuration
3056 * parameters. V8 keeps a cache of various values used for
3057 * date / time computation. This notification will reset
3058 * those cached values for the current context so that date /
3059 * time configuration changes would be reflected in the Date
3062 * This API should not be called more than needed as it will
3063 * negatively impact the performance of date operations.
3065 static void DateTimeConfigurationChangeNotification(Isolate* isolate);
3068 static void CheckCast(v8::Value* obj);
3073 * A Number object (ECMA-262, 4.3.21).
3075 class V8_EXPORT NumberObject : public Object {
3077 static Local<Value> New(Isolate* isolate, double value);
3079 double ValueOf() const;
3081 V8_INLINE static NumberObject* Cast(v8::Value* obj);
3084 static void CheckCast(v8::Value* obj);
3089 * A Boolean object (ECMA-262, 4.3.15).
3091 class V8_EXPORT BooleanObject : public Object {
3093 static Local<Value> New(bool value);
3095 bool ValueOf() const;
3097 V8_INLINE static BooleanObject* Cast(v8::Value* obj);
3100 static void CheckCast(v8::Value* obj);
3105 * A String object (ECMA-262, 4.3.18).
3107 class V8_EXPORT StringObject : public Object {
3109 static Local<Value> New(Handle<String> value);
3111 Local<String> ValueOf() const;
3113 V8_INLINE static StringObject* Cast(v8::Value* obj);
3116 static void CheckCast(v8::Value* obj);
3121 * A Symbol object (ECMA-262 edition 6).
3123 * This is an experimental feature. Use at your own risk.
3125 class V8_EXPORT SymbolObject : public Object {
3127 static Local<Value> New(Isolate* isolate, Handle<Symbol> value);
3129 Local<Symbol> ValueOf() const;
3131 V8_INLINE static SymbolObject* Cast(v8::Value* obj);
3134 static void CheckCast(v8::Value* obj);
3139 * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
3141 class V8_EXPORT RegExp : public Object {
3144 * Regular expression flag bits. They can be or'ed to enable a set
3155 * Creates a regular expression from the given pattern string and
3156 * the flags bit field. May throw a JavaScript exception as
3157 * described in ECMA-262, 15.10.4.1.
3160 * RegExp::New(v8::String::New("foo"),
3161 * static_cast<RegExp::Flags>(kGlobal | kMultiline))
3162 * is equivalent to evaluating "/foo/gm".
3164 static Local<RegExp> New(Handle<String> pattern, Flags flags);
3167 * Returns the value of the source property: a string representing
3168 * the regular expression.
3170 Local<String> GetSource() const;
3173 * Returns the flags bit field.
3175 Flags GetFlags() const;
3177 V8_INLINE static RegExp* Cast(v8::Value* obj);
3180 static void CheckCast(v8::Value* obj);
3185 * A JavaScript value that wraps a C++ void*. This type of value is mainly used
3186 * to associate C++ data structures with JavaScript objects.
3188 class V8_EXPORT External : public Value {
3190 static Local<External> New(Isolate* isolate, void* value);
3191 V8_INLINE static External* Cast(Value* obj);
3192 void* Value() const;
3194 static void CheckCast(v8::Value* obj);
3198 // --- Templates ---
3202 * The superclass of object and function templates.
3204 class V8_EXPORT Template : public Data {
3206 /** Adds a property to each instance created by this template.*/
3207 void Set(Handle<String> name, Handle<Data> value,
3208 PropertyAttribute attributes = None);
3209 V8_INLINE void Set(Isolate* isolate, const char* name, Handle<Data> value);
3211 void SetAccessorProperty(
3213 Local<FunctionTemplate> getter = Local<FunctionTemplate>(),
3214 Local<FunctionTemplate> setter = Local<FunctionTemplate>(),
3215 PropertyAttribute attribute = None,
3216 AccessControl settings = DEFAULT);
3219 * Whenever the property with the given name is accessed on objects
3220 * created from this Template the getter and setter callbacks
3221 * are called instead of getting and setting the property directly
3222 * on the JavaScript object.
3224 * \param name The name of the property for which an accessor is added.
3225 * \param getter The callback to invoke when getting the property.
3226 * \param setter The callback to invoke when setting the property.
3227 * \param data A piece of data that will be passed to the getter and setter
3228 * callbacks whenever they are invoked.
3229 * \param settings Access control settings for the accessor. This is a bit
3230 * field consisting of one of more of
3231 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
3232 * The default is to not allow cross-context access.
3233 * ALL_CAN_READ means that all cross-context reads are allowed.
3234 * ALL_CAN_WRITE means that all cross-context writes are allowed.
3235 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
3236 * cross-context access.
3237 * \param attribute The attributes of the property for which an accessor
3239 * \param signature The signature describes valid receivers for the accessor
3240 * and is used to perform implicit instance checks against them. If the
3241 * receiver is incompatible (i.e. is not an instance of the constructor as
3242 * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
3243 * thrown and no callback is invoked.
3245 void SetNativeDataProperty(Local<String> name,
3246 AccessorGetterCallback getter,
3247 AccessorSetterCallback setter = 0,
3248 // TODO(dcarney): gcc can't handle Local below
3249 Handle<Value> data = Handle<Value>(),
3250 PropertyAttribute attribute = None,
3251 Local<AccessorSignature> signature =
3252 Local<AccessorSignature>(),
3253 AccessControl settings = DEFAULT);
3255 // This function is not yet stable and should not be used at this time.
3256 bool SetDeclaredAccessor(Local<String> name,
3257 Local<DeclaredAccessorDescriptor> descriptor,
3258 PropertyAttribute attribute = None,
3259 Local<AccessorSignature> signature =
3260 Local<AccessorSignature>(),
3261 AccessControl settings = DEFAULT);
3266 friend class ObjectTemplate;
3267 friend class FunctionTemplate;
3272 * NamedProperty[Getter|Setter] are used as interceptors on object.
3273 * See ObjectTemplate::SetNamedPropertyHandler.
3275 typedef void (*NamedPropertyGetterCallback)(
3276 Local<String> property,
3277 const PropertyCallbackInfo<Value>& info);
3281 * Returns the value if the setter intercepts the request.
3282 * Otherwise, returns an empty handle.
3284 typedef void (*NamedPropertySetterCallback)(
3285 Local<String> property,
3287 const PropertyCallbackInfo<Value>& info);
3291 * Returns a non-empty handle if the interceptor intercepts the request.
3292 * The result is an integer encoding property attributes (like v8::None,
3293 * v8::DontEnum, etc.)
3295 typedef void (*NamedPropertyQueryCallback)(
3296 Local<String> property,
3297 const PropertyCallbackInfo<Integer>& info);
3301 * Returns a non-empty handle if the deleter intercepts the request.
3302 * The return value is true if the property could be deleted and false
3305 typedef void (*NamedPropertyDeleterCallback)(
3306 Local<String> property,
3307 const PropertyCallbackInfo<Boolean>& info);
3311 * Returns an array containing the names of the properties the named
3312 * property getter intercepts.
3314 typedef void (*NamedPropertyEnumeratorCallback)(
3315 const PropertyCallbackInfo<Array>& info);
3319 * Returns the value of the property if the getter intercepts the
3320 * request. Otherwise, returns an empty handle.
3322 typedef void (*IndexedPropertyGetterCallback)(
3324 const PropertyCallbackInfo<Value>& info);
3328 * Returns the value if the setter intercepts the request.
3329 * Otherwise, returns an empty handle.
3331 typedef void (*IndexedPropertySetterCallback)(
3334 const PropertyCallbackInfo<Value>& info);
3338 * Returns a non-empty handle if the interceptor intercepts the request.
3339 * The result is an integer encoding property attributes.
3341 typedef void (*IndexedPropertyQueryCallback)(
3343 const PropertyCallbackInfo<Integer>& info);
3347 * Returns a non-empty handle if the deleter intercepts the request.
3348 * The return value is true if the property could be deleted and false
3351 typedef void (*IndexedPropertyDeleterCallback)(
3353 const PropertyCallbackInfo<Boolean>& info);
3357 * Returns an array containing the indices of the properties the
3358 * indexed property getter intercepts.
3360 typedef void (*IndexedPropertyEnumeratorCallback)(
3361 const PropertyCallbackInfo<Array>& info);
3365 * Access type specification.
3377 * Returns true if cross-context access should be allowed to the named
3378 * property with the given key on the host object.
3380 typedef bool (*NamedSecurityCallback)(Local<Object> host,
3387 * Returns true if cross-context access should be allowed to the indexed
3388 * property with the given index on the host object.
3390 typedef bool (*IndexedSecurityCallback)(Local<Object> host,
3397 * A FunctionTemplate is used to create functions at runtime. There
3398 * can only be one function created from a FunctionTemplate in a
3399 * context. The lifetime of the created function is equal to the
3400 * lifetime of the context. So in case the embedder needs to create
3401 * temporary functions that can be collected using Scripts is
3404 * A FunctionTemplate can have properties, these properties are added to the
3405 * function object when it is created.
3407 * A FunctionTemplate has a corresponding instance template which is
3408 * used to create object instances when the function is used as a
3409 * constructor. Properties added to the instance template are added to
3410 * each object instance.
3412 * A FunctionTemplate can have a prototype template. The prototype template
3413 * is used to create the prototype object of the function.
3415 * The following example shows how to use a FunctionTemplate:
3418 * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
3419 * t->Set("func_property", v8::Number::New(1));
3421 * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
3422 * proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
3423 * proto_t->Set("proto_const", v8::Number::New(2));
3425 * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
3426 * instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
3427 * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
3428 * instance_t->Set("instance_property", Number::New(3));
3430 * v8::Local<v8::Function> function = t->GetFunction();
3431 * v8::Local<v8::Object> instance = function->NewInstance();
3434 * Let's use "function" as the JS variable name of the function object
3435 * and "instance" for the instance object created above. The function
3436 * and the instance will have the following properties:
3439 * func_property in function == true;
3440 * function.func_property == 1;
3442 * function.prototype.proto_method() invokes 'InvokeCallback'
3443 * function.prototype.proto_const == 2;
3445 * instance instanceof function == true;
3446 * instance.instance_accessor calls 'InstanceAccessorCallback'
3447 * instance.instance_property == 3;
3450 * A FunctionTemplate can inherit from another one by calling the
3451 * FunctionTemplate::Inherit method. The following graph illustrates
3452 * the semantics of inheritance:
3455 * FunctionTemplate Parent -> Parent() . prototype -> { }
3457 * | Inherit(Parent) | .__proto__
3459 * FunctionTemplate Child -> Child() . prototype -> { }
3462 * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
3463 * object of the Child() function has __proto__ pointing to the
3464 * Parent() function's prototype object. An instance of the Child
3465 * function has all properties on Parent's instance templates.
3467 * Let Parent be the FunctionTemplate initialized in the previous
3468 * section and create a Child FunctionTemplate by:
3471 * Local<FunctionTemplate> parent = t;
3472 * Local<FunctionTemplate> child = FunctionTemplate::New();
3473 * child->Inherit(parent);
3475 * Local<Function> child_function = child->GetFunction();
3476 * Local<Object> child_instance = child_function->NewInstance();
3479 * The Child function and Child instance will have the following
3483 * child_func.prototype.__proto__ == function.prototype;
3484 * child_instance.instance_accessor calls 'InstanceAccessorCallback'
3485 * child_instance.instance_property == 3;
3488 class V8_EXPORT FunctionTemplate : public Template {
3490 /** Creates a function template.*/
3491 static Local<FunctionTemplate> New(
3493 FunctionCallback callback = 0,
3494 Handle<Value> data = Handle<Value>(),
3495 Handle<Signature> signature = Handle<Signature>(),
3498 /** Returns the unique function instance in the current execution context.*/
3499 Local<Function> GetFunction();
3502 * Set the call-handler callback for a FunctionTemplate. This
3503 * callback is called whenever the function created from this
3504 * FunctionTemplate is called.
3506 void SetCallHandler(FunctionCallback callback,
3507 Handle<Value> data = Handle<Value>());
3509 /** Set the predefined length property for the FunctionTemplate. */
3510 void SetLength(int length);
3512 /** Get the InstanceTemplate. */
3513 Local<ObjectTemplate> InstanceTemplate();
3515 /** Causes the function template to inherit from a parent function template.*/
3516 void Inherit(Handle<FunctionTemplate> parent);
3519 * A PrototypeTemplate is the template used to create the prototype object
3520 * of the function created by this template.
3522 Local<ObjectTemplate> PrototypeTemplate();
3525 * Set the class name of the FunctionTemplate. This is used for
3526 * printing objects created with the function created from the
3527 * FunctionTemplate as its constructor.
3529 void SetClassName(Handle<String> name);
3532 * Determines whether the __proto__ accessor ignores instances of
3533 * the function template. If instances of the function template are
3534 * ignored, __proto__ skips all instances and instead returns the
3535 * next object in the prototype chain.
3537 * Call with a value of true to make the __proto__ accessor ignore
3538 * instances of the function template. Call with a value of false
3539 * to make the __proto__ accessor not ignore instances of the
3540 * function template. By default, instances of a function template
3543 void SetHiddenPrototype(bool value);
3546 * Sets the ReadOnly flag in the attributes of the 'prototype' property
3547 * of functions created from this FunctionTemplate to true.
3549 void ReadOnlyPrototype();
3552 * Removes the prototype property from functions created from this
3555 void RemovePrototype();
3558 * Returns true if the given object is an instance of this function
3561 bool HasInstance(Handle<Value> object);
3565 friend class Context;
3566 friend class ObjectTemplate;
3571 * An ObjectTemplate is used to create objects at runtime.
3573 * Properties added to an ObjectTemplate are added to each object
3574 * created from the ObjectTemplate.
3576 class V8_EXPORT ObjectTemplate : public Template {
3578 /** Creates an ObjectTemplate. */
3579 static Local<ObjectTemplate> New(Isolate* isolate);
3580 // Will be deprecated soon.
3581 static Local<ObjectTemplate> New();
3583 /** Creates a new instance of this template.*/
3584 Local<Object> NewInstance();
3587 * Sets an accessor on the object template.
3589 * Whenever the property with the given name is accessed on objects
3590 * created from this ObjectTemplate the getter and setter callbacks
3591 * are called instead of getting and setting the property directly
3592 * on the JavaScript object.
3594 * \param name The name of the property for which an accessor is added.
3595 * \param getter The callback to invoke when getting the property.
3596 * \param setter The callback to invoke when setting the property.
3597 * \param data A piece of data that will be passed to the getter and setter
3598 * callbacks whenever they are invoked.
3599 * \param settings Access control settings for the accessor. This is a bit
3600 * field consisting of one of more of
3601 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
3602 * The default is to not allow cross-context access.
3603 * ALL_CAN_READ means that all cross-context reads are allowed.
3604 * ALL_CAN_WRITE means that all cross-context writes are allowed.
3605 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
3606 * cross-context access.
3607 * \param attribute The attributes of the property for which an accessor
3609 * \param signature The signature describes valid receivers for the accessor
3610 * and is used to perform implicit instance checks against them. If the
3611 * receiver is incompatible (i.e. is not an instance of the constructor as
3612 * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
3613 * thrown and no callback is invoked.
3615 void SetAccessor(Handle<String> name,
3616 AccessorGetterCallback getter,
3617 AccessorSetterCallback setter = 0,
3618 Handle<Value> data = Handle<Value>(),
3619 AccessControl settings = DEFAULT,
3620 PropertyAttribute attribute = None,
3621 Handle<AccessorSignature> signature =
3622 Handle<AccessorSignature>());
3625 * Sets a named property handler on the object template.
3627 * Whenever a named property is accessed on objects created from
3628 * this object template, the provided callback is invoked instead of
3629 * accessing the property directly on the JavaScript object.
3631 * \param getter The callback to invoke when getting a property.
3632 * \param setter The callback to invoke when setting a property.
3633 * \param query The callback to invoke to check if a property is present,
3634 * and if present, get its attributes.
3635 * \param deleter The callback to invoke when deleting a property.
3636 * \param enumerator The callback to invoke to enumerate all the named
3637 * properties of an object.
3638 * \param data A piece of data that will be passed to the callbacks
3639 * whenever they are invoked.
3641 void SetNamedPropertyHandler(
3642 NamedPropertyGetterCallback getter,
3643 NamedPropertySetterCallback setter = 0,
3644 NamedPropertyQueryCallback query = 0,
3645 NamedPropertyDeleterCallback deleter = 0,
3646 NamedPropertyEnumeratorCallback enumerator = 0,
3647 Handle<Value> data = Handle<Value>());
3650 * Sets an indexed property handler on the object template.
3652 * Whenever an indexed property is accessed on objects created from
3653 * this object template, the provided callback is invoked instead of
3654 * accessing the property directly on the JavaScript object.
3656 * \param getter The callback to invoke when getting a property.
3657 * \param setter The callback to invoke when setting a property.
3658 * \param query The callback to invoke to check if an object has a property.
3659 * \param deleter The callback to invoke when deleting a property.
3660 * \param enumerator The callback to invoke to enumerate all the indexed
3661 * properties of an object.
3662 * \param data A piece of data that will be passed to the callbacks
3663 * whenever they are invoked.
3665 void SetIndexedPropertyHandler(
3666 IndexedPropertyGetterCallback getter,
3667 IndexedPropertySetterCallback setter = 0,
3668 IndexedPropertyQueryCallback query = 0,
3669 IndexedPropertyDeleterCallback deleter = 0,
3670 IndexedPropertyEnumeratorCallback enumerator = 0,
3671 Handle<Value> data = Handle<Value>());
3674 * Sets the callback to be used when calling instances created from
3675 * this template as a function. If no callback is set, instances
3676 * behave like normal JavaScript objects that cannot be called as a
3679 void SetCallAsFunctionHandler(FunctionCallback callback,
3680 Handle<Value> data = Handle<Value>());
3683 * Mark object instances of the template as undetectable.
3685 * In many ways, undetectable objects behave as though they are not
3686 * there. They behave like 'undefined' in conditionals and when
3687 * printed. However, properties can be accessed and called as on
3690 void MarkAsUndetectable();
3693 * Sets access check callbacks on the object template.
3695 * When accessing properties on instances of this object template,
3696 * the access check callback will be called to determine whether or
3697 * not to allow cross-context access to the properties.
3698 * The last parameter specifies whether access checks are turned
3699 * on by default on instances. If access checks are off by default,
3700 * they can be turned on on individual instances by calling
3701 * Object::TurnOnAccessCheck().
3703 void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
3704 IndexedSecurityCallback indexed_handler,
3705 Handle<Value> data = Handle<Value>(),
3706 bool turned_on_by_default = true);
3709 * Gets the number of internal fields for objects generated from
3712 int InternalFieldCount();
3715 * Sets the number of internal fields for objects generated from
3718 void SetInternalFieldCount(int value);
3722 static Local<ObjectTemplate> New(internal::Isolate* isolate,
3723 Handle<FunctionTemplate> constructor);
3724 friend class FunctionTemplate;
3729 * A Signature specifies which receivers and arguments are valid
3730 * parameters to a function.
3732 class V8_EXPORT Signature : public Data {
3734 static Local<Signature> New(Isolate* isolate,
3735 Handle<FunctionTemplate> receiver =
3736 Handle<FunctionTemplate>(),
3738 Handle<FunctionTemplate> argv[] = 0);
3746 * An AccessorSignature specifies which receivers are valid parameters
3747 * to an accessor callback.
3749 class V8_EXPORT AccessorSignature : public Data {
3751 static Local<AccessorSignature> New(Isolate* isolate,
3752 Handle<FunctionTemplate> receiver =
3753 Handle<FunctionTemplate>());
3756 AccessorSignature();
3760 class V8_EXPORT DeclaredAccessorDescriptor : public Data {
3762 DeclaredAccessorDescriptor();
3766 class V8_EXPORT ObjectOperationDescriptor : public Data {
3768 // This function is not yet stable and should not be used at this time.
3769 static Local<RawOperationDescriptor> NewInternalFieldDereference(
3771 int internal_field);
3773 ObjectOperationDescriptor();
3777 enum DeclaredAccessorDescriptorDataType {
3778 kDescriptorBoolType,
3779 kDescriptorInt8Type, kDescriptorUint8Type,
3780 kDescriptorInt16Type, kDescriptorUint16Type,
3781 kDescriptorInt32Type, kDescriptorUint32Type,
3782 kDescriptorFloatType, kDescriptorDoubleType
3786 class V8_EXPORT RawOperationDescriptor : public Data {
3788 Local<DeclaredAccessorDescriptor> NewHandleDereference(Isolate* isolate);
3789 Local<RawOperationDescriptor> NewRawDereference(Isolate* isolate);
3790 Local<RawOperationDescriptor> NewRawShift(Isolate* isolate,
3791 int16_t byte_offset);
3792 Local<DeclaredAccessorDescriptor> NewPointerCompare(Isolate* isolate,
3793 void* compare_value);
3794 Local<DeclaredAccessorDescriptor> NewPrimitiveValue(
3796 DeclaredAccessorDescriptorDataType data_type,
3797 uint8_t bool_offset = 0);
3798 Local<DeclaredAccessorDescriptor> NewBitmaskCompare8(Isolate* isolate,
3800 uint8_t compare_value);
3801 Local<DeclaredAccessorDescriptor> NewBitmaskCompare16(
3804 uint16_t compare_value);
3805 Local<DeclaredAccessorDescriptor> NewBitmaskCompare32(
3808 uint32_t compare_value);
3811 RawOperationDescriptor();
3816 * A utility for determining the type of objects based on the template
3817 * they were constructed from.
3819 class V8_EXPORT TypeSwitch : public Data {
3821 static Local<TypeSwitch> New(Handle<FunctionTemplate> type);
3822 static Local<TypeSwitch> New(int argc, Handle<FunctionTemplate> types[]);
3823 int match(Handle<Value> value);
3829 // --- Extensions ---
3831 class V8_EXPORT ExternalAsciiStringResourceImpl
3832 : public String::ExternalAsciiStringResource {
3834 ExternalAsciiStringResourceImpl() : data_(0), length_(0) {}
3835 ExternalAsciiStringResourceImpl(const char* data, size_t length)
3836 : data_(data), length_(length) {}
3837 const char* data() const { return data_; }
3838 size_t length() const { return length_; }
3848 class V8_EXPORT Extension { // NOLINT
3850 // Note that the strings passed into this constructor must live as long
3851 // as the Extension itself.
3852 Extension(const char* name,
3853 const char* source = 0,
3855 const char** deps = 0,
3856 int source_length = -1);
3857 virtual ~Extension() { }
3858 virtual v8::Handle<v8::FunctionTemplate> GetNativeFunctionTemplate(
3859 v8::Isolate* isolate, v8::Handle<v8::String> name) {
3860 return v8::Handle<v8::FunctionTemplate>();
3863 const char* name() const { return name_; }
3864 size_t source_length() const { return source_length_; }
3865 const String::ExternalAsciiStringResource* source() const {
3867 int dependency_count() { return dep_count_; }
3868 const char** dependencies() { return deps_; }
3869 void set_auto_enable(bool value) { auto_enable_ = value; }
3870 bool auto_enable() { return auto_enable_; }
3874 size_t source_length_; // expected to initialize before source_
3875 ExternalAsciiStringResourceImpl source_;
3880 // Disallow copying and assigning.
3881 Extension(const Extension&);
3882 void operator=(const Extension&);
3886 void V8_EXPORT RegisterExtension(Extension* extension);
3891 V8_INLINE Handle<Primitive> Undefined(Isolate* isolate);
3892 V8_INLINE Handle<Primitive> Null(Isolate* isolate);
3893 V8_INLINE Handle<Boolean> True(Isolate* isolate);
3894 V8_INLINE Handle<Boolean> False(Isolate* isolate);
3898 * A set of constraints that specifies the limits of the runtime's memory use.
3899 * You must set the heap size before initializing the VM - the size cannot be
3900 * adjusted after the VM is initialized.
3902 * If you are using threads then you should hold the V8::Locker lock while
3903 * setting the stack limit and you must set a non-default stack limit separately
3906 class V8_EXPORT ResourceConstraints {
3908 ResourceConstraints();
3911 * Configures the constraints with reasonable default values based on the
3912 * capabilities of the current device the VM is running on.
3914 * \param physical_memory The total amount of physical memory on the current
3916 * \param virtual_memory_limit The amount of virtual memory on the current
3917 * device, in bytes, or zero, if there is no limit.
3918 * \param number_of_processors The number of CPUs available on the current
3921 void ConfigureDefaults(uint64_t physical_memory,
3922 uint64_t virtual_memory_limit,
3923 uint32_t number_of_processors);
3925 int max_new_space_size() const { return max_new_space_size_; }
3926 void set_max_new_space_size(int value) { max_new_space_size_ = value; }
3927 int max_old_space_size() const { return max_old_space_size_; }
3928 void set_max_old_space_size(int value) { max_old_space_size_ = value; }
3929 int max_executable_size() const { return max_executable_size_; }
3930 void set_max_executable_size(int value) { max_executable_size_ = value; }
3931 uint32_t* stack_limit() const { return stack_limit_; }
3932 // Sets an address beyond which the VM's stack may not grow.
3933 void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
3934 int max_available_threads() const { return max_available_threads_; }
3935 // Set the number of threads available to V8, assuming at least 1.
3936 void set_max_available_threads(int value) {
3937 max_available_threads_ = value;
3939 int code_range_size() const { return code_range_size_; }
3940 void set_code_range_size(int value) {
3941 code_range_size_ = value;
3945 int max_new_space_size_;
3946 int max_old_space_size_;
3947 int max_executable_size_;
3948 uint32_t* stack_limit_;
3949 int max_available_threads_;
3950 int code_range_size_;
3955 * Sets the given ResourceConstraints on the given Isolate.
3957 bool V8_EXPORT SetResourceConstraints(Isolate* isolate,
3958 ResourceConstraints* constraints);
3961 // --- Exceptions ---
3964 typedef void (*FatalErrorCallback)(const char* location, const char* message);
3967 typedef void (*MessageCallback)(Handle<Message> message, Handle<Value> error);
3971 typedef void (*LogEventCallback)(const char* name, int event);
3974 * Create new error objects by calling the corresponding error object
3975 * constructor with the message.
3977 class V8_EXPORT Exception {
3979 static Local<Value> RangeError(Handle<String> message);
3980 static Local<Value> ReferenceError(Handle<String> message);
3981 static Local<Value> SyntaxError(Handle<String> message);
3982 static Local<Value> TypeError(Handle<String> message);
3983 static Local<Value> Error(Handle<String> message);
3987 // --- Counters Callbacks ---
3989 typedef int* (*CounterLookupCallback)(const char* name);
3991 typedef void* (*CreateHistogramCallback)(const char* name,
3996 typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
3998 // --- Memory Allocation Callback ---
4000 kObjectSpaceNewSpace = 1 << 0,
4001 kObjectSpaceOldPointerSpace = 1 << 1,
4002 kObjectSpaceOldDataSpace = 1 << 2,
4003 kObjectSpaceCodeSpace = 1 << 3,
4004 kObjectSpaceMapSpace = 1 << 4,
4005 kObjectSpaceLoSpace = 1 << 5,
4007 kObjectSpaceAll = kObjectSpaceNewSpace | kObjectSpaceOldPointerSpace |
4008 kObjectSpaceOldDataSpace | kObjectSpaceCodeSpace | kObjectSpaceMapSpace |
4012 enum AllocationAction {
4013 kAllocationActionAllocate = 1 << 0,
4014 kAllocationActionFree = 1 << 1,
4015 kAllocationActionAll = kAllocationActionAllocate | kAllocationActionFree
4018 typedef void (*MemoryAllocationCallback)(ObjectSpace space,
4019 AllocationAction action,
4022 // --- Leave Script Callback ---
4023 typedef void (*CallCompletedCallback)();
4025 // --- Failed Access Check Callback ---
4026 typedef void (*FailedAccessCheckCallback)(Local<Object> target,
4030 // --- AllowCodeGenerationFromStrings callbacks ---
4033 * Callback to check if code generation from strings is allowed. See
4034 * Context::AllowCodeGenerationFromStrings.
4036 typedef bool (*AllowCodeGenerationFromStringsCallback)(Local<Context> context);
4038 // --- Garbage Collection Callbacks ---
4041 * Applications can register callback functions which will be called
4042 * before and after a garbage collection. Allocations are not
4043 * allowed in the callback functions, you therefore cannot manipulate
4044 * objects (set or delete properties for example) since it is possible
4045 * such operations will result in the allocation of objects.
4048 kGCTypeScavenge = 1 << 0,
4049 kGCTypeMarkSweepCompact = 1 << 1,
4050 kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact
4053 enum GCCallbackFlags {
4054 kNoGCCallbackFlags = 0,
4055 kGCCallbackFlagCompacted = 1 << 0,
4056 kGCCallbackFlagConstructRetainedObjectInfos = 1 << 1,
4057 kGCCallbackFlagForced = 1 << 2
4060 typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
4061 typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
4063 typedef void (*InterruptCallback)(Isolate* isolate, void* data);
4067 * Collection of V8 heap information.
4069 * Instances of this class can be passed to v8::V8::HeapStatistics to
4070 * get heap statistics from V8.
4072 class V8_EXPORT HeapStatistics {
4075 size_t total_heap_size() { return total_heap_size_; }
4076 size_t total_heap_size_executable() { return total_heap_size_executable_; }
4077 size_t total_physical_size() { return total_physical_size_; }
4078 size_t used_heap_size() { return used_heap_size_; }
4079 size_t heap_size_limit() { return heap_size_limit_; }
4082 size_t total_heap_size_;
4083 size_t total_heap_size_executable_;
4084 size_t total_physical_size_;
4085 size_t used_heap_size_;
4086 size_t heap_size_limit_;
4089 friend class Isolate;
4093 class RetainedObjectInfo;
4096 * Isolate represents an isolated instance of the V8 engine. V8
4097 * isolates have completely separate states. Objects from one isolate
4098 * must not be used in other isolates. When V8 is initialized a
4099 * default isolate is implicitly created and entered. The embedder
4100 * can create additional isolates and use them in parallel in multiple
4101 * threads. An isolate can be entered by at most one thread at any
4102 * given time. The Locker/Unlocker API must be used to synchronize.
4104 class V8_EXPORT Isolate {
4107 * Stack-allocated class which sets the isolate for all operations
4108 * executed within a local scope.
4110 class V8_EXPORT Scope {
4112 explicit Scope(Isolate* isolate) : isolate_(isolate) {
4116 ~Scope() { isolate_->Exit(); }
4119 Isolate* const isolate_;
4121 // Prevent copying of Scope objects.
4122 Scope(const Scope&);
4123 Scope& operator=(const Scope&);
4128 * Assert that no Javascript code is invoked.
4130 class V8_EXPORT DisallowJavascriptExecutionScope {
4132 enum OnFailure { CRASH_ON_FAILURE, THROW_ON_FAILURE };
4134 DisallowJavascriptExecutionScope(Isolate* isolate, OnFailure on_failure);
4135 ~DisallowJavascriptExecutionScope();
4141 // Prevent copying of Scope objects.
4142 DisallowJavascriptExecutionScope(const DisallowJavascriptExecutionScope&);
4143 DisallowJavascriptExecutionScope& operator=(
4144 const DisallowJavascriptExecutionScope&);
4149 * Introduce exception to DisallowJavascriptExecutionScope.
4151 class V8_EXPORT AllowJavascriptExecutionScope {
4153 explicit AllowJavascriptExecutionScope(Isolate* isolate);
4154 ~AllowJavascriptExecutionScope();
4157 void* internal_throws_;
4158 void* internal_assert_;
4160 // Prevent copying of Scope objects.
4161 AllowJavascriptExecutionScope(const AllowJavascriptExecutionScope&);
4162 AllowJavascriptExecutionScope& operator=(
4163 const AllowJavascriptExecutionScope&);
4167 * Do not run microtasks while this scope is active, even if microtasks are
4168 * automatically executed otherwise.
4170 class V8_EXPORT SuppressMicrotaskExecutionScope {
4172 explicit SuppressMicrotaskExecutionScope(Isolate* isolate);
4173 ~SuppressMicrotaskExecutionScope();
4176 internal::Isolate* isolate_;
4178 // Prevent copying of Scope objects.
4179 SuppressMicrotaskExecutionScope(const SuppressMicrotaskExecutionScope&);
4180 SuppressMicrotaskExecutionScope& operator=(
4181 const SuppressMicrotaskExecutionScope&);
4185 * Types of garbage collections that can be requested via
4186 * RequestGarbageCollectionForTesting.
4188 enum GarbageCollectionType {
4189 kFullGarbageCollection,
4190 kMinorGarbageCollection
4194 * Creates a new isolate. Does not change the currently entered
4197 * When an isolate is no longer used its resources should be freed
4198 * by calling Dispose(). Using the delete operator is not allowed.
4200 static Isolate* New();
4203 * Returns the entered isolate for the current thread or NULL in
4204 * case there is no current isolate.
4206 static Isolate* GetCurrent();
4209 * Methods below this point require holding a lock (using Locker) in
4210 * a multi-threaded environment.
4214 * Sets this isolate as the entered one for the current thread.
4215 * Saves the previously entered one (if any), so that it can be
4216 * restored when exiting. Re-entering an isolate is allowed.
4221 * Exits this isolate by restoring the previously entered one in the
4222 * current thread. The isolate may still stay the same, if it was
4223 * entered more than once.
4225 * Requires: this == Isolate::GetCurrent().
4230 * Disposes the isolate. The isolate must not be entered by any
4231 * thread to be disposable.
4236 * Associate embedder-specific data with the isolate. |slot| has to be
4237 * between 0 and GetNumberOfDataSlots() - 1.
4239 V8_INLINE void SetData(uint32_t slot, void* data);
4242 * Retrieve embedder-specific data from the isolate.
4243 * Returns NULL if SetData has never been called for the given |slot|.
4245 V8_INLINE void* GetData(uint32_t slot);
4248 * Returns the maximum number of available embedder data slots. Valid slots
4249 * are in the range of 0 - GetNumberOfDataSlots() - 1.
4251 V8_INLINE static uint32_t GetNumberOfDataSlots();
4254 * Get statistics about the heap memory usage.
4256 void GetHeapStatistics(HeapStatistics* heap_statistics);
4259 * Adjusts the amount of registered external memory. Used to give V8 an
4260 * indication of the amount of externally allocated memory that is kept alive
4261 * by JavaScript objects. V8 uses this to decide when to perform global
4262 * garbage collections. Registering externally allocated memory will trigger
4263 * global garbage collections more often than it would otherwise in an attempt
4264 * to garbage collect the JavaScript objects that keep the externally
4265 * allocated memory alive.
4267 * \param change_in_bytes the change in externally allocated memory that is
4268 * kept alive by JavaScript objects.
4269 * \returns the adjusted value.
4271 int64_t AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes);
4274 * Returns heap profiler for this isolate. Will return NULL until the isolate
4277 HeapProfiler* GetHeapProfiler();
4280 * Returns CPU profiler for this isolate. Will return NULL unless the isolate
4281 * is initialized. It is the embedder's responsibility to stop all CPU
4282 * profiling activities if it has started any.
4284 CpuProfiler* GetCpuProfiler();
4286 /** Returns true if this isolate has a current context. */
4289 /** Returns the context that is on the top of the stack. */
4290 Local<Context> GetCurrentContext();
4293 * Returns the context of the calling JavaScript code. That is the
4294 * context of the top-most JavaScript frame. If there are no
4295 * JavaScript frames an empty handle is returned.
4297 Local<Context> GetCallingContext();
4299 /** Returns the last entered context. */
4300 Local<Context> GetEnteredContext();
4303 * Schedules an exception to be thrown when returning to JavaScript. When an
4304 * exception has been scheduled it is illegal to invoke any JavaScript
4305 * operation; the caller must return immediately and only after the exception
4306 * has been handled does it become legal to invoke JavaScript operations.
4308 Local<Value> ThrowException(Local<Value> exception);
4311 * Allows the host application to group objects together. If one
4312 * object in the group is alive, all objects in the group are alive.
4313 * After each garbage collection, object groups are removed. It is
4314 * intended to be used in the before-garbage-collection callback
4315 * function, for instance to simulate DOM tree connections among JS
4316 * wrapper objects. Object groups for all dependent handles need to
4317 * be provided for kGCTypeMarkSweepCompact collections, for all other
4318 * garbage collection types it is sufficient to provide object groups
4319 * for partially dependent handles only.
4321 template<typename T> void SetObjectGroupId(const Persistent<T>& object,
4325 * Allows the host application to declare implicit references from an object
4326 * group to an object. If the objects of the object group are alive, the child
4327 * object is alive too. After each garbage collection, all implicit references
4328 * are removed. It is intended to be used in the before-garbage-collection
4329 * callback function.
4331 template<typename T> void SetReferenceFromGroup(UniqueId id,
4332 const Persistent<T>& child);
4335 * Allows the host application to declare implicit references from an object
4336 * to another object. If the parent object is alive, the child object is alive
4337 * too. After each garbage collection, all implicit references are removed. It
4338 * is intended to be used in the before-garbage-collection callback function.
4340 template<typename T, typename S>
4341 void SetReference(const Persistent<T>& parent, const Persistent<S>& child);
4343 typedef void (*GCPrologueCallback)(Isolate* isolate,
4345 GCCallbackFlags flags);
4346 typedef void (*GCEpilogueCallback)(Isolate* isolate,
4348 GCCallbackFlags flags);
4351 * Enables the host application to receive a notification before a
4352 * garbage collection. Allocations are allowed in the callback function,
4353 * but the callback is not re-entrant: if the allocation inside it will
4354 * trigger the garbage collection, the callback won't be called again.
4355 * It is possible to specify the GCType filter for your callback. But it is
4356 * not possible to register the same callback function two times with
4357 * different GCType filters.
4359 void AddGCPrologueCallback(
4360 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
4363 * This function removes callback which was installed by
4364 * AddGCPrologueCallback function.
4366 void RemoveGCPrologueCallback(GCPrologueCallback callback);
4369 * Enables the host application to receive a notification after a
4370 * garbage collection. Allocations are allowed in the callback function,
4371 * but the callback is not re-entrant: if the allocation inside it will
4372 * trigger the garbage collection, the callback won't be called again.
4373 * It is possible to specify the GCType filter for your callback. But it is
4374 * not possible to register the same callback function two times with
4375 * different GCType filters.
4377 void AddGCEpilogueCallback(
4378 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
4381 * This function removes callback which was installed by
4382 * AddGCEpilogueCallback function.
4384 void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
4387 * Request V8 to interrupt long running JavaScript code and invoke
4388 * the given |callback| passing the given |data| to it. After |callback|
4389 * returns control will be returned to the JavaScript code.
4390 * At any given moment V8 can remember only a single callback for the very
4391 * last interrupt request.
4392 * Can be called from another thread without acquiring a |Locker|.
4393 * Registered |callback| must not reenter interrupted Isolate.
4395 void RequestInterrupt(InterruptCallback callback, void* data);
4398 * Clear interrupt request created by |RequestInterrupt|.
4399 * Can be called from another thread without acquiring a |Locker|.
4401 void ClearInterrupt();
4404 * Request garbage collection in this Isolate. It is only valid to call this
4405 * function if --expose_gc was specified.
4407 * This should only be used for testing purposes and not to enforce a garbage
4408 * collection schedule. It has strong negative impact on the garbage
4409 * collection performance. Use IdleNotification() or LowMemoryNotification()
4410 * instead to influence the garbage collection schedule.
4412 void RequestGarbageCollectionForTesting(GarbageCollectionType type);
4415 * Set the callback to invoke for logging event.
4417 void SetEventLogger(LogEventCallback that);
4420 * Adds a callback to notify the host application when a script finished
4421 * running. If a script re-enters the runtime during executing, the
4422 * CallCompletedCallback is only invoked when the outer-most script
4423 * execution ends. Executing scripts inside the callback do not trigger
4424 * further callbacks.
4426 void AddCallCompletedCallback(CallCompletedCallback callback);
4429 * Removes callback that was installed by AddCallCompletedCallback.
4431 void RemoveCallCompletedCallback(CallCompletedCallback callback);
4434 * Experimental: Runs the Microtask Work Queue until empty
4436 void RunMicrotasks();
4439 * Experimental: Enqueues the callback to the Microtask Work Queue
4441 void EnqueueMicrotask(Handle<Function> microtask);
4444 * Experimental: Controls whether the Microtask Work Queue is automatically
4445 * run when the script call depth decrements to zero.
4447 void SetAutorunMicrotasks(bool autorun);
4450 template<class K, class V, class Traits> friend class PersistentValueMap;
4453 Isolate(const Isolate&);
4455 Isolate& operator=(const Isolate&);
4456 void* operator new(size_t size);
4457 void operator delete(void*, size_t);
4459 void SetObjectGroupId(internal::Object** object, UniqueId id);
4460 void SetReferenceFromGroup(UniqueId id, internal::Object** object);
4461 void SetReference(internal::Object** parent, internal::Object** child);
4464 class V8_EXPORT StartupData {
4466 enum CompressionAlgorithm {
4472 int compressed_size;
4478 * A helper class for driving V8 startup data decompression. It is based on
4479 * "CompressedStartupData" API functions from the V8 class. It isn't mandatory
4480 * for an embedder to use this class, instead, API functions can be used
4483 * For an example of the class usage, see the "shell.cc" sample application.
4485 class V8_EXPORT StartupDataDecompressor { // NOLINT
4487 StartupDataDecompressor();
4488 virtual ~StartupDataDecompressor();
4492 virtual int DecompressData(char* raw_data,
4494 const char* compressed_data,
4495 int compressed_data_size) = 0;
4503 * EntropySource is used as a callback function when v8 needs a source
4506 typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
4510 * ReturnAddressLocationResolver is used as a callback function when v8 is
4511 * resolving the location of a return address on the stack. Profilers that
4512 * change the return address on the stack can use this to resolve the stack
4513 * location to whereever the profiler stashed the original return address.
4515 * \param return_addr_location points to a location on stack where a machine
4516 * return address resides.
4517 * \returns either return_addr_location, or else a pointer to the profiler's
4518 * copy of the original return address.
4520 * \note the resolver function must not cause garbage collection.
4522 typedef uintptr_t (*ReturnAddressLocationResolver)(
4523 uintptr_t return_addr_location);
4527 * FunctionEntryHook is the type of the profile entry hook called at entry to
4528 * any generated function when function-level profiling is enabled.
4530 * \param function the address of the function that's being entered.
4531 * \param return_addr_location points to a location on stack where the machine
4532 * return address resides. This can be used to identify the caller of
4533 * \p function, and/or modified to divert execution when \p function exits.
4535 * \note the entry hook must not cause garbage collection.
4537 typedef void (*FunctionEntryHook)(uintptr_t function,
4538 uintptr_t return_addr_location);
4542 * A JIT code event is issued each time code is added, moved or removed.
4544 * \note removal events are not currently issued.
4546 struct JitCodeEvent {
4551 CODE_ADD_LINE_POS_INFO,
4552 CODE_START_LINE_INFO_RECORDING,
4553 CODE_END_LINE_INFO_RECORDING
4555 // Definition of the code position type. The "POSITION" type means the place
4556 // in the source code which are of interest when making stack traces to
4557 // pin-point the source location of a stack frame as close as possible.
4558 // The "STATEMENT_POSITION" means the place at the beginning of each
4559 // statement, and is used to indicate possible break locations.
4567 // Start of the instructions.
4569 // Size of the instructions.
4571 // Script info for CODE_ADDED event.
4572 Handle<Script> script;
4573 // User-defined data for *_LINE_INFO_* event. It's used to hold the source
4574 // code line information which is returned from the
4575 // CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent
4576 // CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events.
4580 // Name of the object associated with the code, note that the string is not
4583 // Number of chars in str.
4587 struct line_info_t {
4592 // The position type.
4593 PositionType position_type;
4597 // Only valid for CODE_ADDED.
4600 // Only valid for CODE_ADD_LINE_POS_INFO
4601 struct line_info_t line_info;
4603 // New location of instructions. Only valid for CODE_MOVED.
4604 void* new_code_start;
4609 * Option flags passed to the SetJitCodeEventHandler function.
4611 enum JitCodeEventOptions {
4612 kJitCodeEventDefault = 0,
4613 // Generate callbacks for already existent code.
4614 kJitCodeEventEnumExisting = 1
4619 * Callback function passed to SetJitCodeEventHandler.
4621 * \param event code add, move or removal event.
4623 typedef void (*JitCodeEventHandler)(const JitCodeEvent* event);
4627 * Interface for iterating through all external resources in the heap.
4629 class V8_EXPORT ExternalResourceVisitor { // NOLINT
4631 virtual ~ExternalResourceVisitor() {}
4632 virtual void VisitExternalString(Handle<String> string) {}
4637 * Interface for iterating through all the persistent handles in the heap.
4639 class V8_EXPORT PersistentHandleVisitor { // NOLINT
4641 virtual ~PersistentHandleVisitor() {}
4642 virtual void VisitPersistentHandle(Persistent<Value>* value,
4643 uint16_t class_id) {}
4648 * Container class for static utility functions.
4650 class V8_EXPORT V8 {
4652 /** Set the callback to invoke in case of fatal errors. */
4653 static void SetFatalErrorHandler(FatalErrorCallback that);
4656 * Set the callback to invoke to check if code generation from
4657 * strings should be allowed.
4659 static void SetAllowCodeGenerationFromStringsCallback(
4660 AllowCodeGenerationFromStringsCallback that);
4663 * Set allocator to use for ArrayBuffer memory.
4664 * The allocator should be set only once. The allocator should be set
4665 * before any code tha uses ArrayBuffers is executed.
4666 * This allocator is used in all isolates.
4668 static void SetArrayBufferAllocator(ArrayBuffer::Allocator* allocator);
4671 * Check if V8 is dead and therefore unusable. This is the case after
4672 * fatal errors such as out-of-memory situations.
4674 static bool IsDead();
4677 * The following 4 functions are to be used when V8 is built with
4678 * the 'compress_startup_data' flag enabled. In this case, the
4679 * embedder must decompress startup data prior to initializing V8.
4681 * This is how interaction with V8 should look like:
4682 * int compressed_data_count = v8::V8::GetCompressedStartupDataCount();
4683 * v8::StartupData* compressed_data =
4684 * new v8::StartupData[compressed_data_count];
4685 * v8::V8::GetCompressedStartupData(compressed_data);
4686 * ... decompress data (compressed_data can be updated in-place) ...
4687 * v8::V8::SetDecompressedStartupData(compressed_data);
4688 * ... now V8 can be initialized
4689 * ... make sure the decompressed data stays valid until V8 shutdown
4691 * A helper class StartupDataDecompressor is provided. It implements
4692 * the protocol of the interaction described above, and can be used in
4693 * most cases instead of calling these API functions directly.
4695 static StartupData::CompressionAlgorithm GetCompressedStartupDataAlgorithm();
4696 static int GetCompressedStartupDataCount();
4697 static void GetCompressedStartupData(StartupData* compressed_data);
4698 static void SetDecompressedStartupData(StartupData* decompressed_data);
4701 * Adds a message listener.
4703 * The same message listener can be added more than once and in that
4704 * case it will be called more than once for each message.
4706 * If data is specified, it will be passed to the callback when it is called.
4707 * Otherwise, the exception object will be passed to the callback instead.
4709 static bool AddMessageListener(MessageCallback that,
4710 Handle<Value> data = Handle<Value>());
4713 * Remove all message listeners from the specified callback function.
4715 static void RemoveMessageListeners(MessageCallback that);
4718 * Tells V8 to capture current stack trace when uncaught exception occurs
4719 * and report it to the message listeners. The option is off by default.
4721 static void SetCaptureStackTraceForUncaughtExceptions(
4723 int frame_limit = 10,
4724 StackTrace::StackTraceOptions options = StackTrace::kOverview);
4727 * Sets V8 flags from a string.
4729 static void SetFlagsFromString(const char* str, int length);
4732 * Sets V8 flags from the command line.
4734 static void SetFlagsFromCommandLine(int* argc,
4738 /** Get the version string. */
4739 static const char* GetVersion();
4742 * Enables the host application to provide a mechanism for recording
4743 * statistics counters.
4745 static void SetCounterFunction(CounterLookupCallback);
4748 * Enables the host application to provide a mechanism for recording
4749 * histograms. The CreateHistogram function returns a
4750 * histogram which will later be passed to the AddHistogramSample
4753 static void SetCreateHistogramFunction(CreateHistogramCallback);
4754 static void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
4756 /** Callback function for reporting failed access checks.*/
4757 static void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
4760 * Enables the host application to receive a notification before a
4761 * garbage collection. Allocations are not allowed in the
4762 * callback function, you therefore cannot manipulate objects (set
4763 * or delete properties for example) since it is possible such
4764 * operations will result in the allocation of objects. It is possible
4765 * to specify the GCType filter for your callback. But it is not possible to
4766 * register the same callback function two times with different
4769 static void AddGCPrologueCallback(
4770 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
4773 * This function removes callback which was installed by
4774 * AddGCPrologueCallback function.
4776 static void RemoveGCPrologueCallback(GCPrologueCallback callback);
4779 * Enables the host application to receive a notification after a
4780 * garbage collection. Allocations are not allowed in the
4781 * callback function, you therefore cannot manipulate objects (set
4782 * or delete properties for example) since it is possible such
4783 * operations will result in the allocation of objects. It is possible
4784 * to specify the GCType filter for your callback. But it is not possible to
4785 * register the same callback function two times with different
4788 static void AddGCEpilogueCallback(
4789 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
4792 * This function removes callback which was installed by
4793 * AddGCEpilogueCallback function.
4795 static void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
4798 * Enables the host application to provide a mechanism to be notified
4799 * and perform custom logging when V8 Allocates Executable Memory.
4801 static void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
4803 AllocationAction action);
4806 * Removes callback that was installed by AddMemoryAllocationCallback.
4808 static void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
4811 * Experimental: Runs the Microtask Work Queue until empty
4813 * Deprecated: Use methods on Isolate instead.
4815 static void RunMicrotasks(Isolate* isolate);
4818 * Experimental: Enqueues the callback to the Microtask Work Queue
4820 * Deprecated: Use methods on Isolate instead.
4822 static void EnqueueMicrotask(Isolate* isolate, Handle<Function> microtask);
4825 * Experimental: Controls whether the Microtask Work Queue is automatically
4826 * run when the script call depth decrements to zero.
4828 * Deprecated: Use methods on Isolate instead.
4830 static void SetAutorunMicrotasks(Isolate *source, bool autorun);
4833 * Initializes from snapshot if possible. Otherwise, attempts to
4834 * initialize from scratch. This function is called implicitly if
4835 * you use the API without calling it first.
4837 static bool Initialize();
4840 * Allows the host application to provide a callback which can be used
4841 * as a source of entropy for random number generators.
4843 static void SetEntropySource(EntropySource source);
4846 * Allows the host application to provide a callback that allows v8 to
4847 * cooperate with a profiler that rewrites return addresses on stack.
4849 static void SetReturnAddressLocationResolver(
4850 ReturnAddressLocationResolver return_address_resolver);
4853 * Allows the host application to provide the address of a function that's
4854 * invoked on entry to every V8-generated function.
4855 * Note that \p entry_hook is invoked at the very start of each
4856 * generated function.
4858 * \param isolate the isolate to operate on.
4859 * \param entry_hook a function that will be invoked on entry to every
4860 * V8-generated function.
4861 * \returns true on success on supported platforms, false on failure.
4862 * \note Setting an entry hook can only be done very early in an isolates
4863 * lifetime, and once set, the entry hook cannot be revoked.
4865 static bool SetFunctionEntryHook(Isolate* isolate,
4866 FunctionEntryHook entry_hook);
4869 * Allows the host application to provide the address of a function that is
4870 * notified each time code is added, moved or removed.
4872 * \param options options for the JIT code event handler.
4873 * \param event_handler the JIT code event handler, which will be invoked
4874 * each time code is added, moved or removed.
4875 * \note \p event_handler won't get notified of existent code.
4876 * \note since code removal notifications are not currently issued, the
4877 * \p event_handler may get notifications of code that overlaps earlier
4878 * code notifications. This happens when code areas are reused, and the
4879 * earlier overlapping code areas should therefore be discarded.
4880 * \note the events passed to \p event_handler and the strings they point to
4881 * are not guaranteed to live past each call. The \p event_handler must
4882 * copy strings and other parameters it needs to keep around.
4883 * \note the set of events declared in JitCodeEvent::EventType is expected to
4884 * grow over time, and the JitCodeEvent structure is expected to accrue
4885 * new members. The \p event_handler function must ignore event codes
4886 * it does not recognize to maintain future compatibility.
4888 static void SetJitCodeEventHandler(JitCodeEventOptions options,
4889 JitCodeEventHandler event_handler);
4892 * Forcefully terminate the current thread of JavaScript execution
4893 * in the given isolate.
4895 * This method can be used by any thread even if that thread has not
4896 * acquired the V8 lock with a Locker object.
4898 * \param isolate The isolate in which to terminate the current JS execution.
4900 static void TerminateExecution(Isolate* isolate);
4903 * Is V8 terminating JavaScript execution.
4905 * Returns true if JavaScript execution is currently terminating
4906 * because of a call to TerminateExecution. In that case there are
4907 * still JavaScript frames on the stack and the termination
4908 * exception is still active.
4910 * \param isolate The isolate in which to check.
4912 static bool IsExecutionTerminating(Isolate* isolate = NULL);
4915 * Resume execution capability in the given isolate, whose execution
4916 * was previously forcefully terminated using TerminateExecution().
4918 * When execution is forcefully terminated using TerminateExecution(),
4919 * the isolate can not resume execution until all JavaScript frames
4920 * have propagated the uncatchable exception which is generated. This
4921 * method allows the program embedding the engine to handle the
4922 * termination event and resume execution capability, even if
4923 * JavaScript frames remain on the stack.
4925 * This method can be used by any thread even if that thread has not
4926 * acquired the V8 lock with a Locker object.
4928 * \param isolate The isolate in which to resume execution capability.
4930 static void CancelTerminateExecution(Isolate* isolate);
4933 * Releases any resources used by v8 and stops any utility threads
4934 * that may be running. Note that disposing v8 is permanent, it
4935 * cannot be reinitialized.
4937 * It should generally not be necessary to dispose v8 before exiting
4938 * a process, this should happen automatically. It is only necessary
4939 * to use if the process needs the resources taken up by v8.
4941 static bool Dispose();
4944 * Iterates through all external resources referenced from current isolate
4945 * heap. GC is not invoked prior to iterating, therefore there is no
4946 * guarantee that visited objects are still alive.
4948 static void VisitExternalResources(ExternalResourceVisitor* visitor);
4951 * Iterates through all the persistent handles in the current isolate's heap
4952 * that have class_ids.
4954 static void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor);
4957 * Iterates through all the persistent handles in the current isolate's heap
4958 * that have class_ids and are candidates to be marked as partially dependent
4959 * handles. This will visit handles to young objects created since the last
4960 * garbage collection but is free to visit an arbitrary superset of these
4963 static void VisitHandlesForPartialDependence(
4964 Isolate* isolate, PersistentHandleVisitor* visitor);
4967 * Optional notification that the embedder is idle.
4968 * V8 uses the notification to reduce memory footprint.
4969 * This call can be used repeatedly if the embedder remains idle.
4970 * Returns true if the embedder should stop calling IdleNotification
4971 * until real work has been done. This indicates that V8 has done
4972 * as much cleanup as it will be able to do.
4974 * The hint argument specifies the amount of work to be done in the function
4975 * on scale from 1 to 1000. There is no guarantee that the actual work will
4978 static bool IdleNotification(int hint = 1000);
4981 * Optional notification that the system is running low on memory.
4982 * V8 uses these notifications to attempt to free memory.
4984 static void LowMemoryNotification();
4987 * Optional notification that a context has been disposed. V8 uses
4988 * these notifications to guide the GC heuristic. Returns the number
4989 * of context disposals - including this one - since the last time
4990 * V8 had a chance to clean up.
4992 static int ContextDisposedNotification();
4995 * Initialize the ICU library bundled with V8. The embedder should only
4996 * invoke this method when using the bundled ICU. Returns true on success.
4998 * If V8 was compiled with the ICU data in an external file, the location
4999 * of the data file has to be provided.
5001 static bool InitializeICU(const char* icu_data_file = NULL);
5004 * Sets the v8::Platform to use. This should be invoked before V8 is
5007 static void InitializePlatform(Platform* platform);
5010 * Clears all references to the v8::Platform. This should be invoked after
5013 static void ShutdownPlatform();
5018 static internal::Object** GlobalizeReference(internal::Isolate* isolate,
5019 internal::Object** handle);
5020 static internal::Object** CopyPersistent(internal::Object** handle);
5021 static void DisposeGlobal(internal::Object** global_handle);
5022 typedef WeakCallbackData<Value, void>::Callback WeakCallback;
5023 static void MakeWeak(internal::Object** global_handle,
5025 WeakCallback weak_callback);
5026 static void* ClearWeak(internal::Object** global_handle);
5027 static void Eternalize(Isolate* isolate,
5030 static Local<Value> GetEternal(Isolate* isolate, int index);
5032 template <class T> friend class Handle;
5033 template <class T> friend class Local;
5034 template <class T> friend class Eternal;
5035 template <class T> friend class PersistentBase;
5036 template <class T, class M> friend class Persistent;
5037 friend class Context;
5042 * An external exception handler.
5044 class V8_EXPORT TryCatch {
5047 * Creates a new try/catch block and registers it with v8. Note that
5048 * all TryCatch blocks should be stack allocated because the memory
5049 * location itself is compared against JavaScript try/catch blocks.
5054 * Unregisters and deletes this try/catch block.
5059 * Returns true if an exception has been caught by this try/catch block.
5061 bool HasCaught() const;
5064 * For certain types of exceptions, it makes no sense to continue execution.
5066 * If CanContinue returns false, the correct action is to perform any C++
5067 * cleanup needed and then return. If CanContinue returns false and
5068 * HasTerminated returns true, it is possible to call
5069 * CancelTerminateExecution in order to continue calling into the engine.
5071 bool CanContinue() const;
5074 * Returns true if an exception has been caught due to script execution
5077 * There is no JavaScript representation of an execution termination
5078 * exception. Such exceptions are thrown when the TerminateExecution
5079 * methods are called to terminate a long-running script.
5081 * If such an exception has been thrown, HasTerminated will return true,
5082 * indicating that it is possible to call CancelTerminateExecution in order
5083 * to continue calling into the engine.
5085 bool HasTerminated() const;
5088 * Throws the exception caught by this TryCatch in a way that avoids
5089 * it being caught again by this same TryCatch. As with ThrowException
5090 * it is illegal to execute any JavaScript operations after calling
5091 * ReThrow; the caller must return immediately to where the exception
5094 Handle<Value> ReThrow();
5097 * Returns the exception caught by this try/catch block. If no exception has
5098 * been caught an empty handle is returned.
5100 * The returned handle is valid until this TryCatch block has been destroyed.
5102 Local<Value> Exception() const;
5105 * Returns the .stack property of the thrown object. If no .stack
5106 * property is present an empty handle is returned.
5108 Local<Value> StackTrace() const;
5111 * Returns the message associated with this exception. If there is
5112 * no message associated an empty handle is returned.
5114 * The returned handle is valid until this TryCatch block has been
5117 Local<v8::Message> Message() const;
5120 * Clears any exceptions that may have been caught by this try/catch block.
5121 * After this method has been called, HasCaught() will return false.
5123 * It is not necessary to clear a try/catch block before using it again; if
5124 * another exception is thrown the previously caught exception will just be
5125 * overwritten. However, it is often a good idea since it makes it easier
5126 * to determine which operation threw a given exception.
5131 * Set verbosity of the external exception handler.
5133 * By default, exceptions that are caught by an external exception
5134 * handler are not reported. Call SetVerbose with true on an
5135 * external exception handler to have exceptions caught by the
5136 * handler reported as if they were not caught.
5138 void SetVerbose(bool value);
5141 * Set whether or not this TryCatch should capture a Message object
5142 * which holds source information about where the exception
5143 * occurred. True by default.
5145 void SetCaptureMessage(bool value);
5148 // Make it hard to create heap-allocated TryCatch blocks.
5149 TryCatch(const TryCatch&);
5150 void operator=(const TryCatch&);
5151 void* operator new(size_t size);
5152 void operator delete(void*, size_t);
5154 v8::internal::Isolate* isolate_;
5158 void* message_script_;
5159 int message_start_pos_;
5160 int message_end_pos_;
5161 bool is_verbose_ : 1;
5162 bool can_continue_ : 1;
5163 bool capture_message_ : 1;
5165 bool has_terminated_ : 1;
5167 friend class v8::internal::Isolate;
5175 * A container for extension names.
5177 class V8_EXPORT ExtensionConfiguration {
5179 ExtensionConfiguration() : name_count_(0), names_(NULL) { }
5180 ExtensionConfiguration(int name_count, const char* names[])
5181 : name_count_(name_count), names_(names) { }
5183 const char** begin() const { return &names_[0]; }
5184 const char** end() const { return &names_[name_count_]; }
5187 const int name_count_;
5188 const char** names_;
5193 * A sandboxed execution context with its own set of built-in objects
5196 class V8_EXPORT Context {
5199 * Returns the global proxy object.
5201 * Global proxy object is a thin wrapper whose prototype points to actual
5202 * context's global object with the properties like Object, etc. This is done
5203 * that way for security reasons (for more details see
5204 * https://wiki.mozilla.org/Gecko:SplitWindow).
5206 * Please note that changes to global proxy object prototype most probably
5207 * would break VM---v8 expects only global object as a prototype of global
5210 Local<Object> Global();
5213 * Detaches the global object from its context before
5214 * the global object can be reused to create a new context.
5216 void DetachGlobal();
5219 * Creates a new context and returns a handle to the newly allocated
5222 * \param isolate The isolate in which to create the context.
5224 * \param extensions An optional extension configuration containing
5225 * the extensions to be installed in the newly created context.
5227 * \param global_template An optional object template from which the
5228 * global object for the newly created context will be created.
5230 * \param global_object An optional global object to be reused for
5231 * the newly created context. This global object must have been
5232 * created by a previous call to Context::New with the same global
5233 * template. The state of the global object will be completely reset
5234 * and only object identify will remain.
5236 static Local<Context> New(
5238 ExtensionConfiguration* extensions = NULL,
5239 Handle<ObjectTemplate> global_template = Handle<ObjectTemplate>(),
5240 Handle<Value> global_object = Handle<Value>());
5243 * Sets the security token for the context. To access an object in
5244 * another context, the security tokens must match.
5246 void SetSecurityToken(Handle<Value> token);
5248 /** Restores the security token to the default value. */
5249 void UseDefaultSecurityToken();
5251 /** Returns the security token of this context.*/
5252 Handle<Value> GetSecurityToken();
5255 * Enter this context. After entering a context, all code compiled
5256 * and run is compiled and run in this context. If another context
5257 * is already entered, this old context is saved so it can be
5258 * restored when the new context is exited.
5263 * Exit this context. Exiting the current context restores the
5264 * context that was in place when entering the current context.
5269 * Returns true if the context has experienced an out of memory situation.
5270 * Since V8 always treats OOM as fatal error, this can no longer return true.
5271 * Therefore this is now deprecated.
5273 V8_DEPRECATED("This can no longer happen. OOM is a fatal error.",
5274 bool HasOutOfMemoryException()) { return false; }
5276 /** Returns an isolate associated with a current context. */
5277 v8::Isolate* GetIsolate();
5280 * Gets the embedder data with the given index, which must have been set by a
5281 * previous call to SetEmbedderData with the same index. Note that index 0
5282 * currently has a special meaning for Chrome's debugger.
5284 V8_INLINE Local<Value> GetEmbedderData(int index);
5287 * Sets the embedder data with the given index, growing the data as
5288 * needed. Note that index 0 currently has a special meaning for Chrome's
5291 void SetEmbedderData(int index, Handle<Value> value);
5294 * Gets a 2-byte-aligned native pointer from the embedder data with the given
5295 * index, which must have bees set by a previous call to
5296 * SetAlignedPointerInEmbedderData with the same index. Note that index 0
5297 * currently has a special meaning for Chrome's debugger.
5299 V8_INLINE void* GetAlignedPointerFromEmbedderData(int index);
5302 * Sets a 2-byte-aligned native pointer in the embedder data with the given
5303 * index, growing the data as needed. Note that index 0 currently has a
5304 * special meaning for Chrome's debugger.
5306 void SetAlignedPointerInEmbedderData(int index, void* value);
5309 * Control whether code generation from strings is allowed. Calling
5310 * this method with false will disable 'eval' and the 'Function'
5311 * constructor for code running in this context. If 'eval' or the
5312 * 'Function' constructor are used an exception will be thrown.
5314 * If code generation from strings is not allowed the
5315 * V8::AllowCodeGenerationFromStrings callback will be invoked if
5316 * set before blocking the call to 'eval' or the 'Function'
5317 * constructor. If that callback returns true, the call will be
5318 * allowed, otherwise an exception will be thrown. If no callback is
5319 * set an exception will be thrown.
5321 void AllowCodeGenerationFromStrings(bool allow);
5324 * Returns true if code generation from strings is allowed for the context.
5325 * For more details see AllowCodeGenerationFromStrings(bool) documentation.
5327 bool IsCodeGenerationFromStringsAllowed();
5330 * Sets the error description for the exception that is thrown when
5331 * code generation from strings is not allowed and 'eval' or the 'Function'
5332 * constructor are called.
5334 void SetErrorMessageForCodeGenerationFromStrings(Handle<String> message);
5337 * Stack-allocated class which sets the execution context for all
5338 * operations executed within a local scope.
5342 explicit V8_INLINE Scope(Handle<Context> context) : context_(context) {
5345 V8_INLINE ~Scope() { context_->Exit(); }
5348 Handle<Context> context_;
5353 friend class Script;
5354 friend class Object;
5355 friend class Function;
5357 Local<Value> SlowGetEmbedderData(int index);
5358 void* SlowGetAlignedPointerFromEmbedderData(int index);
5363 * Multiple threads in V8 are allowed, but only one thread at a time is allowed
5364 * to use any given V8 isolate, see the comments in the Isolate class. The
5365 * definition of 'using a V8 isolate' includes accessing handles or holding onto
5366 * object pointers obtained from V8 handles while in the particular V8 isolate.
5367 * It is up to the user of V8 to ensure, perhaps with locking, that this
5368 * constraint is not violated. In addition to any other synchronization
5369 * mechanism that may be used, the v8::Locker and v8::Unlocker classes must be
5370 * used to signal thead switches to V8.
5372 * v8::Locker is a scoped lock object. While it's active, i.e. between its
5373 * construction and destruction, the current thread is allowed to use the locked
5374 * isolate. V8 guarantees that an isolate can be locked by at most one thread at
5375 * any time. In other words, the scope of a v8::Locker is a critical section.
5381 * v8::Locker locker(isolate);
5382 * v8::Isolate::Scope isolate_scope(isolate);
5384 * // Code using V8 and isolate goes here.
5386 * } // Destructor called here
5389 * If you wish to stop using V8 in a thread A you can do this either by
5390 * destroying the v8::Locker object as above or by constructing a v8::Unlocker
5396 * v8::Unlocker unlocker(isolate);
5398 * // Code not using V8 goes here while V8 can run in another thread.
5400 * } // Destructor called here.
5404 * The Unlocker object is intended for use in a long-running callback from V8,
5405 * where you want to release the V8 lock for other threads to use.
5407 * The v8::Locker is a recursive lock, i.e. you can lock more than once in a
5408 * given thread. This can be useful if you have code that can be called either
5409 * from code that holds the lock or from code that does not. The Unlocker is
5410 * not recursive so you can not have several Unlockers on the stack at once, and
5411 * you can not use an Unlocker in a thread that is not inside a Locker's scope.
5413 * An unlocker will unlock several lockers if it has to and reinstate the
5414 * correct depth of locking on its destruction, e.g.:
5419 * v8::Locker locker(isolate);
5420 * Isolate::Scope isolate_scope(isolate);
5423 * v8::Locker another_locker(isolate);
5424 * // V8 still locked (2 levels).
5427 * v8::Unlocker unlocker(isolate);
5431 * // V8 locked again (2 levels).
5433 * // V8 still locked (1 level).
5435 * // V8 Now no longer locked.
5438 class V8_EXPORT Unlocker {
5441 * Initialize Unlocker for a given Isolate.
5443 V8_INLINE explicit Unlocker(Isolate* isolate) { Initialize(isolate); }
5447 void Initialize(Isolate* isolate);
5449 internal::Isolate* isolate_;
5453 class V8_EXPORT Locker {
5456 * Initialize Locker for a given Isolate.
5458 V8_INLINE explicit Locker(Isolate* isolate) { Initialize(isolate); }
5463 * Returns whether or not the locker for a given isolate, is locked by the
5466 static bool IsLocked(Isolate* isolate);
5469 * Returns whether v8::Locker is being used by this V8 instance.
5471 static bool IsActive();
5474 void Initialize(Isolate* isolate);
5478 internal::Isolate* isolate_;
5480 static bool active_;
5482 // Disallow copying and assigning.
5483 Locker(const Locker&);
5484 void operator=(const Locker&);
5488 // --- Implementation ---
5491 namespace internal {
5493 const int kApiPointerSize = sizeof(void*); // NOLINT
5494 const int kApiIntSize = sizeof(int); // NOLINT
5496 // Tag information for HeapObject.
5497 const int kHeapObjectTag = 1;
5498 const int kHeapObjectTagSize = 2;
5499 const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
5501 // Tag information for Smi.
5502 const int kSmiTag = 0;
5503 const int kSmiTagSize = 1;
5504 const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
5506 template <size_t ptr_size> struct SmiTagging;
5508 template<int kSmiShiftSize>
5509 V8_INLINE internal::Object* IntToSmi(int value) {
5510 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
5511 intptr_t tagged_value =
5512 (static_cast<intptr_t>(value) << smi_shift_bits) | kSmiTag;
5513 return reinterpret_cast<internal::Object*>(tagged_value);
5516 // Smi constants for 32-bit systems.
5517 template <> struct SmiTagging<4> {
5518 static const int kSmiShiftSize = 0;
5519 static const int kSmiValueSize = 31;
5520 V8_INLINE static int SmiToInt(internal::Object* value) {
5521 int shift_bits = kSmiTagSize + kSmiShiftSize;
5522 // Throw away top 32 bits and shift down (requires >> to be sign extending).
5523 return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
5525 V8_INLINE static internal::Object* IntToSmi(int value) {
5526 return internal::IntToSmi<kSmiShiftSize>(value);
5528 V8_INLINE static bool IsValidSmi(intptr_t value) {
5529 // To be representable as an tagged small integer, the two
5530 // most-significant bits of 'value' must be either 00 or 11 due to
5531 // sign-extension. To check this we add 01 to the two
5532 // most-significant bits, and check if the most-significant bit is 0
5534 // CAUTION: The original code below:
5535 // bool result = ((value + 0x40000000) & 0x80000000) == 0;
5536 // may lead to incorrect results according to the C language spec, and
5537 // in fact doesn't work correctly with gcc4.1.1 in some cases: The
5538 // compiler may produce undefined results in case of signed integer
5539 // overflow. The computation must be done w/ unsigned ints.
5540 return static_cast<uintptr_t>(value + 0x40000000U) < 0x80000000U;
5544 // Smi constants for 64-bit systems.
5545 template <> struct SmiTagging<8> {
5546 static const int kSmiShiftSize = 31;
5547 static const int kSmiValueSize = 32;
5548 V8_INLINE static int SmiToInt(internal::Object* value) {
5549 int shift_bits = kSmiTagSize + kSmiShiftSize;
5550 // Shift down and throw away top 32 bits.
5551 return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
5553 V8_INLINE static internal::Object* IntToSmi(int value) {
5554 return internal::IntToSmi<kSmiShiftSize>(value);
5556 V8_INLINE static bool IsValidSmi(intptr_t value) {
5557 // To be representable as a long smi, the value must be a 32-bit integer.
5558 return (value == static_cast<int32_t>(value));
5562 typedef SmiTagging<kApiPointerSize> PlatformSmiTagging;
5563 const int kSmiShiftSize = PlatformSmiTagging::kSmiShiftSize;
5564 const int kSmiValueSize = PlatformSmiTagging::kSmiValueSize;
5565 V8_INLINE static bool SmiValuesAre31Bits() { return kSmiValueSize == 31; }
5566 V8_INLINE static bool SmiValuesAre32Bits() { return kSmiValueSize == 32; }
5569 * This class exports constants and functionality from within v8 that
5570 * is necessary to implement inline functions in the v8 api. Don't
5571 * depend on functions and constants defined here.
5575 // These values match non-compiler-dependent values defined within
5576 // the implementation of v8.
5577 static const int kHeapObjectMapOffset = 0;
5578 static const int kMapInstanceTypeOffset = 1 * kApiPointerSize + kApiIntSize;
5579 static const int kStringResourceOffset = 3 * kApiPointerSize;
5581 static const int kOddballKindOffset = 3 * kApiPointerSize;
5582 static const int kForeignAddressOffset = kApiPointerSize;
5583 static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
5584 static const int kFixedArrayHeaderSize = 2 * kApiPointerSize;
5585 static const int kContextHeaderSize = 2 * kApiPointerSize;
5586 static const int kContextEmbedderDataIndex = 87;
5587 static const int kFullStringRepresentationMask = 0x07;
5588 static const int kStringEncodingMask = 0x4;
5589 static const int kExternalTwoByteRepresentationTag = 0x02;
5590 static const int kExternalAsciiRepresentationTag = 0x06;
5592 static const int kIsolateEmbedderDataOffset = 0 * kApiPointerSize;
5593 static const int kIsolateRootsOffset = 5 * kApiPointerSize;
5594 static const int kUndefinedValueRootIndex = 5;
5595 static const int kNullValueRootIndex = 7;
5596 static const int kTrueValueRootIndex = 8;
5597 static const int kFalseValueRootIndex = 9;
5598 static const int kEmptyStringRootIndex = 177;
5600 static const int kNodeClassIdOffset = 1 * kApiPointerSize;
5601 static const int kNodeFlagsOffset = 1 * kApiPointerSize + 3;
5602 static const int kNodeStateMask = 0xf;
5603 static const int kNodeStateIsWeakValue = 2;
5604 static const int kNodeStateIsPendingValue = 3;
5605 static const int kNodeStateIsNearDeathValue = 4;
5606 static const int kNodeIsIndependentShift = 4;
5607 static const int kNodeIsPartiallyDependentShift = 5;
5609 static const int kJSObjectType = 0xc4;
5610 static const int kFirstNonstringType = 0x80;
5611 static const int kOddballType = 0x83;
5612 static const int kForeignType = 0x8a;
5614 static const int kUndefinedOddballKind = 5;
5615 static const int kNullOddballKind = 3;
5617 static const uint32_t kNumIsolateDataSlots = 4;
5619 V8_EXPORT static void CheckInitializedImpl(v8::Isolate* isolate);
5620 V8_INLINE static void CheckInitialized(v8::Isolate* isolate) {
5621 #ifdef V8_ENABLE_CHECKS
5622 CheckInitializedImpl(isolate);
5626 V8_INLINE static bool HasHeapObjectTag(internal::Object* value) {
5627 return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
5631 V8_INLINE static int SmiValue(internal::Object* value) {
5632 return PlatformSmiTagging::SmiToInt(value);
5635 V8_INLINE static internal::Object* IntToSmi(int value) {
5636 return PlatformSmiTagging::IntToSmi(value);
5639 V8_INLINE static bool IsValidSmi(intptr_t value) {
5640 return PlatformSmiTagging::IsValidSmi(value);
5643 V8_INLINE static int GetInstanceType(internal::Object* obj) {
5644 typedef internal::Object O;
5645 O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
5646 return ReadField<uint8_t>(map, kMapInstanceTypeOffset);
5649 V8_INLINE static int GetOddballKind(internal::Object* obj) {
5650 typedef internal::Object O;
5651 return SmiValue(ReadField<O*>(obj, kOddballKindOffset));
5654 V8_INLINE static bool IsExternalTwoByteString(int instance_type) {
5655 int representation = (instance_type & kFullStringRepresentationMask);
5656 return representation == kExternalTwoByteRepresentationTag;
5659 V8_INLINE static uint8_t GetNodeFlag(internal::Object** obj, int shift) {
5660 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
5661 return *addr & static_cast<uint8_t>(1U << shift);
5664 V8_INLINE static void UpdateNodeFlag(internal::Object** obj,
5665 bool value, int shift) {
5666 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
5667 uint8_t mask = static_cast<uint8_t>(1 << shift);
5668 *addr = static_cast<uint8_t>((*addr & ~mask) | (value << shift));
5671 V8_INLINE static uint8_t GetNodeState(internal::Object** obj) {
5672 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
5673 return *addr & kNodeStateMask;
5676 V8_INLINE static void UpdateNodeState(internal::Object** obj,
5678 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
5679 *addr = static_cast<uint8_t>((*addr & ~kNodeStateMask) | value);
5682 V8_INLINE static void SetEmbedderData(v8::Isolate *isolate,
5685 uint8_t *addr = reinterpret_cast<uint8_t *>(isolate) +
5686 kIsolateEmbedderDataOffset + slot * kApiPointerSize;
5687 *reinterpret_cast<void**>(addr) = data;
5690 V8_INLINE static void* GetEmbedderData(v8::Isolate* isolate, uint32_t slot) {
5691 uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) +
5692 kIsolateEmbedderDataOffset + slot * kApiPointerSize;
5693 return *reinterpret_cast<void**>(addr);
5696 V8_INLINE static internal::Object** GetRoot(v8::Isolate* isolate,
5698 uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) + kIsolateRootsOffset;
5699 return reinterpret_cast<internal::Object**>(addr + index * kApiPointerSize);
5702 template <typename T> V8_INLINE static T ReadField(Object* ptr, int offset) {
5703 uint8_t* addr = reinterpret_cast<uint8_t*>(ptr) + offset - kHeapObjectTag;
5704 return *reinterpret_cast<T*>(addr);
5707 template <typename T>
5708 V8_INLINE static T ReadEmbedderData(Context* context, int index) {
5709 typedef internal::Object O;
5710 typedef internal::Internals I;
5711 O* ctx = *reinterpret_cast<O**>(context);
5712 int embedder_data_offset = I::kContextHeaderSize +
5713 (internal::kApiPointerSize * I::kContextEmbedderDataIndex);
5714 O* embedder_data = I::ReadField<O*>(ctx, embedder_data_offset);
5716 I::kFixedArrayHeaderSize + (internal::kApiPointerSize * index);
5717 return I::ReadField<T>(embedder_data, value_offset);
5720 V8_INLINE static bool CanCastToHeapObject(void* o) { return false; }
5721 V8_INLINE static bool CanCastToHeapObject(Context* o) { return true; }
5722 V8_INLINE static bool CanCastToHeapObject(String* o) { return true; }
5723 V8_INLINE static bool CanCastToHeapObject(Object* o) { return true; }
5724 V8_INLINE static bool CanCastToHeapObject(Message* o) { return true; }
5725 V8_INLINE static bool CanCastToHeapObject(StackTrace* o) { return true; }
5726 V8_INLINE static bool CanCastToHeapObject(StackFrame* o) { return true; }
5729 } // namespace internal
5733 Local<T>::Local() : Handle<T>() { }
5737 Local<T> Local<T>::New(Isolate* isolate, Handle<T> that) {
5738 return New(isolate, that.val_);
5742 Local<T> Local<T>::New(Isolate* isolate, const PersistentBase<T>& that) {
5743 return New(isolate, that.val_);
5747 Handle<T> Handle<T>::New(Isolate* isolate, T* that) {
5748 if (that == NULL) return Handle<T>();
5750 internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
5751 return Handle<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
5752 reinterpret_cast<internal::Isolate*>(isolate), *p)));
5757 Local<T> Local<T>::New(Isolate* isolate, T* that) {
5758 if (that == NULL) return Local<T>();
5760 internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
5761 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
5762 reinterpret_cast<internal::Isolate*>(isolate), *p)));
5768 void Eternal<T>::Set(Isolate* isolate, Local<S> handle) {
5770 V8::Eternalize(isolate, reinterpret_cast<Value*>(*handle), &this->index_);
5775 Local<T> Eternal<T>::Get(Isolate* isolate) {
5776 return Local<T>(reinterpret_cast<T*>(*V8::GetEternal(isolate, index_)));
5781 T* PersistentBase<T>::New(Isolate* isolate, T* that) {
5782 if (that == NULL) return NULL;
5783 internal::Object** p = reinterpret_cast<internal::Object**>(that);
5784 return reinterpret_cast<T*>(
5785 V8::GlobalizeReference(reinterpret_cast<internal::Isolate*>(isolate),
5790 template <class T, class M>
5791 template <class S, class M2>
5792 void Persistent<T, M>::Copy(const Persistent<S, M2>& that) {
5795 if (that.IsEmpty()) return;
5796 internal::Object** p = reinterpret_cast<internal::Object**>(that.val_);
5797 this->val_ = reinterpret_cast<T*>(V8::CopyPersistent(p));
5798 M::Copy(that, this);
5803 bool PersistentBase<T>::IsIndependent() const {
5804 typedef internal::Internals I;
5805 if (this->IsEmpty()) return false;
5806 return I::GetNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
5807 I::kNodeIsIndependentShift);
5812 bool PersistentBase<T>::IsNearDeath() const {
5813 typedef internal::Internals I;
5814 if (this->IsEmpty()) return false;
5815 uint8_t node_state =
5816 I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_));
5817 return node_state == I::kNodeStateIsNearDeathValue ||
5818 node_state == I::kNodeStateIsPendingValue;
5823 bool PersistentBase<T>::IsWeak() const {
5824 typedef internal::Internals I;
5825 if (this->IsEmpty()) return false;
5826 return I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_)) ==
5827 I::kNodeStateIsWeakValue;
5832 void PersistentBase<T>::Reset() {
5833 if (this->IsEmpty()) return;
5834 V8::DisposeGlobal(reinterpret_cast<internal::Object**>(this->val_));
5841 void PersistentBase<T>::Reset(Isolate* isolate, const Handle<S>& other) {
5844 if (other.IsEmpty()) return;
5845 this->val_ = New(isolate, other.val_);
5851 void PersistentBase<T>::Reset(Isolate* isolate,
5852 const PersistentBase<S>& other) {
5855 if (other.IsEmpty()) return;
5856 this->val_ = New(isolate, other.val_);
5861 template <typename S, typename P>
5862 void PersistentBase<T>::SetWeak(
5864 typename WeakCallbackData<S, P>::Callback callback) {
5866 typedef typename WeakCallbackData<Value, void>::Callback Callback;
5867 V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_),
5869 reinterpret_cast<Callback>(callback));
5874 template <typename P>
5875 void PersistentBase<T>::SetWeak(
5877 typename WeakCallbackData<T, P>::Callback callback) {
5878 SetWeak<T, P>(parameter, callback);
5883 template<typename P>
5884 P* PersistentBase<T>::ClearWeak() {
5885 return reinterpret_cast<P*>(
5886 V8::ClearWeak(reinterpret_cast<internal::Object**>(this->val_)));
5891 void PersistentBase<T>::MarkIndependent() {
5892 typedef internal::Internals I;
5893 if (this->IsEmpty()) return;
5894 I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
5896 I::kNodeIsIndependentShift);
5901 void PersistentBase<T>::MarkPartiallyDependent() {
5902 typedef internal::Internals I;
5903 if (this->IsEmpty()) return;
5904 I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
5906 I::kNodeIsPartiallyDependentShift);
5910 template <class T, class M>
5911 T* Persistent<T, M>::ClearAndLeak() {
5920 void PersistentBase<T>::SetWrapperClassId(uint16_t class_id) {
5921 typedef internal::Internals I;
5922 if (this->IsEmpty()) return;
5923 internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
5924 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
5925 *reinterpret_cast<uint16_t*>(addr) = class_id;
5930 uint16_t PersistentBase<T>::WrapperClassId() const {
5931 typedef internal::Internals I;
5932 if (this->IsEmpty()) return 0;
5933 internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
5934 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
5935 return *reinterpret_cast<uint16_t*>(addr);
5939 template<typename T>
5940 ReturnValue<T>::ReturnValue(internal::Object** slot) : value_(slot) {}
5942 template<typename T>
5943 template<typename S>
5944 void ReturnValue<T>::Set(const Persistent<S>& handle) {
5946 if (V8_UNLIKELY(handle.IsEmpty())) {
5947 *value_ = GetDefaultValue();
5949 *value_ = *reinterpret_cast<internal::Object**>(*handle);
5953 template<typename T>
5954 template<typename S>
5955 void ReturnValue<T>::Set(const Handle<S> handle) {
5957 if (V8_UNLIKELY(handle.IsEmpty())) {
5958 *value_ = GetDefaultValue();
5960 *value_ = *reinterpret_cast<internal::Object**>(*handle);
5964 template<typename T>
5965 void ReturnValue<T>::Set(double i) {
5966 TYPE_CHECK(T, Number);
5967 Set(Number::New(GetIsolate(), i));
5970 template<typename T>
5971 void ReturnValue<T>::Set(int32_t i) {
5972 TYPE_CHECK(T, Integer);
5973 typedef internal::Internals I;
5974 if (V8_LIKELY(I::IsValidSmi(i))) {
5975 *value_ = I::IntToSmi(i);
5978 Set(Integer::New(GetIsolate(), i));
5981 template<typename T>
5982 void ReturnValue<T>::Set(uint32_t i) {
5983 TYPE_CHECK(T, Integer);
5984 // Can't simply use INT32_MAX here for whatever reason.
5985 bool fits_into_int32_t = (i & (1U << 31)) == 0;
5986 if (V8_LIKELY(fits_into_int32_t)) {
5987 Set(static_cast<int32_t>(i));
5990 Set(Integer::NewFromUnsigned(GetIsolate(), i));
5993 template<typename T>
5994 void ReturnValue<T>::Set(bool value) {
5995 TYPE_CHECK(T, Boolean);
5996 typedef internal::Internals I;
5999 root_index = I::kTrueValueRootIndex;
6001 root_index = I::kFalseValueRootIndex;
6003 *value_ = *I::GetRoot(GetIsolate(), root_index);
6006 template<typename T>
6007 void ReturnValue<T>::SetNull() {
6008 TYPE_CHECK(T, Primitive);
6009 typedef internal::Internals I;
6010 *value_ = *I::GetRoot(GetIsolate(), I::kNullValueRootIndex);
6013 template<typename T>
6014 void ReturnValue<T>::SetUndefined() {
6015 TYPE_CHECK(T, Primitive);
6016 typedef internal::Internals I;
6017 *value_ = *I::GetRoot(GetIsolate(), I::kUndefinedValueRootIndex);
6020 template<typename T>
6021 void ReturnValue<T>::SetEmptyString() {
6022 TYPE_CHECK(T, String);
6023 typedef internal::Internals I;
6024 *value_ = *I::GetRoot(GetIsolate(), I::kEmptyStringRootIndex);
6027 template<typename T>
6028 Isolate* ReturnValue<T>::GetIsolate() {
6029 // Isolate is always the pointer below the default value on the stack.
6030 return *reinterpret_cast<Isolate**>(&value_[-2]);
6033 template<typename T>
6034 internal::Object* ReturnValue<T>::GetDefaultValue() {
6035 // Default value is always the pointer below value_ on the stack.
6040 template<typename T>
6041 FunctionCallbackInfo<T>::FunctionCallbackInfo(internal::Object** implicit_args,
6042 internal::Object** values,
6044 bool is_construct_call)
6045 : implicit_args_(implicit_args),
6048 is_construct_call_(is_construct_call) { }
6051 template<typename T>
6052 Local<Value> FunctionCallbackInfo<T>::operator[](int i) const {
6053 if (i < 0 || length_ <= i) return Local<Value>(*Undefined(GetIsolate()));
6054 return Local<Value>(reinterpret_cast<Value*>(values_ - i));
6058 template<typename T>
6059 Local<Function> FunctionCallbackInfo<T>::Callee() const {
6060 return Local<Function>(reinterpret_cast<Function*>(
6061 &implicit_args_[kCalleeIndex]));
6065 template<typename T>
6066 Local<Object> FunctionCallbackInfo<T>::This() const {
6067 return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
6071 template<typename T>
6072 Local<Object> FunctionCallbackInfo<T>::Holder() const {
6073 return Local<Object>(reinterpret_cast<Object*>(
6074 &implicit_args_[kHolderIndex]));
6078 template<typename T>
6079 Local<Value> FunctionCallbackInfo<T>::Data() const {
6080 return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
6084 template<typename T>
6085 Isolate* FunctionCallbackInfo<T>::GetIsolate() const {
6086 return *reinterpret_cast<Isolate**>(&implicit_args_[kIsolateIndex]);
6090 template<typename T>
6091 ReturnValue<T> FunctionCallbackInfo<T>::GetReturnValue() const {
6092 return ReturnValue<T>(&implicit_args_[kReturnValueIndex]);
6096 template<typename T>
6097 bool FunctionCallbackInfo<T>::IsConstructCall() const {
6098 return is_construct_call_;
6102 template<typename T>
6103 int FunctionCallbackInfo<T>::Length() const {
6108 Handle<Value> ScriptOrigin::ResourceName() const {
6109 return resource_name_;
6113 Handle<Integer> ScriptOrigin::ResourceLineOffset() const {
6114 return resource_line_offset_;
6118 Handle<Integer> ScriptOrigin::ResourceColumnOffset() const {
6119 return resource_column_offset_;
6122 Handle<Boolean> ScriptOrigin::ResourceIsSharedCrossOrigin() const {
6123 return resource_is_shared_cross_origin_;
6127 ScriptCompiler::Source::Source(Local<String> string, const ScriptOrigin& origin,
6129 : source_string(string),
6130 resource_name(origin.ResourceName()),
6131 resource_line_offset(origin.ResourceLineOffset()),
6132 resource_column_offset(origin.ResourceColumnOffset()),
6133 resource_is_shared_cross_origin(origin.ResourceIsSharedCrossOrigin()),
6134 cached_data(data) {}
6137 ScriptCompiler::Source::Source(Local<String> string,
6139 : source_string(string), cached_data(data) {}
6142 ScriptCompiler::Source::~Source() {
6147 const ScriptCompiler::CachedData* ScriptCompiler::Source::GetCachedData()
6153 Handle<Boolean> Boolean::New(Isolate* isolate, bool value) {
6154 return value ? True(isolate) : False(isolate);
6158 void Template::Set(Isolate* isolate, const char* name, v8::Handle<Data> value) {
6159 Set(v8::String::NewFromUtf8(isolate, name), value);
6163 Local<Value> Object::GetInternalField(int index) {
6164 #ifndef V8_ENABLE_CHECKS
6165 typedef internal::Object O;
6166 typedef internal::HeapObject HO;
6167 typedef internal::Internals I;
6168 O* obj = *reinterpret_cast<O**>(this);
6169 // Fast path: If the object is a plain JSObject, which is the common case, we
6170 // know where to find the internal fields and can return the value directly.
6171 if (I::GetInstanceType(obj) == I::kJSObjectType) {
6172 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
6173 O* value = I::ReadField<O*>(obj, offset);
6174 O** result = HandleScope::CreateHandle(reinterpret_cast<HO*>(obj), value);
6175 return Local<Value>(reinterpret_cast<Value*>(result));
6178 return SlowGetInternalField(index);
6182 void* Object::GetAlignedPointerFromInternalField(int index) {
6183 #ifndef V8_ENABLE_CHECKS
6184 typedef internal::Object O;
6185 typedef internal::Internals I;
6186 O* obj = *reinterpret_cast<O**>(this);
6187 // Fast path: If the object is a plain JSObject, which is the common case, we
6188 // know where to find the internal fields and can return the value directly.
6189 if (V8_LIKELY(I::GetInstanceType(obj) == I::kJSObjectType)) {
6190 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
6191 return I::ReadField<void*>(obj, offset);
6194 return SlowGetAlignedPointerFromInternalField(index);
6198 String* String::Cast(v8::Value* value) {
6199 #ifdef V8_ENABLE_CHECKS
6202 return static_cast<String*>(value);
6206 Local<String> String::Empty(Isolate* isolate) {
6207 typedef internal::Object* S;
6208 typedef internal::Internals I;
6209 I::CheckInitialized(isolate);
6210 S* slot = I::GetRoot(isolate, I::kEmptyStringRootIndex);
6211 return Local<String>(reinterpret_cast<String*>(slot));
6215 String::ExternalStringResource* String::GetExternalStringResource() const {
6216 typedef internal::Object O;
6217 typedef internal::Internals I;
6218 O* obj = *reinterpret_cast<O**>(const_cast<String*>(this));
6219 String::ExternalStringResource* result;
6220 if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
6221 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
6222 result = reinterpret_cast<String::ExternalStringResource*>(value);
6226 #ifdef V8_ENABLE_CHECKS
6227 VerifyExternalStringResource(result);
6233 String::ExternalStringResourceBase* String::GetExternalStringResourceBase(
6234 String::Encoding* encoding_out) const {
6235 typedef internal::Object O;
6236 typedef internal::Internals I;
6237 O* obj = *reinterpret_cast<O**>(const_cast<String*>(this));
6238 int type = I::GetInstanceType(obj) & I::kFullStringRepresentationMask;
6239 *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
6240 ExternalStringResourceBase* resource = NULL;
6241 if (type == I::kExternalAsciiRepresentationTag ||
6242 type == I::kExternalTwoByteRepresentationTag) {
6243 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
6244 resource = static_cast<ExternalStringResourceBase*>(value);
6246 #ifdef V8_ENABLE_CHECKS
6247 VerifyExternalStringResourceBase(resource, *encoding_out);
6253 bool Value::IsUndefined() const {
6254 #ifdef V8_ENABLE_CHECKS
6255 return FullIsUndefined();
6257 return QuickIsUndefined();
6261 bool Value::QuickIsUndefined() const {
6262 typedef internal::Object O;
6263 typedef internal::Internals I;
6264 O* obj = *reinterpret_cast<O**>(const_cast<Value*>(this));
6265 if (!I::HasHeapObjectTag(obj)) return false;
6266 if (I::GetInstanceType(obj) != I::kOddballType) return false;
6267 return (I::GetOddballKind(obj) == I::kUndefinedOddballKind);
6271 bool Value::IsNull() const {
6272 #ifdef V8_ENABLE_CHECKS
6273 return FullIsNull();
6275 return QuickIsNull();
6279 bool Value::QuickIsNull() const {
6280 typedef internal::Object O;
6281 typedef internal::Internals I;
6282 O* obj = *reinterpret_cast<O**>(const_cast<Value*>(this));
6283 if (!I::HasHeapObjectTag(obj)) return false;
6284 if (I::GetInstanceType(obj) != I::kOddballType) return false;
6285 return (I::GetOddballKind(obj) == I::kNullOddballKind);
6289 bool Value::IsString() const {
6290 #ifdef V8_ENABLE_CHECKS
6291 return FullIsString();
6293 return QuickIsString();
6297 bool Value::QuickIsString() const {
6298 typedef internal::Object O;
6299 typedef internal::Internals I;
6300 O* obj = *reinterpret_cast<O**>(const_cast<Value*>(this));
6301 if (!I::HasHeapObjectTag(obj)) return false;
6302 return (I::GetInstanceType(obj) < I::kFirstNonstringType);
6306 template <class T> Value* Value::Cast(T* value) {
6307 return static_cast<Value*>(value);
6311 Symbol* Symbol::Cast(v8::Value* value) {
6312 #ifdef V8_ENABLE_CHECKS
6315 return static_cast<Symbol*>(value);
6319 Number* Number::Cast(v8::Value* value) {
6320 #ifdef V8_ENABLE_CHECKS
6323 return static_cast<Number*>(value);
6327 Integer* Integer::Cast(v8::Value* value) {
6328 #ifdef V8_ENABLE_CHECKS
6331 return static_cast<Integer*>(value);
6335 Date* Date::Cast(v8::Value* value) {
6336 #ifdef V8_ENABLE_CHECKS
6339 return static_cast<Date*>(value);
6343 StringObject* StringObject::Cast(v8::Value* value) {
6344 #ifdef V8_ENABLE_CHECKS
6347 return static_cast<StringObject*>(value);
6351 SymbolObject* SymbolObject::Cast(v8::Value* value) {
6352 #ifdef V8_ENABLE_CHECKS
6355 return static_cast<SymbolObject*>(value);
6359 NumberObject* NumberObject::Cast(v8::Value* value) {
6360 #ifdef V8_ENABLE_CHECKS
6363 return static_cast<NumberObject*>(value);
6367 BooleanObject* BooleanObject::Cast(v8::Value* value) {
6368 #ifdef V8_ENABLE_CHECKS
6371 return static_cast<BooleanObject*>(value);
6375 RegExp* RegExp::Cast(v8::Value* value) {
6376 #ifdef V8_ENABLE_CHECKS
6379 return static_cast<RegExp*>(value);
6383 Object* Object::Cast(v8::Value* value) {
6384 #ifdef V8_ENABLE_CHECKS
6387 return static_cast<Object*>(value);
6391 Array* Array::Cast(v8::Value* value) {
6392 #ifdef V8_ENABLE_CHECKS
6395 return static_cast<Array*>(value);
6399 Promise* Promise::Cast(v8::Value* value) {
6400 #ifdef V8_ENABLE_CHECKS
6403 return static_cast<Promise*>(value);
6407 Promise::Resolver* Promise::Resolver::Cast(v8::Value* value) {
6408 #ifdef V8_ENABLE_CHECKS
6411 return static_cast<Promise::Resolver*>(value);
6415 ArrayBuffer* ArrayBuffer::Cast(v8::Value* value) {
6416 #ifdef V8_ENABLE_CHECKS
6419 return static_cast<ArrayBuffer*>(value);
6423 ArrayBufferView* ArrayBufferView::Cast(v8::Value* value) {
6424 #ifdef V8_ENABLE_CHECKS
6427 return static_cast<ArrayBufferView*>(value);
6431 TypedArray* TypedArray::Cast(v8::Value* value) {
6432 #ifdef V8_ENABLE_CHECKS
6435 return static_cast<TypedArray*>(value);
6439 Uint8Array* Uint8Array::Cast(v8::Value* value) {
6440 #ifdef V8_ENABLE_CHECKS
6443 return static_cast<Uint8Array*>(value);
6447 Int8Array* Int8Array::Cast(v8::Value* value) {
6448 #ifdef V8_ENABLE_CHECKS
6451 return static_cast<Int8Array*>(value);
6455 Uint16Array* Uint16Array::Cast(v8::Value* value) {
6456 #ifdef V8_ENABLE_CHECKS
6459 return static_cast<Uint16Array*>(value);
6463 Int16Array* Int16Array::Cast(v8::Value* value) {
6464 #ifdef V8_ENABLE_CHECKS
6467 return static_cast<Int16Array*>(value);
6471 Uint32Array* Uint32Array::Cast(v8::Value* value) {
6472 #ifdef V8_ENABLE_CHECKS
6475 return static_cast<Uint32Array*>(value);
6479 Int32Array* Int32Array::Cast(v8::Value* value) {
6480 #ifdef V8_ENABLE_CHECKS
6483 return static_cast<Int32Array*>(value);
6487 Float32Array* Float32Array::Cast(v8::Value* value) {
6488 #ifdef V8_ENABLE_CHECKS
6491 return static_cast<Float32Array*>(value);
6495 Float32x4Array* Float32x4Array::Cast(v8::Value* value) {
6496 #ifdef V8_ENABLE_CHECKS
6499 return static_cast<Float32x4Array*>(value);
6503 Float64x2Array* Float64x2Array::Cast(v8::Value* value) {
6504 #ifdef V8_ENABLE_CHECKS
6507 return static_cast<Float64x2Array*>(value);
6511 Int32x4Array* Int32x4Array::Cast(v8::Value* value) {
6512 #ifdef V8_ENABLE_CHECKS
6515 return static_cast<Int32x4Array*>(value);
6519 Float64Array* Float64Array::Cast(v8::Value* value) {
6520 #ifdef V8_ENABLE_CHECKS
6523 return static_cast<Float64Array*>(value);
6527 Uint8ClampedArray* Uint8ClampedArray::Cast(v8::Value* value) {
6528 #ifdef V8_ENABLE_CHECKS
6531 return static_cast<Uint8ClampedArray*>(value);
6535 DataView* DataView::Cast(v8::Value* value) {
6536 #ifdef V8_ENABLE_CHECKS
6539 return static_cast<DataView*>(value);
6543 Function* Function::Cast(v8::Value* value) {
6544 #ifdef V8_ENABLE_CHECKS
6547 return static_cast<Function*>(value);
6551 External* External::Cast(v8::Value* value) {
6552 #ifdef V8_ENABLE_CHECKS
6555 return static_cast<External*>(value);
6559 template<typename T>
6560 Isolate* PropertyCallbackInfo<T>::GetIsolate() const {
6561 return *reinterpret_cast<Isolate**>(&args_[kIsolateIndex]);
6565 template<typename T>
6566 Local<Value> PropertyCallbackInfo<T>::Data() const {
6567 return Local<Value>(reinterpret_cast<Value*>(&args_[kDataIndex]));
6571 template<typename T>
6572 Local<Value> PropertyCallbackInfo<T>::This() const {
6573 return Local<Value>(reinterpret_cast<Value*>(&args_[kThisIndex]));
6577 template<typename T>
6578 Local<Object> PropertyCallbackInfo<T>::Holder() const {
6579 return Local<Object>(reinterpret_cast<Object*>(&args_[kHolderIndex]));
6583 template<typename T>
6584 ReturnValue<T> PropertyCallbackInfo<T>::GetReturnValue() const {
6585 return ReturnValue<T>(&args_[kReturnValueIndex]);
6589 Handle<Primitive> Undefined(Isolate* isolate) {
6590 typedef internal::Object* S;
6591 typedef internal::Internals I;
6592 I::CheckInitialized(isolate);
6593 S* slot = I::GetRoot(isolate, I::kUndefinedValueRootIndex);
6594 return Handle<Primitive>(reinterpret_cast<Primitive*>(slot));
6598 Handle<Primitive> Null(Isolate* isolate) {
6599 typedef internal::Object* S;
6600 typedef internal::Internals I;
6601 I::CheckInitialized(isolate);
6602 S* slot = I::GetRoot(isolate, I::kNullValueRootIndex);
6603 return Handle<Primitive>(reinterpret_cast<Primitive*>(slot));
6607 Handle<Boolean> True(Isolate* isolate) {
6608 typedef internal::Object* S;
6609 typedef internal::Internals I;
6610 I::CheckInitialized(isolate);
6611 S* slot = I::GetRoot(isolate, I::kTrueValueRootIndex);
6612 return Handle<Boolean>(reinterpret_cast<Boolean*>(slot));
6616 Handle<Boolean> False(Isolate* isolate) {
6617 typedef internal::Object* S;
6618 typedef internal::Internals I;
6619 I::CheckInitialized(isolate);
6620 S* slot = I::GetRoot(isolate, I::kFalseValueRootIndex);
6621 return Handle<Boolean>(reinterpret_cast<Boolean*>(slot));
6625 void Isolate::SetData(uint32_t slot, void* data) {
6626 typedef internal::Internals I;
6627 I::SetEmbedderData(this, slot, data);
6631 void* Isolate::GetData(uint32_t slot) {
6632 typedef internal::Internals I;
6633 return I::GetEmbedderData(this, slot);
6637 uint32_t Isolate::GetNumberOfDataSlots() {
6638 typedef internal::Internals I;
6639 return I::kNumIsolateDataSlots;
6643 template<typename T>
6644 void Isolate::SetObjectGroupId(const Persistent<T>& object,
6646 TYPE_CHECK(Value, T);
6647 SetObjectGroupId(reinterpret_cast<v8::internal::Object**>(object.val_), id);
6651 template<typename T>
6652 void Isolate::SetReferenceFromGroup(UniqueId id,
6653 const Persistent<T>& object) {
6654 TYPE_CHECK(Value, T);
6655 SetReferenceFromGroup(id,
6656 reinterpret_cast<v8::internal::Object**>(object.val_));
6660 template<typename T, typename S>
6661 void Isolate::SetReference(const Persistent<T>& parent,
6662 const Persistent<S>& child) {
6663 TYPE_CHECK(Object, T);
6664 TYPE_CHECK(Value, S);
6665 SetReference(reinterpret_cast<v8::internal::Object**>(parent.val_),
6666 reinterpret_cast<v8::internal::Object**>(child.val_));
6670 Local<Value> Context::GetEmbedderData(int index) {
6671 #ifndef V8_ENABLE_CHECKS
6672 typedef internal::Object O;
6673 typedef internal::HeapObject HO;
6674 typedef internal::Internals I;
6675 HO* context = *reinterpret_cast<HO**>(this);
6677 HandleScope::CreateHandle(context, I::ReadEmbedderData<O*>(this, index));
6678 return Local<Value>(reinterpret_cast<Value*>(result));
6680 return SlowGetEmbedderData(index);
6685 void* Context::GetAlignedPointerFromEmbedderData(int index) {
6686 #ifndef V8_ENABLE_CHECKS
6687 typedef internal::Internals I;
6688 return I::ReadEmbedderData<void*>(this, index);
6690 return SlowGetAlignedPointerFromEmbedderData(index);
6697 * A simple shell that takes a list of expressions on the
6698 * command-line and executes them.
6703 * \example process.cc